training
Create Transformers Trainer, TrainingArguments, data-collator, example-script, distributed, checkpoint/resume, Hub push, and safe fine-tuning workflows.
- 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
- Create Transformers Trainer, TrainingArguments, data-collator, example-script, distributed, checkpoint/resume, Hub push, and safe fine-tuning workflows.
- disable-model-invocation
- true
02 资源文件 5
- 参考文档references/api-reference.md7.5 KB
- 参考文档references/distributed-training.md7.8 KB
- 参考文档references/task-recipes.md9.3 KB
- 参考文档references/troubleshooting.md7.7 KB
- 脚本scripts/training_args_smoke.py11.8 KB
03 SKILL.md 正文
Transformers Training
Use this sub-skill when the task is to fine-tune, evaluate during training, resume checkpoints, configure Trainer or Seq2SeqTrainer, adapt PyTorch example scripts, choose collators, or validate TrainingArguments before a run.
Transformers inspected version: 5.13.0.dev0. Import package: transformers. Training APIs are PyTorch-dependent; environments with only the base transformers import may raise optional dependency ImportError for Trainer, TrainingArguments, model classes, or collators until torch and task extras are installed.
Route Here
- Build
TrainingArguments,Seq2SeqTrainingArguments,Trainer, orSeq2SeqTrainerworkflows. - Convert an inference checkpoint into a fine-tuning plan with model/tokenizer/collator validation.
- Adapt a bundled example-script command pattern for text classification, token classification, causal LM, masked LM, summarization, translation, QA, vision, audio, or segmentation.
- Decide between the
Trainerroute and a*_no_trainer.py/Accelerate custom-loop route. - Configure evaluation cadence, checkpoint saves,
load_best_model_at_end, resume, mixed precision,torch_compile, FSDP, DeepSpeed, or Hub push. - Diagnose training failures around missing dependencies, labels, collators, padding,
remove_unused_columns, checkpoints, OOM, or distributed launch.
Route Elsewhere
- Inference-only
pipeline(...),device_map, or dtype loading choices: inference-pipelines. - Text generation decoding, streamers, chat templates, or
GenerationConfig: generation. - Tokenizer, processor, image/audio/video preprocessing details outside training batches: tokenizers-processors.
transformersCLI usage or serving entrypoints: serving-cli.- Quantization, PEFT, bitsandbytes, AWQ/GPTQ, or backend integration details: quantization-integrations.
- Adding a new model architecture, config, processor, or modular model implementation: model-extension.
Fast Workflow
- Identify task shape: classification, token classification, language modeling, seq2seq, QA, vision, audio, or custom model.
- Choose route:
Trainerfor standard supervised fine-tuning; no-trainer/Accelerate for custom optimizer/scheduler loops or fully manual loss handling. - Verify dependencies:
torchfor training, usuallyacceleratefor device/distributed orchestration,datasetsfor example scripts, andevaluatefor metrics. - Load matching components:
AutoConfig,AutoTokenizeror task processor,AutoModelFor*, and a task-appropriate data collator. - Normalize datasets to model inputs and labels; confirm
Trainersees every column required bymodel.forward(...)or setremove_unused_columns=False. - Configure
TrainingArgumentswith output, batch sizes, eval/save/log strategies, precision, checkpoint retention, distributed options, and Hub behavior. - Dry-run with tiny sample limits or a smoke script before long training.
- Train, evaluate, save, resume if needed, and push only when authentication and repository names are deliberate.
Primary References
- API reference: class names, constructor fields, collators, validation checks, and smoke script usage.
- Task recipes: command/API patterns for common fine-tuning tasks and example-script adaptation.
- Distributed training:
torchrun, Accelerate, FSDP, DeepSpeed, mixed precision, compile, and OOM decisions. - Troubleshooting: failure mode diagnosis and fixes.
Trainer Skeleton
from transformers import AutoModelForSequenceClassification, AutoTokenizer, DataCollatorWithPadding, Trainer, TrainingArguments
model_name = "distilbert/distilbert-base-uncased"
tokenizer = AutoTokenizer.from_pretrained(model_name, use_fast=True)
model = AutoModelForSequenceClassification.from_pretrained(model_name, num_labels=2)
args = TrainingArguments(
output_dir="outputs/text-classifier",
per_device_train_batch_size=8,
per_device_eval_batch_size=8,
learning_rate=2e-5,
num_train_epochs=3,
eval_strategy="epoch",
save_strategy="epoch",
logging_steps=50,
load_best_model_at_end=True,
metric_for_best_model="eval_loss",
report_to="none",
)
trainer = Trainer(
model=model,
args=args,
train_dataset=train_dataset,
eval_dataset=eval_dataset,
processing_class=tokenizer,
data_collator=DataCollatorWithPadding(tokenizer),
)
trainer.train(resume_from_checkpoint=None)
Safe Argument Validation
Use the bundled no-network smoke helper before launching expensive jobs:
python scripts/training_args_smoke.py \
--output_dir outputs/smoke \
--per_device_train_batch_size 2 \
--per_device_eval_batch_size 2 \
--eval_strategy steps \
--eval_steps 50 \
--save_strategy steps \
--save_steps 100 \
--load_best_model_at_end \
--metric_for_best_model eval_loss \
--report_to none
Expected signal: it either prints normalized TrainingArguments decisions or clearly reports the missing optional dependency that blocks instantiation.
Required Preflight Checks
eval_strategy="steps"needs nonzeroeval_steps; ifeval_stepsis omitted, confirm fallback tologging_stepsis intentional.load_best_model_at_end=Truerequires evaluation and compatible saving; aligneval_strategyandsave_strategyor usesave_strategy="best"with a metric.save_stepsmust be a round multiple ofeval_stepswhen loading the best model with step-based strategies.- Custom labels need model-compatible names; use
label_names=[...]for multiple label tensors and avoid a label argument literally namedlabel. - If examples include columns not consumed by the model, either remove them during preprocessing or set
remove_unused_columns=Falseand make the collator/model handle them. - Dynamic padding needs a tokenizer/processor with a pad token; causal LM often needs
tokenizer.pad_token = tokenizer.eos_tokenif no pad token exists. - Hub push needs authentication and intentional
hub_model_id; avoidpush_to_hub=Truein local smoke tests unless publishing is desired.
Example-Script Route
Prefer example-script style when the task already maps to a maintained script pattern. The public command shape is:
python ./train_task.py \
--model_name_or_path MODEL_OR_LOCAL_DIR \
--dataset_name DATASET \
--do_train --do_eval \
--max_train_samples 50 --max_eval_samples 50 \
--output_dir outputs/task-smoke \
--per_device_train_batch_size 4 \
--per_device_eval_batch_size 4
For self-contained skills, do not require future agents to open original repo example files. Distill the required flags into the task plan and ask the user for local script/file locations only when executing in their project.
Outputs To Return
For training tasks, return the selected route, dependencies, model/tokenizer/collator choices, exact command or API skeleton, validation checks, expected logs/metrics, resume/publish behavior, and any remaining hardware risk.
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).