Courses3 levels
Level 1 · Foundations11 courses
Level 2 · Core5 courses
Level 3 · Advanced5 courses
Labs8 topics
Library Practice exams AI Range Pricing Start free

Lesson 09 · 60 minutes

Compute attention and shrink a model's weights

After this lesson you can
  • Compute the attention weights of a short text and say which token gets the weight
  • Count the weights and the memory of a small and a large model from a layer table
  • Quantise and prune a layer, then measure the file size and the error added
Lab files of this lesson (34)

The lab folder as it stands after this lesson. Unzip it in ~/krlab.

More

The zip holds every file that the course has printed up to here. To start this lesson with the files of the earlier lessons only, take the zip of the lesson before. Type the code yourself first: you learn more.

Scenario

A vendor offers your branch offices an assistant that runs on office laptops, so that no text leaves the building. It is "the big model, only smaller: 4-bit and half pruned". Your lead asks how a model decides which words matter, how small is small, what shrinking costs, and what to record. You compute, count, and shrink.

Recall

Lesson 2: what is the context window?

The most tokens that a model can use in one call, prompt and answer together.

Lesson 3: the file of `llama3.2:3b` is 2.0 GB. Why is it so much smaller than 3 billion weights of 16 bits (about 6 GB)?

It is quantised: each weight takes about 5 bits, not 16. Step 2 shows the sum.

The idea

The model of lesson 1 looked at one earlier token. A real LLM looks at thousands, with the transformer design of the 2017 paper "Attention Is All You Need" (Vaswani and others). Its core is attention: each token asks which other tokens matter for it. The input is embeddings ("How AI works", lesson 9). Each token has three vectors:

  • a query: what this token looks for;
  • a key: what this token offers to a query;
  • a value: what this token passes on when it is chosen.

The score of a token is the dot product of the query with its key: multiply the matching places and add them up. It is large when the vectors point the same way. The model divides each score by the square root of the vector length (here 3, so about 1.73): without it, long vectors give huge scores and softmax puts nearly all the weight on one token. Softmax turns all scores into positive weights that add up to 1. The new vector of the asking token is the sum of the values, each times its weight.

Attention for one token
QueryScoresWeightsMixdot product with the key of each tokensoftmax makes them add up to 1add the values, each times its weightQueryScoresWeightsMix123
  1. Query → Scores: dot product with the key of each token
  2. Scores → Weights: softmax makes them add up to 1
  3. Weights → Mix: add the values, each times its weight

A real model learns the tables that make queries, keys and values. It has many layers, and each layer runs several heads of this attention side by side. The width is the number of values in one token's vector. Every token scores the others, so n tokens need about n x n scores (about half for a text generator, which looks only back, but still the square of n): a long context window is expensive.

A small language model (SLM) and a large language model (LLM) use the same design. No official line divides them: this course calls a model small when it runs on an ordinary laptop CPU. The cost that matters is memory: the weights times the bits of each weight.

Two methods make a model smaller. Quantisation stores each weight as a whole number of steps with fewer bits, plus one step size. Pruning sets the smallest weights to zero, so that a sparse file or a runtime can skip them. After pruning, a model is often trained a little more (fine-tuned) so that it recovers.

Worked example

Work in ~/krlab/llms-and-agents. The programs use the standard library only.

1. Compute attention weights

In "the firewall blocked the packet because it ...", the token it asks which earlier token it means. The numbers are invented. New in the code: math.sqrt is the square root, math.exp is e to the power of a number, zip(a, b) walks two lists together, and max gives the largest item. In a print line, {token:<9} pads a word to 9 characters (>5 pads on the left), {score:5.2f} prints 2 decimals, and {n * n:,} adds commas.

attention.py

import math

# Invented numbers: a real model learns them. The places are [is a thing, is a device, is an action].
tokens = ["the", "firewall", "blocked", "the", "packet", "because", "it"]
keys = [
    [0.0, 0.0, 0.0],   # the
    [1.0, 2.0, 0.0],   # firewall
    [0.0, 0.0, 2.0],   # blocked
    [0.0, 0.0, 0.0],   # the
    [2.0, 0.0, 0.0],   # packet
    [0.0, 0.0, 0.0],   # because
    [1.0, 0.0, 0.0],   # it
]
values = keys                      # the values equal the keys, to keep it small
query = [2.0, -1.0, 0.0]           # "it" looks for a thing that is not a device


def dot(a, b):
    return sum(x * y for x, y in zip(a, b))


def softmax(scores):
    biggest = max(scores)          # subtract it so that exp() cannot overflow
    exps = [math.exp(s - biggest) for s in scores]
    return [e / sum(exps) for e in exps]


scale = math.sqrt(len(query))      # keeps the scores small
scores = [dot(query, k) / scale for k in keys]
weights = softmax(scores)
for token, score, weight in zip(tokens, scores, weights):
    print(f"{token:<9} score {score:5.2f}  weight {weight:.2f}")
print("weights add up to", round(sum(weights), 2))

mix = [sum(w * v[i] for w, v in zip(weights, values)) for i in range(3)]
print("mix of the values:", [round(m, 2) for m in mix])

for n in (7, 1000, 4096):
    print(f"{n:>5} tokens: {n * n:,} scores")
python3 attention.py
the       score  0.00  weight 0.05
firewall  score  0.00  weight 0.05
blocked   score  0.00  weight 0.05
the       score  0.00  weight 0.05
packet    score  2.31  weight 0.55
because   score  0.00  weight 0.05
it        score  1.15  weight 0.17
weights add up to 1.0
mix of the values: [1.33, 0.11, 0.11]
    7 tokens: 49 scores
 1000 tokens: 1,000,000 scores
 4096 tokens: 16,777,216 scores
Attention weight of each token for "it"
the (first)0.05firewall0.05blocked0.05the (second)0.05packet0.55because0.05it0.17the (first)0.05firewall0.05blocked0.05the (second)0.05packet0.55because0.05it0.17

Check packet by hand. Its dot product is 2 times 2 = 4, and 4 divided by 1.73 is the printed 2.31. Softmax gives e^2.31 = 10.1, divided by the sum of e^score over all seven tokens, 18.2: 0.55. The printed weights are rounded, so they add up to 0.97; the exact ones add up to 1. The query wants a thing that is not a device, so firewall scores 0: its device place cancels its thing place. The mix is mostly the value of packet, so the new vector of it carries "packet". The last lines show the cost: 4,096 tokens need about 16.8 million scores for each head of each layer.

2. Count weights and memory

A layer of a transformer holds about 12 tables of width x width weights (4 for attention and 8 for the feed-forward part), and the vocabulary adds vocab x width. This skips the small parts, so it is an estimate. The two models are invented. Memory in bytes is the weights times the bits, over 8. {n:>15,} pads on the left to 15 characters, and 1e9 is a billion. Create size.py.

size.py

# Two invented models: layers, width of a layer, size of the vocabulary.
MODELS = {
    "small": {"layers": 18, "width": 2048, "vocab": 32000},
    "large": {"layers": 80, "width": 8192, "vocab": 32000},
}
BITS = {"16-bit": 16, "8-bit": 8, "4-bit": 4}


def parameters(layers, width, vocab):
    return 12 * layers * width * width + vocab * width    # 12 tables of width x width in each layer


for name, table in MODELS.items():
    n = parameters(**table)
    sizes = "  ".join(f"{label} {n * bits / 8 / 1e9:6.1f} GB" for label, bits in BITS.items())
    print(f"{name:<6} {n:>15,} weights  {sizes}")

# The model of lesson 3: about 3.21 billion weights in a file of about 2.0 GB.
print("llama3.2:3b bits per weight:", round(2.0e9 * 8 / 3.21e9, 1))
python3 size.py
small      971,505,664 weights  16-bit    1.9 GB  8-bit    1.0 GB  4-bit    0.5 GB
large   64,686,653,440 weights  16-bit  129.4 GB  8-bit   64.7 GB  4-bit   32.3 GB
llama3.2:3b bits per weight: 5.0

The small model fits in a laptop at 16 bits. The large one needs 129 GB at 16 bits, and 32 GB at 4 bits. The file of llama3.2:3b in lesson 3 is 2.0 GB for 3.21 billion weights: about 5 bits each ("Q4_K_M", a mix of 4-bit and 6-bit blocks, each with its step size). Take current figures from the model page. Run-time memory is higher.

3. Quantise a layer

One layer has 1,000 weights and one fixed input. The weights are cubed random numbers: many small, a few large, like a trained layer. random.Random(7) has a fixed seed, so every machine gets the same numbers. struct.pack("1000f", *weights) (* hands the items over one by one) writes 32-bit floats, so its len is a real byte count. quantize divides each weight by one step (the largest weight over 127 for 8 bits), rounds to a whole number, and multiplies back. abs drops the sign, ** is a power, // divides to a whole number, and + in {x:+.4f} prints the sign. weights[1:] is the list without its first item; the last lines use it to plant one large weight, because one large weight sets the step for all the others. Create shrink.py with this first part.

import random
import struct

# One layer of 1000 weights and one fixed input. random() gives the same numbers on every machine.
rng = random.Random(7)
weights = [(2 * rng.random() - 1) ** 3 * 0.8 for _ in range(1000)]   # many small weights, a few large
inputs = [rng.random() for _ in range(1000)]


def output(w):
    return sum(a * b for a, b in zip(w, inputs))       # what the layer gives for the input


def quantize(w, bits):
    top = 2 ** (bits - 1) - 1                          # 127 for 8 bits, 7 for 4 bits
    step = max(abs(x) for x in w) / top
    whole = [round(x / step) for x in w]
    return whole, step, [q * step for q in whole]      # the whole numbers, the step, the weights back


def mean_error(a, b):
    return sum(abs(x - y) for x, y in zip(a, b)) / len(a)


print("float32 file:", len(struct.pack("1000f", *weights)), "bytes")
print("output of the layer:", round(output(weights), 4))
for bits in (8, 4, 2):
    whole, step, back = quantize(weights, bits)
    size = len(whole) * bits // 8 + 4                  # the whole numbers, plus one float32 for the step
    print(f"{bits}-bit: {size:>4} bytes  mean error {mean_error(weights, back):.4f}  "
          f"output change {output(back) - output(weights):+.4f}")

spiky = [3.0] + weights[1:]                            # the same layer with one large weight
_, _, back = quantize(spiky, 8)
print(f"8-bit with one large weight: mean error {mean_error(spiky, back):.4f}")
python3 shrink.py
float32 file: 4000 bytes
output of the layer: -4.5021
8-bit: 1004 bytes  mean error 0.0014  output change +0.0026
4-bit:  504 bytes  mean error 0.0223  output change +0.4128
2-bit:  254 bytes  mean error 0.1269  output change +0.7749
8-bit with one large weight: mean error 0.0051

8 bits cut the size to a quarter (4,000 to 1,004 bytes) and moved the output by 0.0026 (of -4.50). At 4 bits it moves by 0.41; at 2 bits the layer is badly damaged.

The last line shows a danger. One large weight (3.0) sets the step for all the others, and the 8-bit error is 0.0051: more than three times larger than 0.0014. So real formats keep one step for each small block of weights (in the GGUF format of llama.cpp, one for each 32).

4. Prune a layer

prune finds the size below which a share of the weights lie (sorted puts the sizes in order) and zeroes those weights. sum(1 for x in cut if ...) counts the items that pass a test, and {share:.0%} prints a percentage. The new lines also measure a dense file and a sparse one, which stores each non-zero weight with its place. Add these lines at the end of the file.

def prune(w, share):
    cut = sorted(abs(x) for x in w)[int(len(w) * share) - 1]
    return [0.0 if abs(x) <= cut else x for x in w]    # zero the smallest weights, by size


for share in (0.5, 0.9):
    cut = prune(weights, share)
    zeros = sum(1 for x in cut if x == 0.0)
    dense = len(struct.pack("1000f", *cut))               # the zeros are still stored
    sparse = (len(cut) - zeros) * (4 + 2)                 # per kept weight: a float32 value and a 2-byte place
    print(f"prune {share:.0%}: {zeros} zeros  dense {dense} bytes  sparse {sparse} bytes  "
          f"output change {output(cut) - output(weights):+.4f}")
python3 shrink.py | tail -2
prune 50%: 500 zeros  dense 4000 bytes  sparse 3000 bytes  output change +0.9349
prune 90%: 900 zeros  dense 4000 bytes  sparse 600 bytes  output change +2.5049

Half of the weights are zero, and the output moved by 0.93, about a fifth of its value: more than 8-bit quantisation did. One sum is a noisy measure, and its sign can change with another seed. A model is fine-tuned after pruning, and tested again.

The zeros do not shrink the dense file: it still holds 1,000 numbers (4,000 bytes). A sparse file is smaller (3,000 bytes at 50 percent, since each kept weight needs 2 bytes for its place; 600 at 90 percent). A runtime is faster only if it skips the zeros.

5. The finished file

The finished file: shrink.py

shrink.py

import random
import struct

# One layer of 1000 weights and one fixed input. random() gives the same numbers on every machine.
rng = random.Random(7)
weights = [(2 * rng.random() - 1) ** 3 * 0.8 for _ in range(1000)]   # many small weights, a few large
inputs = [rng.random() for _ in range(1000)]


def output(w):
    return sum(a * b for a, b in zip(w, inputs))       # what the layer gives for the input


def quantize(w, bits):
    top = 2 ** (bits - 1) - 1                          # 127 for 8 bits, 7 for 4 bits
    step = max(abs(x) for x in w) / top
    whole = [round(x / step) for x in w]
    return whole, step, [q * step for q in whole]      # the whole numbers, the step, the weights back


def mean_error(a, b):
    return sum(abs(x - y) for x, y in zip(a, b)) / len(a)


print("float32 file:", len(struct.pack("1000f", *weights)), "bytes")
print("output of the layer:", round(output(weights), 4))
for bits in (8, 4, 2):
    whole, step, back = quantize(weights, bits)
    size = len(whole) * bits // 8 + 4                  # the whole numbers, plus one float32 for the step
    print(f"{bits}-bit: {size:>4} bytes  mean error {mean_error(weights, back):.4f}  "
          f"output change {output(back) - output(weights):+.4f}")

spiky = [3.0] + weights[1:]                            # the same layer with one large weight
_, _, back = quantize(spiky, 8)
print(f"8-bit with one large weight: mean error {mean_error(spiky, back):.4f}")


def prune(w, share):
    cut = sorted(abs(x) for x in w)[int(len(w) * share) - 1]
    return [0.0 if abs(x) <= cut else x for x in w]    # zero the smallest weights, by size


for share in (0.5, 0.9):
    cut = prune(weights, share)
    zeros = sum(1 for x in cut if x == 0.0)
    dense = len(struct.pack("1000f", *cut))               # the zeros are still stored
    sparse = (len(cut) - zeros) * (4 + 2)                 # per kept weight: a float32 value and a 2-byte place
    print(f"prune {share:.0%}: {zeros} zeros  dense {dense} bytes  sparse {sparse} bytes  "
          f"output change {output(cut) - output(weights):+.4f}")

Your turn

Change the three programs.

  1. In attention.py, change the query to [1.0, 2.0, 0.0]: a token that looks for a device. Run it.
  2. In size.py, add a third model, medium, with 32 layers, a width of 4096 and a vocabulary of 32000. Run it.
  3. In shrink.py, change the seed to 11. Run it.

Last, write two lines: what you would test and record before a 4-bit, half-pruned copy runs in a branch office. Compare them with the first Field note.

Check yourself

You double the number of tokens in the context window. How many more attention scores does a layer compute?

Four times as many: n x n becomes (2n) x (2n).

Why did one large weight raise the error of 8-bit quantisation for all the other weights?

The step is the largest weight divided by 127. A large weight makes the step large, so every small weight is rounded coarsely.

A pruned and quantised copy passed the vendor's tests. Why must you test it again?

A different artefact: its answers can differ, and so can how often it follows your rules or refuses an attack.

A vendor says that its model is half pruned. Is the file half as big?

Not if the file is dense: the zeros are still stored (4,000 bytes before and after). A sparse file is smaller (3,000 bytes here), and a runtime is faster only if it skips the zeros. Ask for the measured size and speed.

Field notes

  • A quantised or pruned copy is a new artefact. Give it its own inventory entry: the base model and its digest, the method, the bits, the share pruned, the file hash, and your test results. Run the tests of the original (accuracy, refusals, the injection tests of the course "Securing LLM applications") on it before it replaces the original. Ask a vendor for the measured size and speed, not the share pruned.
  • Strangers often share shrunk models. Check the source and the hash before you load one (the course "Securing models and the ML supply chain").
  • A small model that you run yourself keeps your prompts local, but other risks stay: it may invent more (lesson 5) and follow injected text.
  • Attention weights show where one layer put weight, not why the model answered. Do not use them alone as proof in an incident report.