Repository navigation
hip-native: add dense Qwen3.5 full-forward and observed HIP reference comparison - #476
Conversation
There was a problem hiding this comment.
Verdict: MUST_FIX: probe and transfer logic has duplicate owners, and unsafe blocks lack required invariants.
Must fix
1. Keep one owner for probe comparisons and fault checks
labs/hip-native/host/src/forward_core_probe.rs:15 and labs/hip-native/host/src/forward_mixer_probe.rs:22 duplicate the finite/NMSE gate and fault-word check (kind B, R14). Their zero-energy policies already differ. Share these owners before more probes attach; this removes two definitions.
Delete core's compare and fault_is; import the mixer versions:
use crate::forward_mixer_probe::{compare, fault_is};Use these definitions in the mixer probe; core calls can discard NMSE.
pub(super) fn compare(name: &str, got: &[f32], want: &[f32]) -> Result<f64, String> {
if got.len() != want.len() || got.is_empty() {
return Err(format!("{name}: invalid oracle span"));
}
let (mut error, mut energy, mut max_abs) = (0.0f64, 0.0f64, 0.0f64);
for (i, (&a, &b)) in got.iter().zip(want).enumerate() {
if !a.is_finite() || !b.is_finite() {
return Err(format!("{name}: nonfinite value {i}: gpu={a} oracle={b}"));
}
let delta = f64::from(a) - f64::from(b);
error += delta * delta;
energy += f64::from(b) * f64::from(b);
max_abs = max_abs.max(delta.abs());
}
let nmse = if energy == 0.0 {
if error == 0.0 { 0.0 } else { f64::INFINITY }
} else {
error / energy
};
if !nmse.is_finite() || nmse > 1.0e-6 {
return Err(format!("{name}: NMSE={nmse}, max_abs={max_abs}, limit=1e-6"));
}
println!("{{\"operation\":\"{name}\",\"values\":{},\"nmse\":{nmse},\"max_abs\":{max_abs}}}", got.len());
Ok(nmse)
}pub(super) fn fault_is(ctx: &Context, fault: *mut c_void, want: u32, name: &str) -> Result<(), String> {
let mut word = [0u32];
ctx.download(fault, &mut word)?;
if word[0] != want {
return Err(format!("{name}: fault={:#x}, expected={want:#x}", word[0]));
}
Ok(())
}2. Consolidate the host transfer helpers
labs/hip-native/host/src/main.rs:205 duplicates labs/hip-native/host/src/selected.rs:85's typed upload/read logic. labs/hip-native/host/src/forward_mixer_probe.rs:50 also copies selected::overwrite (kind B, R14). One owner keeps later transfer changes local.
Keep Context::upload/download; move overwrite into its impl and call it from upload after allocation:
fn overwrite<T: Copy>(&self, ptr: *mut c_void, values: &[T]) -> Result<(), String> {
// SAFETY: callers retain the allocation covering this typed span; copy synchronizes.
unsafe { self.copy(ptr, values.as_ptr().cast(), std::mem::size_of_val(values), 1) }
}Delete selected::{upload,read,overwrite} and the mixer probe's overwrite. Replace upload(context, x), read(context, p, x), and overwrite(ctx, p, x) with the corresponding context.upload(x), context.download(p, x), and ctx.overwrite(p, x) calls. This removes three definitions.
3. Put the bounds invariant beside each unsafe operation
labs/hip-native/device/src/forward_mixer.rs:35 dereferences p.add(i) without a local SAFETY comment. There are 25 undocumented mixer blocks; labs/hip-native/device/src/forward_math.rs:15 adds another (kind B, R1). Record the invariants while adding the arithmetic. The excluded lab does not enable undocumented_unsafe_blocks.
For input, use:
unsafe fn input(p: *const f32, i: usize, fault: *mut u32, tag: u32) -> f32 {
// SAFETY: callers provide a live F32 span containing i.
let x = unsafe { *p.add(i) };
if x.is_finite() {
x
} else {
// SAFETY: callers provide the launch's live, aligned atomic fault word.
unsafe { mark(fault, tag) };
f32::NAN
}
}Document the remaining blocks' spans, lane ownership, or fault-word invariants locally. Keep kernel bodies intact.
Optimization headroom
- G, per-launch and per-sync fixed cost: labs/hip-native/host/src/main.rs:173 synchronizes after every launch in
Model::step. Queue kernels on the existing stream and wait at summary readback: remove 18×17 + 6×14 + 4 = 394 launch synchronizations/token for the documented 18-GDN/6-GQA model [derived].
Checked
Duplicates: both comparison/fault owners and all cited transfer helpers read; the fixes reduce definitions.
Unsafe: 25 mixer blocks and one math block lack local SAFETY comments.
Headroom: launch count traced through Model::step; axis G confirmed.
Scope: full review; the duplicated implementations and undocumented blocks are added by the diff. No escape-catalog pattern applies to these findings.
Notes
Validation was by source inspection; tests and GPU execution were not rerun. External evidence links were not opened.
🔨 Shingler, bloomery's review bot: approves a clean pull request and requests changes on a must-fix (how it works)
|
Addressed all three MUST_FIX findings in
Fresh clean-HEAD canonical verification: 8 groups / 18 GPU cases passed. Reference/compare self-tests, root contracts, normal HIP reference build, CPU reset compatibility, small HIP comparison and refset library tests (246 passed / 3 ignored) passed. Both fixed English/Korean prompts retain independent greedy8 + forced8 agreement, full finite 248320-value rows, reset2 bit identity and all previous full-row hashes. New exact-source evidence, ledger and reproduction. Source and evidence commits are separate; PR body links now target the new snapshot. The optional synchronization optimization is intentionally not implemented; no performance or production-backend claim. Please re-review the required corrections. |
There was a problem hiding this comment.
Since the last review:
- Comparison and fault-check duplication: fixed in labs/hip-native/host/src/forward_mixer_probe.rs:22.
- Transfer duplication: fixed in labs/hip-native/host/src/main.rs:212.
- Unsafe invariants: fixed beside the mixer and math operations, starting at labs/hip-native/device/src/forward_mixer.rs:35.
- Synchronization advice: answered by the author; intentionally deferred.
Verdict: CLEAN: The earlier must-fix items are resolved, and the incremental changes introduce no blocking defect.
Checked
Duplicates: 2 new function definitions checked; overwrite moves an existing owner, and the regression is unique. Core and mixer now share comparison and fault checks. No dryer pairs were supplied.
Complexity: crapper flags new Plan::open, mixer gdn/gqa, core refusals/elementwise/packed, Model::step/load, probe_contract, forward::run, and kernel gdn_conv; main::run grows one branch. These are full-PR scores. This increment adds no branches to those functions; the kernel remains intact.
Silent failure: 0 new default or discarded-error sites. Comparison refusals abort both probe families; migrated transfers propagate errors.
Tests: restoring a denominator floor in compare's normalization at line 38 fails the zero/tiny-oracle assertions. Changing the threshold comparison at line 43 from > to >= fails the at-limit assertion. These are source-level mutation checks.
Gates: the 1e-6 band is unchanged; zero/tiny-energy acceptance is tightened.
Memory and errors: migrated copies retain their byte counts, directions, synchronization, and error propagation. F32 gain admission protects the four-byte restore.
Performance: device executable lines are unchanged; the transfer consolidation adds no launches, copies, or synchronization.
Escape catalog: no C1–C4 pattern matches.
Notes
Dryer did not run because changed Rust files are outside crates/. Rust tests and HIP execution were not rerun. External evidence links were not opened.
🔨 Shingler, bloomery's review bot: approves a clean pull request and requests changes on a must-fix (how it works)
Filed outside this PR: #479
|
Implemented #479 in Actual GPU FAIL-first: the parent host accepted both cols1/32 zero-oracle mutants (K256, rows4, 576 zero bytes; output store +1e-20). After the fix the same all-column mutant is refused with exit1/NMSE infinity. A separate cols32-only mutant proves that cols1 succeeds before cols32 is refused. The unmodified device still passes both zero-output cases with NMSE0/exit0. The permanent Q4 oracle regression fails before the change and passes afterward, including tiny nonzero oracle energy. Q4, FFN and core/mixer gates share one normalization/acceptance owner; F64 oracles and the 1e-6 threshold are retained. Only 3 host/doc files changed in this increment; device ELF, launches/copies/synchronization and all full-model output row hashes are unchanged. Fresh exact-clean-HEAD verification passed all 8 canonical groups, 18 GPU cases, root contracts/self-tests, normal reference build, CPU reset compatibility, small and fixed English/Korean HIP comparisons, and refset tests (246 passed / 3 ignored). Evidence, source identities, mutation patches, ledger and reproduction. Please review this increment; prior approval is not treated as approval of the new HEAD. |
There was a problem hiding this comment.
Since the last review:
- Comparison and fault-check duplication: fixed; NMSE acceptance now also serves Q4 and FFN.
- Transfer duplication: fixed; unchanged in this increment.
- Unsafe invariants: fixed; unchanged in this increment.
- Synchronization advice: answered by the author; deferred.
Verdict: CLEAN: The incremental changes remove denominator-floor acceptance without introducing a blocking defect.
Non-blocking
⚠ Refresh exact-head evidence: labs/hip-native/host/src/main.rs:314. The body names verified head f71e1483, while this review covers 1a3d1a6f.
Attach the lab verifier JSON for this head, including the new regression's result. CONTRIBUTING requires matching head evidence; doing this before merge keeps the changed gate attributable.
Checked
Duplicates: 3 new definitions checked. checked_nmse consolidates acceptance; q4_nmse moves the existing oracle; the regression checks Q4 integration. No duplicate owner found. No dryer pairs supplied.
Complexity: crapper's Plan::open, mixer gdn/gqa, core refusals/elementwise/packed, Model::step/load, probe_contract, forward::run and kernel gdn_conv scores describe pre-reviewed additions. main::run's prior growth is one branch. This increment adds no growth there.
Silent failure: 0 new default or discarded-error sites; 3 changed acceptance sites followed. Rejection propagates to main's exit code 1 before success records.
Tests: source-level mutation check at labs/hip-native/host/src/main.rs:318: adding a denominator floor makes the new Q4 tiny-oracle assertions fail for 1 and 32 columns. Changing > to >= at line 320 fails the existing at-limit assertion. Rust tests were not executed.
Gates: the 1e-6 band is unchanged; two denominator floors are removed. No gate is relaxed.
Bounds and numerics: case's shape check protects the extracted oracle's spans; its F64 loop is unchanged. Nonfinite values remain rejected; exact zero remains accepted.
Performance: this increment changes verification code, with no hot-path launch, copy or synchronization change.
Escape catalog: no C1–C4 pattern matches.
Notes
Dryer did not run because changed Rust files are outside crates/. HIP execution was not rerun. External evidence links were not opened.
🔨 Shingler, bloomery's review bot: approves a clean pull request and requests changes on a must-fix (how it works)
|
Exact-head evidence clarification for the non-blocking review note: The current PR body identifies verified source
Reports/logs are explicitly path-redacted derivatives; source/tree/binary/model identities, numeric spellings and statuses are unchanged. Complete unmodified originals are retained locally. The separate evidence commit |
|
@Burntgogi Thanks for the contribution. The review is done, so I'm merging this. |
What and why
Extend the excluded native HIP contributor lab with an eager dense Qwen3.5 full-forward numerical harness and a same-file llama.cpp HIP comparison. This follows the agreed full-forward step in #87 after merged #248 and #252. It does not close #87 or introduce a production backend/Session/serving path.
Release notes: Under the hood — Experimental native HIP dense Qwen3.5 full-forward and observed reference comparisons for two fixed raw-token prompts.
1a3d1a6f2f34cc808f4e1ab9fba83d8d23e5e004.11d8a7d37a7648f3d5fc058f293947638313b2c4.84fbace83f79e05ffcc0c31d9ce5830c494f601e.660113afa5a1564dc44d27aebac6e3ccb1b4d40e.fb4b2737a808a3fb7c2117a498f43815dc9be53e, clean official source with normal incremental HIP library build proof, not the cached-library escape.The three mandatory review corrections are included: shared finite/F64 NMSE and fault gates, Context-owned typed host/device transfers, and specific local device unsafe invariants. A zero-oracle denominator-floor error was reproduced in the historical comparator; the current shared comparator rejects it and tiny-energy relative errors, retains the 1e-6 band, and passes the boundary/nonfinite regression. Canonical/model/regression checks were rerun at the new clean HEAD above. Device executable source lines are unchanged. The nonblocking per-launch synchronization optimization is intentionally excluded. Older results are not substituted for new-HEAD evidence. The diff remains confined to the excluded lab, two reference tools and one contribution document; production crates, root workspace/lock/toolchain/pins, workflows and release paths are unchanged.
Code shape
logits-qwen38dreference sets.cargo fmtandcargo clippyare clean on what I touched; the lint count did not go up. Root fmt and warnings-denied lab host/device clippy passed; no full-workspace clippy or global lint-count comparison is claimed.Duplication removed: core imports mixer-owned comparison/fault checks; selected/mixer/forward transfers use
Context::upload,downloadandoverwrite, with upload delegating to overwrite. Synchronous boundaries and error propagation remain unchanged. Native math and its independent reference intentionally remain separate implementations.Review slices: native F32/Q4_K/Q6_K/Q8_0 forward and tied head; GDN/GQA/F16 KV/arena/poison/reset probes; observed HIP reference with separately counted CPU embedding; independent greedy/forced full-row comparison and immutable provenance. Current-main integration preserves v2 tensor sums, corpus and pinned-build refusal semantics and standalone CPU/CUDA attribution.
Q4 zero/tiny-energy gate correction
Closes #479. This focused follow-on changes only the lab README, host main and mixer comparator relative to
f71e148395ab810aa40c577861ff7a3fd277873c.checked_nmse: exact zero error at zero oracle energy returns 0; nonzero error at zero energy is refused; nonzero energy is never floored. The1e-6threshold and finite-value checks remain.q4_nmseisolates the existing CPU oracle so a permanent behavior regression can exercise zero/tiny-energy corruption for cols1/32. That regression failed before the fix and passes after.sum + 1e-20_f32. Observed NMSE: cols13.999999746124184e-10, cols321.2799999187597388e-08; exit0. The fixed host refuses the all-column mutant with exit1/NMSE infinity. A second mutant injects only for cols32: the fixed host first accepts exact-zero cols1, then refuses cols32. The unmodified device passes both exact-zero cases with NMSE0/exit0.GPU before/after proof / baseline reproduction / incremental fix patch. The two public mutant patches are isolated throwaway verification controls, not source changes or canonical-admission artifacts. No timing claim.
What I ran
Fresh current-HEAD evidence is published separately from source:
Commands include the new Q4 regression failing-before/passing-after, actual GPU zero-weight positive and mutant negative controls,
cargo fmt --all -- --check, comment/recipes contracts, reference/comparer self-tests, normal reference build,verify.shwith the recorded K6144/rows64 fixture, small HIP comparison, CPU reset2 compatibility, separate real English/Korean comparisons, andcargo test --locked -p bloomery-refset --lib. Exact path-redacted argv, working directories, exits and logs are linked above. The source README documents reproduction with new evidence directories and matching current-HEAD binaries.Captured canonical summary:
All eight command groups and 18 GPU cases passed. Root static checks, reference/comparer self-tests, C++ build, small HIP comparison and CPU reset2 compatibility passed. The CPU-only refset library run reported 246 passed, 0 failed, 3 ignored; it is not an NVIDIA runtime gate. The shared comparison regression retains its boundary/nonfinite contract; the new Q4 oracle regression covers zero/tiny-energy corruption and exact zero agreement for cols1/32.
Fixed real-model results
File:
notschmee/Qwen3.5-0.8B-GGUF, revision1870603ac8ab59c7ddb9d94cccf3b297e379538f,Qwen3.5-0.8B-Q4_K_M.gguf, 590880672 bytes; SHA-256be5b3cb8c2f3ebd791349c9c775ea38950f23a2b9e792ca2f0411597dd172988.Both lanes use identical raw IDs, context64, ubatch1, F16 KV and step prefill, with no BOS insertion or chat template.
760,6511,314,9338,369178031,148928,154735,159951,16072Reference callbacks observed all 24 layers and the output head on HIP. The standard input-embedding gather is separately counted on CPU; unexpected CPU math is refused. Native token-dependent math remains on device. Reset passes clear actual context/state in process, not merely restart a program. Reference row0 aligns with native row
prompt.len()-1.Cross-engine logits are not bit-identical. Full-row errors are diagnostics, not a new tolerance or general language-quality claim. Original prompt IDs, greedy outputs, native row hashes and final reference raw hash match the previous package. Both lanes retain production FIT_RESERVE=268435456 bytes; stage memory preflight is not a hard cap or measured peak.
Evidence disclosure
Evidence commit
14a96bd8is not the source commit that was run. Reports/logs are explicitly named path-redacted derivatives; source/tree/model/binary/raw identities, numeric spellings, statuses and non-path arguments remain unchanged. The artifact ledger records original and public-copy hashes separately. Nested digests still describe retained original artifacts, not redacted copies. The ZIP is not a self-contained runnable bundle or an unmodified canonical-admission input. Unmodified originals remain retained locally.Model weights, extracted tensor bytes, raw logits, runtime binaries, Git bundles and credentials are excluded. Evidence is outside this source branch; any source commit/rebase needs fresh exact-head verification. Capture/preparation-time publication flags inside reports are historical, not live GitHub status.
No full contrib-check/CI success, NVIDIA/CUDA runtime gate, CUDA/HIP bit parity, serving/chat/tools, general English/Korean quality, other-GPU/IGPU support or performance result is claimed by these local runs. CI/review on this PR remain separate.
Hardware
RX 7900 GRE, gfx1100, compiled wave32; HIP runtime/driver API
70253210. Pinned nightly-2026-08-28: rustc 1.100.0-nightly (e457a7b0d, 2026-08-27), LLVM23.1.0, x86_64 Linux host. Host build uses-C target-cpu=native; device build uses gfx1100 and panic=abort.Host inventory: Intel Core i5-12600K; Linux MemTotal65573888KiB (67147661312 bytes, approximately62.54GiB [derived], not measured installed-DIMM capacity or model peak). No resident GPU service was stopped or reconfigured. No timing claim.