Leanpub Header

Skip to main content

Building Large Language Models from Scratch

A Practical Guide to Training Your Own Transformer-Based AI in Python

This book is 100% completeLast updated on 2026-07-03

Learn how large language models work instead of relying on black-box APIs. Building Large Language Models from Scratch takes you through training a Transformer model in PyTorch, from raw text to a working inference API, covering tokenization, attention, distributed training, and alignment along the way.

Minimum price

$19.00

$29.00

You pay

Author earns

$

Also available for 1 book credit with a Reader Membership

PDF
EPUB
About

About

About the Book

Large language models power some of the most powerful software tools ever built, yet their inner workings remain mysterious to most developers. This book changes that. Starting from raw text and ending with a live inference API, you will build a complete LLM training pipeline from scratch using PyTorch. Every concept is explained clearly, every code listing is production-quality, and every chapter ends with hands-on exercises that cement your understanding. By the time you finish, you will understand tokenization, attention, positional encoding, transformer architecture, data curation, distributed training, fine-tuning, alignment, evaluation, and deployment at a level that no API wrapper can provide.

Share this book

Bundle

Bundles that include this book

Author

About the Author

Steve T. Publications

Steve T. is a cybersecurity leader, researcher, and engineer with more than 20 years of experience across application security, infrastructure security, vulnerability management, software development, and secure engineering practices. Having built his career alongside the growth of the modern internet, he has worked through multiple generations of technology, evolving security threats, and changing development methodologies.

He is currently part of the advanced research organization at a leading cybersecurity company, where he focuses on emerging threats, security innovation, and the practical application of research. His work involves investigating new attack techniques, evaluating emerging technologies, conducting deep technical analysis, and helping organizations better understand and manage complex security risks.

In addition to his research responsibilities, Steve leads a team of senior engineers and subject matter experts who create technical books, training programs, and educational resources for security professionals. Through this work, he helps engineers, developers, architects, and security practitioners strengthen their skills and build more secure systems.

Steve's technical expertise spans software development, reverse engineering, web application security, penetration testing, security architecture, incident response, vulnerability research, operating system internals, and secure software development. His ability to analyze systems at both the source code and binary levels enables him to bridge the worlds of software engineering, security research, and practical defense.

Over the course of his career, Steve has worked with organizations across a wide range of industries, helping them identify, assess, and remediate security weaknesses in critical applications and infrastructure. He is recognized for combining deep technical expertise with a pragmatic approach to security, focusing on solutions that are effective, sustainable, and aligned with business goals.

Through his work in research, engineering, leadership, and education, Steve continues to contribute to the advancement of cybersecurity and the development of secure, resilient technology systems.

Contents

Table of Contents

Building Large Language Models from Scratch

A Practical Guide to Training Your Own Transformer-Based AI in Python

Introduction: Why Build from Scratch?

  1. The Black Box Problem
  2. What You Will Build
  3. Prerequisites and How to Use This Book
  4. A Note on Hardware Requirements

Chapter 1: Tokens, Vocabularies, and Tokenization

  1. From Text to Numbers: The Tokenization Pipeline
  2. Character-Level vs Word-Level vs Subword Tokenization
  3. Building a Byte-Pair Encoding (BPE) Tokenizer
  4. Vocabulary Size, Special Tokens, and Edge Cases
  5. Exercise: Tokenize the Shakespeare Corpus

Chapter 2: Embeddings: Turning Tokens into Vectors

  1. The Embedding Layer as a Lookup Table
  2. Learning vs Pre-trained Embeddings
  3. Vector Space Geometry and Similarity
  4. Implementing Embedding Layers in PyTorch
  5. Exercise: Visualize an Embedding Space

Chapter 3: The Attention Mechanism

  1. What Is Attention and Why It Matters
  2. Scaled Dot-Product Attention from First Principles
  3. Multi-Head Attention: Parallelizing Understanding
  4. Causal Masking for Decoder-Only Models
  5. Exercise: Trace Attention Through a Sentence

Chapter 4: Positional Encoding and Sequence Structure

  1. The Permutation Invariance Problem
  2. Sinusoidal Absolute Positional Encodings
  3. Learned Position Embeddings
  4. Rotary Positional Embeddings (RoPE)
  5. Exercise: Implement Three Position Encoding Schemes

Chapter 5: Building the Decoder-Only Transformer Architecture

  1. The Decoder-Only Design Decision
  2. Feed-Forward Networks and MLP Blocks
  3. Residual Connections and Layer Normalization
  4. Assembling the Full Transformer Block
  5. The Complete Decoder-Only Model
  6. Exercise: Build a 3-Layer Decoder from Scratch

Chapter 6: Data Preparation for Language Model Training

  1. The Data Landscape: Where Does Training Data Come From?
  2. Cleaning and Filtering Pipeline Design
  3. Deduplication Strategies
  4. Dataset Mixing and Domain Balancing
  5. Synthetic Data Generation Strategies
  6. Exercise: Build a Mini C4 Dataset

Chapter 7: The Training Loop: Loss, Optimizers, and Gradient Flow

  1. Cross-Entropy Loss and Next-Token Prediction
  2. The AdamW Optimizer and Why It Works
  3. Learning Rate Schedules: Warmup, Cosine Decay, and Beyond
  4. Gradient Clipping and Training Stability
  5. The Complete Training Loop
  6. Exercise: Train on a Tiny Dataset and Monitor Loss Curves

Chapter 8: Memory-Efficient Training Patterns

  1. The Memory Wall: Why Models Don’t Fit in GPU RAM
  2. Mixed-Precision Training with BF16/FP16
  3. Gradient Accumulation for Effective Batch Sizes
  4. Activation Checkpointing and Recomputation
  5. Exercise: Train a 10x Larger Model on the Same Hardware

Chapter 9: Distributed Training and Parallelism Strategies

  1. Data Parallelism and Distributed Data Parallel (DDP)
  2. Tensor Parallelism for Massive Models
  3. Pipeline Parallelism: Splitting the Forward Pass
  4. Fully Sharded Data Parallel (FSDP)
  5. Exercise: Multi-GPU Training Setup

Chapter 10: Checkpointing, Experiment Tracking, and Reproducibility

  1. Checkpointing Strategies and Recovery
  2. Experiment Tracking: Metrics, Configs, and Artifacts
  3. Reproducibility: Seeds, Determinism, and Hardware Variability
  4. Logging Design for Long Training Runs
  5. Exercise: Set Up a Production-Style Training Dashboard

Chapter 11: Fine-Tuning: LoRA, QLoRA, and Instruction Tuning

  1. The Fine-Tuning Landscape: Full vs Parameter-Efficient
  2. Low-Rank Adaptation (LoRA) from First Principles
  3. Quantized LoRA (QLoRA) for Memory-Constrained Fine-Tuning
  4. Instruction Tuning Dataset Design
  5. Exercise: Fine-Tune a Model on a Custom Task

Chapter 12: Alignment: RLHF and Beyond

  1. Why Raw Models Need Alignment
  2. The RLHF Pipeline: Reward Models and PPO
  3. Direct Preference Optimization (DPO) as a Simpler Alternative
  4. Constitutional AI and Rule-Based Alignment
  5. Exercise: Build a Simple Preference Dataset

Chapter 13: Evaluation: Metrics, Benchmarks, and Red Teaming

  1. Perplexity as a Training Metric vs Real-World Performance
  2. Standard Benchmark Suites (MMLU, GSM8K, HumanEval)
  3. Qualitative Evaluation and LLM-as-Judge
  4. Safety Testing and Red Teaming Methodologies
  5. Exercise: Build an Evaluation Harness

Chapter 14: Deployment: Inference, Quantization, and Serving

  1. Inference Optimization: KV Cache and Speculative Decoding
  2. Quantization Strategies: FP16 -> INT8 -> INT4
  3. Building a Serving API with FastAPI
  4. Containerization and Production Deployment Patterns
  5. Exercise: Deploy Your Model Behind a Live API

Capstone Project: From Raw Data to Live Inference

  1. Project Setup and Architecture Overview
  2. Data Preparation: Curating a 100M-Token Dataset
  3. Training Run: Configuration, Execution, and Monitoring
  4. Evaluation: Benchmarking Against Baselines
  5. Deployment: Containerized API with Health Checks
  6. Post-Mortem: What Went Well and What Would Be Different

Conclusion: The Road Ahead

  1. What You Have Accomplished
  2. Where to Go From Here: Scaling Up
  3. The Future of Language Models
  4. A Final Word on Building vs Using

References

Get the free sample chapters

Click the buttons to get the free sample in PDF or EPUB, or read the sample online here

The Leanpub 60 Day 100% Happiness Guarantee

Within 60 days of purchase you can get a 100% refund on any Leanpub purchase, in two clicks.

See full terms...

Earn $8 on a $10 Purchase, and $16 on a $20 Purchase

We pay 80% royalties on purchases of $7.99 or more, and 80% royalties minus a 50 cent flat fee on purchases between $0.99 and $7.98. You earn $8 on a $10 sale, and $16 on a $20 sale. So, if we sell 5000 non-refunded copies of your book for $20, you'll earn $80,000.

(Yes, some authors have already earned much more than that on Leanpub.)

In fact, authors have earned over $15 million writing, publishing and selling on Leanpub.

Learn more about writing on Leanpub

Free Updates. DRM Free.

If you buy a Leanpub book, you get free updates for as long as the author updates the book! Many authors use Leanpub to publish their books in-progress, while they are writing them. All readers get free updates, regardless of when they bought the book or how much they paid (including free).

Most Leanpub books are available in PDF (for computers) and EPUB (for phones, tablets and Kindle). The formats that a book includes are shown at the top right corner of this page.

Finally, Leanpub books don't have any DRM copy-protection nonsense, so you can easily read them on any supported device.

Learn more about Leanpub's ebook formats and where to read them

Write and Publish on Leanpub

You can use Leanpub to easily write, publish and sell in-progress and completed ebooks and online courses!

Leanpub is a powerful platform for serious authors, combining a simple, elegant writing and publishing workflow with a store focused on selling in-progress ebooks.

Leanpub is a magical typewriter for authors: just write in plain text, and to publish your ebook, just click a button. (Or, if you are producing your ebook your own way, you can even upload your own PDF and/or EPUB files and then publish with one click!) It really is that easy.

Learn more about writing on Leanpub