From base model to assistant: instruction tuning
Turn the custom base model into a small assistant using a chat template with special tokens, conversation packing with document masks, assistant-only loss, and supervised fine-tuning on an open conversation dataset. Evaluate it on a custom instruction set and publish locally with a model card.
After this lesson you can
- Design the chat template and add special tokens to tokenizer and model.
- Implement packing with assistant-only loss masking and verify it with tests.
- Fine-tune the base model and compare before and after on an instruction set.
- Write a model card with data, compute, evaluations, and limitations.
Before you start
- P06HellaSwag likelihood evaluationSampling and qualitative evaluationByte-level BPE tokenizer
- 20Instruction tuningChat templateAssistant-only loss maskingSFT data curationCatastrophic forgetting
- 18Sequence packing and document masking
- 30Rigorous model evaluation and reportingAI risk management frameworks
From base model to assistant
The model pretrained in p06-l06 and evaluated in p06-l07 can continue text. Give it “What is gravity?” and it will most likely continue as a web page would: another question, an FAQ list, or the beginning of an exam. Nothing is broken. It estimates over FineWeb-Edu documents, in which a question is rarely followed by a brief answer that ends and yields the turn.
Supervised fine-tuning of the custom model (SFT) changes this without changing the task: the model still predicts the next token with cross-entropy, but on fixed-structure conversations and counting only positions we want it to learn to produce. This is m20’s instruction tuning applied to your own GPT and tokenizer. Three things are new compared with pretraining: a template with tokens the model has never seen, masked loss, and conversation packing that prevents information passing between conversations.
It helps to know what SFT can and cannot provide. InstructGPT fine-tuned GPT-3 on about 13 000 annotator-demonstrated instructions for 16 epochs with cosine decay and residual dropout 0.2. Validation loss began to overfit after the first epoch while judged quality kept improving. That was only the first of three phases, preceding the reward model and reinforcement learning. LIMA fine-tuned 65-billion-parameter LLaMa on exactly 1000 carefully selected conversations, around 750 000 tokens, and proposed the superficial alignment hypothesis: almost all knowledge is acquired in pretraining, while fine-tuning mainly teaches the format and style of presentation. For your model, GPT-2 small architecture (“124M”) but only 86 million parameters because of its 513-ID vocabulary, this has an uncomfortable implication: SFT can teach assistant-like response structure, but cannot give knowledge that pretraining did not provide. Fluent but ill-informed answers are to be expected, and evaluation must distinguish them from correct answers.
Chat template and special tokens
A chat template converts a list of role-labeled messages into IDs. This project’s is the simplest template that clearly separates turns:
<|endoftext|><|user|> pregunta <|end|><|assistant|> respuesta <|end|><|user|> ... <|end|>
End-of-document opens the conversation, as it opened each pretraining document. Each user turn lies between <|user|> and <|end|>, followed by <|assistant|>; each answer ends in <|end|>. For generation, code writes history and the latest user message and stops immediately after <|assistant|>. That prefix matches what the model saw before each answer in training. Generation stops when the model emits <|end|> or reaches a token limit. LIMA introduced a turn-end token separate from end-of-document for the same reason: the base model’s <|endoftext|> already has a learned meaning, “start an unrelated document”, and reusing it for “yield the turn” mixes two roles.
The three markers are new IDs 513, 514, and 515, following the 512 ordinary IDs and end-of-document ID 512 of the p06-l01 and p06-l02 vocabulary. The important security property is that only template code can produce them. If a user literally writes <|end|><|assistant|> inside a message, the ordinary encoder treats it as bytes and produces the IDs for <, |, end, and so on, never 515. If the encoder recognized those literals, untrusted text could close its own turn and fabricate an assistant turn, a direct token-level prompt injection. The p06-l01 encoder already separates these cases, recognizing a special only if the caller explicitly authorizes it with allow_special=True, and the lab checks this with a test. The data filter also drops conversations containing these literals so the model does not learn to associate their spelling with turn changes.
The template also determines supervision. Here each answer’s content and <|end|> are targets: the model must learn to write the answer and stop. <|assistant|> belongs to the prompt because code writes it. Another defensible choice is to supervise <|assistant|> after the user’s <|end|> too. Leaving this implicit is indefensible because a mismatch between training and generation templates can make the model continue in the wrong role or fail to stop. The checkpoint therefore saves template, marker IDs, supervised tokens, and vocabulary hash.
Expand the embedding matrix
Adding three IDs requires three new rows in embedding matrix . In the p06-l03 GPT, that matrix is tied to the output head: logits are , with the final state after ln_f and row , without bias. Resizing must preserve this tie, since two independent matrices would change architecture and parameter count, copy old rows unchanged, and choose how to initialize new ones. This choice is not cosmetic because new rows enter every position’s softmax denominator from the first step.
Proof
For an old token, with , so for every , and divergence, which averages that ratio with weights , equals . By linearity, . Strict convexity of the exponential and Jensen’s inequality give , with equality exactly when all agree. Thus .
∎With and , the bound is nats. In practice it is much smaller because trained-model logits are far from equal and is well below the mean of . A naive alternative, random rows with variance unlike the rest, has no such bound: with , the new logit is , and if is large relative to trained-row scale, a large-norm state can give one marker nearly all mass. The model begins fine-tuning by generating <|end|> mid-sentence, and initial steps undo the initialization. The lab measures three choices, mean, , and , with real base-model states.
Two qualifications. Mean initialization addresses output, not input: all three markers start with identical embeddings and are initially distinguished by position and context; gradients separate them as soon as they occur in different places. And a marker having an ID does not mean the model understands the role; that is what fine-tuning must teach.
Open SFT data
SFT data curation matters as much as training. This project uses UltraChat 200k, Hugging Face’s filtered version prepared to train Zephyr-7B-β from UltraChat. Its card says the original contains 1.4 million ChatGPT-generated dialogues, a subset was selected, capitalization was corrected in about 5% of data, and dialogues where the assistant replies with formulas such as “I do not have emotions” were removed. It has an MIT license, a train_sft split of 207 865 conversations, and test_sft of 23 110. It is suitable for learning: open, multi-turn, in English like pretraining data, and uniform in structure. Note its limits too: it is synthetic, so the model will imitate ChatGPT’s style, and nobody has checked every answer for truthfulness.
The lab’s filter is explicit and counts every rejection:
- Roles. Turns must alternate user and assistant beginning with user; an unanswered final user turn is removed.
- Content. Empty turns and turns literally containing a template marker or
<|endoftext|>are discarded. - Duplicates. Keep one conversation per normalized first instruction, using lowercase and spaces. This is cheap exact deduplication; near-duplicate detection, such as MinHash, remains an improvement.
- Contamination. Discard conversations whose first instruction matches one in the custom evaluation set, and from validation also those repeating a training instruction. A test split does not prove non-overlap with training or the pretraining corpus.
- Length. Keep the longest prefix of complete exchanges fitting the 1024-token context; if even the first does not fit, discard the conversation. Never cut an answer in half: a truncated answer followed by
<|end|>teaches the model to stop mid-sentence.
The last filter is more severe than it appears. A custom-vocabulary token contains about 2.0 text bytes versus GPT-2’s 4.6, as measured in p06-l06, so 1024 tokens are about 2 KB and a long UltraChat exchange does not fit. The lab prints how many conversations are lost and exchanges trimmed, and records this in the model card because it biases data toward short answers.
Also record the exact dataset revision, repository SHA, license, counts per filter, processed tokens, and supervised targets. These are distinct quantities. If only 60% of tokens are targets, a “20 million token” budget can mean 20 million processed or 12 million supervised, affecting step estimates, effective learning rate, and comparison with other work.
Packing, document masks, and assistant-only loss
Let be a conversation and the positions whose tokens belong to a supervised answer, assistant content and its <|end|>. The assistant-only loss mask defines
and requires : an example with no targets defines no loss and must be discarded or flagged as an error, never divided by zero. This is m20’s assistant-only loss. User tokens remain context, appearing in , but are not targets. If they were targets too, the model would devote capacity to imitating questions and might continue writing the user turn instead of answering.
In code, mask labels, not inputs: an unsupervised token’s label is -100, and F.cross_entropy(..., ignore_index=-100) excludes it from both sum and denominator. Labels are shifted one position, with logits at predicting , exactly once. If the implementation already shifts internally, shifting labels too introduces an off-by-one error without exception, yielding a model learning to predict the current token.
Conversations vary greatly in length. Padding each to 1024 tokens would waste most compute, so several are packed consecutively in one row. With a simple causal mask, a query in the second conversation would attend to the first. The model would learn to use unrelated dialogue as context and behave differently during generation when that context is absent. The solution is m18’s packing mask: query can attend to key exactly when and both positions belong to the same conversation. This mask controls available information; the loss mask controls which targets contribute gradients. Neither replaces the other.
The figure packs three conversations with two padding positions. The upper strip colors tokens by role; the second marks targets in green; the matrix shows keys each query row can attend to. Start with the selected query, the ⟨assistant⟩ preceding answer “6”: it is at position 11 in its conversation and sees 12 keys, those within that conversation up to itself, and nothing else. Disable the document mask and red cells show the exact leakage. Then change the loss policy to “All tokens” and see which counters turn red.
The figure also shows an easily forgotten decision: positions. The second conversation starts at row position 8; without resetting, its first token would receive position embedding 8 and the selected ⟨assistant⟩ 19, while during generation those same tokens occupy positions 0 and 11. Disable “Reset positions” and inspect the query readout. The packer resets positions at each conversation start. Together, document masking and reset positions make packing exactly equivalent to processing each conversation separately.
Proof
Induct over layers. At input the state is in both cases because token and reset position match. Assume equality at layer for every position. LayerNorm, MLP, and projections act positionwise, so queries, keys, and values agree. Attention at softmaxes keys with , exactly positions in the same conversation, with the same scores and values as positions of alone. The set is never empty because it includes the diagonal. Thus attention outputs and residual connections agree. At the final layer ln_f and logits agree. Labels are the same, so loss and its gradient agree.
Assumptions matter. With dropout active, equality holds only in distribution. Without resetting positions, it fails at input. An operation mixing positions or examples, batch normalization for example, would break the inductive step. In floating point, equality is approximate because sums reorder with different shapes: the lab checks it with float32 tolerance. Padding is treated as its own document, each padding position seeing only earlier padding, so no mask row is empty, which would produce softmax over and NaN.
One reduction detail remains. With gradient accumulation, an update processes microbatches with targets and summed losses . The mean of means, , weights each target by : targets in a microbatch with few answers weigh more than those in one with many. During pretraining all were equal; in SFT the supervised fraction varies greatly by row. The correct update-wide mean is , obtained by counting all update targets first and dividing each microbatch’s loss sum by that total before backward().
The next browser cell checks these rules with symbolic IDs: shifting, document isolation, and a reduction unchanged even when losses at ignored positions change. The lab repeats the same tests with real tensors and the p06-l03 GPT.
def build_labels(tokens, roles):
if len(tokens) != len(roles):
raise ValueError('Longitudes distintas')
if any(r not in ('usuario', 'asistente') for r in roles):
raise ValueError('Rol desconocido')
return [token if role == 'asistente' else -100 for token, role in zip(tokens, roles)]
def shifted_targets(tokens, roles, documents):
"""El objetivo de la posición i es la etiqueta de i+1, solo dentro de la misma conversación."""
if len(tokens) != len(documents):
raise ValueError('Longitudes distintas')
labels = build_labels(tokens, roles)
return [labels[i+1] if documents[i] == documents[i+1] else -100
for i in range(len(tokens)-1)]
def attention_mask(documents):
return [[j <= i and documents[i] == documents[j] for j in range(len(documents))]
for i in range(len(documents))]
tokens = [10, 11, 12, 13, 20, 21, 22, 23]
roles = ['usuario', 'usuario', 'asistente', 'asistente'] * 2
docs = [0, 0, 0, 0, 1, 1, 1, 1]
targets = shifted_targets(tokens, roles, docs)
mask = attention_mask(docs)
assert targets == [-100, 12, 13, -100, -100, 22, 23]
assert not mask[6][0] and mask[6][4] and not mask[6][7]
def global_mean(per_position, targets):
valid = [loss for loss, t in zip(per_position, targets) if t != -100]
if len(per_position) != len(targets) or not valid:
raise ValueError('Lote sin objetivos o con longitudes distintas')
return sum(valid) / len(valid)
losses = [4., 1., 2., 9., 8., 3., 4.]
perturbed = [1000., 1., 2., -1000., 700., 3., 4.]
assert global_mean(losses, targets) == global_mean(perturbed, targets) == 2.5
# Dos microlotes con distinto número de objetivos: media global frente a media de medias
micro = [([1.0, 1.0, 1.0, 1.0], [5, 5, 5, 5]), ([3.0, 9.0, 9.0, 9.0], [7, -100, -100, -100])]
sums = [sum(l for l, t in zip(ls, ts) if t != -100) for ls, ts in micro]
counts = [sum(t != -100 for t in ts) for _, ts in micro]
print('Objetivos desplazados:', targets)
print('La consulta 6 ve las posiciones:', [i for i, allowed in enumerate(mask[6]) if allowed])
print('Media sobre objetivos válidos, antes y después de alterar los ignorados:',
global_mean(losses, targets), global_mean(perturbed, targets))
print('Media global:', sum(sums) / sum(counts), '| media de las medias de cada microlote:',
sum(s / c for s, c in zip(sums, counts)) / len(micro))Fine-tuning: learning rate, epochs, and forgetting
Fine-tuning starts at the end of pretraining, where rate fell to from a peak of . Returning to the peak risks moving already well-placed weights too much; staying at the minimum makes fine-tuning slow. The lab defaults to peak with 3% warmup and cosine decay to one tenth, AdamW with , weight decay 0.1 excluding embeddings, biases, and LayerNorm as in p06-l06, and gradient clipping at 1. This is a reasonable starting point, not a published value for this model. If time permits, compare , , and using the same evaluation. As a scale reference, LIMA used with linear decay to for 15 epochs on a 65-billion-parameter model, selecting a checkpoint between epochs 5 and 10 with a 50-example development set because perplexity did not correlate with response quality.
Step count comes from processed tokens rather than conversations. With rows of 1024 tokens and 64 rows per update, each step processes 65 536 tokens; project design calls for two epochs on about 20 million tokens. Each step’s loss is averaged only over supervised targets, a variable fraction of those tokens, and the training log records both counts.
The price of fine-tuning is catastrophic forgetting: weights encoding the pretraining distribution move toward conversation data, and unexercised capabilities may degrade. InstructGPT called it the “alignment tax” and measured it on public tasks: in its automatic-evaluation table, zero-shot HellaSwag accuracy fell from 0.549, 0.673, and 0.781 for GPT-3 with 1.3, 6, and 175 billion parameters to 0.528, 0.672, and 0.753 for SFT models, drops of 2.1, 0.1, and 2.8 points. To reduce this, they mixed pretraining gradients into reinforcement learning, PPO-ptx, recovering and even exceeding GPT-3 on HellaSwag. Equivalent SFT levers are a lower rate, fewer steps, and mixing pretraining rows into each update. The lab exposes mixing through P06_SFT_MIX, the fraction of rows per step from the pretraining corpus with every position targeted. None guarantees a result: measure the effect with pretraining validation loss and HellaSwag before and after.
Evaluation before and after
Three distinct questions and three measurements, all with the same protocol before and after fine-tuning.
Does it follow the format? The custom set has 100 fixed instructions, ten tasks such as explaining in two sentences, giving three facts, or writing a haiku, across ten topics, excluded from training by the contamination filter. Each is generated greedily without sampling for up to 512 new tokens. A response follows format if it ends in <|end|> within the limit, contains no other marker, and has nonempty text. Failures are defined before measurement: a repetitive loop that never closes is a failure, as is an empty answer. The binary metric is reported with its p06-l07 Wilson interval. The project goal is 95%; with 95 successes out of 100 the 95% interval is 0.888 to 0.978, so “95 out of 100” is compatible with a somewhat lower true rate. Format says nothing about quality or truth: a fabricated answer ending in <|end|> counts as a success.
Has it forgotten? Run p06-l07’s HellaSwag evaluator, read from that lesson, on the same rows for the expanded model before fine-tuning and the fine-tuned one. Measurements are paired by example, so report the difference with p06-l07’s paired interval and McNemar test rather than comparing two Wilson intervals. The project goal, “HellaSwag falls by less than 1 point”, can be claimed only if the difference interval’s lower endpoint exceeds −1 point. A point estimate of −0.4 with interval −1.3 to +0.5 does not establish it. With 10 042 examples, if 10% switch from correct to incorrect or vice versa, paired-interval half-width is about 0.62 points; with 20%, 0.87. Alongside HellaSwag, measure pretraining validation loss over 200 fixed p06-l02 validation windows, which reacts earlier and with less noise.
Does it answer well? No automatic metric in this lab measures that. Read full responses and ask questions whose answers you know. An 86-million-parameter model pretrained on 1730 million custom tokens, around 3.5 GB of text, stores little factual knowledge, and SFT has taught it to present generated text confidently. Fluency is not evidence the information exists in its weights. The model card must record that distinction between format and knowledge.
If pretraining loss rises substantially, do not infer a cause blindly. Check that evaluation is identical in rows, windows, and template; compare intermediate checkpoints to locate when the increase begins; and test controlled changes in rate, duration, or mixing one at a time under the same evaluation.
Model card
The model card accompanies weights and describes what they are, how they were obtained and evaluated, and inappropriate uses. Mitchell and colleagues proposed nine sections: model details, intended use, factors, metrics, evaluation data, training data, quantitative analyses, ethical considerations, and caveats and recommendations. Their central contribution is disaggregated evaluation: report performance across relevant conditions and groups, not just an average. This project has no groups of people to disaggregate, but it does have conditions: the lab-generated card breaks format rate down by instruction type, since a model closing definitions well but never haikus differs from one failing randomly.
The card is generated from saved measurements, not written by hand, and follows m30’s honest evaluation reporting: each figure with interval, each comparison with protocol, and an explicit section for what has not been evaluated, including truthfulness, safety, and bias. A card does not turn an absent evaluation into a result. It is part of risk management, requiring out-of-scope uses to be recorded before someone attempts them.
Lab
The lab turns your base model into a small assistant: expanded template and tokenizer, filtered and packed UltraChat 200k data, baseline evaluation, fine-tuning on the RTX 4060, post-evaluation, model card, and terminal chat program. Run the six cells in order in one session; the first only defines and tests, and the rest depend on earlier cells. Only the first is included in the page’s automatic tests: the other five require your p06-l02 data, p06-l06 checkpoint, downloads, and hours of GPU time, and were verified with the short runs described below.
Requirements: completed p06-l02, with manifest and vocabulary in p06_data, and p06-l06, with weights-only model-*.pt copies; PyTorch with CUDA, numpy, and p06-l01 dependencies regex, tiktoken, and hypothesis, because code reads the p06-l01 encoder, p06-l03 GPT class, and p06-l07 HellaSwag evaluator from the current lessons themselves. Run from project root or set P06_PROJECT_ROOT. Environment variables:
| Variable | Default | Use |
|---|---|---|
P06_DATA_DIR | p06_data | p06-l02 manifest, vocabulary, and shards. |
P06_CKPT_DIR | p06_pretrain/runs/full | Folder with p06-l06 model-*.pt copies; the latest is used. |
P06_BASE_CKPT | unset | Path to a specific checkpoint instead of the latest. |
P06_SFT_DIR | p06_sft | UltraChat cache, fine-tuned checkpoint, results, card, and chat.py. |
P06_EVAL_DIR | p06_eval | HellaSwag cache shared with p06-l07. |
P06_HS_LIMIT | 10042 | HellaSwag examples; fewer only for testing. |
P06_SFT_TRAIN_ROWS | 54000 | train_sft conversations read, first in order. |
P06_SFT_VAL_ROWS | 1000 | test_sft conversations for validation loss. |
P06_SFT_EPOCHS, P06_SFT_LR, P06_SFT_MIX, P06_SFT_DROPOUT | 2, 1e-4, 0, 0 | Fine-tuning hyperparameters. |
P06_SFT_ROWS_PER_STEP, P06_SFT_MICRO | 64, 4 | Rows per update and microbatch; lowering microbatch reduces memory without changing the update. |
P06_MIX_DIR | p06_pretrain/corpus | p06-l06 corpus for mixing; if absent, training shards from P06_DATA_DIR are used. |
P06_SFT_MAX_NEW | 512 | New-token limit in format evaluation. |
The first cell contains everything independent of data: chat tokenizer, template, build_labels, packer, document-masked forward pass, and matrix expansion. Its tests use a tiny GPT with byte vocabulary and check four things: literal marker text does not produce special IDs and generation prefix matches training; packed loss exactly matches mean over assistant tokens calculated conversation by conversation, with zero gradient at ignored positions; changing the first conversation leaves second-conversation logits unchanged with the mask and changes them without it, and packed second conversation matches that conversation alone; and the expansion theorem’s bound. The chat program reads this same cell.
"""Plantilla de chat, tokenizador ampliado y empaquetador con máscaras; pruebas en CPU."""
import hashlib
import json
import math
import os
from pathlib import Path
import numpy as np
import torch
from torch import nn
import torch.nn.functional as F
SPECIALS = ('<|user|>', '<|assistant|>', '<|end|>')
IGNORE = -100
def find_project_root():
configured = os.environ.get('P06_PROJECT_ROOT')
candidates = [Path(configured).resolve()] if configured else [Path.cwd(), *Path.cwd().parents]
for candidate in candidates:
if (candidate / 'src/content/lessons/p06/l03-modelo-gpt-y-paridad.mdx').is_file():
return candidate
raise FileNotFoundError('No se encontró la raíz del proyecto; fija P06_PROJECT_ROOT')
def lesson_cell(root, filename, title):
text = (root / 'src/content/lessons/p06' / filename).read_text(encoding='utf-8')
marker = '`' * 3 + f'python run runtime=local title="{title}"\n'
if marker not in text:
raise KeyError(f'No encuentro la celda «{title}» en {filename}')
return text.split(marker, 1)[1].split('\n' + '`' * 3, 1)[0]
def load_previous(root):
"""Codificador de p06-l01 y clase GPT de p06-l03 (sin sus controles), leídos de las lecciones vigentes."""
os.environ.setdefault('BPE_DATA_DIR', str(Path(os.environ.get('P06_SFT_DIR', 'p06_sft')).resolve() / 'bpe_cache'))
bpe = {'__name__': 'bpe_p06_l01'}
exec(compile(lesson_cell(root, 'l01-tokenizador-bpe.mdx', 'Codificador y entrenador BPE incremental'),
'p06-l01.mdx', 'exec'), bpe)
code, found, _ = lesson_cell(root, 'l03-modelo-gpt-y-paridad.mdx', 'GPT propio y controles').partition(
'\nattention_test()\nbehavior_test()')
if not found:
raise KeyError('La celda de p06-l03 ya no termina con attention_test() y behavior_test()')
gpt = {'__name__': 'modelo_p06_l03'}
exec(compile(code, 'p06-l03.mdx', 'exec'), gpt)
return gpt['GPT'], bpe
class ChatTokenizer:
"""BPE de bytes de p06-l02 más tres IDs reservados que solo inserta la plantilla."""
def __init__(self, bpe, ranks, eot, eot_literal='<|endoftext|>'):
if sorted(ranks.values()) != list(range(eot)):
raise ValueError('Se esperaban IDs ordinarios 0..eot-1 y el fin de documento en eot')
self.encode = bpe['make_text_encoder'](ranks) # sin especial: el texto nunca produce IDs reservados
self.eot = eot
self.user, self.assistant, self.end = eot + 1, eot + 2, eot + 3
self.vocab = eot + 4
if self.vocab > 32767:
raise ValueError('El empaquetador guarda IDs en int16')
self.special_ids = frozenset((eot, self.user, self.assistant, self.end))
self.pieces = {v: k for k, v in ranks.items()}
for i, literal in zip((eot, self.user, self.assistant, self.end), (eot_literal, *SPECIALS)):
self.pieces[i] = literal.encode('utf-8')
def decode(self, ids):
return b''.join(self.pieces[i] for i in ids).decode('utf-8', errors='replace')
def render(self, messages):
"""IDs y rol de cada token: EOT <|user|> u <|end|> <|assistant|> a <|end|> ...
Todo lo que escribe el código o el usuario es 'usuario'; el contenido del asistente y su <|end|>, 'asistente'."""
ids, roles = [self.eot], ['usuario']
for k, m in enumerate(messages):
if m['role'] != ('user' if k % 2 == 0 else 'assistant'):
raise ValueError('Los turnos deben alternar user y assistant empezando por user')
body = self.encode(m['content'])
if m['role'] == 'user':
ids += [self.user, *body, self.end, self.assistant]
roles += ['usuario'] * (len(body) + 3)
else:
ids += [*body, self.end]
roles += ['asistente'] * (len(body) + 1)
return ids, roles
def prompt(self, history, user_text):
"""Prefijo de generación: termina en <|assistant|>, igual que delante de cada respuesta del entrenamiento."""
return self.render(history + [{'role': 'user', 'content': user_text}])[0]
def build_labels(tokens, roles):
if len(tokens) != len(roles):
raise ValueError('Longitudes distintas')
if any(role not in ('usuario', 'asistente') for role in roles):
raise ValueError('Rol desconocido')
return [token if role == 'asistente' else IGNORE for token, role in zip(tokens, roles)]
def encode_example(tok, messages):
"""Conversación compacta: IDs en int16 y una máscara booleana de tokens supervisados."""
ids, roles = tok.render(messages)
labels = np.array(build_labels(ids, roles))
return np.array(ids, dtype=np.int16), labels != IGNORE
def pack(examples, context, pad_id):
"""Empaquetado voraz y en orden en filas de longitud fija. Devuelve (filas, 4, context) en int16 con
IDs, conversación, posición y objetivo. El objetivo de la posición i es el token i+1 si es supervisado y de
la misma conversación; el relleno no es objetivo y forma su propio documento (conversación -1)."""
rows, current, used = [], [], 0
def flush():
row = np.full((4, context), IGNORE, dtype=np.int16)
row[0], row[1], row[2] = pad_id, -1, 0
start = 0
for d, (ids, sup) in enumerate(current):
n = len(ids)
row[0, start:start+n] = ids
row[1, start:start+n] = d
row[2, start:start+n] = np.arange(n)
row[3, start:start+n-1] = np.where(sup[1:], ids[1:], IGNORE) # la última posición no tiene objetivo
start += n
rows.append(row)
for ids, sup in examples:
if len(ids) > context:
raise ValueError('Conversación más larga que el contexto: recórtala por intercambios antes de empaquetar')
if used + len(ids) > context:
flush()
current, used = [], 0
current.append((ids, sup))
used += len(ids)
if current:
flush()
return np.stack(rows)
def as_batch(rows, device='cpu'):
"""IDs, conversación, posición y objetivo como tensores int64."""
t = torch.from_numpy(rows.astype(np.int64)).to(device)
return t[:, 0], t[:, 1], t[:, 2], t[:, 3]
def document_mask(docs):
"""(B, 1, T, T): la consulta i ve la clave j si j <= i y son de la misma conversación."""
t = docs.shape[1]
causal = torch.ones(t, t, dtype=torch.bool, device=docs.device).tril()
return causal & (docs[:, :, None] == docs[:, None, :])[:, None]
def forward_packed(model, ids, docs, pos):
"""El forward del GPT de p06-l03 con máscara de documento y posiciones reiniciadas."""
tr = model.transformer
mask = document_mask(docs)
z = tr.drop(tr.wte(ids) + tr.wpe(pos))
for block in tr.h:
attn, h = block.attn, block.ln_1(z)
b, t, d = h.shape
q, k, v = attn.c_attn(h).split(d, dim=-1)
split = lambda u: u.view(b, t, attn.heads, d // attn.heads).transpose(1, 2)
out = F.scaled_dot_product_attention(split(q), split(k), split(v), attn_mask=mask,
dropout_p=attn.p if model.training else 0.0)
z = z + attn.resid_drop(attn.c_proj(out.transpose(1, 2).reshape(b, t, d)))
z = z + block.mlp(block.ln_2(z))
return model.lm_head(tr.ln_f(z))
def masked_loss_sum(logits, targets):
"""Suma de -log p sobre los objetivos válidos; quien llama divide por el total de la actualización."""
return F.cross_entropy(logits.reshape(-1, logits.size(-1)).float(), targets.reshape(-1),
ignore_index=IGNORE, reduction='sum')
def add_chat_tokens(model, new_vocab):
"""Amplía la matriz atada: filas antiguas intactas, nuevas en la media de las antiguas."""
old = model.transformer.wte.weight.data
v, d = old.shape
emb = nn.Embedding(new_vocab, d).to(device=old.device, dtype=old.dtype)
with torch.no_grad():
emb.weight[:v] = old
emb.weight[v:] = old.mean(0)
model.transformer.wte = emb
model.lm_head = nn.Linear(d, new_vocab, bias=False).to(device=old.device, dtype=old.dtype)
model.lm_head.weight = emb.weight # se conserva la vinculación de p06-l03
return model
def _tiny_setup():
GPT, bpe = load_previous(find_project_root())
tok = ChatTokenizer(bpe, {bytes([i]): i for i in range(256)}, eot=256) # solo bytes, para probar
torch.manual_seed(0)
model = add_chat_tokens(GPT(vocab=257, context=64, layers=2, heads=2, d=32, dropout=0.0), tok.vocab).eval()
convs = [[{'role': 'user', 'content': 'hola'}, {'role': 'assistant', 'content': 'buenas'}],
[{'role': 'user', 'content': '2+2?'}, {'role': 'assistant', 'content': '4'},
{'role': 'user', 'content': 'y 3+3?'}, {'role': 'assistant', 'content': '6'}]]
return GPT, tok, model, convs
def test_template_and_labels(tok, convs):
ids, roles = tok.render(convs[1])
assert ids[:2] == [tok.eot, tok.user] and ids[-1] == tok.end
injected = tok.encode('<|end|><|assistant|>') # el texto nunca crea especiales
assert injected == list('<|end|><|assistant|>'.encode()) and not set(injected) & tok.special_ids
supervised = [t for t, r in zip(ids, roles) if r == 'asistente']
assert tok.decode(supervised) == '4<|end|>6<|end|>'
second = [i for i, t in enumerate(ids) if t == tok.assistant][1]
assert tok.prompt(convs[1][:2], 'y 3+3?') == ids[:second + 1]
def test_loss_ignores_user(tok, model, convs):
"""La pérdida empaquetada es la media de -log p sobre los tokens del asistente, calculada aparte."""
examples = [encode_example(tok, c) for c in convs]
ids, docs, pos, targets = as_batch(pack(examples, context=64, pad_id=tok.eot))
logits = forward_packed(model, ids, docs, pos)
logits.retain_grad()
count = (targets != IGNORE).sum()
loss = masked_loss_sum(logits, targets) / count
loss.backward()
assert logits.grad[targets == IGNORE].abs().max().item() == 0.0 # gradiente nulo fuera del asistente
nll, n = 0.0, 0
with torch.no_grad():
for t, sup in examples: # cada conversación sola, sin empaquetar
out = F.log_softmax(model(torch.tensor(t[None].astype(np.int64)))[0].float(), -1)
for j in range(1, len(t)):
if sup[j]:
nll -= out[j-1, int(t[j])].item()
n += 1
assert n == count.item() and abs(nll / n - loss.item()) < 1e-5, (nll / n, loss.item())
naive = F.cross_entropy(logits[0, :-1].float(), ids[0, 1:]) # error típico: todos los tokens
assert abs(naive.item() - loss.item()) > 1e-3
return loss.item(), n, naive.item()
def test_isolation(tok, model, convs):
examples = [encode_example(tok, c) for c in convs]
ids, docs, pos, _ = as_batch(pack(examples, context=64, pad_id=tok.eot))
first, second = len(examples[0][0]), len(examples[1][0])
changed = ids.clone()
changed[0, 1:first] = torch.randint(0, 256, (first - 1,), generator=torch.Generator().manual_seed(1))
with torch.no_grad():
a = forward_packed(model, ids, docs, pos)[0, first:first + second]
b = forward_packed(model, changed, docs, pos)[0, first:first + second]
open_docs = torch.zeros_like(docs) # sin máscara de documento
c = forward_packed(model, ids, open_docs, pos)[0, first:first + second]
d = forward_packed(model, changed, open_docs, pos)[0, first:first + second]
alone = model(torch.tensor(examples[1][0][None].astype(np.int64)))[0] # la segunda sola
assert torch.equal(a, b) and (c - d).abs().max().item() > 1e-3
assert torch.allclose(a, alone, atol=1e-5, rtol=0)
return (c - d).abs().max().item(), (a - alone).abs().max().item()
def test_resize(GPT):
torch.manual_seed(3)
base = GPT(vocab=257, context=16, layers=1, heads=2, d=32, dropout=0.0).eval()
h = torch.randn(512, 32) * 4 # estados finales arbitrarios
old_w = base.transformer.wte.weight.detach().clone()
old_logits = h @ old_w.T
wide = add_chat_tokens(base, 260)
w = wide.transformer.wte.weight.detach()
assert wide.lm_head.weight is wide.transformer.wte.weight and torch.equal(w[:257], old_w)
new_logits = torch.cat([old_logits, h @ w[257:].T], -1)
kl = (torch.logsumexp(new_logits, -1) - torch.logsumexp(old_logits, -1)).max().item() # KL = log Z'/Z
assert kl <= math.log(1 + 3 / 257) + 1e-6
return kl, math.log(1 + 3 / 257)
if __name__ == '__main__':
GPT, tok, model, convs = _tiny_setup()
test_template_and_labels(tok, convs)
loss, n, naive = test_loss_ignores_user(tok, model, convs)
leak, alone = test_isolation(tok, model, convs)
kl, bound = test_resize(GPT)
print('Plantilla, etiquetas y texto con marcadores literales: correctos')
print(f'Pérdida empaquetada {loss:.6f} = media de {n} objetivos del asistente calculada conversación a conversación;'
f' con todos los tokens sería {naive:.6f}')
print('Gradiente en las posiciones ignoradas: exactamente 0')
print(f'Aislamiento: cambiar la conversación 1 no altera la 2 (diferencia 0); sin máscara, hasta {leak:.4f}')
print(f'Segunda conversación empaquetada frente a sola: diferencia máxima {alone:.2e}')
print(f'Filas nuevas en la media: KL máximo {kl:.5f} <= log(1 + 3/257) = {bound:.5f}')npm run lab and open the connection link.The second cell loads the p06-l02 vocabulary, verified by hash and pretokenization expression, and latest p06-l06 weights copy, then expands the matrix. Before expansion it measures, using real base-model final states on four validation windows, how much each new-row initialization would change the distribution.
"""Modelo base de p06-l06, vocabulario de p06-l02 y tokens de chat añadidos."""
import random
import time
DEVICE = 'cuda' if torch.cuda.is_available() else 'cpu'
ROOT = find_project_root()
GPT, BPE = load_previous(ROOT)
DATA = Path(os.environ.get('P06_DATA_DIR', 'p06_data')).resolve()
OUT = Path(os.environ.get('P06_SFT_DIR', 'p06_sft')).resolve()
OUT.mkdir(parents=True, exist_ok=True)
def load_tokenizer(data):
manifest = json.loads((data / 'manifest.json').read_text(encoding='utf-8'))
raw = (data / manifest['vocab_file']).read_bytes()
if hashlib.sha256(raw).hexdigest() != manifest['vocab_sha256']:
raise ValueError('El vocabulario no coincide con el hash del manifiesto')
payload = json.loads(raw)
if payload['pretokenization'] != BPE['PAT'].pattern:
raise ValueError('La pretokenización del vocabulario no es la de p06-l01')
ranks = {bytes.fromhex(k): v for k, v in payload['vocab_hex'].items()}
return ChatTokenizer(BPE, ranks, manifest['eot_id'], payload['special_literal']), manifest
def find_base_checkpoint():
if os.environ.get('P06_BASE_CKPT'):
return Path(os.environ['P06_BASE_CKPT']).resolve()
folder = Path(os.environ.get('P06_CKPT_DIR', 'p06_pretrain/runs/full')).resolve()
snapshots = sorted(folder.rglob('model-*.pt')) # copias de solo pesos que guarda p06-l06
if not snapshots:
raise FileNotFoundError(f'No hay copias model-*.pt en {folder}: fija P06_BASE_CKPT o P06_CKPT_DIR')
return snapshots[-1]
def load_base(path, vocab_sha256):
state = torch.load(path, map_location='cpu', weights_only=True) # solo tensores y tipos básicos
if (state.get('identity') or {}).get('vocab_sha256', vocab_sha256) != vocab_sha256:
raise ValueError(f'{path.name} se entrenó con otro vocabulario')
weights = {k.removeprefix('_orig_mod.'): v for k, v in state.get('model', state).items() if torch.is_tensor(v)}
vocab, d = weights['transformer.wte.weight'].shape
layers = 1 + max(int(k.split('.')[2]) for k in weights if k.startswith('transformer.h.'))
cfg = state.get('config') or {}
arch = {'layers': layers, 'heads': int(cfg.get('heads', 12)), 'd': d,
'context': weights['transformer.wpe.weight'].shape[0]}
model = GPT(vocab=vocab, dropout=0.0, **arch)
model.load_state_dict(weights)
return model, {'checkpoint': str(path), 'step': state.get('step'), 'tokens': state.get('tokens'),
'architecture': arch, 'sha256': hashlib.sha256(path.read_bytes()).hexdigest()}
def valid_windows(manifest, data, context, count):
"""Ventanas fijas y disjuntas de la validación de p06-l02 (documentos que p06-l06 tampoco entrena)."""
stream = np.concatenate([np.fromfile(data / s['file'], dtype='<u2') for s in manifest['parts']['valid']['shards']])
if len(stream) < count * (context + 1):
raise ValueError('La validación es demasiado corta para tantas ventanas')
starts = np.arange(count) * (len(stream) // count)
return torch.from_numpy(np.stack([stream[s:s + context + 1] for s in starts]).astype(np.int64))
tok, manifest = load_tokenizer(DATA)
base_path = find_base_checkpoint()
model, base_meta = load_base(base_path, manifest['vocab_sha256'])
assert model.transformer.wte.weight.shape[0] == tok.eot + 1, 'el checkpoint no usa el vocabulario de p06-l02'
CONTEXT = model.context
PT_WINDOWS = valid_windows(manifest, DATA, CONTEXT, int(os.environ.get('P06_SFT_PT_WINDOWS', '200')))
with torch.no_grad(): # KL(base || ampliado) = log Z'/Z en cada posición real
_, residual = model(PT_WINDOWS[:4, :-1], return_residual=True)
h = model.transformer.ln_f(residual[-1]).reshape(-1, model.d)
w = model.transformer.wte.weight
old = h @ w.T
def kl_with(rows):
return torch.logsumexp(torch.cat([old, h @ rows.T], -1), -1) - torch.logsumexp(old, -1)
g = torch.Generator().manual_seed(0)
inits = {'media de las filas': w.mean(0).expand(3, -1),
'N(0, 0.02²)': 0.02 * torch.randn(3, model.d, generator=g),
'N(0, 1)': torch.randn(3, model.d, generator=g)}
kls = {name: kl_with(rows) for name, rows in inits.items()}
assert kls['media de las filas'].max() <= math.log(1 + 3 / (tok.eot + 1)) + 1e-5, 'la media debería cumplir la cota'
print('Checkpoint base:', {k: v for k, v in base_meta.items() if k != 'sha256'})
print(f'Vocabulario: {tok.eot} ordinarios + EOT + 3 de chat = {tok.vocab} IDs; '
f'norma media de las filas entrenadas {w.norm(dim=1).mean():.3f}')
print(f'Cota del teorema: log(1 + 3/{tok.eot + 1}) = {math.log(1 + 3 / (tok.eot + 1)):.5f} nats')
for name, kl in kls.items():
print(f'KL(base || ampliado) con filas {name}: media {kl.mean():.2e}, máximo {kl.max():.2e} '
f'en {kl.numel()} posiciones')
model = add_chat_tokens(model, tok.vocab).to(DEVICE)npm run lab and open the connection link.The third cell downloads UltraChat 200k in pages of 100 rows via the Hugging Face rows API, caches every page, and records the repository revision. If the repository changes in a later run, it stops rather than mixing versions. Conversations are stored compactly with int16 IDs and a Boolean mask, about 3 bytes per token versus tens of bytes per element in a Python list. Download proceeds page by page and never holds more than one in memory. Defaults total about 370 MB the first time, or 56 MB for 8300 conversations in the short check.
"""UltraChat 200k: descarga por páginas, revisión registrada, filtros, deduplicación y recorte por intercambios."""
import urllib.error
import urllib.request
REPO = 'HuggingFaceH4/ultrachat_200k'
TRAIN_ROWS = int(os.environ.get('P06_SFT_TRAIN_ROWS', '54000'))
VAL_ROWS = int(os.environ.get('P06_SFT_VAL_ROWS', '1000'))
CACHE = OUT / 'ultrachat'
CACHE.mkdir(exist_ok=True)
TASKS = ['Explain {} in two sentences.', 'Give three facts about {}.', 'What is {}?',
'Write a short paragraph about {}.', 'Describe {} to a ten-year-old.',
'List two common misconceptions about {}.', 'Why is {} important?',
'Summarize what you know about {} in one sentence.', 'Write a haiku about {}.',
'Give one everyday example related to {}.']
TOPICS = ['photosynthesis', 'the water cycle', 'prime numbers', 'the Roman Empire', 'volcanoes',
'electricity', 'the human heart', 'gravity', 'recycling', 'the internet']
INSTRUCTIONS = [task.format(topic) for task in TASKS for topic in TOPICS] # 100 fijas; tarea = índice // 10
def fetch_json(url, path):
if not path.exists():
for attempt in range(8):
try:
with urllib.request.urlopen(url, timeout=90) as response:
payload = response.read()
break
except urllib.error.HTTPError as error:
if error.code not in (429, 500, 502, 503, 504) or attempt == 7:
raise
time.sleep(min(60, 5 * 2**attempt))
tmp = path.with_suffix('.tmp')
tmp.write_bytes(payload)
os.replace(tmp, path)
return json.loads(path.read_bytes())
def pinned_revision():
"""La API de filas sirve la revisión actual: se registra la primera vez y se exige la misma después."""
record = CACHE / 'revision.json'
with urllib.request.urlopen(f'https://huggingface.co/api/datasets/{REPO}', timeout=60) as response:
current = json.loads(response.read())
info = {'sha': current['sha'], 'license': (current.get('cardData') or {}).get('license')}
if record.exists():
saved = json.loads(record.read_text(encoding='utf-8'))
if saved['sha'] != info['sha']:
raise RuntimeError(f"La caché es de la revisión {saved['sha']} y el repositorio está en {info['sha']}: "
'borra la caché para empezar con la revisión nueva')
else:
record.write_text(json.dumps(info), encoding='utf-8')
return info['sha'], info['license']
def rows(split, n):
"""Filas en orden, página a página: nunca hay más de una página en memoria."""
for offset in range(0, n, 100):
count = min(100, n - offset)
url = (f'https://datasets-server.huggingface.co/rows?dataset={REPO.replace("/", "%2F")}'
f'&config=default&split={split}&offset={offset}&length={count}')
payload = fetch_json(url, CACHE / f'{split}-{offset:06d}-{count}.json')
assert [r['row_idx'] for r in payload['rows']] == list(range(offset, offset + count))
for r in payload['rows']:
yield r['row']
def norm(text):
return ' '.join(text.lower().split())
def clean(messages):
"""Turnos alternos que empiezan en el usuario y terminan en el asistente; sin vacíos ni literales especiales."""
msgs = [{'role': m['role'], 'content': m['content'].strip()} for m in messages]
if not msgs or any(m['role'] != ('user' if k % 2 == 0 else 'assistant') for k, m in enumerate(msgs)):
return None, 'roles'
if len(msgs) % 2:
msgs = msgs[:-1] # último turno del usuario sin respuesta
if not msgs or any(not m['content'] for m in msgs):
return None, 'vacío'
if any(lit in m['content'] for m in msgs for lit in (*SPECIALS, '<|endoftext|>')):
return None, 'literal especial'
return msgs, None
def fit(messages, context):
"""El prefijo más largo de intercambios completos que cabe en el contexto; nunca se corta una respuesta."""
best = None
for k in range(2, len(messages) + 1, 2):
ids, sup = encode_example(tok, messages[:k])
if len(ids) > context:
break
best = (ids, sup, k // 2)
return best
def prepare(split, n, banned=frozenset()):
seen, examples = set(), []
stats = {'rows': 0, 'kept': 0, 'exchanges': 0, 'exchanges_cut': 0, 'tokens': 0, 'supervised': 0,
'dropped': {'roles': 0, 'vacío': 0, 'literal especial': 0, 'duplicado': 0,
'instrucción de evaluación': 0, 'no cabe': 0}}
for row in rows(split, n):
stats['rows'] += 1
msgs, reason = clean(row['messages'])
if msgs is None:
stats['dropped'][reason] += 1
continue
key = norm(msgs[0]['content'])
if key in banned:
stats['dropped']['instrucción de evaluación'] += 1
continue
if key in seen:
stats['dropped']['duplicado'] += 1
continue
seen.add(key)
result = fit(msgs, CONTEXT)
if result is None:
stats['dropped']['no cabe'] += 1
continue
ids, sup, pairs = result
examples.append((ids, sup))
stats['kept'] += 1
stats['exchanges'] += pairs
stats['exchanges_cut'] += len(msgs) // 2 - pairs
stats['tokens'] += len(ids)
stats['supervised'] += int(sup.sum())
return examples, seen, stats
revision, license_id = pinned_revision()
start = time.perf_counter()
banned = {norm(i) for i in INSTRUCTIONS}
train_examples, train_prompts, train_stats = prepare('train_sft', TRAIN_ROWS, banned)
val_examples, _, val_stats = prepare('test_sft', VAL_ROWS, banned | train_prompts)
data_info = {'dataset': REPO, 'revision': revision, 'license': license_id, 'train_split': 'train_sft',
'val_split': 'test_sft', 'train': train_stats, 'val': val_stats, 'context': CONTEXT}
(OUT / 'data.json').write_text(json.dumps(data_info, ensure_ascii=False, indent=1), encoding='utf-8')
print(f'Revisión {revision}, licencia {license_id}, {time.perf_counter() - start:.0f} s')
for name, s in (('entrenamiento', train_stats), ('validación', val_stats)):
print(f"{name}: {s['kept']} de {s['rows']} conversaciones, {s['tokens']} tokens "
f"({s['tokens'] / max(s['kept'], 1):.0f} por conversación), {s['supervised']} objetivos "
f"({s['supervised'] / max(s['tokens'], 1):.1%}), {s['exchanges']} intercambios, "
f"{s['exchanges_cut']} recortados; descartes {s['dropped']}")npm run lab and open the connection link.The fourth cell fixes evaluation and runs it on the expanded model before fine-tuning. The HellaSwag evaluator comes from p06-l07, read from its lesson: same rows, same protocol, acc_norm using mean ending loss, and same paired comparison. Generation processes one conversation from position 0, as during fine-tuning. It also measures a diagnostic between loss and format: under teacher forcing, where the model sees the real answer, at every validation position where <|end|> should be written, measure the probability assigned to it and whether it is the most likely token. If that probability rises but format does not, the model has learned to close and greedy generation is failing by entering loops before reaching the closing point. With the full model, 100 greedy answers up to 512 tokens and all 10 042 HellaSwag examples take several minutes.
"""Evaluación antes del ajuste: formato en 100 instrucciones, HellaSwag y pérdidas de validación."""
MAX_NEW = int(os.environ.get('P06_SFT_MAX_NEW', '512'))
hs = {'__name__': 'evaluador_p06_l07'} # evaluador de p06-l07: mismas filas, protocolo y comparación
exec(compile(lesson_cell(ROOT, 'l07-evaluacion-del-modelo-base.mdx', 'Evaluador HellaSwag, bits por byte y muestreo'),
'p06-l07.mdx', 'exec'), hs)
HS_ROWS, HS_SHA = hs['hellaswag_rows']()
@torch.no_grad()
def reply(model, prompt_ids, max_new=MAX_NEW, temperature=0.0, top_k=0, generator=None):
"""Genera hasta <|end|> o el límite; temperatura 0 es decodificación voraz."""
ids, out = list(prompt_ids), []
for _ in range(max_new):
if len(ids) >= model.context:
break
logits = model(torch.tensor([ids], device=DEVICE))[0, -1].float()
if temperature == 0:
nxt = int(logits.argmax())
else:
logits = logits / temperature
if top_k:
logits[logits < torch.topk(logits, top_k).values[-1]] = -math.inf
nxt = int(torch.multinomial(torch.softmax(logits, -1).cpu(), 1, generator=generator))
out.append(nxt)
ids.append(nxt)
if nxt == tok.end:
break
return out
def format_ok(out):
"""Cierra con <|end|> dentro del límite, sin otros marcadores y con texto no vacío."""
if not out or out[-1] != tok.end:
return False
body = out[:-1]
return not any(t in tok.special_ids for t in body) and tok.decode(body).strip() != ''
def format_eval(model):
model.eval()
outs = [reply(model, tok.prompt([], text)) for text in INSTRUCTIONS]
ok = [format_ok(o) for o in outs]
return {'ok': sum(ok), 'n': len(ok), 'rate': sum(ok) / len(ok), 'wilson95': hs['wilson'](sum(ok), len(ok)),
'closed': sum(bool(o) and o[-1] == tok.end for o in outs),
'by_task': [sum(ok[10 * t:10 * t + 10]) for t in range(len(TASKS))],
'mean_new_tokens': sum(map(len, outs)) / len(outs), 'replies': [tok.decode(o) for o in outs]}
@torch.no_grad()
def pretrain_loss(model, batch=8):
model.eval()
total, count = 0.0, 0
for i in range(0, len(PT_WINDOWS), batch):
w = PT_WINDOWS[i:i + batch].to(DEVICE)
total += F.cross_entropy(model(w[:, :-1]).flatten(0, 1).float(), w[:, 1:].flatten(), reduction='sum').item()
count += w[:, 1:].numel()
return total / count
@torch.no_grad()
def sft_loss(model, packed, batch=8):
model.eval()
total, count = 0.0, 0
for i in range(0, len(packed), batch):
ids, docs, pos, targets = as_batch(packed[i:i + batch], DEVICE)
total += masked_loss_sum(forward_packed(model, ids, docs, pos), targets).item()
count += int((targets != IGNORE).sum())
return total / count
@torch.no_grad()
def stop_stats(model, packed, batch=8):
"""Con forzado del profesor, en las posiciones de validación donde toca cerrar: probabilidad media de
<|end|> y fracción en la que es el token más probable. Separa «sabe parar» de «la generación voraz se atasca»."""
model.eval()
p_end, top1, n = 0.0, 0, 0
for i in range(0, len(packed), batch):
ids, docs, pos, targets = as_batch(packed[i:i + batch], DEVICE)
logits = forward_packed(model, ids, docs, pos)[targets == tok.end].float()
p_end += torch.softmax(logits, -1)[:, tok.end].sum().item()
top1 += int((logits.argmax(-1) == tok.end).sum())
n += logits.shape[0]
return {'p_end': p_end / n, 'end_top1': top1 / n, 'positions': n}
def evaluate(model, label):
t0 = time.perf_counter()
fmt = format_eval(model)
correct, correct_sum, details = hs['evaluate_examples'](model, tok.encode, HS_ROWS)
n = len(HS_ROWS)
result = {'label': label, 'format': fmt,
'hellaswag': {'n': n, 'rows_sha256': HS_SHA, 'acc_norm': correct / n, 'acc': correct_sum / n,
'correct': correct, 'wilson95': hs['wilson'](correct, n)},
'pretrain_val_loss': pretrain_loss(model), 'sft_val_loss': sft_loss(model, VAL_PACKED),
'stop': stop_stats(model, VAL_PACKED), 'seconds': round(time.perf_counter() - t0, 1)}
return result, details
VAL_PACKED = pack(val_examples, CONTEXT, tok.eot)
before, before_hs = evaluate(model, 'base ampliado, antes del ajuste')
fb = before['format']
print(f"Formato: {fb['ok']} de {fb['n']}, cierran con <|end|>: {fb['closed']}, "
f"{fb['mean_new_tokens']:.0f} tokens nuevos de media")
print(f"HellaSwag acc_norm {before['hellaswag']['acc_norm']:.4f} en {before['hellaswag']['n']} ejemplos | "
f"pérdida de preentrenamiento {before['pretrain_val_loss']:.4f} | SFT en validación {before['sft_val_loss']:.4f}"
f" | {before['seconds']} s")
print(f"Donde toca cerrar ({before['stop']['positions']} posiciones): p(<|end|>) media {before['stop']['p_end']:.4f}, "
f"es el más probable en el {before['stop']['end_top1']:.1%}")
print('Antes del ajuste:', repr(INSTRUCTIONS[2]), '->', repr(fb['replies'][2][:200]))npm run lab and open the connection link.The fifth cell fine-tunes. It shuffles conversations with a fixed seed, packs them, and at each update first counts targets across all 64 rows to divide each microbatch sum by that total: the mean is global, as packing requires. It uses BF16 on GPU, saves weights after each epoch, and records loss, gradient norm, rate, processed tokens, and targets per step in train-log.jsonl. At completion it repeats evaluation and calculates the paired HellaSwag difference.
"""Ajuste supervisado: filas empaquetadas, pérdida solo en el asistente y evaluación después."""
CFG = {'epochs': int(os.environ.get('P06_SFT_EPOCHS', '2')),
'rows_per_step': int(os.environ.get('P06_SFT_ROWS_PER_STEP', '64')),
'micro_batch': int(os.environ.get('P06_SFT_MICRO', '4')),
'lr': float(os.environ.get('P06_SFT_LR', '1e-4')), 'min_lr_ratio': 0.1, 'warmup_ratio': 0.03,
'weight_decay': 0.1, 'betas': (0.9, 0.95), 'clip': 1.0,
'dropout': float(os.environ.get('P06_SFT_DROPOUT', '0')),
'mix': float(os.environ.get('P06_SFT_MIX', '0')), # fracción de filas de preentrenamiento por paso
'eval_every': int(os.environ.get('P06_SFT_EVAL_EVERY', '50')), 'seed': 2026}
assert CFG['rows_per_step'] % CFG['micro_batch'] == 0
def lr_at(s, total):
warmup = max(1, round(CFG['warmup_ratio'] * total))
peak, floor = CFG['lr'], CFG['lr'] * CFG['min_lr_ratio']
if s <= warmup:
return peak * s / warmup
return floor + 0.5 * (peak - floor) * (1 + math.cos(math.pi * (s - warmup) / max(1, total - warmup)))
def pretrain_shards():
"""Shards de entrenamiento para la mezcla: el corpus de p06-l06 si existe; si no, el de p06-l02.
Se abren con memmap: nunca se cargan enteros en memoria."""
folder = Path(os.environ.get('P06_MIX_DIR', 'p06_pretrain/corpus')).resolve()
if not (folder / 'manifest.json').exists():
folder = DATA
mix_manifest = json.loads((folder / 'manifest.json').read_text(encoding='utf-8'))
if mix_manifest['vocab_sha256'] != manifest['vocab_sha256']:
raise ValueError(f'El corpus de {folder} usa otro vocabulario')
shards = [np.memmap(folder / s['file'], dtype='<u2', mode='r') for s in mix_manifest['parts']['train']['shards']]
print(f'Mezcla de preentrenamiento: {sum(map(len, shards)):,} tokens de {folder}')
return [s for s in shards if len(s) > CONTEXT + 1]
def pretrain_rows(shards, count, rng):
"""Ventanas de preentrenamiento, causales y con objetivo en todas las posiciones, para la mezcla opcional."""
rows = np.zeros((count, 4, CONTEXT), dtype=np.int16)
for r in range(count):
stream = rng.choices(shards, weights=[len(s) for s in shards])[0]
s = rng.randrange(len(stream) - CONTEXT - 1)
w = np.asarray(stream[s:s + CONTEXT + 1]).astype(np.int16)
rows[r, 0], rows[r, 2], rows[r, 3] = w[:-1], np.arange(CONTEXT), w[1:]
return rows
for m in model.modules(): # dropout opcional, como el residual de InstructGPT y LIMA
if isinstance(m, nn.Dropout):
m.p = CFG['dropout']
for block in model.transformer.h:
block.attn.p = CFG['dropout']
torch.manual_seed(CFG['seed'])
rng = random.Random(CFG['seed'])
order = train_examples[:]
rng.shuffle(order)
TRAIN_PACKED = pack(order, CONTEXT, tok.eot)
n_pt = round(CFG['mix'] * CFG['rows_per_step'])
n_sft = CFG['rows_per_step'] - n_pt
steps_per_epoch = len(TRAIN_PACKED) // n_sft
total_steps = CFG['epochs'] * steps_per_epoch
if total_steps == 0:
raise ValueError('Hay menos filas que un paso: aumenta P06_SFT_TRAIN_ROWS o reduce P06_SFT_ROWS_PER_STEP')
pt_shards = pretrain_shards() if n_pt else None
real = int((TRAIN_PACKED[:, 1] >= 0).sum())
print(f'{len(TRAIN_PACKED)} filas de {CONTEXT} tokens ({real / TRAIN_PACKED[:, 1].size:.1%} sin relleno, '
f'{int((TRAIN_PACKED[:, 3] != IGNORE).sum())} objetivos), {n_sft} de SFT y {n_pt} de preentrenamiento '
f'por paso, {total_steps} pasos')
no_decay_names = {'transformer.wte.weight', 'transformer.wpe.weight'}
named = list(model.named_parameters())
decay = [p for n, p in named if p.dim() >= 2 and n not in no_decay_names]
no_decay = [p for n, p in named if p.dim() < 2 or n in no_decay_names]
opt = torch.optim.AdamW([{'params': decay, 'weight_decay': CFG['weight_decay']},
{'params': no_decay, 'weight_decay': 0.0}],
lr=CFG['lr'], betas=CFG['betas'], fused=DEVICE == 'cuda')
autocast = torch.autocast('cuda', dtype=torch.bfloat16) if DEVICE == 'cuda' else torch.autocast('cpu', enabled=False)
ckpt = OUT / 'sft-model.pt'
log_path = OUT / 'train-log.jsonl'
log_path.write_text('', encoding='utf-8')
def save_checkpoint(step, epoch):
tmp = ckpt.with_suffix('.tmp')
torch.save({'model': model.state_dict(), 'step': step, 'epoch': epoch, 'tokens': seen_tokens,
'targets': seen_targets, 'config': {**base_meta['architecture'], 'vocab': tok.vocab},
'base': base_meta, 'vocab_sha256': manifest['vocab_sha256'], 'vocab_file': manifest['vocab_file'],
'template': {'specials': list(SPECIALS), 'ids': [tok.user, tok.assistant, tok.end],
'eot_id': tok.eot, 'supervised': 'contenido del asistente y su <|end|>'},
'train_config': {k: (list(v) if isinstance(v, tuple) else v) for k, v in CFG.items()}}, tmp)
os.replace(tmp, ckpt)
log, step, seen_tokens, seen_targets = [], 0, 0, 0
if DEVICE == 'cuda':
torch.cuda.reset_peak_memory_stats()
t_start = time.perf_counter()
for epoch in range(CFG['epochs']):
perm = np.random.default_rng(CFG['seed'] + epoch).permutation(len(TRAIN_PACKED))
for k in range(steps_per_epoch):
step += 1
rows_np = TRAIN_PACKED[perm[k * n_sft:(k + 1) * n_sft]]
if n_pt:
rows_np = np.concatenate([rows_np, pretrain_rows(pt_shards, n_pt, rng)])
rows_t = as_batch(rows_np, DEVICE)
count = int((rows_t[3] != IGNORE).sum()) # objetivos de toda la actualización: media global
for g in opt.param_groups:
g['lr'] = lr_at(step, total_steps)
model.train()
total = 0.0
for i in range(0, len(rows_np), CFG['micro_batch']):
ids, docs, pos, targets = (t[i:i + CFG['micro_batch']] for t in rows_t)
with autocast:
logits = forward_packed(model, ids, docs, pos)
loss = masked_loss_sum(logits, targets) / count
loss.backward()
total += loss.item()
grad_norm = torch.nn.utils.clip_grad_norm_(model.parameters(), CFG['clip']).item()
opt.step()
opt.zero_grad(set_to_none=True)
seen_tokens += rows_np.shape[0] * CONTEXT
seen_targets += count
row = {'step': step, 'epoch': epoch + 1, 'loss': total, 'lr': lr_at(step, total_steps),
'grad_norm': grad_norm, 'tokens': seen_tokens, 'targets': seen_targets}
if step % CFG['eval_every'] == 0 or step == total_steps:
row['val_loss'] = sft_loss(model, VAL_PACKED)
elapsed = time.perf_counter() - t_start
print(f"paso {step}/{total_steps} época {epoch + 1} pérdida {total:.4f} val {row['val_loss']:.4f} "
f"norma {grad_norm:.2f} lr {row['lr']:.2e} {seen_tokens / elapsed:,.0f} tokens/s", flush=True)
log.append(row)
with open(log_path, 'a', encoding='utf-8') as f:
f.write(json.dumps(row) + '\n')
save_checkpoint(step, epoch + 1)
train_seconds = time.perf_counter() - t_start
after, after_hs = evaluate(model, 'tras el ajuste')
hs_change = hs['paired'](after_hs, before_hs) # A = después, B = antes
results = {'base': base_meta, 'data': data_info, 'train_config': CFG, 'checkpoint': str(ckpt),
'compute': {'steps': step, 'tokens_processed': seen_tokens, 'supervised_targets': seen_targets,
'seconds': round(train_seconds), 'tokens_per_second': round(seen_tokens / train_seconds),
'device': torch.cuda.get_device_name() if DEVICE == 'cuda' else 'cpu',
'peak_gib': round(torch.cuda.max_memory_allocated() / 2**30, 2) if DEVICE == 'cuda' else None,
'flops_6nd': 6 * sum(p.numel() for p in model.parameters()) * seen_tokens},
'before': before, 'after': after, 'hellaswag_after_minus_before': hs_change,
'criteria': {'format_at_least_95': after['format']['ok'] >= 95,
'hellaswag_drop_below_1pt_ci': hs_change['ci95'][0] > -0.01},
'instructions': INSTRUCTIONS}
(OUT / 'results.json').write_text(json.dumps(results, ensure_ascii=False, indent=1), encoding='utf-8')
fb, fa = before['format'], after['format']
print(f"Ajuste: {step} pasos, {seen_tokens} tokens procesados, {seen_targets} objetivos, {train_seconds:.0f} s, "
f"pico {results['compute']['peak_gib']} GiB")
print(f"Formato: {fb['ok']} de {fb['n']} antes, {fa['ok']} de {fa['n']} después "
f"(Wilson 95 % de {fa['wilson95'][0]:.3f} a {fa['wilson95'][1]:.3f}); por tarea {fa['by_task']}")
print(f"HellaSwag acc_norm: {before['hellaswag']['acc_norm']:.4f} -> {after['hellaswag']['acc_norm']:.4f}, "
f"diferencia {100 * hs_change['difference']:+.2f} puntos, IC 95 % [{100 * hs_change['ci95'][0]:+.2f}, "
f"{100 * hs_change['ci95'][1]:+.2f}], McNemar p = {hs_change['mcnemar_p']:.3g}")
print(f"Pérdida de preentrenamiento: {before['pretrain_val_loss']:.4f} -> {after['pretrain_val_loss']:.4f}; "
f"SFT en validación: {before['sft_val_loss']:.4f} -> {after['sft_val_loss']:.4f}")
print(f"p(<|end|>) donde toca cerrar: {before['stop']['p_end']:.4f} -> {after['stop']['p_end']:.4f}; "
f"es el más probable en el {before['stop']['end_top1']:.1%} -> {after['stop']['end_top1']:.1%}")
print('Criterios del proyecto:', results['criteria'])
for i in (2, 37, 88):
print(repr(INSTRUCTIONS[i]), '->', repr(fa['replies'][i][:240]))npm run lab and open the connection link.The final cell writes the model card from results.json with Mitchell and colleagues’ nine sections, and chat.py, which loads the fine-tuned checkpoint with weights_only=True, checks that vocabulary and template IDs match those saved, and maintains conversation history. If history plus answer do not fit context, it drops the oldest exchanges. Before finishing it runs chat.py --once in a separate process to check operation outside the notebook.
"""Ficha del modelo a partir de las mediciones y programa de chat en terminal."""
import subprocess
import sys
def pct(x):
return f'{100 * x:.1f} %'
r = results
arch, d, c = r['base']['architecture'], r['data'], r['compute']
hs_b, hs_a, ch = r['before']['hellaswag'], r['after']['hellaswag'], r['hellaswag_after_minus_before']
fa = r['after']['format']
tasks = '\n'.join(f'| {t.format("X")} | {fa["by_task"][i]} de 10 |' for i, t in enumerate(TASKS))
card = f"""# Ficha del modelo: asistente p06 (SFT)
## Detalles del modelo
- GPT de p06-l03: {arch['layers']} bloques, {arch['heads']} cabezas, anchura {arch['d']}, contexto {arch['context']}; {sum(p.numel() for p in model.parameters()):,} parámetros.
- Vocabulario: BPE de bytes de p06-l02 ({tok.eot} IDs ordinarios y fin de documento) más 3 IDs de chat inicializados en la media de las filas existentes.
- Modelo base: `{Path(r['base']['checkpoint']).name}` (SHA-256 `{r['base']['sha256'][:16]}…`), paso {r['base']['step']}, {r['base']['tokens']} tokens de preentrenamiento.
- Plantilla: `<|endoftext|><|user|>…<|end|><|assistant|>…<|end|>`. Solo el código inserta los marcadores; el texto que los contiene se codifica como bytes ordinarios. Objetivos: contenido del asistente y su `<|end|>`.
- Ajuste: {c['steps']} pasos, {r['train_config']['epochs']} épocas, {r['train_config']['rows_per_step']} filas de {arch['context']} tokens por paso, tasa máxima {r['train_config']['lr']} con coseno, AdamW, recorte {r['train_config']['clip']}, dropout {r['train_config']['dropout']}, mezcla de preentrenamiento {r['train_config']['mix']}.
- Cómputo: {c['tokens_processed']:,} tokens procesados ({c['supervised_targets']:,} objetivos), {c['seconds']} s en {c['device']}, pico de memoria {c['peak_gib']} GiB, unos {c['flops_6nd']:.2e} FLOP (6ND).
## Uso previsto
- Estudio personal del ajuste a instrucciones y de su evaluación. Usuario previsto: quien lo entrenó.
- Fuera de alcance: cualquier respuesta en la que importe que sea cierta (hechos, medicina, derecho, finanzas), cualquier uso con otras personas y cualquier entrada no confiable.
## Factores
- Idioma: solo inglés en la práctica (FineWeb-Edu y UltraChat están en inglés).
- Longitud: contexto de {arch['context']} tokens propios, unos 2 KB de texto entre historia y respuesta.
- Tipo de instrucción: la tasa de formato se desglosa por las diez tareas del conjunto propio. No hay grupos de personas que desagregar en estas evaluaciones.
## Métricas
- Formato: fracción de las 100 instrucciones cuya respuesta voraz cierra con `<|end|>` en {MAX_NEW} tokens, sin otros marcadores y no vacía; intervalo de Wilson al 95 %.
- HellaSwag: `acc_norm` con el evaluador de p06-l07; diferencia emparejada después menos antes con intervalo al 95 % y McNemar exacto.
- Pérdidas: nats por token en {len(PT_WINDOWS)} ventanas de la validación de p06-l02 y nats por objetivo en la validación de SFT.
## Datos de evaluación
- 100 instrucciones propias (10 tareas por 10 temas), excluidas del entrenamiento.
- HellaSwag, validación: {hs_a['n']} filas, huella `{hs_a['rows_sha256'][:16]}…`.
- Validación de SFT: {d['val']['kept']} conversaciones de `{d['val_split']}` sin instrucciones repetidas del entrenamiento.
## Datos de entrenamiento
- {d['dataset']}, revisión `{d['revision']}`, licencia {d['license']}, split `{d['train_split']}`: {d['train']['kept']} de {d['train']['rows']} conversaciones leídas, {d['train']['tokens']:,} tokens, {d['train']['supervised']:,} objetivos.
- Filtros: roles alternos, sin turnos vacíos ni literales especiales, primera instrucción única, sin coincidencias con la evaluación; recorte al prefijo de intercambios que cabe en {d['context']} tokens. Descartes: {d['train']['dropped']}; intercambios recortados: {d['train']['exchanges_cut']}.
- Las conversaciones fueron generadas por ChatGPT según la ficha del conjunto: el estilo y los errores del generador se heredan.
## Análisis cuantitativos
| Medida | Antes | Después |
|---|---|---|
| Formato en 100 instrucciones | {pct(r['before']['format']['rate'])} | {pct(fa['rate'])} (Wilson 95 %: {pct(fa['wilson95'][0])} a {pct(fa['wilson95'][1])}) |
| HellaSwag acc_norm, {hs_a['n']} ejemplos | {hs_b['acc_norm']:.4f} | {hs_a['acc_norm']:.4f} |
| Pérdida de preentrenamiento (nats/token) | {r['before']['pretrain_val_loss']:.4f} | {r['after']['pretrain_val_loss']:.4f} |
| Pérdida SFT en validación (nats/objetivo) | {r['before']['sft_val_loss']:.4f} | {r['after']['sft_val_loss']:.4f} |
| Probabilidad media del cierre de turno donde toca, con forzado del profesor | {r['before']['stop']['p_end']:.4f} | {r['after']['stop']['p_end']:.4f} |
Cambio emparejado en HellaSwag: {100 * ch['difference']:+.2f} puntos, IC 95 % [{100 * ch['ci95'][0]:+.2f}, {100 * ch['ci95'][1]:+.2f}], McNemar p = {ch['mcnemar_p']:.3g}.
| Tarea | Formato después |
|---|---|
{tasks}
## Consideraciones éticas
- El modelo inventa hechos con la misma fluidez con que reproduce los ciertos, y el ajuste le ha enseñado a presentarlos con el tono seguro de un asistente.
- No se ha hecho ningún ajuste de seguridad ni evaluación de sesgos o toxicidad; los datos sintéticos pueden contener sesgos del modelo que los generó.
## Advertencias y recomendaciones
- La métrica de formato comprueba estructura, no corrección. No se han evaluado veracidad, seguridad ni sesgos: no hay evidencia sobre ellos.
- Las cifras proceden de una sola ejecución con una semilla; no miden la variación entre ejecuciones.
- Recomendación: usarlo solo para inspeccionar el comportamiento del ajuste y compararlo con el modelo base.
"""
(OUT / 'MODEL_CARD.md').write_text(card, encoding='utf-8')
CHAT = r'''"""Chat en terminal con el asistente de p06-l09. Uso: python chat.py [--once TEXTO] [--temperature T] [--top-k K]"""
import argparse, hashlib, json, math, os, sys
from pathlib import Path
import torch
HERE = Path(__file__).resolve().parent
ROOT = Path(os.environ.get('P06_PROJECT_ROOT', '__ROOT__'))
DATA = Path(os.environ.get('P06_DATA_DIR', '__DATA__'))
os.environ.setdefault('P06_SFT_DIR', str(HERE))
def cell(filename, title):
text = (ROOT / 'src/content/lessons/p06' / filename).read_text(encoding='utf-8')
return text.split('`' * 3 + f'python run runtime=local title="{title}"\n', 1)[1].split('\n' + '`' * 3, 1)[0]
lab = {'__name__': 'chat_p06_l09'} # sin las pruebas de la celda
exec(compile(cell('l09-ajuste-a-chat.mdx', 'Plantilla, tokenizador ampliado y empaquetador'), 'p06-l09.mdx', 'exec'), lab)
GPT, bpe = lab['load_previous'](ROOT)
state = torch.load(HERE / 'sft-model.pt', map_location='cpu', weights_only=True)
manifest = json.loads((DATA / 'manifest.json').read_text(encoding='utf-8'))
raw = (DATA / state['vocab_file']).read_bytes()
assert hashlib.sha256(raw).hexdigest() == state['vocab_sha256'] == manifest['vocab_sha256'], 'otro vocabulario'
payload = json.loads(raw)
tok = lab['ChatTokenizer'](bpe, {bytes.fromhex(k): v for k, v in payload['vocab_hex'].items()},
manifest['eot_id'], payload['special_literal'])
assert [tok.user, tok.assistant, tok.end] == state['template']['ids'], 'otra plantilla'
cfg = state['config']
device = 'cuda' if torch.cuda.is_available() else 'cpu'
model = GPT(vocab=cfg['vocab'], context=cfg['context'], layers=cfg['layers'], heads=cfg['heads'], d=cfg['d'], dropout=0.0)
model.load_state_dict(state['model'])
model.to(device).eval()
@torch.no_grad()
def answer(history, text, temperature, top_k, max_new, gen):
ids = tok.prompt(history, text)
while len(ids) + max_new > model.context and len(history) >= 2:
history = history[2:] # se olvidan los intercambios más antiguos
ids = tok.prompt(history, text)
if len(ids) + 1 > model.context:
return '[la pregunta no cabe en el contexto]', history
out = []
for _ in range(max_new):
if len(ids) >= model.context:
break
logits = model(torch.tensor([ids], device=device))[0, -1].float() / max(temperature, 1e-6)
if top_k:
logits[logits < torch.topk(logits, top_k).values[-1]] = -math.inf
nxt = int(torch.multinomial(torch.softmax(logits, -1).cpu(), 1, generator=gen))
if nxt == tok.end:
break
if nxt in tok.special_ids: # marcador fuera de lugar: se corta la respuesta
break
out.append(nxt)
ids.append(nxt)
text_out = tok.decode(out)
return text_out, history + [{'role': 'user', 'content': text}, {'role': 'assistant', 'content': text_out}]
def main():
p = argparse.ArgumentParser()
p.add_argument('--once')
p.add_argument('--temperature', type=float, default=0.7)
p.add_argument('--top-k', type=int, default=40)
p.add_argument('--max-new', type=int, default=300)
p.add_argument('--seed', type=int, default=0)
a = p.parse_args()
gen = torch.Generator().manual_seed(a.seed)
if a.once:
print(answer([], a.once, a.temperature, a.top_k, a.max_new, gen)[0])
return
print('Asistente p06 (modelo pequeño: inventa hechos). /reset borra la historia, /salir termina.')
history = []
while True:
try:
text = input('tú> ').strip()
except (EOFError, KeyboardInterrupt):
break
if text == '/salir':
break
if text == '/reset':
history = []
continue
if text:
reply_text, history = answer(history, text, a.temperature, a.top_k, a.max_new, gen)
print('asistente>', reply_text)
if __name__ == '__main__':
main()
'''
chat = OUT / 'chat.py'
chat.write_text(CHAT.replace('__ROOT__', ROOT.as_posix()).replace('__DATA__', DATA.as_posix()), encoding='utf-8')
check = subprocess.run([sys.executable, str(chat), '--once', 'What is gravity?', '--seed', '1'], capture_output=True,
text=True, encoding='utf-8', env=dict(os.environ, PYTHONUTF8='1'), timeout=600)
assert check.returncode == 0, check.stderr[-2000:]
print(card)
print('Prueba de chat.py --once:', repr(check.stdout.strip()[:300]))
print('Para conversar:', sys.executable, chat)npm run lab and open the connection link.What to expect and how to check it
The lab was verified end to end with two short runs. None of their figures is what your model will obtain, but they indicate what to inspect. The first used a 4-block GPT with width 256 and context 1024, 3.55 million parameters, pretrained for 600 updates of 16 384 tokens on the 2.2 million p06-l02 training tokens and saved in the p06-l06 copy format. It read 8000 train_sft and 300 test_sft conversations, evaluated HellaSwag on 1000 examples, and left other defaults unchanged.
- Data. 3757 of 8000 conversations survived. The remaining 4243, 53%, were discarded because not even their first exchange fit in 1024 custom tokens, and 7373 exchanges were trimmed from those retained. Retained conversations averaged 784 tokens, 71.4% targets. Packed, they fill 77.7% of 3704 rows, so the supervised fraction of processed tokens falls to 55%. This quantifies the previously described short-answer bias.
- Expansion. With real base-model states at 4096 positions, mean initialization gave mean divergence nats and maximum , below the 0.0058 bound. gave mean and maximum , harmless in this model because those rows are small relative to trained rows, mean norm 0.83. gave mean 15.9 nats and maximum 81: markers took almost all probability mass.
- Fine-tuning. 114 updates processed 7.47 million tokens and 4.14 million targets in 64 s. SFT validation loss fell from 3.832 to 3.642 and pretraining loss rose from 3.857 to 3.913: forgetting appears even in such a short adjustment. HellaSwag remained 0.268 before and after, with paired interval −1.84 to +1.84 points. With 1000 examples, the criterion “falls less than 1 point” cannot be claimed despite zero point difference, and the lab correctly marks it unmet.
- Format. 0 of 100 before and after. Probability of
<|end|>where closing was due rose from 0.0000 to 0.0009: at over 114 steps, the new row barely moved. Repeating fine-tuning at raised that probability to 0.196 and made<|end|>the most likely token at 38.9% of those positions, but format remained 0 of 100: greedy answers entered loops, repeating “2. Cober”, before reaching any closing point, and pretraining loss rose further to 3.970. The intermediate diagnostic detects this dissociation: the model learned to stop but generation never reaches the stopping point.
The second run checked full size: an untrained 12-block GPT with width 768, 86 238 720 parameters with the three new rows, 11 updates of 64 rows at microbatch 1, and 25% pretraining rows in the mix. Peak memory was 2.31 GiB and throughput about 9000 tokens per second on the laptop RTX 4060; chat.py --once loaded the checkpoint and responded from a separate process.
With defaults and short-run proportions, 54 000 conversations yield around 19.9 million tokens, roughly 25 000 rows, 390 updates per epoch and 780 total: about 51 million processed tokens and 28 million targets. At 9000 tokens per second that is a little over an hour and a half; the rate printed in the first few steps establishes the real estimate. Download occupies about 370 MB.
There are no published figures for this exact model, so expectations come from references with different scales and protocols:
- Forgetting. In InstructGPT, SFT reduced HellaSwag by 2.1, 0.1, and 2.8 points for 1.3-, 6-, and 175-billion-parameter models. The SmolLM2-135M-Instruct card, a similarly sized model pretrained on 2 trillion tokens, reports 42.1 HellaSwag for base and 40.9 for instruct, which adds DPO to SFT, using lighteval with different normalization from p06-l07: compare differences, not levels. A drop around one point is therefore typical, and the project’s requirement to demonstrate less than 1 point with its interval is demanding. With 10 042 examples and 10% changed outcomes, the point difference must exceed −0.38 points.
- Format and instructions. LIMA showed that a few hundred steps on 1000 examples can establish format in a 65-billion-parameter model that already knows much. At your scale generation is the risk: the same SmolLM2 card reports 29.9 on IFEval, measuring compliance with verifiable instructions such as “in two sentences” or “three facts”, so expect the model to close turns well before it reliably follows requests. The 95% format rate is a project goal, not a guaranteed result. If unmet, first inspect teacher-forced closing probability. If high while format is low, greedy-decoding loops are the problem; adjust steps or rate, not the metric.
How to check your result:
- First-cell tests pass: gradient exactly zero outside assistant targets, isolated conversation, and expansion bound.
- Expansion is harmless: the second cell prints maximum mean-initialization divergence below 0.0058 nats.
- Fine-tuning learns the intended behavior: SFT validation loss falls and closing probability rises from near zero to an appreciable fraction.
- Criteria are reported with uncertainty: format with Wilson interval, HellaSwag with paired difference and McNemar, and pretraining loss before and after, all in
results.jsonand the card.
Exercises
def build_labels(tokens, roles):
passInstruction tuning does not change the model’s task; it changes data and targets: the template with markers only code inserts, the loss mask deciding what it learns to produce, and the document mask deciding what context each position may use. Packing with document masking and reset positions is exactly equivalent to processing each conversation alone. What is gained, format, and what is lost, pretraining knowledge, are measured before and after using the same protocol, and the model card records both alongside what has not been measured.