A first-principles book on LLMs Two volumes available now

You can call the API.
But could you explain
what just happened?

  • Why does pasting the same prompt twice often give a better answer?
  • Why does GPT-4 fail on "how many Rs in strawberry" but work if you spell it out?
  • Why does LoRA fine-tune a 70B model on one consumer GPU?

Most engineers can call an LLM API. Almost none can explain what happens after the request leaves their machine. They patch around strange behavior with prompt tricks they found by accident. Then ship those tricks into production with nothing to fall back on when something breaks.

This book is the answer.

Inside Large Language Models, Volume I: Foundations and the Complete Transformer Inside Large Language Models, Volume II: Inference, Optimization, and Fine-Tuning

What you will learn across both volumes

  • Large Language Models
  • Transformer Architecture
  • Attention Mechanism
  • Multi-Head Attention
  • Tokenization & BPE
  • Embeddings
  • Positional Encoding
  • Build a GPT from Scratch
  • PyTorch
  • LLM Fine-Tuning
  • LoRA & QLoRA
  • RLHF
  • Instruction Tuning
  • KV Cache
  • Inference Optimization
  • Quantization
  • Prompt Engineering
  • Function Calling
  • AI Agents
  • Agentic AI
  • Tool Use
  • Text-to-SQL
  • Document Classification
  • Production LLMs
  • Math for Machine Learning
  • Backpropagation
  • LLM Interview Questions
  • AI Engineer Interview Prep

Four things you have already noticed.
Four mechanisms most engineers cannot explain.

You noticed

Pasting the prompt twice gets you a better answer.

The mechanism

Decoders generate one token at a time, and every new token correlates with everything before it through attention. Repeat the instruction and the model sees it once near the start, where attention weights run hot, and once at the end, where recency dominates. The signal stacks. Position is not metadata. Position is the math.

Volume I · Chapters 5, 6, 9
You noticed

"How many Rs in strawberry" fails. Spelling it out works.

The mechanism

The model never sees individual letters. Byte-Pair Encoding compresses the word into about two integer token IDs. Counting characters inside a single learned 4096-dimensional vector is asking the model to do something it cannot do. Spell it out and you change the tokenization. Now the letters are separately addressable.

Volume I · Chapters 3, 4
You noticed

Temperature, top-k, top-p change the output. But how?

The mechanism

Temperature divides the model's raw logits before the softmax. Set it to 2 and the distribution flattens. Set it to 0.5 and it sharpens. Top-k truncates to the k highest probabilities, a hard cliff. Top-p adds candidates until cumulative probability reaches p, a soft cutoff that adapts to the distribution. Stop guessing. Start predicting which one will fail when your prompt shifts.

Volume II · Chapter 10
You noticed

LoRA fine-tunes a 70B model on one GPU. How is that even possible?

The mechanism

Full fine-tuning updates every parameter. Billions of degrees of freedom for a task that needs a few thousand. The actual weight update lives in a low-rank subspace. LoRA decomposes it into two small matrices with about 0.1 percent of the parameters. Optimizer state, gradients, and activation memory all shrink by that ratio. Not just the parameter count. The whole memory budget collapses.

Volume II · Chapters 12, 14–17

Knowing the trick is folklore. Knowing the mechanism is the difference between shipping and explaining. Between a hack and a system. Between building once and building reliably.

Two volumes. Eighteen chapters.
Read them in order, or buy the one you need first.

Volume I cover

Volume I

Foundations & the Complete Transformer

Chapters 1 to 9

For the engineer who has shipped with the API and now wants to read a transformer paper without bouncing off Section 3. Builds the model from scratch in PyTorch.

  • Tokenization, embeddings, positional encoding
  • Single-head and multi-head attention
  • Residuals, layer norm, the feed-forward network, the LM head
  • Building and training a complete GPT from scratch (Chapter 9)
Volume II cover

Volume II

Inference, Optimization & Fine-Tuning

Chapters 10 to 18

For the engineer who has been told to fine-tune for the company's actual domain and is six tabs deep in Hugging Face docs without a clear path. Four end-to-end applied projects.

  • Inference internals, KV cache, prefix caching, quantization, batching
  • RLHF, instruction tuning, full fine-tuning vs LoRA vs QLoRA
  • Four applied projects: contract classification, legal-document QLoRA, text-to-SQL, and function calling
  • The function-calling foundation that powers AI agents and agentic AI workflows

A peek inside.
Seven diagrams from the book. This is not even one percent of what is in there.

Byte-Pair Encoding tokenization process
Chapter 3 Byte-Pair Encoding, step by step. How "strawberry" becomes two integer IDs and why that explains every character-counting failure you have ever seen.
Single-head attention overview
Chapter 5 Single-head attention, fully drawn. Queries, keys, values, dot products, softmax. Every arrow color-coded. Every dimension labeled.
Complete GPT architecture
Chapter 7 The complete GPT architecture. Embeddings, transformer blocks, the LM head, the loss. The full system on one page, ready to be built in code.
Autoregressive generation flow
Chapter 9 Autoregressive generation, one token at a time. The mechanism that makes prompt-doubling work. The mechanism that makes streaming feel alive.
KV cache growth
Chapter 10 KV cache growth at inference time. Why putting the variable part of your prompt at the end can cut your bill by 10x. Production-grade insight in one diagram.
LoRA architecture
Chapter 12 LoRA in one picture. Frozen base weights. Two small trainable matrices. The geometric reason why 0.1 percent of parameters is enough.
QLoRA memory budget
Chapter 12 QLoRA memory budget, every byte accounted for. Where the 100x memory reduction comes from, with exact numbers for a 70B model on a single consumer GPU.

Seven diagrams. The book has hundreds.

Each transformation, each operation, each decoder pass is drawn out. Color-coded inputs, computed values, results, and aggregations. Step cards that walk you through the math one tensor at a time. Code with line-by-line annotations. This is not a book you skim. It is a book you build along with.

Every line of math, built up from scratch.
No graduate-level background assumed. If you can read Python, you can read this book.

Most LLM books assume you remember your linear algebra. This one teaches every operation right where it appears, with worked numerical examples, color-coded tensors, and step-by-step breakdowns. From dot products in Chapter 5 to backpropagation in Chapter 8 to cross-entropy loss in Chapter 16, the math is built up where you need it, not gated behind a prerequisites chapter you have to suffer through first.

Dot product similarity broken down step by step with color-coded vectors
Chapter 5

Dot products and similarity

Multiply position by position, add the results, that is it. Chapter 5 builds attention from this single operation. Color-coded so you see exactly which numbers came from where.

Weighted sum operation with attention weights and value vectors
Chapter 5

Weighted sums and softmax

Attention is just a weighted sum where the weights come from a softmax. Both operations are walked through with concrete numbers, before any matrix notation appears.

Cross-entropy loss calculation step by step from logits to scalar loss
Chapter 16

Cross-entropy loss

The loss function that trains every modern LLM. You see it as a sum, you see it as a probability, you see why it punishes confidence in wrong answers. No "the loss is calculated" hand-waving.

AdamW optimizer intuition with momentum and adaptive learning rate
Chapter 8

Optimizers and gradients

Backpropagation, AdamW, weight decay. The intuition first, then the equations, then the PyTorch code that implements them. Three passes through the same idea so it actually sticks.

What you actually need to start: Python (loops, classes, NumPy basics), high-school math (multiplication, exponents, basic graphs), and curiosity. That is it. Calculus shows up briefly for backprop, and Chapter 8 walks through the chain rule from scratch when you need it.

Interview-grade Q&A in every chapter.
150+ scenario-based questions across the two volumes.

Not "what is attention?" trivia. Real scenarios where you have to debug, decide, or defend a choice in front of a hiring manager. The kind of questions FAANG teams, AI labs, and AI-first startups actually ask. Sample of what is inside, with chapter references so you know where the full answer lives.

Volume I · Chapter 6 Why does multi-head attention split d_model across heads instead of running multiple full-dimension attention operations in parallel?

Same total compute as single-head attention, but each head can specialize on different relationships (syntactic, positional, semantic, long-range vs. local). Splitting d_model means head outputs concatenate back to d_model with no extra projection cost. Multiple full-dimension heads would multiply both compute and parameters with no upside, because the heads would learn redundant patterns. The split forces specialization.

Volume I · Chapter 5 Scaled dot-product attention divides QKT by √dk before the softmax. What breaks if you remove the scaling?

As d_k grows, the variance of the dot products grows with it. Without scaling, the softmax inputs blow up, the distribution saturates into a near one-hot, and the gradient through the non-attended entries goes to zero. Training stalls. Dividing by √dk keeps the dot products in a regime where the softmax stays smooth and gradients flow to every key position.

Volume II · Chapter 12 You fine-tune with LoRA rank 4 and the model underfits. Rank 8 also underfits. Rank 16 works but training is slow. What is the principled way to pick rank?

The intrinsic dimension of the task-specific weight update sets the minimum rank. Probe-train on a small subset of your data across ranks 4, 8, 16, 32. The smallest rank where validation loss plateaus is your answer. If even rank 32 underfits, the task likely requires moving general capabilities, not specializing them. At that point you reach for QLoRA at higher rank or full fine-tuning.

Volume II · Chapter 10 A user reports your RAG system gives correct answers with 5 chunks but wrong answers with 50. What is happening at the attention level and how do you fix it?

Two compounding effects. First, attention is a softmax over the full context, so the relevant chunk competes against 49 distractors and its weight drops by roughly an order of magnitude. Second, decoders under-attend to the middle of long contexts (lost-in-the-middle, Liu et al. 2023), and 50 chunks puts the relevant one in the middle band ~80% of the time. Fix: re-rank to top-5, place the best chunk at the start or end of context, and use a cross-encoder reranker before the LLM call.

Volume I · Chapter 9 & Volume II · Chapter 10 Training loss is decreasing smoothly but the model produces gibberish at inference. Three most likely causes, in order of probability?

(1) Train and inference tokenizer mismatch. Different special tokens, different pad token, different BOS/EOS handling. The model sees an out-of-distribution prefix at generation time and produces noise. (2) Sampling parameters wrong for the task. Temperature too high for code generation, top-p too restrictive for creative tasks, or no special-token suppression. (3) Position encoding mismatch. Trained on max sequence length 2048, inferring at 4096 with no rope-scaling. The model has never seen positions that high.

Volume II · Chapter 10 Why does temperature=0 not always give deterministic outputs even with the same prompt and the same model?

Argmax over logits is theoretically deterministic. In practice, GPU floating-point operations are non-associative, so reduction order changes per batch shape and per kernel. Different batching across requests, different cuBLAS algorithm selection, or speculative decoding can all shift the rounding by a few ULPs, occasionally flipping the argmax when two top candidates are within that delta. Determinism in production needs greedy decoding plus pinned kernels plus batch-size locking.

Each chapter ends with 10 to 15 questions like these. Some test the mechanism, some test the trade-off, some test debugging instincts. Across the two volumes, you finish with 150+ scenario-based questions you can actually use to prepare for an LLM-engineer or AI-engineer interview.

After both volumes you will be able to…

01

Read the original transformer paper end to end and recognize every component on the page.

02

Explain attention, residuals, and layer norm without reaching for an analogy you do not trust.

03

Build and train a complete GPT from scratch in PyTorch.

04

Pick a fine-tuning approach (full FT vs LoRA vs QLoRA vs RLHF) and defend the choice.

05

Walk through four end-to-end fine-tuning projects on real domains.

06

Optimize inference for production: KV cache, quantization, batching, speculative decoding.

07

Build the function-calling foundation that AI agents and agentic AI workflows depend on.

08

Predict when a prompt trick will fail. Predict why a fine-tune will work. Stop guessing.

Ritesh Modi, author of Inside Large Language Models

About the author

Ritesh Modi

Head of AI, MarketOnce Ex-Microsoft, Principal Forward Deployed Engineer

Ritesh has spent years building and shipping AI systems in production. At Microsoft, as a Principal Forward Deployed Engineer, he worked alongside enterprise teams turning research-grade models into reliable products. Today, as Head of AI at MarketOnce, he runs the AI organization end to end, from model selection and fine-tuning to inference cost and reliability.

He wrote Inside Large Language Models for the engineer he used to be: someone who could call the API but could not explain what was happening underneath. Two volumes are the book he wishes had existed when he started.

riteshmodi.com →

Frequently asked questions
Everything readers want to know before they click buy.

What is the difference between Volume I and Volume II?

Volume I covers foundations and the complete transformer architecture in nine chapters: tokenization, embeddings, positional encoding, attention, residuals, layer norm, the feed-forward network, and a complete GPT built from scratch in PyTorch. Volume II covers what happens after a model is trained: inference internals, KV cache, quantization, batching, RLHF, instruction tuning, LoRA, QLoRA, and four end-to-end applied projects on real domains.

Which volume should I read first?

If you want to understand how transformers work and read research papers without bouncing, start with Volume I. If you need to ship a fine-tuned LLM into production for a specific domain like legal, SQL, function-calling, or classification, Volume II is the faster path to the answers you need.

What background do I need before reading this book?

Comfort with Python (loops, classes, NumPy basics) and a working understanding of neural networks at a high level. You do not need a graduate degree, you do not need to have read the original transformer paper, and you do not need linear algebra beyond matrix multiplication and dot products. Every concept is built up from intuition first, math second.

What programming language and framework is used?

PyTorch throughout. Volume I builds a complete GPT from scratch in PyTorch in Chapter 9. Volume II uses PyTorch with Hugging Face Transformers and PEFT for the four applied fine-tuning projects.

Does the book cover the latest models like GPT-4, Claude, and Llama?

The mechanisms taught in the book are what every modern LLM is built on: decoder architecture, tokenization, attention, KV cache, RLHF, LoRA. Once you understand these, every commercial model you use, including GPT-4, Claude, Gemini, and the Llama family, becomes legible. The book teaches the substrate, not the API surface.

How is this book different from other LLM books that build a GPT from scratch?

Most build-from-scratch books stop at training a small GPT. Inside Large Language Models keeps going. After Volume I builds and trains the model, Volume II walks through production inference, optimization, RLHF, and four applied fine-tuning projects on real domains: contract classification, legal QLoRA, text-to-SQL, and function calling. You finish with a model in production, not just a model on disk.

Will I be able to build a GPT from scratch after reading?

Chapter 9 of Volume I is exactly this exercise. By the end you will have written every component of a GPT in PyTorch and trained it on real text. Every line is annotated. Every tensor shape is shown.

Does this book cover AI agents and agentic AI?

Chapter 17 of Volume II covers function calling end to end: the LLM-side capability that AI agents and agentic AI workflows depend on. Tool use, structured output, the model-side mechanics that let an LLM decide which function to call and what arguments to pass. The book does not cover specific agent frameworks like LangChain, AutoGPT, or CrewAI. It teaches the LLM-side foundation that every agent framework builds on. Once you understand function calling at the level this book teaches, every agent framework becomes a thin wrapper around what you already know.

Where can I buy the book?

Volume I is available on Leanpub and Amazon. Volume II is available on Amazon. Direct links are at the top and bottom of this page.

Two volumes. Available now.

Stop patching production with prompts you cannot explain.

Every week without this knowledge is another week of folklore engineering. Another shipping decision made on guesswork. Another LLM bug nobody on your team can debug.

Volume I

Foundations & the Complete Transformer. Chapters 1 to 9.

Buy on Leanpub Buy on Amazon

Volume II

Inference, Optimization & Fine-Tuning. Chapters 10 to 18.

Buy on Amazon

If you have ever found a prompt trick that just worked and wished you knew why, these books are written for you. Not someday. Today.