Emergent abilities and in-context learning
Study emergent abilities, metric-induced thresholds, capability prediction, and in-context learning, including sensitivity to examples and labels, data structure, and theoretical explanations.
After this lesson you can
- Define emergent ability and distinguish a metric threshold from a model discontinuity.
- Compare exact accuracy with continuous metrics for a family of open models.
- Predict task performance from pretraining loss or observational scaling laws and assess reliability.
- Measure in-context learning across example counts, order, and label correctness, and apply contextual calibration.
- Train small transformers on data with different burst structure and inspect in-context learning over training.
Before you start
Did an ability appear, or did the measurement rule change?
Imagine evaluating sums and counting an answer correct only if every digit matches. Gradual improvement in predicting individual digits can become a much steeper curve when the whole answer must be perfect. That matters when exact results are required, but alone does not prove the internal mechanism changed abruptly.
Wei and colleagues called an ability emergent when absent in small models and present in larger ones. Their examples include BIG-bench tasks, arithmetic, and learning from in-context examples. “Absent” needs an operational definition: chance level, metric, evaluation set, format, and statistical precision. A flat curve over a few sizes does not prove the correct-answer probability is exactly zero.
Metric-induced emergence occurs when a summary amplifies underlying improvement. Suppose an answer has tokens and each token is correct with probability independently of the rest. Expected fraction of correct tokens is , while expected exact match is . We have not assumed real answers satisfy independence: position dependence, carry errors, length, and tokenizer alter the calculation.
Even a continuous metric does not guarantee a smooth curve versus size: a model’s distribution can change abruptly, greedy decoding has discrete changes, and a small sample can hide a trend. Exact-match accuracy also serves a real need when one error invalidates output. Retain predictions, their probabilities, and several metrics simultaneously rather than choosing after the fact the one producing the most spectacular story.
Schaeffer, Miranda, and Koyejo showed with a mathematical model and several analyses that some emergence curves change under another metric or improved statistics. Their InstructGPT/GPT-3 analysis studied sums of two four-digit integers with two demonstrations. For four- or five-digit targets, accuracy appeared to jump while edit distance traced a different path on the same outputs. This does not show that every emergent ability is an artifact. Their fixed-output argument also does not permit changing questions, format, and decoding simultaneously and attributing the difference only to the metric.
The lab compares exact match of generations, edit distance, and probability measures under the correct answer as a forced prefix. Edit distance depends on the chosen representation. Per-token log probability describes how much the model favors the target answer under teacher forcing, not whether it would generate it completely. Multiclass Brier score compares the vocabulary distribution at each position with the observed token; lower is better. These quantities answer different questions and need not rank models identically.
Could it have been predicted?
Capability prediction estimates future performance from earlier observations rather than merely fitting a curve retrospectively. Du and colleagues used pretraining loss as an axis and observed similar loss-performance relationships for different size and data combinations under fixed corpus, tokenizer, and architecture conditions. They also found tasks with loss thresholds even under continuous metrics. On MMLU and C-Eval they compared accuracy, correct-option probability, and Brier. With four equally likely options, a uniform predictor gets Brier because . A reduction from a higher Brier score to that baseline may reflect better allocation among options without yet distinguishing answers from questions. A loss value is not a universal key: changing measured data or tokenization changes its meaning.
Ruan, Maddison, and Hashimoto built observational laws with around one hundred public models and a low-dimensional capability space. In their analyses, several apparently emergent curves admitted smooth predictions, and some complex tasks could be estimated from simpler evaluations. Results depend on available families, tasks, and data. Observational correlation does not establish that scaling compute has the same effect when corpus, architecture, or post-training changes.
To test a prediction, separate families or scales before fitting, freeze metric and format, and hold models out for evaluation. Compare a curve with simple alternatives and present uncertainty, residuals, and observed range. Points only near chance can be consistent with either later growth or a plateau. Do not retrospectively select the best-fitting threshold and present it as a forecast. Scaling-law extrapolation showed why a good in-range fit does not guarantee out-of-range accuracy.
An identifiability demonstration makes that warning concrete. Define as a capability score increasing with model improvement, and suppose three ideal observations at . The cell’s two explicit models coincide there and predict different values at . They are constructed functions for the argument, not real model data or a fit to the lab. A held-out point, more observations, or external assumptions may rule out an alternative; prior agreement alone does not choose between them.
def meseta(x):
return 0.5
def subida_tardia(x):
# Modelo ilustrativo en el intervalo [0.6, 0.9].
return 0.5 + 0.4 * (max(0.0, x - 0.8) / 0.1)**2
for x in (0.6, 0.7, 0.8, 0.9):
print(f"x={x:.1f} meseta={meseta(x):.2f} subida={subida_tardia(x):.2f}")
print("Brier uniforme, cuatro opciones:", (1-0.25)**2 + 3*0.25**2)Learning without updating weights
In-context learning is the change in predictive distribution when a frozen model is conditioned on input-output examples. It is evaluated on a new query: weights remain fixed while the prefix changes. “Without updating weights” does not mean no compute or working memory, and does not demonstrate which algorithm the transformer implements.
Compare zero examples with several context sizes and repeat for different sets and orders. Question sampling and example selection are distinct uncertainty sources. To compare conditions, use the same queries and, where possible, paired examples. Varying format and labels simultaneously confounds their effects. More examples also consume context window and may displace useful information; a decreasing curve does not imply learning is impossible.
Min and colleagues found that replacing labels with random alternatives barely degraded performance on a variety of classification and multiple-choice tasks in their study of twelve models. Examples still revealed input format, input distribution, and label set. The result does not say labels never matter. Jerry Wei and colleagues also studied inverted and semantically unrelated labels. In their families and tasks, sufficiently large models could follow the context mapping even when it contradicted usual label meaning. For example, text-davinci-002 mean accuracy against original labels fell from 90.3% with correct demonstrations to 22.5% with all inverted. They used 16 examples per class and 100 queries per set. Under the original reference, low accuracy can indicate that the model followed the inversion.
With inverted labels, state whether evaluation uses the original convention or the new context rule. A model faithfully following inversion can appear worse under the first and better under the second. Per-example random labels, a consistent permutation, and binary inversion test different hypotheses; do not treat all as “false labels”. It also matters whether a label is one token, how a multi-token answer is scored, and whether evaluation examples leak into context.
Bias and contextual calibration
A model can prefer a label because of frequency, position, or format even without query information. Zhao and colleagues estimated that bias using a content-free input such as “N/A” with the same format and examples. Let be probability normalized over candidate labels and the corresponding content-free probability. A diagonal correction is
This is a diagonal linear transformation of probabilities followed by renormalization, one case of the affine family studied in the paper. For the content-free input it produces a uniform distribution if all are positive. Numerically, use log space or impose a documented floor before normalization; the floor changes the transformation when a probability is very small. If the control input contains real signals or bias depends on the query, correction can worsen results. Measure calibration and accuracy on separate data and do not confuse removal of constant bias with a guarantee of calibrated probabilities.
What data structure favors context?
Data structure changes which solution is useful during pretraining. A burst groups class elements within a sequence; a long-tailed distribution yields many rare classes. If an association can change across sequences, memorizing a fixed label in weights no longer solves the task and attending to recent examples can help.
Chan and colleagues studied interactions among bursts, rare classes, changing meanings, and architecture. Some experiments showed a tradeoff between learning in context and in weights; with Zipfian distributions both could coexist. In a regime with 12,800 transformed-image classes and burst probability 0.9, both behaviors occurred at Zipf exponent 1: in-context learning on held-out classes and in-weight learning on the ten most common classes. This point depends on the experimental regime and is not universal. Context and weight measurements need not be the same task: one can reassign labels to held-out classes while another asks for known associations without support examples.
The next lab uses an explicit synthetic world, not natural-language examples. It saves curves by configuration, seed, and training point and separates seen and held-out classes. Singh and colleagues studied synthetic regimes where in-context learning appeared and then declined while training loss continued falling. A later accuracy decline can only be claimed if it appears in measured points with sufficient uncertainty control; no configuration guarantees transience. A curve can also vary with optimizer, capacity, mixture, and evaluation protocol. Grokking shares the idea that training and generalization can evolve on different timescales, but is not an automatic explanation.
The figure retains a real short run: with one seed and 120 steps, four measured burst/Zipf combinations ended with 51, 53, 57, and 56 in-context successes out of 128 episodes, respectively, in report configuration order. None exceeds 1/2 chance at that last point. A different in-weight association test obtained 44, 20, 14, and 15 successes out of 128; compare with the figure’s two baselines. These results check the workflow, not prove in-context learning impossible or reproduce a transient curve.
A Bayesian hypothesis, not identification of the mechanism
In a latent-task model, task determines the example distribution . A Bayesian predictor mixes task predictives:
For finitely many tasks, each with positive prior probability, and examples conditionally i.i.d. under the true task, compare each alternative through its likelihood ratio. If log ratios are integrable and every alternative has strictly positive Kullback-Leibler divergence relative to the truth, the strong law of large numbers gives
Therefore each alternative’s posterior mass tends to zero, that of tends to one, and for a bounded predictive distribution the mixture converges to the true task’s predictive. If two tasks generate the same example distribution, context cannot distinguish them by this argument. The proof assumes the true task is in the model and does not automatically cover infinite tasks, arbitrary dependence, or zero prior.
Xie and colleagues studied a more specific construction with hidden Markov model mixtures and long-term coherence. The calculation above illustrates an elementary sufficient condition, not their full theorem or proof that a real LLM is an exact Bayesian reasoner. Other complementary perspectives include attention as gradient descent under specific assumptions and induction heads as circuits copying continuations. Explaining behavior in a simplified model does not itself identify the causal mechanism in all models.
Lab: open-model sweep
Local lab: metrics and ICL in Pythia
Install torch, transformers, huggingface_hub, and numpy locally. Full mode evaluates Pythia 70M, 160M, 410M, 1B, and 1.4B; ORYON_PYTHIA_28=1 adds 2.8B only if free GPU memory permits and may require substantial RAM. Models load one at a time. Missing weights download to the shared cache.
For a bounded check without downloading, configure ORYON_QUICK=1, ORYON_OFFLINE=1, and ORYON_MODELS=14m; one scale cannot establish a scaling trend. ORYON_REVISION fixes a revision if the cache has multiple snapshots. Report oryon-pythia/pythia-report.json records models, revisions, hashes, prompts, predictions, denominators, and probabilities sufficient to reproduce aggregates. Results also depend on library versions, device, and precision.
Greedy generation is scored by exact match of the first complete number and token edit distance. Probability and Brier are computed with the correct answer under teacher forcing: Brier sums over the entire vocabulary and averages over tokens. ICL scores continuations of two labels, not free generation. Demonstrations and queries are separate; labels are assigned before pair permutation, and calibration divides probabilities by N/A input bias. Parity is a control, not a general benchmark.
"""Barrido reproducible de aritmética e ICL con modelos Pythia base.
Ejecución completa: python pythia_eval.py. ORYON_QUICK=1 reduce modelos y casos;
ORYON_OFFLINE=1 exige archivos en caché. ORYON_MODELS=14m limita a Pythia 14M.
ORYON_REVISION fija un snapshot; ORYON_PYTHIA_28=1 añade 2.8B si cabe.
El informe se guarda en ORYON_PYTHIA_OUT o ./oryon-pythia.
"""
import gc
import hashlib
import json
import math
import os
import random
import re
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 AutoModelForCausalLM, AutoTokenizer
QUICK = os.getenv('ORYON_QUICK') == '1'
OFFLINE = os.getenv('ORYON_OFFLINE') == '1'
OUT = Path(os.getenv('ORYON_PYTHIA_OUT', './oryon-pythia'))
DEVICE = 'cuda' if torch.cuda.is_available() else 'cpu'
SEED = 1401
MODELS = ['EleutherAI/pythia-14m', 'EleutherAI/pythia-70m'] if QUICK else [
'EleutherAI/pythia-70m', 'EleutherAI/pythia-160m', 'EleutherAI/pythia-410m',
'EleutherAI/pythia-1b', 'EleutherAI/pythia-1.4b',
]
if not QUICK and os.getenv('ORYON_PYTHIA_28') == '1':
MODELS.append('EleutherAI/pythia-2.8b')
if os.getenv('ORYON_MODELS'):
MODELS = [x.strip() if '/' in x else 'EleutherAI/pythia-' + x.strip()
for x in os.environ['ORYON_MODELS'].split(',') if x.strip()]
if not MODELS:
raise ValueError('ORYON_MODELS no contiene modelos.')
torch.set_num_threads(1)
def levenshtein(a, b):
previous = list(range(len(b) + 1))
for i, x in enumerate(a, 1):
current = [i]
for j, y in enumerate(b, 1):
current.append(min(current[-1] + 1, previous[j] + 1, previous[j - 1] + (x != y)))
previous = current
return previous[-1]
def resolve_model(name):
cache = Path(HF_HUB_CACHE) / ('models--' + name.replace('/', '--'))
requested = os.getenv('ORYON_REVISION')
if OFFLINE:
main = cache / 'refs' / 'main'
snapshots = cache / 'snapshots'
choices = [p for p in snapshots.iterdir() if p.is_dir()] if snapshots.exists() else []
revision = requested or (main.read_text(encoding='utf-8').strip() if main.exists() else None)
if revision is None and len(choices) == 1: revision = choices[0].name
path = snapshots / revision if revision else None
if not path or not path.is_dir():
raise FileNotFoundError(f'Snapshot local no identificado para {name}; fija ORYON_REVISION o descarga el modelo.')
return str(path), revision, path
revision = requested or HfApi().model_info(name, revision='main').sha
if not revision: raise ValueError(f'No se pudo fijar la revisión de {name}')
return name, revision, cache / 'snapshots' / revision
def file_hashes(snapshot):
patterns = ('config.json','tokenizer.json','tokenizer_config.json','special_tokens_map.json',
'*.safetensors','pytorch_model*.bin','*.safetensors.index.json')
files = sorted({p for pattern in patterns for p in snapshot.glob(pattern) if p.is_file()})
if not any(p.name.endswith(('.safetensors','.bin')) for p in files):
raise FileNotFoundError('No se encontraron los pesos en el snapshot resuelto.')
result = {}
for path in files:
h = hashlib.sha256()
with path.open('rb') as stream:
for block in iter(lambda:stream.read(1024*1024),b''): h.update(block)
result[path.name] = h.hexdigest()
return result
def make_items():
randomizer = random.Random(SEED)
pairs = randomizer.sample([(a, b) for a in range(10, 100) for b in range(10, 100)], 12 if QUICK else 100)
arithmetic = [{'a': a, 'b': b, 'answer': str(a + b)} for a, b in pairs]
train = randomizer.sample(range(100, 1000), 32)
candidates = [n for n in range(100, 1000) if n not in set(train)]
test = randomizer.sample(candidates, 8 if QUICK else 40)
return arithmetic, train, test
def encoded_pair(tok, prompt, continuation):
prefix = tok.encode(prompt, add_special_tokens=False)
full = tok.encode(prompt + continuation, add_special_tokens=False)
if not prefix or full[:len(prefix)] != prefix or len(full) == len(prefix):
raise ValueError('La continuación cambia la tokenización del prefijo; modifica el separador.')
return prefix, full
@torch.inference_mode()
def score(tok, model, prompt, continuation, brier=False):
prefix, full = encoded_pair(tok, prompt, continuation)
ids = torch.tensor([full], dtype=torch.long, device=DEVICE)
logits = model(ids).logits[0, len(prefix)-1:len(full)-1].float()
targets = ids[0, len(prefix):]
logp = torch.log_softmax(logits, dim=-1)
target_lp = logp.gather(1, targets[:, None])[:, 0]
result = {'sum_logp': float(target_lp.sum().item()), 'token_logp': target_lp.cpu().tolist(),
'target_ids': targets.cpu().tolist(), 'prefix_ids': prefix}
if brier:
probs = logp.exp()
result['token_brier'] = (probs.square().sum(dim=-1) - 2*probs.gather(1, targets[:, None])[:, 0] + 1).cpu().tolist()
del ids, logits, targets, logp, target_lp
return result
@torch.inference_mode()
def arithmetic_run(tok, model, items):
rows = []
for item in items:
prompt = f"Calculate the sum.\n{item['a']} + {item['b']} ="
answer = ' ' + item['answer']
reference = score(tok, model, prompt, answer, brier=True)
ids = torch.tensor([reference['prefix_ids']], dtype=torch.long, device=DEVICE)
generated = model.generate(ids, max_new_tokens=8, do_sample=False, pad_token_id=tok.eos_token_id)
generated_ids = generated[0, ids.shape[1]:].tolist()
text = tok.decode(generated_ids, skip_special_tokens=True)
match = re.match(r'^\s*([+-]?[0-9]+(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?)(?![0-9]|[.,][0-9]|[eE])', text)
extracted = match.group(1) if match else ''
if extracted:
prefix, full = encoded_pair(tok, prompt, ' ' + extracted)
output_ids = full[len(prefix):]
else:
output_ids = []
target_ids = reference['target_ids']
dist = levenshtein(output_ids, target_ids)
rows.append({**item, 'prompt':prompt, 'reference':answer, 'generated_text':text,
'generated_ids':generated_ids, 'extracted':extracted,
'extracted_ids':output_ids, 'exact':extracted == item['answer'],
'edit_distance':dist, 'edit_denominator':max(len(output_ids), len(target_ids)),
**reference})
return rows
def context(train, k, mode, order, trial):
selection = random.Random(SEED + 1000 + trial)
examples = selection.sample(train, len(train))[:k]
labels = random.Random(SEED + 2000 + trial)
result = []
for x in examples:
label = x % 2
if mode == 'inverted': label = 1-label
if mode == 'random': label = labels.randrange(2)
result.append({'x':x, 'label':label})
if order == 'shuffled':
random.Random(SEED + 3000 + trial).shuffle(result)
return result
def prompt_for(demos, query):
text = 'Classify each integer as even or odd.\n'
for item in demos:
text += f"Q: {item['x']}\nA: {'odd' if item['label'] else 'even'}\n"
return text + f'Q: {query}\nA:'
def normalize_pair(v):
m = max(v)
z = [math.exp(x-m) for x in v]
return [x/sum(z) for x in z]
@torch.inference_mode()
def icl_run(tok, model, train, test):
records = []
for shots in ([0, 2, 4] if QUICK else [0, 1, 2, 4, 8]):
for mode in ('correct', 'random', 'inverted'):
for order in ('fixed', 'shuffled'):
for trial in range(2 if QUICK else 3):
demos = context(train, shots, mode, order, trial)
content_free = prompt_for(demos, 'N/A')
base = [score(tok, model, content_free, ' '+label)['sum_logp'] for label in ('even','odd')]
for x in test:
prompt = prompt_for(demos, x)
logp = [score(tok, model, prompt, ' '+label)['sum_logp'] for label in ('even','odd')]
calibrated = [logp[i]-base[i] for i in range(2)]
pred = int(logp[1] > logp[0]); cal_pred = int(calibrated[1] > calibrated[0]); truth=x%2
records.append({'shots':shots,'mode':mode,'order':order,'trial':trial,'query':x,
'demos':demos,'prompt':prompt,'label':truth,'logp':logp,
'content_free_logp':base,'candidate_probs':normalize_pair(logp),
'pred':pred,'calibrated_pred':cal_pred,'correct':pred==truth,
'calibrated_correct':cal_pred==truth,
'consistent_correct':pred==(1-truth if mode=='inverted' and shots>0 else truth)})
return records
def main():
OUT.mkdir(parents=True, exist_ok=True)
arithmetic, train, test = make_items()
report = {'seed':SEED,'quick':QUICK,'device':DEVICE,'torch':torch.__version__,'transformers':transformers.__version__,
'items':{'arithmetic':arithmetic,'icl_train':train,'icl_test':test}, 'models':[],
'protocol':{'arithmetic':'suma de dos enteros de dos dígitos; greedy hasta 8 tokens; primer número completo debe coincidir con la respuesta entera canónica',
'edit':'distancia Levenshtein entre tokens de respuesta extraída y respuesta objetivo, dividida por la mayor longitud',
'scoring':'teacher forcing, suma y media sobre tokens de la respuesta; Brier multiclase sobre todo el vocabulario',
'icl':'paridad, demostraciones y consultas disjuntas; orden fijo o barajado, etiquetas correctas, aleatorias o invertidas',
'calibration':'restar log-probabilidades de candidatas bajo entrada N/A, equivale a dividir por el sesgo y renormalizar',
'limitations':'paridad es una tarea artificial; estas observaciones no generalizan a todas las tareas o familias'}}
for name in MODELS:
if name.endswith('2.8b') and (DEVICE != 'cuda' or torch.cuda.mem_get_info()[0] < 6.5*1024**3):
print('Se omite 2.8B: memoria GPU libre insuficiente.', flush=True); continue
load_id, revision, snapshot = resolve_model(name)
tok = AutoTokenizer.from_pretrained(load_id, revision=revision, local_files_only=OFFLINE)
model = AutoModelForCausalLM.from_pretrained(load_id, revision=revision, torch_dtype=torch.float16 if DEVICE=='cuda' else torch.float32,
local_files_only=OFFLINE).to(DEVICE).eval()
model.config.use_cache = True
hashes = file_hashes(snapshot)
row = {'model_id':name,'revision':revision,'tokenizer_revision':revision,'files_sha256':hashes,
'parameters':sum(p.numel() for p in model.parameters()),'vocab_size':model.config.vocab_size,
'arithmetic':arithmetic_run(tok,model,arithmetic),'icl':icl_run(tok,model,train,test)}
report['models'].append(row)
raw=json.dumps(report,ensure_ascii=False,indent=2)
(OUT/'pythia-report.json').write_text(raw,encoding='utf-8')
print(name, 'completado; informe SHA256',hashlib.sha256(raw.encode('utf-8')).hexdigest(),flush=True)
del model,tok;gc.collect()
if DEVICE=='cuda':torch.cuda.empty_cache()
if __name__ == '__main__':
main()npm run lab and open the connection link.Lab: synthetic burst tasks
This lab generates symbolic classes, not Omniglot images. Vectors and label assignments are reproducible and fixed throughout training. In-context evaluation classes are separate from training classes. Training sequences combine i.i.d. cases with cases where the query class and a second class each appear at least three times among eight examples. Per-class sampling weights follow a configurable Zipf exponent; in burst cases, sampling without replacement changes the final marginal distribution. This is an educational adaptation of Chan and colleagues, not a reproduction of their models or results.
To evaluate in-context learning, each episode presents two held-out classes, four examples per class, and randomly reassigned labels 0 and 1. Prediction is restricted to those labels: chance is 1/2. To evaluate in-weight learning, nine distinct classes are from training, so the query does not appear in context; prediction uses all labels. Uniform chance is 1/K. A predictor merely eliminating the eight labels seen in support and choosing uniformly from the rest reaches 1/(K-8), without identifying the class from its weights. Exceeding 1/K alone does not prove memorization. These are different tasks and baselines. The same held-out episodes are reused at all points of a curve without updating weights during evaluation, making points dependent.
The report contains successes, episode counts, binomial standard error, and 95% Wilson interval by condition, step, and seed. These uncertainties do not replace variation between training runs. Full mode sweeps bursts, exponents, and two seeds; ORYON_QUICK=1 only checks flow with fewer steps and one seed. No run guarantees observing emergence or transience. Set ORYON_BURST_DIR to choose output. Each completed training run is saved atomically and can resume with the same folder, code, data, and configuration; use a new folder if those conditions change.
"""Aprendizaje en contexto con clases simbólicas y secuencias con ráfagas."""
import os, json, math, gc, hashlib
from pathlib import Path
import numpy as np
import torch
from torch import nn
from torch.nn import functional as F
QUICK = os.getenv('ORYON_QUICK') == '1'
OUT = Path(os.getenv('ORYON_BURST_DIR', './oryon-burstiness'))
DEVICE = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
N_TRAIN, N_HOLD, FEATURE = (64, 64, 32) if QUICK else (512, 512, 64)
WIDTH, LAYERS, HEADS = (32, 2, 4) if QUICK else (64, 4, 4)
STEPS, BATCH, EVAL = (120, 16, 128) if QUICK else (10000, 64, 512)
INTERVAL = 30 if QUICK else 500
BURST_LEVELS = [0.0, 0.9] if QUICK else [0.0, 0.5, 0.9]
ZIPF_LEVELS = [0.0, 1.0] if QUICK else [0.0, 1.0, 2.0]
SEEDS = [1410] if QUICK else [1410, 1411]
DATA_SEED, EVAL_SEED = 1401, 1402
torch.set_num_threads(1)
def features():
rng = np.random.default_rng(DATA_SEED)
vectors = rng.normal(size=(N_TRAIN + N_HOLD, FEATURE)).astype(np.float32)
vectors /= np.linalg.norm(vectors, axis=1, keepdims=True)
labels = rng.permutation(N_TRAIN).astype(np.int64)
return vectors, labels
def training_batch(rng, batch, burst, exponent, labels):
probabilities = np.arange(1, N_TRAIN + 1, dtype=np.float64) ** (-exponent)
probabilities /= probabilities.sum()
ids = np.empty((batch, 9), dtype=np.int64)
for i in range(batch):
if rng.random() < burst:
query, other = rng.choice(N_TRAIN, size=2, replace=False, p=probabilities)
extras = rng.choice(N_TRAIN, size=2, replace=False, p=probabilities)
context = np.array([query] * 3 + [other] * 3 + list(extras), dtype=np.int64)
rng.shuffle(context)
ids[i] = np.r_[context, query]
else:
ids[i] = rng.choice(N_TRAIN, size=9, p=probabilities)
return ids, labels[ids[:, :8]], labels[ids[:, 8]]
def evaluation_batches(labels):
rng = np.random.default_rng(EVAL_SEED)
icl_ids = np.empty((EVAL, 9), dtype=np.int64)
icl_labels = np.empty((EVAL, 8), dtype=np.int64)
icl_targets = np.empty(EVAL, dtype=np.int64)
iwl_ids = np.empty((EVAL, 9), dtype=np.int64)
for i in range(EVAL):
pair = rng.choice(np.arange(N_TRAIN, N_TRAIN + N_HOLD), 2, replace=False)
assignment = rng.permutation(2)
order = rng.permutation(np.repeat(np.arange(2), 4))
q = int(rng.integers(2))
icl_ids[i] = np.r_[pair[order], pair[q]]
icl_labels[i] = assignment[order]
icl_targets[i] = assignment[q]
iwl_ids[i] = rng.choice(N_TRAIN, 9, replace=False)
return (icl_ids, icl_labels, icl_targets), (iwl_ids, labels[iwl_ids[:, :8]], labels[iwl_ids[:, 8]])
class Transformer(nn.Module):
def __init__(self):
super().__init__()
self.project = nn.Linear(FEATURE, WIDTH)
self.label = nn.Embedding(N_TRAIN, WIDTH)
self.position = nn.Parameter(torch.randn(17, WIDTH) * .02)
self.body = nn.ModuleList([
nn.TransformerEncoderLayer(WIDTH, HEADS, 4 * WIDTH, dropout=0,
batch_first=True, norm_first=True)
for _ in range(LAYERS)
])
self.norm = nn.LayerNorm(WIDTH)
self.head = nn.Linear(WIDTH, N_TRAIN)
def forward(self, vectors, ids, labels):
examples = self.project(vectors[ids])
sequence = torch.empty((len(ids), 17, WIDTH), device=ids.device)
sequence[:, 0::2] = examples
sequence[:, 1::2] = self.label(labels)
sequence = sequence + self.position
mask = torch.triu(torch.ones(17, 17, device=ids.device, dtype=torch.bool), diagonal=1)
for block in self.body:
sequence = block(sequence, src_mask=mask)
return self.head(self.norm(sequence[:, -1]))
@torch.inference_mode()
def measure(model, vectors, batch, two_way):
model.eval()
ids, labels, targets = batch
correct = 0
for start in range(0, len(ids), 64):
take = slice(start, start + 64)
x = torch.as_tensor(ids[take], device=DEVICE)
y = torch.as_tensor(labels[take], device=DEVICE)
target = torch.as_tensor(targets[take], device=DEVICE)
logits = model(vectors, x, y)
if two_way:
logits = logits[:, :2]
correct += int((logits.argmax(dim=-1) == target).sum().item())
model.train()
total = len(ids)
p = correct / total
z = 1.959963984540054
den = 1 + z * z / total
center = (p + z * z / (2 * total)) / den
margin = z * math.sqrt(p * (1 - p) / total + z * z / (4 * total * total)) / den
return {'correct': correct, 'total': total, 'accuracy': p,
'binomial_standard_error': math.sqrt(p * (1 - p) / total),
'wilson_95': [max(0., center - margin), min(1., center + margin)]}
def run_one(vectors, labels, heldout, burst, exponent, seed):
torch.manual_seed(seed)
if DEVICE.type == 'cuda':
torch.cuda.manual_seed_all(seed)
rng = np.random.default_rng(seed)
model = Transformer().to(DEVICE)
optim = torch.optim.AdamW(model.parameters(), lr=3e-4, weight_decay=.01)
data = torch.as_tensor(vectors, device=DEVICE)
history = []
for step in range(STEPS + 1):
if step % INTERVAL == 0 or step == STEPS:
icl = measure(model, data, heldout[0], True)
iwl = measure(model, data, heldout[1], False)
history.append({'step': step, 'icl_accuracy': icl['accuracy'], 'icl_correct': icl['correct'],
'icl_total': icl['total'], 'icl_se': icl['binomial_standard_error'], 'icl_wilson_95': icl['wilson_95'],
'iwl_accuracy': iwl['accuracy'], 'iwl_correct': iwl['correct'],
'iwl_total': iwl['total'], 'iwl_se': iwl['binomial_standard_error'], 'iwl_wilson_95': iwl['wilson_95']})
if step == STEPS:
break
ids, support, target = training_batch(rng, BATCH, burst, exponent, labels)
ids = torch.as_tensor(ids, device=DEVICE)
support = torch.as_tensor(support, device=DEVICE)
target = torch.as_tensor(target, device=DEVICE)
optim.zero_grad(set_to_none=True)
loss = F.cross_entropy(model(data, ids, support), target)
if not torch.isfinite(loss):
raise FloatingPointError('Pérdida no finita')
loss.backward()
torch.nn.utils.clip_grad_norm_(model.parameters(), 1.)
optim.step()
del model, optim, data, ids, support, target, loss
gc.collect()
if DEVICE.type == 'cuda':
torch.cuda.empty_cache()
return {'burstiness': burst, 'zipf': exponent, 'seed': seed, 'checkpoints': history}
def main():
OUT.mkdir(parents=True, exist_ok=True)
vectors, labels = features()
heldout = evaluation_batches(labels)
assert not np.intersect1d(heldout[0][0], np.arange(N_TRAIN)).size
assert all(row[-1] not in row[:-1] for row in heldout[1][0])
identity = {'resume_version': 2, 'quick': QUICK, 'train_classes': N_TRAIN,
'holdout_classes': N_HOLD, 'feature_dim': FEATURE,
'feature_hash': hashlib.sha256(vectors.tobytes()).hexdigest(),
'label_hash': hashlib.sha256(labels.tobytes()).hexdigest(),
'width': WIDTH, 'layers': LAYERS, 'heads': HEADS, 'steps': STEPS,
'batch': BATCH, 'eval': EVAL, 'interval': INTERVAL,
'burst_levels': BURST_LEVELS, 'zipf_levels': ZIPF_LEVELS,
'seeds': SEEDS, 'data_seed': DATA_SEED, 'eval_seed': EVAL_SEED,
'torch_version': str(torch.__version__), 'device': str(DEVICE),
'gpu': torch.cuda.get_device_name(DEVICE) if DEVICE.type == 'cuda' else None}
progress_path = OUT / 'burstiness-progress.json'
if progress_path.exists():
progress = json.loads(progress_path.read_text(encoding='utf-8'))
if progress.get('identity') != identity:
raise ValueError('Datos o configuración cambiados: usa otro directorio')
results = progress['runs']
else:
progress = {'identity': identity, 'runs': []}
results = progress['runs']
expected = [(b, z, s) for b in BURST_LEVELS for z in ZIPF_LEVELS for s in SEEDS]
if [(r['burstiness'], r['zipf'], r['seed']) for r in results] != expected[:len(results)]:
raise ValueError('Orden de ejecuciones incompatible con la configuración')
for burst in BURST_LEVELS:
for exponent in ZIPF_LEVELS:
for seed in SEEDS:
if len(results) > expected.index((burst, exponent, seed)):
continue
row = run_one(vectors, labels, heldout, burst, exponent, seed)
results.append(row)
tmp = progress_path.with_suffix('.tmp')
tmp.write_text(json.dumps(progress, ensure_ascii=False, indent=2), encoding='utf-8')
tmp.replace(progress_path)
print('Ráfaga', burst, 'Zipf', exponent, 'semilla', seed,
'último punto', row['checkpoints'][-1], flush=True)
report = {'source': 'Ejercicio simbólico inspirado en Chan et al. (2022), no Omniglot ni reproducción de sus resultados',
'paper': 'https://arxiv.org/abs/2205.05055',
'quick': QUICK, 'train_classes': N_TRAIN, 'holdout_classes': N_HOLD,
'icl_chance': .5, 'iwl_uniform_chance': 1 / N_TRAIN,
'iwl_support_exclusion_chance': 1 / (N_TRAIN - 8),
'feature_dim': FEATURE, 'features_sha256': hashlib.sha256(vectors.tobytes()).hexdigest(),
'labels_sha256': hashlib.sha256(labels.tobytes()).hexdigest(),
'data_seed': DATA_SEED, 'evaluation_seed': EVAL_SEED,
'steps': STEPS, 'batch': BATCH, 'evaluation_episodes': EVAL,
'model': {'width': WIDTH, 'layers': LAYERS, 'heads': HEADS, 'dropout': 0},
'execution': {'torch_version': str(torch.__version__), 'device': str(DEVICE),
'gpu': torch.cuda.get_device_name(DEVICE) if DEVICE.type == 'cuda' else None,
'optimizer': 'AdamW', 'learning_rate': 3e-4, 'weight_decay': .01,
'gradient_clip_norm': 1.},
'train': 'Ocho pares y consulta; con ráfaga hay tres apoyos de la clase de consulta y tres de otra, más dos muestras; sin ráfaga, nueve clases i.i.d. El peso de muestreo por clase sigue Zipf y la selección sin reemplazo puede modificar la frecuencia marginal de los casos con ráfaga. Etiquetas fijas por clase.',
'icl': 'Clases retenidas, cuatro ejemplos de cada una de dos clases, etiquetas 0/1 reasignadas por episodio; argmax solo entre 0 y 1; azar 1/2.',
'iwl': 'Nueve clases de entrenamiento distintas y uniformes, sin apoyo de la consulta; argmax sobre todas las etiquetas. Azar uniforme 1/K; un predictor que excluya las ocho etiquetas del apoyo alcanza 1/(K-8) sin identificar la clase por sus pesos.',
'caveat': 'Los intervalos por episodio no capturan variación entre semillas. No se presupone aprendizaje ni transitoriedad.',
'runs': results}
(OUT / 'burstiness-report.json').write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding='utf-8')
print('Informe:', OUT / 'burstiness-report.json', flush=True)
if __name__ == '__main__':
main()
npm run lab and open the connection link.Exercises
To check the first exercise’s probabilities, run the same formula with four values. Independence and fixed length are assumptions of the example, not general properties of a language model.
for p in (0.6, 0.8, 0.9, 0.95):
print(f"p={p:.2f}: p^5={p**5:.9f}")Step 1 of 3. What happens to the log posterior ratio of an alternative to the true task, divided by n?
import numpy as np
def calibrar(p, q, eps=1e-12):
pass
A capability depends on how you ask and measure. To find what really changed, retain distributions, use context controls, and test predictions on data not used to construct them.