Skip to content

Add experimental dense BF16 Qwen3.5 CUDA scoring - #1137

Closed
akol1 wants to merge 1 commit into
ashhart:mainfrom
akol1:codex/qwen35-bf16-scoring
Closed

akol1 wants to merge 1 commit into
ashhart:mainfrom
akol1:codex/qwen35-bf16-scoring

Conversation

@akol1

@akol1 akol1 commented Oct 21, 2026 •

Copy link
Copy Markdown
Contributor

What this changes

Proposes experimental dense BF16 Qwen3.5 CUDA loading and full-vocabulary-normalized selected-token scoring, with a bounded JSONL development runner. This ports the reusable native engine work to current main; issue #1136 requests agreement on the arithmetic and acceptance gates.

The initial target is the 27B geometry. BF16 activations and FP32 projection accumulation are retained; the scoring head writes FP32 logits. HF offset RMS weights add one in FP32. Score forwards gather only each segment's final normalized row, retain independent cache state, and use separate CUDA graph keys. The reduction returns full-vocabulary log-sum-exp, lower-ID greedy ties and up to 16 selected logits per segment.

The development runner batches up to four requests on one device, resets each request to fresh state and reports zero cached tokens. It is not a new HTTP scheduler or tensor-parallel implementation. Application-specific transports, workloads, infrastructure, credentials, reports and checkpoint identifiers are excluded. Examples use synthetic IDs. The separate prefix store and manual state-copy path have been removed to honor native shared-cache ownership. The native adapter explicitly refuses experimental BF16 before weight loading, with a host regression and a clear explanation.

Draft: not ready to land. An earlier prototype has an unresolved external-reference probability tolerance failure. Greedy agreement does not prove probability equivalence. No public checkpoint revision, speedup or model-fidelity result is claimed. The score reduction and changed norm/head-norm operators still need contract registration and all acceptance gates in issue #1136.

Receipt

  • Port base: d1018b318fb51981c4a18f12e40269a4d3ee9713 (main). Original candidate: db919c6dcf1f3584f2ab788a25ec02bfea5f82ca; contributor-audit head: b8cb073bacde162391328104054b7f49c81a5f75. The original 14 native files matched that compiled tree; all 15 changed native files at the audit revision also match its isolated test tree by SHA-256.
  • Environment: Linux x86_64; exact Zig 0.17.0; changed kernel compiler nvcc 13.3.73. No checkpoint was loaded for this port's checks.
  • zig build test test-golden test-cuda-host test-kernel-contract -j4 --summary all: 227/227 steps succeeded, 3,024 tests passed, 14 skipped, zero failed. Server corpora: 306/319 equal with recorded known differences and 26/26 equal; zero unexpected differences.
  • Final incremental suite including the targeted host target: 231/231 steps succeeded, 219 executed tests passed, three skipped, remaining unchanged checks cached; zero failures.
  • Baseline-only dense BF16 admission probe: 0/1 passed (UnsupportedQwenQuantization); the candidate accepts the same fixture.
  • zig build test-qwen35-bf16-host: 3/3 tests passed, zero failed/skipped. Admission, graph-key separation and label bounds are covered.
  • Native scorer compiled host-only and with real embedded images. The changed Qwen image was rebuilt for sm_120 using -O3 -std=c++17, without fast math; other catalog images were retained assets, not rebuilt. No binary or generated image is uploaded.
  • Lean baseline/candidate: 444/444 inherited findings, zero new (lean_new.py passed). The absolute checker remains nonzero.
  • Python finite-input FP64 reference utility: syntax passed, runtime skipped without PyTorch. This utility is not the five-gate kernel contract.
  • Contributor-audit revision: zig build test test-kernel-contract test-golden fuzz-cortheon test-qwen35-bf16-host qwen35-score -Dfatbins=CATALOG -Doptimize=ReleaseFast -j4 --summary all exited 0: 237/237 steps succeeded; 304 executed tests passed, three skipped, unchanged checks cached. Targeted host tests: 4/4 passed, including native BF16 refusal before weight loading.
  • Plain zig build -j4 --summary all at the original and contributor-audit code revisions: exit 0, 24/24 steps succeeded on each. Separate fuzz-cortheon: exit 0, 11/11 tests passed. The final baseline above also includes fuzz.
  • Final zig build native with real embedded catalog: exit 0, 7/7 steps succeeded; actual tensorfold-native 1.1.1, --help and capabilities --json work (exit 0), Qwen CUDA advertises only mlx-q4g64. This does not qualify a checkpoint or execute a model.
  • Final formatting/diff checks passed; lean still has 444 inherited findings and zero new.
  • Reproduction, wire schema, arithmetic and scope: docs/recipes/qwen3.5-bf16-scoring.md.

Current-head hosted CI is pending; the prior-head Windows failure is disclosed below.

Not run: checkpoint/device inference on this port; per-projection FP64 references and worst-column errors; teacher-forced histories; draft/plain, fresh/resumed, batch/solo, prompt/decode seams and lifecycle gates; new-kernel contract registration/SUMMARY; native server decode/cold-prefill performance; Metal, other SMs and multi-device execution. These remain explicit acceptance work, not implied passes. The host kernel-limit suite checks the existing registry and does not qualify the new unregistered kernel.

Contributor-skill audit

Audited against docs/recipes/SKILL.md at the port base. The recipe contains a requirement-by-requirement table with passed, failed, blocked and not-run states. This is a draft experiment under the skill's explicit draft allowance, not a claim of full qualification.

  • Maintainer-agreed arithmetic/workload/performance gate: blocked. Issue Proposal: dense BF16 Qwen3.5 CUDA scoring #1136 has a proposal but no recorded agreement. The original application target is not substituted for a TensorFold acceptance gate.
  • Kernel contract: not-run. Backend runner integration, declared non-finite/alias/depth semantics, real multi-SM compile records, all five gates, planted controls and complete CUDA SUMMARY remain required. The standalone Python utility is supplementary only.
  • Native/model qualification: not-run. Public checkpoint/tokenizer revisions, FP64 projection-class references, resolution of probability mismatch, native exactness/lifecycle/vision refusals, served latency/decode/concurrency, cold 2k/8k/32k/64k and physical/pinned memory receipts remain required.
  • Windows CI at db919c6: failed (job). 165/211 build steps succeeded; 1,423 tests passed and 15 skipped; 22 build steps failed. All 29 repository files with primary compiler errors match base bytes. A baseline Windows reproduction is still not-run; these observations do not establish that the base passes or fails.
  • Linux host checks and compilation do not prove GPU execution. No previous warm-prefix result is a receipt for the revised fresh-state runner.

Smallest next step: agree the acceptance contract, then finish kernel-runner registration and native lane ownership before an isolated GPU/model qualification run. No thresholds or CI requirements are waived.

Checklist

  • Every token still goes through the lane rounds. No serial path, and nothing that needs drafts off. (Development scoring tool; native server integration/gate pending.)
  • Drafted output equals "draft": false, resumed equals fresh, concurrent equals solo. (Not qualified.)
  • No precision traded for speed. (BF16/FP32 arithmetic documented; exactness gates pending.)
  • A new or changed GPU kernel is registered with the kernel contract; each backend SUMMARY is in the receipt. (Registration and device gates pending.)
  • Prompt processing is no slower than the last release. (No public performance receipt.)
  • Description distinguishes Linux host/compile checks from unrun CUDA device and Metal checks.
  • New tests fail before, pass after, and skip cleanly without dependencies. (Targeted checks pass; device/reference work remains.)
  • New comments/docstrings are single lines; history and measurements live in the recipe/receipt.
  • Publication content and outgoing history inspected for personal data, private hosts/paths, credentials and application-specific material; public noreply Git identity, no tool attribution trailers.

@ashhart ashhart left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

Thanks @akol1. Dense BF16 scoring is wanted (#1136), but this branch is about 800 commits behind and main has since reworked the same area, so it no longer applies:

  • Main already loads HF model.language_model.* names, BF16 embeddings, [conv,1,taps] convolution weights and the norm "+1" at load (cuda_weights.zig), and has a deterministic BF16 row kernel (qwen35_bf16_rows.zig denseRows) with a bf16 kind in cuda_geometry.zig.

Problems we'd need fixed in a rebuild:

  1. qwen35.cu adds (P[5] ? 1 : 0) inside the norm kernels on every Qwen checkpoint's path. For non-BF16 models that adds +0.0f, which turns a -0.0 weight into +0 (output bits can change) and adds a load to the hot loop. Main does the "+1" at load, rounded the way MLX does.
  2. Scores depend on the batch: projections use cuBLASLt plans keyed by row count, and each prompt gets 128 / requests.len rows, so a prompt scored alone and beside three others runs different GEMM shapes. Each prompt's logprobs must equal its solo run bit for bit; fixed chunking that doesn't depend on the batch solves it.
  3. tf_q35_score_stats isn't registered with the kernel contract.
  4. cuda_engine.zig st[ids_at + total*4 .. max_rows*4] is only right while ids_at == 0; st[ids_at..][total*4 .. max_rows*4] is safe.

Suggested path: treat a plain BF16 checkpoint as all-bf16 kinds through main's loader and denseRows, add the scoring entry on top, and register the stats kernel. We'd then check identical tokens on existing MLX/ModelOpt Qwen checkpoints, solo vs batched logprob bits, and an FP64 reference on a Qwen3.5-27B BF16 checkpoint. It's good that native serving refuses the format before loading weights.

A prompt's selected-token logprobs are a full-vocabulary log-sum-exp over
its final row's logits, so they follow from the row alone. They used to
depend on the batch: each prompt took `128 / requests.len` rows, and the
cuBLASLt plan is keyed by row count, so a prompt's bits changed when other
prompts shared the launch.

Every prompt now takes chunks of `chunk_rows` and is scored before the next
one runs, so a prompt's logprobs are the bits of its solo run whatever its
batch carries. The scorer reads the kept BF16 rows straight, so the sum sees
the bits the forward produced.

`tf_q35_score_stats` lands on main's shape: a standalone `.cu` in the fatbin
set with `--fmad=false --ftz=false` so repeats are bit-identical, a lane
module under `zig/src/cuda`, registration in the kernel contract's CUDA
records, and a dedicated host root that checks the stats layout the kernel
writes. Its compiled usage waits on a device of each SM we serve, so the
limits gate fails it closed until a receipt lands.

The engine's padding now slices from `ids_at` before the row offsets, so
the expression no longer assumes that base is zero.
@ashhart

ashhart commented Oct 26, 2026

Copy link
Copy Markdown
Owner

Review of the new head 2412966 against main 3f408b6. Thanks for the changes: the norm "+1" edit is gone, prompts now score one at a time in fixed 128-row chunks so scores no longer depend on the batch, and tf_q35_score_stats is registered. Still to fix:

  • BF16 loading is gone. The head no longer loads plain BF16, and main's config.zig:132 refuses a checkpoint without a quantization table, so the title and body describe the old head. Loading plain BF16 through main's loader and denseRows is still the suggested path.
  • The new kernel is never called. Kernels.stats has no caller; qwen35_score.zig computes log-sum-exp, argmax and logprobs on the host.
  • Overlapping output layout. Log-sum-exp and argmax go to stats[2r] and label logits to stats[8+16r], so from row 4 on the pair overlaps label logits (row 4's pair lands on row 0's first two), and stats() accepts up to 128 rows.
  • The host tests can't fail: they compare constants with themselves (for example r*17+17 == (r+1)*17).
  • Lean: zig/build/cuda.zig reaches 602 lines (one new finding).

@ashhart

ashhart commented Oct 27, 2026

Copy link
Copy Markdown
Owner

Thanks @akol1 for the BF16 scoring work. We're closing this draft for now, as our 26 Oct review hasn't had a reply. Dense BF16 scoring is still wanted (#1136), so please reopen it, or send a fresh PR, that loads plain BF16 through main's loader and calls the registered stats kernel.

@ashhart ashhart closed this Oct 27, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants