Neural networks: matrix multiplications that learned to answer
A neural network is not a program with rules like “if the text contains word X, answer Y.” It is a huge set of numbers, called weights, plus a simple computational scheme: multiply, add, pass through a nonlinear function, and repeat layer after layer. Nobody writes the rules: the weights are tuned automatically using examples. Let’s look at how a single neuron works, how a network learns, how a transformer language model works, and why all of this needs a graphics card.
An artificial neuron: a weighted sum
An artificial neuron receives several numbers as input, multiplies each by its own weight, adds up the results, adds an offset (the bias) and passes the sum through an activation function. Example: inputs 0.5, −1, 2; weights 0.8, −0.2, 0.5; bias 0.1. The sum: 0.4 + 0.2 + 1.0 + 0.1 = 1.7. The ReLU function leaves positive numbers as they are and replaces negative ones with zero, so the neuron’s output is 1.7.
A weight says “how important this input is, and in which direction.” A positive weight amplifies the signal, a negative one suppresses it, and one close to zero ignores the input. In the “Neurons” model at this level, green connections are positive weights, red ones are negative, and brightness shows the magnitude.
Why a nonlinear function? Without it, any number of layers collapses into a single matrix multiplication: a composition of linear functions is linear. Nonlinearity (the “kink” of ReLU, or the smooth GELU or SiLU in modern models) lets the network build complex features out of simple ones: contours from changes in brightness, shapes from contours, and “this is a cat” from shapes.
This construction has little in common with a biological neuron beyond the idea of summing signals and a threshold. A real neuron works with impulses over time and is far more complex. For a computer, though, a neuron is a few multiplications and additions, that is, work for the very same adders and multipliers built from transistors that are taken apart at the lower levels of the model.
See also: Adder: how a processor adds numbers
Layers are a matrix-vector multiplication
Neurons are assembled into layers. Each neuron in a layer receives all the outputs of the previous layer. If there are 4096 numbers at the input and 4096 neurons in the layer, each neuron has 4096 weights, and the layer has 4096 × 4096 ≈ 16.8 million. Written out as a table, these weights form a matrix, and computing the whole layer is a single multiplication of the matrix by the input vector: 16.8 million multiply-adds.
If you feed in many examples at once (a batch), the input vectors stack up into a matrix, and the layer becomes a matrix-matrix multiplication. This very operation, GEMM, makes up more than 90% of a neural network’s computation. Each product is independent of the others, so they can be computed on thousands of compute units simultaneously, which is exactly what graphics cards were built for.
A classic example network is handwritten digit recognition (the MNIST dataset). An image is 28 × 28 = 784 brightness values. A hidden layer of 128 neurons (784 × 128 ≈ 100 thousand weights), and an output layer of 10 neurons, one per digit. About 102 thousand parameters in total, and such a network recognizes about 98% of digits. The “Neurons” model at this level shows a network like this in miniature: 8 inputs, two hidden layers, several outputs.
The numbers that a network passes between layers are called activations, and sets of numbers of any dimensionality are called tensors: a vector is a first-order tensor, a matrix is second-order, and a batch of images (count × height × width × colors) is fourth-order. Hence the names TensorFlow and tensor cores.
See also: Graphics card: how an image appears
The forward pass and answer probabilities
The forward pass is the computation of the network from input to output: the input is multiplied by the first layer’s matrix, the activation is applied to the result, that is multiplied by the second layer’s matrix, and so on. The output of the last layer is a set of score numbers (logits), one for each possible answer.
The scores are turned into probabilities by the softmax function: each score is exponentiated and divided by the sum of all the exponentials. The result is positive numbers that add up to one, with large scores becoming noticeably more probable than small ones. For a digit in an image, the network might output: “7” 0.93, “1” 0.05, “9” 0.01.
It’s important to understand that the network doesn’t “see” the image or “read” the text. It receives numbers and outputs numbers. Everything it “knows” is encoded in the weights, and the computation is the same every time: a fixed chain of multiplications and additions. There are no conditionals, no database lookups and no “thinking” in the usual sense.
How much does it cost? A forward pass requires about 2 operations (a multiplication and an addition) per parameter. The digit network takes 200 thousand operations, instantaneous even on a phone. A language model with 8 billion parameters needs about 16 billion operations for every token of the answer.
Training: adjusting the weights based on error
At first the weights are random and the network answers nonsense. Training is the tuning of weights using examples with known answers. For each example, the network does a forward pass, and a loss function measures how bad the answer is: for instance, if the correct digit is “7” but the network gave it a probability of 0.1, the loss will be large (−ln 0.1 ≈ 2.3), and with a probability of 0.9 it will be small (≈ 0.1).
Next you need to figure out how to change each of the millions of weights so that the loss goes down. To do this, you compute the gradient, the derivative of the loss with respect to each weight: “if I increase this weight slightly, will the error go up or down, and by how much?” Take a single neuron y = w · x and the loss (y − t)². With x = 2, w = 0.5 and the correct answer t = 3, the output is y = 1, the error is −2, and the derivative with respect to w = 2 · (−2) · 2 = −8. With a learning rate of 0.01: w = 0.5 − 0.01 · (−8) = 0.58. The new output is 1.16, closer to 3. Repeating this, the weight will converge to 1.5.
For a deep network, the gradients are computed by backpropagation: it runs from the output to the input and, using the chain rule of derivatives, reuses intermediate results, so the gradients of all the weights cost about as much as two forward passes. The weights are updated not after every example but after a batch of hundreds to thousands of examples, and the entire dataset is passed through many times.
Training large models is one of the most expensive computational tasks on Earth. It takes about 6 operations per parameter for every training token: a model with 8 billion parameters trained on 15 trillion tokens amounts to about 7 · 10²³ operations. The largest models of 2024–2025 were trained on tens of thousands of graphics cards for months. Training is also heavier than inference in terms of memory: besides the weights, you need to store the gradients and the state of the Adam optimizer, about 16 bytes per parameter, or 128 GB for an 8-billion-parameter model, plus activations. That’s why the model is split across many graphics cards and servers in a data center.
See also: Data center: where websites live
Tokens and embeddings: how text becomes numbers
A language model works not with letters or whole words but with tokens, common chunks of words. The token vocabulary (usually 100–200 thousand entries) is built in advance by the BPE algorithm: starting from individual bytes, it repeatedly merges the most frequent pairs into new tokens. As a result, a common word like “computer” may be one or two tokens, while a rare word gets split into several pieces. Russian text usually requires more tokens than English text with the same meaning, because vocabularies are built from data in which English predominates.
Each token is just a number. The number is turned into a vector: the embedding table stores a row of thousands of numbers for each token (4096 for the 8-billion-parameter Llama 3 model). The table holds 128,256 × 4096 numbers, about a billion bytes in 16-bit format. At first these vectors are random, and during training, words that occur in similar contexts end up with similar vectors.
In the “Network layers” model at this level, vectors are shown as columns of 8 numbers (blue for negative, orange for positive). In a space of thousands of dimensions, directions start to mean features: “plural,” “related to food,” “negative connotation.” A classic example from early models: vector(“king”) − vector(“man”) + vector(“woman”) ≈ vector(“queen”).
Position information is added to the token vectors; otherwise “the cat ate the mouse” and “the mouse ate the cat” would look the same. Modern models rotate parts of the vectors by an angle that depends on the position number (the RoPE method), and this is how attention learns how far apart tokens are.
Attention: how tokens look at each other
The meaning of a word depends on context: a “key” to a door or a musical key, a “bank” of a river or a bank that holds money. The attention mechanism lets each token gather information from the preceding ones. For each token, three multiplications of its vector by matrices produce three vectors: a query Q (“what I’m looking for”), a key K (“what I can offer”) and a value V (“what I’ll pass along”).
The current token’s query is compared with the keys of all previous tokens by a dot product: the bigger the number, the better the match. The results are divided by the square root of the dimensionality (so the numbers don’t grow too large), passed through softmax, and become the attention weights, which add up to one. Then the values V of all previous tokens are summed using those weights. In the “Network layers” model, the thickness of the arcs is exactly these weights: how much the last token “it” takes from each word.
There are many attention heads: Llama 3 8B has 32, each working with vectors of 128 numbers and learning its own specialty; one tracks grammatical agreement, another tracks whom a pronoun refers to, a third copies repeated fragments. An important detail is the mask: a token sees only previous tokens, not future ones; otherwise, during training, the model would simply peek at the answer.
So that the keys and values of all previous tokens don’t have to be recomputed when generating each new token, they are stored in a KV cache in video memory. For Llama 3 8B this is 32 layers × 8 key-value groups × 128 numbers × 2 (K and V) × 2 bytes ≈ 128 KB for every token of context. A context of 8 thousand tokens takes about 1 GB, and one of 128 thousand takes 16 GB in FP16, comparable to the weights themselves. That’s why long context is expensive, and the “everyone with everyone” comparison grows as the square of the text length.
The transformer block and the whole model
The transformer, an architecture proposed in 2017, consists of identical blocks stacked on top of one another. Each block: normalization → attention → add the result to the input → normalization → perceptron (MLP) → add to the input again. Adding to the input (the residual connection) matters: each block doesn’t rewrite the token’s vector but adds a correction to it, and the signal passes easily through dozens of layers.
The perceptron is two or three large matrices that first expand the token’s vector (in Llama 3 8B from 4096 to 14,336 numbers), apply a nonlinearity and compress it back. This is where most of the parameters, and apparently most of the model’s “knowledge,” are concentrated: facts, patterns, associations. Attention moves information between tokens; the perceptron processes it within each one.
Let’s count Llama 3 8B: 32 blocks, each with attention matrices (about 42 million weights) and perceptron matrices (about 176 million), for a total of ≈ 7 billion, plus the embedding tables at the input and output, ≈ 1 billion. The largest open models contain hundreds of billions of parameters; many use a “mixture of experts” (MoE): each block has many perceptrons, but only a few of them work on each token, so there is less to compute than to store.
After passing through all the blocks, the vector of the last token is multiplied by the output vocabulary matrix, yielding 128 thousand scores, one for each token, and softmax turns them into probabilities. The “Network layers” model shows this entire path on a small example: tokens → vectors → attention → perceptron → probabilities → word choice.
See also: Graphics card: how an image appears
Generating an answer one token at a time
A language model predicts only one thing: the probabilities of the next token. The answer emerges in a loop: pick a token, append it to the text, run the model again, pick the next one. That’s why the answer is “typed out” on the screen in pieces.
Always choosing the most probable token is boring and leads to repetition. Usually the token is chosen randomly, but weighted by the probabilities. Temperature controls the spread: at a temperature below 1 the distribution becomes sharper (answers are more predictable), above 1 it becomes flatter (more varied and riskier). The top-p method discards the “tail” of unlikely options.
Processing your request is split into two phases. First, the entire request (hundreds to thousands of tokens) passes through the model in one go; this is prefill, where matrices are multiplied by large batches and the graphics card is busy computing. Then comes generation one token at a time: each step requires reading all the weights for the sake of a single vector, and the bottleneck becomes memory rather than computation.
This is also the source of one of the main misconceptions. The model doesn’t look up the answer in a database or “recall” a document: it continues the text in a statistically plausible way. If the correct fact is only weakly anchored in the weights, a plausible continuation may turn out to be a fabrication stated in a confident tone. That’s why modern systems connect models to search and tools instead of relying on the weights alone.
Inference on the graphics card: it all comes down to memory
Why do neural networks run on graphics cards rather than on the processor? A processor core performs a few dozen multiply-adds per clock cycle with vector instructions; 16 cores manage about a trillion per second. A graphics card contains tens of thousands of simple compute units and special tensor cores: the gaming RTX 4090 does hundreds of trillions of operations per second in 16-bit format, the server-grade H100 about 1,000 trillion (1 petaflop), and the B200 of 2024–2025 more than 2 petaflops.
But computation isn’t the only limit. A model with 8 billion parameters in 16-bit format takes up 16 GB. To generate one token for one user, all 16 GB of weights have to be read. The RTX 4090 reads its GDDR6X memory at about 1 TB/s, which means no more than roughly 60 tokens per second, even though the compute units sit idle most of the time. The H100 with HBM3 memory does 3.35 TB/s, and the B200 with HBM3e about 8 TB/s.
Hence the two main tricks. Quantization: storing the weights not in 16 bits but in 8 or 4. An 8-billion-parameter model in 4 bits takes about 5 GB, fits on an ordinary graphics card and runs 2–3 times faster with a small loss in quality. Batching: the server processes requests from dozens of users simultaneously, so the weights are read once but multiplied by dozens of vectors. That’s why the cost of an answer in the cloud is lower than at home on your own graphics card.
There is also a capacity limit. A model with 70 billion parameters, 140 GB in 16 bits, won’t fit on any single graphics card, so it is split across several: layers or parts of matrices are stored on different GPUs, and intermediate results are passed over fast NVLink connections (hundreds of GB/s). That’s why AI servers have 8 interconnected graphics cards each, and HBM memory is the industry’s scarcest component.
See also: Graphics card: how an image appears
Tensor cores: a matrix multiplier in silicon
An ordinary graphics card core performs one multiply-add on a pair of numbers per clock cycle. A tensor core multiplies small blocks of matrices in a single instruction. An instruction executed by a group of 32 threads (a warp) multiplies a 16 × 16 block by a 16 × 8 block and adds the result to an accumulator: 2048 multiply-adds at once. The H100 has 132 multiprocessors with 4 tensor cores each, running at about 1.8 GHz, and that’s where the petaflops come from.
Tensor cores work with short number formats: 16-bit FP16 and BF16, 8-bit FP8, and in the newest ones, 4-bit formats. Fewer bits mean fewer transistors per multiplier, less energy and more numbers per memory read. The products, meanwhile, are accumulated in a more precise 32-bit format so that the sum of thousands of terms doesn’t lose accuracy.
The main engineering challenge is feeding in the data. A block of a matrix is copied from video memory into the L2 cache (50 MB on the H100), from there into the multiprocessor’s fast shared memory (up to 228 KB), and from there into the tensor cores’ registers, and each loaded block needs to be used as many times as possible. Libraries such as cuBLAS and FlashAttention are above all the art of laying out data across the levels of memory, the same idea as processor caches.
And at the bottom of every multiply-add is a multiplier circuit made of thousands of gates, plus adders just like the full adder at the Full adder level of the model. A neural network answering a question is trillions of transistor switchings per second, organized into matrix multiplication.