Repository navigation
gpu, gpu-deepseek41, gpu-gates: windows over raw memory give back their context handle on every path - #513
Conversation
There was a problem hiding this comment.
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)
922abe1 to
5fac97e
Compare
There was a problem hiding this comment.
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)
…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.
5fac97e to
458b875
Compare
There was a problem hiding this comment.
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)
|
The review is done and the contribution check passed, so I'm merging this. |
원시 메모리 창의 컨텍스트 참조를 정상 종료와 생성 오류 경로에서 모두 반납하도록 고칩니다.
What and why
bloomery_gpu::windowreturns aManuallyDrop<DeviceBuffer<T>>that holds a clone of the context'sArc. 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 ofwindow()andDeviceTensor::window, and of the helpers that return their result. These never released the handle:param_viewandf32_view(crates/gpu/src/arch/qwen3moe/scratch.rs): the arena and lane-word windows, everyInbox::upload(once per step), the tap rows, the MTP and ubatch views.rows_of: every window of every unit of a wide walk.R8Kernels::enqueue_in_place(gpu-deepseek41 swap.rs),Stream::spaninlink_probe,transform_checkin the residency clauses, andx_offingate_gemm'sg32_refusecase.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).Shadows::new), and the refusal windows inprefill_gateandgate_qwen3moe_flash.LayerScratch::new, whereParamImage::newreturned 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 checkedWindow::ofinstead, so their hand pointer arithmetic and unsafe blocks go. The constructors that keep manual handles finish their fallible work first:Shadows::newchecks every offset withchecked_mul, andLayerScratch::newallocates 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'sDropor release the handle before propagating an error.Each kind of window now has one constructor:
Body::set_taps,Body35::set_taps). They are nowTapRows::set, which bothset_layer_tapscall.RowsParamsand Qwen3.8'sPassRecordcut the same pass record (eight ids, the position word, the lane word after the ids). They are now onePassRecord<ROWS>in qwen3moe's scratch.rs.LegWindow(host/arena_leg.rs) was its own copy ofWindowMut::from_raw, with its ownDrop. The leg now usesWindowMut::from_raw.The
gpuunsafe pin goes from 1960 to 1953 blocks and from 214 to 213 fns, and thegpu-gatespin from 89 to 81 blocks.Release notes: Fixed: Raw-memory windows release their CUDA context references on successful and failed construction.
gate_deepseek41_unpack'sequalclause 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
WindoworWindowMutwhose drop gives the handle back. A new leak needs a newwindow()orfrom_raw_partscall outside those types, which shows up as a new unsafe block against the per-crate pin intools/unsafe-ratchet.txt.What I ran
Head
09e8f7f8on mainfda5eca2, unless a line names another head.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 logbefore 6 after 22and the unit windowbefore 3 after 4;test result: FAILED. 0 passed; 2 failed. Every unpackequalline sayscontext handle HELD FAIL. This run used head3469cb97, which differs from09e8f7f8only in host/arena_leg.rs and the unsafe pin.NVIDIA GB10, 595.84, main821d7b85), with the tests and fault hooks on the original constructors: DeepSeek2 loggedbefore 9 after 13, and the boundary loggedbefore 2 after 6;test result: FAILED. 0 passed; 2 failed. The original batch tier leg loggedbefore 13 after 14;test result: FAILED. 0 passed; 1 failed. These constructors and tests are unchanged since.bash tools/gate.sh --oxide -p bloomery-gpu --release --lib -- --include-ignored --nocapture --test-threads=1with the six context-count tests andhw_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.just arch=sm_120 gate-gpu-ds41-unpack(head3469cb97): everyequalline sayscontext handle released PASS;gate_deepseek41_unpack: PASS.just arch=sm_120 gate-gpu-gemma-embedding2-head512, which runsprefill_gate::window_refusalswithout a model file:prefill windows at aligned offsets: accepted, bit-identical to the plain launch true PASS, the q, kc and vc windowsrefused by name PASS;gate_gemma_embedding2_head512: PASS.NVIDIA GB10, 595.84, 12.1,sm_121),just arch=sm_121 gate-gpu-gemm --case g32_refuse, withBLOOMERY_REF_MODELset to Qwen3-30B-A3B-Instruct-2507 Q4_K_M: every refusal case reportsrefused;PASSED: gate_gemm.bash tools/ptx-compare.sh fda5eca2 generate_qwen3moe --features gpu(head3469cb97, scanner targetsm_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-targetswith the gates'gpu,deepseek41andglm5nextfeatures passed, and so did the host tests ofgate_ds41_nvtierandgate_glm5next_nvtier.gpu 1953 213 10 = pin,gpu-gates 81 5 1 = pin).Dispatch check
This check ran in the earlier round on head
20cef029against main821d7b85. 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=33andctx=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
Pin512 4096, the runner wasbash tools/ref/depth-qwen3moe.sh P@BLOOMERY_AB_LOAD=arm bin:BASE_BINARY:P@BLOOMERY_AB_LOAD=arm, withBLOOMERY_AB_ROUNDS=4,BLOOMERY_DECODE_N=33,BLOOMERY_GEN_CTX=4608and the Qwen3moe profile.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-flashandgate-gpu-qwen3moe-e2e(the layer taps) did not run: the flash gate stopped at its first reference read (ref_qwen3moe_step4_every_node/MANIFEST.tsvmissing), 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 runlink_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 초안 리뷰는 제가 직접 했습니다.