Registered users can read the full content for free
Register as a Gaohf Library member to read the complete e-book online for free and enjoy a better reading experience.
Page
1
Building Large Language Models from Scratch Design, Train, and Deploy LLMs with PyTorch — Dilyan Grigorov
Page
2
Building Large Language Models from Scratch Design, Train, and Deploy LLMs with PyTorch Dilyan Grigorov
Page
3
Building Large Language Models from Scratch: Design, Train, and Deploy LLMs with PyTorch ISBN-13 (pbk): 979-8-8688-2296-4 ISBN-13 (electronic): 979-8-8688-2297-1 https://doi.org/10.1007/979-8-8688-2297-1 Copyright © 2026 by Dilyan Grigorov This work is subject to copyright. All rights are reserved by the Publisher, whether the whole or part of the material is concerned, specifically the rights of translation, reprinting, reuse of illustrations, recitation, broadcasting, reproduction on microfilms or in any other physical way, and transmission or information storage and retrieval, electronic adaptation, computer software, or by similar or dissimilar methodology now known or hereafter developed. Trademarked names, logos, and images may appear in this book. Rather than use a trademark symbol with every occurrence of a trademarked name, logo, or image we use the names, logos, and images only in an editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the trademark. The use in this publication of trade names, trademarks, service marks, and similar terms, even if they are not identified as such, is not to be taken as an expression of opinion as to whether or not they are subject to proprietary rights. While the advice and information in this book are believed to be true and accurate at the date of publication, neither the authors nor the editors nor the publisher can accept any legal responsibility for any errors or omissions that may be made. The publisher makes no warranty, express or implied, with respect to the material contained herein. Managing Director, Apress Media LLC: Welmoed Spahr Acquisitions Editor: Celestin Suresh John Coordinating Editor: Gryffin Winkler Cover image designed by Giovanni_cg on unsplash.com Distributed to the book trade worldwide by Springer Science+Business Media New York, 1 New York Plaza, New York, NY 10004. Phone 1-800-SPRINGER, fax (201) 348-4505, e-mail orders-ny@springer-sbm.com, or visit www.springeronline.com. Apress Media, LLC is a Delaware LLC and the sole member (owner) is Springer Science + Business Media Finance Inc (SSBM Finance Inc). SSBM Finance Inc is a Delaware corporation. For information on translations, please e-mail booktranslations@springernature.com; for reprint, paperback, or audio rights, please e-mail bookpermissions@springernature.com. Apress titles may be purchased in bulk for academic, corporate, or promotional use. eBook versions and licenses are also available for most titles. For more information, reference our Print and eBook Bulk Sales web page at http://www.apress.com/bulk-sales. Any source code or other supplementary material referenced by the author in this book is available to readers on GitHub. For more detailed information, please visit https://www.apress.com/gp/services/ source-code. If disposing of this product, please recycle the paper Dilyan Grigorov Floor 7, Varna, Bulgaria
Page
4
To the University of Bath, where ideas flourish and boundaries are meant to be pushed. Within these walls, I found not just a place to study but a home where curiosity is celebrated and ambitious dreams are nurtured into reality. To Dr. Harish Tayyar Madabushi, my supervisor, mentor, and guide through the intricate world of language models. Your unwavering belief in my potential gave me the courage to tackle challenges I once thought insurmountable. To my son and my family! With profound gratitude and warmest regards.
Page
5
(This page has no text content)
Page
6
(This page has no text content)
Page
7
(This page has no text content)
Page
8
(This page has no text content)
Page
9
(This page has no text content)
Page
10
(This page has no text content)
Page
11
(This page has no text content)
Page
12
(This page has no text content)
Page
13
(This page has no text content)
Page
14
(This page has no text content)
Page
15
(This page has no text content)
Page
16
(This page has no text content)
Page
17
(This page has no text content)
Page
18
(This page has no text content)
Page
19
(This page has no text content)
Page
20
(This page has no text content)
The above is a preview of the first 20 pages. Register to read the complete e-book.
AI Reading Assistant
Whole-book reading guide from stratified index samples; jump to passages in the text
AI guide
【One-Line Pitch】
A hands-on engineering guide that walks you from the mathematical foundations of transformers to a working, deployable LLM built in PyTorch—best for developers and ML practitioners who want to understand every layer rather than call an API.
【Book Arc】
- **Opening (~0%–14%)**: Sets up the environment and mental model—what an LLM actually is, why the attention mechanism replaced RNNs, and which libraries (NumPy, Matplotlib, CUDA tooling) form the working stack.
- **Early (~14%–36%)**: Builds the mathematical and architectural foundation: scaled dot-product attention, the training objective, probability/optimization theory, and a survey of the 2025 model landscape (Qwen 3, GPT-4.5, Claude 3.7, Gemini 2.5) to frame design choices.
- **Early–Middle (~29%–46%)**: Implements a tokenizer from scratch—BPE algorithm, vocabulary construction, special tokens, save/load round-tripping—turning raw text into model-ready IDs.
- **Middle (~46%–60%)**: Moves into model configuration and internals: RMS normalization, depth (`num_hidden_layers`), `vocab_size`, and modern FFN activations like SwiGLU with gated activations.
- **Late (~60%–90%)**: Covers positional encoding in depth—RoPE, its 2D derivation, NTK and YaRN scaling variants—plus training mechanics and evaluation during pretraining, SFT, and alignment.
- **Ending (~90%–100%)**: Practical performance and deployment: CUDA kernels for training, GPU optimization strategies, scaling laws, responsible-AI considerations, and emerging trends.
【Key Takeaways】
- **Attention is the architectural cornerstone** (Opening): the book grounds everything in the transformer's scaled dot-product attention and why it solved RNN limitations—understanding this is prerequisite to every later chapter.
- **Tokenization is a first-class engineering task, not a preprocessing afterthought** (Early–Middle): a full BPE implementation with vocabulary trimming, special-token reservation, and merge-rank persistence shows how tokenizer design directly shapes model behavior.
- **Depth and vocabulary size are design trade-offs, not defaults** (Middle): `num_hidden_layers` controls hierarchical abstraction but risks vanishing gradients and overfitting; `vocab_size` defines the model's symbolic universe.
- **Modern FFNs rely on gated activations** (Middle): SwiGLU (SiLU gating + element-wise multiplication) boosts expressiveness in transformer MLP blocks, with clipping and tanh saturation as stability tools.
- **Positional encoding has evolved into a scaling problem** (Late): RoPE's geometric rotation intuition is extended via NTK and YaRN to handle long contexts—critical for modern long-window models.
- **Training is a staged pipeline** (Late): pretraining, supervised fine-tuning, and alignment each require distinct evaluation strategies, and benchmarks have real limitations.
- **CUDA-level optimization is where performance is won** (Ending): Tensor Cores, the Transformer Engine, NVLink, and custom kernels (CUTLASS, Triton) determine real-world training throughput.
- **Data and compute discipline beat architecture tricks** (Ending): the book closes on "data is king," scaling laws, degradation prevention, and responsible-AI practice.
【Reading Tips】
- **Deep-read Chapters 2–5** (attention math, tokenizer, config, RoPE)—these are the load-bearing concepts; skim the 2025 model survey if you already follow the field.
- **Code along with the tokenizer chapter**: the BPE save/load and re-encoding round-trip is the most concrete, testable artifact in the excerpts.
- **Treat the CUDA/performance chapter as a reference**, not a linear read—return to it when you hit a throughput bottleneck.
- **Watch for the math-to-code bridge**: the book pairs formulas (scaled dot product, RoPE rotation) with PyTorch implementations; read both together.
- **Note the 2025 framing**: model comparisons (Qwen 3, GPT-4.5, Claude 3.7, Gemini 2.5) date quickly—extract the design principles, not the leaderboard.
【Coverage Limits】
The excerpts are heavily weighted toward the table of contents, tokenizer implementation, and configuration chapters; deployment specifics, full training loops, and the alignment/RLHF details are only partially visible, so this guide reflects the book's stated scope rather than verified chapter-by-chapter depth.
Passage locations
Excerpt 1
78 Data Is King 478 Computational Resource Management 478 Preventing Degradation 479 Scaling Laws and Efficiency 480 Responsible AI Considerations 480 The Fu...
View in text
Excerpt 2
atives LZMA compresses much better than GZIP/BZIP2 (though slower), making it ideal for large static datasets but less suitable for real-time or frequently u...
View in text
Excerpt 3
ost frequent pair of adjacent tokens to build a vocabulary. Below is a detailed outline of the BPE algorithm, as adapted for NLP. Identify Frequent Pairs In...
View in text
Excerpt 4
tok_vocab.json demo_tok_merges.json Re-encode after load: Before IDs: [41, 6, 46, 5, 24, 6, 44, 23] After IDs: [41, 6, 46, 5, 24, 6, 44, 23] Match? True Done...
View in text
Recommended for You
{{#thumbnailUrl}}
{{/thumbnailUrl}}
{{^thumbnailUrl}}
{{/thumbnailUrl}}
Loading recommended books...
Failed to load, please try again later
Tip the Site
Scan the WeChat Pay or Alipay code to tip. No login required.
WeChat Pay
Alipay