Qwen4 Architecture Preview: Deconstructing the Evolution of LLM Design

    This article examines how large language model architecture is shifting from scaling parameters toward spending compute more intelligently, using Qwen3.8-Flash-Next as a preview of where Qwen4 may be heading. It breaks down four core changes layer by layer: sparse attention (a 3:1 mix of Gated DeltaNet linear attention and QSA-indexed global attention), a four-branch gated residual replacing the single-path Pre-Norm design, an N-gram Embedding memory bank inserted at layer 2, and a Muon + AdamW hybrid optimizer. For each change it explains the problem being solved, the trade-offs and costs involved, and the engineering checks required, closing with practical guidance on evaluating and adopting sparse architectures.

    Introduction: From “Bigger” to “Computing Smarter”

    Over the past two years, the main thread in large language models has shifted from simply scaling up parameters to “trading smarter sparse mechanisms for lower per-token cost.” As total parameter counts keep climbing, growth in pre-training compute has steadily slowed, and the overhead of dense Transformers in long-context scenarios has become increasingly prominent. The KV Cache grows linearly with sequence length, attention computation grows quadratically, and activation memory during training is a hard-to-avoid bottleneck. A common judgment is this: the next generation’s competitiveness depends not only on how many parameters a model has, but on how many of them each token actually touches, how much history it consults, and how long the residual path it travels is.

    Qwen3.8-Flash-Next is one sample evolving along this line of thinking. It keeps 125B total parameters while activating only 6B, and attaches a 51B N-gram Embedding knowledge base. Following the convention of using Qwen3-Next as a preview, this is likely a window into the direction of the Qwen4 architecture. So what did this generation change, and how should each change be understood? Let me unpack it layer by layer.

    1. Overall Picture: Decoupling Parameter Scale from “Working Parameters”

    First, the parameter ledger:

    Component Parameter Scale Role
    MoE backbone 125B total, 6B activated per token Routed experts, carrying general capability
    N-gram Embedding knowledge base 51B (not counted in the backbone) External memory, enriching long-tail facts
    Knowledge base trigger rate (assumed value, set to T triggers per word) At least 2T × 6B Lookup cost, rising as the vocabulary grows

    The gap between “total parameters” and “activated parameters” exceeds 20×, and behind it lie two design intents:

    1. Decoupling knowledge density from compute: Sparse routing lets capacity grow with total parameters, while a single token only bears a small fraction of the computation. Many parameters can thus remain “dormant.”
    2. Memory and bandwidth become the new bottleneck: The larger the total parameters, the greater the pressure on weight-resident memory and read bandwidth. The more concentrated the routing hits, the more uneven the load under expert parallelism, and tail experts stretch the wait time for the whole batch.

    Layering on the 51B embedding table, the question becomes: when the backbone compute is constrained and memory costs stay high, where does the next-generation architecture “squeeze out” performance? These changes revolve roughly around four things:

    • How to compute: Linear attention as the base, sparse global attention to fill in retrieval;
    • How to pass information: Residuals upgraded from a single channel to multi-branch gated channels;
    • How to remember: Parameterized memory embeddings supplementing factual knowledge;
    • How to train: A matrix-preconditioned optimizer combined with an adaptive optimizer to reduce training cost.

    2. Attention Evolution: From Dense Gated Attention to Sparse Attention

    2.1 Hybrid Linear Attention: Continuing the 3:1 Division

    The signature design of the Qwen3.5 series is the mixture of linear attention GDN (Gated DeltaNet) and global attention. Qwen3.8-Flash-Next continues the 3:1 ratio of “linear as primary, global as secondary.” The two mechanisms have clear division of labor:

    • Gated DeltaNet: A linear state update with a forgetting gate. It uses a continuously compressing, continuously forgetting state matrix to summarize all history, with computation growing roughly linearly with sequence length, responsible for passing historical information at low cost.
    • Global attention: Every layer can directly look back at the raw tokens, filling in the precise retrieval that limited-state memory is bad at—things like coreference, excerpts, and local rewriting.

    An analogy:

    GDN is like a continuously revised set of reading notes. It is concise and easy to flip through, but may lose the details of the original text; global attention is like going back to the original book to verify page by page.

    Stacked alternately at 3:1, they correspond neatly to the division between compression and verification. The mixture of linear and global attention is also an industry-recognized long-context approach. A few things to watch in practice:

    • Mixture ratio: The ratio determines the cost curve. The more global layers, the closer long-sequence cost approaches quadratic growth; the fewer global layers, the more easily precise retrieval capability is compromised.
    • State capacity: GDN’s compression ability is constrained by the size of the state matrix. Too small a state loses detail; too large weakens the linear advantage.
    • Inference cache: Linear layers only need to cache a fixed-size state, while global layers need the full KV Cache. The inference memory composition of a hybrid architecture is therefore more complex than that of a pure-attention model.

    2.2 Global Layer Modification: QSA with 4:1 Microblock Sparsification and Indexing

    The key change happens in the global layers: Qwen3.8-Flash-Next changes the traditional “GDN + full Gated Attention” into “GDN + QSA sparse attention.” To understand the value of QSA, first look clearly at two costs of global attention in long-context scenarios:

    • Compute: For a sequence length of L, the attention part costs about O(L²);
    • Memory: The KV Cache is about 2 × L × H × d, where H is the number of KV heads and d is the head dimension.

    Taking H=8, d=128, and FP16 as an example, every 1024 tokens occupy about 2 MiB, and a 128K context is 256 MiB—not counting the stacking from multiple requests and multiple replicas.

    Following the line of sparse attention research (such as the route combining a Lightning Indexer with MLA in related work), QSA introduces a lightweight indexer: it first scores historical tokens, then lets the main attention compute only the most important part. The indexer itself can be very short and low-dimensional. Taking the configuration of an open-source approach as an example, the number of index heads is 1/4 of the main attention heads, each index head has dimension 128, and the whole accounts for about 2.8% of the main attention. The trade-off given by related research is: the indexer spends about 3% extra compute in exchange for considerable speedup in long context.

    Its core logic expressed in pseudocode:

    1. def qsa_attention(q, k, v, index_q, index_k, block_size=4, topk_blocks=512):
    2. # q: [B, H, L, d] main attention Query; index_*: low-dim index Query/Key
    3. B, H, L, d = q.shape
    4. pad = (-L) % block_size
    5. index_k_pad = F.pad(index_k, (0, 0, 0, pad))
    6. # Average-pool every block_size index Keys into one microblock; #blocks shrinks to 1/4
    7. index_k_blocks = index_k_pad.view(B, -1, L // block_size + (pad > 0), block_size).mean(-2)
    8. # Each Query scores all historical microblocks -> [B, H, L, num_blocks]
    9. index_score = (index_q @ index_k_blocks.transpose(-1, -2)) ** 2
    10. # Causal mask: the position of the first token in a block must be <= the current query position
    11. causal = block_starts[None, None, :] <= torch.arange(L, device=q.device)[:, None]
    12. index_score = index_score.masked_fill(~causal, float("-inf"))
    13. topk_idx = index_score.topk(topk_blocks, dim=-1).indices # [B, H, L, k]
    14. # Main attention reads only the selected KV
    15. # gather k/v, then restore token-level scores by block_size to get a blockwise causal mask
    16. ...

    QSA’s gains can be broken down as follows. Let the global layers of full length number N in total:

    • The naive approach’s attention compute is N × a × L²;
    • After switching to QSA, the main attention part drops to N × a × L × k (k being the number of selected blocks), and the indexing part is about N × a × L² / 16 × c. Here 16 comes from the quadratic reduction brought by 4× pooling, and c is the overhead ratio of index heads relative to main attention heads.

    Plugging in c ≈ 0.028 from the earlier example:

    • Critical length: When N × a × L × (1 − c/16) = L², the two are equal in compute, and L is about 0.93 × N × a, i.e., roughly equal to the total number of heads across global layers. Taking N=12, a=32 as an example, the critical length is about 360 tokens, beyond which QSA is always more compute-efficient;
    • Crossover point: QSA’s total overhead (indexing + sparse main attention) is N × a × L × (k + cL/16). When L is greater than 16k/(1−c) ≈ 16.5k, QSA’s overhead is actually lower than the naive linearization approach (replacing full attention with an approximately linear kernel).

    On the inference side, a two-level selection of “4 fine blocks + 1 coarse block” can be used: first use coarse blocks to quickly locate the approximate range, then use fine blocks to pick the precise positions. Ablation results show that coarse-granularity selection can be removed, while the combination of “fine-grained + coarse-grained” brings a consistent small improvement over fine-grained alone. This suggests a practical principle: the gains from sparse indexing come from “hierarchical filtering,” not simply shrinking block granularity.

    Three things need focused verification in engineering practice:

    1. Index quality: Whether it can stably cover tasks that rely on precise recall, such as “needle in a haystack,” long-document summarization, and multi-hop retrieval;
    2. Block-level causality: Pooling must span block boundaries, ensuring that any Query’s candidate set contains only blocks “whose position is not greater than its own.” Otherwise the mismatch between training and inference masks will directly harm generation quality;
    3. Training-inference consistency: If training always uses sparse attention but inference falls back to dense, distribution shift will significantly affect results. A common compromise is to mix sparse and dense by ratio in the later stage of training—for example, 9 sparse layers + 3 dense layers—so the model always sees some dense context.

    3. Residual Structure: From Single-Path Pre-Norm to Four-Branch Gated Residual

    3.1 Limitations of the Single-Path Residual

    The residual pathway of a traditional Transformer can be abstracted as:

    1. # Pre-Norm single-path residual
    2. x = x + attn(norm(x))
    3. x = x + ffn(norm(x))

    Its characteristic is: each layer’s sublayer output can only flow into the next layer along a unique additive channel, and the sublayer lacks explicit control over “how it influences the trunk representation.”

    3.2 Four-Branch Gated Residual

    Qwen3.8-Flash-Next changes this into a four-branch Gated Residual, roughly abstractable as:

    1. # Illustrative: four-branch gated residual (only to explain the idea)
    2. def gated_residual_block(x, outputs, norm, gate_proj):
    3. normed = norm(x)
    4. outs = [sub(normed) for sub in outputs] # e.g., attention, FFN and other submodules
    5. # Each branch's "gate-open" weight is determined by the input, then aggregated back to the trunk
    6. gates = gate_proj(normed).view(B, T, 4, 1).softmax(dim=-2)
    7. return x + (gates * torch.stack(outs, dim=-2)).sum(dim=-2)

    Its value lies in:

    • Upgrading from a single information channel to multi-branch cross-layer information channels: Different submodules’ outputs can each write into the trunk in the form of a “gate,” rather than competing in the same additive channel;
    • Gating brings dynamic routing: With different inputs, the weights of each branch also differ. The model can call on demand—simple tokens take a “lightweight path,” complex tokens take a “heavy path”;
    • Unified with the gating idea of MoE: The trunk is full of “score first, then weight” structures, and sparse decisions happen both within and across layers.

    The costs are equally clear:

    • Initialization must be stable: The initial gating values should be as “unbiased” as possible, avoiding a few branches overwhelming the rest right at the start and causing the training to collapse to a single path early on;
    • Interpretability gets worse: Gradients are distributed across multiple paths, and analyzing training behavior requires simultaneously monitoring the distribution of each branch’s gate values;
    • Validation must be layered: Parameters, memory, and throughput must be looked at together, to avoid one branch’s actual utilization being far lower than expected.

    4. Memory Capacity: Layer 2’s N-gram Embedding

    Qwen3.8-Flash-Next inserts a single-layer N-gram Embedding in the shallow layer (layer 2). It generates N-gram keys at three granularities t=1, 2, 3 for each input token (merging into a t=3 key for three consecutive tokens), then maps each to a low-dimensional embedding (each n=3 embedding, while the address encoder is higher, e.g., 4096 dimensions), and after fusion, writes back into the trunk through a linear layer. These keys total 51B parameters in all.

    Based on the experience of the Qwen3.5 series, when the bucket count for t=2 and t=3 is on the order of 2^20, the 2-gram collision rate is about 2% and the 3-gram about 4%, lower than the expected collision rate of ordinary hashing, and its empirical advantage may partly come from this. It should be emphasized that these numbers are the author’s estimates based on general hashing logic, not measured values.

    The flow abstracted in code:

    1. def add_ngram_memory(hidden_states, token_ids, num_buckets=2**20, embed_dim=3):
    2. """
    3. hidden_states: [B, T, D] backbone hidden states
    4. token_ids: [B, T] input token sequence
    5. returns: hidden states after fusing memory
    6. """
    7. # 1. Build n=1/2/3 keys: the n-gram encoder needs no extra params, essentially "take window + hash"
    8. keys = ngram_encoder(token_ids, num_buckets) # [B, T, 3], each column is a bucket id
    9. # 2. Lookup: key2emb[0] is [V, D], key2emb[1] is [N1, d], key2emb[2] is [N2, d]
    10. e1 = key2emb[0][token_ids] # single-token embedding
    11. e2 = key2emb[1][keys[:, :, 1]] # bigram embedding
    12. e3 = key2emb[2][keys[:, :, 2]] # trigram embedding
    13. # 3. Fuse, then linearly map back to trunk dimension, written additively into layer 2
    14. memory = fuse(torch.stack([e1, e2, e3], dim=-2)).mean(dim=-2)
    15. return hidden_states + proj(memory)

    The design intent of this mechanism is very clear:

    • Writing knowledge “into parameters” rather than “into computation”: N-gram keys map local context fragments directly to embedding parameters, equivalent to attaching a differentiable “phrase dictionary” to the model without adding backbone FLOPs;
    • Shallow placement has its rationale: Layer 2 is close to the input side, where token representations are still relatively “raw,” and matching of local fragments (terms, names, code snippets, domain fixed collocations) is more reliable. Injecting knowledge upfront also lets subsequent layers reason on more “informed” representations;
    • Memory overhead must be accounted for: Estimating with t=3, num_buckets=2^20, embed_dim=3, the bigram and trigram embedding tables alone amount to about 6 × 10^9 parameters (about 12% of 51B). The conventional approach first maps integer IDs to a vocabulary-sized table, then uses low-rank weights to save memory; here the number of N-gram buckets far exceeds the vocabulary, so direct mapping is actually more economical. 51B parameters in FP16 are about 100 GiB, requiring trade-offs among parameter sharding, host memory offloading, and high-speed interconnect;
    • Lookup cost cannot be ignored: Let the vocabulary size be V and the batch be B. The N-gram table’s read amplification factor is about B / V × (1 + N1/V + N2/V). When B=V, the read volume is about twice the embedding table itself. If this layer accounts for 5%–10% of the backbone compute, lookup bandwidth could become the new bottleneck;
    • Point of contention: Whether the 51B embedding “counts as parameters” has always been debated. From the perspective of training and memory usage, it must be counted; from the perspective of the computation graph, it indeed consumes no backbone FLOPs. When evaluating a model, reporting only “total parameters / activated parameters” without reporting “embedding parameters” can easily mislead cost estimates.

    5. Training Side: The Muon + AdamW Hybrid Optimizer

    Qwen3.8-Flash-Next switches the optimizer from AdamW to a combination of Muon + AdamW, again “applying strategy by structural layer”:

    • Muon handles 2D matrix parameters: It first performs an orthogonalization on the momentum matrix (approximate via Newton–Schulz iterations), then multiplies back by the learning rate. Intuitively, orthogonalization makes the singular value distribution of the update more uniform, equivalent to “flattening” the step size across directions, avoiding a few directions eating most of the update;
    • AdamW handles the remaining parameters: 1D parameters (biases, LayerNorm scaling), embeddings, and the output layer are still handled by AdamW.

    Illustrative code:

    1. def muon_update(param, buf, lr=0.02, momentum=0.95, ns_steps=5):
    2. buf.mul_(momentum).add_(param.grad) # momentum accumulation
    3. g = buf / buf.norm().add_(1e-7) # normalize to avoid scale dependence
    4. a, b, c = (3.4445, -4.7750, 2.0315) # Newton–Schulz five-step iteration coefficients
    5. X = g
    6. for _ in range(ns_steps):
    7. A = X @ X.T
    8. B = b * A + c * A @ A
    9. X = a * X + B @ X
    10. param.add_(X, alpha=-lr) # update: move along the orthogonalized direction
    11. # Classification: 2D matrices -> Muon; others (1D params, embeddings, etc.) -> AdamW
    12. for name, p in model.named_parameters():
    13. if p.ndim == 2 and "embed" not in name and "head" not in name:
    14. opt_group = muon_group
    15. else:
    16. opt_group = adamw_group

    In engineering, watch:

    • Memory overhead: Muon’s momentum buffer is of the same order as the parameter count, and the extra matrix multiplications of the Newton–Schulz iterations bring compute overhead, so it is usually enabled only on some layers;
    • Distributed strategy: Muon’s update is essentially matrix operations, naturally suited to the sharding scheme of tensor parallelism. If parameters are split by row/column, orthogonalization holds approximately on local shards, which can significantly reduce communication volume;
    • Tuning: Muon’s sensitivity to learning rate scale and iteration steps differs from AdamW, so when migrating hyperparameters you need to re-run a small-scale sweep;
    • Explanation at the principle level: A plain intuition is that the effective update directions of matrix parameters should “cover all singular directions” as much as possible. If the gradient is dominated by a few directions, the parameters actually only wander in a low-dimensional subspace. Orthogonalization “flattens” the update directions, hoping to cover more directions in the same number of steps. This is only an intuitive explanation and cannot replace empirical evidence.

    6. Overall Judgment: What to Watch in This “Next-Generation Architecture”

    Looking at the four changes together, the main thread of Qwen3.8-Flash-Next is very clear: without significantly increasing the per-token compute, hand capacity, memory, and optimization efficiency to more suitable mechanisms respectively. Concretely, it can be summarized in five points:

    1. Attention: global layers change from “compute everything” to “select first, then compute.” QSA’s 4:1 microblock pooling compresses the indexer’s cost to 1/16 of the original (by compute), making global layers cost-effective again under long context;
    2. Residual: from single-channel addition to four-branch gating. Using dynamic weights in place of a fixed identity mapping improves the ability of “information scheduling” across layers;
    3. Memory: treating parameters as a knowledge base. Using N-gram Embedding to decouple “memory capacity” from the computation graph is an engineering practice of “parameters as knowledge”;
    4. Training: using a matrix-preconditioned optimizer in place of a general adaptive optimizer. Competing for better convergence quality under the same training budget;
    5. Mixture ratios and layered placement remain the core experience. The 3:1 linear/global ratio and placing the memory embedding at layer 2 both show that the next-generation architecture is not “piling on new modules” but “placing new modules in the right positions.”

    Practical takeaways for developers and enterprises:

    • When evaluating a model, don’t look only at total parameters or activated parameters: Factor embedding parameters, indexer overhead, KV Cache usage, and lookup bandwidth into the cost accounting;
    • When adopting sparse architectures, prioritize verifying the “quality of sparse decisions” over the “sparsity rate”: The cost of the indexer picking the wrong positions is far higher than computing a few extra blocks;
    • If you consider deploying such models in the cloud, you will typically use general capabilities such as object storage, container platforms, monitoring and alerting, and logging services. For example, use object storage to host weights and embedding tables, use a container platform to carry inference services, and use monitoring and alerting to track abnormal fluctuations in memory and throughput;
    • If you want to reuse these ideas in your own model, it is recommended to proceed in the order of “quantify first, attribute next, then modify”:
      1. First quantify the bottleneck: attention share, KV Cache usage, routing imbalance;
      2. Then attribute layer by layer;
      3. Finally, introduce sparse attention, gated residuals, or memory embeddings in a targeted way, while retaining an ablation baseline.

    Conclusion: The significance of Qwen3.8-Flash-Next lies not in any single-point innovation, but in how it strings “linear + sparse + memory + gated + matrix optimization” into a coherent next-generation roadmap. For engineering practitioners, the most important thing is not to memorize these terms, but to understand what problem each change is solving and what cost it pays. This is the key to truly reading and understanding the “next-generation architecture.”