[GH-ISSUE #5093] [Engine] CUDA DMA empty-group notification can release staged experts before uploads finish (NaN repro) #2379

Open
opened 2026-11-04 01:58:49 +07:00 by bsakaguchi · 2 comments
Owner

Originally created by @AlanJager on GitHub (Nov 3, 2026).
Original GitHub issue: https://github.com/Niko1221/Strata/issues/5093

Area

[Engine] (CUDA DMA expert staging and completion ordering)

Desktop app, Terminal or source?

Source build.

Strata version

Engine 0.1.56, commit ffa80d7313 (also current main when filing).

Graphics card, memory and system

RTX 3090 24GiB (sm_86), 64GiB guest RAM, 32 vCPU Xeon Platinum 8260; Linux 5.15.0-161-generic / KVM, CUDA 12.8, NVIDIA driver 580.126.09. Full model/configuration and measured controls are below.

What happened

Reproduced locally: in explicit CUDA --pcie-mode dma, a later empty PCIe group can publish a larger cumulative flagB while an earlier group's H2D copy is still in flight. The GPU's flagB >= ring wait then passes before its expert weights are ready.

On an RTX 3090, I captured an expert blob containing a correct current-layer prefix and a stale previous-layer suffix. Both portions were independently matched against the original GGUF. With the captured real activation and the original expert kernel, replaying this blob produces 401 nonfinite outputs; replacing only that expert's weights with the correct blob produces zero. The bad replay is bit-identical to the observed expert output.

Expected: a cumulative completion value implies that all preceding uploads have completed. Actual: the empty-group fast path bypasses that ordering.

Related symptom discussion: #879. This report isolates one CUDA DMA failure mechanism; it does not attribute every failure in #879 to it. Main was rechecked before filing and is still the tested commit below.

Source and ordering

At Verifier::fetch_dma:

const uint32_t want = v->cur_layer_ + 1;
if (n <= 0) { raise_flag(v->h_flagB_, want); return; }

// Nonempty path: enqueue uploads, then enqueue the flag callback on copy_.
cudaMemcpyAsync(..., v->copy_);
cudaLaunchHostFunc(v->copy_, ...);

The GPU consumes the PCIe expert groups after a wait_flag_ge. Its implementation spins while *flag < value. raise_flag implements a monotonic maximum; it does not track gaps in completion.

The two-group window schedule intentionally prepares work ahead of consumption. A later plan can therefore be served while an earlier DMA remains pending. Here, empty means zero PCIe expert blobs for this group, not zero preceding work.

Normal: notify through the copy stream

The values 60 and 61 below are completion sequence numbers, not layer numbers.

sequenceDiagram
    participant H as CPU scheduler
    participant D as DMA copy stream
    participant G as GPU compute stream
    H->>D: Enqueue expert upload for sequence 60
    H->>D: Enqueue callback publishing B=60
    G->>G: Compute resident experts
    G->>G: Wait for B at least 60
    D->>D: Finish the upload
    D->>G: Callback publishes B=60
    G->>G: Consume complete expert weights

Failure: empty group publishes outside that stream

sequenceDiagram
    participant H as CPU scheduler
    participant D as DMA copy stream
    participant G as GPU compute stream
    H->>D: Enqueue upload and completion callback for 60
    Note over D: Upload is still pending
    H->>H: Serve later group 61 with zero PCIe blobs
    H->>G: Directly publish B=61
    G->>G: Wait for B at least 60 passes
    G->>G: Read partially updated staging weights
    D-->>G: Callback for 60 executes too late
    Note over G: B stays 61 because publication is monotonic

Captured bytes explain the first expert NaN

Decisive capture: pos=96, T=12, step=59, layer=29, group=1. The consumer needs sequence 60, but sees B=61 while this group's completion callback has not run (completion_seen=0).

The selected blob is layer 29, expert 222, 1,305,600 bytes, with IQ2_XXS gate/up and Q2_0 down. The correct CPU copy equals the corresponding gate/up/down ranges in the original GGUF in full; SHA256:

65edb34bc11a1bba95b38580f2c77794bbf9f67fa112c610afa10d49c7dd087b

The captured staging blob has these independently verified sources (half-open byte ranges):

Captured range Exact GGUF source Full range equal?
[0, 1007616) Current layer 29, expert 222, same offsets Yes
[1007616, 1024000) Previous layer 28, expert 277, [1494016, 1510400) Yes
[1024000, 1305600) Previous layer 28, expert 461, [0, 281600) Yes
flowchart TB
    A["gate: 0 to 422400 — correct"] --> B["up: 422400 to 844800 — correct"]
    B --> C["down prefix: 844800 to 1007616 — correct"]
    C --> D["down tail: 1007616 to 1305600 — previous-layer bytes"]
    D --> E["455 nonfinite FP16 scales across 401 down rows"]
    E --> F["Exactly those 401 output rows become nonfinite"]
    style D fill:#ffe0df,stroke:#c0392b,color:#111
    style E fill:#ffe0df,stroke:#c0392b,color:#111
    style F fill:#ffe0df,stroke:#c0392b,color:#111

The previous layer's blobs are 1,510,400 bytes; the current layer's are 1,305,600. Packing each group at its layer's blob stride makes the stale suffix cross two old blobs. Old quantized code bytes are consequently interpreted as current Q2_0 FP16 scale fields. The stale suffix is 297,984 bytes long, with 296,638 bytes differing from the correct target.

Correct gate/up/down scales are all finite. In the snapshot, gate/up scales remain finite, while down has 455 NaN/Inf scale fields in 401 distinct rows. The set of those rows equals the set of nonfinite output rows exactly. The first bad scale is at blob offset 1011354, down row925/block3, FP16 bits 0x7db4.

Same real activation, same original kernel, A-B-B-A replay

Before expert consumption, a diagnostic snapshots the actual staged blob and its activation/plan. In the freeze arm it redirects only the selected expert to this immutable snapshot; no synthetic bytes are inserted. Replay uses the original native_expert_grouped, identical Q8_1 input, layout, plan, and grid grouping. Only the selected expert's weight pointer changes.

The captured float activation has 15,360 values, all finite (max absolute 2.69835); all 960 Q8_1 FP16 scale/sum fields are finite. The selected expert contributes one planned 2,560-dimensional output row.

Replay Weight Nonfinite outputs / 2560 Maximum finite absolute output
A1 Correct blob 0 0.110884
B1 Captured staging blob 401 208766.03125
B2 Same captured blob 401 208766.03125
A2 Correct blob 0 0.110884

A1 equals A2 bitwise. B1 equals B2 and the observed expert output bitwise. The latter three selected output rows share SHA256 4c2f2874ad53cf185283b78e7020e38a4d894bf2e3f34187e12b6c529a046f41.

In that window, the first weight mismatch and first nonfinite PCIe expert output are both at step59; resident-expert outputs first become nonfinite at step61. This particular speculative window did not trigger a head-nonfinite request termination: computed candidate rows and accepted output tokens have different coverage. A separate request in the original observation arm did terminate with the engine's DONE nonfinite log below.

Proposed focused fix

After DMA has been used, enqueue empty-group completion notifications on the same copy stream, behind prior uploads/callbacks. Before any DMA, retain the direct notification fast path.

sequenceDiagram
    participant H as CPU scheduler
    participant D as DMA copy stream
    participant G as GPU compute stream
    H->>D: Enqueue upload for 60
    H->>D: Enqueue notification B=60
    H->>D: Empty group also enqueues notification B=61
    G->>G: Wait for B at least 60
    D->>D: Finish upload for 60
    D->>G: Publish B=60
    G->>G: Consume complete expert weights
    D->>G: Publish B=61 in stream order

This uses existing FlagSet storage and adds no weight buffer or worker thread. Empty groups after DMA incur one additional host callback and ordered notification latency; CPU submission remains asynchronous. copy_used_ is conservative: it means DMA was used since the last drain/reset, not that a copy must still be in flight. The patch below is the locally tested focused candidate; other flag-publication paths still deserve an ordering audit.

Minimal candidate patch against the tested commit
--- a/src/core/verify.cpp
+++ b/src/core/verify.cpp
@@ -3745,7 +3745,24 @@
 void Verifier::fetch_dma(void* ctx, const uint8_t* const* src, int n, size_t bytes) {
     Verifier* v = (Verifier*) ctx;
     const uint32_t want = v->cur_layer_ + 1;
-    if (n <= 0) { raise_flag(v->h_flagB_, want); return; }
+    if (n <= 0) {
+        // A split window may serve the next group's empty plan while an earlier
+        // group's DMA is still in flight. Keep flag B ordered with those copies.
+        if (!v->copy_used_) { raise_flag(v->h_flagB_, want); return; }
+        FlagSet& fs = v->flag_sets_[v->cur_layer_ % (sizeof v->flag_sets_ / sizeof v->flag_sets_[0])];
+        fs.flag = v->h_flagB_;
+        fs.value = want;
+        const cudaError_t e = cudaLaunchHostFunc(v->copy_, [](void* p) {
+            FlagSet* s = (FlagSet*) p; raise_flag(s->flag, s->value);
+        }, &fs);
+        if (e != cudaSuccess) {
+            std::fprintf(stderr, "strata DMA: empty-group completion failed: %s\n", cudaGetErrorString(e));
+            std::fflush(stderr);
+            v->release_gpu_waits(5000);
+            std::abort();
+        }
+        return;
+    }
     v->copy_used_ = true;
     uint8_t* stage = (uint8_t*) v->sink_.staging;                  // this group's half in a split window
     // STRATA_DMA_BATCH (midhatn's #807, F12): the group's independent uploads as one cudaMemcpyBatchAsync.  Mode 0 is

Reproduction status and validation

Reproduced locally, timing-dependent. The exact same prompt/seed need not fail on every launch. The frozen expert-residency profile and cache history were held constant across controls.

Environment: source build, engine 0.1.56, commit ffa80d7313, CUDA 12.8, driver 580.126.09, RTX 3090 24GiB / sm_86, Linux kernel 5.15.0-161-generic in a KVM guest, 64GiB RAM, 32 vCPU Xeon Platinum 8260. Model: Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS, native GGUF-in-place expert pack, MTP rt, text only, one request at a time. Original arithmetic GPU libraries retain their hashes; diagnostics add sampling/snapshot/finite-check kernels.

Shared settings: LOOKAHEAD=0, official rotation=1, tail skip=0, prefill CPU share=0, DMA/PCIe fraction1, pool workers7, prefill2048, context32768/int8 KV, suffix3, lookup-max-t12/MTP-max4, adapt4/96/0.7/async0. Actual expert cache 12756 slots / 17501MiB, arena 17490MiB, official 16 staging slots. PCIe fraction1 is not a claim that all CPU fallback was absent.

Independent ordering litmus

A bounded host callback holds the copy stream before a 1MiB H2D, its completion event, and its normal flag callback. The test then either directly publishes the later empty flag (original) or queues it on that stream (ordered). cudaEventQuery is checked before releasing the gate. This is a synthetic protocol test, separate from the real-model evidence above.

Mode Copy event still NotReady? Flag before release Flag after drain Gate timeout?
Original empty publication Yes 2 2 No
Ordered empty publication Yes 0 2 No
Standalone CUDA ordering litmus source and reproduction command

Save as ordering_litmus.cpp. Example build command for a Linux CUDA toolkit installation (adjust CUDA_ROOT):

CUDA_ROOT=/usr/local/cuda-12.8
c++ -std=c++20 -O2 -pthread -I"$CUDA_ROOT/include" ordering_litmus.cpp \
  -L"$CUDA_ROOT/lib64" -Wl,-rpath,"$CUDA_ROOT/lib64" -lcudart -o ordering_litmus
./ordering_litmus

The measured litmus execution returned0 and produced the two rows above. This test deliberately holds a stream to expose the protocol ordering; it does not simulate model arithmetic.

#include <cuda_runtime.h>
#include <atomic>
#include <chrono>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <thread>
static void ck(cudaError_t e){if(e!=cudaSuccess){std::fprintf(stderr,"CUDA %s\n",cudaGetErrorString(e));std::exit(2);}}
struct Gate{std::atomic<bool> release{false},timeout{false};};
struct Flag{std::atomic<unsigned>*word;unsigned value;};
static void publish(Flag&f){unsigned x=f.word->load();while(x<f.value&&!f.word->compare_exchange_weak(x,f.value)){};}
int main(){
 ck(cudaSetDevice(0));cudaStream_t s;cudaEvent_t copied;ck(cudaStreamCreateWithFlags(&s,cudaStreamNonBlocking));ck(cudaEventCreateWithFlags(&copied,cudaEventDisableTiming));char*host=nullptr,*gpu=nullptr;const size_t n=1024*1024;ck(cudaHostAlloc((void**)&host,n,cudaHostAllocDefault));ck(cudaMalloc((void**)&gpu,n));std::memset(host,0x5a,n);bool all=true;
 for(int fixed=0;fixed<2;++fixed){Gate gate;std::atomic<unsigned> flag{0};Flag first{&flag,1},empty{&flag,2};ck(cudaLaunchHostFunc(s,[](void*p){auto&g=*static_cast<Gate*>(p);auto end=std::chrono::steady_clock::now()+std::chrono::seconds(2);while(!g.release.load()){if(std::chrono::steady_clock::now()>end){g.timeout.store(true);break;}std::this_thread::yield();}},&gate));ck(cudaMemcpyAsync(gpu,host,n,cudaMemcpyHostToDevice,s));ck(cudaEventRecord(copied,s));ck(cudaLaunchHostFunc(s,[](void*p){publish(*static_cast<Flag*>(p));},&first));
  if(fixed)ck(cudaLaunchHostFunc(s,[](void*p){publish(*static_cast<Flag*>(p));},&empty));else publish(empty);
  const unsigned before=flag.load();const auto ready=cudaEventQuery(copied);const bool copy_pending=ready==cudaErrorNotReady;if(ready!=cudaSuccess&&ready!=cudaErrorNotReady)ck(ready);gate.release.store(true);ck(cudaStreamSynchronize(s));bool correct=copy_pending&&!gate.timeout.load()&&flag.load()==2&&(fixed?before==0:before==2);std::printf("{\"mode\":\"%s\",\"copy_pending\":%s,\"flag_before_copy\":%u,\"flag_after_drain\":%u,\"gate_timeout\":%s,\"expected_property\":%s}\n",fixed?"ordered_empty":"original_empty",copy_pending?"true":"false",before,flag.load(),gate.timeout.load()?"true":"false",correct?"true":"false");all=all&&correct;
 }
 ck(cudaFree(gpu));ck(cudaFreeHost(host));ck(cudaEventDestroy(copied));ck(cudaStreamDestroy(s));return all?0:1;
}

Real workload controls

Each diagnostic arm ran nine serial requests: code and Chinese warmups, three code/Chinese pairs capped at512 output tokens, and a code-repair request capped at2048.

Diagnostic arm Wide T12 windows observed Weight-sample mismatch windows Expert nonfinite windows Head-nonfinite request endings
Original notifications, observe 13 5 2 1
Original notifications, freeze selected real snapshot 12 3 1 0
Ordered empty notifications, same probe/freeze logic 11 0 0 0

The ordered arm never detected a mismatch, so no snapshot pointer redirection occurred there. Sampling checks64 eight-byte locations per expert; finite checks inspect only planned output rows. Instrumentation changes timing: these counts describe the diagnostic run, not production failure rates or throughput.

An earlier unprofiled same-configuration A-B-B-A (28 requests including warmups) compared original DMA against the minimal notification patch: 7/14 versus 0/14 requests ended with nonfinite logits. All four formal original-DMA code requests stopped early; all four patched ones reached512. There is no successful full-length original code baseline for a speedup claim. Earlier full-byte readback on the patched path checked 125171 blobs / 180397721600 bytes, with no mismatch.

Passed: the ordering litmus, independent probe selftest (including ignoring unplanned NaN rows), GGUF byte provenance, original-kernel A-B-B-A replay, and three existing CTests (exchange_storage_test, file_expert_source_test, nv_defaults_test). Original service/files/source/GPU selector state restored; no new dmesg entries during this diagnostic round. Collected189 evidence files were SHA256-verified after transfer.

Observed failures retained: original notification arms have wrong weights/internal nonfinite values; one original diagnostic request ends at the head guard. Other repair-task semantic failures are retained separately and not attributed to this race without a corresponding trace.

Not run: HIP/SYCL execution/build validation of this candidate, other GPUs/models, or a complete root-cause analysis of every #879 symptom. This issue concerns the explicit DMA path. No claim is made that the kernel-copy path has this mechanism.

Relevant log excerpts

CAUSAL_WINDOW pos=96 T=12 mismatched_samples=390 invalid=0 first_weight_step=59 first_hit_nan=61 first_pcie_nan=59 captured=1 freeze=1

Separate original observation request:

strata serve: non-finite logits (#879) in a decode window at position 421 (row 2): its tokens are not emitted, the request ends (DONE nonfinite) and the next request reads its prompt from token 0
Sanitized measured launch arguments and public replay prompts

The following are the engine arguments used in the run; path roles are replaced with variables. Keep a copy of the expert profile and use the same starting profile for each launch. These settings reproduce the tested configuration, not a guaranteed minimal model reproducer.

STRATA_LOOKAHEAD=0 STRATA_EXCHANGE_ROTATE=1 STRATA_ROUTE_TAIL_SKIP=0 STRATA_PREFILL_CPU_SHARE=0 OMP_NUM_THREADS=2 OPENBLAS_NUM_THREADS=2
--pack $PACK --native $SHARD1 --ple-gguf $SHARD2 --expert-profile $PROFILE --expert-cache 17408 --prefill 2048 --spec 4 --spec-min-p 0.5 --mtp $MTP --max-context 32768 --kv int8 --ple-io ram --pcie-frac 1 --pool-workers 7 --aux-cpus auto --prompt-cache 0 --conversation-cache-mib 0 --resident-experts --vram-reserve-mib 1724 --lookup-max-t 12 --suffix-draft 3 --pcie-mode dma --adapt-every 4 --adapt-swaps 96 --adapt-decay 0.7 --adapt-async 0

Send the code request, then the Chinese request as warmups, then repeat that pair three times serially. Wait for loaded: true before sending requests. This is the first eight requests of each recorded arm; the ninth was a separate repair task. Retain failed requests and engine logs. Warm cache/residency history influences whether the race fires.

Code request:

{
  "model": "qwen3.8-flash-next-iq2_xs",
  "messages": [
    {
      "role": "user",
      "content": "连续输出一个大型Python标准库项目的源代码,从配置解析、HTTP客户端、缓存、重试、并发执行器到单元测试,写至少200个函数,每个函数包含文档字符串和错误处理。直接从代码开始,持续写到输出上限,不要总结,不要省略。"
    }
  ],
  "temperature": 0,
  "top_p": 0.95,
  "stream": true,
  "stream_options": {
    "include_usage": true
  },
  "max_tokens": 512,
  "seed": 20261013,
  "reasoning_effort": "none"
}

Chinese request:

{
  "model": "qwen3.8-flash-next-iq2_xs",
  "messages": [
    {
      "role": "user",
      "content": "写一份非常详细的中文数据库故障排查手册,覆盖锁等待、事务隔离、索引、慢查询、复制、备份、磁盘、网络与容量规划。每节含命令、案例和分析,需要至少一万字。直接开始正文,持续写到输出上限,不要总结。"
    }
  ],
  "temperature": 0,
  "top_p": 0.95,
  "stream": true,
  "stream_options": {
    "include_usage": true
  },
  "max_tokens": 512,
  "seed": 20261013,
  "reasoning_effort": "none"
}

Would this ordering invariant and the focused fix be appropriate for an engine regression test/fix? The full raw model snapshots remain local; the report includes their hashes and byte-source checks rather than uploading model-weight data.

AI-assisted investigation and writing; source paths, captured bytes, replay outputs, and reported measurements were checked against the actual experiment artifacts.

Originally created by @AlanJager on GitHub (Nov 3, 2026). Original GitHub issue: https://github.com/Niko1221/Strata/issues/5093 ### Area [Engine] (CUDA DMA expert staging and completion ordering) ### Desktop app, Terminal or source? Source build. ### Strata version Engine 0.1.56, commit ffa80d73133ea5c548aefe57889a16e8085a938f (also current main when filing). ### Graphics card, memory and system RTX 3090 24GiB (sm_86), 64GiB guest RAM, 32 vCPU Xeon Platinum 8260; Linux 5.15.0-161-generic / KVM, CUDA 12.8, NVIDIA driver 580.126.09. Full model/configuration and measured controls are below. ## What happened **Reproduced locally:** in explicit CUDA `--pcie-mode dma`, a later empty PCIe group can publish a larger cumulative `flagB` while an earlier group's H2D copy is still in flight. The GPU's `flagB >= ring` wait then passes before its expert weights are ready. On an RTX 3090, I captured an expert blob containing a correct current-layer prefix and a stale previous-layer suffix. Both portions were independently matched against the original GGUF. With the captured real activation and the original expert kernel, replaying this blob produces **401 nonfinite outputs**; replacing only that expert's weights with the correct blob produces **zero**. The bad replay is bit-identical to the observed expert output. Expected: a cumulative completion value implies that all preceding uploads have completed. Actual: the empty-group fast path bypasses that ordering. Related symptom discussion: #879. This report isolates one CUDA DMA failure mechanism; it does not attribute every failure in #879 to it. Main was rechecked before filing and is still the tested commit below. ## Source and ordering At [`Verifier::fetch_dma`](https://github.com/Niko1221/Strata/blob/ffa80d73133ea5c548aefe57889a16e8085a938f/src/core/verify.cpp#L3744-L3771): ```cpp const uint32_t want = v->cur_layer_ + 1; if (n <= 0) { raise_flag(v->h_flagB_, want); return; } // Nonempty path: enqueue uploads, then enqueue the flag callback on copy_. cudaMemcpyAsync(..., v->copy_); cudaLaunchHostFunc(v->copy_, ...); ``` The GPU consumes the PCIe expert groups after a [`wait_flag_ge`](https://github.com/Niko1221/Strata/blob/ffa80d73133ea5c548aefe57889a16e8085a938f/src/core/verify.cpp#L2404-L2419). Its [implementation](https://github.com/Niko1221/Strata/blob/ffa80d73133ea5c548aefe57889a16e8085a938f/src/kernels/cuda/verify_kernels.cu#L1313-L1316) spins while `*flag < value`. [`raise_flag`](https://github.com/Niko1221/Strata/blob/ffa80d73133ea5c548aefe57889a16e8085a938f/src/core/verify.cpp#L3723-L3740) implements a monotonic maximum; it does not track gaps in completion. The [two-group window schedule](https://github.com/Niko1221/Strata/blob/ffa80d73133ea5c548aefe57889a16e8085a938f/src/core/verify.cpp#L1327-L1336) intentionally prepares work ahead of consumption. A later plan can therefore be served while an earlier DMA remains pending. Here, **empty** means zero PCIe expert blobs for this group, not zero preceding work. ### Normal: notify through the copy stream The values 60 and 61 below are completion sequence numbers, not layer numbers. ```mermaid sequenceDiagram participant H as CPU scheduler participant D as DMA copy stream participant G as GPU compute stream H->>D: Enqueue expert upload for sequence 60 H->>D: Enqueue callback publishing B=60 G->>G: Compute resident experts G->>G: Wait for B at least 60 D->>D: Finish the upload D->>G: Callback publishes B=60 G->>G: Consume complete expert weights ``` ### Failure: empty group publishes outside that stream ```mermaid sequenceDiagram participant H as CPU scheduler participant D as DMA copy stream participant G as GPU compute stream H->>D: Enqueue upload and completion callback for 60 Note over D: Upload is still pending H->>H: Serve later group 61 with zero PCIe blobs H->>G: Directly publish B=61 G->>G: Wait for B at least 60 passes G->>G: Read partially updated staging weights D-->>G: Callback for 60 executes too late Note over G: B stays 61 because publication is monotonic ``` ## Captured bytes explain the first expert NaN Decisive capture: `pos=96, T=12, step=59, layer=29, group=1`. The consumer needs sequence **60**, but sees **B=61** while this group's completion callback has not run (`completion_seen=0`). The selected blob is **layer 29, expert 222**, 1,305,600 bytes, with IQ2_XXS gate/up and Q2_0 down. The correct CPU copy equals the corresponding gate/up/down ranges in the original GGUF in full; SHA256: ```text 65edb34bc11a1bba95b38580f2c77794bbf9f67fa112c610afa10d49c7dd087b ``` The captured staging blob has these independently verified sources (half-open byte ranges): | Captured range | Exact GGUF source | Full range equal? | | --- | --- | --- | | `[0, 1007616)` | Current layer 29, expert 222, same offsets | Yes | | `[1007616, 1024000)` | Previous layer 28, expert 277, `[1494016, 1510400)` | Yes | | `[1024000, 1305600)` | Previous layer 28, expert 461, `[0, 281600)` | Yes | ```mermaid flowchart TB A["gate: 0 to 422400 — correct"] --> B["up: 422400 to 844800 — correct"] B --> C["down prefix: 844800 to 1007616 — correct"] C --> D["down tail: 1007616 to 1305600 — previous-layer bytes"] D --> E["455 nonfinite FP16 scales across 401 down rows"] E --> F["Exactly those 401 output rows become nonfinite"] style D fill:#ffe0df,stroke:#c0392b,color:#111 style E fill:#ffe0df,stroke:#c0392b,color:#111 style F fill:#ffe0df,stroke:#c0392b,color:#111 ``` The previous layer's blobs are 1,510,400 bytes; the current layer's are 1,305,600. Packing each group at its layer's blob stride makes the stale suffix cross two old blobs. Old quantized code bytes are consequently interpreted as current Q2_0 FP16 scale fields. The stale suffix is 297,984 bytes long, with 296,638 bytes differing from the correct target. Correct gate/up/down scales are all finite. In the snapshot, gate/up scales remain finite, while down has **455 NaN/Inf scale fields in 401 distinct rows**. The set of those rows equals the set of nonfinite output rows exactly. The first bad scale is at blob offset `1011354`, down row925/block3, FP16 bits `0x7db4`. ### Same real activation, same original kernel, A-B-B-A replay Before expert consumption, a diagnostic snapshots the actual staged blob and its activation/plan. In the freeze arm it redirects only the selected expert to this immutable snapshot; no synthetic bytes are inserted. Replay uses the original `native_expert_grouped`, identical Q8_1 input, layout, plan, and grid grouping. Only the selected expert's weight pointer changes. The captured float activation has 15,360 values, all finite (max absolute 2.69835); all 960 Q8_1 FP16 scale/sum fields are finite. The selected expert contributes one planned 2,560-dimensional output row. | Replay | Weight | Nonfinite outputs / 2560 | Maximum finite absolute output | | --- | --- | ---: | ---: | | A1 | Correct blob | 0 | 0.110884 | | B1 | Captured staging blob | 401 | 208766.03125 | | B2 | Same captured blob | 401 | 208766.03125 | | A2 | Correct blob | 0 | 0.110884 | A1 equals A2 bitwise. B1 equals B2 **and the observed expert output bitwise**. The latter three selected output rows share SHA256 `4c2f2874ad53cf185283b78e7020e38a4d894bf2e3f34187e12b6c529a046f41`. In that window, the first weight mismatch and first nonfinite PCIe expert output are both at step59; resident-expert outputs first become nonfinite at step61. This particular speculative window did not trigger a head-nonfinite request termination: computed candidate rows and accepted output tokens have different coverage. A separate request in the original observation arm did terminate with the engine's `DONE nonfinite` log below. ## Proposed focused fix After DMA has been used, enqueue **empty-group completion notifications on the same copy stream**, behind prior uploads/callbacks. Before any DMA, retain the direct notification fast path. ```mermaid sequenceDiagram participant H as CPU scheduler participant D as DMA copy stream participant G as GPU compute stream H->>D: Enqueue upload for 60 H->>D: Enqueue notification B=60 H->>D: Empty group also enqueues notification B=61 G->>G: Wait for B at least 60 D->>D: Finish upload for 60 D->>G: Publish B=60 G->>G: Consume complete expert weights D->>G: Publish B=61 in stream order ``` This uses existing `FlagSet` storage and adds no weight buffer or worker thread. Empty groups after DMA incur one additional host callback and ordered notification latency; CPU submission remains asynchronous. `copy_used_` is conservative: it means DMA was used since the last drain/reset, not that a copy must still be in flight. The patch below is the locally tested focused candidate; other flag-publication paths still deserve an ordering audit. <details> <summary>Minimal candidate patch against the tested commit</summary> ```diff --- a/src/core/verify.cpp +++ b/src/core/verify.cpp @@ -3745,7 +3745,24 @@ void Verifier::fetch_dma(void* ctx, const uint8_t* const* src, int n, size_t bytes) { Verifier* v = (Verifier*) ctx; const uint32_t want = v->cur_layer_ + 1; - if (n <= 0) { raise_flag(v->h_flagB_, want); return; } + if (n <= 0) { + // A split window may serve the next group's empty plan while an earlier + // group's DMA is still in flight. Keep flag B ordered with those copies. + if (!v->copy_used_) { raise_flag(v->h_flagB_, want); return; } + FlagSet& fs = v->flag_sets_[v->cur_layer_ % (sizeof v->flag_sets_ / sizeof v->flag_sets_[0])]; + fs.flag = v->h_flagB_; + fs.value = want; + const cudaError_t e = cudaLaunchHostFunc(v->copy_, [](void* p) { + FlagSet* s = (FlagSet*) p; raise_flag(s->flag, s->value); + }, &fs); + if (e != cudaSuccess) { + std::fprintf(stderr, "strata DMA: empty-group completion failed: %s\n", cudaGetErrorString(e)); + std::fflush(stderr); + v->release_gpu_waits(5000); + std::abort(); + } + return; + } v->copy_used_ = true; uint8_t* stage = (uint8_t*) v->sink_.staging; // this group's half in a split window // STRATA_DMA_BATCH (midhatn's #807, F12): the group's independent uploads as one cudaMemcpyBatchAsync. Mode 0 is ``` </details> ## Reproduction status and validation **Reproduced locally, timing-dependent.** The exact same prompt/seed need not fail on every launch. The frozen expert-residency profile and cache history were held constant across controls. Environment: source build, engine **0.1.56**, commit **ffa80d73133ea5c548aefe57889a16e8085a938f**, CUDA **12.8**, driver **580.126.09**, RTX **3090 24GiB / sm_86**, Linux kernel **5.15.0-161-generic** in a KVM guest, **64GiB RAM**, 32 vCPU Xeon Platinum 8260. Model: **Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS**, native GGUF-in-place expert pack, MTP `rt`, text only, one request at a time. Original arithmetic GPU libraries retain their hashes; diagnostics add sampling/snapshot/finite-check kernels. Shared settings: LOOKAHEAD=0, official rotation=1, tail skip=0, prefill CPU share=0, DMA/PCIe fraction1, pool workers7, prefill2048, context32768/int8 KV, suffix3, lookup-max-t12/MTP-max4, adapt4/96/0.7/async0. Actual expert cache **12756 slots / 17501MiB**, arena **17490MiB**, official **16 staging slots**. PCIe fraction1 is not a claim that all CPU fallback was absent. ### Independent ordering litmus A bounded host callback holds the copy stream before a 1MiB H2D, its completion event, and its normal flag callback. The test then either directly publishes the later empty flag (original) or queues it on that stream (ordered). `cudaEventQuery` is checked before releasing the gate. This is a **synthetic protocol test**, separate from the real-model evidence above. | Mode | Copy event still NotReady? | Flag before release | Flag after drain | Gate timeout? | | --- | --- | ---: | ---: | --- | | Original empty publication | Yes | 2 | 2 | No | | Ordered empty publication | Yes | 0 | 2 | No | <details> <summary>Standalone CUDA ordering litmus source and reproduction command</summary> Save as `ordering_litmus.cpp`. Example build command for a Linux CUDA toolkit installation (adjust `CUDA_ROOT`): ```sh CUDA_ROOT=/usr/local/cuda-12.8 c++ -std=c++20 -O2 -pthread -I"$CUDA_ROOT/include" ordering_litmus.cpp \ -L"$CUDA_ROOT/lib64" -Wl,-rpath,"$CUDA_ROOT/lib64" -lcudart -o ordering_litmus ./ordering_litmus ``` The measured litmus execution returned0 and produced the two rows above. This test deliberately holds a stream to expose the protocol ordering; it does not simulate model arithmetic. ```cpp #include <cuda_runtime.h> #include <atomic> #include <chrono> #include <cstdio> #include <cstdlib> #include <cstring> #include <thread> static void ck(cudaError_t e){if(e!=cudaSuccess){std::fprintf(stderr,"CUDA %s\n",cudaGetErrorString(e));std::exit(2);}} struct Gate{std::atomic<bool> release{false},timeout{false};}; struct Flag{std::atomic<unsigned>*word;unsigned value;}; static void publish(Flag&f){unsigned x=f.word->load();while(x<f.value&&!f.word->compare_exchange_weak(x,f.value)){};} int main(){ ck(cudaSetDevice(0));cudaStream_t s;cudaEvent_t copied;ck(cudaStreamCreateWithFlags(&s,cudaStreamNonBlocking));ck(cudaEventCreateWithFlags(&copied,cudaEventDisableTiming));char*host=nullptr,*gpu=nullptr;const size_t n=1024*1024;ck(cudaHostAlloc((void**)&host,n,cudaHostAllocDefault));ck(cudaMalloc((void**)&gpu,n));std::memset(host,0x5a,n);bool all=true; for(int fixed=0;fixed<2;++fixed){Gate gate;std::atomic<unsigned> flag{0};Flag first{&flag,1},empty{&flag,2};ck(cudaLaunchHostFunc(s,[](void*p){auto&g=*static_cast<Gate*>(p);auto end=std::chrono::steady_clock::now()+std::chrono::seconds(2);while(!g.release.load()){if(std::chrono::steady_clock::now()>end){g.timeout.store(true);break;}std::this_thread::yield();}},&gate));ck(cudaMemcpyAsync(gpu,host,n,cudaMemcpyHostToDevice,s));ck(cudaEventRecord(copied,s));ck(cudaLaunchHostFunc(s,[](void*p){publish(*static_cast<Flag*>(p));},&first)); if(fixed)ck(cudaLaunchHostFunc(s,[](void*p){publish(*static_cast<Flag*>(p));},&empty));else publish(empty); const unsigned before=flag.load();const auto ready=cudaEventQuery(copied);const bool copy_pending=ready==cudaErrorNotReady;if(ready!=cudaSuccess&&ready!=cudaErrorNotReady)ck(ready);gate.release.store(true);ck(cudaStreamSynchronize(s));bool correct=copy_pending&&!gate.timeout.load()&&flag.load()==2&&(fixed?before==0:before==2);std::printf("{\"mode\":\"%s\",\"copy_pending\":%s,\"flag_before_copy\":%u,\"flag_after_drain\":%u,\"gate_timeout\":%s,\"expected_property\":%s}\n",fixed?"ordered_empty":"original_empty",copy_pending?"true":"false",before,flag.load(),gate.timeout.load()?"true":"false",correct?"true":"false");all=all&&correct; } ck(cudaFree(gpu));ck(cudaFreeHost(host));ck(cudaEventDestroy(copied));ck(cudaStreamDestroy(s));return all?0:1; } ``` </details> ### Real workload controls Each diagnostic arm ran nine serial requests: code and Chinese warmups, three code/Chinese pairs capped at512 output tokens, and a code-repair request capped at2048. | Diagnostic arm | Wide T12 windows observed | Weight-sample mismatch windows | Expert nonfinite windows | Head-nonfinite request endings | | --- | ---: | ---: | ---: | ---: | | Original notifications, observe | 13 | 5 | 2 | 1 | | Original notifications, freeze selected real snapshot | 12 | 3 | 1 | 0 | | Ordered empty notifications, same probe/freeze logic | 11 | 0 | 0 | 0 | The ordered arm never detected a mismatch, so no snapshot pointer redirection occurred there. Sampling checks64 eight-byte locations per expert; finite checks inspect only planned output rows. Instrumentation changes timing: these counts describe the diagnostic run, not production failure rates or throughput. An earlier **unprofiled** same-configuration A-B-B-A (28 requests including warmups) compared original DMA against the minimal notification patch: **7/14 versus 0/14** requests ended with nonfinite logits. All four formal original-DMA code requests stopped early; all four patched ones reached512. There is no successful full-length original code baseline for a speedup claim. Earlier full-byte readback on the patched path checked **125171 blobs / 180397721600 bytes**, with no mismatch. Passed: the ordering litmus, independent probe selftest (including ignoring unplanned NaN rows), GGUF byte provenance, original-kernel A-B-B-A replay, and three existing CTests (`exchange_storage_test`, `file_expert_source_test`, `nv_defaults_test`). Original service/files/source/GPU selector state restored; no new dmesg entries during this diagnostic round. Collected189 evidence files were SHA256-verified after transfer. Observed failures retained: original notification arms have wrong weights/internal nonfinite values; one original diagnostic request ends at the head guard. Other repair-task semantic failures are retained separately and not attributed to this race without a corresponding trace. Not run: HIP/SYCL execution/build validation of this candidate, other GPUs/models, or a complete root-cause analysis of every #879 symptom. This issue concerns the explicit DMA path. No claim is made that the kernel-copy path has this mechanism. ### Relevant log excerpts ```text CAUSAL_WINDOW pos=96 T=12 mismatched_samples=390 invalid=0 first_weight_step=59 first_hit_nan=61 first_pcie_nan=59 captured=1 freeze=1 ``` Separate original observation request: ```text strata serve: non-finite logits (#879) in a decode window at position 421 (row 2): its tokens are not emitted, the request ends (DONE nonfinite) and the next request reads its prompt from token 0 ``` <details> <summary>Sanitized measured launch arguments and public replay prompts</summary> The following are the engine arguments used in the run; path roles are replaced with variables. Keep a copy of the expert profile and use the same starting profile for each launch. These settings reproduce the tested configuration, not a guaranteed minimal model reproducer. ```sh STRATA_LOOKAHEAD=0 STRATA_EXCHANGE_ROTATE=1 STRATA_ROUTE_TAIL_SKIP=0 STRATA_PREFILL_CPU_SHARE=0 OMP_NUM_THREADS=2 OPENBLAS_NUM_THREADS=2 --pack $PACK --native $SHARD1 --ple-gguf $SHARD2 --expert-profile $PROFILE --expert-cache 17408 --prefill 2048 --spec 4 --spec-min-p 0.5 --mtp $MTP --max-context 32768 --kv int8 --ple-io ram --pcie-frac 1 --pool-workers 7 --aux-cpus auto --prompt-cache 0 --conversation-cache-mib 0 --resident-experts --vram-reserve-mib 1724 --lookup-max-t 12 --suffix-draft 3 --pcie-mode dma --adapt-every 4 --adapt-swaps 96 --adapt-decay 0.7 --adapt-async 0 ``` Send the code request, then the Chinese request as warmups, then repeat that pair three times serially. Wait for `loaded: true` before sending requests. This is the first eight requests of each recorded arm; the ninth was a separate repair task. Retain failed requests and engine logs. Warm cache/residency history influences whether the race fires. Code request: ```json { "model": "qwen3.8-flash-next-iq2_xs", "messages": [ { "role": "user", "content": "连续输出一个大型Python标准库项目的源代码,从配置解析、HTTP客户端、缓存、重试、并发执行器到单元测试,写至少200个函数,每个函数包含文档字符串和错误处理。直接从代码开始,持续写到输出上限,不要总结,不要省略。" } ], "temperature": 0, "top_p": 0.95, "stream": true, "stream_options": { "include_usage": true }, "max_tokens": 512, "seed": 20261013, "reasoning_effort": "none" } ``` Chinese request: ```json { "model": "qwen3.8-flash-next-iq2_xs", "messages": [ { "role": "user", "content": "写一份非常详细的中文数据库故障排查手册,覆盖锁等待、事务隔离、索引、慢查询、复制、备份、磁盘、网络与容量规划。每节含命令、案例和分析,需要至少一万字。直接开始正文,持续写到输出上限,不要总结。" } ], "temperature": 0, "top_p": 0.95, "stream": true, "stream_options": { "include_usage": true }, "max_tokens": 512, "seed": 20261013, "reasoning_effort": "none" } ``` </details> Would this ordering invariant and the focused fix be appropriate for an engine regression test/fix? The full raw model snapshots remain local; the report includes their hashes and byte-source checks rather than uploading model-weight data. AI-assisted investigation and writing; source paths, captured bytes, replay outputs, and reported measurements were checked against the actual experiment artifacts.
Author
Owner

@github-actions[bot] commented on GitHub (Nov 3, 2026):

Thanks for the issue. To keep the tracker readable, every item needs an area prefix in the title and the parts of the issue form filled in. This one is missing:

  • Fill in "Area".
  • Fill in "Desktop app, Terminal or source?".
  • Fill in "Strata version".
  • Fill in "Graphics card, memory and system".

Edit the issue (title and description) and this note goes away on its own. If it is still missing parts in 5 days it will be closed, which is not a rejection: fix it and comment /reopen.

Details: CONTRIBUTING.md

<!-- gh-comment-id:6601910591 --> @github-actions[bot] commented on GitHub (Nov 3, 2026): Thanks for the issue. To keep the tracker readable, every item needs an area prefix in the title and the parts of the issue form filled in. This one is missing: - [ ] Fill in "Area". - [ ] Fill in "Desktop app, Terminal or source?". - [ ] Fill in "Strata version". - [ ] Fill in "Graphics card, memory and system". Edit the issue (title and description) and this note goes away on its own. If it is still missing parts in 5 days it will be closed, which is not a rejection: fix it and comment `/reopen`. Details: [CONTRIBUTING.md](https://github.com/Niko1221/Strata/blob/main/CONTRIBUTING.md)
Author
Owner

@github-actions[bot] commented on GitHub (Nov 3, 2026):

Thanks, this follows the format now.

<!-- gh-comment-id:6601932980 --> @github-actions[bot] commented on GitHub (Nov 3, 2026): Thanks, this follows the format now.
Sign in to join this conversation.
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set.

Reference
Niko1221/Strata#2379
No description provided.