Cheat sheets

End-to-End LLM and Fine-Tuning Pipeline

Plan, run and gate a hashed stage DAG. Head swap, SFT loss mask and DPO loss from the capstones, with defaults.

  • Tasks and commands
  • Annotated code
  • Diagrams
  • Comparisons
  • Defaults and numbers
  • Troubleshooting
  • Questions and tips

Source

Commands#

CommandWhat it does
python code/main.py planValidates the manifest, prints DAG and gates
python code/main.py runRuns stages, prints the manifest JSON
python code/main.py gateApplies eval gates. Prints SHIP or HOLD
python code/main.pyDemo: plan, run, a passing and a failing gate
./pipeline.sh config/llama3.3-8b-domainX.yamlCapstone 07: data to model card
run_demo()Capstones 38 to 40. Exits zero on success

Twelve-stage DAG#

store01-02 Tokenizervocab, mergesstore03 Datasetshardedgpu04-05 Checkpointpre-train, scalegpu06 SFT modelcheckpoint + recipegpu07 Reward + PPOpolicygpu08 DPOpolicygpu09 CAI / GRPOrefined policyprocess10 Eval reportscores, diffsstore11 Quantizedweights + deltaprocess12 Server specendpointclientShip gateSHIP or HOLDstore01-02Tokenizervocab, mergesstore03 Datasetshardedgpu04-05Checkpointpre-train,scalegpu06 SFTmodelcheckpoint +recipegpu07 Reward +PPOpolicygpu08 DPOpolicygpu09 CAI /GRPOrefinedpolicyprocess10 Evalreportscores, diffsstore11Quantizedweights +deltaprocess12 ServerspecendpointclientShip gateSHIP or HOLD

What the orchestrator does#

1Orchestratorresolves the DAG from the manifest.2Orchestratorskips a stage if its output already exists atthe correct hash.3Stageruns. The orchestrator measures wall clock andcost.4Orchestratorchecks the output hash against the next stageinput hash.5CostTrackerhalts with halted_over_budget when total costpasses the budget.6On failurewrites a partial manifest and exits nonzero.

Manifest and gates#

pipeline_version: 1.2.3
seed: 42
git_commit: a1b2c3d4
stages:
01_tokenizer:
input_hash: sha256:...output hash of the stage before
output_hash: sha256:...input hash of the next stage
gates:
mmlu: >= baseline + 0.5no regression
humaneval: >= baseline + 1.0
safety_refusal_rate: <= 0.05
kl_from_reference: <= 25.0KL budget gate
cost_total_usd: <= 50000

Gate defaults in main.py#

SettingDefaultNote
mmlu65.0op >=
humaneval40.0op >=
truthfulqa50.0op >=
safety_refusal_rate0.05op <=
kl_from_reference25.0op <=
cost_total_usd50000.0op <=
budget_usd50000.0Run halts above it
seed42In Manifest

DPO loss#

diff_w = logp_w_pol - logp_w_refchosen log-ratio
diff_l = logp_l_pol - logp_l_refrejected log-ratio
margin = diff_w - diff_limplicit reward difference
z = beta * margin
loss = -F.logsigmoid(z)numerically stable
for p in reference.parameters():
p.requires_grad = Falsereference never trains
reference.eval()

The three capstones side by side#

Factor38 Classifier head swap39 Instruction SFT40 DPO
BuildsBody + mean pool + 2-class headTinyGPT trained on response tokensPolicy against a frozen reference
Data800 SMS, 640 train, 160 test200 pairs, 160 train, 40 test12 (prompt, chosen, rejected) triples
Modelhidden 64, 4 heads, 2 blocks, max 32hidden 96, 2 blockshidden 64, 2 blocks
Train20 epochs head-only, 20 full20 epochs, lr 5e-430 epochs, beta 0.2, lr 1e-3
MetricPrecision, recall, F1, confusionExact-match per categoryChosen minus rejected margin
CheckHead-only and full both reportExact-match rises over epochsLoss falls, margin grows

Key calls in the capstones#

TaskCode
Freeze the body for head-only trainingfreeze_body(model)
Pool hidden states with the maskmean_pool(h, mask)
Pad a batch and mask labels with -100sft_collate(batch)
Causal loss on response tokensshifted_loss(logits, labels)
Score a completion under a modelsequence_log_prob(...)
DPO loss and implicit reward margindpo_loss(lp_w_pol, lp_l_pol, lp_w_ref, lp_l_ref, beta=cfg.beta)
Start the policy from the referencepolicy.load_state_dict(reference.state_dict())

Capstone 07 log lines#

CommandWhat it does
280k accepted (seed=7)Data stage rows kept
val loss 1.42 -> 1.03SFT, 3 epochs on 8xH100
1 epoch, beta=0.08, 4xH100DPO run
GPTQ-INT4 4.6 GB, AWQ-INT4 4.8 GBQuant sizes
EAGLE-3 acceptance 0.74Speculative decoding check
p99 126ms @ bs=8Tail latency at batch 8
MMLU-Pro +3.2, MT-Bench-v2 +0.41Eval gain over base

Troubleshooting#

SymptomCauseFix
HOLD: missing metric <metric>Eval report has no valueAdd the metric to the eval stage
input hash missing for stageUpstream artifact not in storeRe-run the upstream stage
halted_over_budgetTotal cost above budget_usdFix the cost estimate at plan time
DPO model sent through the SFT pathUntyped artifactsTyped artifacts and stage signatures
Model learns to predict the instructionNo loss mask-100 on instruction, pad, boundary
Full fine-tuning overfits 800 examplesSmall data washes out the bodyTrain the head only
MMLU-Pro accuracy jumpsContamination in training dataMinHash check, reject any overlap
DPO prefers short completionsLength biasDivide log-prob by completion length

Rollback and tips#

  • Run plan first every time. It is free. run is expensive.
  • Cheap to re-run: tokenizer, eval, quantization, inference server.
  • Medium: SFT, DPO, CAI. Keep the base model.
  • Expensive: pre-training. Use the last good checkpoint.
  • A failure at stage 06 invalidates 06 to 12. At stage 11, only 11 and 12.
  • Address artifacts by hash. A filename like latest.pt is a foot-gun.
  • Pre-training FLOPs: 6 x params x tokens.

Q&A#

Which two gates catch most disasters?
A regression gate and a KL budget gate.
Reproducible or deterministic?
Reproducible. Floats differ at the 1e-5 level.
Why does log Z(x) drop out of DPO?
It is the same for chosen and rejected.
Why greedy for exact-match?
Temperature makes the metric stochastic.