Review and roadmap: from language model to foundation model
Review autoregressive factorization, per-token cross-entropy, perplexity, bits per byte, and the decoder-only GPT from module 18. Define a foundation model and map the full lifecycle of a modern LLM.
After this lesson you can
- Write the sequence log-likelihood under autoregressive factorization and convert nats per token to perplexity and bits per byte.
- Use the definition by Bommasani and colleagues to distinguish a foundation model from a model trained for a single task.
- Express a task in text-to-text form and evaluate a base model in zero-shot and few-shot settings.
- Place each LLM lifecycle stage, from data and tokenization through training and evaluation, and understand its relative compute cost.
- Load a small base model on the local GPU and inspect its tokenizer, parameter allocation, and next-token distribution.
Before you start
One prediction, many tasks
Completing a sentence, translating, and writing code appear to be different tasks. A causal language model takes a prefix and assigns a distribution to the next token. Repeating this operation lets it continue a sequence describing any of these tasks. The ability to continue a format does not guarantee that it follows instructions, knows a recent fact, or produces a reliable answer. These differences depend on pretraining, adaptation, and evaluation, as well as the next-token equation.
In this lesson we connect the GPT built earlier to the lifecycle of an LLM. To distinguish capabilities from formats, we will measure the probability the model assigns to known text and also observe what it generates from a prefix.
Probability of a sequence
Consider a token sequence and an explicit initial context , which may include a beginning-of-sequence token. The chain rule gives
Maximizing this log-likelihood is equivalent to minimizing empirical cross-entropy. If a batch contains sequences of different lengths, sum the losses over all evaluated tokens and divide by the total number of tokens. Averaging each sequence first and then averaging those results gives short and long sequences equal weight. State which positions are context, which are scored, and whether special tokens are included.
During training, a decoder-only model receives the shifted sequence and computes the logits at its positions in parallel. The causal mask prevents a position from seeing future tokens. During generation, each sample appends a token to the prefix and the next distribution depends on what has already been generated. A key-value cache avoids recomputing some of the work, while reading the context still has a cost.
Nats, perplexity, and bits per byte
For total loss in nats, scored tokens, and UTF-8 bytes of scored text, define
Perplexity is the exponential of the mean loss per token, rather than the number of possible words. Changing the tokenizer changes the unit in the denominator: a lower PPL does not guarantee better compression of the same text. To compare bits per byte, use the exact same string, normalization, split, context, and scoring protocol. A UTF-8 character can use several bytes, so counting characters is different from counting bytes.
Even under those conditions, the score is for the token sequence chosen by the tokenizer. If several token sequences decode to the same string, it is not automatically the marginal probability of the string summed over all of them. Bits per byte also do not control for differences in training data or architecture.
From pretraining to a foundation model
In the formulation of Bommasani and colleagues, a foundation model is trained on broad data and can be adapted to many downstream tasks. The self-supervised objective and scale enable representations to be reused, but do not make every output verified knowledge. Homogenization means that many applications can depend on the same base model and share its benefits and errors. Emergence describes capabilities or behaviors observed as scale or the system changes. Their appearance also depends on measurement and does not prove an inexplicable jump.
A base model continues text according to its distribution. Later stages add role and behavior conventions to an adapted assistant. A conversational formatting failure alone does not show that the base model lacks useful information. Likewise, producing a plausible answer does not establish understanding or correctness.
Tasks as text and in-context learning
A translation can be represented as Español: gato\nInglés: and a classification as Texto: ...\nEtiqueta:. In zero-shot the task is given without labeled examples in context. One-shot includes one example and few-shot includes several. Weights are not updated during this inference. Changing the examples, order, or format can change the result. Evaluation requires separating demonstrations from test examples and fixing a scoring rule. Raffel and colleagues study a text-to-text formulation. Brown and colleagues analyze zero-shot and few-shot evaluation with GPT-3.
On LAMBADA, Radford and colleagues report GPT-2 zero-shot accuracy of 52.66% when predicting the last word and 63.24% with a stop-word filter. This difference shows that output protocol constraints matter. There was no supervised fine-tuning on that dataset for these results.
For example, the GPT-3 paper reports 70.2% zero-shot, 73.2% one-shot, and 77.7% few-shot on Winogrande under its protocol. Not every task improves monotonically. In the corresponding Winograd table the figures are 88.3%, 89.7%, and 88.6%, and the paper flags possible contamination. These results do not establish the behavior of another model or other prompts.
Entropy describes the spread of the complete distribution. A top-k plot does not contain all the probability mass. If entropy rises when examples are added, or the desired answer does not appear, report that result. More context does not guarantee concentration on the correct answer.
The lifecycle of an LLM
The lifecycle starts with data selection and filtering, deduplication, and tokenizer training. Causal pretraining adjusts the weights on large corpora. A later mid-training phase may change the data mixture and learning rate. Supervised fine-tuning teaches formats and behaviors through examples. Preference and reinforcement methods optimize additional signals. Evaluation, data auditing, and contamination detection should accompany every stage.
Not every recipe includes every phase or uses the same order. Among documented examples, OLMo 2 describes pretraining and a later mixture and decay phase. Its 7B variant changes phase at around four trillion tokens, or . Tülu 3 documents a supervised mixture with 939,344 prompts in one of its columns. A prompt is not a token. Without lengths, epochs, and cost per step, these figures cannot be converted into an exact FLOP comparison. Preference or reinforcement stages may also involve generation, reference models, and additional passes.
Module map and local budget
Lessons 02 through 04 study bytes and tokenization. Lessons 05 through 08 build and evaluate objectives and base models. Lessons 09 through 14 cover corpora, scaling, and capabilities. Lessons 15 through 25 cover supervised fine-tuning, preferences, RL, and distillation. Lesson 26 returns to evaluation. The text-to-text formulation connects these steps by changing how the prefix, target, and data are constructed, although not every modality or action can be reduced to text without loss.
An 8 GB GPU can inspect small models and experiment with efficient adaptation. What fits depends on precision, context length, activations, and optimizer. The weights of a 500-million-parameter model in 16 bits occupy approximately 1,000 million bytes before activations, cache, and other tensors. This is arithmetic on parameters, not a promise that every training run of that size fits on the card.
Lab: from log probabilities to bits per byte
The following log probabilities come from a short run with SmolLM2-135M base and Qwen2.5-0.5B-Instruct. Exactly the same UTF-8 string is evaluated, including its final newline. The first token is conditioned on Smol’s BOS or Qwen’s EOS. This prefix is included in neither the scored bytes nor the scored tokens. A final EOS is not scored. The figures describe the canonical tokenizations of two different models with specific initial contexts. They do not attribute the difference solely to the tokenizer. Results were measured in float16 with PyTorch and transformers. This cell’s calculation uses only the standard library. The probability is that of the canonical token sequence, not necessarily the sum of probabilities of all token sequences representing the same text.
Extraction used Python 3.13.1, PyTorch 2.11.0+cu128, and transformers 5.20.2, with seed 2001. Exact model and tokenizer revisions: HuggingFaceTB/SmolLM2-135M 93efa2f097d58c2a74874c7e644dbc9b0cee75a2; Qwen/Qwen2.5-0.5B-Instruct 7ae557604adf67be50417f59c2c2f167def9a775.
"""Métricas de una secuencia con logprobabilidades condicionales naturales."""
import math
def metrics(token_logprobs, text):
if not isinstance(text, str) or not text:
raise ValueError("Se necesita texto no vacío")
if not token_logprobs:
raise ValueError("Se necesita una logprobabilidad por token")
if any(not math.isfinite(value) or value > 0 for value in token_logprobs):
raise ValueError("Las logprobabilidades deben ser finitas y no positivas")
nbytes = len(text.encode("utf-8"))
negative_log_likelihood = -math.fsum(token_logprobs)
nats_per_token = negative_log_likelihood / len(token_logprobs)
return {"tokens": len(token_logprobs), "bytes": nbytes,
"log_probability": -negative_log_likelihood,
"nats_per_token": nats_per_token,
"perplexity": math.exp(nats_per_token),
"bits_per_byte": negative_log_likelihood / (nbytes * math.log(2))}
assert len("aé🙂".encode("utf-8")) == 7
assert abs(metrics([-math.log(2)], "aé🙂")["bits_per_byte"] - 1/7) < 1e-15
TEXTO = 'La inteligencia artificial aprende de datos. Los modelos de lenguaje predicen el siguiente token.\n'
MODELOS = [{'name': 'HuggingFaceTB/SmolLM2-135M',
'context_id': 0,
'token_ids': [15319,
464,
299,
324,
32716,
6416,
253,
1702,
268,
85,
367,
2688,
395,
30,
10677,
1743,
395,
367,
303,
14083,
1346,
85,
36908,
264,
1102,
29459,
101,
1010,
85,
9624,
30,
198],
'logprobs_nats': [-8.63722038269043,
-11.55269718170166,
-2.2948648929595947,
-1.5946950912475586,
-0.1718214452266693,
-8.98953628540039,
-4.56761360168457,
-3.748676300048828,
-0.25145599246025085,
-1.3677864074707031,
-3.4218990802764893,
-6.739171981811523,
-0.03272945433855057,
-3.047914981842041,
-5.062750816345215,
-5.955536842346191,
-0.013480467721819878,
-0.9383291006088257,
-4.9445953369140625,
-0.2844104468822479,
-0.01705046556890011,
-0.18476815521717072,
-12.234944343566895,
-5.68892240524292,
-3.081125259399414,
-5.121268272399902,
-0.06381803005933762,
-0.009071209467947483,
-0.0013908008113503456,
-8.346521377563477,
-2.6407930850982666,
-0.7927968502044678]},
{'name': 'Qwen/Qwen2.5-0.5B-Instruct',
'context_id': 151645,
'token_ids': [8747,
89645,
8792,
20443,
67346,
68,
409,
17751,
13,
9656,
82642,
409,
326,
27004,
11058,
78334,
268,
655,
54901,
3950,
624],
'logprobs_nats': [-17.085546493530273,
-9.738668441772461,
-0.04413832724094391,
-0.46334612369537354,
-7.86118221282959,
-0.007293384987860918,
-2.25266695022583,
-5.532681941986084,
-3.757537364959717,
-3.3451757431030273,
-2.091200828552246,
-0.6227292418479919,
-3.5500142574310303,
-0.3551429808139801,
-0.004772225394845009,
-10.441353797912598,
-0.5910457968711853,
-3.142820358276367,
-3.8370680809020996,
-8.11656665802002,
-4.5316996574401855]}]
for model in MODELOS:
result = metrics(model['logprobs_nats'], TEXTO)
print(model['name'], '| contexto:', model['context_id'])
print('tokens:', result['tokens'], '| bytes:', result['bytes'])
print('log p:', round(result['log_probability'], 6),
'| nats/token:', round(result['nats_per_token'], 6),
'| PPL:', round(result['perplexity'], 6),
'| bits/byte:', round(result['bits_per_byte'], 6))
The converter uses identifiers obtained with tiktoken 0.14.0 on the same TEXTO, using the script tokenizer_measure.py provided with the figure. This cell checks the saved counts. It does not retrain or run the tokenizer again in Pyodide.
ids = {
'GPT-2': [14772,33649,9324,33743,11666,2471,10920,68,390,4818,418,13,5401,2746,418,390,300,13561,1228,68,41219,268,1288,43237,84,1153,68,11241,13,198],
'cl100k': [8921,90745,8968,21075,68446,68,409,18224,13,9853,83742,409,326,28102,11305,79434,268,658,56001,4037,627],
'o200k': [4579,121330,27034,177680,334,18336,13,8964,39564,334,98913,5453,103002,650,36487,6602,558],
}
print('Bytes UTF-8:', len(TEXTO.encode('utf-8')), '| puntos de código:', len(TEXTO))
for name, tokens in ids.items():
print(name, 'tokens:', len(tokens), '| bytes/token:', round(len(TEXTO.encode('utf-8'))/len(tokens), 6))Local lab: anatomy and behavior of a base model
Load SmolLM2-135M base, Qwen2.5-0.5B base, and its instruct version separately. The program reports vocabulary and special tokens, counts unique parameters by component, and states whether the output matrix shares weights with the embedding. It then calculates the probability of the same UTF-8 text without adding special tokens to the target. It prepends BOS as context if available, otherwise EOS. The first text token is predicted from that context; EOS is not added as a target. It also generates a continuation of the same request with greedy decoding. The instruct variant uses its chat template and the base model receives plain text. This illustrates format and behavior, rather than providing a controlled capabilities evaluation.
The bits-per-byte calculation refers to the canonical token sequence produced by each tokenizer and the stated context. It does not sum possible alternative sequences that decode to the same text. Per-token perplexities of two tokenizers are not directly comparable. Bits per byte use the same unit over the same bytes, but still depend on the model, its context, and its training. Next-token probabilities use softmax over the full vocabulary. Entropy uses the whole distribution, not just the top 10. A single token may represent only part of a UTF-8 character, and its isolated representation is not always readable.
Install PyTorch, transformers, tokenizers, and safetensors. Normal mode downloads the three models from Hugging Face one at a time if missing, and saves the report to ORYON_OUTPUT_DIR, defaulting to ./llm-anatomia-output. To check the flow with less load, ORYON_QUICK=1 uses SmolLM2 base and Qwen instruct with a maximum of 24 generated tokens. It does not compare a base/instruct pair from the same family. Normal mode loads the Qwen pair. ORYON_MODELS accepts comma-separated identifiers, and ORYON_REVISIONS_JSON accepts a JSON object with their revisions. SmolLM2 and Qwen instruct default to fixed revisions. The report records the Qwen base revision when the library provides it. Small numerical differences across devices and versions are possible.
In the short check, the same text occupied 32 tokens with SmolLM2 base and 21 with Qwen instruct. Their per-token perplexities were approximately 32.91 and 64.11, while bits per byte were 1.646 and 1.286. The ordering reverses when the unit changes. The model and training also change, so the result cannot be attributed solely to the tokenizer. The quick run did not verify the Qwen base checkpoint. The full cell requests it so that you can run the paired comparison.
"""Anatomía y evaluación corta de modelos causales abiertos."""
import gc
import json
import math
import os
import platform
from pathlib import Path
import torch
import transformers
from transformers import AutoModelForCausalLM, AutoTokenizer
torch.manual_seed(2001)
torch.set_num_threads(1)
DEVICE = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
DTYPE = torch.float16 if DEVICE.type == 'cuda' else torch.float32
QUICK = os.environ.get('ORYON_QUICK') == '1'
OUT = Path(os.environ.get('ORYON_OUTPUT_DIR', './llm-anatomia-output'))
OUT.mkdir(parents=True, exist_ok=True)
TEXT = 'La inteligencia artificial aprende de datos. Los modelos de lenguaje predicen el siguiente token.\n'
PROMPT = 'Explain in one sentence what a language model predicts.'
DEFAULT_MODELS = ('HuggingFaceTB/SmolLM2-135M,Qwen/Qwen2.5-0.5B-Instruct' if QUICK else
'HuggingFaceTB/SmolLM2-135M,Qwen/Qwen2.5-0.5B,Qwen/Qwen2.5-0.5B-Instruct')
MODELS = [name.strip() for name in os.environ.get('ORYON_MODELS', DEFAULT_MODELS).split(',') if name.strip()]
DEFAULT_REVISIONS = {
'HuggingFaceTB/SmolLM2-135M': '93efa2f097d58c2a74874c7e644dbc9b0cee75a2',
'Qwen/Qwen2.5-0.5B-Instruct': '7ae557604adf67be50417f59c2c2f167def9a775',
}
REVISIONS = {**DEFAULT_REVISIONS, **json.loads(os.environ.get('ORYON_REVISIONS_JSON', '{}'))}
assert MODELS
CASES = [
('hecho', 0, 'The capital of France is'),
('suma', 0, '2 + 3 ='),
('codigo', 0, 'def add(a, b):\n return'),
('traduccion', 0, 'Translate English to Spanish.\ncat ->'),
('traduccion', 1, 'Translate English to Spanish.\ndog -> perro\ncat ->'),
('traduccion', 3, 'Translate English to Spanish.\ndog -> perro\nhouse -> casa\nwater -> agua\ncat ->'),
]
def parameter_breakdown(model):
buckets = {'embedding': 0, 'atencion': 0, 'mlp': 0, 'salida_no_compartida': 0, 'otros': 0}
# named_parameters elimina duplicados del mismo Parameter, incluidos embeddings ligados.
for name, parameter in model.named_parameters():
n = parameter.numel()
if 'embed_tokens' in name or '.wte.' in name:
key = 'embedding'
elif '.self_attn.' in name or '.attn.' in name:
key = 'atencion'
elif '.mlp.' in name:
key = 'mlp'
elif name.startswith('lm_head.'):
key = 'salida_no_compartida'
else:
key = 'otros'
buckets[key] += n
total = sum(p.numel() for p in model.parameters())
assert sum(buckets.values()) == total
input_weight = model.get_input_embeddings().weight
output_weight = model.get_output_embeddings().weight
return {'total_unico': total, 'categorias': buckets,
'embedding_y_salida_comparten_parameter': input_weight is output_weight}
def token_metadata(tokenizer):
return {'vocab_size_base': tokenizer.vocab_size, 'vocab_size_total': len(tokenizer),
'special_tokens': tokenizer.special_tokens_map,
'special_ids': tokenizer.all_special_ids,
'bos_id': tokenizer.bos_token_id, 'eos_id': tokenizer.eos_token_id,
'revision': tokenizer.init_kwargs.get('_commit_hash')}
def score_text(model, tokenizer):
ids = tokenizer(TEXT, add_special_tokens=False)['input_ids']
assert ids and tokenizer.decode(ids, clean_up_tokenization_spaces=False) == TEXT
start = tokenizer.bos_token_id
if start is None:
start = tokenizer.eos_token_id
if start is None:
raise ValueError('El tokenizer no declara BOS ni EOS para condicionar el primer token')
x = torch.tensor([[start] + ids], device=DEVICE)
assert x.shape[1] <= model.config.max_position_embeddings
with torch.inference_mode():
logp = model(x).logits[0, :-1].float().log_softmax(-1)
selected = logp.gather(-1, x[0, 1:, None]).squeeze(-1).cpu().double()
nbytes = len(TEXT.encode('utf-8'))
assert nbytes > 0 and len(ids) == len(selected) and torch.isfinite(selected).all()
total = float(selected.sum())
return {'text': TEXT, 'utf8_bytes': nbytes, 'context_id': start,
'context_choice': 'BOS si existe; en otro caso EOS, añadido como prefijo',
'token_ids': ids, 'token_strings': [tokenizer.decode([i], clean_up_tokenization_spaces=False) for i in ids],
'logprobs_nats': selected.tolist(), 'sum_logprob_nats': total,
'nats_per_token': -total / len(ids), 'perplexity': math.exp(-total / len(ids)),
'bits_per_byte': -total / (nbytes * math.log(2)), 'include_eos_target': False}
def next_token_cases(model, tokenizer):
result = []
with torch.inference_mode():
for task, examples, prompt in CASES:
x = tokenizer(prompt, return_tensors='pt', add_special_tokens=False)['input_ids'].to(DEVICE)
logits = model(x).logits[0, -1].float()
logp = logits.log_softmax(-1)
p = logp.exp()
probs, ids = p.topk(10)
result.append({'task': task, 'examples': examples, 'prompt': prompt,
'prompt_token_ids': x[0].tolist(), 'prompt_tokens': x.shape[1],
'entropy_bits': float((-(p * logp).sum() / math.log(2)).item()),
'top_probability_sum': float(probs.sum().item()),
'top': [{'id': int(i), 'token': tokenizer.decode([int(i)], clean_up_tokenization_spaces=False),
'prob': float(v)} for v, i in zip(probs.cpu(), ids.cpu())]})
return result
def generate(model, tokenizer, instruct):
messages = [{'role': 'user', 'content': PROMPT}]
if instruct:
text = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
else:
text = PROMPT + '\n'
x = tokenizer(text, return_tensors='pt', add_special_tokens=False)['input_ids'].to(DEVICE)
with torch.inference_mode():
output = model.generate(x, max_new_tokens=24 if QUICK else 64, do_sample=False,
pad_token_id=tokenizer.eos_token_id)
continuation = output[0, x.shape[1]:].cpu().tolist()
return {'instruction': PROMPT, 'actual_prompt': text, 'chat_template': instruct,
'decoding': 'greedy', 'continuation_ids': continuation,
'continuation': tokenizer.decode(continuation, skip_special_tokens=True,
clean_up_tokenization_spaces=False)}
report = {'python': platform.python_version(), 'torch': torch.__version__,
'transformers': transformers.__version__, 'device': str(DEVICE), 'dtype': str(DTYPE),
'seed': 2001, 'quick': QUICK, 'models': {}}
for name in MODELS:
print('Cargando', name, flush=True)
options = {'revision': REVISIONS[name]} if name in REVISIONS else {}
tokenizer = AutoTokenizer.from_pretrained(name, **options)
model = AutoModelForCausalLM.from_pretrained(name, dtype=DTYPE, **options).to(DEVICE).eval()
revision = getattr(model.config, '_commit_hash', None) or options.get('revision')
entry = {'model_id': name, 'model_revision': revision,
'tokenizer': token_metadata(tokenizer), 'parameters': parameter_breakdown(model),
'score': score_text(model, tokenizer),
'generation': generate(model, tokenizer, name.endswith('-Instruct'))}
entry['tokenizer']['revision'] = entry['tokenizer']['revision'] or options.get('revision')
if name == 'HuggingFaceTB/SmolLM2-135M':
entry['next_token_cases'] = next_token_cases(model, tokenizer)
report['models'][name] = entry
print('Parámetros', entry['parameters'], flush=True)
print('Texto: tokens', len(entry['score']['token_ids']),
'ppl', entry['score']['perplexity'], 'bpb', entry['score']['bits_per_byte'], flush=True)
print('Continuación:', repr(entry['generation']['continuation']), flush=True)
with (OUT / 'report.json').open('w', encoding='utf-8') as f:
json.dump(report, f, ensure_ascii=False, indent=2)
del model, tokenizer
gc.collect()
if DEVICE.type == 'cuda':
torch.cuda.empty_cache()
print('Informe:', OUT / 'report.json', flush=True)
npm run lab and open the connection link.Exercises
import math
def bits_per_byte(token_logprobs, text):
pass
A causal LLM assigns probabilities to tokens. To interpret a capability or compare losses, specify the text, tokenizer, context, training stage, and evaluation protocol.