[GH-ISSUE #5480] [Engine] Windows/HIP: silent data corruption in hipMemcpy2D uploads from read-only file mappings, plus two engine findings (DP pinned-KV waste blocking 1M startup; VRAM reserve coupling into prefill chunk size) #5446

Open
opened 2026-11-07 19:35:51 +07:00 by bsakaguchi · 2 comments
Owner

Originally created by @bigbrid2023 on GitHub (Nov 7, 2026).
Original GitHub issue: https://github.com/Niko1221/Strata/issues/5480

Hi — this is a focused report of three engine-level findings from Windows dual-GPU field work. All three were localized and measured on a build of the rdna3 fork (HEAD bd34f079da92e8b47dc4de6b40d894a867154797), but in each case the mechanism sits in engine code shared with upstream — the weight-upload path, the DP session allocation, and the prefill staging logic — not in fork-specific code, which is why we are filing here as well as filing a full dual-card report with the fork. For each finding we state where it was verified and why we believe it applies upstream. None of the three has yet been re-verified on a stock upstream build; a standalone reproduction script for Finding 1 is included in the Appendix at the end of this issue.

Environment

  • Host: Windows desktop (WDDM), i9-13900KF, 128 GB DDR4, ASUS PRIME Z690-P D4
  • GPUs: 2× RX 7900 XTX 24 GB, driver 32.0.32015.7029; cards are not P2P peers (host-staged exchange)
  • Build where findings were localized: rdna3 fork, HEAD above; model Qwen3.8-Flash-Next UD-IQ4_XS
  • Relevance note for Finding 1: the HIP runtime DLL (amdhip64_7.dll, SHA256 344386DD39B2BBA7060D62720054B9375401F23F2BCD29D730DD8D43019683CD) is byte-identical between the fork build and the stock 0.1.56 engine on this machine, and the Finding 1 reproduction uses no engine code at all.
  • Finding 1 reproduces in both dock topologies tried (Gen3 x4 and Gen4 x4 link to the second card) and on both GPUs.

Summary

  1. Silent data corruption (main finding). On Windows, hipMemcpy2D with a read-only file mapping (MapViewOfFile, FILE_MAP_READ) as the source silently copies wrong data while the API returns success. In the engine this corrupted TP column-slice weight uploads at load time and produced deterministic garbage output. Writable RAM and pinned memory as sources are clean, and packing the slice contiguously on CPU + a single hipMemcpy is clean (240 slices read back with 0 bytes differing).
  2. DP foreign sessions waste ≈12.375 GiB of pinned host KV, which is one link in 1M-context dual configurations failing to start. A shared-KV build that skips the redundant allocation starts at pin caps 12 and 16 GiB (24 GiB still never becomes READY).
  3. VRAM reserve couples into prefill chunking. Reserve 2560 MiB shrank the prefill chunk cap from 32,768 to 29,440 and made the identical 64K input ≈35% slower; restoring the 32,768 chunk recovered ≈46–48% (the exact +48% measurement point is at reserve 1536; see Finding 3). A capacity parameter silently acting as a performance parameter may deserve a guardrail or at least a log line.

Finding 1 — hipMemcpy2D from a read-only file mapping silently corrupts data

Symptom in the engine. Dual-card tensor-parallel serve starts and generates, but output is deterministic garbage (draft acceptance 0). Layer-split without TP on the same build is fully clean.

Engine-level evidence. The TP path uploaded GGUF weights as column slices via hipMemcpy2D. GPU readback of the first layer's blk.0.ssm_out.weight against the correct slice:

8273507 / 8355840 bytes differ
first mismatch offset = 0
expected byte = 244
actual byte = 69
packed = 0

This is load-time model-data corruption, not an output/encoding artifact. Segment-by-segment comparison of the full first layer shows zero difference up to the layer-0 output projection, which is the first divergence (relative RMS ≈ 1.3889). All 96 dual-card all-reduces in the first window are bit-exact against the FP32 sum of both inputs, ruling out link desync.

Standalone reproduction (no engine code). Python ctypes against the same amdhip64_7.dll, copying the same column half-slices (8,355,840 bytes each):

Source Method Result (both GPUs)
Writable host RAM hipMemcpy2D 0 bytes differ
Read-only file mapping (MapViewOfFile, FILE_MAP_READ) hipMemcpy2D 8,323,025 / 8,355,840 bytes differ, API returns success
Pinned host memory hipMemcpy2D 0 bytes differ
Any of the above, packed contiguously on CPU first single hipMemcpy 0 bytes differ

(The two byte counts above — 8,273,507 from the engine readback and 8,323,025 from the standalone repro — are two different slices/stages of the same bug, not a discrepancy.)

Where verified / why upstream-relevant. Verified on the fork build and, independently of any engine, via ctypes against the HIP DLL that is byte-identical to the one shipping with stock 0.1.56 on this machine. Any engine path that uploads 2D slices directly out of a read-only mmap of the model file on Windows/HIP is exposed to the same failure mode. We have not isolated which component inside the HIP/Windows mapped-memory path is responsible (no alternate HIP version tested) and are not claiming a general Windows/driver defect — only that this source/method combination is reliably wrong on this rig while reporting success. Not yet reproduced on a stock upstream build; the script in the Appendix lets you verify in minutes.

Finding 2 — DP foreign sessions allocate ≈12.375 GiB of pinned host KV and discard it; blocks 1M startup

Mechanism (source-level, shared engine code). In generate-main-keep.cpp, a DP foreign session runs session_init(), whose qsa_state_init() allocates a full pinned host KV for every QSA layer. The DP path then overwrites .host with the owner session's KV — the first allocation is never used by that path but keeps holding pinned/lockable memory. On a dual-GPU WDDM system this matters: the source's arena branch notes a default lock/mapping protection of ≈8 GiB once many host pages are mapped to two GPUs, and 1M-context dual configs failed to start at high pin caps on the original build (pin 32 and pin 16 failed during expert-cache init; pin 12 completed allocation but never became READY in 600 s; pin 8 started and passed functional checks).

Fix and pin ladder. A candidate build (engine-shared-kv) lets full-geometry DP foreign sessions borrow the owner session's host KV at init instead of allocating their own (with validation of layer range, context length, page count and KV mode/format/pointer; TP half-head sessions keep the original allocation). Runtime logs quantify the saving exactly: 12 × avoided 1107297280 bytes = 13,287,567,360 bytes ≈ 12.375 GiB skipped. On the shared-KV build (1M max-context, vision on, reserve 2560 MiB), the pin ladder is (two functional 64K requests per rung — functional timings, not medians):

Expert arena pin cap Result
12 GiB Starts (READY ≈53 s); image / Chinese / both 64K retrieval checks pass
16 GiB Starts (READY ≈56 s); all checks pass — adopted for the 1M test config
24 GiB Never READY in 600 s, no inference started — rejected

Caveat. This fix provably removes wasted pinned allocations. It is not established as the cause of the intermittent cold-start wrong answer noted at the end of this report, and we do not claim that.

Finding 3 — VRAM reserve couples into prefill chunking

Mechanism (shared engine code). Prefill::take_stage() sizes the KV staging pool from the session's total page count and Prefill::carve() sizes index workspaces from max_cells; the DP path (dp_step_for() / run_dp()) requires balanced even chunk counts. Raising max-context to 1M at reserve 2560 MiB shrank the per-GPU expert cache by ≈1.9 GiB and dropped the chunk cap from 32,768 to 29,440. A 65,536-token input then splits as 4 × 16,384 instead of 2 × 32,768 (ceil(65536/29440) = 3, padded to even 4) — more expert movement, more cross-card state publishes, smaller GEMMs.

Measurements (same shared-KV engine, pin 16 GiB, only max-context changed; functional runs):

Max-context cap First 64K prefill tok/s
256K 3310.6
1M (reserve 2560) 2153.5 (≈35% lower for the identical 64K input)

Lowering reserve restored the 32,768 chunk: reserve 1536/lend93 measured 3192.9 tok/s (+≈48% vs 2164.2). The adopted final values, reserve 2048/lend97, keep chunk = 32,768 with more external-card headroom and measured 3145.9 / 3191.5 tok/s on cold 64K runs — ≈3150–3200 vs the ≈2160–2175 slow configuration (≈+46–48%). Because lowering reserve both enlarges the cache and crosses the chunk threshold, the gain cannot be split precisely between the two effects.

Why upstream-relevant. The staging/chunk sizing logic is shared engine code, and the failure mode is silent: nothing logs that a reserve change has cut the chunk cap and cost a third of the prefill rate on identical input. A log line (or guardrail) when the chunk cap drops below the configured maximum would have saved the debugging round; at minimum the coupling is worth documenting.

Minimal repro

Finding 1 reproduces without any engine code. The standalone script hip_copy_diagnostic.py (Python, ctypes against amdhip64_7.dll) maps the model file read-only via MapViewOfFile(..., FILE_MAP_READ), copies column half-slices with hipMemcpy2D, and compares device readback against the expected bytes; writable RAM, pinned memory and packed single-hipMemcpy variants run as controls. Expected results on an affected rig: read-only-mapping source → 8,323,025 / 8,355,840 bytes differ with the API returning success; every control → 0 bytes differ. The script is included in the Appendix at the end of this issue (SHA256 7a61551fbc6a8d93e85e60c09bd5ebe29e2ba6ab52f5e6a02cfbe02a8d9fff67).

Workarounds

Finding 1 — pack before uploading. Pack each column slice into one contiguous CPU buffer at load time and upload with a single hipMemcpy (in our fork tree: STRATA_TP_UPLOAD_PACKED=1; optional readback diagnostic STRATA_TP_UPLOAD_CHECK=1). Packing happens only at load; prefill/decode use the resident weights. With the packed build, all 240 row/column slices read back with 0 bytes differ.

Finding 2 — borrow the owner KV instead of duplicating it. The engine-shared-kv build lets full-geometry DP foreign sessions borrow the owner session's host KV at init (with validation) instead of allocating their own; TP half-head sessions keep the original allocation. Absent that build, low pin caps are the only lever we found (pin 8 started on the original build; 12 completed allocation but never became READY, 16 and 32 failed earlier).

Finding 3 — keep the chunk cap at its maximum. Choose reserve values that leave the prefill chunk cap at 32,768 (on this rig: reserve 2048/lend97 for the 1M configuration), and treat any silent drop of the chunk cap as a performance regression to investigate, not a tuning detail.

Verification status

  • Where each finding was verified. All three were localized and measured on the rdna3 fork build (HEAD bd34f079da92e8b47dc4de6b40d894a867154797) on the single rig described under Environment, with full logs retained.
  • Why we believe they apply upstream. In each case the mechanism sits in shared engine code — the 2D weight-upload path, the DP session allocation in generate-main-keep.cpp, and the prefill staging/chunk logic — not in fork-specific code. Finding 1 additionally reproduces with no engine code at all, against a HIP runtime DLL that is byte-identical between the fork build and stock 0.1.56 on this machine.
  • What has not been verified. None of the three findings has yet been reproduced on a stock upstream build; the packed-upload fix, the shared-KV build and the final configuration figures are reported on this rig, not cross-platform conclusions. A second operator independently bisected the same fork build and corroborates the Finding 1 localization up to the TP path (layer-split without TP fully clean; the TP precopy self-check bit-exact), but has not yet re-run the fixes end-to-end. The script in the Appendix lets any maintainer verify Finding 1 directly in minutes.

Open item, for completeness. With the dual "stage2" configuration used for the final numbers in the companion report, one fresh engine process failed its first 64K request after a cold start (retrieval codes not recovered); six subsequent cold starts with identical inputs all passed. The root cause is not located, and those configurations are labelled "Test", not production.

Companion full report (dual-card results, topology, verification detail): https://github.com/nicejunjie/Strata-rdna3/issues/6

Appendix — reproduction script

hip_copy_diagnostic.py — standalone Finding 1 reproduction (Python/ctypes, no engine code). SHA256: 7a61551fbc6a8d93e85e60c09bd5ebe29e2ba6ab52f5e6a02cfbe02a8d9fff67

hip_copy_diagnostic.py (98 lines, SHA256 `7a61551fbc6a8d93e85e60c09bd5ebe29e2ba6ab52f5e6a02cfbe02a8d9fff67`)
import argparse
import ctypes as C
import json
import mmap
import os
import random
import statistics
import time
from pathlib import Path

w=Path(__file__).resolve().parent
p=argparse.ArgumentParser()
p.add_argument('--runtime',default='engine-upload')
p.add_argument('--base',default='baseline.json')
p.add_argument('--output',default='hip-copy-diagnostic.json')
p.add_argument('--source-file',default='hip-2d-source.bin')
p.add_argument('--skip-bandwidth',action='store_true')
a=p.parse_args()
runtime=w/a.runtime
cfg=json.loads((w/a.base).read_text(encoding='utf-8-sig'))
paths=[runtime]+[Path(p) for p in cfg['lib_dirs'] if Path(p).is_dir()]
dirs=[os.add_dll_directory(str(p)) for p in paths]
os.environ['PATH']=';'.join(str(p) for p in paths)+';'+os.environ['PATH']
hip=C.WinDLL(str(runtime/'amdhip64_7.dll'))
def function(name, argtypes):
    f=getattr(hip,name);f.argtypes=argtypes;f.restype=C.c_int;return f
count=function('hipGetDeviceCount',[C.POINTER(C.c_int)])
setdev=function('hipSetDevice',[C.c_int])
busid=function('hipDeviceGetPCIBusId',[C.c_void_p,C.c_int,C.c_int])
malloc=function('hipMalloc',[C.POINTER(C.c_void_p),C.c_size_t])
free=function('hipFree',[C.c_void_p])
hostalloc=function('hipHostMalloc',[C.POINTER(C.c_void_p),C.c_size_t,C.c_uint])
hostfree=function('hipHostFree',[C.c_void_p])
copy=function('hipMemcpy',[C.c_void_p,C.c_void_p,C.c_size_t,C.c_int])
copy2d=function('hipMemcpy2D',[C.c_void_p,C.c_size_t,C.c_void_p,C.c_size_t,C.c_size_t,C.c_size_t,C.c_int])
sync=function('hipDeviceSynchronize',[])
def check(code,name):
    if code:raise RuntimeError(name+': HIP status '+str(code))
rows,stride,width=6144,2720,1360
source=random.Random(12345).randbytes(rows*stride)
pageable=C.create_string_buffer(source)
path=w/a.source_file
path.write_bytes(b'H'*256+source)
fd=path.open('rb')
import msvcrt
k=C.WinDLL('kernel32',use_last_error=True)
k.CreateFileMappingW.argtypes=[C.c_void_p,C.c_void_p,C.c_uint,C.c_uint,C.c_uint,C.c_void_p];k.CreateFileMappingW.restype=C.c_void_p
k.MapViewOfFile.argtypes=[C.c_void_p,C.c_uint,C.c_uint,C.c_uint,C.c_size_t];k.MapViewOfFile.restype=C.c_void_p
k.UnmapViewOfFile.argtypes=[C.c_void_p];k.CloseHandle.argtypes=[C.c_void_p]
mapping=k.CreateFileMappingW(msvcrt.get_osfhandle(fd.fileno()),None,2,0,0,None)
if not mapping:raise C.WinError(C.get_last_error())
view=k.MapViewOfFile(mapping,4,0,0,0)
if not view:raise C.WinError(C.get_last_error())
n=C.c_int();check(count(C.byref(n)),'count')
results=[]
try:
    for dev in range(n.value):
        check(setdev(dev),'set device')
        bus=C.create_string_buffer(64);check(busid(bus,64,dev),'PCI bus id')
        pinned=C.c_void_p();check(hostalloc(C.byref(pinned),len(source),1),'pin source')
        C.memmove(pinned,source,len(source))
        dst=C.c_void_p();check(malloc(C.byref(dst),rows*width),'allocate destination')
        try:
            for kind,ptr in [('pageable',C.addressof(pageable)),('file-readonly-offset256',view+256),('pinned-portable',pinned.value)]:
                for half in range(2):
                    expected=b''.join(source[r*stride+half*width:r*stride+(half+1)*width] for r in range(rows))
                    check(copy2d(dst,width,ptr+half*width,stride,width,rows,1),'2D upload')
                    actual=C.create_string_buffer(rows*width)
                    check(copy(actual,dst,rows*width,2),'2D download')
                    raw=actual.raw[:rows*width]
                    bad=sum(a!=b for a,b in zip(expected,raw))
                    first=next((i for i,(a,b) in enumerate(zip(expected,raw)) if a!=b),len(expected))
                    packed=C.create_string_buffer(expected)
                    check(copy(dst,packed,len(expected),1),'packed upload')
                    check(copy(actual,dst,len(expected),2),'packed download')
                    packed_bad=sum(a!=b for a,b in zip(expected,actual.raw[:len(expected)]))
                    record={'device':dev,'pci_bus':bus.value.decode(),'source':kind,'half':half,'bytes':len(expected),'2d_mismatch':bad,'first_mismatch':first,'packed_mismatch':packed_bad}
                    results.append(record);print(json.dumps(record),flush=True)
        finally:
            check(free(dst),'free');check(hostfree(pinned),'host free')
        if a.skip_bandwidth:
            continue
        size=128*1024*1024
        h=C.c_void_p();d=C.c_void_p()
        check(hostalloc(C.byref(h),size,1),'bandwidth host allocate');C.memset(h,69,size)
        check(malloc(C.byref(d),size),'bandwidth device allocate')
        try:
            times=[]
            for r in range(6):
                begin=time.perf_counter();check(copy(d,h,size,1),'bandwidth upload');check(sync(),'bandwidth sync')
                if r:times.append(time.perf_counter()-begin)
            record={'device':dev,'pci_bus':bus.value.decode(),'upload_GB_s':size/statistics.median(times)/1e9,'times_s':times}
            results.append(record);print(json.dumps(record),flush=True)
        finally:
            check(free(d),'bandwidth free');check(hostfree(h),'bandwidth host free')
finally:
    k.UnmapViewOfFile(view);k.CloseHandle(mapping);fd.close()
    (w/a.output).write_text(json.dumps(results,indent=2),encoding='utf-8')
Originally created by @bigbrid2023 on GitHub (Nov 7, 2026). Original GitHub issue: https://github.com/Niko1221/Strata/issues/5480 Hi — this is a focused report of three engine-level findings from Windows dual-GPU field work. All three were localized and measured on a build of the rdna3 fork (HEAD `bd34f079da92e8b47dc4de6b40d894a867154797`), but in each case the mechanism sits in engine code shared with upstream — the weight-upload path, the DP session allocation, and the prefill staging logic — not in fork-specific code, which is why we are filing here as well as filing a full dual-card report with the fork. For each finding we state where it was verified and why we believe it applies upstream. **None of the three has yet been re-verified on a stock upstream build**; a standalone reproduction script for Finding 1 is included in the Appendix at the end of this issue. ## Environment - Host: Windows desktop (WDDM), i9-13900KF, 128 GB DDR4, ASUS PRIME Z690-P D4 - GPUs: 2× RX 7900 XTX 24 GB, driver 32.0.32015.7029; cards are not P2P peers (host-staged exchange) - Build where findings were localized: rdna3 fork, HEAD above; model Qwen3.8-Flash-Next UD-IQ4_XS - Relevance note for Finding 1: the HIP runtime DLL (`amdhip64_7.dll`, SHA256 `344386DD39B2BBA7060D62720054B9375401F23F2BCD29D730DD8D43019683CD`) is **byte-identical** between the fork build and the stock 0.1.56 engine on this machine, and the Finding 1 reproduction uses no engine code at all. - Finding 1 reproduces in both dock topologies tried (Gen3 x4 and Gen4 x4 link to the second card) and on both GPUs. ## Summary 1. **Silent data corruption (main finding).** On Windows, `hipMemcpy2D` with a read-only file mapping (`MapViewOfFile`, `FILE_MAP_READ`) as the source silently copies wrong data **while the API returns success**. In the engine this corrupted TP column-slice weight uploads at load time and produced deterministic garbage output. Writable RAM and pinned memory as sources are clean, and packing the slice contiguously on CPU + a single `hipMemcpy` is clean (240 slices read back with 0 bytes differing). 2. **DP foreign sessions waste ≈12.375 GiB of pinned host KV**, which is one link in 1M-context dual configurations failing to start. A shared-KV build that skips the redundant allocation starts at pin caps 12 and 16 GiB (24 GiB still never becomes READY). 3. **VRAM reserve couples into prefill chunking.** Reserve 2560 MiB shrank the prefill chunk cap from 32,768 to 29,440 and made the identical 64K input ≈35% slower; restoring the 32,768 chunk recovered ≈46–48% (the exact +48% measurement point is at reserve 1536; see Finding 3). A capacity parameter silently acting as a performance parameter may deserve a guardrail or at least a log line. ## Finding 1 — `hipMemcpy2D` from a read-only file mapping silently corrupts data **Symptom in the engine.** Dual-card tensor-parallel serve starts and generates, but output is deterministic garbage (draft acceptance 0). Layer-split without TP on the same build is fully clean. **Engine-level evidence.** The TP path uploaded GGUF weights as column slices via `hipMemcpy2D`. GPU readback of the first layer's `blk.0.ssm_out.weight` against the correct slice: ```text 8273507 / 8355840 bytes differ first mismatch offset = 0 expected byte = 244 actual byte = 69 packed = 0 ``` This is load-time model-data corruption, not an output/encoding artifact. Segment-by-segment comparison of the full first layer shows zero difference up to the layer-0 output projection, which is the first divergence (relative RMS ≈ 1.3889). All 96 dual-card all-reduces in the first window are bit-exact against the FP32 sum of both inputs, ruling out link desync. **Standalone reproduction (no engine code).** Python ctypes against the same `amdhip64_7.dll`, copying the same column half-slices (8,355,840 bytes each): | Source | Method | Result (both GPUs) | |---|---|---| | Writable host RAM | `hipMemcpy2D` | 0 bytes differ | | **Read-only file mapping (`MapViewOfFile`, `FILE_MAP_READ`)** | **`hipMemcpy2D`** | **8,323,025 / 8,355,840 bytes differ, API returns success** | | Pinned host memory | `hipMemcpy2D` | 0 bytes differ | | Any of the above, packed contiguously on CPU first | single `hipMemcpy` | 0 bytes differ | (The two byte counts above — 8,273,507 from the engine readback and 8,323,025 from the standalone repro — are two different slices/stages of the same bug, not a discrepancy.) **Where verified / why upstream-relevant.** Verified on the fork build and, independently of any engine, via ctypes against the HIP DLL that is byte-identical to the one shipping with stock 0.1.56 on this machine. Any engine path that uploads 2D slices directly out of a read-only mmap of the model file on Windows/HIP is exposed to the same failure mode. We have **not** isolated which component inside the HIP/Windows mapped-memory path is responsible (no alternate HIP version tested) and are not claiming a general Windows/driver defect — only that this source/method combination is reliably wrong on this rig while reporting success. **Not yet reproduced on a stock upstream build**; the script in the Appendix lets you verify in minutes. ## Finding 2 — DP foreign sessions allocate ≈12.375 GiB of pinned host KV and discard it; blocks 1M startup **Mechanism (source-level, shared engine code).** In `generate-main-keep.cpp`, a DP foreign session runs `session_init()`, whose `qsa_state_init()` allocates a full pinned host KV for every QSA layer. The DP path then overwrites `.host` with the owner session's KV — the first allocation is never used by that path but keeps holding pinned/lockable memory. On a dual-GPU WDDM system this matters: the source's arena branch notes a default lock/mapping protection of ≈8 GiB once many host pages are mapped to two GPUs, and 1M-context dual configs failed to start at high pin caps on the original build (pin 32 and pin 16 failed during expert-cache init; pin 12 completed allocation but never became READY in 600 s; pin 8 started and passed functional checks). **Fix and pin ladder.** A candidate build (`engine-shared-kv`) lets full-geometry DP foreign sessions borrow the owner session's host KV at init instead of allocating their own (with validation of layer range, context length, page count and KV mode/format/pointer; TP half-head sessions keep the original allocation). Runtime logs quantify the saving exactly: 12 × `avoided 1107297280 bytes` = **13,287,567,360 bytes ≈ 12.375 GiB** skipped. On the shared-KV build (1M max-context, vision on, reserve 2560 MiB), the pin ladder is (two functional 64K requests per rung — functional timings, not medians): | Expert arena pin cap | Result | |---|---| | 12 GiB | Starts (READY ≈53 s); image / Chinese / both 64K retrieval checks pass | | 16 GiB | Starts (READY ≈56 s); all checks pass — **adopted for the 1M test config** | | 24 GiB | Never READY in 600 s, no inference started — rejected | **Caveat.** This fix provably removes wasted pinned allocations. It is **not** established as the cause of the intermittent cold-start wrong answer noted at the end of this report, and we do not claim that. ## Finding 3 — VRAM reserve couples into prefill chunking **Mechanism (shared engine code).** `Prefill::take_stage()` sizes the KV staging pool from the session's total page count and `Prefill::carve()` sizes index workspaces from `max_cells`; the DP path (`dp_step_for()` / `run_dp()`) requires balanced even chunk counts. Raising max-context to 1M at reserve 2560 MiB shrank the per-GPU expert cache by ≈1.9 GiB and dropped the chunk cap from 32,768 to 29,440. A 65,536-token input then splits as 4 × 16,384 instead of 2 × 32,768 (ceil(65536/29440) = 3, padded to even 4) — more expert movement, more cross-card state publishes, smaller GEMMs. **Measurements (same shared-KV engine, pin 16 GiB, only max-context changed; functional runs):** | Max-context cap | First 64K prefill tok/s | |---|---:| | 256K | 3310.6 | | 1M (reserve 2560) | 2153.5 (≈35% lower for the identical 64K input) | Lowering reserve restored the 32,768 chunk: reserve 1536/lend93 measured 3192.9 tok/s (+≈48% vs 2164.2). The adopted final values, reserve 2048/lend97, keep chunk = 32,768 with more external-card headroom and measured 3145.9 / 3191.5 tok/s on cold 64K runs — ≈3150–3200 vs the ≈2160–2175 slow configuration (≈+46–48%). Because lowering reserve both enlarges the cache and crosses the chunk threshold, the gain cannot be split precisely between the two effects. **Why upstream-relevant.** The staging/chunk sizing logic is shared engine code, and the failure mode is silent: nothing logs that a reserve change has cut the chunk cap and cost a third of the prefill rate on identical input. A log line (or guardrail) when the chunk cap drops below the configured maximum would have saved the debugging round; at minimum the coupling is worth documenting. ## Minimal repro Finding 1 reproduces without any engine code. The standalone script `hip_copy_diagnostic.py` (Python, ctypes against `amdhip64_7.dll`) maps the model file read-only via `MapViewOfFile(..., FILE_MAP_READ)`, copies column half-slices with `hipMemcpy2D`, and compares device readback against the expected bytes; writable RAM, pinned memory and packed single-`hipMemcpy` variants run as controls. Expected results on an affected rig: read-only-mapping source → 8,323,025 / 8,355,840 bytes differ with the API returning success; every control → 0 bytes differ. The script is included in the Appendix at the end of this issue (SHA256 `7a61551fbc6a8d93e85e60c09bd5ebe29e2ba6ab52f5e6a02cfbe02a8d9fff67`). ## Workarounds **Finding 1 — pack before uploading.** Pack each column slice into one contiguous CPU buffer at load time and upload with a single `hipMemcpy` (in our fork tree: `STRATA_TP_UPLOAD_PACKED=1`; optional readback diagnostic `STRATA_TP_UPLOAD_CHECK=1`). Packing happens only at load; prefill/decode use the resident weights. With the packed build, all 240 row/column slices read back with 0 bytes differ. **Finding 2 — borrow the owner KV instead of duplicating it.** The `engine-shared-kv` build lets full-geometry DP foreign sessions borrow the owner session's host KV at init (with validation) instead of allocating their own; TP half-head sessions keep the original allocation. Absent that build, low pin caps are the only lever we found (pin 8 started on the original build; 12 completed allocation but never became READY, 16 and 32 failed earlier). **Finding 3 — keep the chunk cap at its maximum.** Choose reserve values that leave the prefill chunk cap at 32,768 (on this rig: reserve 2048/lend97 for the 1M configuration), and treat any silent drop of the chunk cap as a performance regression to investigate, not a tuning detail. ## Verification status - **Where each finding was verified.** All three were localized and measured on the rdna3 fork build (HEAD `bd34f079da92e8b47dc4de6b40d894a867154797`) on the single rig described under Environment, with full logs retained. - **Why we believe they apply upstream.** In each case the mechanism sits in shared engine code — the 2D weight-upload path, the DP session allocation in `generate-main-keep.cpp`, and the prefill staging/chunk logic — not in fork-specific code. Finding 1 additionally reproduces with no engine code at all, against a HIP runtime DLL that is byte-identical between the fork build and stock 0.1.56 on this machine. - **What has not been verified.** **None of the three findings has yet been reproduced on a stock upstream build**; the packed-upload fix, the shared-KV build and the final configuration figures are *reported on this rig*, not cross-platform conclusions. A second operator independently bisected the same fork build and corroborates the Finding 1 localization up to the TP path (layer-split without TP fully clean; the TP precopy self-check bit-exact), but has not yet re-run the fixes end-to-end. The script in the Appendix lets any maintainer verify Finding 1 directly in minutes. **Open item, for completeness.** With the dual "stage2" configuration used for the final numbers in the companion report, one fresh engine process failed its first 64K request after a cold start (retrieval codes not recovered); six subsequent cold starts with identical inputs all passed. The root cause is **not located**, and those configurations are labelled "Test", not production. Companion full report (dual-card results, topology, verification detail): https://github.com/nicejunjie/Strata-rdna3/issues/6 ## Appendix — reproduction script `hip_copy_diagnostic.py` — standalone Finding 1 reproduction (Python/ctypes, no engine code). SHA256: `7a61551fbc6a8d93e85e60c09bd5ebe29e2ba6ab52f5e6a02cfbe02a8d9fff67` <details> <summary>hip_copy_diagnostic.py (98 lines, SHA256 `7a61551fbc6a8d93e85e60c09bd5ebe29e2ba6ab52f5e6a02cfbe02a8d9fff67`)</summary> ```python import argparse import ctypes as C import json import mmap import os import random import statistics import time from pathlib import Path w=Path(__file__).resolve().parent p=argparse.ArgumentParser() p.add_argument('--runtime',default='engine-upload') p.add_argument('--base',default='baseline.json') p.add_argument('--output',default='hip-copy-diagnostic.json') p.add_argument('--source-file',default='hip-2d-source.bin') p.add_argument('--skip-bandwidth',action='store_true') a=p.parse_args() runtime=w/a.runtime cfg=json.loads((w/a.base).read_text(encoding='utf-8-sig')) paths=[runtime]+[Path(p) for p in cfg['lib_dirs'] if Path(p).is_dir()] dirs=[os.add_dll_directory(str(p)) for p in paths] os.environ['PATH']=';'.join(str(p) for p in paths)+';'+os.environ['PATH'] hip=C.WinDLL(str(runtime/'amdhip64_7.dll')) def function(name, argtypes): f=getattr(hip,name);f.argtypes=argtypes;f.restype=C.c_int;return f count=function('hipGetDeviceCount',[C.POINTER(C.c_int)]) setdev=function('hipSetDevice',[C.c_int]) busid=function('hipDeviceGetPCIBusId',[C.c_void_p,C.c_int,C.c_int]) malloc=function('hipMalloc',[C.POINTER(C.c_void_p),C.c_size_t]) free=function('hipFree',[C.c_void_p]) hostalloc=function('hipHostMalloc',[C.POINTER(C.c_void_p),C.c_size_t,C.c_uint]) hostfree=function('hipHostFree',[C.c_void_p]) copy=function('hipMemcpy',[C.c_void_p,C.c_void_p,C.c_size_t,C.c_int]) copy2d=function('hipMemcpy2D',[C.c_void_p,C.c_size_t,C.c_void_p,C.c_size_t,C.c_size_t,C.c_size_t,C.c_int]) sync=function('hipDeviceSynchronize',[]) def check(code,name): if code:raise RuntimeError(name+': HIP status '+str(code)) rows,stride,width=6144,2720,1360 source=random.Random(12345).randbytes(rows*stride) pageable=C.create_string_buffer(source) path=w/a.source_file path.write_bytes(b'H'*256+source) fd=path.open('rb') import msvcrt k=C.WinDLL('kernel32',use_last_error=True) k.CreateFileMappingW.argtypes=[C.c_void_p,C.c_void_p,C.c_uint,C.c_uint,C.c_uint,C.c_void_p];k.CreateFileMappingW.restype=C.c_void_p k.MapViewOfFile.argtypes=[C.c_void_p,C.c_uint,C.c_uint,C.c_uint,C.c_size_t];k.MapViewOfFile.restype=C.c_void_p k.UnmapViewOfFile.argtypes=[C.c_void_p];k.CloseHandle.argtypes=[C.c_void_p] mapping=k.CreateFileMappingW(msvcrt.get_osfhandle(fd.fileno()),None,2,0,0,None) if not mapping:raise C.WinError(C.get_last_error()) view=k.MapViewOfFile(mapping,4,0,0,0) if not view:raise C.WinError(C.get_last_error()) n=C.c_int();check(count(C.byref(n)),'count') results=[] try: for dev in range(n.value): check(setdev(dev),'set device') bus=C.create_string_buffer(64);check(busid(bus,64,dev),'PCI bus id') pinned=C.c_void_p();check(hostalloc(C.byref(pinned),len(source),1),'pin source') C.memmove(pinned,source,len(source)) dst=C.c_void_p();check(malloc(C.byref(dst),rows*width),'allocate destination') try: for kind,ptr in [('pageable',C.addressof(pageable)),('file-readonly-offset256',view+256),('pinned-portable',pinned.value)]: for half in range(2): expected=b''.join(source[r*stride+half*width:r*stride+(half+1)*width] for r in range(rows)) check(copy2d(dst,width,ptr+half*width,stride,width,rows,1),'2D upload') actual=C.create_string_buffer(rows*width) check(copy(actual,dst,rows*width,2),'2D download') raw=actual.raw[:rows*width] bad=sum(a!=b for a,b in zip(expected,raw)) first=next((i for i,(a,b) in enumerate(zip(expected,raw)) if a!=b),len(expected)) packed=C.create_string_buffer(expected) check(copy(dst,packed,len(expected),1),'packed upload') check(copy(actual,dst,len(expected),2),'packed download') packed_bad=sum(a!=b for a,b in zip(expected,actual.raw[:len(expected)])) record={'device':dev,'pci_bus':bus.value.decode(),'source':kind,'half':half,'bytes':len(expected),'2d_mismatch':bad,'first_mismatch':first,'packed_mismatch':packed_bad} results.append(record);print(json.dumps(record),flush=True) finally: check(free(dst),'free');check(hostfree(pinned),'host free') if a.skip_bandwidth: continue size=128*1024*1024 h=C.c_void_p();d=C.c_void_p() check(hostalloc(C.byref(h),size,1),'bandwidth host allocate');C.memset(h,69,size) check(malloc(C.byref(d),size),'bandwidth device allocate') try: times=[] for r in range(6): begin=time.perf_counter();check(copy(d,h,size,1),'bandwidth upload');check(sync(),'bandwidth sync') if r:times.append(time.perf_counter()-begin) record={'device':dev,'pci_bus':bus.value.decode(),'upload_GB_s':size/statistics.median(times)/1e9,'times_s':times} results.append(record);print(json.dumps(record),flush=True) finally: check(free(d),'bandwidth free');check(hostfree(h),'bandwidth host free') finally: k.UnmapViewOfFile(view);k.CloseHandle(mapping);fd.close() (w/a.output).write_text(json.dumps(results,indent=2),encoding='utf-8') ``` </details>
Author
Owner

@github-actions[bot] commented on GitHub (Nov 7, 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:

  • Start the title with its area: [Engine], [GUI], [TUI], [Benchmark], [Docs] or [Other], then a short description. Example: "[Engine] decode stops after 2 minutes".

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:6706654719 --> @github-actions[bot] commented on GitHub (Nov 7, 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: - [ ] Start the title with its area: [Engine], [GUI], [TUI], [Benchmark], [Docs] or [Other], then a short description. Example: "[Engine] decode stops after 2 minutes". 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 7, 2026):

Thanks, this follows the format now.

<!-- gh-comment-id:6706693580 --> @github-actions[bot] commented on GitHub (Nov 7, 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#5446
No description provided.