[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6QF5W3DXR0Z51SKQD5WDKF6":3,"skill-same:01M6QF5W3DXR0Z51SKQD5WDKF6":100},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":39,"linkOnly":40,"markdownContent":41,"markdownBody":42,"frontMatter":43,"refName":51,"commitSha":52,"skillDirectory":53,"forksCount":14,"repositoryHtmlUrl":54,"repositoryHomepageUrl":55,"ownerHtmlUrl":56,"ownerBlogUrl":57,"ownerDescription":58,"updatedAt":59,"install":60,"resources":73},"01M6QF5W3DXR0Z51SKQD5WDKF6","ml-training-recipes",null,"Battle-tested PyTorch training recipes for all domains — LLMs, vision, diffusion, medical imaging, protein\u002Fdrug discovery, spatial omics, genomics. Covers training loops, optimizer selection (AdamW, Muon), LR scheduling, mixed precision, debugging, and systematic experimentation. Use when training or fine-tuning neural networks, debugging loss spikes or OOM, choosing architectures, or optimizing GPU throughput.","Tashima-Tarsh\u002FDisha6.6","Tashima-Tarsh","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F269906498?v=4","01M6PBH98X03XERH0HFT4PFB1P","NITISH KUMAR","01M6PBH9DA0M6KM3Z12P848F0K",0,"MIT","https:\u002F\u002Fgithub.com\u002FTashima-Tarsh\u002FDisha6.6\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fkal-ml-training-recipes\u002FSKILL.md",[],[19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38],"ml training recipes","ml","training","recipes","biomedical","for","imaging","experimentation","architectures","domains","drug discovery","systematic","neural networks","selection","scheduling","use","discovery","networks","Fine-Tuning","pytorch","2026-11-10 10:12:30",false,"---\nname: ml-training-recipes\ndescription: Battle-tested PyTorch training recipes for all domains — LLMs, vision, diffusion, medical imaging, protein\u002Fdrug discovery, spatial omics, genomics. Covers training loops, optimizer selection (AdamW, Muon), LR scheduling, mixed precision, debugging, and systematic experimentation. Use when training or fine-tuning neural networks, debugging loss spikes or OOM, choosing architectures, or optimizing GPU throughput.\nlicense: MIT\nmetadata:\n  version: 1.0.0\n  category: ml-training\n  maintainer: Kalaris Labs\n  contributor: dailycafi\n  tags: PyTorch, Training, Optimization, LLM, Vision, Diffusion, Biomedical, Muon, AdamW, Debugging\n  dependencies: torch>=2.0.0\n---\n\n# ML Training Recipes\n\nBattle-tested patterns for PyTorch training across domains. Drawn from production codebases\n(Karpathy's autoresearch\u002Fnanochat, torchvision, HuggingFace) and modern training practice.\n\n## Reference files (read when needed)\n\n- `references\u002Farchitecture.md` — Transformer\u002FLLM architecture code patterns, weight init\n- `references\u002Foptimizers.md` — Muon, AdamW hybrid, per-group LR, compiled optimizer steps\n- `references\u002Fdomain-specific.md` — Vision, diffusion, contrastive, distributed, checkpointing, data loading\n- `references\u002Fscaling-and-selection.md` — Scaling laws, compute budget tables, decision trees, DGX Spark\n- `references\u002Fbiomedical.md` — Drug discovery, protein models, medical imaging, genomics, clinical NLP\n- `references\u002Fexperiment-loop.md` — Autonomous experiment loop (autoresearch keep\u002Fdiscard\u002Frevert)\n\n---\n\n## Architecture Selection\n\nPick the right model by **data type** and **data scale**:\n\n| Data Type | \u003C 10K samples | 10K-100K | > 100K |\n|-----------|--------------|----------|--------|\n| **Images** | Pretrained CNN + fine-tune | Fine-tune ViT or CNN | ViT from scratch |\n| **Text (gen)** | Few-shot prompting | Fine-tune GPT\u002FLLaMA (LoRA) | Pretrain from scratch |\n| **Tabular** | XGBoost\u002FLightGBM | Still XGBoost | Neural viable |\n| **Audio** | Pretrained Whisper | Fine-tune AST | Train from scratch |\n| **Molecules** | Pretrained GNN | Fine-tune molecular LM | Train GNN from scratch |\n| **Proteins** | ESM-2 embeddings + head | Fine-tune ESM-2 | Train protein LM |\n| **Medical img** | Pretrained CNN | nnU-Net (auto-config) | Swin-UNETR \u002F MedSAM |\n\n**Key principle**: architecture matters less than training recipe at equal compute. A well-tuned\nResNet beats a poorly-tuned ViT (ref: \"ResNet Strikes Back\", Wightman 2021).\n\nFor biomedical domains, see `references\u002Fbiomedical.md`.\nFor sequence model selection and compute planning, see `references\u002Fscaling-and-selection.md`.\n\n---\n\n## Scaling Laws\n\n### Chinchilla rule (Hoffmann et al., 2022)\n\nCompute-optimal training: **~20 tokens per parameter**.\n\n| Model Size | Compute-Optimal | Inference-Optimal (100×) |\n|-----------|----------------|--------------------------|\n| 125M | 2.5B tokens | 12.5B tokens |\n| 1B | 20B tokens | 100B tokens |\n| 7B | 140B tokens | 700B tokens |\n\n**FLOPs ≈ 6 × N × D** (N=params, D=tokens). Data repetition limit: ~4 epochs before diminishing returns.\n\n---\n\n## Training Loop\n\n```python\nimport gc, time, torch\n\ntorch.manual_seed(42)\ntorch.set_float32_matmul_precision(\"high\")  # TF32 on Ampere+\nautocast_ctx = torch.amp.autocast(device_type=\"cuda\", dtype=torch.bfloat16)\n\ngrad_accum_steps = total_batch_size \u002F\u002F (batch_size * seq_len)\nstep = 0\n\nwhile not done:\n    t0 = time.time()\n    for micro_step in range(grad_accum_steps):\n        with autocast_ctx:\n            loss = model(x, y)\n        (loss \u002F grad_accum_steps).backward()\n        x, y = next(train_loader)\n\n    update_lr(optimizer, progress)\n    optimizer.step()\n    model.zero_grad(set_to_none=True)  # frees memory vs zeroing\n\n    if loss.item() > 100:  # fast-fail on divergence\n        print(\"FAIL: loss exploded\"); exit(1)\n\n    torch.cuda.synchronize()\n    if step == 0:\n        gc.collect(); gc.freeze(); gc.disable()  # avoid ~500ms GC stalls\n    step += 1\n```\n\n### Key principles\n\n- **Gradient clipping**: `clip_grad_norm_(params, 1.0)` — near-universal for Transformers.\n  Exception: Muon optimizer normalizes updates via orthogonalization, so clipping is optional.\n- **Tensor Core alignment**: batch size, hidden dims should be multiples of 8 (bf16) or 64 (A100).\n- **Time-based budgets** make experiments comparable across hardware.\n- **`cudnn.benchmark = True`** for fixed-size vision inputs.\n\n---\n\n## Optimizer Configuration\n\nModern LLM training uses different optimizers per parameter group:\n\n| Parameter Type | Optimizer | LR (base) | Weight Decay |\n|---------------|-----------|-----------|--------------|\n| 2D weight matrices | Muon | 0.04 | 0.2 |\n| Token embeddings | AdamW | 0.6 × scale | 0.0 |\n| Unembedding (lm_head) | AdamW | 0.004 × scale | 0.0 |\n| Per-layer scalars | AdamW | 0.005 × scale | 0.0 |\n\n**LR scaling by dimension**: `lr * (d_model \u002F 768)^(-0.5)` — keeps dynamics stable across sizes.\n\n### Rules of thumb\n\n- Embeddings need higher LR (sparse updates). Never weight-decay embeddings.\n- Weight decay scheduling: linearly decay WD to 0 over training.\n- AdamW defaults: β1=0.9, β2=0.95, eps=1e-10 (not default 1e-8 — prevents stale updates in bf16).\n\nFor Muon details (polar express orthogonalization, NorMuon), see `references\u002Foptimizers.md`.\n\n---\n\n## Learning Rate Scheduling\n\n### Time-based (autoresearch style)\n\n```python\ndef get_lr_multiplier(progress):  # progress = elapsed_time \u002F time_budget\n    if progress \u003C warmup_ratio:\n        return progress \u002F warmup_ratio\n    elif progress \u003C 1.0 - warmdown_ratio:\n        return 1.0\n    else:\n        cooldown = (1.0 - progress) \u002F warmdown_ratio\n        return cooldown + (1 - cooldown) * final_lr_frac\n```\n\n### Cosine decay\n\n```python\ndef get_lr(step, total_steps, max_lr, min_lr, warmup_steps):\n    if step \u003C warmup_steps:\n        return max_lr * step \u002F warmup_steps\n    progress = (step - warmup_steps) \u002F (total_steps - warmup_steps)\n    return min_lr + 0.5 * (max_lr - min_lr) * (1 + math.cos(math.pi * progress))\n```\n\n**WSD (Warmup-Stable-Decay)**: gaining traction — easier to resume training mid-run.\n\n### Guidance\n\n- **Warmup**: 1-5% of training. Zero warmup valid with Muon (autoresearch uses `WARMUP_RATIO=0.0`).\n- **Warmdown**: 30-50% of training in LR decay. Matters more than warmup for final quality.\n- **Final LR**: 0 or ~10% of peak. Zero is simpler.\n\n---\n\n## Mixed Precision & Compilation\n\n```python\nimport os\nos.environ[\"PYTORCH_ALLOC_CONF\"] = \"expandable_segments:True\"  # before torch import\n\nimport torch\ntorch.set_float32_matmul_precision(\"high\")\nautocast_ctx = torch.amp.autocast(device_type=\"cuda\", dtype=torch.bfloat16)\nmodel = torch.compile(model, dynamic=False)\n```\n\n- **bf16** (Ampere+): same exponent as fp32, no loss scaling needed. Preferred over fp16.\n- **fp16**: needs GradScaler. Use only on V100 or older.\n- `dynamic=False` enables max optimization. Add `fullgraph=True` if no graph breaks.\n- First steps are slow (JIT) — exclude from timing.\n\n---\n\n## Memory & Performance\n\n### Meta device init (large models)\n\n```python\nwith torch.device(\"meta\"):\n    model = GPT(config)          # zero memory\nmodel.to_empty(device=\"cuda\")\nmodel.init_weights()\n```\n\n### MFU (Model FLOPs Utilization)\n\n```python\nachieved_flops = model_flops_per_token * batch_tokens \u002F step_time\nmfu = achieved_flops \u002F gpu_peak_flops\n# H100 SXM: 989.5 TFLOPS | A100: 312 | RTX 4090: 165\n```\n\nGood targets: >30% decent, >40% good, >50% excellent (single-GPU).\n\n### OOM solutions (in order)\n\n1. Reduce `DEVICE_BATCH_SIZE`, increase `grad_accum_steps`\n2. `PYTORCH_ALLOC_CONF=expandable_segments:True`\n3. `model.zero_grad(set_to_none=True)`\n4. Meta device init → `to_empty`\n5. Activation checkpointing: `torch.utils.checkpoint.checkpoint()`\n6. 8-bit optimizer (bitsandbytes): ~30% savings on optimizer states\n\n---\n\n## Hyperparameter Search\n\n### Priority order (tune first → last)\n\n1. **Learning rate** — most impactful. Always tune first.\n2. **Batch size** — largest that fits. Speed knob, not quality knob.\n3. **Weight decay** — 0.01-0.1 for AdamW.\n4. **Warmup steps** — 1-5% of training.\n\n### The 2025 default recipe\n\n| Setting | Value |\n|---------|-------|\n| Optimizer | AdamW (β1=0.9, β2=0.95, eps=1e-10) |\n| Weight decay | 0.1 |\n| LR schedule | Cosine decay or WSD |\n| Peak LR | 3e-4 (scale down for larger models) |\n| Precision | bf16 |\n| Grad clipping | max_norm=1.0 |\n| Normalization | RMSNorm (pre-norm) |\n| Activation | SwiGLU |\n| Position encoding | RoPE |\n| Attention | Flash Attention, optionally GQA |\n\n---\n\n## Debugging Checklist\n\n### Karpathy's recipe (still canonical)\n\n1. **Become one with the data** — visualize, check distributions, verify labels\n2. **Get end-to-end running first** — verify on a trivial case\n3. **Overfit one batch** — if you can't, you have a bug\n4. **Then regularize** — add regularization only after overfitting works\n5. **Tune hyperparameters** — start with known defaults\n\n### Loss exploding \u002F NaN\n\n1. Reduce LR (3-10× smaller)\n2. Add gradient clipping: `clip_grad_norm_(params, 1.0)`\n3. Check for inf\u002Fnan in inputs\n4. Add logit soft capping: `softcap * tanh(logits \u002F softcap)`\n5. Add QK-norm in attention\n6. Verify weight init (zero-init output projections?)\n7. Check loss reduction with gradient accumulation (`loss \u002F grad_accum_steps`)\n\n### Slow training \u002F Low MFU\n\n1. Verify `torch.compile` is active\n2. Check `torch.set_float32_matmul_precision(\"high\")`\n3. Pin memory + non_blocking transfers\n4. Profile with `torch.profiler`\n5. GC stalls? `gc.freeze(); gc.disable()`\n6. Tensor Core alignment: dims multiples of 8\u002F64\n\n### Loss plateau \u002F Slow convergence\n\n1. LR too low — try 2-5× larger\n2. Warmup too long\n3. Weight decay too high\n4. Verify LR schedule is actually applied (print each step)\n5. Model too small for task\n\n### Silent failures\n\n1. **Data leakage** between train\u002Fval\n2. **Wrong preprocessing at inference** — augmentation mismatch\n3. **Label errors** — use cleanlab to detect\n4. **Shuffling bugs** — correlated batches\n5. **Tokenizer mismatch** with pretrained model\n\n### What to monitor\n\n- **Gradient norms** — spike precedes loss spike\n- **Per-layer activation stats** — reveals exploding\u002Fvanishing\n- **Dead neurons** — >50% zero ReLU = dying ReLU problem\n- **Learning rate** — verify schedule applied (common silent bug)\n\n---\n\n## Experiment Management\n\nTrack experiments in TSV for easy comparison:\n\n```\ncommit  val_bpb  memory_gb  status   description\na1b2c3d 0.9979   44.0       keep     baseline\nb2c3d4e 0.9932   44.2       keep     increase matrix LR to 0.04\nc3d4e5f 1.0050   44.0       discard  switch to GeLU (worse)\n```\n\n**Simplicity criterion**: all else equal, simpler is better. Removing something and getting equal\nresults is a great outcome. For systematic agent-driven experimentation, see `references\u002Fexperiment-loop.md`.\n\n### Evaluation metrics by domain\n\n| Domain | Primary Metric | Notes |\n|--------|---------------|-------|\n| LLM | BPB (bits per byte) | Vocab-size-independent |\n| Classification | Accuracy \u002F F1 | Macro-F1 for imbalanced |\n| Segmentation | mIoU \u002F Dice | Per-class IoU reveals weak spots |\n| Generation | FID | Needs >10k samples |\n| Regression | RMSE \u002F MAE | Log-transform skewed targets |\n\n## Related skills\n\n- `serving-llms-vllm`: Serves LLMs with high throughput using vLLM's PagedAttention and continuous batching.\n- `llama-factory`: Guides fine-tuning of large language models with LLaMA-Factory, covering the WebUI no-code interface, training across 100+ supported models…\n- `peft-fine-tuning`: Fine-tunes LLMs with Hugging Face PEFT, using LoRA, QLoRA, IA3, AdaLoRA, prefix tuning, and prompt tuning so that under 1% of parameters ar…\n","# ML Training Recipes\n\nBattle-tested patterns for PyTorch training across domains. Drawn from production codebases\n(Karpathy's autoresearch\u002Fnanochat, torchvision, HuggingFace) and modern training practice.\n\n## Reference files (read when needed)\n\n- `references\u002Farchitecture.md` — Transformer\u002FLLM architecture code patterns, weight init\n- `references\u002Foptimizers.md` — Muon, AdamW hybrid, per-group LR, compiled optimizer steps\n- `references\u002Fdomain-specific.md` — Vision, diffusion, contrastive, distributed, checkpointing, data loading\n- `references\u002Fscaling-and-selection.md` — Scaling laws, compute budget tables, decision trees, DGX Spark\n- `references\u002Fbiomedical.md` — Drug discovery, protein models, medical imaging, genomics, clinical NLP\n- `references\u002Fexperiment-loop.md` — Autonomous experiment loop (autoresearch keep\u002Fdiscard\u002Frevert)\n\n---\n\n## Architecture Selection\n\nPick the right model by **data type** and **data scale**:\n\n| Data Type | \u003C 10K samples | 10K-100K | > 100K |\n|-----------|--------------|----------|--------|\n| **Images** | Pretrained CNN + fine-tune | Fine-tune ViT or CNN | ViT from scratch |\n| **Text (gen)** | Few-shot prompting | Fine-tune GPT\u002FLLaMA (LoRA) | Pretrain from scratch |\n| **Tabular** | XGBoost\u002FLightGBM | Still XGBoost | Neural viable |\n| **Audio** | Pretrained Whisper | Fine-tune AST | Train from scratch |\n| **Molecules** | Pretrained GNN | Fine-tune molecular LM | Train GNN from scratch |\n| **Proteins** | ESM-2 embeddings + head | Fine-tune ESM-2 | Train protein LM |\n| **Medical img** | Pretrained CNN | nnU-Net (auto-config) | Swin-UNETR \u002F MedSAM |\n\n**Key principle**: architecture matters less than training recipe at equal compute. A well-tuned\nResNet beats a poorly-tuned ViT (ref: \"ResNet Strikes Back\", Wightman 2021).\n\nFor biomedical domains, see `references\u002Fbiomedical.md`.\nFor sequence model selection and compute planning, see `references\u002Fscaling-and-selection.md`.\n\n---\n\n## Scaling Laws\n\n### Chinchilla rule (Hoffmann et al., 2022)\n\nCompute-optimal training: **~20 tokens per parameter**.\n\n| Model Size | Compute-Optimal | Inference-Optimal (100×) |\n|-----------|----------------|--------------------------|\n| 125M | 2.5B tokens | 12.5B tokens |\n| 1B | 20B tokens | 100B tokens |\n| 7B | 140B tokens | 700B tokens |\n\n**FLOPs ≈ 6 × N × D** (N=params, D=tokens). Data repetition limit: ~4 epochs before diminishing returns.\n\n---\n\n## Training Loop\n\n```python\nimport gc, time, torch\n\ntorch.manual_seed(42)\ntorch.set_float32_matmul_precision(\"high\")  # TF32 on Ampere+\nautocast_ctx = torch.amp.autocast(device_type=\"cuda\", dtype=torch.bfloat16)\n\ngrad_accum_steps = total_batch_size \u002F\u002F (batch_size * seq_len)\nstep = 0\n\nwhile not done:\n    t0 = time.time()\n    for micro_step in range(grad_accum_steps):\n        with autocast_ctx:\n            loss = model(x, y)\n        (loss \u002F grad_accum_steps).backward()\n        x, y = next(train_loader)\n\n    update_lr(optimizer, progress)\n    optimizer.step()\n    model.zero_grad(set_to_none=True)  # frees memory vs zeroing\n\n    if loss.item() > 100:  # fast-fail on divergence\n        print(\"FAIL: loss exploded\"); exit(1)\n\n    torch.cuda.synchronize()\n    if step == 0:\n        gc.collect(); gc.freeze(); gc.disable()  # avoid ~500ms GC stalls\n    step += 1\n```\n\n### Key principles\n\n- **Gradient clipping**: `clip_grad_norm_(params, 1.0)` — near-universal for Transformers.\n  Exception: Muon optimizer normalizes updates via orthogonalization, so clipping is optional.\n- **Tensor Core alignment**: batch size, hidden dims should be multiples of 8 (bf16) or 64 (A100).\n- **Time-based budgets** make experiments comparable across hardware.\n- **`cudnn.benchmark = True`** for fixed-size vision inputs.\n\n---\n\n## Optimizer Configuration\n\nModern LLM training uses different optimizers per parameter group:\n\n| Parameter Type | Optimizer | LR (base) | Weight Decay |\n|---------------|-----------|-----------|--------------|\n| 2D weight matrices | Muon | 0.04 | 0.2 |\n| Token embeddings | AdamW | 0.6 × scale | 0.0 |\n| Unembedding (lm_head) | AdamW | 0.004 × scale | 0.0 |\n| Per-layer scalars | AdamW | 0.005 × scale | 0.0 |\n\n**LR scaling by dimension**: `lr * (d_model \u002F 768)^(-0.5)` — keeps dynamics stable across sizes.\n\n### Rules of thumb\n\n- Embeddings need higher LR (sparse updates). Never weight-decay embeddings.\n- Weight decay scheduling: linearly decay WD to 0 over training.\n- AdamW defaults: β1=0.9, β2=0.95, eps=1e-10 (not default 1e-8 — prevents stale updates in bf16).\n\nFor Muon details (polar express orthogonalization, NorMuon), see `references\u002Foptimizers.md`.\n\n---\n\n## Learning Rate Scheduling\n\n### Time-based (autoresearch style)\n\n```python\ndef get_lr_multiplier(progress):  # progress = elapsed_time \u002F time_budget\n    if progress \u003C warmup_ratio:\n        return progress \u002F warmup_ratio\n    elif progress \u003C 1.0 - warmdown_ratio:\n        return 1.0\n    else:\n        cooldown = (1.0 - progress) \u002F warmdown_ratio\n        return cooldown + (1 - cooldown) * final_lr_frac\n```\n\n### Cosine decay\n\n```python\ndef get_lr(step, total_steps, max_lr, min_lr, warmup_steps):\n    if step \u003C warmup_steps:\n        return max_lr * step \u002F warmup_steps\n    progress = (step - warmup_steps) \u002F (total_steps - warmup_steps)\n    return min_lr + 0.5 * (max_lr - min_lr) * (1 + math.cos(math.pi * progress))\n```\n\n**WSD (Warmup-Stable-Decay)**: gaining traction — easier to resume training mid-run.\n\n### Guidance\n\n- **Warmup**: 1-5% of training. Zero warmup valid with Muon (autoresearch uses `WARMUP_RATIO=0.0`).\n- **Warmdown**: 30-50% of training in LR decay. Matters more than warmup for final quality.\n- **Final LR**: 0 or ~10% of peak. Zero is simpler.\n\n---\n\n## Mixed Precision & Compilation\n\n```python\nimport os\nos.environ[\"PYTORCH_ALLOC_CONF\"] = \"expandable_segments:True\"  # before torch import\n\nimport torch\ntorch.set_float32_matmul_precision(\"high\")\nautocast_ctx = torch.amp.autocast(device_type=\"cuda\", dtype=torch.bfloat16)\nmodel = torch.compile(model, dynamic=False)\n```\n\n- **bf16** (Ampere+): same exponent as fp32, no loss scaling needed. Preferred over fp16.\n- **fp16**: needs GradScaler. Use only on V100 or older.\n- `dynamic=False` enables max optimization. Add `fullgraph=True` if no graph breaks.\n- First steps are slow (JIT) — exclude from timing.\n\n---\n\n## Memory & Performance\n\n### Meta device init (large models)\n\n```python\nwith torch.device(\"meta\"):\n    model = GPT(config)          # zero memory\nmodel.to_empty(device=\"cuda\")\nmodel.init_weights()\n```\n\n### MFU (Model FLOPs Utilization)\n\n```python\nachieved_flops = model_flops_per_token * batch_tokens \u002F step_time\nmfu = achieved_flops \u002F gpu_peak_flops\n# H100 SXM: 989.5 TFLOPS | A100: 312 | RTX 4090: 165\n```\n\nGood targets: >30% decent, >40% good, >50% excellent (single-GPU).\n\n### OOM solutions (in order)\n\n1. Reduce `DEVICE_BATCH_SIZE`, increase `grad_accum_steps`\n2. `PYTORCH_ALLOC_CONF=expandable_segments:True`\n3. `model.zero_grad(set_to_none=True)`\n4. Meta device init → `to_empty`\n5. Activation checkpointing: `torch.utils.checkpoint.checkpoint()`\n6. 8-bit optimizer (bitsandbytes): ~30% savings on optimizer states\n\n---\n\n## Hyperparameter Search\n\n### Priority order (tune first → last)\n\n1. **Learning rate** — most impactful. Always tune first.\n2. **Batch size** — largest that fits. Speed knob, not quality knob.\n3. **Weight decay** — 0.01-0.1 for AdamW.\n4. **Warmup steps** — 1-5% of training.\n\n### The 2025 default recipe\n\n| Setting | Value |\n|---------|-------|\n| Optimizer | AdamW (β1=0.9, β2=0.95, eps=1e-10) |\n| Weight decay | 0.1 |\n| LR schedule | Cosine decay or WSD |\n| Peak LR | 3e-4 (scale down for larger models) |\n| Precision | bf16 |\n| Grad clipping | max_norm=1.0 |\n| Normalization | RMSNorm (pre-norm) |\n| Activation | SwiGLU |\n| Position encoding | RoPE |\n| Attention | Flash Attention, optionally GQA |\n\n---\n\n## Debugging Checklist\n\n### Karpathy's recipe (still canonical)\n\n1. **Become one with the data** — visualize, check distributions, verify labels\n2. **Get end-to-end running first** — verify on a trivial case\n3. **Overfit one batch** — if you can't, you have a bug\n4. **Then regularize** — add regularization only after overfitting works\n5. **Tune hyperparameters** — start with known defaults\n\n### Loss exploding \u002F NaN\n\n1. Reduce LR (3-10× smaller)\n2. Add gradient clipping: `clip_grad_norm_(params, 1.0)`\n3. Check for inf\u002Fnan in inputs\n4. Add logit soft capping: `softcap * tanh(logits \u002F softcap)`\n5. Add QK-norm in attention\n6. Verify weight init (zero-init output projections?)\n7. Check loss reduction with gradient accumulation (`loss \u002F grad_accum_steps`)\n\n### Slow training \u002F Low MFU\n\n1. Verify `torch.compile` is active\n2. Check `torch.set_float32_matmul_precision(\"high\")`\n3. Pin memory + non_blocking transfers\n4. Profile with `torch.profiler`\n5. GC stalls? `gc.freeze(); gc.disable()`\n6. Tensor Core alignment: dims multiples of 8\u002F64\n\n### Loss plateau \u002F Slow convergence\n\n1. LR too low — try 2-5× larger\n2. Warmup too long\n3. Weight decay too high\n4. Verify LR schedule is actually applied (print each step)\n5. Model too small for task\n\n### Silent failures\n\n1. **Data leakage** between train\u002Fval\n2. **Wrong preprocessing at inference** — augmentation mismatch\n3. **Label errors** — use cleanlab to detect\n4. **Shuffling bugs** — correlated batches\n5. **Tokenizer mismatch** with pretrained model\n\n### What to monitor\n\n- **Gradient norms** — spike precedes loss spike\n- **Per-layer activation stats** — reveals exploding\u002Fvanishing\n- **Dead neurons** — >50% zero ReLU = dying ReLU problem\n- **Learning rate** — verify schedule applied (common silent bug)\n\n---\n\n## Experiment Management\n\nTrack experiments in TSV for easy comparison:\n\n```\ncommit  val_bpb  memory_gb  status   description\na1b2c3d 0.9979   44.0       keep     baseline\nb2c3d4e 0.9932   44.2       keep     increase matrix LR to 0.04\nc3d4e5f 1.0050   44.0       discard  switch to GeLU (worse)\n```\n\n**Simplicity criterion**: all else equal, simpler is better. Removing something and getting equal\nresults is a great outcome. For systematic agent-driven experimentation, see `references\u002Fexperiment-loop.md`.\n\n### Evaluation metrics by domain\n\n| Domain | Primary Metric | Notes |\n|--------|---------------|-------|\n| LLM | BPB (bits per byte) | Vocab-size-independent |\n| Classification | Accuracy \u002F F1 | Macro-F1 for imbalanced |\n| Segmentation | mIoU \u002F Dice | Per-class IoU reveals weak spots |\n| Generation | FID | Needs >10k samples |\n| Regression | RMSE \u002F MAE | Log-transform skewed targets |\n\n## Related skills\n\n- `serving-llms-vllm`: Serves LLMs with high throughput using vLLM's PagedAttention and continuous batching.\n- `llama-factory`: Guides fine-tuning of large language models with LLaMA-Factory, covering the WebUI no-code interface, training across 100+ supported models…\n- `peft-fine-tuning`: Fine-tunes LLMs with Hugging Face PEFT, using LoRA, QLoRA, IA3, AdaLoRA, prefix tuning, and prompt tuning so that under 1% of parameters ar…\n",{"name":5,"license":15,"metadata":44,"description":7},{"tags":45,"version":46,"category":47,"maintainer":48,"contributor":49,"dependencies":50},"PyTorch, Training, Optimization, LLM, Vision, Diffusion, Biomedical, Muon, AdamW, Debugging","1.0.0","ml-training","Kalaris Labs","dailycafi","torch>=2.0.0","main","0da4485785ee599388900be50db1635489d53056",".agents\u002Fskills\u002Fkal-ml-training-recipes","https:\u002F\u002Fgithub.com\u002FTashima-Tarsh\u002FDisha6.6","https:\u002F\u002Fdisha6.6.thenitishkr.in\u002F","https:\u002F\u002Fgithub.com\u002FTashima-Tarsh","www.thenitishkr","thenitishkr | AI • Cyber-security • Research\r\n","2026-11-08 03:33:25",{"source":8,"skillName":5,"commands":61,"prompt":71,"zipAvailable":72},[62,65,68],{"tool":63,"command":64},"npx","npx skills add Tashima-Tarsh\u002FDisha6.6 --skill ml-training-recipes",{"tool":66,"command":67},"bunx","bunx skills add Tashima-Tarsh\u002FDisha6.6 --skill ml-training-recipes",{"tool":69,"command":70},"pnpm","pnpm dlx skills add Tashima-Tarsh\u002FDisha6.6 --skill ml-training-recipes","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FTashima-Tarsh\u002FDisha6.6\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fkal-ml-training-recipes\u002FSKILL.md",true,[74,80,84,88,92,96],{"path":75,"resourceType":76,"resourceTypeDesc":77,"sizeBytes":78,"sourceHtmlUrl":79},"references\u002Farchitecture.md","REFERENCE","参考文档",10204,"https:\u002F\u002Fgithub.com\u002FTashima-Tarsh\u002FDisha6.6\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fkal-ml-training-recipes\u002Freferences\u002Farchitecture.md",{"path":81,"resourceType":76,"resourceTypeDesc":77,"sizeBytes":82,"sourceHtmlUrl":83},"references\u002Fbiomedical.md",20778,"https:\u002F\u002Fgithub.com\u002FTashima-Tarsh\u002FDisha6.6\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fkal-ml-training-recipes\u002Freferences\u002Fbiomedical.md",{"path":85,"resourceType":76,"resourceTypeDesc":77,"sizeBytes":86,"sourceHtmlUrl":87},"references\u002Fdomain-specific.md",19018,"https:\u002F\u002Fgithub.com\u002FTashima-Tarsh\u002FDisha6.6\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fkal-ml-training-recipes\u002Freferences\u002Fdomain-specific.md",{"path":89,"resourceType":76,"resourceTypeDesc":77,"sizeBytes":90,"sourceHtmlUrl":91},"references\u002Fexperiment-loop.md",4446,"https:\u002F\u002Fgithub.com\u002FTashima-Tarsh\u002FDisha6.6\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fkal-ml-training-recipes\u002Freferences\u002Fexperiment-loop.md",{"path":93,"resourceType":76,"resourceTypeDesc":77,"sizeBytes":94,"sourceHtmlUrl":95},"references\u002Foptimizers.md",10564,"https:\u002F\u002Fgithub.com\u002FTashima-Tarsh\u002FDisha6.6\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fkal-ml-training-recipes\u002Freferences\u002Foptimizers.md",{"path":97,"resourceType":76,"resourceTypeDesc":77,"sizeBytes":98,"sourceHtmlUrl":99},"references\u002Fscaling-and-selection.md",16832,"https:\u002F\u002Fgithub.com\u002FTashima-Tarsh\u002FDisha6.6\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fkal-ml-training-recipes\u002Freferences\u002Fscaling-and-selection.md",[101,132,156,183,208,232],{"skillNo":102,"name":103,"nameZh":6,"description":104,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":105,"categories":106,"keywords":112,"publishedAt":39},"01M6QRD07D4TGNDK6VJ4EHF8BV","youtube-full","Use when the user needs YouTube transcripts, video search, channel browsing, playlist extraction, or content monitoring. Trigger phrases: 'get the transcript for', 'search YouTube for', 'what are the latest videos on', 'list this playlist', 'monitor this channel', or any request involving a YouTube URL, video ID, or @handle. Do NOT use for downloading video or audio files, YouTube engagement data (likes, comments), or private\u002Fage-restricted videos.","https:\u002F\u002Fgithub.com\u002FTashima-Tarsh\u002FDisha6.6\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fyoutube-full\u002FSKILL.md",[107],{"categoryNo":108,"categoryName":109,"taxonomyType":110,"taxonomyTypeDesc":111},"01JBSEEDCAT000000000000016","图像与多媒体","SCENARIO","使用场景",[113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,128,24,129,130,131],"youtube full","youtube","full","transcript","search","monitoring","data","Video","Audio","list","files","do","get","age","trigger","URL","browsing","request","youtube transcripts",{"skillNo":133,"name":134,"nameZh":6,"description":135,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":136,"categories":137,"keywords":138,"publishedAt":39},"01M6QRCJ3112VYPA97YG7KGMC2","x-twitter-growth","X\u002FTwitter growth engine for building audience, crafting viral content, and analyzing engagement. Use when the user wants to grow on X\u002FTwitter, write tweets or threads, analyze their X profile, research competitors on X, plan a posting strategy, or optimize engagement. Complements social-content (generic multi-platform) with X-specific depth: algorithm mechanics, thread engineering, reply strategy, profile optimization, and competitive intelligence via web search.","https:\u002F\u002Fgithub.com\u002FTashima-Tarsh\u002FDisha6.6\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fx-twitter-growth\u002FSKILL.md",[],[139,140,141,142,117,143,144,145,146,147,148,149,150,151,34,152,153,154,155,24],"twitter","x twitter growth","growth","research","content","engineering","plan","web search","competitors","analyze","engine","write","strategy","platform","grow","posting","competitive",{"skillNo":157,"name":158,"nameZh":6,"description":159,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":160,"categories":161,"keywords":165,"publishedAt":39},"01M6QRBN3EHQNJY42RERP7A149","write-a-skill","Create new agent skills with proper structure, progressive disclosure, and bundled resources. Use when user wants to create, write, build, or author a new skill.","https:\u002F\u002Fgithub.com\u002FTashima-Tarsh\u002FDisha6.6\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fwrite-a-skill\u002FSKILL.md",[162],{"categoryNo":163,"categoryName":164,"taxonomyType":110,"taxonomyTypeDesc":111},"01JBSEEDCAT000000000000023","Skill与智能体开发",[166,150,167,168,169,170,171,172,34,173,174,51,175,176,177,178,179,180,181,182],"write a skill","github","create","https","productivity","matt pocock","direct","example","build","new skill","structure","new agent","resources","with","tree","progressive disclosure","author",{"skillNo":184,"name":185,"nameZh":6,"description":186,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":187,"categories":188,"keywords":189,"publishedAt":39},"01M6QRB6G8P33PNGAF9Y69EJ9T","wrap-up","Close out a launched Claude Managed Agent — recap every primitive the founder now owns, regenerate the single-file overview page, and suggest the next 1-2 upgrades. Use when the user says \"wrap up\", \"close this out\", \"what do I own now\", \"give me the summary\", \"recap the agent\", or when the orchestrator routes phase=wrap-up. primitives_inventory.py tables everything owned (agent, environment, session, memory, outcome, deployment); overview_page.py regenerates a self-contained .\u002Fmy-agent\u002Fagent-overview.html; upgrade_suggester.py ranks the next moves from recorded deferrals plus standing hardening steps. Companion to run-without-you; the last stop before phase=done.","https:\u002F\u002Fgithub.com\u002FTashima-Tarsh\u002FDisha6.6\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fwrap-up\u002FSKILL.md",[],[190,191,192,193,194,195,196,197,198,34,199,124,200,201,202,203,204,205,206,207],"wrap up","up","wrap","gemini","deployment","run","file","hardening","closeout","stop","upgrade","founder","close","companion","you","tables","directions","phase",{"skillNo":209,"name":210,"nameZh":6,"description":211,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":212,"categories":213,"keywords":215,"publishedAt":39},"01M6QRA5AYC1RBFZ39GTWGS3N8","workflow-builder","Design and write deterministic multi-agent workflow scripts (.js files in .claude\u002Fworkflows\u002F) for Claude Code's Workflow tool. Use when a user wants to build, create, author, scaffold, or run a custom Claude Code workflow, orchestrate sub-agents (fan-out, pipeline, loop, judge-panel), or automate a repeatable multi-step task across fresh-context agents.","https:\u002F\u002Fgithub.com\u002FTashima-Tarsh\u002FDisha6.6\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fworkflow-builder\u002FSKILL.md",[214],{"categoryNo":163,"categoryName":164,"taxonomyType":110,"taxonomyTypeDesc":111},[216,217,218,219,220,168,195,221,222,223,224,225,150,226,123,227,228,229,230,231],"workflow","workflow builder","builder","design","workflows","code","orchestrate","pipeline","loop","multi-agent","context","across","fresh","scripts","judge","claude code workflow",{"skillNo":233,"name":234,"nameZh":6,"description":235,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":236,"categories":237,"keywords":238,"publishedAt":39},"01M6QR7QMCZESKQA0ERW1E657M","weekly-review","Use when someone wants to run a weekly review, close open loops, audit stalled projects and commitments, get their system back to trusted, restart a lapsed review habit, or says \"\u002Fcs:weekly-review\". Walks David Allen's three-phase loop — GET CLEAR, GET CURRENT, GET CREATIVE — with deterministic scripts that inventory open loops, gate the checklist with named gaps, and score commitment health 0-100.","https:\u002F\u002Fgithub.com\u002FTashima-Tarsh\u002FDisha6.6\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fweekly-review\u002FSKILL.md",[],[239,240,241,242,243,244,245,246,247,224,248,249,250,251,252,253,125,254,255,207],"review","weekly review","weekly","deterministic scripts","reflect","feeds","inventory","open","team","projects","project-management","scanner","conversation","back","project","sprint","cadence"]