Skip to content

hip-native: add dense Qwen3.5 full-forward and observed HIP reference comparison - #476

Merged
juliankang4 merged 8 commits into
midagedev:mainfrom
Burntgogi:contribution/hip-full-forward-current-20261019
Oct 19, 2026
Merged

juliankang4 merged 8 commits into
midagedev:mainfrom
Burntgogi:contribution/hip-full-forward-current-20261019

Conversation

@Burntgogi

@Burntgogi Burntgogi commented Oct 19, 2026 •

Copy link
Copy Markdown
Contributor

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.

  • Verified source HEAD: 1a3d1a6f2f34cc808f4e1ab9fba83d8d23e5e004.
  • Main base: 11d8a7d37a7648f3d5fc058f293947638313b2c4.
  • Repository tree: 84fbace83f79e05ffcc0c31d9ce5830c494f601e.
  • Lab tree: 660113afa5a1564dc44d27aebac6e3ccb1b4d40e.
  • Reference llama.cpp: 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

  • No second copy. Reuse common GGUF/architecture readers, qdot oracles, the existing reference runner, and the production FIT_RESERVE owner. This is a lab-owned numerical harness, not a second serving engine.
  • Model code holds only architecture facts. Dense admission and GDN/GQA execution remain in the excluded lab; common production owners gain no model-specific branch or backend interface.
  • Dead code is gone. No compatibility shim; the comparer consumes current v2 schedule/corpus/bound interfaces.
  • No silent failure. Unsupported shapes/formats and malformed, nonfinite, incomplete or mismatching captures fail by name. Poison/reset and first-divergence contracts are retained.
  • Comments state what is true now. Comment-contract check passed.
  • No relaxed gate. Existing numerical/selected-Q4 contracts and the production reserve remain. Whole-model logit error is diagnostic, with no invented acceptance band; HIP captures do not impersonate registered logits-qwen38d reference sets.
  • cargo fmt and cargo clippy are 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, download and overwrite, 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.

  • Q4, dense FFN and core/mixer probes now share checked_nmse: exact zero error at zero oracle energy returns 0; nonzero error at zero energy is refused; nonzero energy is never floored. The 1e-6 threshold and finite-value checks remain.
  • Q4 oracle dot products and FFN references remain F64, without narrowing to F32. q4_nmse isolates 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.
  • On RX 7900 GRE, the parent host incorrectly accepted a zero-filled 576-byte Q4_K fixture (K256, rows4) with a device store mutant sum + 1e-20_f32. Observed NMSE: cols1 3.999999746124184e-10, cols32 1.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.
  • No device source, ABI, launch, transfer, synchronization or production path changes; the unmodified device ELF SHA-256 and all small/English/Korean full-row output hashes remain unchanged. All source-head canonical/model runs are fresh, not inherited from the parent.

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.sh with the recorded K6144/rows64 fixture, small HIP comparison, CPU reset2 compatibility, separate real English/Korean comparisons, and cargo 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:

fmt: pass
host-test: pass
host-clippy: pass
device-clippy: pass
device-build: pass
host-build: pass
gpu: pass
forward-gpu: pass

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, revision 1870603ac8ab59c7ddb9d94cccf3b297e379538f, Qwen3.5-0.8B-Q4_K_M.gguf, 590880672 bytes; SHA-256 be5b3cb8c2f3ebd791349c9c775ea38950f23a2b9e792ca2f0411597dd172988.

Both lanes use identical raw IDs, context64, ubatch1, F16 KV and step prefill, with no BOS insertion or chat template.

Fixed text / raw prompt IDs Independent greedy Reference-prefix native forced argmax Complete finite rows Per-engine reset2 Max row relative L2, diagnostic only
The capital of France is / 760,6511,314,9338,369 8/8 match 8/8 match 8 × 248320 values Bit-identical 0.027311885469503642
대한민국의 수도는 / 178031,148928,154735,159951,16072 8/8 match 8/8 match 8 × 248320 values Bit-identical 0.0226808442104578

Reference 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 14a96bd8 is 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.

@github-actions github-actions Bot added documentation Improvements or additions to documentation 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: 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)

@Burntgogi

Copy link
Copy Markdown
Contributor Author

Addressed all three MUST_FIX findings in f71e148395ab810aa40c577861ff7a3fd277873c:

  1. Core now imports mixer-owned compare / fault_is; one F64 finite/NMSE gate uses exact energy normalization, rejects nonzero error against a zero oracle, and preserves 1e-6. The historical core comparator reproduced the false acceptance; the permanent boundary/nonfinite/zero/tiny-energy regression passes.
  2. Context::overwrite owns typed uploads; upload delegates, and selected/mixer/forward callers use Context transfers. Duplicate helpers removed; synchronization/error behavior retained.
  3. Added 26 adjacent local SAFETY explanations for mixer/math unsafe blocks. Non-comment device source lines and the built device ELF SHA-256 are unchanged.

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.

github-actions[bot]
github-actions Bot previously approved these changes 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.

Since the last review:

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

@Burntgogi

Copy link
Copy Markdown
Contributor Author

Implemented #479 in 1a3d1a6f2f34cc808f4e1ab9fba83d8d23e5e004 on this still-unmerged lab PR, without a duplicate/dependent feature PR.

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.

@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:

  • 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)

@Burntgogi

Copy link
Copy Markdown
Contributor Author

Exact-head evidence clarification for the non-blocking review note:

The current PR body identifies verified source 1a3d1a6f2f34cc808f4e1ab9fba83d8d23e5e004 (repo tree 84fbace83f79e05ffcc0c31d9ce5830c494f601e, lab tree 660113afa5a1564dc44d27aebac6e3ccb1b4d40e), not the parent f71e1483. The new evidence links were updated after pushing this 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 14a96bd88cb14c8ba80bd161feaa5bc5bd648e7c is not the source commit that was run. No source change has occurred after verification.

@juliankang4
juliankang4 merged commit bcbf56e into midagedev:main Oct 19, 2026
7 checks passed
@juliankang4

Copy link
Copy Markdown
Collaborator

@Burntgogi Thanks for the contribution. The review is done, so I'm merging this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

documentation Improvements or additions to documentation tools Tools, recipes, CI and the toolchain: tools/, justfile, .github/, Cargo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

hip-native: Q4 NMSE gate accepts incorrect output for zero weights native AMD: Rust/HIP Q4_K and FFN feasibility on RX 7900 GRE (operators only)

2 participants