Understanding How Large Language Models Work: A Computational Breakdown

    This article explains the mechanics of large language models from a computational perspective, treating the model as a deterministic computing device. It follows a single sentence from text to vectors, detailing the tensor shapes, memory access behavior, and bottlenecks at each stage: tokenization, embedding lookup, attention and feed-forward layers, and output sampling. Readers will learn why inference is often memory-bandwidth bound rather than compute bound, how sequence length drives quadratic attention costs, and how to estimate capacity requirements for weights, KV cache, and activations.

    Understanding How Large Language Models Work: A Computational Breakdown

    Many people understand large models only as something that can chat or write code, yet they cannot explain what operations a single prompt actually becomes inside the machine. This article takes a different angle: treat the model as a deterministic computing device, follow one sentence through the first half of its journey from characters to vectors, and lay out the tensor shapes, memory access behavior, and sources of bottlenecks at every step. The example sentence is a plain one: “Big fat fish, do you like eating plain rice?”

    1. Why You Must Understand the Computation First

    In engineering, whether a model can be deployed does not depend on the parameter count alone, but on a combination of three quantities: the parameter count sets the lower bound of GPU memory, the activation volume determines how large a batch you can run, and the memory access volume sets the upper limit of single-card throughput. During inference, most operators are memory-access bound, which means the compute units on the chip are often waiting for data rather than waiting for compute power. Without understanding this, you end up confused by a situation where “GPU utilization is very low but latency is already high.”

    So for each step below, I will note two things: what shape of tensor this step produces, and whether its bottleneck is compute or bandwidth.

    2. Step One: Tokenization, Turning Text into a Sequence of Integers

    The tokenizer has to do three things: preprocess the text (normalize case, handle whitespace and special characters, strip invalid bytes), split it into a number of tokens according to vocabulary rules, and map each token to an integer ID in the vocabulary. The “how many tokens were consumed” you hear about all the time uses the unit of measurement that comes from here.

    The mainstream approach is a merge algorithm like byte pair encoding. What it stores is not words, but merge rules, in a form like:

    1. big + fat -> big fat
    2. big fat + fish -> big fat fish
    3. like + to -> like to
    4. big + white -> big white
    5. white + rice -> white rice

    During inference, it repeatedly merges according to the rules until no more merges are possible, then looks up the ID sequence. When building the merge table, use a min-heap with greedy selection, taking out the currently best adjacent pair each time.

    1. # Illustration: building merge rules based on a priority queue (skeleton of the algorithm only)
    2. import heapq
    3. from collections import Counter
    4. def build_merges(corpus, num_merges):
    5. seqs = [list(w) for w in corpus]
    6. pairs = Counter()
    7. for s in seqs:
    8. for a, b in zip(s, s[1:]):
    9. pairs[(a, b)] += 1
    10. heap = [(-c, p) for p, c in pairs.items()]
    11. heapq.heapify(heap)
    12. merges = []
    13. while len(merges) < num_merges and heap:
    14. _, (a, b) = heapq.heappop(heap)
    15. merges.append((a, b))
    16. # A real implementation needs to incrementally update the counts of affected adjacent pairs
    17. return merges

    The computation in this step is almost negligible in the whole pipeline. It is pure string and hash operations on the CPU, and the real cost is the linear scan over extremely long text. What is more worth attention in engineering is the “length amplification effect” it brings: one Chinese character is often split into one or even multiple tokens, and the token count directly determines the first dimension of all subsequent tensors.

    3. Step Two: Word Embedding, the Real Starting Point of Numerical Computation

    Note a common misconception: the input to the network is not the word IDs, but the vectors looked up from the IDs. Word embedding is a weight table with shape [vocab size, hidden dim]. Suppose the vocabulary is on the order of a hundred thousand and the hidden dimension is two thousand; this table is about two hundred million parameters, roughly a few hundred MB when stored in half precision.

    1. # Illustration: embedding lookup
    2. hidden = embedding_weight[token_ids] # [seq_len] -> [seq_len, hidden]

    Someone will ask: what do those two thousand numbers each represent? The answer is that no one can name them precisely. They are a high-dimensional semantic representation shaped by backpropagation during training; a few dimensions may happen to be weakly correlated with concepts like “animal” or “plant,” but overall it is a distributed encoding that humans cannot interpret dimension by dimension. What you need to firmly remember is that this table is also weights, updated along with training, not a static dictionary.

    The bottleneck in this step is bandwidth, not compute. It is a gather operation with random memory access, hitting few rows but moving a large amount of data each time, so in a single-card scenario it almost immediately saturates the GPU memory bandwidth. A direct consequence is that with a small batch, the embedding lookup may take up a considerable share of the time, which is why industrial implementations often fuse the embedding with subsequent operators, or use wider vectorized memory access to reduce the number of transactions.

    4. Step Three: Attention and Feed-Forward, How Shapes Change Along the Way

    After embedding, the data enters a stacked structure repeated several layers, where each layer contains an attention sub-layer and a feed-forward sub-layer, each with normalization and residuals. Describing it with shapes is the most intuitive; let the sequence length be S and the hidden dimension be H:

    1. Input [S, H]
    2. Q/K/V projection [S, H] x [H, H] -> three [S, H]
    3. Scoring [S, H] x [H, S] -> [S, S]
    4. Weighted sum [S, S] x [S, H] -> [S, H]
    5. FFN up-projection [S, H] x [H, 4H] -> [S, 4H]
    6. FFN down-projection [S, 4H] x [4H, H] -> [S, H]

    Two key conclusions are hidden in the shapes. First, the attention matrix is S by S; if the sequence doubles, the computation for this part becomes four times, and the cost of long context grows quadratically. This is the fundamental motivation behind various sparse and linear attention schemes. Second, the feed-forward layer accounts for the bulk of the parameters and must be run completely for every token, so it is the main consumer of weight bandwidth.

    Inference also has two phases: the prefill phase that processes the input prompt is compute bound, with large matrix multiplications and high parallelism; the decode phase that emits tokens one by one computes only one token per step, yet the weights must be read completely each time, which is a typical bandwidth-bound case. This explains why “the first token is slow and the rest are fast,” and it also explains why batching can significantly improve overall throughput—multiple requests share the same weight read.

    5. Wrapping Up and Capacity Estimation from a Quantitative Perspective

    The last step is output projection plus sampling: map [S, H] to the vocabulary dimension to get logits, then select the next token according to strategies like temperature and top-k sampling, then append it back to the input and repeat the loop.

    Stringing the whole pipeline together, capacity estimation can be done roughly: weight memory is approximately the parameter count multiplied by the bytes per parameter, the KV cache grows linearly with sequence length and concurrency, and the activation volume is proportional to the batch size. In deployment, you typically first build the foundation on a platform like Baidu AI Cloud using general-purpose capabilities—a container platform to host the inference service, object storage for models and data, and log services with monitoring and alerting for observability—then work backward from measured throughput and latency data to determine instance specifications.

    In one sentence: large models are not mysterious; they are a layered pipeline made of tokenization, lookup, matrix multiplication, and sampling. Once you understand the tensor shape and bottleneck property of each step, you have a quantifiable ruler that tells you whether to scale compute, scale bandwidth, or change the model structure.