inference-export
Export Composer or PyTorch models for inference with TorchScript or ONNX, including checkpoint loading, export callbacks, and HuggingFace integration caveats.
- License 许可
- Apache-2.0
- 最近更新
- 2026-09-03
- Stars
- ★ 351
- Forks
- 27
01 前言 Front Matter
- name
- inference-export
- license
- Apache 2.0
- metadata
- { "disco-role": "operating" }
- description
- Export Composer or PyTorch models for inference with TorchScript or ONNX, including checkpoint loading, export callbacks, and HuggingFace integration caveats.
- disable-model-invocation
- true
02 资源文件 4
- 参考文档references/export-and-inference.md6.4 KB
- 参考文档references/huggingface-integration.md3.6 KB
- 参考文档references/troubleshooting.md4.5 KB
- 脚本scripts/export_torchscript_smoke.py2.1 KB
03 SKILL.md 正文
Composer Inference Export
Use this sub-skill when a user asks to make a Composer or PyTorch model ready for inference through TorchScript, ONNX, checkpoint-backed export, ExportForInferenceCallback, or optional HuggingFace/PEFT integration.
Route here
- Export a model to TorchScript or ONNX.
- Export from an existing checkpoint with
load_pathand optionalload_object_store. - Attach
ExportForInferenceCallbackso export happens at the end of training. - Use
Trainer.export_for_inferencefrom an already-constructed Trainer. - Choose
sample_input,dynamic_axes,input_names, andoutput_names. - Apply
surgery_algs,transforms, orquantize_dynamicbefore export. - Validate a saved TorchScript or ONNX artifact.
- Handle HuggingFaceModel tokenizer, embedding, PEFT, or checkpoint metadata caveats.
Reroute
- Training, checkpoint saving, or resume flow details: use
../training/SKILL.md. - Logger destinations, object-store upload, and artifact routing beyond export arguments: use
../observability/SKILL.md. - Distributed launch, wrapping, FSDP setup, or backend rank topology: use
../distributed/SKILL.md. - Speedup method choice before export: use
../methods/SKILL.md, then return here for artifact generation.
Read first
- Export and inference: recipes, signatures, arguments, and validation checks.
- HuggingFace integration: optional
mosaicml[nlp], PEFT, tokenizer/config/embedding caveats, and checkpoint metadata. - Troubleshooting: export-specific failure modes and recovery steps.
- TorchScript export smoke: a safe no-download export/load check.
Core export choices
- Choose
save_format="torchscript"for a self-contained scripted/traced artifact. - Choose
save_format="onnx"when the target runtime expects ONNX and you can provide a representativesample_input. - Use
load_pathwhen the model object needs weights from a Composer checkpoint before export. - Use
surgery_algsfor pre-load model surgery andtransformsfor post-load export-time transforms. - Use
quantize_dynamiconly when the target model layers and runtime support dynamic quantization. - Validate the output artifact immediately on the same example input.
Common API skeleton
from composer.utils import export_for_inference, quantize_dynamic
export_for_inference(
model=model,
save_format="torchscript",
save_path="model.pt",
sample_input=example_batch,
transforms=[quantize_dynamic],
)
For ONNX, provide sample_input and usually explicit names or dynamic axes:
export_for_inference(
model=model,
save_format="onnx",
save_path="model.onnx",
sample_input=(inputs,),
input_names=["input"],
output_names=["logits"],
dynamic_axes={"input": {0: "batch"}, "logits": {0: "batch"}},
)
Callback pattern
Use ExportForInferenceCallback when export should be part of the training lifecycle:
from composer.callbacks import ExportForInferenceCallback
from composer import Trainer
trainer = Trainer(
model=model,
train_dataloader=train_loader,
max_duration="1ep",
callbacks=[ExportForInferenceCallback(save_format="torchscript", save_path="model.pt")],
)
trainer.fit()
For ONNX callbacks, pass sample_input or allow the callback to capture a batch after the dataloader runs.
Distributed and checkpoint caveats
- Only global rank zero writes the export artifact.
- If the model is wrapped in DDP, export the underlying module rather than the wrapper.
- Do not export an FSDP-wrapped module directly; recreate/load the model without FSDP wrapping first.
load_strict=Falseis the export utility default; choose strictness intentionally when loading changed heads or adapter-only weights.- Remote checkpoint paths need matching object-store or logger configuration from the observability route.
HuggingFace quick checks
- Install the NLP extra before using
HuggingFaceModel. - Pass the tokenizer when checkpoint metadata should preserve tokenizer files.
- If tokenizer vocabulary is larger than model embeddings, either resize embeddings before wrapping or set
allow_embedding_resizing=True. - PEFT support is optional and Composer's wrapper expects supported PEFT configuration, with LoRA as the intended adapter path.
Bundled smoke script
Run from this sub-skill directory:
python scripts/export_torchscript_smoke.py
The script exports a tiny CPU model to a temporary TorchScript file, reloads it, and compares outputs.
Ask or stop before proceeding
- The export target is ONNX but
onnx/onnxruntimeare not available and validation is required. - The model requires downloading remote weights/tokenizers and network approval is unclear.
- The checkpoint is untrusted, private, remote, or requires credentials.
- The model is FSDP-wrapped and the unwrapped construction path is unknown.
- The target runtime requires shapes, names, quantization, or operator sets that the source model may not support.
04 同仓库更多 Skills
passnet-triton-opt
Make a single PassNet Triton kernel fast AND numerically faithful: performance model (when a replacement can win at all), block/grid/warp tuning, autotune policy, launch overhead, and per-op numeric recipes to pass the dtype baseline tolerances. Use when a pass matches and is correct but speedup below expected, or when correctness fails by small numeric margins.
passnet-solve
END-TO-END playbook for solving one PassNet sample: analyze the computation graphs, decide the optimization strategy (what to fuse, what to replace, what to leave alone), drive the iteration loop, and maximize the sample score. This is the ENTRY skill — invoke it first for any PassNet optimization task; it tells you when to use passnet-pattern-fusion, passnet-triton-opt and passnet-feedback.
passnet-skill
PassNet GPU kernel optimization via compiler passes. Design and implement Triton-based optimization passes, create pass files under ./pass_dir/, self-evaluate with pass_evaluator, and iterate to maximize GPU speedup.
passnet-pattern-fusion
Author PassNet pass files: write patterns that actually MATCH the FX graph, pick fusion regions (which ops to absorb into one Triton kernel), and structure multi-pass submissions with the mandatory shared-dispatch architecture. Use when creating or fixing pattern()/replacement_args()/replacement_func() files, when a pass "failed to match", or when deciding how to fuse multiple kernels/ops.
passnet-orchestrate
Round/batch planning and decision support for PassNet graph optimization. Use for multi-sample triage, worker allocation, eval-budget policy, and post-eval keep/revert decisions. For solving one concrete sample end to end, use passnet-solve as the entry skill; consult this skill only when you need broader planning or a specific decision gate.
passnet-feedback
Fast, deterministic feedback for PassNet work: pre-flight pattern/match verification WITHOUT burning a GPU evaluation, per-node bottleneck analysis of a sample's graphs, and eval-log parsing into per-variant status + estimated score + failure classification. Use BEFORE every GPU evaluation (check_pattern), at the START of a sample (analyze_graph), and AFTER every evaluation (parse_eval_log).