Lesson 05 · Block and model

The Pieces Are Stacked Into a Model, and Run

Attention with heads is one sub-layer. A model is many of them, and a deep stack needs normalisation, residual paths, a per-unit MLP and, for point clouds, a hierarchy of resolutions. This lesson assembles both models and runs them: GPT-2 small on four tokens, a PTv3-style U-Net on the whole car.

map · flow · code: code/llm/c05_block_gpt.py, code/pc/c05_ptv3_block.py · book: chapter 4

The five lessons; lesson 05 highlighted Both pipelines; the block stack and head rows are marked

Where we are. The last rows: the block, the stack, the head. Book Figure 4.3 lists the order in which chapter 4 builds the pieces; we follow it.

Book Figure 4.3: the order of building blocks: GPT backbone, layer normalisation, GELU, feed forward, shortcut connections, transformer block, final GPT architecture

Book Figure 4.3. The chapter's chain; the cards below are its items 2 to 7, each with the point-cloud instance beside it. Item 1, the backbone's overall shape, is the pipeline figure above.

1The chain of this lesson

Definition · layer normalisation LayerNorm rescales one unit's vector to zero mean and unit variance over its channels, then applies a learned scale and shift: norm(x) = (x − mean) / √(var + ε) · scale + shift. The statistics are per unit, so they do not depend on the batch.

Why we need it: stacking twelve attention + MLP layers without it lets the activations' scale drift layer by layer and the gradients vanish or explode. Per-unit statistics are the point for point clouds too: batches of scenes vary wildly in size, which is why PTv3 moved from BatchNorm to LayerNorm inside the blocks (and kept BatchNorm only in pooling, where the ablation says it helps).

LLM Book Figure 4.5: six layer outputs are normalised to zero mean and unit variance
activations:
 tensor([[0.2260, 0.3470, 0.0000, 0.2216, 0.0000, 0.0000],
        [0.2133, 0.2394, 0.0000, 0.5198, 0.3297, 0.0000]],
       grad_fn=<ReluBackward0>)
mean per row: [0.1324, 0.217]  var per row: [0.0192, 0.0332]
after LayerNorm: mean [0.0, -0.0]  var [0.9995, 0.9997]
⚙ LayerNorm(emb_dim)(x) (Listing 4.2), x.var(dim=-1, unbiased=False) · c05_block_gpt.py § layernorm
code (LayerNorm)
class LayerNorm(nn.Module):
    def __init__(self,emb_dim):
        super().__init__()
        self.eps = 1e-5
        self.scale = nn.Parameter(torch.ones(emb_dim))
        self.shift = nn.Parameter(torch.zeros(emb_dim))

    def forward(self,x):
        mean = x.mean(dim=-1, keepdim=True)
        var = x.var(dim=-1, keepdim=True, unbiased=False)

        norm_x = (x-mean)/torch.sqrt(var + self.eps)

        return self.scale*norm_x + self.shift
Point cloud

The same layer, applied per point: nn.LayerNorm(32) on a (24 949, 32) tensor normalises each row over its 32 channels. The paper's Table 17: LayerNorm in blocks + BatchNorm in pooling scores 77.3 mIoU; LayerNorm everywhere 76.1; BatchNorm everywhere 76.7.

⚙ self.norm1 = nn.LayerNorm(dim) inside PTv3Block · common_pc.py § block

↓ normalised vectors go through a per-unit nonlinearity — which one, and how wide?

Definition · GELU and the feed-forward network The feed-forward network is two linear layers with a nonlinearity between them, applied to each unit on its own: 768 → 3 072 → 768 in GPT-2 (expand ×4, then contract). The nonlinearity is GELU, x · Φ(x), a smooth version of ReLU that keeps a small gradient for negative inputs.

Why we need it: attention only mixes vectors linearly (a weighted sum of values); without a nonlinearity the whole stack would collapse to one linear map. The ×4 expansion gives each unit room to compute features before compressing back. Two thirds of a block's parameters live here. PTv3's MLP is the same, ratio 4, GELU.

LLM Book Figure 4.9: the feed forward network expands 768 to 3072 and contracts back, shapes shown
x      : [-3.0, -1.0, -0.5, 0.0, 0.5, 1.0, 3.0]
GELU(x): [-0.0036, -0.1588, -0.1543, 0.0, 0.3457, 0.8412, 2.9964]
ReLU(x): [0.0, 0.0, 0.0, 0.0, 0.5, 1.0, 3.0]
FeedForward: (2, 3, 768) -> (2, 3, 768)  (expand to 3072 then back); parameters: 4,722,432
⚙ FeedForward(GPT_CONFIG_124M)(torch.rand(2, 3, 768)) (Listings 4.3, 4.4) · c05_block_gpt.py § gelu, § ffn
code (GELU, FeedForward)
class GELU(nn.Module):
    def __init__(self):
        super().__init__()

    def forward(self,x):
        return 0.5 * x *(1+ torch.tanh(
            torch.sqrt(torch.tensor(2.0/torch.pi))*
            (x + 0.044715* torch.pow(x,3))
        ))

class FeedForward(nn.Module):
    def __init__(self,cfg):
        super().__init__()
        self.layers = nn.Sequential(
            nn.Linear(cfg["emb_dim"], 4*cfg["emb_dim"]),
            GELU(),
            nn.Linear(4*cfg["emb_dim"],cfg["emb_dim"]))

    def forward(self,x):
        return self.layers(x)
Point cloud

Identical: nn.Sequential(nn.Linear(C, 4C), nn.GELU(), nn.Linear(4C, C)) per point. Nothing about points changes the MLP, because the MLP never looks at more than one unit.

⚙ self.mlp inside PTv3Block · common_pc.py § block

↓ deep stacks lose the gradient on the way back — give it a shortcut

Definition · shortcut (residual) connection A shortcut adds a sub-layer's input to its output: x ← x + f(x). The sub-layer learns a correction to x instead of a replacement, and the gradient has a path straight through the addition.

Why we need it: the book's experiment (Figure 4.12) shows the mean gradient in the first layer of a five-layer network: 0.0002 without shortcuts, 0.22 with them. Both models use two shortcuts per block, and PTv3 adds a third around xCPE. Lesson 3's softmax weights summing to 1 is what keeps the attention output on the scale of x, so the addition is well behaved.

LLM Book Figure 4.12: gradients vanish in a deep network without shortcut connections and stay healthy with them
⚙ x = x + shortcut twice in TransformerBlock.forward (Listing 4.6)
Point cloud

Three shortcuts per block: around xCPE (x + SparseConv(x)), around attention, around the MLP. The U-Net adds a fourth kind between resolutions: the decoder concatenates each encoder stage's output (the skip in the U figure below).

⚙ seq = seq + self.attn(self.norm1(seq)); x = seq + self.mlp(self.norm2(seq)) · common_pc.py § block

↓ normalisation, attention, shortcut, normalisation, MLP, shortcut — that is one block

Definition · the transformer block One block is: x ← x + Attention(LN(x)); x ← x + MLP(LN(x)), the pre-norm form. The input and output have the same shape, so blocks can be stacked. PTv3's block prepends x ← x + SparseConv(x) (xCPE, lesson 2) and its attention runs inside patches with the order of lesson 4's Shift Order.

Why we need it: one repeatable unit of computation whose shape never changes is what makes "depth" a single knob. Pre-norm (normalise before each sub-layer) is what keeps 12 or 24 stacked blocks trainable; the paper's Table 18: pre-norm 77.3, post-norm 72.3.

LLM Book Figure 4.13: the transformer block: layer norm, masked multi-head attention, dropout, shortcut, layer norm, feed forward, dropout, shortcut
Input shape: (2, 4, 768)  Output shape: (2, 4, 768)
one block = 7,085,568 parameters (attention 2,360,064 + FFN 4,722,432 + norms)
⚙ TransformerBlock(GPT_CONFIG_124M)(torch.rand(2, 4, 768)) (Listing 4.6) · c05_block_gpt.py § block
code (TransformerBlock)
class TransformerBlock(nn.Module):
    def __init__(self,cfg):
        super().__init__()
        self.att = MultiHeadAttention(
            d_in = cfg["emb_dim"],
            d_out = cfg["emb_dim"],
            context_length = cfg["context_length"],
            num_heads = cfg["n_heads"],
            dropout = cfg["drop_rate"],
            qkv_bias = cfg["qkv_bias"])

        self.ff = FeedForward(cfg)
        self.norm1 = LayerNorm(cfg["emb_dim"])
        self.norm2 = LayerNorm(cfg["emb_dim"])
        self.drop_shortcut = nn.Dropout(cfg["drop_rate"])

    def forward(self,x):
        # Shortcut connection for attention block
        shortcut = x
        x= self.norm1(x) # Pre-LayerNorm
        x= self.att(x) # Shape [batch_size, num_toekens, emb_size]
        x= self.drop_shortcut(x)
        x= x + shortcut # add original input back

        # shortcut connection for feed forward block
        shortcut = x
        x= self.norm2(x) #  Pre-LayerNorm
        x=self.ff(x)
        x= self.drop_shortcut(x)
        x= x + shortcut

        return x
Point cloud One GPT block and one PTv3 block drawn as rows of boxes; PTv3 adds xCPE at the front and attends inside patches
block input : (24949, 32) (points, channels) in original order
inside      : serialize -> pad -> 390 patches x 64 -> LN -> attention -> +x -> unserialize -> LN -> MLP -> +x
block output: (24949, 32)  parameters: 12,704
missing vs. the paper: xCPE (a sparse conv with skip before LN), which needs spconv/MinkowskiEngine
⚙ PTv3Block(dim=32, num_heads=4)(x, order, inverse, patch_size=64) · c05_ptv3_block.py § block
code (PTv3Block, no xCPE)
class PTv3Block(nn.Module):
    def __init__(self, dim, num_heads, mlp_ratio=4):
        super().__init__()
        self.norm1 = nn.LayerNorm(dim)
        self.attn = PatchAttention(dim, num_heads)
        self.norm2 = nn.LayerNorm(dim)
        self.mlp = nn.Sequential(nn.Linear(dim, mlp_ratio * dim), nn.GELU(), nn.Linear(mlp_ratio * dim, dim))

    def forward(self, x, order, inverse, patch_size):
        # x: (N, C) in original point order. Attention runs on the serialized, patch-grouped view.
        N, C = x.shape
        pad = (-N) % patch_size
        seq = x[order]
        if pad:                                              # borrow points to fill the last patch
            borrow = (torch.arange(pad) + (N - pad)) % N     # (wraps around if the stage has < patch_size points)
            seq = torch.cat([seq, seq[borrow]])
        seq = seq.view(-1, patch_size, C)                   # (patches, patch_size, C)
        seq = seq + self.attn(self.norm1(seq))              # residual 1: attention inside patches
        seq = seq.view(-1, C)[:N][inverse]                  # back to original order
        x = seq + self.mlp(self.norm2(seq))                 # residual 2: MLP per point
        return x

↓ GPT stacks blocks at one resolution — a point cloud needs to see the whole object, so it changes resolution

Definition · grid pooling (hierarchy) Grid pooling coarsens the grid by ×2 and merges all points that fall into one coarser cell into a single point (mean of their features, mean position). Four poolings take the car from 24 949 points to 29. The decoder reverses it: unpool copies a cell's feature back to its points and concatenates the encoder's skip.

Why we need it: a 64-point patch at 5 cm covers a hub cap; at 80 cm it covers the car. Pooling is how a point cloud gets context at object scale with the same patch attention. The LLM has no counterpart: GPT keeps (batch, tokens, 768) through all 12 blocks, because 1 024 tokens already fit one attention.

LLM

No pooling. The one place GPT changes shape is the head: 768 → 50 257 logits per position.

Point cloud Five points in one 10 cm cell become one pooled point; the car's point counts across the four pooling stages
grid pooling: merge all points of a coarser cell into one point (mean)
  input      :  24949 points at grid 0.05 m
  stage 1    :   2009 points at grid 0.10 m  (x12.4 fewer than input)
  stage 2    :    501 points at grid 0.20 m  (x49.8 fewer than input)
  stage 3    :    116 points at grid 0.40 m  (x215.1 fewer than input)
  stage 4    :     29 points at grid 0.80 m  (x860.3 fewer than input)
⚙ np.unique(floor(coords / g), axis=0, return_inverse=True), then index_add_ for the means · common_pc.py § grid_pool
code (grid_pool)
def grid_pool(coords, feats, grid_size):
    """Returns pooled coords (cell means), pooled feats (means), and the cell index of every input point."""
    cells = np.floor(coords / grid_size).astype(np.int64)
    _, inverse = np.unique(cells, axis=0, return_inverse=True)
    inverse = torch.as_tensor(inverse.reshape(-1))
    n_cells = int(inverse.max()) + 1
    counts = torch.zeros(n_cells).index_add_(0, inverse, torch.ones(len(inverse)))
    pooled_f = torch.zeros(n_cells, feats.shape[1]).index_add_(0, inverse, feats) / counts[:, None]
    pooled_c = torch.zeros(n_cells, 3).index_add_(0, inverse, torch.as_tensor(coords, dtype=torch.float32)) / counts[:, None]
    return pooled_c.numpy(), pooled_f, inverse

↓ embeddings, blocks, (pooling), a final norm and a head — assemble and count

Definition · the model GPTModel: token + position embedding → 12 blocks → LayerNorm → linear head to 50 257 logits per position. PTv3: feature embedding → 4 encoder stages (pool, then 2, 2, 6, 2 blocks at 64, 128, 256, 512 channels with 4, 8, 16, 32 heads) → 4 decoder stages (unpool + skip, 2 blocks each) → linear head per point.

Why we need it: this is where the parameter count becomes concrete: 163 M for GPT (124 M with the output head tied to the embedding), 46.2 M for the paper's PTv3. The mini U-Net below, which lacks the sparse-conv layers, has 13.1 M; the missing 33 M are the xCPE convolutions, which says how much of PTv3 is "position".

LLM Book Figure 4.15: the full GPT model: embeddings, twelve transformer blocks, final norm, output layer
Input batch:
 tensor([[6109, 3626, 6100,  345],
        [6109, 1110, 6622,  257]])
Output shape: (2, 4, 50257) = (batch, tokens, vocab)
Total number of parameters: 163,009,536
Number of trainable parameters considering weight tying: 124,412,160
Total size of the model: 621.83 MB (float32)
⚙ GPTModel(GPT_CONFIG_124M)(batch) (Listing 4.7); sum(p.numel() for p in model.parameters()) · c05_block_gpt.py § gpt
code (GPTModel)
class GPTModel(nn.Module):
    def __init__(self, cfg):
        super().__init__()
        self.tok_emb = nn.Embedding(cfg["vocab_size"], cfg["emb_dim"])
        self.pos_emb = nn.Embedding(cfg["context_length"], cfg["emb_dim"])
        self.drop_emb = nn.Dropout(cfg["drop_rate"])
        self.trf_blocks = nn.Sequential(*[TransformerBlock(cfg) for _ in range(cfg["n_layers"])])

        self.final_norm = LayerNorm(cfg["emb_dim"])

        self.out_head = nn.Linear(cfg["emb_dim"], cfg["vocab_size"], bias=False)

    def forward(self,in_idx):
        batch_size, seq_len = in_idx.shape
        tok_embeds = self.tok_emb(in_idx)

        pos_embeds = self.pos_emb(torch.arange(seq_len, device =in_idx.device))

        x = tok_embeds + pos_embeds

        x = self.drop_emb(x)
        x = self.trf_blocks(x)
        x = self.final_norm(x)
        logits = self.out_head(x)
        return logits
Point cloud The U-Net with the point counts measured on the car: encoder 24 949, 2 009, 501, 116, 29 points; decoder back up with skips; head per point
  embed        :  24949 points x  32 ch
  encoder 1    :   2009 points x  64 ch   depth 2, 4 heads, grid 0.10 m
  encoder 2    :    501 points x 128 ch   depth 2, 8 heads, grid 0.20 m
  encoder 3    :    116 points x 256 ch   depth 6, 16 heads, grid 0.40 m
  encoder 4    :     29 points x 512 ch   depth 2, 32 heads, grid 0.80 m
  decoder 4    :    116 points x 256 ch
  decoder 3    :    501 points x 128 ch
  decoder 2    :   2009 points x  64 ch
  decoder 1    :  24949 points x  64 ch
  head         : (24949, 2) = one logit vector per input point
parameters of this mini model (attention + MLP blocks only, no xCPE/sparse conv): 13,067,874
paper PTv3: 46.2 M parameters with the same depths/channels/heads, including the sparse-conv layers
⚙ run(coords, embed(feats)): pool → blocks per stage, unpool + concat → block, head · c05_ptv3_block.py § unet
code (mini U-Net)
depths, channels, heads = [2, 2, 6, 2], [64, 128, 256, 512], [4, 8, 16, 32]
grids = [0.10, 0.20, 0.40, 0.80]
embed = nn.Linear(4, 32)
proj = nn.ModuleList([nn.Linear(cin, cout) for cin, cout in zip([32] + channels[:-1], channels)])
enc = nn.ModuleList([nn.ModuleList([PTv3Block(c, h) for _ in range(d)]) for d, c, h in zip(depths, channels, heads)])
dec_channels = [256, 128, 64, 64]
dec_proj = nn.ModuleList([nn.Linear(cin + skip, cout) for cin, skip, cout in
                          zip([512, 256, 128, 64], [256, 128, 64, 32], dec_channels)])
dec = nn.ModuleList([PTv3Block(c, h) for c, h in zip(dec_channels, [16, 8, 4, 4])])
head = nn.Linear(64, 2)                                     # e.g. car-part labels

STAGES = []   # (name, points, channels, grid) for the drawn U-Net figure

def run(c, f):
    skips = [(c, f)]
    print(f"  embed        : {len(c):6d} points x {f.shape[1]:3d} ch")
    STAGES.append(("embed", len(c), f.shape[1], 0.05))
    for s in range(4):
        c, f, inv = grid_pool(c, f, grids[s])
        f = proj[s](f)
        o = serialize(quantize_to_grid(c, grids[s]))[1:]          # fresh orders for the pooled points
        order_names = list(PATTERNS)
        for i, blk in enumerate(enc[s]):
            name = order_names[i % 4]                               # Shift Order
            f = blk(f, torch.as_tensor(o[0][name]), torch.as_tensor(o[1][name]), PATCH)
        skips.append((c, f, inv))
        print(f"  encoder {s+1}    : {len(c):6d} points x {f.shape[1]:3d} ch   depth {depths[s]}, {heads[s]} heads, grid {grids[s]:.2f} m")
        STAGES.append((f"enc{s+1}", len(c), f.shape[1], grids[s]))
    for s in range(3, -1, -1):
        c_coarse, f, inv = skips[s + 1]
        c_fine, f_skip = skips[s][0], skips[s][1]
        f = f[inv]                                                  # unpool: copy each cell's feature to its points
        f = dec_proj[3 - s](torch.cat([f, f_skip], dim=1))
        o = serialize(quantize_to_grid(c_fine, grids[s - 1] if s > 0 else 0.05))[1:]
        f = dec[3 - s](f, torch.as_tensor(o[0]["z"]), torch.as_tensor(o[1]["z"]), PATCH)
        print(f"  decoder {s+1}    : {len(c_fine):6d} points x {f.shape[1]:3d} ch")
        STAGES.append((f"dec{s+1}", len(c_fine), f.shape[1], grids[s - 1] if s > 0 else 0.05))
    return head(f)

with torch.no_grad():
    logits = run(coords, embed(feats))
print("  head         :", tuple(logits.shape), "= one logit vector per input point")
n_params = sum(p.numel() for m in [embed, proj, enc, dec_proj, dec, head] for p in m.parameters())
print(f"parameters of this mini model (attention + MLP blocks only, no xCPE/sparse conv): {n_params:,}")
print("paper PTv3: 46.2 M parameters with the same depths/channels/heads, including the sparse-conv layers")

↓ a model that outputs logits — what do we do with them?

Definition · running the model (generate · label) The LLM generates: take the logits of the last position, softmax, argmax, append the chosen token to the input, repeat. The point-cloud model labels: argmax of each point's logits is its class, read back in the input order through lesson 1's inverse permutation. Untrained, both produce noise; the loop is what matters.

Why we need it: this closes the chain back to lesson 1: ids in, ids out, decode. The autoregressive loop is also why the LLM needed the causal mask (lesson 4), and the per-point readout is why the point cloud did not.

LLM Book Figure 4.16: the model generates one token at a time, appending it to the input for the next round Book Figure 4.17: one generation step in detail: encode, logits of the last position, softmax, argmax, decode
Output ids: [[15496, 11, 314, 716, 27018, 24086, 47843, 30961, 42348, 7267]]
Decoded   : 'Hello, I am Featureiman Byeswickattribute argue'
(untrained model: the loop works, the words are random)
⚙ generate_text_simple(model, idx, max_new_tokens=6, context_size=1024) (Listing 4.8) · c05_block_gpt.py § generate
code (generate_text_simple)
def generate_text_simple(model, idx, max_new_tokens, context_size):
    # idx is (batch, n_tokens) array of indices in the current context
    for _ in range(max_new_tokens):
        # Crop current context if it exceeds the supported context size
        idx_cond = idx[:, -context_size:]

        # Get the predictions
        with torch.no_grad():
            logits = model(idx_cond)

        # Focus on the last time step: (batch, n_tokens, vocab_size) -> (batch, vocab_size)
        logits = logits[:, -1, :]

        # Apply softmax to get the probabilities
        probas = torch.softmax(logits, dim=-1) # (batch, vocab_size)

        # get the idx of the vocab entry with the highest probability value
        idx_next = torch.argmax(probas, dim=-1, keepdim= True) # (batch, 1)

        # Append sampled index to the running sequence
        idx = torch.cat((idx,idx_next),dim=1) # (batch, n_tokens+1)

    return idx
Point cloud

One pass, no loop: logits.argmax(-1) is a label for each of the 24 949 points, already in the original order. Training compares it to the ground-truth label per point with cross-entropy (+ Lovász in the paper).

⚙ head(f) → (24 949, classes) in run() · c05_ptv3_block.py § unet

2Try it

LayerNorm by hand

3The parallel, complete

All five lessons in one table.
StepGPT-2 small (LLMs-from-scratch)PTv3
TokenBPE subword, id in 50 2575 cm cell of a point cloud
Ordergivenserialized along 4 space-filling curves
Embeddingtable 50 257 × 768 + position table 1 024 × 768stem 4 → 32 ch; position via xCPE conv in every block
Attention scopeprevious tokens (causal)patch of 1 024 points, no mask
Attention operatorscaled dot-product, 12 headsscaled dot-product, 4/8/16/32 heads
Cross-group flownone neededShift Order, Shuffle Order
NormLayerNorm, pre-normLayerNorm in blocks, BatchNorm in pooling
BlockLN → MHSA → + → LN → FFN → +xCPE → LN → Attn → + → LN → MLP → +
Depth / shape12 blocks at one resolutionU-Net: 4 + 4 stages, depths 2, 2, 6, 2 / 1, 1, 1, 1
Parameters124 M (tied) / 163 M46.2 M
Outputnext-token logits per positionclass logits per point

4What this lesson established

Why 163 M parameters in the output but "124 M" in the name?

GPT-2 ties the output head to the token embedding (same 50 257 × 768 matrix). Without tying it is counted twice: 163 009 536 − 38 597 376 = 124 412 160.

Why does PTv3 keep BatchNorm in pooling but not in the blocks?

Block statistics must not depend on how many scenes are in a batch, so LayerNorm. Pooling merges points, and the paper's ablation finds BatchNorm there stabilises the merged features (77.3 vs 76.1 mIoU with LayerNorm everywhere).

Where does the serialization order appear in the model, and where does it disappear?

Inside each block around attention only: serialize, pad, group, attend, un-serialize. The MLP, the pooling and the head all work on points in their original order.