PTL-1 · NINE-SEVEN

A 326M-parameter Transformer trained from scratch on one RTX 3060 Ti.

Lyra is a decoder-only language model trained on 6.4 billion tokens. This documentation covers the architecture, the training pipeline, and the engineering failures encountered and resolved during development.

326,160,384 Parameters
6.4B Token Budget
10,000 Tokens / sec
178h Wall Clock

Architecture

Lyra follows the standard decoder-only Transformer paradigm, with four specific substitutions to improve training stability and inference efficiency at this scale.

Dimensions

  • Layers24
  • Attention Heads16
  • Head Dimension64
  • Hidden Width1024
  • SwiGLU Intermediate2816
  • Context Window1024 tokens
  • Vocabulary16,384 (BPE)

Key Mechanisms

  • NormalizationRMSNorm
  • AttentionCausal + QK-Norm
  • PositionsLearned Absolute
  • ResidualsScaled by 1/√24
  • Output HeadTied to Embeddings
  • TokenizerSentencePiece
  • Byte FallbackEnabled

The Math

# RMSNorm (No mean subtraction)
y = x / sqrt(mean(x²) + 1e-5) ⊙ g

# SwiGLU Feed-Forward
FFN(x) = (SiLU(x W1) ⊙ (x W2)) W3

# Residual Scaling (Variance control)
x ← x + (1 / sqrt(24)) * Sublayer(RMSNorm(x))

Training Pipeline

The model was trained in two distinct phases: raw next-token prediction, followed by supervised fine-tuning (SFT) with masked loss.

Phase 1: Pretraining

FineWeb-Edu (70%)
Cosmopedia (20%)
Python-Edu (10%)

Phase 2: Supervised Fine-Tuning (SFT-1)

The base model was fine-tuned on ~78,000 examples. Loss was strictly masked to assistant tokens; the model is never penalized for failing to predict the user's prompt.

The Failure Ledger

Building a training pipeline from scratch on constrained hardware surfaces every edge case in PyTorch. These are the 9 major defects encountered, and how they were resolved.

01 The 8x Loss Illusion

The dashboard displayed a loss of ~35.0, while validation was ~4.4. Cause: The GPU accumulator summed one mean-loss per micro-step (8 per optimizer step), but the readout only divided by the number of optimizer steps. Fix: Divide the running sum by nwin * accum_steps.

02 The Resume Rewind

Restarting with --resume silently threw away 10 hours of compute. Cause: best.pt only updated when validation improved. During long flat stretches, it went stale, and --resume loaded the old file. Fix: Introduced last.pt which saves every 500 steps regardless of validation metrics. Resume prefers last.pt.

03 Data Prep OOM at 645M Tokens

The data builder was killed by the OS on a 32GB machine. Cause: Holding token IDs in Python lists consumes ~36 bytes per integer. Fix: Streamed documents through a generator and flushed raw int32 binary chunks directly to disk every 4M tokens. Peak RAM dropped to <1GB.

04 CUDAGraph Collisions

torch.compile(mode="max-autotune") crashed on step 2. Cause: Max-autotune enables CUDA graphs, which require static memory addresses. Gradient accumulation with set_to_none=True frees and reallocates .grad tensors, breaking the graph. Fix: Reverted to mode="default".

05 The 134MB OOM

Out of memory errors at exactly 128MB allocations. Cause: The cross-entropy loss function was manually casting logits to .float() in Python, materializing a massive 134MB fp32 tensor before the kernel ran. Fix: Removed the manual cast. F.cross_entropy handles bf16 natively and upcasts internally.

06 Punctuation Soup

Generation output ⁇ user|> |||||||||. Cause: The streaming data pipeline dropped the regex split for chat markers, meaning the literal text <|user|> was tokenized as standard subwords instead of reserved IDs 3 and 4. Fix: Restored the marker split in the tokenizer wrapper.

07 Checkpoint Memory Leak

Resuming from a checkpoint immediately caused an OOM. Cause: torch.load(..., map_location="cuda") loaded the 1.3GB checkpoint into VRAM, and the local variable c was never deleted, keeping a second copy of the weights alive. Fix: Load to CPU (map_location="cpu"), copy to model, then del c.

08 Dynamic Shape Thrashing

SFT training was 4x slower than pretraining and VRAM kept climbing. Cause: The SFT batch builder grouped examples by exact token length, resulting in hundreds of unique sequence lengths. torch.compile recompiled the graph for every new shape. Fix: Snapped sequence lengths to 6 static buckets (128, 256, 384, 512, 768, 1024) and padded to the bucket ceiling.

09 Random Validation Noise

Validation loss bounced wildly, making it impossible to tell if the model was improving. Cause: evaluate() drew fresh random windows from the validation set on every call. Fix: Generated a fixed set of random seeds at startup to evaluate the exact same validation windows every time.

Usage

Lyra uses a custom architecture and is not natively supported by the transformers library. You must use the provided model.py and lyra_tokenizer.py files.

Installation

git clone https://huggingface.co/luka0x12/Lyra-326M-Instruct
cd Lyra-326M-Instruct
pip install torch safetensors sentencepiece numpy

Interactive Chat

python chat.py

Python API

import torch
from model import GPT, GPTConfig
from lyra_tokenizer import Tokenizer
from safetensors.torch import load_file
import json

# Load config and weights
cfg = json.load(open("config.json"))
model = GPT(GPTConfig(**cfg))
model.load_state_dict(load_file("model.safetensors"), strict=False)
model.eval()

# Load tokenizer
tok = Tokenizer("tok.model")

# Build prompt
prompt = "<|user|>What is the capital of France?<|assistant|>"
ids = torch.tensor([tok.encode(prompt)])

# Generate (simplified)
with torch.no_grad():
    logits, _ = model(ids)
    # ... sampling logic ...