OpenVINO™ is an open source toolkit for optimizing and deploying AI inference
C++ aicomputer-visiondeep-learningdeploy-aidiffusion-modelsgenerative-aigood-first-issueinferencellm-inferencenatural-language-processingnlpopenvinooptimize-aiperformance-boostrecommendation-systemspeech-recognitionstable-diffusiontransformersyolo
[GPU] Ternary (2-bit) FullyConnected via TernOCL, with Bonsai 2 27B support (#38460)
Evangelos Georganasf4e23bfdf1cc
diff --git a/.gitmodules b/.gitmodulesindex 178d8e17768..2f78919d66f 100644--- a/.gitmodules+++ b/.gitmodules@@ -98,3 +98,6 @@path = thirdparty/liburing/liburingurl = https://github.com/axboe/liburing.gitignore = dirty+[submodule "src/plugins/intel_gpu/thirdparty/TernOCL"]+ path = src/plugins/intel_gpu/thirdparty/TernOCL+ url = https://github.com/libxsmm/TernOCL.gitdiff --git a/src/plugins/intel_gpu/docs/ternocl_int2_architecture.md b/src/plugins/intel_gpu/docs/ternocl_int2_architecture.mdnew file mode 100644index 00000000000..57c91b75f1e--- /dev/null+++ b/src/plugins/intel_gpu/docs/ternocl_int2_architecture.md@@ -0,0 +1,311 @@+# TernOCL int2 FullyConnected — Architecture++How 2-bit (ternary) `FullyConnected` layers are executed by the TernOCL OpenCL+kernels inside the OpenVINO GPU plugin.++---++## 1. Overview++Ternary models store each weight as one of `{-1, 0, +1}` with one fp16 scale+per group of 128 along K. OpenVINO has no signed 2-bit type, so they are carried+in the IR as unsigned `u2` codes `{0,1,2}` with a scalar zero point of 1,+dequantized as `(code - 1) * scale`.++The implementation:++1. **At compile time** converts those constants once into the layout the+ kernels read, so inference performs no unpacking or reordering.+2. **At execution time** enqueues one OpenCL GEMM per layer on the plugin's own+ command queue, applying the fused post-op in the kernel epilogue and writing+ the output type the consumer wants.+3. **Per shape and M** selects a tile configuration from tuned tables.++The kernels come from the TernOCL kernel collection, which carries its own+standalone drivers, validation and tuning scripts. Two GEMM families read the+same packed weights:++| Family | Source | Math | Used for |+|---|---|---|---|+| **int2 x f16 up-convert** | `int2_fp16_upcvt/int2_fp16_upcvt.cl` | 2-bit weights dequantized to fp16 in registers (group scale folded in with integer ops), fp16 DPAS, fp32 accumulation, native fp16 activations | all M (default) |+| **int2 x int8 DPAS** | `int2_via_int2_x_int8_dpas/int2_int8_dpas.cl` | activations quantized to int8 per (row, 128-group), native s8 x s2 DPAS on the 2-bit codes, int32 accumulation, per-group rescale | M > 8 with `GPU_TERNOCL_INT2_INT8_PREFILL` (off by default) |++The int8 path is off by default because it changes the numerics. The released+ternary checkpoints are trained and fine-tuned with fp16 activations, so the+default up-convert path keeps them in fp16 and the model computes the way it was+designed. Quantizing activations to int8 makes prefill faster (TTFT at a 1k+prompt drops about 20% on Bonsai 2 27B) and stays within the standard error on+GSM8K (96.97% vs 96.89%), but its outputs are no longer those of the fp16 model.+Decode (M <= 8) always runs the up-convert GEMV.++Both kernel families share the epilogue (`common/epilogue.clh`); rotated-basis checkpoints add+the input transform `hadamard/hadamard_fwht.cl` in front of either.++| File | Role |+|---|---|+| `impls/ocl_v2/ternocl_int2/fully_connected_ternocl_int2.hpp` | Registration, acceptance rules, fused-chain -> epilogue mapping |+| `impls/ocl_v2/ternocl_int2/fully_connected_ternocl_int2.cpp` | Weights reorder request, program cache, tile tables, execution of both GEMM families |+| `impls/ocl_v2/ternocl_int2/ternocl_int2_weights_reorder.cpp` | Weights reorder `u2` -> `format::is_os_yx_isv16_ternary`, folded at build time (section 3) |+| `impls/ocl_v2/CMakeLists.txt` | Embeds the TernOCL sources (up-convert, int2 x int8, FWHT, epilogue) as chunked string literals at configure time |+| `thirdparty/TernOCL` | Submodule: [TernOCL](https://github.com/libxsmm/TernOCL) kernels, drivers, validation, tuning scripts |+| `plugin/transformations/fuse_hadamard_fc.cpp` | Folds the graph-level rotation of rotated-basis checkpoints into the FC (section 7) |+| `plugin/transformations/fuse_rms_rope.cpp` | Folds the per-head Q/K RMSNorm into RoPE when the rotation covers the whole head (Bonsai 1.7B-8B; Bonsai 2 27B's partial-rotary heads stay unfused). Controlled by `GPU_ENABLE_RMS_ROPE_FUSION` (default on) |+| `registry/fully_connected_impls.cpp` | Priority relative to oneDNN/OpenCL |+| `registry/reorder_impls.cpp` | Registers the weights reorder ahead of the stock reorders; it accepts only the TernOCL packed format and hands any other reorder to the stock CPU reorder when the CPU impl type is forced |+| `primitive_inst.cpp` | Lets `ternocl_int2` keep its fused chain under dynamic shapes (section 4) |++The impl needs only the plugin's OpenCL runtime (`GPU_RT_TYPE=OCL`).++---++## 2. Registration and acceptance++`TernoclInt2FCImplementationManager` (`impl_types::ocl`) is registered for+`FullyConnected` ahead of the oneDNN and stock OpenCL managers, for dynamic and+static shapes, when the plugin is built on the OpenCL runtime.++`validate_impl` accepts a node only when every assumption the kernels make+holds; anything else falls through to the existing paths unchanged:++- weights are a constant `u2` `[N, K]` with `K % 128 == 0` and `N % 16 == 0`+ (one lane per output column; the kernels clip partial tiles, so N is not padded)+- the decompression scales are `f16` with the physical layout `[K/128, N]`, which is+ what `prepare_quantization` produces for FC scales (`[N, K/128]` reordered to `fbyx`)+- the zero point is the scalar 1 (`decompression_zero_point_scalar`), i.e. the+ codes {0, 1, 2} are the ternary values {-1, 0, +1}+- activations are `f16`, a plain row-major `[M, K]` matrix without padding+ (`format::bfyx`); the output is `f16` or `f32`, row-major `[M, N]` without padding+- the fused chain maps onto one epilogue (`ternocl_int2_postop()`):++| Fused chain | Typical layer | `POSTOP` |+|---|---|---|+| none | | 0 |+| `swish`, then `eltwise prod` | gate_proj x up_proj | 1 |+| `eltwise sum` | o_proj, down_proj (residual add) | 2 |+| constant bias (same type as the output), nothing fused | GatedDeltaNet `in_proj_a` | 3 |+| `logistic` | GatedDeltaNet `in_proj_b` | 4 |++ and the eltwise operand is `f16`.++A node whose primitive carries a Hadamard input transform (section 7) is+rejected with an error rather than falling through, because no other+implementation applies the transform.++For models with `u2` weights on the OpenCL runtime (with `GPU_ENABLE_TERNOCL_INT2`, the default),+the pipeline always enables the existing gate/up horizontal FC fusion+(`FullyConnectedHorizontalFusion` with the SwiGLU split), which it otherwise+skips on some devices. The merged `[K, 2I]` int2 projection followed by the+SwiGLU primitive is the faster path, and it is required for rotated-basis+checkpoints: a separate `gate_proj` carries a fused chain none of the epilogues+covers, and its Hadamard input cannot fall back to another implementation.++---++## 3. Compile-time preparation++The weights are packed with OpenVINO's weights reorder mechanism, like the+blocked weight formats of the stock FC and convolution kernels:++- `create()` sets the impl's `WeightsReorderParams` from the `u2` weights layout to+ the same shape in `format::is_os_yx_isv16_ternary`.+- `post_optimize_weights` inserts that reorder in front of the FC, and+ `propagate_constants` folds it, so the packed weights are an ordinary constant of the+ program: it is freed with the compiled model, saved by `export_model` / the model+ cache like any other constant, and the source `u2` constant is left untouched+ (it is dropped when nothing else reads it). FCs on the same weights share one+ packed constant.+- `TernoclInt2WeightsReorderImplementationManager` executes the reorder on the host:+ it re-encodes `code - 1` to two's complement (`-1` as `0b11`), rejecting a code+ outside `{0, 1, 2}`, and packs 16 values per `uint32`, K-major: word `(k/16, n)`+ holds rows `16*(k/16) .. +15` of column n, row `16*kb+j` at bits `[2j, 2j+1]`.+ Both GEMM families read this layout: the up-convert kernels dequantize it, the+ int8 kernels feed the codes to the s8 x s2 DPAS as they are.++- **Scales**: read from the FC's scale input, whose `[K/128, N]` physical layout+ `prepare_quantization` already provides.+- **Hadamard signs** (rotated checkpoints): the `+-1` vector as `i8[K]` on the device,+ owned by the impl and rebuilt from the primitive when an exported model is loaded.+ The signs are part of the primitive's hash and equality, so an impl taken from the+ in-memory impl cache always carries the signs of the node that uses it.++Per-node scratch is allocated at execution and grown with M: the rotated+activation `f16 [M, K]` (rotated checkpoints) and, for the int8 prefill, the+activation scales `f16 [K/128, (M+31) & ~31]`.++The impl keeps no per-node buffers: weights and scales come from the node's+inputs, so one impl object can serve every node with equal `kernel_impl_params`.+`save()` / `load()` serialize its scalar state; kernels are rebuilt on first use+after a load.++---++## 4. Execution++```mermaid+flowchart TD+ A["execute_impl"] --> B["packed weights and scales from the node's inputs"]+ B --> C{"hadamard_block?"}+ C -->|yes| D["hadamard_fwht_1024: y = H(s*x)/32<br/>into a per-node scratch"]+ C -->|no| E+ D --> E{"M > 8 and<br/>GPU_TERNOCL_INT2_INT8_PREFILL?"}+ E -->|no| F["up-convert: pick launch class from M<br/>(build program on first use)"]+ F --> G["int2_fp16_upcvt_gemm / _gemm_mt<br/>(A, B, S, C, Other, Bias, M, N, K)"]+ E -->|yes| H["quant_a: SA = 127 / absmax<br/>per (row, 128-group)"]+ H --> I["int2_int8_gemm_mt<br/>(A, SA, B, S, C, Other, Bias, M, N, K)"]+ G --> J["epilogue in registers:<br/>POSTOP 0..4, f16 or f32 store"]+ I --> J+```++`M` is derived from the output shape, so one impl serves prefill and decode.+Kernels are launched through the plugin stream (`set_arguments` /+`enqueue_kernel`), so they take part in the normal in-order / out-of-order+event handling and cost no host synchronisation.++**Programs** are built with `clBuildProgram` on the engine's `cl_context`, once+per (source, option string), in a cache shared by the impls created on that+context and released with the last of them; each impl creates its `cl_kernel`+from them on first use of a launch class. Clones share the kernel+handles, like the stock OpenCL impls: OpenVINO clones cached impls on every+shape update.++**Fusion under dynamic shapes**: `primitive_inst::is_valid_fusion()` only+trusts fused eltwise ops on `impl_types::ocl` FCs whose kernel it knows and+otherwise silently executes an *unfused subgraph* (the FC plus separate+eltwise/activation primitives). `ternocl_int2` is whitelisted there; without it+the model runs every epilogue as a separate pass.++**Output type**: f32 logits are written directly (`-DOUT_F32`), the+accumulator is fp32 already.++---++## 5. Kernels++Each family is one program source, specialised with `-D` options. All GEMMs take+`POSTOP` (0..4) and `OUT_F32`; the shared epilogue (`common/epilogue.clh`)+computes SiLU-gate, residual add, bias and sigmoid (with an `x <= -10 -> 0`+clamp) on the fp32 accumulator before the store.++### 5.1 int2 x f16 up-convert (`int2_fp16_upcvt.cl`, default)++| Kernel | Used for | Options |+|---|---|---|+| `int2_fp16_upcvt_gemm` | GEMV, M <= 8 | `SGM` rows per sub-group (1/2/4/8), `NSG_N` sub-groups along N (work-group width `WGN = 16*NSG_N`), `LS` local k-slicing through SLM, `U` k-steps loaded ahead |+| `int2_fp16_upcvt_gemm_mt` | M > 8 | sub-group tile `MT_M x MT_N`, work-group `WG_M x WG_N` sub-groups, 256 GRF; B dequantized once per 16 columns and reused for all `MT_M/8` DPAS row blocks; 2D block I/O clips at the matrix edge so any M works |++### 5.2 int2 x int8 DPAS (`int2_int8_dpas.cl`, `GPU_TERNOCL_INT2_INT8_PREFILL`)++The weights are never unpacked: the 2-bit codes go straight into the s8 x s2+DPAS (`intel_sub_group_i8_i2_matrix_mad_k32`). Per 128-group `g` along K:++ SA[g, m] = 127 / absmax_{k in g} |A[m, k]|+ q[m, k] = sat_int8(A[m, k] * SA[g, m])+ C[m, n] = epi( sum_g float(sum_{k in g} q[m, k] * code(B[k, n])) * SB[g, n] / SA[g, m] )++| Kernel | Role | Options |+|---|---|---|+| `quant_a` | one sub-group per (row, 128-group): absmax reduction, writes `SA` into the per-node scratch | |+| `int2_int8_gemm_mt` | M > 8: quantizes each 8 x 128 A block to int8 in registers once and reuses it for all 16-column blocks of the tile (`QMODE=1`); B and `SB` are loaded once per group and reused for all 8-row blocks | sub-group tile `MT_M x MT_N`, work-group `WG_M x WG_N`, 256 GRF; 2D block I/O, any M |++The int8 activation quantization changes the numerics slightly, so greedy+outputs can differ from the default path at near-tie tokens; on Bonsai 2 27B the+GSM8K score stays within the evaluation's standard error of the default path.+The kernel collection also has an int8 GEMV (`int2_int8_gemv`) and an upfront+quantization mode (`QMODE=0`, int8 A written by `quant_a`); the plugin uses+neither, so decode is unchanged and no `[M, K]` int8 scratch is needed.++### 5.3 Hadamard input transform (`hadamard_fwht.cl`)+1024-block, the ten radix-2 stages as three radix-8 passes through SLM and a+final radix-2 pass that scales and stores, fp32 butterflies. Its output feeds+either GEMM family.++---++## 6. Configuration selection++`get_launch()` (up-convert) and `get_int8_launch()` (int8 prefill) map M to a+launch class and build its kernels on first use:++| M | Kernel | Tile |+|---|---|---|+| 1, 2, <= 4, <= 8 | up-convert GEMV, `SGM` = 1/2/4/8 | `gemv_tile(K, N)`: exact (K, N) entries, separate table for the integrated GPU |+| 9..16, 17..32, 33..63 | up-convert M-tiled | `mt_tile()`: one tile per M band and output width class (N <= 8192, < 65536, >= 65536), per GPU class |+| >= 64 | up-convert M-tiled | `mt_tile()`: exact (K, N) entries, per GPU class |+| > 8, with `GPU_TERNOCL_INT2_INT8_PREFILL` | `quant_a` + `int2_int8_gemm_mt` | `int8_tile()`: exact (K, N) entries per M band (<= 16, <= 32, < 64, >= 64), default tile per band |++The tiles are hard-coded tables in `fully_connected_ternocl_int2.cpp`, filled from+TernOCL's benchmark sweeps (`bench.sh`, `sweep_midm.sh`):++- **up-convert**: one set of tables for discrete Xe2 and one for integrated Xe2+ (selected from the device type). The decode GEMV (M = 1) has entries for the+ layer shapes of Bonsai 1.7B / 4B / 8B / 27B and CAT-Q 32B on both (CAT-Q 1.7B+ and 8B share the Bonsai shapes); the M-tiled GEMM is tuned on the 27B shapes;+- **int8 prefill**: one table, with entries for the Bonsai 27B layer shapes,+ tuned on discrete Xe2;+- any other shape uses a default tile per launch class: it runs correctly, but+ is not tuned.++New entries come from TernOCL's sweeps, which tune each tile on the standalone+kernels. With debug caps, `OV_VERBOSE=4` prints every built program and the tile chosen.++### 6.1 Other GPUs and new networks++The tables are keyed on the device type, not the architecture: integrated GPUs+(Lunar Lake, and Panther Lake / Nova Lake, Xe3 / Xe3P) use the Arc 140V+tables, discrete GPUs use the Arc Pro B70 tables. Any shape without an entry+gets the default tile of its launch class. Both run correctly, they are just+not tuned for that GPU or shape.++To tune a new GPU or network:++1. **List the FC shapes.** Run the model once with a debug-caps build and+ `OV_VERBOSE=3`; every `[ternocl-int2] create ... N=<N> K=<K> ...` line is one+ shape to tune.+2. **Build the standalone drivers** in the TernOCL checkout+ (`thirdparty/TernOCL`, with the oneAPI environment or `CXX=g++`): `make -C int2_fp16_upcvt` and, for int8 prefill,+ `make -C int2_via_int2_x_int8_dpas`. Each driver runs one kernel over+ >= 2 GiB of rotating weights, checks it against a host reference, and prints+ the device time as `Avg dev time`.+3. **Sweep each shape** (add `--no-validate` once a tile has passed validation):+ - decode GEMV (M = 1): `--wgn {16,32,64} --ls {1,2,4,6,8} --u {1,2}`, e.g.++ ```bash+ cd int2_fp16_upcvt+ for wn in 16 32 64; do for ls in 1 2 4 6 8; do for u in 1 2; do+ echo "wgn=$wn ls=$ls u=$u $(./build/int2_fp16_upcvt_ocl --m 1 --k $K --n $N \+ --wgn $wn --ls $ls --u $u --iters 50 --no-validate | grep 'Avg dev time')"+ done; done; done+ ```+ - M-tiled GEMM: `--mt-m/--mt-n/--wg-m/--wg-n` at M = 12, 20, 32, 48 (the+ M < 64 bands) and at a prompt length such as 1024; `sweep_mt.sh <K> <N> <M> <out>`+ does this for one shape and M;+ - int8 prefill: the same flags on `int2_int8_dpas_ocl`, per M band.++ Re-measure the best few tiles a few times and keep the median: integrated+ GPUs share memory bandwidth with the CPU and drift under sustained load.+4. **Add the winners** to `gemv_tile()`, `mt_tile()` or `int8_tile()` (the+ integrated or discrete table, or a new table selected from+ `device_info.arch`), then check the end-to-end tokens and speed with the+ benchmark from the Bonsai 2 guide.++---++## 7. Rotated-basis checkpoints (Hadamard input transform)++Bonsai 2 stores its ternary weights in a rotated basis: every folded+projection expects its input `x` replaced by `H_1024 (s * x) / 32`, per+1024-wide block along K with a fixed `+-1` sign vector `s`. In the IR this+arrives as `[Multiply(s)] -> Reshape(..., K/1024, 1024) -> MatMul(H) -> Reshape(..., K)`+in front of the compressed FC (produced by `tools/int2/bonsai2_gguf_to_ir.py`).++`FuseHadamardIntoFC` (registered after the horizontal FC fusion, so a merged+gate/up FC absorbs the shared rotation once) recognises the chain, verifies the+constant is the normalised Sylvester `H_1024`, rewires the FC to the original+activation and records `int2_hadamard_block` / `int2_hadamard_signs` in the+rt_info; the FC translator moves them onto the cldnn `fully_connected`+primitive (part of its hash and serialization). At execution the impl runs+`hadamard_fwht_1024` into a per-node scratch and points the GEMM at it.+The pass is registered only on the OpenCL runtime with TernOCL enabled, since no+other implementation applies a fused rotation; otherwise (and with+`GPU_ENABLE_HADAMARD_FC_FUSION=0` in debug-caps builds) the rotation stays in the graph.+`OV_VERBOSE=4` traces the match per FC.diff --git a/src/plugins/intel_gpu/docs/ternocl_int2_bonsai2_from_scratch.md b/src/plugins/intel_gpu/docs/ternocl_int2_bonsai2_from_scratch.mdnew file mode 100644index 00000000000..36ebb8961a1--- /dev/null+++ b/src/plugins/intel_gpu/docs/ternocl_int2_bonsai2_from_scratch.md@@ -0,0 +1,285 @@+# Bonsai 2 27B on the OpenVINO GPU plugin with the TernOCL int2 kernels — step by step++From an empty directory to Bonsai 2 27B decoding on an Intel Xe2 GPU (discrete+or integrated) through OpenVINO GenAI, with performance from `llm_bench` and+accuracy from `who_what_bench`. How the int2 `FullyConnected` path works is described in+[ternocl_int2_architecture.md](ternocl_int2_architecture.md).++---++## 0. What you need++| | |+|---|---|+| GPU | Intel Xe2, discrete (Arc Pro B-series) or integrated (Lunar Lake Arc 140V) |+| GPU runtime | Intel compute runtime with OpenCL — the int2 path runs on the plugin's **OpenCL** runtime |+| Compiler | GCC (tested with 14.3); Intel oneAPI `icx`/`icpx` also works, see the note in step 2 |+| Tools | CMake ≥ 3.26, Ninja, git, Python 3.11+ |+| Disk | ~160 GB: OpenVINO + GenAI build ~35 GB, Bonsai 1 27B checkpoint 51 GB + fp16 IR 51 GB (template, see step 3), Bonsai 2 GGUF 7.2 GB, final IR 7.2 GB |+| RAM | ≥ 64 GB on the machine that runs the exports (step 3 loads the 27B in fp16) |++The environment every command needs (put it in a file and `source` it):++```bash+# env.sh+export WORK=$HOME/ov-bonsai2+export OV_ROOT=$WORK/openvino+export TOOLS=$OV_ROOT/src/plugins/intel_gpu/tools/int2+export ZE_AFFINITY_MASK=0 # multi-GPU hosts: which GPU to use+```++and, for the GPU runs of step 5, the OpenVINO + GenAI build of step 2:++```bash+# genai.sh+source $WORK/env.sh+source $OV_ROOT/install/setupvars.sh+source $WORK/bench-venv/bin/activate+```++---++## 1. Download the sources++```bash+mkdir -p $WORK && cd $WORK+git clone https://github.com/openvinotoolkit/openvino.git openvino+cd openvino && git submodule update --init --recursive && cd .. # includes thirdparty/TernOCL+git clone --recursive https://github.com/openvinotoolkit/openvino.genai.git openvino.genai # includes openvino_tokenizers++# gguf-py of the PrismML llama.cpp fork: stock gguf does not know the PQ2_0 tensor type+git clone --depth 1 -b prism https://github.com/PrismML-Eng/llama.cpp llama.cpp-prism+```++The OpenCL kernels come from [TernOCL](https://github.com/libxsmm/TernOCL),+pinned as the submodule `src/plugins/intel_gpu/thirdparty/TernOCL`.++## 2. Build OpenVINO with GenAI, and the benchmark environment++OpenVINO is built with GenAI and OpenVINO Tokenizers as extra modules, so the+`openvino`, `openvino_genai` and tokenizer libraries come from one build. The+TernOCL sources are read from the submodule at configure time; set+`-DTERNOCL_ROOT=<dir>` only to build against another TernOCL checkout.++The Python environment for `llm_bench` and `who_what_bench` comes first, since+the build compiles the Python bindings for it:++```bash+source env.sh && cd $WORK+python3 -m venv bench-venv+for t in llm_bench who_what_benchmark; do+ bench-venv/bin/pip install -r openvino.genai/tools/$t/requirements.txt+done+bench-venv/bin/pip install --no-deps -e openvino.genai/tools/who_what_benchmark+bench-venv/bin/pip uninstall -y openvino openvino-tokenizers openvino-genai # use this build's packages instead+```++```bash+cd $OV_ROOT+cmake -B build -G Ninja \+ -DCMAKE_BUILD_TYPE=Release \+ -DCMAKE_INSTALL_PREFIX=$OV_ROOT/install \+ -DOPENVINO_EXTRA_MODULES=$WORK/openvino.genai \+ -DENABLE_PYTHON=ON -DPython3_EXECUTABLE=$WORK/bench-venv/bin/python \+ -DGPU_RT_TYPE=OCL -DENABLE_SYSTEM_OPENCL=OFF \+ -DENABLE_INTEL_CPU=ON -DENABLE_INTEL_NPU=OFF \+ -DENABLE_SAMPLES=OFF -DENABLE_TESTS=OFF \+ -DENABLE_OV_ONNX_FRONTEND=OFF -DENABLE_OV_PADDLE_FRONTEND=OFF -DENABLE_OV_PYTORCH_FRONTEND=OFF \+ -DENABLE_OV_TF_FRONTEND=OFF -DENABLE_OV_TF_LITE_FRONTEND=OFF -DENABLE_OV_JAX_FRONTEND=OFF+cmake --build build -j $(nproc) && cmake --install build+```++The CPU plugin runs the tokenizers. `ENABLE_SYSTEM_OPENCL=OFF` keeps GenAI's+OpenCL code on the bundled headers; mixing them with a newer system+`CL/opencl.hpp` fails to compile.++With `icx`/`icpx` instead of GCC, also pass `-DCMAKE_C_FLAGS=-fp-model=precise+-DCMAKE_CXX_FLAGS=-fp-model=precise`: their default fast floating-point model+rewrites the `double` division in `ov::Dimension` shape arithmetic as a+multiplication by the reciprocal, which rounds some exact quotients down (e.g.+49 / 49 → 0). Reshapes with a `-1` then fail at run time for about one prompt+length in five ("Non-'-1' output dimensions do not evenly divide the input dimensions").+Also pass `-DENABLE_XGRAMMAR=OFF` (GenAI's xgrammar dependency does not link with+`icpx`; it only serves structured output), and source the oneAPI environment+before running, for the compiler runtime libraries. On an Arc Pro B70 the icx+build generates the same tokens as GCC, with a ~10% shorter first token and the+same decode speed.++```bash+source $WORK/genai.sh+python -c "import openvino as ov, openvino_genai; print(ov.get_version(), ov.Core().available_devices)" # ... ['CPU', 'GPU']+```++Python side of the model preparation (steps 3-4; no GPU, no OpenVINO build+needed — it uses the pip wheels in a separate venv):++```bash+cd $WORK+python3 -m venv venv && ./venv/bin/pip install openvino openvino-tokenizers numpy pyyaml+./venv/bin/pip install "optimum-intel[openvino]==2.1.0" "transformers==5.2.0" # step 3 only+```++## 3. Get the graph template: Bonsai 27B (1st generation) IR++Bonsai 2 27B ships only as GGUF and has *exactly* the Qwen3.5-27B architecture+of Bonsai 27B. Instead of rebuilding a 54 GB dense checkpoint and re-exporting,+the converter reuses the Bonsai 27B IR as the graph and swaps every weight in+from the GGUF (step 4). So the Bonsai 27B IR is a one-time prerequisite; if you+already have `bonsai27b-u2/` skip to step 4.++```bash+cd $WORK+./venv/bin/hf download prism-ml/Ternary-Bonsai-27B-unpacked --local-dir bonsai27b-hf # 51 GB, 12 safetensors shards++# fp16 export; the 27B is a VLM, so the task is image-text-to-text and it produces several models+./venv/bin/optimum-cli export openvino --model bonsai27b-hf \+ --task image-text-to-text --weight-format fp16 bonsai27b-fp16 # needs ~60 GB RAM++# rewrite the 497 ternary MatMuls as u2 codes + fp16 group scales (exact: the weights already are ternary)+./venv/bin/python $TOOLS/quantize_ir_ternary.py \+ --in bonsai27b-fp16/openvino_language_model.xml \+ --out bonsai27b-u2/openvino_model.xml+# expected: "rewriting 497 MatMul weights" ... "weights 47.72 GiB -> 6.34 GiB"+```++The converter of step 4 uses `bonsai27b-u2/openvino_model.xml` (+`.bin`) as its+graph; the GenAI model directory of step 4 takes the tokenizer, config and+vision encoders of `bonsai27b-fp16` and the processor configs of `bonsai27b-hf`.+Copy those (step 4) before deleting the fp16 language model+(`bonsai27b-fp16/openvino_language_model.*`, 51 GB) and the `bonsai27b-hf` shards.++## 4. Download Bonsai 2 27B and build its IR++```bash+cd $WORK+./venv/bin/hf download prism-ml/Ternary-Bonsai-2-27B-gguf Ternary-Bonsai-2-27B-PQ2_0.gguf --local-dir bonsai2-gguf # 7.2 GB++./venv/bin/python $TOOLS/bonsai2_gguf_to_ir.py \+ --gguf bonsai2-gguf/Ternary-Bonsai-2-27B-PQ2_0.gguf \+ --template-dir bonsai27b-u2 \+ --gguf-py llama.cpp-prism/gguf-py \+ --out-dir bonsai2-27b-u2+```++Needs ~16 GB RAM. Expected log:++```+[ir] ...PQ2_0.gguf: 851 tensors, GDN nv=48 nk=16 hd=128+[ir] hadamard H1024: 401 folded weights, sign widths [5120, 6144, 17408]+[ir] 497 linear MatMuls in template+[ir] weights: 401 ternary, 96 dense, 64 up_proj row folds+[ir] hadamard: 257 rotations inserted, 64 explicit sign multiplies, 129 norm folds+[ir] embedding: ternary 248320x5120, inverse-rotated on the device+[ir] wrote bonsai2-27b-u2+```++Output: `bonsai2-27b-u2/openvino_model.xml` + `.bin` (6.9 GB; u2 weights, fp16+scales, the H_1024 rotation in front of every folded projection) and+`bonsai2-27b-u2/openvino_text_embeddings_model.xml` + `.bin` (0.34 GB: the+ternary table as u8-packed codes + fp16 scales; the GPU gathers the rows,+dequantises them and applies the inverse rotation). How the rotation is executed+is described in section 7 of the architecture doc. Self-check of the mapping+(optional): run the tool on the Bonsai 1 GGUF with `--verify --template-embed+bonsai27b-fp16/openvino_text_embeddings_model.xml`; it must print `verify OK`+(every ternary matrix bit-identical to the template).++For GenAI, Bonsai 2 27B is a Qwen3.5 vision-language model (`VLMPipeline`):+its model directory holds the two Bonsai 2 models next to the Qwen3.5 tokenizer,+config and vision encoders of the template export (Bonsai 2 uses the same+vocabulary; the vision encoders are loaded but text-only prompts never run them):++```bash+mkdir -p bonsai2-27b-genai && cd bonsai2-27b-genai+ln -s ../bonsai2-27b-u2/openvino_model.xml openvino_language_model.xml+ln -s ../bonsai2-27b-u2/openvino_model.bin openvino_language_model.bin+ln -s ../bonsai2-27b-u2/openvino_text_embeddings_model.xml ../bonsai2-27b-u2/openvino_text_embeddings_model.bin .+ln -s ../bonsai27b-fp16/*.json ../bonsai27b-fp16/chat_template.jinja \+ ../bonsai27b-fp16/openvino_*tokenizer.* ../bonsai27b-fp16/openvino_vision_embeddings_* .+cp ../bonsai27b-hf/*processor_config.json . # the processor configs WWB loads for a VLM+cd ..+```++## 5. Run++```bash+source $WORK/genai.sh+```++### 5.1 Performance (`llm_bench`)++```bash+cd $WORK/openvino.genai/tools/llm_bench+python benchmark.py -m $WORK/bonsai2-27b-genai -d GPU \+ -p "Explain photosynthesis in two sentences." --disable_prompt_permutation -ic 256 -n 3+```++The warm-up iteration builds the OpenCL programs for the new shapes; the+average is over the following iterations. Arc Pro B70 (GCC build): 1st token+~100 ms, 2nd token 19.3 ms (52 tokens/s). The same command runs on integrated+Xe2. Batch-1 decode is partly host-bound, so the host CPU moves these numbers;+compare builds on one machine.++### 5.2 Accuracy (`who_what_bench`)++There is no fp16 Bonsai 2, so the reference is the same model on the stock+OpenVINO FC kernels; the score then measures what the TernOCL kernels change:++```bash+cd $WORK/openvino.genai/tools/who_what_benchmark+OV_GPU_ENABLE_TERNOCL_INT2=0 wwb --base-model $WORK/bonsai2-27b-genai --gt-data gt_stock.csv \+ --model-type visual-text-only --genai --device GPU # reference; the stock kernels run at ~2 tokens/s+wwb --target-model $WORK/bonsai2-27b-genai --gt-data gt_stock.csv \+ --model-type visual-text-only --genai --device GPU+```++### 5.3 Other ternary checkpoints (Bonsai 1.7B-8B, CAT-Q)++The same impl serves any ternary checkpoint; nothing above is specific to the+27B except the Hadamard rotation. A Qwen3-family checkpoint is a plain LLM for+GenAI (`LLMPipeline`). Export the fp16 IR, rewrite its weights and copy the+tokenizer and config files next to it:++```bash+cd $WORK+./venv/bin/optimum-cli export openvino --model <hf-checkpoint> \+ --task text-generation-with-past --weight-format fp16 <name>-fp16+./venv/bin/python $TOOLS/quantize_ir_ternary.py --in <name>-fp16/openvino_model.xml \+ --out <name>-u2/openvino_model.xml # CAT-Q: add --skip-n 151936 (lm_head stays 16-bit)+cp <name>-fp16/*.json <name>-fp16/openvino_*tokenizer.* <name>-u2/+```++Then `llm_bench` as in 5.1, and `wwb --model-type text` against `<name>-fp16`+(or against the stock kernels as in 5.2). Bonsai 8B on an Arc Pro B70: 168+tokens/s; WWB similarity 0.988 between TernOCL and the stock kernels, 0.77+between the ternary and the fp16 model (the stock kernels score the same 0.77).++## 6. Knobs that matter++GPU plugin options (`options.inl`); each can be passed as a compile property or+set through the environment as `OV_<NAME>`, e.g. `OV_GPU_TERNOCL_INT2_INT8_PREFILL=1`.+On/off values are `1`/`0`, `true`/`false`, `on`/`off` or `yes`/`no`.++| Option | Default | Effect |+|---|---|---|+| `GPU_TERNOCL_INT2_INT8_PREFILL` | 0 | `1`: prompts and batches (M > 8) on the int2 x int8 DPAS kernel (activations quantized to int8 per 128-group); same weights, GSM8K within the standard error of the default |+| `GPU_ENABLE_TERNOCL_INT2` | 1 | `0`: use the stock OpenVINO FC kernels instead of TernOCL (the Hadamard rotation then runs as graph ops and the gate/up merge follows the stock heuristic) |+| `GPU_ENABLE_HADAMARD_FC_FUSION` | 1 | debug-caps builds only; `0` leaves the Hadamard rotation as separate graph ops (slower) |+| `GPU_ENABLE_RMS_ROPE_FUSION` | 1 | `0` keeps the per-head Q/K RMSNorm as its own kernel instead of folding it into RoPE. No effect on Bonsai 2 27B, whose heads are only partly rotated |++With `-DENABLE_DEBUG_CAPS=ON`, `OV_VERBOSE=3` logs which FCs the TernOCL impl+accepts and how many rotations were fused ("fused 257 input rotations"), and+`OV_VERBOSE=4` adds every rejection reason and every OpenCL program it builds.++## 7. Troubleshooting++| Symptom | Cause / fix |+|---|---|+| `Segmentation fault` when Python exits, after all results are printed | a teardown race outside this path: it also occurs with upstream OpenVINO master and with TernOCL disabled; the results are complete |+| GenAI build: `CL_EXTERNAL_MEMORY_HANDLE_D3D11_TEXTURE_KHR` was not declared | system OpenCL C++ headers mixed with the bundled ones: configure with `-DENABLE_SYSTEM_OPENCL=OFF` |+| `Check '!chat_template.empty()' failed` (`llm_bench --apply_chat_template`) | the checkpoint has no chat template; drop the option or add `chat_template.jinja` before converting the tokenizer |+| `TernOCL kernel ... not found` at configure | the submodule is not checked out: `git submodule update --init src/plugins/intel_gpu/thirdparty/TernOCL` (or pass `-DTERNOCL_ROOT=<dir>`) |+| `ternocl int2: kernel build failed (...)` | the OpenCL compiler rejected the TernOCL source; the build log follows the message |+| `... carries a Hadamard input transform but the TernOCL impl rejected it` | an FC of the rotated model fell outside the impl's rules; the reason is in the message |+| `ModuleNotFoundError: yaml` from the converter | `pip install pyyaml` (gguf-py of the fork imports it) |+| converter: `need the PrismML llama.cpp fork's gguf-py` | pass `--gguf-py <fork>/gguf-py`; stock gguf lacks type id 142 (PQ2_0) |+| fluent nonsense output | wrong tokenizer for decoding (Bonsai 2 uses the Qwen3.5 vocabulary) — or a converter/mapping error: run `--verify` |diff --git a/src/plugins/intel_gpu/include/intel_gpu/primitives/fully_connected.hpp b/src/plugins/intel_gpu/include/intel_gpu/primitives/fully_connected.hppindex 8a80a4dc067..b7fec5d9e89 100644--- a/src/plugins/intel_gpu/include/intel_gpu/primitives/fully_connected.hpp+++ b/src/plugins/intel_gpu/include/intel_gpu/primitives/fully_connected.hpp@@ -182,6 +182,12 @@ struct fully_connected : public primitive_base<fully_connected> {input_info activation_precomputed_reduction = {"", 0};std::optional<float> decompression_zero_point_scalar;+ /// @brief Input pre-transform: blockwise normalised Walsh-Hadamard of size+ /// hadamard_block along K, after an optional per-element sign flip. Set by+ /// FuseHadamardIntoFC; only the TernOCL int2 implementation honours it.+ size_t hadamard_block = 0;+ std::vector<int8_t> hadamard_signs;+/// @brief Primitive dimension size.size_t input_size = 2;/// @brief Primitive weights rank.@@ -209,6 +215,8 @@ struct fully_connected : public primitive_base<fully_connected> {seed = hash_combine(seed, activation_precomputed_reduction.is_valid());seed = hash_combine(seed, decompression_zero_point_scalar.has_value());seed = hash_combine(seed, decompression_zero_point_scalar.value_or(0.0f));+ seed = hash_combine(seed, hadamard_block);+ seed = hash_combine(seed, hadamard_signs.size());return seed;}@@ -231,7 +239,8 @@ struct fully_connected : public primitive_base<fully_connected> {activation_scale.is_valid() == rhs_casted.activation_scale.is_valid() &&activation_zero_point.is_valid() == rhs_casted.activation_zero_point.is_valid() &&activation_precomputed_reduction.is_valid() == rhs_casted.activation_precomputed_reduction.is_valid() &&- decompression_zero_point_scalar.value_or(0.0f) == rhs_casted.decompression_zero_point_scalar.value_or(0.0f);+ decompression_zero_point_scalar.value_or(0.0f) == rhs_casted.decompression_zero_point_scalar.value_or(0.0f) &&+ hadamard_block == rhs_casted.hadamard_block && hadamard_signs == rhs_casted.hadamard_signs;}void save(BinaryOutputBuffer& ob) const override {@@ -260,6 +269,8 @@ struct fully_connected : public primitive_base<fully_connected> {} else {ob << false;}+ ob << hadamard_block;+ ob << hadamard_signs;}void load(BinaryInputBuffer& ib) override {@@ -290,6 +301,8 @@ struct fully_connected : public primitive_base<fully_connected> {} else {decompression_zero_point_scalar = std::optional<float>();}+ ib >> hadamard_block;+ ib >> hadamard_signs;}protected:diff --git a/src/plugins/intel_gpu/include/intel_gpu/primitives/rope.hpp b/src/plugins/intel_gpu/include/intel_gpu/primitives/rope.hppindex 79cca4931d3..e312741ef2a 100644--- a/src/plugins/intel_gpu/include/intel_gpu/primitives/rope.hpp+++ b/src/plugins/intel_gpu/include/intel_gpu/primitives/rope.hpp@@ -23,10 +23,14 @@ struct rope : public primitive_base<rope> {rope(const primitive_id& id,const std::vector<input_info>& inputs,const RoPE::Config& config,- size_t gather_rank = 0)+ size_t gather_rank = 0,+ bool fuse_rms_norm = false,+ float rms_epsilon = 0.0f): primitive_base(id, inputs),config(config),- gather_rank(gather_rank) {+ gather_rank(gather_rank),+ fuse_rms_norm(fuse_rms_norm),+ rms_epsilon(rms_epsilon) {OPENVINO_ASSERT((!config.support_2d_rope|| (config.support_2d_rope && config.is_chatglm)),"2D RoPE is currently only supported in Chatglm!");@@ -36,6 +40,9 @@ struct rope : public primitive_base<rope> {RoPE::Config config;size_t gather_rank = 0;+ // Set when a preceding per-head RMSNorm is folded into the RoPE kernel; input 3 is then gamma.+ bool fuse_rms_norm = false;+ float rms_epsilon = 0.0f;size_t hash() const override {size_t seed = primitive::hash();@@ -55,6 +62,8 @@ struct rope : public primitive_base<rope> {seed = hash_combine(seed, config.slice_start);seed = hash_combine(seed, config.slice_stop);seed = hash_combine(seed, gather_rank);+ seed = hash_combine(seed, fuse_rms_norm);+ seed = hash_combine(seed, rms_epsilon);return seed;}@@ -80,7 +89,9 @@ struct rope : public primitive_base<rope> {config.rotary_ndims == rhs_casted.config.rotary_ndims &&config.slice_start == rhs_casted.config.slice_start &&config.slice_stop == rhs_casted.config.slice_stop &&- gather_rank == rhs_casted.gather_rank;+ gather_rank == rhs_casted.gather_rank &&+ fuse_rms_norm == rhs_casted.fuse_rms_norm &&+ rms_epsilon == rhs_casted.rms_epsilon;}void save(BinaryOutputBuffer& ob) const override {@@ -102,6 +113,8 @@ struct rope : public primitive_base<rope> {ob << config.slice_start;ob << config.slice_stop;ob << gather_rank;+ ob << fuse_rms_norm;+ ob << rms_epsilon;}void load(BinaryInputBuffer& ib) override {@@ -123,6 +136,8 @@ struct rope : public primitive_base<rope> {ib >> config.slice_start;ib >> config.slice_stop;ib >> gather_rank;+ ib >> fuse_rms_norm;+ ib >> rms_epsilon;}};} // namespace cldnndiff --git a/src/plugins/intel_gpu/include/intel_gpu/runtime/format.hpp b/src/plugins/intel_gpu/include/intel_gpu/runtime/format.hppindex dc24d16e2a2..f49403b5742 100644--- a/src/plugins/intel_gpu/include/intel_gpu/runtime/format.hpp+++ b/src/plugins/intel_gpu/include/intel_gpu/runtime/format.hpp@@ -250,6 +250,9 @@ struct format {gi_yxs_os_yxsv2_osv16,giy_xs_os_xsv2_osv8__ao32,giy_xs_os_xsv2_osv16__ao32,+ is_os_yx_isv16_ternary, ///< u2 fully connected weights for the TernOCL int2 impl: K blocked by 16 into one+ ///< dword per (K/16, N), values re-encoded from codes {0,1,2} (zero point 1)+ ///< to 2-bit two's complement {-1,0,+1}format_num, ///< number of format typescustom, ///< means that this format is created based on custom format traits and may have no corresponding labeldiff --git a/src/plugins/intel_gpu/include/intel_gpu/runtime/internal_properties.hpp b/src/plugins/intel_gpu/include/intel_gpu/runtime/internal_properties.hppindex 73427718c91..5d739ff2562 100644--- a/src/plugins/intel_gpu/include/intel_gpu/runtime/internal_properties.hpp+++ b/src/plugins/intel_gpu/include/intel_gpu/runtime/internal_properties.hpp@@ -209,6 +209,10 @@ static constexpr Property<bool, ov::PropertyMutability::RW> disable_fc_swiglu_fustatic constexpr Property<bool, ov::PropertyMutability::RW> disable_gated_mlp_fusion{"GPU_DISABLE_GATED_MLP_FUSION"};static constexpr Property<bool, ov::PropertyMutability::RW> disable_fake_alignment{"GPU_DISABLE_FAKE_ALIGNMENT"};static constexpr Property<bool, ov::PropertyMutability::RW> moe_disable_fusion{"GPU_MOE_DISABLE_FUSION"};+static constexpr Property<bool, ov::PropertyMutability::RW> enable_ternocl_int2{"GPU_ENABLE_TERNOCL_INT2"};+static constexpr Property<bool, ov::PropertyMutability::RW> ternocl_int2_int8_prefill{"GPU_TERNOCL_INT2_INT8_PREFILL"};+static constexpr Property<bool, ov::PropertyMutability::RW> enable_hadamard_fc_fusion{"GPU_ENABLE_HADAMARD_FC_FUSION"};+static constexpr Property<bool, ov::PropertyMutability::RW> enable_rms_rope_fusion{"GPU_ENABLE_RMS_ROPE_FUSION"};static constexpr Property<bool, ov::PropertyMutability::RW> moe_use_micro_gemm_prefill{"GPU_MOE_USE_MICRO_GEMM_PREFILL"};static constexpr Property<bool, ov::PropertyMutability::RW> moe_use_gpu_mask_gen_prefill{"GPU_MOE_USE_GPU_MASK_GEN_PREFILL"};static constexpr Property<bool, ov::PropertyMutability::RW> moe_use_grouped_gemm_prefill{"GPU_MOE_USE_GROUPED_GEMM_PREFILL"};diff --git a/src/plugins/intel_gpu/include/intel_gpu/runtime/options.inl b/src/plugins/intel_gpu/include/intel_gpu/runtime/options.inlindex 1709bcfb1e5..b059c66aab9 100644--- a/src/plugins/intel_gpu/include/intel_gpu/runtime/options.inl+++ b/src/plugins/intel_gpu/include/intel_gpu/runtime/options.inl@@ -84,6 +84,9 @@ OV_CONFIG_RELEASE_INTERNAL_OPTION(ov::intel_gpu, moe_use_gpu_mask_gen_prefill, fOV_CONFIG_RELEASE_INTERNAL_OPTION(ov::intel_gpu, moe_use_grouped_gemm_prefill, true, "MoE 3GEMM: use a single OneDNN grouped matmul per GEMM layer for the prefill path. Takes priority over micro-kernel GEMM")OV_CONFIG_RELEASE_INTERNAL_OPTION(ov::intel_gpu, moe_batched_gemv_threshold, 32, "MoE 3-GEMM: token count (<=) that selects the batched GEMV decode path instead of the prefill path")OV_CONFIG_RELEASE_INTERNAL_OPTION(ov::intel_gpu, moe_disable_fusion, false, "Disable fusion of MoE subgraph to composite MoE operation")+OV_CONFIG_RELEASE_INTERNAL_OPTION(ov::intel_gpu, enable_ternocl_int2, true, "Enable/Disable the TernOCL implementation of FullyConnected with ternary (u2) weights; when disabled the stock kernels are used")+OV_CONFIG_RELEASE_INTERNAL_OPTION(ov::intel_gpu, enable_rms_rope_fusion, true, "Enable/Disable the pass which folds per-head Q/K RMSNorm into RoPE")+OV_CONFIG_RELEASE_INTERNAL_OPTION(ov::intel_gpu, ternocl_int2_int8_prefill, false, "TernOCL ternary FullyConnected: run M > 8 on the int2 x int8 DPAS GEMM, quantizing activations to int8 per 128-group")OV_CONFIG_RELEASE_INTERNAL_OPTION(ov::intel_gpu, record_replay, false, "Enable level-zero command list through record and replay for static models")OV_CONFIG_DEBUG_GLOBAL_OPTION(ov::intel_gpu, help, false, "Print help message for all config options")@@ -121,6 +124,7 @@ OV_CONFIG_DEBUG_OPTION(ov::intel_gpu, disable_post_ops_fusions, 0, "Disable fusiOV_CONFIG_DEBUG_OPTION(ov::intel_gpu, disable_horizontal_fc_fusion, false, "Disable pass which merges QKV projections into single MatMul")OV_CONFIG_DEBUG_OPTION(ov::intel_gpu, disable_fc_swiglu_fusion, false, "Disable pass which merges FC and SwiGLU ops")OV_CONFIG_DEBUG_OPTION(ov::intel_gpu, disable_gated_mlp_fusion, true, "Disable pass which fuses FC+SwiGLU to GatedMLP")+OV_CONFIG_DEBUG_OPTION(ov::intel_gpu, enable_hadamard_fc_fusion, true, "Enable/Disable the pass which folds a Hadamard input rotation into a ternary FullyConnected")OV_CONFIG_DEBUG_OPTION(ov::intel_gpu, disable_fake_alignment, false, "Disable fake alignment feature which tries to keep gpu friendly memory alignment for arbitrary tensor shapes")OV_CONFIG_DEBUG_OPTION(ov::intel_gpu, disable_memory_reuse, false, "Disable memory reuse for activation tensors")OV_CONFIG_DEBUG_OPTION(ov::intel_gpu, disable_runtime_skip_reorder, false, "Disable skip reorder optimization applied in runtime")diff --git a/src/plugins/intel_gpu/sources.cmake b/src/plugins/intel_gpu/sources.cmakeindex 37440ebe9c3..0092d03a0d8 100644--- a/src/plugins/intel_gpu/sources.cmake+++ b/src/plugins/intel_gpu/sources.cmake@@ -175,9 +175,11 @@ set(GPU_PLUGIN_TRANSFORMATIONS_SOURCES${CMAKE_CURRENT_LIST_DIR}/src/plugin/transformations/fuse_avg_down.cpp${CMAKE_CURRENT_LIST_DIR}/src/plugin/transformations/fuse_gated_mlp.cpp${CMAKE_CURRENT_LIST_DIR}/src/plugin/transformations/fuse_grouped_depth_to_space.cpp+ ${CMAKE_CURRENT_LIST_DIR}/src/plugin/transformations/fuse_hadamard_fc.cpp${CMAKE_CURRENT_LIST_DIR}/src/plugin/transformations/fuse_moe_router.cpp${CMAKE_CURRENT_LIST_DIR}/src/plugin/transformations/fuse_moe_router_scale.cpp${CMAKE_CURRENT_LIST_DIR}/src/plugin/transformations/fuse_moe_shared_expert.cpp+ ${CMAKE_CURRENT_LIST_DIR}/src/plugin/transformations/fuse_rms_rope.cpp${CMAKE_CURRENT_LIST_DIR}/src/plugin/transformations/fuse_rope_input_deinterleave.cpp${CMAKE_CURRENT_LIST_DIR}/src/plugin/transformations/group_query_attention_decomposition.cpp${CMAKE_CURRENT_LIST_DIR}/src/plugin/transformations/increase_position_ids_precision.cppdiff --git a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/CMakeLists.txt b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/CMakeLists.txtindex 31f2ef025e0..d933c9fb84f 100644--- a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/CMakeLists.txt+++ b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/CMakeLists.txt@@ -44,6 +44,54 @@ add_custom_command(OUTPUT "${CODEGEN_INCDIR}/${KERNEL_SOURCES}"add_custom_target(run_ocl_codegen${OV_GPU_SUFFIX} ALL DEPENDS "${CODEGEN_INCDIR}/${KERNEL_SOURCES}")+# TernOCL int2 kernels (ternocl_int2/), embedded as source strings. They come from+# the thirdparty/TernOCL submodule (github.com/libxsmm/TernOCL); TERNOCL_ROOT+# (cache or environment) points at another checkout, e.g. while editing kernels.+if(NOT DEFINED TERNOCL_ROOT)+ if(DEFINED ENV{TERNOCL_ROOT})+ set(TERNOCL_ROOT "$ENV{TERNOCL_ROOT}")+ else()+ set(TERNOCL_ROOT "${MAIN_DIR}/thirdparty/TernOCL")+ endif()+endif()+set(TERNOCL_ROOT "${TERNOCL_ROOT}" CACHE PATH "TernOCL kernel collection used by the int2 FullyConnected impl")+set(TERNOCL_FILES "${TERNOCL_ROOT}/int2_fp16_upcvt/int2_fp16_upcvt.cl"+ "${TERNOCL_ROOT}/int2_via_int2_x_int8_dpas/int2_int8_dpas.cl"+ "${TERNOCL_ROOT}/common/epilogue.clh"+ "${TERNOCL_ROOT}/hadamard/hadamard_fwht.cl")+foreach(f IN LISTS TERNOCL_FILES)+ if(NOT EXISTS "${f}")+ message(FATAL_ERROR "TernOCL kernel ${f} not found: run `git submodule update --init "+ "src/plugins/intel_gpu/thirdparty/TernOCL` or set TERNOCL_ROOT")+ endif()+endforeach()+set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS ${TERNOCL_FILES})+# Emits a source as concatenated raw-string chunks: MSVC caps a single literal at 16 KB.+function(ternocl_literal out_var name text)+ string(LENGTH "${text}" len)+ set(lit "static const char ${name}[] =")+ set(pos 0)+ while(pos LESS len)+ string(SUBSTRING "${text}" ${pos} 8000 chunk)+ string(APPEND lit "\n R\"TERNOCL(${chunk})TERNOCL\"")+ math(EXPR pos "${pos} + 8000")+ endwhile()+ set(${out_var} "${lit};\n" PARENT_SCOPE)+endfunction()+file(READ "${TERNOCL_ROOT}/common/epilogue.clh" TERNOCL_EPILOGUE)+file(READ "${TERNOCL_ROOT}/int2_fp16_upcvt/int2_fp16_upcvt.cl" TERNOCL_UPCVT)+string(REPLACE "#include \"epilogue.clh\"" "${TERNOCL_EPILOGUE}" TERNOCL_UPCVT "${TERNOCL_UPCVT}")+file(READ "${TERNOCL_ROOT}/int2_via_int2_x_int8_dpas/int2_int8_dpas.cl" TERNOCL_INT8)+string(REPLACE "#include \"epilogue.clh\"" "${TERNOCL_EPILOGUE}" TERNOCL_INT8 "${TERNOCL_INT8}")+file(READ "${TERNOCL_ROOT}/hadamard/hadamard_fwht.cl" TERNOCL_FWHT)+ternocl_literal(TERNOCL_UPCVT_LIT kTernoclUpcvtSource "${TERNOCL_UPCVT}")+ternocl_literal(TERNOCL_INT8_LIT kTernoclInt8Source "${TERNOCL_INT8}")+ternocl_literal(TERNOCL_FWHT_LIT kTernoclFwhtSource "${TERNOCL_FWHT}")+file(WRITE "${CODEGEN_CACHE_DIR}/ternocl_int2_kernels.inc"+ "// Generated from ${TERNOCL_ROOT} by impls/ocl_v2/CMakeLists.txt; do not edit.\n#pragma once\n"+ "${TERNOCL_UPCVT_LIT}${TERNOCL_INT8_LIT}${TERNOCL_FWHT_LIT}")+configure_file("${CODEGEN_CACHE_DIR}/ternocl_int2_kernels.inc" "${CODEGEN_INCDIR}/ternocl_int2_kernels.inc" COPYONLY)+ov_gpu_add_backend_target(NAME ${TARGET_NAME}INCLUDES $<BUILD_INTERFACE:${CODEGEN_INCDIR}>diff --git a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/rope_opt.cl b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/rope_opt.clindex e3cff3cf1f7..471fe88e948 100644--- a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/rope_opt.cl+++ b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/rope_opt.cl@@ -393,6 +393,9 @@ KERNEL(rope_opt)const __global INPUT2_TYPE* sin,#ifdef ENABLE_GATHERconst __global INPUT3_TYPE* gather,+#endif+#ifdef FUSE_RMS_NORM+ const __global INPUT3_TYPE* gamma,#endif__global OUTPUT_TYPE* output) {#ifdef REVERSED_GWS@@ -475,6 +478,13 @@ uint cos_sin_p = p;uint output_idx = OUTPUT_GET_INDEX(b, h, p, 0);+#ifdef FUSE_RMS_NORM+#ifdef INPUT_INTERLEAVED+# error "rope_opt.cl - FUSE_RMS_NORM does not support INPUT_INTERLEAVED"+#endif+ __local float rms_partial[RMS_WORKERS];+#endif+#if VEC_SIZE == 1#ifdef INPUT_INTERLEAVEDACCUMULATOR_TYPE in1 = DECODE_INPUT0_COMPUTE_TYPE(input[input_idx + 2 * r]);@@ -524,6 +534,30 @@ uint cos_sin_p = p;#elseINPUT_VEC_TYPE in1 = *(INPUT_VEC_TYPE*)(input + input_idx + r);INPUT_VEC_TYPE in2 = *(INPUT_VEC_TYPE*)(input + input_idx + HALF_ROTARY_NDIMS + r);+#ifdef FUSE_RMS_NORM+ {+ // Mirror rms_gpu_bfyx_opt.cl arithmetic so the fused path matches the standalone RMSNorm.+ float partial = 0.0f;+ unroll_for (uint i = 0; i < VEC_SIZE; ++i) {+ partial += native_powr(convert_float(in1[i]), 2);+ partial += native_powr(convert_float(in2[i]), 2);+ }+ rms_partial[get_local_id(2)] = partial;+ barrier(CLK_LOCAL_MEM_FENCE);++ float total = 0.0f;+ unroll_for (uint i = 0; i < RMS_WORKERS; ++i) {+ total += rms_partial[i];+ }+ const float scale = native_powr(sqrt(total / (float)ROTARY_NDIMS + RMS_EPSILON), -1);++ unroll_for (uint i = 0; i < VEC_SIZE; ++i) {+ in1[i] = (INPUT0_TYPE)(scale * convert_float(in1[i]) * convert_float(gamma[r + i]));+ in2[i] = (INPUT0_TYPE)(scale * convert_float(in2[i]) *+ convert_float(gamma[HALF_ROTARY_NDIMS + r + i]));+ }+ }+#endif#endifINPUT_VEC_TYPE cos1 = *(INPUT_VEC_TYPE*)(cos + cos_idx + r);INPUT_VEC_TYPE cos2 = *(INPUT_VEC_TYPE*)(cos + cos_idx + COS_SIN_TABLE_OFFSET + r);diff --git a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/rope_opt.cpp b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/rope_opt.cppindex ddd1bc70643..6be544e485e 100644--- a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/rope_opt.cpp+++ b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/rope_opt.cpp@@ -50,6 +50,14 @@ size_t get_vec_size(const RuntimeParams& params) {return vec_size;}+// The fused RMSNorm reduction relies on the non-reversed GWS layout, which is only used when VEC_SIZE > 1.+bool fused_rms_enabled(const RuntimeParams& params) {+ if (!params.typed_desc<rope>()->fuse_rms_norm)+ return false;+ OPENVINO_ASSERT(get_vec_size(params) > 1, "[GPU] rope: a fused RMSNorm needs the vectorized RoPE kernel");+ return true;+}+class RopeGenerator : public KernelGenerator {public:RopeGenerator() : KernelGenerator("rope_opt") {}@@ -112,6 +120,12 @@ protected:}}jit.make("VEC_SIZE", get_vec_size(params));+ if (fused_rms_enabled(params)) {+ // One workgroup owns a whole head along gws[2], so the RMS reduction is workgroup-local.+ jit.make("FUSE_RMS_NORM", true);+ jit.make("RMS_EPSILON", desc->rms_epsilon);+ jit.make("RMS_WORKERS", desc->config.rotary_ndims / (2 * get_vec_size(params)));+ }if (in_l.data_type == ov::element::bf16) {jit.add(make_type_jit_constants("ACCUMULATOR", ov::element::f32));} else if (params.get_input_layout(0).data_type != params.get_input_layout(1).data_type) {@@ -141,6 +155,10 @@ protected:args.push_back({ArgumentDescriptor::Types::INPUT, i});}+ if (fused_rms_enabled(params)) {+ args.push_back({ArgumentDescriptor::Types::INPUT, num_of_inputs});+ }+args.push_back({ArgumentDescriptor::Types::OUTPUT, 0});return args;@@ -194,7 +212,10 @@ protected:}// We need to set the 1st local workgroup size as large as possible for better performance.- if (vec_size == 1) {+ if (fused_rms_enabled(params)) {+ // Keep every work item of one head in a single workgroup for the RMS reduction.+ wgs.local = {1, 1, cfg.rotary_ndims / (2 * vec_size)};+ } else if (vec_size == 1) {auto get_max_lws = [](size_t gws, size_t max_workgroup_size) -> size_t {size_t val = 1;size_t lws = 1;diff --git a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sources.cmake b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sources.cmakeindex 1830550f1ed..f8a56adc5fd 100644--- a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sources.cmake+++ b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sources.cmake@@ -89,6 +89,10 @@ set(GPU_OCL_V2_IMPL_SOURCES${CMAKE_CURRENT_LIST_DIR}/selective_ssm_utils.hpp${CMAKE_CURRENT_LIST_DIR}/slice_scatter.cpp${CMAKE_CURRENT_LIST_DIR}/slice_scatter.hpp+ ${CMAKE_CURRENT_LIST_DIR}/ternocl_int2/fully_connected_ternocl_int2.cpp+ ${CMAKE_CURRENT_LIST_DIR}/ternocl_int2/fully_connected_ternocl_int2.hpp+ ${CMAKE_CURRENT_LIST_DIR}/ternocl_int2/ternocl_int2_weights_reorder.cpp+ ${CMAKE_CURRENT_LIST_DIR}/ternocl_int2/ternocl_int2_weights_reorder.hpp${CMAKE_CURRENT_LIST_DIR}/utils/fused_ops_jitter.cpp${CMAKE_CURRENT_LIST_DIR}/utils/fused_ops_jitter.hpp${CMAKE_CURRENT_LIST_DIR}/utils/jitter.cppdiff --git a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/ternocl_int2/fully_connected_ternocl_int2.cpp b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/ternocl_int2/fully_connected_ternocl_int2.cppnew file mode 100644index 00000000000..f713c8b5af2--- /dev/null+++ b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/ternocl_int2/fully_connected_ternocl_int2.cpp@@ -0,0 +1,640 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "fully_connected_ternocl_int2.hpp"++#ifdef OV_GPU_WITH_OCL_RT++# include <array>+# include <atomic>+# include <cmath>+# include <cstdint>+# include <cstdio>+# include <cstdlib>+# include <iostream>+# include <map>+# include <mutex>+# include <vector>++# include "fully_connected_inst.h"+# include "intel_gpu/runtime/debug_configuration.hpp"+# include "intel_gpu/runtime/kernel_args.hpp"+# include "intel_gpu/runtime/memory.hpp"+# include "primitive_inst.h"+# include "registry/registry.hpp"+# include "runtime/ocl/ocl_engine.hpp"+# include "runtime/ocl/ocl_kernel.hpp"+# include "ternocl_int2_kernels.inc" // generated from TERNOCL_ROOT (CMakeLists.txt)++namespace cldnn {+namespace ocl {++namespace {++// ---------------------------------------------------------------------------+// Tile selection. GEMV (M <= 8): sub-group rows SGM, work-group width WGN+// (16 per sub-group), local k-slicing LS, loads issued ahead U. M-tiled GEMM+// (M > 8): sub-group tile MT_M x MT_N, work-group WG_M x WG_N sub-groups.+// Tuned with TernOCL's bench.sh (>= 2 GiB rotating weights, median of 3).+struct GemvTile {+ int wgn, ls, u;+};+struct MtTile {+ int mt_m, mt_n, wg_m, wg_n;+};++GemvTile gemv_tile(size_t K, size_t N, bool integrated) {+ struct Entry {+ size_t k, n;+ GemvTile t;+ };+ // Arc Pro B70, M = 1 (TernOCL int2_fp16_upcvt default_tiles).+ static const Entry discrete[] = {+ {4096, 6144, {16, 4, 1}}, // 8B qkv+ {4096, 4096, {32, 8, 1}}, // 8B o_proj+ {4096, 24576, {64, 1, 1}}, // 8B gate_up (merged)+ {12288, 4096, {32, 8, 1}}, // 8B down+ {4096, 151680, {32, 1, 1}}, // 8B lm_head+ {5120, 34816, {32, 8, 1}}, // 27B gate_up (merged)+ {17408, 5120, {16, 6, 1}}, // 27B down+ {5120, 16384, {32, 2, 1}}, // 27B in_proj_qkvz+ {6144, 5120, {16, 6, 1}}, // 27B out_proj / o_proj+ {5120, 14336, {32, 2, 1}}, // 27B qkv+ {5120, 248320, {16, 1, 1}}, // 27B lm_head+ // Bonsai 1.7B (also CAT-Q 1.7B): qkv, o_proj, gate_up, down, lm_head+ {2048, 4096, {32, 8, 1}},+ {2048, 2048, {32, 8, 1}},+ {2048, 12288, {16, 2, 1}},+ {6144, 2048, {16, 8, 1}},+ {2048, 151680, {32, 1, 1}},+ // Bonsai 4B+ {2560, 6144, {32, 4, 1}},+ {4096, 2560, {32, 8, 1}},+ {2560, 19456, {64, 1, 1}},+ {9728, 2560, {32, 8, 1}},+ {2560, 151680, {32, 1, 1}},+ // CAT-Q (Qwen3) 32B: gate_up, down, qkv, o_proj+ {5120, 51200, {16, 1, 1}},+ {25600, 5120, {16, 6, 1}},+ {5120, 10240, {16, 8, 1}},+ {8192, 5120, {32, 6, 1}},+ };+ // Arc 140V (Lunar Lake), M = 1, paced sweep (select decode).+ static const Entry igpu[] = {+ {5120, 34816, {16, 2, 1}},+ {17408, 5120, {128, 1, 1}},+ {5120, 16384, {16, 1, 2}},+ {6144, 5120, {64, 1, 1}},+ {5120, 14336, {16, 1, 1}},+ {5120, 248320, {32, 2, 2}},+ // Bonsai 1.7B / 4B / 8B, CAT-Q 32B (host on the E-cores)+ {2048, 4096, {32, 2, 1}},+ {2048, 2048, {16, 4, 1}},+ {2048, 12288, {16, 1, 1}},+ {6144, 2048, {32, 4, 1}},+ {2048, 151680, {32, 4, 1}},+ {2560, 6144, {16, 1, 1}},+ {4096, 2560, {32, 2, 1}},+ {2560, 19456, {16, 2, 1}},+ {9728, 2560, {32, 2, 2}},+ {2560, 151680, {32, 4, 1}},+ {4096, 6144, {64, 1, 1}},+ {4096, 4096, {32, 2, 1}},+ {4096, 24576, {16, 2, 1}},+ {12288, 4096, {32, 2, 1}},+ {4096, 151680, {16, 1, 1}},+ {5120, 10240, {16, 4, 1}},+ {8192, 5120, {64, 1, 1}},+ {5120, 51200, {16, 2, 1}},+ {25600, 5120, {32, 1, 1}},+ };+ if (integrated) {+ for (const auto& e : igpu) {+ if (e.k == K && e.n == N)+ return e.t;+ }+ }+ for (const auto& e : discrete) {+ if (e.k == K && e.n == N)+ return e.t;+ }+ return N <= 8192 ? GemvTile{32, 4, 1} : GemvTile{32, 2, 1};+}++MtTile mt_tile(size_t K, size_t N, size_t M, bool integrated) {+ if (M < 64) {+ // Sweep at M = 12 / 20 / 32 / 48 over the 27B shapes; the winners group+ // by output width (narrow N <= 8192, head N >= 65536).+ const int band = M <= 16 ? 0 : (M <= 32 ? 1 : 2);+ static const MtTile narrow[3] = {{16, 16, 2, 2}, {32, 16, 2, 4}, {32, 16, 1, 4}}; // Arc Pro B70+ static const MtTile wide[3] = {{16, 16, 1, 8}, {32, 16, 1, 4}, {64, 16, 1, 8}};+ static const MtTile head[3] = {{16, 16, 1, 4}, {64, 32, 1, 8}, {64, 32, 1, 8}};+ static const MtTile i_narrow[3] = {{16, 32, 1, 4}, {32, 32, 1, 8}, {64, 32, 1, 8}}; // Arc 140V+ static const MtTile i_wide[3] = {{16, 16, 1, 8}, {64, 32, 1, 4}, {64, 32, 1, 4}};+ static const MtTile i_head[3] = {{16, 16, 1, 4}, {32, 16, 1, 8}, {64, 32, 1, 4}};+ if (integrated)+ return N <= 8192 ? i_narrow[band] : (N >= 65536 ? i_head[band] : i_wide[band]);+ return N <= 8192 ? narrow[band] : (N >= 65536 ? head[band] : wide[band]);+ }+ struct Entry {+ size_t k, n;+ MtTile t;+ };+ // Arc Pro B70, M = 1024 (TernOCL int2_fp16_upcvt README).+ static const Entry table[] = {+ {4096, 6144, {64, 32, 4, 4}},+ {4096, 4096, {64, 16, 2, 4}},+ {4096, 24576, {64, 16, 2, 2}},+ {12288, 4096, {64, 32, 4, 2}},+ {4096, 151680, {64, 32, 4, 4}},+ {5120, 34816, {64, 32, 4, 4}},+ {17408, 5120, {32, 32, 1, 8}},+ {5120, 16384, {64, 16, 2, 2}},+ {6144, 5120, {64, 16, 1, 8}},+ {5120, 14336, {64, 32, 4, 4}},+ {5120, 248320, {64, 32, 4, 4}},+ };+ // Arc 140V (Lunar Lake), M = 512.+ static const Entry igpu[] = {+ {5120, 34816, {128, 16, 2, 2}},+ {17408, 5120, {64, 32, 4, 2}},+ {5120, 16384, {128, 16, 2, 4}},+ {6144, 5120, {128, 16, 2, 4}},+ {5120, 14336, {128, 16, 2, 4}},+ {5120, 248320, {128, 16, 2, 2}},+ };+ if (integrated) {+ for (const auto& e : igpu) {+ if (e.k == K && e.n == N)+ return e.t;+ }+ return MtTile{128, 16, 2, 4};+ }+ for (const auto& e : table) {+ if (e.k == K && e.n == N)+ return e.t;+ }+ return MtTile{64, 32, 4, 4};+}++// Arc Pro B70 sweep of the 27B shapes, per M band (<= 16, <= 32, < 64, >= 64).+MtTile int8_tile(size_t K, size_t N, size_t M) {+ const int band = M <= 16 ? 0 : (M <= 32 ? 1 : (M < 64 ? 2 : 3));+ struct Entry {+ size_t k, n;+ MtTile t[4];+ };+ static const Entry table[] = {+ {5120, 34816, {{8, 128, 1, 4}, {8, 64, 4, 1}, {8, 128, 8, 2}, {8, 128, 8, 2}}}, // gate_up (merged)+ {17408, 5120, {{8, 32, 2, 4}, {8, 32, 2, 4}, {8, 64, 8, 2}, {8, 128, 8, 2}}}, // down+ {5120, 16384, {{8, 32, 2, 4}, {8, 64, 2, 2}, {8, 128, 2, 4}, {8, 128, 16, 1}}}, // in_proj_qkvz+ {6144, 5120, {{8, 32, 2, 4}, {8, 32, 2, 4}, {8, 64, 8, 2}, {8, 128, 8, 2}}}, // out_proj / o_proj+ {5120, 14336, {{8, 32, 2, 4}, {8, 64, 2, 2}, {8, 128, 8, 2}, {8, 128, 4, 2}}}, // qkv+ {5120, 248320, {{8, 128, 2, 4}, {8, 128, 4, 4}, {8, 128, 8, 2}, {8, 128, 16, 1}}}, // lm_head+ };+ for (const auto& e : table) {+ if (e.k == K && e.n == N)+ return e.t[band];+ }+ static const MtTile fallback[4] = {{8, 32, 2, 4}, {8, 64, 2, 2}, {8, 128, 8, 2}, {8, 128, 8, 2}};+ return fallback[band];+}++// ---------------------------------------------------------------------------+// Programs are built once per (context, source, options) and shared by the impls created on that+// context (the FCs of a model differ only in a few shapes); every impl creates its own cl_kernel+// from them, so argument state is never shared. Each impl holds the cache, so it is released with+// the last of them.+class TernoclProgramCache {+public:+ static std::shared_ptr<TernoclProgramCache> get(const ocl_engine& engine) {+ static std::mutex m;+ static std::map<cl_context, std::weak_ptr<TernoclProgramCache>> caches;+ std::lock_guard<std::mutex> lock(m);+ for (auto it = caches.begin(); it != caches.end();) {+ it = it->second.expired() ? caches.erase(it) : std::next(it);+ }+ auto& entry = caches[engine.get_cl_context().get()];+ auto cache = entry.lock();+ if (!cache) {+ cache = std::make_shared<TernoclProgramCache>();+ entry = cache;+ }+ return cache;+ }++ cl::Program get_program(const ocl_engine& engine, const char* src, const std::string& opts) {+ const std::string key = std::to_string(reinterpret_cast<uintptr_t>(src)) + "|" + opts;+ std::lock_guard<std::mutex> lock(_m);+ auto it = _programs.find(key);+ if (it != _programs.end())+ return it->second;+ cl::Program prog(engine.get_cl_context(), std::string(src));+ try {+ prog.build(std::vector<cl::Device>{engine.get_cl_device()}, opts.c_str());+ } catch (const cl::Error&) {+ OPENVINO_THROW("[GPU] ternocl int2: kernel build failed (", opts, "):\n", prog.getBuildInfo<CL_PROGRAM_BUILD_LOG>(engine.get_cl_device()));+ }+ GPU_DEBUG_TRACE_DETAIL << "[ternocl-int2] built " << opts << std::endl;+ return _programs.emplace(key, prog).first->second;+ }++private:+ std::mutex _m;+ std::map<std::string, cl::Program> _programs;+};++kernel::ptr make_kernel(const ocl_engine& engine, const cl::Program& prog, const char* name) {+ return std::make_shared<ocl_kernel>(ocl_kernel_type(cl::Kernel(prog, name), engine.get_usm_helper()), name);+}++size_t ceil_div(size_t a, size_t b) {+ return (a + b - 1) / b;+}++} // namespace++struct fully_connected_ternocl_int2 : typed_primitive_impl<fully_connected> {+ using parent = typed_primitive_impl<fully_connected>;++ DECLARE_OBJECT_TYPE_SERIALIZATION(cldnn::ocl::fully_connected_ternocl_int2)++ // Weights and scales come from the node's inputs: the weights reorder packs the weights, and+ // prepare_quantization lays the grouped scales out as [groups, N]. Nothing here depends on the+ // node beyond kernel_impl_params, so a cached impl can serve any FC with equal params.+ const ocl_engine* _engine = nullptr;+ std::shared_ptr<TernoclProgramCache> _programs;+ // i8 [K] +-1 from the primitive's hadamard_signs (part of the impl cache key), or null.+ memory::ptr _had_signs;+ size_t _N = 0;+ size_t _K = 0;+ TernoclPostop _postop = TernoclPostop::none;+ size_t _other_dep = 0;+ size_t _scale_dep = 0;+ bool _out_f32 = false;+ size_t _had_block = 0;+ bool _integrated = false;+ // GPU_TERNOCL_INT2_INT8_PREFILL: M > 8 on the int2 x int8 DPAS GEMM (activations quantized per 128-group).+ bool _int8_prefill = false;++ // GEMV for M = 1, 2, <= 4, <= 8; M-tiled for M <= 16, <= 32, < 64, >= 64.+ struct Launch {+ kernel::ptr k;+ GemvTile g{};+ MtTile t{};+ };+ std::array<Launch, 8> _launch;+ // int8 prefill, M-tiled classes 4..7: scale pre-kernel + GEMM from one program.+ struct Int8Launch {+ kernel::ptr quant, gemm;+ MtTile t{};+ };+ std::array<Int8Launch, 4> _int8_launch;+ kernel::ptr _fwht;++ fully_connected_ternocl_int2() : parent("ternocl_int2") {}+ fully_connected_ternocl_int2(ocl_engine& engine,+ const fully_connected& desc,+ size_t N,+ size_t K,+ TernoclPostop postop,+ size_t other_dep,+ size_t scale_dep,+ bool out_f32,+ bool int8)+ : parent("ternocl_int2"),+ _N(N),+ _K(K),+ _postop(postop),+ _other_dep(other_dep),+ _scale_dep(scale_dep),+ _out_f32(out_f32),+ _had_block(desc.hadamard_block),+ _int8_prefill(int8) {+ attach(engine, desc);+ }++ // Engine-bound state, rebuilt rather than serialized.+ void attach(ocl_engine& engine, const fully_connected& desc) {+ _engine = &engine;+ _integrated = engine.get_device_info().dev_type == device_type::integrated_gpu;+ _programs = TernoclProgramCache::get(engine);+ _had_signs = nullptr;+ if (desc.hadamard_block != 0 && !desc.hadamard_signs.empty()) {+ OPENVINO_ASSERT(desc.hadamard_signs.size() == _K, "[GPU] ternocl int2: hadamard signs length mismatch");+ _had_signs =+ engine.allocate_memory(layout{ov::PartialShape{static_cast<int64_t>(_K)}, data_types::i8, format::bfyx}, allocation_type::usm_device, false);+ _had_signs->copy_from(engine.get_service_stream(), desc.hadamard_signs.data(), true);+ }+ }++ void save(BinaryOutputBuffer& ob) const override {+ parent::save(ob);+ ob << _N;+ ob << _K;+ ob << static_cast<int>(_postop);+ ob << _other_dep;+ ob << _scale_dep;+ ob << _out_f32;+ ob << _had_block;+ ob << _int8_prefill;+ }++ void load(BinaryInputBuffer& ib) override {+ parent::load(ib);+ int postop = 0;+ ib >> _N;+ ib >> _K;+ ib >> postop;+ ib >> _other_dep;+ ib >> _scale_dep;+ ib >> _out_f32;+ ib >> _had_block;+ ib >> _int8_prefill;+ _postop = static_cast<TernoclPostop>(postop);+ const auto* params = reinterpret_cast<const kernel_impl_params*>(ib.getKernelImplParams());+ OPENVINO_ASSERT(params != nullptr, "[GPU] ternocl int2: kernel_impl_params are required to load the impl");+ attach(downcast<ocl_engine>(ib.get_engine()), *params->typed_desc<fully_connected>());+ }++ std::unique_ptr<primitive_impl> clone() const override {+ // Shares the kernel handles like the stock OCL impls: OpenVINO clones+ // cached impls on every shape update, and rebuilding costs tens of us per FC.+ return std::make_unique<fully_connected_ternocl_int2>(*this);+ }++ bool is_cpu() const override {+ return false;+ }+ bool is_onednn() const override {+ return false;+ }++ // Scratch comes from the network memory pool, so it is shared across primitives+ // and resized with M: [had] f16 [M, K] rotated activation, [int8] f16 [K/128, LDSA(M)] scales.+ std::vector<BufferDescriptor> get_internal_buffer_descs(const kernel_impl_params& params) const override {+ const auto& out = params.output_layouts[0];+ if (out.is_dynamic() || _N == 0)+ return {};+ const size_t M = ov::shape_size(out.get_shape()) / _N;+ std::vector<BufferDescriptor> descs;+ if (_had_block != 0)+ descs.emplace_back(M * _K, ov::element::f16);+ if (M > 8 && _int8_prefill)+ descs.emplace_back((_K / kTernoclGroupSize) * ((M + 31) & ~size_t{31}), ov::element::f16);+ return descs;+ }++protected:+ void init_kernels(const kernels_cache&, const kernel_impl_params&) override {}+ void set_arguments_impl(typed_primitive_inst<fully_connected>&) override {}+ void set_arguments_impl(typed_primitive_inst<fully_connected>&, kernel_arguments_data&) override {}++ std::string epi_opts() const {+ return " -DPOSTOP=" + std::to_string(static_cast<int>(_postop)) + (_out_f32 ? " -DOUT_F32" : "");+ }++ static size_t launch_class(size_t M) {+ if (M <= 8)+ return M == 1 ? 0 : (M == 2 ? 1 : (M <= 4 ? 2 : 3));+ return M <= 16 ? 4 : (M <= 32 ? 5 : (M < 64 ? 6 : 7));+ }++ Launch& get_launch(size_t M) {+ auto& l = _launch[launch_class(M)];+ if (l.k)+ return l;+ std::string opts = "-cl-std=CL3.0";+ if (M <= 8) {+ const int sgm = M == 1 ? 1 : (M == 2 ? 2 : (M <= 4 ? 4 : 8));+ l.g = gemv_tile(_K, _N, _integrated);+ opts += " -DSGM=" + std::to_string(sgm) + " -DNSG_N=" + std::to_string(l.g.wgn / 16) + " -DLS=" + std::to_string(l.g.ls) ++ " -DU=" + std::to_string(l.g.u) + " -DPF=0";+ l.k = make_kernel(*_engine, _programs->get_program(*_engine, kTernoclUpcvtSource, opts + epi_opts()), "int2_fp16_upcvt_gemm");+ } else {+ l.t = mt_tile(_K, _N, M, _integrated);+ opts += " -DMT_M=" + std::to_string(l.t.mt_m) + " -DMT_N=" + std::to_string(l.t.mt_n) + " -DWG_M=" + std::to_string(l.t.wg_m) ++ " -DWG_N=" + std::to_string(l.t.wg_n) + " -cl-intel-256-GRF-per-thread";+ l.k = make_kernel(*_engine, _programs->get_program(*_engine, kTernoclUpcvtSource, opts + epi_opts()), "int2_fp16_upcvt_gemm_mt");+ }+ GPU_DEBUG_TRACE_DETAIL << "[ternocl-int2] K=" << _K << " N=" << _N << " M-class " << launch_class(M) << ": " << opts << epi_opts() << std::endl;+ return l;+ }++ Int8Launch& get_int8_launch(size_t M) {+ auto& l = _int8_launch[launch_class(M) - 4];+ if (l.gemm)+ return l;+ l.t = int8_tile(_K, _N, M);+ const std::string opts = "-cl-std=CL3.0 -cl-fp32-correctly-rounded-divide-sqrt -DQMODE=1 -DMT_M=" + std::to_string(l.t.mt_m) ++ " -DMT_N=" + std::to_string(l.t.mt_n) + " -DWG_M=" + std::to_string(l.t.wg_m) + " -DWG_N=" + std::to_string(l.t.wg_n) ++ " -cl-intel-256-GRF-per-thread" + epi_opts();+ const auto prog = _programs->get_program(*_engine, kTernoclInt8Source, opts);+ l.quant = make_kernel(*_engine, prog, "quant_a");+ l.gemm = make_kernel(*_engine, prog, "int2_int8_gemm_mt");+ GPU_DEBUG_TRACE_DETAIL << "[ternocl-int2] K=" << _K << " N=" << _N << " M-class " << launch_class(M) << " int8: " << opts << std::endl;+ return l;+ }++ event::ptr execute_int8(typed_primitive_inst<fully_connected>& instance, memory::cptr in, std::vector<event::ptr> deps, size_t M) {+ auto& network = instance.get_network();+ auto& stream = network.get_stream();+ auto& l = get_int8_launch(M);+ const size_t groups = _K / kTernoclGroupSize;+ const auto& sa = instance.get_intermediates_memories().at(_had_block != 0 ? 1 : 0);++ // quant_a(A, SA, Aq, M, K): SA[g, m] = 127 / absmax of row m over group g. Aq is not written in QMODE 1.+ kernel_arguments_desc qd;+ qd.workGroups.global = {groups * 16, M, 1};+ qd.workGroups.local = {16, 1, 1};+ qd.arguments = {{argument_desc::Types::INPUT, 0},+ {argument_desc::Types::OUTPUT, 0},+ {argument_desc::Types::INPUT, 0},+ {argument_desc::Types::SCALAR, 0},+ {argument_desc::Types::SCALAR, 1}};+ scalars_desc qs(2);+ qs[0].t = qs[1].t = scalar_desc::Types::INT32;+ qs[0].v.s32 = static_cast<int32_t>(M);+ qs[1].v.s32 = static_cast<int32_t>(_K);+ kernel_arguments_data qa;+ qa.inputs = {in};+ qa.outputs = {sa};+ qa.scalars = &qs;+ stream.set_arguments(*l.quant, qd, qa);+ deps = {stream.enqueue_kernel(*l.quant, qd, qa, deps, false)};++ // A, Aq (unused), SA, B, SB, C, Other, Bias, M, N, K+ kernel_arguments_desc d;+ const size_t tn = static_cast<size_t>(l.t.mt_n * l.t.wg_n), tm = static_cast<size_t>(l.t.mt_m * l.t.wg_m);+ d.workGroups.local = {16 * static_cast<size_t>(l.t.wg_n * l.t.wg_m), 1, 1};+ d.workGroups.global = {ceil_div(_N, tn) * d.workGroups.local[0], ceil_div(M, tm), 1};+ d.arguments = {{argument_desc::Types::INPUT, 0},+ {argument_desc::Types::INPUT, 0},+ {argument_desc::Types::INPUT, 1},+ {argument_desc::Types::INPUT, 2},+ {argument_desc::Types::INPUT, 3},+ {argument_desc::Types::OUTPUT, 0},+ {argument_desc::Types::INPUT, 4},+ {argument_desc::Types::INPUT, 5},+ {argument_desc::Types::SCALAR, 0},+ {argument_desc::Types::SCALAR, 1},+ {argument_desc::Types::SCALAR, 2}};+ scalars_desc sc(3);+ for (auto& s : sc)+ s.t = scalar_desc::Types::INT32;+ sc[0].v.s32 = static_cast<int32_t>(M);+ sc[1].v.s32 = static_cast<int32_t>(_N);+ sc[2].v.s32 = static_cast<int32_t>(_K);+ memory::cptr other = ternocl_postop_reads_other(_postop) ? instance.dep_memory_ptr(_other_dep) : in;+ memory::cptr bias = _postop == TernoclPostop::bias ? instance.bias_memory() : in;+ kernel_arguments_data a;+ a.inputs = {in, sa, instance.weights_memory(), instance.dep_memory_ptr(_scale_dep), other, bias};+ a.outputs = {instance.output_memory_ptr(0)};+ a.scalars = ≻+ stream.set_arguments(*l.gemm, d, a);+ return stream.enqueue_kernel(*l.gemm, d, a, deps, instance.is_output());+ }++ event::ptr execute_impl(const std::vector<event::ptr>& events, typed_primitive_inst<fully_connected>& instance) override {+ auto& network = instance.get_network();+ auto& stream = network.get_stream();+ const auto& params = instance.get_impl_params();+ const size_t M = ov::shape_size(params->output_layouts[0].get_shape()) / _N;++ memory::cptr in = instance.input_memory_ptr(0);+ std::vector<event::ptr> deps = events;+ if (_had_block != 0) {+ // Rotated-basis checkpoint: the GEMM consumes H_1024(s * x) / 32.+ const auto& rotated = instance.get_intermediates_memories().at(0);+ if (!_fwht)+ _fwht = make_kernel(*_engine, _programs->get_program(*_engine, kTernoclFwhtSource, "-cl-std=CL3.0"), "hadamard_fwht_1024");+ kernel_arguments_desc d;+ d.workGroups.global = {M * (_K / 1024) * 128, 1, 1};+ d.workGroups.local = {128, 1, 1};+ d.arguments = {{argument_desc::Types::INPUT, 0},+ {argument_desc::Types::INPUT, 1},+ {argument_desc::Types::OUTPUT, 0},+ {argument_desc::Types::SCALAR, 0},+ {argument_desc::Types::SCALAR, 1}};+ scalars_desc sc(2);+ sc[0].t = sc[1].t = scalar_desc::Types::INT32;+ sc[0].v.s32 = static_cast<int32_t>(_K);+ sc[1].v.s32 = _had_signs ? 1 : 0;+ kernel_arguments_data a;+ a.inputs = {in, _had_signs ? memory::cptr(_had_signs) : in};+ a.outputs = {rotated};+ a.scalars = ≻+ stream.set_arguments(*_fwht, d, a);+ deps = {stream.enqueue_kernel(*_fwht, d, a, deps, false)};+ in = rotated;+ }++ if (M > 8 && _int8_prefill)+ return execute_int8(instance, in, deps, M);++ auto& l = get_launch(M);+ kernel_arguments_desc d;+ if (M <= 8) {+ const size_t sgm = M == 1 ? 1 : (M == 2 ? 2 : (M <= 4 ? 4 : 8));+ const size_t wgn = static_cast<size_t>(l.g.wgn);+ d.workGroups.local = {wgn * static_cast<size_t>(l.g.ls), 1, 1};+ d.workGroups.global = {ceil_div(_N, wgn) * d.workGroups.local[0], ceil_div(M, sgm), 1};+ } else {+ const size_t tn = static_cast<size_t>(l.t.mt_n * l.t.wg_n), tm = static_cast<size_t>(l.t.mt_m * l.t.wg_m);+ d.workGroups.local = {16 * static_cast<size_t>(l.t.wg_n * l.t.wg_m), 1, 1};+ d.workGroups.global = {ceil_div(_N, tn) * d.workGroups.local[0], ceil_div(M, tm), 1};+ }+ // A, B, S, C, Other, Bias, M, N, K+ d.arguments = {{argument_desc::Types::INPUT, 0},+ {argument_desc::Types::INPUT, 1},+ {argument_desc::Types::INPUT, 2},+ {argument_desc::Types::OUTPUT, 0},+ {argument_desc::Types::INPUT, 3},+ {argument_desc::Types::INPUT, 4},+ {argument_desc::Types::SCALAR, 0},+ {argument_desc::Types::SCALAR, 1},+ {argument_desc::Types::SCALAR, 2}};+ scalars_desc sc(3);+ for (auto& s : sc)+ s.t = scalar_desc::Types::INT32;+ sc[0].v.s32 = static_cast<int32_t>(M);+ sc[1].v.s32 = static_cast<int32_t>(_N);+ sc[2].v.s32 = static_cast<int32_t>(_K);+ // Unused Other / Bias slots are never read, but need a valid buffer.+ memory::cptr other = ternocl_postop_reads_other(_postop) ? instance.dep_memory_ptr(_other_dep) : in;+ memory::cptr bias = _postop == TernoclPostop::bias ? instance.bias_memory() : in;+ kernel_arguments_data a;+ a.inputs = {in, instance.weights_memory(), instance.dep_memory_ptr(_scale_dep), other, bias};+ a.outputs = {instance.output_memory_ptr(0)};+ a.scalars = ≻+ stream.set_arguments(*l.k, d, a);+ return stream.enqueue_kernel(*l.k, d, a, deps, instance.is_output());+ }++public:+ static std::unique_ptr<primitive_impl> create(const fully_connected_node& arg, const kernel_impl_params& impl_params) {+ auto& prog = arg.get_program();+ const bool int8 = prog.get_config().get_ternocl_int2_int8_prefill();+ const auto& desc = impl_params.typed_desc<fully_connected>();++ // At build the weights input is the u2 constant; once the reorder below is folded it is the packed one.+ const auto& wei_layout = impl_params.get_input_layout(1);+ const auto wei_shape = wei_layout.get_shape();+ const size_t N = wei_shape[0];+ const size_t K = wei_shape[1];++ size_t other_dep = 0;+ const auto postop = ternocl_int2_postop(impl_params.fused_desc, desc->bias.is_valid(), &other_dep);+ OPENVINO_ASSERT(postop.has_value(), "[GPU] ternocl int2: ", arg.id(), " has no folded epilogue for its fused chain");+ const bool out_f32 = impl_params.output_layouts[0].data_type == data_types::f32;+ // Dependencies are input, weights, [bias], scale, [zero point].+ const size_t scale_dep = desc->bias.is_valid() ? 3 : 2;++ GPU_DEBUG_TRACE << "[ternocl-int2] create " << arg.id() << " N=" << N << " K=" << K << " postop=" << static_cast<int>(*postop) << " out_f32=" << out_f32+ << " hadamard=" << desc->hadamard_block << " int8_prefill=" << int8 << std::endl;++ auto impl =+ std::make_unique<fully_connected_ternocl_int2>(downcast<ocl_engine>(prog.get_engine()), *desc, N, K, *postop, other_dep, scale_dep, out_f32, int8);+ auto packed_layout = wei_layout;+ packed_layout.format = format::is_os_yx_isv16_ternary;+ impl->_weights_reorder_params = std::make_shared<WeightsReorderParams>(wei_layout, packed_layout);+ return impl;+ }+};++// A forced impl type (unit tests) skips validate() and takes the first OCL manager,+// so FCs this impl rejects are handed to the next OCL FC manager.+static const ImplementationManager& stock_ocl_manager(const ImplementationManager& self, shape_types shape_type) {+ for (const auto& m : ov::intel_gpu::Registry<fully_connected>::get_implementations()) {+ if (m->get_impl_type() == impl_types::ocl && m->get_type_info() != self.get_type_info() && (m->get_shape_type() & shape_type) == shape_type)+ return *m;+ }+ OPENVINO_THROW("[GPU] ternocl int2: no OCL FullyConnected implementation to fall back to");+}++std::unique_ptr<primitive_impl> TernoclInt2FCImplementationManager::create_impl(const program_node& node, const kernel_impl_params& params) const {+ assert(node.is_type<fully_connected>());+ if (!validate_impl(node))+ return stock_ocl_manager(*this, get_shape_type(node)).create_impl(node, params);+ return fully_connected_ternocl_int2::create(static_cast<const fully_connected_node&>(node), params);+}++std::unique_ptr<primitive_impl> TernoclInt2FCImplementationManager::create_impl(const kernel_impl_params& params) const {+ if (params.input_layouts.size() < 2 || params.input_layouts[1].data_type != data_types::u2)+ return stock_ocl_manager(*this, get_shape_type(params)).create_impl(params);+ OPENVINO_NOT_IMPLEMENTED;+}++in_out_fmts_t TernoclInt2FCImplementationManager::query_formats(const program_node& node) const {+ if (!validate_impl(node))+ return stock_ocl_manager(*this, get_shape_type(node)).query_formats(node);+ return ImplementationManager::query_formats(node);+}++} // namespace ocl+} // namespace cldnn++BIND_BINARY_BUFFER_WITH_TYPE(cldnn::ocl::fully_connected_ternocl_int2)++#endif // OV_GPU_WITH_OCL_RTdiff --git a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/ternocl_int2/fully_connected_ternocl_int2.hpp b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/ternocl_int2/fully_connected_ternocl_int2.hppnew file mode 100644index 00000000000..236f57d03c9--- /dev/null+++ b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/ternocl_int2/fully_connected_ternocl_int2.hpp@@ -0,0 +1,189 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#pragma once++#include <cmath>+#include <memory>+#include <optional>+#include <string>+#include <vector>++#include "activation_inst.h"+#include "data_inst.h"+#include "eltwise_inst.h"+#include "fully_connected_inst.h"+#include "intel_gpu/graph/fused_primitive_desc.hpp"+#include "intel_gpu/runtime/debug_configuration.hpp"+#include "registry/implementation_manager.hpp"++namespace cldnn {+namespace ocl {++// Ternary weights are 2 bits per value in groups of 128 along K, one f16 scale per group.+inline constexpr size_t kTernoclGroupSize = 128;+inline constexpr size_t kTernoclPackFactor = 16;++// Epilogue folded into the kernel; the value is passed to it as the POSTOP macro.+enum class TernoclPostop : int {+ none = 0,+ silu_mul = 1, // silu(acc) * other (gate/up)+ residual_add = 2, // acc + other+ bias = 3, // acc + bias+ sigmoid = 4, // sigmoid(acc)+};++inline bool ternocl_postop_reads_other(TernoclPostop p) {+ return p == TernoclPostop::silu_mul || p == TernoclPostop::residual_add;+}++// The epilogue for a fused chain, or nullopt when it has no single-pass equivalent.+// `other_dep` receives the dependency index of the eltwise operand.+inline std::optional<TernoclPostop> ternocl_int2_postop(const std::vector<fused_primitive_desc>& fused, bool has_bias, size_t* other_dep = nullptr) {+ if (fused.empty())+ return has_bias ? TernoclPostop::bias : TernoclPostop::none;+ if (has_bias)+ return std::nullopt;+ const auto act0 = std::dynamic_pointer_cast<const activation>(fused[0].desc);+ const auto elt_last = std::dynamic_pointer_cast<const eltwise>(fused.back().desc);+ if (elt_last && other_dep != nullptr)+ *other_dep = static_cast<size_t>(fused.back().outer_dep_start_idx);+ if (fused.size() == 2 && act0 && act0->activation_function == activation_func::swish && elt_last && elt_last->mode == eltwise_mode::prod)+ return TernoclPostop::silu_mul;+ if (fused.size() == 1 && elt_last && elt_last->mode == eltwise_mode::sum)+ return TernoclPostop::residual_add;+ if (fused.size() == 1 && act0 && act0->activation_function == activation_func::logistic)+ return TernoclPostop::sigmoid;+ return std::nullopt;+}++// The kernels read the grouped f16 scales as [groups, N]. With transpose_b_scale the scales are+// [N, groups], which prepare_quantization reorders to fbyx, i.e. that physical layout (a single+// group is not reordered: [N, 1] in bfyx is the same); otherwise they are [groups, N] in bfyx.+inline bool ternocl_scales_group_major(const layout& l, bool transpose_b_scale, int64_t N, int64_t G) {+ if (l.data_type != data_types::f16 || l.data_padding || l.is_dynamic())+ return false;+ const auto& ps = l.get_partial_shape();+ if (ps.size() < 2)+ return false;+ for (size_t i = 2; i < ps.size(); ++i) {+ if (ps[i].get_length() != 1)+ return false;+ }+ const auto d0 = ps[0].get_length();+ const auto d1 = ps[1].get_length();+ if (transpose_b_scale)+ return d0 == N && d1 == G && (l.format == format::fbyx || (G == 1 && l.format == format::bfyx));+ return d0 == G && d1 == N && l.format == format::bfyx;+}++// Weight-only-quantized FullyConnected on 2-bit ternary weights, executed by the+// TernOCL int2 x f16 up-convert OpenCL kernels (fp16 DPAS). OpenVINO has no+// signed 2-bit type, so ternary weights arrive as u2 codes {0,1,2} plus a zero+// point of 1. The impl requests format::is_os_yx_isv16_ternary through its weights+// reorder params: the weights are re-encoded to the kernel's {0,1,3} and packed by+// TernoclInt2WeightsReorderImplementationManager when the program folds its constants.+struct TernoclInt2FCImplementationManager : public ImplementationManager {+ OV_GPU_PRIMITIVE_IMPL("TernoclInt2FCImplementationManager")+ TernoclInt2FCImplementationManager(shape_types shape_type, ValidateFunc vf = nullptr) : ImplementationManager(impl_types::ocl, shape_type, vf) {}++ std::unique_ptr<primitive_impl> create_impl(const program_node& node, const kernel_impl_params& params) const override;+ std::unique_ptr<primitive_impl> create_impl(const kernel_impl_params& params) const override;+ in_out_fmts_t query_formats(const program_node& node) const override;++ bool validate_impl(const program_node& node) const override {+ assert(node.is_type<fully_connected>());+ const auto& fc_node = node.as<fully_connected>();+ const auto& fc_prim = fc_node.get_primitive();+ if (!node.get_program().get_config().get_enable_ternocl_int2())+ return false;+ // The kernels use SIMD16 DPAS and 2D block loads.+ const auto& device_info = node.get_program().get_engine().get_device_info();+ if (device_info.arch < gpu_arch::xe2 || !device_info.supports_immad)+ return false;+#define TERNOCL_REJECT(reason) \+ do { \+ GPU_DEBUG_TRACE_DETAIL << "[ternocl-int2] reject " << fc_node.id() << ": " << (reason) << std::endl; \+ /* no other impl accepts a fused Hadamard input: fail here with the reason */ \+ OPENVINO_ASSERT(fc_prim->hadamard_block == 0, \+ "[GPU] ternocl int2: ", \+ fc_node.id(), \+ " carries a Hadamard input transform but the TernOCL impl rejected it: ", \+ (reason)); \+ return false; \+ } while (0)++ if (!fc_prim->compressed_weights)+ TERNOCL_REJECT("not compressed_weights");+ if (fc_node.weights().get_output_layout(false).data_type != data_types::u2)+ TERNOCL_REJECT("weights are not u2");+ if (!fc_node.weights().is_type<data>())+ TERNOCL_REJECT("weights are not a constant");+ // Ternary {-1, 0, +1} arrives as u2 codes {0, 1, 2} with a scalar zero point of 1.+ if (!fc_prim->decompression_zero_point_scalar.has_value() || std::lround(fc_prim->decompression_zero_point_scalar.value()) != 1)+ TERNOCL_REJECT("zero point is not the scalar 1");++ const auto& in_layout = fc_node.get_input_layout(0);+ const auto& out_layout = fc_node.get_output_layout(0);+ if (in_layout.data_type != data_types::f16)+ TERNOCL_REJECT("activations are not f16");+ if (out_layout.data_type != data_types::f16 && out_layout.data_type != data_types::f32)+ TERNOCL_REJECT("output is not f16 or f32");+ if (in_layout.format != format::bfyx || out_layout.format != format::bfyx)+ TERNOCL_REJECT("unsupported activation format");+ if (in_layout.data_padding || out_layout.data_padding)+ TERNOCL_REJECT("padded activations");++ // A constant bias folds into the epilogue (TernoclPostop::bias); it has the output type.+ if (fc_prim->bias.is_valid()) {+ if (!fc_node.bias().is_type<data>())+ TERNOCL_REJECT("bias is not a constant");+ if (fc_node.bias().get_output_layout(false).data_type != out_layout.data_type)+ TERNOCL_REJECT("bias type differs from the output type");+ }+ size_t other_dep = 0;+ const auto postop = ternocl_int2_postop(fc_node.get_fused_primitives(), fc_prim->bias.is_valid(), &other_dep);+ if (!postop)+ TERNOCL_REJECT("fused chain has no folded epilogue");+ if (ternocl_postop_reads_other(*postop) &&+ (other_dep >= fc_node.get_dependencies().size() || fc_node.get_dependency(other_dep).get_output_layout(false).data_type != data_types::f16))+ TERNOCL_REJECT("eltwise operand is not f16");++ // Weight layouts are canonicalized to 4D, so [N, K] arrives as [N, K, 1, 1].+ const auto& wei_pshape = fc_node.weights().get_output_layout(false).get_partial_shape();+ if (wei_pshape.is_dynamic() || wei_pshape.size() < 2)+ TERNOCL_REJECT("weights shape is not a static [N, K]: " + wei_pshape.to_string());+ for (size_t i = 2; i < wei_pshape.size(); ++i) {+ if (wei_pshape[i].get_length() != 1)+ TERNOCL_REJECT("weights shape is not a static [N, K]: " + wei_pshape.to_string());+ }+ const auto N = wei_pshape[0].get_length();+ const auto K = wei_pshape[1].get_length();+ if (K % static_cast<int64_t>(kTernoclGroupSize) != 0)+ TERNOCL_REJECT("K is not a multiple of the group size");+ // One lane per output column in 16-wide sub-group blocks; the tail is clipped, not padded.+ if (N % 16 != 0)+ TERNOCL_REJECT("N is not a multiple of 16");+ if (fc_prim->hadamard_block != 0 && (fc_prim->hadamard_block != 1024 || K % 1024 != 0))+ TERNOCL_REJECT("hadamard block must be 1024 and divide K");+ if (fc_prim->hadamard_block != 0 && !fc_prim->hadamard_signs.empty() && fc_prim->hadamard_signs.size() != static_cast<size_t>(K))+ TERNOCL_REJECT("hadamard signs length differs from K");++ const size_t scale_dep = fc_prim->bias.is_valid() ? 3 : 2;+ if (!fc_prim->decompression_scale.is_valid() || scale_dep >= fc_node.get_dependencies().size())+ TERNOCL_REJECT("no decompression scale");+ if (!ternocl_scales_group_major(fc_node.get_dependency(scale_dep).get_output_layout(false),+ fc_prim->transpose_b_scale,+ N,+ K / static_cast<int64_t>(kTernoclGroupSize)))+ TERNOCL_REJECT("decompression scales are not f16 [groups, N]: " + fc_node.get_dependency(scale_dep).get_output_layout(false).to_short_string());++ GPU_DEBUG_TRACE_DETAIL << "[ternocl-int2] accept " << fc_node.id() << std::endl;+ return true;+#undef TERNOCL_REJECT+ }+};++} // namespace ocl+} // namespace cldnndiff --git a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/ternocl_int2/ternocl_int2_weights_reorder.cpp b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/ternocl_int2/ternocl_int2_weights_reorder.cppnew file mode 100644index 00000000000..5d232726ff4--- /dev/null+++ b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/ternocl_int2/ternocl_int2_weights_reorder.cpp@@ -0,0 +1,136 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "ternocl_int2_weights_reorder.hpp"++#include <algorithm>+#include <atomic>+#include <cstdint>+#include <cstring>+#include <string>++#include "fully_connected_ternocl_int2.hpp"+#include "impls/cpu/cpu_impl_helpers.hpp"+#include "intel_gpu/runtime/memory.hpp"+#include "openvino/core/parallel.hpp"+#include "primitive_inst.h"+#include "registry/registry.hpp"+#include "reorder_inst.h"++namespace cldnn {+namespace ocl {++namespace {++// [N, K] u2 codes -> [K/16, N] uint32, re-encoding (code - 1) to the kernel's+// two's-complement {0, +1, -1} = {0, 1, 3}; row 16*kb+j of column n sits at bits [2j, 2j+1].+// The TernOCL FC impl only requests this layout for a scalar zero point of 1.+// u2 is little-endian inside each byte, so on a little-endian host the 16 codes of one word are+// 4 consecutive source bytes already at their output bit positions: each 2-bit field b1b0 maps+// 00->11, 01->00, 10->01.+// Returns false if a code is 3, which is not ternary.+bool pack_weights(const uint8_t* src, uint32_t* dst, size_t N, size_t K) {+ constexpr uint32_t lo = 0x55555555u;+ const size_t kblocks = K / kTernoclPackFactor;+ std::atomic<bool> ternary{true};+ ov::parallel_for(kblocks, [&](size_t kb) {+ uint32_t invalid = 0;+ for (size_t n = 0; n < N; ++n) {+ uint32_t w;+ std::memcpy(&w, src + (n * K + kb * kTernoclPackFactor) / 4, sizeof(w));+ const uint32_t b0 = w & lo;+ const uint32_t b1 = (w >> 1) & lo;+ invalid |= b0 & b1;+ dst[kb * N + n] = (~b0 & lo) | ((~(b0 ^ b1) & lo) << 1);+ }+ if (invalid != 0)+ ternary = false;+ });+ return ternary;+}++} // namespace++struct ternocl_int2_weights_reorder : public typed_primitive_impl<reorder> {+ using parent = typed_primitive_impl<reorder>;++ DECLARE_OBJECT_TYPE_SERIALIZATION(cldnn::ocl::ternocl_int2_weights_reorder)++ // Used by deserialization, whose load() restores the kernel name.+ ternocl_int2_weights_reorder() = default;+ explicit ternocl_int2_weights_reorder(const std::string& kernel_name) : parent(kernel_name) {}++ std::unique_ptr<primitive_impl> clone() const override {+ return std::make_unique<ternocl_int2_weights_reorder>(*this);+ }++ bool is_cpu() const override {+ return true;+ }++ void init_kernels(const kernels_cache&, const kernel_impl_params&) override {}+ void update(primitive_inst&, const kernel_impl_params&) override {}++ event::ptr execute_impl(const std::vector<event::ptr>& events, reorder_inst& instance) override {+ auto& stream = instance.get_network().get_stream();+ stream.wait_for_events(events);++ const auto& in_layout = instance.get_impl_params()->get_input_layout(0);+ const auto& shape = in_layout.get_shape();+ const size_t N = shape[0];+ const size_t K = shape[1];+ OPENVINO_ASSERT(ov::shape_size(shape) == N * K && K % kTernoclPackFactor == 0,+ "[GPU] ternocl int2: unexpected weights shape ",+ in_layout.to_short_string(),+ " for ",+ instance.id());++ cldnn::mem_lock<uint8_t, mem_lock_type::read> src(instance.input_memory_ptr(), stream);+ cldnn::mem_lock<uint32_t, mem_lock_type::write> dst(instance.output_memory_ptr(), stream);+ OPENVINO_ASSERT(src.size() >= N * K / 4 && dst.size() * sizeof(uint32_t) >= N * K / 4,+ "[GPU] ternocl int2: weight buffers are smaller than ",+ N * K / 4,+ " B for ",+ instance.id());+ OPENVINO_ASSERT(pack_weights(src.data(), dst.data(), N, K),+ "[GPU] ternocl int2: ",+ instance.id(),+ " has a weight code outside the ternary range {-1, 0, +1}");++ return cpu::make_output_event(stream, instance.is_output());+ }+};++// A forced impl type (unit tests) skips validate() and takes the first manager of that type,+// so reorders other than the TernOCL weights packing are handed to the next manager of the type.+static const ImplementationManager& stock_reorder_manager(const ImplementationManager& self, shape_types shape_type) {+ for (const auto& m : ov::intel_gpu::Registry<reorder>::get_implementations()) {+ if (m->get_impl_type() == self.get_impl_type() && m->get_type_info() != self.get_type_info() && (m->get_shape_type() & shape_type) == shape_type)+ return *m;+ }+ OPENVINO_THROW("[GPU] ternocl int2: no reorder implementation to fall back to");+}++std::unique_ptr<primitive_impl> TernoclInt2WeightsReorderImplementationManager::create_impl(const program_node& node, const kernel_impl_params& params) const {+ if (!validate_impl(node))+ return stock_reorder_manager(*this, get_shape_type(node)).create_impl(node, params);+ return std::make_unique<ternocl_int2_weights_reorder>("ternocl_int2_weights_reorder");+}++std::unique_ptr<primitive_impl> TernoclInt2WeightsReorderImplementationManager::create_impl(const kernel_impl_params& params) const {+ if (params.get_output_layout().format != format::is_os_yx_isv16_ternary)+ return stock_reorder_manager(*this, get_shape_type(params)).create_impl(params);+ return std::make_unique<ternocl_int2_weights_reorder>("ternocl_int2_weights_reorder");+}++in_out_fmts_t TernoclInt2WeightsReorderImplementationManager::query_formats(const program_node& node) const {+ if (!validate_impl(node))+ return stock_reorder_manager(*this, get_shape_type(node)).query_formats(node);+ return ImplementationManager::query_formats(node);+}++} // namespace ocl+} // namespace cldnn++BIND_BINARY_BUFFER_WITH_TYPE(cldnn::ocl::ternocl_int2_weights_reorder)diff --git a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/ternocl_int2/ternocl_int2_weights_reorder.hpp b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/ternocl_int2/ternocl_int2_weights_reorder.hppnew file mode 100644index 00000000000..659f63c5e83--- /dev/null+++ b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/ternocl_int2/ternocl_int2_weights_reorder.hpp@@ -0,0 +1,40 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#pragma once++#include <memory>++#include "intel_gpu/primitives/reorder.hpp"+#include "program_node.h"+#include "registry/implementation_manager.hpp"++namespace cldnn {+namespace ocl {++// Packs the ternary u2 weights of a TernOCL FullyConnected into format::is_os_yx_isv16_ternary.+// The FC impl requests this layout through its weights reorder params, so post_optimize_weights+// inserts the reorder and propagate_constants folds it at build time: the packed weights are an+// ordinary constant of the program and the source constant is left untouched for any other user.+// The packing runs on the host (it also checks that every code is ternary), hence impl_types::cpu.+struct TernoclInt2WeightsReorderImplementationManager : public ImplementationManager {+ OV_GPU_PRIMITIVE_IMPL("TernoclInt2WeightsReorderImplementationManager")+ explicit TernoclInt2WeightsReorderImplementationManager(shape_types shape_type, ValidateFunc vf = nullptr)+ : ImplementationManager(impl_types::cpu, shape_type, vf) {}++ std::unique_ptr<primitive_impl> create_impl(const program_node& node, const kernel_impl_params& params) const override;+ std::unique_ptr<primitive_impl> create_impl(const kernel_impl_params& params) const override;+ in_out_fmts_t query_formats(const program_node& node) const override;++ bool validate_impl(const program_node& node) const override {+ assert(node.is_type<reorder>());+ const auto& in = node.get_input_layout(0);+ const auto& out = node.get_output_layout(0);+ return out.format == format::is_os_yx_isv16_ternary && out.data_type == data_types::u2 && in.data_type == data_types::u2 &&+ (in.format == format::bfyx || in.format == format::oiyx) && !in.data_padding && in.is_static();+ }+};++} // namespace ocl+} // namespace cldnndiff --git a/src/plugins/intel_gpu/src/graph/impls/onednn/fully_connected_onednn.hpp b/src/plugins/intel_gpu/src/graph/impls/onednn/fully_connected_onednn.hppindex 4c21cd4e55c..96c5b45aa64 100644--- a/src/plugins/intel_gpu/src/graph/impls/onednn/fully_connected_onednn.hpp+++ b/src/plugins/intel_gpu/src/graph/impls/onednn/fully_connected_onednn.hpp@@ -40,6 +40,11 @@ struct FullyConnectedImplementationManager : public ImplementationManager {auto out_dt = out_layout.data_type;auto fc_prim = fc_node.get_primitive();+ // A fused Hadamard input transform is applied only by the TernOCL impl.+ if (fc_prim->hadamard_block != 0) {+ LOG_AND_RETURN_FALSE(node);+ }+if (one_of(data_types::i64, {in0_dt, wei_dt})) {LOG_AND_RETURN_FALSE(node);}diff --git a/src/plugins/intel_gpu/src/graph/primitive_inst.cpp b/src/plugins/intel_gpu/src/graph/primitive_inst.cppindex df7f7074e48..9607ea5a236 100644--- a/src/plugins/intel_gpu/src/graph/primitive_inst.cpp+++ b/src/plugins/intel_gpu/src/graph/primitive_inst.cpp@@ -3400,9 +3400,11 @@ bool primitive_inst::is_valid_fusion() const {if (!get_node().get_selected_impl()) {LOG_AND_RETURN_FALSE(_node);}+ // ternocl_int2 folds its fused chain into the GEMM epilogue itself (see its validate_impl).if (!data_type_traits::is_i8_u8(get_node().get_input_layout(0).data_type) &&(get_node().get_selected_impl()->get_kernel_name().find("fully_connected_gpu_bf_tiled") == std::string::npos) &&- (get_node().get_selected_impl()->get_kernel_name().find("fully_connected_gpu_bfyx_ref") == std::string::npos)) {+ (get_node().get_selected_impl()->get_kernel_name().find("fully_connected_gpu_bfyx_ref") == std::string::npos) &&+ (get_node().get_selected_impl()->get_kernel_name() != "ternocl_int2")) {LOG_AND_RETURN_FALSE(_node);}}diff --git a/src/plugins/intel_gpu/src/graph/registry/fully_connected_impls.cpp b/src/plugins/intel_gpu/src/graph/registry/fully_connected_impls.cppindex 61a3567d08a..2834488c6d5 100644--- a/src/plugins/intel_gpu/src/graph/registry/fully_connected_impls.cpp+++ b/src/plugins/intel_gpu/src/graph/registry/fully_connected_impls.cpp@@ -10,6 +10,13 @@#if OV_GPU_WITH_ONEDNN#include "impls/onednn/fully_connected_onednn.hpp"#endif+// The TernOCL int2 impl builds its programs on the OpenCL engine's context.+#if OV_GPU_WITH_OCL && defined(OV_GPU_WITH_OCL_RT)+# include "impls/ocl_v2/ternocl_int2/fully_connected_ternocl_int2.hpp"+# define OV_GPU_CREATE_INSTANCE_TERNOCL(...) OV_GPU_CREATE_INSTANCE_OCL(__VA_ARGS__)+#else+# define OV_GPU_CREATE_INSTANCE_TERNOCL(...)+#endifnamespace ov::intel_gpu {@@ -19,15 +26,24 @@ const std::vector<std::shared_ptr<cldnn::ImplementationManager>>& Registry<fullystatic const auto ocl_supports_weights_layout = [](const program_node& node) {return node.as<fully_connected>().get_primitive()->weights_transposed;};+ // A fused Hadamard input transform is applied only by the TernOCL impl.+ static const auto no_hadamard_input = [](const program_node& node) {+ return node.as<fully_connected>().get_primitive()->hadamard_block == 0;+ };static const std::vector<std::shared_ptr<ImplementationManager>> impls = {+ OV_GPU_CREATE_INSTANCE_TERNOCL(cldnn::ocl::TernoclInt2FCImplementationManager, shape_types::dynamic_shape)+ OV_GPU_CREATE_INSTANCE_TERNOCL(cldnn::ocl::TernoclInt2FCImplementationManager, shape_types::static_shape)OV_GPU_CREATE_INSTANCE_ONEDNN(onednn::FullyConnectedImplementationManager, shape_types::static_shape)- OV_GPU_GET_INSTANCE_OCL(fully_connected, shape_types::static_shape, ocl_supports_weights_layout)+ OV_GPU_GET_INSTANCE_OCL(fully_connected, shape_types::static_shape,+ [](const program_node& node) {+ return ocl_supports_weights_layout(node) && no_hadamard_input(node);+ })OV_GPU_GET_INSTANCE_OCL(fully_connected, shape_types::dynamic_shape,[](const program_node& node) {if (node.can_use(impl_types::onednn))return false;- if (!ocl_supports_weights_layout(node))+ if (!ocl_supports_weights_layout(node) || !no_hadamard_input(node))return false;return node.get_output_pshape().size() <= 3;})diff --git a/src/plugins/intel_gpu/src/graph/registry/reorder_impls.cpp b/src/plugins/intel_gpu/src/graph/registry/reorder_impls.cppindex aa1089ec5cf..451c7baf0b8 100644--- a/src/plugins/intel_gpu/src/graph/registry/reorder_impls.cpp+++ b/src/plugins/intel_gpu/src/graph/registry/reorder_impls.cpp@@ -14,6 +14,13 @@#if OV_GPU_WITH_OCL#include "impls/ocl/reorder.hpp"#endif+// Packs the weights of the TernOCL int2 FullyConnected impl, so it is registered wherever that impl is.+#if OV_GPU_WITH_OCL && defined(OV_GPU_WITH_OCL_RT)+# include "impls/ocl_v2/ternocl_int2/ternocl_int2_weights_reorder.hpp"+# define OV_GPU_CREATE_INSTANCE_TERNOCL(...) OV_GPU_CREATE_INSTANCE_OCL(__VA_ARGS__)+#else+# define OV_GPU_CREATE_INSTANCE_TERNOCL(...)+#endifnamespace ov::intel_gpu {@@ -41,6 +48,7 @@ static std::vector<format> supported_dyn_formats = {const std::vector<std::shared_ptr<cldnn::ImplementationManager>>& Registry<reorder>::get_implementations() {static const std::vector<std::shared_ptr<ImplementationManager>> impls = {+ OV_GPU_CREATE_INSTANCE_TERNOCL(ocl::TernoclInt2WeightsReorderImplementationManager, shape_types::static_shape)OV_GPU_CREATE_INSTANCE_ONEDNN(onednn::ReorderImplementationManager, shape_types::static_shape, not_in_shape_flow())OV_GPU_CREATE_INSTANCE_OCL(ocl::ReorderImplementationManager, shape_types::static_shape, not_in_shape_flow())OV_GPU_CREATE_INSTANCE_OCL(ocl::ReorderImplementationManager, shape_types::dynamic_shape,diff --git a/src/plugins/intel_gpu/src/plugin/ops/fully_connected.cpp b/src/plugins/intel_gpu/src/plugin/ops/fully_connected.cppindex b51fbb00fc1..9370818bea4 100644--- a/src/plugins/intel_gpu/src/plugin/ops/fully_connected.cpp+++ b/src/plugins/intel_gpu/src/plugin/ops/fully_connected.cpp@@ -12,6 +12,7 @@#include "intel_gpu/primitives/fully_connected.hpp"#include "intel_gpu/primitives/reshape.hpp"#include "intel_gpu/primitives/reorder.hpp"+#include "plugin/transformations/fuse_hadamard_fc.hpp"namespace ov {namespace op {@@ -71,6 +72,14 @@ static void CreateFullyConnectedCompressedOp(ProgramBuilder& p, const std::sharefc.decompression_zero_point_scalar = zp_value;}+ // Input rotation absorbed by FuseHadamardIntoFC.+ const auto& rt = op->get_rt_info();+ if (auto it = rt.find(int2_hadamard_block_key); it != rt.end()) {+ fc.hadamard_block = static_cast<size_t>(it->second.as<int64_t>());+ if (auto st = rt.find(int2_hadamard_signs_key); st != rt.end())+ fc.hadamard_signs = st->second.as<std::vector<int8_t>>();+ }+p.add_primitive(*op, fc);if (op->get_input_partial_shape(0).size() > 3 && !p.use_new_shape_infer()) {diff --git a/src/plugins/intel_gpu/src/plugin/ops/rope.cpp b/src/plugins/intel_gpu/src/plugin/ops/rope.cppindex 23bfbbaf903..d6849073b83 100644--- a/src/plugins/intel_gpu/src/plugin/ops/rope.cpp+++ b/src/plugins/intel_gpu/src/plugin/ops/rope.cpp@@ -7,6 +7,7 @@#include "intel_gpu/plugin/common_utils.hpp"#include "intel_gpu/primitives/rope.hpp"#include "intel_gpu/primitives/permute.hpp"+#include "plugin/transformations/fuse_rms_rope.hpp"namespace ov {namespace op {@@ -30,10 +31,21 @@ static void CreateRoPEOp(ProgramBuilder& p, const std::shared_ptr<op::internal::OPENVINO_ASSERT(!config.is_interleaved || !config.output_trans0213, "[GPU] Unsupported ROPE parameters");+ const auto& rt_info = op->get_rt_info();+ const auto fused_rms = rt_info.find(fuse_rms_rope_epsilon_key);+ const bool fuse_rms_norm = fused_rms != rt_info.end();+ float rms_epsilon = 0.0f;+ if (fuse_rms_norm) {+ OPENVINO_ASSERT(inputs.size() == 4 && gather_rank == 0, "[GPU] Invalid fused RMSNorm and RoPE inputs");+ rms_epsilon = fused_rms->second.as<float>();+ }+auto rope = cldnn::rope(layer_type_name_ID(op),inputs,config,- gather_rank);+ gather_rank,+ fuse_rms_norm,+ rms_epsilon);p.add_primitive(*op, rope);}diff --git a/src/plugins/intel_gpu/src/plugin/transformations/fuse_hadamard_fc.cpp b/src/plugins/intel_gpu/src/plugin/transformations/fuse_hadamard_fc.cppnew file mode 100644index 00000000000..35d6920c12c--- /dev/null+++ b/src/plugins/intel_gpu/src/plugin/transformations/fuse_hadamard_fc.cpp@@ -0,0 +1,135 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "fuse_hadamard_fc.hpp"++#include <bitset>+#include <cmath>++#include "intel_gpu/op/fully_connected.hpp"+#include "intel_gpu/op/fully_connected_compressed.hpp"+#include "intel_gpu/runtime/debug_configuration.hpp"+#include "openvino/op/constant.hpp"+#include "openvino/op/convert.hpp"+#include "openvino/op/matmul.hpp"+#include "openvino/op/multiply.hpp"+#include "openvino/op/reshape.hpp"+#include "openvino/op/transpose.hpp"++namespace ov::intel_gpu {++namespace {++constexpr size_t kBlock = 1024;++std::shared_ptr<ov::op::v0::Constant> constant_behind(const ov::Output<ov::Node>& out) {+ auto node = out.get_node_shared_ptr();+ // ConvertMatMulToFullyConnected leaves Convert(Transpose(H)); H is symmetric.+ for (int i = 0; i < 3; ++i) {+ if (ov::as_type_ptr<ov::op::v0::Convert>(node) || ov::as_type_ptr<ov::op::v1::Transpose>(node))+ node = node->get_input_node_shared_ptr(0);+ }+ return ov::as_type_ptr<ov::op::v0::Constant>(node);+}++// The normalised Sylvester H_1024: +1/32 everywhere in row/column 0, and+// H[i][j] = (-1)^popcount(i & j) / 32. Checking a stride of rows is enough to+// tell it from any other 1024x1024 constant.+bool is_hadamard_1024(const std::shared_ptr<ov::op::v0::Constant>& c) {+ if (!c)+ return false;+ const auto& s = c->get_shape();+ if (s.size() != 2 || s[0] != kBlock || s[1] != kBlock)+ return false;+ const auto v = c->cast_vector<float>();+ const float want = 1.0f / 32.0f;+ for (size_t i = 0; i < kBlock; i += 37) {+ for (size_t j = 0; j < kBlock; j += 41) {+ const float sign = (std::bitset<32>(i & j).count() & 1) ? -1.0f : 1.0f;+ if (std::fabs(v[i * kBlock + j] - sign * want) > 1e-4f)+ return false;+ }+ }+ return true;+}++} // namespace++bool FuseHadamardIntoFC::run_on_model(const std::shared_ptr<ov::Model>& model) {+ size_t fused = 0;+ for (const auto& node : model->get_ordered_ops()) {+ auto fc = ov::as_type_ptr<op::FullyConnectedCompressed>(node);+ if (!fc)+ continue;+ const auto& wshape = fc->get_input_partial_shape(1);+ if (wshape.rank().is_dynamic() || wshape.rank().get_length() < 2 || !wshape[1].is_static())+ continue;+ const size_t K = static_cast<size_t>(wshape[1].get_length());+ if (K % kBlock != 0)+ continue;++ // Reshape back to [..., K]+ auto back = ov::as_type_ptr<ov::op::v1::Reshape>(fc->get_input_node_shared_ptr(0));+ if (!back) {+ GPU_DEBUG_TRACE_DETAIL << "[hadamard-fc] " << fc->get_friendly_name() << ": input is " << fc->get_input_node_shared_ptr(0)->get_type_name()+ << std::endl;+ continue;+ }+ // MatMul / FullyConnected with the H constant+ auto mm = back->get_input_node_shared_ptr(0);+ std::shared_ptr<ov::op::v0::Constant> h;+ if (ov::as_type_ptr<ov::op::v0::MatMul>(mm) || ov::as_type_ptr<op::FullyConnected>(mm))+ h = constant_behind(mm->input_value(1));+ if (!is_hadamard_1024(h)) {+ GPU_DEBUG_TRACE_DETAIL << "[hadamard-fc] " << fc->get_friendly_name() << ": no H_1024 constant behind " << mm->get_type_name() << std::endl;+ continue;+ }+ // Reshape to [..., K/1024, 1024]+ auto fwd = ov::as_type_ptr<ov::op::v1::Reshape>(mm->get_input_node_shared_ptr(0));+ if (!fwd)+ continue;+ ov::Output<ov::Node> x = fwd->input_value(0);+ std::vector<int8_t> signs;+ if (auto mul = ov::as_type_ptr<ov::op::v1::Multiply>(x.get_node_shared_ptr())) {+ std::shared_ptr<ov::op::v0::Constant> sc;+ size_t data_port = 0;+ for (size_t p = 0; p < 2 && !sc; ++p) {+ sc = constant_behind(mul->input_value(p));+ data_port = 1 - p;+ }+ if (sc && ov::shape_size(sc->get_shape()) == K) {+ const auto vals = sc->cast_vector<float>();+ bool ok = true;+ signs.resize(K);+ for (size_t i = 0; i < K && ok; ++i) {+ ok = std::fabs(std::fabs(vals[i]) - 1.0f) < 1e-6f;+ signs[i] = vals[i] < 0 ? -1 : 1;+ }+ if (ok) {+ x = mul->input_value(data_port);+ } else {+ signs.clear();+ }+ }+ }+ // The Reshape to [..., K/1024, 1024] already pins the source's last dim+ // to K; it only needs to be checked when the graph states it.+ const auto& xs = x.get_partial_shape();+ if (xs.rank().is_dynamic() || (xs[xs.rank().get_length() - 1].is_static() && static_cast<size_t>(xs[xs.rank().get_length() - 1].get_length()) != K)) {+ GPU_DEBUG_TRACE_DETAIL << "[hadamard-fc] " << fc->get_friendly_name() << ": source shape " << xs << " does not end in K=" << K << std::endl;+ continue;+ }+ fc->input(0).replace_source_output(x);+ auto& rt = fc->get_rt_info();+ rt[int2_hadamard_block_key] = static_cast<int64_t>(kBlock);+ rt[int2_hadamard_signs_key] = signs;+ ++fused;+ GPU_DEBUG_TRACE_DETAIL << "[hadamard-fc] fused into " << fc->get_friendly_name() << " K=" << K << " signs=" << (signs.empty() ? "folded" : "explicit")+ << std::endl;+ }+ GPU_DEBUG_TRACE << "[hadamard-fc] fused " << fused << " input rotations" << std::endl;+ return fused != 0;+}++} // namespace ov::intel_gpudiff --git a/src/plugins/intel_gpu/src/plugin/transformations/fuse_hadamard_fc.hpp b/src/plugins/intel_gpu/src/plugin/transformations/fuse_hadamard_fc.hppnew file mode 100644index 00000000000..c0b4da9c491--- /dev/null+++ b/src/plugins/intel_gpu/src/plugin/transformations/fuse_hadamard_fc.hpp@@ -0,0 +1,30 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#pragma once++#include "openvino/pass/pass.hpp"++namespace ov::intel_gpu {++// rt_info keys carried on a FullyConnectedCompressed whose input transform was+// absorbed; the FC translator moves them onto the cldnn primitive.+inline constexpr char int2_hadamard_block_key[] = "int2_hadamard_block";+inline constexpr char int2_hadamard_signs_key[] = "int2_hadamard_signs";++// Folds the graph-level input rotation of Hadamard-basis checkpoints (Bonsai 2)+//+// x -> [Multiply(+-1 signs)] -> Reshape(..., K/1024, 1024) -> MatMul(H_1024)+// -> Reshape(..., K) -> FullyConnectedCompressed(u2)+//+// into the FullyConnected itself, which then runs one fused sign+FWHT kernel in+// front of its GEMV instead of three graph primitives. Only the TernOCL int2 FC+// implementation honours the resulting primitive fields.+class FuseHadamardIntoFC : public ov::pass::ModelPass {+public:+ OPENVINO_MODEL_PASS_RTTI("FuseHadamardIntoFC");+ bool run_on_model(const std::shared_ptr<ov::Model>& model) override;+};++} // namespace ov::intel_gpudiff --git a/src/plugins/intel_gpu/src/plugin/transformations/fuse_rms_rope.cpp b/src/plugins/intel_gpu/src/plugin/transformations/fuse_rms_rope.cppnew file mode 100644index 00000000000..58c441e97dd--- /dev/null+++ b/src/plugins/intel_gpu/src/plugin/transformations/fuse_rms_rope.cpp@@ -0,0 +1,87 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "fuse_rms_rope.hpp"++#include "intel_gpu/runtime/debug_configuration.hpp"+#include "openvino/core/graph_util.hpp"+#include "openvino/core/rt_info.hpp"+#include "openvino/core/shape.hpp"+#include "openvino/op/reshape.hpp"+#include "openvino/op/transpose.hpp"+#include "ov_ops/rms.hpp"+#include "ov_ops/rotary_positional_embeddings.hpp"++namespace ov::intel_gpu {++bool FuseRMSRoPE::run_on_model(const std::shared_ptr<ov::Model>& model) {+ size_t fused = 0;++ for (const auto& node : model->get_ordered_ops()) {+ auto rope = ov::as_type_ptr<ov::op::internal::RoPE>(node);+ if (!rope)+ continue;++ const auto& config = rope->get_config();++ if (rope->get_input_size() != 3 || config.gather_position_arg_id != 0 || config.is_qwen || config.is_chatglm || config.is_ltx_video ||+ config.is_interleaved || config.input_interleaved || config.output_trans0213 || config.slice_start != 0 || config.slice_stop != 0 ||+ rope->get_input_element_type(0) != ov::element::f16) {+ continue;+ }++ // Full-head RotateHalf only: the fused kernel normalizes exactly the rotated elements.+ const auto& rope_shape = rope->get_input_partial_shape(0);+ if (rope_shape.rank().is_dynamic() || rope_shape.rank().get_length() != 4 || !rope_shape[3].is_static())+ continue;+ const auto head_size = static_cast<size_t>(rope_shape[3].get_length());+ // rope_opt reduces the head only on its 16-wide f16 path: f16 cos/sin and head_size % 32 == 0.+ if (head_size != config.rotary_ndims || head_size % 32 != 0 || rope->get_input_element_type(1) != ov::element::f16 ||+ rope->get_input_element_type(2) != ov::element::f16)+ continue;++ // The RMSNorm either feeds RoPE directly (transpose already absorbed) or through a single view.+ const auto producer = rope->get_input_node_shared_ptr(0);+ auto rms = ov::as_type_ptr<ov::op::internal::RMS>(producer);+ std::shared_ptr<ov::Node> view;+ if (!rms) {+ if ((!ov::is_type<ov::op::v1::Reshape>(producer) && !ov::is_type<ov::op::v1::Transpose>(producer)) ||+ producer->output(0).get_target_inputs().size() != 1) {+ continue;+ }+ view = producer;+ rms = ov::as_type_ptr<ov::op::internal::RMS>(view->get_input_node_shared_ptr(0));+ }++ if (!rms || !rms->get_elementwise_affine() || rms->get_input_size() != 2 || rms->output(0).get_target_inputs().size() != 1 ||+ rms->get_output_element_type(0) != ov::element::f16 || rms->get_input_element_type(1) != ov::element::f16) {+ continue;+ }++ const auto gamma_shape = rms->get_input_partial_shape(1);+ if (!gamma_shape.is_static() || ov::shape_size(gamma_shape.to_shape()) != head_size)+ continue;++ const ov::Output<ov::Node> rope_data = view ? view->output(0) : rms->input_value(0);+ ov::OutputVector inputs{rope_data, rope->input_value(1), rope->input_value(2), rms->input_value(1)};+ auto fused_rope = std::make_shared<ov::op::internal::RoPE>(inputs, config);+ fused_rope->set_friendly_name(rope->get_friendly_name());+ if (view) {+ ov::copy_runtime_info({rms, view, rope}, fused_rope);+ view->input(0).replace_source_output(rms->input_value(0));+ } else {+ ov::copy_runtime_info({rms, rope}, fused_rope);+ }+ fused_rope->get_rt_info()[fuse_rms_rope_epsilon_key] = static_cast<float>(rms->get_epsilon());++ ov::replace_node(rope, fused_rope);+ ++fused;+ GPU_DEBUG_TRACE_DETAIL << "[rms_rope] fused into " << fused_rope->get_friendly_name() << std::endl;+ }++ GPU_DEBUG_TRACE << "[rms_rope] fused " << fused << " RMSNorm + RoPE pairs" << std::endl;+ return fused > 0;+}++} // namespace ov::intel_gpudiff --git a/src/plugins/intel_gpu/src/plugin/transformations/fuse_rms_rope.hpp b/src/plugins/intel_gpu/src/plugin/transformations/fuse_rms_rope.hppnew file mode 100644index 00000000000..5de22294bd6--- /dev/null+++ b/src/plugins/intel_gpu/src/plugin/transformations/fuse_rms_rope.hpp@@ -0,0 +1,19 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#pragma once++#include "openvino/pass/manager.hpp"++namespace ov::intel_gpu {++inline constexpr char fuse_rms_rope_epsilon_key[] = "intel_gpu_fuse_rms_rope_epsilon";++class FuseRMSRoPE : public ov::pass::ModelPass {+public:+ OPENVINO_MODEL_PASS_RTTI("FuseRMSRoPE");+ bool run_on_model(const std::shared_ptr<ov::Model>& model) override;+};++} // namespace ov::intel_gpudiff --git a/src/plugins/intel_gpu/src/plugin/transformations_pipeline.cpp b/src/plugins/intel_gpu/src/plugin/transformations_pipeline.cppindex b3bad016ccb..4f26c385ccd 100644--- a/src/plugins/intel_gpu/src/plugin/transformations_pipeline.cpp+++ b/src/plugins/intel_gpu/src/plugin/transformations_pipeline.cpp@@ -106,8 +106,10 @@#include "plugin/transformations/fuse_gated_mlp.hpp"#include "plugin/transformations/fuse_atan2_decomposed.hpp"#include "plugin/transformations/fuse_grouped_depth_to_space.hpp"+#include "plugin/transformations/fuse_hadamard_fc.hpp"#include "plugin/transformations/fuse_moe_router.hpp"#include "plugin/transformations/fuse_moe_router_scale.hpp"+#include "plugin/transformations/fuse_rms_rope.hpp"#include "plugin/transformations/group_query_attention_decomposition.hpp"#include "plugin/transformations/increase_position_ids_precision.hpp"#include "plugin/transformations/indirect_kv_cache.hpp"@@ -1645,6 +1647,10 @@ void TransformationsPipeline::apply(std::shared_ptr<ov::Model> func) {pass_config->disable<ov::pass::RoPEFusionIOSlicing>();pass_config->disable<ov::pass::RoPEShareCosSin>();+ if (config.get_enable_rms_rope_fusion()) {+ manager.register_pass<ov::intel_gpu::FuseRMSRoPE>();+ }+manager.register_pass<ov::intel_gpu::IncreasePositionIdsPrecision>();manager.register_pass<ov::intel_gpu::FuseAtan2Decomposed>();if (device_info.supports_immad && config.get_use_onednn() && !disable_gated_mlp_fusion) {@@ -1748,11 +1754,25 @@ void TransformationsPipeline::apply(std::shared_ptr<ov::Model> func) {const bool disable_horizontal_fc_fusion = GPU_DEBUG_VALUE_OR(config.get_disable_horizontal_fc_fusion(), false);const bool disable_fc_swiglu_fusion = GPU_DEBUG_VALUE_OR(config.get_disable_fc_swiglu_fusion(), false);- // mlp fusion is only supported for cldnn on high performant GPUis+ // Ternary (u2) checkpoints on the TernOCL path run faster with gate/up merged into+ // one FC followed by the SwiGLU primitive.+ const bool ternocl_int2 = m_context->get_engine().runtime_type() == cldnn::runtime_types::ocl && config.get_enable_ternocl_int2() &&+ device_info.arch >= cldnn::gpu_arch::xe2 && device_info.supports_immad;+ bool has_u2_weights = false;+ for (const auto& op : func->get_ops()) {+ const auto c = ov::as_type_ptr<ov::op::v0::Constant>(op);+ if (c && c->get_element_type() == ov::element::u2) {+ has_u2_weights = true;+ break;+ }+ }+ const bool int2_merge_mlp = ternocl_int2 && has_u2_weights && !disable_fc_swiglu_fusion;bool fuse_mlp_swiglu = !config.get_use_onednn() &&!device_info.supports_immad &&device_info.execution_units_count >= 128 &&!disable_fc_swiglu_fusion;+ // Not bound by the 128-EU floor: on the 64-EU integrated Xe2 the merged int2 projection is still faster.+ fuse_mlp_swiglu |= int2_merge_mlp;if (!disable_horizontal_fc_fusion) {manager.register_pass<ov::intel_gpu::FullyConnectedHorizontalFusion>(fuse_mlp_swiglu);@@ -1765,6 +1785,12 @@ void TransformationsPipeline::apply(std::shared_ptr<ov::Model> func) {manager.register_pass<ov::intel_gpu::LoRAHorizontalFusion>();}}+ // After the horizontal fusion so a merged gate/up FC absorbs the shared+ // rotation once. Only the TernOCL impl applies a fused rotation, so without it+ // the rotation stays in the graph.+ if (ternocl_int2 && GPU_DEBUG_VALUE_OR(config.get_enable_hadamard_fc_fusion(), true)) {+ manager.register_pass<ov::intel_gpu::FuseHadamardIntoFC>();+ }// ZP should not be folded for FC. But still, ZP should be folded for Gather.// Therefore, run MarkDequantization again to fold ZP constant.diff --git a/src/plugins/intel_gpu/src/runtime/format.cpp b/src/plugins/intel_gpu/src/runtime/format.cppindex 28a18a3f1c2..577939b0e16 100644--- a/src/plugins/intel_gpu/src/runtime/format.cpp+++ b/src/plugins/intel_gpu/src/runtime/format.cpp@@ -202,6 +202,7 @@ static const std::map<format::type, format_traits> format_traits_map{FMT_TRAITS(gi_yxs_os_yxsv2_osv16, 1, 1, 2, 1, {0, 2, 3, 4, 1}, "giyxo", "oixy????g", {{0, 16}}, {{1, 16}}), // NOLINTFMT_TRAITS(giy_xs_os_xsv2_osv8__ao32, 1, 1, 2, 1, {0, 2, 3, 4, 1}, "giyxo", "oixy????g", {{2, 2}, {0, 8}}, {{4, 2}, {1, 8}}), // NOLINTFMT_TRAITS(giy_xs_os_xsv2_osv16__ao32, 1, 1, 2, 1, {0, 2, 3, 4, 1}, "giyxo", "oixy????g", {{2, 2}, {0, 16}}, {{4, 2}, {1, 16}}), // NOLINT+ FMT_TRAITS(is_os_yx_isv16_ternary, 1, 1, 2, 0, {1, 0, 2, 3}, "ioyx", "oixy", {{1, 16}}, {{1, 16}}), // NOLINT};const format_traits& format::traits(type fmt) {diff --git a/src/plugins/intel_gpu/tests/unit/sources.cmake b/src/plugins/intel_gpu/tests/unit/sources.cmakeindex 1a5b6afa388..db36ba66b55 100644--- a/src/plugins/intel_gpu/tests/unit/sources.cmake+++ b/src/plugins/intel_gpu/tests/unit/sources.cmake@@ -428,12 +428,16 @@ set(GPU_UNIT_TESTS_TRANSFORMATIONS_SRCS${CMAKE_HOME_DIRECTORY}/src/plugins/intel_gpu/src/plugin/transformations/fuse_grouped_depth_to_space.hpp${CMAKE_HOME_DIRECTORY}/src/plugins/intel_gpu/src/plugin/transformations/fuse_gated_mlp.cpp${CMAKE_HOME_DIRECTORY}/src/plugins/intel_gpu/src/plugin/transformations/fuse_gated_mlp.hpp+ ${CMAKE_HOME_DIRECTORY}/src/plugins/intel_gpu/src/plugin/transformations/fuse_hadamard_fc.cpp+ ${CMAKE_HOME_DIRECTORY}/src/plugins/intel_gpu/src/plugin/transformations/fuse_hadamard_fc.hpp${CMAKE_HOME_DIRECTORY}/src/plugins/intel_gpu/src/plugin/transformations/fuse_moe_router.cpp${CMAKE_HOME_DIRECTORY}/src/plugins/intel_gpu/src/plugin/transformations/fuse_moe_router.hpp${CMAKE_HOME_DIRECTORY}/src/plugins/intel_gpu/src/plugin/transformations/fuse_moe_router_scale.cpp${CMAKE_HOME_DIRECTORY}/src/plugins/intel_gpu/src/plugin/transformations/fuse_moe_router_scale.hpp${CMAKE_HOME_DIRECTORY}/src/plugins/intel_gpu/src/plugin/transformations/fuse_moe_shared_expert.cpp${CMAKE_HOME_DIRECTORY}/src/plugins/intel_gpu/src/plugin/transformations/fuse_moe_shared_expert.hpp+ ${CMAKE_HOME_DIRECTORY}/src/plugins/intel_gpu/src/plugin/transformations/fuse_rms_rope.cpp+ ${CMAKE_HOME_DIRECTORY}/src/plugins/intel_gpu/src/plugin/transformations/fuse_rms_rope.hpp${CMAKE_HOME_DIRECTORY}/src/plugins/intel_gpu/src/plugin/transformations/fuse_rope_input_deinterleave.cpp${CMAKE_HOME_DIRECTORY}/src/plugins/intel_gpu/src/plugin/transformations/fuse_rope_input_deinterleave.hpp${CMAKE_HOME_DIRECTORY}/src/plugins/intel_gpu/src/plugin/transformations/group_query_attention_decomposition.cppdiff --git a/src/plugins/intel_gpu/tests/unit/test_cases/fully_connected_gpu_test.cpp b/src/plugins/intel_gpu/tests/unit/test_cases/fully_connected_gpu_test.cppindex c0a7b19aec9..8f7327be7c3 100644--- a/src/plugins/intel_gpu/tests/unit/test_cases/fully_connected_gpu_test.cpp+++ b/src/plugins/intel_gpu/tests/unit/test_cases/fully_connected_gpu_test.cpp@@ -2,6 +2,7 @@// SPDX-License-Identifier: Apache-2.0//+#include "intel_gpu/primitives/activation.hpp"#include "intel_gpu/primitives/crop.hpp"#include "intel_gpu/primitives/eltwise.hpp"#include "intel_gpu/primitives/tile.hpp"@@ -6705,3 +6706,364 @@ INSTANTIATE_TEST_SUITE_P(smoke,std::make_tuple(2, 8, 4, 4, 3, true) // 3D with zero-point),fully_connected_gpu_u2_validation::GetTestCaseName);++// TernOCL ternary FullyConnected (fully_connected_ternocl_int2): u2 codes {0, 1, 2} with the scalar+// zero point 1, i.e. weights {-1, 0, +1}, and one f16 scale per 128-group along K.+namespace {++enum class ternary_epilogue { none, bias, sigmoid, residual };++struct ternary_fc_params {+ int64_t m, n, k;+ ternary_epilogue epilogue;+ bool out_f32;+ bool int8_prefill;+ bool hadamard;+};++std::ostream& operator<<(std::ostream& os, const ternary_fc_params& p) {+ static const char* epi[] = {"none", "bias", "sigmoid", "residual"};+ return os << "m" << p.m << "_n" << p.n << "_k" << p.k << "_" << epi[static_cast<int>(p.epilogue)] << (p.out_f32 ? "_f32" : "")+ << (p.int8_prefill ? "_int8" : "") << (p.hadamard ? "_had" : "");+}++bool ternocl_int2_supported(engine& engine) {+ const auto& info = engine.get_device_info();+ return engine.runtime_type() == runtime_types::ocl && info.arch >= gpu_arch::xe2 && info.supports_immad;+}++// Normalised Sylvester H_1024 applied to s * x, per 1024-wide block of every row.+void hadamard_1024(std::vector<float>& x, int64_t m, int64_t k, const std::vector<int8_t>& signs) {+ std::vector<float> blk(1024);+ for (int64_t r = 0; r < m; ++r) {+ for (int64_t b0 = 0; b0 < k; b0 += 1024) {+ for (int64_t i = 0; i < 1024; ++i)+ blk[i] = x[r * k + b0 + i] * signs[b0 + i];+ for (int64_t h = 1; h < 1024; h <<= 1) {+ for (int64_t i = 0; i < 1024; i += 2 * h) {+ for (int64_t j = i; j < i + h; ++j) {+ const float a = blk[j], c = blk[j + h];+ blk[j] = a + c;+ blk[j + h] = a - c;+ }+ }+ }+ for (int64_t i = 0; i < 1024; ++i)+ x[r * k + b0 + i] = blk[i] / 32.0f;+ }+ }+}++class fully_connected_gpu_ternocl_int2 : public ::testing::TestWithParam<ternary_fc_params> {+public:+ static std::string GetTestCaseName(const testing::TestParamInfo<ternary_fc_params>& obj) {+ std::ostringstream ss;+ ss << obj.param;+ return ss.str();+ }++ // Runs the FC on M rows of a [-1, K] (dynamic) or [M, K] input and checks it against a host reference.+ // With is_caching_test the network is exported and imported before it runs.+ static void run(const ternary_fc_params& p, bool dynamic, const std::vector<int64_t>& ms, bool is_caching_test = false) {+ auto& engine = get_test_engine();+ const int64_t groups = p.k / 128;+ tests::random_generator rg(GET_SUITE_NAME);++ // About 40% zeros, as in the ternary checkpoints.+ auto u = rg.generate_random_1d<float>(p.n * p.k, 0.0f, 1.0f, 100);+ std::vector<int8_t> w(p.n * p.k);+ std::vector<uint8_t> packed(p.n * p.k / 4, 0);+ for (int64_t i = 0; i < p.n * p.k; ++i) {+ w[i] = u[i] < 0.4f ? 0 : (u[i] < 0.7f ? 1 : -1);+ packed[i / 4] |= static_cast<uint8_t>((w[i] + 1) << (2 * (i % 4)));+ }+ auto scales = rg.generate_random_1d<ov::float16>(p.n * groups, 0.01f, 0.1f, 1000);+ auto bias = rg.generate_random_1d<ov::float16>(p.n, -1.0f, 1.0f);+ std::vector<int8_t> signs;+ if (p.hadamard) {+ auto s = rg.generate_random_1d<float>(p.k, -1.0f, 1.0f);+ for (auto v : s)+ signs.push_back(v < 0 ? -1 : 1);+ }++ auto weights_mem = engine.allocate_memory({{p.n, p.k}, data_types::u2, format::bfyx});+ auto scale_mem = engine.allocate_memory({{p.n, groups}, data_types::f16, format::bfyx});+ set_values(weights_mem, packed);+ set_values(scale_mem, scales);+ const auto out_dt = p.out_f32 ? data_types::f32 : data_types::f16;++ const int64_t max_m = *std::max_element(ms.begin(), ms.end());+ auto in_layout = dynamic ? layout{{-1, p.k}, data_types::f16, format::bfyx} : layout{{max_m, p.k}, data_types::f16, format::bfyx};+ topology topology(input_layout("input", in_layout), data("weights", weights_mem), data("scale", scale_mem));+ const bool has_bias = p.epilogue == ternary_epilogue::bias;+ if (has_bias) {+ auto bias_mem = engine.allocate_memory({{1, p.n}, out_dt, format::bfyx});+ if (p.out_f32) {+ std::vector<float> b(bias.begin(), bias.end());+ set_values(bias_mem, b);+ } else {+ set_values(bias_mem, bias);+ }+ topology.add(data("bias", bias_mem));+ }+ auto fc = fully_connected("fc_prim", input_info("input"), "weights", has_bias ? "bias" : "", "scale", "", out_dt, 2, 2);+ fc.decompression_zero_point_scalar = 1;+ if (p.hadamard) {+ fc.hadamard_block = 1024;+ fc.hadamard_signs = signs;+ }+ topology.add(fc);+ std::string out_id = "fc_prim";+ if (p.epilogue == ternary_epilogue::sigmoid) {+ topology.add(activation("act", input_info("fc_prim"), activation_func::logistic));+ out_id = "act";+ } else if (p.epilogue == ternary_epilogue::residual) {+ auto res_layout = dynamic ? layout{{-1, p.n}, data_types::f16, format::bfyx} : layout{{max_m, p.n}, data_types::f16, format::bfyx};+ topology.add(input_layout("residual", res_layout));+ topology.add(eltwise("sum", {input_info("fc_prim"), input_info("residual")}, eltwise_mode::sum, out_dt));+ out_id = "sum";+ }+ const bool fused_epilogue = p.epilogue == ternary_epilogue::sigmoid || p.epilogue == ternary_epilogue::residual;+ if (fused_epilogue) {+ // An eltwise that is a network output is never fused, so give the epilogue a consumer.+ topology.add(reorder("out", input_info(out_id), format::bfyx, data_types::f32));+ out_id = "out";+ }+ const bool read_f32 = p.out_f32 || fused_epilogue;++ auto config = get_test_default_config(engine);+ config.set_property(ov::intel_gpu::allow_new_shape_infer(true));+ config.set_property(ov::intel_gpu::optimize_data(true));+ config.set_property(ov::intel_gpu::ternocl_int2_int8_prefill(p.int8_prefill));+ config.set_user_property(ov::hint::dynamic_quantization_group_size(0));+ network::ptr net = get_network(engine, topology, config, get_test_stream_ptr(), is_caching_test);++ // The weights are packed into a constant of their own; the u2 source is left untouched.+ {+ cldnn::mem_lock<uint8_t, mem_lock_type::read> src(weights_mem, get_test_stream());+ ASSERT_TRUE(std::equal(packed.begin(), packed.end(), src.begin()));+ }++ for (const int64_t m : ms) {+ auto x = rg.generate_random_1d<ov::float16>(m * p.k, -1.0f, 1.0f, 100);+ auto input_mem = engine.allocate_memory({{m, p.k}, data_types::f16, format::bfyx});+ set_values(input_mem, x);+ net->set_input_data("input", input_mem);+ std::vector<ov::float16> res;+ if (p.epilogue == ternary_epilogue::residual) {+ res = rg.generate_random_1d<ov::float16>(m * p.n, -1.0f, 1.0f);+ auto res_mem = engine.allocate_memory({{m, p.n}, data_types::f16, format::bfyx});+ set_values(res_mem, res);+ net->set_input_data("residual", res_mem);+ }+ auto outputs = net->execute();++ ASSERT_EQ(net->get_primitive("fc_prim")->get_impl()->get_kernel_name(), "ternocl_int2");+ if (fused_epilogue) {+ ASSERT_TRUE(net->get_primitive("fc_prim")->get_node().has_fused_primitives());+ }++ std::vector<float> xf(x.begin(), x.end());+ if (p.hadamard)+ hadamard_1024(xf, m, p.k, signs);+ std::vector<float> ref(m * p.n);+ float max_abs = 0.0f;+ for (int64_t r = 0; r < m; ++r) {+ for (int64_t n = 0; n < p.n; ++n) {+ float acc = 0.0f;+ for (int64_t g = 0; g < groups; ++g) {+ float part = 0.0f;+ for (int64_t kk = g * 128; kk < (g + 1) * 128; ++kk)+ part += xf[r * p.k + kk] * w[n * p.k + kk];+ acc += part * static_cast<float>(scales[n * groups + g]);+ }+ if (has_bias)+ acc += static_cast<float>(bias[n]);+ if (p.epilogue == ternary_epilogue::sigmoid)+ acc = 1.0f / (1.0f + std::exp(-acc));+ if (p.epilogue == ternary_epilogue::residual)+ acc += static_cast<float>(res[r * p.n + n]);+ ref[r * p.n + n] = acc;+ max_abs = std::max(max_abs, std::fabs(acc));+ }+ }++ // int8 prefill quantizes the activations per 128-group (~1/127 relative per element).+ const float tol = (p.int8_prefill && m > 8 ? 0.02f : 0.005f) * std::max(max_abs, 1.0f);+ // A dynamic network may hand back a buffer larger than the current shape; only m * n values are valid.+ ASSERT_EQ(outputs.at(out_id).get_layout().count(), ref.size());+ auto out_mem = outputs.at(out_id).get_memory();+ std::vector<float> out;+ if (read_f32) {+ cldnn::mem_lock<float> l(out_mem, get_test_stream());+ out.assign(l.begin(), l.begin() + ref.size());+ } else {+ cldnn::mem_lock<ov::float16> l(out_mem, get_test_stream());+ out.assign(l.begin(), l.begin() + ref.size());+ }+ for (size_t i = 0; i < ref.size(); ++i)+ ASSERT_NEAR(ref[i], out[i], tol) << "m=" << m << " index " << i;+ }+ }+};++} // namespace++TEST_P(fully_connected_gpu_ternocl_int2, static_shape) {+ if (!ternocl_int2_supported(get_test_engine()))+ GTEST_SKIP();+ // Post-op fusion into an f16 OCL FC is only done for dynamic shapes (as in the LLMs), so the epilogue cases use one.+ const auto& p = GetParam();+ const bool dynamic = p.epilogue == ternary_epilogue::sigmoid || p.epilogue == ternary_epilogue::residual;+ run(p, dynamic, {p.m});+}++INSTANTIATE_TEST_SUITE_P(smoke,+ fully_connected_gpu_ternocl_int2,+ ::testing::Values(+ // GEMV classes (M = 1, 2, <= 4, <= 8), then the M-tiled GEMM bands+ ternary_fc_params{1, 256, 1024, ternary_epilogue::none, false, false, false},+ ternary_fc_params{2, 512, 512, ternary_epilogue::none, false, false, false},+ ternary_fc_params{3, 1024, 256, ternary_epilogue::none, false, false, false},+ ternary_fc_params{7, 256, 2048, ternary_epilogue::none, false, false, false},+ ternary_fc_params{12, 256, 1024, ternary_epilogue::none, false, false, false},+ ternary_fc_params{33, 512, 512, ternary_epilogue::none, false, false, false},+ ternary_fc_params{70, 256, 1024, ternary_epilogue::none, false, false, false},+ // as many groups as output columns: [N, groups] and [groups, N] scales have equal shapes+ ternary_fc_params{1, 16, 2048, ternary_epilogue::none, false, false, false},+ // epilogues and output type+ ternary_fc_params{1, 256, 1024, ternary_epilogue::bias, false, false, false},+ ternary_fc_params{20, 256, 1024, ternary_epilogue::bias, false, false, false},+ ternary_fc_params{1, 256, 1024, ternary_epilogue::sigmoid, false, false, false},+ ternary_fc_params{1, 256, 1024, ternary_epilogue::residual, false, false, false},+ ternary_fc_params{17, 256, 1024, ternary_epilogue::residual, false, false, false},+ ternary_fc_params{5, 256, 1024, ternary_epilogue::none, true, false, false},+ ternary_fc_params{40, 256, 1024, ternary_epilogue::none, true, false, false},+ // int2 x int8 DPAS prefill+ ternary_fc_params{12, 256, 1024, ternary_epilogue::none, false, true, false},+ ternary_fc_params{70, 512, 2048, ternary_epilogue::none, false, true, false},+ // Hadamard input rotation (rotated-basis checkpoints)+ ternary_fc_params{1, 256, 2048, ternary_epilogue::none, false, false, true},+ ternary_fc_params{20, 256, 1024, ternary_epilogue::none, false, false, true},+ ternary_fc_params{20, 256, 1024, ternary_epilogue::none, false, true, true}),+ fully_connected_gpu_ternocl_int2::GetTestCaseName);++TEST(fully_connected_gpu_ternocl_int2_dynamic, gemv_and_gemm_on_one_network) {+ if (!ternocl_int2_supported(get_test_engine()))+ GTEST_SKIP();+ fully_connected_gpu_ternocl_int2::run(ternary_fc_params{1, 256, 1024, ternary_epilogue::none, false, false, false}, true, {1, 33, 4, 70, 1});+}++TEST(fully_connected_gpu_ternocl_int2_dynamic, residual_epilogue) {+ if (!ternocl_int2_supported(get_test_engine()))+ GTEST_SKIP();+ fully_connected_gpu_ternocl_int2::run(ternary_fc_params{1, 256, 1024, ternary_epilogue::residual, false, false, false}, true, {1, 17, 2});+}++TEST(fully_connected_gpu_ternocl_int2_cached, static_gemv) {+ if (!ternocl_int2_supported(get_test_engine()))+ GTEST_SKIP();+ fully_connected_gpu_ternocl_int2::run(ternary_fc_params{1, 256, 1024, ternary_epilogue::none, false, false, false}, false, {1}, true);+}++TEST(fully_connected_gpu_ternocl_int2_cached, dynamic_residual) {+ if (!ternocl_int2_supported(get_test_engine()))+ GTEST_SKIP();+ fully_connected_gpu_ternocl_int2::run(ternary_fc_params{1, 256, 1024, ternary_epilogue::residual, false, false, false}, true, {1, 17}, true);+}++TEST(fully_connected_gpu_ternocl_int2_cached, dynamic_hadamard) {+ if (!ternocl_int2_supported(get_test_engine()))+ GTEST_SKIP();+ fully_connected_gpu_ternocl_int2::run(ternary_fc_params{1, 256, 2048, ternary_epilogue::none, false, false, true}, true, {1, 20}, true);+}++TEST(fully_connected_gpu_ternocl_int2_cached, static_int8_prefill_bias) {+ if (!ternocl_int2_supported(get_test_engine()))+ GTEST_SKIP();+ fully_connected_gpu_ternocl_int2::run(ternary_fc_params{20, 256, 1024, ternary_epilogue::bias, false, true, false}, false, {20}, true);+}++// Two FCs on one weight constant: both run the TernOCL impl on the same packed weights.+TEST(fully_connected_gpu_ternocl_int2_dynamic, shared_weights) {+ auto& engine = get_test_engine();+ if (!ternocl_int2_supported(engine))+ GTEST_SKIP();+ const int64_t m = 3, n = 256, k = 1024, groups = k / 128;+ tests::random_generator rg(GET_SUITE_NAME);+ auto u = rg.generate_random_1d<float>(n * k, 0.0f, 1.0f, 100);+ std::vector<int8_t> w(n * k);+ std::vector<uint8_t> packed(n * k / 4, 0);+ for (int64_t i = 0; i < n * k; ++i) {+ w[i] = u[i] < 0.4f ? 0 : (u[i] < 0.7f ? 1 : -1);+ packed[i / 4] |= static_cast<uint8_t>((w[i] + 1) << (2 * (i % 4)));+ }+ auto scales = rg.generate_random_1d<ov::float16>(n * groups, 0.01f, 0.1f, 1000);+ auto weights_mem = engine.allocate_memory({{n, k}, data_types::u2, format::bfyx});+ auto scale_mem = engine.allocate_memory({{n, groups}, data_types::f16, format::bfyx});+ set_values(weights_mem, packed);+ set_values(scale_mem, scales);++ const layout in_layout{{-1, k}, data_types::f16, format::bfyx};+ topology topology(input_layout("input0", in_layout), input_layout("input1", in_layout), data("weights", weights_mem), data("scale", scale_mem));+ for (const auto* id : {"0", "1"}) {+ auto fc = fully_connected(std::string("fc") + id, input_info(std::string("input") + id), "weights", "", "scale", "", data_types::f16, 2, 2);+ fc.decompression_zero_point_scalar = 1;+ topology.add(fc);+ }+ auto config = get_test_default_config(engine);+ config.set_property(ov::intel_gpu::allow_new_shape_infer(true));+ config.set_property(ov::intel_gpu::optimize_data(true));+ config.set_user_property(ov::hint::dynamic_quantization_group_size(0));+ network::ptr net = get_network(engine, topology, config, get_test_stream_ptr(), false);++ std::vector<std::vector<ov::float16>> xs;+ for (const auto* id : {"0", "1"}) {+ xs.push_back(rg.generate_random_1d<ov::float16>(m * k, -1.0f, 1.0f, 100));+ auto input_mem = engine.allocate_memory({{m, k}, data_types::f16, format::bfyx});+ set_values(input_mem, xs.back());+ net->set_input_data(std::string("input") + id, input_mem);+ }+ auto outputs = net->execute();+ for (size_t f = 0; f < 2; ++f) {+ const auto id = "fc" + std::to_string(f);+ ASSERT_EQ(net->get_primitive(id)->get_impl()->get_kernel_name(), "ternocl_int2");+ cldnn::mem_lock<ov::float16> out(outputs.at(id).get_memory(), get_test_stream());+ for (int64_t r = 0; r < m; ++r) {+ for (int64_t c = 0; c < n; ++c) {+ float acc = 0.0f;+ for (int64_t g = 0; g < groups; ++g) {+ float part = 0.0f;+ for (int64_t kk = g * 128; kk < (g + 1) * 128; ++kk)+ part += static_cast<float>(xs[f][r * k + kk]) * w[c * k + kk];+ acc += part * static_cast<float>(scales[c * groups + g]);+ }+ ASSERT_NEAR(acc, static_cast<float>(out[r * n + c]), 0.005f * std::max(std::fabs(acc), 1.0f)) << id << " row " << r << " col " << c;+ }+ }+ }+ cldnn::mem_lock<uint8_t, mem_lock_type::read> src(weights_mem, get_test_stream());+ ASSERT_TRUE(std::equal(packed.begin(), packed.end(), src.begin()));+}++TEST(fully_connected_gpu_ternocl_int2_dynamic, non_ternary_zero_point_falls_back) {+ auto& engine = get_test_engine();+ if (!ternocl_int2_supported(engine))+ GTEST_SKIP();+ auto weights_mem = engine.allocate_memory({{256, 1024}, data_types::u2, format::bfyx});+ auto scale_mem = engine.allocate_memory({{256, 8}, data_types::f16, format::bfyx});+ set_values(weights_mem, std::vector<uint8_t>(256 * 1024 / 4, 0x55));+ set_values(scale_mem, std::vector<ov::float16>(256 * 8, ov::float16(0.5f)));+ auto fc = fully_connected("fc_prim", input_info("input"), "weights", "", "scale", "", data_types::f16, 2, 2);+ fc.decompression_zero_point_scalar = 2;+ topology topology(input_layout("input", layout{{1, 1024}, data_types::f16, format::bfyx}), data("weights", weights_mem), data("scale", scale_mem), fc);+ auto config = get_test_default_config(engine);+ config.set_property(ov::intel_gpu::allow_new_shape_infer(true));+ config.set_property(ov::intel_gpu::optimize_data(true));+ network::ptr net = get_network(engine, topology, config, get_test_stream_ptr(), false);+ auto input_mem = engine.allocate_memory({{1, 1024}, data_types::f16, format::bfyx});+ set_values(input_mem, std::vector<ov::float16>(1024, ov::float16(1.0f)));+ net->set_input_data("input", input_mem);+ net->execute();+ ASSERT_NE(net->get_primitive("fc_prim")->get_impl()->get_kernel_name(), "ternocl_int2");+}diff --git a/src/plugins/intel_gpu/tests/unit/test_cases/rope_gpu_test.cpp b/src/plugins/intel_gpu/tests/unit/test_cases/rope_gpu_test.cppindex 41553757c8b..c48ee7c1808 100644--- a/src/plugins/intel_gpu/tests/unit/test_cases/rope_gpu_test.cpp+++ b/src/plugins/intel_gpu/tests/unit/test_cases/rope_gpu_test.cpp@@ -2,6 +2,7 @@// SPDX-License-Identifier: Apache-2.0//+#include <intel_gpu/primitives/data.hpp>#include <intel_gpu/primitives/input_layout.hpp>#include <intel_gpu/primitives/reorder.hpp>#include <intel_gpu/primitives/rope.hpp>@@ -642,3 +643,79 @@ TEST_P(rope_gpu_test, rope_chatglm_cache) {TEST_P(rope_gpu_test, rope_chatglm_cache_large) {run_rope(GetParam(), ov::PartialShape{16, 1, 512}, 8, 64, false, false, rope_variant::chatglm, true);}++// RoPE with a per-head RMSNorm folded in (FuseRMSRoPE): input 3 is the RMSNorm gamma, and the+// output must match RMSNorm over each head followed by RotateHalf RoPE.+static void run_rope_fused_rms(const ov::PartialShape& in_shape, size_t head_size, bool dynamic) {+ auto& engine = get_test_engine();+ const size_t batch = in_shape[0].get_length(), head_cnt = in_shape[1].get_length(), seq = in_shape[2].get_length();+ const float eps = 1e-6f;+ const ov::PartialShape cos_shape{1, 1, static_cast<int64_t>(seq), static_cast<int64_t>(head_size)};++ auto input = engine.allocate_memory({in_shape, data_types::f16, format::bfyx});+ auto cos = engine.allocate_memory({cos_shape, data_types::f16, format::bfyx});+ auto sin = engine.allocate_memory({cos_shape, data_types::f16, format::bfyx});+ auto gamma = engine.allocate_memory({ov::PartialShape{static_cast<int64_t>(head_size)}, data_types::f16, format::bfyx});+ auto normed = engine.allocate_memory({in_shape, data_types::f16, format::bfyx});+ auto output_ref = engine.allocate_memory({in_shape, data_types::f16, format::bfyx});+ tests::set_random_values<ov::float16>(input, true, 10, 4);+ tests::set_random_values<ov::float16>(cos, true, 10, 1);+ tests::set_random_values<ov::float16>(sin, true, 10, 1);+ tests::set_random_values<ov::float16>(gamma, true, 10, 2);++ {+ cldnn::mem_lock<ov::float16> in(input, get_test_stream());+ cldnn::mem_lock<ov::float16> g(gamma, get_test_stream());+ cldnn::mem_lock<ov::float16> out(normed, get_test_stream());+ for (size_t row = 0; row < batch * head_cnt * seq; ++row) {+ float ss = 0.0f;+ for (size_t i = 0; i < head_size; ++i)+ ss += static_cast<float>(in[row * head_size + i]) * static_cast<float>(in[row * head_size + i]);+ const float scale = 1.0f / std::sqrt(ss / static_cast<float>(head_size) + eps);+ for (size_t i = 0; i < head_size; ++i)+ out[row * head_size + i] = ov::float16(static_cast<float>(in[row * head_size + i]) * scale * static_cast<float>(g[i]));+ }+ }+ rope_ref(normed, cos, sin, output_ref, batch, head_cnt, seq, head_size, head_size, false);++ ov::op::internal::RoPE::Config config;+ config.head_cnt = head_cnt;+ config.head_size = head_size;+ config.rotary_ndims = head_size;++ const auto in_lay = dynamic ? layout{ov::PartialShape::dynamic(4), data_types::f16, format::bfyx} : input->get_layout();+ topology topology(input_layout("input", in_lay),+ input_layout("cos", cos->get_layout()),+ input_layout("sin", sin->get_layout()),+ data("gamma", gamma),+ rope("rope", {input_info("input"), input_info("cos"), input_info("sin"), input_info("gamma")}, config, 0, true, eps));++ ExecutionConfig cfg = get_test_default_config(engine);+ cfg.set_property(ov::intel_gpu::allow_new_shape_infer(true));+ network network(engine, topology, cfg);+ network.set_input_data("input", input);+ network.set_input_data("cos", cos);+ network.set_input_data("sin", sin);+ auto outputs = network.execute();++ cldnn::mem_lock<ov::float16> out(outputs.at("rope").get_memory(), get_test_stream());+ cldnn::mem_lock<ov::float16> ref(output_ref, get_test_stream());+ ASSERT_EQ(out.size(), ref.size());+ for (size_t i = 0; i < ref.size(); ++i) {+ const float r = static_cast<float>(ref[i]);+ ASSERT_LE(std::abs(static_cast<float>(out[i]) - r), std::max(0.02f, std::abs(r) * 0.04f)) << "Mismatch at i=" << i;+ }+}++// 16-wide f16 path the fusion is restricted to (head_size % 32 == 0)+TEST(rope_gpu_fused_rms, head64) {+ run_rope_fused_rms(ov::PartialShape{1, 8, 16, 64}, 64, false);+}++TEST(rope_gpu_fused_rms, head128) {+ run_rope_fused_rms(ov::PartialShape{2, 4, 5, 128}, 128, false);+}++TEST(rope_gpu_fused_rms, head128_dynamic) {+ run_rope_fused_rms(ov::PartialShape{1, 16, 7, 128}, 128, true);+}diff --git a/src/plugins/intel_gpu/thirdparty/TernOCL b/src/plugins/intel_gpu/thirdparty/TernOCLnew file mode 160000index 00000000000..43ce83e1cde--- /dev/null+++ b/src/plugins/intel_gpu/thirdparty/TernOCL@@ -0,0 +1 @@+Subproject commit 43ce83e1cdec77ecf83bf5680b1d4393d1b1e7e6diff --git a/src/plugins/intel_gpu/tools/int2/bonsai2_gguf_to_ir.py b/src/plugins/intel_gpu/tools/int2/bonsai2_gguf_to_ir.pynew file mode 100644index 00000000000..7d1e22ffeb5--- /dev/null+++ b/src/plugins/intel_gpu/tools/int2/bonsai2_gguf_to_ir.py@@ -0,0 +1,615 @@+# Copyright (C) 2018-2026 Intel Corporation+# SPDX-License-Identifier: Apache-2.0++"""Build the Bonsai 2 27B u2 IR from its PQ2_0 GGUF, using the Bonsai 1 27B IR+as a template.++Bonsai 2 27B (prism-ml/Ternary-Bonsai-2-27B-gguf) has the Qwen3.5-27B+architecture of Bonsai 27B, so the exported+quantized Bonsai 1 IR already holds+the right graph. This tool keeps that graph and swaps every weight:++ * ternary MatMuls: the PQ2_0 blocks *are* the u2 layout the GPU plugin's+ weight-compression pattern expects (codes {0,1,2}, zero point 1, one fp16+ scale per 128), so the code bytes are copied and only the scales are split+ off;+ * dense tensors (norms, GDN A_log/dt_bias/conv1d/in_proj_a/in_proj_b): read+ from the GGUF, with llama.cpp's V-head reorder undone the way the HF model+ expects;+ * the token embedding goes into the separate text-embeddings IR, still ternary+ (u8-packed codes + fp16 scales, 0.34 GB): the device gathers the rows and+ dequantises them.++Bonsai 2 additionally stores its folded weights in a rotated basis: the input+of each folded projection is sign-flipped and put through a blockwise (1024)+normalised Walsh-Hadamard transform, and the embedding table is stored rotated.+The transform is inserted into the graph (Reshape -> MatMul with one shared+H_1024 constant -> Reshape); the sign flips are folded into the preceding+RMSNorm weight where every consumer is folded (compensating the dense GDN gate+projections), into the up_proj rows for down_proj, and kept as an explicit+Multiply only for the two attention output projections whose producer is not a+per-channel weight. The embedding rows get the inverse transform after the+gather, on the device.++ python bonsai2_gguf_to_ir.py \+ --gguf <Ternary-Bonsai-2-27B-PQ2_0.gguf> \+ --template-dir <bonsai27b-u2 dir with openvino_model.xml> \+ --out-dir <bonsai2-27b-u2> [--gguf-py <prism llama.cpp>/gguf-py]++ # self-check: run it on the Bonsai 1 GGUF and compare against its own IR+ python bonsai2_gguf_to_ir.py --gguf <Ternary-Bonsai-27B-PQ2_0.gguf> \+ --template-dir ... --template-embed ... --verify++Reading PQ2_0 needs the PrismML llama.cpp fork's gguf-py (type id 142).+"""+from __future__ import annotations++import argparse+import os+import re+import sys+import time++import numpy as np+import openvino as ov+from openvino import opset13 as ops++GROUP = 128+BLOCK_BYTES = 2 + GROUP // 4+PREFIX = "__module.model." # optimum's module prefix in node names+LM = "model.language_model."++# HF module leaf -> GGUF tensor stem (per block)+QUANT_MAP = {+ "self_attn.q_proj": "attn_q", "self_attn.k_proj": "attn_k",+ "self_attn.v_proj": "attn_v", "self_attn.o_proj": "attn_output",+ "mlp.gate_proj": "ffn_gate", "mlp.up_proj": "ffn_up", "mlp.down_proj": "ffn_down",+ "linear_attn.in_proj_qkv": "attn_qkv", "linear_attn.in_proj_z": "attn_gate",+ "linear_attn.out_proj": "ssm_out",+ "linear_attn.in_proj_a": "ssm_alpha", "linear_attn.in_proj_b": "ssm_beta",+}+# node-name suffix (relative to the layer) -> (GGUF stem, kind)+DENSE_MAP = {+ "input_layernorm/aten::mul/Multiply_1": ("attn_norm.weight", "norm"),+ "post_attention_layernorm/aten::mul/Multiply_1": ("post_attention_norm.weight", "norm"),+ "self_attn.q_norm/aten::mul/Multiply_1": ("attn_q_norm.weight", "norm"),+ "self_attn.k_norm/aten::mul/Multiply_1": ("attn_k_norm.weight", "norm"),+ "linear_attn.norm/aten::mul/Multiply_1": ("ssm_norm.weight", "norm"),+ "linear_attn/aten::exp/Exp": ("ssm_a", "a_log"),+ "linear_attn/aten::add/Add_2": ("ssm_dt.bias", "dt_bias"),+ "linear_attn/aten::_convolution/GroupConvolution": ("ssm_conv1d.weight", "conv1d"),+}+++def find_gguf_py(explicit: str | None) -> str:+ here = os.path.dirname(os.path.abspath(__file__))+ cands = [explicit or "", os.environ.get("PRISM_GGUF_PY", ""),+ os.path.join(here, "..", "..", "..", "..", "..", "..", "third_party",+ "llama.cpp-prism", "gguf-py")]+ for c in cands:+ if c and os.path.isfile(os.path.join(c, "gguf", "constants.py")):+ with open(os.path.join(c, "gguf", "constants.py")) as fh:+ if "PQ2_0" in fh.read():+ return os.path.abspath(c)+ sys.exit("need the PrismML llama.cpp fork's gguf-py (knows PQ2_0): --gguf-py or "+ "$PRISM_GGUF_PY; git clone --depth 1 -b prism "+ "https://github.com/PrismML-Eng/llama.cpp")+++def gguf_f32(t) -> np.ndarray:+ shape = tuple(int(x) for x in reversed(t.shape))+ arr = np.asarray(t.data)+ if t.tensor_type.name == "BF16":+ return (arr.view(np.uint16).astype(np.uint32) << 16).view(np.float32).reshape(shape)+ if t.tensor_type.name in ("F32", "F16"):+ return arr.astype(np.float32).reshape(shape)+ sys.exit(f"{t.name}: unsupported dense type {t.tensor_type.name}")+++def pq2_blocks(t) -> np.ndarray:+ """PQ2_0 tensor -> uint8 [N, K/128, 34] (fp16 scale, then 32 code bytes)."""+ n, k = (int(x) for x in reversed(t.shape))+ raw = np.ascontiguousarray(t.data).reshape(-1).view(np.uint8)+ if raw.size != n * (k // GROUP) * BLOCK_BYTES:+ sys.exit(f"{t.name}: PQ2_0 byte length mismatch")+ return raw.reshape(n, k // GROUP, BLOCK_BYTES)+++def blocks_dequant(blocks: np.ndarray) -> np.ndarray:+ """[N, G, 34] -> fp32 [N, G*128]."""+ n, g, _ = blocks.shape+ scale = blocks[:, :, :2].copy().view("<f2").astype(np.float32).reshape(n, g, 1)+ q = blocks[:, :, 2:]+ codes = np.stack([(q >> (2 * j)) & 3 for j in range(4)], axis=-1) # [N,G,32,4]+ codes = codes.reshape(n, g, GROUP).astype(np.float32) - 1.0+ return (codes * scale).reshape(n, g * GROUP)+++def flip_code_bytes(q: np.ndarray) -> np.ndarray:+ """Negate ternary codes c -> 2 - c in every 2-bit lane (0<->2, 1 stays)."""+ q = q.astype(np.uint8)+ hi = (~(q | (q << 1))) & 0xAA+ return (hi | (q & 0x55)).astype(np.uint8)+++def hadamard(n: int) -> np.ndarray:+ i = np.arange(n)+ pop = np.array([bin(x).count("1") for x in range(n)])+ return np.where(pop[i[:, None] & i[None, :]] % 2, -1.0, 1.0) / np.sqrt(n)+++def ternary_embedding(blocks: np.ndarray, block: int, signs_k: np.ndarray | None) -> ov.Model:+ """Embedding model that gathers the ternary rows and dequantises them on the device.++ Byte j of a u8 table row holds the codes of columns j, j+K/4, j+K/2 and j+3K/4 in its+ four 2-bit lanes, so unpacking is four floor/mod planes concatenated in column order.+ With a Hadamard contract the gathered rows get the inverse rotation (x H_block * signs)."""+ v, g, _ = blocks.shape+ k = g * GROUP+ q = blocks[:, :, 2:]+ codes = np.stack([(q >> (2 * j)) & 3 for j in range(4)], axis=-1).reshape(v, k)+ quarter = k // 4+ table = np.zeros((v, quarter), np.uint8)+ for p in range(4):+ table |= codes[:, p * quarter:(p + 1) * quarter] << (2 * p)+ del codes+ scales = np.ascontiguousarray(blocks[:, :, :2]).view("<f2").reshape(v, g)++ ids = ops.parameter([-1, -1], ov.Type.i64, name="input")+ idx = ops.convert(ids, ov.Type.i32)+ axis = ops.constant(np.int32(0))+ qf = ops.convert(ops.gather(ops.constant(table), idx, axis), ov.Type.f32)+ planes = []+ for p in range(4):+ x = ops.floor(ops.divide(qf, ops.constant(np.float32(4 ** p)))) if p else qf+ planes.append(ops.floor_mod(x, ops.constant(np.float32(4))) if p < 3 else x)+ w = ops.subtract(ops.concat(planes, -1), ops.constant(np.float32(1))) # codes {0,1,2} - zp+ s = ops.convert(ops.gather(ops.constant(scales), idx, axis), ov.Type.f32)+ w = ops.multiply(ops.reshape(w, ops.constant(np.array([0, 0, g, GROUP], np.int64)), True),+ ops.unsqueeze(s, ops.constant(np.int64(-1))))+ w = ops.reshape(w, ops.constant(np.array([0, 0, k], np.int64)), True)+ if signs_k is not None:+ w = ops.reshape(w, ops.constant(np.array([0, 0, k // block, block], np.int64)), True)+ w = ops.matmul(w, ops.constant(hadamard(block).astype(np.float32)), False, False)+ w = ops.multiply(ops.reshape(w, ops.constant(np.array([0, 0, k], np.int64)), True),+ ops.constant(signs_k.reshape(1, 1, k).astype(np.float32)))+ out = ops.result(w)+ out.output(0).get_tensor().set_names({"inputs_embeds"})+ return ov.Model([out], [ids], "text_embeddings")+++def f32_to_bf16_bits(x: np.ndarray) -> np.ndarray:+ u = np.ascontiguousarray(x, dtype=np.float32).view(np.uint32)+ rounding = ((u >> 16) & 1) + 0x7FFF+ return ((u + rounding) >> 16).astype(np.uint16)+++def vperm(nv: int, nk: int, unit: int) -> np.ndarray:+ """llama.cpp tiled V order -> HF grouped order (index vector)."""+ return np.arange(nv * unit).reshape(nv // nk, nk, unit).transpose(1, 0, 2).reshape(-1)+++def const_of(node, port: int):+ """Constant behind input `port` of node, looking through Convert/Reshape."""+ src = node.input_value(port).get_node()+ while src.get_type_name() in ("Convert", "Reshape"):+ src = src.input_value(0).get_node()+ return src if src.get_type_name() == "Constant" else None+++def u2_chain(mm):+ """(u2 Constant, scale Constant) of the weight-decompression subgraph on+ MatMul input 1: Convert <- Reshape <- Multiply(Subtract(Convert(u2), zp), scale)."""+ src = mm.input_value(1).get_node()+ mul = None+ while src.get_type_name() in ("Convert", "Reshape", "Multiply", "Subtract"):+ if src.get_type_name() == "Multiply":+ mul = src+ src = src.input_value(0).get_node()+ if src.get_type_name() != "Constant" or src.get_output_element_type(0) != ov.Type.u2 or mul is None:+ return None, None+ return src, const_of(mul, 1)+++def replace_const(old, data: np.ndarray, et: ov.Type | None = None):+ if et is None:+ et = old.get_output_element_type(0)+ if et == ov.Type.bf16:+ t = ov.Tensor(et, list(data.shape))+ np.frombuffer(t.data, dtype=np.uint16)[:] = f32_to_bf16_bits(data).reshape(-1)+ new = ops.constant(t)+ else:+ new = ops.constant(data.astype(et.to_dtype()))+ new.set_friendly_name(old.get_friendly_name())+ for tgt in list(old.output(0).get_target_inputs()):+ tgt.replace_source_output(new.output(0))+ return new+++def const_f32(c) -> np.ndarray:+ d = c.get_data()+ if c.get_output_element_type(0) == ov.Type.bf16:+ return (d.view(np.uint16).astype(np.uint32) << 16).view(np.float32)+ return d.astype(np.float32)+++class Report:+ def __init__(self):+ self.worst = {}++ def add(self, kind: str, name: str, got: np.ndarray, want: np.ndarray):+ if got.shape != want.shape:+ sys.exit(f"{name}: shape {got.shape} vs template {want.shape}")+ err = float(np.abs(got.astype(np.float32) - want.astype(np.float32)).max())+ rel = err / (float(np.abs(want).max()) + 1e-12)+ if kind not in self.worst or rel > self.worst[kind][0]:+ self.worst[kind] = (rel, err, name)++ def dump(self):+ for k, (rel, err, name) in sorted(self.worst.items()):+ print(f" {k:10s} worst rel {rel:.3e} (abs {err:.3e}) at {name}")+++def main():+ ap = argparse.ArgumentParser()+ ap.add_argument("--gguf", required=True)+ ap.add_argument("--template-dir", required=True,+ help="dir with the Bonsai 1 27B u2 openvino_model.xml")+ ap.add_argument("--template-embed",+ help="Bonsai 1 27B openvino_text_embeddings_model.xml (--verify only)")+ ap.add_argument("--out-dir")+ ap.add_argument("--gguf-py")+ ap.add_argument("--verify", action="store_true",+ help="compare GGUF-derived tensors with the template instead of writing")+ ap.add_argument("--no-hadamard", action="store_true",+ help="ignore the prism.hadamard contract (debug)")+ ap.add_argument("--explicit-signs", action="store_true",+ help="keep every sign flip as a Multiply instead of folding into weights (debug)")+ ap.add_argument("--no-fold-norm", action="store_true", help="debug: no RMSNorm sign folds")+ ap.add_argument("--no-fold-up", action="store_true", help="debug: no up_proj row folds")+ a = ap.parse_args()+ fold_norm = not (a.explicit_signs or a.no_fold_norm)+ fold_up = not (a.explicit_signs or a.no_fold_up)+ if not a.verify and not a.out_dir:+ ap.error("--out-dir is required unless --verify")+ if a.verify and not a.template_embed:+ ap.error("--verify needs --template-embed")++ sys.path.insert(0, find_gguf_py(a.gguf_py))+ from gguf import GGUFReader # noqa: E402++ t0 = time.perf_counter()+ r = GGUFReader(a.gguf)+ fields = {k: v.contents() for k, v in r.fields.items()}+ if fields.get("general.architecture") != "qwen35":+ sys.exit(f"unsupported architecture {fields.get('general.architecture')!r}")+ g = lambda key: fields["qwen35." + key] # noqa: E731+ nv, nk = int(g("ssm.time_step_rank")), int(g("ssm.group_count"))+ hd = int(g("ssm.inner_size")) // nv+ qk_rows = 2 * nk * int(g("ssm.state_size"))+ perm_hd, perm_1 = vperm(nv, nk, hd), vperm(nv, nk, 1)+ # llama.cpp also permutes ssm_out's input columns to its tiled V order unless+ # the exporter kept them grouped (Bonsai 2 must: a folded weight cannot be+ # column-permuted).+ v_grouped = bool(fields.get("prism.hadamard.gdn_v_grouped", False))+ tensors = {t.name: t for t in r.tensors}+ print(f"[ir] {a.gguf}: {len(tensors)} tensors, GDN nv={nv} nk={nk} hd={hd}")++ # ---- Hadamard contract -------------------------------------------------+ folded: set[str] = set()+ signs: dict[int, np.ndarray] = {}+ block = 0+ if int(fields.get("prism.hadamard.version", 0)) == 1 and not a.no_hadamard:+ if fields["prism.hadamard.transform"] != "normalized-sylvester-walsh-hadamard" \+ or fields["prism.hadamard.axis"] != "input-last-dimension" \+ or fields["prism.hadamard.sign_mode"] != "explicit" \+ or not fields.get("prism.hadamard.gdn_v_grouped", False):+ sys.exit("unexpected prism.hadamard contract")+ block = int(fields["prism.hadamard.block_size"])+ folded = set(fields["prism.hadamard.weight_names"])+ inverse = set(fields.get("prism.hadamard.inverse_weight_names", []))+ if inverse != {"token_embd.weight"}:+ sys.exit(f"unexpected inverse set {inverse}")+ vals = np.asarray(fields["prism.hadamard.sign_values"], dtype=np.float32)+ off = 0+ for w in fields["prism.hadamard.sign_widths"]:+ w = int(w)+ signs[w] = vals[off:off + w]+ off += w+ if off != len(vals) or any(not np.isin(s, [-1, 1]).all() for s in signs.values()):+ sys.exit("bad sign vectors")+ print(f"[ir] hadamard H{block}: {len(folded)} folded weights, sign widths {sorted(signs)}")+ else:+ print("[ir] no hadamard contract: plain ternary model")++ core = ov.Core()+ model = core.read_model(os.path.join(a.template_dir, "openvino_model.xml"))+ rep = Report()++ # ---- ternary + dense MatMul weights -------------------------------------+ mm_re = re.compile(re.escape(PREFIX) + r"(.+)/ov_ext::linear/MatMul$")+ matmuls = {}+ for node in model.get_ordered_ops():+ if node.get_type_name() != "MatMul":+ continue+ m = mm_re.match(node.get_friendly_name())+ if m:+ matmuls[m.group(1)] = node+ print(f"[ir] {len(matmuls)} linear MatMuls in template")++ layer_re = re.compile(re.escape(LM) + r"layers\.(\d+)\.(.+)$")+ n_u2 = n_dense = n_row_fold = 0+ k_of = {} # hf module -> K+ for hf, mm in sorted(matmuls.items()):+ if hf == "lm_head":+ gname, leaf, layer = "output.weight", "lm_head", -1+ else:+ lm = layer_re.match(hf)+ if not lm:+ sys.exit(f"unexpected MatMul {hf}")+ layer, leaf = int(lm.group(1)), lm.group(2)+ if leaf not in QUANT_MAP:+ sys.exit(f"unmapped MatMul {hf}")+ gname = f"blk.{layer}.{QUANT_MAP[leaf]}.weight"+ t = tensors.get(gname)+ if t is None:+ sys.exit(f"{hf}: {gname} missing from GGUF")+ k_of[hf] = int(t.shape[0])+ # row permutation undoing llama.cpp's tiled V heads+ stem = QUANT_MAP.get(leaf)+ rows = cols = None+ if stem == "attn_qkv":+ rows = np.concatenate([np.arange(qk_rows), qk_rows + perm_hd])+ elif stem == "attn_gate":+ rows = perm_hd+ elif stem in ("ssm_alpha", "ssm_beta"):+ rows = perm_1+ elif stem == "ssm_out" and not v_grouped:+ if hd != GROUP:+ sys.exit("ssm_out column permutation needs head_v_dim == 128")+ cols = perm_1 # whole 128-groups move++ u2c, sc_c = u2_chain(mm)+ if u2c is not None and t.tensor_type.name != "PQ2_0":+ # ternary in the template, dense in this GGUF (Bonsai 2 keeps the+ # GDN gate projections in bf16): drop the decompression subgraph+ if a.verify:+ sys.exit(f"{hf}: template is u2 but GGUF holds {t.tensor_type.name}")+ w = gguf_f32(t)+ if rows is not None:+ w = w[rows]+ if w.shape[1] in signs and fold_norm \+ and _norm_folded_input(mm, folded, tensors, layer):+ w = w * signs[w.shape[1]][None, :]+ wc = ops.constant(w.astype(np.float16))+ wc.set_friendly_name(u2c.get_friendly_name().replace("_compressed", "") + "_dense")+ mm.input(1).replace_source_output(+ ops.convert(wc, mm.input_value(1).get_element_type()).output(0))+ n_dense += 1+ elif u2c is not None:+ if t.tensor_type.name != "PQ2_0":+ sys.exit(f"{hf}: template is u2 but GGUF holds {t.tensor_type.name}")+ blocks = pq2_blocks(t)+ if rows is not None:+ blocks = blocks[rows]+ if cols is not None:+ blocks = blocks[:, cols]+ n, gcount = blocks.shape[:2]+ if list(u2c.get_output_shape(0)) != [n, gcount, GROUP]:+ sys.exit(f"{hf}: u2 shape {list(u2c.get_output_shape(0))} vs GGUF {[n, gcount, GROUP]}")+ codes = np.ascontiguousarray(blocks[:, :, 2:])+ scale = blocks[:, :, :2].copy().view("<f2").reshape(n, gcount, 1)+ if a.verify:+ same = np.array_equal(u2c.get_data().view(np.uint8), codes.reshape(-1))+ tmpl_scale = sc_c.get_data().astype(np.float32).reshape(n, gcount)+ # groups that are all-zero get scale 0 from the quantizer+ allzero = (codes == 0x55).all(axis=2)+ sd = np.abs(tmpl_scale - scale.reshape(n, gcount).astype(np.float32))+ sd[allzero] = 0+ if not same or sd.max() != 0:+ sys.exit(f"{hf}: verify failed codes_equal={same} scale_maxdiff={sd.max()}")+ else:+ if leaf == "mlp.up_proj" and f"blk.{layer}.ffn_down.weight" in folded \+ and fold_up:+ # down_proj's input sign flip folds into up_proj's output rows+ neg = signs[n] < 0+ codes = codes.reshape(n, -1).copy()+ codes[neg] = flip_code_bytes(codes[neg])+ n_row_fold += 1+ tq = ov.Tensor(ov.Type.u2, [n, gcount, GROUP])+ np.frombuffer(tq.data, dtype=np.uint8)[:] = codes.reshape(-1)+ new_q = ops.constant(tq)+ new_q.set_friendly_name(u2c.get_friendly_name())+ for tgt in list(u2c.output(0).get_target_inputs()):+ tgt.replace_source_output(new_q.output(0))+ replace_const(sc_c, scale.astype(np.float16))+ n_u2 += 1+ else:+ # dense fp16/bf16 weight behind a Convert+ wc = const_of(mm, 1)+ if wc is None:+ sys.exit(f"{hf}: no constant weight found")+ w = gguf_f32(t)+ if rows is not None:+ w = w[rows]+ if a.verify:+ rep.add("dense_w", hf, w, const_f32(wc))+ else:+ if gname in folded:+ sys.exit(f"{hf}: dense weight marked folded")+ # compensate the sign flip folded into its RMSNorm input+ k = w.shape[1]+ if k in signs and fold_norm \+ and _norm_folded_input(mm, folded, tensors, layer):+ w = w * signs[k][None, :]+ replace_const(wc, w)+ n_dense += 1+ print(f"[ir] weights: {n_u2} ternary, {n_dense} dense, {n_row_fold} up_proj row folds "+ f"({time.perf_counter() - t0:.0f}s)")++ # ---- dense per-layer tensors --------------------------------------------+ n_layers = int(g("block_count"))+ norm_nodes = {}+ for node in model.get_ordered_ops():+ name = node.get_friendly_name()+ if not name.startswith(PREFIX + LM):+ continue+ rest = name[len(PREFIX + LM):]+ if rest == "norm/aten::mul/Multiply_1":+ layer, suffix = -1, "norm"+ gname, kind = "output_norm.weight", "norm"+ else:+ lm = re.match(r"layers\.(\d+)\.(.+)$", rest)+ if not lm or lm.group(2) not in DENSE_MAP:+ continue+ layer, suffix = int(lm.group(1)), lm.group(2)+ stem, kind = DENSE_MAP[suffix]+ gname = f"blk.{layer}.{stem}"+ t = tensors.get(gname)+ if t is None:+ sys.exit(f"{name}: {gname} missing from GGUF")+ x = gguf_f32(t)+ port = 0 if kind == "a_log" else 1+ if kind == "norm" and suffix == "linear_attn.norm/aten::mul/Multiply_1":+ port = 0+ c = const_of(node, port)+ if c is None:+ sys.exit(f"{name}: constant not found on port {port}")+ shape = list(c.get_output_shape(0))+ if kind == "a_log":+ if not (x < 0).all():+ sys.exit(f"{gname}: expected A = -exp(A_log) < 0")+ x = (-x)[perm_1] # template holds exp(A_log)+ elif kind == "dt_bias":+ x = x[perm_1]+ elif kind == "conv1d":+ idx = np.concatenate([np.arange(qk_rows), qk_rows + perm_hd])+ x = x[idx] # [C, k]+ x = x.reshape(shape)+ if a.verify:+ rep.add(kind if kind != "norm" else f"norm:{suffix.split('/')[0].split('.')[-1]}",+ name, x, const_f32(c))+ else:+ c = replace_const(c, x) # the fold below must see the new data+ if kind == "norm":+ norm_nodes[(layer, suffix.split("/")[0])] = (node, c)+ print(f"[ir] dense per-layer tensors done ({time.perf_counter() - t0:.0f}s)")++ if a.verify:+ rep.dump()++ # ---- Hadamard rotation ---------------------------------------------------+ if folded and not a.verify:+ H = ops.constant(hadamard(block).astype(np.float32))+ H.set_friendly_name("hadamard.H1024")+ n_rot = n_sign_mul = n_norm_fold = 0+ rotated_outputs = {} # producer output -> rotated output (shared)++ def rotate(src_out, k: int, explicit_sign: bool):+ nonlocal n_rot, n_sign_mul+ key = (src_out.get_node().get_friendly_name(), src_out.get_index(), explicit_sign)+ if key in rotated_outputs:+ return rotated_outputs[key]+ x = src_out+ if explicit_sign:+ s = ops.constant(signs[k].reshape(1, 1, k).astype(np.float32))+ x = ops.multiply(x, s)+ n_sign_mul += 1+ r = ops.reshape(x, ops.constant(np.array([0, 0, k // block, block], np.int64)), True)+ h = ops.matmul(r, H, False, False)+ out = ops.reshape(h, ops.constant(np.array([0, 0, k], np.int64)), True)+ out.set_friendly_name(src_out.get_node().get_friendly_name() + "/hadamard")+ rotated_outputs[key] = out.output(0)+ n_rot += 1+ return out.output(0)++ for hf, mm in sorted(matmuls.items()):+ if hf == "lm_head":+ gname, layer, leaf = "output.weight", -1, "lm_head"+ else:+ lm = layer_re.match(hf)+ layer, leaf = int(lm.group(1)), lm.group(2)+ gname = f"blk.{layer}.{QUANT_MAP[leaf]}.weight"+ if gname not in folded:+ continue+ k = k_of[hf]+ if k not in signs:+ sys.exit(f"{hf}: folded with K={k} but no sign vector")+ src = mm.input_value(0)+ producer = src.get_node().get_friendly_name()+ # sign handling per input kind+ if leaf in ("self_attn.q_proj", "self_attn.k_proj", "self_attn.v_proj",+ "linear_attn.in_proj_qkv", "linear_attn.in_proj_z",+ "mlp.gate_proj", "mlp.up_proj", "lm_head"):+ explicit = not fold_norm # folded into the RMSNorm weight below+ elif leaf == "mlp.down_proj":+ explicit = not fold_up # folded into up_proj rows+ else:+ explicit = True # attention/GDN out_proj+ mm.input(0).replace_source_output(rotate(src, k, explicit))++ # RMSNorm sign folds (input_layernorm, post_attention_layernorm, final norm)+ for (layer, which), (node, c) in norm_nodes.items():+ if not fold_norm or which not in ("input_layernorm", "post_attention_layernorm", "norm"):+ continue+ k = int(np.prod(c.get_output_shape(0)))+ if k not in signs:+ continue+ consumers = [t.get_node() for t in node.output(0).get_target_inputs()]+ kinds = {cn.get_type_name() for cn in consumers}+ if not kinds <= {"MatMul", "ShapeOf", "Reshape"}:+ sys.exit(f"{node.get_friendly_name()}: unexpected consumers {kinds}")+ data = const_f32(c).reshape(-1) * signs[k]+ replace_const(c, data.reshape(c.get_output_shape(0)))+ n_norm_fold += 1+ print(f"[ir] hadamard: {n_rot} rotations inserted, {n_sign_mul} explicit sign multiplies, "+ f"{n_norm_fold} norm folds")++ # ---- embedding ------------------------------------------------------------+ t = tensors["token_embd.weight"]+ if t.tensor_type.name != "PQ2_0":+ sys.exit(f"token_embd is {t.tensor_type.name}, expected PQ2_0")+ if a.verify:+ emb = core.read_model(a.template_embed)+ emb_c = next(n for n in emb.get_ordered_ops()+ if n.get_type_name() == "Constant" and len(n.get_output_shape(0)) == 2+ and n.get_output_shape(0)[1] == int(g("embedding_length")))+ E = blocks_dequant(pq2_blocks(t))+ if folded:+ k = E.shape[1]+ Hn = hadamard(block).astype(np.float32)+ for b in range(k // block):+ E[:, b * block:(b + 1) * block] = E[:, b * block:(b + 1) * block] @ Hn+ E *= signs[k][None, :]+ rep.add("embedding", "token_embd", E, const_f32(emb_c))+ rep.dump()+ print("[ir] verify OK")+ return+ blocks = pq2_blocks(t)+ emb = ternary_embedding(blocks, block, signs[blocks.shape[1] * GROUP] if folded else None)+ print(f"[ir] embedding: ternary {blocks.shape[0]}x{blocks.shape[1] * GROUP}"+ f"{', inverse-rotated on the device' if folded else ''} ({time.perf_counter() - t0:.0f}s)")+ del blocks++ os.makedirs(a.out_dir, exist_ok=True)+ ov.save_model(model, os.path.join(a.out_dir, "openvino_model.xml"), compress_to_fp16=False)+ ov.save_model(emb, os.path.join(a.out_dir, "openvino_text_embeddings_model.xml"),+ compress_to_fp16=False)+ print(f"[ir] wrote {a.out_dir} ({time.perf_counter() - t0:.0f}s)")+++def _norm_folded_input(mm, folded, tensors, layer) -> bool:+ """True when the RMSNorm feeding this dense MatMul had its weight+ sign-folded (i.e. some sibling consumer is a folded projection)."""+ src = mm.input_value(0).get_node()+ for tgt in src.output(0).get_target_inputs():+ sib = tgt.get_node()+ m = re.match(re.escape(PREFIX) + re.escape(LM) + r"layers\.(\d+)\.(.+)/ov_ext::linear/MatMul$",+ sib.get_friendly_name())+ if m and m.group(2) in QUANT_MAP:+ if f"blk.{m.group(1)}.{QUANT_MAP[m.group(2)]}.weight" in folded:+ return True+ return False+++if __name__ == "__main__":+ main()diff --git a/src/plugins/intel_gpu/tools/int2/quantize_ir_ternary.py b/src/plugins/intel_gpu/tools/int2/quantize_ir_ternary.pynew file mode 100644index 00000000000..d8eb2821b1d--- /dev/null+++ b/src/plugins/intel_gpu/tools/int2/quantize_ir_ternary.py@@ -0,0 +1,116 @@+# Copyright (C) 2018-2026 Intel Corporation+# SPDX-License-Identifier: Apache-2.0++"""Rewrite the fp16 MatMul weights of an exported LLM into ternary u2 weights.++OpenVINO has no signed 2-bit type, so ternary is expressed the way the GPU+plugin's weight-compression pattern expects: u2 codes {0,1,2} with a scalar zero+point of 1, times a per-group fp16 scale. Weights that are already exactly+ternary are reproduced rather than approximated.+"""++import argparse+import gc+import numpy as np+import openvino as ov+from openvino import opset13 as ops++GROUP = 128+++def pack_u2(codes: np.ndarray) -> np.ndarray:+ """[..] uint8 in {0,1,2} -> packed u2, value j at bits [2j, 2j+1]."""+ flat = codes.reshape(-1).astype(np.uint8) & 0x3+ if flat.size % 4:+ flat = np.pad(flat, (0, 4 - flat.size % 4))+ q = flat.reshape(-1, 4)+ return (q[:, 0] | (q[:, 1] << 2) | (q[:, 2] << 4) | (q[:, 3] << 6)).astype(np.uint8)+++def to_f32(const) -> np.ndarray:+ """Constant data as fp32, decoding bf16 by hand.++ numpy has no bf16, so Constant.get_data() hands back a float16-typed *view*+ of the raw bf16 bits rather than a conversion. Reading that as fp16 keeps the+ ternary codes (the sign is bit 15 either way) but corrupts every group scale,+ which is silent: the model loads and generates fluent nonsense.+ """+ raw = const.get_data()+ if const.get_output_element_type(0) == ov.Type.bf16:+ return (raw.view(np.uint16).astype(np.uint32) << 16).view(np.float32)+ return raw.astype(np.float32)+++def ternary_quantize(w: np.ndarray):+ """w is [N, K] fp32. Returns u2 codes [N, K] and fp16 scales [N, K/GROUP]."""+ n, k = w.shape+ g = w.reshape(n, k // GROUP, GROUP)+ scale = np.abs(g).max(axis=2)+ safe = np.where(scale == 0, 1.0, scale)+ q = np.clip(np.rint(g / safe[:, :, None]), -1, 1).astype(np.int8).reshape(n, k)+ return (q + 1).astype(np.uint8), scale.astype(np.float16)+++def main():+ ap = argparse.ArgumentParser()+ ap.add_argument("--in", dest="src", required=True)+ ap.add_argument("--out", dest="dst", required=True)+ ap.add_argument("--min-k", type=int, default=1024, help="skip tiny MatMuls")+ ap.add_argument("--skip-n", type=int, default=0, help="keep MatMuls with this N dense (non-ternary lm_head)")+ args = ap.parse_args()++ core = ov.Core()+ model = core.read_model(args.src)++ targets = []+ for node in model.get_ordered_ops():+ if node.get_type_name() != "MatMul":+ continue+ w = node.input_value(1).get_node()+ # optimum emits fp16 weights behind a Convert to the inference precision+ conv = None+ if w.get_type_name() == "Convert":+ conv, w = w, w.input_value(0).get_node()+ if w.get_type_name() != "Constant":+ continue+ shape = list(w.get_output_shape(0))+ if len(shape) != 2 or shape[1] % GROUP or shape[1] < args.min_k or shape[0] == args.skip_n:+ continue+ targets.append((node, conv, w, shape))++ print(f"rewriting {len(targets)} MatMul weights")+ total_in = total_out = 0+ for i, (mm, conv, const, (n, k)) in enumerate(targets):+ # whatever fed the MatMul before, the replacement has to keep that type+ orig_et = mm.input_value(1).get_element_type()+ w = to_f32(const)+ codes, scale = ternary_quantize(w)+ total_in += w.size * 2+ del w++ packed = pack_u2(codes)+ t = ov.Tensor(ov.Type.u2, [n, k // GROUP, GROUP])+ np.frombuffer(t.data, dtype=np.uint8)[: packed.size] = packed+ wq = ops.constant(t)+ del codes, packed++ zp = ops.constant(np.array(1.0, np.float16).reshape(1, 1, 1))+ sc = ops.constant(scale.reshape(n, k // GROUP, 1))+ total_out += scale.size * 2 + (n * k) // 4+ del scale++ deq = ops.multiply(ops.subtract(ops.convert(wq, "f16"), zp), sc)+ flat = ops.reshape(deq, ops.constant(np.array([n, k], np.int64)), False)+ out = flat if orig_et == ov.Type.f16 else ops.convert(flat, orig_et)+ mm.input(1).replace_source_output(out.output(0))+ if (i + 1) % 50 == 0:+ print(f" {i + 1}/{len(targets)}")+ gc.collect()++ print(f"weights {total_in / 2**30:.2f} GiB -> {total_out / 2**30:.2f} GiB")+ ov.save_model(model, args.dst, compress_to_fp16=False)+ print("saved", args.dst)+++if __name__ == "__main__":+ main()