@ericrisco/rsc 0.1.39 → 0.1.41
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +8 -2
- package/manifest.json +181 -3
- package/package.json +1 -1
- package/scripts/lib/domains.js +1 -0
- package/scripts/lib/recommend.js +6 -0
- package/skills/deep-learning/SKILL.md +263 -0
- package/skills/deep-learning/evals/README.md +11 -0
- package/skills/deep-learning/evals/cases.yaml +48 -0
- package/skills/deep-learning/references/distributed.md +105 -0
- package/skills/deep-learning/references/training-recipes.md +135 -0
- package/skills/finetuning/SKILL.md +244 -0
- package/skills/finetuning/evals/README.md +13 -0
- package/skills/finetuning/evals/cases.yaml +50 -0
- package/skills/finetuning/references/hyperparameters-and-eval.md +74 -0
- package/skills/finetuning/references/methods.md +189 -0
- package/skills/harness/references/providers.yaml +35 -0
- package/skills/huggingface/SKILL.md +1 -1
- package/skills/machine-learning/SKILL.md +260 -0
- package/skills/machine-learning/evals/README.md +15 -0
- package/skills/machine-learning/evals/cases.yaml +54 -0
- package/skills/machine-learning/references/gbdt-and-tuning.md +83 -0
- package/skills/machine-learning/references/metrics-and-imbalance.md +82 -0
- package/skills/machine-learning/references/pipelines-and-cv.md +135 -0
- package/skills/nlp/SKILL.md +225 -0
- package/skills/nlp/evals/README.md +10 -0
- package/skills/nlp/evals/cases.yaml +45 -0
- package/skills/nlp/references/evaluation.md +107 -0
- package/skills/nlp/references/tokenization.md +95 -0
- package/skills/open-weights/SKILL.md +239 -0
- package/skills/open-weights/evals/README.md +14 -0
- package/skills/open-weights/evals/cases.yaml +42 -0
- package/skills/open-weights/references/licenses.md +123 -0
- package/skills/open-weights/references/model-families.md +83 -0
- package/skills/open-weights/references/sizing-and-quant.md +89 -0
- package/skills/roast-me/tools/adapters/__pycache__/__init__.cpython-312.pyc +0 -0
- package/skills/roast-me/tools/adapters/__pycache__/base.cpython-312.pyc +0 -0
- package/skills/roast-me/tools/adapters/__pycache__/claude.cpython-312.pyc +0 -0
- package/skills/roast-me/tools/adapters/__pycache__/codex.cpython-312.pyc +0 -0
- package/skills/roast-me/tools/adapters/__pycache__/gemini.cpython-312.pyc +0 -0
- package/skills/roast-me/tools/adapters/__pycache__/registry.cpython-312.pyc +0 -0
- package/skills/training-data/SKILL.md +226 -0
- package/skills/training-data/evals/README.md +13 -0
- package/skills/training-data/evals/cases.yaml +41 -0
- package/skills/training-data/references/formats.md +118 -0
- package/skills/training-data/references/synthesis-dedup-quality.md +134 -0
- package/skills/unsloth/SKILL.md +254 -0
- package/skills/unsloth/evals/README.md +10 -0
- package/skills/unsloth/evals/cases.yaml +42 -0
- package/skills/unsloth/references/export.md +75 -0
- package/skills/unsloth/references/grpo.md +91 -0
- package/skills/unsloth/references/masking-and-templates.md +91 -0
- package/skills/vllm/SKILL.md +235 -0
- package/skills/vllm/evals/README.md +9 -0
- package/skills/vllm/evals/cases.yaml +47 -0
- package/skills/vllm/references/flags-and-endpoints.md +105 -0
- package/skills/vllm/references/memory-and-throughput.md +78 -0
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
skill: deep-learning
|
|
2
|
+
|
|
3
|
+
should_trigger:
|
|
4
|
+
- prompt: "My PyTorch training loss isn't going down at all — the loop looks fine, what am I missing?"
|
|
5
|
+
why: "Core training-loop debugging in Torch; the diagnosis lands on the five-step loop and its silent bugs, this skill's center."
|
|
6
|
+
- prompt: "Loss becomes NaN after a few hundred steps when I turn on float16. How do I fix it?"
|
|
7
|
+
why: "AMP fp16 underflow / missing GradScaler and the bf16 alternative — the mixed-precision section owns this."
|
|
8
|
+
- prompt: "How do I use torch.autocast and GradScaler, and should I pick bf16 or fp16?"
|
|
9
|
+
why: "Explicit AMP API + the bf16-vs-fp16 decision this skill teaches."
|
|
10
|
+
- prompt: "I need to train this model across 4 GPUs — DDP or FSDP, and how do I launch it?"
|
|
11
|
+
why: "Distributed choice by memory-fit plus torchrun launch is a named section (and references/distributed.md)."
|
|
12
|
+
- prompt: "My validation accuracy is way worse than training and I think I forgot model.eval()."
|
|
13
|
+
why: "Non-obvious guardrail: eval() vs train() flips Dropout/BatchNorm; squarely a load-bearing gotcha here."
|
|
14
|
+
- prompt: "Gradients seem to add up across batches and training blows up — is my loop wrong?"
|
|
15
|
+
why: "Non-obvious: the symptom is a missing optimizer.zero_grad(), the flagship silent bug of this skill; no API named."
|
|
16
|
+
- prompt: "Build a CNN from scratch in PyTorch and write the training loop to fit it on my image dataset."
|
|
17
|
+
why: "From-scratch net + custom loop in Torch — inside the boundary vs finetuning/ML."
|
|
18
|
+
- prompt: "vull entrenar una xarxa neuronal des de zero amb PyTorch i que sigui reproduïble"
|
|
19
|
+
why: "Catalan trigger: from-scratch neural net + reproducibility, both owned here."
|
|
20
|
+
|
|
21
|
+
should_not_trigger:
|
|
22
|
+
- prompt: "Fine-tune Llama with QLoRA on my instruction dataset using trl and peft."
|
|
23
|
+
route_to: finetuning
|
|
24
|
+
why: "Adapting a pretrained LLM with LoRA/QLoRA is the finetuning method skill, not general net training."
|
|
25
|
+
- prompt: "Should I use XGBoost or a random forest for this tabular churn dataset?"
|
|
26
|
+
route_to: machine-learning
|
|
27
|
+
why: "Classic/tabular GBDT modeling — no autograd, no PyTorch loop."
|
|
28
|
+
- prompt: "Which tokenizer and how do I compute F1/BLEU for my text classification task?"
|
|
29
|
+
route_to: nlp
|
|
30
|
+
why: "Tokenization and NLP task metrics live in nlp; only the raw training loop routes back here."
|
|
31
|
+
- prompt: "Serve my trained model with vLLM and set the right batching flags for throughput."
|
|
32
|
+
route_to: vllm
|
|
33
|
+
why: "Inference/serving engine, not training."
|
|
34
|
+
- prompt: "Set up a clean Python project with uv, pytest, and type checking for my model code."
|
|
35
|
+
route_to: python
|
|
36
|
+
why: "Env/packaging/testing hygiene, not the neural-net training itself."
|
|
37
|
+
|
|
38
|
+
capability:
|
|
39
|
+
- scenario: "A user is training a from-scratch image classifier in PyTorch on one A100. Training loss is unstable and sometimes NaNs, validation numbers look wrong, and they want it faster and reproducible. Write the training setup and explain the fixes."
|
|
40
|
+
must_include:
|
|
41
|
+
- "Correct five-step loop with optimizer.zero_grad(set_to_none=True) EVERY step, explaining that PyTorch accumulates .grad so skipping zero_grad silently sums gradients across batches"
|
|
42
|
+
- "AMP via torch.autocast on forward+loss only with torch.amp.GradScaler; recommends bf16 on A100 (no scaler needed) and notes fp16 REQUIRES the scaler to avoid underflow NaNs"
|
|
43
|
+
- "Gradient clipping done after scaler.unscale_(optimizer), and CrossEntropyLoss fed raw logits (no Softmax before it)"
|
|
44
|
+
- "model.eval() plus torch.no_grad() for validation, stating it changes Dropout/BatchNorm behavior and prevents graph build, and model.train() to switch back — as the cause of bad val numbers"
|
|
45
|
+
- "AdamW with weight decay excluded from bias/Norm params, plus a warmup→cosine schedule (LinearLR + CosineAnnealingLR via SequentialLR) with step() cadence matching the scheduler units"
|
|
46
|
+
- "torch.compile(model) offered as the speedup, noting first steps are slow due to compilation"
|
|
47
|
+
- "Reproducibility: seed random/numpy/torch, torch.use_deterministic_algorithms(True), cudnn.deterministic/benchmark=False, CUBLAS_WORKSPACE_CONFIG, and the honest caveat that results are NOT guaranteed across PyTorch releases/platforms or CPU-vs-GPU even with identical seeds"
|
|
48
|
+
- "Checkpoints save model+optimizer+scheduler+scaler state_dicts (not the model object), resuming model first; version hedged to PyTorch 2.x (~2.13, verify)"
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
# Distributed training — DDP, FSDP2, DeepSpeed ZeRO (mechanics)
|
|
2
|
+
|
|
3
|
+
Grounded in `pytorch.org/docs/stable/` (DDP: `notes/ddp.html`, `generated/torch.nn.parallel.DistributedDataParallel.html`;
|
|
4
|
+
FSDP2: `distributed.fsdp.fully_shard.html`). Verify API against the installed version — distributed
|
|
5
|
+
APIs move faster than the core loop.
|
|
6
|
+
|
|
7
|
+
## The decision, restated
|
|
8
|
+
|
|
9
|
+
| Situation | Use | Why |
|
|
10
|
+
|---|---|---|
|
|
11
|
+
| Model fits on one GPU, want more throughput / bigger effective batch | **DDP** | Simplest; replicate + all-reduce grads |
|
|
12
|
+
| Model (params+grads+optimizer state) does NOT fit on one GPU | **FSDP2** | Shards the three memory hogs across ranks |
|
|
13
|
+
| Need CPU/NVMe offload, or config-first scaling, or already using Accelerate/DeepSpeed | **DeepSpeed ZeRO** | Stage 1/2/3 + offload, external library |
|
|
14
|
+
|
|
15
|
+
Data parallel of any kind assumes each rank sees a **different shard of the batch** — use
|
|
16
|
+
`DistributedSampler` so ranks don't all train on the same rows.
|
|
17
|
+
|
|
18
|
+
## DDP — one process per GPU
|
|
19
|
+
|
|
20
|
+
```python
|
|
21
|
+
import os, torch, torch.distributed as dist
|
|
22
|
+
from torch.nn.parallel import DistributedDataParallel as DDP
|
|
23
|
+
|
|
24
|
+
dist.init_process_group("nccl") # NCCL for CUDA; "gloo" for CPU
|
|
25
|
+
local_rank = int(os.environ["LOCAL_RANK"]) # set by torchrun
|
|
26
|
+
torch.cuda.set_device(local_rank)
|
|
27
|
+
|
|
28
|
+
model = MyModel().to(local_rank)
|
|
29
|
+
model = DDP(model, device_ids=[local_rank]) # grads all-reduced automatically in backward
|
|
30
|
+
|
|
31
|
+
from torch.utils.data import DataLoader
|
|
32
|
+
from torch.utils.data.distributed import DistributedSampler
|
|
33
|
+
sampler = DistributedSampler(train_ds) # disjoint shard per rank
|
|
34
|
+
loader = DataLoader(train_ds, sampler=sampler, batch_size=bs)
|
|
35
|
+
|
|
36
|
+
for epoch in range(epochs):
|
|
37
|
+
sampler.set_epoch(epoch) # REQUIRED: reshuffles per epoch across ranks
|
|
38
|
+
for x, y in loader:
|
|
39
|
+
... # normal 5-step loop; DDP syncs grads for you
|
|
40
|
+
|
|
41
|
+
if local_rank == 0:
|
|
42
|
+
torch.save(model.module.state_dict(), "ckpt.pt") # .module unwraps DDP; save on rank 0 only
|
|
43
|
+
dist.destroy_process_group()
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
Launch: `torchrun --standalone --nproc_per_node=4 train.py` (4 GPUs, one node). Multi-node adds
|
|
47
|
+
`--nnodes`, `--node_rank`, `--rdzv_endpoint`.
|
|
48
|
+
|
|
49
|
+
DDP gotchas:
|
|
50
|
+
- **`sampler.set_epoch(epoch)`** or every epoch sees the same order — a silent correctness bug.
|
|
51
|
+
- **`find_unused_parameters=True`** only if some params get no grad each step (costs a graph
|
|
52
|
+
traversal); leaving it True unnecessarily slows training.
|
|
53
|
+
- Save/load on **rank 0** and unwrap with `.module`; barrier before others load.
|
|
54
|
+
- Effective batch = `per_gpu_batch * world_size` — scale LR accordingly (linear-scaling rule).
|
|
55
|
+
|
|
56
|
+
## FSDP2 — shard when it doesn't fit
|
|
57
|
+
|
|
58
|
+
FSDP2 (`fully_shard`) is the current API: DTensor-based, per-parameter dim-0 sharding. Apply it
|
|
59
|
+
**bottom-up** — wrap the repeated blocks first, then the root module — so each `fully_shard` call
|
|
60
|
+
forms a communication group and gathers params just-in-time.
|
|
61
|
+
|
|
62
|
+
```python
|
|
63
|
+
from torch.distributed.fsdp import fully_shard
|
|
64
|
+
|
|
65
|
+
for block in model.transformer_blocks: # wrap leaves/blocks first
|
|
66
|
+
fully_shard(block)
|
|
67
|
+
fully_shard(model) # then the root
|
|
68
|
+
|
|
69
|
+
# Mixed precision is a policy here, not GradScaler:
|
|
70
|
+
from torch.distributed.fsdp import MixedPrecisionPolicy
|
|
71
|
+
for block in model.transformer_blocks:
|
|
72
|
+
fully_shard(block, mp_policy=MixedPrecisionPolicy(param_dtype=torch.bfloat16))
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
- `reshard_after_forward=True` (default for non-root) frees gathered params after forward and
|
|
76
|
+
re-gathers in backward — saves memory, costs an all-gather. `False` (default for root) keeps them.
|
|
77
|
+
- Wrapping **only** the root makes one giant communication group with no compute/comm overlap —
|
|
78
|
+
wrap blocks to overlap.
|
|
79
|
+
- FSDP2 uses AMP via `MixedPrecisionPolicy`, not `torch.amp.GradScaler`.
|
|
80
|
+
- Full-state-dict save needs `DTensor.full_tensor()` or Distributed Checkpoint (DCP) APIs; prefer
|
|
81
|
+
sharded checkpoints for large models.
|
|
82
|
+
|
|
83
|
+
## DeepSpeed ZeRO — external, config-driven
|
|
84
|
+
|
|
85
|
+
DeepSpeed is a **separate library** (Microsoft), commonly driven through a JSON config and/or HF
|
|
86
|
+
Accelerate. Verify the current version and config schema — it evolves independently of Torch.
|
|
87
|
+
|
|
88
|
+
| Stage | Shards | Rough memory win vs DDP | Comm cost |
|
|
89
|
+
|---|---|---|---|
|
|
90
|
+
| ZeRO-1 | optimizer states | ~4× on optimizer state | ~DDP |
|
|
91
|
+
| ZeRO-2 | + gradients | more | ~DDP |
|
|
92
|
+
| ZeRO-3 | + parameters (≈ FSDP) | largest | higher (gather params) |
|
|
93
|
+
| + offload | move state to CPU/NVMe | fit far bigger models | slowest (PCIe/disk bound) |
|
|
94
|
+
|
|
95
|
+
Choose ZeRO over FSDP2 when you specifically want **offload** or a config-first workflow, or you're
|
|
96
|
+
already in the DeepSpeed/Accelerate stack. For pure Torch, FSDP2 covers the same ZeRO-3 territory
|
|
97
|
+
natively.
|
|
98
|
+
|
|
99
|
+
## Cross-cutting
|
|
100
|
+
|
|
101
|
+
- **Gradient accumulation** (micro-batching) simulates a bigger batch on limited memory: run N
|
|
102
|
+
forward/backward passes, then one `optimizer.step()` + `zero_grad()`. Under DDP, wrap the
|
|
103
|
+
non-final micro-steps in `model.no_sync()` to skip redundant all-reduces.
|
|
104
|
+
- **`torch.compile` composes** with DDP and FSDP2, but compile after wrapping and expect a longer
|
|
105
|
+
warmup.
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
# Training recipes — a full loop, reproducibility harness, and debug ladder
|
|
2
|
+
|
|
3
|
+
Concrete, runnable single-GPU scaffolding to lift into a project. APIs verified against
|
|
4
|
+
`pytorch.org/docs/stable/` (amp_examples, optim, notes/randomness). Hedge versions to "PyTorch 2.x".
|
|
5
|
+
|
|
6
|
+
## A complete single-GPU training loop (AMP + AdamW + warmup→cosine + checkpoint)
|
|
7
|
+
|
|
8
|
+
```python
|
|
9
|
+
import torch, torch.nn as nn
|
|
10
|
+
from torch.optim.lr_scheduler import LinearLR, CosineAnnealingLR, SequentialLR
|
|
11
|
+
|
|
12
|
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
|
13
|
+
model = MyModel().to(device)
|
|
14
|
+
model = torch.compile(model) # optional speedup; first steps compile (slow)
|
|
15
|
+
|
|
16
|
+
# No weight decay on bias/Norm params — two groups.
|
|
17
|
+
decay, no_decay = [], []
|
|
18
|
+
for n, p in model.named_parameters():
|
|
19
|
+
if not p.requires_grad:
|
|
20
|
+
continue
|
|
21
|
+
(no_decay if p.ndim <= 1 or n.endswith(".bias") else decay).append(p)
|
|
22
|
+
opt = torch.optim.AdamW(
|
|
23
|
+
[{"params": decay, "weight_decay": 0.01},
|
|
24
|
+
{"params": no_decay, "weight_decay": 0.0}],
|
|
25
|
+
lr=3e-4, betas=(0.9, 0.999),
|
|
26
|
+
)
|
|
27
|
+
|
|
28
|
+
total_steps = len(train_loader) * epochs
|
|
29
|
+
warmup = LinearLR(opt, start_factor=0.1, total_iters=min(500, total_steps // 20))
|
|
30
|
+
cosine = CosineAnnealingLR(opt, T_max=total_steps - warmup.total_iters, eta_min=3e-5)
|
|
31
|
+
sched = SequentialLR(opt, [warmup, cosine], milestones=[warmup.total_iters])
|
|
32
|
+
|
|
33
|
+
loss_fn = nn.CrossEntropyLoss(label_smoothing=0.1) # takes RAW logits
|
|
34
|
+
scaler = torch.amp.GradScaler("cuda", enabled=(device == "cuda"))
|
|
35
|
+
USE_BF16 = torch.cuda.is_bf16_supported() if device == "cuda" else False
|
|
36
|
+
amp_dtype = torch.bfloat16 if USE_BF16 else torch.float16
|
|
37
|
+
# NOTE: with bf16 the scaler is a no-op; keep enabled only for fp16.
|
|
38
|
+
|
|
39
|
+
best_val = float("inf")
|
|
40
|
+
for epoch in range(epochs):
|
|
41
|
+
model.train()
|
|
42
|
+
for x, y in train_loader:
|
|
43
|
+
x, y = x.to(device), y.to(device)
|
|
44
|
+
opt.zero_grad(set_to_none=True)
|
|
45
|
+
with torch.autocast(device_type=device, dtype=amp_dtype, enabled=(device == "cuda")):
|
|
46
|
+
loss = loss_fn(model(x), y)
|
|
47
|
+
scaler.scale(loss).backward()
|
|
48
|
+
scaler.unscale_(opt) # unscale before clipping
|
|
49
|
+
torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
|
|
50
|
+
scaler.step(opt)
|
|
51
|
+
scaler.update()
|
|
52
|
+
sched.step() # per-step: units are steps
|
|
53
|
+
|
|
54
|
+
# ---- validation ----
|
|
55
|
+
model.eval()
|
|
56
|
+
val_loss, n = 0.0, 0
|
|
57
|
+
with torch.no_grad(): # no graph, no Dropout/BN train stats
|
|
58
|
+
for x, y in val_loader:
|
|
59
|
+
x, y = x.to(device), y.to(device)
|
|
60
|
+
val_loss += loss_fn(model(x), y).item() * x.size(0) # .item() -> no graph leak
|
|
61
|
+
n += x.size(0)
|
|
62
|
+
val_loss /= n
|
|
63
|
+
|
|
64
|
+
if val_loss < best_val: # early-stopping signal + best ckpt
|
|
65
|
+
best_val = val_loss
|
|
66
|
+
torch.save({"epoch": epoch,
|
|
67
|
+
"model": model.state_dict(),
|
|
68
|
+
"optimizer": opt.state_dict(),
|
|
69
|
+
"scheduler": sched.state_dict(),
|
|
70
|
+
"scaler": scaler.state_dict(),
|
|
71
|
+
"best_val": best_val}, "best.pt")
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
Resume:
|
|
75
|
+
|
|
76
|
+
```python
|
|
77
|
+
ckpt = torch.load("best.pt", map_location=device)
|
|
78
|
+
model.load_state_dict(ckpt["model"]) # model FIRST
|
|
79
|
+
opt.load_state_dict(ckpt["optimizer"])
|
|
80
|
+
sched.load_state_dict(ckpt["scheduler"])
|
|
81
|
+
scaler.load_state_dict(ckpt["scaler"])
|
|
82
|
+
start_epoch = ckpt["epoch"] + 1
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
## Reproducibility harness (with the honest caveat)
|
|
86
|
+
|
|
87
|
+
`pytorch.org/docs/stable/notes/randomness.html`: *"Completely reproducible results are not
|
|
88
|
+
guaranteed across PyTorch releases, individual commits, or different platforms … results may not be
|
|
89
|
+
reproducible between CPU and GPU executions, even when using identical seeds."* Seed for
|
|
90
|
+
debugging/regression, never promise bit-exactness across machines.
|
|
91
|
+
|
|
92
|
+
```python
|
|
93
|
+
import os, random, numpy as np, torch
|
|
94
|
+
|
|
95
|
+
def make_reproducible(seed=42, strict=False):
|
|
96
|
+
random.seed(seed); np.random.seed(seed); torch.manual_seed(seed) # CPU + all CUDA devices
|
|
97
|
+
if strict:
|
|
98
|
+
torch.use_deterministic_algorithms(True) # raises on ops lacking a deterministic path
|
|
99
|
+
torch.backends.cudnn.deterministic = True
|
|
100
|
+
torch.backends.cudnn.benchmark = False # benchmark=True autotunes -> nondeterministic
|
|
101
|
+
os.environ.setdefault("CUBLAS_WORKSPACE_CONFIG", ":4096:8") # CUDA>=10.2; set before launch
|
|
102
|
+
|
|
103
|
+
# DataLoader workers fork their own RNG — seed each one, plus a seeded generator.
|
|
104
|
+
def seed_worker(worker_id):
|
|
105
|
+
ws = torch.initial_seed() % 2**32
|
|
106
|
+
np.random.seed(ws); random.seed(ws)
|
|
107
|
+
|
|
108
|
+
g = torch.Generator(); g.manual_seed(42)
|
|
109
|
+
loader = torch.utils.data.DataLoader(ds, batch_size=64, num_workers=4,
|
|
110
|
+
worker_init_fn=seed_worker, generator=g)
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
`strict=True` (deterministic algorithms + `benchmark=False`) trades speed for reproducibility —
|
|
114
|
+
use while debugging, drop for throughput runs.
|
|
115
|
+
|
|
116
|
+
## Debug ladder — "loss won't go down" / "loss is NaN"
|
|
117
|
+
|
|
118
|
+
Work top-down; each rules out a class of bug.
|
|
119
|
+
|
|
120
|
+
1. **Overfit one batch.** Loop on a single mini-batch; loss must reach ~0. If it can't, the bug is
|
|
121
|
+
in the model/loss/data wiring, not optimization.
|
|
122
|
+
2. **Check the loss input.** `CrossEntropyLoss`/`BCEWithLogitsLoss` want **raw logits** — a Softmax
|
|
123
|
+
before them silently stalls learning. Confirm target shape/dtype (class indices, not one-hot,
|
|
124
|
+
for `CrossEntropyLoss`).
|
|
125
|
+
3. **Confirm grads flow.** After `backward()`, inspect a param's `.grad`: all `None`/zero means the
|
|
126
|
+
graph is detached (a stray `.detach()`, `.item()`, `.numpy()`, or `no_grad` in the path) or you
|
|
127
|
+
forgot `zero_grad` and are reading stale state.
|
|
128
|
+
4. **LR sweep.** NaN early → LR too high (drop 10×) or missing fp16 scaler. No movement → LR too low
|
|
129
|
+
or a dead activation (all-zero ReLU). Add `clip_grad_norm_(…, 1.0)`.
|
|
130
|
+
5. **Precision.** fp16 NaN/Inf → ensure `GradScaler` is active, or switch to **bf16** (wider range,
|
|
131
|
+
no scaler). Check for `log(0)`/`sqrt(neg)`/`0/0` in any custom loss.
|
|
132
|
+
6. **Data.** NaNs/Infs in inputs, unnormalized features, or shuffled labels. Verify a few batches by
|
|
133
|
+
eye.
|
|
134
|
+
7. **eval vs train mismatch.** Great train loss, bad val → you likely forgot `model.eval()` (Dropout
|
|
135
|
+
still on, BatchNorm using batch stats) or you're leaking train data into val.
|
|
@@ -0,0 +1,244 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: finetuning
|
|
3
|
+
description: "Use when adapting an open-weight model to a target FORM or BEHAVIOR — tone, output format, domain style, a reasoning/tool-calling pattern — via LoRA/QLoRA or full fine-tuning with TRL SFTTrainer and then preference optimization (DPO/ORPO/KTO/GRPO); when choosing fine-tune vs prompt vs RAG vs longer context; when setting LoRA r/alpha/target_modules; when eval loss climbs while train loss keeps falling; when the adapter seems to have learned nothing; when inference outputs garbage after a run. Triggers: 'fine-tune Llama/Qwen on our data', 'LoRA vs QLoRA vs full fine-tune', 'SFT then DPO/ORPO/KTO/GRPO', 'set target_modules / rank / alpha', 'my fine-tune overfits', 'the model forgot everything after training', 'write a GRPO reward function', 'ajustar un modelo amb LoRA amb les nostres dades'. NOT adding facts or fresh knowledge to a model (that is rag); NOT the fast single-GPU Unsloth backend or GGUF export (that is unsloth); NOT serving the trained model (that is vllm)."
|
|
4
|
+
tags: [finetuning, lora, qlora, sft, dpo, grpo, peft, trl, preference-optimization]
|
|
5
|
+
recommends: [training-data, unsloth, open-weights, huggingface, vllm, rag]
|
|
6
|
+
origin: risco
|
|
7
|
+
---
|
|
8
|
+
|
|
9
|
+
# finetuning — teach an open model a form or behavior, not a fact
|
|
10
|
+
|
|
11
|
+
You own the discipline of **adapting an open-weight model**: deciding whether to fine-tune at all,
|
|
12
|
+
then running SFT and (optionally) preference optimization with `trl` + `peft`, backend-agnostic.
|
|
13
|
+
You are judged by whether the tuned model reliably produces the target **form/behavior** on a
|
|
14
|
+
held-out set — not by train loss, and not by vibes.
|
|
15
|
+
|
|
16
|
+
The one sentence that routes half of all "should I fine-tune?" questions correctly:
|
|
17
|
+
**fine-tuning teaches *form and behavior*; RAG supplies *facts*.** If the ask is "know our latest
|
|
18
|
+
prices / docs / tickets," that is retrieval (`../rag/SKILL.md`), not training. If the ask is "sound
|
|
19
|
+
like us, always emit this JSON, follow this reasoning pattern," that is here.
|
|
20
|
+
|
|
21
|
+
## Decision gate — try this BEFORE reaching for a GPU
|
|
22
|
+
|
|
23
|
+
Fine-tuning is the last lever, not the first. Exhaust the cheaper, reversible options first; each
|
|
24
|
+
row below is a real off-ramp.
|
|
25
|
+
|
|
26
|
+
| If the goal is… | Do this first | Fine-tune only when… |
|
|
27
|
+
|---|---|---|
|
|
28
|
+
| The model should *know* current/company facts | **RAG** (`../rag/SKILL.md`) — retrieve + ground | never for facts; facts go stale, weights don't update |
|
|
29
|
+
| One-off format/tone, small volume | **Prompt + few-shot** (`prompt-engineering`) | the prompt is huge, brittle, or you pay for it every call |
|
|
30
|
+
| Behavior depends on a long document | **Longer context** / put it in the prompt | context won't fit, or per-call token cost is the bottleneck |
|
|
31
|
+
| Consistent *form/behavior* at scale, latency/cost sensitive | — | prompting plateaus AND you have (or can build) good examples |
|
|
32
|
+
| A capability the base model just can't do | — | you have a reward signal or demonstration data for it |
|
|
33
|
+
|
|
34
|
+
Route out explicitly. Facts / freshness / citations → `../rag/SKILL.md`. Squeezing a prompt before
|
|
35
|
+
spending money → `prompt-engineering`. Picking *which* base model (size/license/task) → `open-weights`.
|
|
36
|
+
Building the JSONL/preference corpus → `training-data`. A fast single-GPU run + GGUF export →
|
|
37
|
+
`../unsloth/SKILL.md`. Serving the result → `../vllm/SKILL.md`.
|
|
38
|
+
|
|
39
|
+
> The cheapest fine-tune is the one you didn't need. Prompt + RAG solves most "make it behave"
|
|
40
|
+
> asks at zero training cost and updates instantly. Fine-tune when that ceiling is real, measured,
|
|
41
|
+
> and you can afford to re-run it every time the base model or data changes.
|
|
42
|
+
|
|
43
|
+
## Version reality (verify at author time — this stack moves monthly)
|
|
44
|
+
|
|
45
|
+
- **`trl`** consolidated into a **v1.x** line (v1.0 landed ~2026; docs at author time referenced
|
|
46
|
+
~v1.8). Every method has a `Trainer` + a `Config` dataclass that inherits
|
|
47
|
+
`transformers.TrainingArguments` (`SFTTrainer`/`SFTConfig`, `DPOTrainer`/`DPOConfig`, …). Confirm
|
|
48
|
+
the current major before pinning: `pip show trl` / the [TRL docs](https://huggingface.co/docs/trl).
|
|
49
|
+
- **`transformers`** is on a **v5.x** line; `peft`, `bitsandbytes`, `accelerate`, `datasets`
|
|
50
|
+
round out the stack. Do not freeze a pin as "the version" — say "current major is ~X, verify."
|
|
51
|
+
- Some methods migrated to `trl.experimental.*` (e.g. `from trl.experimental.orpo import ORPOTrainer`
|
|
52
|
+
at author time). Import paths churn — check the method's doc page before copying an import.
|
|
53
|
+
- **Model licenses are not facts to memorize.** Llama ships under the Meta *Community* license
|
|
54
|
+
(usage caps, not OSI-open); Gemma under custom Google terms; Qwen/Mistral vary per size and often
|
|
55
|
+
Apache-2.0 — but **read the specific model card, licenses change.** License/size selection is
|
|
56
|
+
`open-weights`.
|
|
57
|
+
|
|
58
|
+
## LoRA / QLoRA vs full fine-tuning
|
|
59
|
+
|
|
60
|
+
Three options on one memory↔quality axis. Default to **QLoRA** unless you have a proven reason not to.
|
|
61
|
+
|
|
62
|
+
| Method | What trains | Rough VRAM (7–8B) | Use when |
|
|
63
|
+
|---|---|---|---|
|
|
64
|
+
| **Full FT** | every weight, fp16/bf16 | very high (needs multi-GPU / offload) | you have the hardware and a large, high-quality corpus and adapters underfit |
|
|
65
|
+
| **LoRA** | small low-rank adapter matrices; base frozen (fp16) | high | base fits in fp16 and you want adapter portability + speed |
|
|
66
|
+
| **QLoRA** | LoRA adapters over a **4-bit NF4** frozen base | lowest — single consumer GPU for 7–13B | the default; fine-tune big models on one GPU with ~no quality loss |
|
|
67
|
+
|
|
68
|
+
**QLoRA** (Dettmers et al., [arXiv:2305.14314](https://arxiv.org/abs/2305.14314)): load the base
|
|
69
|
+
in 4-bit **NF4** with double quantization, keep it frozen, and train LoRA adapters in bf16 on top.
|
|
70
|
+
It made single-GPU fine-tuning of large models practical at near-full-FT quality.
|
|
71
|
+
|
|
72
|
+
```python
|
|
73
|
+
import torch
|
|
74
|
+
from transformers import BitsAndBytesConfig
|
|
75
|
+
from peft import LoraConfig
|
|
76
|
+
from trl import SFTTrainer, SFTConfig
|
|
77
|
+
|
|
78
|
+
# 4-bit NF4 base (QLoRA). Verify arg names against current bitsandbytes/transformers.
|
|
79
|
+
bnb = BitsAndBytesConfig(
|
|
80
|
+
load_in_4bit=True,
|
|
81
|
+
bnb_4bit_quant_type="nf4",
|
|
82
|
+
bnb_4bit_use_double_quant=True,
|
|
83
|
+
bnb_4bit_compute_dtype=torch.bfloat16,
|
|
84
|
+
)
|
|
85
|
+
|
|
86
|
+
# LoRA over ALL linear layers — the safe target for QLoRA (PEFT quantization guide).
|
|
87
|
+
peft_config = LoraConfig(
|
|
88
|
+
r=16, lora_alpha=32, lora_dropout=0.05,
|
|
89
|
+
bias="none", task_type="CAUSAL_LM",
|
|
90
|
+
target_modules="all-linear", # or explicit ["q_proj","k_proj","v_proj","o_proj",...]
|
|
91
|
+
)
|
|
92
|
+
|
|
93
|
+
trainer = SFTTrainer(
|
|
94
|
+
model="Qwen/Qwen2.5-7B-Instruct", # instruct base → chat template already present
|
|
95
|
+
args=SFTConfig(output_dir="out", max_length=2048, packing=True,
|
|
96
|
+
learning_rate=2e-4, num_train_epochs=2, bf16=True),
|
|
97
|
+
train_dataset=dataset, # conversational: TRL applies the chat template
|
|
98
|
+
peft_config=peft_config,
|
|
99
|
+
quantization_config=bnb, # SFTTrainer + peft_config + this == QLoRA
|
|
100
|
+
)
|
|
101
|
+
trainer.train()
|
|
102
|
+
trainer.save_model("out") # saves the ADAPTER, not a merged model
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
`peft_config` + `quantization_config` on `SFTTrainer` is the current one-liner for QLoRA — no manual
|
|
106
|
+
`get_peft_model` / `prepare_model_for_kbit_training` wiring needed. `save_model` writes the small
|
|
107
|
+
adapter; merge to a standalone model only when serving requires it (see references).
|
|
108
|
+
|
|
109
|
+
## Pipeline: SFT first, then (maybe) preference optimization
|
|
110
|
+
|
|
111
|
+
`SFT → preference optimization` is the standard post-training arc. **SFT** teaches the model the
|
|
112
|
+
format and gives it the behavior by imitation. **Preference optimization** then sharpens *which* of
|
|
113
|
+
several plausible outputs is better. Most projects need only SFT; add a preference stage when "the
|
|
114
|
+
outputs are fine but I want the *good* one preferred" is the remaining gap.
|
|
115
|
+
|
|
116
|
+
| Method | Data it needs | Stage | Pick it when |
|
|
117
|
+
|---|---|---|---|
|
|
118
|
+
| **SFT** | demonstrations (chat/`messages` or prompt→completion) | base of everything | always first (except ORPO) |
|
|
119
|
+
| **DPO** ([2305.18290](https://arxiv.org/abs/2305.18290)) | paired `chosen`/`rejected` | after SFT | you have pairwise preferences; the workhorse aligner |
|
|
120
|
+
| **ORPO** ([2403.07691](https://arxiv.org/abs/2403.07691)) | paired preferences | **replaces** SFT+DPO (single stage, ref-free) | you want one pass from a base model and have pairs |
|
|
121
|
+
| **KTO** ([2402.01306](https://arxiv.org/abs/2402.01306)) | *unpaired* binary good/bad labels | after SFT | you have thumbs-up/down, not matched pairs |
|
|
122
|
+
| **GRPO** ([2402.03300](https://arxiv.org/abs/2402.03300); DeepSeek-R1 [2501.12948](https://arxiv.org/abs/2501.12948)) | a **reward function** (verifier), no pairs | after SFT | correctness is checkable (math/code/format) → RL for reasoning |
|
|
123
|
+
|
|
124
|
+
Rule of thumb: **have pairs → DPO** (or ORPO to fuse the two stages); **have only up/down votes → KTO**;
|
|
125
|
+
**can score an answer programmatically → GRPO**. Preference optimization uses a *tiny* learning rate.
|
|
126
|
+
|
|
127
|
+
```python
|
|
128
|
+
# DPO after SFT — dataset has prompt / chosen / rejected columns.
|
|
129
|
+
from trl import DPOTrainer, DPOConfig
|
|
130
|
+
trainer = DPOTrainer(
|
|
131
|
+
model="out", # your SFT checkpoint (or SFT+adapter)
|
|
132
|
+
args=DPOConfig(output_dir="dpo-out", beta=0.1, # beta = KL strength to the ref model
|
|
133
|
+
learning_rate=5e-7, max_length=1024,
|
|
134
|
+
precompute_ref_log_probs=True), # saves memory; ref model auto-created
|
|
135
|
+
train_dataset=pref_dataset,
|
|
136
|
+
peft_config=peft_config, # LoRA works for preference stages too
|
|
137
|
+
)
|
|
138
|
+
trainer.train()
|
|
139
|
+
```
|
|
140
|
+
|
|
141
|
+
```python
|
|
142
|
+
# GRPO — no preference pairs, a reward FUNCTION that returns a score per completion.
|
|
143
|
+
from trl import GRPOTrainer, GRPOConfig
|
|
144
|
+
def format_reward(completions, **kwargs): # signature: gets completions (+ dataset cols via kwargs)
|
|
145
|
+
return [1.0 if "\\boxed{" in c[0]["content"] else 0.0 for c in completions]
|
|
146
|
+
|
|
147
|
+
trainer = GRPOTrainer(
|
|
148
|
+
model="out",
|
|
149
|
+
reward_funcs=[format_reward], # one or many; GRPOConfig.reward_weights to combine
|
|
150
|
+
args=GRPOConfig(output_dir="grpo-out", num_generations=8, # group size per prompt
|
|
151
|
+
beta=0.04, learning_rate=1e-6, use_vllm=True), # vLLM speeds rollouts
|
|
152
|
+
train_dataset=prompts_dataset,
|
|
153
|
+
)
|
|
154
|
+
trainer.train()
|
|
155
|
+
```
|
|
156
|
+
|
|
157
|
+
Full runnable SFT→DPO and GRPO scripts, ORPO/KTO variants, dataset schemas, and adapter-merge steps
|
|
158
|
+
are in `references/methods.md`.
|
|
159
|
+
|
|
160
|
+
## Data — quality over quantity (LIMA)
|
|
161
|
+
|
|
162
|
+
More rows is not the win. **LIMA** ([arXiv:2305.11206](https://arxiv.org/abs/2305.11206)) got strong
|
|
163
|
+
instruction-following from **~1,000** carefully curated examples — "less is more for alignment."
|
|
164
|
+
A thousand clean, on-distribution, correctly-templated examples beat 100k scraped noisy ones, which
|
|
165
|
+
actively teach the model bad form. Building and validating that corpus (JSONL `messages`, preference
|
|
166
|
+
pairs, dedup, contamination checks) is `training-data` — bring it here already clean.
|
|
167
|
+
|
|
168
|
+
## Hyperparameters — the few that move the needle
|
|
169
|
+
|
|
170
|
+
- **LoRA `r` and `lora_alpha`**: `r` = adapter rank (capacity); effective scaling = `lora_alpha / r`.
|
|
171
|
+
Common heuristic **`alpha ≈ 2·r`** (e.g. r=16→alpha=32) so scaling ≈ 2; then adjust LR, not both.
|
|
172
|
+
Start `r=8–16` for style/format, higher (32–64+) for harder behavior. (Newer "LoRA-without-regret"
|
|
173
|
+
guidance favors `target_modules="all-linear"` + higher rank + tuned LR — verify current advice.)
|
|
174
|
+
- **`target_modules`**: `"all-linear"` is the safe default. Targeting too few / wrong-named modules
|
|
175
|
+
is a top silent failure — the run "succeeds," loss barely moves, the adapter learned ~nothing.
|
|
176
|
+
- **Learning rate**: LoRA/QLoRA SFT ~**1e-4–2e-4** (adapters tolerate higher LR than full FT, whose
|
|
177
|
+
~2e-5 is the `SFTConfig` default). Preference optimization is far lower — **DPO ~5e-7, GRPO ~1e-6**.
|
|
178
|
+
- **Epochs**: usually **1–3**. This is the overfitting knob — see below. Watch **eval** loss.
|
|
179
|
+
- **Batch × grad-accum**: raise the *effective* batch with `gradient_accumulation_steps` when VRAM
|
|
180
|
+
caps `per_device_train_batch_size`. Enable `packing=True` + `gradient_checkpointing` to fit more.
|
|
181
|
+
- **Warmup**: a short `warmup_ratio` (~0.03–0.1) stabilizes the early, high-gradient steps.
|
|
182
|
+
|
|
183
|
+
## Catastrophic forgetting
|
|
184
|
+
|
|
185
|
+
Fine-tuning on a narrow task can degrade general ability the base model had. Three mitigations,
|
|
186
|
+
cheapest first: **use LoRA/QLoRA** (base weights frozen — inherently gentler than full FT); **keep
|
|
187
|
+
the LR low and epochs few**; and **replay** — mix a slice of general instruction data into your
|
|
188
|
+
task data so the model doesn't forget how to be a general assistant. If a tuned model suddenly
|
|
189
|
+
"got dumber" at everything else, this is the usual cause.
|
|
190
|
+
|
|
191
|
+
## Evaluation — a held-out set and a task metric, not a vibe-check
|
|
192
|
+
|
|
193
|
+
A vibe-check is **not** an eval. Before training, split off a **held-out** set the model never sees,
|
|
194
|
+
and define a concrete task metric (exact-match / JSON-valid rate / rubric score / a task-specific
|
|
195
|
+
score). Judge the run on that, plus **eval loss**.
|
|
196
|
+
|
|
197
|
+
- **Watch eval loss, not train loss.** Train loss falling while **eval loss rises** = overfitting →
|
|
198
|
+
fewer epochs, lower LR, more/cleaner data, or earlier checkpoint. Train loss always keeps falling;
|
|
199
|
+
it tells you nothing about generalization.
|
|
200
|
+
- **Contamination**: if eval examples leaked into training, your metric is a lie. De-dup train vs
|
|
201
|
+
eval; keep the held-out set quarantined. (Corpus-side hygiene is `training-data`.)
|
|
202
|
+
- General LLM/agent eval harness and judging → `agent-eval`. Bring your task metric here.
|
|
203
|
+
|
|
204
|
+
## When NOT to fine-tune (anti-patterns)
|
|
205
|
+
|
|
206
|
+
| Anti-pattern | Why it breaks | Do instead |
|
|
207
|
+
|---|---|---|
|
|
208
|
+
| Fine-tune to add facts / fresh knowledge | Weights memorize poorly and go stale; hallucinations | `../rag/SKILL.md` — retrieve + ground |
|
|
209
|
+
| Fine-tune before trying prompt + few-shot | Slow, costly, irreversible for a prompt-solvable ask | `prompt-engineering` first |
|
|
210
|
+
| Wrong / too-few `target_modules` | Adapter has no capacity where it matters → learns ~nothing | `"all-linear"` (or correct proj names) |
|
|
211
|
+
| Judge success by train loss | Falls even while the model overfits | Held-out eval set + task metric + **eval** loss |
|
|
212
|
+
| Crank epochs "to learn it better" | Overfits, forgets, memorizes noise | 1–3 epochs; stop when eval loss turns up |
|
|
213
|
+
| Train with a wrong/absent chat template | Inference emits garbage / never stops | Match train template to serve; align `eos_token` |
|
|
214
|
+
| A few dozen examples for full FT | Not enough signal; unstable | Curate ~hundreds–thousands (LIMA) or use LoRA |
|
|
215
|
+
| Fine-tune a model you can't legally deploy | License blocks your use case | Check the model card first → `open-weights` |
|
|
216
|
+
|
|
217
|
+
## Related skills
|
|
218
|
+
|
|
219
|
+
- **`../rag/SKILL.md`** — the fork of the decision gate: facts/freshness/citations live there;
|
|
220
|
+
form/behavior lives here. Most "make it behave" asks are RAG or prompting, not training.
|
|
221
|
+
- **`prompt-engineering`** — the cheaper lever to exhaust before spending a GPU.
|
|
222
|
+
- **`training-data`** — builds/validates the JSONL `messages` and preference-pair corpus you feed
|
|
223
|
+
here (LLM corpora, NOT tabular cleaning — that is `data-cleaning`).
|
|
224
|
+
- **`open-weights`** — chooses *which* base model by task/size/license; you consume that choice.
|
|
225
|
+
- **`../unsloth/SKILL.md`** — a fast single-GPU training backend + GGUF export; same LoRA/QLoRA
|
|
226
|
+
concepts, one optimized implementation. This skill stays backend-agnostic.
|
|
227
|
+
- **`huggingface`** — download the base, push the adapter/merged model, host inference (NOT training).
|
|
228
|
+
- **`../vllm/SKILL.md`** — serves the trained/merged model (adapter hot-swap, throughput flags).
|
|
229
|
+
|
|
230
|
+
## Checklist
|
|
231
|
+
|
|
232
|
+
- [ ] Ran the decision gate: confirmed this is a form/behavior need, not a facts need (else → rag).
|
|
233
|
+
- [ ] Chose base model by license + size (→ `open-weights`); read the actual model card.
|
|
234
|
+
- [ ] Picked method: QLoRA by default; full FT only with the hardware + a reason.
|
|
235
|
+
- [ ] Data is clean, on-distribution, correctly templated (→ `training-data`); dedup vs eval.
|
|
236
|
+
- [ ] Chat template applied at train time and it **matches** the serving template; `eos_token` aligned.
|
|
237
|
+
- [ ] `target_modules="all-linear"` (or verified names); `alpha ≈ 2·r`; LoRA LR ~1e-4–2e-4.
|
|
238
|
+
- [ ] Held-out eval set + a concrete task metric defined **before** training.
|
|
239
|
+
- [ ] Trained 1–3 epochs; watched **eval** loss (not train) for the overfitting turn.
|
|
240
|
+
- [ ] Preference stage only if needed; correct method for the data (pairs→DPO/ORPO, votes→KTO, verifier→GRPO); tiny LR.
|
|
241
|
+
- [ ] Verified `trl`/`peft`/`transformers` current majors and import paths at author time.
|
|
242
|
+
|
|
243
|
+
See `references/methods.md` for full SFT→DPO/GRPO/ORPO/KTO scripts, dataset schemas, and adapter
|
|
244
|
+
merging; `references/hyperparameters-and-eval.md` for the tuning + forgetting + evaluation playbook.
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
# finetuning evals — how to run
|
|
2
|
+
|
|
3
|
+
Routing and capability checks, not unit tests. Run the `should_trigger` prompts against your skill
|
|
4
|
+
router and confirm `finetuning` fires (form/behavior adaptation, method choice, pipeline, and the
|
|
5
|
+
overfit/forgetting/target_modules diagnostics). Run `should_not_trigger` and confirm the router
|
|
6
|
+
defers to the named sibling instead (`rag` for facts, `prompt-engineering` for the cheaper lever,
|
|
7
|
+
`open-weights` for base-model choice, `training-data` for corpus building, `vllm` for serving,
|
|
8
|
+
`unsloth` for the fast single-GPU backend) — a miss there means the boundary in the description
|
|
9
|
+
needs sharpening. For the `capability` case, hand the scenario to an agent with this skill loaded
|
|
10
|
+
and grade the answer against each `must_include` bullet pass/fail: the decision gate (form vs
|
|
11
|
+
facts), QLoRA + TRL/PEFT current API, the alpha≈2r and LR/epoch hyperparameters, the chat-template
|
|
12
|
+
guardrail, LIMA quality-over-quantity, held-out eval watching eval loss, KTO for unpaired feedback,
|
|
13
|
+
and the version/license hedge.
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
skill: finetuning
|
|
2
|
+
|
|
3
|
+
should_trigger:
|
|
4
|
+
- prompt: "We want Qwen to always answer in our brand voice and emit a fixed JSON schema — fine-tune it on ~2k of our examples."
|
|
5
|
+
why: A form/behavior adaptation (tone + output format) with demonstrations — the core SFT use case finetuning owns.
|
|
6
|
+
- prompt: "Should I use LoRA, QLoRA, or full fine-tuning to adapt an 8B model on a single 24GB GPU?"
|
|
7
|
+
why: The memory/quality method choice (LoRA vs QLoRA vs full FT) is squarely this skill's decision.
|
|
8
|
+
- prompt: "I ran SFT and now want to prefer the better of two answers — set up DPO after it with our chosen/rejected pairs."
|
|
9
|
+
why: SFT → preference optimization pipeline; picking DPO for paired preference data is finetuning's job.
|
|
10
|
+
- prompt: "My fine-tune's train loss keeps dropping but eval loss is climbing and it forgot general chat — what's wrong?"
|
|
11
|
+
why: Overfitting (watch eval not train loss) plus catastrophic forgetting — both are finetuning diagnostics.
|
|
12
|
+
- prompt: "My LoRA run finished but the adapter barely changed anything — did I set target_modules wrong?"
|
|
13
|
+
why: The classic silent failure (wrong/too-few target_modules → adapter learns ~nothing) lives here.
|
|
14
|
+
- prompt: "Correctness is checkable for our math tasks — write a GRPO reward function to RL the model toward right answers."
|
|
15
|
+
why: GRPO with a reward function for a verifiable task is a finetuning preference-optimization method.
|
|
16
|
+
- prompt: "Ajustar un model Qwen amb LoRA amb les nostres dades perquè segueixi el nostre estil."
|
|
17
|
+
why: Catalan — LoRA fine-tuning to teach a house style is a form/behavior adaptation this skill owns.
|
|
18
|
+
|
|
19
|
+
should_not_trigger:
|
|
20
|
+
- prompt: "The bot needs to answer from our latest policy PDFs and cite them — it keeps giving stale info."
|
|
21
|
+
route_to: rag
|
|
22
|
+
why: Facts/freshness/citations are supplied by retrieval, not baked into weights — fine-tuning teaches form, not facts.
|
|
23
|
+
- prompt: "The prompt works sometimes; can I get consistent JSON with a few-shot example instead of training?"
|
|
24
|
+
route_to: prompt-engineering
|
|
25
|
+
why: The cheaper, reversible lever to exhaust before spending a GPU; no training needed.
|
|
26
|
+
- prompt: "Which open model should I pick by license and size for commercial use — Llama vs Qwen vs Mistral?"
|
|
27
|
+
route_to: open-weights
|
|
28
|
+
why: Base-model selection by license/size/task is the choice layer feeding finetuning, not the training method.
|
|
29
|
+
- prompt: "Build and dedup our instruction JSONL and preference pairs corpus and check for contamination."
|
|
30
|
+
route_to: training-data
|
|
31
|
+
why: Constructing/validating the training corpus is training-data; finetuning consumes an already-clean corpus.
|
|
32
|
+
- prompt: "Run our fine-tuned model as a high-throughput API with batching and adapter hot-swapping."
|
|
33
|
+
route_to: vllm
|
|
34
|
+
why: Serving the trained model (throughput, adapter hot-swap) is vllm, not the training discipline.
|
|
35
|
+
- prompt: "Give me the fastest single-GPU way to fine-tune and export a GGUF for llama.cpp."
|
|
36
|
+
route_to: unsloth
|
|
37
|
+
why: A specific fast single-GPU backend plus GGUF export is unsloth; finetuning stays backend-agnostic.
|
|
38
|
+
|
|
39
|
+
capability:
|
|
40
|
+
- scenario: "A team wants an 8B open model to consistently reply in their support tone and always return a fixed JSON envelope, on one 24GB GPU. They have ~1,500 curated examples and later some thumbs-up/down feedback. Design the approach end to end."
|
|
41
|
+
must_include:
|
|
42
|
+
- Applies the decision gate and confirms this is a form/behavior task (tone + format), explicitly contrasting it with RAG (facts) and prompting.
|
|
43
|
+
- Chooses QLoRA (4-bit NF4 base + LoRA adapters, arXiv 2305.14314) as the memory-efficient default for a single 24GB GPU.
|
|
44
|
+
- Uses TRL SFTTrainer with an SFTConfig and a PEFT LoraConfig, passing peft_config (and quantization_config for QLoRA); target_modules="all-linear".
|
|
45
|
+
- States LoRA hyperparameters: r/alpha with the alpha≈2r heuristic and a LoRA-appropriate learning rate (~1e-4–2e-4), 1–3 epochs.
|
|
46
|
+
- Warns that the chat template at train time must match serving and eos_token must be aligned, or inference outputs garbage.
|
|
47
|
+
- Notes the ~1,500 curated examples fit LIMA's quality-over-quantity finding (2305.11206) and routes corpus building to training-data.
|
|
48
|
+
- Defines evaluation on a held-out set with a task metric and says to watch EVAL loss (not train loss) for overfitting, plus contamination check.
|
|
49
|
+
- For the later thumbs-up/down feedback, recommends KTO (unpaired binary preference) rather than DPO (which needs paired chosen/rejected).
|
|
50
|
+
- Hedges that trl/peft/transformers versions and import paths (and model licenses) must be verified at author time as they change frequently.
|