training
Build and debug Composer Trainer workflows, model/data contracts, time units, checkpoint save/load, manual resume, autoresume, evaluation, prediction, and basic CPU/GPU precision choices.
- License 许可
- Apache-2.0
- 最近更新
- 2026-09-03
- Stars
- ★ 351
- Forks
- 27
01 前言 Front Matter
- name
- training
- license
- Apache 2.0
- metadata
- { "disco-role": "operating" }
- description
- Build and debug Composer Trainer workflows, model/data contracts, time units, checkpoint save/load, manual resume, autoresume, evaluation, prediction, and basic CPU/GPU precision choices.
- disable-model-invocation
- true
02 资源文件 6
- 参考文档references/checkpointing-and-time.md7.6 KB
- 参考文档references/model-and-data-contracts.md8.1 KB
- 参考文档references/trainer-workflows.md7.5 KB
- 参考文档references/troubleshooting.md7.7 KB
- 脚本scripts/checkpoint_smoke.py9.4 KB
- 脚本scripts/train_smoke.py5.4 KB
03 SKILL.md 正文
Composer Training
Use this sub-skill when the task is to create, run, resume, or debug a MosaicML Composer training workflow with Trainer, ComposerModel, ComposerClassifier, DataSpec, Evaluator, State, Time, Timestamp, optimizers, schedulers, devices, precision, and checkpoints.
The public package install for examples is:
pip install mosaicml
Import the runtime module as composer.
Route here
- Construct
Trainer(model=..., train_dataloader=..., max_duration=..., optimizers=...)for CPU or single-process GPU experiments. - Decide whether to wrap a PyTorch module with
ComposerClassifieror subclassComposerModel. - Pass ordinary PyTorch
DataLoaderobjects,DataSpecobjects, orEvaluatorobjects to training and validation. - Call
trainer.fit(),trainer.eval(), ortrainer.predict()and inspecttrainer.stateafter the run. - Choose
max_duration,duration,eval_interval,save_interval, or scheduler milestones using Composer time strings. - Save checkpoints with
save_folder,save_filename,save_latest_filename, andsave_interval. - Resume manually with
load_pathor configureautoresume=Truewith stablerun_nameandsave_folder. - Recover from model-head or state mismatches using
load_weights_only,load_strict_model_weights, andload_ignore_keys. - Debug custom batch schemas, token counting, sample counting, microbatch splitting, and timestamp updates.
- Make basic
deviceandprecisionchoices such as CPU plusfp32or GPU plus AMP.
Reroute
- Efficiency algorithm catalog, method-specific arguments, algorithm ordering, and recipe selection: use
../methods/SKILL.md. - Loggers, experiment trackers, profiling, artifact upload, and telemetry destinations: use
../observability/SKILL.md. - Multi-rank launch, distributed samplers, FSDP, tensor parallelism, sharded checkpointing, and auto-microbatching: use
../distributed/SKILL.md. - TorchScript, ONNX, HuggingFace export, and inference packaging: use
../inference-export/SKILL.md.
Start fast
- Define the model contract.
Use
ComposerClassifier(module, num_classes=...)when batches are(inputs, targets)and the module mapsinputs -> logits. - For non-classification or custom batches, subclass
ComposerModeland implementforward(batch)plusloss(outputs, batch). - Build a small
torch.utils.data.DataLoaderfirst. If Composer cannot infer samples, tokens, transforms, or microbatch splitting, wrap it inDataSpec. - Create the optimizer explicitly before the trainer, for example
torch.optim.AdamW(model.parameters(), lr=...). - Set
max_durationusing a Composer time string such as"2ba","1ep","100sp", or"2048tok". - Start CPU-safe with
device="cpu"andprecision="fp32"; switch todevice="gpu"and AMP only after CPU logic works. - Keep
run_namestable when checkpoints or external logs must be grouped across restarts. - Call
trainer.fit()and validatetrainer.state.timestamp,trainer.state.train_metrics, andtrainer.saved_checkpoints. - Call
trainer.eval()for standalone validation, andtrainer.predict(dataloader)when batch outputs are needed. - Run the bundled smoke scripts before adapting a larger workflow.
Minimal Trainer skeleton
Keep examples small and explicit before adding algorithms, distributed launchers, or loggers:
from composer import Trainer
from composer.models import ComposerClassifier
import torch
model = ComposerClassifier(module=torch.nn.Linear(8, 3), num_classes=3)
optimizer = torch.optim.AdamW(model.parameters(), lr=1e-3)
trainer = Trainer(
model=model,
train_dataloader=train_loader,
eval_dataloader=eval_loader,
optimizers=optimizer,
max_duration="10ba",
device="cpu",
precision="fp32",
run_name="debug-run",
)
trainer.fit()
trainer.eval()
Use references/trainer-workflows.md when the task needs complete construction patterns.
Model and data checklist
ComposerModel.forward(batch)consumes the dataloader batch, not just tensors already unpacked from the batch.ComposerModel.loss(outputs, batch)returns the loss tensor that the trainer backpropagates.ComposerModel.eval_forward(batch, outputs=None)defaults tooutputsorforward(batch); override it for custom eval behavior.ComposerModel.get_metrics(is_train)returns a dictionary of TorchMetrics; Composer deep-copies metrics per split.ComposerModel.update_metric(batch, outputs, metric)must update each metric with the same batch/output schema.ComposerClassifierexpects(input, target)batches and can infer or receivenum_classesfor default accuracy metrics.DataSpecowns batch transforms, microbatch transforms, splitting, sample counting, token counting, and epoch sizing.- Use
Evaluator(label=..., dataloader=..., metric_names=...)when multiple eval loaders or selected metric names are needed.
Use references/model-and-data-contracts.md for custom batch schemas, token counting, metrics, and eval/predict contracts.
Checkpoint and time checklist
- Parse duration strings with
Time.from_timestring(...)when validating user input. - Time units are
iter,ep,ba,sp,tok,dur, andsec;max_durationcannot use circular duration or wall-clock seconds. Timestamptracks total and in-epoch counts such asbatch,sample,token,batch_in_epoch, andtoken_in_epoch.- Configure saving with
save_folder,save_filename,save_latest_filename,save_interval, andsave_overwrite. - Use
trainer.saved_checkpointsor the latest symlink/name to choose a manualload_path. - Full resume restores the trainer state;
max_durationis the total target, not the additional duration. - For fine-tuning or changed heads, start with
load_weights_only=True; add non-strict or ignored keys only when needed. autoresume=Truerequires stablerun_name,save_folder, andsave_latest_filenameso Composer can find the latest checkpoint.
Use references/checkpointing-and-time.md for save/load/autoresume recipes and validation steps.
Debug workflow
- Reproduce with
device="cpu",precision="fp32", a tiny synthetic dataloader, andmax_duration="1ba". - Confirm the model is a
ComposerModeland that one batch can pass throughforward,loss,eval_forward, and metrics. - If a batch is a dict, ragged object, or text batch, wrap the loader in
DataSpecand provide counting/splitting functions. - Inspect
trainer.state.timestampfor unexpected epochs, batches, samples, or tokens. - Inspect
trainer.state.eval_metricsby evaluator label when validation appears missing. - For checkpoint load failures, distinguish full-state resume, weights-only fine-tuning, and explicit ignored keys.
- For autoresume failures, verify
run_name,save_folder, latest filename, and whether a latest checkpoint actually exists. - Use
references/troubleshooting.mdto map common error messages to fixes.
Bundled smoke scripts
Run these from this sub-skill directory in any environment with mosaicml installed:
python scripts/train_smoke.py --batches 2 --eval-batches 1 --predict
python scripts/checkpoint_smoke.py --mode both
The scripts use only random CPU tensors and temporary directories; they do not download datasets or models.
Ask or stop before proceeding
- The user requires multi-node, FSDP, sharded checkpoints, or automatic microbatching details not covered by this training route.
- The user asks for logger setup, profiler traces, object-store upload, or experiment tracking configuration.
- A checkpoint is remote, untrusted, from an incompatible Composer/PyTorch version, or requires credentials.
- The required batch schema is not observable from user code and cannot be safely inferred.
- A model-head change has same-named parameters with different shapes and no safe ignore-key pattern is known.
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).