OpenLanguage Model.

A modular PyTorch LLM library for building, training, teaching, and researching transformer language models. OLM does for LLMs what PyTorch did for deep learning: make the machinery readable, composable, and yours.

PyPI versionGitHub starsPython 3.10-3.12MIT license
30+LM training runs from 100M to 1B scale.
27Named model presets implemented, including GPT-2, Llama, Qwen, Phi, Gemma, OLMo, and OPT.
llama3_block.py
from olm.nn.structure import Block
from olm.nn.structure.combinators import Residual
from olm.nn.attention import GroupedQueryAttention
from olm.nn.feedforward import SwiGLUFFN
from olm.nn.norms import RMSNorm

llama3_block = Block([
    Residual(Block([
        RMSNorm(embed_dim, eps=1e-5),
        GroupedQueryAttention(
            embed_dim,
            num_heads,
            num_kv_heads,
            max_seq_len,
            dropout=dropout,
            rope_theta=rope_theta,
            use_bias=False,
        ),
    ])),
    Residual(Block([
        RMSNorm(embed_dim, eps=1e-5),
        SwiGLUFFN(
            embed_dim,
            hidden_dim=intermediate_size,
            dropout=dropout,
            bias=False,
        ),
    ])),
])
02 — Quickstart

Write the GPT-2 Architecture

Start with a compact GPT-style model, then trace how embeddings, transformer blocks, and the output head fit together. The same pieces are available when you want to open the model and change a part.

GPT-2 components mapped to OLM building blocks

Train your first language model →

03 — For Everyone

OLM Is For Everyone

Beginner

Train a Language Model With About $6

FineWeb-Edu streaming, GPT-2 tokenization, a roughly 125M parameter model, and the training loop in one readable script.

import torch

from olm.nn.blocks import LM
from olm.train import Trainer
from olm.data.tokenization import HFTokenizer
from olm.data.datasets import FineWebEduDataset, DataLoader

tok = HFTokenizer("gpt2")
model = LM(
    tok.vocab_size,
    embed_dim=640,
    num_heads=10,
    num_layers=12,
    max_seq_len=1024,
    ff_multiplier=2.75,
)

dataset = FineWebEduDataset(tok, context_length=1024)
loader = DataLoader(dataset, batch_size=8, num_workers=4)
optimizer = torch.optim.AdamW(model.parameters(), lr=3e-4)
device = "cuda" if torch.cuda.is_available() else "cpu"

losses = Trainer(
    model,
    optimizer,
    loader,
    device,
    context_length=1024,
    use_amp=device == "cuda",
).train(epochs=1, max_steps=20_000)

For the guided version with text generation and save/load, see Your First Language Model →

Researcher

Change Only What You Need To

Change the attention rule, test the idea, and leave the rest of the training path alone.

import torch

from olm.nn.attention import AttentionBase

class LocalWindowAttention(AttentionBase):
    def __init__(self, embed_dim, num_heads, window=256):
        super().__init__(embed_dim, num_heads)
        self.window = window

    def compute_attention(self, q, k, v, mask=None):
        scores = (q @ k.transpose(-2, -1)) * self.scale
        seq = q.size(-2)
        pos = torch.arange(seq, device=q.device)
        local = (pos[:, None] - pos[None, :]).abs() <= self.window
        causal = pos[:, None] >= pos[None, :]
        scores = scores.masked_fill(~(local & causal), float("-inf"))
        if mask is not None:
            scores = scores.masked_fill(mask == 0, float("-inf"))
        probs = self.dropout(scores.softmax(dim=-1))
        return probs @ v

attention = LocalWindowAttention(d_model, heads, window=256)
# Drop it into a Block, a custom model, or your PyTorch loop.
Automatic Distributed Training ManagementOLM handles AMP, gradient accumulation, schedules, callbacks, DDP, FSDP, distributed sampling, rank-aware logging, metrics, and checkpointing when you want to scale.
Fits PyTorch workflowsuse OLM modules inside existing PyTorch loops, scripts, notebooks, and research pipelines.
OLM is made for learning

Teach Language Modelling By Building One

For courses, labs, and reading groups, OLM turns language modelling into a sequence students can inspect: tokens, embeddings, attention, blocks, and training.

Start the course →
04 — Architecture

A Real Llama-Style Model, Written as Blocks

The core idea is separation: components say what happens;Block, Residual, and Repeat say how those components are wired. That makes architecture experiments local edits.

from olm.nn.structure import Block
from olm.nn.structure.combinators import Residual, Repeat
from olm.nn.attention import GroupedQueryAttention
from olm.nn.feedforward import SwiGLUFFN
from olm.nn.norms import RMSNorm
from olm.nn.embeddings import Embedding
from torch.nn import Linear

Llama3Style = Block([
    Embedding(vocab_size, embed_dim),
    Repeat(lambda: Block([
        Residual(Block([
            RMSNorm(embed_dim, eps=1e-5),
            GroupedQueryAttention(
                embed_dim, num_heads, num_kv_heads, max_seq_len, use_bias=False
            )
        ])),
        Residual(Block([
            RMSNorm(embed_dim, eps=1e-5),
            SwiGLUFFN(embed_dim, hidden_dim=intermediate_size, bias=False)
        ]))
    ]), num_layers),
    RMSNorm(embed_dim, eps=1e-5),
    Linear(embed_dim, vocab_size, bias=False)
])

Learn the Block system →

Bring Your Own Loop

OLM components are ordinary PyTorch modules. You can train with OLM's trainer, or call the model yourself inside the PyTorch loop you already use.

for inputs, targets in loader:
    logits = model(inputs)
    loss = loss_fn(logits, targets)
    loss.backward()
    optimizer.step()
    optimizer.zero_grad()
06 — Roadmap

Roadmap

OLM already supports complete language-model pretraining: modern architectures, swappable components, streaming data, checkpoints, mixed precision, and fast single-node multi-GPU training.

v1.0Foundation, core architectures, streaming data, single-GPU training.
v1.1Flash/SDPA attention, RoPE/ALiBi variants, W&B logging, API docs.
v2.0DDP, FSDP, and readable Mixture-of-Experts routing.
v2.1AutoTrainer, hardware-aware training setup, and distributed/attention stability fixes.
v2.2Stability and bug fixes, website, SEO, mascot, API reference polish, and documentation refinement.
v3.0Further training: SFT, LoRA, DPO, PPO/RLHF, GRPO-style RLVR, and evaluation recipes.
v4.0Multi-node training and cluster support.
07 — Contribute

We're Open Source & Looking for Contributors

Contributions are welcome across docs, examples, API reference, model implementations, training stability, release polish, and roadmap features. The docs and website render from the same Markdown in this repository, so improvements travel everywhere.