Skip to content

spacemit: repack BF16 and F32 weights for parallel RVV decode - #95

Open
co-seven wants to merge 3 commits into
spacemit-com:mtmd-backendfrom
co-seven:pr/nomtp-bf16-f32-20261203
Open

co-seven wants to merge 3 commits into
spacemit-com:mtmd-backendfrom
co-seven:pr/nomtp-bf16-f32-20261203

Conversation

@co-seven

@co-seven co-seven commented Dec 3, 2026 •

Copy link
Copy Markdown
Collaborator

Problem and behavior

Performance optimization following #85. Eligible BF16/F32 projection weights currently use their original row layout for RVV multiplication. Store an additional layout through the backend's existing weight-repack interface and split output columns across workers for small batches. Original bytes remain available for readback and the existing fallback.

For F32, the compact BF16 representation is selected only when every finite weight round-trips exactly through BF16; this is not an approximate conversion of arbitrary F32 weights.

Change and design

  • ime.cpp: choose repack traits and allocation sizes from tensor/layout constraints; route F32 N=1 matrices as well.
  • scalar_kernels.cpp/.h: construct both representations, check lossless F32 representability, and select RVV decode or the existing fallback.
  • rvv_kernels.cpp/.h: multiply the packed weights and partition output columns across workers. Counters retain full tensor-dimension width.
  • ggml-spacemit.cpp: activate BF16/F32 repack during weight upload, after the buffer has been marked as WEIGHTS.

The added paths use no tensor-name or model-name dispatch and no optimization environment switch. With K=ne[0] and N=ne[1], their dimensional requirements are:

Weight type Repack shape requirements
BF16 Positive K/N, ne[2]=ne[3]=1, N divisible by 128; no K divisibility requirement
F32 Positive K/N, ne[2]=ne[3]=1; no K/N divisibility requirement, including odd N and N=1

BF16 stores complete 128-column blocks; F32 retains element order in its compact copy and handles K and N tails. Both require a contiguous, non-view tensor with op NONE. Existing IME2 platform selection and the RVV VLEN=1024 execution guard remain. The separate F32-to-Q8_0 routing inherited from the target baseline is outside this change.

Allocation and unallocated model-placement probes reserve the additional layout. Actual BF16/F32 packing starts when an allocated buffer is marked WEIGHTS and fully uploaded. Allocated ANY recurrent-state buffers and COMPUTE buffers do not acquire these new traits, so ordinary partial state uploads remain supported. Because usage is assigned after allocation, eligible unclassified buffers can conservatively reserve extra space without using it.

F32 enables its compact representation only if every element is finite and its low 16 bits are zero; otherwise multiplication reads the original F32 data. BF16 retains the original values exactly. M=1 decode uses the new representation; other batches keep the existing original-layout paths. BF16 reserves twice the original bytes plus up to 127 alignment bytes; F32 reserves 1.5 times the original bytes plus 128 bytes for the tag/alignment.

Scope is limited to ggml/src/ggml-spacemit/. Impact classification: execution-path change. No changes to the retired CPU backend, model code, public API or test sources. Local validation fixtures are excluded. This independently based module commit preserves the target branch's common MTP graph/rollback paths; experimental noMTP-wide reversions are not submitted. No new external dependency is added.

Validation

Base: mtmd-backend at 3f5ce5fd84f4dc6e7e621642cfef0143d49e7c24. Candidate: 187c8d2bb2c9546b33104631f332979a06faf166; source tree edecd512c030ccd3413dcef8f104bd21e45c74ce.

The exact submitted production source passed a RISC-V Release cross-build of ggml-spacemit using the SpacemiT v1.1.2 toolchain (GCC 14.3), cmake/riscv64-spacemit-linux-gnu-gcc.cmake, GGML_SPACEMIT=ON, GGML_RV_ZBA=ON, GGML_OPENMP=OFF, Spert 0.6.3 and SpacemiT ORT 2.0.6. Build target: cmake --build <build> --target ggml-spacemit --parallel 24. Backend DSO SHA-256: cf18c41e5645dc6e29916dae7bef9ebe7fc0b36c9c37aca55db0a7b6f89f9f87. Source hashes were checked before/after the build and against the committed files.

The generalized source passed 168 numerical cases under QEMU RVV VLEN=1024, using exact-extracted production repack and RVV functions with real ggml tensor descriptors and a worker-index context shim. Cases include K=1/127/129/257/1025 and the original supported shapes; BF16 N=128/256/384, F32 odd N and N=1; 1/3/8 workers and 2x2 activation batches. Two deterministic input sets cover exact dyadic and full F32 mantissa inputs. An independent scalar reference uses rounded F32 products and ordered F64 accumulation for BF16, and scalar higher-precision accumulation for F32. Every output satisfied abs(error) <= 1e-5 * (1 + abs(reference)); maximum absolute errors were 0 and 0.00390625 for the two input sets. Original bytes, packed element mappings, alignment and allocation canaries passed. Six additional F32 checks cover low-bit/Inf/NaN rejection and exact -> inexact -> exact full re-upload.

A separate 43-case host fixture uses exact-extracted eligibility branches, allocation sizing and buffer callbacks with real ggml allocation/tensor/buffer APIs. It covers accepted and rejected shapes/layouts, empty dimensions, hardware disabled, unallocated ANY model-placement probes, allocated ANY and COMPUTE exclusions, and allocation -> WEIGHTS marking -> full upload -> repack -> readback. F32 N=1 routing and partial writes to ordinary state buffers pass. Trait objects and the repack bridge are stubbed in this host fixture; it is not a complete backend integration test.

Local reproducer sources remain outside the submitted diff. Commands and source hashes are retained in pr95-general-repack-20261204/{numerical,dispatch}. The numerical runner cross-compiles the extracted code with the SpacemiT toolchain and invokes qemu-riscv64 with RVV VLEN=1024. These checks do not execute a full SPACEMIT0 model or the M>1 generic fallback. Earlier module QEMU coverage of three batch sizes is historical evidence only.

The historical Gemma model comparison produced identical 128 output token IDs across all 12 formal requests. This measures the combined BF16/F32 module, not an isolated benefit for each weight type.

Check Status Evidence / scope
Exact-source RISC-V backend build PASS Configuration and DSO identity above
Diff / scope / formatting checks PASS Backend-only; no test changes or new environment controls; git diff --check, UTF-8/LF and added-line whitespace
Generalized shape and representation checks PASS (QEMU) 168 numerical cases and 6 representation checks, scope above
Eligibility and upload lifecycle PASS (host) 43 cases; source hashes match the built candidate
Local branch synchronization PASS Identical update in publication, module and aggregate trees
Model outputs PASS (historical) All 128 IDs match in 12 Gemma requests
Model performance PASS (historical measurement) Decode +3.31%; prefill -1.26%; combined module
Final-head board / additional platform coverage NOT RUN Historical target results are carried forward; no new final-head K3 or K1 run

Performance

Case Baseline decode tok/s Candidate decode tok/s Samples per arm Change
Gemma 4 E2B Q4_0, 10K 12.312 ± 0.022 12.719 ± 0.063 6 +3.31%

Prefill: 251.38 → 248.21 tok/s (-1.26%). Historical comparison: 71a69aeb → b796a32be, run label gemma-bf16-f32.

Historical K3 A/B protocol: X100 2.2 GHz / A100 1.8 GHz, eight backend workers on cores 8–15; fixed 10,240 prompt token IDs and 128 generated IDs; MTP off, FA on, F16 KV. Server: -np 1 -c 12288 -b 2048 -ub 512 -t 8 --device SPACEMIT0 -ngl 99 -fa on -lm none -ctk f16 -ctv f16 --no-cache-prompt --cache-ram 0 --spec-type none. Nonstreaming /completion: n_predict=128, ignore_eos=true, temperature=0, samplers=["temperature"], seed=123, return_tokens=true, cache_prompt=false.

ABBA order, four fresh server processes, one 16-token warmup and three formal requests per process: six samples across two startups per arm. Only the backend DSO changed. Runtime identity, frequencies and interference monitoring passed the archived audit. Decode throughput is 127 / decode_seconds; values are mean ± sample standard deviation. Delta = 100 * (candidate / baseline - 1). Prefill uses the server's prompt timing.

Risks and limits

The new dimensional coverage has emulator/host validation, but no fresh target-board model or performance measurements. Historical performance below does not establish a gain or absence of regressions for newly eligible shapes. Additional resident weight memory and conservative allocation before usage classification are tradeoffs. The full M>1 fallback and broader target-platform coverage were not rerun for this update.

This repack contract assumes immutable model weights following complete uploads. As discussed in review, writes through memset/views do not synchronize the packed copy; that existing review issue is not changed by this shape-generalization update. Allocated ordinary state buffers are specifically kept outside the new repack paths.

The historical module comparisons used the common noMTP experimental baseline on top of 3f5ce5fd; this PR instead preserves upstream common MTP behavior. Historical results are not claimed as new measurements of the final independent head. Raw build/test/benchmark archives are retained privately and are not publicly attached; the cases, results, artifact identities and limits above are the reviewable record here. Exact-input model replay is not provided by these summaries. Required final-head target evidence remains pending; this submission requests review, not a waiver or a claim of merge readiness. No maintainer exception has been granted. CI status is separate from the local results above.

AI assistance and contributor responsibility

Codex assisted with source preparation, static review, local build/check execution, historical evidence analysis and this PR description. The contributor discussed the module design and explicitly requested publication. No unrecorded personal review, maintainer approval or target execution is asserted. The contributor remains responsible for reviewing the submitted code and claims and addressing review feedback.

Copy link
Copy Markdown
Collaborator

Please fix the packed-weight invalidation before merging. The new BF16/F32 paths keep both the original weights and a packed copy, but buffer_memset_tensor only changes the original bytes. After a full upload and a partial zero-fill, readback can see the new weights while the M=1 path still uses the old packed copy. The F32 validity tag is left set. Partial set_tensor on weights that previously used the plain layout also now asserts.

Please preserve the existing write semantics, either by updating the packed copy or invalidating it and falling back to the original layout. Please cover writes through views as well. A focused regression is full upload → zero one weight row → compare both readback and M=1 output against a CPU reference for BF16 and F32. For performance, please report the BF16 and F32 changes separately, including the extra resident bytes.

Select BF16 by its 128-column layout requirement and accept arbitrary F32 matrix dimensions. Activate float repacking on weight uploads so recurrent state buffers retain plain storage semantics.

Assisted-by: Codex
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