Module contents
Lesson 15 of 26Core 110 min

Instruction tuning and supervised fine-tuning

Study instruction-response supervised fine-tuning, curated and synthetic datasets, chat templates, assistant-only loss, packing, and instruction-following evaluation.

After this lesson you can

  • Explain evidence from FLAN and T0 on multitask instruction tuning and transfer to held-out tasks.
  • Implement a role-based chat template and loss mask supervising assistant turns only.
  • Generate local Self-Instruct pairs and filter them for diversity and quality.
  • Perform full SFT of a 135M to 360M model within 8 GB using correct packing and masks.
  • Evaluate instruction following with verifiable constraints and detect regressions from the base model.

Before you start

From continuing text to answering

A base model predicts the next token from a document distribution. Given “Write a poem about the sea,” it might produce a poem, continue a list of instructions, or imitate another pretraining-compatible fragment. Supervised fine-tuning changes which continuations are more likely under a conversation format. It does not automatically make every answer true or erase prior learning.

Instruction tuning adapts a pretrained model on task descriptions and desired responses. The loss remains next-token prediction; what changes is the example distribution and often which positions are supervised. Apparently conversational behavior also depends on template, data, decoder, and later stages, not just the number of tuning steps.

FLAN tuned a 137,000-million-parameter model with instructions from over 60 natural-language-processing tasks. Under its study conditions it outperformed 175,000-million-parameter GPT-3 zero-shot on 20 of 25 evaluated tasks; ablations also studied dataset count, scale, and instruction wording. T0 turned supervised datasets into multiple readable templates and held task families out to assess transfer. Holding a task out of fine-tuning does not prove its texts or knowledge were absent during pretraining.

A held-out task group tests more demanding generalization than changing a few words of a training template. Results still depend on held-out families, mixture, shared data, base model, and metric. Do not infer that a few instructions teach any skill the model lacked. InstructGPT combined supervised demonstrations with preference and reinforcement stages; attributing all its behavior to SFT ignores part of the procedure.

A conversation is a token sequence

A chat template defines the contract between structured messages and the sequence processed by the model: delimiters, role names, line breaks, turn end, and generation prefix. Two templates with the same text can produce different IDs and probabilities. The inference engine must use the same contract as fine-tuning; adding a second BOS or changing a space can modify the prefix.

InteractiveInside a chat template

Each box is a token in an explicit 256-byte model with symbolic controls. The structure follows the cited templates, but IDs and segmentation are not those of Llama, Gemma or ChatML tokenizers. The dot indicates a space, ↵ a newline, and [xx] a hexadecimal byte.

Text is encoded as ordinary bytes and controls are inserted separately: typing their representation in the message does not create a control token. This separation limits role confusion but does not guarantee that the model obeys the instruction hierarchy.

With lossWithout lossSpecial control

Scroll the box to inspect the full sequence; you can also focus it and use the keyboard.

<|im_start|>system↵Responde·de·forma·breve.<|im_end|>↵<|im_start|>user↵[c2][bf]Cu[c3][a1]nto·es·2·+·2?<|im_end|>↵<|im_start|>assistant↵Son·4.<|im_end|>↵<|im_start|>user↵[c2][bf]Y·3·+·3?<|im_end|>↵<|im_start|>assistant↵Son·6.<|im_end|>↵

The proposed mask supervises assistant content and its end of turn, not its header. The generation prompt is excluded from loss; with Gemma 1 to 3 the system instruction is incorporated into the first user turn. Llama and Gemma trim whitespace at the ends of content; ChatML preserves it. The first token has no previous prediction. Llama 3 format · Gemma format · ChatML.

Teaching tokens
117
With loss
14
Without loss
103
Change the template and mask to observe the structure received by the model and supervised positions.

The interactive represents several families’ structure with an explicit teaching tokenizer. Its text units are not native Llama, Gemma, or ChatML tokens; they illustrate boundaries and masking. A real implementation must use the tokenizer and template of the specific model revision. Consult the template documentation and check real IDs, not just their visible representation.

Structure comes from typed messages, not concatenating arbitrary user text as a template. Some libraries recognize the literal spelling of a special token even with options preventing automatic token addition. Check tokenization of ordinary segments: collisions with all reserved markers can be rejected or escaped, and round-trip behavior must be tested. Rejecting a legitimate string is an availability tradeoff to document. Isolating delimiters reduces structural confusion; it does not prove that the model obeys an instruction hierarchy or eliminate prompt injection.

The mask decides what is directly learned

In a tokenized conversation x1,…,xTx_1,\ldots,x_T, let mt=1m_t=1 if target token xtx_t belongs to a supervised response and 00 otherwise. Assistant-only loss is

L(θ)=−∑t=2Tmtlog⁡pθ(xt∣x<t)∑t=2Tmt,∑t=2Tmt>0.\mathcal L(\theta)=-\frac{\sum_{t=2}^{T}m_t\log p_\theta(x_t\mid x_{<t})}{\sum_{t=2}^{T}m_t},\qquad \sum_{t=2}^{T}m_t>0.

System and user tokens remain in context and affect prediction even though their direct loss terms are excluded. In a multi-turn conversation, include content of every response you want to supervise and its end-of-turn token. Explicitly decide whether to supervise the assistant header too: it must match the prefix supplied at inference. If turn end is excluded or generation stops with another ID, the model can continue speaking or produce another role.

Causal implementations usually align logits at position t−1t-1 with the label at tt. A mask index applied before or after that shift must preserve the correspondence exactly. In PyTorch, −100 is the usual cross-entropy ignore value, not a vocabulary token. If an example has no valid targets, discard it or report the error before dividing by zero.

Training on prompts as well is not always “wrong,” but optimizes a different function: it increases pressure to imitate questions and system text. Compare objectives and outcomes at equal budget rather than attributing every difference solely to the mask. Count both processed tokens, which consume compute, and supervised tokens, which contribute to loss.

Packing without one example reading another

Concatenating short conversations reduces padding, but an ordinary causal mask lets the second attend to the first. For independent examples identify the segment sis_i of each position and use an additive attention mask

Aij={0si j≤i y si=sj,−∞en otro caso.A_{ij}=\begin{cases}0&\text{si }j\le i\text{ y }s_i=s_j,\\-\infty&\text{en otro caso.}\end{cases}

Reset position indices per conversation when reproducing separate processing, and avoid supervising an artificial cross-segment transition. Check how your architecture handles block masks and positions: some attention paths accept only particular representations. With dropout off, compare logits and summed loss for each separate conversation with its packed version. Allow device-appropriate numerical tolerance and compute the mean over the same total valid-token count.

Gradient accumulation has the same denominator problem. If microbatches have different supervised-token counts, averaging their mean losses equally is not the per-token mean loss. Accumulate loss sums and normalize by total valid targets in the effective batch. The packing mask and per-token accounting help verify equivalence.

Synthetic data and selection

Self-Instruct begins with seed tasks, asks a model to propose instructions and examples, filters outputs, and fine-tunes a model on the resulting pairs. Wang and colleagues started from 175 handwritten tasks and added a new instruction only if ROUGE-L similarity to every existing instruction was below 0.7. They also filtered duplicate or invalid examples. A lexical rule measures sequence overlap, not truth, difficulty, or semantic diversity.

Alpaca adapted an instruction-generation variant to tune LLaMA. A synthetic answer carries its teacher’s and generation template’s preferences and errors. Save model, revision, seed, prompt, original output, filter decisions, and provenance. Before comparing with a public mixture, equalize token count and training budget, separate evaluation questions, and check duplicates. Neither lexical filtering nor an embedding threshold guarantees absence of paraphrase contamination.

InteractiveDiversity of generated instructions

Loading the instruction projection.

Explore the real sample and change the filter without confusing embedding proximity with quality.

SFT data curation also matters with few examples. In LIMA, a 65,000-million-parameter LLaMA base model was tuned on 1,000 selected pairs, with 50 development examples and 300 test prompts. The authors hypothesized that much capability comes from pretraining and tuning teaches a useful format. The experiment shows what worked under its conditions; it does not prove SFT never teaches knowledge or that any thousand examples suffice.

InteractiveBase versus supervised fine-tuning

Preparing the measured comparison.

Compare actual responses generated for the same prompts and inspect their training steps.

Hyperparameters and evaluation

SFT is transfer: it starts from a model with prior knowledge, and rate, data, and update count can change or degrade other abilities. Record initialization, model revision, sequences, length, precision, effective batch, accumulation, optimizer, warmup, clipping, and seeds. An epoch on a small set can repeat answers many times; validate before continuing and do not interpret lower loss as a guarantee of better out-of-distribution answers.

NEFTune studied adding independent uniform noise to each embedding component during tuning: ϵij∼U(−1,1)\epsilon_{ij}\sim U(-1,1) and eij′=eij+αϵij/Lde'_{ij}=e_{ij}+\alpha\epsilon_{ij}/\sqrt{Ld} for length LL, dimension dd, and scale α\alpha. The expected squared noise norm for a sequence is exactly α2/3\alpha^2/3 under those assumptions; no noise is added at inference. Published results depend on model and data, so do not enable it without a comparison and validation set.

Instruction-following evaluation needs more than answer appearance. IFEval proposed 25 types of verifiable constraints and 541 prompts, some with multiple instructions. Separately report the fraction of satisfied instructions and prompts satisfying every constraint, plus strict or loose checking. A word, JSON, or character checker illustrates the mechanism but is not the full official benchmark.

Evaluate the base model and every checkpoint on the same held-out prompts under a fixed generation protocol. Inspect regressions in general tasks, length, format, termination, and factuality; a format checker does not validate content truth. For paired rate comparisons, retain each prompt’s result and associated uncertainty. Do not repeatedly choose data or hyperparameters on test and then present it as independent evaluation.

Lab: SFT with an assistant mask

This lab implements full SmolLM2-135M supervised fine-tuning. Data come from public train_sft and test_sft splits of UltraChat; the report saves revision and accepted-conversation hashes. Model and data are resolved from shared cache or downloaded from sources. You can supply ORYON_ULTRACHAT_JSONL with real rows, messages and split, to avoid downloading the sample again. Do not train on the evaluation set.

The template is defined by token segments: <|im_start|>, role, newline, content, <|im_end|>, and newline. Ordinary text containing the spelling of any special token is rejected; this avoids interpreting it as structure but can discard legitimate examples. The objective supervises assistant content and turn end only. Each packed conversation has its own causal attention and positions begin at zero. An initial test compares logits for two conversations separately and packed; it aborts if they differ. Accumulated gradient is normalized by total supervised-token count.

The report compares base and tuned models, saves UltraChat validation responses at intermediate steps, and evaluates assistant loss on held-out conversations. It also loads IFEval prompts only for final paired evaluation; they are not used to select a checkpoint. If the official instruction_following_eval package is installed, it runs strict and loose checkers and records per-prompt and per-instruction accuracy. Missing checkers are reported as unevaluated, not replaced with invented metrics. Paraphrases across corpora are not removed. ORYON_QUICK=1 reduces examples, steps, and prompts only to check flow; improved instruction following is not guaranteed. ORYON_SFT_MAX_UPDATES limits updates in both modes; zero removes that limit. The full checkpoint is saved by default. ORYON_SFT_SKIP_SAVE=1 skips saving and records that choice, allowing additional branches without storing weights but preventing later TRL comparison and independent IFEval of that branch. Use distinct output folders. PyTorch, Transformers, Datasets, Hugging Face Hub, and official Google Research code and dependencies for IFEval are required.

To install the official checkers in your environment, first run:

python -m pip install absl-py==2.5.1 langdetect==1.0.9 nltk==3.10.4 immutabledict==4.3.1
python -m nltk.downloader -d ./oryon-nltk-data punkt punkt_tab

Then download the four files from the pinned revision and verify their hashes:

from hashlib import sha256
from pathlib import Path
from urllib.request import urlopen

revision = 'e6890f85757dd84e27ca6df2dd30651dafad28e0'
expected = {
    'evaluation_lib.py': '35decc06000718487f44d7deafa6d3f48a8ec0886281edf40162c0265b7d248c',
    'instructions.py': '60e086f5342a03ce8e18b64bbcccf86308f523c08aa826707a562150a52f3edf',
    'instructions_registry.py': 'ec92d72c264f6d906978613085db262356174300370a3fffe6fefd5969ce9cfc',
    'instructions_util.py': 'a73797261eee5bf447e279d82a2b700b1bdd3cb1193412dbab1270a85832bc6b',
}
directory = Path('oryon-ifeval/instruction_following_eval')
directory.mkdir(parents=True, exist_ok=True)
base = 'https://raw.githubusercontent.com/google-research/google-research/'
for name, expected_hash in expected.items():
    url = base + revision + '/instruction_following_eval/' + name
    with urlopen(url, timeout=30) as response:
        data = response.read()
    if sha256(data).hexdigest() != expected_hash:
        raise ValueError('Hash incorrecto: ' + name)
    (directory / name).write_bytes(data)

In PowerShell, before opening the process that runs the cells, add the parent directory and NLTK data:

$env:PYTHONPATH = (Resolve-Path ./oryon-ifeval).Path + [IO.Path]::PathSeparator + $env:PYTHONPATH
$env:NLTK_DATA = (Resolve-Path ./oryon-nltk-data).Path

On Linux or macOS, set the same variables with export PYTHONPATH="$PWD/oryon-ifeval:$PYTHONPATH" and export NLTK_DATA="$PWD/oryon-nltk-data". Check that from instruction_following_eval import evaluation_lib imports successfully. If the library or a dependency is missing, the report declares IFEval unavailable.

IFEval uses the same limit for both models: 64 new tokens in QUICK and 2048 in the full run. ORYON_IFEVAL_MAX_NEW_TOKENS allows another positive integer. This is a token budget, not a guarantee of reaching a requested word count. The prompt and budget are checked against model context. Each response records whether it ended by EOS, limit, or another reason, and the report counts those reaching the limit without EOS; they remain in the official metric.

Official-checker seed is derived from the general seed and case key using SHA-256; both models use the same seed, then the previous random state is restored. ORYON_SFT_ACCUM changes microbatches per update: it must be positive and defaults to 2 in QUICK and 4 in the full run. Equal updates or documents do not guarantee equal supervised-token counts.

[ ]SFT with per-conversation attentionLocal GPU
"""SFT autocontenido de SmolLM2 con máscaras por turno y empaquetado aislado."""
import gc, hashlib, json, math, os, random
from pathlib import Path
from itertools import islice

import numpy as np
import torch
from torch.nn import functional as F
from datasets import load_dataset
from huggingface_hub import HfApi
from transformers import AutoModelForCausalLM, AutoTokenizer

QUICK = os.getenv('ORYON_QUICK') == '1'
OFFLINE = os.getenv('ORYON_OFFLINE') == '1'
OUT = Path(os.getenv('ORYON_SFT_DIR', './oryon-sft'))
LOCAL = os.getenv('ORYON_ULTRACHAT_JSONL', '')
MODEL = 'HuggingFaceTB/SmolLM2-135M'
MODEL_REV = '93efa2f097d58c2a74874c7e644dbc9b0cee75a2'
DATASET = 'HuggingFaceH4/ultrachat_200k'
DATA_REV = os.getenv('ORYON_SFT_DATA_REVISION', '')
IFEVAL_REV = os.getenv('ORYON_IFEVAL_REVISION', '')
IFEVAL_LOCAL = os.getenv('ORYON_IFEVAL_JSONL', '')
SEED = 1510
MAX_CONTEXT = 256 if QUICK else 1024
TRAIN_DOCS = 32 if QUICK else int(os.getenv('ORYON_SFT_DOCS', '5000'))
VAL_DOCS = 8 if QUICK else 128
EPOCHS = 1 if QUICK else 3
ACCUM = int(os.getenv('ORYON_SFT_ACCUM', '2' if QUICK else '4'))
if ACCUM < 1: raise ValueError('ORYON_SFT_ACCUM debe ser positivo')
MAX_UPDATES = int(os.getenv('ORYON_SFT_MAX_UPDATES', '4' if QUICK else '0'))
if MAX_UPDATES < 0: raise ValueError('ORYON_SFT_MAX_UPDATES debe ser no negativo')
IFEVAL_MAX_NEW_TOKENS = int(os.getenv('ORYON_IFEVAL_MAX_NEW_TOKENS', '64' if QUICK else '2048'))
if IFEVAL_MAX_NEW_TOKENS < 1: raise ValueError('ORYON_IFEVAL_MAX_NEW_TOKENS debe ser positivo')
N_EVAL = 8 if QUICK else 541
DEVICE = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
torch.set_num_threads(1)

def sha(text):
    return hashlib.sha256(text.encode('utf-8')).hexdigest()

def json_hash(value):
    return sha(json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(',', ':')))

def file_hash(path):
    digest = hashlib.sha256()
    with path.open('rb') as f:
        for part in iter(lambda: f.read(1024 * 1024), b''):
            digest.update(part)
    return digest.hexdigest()

def plain_ids(tokenizer, text):
    # Rechazar, en vez de interpretar, toda grafía registrada como token especial.
    if not isinstance(text, str):
        raise ValueError('El contenido del turno debe ser texto')
    forbidden = [item.content for item in tokenizer.added_tokens_decoder.values() if item.special]
    if any(marker and marker in text for marker in forbidden):
        raise ValueError('Un turno contiene la grafía de un token especial')
    ids = tokenizer.encode(text, add_special_tokens=False)
    special_ids = {i for i, item in tokenizer.added_tokens_decoder.items() if item.special}
    if any(i in special_ids for i in ids):
        raise ValueError('El tokenizador produjo un token de control desde texto ordinario')
    if tokenizer.decode(ids, skip_special_tokens=False, clean_up_tokenization_spaces=False) != text:
        raise ValueError('El contenido no admite ida y vuelta exacta')
    return ids

def render(tokenizer, messages, generation=False):
    start = tokenizer.convert_tokens_to_ids('<|im_start|>')
    end = tokenizer.convert_tokens_to_ids('<|im_end|>')
    if start != 1 or end != 2:
        raise ValueError('Esta plantilla exige los ID de SmolLM2')
    ids, labels = [], []
    for message in messages:
        role, text = message['role'], message['content']
        if role not in ('system', 'user', 'assistant'):
            raise ValueError('Rol no admitido')
        header = [start] + plain_ids(tokenizer, role + '\n')
        content = plain_ids(tokenizer, text)
        ids.extend(header + content + [end] + plain_ids(tokenizer, '\n'))
        labels.extend([-100] * len(header) + (content + [end] if role == 'assistant'
                                               else [-100] * (len(content) + 1))
                      + [-100] * len(plain_ids(tokenizer, '\n')))
    if generation:
        header = [start] + plain_ids(tokenizer, 'assistant\n')
        ids.extend(header); labels.extend([-100] * len(header))
    return ids, labels

def normalize_messages(row):
    messages = row.get('messages', [])
    result = []
    for m in messages:
        if (m.get('role') not in ('system', 'user', 'assistant')
                or not isinstance(m.get('content'), str) or not m['content'].strip()):
            raise ValueError('Formato de conversación desconocido')
        result.append({'role': m['role'], 'content': m['content']})
    if not result or not any(m['role'] == 'assistant' for m in result):
        raise ValueError('Conversación sin respuesta de asistente')
    return result

def prompt_fingerprints(messages):
    fingerprints = [sha(' '.join(m['content'].split()).casefold())
                    for m in messages if m['role'] == 'user']
    if not fingerprints: raise ValueError('Conversación sin turno de usuario')
    return fingerprints

def local_rows(path, split):
    with open(path, encoding='utf-8') as f:
        for line in f:
            row = json.loads(line)
            if row.get('split') == split:
                yield row

def data_source():
    if LOCAL:
        path = Path(LOCAL)
        if not path.is_file(): raise FileNotFoundError(path)
        digest = file_hash(path)
        return {'kind': 'jsonl local', 'sha256': digest}, lambda split: local_rows(path, split)
    if OFFLINE and not DATA_REV:
        raise ValueError('Sin red, fija ORYON_SFT_DATA_REVISION o proporciona ORYON_ULTRACHAT_JSONL')
    revision = DATA_REV or HfApi().dataset_info(DATASET, revision='main').sha
    if not revision: raise ValueError('No se pudo fijar la revisión del conjunto')
    def stream(split):
        return iter(load_dataset(DATASET, split=split, revision=revision, streaming=True))
    return {'kind': 'Hugging Face', 'id': DATASET, 'revision': revision,
            'license': 'MIT según la ficha del conjunto'}, stream

def collect(tokenizer, source, split, limit, banned):
    rows, rejected, seen = [], {}, set()
    for row in source(split):
        try:
            messages = normalize_messages(row)
            fingerprints = prompt_fingerprints(messages)
            if any(h in banned or h in seen for h in fingerprints):
                raise ValueError('solapamiento exacto de instrucciones')
            ids, labels = render(tokenizer, messages)
            if len(ids) > MAX_CONTEXT or sum(y != -100 for y in labels) == 0:
                raise ValueError('demasiado largo o sin objetivos')
            seen.update(fingerprints)
            rows.append({'id': row.get('prompt_id', json_hash(messages)),
                         'prompt_sha256': fingerprints, 'messages_sha256': json_hash(messages),
                         'messages': messages, 'ids': ids, 'labels': labels})
            if len(rows) == limit: break
        except ValueError as exc:
            key = str(exc); rejected[key] = rejected.get(key, 0) + 1
    if not rows: raise ValueError(f'No se obtuvieron conversaciones válidas en {split}')
    return rows, rejected

def packs(rows):
    result, current, length = [], [], 0
    for row in rows:
        n = len(row['ids'])
        if current and length + n > MAX_CONTEXT:
            result.append(current); current, length = [], 0
        current.append(row); length += n
    if current: result.append(current)
    return result

def batch(packed):
    ids, targets, positions, group = [], [], [], []
    for i, row in enumerate(packed):
        n = len(row['ids'])
        ids.extend(row['ids']); targets.extend(row['labels'])
        positions.extend(range(n)); group.extend([i] * n)
    ids = torch.tensor([ids], dtype=torch.long, device=DEVICE)
    targets = torch.tensor([targets], dtype=torch.long, device=DEVICE)
    positions = torch.tensor([positions], dtype=torch.long, device=DEVICE)
    groups = torch.tensor(group, device=DEVICE)
    same = groups[:, None] == groups[None, :]
    allowed = same & torch.ones_like(same, dtype=torch.bool).tril()
    return ids, targets, positions, allowed[None, None]

def token_loss(model, packed):
    ids, targets, positions, mask = batch(packed)
    logits = model(input_ids=ids, attention_mask=mask, position_ids=positions, use_cache=False).logits
    loss = F.cross_entropy(logits[:, :-1].float().reshape(-1, logits.shape[-1]),
                           targets[:, 1:].reshape(-1), ignore_index=-100, reduction='sum')
    count = int((targets[:, 1:] != -100).sum().item())
    if not count: raise ValueError('El paquete no tiene tokens supervisados')
    return loss, count

@torch.inference_mode()
def verify_packing(model, rows):
    if len(rows) < 2: raise ValueError('Se necesitan dos conversaciones para probar packing')
    first, second = rows[:2]
    if len(first['ids']) + len(second['ids']) > model.config.max_position_embeddings:
        raise ValueError('Dos conversaciones superan el límite del modelo en la prueba')
    model.eval()
    both_ids, _, both_pos, both_mask = batch([first, second])
    both = model(input_ids=both_ids, position_ids=both_pos, attention_mask=both_mask, use_cache=False).logits
    errors = []
    for row, offset in ((first, 0), (second, len(first['ids']))):
        ids, _, pos, mask = batch([row])
        separate = model(input_ids=ids, position_ids=pos, attention_mask=mask, use_cache=False).logits
        segment = both[:, offset:offset+len(row['ids'])]
        error = (segment.float() - separate.float()).abs()
        errors.append({'max_abs': float(error.max().item()), 'mean_abs': float(error.mean().item()),
                       'allclose': bool(torch.allclose(segment, separate, atol=2e-4, rtol=2e-4))})
    changed = both_ids.clone()
    changed[0, 0] = (int(changed[0, 0]) + 7) % model.config.vocab_size
    changed_logits = model(input_ids=changed, position_ids=both_pos, attention_mask=both_mask, use_cache=False).logits
    cross = (both[:, len(first['ids']):].float() - changed_logits[:, len(first['ids']):].float()).abs()
    cross_max = float(cross.max().item())
    print('Diagnóstico packing:', errors, 'máximo al alterar primer bloque:', cross_max, flush=True)
    if not all(row['allclose'] for row in errors) or cross_max > 1e-6:
        raise AssertionError('La prueba de aislamiento o comparación de logits falló')
    return {'packing_logits_verified': True, 'n1': len(first['ids']), 'n2': len(second['ids']),
            'logit_errors': errors, 'atol': 2e-4, 'rtol': 2e-4,
            'cross_block_change_max': cross_max, 'cross_block_atol': 1e-6,
            'dtype': str(both.dtype)}

@torch.inference_mode()
def validation_nll(model, rows):
    model.eval(); total = count = 0
    for row in rows:
        loss, n = token_loss(model, [row])
        total += float(loss.item()); count += n
    return {'nll_nats': total, 'assistant_tokens': count, 'nats_per_token': total / count}

def stop_reason(ids, max_new_tokens, eos_ids):
    if ids and ids[-1] in eos_ids: return 'eos'
    if len(ids) >= max_new_tokens: return 'limite'
    return 'otro'

@torch.inference_mode()
def generate(model, tokenizer, prompt, max_new_tokens=None):
    ids, _ = render(tokenizer, [{'role': 'user', 'content': prompt}], generation=True)
    if len(ids) > MAX_CONTEXT - 1: raise ValueError('Prompt de evaluación demasiado largo')
    if max_new_tokens is None: max_new_tokens = 64 if QUICK else 256
    if max_new_tokens < 1: raise ValueError('El límite de generación debe ser positivo')
    if len(ids) + max_new_tokens > model.config.max_position_embeddings:
        raise ValueError('Prompt y límite de generación superan el contexto del modelo')
    x = torch.tensor([ids], device=DEVICE)
    out = model.generate(x, do_sample=False, max_new_tokens=max_new_tokens,
                         eos_token_id=[0, 2], pad_token_id=0)
    result = out[0, x.shape[1]:].tolist()
    return {'text': tokenizer.decode(result, skip_special_tokens=True),
            'token_ids': result, 'ended_with': result[-1] if result else None,
            'stop_reason': stop_reason(result, max_new_tokens, [0, 2])}

def verify_ifeval(row, response):
    try:
        from instruction_following_eval import evaluation_lib
        import langdetect
    except ImportError:
        return {'available': False, 'reason': 'Falta el paquete oficial instruction_following_eval'}
    kwargs = [{k: v for k, v in x.items() if v is not None} for x in row['kwargs']]
    item = evaluation_lib.InputExample(key=row['key'], prompt=row['prompt'],
                    instruction_id_list=row['instruction_id_list'], kwargs=kwargs)
    lookup = {row['prompt']: response['text']}
    seed = int(json_hash([SEED, row['key']])[:8], 16)
    previous_rng, previous_langdetect = random.getstate(), langdetect.DetectorFactory.seed
    try:
        random.seed(seed); langdetect.DetectorFactory.seed = seed
        strict = evaluation_lib.test_instruction_following_strict(item, lookup)
        loose = evaluation_lib.test_instruction_following_loose(item, lookup)
    finally:
        random.setstate(previous_rng); langdetect.DetectorFactory.seed = previous_langdetect
    return {'available': True, 'instruction_ids': row['instruction_id_list'],
            'strict': strict.follow_instruction_list, 'loose': loose.follow_instruction_list,
            'failed_strict_ids': [key for key, passed in zip(row['instruction_id_list'], strict.follow_instruction_list) if not passed],
            'failed_loose_ids': [key for key, passed in zip(row['instruction_id_list'], loose.follow_instruction_list) if not passed]}

def sample_validation(model, tokenizer, rows):
    results = []
    for row in rows:
        prompt = next(m['content'] for m in row['messages'] if m['role'] == 'user')
        response = generate(model, tokenizer, prompt)
        response['verification'] = {'available': False, 'reason': 'Validación UltraChat sin verificadores IFEval'}
        results.append(response)
    return results

def official_ifeval(model, tokenizer, cases):
    try:
        from instruction_following_eval import evaluation_lib
    except ImportError:
        return {'available': False, 'reason': 'Falta el paquete oficial instruction_following_eval'}
    outputs = []
    for row in cases:
        response = generate(model, tokenizer, row['prompt'], IFEVAL_MAX_NEW_TOKENS)
        verification = verify_ifeval(row, response)
        outputs.append({'key': row['key'], 'response': response,
                        'strict': verification['strict'], 'loose': verification['loose']})
    result = {'available': True, 'cases': outputs,
              'truncated_at_limit': sum(x['response']['stop_reason'] == 'limite' for x in outputs)}
    for mode in ('strict', 'loose'):
        result[mode + '_prompt_accuracy'] = sum(all(x[mode]) for x in outputs) / len(outputs)
        result[mode + '_instruction_accuracy'] = sum(sum(x[mode]) for x in outputs) / sum(len(x[mode]) for x in outputs)
    return result

def main():
    random.seed(SEED); np.random.seed(SEED); torch.manual_seed(SEED)
    if DEVICE.type == 'cuda': torch.cuda.manual_seed_all(SEED)
    OUT.mkdir(parents=True, exist_ok=True)
    tok = AutoTokenizer.from_pretrained(MODEL, revision=MODEL_REV, local_files_only=OFFLINE)
    meta, source = data_source()
    if IFEVAL_LOCAL:
        path = Path(IFEVAL_LOCAL)
        with path.open(encoding='utf-8') as f:
            eval_rows = [json.loads(line) for line in f if line.strip()]
        eval_source = {'kind': 'jsonl local', 'sha256': file_hash(path),
                       'note': 'Comprueba que el archivo corresponda al conjunto oficial IFEval.'}
    else:
        if OFFLINE and not IFEVAL_REV:
            raise ValueError('Fija ORYON_IFEVAL_REVISION o usa ORYON_IFEVAL_JSONL sin red')
        eval_revision = IFEVAL_REV or HfApi().dataset_info('google/IFEval', revision='main').sha
        if not eval_revision: raise ValueError('No se pudo fijar la revisión de IFEval')
        eval_rows = load_dataset('google/IFEval', split='train', revision=eval_revision, streaming=True)
        eval_source = {'kind': 'Hugging Face', 'id': 'google/IFEval', 'revision': eval_revision}
    cases, eval_rejected = [], 0
    for row in eval_rows:
        try:
            ids, _ = render(tok, [{'role': 'user', 'content': row['prompt']}], generation=True)
            if len(ids) >= MAX_CONTEXT: raise ValueError('Prompt de evaluación largo')
            cases.append(row)
            if len(cases) == N_EVAL: break
        except ValueError:
            eval_rejected += 1
    if not cases: raise ValueError('IFEval sin preguntas')
    forbidden = {sha(' '.join(x['prompt'].split()).casefold()) for x in cases}
    val, val_rejected = collect(tok, source, 'test_sft', VAL_DOCS, forbidden)
    forbidden.update(h for x in val for h in x['prompt_sha256'])
    train, train_rejected = collect(tok, source, 'train_sft', TRAIN_DOCS, forbidden)
    sample_rows = val[:min(4, len(val))]
    checkpoint_prompts = [next(m['content'] for m in r['messages'] if m['role'] == 'user') for r in sample_rows]
    model = AutoModelForCausalLM.from_pretrained(MODEL, revision=MODEL_REV,
                         local_files_only=OFFLINE, dtype=torch.float32, attn_implementation='sdpa').to(DEVICE)
    print('Precisión de parámetros:', next(model.parameters()).dtype, flush=True)
    model.config.use_cache = False
    short = sorted(train, key=lambda x: len(x['ids']))
    check = verify_packing(model, short)
    if os.getenv('ORYON_SFT_DIAG_ONLY') == '1':
        print('Diagnóstico terminado:', check, flush=True)
        return
    packed_ids, packed_labels, packed_positions, _ = batch(short[:2])
    trl_batch = {'input_ids': packed_ids[0].tolist(), 'labels': packed_labels[0].tolist(),
                 'position_ids': packed_positions[0].tolist(),
                 'segment_lengths': [len(x['ids']) for x in short[:2]],
                 'message_sha256': [x['messages_sha256'] for x in short[:2]]}
    (OUT / 'sft-trl-batch.json').write_text(json.dumps(trl_batch, ensure_ascii=False), encoding='utf-8')
    del packed_ids, packed_labels, packed_positions
    before = {'validation': validation_nll(model, val),
              'samples': sample_validation(model, tok, sample_rows),
              'ifeval': official_ifeval(model, tok, cases)}
    model.train()
    if DEVICE.type == 'cuda': model.gradient_checkpointing_enable()
    optimizer = torch.optim.AdamW(model.parameters(), lr=2e-5, weight_decay=.01)
    log, snapshots, steps = [], [], 0
    packs_path = OUT / 'sft-training-packs.jsonl'
    pack_stream = packs_path.open('w', encoding='utf-8')
    sample_steps = {1, 2, 4} if QUICK else {25, 100, 300}
    for epoch in range(EPOCHS):
        order = list(train); random.Random(SEED + epoch).shuffle(order)
        groups = packs(order)
        optimizer.zero_grad(set_to_none=True); tokens = 0; processed = 0; batches = 0; nll_sum = 0.
        for i, pack in enumerate(groups):
            pack_stream.write(json.dumps({'epoch': epoch + 1, 'update': steps + 1,
                'input_ids': [x for row in pack for x in row['ids']],
                'labels': [x for row in pack for x in row['labels']],
                'segment_lengths': [len(row['ids']) for row in pack],
                'messages_sha256': [row['messages_sha256'] for row in pack]}) + '\n')
            # El gradiente se suma en unidades de pérdida, y se divide por el
            # número total de tokens al actualizar, no por microbatch.
            loss, n = token_loss(model, pack)
            nll_sum += float(loss.detach().item())
            loss.backward(); tokens += n; processed += sum(len(row['ids']) for row in pack); batches += 1
            if batches == ACCUM or i == len(groups)-1:
                for parameter in model.parameters():
                    if parameter.grad is not None: parameter.grad.div_(tokens)
                torch.nn.utils.clip_grad_norm_(model.parameters(), 1.)
                optimizer.step(); optimizer.zero_grad(set_to_none=True)
                steps += 1; log.append({'epoch': epoch + 1, 'step': steps, 'assistant_tokens': tokens,
                                        'processed_tokens': processed, 'microbatches': batches,
                                        'nll_nats_sum': nll_sum, 'nats_per_token': nll_sum / tokens})
                tokens = processed = batches = 0; nll_sum = 0.
                if steps in sample_steps:
                    model.eval()
                    snapshots.append({'step': steps, 'samples': sample_validation(model, tok, sample_rows)})
                    model.train()
                if MAX_UPDATES and steps >= MAX_UPDATES: break
        if MAX_UPDATES and steps >= MAX_UPDATES: break
    pack_stream.close()
    after = {'validation': validation_nll(model, val),
             'samples': sample_validation(model, tok, sample_rows),
             'ifeval': official_ifeval(model, tok, cases)}
    checkpoint = OUT / 'final'
    skip_save = os.getenv('ORYON_SFT_SKIP_SAVE') == '1'
    if not skip_save:
        model.save_pretrained(checkpoint, safe_serialization=True)
        tok.save_pretrained(checkpoint)
    report = {'model': MODEL, 'revision': MODEL_REV, 'quick': QUICK, 'seed': SEED,
              'checkpoint_saved': not skip_save,
              'data': meta, 'ifeval_source': eval_source, 'ifeval_rejected': eval_rejected,
              'ifeval_keys': [c['key'] for c in cases], 'ifeval_requested': N_EVAL,
              'train_ids': [x['id'] for x in train], 'validation_ids': [x['id'] for x in val],
              'train_messages_sha256': [x['messages_sha256'] for x in train],
              'validation_messages_sha256': [x['messages_sha256'] for x in val],
              'rejected_train': train_rejected, 'rejected_validation': val_rejected,
              'overlap_policy': 'Solo se excluyen coincidencias exactas tras normalización de espacios y mayúsculas; no detecta paráfrasis.',
              'prompts': checkpoint_prompts, 'sample_source': 'validación UltraChat test_sft',
              'sample_keys': [r['id'] for r in sample_rows], 'packing_check': check,
              'trl_batch_sha256': json_hash(trl_batch),
              'training_packs_sha256': file_hash(packs_path),
              'generation': {'seed': SEED, 'do_sample': False, 'max_new_tokens': 64 if QUICK else 256,
                             'eos_token_ids': [0, 2], 'template': '<|im_start|>user' + chr(10) + '{texto}<|im_end|>' + chr(10) + '<|im_start|>assistant' + chr(10)},
              'ifeval_generation': {'seed': SEED, 'do_sample': False, 'max_new_tokens': IFEVAL_MAX_NEW_TOKENS,
                             'eos_token_ids': [0, 2], 'template': '<|im_start|>user' + chr(10) + '{texto}<|im_end|>' + chr(10) + '<|im_start|>assistant' + chr(10),
                             'verifier_seed_rule': 'primeros 32 bits SHA-256 de [semilla, clave] para random y langdetect'},
              'before': before, 'after': after, 'snapshots': snapshots, 'training': log,
              'config': {'epochs': EPOCHS, 'context': MAX_CONTEXT, 'accumulation': ACCUM,
                         'max_updates': MAX_UPDATES, 'update_limit_reached': bool(MAX_UPDATES and steps >= MAX_UPDATES),
                         'optimizer': 'AdamW', 'lr': 2e-5, 'weight_decay': .01,
                         'clip': 1., 'dtype': 'float32', 'torch': str(torch.__version__)},
              'limitations': 'Evaluación corta y una semilla no demuestran mejoras generales ni ausencia de contaminación aproximada.'}
    (OUT / 'sft-report.json').write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding='utf-8')
    print('Packing:', json.dumps(report['packing_check'], ensure_ascii=False))
    print('Conversaciones train/validación:', len(report['train_ids']), len(report['validation_ids']))
    print('Actualizaciones:', len(report['training']), 'tokens procesados:', sum(s['processed_tokens'] for s in report['training']),
          'tokens supervisados:', sum(s['assistant_tokens'] for s in report['training']))
    print('NLL validación antes/después:', report['before']['validation'], report['after']['validation'])
    del model, optimizer; gc.collect()
    if DEVICE.type == 'cuda': torch.cuda.empty_cache()
    print('Informe:', OUT / 'sft-report.json')

if __name__ == '__main__':
    main()
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Repeat IFEval without retraining

After tuning, this optional cell sequentially reloads the base model and final checkpoint without retraining. It recovers the same IFEval keys and verifies local data hash where applicable. It needs the four official files, dependencies, and NLTK data installed above. Set ORYON_SFT_DIR to the tuning output folder and, if local data were used, ORYON_IFEVAL_JSONL to the same file. Without official checkers the cell does not run and the earlier report says IFEval was not evaluated. Separate output preserves responses, per-instruction results, hashes, and strict and loose accuracies; it must not select a checkpoint. Use IFEval configuration saved in the report; for older reports lacking it, recover general generation configuration. Record stop reason and number of responses reaching the limit without EOS. Progress is saved atomically after every case and resumes only with identical data, models, weights, checkers, configuration, and environment. The final report is created only when both models complete every case.

[ ]Official IFEval without retrainingLocal GPU
"""Evaluación IFEval emparejada de base y checkpoint SFT, sin reentrenar."""
import gc, hashlib, json, os, random
from pathlib import Path

import torch
import transformers
import langdetect
from datasets import load_dataset
from transformers import AutoModelForCausalLM, AutoTokenizer
from instruction_following_eval import evaluation_lib, instructions, instructions_registry, instructions_util

OUT = Path(os.getenv('ORYON_SFT_DIR', './oryon-sft'))
OFFLINE = os.getenv('ORYON_OFFLINE') == '1'
DEVICE = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
CODE_REVISION = 'e6890f85757dd84e27ca6df2dd30651dafad28e0'
EXPECTED_CODE_HASHES = {
    'evaluation_lib.py': '35decc06000718487f44d7deafa6d3f48a8ec0886281edf40162c0265b7d248c',
    'instructions.py': '60e086f5342a03ce8e18b64bbcccf86308f523c08aa826707a562150a52f3edf',
    'instructions_registry.py': 'ec92d72c264f6d906978613085db262356174300370a3fffe6fefd5969ce9cfc',
    'instructions_util.py': 'a73797261eee5bf447e279d82a2b700b1bdd3cb1193412dbab1270a85832bc6b',
}

def file_hash(path):
    h = hashlib.sha256()
    with Path(path).open('rb') as f:
        for part in iter(lambda: f.read(1024 * 1024), b''): h.update(part)
    return h.hexdigest()

def json_hash(value):
    return hashlib.sha256(json.dumps(value, ensure_ascii=False, sort_keys=True,
                                    separators=(',', ':')).encode('utf-8')).hexdigest()

def atomic_json(path, value):
    temporary = path.with_suffix(path.suffix + '.tmp')
    temporary.write_text(json.dumps(value, ensure_ascii=False, indent=2), encoding='utf-8')
    os.replace(temporary, path)

def plain_ids(tok, text):
    special = [(i, item.content) for i, item in tok.added_tokens_decoder.items() if item.special]
    if any(marker and marker in text for _, marker in special):
        raise ValueError('El prompt contiene la grafía de un token de control')
    ids = tok.encode(text, add_special_tokens=False)
    if any(i in {key for key, _ in special} for i in ids):
        raise ValueError('El texto ordinario produjo un token especial')
    if tok.decode(ids, skip_special_tokens=False, clean_up_tokenization_spaces=False) != text:
        raise ValueError('El prompt no es reversible')
    return ids

def build_prompt(tok, prompt):
    if tok.convert_tokens_to_ids('<|im_start|>') != 1 or tok.convert_tokens_to_ids('<|im_end|>') != 2:
        raise ValueError('Los ID no corresponden a la plantilla utilizada en SFT')
    return ([1] + plain_ids(tok, 'user\n') + plain_ids(tok, prompt) + [2]
            + plain_ids(tok, '\n') + [1] + plain_ids(tok, 'assistant\n'))

def stop_reason(ids, max_new_tokens, eos_ids):
    if ids and ids[-1] in eos_ids: return 'eos'
    if len(ids) >= max_new_tokens: return 'limite'
    return 'otro'

def ifeval_generation(report):
    config = report.get('ifeval_generation', report['generation'])
    budget = config['max_new_tokens']
    if not isinstance(budget, int) or isinstance(budget, bool) or budget < 1:
        raise ValueError('El límite de generación IFEval debe ser un entero positivo')
    return config

def load_cases(report):
    source = report['ifeval_source']
    if source['kind'] == 'jsonl local':
        local = os.getenv('ORYON_IFEVAL_JSONL', '')
        if not local or file_hash(local) != source['sha256']:
            raise ValueError('Se necesita el JSONL original con el mismo hash del informe')
        with open(local, encoding='utf-8') as f:
            rows = [json.loads(line) for line in f if line.strip()]
    elif source['kind'] == 'Hugging Face':
        rows = load_dataset(source['id'], split='train', revision=source['revision'], streaming=True)
    else:
        raise ValueError('Fuente IFEval desconocida')
    wanted = report['ifeval_keys']
    if not wanted or len(set(wanted)) != len(wanted):
        raise ValueError('Se necesitan claves IFEval distintas y no vacías')
    seen = {}
    for row in rows:
        if row['key'] in wanted:
            if row['key'] in seen: raise ValueError('Clave IFEval repetida')
            seen[row['key']] = row
    if len(seen) != len(wanted): raise ValueError('Faltan preguntas del informe original')
    return [seen[key] for key in wanted]

@torch.inference_mode()
def evaluate_case(model, tok, row, generation):
    model.eval()
    seed = int(json_hash([generation['seed'], row['key']])[:8], 16)
    random.seed(seed); langdetect.DetectorFactory.seed = seed
    input_ids = torch.tensor([build_prompt(tok, row['prompt'])], device=DEVICE)
    if input_ids.shape[1] + generation['max_new_tokens'] > model.config.max_position_embeddings:
        raise ValueError('Prompt y límite IFEval superan el contexto del modelo')
    output = model.generate(input_ids, do_sample=False,
                max_new_tokens=generation['max_new_tokens'],
                eos_token_id=generation['eos_token_ids'], pad_token_id=0)
    ids = output[0, input_ids.shape[1]:].tolist()
    text = tok.decode(ids, skip_special_tokens=True)
    kwargs = [{k: v for k, v in obj.items() if v is not None} for obj in row['kwargs']]
    example = evaluation_lib.InputExample(key=row['key'], prompt=row['prompt'],
                instruction_id_list=row['instruction_id_list'], kwargs=kwargs)
    lookup = {row['prompt']: text}
    strict = evaluation_lib.test_instruction_following_strict(example, lookup)
    loose = evaluation_lib.test_instruction_following_loose(example, lookup)
    return {'key': row['key'], 'response': text, 'token_ids': ids,
            'stop_reason': stop_reason(ids, generation['max_new_tokens'], generation['eos_token_ids']),
            'instruction_ids': row['instruction_id_list'],
            'strict': strict.follow_instruction_list, 'loose': loose.follow_instruction_list}

def summarize(results):
    summary = {'rows': results, 'truncated_at_limit': sum(r['stop_reason'] == 'limite' for r in results)}
    for mode in ('strict', 'loose'):
        prompt_correct = sum(all(r[mode]) for r in results)
        instruction_correct = sum(sum(r[mode]) for r in results)
        instruction_total = sum(len(r[mode]) for r in results)
        summary[mode + '_prompt_correct'] = prompt_correct
        summary[mode + '_prompt_total'] = len(results)
        summary[mode + '_instruction_correct'] = instruction_correct
        summary[mode + '_instruction_total'] = instruction_total
        summary[mode + '_prompt_accuracy'] = prompt_correct / len(results)
        summary[mode + '_instruction_accuracy'] = instruction_correct / instruction_total
    return summary

def main():
    modules = [evaluation_lib, instructions, instructions_registry, instructions_util]
    code_hashes = {Path(m.__file__).name: file_hash(m.__file__) for m in modules}
    if code_hashes != EXPECTED_CODE_HASHES:
        raise ValueError('Los archivos del verificador no coinciden con la revisión fijada')
    report_path = OUT / 'sft-report.json'
    report = json.loads(report_path.read_text(encoding='utf-8'))
    if report.get('checkpoint_saved') is False:
        raise ValueError('Este informe se creó con ORYON_SFT_SKIP_SAVE=1 y no tiene checkpoint; repite el ajuste sin esa opción para evaluar IFEval.')
    if not (OUT / 'final' / 'model.safetensors').is_file():
        raise FileNotFoundError('Falta final/model.safetensors: se necesita el checkpoint del ajuste para evaluar IFEval.')
    cases = load_cases(report)
    generation = ifeval_generation(report)
    identity = {'source_report_sha256': file_hash(report_path), 'dataset': report['ifeval_source'],
                'cases_sha256': json_hash(cases), 'keys': report['ifeval_keys'],
                'model': report['model'], 'revision': report['revision'],
                'sft_checkpoint_sha256': file_hash(OUT / 'final' / 'model.safetensors'),
                'verifier_revision': CODE_REVISION, 'verifier_files_sha256': code_hashes,
                'generation': generation, 'torch': str(torch.__version__),
                'transformers': transformers.__version__, 'device': str(DEVICE),
                'verifier_seed_rule': 'primeros 32 bits SHA-256 de [semilla, clave] para random y langdetect'}
    progress_path = OUT / 'sft-ifeval-progress.json'
    progress = {'identity': identity, 'rows': {'base': {}, 'sft': {}}}
    if progress_path.exists():
        progress = json.loads(progress_path.read_text(encoding='utf-8'))
        if progress.get('identity') != identity:
            raise ValueError('El progreso IFEval pertenece a otra ejecución; usa otra carpeta de salida')
        expected = {str(row['key']) for row in cases}
        if set(progress['rows']) != {'base', 'sft'} or any(not set(rows).issubset(expected) for rows in progress['rows'].values()):
            raise ValueError('Claves inesperadas en el progreso IFEval')
    torch.manual_seed(generation['seed'])
    if DEVICE.type == 'cuda': torch.cuda.manual_seed_all(generation['seed'])
    tok = AutoTokenizer.from_pretrained(report['model'], revision=report['revision'], local_files_only=OFFLINE)
    for label, identifier in [('base', report['model']), ('sft', str(OUT / 'final'))]:
        pending = [row for row in cases if str(row['key']) not in progress['rows'][label]]
        if not pending: continue
        options = {'local_files_only': OFFLINE if label == 'base' else True,
                   'dtype': torch.float32, 'attn_implementation': 'sdpa'}
        if label == 'base': options['revision'] = report['revision']
        model = AutoModelForCausalLM.from_pretrained(identifier, **options).to(DEVICE).eval()
        model.config.use_cache = False
        for row in pending:
            progress['rows'][label][str(row['key'])] = evaluate_case(model, tok, row, generation)
            atomic_json(progress_path, progress)
            print('IFEval', label, len(progress['rows'][label]), '/', len(cases), flush=True)
        del model; gc.collect()
        if DEVICE.type == 'cuda': torch.cuda.empty_cache()
    outputs = {label: summarize([progress['rows'][label][str(row['key'])] for row in cases])
               for label in ('base', 'sft')}
    result = {**identity, 'generation_source': 'ifeval_generation' if 'ifeval_generation' in report else 'generation (informe anterior)', 'results': outputs,
              'limitation': 'Solo las claves registradas y una generación greedy por modelo; no demuestra calidad general.'}
    path = OUT / 'sft-ifeval-report.json'
    if path.exists():
        previous = json.loads(path.read_text(encoding='utf-8'))
        if any(previous.get(key) != value for key, value in identity.items()):
            raise ValueError('El informe IFEval existente pertenece a otra ejecución; usa otra carpeta de salida')
    atomic_json(path, result)
    for label, output in outputs.items():
        print(label, 'prompts/instrucciones estrictos:', f"{output['strict_prompt_correct']}/{output['strict_prompt_total']}",
              f"{output['strict_instruction_correct']}/{output['strict_instruction_total']}",
              'laxos:', f"{output['loose_prompt_correct']}/{output['loose_prompt_total']}",
              f"{output['loose_instruction_correct']}/{output['loose_instruction_total']}",
              'truncados:', output['truncated_at_limit'], '/', len(cases), flush=True)
    print('Evaluación:', path, flush=True)

if __name__ == '__main__':
    main()
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

In a reduced check with three updates and eight held-out prompts, official checkers gave base and tuned models 1 of 8 prompts and 3 of 14 instructions correct under both strict and loose variants. All eight responses from each model reached the 64-token limit without termination. This checks execution and shows every output was truncated, but cannot establish equal model quality. The report retains each response and stop reason; repeat with a larger budget before interpreting the result.

Lab: local Self-Instruct

Local lab: Self-Instruct and diversity

The first cell generates instruction-response pairs with Qwen2.5-0.5B-Instruct. It starts from 50 explicit seed instructions, checks JSON format, and discards duplicates using ROUGE-L F1 against seeds and accepted candidates. Threshold 0.70 follows Self-Instruct, but generation, seeds, and quality filter are a reduced version, not an exact replica. Formal rules do not check correctness, safety, or semantic diversity; review pairs before training and do not run generated code.

By default it seeks 5,000 pairs with at most eight attempts per pair. ORYON_QUICK=1 limits the check to 40 proposals and 12 acceptances; ORYON_OFFLINE=1 requires cached models; ORYON_SELF_DIR chooses output folder. Teacher and E5 encoder load separately and both save revision and SHA256. Real E5 embeddings for up to 128 valid candidates and two-dimensional PCA are computed. If candidates are insufficient, the report states so and does not draw a fictitious projection. synthetic-sft.jsonl retains only accepted pairs.

[ ]Generate and filter instructionsLocal GPU
"""Generación local de instrucciones, filtro ROUGE-L y proyección de embeddings.

ORYON_QUICK=1 reduce el número de propuestas; ORYON_OFFLINE=1 exige caché.
ORYON_SELF_DIR elige el directorio de salida. No se ejecuta texto generado.
"""
import gc,hashlib,json,os,random,re,unicodedata
from pathlib import Path
import numpy as np
import torch
import transformers
from huggingface_hub import HfApi
from huggingface_hub.constants import HF_HUB_CACHE
from transformers import AutoModel,AutoModelForCausalLM,AutoTokenizer

SEED=1515; QUICK=os.getenv('ORYON_QUICK')=='1'; OFFLINE=os.getenv('ORYON_OFFLINE')=='1'
OUT=Path(os.getenv('ORYON_SELF_DIR','./oryon-self-instruct'))
DEVICE='cuda' if torch.cuda.is_available() else 'cpu'
TARGET=12 if QUICK else int(os.getenv('ORYON_SELF_COUNT','5000'))
if TARGET<1:raise ValueError('ORYON_SELF_COUNT debe ser positivo')
MAX_ATTEMPTS=40 if QUICK else TARGET*8
THRESHOLD=.7
TOPICS=['everyday science','history','writing','basic arithmetic','programming concepts','geography','health literacy','data analysis','music','environment']
TEMPLATES=['Explain a basic concept about {} for a beginner.',
           'Create a short question and answer about {}.',
           'Summarize three key ideas about {}.',
           'Compare two common approaches related to {}.',
           'Design a short practice activity about {}.']
SEEDS=[template.format(topic) for topic in TOPICS for template in TEMPLATES]
assert len(SEEDS)==50
torch.set_num_threads(1)

def sha(text):return hashlib.sha256(text.encode('utf-8')).hexdigest()
def words(text):return re.findall(r'\w+',unicodedata.normalize('NFC',text).casefold(),flags=re.UNICODE)
def rouge_l(a,b):
    if not a or not b:return 0.
    if len(a)<len(b):a,b=b,a
    previous=[0]*(len(b)+1)
    for x in a:
        current=[0]
        for j,y in enumerate(b,1):current.append(previous[j-1]+1 if x==y else max(previous[j],current[-1]))
        previous=current
    return 2*previous[-1]/(len(a)+len(b))

def max_similarity(tokens,pool,threshold=None):
    best=0.
    for old in pool:
        if threshold is not None and 2*min(len(tokens),len(old))/(len(tokens)+len(old))<threshold:continue
        best=max(best,rouge_l(tokens,old))
        if threshold is not None and best>=threshold:return best
    return best

def resolve(name):
    cache=Path(HF_HUB_CACHE)/('models--'+name.replace('/','--')); snaps=cache/'snapshots'; main=cache/'refs'/'main'
    if OFFLINE:
        choices=[x for x in snaps.iterdir() if x.is_dir()] if snaps.exists() else []
        revision=main.read_text(encoding='utf-8').strip() if main.exists() else (choices[0].name if len(choices)==1 else None)
        if not revision or not (snaps/revision).is_dir():raise FileNotFoundError(f'Snapshot local no identificado: {name}')
        return str(snaps/revision),revision,snaps/revision
    revision=HfApi().model_info(name,revision='main').sha
    if not revision:raise ValueError('No se pudo fijar la revisión')
    return name,revision,snaps/revision

def hashes(snapshot):
    pats=('config.json','tokenizer.json','tokenizer_config.json','special_tokens_map.json','*.safetensors','pytorch_model*.bin')
    files=sorted({p for pattern in pats for p in snapshot.glob(pattern) if p.is_file()}); result={}
    if not any(p.suffix in ('.bin','.safetensors') for p in files):raise FileNotFoundError('Faltan pesos del snapshot')
    for path in files:
        h=hashlib.sha256()
        with path.open('rb') as f:
            for block in iter(lambda:f.read(1048576),b''):h.update(block)
        result[path.name]=h.hexdigest()
    return result

def parse_object(text):
    decoder=json.JSONDecoder()
    for m in re.finditer(r'\{',text):
        try:
            obj,_=decoder.raw_decode(text[m.start():])
            if isinstance(obj,dict):return obj
        except json.JSONDecodeError:pass
    return None

def quality(obj):
    if not isinstance(obj,dict):return 'json_inválido'
    instruction=obj.get('instruction'); answer=obj.get('output')
    if not isinstance(instruction,str) or not isinstance(answer,str):return 'campos_ausentes'
    instruction=instruction.strip();answer=answer.strip();n=len(words(instruction))
    if not 5<=n<=50 or not 2<=len(words(answer))<=200:return 'longitud'
    if instruction.casefold()==answer.casefold():return 'respuesta_repite_instrucción'
    if any(x in instruction.casefold() or x in answer.casefold() for x in ('<|im_start|>','<|im_end|>','<|endoftext|>')):return 'marcador_de_control'
    return None

@torch.inference_mode()
def generate():
    name='Qwen/Qwen2.5-0.5B-Instruct';load_id,revision,snapshot=resolve(name)
    tok=AutoTokenizer.from_pretrained(load_id,revision=revision,local_files_only=OFFLINE)
    model=AutoModelForCausalLM.from_pretrained(load_id,revision=revision,local_files_only=OFFLINE,
                torch_dtype=torch.float16 if DEVICE=='cuda' else torch.float32).to(DEVICE).eval()
    fingerprint=hashes(snapshot);teacher={'id':name,'revision':revision,'sha256':fingerprint}
    signature=sha(json.dumps({'seeds':SEEDS,'topics':TOPICS,'threshold':THRESHOLD,'temperature':.8,'top_p':.9,
                              'max_new_tokens':180,'torch':str(torch.__version__),'transformers':transformers.__version__,
                              'device':DEVICE,'protocol':'self-instruct-v1'},ensure_ascii=False,sort_keys=True))
    progress_path=OUT/'self-progress.json';candidates=[];accepted=[];rejected={};attempts=0
    if progress_path.exists():
        progress=json.loads(progress_path.read_text(encoding='utf-8'))
        if progress['seed']!=SEED or progress['target']!=TARGET or progress['attempt_limit']!=MAX_ATTEMPTS or progress['teacher']!=teacher or progress.get('signature')!=signature:
            raise ValueError('El progreso pertenece a otra configuración o revisión; utiliza otro directorio')
        candidates=progress['candidates'];accepted=[row for row in candidates if row['accepted_07']]
        rejected=progress['rejected'];attempts=progress['attempts']
    pool=list(SEEDS)+[row['instruction'] for row in accepted];pool_words=[words(s) for s in pool]
    for attempt in range(attempts,MAX_ATTEMPTS):
        if len(accepted)>=TARGET:break
        topic=TOPICS[attempt%len(TOPICS)];examples=random.Random(SEED+100000+attempt).sample(pool,min(4,len(pool)))
        prompt=('Create one new safe instructional task and a helpful answer. Return only a JSON object with string keys '
                '"instruction" and "output". Topic requested: '+topic+'. Avoid medical diagnosis and personal data. '
                'The task must differ from these examples:\n'+'\n'.join('- '+s for s in examples))
        inputs=tok.apply_chat_template([{'role':'user','content':prompt}],tokenize=True,add_generation_prompt=True,return_tensors='pt',return_dict=True).to(DEVICE)
        torch.manual_seed(SEED+attempt)
        out=model.generate(**inputs,max_new_tokens=180,do_sample=True,temperature=.8,top_p=.9,pad_token_id=tok.eos_token_id)
        raw=tok.decode(out[0,inputs['input_ids'].shape[1]:],skip_special_tokens=True,clean_up_tokenization_spaces=False)
        obj=parse_object(raw);reason=quality(obj)
        if reason:rejected[reason]=rejected.get(reason,0)+1
        else:
            instruction=obj['instruction'].strip();output=obj['output'].strip();tokens=words(instruction)
            similarity=max_similarity(tokens,pool_words,THRESHOLD)
            row={'instruction':instruction,'output':output,'prompt':prompt,'raw_generation':raw,'topic_requested':topic,'first_word':tokens[0],
                 'words':tokens,'attempt':attempt,'generation_seed':SEED+attempt,'sha256':sha(instruction),
                 'accepted_07':similarity<THRESHOLD}
            candidates.append(row)
            if row['accepted_07']:
                accepted.append(row);pool.append(instruction);pool_words.append(tokens)
        attempts=attempt+1
        progress={'seed':SEED,'target':TARGET,'attempt_limit':MAX_ATTEMPTS,'teacher':teacher,'signature':signature,
                  'attempts':attempts,'candidates':candidates,'rejected':rejected}
        temporary=progress_path.with_suffix('.tmp')
        temporary.write_text(json.dumps(progress,ensure_ascii=False),encoding='utf-8');os.replace(temporary,progress_path)
    del model,tok;gc.collect()
    if DEVICE=='cuda':torch.cuda.empty_cache()
    return candidates,accepted,rejected,teacher,attempts

@torch.inference_mode()
def embed(candidates):
    if not candidates:return [],None
    name='intfloat/multilingual-e5-small';load_id,revision,snapshot=resolve(name)
    tok=AutoTokenizer.from_pretrained(load_id,revision=revision,local_files_only=OFFLINE)
    model=AutoModel.from_pretrained(load_id,revision=revision,local_files_only=OFFLINE).to(DEVICE).eval()
    fingerprint=hashes(snapshot); chunks=[]
    for start in range(0,len(candidates),16):
        batch=['query: '+x['instruction'] for x in candidates[start:start+16]]
        inputs=tok(batch,padding=True,truncation=True,max_length=256,return_tensors='pt').to(DEVICE)
        hidden=model(**inputs).last_hidden_state;mask=inputs['attention_mask'].unsqueeze(-1)
        pooled=(hidden*mask).sum(1)/mask.sum(1).clamp_min(1);pooled=torch.nn.functional.normalize(pooled,p=2,dim=1)
        chunks.append(pooled.cpu().float().numpy())
    matrix=np.concatenate(chunks);del model,tok;gc.collect()
    if DEVICE=='cuda':torch.cuda.empty_cache()
    if len(matrix)<2:return [],{'id':name,'revision':revision,'sha256':fingerprint,'note':'PCA requiere al menos dos candidatos'}
    centered=matrix-matrix.mean(0);u,s,vt=np.linalg.svd(centered,full_matrices=False);xy=centered@vt[:2].T
    if xy.shape[1]<2:xy=np.pad(xy,((0,0),(0,2-xy.shape[1])))
    for j in range(2):
        index=np.argmax(np.abs(vt[j])) if j<len(vt) else 0
        if j<len(vt) and vt[j,index]<0:xy[:,j]*=-1
    result=[]
    for row,point in zip(candidates,xy):result.append({**row,'x':float(point[0]),'y':float(point[1])})
    return result,{'id':name,'revision':revision,'sha256':fingerprint,'pooling':'media con máscara, L2; prefijo query:',
                   'projection':'PCA sobre embeddings de los candidatos mostrados, centrados; signo fijado',
                   'singular_values':[float(x) for x in s[:2]]}

def main():
    OUT.mkdir(parents=True,exist_ok=True);candidates,accepted,rejected,teacher,attempts=generate()
    points,encoder=embed(candidates[:128]);report={'seed':SEED,'quick':QUICK,'requested':TARGET,'attempt_limit':MAX_ATTEMPTS,'attempts':attempts,
         'device':DEVICE,'torch':torch.__version__,'transformers':transformers.__version__,
         'sampling':{'temperature':.8,'top_p':.9,'max_new_tokens':180,'seed_per_attempt':'1515 + attempt'},
         'threshold':THRESHOLD,'seed_instructions':SEEDS,'candidate_count':len(candidates),'accepted_count':len(accepted),
         'rejected':rejected,'teacher':teacher,'encoder':encoder,'points':points,
         'note':'El control de umbral reevalúa los primeros 128 candidatos válidos, en orden, con el corpus fijo; no regenera instrucciones.'}
    (OUT/'self-instruct-report.json').write_text(json.dumps(report,ensure_ascii=False,indent=2),encoding='utf-8')
    with (OUT/'synthetic-sft.jsonl').open('w',encoding='utf-8') as f:
        for row in accepted:
            r={'split':'train_sft','messages':[{'role':'user','content':row['instruction']},{'role':'assistant','content':row['output']}],
               'prompt_id':'synthetic-'+row['sha256'],'source':'Qwen Self-Instruct simplificado','generation_seed':row['generation_seed']}
            f.write(json.dumps(r,ensure_ascii=False)+'\n')
    print('Candidatos válidos:',len(candidates),'aceptados:',len(accepted),'rechazos:',rejected,flush=True)
    print('Salidas:',OUT,flush=True)

if __name__=='__main__':main()
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

The next cell prepares two files with the same number of candidate examples and a common public holdout. By default it streams HuggingFaceH4/ultrachat_200k; for offline work set ORYON_PUBLIC_JSONL to a file with train_sft rows and test_sft, messages, and prompt_id. It records source revision or hash and excludes exact instruction matches with the holdout. This does not exclude semantic matches.

[ ]Prepare a paired comparisonLocal GPU
"""Prepara dos archivos SFT pareados con una reserva pública compartida.

ORYON_PUBLIC_JSONL: JSONL público local con split train_sft/test_sft y messages.
Sin esa variable se usa UltraChat por streaming en una revisión fijada.
"""
import hashlib,json,os
from collections import Counter
from pathlib import Path
from tokenizers import Tokenizer
from huggingface_hub import hf_hub_download

OUT=Path(os.getenv('ORYON_SELF_DIR','./oryon-self-instruct'))
PUBLIC=os.getenv('ORYON_PUBLIC_JSONL','')
QUICK=os.getenv('ORYON_QUICK')=='1'
OFFLINE=os.getenv('ORYON_OFFLINE')=='1'
MODEL='HuggingFaceTB/SmolLM2-135M';REV='93efa2f097d58c2a74874c7e644dbc9b0cee75a2'
MAX_CONTEXT=256 if QUICK else 1024

def tokenizer():
    local=Path.home()/'.cache/huggingface/hub/models--HuggingFaceTB--SmolLM2-135M/snapshots'/REV/'tokenizer.json'
    path=local if local.exists() else Path(hf_hub_download(MODEL,'tokenizer.json',revision=REV,local_files_only=OFFLINE))
    return Tokenizer.from_file(str(path))

def token_counts(tok,messages):
    special=tok.get_added_tokens_decoder();ids_special={i for i,t in special.items() if t.special};markers=[t.content for t in special.values() if t.special and t.content]
    if tok.token_to_id('<|im_start|>')!=1 or tok.token_to_id('<|im_end|>')!=2:raise ValueError('Plantilla incompatible')
    def plain(text):
        if any(s in text for s in markers):raise ValueError('Marcador especial')
        ids=tok.encode(text,add_special_tokens=False).ids
        if any(i in ids_special for i in ids) or tok.decode(ids,skip_special_tokens=False)!=text:raise ValueError('Ida y vuelta incompatible')
        return ids
    total=0;supervised=0
    for m in messages:
        content=plain(m['content']);total+=1+len(plain(m['role']+'\n'))+len(content)+1+len(plain('\n'))
        if m['role']=='assistant':supervised+=len(content)+1
    if total>MAX_CONTEXT or not supervised:raise ValueError('Fuera de contexto o sin objetivos')
    return total,supervised

def norm(text):return ' '.join(text.split()).casefold()
def fingerprint(messages):
    return {hashlib.sha256(norm(m['content']).encode('utf-8')).hexdigest() for m in messages if m['role']=='user'}
def clean(row):
    messages=row.get('messages')
    if not isinstance(messages,list) or not messages: return None
    if any(not isinstance(m,dict) or m.get('role') not in ('system','user','assistant') or not isinstance(m.get('content'),str) or not m['content'].strip() for m in messages):return None
    if not any(m['role']=='user' for m in messages) or not any(m['role']=='assistant' for m in messages):return None
    return [{'role':m['role'],'content':m['content']} for m in messages]

def streams():
    if PUBLIC:
        path=Path(PUBLIC);raw=path.read_bytes();digest=hashlib.sha256(raw).hexdigest()
        def rows(split):
            with path.open(encoding='utf-8') as f:
                for line in f:
                    if line.strip():
                        row=json.loads(line)
                        if row.get('split')==split:yield row
        return rows,{'kind':'jsonl','sha256':digest}
    from datasets import load_dataset
    from huggingface_hub import HfApi
    name='HuggingFaceH4/ultrachat_200k';revision=os.getenv('ORYON_SFT_DATA_REVISION') or HfApi().dataset_info(name,revision='main').sha
    if not revision:raise ValueError('No se pudo fijar la revisión del conjunto público')
    def rows(split):return iter(load_dataset(name,split=split,revision=revision,streaming=True))
    return rows,{'kind':'Hugging Face','id':name,'revision':revision}

def main():
    path=OUT/'synthetic-sft.jsonl'
    with path.open(encoding='utf-8') as f:synthetic=[json.loads(line) for line in f if line.strip()]
    if not synthetic:raise ValueError('No hay instrucciones sintéticas aceptadas')
    tok=tokenizer();rows,origin=streams();seen=set();validation=[];rejections=[]
    def reject(row,stage,reason):
        digest=hashlib.sha256(json.dumps(row,ensure_ascii=False,sort_keys=True).encode('utf-8')).hexdigest()
        rejections.append({'stage':stage,'prompt_id':row.get('prompt_id'),'row_sha256':digest,'reason':str(reason)})
    for row in rows('test_sft'):
        messages=clean(row)
        if not messages:reject(row,'validación','formato');continue
        try:token_counts(tok,messages)
        except ValueError as exc:reject(row,'validación',exc);continue
        keys=fingerprint(messages)
        if keys&seen:reject(row,'validación','solapamiento exacto');continue
        seen.update(keys);validation.append({'split':'test_sft','messages':messages,'prompt_id':row.get('prompt_id','public-test-'+str(len(validation)))})
        if len(validation)>=(8 if QUICK else 128):break
    if not validation:raise ValueError('No hay reserva pública válida')
    clean_synthetic=[];used=set(seen)
    for row in synthetic:
        messages=clean(row)
        if not messages:reject(row,'sintético','formato');continue
        try:token_counts(tok,messages)
        except ValueError as exc:reject(row,'sintético',exc);continue
        keys=fingerprint(messages)
        if keys&used:reject(row,'sintético','solapamiento exacto');continue
        used.update(keys);clean_synthetic.append({'split':'train_sft','messages':messages,'prompt_id':row['prompt_id']})
    if not clean_synthetic:raise ValueError('No quedan ejemplos sintéticos distintos de la reserva')
    public=[];used=set(seen)
    for row in rows('train_sft'):
        messages=clean(row)
        if not messages:reject(row,'público','formato');continue
        try:token_counts(tok,messages)
        except ValueError as exc:reject(row,'público',exc);continue
        keys=fingerprint(messages)
        if keys&used:reject(row,'público','solapamiento exacto');continue
        used.update(keys);public.append({'split':'train_sft','messages':messages,'prompt_id':row.get('prompt_id','public-train-'+str(len(public)))})
        if len(public)>=len(clean_synthetic):break
    n=min(len(public),len(clean_synthetic))
    if not n:raise ValueError('Sin ejemplos públicos para comparar')
    for row in clean_synthetic[n:]:reject(row,'sintético','sin pareja pública')
    results={}
    for name,train in [('synthetic',clean_synthetic[:n]),('public',public[:n])]:
        content=''.join(json.dumps(row,ensure_ascii=False)+'\n' for row in train+validation)
        path=OUT/(name+'-paired.jsonl');path.write_text(content,encoding='utf-8')
        totals=[token_counts(tok,row['messages']) for row in train]
        results[name]={'path':str(path),'sha256':hashlib.sha256(content.encode('utf-8')).hexdigest(),'train_rows':len(train),'validation_rows':len(validation),
                       'processed_tokens':sum(x[0] for x in totals),'supervised_tokens':sum(x[1] for x in totals)}
    rejection_content=''.join(json.dumps(row,ensure_ascii=False)+'\n' for row in rejections)
    rejection_path=OUT/'comparison-rejections.jsonl';rejection_path.write_text(rejection_content,encoding='utf-8')
    report={'public_source':origin,'tokenizer':{'id':MODEL,'revision':REV,'max_context':MAX_CONTEXT},'pairs':n,'validation_shared':True,'outputs':results,
            'rejections':{'path':str(rejection_path),'sha256':hashlib.sha256(rejection_content.encode('utf-8')).hexdigest(),
                          'counts':dict(Counter(x['stage']+': '+x['reason'] for x in rejections))},
            'limitations':'Coincidencias exactas por turno, no similitud semántica; el entrenador puede rechazar ejemplos adicionales. Comprueba sus conteos, tokens y pasos antes de comparar.'}
    (OUT/'comparison-data.json').write_text(json.dumps(report,ensure_ascii=False,indent=2),encoding='utf-8')
    print('Parejas preparadas:',n,'reserva compartida:',len(validation),flush=True)

if __name__=='__main__':main()
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Run the earlier SFT cell twice, setting ORYON_ULTRACHAT_JSONL first to synthetic-paired.jsonl and then public-paired.jsonl, using different ORYON_SFT_DIR folders. Keep initial checkpoint, seeds, hyperparameters, holdout, and IFEval identical. In the reduced six-row-per-branch comparison, use ORYON_SFT_ACCUM=3 and ORYON_SFT_MAX_UPDATES=2 in both: all examples are processed in two updates, but the synthetic branch accumulates three microbatches then one, while the public branch accumulates three and three. Their lengths differ too, so processed and supervised tokens are not equalized. If only comparing reports, ORYON_SFT_SKIP_SAVE=1 avoids checkpoint storage; without them, TRL comparison and reevaluation cannot follow. Check surviving examples, steps, and processed and supervised tokens in both reports. These differences prevent attributing the result solely to data origin; a reduced run cannot establish general superiority of either source.

In a reduced run, both branches used six training conversations, six validation conversations, and two updates. Initial validation loss was 2.2579 nats per supervised token; afterward it was 2.2236 for synthetic and 2.2187 for public data. The synthetic branch processed 719 tokens, 576 supervised; the public branch processed 1,066, 548 supervised. Reports also show different microbatch allocation across updates. This sample checks the protocol but cannot attribute the difference solely to data origin or generalize it.

Lab: comparison with TRL

To compare a batch with TRL, first run the earlier lab and retain its report and sft-trl-batch.json. Install a compatible TRL version and dependencies. SFTTrainer receives the same explicit input_ids and labels, and a collator built here supplies the same block causal mask and reset positions. Default TRL packing is not assumed to isolate conversations.

The cell checks that the collator retains IDs, labels, and positions; computes manual mean loss on supervised targets; and compares it with TRL. It then traverses all recorded packs and updates: each entry groups an update’s microbatches, and a subclass of SFTTrainer sums their losses normalized by total supervised tokens. It uses the same AdamW over all parameters, constant rate, and clipping. Compare budgets, step losses, and final weights with the custom run. Some versions may miscount tokens if they sum the 4D attention mask: that sum counts attention pairs, not tokens. Reliable counts come from labels and the custom log. The result quantifies numerical differences for that run; it does not guarantee bitwise identity or equivalence to default TRL packing.

[ ]Compare a batch with TRLLocal GPU
"""Contraste de un lote empaquetado entre SFT manual y TRL SFTTrainer."""
import gc, hashlib, json, os
from pathlib import Path
import torch
from torch.nn import functional as F
from datasets import IterableDataset
from safetensors import safe_open
from transformers import AutoModelForCausalLM, AutoTokenizer

try:
    import trl
    from trl import SFTConfig, SFTTrainer
except ImportError as exc:
    raise ImportError('Instala una versión compatible de TRL y sus dependencias para ejecutar este contraste') from exc

OUT = Path(os.getenv('ORYON_SFT_DIR', './oryon-sft'))
OFFLINE = os.getenv('ORYON_OFFLINE') == '1'
DEVICE = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
MODEL = 'HuggingFaceTB/SmolLM2-135M'
REVISION = '93efa2f097d58c2a74874c7e644dbc9b0cee75a2'

def json_hash(value):
    encoded = json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(',', ':'))
    return hashlib.sha256(encoded.encode('utf-8')).hexdigest()

def collate(rows):
    if len(rows) != 1:
        raise ValueError('El contraste usa exactamente un paquete por microbatch')
    row = rows[0]
    lengths = row['segment_lengths']
    if not lengths or any(n <= 0 for n in lengths) or sum(lengths) != len(row['input_ids']):
        raise ValueError('Longitudes incompatibles')
    if len(row['labels']) != len(row['input_ids']):
        raise ValueError('Etiquetas incompatibles')
    ids = torch.tensor([row['input_ids']], dtype=torch.long)
    labels = torch.tensor([row['labels']], dtype=torch.long)
    positions = torch.tensor([sum((list(range(n)) for n in lengths), [])], dtype=torch.long)
    groups = torch.tensor(sum(([i] * n for i, n in enumerate(lengths)), []))
    same = groups[:, None] == groups[None, :]
    allowed = same & torch.ones_like(same, dtype=torch.bool).tril()
    return {'input_ids': ids, 'labels': labels, 'position_ids': positions,
            'attention_mask': allowed[None, None]}

def file_hash(path):
    h = hashlib.sha256()
    with path.open('rb') as f:
        for block in iter(lambda: f.read(1024 * 1024), b''): h.update(block)
    return h.hexdigest()

def groups_from_file(filename):
    current = None
    packs = []
    with open(filename, encoding='utf-8') as stream:
        for line in stream:
            row = json.loads(line)
            update = row['update']
            if current is None: current = update
            if update != current:
                yield {'packs': packs}
                packs, current = [], update
            packs.append({k: row[k] for k in ('input_ids', 'labels', 'segment_lengths')})
    if packs: yield {'packs': packs}

def group_collator(rows):
    if len(rows) != 1: raise ValueError('Cada entrada representa una actualización')
    return {'packs': rows[0]['packs']}

class ReplayTrainer(SFTTrainer):
    # Un batch del Trainer equivale a una actualización original completa.
    # No se usa el packing automático ni su acumulación por microbatch.
    def training_step(self, model, inputs, num_items_in_batch=None):
        model.train()
        packs = inputs['packs']
        total = sum(sum(x != -100 for x in p['labels'][1:]) for p in packs)
        if not total: raise ValueError('Actualización sin objetivos')
        sum_loss = 0.
        for pack in packs:
            batch = {k: v.to(self.accelerator.device) for k, v in collate([pack]).items()}
            with self.compute_loss_context_manager():
                loss = self.compute_loss(model, batch, num_items_in_batch=total)
            sum_loss += float(loss.detach().item())
            self.accelerator.backward(loss)
        self.replayed.append({'assistant_tokens': total, 'microbatches': len(packs),
                              'nats_per_token': sum_loss})
        return torch.tensor(sum_loss, device=self.accelerator.device)

def main():
    report = json.loads((OUT / 'sft-report.json').read_text(encoding='utf-8'))
    if report.get('checkpoint_saved') is False:
        raise ValueError('Este informe se creó con ORYON_SFT_SKIP_SAVE=1 y no tiene checkpoint; repite el ajuste sin esa opción para comparar con TRL.')
    if not (OUT / 'final' / 'model.safetensors').is_file():
        raise FileNotFoundError('Falta final/model.safetensors: se necesita el checkpoint del ajuste para comparar con TRL.')
    row = json.loads((OUT / 'sft-trl-batch.json').read_text(encoding='utf-8'))
    if json_hash(row) != report['trl_batch_sha256']:
        raise ValueError('El lote no corresponde al informe SFT')
    packs_path = OUT / 'sft-training-packs.jsonl'
    if file_hash(packs_path) != report['training_packs_sha256']:
        raise ValueError('Los paquetes no corresponden al informe SFT')
    reference_steps = report['training']
    group_count = 0
    for group, expected in zip(groups_from_file(str(packs_path)), reference_steps, strict=True):
        count = sum(sum(x != -100 for x in p['labels'][1:]) for p in group['packs'])
        processed = sum(len(p['input_ids']) for p in group['packs'])
        if (count != expected['assistant_tokens'] or processed != expected['processed_tokens']
                or len(group['packs']) != expected['microbatches']):
            raise AssertionError('El presupuesto registrado no coincide con los paquetes')
        group_count += 1
    if group_count != len(reference_steps) or not group_count:
        raise ValueError('No hay actualizaciones registradas')
    torch.manual_seed(report['seed'])
    tok = AutoTokenizer.from_pretrained(MODEL, revision=REVISION, local_files_only=OFFLINE)
    tok.pad_token = tok.eos_token
    model = AutoModelForCausalLM.from_pretrained(MODEL, revision=REVISION,
                local_files_only=OFFLINE, dtype=torch.float32, attn_implementation='sdpa').to(DEVICE)
    model.config.use_cache = False
    dataset = IterableDataset.from_generator(groups_from_file, gen_kwargs={'filename': str(packs_path)})
    args = SFTConfig(output_dir=str(OUT / 'trl-check'), max_steps=group_count,
        per_device_train_batch_size=1, gradient_accumulation_steps=1,
        learning_rate=2e-5, weight_decay=.01, max_grad_norm=1., lr_scheduler_type='constant',
        packing=False, max_length=None, dataset_kwargs={'skip_prepare_dataset': True},
        remove_unused_columns=False, bf16=False, fp16=False, report_to=[],
        save_strategy='no', logging_steps=1, seed=report['seed'],
        gradient_checkpointing=DEVICE.type == 'cuda')
    optimizer = torch.optim.AdamW(model.parameters(), lr=2e-5, weight_decay=.01)
    trainer = ReplayTrainer(model=model, args=args, train_dataset=dataset,
                            processing_class=tok, data_collator=group_collator,
                            optimizers=(optimizer, None))
    if trainer.accelerator.num_processes != 1:
        raise ValueError('Este contraste está definido para un solo proceso')
    trainer.replayed = []
    batch = collate([row])
    for name in ('input_ids', 'labels'):
        if batch[name].tolist() != [row[name]]:
            raise AssertionError(f'TRL alteró {name}')
    expected_positions = sum((list(range(n)) for n in row['segment_lengths']), [])
    if row['position_ids'] != expected_positions:
        raise AssertionError('Las posiciones guardadas no coinciden con las longitudes')
    if batch['position_ids'].tolist() != [expected_positions]:
        raise AssertionError('TRL alteró las posiciones')
    inputs = {name: tensor.to(DEVICE) for name, tensor in batch.items()}
    model.eval()
    with torch.no_grad():
        logits = model(input_ids=inputs['input_ids'], attention_mask=inputs['attention_mask'],
                       position_ids=inputs['position_ids'], use_cache=False).logits
        targets = inputs['labels'][:, 1:]
        count = int((targets != -100).sum())
        if not count:
            raise ValueError('El lote no contiene objetivos supervisados')
        reference = F.cross_entropy(logits[:, :-1].float().reshape(-1, logits.shape[-1]),
                                     targets.reshape(-1), ignore_index=-100, reduction='sum') / count
        trl_loss = trainer.compute_loss(model, dict(inputs))
        if not torch.allclose(reference, trl_loss, rtol=1e-5, atol=1e-6):
            raise AssertionError('Las pérdidas manual y TRL no coinciden')
    before = float(reference.item()); observed = float(trl_loss.item())
    del logits, inputs, batch, reference, trl_loss
    gc.collect()
    if DEVICE.type == 'cuda': torch.cuda.empty_cache()
    trainer.train()
    if trainer.state.global_step != group_count or len(trainer.replayed) != group_count:
        raise AssertionError('TRL no completó todas las actualizaciones')
    comparisons = []
    for expected, actual in zip(reference_steps, trainer.replayed, strict=True):
        comparisons.append({'step': expected['step'], 'manual_nats_per_token': expected['nats_per_token'],
                            'trl_nats_per_token': actual['nats_per_token'],
                            'absolute_difference': abs(expected['nats_per_token'] - actual['nats_per_token']),
                            'assistant_tokens': actual['assistant_tokens'], 'microbatches': actual['microbatches']})
    state = model.state_dict()
    max_error = 0.
    reference_path = OUT / 'final' / 'model.safetensors'
    with safe_open(str(reference_path), framework='pt', device='cpu') as checkpoint:
        keys = checkpoint.keys()
        for name in keys:
            if name not in state: raise ValueError(f'Parámetro no encontrado: {name}')
            error = (state[name].detach().float().cpu() - checkpoint.get_tensor(name).float()).abs()
            max_error = max(max_error, float(error.max().item()))
    result = {'trl_version': trl.__version__, 'model': MODEL, 'revision': REVISION,
              'batch_sha256': report['trl_batch_sha256'], 'assistant_tokens': count,
              'manual_nats_per_token': before, 'trl_nats_per_token': observed,
              'training_steps': trainer.state.global_step, 'step_comparisons': comparisons,
              'final_weight_max_abs_difference': max_error, 'compared_weight_tensors': len(keys),
              'scope': 'Recorrido completo de los paquetes registrados en un solo proceso; diferencias numéricas medidas, no se presupone igualdad bit a bit.',
              'note': 'Se usa la máscara explícita por bloques; no se presupone aislamiento del packing predeterminado de TRL. El conteo fiable se obtiene de labels, no de la suma de una máscara 4D.'}
    (OUT / 'trl-compare.json').write_text(json.dumps(result, ensure_ascii=False, indent=2), encoding='utf-8')
    print('NLL inicial manual / TRL:', result['manual_nats_per_token'], result['trl_nats_per_token'])
    print('Diferencias y recuentos por paso:', json.dumps(result['step_comparisons'], ensure_ascii=False))
    print('Máximo error en pesos:', result['final_weight_max_abs_difference'], 'tensores:', result['compared_weight_tensors'])
    del trainer, model
    if DEVICE.type == 'cuda': torch.cuda.empty_cache()
    print('Contraste:', OUT / 'trl-compare.json')

if __name__ == '__main__':
    main()
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Exercises

This cell checks the following exercise’s token counts. The quantities are exercise assumptions; real corpus lengths and supervised proportions vary.

[ ]PythonBrowser
conversaciones, longitud, epocas = 10_000, 600, 3
procesados = conversaciones * longitud * epocas
supervisados = procesados * 40 // 100
print("Tokens procesados:", procesados)
print("Tokens supervisados:", supervisados)
NumericProcessed budget
You train for 3 epochs on 10,000 conversations averaging 600 tokens. How many tokens are processed in total?
NumericSupervised budget
In the same 10,000 conversations of 600 tokens over 3 epochs, 40% of tokens are assistant targets. How many supervised tokens are processed in total?
QuizAn assistant that does not stop
After SFT, the model answers and continues generating turns. What is the strongest first investigation?
QuizInterpreting LIMA
Which conclusion is supported by the LIMA experiment?
CodeMask assistant turns
Implement build_assistant_mask(ids, template). Each complete turn in this teaching format is [start, role, sep, content..., end]. template is a dictionary with distinct integer IDs for start, end, sep, system, user, and assistant. Return a Boolean list of equal length: True only for each assistant turn's content and its end. Reject negative or non-integer IDs, duplicate markers, unknown roles, malformed headers, structural markers inside content, unclosed turns, and empty conversations with ValueError. An empty answer supervises its end.
def build_assistant_mask(ids, template):
  pass
Shift+Enter to run
CodeConstraint checkers
Implement verificar(texto, minimo, maximo). Count words with texto.split(), check whether all text is valid strict JSON and contains no ASCII comma. Return a dictionary with Boolean keys palabras, json, sin_comas, and todas, where todas is their conjunction. Reject non-text input, non-integer or negative limits, and minimo greater than maximo. JSON does not admit NaN or Infinity. This teaching checker is not the official IFEval benchmark.
def verificar(texto, minimo, maximo):
  pass
Shift+Enter to run
Key idea

SFT is a chain of contracts: data, template, mask, example isolation, stopping criterion, and evaluation. Check each with concrete tokens and outputs before attributing a change to model capability.