# 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.

- URL: https://dmxsf.com/en/wiki/foundations/tensors-and-shapes/
- [DMXSF](https://dmxsf.com/en/about/)
- Beginner
- Updated: 2026-11-26
- Tags: Language modeling, Embeddings

## 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.

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.

*Figure: 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](https://docs.python.org/3/using/index.html) 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.

| Quantity | Shape | Axis 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](https://github.com/dmxsf/dmxsf/blob/main/labs/foundations/tensors-and-shapes/run.py)

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.

```python
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)
```

```text
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

| Symptom | Look here first | A small test |
| --- | --- | --- |
| Matrix dimensions cannot multiply | Last input axis and first weight axis | Three input features require three weight rows |
| Values look right in the wrong row | Axis order and indexing | Calculate one position and check where it appears |
| Bias cannot be added | Bias and last output axis | Two output features need two bias entries |
| Samples interfere unexpectedly | The reduction or normalization axis | Change 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?**

- [x] 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).
- [x] (2, 4).

> The shared dimension is summed out.

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

- [x] 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.
- [x] 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.

<details>
<summary>Worked answer</summary>

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.

</details>

## Further reading

- [NumPy broadcasting rules](https://numpy.org/doc/stable/user/basics.broadcasting.html).
- Continue with [neural network basics](https://dmxsf.com/en/wiki/foundations/neural-network-basics/) and the [Transformer block](https://dmxsf.com/en/wiki/architecture/transformer-block/).
- The next lesson in the four exercises is [LLM hardware basics](https://dmxsf.com/en/wiki/systems/hardware-basics/).

## Companion code

[Tensor shapes: a linear layer by hand](https://github.com/dmxsf/dmxsf/tree/main/labs/foundations/tensors-and-shapes): Track position and feature axes through a projection, bias and ReLU.

- Run it in the companion repository (add --quick for a fast pass): `uv run dmxsf run foundations/tensors-and-shapes`
- [View the lab script](https://github.com/dmxsf/dmxsf/blob/main/labs/foundations/tensors-and-shapes/run.py)
- [Lab write-up](https://github.com/dmxsf/dmxsf/blob/main/labs/foundations/tensors-and-shapes/README.en.md)
- [`tensor_shapes.py`](https://github.com/dmxsf/dmxsf/blob/main/src/dmxsf/foundations/tensor_shapes.py)
- [Find this lab in the catalog](https://dmxsf.com/en/code/#tensors-and-shapes)

## 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.
