Custom Language Model

Custom Language Model

A GPT-2 Small equivalent LLM built from scratch with PyTorch—custom tokenizer, transformer blocks, and training loop.

Technologies Used

DockerFlaskHugging Face TokenizersPythonPyTorchReactTypeScript

Overview

A decoder-only transformer language model built from first principles. The architecture follows GPT-2 Small: 12 transformer layers, 12 attention heads, 768 embedding dimensions, and a 1024-token context window. Trained on 100K+ synthetic customer service conversations using a custom BPE tokenizer.

Read the full story →


Model Architecture

Specifications

ComponentValue
Vocabulary Size5,000 tokens (BPE)
Context Length1,024 tokens
Embedding Dimension768
Transformer Layers12
Attention Heads12
Head Dimension64 (768 / 12)
Feed-Forward Hidden3,072 (4 × 768)
Dropout0.2
Parameters~85 million

Component Stack

The model is composed of five core modules:

  1. EmbeddingModule — Token embeddings + learned positional embeddings, summed to produce input representations of shape (B, T, 768)

  2. SelfAttentionHead — Single attention head with Q/K/V projections. Uses a causal mask (lower triangular) to prevent attending to future tokens. Scaled dot-product attention with head_size^-0.5 normalization.

  3. MultiHeadAttention — 12 parallel attention heads, concatenated and projected back to 768 dimensions

  4. FeedForward — Two-layer MLP with ReLU activation: 768 → 3072 → 768 with dropout

  5. TransformerBlock — Pre-LN architecture: LayerNorm → Attention → Residual → LayerNorm → FFN → Residual

Forward Pass

Input IDs (B, T)
    ↓
Token Embedding + Positional Embedding → (B, T, 768)
    ↓
12× TransformerBlock
    ↓
Final LayerNorm
    ↓
Linear Head → Logits (B, T, vocab_size)
    ↓
Cross-Entropy Loss (against shifted targets)

Tokenization

Custom BPE tokenizer trained with Hugging Face tokenizers library:

TokenID
<|unk|>Unknown token
<|pad|>Padding (ignored in loss)
<|user|>User turn marker
<|assistant|>Assistant turn marker
<|endoftext|>End of conversation

Training data format:

<|user|>
Hi, I just received my latest invoice and there's a charge for "Premium Support" that I don't remember signing up for. Can you help me figure out what's going on?
<|assistant|>
Absolutely, I'd be happy to help. Let me pull up your account details. Could you confirm the invoice number or the date it was sent?
<|user|>
Sure, the invoice number is INV-2025-0789 and it was issued on September 12th.
<|assistant|>
Thanks! I see the invoice in our system. The "Premium Support" line appears because a trial subscription for that service was activated automatically when you upgraded your plan last month. Did you notice any changes in your plan around that time?
<|user|>
I didn't realize there was a trial. I thought the upgrade was just to get more storage.
<|assistant|>
That makes sense. The trial is free for 30 days, but the billing cycle starts after that period. I can cancel the Premium Support trial for you and adjust the invoice so you're not charged. Would that be okay?
<|user|>
Yes, please cancel it. Also, can you confirm that I won't see any additional charges for that service in the next month?
<|assistant|>
I've canceled the trial, and I've updated your invoice to remove the Premium Support line. You won't see any more charges for that service, and I've sent a revised invoice to your email. Let me know if there's anything else I can help with.
<|endoftext|>

Loss masking: User turns are masked with -100 so the model only learns to predict assistant responses, not echo user input.


Training Configuration

HyperparameterValue
Batch Size32
Learning Rate1e-4
OptimizerAdamW (weight decay: 0.1)
LR ScheduleCosine annealing with 100-step warmup
Gradient Accumulation4 steps
Epochs500 (with early stopping)
Early Stopping Patience5 epochs
Eval IntervalEvery 100 steps

Training Loop Highlights

  • Gradient accumulation: Effective batch size of 128 (32 × 4) while staying within VRAM limits
  • Learning rate warmup: Linear warmup over 100 steps before cosine decay
  • Checkpointing: Model, optimizer, and scheduler states saved after each epoch
  • Early stopping: Training halts if validation loss doesn't improve for 5 consecutive epochs

Inference & Generation

Sampling Parameters

ParameterDefaultDescription
max_tokens50Maximum tokens to generate
temperature0.7Softmax temperature (higher = more random)
top_k50Consider only top-k most likely tokens
top_p0.9Nucleus sampling threshold
repetition_penalty1.2Penalty applied to repeated tokens

Generation Algorithm

  1. Encode prompt with <|user|>...<|assistant|> format
  2. Forward pass → get logits for last position
  3. Apply repetition penalty to previously generated tokens
  4. Scale by temperature
  5. Apply top-p (nucleus) filtering OR top-k filtering
  6. Sample from resulting distribution
  7. Append token, repeat until <|endoftext|> or max tokens

Deployment Stack

LayerTechnology
Inference APIFlask with CORS, streaming SSE
FrontendReact + TypeScript
ContainerizationDocker (CPU and GPU variants)
Model ServingPyTorch with torch.no_grad() context

Try It Yourself

The demo exposes all generation parameters—temperature, top-k, top-p, and repetition penalty—so you can see how each affects output quality.

Launch the Demo →

// work with me

Want a build like this for your own business? I take on a limited number of engagements spanning technology consulting, AI engineering services, and website development & hosting.

// more from the record

Related Projects

ClickIQ: An AI-Powered Marketing Intelligence & Automation Platform
project · related

ClickIQ: An AI-Powered Marketing Intelligence & Automation Platform

As the lead architect and engineer, I spearheaded the development of ClickIQ, an AI-driven advertising intelligence platform that transformed Click Here Digital's operations by automating campaign management, unifying data analytics, and providing a single source of truth for measuring ROI across a vast digital landscape.

Amazon Web ServicesGoKubernetes
view project →
Facebook Ad Preview Validator
project · related

Facebook Ad Preview Validator

A recurring issue with the Facebook API was causing broken ad previews in client-facing reports, creating confusion and disabling a feature our clients had come to rely on. To address this, I developed the Facebook Ad Preview Validator, creating a classification engine, powered by Machine Learning, to validate ad creatives and protect the client experience.

Computer VisionDeep LearningDocker
view project →

tell me what you're building.

Free 30-minute consult. If I'm not the right fit, I'll say so and point you to who is.

Book a consultation