2 Foundations 1 / 6
  1. In this chapter
  2. Python and tensor shapes
  3. From Language Modeling to Next-Token Prediction
  4. Neural Network Basics
  5. Information Theory Refresher
  6. Tokenizers and Embeddings
  7. Optimizers and Training Stability
All chapters →

Chapter 2 · Foundations 2.1

Python and tensor shapes: from a table to a linear layer

Start with a table of numbers, name the position and feature axes, and calculate a dot product and bias before running a linear layer in standard Python.

Beginner 7 min read Updated Companion code ↓

After this page you will be able to

  • Run a Python script and read its output.
  • Identify scalar, position, feature, and batch dimensions.
  • Calculate one linear-layer output by hand and check it in code.
  • Use axis order to diagnose matrix multiplication and broadcast errors.
On this page
  1. Step 1: run a line of Python
  2. Step 2: name each axis
  3. Step 3: use one dot product to fill a table
  4. Experiment: implement a tiny linear layer
  5. Step 4: use shapes to debug
  6. Summary and exercises
  7. Quick self-check
  8. Add a third input row
  9. Further reading
  10. FAQ

Think of a tensor as a table of numbers with coordinates. Its shape tells you how many entries lie along each axis, and axis names tell you what the coordinates mean. Read a two-by-three table, calculate one output by hand, and then run a tiny linear layer in Python. The examples use a CPU and the standard library.

Three colored tensor grids show input features multiplied by weights to produce output features.
Matrix multiplication aligns and reduces the input feature axis with the weight input axis, preserves positions, and produces a new feature axis.

Step 1: run a line of Python

Open a terminal and run python3 --version. On Windows, try py -3 --version. If Python is unavailable, use the official setup instructions for your operating system. Use Python 3.10 or newer. Save the code below as lesson.py and run python3 lesson.py from its directory, or py -3 lesson.py on Windows. Once it prints a result, change one input and run it again.

Square brackets create a list. The expression rows[0] reads the first row, and rows[0][1] reads its second entry. Python counts from zero. An indented line after a colon belongs to a function, loop, or other block. An assert checks an expectation and stops on failure. When a test fails, print the actual and expected values before tracing the calculation.

Step 2: name each axis

Suppose two token positions each have three features. Store one position per row and one feature per column. A third axis can represent several independent sequences.

QuantityShapeAxis meanings
One number()Scalar with no axes
Features of one token(D,)Features
Features of one sequence(T, D)Positions and features
A batch of equal-length sequences(B, T, D)Samples, positions, and features
Output scores of a language model(B, T, V)Samples, positions, and vocabulary entries

Axes can have equal sizes and distinct meanings. If batch size and sequence length are both two, selecting the first sequence gives a different result from selecting the first token in each sequence. Write axis names next to the dimensions, then check which one each index or summation operates on.

Step 3: use one dot product to fill a table

Each input row has three values. Each weight column has three coefficients and defines one output feature. Multiply the first input row [1, 2, 0] and first weight column [2, 1, 0] entry by entry, then sum to get four. Add the corresponding bias of one to get five. Repeat for every row and weight column to fill the output.

Matrix multiplication matches the inner dimensions. Multiplying input shape (T, D) by weights of shape (D, H) gives (T, H). The input feature axis is reduced, and each position survives. A bias of length H adds the same offsets to every row. This is broadcasting. An array library can apply that rule without physically copying the bias into each row.

Experiment: implement a tiny linear layer

Linear-layer and ReLU lab script

The code reads weight columns with zip(*weights). The star passes the rows as separate inputs to zip, which takes one entry from each row to form a column. Then the code computes dot products and adds bias. ReLU replaces negative values with zero and keeps the same shape. This example ran on an Apple M2 Max with Python 3.12.14.

from __future__ import annotations


def linear(
    rows: list[list[int]],
    weights: list[list[int]],
    bias: list[int],
) -> list[list[int]]:
    """Apply a linear layer to a batch of rows."""
    bad_weights = any(len(weight) != len(bias) for weight in weights)
    if not weights or not bias or bad_weights:
        raise ValueError("weight columns must match the bias")
    if any(len(row) != len(weights) for row in rows):
        raise ValueError("input width must match the number of weight rows")
    columns = list(zip(*weights, strict=True))
    output = []
    for row in rows:
        projected = []
        for column, offset in zip(columns, bias, strict=True):
            dot = sum(value * w for value, w in zip(row, column, strict=True))
            projected.append(dot + offset)
        output.append(projected)
    return output


def relu(rows: list[list[int]]) -> list[list[int]]:
    """Set negative entries to zero without changing the shape."""
    return [[max(0, value) for value in row] for row in rows]


rows = [[1, 2, 0], [-1, 0, 2]]
weights = [[2, 0], [1, -1], [0, 2]]
bias = [1, -1]
values = linear(rows, weights, bias)
activated = relu(values)
assert values == [[5, -3], [-1, 3]]
assert activated == [[5, 0], [0, 3]]
print("linear layer:", values)
print("ReLU output:", activated)
linear layer: [[5, -3], [-1, 3]]
ReLU output: [[5, 0], [0, 3]]

Change the second bias from minus one to zero. Predict the changed values and run the script. The original assertion describes the original inputs. Work out the new expected values before updating the assertion.

Step 4: use shapes to debug

SymptomLook here firstA small test
Matrix dimensions cannot multiplyLast input axis and first weight axisThree input features require three weight rows
Values look right in the wrong rowAxis order and indexingCalculate one position and check where it appears
Bias cannot be addedBias and last output axisTwo output features need two bias entries
Samples interfere unexpectedlyThe reduction or normalization axisChange another sample and check whether this sample changes

The same axis names transfer to Transformers. When you meet queries, keys, and values, start by treating them as separate projections and checking the shape of each. Find the first incorrect shape before comparing values downstream.

The widget below makes both of these clickable. Its shape checker gives every axis a name (B, T, D, H, V); pick two tensors and a matmul, a broadcast add or a sum along one axis, and watch NumPy’s shape rule right-align and compare axis by axis, naming which row of the table above an error belongs to. Below it is the page’s linear layer ported line by line: click any output cell to see how it is filled, append the exercise’s third row [0, 1, 1] to get [2, 0], or append a row with only two values and watch the width check stop the program.

Summary and exercises

  • Shape records axis sizes, and axis names record their meaning.
  • A linear layer reduces the input feature axis and keeps the positions.
  • Elementwise functions preserve shape. Broadcasting applies offsets to multiple rows.

Quick self-check

1. Two rows and three columns describe two positions. How many features per position?

  • Three.
  • Two.

Rows are positions and columns are features.

2. Input is (2, 3) and weights are (3, 4). What is the output shape?

  • (3, 3).
  • (2, 4).

The shared dimension is summed out.

3. How long is the bias for an output with shape (T, H)?

  • H.
  • T.

Each output feature gets one offset across positions.

4. What does ReLU do to the shape?

  • It shortens the sequence by dropping negative values.
  • It preserves the shape.

ReLU replaces a negative value with zero and keeps that coordinate.

Add a third input row

Add [0, 1, 1]. Predict the output shape and the last row. Then try a row with only two values and see which check fails.

Worked answer

The output has shape (3, 2). The new row has first value one plus the bias of one, and second value minus one plus two minus one. The result is [2, 0]. The two-feature row fails the input-width check.

Further reading

FAQ

Do I need a GPU for this lesson?
No. The example uses standard Python lists and loops. The same shapes carry over to arrays and GPUs.
How do shape and axis meaning differ?
Shape gives the lengths. Axis names tell you which lengths describe positions, features, or samples.
Why does bias leave the row count alone?
Each output feature has an offset that applies to the same column at each position.