Skip to content

gpu, gpu-deepseek41, gpu-gates: windows over raw memory give back their context handle on every path - #513

Merged
juliankang4 merged 1 commit into
midagedev:mainfrom
juliankang4:fix-window-context-handle
Oct 20, 2026
Merged

juliankang4 merged 1 commit into
midagedev:mainfrom
juliankang4:fix-window-context-handle

Conversation

@juliankang4

@juliankang4 juliankang4 commented Oct 19, 2026 •

Copy link
Copy Markdown
Collaborator

원시 메모리 창의 컨텍스트 참조를 정상 종료와 생성 오류 경로에서 모두 반납하도록 고칩니다.

What and why

bloomery_gpu::window returns a ManuallyDrop<DeviceBuffer<T>> that holds a clone of the context's Arc. Its caller has to give that handle back (into_raw_parts) or it is never released, and the context cannot be destroyed when its last real owner drops it. I went through every caller of window() and DeviceTensor::window, and of the helpers that return their result. These never released the handle:

  • qwen3moe's param_view and f32_view (crates/gpu/src/arch/qwen3moe/scratch.rs): the arena and lane-word windows, every Inbox::upload (once per step), the tap rows, the MTP and ubatch views.
  • wide38's rows_of: every window of every unit of a wide walk.
  • R8Kernels::enqueue_in_place (gpu-deepseek41 swap.rs), Stream::span in link_probe, transform_check in the residency clauses, and x_off in gate_gemm's g32_refuse case.

These released it, but not when an error returned first:

  • Boundary::with_cols (host/step.rs), a tier leg's staging rows (host/batch.rs), the tier fault copy (host/tier.rs).
  • The deepseek41 ring shadows (Shadows::new), and the refusal windows in prefill_gate and gate_qwen3moe_flash.
  • DeepSeek2's LayerScratch::new, where ParamImage::new returned four manual handles before the remaining scratch allocations could fail.

The scoped windows now use WindowMut::from_raw, whose drop releases the handle and frees nothing. The gates' refusal windows over a buffer they hold (prefill_gate, gate_qwen3moe_flash, gate_gemm) use the checked Window::of instead, so their hand pointer arithmetic and unsafe blocks go. The constructors that keep manual handles finish their fallible work first: Shadows::new checks every offset with checked_mul, and LayerScratch::new allocates every scratch buffer, gather table and probe before taking the parameter image's handles. I also checked the remaining manual buffer and tensor handles through their constructors and callers. They either have an owning type's Drop or release the handle before propagating an error.

Each kind of window now has one constructor:

  • The Qwen3-MoE and Qwen3.6 layer taps had two copies of the same allocation and row cut (Body::set_taps, Body35::set_taps). They are now TapRows::set, which both set_layer_taps call.
  • Qwen3.6's RowsParams and Qwen3.8's PassRecord cut the same pass record (eight ids, the position word, the lane word after the ids). They are now one PassRecord<ROWS> in qwen3moe's scratch.rs.
  • The arena leg's LegWindow (host/arena_leg.rs) was its own copy of WindowMut::from_raw, with its own Drop. The leg now uses WindowMut::from_raw.

The gpu unsafe pin goes from 1960 to 1953 blocks and from 214 to 213 fns, and the gpu-gates pin from 89 to 81 blocks.

Release notes: Fixed: Raw-memory windows release their CUDA context references on successful and failed construction.

gate_deepseek41_unpack's equal clause checks that the context's strong count is the same after an in-place unpack as before it. Card tests check the same for the qwen3moe views (hw_the_views_give_back_their_context_handles: an upload, a lane word with three views, a pass record, the layer taps armed twice and a row view) and for a wide38 unit window (hw_a_unit_window_gives_back_its_context_handle). A shared test-only fault hook forces errors at the boundary's final sum allocation, DeepSeek2's first scratch allocation and the batch tier leg's places allocation. Each error case asserts that the constructor returns the injected error and leaves the context count unchanged.

The count is read only in tests because after this change no window in these paths needs a manual release: each one is a Window or WindowMut whose drop gives the handle back. A new leak needs a new window() or from_raw_parts call outside those types, which shows up as a new unsafe block against the per-crate pin in tools/unsafe-ratchet.txt.

What I ran

Head 09e8f7f8 on main fda5eca2, unless a line names another head.

  • FAIL-first on main fda5eca2, RTX 5090 (NVIDIA GeForce RTX 5090, 595.99.02, 12.0, sm_120): the head's view and unit-window tests and its unpack gate, put into main's tree unchanged, fail. The views log before 6 after 22 and the unit window before 3 after 4; test result: FAILED. 0 passed; 2 failed. Every unpack equal line says context handle HELD FAIL. This run used head 3469cb97, which differs from 09e8f7f8 only in host/arena_leg.rs and the unsafe pin.
  • FAIL-first from the earlier round (DGX Spark, NVIDIA GB10, 595.84, main 821d7b85), with the tests and fault hooks on the original constructors: DeepSeek2 logged before 9 after 13, and the boundary logged before 2 after 6; test result: FAILED. 0 passed; 2 failed. The original batch tier leg logged before 13 after 14; test result: FAILED. 0 passed; 1 failed. These constructors and tests are unchanged since.
  • RTX 5090, bash tools/gate.sh --oxide -p bloomery-gpu --release --lib -- --include-ignored --nocapture --test-threads=1 with the six context-count tests and hw_the_card_leg_sums_its_held_ids_as_the_stack_launches_do: test result: ok. 7 passed; 0 failed. The views and the unit window leave counts unchanged (before 6 after 6, before 3 after 3), as do the injected scratch, batch and boundary failures (before 9 after 9, before 13 after 13, before 2 after 2). The card leg test builds the arena leg over its windows and matches the stack launches bit for bit.
  • RTX 5090, just arch=sm_120 gate-gpu-ds41-unpack (head 3469cb97): every equal line says context handle released PASS; gate_deepseek41_unpack: PASS.
  • RTX 5090, just arch=sm_120 gate-gpu-gemma-embedding2-head512, which runs prefill_gate::window_refusals without a model file: prefill windows at aligned offsets: accepted, bit-identical to the plain launch true PASS, the q, kc and vc windows refused by name PASS; gate_gemma_embedding2_head512: PASS.
  • DGX Spark (NVIDIA GB10, 595.84, 12.1, sm_121), just arch=sm_121 gate-gpu-gemm --case g32_refuse, with BLOOMERY_REF_MODEL set to Qwen3-30B-A3B-Instruct-2507 Q4_K_M: every refusal case reports refused; PASSED: gate_gemm.
  • bash tools/ptx-compare.sh fda5eca2 generate_qwen3moe --features gpu (head 3469cb97, scanner target sm_86, JIT on the RTX 5090): 277 entries on each side, no added, removed or changed entries; ptx-compare: identical (rc 0).
  • cargo check -p bloomery-gpu -p bloomery-gpu-gates -p bloomery-gpu-glm5next --all-targets with the gates' gpu, deepseek41 and glm5next features passed, and so did the host tests of gate_ds41_nvtier and gate_glm5next_nvtier.
  • On a Linux CPU host, pinned rustfmt over every changed file and the unsafe ratchet passed (gpu 1953 213 10 = pin, gpu-gates 81 5 1 = pin).

Dispatch check

This check ran in the earlier round on head 20cef029 against main 821d7b85. The changes since then are the shared tap and pass-record constructors, the arena leg and the gates; none of them is on the Qwen3-MoE decode or prefill path it measures, so it was not repeated.

The same Qwen3-30B-A3B-Instruct-2507 Q4_K_M file ran on both binaries with BLOOMERY_AB_LOAD=arm, n=33 and ctx=4608. Each prompt length used its own lease, with four runs per binary in ABBAABBA order. The two comparisons therefore have separate leases; together they took 79 seconds.

For each P in 512 4096, the runner was bash tools/ref/depth-qwen3moe.sh P@BLOOMERY_AB_LOAD=arm bin:BASE_BINARY:P@BLOOMERY_AB_LOAD=arm, with BLOOMERY_AB_ROUNDS=4, BLOOMERY_DECODE_N=33, BLOOMERY_GEN_CTX=4608 and the Qwen3moe profile.

Metric Prompt/depth Main tok/s Head tok/s Delta [derived]
Decode 512 99.09 98.92 -0.17%
Decode 4096 83.12 82.85 -0.32%
Prefill 512 3257.10 3251.89 -0.16%
Prefill 4096 4866.73 4871.56 +0.10%

Delta is derived from the displayed means. Every paired 95% interval includes zero, so these samples do not resolve a throughput change. Contention, cold, failed-arm and token-mismatch counters were all zero.

For the container run, a per-run adapter corrected findmnt's bind-root notation when identifying the physical drive; both arms used the same model and measurement path. The kernel-journal guard used the host's real journal reader and mounted journal files. No timing guard was relaxed.

What I ran into

None of this blocks the PR. gate-gpu-qwen3moe-flash and gate-gpu-qwen3moe-e2e (the layer taps) did not run: the flash gate stopped at its first reference read (ref_qwen3moe_step4_every_node/MANIFEST.tsv missing), and no machine I could use has the Qwen3-MoE reference sets. The shared tap and pass-record constructors are covered by the card test above, and the prefill refusal windows by the EmbeddingGemma 2 gate. The DeepSeek V4.1 and GLM tier gates over the arena leg need model files I did not have on these machines; the card leg test covers the leg. I did not run link_probe, which needs two nodes with RDMA, or the residency gates, which need reference sets or model files. The boundary, DeepSeek2 and batch tier leg tests force allocation errors. The fault copy and ring shadows do not have forced-error tests.

AI help

AI 코딩 에이전트가 코드를 작성한 후 설명을 썼고, 테스트를 마쳤습니다. diff 리뷰와 PR 초안 리뷰는 제가 직접 했습니다.

@github-actions github-actions Bot added gpu The card engine: crates/gpu*, crates/app needs-gpu Changes code a card must check, and carries no gate run on a card tools Tools, recipes, CI and the toolchain: tools/, justfile, .github/, Cargo labels Oct 19, 2026

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Verdict: MUST_FIX: A sibling caller still leaks the context handle this PR fixes elsewhere.

Must fix

1. Release the sibling gate's context handle

crates/gpu-gates/src/bin/gate_gemm.rs:5761 Running the g32_refuse case reaches refusals(), where x_off uses window(). That constructor clones the context's Arc into a ManuallyDrop<DeviceBuffer<_>>. The function returns without releasing its raw parts, leaving a strong reference that prevents context teardown when the real owners drop. One call per process bounds the leak but retains the same defect on this sibling path.

The existing constructor replacement closes this caller during the current leak audit. Replace the x_off declaration, keeping its safety comment:

let x_off = unsafe {
    bloomery_gpu::WindowMut::<f32>::from_raw(x.cu_deviceptr() + 4, 4 * k, x.context())
};

Non-blocking

⚠ Supply complete GPU evidence: crates/gpu-gates/src/bin/gate_deepseek41_unpack.rs:93. The report lacks the nvidia-smi line, the base revision used for the FAIL-first run, and the exact just gate-* invocation with output. Attach them so the run can be reproduced and receive the GPU evidence label.

Checked

Duplicates: no new functions, types or constants; the changed span reuses WindowMut.

Complexity: equal adds one boolean condition.

Silent failure: the two existing display defaults only format comparison results; mismatches still reach the gate's failing exit status. Changed CUDA calls propagate errors.

Tests: restoring window() at swap.rs:543 leaves an extra reference; released becomes false, equal fails, and the gate exits unsuccessfully. The PR reports this FAIL-first result.

Gates: no threshold or pin moved; the existing equal clause gains the handle-release check.

Memory: dropping WindowMut releases the context handle without freeing the backing allocation. No device launch, copy, allocation or synchronization was added.

Escape catalog: no C1–C4 pattern matched.

Notes

Static validation only; GPU gates were not rerun.

Card check: needs-gpu. This pull request changes crates/gpu-deepseek41/src/swap.rs, crates/gpu-gates/src/bin/gate_deepseek41_unpack.rs, crates/gpu-gates/src/bin/link_probe.rs … and carries no gate run on a card (CONTRIBUTING's evidence list); a maintainer adds gpu-verified after one.

🔨 Shingler, bloomery's review bot: approves a clean pull request and requests changes on a must-fix (how it works)

@juliankang4
juliankang4 force-pushed the fix-window-context-handle branch from 922abe1 to 5fac97e Compare October 20, 2026 01:21
@juliankang4 juliankang4 changed the title gpu-deepseek41, gpu-gates: the swap unpack's and link_probe's page windows give back their context handle gpu, gpu-deepseek41, gpu-gates: windows over raw memory give back their context handle on every path Oct 20, 2026

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Verdict: MUST_FIX: the changed tap allocation has two owners.

Must fix

1. Put tap allocation on the shared TapRows owner

crates/gpu/src/arch/qwen3moe/body.rs:627 and crates/gpu/src/arch/qwen3moe/body35.rs:2272 allocate the same buffer and cut the same rows into the same type. No architecture fact differs. This is kind B duplication (R14).
Fixing ownership in one place now avoids maintaining both unsafe constructions.

Add this beside TapRows in body.rs. Delete both bodies' set_taps methods, remove the f32_view import from body35.rs, and change the Body::taps doc link to TapRows::set. This replaces two allocation functions with one.

impl TapRows {
    pub(super) fn set(
        taps: &mut Option<Self>,
        stream: &CudaStream,
        layers: usize,
        hidden: usize,
        on: bool,
    ) -> Result<(), GpuError> {
        *taps = None;
        if on {
            let buf = DeviceBuffer::<f32>::zeroed(stream, layers * hidden)?;
            let rows = (0..layers)
                // SAFETY: each row lies inside buf; the parent and windows
                // stay together, and dropping a window frees no memory.
                .map(|l| unsafe { f32_view(&buf, l * hidden, hidden) })
                .collect();
            *taps = Some(Self { buf, rows });
        }
        Ok(())
    }
}

Replace set_layer_taps in taps.rs with:

pub fn set_layer_taps(&mut self, on: bool) -> Result<(), GpuError> {
    self.set_mode(StepMode::Eager);
    let (gpu, _, body) = self.body_parts("qwen3moe::set_layer_taps")?;
    super::body::TapRows::set(
        &mut body.taps,
        gpu.stream(),
        body.plans.len(),
        body.s.dims.hidden,
        on,
    )
}

Replace set_layer_taps in taps35.rs with:

pub fn set_layer_taps(&mut self, on: bool) -> Result<(), GpuError> {
    self.set_mode(StepMode::Eager);
    let (gpu, _, body) = self.body_parts("qwen35moe::set_layer_taps")?;
    super::body::TapRows::set(
        &mut body.taps,
        gpu.stream(),
        body.plans.len(),
        body.s.dims.hidden,
        on,
    )
}

Non-blocking

⚠ Explain the diagnostic coverage: crates/gpu/src/arch/qwen3moe/scratch.rs:1920 exposes context counts only in tests. Why is that sufficient for diagnosing recurrence? State the reason in the PR body, or reuse an existing diagnostic record so another leak does not require fresh instrumentation.

Checked

Duplicates: both changed tap allocators and their callers read; they construct the same existing TapRows type. The fix replaces two methods with one.
Complexity: each tap setter has one if on branch; no architecture-specific branch distinguishes them.
Silent failure: both tap setters propagate allocation errors with ?.
Tests: the Qwen view test asserts that the context count returns to its starting value after the views drop.
Gates: no gate thresholds change in the tap-allocation hunks.
Escape catalog: no pattern applies to these findings. No ledger lessons are in force.

Notes

GPU tests were not rerun during this static review. The PR reports GB10 gate runs and identical PTX. FAIL-first output covers the injected constructor failures; it does not show the new view/window or unpack count checks failing on the base.

Card check: gpu-evidence. This pull request changes crates/gpu-deepseek41/src/body.rs, crates/gpu-deepseek41/src/swap.rs, crates/gpu-gates/src/bin/gate_deepseek41_unpack.rs … and carries a gate run on the author's card, which counts as verified.

🔨 Shingler, bloomery's review bot: approves a clean pull request and requests changes on a must-fix (how it works)

@github-actions github-actions Bot added gpu-evidence Verified on the author's card: the pull request carries the gate run and its output and removed needs-gpu Changes code a card must check, and carries no gate run on a card labels Oct 20, 2026
…ir context handle on every path

window() wraps a non-owning DeviceBuffer in ManuallyDrop, so a caller that never drops its raw parts keeps one handle
on the context for good. qwen3moe's param_view, f32_view and wide38's unit windows (every input upload, unit walk,
tap row, lane word and arena block over them), R8Kernels::enqueue_in_place, link_probe's Stream::span, the residency
clauses' slot reads and gate_gemm's g32_refuse offset input never released theirs; the boundary page, a tier leg's
staging rows, the tier fault copy, the ring shadows and the prefill gates' refusal windows released theirs only when
no error came first. The windows over memory beside its owner now take WindowMut::from_raw, whose drop releases the
handle and frees nothing (the ring shadows check every offset before the first window); the gates' windows over a
buffer they hold take the checked Window::of instead. The manual releases and Drop impls those types replace go,
and so does the arena leg's LegWindow, which did the same as WindowMut::from_raw.

The layer taps of Qwen3-MoE and Qwen3.6 are cut by one TapRows::set, and Qwen3.6's and Qwen3.8's pass records
are one PassRecord in scratch.rs, so each of those windows has one constructor. A constructor that fails after its
windows are cut gives them back too: DeepSeek2's LayerScratch allocates everything before its parameter image, and
the boundary and the tier leg drop the windows they hold. gpu's unsafe pin comes down by seven blocks and one fn,
gpu-gates' by eight blocks.

gate_deepseek41_unpack's equal clause checks that the context's handle count is the same after an in-place unpack as
before it, and card tests check the same for the qwen3moe views, pass record and layer taps, the unit windows, and a
boundary, scratch and tier leg whose allocation fails after their windows are cut.
@juliankang4
juliankang4 force-pushed the fix-window-context-handle branch from 5fac97e to 458b875 Compare October 20, 2026 03:03

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Since the last review:

  • Must-fix 1 fixed: both tap setters use TapRows::set at crates/gpu/src/arch/qwen3moe/body.rs:202.
  • Diagnostic-coverage question answered: the PR body explains the context-count tests and unsafe ratchet.

Verdict: CLEAN: the earlier finding is resolved, and the interdiff has no surviving behavior or quality finding.

Checked

Duplicates: 9 new definitions checked. Both dryer pairs read: the tap setters delegate to one owner; the two view functions retain distinct typed offset contracts. PassRecord replaces both record implementations; WindowMut replaces LegWindow.
Complexity: window_refusals 19→23 and g32::refusals 42→43 gain checked-window error exits. LayerScratch::new 40→41 gains a test fault hook, unchanged in the interdiff. No new model-policy branch appears.
Silent failure: 0 new defaulting sites; all 8 checked-window calls propagate errors. PassRecord rejects empty and oversized input with named errors.
Tests (mutation by inspection): restoring leaking manual handles at scratch.rs:1765 or scratch.rs:1782 fails the extended view test's context-count assertion. Flipping body.rs:210's on branch fails its row-count assertion. The PR supplies FAIL-first output.
Gates: no tolerance or case is relaxed. Unsafe pins tighten to gpu 1967 blocks/221 functions and gpu-gates 81 blocks.
Behavior: zero and excessive pass widths are guarded; tap rearming clears captures before replacing buffers; partial arena-leg construction releases its windows.
Performance: the ownership substitutions add no device launches, copies or token allocations. The PR reports identical PTX; the reported decode/prefill A/B intervals include zero.
Escape catalog: no matching pattern. No ledger lessons are in force.

Notes

Static review only; GPU tests were not rerun here. The PR reports RTX 5090 and GB10 gate output and discloses unavailable reference-set and multi-node runs.
Dryer did not search gpu-gates; the changed gate-window constructors were checked directly.

Card check: gpu-evidence. This pull request changes crates/gpu-deepseek41/src/body.rs, crates/gpu-deepseek41/src/swap.rs, crates/gpu-gates/src/bin/gate_deepseek41_unpack.rs … and carries a gate run on the author's card, which counts as verified.

🔨 Shingler, bloomery's review bot: approves a clean pull request and requests changes on a must-fix (how it works)

@juliankang4

Copy link
Copy Markdown
Collaborator Author

The review is done and the contribution check passed, so I'm merging this.

@juliankang4
juliankang4 merged commit d422f52 into midagedev:main Oct 20, 2026
6 of 10 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

gpu The card engine: crates/gpu*, crates/app gpu-evidence Verified on the author's card: the pull request carries the gate run and its output tools Tools, recipes, CI and the toolchain: tools/, justfile, .github/, Cargo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant