Skip to content

spacemit: retain compact Q6_K weights with aligned IME2 tiles - #101

Merged
alex-spacemit merged 1 commit into
spacemit-com:mtmd-backendfrom
co-seven:split/no-mtp/q6k
Dec 4, 2026
Merged

alex-spacemit merged 1 commit into
spacemit-com:mtmd-backendfrom
co-seven:split/no-mtp/q6k

Conversation

@co-seven

@co-seven co-seven commented Dec 4, 2026

Copy link
Copy Markdown
Collaborator

Overview

The IME2 Q6_K output-head path currently expands weights to Q8 at load time. For the contiguous K2048/N248320 head used by Qwen3.6-35B-A3B, this increases the weight buffer and the bytes copied for each decode step. This change retains the original six-bit codes and scales in a compact, 128-byte-aligned layout and consumes it with a matching IME2 kernel.

The final head allocation decreases from 540,344,320 to 421,150,720 bytes (-22.06%). Earlier same-board experiments measured decode improvements of 8.526776 -> 8.934479 token/s for compact repacking on K3-235, followed by 9.683554 -> 9.817370 token/s for alignment on K3-175. These are two separate comparisons, not a cross-board speedup. The measurements belong to the experimental packages described below; this standalone commit has not been rerun end-to-end on a board.

Related context: #98 covers existing dense Q8_0/Q6_K tail correctness. The fixed-input operator/model comparisons below document the performance problem addressed here.

Scope and design

One commit, 4d60c576e230afc7a1f5b79f51c05a073a4840c2, directly above mtmd-backend at 75b1485aaad93fbb44d1b5f517a79a7bf0457dd3: seven files, 375 added lines.

Changed files Responsibility and reason
repack.cpp, repack.h Define the private N32/K256 layout and lossless upload/readback conversion.
ime2_kernels.cpp, ime_kernels.h Decode six-bit weights in registers and execute the corresponding IME2 dot products.
ime.cpp Select the compact trait, calculate physical allocation/workspace sizes, quantize activations, align worker-local TCM and schedule the kernel.
ime.h, ggml-spacemit.cpp Preserve compact traits for complete aliases and reject unsupported compact views during buffer initialization.
  • Dispatch requires IME2, a static contiguous non-view Q6_K tensor, and dimensions [2048, 248320, 1, 1]. Other shapes retain their existing path. This is an execution-path optimization affecting weight upload/readback, allocation, matmul dispatch and the model output head.
  • Each N32/K256 tile contains 64 bytes of FP16 scales, 512 bytes of signed K16 scales, 64 bytes of padding and 6,144 bytes of six-bit payload: 6,784 bytes total. Payload offset 640, group stride 384 and tile stride 6,784 all preserve 128-byte alignment when the base is aligned. The worker-local TCM base is aligned before capacity checks.
  • Four six-bit weights occupy three bytes. The kernel expands them to signed int8 only in registers, applies the original signed subgroup scales and FP16 block scales, and accumulates FP32 outputs. Repacking preserves the original codes and scale bit patterns; there is no new GGUF type or persisted format.
  • Retain the existing R1 activation quantizer, paired-worker scheduling and compact-weight TCM staging. Alignment costs 0.9524% more storage than the initial unaligned compact layout. This change does not eliminate all staging copies.
  • Full zero-offset aliases with identical type, shape and strides retain the compact trait. Partial, offset, transposed or otherwise incompatible compact views fail explicitly; arbitrary-view fallback is not implemented.
  • All changes are within ggml/src/ggml-spacemit/. No changes to the retired CPU backend, public APIs, build dependencies, other optimization modules, test sources or experiment controls are included. Temporary validation fixtures remain outside the submitted diff.

Validation

Base: 75b1485aaad93fbb44d1b5f517a79a7bf0457dd3. Candidate: 4d60c576e230afc7a1f5b79f51c05a073a4840c2.

Check Applicability and reason Status Result and evidence
IME2 Release backend build Changed backend/kernel PASS Exact candidate sources; ggml-spacemit target built successfully.
IME1-only Release backend build Compile-time boundary and shared view entry point PASS Compact implementation excluded; existing non-IME2 behavior builds.
Repack/readback and allocation New physical layout PASS 146 host ASan/UBSan cases; complete 417,177,600-byte logical head roundtrips through 421,150,720 physical bytes.
View/allocation lifecycle New trait propagation and rejection PASS Six host fixture groups using real GGML allocation/view initialization; unsupported views terminate with the expected diagnostic. Unrelated traits are stubbed and IME2 is not executed.
IME2 leaf identity Carry-forward evidence for arithmetic PASS All 95 instructions / 370 bytes are byte-identical to the aligned kernel tested on K3-175; no calls or stack accesses. This does not establish whole-backend equivalence.
Diff/style checks Submission hygiene PASS git diff --check, added-line EditorConfig checks and the code-style workflow's model-naming script (177 mappings).
Full EditorConfig workflow Repository style tool NOT RUN editorconfig-checker is unavailable locally; the added-line check is not claimed as full-workflow coverage.
Historical board correctness Tested experimental implementations PASS Aligned backend: baseline and candidate each pass 11 CPU-reference cases, readback checks and M1/2/3/4/5/8 dispatch checks. All four reported model runs produce the same 128 output token IDs.
Exact-candidate K3 operator/model execution and performance Required for this execution-path change NOT RUN The standalone extraction and view integration have build/host evidence, but no new board run. Historical package results below are not relabeled as candidate acceptance.
K1 runtime IME2 fast path is excluded; shared entry point has compile coverage NOT RUN No K1 runtime claim; IME1-only compilation passed.

The layout fixture extracts the exact committed repack functions and layout constants and uses real block_q6_K/GGML types. An independent raw-Q6 decoder checks the represented codes/scales. Cases cover row counts 1/7/8/24/31/32, K256 block counts 1/2/8, random/extreme/zero/subnormal/NaN metadata, all 64 six-bit codes, all 256 signed-scale bit patterns and all 65,536 FP16 scale bit patterns. Guard bytes, unchanged input, zero padding, aligned payloads and rejected short uploads are checked. These helper-boundary cases do not expand production dispatch beyond the stated shape. The extracted repack code and fixture are sanitizer-instrumented; the linked host ggml-base is not.

The view fixture covers root allocation before/after buffer assignment, full and nested aliases, noncompact parents, neighboring shapes, and rejection of shape/offset/stride/type/transpose changes. It checks the initialization-order defect found during extraction, where compact storage could otherwise acquire the legacy Q8 trait. A full on-board view matmul regression comparison remains unverified.

Build environment: SpacemiT GNU toolchain package 1.1.2, spine-runtime 0.6.3, ORT package 2.0.6, RISC-V Release, GGML_SPACEMIT=ON, GGML_RV_ZBA=ON, OpenMP off. The executed configuration can be reproduced with the SDK paths set locally:

cmake -S . -B build-q6k \
  -DCMAKE_TOOLCHAIN_FILE=cmake/riscv64-spacemit-linux-gnu-gcc.cmake \
  -DCMAKE_BUILD_TYPE=Release -DGGML_SPACEMIT=ON -DGGML_RV_ZBA=ON \
  -DGGML_OPENMP=OFF -DLLAMA_BUILD_TESTS=OFF -DLLAMA_BUILD_TOOLS=OFF \
  -DLLAMA_BUILD_SERVER=OFF -DLLAMA_CURL=OFF -DLLAMA_SERVER_SMT_MTMD=OFF \
  -DSPACEMIT_ORT_DIR="$SPACEMIT_ORT_DIR" -DSPERT_DIR="$SPERT_DIR"
cmake --build build-q6k --target ggml-spacemit -j12

For the IME1-only build, the same configuration additionally disables SPACEMIT_RISCV_COMPILER_SUPPORT_VMADOT_S4, SPACEMIT_RISCV_COMPILER_SUPPORT_VPACK and SPACEMIT_RISCV_COMPILER_SUPPORT_VNPACK.

Performance

Historical experimental-package measurements, collected before standalone extraction. Model: Qwen3.6-35B-A3B-Q4_0.gguf, 20,836,243,072 bytes, with the Q6_K output head. All model runs use the same 10,240 prompt token IDs, 128 generated tokens, no prompt cache, no MTP/speculation, temperature 0, seed 123 and ignore_eos=true. Native timing has tracing disabled and excludes model loading. CPU threads/batch threads are 8/8; the backend uses eight A100 workers pinned to CPUs 8-15.

Common server options: --device SPACEMIT0 -ngl 99 -np 1 -c 32768 -b 2048 -ub 2048 -t 8 -tb 8 -fa on -lm none -ctk f16 -ctv f16 --no-cache-prompt --cache-ram 0 --reasoning off --warmup --spec-type none. Each formal model sample is from a separate server process with the same request. K3-235 ran compact then baseline; K3-175 ran compact then aligned. Server-reported prompt/decode token rates are used, not wall-clock loading or trace-derived rates. The response contains 128 generated IDs; decode throughput is 127000 / predicted_ms because the first token comes from prefill. Prefill throughput is 10240000 / prompt_ms.

Board X100 / A100 / CCI frequency Comparison
K3-235 2.0 / 1.8 / 1.0 GHz Existing Q8-expanded weights vs initial compact Q6
K3-175 2.2 / 1.8 / 1.2288 GHz Initial compact Q6 vs 128-byte-aligned compact Q6

Full-model results

One native sample per version; these are individual observations, not repeated-run means. Throughput change is (after / before - 1) * 100; higher is better.

Same-board comparison Metric Before (token/s) After (token/s) Change Samples before / after
K3-235: Q8-expanded -> compact Q6 Decode, 10K context 8.526776 8.934479 +4.78% 1 / 1
K3-235: Q8-expanded -> compact Q6 Prefill, 10,240 tokens 114.605419 114.927077 +0.28% 1 / 1
K3-175: compact Q6 -> aligned compact Q6 Decode, 10K context 9.683554 9.817370 +1.38% 1 / 1
K3-175: compact Q6 -> aligned compact Q6 Prefill, 10,240 tokens 116.772005 117.181505 +0.35% 1 / 1

All 128 generated token IDs match across these four runs. Formal timing windows have no detected competing workload: 20 clean observations per K3-235 run and 19 per K3-175 run. All servers exit 0 and release all eight TCM allocations. The measured aligned K3-175 result remains below 10 token/s; the single-sample model comparisons do not establish a statistically stable gain.

Output-head operator results

M1/K2048/N248320 Q6_K head. Each launch uses one untimed warmup and an adaptive performance loop; every recorded sample reports 99 timed runs. Reported values are arithmetic means of the listed per-launch native samples. Latency change is (after / before - 1) * 100; lower is better. These percentages are operator improvements, not model-throughput improvements.

Same-board comparison Before (ms) After (ms) Latency change Order / samples per version
K3-235: Q8-expanded -> compact Q6 20.648983 15.860370 -23.19% ABBAAB / 3
K3-175: compact Q6 -> aligned compact Q6 13.914695 13.397870 -3.71% ABBA / 2

Raw per-run operator timings, in microseconds:

235 baseline: 20629.21, 20678.53, 20639.21
235 compact:  15823.26, 15844.88, 15912.97
175 compact:  13907.43, 13921.96
175 aligned:  13157.77, 13637.97

The two K3-175 aligned samples differ by 480.20 us, so the -3.71% result is an observed mean improvement with material variation. A separate same-board direct-weight-read experiment regressed head latency by 15.60%; retaining compact-weight TCM staging is intentional.

The operator command used a local adaptation of test-backend-ops that adds this full-head case; it is not an unmodified upstream test executable:

TEST_Q36_Q6_HEAD_PLANAR_CASES=1 \
GGML_SPACEMIT_BACKEND=1 GGML_SPACEMIT_WORKERS=8 \
SPACEMIT_PERFER_CORE_ID=8,9,10,11,12,13,14,15 \
LD_LIBRARY_PATH="$arm/bin" \
LD_PRELOAD="$arm/bin/libggml-spacemit.so.1.0.0" \
"$fixture/bin/test-backend-ops" perf -b SPACEMIT0 -o MUL_MAT \
  -p 'type_a=q6_K.*m=248320,n=1,k=2048.*q36_q6_planar=1' -j 1

Weight allocation

Representation Head bytes Change vs Q8-expanded
Existing Q8-expanded 540,344,320 Baseline
Initial compact Q6 417,177,600 -22.79%
Final aligned compact Q6 421,150,720 -22.06%

Evidence identities and applicability

Artifact Backend SHA256
Historical Q8-expanded baseline used on 235 c6bf421ca21e3107386861b31ce70b604a281b1c52343a49cbf42791ef0f349e
Historical compact package used on 235 and 175 801812eedc52dc5c5f485d7cbeb709bbc8b8ad47988e456b7c1093ac1b0200ab
Historical aligned package used on 175 2dfa42f730d457958b820807e2a83915851cbf5df73d1f620079fe21c71f9529
Exact standalone candidate build 1f1c848d004248c485de3aa05f734eaf8561fde4162a843321114294d3dfd50e

Recorded run labels are baselinecompact2, q6compactmodel1, compact175r2, q6alignedmodel175r1, q6compactnative1 and q6alignednative175r1. Full-model comparisons come from same-round-model-results.json and model175-results.json; operator results come from operator-results.json and native175-results.json. The final 95-instruction leaf matches the historical aligned package, but standalone integration and the new view guard were not included in that package's model run.

The identical formal request files have SHA256 08331861b9ff37c44c497576a45f96def7c143cfc59d871d7ef512d935a6c615; the recorded prompt-file SHA256 is ae8948cf4a76edf42c09ba63ae321ba8b396bfef6b5e06c24d620f2d292f6630. The operator fixture executable is 7ed4a53b8b55e2e68c6f0d4457284672a572c3f86fb64d1c235cc71d3085fc09. Model identity was recorded by path, size and modification time; a model-content SHA256 was not recorded.

Risks and limits

  • Exact-candidate K3 dispatch, model correctness and comparable performance remain NOT RUN. The available substitutes are exact-source host checks, builds and leaf machine-code identity plus the separately identified historical board runs. These do not establish end-to-end acceptance of the new branch. Merge remains pending the required evidence or an explicit maintainer decision on the validation gap; no exception has been granted.
  • Dispatch is intentionally restricted to the tested head dimensions. Arbitrary compact views are rejected explicitly, and on-board view matmul behavior remains unverified. Token equality on one fixed request is not a broad model-quality evaluation.
  • Raw logs, local fixture sources and the fixed prompt token array are retained locally and are not publicly attached. Essential measurements, raw operator samples, conditions and artifact identities are reproduced above; reviewers cannot independently replay those exact local fixtures from this PR alone. No new test code is submitted.
  • An initial K3-175 attempt was stopped during slow model loading and replaced by the reported run; it is not a timing sample. An initial host fixture compilation failed on an unrelated Q4 _Float16 declaration; the corrected extraction excludes that declaration while preserving Q6 code verbatim. Neither attempt is counted as a passing result.
  • Follow-up: validate the exact standalone candidate on K3 before making a merge-readiness or final-branch performance claim. K1 runtime was not measured.

AI assistance and responsibility

Codex assisted with implementation, experiments, local validation, code review, evidence checking and this PR description. The contributor reviewed the file-by-file changes and compact data layout before explicitly requesting publication. Contributor co-seven owns the submitted code and claims, including the stated validation limits.

Keep the original six-bit codes and signed subgroup scales for the
K2048/N248320 output head instead of expanding weights to Q8. Add a
lossless repack and inverse with 128-byte-aligned payloads, matched
physical allocation, and the paired TCM staging/IME2 decode path.

Preserve compact storage for complete zero-offset aliases and reject
unsupported views before they can enter the legacy weight path.

Assisted-by: Codex
@alex-spacemit
alex-spacemit merged commit fc01796 into spacemit-com:mtmd-backend Dec 4, 2026
11 of 20 checks passed
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