Skip to content

dspark: corrected draft runtime and shared packed target head - #179

Merged
bri-prism merged 8 commits into
prismfrom
feat/dspark-shared-head-runtime
Sep 18, 2026
Merged

bri-prism merged 8 commits into
prismfrom
feat/dspark-shared-head-runtime

Conversation

@bri-prism

@bri-prism bri-prism commented Sep 18, 2026 •

Copy link
Copy Markdown
Collaborator

Adds opt-in DSpark runtime optimizations: greedy token-ID output, MASK projection reuse, reduced correction/head work for retained positions, and a shared packed target output head. Full-block attention remains unchanged, and defaults remain unchanged.

The packed-head comparison improved 143.7 to 184.4 tokens/s (+28.3%) with unchanged acceptance on three short tasks. Sharing the packed head reduced the drafter weight buffer from 2954.90 to 2632.83 MiB; sharing itself did not provide a measurable speed gain over copying it. Those earlier checks passed token parity on all 72 requests.

The RTX 5090 depth sweep uses greedy decoding, a fixed full attention block of eight, 32 measured prompts across eight domains, and two passes in opposite depth order. Fresh three-run confirmations on one fixed JSON extraction example produced:

Retained depth Baseline tokens/s DSpark tokens/s Speedup
1 136.8 170.0 1.24×
2 137.1 214.7 1.57×
3 136.6 234.2 1.71×
4 136.5 271.1 1.99×
6 136.9 298.2 2.18×
8 136.8 329.5 2.41×

These are selected best-case measurements, not corpus averages. All three confirmation requests at each depth matched the baseline tokens. Across the broader corpus, only 28–34 of 64 measured requests per depth matched exactly; no overall performance or correctness claim is made. Target-only diagnostics over 2,304 scored positions produced zero KLD for the same-path control, approximately 1.40e-8 mean KLD for single-row verification with identical prefill, and 8.76e-5 for five-row verification. These quantify numerical differences; they do not establish that all parity failures are harmless.

Additional depth-eight confirmations using the same fixed JSON prompt and frozen runtime (three matching-output runs each):

GPU Baseline tokens/s DSpark tokens/s Speedup
H100 PCIe 87.7 190.4 2.17×
RTX PRO 6000 123.1 311.2 2.53×

These are selected examples. Both additional GPUs also retain broad-domain parity failures; neither establishes a whole-corpus speedup.

Metal passed the real-weight shared-head and prefix-equivalence checks. One broader depth-four pass matched all 33 requests including warmup, but measured 21.01 tokens/s against 26.77 baseline (0.785×). A shorter coding depth screen peaked at 0.985× at depth two. CUDA gains should not be assumed to carry over to Metal.

Review fixes and base-branch reconciliation are integrated. Local CPU checks pass 108 exact prefix forwards, eight rejection checks, graph-reuse checks, and atomic capture-list rejection. The isolated review candidate also passed 236 CUDA mask-selection checks, 108 exact CUDA prefix forwards and eight rejection checks after a clean rebuild. Those fixes are integrated; two subsequent initialization/byte-count corrections are not covered by that earlier GPU run. The broader output-parity failures remain unresolved. H100 and PRO 6000 sweeps are complete; RTX 4090, A100 and L40S sweeps are ongoing; GDN support is separate work and is not supported by this PR yet.

The target must outlive the drafter and its contexts when sharing the output head. Callers must provide a compatible target/drafter pair.

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🔵 Needs a closer look

The runtime spans public APIs, graph reuse, conversion, and multiple GPU backends while known parity failures and several correctness issues remain.

Pull request overview

Adds DSpark model conversion, graph execution, speculative drafting, target-state capture, shared output heads, and optional CUDA/Metal acceleration.

Changes:

  • Implements DSpark loading, conversion, inference, and speculative decoding.
  • Adds target-layer capture and shared-head support.
  • Adds DSpark validation and backend-specific test harnesses.
File summaries
File Description
CMakeLists.txt Adds DSpark acceleration options.
common/CMakeLists.txt Builds optional BLAS, CUDA, and Metal paths.
common/dspark-markov.cu Implements CUDA Markov resampling.
common/dspark-markov.h Declares CUDA resampling APIs.
common/dspark-markov-metal.h Declares Metal resampling APIs.
common/dspark-markov-metal.mm Implements Metal Markov resampling.
common/speculative.cpp Adds the DSpark drafting runtime.
common/speculative.h Exposes DSpark capture and test hooks.
conversion/__init__.py Registers DSpark model classes.
conversion/dspark.py Converts DSpark checkpoints.
gguf-py/gguf/constants.py Adds DSpark architecture metadata.
gguf-py/gguf/gguf_writer.py Adds DSpark GGUF writer helpers.
include/llama.h Adds shared-head model parameters.
src/llama-arch.h Defines DSpark architecture identifiers.
src/llama-context.cpp Implements capture and DSpark context staging.
src/llama-context.h Stores capture and staged context state.
src/llama-cparams.h Adds capture configuration.
src/llama-ext.h Exposes DSpark extension APIs.
src/llama-graph.cpp Adds DSpark graph inputs and greedy outputs.
src/llama-graph.h Defines DSpark graph state and results.
src/llama-hparams.h Adds DSpark hyperparameters.
src/llama-model.cpp Registers DSpark loading and metadata APIs.
src/llama-model.h Stores DSpark tensors.
src/models/dspark.cpp Implements the DSpark model graph.
src/models/models.h Declares the DSpark model class.
src/models/qwen35.cpp Captures intermediate target layers.
tests/CMakeLists.txt Registers DSpark test executables.
tests/gen-tiny-dspark.py Generates metadata-test fixtures.
tests/test-dspark-logsnr-meta.cpp Tests log-SNR metadata validation.
tests/test-dspark-loop.cpp Tests deterministic drafting behavior.
tests/test-dspark-real-eval.cpp Adds real-model parity and performance evaluation.
Review details
  • Files reviewed: 33/33 changed files
  • Comments generated: 6
  • Review effort level: Balanced

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

Comment thread common/speculative.cpp
Comment on lines +762 to +765
for (int32_t k = 0; k < correction_rows; ++k) {
if (k > 0) {
GGML_ASSERT(prev_token != mask_token_id &&
"dspark: markov resample must chain the previous step's SAMPLED "
Comment thread common/dspark-markov.cu Outdated
Comment on lines +101 to +107
const float logit = base[base_off + v] + acc;
if (scores) {
scores[v] = logit;
}
// strict >: rows are visited in increasing v, so the lowest index
// wins ties (same as the host scalar/BLAS argmax).
if (logit > bestv) {
Comment thread conversion/dspark.py Resolved
Comment thread src/llama-context.cpp Outdated
Comment on lines +1346 to +1349
if (il < 0 || il >= n_layer || il >= LLAMA_MAX_LAYERS) {
LLAMA_LOG_ERROR("%s: capture layer %d out of range [0, %d)\n", __func__, il, n_layer);
continue;
}
Comment thread src/llama-graph.h
const llama_adapter_loras * loras;
const llama_memory_context_i * mctx;
const llama_cross * cross;
const llama_dspark_ctx * dspark_ctx;
Comment thread gguf-py/gguf/constants.py Resolved
Comment thread src/llama-context.cpp Fixed
Comment thread src/llama-context.cpp Fixed
The row count and token counts are both uint32, so the product wrapped before
widening; the guarding asserts were already 64-bit.
The three fields were declared alongside dspark_ctx but left out of the
constructor, so any read would have returned indeterminate values.
@bri-prism
bri-prism merged commit 1a07bfa into prism Sep 18, 2026
8 of 11 checks passed
MasterCool4389 pushed a commit to MasterCool4389/Built_PrismML-ENG-CUDA_llama.cpp that referenced this pull request Sep 18, 2026
…ing, and -fa off (ggml-org#24503)

* Add interface is_model_splitted() to check the c-graph is splited or not

* Infer and propagate dynamic-dimension indices for all tensors in the GGML graph in api compute_model_outputs()

* Only do this for fallback sub graph

* Move dynamic dims compute in graph missmatch

* ggml-openvino: fix tensor data handling for PERMUTE/VIEW ops in split models

* ggml-openvino:add comments

* ggml-openvino: override VIEW op_case to 0 for split model inputs

* openvino backend: Handle unsupported VIEW shape-mismatch in OpenVINO backend

* Enable additional mul_mat tests and add tensor data saving function (PrismML-Eng#81)

* ggml-openvino: fix CONT/TRANSPOSE mapping and improve dynamic-dimension handling

* OpenVINO: add NORM/TANH support and rework SOFT_MAX translation

* ggml-openvino: extend VIEW handling

* Enable -fa off (PrismML-Eng#118)

* Enable --context-shift

* Fix llm param compute error for normal softmax not the softmax in attention

* OpenVINO backend: fix error for attention size compute in llm param

* use tensor->extra in infer_request i/o

* OpenVINO backend: refacter the compute_llm_params() func add get_attention_pattern_case to easy extand

* OpenVINO backend: clean unused code

* 1to1 match op update (PrismML-Eng#146)

* added translate_1to1_match_1_input function and updated gelu and tanh translations

* Remove unused translation function calls

---------

Co-authored-by: Mustafa Cavus <[email protected]>

* initial gemma4 support

* removed hardcoded names for kv cache slicing

* OpenVINO backend: Add new attention pattern for llm parameters compute

* flash attn Q shape static conversion

* Remove slice in permute translation when n_seq is 1

* return optional in extract_layer_from_name

* OpenVINO backend: refactor VIEW related operation (PrismML-Eng#148)

* OpenVINO backend: refactor VIEW related operation

* Enable VIEW handling in following ops

* OpenVINO backend does not support GGML_OP_NORM & GGML_OP_L2_NORM with VIEW input accuracy issue from OpenVINO

* OpenVINO backend: Add ops l2_norm & pad

* OpenVINO backend does not support CPY with non-contiguous data or mismatched types

* add op SSM_CONV GATED_DELTA_NET

* OpenVINO backend: fix error for bf16 in OV gpu plugin

* reverted static Q input shape for attention layer

* OpenVINO backend: remove hardcode name inp_tokens, which ignore some leaf case

* Disable remote tensor due to bug in ov gpu

* Disable n_token > 1 GATED_DELTA_NET on gpu

* OpenVINO backend: fix the view op dynamic handling issue in gemma4 & enable view + get_row

* OpenVINO backend: clean code

* OpenVINO backend: enable view + norm/rms_norm

* OpenVINO backend: concat op

* OpenVINO backend: argsort op

* OpenVINO backend: enable unary + view & GGML_UNARY_OP_SOFTPLUS

* Fix issue for test-backend-ops in TOPK_MOE, which compare VIEW ops result, VIEW node in OpenVINO no need compare, the whole graph result is correct

* OpenVINO backend: enable sum_rows

* OpenVINO backend: enable clamp

* OpenVINO backend: enable DIV

* OpenVINO backend: enable GGML_OP_MUL_MAT_ID

* OpenVINO backend: disable MUL_MAT_ID_FUSION case with large mem needed

* OpenVINO backend: Disable GGML_OP_ARGSORT, cause test_backend-ops failed

* OpenVINO backend: fix issue in mul_mat_id

* OpenVINO backend: Disable DIV with broadcast on GPU

* OpenVINO backend: update DIV

* use ov internal op GatedDeltaNet

* OpenVINO backend: enable llama erch test qwen3next

* OpenVINO backend: enable RMS_NORM + VIEW & remove op_case 2 for rope

* OpenVINO backend: fix error

* suggested changes, need review

* suggested changes, need review

* OpenVINO backend: clean unused code & fix build warning

* OpenVINO backend: enable minicpm3 for arch test

* Disable GDN op (PrismML-Eng#177)

* disable gated_delta_net

* update stateful_kv_size correctly in mismatch case

* OpenVINO backend: enable arch test for qwen3vl

* OpenVINO backend: enable cohere2 for arch test

* OpenVINO backend: enable t5 for arch test

* OpenVINO backend: enable jamba for arch test

* OpenVINO backend: remove warning for tmp

* OpenVINO backend: enable kimi-linear for arch test

* Remove unused

* Fix gpt-oss accuracy issue

* OpenVINO backend: enable arctic for arch test

* OpenVINO backend: enable grok for arch test

* Gemma4 initial npu support (PrismML-Eng#179)

* Initiall gemma4 npu support

* temp. fix for gemma4 accuracy bug on npu

* Remove hardcoded names for npu-fold handling

* revert static n tokens for cont translation as it is not needed

* removed unused variable

* ggml-openvino: add GGML_OPENVINO_ENABLE_CACHE env var to control decoder cache. Add environment variable GGML_OPENVINO_ENABLE_CACHE (default: YES). When set to NO, the decoder_cache is bypassed and models are rebuilt from the cgraph on every inference call in both dynamic and static compute paths. This is useful for debugging and verifying correctness without caching interference.

* Revert "Gemma4 initial npu support (PrismML-Eng#179)"

This reverts commit 0d29a9c.

* OpenVINO backend: disable debug log print

* Update TBB discovery. Delegated to OpenVINOs own config.

* OpenVINO backend: GGML_OPENVINO_ENABLE_CACHE YES -> 1

* OpenVINO backend: fallback FLASH_ATTN_EXT in gemma3n to CPU backend

* Add raw ov infer profiling metric

* Add OV raw infer time metric to static compute path

Co-authored-by: virajwad <[email protected]>

* Modify precision of static profiling

* update to OV 2026.2, add OV windows CI

* fix editorconfig-checks

* Initiall gemma4 npu support

* temp. fix for gemma4 accuracy bug on npu

* Remove hardcoded names for npu-fold handling

* revert static n tokens for cont translation as it is not needed

* removed unused variable

* test-llama-archs fix

* Fix gemma4 flash_attn fallback

* support im2col

* fix code style

* disable add_rope_sin_cos optimization

* stateless boradcast and rope optimizations

* Enable manual gqa attn by default for stateless gpu

* manual gqa: fixed static batch

* gemma4 llama-bench ctx update fix

* Update OV win CI

* stateful rope fusion temp. fix

* OpenVINO backend: Conslolidate supported ops

* Exclude unsupported GGML_OP_SUB cases

* Exclude unsupported TOPK_MOE cases

* OpenVINO Backend: MUL_MAT enhancements

* Update OV CI

* support f16 mask input for npu

* Make GGML_OPENVINO_* env vars usage uniform

Standardize all GGML_OPENVINO_* env flags:
positive integers >0 to enable. Unset, empty, =0, or non-numeric values to disable.
This fixes cases where text values or empty strings enabled features.

* OpenVINO backend: Enhance envvar handling

* more cleanup

* move ggml_openvino_env_flag to appropriate place

* OpenVINO backend: add REPEAT translator, Q5_1 weights, and GLU view-input fix

* ggml-openvino: fix -Werror=cast-qual in extract_q5_1_data

* Update openvino.Dockerfile

Use BuildKit cache mounts for faster Docker rebuilds.
Use apt instead of dpkg, remove unused .ddeb downloads, add DLLAMA_BUILD_TESTS=OFF.

* ggml-openvino: centralize env var access via *getenv_str/getenv_int helpers

Replace getenv and legacy flags with _str and _int helpers.Minor cleanup, doc updates.

* OpenVINO backend: Enable GGML_OP_ADD_ID

* Uptade openvino backend clamg-format

* clang-format

* Update OPENVINO.md (PrismML-Eng#211)

* OpenVINO backend: fix accuracy issue for op CONCAT with i64 precision

* Remove strict concurrency for gpu-openvino-low-perf

* Update openvino CI keynames; add ccache-clear

* Apply suggestions from code review

Co-authored-by: Sigbjørn Skjæret <[email protected]>

* Fix formatting

---------

Co-authored-by: Xuejun Zhai <[email protected]>
Co-authored-by: Mustafa Cavus <[email protected]>
Co-authored-by: Mustafa Cavus <[email protected]>
Co-authored-by: Xuejun <[email protected]>
Co-authored-by: Wang Yang <[email protected]>
Co-authored-by: Ravi Panchumarthy <[email protected]>
Co-authored-by: virajwad <[email protected]>
Co-authored-by: copilot-swe-agent[bot] <[email protected]>
Co-authored-by: Mostafa Faheem <[email protected]>
Co-authored-by: Sigbjørn Skjæret <[email protected]>
bri-prism pushed a commit that referenced this pull request Sep 21, 2026
… and head

A `dflash` drafter that ships no `token_embd.weight` or `output.weight` reads the target's through `ctx_other`. When the target is Hadamard-folded (`prism.hadamard.*`), those two tensors carry the target's transforms: `output.weight` expects a rotated activation, and `token_embd.weight` stores rotated rows that need the inverse after the lookup. The draft context only consulted its own transform maps, which are empty for such a drafter, so it fed the packed head an unrotated activation and used the rotated embedding rows as if they were primal. The graph built and ran, and the draft logits were noise. DSpark drafts against Ternary-Bonsai-2-27B-PQ2_0 accepted 1-2% of drafted tokens instead of 43-57%, with no error and no warning.

Ternary-Bonsai-2-27B (PQ2_0 and PTQ1_0) folds 401 weights including `output.weight` and lists `token_embd.weight` as an inverse-lookup table. A drafter converted with `gguf-dspark-to-dflash --drop-shared-tensors` (the documented path) borrows both tensors, so every Bonsai 2 DSpark pairing takes this route. The earlier Ternary-Bonsai-27B GGUFs (PQ2_0 and Q2_g64) carry no `prism.hadamard` metadata at all (0 folded weights, no inverse tables in the published headers), so borrowing their head and embeddings never needed a transform and the gap stayed invisible until Bonsai 2.

Fix, five files, +48 / -20:

- `llama_context` keeps `hadamard_rotations` and `hadamard_inverses`: the model's own entries plus the target's when `ctx_other` is set. Entries are keyed by tensor pointer, so the two models' entries never collide. `graph_params` and the one-time `llama_verify_hadamard_graph` coverage check use these maps, so a draft graph that bypasses a transform on a borrowed tensor now fails at reserve time with the existing "consumed without its activation transform" error instead of computing wrong logits.
- `llm_graph_context::build_embd_rows(tok_embd, ids)` is `ggml_get_rows` followed by the inverse transform when the table is latent. `build_inp_embd` now calls it (same ops as before), and `dflash.cpp` uses it for the decoder input rows (DFlash/DSpark and the DSV4 backbone) and for the DFly chain's predecessor embedding.
- `build_lora_mm` already applies the forward transform to the borrowed `output.weight` once the map contains it, so the head needs no new code.
- The `dspark` arch from #179 is untouched: it copies the head's rotation into its own map at load time when `dspark_head_source` is set, and requires its own `token_embd.weight`. A drafter that carries its own tables is unaffected: its tensors are not in the target's maps.

Eagle3 and Gemma4-assistant contexts also borrow through `ctx_other`. Neither is changed by this patch: the eagle3 decoder reads `tok_embd` with a bare `ggml_get_rows` (`src/models/eagle3.cpp`), so on a Hadamard-folded target it now fails at the coverage check instead of computing wrong logits; a follow-up can route it through `build_embd_rows`. Gemma4-assistant reads `model_other->tok_embd` with a bare `ggml_get_rows`; against a folded target it will now fail the coverage check at reserve time rather than silently read rotated rows. I have no folded Gemma4 pair to test, so that path is left as is.
@khosravipasha
khosravipasha deleted the feat/dspark-shared-head-runtime branch September 24, 2026 07:27
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants