← Andrei Vogulkin Β· all writing

πŸ€– Agentic shootout β€” Atlas Γ— Flash-Next research

Each config drove an identical LangGraph ReAct agent (tools: list_dir, read_file, search_code over the Atlas-Inf/atlas Rust codebase β€” 1,770 .rs files β€” plus a Flash-Next architecture reference) to produce a gap analysis: what Atlas must adopt to support Qwen3.8-Flash-Next (qwen4exp). No token budget; wrap-up nudge after ~100 messages; no-think; temp 0.3. Same hardware/configs as the tower-defense shootout. 2026-08-30.

Results

ConfigWallLLM stepsTool callsInput tokOutput tokPrefill tok/sDecode tok/sAgent tok/s†ReportGrade*
P (prod 27B)17.7 min57 (hit cap)792.10M16.6K720.6~4915.7 truncated β€” table cut mid-row; plan/risks lost6/10
E2 (FN Q3)13.4 min41 (self-stopped)651.42M5.3K475.0~206.6 truncated β€” overview only4/10
A (FN Q4)13.4 min36 (self-stopped)661.23M6.8K465.7~198.4 complete β€” 14.2 KB, all 4 sections8.5/10

†Agent tok/s = output tokens Γ· total wall time β€” the effective end-to-end agent speed, dragged down by re-prefilling the growing history every step (this is why it is far below decode speed, and why prefill throughput matters most for agentic work). Prefill is the server-side measured rate on long file-embedded prompts; decode from the tower-defense long-generation rounds on the same servers.

*Graded against the ground-truth qwen4exp feature list (llama.cpp PR #27742): coverage of the 9 required features, evidence quality, plan actionability, report completeness. A wins: complete, deep (found the in-tree kernels/gb10/qwen3.8-27b precedent, identified the sparse-attention indexer as the one real kernel gap, named concrete risk classes) β€” though it entirely missed the 51B n-gram PLE table, conflating "n-gram" with n-gram speculative drafting. P had the best raw research coverage β€” the only one to verify PLE is missing (grep: 0 hits) and to flag the shared-expert gating question β€” but never self-terminated (researched to the step cap) and its report was cut. E2 stopped earliest and delivered the least.

Findings worth keeping

1) Prefill dominates agentic work: each ReAct step re-feeds the growing history β€” 1.2–2.4M input tokens per run. Prod's 720 tok/s prefill gave it a 3.4Γ— wall-clock edge at equal steps in run 1.
2) No model self-terminates without pressure: with no budget, all three researched until the 170-step cap in run 1. A wrap-up nudge fixed it β€” and the 125B configs heeded it better (36–41 steps) than the 27B (cap again).
3) Template-token collision: P's and E2's reports quoted literal <think> / </tool_call> while describing Atlas's chat templates β€” llama.cpp's template parser intercepted them and swallowed the rest of the message. A real hazard for agents that write about chat templates on llama.cpp-served models.

Reports (verbatim)

A β€” Flash-Next Q4 (complete, 14.2 KB) β€” grade 8.5/10

Atlas x Qwen3.8-Flash-Next: gap analysis

(a) Overview of Atlas's current architecture

Atlas is a single-GPU-first, Rust inference engine organized around a registry-driven model factory and a model-agnostic runtime:

Notably, the repo already carries a kernels/gb10/qwen3.8-27b/ target whose MODEL.toml documents a dense sibling of the same architecture family (GDN + full attention + MRoPE-interleaved + gated attention, mrope_section=[11,11,10], partial_rotary_factor=0.25), reusing kernel_source = "qwen3.6-27b" β€” strong evidence that much of the Flash-Next feature surface is already exercised in-tree.

(b) Feature-by-feature gap table

Flash-Next featureAtlas statusEvidence file(s)
model_type = qwen4exp registrationNot present β€” factory bails on unknown types; closest arms are qwen3_next, qwen3_5/3_6_moe, holo3_1_moecrates/spark-model/src/factory.rs (loader_for_config), crates/atlas-core/src/config/dispatch.rs
Hybrid GDN + full-attention layer layoutPresent, mature β€” LayerType/layer_types, full GDN decode/prefill (FLA chunked, WY, reg-resident), conv1d+L2-norm, gated RMSNorm, per-layer state (SsmLayerState)crates/atlas-core/src/config.rs, crates/spark-model/src/layers/qwen3_ssm/mod.rs, kernels/gb10/common/gated_delta_rule*.cu, crates/spark-model/src/layer.rs
Gated Q output (attn_output_gate)Present β€” attn_gated flag drives 2Γ— q_proj sizing, TP sharding, LoRA shapescrates/atlas-core/src/config.rs:333, crates/spark-runtime/src/buffers/sizes.rs, crates/spark-model/src/tp_shard.rs
Partial RoPE (factor 0.25) + YaRN variantsPresent β€” partial_rotary_factor, full YaRN parameter set, rope_yarn kernelscrates/atlas-core/src/config.rs:52,285-309, kernels/gb10/common/rope.cu
MRoPE-interleaved [11,11,10]Present β€” mrope_section, mrope_interleaved, dedicated kernel; documented on qwen3.6/3.8 targetscrates/atlas-core/src/config.rs:338-347, kernels/gb10/common/rope_mrope_interleaved.cu, kernels/gb10/qwen3.8-27b/MODEL.toml
MoE: sigmoid routing + correction bias (noaux_tc), shared expert with sigmoid gate, routed scalingPresent β€” moe_topk_sigmoid (≀512 experts, ≀top-32), moe_topk_sqrtsoftplus (V4), shared-expert gate, routed_scaling_factor; K2/K3/grouped/token-major/EP kernelskernels/gb10/common/moe_topk_sigmoid.cu, crates/spark-model/src/layers/ops/moe_gate.rs, crates/spark-model/src/layers/moe/{mod,forward,init}.rs
Per-layer heterogeneous MoE (intermediate size / top-k)Present β€” moe_intermediate_sizes, num_experts_per_toks (Puzzle)crates/atlas-core/src/config.rs:200-208
MTP speculative decoding (multi-module)Present β€” mtp_num_hidden_layers, single/multi MTP heads, verify pipeline, --speculative/--num-draftscrates/spark-model/src/layers/mtp_{head,multi}.rs, crates/spark-server/src/cli/serve_args.rs:504-527
N-gram / self-speculative draftingPresent β€” --ngram-speculative, --self-speculative, DFlash draftercrates/spark-server/src/ngram.rs, crates/spark-server/src/cli/serve_args.rs, crates/spark-model/src/layers/dflash_head.rs
Paged KV + FP8/NVFP4 KV, prefix cache, sliding windowPresent β€” paged decode kernels across KV dtypes, radix prefix cache, sliding-window attentioncrates/spark-runtime/src/kv_cache.rs, prefix_cache.rs, radix_tree.rs, kernels/gb10/common/paged_decode_attn*.cu
GDN recurrent-state management for prefix cache / branchingPresent β€” SSM snapshot/restore, async checkpoint, pool-slot remap on prefix reusecrates/spark-model/src/model/ssm_snapshot.rs, model/trait_impl/async_chkpt.rs, sequence.rs
Quantization: NVFP4, FP8 block/per-row, MXFP4-E8M0, GGUF Q2/Q4, mixed-precision exemption listsPresent β€” QuantFormat dispatcher, ignore-lists, per-row FP8 prefill arm (the exact case flagged for Qwen3.8-27B-NVFP4's mixed FP8/NVFP4 config)crates/spark-model/src/quant_format/, config/parsers/quantization.rs, layers/qwen3_ssm/mod.rs (qkvz_fp8w_rowwise), kernels/gb10/qwen3.8-27b/MODEL.toml:9-30
Vision tower / multimodal (if Flash-Next ships vision_config)Present β€” Qwen3-VL loader + vision/video preprocess; MRoPE interleaved already wiredcrates/spark-model/src/weight_loader/qwen3_vl.rs, vision_preprocess.rs, video_preprocess.rs
Thinking mode / chat templatePresent β€” enable_thinking, thinking budgets, jinja templates per family (qwen3_5_moe.jinja); a Flash-Next template file likely neededcrates/spark-server/src/openai/chat_request.rs, jinja-templates/, kernels/gb10/qwen3.8-27b/MODEL.toml sampling presets
Semantic-indexer top-k sparse attention (index_n_heads/index_head_dim/index_topk)Config fields exist; kernel/forward path NOT found β€” V4's CSA/HCA path implements windowed softmax-gated compression (csa_compress) but no learned indexer selecting top-k compressed blocks; comments explicitly call the indexer "a no-op"crates/atlas-core/src/config.rs:272-280, crates/spark-model/src/layers/qwen3_attention/prefill/cache_skip_v4.rs:414-417 (repo-wide grep for indexer finds only config + comments)
**N-gram drafting combined with MTP** (Flash-Next's recommended hybrid drafting, if that is the reference recipe)Partially β€” both mechanisms exist but appear mutually exclusive per CLI validation grouping; needs verification of combinabilitycrates/spark-server/src/cli/serve_args.rs:504-527, validate.rs:217-230
CPU/RAM weight streaming for oversized MoE (single-box)Partial β€” RDMA expert-tier peer paging exists (expert_peer.rs), but no local mmap-backed on-demand expert streaming found in spark-runtime/src/weights/crates/spark-storage/src/expert_tier_rdma.rs, spark-runtime/src/weights/loader.rs
qwen4exp-specific config parser (new fields, e.g. updated GDN gate form, new rope scheme)Not present β€” no parsers/qwen4exp.rs; unknown fields silently default, which risks wrong numericscrates/atlas-core/src/config/parsers/

(c) Prioritized adoption plan

  1. 1. P0 β€” Config parsing & registration for qwen4exp (Complexity: Low–Medium).

Add config/parsers/qwen4exp.rs (clone the qwen3.5/3.6 dispatch path in config/dispatch.rs), set attn_gated, mrope_section/interleaved, partial_rotary_factor, layer-type layout, MoE routing kind; add the "qwen4exp" arm in factory.rs::loader_for_config. Reuse Qwen35WeightLoader/Qwen35DenseWeightLoader if tensor names match (the qwen3.8-27b precedent shows name-level identity across 3.6/3.8).

  1. 2. P0 β€” Weight loader validation + quant-format routing (Complexity: Low if names match, Medium otherwise).

Verify checkpoint tensor names against the qwen35 loader arms (weight_loader/qwen35/load_layers/attention_arms.rs, qwen35_dense.rs); route mixed FP8-channel + NVFP4 configs through the existing QuantFormat dispatcher and the per-row-FP8 prefill arm; document any double-quantization (per-row FP8 β†’ BF16 β†’ NVFP4) exactly as done for qwen3.8-27b.

  1. 3. P1 β€” Semantic-indexer sparse attention (if enabled by the checkpoint's index_topk > 0) (Complexity: High).

Atlas has the compressed-KV pool infrastructure (V4 csa_compress, FP8 compressed-block persistence) but no indexer: needs indexer projections (q/index weights), a top-k selection kernel over compressed blocks, gather-based attention over selected blocks in both prefill and decode, and pool bookkeeping in kv_cache/prefix cache. This is the single largest genuine kernel gap.

  1. 4. P1 β€” MoE routing-kind selection (Complexity: Low–Medium).

Wire the checkpoint's routing (sigmoid+correction-bias vs softmax vs sqrtsoftplus) through the existing selection logic in layers/moe/init.rs/forward.rs; check num_experts ≀ 512, top_k ≀ 32 kernel bounds; add a MODEL.toml kernel target with match_names if config alone cannot disambiguate from qwen3.5/3.6 (the documented tie-breaking requirement in atlas-kernels/src/resolve.rs).

  1. 5. P1 β€” Speculative decoding config (Complexity: Low).

Map Flash-Next's MTP module count to mtp_num_hidden_layers and existing MTP heads; if the reference recipe combines n-gram + MTP drafting, extend cli/validate.rs and the scheduler proposer chain to allow composition (Complexity: Medium, scheduler work).

  1. 6. P2 β€” Chat template & server behavior presets (Complexity: Low).

Add jinja-templates/qwen4exp.jinja (or rely on the checkpoint-embedded template), MODEL.toml with card-derived sampling presets (thinking/non-thinking/tools, penalty-free tools per family rule), thinking_default, loop-watchdog settings β€” mirroring kernels/gb10/qwen3.8-27b/MODEL.toml.

  1. 7. P2 β€” Long-context & KV budget validation (Complexity: Medium, mostly measurement).

Re-derive effective_context and sliding-window interaction for Flash-Next's context length; validate FP8-KV calibration path (fp8_calibration.rs, --fp8-kv-headroom) and GDN state memory (48/64 linear layers β‡’ per-seq state cost) against the buffer arena sizing in spark-runtime/src/buffers/sizes.rs.

  1. 8. P3 β€” Local expert-streaming for very large MoE variants (Complexity: High).

If a Flash-Next MoE variant exceeds single-GPU weight budget, build on spark-storage expert-tier machinery to add a local mmap/pinned-RAM expert tier (pinned_hosts.rs exists) with async H2D prefetch on routed expert ids.

(d) Risks / unknowns

P β€” prod 27B (truncated at template-token, 5.7 KB) β€” grade 6/10

Atlas x Qwen3.8-Flash-Next: gap analysis

(a) Atlas current architecture

Atlas is an AGPL-3.0 inference stack for NVIDIA GB10 / DGX Spark (unified memory). Relevant pieces I inspected:

Existing model support matrix (from factory.rs): qwen3_next, qwen3_5_moe, qwen3_5, qwen3_6_moe, holo3_1_moe, qwen3_vl_moe, nemotron_h, nemotron_h_puzzle, gemma4, mistral, minimax_m2, step3p7, laguna, deepseek_v4, m2m_100.

(b) Feature-by-feature gap table

Flash-Next featureAtlas statusEvidence
model_type = "qwen4_exp" dispatchMissing β€” no arm in loader_for_config; no parser in dispatch.rscrates/spark-model/src/factory.rs; crates/atlas-core/src/config/dispatch.rs:51-273
Gated DeltaNet (3 of 4 layers, recurrent state)Present β€” full GDN stack: decode, batched, prefill (WY32, FLA, TMA, reg-resident), per-sequence state pool, FP16/FP32 h-statecrates/spark-model/src/layers/qwen3_ssm/mod.rs (498 lines of kernel handles)
GDN sigmoid output gatePresent β€” gated_rms_norm_k / gated_rms_norm_f32_k (Z-gate on GDN output)crates/spark-model/src/layers/qwen3_ssm/mod.rs:87-88
Per-seq recurrent state, checkpointed for batching, reset per seqPresent β€” SsmLayerState, h_is_f16, per-seq pool slots, batched dispatchcrates/spark-model/src/layers/qwen3_ssm/mod.rs:122-130
Full-attention layers (GQA)Present β€” shared Qwen3AttentionLayercrates/spark-model/src/layers/qwen3_attention/
Hybrid layer schedule (GDN + full attn, 3:1)Present β€” LayerType::{FullAttention, SlidingAttention, LinearAttention, Moe} + layer_types / full_attention_intervalcrates/atlas-core/src/config.rs:12-20,92-101
Sparse MoE, 512 experts, top-10Present β€” routed + shared expert, BF16/FP8/NVFP4, EP/TP; per-layer top-K (num_experts_per_toks)crates/spark-model/src/layers/moe/forward.rs; crates/atlas-core/src/config.rs:70-90,208
Gated shared expert (gating differs from Qwen3-MoE)Partial β€” shared-expert FFN exists (fused gate/up+silu/down, BF16/FP8/NVFP4), but the output is a plain additive sum; no learned gate on the shared-expert output foundcrates/spark-model/src/layers/moe/forward.rs (shared expert computed, added); no shared_gate/shared_expert_gate symbol
norm_topk_probPresentcrates/atlas-core/src/config.rs:85
Qwen Sparse Attention (QSA) β€” budget-based, indexer selects KV under a token budgetPartial β€” DeepSeek-V4 CSA/HCA path exists (compress_ratios, index_n_heads, index_head_dim, index_topk) but is ratio-based, not budget-based; no token_budget/attn_budget symbolscrates/atlas-core/src/config.rs:267-283; crates/spark-model/src/layers/qwen3_attention/init_arch_gates.rs:37-53; crates/spark-model/src/weight_loader/deepseek_v4/assemble.rs:366-369
QSA + quantized KV "attn-rot disable" interactionPartial β€” FP8 KV cache + online calibration exist; no explicit RoPE-disable flag for sparse layers foundcrates/atlas-core/src/config.rs:380-390; no attn_rot_disable symbol
Per-layer n-gram embeddings (PLE), ~51B table, hashed lookups, host-side placementMissing β€” no ngram, n_gram, ple_, per_layer_emb symbols anywheregrep across crates/ returns 0 hits
Low-rank hyper-connections (hc_count=4, learned low-rank projections)Present β€” DeepSeek-V4 mHC path: hc_mult, hc_sinkhorn_iters, hc_eps, buffers, opscrates/atlas-core/src/config.rs:255-266; crates/spark-model/src/layers/ops/hyper_connection.rs; crates/spark-runtime/src/buffers/sizes.rs:449-465
MTP head (speculative)Present β€” MtpHead, BF16/FP8/NVFP4, drafter prefill, catch-up, refeed; multi-module mtp_multi.rscrates/spark-model/src/layers/mtp_head/; crates/spark-model/src/layers/mtp_multi.rs; crates/spark-model/src/speculative.rs
Multimodal (image+video, CLIP-style ViT + mmproj)Present β€” vision_encoder/enc_impl/ (patch_embed, pos_embed, vit_block, merger); vision_config parsingcrates/spark-model/src/layers/vision_encoder/enc_impl/; crates/atlas-core/src/config/parsers/vision.rs
262,144-token contextPresent β€” max_position_embeddings + YaRN fields; radix/prefix cachecrates/atlas-core/src/config.rs:112,285-312; crates/spark-runtime/src/radix_tree/
Thinking/non-thinking chat modes (enable_thinking)Present β€” qwen3_5_moe.jinja emits `
E2 β€” Flash-Next Q3 (truncated at template-token, 3.4 KB) β€” grade 4/10

Atlas x Qwen3.8-Flash-Next: gap analysis

Research caveat: this report is based on direct inspection of the Atlas tree (atlas-core config layer, spark-model factory/loaders/layers, spark-runtime KV/buffers/backends, spark-server tokenizer/tool-parsing, kernels/gb10/* target manifests) plus the Flash-Next architecture reference. A few late verification searches were truncated (notably: generic CPU/mmap weight-residency per tensor group, and the exact spark-quant crate layout). Items resting on those are marked unverified rather than asserted as gaps.

(a) Atlas today β€” architecture overview

Atlas is a single-binary, single-hardware (NVIDIA GB10 / SM121) inference engine organized around seven trait/convention plug points, all confirmed in code:

  1. 1. Config layer β€” crates/atlas-core/src/config.rs defines one ModelConfig as the "single source of truth" for dimensions and feature flags. config/dispatch.rs::parse_config probes model_type and routes to family parsers (config/parsers/{deepseek_v4,gemma4,minimax,mistral,step3p7,laguna}.rs, plus inline Qwen3.5/3.6/Nemotron arms). Parsers normalize HF field names into canonical Atlas fields and set architecture flags (attn_gated, mrope_interleaved, scoring_func, hc_mult, hc_sinkhorn_iters, hc_eps, compress_ratios, index_n_heads/index_head_dim/index_topk, num_hash_layers, kv_lora_rank, moe_latent_size, …).
  2. 2. Loader registry β€” crates/spark-model/src/factory.rs::loader_for_config is documented as "the ONLY place model_type strings are matched"; ~14 loaders under spark-model/src/weight_loader/ implement ModelWeightLoader. factory::build_model assembles a model-agnostic TransformerModel (embed β†’ [layers] β†’ norm β†’ lm_head).
  3. 3. Layer composition β€” spark-model/src/layers/ holds composable TransformerLayer impls: qwen3_attention/ (GQA + paged KV), qwen3_ssm/ (Gated DeltaNet: QKVZ proj, causal conv1d, delta-rule recurrence, gated RMS-norm β€” decode / batched decode / FLA-chunked prefill / WY32 / reg-resident kernel families), nemotron_mamba2/, moe/ + nemotron_moe/ (routed + shared experts, LatentMoE, sigmoid/sqrtsoftplus scoring, routing bias), dense_ffn.rs, mtp_head/ + mtp_multi.rs, deepseek_v4_mtp.rs, dflash_head/, vision_encoder/, and layers/ops/hyper_connection.rs (mHC expand/collapse/Sinkhorn ops).
  4. 4. Runtime β€” spark-runtime: kv_cache.rs (KvCacheDtype, 16 variants incl. turbo*/asymmetric), prefix_cache/ + radix_tree/, kv_spill.rs (NVMe offload via StorageBackend), buffers/ (arena sizing incl. hc_streams/hc_post/hc_comb, moe_latent buffers), gpu/ (GpuBackend trait; CUDA + Metal backends), sampler/, weights/ (WeightStore, O_DIRECT fast loader with mmap fallback).
  5. 5. Kernels β€” kernels/<hw>/<model>/<quant>/ auto-discovered by build.rs; kernels/gb10/deepseek-v4-flash/MODEL.toml carries per-model geometry (hc_mult = 4).
  6. 6. Serving β€” spark-server: OpenAI/Anthropic APIs, scheduler (fifo/slai), MTP + DFlash speculative decoding (spark-model/src/speculative.rs, preflight.rs MTP_SUPPORTED_MODEL_TYPES), tokenizer/ (jinja rendering, effort/thinking directives β€” openai/tests/thinking.rs shows a full enable_thinking/budget/effort pipeline with reasoning_content streaming), tool_parser.rs (ToolCallParser trait; hermes JSON and qwen3_coder XML inner formats under shared `
Flash-Next architecture reference given to the agents

Qwen3.8-Flash-Next β€” architecture reference (qwen4exp)

Released 2026-08-26 by the Qwen team; the first public preview of the Qwen4 architecture.

HF: Qwen/Qwen3.8-Flash-Next (BF16, ~355 GB) and Qwen/Qwen3.8-Flash-Next-FP8.

Config model_type: qwen4_exp. Not supported by released Transformers/vLLM as of 2026-08-28;

llama.cpp support exists only in unmerged PR ggml-org/llama.cpp#27742.

Key architectural features an inference engine must implement:

  1. 1. Sparse MoE: 125B total parameters, ~6B active per token. 512 experts, top-10 routing,

plus a gated shared expert. Standard grouped expert FFN kernels apply, but the router

and shared-expert gating differ from Qwen3-MoE.

  1. 2. Gated DeltaNet layers: 3 of every 4 layers are linear-attention (recurrent, constant-size

state) DeltaNet blocks with a sigmoid output gate. No KV cache for these layers; instead a

per-sequence recurrent state that must be tracked, checkpointed for batching, and reset per sequence.

  1. 3. Qwen Sparse Attention (QSA): the remaining 1/4 of layers use budget-based sparse attention β€”

an indexer selects which cached KV entries each query attends to under a token budget.

Quantized KV cache interacts poorly with rotation tricks (llama.cpp needed an attn-rot disable).

  1. 4. Per-layer n-gram embeddings (PLE): an auxiliary ~51B-parameter n-gram embedding table,

hashed lookups per layer. Can be executed host-side (CPU/mmap) to keep it out of GPU memory;

engines should support placing this tensor group on a separate backend/device.

  1. 5. Low-rank hyper-connections: hc_count = 4 residual streams mixed by learned low-rank

projections (replaces the single residual stream; affects the whole block dataflow).

  1. 6. Multi-token prediction (MTP): the checkpoint ships an MTP head usable for speculative

decoding (analogous to Qwen3.5's MTP-2).

  1. 7. Multimodal: image+video input through a CLIP-style vision encoder (separate mmproj in GGUF).
  2. 8. Context: 262,144 tokens native. Thinking/non-thinking chat modes via chat template

(enable_thinking flag); recommended sampling: instruct temp 0.7 top_p 0.8, thinking temp 1.0 top_p 0.95.

  1. 9. Tokenizer: Qwen3-family BPE, extended special tokens for tool calling; standard Qwen chat template

with tool-call JSON blocks.

Quantization notes: community GGUFs exist (Unsloth UD-Q3_K_XL 84 GB, UD-Q4_K_XL 111 GB).

On 128 GB unified-memory hosts the PLE table is typically offloaded to CPU/mmap.

Round 2 β€” vLLM's real implementation vs Atlas (bigger budget)

The research target grew: vLLM checked out at PR #53896 (the actual Flash-Next implementation β€” which revealed vLLM's "day-0 support" is also an unmerged PR, same as llama.cpp's). Agents research BOTH codebases and write a comparative adoption plan. Budget: 400-step cap, ~10K tok/step, wrap-up nudge at ~260 messages, special-token escaping rule (fixes round 1's truncation bug). 2026-08-30/31.

ConfigWallLLM stepsTool callsInput tokOutput tokReportGrade*
A (FN Q4)125 min113 (self-stopped)1485.01M14.0K complete, 20.6 KB9.5/10
E2 (FN Q3)60 min126 (self-stopped)1366.10M11.7K complete, 12.8 KB6.5/10
P (prod 27B)72 min†130 (hit cap)1336.43M11.2K forced (toolless finale), 9.6 KB5.5/10

*Graded by verifying every cited vLLM file against the actual PR tree and cross-checking mechanism descriptions against the code. A: 9.5/10 β€” every citation real, package layout exactly right, and the code check confirmed its QSA account (Qwen4ExpQSAAttention merged owner + QSAKeyStateCache/QSACompressedKeyCache + the qwen4_exp_qsa_with_output custom op); staff-engineer-grade 6-phase plan with a GB10-specific divergence (host-resident PLE via UVA/mmap). E2: 6.5/10 β€” excellent Atlas-side table, but fabricated two vLLM files (common/gdn.py, common/ngram_embedding.py) and confabulated an MLA-aliasing QSA mechanism β€” dangerous precisely because of its confident line-number citations. P: 5.5/10 β€” honest method (read one kernel fully, inferred the rest β€” citations real), but shallow vLLM coverage, and its Atlas status table contradicts round 1's verified findings (claims GDN/MTP/HC missing when they exist) β€” its pruned context had evicted the early Atlas research. †P failed round 1 of this task outright (researched to the cap, ignored all stop instructions incl. "no more tools"); the number is its re-run with a force-final that binds no tools. The 27B never voluntarily stops digging; both 125B configs self-terminated.

Round 2 reports (verbatim)

A β€” Flash-Next Q4 (20.6 KB) β€” 9.5/10, all citations verified

Flash-Next support: vLLM vs Atlas

Scope note: this report is based on a deep read of the vLLM PR #53896 tree (vllm/models/qwen4_exp/, config plumbing, cache specs) and on targeted searches of the Atlas tree. A few Atlas-side confirmations (exact kernel inventories per feature) were still in flight when research was cut off; where Atlas status is stated with lower confidence it is flagged as such. All findings below are from files actually read; inferences are labeled.

---

(a) How vLLM implements qwen4exp, feature by feature

0. Overall layout
1. Config conversion β€” vllm/models/qwen4_exp/config.py
2. Model skeleton β€” nvidia/model.py
3. Hyper-connections β€” common/hyperconnection.py + nvidia/hyperconnection.py + nvidia/ops/hc.py
4. Gated DeltaNet (linear attention)
5. PLE / per-layer n-gram embedding β€” nvidia/ple_layer.py (+ common/ple.py)
6. QSA sparse attention + indexer β€” nvidia/qsa.py, nvidia/indexer_qsa.py, common/qsa_cache.py, nvidia/ops/qsa*.py
7. MoE
8. MTP β€” nvidia/mtp.py
9. Misc

---

(b) Atlas current status per feature

(Inferred from searches of the Atlas tree; confidence noted.)

AreaAtlas statusEvidence / notes
Gated DeltaNetLikely present or close β€” Atlas already runs Qwen3-Next-class hybrids; search for gated delta/gdn/ssm hits in the mamba/linear-attention paths (medium confidence β€” exact kernel parity with vLLM's QwenGatedDeltaNetAttention not fully verified).If present, main gap is gqa_interleaved_layout=False handling and num_spec-extended conv state.
Hybrid (GDN+full) scheduling / mamba-style state cachePartially exists β€” Atlas has per-request recurrent state for its existing hybrid models, but no notion of *two different* state kinds (GDN + short-conv) with different page sizes / TP-replication.vLLM's get_mamba_specs_from_config returning a tuple of specs and taking max page size is the pattern to mirror.
QSA sparse attentionMissing. No indexer, no block-topk sparse paged attention kernel. Atlas has dense paged attention only.
Indexer + side cachesMissing. No CircularBufferSpec analogue (per-request fixed ring block), no MLAAttentionSpec-with-tokens_per_state analogue (compressed cache tied to main block table).
PLE / n-gram embeddingsMissing. No per-layer embedding branch, no hashed n-gram lookup, no short dilated conv state, no ngram_context plumbing through the scheduler/runner.
Hyper-connectionsMissing. No multi-stream [T, HCΒ·H] hidden state, no gated mix/combine, no fused combine+norm kernel. Atlas residual flow is single-stream fused-add+rmsnorm.
MoEExists (routing, shared expert, expert-parallel). Gaps: fused-shared-expert packing semantics matching qwen3_next, EPLB-style metadata hooks, and the SP-MoE-rejection interaction with HC.
MTPPartially exists (Atlas has spec decode / MTP for existing models). Gap: feeding multi-stream hidden to the drafter, skip_topk reuse, spec-aware state shapes.
Config plumbingMissing qwen4exp config: hc/ple/ngram/qsa fields + validation (indexer_kv_heads=1, budget/ratio ∈ {512,2048}, ring divides block size, etc.).
Raw input tokens to modelNeeds check β€” Atlas must pass input_ids, query_start_loc, ngram_context into the model forward (vLLM: requires_raw_input_tokens).

---

(c) Side-by-side comparison

FeaturevLLM mechanism (files)Atlas statusPort difficulty
Config + validationmodels/qwen4_exp/config.py subclass of Qwen3NextConfig; strict QSA/PLE validatorsMissingLow
Multi-stream HC statehidden.repeat(1,4) through stack; delayed combine (nvidia/hyperconnection.py, model.py)MissingHigh (touches every layer's tensor shapes)
HC mix/combine kernelsTriton hc_combine_norm, hc_gate_mix, hc_silu, grouped GemmaRMSNorm; merged down+inject GEMM padded to 16MissingMedium (custom CUDA/Metal/C++ kernels in Atlas; fusions matter for perf)
Gated DeltaNetReuses qwen3_next QwenGatedDeltaNetAttention + mamba state calculatorsLikely exists (verify)Low–Medium
Dual state kinds (GDN + short-conv)Two MambaSpecs, max page size, tp_replicated short-conv, mamba_cache_mode=alignPartial (single state kind)Medium
PLE n-gram branchnvidia/ple_layer.py: hashed n-gram lookup (~20M rows) + dilated short conv on HCΒ·H channels, ngram_context across requestsMissingHigh (new cache kind + runner plumbing + big table memory)
QSA sparse attentionMerged owner + opaque custom op; Triton qsa_sparse_paged_attention over manager pages + topk indicesMissingHigh
Indexer + side cachesindexer_qsa.py, qsa_cache.py: raw-key ring (CircularBufferSpec) + compressed keys (MLAAttentionSpec.tokens_per_state), fused pre-indexer, on-device metadata kernelMissingHigh
MoEqwen3_next MoE reuse + EPLB + fused shared expertExistsLow
MTPMulti-stream target hidden buffer; skip_topk; spec-aware state sizesPartialMedium
Weight loading quirksHC merged GEMM mapper, QSA scale remap, non-persistent skipsNeeds equivalents in Atlas loaderLow–Medium
Low-latency skinny GEMMlow_latency_gemm.py for HC projectionsMissingLow (GB10 cublasLt likely fine; measure)

---

(d) Prioritized Atlas adoption plan

Phase 1 β€” config & skeleton (1–2 wks).

  1. 1. Add Qwen4ExpConfig/TextConfig with all hc/ple/qsa fields and port vLLM's validators verbatim (they encode kernel constraints: indexer_kv_heads==1, budget/ratio ∈ {512,2048}, rotary_dim ≀ indexer_head_dim, ring capacity divides block size, ple_embed_dim % ((ngram_size-1)*heads_per_ngram) == 0).
  2. 2. Layer-type dispatch (linear vs full), MoE/dense MLP selection from decoder_sparse_step/mlp_only_layers.

Phase 2 β€” hyper-connections (highest structural impact, do early).

  1. 3. Switch the decoder stack to carry [T, HCΒ·H]; implement mix/combine/combine_and_mix with vLLM's delayed-combine dataflow β€” it is what keeps the extra HCΒ·H bandwidth to ~1 extra read+write per block instead of per mix+combine. Write fused combine+RMSNorm and gate-mix kernels; merge down+inject into one GEMM padded to 16 rows; keep HC projections un-quantized and un-TP'd (vLLM: disable_tp=True, without_modelopt_fp4 on QKV).
  2. 4. PP/last-rank mixer equivalents: materialize before any external addition (deepstack, PLE) and at stage boundaries.

Phase 3 β€” GDN + dual state cache.

  1. 5. Reuse/verify Atlas GDN against QwenGatedDeltaNetAttention semantics (non-interleaved layout, a/b gating, conv+SSM states, spec-token extension).
  2. 6. Generalize Atlas's recurrent-state manager to multiple state specs per model (GDN per-head-sharded; short-conv TP-replicated; page size = max across specs), mirroring get_mamba_specs_from_config. Adopt "align"-style prefix-cache semantics only; vLLM rejects all.

Phase 4 β€” PLE.

  1. 7. Implement hashed n-gram lookup + per-head embedding + dilated short conv over HCΒ·H channels, with conv state as the second mamba spec and ngram_context (ngram_size-1 tokens) threaded through the scheduler/runner alongside query_start_loc. In Rust, the hash/lookup kernel is straightforward; the runner plumbing (raw input tokens to forward, per-request boundary masking) is the real work.
  2. 8. Diverge on memory: the ~20MΓ—ple_embed_dim table is large on a unified-memory GB10. Here Atlas can do *better* than this vLLM tree: implement the future PRs' idea natively β€” mmap the embedding table and expose it to CUDA via UVA/zero-copy (GB10's coherent C2C makes host-resident PLE attractive; consider GB10-resident with L2-friendly hashing). This is a Rust/GB10-specific divergence vLLM's separate PRs validate.

Phase 5 β€” QSA.

  1. 9. Build the merged QSA owner: main FullAttentionSpec BF16 cache + indexer side branch, wrapped as one opaque transaction (Atlas's graph capture must treat index→KV-write→sparse-attend as one node, like qwen4_exp_qsa_with_output).
  2. 10. Side caches: per-request raw-key ring (capacity compress_ratio + num_spec rounded to groups, must divide block size) and compressed-key cache whose block table shares the main KV block table lifecycle (vLLM's tokens_per_state trick β€” in Atlas, alias the compressed cache's page mapping to the main block table at 1/ratio density).
  3. 11. Kernels: pre-indexer fusion (norm+RoPE+store+group-compress), weight-free scoring of compressed keys, block top-k (512/2048 groups), group→token expansion (budget + ratio - 1, -1 padded), and a sparse paged GQA kernel consuming logical indices. Port vLLM's on-device metadata kernel semantics (token_to_req, logical_positions, slot mappings, compressor work-list) into Atlas's CUDA-graph-safe metadata builder.
  4. 12. Constraints to enforce initially: BF16 only, no KV quant, no CP, MQA indexer.

Phase 6 β€” MTP + polish.

  1. 13. Expose pre-final-mixer multi-stream hidden to the drafter (scheme A buffer), skip_topk reuse on draft steps, spec-aware state shapes; then EPLB/fused-shared-expert parity and low-latency skinny GEMM tuning (measure on GB10 before porting vLLM's custom path).

Suggested ordering rationale: HC changes the tensor contract of the whole stack (do first, once); PLE and QSA both depend on HC state shapes and on the generalized state manager; MTP last.

---

(e) Risks and open questions

  1. 1. HC bandwidth on GB10: HCΒ·H streams multiply activation traffic ~4Γ—. vLLM's delayed-combine + fused combine-norm is essential; Atlas must match these fusions or HC will dominate decode latency. Quantify before/after.
  2. 2. PLE table memory: 20M-row hashed n-gram vocab per dense-PLE layer group β€” on-device residency may be infeasible alongside KV cache on GB10's unified pool. UVA/mmap (per the separate vLLM PR line) is the mitigation; host-bandwidth sensitivity of the lookup is unmeasured. Open: is the table shared across PLE layers or per-layer? (vLLM tree: per-ple_dense_layer_id tables β€” confirm sizing.)
  3. 3. QSA correctness coupling: indexer RoPE must be *bit-identical* to main attention RoPE (incl. interleaved MRoPE); the ring-capacity-divides-block-size invariant interacts with scheduler block-size LCM computation. Any Atlas block-size policy change can silently break it β€” port the validators.
  4. 4. Spec-decode interactions: rejected-draft rows vs. committed ring keys, skip_topk reuse, +1 conv-kernel slack for short-conv/GDN states β€” subtle; vLLM's comments encode hard-won edge cases worth mirroring in tests.
  5. 5. Unverified Atlas assumptions: GDN kernel parity and MoE routing details in Atlas were not fully read before the research cutoff; Phase 3/6 estimates depend on that verification.
  6. 6. Torch.compile opacity: vLLM hides QSA and HC glue from compilation via custom ops; Atlas's graph builder needs an equivalent "opaque multi-kernel region" concept β€” confirm its executor supports side-buffer outputs (topk buffer) across graph replays.
  7. 7. Multimodal/deepstack: if Atlas targets the VL checkpoint, deepstack additions must terminate delayed HC combines exactly as in model.py; text-only first would de-risk.
  8. 8. Quantization policy: vLLM keeps HC, QKV-under-modelopt-FP4, and QSA KV in BF16; any Atlas quantization plan must respect these carve-outs or accuracy regresses.
E2 β€” Flash-Next Q3 (12.8 KB) β€” 6.5/10, two fabricated citations

Flash-Next support: vLLM vs Atlas

Scope and method note

Research was done against the PR #53896 tree in vllm (model package vllm/models/qwen4_exp/{common,nvidia,amd}, config in vllm/transformers_utils/configs/qwen4_exp.py, registry entries at vllm/model_executor/models/registry.py:114-117 and :670) and the Atlas tree (crates/atlas-core, crates/spark-runtime, crates/spark-model). Where I could not fully trace a vLLM function to its leaf (notably the exact stream-collapse op feeding Qwen4ExpModel.norm), I say so explicitly rather than guess.

---

(a) How vLLM implements qwen4exp, feature by feature

1. Config conversion and model registration
2. Hybrid GDN + full attention
3. QSA sparse attention + n-gram indexer
4. Per-layer embedding (PLE) / n-gram
5. Hyper-connections (gated_residual)
6. MoE routing
7. MTP
8. Multimodal wrapper

---

(b) Atlas current status, per feature

FeatureAtlas evidenceStatus
Config plumbingcrates/atlas-core/src/config.rs has hc_mult, num_experts, num_experts_per_tok, num_experts_per_toks (per-layer K, :206-208), mamba_num_heads/mamba_head_dim, conv_dim; parsers live in crates/atlas-core/src/config/parsers/*.rs; factory dispatch at crates/spark-model/src/factory.rs:109-113 (supported list: qwen3_next, qwen3_5_moe, …, deepseek_v4 β€” no qwen4exp)Missing for qwen4exp; infra exists
GDN (Gated DeltaNet)crates/spark-model/src/layers/qwen3_ssm/ β€” full GDN: init.rs (gated_delta_rule_decode, _f32_*, wy2/wy3 variants), trait_prefill_gdn.rs + trait_prefill_gdn/batched.rs (FLA recompute_wu β†’ chunk_delta_h_ksplit β†’ chunk_fwd_o, plus FlashInfer tensor-core path behind ATLAS_GDN_FLASHINFER=1), trait_decode_batched_conv_gdn*.rs (fused conv+GDN decode, K=2..8 for spec verify), ssm_forward.rsExists and is mature (Qwen3-Next lineage)
SSM state pagingcrates/spark-model/src/ssm_reserve.rs, model/ssm_tier/fingerprint.rs, weight_loader/qwen35_dense.rsExists
MLAcrates/spark-model/src/layers/qwen3_attention/ (paged decode, FP8/2-bit KV, RoPE)Exists
QSA / top-k sparse attentionNo indexer anywhere (indexer, index_topk, topk_attention β†’ no matches). Nearest thing is DeepSeek-V4 CSA/HCA compressed-KV (layers/qwen3_attention/types_weights.rs:80, init_arch_gates.rs:37, prefill/cache_skip_v4.rs:415) β€” a fixed-ratio compressor, not learned top-k selectionMissing
Per-row top-k kernelOnly moe_topk_softmax* (layers/moe/init.rs:93-101) β€” softmax top-k for routing, not FP32 logit top-k over a KV rowMissing
PLE / n-gramZero matches for ngram, per_layer_embed, ple across crates/Missing entirely
Hyper-connectionscrates/spark-model/src/layers/ops/hyper_connection.rs implements mHC (Sinkhorn comb, hc_pre/hc_post/hc_head) for DeepSeek-V4; buffers [M, hc_mult, hidden] in crates/spark-runtime/src/buffers/{sizes.rs:449-465,accessors.rs:149-157}; config hc_mult/hc_sinkhorn_iters/hc_epsPartially exists β€” wrong variant. No sigmoid gated_residual mode
MoE grouped routinglayers/moe/{mod.rs,init.rs,forward*.rs} β€” W4A16/FP8/W8A8 grouped GEMM, shared-expert fusion, sort-by-expert, EP dispatch (layers/ep_dispatch.rs), num_experts_per_toks per-layer K, correction_bias preflight (preflight.rs:299-305)Exists; needs scoring_func/topk_group/n_group verification
MTPlayers/mtp_head.rs (single-layer drafter, NVFP4/FP8/BF16, drafter-context prefill), layers/mtp_multi.rs, layers/deepseek_v4_mtp.rs, speculative.rs (DraftProposer), weight_loader/deepseek_v4/mtp.rsExists; no PLE-aware input construction
CUDA graphs / shape stabilitylayers/qwen3_attention/decode/run_paged_decode.rs, model/trait_impl/*Exists; top-k buffer padding is new

---

(c) Side-by-side comparison

FeaturevLLM mechanism (file)Atlas statusPort difficulty
Config + registrationconfigs/qwen4_exp.py, `Q
P β€” prod 27B (9.6 KB) β€” 5.5/10, forced finale

Flash-Next support: vLLM vs Atlas

(a) How vLLM implements qwen4exp β€” feature by feature

The tree is the PR #53896 branch. The model lives under vllm/models/qwen4_exp/ (with an nvidia/ sub-tree of Triton/CUDA ops). I read the QSA pre-indexer kernel in depth; the other features are described from their file locations and the architecture reference.

Model definition & config. vllm/models/qwen4_exp/model.py defines the decoder stack and registers the qwen4exp architecture. Config conversion in vllm/config/model.py maps the HF config (hidden size, layer types, MoE dims, SSM dims, QSA dims, PLE dims, MTP depth) into vLLM's ModelConfig/CacheConfig. Layer types are per-layer: a mix of Gated DeltaNet (linear-attention/SSM) layers, QSA sparse-attention layers, and MoE FFN layers, plus per-layer n-gram (PLE) embedding layers.

Gated DeltaNet (linear attention / SSM). Implemented via the shared vllm/model_executor/layers/mamba/ + gated_delta_net kernels (chunked scan with a per-head recurrent state). Caching: a per-request fixed-size recurrent state (the "conv state" + "ssm state"), not a KV cache. Prefill runs the chunked parallel scan; decode runs the single-step recurrence. This is the same mechanism vLLM uses for Qwen3-Next / Falcon-Mamba, so the plumbing (state layout, slot allocation, prefix-cache semantics for the recurrent state) already exists.

QSA sparse attention + indexer. This is the novel piece. vllm/models/qwen4_exp/nvidia/ops/qsa_pre_indexer.py (508 lines, read in full) is a fused Triton kernel that, in one launch:

So QSA keeps two caches: a small circular raw-K window (for the indexer's local attention) and a compressed-K cache (for the sparse long-range attention). The indexer scores queries against the compressed cache to select which raw/compressed K blocks the full attention reads. The kernel is tiled over (token, head) for Q and over compression groups for K, with TILE_T_Q/TILE_H_Q chosen by token count (≀4096 β†’ 2Γ—2, else 2Γ—4), num_warps=1.

Per-layer n-gram (PLE) embeddings. PLE layers inject n-gram-derived embeddings per layer. In this tree they are computed inline (the baseline); the offload variants (UVA/mmap) are in the separate PRs #53899/#54129/#54371 and are not in this tree. The baseline keeps PLE tables in HBM and gathers per-layer.

Hyper-connections. Residual "hyper-connection" mixing across the per-layer branches is implemented as extra learned mixing weights applied in the decoder block forward (see the block forward in model.py); it is a small per-token linear combine, not a new cache.

MoE routing. Standard grouped-expert MoE with the existing vLLM fused-MoE kernels (top-k gating, expert parallelism optional). Nothing qwen4exp-specific beyond dims.

MTP. Multi-token-prediction head(s) per the config depth, using the existing MTP scaffolding (draft head + shared trunk), with the recurrent/SSM state carried across the MTP steps.

(b) Atlas current status per feature

Atlas (Rust, GB10) has no qwen4exp in the tree. Searching for the feature keywords:

(c) Side-by-side comparison

FeaturevLLM mechanismAtlas statusPort difficulty
Gated DeltaNet (SSM)Chunked parallel scan (prefill) + single-step recurrence (decode); per-request recurrent state, not KVMissing (KV-centric)High β€” new state type, new kernels, new cache manager
QSA sparse attentionFused pre-indexer (norm+RoPE+K-compress+circular raw state) + indexer selection + sparse attention over compressed/raw KMissingHigh β€” dual K cache + indexer + sparse attention
Indexer / compressed-K cacheCOMPRESS_RATIO compressed cache + circular raw-K window, slot/block tablesMissingHigh
mrope (interleaved t/h/w)pairs % 3 axis masks in fused kernelPartial (plain RoPE)Medium
PLE per-layer n-gramInline per-layer gather (baseline); offload in separate PRsMissingMedium
Hyper-connectionsPer-block learned residual mixingMissingLow–Medium
MoE routingFused grouped-expert MoEExists (reusable)Low
MTPDraft head + shared trunk, state carriedMissingMedium
Config plumbingqwen4exp arch + per-layer type mappingMissingLow

(d) Prioritized adoption plan for Atlas

  1. 1. Config + model skeleton (Low). Add qwen4exp arch, per-layer type table (DeltaNet / QSA / MoE / PLE), and the decoder-block forward with hyper-connection mixing. Reuse the existing MoE path. This unblocks everything else and is mostly plumbing.
  2. 2. Gated DeltaNet (High, do early β€” it's on the critical path). Port the chunked-scan (prefill) and recurrent (decode) kernels to GB10 (CUDA or the existing Rust kernel harness). Introduce a recurrent-state cache manager distinct from paged KV: fixed per-request state, slot-allocated, prefix-cacheable by state-copy. This is the biggest new subsystem.
  3. 3. QSA sparse attention + indexer (High). Port qsa_pre_indexer as a fused kernel (norm + mrope + K-compress + circular raw-state commit). Add the two caches (compressed-K at COMPRESS_RATIO, circular raw-K window) with slot/block tables. Then the indexer (score Q vs compressed cache β†’ select blocks) and the sparse attention over the selected raw/compressed K. Keep the single-launch K-work/Q-work split; it's the design decision worth borrowing.
  4. 4. mrope (Medium). Extend the RoPE path with the interleaved t/h/w pair selection (the pairs % 3 masks). Fold into the QSA pre-indexer kernel as vLLM does rather than a separate op.
  5. 5. PLE per-layer n-gram (Medium). Start with the inline baseline (HBM tables, per-layer gather). Defer the UVA/mmap offload (PRs #53899/#54129/#54371) until the baseline is correct β€” it's a memory-bandwidth optimization, not a correctness requirement.
  6. 6. MTP (Medium). Add the draft-head + shared-trunk path and carry the DeltaNet/QSA state across MTP steps.
  7. 7. Hyper-connections (Low–Medium). Per-block learned residual mixing; small, do alongside the model skeleton.

Where to diverge for Rust/GB10: (i) implement the fused pre-indexer as a CUDA kernel in Atlas's kernel harness rather than Triton; (ii) if GB10's memory hierarchy favors it, consider fusing the indexer scoring into the same kernel as the K-compress (vLLM keeps them separate for register-shape independence β€” keep that separation first, fuse later only if profiling demands); (iii) keep the recurrent-state cache as a first-class cache type in Atlas's cache manager rather than shoehorning it into paged KV.

(e) Risks and open questions

Special tokens (if quoting the chat template): [think], [/tool_call], [IM_START].

Round 3 β€” llama.cpp (PR #27742) vs Atlas

Same comparative format as round 2, new blueprint: the llama.cpp tree that actually serves Flash-Next in these very benches (PR #27742). 2026-08-31.

ConfigWallLLM stepsTool callsInput tokOutput tokReportGrade*
E2 (FN Q3)84 min113 (self-stopped)1495.83M15.3K complete, 24.0 KB9.5/10
A (FN Q4)43 min116 (self-stopped)1455.94M14.7K complete, 21.1 KB9/10
P (prod 27B)115 min133 (hit cap)1346.61M10.9K forced finale, 10.9 KB4.5/10

*Every cited llama.cpp path was checked against the tree; the boldest mechanism claims were verified line-by-line. E2: 9.5/10 β€” zero fabrications this round, and every spot-check landed exactly (the ple_history struct with its seq_rm/cp/keep/add/div mirrors, the signed-sqrt PLE gate, the converter's np.memmap trick, ggml_solve_tri in the delta-rule, the FWHT matmul hint). Deepest implementation analysis of the whole series β€” a total reversal of its round-2 confabulation, suggesting that failure was variance, not a Q3 trait. A: 9/10 β€” equally sound, with unique correctness insights (the indexer cache reusing the attention cache's slot layout so the two "cannot drift"; the mirrored-not-split multi-GPU indexer; precomputed Hadamard matrices); one garbled filename (wht_bf16.cu for the real fwht.cu). P: 4.5/10 β€” decent llama.cpp half, but its Atlas half is confidently wrong (declares GDN/MTP/hyper-connections "missing" β€” all verified present in rounds 1–2): context pruning evicts its early research and it back-fills with guesses. Third run out of three where it researched to the hard cap and needed the toolless forced finale. Bonus robustness note: a leftover contradictory heading instruction in the prompt ("vLLM vs Atlas" vs the llama.cpp marker) was noticed, resolved correctly, and documented by both 125B configs.

Round 3 reports (verbatim)

E2 β€” Flash-Next Q3 (24.0 KB) β€” 9.5/10, all spot-checks verified to the line

Flash-Next support: llama.cpp vs Atlas

*(Note on title: the task brief asked for a "vLLM vs Atlas" heading; the actual comparison performed is llama.cpp PR #27742 vs Atlas, so the report uses the accurate title as instructed by the final directive.)*

---

(a) How llama.cpp implements Qwen3.8-Flash-Next (qwen4exp)

llama.cpp adds a new arch LLM_ARCH_QWEN4EXP (src/llama-arch.cpp:43) with a dedicated model-builder src/models/qwen4exp.cpp (~1,148 lines), a new memory class llama_memory_hybrid_idx (src/llama-memory-hybrid-idx.{h,cpp}), hparams extensions (src/llama-hparams.h:253–291), a converter (conversion/qwen4exp.py), and two new GGML primitives (GGML_OP_GATED_DELTA_NET, GGML_HINT_SRC0_IS_HADAMARD). The model is composed of five architectural features, most of which are shared with an existing DeepSeek-V4 (deepseek4.cpp) and Qwen3.5 (qwen35*.cpp) code base β€” this reuse is llama.cpp's single most important design property, and it maps well onto Atlas, which already ships DeepSeek-V4 and Qwen3.5/Qwen3.6.

1. Hyper-connections (mHC), replacing every residual + norm
2. Hybrid memory: attention KV + recurrent (GDN conv/SSM) state + a third *indexer* cache
3. QSA block-sparse attention (gated top-k over block-compressed KV)
4. Gated delta net (GDN) linear attention β€” inherited, not re-implemented
5. PLE β€” per-layer n-gram-hash embedding injection (the genuinely new part)
6. Conversion / quantization / offload handling

---

(b) Atlas current status, per feature

FeatureAtlas statusEvidence
Hyper-connections (mHC)Exists (DeepSeek-V4). FP32 [M, hc_mult, hidden] highway in the buffer arena, fused hc_pre/hc_post/hc_head kernels incl. Sinkhorn, wired into the Qwen3-attention layer trait for prefill, decode and multi-seq.kernels/gb10/deepseek-v4-flash/nvfp4/hyper_connection.cu; crates/spark-model/src/layers/ops/hyper_connection.rs; crates/spark-runtime/src/buffers.rs:84, buffers/sizes.rs:51,451, buffers/accessors.rs:149; layers/qwen3_attention/{types.rs:101, init.rs:153, types_weights.rs:142, trait_impl/prefill_inner.rs:39, trait_impl/decode_inner.rs:30, trait_impl/multi_seq/mod.rs:52}; crates/atlas-core/src/config/parsers/deepseek_v4.rs:210
Gated delta net / linear attentionExists (Qwen3.5/3.6 + qwen3_next). Full GDN prefill (chunked) + decode (single & multi-seq), conv+GDN fused decode variants, exact and multi variants, plus a dedicated SSM state pool with snapshot/spill/tier management.crates/spark-model/src/layers/qwen3_ssm/{mod.rs, ssm_forward.rs, trait_prefill_gdn.rs, trait_decode_batched_conv_gdn*.rs, gdn_flags.rs}; crates/spark-model/src/forward/qwen3_5/linear_attention.rs; crates/spark-model/src/model/{ssm_pool.rs, ssm_snapshot*.rs, ssm_batched_copy.rs, ssm_reserve.rs}
Hybrid attn+recurrent memoryExists. Paged KV + a separately managed recurrent-state pool with snapshots, spill to lower tiers, fault-in, and batched copy.crates/spark-model/src/model/ssm_pool.rs, ssm_snapshot*.rs, ssm_tier/; crates/spark-model/src/ssm_reserve.rs
MoE / expertsExists, incl. grouped decode, EP dispatch, NVFP4/MXFP4 routed experts.layers/moe/, layers/ep_dispatch.rs, layers/moe_grouped_decode_tests.rs, weight_loader/deepseek_v4/*
Sparse attention / indexerPartially exists, but a different mechanism. Atlas has DeepSeek-V4 CSA/HCA window compression (a compressor kernel + attention over `[raw causalcompressed] KV + sink) and config fields for a *semantic indexer* (indexer_n_head/head_dim/top_k), but the indexer fields appear to be config-only; there is no top-k-over-blocks selection path, no indexer key cache, and no cell_blk/blk_cells/bias` plumbing.kernels/gb10/deepseek-v4-flash/nvfp4/{csa_compress.cu, prefill_attn_compressed.cu}; crates/atlas-core/src/config.rs:267–278; layers/qwen3_attention/prefill/cache_skip_v4.rs:414–490; layers/qwen3_attention/prefill/paged_v4.rs:187; weight_loader/deepseek_v4/assemble.rs:366–420
PLE / n-gram hash embeddingsMissing. No per_layer_*, no hashed embedding table, no n-gram history. (ngram in Atlas refers exclusively to the unrelated n-gram *speculative decoding* proposer.)grep for `per_layerple_ngram in crates/ β†’ only spark-server/src/ngram.rs (spec-decode) and unrelated IndexError` hits
MTPExists, incl. a DeepSeek-V4-specific MTP that reuses the V4 layer body (MLA + mHC + MoE) β€” the right precedent for a Flash-Next MTP if one is ever wanted.layers/deepseek_v4_mtp.rs, weight_loader/deepseek_v4/mtp.rs, docs/deepseek_v4_mtp_support.md
MRoPE interleavedExists (Qwen3.5/3.6 VL path): T/H/W position streams staged per prefill chunk, mrope_interleaved config flag.model/trait_impl/prefill_b/{mrope_pos.rs, stage_batched.rs, upload_meta.rs}, layer.rs:116–183, factory.rs:89
Model registration for qwen4expMissing. factory.rs::loader_for_config matches qwen3_next, qwen3_5*, qwen3_6_moe, deepseek_v4, … β€” no qwen4exp/Qwen4ExpForConditionalGeneration.crates/spark-model/src/factory.rs:65–118
Hadamard fast path for HC matmulsNot found (no hadamard/fwht in Atlas); Atlas uses fused HC kernels instead.grep hadamard in atlas β†’ no matches

---

(c) Side-by-side comparison

Featurellama.cpp mechanism (PR #27742)Atlas statusPort difficulty
Arch registration / hparamsLLM_ARCH_QWEN4EXP + LLM_KV_*/LLM_TENSOR_* tables; per-layer is_ple_impl, is_indexer_full_impl arraysfactory.rs string dispatch + atlas-core::config parsers (deepseek_v4.rs precedent)Easy β€” mechanical
Hyper-connectionsShared DSV4 mHC; Hadamard hinted MUL_MAT + ggml_sinkhorn; n_embd_out_impl = hc_mult*n_embdFull mHC already (fused CUDA kernels, FP32 highway, prefill/decode/multi-seq)Easy β€” reuse V4 layer body; only the *low-rank* HC variant (hc_lowrank) may need a new branch
GDN linear attentionShared llm_build_delta_net_base; GGML_OP_GATED_DELTA_NET fused op w/ K snapshots, or ggml_solve_tri chunked referenceNative Rust/CUDA GDN prefill+decode, conv+GDN fused, multi-seq, exact variantsEasy–Medium β€” already there; must confirm *scalar-g* GDN (not KDA) config and conv kernel=4 semantics match Qwen3.5's
Hybrid memory (KV + recurrent)llama_memory_hybrid with rs rows packing conv + PLE conv history into n_embd_r()Paged KV + ssm_pool + snapshot/spill/tierMedium β€” Atlas's rs pool is *not* row-packed the llama.cpp way; PLE conv state needs a new per-seq state slot
QSA block-sparse attentionThird cell-aligned indexer cache + host-built cell_blk/blk_cells/blk_pos/bias; blocks cut the *position* line; additive Β±inf/1e9 bias; full/shared indexer alternationCSA/HCA compressor exists; no top-k block selection, no indexer key cacheHard β€” biggest new subsystem: new cache buffer, new selection kernel, paged-block gather, bias/mask integration into both prefill and decode attention
PLE n-gram hash embeddingsHost-side hash of token window (history in memory layer), get_rows gather from a giant table, grouped RMS norms, signed-sqrt sigmoid gate, dilated depthwise conv as sum-of-shifts, conv state in rs cacheMissing entirelyMedium–Hard β€” math is simple; the work is (i) a new per-seq hash-history object wired into rollback/branch/prefix-cache, (ii) hosting a ~100 GB table, (iii) 3 new small kernels
PLE table hosting / offloadLAYER_INPUT + GET_ROWS β†’ --override-tensor CPU/mmap; quantized as token-embedding type, name-overridableAtlas has pinned-pack / tier / overlay machinery (model/pinned_pack.rs, token_overlay.rs, atlas-tier) but no embedding-table offload policyMedium β€” needs a gather-from-host or tiered-table path; GB10 unified memory makes host-resident + cudaHost gather viable
MTPDeliberately dropped at conversion (no_mtp = True)V4-style MTP already implementedN/A now β€” skip, matching llama.cpp
MRoPE interleavedInherited _Qwen35MRopeMixinAlready implemented for Qwen3.5/3.6Easy
Converterconversion/qwen4exp.py: memmap-stitched 128-shard table, int64 constants read raw, qk-proj split, gamma +1Atlas weight loaders (weight_loader/deepseek_v4/assemble.rs, csa_ape.rs for exact-F32-constant handling)Medium β€” the shard-stitching and int64-exactness traps apply verbatim to a Rust loader
Session/state persistenceple_history serialized into the state blob alongside the cachesAtlas snapshots/spill cover KV+SSM; PLE history would need addingMedium β€” easy to forget, catastrophic when wrong

---

(d) Adoption plan for Atlas (prioritized)

P0 β€” Registration + config (1–2 days).

Add qwen4exp to factory.rs::loader_for_config and a config/parsers/qwen4exp.rs modeled on deepseek_v4.rs. Reuse the existing hc_mult/compress_ratios/indexer_* fields (atlas-core/src/config.rs:233–278) β€” they already exist because of V4. Add new fields for PLE (ple_layers, ngram_size, heads_per_ngram, conv_kernel, head_dim, eos_token_id, image_token_id, and the three int64 constant arrays). Borrow llama.cpp's decision to keep these as per-layer arrays (is_ple_impl, is_indexer_full_impl) rather than predicates β€” Flash-Next's layer pattern is irregular.

P1 β€” Layer body: mHC + GDN + MoE + MRoPE (days, mostly wiring).

Assemble the layer from parts Atlas already has, exactly as weight_loader/deepseek_v4/assemble.rs assembles a V4 layer. This mirrors llama.cpp's own structure (qwen4exp.cpp inherits delta-net from qwen35 and HC from deepseek4). Two checks: (i) confirm the GDN is scalar-g (chunk 64), not KDA β€” llama.cpp distinguishes them by g->ne[0] == S_k (delta-net-base.cpp:31); (ii) confirm hc_lowrank handling, since llama.cpp exposes hc_low_rank separately from the V4 default. Divergence: do *not* port llama.cpp's Hadamard-hint trick β€” Atlas's fused hyper_connection.cu already fuses residual+norm+mix and is the better design for a GPU-first engine.

P2 β€” PLE (the differentiator; ~2–3 weeks).

P3 β€” QSA sparse attention (~3–5 weeks, hardest).

P4 β€” Loader + conversion parity.

Port conversion/qwen4exp.py semantics into a Rust loader. Two traps llama.cpp documents explicitly: (i) int64 hash constants must not pass through a float cast β€” 45-bit multipliers silently round (qwen4exp.py:43–56); Atlas's csa_ape.rs already has the "keep exact F32/int constants" discipline to extend. (ii) The 128-shard n-gram table must be streamed to a scratch file at final row offsets, never concatenated in RAM (peak ~300 GB otherwise). Also: split fused index_qk_proj into q/k, and apply the Gemma zero-centered gamma +1 to ple.norm_{key,query,conv} and indexer.{q,k}_layernorm.

P5 β€” Skip MTP at export, matching llama.cpp (no_mtp = True, qwen4exp.py:30). Revisit only if a Flash-Next MTP is validated; layers/deepseek_v4_mtp.rs shows the pattern (reuse the real layer body).

P6 β€” Verification. Per-feature parity vs. the HF reference and vs. llama.cpp itself (which is a working reference implementation on the same weights): greedy logprob diff for (a) PLE on/off, (b) chunked vs single-shot prefill (exercises both conv-state paths), (c) branch

A β€” Flash-Next Q4 (21.1 KB) β€” 9/10

Flash-Next support: llama.cpp vs Atlas

*(Scope note: the requested heading was "vLLM vs Atlas", but the task β€” and all research performed β€” compares llama.cpp PR #27742 against Atlas. The title below reflects what was actually analyzed.)*

---

(a) How llama.cpp implements Qwen3.8-Flash-Next (qwen4exp)

1. Architecture registration and hparams
2. Graph construction (src/models/qwen4exp.cpp)
3. Hybrid memory (src/llama-memory-hybrid*.cpp)
4. Tensor placement / offload
5. Conversion

---

(b) Atlas current status per feature

FeatureStatusEvidence
Config dispatch / new model_typeExists, extensible β€” JSON model_type β†’ parser routingcrates/atlas-core/src/config/dispatch.rs:41-164; per-family parsers in crates/atlas-core/src/config/parsers/ (deepseek_v4, minimax, mistral, …). No qwen4exp entry.
Capability flagsExists β€” ModelCapabilities SSOT (SsmArchitecture::Gdn, has_moe_layers, has_mtp, AttentionType::Mla)crates/atlas-core/src/capabilities.rs:9-106. No PLE/hyper-connection/sparse-attention flags.
Gated delta net (decode)Mature β€” decode kernels incl. FP32/FP16 h-state, strided multi-seq batched, half/SRAM retention variantscrates/spark-model/src/layers/qwen3_ssm/mod.rs:107-131 (gdn_f32_strided_norm_*, gdn_f16_*), trait_decode_batched_conv_gdn*.rs
GDN prefillMature β€” WY4/WY32, FLA chunked multi-kernel (recompute_wu β†’ chunk_delta_h β†’ chunk_fwd_o), TMA variant, register-resident replayqwen3_ssm/mod.rs:150-198
Conv1d + L2-norm inside GDNExistsconv1d_l2norm_f32_strided_k (mod.rs:100-106)
Recurrent state pool (paged/batched, snapshots, spill/tiering)Exists, strong β€” SSM pool, snapshots, spill, tiering, batched copycrates/spark-model/src/model/ssm_pool.rs, ssm_snapshot*.rs, ssm_tier/, ssm_batched_copy.rs, ssm_reserve.rs
Hybrid layer scheduling (attn vs SSM per layer)Exists β€” LayerType::{LinearAttention, FullAttention, Moe} + hybrid pattern mappingconfig/dispatch.rs:194-200 (Nemotron pattern), capabilities.rs:67-75
MoE (grouped GEMM, EP/TP, routing bias)Existslayers/moe/, ep_dispatch.rs, tp_shard.rs, config scoring_func/use_routing_bias (atlas-core/src/config.rs:402-415)
MTP speculative decodingExists β€” Qwen3.5 single-module, MiniMax multi-module, DFlash, DeepSeek-V4 MTP headslayers/mtp_head/, mtp_multi.rs, deepseek_v4_mtp.rs, dflash_head.rs, config num_mtp_modules (config.rs:422-430)
Hyper-connections (mHC, Sinkhorn)Exists but DSv4-hardwired β€” hc_mult/hc_sinkhorn_iters/hc_eps config fields, HC buffers, fused CUDA kernelsconfig.rs:255-266; spark-runtime/src/buffers/sizes.rs:449-465; kernels/gb10/deepseek-v4-flash/nvfp4/hyper_connection.cu; loader weight_loader/deepseek_v4/*. Flash-Next needs hc_mult=2 + learned per-site alpha scales, which the DSv4 path (hc=4, no alpha) does not cover.
Sparse attention / lightning indexerConfig fields exist; no runtime path for this shape β€” index_n_heads/index_head_dim/index_topk parsed only by the DeepSeek-V4 parser (config/parsers/deepseek_v4.rs:200-201); DSv4 uses a *compressed-KV* LID path (layers/qwen3_attention/prefill/cache_skip_v4.rs, weight_loader/deepseek_v4/assemble.rs:367). No generic "gather top-k from paged KV by indexer score" kernel found.
Hadamard rotation as fused opMissing as attention op β€” WHT exists only inside TurboQuant KV quantization (kernels/gb10/common/wht_bf16.cu, qwen3_attention/decode/write_kv_cache.rs:67), not as a Q/K/V transform in the attention path.
PLE / per-layer token embeddingMissing entirely β€” no per_layer*/n-gram/altup code anywhere in spark-model. Embedding is a single embed_tokens table + batched_embed (model/trait_impl/prefill_c.rs:121, decode_b.rs:144).
PLE dilated n-gram conv stateMissing β€” SSM row layout has conv+state only; no second dilated-conv slot (layer.rs SsmLayerState, ssm_reserve.rs).
Indexer key cache as third memoryMissing β€” memory is paged KV (spark-runtime/src/kv_cache.rs) + SSM pool; no per-layer MQA "index cache" sharing slot layout with the main KV.
Large-embedding CPU/mmap offloadPartially exists — weight loader has precision/tier machinery (precision_schedule.rs, w4a16_gemv_tiers.rs, pinned_pack.rs, token_overlay.rs), but no regex tensor→CPU-buffer override equivalent to --override-tensor.
MRoPE (T,H,W streams)Exists β€” interleaved MRoPE with 3 position streams through prefill/verifymodel/trait_impl/prefill_b/mrope_pos.rs, stage_batched.rs:78-187, layer.rs:116-183. Flash-Next's imrope variant (llama.cpp n_pos_per_embd returns 4 for MROPE/IMROPE, llama-hparams.cpp:260-262) needs verification.
swiglu_oai FFN activationLikely missing β€” no SWIGLU_OAI analog found in Atlas kernels; standard SwiGLU exists in dense_ffn.rs/moe/.

---

(c) Side-by-side comparison

Featurellama.cpp mechanism (PR #27742)Atlas statusPort difficulty
Arch/config registrationLLM_ARCH_QWEN4EXP + hparams predicate tables (is_recr/is_ple/is_indexer_full)dispatch.rs + ModelCapabilities SSOTLow β€” add parser + capability flags
Gated delta netGGML_OP_GATED_DELTA_NET, per-seq recurrent rowsMature GDN kernels (decode+chunked prefill, batched, FP16 state)Low β€” reuse; validate head dims (32Γ—128) & gate formula vs reference
Recurrent state mgmtllama_memory_recurrent, uniform rows incl. PLE slotssm_pool + snapshots + tiering (better than llama.cpp)Low-Med β€” extend row layout with PLE conv slot
Hybrid memory compositionllama_memory_hybrid = KV + recurrent, layer filtersLayerType-driven layer schedulingLow
Sparse attention (top-k gather)attention gathers top-k cells from KV by indexer score; indexer cache shares attention slot layoutNo generic top-k-gather attention; DSv4 path is compressed-KV specificHigh β€” new kernel (gather-from-paged + flash over ≀512 selected blocks)
Lightning indexerGGML_OP_LIGHTNING_INDEXER + GGML_OP_TOP_K + ARGMAX chain; own MQA cache (idx_ prefix), mirrored across GPUsconfig fields only (index_topk etc.)High β€” new op + index-cache memory + top-k kernel
Hadamard Q/K/V rotationmul_mat + SRC0_IS_HADAMARD hint β†’ FWHT fast path; precomputed matrices in cache objectWHT kernels exist but only in KV-quant pathMed β€” expose wht_bf16 as a standalone transform in the attention path
mHC hyper-connectionsreuse DSV4_HC_{PRE,POST,COMB} ops, dsv4_hc_multDSv4 kernels + buffers, hc=4 hard-tuned, no learned alphaMed β€” generalize to hc=2 + per-site alpha scales; buffers already parameterized by hc_mult
PLE (per-layer embed + n-gram dilated conv)fused per_layer_token_embd tensor, GET_ROWS per layer, dilated conv state in recurrent row, ple_hist window in memory layerNothingHigh β€” new layer component + state slot + memory bookkeeping
PLE weight offload (CPU/mmap)regex --override-tensor β†’ CPU buft, mmap warning (llama-model-loader.cpp:1182-1208)no equivalent; has pinned/pack/tier machineryMed β€” add per-tensor placement policy to loader
MTP nextnn_layer_nextn, DFLASH nextn recognized for dsv4-hc modelsMTP heads incl. multi-module & DFlashLow-Med β€” wire nextn layer through existing MTP infra
Quant/conversionqwen4exp.py; PLE tensor follows token-embedding type, row-independent imatrixquant_format/ dispatcher, NVFP4/FP8/Q2 pathsMed β€” new weight_map + loader; PLE tensor quant policy
MRoPEimrope rope type, 4 pos/embdinterleaved MRoPE T/H/W streamsLow β€” verify imrope semantics against Atlas's rule (mrope_pos.rs)
swiglu_oaiGGML_GLU_OP_SWIGLU_OAI (ggml.h:627)not foundLow β€” pointwise kernel
Multi-GPU splitindexer cache mirrored (llama-model.cpp:495-498)TP/EP sharding existsLow priority (GB10 single device)

---

(d) Adoption plan for Atlas (prioritized)

Phase 1 β€” config + skeleton (no kernels).

  1. 1. Add qwen4exp to config/dispatch.rs (nested-config handling like qwen3_5_moe), new fields for PLE (ple_n_heads, ple_conv_kernel, ple_ngram_size), hc_mult reuse, index_* reuse, full_attention_interval, n_layer_nextn. Extend ModelCapabilities with has_ple, has_hyper_connections, has_sparse_attention β€” following the SSOT philosophy of capabilities.rs.
  2. 2. New model family module layers/qwen4exp/ reusing qwen3_ssm (GDN), qwen3_attention, moe components; layer-kind selection via layer_types (already the Atlas pattern).

Phase 2 β€” reuse what Atlas already does better than llama.cpp.

  1. 3. GDN: use the existing qwen3_ssm decode/prefill kernels verbatim if dims match (32 heads Γ— 128, conv kernel 4); the Atlas FLA chunked prefill and batched multi-seq decode will substantially beat llama.cpp's per-token recurrent path at batch >1. Add the PLE dilated-conv slot to the SSM row layout (ssm_reserve.rs, layer.rs::SsmLayerState) β€” copy llama.cpp's uniform-row decision (llama-hparams.cpp:206-208): reserve the slot on every recurrent layer so pool slices stay uniform and batched copies (ssm_batched_copy.rs) remain trivial.
  2. 4. mHC: generalize hyper_connection.cu + buffers/sizes.rs from DSv4 (hc=4) to Flash-Next (hc=2) and add the learned per-site alpha scales. Atlas's fixed [M, hc_mult, hidden] BF16 stream buffers map 1:1 to llama.cpp's HC ops; this is a parameterization task, not a new design.

Phase 3 β€” new ops (the genuinely hard part).

  1. 5. Indexer: implement as a fused kernel index_score_topk(q_idx, k_idx_cache, paged_slots) β†’ topk_indices[n, 512]. Adopt llama.cpp's two decisive design choices: (i) indexer cache is a 1-head MQA cache of indexer_head_size rows, allocated with the same slot layout as the main paged KV (llama-memory-hybrid-idx.cpp:114-119) β€” in Atlas this means a second block table per sequence sharing the main block allocation, so a top-k slot index is directly usable by the attention gather; (ii) Hadamard-rotate q/k before scoring β€” reuse wht_bf16.cu as a standalone transform (fused into the indexer prologue ideally), rather than llama.cpp's matmul-with-hint indirection.
  2. 6. Sparse attention gather: flash-decode/prefill variant that reads only the ≀512 gathered slots from the paged cache (Atlas's paged layout makes this *cleaner* than llama.cpp's slot-cell gather β€” indices map to (block, offset) with no compaction). Recent-window tokens (last 128) are always kept: union with the top-k set.
  3. 7. PLE layer component: per-layer GET_ROWS from per_layer_token_embd (batched embed kernel already exists), n-gram combine with dilated conv (dilation = n-gram size) over the hc_mult Γ— n_embd stream, sigmoid gate, residual add. Bookkeeping: mirror llama.cpp's ple_hist β€” the n-gram window must follow seq_rm/cp/keep semantics; in Atlas this belongs in the sequence-state manager next to the SSM pool slots, and must be snapshot/rollback-aware for spec decode (Atlas's ssm_snapshot* machinery is the right hook; llama.cpp needed [TAG_RECURRENT_ROLLBACK_SPLITS] for exactly this).
  4. 8. Small ops: swiglu_oai pointwise kernel; verify imrope against mrope_pos.rs.

Phase 4 β€” weights + serving.

  1. 9. Loader: GGUF + HF safetensors paths; fuse per_layer_token_embd into one tensor (llama.cpp convention) but place it CPU-resident by default with pinned staging β€” add a tensor-placement policy to weight_loader/ (Atlas lacks --override-tensor; pinned_pack.rs/token_overlay.rs are the natural extension point). On GB10's unified memory this is a bandwidth decision: measure row-gather-over-UVM vs pinned double-buffer; llama.cpp's mmap warning (llama-model-loader.cpp:1191-1196) shows the mmap+CPU-override trap to avoid.
  2. 10. MTP: route the nextn layer through mtp_head/ with HC-aware input (mtp_carry.rs), reusing the DFlash/DSv4-MTP precedent.
  3. 11. Validation: per-layer cosine gates against HF reference (Atlas already has this discipline β€” numeric.rs, preflight preflight/deepseek_v4.rs); add a preflight/qwen4exp.rs mirroring the DSv4 tensor-shape checks.

Where to diverge from llama.cpp: (1) do *not* copy the matmul-hint Hadamard indirection β€” fuse WHT directly; (2) llama.cpp's recurrent memory is per-sequence rows with CPU offload β€” Atlas's paged SSM pool + snapshots should absorb PLE state rather than adopting the row model; (3) llama.cpp's ubatch splitting keeps rollback tokens together β€” Atlas's CUDA-graph verify paths need the PLE window carried in the existing speculative carry buffers instead; (4) indexer-cache mirroring is irrelevant on single-device GB10 β€” skip.

---

(e) Risks and open questions

  1. 1. Top-k gather attention performance: the biggest unknown. Flash-decode over 512 scattered slots needs either a gather kernel + flash pass or an index-driven FA; llama.cpp pays for this with a huge graph-node budget (n_tokens*40, llama-context.cpp:2310) β€” Atlas's CUDA-graph capture must handle the same op-count explosion (HC + indexer + PLE per layer Γ— 48 layers).
  2. 2. PLE state under speculative rollback: llama.cpp needed explicit rollback-snapshot tagging; Atlas's ghost-token verify paths (verify_e.rs) synthesize steps β€” the PLE n-gram window and dilated conv state must be rolled back identically or acceptance/resample diverges. Highest correctness risk in the port.
  3. 3. PLE memory traffic: [n_layer Γ— n_vocab Γ— n_embd] at 256K vocab is tens of GB in BF16; even row-gathered it's ~48 embedding reads/token. Needs a quantization policy (llama.cpp keeps it at token-embedding type; Atlas could NVFP4 it β€” rows are independent, as llama.cpp's imatrix note observes, llama-quant.cpp:1283).
  4. 4. hc_mult=2 alpha scales: whether Atlas's DSv4 Sinkhorn kernels are bit-compatible at hc=2 with per-site alphas, or need a rewrite; the kernels are tuned for hc=4 (hyper_connection.cu:18).
  5. 5. imrope semantics: llama.cpp distinguishes it from mrope (llama-hparams.cpp:260-262); the exact position-stream rule must be diffed against Atlas's mrope_pos.rs before trusting vision/long-context paths.
  6. 6. Attention-layer V Hadamard (self_v_rot): applied to V *before cache write and after read* β€” the cache stores rotated V. This interacts with Atlas's TurboQuant KV (which also applies WHT before quantization): composing two rotations (or double-rotating) must be checked; likely the model's V-rotation should be fused into the existing WHT bookend rather than stacked.
  7. 7. Gate formula / norm placement in GDN: Atlas's GDN was validated against Qwen3-Next/3.5; Flash-Next's reference may differ in L2-norm placement or beta/gate details β€” needs a numerical diff before kernel reuse is assumed.
  8. 8. Conversion fidelity: conversion/qwen4exp.py is the ground truth for tensor fusion (BA packing, interleaved QKVZ vs sequential β€” Atlas already supports both modes, qwen3_ssm/mod.rs:75-78); pin the exact variant rather than auto-detecting.
P β€” prod 27B (10.9 KB) β€” 4.5/10, Atlas half unreliable

Flash-Next support: llama.cpp vs Atlas

(a) How llama.cpp implements qwen4exp (PR #27742 tree)

Architecture identity. LLM_ARCH_QWEN4EXP is registered as a *hybrid* architecture (llm_arch_is_hybrid true, llm_arch_is_recurrent false). It is grouped with QWEN3NEXT / QWEN35 / QWEN35MOE throughout the code, meaning it reuses the same "gated delta net (SSM/linear-attention) + sparse attention" block family, with two qwen4exp-specific additions: a per-token indexer cache (sparse attention over an indexer) and per-layer token embeddings (per_layer_token_embd).

Memory / cache strategy β€” the core design decision. In llama_model::create_memory (src/llama-model.cpp:2441-2536), qwen4exp is routed to a dedicated memory type:

Tensor placement / offload. The generic split logic in llama-model.cpp treats qwen4exp identically to Qwen3Next/3.5 for the SSM/delta-net tensors:

Graph / ops. The recurrent block is the standard gated-delta-net / SSM op set (ssm_in, ssm_conv1d, ssm_dt, ssm_a, ssm_alpha, ssm_beta, ssm_out, plus r_cache/s_cache state). The sparse-attention path uses the pattern_idx_cache indexer plus the normal Q/K/V attention ops. MoE experts use the ffn_gate_up_exps / ffn_down_exps fused-expert tensors (create_tensor_gate_up_exps, :3122-3128). per_layer_token_embd is handled via the generic per-layer embedding path and can be offloaded to CPU/mmap with --override-tensor.

Conversion. conversion/qwen4exp.py maps HF weights to the GGUF tensor names above (ssm_*, ssm_conv1d, ssm_dt/a/alpha/beta, ssm_out, r_cache/s_cache, idx cache, ffn_*_exps, per_layer_token_embd) and emits the GGUF keys that drive is_recr(il), indexer_head_size, ssm_d_state, ssm_n_group, ssm_dt_rank, ssm_d_conv.

Key point for Atlas: llama.cpp's whole approach is *state-centric* β€” the recurrent layers keep a fixed-size SSM state per sequence (no KV growth), the sparse layers keep a full KV + a per-token indexer, and everything is expressed as a single fused graph with per-tensor device placement. It is not paged and not batched in the vLLM/Atlas sense; batching is via the graph's seq dimension and the hybrid memory's n_seq_max/n_rs_seq bookkeeping.

(b) Atlas current status per feature

Atlas (Rust, GB10, paged/batched/GPU-first) does not yet support qwen4exp. Per feature:

(c) Side-by-side comparison

Featurellama.cpp mechanismAtlas statusPort difficulty
Recurrent gated-delta-net (SSM) blockssm_* ops + r_cache/s_cache fixed per-seq state; head-axis split (ssm_d_state,ssm_n_group,ssm_dt_rank)Missing (KV-only)High β€” new op family + new state type
Recurrent state memoryllama_memory_hybrid/_idx recurrent stream, n_rs_seqMissingHigh β€” new cache dimension
Sparse attention + per-token indexerpattern_idx_cache (mirrored) + top-k over indexer on dense layersMissingHigh β€” new cache + selection kernel
Hybrid KV+recurrent(+idx) memoryllama_memory_hybrid_idx with 3 filtersMissing (paged KV only)High β€” unify 3 state streams
MoE experts (fused gate_up/down_exps)create_tensor_gate_up_exps, per-expert scalesPartialMedium
per_layer_token_embdper-layer embedding + --override-tensor offloadMissingMedium
Quant sidecars (ssm/expert)generic .scale/.input_scale loadPartialLow–Medium
Conversion HF→GGUFconversion/qwen4exp.pyn/a (Atlas loads its own format)Medium — mapping table
Tensor placement/offloadper-tensor split axis + granularityAtlas uses paged placementMedium β€” adapt to paged model

(d) Prioritized adoption plan for Atlas

  1. 1. Add the recurrent (gated-delta-net) op family + state. Port the ssm_in β†’ ssm_conv1d β†’ (ssm_dt,ssm_a,ssm_alpha,ssm_beta) β†’ ssm_out graph and the r_cache/s_cache per-sequence fixed-size state. This is the single biggest gap. Borrow llama.cpp's head layout (ssm_d_state, ssm_n_group, ssm_dt_rank) and the lcm(blck_size,128,ssm_d_state) alignment so quant blocks don't straddle heads. *Diverge:* store the recurrent state in a contiguous per-sequence slab (not paged), since it is fixed-size β€” this is cheaper than paging and matches llama.cpp's n_rs_seq model.
  1. 2. Introduce a hybrid cache in Atlas. Extend the paged KV cache manager to also own (a) the recurrent slab and (b) the indexer cache, keyed by sequence. Keep the three llama.cpp filters (filter_attn = non-recurrent, filter_recr = recurrent, filter_idx = non-recurrent with indexer_head_size>0) as the source of truth for which layers use which stream. *Diverge:* Atlas can keep KV paged (its strength) while the recurrent + indexer streams are dense per-sequence buffers β€” do not force paging onto the fixed-size state.
  1. 3. Add sparse attention + per-token indexer. Implement the indexer cache (mirrored, single key head) and the top-k selection over it on the dense-attention layers. This is the qwen4exp-specific delta over Qwen3Next. Reuse llama.cpp's "indexer is mirrored, not sharded" decision.
  1. 4. Wire MoE experts + per-expert quant sidecars using the fused ffn_gate_up_exps/ffn_down_exps layout and the generic .scale/.input_scale sidecar loading.
  1. 5. Add per_layer_token_embd with an offload path (Atlas equivalent of --override-tensor), so the per-layer embedding table can live in host/mmap memory.
  1. 6. Conversion/mapping table for HF→Atlas weights mirroring conversion/qwen4exp.py (ssm_*, ssm_conv1d, ssm_dt/a/alpha/beta, ssm_out, r/s cache, idx cache, ffn_*_exps, per_layer_token_embd, and the GGUF keys is_recr, indexer_head_size, ssm_d_state, ssm_n_group, ssm_dt_rank, ssm_d_conv).
  1. 7. Validation: parity test against llama.cpp's qwen4exp logits on a short prompt, then a long-context test to exercise the recurrent-state vs KV divergence.

(e) Risks and open questions

Conclusion β€” the synthesized Atlas implementation plan

Cross-referencing all nine agent reports (rounds 1–3), keeping only claims verified against the actual trees, and choosing per feature whichever engine's design fits Atlas's paged/batched/GPU-first architecture.

Already in Atlas β€” don't rebuild

Mature Gated DeltaNet (layers/qwen3_ssm/) + recurrent-state pool (snapshots/spill/tiering); DSV4 mHC infra; 512-expert-capable MoE; MTP (DSV4 "reuse the layer body" precedent); MRoPE-interleaved; vision tower; quant dispatcher.

The four gaps β€” and whose design to copy

  1. Config/registration ← vLLM (Low): port Qwen4ExpConfig validators verbatim (they encode kernel invariants: MQA indexer, budget/ratio ∈ {512,2048}, ringΓ·block-size, PLE divisibility). Reuse qwen3.5 loader arms; match_names tie-break. Trap from llama.cpp: 45-bit n-gram hash multipliers are int64 β€” never fp32-cast.
  2. Hyper-connections ← Atlas infra + vLLM dataflow (High, do FIRST): add gated_residual mode to the existing mHC path; adopt vLLM's delayed-combine (β‰ˆ1 extra read+write per block instead of per mix+combine) + fused combine+RMSNorm + merged down/inject GEMM (un-TP'd, un-quantized). Changes the whole stack's tensor contract. Verify sigmoid-vs-Sinkhorn gate against the checkpoint.
  3. PLE ← llama.cpp bookkeeping, GB10 divergence on memory (Med-High): host-side n-gram hashing at graph input; ple_history in the memory layer with mirrors for every seq mutation + session serialize; dilated short-conv state stored inside the recurrent row β†’ reuses Atlas's SSM pool as a second state-kind. Table stays host-resident (mmap/UVA) β€” one GET_ROWS consumer makes it clean; GB10 coherent C2C makes it fast; production --override-tensor offload already validates it.
  4. QSA ← merge both engines (High, the long pole): llama.cpp's cell-aligned third cache (indexer keys reuse the attention cache's slot layout β€” layouts cannot drift; top-k indices transfer directly), additive-bias visibility (finite +1e9 tail, never NaN), blocks cut the position line, shared-indexer layers reuse previous top-k; plus vLLM's compressed-key cache following the main block table at 1/ratio density, fused pre-indexer kernel, weight-free block-top-k, skip_topk on draft steps, and the whole indexβ†’writeβ†’attend transaction as one opaque graph node. v1 constraints: BF16 KV, MQA indexer, no KV quant.

Phasing

PhaseWhatEffortExpected outcome
0Config + validators + factory + loader verifyLow Checkpoint parses and loads with the correct loader; all invariants enforced (bad configs fail loudly, not numerically); tensor names mapped end-to-end. No forward yet.
1HC gated_residual + delayed combine (tensor contract)High Decoder stack carries the 4-stream state; HC mix/combine unit-tests match reference numerics bit-for-bit; existing models untouched; measured HC overhead ≀ ~15% decode latency (fusions proven).
2GDN parity check + multi-state-kind poolLow–Med Hybrid GDN+attention layers run on the HC stream; GDN output matches llama.cpp goldens; state pool hosts two state kinds (GDN + short-conv) with per-spec sizing, snapshot/rollback intact.
3PLE (llama.cpp bookkeeping + host-resident table)Med-High Full forward through GDN/dense layers is token-parity with llama.cpp on fixed prompts incl. n-gram effects across chunk boundaries and after seq_rm/cp; PLE table off-GPU with <~2 GB device overhead; branch/rollback tests green.
4QSA (cell-aligned indexer + compressed cache)High β€” long pole End-to-end generation works. Quality parity with llama.cpp PR (~4.01 wikitext-2 ppl, β‰₯98% top-1 agreement); first Atlas tok/s numbers β€” target β‰₯ llama.cpp single-stream (~25 t/s) with batched upside.
5MTP scheme-A (pre-mixer multi-stream β†’ drafter) + polishMed Speculative decode live (target β‰₯1.3Γ— decode speedup); EPLB/shared-expert parity; batched serving stable β†’ production-candidate build that beats llama.cpp on concurrent throughput.

Top risks

  1. HC 4Γ— activation bandwidth β€” the fusions are mandatory; measure.
  2. Indexer RoPE bit-parity with main attention (incl. MRoPE) β€” golden-output test vs vLLM/llama.cpp.
  3. Ring/block-size invariants vs Atlas block-size policy β€” port validators so violations fail loudly.
  4. Loader mis-selection (qwen4exp vs qwen3.5/3.6 numeric ambiguity) β€” match_names guard.
  5. Cross-request state-leak surface (paged KV + GDN snapshots + PLE history + compressed pool) β€” targeted branch/rollback tests.

Round 4 β€” reviewing Atlas PR #16 (real Flash-Next implementation): A vs Claude

Atlas PR #16 actually implements qwen4exp serving (372 files, +45.6K lines, RadixArk NVFP4 on one GB10, "six silent defects" fixed). Two independent reviews of the same PR, written blind to each other: config A (Flash-Next Q4, 124 steps / 96 min / 6.17M input tokens) and Claude (~30 min of targeted reading). 2026-08-31.

A (Flash-Next Q4)Claude
DepthCode-level, exhaustive β€” 21.9 KB, all four forward shapes tracedArchitecture + narrative verification, targeted reads
Unique catchesD1 padding-row inference from ple: None (diverged call sites); D2 aux blobs excluded from the NVMe spill tier, unversioned; D3 conv-carry rewind unproven across six verify paths; D5 exact-leaf prefix hit disabled by default over a 23%-vs-60% quality regression (verified verbatim in code); dual PLE kernels with one oracle; 7 targeted pre-merge tests ATLAS_PLE_MAX_TOKENS default footgun (2048 fails a 2,191-token prompt); cross-engine grounding (vLLM/llama.cpp PLE + QSA design comparison); perf context vs llama.cpp; NVMe latency-probe suggestion
Verified accuracySpot-checks landed verbatim (23%/60% comment, GDN-deferral note, aux HashMap)All claims code-verified before writing
Verdict reachedMerge after targeted hardening (fix D1, version+tier aux blobs, land D3 test)Merge gated on CLA + PLE default fix + long-context quality gate

Honest scoring: A 9.5/10, Claude 8/10 on this task. A's review is materially deeper where it counts β€” D1/D2/D3/D5 are real pre-merge findings Claude's pass missed, and every spot-checked citation was verbatim-accurate. Claude's added value was contextual (engine comparisons, ops posture, the env-var footgun A overlooked). The reviews are complementary: union them and you have a genuinely complete PR review.

Round 4 reviews (verbatim)

A β€” Flash-Next Q4 review of PR #16 (21.9 KB) β€” 9.5/10

PR 16 review: qwen4exp serving in Atlas

Scope note: this review is based on direct reading of the PR tree (atlaspr) against atlas main across the areas that carry the correctness burden: config/buffer sizing, hyper-connections (mHC highway), PLE / n-gram embedding and its history bookkeeping, QSA sparse attention + indexer, the batched/multi-sequence and speculative (verify) dispatch paths, aux-state snapshotting (Marconi/prefix cache), and the new kernels/gb10/qwen3.8-flash-next + kernels/gb10/common kernel families. I did not execute the test suite (no GPU here); everything below is static review plus the PR's own documented measurements.

---

(a) What the PR implements, feature by feature

1. Config parsing / model registration.

The qwen4_exp model type is parsed into ModelConfig with both spellings of the stream count retained: hc_count (the checkpoint's own field name, read by the manifest and the reference crate) is *mapped onto* hc_mult (the field the engine dispatches on). Both are kept so the reference/manifest readers keep working β€” see the sizing tests in crates/spark-runtime/src/buffers/sizes.rs:611-676 (both_spellings_size_the_same_highway). Layer typing reuses the existing LinearAttention (GDN) / FullAttention (QSA) alternation, with index_topk / index_compress_ratio / index_n_heads / index_head_dim fields driving the sparse-attention path.

2. Hyper-connections (mHC, multi-stream highway).

An FP32 [n, hc_mult*H] stream highway (buffers.hc_streams()) with hc_expand / hc_pre_site / hc_post_site / hc_head_site ops, per-site weight groups (hc.attn, hc.ffn, hc.head), low-rank mixing scratch (hc_lowrank_scratch), and a HcVariant abstraction that encodes the Qwen-vs-DeepSeek-V4 divergence: on Qwen, hc_pre's grouped hc_norm *is* the block input norm, so no second RMS is applied and there is no per-layer input_layernorm (qwen3_attention/trait_impl/prefill_inner.rs:640-659, multi_seq/mod.rs:207-223). Highway sites are wired in all four forward shapes: single decode (decode_a), batched multi-seq decode (qwen3_ssm/trait_decode_multi_seq/hc.rs, qwen3_attention/trait_impl/multi_seq/mod.rs:131+), batched verify (qwen3_ssm/trait_decode_batched_hc.rs), and prefill (prefill_inner.rs).

3. Gated DeltaNet (GDN) changes.

The SSM layer (qwen3_ssm) gained an hc and a ple optional member, a per-seq SsmLayerState { …, ple: Option<PleSeqState> }, a batched-GEMM decode core (try_decode_multi_seq_ssm_batched) and a per-seq recurrence fallback, and the highway-aware multi-seq driver described above. The batched core is deliberately *not* engaged under the highway yet because its epilogues fold the residual in (trait_decode_multi_seq/hc.rs:26-29) β€” an honest, documented deferral.

4. PLE / n-gram embedding.

crates/spark-model/src/layers/ple/layer.rs + kernels/gb10/qwen3.8-flash-next/nvfp4/ple.cu (+ the kernels/gb10/common/qwen4exp_ple.cu twin): key/value projections of hashed n-gram embeddings, a highway-conditioned gate (ple_gate), a dilated depthwise causal conv with in-place rolled carry (ple_conv, state [(k_size-1)*dilation, C], FP32 chain end-to-end β€” see the PRECISION NOTE referenced in ops/ple.rs:10-16), and ple_add_highway, which injects into the FP32 highway *before* the layer's attention hyper-connection, matching the reference ordering.

History bookkeeping is the interesting part:

5. QSA sparse attention + indexer.

layers/qsa.rs + layers/qsa_select.rs: per-seq QsaSeqState lazily created via helpers::qsa_seq_state (helpers.rs:256-269); prefill *ingests* raw indexer keys per chunk (prefill_inner.rs:661-668), decode steps decode_select against them; selection is inert below index_topk + index_compress_ratio - 1 visible tokens (the "budget" bound, decode_a2.rs:127-134). Selection scratch is a fixed-address arena sized in buffers/sizes.rs:539-550 (ROWS=2048, q/k-weight + key + score-block + topk regions), with the ROWS constant duplicated in qsa_select.rs:136 β€” a coupling that should be a shared const.

6. MoE routing.

Reuses the existing event-dispatch / hash-MoE machinery (token_ids stable buffer for tid2eid), plus route-aware LoRA handling on the new paths (moe_lora_route, reject_decode_lora on multi-seq/speculative). The batched FFN ladder explicitly *refuses* shortcut-MoE models rather than silently computing an incomplete block (multi_seq/ffn.rs:41-49) β€” good fail-loud discipline.

7. MTP / speculative.

layers/qwen4exp_mtp_forward.rs, layers/deepseek_v4_mtp.rs, and the verify family (verify_a/b/c/c2/d/e/fused), with PLE/QSA hooks threaded through: per-seq prestaging, row_owner maps so the indexer advances once per row against its owner (verify_e.rs:474-481, multi_seq/mod.rs:247-289), and mapped-argmax to kill a measured 137 ms copy-engine tail stall (verify_e.rs:566-581).

8. Sequence-op bookkeeping (prefix cache / snapshots / HSS).

A new generic aux-state mechanism: Layer::{has_aux_state, snapshot_aux, restore_aux} driven by collect_aux_states / apply_aux_states / requires_aux_state (model/trait_impl/mod.rs:893-935), blobs attached to SSM snapshot slots (model/ssm_snapshot.rs:452-470), and a restore gate that declines aux-less snapshots for aux-carrying models (prefill_a.rs:155, prefill_c.rs:194, prefill_b/prefix_lookup.rs:208-211). Aux is captured at every snapshot site: chunk-boundary (prefill_b/finalize_last.rs:393-400), intermediate checkpoint (prefill_b/save_checkpoint.rs:137-146), decode Marconi checkpoint and retire-leaf (decode_checkpoint.rs:131-142, 254-263). This is the right shape for PLE history + QSA indexer keys, which a GDN-only snapshot would otherwise silently drop.

9. Kernels.

kernels/gb10/qwen3.8-flash-next/ (nvfp4 PLE chain, hc ops, GDN) and kernels/gb10/common/qwen4exp_ple.cu, with oracle/parity harnesses (layers/ops/qwen4exp_oracle_ple_tests.rs runs the *production* ple_gate β†’ ple_conv β†’ ple_add_highway chain against a reference; ple_tests.rs, qsa_tests*.rs, microtest examples under spark-model/examples/qwen4exp_microtest/).

---

(b) Design assessment vs the reference architecture

Where the PR is right, and right in a non-obvious way:

Notable divergences / debatable choices:

  1. 1. QSA selection is host-side (top-k D2H) and vetoes CUDA graphs for the whole model (decode_a.rs:247-250, decode_a2.rs:260-265). Sound correctness-wise β€” a dense-captured graph replaying after selection activates would be catastrophic β€” but it means once any sequence crosses the budget bound, *all* decode goes eager and/or per-seq. That is a large, permanent perf cliff for long-context Flash-Next serving, and it is architectural, not incidental.
  2. 2. Batched highway decode falls back to a per-seq loop whenever QSA is active (decode_a2.rs:114-136), with logits staged through the host per sequence. Correct, but the "real concurrent batches, not queued interleaving" claim is only true below the QSA inert bound or with the batched GEMM core engaged β€” and the core is explicitly *not* engaged under the highway (trait_decode_multi_seq/hc.rs:26-29). The headline capability is therefore narrower than the PR text implies.
  3. 3. The QSA "budget" model β€” index_topk interpreted as a token budget with selection inert below topk + ratio - 1 β€” is a serving shortcut: past the budget, selection activates and everything gets slow. It matches a 2048-token scratch design, but it hard-couples max effective context behavior to a buffer constant duplicated in two files.
  4. 4. hc_streams is FP32 sized by max(mult, count) β€” good β€” but the dual-spelling (hc_mult and hc_count both live on the config) is a standing foot-gun; it is defended only by tests, not by construction.

---

(c) Defects and risks

The claimed "six silent defects" β€” visible and mostly sound

I could positively identify several of the class of fixes the PR claims, and they are genuine silent-corruption fixes, not cosmetic:

  1. 1. hc_count vs hc_mult buffer sizing (sizes.rs:611-631): a model spelling the field hc_count would have received a 256-byte placeholder highway and written over neighboring buffers. Fixed with a max-of-both allocation and four tests. Sound.
  2. 2. Padded-batch vs active-length host_token_ids (trait_decode_multi_seq/hc.rs:85-112, documented in decode_a2.rs:381-394): the per-seq PLE loop bounded by padded_n indexing an active-length slice β€” previously rejected every non-boundary batch ("3 host ids for 4 seqs"). The fix (skip padding rows, which carry ple: None by construction; stay loud for a live state with no token) is correct. However β€” see D1 below.
  3. 3. Per-seq staging on the wrong stream (decode_a2.rs:147-154): staging logits copies on the scheduler's stream 0 while decode() runs on the backend default stream produced a measured two-way row swap at every C=2 step. Fixed by staging on gpu.default_stream() with copy_d2h_on_stream. Sound, and a textbook silent cross-sequence contamination bug.
  4. 4. QSA ingest desync across graph replay (verify_c.rs:186-197): the indexer's ingested counter froze at the capture step while the sequence advanced, surfacing only at the MTP gate's batch-width switch ("decode at pos 34 but 26 tokens ingested"). Fixed by extending the decode_graph_unsupported veto to the verify paths. Sound.
  5. 5. PLE prestaging missing on verify paths (verify_c.rs:199-212, verify_e.rs:421-437): without hoisting, the forward fell back to a D2H readback that invalidated the recording graph (error 901). Fixed; and the multi-seq variant in verify_e correctly windows per sequence.
  6. 6. PLE conv carry not rewindable on rejected drafts (ple/layer.rs:413-456): per-row conv launches + parked carries at verify widths. The mechanism is sound; the *rollback application* is the risk (see D3).
Defects and risks I can identify in the current code

D1 β€” Padding-row PLE skip is a correctness landmine in the graph-borrow path (medium-high).

trait_decode_multi_seq/hc.rs:98-105 treats "no ple state" as "padding row, skip". That invariant holds for the all_layer_states construction in decode_a2.rs:434-468 (ple: None for pads) and for the drain-tail graph borrow. But the same take(n) loop is used with states vectors built elsewhere (e.g. decode_batched_hc.rs:164 uses the stricter host.len() >= n check β€” the two call sites have *diverged* on the same question). If any future caller hands a live sequence whose ple field is None because its state was constructed through a different path (checkpoint restore, h_prefill_stage variants, LoRA paths), the row silently receives no PLE injection β€” degraded output with no error. The safe form is to pass the active count separately (or a per-row is_pad flag) rather than inferring padding from state contents.

D2 β€” Aux blobs live only in a host HashMap keyed by snapshot slot (high).

ssm_snapshot.rs:65, 452-470: aux (PLE n-gram history, conv carry, QSA indexer keys) is a Mutex<HashMap<usize, Vec<u8>>> in RAM. But the SSM snapshot pool has an explicit spill/fault-in tier (ssm_snapshot_spill.rs, ssm_snapshot_faultin.rs, ssm_tier/) and free() drops aux with the slot. Consequences: (i) a snapshot spilled to the NVMe tier and faulted back β€” or a process restart with tier replay β€” restores SSM state but is aux-less, so the restore gate declines it: correct, but every warm multi-turn hit that spilled silently loses its Marconi benefit; (ii) there is no versioning/serialization format, so any blob-layout change is an in-place corruption across a rolling deploy if the tier store survives; (iii) aux is cloned on every aux() read. This is the weakest data-lifecycle decision in the PR.

D3 β€” Verify conv-carry rollback: snapshot mechanism visible, rewind application not proven.

ple/layer.rs parks per-row carries into st.verify_snaps and records verify_snap_rows, and ple/verify.rs exists, but I did not find (nor a test demonstrating) the rewind being invoked on *partial* acceptance in every verify variant (verify_a/b/c/c2/d/e/fused β€” six paths; verify_e additionally has ghost/borrowed rows). If any one accept path forgets the rewind, the conv carry is over-advanced by the rejected suffix β€” a silent, slowly-accumulating quality regression that only shows up with drafts rejected mid-window, i.e. exactly the regime benchmarks don't stress. This needs a targeted test, not inspection.

D4 β€” QSA row_owner ordering is an asserted invariant, not an enforced one.

multi_seq/mod.rs:253-288: "decode_select asserts pos == ingested, so the ordering here is the invariant, not an optimization." Several rows share one sequence's state and must advance in row order. The assert exists, but the batched path also *relies on the dispatch gate agreeing* (sel.is_none() bail). Two independent mechanisms (gate + assert) guarding one property is fine, but the gate computes activity from seqs.iter().any(|s| s.seq_len >= bound) while the assert fires per-row mid-forward β€” a mismatch aborts a request in flight rather than never occurring.

D5 β€” Exact-leaf snapshot shortcut is disabled by default.

prefix_lookup.rs:299-310: the exact full-prompt hit path is force-recomputed ("ATLAS_MARCONI_EXACT=1 re-enables") because cache-on workspace quality was ~23% vs ~60% cache-off. That is an admission that the exact-hit path (including the stashed-hidden first-token trick) is still suspect on this model family. Defensible as a default, but it means the PR's prefix-cache story is materially weaker than its code volume suggests, and the disabled path still ships.

D6 β€” hc_streams FP32 at max_batch Γ— 4 Γ— H Γ— 4 bytes is a large fixed arena (e.g. 128Γ—4Γ—2560Γ—4 β‰ˆ 5 MB β€” fine on GB10, but it scales with batch and is allocated whenever either hc spelling is nonzero, including for speculative row widths r_total that exceed decode batch). Verify the arena is sized against r_total (VERIFY_ROW_CAP) and not just decode padded_n; I saw hc buffers indexed by n on the verify path with n = Ξ£ ks[i].

D7 β€” Smaller items.

---

(d) Gaps for full qwen4exp support

  1. 1. Batched GDN projections under the highway β€” the QKVZ/out_proj weight-read amortization is explicitly deferred (trait_decode_multi_seq/hc.rs:26-29); concurrent-batch bandwidth scaling is therefore not yet delivered.
  2. 2. QSA selection on the batched path β€” no per-seq indexer hook; any batch containing a past-budget sequence drops to the per-seq host-staged loop. Long-context concurrent serving is the worst case.
  3. 3. CUDA graphs are off for the whole model once QSA selection is active (host top-k D2H). A capture-safe device-side top-k is the missing piece.
  4. 4. Aux-state tiering β€” PLE/QSA blobs do not participate in the NVMe snapshot spill tier (D2); cross-restart warm restore is effectively unsupported for aux-carrying models.
  5. 5. Exact-leaf prefix hit path disabled (D5) pending quality resolution.
  6. 6. HSS (high-speed swap) + highway prefill batched mode β€” refused outright.
  7. 7. Shortcut-MoE on batched FFN β€” refused (fine if Flash-Next doesn't use it; must be stated in the recipe).
  8. 8. TP: the hc multi-seq paths do all-reduce, but the batched-highway + TP + graph interactions are barely exercised; the PR's own graph-borrow code disables borrow under comm.is_some().
  9. 9. Verify rewind coverage across all six verify variants unproven (D3).

---

(e) Verdict

Merge-ready with conditions β€” I would not merge as-is; I would merge after a short, targeted hardening pass. The architecture reading is excellent (FP32 highway, norm reuse, PLE ordering, aux-gated restore, fail-loud gates), and the silent-defect fixes I could identify are real, well-diagnosed, and soundly repaired. The residual risk is concentrated in (1) padding-row inference by state contents (D1), (2) the un-tiered, unversioned aux blob lifecycle (D2), and (3) unproven conv-carry rewind across the six verify paths (D3).

Tests I would require before merge:

  1. 1. PLE history bookkeeping across sequence ops (the single most important gap): a deterministic test that runs prompt A β†’ snapshot β†’ preempt β†’ prompt B sharing a prefix β†’ restore, and asserts token-for-token equality of greedy decode against a no-cache reference; plus the same through NVMe spill/fault-in (expected: *declined*, not wrong), and across a rolling-deploy blob version bump.
  2. 2. Verify partial-acceptance rewind: for each verify variant in use, force accept-1-of-k and accept-2-of-k patterns and assert post-verify PLE conv carry and QSA ingested equal the no-draft reference state (bitwise for conv, since it's the rewindable one).
  3. 3. Padded-batch concurrency matrix: live counts 1..padded_n at every ladder width, with ATLAS_HC_PERSEQ_DECODE on/off, asserting batched decode == per-seq decode logits within tolerance β€” this is the regression class that produced "3 host ids for 4 seqs".
  4. 4. QSA budget-boundary test: sequences straddling index_topk + ratio - 1 in one batch; assert the gate routes per-seq, no sel.is_none() bail fires, and outputs match a dense-reference for below-budget and the reference sparse selection above it.
  5. 5. Dual-kernel parity: run ple_gate vs q4e_ple_gate (and the conv/add twins) on identical inputs in CI, or delete one.
  6. 6. End-to-end parity gate against the qwen4exp_reference crate on the checkpoint: greedy prompts at lengths spanning {below budget, across budget, across a chunk boundary, across a snapshot restore}, with the quickstart recipe run as a smoke test.
  7. 7. hc arena bounds under speculative widths: ASAN/preflight assert that hc_streams/hc_post/hc_comb sizing covers r_total on the widest verify configuration.

Fix D1 (explicit pad flag), file D2 as a blocking follow-up with the blob format versioned *now* (before any tier store exists to migrate), land the D3 test, and this is a strong merge.

Claude β€” review of PR #16 β€” 8/10

PR 16 review: qwen4exp serving in Atlas (Claude's review)

(a) What it implements β€” verified in code

(b) Design assessment

Better than both reference engines on PLE memory strategy for this hardware; simpler than both on QSA (no cell-aligned third cache, no compressed-key cache) β€” defensible for v1 single-GB10; stage 2 will need one of those designs. The eight-defect narrative checks out where visible: shard-mapped rows (#1), dtype-aware strides (#2), pin-lifetime fix (#5) each carry an honest post-mortem in comments.

(c) Risks beyond the PR's own list

  1. 1. ATLAS_PLE_MAX_TOKENS default (2048) fails a 2,191-token prompt at layer 1 β€” production footgun; should be derived from the prefill chunk (8193), not an env var. Fix pre-merge.
  2. 2. Long-context quality unproven where QSA actually activates (>2051): prefill-dense/decode-sparse asymmetry + the measured 0.37-nat top-20 KL drift are each fine alone; their interaction at 8K+ is unevaluated.
  3. 3. Multi-stream + QSA-active untested (the C=4 result likely ran in the inert regime); selection is single-sequence in v1.
  4. 4. NVMe-mount hazard documented but unguarded β€” add a startup read-latency probe with a hard warn.

(d) Verdict

Merge-worthy engineering, gated on: CLA, the PLE scratch default fix, a long-context (>2051) quality gate, and tap-diff in CI on a slice checkpoint. The evidence culture (bitwise-determinism control, independent reproduction, honest known-not-done) is the best seen in this evaluation. Perf context: 14.5–16.5 tok/s single NVFP4 trails llama.cpp's ~25 (Q3 GGUF), but 28.4 aggregate @4 streams is the batching llama.cpp can't do β€” Atlas's reason to exist.

Round 5 β€” from analysis to shipped PR (the orchestration program)

The capstone: Claude as orchestrator/reviewer, spark's models as executors, turning the round-4 review findings into real patches against Atlas PR #16 β€” culminating in PR #17. 2026-08-31 β†’ 09-01.

The program

#ItemExecutorOutcome
1RadixArk NVFP4 checkpoint (126 GB, 206 shards) verifyorchestrator + agentβœ… SERVE-READY (all config fields match parser)
2Build PR #16 tree on GB10agent diagnose + orchestrator verifyβœ… (found CUDARC_CUDA_VERSION convention; NCCL link dep harvested from container)
3πŸ§ͺ Gate 1: quickstartorchestratorβœ… 7/7 coherence Β· 6/6 tools Β· 17.0 / 36.5 tok/s β€” above the author's 14.5 / 28.4 (3rd independent GB10)
4PLE docs staleness fix27Bβœ… 12 steps, 88 s β€” after discovering the intended code fix already existed in the PR
5QSA scratch-rows shared const27Bβœ… textbook diff, lint-aware
6πŸ§ͺ Gate 2: regressionorchestratorβœ… on rerun (first run lost a temp-1.0 sampling dice roll β€” probes are stochastic by design)
7Explicit padding-row accounting (review finding D1)27B plan Γ—2 β†’ A executesβœ… 8-file behavioral fix + negative test; 654 tests green
8PLE rewind partial-acceptance test (D3)A Γ—4❌ not landed β€” fully specced (seam proven CPU-observable), attached as suggested test
9πŸ§ͺ Gate 3: cuda suite + quickstartorchestratorβœ… after fixing a pre-existing doctest failure the gate itself exposed

Shipped: PR #17 (4 droppable commits onto feat/qwen4exp-serve)

  1. docs: PLE scratch sizing notes aligned with the shipped derived-floor behavior (recipe + 2 scripts)
  2. qsa: QSA_SELECT_SCRATCH_ROWS β€” one authoritative constant (was duplicated with a "must agree" comment)
  3. hc decode: explicit active_seqs threading β€” a live row with no PLE carry now fails loudly instead of silently losing its n-gram injection; includes a MockGpuBackend negative test
  4. docs: fault_threads timing table fenced as text (was compiled as a Rust doctest and failing --doc)

Status at time of writing: CLA signed βœ…; five CI workflows awaiting first-time-contributor approval from the maintainer.

What the program taught us (the lasting part)

The harness (verbatim source)

Everything above was produced by two small Python programs driving llama.cpp's OpenAI-compatible endpoint through LangGraph, plus bash drivers (server lifecycle: stop prod β†’ serve config β†’ run β†’ trap-restore prod). The research agent below is the round-2 version; rounds 3–4 are the same program with the repo pair, marker and system prompt swapped. Full archive on spark: ~/agentbench/ (agents, briefs, per-item traces) and ~/driver_*.sh.

research agent β€” LangGraph ReAct over code repos (rounds 2–4) Β· agent2.py
#!/usr/bin/env python3
# Agentic shootout round 2: compare vLLM's Flash-Next implementation (PR #53896 branch)
# with Atlas, produce an adoption plan. usage: agent2.py <base_url_v1> <label>
import json, os, subprocess, sys, time

from langchain_core.tools import tool
from langchain_core.messages import HumanMessage, AIMessage, ToolMessage
from langchain_openai import ChatOpenAI
from langgraph.prebuilt import create_react_agent

BASE = sys.argv[1]
LABEL = sys.argv[2]
REPOS = {"atlas": os.path.expanduser("~/agentbench/atlas"),
         "vllm": os.path.expanduser("~/agentbench/vllm")}
OUT = os.path.expanduser(f"~/agentbench/out2/{LABEL}")
os.makedirs(OUT, exist_ok=True)
trace = open(f"{OUT}/trace.jsonl", "a")
T0 = time.time()
MARKER = "# Flash-Next support: vLLM vs Atlas"


def _safe(repo: str, path: str) -> str:
    root = REPOS.get(repo)
    if not root:
        raise ValueError("repo must be 'atlas' or 'vllm'")
    p = os.path.normpath(os.path.join(root, path.lstrip("/")))
    if not p.startswith(root):
        raise ValueError("path escapes repo")
    return p


@tool
def list_dir(repo: str, path: str = ".") -> str:
    """List files/directories at a path inside a repository. repo is 'atlas' (Rust inference
    engine) or 'vllm' (Python, checked out at the Flash-Next support PR #53896 branch).
    Directories end with '/'."""
    p = _safe(repo, path)
    if not os.path.isdir(p):
        return f"not a directory: {repo}:{path}"
    out = []
    for e in sorted(os.listdir(p)):
        if e in (".git", "target", "__pycache__"):
            continue
        full = os.path.join(p, e)
        out.append(e + "/" if os.path.isdir(full) else f"{e} ({os.path.getsize(full)}b)")
    return "\n".join(out[:200]) or "(empty)"


@tool
def read_file(repo: str, path: str, start_line: int = 1) -> str:
    """Read up to 200 lines of a file in repo 'atlas' or 'vllm', starting at start_line (1-based).
    Call again with a higher start_line to continue."""
    p = _safe(repo, path)
    if not os.path.isfile(p):
        return f"not a file: {repo}:{path}"
    try:
        lines = open(p, errors="replace").read().splitlines()
    except Exception as e:
        return f"error: {e}"
    s = max(1, int(start_line)) - 1
    chunk = lines[s:s + 200]
    body = "\n".join(f"{s+i+1}: {l[:400]}" for i, l in enumerate(chunk))
    more = f"\n... file has {len(lines)} lines total" if len(lines) > s + 200 else "\n(end of file)"
    return (body or "(empty)") + more


@tool
def search_code(repo: str, pattern: str, subdir: str = ".") -> str:
    """Search a repository ('atlas' or 'vllm') for a regex pattern (grep -rn, case-insensitive).
    Returns up to 60 matching lines as path:line:text."""
    p = _safe(repo, subdir)
    try:
        r = subprocess.run(
            ["grep", "-rniI", "--include=*.rs", "--include=*.py", "--include=*.cu",
             "--include=*.cuh", "--include=*.toml", "--include=*.md",
             "--exclude-dir=.git", "--exclude-dir=target", "--exclude-dir=__pycache__",
             "-e", pattern, p],
            capture_output=True, text=True, timeout=60)
    except subprocess.TimeoutExpired:
        return "search timed out; use a narrower pattern or subdir"
    total = len(r.stdout.splitlines())
    lines = [l.replace(REPOS[repo] + "/", f"{repo}:")[:300] for l in r.stdout.splitlines()[:60]]
    tail = f"\n... {total} total matches (showing 60)" if total > 60 else ""
    return ("\n".join(lines) or "no matches") + tail


@tool
def read_flashnext_reference() -> str:
    """Read the Qwen3.8-Flash-Next (qwen4exp) architecture reference: every feature an
    inference engine must implement to run this model."""
    return open(os.path.expanduser("~/agentbench/flashnext_reference.md")).read()


SYSTEM = """You are a senior systems engineer. Two codebases are available through your tools:
- repo 'vllm' (Python): vLLM checked out at the branch of PR #53896, which ADDS Qwen3.8-Flash-Next (qwen4exp) support. This is a real, working implementation. Key areas to find: model definition, config conversion, Gated DeltaNet integration, QSA sparse attention + indexer, per-layer n-gram (PLE) embedding handling, hyper-connections, MoE routing, MTP. (Separate open PRs #53899/#54129/#54371 add PLE offload via UVA/mmap; they are NOT in this tree, but PLE handling in this tree shows the baseline.)
- repo 'atlas' (Rust): the Atlas inference engine for NVIDIA GB10, which does NOT yet support qwen4exp.

Your goal: a comparative implementation analysis that tells the Atlas team exactly how to add Flash-Next support, using vLLM's implementation as the blueprint.

Method:
1. Read the Flash-Next architecture reference.
2. In 'vllm': locate and READ the qwen4_exp implementation (search for qwen4_exp, flash_next, deltanet, qsa, indexer, ngram, ple, hyper). Understand HOW each architectural feature is implemented: dataflow, caching strategy, kernels/ops used, config plumbing.
3. In 'atlas': determine per feature what exists, partially exists, or is missing (search for: gated delta, ssm, moe, expert, sparse, indexer, hyper_connection, mtp, ngram, per_layer).
4. Compare: for each feature, how vLLM does it vs what Atlas would need.

IMPORTANT OUTPUT RULE: when quoting chat-template or special tokens, ALWAYS write them with square brackets (e.g. [think], [/tool_call], [IM_START]) β€” NEVER with literal angle brackets, which corrupt the transport.

When (and only when) research is complete, output the final report in markdown, starting exactly with:
# Flash-Next support: vLLM vs Atlas

Report sections: (a) how vLLM implements qwen4exp β€” feature by feature, with file citations; (b) Atlas current status per feature, with file citations; (c) side-by-side comparison table (feature | vLLM mechanism | Atlas status | port difficulty); (d) a concrete, prioritized adoption plan for Atlas that borrows vLLM's design decisions where sensible (and diverges where Rust/GB10 constraints demand); (e) risks and open questions."""

TASK = ("Compare vLLM's Qwen3.8-Flash-Next implementation (PR #53896 tree) with Atlas and produce "
        "the comparative gap analysis and Atlas adoption plan.")

llm = ChatOpenAI(
    base_url=BASE, api_key="x", model="qwen",
    temperature=0.3, max_tokens=10240, timeout=3600,
    extra_body={"chat_template_kwargs": {"enable_thinking": False}},
)
tools = [read_flashnext_reference, list_dir, read_file, search_code]


def prune(state):
    msgs = state["messages"]
    head, tail = msgs[:1], msgs[1:]
    budget = 150_000
    kept, size = [], 0
    for m in reversed(tail):
        c = m.content if isinstance(m.content, str) else json.dumps(m.content)
        size += len(c)
        kept.append(m)
        if size > budget:
            break
    kept = list(reversed(kept))
    while kept and isinstance(kept[0], ToolMessage):
        kept.pop(0)
    out = head + kept
    if len(msgs) > 260:
        out = out + [HumanMessage(
            "You have used a very large number of research steps. Finish up: stop calling tools and "
            f"write the complete final report NOW, starting with '{MARKER}'.")]
    return {"llm_input_messages": out}


agent = create_react_agent(llm, tools, prompt=SYSTEM, pre_model_hook=prune)

steps = tool_calls = 0
in_tok = out_tok = 0
report = None
messages = [HumanMessage(TASK)]
last_msgs = messages

try:
    for chunk in agent.stream({"messages": messages},
                              config={"recursion_limit": 400}, stream_mode="values"):
        last_msgs = chunk["messages"]
        m = last_msgs[-1]
        if isinstance(m, AIMessage):
            steps += 1
            u = getattr(m, "usage_metadata", None) or {}
            in_tok += u.get("input_tokens", 0)
            out_tok += u.get("output_tokens", 0)
            calls = [tc["name"] for tc in (m.tool_calls or [])]
            tool_calls += len(calls)
            content = m.content if isinstance(m.content, str) else ""
            trace.write(json.dumps({"t": round(time.time() - T0, 1), "step": steps,
                                    "tools": calls, "in": u.get("input_tokens", 0),
                                    "out": u.get("output_tokens", 0),
                                    "content_head": content[:150]}) + "\n")
            trace.flush()
            print(f"[{LABEL} step {steps}] t={time.time()-T0:.0f}s tools={calls} "
                  f"in={u.get('input_tokens',0)} out={u.get('output_tokens',0)}", flush=True)
            if MARKER in content:
                report = content
except Exception as e:
    print(f"[{LABEL}] agent loop ended: {type(e).__name__}: {str(e)[:200]}", flush=True)

if report is None:
    print(f"[{LABEL}] forcing final report", flush=True)
    try:
        from langchain_core.messages import SystemMessage
        pruned = prune({"messages": list(last_msgs)})["llm_input_messages"]
        # call the RAW llm with no tools bound: it physically cannot call tools
        final_msg = llm.invoke(
            [SystemMessage(SYSTEM)] + pruned + [HumanMessage(
                "Research is over. Using everything gathered above, write the complete final report "
                f"immediately. Start with '{MARKER}'.")])
        if isinstance(final_msg.content, str) and len(final_msg.content) > 1000:
            report = final_msg.content
            u = getattr(final_msg, "usage_metadata", None) or {}
            in_tok += u.get("input_tokens", 0); out_tok += u.get("output_tokens", 0)
    except Exception as e:
        print(f"[{LABEL}] force-final failed: {e}", flush=True)

wall = time.time() - T0
if report:
    open(f"{OUT}/report.md", "w").write(report)
summary = {"label": LABEL, "wall_s": round(wall, 1), "llm_steps": steps, "tool_calls": tool_calls,
           "input_tokens": in_tok, "output_tokens": out_tok,
           "gen_tps_overall": round(out_tok / wall, 2) if wall else 0,
           "report": bool(report), "report_chars": len(report or "")}
open(f"{OUT}/summary.json", "w").write(json.dumps(summary, indent=1))
print(f"=== AGENT_SUMMARY {json.dumps(summary)}", flush=True)
print(f"=== AGENTBENCH2_DONE {LABEL} ===", flush=True)
executor agent β€” edit/write/cargo tools, budgeted work items (round 5) Β· agent5.py
#!/usr/bin/env python3
# Executor agent: carries out ONE work item on the Atlas PR-16 work tree.
# usage: agent5.py <base_url_v1> <item_id> <brief_path>
# Budget: 50 agent turns. Orchestrator reviews the diff afterwards.
import json, os, subprocess, sys, time

from langchain_core.tools import tool
from langchain_core.messages import HumanMessage, AIMessage, ToolMessage, SystemMessage
from langchain_openai import ChatOpenAI
from langgraph.prebuilt import create_react_agent

BASE = sys.argv[1]
ITEM = sys.argv[2]
BRIEF_PATH = sys.argv[3]
WORK = os.path.expanduser("~/agentbench/atlas-work")
OUT = os.path.expanduser(f"~/agentbench/items/{ITEM}")
os.makedirs(OUT, exist_ok=True)
trace = open(f"{OUT}/trace.jsonl", "a")
T0 = time.time()
MARKER = "# ITEM COMPLETE"


def _safe(path: str) -> str:
    p = os.path.normpath(os.path.join(WORK, path.lstrip("/")))
    if not p.startswith(WORK):
        raise ValueError("path escapes the work tree")
    return p


@tool
def read_brief() -> str:
    """Read this work item's brief: the goal, constraints, and acceptance criteria."""
    return open(BRIEF_PATH).read()


@tool
def list_dir(path: str = ".") -> str:
    """List files/directories at a path in the work tree."""
    p = _safe(path)
    if not os.path.isdir(p):
        return f"not a directory: {path}"
    out = []
    for e in sorted(os.listdir(p)):
        if e in (".git", "target", "__pycache__"):
            continue
        full = os.path.join(p, e)
        out.append(e + "/" if os.path.isdir(full) else f"{e} ({os.path.getsize(full)}b)")
    return "\n".join(out[:200]) or "(empty)"


@tool
def read_file(path: str, start_line: int = 1) -> str:
    """Read up to 200 lines of a file in the work tree, starting at start_line (1-based)."""
    p = _safe(path)
    if not os.path.isfile(p):
        return f"not a file: {path}"
    lines = open(p, errors="replace").read().splitlines()
    s = max(1, int(start_line)) - 1
    chunk = lines[s:s + 200]
    body = "\n".join(f"{s+i+1}: {l[:400]}" for i, l in enumerate(chunk))
    more = f"\n... file has {len(lines)} lines total" if len(lines) > s + 200 else "\n(end of file)"
    return (body or "(empty)") + more


@tool
def search_code(pattern: str, subdir: str = ".") -> str:
    """Search the work tree for a regex pattern (grep -rn, case-insensitive), up to 60 hits."""
    p = _safe(subdir)
    r = subprocess.run(
        ["grep", "-rniI", "--include=*.rs", "--include=*.toml", "--include=*.cu",
         "--include=*.py", "--include=*.sh", "--include=*.yaml", "--include=*.md",
         "--exclude-dir=.git", "--exclude-dir=target", "-e", pattern, p],
        capture_output=True, text=True, timeout=60)
    total = len(r.stdout.splitlines())
    lines = [l.replace(WORK + "/", "")[:300] for l in r.stdout.splitlines()[:60]]
    tail = f"\n... {total} total matches (showing 60)" if total > 60 else ""
    return ("\n".join(lines) or "no matches") + tail


@tool
def edit_file(path: str, old: str, new: str) -> str:
    """Edit a file by exact string replacement. `old` must appear EXACTLY ONCE in the file
    (include enough surrounding lines to make it unique). Returns ok or a precise error."""
    p = _safe(path)
    if not os.path.isfile(p):
        return f"not a file: {path}"
    src = open(p, errors="replace").read()
    n = src.count(old)
    if n == 0:
        return "ERROR: `old` not found β€” re-read the file and copy the text exactly"
    if n > 1:
        return f"ERROR: `old` appears {n} times β€” include more context to make it unique"
    open(p, "w").write(src.replace(old, new, 1))
    return f"ok: replaced 1 occurrence in {path}"


@tool
def write_file(path: str, content: str) -> str:
    """Create or overwrite a file in the work tree (use for NEW files, e.g. tests)."""
    p = _safe(path)
    os.makedirs(os.path.dirname(p), exist_ok=True)
    open(p, "w").write(content)
    return f"ok: wrote {len(content)} bytes to {path}"


@tool
def cargo(command_line: str) -> str:
    """Run cargo in the work tree. Pass the full cargo arguments as one string in `command_line`.
    Allowed subcommands: check, build, test, fmt, metadata. You may prefix whitelisted
    env assignments (CUDARC_CUDA_VERSION, ATLAS_SKIP_BUILD, ATLAS_TARGET_HW/MODEL/QUANT, RUST_BACKTRACE).
    Example: command_line='CUDARC_CUDA_VERSION=13000 check --workspace'."""
    parts = command_line.split()
    env = dict(os.environ)
    env["PATH"] = os.path.expanduser("~/.cargo/bin") + ":" + env.get("PATH", "")
    ALLOWED_ENV = ("CUDARC_CUDA_VERSION", "ATLAS_SKIP_BUILD", "ATLAS_TARGET_HW",
                   "ATLAS_TARGET_MODEL", "ATLAS_TARGET_QUANT", "RUST_BACKTRACE")
    while parts and "=" in parts[0] and not parts[0].startswith("-"):
        k, _, v = parts[0].partition("=")
        if k not in ALLOWED_ENV:
            return f"ERROR: env var {k} not in whitelist {ALLOWED_ENV}"
        env[k] = v
        parts = parts[1:]
    if not parts or parts[0] not in ("check", "build", "test", "fmt", "metadata"):
        return "ERROR: only check/build/test/fmt/metadata are allowed"
    try:
        r = subprocess.run(["cargo"] + parts, cwd=WORK, capture_output=True, text=True,
                           timeout=3600, env=env)
    except subprocess.TimeoutExpired:
        return "ERROR: cargo timed out after 3600s"
    out = (r.stdout + "\n" + r.stderr).strip()
    lines = out.splitlines()
    if len(lines) > 120:
        out = "\n".join(lines[:20]) + f"\n... [{len(lines)-80} lines elided] ...\n" + "\n".join(lines[-60:])
    return f"exit={r.returncode}\n{out}"


@tool
def git_diff() -> str:
    """Show the current uncommitted diff of the work tree (your changes so far)."""
    r = subprocess.run(["git", "diff", "--stat"], cwd=WORK, capture_output=True, text=True)
    r2 = subprocess.run(["git", "diff"], cwd=WORK, capture_output=True, text=True)
    d = r2.stdout
    if len(d) > 12000:
        d = d[:12000] + "\n... [diff truncated]"
    return r.stdout + "\n" + d


SYSTEM = """You are a senior Rust engineer executing ONE scoped work item on the Atlas inference
engine (work tree = the PR #16 qwen4exp branch). Read the brief FIRST (read_brief), then do exactly
what it asks β€” no scope creep, no drive-by refactors. The diff you leave will be reviewed by a human
orchestrator and become a standalone PR, so keep it minimal, correct, and in the codebase's own style
(match the surrounding comment density and naming).

Rules:
- Verify claims by reading code, not by assumption.
- After editing, run the brief's acceptance commands (cargo check/test as specified) and fix what breaks.
- You have a budget of ~50 turns. Leave time to verify.
- When (and only when) the item is done and verified, output a summary starting exactly with:
# ITEM COMPLETE
containing: what changed (files), why, how it was verified (commands + results), and anything the
reviewer must double-check."""

llm = ChatOpenAI(
    base_url=BASE, api_key="x", model="qwen",
    temperature=0.2, max_tokens=8192, timeout=3600,
    extra_body={"chat_template_kwargs": {"enable_thinking": False}},
)
tools = [read_brief, list_dir, read_file, search_code, edit_file, write_file, cargo, git_diff]


def prune(state):
    msgs = state["messages"]
    head, tail = msgs[:1], msgs[1:]
    budget = 140_000
    kept, size = [], 0
    for m in reversed(tail):
        c = m.content if isinstance(m.content, str) else json.dumps(m.content)
        size += len(c)
        kept.append(m)
        if size > budget:
            break
    kept = list(reversed(kept))
    while kept and isinstance(kept[0], ToolMessage):
        kept.pop(0)
    out = head + kept
    if len(msgs) > int(os.environ.get("ITEM_NUDGE_MSGS", "80")):
        out = out + [HumanMessage(
            f"Budget nearly exhausted. Finish verification and output the summary NOW, starting with '{MARKER}'.")]
    return {"llm_input_messages": out}


# pin the brief into the system prompt so context pruning can never evict it
SYSTEM = SYSTEM + "\n\n===== THE WORK ITEM BRIEF (authoritative, do exactly this) =====\n" + open(BRIEF_PATH).read()

agent = create_react_agent(llm, tools, prompt=SYSTEM, pre_model_hook=prune)

steps = 0
in_tok = out_tok = 0
report = None
messages = [HumanMessage("Execute the work item described by read_brief().")]
last_msgs = messages

try:
    for chunk in agent.stream({"messages": messages},
                              config={"recursion_limit": int(os.environ.get("ITEM_RECURSION", "100"))}, stream_mode="values"):
        last_msgs = chunk["messages"]
        m = last_msgs[-1]
        if isinstance(m, AIMessage):
            steps += 1
            u = getattr(m, "usage_metadata", None) or {}
            in_tok += u.get("input_tokens", 0)
            out_tok += u.get("output_tokens", 0)
            calls = [tc["name"] for tc in (m.tool_calls or [])]
            content = m.content if isinstance(m.content, str) else ""
            trace.write(json.dumps({"t": round(time.time()-T0, 1), "step": steps, "tools": calls,
                                    "in": u.get("input_tokens", 0), "out": u.get("output_tokens", 0),
                                    "head": content[:120]}) + "\n")
            trace.flush()
            print(f"[{ITEM} step {steps}] t={time.time()-T0:.0f}s {calls}", flush=True)
            if MARKER in content:
                report = content
except Exception as e:
    print(f"[{ITEM}] loop ended: {type(e).__name__}: {str(e)[:200]}", flush=True)

if report is None:
    print(f"[{ITEM}] forcing summary", flush=True)
    try:
        pruned = prune({"messages": list(last_msgs)})["llm_input_messages"]
        fm = llm.invoke([SystemMessage(SYSTEM)] + pruned + [HumanMessage(
            f"Time is up. Output the item summary NOW, starting with '{MARKER}'. State honestly what is done and what is not.")])
        if isinstance(fm.content, str):
            report = fm.content
    except Exception as e:
        print(f"[{ITEM}] force-final failed: {e}", flush=True)

if report:
    open(f"{OUT}/summary.md", "w").write(report)
print(f"=== ITEM_STATS {json.dumps({'item': ITEM, 'wall_s': round(time.time()-T0,1), 'steps': steps, 'in': in_tok, 'out': out_tok, 'summary': bool(report)})}", flush=True)
print(f"=== ITEM_DONE {ITEM} ===", flush=True)

Final conclusions of this research

The funnel: benchmark wide β†’ select β†’ harness

None of the stages above were isolated experiments β€” they were a selection funnel, each stage cutting candidates and feeding what survived into a harder test, until the survivor was put to work on a real deliverable:

StageFieldCut / decisionWhat it taught the next stage
1. Feasibility screen6 configs (P, A, B, C, D, E) Γ— 3 enginesD out (vLLM can't load qwen4_exp), C out (12.5 tok/s), B dominated by Athe working recipes + the stop-prod rule (unified memory)
2. Capability benchesP, E2, Anone cut β€” profiles built: prod fastest, Flash-Next best craft; no-think mandatoryprompts, budgets and sampling for agentic work
3. Agentic research Γ—3P, E2, A on real codebasesP out for long-horizon work (never terminates, pruning amnesia); E2 β‰ˆ A, A most consistentverification-first grading; wrap-up pressure; token-escape rule
4. External calibrationA vs Claude on a 45K-line PRA confirmed at/above strong-reviewer level (9.5 vs 8)the exact defect list that became the work items
5. SelectionA (Q4) chosen as sole executor β€” by measured behavior, not benchmark folklore; 27B kept briefly as investigator, then retired
6. Harness & deliveryA + orchestrator/reviewer9 items, 3 hardware gates, task-shaped budgetsshipped: Atlas PR #17, 4 verified fixes on a real engine
Stage 1 Β· Feasibility β€” single-stream decode, tok/sP: 44.5 β€” keptP44.5E2: 27.0 β€” keptE227A: 25.1 β€” SELECTEDA25.1B: 25.1 β€” cutB25.1 βœ• cutC: 12.5 β€” cutC12.5 βœ• cutD: did not load β€” cutDDNF βœ• cutcut: D (engine can't load qwen4_exp) Β· C (12.5, too slow) Β· B (identical to A with less context)Stage 2 Β· Capability β€” long-prompt prefill, tok/sP: 720.6 β€” keptP720.6E2: 475.0 β€” keptE2475A: 465.7 β€” SELECTEDA465.7no cut β€” profiles built: P fastest, Flash-Next best craft; no-think made mandatoryStage 3 Β· Agentic research β€” verified grade, avg of rounds 2–3 (/10)A: 9.25 β€” SELECTEDA9.25E2: 8.0 β€” keptE28P: 5.0 β€” cutP5 βœ• cutcut: P β€” never self-terminates, context-pruning amnesiaStage 4 Β· External calibration β€” PR #16 review grade (/10)A: 9.5 β€” SELECTEDA9.5Claude: 8.0 β€” keptClaude8A confirmed at/above strong-reviewer levelSELECTED: A β€” Flash-Next Q4β†’ shipped Atlas PR #17 Β· 4 commits Β· gates 3/3 Β· 654 tests greenA β€” the selectionin the runningeliminated at this stage (βœ•)

The point of the funnel: benchmarks were never the product β€” they were selection pressure. Every number earned its keep by deciding something (a config cut, a budget set, a role assigned), and by stage 6 the choice of executor, its turn budget, its sampling mode, and even its prompt hygiene were all decisions the earlier stages had already paid for. That is the reusable method: screen wide on your own hardware β†’ profile on tasks shaped like your real work β†’ select on verified behavior β†’ spend the harness engineering on the survivor.

  1. A local model on a $4K box did real engineering work. Qwen3.8-Flash-Next Q4 (GGUF, llama.cpp, 128 GB unified memory) produced citation-verified code analyses at staff-engineer depth, out-reviewed Claude on a 45K-line Rust PR (9.5 vs 8), and wrote code that shipped in a real upstream PR β€” four days after the model's release.
  2. Model personalities are stable, task-shaped, and exploitable. Across every round: the 27B is a fast, honest investigator that never voluntarily stops and suffers pruning amnesia; the 125B is slower but self-terminates and finishes. The winning org chart used both: 27B investigates β†’ plan frozen into the brief β†’ 125B executes β†’ orchestrator verifies.
  3. Quant fidelity (Q3 vs Q4) was not measurable in outcomes; trajectory variance was. The same model flipped ranks between rounds purely on which files its first steps happened to open. One run is a sample size of one β€” verify artifacts, not reputations.
  4. Prefill economics rule agentic work. Research runs consumed 1–6.5M input tokens against 5–24K output; the engine's long-prompt prefill rate (720 vs ~470 tok/s here) mattered more than the headline decode number.
  5. Verification is the product. Every grade in this report came from checking citations against the actual trees and re-running every claimed command. That process caught two confabulated reports, one fabricated verification, and β€” equally β€” proved the best reports correct to the line number. Models' honesty was excellent (seven self-reported "NOT DONE"s); their green checkmarks required re-execution.
  6. The harness is half the system. The decisive fixes were never model upgrades: task-shaped budgets (~50 turns for edits, ~150 for tests), briefs pinned into the system prompt, a toolless forced-finale, special-token escaping, and mangle-proof tool parameter names. Same models, different harness β€” different outcomes.
  7. Ecosystem reality check: at day-1 for a new architecture, both llama.cpp and vLLM support lived in unmerged PRs; the practical path on this hardware was community GGUFs + a patched build. Independent reproduction (ours was the third GB10) is what turns a claim into a fact β€” and this page exists so the next reproduction is cheaper.
BMO from Adventure Time swapping his own batteries

self-maintenance, as demonstrated by the field's true pioneer  Β·  via Tenor