# Zero to Godhood: full text of the free sample chapters > Zero to Godhood is a book series by Shreejit Verma for engineers who want total mastery, not survey-level familiarity: C++ from C++98 to C++26, the evolutionary history of Python at the level of the implementation, and agentic AI engineering from first principles to the research frontier. > Copyright 2026 Shreejit Verma. All rights reserved. Content signals: search=yes, ai-input=yes, ai-train=no. --- # Chapter 12: Move Semantics and Smart Pointers > Free sample chapter from *C++: Zero to Godhood* (Book I of the Zero to Godhood series) by Shreejit Verma. > Canonical URL: https://zerotogodhood.com/books/cpp/move-semantics-and-smart-pointers/ > Copyright 2026 Shreejit Verma. All rights reserved. Content signals: search=yes, ai-input=yes, ai-train=no. > *The two features that, together, abolished the "performance tax" of C++ and replaced manual memory management with a formal model of ownership.* C++11 made two intertwined contributions that define modern C++ resource management. **Move semantics** let an object transfer ownership of its internal resources instead of deep-copying them, collapsing expensive copies into pointer swaps. **Smart pointers** encode ownership in the type system, making `new`/`delete` obsolete in user code. This chapter develops both from first principles, then unifies them through perfect forwarding. --- ## Table of Contents - [12.1 The Move Revolution](#121-the-move-revolution) - [12.2 Value Categories: lvalue, rvalue, and the Full Taxonomy](#122-value-categories-lvalue-rvalue-and-the-full-taxonomy) - [12.3 Rvalue References (`T&&`)](#123-rvalue-references-t) - [12.4 `std::move`: The Shipping Label](#124-stdmove-the-shipping-label) - [12.5 The Move Constructor and Move Assignment](#125-the-move-constructor-and-move-assignment) - [12.6 Complexity Optimization: O(n²) to O(n)](#126-complexity-optimization-on²-to-on) - [12.7 Perfect Forwarding and Reference Collapsing](#127-perfect-forwarding-and-reference-collapsing) - [12.8 Smart Pointers and RAII](#128-smart-pointers-and-raii) - [12.9 `std::unique_ptr`: Exclusive Ownership](#129-stdunique_ptr-exclusive-ownership) - [12.10 `std::shared_ptr`: Shared Ownership](#1210-stdshared_ptr-shared-ownership) - [12.11 `std::weak_ptr`: Non-Owning Observation](#1211-stdweak_ptr-non-owning-observation) - [12.12 `enable_shared_from_this` and Smart-Pointer Casts](#1212-enable_shared_from_this-and-smart-pointer-casts) - [12.13 Professional Insights](#1213-professional-insights) --- ## 12.1 The Move Revolution In the early 2000s C++ felt "heavy." Given a `std::vector` of 10,000 long strings, passing it to a function offered two bad choices: 1. **Pass by pointer** — fast, but ownership is ambiguous and dangerous. 2. **Pass by value** — safe, but the program would *clone* all 10,000 strings, then destroy the originals a microsecond later. This was the **performance tax** of C++. C++11 abolished it with **move semantics**: when the source of a copy is a temporary (or something you have explicitly given up), its resources can be *stolen* rather than duplicated. > **Fireside chat — the "magic box."** > *Student:* "Why does stealing need special syntax?" > *Architect:* "Because the compiler needs your **permission** to steal. If you are holding a sandwich (an **lvalue**), I cannot take a bite — that is theft. But a sandwich in a trash can marked *FREE* (an **rvalue**) is fair game. `std::move` is how you put the *FREE* sign on a variable you are done with." Think of memory as a neighborhood: an **lvalue** is a *house* — a permanent address with a name that persists; an **rvalue** is a *shipping box* — temporary, in transit, about to be discarded. In `int x = 10;`, `x` is the house (lvalue) and `10` is the delivery box (rvalue). --- ## 12.2 Value Categories: lvalue, rvalue, and the Full Taxonomy Every C++ expression has a **value category**. Two independent properties define them: - **Identity** — does the expression refer to a named object with an address? - **Movability** — may the expression be implicitly moved from (bound to a `T&&` parameter)? The standard combines these into three primary categories, plus two umbrella groupings: | Category | Identity | Movable | Examples | | :------- | :------: | :-----: | :------- | | **lvalue** | Yes | No | `x`, `*ptr`, `foo_ref()`, a string literal | | **xvalue** (eXpiring) | Yes | Yes | `std::move(x)`, `X{4}.n` | | **prvalue** (pure rvalue) | No | Yes | `42`, `x + 2`, `X{4}`, a lambda, `foo()` returning by value | | **glvalue** = lvalue ∪ xvalue | Yes | — | anything with identity | | **rvalue** = xvalue ∪ prvalue | — | Yes | anything movable-from | ```cpp // Listing 12.1: classifying expressions struct X { int n; }; extern X x; 4; // prvalue: no identity x; // lvalue x.n; // lvalue std::move(x); // xvalue: has identity AND is movable std::forward(x); // lvalue X{4}; // prvalue X{4}.n; // xvalue ``` The crucial, counter-intuitive rule: **a named rvalue reference is itself an lvalue.** ```cpp // Listing 12.2: a named rvalue reference is an lvalue std::string str("init"); std::string &&str_ref = std::move(str); // str_ref is a named variable std::string test(str_ref); // COPY — str_ref is an lvalue expression! std::string test2(std::move(str_ref)); // MOVE — re-apply std::move ``` This is *why* `std::forward` exists (§12.7): inside a function, the parameter is always a named lvalue, even when it was initialized from an rvalue. --- ## 12.3 Rvalue References (`T&&`) C++11 introduced the **rvalue reference** `T&&`, which binds *only* to rvalues. It is the "box snatcher" — a hook that grabs a temporary before it is destroyed so its contents can be pilfered. ```cpp // Listing 12.3: rvalue references bind only to rvalues int x = 10; int& lref = x; // lvalue reference binds to an lvalue // int&& bad = x; // ERROR: cannot bind rvalue ref to an lvalue int&& rref = 20; // OK: 20 is an rvalue ``` The point of having two reference types is to select two behaviors via overload resolution: **lvalue-reference overloads copy; rvalue-reference overloads move.** --- ## 12.4 `std::move`: The Shipping Label **`std::move` does not move anything.** It is an unconditional cast to an rvalue reference — a *shipping label* you stick on an lvalue that says "this house is now a box; feel free to take the furniture." The actual transfer happens later, inside a move constructor or move assignment operator. ```cpp // Listing 12.4: std::move enables the move overload Vector v1(100); Vector v2 = std::move(v1); // selects the move constructor // v1 is now in a valid-but-unspecified (typically empty) state ``` `std::move(obj)` by itself changes nothing about `obj`; only the move operation it *enables* does. **Do not read a moved-from object** except to assign to it or destroy it. --- ## 12.5 The Move Constructor and Move Assignment Instead of copying data (slow), move operations steal pointers (fast) and null out the source so its destructor does no harm. ```cpp // Listing 12.5: move constructor and move assignment class BigData { int* buffer; size_t size; public: // Move constructor BigData(BigData&& other) noexcept : buffer(other.buffer), size(other.size) { // A. steal the data other.buffer = nullptr; // B. nullify the victim other.size = 0; // else 'other's destructor double-frees our buffer } // Move assignment BigData& operator=(BigData&& other) noexcept { if (this != &other) { delete[] buffer; // free our own resources buffer = other.buffer; // steal size = other.size; other.buffer = nullptr; // nullify source other.size = 0; } return *this; } }; ``` ### Why `noexcept` is mandatory for moves If your move constructor is **not** `noexcept`, the standard containers will often *refuse to use it*. When `std::vector` reallocates, it must preserve the **strong exception guarantee**: if moving an element could throw mid-reallocation, the vector could not roll back to a consistent state. So it falls back to *copying* — silently discarding your move optimization. **Always mark moves `noexcept`.** > The compiler generates move operations for you when the class has no user-declared copy operations, destructor, or move operations. Declaring any of those (the "Rule of Five") suppresses the implicit moves — declare them all, or `= default` them, when managing a resource. --- ## 12.6 Complexity Optimization: O(n²) to O(n) Moving a container is **O(1)** (steal a pointer); copying is **O(n)**. In code written in an immutable style — where loops are expressed as recursion that logically copies a container each step (e.g. generating a Collatz sequence) — moves can collapse the overall complexity from **O(n²)** to **O(n)**. ```cpp // Listing 12.6: immutable-style recursion made linear by moves // (after Andrew Koenig, "Containers That Never Change", Dr. Dobb's, 2013) std::vector concat(std::vector const& v, int x) { auto result = v; // the only real copy result.push_back(x); return result; // returned by move (RVO / implicit move) } std::vector collatz_aux(int n, std::vector const& result) { if (n == 1) return result; auto next = concat(result, n); // moved into 'next' return (n % 2 == 0) ? collatz_aux(n / 2, next) : collatz_aux(3 * n + 1, next); } ``` Returning a local by value is automatically a move (or is elided entirely by RVO) — never write `return std::move(local);`, which can *defeat* copy elision. --- ## 12.7 Perfect Forwarding and Reference Collapsing Generic wrappers must pass arguments onward while preserving their value category (lvalue vs rvalue). This is **perfect forwarding**, and it rests on two mechanisms. ### 12.7.1 Forwarding (Universal) References When `T` is a *deduced* template parameter, `T&&` is a **forwarding reference**, not a plain rvalue reference — it binds to anything, and `T` encodes whether the argument was an lvalue or rvalue. ### 12.7.2 Reference Collapsing Rules | Combination | Collapses to | | :---------- | :----------- | | `& ` + `& ` | `&` | | `& ` + `&&` | `&` | | `&&` + `& ` | `&` | | `&&` + `&&` | `&&` | **Mnemonic:** an lvalue reference is a "black hole" — if `&` appears anywhere, the result is `&`. Only `&& + &&` stays `&&`. ### 12.7.3 `std::forward` `std::forward(arg)` casts `arg` back to an rvalue *only if* `T` was deduced from an rvalue; otherwise it passes it as an lvalue. It undoes the "named rvalue reference is an lvalue" problem from §12.2. ```cpp // Listing 12.7: a perfectly-forwarding wrapper template void wrapper(T&& arg) { // forwarding reference func(std::forward(arg)); // preserves value category } ``` ### 12.7.4 The canonical use: factory functions ```cpp // Listing 12.8: variadic perfect-forwarding factory (this IS make_unique) template std::unique_ptr make_unique(A&&... args) { return std::unique_ptr(new T(std::forward(args)...)); } struct Foo { Foo(const Foo&); Foo(Foo&&); Foo(int,int,int); }; Foo f; auto p1 = make_unique(f); // forwards lvalue -> copy ctor auto p2 = make_unique(std::move(f)); // forwards rvalue -> move ctor auto p3 = make_unique(1, 2, 3); // forwards prvalues ``` This is exactly how `emplace_back`, `make_shared`, and `make_unique` avoid extra copies. --- ## 12.8 Smart Pointers and RAII Manual dynamic memory in C++98 invited four classic defects: 1. **Memory leaks** — forgetting `delete`. 2. **Dangling pointers** — using memory after `delete`. 3. **Double free** — deleting the same memory twice. 4. **Exception-unsafety** — an exception thrown before `delete` leaks. Smart pointers solve all four through **RAII** (Resource Acquisition Is Initialization): the resource's lifetime is tied to an object's lifetime, so the destructor always releases it. The single axis that distinguishes the smart pointers is **ownership**: | Type | Ownership | Copyable? | Main use case | | :--- | :-------- | :-------- | :------------ | | `std::unique_ptr` | **Exclusive** | No (move-only) | Default for single-owner resources | | `std::shared_ptr` | **Shared** | Yes | Multiple co-owners of one resource | | `std::weak_ptr` | **None** (observer) | Yes | Observation; breaking reference cycles | --- ## 12.9 `std::unique_ptr`: Exclusive Ownership A non-null `std::unique_ptr` *exclusively* owns its pointee. It cannot be copied — only **moved** — which is how the type enforces a single owner at compile time. It is the lightest smart pointer, with essentially zero overhead over a raw pointer, and should be your **default**. ```cpp // Listing 12.9: move-only ownership transfer #include #include std::unique_ptr make() { return std::unique_ptr(new int(5)); } int main() { auto p1 = make(); // p1 owns the int // auto bad = p1; // ERROR: copy is deleted auto p2 = std::move(p1); // ownership transferred; p1 is now null int a = *p2; // OK // int b = *p1; // UB: p1 is nullptr } ``` Returning a `unique_ptr` is the **preferred C++11 way to write factory functions** — the return type documents that the caller now owns the resource, unlike a raw `int* foo();` where ownership is unclear. ### Custom deleters `unique_ptr` accepts a deleter type, ideal for C-style resources: ```cpp // Listing 12.10: custom deleters auto closer = [](FILE* f){ if (f) fclose(f); }; std::unique_ptr file(fopen("data.txt", "r"), closer); // Function-pointer deleter form: std::unique_ptr file2(fopen("data.txt","r"), fclose); ``` ### Arrays There is a dedicated array specialization that calls `delete[]` and supports `operator[]`: ```cpp // Listing 12.11: unique_ptr to an array std::unique_ptr arr(new int[10]); arr[2] = 10; // index access on the array specialization ``` ### `make_unique` is C++14 — and how to write it in C++11 `std::make_unique` was added in **C++14**, not C++11. It is trivial to provide in C++11: ```cpp // Listing 12.12: a C++11 make_unique (non-array and array forms) #include #include template typename std::enable_if::value, std::unique_ptr >::type make_unique(Args&&... args) { return std::unique_ptr(new T(std::forward(args)...)); } template typename std::enable_if::value, std::unique_ptr >::type make_unique(std::size_t n) { return std::unique_ptr(new typename std::remove_extent::type[n]()); } ``` > `std::unique_ptr` replaced the deeply flawed C++98 `std::auto_ptr`, whose "copy" silently transferred ownership (and which is removed in C++17). --- ## 12.10 `std::shared_ptr`: Shared Ownership `std::shared_ptr` implements **shared ownership** via **reference counting**. The managed object is destroyed only when the *last* owning `shared_ptr` is destroyed or reassigned. ### The control block A `shared_ptr` carries two pointers (to the object and to a heap **control block**). The control block stores: 1. the **strong** reference count (owners), 2. the **weak** reference count (observers), 3. the deleter / allocator state, 4. and, with `make_shared`, the object itself (co-located in one allocation). ```cpp // Listing 12.13: reference counting in action #include auto p1 = std::make_shared(100); // strong count = 1; one allocation { auto p2 = p1; // copy -> strong count = 2 std::cout << p1.use_count(); // 2 } // p2 destroyed -> strong count = 1 // p1 destroyed -> count = 0 -> object freed ``` **Prefer `make_shared`:** it allocates the object and control block in a single block (faster, one cache-friendlier allocation) and is exception-safe. (Its one downside: the object's memory cannot be freed until all *weak* references are also gone, since they share the block.) ### Ownership pitfalls A `shared_ptr` only coordinates with other `shared_ptr`s **copied from it**. Constructing two independent `shared_ptr`s from the *same raw pointer* creates two separate control blocks and a double free: ```cpp // Listing 12.14: the double-free trap Foo* raw = new Foo; std::shared_ptr a(raw); std::shared_ptr b(raw); // WRONG: independent control block // when a and b both expire, raw is deleted twice -> UB ``` The **aliasing constructor** lets a `shared_ptr` share ownership of one object while pointing at a sub-object, keeping the whole object alive: ```cpp // Listing 12.15: aliasing constructor struct Foo { int x; }; auto p1 = std::make_shared(); std::shared_ptr p2(p1, &p1->x); // p2 points at x, co-owns the Foo ``` ### A toy implementation The mechanism is small enough to sketch — note the **atomic** count, which is what makes copies thread-safe (and costly): ```cpp // Listing 12.16: minimal shared_ptr to show the control block template class SharedPtr { T* ptr; struct ControlBlock { std::atomic ref_count{1}; }* cb; public: explicit SharedPtr(T* p) : ptr(p), cb(new ControlBlock()) {} SharedPtr(const SharedPtr& o) : ptr(o.ptr), cb(o.cb) { if (cb) ++cb->ref_count; } ~SharedPtr() { if (cb && --cb->ref_count == 0) { delete ptr; delete cb; } } }; ``` **The cost of sharing:** a `shared_ptr` is twice the size of a raw pointer, and every copy/destruction performs an *atomic* increment/decrement. Use it only when ownership is genuinely shared or indeterminate — never merely because it "feels safer." --- ## 12.11 `std::weak_ptr`: Non-Owning Observation A `std::weak_ptr` references an object owned by `shared_ptr`s **without** affecting the strong count — so it never keeps the object alive. To use it you must `lock()` it, which atomically produces a `shared_ptr` if the object is still alive, or an empty one if it has expired. ```cpp // Listing 12.17: observing without owning auto sp = std::make_shared(42); std::weak_ptr wp = sp; // observe; strong count still 1 if (auto locked = wp.lock()) { // try to acquire temporary ownership use(*locked); } sp.reset(); // last owner gone -> object destroyed if (auto locked = wp.lock()) { /* ... */ } else { /* object expired */ } ``` ### Breaking reference cycles Two objects that hold `shared_ptr`s to each other form a cycle whose counts never reach zero — a leak. Make the back-reference a `weak_ptr`: ```cpp // Listing 12.18: weak_ptr breaks an ownership cycle struct B; struct A { std::shared_ptr b; }; struct B { std::weak_ptr a; }; // back-edge is weak -> no cycle ``` The rule: if `Parent` owns `Child` via `shared_ptr`, `Child` should refer back to `Parent` via `weak_ptr`. --- ## 12.12 `enable_shared_from_this` and Smart-Pointer Casts To obtain a `shared_ptr` to `this` from inside a member function — without creating a *second* control block — derive from `std::enable_shared_from_this` and call `shared_from_this()`: ```cpp // Listing 12.19: shared_from_this #include class Widget : public std::enable_shared_from_this { public: void register_self() { std::shared_ptr self = shared_from_this(); // shares the existing block EventManager::add(self); } }; int main() { auto w = std::make_shared(); w->register_self(); } ``` Calling `shared_from_this()` on an object **not** already owned by a `shared_ptr` (a stack/global object, or from within the constructor) is undefined behavior (C++17 makes it throw `std::bad_weak_ptr`). To convert between related `shared_ptr` types while preserving the shared control block, use the dedicated casts: **`std::static_pointer_cast`**, **`std::dynamic_pointer_cast`**, **`std::const_pointer_cast`**. --- ## 12.13 Professional Insights **Design rules.** - **Default to `unique_ptr`** — simpler, faster, clearer; zero overhead. - **Upgrade to `shared_ptr` only when ownership is genuinely shared** or its end is indeterminate. - **Use `weak_ptr` for non-owning access** and to break cycles. - **Avoid `new`/`delete`** — prefer `make_unique` (C++14) and `make_shared` (C++11) for exception safety and a single allocation. - **Think in ownership:** "Who owns this? Who merely uses it? Can two objects accidentally keep each other alive?" **The `value_ptr` / pImpl pattern.** A `value_ptr` (not standard, but common in expert code) is a smart pointer with *value* semantics: copying it deep-copies the pointee. It is the natural backbone of the **pImpl** ("pointer to implementation") idiom, giving a class value semantics while hiding its implementation behind a forward-declared pointer in the header — cutting compile-time coupling, a real win in large codebases. **`noexcept` moves and the standard library.** This is not stylistic: `std::vector`'s growth uses `std::move_if_noexcept`. A throwing move constructor forces the slow copy path during reallocation, silently erasing the very optimization you wrote the move constructor for. In latency-sensitive systems, audit that your movable types' move operations are `noexcept`. **Atomic ref-counts are not free.** Every `shared_ptr` copy is an atomic RMW on the strong count, which serializes cache lines across cores. In hot paths, pass `const shared_ptr&` (or a raw/`weak_ptr` observer) instead of copying, and reserve `shared_ptr` *by value* for the points where ownership genuinely changes hands. --- # Chapter 76: The C++ Memory Model in Depth > Free sample chapter from *C++: Zero to Godhood* (Book I of the Zero to Godhood series) by Shreejit Verma. > Canonical URL: https://zerotogodhood.com/books/cpp/the-cpp-memory-model/ > Copyright 2026 Shreejit Verma. All rights reserved. Content signals: search=yes, ai-input=yes, ai-train=no. The C++ memory model is the contract that makes multithreaded code *meaningful*: it defines, for a program with concurrent access to shared memory, which writes a read is permitted to observe. Without it, the compiler, the CPU, and the cache coherence protocol are each free to reorder memory operations for performance, and "the value of `x`" stops being a well-defined question. This chapter develops the model from the ground up — the abstract machine, the happens-before relation, the six memory orderings and what each actually costs on real hardware — because every lock-free structure, every atomic flag, and every correctness argument in the chapters that follow rests on it. ## Chapter Roadmap - 76.1 Why a Memory Model Exists: Reordering and the Abstract Machine - 76.2 Data Races and Undefined Behaviour - 76.3 The Relations: Sequenced-Before, Synchronizes-With, Happens-Before - 76.4 `std::atomic` and Atomicity - 76.5 The Six Memory Orderings - 76.6 The Release/Acquire Pattern in Depth - 76.7 Relaxed Ordering and Its Legitimate Uses - 76.8 Sequential Consistency and Its Cost - 76.9 Fences - 76.10 The Hardware Cost Model: x86 vs ARM/POWER - 76.11 Common Bugs and Anti-Patterns --- ## 76.1 Why a Memory Model Exists: Reordering and the Abstract Machine C++ is defined in terms of an **abstract machine**. The compiler must preserve the *observable behaviour* of a single thread (the "as-if" rule), but it is otherwise free to reorder, combine, and eliminate memory operations. The CPU does the same at runtime: an out-of-order core executes loads and stores whenever their operands are ready, store buffers delay writes from becoming globally visible, and the cache coherence protocol propagates changes between cores with latency. Three independent layers reorder memory: 1. **The compiler** — hoists loads out of loops, sinks stores, keeps values in registers, reorders independent operations. 2. **The CPU** — speculative and out-of-order execution issue memory ops out of program order. 3. **The memory subsystem** — store buffers, invalidation queues, and coherence traffic mean a store on one core becomes visible to another only after a delay, and not necessarily in program order. > **Why this matters.** In a single thread none of this is observable — the hardware and compiler guarantee a thread sees its own operations in order. Across threads, all three layers are visible, and the *naive* assumption that thread B sees thread A's writes in the order A issued them is simply false. The memory model is the precise specification of what *is* guaranteed, so you can reason about concurrent code without modelling every microarchitecture. --- ## 76.2 Data Races and Undefined Behaviour A **data race** occurs when two threads access the same memory location concurrently, at least one access is a write, and the accesses are not ordered by any synchronisation. **A data race is undefined behaviour** — full stop. Not "you read a stale value"; the entire program's behaviour is undefined, and the optimiser is entitled to assume races never happen. ```cpp // BUGGY — data race, undefined behaviour. Min standard: C++11. int data = 0; bool ready = false; // plain bool, not atomic void producer() { data = 42; ready = true; } // two plain writes void consumer() { while (!ready) {} assert(data == 42); } // racy reads ``` *Listing 76.1 — A textbook data race. The compiler may hoist `ready` into a register, making the loop spin forever; or reorder the two writes so `ready` is seen true before `data == 42`.* > **Why this matters / cost model.** The fix is not a `volatile` (which constrains the compiler but provides *no* inter-thread ordering or atomicity — a common and dangerous misconception) but `std::atomic` with an appropriate ordering. The reason UB is so severe here is that the optimiser, proving no race can exist, may delete the spin loop entirely, fold the two paths, or assume `ready` never changes. Correctness in concurrent C++ begins with: *every cross-thread shared access is either protected by a mutex or is an atomic operation.* --- ## 76.3 The Relations: Sequenced-Before, Synchronizes-With, Happens-Before The model is built from three relations: - **Sequenced-before** — the intra-thread program order between evaluations (within the limits of unspecified evaluation order). This is what gives single-threaded code its meaning. - **Synchronizes-with** — the cross-thread relation established by a *release* operation paired with an *acquire* operation that reads the released value. This is the only way to manufacture an ordering edge *between* threads. - **Happens-before** — the transitive closure of sequenced-before and synchronizes-with. If write W happens-before read R, then R is guaranteed to observe W (or a later write); if neither happens-before the other and they conflict, you have a data race. > **Why this matters.** "Happens-before" is the single concept that makes concurrent reasoning tractable. You never reason about caches or store buffers directly; you ask: *is there a happens-before edge from this write to that read?* If yes, the value is visible. If no, it is a race (UB) or — for non-conflicting atomics — merely unordered. Every synchronisation primitive (mutex lock/unlock, atomic release/acquire, thread create/join) exists to create exactly these edges. --- ## 76.4 `std::atomic` and Atomicity `std::atomic` guarantees that read-modify-write and load/store operations on the object are **indivisible**: no thread observes a half-written value, and the operation is free of data races by definition. ```cpp // Min standard: C++11. Portable. #include std::atomic count{0}; count.fetch_add(1, std::memory_order_relaxed); // indivisible increment int c = count.load(std::memory_order_relaxed); ``` *Listing 76.2 — Atomic read-modify-write.* Atomicity and ordering are **orthogonal**. `fetch_add` is always atomic regardless of the memory order argument; the order argument controls only what *other* memory operations are ordered relative to it. `atomic::is_lock_free()` reports whether operations use hardware atomics or a hidden lock — for types wider than the platform's atomic width (e.g. a 16-byte struct without `cmpxchg16b`), the implementation may fall back to a mutex, which destroys the lock-free property you may have been relying on. --- ## 76.5 The Six Memory Orderings Every atomic operation takes a `std::memory_order` controlling the ordering edges it creates: | Order | Applies to | Guarantee | |---|---|---| | `relaxed` | load/store/RMW | Atomicity only. No ordering with other memory ops. | | `acquire` | load, RMW | No load/store *after* it (in program order) may be reordered before it. Pairs with a release to synchronize. | | `release` | store, RMW | No load/store *before* it may be reordered after it. Publishes prior writes. | | `acq_rel` | RMW | Both acquire (on the read) and release (on the write) for read-modify-write ops. | | `seq_cst` | all | Acquire/release **plus** a single global total order over all `seq_cst` operations. The default. | | `consume` | load | Weaker acquire ordering only data-dependent operations; **discouraged/effectively deprecated** — compilers promote it to acquire. | > **Why this matters.** These are not interchangeable knobs to twist for speed; each names a precise guarantee. Choosing one weaker than your algorithm requires is a correctness bug that may *never* reproduce on x86 (which is strongly ordered) and then fail in production on ARM. Choosing one stronger than required is a performance bug — `seq_cst` everywhere forces full barriers that serialise the store buffer. The discipline is: derive the *minimum* ordering each operation needs from a happens-before argument, then use exactly that. --- ## 76.6 The Release/Acquire Pattern in Depth The canonical publication pattern: a producer writes data, then *releases* a flag; a consumer *acquires* the flag, then reads the data. The release/acquire pair creates a synchronizes-with edge, so everything sequenced-before the release in the producer happens-before everything sequenced-after the acquire in the consumer. ```cpp // Min standard: C++11. Portable. Correct publication. #include #include std::atomic ready{false}; int data = 0; // plain int — safe because release/acquire orders it void producer() { data = 42; // (1) ordinary write ready.store(true, std::memory_order_release); // (2) publish: (1) cannot move after (2) } void consumer() { while (!ready.load(std::memory_order_acquire)) {} // (3) acquire: (4) cannot move before (3) assert(data == 42); // (4) guaranteed to read 42 } ``` *Listing 76.3 — Release/acquire publication. `data` need not be atomic because the happens-before edge orders it.* > **Why this matters / cost model.** This is the workhorse of lock-free code — SPSC queues, lazy initialisation, sequence-locks all use it. The key insight is that `data` itself is a plain non-atomic `int`: the release/acquire pair on `ready` transitively orders the access to `data`, so there is no race. This is strictly cheaper than `seq_cst`: on x86 both the release store and acquire load are plain `mov` instructions (the hardware already gives the needed ordering), and on ARM they map to `stlr`/`ldar` — far cheaper than the full `dmb ish` barrier a `seq_cst` operation requires. The synchronisation is also *pairwise*: a release synchronizes only with the specific acquire that reads its value, not globally. --- ## 76.7 Relaxed Ordering and Its Legitimate Uses `relaxed` provides atomicity with no ordering. It is correct precisely when you need an atomic counter or flag but no happens-before edge to other data. ```cpp // Min standard: C++11. Portable. #include std::atomic hits{0}; void on_request() { hits.fetch_add(1, std::memory_order_relaxed); } // pure statistic ``` *Listing 76.4 — A relaxed counter: no data is published through it, so no ordering is needed.* Legitimate uses: monotonic statistics counters, reference counts on *increment* (the decrement that may trigger destruction needs `acq_rel`/release+acquire), and generating unique IDs. The hazard is using `relaxed` on the flag of Listing 76.3 — it would make `data` a race, because relaxed creates no synchronizes-with edge. > **Why this matters.** Relaxed is the cheapest atomic (a bare `lock xadd` on x86, a plain `ldxr/stxr` loop on ARM with no barrier) and the easiest to misuse. The litmus test: *does any other memory access depend on the ordering of this atomic?* If no, relaxed is correct and optimal. If yes, you need at least release/acquire. --- ## 76.8 Sequential Consistency and Its Cost `seq_cst` is the default and the easiest to reason about: all `seq_cst` operations across all threads appear to execute in one global total order consistent with each thread's program order. It is what most programmers intuitively assume memory "should" do. ```cpp // Min standard: C++11. Portable. Dekker-style: seq_cst is required here. std::atomic x{false}, y{false}; std::atomic z{0}; void t1() { x.store(true); if (!y.load()) ++z; } // default seq_cst void t2() { y.store(true); if (!x.load()) ++z; } // With seq_cst, z == 2 is impossible. With acquire/release, z == 2 CAN occur. ``` *Listing 76.5 — A case where only `seq_cst` gives the intuitive result (store-load ordering across two locations).* > **Why this matters / cost model.** The single global order is exactly the guarantee release/acquire does *not* provide: release/acquire orders a store before a later load only within a synchronizes-with chain, not across independent locations. The cost is a full memory barrier on the store side: on x86 a `seq_cst` store compiles to `xchg` (or `mov` + `mfence`), draining the store buffer; on ARM it is `dmb ish`. That barrier serialises the pipeline against the store buffer and can dominate a hot path. Use `seq_cst` when you genuinely need the total order (some mutual-exclusion and consensus algorithms do); otherwise prefer release/acquire. --- ## 76.9 Fences `std::atomic_thread_fence(order)` imposes ordering without being tied to a particular atomic object, letting you combine cheap `relaxed` atomics with a single barrier rather than paying for ordering on every operation. ```cpp // Min standard: C++11. Portable. #include std::atomic ready{false}; int data = 0; void producer() { data = 42; std::atomic_thread_fence(std::memory_order_release); // fence, not a release store ready.store(true, std::memory_order_relaxed); // relaxed store after the fence } void consumer() { while (!ready.load(std::memory_order_relaxed)) {} std::atomic_thread_fence(std::memory_order_acquire); // acquire fence assert(data == 42); } ``` *Listing 76.6 — A standalone fence pairs with another fence (or operation) to create the synchronizes-with edge.* > **Why this matters.** Fences are valuable when many relaxed operations share one ordering point — e.g. filling several fields then publishing once. A release *fence* followed by a relaxed store synchronizes with an acquire *fence* preceded by a relaxed load that reads the value. The subtlety: a fence's ordering is *positional* (it orders operations before/after it in program order), unlike an operation's ordering which is tied to that operation. Misplacing a fence relative to the atomic it is meant to order is a classic bug. --- ## 76.10 The Hardware Cost Model: x86 vs ARM/POWER The same C++ code has wildly different costs depending on the target's memory model: | Operation | x86-64 (TSO, strongly ordered) | AArch64 (weakly ordered) | |---|---|---| | `relaxed` load/store | plain `mov` | plain `ldr`/`str` | | `acquire` load | plain `mov` (free) | `ldar` | | `release` store | plain `mov` (free) | `stlr` | | `seq_cst` store | `xchg` / `mov+mfence` (drains store buffer) | `dmb ish` or `stlr`+barrier | | RMW (`fetch_add`) | `lock xadd` | `ldaxr/stlxr` retry loop | > **Why this matters.** x86's Total Store Order means acquire/release are *free* — the hardware already forbids the reorderings that matter — so code that is actually under-synchronised often passes all tests on x86 and only fails when ported to ARM (Apple Silicon, Graviton, mobile). This is the single most common way concurrency bugs escape to production. Conversely, `seq_cst`'s cost is mostly hidden on x86 (only stores pay) but pervasive on ARM. The lesson: *reason from the C++ memory model, not from x86 behaviour*, and test on a weakly-ordered target. --- ## 76.11 Common Bugs and Anti-Patterns - **Using `volatile` for synchronisation.** `volatile` prevents the compiler from eliding accesses (correct for MMIO) but provides no atomicity and no inter-thread ordering. It is never a substitute for `std::atomic`. - **Under-ordering that passes on x86.** Using `relaxed` where release/acquire is needed; works on TSO, races on ARM. - **Assuming release/acquire gives a global order.** It does not (Listing 76.5); store-load ordering across independent locations needs `seq_cst`. - **`seq_cst` everywhere "to be safe."** Correct but slow; serialises the store buffer on every operation. - **Non-lock-free atomics.** A wide `atomic` may use a hidden lock; check `is_lock_free()` before relying on lock-free progress. - **Mixed orderings on one variable without a happens-before argument.** If you cannot state the happens-before edge in words, the code is not yet correct. > **The discipline.** For every atomic operation, write down the happens-before edge it participates in and the *minimum* ordering that establishes it. This single habit prevents the majority of memory-model bugs and is the foundation for the atomics, lock-free, reclamation, and lock-design chapters that follow. --- # Preface > Free sample chapter from *Python: Zero to Godhood* (Book II of the Zero to Godhood series) by Shreejit Verma. > Canonical URL: https://zerotogodhood.com/books/python/preface/ > Copyright 2026 Shreejit Verma. All rights reserved. Content signals: search=yes, ai-input=yes, ai-train=no. ## What this book is This is the evolutionary history of Python, told at the level of the implementation. It begins with Guido van Rossum's Christmas 1989 prototype and ends at the free-threaded frontier of the current release. Every feature is traced to the release that introduced it, the PEP that argued for it, the problem it solved, and what it cost. It is not a tutorial and not a reference in the usual sense. It is a mastery guide. It does not explain what a `for` loop is; it explains what the interpreter does when it runs one, why the language acquired the construct when it did, and how that decision still shapes the code you write today. The book assumes fluency in at least one systems language, comfort with operating-system and memory concepts, and working Python. It is written for the senior engineer who already uses Python well and wants to understand it completely. ## How the book is organized: two tracks The book runs on two interleaved tracks, and understanding the distinction is the key to reading it. The **timeline volumes** (Volume 1 through Volume 19) follow Python's releases in order, from the pre-history of ABC through Python 3.14 and beyond. Each timeline chapter opens with the constraint the release was operating under and shows the modern consequence of a historical decision, verified on today's interpreters. The timeline volumes *use* the language's mechanisms and cross-reference the deep volume that owns each one; they narrate *when* and *why*. The **deep volumes** (Deep Volume A through Deep Volume W) are topical masteries: the object model, memory management, the type system, iteration and coroutines, the interpreter, concurrency, performance engineering, the C-API, packaging, the standard library, and the applied domains. A deep volume *owns* a mechanism and explains it in full: the internals, the cost model, the failure modes. Deep volumes explain *how* and *how well*. The two tracks are woven together within each Part. A timeline chapter on the set type points at the deep volume that owns the hash table; a deep volume on performance engineering supplies the cost model that a dozen timeline chapters invoke. Read straight through and the two tracks reinforce each other; read a single volume and it stands on its own. ## Verification: the listings are real Every runnable listing in this book was executed, and its output recorded byte-for-byte, across three interpreters: CPython 3.13.5, CPython 3.14.6, and the free-threaded CPython 3.14 build. Output blocks marked *Verified output* reproduce those recordings exactly. Where a feature exists only on a newer interpreter, the listing is marked accordingly and its output was recorded on the interpreters that support it. This is a deliberate discipline, not a formality. A book about the implementation earns its authority only if its claims can be checked, and a claim about behavior is worth nothing if it was never run. Nothing in these pages is a benchmark asserted from memory or an output typed from expectation. The numbers are measurements; the outputs are recordings. ## A note on chapter numbering The chapters carry the numbers under which they were written and cross-referenced. Because the book was composed as a large, interlocking system rather than a linear draft, a chapter's number is a stable label used by the roughly forty-five hundred cross-references throughout the text, not a strict position in the reading order. Follow the Part and Volume structure of the table of contents for sequence; follow the chapter labels for cross-references. Every chapter is unique, and the table of contents lists all of them in reading order under their volumes. ## How to read it If you are reading cover to cover, the Parts are chronological and the difficulty accumulates gently, because Python's own changes accumulated gently: an annual cadence of small, composable releases rather than rare, disruptive leaps. If you are reading to master one subject, go straight to its deep volume. Each is self-contained, and the timeline chapters that use its mechanism are cross-referenced from it. If you are reading to understand a specific release, its timeline volume gathers everything that shipped in that window, with each feature pointed at the deep volume that explains it fully. However you read it, one thing holds throughout, and the final chapter returns to it: the releases come and go, but the data model stays. Everything is an object, and behavior comes from protocols any type can implement. That small, stable core is what let two decades of features accumulate without the language fracturing, and it is the highest-leverage thing a Python programmer can learn. The frontier moves; the core holds. --- # Chapter 2: Inception and the Executable Pipeline (Python 1.0-1.6) > Free sample chapter from *Python: Zero to Godhood* (Book II of the Zero to Godhood series) by Shreejit Verma. > Canonical URL: https://zerotogodhood.com/books/python/inception-and-the-executable-pipeline/ > Copyright 2026 Shreejit Verma. All rights reserved. Content signals: search=yes, ai-input=yes, ai-train=no. A senior engineer arriving from C++ writes this, expecting a deep copy, and ships a bug: ```python config = {"retries": 3} defaults = config # "save the defaults before I mutate" config["retries"] = 10 # defaults["retries"] is now 10, not 3 ``` The bug is not a typo. It is a wrong mental model of what a name is, and it survives code review because the code looks obviously correct to anyone thinking in terms of variables-as-storage. Python does not have variables in that sense. It has names bound to objects, and until that distinction is in muscle memory it will keep producing bugs that the type checker cannot catch and the reviewer cannot see. This chapter builds the correct model from the bottom. It follows one line of source from text to result through the five stages of CPython's pipeline, and it establishes the vocabulary that every later chapter assumes: names, bindings, scopes, cells, code objects, frames, opcodes. It anchors in Python's 1.x origins because the decisions made then, names as bindings, everything-is-an-object, a static scope-analysis pass before execution, still govern how CPython 3.14 behaves today. Chapter 1 covered why Guido built the language; this chapter is the machine he built. ## Section index - **2.1** Names are bindings, not storage - **2.2** The execution pipeline, end to end - **2.3** Parser evolution: LL(1) to PEG - **2.4** The symbol table and static scope classification - **2.5** Closures and cell objects - **2.6** `PyCodeObject`: the compiled blueprint - **2.7** The virtual machine: frames and the evaluation loop - **2.8** Measurement: locals, globals, and a piece of overturned folklore - **2.9** Edges and failure modes - **2.10** Connections - **2.11** Exercises - **2.12** Summary and cross-references Listings live under `code/ch001/` and are re-executed by `make verify` on both verification interpreters. --- ## 2.1 Names are bindings, not storage **The model.** A Python name lives in a namespace, a mapping from `str` to object. Assignment binds the name to an object; it never copies the object and never mutates whatever the name referred to before. Every object carries at least a reference count and a type pointer (Chapter 19 dissects the header). So assignment is a constant two-step: bind the name, and increment the target's refcount. The bug in the introduction is this model applied correctly to code written as if the other model were true: ```python # code/ch001/l01_names_are_bindings.py a = [1, 2, 3] b = a # b is NOT a copy; a and b name the same list b.append(4) ``` Verified output (CPython 3.13.5): ```text after b.append(4): a = [1, 2, 3, 4] b = [1, 2, 3, 4] a is b = True a == b = True ``` `b.append(4)` is visible through `a` because there was only ever one list. Then the crucial contrast, rebinding versus mutating: ```text contrast: rebinding a name does not touch the object or the other name a = [1, 2, 3, 4] c = [1, 2, 3, 4, 5] a is c = False ``` `c = c + [5]` builds a new list and binds `c` to it. `a` is untouched, because rebinding a name changes the name, not the object. Mutating through a name (`append`) changes the shared object; rebinding a name (`=`) changes only that one edge. Every copy-versus-alias surprise in Python is that one distinction. **The senior-engineer contrast.** This is exactly where systems intuition misleads: | Concept | C / C++ | Java | Python (CPython) | |---|---|---|---| | What a variable *is* | typed storage at an address | a typed slot holding a primitive or a reference | a name bound to an object; the name has no type | | `a = b` | copies bytes per the declared type | copies a primitive, or copies a reference | binds `a` to the same object `b` names; no copy | | Type belongs to | the variable, fixed at compile time | the variable | the **object**, not the name | | Lifetime | scope / `new`/`delete` / RAII | tracing GC | refcount to immediate free, plus a cyclic collector (Chapter 3) | `is` compares identity, `==` compares value. In C, `a == b` on pointers already is identity, so the language needs no separate operator. Python needs two because a name and an object are two different things. Fix the model here and most of the language's surprises stop being surprising: **a Python program is a graph of objects, and names are labelled edges into it.** --- ## 2.2 The execution pipeline, end to end **Why this exists.** Python feels interpreted, you type a line and it runs, but nothing executes until it has been compiled to bytecode. Knowing the pipeline tells you where each error is produced (a `SyntaxError` cannot happen at runtime; a `NameError` cannot happen at compile time) and why certain constructs are fast or slow. Text to result is five stages: ```text [ source text ] | tokenizer (Parser/tokenizer.c): token stream, including INDENT/DEDENT v [ token stream ] | parser (Parser/, PEG since 3.9): builds the Abstract Syntax Tree v [ AST ] ( the ast module exposes this tree ) | symbol-table pass (Python/symtable.c): classifies every name into a scope v [ symbol table ] | compiler (Python/compile.c): emits bytecode + metadata v [ PyCodeObject ] ( immutable: bytecode, constants, names, flags ) | evaluation loop (Python/ceval.c): runs per frame v [ result ] ``` The first four stages are ahead-of-time compilation; only the last is interpretation. Each boundary is observable from the standard library: `tokenize` for stage 1 (Chapter 1 showed its INDENT/DEDENT output), `ast` for stages 2-3, `symtable` for stage 4, `dis` for stage 5's input, and the running program for the loop. The rest of this chapter takes each in turn. --- ## 2.3 Parser evolution: LL(1) to PEG (PEP 617) **Why this exists.** For most of its life CPython used a hand-tunable **LL(1)** parser: **L**eft-to- right scan, **L**eftmost derivation, **1** token of lookahead. It is fast and simple but structurally limited, and its limits shaped the grammar, and therefore the language, for two decades. **PEP 617 (the PEG parser)** replaced it in Python 3.9 (Chapter 14). **The LL(1) limitation: left recursion.** A top-down LL(1) parser cannot directly handle a left- recursive rule, one whose right-hand side begins with the non-terminal itself: $$A \rightarrow A\,\alpha \;\mid\; \beta$$ Asked to expand $A$, it would expand $A$ again before consuming input, recursing forever. The classic fix rewrites the rule into an equivalent right-recursive pair: $$A \rightarrow \beta A' \qquad A' \rightarrow \alpha A' \;\mid\; \varepsilon$$ This is equivalent as a *language* but distorts the grammar: the natural left-associative shape of `a - b - c` has to be reconstructed afterward, and the grammar gets harder to read and evolve. **The PEG parser.** A Parsing Expression Grammar parser is also top-down, but adds ordered choice (alternatives tried in order, first match wins), unlimited lookahead via backtracking, packrat memoization (each rule-at-position result cached, so backtracking stays linear and left recursion works directly by seeding the memo table to a fixed point), and direct AST construction that skips the old Concrete Syntax Tree. ```text LL(1) pipeline (pre-3.9): [source] -> [tokenizer] -> [Concrete Syntax Tree] -> [AST builder] -> [AST] PEG pipeline (3.9+, PEP 617): [source] -> [tokenizer] -> [PEG parser (memoized)] -> [AST] ``` **Old-versus-new, why it mattered.** The switch was not cosmetic. The structural pattern matching of `match`/`case` (PEP 634, Chapter 16) is expressible largely *because* the grammar is no longer bound by LL(1). The cost is that a PEG grammar can encode order-dependent rules, which puts more responsibility on the grammar's authors; for the language's user, the result is strictly more expressive syntax and better error messages. > **Implementation detail, not language semantics.** The parser is a CPython concern. The *language* > is defined by the grammar in the reference; whether it is parsed LL(1) or PEG is invisible to a > correct program, with the narrow exception of newly expressible syntax. The formal grammar and > lexical rules are **Deep S**. --- ## 2.4 The symbol table and static scope classification **Why this exists.** Before emitting a single opcode, the compiler walks the AST to decide, statically, what every name means: local to this function, a parameter, a global, a builtin, or a free variable captured from an enclosing function. That classification is what lets CPython use array-indexed local access (`LOAD_FAST`) instead of a dictionary lookup for every variable, the single largest reason Python functions are not slower than they are. CPython classifies each binding into local, explicit global (`global x`), implicit global (referenced but never bound, resolved at runtime against module globals then builtins), or enclosing/free (bound in an outer function and read, or with `nonlocal` rebound, by a nested one). The `symtable` module exposes exactly this pass: ```python # code/ch001/l02_symbol_table.py import symtable table = symtable.symtable(SRC, filename="", compile_type="exec") outer = table.lookup("outer_func").get_namespace() ``` Verified output (CPython 3.13.5): ```text outer identifiers: ['inner_func', 'x', 'z'] 'z' is_local in outer: True 'x' is_parameter in outer: True inner free vars (closure): ('x', 'z') 'z' is_free in inner: True ``` `z` is local to `outer_func`, `x` is its parameter, and inside `inner_func` both are free variables captured from the enclosing scope. (`get_frees()` returns an unordered set; the listing sorts it so the output is stable, which is a habit worth keeping for any set-valued result you intend to print.) > **A correctness note that cost a real debugging session.** Earlier drafts of this material called > `Symbol.is_cell()`. That method does not exist in the `symtable` API; it raises `AttributeError` on > 3.13.5. The supported predicates are `is_local`, `is_global`, `is_free`, `is_parameter`, > `is_namespace`, `is_nonlocal`, `is_declared_global`, `is_assigned`, `is_referenced`, `is_imported`, > `is_annotated`. To see which enclosing locals were promoted to cells, read the compiled code > object's `co_cellvars` (§2.5), which is the authoritative view. --- ## 2.5 Closures and cell objects **Why this exists.** A nested function can outlive the call that created it, yet still read the enclosing function's locals. Those locals cannot live in the outer frame's fast-locals array, because that array dies when the frame is popped. CPython promotes a captured local to a **cell**: a one-slot heap object shared by reference between the enclosing and nested functions. ```c /* Illustrative; Objects/cellobject.c. A cell is a one-slot indirection on the heap. */ typedef struct { PyObject_HEAD PyObject *ob_ref; /* the captured object, shared by closure and enclosing scope */ } PyCellObject; ``` The compiler records on each code object which locals are cells (`co_cellvars`) and which names are read from an enclosing scope (`co_freevars`): ```python # code/ch001/l03_cells.py top = compile(SRC, "", "exec") ``` Verified output (CPython 3.13.5): ```text outer_func co_cellvars: ('x', 'z') inner_func co_freevars: ('x', 'z') the cell is shared, so a closure sees LIVE updates, not a snapshot: bump() -> 1 2 3 ``` Both `x` and `z` are cells in `outer_func` and free variables of `inner_func`. The shared cell is why `bump()` returns 1, 2, 3 rather than 1, 1, 1: the closure sees live updates to the captured variable, not a snapshot taken at closure-creation time. That same sharing is the mechanism behind the notorious late-binding-closure-in-a-loop bug, which Chapter 3 dissects alongside comprehension scope. --- ## 2.6 `PyCodeObject`: the compiled blueprint **Why this exists.** Compilation produces a `PyCodeObject`: an immutable, shareable description of a unit of executable code (a module body, a function, a `lambda`, a comprehension, a class body). It is immutable so it can be cached, shared across calls and threads, and reasoned about statically. A *function* is a thin mutable wrapper (`__defaults__`, `__closure__`, `__globals__`) around an immutable code object. ```c /* Illustrative; fields from Include/cpython/code.h. The real struct changed across versions (notably the 3.11 frame/codeobject rework); these fields are stable and observable from Python as co_* attributes. */ struct PyCodeObject { PyObject_HEAD int co_argcount; /* positional parameters */ int co_posonlyargcount; /* positional-only parameters (PEP 570, 3.8+) */ int co_kwonlyargcount; /* keyword-only parameters */ int co_nlocals; /* number of local variables */ int co_stacksize; /* max evaluation-stack depth to reserve */ int co_flags; /* CO_OPTIMIZED, CO_NEWLOCALS, CO_GENERATOR ... */ PyObject *co_consts; /* tuple of literal constants */ PyObject *co_names; /* tuple of global/attribute names */ PyObject *co_varnames; /* tuple of local variable names */ PyObject *co_freevars; /* tuple of free (captured) names */ PyObject *co_cellvars; /* tuple of local names boxed into cells */ /* bytecode, line table, exception table, etc. */ }; ``` Every `co_*` field is readable from Python: ```python # code/ch001/l04_code_object.py def example_fn(a, b): local_val = 42 return a + b + local_val co = example_fn.__code__ ``` Verified output (CPython 3.13.5): ```text co_varnames : ('a', 'b', 'local_val') co_consts : (None, 42) co_argcount : 2 co_nlocals : 3 co_stacksize: 2 co_flags : 0b11 ``` Three details to internalize: - `co_consts` contains `None` although the source never mentions it: it is the implicit return value's constant. `42` is interned into the pool and referenced by index. - `co_flags == 0b11` sets `CO_OPTIMIZED | CO_NEWLOCALS`, the flags meaning "a real function: use fast array-indexed locals and a fresh locals namespace per call." A module or class body sets neither, which is precisely why module-level code uses dictionary-based `LOAD_NAME` and is slower (§2.8). - The listing also demonstrates the immutability boundary: setting `example_fn.__defaults__` changes the *function wrapper* and leaves the code object untouched. The blueprint is frozen; the wrapper around it is where all runtime configurability lives. There is a fourth detail you will meet in disassembly of large functions: **`EXTENDED_ARG`**. An opcode's inline argument is one byte, so to reference the 300th constant the compiler prefixes an `EXTENDED_ARG` that supplies the high bits, which the VM shifts and combines, allowing arguments up to 32 bits wide. --- ## 2.7 The virtual machine: frames and the evaluation loop **Why this exists.** CPython is a stack-based virtual machine. Each call creates a frame holding the code object, the local variables, and an evaluation stack onto which operands are pushed and from which results are popped. A single C function, `_PyEval_EvalFrameDefault` in `Python/ceval.c`, dispatches opcodes in a loop until the frame returns. ```c /* Illustrative shape, Python/ceval.c. The modern loop uses computed-goto threaded dispatch and inline caches, but the skeleton is this. */ PyObject *_PyEval_EvalFrameDefault(PyThreadState *tstate, _PyInterpreterFrame *frame, int throwflag) { for (;;) { _Py_CODEUNIT word = *next_instr++; switch (word.op.code) { case LOAD_FAST: { /* push a local by array index */ PyObject *v = GETLOCAL(word.op.arg); Py_INCREF(v); PUSH(v); DISPATCH(); } case RETURN_VALUE: return POP(); } } } ``` Do not trust the textbook picture of the bytecode; read what *this* interpreter emits. Listing 2.5 prints the instruction stream as opname plus argument, which is stable regardless of where the function lands in a file: ```python # code/ch001/l05_bytecode.py for ins in dis.get_instructions(example_fn): ... ``` Verified output (CPython 3.13.5): ```text bytecode of example_fn (opname [arg]): RESUME LOAD_CONST 42 STORE_FAST local_val LOAD_FAST_LOAD_FAST a, b BINARY_OP + LOAD_FAST local_val BINARY_OP + RETURN_VALUE ``` This single listing demolishes several outdated mental models: - **`RESUME`** opens every code object since 3.11. It is a no-op hook for the specializing adaptive interpreter and for debuggers; its presence tells you that you are reading modern bytecode. - **`BINARY_OP +`**, not `BINARY_ADD`. Python 3.11 collapsed the per-operator binary opcodes into one `BINARY_OP` whose argument selects the operation. Material still showing `BINARY_ADD` predates 3.11. - **`LOAD_FAST_LOAD_FAST a, b`** is a superinstruction: the compiler fused two adjacent `LOAD_FAST`s into one opcode to cut dispatch overhead. The VM is no longer one opcode per source operation. - There is no trailing `LOAD_CONST None` / `RETURN_VALUE`, because the function ends in an explicit `return` and the compiler does not append the implicit `return None`. > **Version drift, and why this book runs the listing on both interpreters.** Every opcode above > except `RESUME`, `STORE_FAST`, `BINARY_OP`, and `RETURN_VALUE` is different on CPython 3.14. There, > `LOAD_CONST 42` becomes **`LOAD_SMALL_INT`** (small integers are no longer even constants; they are > produced directly), `LOAD_FAST_LOAD_FAST` becomes **`LOAD_FAST_BORROW_LOAD_FAST_BORROW`**, and the > plain `LOAD_FAST` becomes **`LOAD_FAST_BORROW`**. The `_BORROW` family is a 3.14 optimization that > pushes a *borrowed* reference (no refcount increment) where the compiler can prove the local > outlives the use, eliminating a great many incref/decref pairs. Both interpreters' output is > recorded under `code/ch001/expected/`; a book that showed only one and called it "the bytecode" > would be wrong within a year. This is the drift the whole verification harness exists to catch. Tracing the evaluation stack for `a + b` makes the stack discipline concrete: ```text LOAD_FAST_LOAD_FAST(a,b) BINARY_OP(+) ... RETURN_VALUE +---------+ +---------+ +---------+ | b | | a + b | | (empty) | +---------+ +---------+ --> +---------+ | a | --> | (empty) | | (empty) | +---------+ +---------+ +---------+ ``` > **3.11+ reality: the specializing adaptive interpreter.** Modern CPython does not execute a fixed > opcode stream forever. As code runs hot, generic opcodes are specialized in place into faster > variants, backed by inline caches stored in the code units. This is not the JIT (PEP 744); it is > interpretation that rewrites itself, and it is the direct reason the folklore in §2.8 no longer > holds the way it once did. Chapter 17 covers it in full. --- ## 2.8 Measurement: locals, globals, and a piece of overturned folklore Every intermediate Python guide teaches the same optimization: bind a global or a method to a local before a hot loop, because a local read is `LOAD_FAST` (an array index) while a global read is `LOAD_GLOBAL` (a dict probe of module globals, then builtins). The advice is correct in direction. The interesting question, which the guides never answer, is *how large the effect actually is on a current interpreter*. **Methodology.** `code/ch001/bench_locals_vs_globals.py`, run through `_harness/bench.py`. A 1000-element list comprehension calling `math.sqrt` per element, resolved either as a global-plus- attribute each iteration or hoisted to a local once. Fifteen batches, `min` as the headline statistic (microbenchmark noise is one-sided), median and RSD as diagnostics. CPython 3.13.5, `-O2`, computed gotos on. Apple M3 Pro, macOS 27.0, arm64. Ratios are within this one interpreter. | case | min (ns/loop) | ratio | |---|---|---| | global lookup per item | 22,820 | 1.00x | | hoisted local per item | 21,851 | 0.96x | **The hoist saves about 4%.** Not the dramatic win the folklore implies, and the reason is §2.7's specializing interpreter. Confirmed directly: ```python # after warming the function, the global load has specialized >>> [op for op in opnames(uses_global) if op.startswith("LOAD_GLOBAL")] ['LOAD_GLOBAL_MODULE'] ``` Since 3.11, a hot `LOAD_GLOBAL` specializes into **`LOAD_GLOBAL_MODULE`**, an inline-cached read that skips the hashing and probing and is nearly as cheap as `LOAD_FAST`. The optimization that mattered in Python 2, where every global read was a full dict lookup, was largely absorbed into the interpreter. It remains a real constant-factor win for genuine hot loops and nothing else; in cold code it buys nothing and costs a line of clarity. This is the chapter's methodological point in miniature: **an optimization's value is a number, not a belief, and the number changes as the interpreter does.** Measure on the interpreter you ship on. --- ## 2.9 Edges and failure modes **The copy-that-was-not.** §2.1. `b = a` aliases; it does not copy. When you need a copy, say so: `b = a.copy()`, `b = list(a)`, or `copy.deepcopy(a)` for a recursive one. The introduction's config bug is this failure in the wild. **The dynamic-namespace trap.** If the compiler cannot statically know a function's locals, because it contains `exec()` against an implicit namespace, it abandons fast locals and falls back to dictionary- based `LOAD_NAME`, searching local then global then builtin at runtime. (`from module import *` at function scope, which would cause the same problem, is a `SyntaxError` in Python 3 precisely to prevent it.) Keep function scopes statically analyzable; dynamic features defeat the single most important optimization the compiler performs. **`SyntaxError` versus `NameError`, and where they live.** Parsing and symbol analysis happen before any execution, so a malformed expression is rejected at compile time and can never reach the VM. An unbound name is a runtime `NameError`, because name resolution against globals and builtins is a runtime operation. Knowing which stage owns an error tells you where to look. **Do not fight code-object immutability.** Code objects are immutable by design; patching bytecode at runtime is a stunt, not an optimization. The supported lever is the function wrapper: decorators, `functools.partial`, closures. **Do not benchmark cold code.** §2.8's numbers are steady-state, after the specializer has warmed. A first-call measurement runs generic opcodes and measures something you will never ship. This is the discipline of **Deep K**. --- ## 2.10 Connections **Backward.** Chapter 1 covered why Guido reversed ABC's flaws, and showed the tokenizer emitting the INDENT/DEDENT tokens this chapter's parser consumes. The design commitments named there, everything- is-an-object and names-as-bindings, are the model §2.1 makes precise. **Forward.** The `PyObject` header whose refcount §2.1 increments is Chapter 19 (**Deep A**). Cyclic garbage collection and the late-binding-closure bug are Chapter 3. The PEG parser that replaced LL(1) is Chapter 14 (Python 3.9). The specializing adaptive interpreter that overturned §2.8's folklore is Chapter 17. The `_BORROW` opcode family and the full `ceval.c` loop are **Deep J**. Benchmarking discipline is **Deep K**. **Across books.** The pipeline stops at bytecode, and bytecode is an interpreter's internal affair, which is why crossing into **Book I** means leaving it entirely: a C++ function reached through `nanobind` is not compiled to a `PyCodeObject` and never enters this loop. Understanding where the Python pipeline ends is understanding where the C boundary begins, and that boundary is **Deep M**. --- ## 2.11 Exercises **1. Predict the aliasing.** Without running it, state the final value of every name: ```python x = [1, 2] y = x z = x[:] y.append(3) z.append(4) ``` Then run it. Which of `y` and `z` is a copy, and which single character made the difference? Explain in terms of §2.1. **2. Read the scopes.** Write a three-level nested function where the innermost reads a name from the outermost, skipping the middle. Use `symtable` (Listing 2.2) to show how each level classifies that name, then use `co_freevars`/`co_cellvars` (Listing 2.3) to show how the cell is threaded through the middle function that never uses it. Why must the middle function carry a free variable it does not reference? **3. Find `EXTENDED_ARG`.** §2.6 claims the compiler emits `EXTENDED_ARG` when an argument exceeds one byte. Construct the smallest function whose disassembly contains one, and confirm it with `dis`. Predict the number of constants or locals needed before writing the function. **4. Reproduce and extend the measurement.** Run `bench_locals_vs_globals.py`. Then modify it so the loop body does *less* work per item than `math.sqrt`, and predict, before running, whether the hoist's advantage grows or shrinks. Explain the result in terms of §2.7's specialization, and state the condition under which the classic advice would still be worth a line of readability. **5. The design question.** §2.8 shows that a headline optimization from Python 2 was largely absorbed into the interpreter by 3.11. Argue what this implies for how a performance-minded engineer should learn Python: which knowledge has a short half-life, which is durable, and how you would tell the difference before spending effort on it. Name one other optimization in this chapter that you expect the interpreter to eventually absorb, and say why. --- ## 2.12 Summary and cross-references - A Python program is a **graph of heap objects**; names are **bindings**, not typed storage. Assignment rebinds and adjusts refcounts; it never copies. `is` is identity, `==` is value. The aliasing bug in the introduction is this one fact, misunderstood. - Source is **compiled ahead of time** through tokenizer, PEG parser (PEP 617, 3.9+), symbol table, and compiler into an immutable **`PyCodeObject`**. Only the **evaluation loop** is interpretation. - The **symbol table** statically classifies every name, enabling array-indexed `LOAD_FAST` locals and **cell**-based closures that share live state. - Modern bytecode (3.11+) carries `RESUME`, the unified `BINARY_OP`, and fused **superinstructions**, and it **specializes itself** as it runs. On **3.14** the `LOAD_FAST` family became `LOAD_FAST_BORROW`; read `dis` on your interpreter, not folklore. - **Measured:** hoisting a global to a local saves about **4%** here, not the classic dramatic win, because 3.11+ specializes `LOAD_GLOBAL` into an inline-cached `LOAD_GLOBAL_MODULE`. An optimization's value is a number, and the number moves with the interpreter. **Cross-references.** The `PyObject` header and reference counting → Chapter 19 (Deep A). Cyclic GC and closure/comprehension scope → Chapter 3. The PEG parser → Chapter 14. The specializing adaptive interpreter → Chapter 17. The `ceval.c` loop and the `_BORROW` opcodes → Deep J. Benchmarking discipline → Deep K. The formal grammar and lexical rules → Deep S. The C-API boundary → Deep M. --- # Chapter 01 - From N-Grams to Neural Language Models > Free sample chapter from *Agentic AI: Zero to Godhood* (Book III of the Zero to Godhood series) by Shreejit Verma. > Canonical URL: https://zerotogodhood.com/books/agentic-ai/from-n-grams-to-neural-language-models/ > Copyright 2026 Shreejit Verma. All rights reserved. Content signals: search=yes, ai-input=yes, ai-train=no. ## What you will master - The language modeling objective stated precisely, and why it is a compression problem in disguise. - N-gram models, their smoothing machinery, and the exact reasons they hit a wall. - Neural language models from Bengio's 2003 formulation through RNNs, LSTMs, and seq2seq with attention. - Why next-token prediction, a seemingly trivial objective, produces general-purpose capability. - The GPT lineage and the wider frontier-model timeline through 2025, date-stamped so you can tell principle from ephemera. ## 1. The language modeling objective A language model assigns a probability to a sequence of tokens. Formally, for a sequence w_1, w_2, ..., w_T, the model estimates P(w_1, ..., w_T). The chain rule of probability factorizes this exactly, with no approximation: ``` P(w_1, ..., w_T) = P(w_1) * P(w_2 | w_1) * P(w_3 | w_1, w_2) * ... * P(w_T | w_1, ..., w_{T-1}) ``` This factorization turns the joint distribution over all possible texts into a product of next-token conditionals. Every language model you will ever use, from a bigram counter to Claude, is an estimator of P(next token | all previous tokens). The entire field disagrees only about how to represent the conditioning context and how to parameterize the conditional. Training minimizes the negative log-likelihood of the data, which is the cross-entropy between the empirical distribution and the model: ``` L = - (1/T) * sum_t log P_model(w_t | w_1, ..., w_{t-1}) ``` Perplexity is exp(L), the effective branching factor: a perplexity of 20 means the model is, on average, as uncertain as a uniform choice over 20 tokens. Perplexity is the oldest metric in the field and still the most honest one for pretraining, because it cannot be gamed by formatting tricks the way benchmark accuracy can. Its downside is that it correlates imperfectly with downstream usefulness, especially after post-training deliberately moves the model away from the pretraining distribution. ### The compression view Shannon's source coding theorem links prediction and compression: a model with cross-entropy H bits per token can compress text to H bits per token with arithmetic coding. A better language model is, literally, a better compressor of human text. This is not a metaphor; it is an identity, and it explains why scale helps. Compressing Wikipedia well requires knowing facts; compressing GitHub well requires knowing how programs behave; compressing dialogue well requires a model of what speakers want. The objective never mentions facts, programs, or intent, but the loss cannot go below a floor without them. Hold onto this framing, because Section 4 builds on it. ## 2. N-gram models The n-gram model makes a Markov assumption: the next token depends only on the previous n-1 tokens. ``` P(w_t | w_1, ..., w_{t-1}) ~= P(w_t | w_{t-n+1}, ..., w_{t-1}) ``` Estimation is counting: ``` P(w_t | context) = count(context, w_t) / count(context) ``` A trigram model over a large corpus can be built in an afternoon with a hash map, and until roughly 2012 this family powered production speech recognition and machine translation. Google's 2007 "large language models in machine translation" work used 5-gram models trained on trillions of tokens, which is a useful reminder that "train on the whole web" predates neural networks. ### Smoothing Raw counts fail catastrophically: any n-gram unseen in training gets probability zero, and one zero annihilates the whole product. Smoothing redistributes probability mass to unseen events, and the ladder of techniques is worth knowing because the ideas recur elsewhere. Laplace (add-one) smoothing adds one to every count. It is trivially simple but badly miscalibrated for large vocabularies, because it steals far too much mass from seen events. Backoff (Katz) uses the trigram estimate when the trigram was seen, otherwise falls back to the bigram, then the unigram. Interpolation (Jelinek-Mercer) always mixes all orders with learned weights, which is usually better than hard backoff. Kneser-Ney smoothing, the practical state of the art for n-grams, has an idea that survives into the neural era: estimate a word's backoff probability from how many distinct contexts it appears in, not how often it appears. "Francisco" is frequent but appears almost only after "San", so it should get low probability in novel contexts, even though its raw unigram count is high. Continuation probability is a primitive form of distributional generalization, which neural embeddings later do properly. ### Why n-grams hit a wall The failure modes are structural, not fixable by more data. - Combinatorial sparsity: the number of possible n-grams grows as V^n, so for any realistic vocabulary V most 5-grams that will occur in test data have never occurred in any training corpus, no matter how large. - No parameter sharing: "the cat sat on the" and "the dog sat on the" are unrelated events to an n-gram model; nothing learned about cats transfers to dogs. - Hard context ceiling: dependencies longer than n-1 tokens are invisible by construction, so agreement, coreference, and topic coherence beyond a few words are unmodelable. - Memory scales with data: the model is the count table, so more data means a bigger model with no abstraction. The lesson to carry forward: generalization requires representing words and contexts in a space where similarity is meaningful, so that evidence about one sequence informs predictions about related sequences. That is exactly what embeddings provide. ## 3. Neural language models ### Bengio 2003: the feedforward neural LM Bengio et al. (2003) introduced the architecture that defines the neural approach: map each vocabulary item to a learned dense vector (an embedding), concatenate the embeddings of the last n-1 words, and pass them through a feedforward network with a softmax over the vocabulary. Two ideas here are permanent. First, the embedding table shares parameters across contexts, so "cat" and "dog" can end up with nearby vectors and the model generalizes across them; this directly fixes the n-gram sharing failure. Second, the softmax over the full vocabulary, trained with cross-entropy, is still how every modern LLM produces its output distribution. The architecture kept the fixed context window of n-grams, so the context ceiling remained. Word2vec (Mikolov et al., 2013) later showed that embeddings trained on simple objectives capture striking regularities, popularized by the king - man + woman ~= queen example. Word2vec is not a language model in the generative sense, but it demonstrated that distributional structure is learnable at scale and cheap to learn, which made the field take embeddings seriously as the substrate for everything that followed. ### RNNs: unbounded context in principle The recurrent neural network (Elman 1990, applied to language modeling by Mikolov et al., 2010) removes the fixed window. At each step the RNN consumes one token and updates a hidden state: ``` h_t = tanh(W_hh * h_{t-1} + W_xh * x_t + b) P(w_t+1 | w_1..t) = softmax(W_out * h_t) ``` The hidden state is a fixed-size summary of the entire prefix, so in principle the context is unbounded. In practice two problems bite. The first is vanishing and exploding gradients. Backpropagation through time multiplies Jacobians across steps, so gradient norms shrink or blow up exponentially with distance. Exploding gradients are treatable with clipping; vanishing gradients mean long-range dependencies receive essentially no learning signal. The second is the fixed-size bottleneck: every fact about a 10,000-token prefix must be squeezed into one hidden vector, and information is overwritten as new tokens arrive. This is a lossy, recency-biased compression with no way to retrieve arbitrary earlier detail. ### LSTMs and GRUs The LSTM (Hochreiter and Schmidhuber, 1997) attacks the vanishing gradient with an additive cell state and multiplicative gates. The cell state c_t is updated by addition rather than repeated matrix multiplication, giving gradients a protected path backward in time: ``` f_t = sigmoid(W_f [h_{t-1}, x_t]) # forget gate i_t = sigmoid(W_i [h_{t-1}, x_t]) # input gate c_t = f_t * c_{t-1} + i_t * tanh(W_c [h_{t-1}, x_t]) o_t = sigmoid(W_o [h_{t-1}, x_t]) # output gate h_t = o_t * tanh(c_t) ``` The GRU (Cho et al., 2014) is a cheaper two-gate variant with similar practical performance. LSTMs powered the 2014-2017 era: Google's neural machine translation system, early neural speech systems, and character-level LMs that could generate plausible C code and Wikipedia markup (Karpathy's 2015 "Unreasonable Effectiveness of RNNs" post is the era's best artifact). LSTMs mitigated gradient decay but kept two structural limits. The fixed-size state bottleneck remained: gates decide what to forget, but something must be forgotten. And computation is inherently sequential: h_t cannot be computed before h_{t-1}, so training cannot parallelize across the time dimension, which caps the corpus size you can practically train on. The transformer's core economic advantage, before any modeling advantage, is that it removed this sequential dependency during training. ### Seq2seq and the birth of attention Sequence-to-sequence models (Sutskever et al., 2014) encode a source sentence into one vector and decode the target from it, and they made neural machine translation competitive. They also made the bottleneck vivid: translation quality collapsed on long sentences because one vector cannot hold a paragraph. Bahdanau et al. (2014) introduced attention as a fix: at each decoding step, compute a weighted average over all encoder hidden states, with weights derived from a learned relevance score between the decoder state and each encoder state. The decoder now retrieves from the whole source instead of relying on a single compressed summary. Attention was born as a patch on RNNs. The transformer's 2017 insight, covered in Chapter 02, was that the patch was the load-bearing part: with attention providing content-based retrieval over the whole context, the recurrence could be deleted entirely. ## 4. Why next-token prediction is so powerful It is worth being precise about why such a simple objective produces general capability, because sloppy versions of this argument ("it just predicts the next word, so it cannot reason") and equally sloppy counter-arguments are both common. First, the objective is a universal task container. Any task whose input and output can be serialized as text is an instance of next-token prediction: translation, summarization, question answering, code synthesis, and tool-call emission are all "predict the continuation of this prefix". The objective does not need to change per task; only the prefix does. This is why one pretrained model plus prompting replaced a decade of per-task architectures. Second, the loss floor forces modeling of the generative process. Text is produced by people who have knowledge, goals, and reasoning; predicting their output optimally requires modeling those latent causes, per the compression identity of Section 1. To predict the next token of a chess transcript at the ceiling you must model chess; to predict the last line of a proof you must verify the proof holds. How deeply current models actually model these latent causes, versus exploiting shallower statistical structure, is a live empirical question; the point here is about the direction the objective pushes, not a claim of achieved perfection. Third, the objective yields dense supervision at web scale. Every token of every document is a labeled training example, with no annotation cost. No other objective in machine learning combines this label density with this data availability, and Chapter 04 shows that data volume is half of the scaling-law story. Fourth, in-context learning falls out. Pretraining corpora contain endless documents where a pattern is established and then continued: lists, tables, Q&A pages, parallel translations. A model good at continuing such documents can be steered by demonstrations at inference time with no weight updates. This was observed as a surprise in GPT-2 and became the central interface in GPT-3 ("Language Models are Few-Shot Learners", 2020). The honest caveats, which Chapter 04 and Chapter 05 develop: - Likelihood training imitates the data distribution, including its errors, biases, and confident-sounding falsehoods; nothing in the objective rewards truth over truthiness. - The objective is myopic per token, and there is a train-test mismatch called exposure bias: training always conditions on real prefixes, generation conditions on the model's own possibly-flawed output. - A raw pretrained model is a document continuer, not an assistant; asked a question, it may respond with three more questions, because that is a plausible document. Post-training exists to close that gap. ## 5. The GPT lineage and the frontier timeline through 2025 Dates and orders of magnitude below are stated as of early 2026. Parameter counts are cited only where the developer disclosed them; frontier labs stopped disclosing around 2023. ### The GPT line - GPT-1 (OpenAI, June 2018): a 117M-parameter decoder-only transformer pretrained on BooksCorpus, then fine-tuned per task. The paper's thesis was generative pretraining as the universal initialization, beating task-specific architectures. - GPT-2 (February 2019): 1.5B parameters, trained on WebText. The headline result was zero-shot task performance: translation and summarization emerging without any fine-tuning, purely from the pretraining objective. The staged release over misuse concerns was the field's first mainstream safety controversy. - GPT-3 (May 2020): 175B parameters, roughly 300B training tokens. It established in-context few-shot learning as an interface and validated the Kaplan scaling laws in public. The API-only release created the "model as a service" business model. - Codex (2021): GPT-3 fine-tuned on code, powering GitHub Copilot; the proof that code generation was commercially real, and the ancestor of every coding agent in Volume 13. - InstructGPT (January 2022): the RLHF paper. A 1.3B instruction-tuned model was preferred by humans over the 175B raw GPT-3, the clearest early evidence that post-training quality can beat raw scale for usefulness. - ChatGPT (November 30, 2022): productized RLHF chat on the GPT-3.5 series. Technically incremental, historically pivotal; it made conversational LLMs a consumer category in weeks. - GPT-4 (March 2023): multimodal input, large capability jump, and a technical report that disclosed neither parameter count nor architecture, marking the industry's turn to secrecy. - GPT-4 Turbo (late 2023) and GPT-4o (May 2024): longer context, lower price, native multimodality, and much lower latency; the era's theme was making frontier capability cheap and fast rather than just bigger. - o1 (September 2024): the first production reasoning model, trained with RL to produce long private chains of thought; covered in depth in Chapter 06. - o3 (announced December 2024, released 2025) and GPT-5 (August 2025): continued the reasoning line; GPT-5 unified fast and reasoning modes behind a router. ### The Claude line - Claude 1 (Anthropic, March 2023) introduced Constitutional AI training to production. - Claude 2 (July 2023) pushed long context (100K tokens) before it was standard. - Claude 3 family (March 2024): Haiku, Sonnet, Opus; the tiered small/medium/large family became the industry norm. - Claude 3.5 Sonnet (June 2024) plus computer use (October 2024): the first frontier-lab agent controlling a real desktop, foreshadowing Volume 13. - Claude 3.7 Sonnet (February 2025): extended thinking with a controllable thinking budget. - Claude 4 Opus and Sonnet (May 2025), then Sonnet 4.5 and Opus 4.5 later in 2025: emphasis on agentic coding, long-horizon task persistence, and interleaved thinking between tool calls. ### The open-weight line - Llama 1 (Meta, February 2023) leaked and ignited the open-weight ecosystem; Llama 2 (July 2023) made the weights commercially licensed. - Mistral 7B (September 2023) and Mixtral 8x7B (December 2023) mainstreamed sliding-window attention and mixture-of-experts respectively at open scale. - Llama 3 and 3.1 (2024) brought open weights to 405B dense parameters and near-frontier quality. - Qwen (Alibaba) and DeepSeek releases through 2024-2025 made China-origin open weights competitive; DeepSeek-V3 (December 2024) demonstrated frontier-adjacent quality at unusually low disclosed training cost, and DeepSeek-R1 (January 2025) open-sourced an o1-class reasoning model, both covered later in this volume. ### Google's line, briefly Google invented the transformer (2017) and ran the encoder branch (BERT, 2018; T5, 2019) that dominated NLP benchmarks before decoder-only scaling won. PaLM (2022), Gemini 1 (December 2023), Gemini 1.5 with million-token context (2024), and Gemini 2.x (2025) mark its convergence onto the same decoder-only, long-context, reasoning-model trajectory as everyone else. ### What to remember from the timeline The stable pattern across all lineages: pretraining scale-ups from 2018 to 2023, then a pivot to post-training, inference efficiency, and test-time compute from 2024 onward as pretraining returns flattened and data limits approached. Model names and leaderboard positions in this section will rot; that pattern, and the objective from Section 1, will not. ## Exercises 1. Derive the chain-rule factorization for a three-token sequence and explain why it is exact rather than an approximation, and where the approximation enters for an n-gram model. 2. Train a trigram character-level model with add-one smoothing on a book from Project Gutenberg (pure Python, a dict of counts is enough). Sample 500 characters from it, compute its per-character perplexity on a held-out chapter, and identify three generated artifacts that demonstrate the Markov horizon. 3. Implement Kneser-Ney continuation counts for your corpus and show one concrete word (like "Francisco") whose continuation probability diverges sharply from its unigram probability. 4. Write the backpropagation-through-time gradient for a linear RNN h_t = W h_{t-1} + x_t and show that the gradient of the loss at step T with respect to h_1 contains W^(T-1). State the spectral condition on W under which the gradient vanishes. 5. Explain the LSTM cell-state update as a mitigation of your answer to exercise 4, and explain why the mitigation still cannot give the model random access to token 3 of a 10,000-token prefix. 6. Take any task you have shipped with an LLM (extraction, code review, summarization) and write out explicitly how it reduces to next-token prediction, including where the task specification lives in the token sequence. 7. Compute, from the compression identity, the compressed size in bytes of a 1M-token corpus under a model with 1.2 bits per token cross-entropy, and compare it to gzip's typical ratio on English text (measure gzip yourself; do not trust a remembered number). ## Godhood check You are ready for Chapter 02 when you can do all of the following without notes. - State the language modeling objective and the chain-rule factorization, and explain the exact location of the Markov approximation in an n-gram model. - Explain why smoothing is necessary, and what Kneser-Ney's context-diversity idea anticipates about embeddings. - Give the two structural failures of n-grams (sparsity without sharing, hard context ceiling) and map each to the neural mechanism that fixed it. - Explain vanishing gradients through the repeated-Jacobian argument and how the LSTM's additive cell state addresses it. - Name the two limits that survived into LSTMs (state bottleneck, sequential training) and which one the transformer's parallelism addressed first. - Argue both directions of the next-token-prediction debate: why the objective pushes toward modeling latent causes of text, and what the objective genuinely does not provide (truthfulness, non-myopia, assistant behavior). - Reconstruct the GPT lineage with approximate dates from 2018 to 2025 and state the field-level pivot that happened around 2024. --- # Chapter 01 - What Is An Agent > Free sample chapter from *Agentic AI: Zero to Godhood* (Book III of the Zero to Godhood series) by Shreejit Verma. > Canonical URL: https://zerotogodhood.com/books/agentic-ai/what-is-an-agent/ > Copyright 2026 Shreejit Verma. All rights reserved. Content signals: search=yes, ai-input=yes, ai-train=no. ## What you will master - Why "agent" has no settled definition, and why the definitional fights are really fights about money, safety, and product positioning. - The spectrum from hardcoded workflow to fully autonomous agent, and where real production systems actually sit on it. - Anthropic's operational framing: an agent is a model using tools in a loop, and why this definition won by being useful rather than by being philosophically complete. - The augmented LLM as the atomic building block: a model plus retrieval, tools, and memory. - A practical taxonomy of autonomy degrees you can use to scope a system before writing code. - The discipline of not building an agent: when a workflow, a single prompt, or a plain script beats an agent on every axis that matters. ## 1.1 The definition problem and its politics Ask five practitioners what an agent is and you will get five answers, each shaped by what its author sells or fears. This is not a sign that the field is confused about the technology. It is a sign that "agent" is a word doing economic and rhetorical work, not just technical work. Consider the incentives behind each common definition. Framework vendors tend to define agents structurally: an agent is a thing with a planner, a memory module, and a tool registry. This definition is convenient because it makes the framework's abstractions look load-bearing. The downside is that it imports architecture into the definition, so a fifty-line loop that outperforms the framework does not count as an agent. Marketing teams define agents by aspiration: an agent is software that does a job a human used to do. This definition sells, but it is unfalsifiable and covers everything from a cron job to a coworker. AI safety researchers define agents by goal-directedness: a system that pursues objectives over time, models its environment, and selects actions to achieve outcomes. This definition is precise about what makes systems dangerous, but it classifies a thermostat as a weak agent and says little about how to build software this quarter. Academic multi-agent-systems literature, which predates LLMs by decades, defines agents by properties: autonomy, reactivity, proactiveness, and social ability. The terminology is rigorous, but it was designed for BDI architectures and robotic control, and it maps awkwardly onto a stochastic text model calling a weather API. The practical resolution, and the one this volume adopts, is to stop asking "what is an agent" as an ontological question and ask it as an engineering question: what property of my system changes when I call it an agent. The answer is control flow ownership. In a workflow, your code decides what happens next. In an agent, the model decides what happens next. Everything else - memory, planning, multi-agent topologies - is elaboration on top of that single inversion of control. The trade-off in adopting this narrow definition is that it excludes some systems people call agentic, such as a fixed retrieval-then-summarize pipeline. That exclusion is deliberate. A definition that includes everything predicts nothing about cost, latency, failure modes, or testing strategy, and those predictions are the entire point of having a definition. ## 1.2 The spectrum from workflow to agent Anthropic's engineering guidance, first published in the "Building effective agents" essay in December 2024, drew a line that the industry largely adopted: distinguish workflows from agents. Workflows are systems where LLMs and tools are orchestrated through predefined code paths. Agents are systems where the LLM dynamically directs its own processes and tool usage, maintaining control over how it accomplishes tasks. This is a spectrum, not a binary, and it is worth walking through the rungs in order of increasing model control. ### Rung 0: single augmented call One prompt, one response, possibly with retrieval context or a forced tool call. Your code owns everything: what goes in, what the output must look like, what happens next. Classification, extraction, summarization, and translation live here. Most LLM value shipped to production as of early 2026 still lives here, which is worth remembering when agent hype peaks. ### Rung 1: prompt chaining A fixed sequence of LLM calls, where each step's output feeds the next step's input, often with programmatic checks between steps. Example: generate an outline, validate it against length constraints in code, then write the document from the outline. The decomposition trades latency for accuracy: each call does an easier task than the whole. The model has zero control over sequencing. ### Rung 2: routing An LLM classifies the input and your code dispatches to one of several specialized downstream paths. Example: a support system that routes refund requests, technical questions, and account issues to different prompts, tools, or models. The model makes exactly one decision, from a closed menu you wrote. ### Rung 3: parallelization Your code fans a task out across multiple simultaneous LLM calls and aggregates programmatically. Two subspecies matter: sectioning, where independent subtasks run in parallel, and voting, where the same task runs multiple times for diverse or higher-confidence output. Control flow is still entirely yours. ### Rung 4: orchestrator-workers A central LLM dynamically decomposes a task into subtasks it could not have enumerated in advance, delegates them to worker LLM calls, and synthesizes the results. This is the first rung where the shape of the computation is decided at runtime by a model. The number of subtasks, their content, and their ordering are model outputs. ### Rung 5: evaluator-optimizer One LLM produces work, another evaluates it against criteria, and the loop repeats until the evaluator is satisfied or a budget runs out. The model now controls loop termination within your outer bounds. ### Rung 6: the agent The model receives a goal, a tool set, and an environment. It plans, acts through tools, observes real results from the environment, adjusts, and continues until it judges the task complete or a hard limit stops it. Your code executes tools and enforces budgets; the model owns the trajectory. Two observations about this ladder matter more than the ladder itself. First, each rung up buys generality and costs predictability. A rung-1 chain has bounded cost, bounded latency, and unit-testable steps. A rung-6 agent has none of those properties without deliberate engineering, which is what Chapters 5 and 6 of this volume are about. Second, rungs compose. A production agent is frequently a rung-6 loop whose individual tools are rung-1 chains, sitting behind a rung-2 router that decides whether the request needs an agent at all. Reaching for composition before reaching for more autonomy is usually the right instinct. ## 1.3 Models using tools in a loop The definition this track builds on is the one Anthropic's engineers converged on and popularized through 2024 and 2025: an agent is a model using tools in a loop. Written as pseudocode, the entire concept is: ``` env_state = initial_task while not done: action = model(env_state, history) observation = execute(action) history.append(action, observation) done = stop_condition(action, history) ``` The definition earns its keep through what it refuses to include. It does not mention planning, because planning is just tokens the model emits before acting, not a separate module. It does not mention memory, because within a task the message history is the memory, and across tasks memory is just another tool. It does not mention reflection, self-critique, or reasoning strategies, because those are prompting patterns expressible inside the loop, not architecture. It does not mention multi-agent systems, because a subagent is just a tool whose implementation happens to contain another loop. This minimalism is a strong empirical claim: most of the capability lives in the model, and the harness should be thin. The claim has held up well. Claude Code, one of the most capable agents deployed as of early 2026, is at its core a single-threaded loop of exactly this shape, with capability coming from the model, the tool design, and the prompts rather than from orchestration machinery. The bitter-lesson reading is that elaborate scaffolding built to compensate for model weaknesses tends to become dead weight one model generation later, while a thin loop rides each model improvement for free. The trade-off of the thin-loop philosophy is that it concentrates trust in the model. When the model is not capable enough for the domain, a thin loop fails openly and repeatedly, and you must either add scaffolding, constrain the task, or wait for a better model. Knowing which of those three to choose is a judgment skill this volume tries to train. ## 1.4 The augmented LLM The building block underneath every rung of the ladder is what Anthropic's essay called the augmented LLM: a base model enhanced with three capabilities. Retrieval lets the model pull relevant knowledge into context on demand instead of relying on training data. Tools let the model act on the world and observe fresh, ground-truth results. Memory lets state survive beyond a single context window, whether as conversation history, files, or an external store. Each augmentation changes the failure characteristics of the system, not just its capabilities. Retrieval converts "the model does not know" into "the retriever did not find", which is a measurable, improvable engineering problem. Tools convert hallucination into verifiable error: a model that claims a test passed can be contradicted by the actual exit code in the transcript. Memory converts context-window exhaustion into a cache-management problem, with all the invalidation bugs that implies. A point that will recur throughout this volume: the interface quality of each augmentation matters as much as its existence. A tool with a vague description gets misused. A retriever that returns 40,000 tokens of marginal context poisons the loop it was meant to help. Anthropic's guidance is to spend as much design effort on tool definitions as on the prompts themselves, and Chapter 4 takes that instruction seriously. ## 1.5 Degrees of autonomy "Autonomous" is not a property a system has or lacks; it is a budget you grant along several independent axes. Scoping an agent means choosing a point on each axis explicitly. ### Axis 1: action authority What can the agent do without a human in the loop. Levels, roughly: read-only observation, reversible writes in a sandbox, reversible writes in production, irreversible actions with approval, irreversible actions without approval. A coding agent that can read a repo and propose a diff sits two full levels below one that can push to main, even if the loop code is identical. ### Axis 2: temporal scope How long the agent runs before a human sees anything. Levels: single response, single task of minutes, session of hours, standing process that runs on a schedule or reacts to events indefinitely. Cost variance and failure blast radius grow superlinearly with temporal scope, because errors compound across turns. ### Axis 3: goal ownership Who decides what the agent works on. Levels: human specifies each task, human specifies an outcome and the agent decomposes it, agent proposes tasks for approval, agent selects its own objectives within a charter. Nearly all production systems as of early 2026 sit at the first two levels, and the systems at the third and fourth levels are mostly research artifacts and demos. ### Axis 4: resource authority What the agent may spend: tokens, dollars, API rate limits, compute, and third-party quota. An agent without an explicit resource budget has an implicit one, namely everything, and it will eventually find that budget for you. Writing down a system's position on all four axes takes ten minutes and prevents the most common failure of agent projects, which is building level-4 authority infrastructure for a level-1 problem or, worse, granting level-4 authority to a system tested at level 1. ## 1.6 When not to build an agent Anthropic's guidance opens with advice that most agent content buries: find the simplest solution possible, and only increase complexity when demonstrably needed. Agents trade latency, cost, and predictability for capability on open-ended tasks, and that trade is frequently bad. Use the following four gates, and require a yes on all of them before building an agent. ### Gate 1: complexity Is the task genuinely open-ended, with steps that cannot be enumerated in advance. If a human expert could write down the procedure as a flowchart, encode the flowchart as a workflow. Workflows are cheaper, faster, testable step-by-step, and debuggable by reading code instead of transcripts. "Turn a design doc into a working PR" clears this gate; "extract the invoice total from this PDF" does not. ### Gate 2: value Does the outcome justify agent economics. An agent burning several dollars of tokens across dozens of turns is easily two orders of magnitude more expensive than a single call. A task worth fifty cents to solve cannot carry that cost; a task that replaces an hour of engineer time can. Latency has the same shape: interactive users tolerate seconds, and agents routinely take minutes. ### Gate 3: viability Is the current model actually capable at this task class, with the tools you can realistically provide. The honest test is empirical: run twenty representative tasks through a thin prototype loop before committing to the project. If the model succeeds at two of twenty, no amount of harness engineering will save the product, because harnesses amplify model capability rather than create it. ### Gate 4: cost of error Can mistakes be caught cheaply and reversed. Agents in domains with cheap verification, such as code with a test suite, thrive because the loop can self-correct against ground truth. Agents in domains where errors are expensive, silent, or irreversible, such as sending external emails or mutating financial records, need human gates that erode the autonomy you were paying for. If every action needs review, a workflow that drafts for human approval delivers the same value with far less machinery. Two anti-patterns deserve explicit names because they recur constantly. The resume-driven agent is a system built as an agent because agents are the prestigious shape in the current cycle, where a router plus three chains would outperform it on every metric. The demo-shaped agent is a system whose autonomy demos well on curated tasks but whose gates 3 and 4 were never honestly evaluated, and which therefore ships with an unbounded error budget its owners discover in production. ## 1.7 A worked example Task: customers email support asking to change their subscription plan. The agent-shaped temptation: an autonomous support agent with tools for reading the account, modifying the subscription, issuing refunds, and replying to the customer. Walking the gates: complexity is low, because plan changes follow an enumerable procedure with perhaps a dozen branches. Value per task is modest. Viability is fine, which is seductive. Cost of error is high, because wrong charges and wrong emails are customer-visible and partially irreversible. The correct build is a rung-2 router plus rung-1 chains: classify the request, extract the desired plan change with a schema-constrained call, look up the account in plain code, draft the reply and the change summary with a model call, and gate execution on one human click for anything touching billing. The model makes two constrained decisions; your code owns everything else. This system is boring, and boring is the highest compliment infrastructure can receive. Now change one assumption: the requests are not plan changes but arbitrary technical problems requiring investigation across logs, docs, and the customer's configuration. Complexity is now genuinely open-ended, verification is cheap because a proposed fix can be tested against the customer's reported symptoms, and value per resolution is high. The gates now say agent, and the rest of this volume is about building it properly. ## 1.8 Vocabulary you will need The following terms are used precisely for the rest of the volume. Harness: the code you write around the model - the loop, tool executors, budgets, and safety gates. Turn: one model call plus the execution of whatever tool calls it emitted. Trajectory: the full sequence of turns for one task, as recorded in the message history. Observation: any information returned to the model as a result of its action, including errors. Stop condition: the predicate that ends the loop, whether model-initiated, budget-initiated, or human-initiated. Environment: everything the tools can read or mutate, from a filesystem to a browser to a production database. ## Exercises 1. Take three systems currently marketed as "AI agents" and place each on the rung ladder from section 1.2, citing the specific control-flow evidence for your placement. 2. Write the four-axis autonomy scoping from section 1.5 for a coding assistant that reviews pull requests and pushes fix-up commits when its confidence is high. 3. Pick a task from your own work and run it through the four gates of section 1.6 in writing, reaching an explicit build or do-not-build verdict. 4. The pseudocode loop in section 1.3 has a subtle design decision: the stop condition inspects both the last action and the whole history. List three concrete stop conditions that require the history, not just the last action. 5. Argue the strongest possible case that the "models using tools in a loop" definition is too narrow, using a real system as your counterexample, then write the rebuttal. 6. Design the router-plus-chains version of the subscription-change system from section 1.7 as a diagram with every model call, code step, and human gate labeled. ## Godhood check You have mastered this chapter when you can do the following without reference material. - State three competing definitions of "agent", name the incentive behind each, and explain what the control-flow-ownership definition predicts that they do not. - Reconstruct the workflow-to-agent ladder from memory with a concrete example per rung, and explain what each rung trades for what. - Write the minimal agent loop as pseudocode and defend, one by one, why planning, memory, and multi-agent structure are absent from it. - Scope any proposed agent on the four autonomy axes in under ten minutes, producing limits concrete enough to implement. - Kill a bad agent project in a design review using the four gates, and specify the simpler system that should be built instead. - Explain why cheap verification is the single strongest predictor of agent success in a domain, with two examples on each side.