LLMs-from-scratch
ModelFreeImplement a ChatGPT-like LLM in PyTorch from scratch, step by step
Capabilities13 decomposed
multi-head attention mechanism with causal masking for autoregressive generation
Medium confidenceImplements scaled dot-product attention using Query/Key/Value linear projections (W_query, W_key, W_value) with causal masking to prevent attending to future tokens. The mechanism splits embeddings across multiple heads, computes attention scores via matrix multiplication (queries @ keys.transpose), applies a triangular mask buffer registered in __init__, and projects concatenated head outputs through out_proj. This enables parallel attention computation across sequence positions while maintaining autoregressive constraints required for token-by-token generation.
Provides pedagogically clear, step-by-step attention implementation with explicit mask buffer registration and head concatenation, making the mechanism's mechanics transparent rather than abstracted behind framework utilities. Includes visualization-friendly attention weight extraction for debugging.
More interpretable than PyTorch's native scaled_dot_product_attention (which optimizes for speed) because it exposes each computation step, making it ideal for learning but ~15-20% slower for production inference.
gpt architecture scaling from 124m to 1558m parameters via configuration dictionary
Medium confidenceImplements a modular GPTModel class that accepts a configuration dictionary specifying embedding dimension, number of layers, attention heads, and feed-forward width. The architecture stacks transformer blocks (each containing multi-head attention, layer normalization, and feed-forward networks) with token and positional embeddings, then projects to vocabulary logits. The configuration pattern allows instantiation of model variants (GPT-small, GPT-medium, GPT-large) by changing dict values rather than code, enabling systematic scaling studies and transfer learning experiments.
Uses explicit configuration dictionaries rather than dataclass configs or factory functions, making model variants immediately visible as data structures. Includes pre-defined configs for GPT2-small, GPT2-medium, GPT2-large that match OpenAI's published parameter counts, enabling direct weight loading from official checkpoints.
More transparent than HuggingFace Transformers' AutoModel factory pattern because hyperparameters are visible as Python dicts rather than hidden in JSON configs, but requires manual weight conversion from HF format.
positional encoding via absolute position embeddings for sequence position awareness
Medium confidenceAdds learnable or fixed positional embeddings to token embeddings to encode sequence positions, enabling the model to distinguish between tokens at different positions. The implementation creates a position embedding matrix (context_length, embedding_dim) and adds it element-wise to token embeddings before passing to transformer blocks. This allows attention mechanisms to incorporate position information, critical for understanding word order in language.
Implements positional embeddings as a learnable parameter matrix added to token embeddings, making the encoding mechanism transparent. Includes utilities to visualize position embedding patterns and to analyze how positions are represented in the embedding space.
More interpretable than rotary embeddings (RoPE) because position information is explicit in embedding space; less effective for long sequences because absolute positions don't generalize beyond training context length.
batch data loading with sliding window context for efficient sequence packing
Medium confidenceCreates training batches by sliding a fixed-size window over tokenized text, generating overlapping sequences that maximize data utilization. The implementation reads tokenized text, creates sliding windows of context_length, groups windows into batches, and yields (input, target) pairs where targets are inputs shifted by one position. This approach reduces memory overhead compared to padding variable-length sequences and ensures all tokens contribute to training.
Implements sliding window batching with explicit overlap handling and target sequence creation (shifted inputs), making data preparation transparent. Includes utilities to visualize batch composition and to analyze token distribution across batches.
More efficient than padding variable-length sequences because it eliminates padding overhead; less flexible than HuggingFace datasets because it requires pre-tokenized data and doesn't support on-the-fly tokenization.
model evaluation via perplexity and loss metrics on validation sets
Medium confidenceEvaluates model quality by computing perplexity (exp(loss)) and cross-entropy loss on held-out validation data. The implementation runs the model in evaluation mode (disabling dropout), computes loss without gradient computation, and aggregates metrics across batches. Perplexity measures how well the model predicts validation tokens — lower is better, with perplexity=1 indicating perfect predictions.
Implements evaluation with explicit loss computation and perplexity calculation, making model quality assessment transparent. Includes utilities to compute confidence intervals and to visualize loss curves across validation batches.
More interpretable than black-box evaluation frameworks because metrics are computed explicitly; lacks task-specific metrics like BLEU or ROUGE, requiring external evaluation for generation quality.
byte-pair encoding (bpe) tokenization with vocabulary merging
Medium confidenceImplements BPE tokenization by iteratively merging the most frequent adjacent token pairs in a corpus, building a vocabulary of subword units. The algorithm tracks pair frequencies, applies merges in order, and encodes text by greedily matching longest subword sequences. This approach reduces vocabulary size compared to character-level tokenization while maintaining semantic meaning, enabling efficient representation of rare words through composition.
Provides step-by-step BPE implementation with explicit pair frequency tracking and merge visualization, making the algorithm's behavior transparent. Includes utilities to inspect which subword boundaries are created at each merge step, useful for debugging tokenization issues.
More educational than using tiktoken or SentencePiece directly because it exposes the merge algorithm; slower than optimized C++ implementations but sufficient for corpora <1GB and ideal for understanding tokenization mechanics.
causal language modeling pretraining with next-token prediction loss
Medium confidenceImplements a training loop that predicts the next token given preceding context by computing cross-entropy loss between model logits and ground-truth next tokens. The loop iterates over batches, performs forward passes through the GPT model, computes loss on shifted token sequences (input tokens predict next tokens), backpropagates gradients, and updates weights via optimizer steps. This approach trains the model to learn conditional probability distributions P(token_t | tokens_0..t-1), the foundation of autoregressive generation.
Implements training with explicit loss computation on shifted sequences (input[:-1] predicts target[1:]), making the causal prediction objective transparent. Includes detailed logging of loss curves and validation metrics, enabling visual inspection of training dynamics.
More interpretable than Hugging Face Trainer because loss computation is explicit and modifiable; slower due to lack of distributed training and gradient accumulation, but suitable for educational purposes and small-scale experiments.
instruction fine-tuning with supervised learning on task-specific examples
Medium confidenceAdapts a pretrained language model to follow instructions by fine-tuning on curated instruction-response pairs. The approach computes loss only on response tokens (not instruction tokens), using a mask to zero out instruction loss. This trains the model to generate appropriate responses given task descriptions, shifting from next-token prediction to instruction-following behavior. The implementation supports both full-parameter fine-tuning and parameter-efficient variants.
Implements response-only loss masking by explicitly zeroing instruction token gradients, making the fine-tuning objective clear. Includes utilities to visualize which tokens contribute to loss, helping debug instruction-response boundary issues.
More transparent than HuggingFace's trainer because loss masking is explicit and modifiable; requires manual implementation of evaluation metrics unlike AutoTrain, but enables fine-grained control over training dynamics.
parameter-efficient fine-tuning via low-rank adaptation (lora)
Medium confidenceReduces fine-tuning memory and compute by freezing pretrained weights and adding low-rank decomposition matrices (A and B) to attention and feed-forward layers. During forward pass, the model computes output as W*x + (B @ A)*x, where W is frozen and (B @ A) is trainable with rank r << hidden_dim. This approach reduces trainable parameters by 99%+ while maintaining performance, enabling fine-tuning of large models on consumer GPUs. The implementation applies LoRA to query/key/value projections and feed-forward layers.
Implements LoRA by explicitly adding low-rank matrices to linear layers with configurable rank and alpha scaling, making the decomposition structure transparent. Includes utilities to merge LoRA weights into base model for inference and to analyze rank utilization across layers.
More educational than using peft library because LoRA computation is explicit; less optimized than production implementations but sufficient for understanding parameter efficiency and prototyping.
text generation via autoregressive sampling with temperature and top-k/top-p filtering
Medium confidenceGenerates text by iteratively predicting the next token given previous tokens, using sampling strategies to control output diversity. The implementation computes logits for the next position, applies temperature scaling (dividing by T to sharpen or smooth probability distribution), filters to top-k or top-p (nucleus) tokens, and samples from the resulting distribution. This enables controllable generation from deterministic (temperature=0, greedy) to highly stochastic (temperature=2.0, top-p=0.95) outputs.
Implements sampling with explicit temperature scaling and top-k/top-p filtering steps, making the decoding process transparent and modifiable. Includes utilities to visualize probability distributions at each step and to compare outputs across different temperature/sampling settings.
More interpretable than transformers.generation because each sampling step is explicit; slower due to lack of optimizations like KV-cache reuse, but suitable for understanding generation mechanics and prototyping.
direct preference optimization (dpo) for alignment without reward modeling
Medium confidenceAligns model outputs to human preferences by directly optimizing a preference loss on pairs of chosen/rejected responses, without training a separate reward model. The approach computes log probabilities for both responses, applies a preference loss (e.g., binary cross-entropy on preference logits), and backpropagates to update model weights. This simplifies RLHF by eliminating the reward model training phase while maintaining alignment to human feedback.
Implements DPO with explicit preference loss computation (typically binary cross-entropy on preference logits), making the alignment objective transparent. Includes utilities to analyze preference margins and to visualize how model outputs shift during DPO training.
Simpler than RLHF implementations because it eliminates reward model training; less mature than PPO-based approaches but emerging as a practical alternative for preference-based alignment.
model checkpoint loading and weight conversion from huggingface/openai formats
Medium confidenceLoads pretrained weights from external sources (HuggingFace, OpenAI) into the custom GPT architecture by mapping layer names and handling format differences. The implementation reads state dicts from checkpoint files, renames keys to match the custom model's naming scheme, and validates shape compatibility before loading. This enables transfer learning from large pretrained models without reimplementing the architecture in the original framework.
Provides explicit key mapping and shape validation utilities, making weight conversion transparent and debuggable. Includes detailed loading reports showing which weights were loaded and which layers were skipped, useful for diagnosing architecture mismatches.
More transparent than HuggingFace's from_pretrained because weight mapping is explicit; requires more manual work but enables loading into custom architectures that don't inherit from PreTrainedModel.
classification fine-tuning by replacing language modeling head with task-specific classifier
Medium confidenceAdapts a pretrained language model for classification by removing the language modeling head and replacing it with a linear classifier that maps the final hidden state to class logits. The approach freezes or partially fine-tunes the transformer backbone and trains the classifier head on labeled examples using cross-entropy loss. This leverages pretrained representations for downstream classification tasks like sentiment analysis or topic classification.
Implements classification by explicitly replacing the language modeling head with a linear classifier, making the task adaptation transparent. Includes utilities to freeze/unfreeze backbone layers and to analyze which layers contribute most to classification decisions.
More interpretable than HuggingFace AutoModelForSequenceClassification because the head replacement is explicit; requires manual implementation of evaluation metrics but enables fine-grained control over fine-tuning.
Capabilities are decomposed by AI analysis. Each maps to specific user intents and improves with match feedback.
Related Artifactssharing capabilities
Artifacts that share capabilities with LLMs-from-scratch, ranked by overlap. Discovered automatically through the match graph.
bert-large-uncased
fill-mask model by undefined. 10,12,796 downloads.
DeepSeek V3
671B MoE model matching GPT-4o at fraction of training cost.
bert-base-uncased
fill-mask model by undefined. 6,06,75,227 downloads.
Build a Large Language Model (From Scratch)
A guide to building your own working LLM, by Sebastian Raschka.
Transformers
Hugging Face's model library — thousands of pretrained transformers for NLP, vision, audio.
Deep Learning Systems: Algorithms and Implementation - Tianqi Chen, Zico Kolter

Best For
- ✓ML researchers learning transformer internals
- ✓Students building LLM implementations from first principles
- ✓Engineers optimizing attention computation for inference
- ✓Researchers conducting scaling law experiments
- ✓Teams building custom LLM variants with specific parameter budgets
- ✓Educators demonstrating how hyperparameters affect model capacity
- ✓Researchers studying positional encoding effects on model performance
- ✓Teams building custom transformers requiring position awareness
Known Limitations
- ⚠Causal masking adds O(n²) memory overhead for sequence length n — not suitable for sequences >8k tokens without optimization
- ⚠No built-in support for relative position embeddings or ALiBi — uses absolute positional encoding only
- ⚠Single-GPU implementation without distributed attention sharding
- ⚠Configuration dict approach lacks runtime validation — invalid combinations (e.g., embedding_dim not divisible by num_heads) fail at forward pass, not config time
- ⚠No built-in support for mixture-of-experts or conditional computation — all parameters active regardless of input
- ⚠Weight initialization uses fixed schemes (Xavier/Kaiming) without layer-specific tuning for stability at extreme scales
Requirements
Input / Output
UnfragileRank
UnfragileRank is computed from adoption signals, documentation quality, ecosystem connectivity, match graph feedback, and freshness. No artifact can pay for a higher rank.
Repository Details
Last commit: Apr 16, 2026
About
Implement a ChatGPT-like LLM in PyTorch from scratch, step by step
Categories
Alternatives to LLMs-from-scratch
Are you the builder of LLMs-from-scratch?
Claim this artifact to get a verified badge, access match analytics, see which intents users search for, and manage your listing.
Get the weekly brief
New tools, rising stars, and what's actually worth your time. No spam.
Data Sources
Looking for something else?
Search →