call/text us now

+1 (855) 6-KANERI

LLM Architecture Explained: How Transformers, Attention, MoE and the KV Cache Work
Five colleagues in business attire lean over a table reviewing large architectural plans together, one seated in the center and four standing around him
Table of Contents

LLM Architecture Explained: How Transformers, Attention, MoE and the KV Cache Work

TL;DR

LLM architecture is the set of layers that turns your prompt into a reply. A tokenizer first cuts the text into small pieces called tokens. Attention layers then let each token pick up meaning from the words before it. Mixture-of-experts models send each token to a few small expert networks, which saves compute. A memory store called the KV cache keeps past tokens, so it grows as prompts get longer. For long documents pick a small cache, and for heavy traffic pick fewer active parameters.

Key Takeaways

  • LLM architecture has five working parts: a tokenizer, embeddings, a stack of transformer blocks, an output head and a decoding loop.
  • Prefill reads the whole prompt in parallel and sets time to first token, while decode adds one token at a time and is limited by memory.
  • Grouped-query attention lets Qwen3.8 keep 4 KV heads for 64 query heads, a cache 16x smaller than full multi-head attention would need.
  • Mixture-of-experts models carry two parameter counts: Mistral Large 4 holds 1T weights but activates 52B per token.
  • By our arithmetic, the latent cache of Mistral Large 4 is about 81 KiB per token, or about 81 GiB for one 1,048,576-token request.
  • Quantization, paged KV caches, continuous batching and speculative decoding cut serving cost without changing the model’s design.
Kanerika diagram of how one request moves through LLM architecture: tokenize, embed, 40 to 92 transformer blocks, logits and sample, with prefill marked compute-bound for time to first token and decode marked memory-bound for tokens per second

Reading One Sentence the Way a Model Does

Picture a support ticket landing in a queue at 9:02 on a Monday, just before the team logs in. It reads: “The contract renewed automatically because it had no termination clause. Can you cancel it?” Before an assistant built on a large language model can reply, it has to work out what “it” refers to.

That small act of reading takes several hops, even though it feels instant. First the text is cut into tokens, turned into vectors and passed through dozens of transformer blocks. There, “it” looks back at “contract” and borrows its meaning. Then the model writes the first word of its reply, then the next, until the answer is done.

Each of those hops has a price in GPU memory, latency or dollars. So this guide follows a request through the parts in the order it meets them. The numbers come from the published configs of three current open-weight models.

What Is LLM Architecture?

LLM architecture is the design of a large language model: which layers it has, how they connect and how text flows through them. It decides how much the model can read at once, how fast it answers and how much hardware it needs.

Nearly every current generative model shares the same five-part skeleton. The parts differ in size from model to model, but a request always passes through them in this order.

  1. Tokenizer: splits text into subword pieces and maps each piece to an ID.
  2. Embedding layer: turns each ID into a vector of numbers the network can compute with.
  3. Transformer blocks: a stack of repeating layers, 40 to 92 deep in the models below, where tokens share context.
  4. Output head: scores every entry in the vocabulary as a candidate next token.
  5. Decoding loop: picks one token, appends it and runs the model again until the reply ends.

The rest of this guide opens each part in turn. Where a number appears, it comes from the published config of Qwen3.8, Mistral Large 4 or DeepSeek V4.1-Flash, so you can check it yourself.

Why Transformers Replaced Recurrent Networks

Before 2017, most language models were recurrent neural networks. An RNN reads text one word at a time and carries a running memory forward. Long sentences blur in that memory, and training also cannot run in parallel across the words.

Then the 2017 paper Attention Is All You Need replaced that loop with attention alone. Every token can look at every other token in a single step, which suits GPUs and scales to far longer text. All three models in this guide still use that design, with changes to how attention is shared and stored.

How Does One Request Move Through an LLM?

A request moves through an LLM in two phases, even though both use the same weights. Prefill reads the whole prompt at once, and decode writes the answer one token at a time.

Take the support ticket again, for example. Its prompt of a few hundred tokens goes through every block in one parallel pass. That pass builds the cache that decode reads from, and it ends with the first reply token.

  1. Tokenize: the text becomes a list of token IDs.
  2. Embed: each ID becomes a vector, and position information is applied.
  3. Run the blocks: every block applies attention and then a feed-forward layer, refining each vector.
  4. Score: the output head turns the last vector into a logit, a raw score, for every vocabulary entry.
  5. Sample: the decoder picks a token from those scores, and the loop starts again with that one new token.

Steps 1 to 4 for the full prompt are prefill. Every later pass handles a single new token and is called decode, which is why a long answer takes longer than a long question.

Case Study

80% Ticket Auto-Resolution with LLM-Driven AI

An LLM resolution system built on a software company’s own ticket history now auto-responds to 80% of tickets, with 70% lower staffing cost and 50% faster resolution.

Read the Case Study →

Why LLM Architecture Sets Cost, Speed and Memory

Those two phases explain why the design of a model shows up on the invoice. Three effects follow directly from them, and each one can be measured.

  1. Prefill is compute-bound: its time grows with prompt length and the number of active parameters, and it sets time to first token.
  2. Decode is memory-bound: its speed depends on how fast the GPU can read the weights and the KV cache for each new token.
  3. Memory must hold every weight plus the cache for every open conversation, and that ceiling sets how many users one server carries.

So the same model can feel fast in a demo and slow in production. A demo runs one short prompt, while production runs many long ones at the same time.

Tokenization and Embeddings: How Text Becomes Numbers

A neural network cannot read letters, so the first job is turning text into numbers. Two steps do that: a tokenizer cuts the text into pieces, and an embedding table turns each piece into a vector.

Tokens Are Not Words

A token is a chunk of text from a fixed vocabulary. Common words are usually one token, while rare words, code and numbers often split into several pieces. A product code such as “XQ-4471” can easily cost four or five tokens.

Vocabulary size is also a design trade-off. A larger vocabulary packs more text into each token, which shortens sequences and saves compute. It also makes the embedding table and the output head bigger, since both have one row per entry.

Table 1: Vocabulary size and depth in three current open-weight configs

ModelVocabulary sizeTransformer layers
DeepSeek V4.1-Flash129,28040
Mistral Large 4204,80072
Qwen3.8248,32092

Token counts are also the unit you pay in. The same paragraph can cost a different number of tokens on two models. So compare prices on your own text rather than on a price list alone.

Kanerika Service

Plan a Generative AI Build Around Real Costs

Kanerika plans and builds generative AI applications, from model choice and token-cost sizing to deployment on your own data.

Explore Generative AI Services

Embeddings Turn Token IDs Into Vectors

Each token ID is simply a row number in a large table of learned vectors. Looking up that row gives the model its first view of the token, a long list of numbers that places it near related words.

Training arranges this space so that similar meanings sit close together. “Contract” and “agreement” end up near each other, and later layers adjust each vector to fit its sentence. Our deep learning glossary entry covers how layered networks learn these representations.

Positional Encoding and RoPE

Attention on its own has no sense of order. Without extra help, “the contract renewed” and “renewed the contract” would look alike to it.

Most current models solve this with rotary position embedding, or RoPE. It rotates each query and key vector by an angle tied to its position. Because of that rotation, the score between two tokens depends on how far apart they sit. The idea comes from the RoFormer paper, and adjusting those rotations is a common way to extend a context window.

Inside a Transformer Block, the Core of LLM Architecture

The transformer block is the repeating unit of LLM architecture. Each block does two jobs: an attention sublayer lets tokens exchange information, and a feed-forward sublayer then refines each token on its own.

Stacking blocks is how models gain depth, since every block refines the output of the one before. DeepSeek V4.1-Flash stacks 40 of them, Mistral Large 4 stacks 72 and Qwen3.8 stacks 92, per their config files. The sketch below shows the logic of one block in simplified Python.

def transformer_block(x):
    # x holds one vector per token: shape [tokens, d_model]
    h = x + attention(rms_norm(x))         # tokens share information
    out = h + feed_forward(rms_norm(h))    # each token is refined on its own
    return out

def next_token_scores(token_ids):
    x = embed(token_ids)                   # token IDs become vectors
    for block in blocks:                   # 40 to 92 blocks in current models
        x = transformer_block(x)
    logits = output_head(rms_norm(x))      # one score per vocabulary entry
    return logits[-1]                      # scores for the next token

Real implementations add caching, fused GPU kernels and training details, but the flow is the same.

Feed-Forward Layers Hold Most of the Weights

Attention gets the headlines, yet the feed-forward network is where most of a dense block’s parameters live. It widens each token’s vector several times over, applies a gated activation and narrows it back.

That wide middle layer is where much of the model’s stored knowledge appears to sit. It is also the part that mixture-of-experts designs replace, swapping one large feed-forward layer for many smaller experts.

Residual Connections and Normalization Keep Deep Stacks Stable

Look again at the “x +” in the sketch. That is a residual connection, where each sublayer adds a correction to its input instead of replacing it. As a result, early information flows straight to later layers.

RMSNorm does a related job. It rescales each vector before a sublayer reads it, which keeps numbers stable across 72 or 92 layers. Neither part is glamorous, but deep stacks would not train reliably without them.

Kanerika Service

Build Custom Models Sized to the Job

Kanerika’s AI model development practice builds custom models for specific problems, sized to the workload they serve.

Explore AI Model Development

How Does Self-Attention Work?

Self-attention is the step that lets each token gather context from the tokens around it. It is how “it” in the support ticket finds “contract”. It is also the part of the model that grows most expensive as prompts get longer.

Queries, Keys and Values

Each token’s vector is projected three ways. The query says what the token is looking for, while the key says what it can match. Its value carries the content it passes on when chosen.

The model compares one token’s query with every key using a dot product. A softmax then turns those scores into weights that add up to 1. The token’s new vector is then a weighted blend of the values, so it carries context from the tokens it attended to most.

Models run many of these attention heads side by side, each on its own slice of the vector. One head may track grammar while another tracks which noun a pronoun points to. Qwen3.8, for example, uses 64 query heads in each of its 23 full-attention layers.

A Worked Example: Resolving One Pronoun

Return to the ticket sentence. When the model processes “it”, its query is compared with the keys of the tokens before it and with its own key. The weights below are illustrative, chosen to show the shape of a trained head rather than measured from a real model.

Table 2: Illustrative attention weights for the token “it”

Earlier tokenAttention weightWhat the weight means
contract0.61Most likely referent, so its value dominates the blend
renewed0.12The action the subject took
automatically0.08Modifier, minor context
because0.07Signals that a reason follows
it (itself)0.07Keeps some of its own meaning
The0.05Little information to add

After this step, the vector for “it” carries most of the meaning of “contract”. Later layers can then link “had no termination clause” to the right noun. In a trained model, several heads usually share this work instead of one head doing it alone.

Causal Masking Stops the Model Peeking Ahead

Notice what “it” could not see. The words “termination clause” come after the pronoun, and a generative model may not read ahead, because during generation those words do not exist yet. A causal mask blocks every token from attending to later positions.

The model still resolves the sentence, just a little later. When it reaches “clause”, that token can attend back to both “it” and “contract”. This one-way flow is the defining trait of decoder-only models.

Why Long Prompts Make Attention Expensive

In full attention, every token is scored against every earlier token, so the score matrix grows with the square of the sequence length. Doubling a prompt roughly quadruples that work during prefill.

FlashAttention attacks the cost from the hardware side. It computes exact attention in tiles that stay in fast on-chip memory, so the full score matrix is never written out. The math is unchanged, but long prompts run faster and use less memory. The official FlashAttention repository ships these kernels for recent NVIDIA and AMD GPUs.

Kernel tricks do not change the growth curve, though. To bend that curve, model designers change attention itself, which is what the next section covers.

Kanerika Service

Keep Prompts Short With Better Retrieval

Long prompts raise attention cost and cache memory. Kanerika’s RAG development team builds retrieval that sends the model only the passages it needs.

Explore RAG Development

Attention Variants That Shrink Memory: MQA, GQA, MLA, Sliding-Window, Sparse and Linear

Attention variants are the part of LLM architecture that answers one question: how much does each token have to remember? During decode, every layer stores a key and a value for each past token, and that store is the KV cache.

Classic multi-head attention (MHA) keeps a separate key and value for every head, which is flexible but heavy. So each variant below shares, compresses or skips part of that store to shrink the cache.

Table 3: Attention variants and where current open models use them

VariantWhat it shares or dropsEffect on KV cacheWhere a current open model uses it (config.json)
Multi-head attention (MHA)Nothing; every query head has its own keys and valuesLargest; the baselineReference design of the 2017 transformer
Multi-query attention (MQA)All query heads share one key-value headSmallest of the head-sharing designsDeepSeek V4.1-Flash: 64 query heads, 1 KV head
Grouped-query attention (GQA)Query heads share a few key-value groupsCut by the ratio of query heads to KV headsQwen3.8: 64 query heads, 4 KV heads (16:1)
Latent KV (MLA-style)Keys and values compressed into one small latent vectorStores the latent instead of full keys and valuesMistral Large 4: kv_lora_rank 512 plus 64 RoPE dims
Sliding-windowEach token attends only to recent tokensCapped at the window on those layersDeepSeek V4.1-Flash: sliding_window 128
Sparse or indexedEach token attends to a selected top-k subsetReads less of the cache per stepMistral Large 4: index_topk 2,048; DeepSeek V4.1-Flash: index_topk 512
Linear-attention hybridMost layers keep a fixed-size running stateOnly the full-attention layers grow a cacheQwen3.8: 69 linear plus 23 full layers

How Current Models Share Keys and Values

The GQA paper describes grouped-query attention as a middle ground between multi-query and multi-head attention. You keep most of the quality of separate heads while storing far fewer keys and values.

Qwen3.8 shows how far that sharing can go when pushed. With 4 KV heads serving 64 query heads, its cache is 16x smaller than the same layers would need under full multi-head attention.

The model also mixes layer types. Its config places a full-attention layer at every 4th position and uses linear attention elsewhere. Only 23 of its 92 layers keep a growing cache as a result.

Kanerika matrix of attention variants and their KV cache effect: MHA as the baseline, MQA with 1 KV head in DeepSeek V4.1-Flash, GQA with 4 KV heads for 64 query heads in Qwen3.8 for a 16x smaller cache, latent KV in Mistral Large 4, sliding window, sparse and linear hybrid layers

The sparse rows need a caution. The Mistral and DeepSeek configs list an index top-k, which points to a sparse-attention design; check the model card before relying on it. A config describes the shape of a model, and the runtime behavior still needs a test.

Encoder-Only vs Decoder-Only vs Encoder-Decoder Models

Transformers come in three layouts, and the split is about which way attention may look. An encoder sees the whole input at once in both directions, while a decoder sees only what came before.

That one choice decides what each layout is good at. A model that reads in both directions understands a fixed input well but cannot write freely. A model that reads left to right can keep writing, one token after another.

Table 4: The three transformer layouts

LayoutAttention directionTypical jobExample family
Encoder-onlyBoth directions over the inputClassification, search embeddings, taggingBERT
Encoder-decoderTwo-way encoder plus a causal decoderTranslation, summarization, rewriting an inputT5
Decoder-onlyCausal, left to rightOpen-ended generation, chat, code and agentsGPT and the three models in this guide

BERT, T5 and the early GPT models made these three branches familiar to engineers. The branches still exist, but they now serve very different jobs inside a product.

Why Generative Models Settled on Decoder-Only

Decoder-only models won the generative race for practical reasons. One stack handles every task as next-token prediction, so the same training objective covers chat, code and reasoning. Agents build on the same decoder by adding tools, memory and planning, as our comparison of AI agents vs LLMs explains.

The causal layout also makes the KV cache possible. Past tokens never change once written, so their keys and values can be stored and reused on every later step.

Encoders still matter in production. Embedding models for search and small classifiers are often encoder-only, because the job is to return a vector or a label, not new text.

Kanerika decision diagram for transformer layouts: encoder-only such as BERT when the output is a label or vector, decoder-only such as GPT, Qwen3.8 and Mistral Large 4 for new text, and encoder-decoder such as T5 for a rewritten input

One caution applies to closed models. Vendors such as OpenAI, Anthropic and Google do not publish full layouts for their flagship models. So treat any claim about their internal design as unconfirmed, and judge them on measured behavior instead.

Mixture of Experts: Why Sparse Models Have Two Parameter Counts

A mixture-of-experts (MoE) model replaces each feed-forward layer with many smaller expert networks and a router. For every token, the router picks a few experts, and the rest of the layer stays idle.

That is why MoE models quote two numbers. Total parameters are every weight the model owns, whether or not a token uses them. Active parameters are the weights one token uses, and they set the compute per token.

Table 5: MoE sizes from published figures and configs

ModelTotal parametersActive parametersExperts per layerExperts per token
Qwen3.8-Max2.4T95B (4.0%)51210
Mistral Large 41T52B (5.2%)128 routed plus 1 shared4
DeepSeek V4.1-FlashNot published on the page we readNot published on the page we read384 routed plus 1 shared6

The rule that follows is simple. Memory scales with total parameters, while per-token compute scales with active ones. Mistral Large 4 does roughly the math of a 52B model per token, yet all 1T of its weights must still sit in GPU memory.

A shared expert sees every token and tends to hold common patterns, while routed experts specialize. Load balancing during training keeps the router from sending most tokens to a few favorite experts.

MoE pays off when you serve high volume on enough GPUs to hold the whole model. For a small deployment, a dense model of similar active size can be simpler to run. Our guide to MoE architecture covers routing, load balancing and expert parallelism in more depth.

Kanerika bar chart of mixture-of-experts parameter counts: Qwen3.8-Max with 2.4T total and 95B active parameters, Mistral Large 4 with 1T total and 52B active, showing that total sets GPU memory and active sets compute per token

Context Windows and the KV Cache in LLM Architecture

The context window is how many tokens a model can consider at once, prompt and answer together. The KV cache is the memory that makes a long window usable, and it is often the real limit on serving cost.

What Sets the Context Window

A window is set by training, position encoding and the memory budget of the serving stack. As of November 2026, 1M-class windows are common at the top of the market.

  • Claude Opus 5.5, Sonnet 5.5 and Haiku 5.5: 1M tokens.
  • GPT-6.1 Sol: 1,050,000 tokens.
  • Gemini 4 Argon: up to 1M tokens.
  • DeepSeek V4.1-Flash: 1M tokens.
  • Mistral Large 4: Mistral’s pages do not state a served window, but its config allows 1,048,576 positions.
  • Grok 4.7: 500,000 tokens.
  • Qwen3.8: 262,144 native positions in its config, while hosted Qwen3.8-Max allows 1M by default.

A Bigger Window Is Not Better Recall

A model that accepts 1M tokens does not use all of them equally well. The Lost in the Middle study found that models recall information best when it sits at the start or end of the context.

Facts buried in the middle are the ones most likely to be missed. In delivery work we test retrieval placement against this effect before trusting a long prompt, and placing the most relevant passages first usually helps. Our guide to context engineering covers these patterns.

A Worked KV Cache Calculation

The cache size per token follows straight from the config. For standard or grouped attention it is the formula below, with 2 bytes per value for BF16 storage.

kv_bytes_per_token = 2 * layers_with_kv * kv_heads * head_dim * bytes_per_value

# Qwen3.8: 23 full-attention layers, 4 KV heads, head_dim 256, BF16
2 * 23 * 4 * 256 * 2         = 94,208 bytes   (92 KiB per token)
92 KiB * 262,144 tokens      = 23.0 GiB per full-length request
if all 92 layers were full   = 92.0 GiB per full-length request

# Mistral Large 4: latent KV, 72 layers, (512 + 64) values per layer, BF16
(512 + 64) * 72 * 2          = 82,944 bytes   (81 KiB per token)
81 KiB * 1,048,576 tokens    = 81.0 GiB per full-length request

These figures are by our arithmetic from the published config.json files, assuming BF16. The factor of 2 also covers one key and one value. The latent design stores one compressed vector plus a small RoPE part per layer, so it has no separate key and value.

This is a simple count over all 72 layers. The config shows 9 layers reuse another layer’s cache, and a sparse indexer keeps its own small key cache. The two roughly cancel out, so treat 81 KiB as an estimate.

Kanerika bar chart of KV cache per request at BF16: Qwen3.8 with all 92 layers full at 92.0 GiB and its hybrid 23-layer layout at 23.0 GiB for 262,144 tokens, and Mistral Large 4 latent KV at 81.0 GiB for 1,048,576 tokens

Table 6: KV cache per request, by our arithmetic

Model and layoutCache per tokenContext usedCache per request
Qwen3.8, hybrid (23 full layers)92 KiB262,144 tokens23.0 GiB
Qwen3.8 if all 92 layers were full368 KiB262,144 tokens92.0 GiB
Mistral Large 4, latent KV81 KiB1,048,576 tokens81.0 GiB

Two lessons stand out when you compare the rows. Qwen3.8’s hybrid layout cuts its cache 4x at the same context length. Mistral’s latent cache holds a window four times longer in less memory than an all-full Qwen3.8 would need.

Now set the cache next to the weights, because both compete for the same GPU memory. Every open long conversation adds its own cache, so ten users at full Qwen3.8 length would need 230 GiB for caches alone.

That is why serving teams size the cache before they order GPUs. The KV head count and attention type in a config are two of the most useful numbers an engineer can read.

How Training Fills an LLM Architecture With Knowledge

An LLM architecture is the empty building, and training then furnishes it. The same layout can become a weak or a strong model depending on the data and the stages it goes through.

  1. Pretraining: the model reads a very large text corpus and learns to predict the next token. This stage builds language, facts and most general skill, and it uses the most compute.
  2. Supervised fine-tuning (SFT): curated prompt and answer pairs teach the model to follow instructions and use a chat format.
  3. Preference tuning: methods such as RLHF and DPO push the model toward answers people rate higher, such as clearer or safer replies.
  4. Reasoning reinforcement learning: the model is rewarded for correct answers on checkable tasks such as math and code, which teaches it to work through longer chains of steps.

Enterprises rarely touch the first stage, because it costs the most. Our LLM training guide walks through all four stages. For adapting a model cheaply, parameter-efficient fine-tuning trains only a small set of extra weights.

The practical question is whether to fine-tune a model on your data or retrieve that data at query time. A simple rule holds in most projects: fine-tune for a new behavior, format or tone, and retrieve for facts that change. The trade-offs are laid out in our comparison of RAG vs fine-tuning.

Kanerika Service

Size and Deploy the Right LLM for Your Workload

Kanerika’s LLM development team shortlists models, decides between fine-tuning and retrieval, sizes weights and KV cache for your traffic, and deploys with monitoring.

Explore LLM Development

Inference Optimizations That Change the Bill

Inference optimizations change how a model runs without changing its LLM architecture. They are where serving teams win back much of the cost that the architecture sets.

Quantization and Paged KV Caches

Quantization is usually the first lever. Storing weights at 8 bits instead of 16 halves weight memory, and 4-bit formats halve it again. Mistral Large 4 has FP8 and NVFP4 checkpoints on Hugging Face. DeepSeek V4.1-Flash ships FP8 weights with its experts stored in FP4, per its config. NVIDIA introduced NVFP4, a 4-bit floating point format, with its Blackwell GPUs.

Serving engines such as vLLM then handle much of the rest. PagedAttention stores the KV cache in fixed-size blocks, like pages in an operating system, which cuts fragmentation waste to near zero. Continuous batching then adds new requests to a running batch as soon as others finish.

Table 7: Inference techniques and their trade-offs

TechniqueWhat it savesTrade-off
Quantization (FP8, 4-bit)Weight memory and memory bandwidthPossible quality loss, so test on your own tasks
PagedAttentionKV cache memory lost to fragmentationNeeds a serving engine that supports it
Continuous batchingIdle GPU time between requestsPer-request latency can rise under heavy load
Speculative decodingDecode time per tokenNeeds a draft model and spare compute
Tensor parallelismFits one model across several GPUs in a nodeNeeds a fast interconnect between GPUs
Pipeline parallelismSpreads layers across GPUs or nodesAdds idle bubbles and some latency

Watch on YouTube

What Does It Take to Deploy an Enterprise LLM?

Kanerika’s team talks through what it takes to move an enterprise LLM from a pilot into production.

Speculative Decoding and Parallelism

Speculative decoding works around the memory-bound decode phase. A small draft model proposes several tokens, and the large model checks them in one pass, keeping the ones it agrees with. The output matches what the large model would have written alone. The paper’s Google Research authors report using it in products such as AI Overviews in Search.

Parallelism mainly exists to fit a model that is too big for one GPU. Tensor parallelism splits each layer’s matrices across the GPUs in one server, so every token touches all of them. Pipeline parallelism gives each GPU a slice of the layers, which suits models too large for one node.

A 1T-parameter MoE model shows why both matter. Its experts can be spread across GPUs with expert parallelism, while its attention layers use tensor parallelism. The serving engine then has to balance the two.

Order matters when you pull these levers. Quantize first if the weights do not fit, add paged caching and continuous batching for throughput, and try speculative decoding last for latency.

Choosing a Serving Engine

Picking an engine matters as much as picking a technique, because each saving in Table 7 only counts if the engine supports it. Check four things: paged KV caches, continuous batching, speculative decoding and the model’s own attention variant, such as latent or hybrid attention. For example, the vLLM speculative decoding guide lists draft-model, n-gram and EAGLE methods.

Our comparisons of vLLM vs Ollama and SGLang vs vLLM cover the main open-source servers. AI inference vs training explains why serving and training need different hardware plans.

For teams that run several models on shared GPUs, our guide to virtual large language models goes deeper on serving at scale. It picks up where this section stops, with scheduling and memory sharing across models.

Where the Model Sits in a Production System

The LLM architecture is only one box in a larger system. In production, a request usually passes through four other layers before and after it reaches the weights.

  1. Gateway: an LLM gateway routes requests across models, applies rate limits and falls back when a provider fails.
  2. Retrieval: retrieval-augmented generation pulls relevant passages from a store and adds them to the prompt. Our vector database comparison covers the storage choices.
  3. Guardrails: input and output checks block prompt injection, leaked personal data and off-policy answers.
  4. Observability: LLM observability tracks latency, token spend, errors and answer quality for each request.

Each layer adds latency of its own, so measure end-to-end time to first token instead of the model’s figure alone. A gateway hop, a retrieval query and two guardrail checks all run before the first reply token appears.

Retrieval also changes the architecture math. Every retrieved passage lands in the prompt, so it raises prefill cost and the KV cache for that request. A few tight passages cost less than many loose ones, and the lost-in-the-middle effect suggests they are easier for the model to use. Our RAG pipeline guide walks through the chunking and reranking stages that keep them tight.

Evaluation and security sit across all four layers, because a model change can shift quality and risk at once. The full stack, from data to user interface, is mapped in our generative AI architecture guide.

Kanerika Service

Keep Production LLMs Running Reliably

Every layer around the model needs watching once real traffic arrives. Kanerika’s MLOps consulting team keeps models running reliably in production.

Explore MLOps Consulting

What LLM Architecture Means for Enterprise Model Selection

Model selection goes better when you start from the workload instead of a leaderboard. Each workload stresses a different part of the architecture, so the trait worth checking changes too.

Table 8: Matching workloads to architecture traits

WorkloadArchitecture trait that mattersWhat to check
Long-document Q&AContext window and cache per tokenKV heads, latent or hybrid attention, and recall at your real document length
High-volume classificationActive parameters and latencyWhether small language models clear your accuracy bar
Multimodal intakeNative image and document inputImage token cost and accuracy on your scans, as covered in multimodal AI
Self-hosted open-weightTotal parameters, license and quantized checkpointsGPU memory for weights plus cache, from DeepSeek’s open-weight models to other open-source LLMs and private LLMs
Latency-critical chatTime to first token and decode speedPrefill cost of your system prompt and tokens per second under load

Checklist

Generative AI Checklist

Before you commit to a model, check data readiness, security, governance and evaluation across every layer around it.

Get the Checklist →

Price follows the same logic, since every token passes through the same parts. As of November 2026, GPT-6.1 Sol and Gemini 4 Argon both list $2 per 1M input tokens and $10 per 1M output tokens. Argon’s list price rises to $4 and $20 on December 1, 2026, the same rate Claude Opus 5.5 lists.

Latency Comes From Two Different Places

Time to first token (TTFT) comes from prefill, so it grows with prompt length and active parameters. A long system prompt slows every reply before the model writes a word.

Tokens per second comes from decode, so it tracks memory bandwidth, batch size and cache size. A chat product needs both numbers measured separately, under the load you expect.

Memory Is Weights Plus Cache

GPU memory has to hold two things: the weights and the cache for every open request. First, weights scale with total parameters times bytes per value. By our arithmetic, the 1T weights of Mistral Large 4 need about 2 TB at BF16 and about 1 TB at FP8.

The cache then scales with users, context length and cache per token. Size both before you pick hardware, and leave headroom for batching. If the totals will not fit the budget, our comparison of SLMs vs LLMs covers when a smaller model is the better trade.

Where LLM Architecture Is Heading

The direction of LLM architecture is easy to read from the configs above: spend less memory per token and less compute per answer. Five threads show where designers are pushing next.

  1. Sparse attention: index-based top-k selection, as listed in the Mistral Large 4 and DeepSeek V4.1-Flash configs, reads only part of a long context per step.
  2. Hybrid stacks: Qwen3.8 mixes 69 linear-attention layers with 23 full ones, so most layers keep a fixed-size state instead of a growing cache.
  3. State space models: Mamba showed that selective state spaces can model sequences in linear time, and hybrid designs pair such layers with attention.
  4. Native multimodality: models trained on text, images and audio together, a shift covered in our guide to multimodal models.
  5. Reasoning-time compute: models spend more decode tokens working through a problem before they answer, which moves cost from training toward inference.

Reasoning-time compute deserves a closer look, because it moves the bill to a new place. A model that works through a few thousand tokens before answering pays decode cost on each of them. Those tokens also fill the KV cache. Budget for output tokens as carefully as input tokens when a reasoning model joins the stack.

Each thread pulls on the same lever. The cache and the decode loop are the expensive parts, so that is where designers keep cutting.

For engineers, the habit to build is simple. When a new model ships, open its config before its benchmark chart, and the cost story is usually there in plain numbers.

How Kanerika Helps Enterprises Put the Right LLM Architecture to Work

Kanerika helps enterprises match LLM architecture to real workloads, from the first sizing sheet to a monitored production system. Our LLM development services cover model selection, retrieval, fine-tuning and deployment, and our AI application development team extends that work to full applications.

Kanerika is an OpenAI Select Partner and is certified in the Claude Partner Network. That lets our teams compare closed APIs and open-weight models on the same workload instead of defaulting to one vendor.

The support ticket at the top of this guide has a real counterpart. A software company serving small and mid-sized businesses in over 40 countries kept losing staff time to repeat tickets. Customers skipped the manuals, so the same questions kept arriving.

Kanerika built a knowledge base, prepared the company’s historical tickets for machine learning, and put an LLM-driven resolution system in front of the queue. The results were 80% of tickets answered automatically, 70% lower staffing cost and 50% faster resolution.

How an Engagement Runs

We scope LLM engagements in five stages that follow the order of this guide. How deep each stage goes depends on the workload.

  1. Workload profiling: context length, request volume, latency target and data residency.
  2. Architecture shortlist: dense or MoE, attention variant, context window, and closed API or open weights.
  3. Memory and cost sizing: weights plus KV cache arithmetic like the worked example above.
  4. Evaluation: tests on the client’s own documents, scored with metrics from our LLM evaluation framework, comparing accuracy, latency and cost per task side by side.
  5. Deployment: a gateway, monitoring and fallback models from the first release, plus guardrails tuned to the client’s own policies.

Two Kanerika products also sit around the model. FLIP, Kanerika’s intelligent workflow automation platform, has a DataOps use case that automates data pipelines for faster delivery. KARL is a data insights agent that analyzes data and delivers quick insights.

KARL has a retrieval result of its own. An investment bank deployed KlarityIQ and Karl for chat-based document and database retrieval, and its document retrieval time fell 43%.

FLIP matters here because retrieval quality starts with the pipelines that feed it. A model with a well-sized architecture still answers badly if the documents behind it are stale, duplicated or split in the wrong places.

Habits From Delivery Work

Sizing comes before vendor talks for a reason. A workload with long prompts and few users needs a different server than one with short prompts and many users, even on the same model. The cache sizing, retrieval placement and config checks earlier in this guide are how we tell which one a client has.

Talk to Kanerika

Talk to Kanerika About Your LLM Architecture

Bring your workload, context length and traffic, and we will help you shortlist models and size the hardware in a short working session.

Book a Meeting →

Wrapping Up

LLM architecture comes down to a few parts doing heavy work. Tokens become vectors, attention blends context, feed-forward layers or experts transform it, and the KV cache carries it forward one token at a time.

When you read a model through those parts, its costs stop being a surprise. Grouped or latent attention keeps the cache small, MoE trades memory for cheaper compute, and a long window only helps if recall holds. That is how transformers, attention, MoE and the KV cache work, and why each one shows up on the bill.

Frequently Asked Questions

What is LLM architecture?

LLM architecture is the internal design of a large language model. It covers the tokenizer, the embedding layer, the stack of transformer blocks, the output head and the loop that writes one token at a time. These choices set how much text the model reads at once, how fast it replies and how much GPU memory it needs.

What are the main components of an LLM?

An LLM has five main parts. A tokenizer turns text into token IDs, and an embedding layer turns those IDs into vectors. A stack of transformer blocks mixes context through attention and feed-forward layers. An output head scores every possible next token, and a decoding loop picks one token and repeats until the reply is complete.

What is the difference between LLM architecture and RAG architecture?

LLM architecture describes the inside of one model, including its tokenizer, transformer blocks, attention and cache. RAG architecture describes a system around the model. It retrieves relevant passages from a document store at query time and adds them to the prompt. A RAG system can use any LLM, and the retrieved text raises that model’s prefill cost.

What is the difference between prefill and decode?

Prefill is the first phase of a request, when the model processes the whole prompt in one parallel pass and builds the KV cache. It is compute-bound and sets time to first token. Decode follows and generates one token per pass. It is memory-bound, so memory bandwidth sets how many tokens per second the user sees.

How much GPU memory does it take to run an LLM?

GPU memory must hold the weights plus the KV cache for every open request. Weights equal total parameters times bytes per value, so by our arithmetic Mistral Large 4 needs about 2 TB at BF16 and about 1 TB at FP8. The cache comes on top, reaching about 81 GiB by our estimate for one 1,048,576-token Mistral Large 4 request.

Are state space models replacing transformers?

State space models such as Mamba process sequences in linear time and keep a fixed-size state, which makes very long inputs cheaper to handle. They mostly appear inside hybrid designs that mix them with attention layers. Qwen3.8 follows a related idea with linear attention, using 69 linear layers and 23 full-attention layers in its 92-layer stack.

What is the difference between a transformer and an LLM?

A transformer is a neural network design built on attention, introduced in a 2017 paper. An LLM is a large model trained on huge amounts of text, and almost every current LLM uses a decoder-only transformer at its core. The transformer is the blueprint, and the LLM is one very large model built from it.

Why do most generative LLMs use a decoder-only architecture?

Decoder-only models treat every task as next-token prediction, so one training objective covers chat, code, summaries and reasoning. Their causal attention reads only earlier tokens, which lets the model store past keys and values in a KV cache and reuse them on every step. That makes generation faster and keeps the design simple to scale.

How does self-attention work in an LLM?

Each token is projected into a query, a key and a value. The model compares one token’s query with the keys of earlier tokens, turns the scores into weights with a softmax and blends the matching values. The result is a new vector that carries context, which is how a pronoun picks up the meaning of its noun.

What is the difference between dense and mixture-of-experts LLMs?

A dense model uses every weight for every token. A mixture-of-experts model splits its feed-forward layers into many experts and routes each token to a few of them. Mistral Large 4, for example, has 1T total parameters and 52B active ones. Memory follows the total count, and compute per token follows the active count.

What is a KV cache in an LLM?

A KV cache stores the key and value vectors of every token the model has already processed. During generation, each new token reads this cache so the model can skip recomputing the past. The cache grows with context length, and by our arithmetic one 262,144-token Qwen3.8 request needs 23.0 GiB of it at BF16.

Does a larger context window make an LLM more accurate?

A larger window lets a model accept more text, and accuracy depends on where facts sit inside it. The Lost in the Middle study found that models use facts best at the start or end of a prompt. Long prompts also raise prefill time and cache size, so put the most relevant passages first and trim the rest.

What is grouped-query attention?

Grouped-query attention lets several query heads share one set of keys and values. It sits between multi-head attention, where every head keeps its own keys and values, and multi-query attention, where all heads share one set. Qwen3.8 uses 64 query heads and 4 KV heads, which makes its KV cache 16 times smaller than full multi-head attention.

How does LLM architecture affect enterprise cost?

Architecture sets three cost drivers. Active parameters set compute per token, total parameters set the memory needed for weights, and the attention design sets the KV cache per user. Together they decide how many requests one GPU server can carry. Checking these numbers in a model’s config.json before buying hardware avoids oversized or undersized deployments.

Authored by

Author Profile Picture

Gaurav Verma | Chief Marketing Officer

Gaurav Verma brings 25+ years of B2B SaaS marketing expertise, helping brands sharpen positioning, build demand, and drive measurable growth in competitive markets.

View Profile ⇒

Reviewed by

Reviewer Profile Picture

Amit Jena | Lead - AI/ML

Amit leads Kanerika's AI team, bringing expertise in machine learning, NLP, deep learning, and predictive analytics to help clients implement AI and extract value from their data.

View Profile ⇒

Let’s Transform Your Business

get started today

Your Free Resource is Just a Click Away!