Platform Engineering · Lesson 250

NumPy: Arrays and Vectorised Maths

Almost all AI code in Python stands on NumPy: a fixed-type, n-dimensional array whose maths runs in compiled code instead of Python loops. pandas, scikit-learn, PyTorch, and every embedding search either use it or copy its ideas. This lesson follows one batch of embeddings from loading to a similarity search, through dtype, shape, vectorisation, broadcasting, and views, and shows the two mistakes that cost the most: a Python loop over ten million rows, and a broadcasting shape that silently builds an enormous wrong matrix.

Difficulty: Intermediate · Know this first: Lesson 235, Lesson 34

Run it as:

When it breaks, I check

One thing to remember

Where the time goes

This bar adds up seconds to score one batch of embeddings. It is a worked example, not a measurement. The vectorise and broadcast hops hold the costly mistakes.

Try it: what shape does broadcasting produce?

Pick the shapes of two arrays and the number of rows. See the result shape and how much memory it needs in float32.

(n, n)result shape
40 GBfloat32 memory

Surprise: (n,) and (n, 1) broadcast to an n-by-n matrix

Check yourself

Three questions. No score is saved anywhere — this is just you against the material.

Basic to master

NumPy grows in four levels: arrays, vectorised thinking, broadcasting and linear algebra, and memory-aware computing at scale.

Basic — Arrays

At the basic level you can create and inspect arrays.

  • np.array, np.zeros, np.arange, np.linspace, np.random.default_rng(0).
  • .shape, .dtype, .ndim, .size, .nbytes.
  • Indexing a[i, j], slicing a[:, 0].

Where it breaks: np.array([1, "a"]) silently makes everything a string.

Try it: Basic

What is the dtype of np.array([1, 2.5, 3])?

Now do it: Create arrays from mixed lists and print their dtype.

Intermediate — Vectorised thinking

At the intermediate level you replace loops with array operations.

  • Element-wise maths and ufuncs: np.exp, np.log, np.clip.
  • Reductions with axis= and keepdims=; boolean masks; np.where.
  • Softmax, normalisation, and z-scores in one line each.

Try it: Intermediate

How do you z-score each column of a (rows, cols) array?

Now do it: Write softmax for a (batch, classes) array without loops.

Advanced — Broadcasting and linear algebra

At the advanced level shapes and maths are deliberate.

  • Broadcasting rules; None or np.newaxis to add axes; asserting shapes.
  • @, np.einsum, np.linalg (norm, solve, svd).
  • argpartition for top-k; pairwise distances with broadcasting in chunks.

Try it: Advanced

Pairwise distances between 100,000 points need a (100,000, 100,000) matrix. How do you avoid the memory?

Now do it: Compute top-5 neighbours for 10,000 random vectors in chunks of 1,000.

Master — Memory-aware computing

At the master level arrays fit the machine.

  • Views versus copies, in-place operations, contiguous memory (np.ascontiguousarray), and memmap.
  • Lower precision (float16, int8 quantisation) and its accuracy cost.
  • When to move to PyTorch or CuPy on GPU, or to a vector database.

Trade-off: in-place operations and views save memory and make code harder to reason about, because changes show up through other names.

Try it: Master

b = a[::2] and then b *= 0. What happens to a?

Now do it: Check np.shares_memory for a slice, a mask, and a fancy index.

Go deeper

A similarity search over random unit vectors, small enough for a laptop. Install with pip install numpy in a virtual environment.

import numpy as np, time

rng = np.random.default_rng(0)
n, d = 200_000, 384
a = rng.standard_normal((n, d), dtype=np.float32)
print(a.shape, a.dtype, f"{a.nbytes / 1e6:.0f} MB")

t = time.perf_counter()
a /= np.linalg.norm(a, axis=1, keepdims=True)      # (n, d) / (n, 1): in place
print(f"normalised in {time.perf_counter() - t:.2f} s")

t = time.perf_counter()
for i in range(10_000):                             # the slow way, on 5% of rows
    a[i] = a[i] / np.linalg.norm(a[i])
print(f"loop over 10,000 rows: {time.perf_counter() - t:.2f} s")

q = a[42] + 0.05 * rng.standard_normal(d, dtype=np.float32)
q /= np.linalg.norm(q)
scores = a @ q                                      # (n, d) @ (d,) = (n,)
top = np.argpartition(-scores, 5)[:5]
print("top 5:", top[np.argsort(-scores[top])], "best score", round(float(scores.max()), 3))

x, y = np.ones(4), np.ones((4, 1))
print("broadcast trap:", (x - y).shape)             # (4, 4), not (4,)

One time it broke

This is a composite of a failure pattern that keeps repeating; the details are illustrative. A metric looked fine in a notebook and filled a server's memory in production.

Timeline

  • NotebookA data scientist centres scores with scores - means. On 1,000 rows it runs instantly; the numbers look plausible.
  • ProductionThe batch job runs on 2 million rows. means has shape (n, 1) and scores (n,); the result is (n, n). The job requests terabytes and is killed.
  • Next dayAn assert on shapes and a reshape fix it; reviewers find the notebook's numbers were wrong all along.

What changed after

Array code has shape assertions at function boundaries, tests use non-square inputs so (n, n) mistakes show, and batch jobs run with memory limits so they fail fast.

Try it yourself, from scratch

Everything here runs on any Linux machine: your own laptop, WSL on Windows (run wsl --install in PowerShell once), or a small cloud VM. The Python needs only Python 3 and its standard library; check that you have it with python3 --version.

Before you start: A virtual environment: python3 -m venv ~/py-lab && . ~/py-lab/bin/activate. Then pip install numpy for the commands.

1. Linux commands

Type each one, read what it prints, and compare it with the note above it.

  1. Memory is shape times bytes per element.

    python3 -c "import numpy as np; a = np.zeros((1_000_000, 384), dtype=np.float32); print(a.shape, a.dtype, a.nbytes / 1e6, 'MB')"
  2. A vectorised operation against a Python loop.

    python3 -c "import numpy as np, time
    a = np.random.default_rng(0).random(2_000_000)
    t = time.perf_counter(); b = a * 2 + 1; v = time.perf_counter() - t
    t = time.perf_counter(); c = [x * 2 + 1 for x in a]; l = time.perf_counter() - t
    print(f'vectorised {v:.4f} s, loop {l:.4f} s, {l / v:.0f}x slower')"
  3. The broadcasting trap: (n,) minus (n, 1).

    python3 -c "import numpy as np; x = np.ones(4); y = np.ones((4, 1)); print((x - y).shape, np.broadcast_shapes((4,), (4, 1)))"
  4. Slices are views of the same memory.

    python3 -c "import numpy as np; a = np.arange(6); b = a[:3]; b[0] = 99; print(a, np.shares_memory(a, b))"

2. Python: shapes_by_hand.py

This program implements NumPy's broadcasting rule in plain Python, so you can see why some shape pairs stretch, some fail, and one common pair silently becomes a square matrix. Save it as shapes_by_hand.py, then run it.

# shapes_by_hand.py
def broadcast(a, b):
    a, b = list(a), list(b)
    while len(a) < len(b): a.insert(0, 1)
    while len(b) < len(a): b.insert(0, 1)
    out = []
    for x, y in zip(a, b):
        if x != y and 1 not in (x, y):
            return None
        out.append(max(x, y))
    return tuple(out)

n = 10_000_000
for a, b, meaning in [((n, 384), (n, 1), "divide each row by its norm"),
                      ((n, 384), (384,), "subtract the column means"),
                      ((n,), (n, 1), "scores minus per-row means (a bug)"),
                      ((n, 384), (n,), "rows against a vector of length n")]:
    out = broadcast(a, b)
    size = "" if out is None else f", {4 * eval('*'.join(map(str, out))) / 1e9:,.1f} GB in float32"
    print(f"{str(a):<16} with {str(b):<11} -> {'ERROR' if out is None else str(out)}{size}  ({meaning})")

Run it, and you should see this output:

$ python3 shapes_by_hand.py
(10000000, 384)  with (10000000, 1) -> (10000000, 384), 15.4 GB in float32  (divide each row by its norm)
(10000000, 384)  with (384,)      -> (10000000, 384), 15.4 GB in float32  (subtract the column means)
(10000000,)      with (10000000, 1) -> (10000000, 10000000), 400,000.0 GB in float32  (scores minus per-row means (a bug))
(10000000, 384)  with (10000000,) -> ERROR  (rows against a vector of length n)

3. What to notice

4. Advanced: every step as one Bash script

The same Linux steps, made into a real script you can keep and run again. It uses the Bash features a production script needs: functions (one per step), an array of step names, arguments to choose steps, a case for options, exit codes recorded for each step, and a trap that prints a summary even when you stop it with Ctrl+C. Make a folder for this lesson (mkdir -p ~/labs/numpy-arrays-and-vectorised-maths && cd ~/labs/numpy-arrays-and-vectorised-maths) and save this as lab.sh.

#!/usr/bin/env bash
# The Linux steps of "NumPy: Arrays and Vectorised Maths", as one script (save it as lab.sh).
#
#   ./lab.sh          run every step, in order
#   ./lab.sh 2 4      run only steps 2 and 4
#   ./lab.sh --list   list the steps
#
# The steps share one shell, so a later step can use what an earlier one set up (a folder,
# a variable, a container): run them all in order the first time. Your own scripts should
# start with "set -euo pipefail"; this one runs teaching commands, and some of them fail on
# purpose, so it records each step's exit code instead of stopping at the first failure.

STEPS=(
  'Memory is shape times bytes per element.'
  'A vectorised operation against a Python loop.'
  'The broadcasting trap: (n,) minus (n, 1).'
  'Slices are views of the same memory.'
)

step_1() {
python3 -c "import numpy as np; a = np.zeros((1_000_000, 384), dtype=np.float32); print(a.shape, a.dtype, a.nbytes / 1e6, 'MB')"
}

step_2() {
python3 -c "import numpy as np, time
a = np.random.default_rng(0).random(2_000_000)
t = time.perf_counter(); b = a * 2 + 1; v = time.perf_counter() - t
t = time.perf_counter(); c = [x * 2 + 1 for x in a]; l = time.perf_counter() - t
print(f'vectorised {v:.4f} s, loop {l:.4f} s, {l / v:.0f}x slower')"
}

step_3() {
python3 -c "import numpy as np; x = np.ones(4); y = np.ones((4, 1)); print((x - y).shape, np.broadcast_shapes((4,), (4, 1)))"
}

step_4() {
python3 -c "import numpy as np; a = np.arange(6); b = a[:3]; b[0] = 99; print(a, np.shares_memory(a, b))"
}

# print a step that has to be run by hand, instead of running it
by_hand() {
  echo "  (run this one yourself: $1)"
  sed 's/^/    /'
}

RESULTS=()
run_step() {
  local n=$1 start=$SECONDS code
  printf '\n== step %d of %d: %s\n' "$n" "${#STEPS[@]}" "${STEPS[n-1]}"
  "step_$n"
  code=$?
  RESULTS+=("step $n: exit code $code, $((SECONDS - start)) s")
}

summary() {
  echo
  echo "== summary"
  local r
  for r in "${RESULTS[@]}"; do echo "  $r"; done
}

case "${1:-}" in
  -h|--help) sed -n '2,6p' "$0"; exit 0 ;;
  --list) for i in "${!STEPS[@]}"; do echo "$((i + 1)). ${STEPS[i]}"; done; exit 0 ;;
esac

[ $# -eq 0 ] && set -- $(seq 1 "${#STEPS[@]}")
for n in "$@"; do
  if ! [[ $n =~ ^[0-9]+$ ]] || (( n < 1 || n > ${#STEPS[@]} )); then
    echo "there is no step '$n'; try --list" >&2
    exit 2
  fi
done
trap summary EXIT
trap 'echo; echo "stopped with Ctrl+C"; exit 130' INT
for n in "$@"; do run_step "$n"; done

Then make it executable and run it:

chmod +x lab.sh
./lab.sh --list     # the steps
./lab.sh            # every step, then a summary of exit codes and times
./lab.sh 2 3        # only steps 2 and 3

5. Learn the basics behind it

New to a feature used above? These W3Schools pages explain each one from zero, with examples you can run in the browser.

If you remember nothing else

Design exercise

Build the scoring step of a semantic search: 5 million document embeddings of 768 numbers, queried 50 times a second for the top 10.

Clarifying questions to ask

What dtype and how much memory? How is each query scored, and how long may it take? How do you find the top 10 without sorting everything? When does this stop fitting on one machine?

Rough sizing

Say float32, unit-normalised vectors, a 100 ms budget per query, and one 32-core server with 64 GB of RAM.

Shape of the answer

float32 normalised once at load (15.4 GB), kept contiguous; each query normalised and scored with one matrix-vector product; argpartition for top 10, then sort those 10; batch several queries into one matrix product for throughput; shape assertions; above roughly 20 GB move to float16 or int8 or an approximate index.

Trade-offs to name

Exact search with NumPy is simple and correct and grows linearly with the data; approximate indexes are far faster at scale and trade a little recall. Lower precision halves memory and changes scores slightly.

Saved on this device, in this browser.
Next in this series · Lesson 251
pandas for ML Data Preparation

Before any model trains, someone turns raw tables into a clean training set, and that is usually done in pandas: a DataFrame of named, typed columns with fast group-by, join, and time operations.

Go to Lesson 251 →

Or browse the full course from the Lessons index.