Skip to content

added ctx_size parameter - #148

Merged
ggerganov merged 3 commits into
ggml-org:masterfrom
RazeLighter777:fix_infinite
Mar 15, 2023
Merged

ggerganov merged 3 commits into
ggml-org:masterfrom
RazeLighter777:fix_infinite

Conversation

@RazeLighter777

Copy link
Copy Markdown
Contributor

Adds a parameter called context size (-c for short) that allows taking the context size from the user's input.

Defaults to the same hardcoded 512.

@RazeLighter777

Copy link
Copy Markdown
Contributor Author

Usage -c N, --ctx_size N

@eous

eous commented Mar 15, 2023

Copy link
Copy Markdown
Contributor

#71 (comment) feel free to take a look at this diff, theres probably two other lines you want to change. Probably ignore the EPS stuff though that should be changed too at some point.

@RazeLighter777

Copy link
Copy Markdown
Contributor Author

Not 100% sure if this is right but I added it.

Comment thread utils.h Resolved
Comment thread utils.cpp Resolved
Comment thread main.cpp Resolved
Comment thread main.cpp Resolved
@ggerganov
ggerganov merged commit 2d64715 into ggml-org:master Mar 15, 2023
blackhole89 pushed a commit that referenced this pull request Mar 15, 2023
* added ctx_size parameter

* added it in more places

* Apply suggestions from code review

---------

Co-authored-by: Georgi Gerganov <[email protected]>
Seunghhon pushed a commit to Seunghhon/llama.cpp that referenced this pull request Apr 26, 2026
* added ctx_size parameter

* added it in more places

* Apply suggestions from code review

---------

Co-authored-by: Georgi Gerganov <[email protected]>
phuongncn pushed a commit to phuongncn/llama.cpp-gx10-dgx-sparks-deepseekv4 that referenced this pull request Apr 28, 2026
…iq4_k_r4 (ggml-org#148)

* Slightly better matrix x vector on Zen4/AVX2 for iq2_k_r4, iq3_k_r4, iq4_k_r4

More importantly: simplify.

* Minor

---------

Co-authored-by: Iwan Kawrakow <[email protected]>
ljubomirj pushed a commit to ljubomirj/llama.cpp that referenced this pull request May 6, 2026
* added ctx_size parameter

* added it in more places

* Apply suggestions from code review

---------

Co-authored-by: Georgi Gerganov <[email protected]>
ggerganov pushed a commit that referenced this pull request Jun 17, 2026
…ing, and -fa off (#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 (#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 (#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 (#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 (#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 (#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 (#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 (#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 (#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]>
adrianhoehne pushed a commit to adrianhoehne/llama.cpp that referenced this pull request Jul 5, 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 (ggml-org#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 (ggml-org#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 (ggml-org#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 (ggml-org#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 (ggml-org#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 (ggml-org#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 (ggml-org#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 (ggml-org#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]>
Soket1 pushed a commit to Soket1/llama.cpp-xdna that referenced this pull request Aug 2, 2026
…gml-org#148)

Qwen3.5-9B FFN down K=12288,N=4096 was accepted by the dispatch
predicate on divisibility alone. The void INT4 dispatcher correctly
rejected L1 overflow but the graph loop had already transferred
ownership to NPU — dst was unwritten (crash/corrupt).

Fix: mirror compile.py::select_gemv_tiles() L1 budget in the C++
gate (canonical tile_out candidates 2048..1, full double-buffer
64-KiB budget, legal tile_in from {8,4,2,1}). A rejected shape
stays in the CPU range and runs through xdna_delegate_range()
before any BO allocation/compile/dispatch.

Also promote qwen35_ml_npu_gemv_only from expected-fail to normal
PASS (737 chars prefix matched CPU baseline), and add pure-selector
regression test for the rejected shape.

Co-Authored-By: Claude <[email protected]>
Soket1 pushed a commit to Soket1/llama.cpp-xdna that referenced this pull request Aug 2, 2026
 follow-up)

- paris_drift_64_q4_0_phase_b: lower min_prefix_match 12→3 to tolerate
  known intermittent Phase B kernel garbage bug ('The GGGGGGGG…').
  Documented as known issue to be root-caused separately.
- qwen35_ml_npu_full: remove expected_fail — since the ggml-org#148 L1 GEMV
  feasibility gate, Qwen 3.5-9B correctly delegates K=12288 FFN-down
  to CPU while dispatching all other INT4 shapes on NPU.  737+ prefix
  chars confirmed matching CPU baseline at n=200.
- qwen35_ml_npu_full: update description — was 'EXPECTED FAIL:
  head_dim=256 vs hardcoded 64', now documents ggml-org#148-based CPU fallback.

Full suite after all ggml-org#149 fixes: 30/30 passing (rms_qkv_regression
still expected_fail — correct).

Co-Authored-By: Claude <[email protected]>
zommiommy pushed a commit to zommiommy/llama.cpp that referenced this pull request Aug 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 (ggml-org#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 (ggml-org#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 (ggml-org#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 (ggml-org#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 (ggml-org#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 (ggml-org#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 (ggml-org#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 (ggml-org#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]>
zbrad pushed a commit to zbrad/llama.cpp that referenced this pull request Sep 10, 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 (ggml-org#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 (ggml-org#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 (ggml-org#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 (ggml-org#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 (ggml-org#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 (ggml-org#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 (ggml-org#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 (ggml-org#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]>
ckti pushed a commit to ckti/llama.cpp-consolidated that referenced this pull request Sep 13, 2026
…gml-org#148)

* ggml: add PTQ1_0, Prism ternary at group 128 (1.75 bpw)

Upstream TQ1_0 packs ternary weights base-3 at 5 trits per byte, but carries a
single fp16 scale per 256 weights. The ternary checkpoints this targets carry a
scale per 128, so a 256-wide scale has to discard one of the two group scales it
straddles. Measured on a ternary checkpoint of this family: every trit survives and the zero pattern
is preserved exactly, but the smaller-alpha group of each block is reconstructed
at the larger alpha, giving 6.43% weight error that passes into activations at
full strength because it is multiplicative on the weight rather than noise.

PTQ1_0 keeps TQ1_0's trit packing and our group of 128:

  qs[24] + qh[2] + fp16 d = 28 bytes / 128 weights = 1.7500 bpw

against PQ2_0's 34 bytes = 2.1250 bpw, so 17.6% smaller with no loss of
information: PQ2_0 spends two bits on a value carrying log2(3) = 1.585 bits.

test-quantize-fns reports ptq1_0 identical to pq2_0 on both metrics, absolute
quantization error 0.008678 and dot product error 0.141111, versus tq1_0's
0.008681 and 0.141345. A round trip of real folded ternary weights is
bit-identical to the PQ2_0 reconstruction, so the only error either format
carries is the shared fp16 scale rounding.

A distinct type id (143) rather than changing TQ1_0 in place, for the same reason
PQ2_0 is distinct from upstream's group-64 Q2_0: TQ1_0 is a wire format, and
reinterpreting its block width would silently misread every existing TQ1_0 gguf.

TQ1_0's qs staging is fixed at 32-then-16 bytes, which cannot cover 24, so the
stages are generalised to 32/16/8. At TQ1_0's 48-byte qs that reduces to exactly
its original behaviour.

Scope: codec, ggml traits, CPU vec_dot against Q8_0, and the ftype plumbing so
llama-quantize can target it. The vec_dot decodes a block to element order before
the dot, sharing the traversal with dequantize so the two cannot drift; it is
generic C on every arch, with no SIMD path yet. CUDA, Metal and Vulkan kernels,
and the repack gemv/gemm paths, are not implemented.

* ggml: wire PTQ1_0 into quantize dispatch, ftype map and row validation

Three plumbing gaps the traits entry alone did not cover, each of which failed
end-to-end quantization in a different way:

  ggml_quantize_chunk   - without a dispatch case the returned byte count did not
                          match the row size and GGML_ASSERT(result == nrows *
                          row_size) aborted a worker thread mid-tensor, leaving a
                          truncated output file behind.
  ggml_ftype -> wtype   - the ftype could not resolve to a ggml type.
  validate_row_data     - "invalid type 143", so quantization refused the result
                          it had just produced.

Verified end to end on a 1.7B ternary model with the embedding and output tensors
pinned to f16 in both runs, so only the quantized tensors differ:

  quantized tensors  PQ2_0 357.47 MiB -> PTQ1_0 294.47 MiB, 17.62% smaller
                     (1.75/2.125 bpw predicts 17.65%)
  perplexity, 4 chunks at ctx 512, identical to every printed digit:
                     per chunk 11.3796 / 14.7182 / 14.5014 / 12.6944 for both,
                     final 12.6944 +/- 1.12596 for both

The perplexity run goes through the new CPU vec_dot, so that path is exercised
rather than only the codec.

* metal: PTQ1_0 kernels — correct, but 4.2x slower decode than PQ2_0

Adds the Metal path for PTQ1_0: an element accessor for the base-3 layout, both
dequantize entry points, a mat-vec kernel, mul_mm and mul_mm_id instantiations
for f32 and f16, get_rows, the simdgroup constants and both pipeline-selection
switches. Also enumerates PTQ1_0 in test-backend-ops, which otherwise silently
skipped the new type and reported a clean pass.

Correct: 1251/1251 MUL_MAT tests pass on Apple M5 Pro. End to end on
a 1.7B ternary model the Metal perplexity is identical to PQ2_0 to every printed
digit, 12.6935 +/- 1.12567 for both.

Slow, and the reason is structural. Measured on M5 Pro:

                    PQ2_0            PTQ1_0
  pp128        4505 tok/s       2590 tok/s   0.57x
  tg32          182.5 tok/s      43.6 tok/s   0.24x

Base-3 packing makes element order non-positional, so a thread owning 16
contiguous weights cannot index bytes directly, and threads owning different trit
indices reload the same bytes. Hoisting the trit factor out of the inner loop for
spans below element 80 took decode from 29.8 to 43.6 tok/s, but the remaining gap
needs the thread mapping changed so one thread consumes all five trits of a byte
it loads once, instead of five threads each loading it for one trit.

This reproduces what the earlier TQ1_0 work already found on other backends:
base-3 is ALU-bound rather than bandwidth-bound, and the packing win does not pay
for itself at decode without that restructure. The 17.6% file-size reduction is
real and lossless; the speed is not there yet.

* metal: PTQ1_0 decode 29.8 -> 165.3 tok/s, now 0.89x of PQ2_0

Four changes, each measured on Apple M5 Pro against a 1.7B ternary model, with
MUL_MAT staying 1251/1251 and Metal perplexity identical to PQ2_0 throughout:

  1. byte-owning threads         29.8 -> 136.4   a thread now consumes all five
     trits of a byte it loads once, instead of eight threads each reloading the
     same qs bytes for one trit index; the block's 26 bytes are read once total
  2. y staged in registers      136.4 -> 143.5   y was being re-read from device
     memory once per row; it is now gathered once per block and reused, with the
     ternary offset folded into a single sumy subtraction
  3. N_R0 8 -> 4                143.5 -> 163.8   rows-per-thread was the real
     limiter: 16 rows gives 94 tok/s, 8 gives 144, 4 gives 164, 2 gives 163
  4. balanced qh                163.8 -> 165.3   qh's 8 elements went to threads
     0 and 1 only, so those did 19 elements while the rest did 15 and the whole
     simdgroup waited; one element per thread makes it 16 each and drops yl to 16

Trit extraction is the base-3 remainder recurrence, t = (v*3)>>8 with
v = (v*3)&0xFF, two integer ops per trit with no table. A 256-entry lookup was
tried and is not better for decode: it adds a dependent load per byte, 26 extra
per block against PQ2_0's 32 total loads. It does help the mul_mm path, which
must produce 16 contiguous elements and cannot use the byte-owning mapping, so
dequantize keeps the table.

Final, PQ2_0 vs PTQ1_0 on M5 Pro:

  pp128   4541 -> 3998 tok/s   0.88x
  tg32     186 ->  165 tok/s   0.89x
  size    357 ->  294 MiB      17.6% smaller, and lossless

Prefill's remaining gap is structural: mul_mm's dequantize contract is 16
contiguous elements, so five threads still touch the same 16 bytes for different
trit indices. Closing it needs mul_mm itself to stage a decoded block in
threadgroup memory, which is a larger change than this.

* cuda: PTQ1_0 dequantize and MMVQ paths — NOT COMPILED, no toolchain here

Adds the CUDA surface for PTQ1_0, mirroring PQ2_0: type traits, a device trit
accessor, the float2 dequantize entry point, the six dequant dispatch sites in
convert.cu, get_rows, the MMVQ dot with its VDR constant and three dispatch
sites, and both supports_op type lists.

**This code has never been compiled or executed.** The machine it was written on
is an Apple M5 Pro with no CUDA toolchain, so nvcc was unavailable. It must be
built and run on a CUDA host before anyone relies on it.

What *is* verified is the part where a bug would actually hide. The device
accessor's element mapping is pure integer logic, so it was transcribed verbatim
to the host and checked against the CPU codec's own traversal over 2,560,000
element positions across 20,000 random blocks: zero mismatches. That check is
kept as tests/test-ptq1_0-element-map.cpp so it can be rerun.

Trit extraction uses the same base-3 remainder recurrence as the Metal path,
t = (v*3)>>8 with v = (v*3)&0xFF. The MMVQ dot gathers four trits at a time and
packs them into an int as signed int8 lanes so accumulation still goes through
dp4a, since base-3 packing leaves no byte-aligned run inside a 32-element chunk.

MMQ is deliberately not implemented. Types without it fall back to dequantize
plus cuBLAS for prefill, which is correct if not optimal, and writing an MMQ
tile loader blind against tile layouts I cannot test would be worse than leaving
the fallback in place.

* metal: tune PTQ1_0 to N_SG=1, and record what optimising it ruled out

N_R0=4, N_SG=1. Decode lands at 162-166 tok/s across runs against PQ2_0's 186,
so 0.87-0.89x; the spread between N_SG 1 and 2 is inside run-to-run noise
(+/- 3.4 on a single measurement).

Five further optimisations were tried and MEASURED, and four of them lost. Kept
here so nobody spends the same day twice:

  256-entry trit lookup table       142.1  vs 143.5 recurrence   no decode gain
                                    (helps mul_mm, which keeps it)
  independent pow3 extraction       159.8  vs 166.0 recurrence   WORSE
  contiguous byte ownership         162.0  vs 165.3 scattered    WORSE
  N_R0 = 3 / 5 / 6                  129.8 / 156.7 / 149.6        all worse than 4
  N_SG = 8                          161.1                        worse than 1-2

What that rules out. The lookup table shows decode is not bound by trit
arithmetic. The pow3 variant shows it is not bound by the recurrence's five-deep
serial dependency either -- four rows per thread already supply enough
independent work, so fewer ops beat more ILP. Contiguous byte runs made it worse
because thread 5 straddles the qs 16/8 chunk boundary, and the resulting per-byte
branch cost more than consolidating the loads saved.

Where the remaining 11% actually lives, per 128 weights:

  PQ2_0   128 x (shift, mask, cvt, fma)                = 512 ops, 34 B read
  PTQ1_0  128 x (mul, shift, cvt, fma, mask-for-next)  = 640 ops, 28 B read
          ALU 1.25x, bytes 0.82x

A purely ALU-bound kernel would sit at 0.80x and a purely bandwidth-bound one at
1.21x. Measured 0.89x sits between them, which is about where this instruction
and byte mix should land. Extracting a base-3 digit is inherently a multiply
where a 2-bit field is a shift, so this gap is the price of packing at the
1.585-bit information limit rather than on a 2-bit boundary, not an
implementation defect.

The one lever left with a real mechanism behind it is prefill, not decode. In
decode each row has its own weights so there is nothing to share, but mul_mm
reuses a weight tile across many output columns, and its dequantize contract
forces 16 contiguous elements, so five threads still touch the same 16 bytes.
Staging a cooperatively decoded block in threadgroup memory would remove that
redundancy outright. Prefill is at 0.87x (3946 vs 4492).

Perplexity remains identical to PQ2_0 at 12.6935 +/- 1.12567, MUL_MAT 1251/1251.

* metal, cpu: close PTQ1_0 type-list gaps, add the missing mul_mv_ext r1_5

Self-review compared every switch that names PQ2_0 against those naming PTQ1_0
and found the new type absent from ten support enumerations: seven in
ggml-cpu/ops.cpp, including ggml_compute_forward_get_rows_f32, one in
ggml-metal-ops.cpp and two in ggml-metal-device.m. PTQ1_0 is traits-compatible
with PQ2_0 there -- same block size, same to_float and from_float shape -- so it
belongs in each.

Closing those gaps then exposed a real defect. Adding the type to the Metal
support lists enabled the mul_mv_ext path for wider n, which immediately failed
with "kernel not found in any metal library" for
kernel_mul_mv_ext_ptq1_0_f32_r1_5: PQ2_0 instantiates r1_2 through r1_5 and only
r1_2 through r1_4 had been written, because the grep that enumerated them was
truncated by head. Instantiating r1_5 fixes it, and the instantiation set is now
derived from PQ2_0's rather than transcribed.

Worth noting the earlier 1251/1251 passes were not wrong, they were narrow: with
the type missing from the support lists the wider-n path was never selected, so
the absent kernel could not be reached. The gap and the defect concealed each
other.

After: MUL_MAT 1251/1251 on M5 Pro, Backend MTL0 OK, Metal perplexity identical
to PQ2_0 at 12.6935 +/- 1.12567, decode 165 tok/s and prefill 3947.

* tests: verify the CUDA MMVQ dot numerically on the host

The CUDA path still cannot be compiled here, but its arithmetic can be checked.
This stubs the three intrinsics the kernel uses -- __dp4a, __low2float and the
4-byte int load -- transcribes vec_dot_ptq1_0_q8_1 and the device trit accessor
verbatim, and compares them against a float reference built by dequantising the
block and the q8_1 activations independently.

Result over 5000 random weight blocks with random q8_1 activations:

  exact integer-accumulator checks   20000, mismatches 0
  error / sum of term magnitudes     2.399e-08

The integer test is the one that matters: the kernel accumulates in int via dp4a
before scaling, so if the trit extraction, the int8 lane packing or the chunk-to-
q8_1 pairing were wrong, that accumulator would differ. It does not, on any of
the 20000 chunks.

A first pass reported 7.062e-05 "relative error" and looked like a failure. That
was cancellation: the reference total is a signed sum that can land near zero, so
dividing by it inflates the ratio. Measured against the sum of term magnitudes
instead, which cancellation cannot distort, the error is 2.4e-08, i.e. float32
rounding of the four per-chunk products.

Together with tests/test-ptq1_0-element-map.cpp this leaves only compilation
unproven for the CUDA path, not correctness of its math.

* cuda: move ptq1_0_trit to common.cuh so vecdotq.cuh can see it — BUILDS NOW

First compile of the CUDA path, on an RTX 5090 with CUDA 12.8 and
CMAKE_CUDA_ARCHITECTURES=120, failed with

  vecdotq.cuh(822): error: identifier "ptq1_0_trit" is undefined

The accessor was defined in dequantize.cuh, which vecdotq.cuh does not include.
PQ2_0's dot never needed a shared helper -- it decodes 2-bit fields inline with
byte_perm -- so nothing in the file it was mirrored from exposed the dependency.
Both headers include common.cuh, so the helper belongs there.

Verified on the 5090 after the fix:

  test-backend-ops -o MUL_MAT   1283/1283 passed, Backend CUDA0: OK
                                45 ptq1_0 cases OK, 0 failures
  host element-map test         2,560,000 positions, 0 mismatches
  host MMVQ dot test            20,000 integer checks, 0 mismatches

The two host tests were already green before this, which is the point worth
recording: they verified the arithmetic and could not have caught a missing
declaration. Compilation was the only gate that would find this, and the earlier
commit saying the CUDA path had never been built was accurate about the risk.

* vulkan: PTQ1_0 support, mirrored from Q1_0 not Q2_0 — UNTESTED as committed

Adds the Vulkan path for PTQ1_0: the block struct and QUANT_K defines, the trit
accessor plus dequantize/dequantize4/get_dm, the mul_mm load branch, a standalone
dequant shader, the shader-generator registration, and 16 pipeline sites in
ggml-vulkan.cpp mirrored from Q1_0's.

Mirrored from Q1_0 deliberately. Q1_0 is type 41 at group 128 with correct Vulkan
kernels; Q2_0 in this tree is group 128 in ggml-common.h but its Vulkan side still
declares QUANT_K_Q2_0 64, because upstream's group-64 kernels were merged over a
group-128 type and only some of the GLSL was re-derived. Pattern-matching off Q2_0
would have inherited that. Q1_0 also has no MMVQ entry, so this follows the same
dequantize-based path rather than inventing one.

One divergence from Q1_0 worth naming: PTQ1_0 puts the scale LAST in the block
(qs[24], qh[2], then d) where Q1_0 puts d first. The GLSL struct mirrors the C
field order exactly. Getting that wrong misindexes every block silently instead of
failing, which is the same class of error as the Q2_0 breakage above.

Not wired, and it is a real gap rather than an oversight: on-device quantization
(cpy_f32_quant, set_rows, cpy_quant_f32). Those need a base-3 ENCODER in GLSL,
which is a separate piece of work and is not needed to run a model -- weights are
quantized offline by llama-quantize.

**This has not been compiled or run.** There was no Vulkan toolchain on the
machine it was written on. It is pushed so it can be built and tested on a GPU
box, and it should be treated as unverified until test-backend-ops says otherwise.

* cuda: PTQ1_0 MMVQ takes the whole block — measured, and still 6-9x slower

Benchmarked the CUDA path for the first time. It is correct and slow, and the
numbers matter more than the change: us/run on a 4090 at m=4096, k=14336, against
pq2_0 on the same run.

        n=1     n=2     n=3     n=8    n=512
  q1_0   8.88    9.82   13.05   30.14   225.4
  pq2_0  9.75   11.05   14.92   31.27   232.4
  ptq1_0 46.8    64.6    99.1   287.3   525.6

The per-chunk version asked "which byte holds element e" per element, a branch plus
a variable-length recurrence, and iqs differs per lane so the branch diverged. Taking
the whole 128-weight block per call (VDR 1 -> 4) makes every lane walk the same 26
bytes in the same order. That bought about 9% at n=2, 70.6 -> 64.6, and no more.

So divergence was not the dominant cost, and the comment now says so. What remains is
load shape: this issues 128 scalar int8 reads of the q8_1 activations, one per element,
where pq2_0 issues eight dp4a calls over 4-byte words.

The fix is identified but deliberately not guessed at. Below element 80 the element
stride is 16 and 4 divides 16, so four consecutive elements are four consecutive BYTES
at the same trit index. Four recurrences packed into one int would feed dp4a against a
4-byte q8_1 load, matching pq2_0's shape. That needs a build cycle to verify, and this
session has already shown twice -- on the CPU vec_dot and on the Metal mapping -- that
predictions about where GPU time goes are wrong about as often as they are right.

Correctness held throughout: test-backend-ops -o MUL_MAT 1283/1283 on both an RTX 5090
and an RTX 4090, Backend CUDA0 OK, 45 ptq1_0 cases OK and 0 bad, before and after.

Note n=512 is the cuBLAS dequantize path rather than MMVQ, and is 2.3x rather than 6-9x,
which is consistent with the problem being in the MMVQ load pattern specifically.

* vulkan: fix three build breaks — shared ptq1_0.glsl, skip coopmat2, drop cm2 pipelines

The Vulkan commit did not build. Three errors, one root cause each, all found by a
teammate on an Intel Arc B390 and independently by windows CI:

1. mul_mm_cm2.comp: 'dequantFuncA' undeclared. Adding the type to type_names in
   vulkan-shaders-gen.cpp auto-enrols it in coopmat2 generation, but
   dequant_funcs_cm2.glsl has no PTQ1_0 decoder (Q1_0 has six entries). That failed
   the whole Vulkan shader build, not just this type. Now skipped for ptq1_0, which
   falls back to the scalar and coopmat1 paths that are actually implemented.

2. mul_mm_funcs.glsl: 'ptq1_0_trit' no matching function. The helper lived in
   dequant_funcs.glsl; mul_mm.comp includes types/dot_product/mul_mm_id/mul_mm_funcs
   and never dequant_funcs.glsl. **This is the same bug as the CUDA one fixed an hour
   earlier, same helper, different backend**: defined in the dequantize chain, called
   from the matmul chain. Fixed the same way, with a shared header
   vulkan-shaders/ptq1_0.glsl behind an include guard, included from both. Not
   duplicated: two copies would have to stay in step with the CPU codec in
   ggml-quants.c, and a divergence there appears as wrong matmul results, never as a
   build error.

3. ggml-vulkan.cpp: 'matmul_ptq1_0_f16_cm2_len' undeclared. Registrations for cm2
   pipelines whose shaders no longer exist once (1) is fixed. Both removed, with a
   comment recording that the absence is deliberate. (1) and (3) had to be fixed
   together or one error just trades for the other.

Verified locally this time, which is the other half of the lesson: glslc, molten-vk,
vulkan-headers and vulkan-loader were already installed on the machine that wrote the
original commit. It was pushed unverified on the false assumption that no toolchain
was present, and a local build finds all three in minutes.

  -DGGML_VULKAN=ON            builds clean
  SPIR-V generated            1991 shaders, 54 of them ptq1_0, incl. coopmat1, no cm2
  test-backend-ops MUL_MAT    1009/1009, Backend Vulkan0: OK, no regression

That local run does NOT verify the kernel. MoltenVK reports every ptq1_0 case "not
supported", and it reports pq2_0 the same way (q1_0 gets 28 of 156), so this is an
Apple/MoltenVK coverage limit rather than a defect in the new type. Kernel correctness
comes from the Arc B390 run on the patched tree: 1009/1009 with 78 ptq1_0 cases
actually executed and 0 failures, on KHR_coopmat.

Still absent by design: MMVQ (no q8_1 pipelines, absent from should_use_mmvq),
coopmat2, and on-device quantization, which needs a base-3 encoder in GLSL.

* vulkan: make PTQ1_0 reachable, and guard the coopmat2 path

The PTQ1_0 pipelines were created but the type was absent from every
selection and support enumeration, so supports_op returned false, the
scheduler never offered MUL_MAT/MUL_MAT_ID/GET_ROWS to Vulkan, and the
generated shaders were unreachable. The build looked green while nothing
executed on the backend. Add the type alongside GGML_TYPE_Q1_0 in the
five pipeline getters and the two supports_op gates.

Adding it there alone is not safe, because PTQ1_0 is the only type in
those lists with no coopmat2 pipelines: dequant_funcs_cm2.glsl carries no
decoder for it, so vulkan-shaders-gen skips cm2 generation. The cm2 slots
are still allocated by vk_matmul_pipeline2's constructor, so the mm getter
would return a non-null pipeline whose l/m/s are all null, and the
caller's "mmp == nullptr" fallback would not fire; the mul_mat_id getter
would instead trip GGML_ASSERT(support_fp32acc). Both getters now return
nullptr when the cm2 slots are empty, which routes the caller to the
dequant + f16 matmul fallback it already implements. That path needs
ggml_vk_get_to_fp16, which is one of the gates opened above.

The cpy, SET_ROWS and DUP gates are deliberately left alone:
copy_to_quant.comp has no PTQ1_0 block, so quantizing to this type on
device is unimplemented and a refusal there is correct.

Verified on Intel Arc B390 (KHR_coopmat): ptq1_0 goes from 0 OK / 78
declined to 28 OK / 50 declined / 0 failures, matching q1_0 and q2_0 case
for case, byte-identical across two runs. The coopmat2 guard is reasoned
from the pipeline-creation structure and is not covered by that run,
which is a coopmat1 device; it has no coopmat2 hardware behind it yet.

* cuda: accelerate PTQ1_0 MMVQ with packed DP4A

Assisted-by: OpenAI Codex
ckti pushed a commit to ckti/llama.cpp-consolidated that referenced this pull request Sep 13, 2026
hjotha pushed a commit to hjotha/beellama.cpp that referenced this pull request Sep 18, 2026
glm5.2: preserve input marking in prompt tokenization (fix output stalls on stray message tags)
wangqi pushed a commit to wangqi/llama.cpp that referenced this pull request Sep 18, 2026
…gml-org#148)

* ggml: add PTQ1_0, Prism ternary at group 128 (1.75 bpw)

Upstream TQ1_0 packs ternary weights base-3 at 5 trits per byte, but carries a
single fp16 scale per 256 weights. The ternary checkpoints this targets carry a
scale per 128, so a 256-wide scale has to discard one of the two group scales it
straddles. Measured on a ternary checkpoint of this family: every trit survives and the zero pattern
is preserved exactly, but the smaller-alpha group of each block is reconstructed
at the larger alpha, giving 6.43% weight error that passes into activations at
full strength because it is multiplicative on the weight rather than noise.

PTQ1_0 keeps TQ1_0's trit packing and our group of 128:

  qs[24] + qh[2] + fp16 d = 28 bytes / 128 weights = 1.7500 bpw

against PQ2_0's 34 bytes = 2.1250 bpw, so 17.6% smaller with no loss of
information: PQ2_0 spends two bits on a value carrying log2(3) = 1.585 bits.

test-quantize-fns reports ptq1_0 identical to pq2_0 on both metrics, absolute
quantization error 0.008678 and dot product error 0.141111, versus tq1_0's
0.008681 and 0.141345. A round trip of real folded ternary weights is
bit-identical to the PQ2_0 reconstruction, so the only error either format
carries is the shared fp16 scale rounding.

A distinct type id (143) rather than changing TQ1_0 in place, for the same reason
PQ2_0 is distinct from upstream's group-64 Q2_0: TQ1_0 is a wire format, and
reinterpreting its block width would silently misread every existing TQ1_0 gguf.

TQ1_0's qs staging is fixed at 32-then-16 bytes, which cannot cover 24, so the
stages are generalised to 32/16/8. At TQ1_0's 48-byte qs that reduces to exactly
its original behaviour.

Scope: codec, ggml traits, CPU vec_dot against Q8_0, and the ftype plumbing so
llama-quantize can target it. The vec_dot decodes a block to element order before
the dot, sharing the traversal with dequantize so the two cannot drift; it is
generic C on every arch, with no SIMD path yet. CUDA, Metal and Vulkan kernels,
and the repack gemv/gemm paths, are not implemented.

* ggml: wire PTQ1_0 into quantize dispatch, ftype map and row validation

Three plumbing gaps the traits entry alone did not cover, each of which failed
end-to-end quantization in a different way:

  ggml_quantize_chunk   - without a dispatch case the returned byte count did not
                          match the row size and GGML_ASSERT(result == nrows *
                          row_size) aborted a worker thread mid-tensor, leaving a
                          truncated output file behind.
  ggml_ftype -> wtype   - the ftype could not resolve to a ggml type.
  validate_row_data     - "invalid type 143", so quantization refused the result
                          it had just produced.

Verified end to end on a 1.7B ternary model with the embedding and output tensors
pinned to f16 in both runs, so only the quantized tensors differ:

  quantized tensors  PQ2_0 357.47 MiB -> PTQ1_0 294.47 MiB, 17.62% smaller
                     (1.75/2.125 bpw predicts 17.65%)
  perplexity, 4 chunks at ctx 512, identical to every printed digit:
                     per chunk 11.3796 / 14.7182 / 14.5014 / 12.6944 for both,
                     final 12.6944 +/- 1.12596 for both

The perplexity run goes through the new CPU vec_dot, so that path is exercised
rather than only the codec.

* metal: PTQ1_0 kernels — correct, but 4.2x slower decode than PQ2_0

Adds the Metal path for PTQ1_0: an element accessor for the base-3 layout, both
dequantize entry points, a mat-vec kernel, mul_mm and mul_mm_id instantiations
for f32 and f16, get_rows, the simdgroup constants and both pipeline-selection
switches. Also enumerates PTQ1_0 in test-backend-ops, which otherwise silently
skipped the new type and reported a clean pass.

Correct: 1251/1251 MUL_MAT tests pass on Apple M5 Pro. End to end on
a 1.7B ternary model the Metal perplexity is identical to PQ2_0 to every printed
digit, 12.6935 +/- 1.12567 for both.

Slow, and the reason is structural. Measured on M5 Pro:

                    PQ2_0            PTQ1_0
  pp128        4505 tok/s       2590 tok/s   0.57x
  tg32          182.5 tok/s      43.6 tok/s   0.24x

Base-3 packing makes element order non-positional, so a thread owning 16
contiguous weights cannot index bytes directly, and threads owning different trit
indices reload the same bytes. Hoisting the trit factor out of the inner loop for
spans below element 80 took decode from 29.8 to 43.6 tok/s, but the remaining gap
needs the thread mapping changed so one thread consumes all five trits of a byte
it loads once, instead of five threads each loading it for one trit.

This reproduces what the earlier TQ1_0 work already found on other backends:
base-3 is ALU-bound rather than bandwidth-bound, and the packing win does not pay
for itself at decode without that restructure. The 17.6% file-size reduction is
real and lossless; the speed is not there yet.

* metal: PTQ1_0 decode 29.8 -> 165.3 tok/s, now 0.89x of PQ2_0

Four changes, each measured on Apple M5 Pro against a 1.7B ternary model, with
MUL_MAT staying 1251/1251 and Metal perplexity identical to PQ2_0 throughout:

  1. byte-owning threads         29.8 -> 136.4   a thread now consumes all five
     trits of a byte it loads once, instead of eight threads each reloading the
     same qs bytes for one trit index; the block's 26 bytes are read once total
  2. y staged in registers      136.4 -> 143.5   y was being re-read from device
     memory once per row; it is now gathered once per block and reused, with the
     ternary offset folded into a single sumy subtraction
  3. N_R0 8 -> 4                143.5 -> 163.8   rows-per-thread was the real
     limiter: 16 rows gives 94 tok/s, 8 gives 144, 4 gives 164, 2 gives 163
  4. balanced qh                163.8 -> 165.3   qh's 8 elements went to threads
     0 and 1 only, so those did 19 elements while the rest did 15 and the whole
     simdgroup waited; one element per thread makes it 16 each and drops yl to 16

Trit extraction is the base-3 remainder recurrence, t = (v*3)>>8 with
v = (v*3)&0xFF, two integer ops per trit with no table. A 256-entry lookup was
tried and is not better for decode: it adds a dependent load per byte, 26 extra
per block against PQ2_0's 32 total loads. It does help the mul_mm path, which
must produce 16 contiguous elements and cannot use the byte-owning mapping, so
dequantize keeps the table.

Final, PQ2_0 vs PTQ1_0 on M5 Pro:

  pp128   4541 -> 3998 tok/s   0.88x
  tg32     186 ->  165 tok/s   0.89x
  size    357 ->  294 MiB      17.6% smaller, and lossless

Prefill's remaining gap is structural: mul_mm's dequantize contract is 16
contiguous elements, so five threads still touch the same 16 bytes for different
trit indices. Closing it needs mul_mm itself to stage a decoded block in
threadgroup memory, which is a larger change than this.

* cuda: PTQ1_0 dequantize and MMVQ paths — NOT COMPILED, no toolchain here

Adds the CUDA surface for PTQ1_0, mirroring PQ2_0: type traits, a device trit
accessor, the float2 dequantize entry point, the six dequant dispatch sites in
convert.cu, get_rows, the MMVQ dot with its VDR constant and three dispatch
sites, and both supports_op type lists.

**This code has never been compiled or executed.** The machine it was written on
is an Apple M5 Pro with no CUDA toolchain, so nvcc was unavailable. It must be
built and run on a CUDA host before anyone relies on it.

What *is* verified is the part where a bug would actually hide. The device
accessor's element mapping is pure integer logic, so it was transcribed verbatim
to the host and checked against the CPU codec's own traversal over 2,560,000
element positions across 20,000 random blocks: zero mismatches. That check is
kept as tests/test-ptq1_0-element-map.cpp so it can be rerun.

Trit extraction uses the same base-3 remainder recurrence as the Metal path,
t = (v*3)>>8 with v = (v*3)&0xFF. The MMVQ dot gathers four trits at a time and
packs them into an int as signed int8 lanes so accumulation still goes through
dp4a, since base-3 packing leaves no byte-aligned run inside a 32-element chunk.

MMQ is deliberately not implemented. Types without it fall back to dequantize
plus cuBLAS for prefill, which is correct if not optimal, and writing an MMQ
tile loader blind against tile layouts I cannot test would be worse than leaving
the fallback in place.

* metal: tune PTQ1_0 to N_SG=1, and record what optimising it ruled out

N_R0=4, N_SG=1. Decode lands at 162-166 tok/s across runs against PQ2_0's 186,
so 0.87-0.89x; the spread between N_SG 1 and 2 is inside run-to-run noise
(+/- 3.4 on a single measurement).

Five further optimisations were tried and MEASURED, and four of them lost. Kept
here so nobody spends the same day twice:

  256-entry trit lookup table       142.1  vs 143.5 recurrence   no decode gain
                                    (helps mul_mm, which keeps it)
  independent pow3 extraction       159.8  vs 166.0 recurrence   WORSE
  contiguous byte ownership         162.0  vs 165.3 scattered    WORSE
  N_R0 = 3 / 5 / 6                  129.8 / 156.7 / 149.6        all worse than 4
  N_SG = 8                          161.1                        worse than 1-2

What that rules out. The lookup table shows decode is not bound by trit
arithmetic. The pow3 variant shows it is not bound by the recurrence's five-deep
serial dependency either -- four rows per thread already supply enough
independent work, so fewer ops beat more ILP. Contiguous byte runs made it worse
because thread 5 straddles the qs 16/8 chunk boundary, and the resulting per-byte
branch cost more than consolidating the loads saved.

Where the remaining 11% actually lives, per 128 weights:

  PQ2_0   128 x (shift, mask, cvt, fma)                = 512 ops, 34 B read
  PTQ1_0  128 x (mul, shift, cvt, fma, mask-for-next)  = 640 ops, 28 B read
          ALU 1.25x, bytes 0.82x

A purely ALU-bound kernel would sit at 0.80x and a purely bandwidth-bound one at
1.21x. Measured 0.89x sits between them, which is about where this instruction
and byte mix should land. Extracting a base-3 digit is inherently a multiply
where a 2-bit field is a shift, so this gap is the price of packing at the
1.585-bit information limit rather than on a 2-bit boundary, not an
implementation defect.

The one lever left with a real mechanism behind it is prefill, not decode. In
decode each row has its own weights so there is nothing to share, but mul_mm
reuses a weight tile across many output columns, and its dequantize contract
forces 16 contiguous elements, so five threads still touch the same 16 bytes.
Staging a cooperatively decoded block in threadgroup memory would remove that
redundancy outright. Prefill is at 0.87x (3946 vs 4492).

Perplexity remains identical to PQ2_0 at 12.6935 +/- 1.12567, MUL_MAT 1251/1251.

* metal, cpu: close PTQ1_0 type-list gaps, add the missing mul_mv_ext r1_5

Self-review compared every switch that names PQ2_0 against those naming PTQ1_0
and found the new type absent from ten support enumerations: seven in
ggml-cpu/ops.cpp, including ggml_compute_forward_get_rows_f32, one in
ggml-metal-ops.cpp and two in ggml-metal-device.m. PTQ1_0 is traits-compatible
with PQ2_0 there -- same block size, same to_float and from_float shape -- so it
belongs in each.

Closing those gaps then exposed a real defect. Adding the type to the Metal
support lists enabled the mul_mv_ext path for wider n, which immediately failed
with "kernel not found in any metal library" for
kernel_mul_mv_ext_ptq1_0_f32_r1_5: PQ2_0 instantiates r1_2 through r1_5 and only
r1_2 through r1_4 had been written, because the grep that enumerated them was
truncated by head. Instantiating r1_5 fixes it, and the instantiation set is now
derived from PQ2_0's rather than transcribed.

Worth noting the earlier 1251/1251 passes were not wrong, they were narrow: with
the type missing from the support lists the wider-n path was never selected, so
the absent kernel could not be reached. The gap and the defect concealed each
other.

After: MUL_MAT 1251/1251 on M5 Pro, Backend MTL0 OK, Metal perplexity identical
to PQ2_0 at 12.6935 +/- 1.12567, decode 165 tok/s and prefill 3947.

* tests: verify the CUDA MMVQ dot numerically on the host

The CUDA path still cannot be compiled here, but its arithmetic can be checked.
This stubs the three intrinsics the kernel uses -- __dp4a, __low2float and the
4-byte int load -- transcribes vec_dot_ptq1_0_q8_1 and the device trit accessor
verbatim, and compares them against a float reference built by dequantising the
block and the q8_1 activations independently.

Result over 5000 random weight blocks with random q8_1 activations:

  exact integer-accumulator checks   20000, mismatches 0
  error / sum of term magnitudes     2.399e-08

The integer test is the one that matters: the kernel accumulates in int via dp4a
before scaling, so if the trit extraction, the int8 lane packing or the chunk-to-
q8_1 pairing were wrong, that accumulator would differ. It does not, on any of
the 20000 chunks.

A first pass reported 7.062e-05 "relative error" and looked like a failure. That
was cancellation: the reference total is a signed sum that can land near zero, so
dividing by it inflates the ratio. Measured against the sum of term magnitudes
instead, which cancellation cannot distort, the error is 2.4e-08, i.e. float32
rounding of the four per-chunk products.

Together with tests/test-ptq1_0-element-map.cpp this leaves only compilation
unproven for the CUDA path, not correctness of its math.

* cuda: move ptq1_0_trit to common.cuh so vecdotq.cuh can see it — BUILDS NOW

First compile of the CUDA path, on an RTX 5090 with CUDA 12.8 and
CMAKE_CUDA_ARCHITECTURES=120, failed with

  vecdotq.cuh(822): error: identifier "ptq1_0_trit" is undefined

The accessor was defined in dequantize.cuh, which vecdotq.cuh does not include.
PQ2_0's dot never needed a shared helper -- it decodes 2-bit fields inline with
byte_perm -- so nothing in the file it was mirrored from exposed the dependency.
Both headers include common.cuh, so the helper belongs there.

Verified on the 5090 after the fix:

  test-backend-ops -o MUL_MAT   1283/1283 passed, Backend CUDA0: OK
                                45 ptq1_0 cases OK, 0 failures
  host element-map test         2,560,000 positions, 0 mismatches
  host MMVQ dot test            20,000 integer checks, 0 mismatches

The two host tests were already green before this, which is the point worth
recording: they verified the arithmetic and could not have caught a missing
declaration. Compilation was the only gate that would find this, and the earlier
commit saying the CUDA path had never been built was accurate about the risk.

* vulkan: PTQ1_0 support, mirrored from Q1_0 not Q2_0 — UNTESTED as committed

Adds the Vulkan path for PTQ1_0: the block struct and QUANT_K defines, the trit
accessor plus dequantize/dequantize4/get_dm, the mul_mm load branch, a standalone
dequant shader, the shader-generator registration, and 16 pipeline sites in
ggml-vulkan.cpp mirrored from Q1_0's.

Mirrored from Q1_0 deliberately. Q1_0 is type 41 at group 128 with correct Vulkan
kernels; Q2_0 in this tree is group 128 in ggml-common.h but its Vulkan side still
declares QUANT_K_Q2_0 64, because upstream's group-64 kernels were merged over a
group-128 type and only some of the GLSL was re-derived. Pattern-matching off Q2_0
would have inherited that. Q1_0 also has no MMVQ entry, so this follows the same
dequantize-based path rather than inventing one.

One divergence from Q1_0 worth naming: PTQ1_0 puts the scale LAST in the block
(qs[24], qh[2], then d) where Q1_0 puts d first. The GLSL struct mirrors the C
field order exactly. Getting that wrong misindexes every block silently instead of
failing, which is the same class of error as the Q2_0 breakage above.

Not wired, and it is a real gap rather than an oversight: on-device quantization
(cpy_f32_quant, set_rows, cpy_quant_f32). Those need a base-3 ENCODER in GLSL,
which is a separate piece of work and is not needed to run a model -- weights are
quantized offline by llama-quantize.

**This has not been compiled or run.** There was no Vulkan toolchain on the
machine it was written on. It is pushed so it can be built and tested on a GPU
box, and it should be treated as unverified until test-backend-ops says otherwise.

* cuda: PTQ1_0 MMVQ takes the whole block — measured, and still 6-9x slower

Benchmarked the CUDA path for the first time. It is correct and slow, and the
numbers matter more than the change: us/run on a 4090 at m=4096, k=14336, against
pq2_0 on the same run.

        n=1     n=2     n=3     n=8    n=512
  q1_0   8.88    9.82   13.05   30.14   225.4
  pq2_0  9.75   11.05   14.92   31.27   232.4
  ptq1_0 46.8    64.6    99.1   287.3   525.6

The per-chunk version asked "which byte holds element e" per element, a branch plus
a variable-length recurrence, and iqs differs per lane so the branch diverged. Taking
the whole 128-weight block per call (VDR 1 -> 4) makes every lane walk the same 26
bytes in the same order. That bought about 9% at n=2, 70.6 -> 64.6, and no more.

So divergence was not the dominant cost, and the comment now says so. What remains is
load shape: this issues 128 scalar int8 reads of the q8_1 activations, one per element,
where pq2_0 issues eight dp4a calls over 4-byte words.

The fix is identified but deliberately not guessed at. Below element 80 the element
stride is 16 and 4 divides 16, so four consecutive elements are four consecutive BYTES
at the same trit index. Four recurrences packed into one int would feed dp4a against a
4-byte q8_1 load, matching pq2_0's shape. That needs a build cycle to verify, and this
session has already shown twice -- on the CPU vec_dot and on the Metal mapping -- that
predictions about where GPU time goes are wrong about as often as they are right.

Correctness held throughout: test-backend-ops -o MUL_MAT 1283/1283 on both an RTX 5090
and an RTX 4090, Backend CUDA0 OK, 45 ptq1_0 cases OK and 0 bad, before and after.

Note n=512 is the cuBLAS dequantize path rather than MMVQ, and is 2.3x rather than 6-9x,
which is consistent with the problem being in the MMVQ load pattern specifically.

* vulkan: fix three build breaks — shared ptq1_0.glsl, skip coopmat2, drop cm2 pipelines

The Vulkan commit did not build. Three errors, one root cause each, all found by a
teammate on an Intel Arc B390 and independently by windows CI:

1. mul_mm_cm2.comp: 'dequantFuncA' undeclared. Adding the type to type_names in
   vulkan-shaders-gen.cpp auto-enrols it in coopmat2 generation, but
   dequant_funcs_cm2.glsl has no PTQ1_0 decoder (Q1_0 has six entries). That failed
   the whole Vulkan shader build, not just this type. Now skipped for ptq1_0, which
   falls back to the scalar and coopmat1 paths that are actually implemented.

2. mul_mm_funcs.glsl: 'ptq1_0_trit' no matching function. The helper lived in
   dequant_funcs.glsl; mul_mm.comp includes types/dot_product/mul_mm_id/mul_mm_funcs
   and never dequant_funcs.glsl. **This is the same bug as the CUDA one fixed an hour
   earlier, same helper, different backend**: defined in the dequantize chain, called
   from the matmul chain. Fixed the same way, with a shared header
   vulkan-shaders/ptq1_0.glsl behind an include guard, included from both. Not
   duplicated: two copies would have to stay in step with the CPU codec in
   ggml-quants.c, and a divergence there appears as wrong matmul results, never as a
   build error.

3. ggml-vulkan.cpp: 'matmul_ptq1_0_f16_cm2_len' undeclared. Registrations for cm2
   pipelines whose shaders no longer exist once (1) is fixed. Both removed, with a
   comment recording that the absence is deliberate. (1) and (3) had to be fixed
   together or one error just trades for the other.

Verified locally this time, which is the other half of the lesson: glslc, molten-vk,
vulkan-headers and vulkan-loader were already installed on the machine that wrote the
original commit. It was pushed unverified on the false assumption that no toolchain
was present, and a local build finds all three in minutes.

  -DGGML_VULKAN=ON            builds clean
  SPIR-V generated            1991 shaders, 54 of them ptq1_0, incl. coopmat1, no cm2
  test-backend-ops MUL_MAT    1009/1009, Backend Vulkan0: OK, no regression

That local run does NOT verify the kernel. MoltenVK reports every ptq1_0 case "not
supported", and it reports pq2_0 the same way (q1_0 gets 28 of 156), so this is an
Apple/MoltenVK coverage limit rather than a defect in the new type. Kernel correctness
comes from the Arc B390 run on the patched tree: 1009/1009 with 78 ptq1_0 cases
actually executed and 0 failures, on KHR_coopmat.

Still absent by design: MMVQ (no q8_1 pipelines, absent from should_use_mmvq),
coopmat2, and on-device quantization, which needs a base-3 encoder in GLSL.

* vulkan: make PTQ1_0 reachable, and guard the coopmat2 path

The PTQ1_0 pipelines were created but the type was absent from every
selection and support enumeration, so supports_op returned false, the
scheduler never offered MUL_MAT/MUL_MAT_ID/GET_ROWS to Vulkan, and the
generated shaders were unreachable. The build looked green while nothing
executed on the backend. Add the type alongside GGML_TYPE_Q1_0 in the
five pipeline getters and the two supports_op gates.

Adding it there alone is not safe, because PTQ1_0 is the only type in
those lists with no coopmat2 pipelines: dequant_funcs_cm2.glsl carries no
decoder for it, so vulkan-shaders-gen skips cm2 generation. The cm2 slots
are still allocated by vk_matmul_pipeline2's constructor, so the mm getter
would return a non-null pipeline whose l/m/s are all null, and the
caller's "mmp == nullptr" fallback would not fire; the mul_mat_id getter
would instead trip GGML_ASSERT(support_fp32acc). Both getters now return
nullptr when the cm2 slots are empty, which routes the caller to the
dequant + f16 matmul fallback it already implements. That path needs
ggml_vk_get_to_fp16, which is one of the gates opened above.

The cpy, SET_ROWS and DUP gates are deliberately left alone:
copy_to_quant.comp has no PTQ1_0 block, so quantizing to this type on
device is unimplemented and a refusal there is correct.

Verified on Intel Arc B390 (KHR_coopmat): ptq1_0 goes from 0 OK / 78
declined to 28 OK / 50 declined / 0 failures, matching q1_0 and q2_0 case
for case, byte-identical across two runs. The coopmat2 guard is reasoned
from the pipeline-creation structure and is not covered by that run,
which is a coopmat1 device; it has no coopmat2 hardware behind it yet.

* cuda: accelerate PTQ1_0 MMVQ with packed DP4A

Assisted-by: OpenAI Codex
(cherry picked from commit 01fd952)
imaami pushed a commit to imaami/llama.cpp that referenced this pull request Oct 10, 2026
…gml-org#148)

* ggml: add PTQ1_0, Prism ternary at group 128 (1.75 bpw)

Upstream TQ1_0 packs ternary weights base-3 at 5 trits per byte, but carries a
single fp16 scale per 256 weights. The ternary checkpoints this targets carry a
scale per 128, so a 256-wide scale has to discard one of the two group scales it
straddles. Measured on a ternary checkpoint of this family: every trit survives and the zero pattern
is preserved exactly, but the smaller-alpha group of each block is reconstructed
at the larger alpha, giving 6.43% weight error that passes into activations at
full strength because it is multiplicative on the weight rather than noise.

PTQ1_0 keeps TQ1_0's trit packing and our group of 128:

  qs[24] + qh[2] + fp16 d = 28 bytes / 128 weights = 1.7500 bpw

against PQ2_0's 34 bytes = 2.1250 bpw, so 17.6% smaller with no loss of
information: PQ2_0 spends two bits on a value carrying log2(3) = 1.585 bits.

test-quantize-fns reports ptq1_0 identical to pq2_0 on both metrics, absolute
quantization error 0.008678 and dot product error 0.141111, versus tq1_0's
0.008681 and 0.141345. A round trip of real folded ternary weights is
bit-identical to the PQ2_0 reconstruction, so the only error either format
carries is the shared fp16 scale rounding.

A distinct type id (143) rather than changing TQ1_0 in place, for the same reason
PQ2_0 is distinct from upstream's group-64 Q2_0: TQ1_0 is a wire format, and
reinterpreting its block width would silently misread every existing TQ1_0 gguf.

TQ1_0's qs staging is fixed at 32-then-16 bytes, which cannot cover 24, so the
stages are generalised to 32/16/8. At TQ1_0's 48-byte qs that reduces to exactly
its original behaviour.

Scope: codec, ggml traits, CPU vec_dot against Q8_0, and the ftype plumbing so
llama-quantize can target it. The vec_dot decodes a block to element order before
the dot, sharing the traversal with dequantize so the two cannot drift; it is
generic C on every arch, with no SIMD path yet. CUDA, Metal and Vulkan kernels,
and the repack gemv/gemm paths, are not implemented.

* ggml: wire PTQ1_0 into quantize dispatch, ftype map and row validation

Three plumbing gaps the traits entry alone did not cover, each of which failed
end-to-end quantization in a different way:

  ggml_quantize_chunk   - without a dispatch case the returned byte count did not
                          match the row size and GGML_ASSERT(result == nrows *
                          row_size) aborted a worker thread mid-tensor, leaving a
                          truncated output file behind.
  ggml_ftype -> wtype   - the ftype could not resolve to a ggml type.
  validate_row_data     - "invalid type 143", so quantization refused the result
                          it had just produced.

Verified end to end on a 1.7B ternary model with the embedding and output tensors
pinned to f16 in both runs, so only the quantized tensors differ:

  quantized tensors  PQ2_0 357.47 MiB -> PTQ1_0 294.47 MiB, 17.62% smaller
                     (1.75/2.125 bpw predicts 17.65%)
  perplexity, 4 chunks at ctx 512, identical to every printed digit:
                     per chunk 11.3796 / 14.7182 / 14.5014 / 12.6944 for both,
                     final 12.6944 +/- 1.12596 for both

The perplexity run goes through the new CPU vec_dot, so that path is exercised
rather than only the codec.

* metal: PTQ1_0 kernels — correct, but 4.2x slower decode than PQ2_0

Adds the Metal path for PTQ1_0: an element accessor for the base-3 layout, both
dequantize entry points, a mat-vec kernel, mul_mm and mul_mm_id instantiations
for f32 and f16, get_rows, the simdgroup constants and both pipeline-selection
switches. Also enumerates PTQ1_0 in test-backend-ops, which otherwise silently
skipped the new type and reported a clean pass.

Correct: 1251/1251 MUL_MAT tests pass on Apple M5 Pro. End to end on
a 1.7B ternary model the Metal perplexity is identical to PQ2_0 to every printed
digit, 12.6935 +/- 1.12567 for both.

Slow, and the reason is structural. Measured on M5 Pro:

                    PQ2_0            PTQ1_0
  pp128        4505 tok/s       2590 tok/s   0.57x
  tg32          182.5 tok/s      43.6 tok/s   0.24x

Base-3 packing makes element order non-positional, so a thread owning 16
contiguous weights cannot index bytes directly, and threads owning different trit
indices reload the same bytes. Hoisting the trit factor out of the inner loop for
spans below element 80 took decode from 29.8 to 43.6 tok/s, but the remaining gap
needs the thread mapping changed so one thread consumes all five trits of a byte
it loads once, instead of five threads each loading it for one trit.

This reproduces what the earlier TQ1_0 work already found on other backends:
base-3 is ALU-bound rather than bandwidth-bound, and the packing win does not pay
for itself at decode without that restructure. The 17.6% file-size reduction is
real and lossless; the speed is not there yet.

* metal: PTQ1_0 decode 29.8 -> 165.3 tok/s, now 0.89x of PQ2_0

Four changes, each measured on Apple M5 Pro against a 1.7B ternary model, with
MUL_MAT staying 1251/1251 and Metal perplexity identical to PQ2_0 throughout:

  1. byte-owning threads         29.8 -> 136.4   a thread now consumes all five
     trits of a byte it loads once, instead of eight threads each reloading the
     same qs bytes for one trit index; the block's 26 bytes are read once total
  2. y staged in registers      136.4 -> 143.5   y was being re-read from device
     memory once per row; it is now gathered once per block and reused, with the
     ternary offset folded into a single sumy subtraction
  3. N_R0 8 -> 4                143.5 -> 163.8   rows-per-thread was the real
     limiter: 16 rows gives 94 tok/s, 8 gives 144, 4 gives 164, 2 gives 163
  4. balanced qh                163.8 -> 165.3   qh's 8 elements went to threads
     0 and 1 only, so those did 19 elements while the rest did 15 and the whole
     simdgroup waited; one element per thread makes it 16 each and drops yl to 16

Trit extraction is the base-3 remainder recurrence, t = (v*3)>>8 with
v = (v*3)&0xFF, two integer ops per trit with no table. A 256-entry lookup was
tried and is not better for decode: it adds a dependent load per byte, 26 extra
per block against PQ2_0's 32 total loads. It does help the mul_mm path, which
must produce 16 contiguous elements and cannot use the byte-owning mapping, so
dequantize keeps the table.

Final, PQ2_0 vs PTQ1_0 on M5 Pro:

  pp128   4541 -> 3998 tok/s   0.88x
  tg32     186 ->  165 tok/s   0.89x
  size    357 ->  294 MiB      17.6% smaller, and lossless

Prefill's remaining gap is structural: mul_mm's dequantize contract is 16
contiguous elements, so five threads still touch the same 16 bytes for different
trit indices. Closing it needs mul_mm itself to stage a decoded block in
threadgroup memory, which is a larger change than this.

* cuda: PTQ1_0 dequantize and MMVQ paths — NOT COMPILED, no toolchain here

Adds the CUDA surface for PTQ1_0, mirroring PQ2_0: type traits, a device trit
accessor, the float2 dequantize entry point, the six dequant dispatch sites in
convert.cu, get_rows, the MMVQ dot with its VDR constant and three dispatch
sites, and both supports_op type lists.

**This code has never been compiled or executed.** The machine it was written on
is an Apple M5 Pro with no CUDA toolchain, so nvcc was unavailable. It must be
built and run on a CUDA host before anyone relies on it.

What *is* verified is the part where a bug would actually hide. The device
accessor's element mapping is pure integer logic, so it was transcribed verbatim
to the host and checked against the CPU codec's own traversal over 2,560,000
element positions across 20,000 random blocks: zero mismatches. That check is
kept as tests/test-ptq1_0-element-map.cpp so it can be rerun.

Trit extraction uses the same base-3 remainder recurrence as the Metal path,
t = (v*3)>>8 with v = (v*3)&0xFF. The MMVQ dot gathers four trits at a time and
packs them into an int as signed int8 lanes so accumulation still goes through
dp4a, since base-3 packing leaves no byte-aligned run inside a 32-element chunk.

MMQ is deliberately not implemented. Types without it fall back to dequantize
plus cuBLAS for prefill, which is correct if not optimal, and writing an MMQ
tile loader blind against tile layouts I cannot test would be worse than leaving
the fallback in place.

* metal: tune PTQ1_0 to N_SG=1, and record what optimising it ruled out

N_R0=4, N_SG=1. Decode lands at 162-166 tok/s across runs against PQ2_0's 186,
so 0.87-0.89x; the spread between N_SG 1 and 2 is inside run-to-run noise
(+/- 3.4 on a single measurement).

Five further optimisations were tried and MEASURED, and four of them lost. Kept
here so nobody spends the same day twice:

  256-entry trit lookup table       142.1  vs 143.5 recurrence   no decode gain
                                    (helps mul_mm, which keeps it)
  independent pow3 extraction       159.8  vs 166.0 recurrence   WORSE
  contiguous byte ownership         162.0  vs 165.3 scattered    WORSE
  N_R0 = 3 / 5 / 6                  129.8 / 156.7 / 149.6        all worse than 4
  N_SG = 8                          161.1                        worse than 1-2

What that rules out. The lookup table shows decode is not bound by trit
arithmetic. The pow3 variant shows it is not bound by the recurrence's five-deep
serial dependency either -- four rows per thread already supply enough
independent work, so fewer ops beat more ILP. Contiguous byte runs made it worse
because thread 5 straddles the qs 16/8 chunk boundary, and the resulting per-byte
branch cost more than consolidating the loads saved.

Where the remaining 11% actually lives, per 128 weights:

  PQ2_0   128 x (shift, mask, cvt, fma)                = 512 ops, 34 B read
  PTQ1_0  128 x (mul, shift, cvt, fma, mask-for-next)  = 640 ops, 28 B read
          ALU 1.25x, bytes 0.82x

A purely ALU-bound kernel would sit at 0.80x and a purely bandwidth-bound one at
1.21x. Measured 0.89x sits between them, which is about where this instruction
and byte mix should land. Extracting a base-3 digit is inherently a multiply
where a 2-bit field is a shift, so this gap is the price of packing at the
1.585-bit information limit rather than on a 2-bit boundary, not an
implementation defect.

The one lever left with a real mechanism behind it is prefill, not decode. In
decode each row has its own weights so there is nothing to share, but mul_mm
reuses a weight tile across many output columns, and its dequantize contract
forces 16 contiguous elements, so five threads still touch the same 16 bytes.
Staging a cooperatively decoded block in threadgroup memory would remove that
redundancy outright. Prefill is at 0.87x (3946 vs 4492).

Perplexity remains identical to PQ2_0 at 12.6935 +/- 1.12567, MUL_MAT 1251/1251.

* metal, cpu: close PTQ1_0 type-list gaps, add the missing mul_mv_ext r1_5

Self-review compared every switch that names PQ2_0 against those naming PTQ1_0
and found the new type absent from ten support enumerations: seven in
ggml-cpu/ops.cpp, including ggml_compute_forward_get_rows_f32, one in
ggml-metal-ops.cpp and two in ggml-metal-device.m. PTQ1_0 is traits-compatible
with PQ2_0 there -- same block size, same to_float and from_float shape -- so it
belongs in each.

Closing those gaps then exposed a real defect. Adding the type to the Metal
support lists enabled the mul_mv_ext path for wider n, which immediately failed
with "kernel not found in any metal library" for
kernel_mul_mv_ext_ptq1_0_f32_r1_5: PQ2_0 instantiates r1_2 through r1_5 and only
r1_2 through r1_4 had been written, because the grep that enumerated them was
truncated by head. Instantiating r1_5 fixes it, and the instantiation set is now
derived from PQ2_0's rather than transcribed.

Worth noting the earlier 1251/1251 passes were not wrong, they were narrow: with
the type missing from the support lists the wider-n path was never selected, so
the absent kernel could not be reached. The gap and the defect concealed each
other.

After: MUL_MAT 1251/1251 on M5 Pro, Backend MTL0 OK, Metal perplexity identical
to PQ2_0 at 12.6935 +/- 1.12567, decode 165 tok/s and prefill 3947.

* tests: verify the CUDA MMVQ dot numerically on the host

The CUDA path still cannot be compiled here, but its arithmetic can be checked.
This stubs the three intrinsics the kernel uses -- __dp4a, __low2float and the
4-byte int load -- transcribes vec_dot_ptq1_0_q8_1 and the device trit accessor
verbatim, and compares them against a float reference built by dequantising the
block and the q8_1 activations independently.

Result over 5000 random weight blocks with random q8_1 activations:

  exact integer-accumulator checks   20000, mismatches 0
  error / sum of term magnitudes     2.399e-08

The integer test is the one that matters: the kernel accumulates in int via dp4a
before scaling, so if the trit extraction, the int8 lane packing or the chunk-to-
q8_1 pairing were wrong, that accumulator would differ. It does not, on any of
the 20000 chunks.

A first pass reported 7.062e-05 "relative error" and looked like a failure. That
was cancellation: the reference total is a signed sum that can land near zero, so
dividing by it inflates the ratio. Measured against the sum of term magnitudes
instead, which cancellation cannot distort, the error is 2.4e-08, i.e. float32
rounding of the four per-chunk products.

Together with tests/test-ptq1_0-element-map.cpp this leaves only compilation
unproven for the CUDA path, not correctness of its math.

* cuda: move ptq1_0_trit to common.cuh so vecdotq.cuh can see it — BUILDS NOW

First compile of the CUDA path, on an RTX 5090 with CUDA 12.8 and
CMAKE_CUDA_ARCHITECTURES=120, failed with

  vecdotq.cuh(822): error: identifier "ptq1_0_trit" is undefined

The accessor was defined in dequantize.cuh, which vecdotq.cuh does not include.
PQ2_0's dot never needed a shared helper -- it decodes 2-bit fields inline with
byte_perm -- so nothing in the file it was mirrored from exposed the dependency.
Both headers include common.cuh, so the helper belongs there.

Verified on the 5090 after the fix:

  test-backend-ops -o MUL_MAT   1283/1283 passed, Backend CUDA0: OK
                                45 ptq1_0 cases OK, 0 failures
  host element-map test         2,560,000 positions, 0 mismatches
  host MMVQ dot test            20,000 integer checks, 0 mismatches

The two host tests were already green before this, which is the point worth
recording: they verified the arithmetic and could not have caught a missing
declaration. Compilation was the only gate that would find this, and the earlier
commit saying the CUDA path had never been built was accurate about the risk.

* vulkan: PTQ1_0 support, mirrored from Q1_0 not Q2_0 — UNTESTED as committed

Adds the Vulkan path for PTQ1_0: the block struct and QUANT_K defines, the trit
accessor plus dequantize/dequantize4/get_dm, the mul_mm load branch, a standalone
dequant shader, the shader-generator registration, and 16 pipeline sites in
ggml-vulkan.cpp mirrored from Q1_0's.

Mirrored from Q1_0 deliberately. Q1_0 is type 41 at group 128 with correct Vulkan
kernels; Q2_0 in this tree is group 128 in ggml-common.h but its Vulkan side still
declares QUANT_K_Q2_0 64, because upstream's group-64 kernels were merged over a
group-128 type and only some of the GLSL was re-derived. Pattern-matching off Q2_0
would have inherited that. Q1_0 also has no MMVQ entry, so this follows the same
dequantize-based path rather than inventing one.

One divergence from Q1_0 worth naming: PTQ1_0 puts the scale LAST in the block
(qs[24], qh[2], then d) where Q1_0 puts d first. The GLSL struct mirrors the C
field order exactly. Getting that wrong misindexes every block silently instead of
failing, which is the same class of error as the Q2_0 breakage above.

Not wired, and it is a real gap rather than an oversight: on-device quantization
(cpy_f32_quant, set_rows, cpy_quant_f32). Those need a base-3 ENCODER in GLSL,
which is a separate piece of work and is not needed to run a model -- weights are
quantized offline by llama-quantize.

**This has not been compiled or run.** There was no Vulkan toolchain on the
machine it was written on. It is pushed so it can be built and tested on a GPU
box, and it should be treated as unverified until test-backend-ops says otherwise.

* cuda: PTQ1_0 MMVQ takes the whole block — measured, and still 6-9x slower

Benchmarked the CUDA path for the first time. It is correct and slow, and the
numbers matter more than the change: us/run on a 4090 at m=4096, k=14336, against
pq2_0 on the same run.

        n=1     n=2     n=3     n=8    n=512
  q1_0   8.88    9.82   13.05   30.14   225.4
  pq2_0  9.75   11.05   14.92   31.27   232.4
  ptq1_0 46.8    64.6    99.1   287.3   525.6

The per-chunk version asked "which byte holds element e" per element, a branch plus
a variable-length recurrence, and iqs differs per lane so the branch diverged. Taking
the whole 128-weight block per call (VDR 1 -> 4) makes every lane walk the same 26
bytes in the same order. That bought about 9% at n=2, 70.6 -> 64.6, and no more.

So divergence was not the dominant cost, and the comment now says so. What remains is
load shape: this issues 128 scalar int8 reads of the q8_1 activations, one per element,
where pq2_0 issues eight dp4a calls over 4-byte words.

The fix is identified but deliberately not guessed at. Below element 80 the element
stride is 16 and 4 divides 16, so four consecutive elements are four consecutive BYTES
at the same trit index. Four recurrences packed into one int would feed dp4a against a
4-byte q8_1 load, matching pq2_0's shape. That needs a build cycle to verify, and this
session has already shown twice -- on the CPU vec_dot and on the Metal mapping -- that
predictions about where GPU time goes are wrong about as often as they are right.

Correctness held throughout: test-backend-ops -o MUL_MAT 1283/1283 on both an RTX 5090
and an RTX 4090, Backend CUDA0 OK, 45 ptq1_0 cases OK and 0 bad, before and after.

Note n=512 is the cuBLAS dequantize path rather than MMVQ, and is 2.3x rather than 6-9x,
which is consistent with the problem being in the MMVQ load pattern specifically.

* vulkan: fix three build breaks — shared ptq1_0.glsl, skip coopmat2, drop cm2 pipelines

The Vulkan commit did not build. Three errors, one root cause each, all found by a
teammate on an Intel Arc B390 and independently by windows CI:

1. mul_mm_cm2.comp: 'dequantFuncA' undeclared. Adding the type to type_names in
   vulkan-shaders-gen.cpp auto-enrols it in coopmat2 generation, but
   dequant_funcs_cm2.glsl has no PTQ1_0 decoder (Q1_0 has six entries). That failed
   the whole Vulkan shader build, not just this type. Now skipped for ptq1_0, which
   falls back to the scalar and coopmat1 paths that are actually implemented.

2. mul_mm_funcs.glsl: 'ptq1_0_trit' no matching function. The helper lived in
   dequant_funcs.glsl; mul_mm.comp includes types/dot_product/mul_mm_id/mul_mm_funcs
   and never dequant_funcs.glsl. **This is the same bug as the CUDA one fixed an hour
   earlier, same helper, different backend**: defined in the dequantize chain, called
   from the matmul chain. Fixed the same way, with a shared header
   vulkan-shaders/ptq1_0.glsl behind an include guard, included from both. Not
   duplicated: two copies would have to stay in step with the CPU codec in
   ggml-quants.c, and a divergence there appears as wrong matmul results, never as a
   build error.

3. ggml-vulkan.cpp: 'matmul_ptq1_0_f16_cm2_len' undeclared. Registrations for cm2
   pipelines whose shaders no longer exist once (1) is fixed. Both removed, with a
   comment recording that the absence is deliberate. (1) and (3) had to be fixed
   together or one error just trades for the other.

Verified locally this time, which is the other half of the lesson: glslc, molten-vk,
vulkan-headers and vulkan-loader were already installed on the machine that wrote the
original commit. It was pushed unverified on the false assumption that no toolchain
was present, and a local build finds all three in minutes.

  -DGGML_VULKAN=ON            builds clean
  SPIR-V generated            1991 shaders, 54 of them ptq1_0, incl. coopmat1, no cm2
  test-backend-ops MUL_MAT    1009/1009, Backend Vulkan0: OK, no regression

That local run does NOT verify the kernel. MoltenVK reports every ptq1_0 case "not
supported", and it reports pq2_0 the same way (q1_0 gets 28 of 156), so this is an
Apple/MoltenVK coverage limit rather than a defect in the new type. Kernel correctness
comes from the Arc B390 run on the patched tree: 1009/1009 with 78 ptq1_0 cases
actually executed and 0 failures, on KHR_coopmat.

Still absent by design: MMVQ (no q8_1 pipelines, absent from should_use_mmvq),
coopmat2, and on-device quantization, which needs a base-3 encoder in GLSL.

* vulkan: make PTQ1_0 reachable, and guard the coopmat2 path

The PTQ1_0 pipelines were created but the type was absent from every
selection and support enumeration, so supports_op returned false, the
scheduler never offered MUL_MAT/MUL_MAT_ID/GET_ROWS to Vulkan, and the
generated shaders were unreachable. The build looked green while nothing
executed on the backend. Add the type alongside GGML_TYPE_Q1_0 in the
five pipeline getters and the two supports_op gates.

Adding it there alone is not safe, because PTQ1_0 is the only type in
those lists with no coopmat2 pipelines: dequant_funcs_cm2.glsl carries no
decoder for it, so vulkan-shaders-gen skips cm2 generation. The cm2 slots
are still allocated by vk_matmul_pipeline2's constructor, so the mm getter
would return a non-null pipeline whose l/m/s are all null, and the
caller's "mmp == nullptr" fallback would not fire; the mul_mat_id getter
would instead trip GGML_ASSERT(support_fp32acc). Both getters now return
nullptr when the cm2 slots are empty, which routes the caller to the
dequant + f16 matmul fallback it already implements. That path needs
ggml_vk_get_to_fp16, which is one of the gates opened above.

The cpy, SET_ROWS and DUP gates are deliberately left alone:
copy_to_quant.comp has no PTQ1_0 block, so quantizing to this type on
device is unimplemented and a refusal there is correct.

Verified on Intel Arc B390 (KHR_coopmat): ptq1_0 goes from 0 OK / 78
declined to 28 OK / 50 declined / 0 failures, matching q1_0 and q2_0 case
for case, byte-identical across two runs. The coopmat2 guard is reasoned
from the pipeline-creation structure and is not covered by that run,
which is a coopmat1 device; it has no coopmat2 hardware behind it yet.

* cuda: accelerate PTQ1_0 MMVQ with packed DP4A

Assisted-by: OpenAI Codex
(cherry picked from commit 01fd952)
Assisted-by: GitHub Copilot
imaami pushed a commit to imaami/llama.cpp that referenced this pull request Oct 10, 2026
fletto2 pushed a commit to fletto2/llama.cpp-classifier that referenced this pull request Oct 23, 2026
…ma.cpp 01fd952, ggml-org#148)

Ports the PTQ1_0 type (ggml type 143, llama ftype 143, 28-byte blocks of 128
ternary weights: base-3 trits as in TQ1_0, one fp16 scale per 128) from the
PrismML fork, so its Ternary Bonsai PTQ1_0 GGUFs load here. Ids match the
PrismML fork. Their PQ2_0 type (142), which the original commit builds on, is
not ported; Metal and Vulkan parts are left out.

Included: codec, CPU traits with the generic vec_dot against Q8_0 (aliased on
every architecture; no SIMD yet), quantize plumbing, the CUDA dequantize and
MMVQ paths from the original commit (not yet compiled here), and its tests.

Checked on CPU: test-quantize-fns passes (ptq1_0 dot error 0.141111, as in the
original); Ternary-Bonsai-2-2B-PTQ1_0.gguf (sha256 36061ad4...) gives PPL
31.82 against 31.79 for the same model's Q2_0 file on 2x512 tokens of held-out
news.
bong-water-water-bong referenced this pull request in 1bit-MONSTER/llama.cpp Oct 24, 2026
## Overview

Retain reusable IQ3_S metadata and Q5 headers/payloads across repeated work in HRX kernels, following the format-specific preload/fallback structure introduced in #148. This reduces repeated loads and decoding while preserving generic fallbacks and numerical operation order.

The IQ3_S metadata preload uses byte-aligned loads: the metadata at offset 106 in a 110-byte block cannot promise four-byte alignment. This fixes an alignment error found during integration.

## Scope

The hidden-2048 RMSNorm retained-input specialization was removed in `ba5cf74512097303b19f5518760ce9a78370fdb7`; `rmsnorm_binary_f32_f16.loom` exactly matches the PR baseline. Generic caller-parameterized RMSNorm unrolling is a separate workstream. This PR now changes only IQ3_S metadata and Q5_K header/payload reuse.

## Reproduced local benchmark results

Compared exact revised head `ba5cf74512097303b19f5518760ce9a78370fdb7` against `43b0ec2c41cc671cc0add797a4b8c0aae87b2f1a` (includes #148), on Radeon RX 7900 XTX (gfx1100), with the original pinned HRX `61c152ac4b40dd758803a2cbcd237184a8dfb669` SDK and ROCm/toolchain. The original baseline binary/SDK hashes were verified; the revised candidate was rebuilt with the original build options. All 27 original manifest model files were SHA256-verified.

- Clean run: October 21, 2026, 00:08:27–01:14:31 UTC; 756/756 fresh-process calls succeeded. 540 scored calls and 216 control calls cover 54 model/mode comparisons.
- Same original protocol: llama-bench pp512/tg128, 8 threads, batch 512, microbatch 512, full GPU offload, 5 inner repetitions per process. Default warmup enabled: a full 512-token prompt pass for prefill and one generated token for decode, outside measured repetitions. Five balanced ABBA blocks give 10 disjoint process pairs per model, with 4 baseline control pairs. Original deterministic model order.
- Seven decode gains (+0.73% to +1.71%) survive simultaneous 95% intervals across all 54 comparisons; Holm correction agrees. All seven are positive in both AB/BA order subsets and five-block sensitivity intervals. No prefill change or regression survives the same threshold. Three additional comparisons are nominal improvements only; all remaining results are inconclusive. Inconclusive does not establish equivalence.
- Same-arm adjacent control variation reached 2.67% for prefill and 2.74% for decode; maximum absolute before/after baseline drift was 1.36% and 0.90%, respectively. Effects below use paired log ratios, not comparison of unpaired aggregate means. Inner repeats are not independent observations.
- An earlier 241-call attempt (29 load failures) overlapped confirmed GPU activity from an independent MTP correctness investigation. It was excluded **in full**, with raw results retained. The full original schedule was restarted after both GPU workstreams confirmed release. All reported results come from the single clean restart; no individual scores were selected and no outliers removed. The shared exclusive GPU lock was held throughout scoring.

The same seven models improved in the earlier combined-patch measurement, with effects of similar magnitude. This is a reproduction of the reduced changeset's gains; separate-session differences do not isolate RMSNorm's contribution.

<details>
<summary>Full 27-model prefill/decode results for revised head (simultaneous 95% confidence intervals)</summary>

Rates are arithmetic means of process means. Percentage changes use paired log ratios; intervals use Bonferroni across 54 comparisons. AB/BA order, five-block sensitivity, controls, drift and Holm diagnostics were retained alongside raw measurements.

| Model | Mode | Baseline tok/s | Candidate tok/s | Paired delta | Simultaneous 95% CI |
|---|---|---:|---:|---:|---:|
| qwen3-30b-a3b-instruct-2507 | pp512 | 4661.02 | 4662.73 | +0.037% | [-0.288, +0.362]% |
| qwen3-30b-a3b-instruct-2507 | tg128 | 198.89 | 198.44 | -0.226% | [-1.078, +0.633]% |
| gemma-4-12b | pp512 | 2675.80 | 2675.59 | -0.008% | [-0.143, +0.128]% |
| gemma-4-12b | tg128 | 62.92 | 64.00 | +1.712% | [+1.453, +1.971]% |
| llama-3.1-8b | pp512 | 5039.77 | 5035.94 | -0.076% | [-0.312, +0.161]% |
| llama-3.1-8b | tg128 | 129.11 | 129.15 | +0.038% | [-0.066, +0.142]% |
| minicpm5-1b | pp512 | 29712.67 | 29596.55 | -0.393% | [-1.567, +0.795]% |
| minicpm5-1b | tg128 | 537.07 | 537.01 | -0.011% | [-0.702, +0.684]% |
| minicpm3-4b | pp512 | 5313.59 | 5300.23 | -0.256% | [-2.739, +2.290]% |
| minicpm3-4b | tg128 | 67.34 | 67.32 | -0.023% | [-0.665, +0.623]% |
| minicpm-v-4.6 | pp512 | 26316.86 | 26365.37 | +0.184% | [-0.742, +1.119]% |
| minicpm-v-4.6 | tg128 | 408.73 | 409.13 | +0.100% | [-0.174, +0.374]% |
| minicpm-v-4.6-thinking | pp512 | 26425.27 | 26560.66 | +0.514% | [-0.466, +1.503]% |
| minicpm-v-4.6-thinking | tg128 | 409.87 | 409.85 | -0.005% | [-0.290, +0.280]% |
| qwen3-0.6b | pp512 | 30620.85 | 30593.63 | -0.088% | [-2.153, +2.021]% |
| qwen3-0.6b | tg128 | 460.46 | 460.33 | -0.027% | [-0.602, +0.552]% |
| gemma-3-270m-it | pp512 | 52961.82 | 53586.24 | +1.181% | [-0.921, +3.328]% |
| gemma-3-270m-it | tg128 | 456.47 | 453.33 | -0.663% | [-4.186, +2.990]% |
| qwen3-1.7b | pp512 | 12439.81 | 12377.94 | -0.495% | [-2.034, +1.068]% |
| qwen3-1.7b | tg128 | 317.14 | 316.50 | -0.204% | [-0.766, +0.362]% |
| qwen3-4b | pp512 | 4723.80 | 4721.72 | -0.045% | [-1.007, +0.927]% |
| qwen3-4b | tg128 | 183.51 | 183.67 | +0.086% | [-0.311, +0.484]% |
| qwen3-4b-instruct-2507 | pp512 | 8508.20 | 8500.54 | -0.090% | [-0.814, +0.641]% |
| qwen3-4b-instruct-2507 | tg128 | 183.73 | 183.65 | -0.047% | [-0.728, +0.638]% |
| bonsai-8b | pp512 | 2571.80 | 2572.18 | +0.015% | [-0.363, +0.394]% |
| bonsai-8b | tg128 | 158.08 | 158.04 | -0.025% | [-0.345, +0.297]% |
| bonsai-4b | pp512 | 5004.24 | 5021.44 | +0.348% | [-1.306, +2.029]% |
| bonsai-4b | tg128 | 222.83 | 222.58 | -0.115% | [-1.236, +1.018]% |
| bonsai-1.7b | pp512 | 12405.81 | 12413.46 | +0.061% | [-0.977, +1.111]% |
| bonsai-1.7b | tg128 | 358.11 | 359.09 | +0.270% | [-1.203, +1.765]% |
| phi-4-mini-instruct | pp512 | 9842.45 | 9851.63 | +0.093% | [-0.217, +0.405]% |
| phi-4-mini-instruct | tg128 | 189.14 | 191.45 | +1.223% | [+0.922, +1.525]% |
| lfm2-1.2b | pp512 | 28715.64 | 28738.45 | +0.081% | [-1.036, +1.212]% |
| lfm2-1.2b | tg128 | 523.44 | 523.23 | -0.042% | [-0.239, +0.156]% |
| lfm2.5-1.2b-instruct | pp512 | 28544.30 | 28540.05 | -0.018% | [-4.134, +4.274]% |
| lfm2.5-1.2b-instruct | tg128 | 523.25 | 523.56 | +0.058% | [-0.323, +0.440]% |
| promptbridge-0.6b-alpha | pp512 | 34693.11 | 34681.71 | -0.041% | [-2.906, +2.907]% |
| promptbridge-0.6b-alpha | tg128 | 442.55 | 443.57 | +0.230% | [-0.228, +0.691]% |
| jan-nano-128k | pp512 | 8523.09 | 8522.00 | -0.013% | [-0.503, +0.479]% |
| jan-nano-128k | tg128 | 184.08 | 184.18 | +0.052% | [-0.692, +0.802]% |
| jan-v1-4b | pp512 | 8529.04 | 8543.25 | +0.167% | [-0.329, +0.665]% |
| jan-v1-4b | tg128 | 183.89 | 184.26 | +0.198% | [-0.374, +0.772]% |
| llama-3.2-1b-instruct | pp512 | 19935.02 | 19902.70 | -0.166% | [-2.545, +2.272]% |
| llama-3.2-1b-instruct | tg128 | 470.43 | 475.08 | +0.990% | [+0.764, +1.216]% |
| llama-3.2-3b-instruct | pp512 | 9236.47 | 9238.47 | +0.022% | [-0.387, +0.432]% |
| llama-3.2-3b-instruct | tg128 | 227.63 | 229.28 | +0.725% | [+0.501, +0.950]% |
| smollm3-3b-128k | pp512 | 8470.96 | 8477.20 | +0.073% | [-0.324, +0.472]% |
| smollm3-3b-128k | tg128 | 217.14 | 218.73 | +0.730% | [+0.558, +0.902]% |
| ministral-3-3b-instruct-2512 | pp512 | 11015.70 | 11014.01 | -0.015% | [-0.472, +0.444]% |
| ministral-3-3b-instruct-2512 | tg128 | 233.78 | 233.97 | +0.080% | [-0.492, +0.654]% |
| qwen3.5-0.8b | pp512 | 24610.85 | 24617.16 | +0.027% | [-1.608, +1.690]% |
| qwen3.5-0.8b | tg128 | 387.55 | 390.49 | +0.757% | [+0.400, +1.116]% |
| qwen3.5-2b | pp512 | 13809.41 | 13829.31 | +0.144% | [-0.301, +0.591]% |
| qwen3.5-2b | tg128 | 263.97 | 267.56 | +1.360% | [+1.003, +1.718]% |

</details>

## Correctness and CI provenance

For the revised head, the restored RMSNorm kernel was linked and compiled for gfx1100 (H2048,multiply,T9), both benchmark arms passed separate unscored loader/device smoke checks, and the diff passed whitespace checks. An initial smoke check failed to locate libomp because the historical build used the old workspace path; adding the original ROCm llvm/lib directory to both arms' library search path resolved it. No binary or SDK substitution was made.

No new full-model perplexity campaign or ggml-staging-automation run was requested or performed. The following evidence is historical and applies to combined commit `01d0a3ad5054231298806d547eae33c283336a70`, which included RMSNorm retention:

- [Full ggml-staging-automation CI — successful attempt 3](https://github.com/ROCm/ggml-staging-automation/actions/runs/38806373681/attempts/3).
- All 27 expected-pass manifest models passed unchanged local CI-equivalent perplexity on both arms: 108 HRX/Vulkan comparisons, 216 measurements; maximum ratio 1.00655 against threshold 1.10. Prefill c512/b512/ub512/32chunks; decode c512/b512/ub1/2chunks. Expected-fail/report-only models excluded as documented in the frozen manifest.
- Captured production/tail checks, alignment fixtures and 36/36 fallback checks passed. Focused checks 52/56 passed; four failures were the same inherited IQ3_S K2048/N256/T32 synthetic mismatch on both arms in normal/access modes, with all 8192 outputs bit-identical. The discrepancy remains unresolved; tolerances were not relaxed.

## Requirements

- Contributing guidelines reviewed; draft submitted for human review and ownership of the changes.
- AI usage disclosure: YES. Codex assisted with investigation, implementation, testing, statistical analysis, and drafting this PR under the contributor's direction.
jammm pushed a commit to jammm/llama.cpp that referenced this pull request Nov 19, 2026
…-org#148)

Load use optimization for scales etc that are re-used when dequantizing several 16x16 blocks destined for WMMA ops. Specifically, dense and paired gate/up tiled matmul currently reload Q5_K/IQ4_XS block metadata for each K32 group. This change loads it once per K256 block and retains it across the eight groups, explicitly inside each matmul kernel.

## Generic preload & dequantize helper functions?

This was tried, it ends up being pretty ugly. Each kernel really needs explicitly own what gets retained and for how long to reach peak performance and a generic solution pulls against that. Preloading exactly where and exactly what the kernel wants to when it wants to requires an `if/else` block for quantization types can get a little unwieldy but it all gets stripped out by the compiler.

## Validation

- Current inline implementation commit: `4e6fb071096d27af05298157d7d8469cdd329928`.
- Base: `hrx-graph-develop-v2` at `dbe1d6e1a27ea78e432f3da84778ecb591f196a6`.
- Local HRX SDK: `771711d49befd397f10c3c6deb66f1c5c89e5042`; pinned RX 7900 XTX (`gfx1100`).
- Current inline implementation rebuild passed; all 17 CPU-reference cases passed normally and with Loom access + HAL ASAN instrumentation.
- All 19 exact captured configurations (9 dense including fallbacks, 10 paired) compile to byte-identical native `.text` compared with the benchmarked template candidates. No performance rerun is claimed for this source-only refactor; the native-code comparison preserves the link to the recorded timings.
- Separate candidates previously passed 36 dense/16 gate native compile checks and 18 dense/20 gate exact captured-config checks. No spills; captured Qwen fallback machine code unchanged.
- All 30 baseline/dense/gate model perplexity runs matched printed estimates (five models, prefill and decode). These are independent-candidate results, not a combined performance claim.

## Direct kernel measurements

Actual Llama 3.2 3B production entry points/configurations, 512 tokens, original model weights and identical deterministic nonzero synthetic activations. Ten alternating before/after process pairs. Batch-normalized host queue-completion time per dispatch, batch16, binding ring8; compilation and warmup excluded. Speedup is before/after throughput; 95% intervals use paired log ratios.

| Kernel | Before | After | Speedup (95% CI) |
|---|---:|---:|---:|
| dense_q5 | 956.7 us | 868.0 us | +10.22% [+9.80, +10.65] |
| gate_q5 | 2303.0 us | 1928.9 us | +19.39% [+18.02, +20.79] |
| gate_iq4 | 2173.8 us | 1879.6 us | +15.65% [+15.14, +16.16] |

Dense shape K8192/N3072; paired shapes K3072/N8192. These differ in shape and epilogue, so this is not an isolation of the cause of their different gains.

## Independent model measurements

Original UD-Q4_K_XL models, pp512, ten alternating process pairs with five repetitions each, same GPU/toolchain. Per-model 95% intervals are exploratory and unadjusted. No outliers removed; pilots excluded. Columns compare each change independently against the baseline; gains must not be added together.

| Model | Dense change (95% CI) | Gate/up change (95% CI) |
|---|---:|---:|
| llama-3.2-1b-instruct | +1.14% [+0.14, +2.16] | +7.63% [+6.28, +9.00] |
| llama-3.2-3b-instruct | +0.44% [-0.03, +0.92] | +5.58% [+5.19, +5.98] |
| qwen3.5-0.8b | -0.21% [-0.83, +0.42] | +1.36% [+0.90, +1.81] |
| qwen3.5-2b | +0.23% [-0.36, +0.84] | +3.81% [+3.43, +4.20] |
| smollm3-3b-128k | +0.45% [+0.14, +0.75] | +4.46% [+4.14, +4.77] |

Every model exercises five affected Q5 dense residual dispatches and nine or ten affected paired Q5/IQ4 dispatches. Decode does not exercise these tiled reuse paths. Dense IQ4 has focused numerical/compiler coverage, not a model-level speedup claim. No broad split-count sweep or other-GPU performance claim.

## ggml-staging-automation

Current [ggml-staging-automation CI run 38642793413](https://github.com/ROCm/ggml-staging-automation/actions/runs/38642793413) is queued, with smoke benchmarks and perplexity enabled (`skip_benchmarks=[]`). Staging commit `ce208c65eda6a1ab75d978ed372fb90840d7033f` pins this PR's inline revision `4e6fb0710` and retains HRX `dbda3434868da87540e7e093314c3f4dca867930`. Staging uses a different SDK from the local timings, and no passing staging result is claimed yet.

The [earlier run 38635190536](https://github.com/ROCm/ggml-staging-automation/actions/runs/38635190536) targeted the superseded template commit and was canceled.

Local raw evidence is retained under `build/decoder-reuse-head-refresh/`: `timing/paired-summary.json`, `timing/evidence.txt`, `kernel-timing/kernel-summary.json`, `combined/correctness-{normal,access}.{json,log}`, and each arm's native reports. These workspace paths are provenance notes, not publicly accessible artifact links. The staging run supplies shareable CI evidence.
jammm pushed a commit to jammm/llama.cpp that referenced this pull request Nov 19, 2026
## Overview

Retain reusable IQ3_S metadata and Q5 headers/payloads across repeated work in HRX kernels, following the format-specific preload/fallback structure introduced in ggml-org#148. This reduces repeated loads and decoding while preserving generic fallbacks and numerical operation order.

The IQ3_S metadata preload uses byte-aligned loads: the metadata at offset 106 in a 110-byte block cannot promise four-byte alignment. This fixes an alignment error found during integration.

## Scope

The hidden-2048 RMSNorm retained-input specialization was removed in `ba5cf74512097303b19f5518760ce9a78370fdb7`; `rmsnorm_binary_f32_f16.loom` exactly matches the PR baseline. Generic caller-parameterized RMSNorm unrolling is a separate workstream. This PR now changes only IQ3_S metadata and Q5_K header/payload reuse.

## Reproduced local benchmark results

Compared exact revised head `ba5cf74512097303b19f5518760ce9a78370fdb7` against `43b0ec2c41cc671cc0add797a4b8c0aae87b2f1a` (includes ggml-org#148), on Radeon RX 7900 XTX (gfx1100), with the original pinned HRX `61c152ac4b40dd758803a2cbcd237184a8dfb669` SDK and ROCm/toolchain. The original baseline binary/SDK hashes were verified; the revised candidate was rebuilt with the original build options. All 27 original manifest model files were SHA256-verified.

- Clean run: October 21, 2026, 00:08:27–01:14:31 UTC; 756/756 fresh-process calls succeeded. 540 scored calls and 216 control calls cover 54 model/mode comparisons.
- Same original protocol: llama-bench pp512/tg128, 8 threads, batch 512, microbatch 512, full GPU offload, 5 inner repetitions per process. Default warmup enabled: a full 512-token prompt pass for prefill and one generated token for decode, outside measured repetitions. Five balanced ABBA blocks give 10 disjoint process pairs per model, with 4 baseline control pairs. Original deterministic model order.
- Seven decode gains (+0.73% to +1.71%) survive simultaneous 95% intervals across all 54 comparisons; Holm correction agrees. All seven are positive in both AB/BA order subsets and five-block sensitivity intervals. No prefill change or regression survives the same threshold. Three additional comparisons are nominal improvements only; all remaining results are inconclusive. Inconclusive does not establish equivalence.
- Same-arm adjacent control variation reached 2.67% for prefill and 2.74% for decode; maximum absolute before/after baseline drift was 1.36% and 0.90%, respectively. Effects below use paired log ratios, not comparison of unpaired aggregate means. Inner repeats are not independent observations.
- An earlier 241-call attempt (29 load failures) overlapped confirmed GPU activity from an independent MTP correctness investigation. It was excluded **in full**, with raw results retained. The full original schedule was restarted after both GPU workstreams confirmed release. All reported results come from the single clean restart; no individual scores were selected and no outliers removed. The shared exclusive GPU lock was held throughout scoring.

The same seven models improved in the earlier combined-patch measurement, with effects of similar magnitude. This is a reproduction of the reduced changeset's gains; separate-session differences do not isolate RMSNorm's contribution.

<details>
<summary>Full 27-model prefill/decode results for revised head (simultaneous 95% confidence intervals)</summary>

Rates are arithmetic means of process means. Percentage changes use paired log ratios; intervals use Bonferroni across 54 comparisons. AB/BA order, five-block sensitivity, controls, drift and Holm diagnostics were retained alongside raw measurements.

| Model | Mode | Baseline tok/s | Candidate tok/s | Paired delta | Simultaneous 95% CI |
|---|---|---:|---:|---:|---:|
| qwen3-30b-a3b-instruct-2507 | pp512 | 4661.02 | 4662.73 | +0.037% | [-0.288, +0.362]% |
| qwen3-30b-a3b-instruct-2507 | tg128 | 198.89 | 198.44 | -0.226% | [-1.078, +0.633]% |
| gemma-4-12b | pp512 | 2675.80 | 2675.59 | -0.008% | [-0.143, +0.128]% |
| gemma-4-12b | tg128 | 62.92 | 64.00 | +1.712% | [+1.453, +1.971]% |
| llama-3.1-8b | pp512 | 5039.77 | 5035.94 | -0.076% | [-0.312, +0.161]% |
| llama-3.1-8b | tg128 | 129.11 | 129.15 | +0.038% | [-0.066, +0.142]% |
| minicpm5-1b | pp512 | 29712.67 | 29596.55 | -0.393% | [-1.567, +0.795]% |
| minicpm5-1b | tg128 | 537.07 | 537.01 | -0.011% | [-0.702, +0.684]% |
| minicpm3-4b | pp512 | 5313.59 | 5300.23 | -0.256% | [-2.739, +2.290]% |
| minicpm3-4b | tg128 | 67.34 | 67.32 | -0.023% | [-0.665, +0.623]% |
| minicpm-v-4.6 | pp512 | 26316.86 | 26365.37 | +0.184% | [-0.742, +1.119]% |
| minicpm-v-4.6 | tg128 | 408.73 | 409.13 | +0.100% | [-0.174, +0.374]% |
| minicpm-v-4.6-thinking | pp512 | 26425.27 | 26560.66 | +0.514% | [-0.466, +1.503]% |
| minicpm-v-4.6-thinking | tg128 | 409.87 | 409.85 | -0.005% | [-0.290, +0.280]% |
| qwen3-0.6b | pp512 | 30620.85 | 30593.63 | -0.088% | [-2.153, +2.021]% |
| qwen3-0.6b | tg128 | 460.46 | 460.33 | -0.027% | [-0.602, +0.552]% |
| gemma-3-270m-it | pp512 | 52961.82 | 53586.24 | +1.181% | [-0.921, +3.328]% |
| gemma-3-270m-it | tg128 | 456.47 | 453.33 | -0.663% | [-4.186, +2.990]% |
| qwen3-1.7b | pp512 | 12439.81 | 12377.94 | -0.495% | [-2.034, +1.068]% |
| qwen3-1.7b | tg128 | 317.14 | 316.50 | -0.204% | [-0.766, +0.362]% |
| qwen3-4b | pp512 | 4723.80 | 4721.72 | -0.045% | [-1.007, +0.927]% |
| qwen3-4b | tg128 | 183.51 | 183.67 | +0.086% | [-0.311, +0.484]% |
| qwen3-4b-instruct-2507 | pp512 | 8508.20 | 8500.54 | -0.090% | [-0.814, +0.641]% |
| qwen3-4b-instruct-2507 | tg128 | 183.73 | 183.65 | -0.047% | [-0.728, +0.638]% |
| bonsai-8b | pp512 | 2571.80 | 2572.18 | +0.015% | [-0.363, +0.394]% |
| bonsai-8b | tg128 | 158.08 | 158.04 | -0.025% | [-0.345, +0.297]% |
| bonsai-4b | pp512 | 5004.24 | 5021.44 | +0.348% | [-1.306, +2.029]% |
| bonsai-4b | tg128 | 222.83 | 222.58 | -0.115% | [-1.236, +1.018]% |
| bonsai-1.7b | pp512 | 12405.81 | 12413.46 | +0.061% | [-0.977, +1.111]% |
| bonsai-1.7b | tg128 | 358.11 | 359.09 | +0.270% | [-1.203, +1.765]% |
| phi-4-mini-instruct | pp512 | 9842.45 | 9851.63 | +0.093% | [-0.217, +0.405]% |
| phi-4-mini-instruct | tg128 | 189.14 | 191.45 | +1.223% | [+0.922, +1.525]% |
| lfm2-1.2b | pp512 | 28715.64 | 28738.45 | +0.081% | [-1.036, +1.212]% |
| lfm2-1.2b | tg128 | 523.44 | 523.23 | -0.042% | [-0.239, +0.156]% |
| lfm2.5-1.2b-instruct | pp512 | 28544.30 | 28540.05 | -0.018% | [-4.134, +4.274]% |
| lfm2.5-1.2b-instruct | tg128 | 523.25 | 523.56 | +0.058% | [-0.323, +0.440]% |
| promptbridge-0.6b-alpha | pp512 | 34693.11 | 34681.71 | -0.041% | [-2.906, +2.907]% |
| promptbridge-0.6b-alpha | tg128 | 442.55 | 443.57 | +0.230% | [-0.228, +0.691]% |
| jan-nano-128k | pp512 | 8523.09 | 8522.00 | -0.013% | [-0.503, +0.479]% |
| jan-nano-128k | tg128 | 184.08 | 184.18 | +0.052% | [-0.692, +0.802]% |
| jan-v1-4b | pp512 | 8529.04 | 8543.25 | +0.167% | [-0.329, +0.665]% |
| jan-v1-4b | tg128 | 183.89 | 184.26 | +0.198% | [-0.374, +0.772]% |
| llama-3.2-1b-instruct | pp512 | 19935.02 | 19902.70 | -0.166% | [-2.545, +2.272]% |
| llama-3.2-1b-instruct | tg128 | 470.43 | 475.08 | +0.990% | [+0.764, +1.216]% |
| llama-3.2-3b-instruct | pp512 | 9236.47 | 9238.47 | +0.022% | [-0.387, +0.432]% |
| llama-3.2-3b-instruct | tg128 | 227.63 | 229.28 | +0.725% | [+0.501, +0.950]% |
| smollm3-3b-128k | pp512 | 8470.96 | 8477.20 | +0.073% | [-0.324, +0.472]% |
| smollm3-3b-128k | tg128 | 217.14 | 218.73 | +0.730% | [+0.558, +0.902]% |
| ministral-3-3b-instruct-2512 | pp512 | 11015.70 | 11014.01 | -0.015% | [-0.472, +0.444]% |
| ministral-3-3b-instruct-2512 | tg128 | 233.78 | 233.97 | +0.080% | [-0.492, +0.654]% |
| qwen3.5-0.8b | pp512 | 24610.85 | 24617.16 | +0.027% | [-1.608, +1.690]% |
| qwen3.5-0.8b | tg128 | 387.55 | 390.49 | +0.757% | [+0.400, +1.116]% |
| qwen3.5-2b | pp512 | 13809.41 | 13829.31 | +0.144% | [-0.301, +0.591]% |
| qwen3.5-2b | tg128 | 263.97 | 267.56 | +1.360% | [+1.003, +1.718]% |

</details>

## Correctness and CI provenance

For the revised head, the restored RMSNorm kernel was linked and compiled for gfx1100 (H2048,multiply,T9), both benchmark arms passed separate unscored loader/device smoke checks, and the diff passed whitespace checks. An initial smoke check failed to locate libomp because the historical build used the old workspace path; adding the original ROCm llvm/lib directory to both arms' library search path resolved it. No binary or SDK substitution was made.

No new full-model perplexity campaign or ggml-staging-automation run was requested or performed. The following evidence is historical and applies to combined commit `01d0a3ad5054231298806d547eae33c283336a70`, which included RMSNorm retention:

- [Full ggml-staging-automation CI — successful attempt 3](https://github.com/ROCm/ggml-staging-automation/actions/runs/38806373681/attempts/3).
- All 27 expected-pass manifest models passed unchanged local CI-equivalent perplexity on both arms: 108 HRX/Vulkan comparisons, 216 measurements; maximum ratio 1.00655 against threshold 1.10. Prefill c512/b512/ub512/32chunks; decode c512/b512/ub1/2chunks. Expected-fail/report-only models excluded as documented in the frozen manifest.
- Captured production/tail checks, alignment fixtures and 36/36 fallback checks passed. Focused checks 52/56 passed; four failures were the same inherited IQ3_S K2048/N256/T32 synthetic mismatch on both arms in normal/access modes, with all 8192 outputs bit-identical. The discrepancy remains unresolved; tolerances were not relaxed.

## Requirements

- Contributing guidelines reviewed; draft submitted for human review and ownership of the changes.
- AI usage disclosure: YES. Codex assisted with investigation, implementation, testing, statistical analysis, and drafting this PR under the contributor's direction.
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.

3 participants