Skip to content
← writing

My favourite interview questions

Feb 13, 2026 · 25 min read · interviews

contents
  1. 1Q1: what is the complexity of matrix multiplication?
  2. 2Q2: given a function that generates a random number between 0 and 1 (uniformly distributed), calculate pi.
  3. 3Q3: what happens when you enter www.google.com and press enter?
  4. 4Q4: how does CUDA work? what is Flash Attention?
  5. 5Q5: implement a GPT from scratch. no libraries.

Because no one wants to ask the candidate to derive Kadane's algorithm in 30 minutes while pretending they've never seen it.


Q1: what is the complexity of matrix multiplication?

O(n^3)

For two n×n matrices, each of the n² outputs is a dot product of length n: n multiplies and n adds. That is n³ multiply-adds, or 2n³ FLOPs (what a FLOP is). For n = 1024, that is 2.1 billion FLOPs.

First you check if they can even be multiplied: the columns of a must equal the rows of b. Then you create an output array to store the results. Then you run a triple loop. You'd be surprised how many people (including my roomate at IDFC bank) think it's n²

python
import numpy as np
 
def matrixmul(a, b):
    m, n1 = len(a), len(a[0])
    n2, p = len(b), len(b[0])
    if n1 != n2: return -1
    # else do matrix mul
    c = [[0 for _ in range(p)] for _ in range(m)]
    for i in range(m):
        for j in range(p):
            for k in range(n1):
                c[i][j] += a[i][k] * b[k][j]
    return c
 
def matrixmulNumpy(a, b):
    a, b = np.array(a), np.array(b)
    if a.shape[1] != b.shape[0]: return -1
    return (a @ b).tolist()

How do you optimise it? Let's do a test, using this same on float32 precision, on M4 macbook (n = 1024; the pure Python version uses n = 256 because n = 1024 takes minutes):

VersionGFLOP/svs Python
Pure Python triple loop0.061×
C, i-j-k loop, clang -O32.45approximately 44×
C, i-k-j loop, clang -O332.6approximately 580×
NumPy a @ b (Apple Accelerate BLAS)1,529approximately 27,000×

1. Loop order is worth 13×. NumPy and C store matrices row by row, so accessing elements next to each other in a row is faster. In the i-j-k loop order, the code jumps around memory when reading matrix b. Each step moves 4 KB to get just 4 bytes of data. Most of the data loaded into the CPU cache goes unused. In the i-k-j loop order, the code reads elements next to each other in a row. It makes better use of the CPU cache because almost every byte loaded gets used. It also allows the compiler to use SIMD instructions, which perform multiple multiplications and additions in a single instruction. We can verify this using clang -Rpass=loop-vectorize option: it vectorizes the i-k-j loop but not the i-j-k loop.

The result: Both loops perform the same calculations and have the same O(n³) time complexity, but changing the loop order makes the code 13× faster because it uses memory and the CPU more efficiently.

i-j-k: inner loop over k walks DOWN a column of B 8 cache lines for 8 numbers i-k-j: inner loop over j walks ALONG a row of B 1 cache line for 8 numbers Each band is one row of B, contiguous in memory. Measured on an M4 (n = 1024): i-j-k 2.45 GFLOP/s · i-k-j 32.6 GFLOP/s

Figure: why the inner loop order matters. Each band is one row of b, contiguous in memory. Walking down a column touches a new cache line for every number.

2. Tiling Compute c in 64×64 blocks so the working set stays in cache.

3. Let BLAS do it. When you write a @ b in NumPy, you are not running Python. NumPy calls BLAS (Basic Linear Algebra Subprograms), they are another 47× faster than my best loop. They keep a small block of c in registers so that each loaded number feeds many multiply-adds, they pack tiles into contiguous buffers, they use SIMD, and they use every core. Python only makes the call.

python
import numpy as np
import time
 
n = 1024
a, b = np.random.rand(n, n).astype(np.float32), np.random.rand(n, n).astype(np.float32)
 
start = time.perf_counter()
c = a @ b
t = time.perf_counter() - start
print(f"numpy (BLAS) {n}x{n}: {t*1e3:.2f} ms, {2*n**3/t/1e9:.0f} GFLOP/s")
 
# now try the naive python triple loop with n=1024 and see how long you have to wait...

What about Strassen's Algorithm? No one really remembers, it's anyway O(n^2.807) and I don't like to ask algorithmic cramming questions.. because I don't know them.


Q2: given a function that generates a random number between 0 and 1 (uniformly distributed), calculate pi.

first response when I ask this is "what??"

Draw a unit square. Now draw a quarter circle of radius 1 inside it, center at the origin.

The area of the square is 1. The area of the quarter circle will be area of circle divided by 4:: πr2/4=π/4\pi r^2 / 4 = \pi / 4.

Now throw random points at the square. Because points uniformly distributed at random, the the probability of a point landing inside the quarter circle is area of quarter circle / area of square. The point obviously has (x, y) and if x2+y2≤1x^2 + y^2 \le 1, the point landed inside the quarter circle. The fraction of point inside converges to the ratio of the areas, π/4\pi / 4, which is almost 79% which means 79% of points should land inside quarter circle, which means if you throw 1000 points, 790 are inside, 210 on the outside, get the ratio: 3.76.. yo that's close to the number pi.

So π=4×inside/total\pi = 4 \times \text{inside} / \text{total}.

python
import random
 
def estimate_pi(n):
    inside = 0
    for _ in range(n):
        x, y = random.random(), random.random()
        if x**2 + y**2 <= 1:
            inside += 1
    return 4 * inside / n
 
# more darts = better estimate
for n in [100, 1_000, 10_000, 100_000, 1_000_000]:
    print(f"n={n:>10,} -> pi = {estimate_pi(n):.6f}")
011 darts: 25inside: 20π ≈ 4 × 20/25= 3.20 darts: 50inside: 41π ≈ 4 × 41/50= 3.28 darts: 100inside: 77π ≈ 4 × 77/100= 3.08 darts: 200inside: 155π ≈ 4 × 155/200= 3.10 true π = 3.14159… The error shrinks like 1/√n

Figure: 200 random points. The estimate after 25, 50, 100 and 200 darts: 3.2, 3.28, 3.08, 3.1.

Found this problem on my goat's channel Joma Tech


Q3: what happens when you enter www.google.com and press enter?

This was inspired by this repo I read long time ago

If you start from the key press.. #InstantHire

1. The key press. The keyboard controller detects the key, the keyboard sends a USB HID (human interface device) report, the OS turns it into a key event/interrupt, and the browser gets "Enter".

2. The browser reads the address bar. "www.google.com" has no scheme, so the browser decides it is a URL, not a search query, and adds https://. If you type google.com instead, Google answers with a 301 redirect to www.google.com, which costs one more round trip.

3. DNS: name to IP address. The network routes IP addresses, not names. The browser checks its own cache, then the OS cache, then asks a DNS resolver (your router, your ISP or a public resolver). On a miss, the resolver asks a root nameserver, then the .com nameservers, then Google's own nameservers. My lookup took 2 ms because the answer was cached. Each run returned a different IP (142.251.150.119, 142.251.151.119, 142.251.155.119): Google spreads traffic over many front-end servers.

4. TCP: one round trip. SYN, SYN-ACK, ACK. Both sides agree on sequence numbers before any data flows, so TCP can detect and resend lost packets. Acknowledgement is necessary. Connected at 11 ms, so one round trip to Google's server is approximately 9 ms from here.

5. TLS 1.3: one more round trip. The browser sends a ClientHello with its supported ciphers and a key share. The server answers with its key share, its certificate (signed by a certificate authority) and a Finished message. Both sides compute the same secret from the two key shares and everything after this is encrypted with symmetric keys derived from it. TLS was done at 40-63 ms. Basically checking if all packets have arrived.

6. HTTP: the request. GET / over HTTP/2, with headers: cookies, user-agent, accept-encoding. Google's load balancers send it to a server that builds the page. The first byte of the response arrived at 140-189 ms, so most of the time is the server's work and the network, not the handshakes.

7. Rendering. Parse the HTML into a DOM tree and the CSS into a CSSOM. Combine them into a render tree, compute the layout (the position and size of every element), paint pixels, and composite the layers on the GPU. The HTML references more files (JavaScript, images), and the browser fetches them in parallel over the same connection.

browser DNS resolver www.google.com where is www.google.com? 142.251.x.x SYN SYN-ACK ACK ClientHello + key share ServerHello + cert + Finished Finished GET / (HTTP/2) 200 OK + HTML 2 ms (cached) 11 ms 40-63 ms 140-189 ms DNS 1 round trip (to a cache) · TCP 1 · TLS 1.3 1 · HTTP 1 Times: curl from my machine, cumulative from the start, 3 runs Next visit: HTTP/3 over QUIC merges TCP and TLS into one round trip

Figure: one page load as round trips. DNS, TCP and TLS each cost a round trip before the first byte of HTML moves.

The follow-up question: can you skip a round trip? Yes. Google's response includes alt-svc: h3=":443". That header tells the browser that HTTP/3 is available. On the next visit, Chrome uses QUIC over UDP, which merges the transport handshake and the TLS 1.3 handshake into one round trip.

You can see steps 3 to 6 in code:

python
import socket
import ssl
 
# step 1: DNS
ip = socket.getaddrinfo('www.google.com', 443)[0][4][0]
print(f"DNS: www.google.com -> {ip}")
 
# step 2: TCP + TLS
sock = socket.create_connection(('www.google.com', 443))
context = ssl.create_default_context()
ssock = context.wrap_socket(sock, server_hostname='www.google.com')
print(f"TLS: {ssock.version()}")
 
# step 3: raw HTTP request
ssock.sendall(b'GET / HTTP/1.1\r\nHost: www.google.com\r\nConnection: close\r\n\r\n')
response = ssock.recv(512).decode()
print(response[:200])
ssock.close()

You can measure each phase yourself:

bash
curl -s -o /dev/null -w "dns %{time_namelookup} tcp %{time_connect} tls %{time_appconnect} first byte %{time_starttransfer}\n" https://www.google.com/ #dns 0.008278 tcp 0.018217 tls 0.050770 first byte 0.157129

Q4: how does CUDA work? what is Flash Attention?

do you know what happens when you call torch.device("cuda") ?

This is a tricky one to write an "answer" to so I'll start with 3 things: the hardware, the programming, and an example of Flash Attention

the hardware

A GPU is many small processors called streaming multiprocessors (SMs). My RTX 3090 has 82. Each SM runs threads in groups of 32 called warps, and all 32 threads of a warp execute the same instruction at the same time on different data. NVIDIA calls this SIMT (single instruction, multiple threads).

The memory is a hierarchy, from fast and small to slow and large:

  1. Registers, private to each thread.
  2. Shared memory, on the SM and shared by the threads of one block. It holds tens of KB per block.
  3. L2 cache, shared by all SMs.
  4. Global memory (VRAM), the GBs on the card: GDDR on gaming cards, HBM on data-center cards.

Each step down is slower. Fast GPU code keeps its data in the top two levels. You can see a nice diagram of this on Modal

the programming

A kernel is a function that runs one time per thread. You launch a grid of blocks, and each block holds up to 1024 threads. Inside the kernel, blockIdx and threadIdx tell each thread which piece of the work is its own. Same concept we learnt in OS class.. Threads in one block share the block's shared memory and can wait for each other with __syncthreads().

For matmul, the natural mapping is one thread per output element:

python
# CPU: one thread loops over everything sequentially
for i in range(N):
    for j in range(N):
        for k in range(N):
            C[i][j] += A[i][k] * B[k][j]
c
// GPU (CUDA): one thread per output element C[i][j]
__global__ void matmul(float* A, float* B, float* C, int N) {
    int i = blockIdx.y * blockDim.y + threadIdx.y;
    int j = blockIdx.x * blockDim.x + threadIdx.x;
    float sum = 0;
    for (int k = 0; k < N; k++)
        sum += A[i*N + k] * B[k*N + j];
    C[i*N + j] = sum;
}
// launched with <<<grid, block>>>, e.g. 32x32 threads per block

The two outer loops become the thread grid. For N = 4096 that is 16.8 million threads. They don't all run at once: each SM runs as many warps as fit, and the rest wait for a free slot.

grid of blocks → threads block (y=1, x=0) thread (y=1, x=2) → C[5][2] i = blockIdx.y × blockDim.y + threadIdx.y = 1 × 4 + 1 j = blockIdx.x × blockDim.x + threadIdx.x = 0 × 4 + 2 tiled: share loads in a block C block A: row band B: column band 1. load one tile of A and one of B into shared memory2. __syncthreads()3. each thread uses each loaded number 32 times4. move to the next pair of tiles

Figure: left, how block and thread indices pick the output element. Right, the tiled kernel: the threads of one block load tiles of A and B into shared memory and reuse them.

making the kernel fast

The naive kernel reads every number of A and B from global memory again and again: each thread reads 2N numbers to do 2N FLOPs. The fix is the same idea as cache blocking on the CPU. The threads of a block load a 32×32 tile of A and a 32×32 tile of B into shared memory one time, wait at __syncthreads(), and then each loaded number feeds 32 multiply-adds:

c
#define TILE 32
__global__ void tiled(const float* A, const float* B, float* C, int N) {
    __shared__ float As[TILE][TILE], Bs[TILE][TILE];
    int i = blockIdx.y * TILE + threadIdx.y, j = blockIdx.x * TILE + threadIdx.x;
    float s = 0;
    for (int t = 0; t < N; t += TILE) {
        As[threadIdx.y][threadIdx.x] = A[i*N + t + threadIdx.x];    // each thread loads one number
        Bs[threadIdx.y][threadIdx.x] = B[(t + threadIdx.y)*N + j];
        __syncthreads();                                            // wait until the tile is loaded
        for (int k = 0; k < TILE; k++) s += As[threadIdx.y][k] * Bs[k][threadIdx.x];
        __syncthreads();                                            // wait before the next tile overwrites it
    }
    C[i*N + j] = s;
}

I measured both kernels and cuBLAS on an RTX 3090 (N = 4096, float32, TF32 off). All three give the same output:

KernelTimeTFLOP/s
Naive, one thread per output62 ms2.2
Tiled, shared memory44 ms3.1
cuBLAS (torch.matmul)4.9 ms28.3

Flash Attention

Standard attention computes S = QKᵀ, an N×N matrix, writes it to global memory, reads it back for the softmax, writes the result, and reads it again to multiply by V. For N = 4096 in fp16, S is 32 MiB per head, per layer. The math per byte is small, so the GPU waits on memory: attention is memory-bound.

Flash Attention never stores S. It takes one block of queries at a time and streams blocks of K and V through shared memory. The problem is the softmax: it needs the maximum and the sum over the whole row, and the row arrives one tile at a time. The fix is the online softmax. For each query row, keep a running maximum m, a running sum ℓ and a running output O. When a new tile of scores s arrives:

m′=max⁡(m,max⁡(s))ℓ′=ℓ em−m′+∑es−m′O′=O em−m′+es−m′Vtile\begin{aligned} m' &= \max(m, \max(s)) \\ \ell' &= \ell \, e^{m - m'} + \textstyle\sum e^{s - m'} \\ O' &= O \, e^{m - m'} + e^{s - m'} V_{tile} \end{aligned}

At the end, divide O by ℓ. The factor em−m′e^{m - m'} fixes the old partial sums whenever a larger score appears. O(N) extra memory instead of O(N²), and far fewer trips to global memory. This is a little overkill for an interview but it's experience agnostic.. I know some companies that tell you to write Flash Attention from scratch.. God bless them candidates.

standard: S = QKᵀ is N × N written to and read from global memory N = 4096, fp16: 32 MiB per head flash: one Q block at a time K, V tiles stream through shared memory Q block tile 1 of 4: scores for this block only tile 2 of 4: scores for this block only tile 3 of 4: scores for this block only tile 4 of 4: scores for this block only K, V tiles keep per query row:m = running max of scoresℓ = running sum of exp(score − m)O = running weighted sum of V Same exact result. The N × N matrix never exists.

Figure: standard attention materializes the full N×N matrix in global memory. Flash Attention streams K and V tiles through shared memory and keeps only the running max, sum and output for each query row.

It is the same idea for the third time in this post: move the work into fast memory, and reuse every number you load as many times as you can.


Q5: implement a GPT from scratch. no libraries.

I mean.. if you can walk me through this, that also works..

autograd: why it matters

Autograd records every operation of the forward pass in a graph. You call loss.backward(), and it walks the graph in reverse and multiplies the local derivatives. Chain rule.

PyTorch hides this behind one method call (how PyTorch autograd works). MicroGPT does it one scalar at a timeso you can see the gradient of every number.

what is a gradient, practically?

A gradient tells you what a small nudge does. Take a weight with a gradient of 0.5. Increase that weight by a tiny amount, and the loss increases by half that amount. Training nudges every weight in the opposite direction of its gradient, so the loss goes down.

the value class: building the computational graph

The Value class is the whole autograd engine. Each Value wraps one floating-point number and tracks three things:

  1. data, the number itself. The forward pass computes it.
  2. grad, the derivative of the final loss with respect to this number. The backward pass fills it in.
  3. _children and local_grads, the inputs that created this value and the local derivative of the operation with respect to each input.

When you compute a + b or a * b on two Value objects, Python calls __add__ or __mul__. That method creates a new Value, which stores its inputs and the local gradients. For addition, the local gradient with respect to each input is 1.0, because ∂(a+b)/∂a=∂(a+b)/∂b=1\partial(a+b)/\partial a = \partial(a+b)/\partial b = 1. For multiplication, the local gradient with respect to a is b.data, and the local gradient with respect to b is a.data. The reason is ∂(ab)/∂a=b\partial(ab)/\partial a = b and ∂(ab)/∂b=a\partial(ab)/\partial b = a.

These objects make a directed acyclic graph (DAG). Each node is a scalar. Each edge goes from an input to the value it helps compute.

In PyTorch, you write x = torch.randn(10, 10, requires_grad=True). In MicroGPT, the same 10×10 matrix is a list of lists with 100 separate Value objects. A call to backward() visits every addition and multiplication that produced the loss, one scalar at a time.

the chain rule and DAG traversal

For a chain L=f(g(h(w)))L = f(g(h(w))):

dLdw=dLdg⋅dgdh⋅dhdw\frac{dL}{dw} = \frac{dL}{dg} \cdot \frac{dg}{dh} \cdot \frac{dh}{dw}

Each factor is a local gradient. Multiply the local gradients along the path and you get the total.

backward() does two things:

  1. Topological sort. A recursive depth-first search (DFS) appends each node to a list after all of its inputs. So every node comes after the nodes it depends on.
  2. Reverse traversal. The code sets the gradient of the loss to 1.0, because dL/dL=1dL/dL = 1. Then it walks the sorted list backwards. For each node, it adds local_grad * v.grad to the .grad of each input.

The += is important. When a value feeds many operations, its gradient is the sum of the contributions from all of them. Take a w that feeds both a = w * 3 and b = w * 5:

dLdw=3 dLda+5 dLdb\frac{dL}{dw} = 3 \, \frac{dL}{da} + 5 \, \frac{dL}{db}

The MicroGPT post explains the same backward() step by step.

Autograd Value class - scalar computation graph with backward() chain rule, showing L=(a*b)+c example with gradient flow

Every operation builds a DAG node. backward() walks the DAG in reverse and multiplies the local gradients by the chain rule.

forward: each operation creates a node backward: child.grad += local × grad, from e back to a and b a = 3 b = 4 d = 5 c = a × b= 12 e = c + d= 17 grad = 1 (seed) local 1 local 1 grad = 1 × 1 = 1 grad = 1 × 1 = 1 local b = 4 local a = 3 grad = 4 × 1 = 4 grad = 3 × 1 = 3

Figure: the forward pass builds the DAG for e = a × b + d. The backward pass seeds e.grad = 1 and walks the graph in reverse. Each input gets local gradient × output gradient: a.grad = b = 4, b.grad = a = 3.

  • A linear layer. Instead of nn.Linear(16, 16, bias=False), MicroGPT computes one dot product per row of the weight matrix: [sum(wi * xi for wi, xi in zip(wo, x)) for wo in w].
  • The activation. Instead of nn.ReLU(), the Value class has a relu() method. It returns max(0, x) and stores a local gradient of 1 or 0.
  • The normalisation. rmsnorm(x) divides each element of the list by the root mean square of the list. It has no learnable gain.

sequential training and the KV cache

Biggest break from how PyTorch trains.

  • A PyTorch GPT trains on all positions of a sequence in parallel. It takes a [batch, seq_len] tensor and uses a causal mask, a triangle of −∞-\infty scores, to hide future tokens.
  • MicroGPT processes one token at a time (for pos_id in range(n)). It appends the keys and values of each position to a list, the KV cache.

With a 2D causal mask, the scalar Value code would compute the full score matrix and then throw away the masked half. With the cache, position t sees only the keys and values of positions 0 to t, so the model cannot peek ahead. The code is also easier to read.

Multi-head attention - Q,K,V projections split into 4 heads, scaled dot-product attention with KV cache

4 heads × 4 dimensions = 16. Each head attends over the KV cache on its own. The code concatenates the 4 head outputs and multiplies them by Wo.

Adam from scratch

In PyTorch, you call optimizer.step(). MicroGPT implements Adam by hand. For each parameter, it tracks:

  1. m, the first moment. It is a moving average of the gradient (momentum).
  2. v, the second moment. It is a moving average of the squared gradient (uncentered variance).
  3. m_hat and v_hat, the bias-corrected moments. m and v start at 0, so they are too small in the first steps. Division by 1−βt1 - \beta^t removes this bias.

Then it updates param.data directly, with learning rate α\alpha and step tt:

θ←θ−α m^tv^t+ϵ\theta \leftarrow \theta - \alpha \, \frac{\hat{m}_t}{\sqrt{\hat{v}_t} + \epsilon}

Each weight gets its own step size, from the history of its own gradients. The code puts ϵ\epsilon outside the square root, as in Algorithm 1 of the Adam paper. It uses β1=0.85\beta_1 = 0.85 and β2=0.99\beta_2 = 0.99, the values from Karpathy's microgpt.

Training loop - tokenize, forward pass, cross-entropy loss, backward pass, Adam optimizer update, zero gradients

One complete training step: tokenize a name, run gpt(), compute the cross-entropy loss, call backward(), do the Adam update with learning-rate decay, and set the gradients to zero.

the gradient journey

A call to loss.backward() multiplies local derivatives from the loss back to every weight.

Start at the last operation, loss = total_loss / batch_size.

  • backward() sets loss.grad to 1.0.
  • total_loss.grad becomes 1.0 / batch_size, the local gradient of the division.
  • If total_loss = loss1 + loss2, then loss1.grad and loss2.grad both get total_loss.grad, because the derivative of x + y with respect to x is 1.

The same steps continue back to the token embeddings. After loss.backward() and before the Adam update, you can print state_dict['wte'][10][5].grad. It shows how much dimension 5 of the embedding of token 10 (both 0-indexed) changes the loss of the batch, for example a batch with a name like "Andre-j" in it.

numerical stability: the max_logit trick

In the softmax function, you'll see:

python
max_logit = max(l.data for l in logits)
exp_logits = [(logit - max_logit).exp() for logit in logits]

Why? exe^x grows fast. With a logit of 100, e100≈2.7×1043e^{100} \approx 2.7 \times 10^{43}. That overflows float32, whose maximum is about 3.4×10383.4 \times 10^{38}. Python floats are float64, and math.exp raises OverflowError for inputs above about 709.8.

Subtract the maximum first, and the largest term becomes e0=1e^0 = 1. Every other term falls between 0 and 1. Softmax is shift-invariant, so the result does not change:

softmax(x)i=exi∑jexj=exi−c∑jexj−c\mathrm{softmax}(x)_i = \frac{e^{x_i}}{\sum_j e^{x_j}} = \frac{e^{x_i - c}}{\sum_j e^{x_j - c}}

It's a clever trick to stop it from crashing..

embedding + positional encoding

The model adds two learned vectors: the row of wte for the token, and the row of wpe for its position. The original transformer uses fixed sin/cos positional encodings instead.

Embedding and positional encoding - wte token lookup table and wpe position lookup table, element-wise addition

wte (27×16) encodes what the token IS, wpe (16×16) encodes where the token SITS. Both are learnable, no sin/cos here.

MicroGPT GPT Architecture - decoder-only transformer pipeline from token input to next-token prediction

The gpt() function as a pipeline: embedding lookup, RMSNorm, multi-head attention with residual, MLP with residual, lm_head projection, softmax.

the code (200 lines)

If you can code this in an hour even in pseudocode, you probably know the transformer architecture in detail.

python
import math
import random
import urllib.request
 
random.seed(42)
 
names_url = 'https://raw.githubusercontent.com/karpathy/makemore/refs/heads/master/names.txt'
urllib.request.urlretrieve(names_url, 'names.txt')
 
docs = [l.strip() for l in open('names.txt').read().strip().split('\n') if l.strip()]
random.shuffle(docs)
 
print(f"Number of docs: {len(docs)}")
 
# Tokeniser
chars = sorted(set(''.join(docs))) # unique characters in the dataset
BOS = len(chars) # beginning of sequence token
vocab_size = len(chars) + 1 # number of unique characters + 1 for the BOS token
 
print(f"Vocab size: {vocab_size}")
 
# Autograd for DAG of operations
 
class Value:
    def __init__(self, data, _children=(), local_grads = ()):
        self.data = data # the value of this node (scalar (forward pass))
        self.grad = 0 # derivative of loss wrt this node
        self._children = _children # children of this node in the computational graph
        self.local_grads = local_grads # local derivatives of this node wrt its children
 
    def __add__(self, other):
        other = other if isinstance(other, Value) else Value(other)
        out = Value(self.data + other.data, _children=(self, other))
        out.local_grads = (1.0, 1.0)
        return out
 
    def __mul__(self, other):
        other = other if isinstance(other, Value) else Value(other)
        out = Value(self.data * other.data, _children=(self, other))
        out.local_grads = (other.data, self.data)
        return out
 
    def __pow__(self, other):
        assert isinstance(other, (int, float)), "only supporting int/float powers for now"
        return Value(self.data**other, (self,), (other * self.data**(other-1),))
 
    def log(self): return Value(math.log(self.data + 1e-10), (self,), (1/(self.data + 1e-10),))
    def exp(self): return Value(math.exp(self.data), (self,), (math.exp(self.data),))
    def relu(self): return Value(max(0, self.data), (self,), (float(self.data > 0),))
 
    def __neg__(self): return self * -1
    def __radd__(self, other): return self + other
    def __sub__(self, other): return self + (-other)
    def __rsub__(self, other): return other + (-self)
    def __rmul__(self, other): return self * other
    def __truediv__(self, other): return self * other**-1
    def __rtruediv__(self, other): return other * self**-1
    def __lt__(self, other): return self.data < (other.data if isinstance(other, Value) else other)
    def __gt__(self, other): return self.data > (other.data if isinstance(other, Value) else other)
 
    def backward(self):
        topological_graph = []
        visited = set()
        def build_top(v):
            if v not in visited:
                visited.add(v)
                for child in v._children:
                    build_top(child)
                topological_graph.append(v)
 
        build_top(self)
        self.grad = 1 # seed the gradient of the output node with 1.0 (dL/dL = 1)
        for v in reversed(topological_graph):
            for child, local_grad in zip(v._children, v.local_grads):
                child.grad += local_grad * v.grad
 
 
# Initialise the parameters of the model
n_embed = 16
n_head = 4
n_layer = 1
block_size = 16 # maximum context length for predictions
head_dim = n_embed // n_head # dimension of each attention head
 
# Randomly initialise the parameters of the model as Value objects
matrix = lambda rows, cols: [[Value(random.gauss(0, 0.08)) for _ in range(cols)] for _ in range(rows)]
state_dict = {'wte': matrix(vocab_size, n_embed), 'wpe': matrix(block_size, n_embed), 'lm_head': matrix(vocab_size, n_embed)}
 
for i in range(n_layer):
    state_dict[f'blocks.{i}.attn.wq'] = matrix(n_embed, n_embed)
    state_dict[f'blocks.{i}.attn.wk'] = matrix(n_embed, n_embed)
    state_dict[f'blocks.{i}.attn.wv'] = matrix(n_embed, n_embed)
    state_dict[f'blocks.{i}.attn.wo'] = matrix(n_embed, n_embed)
    state_dict[f'blocks.{i}.mlp_fc1'] = matrix(4 * n_embed, n_embed)
    state_dict[f'blocks.{i}.mlp_fc2'] = matrix(n_embed, 4 * n_embed)
 
params = [p for matrix in state_dict.values() for row in matrix for p in row] # flatten the parameters into a single list
print(f"Number of parameters: {len(params)}")
 
# model architecture -> GPT-2 style (RMSNorm instead of LayerNorm, no biases, ReLU instead of GeLU)
 
# Linear layer used for forward pass
def linear(x, w):
    return [sum(wi * xi for wi, xi in zip(wo, x)) for wo in w]
 
# Convert logits to probabilities between 0 and 1 that sum to 1
def softmax(logits):
    max_logit = max(l.data for l in logits)
    exp_logits = [(logit - max_logit).exp() for logit in logits] # subtract max logit for numerical stability
    sum_exp_logits = sum(exp_logits)
    return [exp_logit / sum_exp_logits for exp_logit in exp_logits]
 
# RMSNorm used in the transformer blocks: divide x by its root mean square (no learnable gain)
def rmsnorm(x):
    eps = 1e-8
    mean_square = sum(xi**2 for xi in x) / len(x)
    root_mean_square = (mean_square + eps)**0.5
    return [xi / root_mean_square for xi in x]
 
# Decoder-only transformer architecture
def gpt(token_id, pos_id, keys, values):
    token_embedding = state_dict['wte'][token_id] # get the token embedding for the input token ID
    position_embedding = state_dict['wpe'][pos_id] # get the position embedding for the input position ID
    x = [te + pe for te, pe in zip(token_embedding, position_embedding)] # add the token and position embeddings to get the input representation for the transformer block
    x = rmsnorm(x) # apply RMSNorm to the input representation
    for i in range(n_layer):
        # mha block
        x_residual = x # save the input to the MHA block for the residual connection
        x = rmsnorm(x)
        q = linear(x, state_dict[f'blocks.{i}.attn.wq']) # compute the query vectors for the MHA block
        k = linear(x, state_dict[f'blocks.{i}.attn.wk']) # compute the key vectors for the MHA block
        v = linear(x, state_dict[f'blocks.{i}.attn.wv']) # compute the value vectors for the MHA block
        keys[i].append(k)
        values[i].append(v)
        x_attention = []
        for h in range(n_head):
            hsize = h * head_dim # compute the start index of the current head in the query/key/value vectors
            qh = q[hsize:hsize+head_dim] # get the query vector for the current head
            kh = [ki[hsize:hsize+head_dim] for ki in keys[i]] # get the key vectors for the current head from all previous time steps
            vh = [vi[hsize:hsize+head_dim] for vi in values[i]] # get the value vectors for the current head from all previous time steps
            attention_scores = [sum(qhi * khi for qhi, khi in zip(qh, khj)) / math.sqrt(head_dim) for khj in kh] # compute the attention scores for the current head
            attention_weights = softmax(attention_scores) # compute the attention weights for the current head
            head_output = [sum(aw * vhi for aw, vhi in zip(attention_weights, vhj)) for vhj in zip(*vh)] # compute the output of the current head as a weighted sum of the value vectors
            x_attention.extend(head_output) # concatenate the outputs of all heads to get the output of the MHA block
        x_attention = linear(x_attention, state_dict[f'blocks.{i}.attn.wo']) # apply the output projection to the concatenated head outputs
        x = [a + b for a, b in zip(x_attention, x_residual)] # add the residual connection to get the output of the MHA block
        # mlp block
        x_residual = x # save the input to the MLP block for the residual connection
        x = rmsnorm(x) # apply RMSNorm to the input of the MLP block
        x = linear(x, state_dict[f'blocks.{i}.mlp_fc1']) # apply the first linear layer of the MLP block
        x = [xi.relu() for xi in x] # apply the ReLU activation function to the output of the first linear layer
        x = linear(x, state_dict[f'blocks.{i}.mlp_fc2'])
        x = [a + b for a, b in zip(x, x_residual)] # add the residual connection to get the output of the MLP block
    logits = linear(x, state_dict['lm_head']) # apply the final linear layer to get the logits for the next token prediction
    return logits
 
 
# Adam optimiser
learning_rate, beta1, beta2, eps_adam = 0.01, 0.85, 0.99, 1e-8
m = [0.0] * len(params) # initialize the first moment vector for Adam
v = [0.0] * len(params) # initialize the second moment vector for Adam
 
# Training loop
num_steps = 20
for step in range(num_steps):
    # forward pass
    total_loss = Value(0.0)
 
    batch_size = 8
    for b in range(batch_size):
        # take a document from the dataset and convert it to a list of token IDs (add BOS token at the beginning)
        doc = docs[(step * batch_size + b) % len(docs)]
        tokens = [BOS] + [chars.index(c) for c in doc] + [BOS]
        n = min(block_size, len(tokens) - 1)
 
        keys = [[] for _ in range(n_layer)]
        values = [[] for _ in range(n_layer)]
 
        losses = []
        for pos_id in range(n):
            token_id, target_id = tokens[pos_id], tokens[pos_id + 1]
            logits = gpt(token_id, pos_id, keys, values)
            probs = softmax(logits)
            losses.append(-probs[target_id].log())
        total_loss += sum(losses) / n
 
    loss = total_loss / batch_size
    loss.backward() # compute the gradients of the loss with respect to all parameters in the computational graph (backward pass)
 
    # update the parameters using Adam (optimiser.step())
    learning_rate_target = learning_rate * (1 - step / num_steps) # linearly decay the learning rate toward zero (the last step uses learning_rate / num_steps)
    for i, param in enumerate(params):
        m[i] = beta1 * m[i] + (1 - beta1) * param.grad # update the first moment vector for the current parameter
        v[i] = beta2 * v[i] + (1 - beta2) * param.grad**2 # update the second moment vector for the current parameter
        m_hat = m[i] / (1 - beta1**(step + 1)) # compute the bias-corrected first moment estimate
        v_hat = v[i] / (1 - beta2**(step + 1)) # compute the bias-corrected second moment estimate
        param.data -= learning_rate_target * m_hat / (math.sqrt(v_hat) + eps_adam) # update the parameter using the Adam update rule
        param.grad = 0 # reset the gradient of the parameter to zero for the next iteration
 
    print(f"Step {step + 1}/{num_steps}, Loss: {loss.data:.4f}")
 
# inference (no_grad())
temperature = 0.5 # control creativity of generated text
print("\nGenerated names:")
for _ in range(10):
    keys, values = [[] for _ in range(n_layer)], [[] for _ in range(n_layer)] # reset the list of key and value vectors for each transformer block
    token_id = BOS # start with the BOS token
    generated_name = ''
    for pos_id in range(block_size):
        logits = gpt(token_id, pos_id, keys, values)
        probs = softmax([l / temperature for l in logits])
        token_id = random.choices(range(vocab_size), weights=[p.data for p in probs])[0]
        if token_id == BOS: # stop generating if we sample the BOS token again
            break
        generated_name += chars[token_id] # append the generated character to the name
    print(generated_name)

Run it: with random.seed(42), the loss starts at 3.28, close to ln 27 = 3.30 (a uniform guess over 27 tokens), and falls to 2.68 after 20 steps.

I also sometimes ask silly questions like speed of light, what is 13 in binary etc.. just to check their fluency with these numbers. In general, fluency with computers is what gets you hired, not passion.


reply by email