Domain SFT and forgetting measurement
Build an instruction dataset for a domain from public sources, such as explaining and classifying software weaknesses from the CWE catalog and public advisories in Spanish; filter and deduplicate it against evaluation and fine-tune with LoRA or QLoRA. A small hyperparameter sweep measures domain gain and forgetting on general tasks.
After this lesson you can
- Build an SFT dataset from public sources with quality filtering and deduplication against evaluation.
- Fine-tune with assistant-only loss, packing and the model's chat template.
- Sweep learning rate, rank and target modules with domain and general evaluation.
- Quantify forgetting and select a configuration using a criterion declared in advance.
Before you start
Teach a specialty without erasing everything else
A security analyst receives advisories like this every day: “Off-by-one error allows remote attackers to cause a denial of service and possibly execute arbitrary code via requests that do not contain newlines.” The work begins by naming the root cause in the industry’s shared vocabulary, MITRE’s CWE (Common Weakness Enumeration) catalog: here, CWE-193, an off-by-one error. That name determines who gets the fix, which quality control was missing, and how statistics are aggregated. The Qwen2.5-0.5B-Instruct selected in p08-l01 knows the format CWE-<número>, but fills it almost at random: in the first version of this lesson, with 106 possible weaknesses, it got 0 out of 117 development advisories right.
Domain instruction tuning (SFT, supervised fine-tuning) is the tool for this: a few thousand task-specific instruction–response pairs, cross-entropy loss over the answers, and a LoRA adapter. The hard part is not the training loop, which you already wrote in p08-l02 and p08-l03. It is three questions the loop does not answer:
- Where do the data come from, and what cannot be used? Licenses, confidentiality, labels leaking into inputs, and examples that also appear in evaluation.
- How do I choose a configuration without fooling myself? If you try twelve combinations and keep the one scoring best on the test, the test stops measuring.
- What have I lost? Tuning to a narrow domain can degrade general capabilities: catastrophic forgetting. Measure it as carefully as the gain.
The third question has a well-documented empirical answer. Biderman and colleagues (2024) compared LoRA with full fine-tuning of Llama-2-7B on code and mathematics and summarized the result in their title: LoRA learns less and forgets less. This is the learning–forgetting tradeoff, and it is easier to see than to describe.
What you should see in the published data:
- Each trajectory moves down and left as epochs increase. In code, full fine-tuning drops from an average 59.5% retained on HellaSwag, ARC-Challenge and WinoGrande after one epoch to 41.4% after sixteen; rank-16 LoRA drops from 65.3% to 60.9%. More passes over the same data buy little domain performance and cost substantial generality.
- In code, the frontier consists only of LoRA points (rank 256 at two and four epochs, and rank 64 at four). Full fine-tuning reaches 49.7% on HumanEval at eight epochs while retaining 44.6%; rank-256 LoRA reaches 49.8% at four epochs while retaining 63.1%.
- In mathematics, full fine-tuning does enter the frontier at the greater-domain-performance end (64.2% on GSM8K at four epochs), and LoRA occupies the higher-retention end. No sixteen-epoch point lies on the frontier in either domain.
The frontier does not choose for you: it says which configurations are reasonable, not which you prefer. Choosing requires a rule, and that rule must be fixed before seeing the results. This lesson builds what you need to do that for your own domain: the dataset, training, sweep and forgetting measurement.
The domain and its sources
The task
Besides a description, each CWE catalog entry contains a list of observed examples: published vulnerabilities (with CVE identifiers) and a sentence describing them. These are ideal classification material: real advisory text and a label assigned by the MITRE team. The lesson’s task is:
Given advisory text and four candidate weaknesses, answer with the correct CWE identifier.
Why candidates? The first version was open-ended: the model had to write an identifier from 106 possibilities. The base model got 0 of 117 development advisories correct, and after one fine-tuning epoch with about eight examples per class, no configuration exceeded 5 of 117. With so few examples per class, a 0.5B model does not learn 106 arbitrary text-to-number mappings; it learns to write the format. Candidates turn this into the task real tools perform after retrieval: choosing among the few entries a search engine considers plausible. It remains verifiable because the answer is an identifier compared with the label, and difficult because the three false candidates are not random: they are the entries whose names and descriptions share the most words with the correct one.
Two baselines establish the scale before training. Random choice gets 25% correct. Choosing the candidate sharing the most words with the advisory, without any model, gets 52.1% on development. A tuned model that does not beat the second has learned nothing a Python set could not do.
Licenses, provenance and what must not be used
The source here is version 5.0 of the catalog, a 2.1 MB zip that the cell downloads and verifies by its SHA-256 fingerprint. Its terms of use say CWE is free to use for research, development and commercial purposes under a free, nonexclusive license, provided MITRE’s copyright designation and the license itself are reproduced in any copy. In practice, include that notice in the dataset card if you publish the derivative dataset. Observed examples are included in the catalog; if you add full NVD descriptions or vendor advisories, each source has its own terms that must be reviewed separately.
Accessibility does not mean permission to use something. Before adding a source, review this list:
- Customer or internal data: never use them in an experimental model. Audit reports, tickets, customer code or findings from an ongoing assessment are confidential even on your own disk. A fine-tuned model may reproduce training fragments verbatim, and an adapter is much easier to copy and share than a protected folder.
- Licenses with obligations. CC BY-SA content (such as Stack Overflow answers) requires attribution and sharing derivatives under the same license; some forums and blogs explicitly prohibit reuse.
- Outputs from restrictively licensed models. If you generate instructions with a model, its license governs use of the generated material. Qwen2.5-3B-Instruct, used in p08-l03, has a research license; Qwen2.5-1.5B-Instruct and the 0.5B are Apache-2.0.
- Exploit code. Classifying weaknesses does not require working proofs of concept or payloads, and training on them teaches their production. The catalog describes mechanisms and mitigations: that is the appropriate level of detail for a triage assistant.
- Evaluation sets. Neither this lesson’s test nor the general-task tests may appear in training, even paraphrased. The next section turns that into code.
Build the instructions
The training set mixes three types of instructions, all derived from the catalog:
- Classify: an observed training-split example with four candidates; the answer is
CWE-<número>. Three different wording templates are used, and the test uses a fourth absent from training, so it measures the task rather than memory of a specific phrase. - Definition: a weakness’s official description; the answer is its identifier.
- Name: an identifier; the answer is the entry’s official title.
Four curation choices, all visible in the cell, change what the model learns (SFT data curation applied to a concrete case):
- The label cannot appear in the input. 370 observed-example descriptions mention a CWE identifier in the text, usually in cause-and-effect chains (“does not use the Secure flag (CWE-614) or HTTPOnly security attribute (CWE-1004)”), and 264 include the entry’s own label. If left in, the model learns to copy the number and mentions of other entries reveal candidates. The cell removes any
CWE-<número>mention from the advisory text. - Only labels MITRE recommends using. Each entry carries usage notes for classifying vulnerabilities:
Allowed,Allowed-with-Review,DiscouragedorProhibited. CWE-20 (improper input validation) has 42 observed examples but its use is discouraged because it is too broad. The label set comprises the 106 weaknesses with at least eight examples and allowed usage. - One answer per text. An advisory may appear under several weaknesses (for example a class and its variant). On the test, any of them counts as correct; in training, the answer is the most specific according to the catalog hierarchy (variant before base, base before class), so the same question is not taught with two different answers.
- Short, verifiable answers. Classification responses are identifiers; no explanations that the small model could learn to imitate without understanding.
Generation assisted by a local model
The three types above teach classification, but not explanation. That would require Spanish answers written for the domain, while the catalog is in English. The standard approach is Self-Instruct: a model generates instructions and answers from a few seeds, and a filter decides what enters. Wang and colleagues started with 175 handwritten tasks, generated 52,445 instructions with GPT-3 and accepted a new instruction only if its ROUGE-L similarity to all previous ones was below 0.7. Their manual review of 200 random examples measures the risk: 92% described a valid task, but only 58% had a correct answer and 54% were valid in all fields (this is model-generated instructions).
The assisted-generation cell applies this idea using a local Apache-2.0 model: for each weakness it requests a brief Spanish explanation from the official description and applies five automatic filters (length, whether it looks like Spanish, no code or attack strings, no mention of another CWE, and no evaluation overlap). Proposals are written to explicaciones_para_revisar.jsonl with the aprobada field empty. Only those a person marks as approved in explicaciones_revisadas.jsonl enter training: 58% correct answers is too low to train without review.
Split before filtering
Order matters: freeze evaluation first, then build training and filter against it. But how should you split? The natural choice is by CVE: each vulnerability goes entirely to training, development or test. That fails. The catalog reuses the same sentence for different vulnerabilities (“Alternate data streams for NTFS files are not cleared when files are wiped,” for example, describes five CVEs), and splitting by CVE leaves 29 evaluation texts identical to a training text. The model would answer them from memory, and the measured gain would partly be leakage.
The solution is to define groups using all keys that can leak information at once.
Proof
Every example is an edge of , so CVE and text are in the same component , and the example goes to the split of . If a CVE appeared in two splits, there would be two examples and in components assigned to different splits; but both contain node , so they are in the same component, a contradiction. The argument is identical for a text shared by two CVEs.
∎The cell constructs components using union-find, which computes them in near-linear time, and assigns each component using a hash of its smallest CVE: the split is deterministic and independent of seeds or file order. The proposition guarantees no leakage by exact key. Approximate leakage (the same advisory with different capitalization, an added prefix, a paraphrase) needs a second filter that compares content.
What each filter sees
There are three common comparisons, from strictest to loosest, and it helps to know what each detects (exact deduplication and approximate deduplication):
- Exact match after normalization. Lowercase, words only, and compare the entire sequence. Detects copies and nothing else.
- Shared n-grams. A training example is discarded if it shares a sequence of consecutive words with an evaluation text. GPT-3’s contamination analysis popularized : long enough that a chance match is rare in natural text.
- Jaccard similarity between shingles. Each text becomes the set of its groups of 5 consecutive words and is measured. This detects nearly identical texts even when they share no long sequence. For millions of documents it is approximated with MinHash; here direct calculation is enough.
The six pairs summarize possible failures. A nine-word text contains no 13-gram: the n-gram filter is blind to short leaks, which only exact comparison and Jaccard see. A prefix (“Chain:”) is enough for exact matching to fail and the common sequence to shrink to eleven words; only Jaccard catches that. At the other extreme, the NVD phrase “allows remote attackers to cause a denial of service and possibly execute arbitrary code via” has fifteen words: with , the filter discards a legitimate advisory about another weakness solely because it shares the stock phrase. Lowering increases false positives; raising it increases false negatives. The cell combines all three rules and logs what each discards.
No text filter resolves two problems. Paraphrases (the same flaw described in different words) require semantic deduplication: embeddings, nearest neighbors and human review of borderline cases. Pretraining contamination cannot be filtered out: the CWE catalog and CVE descriptions have been public for years and are likely present in Qwen’s training data. The protocol does guarantee that the difference between base and fine-tuned models is not due to seeing the test during SFT; both absolute scores may be equally inflated (benchmark contamination).
The next cell downloads the catalog, builds labels, splits by component and freezes development and test with their fingerprint. It needs no GPU. If you set P08_L04_DIR to an absolute path before starting the lab, it saves the zip, tests and everything generated by subsequent cells there; if the frozen test in that directory differs from the newly calculated one, it refuses to continue.
import collections, hashlib, io, json, os, re, tempfile, urllib.request, zipfile
import xml.etree.ElementTree as ET
from pathlib import Path
CWE_URL = 'https://cwe.mitre.org/data/xml/cwec_v5.0.xml.zip'
CWE_SHA256 = 'bcda44c9abf61ff977f50c3c6649eea5a97a7b0626b0396c2c3ec4bfb973a3dc'
NS = {'c': 'http://cwe.mitre.org/cwe-8'}
def lab_dir():
value = os.environ.get('P08_L04_DIR')
if not value:
return None
path = Path(value)
if not path.is_absolute():
raise ValueError('P08_L04_DIR debe ser una ruta absoluta')
path.mkdir(parents=True, exist_ok=True)
return path
LAB = lab_dir()
zip_path = (LAB or Path(tempfile.gettempdir())) / 'cwec_v5.0.xml.zip'
if not zip_path.is_file():
zip_path.write_bytes(urllib.request.urlopen(CWE_URL, timeout=60).read())
raw = zip_path.read_bytes()
if hashlib.sha256(raw).hexdigest() != CWE_SHA256:
raise ValueError('El zip descargado no es la versión 5.0 fijada')
with zipfile.ZipFile(io.BytesIO(raw)) as z:
root = ET.fromstring(z.read('cwec_v5.0.xml'))
def flat(el):
return ' '.join(''.join(el.itertext()).split()) if el is not None else ''
catalog = {}
for w in root.findall('c:Weaknesses/c:Weakness', NS):
if w.get('Status') == 'Deprecated':
continue
catalog[int(w.get('ID'))] = {
'name': w.get('Name'), 'abstraction': w.get('Abstraction'),
'usage': w.findtext('c:Mapping_Notes/c:Usage', default='', namespaces=NS).strip(),
'description': flat(w.find('c:Description', NS)),
'observed': [(o.findtext('c:Reference', namespaces=NS).strip(), flat(o.find('c:Description', NS)))
for o in w.findall('c:Observed_Examples/c:Observed_Example', NS)]}
del root
WORD = re.compile(r'\w+', re.UNICODE)
def words(s):
return WORD.findall(s.casefold())
def norm(s):
return ' '.join(words(s))
LEAK = re.compile(r'\s*\(?\bCWE-\d+\)?', re.IGNORECASE)
observed, leaked = [], 0
for cid, entry in catalog.items():
for ref, text in entry['observed']:
clean = ' '.join(LEAK.sub('', text).split())
leaked += clean != text
if len(words(clean)) >= 4:
observed.append((ref, clean, cid))
counts = collections.Counter(cid for _, _, cid in observed)
LABELS = sorted(c for c, n in counts.items()
if n >= 8 and catalog[c]['usage'] in ('Allowed', 'Allowed-with-Review'))
observed = [o for o in observed if o[2] in LABELS]
# Grupos: dos ejemplos van juntos si comparten CVE o texto normalizado (unión y búsqueda).
parent = {}
def find(x):
parent.setdefault(x, x)
while parent[x] != x:
parent[x] = parent[parent[x]]
x = parent[x]
return x
for ref, text, _ in observed:
parent[find(('cve', ref))] = find(('txt', norm(text)))
def bucket(key):
return int(hashlib.sha256(('p08-l04|' + key).encode()).hexdigest(), 16) % 100
def split_of(b):
return 'test' if b < 20 else 'dev' if b < 30 else 'train'
members = collections.defaultdict(list)
for ref, text, cid in observed:
members[find(('cve', ref))].append((ref, text, cid))
SPECIFIC = {'Variant': 0, 'Base': 1, 'Compound': 1, 'Class': 2, 'Pillar': 3}
rows = {'train': {}, 'dev': {}, 'test': {}}
for group in members.values():
split = split_of(bucket(min(ref for ref, _, _ in group)))
for ref, text, cid in group:
row = rows[split].setdefault(norm(text), {'text': text, 'refs': set(), 'gold': set()})
row['refs'].add(ref); row['gold'].add(cid)
# Comparación: partir solo por CVE deja textos idénticos a ambos lados.
naive = {'train': set(), 'eval': set()}
for ref, text, _ in observed:
naive['eval' if bucket(ref) < 30 else 'train'].add(norm(text))
print(f'catálogo CWE 5.0: {len(catalog)} debilidades vigentes; {len(LABELS)} clases con 8 o más ejemplos y uso permitido')
print(f'descripciones que citan algún CWE (se borra la mención): {leaked}')
print(f'partición ingenua por CVE: {len(naive["train"] & naive["eval"])} textos de evaluación idénticos a uno de entrenamiento')
# Cuatro candidatas: la correcta y las tres entradas de la lista más parecidas (Jaccard de palabras
# del nombre y la descripción). Son distractores difíciles y fijos, no elegidos al azar.
VOCAB = {c: {w for w in words(catalog[c]['name'] + ' ' + catalog[c]['description']) if len(w) > 3} for c in LABELS}
def options(key, gold, target):
near = sorted((c for c in LABELS if c not in gold),
key=lambda c: (-len(VOCAB[c] & VOCAB[target]) / len(VOCAB[c] | VOCAB[target]), c))[:3]
return sorted([target, *near], key=lambda c: hashlib.sha256(f'{key}|{c}'.encode()).hexdigest())
def listing(opts):
return '\n'.join(f'- CWE-{c}: {catalog[c]["name"]}' for c in opts)
EVAL_TEMPLATE = ('Clasifica la debilidad de software que describe este aviso de seguridad. Elige una de las '
'candidatas y responde solo con su identificador.\n\nAviso: {text}\n\nCandidatas:\n{options}')
def most_specific(gold):
return min(gold, key=lambda c: (SPECIFIC.get(catalog[c]['abstraction'], 4), c))
def frozen(split):
out = []
for key in sorted(rows[split]):
r = rows[split][key]
opts = options(key, r['gold'], most_specific(r['gold']))
out.append({'id': min(r['refs']), 'refs': sorted(r['refs']), 'text': r['text'], 'options': opts,
'prompt': EVAL_TEMPLATE.format(text=r['text'], options=listing(opts)), 'gold': sorted(r['gold'])})
return out
def sha(obj):
return hashlib.sha256(json.dumps(obj, ensure_ascii=False, sort_keys=True, separators=(',', ':')).encode()).hexdigest()
dev, test = frozen('dev'), frozen('test')
def lexical(r): # línea base sin modelo: la candidata que comparte más palabras con el aviso
w = {x for x in words(r['text']) if len(x) > 3}
return max(r['options'], key=lambda c: (len(w & VOCAB[c]) / max(1, len(w | VOCAB[c])), -c))
print(f'desarrollo: {len(dev)} avisos, prueba: {len(test)} avisos, entrenamiento: {len(rows["train"])} textos')
print(f'líneas base en desarrollo: azar 0.25 · candidata con más palabras en común '
f'{sum(lexical(r) in r["gold"] for r in dev) / len(dev):.3f}')
print('huella de desarrollo:', sha(dev)[:16], '· huella de prueba:', sha(test)[:16])
if LAB:
for name, data in (('dev', dev), ('test', test)):
path = LAB / f'{name}.json'
if path.is_file() and sha(json.loads(path.read_text(encoding='utf-8'))) != sha(data):
raise ValueError(f'{path} existe y es distinto: el examen congelado ha cambiado')
path.write_text(json.dumps(data, ensure_ascii=False, indent=1), encoding='utf-8')npm run lab and open the connection link.The second cell builds instructions and applies, in order, exact deduplication, the 13-gram filter with normalized exact matching, and Jaccard to evidence texts, not the full instruction: the template adds words that would obscure overlap. Look at the third discard it prints: it is a false positive. It shares its first fourteen normalized words with a development advisory for another weakness (reachable assertion, CWE-617, versus null pointer dereference, CWE-476): “Chat client allows remote attackers to cause a denial of service (crash) via a”, the product type plus another variant of the NVD stock phrase. Losing it is accepted: with the rule fixed in advance, one fewer example costs little and a leak invalidates the test.
TRAIN_TEMPLATES = [
'¿Qué CWE describe mejor esta vulnerabilidad publicada? Contesta solo con el identificador.\n\n{text}\n\nOpciones:\n{options}',
'Eres analista de seguridad. Asigna a este aviso una de estas debilidades (solo el identificador):\n{options}\n\nAviso: {text}',
'Aviso: {text}\n\nCausa raíz, entre:\n{options}\n\nIdentificador CWE:',
]
candidates = []
for i, key in enumerate(sorted(rows['train'])):
r = rows['train'][key]
target = most_specific(r['gold'])
opts = listing(options(key, r['gold'], target))
candidates.append({'id': f'cls-{min(r["refs"])}', 'kind': 'clasificar', 'evidence': r['text'],
'prompt': TRAIN_TEMPLATES[i % 3].format(text=r['text'], options=opts), 'answer': f'CWE-{target}'})
for c in LABELS:
e = catalog[c]
candidates.append({'id': f'def-{c}', 'kind': 'definición', 'evidence': e['description'],
'prompt': f'¿Qué entrada del catálogo CWE corresponde a esta descripción?\n\n{e["description"]}',
'answer': f'CWE-{c}'})
candidates.append({'id': f'nom-{c}', 'kind': 'nombre', 'evidence': e['name'],
'prompt': f'¿Cómo se titula la entrada CWE-{c} del catálogo de MITRE?', 'answer': e['name']})
def ngrams(tokens, n):
return {tuple(tokens[i:i + n]) for i in range(len(tokens) - n + 1)}
def decontaminate(train, evaluation, n=13):
held = [tuple(words(t)) for t in evaluation]
exact = set(held)
banned = set().union(*(ngrams(t, n) for t in held))
keep = []
for text in train:
t = tuple(words(text))
if t not in exact and not ngrams(t, n) & banned:
keep.append(text)
return keep
eval_texts = [r['text'] for r in dev + test]
allowed = set(decontaminate([c['evidence'] for c in candidates], eval_texts, 13))
removed = [c for c in candidates if c['evidence'] not in allowed]
train = [c for c in candidates if c['evidence'] in allowed]
def shingles(s, k=5):
t = words(s)
return ngrams(t, k) if len(t) >= k else {tuple(t)}
eval_sh = [shingles(t) for t in eval_texts]
near = []
for c in train:
s = shingles(c['evidence'])
j, k = max((len(s & e) / len(s | e), k) for k, e in enumerate(eval_sh))
if j >= 0.5:
near.append((round(j, 2), c['evidence'], eval_texts[k]))
near_texts = {a for _, a, _ in near}
train = [c for c in train if c['evidence'] not in near_texts]
print(f'candidatas: {len(candidates)} · descartadas por 13-gramas o coincidencia exacta: {len(removed)}'
f' · por casi duplicado: {len(near_texts)} · quedan: {len(train)}')
for c in removed[:3]:
print(' descartada:', c['evidence'][:110])
print(f'casi duplicados que el filtro de 13-gramas deja pasar (Jaccard de 5-shingles >= 0.5), también fuera: {len(near)}')
for j, a, b in near[:3]:
print(f' {j}: «{a[:70]}» / «{b[:70]}»')
print('composición:', dict(collections.Counter(c['kind'] for c in train)))
if LAB:
(LAB / 'train.json').write_text(json.dumps(train, ensure_ascii=False, indent=1), encoding='utf-8')npm run lab and open the connection link.import re
def decontaminate(train, evaluation, n=13):
return list(train)Assisted generation is optional and requires a GPU. Enable it with P08_L04_ASSIST=1; P08_L04_ASSIST_MODEL selects the generator (default Qwen2.5-1.5B-Instruct, about 3 GB to download) and P08_L04_ASSIST_N limits how many weaknesses are processed. To incorporate explanations, copy explicaciones_para_revisar.jsonl to explicaciones_revisadas.jsonl, read them one by one and set "aprobada": true only on correct ones. The cell filters approved proposals again before adding them.
SPANISH = {'de', 'la', 'el', 'que', 'en', 'los', 'las', 'una', 'un', 'se', 'por', 'con', 'para', 'del', 'es', 'no', 'al', 'lo', 'como', 'su'}
def assist_problems(text, cid, truncated=False):
w = words(text)
problems = ['cortada por el límite de tokens'] if truncated else []
if not 25 <= len(w) <= 140:
problems.append('longitud')
if sum(x in SPANISH for x in w) / max(1, len(w)) < 0.15:
problems.append('no parece español')
if re.search(r'```|<script|/etc/passwd|\bunion\s+select\b', text, re.IGNORECASE):
problems.append('código o cadena de ataque')
if any(int(m) != cid for m in re.findall(r'CWE-(\d+)', text)):
problems.append('cita otro CWE')
if not decontaminate([text], eval_texts, 13):
problems.append('solapa con la evaluación')
return problems
if os.environ.get('P08_L04_ASSIST') == '1':
import gc, torch
from transformers import AutoModelForCausalLM, AutoTokenizer
if not LAB:
raise ValueError('Define P08_L04_DIR para guardar las propuestas')
gen_name = os.environ.get('P08_L04_ASSIST_MODEL', 'Qwen/Qwen2.5-1.5B-Instruct')
n_assist = int(os.environ.get('P08_L04_ASSIST_N', str(len(LABELS))))
gen_rev = os.environ.get('P08_L04_ASSIST_REVISION') # fija la revisión exacta del generador
gtok = AutoTokenizer.from_pretrained(gen_name, revision=gen_rev)
gen = AutoModelForCausalLM.from_pretrained(gen_name, revision=gen_rev, dtype=torch.bfloat16,
device_map='cuda', low_cpu_mem_usage=True)
proposals = []
for c in LABELS[:n_assist]:
e = catalog[c]
ask = (f'Explica en español, en dos o tres frases y sin código, qué es la debilidad CWE-{c} ({e["name"]}) '
f'y cómo se previene. Descripción oficial: {e["description"]}')
text = gtok.apply_chat_template([{'role': 'user', 'content': ask}], add_generation_prompt=True, tokenize=False)
enc = gtok(text, return_tensors='pt', add_special_tokens=False).to('cuda')
with torch.no_grad():
out = gen.generate(**enc, max_new_tokens=180, do_sample=False, pad_token_id=gtok.eos_token_id)
new = out[0, enc['input_ids'].shape[1]:]
answer = gtok.decode(new, skip_special_tokens=True).strip()
truncated = len(new) == 180 and int(new[-1]) not in (gtok.eos_token_id, gtok.convert_tokens_to_ids('<|im_end|>'))
proposals.append({'cwe': c, 'generador': gen_name, 'revisión': gen_rev, 'respuesta': answer,
'problemas': assist_problems(answer, c, truncated), 'aprobada': None})
del gen; gc.collect(); torch.cuda.empty_cache()
with (LAB / 'explicaciones_para_revisar.jsonl').open('w', encoding='utf-8') as f:
for p in proposals:
f.write(json.dumps(p, ensure_ascii=False) + '\n')
passed = [p for p in proposals if not p['problemas']]
print(f'{gen_name}: {len(passed)} de {len(proposals)} propuestas pasan los filtros automáticos')
for p in proposals:
print(f" CWE-{p['cwe']} · problemas: {', '.join(p['problemas']) or 'ninguno'} · {' '.join(p['respuesta'].split())[:150]}")
reviewed = LAB / 'explicaciones_revisadas.jsonl' if LAB else None
if reviewed and reviewed.is_file():
extra = [json.loads(line) for line in reviewed.read_text(encoding='utf-8').splitlines() if line.strip()]
extra = [p for p in extra if p.get('aprobada') is True and not assist_problems(p['respuesta'], p['cwe'])]
train += [{'id': f"exp-{p['cwe']}", 'kind': 'explicación', 'evidence': p['respuesta'],
'prompt': f"Explica en español la debilidad CWE-{p['cwe']} y cómo se previene.", 'answer': p['respuesta']}
for p in extra]
print('explicaciones revisadas y aprobadas que entran en el entrenamiento:', len(extra))
else:
print('Sin explicaciones revisadas: el entrenamiento usa solo instrucciones derivadas del catálogo.')npm run lab and open the connection link.To check the cell end to end, the short run used Qwen2.5-0.5B-Instruct itself as generator for four weaknesses (CWE-22, 23, 36 and 41). All four proposals are fluent Spanish and contain no code. Three are cut off at the 180-token limit, which a filter detects. The one that passes all filters, for CWE-23, says the attacker accesses files “inside a restricted environment,” when the issue is precisely leaving it. The others would not withstand review either: CWE-22 calls the weakness “malicious behavior in the software,” when it is a defect an attacker exploits; CWE-36 recommends treating “input commands as text inputs rather than HTTP requests,” unrelated to the weakness; CWE-41 proposes “implementing larger data blocks.” Automatic filters remove obvious garbage; technical correctness can only be checked by someone who knows the subject. A larger generator increases the proportion of useful proposals, but review remains mandatory.
SFT loss: template, mask and packing
An SFT example is a dialogue serialized with the model’s chat template: a sequence of tokens, of which a subset are tokens written by the assistant. Loss is cross-entropy over those tokens alone:
System tokens, user tokens and template markers condition the prediction but are not predicted. Training on the prompt too is not catastrophic, but spends capacity imitating questions (here, English advisory text) instead of answering them, and dilutes the signal in this task: only 5.6% of dataset tokens are answers.
Three implementation details determine whether this works:
- The model’s exact template. Qwen2.5 inserts a default system message if you do not provide one and ends each turn with
<|im_end|>. The cell constructs the prefix withapply_chat_template(..., add_generation_prompt=True)and checks two things: that the full dialogue begins with prefix plus answer plus end-of-turn, and that tokenizing the prefix alone produces the same IDs as its part of the complete sequence. If the prefix–answer boundary fell inside a token, the mask would be shifted. - End-of-turn is part of the answer. If
<|im_end|>has no loss, the model does not learn to stop and keeps writing at inference. In the cell output, identifier digits are independent tokens (C,WE,-,8,3,3), and the last token with loss is end-of-turn. - Normalization with gradient accumulation. If a step accumulates several rows, the mean must cover all loss-bearing tokens in the step, rather than averaging row averages: a row with few answer tokens would weigh as much as one with many. The loop divides each row’s sum by the step total before
backward.
import numpy as np
rng = np.random.default_rng(0)
# dos filas del mismo paso: 40 y 4 tokens de respuesta con pérdidas distintas
a = rng.normal(0.8, 0.1, 40)
b = rng.normal(2.5, 0.1, 4)
print('media por token (correcta):', round(np.concatenate([a, b]).mean(), 4))
print('media de las medias por fila:', round((a.mean() + b.mean()) / 2, 4))
print('peso efectivo de cada token de la fila corta frente a la larga:', (1 / 2 / 4) / (1 / 2 / 40))Pack without mixing
Instructions have a median of 131 tokens and a maximum of 230. If 16 are batched and padded to the longest, 18% of batch slots are padding. Packing puts multiple examples consecutively in one row and removes padding. Naive packing introduces a silent error: with an ordinary causal mask, each example can attend to earlier examples in its row and receives positions it would not have at inference.
Proof
By induction over layers. The first-layer input at position depends only on token and its position, which by assumption match the isolated example. Suppose that at the input to layer the state at each position matches that of example processed alone. Per-position operations (normalization, MLP, residuals) preserve equality. In attention, the output at combines values at positions with , namely of the same segment, with weights depending on queries and keys at those same positions; with RoPE they also depend on positions, which are those of the isolated example. This is exactly the set and weights of causal attention for the example alone. Equality holds after layer and, by induction, in the logits.
∎The two assumptions do not carry equal weight. With RoPE, the product of a query at and a key at depends only on their difference , so with a block mask logits already agree in exact arithmetic even without resetting positions; resetting makes the result valid for any positional encoding, including absolute encoding, and avoids training with positions the example will never have. The mask, however, is always essential. Equality is perfect in exact arithmetic; in floating point, addition order changes with tensor shape. The training cell checks this in float32 before the sweep: with the block mask, maximum logit error versus each example alone is on the order of ; without it, tens of units.
Libraries solve this differently. In TRL, SFTConfig(packing=True) defaults to strategy bfd (best-fit decreasing), enabling padding-free mode (padding_free): it flattens the batch and passes example boundaries to attention, which documentation guarantees only with FlashAttention 2 or 3. On Windows those kernels are often unavailable; this lesson’s explicit 4D mask works with PyTorch SDPA attention and costs memory quadratic in row length, which is why rows have 512 tokens.
The next cell tokenizes the dataset, prints an example’s ending with loss-bearing tokens in brackets, and compares padding with packing. It loads only the tokenizer.
from transformers import AutoTokenizer
MODEL, REVISION = 'Qwen/Qwen2.5-0.5B-Instruct', '7ae557604adf67be50417f59c2c2f167def9a775'
tok = AutoTokenizer.from_pretrained(MODEL, revision=REVISION)
END = '<|im_end|>'
def encode(prompt, answer):
"""IDs del diálogo y etiquetas: -100 en todo lo que no escribe el asistente."""
user = [{'role': 'user', 'content': prompt}]
prefix = tok.apply_chat_template(user, add_generation_prompt=True, tokenize=False)
full = tok.apply_chat_template(user + [{'role': 'assistant', 'content': answer}], tokenize=False)
if not full.startswith(prefix + answer + END):
raise ValueError('La plantilla no produce prefijo + respuesta + fin de turno')
p_ids = tok(prefix, add_special_tokens=False)['input_ids']
ids = tok(prefix + answer + END, add_special_tokens=False)['input_ids']
if ids[:len(p_ids)] != p_ids:
raise ValueError('La tokenización del prefijo cambia al añadir la respuesta')
return ids, [-100] * len(p_ids) + ids[len(p_ids):]
def pack(examples, max_len=512):
"""Primer ajuste decreciente: cada fila es una lista de ejemplos que caben en max_len."""
bins = []
for ids, labels in sorted(examples, key=lambda e: -len(e[0])):
if len(ids) > max_len:
raise ValueError('Ejemplo más largo que max_len')
for b in bins:
if b['n'] + len(ids) <= max_len:
b['items'].append((ids, labels)); b['n'] += len(ids); break
else:
bins.append({'items': [(ids, labels)], 'n': len(ids)})
rows = []
for b in bins:
ids = [t for i, _ in b['items'] for t in i]
labels = [t for _, l in b['items'] for t in l]
segment = [k for k, (i, _) in enumerate(b['items']) for _ in i]
position = [p for i, _ in b['items'] for p in range(len(i))]
rows.append((ids, labels, segment, position))
return rows
ids, labels = encode(train[0]['prompt'], train[0]['answer'])
shown = [(tok.decode([t]), l != -100) for t, l in zip(ids, labels)]
print('fin del primer ejemplo (entre corchetes, los tokens con pérdida):')
print(''.join(f'[{s}]' if on else s for s, on in shown[-14:]).replace('\n', '⏎'))
encoded = [encode(c['prompt'], c['answer']) for c in train]
lengths = sorted(len(i) for i, _ in encoded)
loss_tokens = sum(sum(l != -100 for l in lab) for _, lab in encoded)
print(f'tokens por ejemplo: mediana {lengths[len(lengths) // 2]}, máximo {lengths[-1]}; '
f'con pérdida: {loss_tokens} de {sum(lengths)} ({loss_tokens / sum(lengths):.1%})')
for B in (16,):
batches = [encoded[i:i + B] for i in range(0, len(encoded), B)]
padded = sum(len(b) * max(len(i) for i, _ in b) for b in batches)
packed_rows = sum(len(pack(b)) for b in batches)
print(f'lote de {B}: relleno al más largo = {sum(lengths) / padded:.1%} de tokens útiles; '
f'empaquetado = {packed_rows} filas de hasta 512 para {len(batches)} pasos')npm run lab and open the connection link.A sweep with the rule written in advance
The lesson’s sweep crosses three factors:
- Learning rate: , and . Biderman and colleagues observed that LoRA is more sensitive to rate than full fine-tuning, that its best rate is about an order of magnitude higher, and recommend sweeping between and . is deliberately higher: the sweep must include configurations that forget, or you will not know where the boundary lies.
- Rank: 8 and 64, with as the same authors recommend, so scale is the same at all ranks.
- Modules: attention only (), or also the MLP’s three projections. In p08-l02 you saw how much the number of trainable parameters changes between these choices.
There are twelve configurations of three epochs each. With 1053 instructions and batches of 16, each epoch has steps and each configuration 198. Everything else is fixed: AdamW without weight decay, linear warmup over 5% of steps and linear decay to zero, 0.05 adapter dropout, gradient norm clipping at 1, and the same permutation of examples for every configuration in each epoch. The p08-l03 QLoRA setup works if you switch to a larger model; the bf16 0.5B has memory to spare (in the short run peak allocation was 2.9 GB, with rank 64 in all modules).
The selection rule is written to manifest.json before training, alongside data fingerprints and the configuration list, and the cell refuses to continue in a directory whose manifest differs:
Eligible configurations have an accuracy drop (
acc) of at most 2 percentage points on each of the two general tasks. Among eligible configurations, select the highest development accuracy; break ties by lower rank, then lower learning rate.
Two details are deliberate. The threshold applies to each task, not the mean: improvement on one does not offset a drop on another. The domain test plays no role: selecting by test score would make that score a biased estimate. With twelve candidates, the best on development benefits from noise (the winner’s curse), and its development accuracy overestimates the real value; the test, opened once, corrects that. The local sweeps built in m00 have the same structure: a manifest, one directory per run and the ability to resume without repeating finished work.
The next two cells do the GPU work. The first defines evaluators and measures the base model; the second checks packing and trains missing configurations. Enable them with P08_L04_DIR and P08_L04_RUN=1, while P08_L04_SCALE selects scale: completo (default) is the described sweep, with all ARC-Easy test questions (2376) and the first 2000 HellaSwag validation questions; corto is this lesson’s verification run (two rates, and , one epoch and 300 questions per general task). For example, in PowerShell:
$env:P08_L04_DIR = "C:\ruta\nueva\p08-l04" # resultados, adaptadores y manifiesto
$env:P08_L04_RUN = "1" # entrenar y evaluar lo que falte
$env:P08_L04_SCALE = "completo" # o "corto" para una verificación de unos minutos
Each configuration saves its result in resultados/ and its adapter in adaptadores/. If interrupted, rerunning skips completed work. To reread a directory without training, set only P08_L04_DIR. A watchdog aborts the process if RAM exceeds P08_L04_MAX_RAM_GB (8 GB by default). The model loads directly onto the GPU and general datasets are read by index without copying them in full.
General tasks are scored with a custom multiple-choice evaluator reproducing lm-evaluation-harness 0.4: the same question text, the same context–continuation concatenation, acc as the highest log-likelihood option and acc_norm divided by character length. Writing it avoids installing the harness in the lab environment, and the cell validates it against p08-l01: on the first 20 questions the base model must score exactly 0.65 on ARC-Easy and 0.35 on HellaSwag, the baseline evaluation figures.
import gc, math, threading, time
import numpy as np
import torch
RUN = os.environ.get('P08_L04_RUN') == '1'
SCALE = os.environ.get('P08_L04_SCALE', 'completo')
PLAN = {'completo': {'épocas': 3, 'tasas': [5e-5, 2e-4, 1e-3], 'rangos': [8, 64], 'generales': {'arc_easy': 2376, 'hellaswag': 2000}},
'corto': {'épocas': 1, 'tasas': [2e-4, 1e-3], 'rangos': [8, 64], 'generales': {'arc_easy': 300, 'hellaswag': 300}}}[SCALE]
MODULES = {'atención': ['q_proj', 'k_proj', 'v_proj', 'o_proj'],
'todas': ['q_proj', 'k_proj', 'v_proj', 'o_proj', 'gate_proj', 'up_proj', 'down_proj']}
CONFIGS = [{'id': f'r{r}-{"att" if m == "atención" else "all"}-{lr:g}', 'rank': r, 'lr': lr, 'modules': m}
for m in MODULES for r in PLAN['rangos'] for lr in PLAN['tasas']]
RULE = {'umbral_pp': 2.0, 'métrica_general': 'acc', 'objetivo': 'exactitud en desarrollo',
'desempate': 'menor rango, después menor tasa'}
BATCH, MAX_LEN, SEED = 16, 512, 0
manifest = {'modelo': MODEL, 'revisión': REVISION, 'cwe_zip_sha256': CWE_SHA256, 'dev': sha(dev), 'test': sha(test),
'train': sha(train), 'escala': SCALE, 'plan': PLAN, 'configuraciones': CONFIGS, 'regla': RULE,
'lote': BATCH, 'max_len': MAX_LEN, 'semilla': SEED}
if LAB:
path = LAB / 'manifest.json'
if path.is_file() and json.loads(path.read_text(encoding='utf-8')) != manifest:
raise ValueError('Este directorio tiene otro protocolo: usa un P08_L04_DIR nuevo')
path.write_text(json.dumps(manifest, ensure_ascii=False, indent=1), encoding='utf-8')
print(f'escala {SCALE}: {len(CONFIGS)} configuraciones, {PLAN["épocas"]} épocas, '
f'{PLAN["épocas"] * math.ceil(len(train) / BATCH)} pasos de {BATCH} ejemplos cada una')
def ram_guard(limit_gb=float(os.environ.get('P08_L04_MAX_RAM_GB', '8'))):
import psutil
proc = psutil.Process()
def watch():
while True:
if proc.memory_info().rss > limit_gb * 1e9:
print(f'RAM del proceso por encima de {limit_gb} GB: se aborta', flush=True)
os._exit(3)
time.sleep(1)
threading.Thread(target=watch, daemon=True).start()
def load_general():
from datasets import load_dataset
arc = load_dataset('allenai/ai2_arc', 'ARC-Easy', revision='210d026faf9955653af8916fad021475a3f00453', split='test')
hs = load_dataset('Rowan/hellaswag', revision='218ec52e09a7e7462a5400043bb9a69a41d06b76', split='validation')
def clean(t): # preprocesado de HellaSwag en lm-eval 0.4
t = t.strip().replace(' [title]', '. ')
return re.sub('\\[.*?\\]', '', t).replace(' ', ' ')
docs = {'arc_easy': [], 'hellaswag': []}
for i in range(PLAN['generales']['arc_easy']):
d = arc[i]
docs['arc_easy'].append(('Question: ' + d['question'] + '\nAnswer:', d['choices']['text'],
d['choices']['label'].index(d['answerKey'])))
for i in range(PLAN['generales']['hellaswag']):
d = hs[i]
ctx = clean(d['activity_label'] + ': ' + d['ctx_a'] + ' ' + d['ctx_b'].capitalize())
docs['hellaswag'].append((ctx, [clean(e) for e in d['endings']], int(d['label'])))
return docs
def encode_pair(context, continuation): # igual que HFLM._encode_pair en lm-eval
n = len(context) - len(context.rstrip())
if n:
context, continuation = context[:-n], context[-n:] + continuation
whole = tok(context + continuation, add_special_tokens=False)['input_ids']
ctx = tok(context, add_special_tokens=False)['input_ids']
return ctx, whole[len(ctx):]
@torch.no_grad()
def score_choices(model, docs, batch=8):
"""acc: opción de mayor log-verosimilitud; acc_norm: la misma dividida por caracteres."""
reqs = [(i, j, *encode_pair(ctx, ' ' + c), len(c)) for i, (ctx, cs, _) in enumerate(docs) for j, c in enumerate(cs)]
ll = {}
for k in range(0, len(reqs), batch):
chunk = reqs[k:k + batch]
seqs = [(a + b)[:-1] for _, _, a, b, _ in chunk]
L = max(map(len, seqs))
inp = torch.full((len(seqs), L), tok.pad_token_id, device='cuda')
att = torch.zeros((len(seqs), L), dtype=torch.long, device='cuda')
for r, s in enumerate(seqs):
inp[r, :len(s)] = torch.tensor(s); att[r, :len(s)] = 1
logits = model(input_ids=inp, attention_mask=att).logits
for r, (i, j, a, b, n) in enumerate(chunk):
lp = logits[r, len(a) - 1:len(a) - 1 + len(b)].float().log_softmax(-1)
ll[i, j] = (lp.gather(-1, torch.tensor(b, device='cuda')[:, None]).sum().item(), n)
del logits
acc, acc_norm = [], []
for i, (_, cs, gold) in enumerate(docs):
v = [ll[i, j] for j in range(len(cs))]
acc.append(int(max(range(len(v)), key=lambda j: v[j][0]) == gold))
acc_norm.append(int(max(range(len(v)), key=lambda j: v[j][0] / v[j][1]) == gold))
return {'acc': acc, 'acc_norm': acc_norm}
CWE_RE = re.compile(r'CWE-(\d+)')
@torch.no_grad()
def classify(model, rows, batch=32):
tok.padding_side = 'left'
out = []
for k in range(0, len(rows), batch):
chunk = rows[k:k + batch]
texts = [tok.apply_chat_template([{'role': 'user', 'content': r['prompt']}], add_generation_prompt=True,
tokenize=False) for r in chunk]
enc = tok(texts, return_tensors='pt', padding=True, add_special_tokens=False).to('cuda')
gen = model.generate(**enc, max_new_tokens=12, do_sample=False, pad_token_id=tok.pad_token_id)
for r, g in zip(chunk, gen[:, enc['input_ids'].shape[1]:]):
answer = tok.decode(g, skip_special_tokens=True).strip()
m = CWE_RE.search(answer)
out.append({'id': r['id'], 'salida': answer, 'formato': int(bool(m)),
'correcto': int(bool(m) and int(m.group(1)) in r['gold'])})
tok.padding_side = 'right'
return out
def evaluate(model, rows, general_docs):
model.eval()
record = {'dominio': classify(model, rows)}
for task, docs in general_docs.items():
record[task] = score_choices(model, docs)
return record
def summary(rec):
out = {'dominio': float(np.mean([r['correcto'] for r in rec['dominio']]))}
for task in ('arc_easy', 'hellaswag'):
out[task] = {m: float(np.mean(rec[task][m])) for m in ('acc', 'acc_norm')}
return out
def load_base():
from transformers import AutoModelForCausalLM
return AutoModelForCausalLM.from_pretrained(MODEL, revision=REVISION, dtype=torch.bfloat16,
device_map='cuda', low_cpu_mem_usage=True)
def save(name, record):
results[name] = record
(LAB / 'resultados' / f'{name}.json').write_text(json.dumps(record, ensure_ascii=False), encoding='utf-8')
results = {}
if LAB and (LAB / 'resultados').is_dir():
for f in sorted((LAB / 'resultados').glob('*.json')):
results[f.stem] = json.loads(f.read_text(encoding='utf-8'))
general = None
if RUN:
if not LAB:
raise ValueError('Define P08_L04_DIR para guardar los resultados')
if not torch.cuda.is_available():
raise RuntimeError('El barrido necesita CUDA')
ram_guard()
(LAB / 'resultados').mkdir(exist_ok=True)
general = load_general()
if 'base' not in results:
model = load_base()
t0 = time.time()
rec = evaluate(model, dev, general)
rec['segundos'] = round(time.time() - t0, 1)
save('base', rec)
del model; gc.collect(); torch.cuda.empty_cache()
if 'base' in results:
s = summary(results['base'])
print(f"base · dominio (desarrollo) {s['dominio']:.3f} · ARC-Easy acc {s['arc_easy']['acc']:.3f} "
f"(norm {s['arc_easy']['acc_norm']:.3f}) · HellaSwag acc {s['hellaswag']['acc']:.3f} "
f"(norm {s['hellaswag']['acc_norm']:.3f})")
print('base en las 20 primeras preguntas generales (para comparar con p08-l01):',
{t: float(np.mean(results['base'][t]['acc'][:20])) for t in ('arc_easy', 'hellaswag')})
print('respuestas con formato CWE válido:', float(np.mean([r['formato'] for r in results['base']['dominio']])))
else:
print('Evaluación base pendiente: define P08_L04_DIR y P08_L04_RUN=1 antes de iniciar el laboratorio.')npm run lab and open the connection link.def block_mask(segment):
"""Máscara 4D booleana: causal y solo dentro del mismo ejemplo empaquetado."""
s = torch.tensor(segment, device='cuda')
T = len(segment)
causal = torch.ones(T, T, dtype=torch.bool, device='cuda').tril()
return ((s[:, None] == s[None, :]) & causal)[None, None]
def train_one(cfg):
from peft import LoraConfig, get_peft_model
torch.manual_seed(SEED)
model = get_peft_model(load_base(), LoraConfig(
r=cfg['rank'], lora_alpha=2 * cfg['rank'], lora_dropout=0.05,
target_modules=MODULES[cfg['modules']], task_type='CAUSAL_LM'))
params = [p for p in model.parameters() if p.requires_grad]
opt = torch.optim.AdamW(params, lr=cfg['lr'], weight_decay=0.0)
steps_per_epoch = math.ceil(len(encoded) / BATCH)
total = PLAN['épocas'] * steps_per_epoch
warm = max(1, round(0.05 * total))
sched = torch.optim.lr_scheduler.LambdaLR(
opt, lambda s: (s + 1) / warm if s < warm else max(0.0, (total - s) / (total - warm)))
gen = torch.Generator().manual_seed(SEED)
model.train()
losses, t0, tokens = [], time.time(), 0
for epoch in range(PLAN['épocas']):
order = torch.randperm(len(encoded), generator=gen).tolist()
for k in range(0, len(order), BATCH):
rows = pack([encoded[i] for i in order[k:k + BATCH]], MAX_LEN)
n_target = sum(sum(l != -100 for l in r[1][1:]) for r in rows)
step_loss = 0.0
for ids, labels, segment, position in rows:
keep = [t for t in range(len(ids) - 1) if labels[t + 1] != -100]
out = model(input_ids=torch.tensor([ids], device='cuda'),
attention_mask=block_mask(segment),
position_ids=torch.tensor([position], device='cuda'),
logits_to_keep=torch.tensor(keep, device='cuda'))
target = torch.tensor([labels[t + 1] for t in keep], device='cuda')
loss = torch.nn.functional.cross_entropy(out.logits[0].float(), target, reduction='sum') / n_target
loss.backward()
step_loss += loss.item(); tokens += len(ids)
del out, loss
torch.nn.utils.clip_grad_norm_(params, 1.0)
opt.step(); sched.step(); opt.zero_grad(set_to_none=True)
losses.append(round(step_loss, 4))
seconds = time.time() - t0
rec = evaluate(model, dev, general)
rec.update({'config': cfg, 'pérdidas': losses, 'pasos': len(losses), 'segundos_entrenamiento': round(seconds, 1),
'tokens_por_segundo': round(tokens / seconds, 1), 'pico_gpu_gb': round(torch.cuda.max_memory_allocated() / 1e9, 3)})
model.save_pretrained(LAB / 'adaptadores' / cfg['id'])
del model, opt, params; gc.collect(); torch.cuda.empty_cache(); torch.cuda.reset_peak_memory_stats()
return rec
@torch.no_grad()
def check_packing():
"""En fp32, los logits empaquetados con máscara por bloques deben coincidir con los de cada ejemplo solo."""
from transformers import AutoModelForCausalLM
m = AutoModelForCausalLM.from_pretrained(MODEL, revision=REVISION, dtype=torch.float32,
device_map='cuda', low_cpu_mem_usage=True).eval()
ids, labels, segment, position = pack(encoded[:4], MAX_LEN)[0]
x = torch.tensor([ids], device='cuda')
packed = m(input_ids=x, attention_mask=block_mask(segment), position_ids=torch.tensor([position], device='cuda')).logits[0]
naive = m(input_ids=x).logits[0]
err_block = err_naive = 0.0
for k in sorted(set(segment)):
idx = [i for i, s in enumerate(segment) if s == k]
alone = m(input_ids=torch.tensor([[ids[i] for i in idx]], device='cuda')).logits[0]
err_block = max(err_block, (packed[idx] - alone).abs().max().item())
err_naive = max(err_naive, (naive[idx] - alone).abs().max().item())
del m; gc.collect(); torch.cuda.empty_cache()
return len(set(segment)), err_block, err_naive
if RUN:
k, eb, en = check_packing()
print(f'empaquetado de {k} ejemplos, error máximo de logits frente a cada ejemplo solo (fp32): '
f'con máscara por bloques {eb:.1e}; sin ella {en:.1f}')
for cfg in CONFIGS:
if cfg['id'] in results:
continue
save(cfg['id'], train_one(cfg))
s = summary(results[cfg['id']])
print(f"{cfg['id']}: desarrollo {s['dominio']:.3f} · ARC {s['arc_easy']['acc']:.3f} · HellaSwag {s['hellaswag']['acc']:.3f}"
f" · {results[cfg['id']]['segundos_entrenamiento']} s · pérdida {results[cfg['id']]['pérdidas'][0]} → {results[cfg['id']]['pérdidas'][-1]}", flush=True)
done = [c for c in CONFIGS if c['id'] in results]
print(f'configuraciones con resultados: {len(done)} de {len(CONFIGS)}')npm run lab and open the connection link.Measure forgetting
Pairing matters. Both scores are computed on the same questions, so most variability is shared: both models answer easy questions correctly and miss impossible ones. Forgetting is measured by questions that change. This takes the idea of forgetting metrics into statistics.
Proof
Linearity of expectation gives . Since , we have and . By independence, the variance of the sum is the sum of variances, and .
∎The practical consequence is stark. With (one in five questions changes answer, common after tuning) and , the drop’s standard error is , ten percentage points. A 2-point threshold over 20 questions is a coin toss. The 20 questions in p08-l01 fixed the protocol; they were not for measuring forgetting.
There are two ways to use the threshold, compared in the interactive:
- Point estimate: accept if . This is the sweep rule. With small samples it often accepts configurations that do forget and rejects others that do not.
- Interval upper bound: accept if . This is a noninferiority test: it accepts only when data rule out a drop greater than . With , and , requiring a 2-point half-width needs questions, and acceptance is still only 50%.
That is why the full scale uses all of ARC-Easy and 2000 HellaSwag questions, and why the results table includes intervals: a 1.3-point drop with interval does not say the same thing as one with .
import numpy as np
for d in (0.1, 0.2):
for n in (20, 300, 1000, 2376):
print(f'd = {d}, n = {n:5d}: error típico de la caída = {100 * np.sqrt(d / n):5.2f} pp')
need = int(np.ceil(1.96**2 * 0.1 / 0.02**2))
print('preguntas para un semiancho de 2 pp con d = 0.1:', need)
# comprobación por simulación del teorema con d = 0.2 y delta = 0.01
rng = np.random.default_rng(1)
n, d, delta = 300, 0.2, 0.01
u = rng.random((10000, n))
D = (u < (d + delta) / 2).astype(int) - ((u >= (d + delta) / 2) & (u < d)).astype(int)
est = D.mean(axis=1)
print('media simulada', round(est.mean(), 4), '· varianza simulada', round(est.var(), 6),
'· teórica', round((d - delta**2) / n, 6))The lab’s two general tasks are in English and measure school reasoning (ARC-Easy) and commonsense continuations (HellaSwag). A Spanish assistant would also need a general Spanish task with verified license and protocol; if available, add it to the manifest before the sweep, never afterward.
Results and selection
The table summarizes the short verification run: scale corto (eight configurations, one epoch of 66 steps each, 117 development advisories and 300 questions per general task) on an 8 GB RTX 4060 Laptop GPU shared with other processes. Each configuration took 38–103 seconds to train. These figures are from one run with one seed; they verify the lab end to end and show the shape of the tradeoff, not a definitive task result.
The base model gets 40 of 117 development advisories right (0.342). It is below the lexical baseline (0.521): even with candidates in front of it, the untuned model does not exploit shared words. Gains are paired differences in percentage points; general changes are tuned minus base, so a negative value means forgetting.
| Configuration | Development | Gain (pp) [95% CI] | ARC-Easy change (pp) [CI] | HellaSwag change (pp) [CI] | Eligible |
|---|---|---|---|---|---|
r8-att-0.0002 | 0.735 | +39.3 [+29.9, +48.7] | +4.7 [+1.7, +8.0] | +1.0 [0.0, +2.3] | yes |
r8-att-0.001 | 0.803 | +46.2 [+35.0, +57.3] | +6.0 [+1.7, +10.3] | −0.3 [−2.3, +1.7] | yes |
r64-att-0.0002 | 0.829 | +48.7 [+37.6, +59.0] | +4.7 [+0.7, +8.7] | −1.0 [−3.0, +1.0] | yes |
r64-att-0.001 | 0.436 | +9.4 [−2.6, +22.2] | −5.7 [−11.0, −0.3] | −3.7 [−6.7, −0.7] | no |
r8-all-0.0002 | 0.795 | +45.3 [+35.0, +55.6] | +6.0 [+2.3, +10.0] | +0.3 [−0.7, +1.7] | yes |
r8-all-0.001 | 0.496 | +15.4 [+4.3, +26.5] | +6.3 [+2.7, +10.3] | −0.7 [−3.0, +1.7] | yes |
r64-all-0.0002 | 0.368 | +2.6 [−8.5, +14.5] | +1.7 [−3.0, +6.3] | 0.0 [−2.3, +2.3] | yes |
r64-all-0.001 | 0.487 | +14.5 [+1.7, +28.2] | −23.3 [−29.7, −17.0] | −6.3 [−10.3, −2.7] | no |
Five readings, all visible in the first figure with “This lesson’s short run” selected:
- The domain is learned quickly. Four configurations rise from 0.342 to between 0.735 and 0.829 in one epoch, with intervals far from zero.
- The rate is the boundary. At rank 64 it not only learns less: it forgets the most.
r64-all-0.001drops ARC-Easy by 23.3 points, the same phenomenon as in the first task version, where that configuration fell 24.7 points without learning classification. The rule rejects both configurations with drops greater than 2 points. - More parameters are not automatically better.
r64-all-0.0002barely improves the domain in one epoch. Do not overinterpret one seed and 66 steps, but it reminds us that rank and modules interact with rate and duration; hence they are swept together. - ARC-Easy improves in several configurations (up to 6.3 points, with intervals excluding zero). General-task improvement after narrow SFT is not unusual, but with 300 questions and one seed it is too early to explain: the full scale will show whether it persists.
- The rule selects
r64-att-0.0002, the eligible configuration with highest development accuracy. Its HellaSwag drop is 1.0 point, within the threshold, but its interval reaches 3.0. The strict upper-bound rule (in the fourth interactive) would make it ineligible and chooser8-all-0.0002, with 0.795 development accuracy and a HellaSwag interval no worse than a 0.7-point drop. Both rules are defensible; choosing which to use after seeing this table is not.
Only then is the test opened. Of its 233 advisories, the base gets 95 right (0.408) and r64-att-0.0002 gets 182 (0.781): a gain of 37.3 points with a 95% paired bootstrap interval of [29.6, 45.1], comfortably excluding zero. Pairing is visible in the counts: 103 advisories move from wrong to right, 16 from right to wrong, 79 are answered correctly by both and 35 are missed by both. Test gain is about eleven points lower than development gain (48.7), consistent with the winner’s curse: among eight candidates, the development winner partly benefited from luck. The lesson’s verifiable outcome holds in the short run: domain improvement with an interval excluding zero, and a quantified drop on each general task below the threshold fixed before the sweep.
The next cell recalculates the table, intervals and selection from files in resultados/, opens the test if it has not yet been opened, and writes frontera.json, the file accepted by the first interactive’s “Load your frontera.json.”
def paired_ci(a, b, reps=10000, seed=0):
"""Diferencia media b − a por elemento y su intervalo bootstrap percentil del 95 %."""
d = np.asarray(b, float) - np.asarray(a, float)
idx = np.random.default_rng(seed).integers(0, len(d), size=(reps, len(d)))
boot = d[idx].mean(axis=1)
return float(d.mean()), float(np.percentile(boot, 2.5)), float(np.percentile(boot, 97.5))
table, chosen = [], None
if 'base' in results and done:
base = results['base']
for c in done:
r = results[c['id']]
gain = paired_ci([x['correcto'] for x in base['dominio']], [x['correcto'] for x in r['dominio']])
drops = {}
for t in ('arc_easy', 'hellaswag'):
m, lo, hi = paired_ci(r[t]['acc'], base[t]['acc']) # base − ajustada: positivo = empeora
drops[t] = (100 * lo, 100 * m, 100 * hi)
eligible = all(drops[t][1] <= RULE['umbral_pp'] for t in drops)
table.append({'id': c['id'], 'rank': c['rank'], 'lr': c['lr'], 'modules': c['modules'],
'gain': gain[0], 'gainLo': gain[1], 'gainHi': gain[2],
'arcDrop': drops['arc_easy'][1], 'arcLo': drops['arc_easy'][0], 'arcHi': drops['arc_easy'][2],
'hsDrop': drops['hellaswag'][1], 'hsLo': drops['hellaswag'][0], 'hsHi': drops['hellaswag'][2],
'eligible': eligible})
ok = [t for t in table if t['eligible']]
if ok:
chosen = max(ok, key=lambda t: (t['gain'], -t['rank'], -t['lr']))['id']
print('config ganancia dev [IC 95 %] caída ARC (pp) caída HellaSwag (pp) apta')
for t in table:
print(f"{t['id']:<17} {t['gain']:+.3f} [{t['gainLo']:+.3f}, {t['gainHi']:+.3f}] {t['arcDrop']:+6.2f}"
f" {t['hsDrop']:+6.2f} {'sí' if t['eligible'] else 'no'}")
print('elegida por la regla:', chosen)
final = None
if chosen and RUN and 'final' not in results:
from peft import PeftModel
model = load_base()
base_test = classify(model, test)
model = PeftModel.from_pretrained(model, LAB / 'adaptadores' / chosen)
save('final', {'elegida': chosen, 'base': base_test, 'ajustada': classify(model.eval(), test)})
del model; gc.collect(); torch.cuda.empty_cache()
if 'final' in results and results['final']['elegida'] == chosen:
f = results['final']
final = paired_ci([x['correcto'] for x in f['base']], [x['correcto'] for x in f['ajustada']])
print(f"prueba ({len(test)} avisos): base {np.mean([x['correcto'] for x in f['base']]):.3f} → "
f"{chosen} {np.mean([x['correcto'] for x in f['ajustada']]):.3f}; ganancia {final[0]:+.3f} "
f"[{final[1]:+.3f}, {final[2]:+.3f}]")
if LAB and table:
meta = {'escala': SCALE, 'umbral_pp': RULE['umbral_pp'], 'n_dev': len(dev), 'n_test': len(test),
'generales': PLAN['generales'], 'base': summary(results['base']), 'elegida': chosen,
'prueba': None if final is None else {'ganancia': final[0], 'lo': final[1], 'hi': final[2]}}
(LAB / 'frontera.json').write_text(json.dumps({'meta': meta, 'rows': table}, ensure_ascii=False, indent=1),
encoding='utf-8')
print('datos para el interactivo:', LAB / 'frontera.json')npm run lab and open the connection link.What to expect at full scale. No figures are published for this exact task, so the reference is the pattern documented by Biderman and colleagues, which your sweep should reproduce on a smaller scale. With three epochs, stable configurations’ development accuracy should reach at least the short-run level, and general retention should worsen as epochs, rate and module count increase, as in the first figure. Configurations at rate should separate from the rest: they learn less, forget more, or both, and the rule should reject some. With 2376 and 2000 general questions, drop-interval half-width falls to between 1.3 and 2 points (for disagreement rates 0.1–0.2), and the threshold begins to discriminate, which it barely does with 300 questions.
If your sweep differs, check the protocol before interpreting it: test fingerprints printed by the first cell must match this lesson (development 81526ee6b5e42535, test fa0bd7c5a680bcb1), the base model must score 0.65 and 0.35 on the first 20 general questions and about 0.34 on development, and the packing check must give error on the order of .
The same recipe with TRL
The library version replaces the loop with TRL’s SFTTrainer. This snippet corresponds to the documented TRL 1.17 API and does not run in the lab (TRL is absent from its environment). Two differences matter. assistant_only_loss=True requires the chat template to mark assistant turns with {% generation %}; TRL automatically patches some known families, and otherwise prompt–response format (completion_only_loss, enabled by default with that format) gives the same mask. packing=True with strategy bfd enables padding-free mode, which documentation supports only with FlashAttention 2 or 3.
from datasets import Dataset
from peft import LoraConfig
from trl import SFTConfig, SFTTrainer
rows = [{'prompt': [{'role': 'user', 'content': c['prompt']}],
'completion': [{'role': 'assistant', 'content': c['answer']}]} for c in train]
config = SFTConfig(
output_dir='sft-cwe', num_train_epochs=3, per_device_train_batch_size=16,
learning_rate=2e-4, lr_scheduler_type='linear', warmup_steps=0.05, weight_decay=0.0,
bf16=True, model_init_kwargs={'dtype': 'bfloat16'}, max_length=512,
packing=False, # sin FlashAttention, mejor sin empaquetar
completion_only_loss=True, logging_steps=10, report_to='none', seed=0)
trainer = SFTTrainer(
model='Qwen/Qwen2.5-0.5B-Instruct', args=config, train_dataset=Dataset.from_list(rows),
peft_config=LoraConfig(r=64, lora_alpha=128, lora_dropout=0.05, task_type='CAUSAL_LM',
target_modules=['q_proj', 'k_proj', 'v_proj', 'o_proj']))
trainer.train()
Before trusting the library, compare: with the same example order and seed, loss on the first steps should match your loop up to bf16 noise. If not, the likely cause is the mask (does <|im_end|> enter the loss?) or accumulation normalization. Evaluate the resulting adapter unmerged or merged according to the p08-l02 merge-equivalence check.
Common mistakes
Exercises
Summary
Honest domain SFT is primarily a data and measurement problem. Sources are chosen by license and confidentiality, not availability; evaluation is frozen first and training separated by connected components and filtered using exact matching, n-grams and similarity. Loss applies only to assistant tokens, including end-of-turn, and packing requires a block mask and reset positions to preserve the function. The sweep is declared in advance with a rule using development and general tasks, and the test is opened once. Forgetting is measured per task, paired and with an interval, over enough questions for the threshold to mean something: with twenty, no rule separates forgetting from noise.