Skip to content
ImagineWorld

End-to-End Workflow from Scratch

node_idnode-book_llm-systems-engineering_module-38-end-to-end-workflow-from-scratch
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num38
chapter_titleEnd-to-End Workflow from Scratch
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Module 38 — End-to-End Workflow from Scratch

Section titled “Module 38 — End-to-End Workflow from Scratch”

The progression from a blank codebase to a usable base model demands that each stage of the pipeline operate under tight coordination, since every downstream step inherits the assumptions and artifacts of the prior one. This module walks through the practical implementation of a from-scratch training run, connecting the infrastructure mapped in the previous module with the concrete commands and routines that activate it. Tokenizer construction opens the sequence and the packaging of a completed checkpoint closes it, with model initialization and staged scaling filling the work in between. At each stage, small errors can compound silently and invalidate enormous amounts of compute. The examples and patterns presented here emphasize defensive engineering practices that make failures detectable early. While this module does not provide step-by-step coding examples on how to set up an LLM from scratch, it guides you through the distinct stages, providing you with guidance on the end-to-end workflow design.

Configuring the vocabulary size is the first concrete decision of training a tokenizer. Current frontier models commonly select values well above 100 thousand entries because larger vocabularies improve compression and reduce sequence length for long documents. Alongside the raw count, you must enumerate the special tokens that the architecture expects. Reserved identifiers for chat formatting or tool calls are frequently added during later post-training stages, so forward compatibility calls for allocating unused slots in the vocabulary during initial training. Skipping this step forces either a messy vocabulary extension later or the repurposing of tokens that the model has already learned to interpret.

A minimal tokenizer training routine using the Hugging Face tokenizers library demonstrates the standard pattern:

from tokenizers import Tokenizer, models, trainers, pre_tokenizers
tokenizer = Tokenizer(models.BPE(unk_token="<unk>"))
tokenizer.pre_tokenizer = pre_tokenizers.ByteLevel(add_prefix_space=False)
trainer = trainers.BpeTrainer(
vocab_size=128_000,
special_tokens=["<unk>", "<s>", "</s>", "<pad>"],
min_frequency=2,
show_progress=True,
)
tokenizer.train(files=["corpus_sample.txt"], trainer=trainer)
tokenizer.save("tokenizer.json")

Once trained, the tokenizer must undergo validation before the vocabulary is frozen. Round-trip encoding tests verify that the decode of an encoded string exactly reproduces the input, which catches bugs in special-token handling and byte-level preprocessing. Compression ratio measurement, often reported as bytes per token or as the fertility score (tokens per word), reveals whether the vocabulary is well-adapted to the target domains. A higher fertility score in any domain predicts wasted compute and degraded inference economics for text in that domain. Coverage analysis across representative samples from each expected domain exposes pathological cases. Source code tokenized one character at a time is a common example, caused by the trainer seeing too little code during vocabulary induction.

Vocabulary refinement approaches developed in recent work can improve the quality of the final vocabulary without changing the training corpus. Picky BPE, for instance, removes intermediate merges that have become obsolete during training, producing a cleaner vocabulary of the desired size (Chizhov et al., 2024). Once validation passes, the tokenizer file should be versioned and frozen, and any later change to the vocabulary must be treated as a breaking change that invalidates prior training runs.

Model Initialization and Pre-Training Checks

Section titled “Model Initialization and Pre-Training Checks”

After the tokenizer is frozen, attention turns to the model definition and the initialization of its weights. Initialization controls signal propagation through the network at step zero, and poor choices here produce dead neurons, exploding activations, or silent asymmetries that optimization cannot recover from efficiently. Standard practice for transformer projections uses a Gaussian distribution with a small standard deviation such as 0.02. Depth-aware schemes additionally scale residual-branch initializations by a factor involving the number of layers, which prevents variance growth in the residual stream as depth increases (Zhang et al., 2025). The choice of scheme should be made in conjunction with the normalization placement and any parameterization in use. The Maximal Update Parameterization in particular prescribes its own initialization scale adjustments so that hyperparameters transfer cleanly from small to large models (Yang et al., 2022).

A practical initialization in PyTorch looks like this:

import math
import torch
import torch.nn as nn
def init_weights(module, n_layers):
if isinstance(module, nn.Linear):
nn.init.normal_(module.weight, mean=0.0, std=0.02)
if module.bias is not None:
nn.init.zeros_(module.bias)
elif isinstance(module, nn.Embedding):
nn.init.normal_(module.weight, mean=0.0, std=0.02)
if getattr(module, "is_residual_projection", False):
with torch.no_grad():
module.weight.mul_(1.0 / math.sqrt(2 * n_layers))
model.apply(lambda m: init_weights(m, n_layers=model.config.n_layers))

With the model parameters in place, the data loader is wired into the training loop and a diagnostic sequence begins. The forward-pass shape check confirms that a single batch travels through the network without dimension errors, and that the output logits have the expected shape of (batch, sequence, vocab_size). Immediately afterward, the expected initial loss is computed. For a properly initialized autoregressive language model, the first-step cross-entropy loss should approximate the natural logarithm of the vocabulary size, because the model at initialization should assign roughly uniform probability across all tokens. A measured loss far above this value usually points to an initialization scale problem or to an error in the logit scaling factor.

import math
expected_loss = math.log(tokenizer.vocab_size)
model.eval()
with torch.no_grad():
logits = model(batch["input_ids"])
loss = torch.nn.functional.cross_entropy(
logits.view(-1, tokenizer.vocab_size),
batch["labels"].view(-1),
)
print(f"initial loss: {loss.item():.3f}, expected ~{expected_loss:.3f}")

Gradient flow inspection follows. A backward pass on a few batches should produce non-zero gradients in every layer, with norms that scale smoothly across depth. Layers with vanishing gradients may indicate initialization errors or bugs in the residual connections, and exploding gradients often indicate misconfigured layer normalization. Recent research on variance dynamics has documented systematic patterns in which shallow layers exhibit rapid early expansion of weight standard deviations. Deeper layers evolve more gradually and eventually settle into narrow variance bands. You should log per-layer gradient norms throughout the first hundred steps to catch drift away from these expected patterns.

The final check before large-scale training is overfitting a single batch. The model is trained repeatedly on the same small batch, and the training loss should approach zero within a few hundred optimizer steps. If the loss fails to descend, the root cause commonly lies in a sign error in the loss computation or in a misalignment between the tokenized labels and the model’s expected input shape.

model.train()
optimizer = torch.optim.AdamW(model.parameters(), lr=3e-4)
fixed_batch = next(iter(dataloader))
for step in range(400):
optimizer.zero_grad()
logits = model(fixed_batch["input_ids"])
loss = torch.nn.functional.cross_entropy(
logits.view(-1, tokenizer.vocab_size),
fixed_batch["labels"].view(-1),
)
loss.backward()
optimizer.step()
if step % 50 == 0:
print(f"step {step}: loss={loss.item():.4f}")
assert loss.item() < 0.1, "overfit test failed; inspect pipeline"

Once the pipeline passes its diagnostic checks, you should resist the temptation to begin the full-scale run. A sequence of progressively larger pilot runs should first surface instabilities and tune hyperparameters at a small fraction of the final cost. These pilot runs serve two purposes. The first is operational, confirming that the distributed training framework and the checkpoint system both remain stable for tens of thousands of steps. The second is predictive, producing data points that extrapolate to the intended full-scale configuration.

Predictive scaling requires that hyperparameters transfer cleanly from small to large. This is the central motivation for the Maximal Update Parameterization, under which many optimal hyperparameters remain stable as model width increases. Tuning can therefore proceed on small models with zero-shot transfer to the target. Yang et al. (2022) have reported that zero-shot transfer from models as small as 40 million parameters can outperform the tuned configurations of large published models while consuming only a fraction of the tuning budget.

Pilot runs should also validate decisions about data. Small-scale experiments can predict which pretraining corpora produce the strongest downstream performance, though the reliability of this signal depends on how closely the pilot setup mirrors the target regime. The DataDecide investigation demonstrated that small models ranked pretraining datasets with 80 percent accuracy relative to large-scale outcomes, and it also documented the limits of this approach for fine-grained decisions (Magnusson et al., 2025). A reasonable staging pattern begins with a model roughly one hundredth the size of the target. The pilot run long enough to pass the regime where loss curves are dominated by initial transients, and then progresses to an intermediate scale before committing to the full run.

A configuration pattern for reproducible scaling experiments centralizes all hyperparameters in a single file and parameterizes the model size along a known scaling axis:

scaling_config.yaml
base:
vocab_size: 128000
sequence_length: 4096
optimizer: adamw
betas: [0.9, 0.95]
weight_decay: 0.1
warmup_steps: 2000
variants:
pilot_small:
n_layers: 12
d_model: 768
n_heads: 12
learning_rate: 3.0e-4
train_tokens: 10_000_000_000
pilot_mid:
n_layers: 24
d_model: 2048
n_heads: 16
learning_rate: 3.0e-4 # transferred via muP
train_tokens: 50_000_000_000
target:
n_layers: 40
d_model: 5120
n_heads: 40
learning_rate: 3.0e-4 # transferred via muP
train_tokens: 1_000_000_000_000

During each pilot, you must watch for training instabilities that can later derail the target run. Loss spikes, in which the training loss momentarily increases by orders of magnitude, have been connected to non-uniformity of parameter norms and to unchecked amplification in the residual connections (Takase et al., 2024). Mitigations such as weight-scaling reparameterization and spike-aware optimizer adjustments can be evaluated at pilot scale before they work in production. The pilot phase is also where checkpointing behavior should be stress-tested. Systems such as hybrid in-memory checkpointing dramatically reduce the overhead and recovery cost that later become critical when training spans weeks. Throughput instrumentation during pilots produces the numbers that drive budget planning. Tokens per second per device and optimizer step time must both fall within acceptable ranges at the target parallelism configuration. Data-loader saturation deserves separate attention, since a data pipeline that starves the accelerators invalidates any throughput projection. Any pilot that fails to meet expectations on these measurements signals that the full run will either overrun budget or produce a weaker model than its compute would predict.

Transitioning From Base Model to Usable System

Section titled “Transitioning From Base Model to Usable System”

When the target training run completes, the base model exists as a set of optimizer state files and weight shards on distributed storage. Converting this artifact into a usable system requires final evaluation, consolidation, and packaging. The final evaluation harness runs the trained model through the suite of benchmarks and internal tasks selected during the planning phase. Open evaluation frameworks such as the EleutherAI LM Evaluation Harness provide standardized prompt templates and metric implementations that make results comparable across papers and organizations, with reproducibility enforced by unifying benchmark implementations and evaluation logic in a single codebase (Biderman et al., 2024b). Evaluation at this stage serves as the last opportunity to detect silent failures in the pretraining data pipeline or in the checkpoint loading code. A sudden drop in benchmark scores between the final training checkpoint and the consolidated artifact usually indicates a sharding or precision mismatch during the merge step.

Packaging the checkpoint means producing a distributable bundle that pairs the consolidated weights with the frozen tokenizer. A canonical configuration file accompanies both and exhaustively describes the model architecture alongside the training metadata, so that downstream fine-tuning runs can reproduce the environment in which the base model was produced.

A minimal packaging routine enforces the boundaries between training state and release artifact:

import json, torch
from pathlib import Path
release_dir = Path("artifacts/base_model_v1")
release_dir.mkdir(parents=True, exist_ok=True)
consolidated = merge_sharded_checkpoint("training/step_500000/")
torch.save(consolidated, release_dir / "pytorch_model.bin")
tokenizer.save(str(release_dir / "tokenizer.json"))
config = {
"architecture": "transformer_lm",
"n_layers": 40,
"d_model": 5120,
"n_heads": 40,
"vocab_size": 128000,
"sequence_length": 4096,
"tokenizer_sha256": tokenizer_file_hash,
"training_tokens": 1_000_000_000_000,
"parameterization": "muP",
"training_config_sha256": yaml_config_hash,
}
with open(release_dir / "config.json", "w") as f:
json.dump(config, f, indent=2)
with open(release_dir / "MODEL_CARD.md", "w") as f:
f.write(generate_model_card(config, eval_results))

The decisions made at this transition point carry directly into subsequent stages. The tokenizer in the release bundle becomes the contract that all fine-tuning and alignment stages must honor, since any change would invalidate the base model’s learned embeddings. Special tokens reserved for later chat or tool use should already be present in the vocabulary so that post-training does not require vocabulary extension. The configuration file should record the parameterization scheme so that later fine-tuning runs can replicate the numerical conditions under which the base model was produced. Evaluation results at this stage form the baseline against which every subsequent modification of the model will be compared, which makes the choice of evaluation suite a consequential decision in its own right. A base model that passes this transition with complete versioned artifacts and a comprehensive evaluation baseline is ready to enter the fine-tuning and alignment pipelines discussed in Chapter V.