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] GatedResidual(Hyper-connection) internal op support (#39014)
River Lidf1ae4592f34
diff --git a/docs/articles_en/documentation/openvino-ir-format/operation-sets/operation-specs.rst b/docs/articles_en/documentation/openvino-ir-format/operation-sets/operation-specs.rstindex 7a37919e72b..3911635b1a9 100644--- a/docs/articles_en/documentation/openvino-ir-format/operation-sets/operation-specs.rst+++ b/docs/articles_en/documentation/openvino-ir-format/operation-sets/operation-specs.rst@@ -88,6 +88,7 @@ Operation SpecificationsGRUCell-3 <operation-specs/sequence/gru-cell-3>GRUSequence-5 <operation-specs/sequence/gru-sequence-5>GatedDeltaNet <operation-specs/internal/gated-delta-net>+ GatedResidual <operation-specs/internal/gated-residual>GatherTree-1 <operation-specs/movement/gather-tree-1>Gather-1 <operation-specs/movement/gather-1>Gather-7 <operation-specs/movement/gather-7>diff --git a/docs/articles_en/documentation/openvino-ir-format/operation-sets/operation-specs/internal/gated-residual.rst b/docs/articles_en/documentation/openvino-ir-format/operation-sets/operation-specs/internal/gated-residual.rstnew file mode 100644index 00000000000..1d52496a8d2--- /dev/null+++ b/docs/articles_en/documentation/openvino-ir-format/operation-sets/operation-specs/internal/gated-residual.rst@@ -0,0 +1,432 @@+.. {#openvino_docs_ops_internal_GatedResidual}++GatedResidual+=============++.. meta::+ :description: Learn about GatedResidual, an internal operation for branch-wise gated residual READ and WRITE computations used by hyper-connection transformer models.++**Versioned name**: *GatedResidual*++**Category**: *Internal*++**Short description**:+The *GatedResidual* operation represents the gated residual (hyper-connection) mechanism used by Qwen4-Exp / Qwen3.8-Flash-Next-style models. It handles branch-wise normalization and gated branch merging, and the gated residual update. READ and WRITE are distinct operation modes; the sub-layer output is an explicit input to WRITE. READ optionally accepts ``i4``/``u4``/``i8``/``u8`` compressed ``w_down`` / ``w_up`` / ``w_inject`` weights.++**Detailed description**++A residual stream with ``C`` branches and per-branch hidden size ``D`` is physically stored as+``[B, T, C*D]`` and logically interpreted as ``[B, T, C, D]``. ``GatedResidual`` provides two+modes:++* ``READ`` normalizes each branch independently, computes a low-rank channel-wise read gate,+ merges the gated branches, and may also emit a per-branch write gate. Without a write gate+ it is a terminal branch mixer.+* ``WRITE`` broadcasts a previously computed per-branch write gate over the hidden dimension+ and adds the gated sub-layer output to every residual branch.++A typical transformer region is:++.. code-block:: text++ GatedResidual(READ) -> attention / MLP / other sub-layer -> GatedResidual(WRITE)++The branch normalization is over each branch's ``D`` channels, not over the concatenated+``C*D`` dimension. The factors ``1/C`` in the down projection, branch merge, and write-gate+projection are part of the operation semantics. The read gate is per branch and channel; the+write gate is one scalar per branch and token, with range ``(0, 2)``.++**Mathematical definition**++Let ``R_c`` be branch ``c`` of the residual row, ``Rbar_c`` its normalized value, ``W_down``+shape ``[L, C*D]``, ``W_up`` shape ``[C*D, L]``, and ``W_inject`` shape ``[C, C*D]``. The+stored normalization weight ``w`` is the gain :math:`\gamma = w`; a checkpoint that stores+``w`` as an offset from one must fold the ``1 +`` into the weight. :math:`\gamma_c` is the+``D``-element segment of :math:`\gamma` that belongs to branch ``c``.++For each branch:++.. math::++ \bar{R}_c = \frac{R_c}{\sqrt{\operatorname{mean}(R_c^2) + \epsilon}} \odot \gamma_c++where the mean is taken over the ``D`` channels of branch ``c``.++For the READ projections, let ``Rbar`` denote the normalized branches represented as a+``C*D``-wide vector:++.. math::++ T = \operatorname{SiLU}\left(\frac{\bar{R} W_{down}^{T}}{C}\right)++ G = \operatorname{sigmoid}(T W_{up}^{T})++ M = \frac{1}{C}\sum_{c=0}^{C-1} G_c \odot \bar{R}_c++``G`` is a per-branch, per-channel gate. If ``produce_write_gate`` is true, READ also computes:++.. math::++ S = 2\,\operatorname{sigmoid}\left(\frac{\bar{R} W_{inject}^{T}}{C}\right)++``S`` has logical shape ``[B, T, C]``. Its values are in ``(0, 2)`` and it must not be clamped+to ``(0, 1)``.++WRITE mode uses the original widened residual and the sub-layer output ``Y``:++.. math::++ R'_c = R_c + S_c Y++The scalar ``S_c`` broadcasts across the ``D`` channels of branch ``c``. Without+``produce_write_gate``, READ uses the same equations for ``M`` but does not calculate ``S``.++The following PyTorch-equivalent code illustrates the full computation. Weights are given as+decompressed floating-point tensors; ``dequantize_weight`` shows how the compressed+``i4``/``u4``/``i8``/``u8`` weights (``w_down``, ``w_up`` and ``w_inject``) are expanded first, with ``zp``+already unpacked to one value per element (signed types sign-extended) or ``None`` when the op has no zero points.++.. code-block:: py++ import torch+ import torch.nn.functional as F++ def dequantize_weight(q, scale, zp=None):+ # q: [N, K] i4/u4/i8/u8 values, scale / zp: [N, G]; the group size K // G is derived from the shapes+ N, K = q.shape+ G = scale.shape[1]+ assert K % G == 0+ s = scale.repeat_interleave(K // G, dim=1) # [N, K]+ z = zp.repeat_interleave(K // G, dim=1).float() if zp is not None else 0.0 # no zero points: 0+ return ((q.float() - z) * s.float()).half()++ def branch_rms_norm(residual, norm_weight, C, D, epsilon):+ # residual: [..., C*D]; every branch is normalized over its own D channels+ r = residual.float().unflatten(-1, (C, D))+ r = r * torch.rsqrt(r.pow(2).mean(dim=-1, keepdim=True) + epsilon)+ gain = norm_weight.float().unflatten(-1, (C, D))+ return r * gain # [..., C, D]++ def gated_residual_read(residual, norm_weight, w_down, w_up, w_inject,+ C, D, epsilon=1e-6, produce_write_gate=False):+ # READ; w_inject is None when produce_write_gate is False+ r_bar = branch_rms_norm(residual, norm_weight, C, D, epsilon)+ r_bar_flat = r_bar.flatten(-2) # [..., C*D]++ t = F.silu(F.linear(r_bar_flat, w_down.float()) / C) # [..., L]+ gate = torch.sigmoid(F.linear(t, w_up.float())).unflatten(-1, (C, D))+ mixed = (gate * r_bar).mean(dim=-2) # [..., D]++ if not produce_write_gate:+ return mixed.to(residual.dtype)+ write_gate = 2.0 * torch.sigmoid(F.linear(r_bar_flat, w_inject.float()) / C) # [..., C]+ return mixed.to(residual.dtype), write_gate.to(residual.dtype)++ def gated_residual_write(residual, sublayer_y, write_gate, C, D):+ # residual: [..., C*D], sublayer_y: [..., D], write_gate: [..., C] in (0, 2)+ r = residual.float().unflatten(-1, (C, D))+ out = r + write_gate.float().unsqueeze(-1) * sublayer_y.float().unsqueeze(-2)+ return out.flatten(-2).to(residual.dtype) # [..., C*D]++**Attributes**++* *mode*++ * **Description**: Selects ``READ`` or ``WRITE``.+ * **Range of values**: ``0`` (READ), ``1`` (WRITE)+ * **Type**: ``int``+ * **Required**: *yes*++* *hc_count*++ * **Description**: Number of residual branches, :math:`C`.+ * **Range of values**: a positive integer+ * **Type**: ``int``+ * **Required**: *yes*++* *hidden_size*++ * **Description**: Hidden width of each branch, :math:`D`.+ * **Range of values**: a positive integer+ * **Type**: ``int``+ * **Required**: *yes*++* *lowrank*++ * **Description**: Low-rank width, :math:`L`, used by READ projections. It must be positive for READ and is unused by WRITE.+ * **Range of values**: a positive integer for READ; any non-negative integer for WRITE+ * **Type**: ``int``+ * **Required**: *yes*++* *epsilon*++ * **Description**: Epsilon used by branch-wise RMS normalization.+ * **Range of values**: a positive floating-point number+ * **Type**: ``float``+ * **Default value**: ``1e-6``+ * **Required**: *no*++* *produce_write_gate*++ * **Description**: In READ mode, compute and emit the write gate using ``w_inject``. It is unused in WRITE mode.+ * **Type**: ``bool``+ * **Default value**: ``false``+ * **Required**: *no*++* *scale_gn*++ * **Description**: Plugin-internal. When true, the scales and zero points of the compressed weights are laid out ``[G, N]`` instead of ``[N, G]``. The GPU plugin sets it when it converts the layout for its kernels; IR producers should leave it unset.+ * **Type**: ``bool``+ * **Default value**: ``false``+ * **Required**: *no*++**Inputs**++Input indices depend on ``mode``. All dimensions below use ``B`` for batch, ``T`` for tokens,+``C`` for branches, ``D`` for per-branch hidden width, and ``L`` for low-rank width. The logical+residual shape is ``[B, T, C, D]``; the physical shape is ``[B, T, C*D]``. Any rank of at least 2+is accepted for the data inputs (``residual``, ``sublayer_y``, ``write_gate``), as long as the+last dimension is as specified below and the leading dimensions agree across them.++* **READ input 0**: ``residual``+ A floating-point tensor with logical shape ``[B, T, C, D]`` and physical shape+ ``[B, T, C*D]``. **Required.**++* **READ input 1**: ``norm_weight``+ A 1D tensor of shape ``[C*D]`` containing the branch-wise normalization gains in flattened+ storage order. Each branch uses its own contiguous ``D``-element segment. **Required.**++* **READ input 2**: ``w_down``+ A 2D tensor of shape ``[L, C*D]`` for the low-rank down projection. Floating-point in the+ uncompressed forms, ``i4``, ``u4``, ``i8`` or ``u8`` in the compressed forms. **Required.**++* **READ input 3**: ``w_up``+ A 2D tensor of shape ``[C*D, L]`` for the up projection that produces read-gate logits. Floating-point in the+ uncompressed forms, ``i4``, ``u4``, ``i8`` or ``u8`` in the compressed forms. **Required.**++READ accepts one of six input forms, selected by the weight element type, by whether+zero points are present, and by ``produce_write_gate``. Inputs 0-3 are identical in all of them. The+compression parameters, when present, follow input 3. The write-gate inputs, when present, are always+the **last** inputs, so the index of ``w_inject`` depends on the form:++.. list-table::+ :header-rows: 1++ * - Form+ - Inputs+ * - Floating-point weights+ - 4 inputs: ``residual``, ``norm_weight``, ``w_down``, ``w_up``+ * - Floating-point weights, write gate+ - 5 inputs: inputs 0-3 as above, then ``w_inject`` (input 4)+ * - Compressed weights, no zero points+ - 6 inputs: inputs 0-3 as above, then ``scale_down`` (4), ``scale_up`` (5)+ * - Compressed weights+ - 8 inputs: inputs 0-5 as in the previous form, then ``zp_down`` (6), ``zp_up`` (7)+ * - Compressed weights, no zero points, write gate+ - 8 inputs: inputs 0-5 as in the compressed form without zero points, then ``w_inject`` (6),+ ``scale_inject`` (7)+ * - Compressed weights, write gate+ - 11 inputs: inputs 0-7 as in the compressed form, then ``w_inject`` (8), ``scale_inject`` (9),+ ``zp_inject`` (10)++Zero points are optional but all-or-nothing: either ``zp_down`` and ``zp_up`` (and ``zp_inject``) are all+present or none is, and a missing zero point is 0. For a given ``produce_write_gate`` the number of+inputs selects the form unambiguously.++* **READ inputs 4-5 (compressed forms only)**: when the weights are ``i4``, ``u4``, ``i8`` or+ ``u8``, these inputs carry the scales of ``w_down`` and ``w_up``.++ * input 4: ``scale_down``, ``f16``, shape ``[L, G_d]``+ * input 5: ``scale_up``, ``f16``, shape ``[C*D, G_u]``++* **READ inputs 6-7 (compressed forms with zero points only)**:++ * input 6: ``zp_down``, same element type as ``w_down``, same shape as ``scale_down``+ * input 7: ``zp_up``, same element type as ``w_up``, same shape as ``scale_up``++* **READ write-gate inputs (when produce_write_gate is true; always the last inputs)**:++ * ``w_inject``: a 2D tensor of shape ``[C, C*D]`` used to compute the write gate. Floating-point+ in the five-input form (input 4), ``i4``, ``u4``, ``i8`` or ``u8`` in the compressed forms+ (input 6 without zero points, input 8 with them).+ * ``scale_inject``, compressed forms only: ``f16``, shape ``[C, G_i]`` (the input after ``w_inject``).+ * ``zp_inject``, compressed form with zero points only (input 10): same element type as ``w_inject``,+ same shape as ``scale_inject``.++For every compressed weight, scales and zero points have shape ``[N, G]``, where ``N`` is the output+channel count (the number of rows of the weight) and ``G`` the number of groups. The group size is not an attribute: it is derived as ``group_size = K / G``,+where ``K`` is the number of columns of the weight (``C*D`` for ``w_down`` and ``w_inject``, ``L``+for ``w_up``) and ``G`` the number of columns of the scale and zero point. ``K`` must be divisible by+``G``; ``G = 1`` means per-channel quantization. ``w_down``, ``w_up`` and ``w_inject`` (when+present) must all share one element type; ``i4``/``u4``/``i8``/``u8`` weights are accepted only in the compressed+forms. 4-bit weights and zero points are packed two elements per byte in row-major order, the even+element in the low nibble; ``i4`` elements are two's complement nibbles. Dequantization is+``w = (q - zp) * scale`` with ``q`` and ``zp`` interpreted according to the element type, see ``dequantize_weight``+above.++* **WRITE input 0**: ``residual``+ A floating-point tensor with logical shape ``[B, T, C, D]`` and physical shape+ ``[B, T, C*D]``. **Required.**++* **WRITE input 1**: ``sublayer_y``+ A floating-point tensor of shape ``[B, T, D]``, containing the output of the intervening+ sub-layer. **Required.**++* **WRITE input 2**: ``write_gate``+ A floating-point tensor of shape ``[B, T, C]``. The gate is scalar per branch and broadcasts+ over that branch's ``D`` channels. **Required.**++**Outputs**++* **READ output 0**: ``mixed``+ A tensor of shape ``[B, T, D]``. It is the mean of the branch-wise, read-gated normalized+ residual states.++* **READ output 1**: ``write_gate``+ Present only when ``produce_write_gate`` is true. Shape ``[B, T, C]``; values are in ``(0, 2)``.++* **WRITE output 0**: ``residual_out``+ A tensor with the same shape as the residual input, ``[B, T, C*D]`` (logically+ ``[B, T, C, D]``).++**Shape inference and type rules**++* ``hc_count`` and ``hidden_size`` must be positive.+* The residual rank must be at least 2, and its last dimension must be compatible with+ ``hc_count * hidden_size``.+* READ requires four inputs with floating-point weights, five when ``produce_write_gate`` is true, six (without zero points) or eight (with zero points) for compressed weights, or eight (without) or eleven (with zero points) for compressed weights with a write gate (see the input forms above).+ The write-gate inputs are always the last inputs.+ READ requires ``lowrank > 0``.+* ``norm_weight`` must have shape ``[C*D]``, ``w_down`` ``[L, C*D]``, ``w_up`` ``[C*D, L]``, and+ ``w_inject`` (if present) ``[C, C*D]``. ``w_down``, ``w_up`` and ``w_inject`` (if present) must share one element type.+* For the compressed form, scale tensors must be rank 2 with first dimension equal to the weight's+ output channel count (``L`` for ``w_down``, ``C*D`` for ``w_up``, ``C`` for ``w_inject``) and last dimension equal to the group count ``G``, zero points (when present) must have the+ same shape as their scales, scales must be ``f16``, zero points must have the weight element type (``i4``, ``u4``, ``i8`` or ``u8``), and ``K`` must be divisible by the group count ``G``+ (the group size ``K / G`` is derived from the shapes, see the compressed inputs above).+* WRITE requires exactly three inputs and returns the residual shape. ``sublayer_y`` must have+ last dimension ``D``, ``write_gate`` must have last dimension ``C``, and both must share the+ residual element type.+* READ output 0 preserves the residual rank and leading dimensions and replaces the+ final dimension with ``hidden_size``. When the write gate is produced, output 1 preserves the+ leading dimensions and replaces the final dimension with ``hc_count``.+* All outputs use the element type of ``residual``.++**Implementation notes**++The specification places no limit on ``hc_count``, ``hidden_size`` or ``lowrank`` beyond being+positive. A plugin may support only a subset of geometries, element types, quantization group+sizes, or the compressed-weight form, and is expected to reject or not fuse the operation otherwise.+++**Example**++The example below shows READ with four branches, per-branch hidden width 64, low-rank width 32,+and a generated write gate. The flattened residual has shape ``[1, 2, 256]``.++.. code-block:: xml+ :force:++ <layer ... type="GatedResidual">+ <data mode="0" hc_count="4" hidden_size="64" lowrank="32"+ epsilon="1e-6" produce_write_gate="true"/>+ <input>+ <port id="0"> <!-- residual: [B,T,C*D] -->+ <dim>1</dim><dim>2</dim><dim>256</dim>+ </port>+ <port id="1"> <!-- norm_weight: [C*D] -->+ <dim>256</dim>+ </port>+ <port id="2"> <!-- w_down: [L,C*D] -->+ <dim>32</dim><dim>256</dim>+ </port>+ <port id="3"> <!-- w_up: [C*D,L] -->+ <dim>256</dim><dim>32</dim>+ </port>+ <port id="4"> <!-- w_inject: [C,C*D] -->+ <dim>4</dim><dim>256</dim>+ </port>+ </input>+ <output>+ <port id="5"> <!-- mixed: [B,T,D] -->+ <dim>1</dim><dim>2</dim><dim>64</dim>+ </port>+ <port id="6"> <!-- write_gate: [B,T,C] -->+ <dim>1</dim><dim>2</dim><dim>4</dim>+ </port>+ </output>+ </layer>++The matching WRITE that adds the sub-layer output back to every branch:++.. code-block:: xml+ :force:++ <layer ... type="GatedResidual">+ <data mode="1" hc_count="4" hidden_size="64" lowrank="32"+ epsilon="1e-6" produce_write_gate="false"/>+ <input>+ <port id="0"> <!-- residual: [B,T,C*D] -->+ <dim>1</dim><dim>2</dim><dim>256</dim>+ </port>+ <port id="1"> <!-- sublayer_y: [B,T,D] -->+ <dim>1</dim><dim>2</dim><dim>64</dim>+ </port>+ <port id="2"> <!-- write_gate: [B,T,C] -->+ <dim>1</dim><dim>2</dim><dim>4</dim>+ </port>+ </input>+ <output>+ <port id="3"> <!-- residual_out: [B,T,C*D] -->+ <dim>1</dim><dim>2</dim><dim>256</dim>+ </port>+ </output>+ </layer>++A READ without a write gate, with ``u4`` compressed weights (eight-input form). ``w_down`` has ``K = C*D = 256``+and ``G_d = 8``, so its group size is ``256 / 8 = 32``; ``w_up`` has ``K = L = 32`` and ``G_u = 1``,+so it is per-channel (group size 32 = K):++.. code-block:: xml+ :force:++ <layer ... type="GatedResidual">+ <data mode="0" hc_count="4" hidden_size="64" lowrank="32"+ epsilon="1e-6" produce_write_gate="false"/>+ <input>+ <port id="0"> <!-- residual: f16 [B,T,C*D] -->+ <dim>1</dim><dim>2</dim><dim>256</dim>+ </port>+ <port id="1"> <!-- norm_weight: f16 [C*D] -->+ <dim>256</dim>+ </port>+ <port id="2"> <!-- w_down: u4 [L,C*D] -->+ <dim>32</dim><dim>256</dim>+ </port>+ <port id="3"> <!-- w_up: u4 [C*D,L] -->+ <dim>256</dim><dim>32</dim>+ </port>+ <port id="4"> <!-- scale_down: f16 [L,G_d] -->+ <dim>32</dim><dim>8</dim>+ </port>+ <port id="5"> <!-- scale_up: f16 [C*D,G_u] -->+ <dim>256</dim><dim>1</dim>+ </port>+ <port id="6"> <!-- zp_down: u4 [L,G_d] -->+ <dim>32</dim><dim>8</dim>+ </port>+ <port id="7"> <!-- zp_up: u4 [C*D,G_u] -->+ <dim>256</dim><dim>1</dim>+ </port>+ </input>+ <output>+ <port id="8"> <!-- mixed: f16 [B,T,D] -->+ <dim>1</dim><dim>2</dim><dim>64</dim>+ </port>+ </output>+ </layer>++**Types**++* *T*: floating-point element type of the data inputs.+* *T_W*: ``i4``, ``u4``, ``i8`` or ``u8`` for compressed ``w_down`` / ``w_up`` / ``w_inject`` (compressed forms only); in the uncompressed forms they use a floating-point type.+* Outputs use the element type of ``residual``.diff --git a/src/plugins/intel_gpu/include/intel_gpu/op/gated_residual.hpp b/src/plugins/intel_gpu/include/intel_gpu/op/gated_residual.hppnew file mode 100644index 00000000000..ea9284124d5--- /dev/null+++ b/src/plugins/intel_gpu/include/intel_gpu/op/gated_residual.hpp@@ -0,0 +1,185 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#pragma once++#include <cstddef>+#include <optional>+#include <vector>++#include "openvino/core/node.hpp"+#include "openvino/core/partial_shape.hpp"+#include "openvino/core/type/element_type.hpp"+#include "openvino/op/op.hpp"++namespace ov::intel_gpu::op {++/// @brief GPU-internal Gated Residual (Hyper Connection) operation.+///+/// The op models the two halves of the gated-residual mechanism used by+/// Qwen4-Exp / Qwen3.8-Flash-Next style models, where the residual stream is widened+/// from [B,T,D] to [B,T,C,D] (physically stored as [B,T,C*D]).+///+/// READ (branch merge, executed *before* a sub-layer):+/// Rbar_c = rms_norm(R_c) * gain_c (branch-wise grouped RMSNorm, group width D)+/// G = sigmoid(W_up * SiLU(W_down * Rbar / C))+/// mixed = (1/C) * sum_c G_c (*) Rbar_c+/// S = 2 * sigmoid(W_inject * Rbar / C) (optional, only when produce_write_gate)+///+/// WRITE (branch update, executed *after* a sub-layer):+/// R'_c = R_c + S_c * Y+///+/// Notes on semantics that must not be "optimized away":+/// - the normalization is per-branch over D channels, *not* a single RMSNorm over C*D;+/// - all three 1/C factors are part of the model semantics;+/// - the read gate is per-(branch, channel), the write gate is a per-branch scalar in (0,2);+/// - the norm weight is the gain as is; a `1 + w` fold of the checkpoint is the producer's job.+class GatedResidual : public ov::op::Op {+public:+ OPENVINO_OP("GatedResidual", "gpu_opset");++ enum class Mode : int32_t {+ READ = 0, ///< branch merge, optionally also produces the write gate+ WRITE = 1, ///< branch update using a precomputed write gate+ };++ /// @brief Input indices for Mode::READ that do not depend on the input form+ struct ReadInputIdx {+ static constexpr size_t RESIDUAL = 0; ///< [B,T,C*D]+ static constexpr size_t NORM_WEIGHT = 1; ///< [C*D]+ static constexpr size_t W_DOWN = 2; ///< [L, C*D]+ static constexpr size_t W_UP = 3; ///< [C*D, L]++ // Compressed weights (W_DOWN / W_UP are i4, u4, i8 or u8). scale/zp are [N, G] as in the operation specification, or+ // [G, N] (N contiguous) when the op's `scale_gn` flag is set. The kernels read [G, N]: one sub-group block read gives+ // every lane the scale of its own output channel; ConvertGatedResidualScaleLayout converts the former into the latter.+ static constexpr size_t SCALE_DOWN = 4; ///< f16 [L, G_d] ([G_d, L] with scale_gn)+ static constexpr size_t SCALE_UP = 5; ///< f16 [C*D, G_u] ([G_u, C*D] with scale_gn)+ static constexpr size_t ZP_DOWN = 6; ///< same type as the weights (4-bit packed), shape of SCALE_DOWN, only with zero points+ static constexpr size_t ZP_UP = 7; ///< same type as the weights (4-bit packed), shape of SCALE_UP, only with zero points+ };++ /// @brief Input form of a READ node. The write-gate inputs are always the last inputs, so their indices depend on+ /// the form:+ /// floating-point weights: residual, norm, w_down, w_up [, w_inject]+ /// compressed, no zero points: residual, norm, w_down, w_up, scale_down, scale_up [, w_inject, scale_inject]+ /// compressed with zero points: ... scale_up, zp_down, zp_up [, w_inject, scale_inject, zp_inject]+ /// Zero points are all-or-nothing; without them they are 0.+ struct ReadLayout {+ bool compressed = false;+ bool has_zp = false;+ bool write_gate = false;+ size_t input_count = 4;+ size_t w_inject = 0; ///< valid when write_gate+ size_t scale_inject = 0; ///< valid when write_gate and compressed+ size_t zp_inject = 0; ///< valid when write_gate, compressed and has_zp+ };++ static constexpr ReadLayout make_read_layout(bool compressed, bool has_zp, bool write_gate) {+ ReadLayout l;+ l.compressed = compressed;+ l.has_zp = compressed && has_zp;+ l.write_gate = write_gate;+ size_t base = 4;+ if (compressed) {+ base = l.has_zp ? 8 : 6;+ }+ l.w_inject = base;+ l.scale_inject = base + 1;+ l.zp_inject = base + 2;+ size_t gate_inputs = 0;+ if (write_gate) {+ gate_inputs = 1;+ if (compressed) {+ gate_inputs = l.has_zp ? 3 : 2;+ }+ }+ l.input_count = base + gate_inputs;+ return l;+ }++ /// The form selected by the input count; empty when no form has that many inputs.+ static std::optional<ReadLayout> read_layout(size_t input_count, bool write_gate) {+ for (const bool compressed : {false, true}) {+ for (const bool has_zp : {false, true}) {+ const auto l = make_read_layout(compressed, has_zp, write_gate);+ if (l.has_zp == has_zp && l.input_count == input_count) {+ return l;+ }+ }+ }+ return std::nullopt;+ }++ std::optional<ReadLayout> get_read_layout() const {+ return read_layout(get_input_size(), m_produce_write_gate);+ }++ static bool is_compressed_weight_type(const ov::element::Type& t) {+ return t == ov::element::i4 || t == ov::element::u4 || t == ov::element::i8 || t == ov::element::u8;+ }++ /// Output shapes derived from the residual shape; shared by validate_and_infer_types() and the primitive's shape inference.+ static std::vector<ov::PartialShape> infer_output_shapes(Mode mode,+ size_t hc_count,+ size_t hidden_size,+ bool produce_write_gate,+ const ov::PartialShape& residual_ps);++ /// @brief Input indices for Mode::WRITE+ struct WriteInputIdx {+ static constexpr size_t RESIDUAL = 0; ///< [B,T,C*D]+ static constexpr size_t SUBLAYER_Y = 1; ///< [B,T,D]+ static constexpr size_t WRITE_GATE = 2; ///< [B,T,C]+ };++ GatedResidual() = default;++ GatedResidual(const ov::OutputVector& args,+ Mode mode,+ size_t hc_count,+ size_t hidden_size,+ size_t lowrank,+ float epsilon,+ bool produce_write_gate,+ bool scale_gn = false);++ bool visit_attributes(ov::AttributeVisitor& visitor) override;+ void validate_and_infer_types() override;+ std::shared_ptr<Node> clone_with_new_inputs(const ov::OutputVector& new_args) const override;++ Mode get_mode() const {+ return m_mode;+ }+ size_t get_hc_count() const {+ return m_hc_count;+ }+ size_t get_hidden_size() const {+ return m_hidden_size;+ }+ size_t get_lowrank() const {+ return m_lowrank;+ }+ float get_epsilon() const {+ return m_epsilon;+ }+ bool get_produce_write_gate() const {+ return m_produce_write_gate;+ }+ /// True when the compressed scales / zero points are laid out [G, N] (the kernel layout) instead of [N, G].+ bool get_scale_gn() const {+ return m_scale_gn;+ }++private:+ Mode m_mode = Mode::READ;+ size_t m_hc_count = 4;+ size_t m_hidden_size = 0;+ size_t m_lowrank = 0;+ float m_epsilon = 1e-6F;+ bool m_produce_write_gate = false;+ bool m_scale_gn = false;+};++} // namespace ov::intel_gpu::opdiff --git a/src/plugins/intel_gpu/include/intel_gpu/plugin/primitives_list.hpp b/src/plugins/intel_gpu/include/intel_gpu/plugin/primitives_list.hppindex e4b87b59c66..0676d2cb469 100644--- a/src/plugins/intel_gpu/include/intel_gpu/plugin/primitives_list.hpp+++ b/src/plugins/intel_gpu/include/intel_gpu/plugin/primitives_list.hpp@@ -337,6 +337,7 @@ REGISTER_FACTORY(internal, Swoosh);#ifdef ENABLE_MLIR_FOR_GPUREGISTER_FACTORY(internal, MLIR);#endif+REGISTER_FACTORY(internal, GatedResidual);REGISTER_FACTORY(internal, PagedQSAIndexer);REGISTER_FACTORY(internal, QSAIndexer);REGISTER_FACTORY(internal, SparsePA);diff --git a/src/plugins/intel_gpu/include/intel_gpu/primitives/gated_residual.hpp b/src/plugins/intel_gpu/include/intel_gpu/primitives/gated_residual.hppnew file mode 100644index 00000000000..6a4a8dd4178--- /dev/null+++ b/src/plugins/intel_gpu/include/intel_gpu/primitives/gated_residual.hpp@@ -0,0 +1,96 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#pragma once++#include <vector>++#include "intel_gpu/op/gated_residual.hpp"+#include "primitive.hpp"++namespace cldnn {++/// @brief gated_residual primitive.+/// @details Implements the READ/MIX and WRITE/COMBINE stages of the+/// gated residual (hyper connection) mechanism. See ov::intel_gpu::op::GatedResidual+/// for the exact semantics.+struct gated_residual : public primitive_base<gated_residual> {+ CLDNN_DECLARE_PRIMITIVE(gated_residual)++ using Mode = ov::intel_gpu::op::GatedResidual::Mode;++ gated_residual() : primitive_base("", {}) {}++ gated_residual(const primitive_id& id,+ const std::vector<input_info>& inputs,+ Mode mode,+ size_t hc_count,+ size_t hidden_size,+ size_t lowrank,+ float epsilon,+ bool produce_write_gate)+ // READ with produce_write_gate emits (mixed, S); output_data_types and+ // output_paddings must be sized accordingly or get_output_layout(1) is invalid.+ : primitive_base(id,+ inputs,+ produce_write_gate ? 2 : 1,+ std::vector<optional_data_type>(produce_write_gate ? 2 : 1, optional_data_type()),+ std::vector<padding>(produce_write_gate ? 2 : 1, padding())),+ mode(mode),+ hc_count(hc_count),+ hidden_size(hidden_size),+ lowrank(lowrank),+ epsilon(epsilon),+ produce_write_gate(produce_write_gate) {}++ Mode mode = Mode::READ;+ size_t hc_count = 4;+ size_t hidden_size = 0;+ size_t lowrank = 0;+ float epsilon = 1e-6F;+ bool produce_write_gate = false;++ size_t hash() const override {+ size_t seed = primitive::hash();+ seed = hash_combine(seed, static_cast<int>(mode));+ seed = hash_combine(seed, hc_count);+ seed = hash_combine(seed, hidden_size);+ seed = hash_combine(seed, lowrank);+ seed = hash_combine(seed, epsilon);+ seed = hash_combine(seed, produce_write_gate);+ return seed;+ }++ bool operator==(const primitive& rhs) const override {+ if (!compare_common_params(rhs)) {+ return false;+ }++ auto rhs_casted = downcast<const gated_residual>(rhs);+ return mode == rhs_casted.mode && hc_count == rhs_casted.hc_count && hidden_size == rhs_casted.hidden_size && lowrank == rhs_casted.lowrank &&+ epsilon == rhs_casted.epsilon && produce_write_gate == rhs_casted.produce_write_gate;+ }++ void save(BinaryOutputBuffer& ob) const override {+ primitive_base<gated_residual>::save(ob);+ ob << make_data(&mode, sizeof(Mode));+ ob << hc_count;+ ob << hidden_size;+ ob << lowrank;+ ob << epsilon;+ ob << produce_write_gate;+ }++ void load(BinaryInputBuffer& ib) override {+ primitive_base<gated_residual>::load(ib);+ ib >> make_data(&mode, sizeof(Mode));+ ib >> hc_count;+ ib >> hidden_size;+ ib >> lowrank;+ ib >> epsilon;+ ib >> produce_write_gate;+ }+};++} // namespace cldnndiff --git a/src/plugins/intel_gpu/include/intel_gpu/primitives/gated_residual_caps.hpp b/src/plugins/intel_gpu/include/intel_gpu/primitives/gated_residual_caps.hppnew file mode 100644index 00000000000..a58f379cc27--- /dev/null+++ b/src/plugins/intel_gpu/include/intel_gpu/primitives/gated_residual_caps.hpp@@ -0,0 +1,70 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#pragma once++#include <cstddef>++#include "intel_gpu/op/gated_residual.hpp"+#include "intel_gpu/runtime/device_info.hpp"++namespace ov::intel_gpu {+struct ExecutionConfig;+} // namespace ov::intel_gpu++/// What the GatedResidual OpenCL kernels can execute; shared by the fusion pass and the impl's validate_impl so that a fused+/// node always has an implementation.+namespace cldnn::gated_residual_caps {++using Mode = ov::intel_gpu::op::GatedResidual::Mode;++constexpr size_t supported_hc_count = 4;+constexpr size_t max_lowrank = 512; // the scalar gr_read.cl keeps t in registers+constexpr size_t max_total_width = 16384; // the scalar gr_read.cl keeps C*D f16 in SLM+constexpr size_t group_size_step = 32; // group sizes along K are multiples of one dpas K32 slice++/// Subgroup extensions every GatedResidual kernel needs.+inline bool is_device_supported(const device_info& info) {+ return info.supports_intel_subgroups && info.supports_intel_subgroups_short;+}++/// The READ runs the dpas kernels: Xe2+ with systolic arrays (supports_immad); GPU_GR_KERNEL_SELECTION=scalar (debug option) pretends not.+bool uses_dpas_kernels(const device_info& info, const ov::intel_gpu::ExecutionConfig& config);++/// A READ runs on the dpas kernels exactly when this holds; the scalar gr_read.cl takes the rest.+constexpr bool uses_dpas_read(size_t lowrank, bool systolic) {+ return systolic && lowrank != 0 && lowrank % 32 == 0;+}++constexpr bool is_geometry_supported(Mode mode, size_t hc_count, size_t hidden_size, size_t lowrank, bool systolic) {+ if (hc_count != supported_hc_count || hidden_size == 0 || hidden_size % 16 != 0) {+ return false;+ }+ if (mode == Mode::WRITE || uses_dpas_read(lowrank, systolic)) {+ return true;+ }+ return hc_count * hidden_size <= max_total_width && lowrank != 0 && lowrank % 16 == 0 && lowrank <= max_lowrank;+}++/// Group size along K (K / G) of a scale with G groups per output channel, or 0 when K is not divisible by G.+constexpr size_t derive_group_size(size_t k, size_t g) {+ return (g == 0 || k % g != 0) ? 0 : k / g;+}++/// A multiple of 32 that divides K (group size == K is per-channel).+constexpr bool is_group_size_supported(size_t k, size_t group_size) {+ return group_size != 0 && group_size % group_size_step == 0 && k % group_size == 0;+}++/// Compressed weight rows of K elements with G scale groups per row; `bits` is 4 (i4 / u4) or 8 (i8 / u8).+constexpr bool is_row_compression_supported(size_t bits, size_t k, size_t g) {+ return (bits == 4 || bits == 8) && k != 0 && k % 32 == 0 && is_group_size_supported(k, derive_group_size(k, g)) && (k * bits / 8) % 16 == 0;+}++/// Compressed W_down / W_up [N, K]. W_inject has only C (< 16) rows and is checked with is_row_compression_supported alone.+constexpr bool is_matrix_compression_supported(size_t bits, size_t n, size_t k, size_t g) {+ return n != 0 && n % 16 == 0 && is_row_compression_supported(bits, k, g);+}++} // namespace cldnn::gated_residual_capsdiff --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 a64b77a09b4..c275e66b42e 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@@ -241,6 +241,9 @@ static constexpr Property<std::vector<int>, ov::PropertyMutability::RW> micro_sdstatic constexpr Property<int, ov::PropertyMutability::RW> micro_sdpa_disable_prefetch{"GPU_MICRO_SDPA_DISABLE_PREFETCH"};static constexpr Property<std::string, ov::PropertyMutability::RW> pa_mixed_route_mode{"GPU_PA_MIXED_ROUTE_MODE"};static constexpr Property<bool, PropertyMutability::RW> record_replay_dynamic{"GPU_RECORD_REPLAY_DYNAMIC"};+static constexpr Property<int64_t, ov::PropertyMutability::RW> gr_pd_row_threshold{"GPU_GR_PD_ROW_THRESHOLD"};+static constexpr Property<size_t, ov::PropertyMutability::RW> gr_scratch_limit_mb{"GPU_GR_SCRATCH_LIMIT_MB"};+static constexpr Property<std::string, ov::PropertyMutability::RW> gr_kernel_selection{"GPU_GR_KERNEL_SELECTION"};static constexpr Property<std::vector<std::string>, ov::PropertyMutability::RW> force_fp32_layer_types{"GPU_FORCE_FP32_LAYER_TYPES"};static constexpr Property<std::vector<std::string>, ov::PropertyMutability::RW> force_fp32_layer_names{"GPU_FORCE_FP32_LAYER_NAMES"};} // namespace ov::intel_gpudiff --git a/src/plugins/intel_gpu/include/intel_gpu/runtime/options.inl b/src/plugins/intel_gpu/include/intel_gpu/runtime/options.inlindex 3bf47deff3e..04fb406b966 100644--- a/src/plugins/intel_gpu/include/intel_gpu/runtime/options.inl+++ b/src/plugins/intel_gpu/include/intel_gpu/runtime/options.inl@@ -140,6 +140,9 @@ OV_CONFIG_DEBUG_OPTION(ov::intel_gpu, print_input_data_shapes, false, "print inpOV_CONFIG_DEBUG_OPTION(ov::intel_gpu, pa_integrity_check, false, "Enable in-kernel SDPA micro-GEMM integrity checks (per-row K^T*Q and V*S reference comparisons)")OV_CONFIG_DEBUG_OPTION(ov::intel_gpu, micro_sdpa_workgroup_config, std::vector<int>{}, "Override SDPA micro-kernel workgroup config: 4 ints [wg_m_kq wg_n_kq wg_m_vs wg_n_vs]")OV_CONFIG_DEBUG_OPTION(ov::intel_gpu, micro_sdpa_disable_prefetch, 0, "Disable SDPA micro-kernel prefetches (Xe-HPC+). Bitmask: 1 - attn mask, 2 - K, 4 - V, 7 - all")+OV_CONFIG_DEBUG_OPTION(ov::intel_gpu, gr_pd_row_threshold, -1, "GatedResidual: a compressed READ dequantizes its weights into f16 scratch above this many rows; -1 keeps the default of 5 rows per EU")+OV_CONFIG_DEBUG_OPTION(ov::intel_gpu, gr_scratch_limit_mb, 256, "GatedResidual: Rbar scratch limit in MB of the compressed 3-dispatch READ; above it the single READ kernel runs")+OV_CONFIG_DEBUG_OPTION(ov::intel_gpu, gr_kernel_selection, std::string("auto"), "GatedResidual: READ kernels. auto: by device, weights and row count; ocl3: RBAR + DOWN_PROJ + UP_PROJ; single: one gr_read_dpas kernel; scalar: the scalar gr_read kernel, as on a device without systolic arrays")OV_CONFIG_DEBUG_OPTION(ov::intel_gpu, record_replay_dynamic, false, "Enable level-zero command list through record and replay for all (static and dynamic) models. Feature is work in progress and may produce incorrect results.")OV_CONFIG_DEBUG_OPTION(ov::intel_gpu, force_fp32_layer_types, std::vector<std::string>{}, "Space separated list of layer types to force FP32 precision; PASSTHROUGH_OPS selects data movement types (no automatic propagation)")OV_CONFIG_DEBUG_OPTION(ov::intel_gpu, force_fp32_layer_names, std::vector<std::string>{}, "Space separated list of layer name substrings to force FP32 precision (AND with layer_types if both set)")diff --git a/src/plugins/intel_gpu/sources.cmake b/src/plugins/intel_gpu/sources.cmakeindex abfd4880168..c9a265d51d7 100644--- a/src/plugins/intel_gpu/sources.cmake+++ b/src/plugins/intel_gpu/sources.cmake@@ -54,6 +54,7 @@ set(GPU_PLUGIN_OPS_SOURCES${CMAKE_CURRENT_LIST_DIR}/src/plugin/ops/fake_quantize.cpp${CMAKE_CURRENT_LIST_DIR}/src/plugin/ops/fully_connected.cpp${CMAKE_CURRENT_LIST_DIR}/src/plugin/ops/gated_delta_net.cpp+ ${CMAKE_CURRENT_LIST_DIR}/src/plugin/ops/gated_residual.cpp# NOTE: filename contains a literal space (pre-existing, not a typo introduced here)"${CMAKE_CURRENT_LIST_DIR}/src/plugin/ops/gather tree.cpp"${CMAKE_CURRENT_LIST_DIR}/src/plugin/ops/gather.cpp@@ -203,6 +204,8 @@ set(GPU_PLUGIN_TRANSFORMATIONS_SOURCES${CMAKE_CURRENT_LIST_DIR}/src/plugin/transformations/optimize_subsequent_reshapes.cpp${CMAKE_CURRENT_LIST_DIR}/src/plugin/transformations/preserve_single_selective_ssm_output.cpp${CMAKE_CURRENT_LIST_DIR}/src/plugin/transformations/print_model_statistics.cpp+ ${CMAKE_CURRENT_LIST_DIR}/src/plugin/transformations/convert_gated_residual_scale_layout.cpp+ ${CMAKE_CURRENT_LIST_DIR}/src/plugin/transformations/gated_residual_fusion.cpp${CMAKE_CURRENT_LIST_DIR}/src/plugin/transformations/reduce_fc_dimensions.cpp${CMAKE_CURRENT_LIST_DIR}/src/plugin/transformations/remove_fq_before_dw_conv.cpp${CMAKE_CURRENT_LIST_DIR}/src/plugin/transformations/scale_down_gated_mlp_input.cpp@@ -220,6 +223,7 @@ set(GPU_PLUGIN_TRANSFORMATIONS_OP_SOURCES${CMAKE_CURRENT_LIST_DIR}/src/plugin/transformations/op/convolution.cpp${CMAKE_CURRENT_LIST_DIR}/src/plugin/transformations/op/fully_connected.cpp${CMAKE_CURRENT_LIST_DIR}/src/plugin/transformations/op/fully_connected_compressed.cpp+ ${CMAKE_CURRENT_LIST_DIR}/src/plugin/transformations/op/gated_residual.cpp${CMAKE_CURRENT_LIST_DIR}/src/plugin/transformations/op/gemm.cpp${CMAKE_CURRENT_LIST_DIR}/src/plugin/transformations/op/grouped_depth_to_space.cpp${CMAKE_CURRENT_LIST_DIR}/src/plugin/transformations/op/grouped_space_to_depth.cppdiff --git a/src/plugins/intel_gpu/src/graph/gated_residual.cpp b/src/plugins/intel_gpu/src/graph/gated_residual.cppnew file mode 100644index 00000000000..de1c4d903db--- /dev/null+++ b/src/plugins/intel_gpu/src/graph/gated_residual.cpp@@ -0,0 +1,90 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include <limits>+#include <string>+#include <vector>++#include "gated_residual_inst.h"+#include "intel_gpu/primitives/gated_residual_caps.hpp"+#include "intel_gpu/runtime/debug_configuration.hpp"+#include "intel_gpu/runtime/execution_config.hpp"+#include "json_object.h"+#include "primitive_type_base.h"+#include "to_string_utils.h"++namespace cldnn {++bool gated_residual_caps::uses_dpas_kernels(const device_info& info, const ov::intel_gpu::ExecutionConfig& config) {+ const bool force_scalar = GPU_DEBUG_VALUE_OR(config.get_gr_kernel_selection(), std::string("auto")) == "scalar";+ return !force_scalar && is_device_supported(info) && info.arch >= gpu_arch::xe2 && info.supports_immad;+}++GPU_DEFINE_PRIMITIVE_TYPE_ID(gated_residual)++layout gated_residual_inst::calc_output_layout(const gated_residual_node& node, const kernel_impl_params& impl_param) {+ return calc_output_layouts<ov::PartialShape>(node, impl_param)[0];+}++template <typename ShapeType>+std::vector<layout> gated_residual_inst::calc_output_layouts(const gated_residual_node& /*node*/, const kernel_impl_params& impl_param) {+ const auto& desc = impl_param.typed_desc<gated_residual>();+ const auto residual_layout = impl_param.get_input_layout(0);+ const auto out_dt =+ desc->output_data_types.empty() || !desc->output_data_types[0].has_value() ? residual_layout.data_type : desc->output_data_types[0].value();++ OPENVINO_ASSERT(+ desc->hc_count > 0 && desc->hidden_size > 0 && desc->hc_count <= static_cast<size_t>(std::numeric_limits<int64_t>::max()) / desc->hidden_size,+ "[GPU] gated_residual: invalid or overflowing residual width");+ const auto width = static_cast<int64_t>(desc->hc_count * desc->hidden_size);+ const auto& residual_ps = residual_layout.get_partial_shape();+ OPENVINO_ASSERT(residual_ps.rank().is_static() && residual_ps.size() >= 2, "[GPU] gated_residual requires a static-rank residual input of rank >= 2");+ OPENVINO_ASSERT(residual_ps[residual_ps.size() - 1].compatible(width),+ "[GPU] gated_residual: the residual's width must equal hc_count * hidden_size = ",+ width,+ ", got ",+ residual_ps);++ const auto shapes = ov::intel_gpu::op::GatedResidual::infer_output_shapes(desc->mode,+ desc->hc_count,+ desc->hidden_size,+ desc->produce_write_gate,+ residual_layout.get_partial_shape());+ std::vector<layout> output_layouts;+ output_layouts.emplace_back(shapes[0], out_dt, residual_layout.format);+ if (shapes.size() > 1) {+ const auto gate_dt = desc->output_data_types.size() > 1 && desc->output_data_types[1].has_value() ? desc->output_data_types[1].value() : out_dt;+ output_layouts.emplace_back(shapes[1], gate_dt, residual_layout.format);+ }++ return output_layouts;+}++template std::vector<layout> gated_residual_inst::calc_output_layouts<ov::PartialShape>(const gated_residual_node& node, const kernel_impl_params& impl_param);++std::string gated_residual_inst::to_string(const gated_residual_node& node) {+ auto node_info = node.desc_to_json();+ auto desc = node.get_primitive();++ std::stringstream primitive_description;++ json_composite info;+ info.add("mode", static_cast<int>(desc->mode));+ info.add("hc_count", desc->hc_count);+ info.add("hidden_size", desc->hidden_size);+ info.add("lowrank", desc->lowrank);+ info.add("epsilon", desc->epsilon);+ info.add("produce_write_gate", desc->produce_write_gate);++ node_info->add("gated_residual_info", info);+ node_info->dump(primitive_description);++ return primitive_description.str();+}++gated_residual_inst::typed_primitive_inst(network& network, const gated_residual_node& node) : parent(network, node) {}++} // namespace cldnn++BIND_BINARY_BUFFER_WITH_TYPE(cldnn::gated_residual)diff --git a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/gated_residual/gated_residual.cpp b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/gated_residual/gated_residual.cppnew file mode 100644index 00000000000..891bf0f1c25--- /dev/null+++ b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/gated_residual/gated_residual.cpp@@ -0,0 +1,1394 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "gated_residual.hpp"++#include <algorithm>+#include <cstdio>+#include <limits>+#include <memory>+#include <mutex>+#include <optional>+#include <string>+#include <string_view>+#include <utility>+#include <vector>++#include "../primitive_ocl_base.hpp"+#include "../utils/kernel_generator.hpp"+#include "common_utils/jitter.hpp"+#include "intel_gpu/graph/kernel_impl_params.hpp"+#include "intel_gpu/graph/program.hpp"+#include "intel_gpu/primitives/gated_residual.hpp"+#include "intel_gpu/primitives/gated_residual_caps.hpp"+#include "intel_gpu/runtime/debug_configuration.hpp"+#include "registry/implementation_manager.hpp"++namespace ov::intel_gpu::ocl {++using namespace cldnn;+namespace caps = cldnn::gated_residual_caps;++namespace {++constexpr size_t gr_sg = 16; // subgroup size == one hardware thread on Xe2++constexpr size_t gr_wg_size = 16; // subgroups of the scalar / single-kernel work-groups+constexpr size_t gr_dpas_k_step = 32; // K consumed per dpas loop step (two K16 slices)+constexpr size_t gr_dpas_n = 16; // dpas N axis == GRF width on Xe2++constexpr size_t gr_down_tn = 32; // low-rank columns per down-projection subgroup+constexpr size_t gr_decode_rows = 32; // up to here both GEMMs use decode tiling+constexpr size_t gr_read_dpas_tm = 32;+constexpr size_t gr_read_dpas_nt = 2;++size_t get_num_rows(const layout& l, size_t last_dim) {+ const auto count = l.count();+ const auto& ps = l.get_partial_shape();+ OPENVINO_ASSERT(ps.rank().is_static() && ps.size() >= 2 && last_dim <= static_cast<size_t>(std::numeric_limits<int64_t>::max()) &&+ ps[ps.size() - 1].is_static() && ps[ps.size() - 1] == ov::Dimension(static_cast<int64_t>(last_dim)),+ "[GPU][OCL] gated_residual: residual width must equal ",+ last_dim,+ ", got ",+ ps);+ OPENVINO_ASSERT(last_dim > 0 && count % last_dim == 0, "[GPU][OCL] gated_residual: input element count is not divisible by the last dimension");+ return count / last_dim;+}++/// Widest elements-per-subgroup tile (a multiple of 16) that evenly divides `width`.+size_t gr_best_tile(size_t width) {+ for (size_t t : {size_t{128}, size_t{64}, size_t{32}, size_t{16}}) {+ if (width % t == 0) {+ return t;+ }+ }+ return 16;+}++/// Chunk (halves) of a K loop over `width` elements, at most 64 (one 128 B block message per lane group).+size_t gr_k_chunk(size_t width) {+ if (width % 64 == 0) {+ return 64;+ }+ return (width % 32 == 0) ? 32 : 16;+}++/// gr_read work-group size in subgroups: Xe2+ runs 32 in 256-GRF mode, which halves the per-row latency of the two GEMVs.+size_t gr_read_wg_size(const cldnn::device_info& info) {+ return info.arch >= gpu_arch::xe2 ? 32 : gr_wg_size;+}++/// Token rows per gr_read work-group: every weight chunk is reused for all of them, so as many as the SLM budget (Rbar f16+/// + t f32 per row) allows. Decode keeps one row per work-group.+size_t gr_read_rows(const gated_residual& desc, const cldnn::device_info& info, bool decode) {+ if (decode) {+ return 1;+ }+ const size_t per_row = (desc.hc_count * desc.hidden_size * 2) + ((desc.lowrank + desc.hc_count + 3) / 4 * 4 * 4);+ const size_t budget = std::min<size_t>(info.max_local_mem_size, 96 * 1024);+ for (size_t rb : {size_t{8}, size_t{4}, size_t{2}}) {+ if (rb * per_row <= budget) {+ return rb;+ }+ }+ return 1;+}++size_t gr_div_up(size_t a, size_t b) {+ return (a + b - 1) / b;+}++size_t largest_divisor_up_to(size_t n, size_t cap) {+ for (size_t d = std::min(n, cap); d > 1; d--) {+ if (n % d == 0) {+ return d;+ }+ }+ return 1;+}++/// Weight storage of the READ kernels (GR_W_TYPE): f16, or the compressed forms with f16 scales and optional zero+/// points. u4 stands for the 4-bit types (i4 / u4), u8 for the 8-bit ones (i8 / u8); signedness is gr_weight_signed().+enum class GrWType : int { f16 = 0, u4 = 1, u8 = 2 };++using GrOp = ov::intel_gpu::op::GatedResidual;++/// Row-count regimes of the two dpas GEMM stages: few rows need the K reduction split over a work-group so the weights are+/// streamed by enough threads; the split stops paying off once the token tiles alone fill the GPU. `gemv` is the decode tier+/// of the compressed DOWN_PROJ for up to gr_gemv_rows rows (one 8-token dpas tile); every other kernel treats it as decode.+enum class GrTier { gemv, decode, mid, wide };++constexpr size_t gr_gemv_rows = 8;++bool gr_decode_like(GrTier tier) {+ return tier == GrTier::gemv || tier == GrTier::decode;+}++/// Rows up to which the token tiles alone do not fill the GPU (~4 per EU): the GEMMs split K over a work-group and the f16 READ runs+/// the pipeline rather than the single kernel.+size_t gr_mid_max_rows(const cldnn::device_info& info) {+ return 4 * static_cast<size_t>(info.execution_units_count);+}++GrTier gr_down_tier(size_t num_rows, const cldnn::device_info& info) {+ if (num_rows <= gr_decode_rows) {+ return num_rows <= gr_gemv_rows ? GrTier::gemv : GrTier::decode;+ }+ return num_rows <= gr_mid_max_rows(info) ? GrTier::mid : GrTier::wide;+}++GrTier gr_up_tier(size_t num_rows) {+ return num_rows <= gr_decode_rows ? GrTier::decode : GrTier::wide;+}++struct GrGemmTiling {+ size_t tm; // tokens per subgroup+ size_t ksplit; // subgroups of a work-group splitting the K reduction+ size_t lws_y; // token tiles per work-group (ksplit == 1 only)+ size_t wq_bytes = 32; // compressed per-subgroup kernels: per-lane weight bytes per load (see gr_wq_kch)+};++GrGemmTiling gr_down_tiling(const gated_residual& desc, const cldnn::device_info& info, GrTier tier, GrWType wtype = GrWType::f16) {+ const size_t cd_steps = desc.hc_count * desc.hidden_size / gr_dpas_k_step;+ const bool compressed = wtype != GrWType::f16;+ // Dequantizing makes every K step longer, so compressed weights want more subgroups splitting K.+ const size_t boost = compressed ? 2 : 1;+ switch (tier) {+ case GrTier::gemv:+ case GrTier::decode: {+ // the compressed gemv tier uses one 8-token tile per subgroup, which halves the unpack / dpas work+ const size_t tm = compressed && tier == GrTier::gemv ? size_t{8} : size_t{16};+ const size_t ksplit = largest_divisor_up_to(cd_steps, 8 * boost);+ if (tier == GrTier::gemv && wtype == GrWType::u4) {+ // Wide 4-bit DOWN_PROJs whose split fills more than 3/4 of the resident subgroups (4 per EU with 256 GRF) stream+ // faster as fewer, longer K segments read 64 B per lane, filling at most 2/3 of them in one wave.+ const size_t wgs = (desc.lowrank / gr_dpas_n) + (desc.produce_write_gate ? 1 : 0);+ const size_t resident = 4 * static_cast<size_t>(info.execution_units_count);+ if (4 * wgs * ksplit > 3 * resident) {+ return {tm, largest_divisor_up_to(cd_steps, std::max<size_t>(1, 2 * resident / (3 * wgs))), 1, 64};+ }+ }+ return {tm, ksplit, 1};+ }+ case GrTier::mid:+ return {32, largest_divisor_up_to(cd_steps, (info.execution_units_count >= 128 ? 4 : 2) * boost), 1};+ default:+ return {32, 1, 1};+ }+}++GrGemmTiling gr_up_tiling(const gated_residual& desc, const cldnn::device_info& info, GrTier tier, GrWType wtype) {+ if (!gr_decode_like(tier)) {+ return {16, 1, 8};+ }+ // Narrow D leaves few column tiles; split L until there are ~2 subgroups per EU. Compressed weights move fewer bytes per+ // K step and split further: u4 down to two K32 steps per subgroup, u8 down to one.+ const bool compressed = wtype != GrWType::f16;+ const size_t col_tiles = desc.hidden_size / gr_dpas_n;+ const size_t eu = info.execution_units_count;+ const size_t steps = desc.lowrank / gr_dpas_k_step;+ size_t cap = 2 * eu / col_tiles;+ if (wtype == GrWType::u8) {+ cap = steps;+ } else if (compressed) {+ cap = std::min(gr_div_up(8 * eu, col_tiles), steps / 2);+ }+ // f16 reads every W_up byte once per token tile, so a 16-token tile halves that traffic; the compressed kernels unpack the+ // weights again per tile and keep 8.+ return {compressed ? size_t{8} : size_t{16}, largest_divisor_up_to(steps, std::max<size_t>(1, cap)), 1};+}++/// Kernel name suffix of a pipeline GEMM stage, e.g. "down_q_mid" or "up_pd_decode".+std::string gr_tier_suffix(GrTier tier, bool down, bool q, bool pd) {+ static constexpr const char* tiers[] = {"_gemv", "_decode", "_mid", ""};+ std::string variant;+ if (pd) {+ variant = "_pd";+ } else if (q) {+ variant = "_q";+ }+ return std::string(down ? "down" : "up") + variant + tiers[static_cast<size_t>(tier)];+}++/// Whether the READ runs on the systolic kernels instead of the fused scalar gr_read kernel.+bool can_use_dpas_gr_read(const RuntimeParams& params) {+ return caps::uses_dpas_read(params.typed_desc<gated_residual>()->lowrank,+ caps::uses_dpas_kernels(params.get_device_info(), params.get_program().get_config()));+}++GrWType gr_weight_type(const RuntimeParams& params) {+ const auto dt = params.get_input_layout(2).data_type;+ if (dt == ov::element::u4 || dt == ov::element::i4) {+ return GrWType::u4;+ }+ return dt == ov::element::u8 || dt == ov::element::i8 ? GrWType::u8 : GrWType::f16;+}++bool gr_weight_signed(const RuntimeParams& params) {+ const auto dt = params.get_input_layout(2).data_type;+ return dt == ov::element::i4 || dt == ov::element::i8;+}++/// Input form of a READ node (the op validated that its input count is one of the forms).+GrOp::ReadLayout gr_read_layout(const RuntimeParams& params) {+ const auto layout = GrOp::read_layout(params.get_input_layout_size(), params.typed_desc<gated_residual>()->produce_write_gate);+ OPENVINO_ASSERT(layout.has_value(), "[GPU][OCL] gated_residual: unexpected number of inputs ", params.get_input_layout_size());+ return *layout;+}++ArgumentDescriptor gr_input(size_t idx) {+ return {ArgumentDescriptor::Types::INPUT, static_cast<uint32_t>(idx)};+}++ArgumentDescriptor gr_output(size_t idx) {+ return {ArgumentDescriptor::Types::OUTPUT, static_cast<uint32_t>(idx)};+}++ArgumentDescriptor gr_scratch(size_t idx) {+ return {ArgumentDescriptor::Types::INTERNAL_BUFFER, static_cast<uint32_t>(idx)};+}++ArgumentDescriptor gr_num_rows_arg() {+ return {ArgumentDescriptor::Types::SCALAR, 0};+}++/// The kernels always take a zp argument; without zero points the scale buffer is bound instead and never read (GR_HAS_ZP == 0).+ArgumentDescriptor gr_zp_arg(const GrOp::ReadLayout& layout, size_t zp_idx, size_t scale_idx) {+ return gr_input(layout.has_zp ? zp_idx : scale_idx);+}++size_t gr_weight_bits(GrWType t) {+ return t == GrWType::u4 ? 4 : 8;+}++/// K values one lane loads per step from its weight row (K32 slices are dequantized one by one out of the raw registers).+/// Wider loads fill whole cache lines (u4 reads only 16 B per K32 otherwise) but cost registers, so `max_bytes` is chosen per+/// kernel; the width must divide the K range a subgroup walks and keep every load inside one aligned block of the row.+size_t gr_wq_kch(GrWType t, size_t segment, size_t row_k, size_t max_bytes) {+ const size_t bits = gr_weight_bits(t);+ for (size_t bytes : {size_t{64}, size_t{32}, size_t{16}}) {+ const size_t kch = bytes * 8 / bits;+ if (bytes <= max_bytes && kch >= 32 && segment % kch == 0 && row_k % kch == 0) {+ return kch;+ }+ }+ return 32;+}++constexpr size_t gr_wq_up_load_bytes = 64; // UP: a lane loads up to one cache line of its row per step+constexpr size_t gr_wq_dpas_load_bytes = 32; // gr_read_dpas is register bound++/// Compressed READ above the decode regime: `st` token subgroups (and `ks` K subgroups) of one work-group dequantize+/// every weight slice once into SLM and all of them run their dpas on it, instead of each token subgroup dequantizing the+/// weights again. The decode tier keeps the per-subgroup dequantization (one or two token tiles, nothing to share).+struct GrQShare {+ size_t st; // token subgroups per work-group+ size_t ks; // K subgroups per work-group+};++GrQShare gr_down_q_share(const gated_residual& desc, GrTier tier) {+ const size_t cd_steps = desc.hc_count * desc.hidden_size / gr_dpas_k_step;+ return tier == GrTier::mid ? GrQShare{4, largest_divisor_up_to(cd_steps, 4)} : GrQShare{8, 1};+}++constexpr size_t gr_up_q_st = 4;++/// Group size along K (K / G) of the weight whose f16 scale is input `scale_idx`.+size_t gr_group_size(const RuntimeParams& params, size_t scale_idx, size_t k) {+ const auto& ps = params.get_input_layout(scale_idx).get_partial_shape();+ OPENVINO_ASSERT(ps.rank().is_static() && ps.size() == 2 && ps[0].is_static(), "[GPU][OCL] gated_residual: the scale must be a static [G, N] tensor");+ return caps::derive_group_size(k, static_cast<size_t>(ps[0].get_length()));+}++/// GR_<prefix>_KCH / _NRAW / _RB / _GS32 (group size in K32 slices) / _PERCH (one group) of one weight matrix [N, K].+void add_wq_matrix_constants(JitConstants& jit, const std::string& prefix, GrWType t, size_t kch, size_t row_k, size_t group_size) {+ jit.make(prefix + "_KCH", kch);+ jit.make(prefix + "_NRAW", kch * gr_weight_bits(t) / 32);+ jit.make(prefix + "_RB", row_k * gr_weight_bits(t) / 8);+ jit.make(prefix + "_GS32", group_size / gr_dpas_k_step);+ jit.make(prefix + "_PERCH", group_size == row_k ? 1 : 0);+}++/// Weight format of a compressed kernel: bit width class, signedness and whether there are zero points.+void add_wq_format_constants(JitConstants& jit, const RuntimeParams& params) {+ jit.make("GR_W_TYPE", static_cast<int>(gr_weight_type(params)));+ jit.make("GR_W_SIGNED", gr_weight_signed(params) ? 1 : 0);+ jit.make("GR_HAS_ZP", gr_read_layout(params).has_zp ? 1 : 0);+}++/// Float as an OpenCL C literal with full single precision (an unsuffixed literal would be a double). Always in exponent+/// notation: "%g" prints integral values without a decimal point ("1f"), which is not a floating constant.+JitConstant float_constant(const std::string& name, float value) {+ char buf[64];+ std::snprintf(buf, sizeof(buf), "%.9ef", static_cast<double>(value));+ return JitConstant(name, buf);+}++void push_num_rows(KernelData& kd, size_t num_rows) {+ kd.params.scalars.clear();+ scalar_desc s;+ s.t = scalar_desc::Types::UINT32;+ s.v.u32 = static_cast<uint32_t>(num_rows);+ kd.params.scalars.push_back(s);+}++size_t rows_of(const RuntimeParams& params, const gated_residual& desc) {+ return get_num_rows(params.get_input_layout(0), desc.hc_count * desc.hidden_size);+}++// ---------------------------------------------------------------------------+// Kernel selection+// ---------------------------------------------------------------------------++/// READ kernels (the GPU_GR_KERNEL_SELECTION debug option). `auto`: the row count picks between the 3-dispatch pipeline and+/// the single kernel. `ocl3` / `single` force one of them. `scalar`: the scalar gr_read kernel (caps::uses_dpas_kernels is false).+enum class GrPath { automatic, ocl3, single, scalar };++GrPath gr_kernel_selection(const RuntimeParams& params) {+ static constexpr std::pair<std::string_view, GrPath> paths[] = {+ {"auto", GrPath::automatic},+ {"ocl3", GrPath::ocl3},+ {"single", GrPath::single},+ {"scalar", GrPath::scalar},+ };+ const auto name = GPU_DEBUG_VALUE_OR(params.get_program().get_config().get_gr_kernel_selection(), std::string("auto"));+ for (const auto& [key, path] : paths) {+ if (name == key) {+ return path;+ }+ }+ OPENVINO_ASSERT(name.empty(), "[GPU][OCL] gated_residual: unknown GPU_GR_KERNEL_SELECTION '", name, "'");+ return GrPath::automatic;+}++/// A compressed READ above this many rows dequantizes both matrices into f16 scratch first and runs the f16 kernels: below+/// ~4 rows per EU the dequantizing GEMM kernels win, above ~5 rows per EU the f16 single kernel (no Rbar / T scratch traffic,+/// weights hot in cache) does. The GPU_GR_PD_ROW_THRESHOLD debug option overrides it.+size_t gr_pd_min_rows(const RuntimeParams& params) {+ const int64_t rows = GPU_DEBUG_VALUE_OR(params.get_program().get_config().get_gr_pd_row_threshold(), int64_t{-1});+ return rows >= 0 ? static_cast<size_t>(rows) : 5 * static_cast<size_t>(params.get_device_info().execution_units_count);+}++/// Rows whose Rbar scratch (rows * C*D * 2 bytes) of the compressed 3-dispatch pipeline fits the GPU_GR_SCRATCH_LIMIT_MB limit;+/// above them the compressed single kernel (Rbar in SLM, dequantizing per token tile) runs instead.+size_t gr_q_scratch_max_rows(const RuntimeParams& params) {+ const auto desc = params.typed_desc<gated_residual>();+ const size_t limit = GPU_DEBUG_VALUE_OR(params.get_program().get_config().get_gr_scratch_limit_mb(), size_t{256}) << 20;+ return limit / (desc->hc_count * desc->hidden_size * 2);+}++/// Above the mid tier the single systolic kernel gr_read_dpas beats the 3-dispatch pipeline and needs no scratch; below it the+/// pipeline's split-K tiers parallelize better.+bool gr_single_f16(const RuntimeParams& params, GrPath path, size_t rows) {+ return params.typed_desc<gated_residual>()->hidden_size % 32 == 0 &&+ (path == GrPath::single || (path == GrPath::automatic && rows > gr_mid_max_rows(params.get_device_info())));+}++bool gr_single_q(const RuntimeParams& params, GrPath path, size_t rows) {+ return params.typed_desc<gated_residual>()->hidden_size % 32 == 0 &&+ (path == GrPath::single || (path == GrPath::automatic && rows > gr_q_scratch_max_rows(params)));+}++/// The dispatches of one READ on the dpas path for `rows` token rows.+struct ReadPlan {+ bool q = false; // compressed weights+ GrTier tier = GrTier::wide; // DOWN_PROJ tier of the 3-dispatch pipeline+ bool pd = false; // both matrices dequantized into f16 scratch first+ bool single = false; // one gr_read_dpas dispatch+ bool gate_dispatch = false; // separate write-gate dispatch (compressed weights, shared DOWN_PROJ)+ bool dq_inject = false; // compressed W_inject dequantized into f16 scratch+};++ReadPlan read_plan(const RuntimeParams& params, size_t rows) {+ const auto desc = params.typed_desc<gated_residual>();+ const auto path = gr_kernel_selection(params);+ ReadPlan p;+ p.q = gr_weight_type(params) != GrWType::f16;+ p.tier = gr_down_tier(rows, params.get_device_info());+ const bool gate_q = p.q && desc->produce_write_gate;+ // The compressed single kernel has no write-gate tile: with a write gate that regime predequantizes as well.+ const bool single_q = p.q && gr_single_q(params, path, rows);+ p.pd = p.q && (rows > gr_pd_min_rows(params) || (gate_q && single_q));+ p.single = p.q && !p.pd ? single_q : gr_single_f16(params, path, rows);+ p.gate_dispatch = gate_q && !p.pd && !p.single && !gr_decode_like(p.tier);+ p.dq_inject = gate_q && (p.pd || p.gate_dispatch);+ return p;+}++/// 4-bit decode GEMMs unpack their weights in a permuted K order and read Rbar / T stored with the same permutation (GR_KP). The+/// decode RBAR cannot know the row count of a dynamic shape, so this holds only when no decode row count takes the predequantized,+/// or single-kernel path; each of them holds for the largest decode row count if it holds for any.+bool gr_decode_kperm(const RuntimeParams& params) {+ // the decode RBAR permutes in registers: 128-half chunks, 8 halves per lane+ if (gr_weight_type(params) != GrWType::u4 || gr_best_tile(params.typed_desc<gated_residual>()->hidden_size) != 128) {+ return false;+ }+ const auto p = read_plan(params, gr_decode_rows);+ return !p.pd && !p.single;+}++/// Row counts on both sides of every threshold of read_plan() and of the stage variants. The stages are a step function of the+/// row count, so these yield every stage some row count runs (what a dynamic shape has to build).+std::vector<size_t> gr_routing_rows(const RuntimeParams& params) {+ const size_t thresholds[] = {+ gr_gemv_rows,+ gr_decode_rows,+ gr_mid_max_rows(params.get_device_info()),+ gr_pd_min_rows(params),+ gr_q_scratch_max_rows(params),+ };+ std::vector<size_t> rows = {1};+ for (const size_t t : thresholds) {+ rows.push_back(std::max<size_t>(1, t));+ rows.push_back(t + 1);+ }+ std::sort(rows.begin(), rows.end());+ rows.erase(std::unique(rows.begin(), rows.end()), rows.end());+ return rows;+}++/// Common base of the stages: the kernels take their geometry from JIT constants and `num_rows`, never from shape_info or the+/// INPUT0_* layout macros, so only the base JIT constants are used.+class GrGenerator : public KernelGenerator {+public:+ GrGenerator(std::string_view template_name, std::string_view suffix, bool large_grf = true)+ : KernelGenerator(template_name, suffix),+ m_large_grf(large_grf) {}++protected:+ [[nodiscard]] std::string get_build_options(const RuntimeParams& params) const override {+ auto options = KernelGenerator::get_build_options(params);+ if (m_large_grf && params.get_device_info().arch >= gpu_arch::xe_hpg) {+ options += " -cl-intel-256-GRF-per-thread";+ }+ return options;+ }++ [[nodiscard]] JitConstants get_jit_constants(const RuntimeParams& params) const override {+ auto jit = make_base_jit_constants(params);+ const auto desc = params.typed_desc<gated_residual>();+ jit.make("SUBGROUP_SIZE", gr_sg);+ jit.make("GR_BRANCHES", desc->hc_count);+ jit.make("GR_HIDDEN", desc->hidden_size);+ return jit;+ }++ static void add_norm_constants(JitConstants& jit, const gated_residual& desc) {+ jit.add(float_constant("GR_EPS", desc.epsilon));+ }++ /// Arguments of the single-dispatch READ kernels: residual, norm weight, W_down, W_up [, their scales and zero points]+ /// [, W_inject [, its scale and zero point]], mixed [, write gate], num_rows. `pd`: the f16 scratch copies of the compressed+ /// weights are read; `gate`: the kernel computes the write gate.+ [[nodiscard]] static Arguments read_arguments(const GrOp::ReadLayout& layout, GrWType wtype, bool pd, bool gate) {+ using Idx = GrOp::ReadInputIdx;+ Arguments args = {gr_input(Idx::RESIDUAL), gr_input(Idx::NORM_WEIGHT)};+ if (pd) {+ args.push_back(gr_scratch(GatedResidualInternalBufIdx::WD_F16));+ args.push_back(gr_scratch(GatedResidualInternalBufIdx::WU_F16));+ } else {+ args.push_back(gr_input(Idx::W_DOWN));+ args.push_back(gr_input(Idx::W_UP));+ }+ if (wtype != GrWType::f16) {+ args.push_back(gr_input(Idx::SCALE_DOWN));+ args.push_back(gr_input(Idx::SCALE_UP));+ args.push_back(gr_zp_arg(layout, Idx::ZP_DOWN, Idx::SCALE_DOWN));+ args.push_back(gr_zp_arg(layout, Idx::ZP_UP, Idx::SCALE_UP));+ }+ if (gate) {+ if (pd) {+ args.push_back(gr_scratch(GatedResidualInternalBufIdx::WI_F16));+ } else {+ args.push_back(gr_input(layout.w_inject));+ if (wtype != GrWType::f16) {+ args.push_back(gr_input(layout.scale_inject));+ args.push_back(gr_zp_arg(layout, layout.zp_inject, layout.scale_inject));+ }+ }+ }+ args.push_back(gr_output(0)); // mixed+ if (gate) {+ args.push_back(gr_output(1)); // write gate S+ }+ args.push_back(gr_num_rows_arg());+ return args;+ }++private:+ bool m_large_grf;+};++// ---------------------------------------------------------------------------+// READ / MIX, fused scalar kernel+// ---------------------------------------------------------------------------+class GrReadGenerator : public GrGenerator {+public:+ explicit GrReadGenerator(bool decode = false) : GrGenerator("gr_read", decode ? "decode" : "wide"), m_decode(decode) {}++protected:+ [[nodiscard]] JitConstants get_jit_constants(const RuntimeParams& params) const override {+ auto jit = GrGenerator::get_jit_constants(params);+ const auto desc = params.typed_desc<gated_residual>();+ add_norm_constants(jit, *desc);+ jit.make("GR_LOWRANK", desc->lowrank);+ jit.make("GR_PRODUCE_WRITE_GATE", desc->produce_write_gate ? 1 : 0);+ jit.make("GR_WG_SIZE", gr_read_wg_size(params.get_device_info()));+ jit.make("GR_READ_ROWS", gr_read_rows(*desc, params.get_device_info(), m_decode));+ jit.make("GR_NV_D", gr_k_chunk(desc->hidden_size) / 16);+ jit.make("GR_NV_C", gr_k_chunk(desc->hc_count * desc->hidden_size) / 16);+ jit.make("GR_NV_L", gr_k_chunk(desc->lowrank) / 16);+ if (gr_weight_type(params) != GrWType::f16) {+ const size_t cd = desc->hc_count * desc->hidden_size;+ add_wq_format_constants(jit, params);+ jit.make("GR_RD_GSD", gr_group_size(params, GrOp::ReadInputIdx::SCALE_DOWN, cd));+ jit.make("GR_RD_GSU", gr_group_size(params, GrOp::ReadInputIdx::SCALE_UP, desc->lowrank));+ if (desc->produce_write_gate) {+ jit.make("GR_RD_GSI", gr_group_size(params, gr_read_layout(params).scale_inject, cd));+ }+ }+ return jit;+ }++ [[nodiscard]] Arguments get_arguments_desc(const RuntimeParams& params) const override {+ return read_arguments(gr_read_layout(params), gr_weight_type(params), false, params.typed_desc<gated_residual>()->produce_write_gate);+ }++ [[nodiscard]] DispatchDataFunc get_dispatch_data_func() const override {+ return DispatchDataFunc{[decode = m_decode](const RuntimeParams& params, KernelData& kd, ImplRuntimeParams*) {+ if (params.is_dynamic()) {+ return;+ }+ const auto desc = params.typed_desc<gated_residual>();+ const size_t num_rows = rows_of(params, *desc);+ const size_t wg = gr_read_wg_size(params.get_device_info());+ const size_t rows_per_wg = gr_read_rows(*desc, params.get_device_info(), decode);++ auto& wgs = kd.params.workGroups;+ wgs.global = {wg * gr_sg, std::max<size_t>(1, gr_div_up(num_rows, rows_per_wg)), 1};+ wgs.local = {wg * gr_sg, 1, 1};+ push_num_rows(kd, num_rows);+ }};+ }++private:+ bool m_decode;+};++// ---------------------------------------------------------------------------+// READ / MIX, single systolic kernel (many rows)+// ---------------------------------------------------------------------------+class GrReadDpasGenerator : public GrGenerator {+public:+ static const char* variant_name(bool q, bool pd) {+ if (q) {+ return "q";+ }+ return pd ? "pd" : "";+ }++ explicit GrReadDpasGenerator(bool q = false, bool pd = false) : GrGenerator("gr_read_dpas", variant_name(q, pd)), m_q(q), m_pd(pd) {}++protected:+ [[nodiscard]] JitConstants get_jit_constants(const RuntimeParams& params) const override {+ auto jit = GrGenerator::get_jit_constants(params);+ const auto desc = params.typed_desc<gated_residual>();+ add_norm_constants(jit, *desc);+ jit.make("GR_LOWRANK", desc->lowrank);+ jit.make("GR_PRODUCE_WRITE_GATE", gate(params) ? 1 : 0);+ jit.make("GR_WG_SIZE", gr_wg_size);+ jit.make("GR_RD_TM", gr_read_dpas_tm);+ jit.make("GR_RD_NT", gr_read_dpas_nt);+ jit.make("GR_NV_KD", (desc->hidden_size % 128 == 0 ? 128 : 32) / 16);+ const size_t cd = desc->hc_count * desc->hidden_size;+ const size_t slm_bytes = (desc->hc_count * gr_read_dpas_tm * 4) + (gr_read_dpas_tm * desc->lowrank * 2);+ // Larger SLM footprints shrink L1, which phase 2 relies on to share the residual tile between subgroups.+ const size_t slm_limit = std::min<size_t>(params.get_device_info().max_local_mem_size, 64 * 1024);+ int slm_gain = 0;+ if (slm_bytes + (cd * 4) <= slm_limit) {+ slm_gain = 2;+ } else if (slm_bytes + ((cd + 48) * 2) <= slm_limit) {+ slm_gain = 1;+ }+ jit.make("GR_RD_SLM_GAIN", slm_gain);+ if (m_q) {+ const auto wtype = gr_weight_type(params);+ add_wq_format_constants(jit, params);+ add_wq_matrix_constants(jit,+ "GR_WD",+ wtype,+ gr_wq_kch(wtype, desc->hidden_size, cd, gr_wq_dpas_load_bytes),+ cd,+ gr_group_size(params, GrOp::ReadInputIdx::SCALE_DOWN, cd));+ add_wq_matrix_constants(jit,+ "GR_WU",+ wtype,+ gr_wq_kch(wtype, desc->lowrank, desc->lowrank, gr_wq_dpas_load_bytes),+ desc->lowrank,+ gr_group_size(params, GrOp::ReadInputIdx::SCALE_UP, desc->lowrank));+ }+ return jit;+ }++ [[nodiscard]] Arguments get_arguments_desc(const RuntimeParams& params) const override {+ return read_arguments(gr_read_layout(params), m_q ? gr_weight_type(params) : GrWType::f16, m_pd, gate(params));+ }++ [[nodiscard]] DispatchDataFunc get_dispatch_data_func() const override {+ return DispatchDataFunc{[](const RuntimeParams& params, KernelData& kd, ImplRuntimeParams*) {+ if (params.is_dynamic()) {+ return;+ }+ const auto desc = params.typed_desc<gated_residual>();+ const size_t num_rows = rows_of(params, *desc);+ auto& wgs = kd.params.workGroups;+ wgs.global = {gr_wg_size * gr_sg, std::max<size_t>(1, gr_div_up(num_rows, gr_read_dpas_tm)), 1};+ wgs.local = {gr_wg_size * gr_sg, 1, 1};+ push_num_rows(kd, num_rows);+ }};+ }++private:+ /// The kernel has the write-gate column tile for f16 weights only: a compressed READ computes the gate in the pipeline or,+ /// predequantized (`pd`), in this kernel on the dequantized W_inject.+ [[nodiscard]] bool gate(const RuntimeParams& params) const {+ return params.typed_desc<gated_residual>()->produce_write_gate && !m_q;+ }++ bool m_q;+ bool m_pd;+};++// ---------------------------------------------------------------------------+// WRITE / COMBINE+// ---------------------------------------------------------------------------+class GrWriteGenerator : public GrGenerator {+public:+ GrWriteGenerator() : GrGenerator("gr_write", "", /*large_grf=*/false) {}++protected:+ [[nodiscard]] JitConstants get_jit_constants(const RuntimeParams& params) const override {+ auto jit = GrGenerator::get_jit_constants(params);+ const auto desc = params.typed_desc<gated_residual>();+ const size_t tile = gr_best_tile(desc->hidden_size);+ jit.make("GR_WRITE_TILE", tile);+ jit.make("GR_WRITE_NV", tile / 16);+ return jit;+ }++ [[nodiscard]] Arguments get_arguments_desc(const RuntimeParams& /*params*/) const override {+ using Idx = GrOp::WriteInputIdx;+ return {gr_input(Idx::RESIDUAL), gr_input(Idx::SUBLAYER_Y), gr_input(Idx::WRITE_GATE), gr_output(0), gr_num_rows_arg()};+ }++ [[nodiscard]] DispatchDataFunc get_dispatch_data_func() const override {+ return DispatchDataFunc{[](const RuntimeParams& params, KernelData& kd, ImplRuntimeParams*) {+ if (params.is_dynamic()) {+ return;+ }+ const auto desc = params.typed_desc<gated_residual>();+ const size_t num_rows = rows_of(params, *desc);+ // Dynamic dims cannot be proven equal at compile time; the kernel indexes Y and the gate by the residual's row.+ OPENVINO_ASSERT(params.get_input_layout(GrOp::WriteInputIdx::SUBLAYER_Y).count() == num_rows * desc->hidden_size &&+ params.get_input_layout(GrOp::WriteInputIdx::WRITE_GATE).count() == num_rows * desc->hc_count,+ "[GPU][OCL] gated_residual (WRITE): sub-layer output and write gate must have one row per residual row");+ const size_t tile = gr_best_tile(desc->hidden_size);+ auto& wgs = kd.params.workGroups;+ wgs.global = {gr_div_up(desc->hidden_size, tile) * gr_sg, num_rows, 1};+ wgs.local = {gr_sg, 1, 1};+ push_num_rows(kd, num_rows);+ }};+ }+};++// ---------------------------------------------------------------------------+// 3-dispatch systolic pipeline: all three stages compile gr_read_pipeline.cl with a different GR_PIPELINE_STAGE+// ---------------------------------------------------------------------------+class GrRbarGenerator : public GrGenerator {+public:+ explicit GrRbarGenerator(bool decode = false) : GrGenerator("gr_read_pipeline", decode ? "rbar_decode" : "rbar"), m_decode(decode) {}++protected:+ [[nodiscard]] JitConstants get_jit_constants(const RuntimeParams& params) const override {+ auto jit = GrGenerator::get_jit_constants(params);+ const auto desc = params.typed_desc<gated_residual>();+ const size_t ch = gr_best_tile(desc->hidden_size);+ jit.make("GR_PIPELINE_STAGE", 0);+ add_norm_constants(jit, *desc);+ jit.make("GR_CH", ch);+ jit.make("GR_NV_CH", ch / 16);+ const size_t nch = desc->hidden_size / ch;+ const size_t s = rbar_split(*desc, m_decode);+ jit.make("GR_NCH", nch);+ jit.make("GR_RB_S", s);+ // Gain chunks are independent of the norm: preload up to 16 (64 GRFs) while the row is still being reduced.+ jit.make("GR_GPF", desc->hidden_size <= 2560 ? std::min<size_t>(nch / s, 16) : 0);+ jit.make("GR_KPERM", m_decode && gr_decode_kperm(params) ? 1 : 0);+ return jit;+ }++ /// Subgroups sharing one branch row. Decode has a work-group per row and little else to run, so the row is split down to+ /// 4 chunks per subgroup; with more rows the SLM reduction only adds latency.+ static size_t rbar_split(const gated_residual& desc, bool decode) {+ const size_t nch = desc.hidden_size / gr_best_tile(desc.hidden_size);+ if (!decode) {+ return 1;+ }+ return largest_divisor_up_to(nch, std::min(std::max<size_t>(1, nch / 4), std::max<size_t>(1, 32 / desc.hc_count)));+ }++ [[nodiscard]] Arguments get_arguments_desc(const RuntimeParams& /*params*/) const override {+ using Idx = GrOp::ReadInputIdx;+ return {gr_input(Idx::RESIDUAL), gr_input(Idx::NORM_WEIGHT), gr_scratch(GatedResidualInternalBufIdx::RBAR), gr_num_rows_arg()};+ }++ [[nodiscard]] DispatchDataFunc get_dispatch_data_func() const override {+ return DispatchDataFunc{[decode = m_decode](const RuntimeParams& params, KernelData& kd, ImplRuntimeParams*) {+ if (params.is_dynamic()) {+ return;+ }+ const auto desc = params.typed_desc<gated_residual>();+ const size_t num_rows = rows_of(params, *desc);+ auto& wgs = kd.params.workGroups;+ // S subgroups per (branch, row) reduce the branch norm through SLM; one work-group per row.+ const size_t s = rbar_split(*desc, decode);+ wgs.global = {desc->hc_count * s * gr_sg, std::max<size_t>(1, num_rows), 1};+ wgs.local = {desc->hc_count * s * gr_sg, 1, 1};+ push_num_rows(kd, num_rows);+ }};+ }++private:+ bool m_decode;+};++class GrDownProjGenerator : public GrGenerator {+public:+ explicit GrDownProjGenerator(GrTier tier, bool q = false, bool pd = false)+ : GrGenerator("gr_read_pipeline", gr_tier_suffix(tier, true, q, pd)),+ m_tier(tier),+ m_q(q),+ m_pd(pd) {}++protected:+ struct Geometry {+ bool share; // compressed mid / wide tiers: the work-group dequantizes every weight slice once into SLM+ GrQShare qs; // token / K subgroups of a shared work-group+ GrGemmTiling tiling; // token tile and K split+ size_t tn; // low-rank columns per subgroup+ bool gate; // extra write-gate column tile+ };++ /// Every DOWN_PROJ except the work-group shared compressed one has the write-gate column tile. Compressed decode streams 4-8x+ /// fewer weight bytes per column tile, so 16-column tiles spread the work over more work-groups; with two token tiles (9-32+ /// rows) the extra write-gate tile would start a second wave of work-groups, so that case keeps 32 columns.+ static Geometry geometry(const RuntimeParams& params, GrTier tier, bool q) {+ const auto desc = params.typed_desc<gated_residual>();+ const bool share = q && !gr_decode_like(tier);+ const auto qs = gr_down_q_share(*desc, tier);+ const auto tiling =+ share ? GrGemmTiling{32, qs.ks, 1} : gr_down_tiling(*desc, params.get_device_info(), tier, q ? gr_weight_type(params) : GrWType::f16);+ const bool narrow = q && gr_decode_like(tier) && (tier != GrTier::decode || !desc->produce_write_gate);+ return {share, qs, tiling, narrow ? gr_dpas_n : gr_down_tn, desc->produce_write_gate && !share};+ }++ [[nodiscard]] JitConstants get_jit_constants(const RuntimeParams& params) const override {+ auto jit = GrGenerator::get_jit_constants(params);+ const auto desc = params.typed_desc<gated_residual>();+ const auto g = geometry(params, m_tier, m_q);+ jit.make("GR_PIPELINE_STAGE", 1);+ jit.make("GR_LOWRANK", desc->lowrank);+ jit.make("GR_DOWN_TM", g.tiling.tm);+ jit.make("GR_DOWN_TN", g.tn);+ jit.make("GR_DOWN_KSPLIT", g.tiling.ksplit);+ jit.make("GR_PRODUCE_WRITE_GATE", g.gate ? 1 : 0);+ if (m_q) {+ const auto wtype = gr_weight_type(params);+ const size_t cd = desc->hc_count * desc->hidden_size;+ const size_t gs_down = gr_group_size(params, GrOp::ReadInputIdx::SCALE_DOWN, cd);+ const size_t gs_inject = g.gate ? gr_group_size(params, gr_read_layout(params).scale_inject, cd) : cd;+ add_wq_format_constants(jit, params);+ jit.make("GR_Q_SHARE", g.share ? 1 : 0);+ jit.make("GR_KPERM", !g.share && gr_decode_kperm(params) ? 1 : 0);+ if (g.share) {+ jit.make("GR_Q_ST", g.qs.st);+ }+ // per-channel 8-bit weights (also in the write-gate tile) fold their zero point and scale into the epilogue+ jit.make("GR_WQ_FOLD", !g.share && wtype == GrWType::u8 && gs_down == cd && gs_inject == cd ? 1 : 0);+ if (g.gate) {+ jit.make("GR_WI_GS32", gs_inject / gr_dpas_k_step);+ }+ const size_t kch = g.share ? gr_dpas_k_step : gr_wq_kch(wtype, cd / g.tiling.ksplit, cd, g.tiling.wq_bytes);+ add_wq_matrix_constants(jit, "GR_WD", wtype, kch, cd, gs_down);+ }+ return jit;+ }++ [[nodiscard]] Arguments get_arguments_desc(const RuntimeParams& params) const override {+ using Idx = GrOp::ReadInputIdx;+ const auto layout = gr_read_layout(params);+ Arguments args = {gr_scratch(GatedResidualInternalBufIdx::RBAR), m_pd ? gr_scratch(GatedResidualInternalBufIdx::WD_F16) : gr_input(Idx::W_DOWN)};+ if (m_q) {+ args.push_back(gr_input(Idx::SCALE_DOWN));+ args.push_back(gr_zp_arg(layout, Idx::ZP_DOWN, Idx::SCALE_DOWN));+ }+ const bool gate = geometry(params, m_tier, m_q).gate;+ if (gate && m_q) {+ args.push_back(gr_input(layout.w_inject));+ args.push_back(gr_input(layout.scale_inject));+ args.push_back(gr_zp_arg(layout, layout.zp_inject, layout.scale_inject));+ } else if (gate) {+ args.push_back(m_pd ? gr_scratch(GatedResidualInternalBufIdx::WI_F16) : gr_input(layout.w_inject));+ }+ args.push_back(gr_scratch(GatedResidualInternalBufIdx::T_SCRATCH));+ if (gate) {+ args.push_back(gr_output(1)); // write gate S+ }+ args.push_back(gr_num_rows_arg());+ return args;+ }++ [[nodiscard]] DispatchDataFunc get_dispatch_data_func() const override {+ return DispatchDataFunc{[tier = m_tier, q = m_q](const RuntimeParams& params, KernelData& kd, ImplRuntimeParams*) {+ if (params.is_dynamic()) {+ return;+ }+ const auto desc = params.typed_desc<gated_residual>();+ const size_t num_rows = rows_of(params, *desc);+ const auto g = geometry(params, tier, q);+ const size_t col_tiles = (desc->lowrank / g.tn) + (g.gate ? 1 : 0);+ const size_t row_tiles = std::max<size_t>(1, gr_div_up(num_rows, g.tiling.tm));++ auto& wgs = kd.params.workGroups;+ if (g.share) {+ // one work-group = st token subgroups x ks K subgroups on one column tile+ wgs.global = {col_tiles * g.qs.st * g.qs.ks * gr_sg, gr_div_up(row_tiles, g.qs.st), 1};+ wgs.local = {g.qs.st * g.qs.ks * gr_sg, 1, 1};+ } else {+ // one work-group per (column tile, token tile); KSPLIT subgroups split the K reduction+ wgs.global = {col_tiles * g.tiling.ksplit * gr_sg, row_tiles, 1};+ wgs.local = {g.tiling.ksplit * gr_sg, 1, 1};+ }+ push_num_rows(kd, num_rows);+ }};+ }++private:+ GrTier m_tier;+ bool m_q;+ bool m_pd;+};++const char* gr_gate_suffix(GrTier tier) {+ return tier == GrTier::mid ? "gate_mid" : "gate";+}++/// Write gate S = 2 * sigmoid(Rbar . W_inject^T / C) of a compressed READ above the decode regime: the f16 DOWN_PROJ kernel+/// restricted to its write-gate column tile, reading the Rbar scratch and the dequantized W_inject (the work-group shared+/// compressed DOWN_PROJ has no such tile; the decode one has).+class GrGateProjGenerator : public GrGenerator {+public:+ explicit GrGateProjGenerator(GrTier tier) : GrGenerator("gr_read_pipeline", gr_gate_suffix(tier)), m_tier(tier) {}++protected:+ [[nodiscard]] JitConstants get_jit_constants(const RuntimeParams& params) const override {+ auto jit = GrGenerator::get_jit_constants(params);+ const auto desc = params.typed_desc<gated_residual>();+ const auto tiling = gr_down_tiling(*desc, params.get_device_info(), m_tier);+ jit.make("GR_PIPELINE_STAGE", 1);+ jit.make("GR_LOWRANK", desc->lowrank);+ jit.make("GR_DOWN_TM", tiling.tm);+ jit.make("GR_DOWN_TN", gr_dpas_n);+ jit.make("GR_DOWN_KSPLIT", tiling.ksplit);+ jit.make("GR_PRODUCE_WRITE_GATE", 1);+ jit.make("GR_GATE_ONLY", 1);+ return jit;+ }++ [[nodiscard]] Arguments get_arguments_desc(const RuntimeParams& /*params*/) const override {+ return {gr_scratch(GatedResidualInternalBufIdx::RBAR), gr_scratch(GatedResidualInternalBufIdx::WI_F16), gr_output(1), gr_num_rows_arg()};+ }++ [[nodiscard]] DispatchDataFunc get_dispatch_data_func() const override {+ return DispatchDataFunc{[tier = m_tier](const RuntimeParams& params, KernelData& kd, ImplRuntimeParams*) {+ if (params.is_dynamic()) {+ return;+ }+ const auto desc = params.typed_desc<gated_residual>();+ const size_t num_rows = rows_of(params, *desc);+ const auto tiling = gr_down_tiling(*desc, params.get_device_info(), tier);+ const size_t row_tiles = std::max<size_t>(1, gr_div_up(num_rows, tiling.tm));+ auto& wgs = kd.params.workGroups;+ wgs.global = {tiling.ksplit * gr_sg, row_tiles, 1};+ wgs.local = {tiling.ksplit * gr_sg, 1, 1};+ push_num_rows(kd, num_rows);+ }};+ }++private:+ GrTier m_tier;+};++class GrUpProjGenerator : public GrGenerator {+public:+ explicit GrUpProjGenerator(GrTier tier, bool q = false, bool pd = false)+ : GrGenerator("gr_read_pipeline", gr_tier_suffix(tier, false, q, pd)),+ m_tier(tier),+ m_q(q),+ m_pd(pd) {}++protected:+ struct Geometry {+ bool share; // compressed wide tier: the work-group dequantizes every weight slice once into SLM+ bool bsplit; // 4-bit K-permuted decode: one subgroup per branch over the whole low rank+ GrGemmTiling tiling; // token tile and K split+ };++ static Geometry geometry(const RuntimeParams& params, GrTier tier, bool q) {+ const auto desc = params.typed_desc<gated_residual>();+ const bool share = q && !gr_decode_like(tier);+ const bool bsplit = q && gr_decode_like(tier) && gr_decode_kperm(params);+ GrGemmTiling tiling{16, 1, 1};+ if (!share) {+ tiling = bsplit ? GrGemmTiling{8, 1, 1} : gr_up_tiling(*desc, params.get_device_info(), tier, q ? gr_weight_type(params) : GrWType::f16);+ }+ return {share, bsplit, tiling};+ }++ [[nodiscard]] JitConstants get_jit_constants(const RuntimeParams& params) const override {+ auto jit = GrGenerator::get_jit_constants(params);+ const auto desc = params.typed_desc<gated_residual>();+ const auto g = geometry(params, m_tier, m_q);+ jit.make("GR_PIPELINE_STAGE", 2);+ jit.make("GR_LOWRANK", desc->lowrank);+ jit.make("GR_UP_TM", g.tiling.tm);+ jit.make("GR_UP_KSPLIT", g.tiling.ksplit);+ jit.make("GR_UP_BSPLIT", g.bsplit ? 1 : 0);+ if (m_q) {+ const auto wtype = gr_weight_type(params);+ const size_t gs_up = gr_group_size(params, GrOp::ReadInputIdx::SCALE_UP, desc->lowrank);+ add_wq_format_constants(jit, params);+ jit.make("GR_Q_SHARE", g.share ? 1 : 0);+ jit.make("GR_KPERM", g.bsplit ? 1 : 0);+ if (g.share) {+ jit.make("GR_Q_ST", gr_up_q_st);+ }+ jit.make("GR_WQ_FOLD", !g.share && wtype == GrWType::u8 && gs_up == desc->lowrank ? 1 : 0);+ const size_t kch = g.share ? gr_dpas_k_step : gr_wq_kch(wtype, desc->lowrank / g.tiling.ksplit, desc->lowrank, gr_wq_up_load_bytes);+ add_wq_matrix_constants(jit, "GR_WU", wtype, kch, desc->lowrank, gs_up);+ }+ return jit;+ }++ [[nodiscard]] Arguments get_arguments_desc(const RuntimeParams& params) const override {+ using Idx = GrOp::ReadInputIdx;+ Arguments args = {gr_scratch(GatedResidualInternalBufIdx::T_SCRATCH), m_pd ? gr_scratch(GatedResidualInternalBufIdx::WU_F16) : gr_input(Idx::W_UP)};+ if (m_q) {+ args.push_back(gr_input(Idx::SCALE_UP));+ args.push_back(gr_zp_arg(gr_read_layout(params), Idx::ZP_UP, Idx::SCALE_UP));+ }+ args.push_back(gr_scratch(GatedResidualInternalBufIdx::RBAR));+ args.push_back(gr_output(0)); // mixed+ args.push_back(gr_num_rows_arg());+ return args;+ }++ [[nodiscard]] DispatchDataFunc get_dispatch_data_func() const override {+ return DispatchDataFunc{[tier = m_tier, q = m_q](const RuntimeParams& params, KernelData& kd, ImplRuntimeParams*) {+ if (params.is_dynamic()) {+ return;+ }+ const auto desc = params.typed_desc<gated_residual>();+ const size_t num_rows = rows_of(params, *desc);+ const auto g = geometry(params, tier, q);+ const size_t col_tiles = desc->hidden_size / gr_dpas_n;+ const size_t row_tiles = std::max<size_t>(1, gr_div_up(num_rows, g.tiling.tm));++ auto& wgs = kd.params.workGroups;+ if (g.bsplit) {+ // one subgroup per branch+ wgs.global = {col_tiles * desc->hc_count * gr_sg, row_tiles, 1};+ wgs.local = {desc->hc_count * gr_sg, 1, 1};+ } else if (g.share) {+ wgs.global = {col_tiles * gr_up_q_st * gr_sg, gr_div_up(row_tiles, gr_up_q_st), 1};+ wgs.local = {gr_up_q_st * gr_sg, 1, 1};+ } else if (g.tiling.ksplit > 1) {+ wgs.global = {col_tiles * g.tiling.ksplit * gr_sg, row_tiles, 1};+ wgs.local = {g.tiling.ksplit * gr_sg, 1, 1};+ } else {+ // work-groups of lws_y token tiles reuse the same W_up columns from L1+ const size_t lws_y = std::min(g.tiling.lws_y, row_tiles);+ wgs.global = {col_tiles * gr_sg, gr_div_up(row_tiles, lws_y) * lws_y, 1};+ wgs.local = {gr_sg, lws_y, 1};+ }+ push_num_rows(kd, num_rows);+ }};+ }++private:+ GrTier m_tier;+ bool m_q;+ bool m_pd;+};++// ---------------------------------------------------------------------------+// Weight dequantization into an f16 scratch matrix (see gr_pd_min_rows)+// ---------------------------------------------------------------------------+class GrDequantGenerator : public GrGenerator {+public:+ explicit GrDequantGenerator(bool down) : GrGenerator("gr_common", down ? "down" : "up", /*large_grf=*/false), m_down(down) {}++protected:+ /// W_down [L, C*D] or W_up [C*D, L] as [N, K], and the K values one lane converts per work-item+ struct Geometry {+ size_t n;+ size_t k;+ size_t kch;+ };++ static Geometry geometry(const RuntimeParams& params, bool down) {+ const auto desc = params.typed_desc<gated_residual>();+ const size_t cd = desc->hc_count * desc->hidden_size;+ const size_t k = down ? cd : desc->lowrank;+ return {down ? desc->lowrank : cd, k, gr_wq_kch(gr_weight_type(params), k, k, 64)};+ }++ [[nodiscard]] JitConstants get_jit_constants(const RuntimeParams& params) const override {+ auto jit = GrGenerator::get_jit_constants(params);+ const auto g = geometry(params, m_down);+ jit.make("GR_DEQUANT_WEIGHTS", 1);+ add_wq_format_constants(jit, params);+ jit.make("GR_DQ_N", g.n);+ jit.make("GR_DQ_K", g.k);+ const size_t scale_idx = m_down ? GrOp::ReadInputIdx::SCALE_DOWN : GrOp::ReadInputIdx::SCALE_UP;+ add_wq_matrix_constants(jit, "GR_DQ", gr_weight_type(params), g.kch, g.k, gr_group_size(params, scale_idx, g.k));+ return jit;+ }++ [[nodiscard]] Arguments get_arguments_desc(const RuntimeParams& params) const override {+ using Idx = GrOp::ReadInputIdx;+ const size_t scale_idx = m_down ? Idx::SCALE_DOWN : Idx::SCALE_UP;+ return {+ gr_input(m_down ? Idx::W_DOWN : Idx::W_UP),+ gr_input(scale_idx),+ gr_zp_arg(gr_read_layout(params), m_down ? Idx::ZP_DOWN : Idx::ZP_UP, scale_idx),+ gr_scratch(m_down ? GatedResidualInternalBufIdx::WD_F16 : GatedResidualInternalBufIdx::WU_F16),+ };+ }++ [[nodiscard]] DispatchDataFunc get_dispatch_data_func() const override {+ return DispatchDataFunc{[down = m_down](const RuntimeParams& params, KernelData& kd, ImplRuntimeParams*) {+ // one subgroup per 16 rows x kch columns+ const auto g = geometry(params, down);+ auto& wgs = kd.params.workGroups;+ wgs.global = {g.n / 16 * gr_sg, g.k / g.kch, 1};+ wgs.local = {gr_sg, 1, 1};+ }};+ }++private:+ bool m_down;+};++/// Dequantizes the compressed W_inject into the f16 scratch matrix WI_F16, see gr_common.cl.+class GrDequantInjectGenerator : public GrGenerator {+public:+ GrDequantInjectGenerator() : GrGenerator("gr_common", "inject", /*large_grf=*/false) {}++protected:+ [[nodiscard]] JitConstants get_jit_constants(const RuntimeParams& params) const override {+ auto jit = GrGenerator::get_jit_constants(params);+ const auto desc = params.typed_desc<gated_residual>();+ const size_t k = desc->hc_count * desc->hidden_size;+ jit.make("GR_DEQUANT_INJECT", 1);+ add_wq_format_constants(jit, params);+ jit.make("GR_DQ_N", desc->hc_count);+ jit.make("GR_DQ_K", k);+ jit.make("GR_DQ_GS", gr_group_size(params, gr_read_layout(params).scale_inject, k));+ return jit;+ }++ [[nodiscard]] Arguments get_arguments_desc(const RuntimeParams& params) const override {+ const auto layout = gr_read_layout(params);+ return {+ gr_input(layout.w_inject),+ gr_input(layout.scale_inject),+ gr_zp_arg(layout, layout.zp_inject, layout.scale_inject),+ gr_scratch(GatedResidualInternalBufIdx::WI_F16),+ };+ }++ [[nodiscard]] DispatchDataFunc get_dispatch_data_func() const override {+ return DispatchDataFunc{[](const RuntimeParams& params, KernelData& kd, ImplRuntimeParams*) {+ // one work-item per element of W_inject [C, C*D]+ const auto desc = params.typed_desc<gated_residual>();+ auto& wgs = kd.params.workGroups;+ wgs.global = {desc->hc_count * desc->hc_count * desc->hidden_size, 1, 1};+ wgs.local = {gr_sg, 1, 1};+ }};+ }+};++class GatedResidualImpl : public PrimitiveImplOCL {+public:+ DECLARE_OBJECT_TYPE_SERIALIZATION(ov::intel_gpu::ocl::GatedResidualImpl)++ Stage::Ptr gr_read = make_stage<GrReadGenerator>(false);+ Stage::Ptr gr_read_decode = make_stage<GrReadGenerator>(true);+ Stage::Ptr gr_write = make_stage<GrWriteGenerator>();+ Stage::Ptr gr_rbar = make_stage<GrRbarGenerator>();+ Stage::Ptr gr_rbar_decode = make_stage<GrRbarGenerator>(true);+ Stage::Ptr gr_down_proj = make_stage<GrDownProjGenerator>(GrTier::wide);+ Stage::Ptr gr_down_proj_mid = make_stage<GrDownProjGenerator>(GrTier::mid);+ Stage::Ptr gr_down_proj_decode = make_stage<GrDownProjGenerator>(GrTier::decode);+ Stage::Ptr gr_up_proj = make_stage<GrUpProjGenerator>(GrTier::wide);+ Stage::Ptr gr_up_proj_decode = make_stage<GrUpProjGenerator>(GrTier::decode);+ Stage::Ptr gr_read_dpas = make_stage<GrReadDpasGenerator>();+ // compressed weights (same kernel files as f16, selected by GR_W_TYPE)+ Stage::Ptr gr_down_proj_q = make_stage<GrDownProjGenerator>(GrTier::wide, true);+ Stage::Ptr gr_down_proj_q_mid = make_stage<GrDownProjGenerator>(GrTier::mid, true);+ Stage::Ptr gr_down_proj_q_decode = make_stage<GrDownProjGenerator>(GrTier::decode, true);+ Stage::Ptr gr_down_proj_q_gemv = make_stage<GrDownProjGenerator>(GrTier::gemv, true);+ Stage::Ptr gr_up_proj_q = make_stage<GrUpProjGenerator>(GrTier::wide, true);+ Stage::Ptr gr_up_proj_q_decode = make_stage<GrUpProjGenerator>(GrTier::decode, true);+ Stage::Ptr gr_read_dpas_q = make_stage<GrReadDpasGenerator>(true);+ // compressed weights dequantized into f16 scratch by gr_dq_*, then the f16 kernels on the scratch (see gr_pd_min_rows)+ Stage::Ptr gr_dq_down = make_stage<GrDequantGenerator>(true);+ Stage::Ptr gr_dq_up = make_stage<GrDequantGenerator>(false);+ Stage::Ptr gr_down_proj_pd = make_stage<GrDownProjGenerator>(GrTier::wide, false, true);+ Stage::Ptr gr_down_proj_pd_mid = make_stage<GrDownProjGenerator>(GrTier::mid, false, true);+ Stage::Ptr gr_down_proj_pd_decode = make_stage<GrDownProjGenerator>(GrTier::decode, false, true);+ Stage::Ptr gr_up_proj_pd = make_stage<GrUpProjGenerator>(GrTier::wide, false, true);+ Stage::Ptr gr_up_proj_pd_decode = make_stage<GrUpProjGenerator>(GrTier::decode, false, true);+ Stage::Ptr gr_read_dpas_pd = make_stage<GrReadDpasGenerator>(false, true);+ // write gate of a compressed READ above the decode regime: W_inject dequantized into f16 scratch, then the f16 gate-only+ // kernel on the Rbar scratch (the decode DOWN_PROJ has the write-gate tile itself)+ Stage::Ptr gr_dq_inject = make_stage<GrDequantInjectGenerator>();+ Stage::Ptr gr_gate_mid = make_stage<GrGateProjGenerator>(GrTier::mid);+ Stage::Ptr gr_gate_wide = make_stage<GrGateProjGenerator>(GrTier::wide);++ GatedResidualImpl() : PrimitiveImplOCL(GatedResidualImplementationManager::get_type_info_static()) {}+ GatedResidualImpl(const program_node& /*node*/, const RuntimeParams& params) : GatedResidualImpl() {+ // a dynamic shape builds the stages of every row count+ const auto rows_list = params.is_dynamic() ? gr_routing_rows(params) : std::vector<size_t>{rows_of(params, *params.typed_desc<gated_residual>())};+ for (const size_t rows : rows_list) {+ for (auto* stage : stages_for(params, rows)) {+ if (!has_stage(*stage)) {+ add_stage(*stage, params);+ OPENVINO_ASSERT(has_stage(*stage), "[GPU][OCL] gated_residual: can't build a kernel for ", rows, " rows");+ }+ }+ }+ }++ /// The stages one call over `rows` token rows dispatches, in order: the scratch buffers are produced and consumed in it.+ std::vector<Stage::Ptr*> stages_for(const RuntimeParams& params, size_t rows) {+ const auto desc = params.typed_desc<gated_residual>();+ if (desc->mode == gated_residual::Mode::WRITE) {+ return {&gr_write};+ }+ if (!can_use_dpas_gr_read(params)) {+ return {rows <= gr_decode_rows ? &gr_read_decode : &gr_read};+ }+ const auto p = read_plan(params, rows);+ std::vector<Stage::Ptr*> stages;+ if (p.pd) {+ stages.push_back(&gr_dq_down);+ stages.push_back(&gr_dq_up);+ }+ if (p.dq_inject) {+ stages.push_back(&gr_dq_inject);+ }+ if (p.single) {+ stages.push_back(read_dpas_stage(p.q, p.pd));+ return stages;+ }+ stages.push_back(&rbar_stage(rows));+ if (p.gate_dispatch) {+ stages.push_back(&gate_stage(p.tier));+ }+ stages.push_back(&down_stage(p.tier, p.q, p.pd));+ stages.push_back(&up_stage(gr_up_tier(rows), p.q, p.pd));+ return stages;+ }++ Stage::Ptr* read_dpas_stage(bool q, bool pd) {+ if (pd) {+ return &gr_read_dpas_pd;+ }+ return q ? &gr_read_dpas_q : &gr_read_dpas;+ }++ Stage::Ptr& rbar_stage(size_t rows) {+ return rows <= gr_decode_rows ? gr_rbar_decode : gr_rbar;+ }++ Stage::Ptr& down_stage(GrTier tier, bool q, bool pd) {+ if (pd) {+ if (gr_decode_like(tier)) {+ return gr_down_proj_pd_decode;+ }+ return tier == GrTier::mid ? gr_down_proj_pd_mid : gr_down_proj_pd;+ }+ if (q) {+ if (tier == GrTier::gemv) {+ return gr_down_proj_q_gemv;+ }+ if (tier == GrTier::decode) {+ return gr_down_proj_q_decode;+ }+ return tier == GrTier::mid ? gr_down_proj_q_mid : gr_down_proj_q;+ }+ if (gr_decode_like(tier)) {+ return gr_down_proj_decode;+ }+ return tier == GrTier::mid ? gr_down_proj_mid : gr_down_proj;+ }++ Stage::Ptr& up_stage(GrTier tier, bool q, bool pd) {+ if (pd) {+ return tier == GrTier::decode ? gr_up_proj_pd_decode : gr_up_proj_pd;+ }+ if (q) {+ return tier == GrTier::decode ? gr_up_proj_q_decode : gr_up_proj_q;+ }+ return tier == GrTier::decode ? gr_up_proj_decode : gr_up_proj;+ }++ Stage::Ptr& gate_stage(GrTier tier) {+ return tier == GrTier::mid ? gr_gate_mid : gr_gate_wide;+ }++ [[nodiscard]] std::unique_ptr<primitive_impl> clone() const override {+ return make_deep_copy<GatedResidualImpl>(this);+ }++ // A dynamic impl holds every stage; the row count picks the ones to run.+ [[nodiscard]] std::vector<size_t> get_stages_execution_order(const kernel_impl_params& params) const override {+ const size_t rows = rows_of(params, *params.typed_desc<gated_residual>());+ // stages_for only reads the identities of the stage members+ const auto stages = const_cast<GatedResidualImpl*>(this)->stages_for(params, rows);+ std::vector<size_t> order;+ for (const auto* stage : stages) {+ const auto it = std::find(_stages.begin(), _stages.end(), stage->get());+ OPENVINO_ASSERT(it != _stages.end() && has_stage(*stage), "[GPU][OCL] gated_residual: a stage for ", rows, " rows was not built");+ order.push_back(static_cast<size_t>(it - _stages.begin()));+ }+ return order;+ }++ // Scratch buffers of the static dpas READ. Their indices are fixed (the dynamic impl's kernels bind them before the row count is+ // known), so a buffer the plan does not use is a 1-element placeholder.+ [[nodiscard]] std::vector<BufferDescriptor> get_internal_buffer_descs(const kernel_impl_params& params) const override {+ const auto desc = params.typed_desc<gated_residual>();+ if (params.is_dynamic() || desc->mode == gated_residual::Mode::WRITE || !can_use_dpas_gr_read(params)) {+ return {};+ }+ const size_t cd = desc->hc_count * desc->hidden_size;+ const size_t rows = rows_of(params, *desc);+ const auto p = read_plan(params, rows);+ const auto f16_buffer = [](bool used, size_t count) {+ return BufferDescriptor{used ? std::max<size_t>(1, count) : 1, ov::element::f16};+ };+ return {+ f16_buffer(!p.single, rows * cd), // RBAR+ f16_buffer(!p.single, rows * desc->lowrank), // T_SCRATCH+ f16_buffer(p.pd, desc->lowrank * cd), // WD_F16+ f16_buffer(p.pd, cd * desc->lowrank), // WU_F16+ f16_buffer(p.dq_inject, desc->hc_count * cd),+ }; // WI_F16+ }+};++} // namespace++bool GatedResidualImplementationManager::validate_impl(const cldnn::program_node& node) const {+ OPENVINO_ASSERT(node.is_type<cldnn::gated_residual>());++ if (node.has_fused_primitives()) {+ return false;+ }++ const auto& info = node.get_program().get_engine().get_device_info();+ if (!caps::is_device_supported(info)) {+ return false;+ }++ const auto desc = node.as<cldnn::gated_residual>().get_primitive();+ const bool systolic = caps::uses_dpas_kernels(info, node.get_program().get_config());+ if (!caps::is_geometry_supported(desc->mode, desc->hc_count, desc->hidden_size, desc->lowrank, systolic)) {+ return false;+ }++ // The kernels index dense rows from JIT constants, so padded layouts are not supported.+ const auto is_bfyx = [](const cldnn::layout& l, ov::element::Type type) {+ return l.format == cldnn::format::bfyx && l.data_type == type && l.data_padding == cldnn::padding();+ };+ for (size_t i = 0; i < node.get_outputs_count(); i++) {+ if (!is_bfyx(node.get_output_layout(i), ov::element::f16)) {+ return false;+ }+ }++ const size_t input_count = node.get_dependencies().size();+ std::optional<GrOp::ReadLayout> layout;+ if (desc->mode != cldnn::gated_residual::Mode::WRITE) {+ layout = GrOp::read_layout(input_count, desc->produce_write_gate);+ if (!layout) {+ return false;+ }+ }+ if (!layout || !layout->compressed) {+ for (size_t i = 0; i < input_count; i++) {+ if (!is_bfyx(node.get_input_layout(i), ov::element::f16)) {+ return false;+ }+ }+ return true;+ }++ // Compressed READ (dpas kernels and the scalar gr_read.cl): i4 / u4 / i8 / u8 W_down / W_up (and W_inject) with+ // static f16 [G, N] scales and optional zero points of the weight type.+ using Idx = GrOp::ReadInputIdx;+ const ov::element::Type wt = node.get_input_layout(Idx::W_DOWN).data_type;+ if (!GrOp::is_compressed_weight_type(wt)) {+ return false;+ }+ for (size_t i = 0; i < input_count; i++) {+ const bool f16_input = i == Idx::RESIDUAL || i == Idx::NORM_WEIGHT || i == Idx::SCALE_DOWN || i == Idx::SCALE_UP ||+ (desc->produce_write_gate && i == layout->scale_inject);+ if (!is_bfyx(node.get_input_layout(i), f16_input ? ov::element::f16 : wt)) {+ return false;+ }+ }+ const auto& sd = node.get_input_layout(Idx::SCALE_DOWN);+ const auto& su = node.get_input_layout(Idx::SCALE_UP);+ if (sd.is_dynamic() || su.is_dynamic() || sd.get_partial_shape().size() != 2 || su.get_partial_shape().size() != 2) {+ return false;+ }+ const size_t cd = desc->hc_count * desc->hidden_size;+ const size_t bits = wt.bitwidth();+ if (sd.get_shape()[1] != desc->lowrank || su.get_shape()[1] != cd || !caps::is_matrix_compression_supported(bits, desc->lowrank, cd, sd.get_shape()[0]) ||+ !caps::is_matrix_compression_supported(bits, cd, desc->lowrank, su.get_shape()[0])) {+ return false;+ }+ if (desc->produce_write_gate) {+ const auto& wi = node.get_input_layout(layout->w_inject);+ const auto& si = node.get_input_layout(layout->scale_inject);+ if (wi.is_dynamic() || si.is_dynamic() || wi.get_partial_shape().size() != 2 || si.get_partial_shape().size() != 2 ||+ wi.get_shape()[0] != desc->hc_count || wi.get_shape()[1] != cd || si.get_shape()[1] != desc->hc_count ||+ !caps::is_row_compression_supported(bits, cd, si.get_shape()[0])) {+ return false;+ }+ }+ return true;+}++std::unique_ptr<cldnn::primitive_impl> GatedResidualImplementationManager::create_impl(const cldnn::program_node& node,+ const cldnn::kernel_impl_params& params) const {+ OPENVINO_ASSERT(node.is_type<cldnn::gated_residual>());+ return std::make_unique<GatedResidualImpl>(node, params);+}++} // namespace ov::intel_gpu::ocl++BIND_BINARY_BUFFER_WITH_TYPE(ov::intel_gpu::ocl::GatedResidualImpl)diff --git a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/gated_residual/gated_residual.hpp b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/gated_residual/gated_residual.hppnew file mode 100644index 00000000000..5c8c99ae841--- /dev/null+++ b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/gated_residual/gated_residual.hpp@@ -0,0 +1,44 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#pragma once++#include <memory>+#include <utility>++#include "gated_residual_inst.h"+#include "intel_gpu/runtime/layout.hpp"+#include "program_node.h"+#include "registry/implementation_manager.hpp"++namespace ov::intel_gpu::ocl {++/// @brief Internal (scratch) buffers of the 3-dispatch systolic READ pipeline.+struct GatedResidualInternalBufIdx {+ static constexpr size_t RBAR = 0; ///< f16 [num_rows, C*D], branch-wise RMSNorm output+ static constexpr size_t T_SCRATCH = 1; ///< f16 [num_rows, L], down-projection + SiLU output+ static constexpr size_t WD_F16 = 2; ///< f16 [L, C*D], dequantized W_down (compressed weights with many rows)+ static constexpr size_t WU_F16 = 3; ///< f16 [C*D, L], dequantized W_up+ static constexpr size_t WI_F16 = 4; ///< f16 [C, C*D], dequantized W_inject (compressed weights with a write gate)+};++/// @brief OpenCL implementation of the gated residual READ/WRITE stages.+struct GatedResidualImplementationManager : public cldnn::ImplementationManager {+ OV_GPU_PRIMITIVE_IMPL("ocl::gated_residual")+ explicit GatedResidualImplementationManager(cldnn::shape_types shape_type, cldnn::ValidateFunc vf = nullptr)+ : ImplementationManager(cldnn::impl_types::ocl, shape_type, std::move(vf)) {}++ [[nodiscard]] std::unique_ptr<cldnn::primitive_impl> create_impl(const cldnn::program_node& node, const cldnn::kernel_impl_params& params) const override;++ // READ with `produce_write_gate` has two outputs; every output needs an explicit format.+ [[nodiscard]] cldnn::in_out_fmts_t query_formats(const cldnn::program_node& node) const override {+ std::vector<cldnn::format::type> in_fmts(node.get_dependencies().size(), cldnn::format::bfyx);+ std::vector<cldnn::format::type> out_fmts(node.get_outputs_count(), cldnn::format::bfyx);+ return {in_fmts, out_fmts};+ }++ [[nodiscard]] bool validate_impl(const cldnn::program_node& node) const override;+};++} // namespace ov::intel_gpu::ocldiff --git a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/gr_common.cl b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/gr_common.clnew file mode 100644index 00000000000..afe851c573a--- /dev/null+++ b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/gr_common.cl@@ -0,0 +1,327 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++// Shared helpers of the GatedResidual OpenCL kernels, plus the weight dequantization kernel (GR_DEQUANT_WEIGHTS). One subgroup+// (16 lanes) is one Xe2 hardware thread; a row of 16*NV halves is held lane-interleaved: element e lives in component (e / 16)+// of lane (e % 16), which is exactly what intel_sub_group_block_read_us{1,2,4,8} returns. The header is inlined into every+// kernel separately (no include guard, helper functions go through FUNC).++#include "include/batch_headers/common.cl"+#include "include/batch_headers/sub_group_block_read.cl"+#include "include/batch_headers/sub_group_block_write.cl"++#define GR_LOG2E 1.4426950408889634f++#define GR_BR_1 intel_sub_group_block_read_us+#define GR_BR_2 intel_sub_group_block_read_us2+#define GR_BR_4 intel_sub_group_block_read_us4+#define GR_BR_8 intel_sub_group_block_read_us8+#define GR_BW_1 intel_sub_group_block_write_us+#define GR_BW_2 intel_sub_group_block_write_us2+#define GR_BW_4 intel_sub_group_block_write_us4+#define GR_BW_8 intel_sub_group_block_write_us8+#define GR_CVF_1 convert_float+#define GR_CVF_2 convert_float2+#define GR_CVF_4 convert_float4+#define GR_CVF_8 convert_float8+#define GR_ASH_1 as_half+#define GR_ASH_2 as_half2+#define GR_ASH_4 as_half4+#define GR_ASH_8 as_half8+#define GR_CVH_1 convert_half_rte+#define GR_CVH_2 convert_half2_rte+#define GR_CVH_4 convert_half4_rte+#define GR_CVH_8 convert_half8_rte+#define GR_ASU_1 as_ushort+#define GR_ASU_2 as_ushort2+#define GR_ASU_4 as_ushort4+#define GR_ASU_8 as_ushort8++#define GR_UT(nv) MAKE_VECTOR_TYPE(ushort, nv)+#define GR_FT(nv) MAKE_VECTOR_TYPE(float, nv)++// ushort block of 16*nv halves -> float vector, and back (round to nearest even)+#define GR_LDF(nv, p) CAT(GR_CVF_, nv)(CAT(GR_ASH_, nv)(CAT(GR_BR_, nv)(p)))+#define GR_BRU(nv, p) CAT(GR_BR_, nv)(p)+#define GR_STF(nv, p, f) CAT(GR_BW_, nv)(p, CAT(GR_ASU_, nv)(CAT(GR_CVH_, nv)(f)))+#define GR_U2F(nv, u) CAT(GR_CVF_, nv)(CAT(GR_ASH_, nv)(u))+#define GR_F2U(nv, f) CAT(GR_ASU_, nv)(CAT(GR_CVH_, nv)(f))++// sequential per-lane accumulation over the components+#define GR_ACC_1(s, v) { s += (v); }+#define GR_ACC_2(s, v) { s += (v).s0; s += (v).s1; }+#define GR_ACC_4(s, v) { s += (v).s0; s += (v).s1; s += (v).s2; s += (v).s3; }+#define GR_ACC_8(s, v) { s += (v).s0; s += (v).s1; s += (v).s2; s += (v).s3; s += (v).s4; s += (v).s5; s += (v).s6; s += (v).s7; }+#define GR_ACC(nv, s, v) CAT(GR_ACC_, nv)(s, v)++// s += a . b over the components+#define GR_DOT_1(s, a, b) { s += (a) * (b); }+#define GR_DOT_2(s, a, b) { s += (a).s0 * (b).s0; s += (a).s1 * (b).s1; }+#define GR_DOT_4(s, a, b) { s += (a).s0 * (b).s0; s += (a).s1 * (b).s1; s += (a).s2 * (b).s2; s += (a).s3 * (b).s3; }+#define GR_DOT_8(s, a, b) { s += (a).s0 * (b).s0; s += (a).s1 * (b).s1; s += (a).s2 * (b).s2; s += (a).s3 * (b).s3; s += (a).s4 * (b).s4; s += (a).s5 * (b).s5; s += (a).s6 * (b).s6; s += (a).s7 * (b).s7; }+#define GR_DOT(nv, s, a, b) CAT(GR_DOT_, nv)(s, a, b)++// lane-interleaved SLM access of 16*nv ushorts+#define GR_SLMST_1(p, v, l) { (p)[l] = (v); }+#define GR_SLMST_2(p, v, l) { (p)[l] = (v).s0; (p)[16 + l] = (v).s1; }+#define GR_SLMST_4(p, v, l) { (p)[l] = (v).s0; (p)[16 + l] = (v).s1; (p)[32 + l] = (v).s2; (p)[48 + l] = (v).s3; }+#define GR_SLMST_8(p, v, l) { (p)[l] = (v).s0; (p)[16 + l] = (v).s1; (p)[32 + l] = (v).s2; (p)[48 + l] = (v).s3; (p)[64 + l] = (v).s4; (p)[80 + l] = (v).s5; (p)[96 + l] = (v).s6; (p)[112 + l] = (v).s7; }+#define GR_SLMST(nv, p, v, l) CAT(GR_SLMST_, nv)(p, v, l)+#define GR_SLMLD_1(p, l) ((p)[l])+#define GR_SLMLD_2(p, l) ((ushort2)((p)[l], (p)[16 + l]))+#define GR_SLMLD_4(p, l) ((ushort4)((p)[l], (p)[16 + l], (p)[32 + l], (p)[48 + l]))+#define GR_SLMLD_8(p, l) ((ushort8)((p)[l], (p)[16 + l], (p)[32 + l], (p)[48 + l], (p)[64 + l], (p)[80 + l], (p)[96 + l], (p)[112 + l]))+#define GR_SLMLD(nv, p, l) CAT(GR_SLMLD_, nv)(p, l)++#define GR_SIGMOID(x) native_recip(1.0f + native_exp2(-(x) * GR_LOG2E))++// K permutation of the 4-bit decode GEMMs (GR_KPERM), applied inside every 8 consecutive K values: storage position p holds+// k = GR_KP(p), k sits at position GR_KQ(k)+#define GR_KP(p) (((p) & ~7u) | (((p) & 7u) >> 1) | (((p) & 1u) << 2))+#define GR_KQ(k) (((k) & ~7u) | (((k) & 3u) << 1) | (((k) >> 2) & 1u))+#ifndef GR_KPERM+#define GR_KPERM 0+#endif++#define GR_MAD intel_sub_group_f16_f16_matrix_mad_k16++// 2D block reads of a row-major f16 matrix (surface: width/pitch in bytes, height in rows; rows past the height read 0).+// GR_RD2D(rows, ...): rows x 32 halves (two K16 slices) -> dst[s * rows + r] = M[y + r][x + 16 * s + lane]+// GR_RD2D1(rows, ...): rows x 16 halves -> dst[r] = M[y + r][x + lane]+#define GR_RD2D_8 intel_sub_group_2d_block_read_16b_8r16x2c+#define GR_RD2D_16 intel_sub_group_2d_block_read_16b_16r16x2c+#define GR_RD2D_32 intel_sub_group_2d_block_read_16b_32r16x2c+#define GR_RD2D(rows, base, width, height, pitch, x, y, dst) CAT(GR_RD2D_, rows)((__global void*)(base), (width), (height), (pitch), (int2)((x), (y)), (dst))+#define GR_RD2D1_8 intel_sub_group_2d_block_read_16b_8r16x1c+#define GR_RD2D1(rows, base, width, height, pitch, x, y, dst) CAT(GR_RD2D1_, rows)((__global void*)(base), (width), (height), (pitch), (int2)((x), (y)), (dst))++// SLM block write; the __local overload of intel_sub_group_block_write needs cl_intel_subgroup_local_block_io, otherwise each lane stores+// its own column+#if defined(cl_intel_subgroup_local_block_io)+ #define GR_BLOCK_WRITEN_SLM(type, nv, ptr, offset, val) BLOCK_WRITEN_SLM(type, nv, ptr, offset, val)+#else+ #define GR_BLOCK_WRITEN_SLM(type, nv, ptr, offset, val) GR_SLMST(nv, (__local type*)(ptr) + (offset), val, get_sub_group_local_id())+#endif++// rows of 8 tokens: component i of the 8 values is token i (one SLM block message per tile)+inline void FUNC(gr_st8)(__local float* p, float8 v) {+ GR_BLOCK_WRITEN_SLM(uint, 8, (__local uint*)p, 0, as_uint8(v));+}++inline float8 FUNC(gr_ld8)(const __local float* p) {+ return as_float8(BLOCK_READN_SLM(uint, 8, (const __local uint*)p, 0));+}++// Compressed-weight (i4/u4 and i8/u8, group size a multiple of 32, optional zero point) helpers of the GatedResidual dpas kernels.+//+// A dpas B operand is b[j] = pack(B[2j][n = lane], B[2j+1][n = lane]): the two k values of one lane share a dword. W is+// [N, K] with K contiguous, so a lane that owns row n reads its raw bytes and unpacks them in registers:+// 4-bit: one byte = (w[n,k], w[n,k+1]) for even k (low nibble = even k) -> one VNNI dword per byte+// 8-bit: one dword = two VNNI dwords+// Signed weights are moved to the unsigned domain by flipping the sign bit of every element when the raw dwords are loaded+// (q + 2^(bits - 1)); zero points get the same shift, so q - zp is unchanged. A missing zero point is 0 (2^(bits - 1) once shifted).+// 0x6400 | v (v < 1024) is the half 1024 + v, so a pair becomes two halves with one mask/or; (pair - (1024 + zp)) * scale then+// equals half(half(q - zp) * scale) of the decompression graph bit for bit (q - zp is exact in half, one RNE multiply).+// scale / zp are [G, N] with N contiguous: one sub-group block read gives every lane the scale of its own output channel.+// A group spans GS32 K32 slices (group size 32 * GS32; the GR_W*_GS32 JIT constants); GR_W*_PERCH marks a single group.+//+// JIT of the including kernel: GR_W_TYPE (0 f16, 1 4-bit, 2 8-bit), GR_W_SIGNED (default 0), GR_HAS_ZP (default 1; kernels still+// take the zp argument, the host binds any buffer when there is no zp tensor and it is never read).++#ifndef GR_GATE_ONLY+#define GR_GATE_ONLY 0+#endif++#ifndef GR_W_TYPE+#define GR_W_TYPE 0+#endif+#ifndef GR_W_SIGNED+#define GR_W_SIGNED 0+#endif+#ifndef GR_HAS_ZP+#define GR_HAS_ZP 1+#endif+#define GR_WT_F16 0+#define GR_WT_U4 1 // 4-bit weights, signed or not (GR_W_SIGNED)+#define GR_WT_U8 2 // 8-bit weights, signed or not++#if GR_W_TYPE != GR_WT_F16++#if GR_W_TYPE == GR_WT_U4+ #define GR_WQ_BITS 4+ #define GR_WQ_SIGN 0x8u+ #define GR_WQ_RAW_FLIP 0x88888888u+#else+ #define GR_WQ_BITS 8+ #define GR_WQ_SIGN 0x80u+ #define GR_WQ_RAW_FLIP 0x80808080u+#endif+#if GR_W_SIGNED+ #define GR_WQ_FLIP(v) ((v) ^ GR_WQ_SIGN)+#else+ #define GR_WQ_FLIP(v) (v)+#endif++// Element i of a [G, N] zero point table (4-bit: packed two per byte, low nibble = even index; N % 16 == 0, so a 16-lane block+// never straddles a row) in the unsigned domain.+#if GR_HAS_ZP+ #if GR_W_TYPE == GR_WT_U4+ #define GR_WQ_ZPAT(zp, i) GR_WQ_FLIP((uint)((((zp)[(size_t)(i) >> 1]) >> (((size_t)(i) & 1) * 4)) & 0xF))+ #else+ #define GR_WQ_ZPAT(zp, i) GR_WQ_FLIP((uint)((zp)[i]))+ #endif+ // the same for an already loaded zp byte, `sh` selecting the nibble of a 4-bit table+ #if GR_W_TYPE == GR_WT_U4+ #define GR_WQ_ZPLD(b, sh) GR_WQ_FLIP((uint)(((b) >> (sh)) & 0xF))+ #else+ #define GR_WQ_ZPLD(b, sh) GR_WQ_FLIP((uint)(b))+ #endif+#else+ #define GR_WQ_ZPAT(zp, i) GR_WQ_FLIP(0u)+ #define GR_WQ_ZPLD(b, sh) GR_WQ_FLIP(0u)+#endif++// Group of K32 slice s when a group spans gs32 slices (group size = 32 * gs32)+#define GR_WQ_G(s, gs32) ((s) / (gs32))+// Offset the group-fold B operand carries: half(1024 + q) for 4-bit, half(q) for 8-bit+#if GR_W_TYPE == GR_WT_U4+ #define GR_WQ_BIAS 1024.0f+#else+ #define GR_WQ_BIAS 0.0f+#endif++#define GR_WQ_MAGIC 0x64006400u++// u4: s holds k = 8w .. 8w+7; byte b is the pair (8w+2b, 8w+2b+1), the even k in the low half+#define GR_U4_PAIR0(s) ((((s)) & 0x0000000Fu) | (((s) << 12) & 0x000F0000u) | GR_WQ_MAGIC)+#define GR_U4_PAIR1(s) ((((s) >> 8) & 0x0000000Fu) | (((s) << 4) & 0x000F0000u) | GR_WQ_MAGIC)+#define GR_U4_PAIR2(s) ((((s) >> 16) & 0x0000000Fu) | (((s) >> 4) & 0x000F0000u) | GR_WQ_MAGIC)+#define GR_U4_PAIR3(s) ((((s) >> 24) & 0x0000000Fu) | (((s) >> 12) & 0x000F0000u) | GR_WQ_MAGIC)+// u8: s holds k = 4w .. 4w+3+#define GR_U8_PAIR0(s) ((((s)) & 0x000000FFu) | (((s) << 8) & 0x00FF0000u) | GR_WQ_MAGIC)+#define GR_U8_PAIR1(s) ((((s) >> 16) & 0x000000FFu) | (((s) >> 8) & 0x00FF0000u) | GR_WQ_MAGIC)++// zp2 = (half2)(1024 + zp), sc2 = (half2)(scale): both halves of a pair belong to the same output channel+#define GR_WQ_DQ(pair, zp2, sc2) as_uint((as_half2(pair) - (zp2)) * (sc2))++// One K32 slice (q = the raw dwords of the lane's row starting at index o) -> the 16 dwords of the B operand+// (.lo = K16 slice 0, .hi = K16 slice 1)+#define GR_Q4_4(a, zp2, sc2) GR_WQ_DQ(GR_U4_PAIR0(a), zp2, sc2), GR_WQ_DQ(GR_U4_PAIR1(a), zp2, sc2), GR_WQ_DQ(GR_U4_PAIR2(a), zp2, sc2), GR_WQ_DQ(GR_U4_PAIR3(a), zp2, sc2)+#define GR_Q8_2(a, zp2, sc2) GR_WQ_DQ(GR_U8_PAIR0(a), zp2, sc2), GR_WQ_DQ(GR_U8_PAIR1(a), zp2, sc2)++#if GR_W_TYPE == GR_WT_U4+ #define GR_WQ_RAW_PER_K32 4+ #define GR_WQ_DEQ32(q, o, zp2, sc2) ((uint16)(GR_Q4_4((q)[(o)], zp2, sc2), GR_Q4_4((q)[(o) + 1], zp2, sc2), GR_Q4_4((q)[(o) + 2], zp2, sc2), GR_Q4_4((q)[(o) + 3], zp2, sc2)))+ // B operand half(1024 + q) of one K32 slice, no arithmetic: the caller applies (1024 + zp) and the group scale to the accumulator+ #define GR_U4M_4(a) GR_U4_PAIR0(a), GR_U4_PAIR1(a), GR_U4_PAIR2(a), GR_U4_PAIR3(a)+ #define GR_WQ_U4M32(q, o) ((uint16)(GR_U4M_4((q)[(o)]), GR_U4M_4((q)[(o) + 1]), GR_U4M_4((q)[(o) + 2]), GR_U4M_4((q)[(o) + 3])))+#else+ #define GR_WQ_RAW_PER_K32 8+ #define GR_WQ_DEQ32(q, o, zp2, sc2) \+ ((uint16)(GR_Q8_2((q)[(o)], zp2, sc2), GR_Q8_2((q)[(o) + 1], zp2, sc2), GR_Q8_2((q)[(o) + 2], zp2, sc2), GR_Q8_2((q)[(o) + 3], zp2, sc2), \+ GR_Q8_2((q)[(o) + 4], zp2, sc2), GR_Q8_2((q)[(o) + 5], zp2, sc2), GR_Q8_2((q)[(o) + 6], zp2, sc2), GR_Q8_2((q)[(o) + 7], zp2, sc2)))+#endif++// raw[] <- nraw dwords of the lane's weight row at K index k (brow: the row's first byte), signed weights shifted to unsigned+#if GR_W_SIGNED+#define GR_WQ_LOAD_RAW(raw, nraw, brow, k) { MAKE_VECTOR_TYPE(uint, nraw) t_ = CAT(vload, nraw)(0, (const __global uint*)((brow) + (size_t)(k) * GR_WQ_BITS / 8)); t_ ^= GR_WQ_RAW_FLIP; CAT(vstore, nraw)(t_, 0, raw); }+#else+#define GR_WQ_LOAD_RAW(raw, nraw, brow, k) { MAKE_VECTOR_TYPE(uint, nraw) t_ = CAT(vload, nraw)(0, (const __global uint*)((brow) + (size_t)(k) * GR_WQ_BITS / 8)); CAT(vstore, nraw)(t_, 0, raw); }+#endif++// scale / zp row g holds N entries; nb..nb+15 is one contiguous block read, lane l gets output channel nb + l+#define GR_WQ_SCALE2(scale, g, N, nb) ((half2)(as_half(intel_sub_group_block_read_us((scale) + (size_t)(g) * (N) + (nb)))))+#define GR_WQ_ZP2(zp, g, N, nb, lane) ((half2)((half)1024.0h + convert_half(GR_WQ_ZPAT(zp, (size_t)(g) * (N) + (nb) + (lane)))))++// 8-bit decode GEMMs (see GR_WQ_FOLD) feed half(q) as the B operand; q < 256 is exact in half+#define GR_WQ_ONES_U 0x3C003C00u+#define GR_WQ_ONES ((int8)(GR_WQ_ONES_U))+#define GR_WQ_U8H16(q, o) as_uint8(convert_half16(as_uchar16((uint4)((q)[(o)], (q)[(o) + 1], (q)[(o) + 2], (q)[(o) + 3]))))+#define GR_WQ_U8B32(q, o) ((uint16)(GR_WQ_U8H16(q, o), GR_WQ_U8H16(q, (o) + 4)))+// B operand of the group-fold loops: half(bias + q) of one K32 slice, no arithmetic (GR_WQ_BIAS)+#if GR_W_TYPE == GR_WT_U4+ #define GR_WQ_GB32(q, o) GR_WQ_U4M32(q, o)+#else+ #define GR_WQ_GB32(q, o) GR_WQ_U8B32(q, o)+#endif+// 4-bit B operand in the K-permuted order (GR_KPERM): dword j of a raw dword holds nibbles (j, j + 4), one shift and one mask+// per B dword. The activations are stored with the same permutation: position p holds k = GR_KP(p).+#define GR_U4P_4(a) (((a) & 0x000F000Fu) | GR_WQ_MAGIC), ((((a) >> 4) & 0x000F000Fu) | GR_WQ_MAGIC), ((((a) >> 8) & 0x000F000Fu) | GR_WQ_MAGIC), ((((a) >> 12) & 0x000F000Fu) | GR_WQ_MAGIC)+#define GR_WQ_U4P32(q, o) ((uint16)(GR_U4P_4((q)[(o)]), GR_U4P_4((q)[(o) + 1]), GR_U4P_4((q)[(o) + 2]), GR_U4P_4((q)[(o) + 3])))+#define GR_WQ_SCALEF(scale, nb) convert_float(as_half(intel_sub_group_block_read_us((scale) + (nb))))+#define GR_WQ_ZPF(zp, nb, lane) convert_float(GR_WQ_ZPAT(zp, (nb) + (lane)))++#endif // GR_W_TYPE != GR_WT_F16++// Per-channel 8-bit weights (the kernel's JIT sets GR_WQ_FOLD) have their zero point and scale folded out of the K loop: the dpas+// runs on half(q), also accumulates the token row sums against a ones operand, and the epilogue applies+// acc = scale * (acc - zp * rowsum). Every other layout applies them per group (see the group-fold loops).+#ifndef GR_WQ_FOLD+#define GR_WQ_FOLD 0+#endif++#if GR_DEQUANT_WEIGHTS+// Dequantizes one compressed GatedResidual weight matrix [N, K] (4-bit / 8-bit, scale / zp [G, N]) into a+// row-major f16 scratch matrix with the arithmetic of the decompression graph, see the helpers above. The f16 GEMM kernels then+// run on the scratch (used above the GPU_GR_PD_ROW_THRESHOLD row count).+//+// One subgroup owns 16 rows x GR_DQ_KCH columns; lane l owns row 16 * tile + l.+// JIT: GR_DEQUANT_WEIGHTS, GR_W_TYPE, GR_DQ_N, GR_DQ_K, GR_DQ_KCH, GR_DQ_NRAW (dwords per raw load), GR_DQ_RB (row bytes), GR_DQ_GS32+// (group size / 32), GR_DQ_PERCH (one group).+// Dispatch: gws = [N / 16 * 16, K / GR_DQ_KCH, 1], lws = [16, 1, 1].++#if GR_W_TYPE == GR_WT_F16+ #error "gr_common.cl: compressed weights only"+#endif++REQD_SUB_GROUP_SIZE(16)+KERNEL(gr_dequant_weights)(const __global uchar* w, const __global ushort* scale, const __global uchar* zp, __global ushort* out) {+ const uint lane = get_sub_group_local_id();+ const uint n0 = get_group_id(0) * 16;+ const uint k = get_group_id(1) * GR_DQ_KCH;+ const __global uchar* brow = w + (size_t)(n0 + lane) * GR_DQ_RB;++ uint rw[GR_DQ_NRAW];+ GR_WQ_LOAD_RAW(rw, GR_DQ_NRAW, brow, k);+#if GR_DQ_PERCH+ const half2 scv = GR_WQ_SCALE2(scale, 0, GR_DQ_N, n0);+ const half2 zpv = GR_WQ_ZP2(zp, 0, GR_DQ_N, n0, lane);+#endif+ unroll_for (uint s_ = 0; s_ < GR_DQ_KCH / 32; s_++) {+#if !GR_DQ_PERCH+ const half2 scv = GR_WQ_SCALE2(scale, GR_WQ_G((k >> 5) + s_, GR_DQ_GS32), GR_DQ_N, n0);+ const half2 zpv = GR_WQ_ZP2(zp, GR_WQ_G((k >> 5) + s_, GR_DQ_GS32), GR_DQ_N, n0, lane);+#endif+ const uint16 b = GR_WQ_DEQ32(rw, s_ * GR_WQ_RAW_PER_K32, zpv, scv);+ // the B operand dwords are (k, k + 1) pairs in k order, i.e. already the row-major f16 layout+ vstore16(b, 0, (__global uint*)(out + (size_t)(n0 + lane) * GR_DQ_K + k + 32 * s_));+ }+}+#endif // GR_DEQUANT_WEIGHTS++#if GR_DEQUANT_INJECT+// Dequantizes the compressed write-gate weight W_inject [N = C, K = C*D] (4-bit / 8-bit, scale / zp [G, N]) into a+// row-major f16 scratch matrix with the arithmetic of the decompression graph: half(half(q - zp) * scale). W_inject has only C rows,+// so there is no 16-row tile to share a scale block read; one work-item converts one element.+// JIT: GR_DEQUANT_INJECT, GR_W_TYPE, GR_DQ_N (C), GR_DQ_K (C*D), GR_DQ_GS (group size along K). Dispatch: gws = [N * K], lws = [16].+#if GR_W_TYPE == GR_WT_F16+ #error "gr_common.cl: compressed weights only"+#endif++KERNEL(gr_dequant_inject)(const __global uchar* w, const __global ushort* scale, const __global uchar* zp, __global ushort* out) {+ const uint i = get_global_id(0);+ const uint n = i / GR_DQ_K;+ const uint k = i % GR_DQ_K;+ const uint zi = (k / GR_DQ_GS) * GR_DQ_N + n; // [G, N]+#if GR_W_TYPE == GR_WT_U4+ const uint q = GR_WQ_FLIP((w[i >> 1] >> ((i & 1) * 4)) & 0xF);+#else+ const uint q = GR_WQ_FLIP((uint)w[i]);+#endif+ const uint z = GR_WQ_ZPAT(zp, zi);+ // q - zp is exact in half; one RNE multiply by the scale, as in the decompression graph+ const half d = convert_half((int)q - (int)z);+ out[i] = as_ushort(d * as_half(scale[zi]));+}+#endif // GR_DEQUANT_INJECTdiff --git a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/gr_read.cl b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/gr_read.clnew file mode 100644index 00000000000..b402c8af1b8--- /dev/null+++ b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/gr_read.cl@@ -0,0 +1,273 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++// GatedResidual READ / MIX, fused scalar fallback (pre-Xe2 or shapes the systolic path rejects).+//+// Rbar = branch-wise RMSNorm(R) * gain -> t = SiLU(W_down Rbar / C) -> G = sigmoid(W_up t)+// mixed = (1/C) * sum_c G_c * Rbar_c, optionally S = 2 * sigmoid(W_inject Rbar / C)+//+// One work-group owns GR_READ_ROWS token rows; one subgroup is one hardware thread. Rbar and t live in SLM.+// JIT: GR_BRANCHES (4), GR_HIDDEN, GR_LOWRANK, GR_EPS, GR_PRODUCE_WRITE_GATE,+// GR_WG_SIZE (subgroups per work-group), GR_READ_ROWS, GR_NV_D / GR_NV_C / GR_NV_L (= chunk halves / 16 of the+// three K loops over D, C*D and L).+// Compressed weights (GR_W_TYPE != 0, see gr_common.cl: i4 / u4 / i8 / u8 rows [N, K] with f16 scale / zero point [G, N]) are+// dequantized per element in registers with the arithmetic of the decompression graph, half(half(q - zp) * scale), so the results+// are bit-identical to this kernel fed the decompressed f16 weights. JIT: GR_W_SIGNED, GR_HAS_ZP, GR_RD_GSD / GR_RD_GSU /+// GR_RD_GSI (group size along K of W_down / W_up / W_inject).+// Dispatch: gws = [WG * 16, ceil(rows / RB), 1], lws = [WG * 16, 1, 1].++#include "gr_common.cl"++#if GR_BRANCHES < 1 || GR_BRANCHES > 4+ #error "gr_read.cl: branch count must be in [1, 4]"+#endif+#if GR_PRODUCE_WRITE_GATE && GR_BRANCHES != 4+ #error "gr_read.cl: packed write-gate store expects 4 branches"+#endif+#if GR_HIDDEN % 16 != 0 || GR_LOWRANK % 16 != 0+ #error "gr_read.cl: hidden size and low rank must be multiples of 16"+#endif++#define GR_CD (GR_BRANCHES * GR_HIDDEN)+#define GR_NOUT (GR_LOWRANK + (GR_PRODUCE_WRITE_GATE ? GR_BRANCHES : 0))+#define GR_TSTRIDE ((GR_NOUT + 3) / 4 * 4)+#define GR_NJ 4+#define GR_KD (GR_NV_D * 16)+#define GR_KC (GR_NV_C * 16)+#define GR_KL (GR_NV_L * 16)+#define GR_NK (GR_LOWRANK / 16)+#define GR_INV_C (1.0f / (float)GR_BRANCHES)++#if GR_W_TYPE == GR_WT_F16+ #define GR_WPTR const __global ushort*+#else+ #define GR_WPTR const __global uchar*+ #define GR_ROW_BYTES(k) ((k) * GR_WQ_BITS / 8)+ #define GR_CD_RB GR_ROW_BYTES(GR_CD)+ #define GR_UP_RB GR_ROW_BYTES(GR_LOWRANK)+ // raw (unsigned domain) element e of a row, and its dequantized value as float; scale / zp are [G, N], n is the output channel+ #if GR_W_TYPE == GR_WT_U4+ #define GR_WQ_RAW(w, e) ((uint)(((w)[(e) >> 1] >> (((e) & 1) * 4)) & 0xF))+ #else+ #define GR_WQ_RAW(w, e) ((uint)(w)[e])+ #endif+ #define GR_WQ_ONE(w, scale, zp, N, GS, n, e) \+ convert_float(convert_half((int)GR_WQ_FLIP(GR_WQ_RAW(w, e)) - (int)GR_WQ_ZPAT(zp, (size_t)((e) / (GS)) * (N) + (n))) * \+ as_half((scale)[(size_t)((e) / (GS)) * (N) + (n)]))+ // 16 * nv elements starting at K index k, lane-interleaved like GR_LDF (element k + 16 * v + lane in component v)+ #define GR_LDWQ_1(w, sc, zp, N, GS, n, k) GR_WQ_ONE(w, sc, zp, N, GS, n, (k) + lane)+ #define GR_LDWQ_2(w, sc, zp, N, GS, n, k) ((float2)(GR_LDWQ_1(w, sc, zp, N, GS, n, k), GR_LDWQ_1(w, sc, zp, N, GS, n, (k) + 16)))+ #define GR_LDWQ_4(w, sc, zp, N, GS, n, k) ((float4)(GR_LDWQ_1(w, sc, zp, N, GS, n, k), GR_LDWQ_1(w, sc, zp, N, GS, n, (k) + 16), \+ GR_LDWQ_1(w, sc, zp, N, GS, n, (k) + 32), GR_LDWQ_1(w, sc, zp, N, GS, n, (k) + 48)))+ #define GR_LDWQ(nv, w, sc, zp, N, GS, n, k) CAT(GR_LDWQ_, nv)(w, sc, zp, N, GS, n, k)+#endif++#define GR_TH_1(r, kb) ((float)th[(r) * GR_NK + (kb)])+#define GR_TH_2(r, kb) ((float2)((float)th[(r) * GR_NK + (kb)], (float)th[(r) * GR_NK + (kb) + 1]))+#define GR_TH_4(r, kb) ((float4)((float)th[(r) * GR_NK + (kb)], (float)th[(r) * GR_NK + (kb) + 1], (float)th[(r) * GR_NK + (kb) + 2], (float)th[(r) * GR_NK + (kb) + 3]))+#define GR_TH(nv, r, kb) CAT(GR_TH_, nv)(r, kb)++REQD_SUB_GROUP_SIZE(16)+KERNEL(gr_read)(const __global ushort* residual,+ const __global ushort* norm_weight,+ GR_WPTR w_down,+ GR_WPTR w_up,+#if GR_W_TYPE != GR_WT_F16+ const __global ushort* scale_down,+ const __global ushort* scale_up,+ const __global uchar* zp_down,+ const __global uchar* zp_up,+#endif+#if GR_PRODUCE_WRITE_GATE+ GR_WPTR w_inject,+#if GR_W_TYPE != GR_WT_F16+ const __global ushort* scale_inject,+ const __global uchar* zp_inject,+#endif+#endif+ __global ushort* mixed,+#if GR_PRODUCE_WRITE_GATE+ __global ushort* write_gate,+#endif+ uint num_rows) {+ __local ushort slm_rbar[GR_READ_ROWS * GR_CD];+ __local float slm_t[GR_READ_ROWS * GR_TSTRIDE] __attribute__((aligned(16)));++ const uint row0 = get_group_id(1) * GR_READ_ROWS;+ if (row0 >= num_rows) {+ return;+ }+ const uint nrows = min((uint)GR_READ_ROWS, num_rows - row0);+ const uint sg = get_sub_group_id();+ const uint lane = get_sub_group_local_id();++ // Phase 1: Rbar = rms_norm(R_c) * gain into SLM, one subgroup per (row, branch).+ for (uint p = sg; p < GR_READ_ROWS * GR_BRANCHES; p += GR_WG_SIZE) {+ const uint r = p / GR_BRANCHES;+ const uint c = p % GR_BRANCHES;+ if (r >= nrows) {+ continue;+ }+ const size_t gbase = (size_t)(row0 + r) * GR_CD + c * GR_HIDDEN;+ const uint sbase = r * GR_CD + c * GR_HIDDEN;+ float sq = 0.0f;+ for (uint d = 0; d < GR_HIDDEN; d += GR_KD) {+ const GR_UT(GR_NV_D) xu = GR_BRU(GR_NV_D, residual + gbase + d);+ const GR_FT(GR_NV_D) f = GR_U2F(GR_NV_D, xu);+ const GR_FT(GR_NV_D) q = f * f;+ GR_ACC(GR_NV_D, sq, q);+ GR_SLMST(GR_NV_D, slm_rbar + sbase + d, xu, lane);+ }+ const float inv_rms = native_rsqrt(sub_group_reduce_add(sq) * (1.0f / (float)GR_HIDDEN) + GR_EPS);+ for (uint d = 0; d < GR_HIDDEN; d += GR_KD) {+ const GR_UT(GR_NV_D) xu = GR_SLMLD(GR_NV_D, slm_rbar + sbase + d, lane);+ const GR_UT(GR_NV_D) gu = GR_BRU(GR_NV_D, norm_weight + c * GR_HIDDEN + d);+ const GR_FT(GR_NV_D) f = GR_U2F(GR_NV_D, xu);+ const GR_FT(GR_NV_D) gain = GR_U2F(GR_NV_D, gu);+ const GR_FT(GR_NV_D) o = (f * inv_rms) * gain;+ const GR_UT(GR_NV_D) ou = GR_F2U(GR_NV_D, o);+ GR_SLMST(GR_NV_D, slm_rbar + sbase + d, ou, lane);+ }+ }+ barrier(CLK_LOCAL_MEM_FENCE);++ // Phase 2: low-rank down projection (+ write-gate rows), GR_NJ outputs x GR_READ_ROWS rows per pass.+ for (uint l0 = sg * GR_NJ; l0 < GR_NOUT; l0 += GR_WG_SIZE * GR_NJ) {+ float acc[GR_NJ * GR_READ_ROWS];+#pragma unroll+ for (uint i = 0; i < GR_NJ * GR_READ_ROWS; i++) {+ acc[i] = 0.0f;+ }+ for (uint k = 0; k < GR_CD; k += GR_KC) {+ GR_FT(GR_NV_C) rv[GR_READ_ROWS];+#pragma unroll+ for (uint r = 0; r < GR_READ_ROWS; r++) {+ rv[r] = GR_U2F(GR_NV_C, GR_SLMLD(GR_NV_C, slm_rbar + r * GR_CD + k, lane));+ }+#pragma unroll+ for (uint j = 0; j < GR_NJ; j++) {+ const uint l = min(l0 + j, (uint)(GR_NOUT - 1));+#if GR_W_TYPE == GR_WT_F16+#if GR_PRODUCE_WRITE_GATE+ const __global ushort* wp = l >= GR_LOWRANK ? w_inject + (size_t)(l - GR_LOWRANK) * GR_CD : w_down + (size_t)l * GR_CD;+#else+ const __global ushort* wp = w_down + (size_t)l * GR_CD;+#endif+ const GR_FT(GR_NV_C) wf = GR_LDF(GR_NV_C, wp + k);+#else+#if GR_PRODUCE_WRITE_GATE+ const bool gate_row = l >= GR_LOWRANK;+ GR_WPTR wp = gate_row ? w_inject + (size_t)(l - GR_LOWRANK) * GR_CD_RB : w_down + (size_t)l * GR_CD_RB;+ const __global ushort* wsc = gate_row ? scale_inject : scale_down;+ const __global uchar* wzp = gate_row ? zp_inject : zp_down;+ const uint wn = gate_row ? l - GR_LOWRANK : l;+ const uint wN = gate_row ? GR_BRANCHES : GR_LOWRANK;+ const uint wgs = gate_row ? GR_RD_GSI : GR_RD_GSD;+#else+ GR_WPTR wp = w_down + (size_t)l * GR_CD_RB;+ const __global ushort* wsc = scale_down;+ const __global uchar* wzp = zp_down;+ const uint wn = l;+ const uint wN = GR_LOWRANK;+ const uint wgs = GR_RD_GSD;+#endif+ const GR_FT(GR_NV_C) wf = GR_LDWQ(GR_NV_C, wp, wsc, wzp, wN, wgs, wn, k);+#endif+#pragma unroll+ for (uint r = 0; r < GR_READ_ROWS; r++) {+ GR_DOT(GR_NV_C, acc[j * GR_READ_ROWS + r], wf, rv[r]);+ }+ }+ }+#pragma unroll+ for (uint r = 0; r < GR_READ_ROWS; r++) {+ float4 logits;+ logits.s0 = sub_group_reduce_add(acc[0 * GR_READ_ROWS + r]) * GR_INV_C;+ logits.s1 = sub_group_reduce_add(acc[1 * GR_READ_ROWS + r]) * GR_INV_C;+ logits.s2 = sub_group_reduce_add(acc[2 * GR_READ_ROWS + r]) * GR_INV_C;+ logits.s3 = sub_group_reduce_add(acc[3 * GR_READ_ROWS + r]) * GR_INV_C;+ const float4 sig = GR_SIGMOID(logits);+ float4 act = logits * sig;+#if GR_PRODUCE_WRITE_GATE+ // The write gate lives in (0, 2); it must not be clamped to (0, 1).+ if (l0 >= GR_LOWRANK) {+ act = 2.0f * sig;+ }+#endif+ if (lane == 0) {+ vstore4(act, 0, slm_t + r * GR_TSTRIDE + l0);+ }+ }+ }+ barrier(CLK_LOCAL_MEM_FENCE);++#if GR_PRODUCE_WRITE_GATE+ if (sg < nrows && lane < GR_BRANCHES) {+ write_gate[(size_t)(row0 + sg) * GR_BRANCHES + lane] = as_ushort(convert_half_rte(slm_t[sg * GR_TSTRIDE + GR_LOWRANK + lane]));+ }+#endif++ // Phase 3: per-(branch, channel) sigmoid read gate and branch reduce mean. t is held as half in registers.+ half th[GR_READ_ROWS * GR_NK];+#pragma unroll+ for (uint r = 0; r < GR_READ_ROWS; r++) {+#pragma unroll+ for (uint kb = 0; kb < GR_NK; kb++) {+ th[r * GR_NK + kb] = convert_half_rte(slm_t[r * GR_TSTRIDE + kb * 16 + lane]);+ }+ }++ for (uint d0 = sg * 16; d0 < GR_HIDDEN; d0 += GR_WG_SIZE * 16) {+ float mix[GR_READ_ROWS];+#pragma unroll+ for (uint r = 0; r < GR_READ_ROWS; r++) {+ mix[r] = 0.0f;+ }+ for (uint c = 0; c < GR_BRANCHES; c++) {+ float logit[GR_READ_ROWS];+#pragma unroll+ for (uint j = 0; j < 16; j++) {+ float a[GR_READ_ROWS];+#pragma unroll+ for (uint r = 0; r < GR_READ_ROWS; r++) {+ a[r] = 0.0f;+ }+#if GR_W_TYPE == GR_WT_F16+ const __global ushort* wrow = w_up + (size_t)(c * GR_HIDDEN + d0 + j) * GR_LOWRANK;+#else+ GR_WPTR wrow = w_up + (size_t)(c * GR_HIDDEN + d0 + j) * GR_UP_RB;+#endif+#pragma unroll+ for (uint k = 0; k < GR_LOWRANK; k += GR_KL) {+#if GR_W_TYPE == GR_WT_F16+ const GR_FT(GR_NV_L) wf = GR_LDF(GR_NV_L, wrow + k);+#else+ const GR_FT(GR_NV_L) wf = GR_LDWQ(GR_NV_L, wrow, scale_up, zp_up, GR_CD, GR_RD_GSU, c * GR_HIDDEN + d0 + j, k);+#endif+#pragma unroll+ for (uint r = 0; r < GR_READ_ROWS; r++) {+ const GR_FT(GR_NV_L) tv = GR_TH(GR_NV_L, r, k / 16);+ GR_DOT(GR_NV_L, a[r], wf, tv);+ }+ }+#pragma unroll+ for (uint r = 0; r < GR_READ_ROWS; r++) {+ const float total = sub_group_reduce_add(a[r]);+ logit[r] = j == 0 ? (lane == 0 ? total : 0.0f) : (lane == j ? total : logit[r]);+ }+ }+#pragma unroll+ for (uint r = 0; r < GR_READ_ROWS; r++) {+ const float rbar = convert_float(as_half(slm_rbar[r * GR_CD + c * GR_HIDDEN + d0 + lane]));+ mix[r] += GR_SIGMOID(logit[r]) * rbar;+ }+ }+#pragma unroll+ for (uint r = 0; r < GR_READ_ROWS; r++) {+ if (r < nrows) {+ intel_sub_group_block_write_us(mixed + (size_t)(row0 + r) * GR_HIDDEN + d0, as_ushort(convert_half_rte(mix[r] * GR_INV_C)));+ }+ }+ }+}diff --git a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/gr_read_dpas.cl b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/gr_read_dpas.clnew file mode 100644index 00000000000..bbf26fec1ad--- /dev/null+++ b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/gr_read_dpas.cl@@ -0,0 +1,450 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++// GatedResidual READ / MIX as ONE systolic (dpas) kernel. One work-group owns GR_RD_TM token rows:+// phase 1 inv_rms[row, c] of the branch-wise RMSNorm -> SLM+// phase 2 t = SiLU(Rbar @ W_down^T / C) (+ write gate S as an extra tile) -> SLM (dpas A-operand slots)+// phase 3 mixed = (1/C) sum_c sigmoid(t @ W_up^T)[c] * Rbar[c] -> global+// Rbar is never materialized: phase 2 normalizes each residual A tile in f32 (inv_rms from SLM, then the gain) and rounds it+// once to half, as gr_rbar does; phase 3 recomputes Rbar in f32. The accumulator layout of a dpas (token i in+// component i, column n in lane n) is already the A-operand layout of the next one, so t only needs an SLM slot+// of 8 tokens x 16 low-rank values per (token tile, K16 block).+// The residual tiles come through 2D block reads (a whole TM x K32 A tile per message, rows past the end read 0); W rows+// are K-contiguous, so every lane reads its own row with one 64 B vload16.+//+// JIT: GR_BRANCHES, GR_HIDDEN (multiple of 32), GR_LOWRANK (multiple of 32), GR_EPS,+// GR_PRODUCE_WRITE_GATE, GR_WG_SIZE (subgroups), GR_RD_TM (8/16/32), GR_RD_NT, GR_NV_KD (phase 1 chunk halves / 16),+// GR_RD_SLM_GAIN (0 = gain from global, 1 = padded SLM copy, 2 = duplicated SLM copy), GR_P3_GB (optional: branches per+// phase-3 K loop).+// Compressed weights (GR_W_TYPE 4-bit group 32 / 8-bit per-channel, gr_common.cl; no write gate): GR_WD_KCH / GR_WD_NRAW / GR_WD_RB and+// GR_WU_KCH / GR_WU_NRAW / GR_WU_RB give the k values per raw load, its dwords and the row bytes of W_down / W_up.+// Dispatch: gws = [WG * 16, ceil(rows / TM), 1], lws = [WG * 16, 1, 1].++#include "gr_common.cl"++#define GR_CD (GR_BRANCHES * GR_HIDDEN)+#define GR_MT (GR_RD_TM / 8)+#define GR_KB (GR_LOWRANK / 16)+#define GR_TASKS (GR_KB / GR_RD_NT + (GR_PRODUCE_WRITE_GATE ? 1 : 0))+#define GR_KD (GR_NV_KD * 16)+#define GR_INV_C (1.0f / (float)GR_BRANCHES)++#if GR_HIDDEN % 32 != 0 || GR_LOWRANK % 32 != 0 || GR_KB % GR_RD_NT != 0+ #error "gr_read_dpas.cl: hidden size and low rank must be multiples of 32 and GR_RD_NT must divide L / 16"+#endif+#if GR_BRANCHES % 2 != 0 || GR_BRANCHES > 16+ #error "gr_read_dpas.cl: the write gate is one N16 tile stored in half pairs"+#endif+#if GR_W_TYPE != GR_WT_F16 && GR_PRODUCE_WRITE_GATE+ #error "gr_read_dpas.cl: compressed weights do not support the write gate"+#endif+#if GR_W_TYPE != GR_WT_F16 && (GR_HIDDEN % GR_WD_KCH != 0 || GR_LOWRANK % GR_WU_KCH != 0)+ #error "gr_read_dpas.cl: D and L must be multiples of the weight load widths"+#endif++// The gain of a K16 slice is one register half: A rows alternate between the low and high half of a GRF, and IGC realigns+// (mov + mul + mov) whenever the gain sits at the other offset. The gain is therefore staged in SLM so that every gain+// half is also read at the other offset: duplicated (GS = (g0, g0, g1, g1)) or behind a 16-half pad (GE = (g0, g1),+// GS = (g-1, g0, g1, g2)).+#if GR_RD_SLM_GAIN == 2+ #define GR_SLM_G_SIZE (2 * GR_CD)+ #define GR_P2_GAIN(GE, GS, KK) { GS = BLOCK_READN_SLM(ushort, 4, slm_g + 2 * (KK), 0); }+ #define GR_G0E(GE, GS) as_half((GS).s0)+ #define GR_G0O(GE, GS) as_half((GS).s1)+ #define GR_G1E(GE, GS) as_half((GS).s2)+ #define GR_G1O(GE, GS) as_half((GS).s3)+#elif GR_RD_SLM_GAIN+ #define GR_SLM_G_SIZE (GR_CD + 48)+ #define GR_P2_GAIN(GE, GS, KK) { GE = BLOCK_READN_SLM(ushort, 2, slm_g + 16 + (KK), 0); GS = BLOCK_READN_SLM(ushort, 4, slm_g + (KK), 0); }+ #define GR_G0E(GE, GS) as_half((GE).s0)+ #define GR_G0O(GE, GS) as_half((GS).s1)+ #define GR_G1E(GE, GS) as_half((GS).s2)+ #define GR_G1O(GE, GS) as_half((GE).s1)+#else+ #define GR_P2_GAIN(GE, GS, KK) { GE = intel_sub_group_block_read_us2(norm_weight + (KK)); }+ #define GR_G0E(GE, GS) as_half((GE).s0)+ #define GR_G0O(GE, GS) as_half((GE).s0)+ #define GR_G1E(GE, GS) as_half((GE).s1)+ #define GR_G1O(GE, GS) as_half((GE).s1)+#endif++// One K32 step of phase 2: loads of the A tile (raw residual), the gain and the W rows of every column tile ...+#if GR_W_TYPE == GR_WT_F16+#define GR_P2_LDB(dst, j, KK) dst = vload16(0, (const __global uint*)(brow[j] + (KK)))++#define GR_P2_LOAD(AT, GE, GS, B, KK) { GR_RD2D(GR_RD_TM, residual, GR_CD * 2, num_rows, GR_CD * 2, (KK), t0, AT); GR_P2_GAIN(GE, GS, KK); unroll_for (uint j_ = 0; j_ < GR_RD_NT; j_++) { GR_P2_LDB(B[j_], j_, KK); } }+#endif++// Rbar of 8 token rows (component i = token i, lane = k) in f32, rounded once: the gr_rbar formula, so the A operand stays+// finite whenever Rbar does (|R * inv_rms| <= sqrt(D), whereas R * gain alone can overflow half).+#define GR_P2_SCALE(v, inv, g) as_short8(convert_half8_rte((convert_float8(as_half8(v)) * (inv)) * (g)))++// ... and its dpas: A = Rbar of branch c (inv_rms of its rows in invv), two K16 slices, slice 0 first+#define GR_P2_MMA(AT, GE, GS, B) \+ { \+ const float g0_ = convert_float(GR_G0E(GE, GS)); \+ const float g1_ = convert_float(GR_G1E(GE, GS)); \+ unroll_for (uint m_ = 0; m_ < GR_MT; m_++) { \+ const short8 av_ = GR_P2_SCALE(vload8(m_, (AT)), invv[m_], g0_); \+ unroll_for (uint j_ = 0; j_ < GR_RD_NT; j_++) { \+ acc[j_ * GR_MT + m_] = GR_MAD(av_, as_int8((B)[j_].lo), acc[j_ * GR_MT + m_]); \+ } \+ } \+ unroll_for (uint m_ = 0; m_ < GR_MT; m_++) { \+ const short8 av_ = GR_P2_SCALE(vload8(GR_MT + m_, (AT)), invv[m_], g1_); \+ unroll_for (uint j_ = 0; j_ < GR_RD_NT; j_++) { \+ acc[j_ * GR_MT + m_] = GR_MAD(av_, as_int8((B)[j_].hi), acc[j_ * GR_MT + m_]); \+ } \+ } \+ }++REQD_SUB_GROUP_SIZE(16)+KERNEL(gr_read_dpas)(const __global ushort* residual,+ const __global ushort* norm_weight,+#if GR_W_TYPE == GR_WT_F16+ const __global ushort* w_down,+ const __global ushort* w_up,+#else+ const __global uchar* w_down,+ const __global uchar* w_up,+ const __global ushort* scale_down,+ const __global ushort* scale_up,+ const __global uchar* zp_down,+ const __global uchar* zp_up,+#endif+#if GR_PRODUCE_WRITE_GATE+ const __global ushort* w_inject,+#endif+ __global ushort* mixed,+#if GR_PRODUCE_WRITE_GATE+ __global ushort* write_gate,+#endif+ uint num_rows) {+ __local float slm_inv[GR_BRANCHES * GR_RD_TM] __attribute__((aligned(32)));+ __local ushort slm_t[GR_MT * GR_KB * 128] __attribute__((aligned(16)));+#if GR_RD_SLM_GAIN+ __local ushort slm_g[GR_SLM_G_SIZE] __attribute__((aligned(64)));+#endif++ const uint lane = get_sub_group_local_id();+ const uint sg = get_sub_group_id();+ const uint t0 = get_group_id(1) * GR_RD_TM;+ if (t0 >= num_rows) {+ return;+ }++#if GR_RD_SLM_GAIN+ {+ // All chunk loads are issued before the SLM stores so the copy costs one load latency.+#if GR_CD % 128 == 0+ #define GR_GNV 8+#else+ #define GR_GNV 2+#endif+#define GR_GIT ((GR_CD + GR_WG_SIZE * GR_GNV * 16 - 1) / (GR_WG_SIZE * GR_GNV * 16))+ GR_UT(GR_GNV) gv[GR_GIT];+#pragma unroll+ for (uint it = 0; it < GR_GIT; it++) {+ gv[it] = GR_BRU(GR_GNV, norm_weight + min((it * GR_WG_SIZE + sg) * GR_GNV * 16, (uint)(GR_CD - GR_GNV * 16)));+ }+#pragma unroll+ for (uint it = 0; it < GR_GIT; it++) {+ const uint i = (it * GR_WG_SIZE + sg) * GR_GNV * 16;+ if (i < GR_CD) {+ const GR_UT(GR_GNV) g = gv[it];+#if GR_RD_SLM_GAIN == 2+ ushort gq[GR_GNV];+ CAT(vstore, GR_GNV)(g, 0, gq);+#pragma unroll+ for (uint q = 0; q < GR_GNV; q++) {+ GR_BLOCK_WRITEN_SLM(ushort, 2, slm_g + 2 * (i + 16 * q), 0, (ushort2)(gq[q], gq[q]));+ }+#else+ GR_BLOCK_WRITEN_SLM(ushort, GR_GNV, slm_g + 16 + i, 0, g);+#endif+ }+ }+ }+#endif++ // Phase 1: inv_rms[c][row] for 4 rows per task. Rows past num_rows re-read the last row and get 0.+ for (uint p = sg; p < GR_BRANCHES * (GR_RD_TM / 4); p += GR_WG_SIZE) {+ const uint c = p / (GR_RD_TM / 4);+ const uint r0 = (p % (GR_RD_TM / 4)) * 4;+ size_t off[4];+ float sq[4];+#pragma unroll+ for (uint r = 0; r < 4; r++) {+ off[r] = (size_t)min(t0 + r0 + r, num_rows - 1) * GR_CD + c * GR_HIDDEN;+ sq[r] = 0.0f;+ }+ // The next chunk of the 4 rows is in flight while the current one is reduced (the last step re-reads the last chunk).+ GR_UT(GR_NV_KD) x[4];+#pragma unroll+ for (uint r = 0; r < 4; r++) {+ x[r] = GR_BRU(GR_NV_KD, residual + off[r]);+ }+ for (uint d = 0; d < GR_HIDDEN; d += GR_KD) {+ const uint dn = min(d + GR_KD, (uint)(GR_HIDDEN - GR_KD));+ GR_UT(GR_NV_KD) xn[4];+#pragma unroll+ for (uint r = 0; r < 4; r++) {+ xn[r] = GR_BRU(GR_NV_KD, residual + off[r] + dn);+ }+#pragma unroll+ for (uint r = 0; r < 4; r++) {+ const GR_FT(GR_NV_KD) f = GR_U2F(GR_NV_KD, x[r]);+ const GR_FT(GR_NV_KD) q = f * f;+ GR_ACC(GR_NV_KD, sq[r], q);+ x[r] = xn[r];+ }+ }+ float4 inv;+ inv.s0 = t0 + r0 + 0 < num_rows ? native_rsqrt(sub_group_reduce_add(sq[0]) * (1.0f / (float)GR_HIDDEN) + GR_EPS) : 0.0f;+ inv.s1 = t0 + r0 + 1 < num_rows ? native_rsqrt(sub_group_reduce_add(sq[1]) * (1.0f / (float)GR_HIDDEN) + GR_EPS) : 0.0f;+ inv.s2 = t0 + r0 + 2 < num_rows ? native_rsqrt(sub_group_reduce_add(sq[2]) * (1.0f / (float)GR_HIDDEN) + GR_EPS) : 0.0f;+ inv.s3 = t0 + r0 + 3 < num_rows ? native_rsqrt(sub_group_reduce_add(sq[3]) * (1.0f / (float)GR_HIDDEN) + GR_EPS) : 0.0f;+ if (lane == 0) {+ vstore4(inv, 0, slm_inv + c * GR_RD_TM + r0);+ }+ }+ barrier(CLK_LOCAL_MEM_FENCE);++ // Phase 2: down projection, GR_RD_NT low-rank tiles (or the write-gate tile) per task.+ // acc += half((R[:, c] * inv_rms[:, c]) * gain[c]) @ W[:, c]^T per branch c+ for (uint task = sg; task < GR_TASKS; task += GR_WG_SIZE) {+#if GR_PRODUCE_WRITE_GATE+ const bool is_wgate = task == GR_TASKS - 1;+ const __global ushort* w = is_wgate ? w_inject : w_down;+ const uint n0 = is_wgate ? 0 : task * GR_RD_NT * 16;+#else+#if GR_W_TYPE == GR_WT_F16+ const __global ushort* w = w_down;+#endif+ const uint n0 = task * GR_RD_NT * 16;+#endif+#if GR_W_TYPE == GR_WT_F16+ const __global ushort* brow[GR_RD_NT];+#else+ const __global uchar* brow[GR_RD_NT];+#endif+#pragma unroll+ for (uint j = 0; j < GR_RD_NT; j++) {+#if GR_PRODUCE_WRITE_GATE+ const uint row = is_wgate ? min(lane, (uint)(GR_BRANCHES - 1)) : n0 + 16 * j + lane;+#else+ const uint row = n0 + 16 * j + lane;+#endif+#if GR_W_TYPE == GR_WT_F16+ brow[j] = w + (size_t)row * GR_CD;+#else+ brow[j] = w_down + (size_t)row * GR_WD_RB;+#endif+ }+#if GR_W_TYPE != GR_WT_F16 && GR_WD_PERCH+ // one group: one scale / zp per output channel for the whole K+ half2 scv[GR_RD_NT];+ half2 zpv[GR_RD_NT];+ unroll_for (uint j_ = 0; j_ < GR_RD_NT; j_++) {+ scv[j_] = GR_WQ_SCALE2(scale_down, 0, GR_LOWRANK, n0 + 16 * j_);+ zpv[j_] = GR_WQ_ZP2(zp_down, 0, GR_LOWRANK, n0 + 16 * j_, lane);+ }+#endif++ float8 acc[GR_RD_NT * GR_MT];+#pragma unroll+ for (uint i = 0; i < GR_RD_NT * GR_MT; i++) {+ acc[i] = (float8)(0.0f);+ }+ for (uint c = 0; c < GR_BRANCHES; c++) {+ float8 invv[GR_MT];+#pragma unroll+ for (uint m = 0; m < GR_MT; m++) {+ invv[m] = vload8(0, slm_inv + c * GR_RD_TM + m * 8);+ }+ const uint kbeg = c * GR_HIDDEN;+ const uint kend = kbeg + GR_HIDDEN;+ ushort at0[2 * GR_RD_TM];+ ushort2 ge0;+ ushort4 gs0;+ uint16 b0[GR_RD_NT];+#if GR_W_TYPE == GR_WT_F16+ for (uint k = kbeg; k < kend; k += 32) {+ GR_P2_LOAD(at0, ge0, gs0, b0, k);+ GR_P2_MMA(at0, ge0, gs0, b0);+ }+#else+ for (uint k = kbeg; k < kend; k += GR_WD_KCH) {+ uint rw[GR_RD_NT][GR_WD_NRAW];+ unroll_for (uint j_ = 0; j_ < GR_RD_NT; j_++) {+ GR_WQ_LOAD_RAW(rw[j_], GR_WD_NRAW, brow[j_], k);+ }+ unroll_for (uint s_ = 0; s_ < GR_WD_KCH / 32; s_++) {+ GR_RD2D(GR_RD_TM, residual, GR_CD * 2, num_rows, GR_CD * 2, k + 32 * s_, t0, at0);+ GR_P2_GAIN(ge0, gs0, k + 32 * s_);+ unroll_for (uint j_ = 0; j_ < GR_RD_NT; j_++) {+#if GR_WD_PERCH+ b0[j_] = GR_WQ_DEQ32(rw[j_], s_ * GR_WQ_RAW_PER_K32, zpv[j_], scv[j_]);+#else+ const half2 scv = GR_WQ_SCALE2(scale_down, GR_WQ_G((k >> 5) + s_, GR_WD_GS32), GR_LOWRANK, n0 + 16 * j_);+ const half2 zpv = GR_WQ_ZP2(zp_down, GR_WQ_G((k >> 5) + s_, GR_WD_GS32), GR_LOWRANK, n0 + 16 * j_, lane);+ b0[j_] = GR_WQ_DEQ32(rw[j_], s_ * GR_WQ_RAW_PER_K32, zpv, scv);+#endif+ }+ GR_P2_MMA(at0, ge0, gs0, b0);+ }+ }+#endif+ }++ const float inv_c = GR_INV_C;+#if GR_PRODUCE_WRITE_GATE+ if (is_wgate) {+ if (lane < GR_BRANCHES) {+#pragma unroll+ for (uint m = 0; m < GR_MT; m++) {+ // Write-gate range is (0, 2) - it must not be clamped to (0, 1).+ const float8 s = 2.0f * GR_SIGMOID(acc[m] * inv_c);+ float tmp[8];+ vstore8(s, 0, tmp);+#pragma unroll+ for (uint i = 0; i < 8; i++) {+ const uint tok = t0 + m * 8 + i;+ if (tok < num_rows) {+ write_gate[(size_t)tok * GR_BRANCHES + lane] = as_ushort(convert_half_rte(tmp[i]));+ }+ }+ }+ }+ continue;+ }+#endif+#pragma unroll+ for (uint j = 0; j < GR_RD_NT; j++) {+#pragma unroll+ for (uint m = 0; m < GR_MT; m++) {+ const float8 x = acc[j * GR_MT + m] * inv_c;+ const ushort8 tu = as_ushort8(convert_half8_rte(x * GR_SIGMOID(x)));+ GR_BLOCK_WRITEN_SLM(ushort, 8, slm_t + (m * GR_KB + n0 / 16 + j) * 128, 0, tu);+ }+ }+ }+ barrier(CLK_LOCAL_MEM_FENCE);++ // Phase 3: up projection + sigmoid read gate + branch mix, 16 channels per pass. Up to 4 branches run in one K loop so+ // each SLM read of t feeds several dpas; the mix still adds the branches in order 0..C-1.+#ifndef GR_P3_GB+#define GR_P3_GB (GR_BRANCHES % 4 == 0 ? 4 : 2)+#endif+ for (uint dt = sg; dt < GR_HIDDEN / 16; dt += GR_WG_SIZE) {+ const uint d0 = dt * 16;+ float8 mix[GR_MT];+#pragma unroll+ for (uint m = 0; m < GR_MT; m++) {+ mix[m] = (float8)(0.0f);+ }+ for (uint cg = 0; cg < GR_BRANCHES; cg += GR_P3_GB) {+ float8 acc[GR_P3_GB * GR_MT];+#pragma unroll+ for (uint i = 0; i < GR_P3_GB * GR_MT; i++) {+ acc[i] = (float8)(0.0f);+ }+#if GR_W_TYPE == GR_WT_F16+ const __global ushort* wrow[GR_P3_GB];+#pragma unroll+ for (uint g = 0; g < GR_P3_GB; g++) {+ wrow[g] = w_up + (size_t)((cg + g) * GR_HIDDEN + d0 + lane) * GR_LOWRANK;+ }+ for (uint kb = 0; kb < GR_KB; kb += 2) {+ uint16 b[GR_P3_GB];+#pragma unroll+ for (uint g = 0; g < GR_P3_GB; g++) {+ b[g] = vload16(0, (const __global uint*)(wrow[g] + kb * 16));+ }+#pragma unroll+ for (uint m = 0; m < GR_MT; m++) {+ const short8 a0 = as_short8(BLOCK_READN_SLM(ushort, 8, slm_t + (m * GR_KB + kb) * 128, 0));+ const short8 a1 = as_short8(BLOCK_READN_SLM(ushort, 8, slm_t + (m * GR_KB + kb + 1) * 128, 0));+#pragma unroll+ for (uint g = 0; g < GR_P3_GB; g++) {+ acc[g * GR_MT + m] = GR_MAD(a0, as_int8(b[g].lo), acc[g * GR_MT + m]);+ acc[g * GR_MT + m] = GR_MAD(a1, as_int8(b[g].hi), acc[g * GR_MT + m]);+ }+ }+ }+#else+ const __global uchar* wrow[GR_P3_GB];+#pragma unroll+ for (uint g = 0; g < GR_P3_GB; g++) {+ wrow[g] = w_up + (size_t)((cg + g) * GR_HIDDEN + d0 + lane) * GR_WU_RB;+ }+#if GR_WU_PERCH+ half2 scv[GR_P3_GB];+ half2 zpv[GR_P3_GB];+ unroll_for (uint g_ = 0; g_ < GR_P3_GB; g_++) {+ scv[g_] = GR_WQ_SCALE2(scale_up, 0, GR_CD, (cg + g_) * GR_HIDDEN + d0);+ zpv[g_] = GR_WQ_ZP2(zp_up, 0, GR_CD, (cg + g_) * GR_HIDDEN + d0, lane);+ }+#endif+ for (uint kb = 0; kb < GR_KB; kb += GR_WU_KCH / 16) {+ uint rw[GR_P3_GB][GR_WU_NRAW];+ unroll_for (uint g_ = 0; g_ < GR_P3_GB; g_++) {+ GR_WQ_LOAD_RAW(rw[g_], GR_WU_NRAW, wrow[g_], kb * 16);+ }+ unroll_for (uint s_ = 0; s_ < GR_WU_KCH / 32; s_++) {+ uint16 b[GR_P3_GB];+ unroll_for (uint g_ = 0; g_ < GR_P3_GB; g_++) {+#if GR_WU_PERCH+ b[g_] = GR_WQ_DEQ32(rw[g_], s_ * GR_WQ_RAW_PER_K32, zpv[g_], scv[g_]);+#else+ const half2 scv = GR_WQ_SCALE2(scale_up, GR_WQ_G((kb >> 1) + s_, GR_WU_GS32), GR_CD, (cg + g_) * GR_HIDDEN + d0);+ const half2 zpv = GR_WQ_ZP2(zp_up, GR_WQ_G((kb >> 1) + s_, GR_WU_GS32), GR_CD, (cg + g_) * GR_HIDDEN + d0, lane);+ b[g_] = GR_WQ_DEQ32(rw[g_], s_ * GR_WQ_RAW_PER_K32, zpv, scv);+#endif+ }+#pragma unroll+ for (uint m = 0; m < GR_MT; m++) {+ const short8 a0 = as_short8(BLOCK_READN_SLM(ushort, 8, slm_t + (m * GR_KB + kb + 2 * s_) * 128, 0));+ const short8 a1 = as_short8(BLOCK_READN_SLM(ushort, 8, slm_t + (m * GR_KB + kb + 2 * s_ + 1) * 128, 0));+#pragma unroll+ for (uint g = 0; g < GR_P3_GB; g++) {+ acc[g * GR_MT + m] = GR_MAD(a0, as_int8(b[g].lo), acc[g * GR_MT + m]);+ acc[g * GR_MT + m] = GR_MAD(a1, as_int8(b[g].hi), acc[g * GR_MT + m]);+ }+ }+ }+ }+#endif+#pragma unroll+ for (uint g = 0; g < GR_P3_GB; g++) {+ const uint c = cg + g;+ ushort rt[GR_MT][8];+#pragma unroll+ for (uint m = 0; m < GR_MT; m++) {+ GR_RD2D1(8, residual, GR_CD * 2, num_rows, GR_CD * 2, c * GR_HIDDEN + d0, t0 + m * 8, rt[m]);+ }+ const float gain = convert_float(as_half(intel_sub_group_block_read_us(norm_weight + c * GR_HIDDEN + d0)));+#pragma unroll+ for (uint m = 0; m < GR_MT; m++) {+ const float8 invv = vload8(0, slm_inv + c * GR_RD_TM + m * 8);+ const float8 rbar = (convert_float8(as_half8(vload8(0, rt[m]))) * gain) * invv;+ mix[m] += GR_SIGMOID(acc[g * GR_MT + m]) * rbar;+ }+ }+ }+#pragma unroll+ for (uint m = 0; m < GR_MT; m++) {+ const ushort8 ou = as_ushort8(convert_half8_rte(mix[m] * GR_INV_C));+ ushort tmp[8];+ vstore8(ou, 0, tmp);+#pragma unroll+ for (uint i = 0; i < 8; i++) {+ const uint tok = t0 + m * 8 + i;+ if (tok < num_rows) {+ intel_sub_group_block_write_us(mixed + (size_t)tok * GR_HIDDEN + d0, tmp[i]);+ }+ }+ }+ }+}diff --git a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/gr_read_pipeline.cl b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/gr_read_pipeline.clnew file mode 100644index 00000000000..df8fcca8aac--- /dev/null+++ b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/gr_read_pipeline.cl@@ -0,0 +1,1277 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++// GatedResidual READ / MIX as a systolic (dpas) pipeline of three dispatches sharing this template:+// GR_PIPELINE_STAGE == 0 RBAR branch-wise grouped RMSNorm -> Rbar scratch (global memory)+// GR_PIPELINE_STAGE == 1 DOWN_PROJ T = SiLU((Rbar . W_down^T) / C) (+ write gate S as one extra column tile)+// GR_PIPELINE_STAGE == 2 UP_PROJ mixed = (1/C) * sum_c sigmoid(T . W_up^T)[c] * Rbar[c]+//+// One subgroup is one hardware thread. dpas operands (SIMD16, M = 8 tokens, N = 16, K = 16):+// A (short8) a[i] = A[token i][k = lane] -> a whole TM x K32 tile per 2D block read (rows past the end read 0)+// B (int8) b[j] = pack(B[2j][n = lane], B[2j+1][n = lane]); W rows are K-contiguous, so every lane reads its own+// row of W with one 64 B vload16 (K32) - no transposed load needed+// C (float8) c[i] = C[token i][n = lane]+// The accumulator layout of one GEMM is the A layout of the next one. The loads of the next K32 step are issued before the+// dpas of the current one (two register buffers).+//+// Compressed weights (GR_W_TYPE = 4-bit group 32 / 8-bit per-channel, see gr_common.cl): the lane loads GR_W*_KCH k values of its row as raw+// bytes per step and unpacks one K32 slice at a time into the same uint16 B operand; MMA and epilogues are shared.+// The per-subgroup (decode) DOWN / UP kernels fold the zero point and scale out of the B operand: u8 per channel into the+// epilogue (GR_WQ_FOLD), u4 per K32 group into the accumulator update (B = half(1024 + q), no per-weight arithmetic). The+// others (GR_Q_SHARE) dequantize each K32 slice once per work-group into SLM. RBAR is the same for every weight type.+//+// Common JIT: GR_BRANCHES, GR_HIDDEN, GR_W_TYPE (default f16). Dispatch: see the per-stage comments.++#include "gr_common.cl"++#define GR_CD (GR_BRANCHES * GR_HIDDEN)+#define GR_INV_C (1.0f / (float)GR_BRANCHES)+// Per-subgroup compressed kernels: the u8 ones also issue the activation tiles of the next weight chunk together with it; u4+// loads them per K32 slice, which is as fast.+#define GR_APF GR_WQ_FOLD++#if GR_PIPELINE_STAGE == 0+// ---------------------------------------------------------------------------------------------------------------+// RBAR. JIT: GR_EPS, GR_CH (halves per chunk), GR_NV_CH (= GR_CH / 16), GR_NCH (= D / GR_CH),+// GR_RB_S (subgroups per branch row, divides GR_NCH), GR_GPF (gain chunks loaded before the norm+// reduction; bounded by the register budget).+// GR_RB_S subgroups per (branch, row): gws = [C * GR_RB_S * 16, rows, 1], lws = [C * GR_RB_S * 16, 1, 1].+// GR_KPERM: Rbar is stored K-permuted for the 4-bit decode GEMMs (see GR_KP).+// ---------------------------------------------------------------------------------------------------------------+#if GR_KPERM+#if GR_NV_CH != 8+ #error "gr_read_pipeline.cl: the K-permuted RBAR needs 128-half chunks"+#endif+// lane l owns the halves 8 l .. 8 l + 7 of a chunk (not 16 v + l), so the K permutation (GR_KP) is a register swizzle+#define GR_RB_LDU(P) as_ushort8(vload4(get_sub_group_local_id(), (const __global uint*)(P)))+#define GR_RB_ST(P, O) vstore4(as_uint4(GR_F2U(8, O).s04152637), get_sub_group_local_id(), (__global uint*)(P))+#else+#define GR_RB_LDU(P) GR_BRU(GR_NV_CH, P)+#define GR_RB_ST(P, O) GR_STF(GR_NV_CH, P, O)+#endif+#define GR_RB_LDF(P) GR_U2F(GR_NV_CH, GR_RB_LDU(P))+REQD_SUB_GROUP_SIZE(16)+KERNEL(gr_rbar)(const __global ushort* residual, const __global ushort* norm_weight, __global ushort* rbar_out, uint num_rows) {+ const uint sg = get_sub_group_id();+ const uint c = sg / GR_RB_S;+ const uint row = get_group_id(1);+ if (c >= GR_BRANCHES || row >= num_rows) {+ return;+ }+#define GR_NCHP (GR_NCH / GR_RB_S) // chunks of one subgroup+ const uint d_begin = (sg % GR_RB_S) * GR_NCHP * GR_CH;+ const size_t base = (size_t)row * GR_CD + c * GR_HIDDEN + d_begin;+ const uint gbase = c * GR_HIDDEN + d_begin;++#if GR_HIDDEN <= 4096+ // The subgroup's part of the branch row stays in registers: one read, normalized in place.+ GR_UT(GR_NV_CH) r[GR_NCHP];+ float sq = 0.0f;+#pragma unroll+ for (uint i = 0; i < GR_NCHP; i++) {+ r[i] = GR_RB_LDU(residual + base + i * GR_CH);+ const GR_FT(GR_NV_CH) f = GR_U2F(GR_NV_CH, r[i]);+ const GR_FT(GR_NV_CH) q = f * f;+ GR_ACC(GR_NV_CH, sq, q);+ }+ // The gain does not depend on the norm: the first GR_GPF chunks are loaded before the reduction to hide its latency.+#if GR_GPF > 0+ GR_UT(GR_NV_CH) gr_[GR_GPF];+#pragma unroll+ for (uint i = 0; i < GR_GPF; i++) {+ gr_[i] = GR_RB_LDU(norm_weight + gbase + i * GR_CH);+ }+#endif+#if GR_RB_S > 1+ __local float sq_part[GR_BRANCHES * GR_RB_S];+ sq = sub_group_reduce_add(sq);+ if (get_sub_group_local_id() == 0) {+ sq_part[sg] = sq;+ }+ barrier(CLK_LOCAL_MEM_FENCE);+ sq = 0.0f;+ unroll_for (uint p = 0; p < GR_RB_S; p++) {+ sq += sq_part[c * GR_RB_S + p];+ }+#else+ sq = sub_group_reduce_add(sq);+#endif+ const float inv_rms = native_rsqrt(sq * (1.0f / (float)GR_HIDDEN) + GR_EPS);+#pragma unroll+ for (uint i = 0; i < GR_NCHP; i++) {+#if GR_GPF > 0+ const GR_FT(GR_NV_CH) gain = i < GR_GPF ? GR_U2F(GR_NV_CH, gr_[i]) : GR_RB_LDF(norm_weight + gbase + i * GR_CH);+#else+ const GR_FT(GR_NV_CH) gain = GR_RB_LDF(norm_weight + gbase + i * GR_CH);+#endif+ const GR_FT(GR_NV_CH) f = GR_U2F(GR_NV_CH, r[i]);+ const GR_FT(GR_NV_CH) o = (f * inv_rms) * gain;+ GR_RB_ST(rbar_out + base + i * GR_CH, o);+ }+#else+ // Wide branches: two passes over the subgroup's part of the row, the second one re-reads it from cache.+ float sq = 0.0f;+ for (uint d = 0; d < GR_NCHP * GR_CH; d += GR_CH) {+ const GR_FT(GR_NV_CH) f = GR_RB_LDF(residual + base + d);+ const GR_FT(GR_NV_CH) q = f * f;+ GR_ACC(GR_NV_CH, sq, q);+ }+#if GR_RB_S > 1+ __local float sq_part[GR_BRANCHES * GR_RB_S];+ sq = sub_group_reduce_add(sq);+ if (get_sub_group_local_id() == 0) {+ sq_part[sg] = sq;+ }+ barrier(CLK_LOCAL_MEM_FENCE);+ sq = 0.0f;+ unroll_for (uint p = 0; p < GR_RB_S; p++) {+ sq += sq_part[c * GR_RB_S + p];+ }+#else+ sq = sub_group_reduce_add(sq);+#endif+ const float inv_rms = native_rsqrt(sq * (1.0f / (float)GR_HIDDEN) + GR_EPS);+ for (uint d = 0; d < GR_NCHP * GR_CH; d += GR_CH) {+ const GR_FT(GR_NV_CH) f = GR_RB_LDF(residual + base + d);+ const GR_FT(GR_NV_CH) gain = GR_RB_LDF(norm_weight + gbase + d);+ const GR_FT(GR_NV_CH) o = (f * inv_rms) * gain;+ GR_RB_ST(rbar_out + base + d, o);+ }+#endif+}++#elif GR_PIPELINE_STAGE == 1+#if GR_Q_SHARE+// ---------------------------------------------------------------------------------------------------------------+// DOWN_PROJ with a work-group shared dequantization. One work-group = GR_Q_ST token subgroups x GR_DOWN_KSPLIT K subgroups on+// one 32-column tile. Every iteration each subgroup dequantizes ONE K32 slice of its K range for both column tiles into SLM+// (f16, already in the lane = n B-operand layout), then all GR_Q_ST token subgroups run their dpas on all slices: the+// dequantization is paid once per work-group instead of once per token tile.+// JIT: GR_LOWRANK, GR_DOWN_TM (32), GR_DOWN_TN (32), GR_DOWN_KSPLIT, GR_Q_ST.+// gws = [NX * GR_Q_ST * KSPLIT * 16, ceil(ceil(tokens / TM) / GR_Q_ST), 1], lws = [GR_Q_ST * KSPLIT * 16, 1, 1], NX = L / TN.+// ---------------------------------------------------------------------------------------------------------------+#define GR_MT (GR_DOWN_TM / 8)+#define GR_NT (GR_DOWN_TN / 16)+#define GR_KPT (GR_CD / GR_DOWN_KSPLIT)+#define GR_NSL (GR_KPT / 32)+#define GR_ITERS ((GR_NSL + GR_Q_ST - 1) / GR_Q_ST)+#define GR_KREG (GR_Q_ST * GR_NT * 256)+#define GR_BUF_U (GR_DOWN_KSPLIT * GR_KREG)+#define GR_RED_U (GR_Q_ST * GR_DOWN_KSPLIT * GR_NT * GR_MT * 128)+#define GR_SLM_U (2 * GR_BUF_U > GR_RED_U ? 2 * GR_BUF_U : GR_RED_U)++#if GR_CD % 32 != 0 || GR_LOWRANK % 32 != 0 || GR_KPT % 32 != 0+ #error "gr_read_pipeline.cl: C*D, L and the per-subgroup K range must be multiples of 32"+#endif+#if GR_PRODUCE_WRITE_GATE+ #error "gr_read_pipeline.cl: compressed weights do not support the write gate"+#endif++#define GR_DNS_MMA(AT, BLO, BHI) \+ { \+ unroll_for (uint m_ = 0; m_ < GR_MT; m_++) { \+ const short8 av_ = as_short8(vload8(m_, (AT))); \+ unroll_for (uint j_ = 0; j_ < GR_NT; j_++) { \+ acc[j_ * GR_MT + m_] = GR_MAD(av_, as_int8((BLO)[j_]), acc[j_ * GR_MT + m_]); \+ } \+ } \+ unroll_for (uint m_ = 0; m_ < GR_MT; m_++) { \+ const short8 av_ = as_short8(vload8(GR_MT + m_, (AT))); \+ unroll_for (uint j_ = 0; j_ < GR_NT; j_++) { \+ acc[j_ * GR_MT + m_] = GR_MAD(av_, as_int8((BHI)[j_]), acc[j_ * GR_MT + m_]); \+ } \+ } \+ }++REQD_SUB_GROUP_SIZE(16)+KERNEL(gr_down_proj_dpas)(const __global ushort* rbar,+ const __global uchar* w_down,+ const __global ushort* w_scale,+ const __global uchar* w_zp,+ __global ushort* t_out,+ uint num_tokens) {+ __local uint slm[GR_SLM_U] __attribute__((aligned(64)));+ const uint lane = get_sub_group_local_id();+ const uint sg = get_sub_group_id();+ const uint tk = sg % GR_Q_ST;+ const uint kid = sg / GR_Q_ST;+ const uint jt = get_group_id(0);+ if (jt >= GR_LOWRANK / GR_DOWN_TN) {+ return;+ }+ const uint t0 = (get_group_id(1) * GR_Q_ST + tk) * GR_DOWN_TM;+ const uint n0 = jt * GR_DOWN_TN;++ const __global uchar* brow[GR_NT];+#pragma unroll+ for (uint j = 0; j < GR_NT; j++) {+ brow[j] = w_down + (size_t)(n0 + 16 * j + lane) * GR_WD_RB;+ }+ float8 acc[GR_NT * GR_MT];+#pragma unroll+ for (uint i = 0; i < GR_NT * GR_MT; i++) {+ acc[i] = (float8)(0.0f);+ }+#if GR_WD_PERCH+ half2 scv[GR_NT];+ half2 zpv[GR_NT];+ unroll_for (uint j_ = 0; j_ < GR_NT; j_++) {+ scv[j_] = GR_WQ_SCALE2(w_scale, 0, GR_LOWRANK, n0 + 16 * j_);+ zpv[j_] = GR_WQ_ZP2(w_zp, 0, GR_LOWRANK, n0 + 16 * j_, lane);+ }+#endif++ const uint k_begin = kid * GR_KPT;+ ushort at0[2 * GR_DOWN_TM];+ for (uint it = 0; it < GR_ITERS; it++) {+ __local uint* sb = slm + (it & 1) * GR_BUF_U + kid * GR_KREG;+ const uint sl = it * GR_Q_ST + tk;+ if (sl < GR_NSL) {+ const uint k = k_begin + sl * 32;+ unroll_for (uint j_ = 0; j_ < GR_NT; j_++) {+ uint rw[GR_WQ_RAW_PER_K32];+ GR_WQ_LOAD_RAW(rw, GR_WQ_RAW_PER_K32, brow[j_], k);+#if GR_WD_PERCH+ const uint16 b = GR_WQ_DEQ32(rw, 0, zpv[j_], scv[j_]);+#else+ const half2 scv = GR_WQ_SCALE2(w_scale, GR_WQ_G(k >> 5, GR_WD_GS32), GR_LOWRANK, n0 + 16 * j_);+ const half2 zpv = GR_WQ_ZP2(w_zp, GR_WQ_G(k >> 5, GR_WD_GS32), GR_LOWRANK, n0 + 16 * j_, lane);+ const uint16 b = GR_WQ_DEQ32(rw, 0, zpv, scv);+#endif+ GR_BLOCK_WRITEN_SLM(uint, 8, sb + (tk * GR_NT + j_) * 256, 0, b.lo);+ GR_BLOCK_WRITEN_SLM(uint, 8, sb + (tk * GR_NT + j_) * 256 + 128, 0, b.hi);+ }+ }+ barrier(CLK_LOCAL_MEM_FENCE);+ const uint nsl = min((uint)GR_Q_ST, (uint)(GR_NSL - it * GR_Q_ST));+ unroll_for (uint s_ = 0; s_ < GR_Q_ST; s_++) {+ if (s_ < nsl) {+ GR_RD2D(GR_DOWN_TM, rbar, GR_CD * 2, num_tokens, GR_CD * 2, k_begin + (it * GR_Q_ST + s_) * 32, t0, at0);+ uint8 blo[GR_NT];+ uint8 bhi[GR_NT];+ unroll_for (uint j_ = 0; j_ < GR_NT; j_++) {+ blo[j_] = BLOCK_READN_SLM(uint, 8, (const __local uint*)(sb + (s_ * GR_NT + j_) * 256), 0);+ bhi[j_] = BLOCK_READN_SLM(uint, 8, (const __local uint*)(sb + (s_ * GR_NT + j_) * 256 + 128), 0);+ }+ GR_DNS_MMA(at0, blo, bhi);+ }+ }+ }++#if GR_DOWN_KSPLIT > 1+ barrier(CLK_LOCAL_MEM_FENCE);+ __local float* red = (__local float*)slm;+#pragma unroll+ for (uint i = 0; i < GR_NT * GR_MT; i++) {+ FUNC_CALL(gr_st8)(red + ((tk * GR_DOWN_KSPLIT + kid) * GR_NT * GR_MT + i) * 128, acc[i]);+ }+ barrier(CLK_LOCAL_MEM_FENCE);+ if (kid != 0) {+ return;+ }+ for (uint s = 1; s < GR_DOWN_KSPLIT; s++) {+#pragma unroll+ for (uint i = 0; i < GR_NT * GR_MT; i++) {+ acc[i] += FUNC_CALL(gr_ld8)(red + ((tk * GR_DOWN_KSPLIT + s) * GR_NT * GR_MT + i) * 128);+ }+ }+#endif++ const float inv_c = GR_INV_C;+#pragma unroll+ for (uint m = 0; m < GR_MT; m++) {+#pragma unroll+ for (uint j = 0; j < GR_NT; j++) {+ const float8 x = acc[j * GR_MT + m] * inv_c;+ const float8 t = x * GR_SIGMOID(x);+ const ushort8 tu = as_ushort8(convert_half8_rte(t));+ ushort tmp[8];+ vstore8(tu, 0, tmp);+ // rows past num_tokens are dropped by the 2D store+ intel_sub_group_2d_block_write_16b_8r16x1c((__global void*)t_out, GR_LOWRANK * 2, num_tokens, GR_LOWRANK * 2, (int2)(n0 + 16 * j, t0 + m * 8), tmp);+ }+ }+}++#else // GR_Q_SHARE == 0: every subgroup loads (and dequantizes) its own weights (few token tiles)+// ---------------------------------------------------------------------------------------------------------------+// DOWN_PROJ. JIT: GR_LOWRANK, GR_DOWN_TM (tokens per subgroup), GR_DOWN_TN (32), GR_DOWN_KSPLIT, GR_PRODUCE_WRITE_GATE.+// KSPLIT == 1: gws = [NX * 16, NY, 1], lws = [16, 1, 1]; KSPLIT > 1: gws = [NX * KSPLIT * 16, NY, 1], lws = [KSPLIT * 16, 1, 1]+// with NX = L / TN + write-gate tile, NY = ceil(tokens / TM). KSPLIT subgroups split the K reduction through SLM.+// ---------------------------------------------------------------------------------------------------------------+#define GR_MT (GR_DOWN_TM / 8)+#define GR_NT (GR_DOWN_TN / 16)+#define GR_KPT (GR_CD / GR_DOWN_KSPLIT)+#define GR_NACC ((GR_NT + GR_WQ_FOLD) * GR_MT) // + the row sums of the folded u8 zero point++#if GR_CD % 32 != 0 || GR_LOWRANK % 32 != 0 || GR_KPT % 32 != 0+ #error "gr_read_pipeline.cl: C*D, L and the per-subgroup K range must be multiples of 32"+#endif+#if GR_W_TYPE != GR_WT_F16 && (GR_KPT % GR_WD_KCH != 0)+ #error "gr_read_pipeline.cl: the per-subgroup K range must be a multiple of the weight load width"+#endif++#define GR_DN_LDA(AT, KK) GR_RD2D(GR_DOWN_TM, rbar, GR_CD * 2, num_tokens, GR_CD * 2, (KK), t0, AT)++#if GR_W_TYPE != GR_WT_F16 && !GR_WQ_FOLD+// Group of K32 slice s: W_inject has its own group size (GR_WI_GS32) in the write-gate tile+#if GR_PRODUCE_WRITE_GATE+#define GR_DN_GRP(s) (is_wgate ? GR_WQ_G(s, GR_WI_GS32) : GR_WQ_G(s, GR_WD_GS32))+#else+#define GR_DN_GRP(s) GR_WQ_G(s, GR_WD_GS32)+#endif+// scale / zp of the groups of the chunk at KK (one entry per K32 slice); W_inject's [G, C] rows are too short for block reads+#define GR_DN_LDSZ(SC, ZP, KK) \+ unroll_for (uint j_ = 0; j_ < GR_NT; j_++) { \+ unroll_for (uint s_ = 0; s_ < GR_WD_KCH / 32; s_++) { \+ const uint i_ = GR_DN_GRP(((KK) >> 5) + s_) * qn + nrow[j_]; \+ SC[j_][s_] = qs[i_]; \+ ZP[j_][s_] = GR_HAS_ZP ? qz[GR_WQ_BITS == 4 ? (i_ >> 1) : i_] : 0; \+ } \+ }+#endif++#if GR_W_TYPE == GR_WT_F16+#define GR_DN_LDB(dst, j, KK) dst = vload16(0, (const __global uint*)(brow[j] + (KK)))++#define GR_DN_LOAD(AT, B, KK) { GR_DN_LDA(AT, KK); unroll_for (uint j_ = 0; j_ < GR_NT; j_++) { GR_DN_LDB(B[j_], j_, KK); } }+#endif++#define GR_DN_MMA_TO(ACC, AT, B) \+ { \+ unroll_for (uint m_ = 0; m_ < GR_MT; m_++) { \+ const short8 av_ = as_short8(vload8(m_, (AT))); \+ unroll_for (uint j_ = 0; j_ < GR_NT; j_++) { \+ (ACC)[j_ * GR_MT + m_] = GR_MAD(av_, as_int8((B)[j_].lo), (ACC)[j_ * GR_MT + m_]); \+ } \+ } \+ unroll_for (uint m_ = 0; m_ < GR_MT; m_++) { \+ const short8 av_ = as_short8(vload8(GR_MT + m_, (AT))); \+ unroll_for (uint j_ = 0; j_ < GR_NT; j_++) { \+ (ACC)[j_ * GR_MT + m_] = GR_MAD(av_, as_int8((B)[j_].hi), (ACC)[j_ * GR_MT + m_]); \+ } \+ } \+ }+#define GR_DN_MMA(AT, B) GR_DN_MMA_TO(acc, AT, B)++#if GR_W_TYPE != GR_WT_F16+// token row sums of the A tile: RS[m] = A[m-th 8 tokens][K32 slice] . 1+#define GR_DN_RS_TO(RS, AT) \+ { \+ unroll_for (uint m_ = 0; m_ < GR_MT; m_++) { \+ (RS)[m_] = GR_MAD(as_short8(vload8(m_, (AT))), wq_ones, (RS)[m_]); \+ (RS)[m_] = GR_MAD(as_short8(vload8(GR_MT + m_, (AT))), wq_ones, (RS)[m_]); \+ } \+ }+#endif+#if GR_WQ_FOLD+#define GR_DN_RS(AT) GR_DN_RS_TO(acc + GR_NT * GR_MT, AT)+#endif++REQD_SUB_GROUP_SIZE(16)+KERNEL(gr_down_proj_dpas)(const __global ushort* rbar,+#if !GR_GATE_ONLY+#if GR_W_TYPE == GR_WT_F16+ const __global ushort* w_down,+#else+ const __global uchar* w_down,+ const __global ushort* w_scale,+ const __global uchar* w_zp,+#endif+#endif+#if GR_PRODUCE_WRITE_GATE+#if GR_W_TYPE == GR_WT_F16+ const __global ushort* w_inject,+#else+ const __global uchar* w_inject,+ const __global ushort* s_inject,+ const __global uchar* z_inject,+#endif+#endif+#if !GR_GATE_ONLY+ __global ushort* t_out,+#endif+#if GR_PRODUCE_WRITE_GATE+ __global ushort* write_gate_out,+#endif+ uint num_tokens) {+#if GR_DOWN_KSPLIT > 1+ __local float slm[GR_DOWN_KSPLIT * GR_NACC * 128] __attribute__((aligned(64)));+#endif+ const uint lane = get_sub_group_local_id();+ const uint kid = get_sub_group_id();+ const uint jt = get_group_id(0);+ const uint t0 = get_group_id(1) * GR_DOWN_TM;+ if (t0 >= num_tokens) {+ return;+ }+#if GR_GATE_ONLY+ // only the write-gate column tile: S = 2 * sigmoid(Rbar . W_inject^T / C)+ if (jt != 0) {+ return;+ }+ const bool is_wgate = true;+ const uint n0 = 0;+#elif GR_PRODUCE_WRITE_GATE+ if (jt > GR_LOWRANK / GR_DOWN_TN) {+ return;+ }+ const bool is_wgate = jt == GR_LOWRANK / GR_DOWN_TN;+ const uint n0 = is_wgate ? 0 : jt * GR_DOWN_TN;+#else+ if (jt >= GR_LOWRANK / GR_DOWN_TN) {+ return;+ }+ const bool is_wgate = false;+ const uint n0 = jt * GR_DOWN_TN;+#endif++ // B: lane n owns row (n0 + 16 * j + n) of W; the write-gate tile has only C rows, the rest repeat the last one.+ uint nrow[GR_NT];+#pragma unroll+ for (uint j = 0; j < GR_NT; j++) {+ nrow[j] = is_wgate ? min(lane, (uint)(GR_BRANCHES - 1)) : n0 + 16 * j + lane;+ }+#if GR_W_TYPE == GR_WT_F16+#if GR_GATE_ONLY+ const __global ushort* w = w_inject;+#elif GR_PRODUCE_WRITE_GATE+ const __global ushort* w = is_wgate ? w_inject : w_down;+#else+ const __global ushort* w = w_down;+#endif+ const __global ushort* brow[GR_NT];+#pragma unroll+ for (uint j = 0; j < GR_NT; j++) {+ brow[j] = w + (size_t)nrow[j] * GR_CD;+ }+#else+ // W_down has [G, L] scale / zp, W_inject [G, C]: the row stride qn of the scale / zp table differs+#if GR_GATE_ONLY+ const __global uchar* qw = w_inject;+ const __global ushort* qs = s_inject;+ const __global uchar* qz = z_inject;+ const uint qn = GR_BRANCHES;+#elif GR_PRODUCE_WRITE_GATE+ const __global uchar* qw = is_wgate ? w_inject : w_down;+ const __global ushort* qs = is_wgate ? s_inject : w_scale;+ const __global uchar* qz = is_wgate ? z_inject : w_zp;+ const uint qn = is_wgate ? GR_BRANCHES : GR_LOWRANK;+#else+ const __global uchar* qw = w_down;+ const __global ushort* qs = w_scale;+ const __global uchar* qz = w_zp;+ const uint qn = GR_LOWRANK;+#endif+ const __global uchar* brow[GR_NT];+#pragma unroll+ for (uint j = 0; j < GR_NT; j++) {+ brow[j] = qw + (size_t)nrow[j] * GR_WD_RB;+ }+#endif++ float8 acc[GR_NACC];+#pragma unroll+ for (uint i = 0; i < GR_NACC; i++) {+ acc[i] = (float8)(0.0f);+ }+#if GR_W_TYPE != GR_WT_F16+ // a per-lane value (not a uniform constant), so the 8 registers of the row-sum operand stay live instead of being rebuilt per slice+ const int8 wq_ones = as_int8((uint8)(GR_WQ_ONES_U | ((num_tokens + lane) >> 31)));+#endif++ const uint k_begin = kid * GR_KPT;+ const uint k_end = k_begin + GR_KPT;+#if GR_W_TYPE == GR_WT_F16+ ushort at0[2 * GR_DOWN_TM];+#endif+ uint16 b0[GR_NT];+#if GR_W_TYPE != GR_WT_F16+ // the first weight chunk and its activation tiles are in flight before the loop+ uint rw[GR_NT][GR_WD_NRAW];+ unroll_for (uint j_ = 0; j_ < GR_NT; j_++) {+ GR_WQ_LOAD_RAW(rw[j_], GR_WD_NRAW, brow[j_], k_begin);+ }+#if GR_APF+ ushort atc[GR_WD_KCH / 32][2 * GR_DOWN_TM];+ unroll_for (uint s_ = 0; s_ < GR_WD_KCH / 32; s_++) {+ GR_DN_LDA(atc[s_], k_begin + 32 * s_);+ }+#endif+#if GR_W_TYPE != GR_WT_F16 && !GR_WQ_FOLD+ ushort scr[GR_NT][GR_WD_KCH / 32];+ uchar zpr[GR_NT][GR_WD_KCH / 32];+ GR_DN_LDSZ(scr, zpr, k_begin);+ uint zsh[GR_NT];+ unroll_for (uint j_ = 0; j_ < GR_NT; j_++) {+ zsh[j_] = GR_WQ_BITS == 4 ? (nrow[j_] & 1) * 4 : 0; // qn is even, so the nibble of (g * qn + row) only depends on the row+ }+ // A . (bias + q) and the A row sums of the current group; scale / zp are applied once per group+#if GR_PRODUCE_WRITE_GATE+ const uint gs32 = is_wgate ? GR_WI_GS32 : GR_WD_GS32;+#else+ const uint gs32 = GR_WD_GS32;+#endif+ float8 tq[GR_NT * GR_MT];+ float8 rs[GR_MT];+ unroll_for (uint i_ = 0; i_ < GR_NT * GR_MT; i_++) {+ tq[i_] = (float8)(0.0f);+ }+ unroll_for (uint m_ = 0; m_ < GR_MT; m_++) {+ rs[m_] = (float8)(0.0f);+ }+#elif GR_W_TYPE != GR_WT_F16+ float sf[GR_NT];+ float zf[GR_NT];+ unroll_for (uint j_ = 0; j_ < GR_NT; j_++) {+ sf[j_] = convert_float(as_half(qs[nrow[j_]]));+ zf[j_] = convert_float(GR_WQ_ZPAT(qz, nrow[j_]));+ }+#endif+#endif++#if GR_W_TYPE == GR_WT_F16+ for (uint k = k_begin; k < k_end; k += 32) {+ GR_DN_LOAD(at0, b0, k);+ GR_DN_MMA(at0, b0);+ }+#else+ // The raw bytes (u4 scale / zp) and activation tiles of the next chunk are in flight while the current one is unpacked+ // and consumed (the last step re-reads the last chunk); a single chunk covering the K range is all in flight before the loop.+ for (uint k = k_begin; k < k_end; k += GR_WD_KCH) {+#if GR_WD_KCH < GR_KPT+ uint rwn[GR_NT][GR_WD_NRAW];+ const uint kn = min(k + GR_WD_KCH, k_end - GR_WD_KCH);+ unroll_for (uint j_ = 0; j_ < GR_NT; j_++) {+ GR_WQ_LOAD_RAW(rwn[j_], GR_WD_NRAW, brow[j_], kn);+ }+#if GR_W_TYPE != GR_WT_F16 && !GR_WQ_FOLD+ ushort scn[GR_NT][GR_WD_KCH / 32];+ uchar zpn[GR_NT][GR_WD_KCH / 32];+ GR_DN_LDSZ(scn, zpn, kn);+#endif+#if GR_APF+ ushort atn[GR_WD_KCH / 32][2 * GR_DOWN_TM];+ unroll_for (uint s_ = 0; s_ < GR_WD_KCH / 32; s_++) {+ GR_DN_LDA(atn[s_], kn + 32 * s_);+ }+#endif+#endif+ unroll_for (uint s_ = 0; s_ < GR_WD_KCH / 32; s_++) {+#if GR_APF+ const ushort* at0 = atc[s_];+#else+ ushort at0[2 * GR_DOWN_TM];+ GR_DN_LDA(at0, k + 32 * s_);+#endif+ unroll_for (uint j_ = 0; j_ < GR_NT; j_++) {+#if GR_WQ_FOLD+ b0[j_] = GR_WQ_U8B32(rw[j_], s_ * GR_WQ_RAW_PER_K32);+#elif GR_KPERM+ b0[j_] = GR_WQ_U4P32(rw[j_], s_ * GR_WQ_RAW_PER_K32);+#else+ b0[j_] = GR_WQ_GB32(rw[j_], s_ * GR_WQ_RAW_PER_K32);+#endif+ }+#if GR_WQ_FOLD+ GR_DN_MMA(at0, b0);+ GR_DN_RS(at0);+#else+ // acc += scale * (A . (bias + q) - (bias + zp) * rowsum(A)) per quantization group, no per-weight arithmetic+ GR_DN_MMA_TO(tq, at0, b0);+ GR_DN_RS_TO(rs, at0);+ const uint sl_ = (k >> 5) + s_;+ if ((sl_ + 1) % gs32 == 0 || sl_ + 1 == (k_end >> 5)) {+ unroll_for (uint j_ = 0; j_ < GR_NT; j_++) {+ const float sc = convert_float(as_half(scr[j_][s_]));+ const float zz = GR_WQ_BIAS + (float)GR_WQ_ZPLD(zpr[j_][s_], zsh[j_]);+ unroll_for (uint m_ = 0; m_ < GR_MT; m_++) {+ acc[j_ * GR_MT + m_] = fma((float8)(sc), fma((float8)(-zz), rs[m_], tq[j_ * GR_MT + m_]), acc[j_ * GR_MT + m_]);+ tq[j_ * GR_MT + m_] = (float8)(0.0f);+ }+ }+ unroll_for (uint m_ = 0; m_ < GR_MT; m_++) {+ rs[m_] = (float8)(0.0f);+ }+ }+#endif+ }+#if GR_WD_KCH < GR_KPT+#if GR_APF+ unroll_for (uint s_ = 0; s_ < GR_WD_KCH / 32; s_++) {+ unroll_for (uint i_ = 0; i_ < 2 * GR_DOWN_TM; i_++) {+ atc[s_][i_] = atn[s_][i_];+ }+ }+#endif+ unroll_for (uint j_ = 0; j_ < GR_NT; j_++) {+ unroll_for (uint i_ = 0; i_ < GR_WD_NRAW; i_++) {+ rw[j_][i_] = rwn[j_][i_];+ }+#if GR_W_TYPE != GR_WT_F16 && !GR_WQ_FOLD+ unroll_for (uint s_ = 0; s_ < GR_WD_KCH / 32; s_++) {+ scr[j_][s_] = scn[j_][s_];+ zpr[j_][s_] = zpn[j_][s_];+ }+#endif+ }+#endif+ }+#endif++#if GR_DOWN_KSPLIT > 1+#pragma unroll+ for (uint i = 0; i < GR_NACC; i++) {+ FUNC_CALL(gr_st8)(slm + (kid * GR_NACC + i) * 128, acc[i]);+ }+ barrier(CLK_LOCAL_MEM_FENCE);+ // subgroup i sums accumulator i over the K split (in K order, as one subgroup would) into the slot of split 0+ for (uint i = kid; i < GR_NACC; i += GR_DOWN_KSPLIT) {+ float8 s = FUNC_CALL(gr_ld8)(slm + i * 128);+ unroll_for (uint p = 1; p < GR_DOWN_KSPLIT; p++) {+ s += FUNC_CALL(gr_ld8)(slm + (p * GR_NACC + i) * 128);+ }+ FUNC_CALL(gr_st8)(slm + i * 128, s);+ }+ barrier(CLK_LOCAL_MEM_FENCE);+ if (kid != 0) {+ return;+ }+#pragma unroll+ for (uint i = 0; i < GR_NACC; i++) {+ acc[i] = FUNC_CALL(gr_ld8)(slm + i * 128);+ }+#endif+#if GR_WQ_FOLD+#pragma unroll+ for (uint m = 0; m < GR_MT; m++) {+#pragma unroll+ for (uint j = 0; j < GR_NT; j++) {+ acc[j * GR_MT + m] = (acc[j * GR_MT + m] - zf[j] * acc[GR_NT * GR_MT + m]) * sf[j];+ }+ }+#endif++ const float inv_c = GR_INV_C;+#if GR_PRODUCE_WRITE_GATE+ if (is_wgate) {+ if (lane < GR_BRANCHES) {+#pragma unroll+ for (uint m = 0; m < GR_MT; m++) {+ const float8 x = acc[m] * inv_c;+ const float8 s = 2.0f * GR_SIGMOID(x);+ float tmp[8];+ vstore8(s, 0, tmp);+#pragma unroll+ for (uint i = 0; i < 8; i++) {+ const uint tok = t0 + m * 8 + i;+ if (tok < num_tokens) {+ write_gate_out[(size_t)tok * GR_BRANCHES + lane] = as_ushort(convert_half_rte(tmp[i]));+ }+ }+ }+ }+ return;+ }+#endif+#if !GR_GATE_ONLY+#pragma unroll+ for (uint m = 0; m < GR_MT; m++) {+#pragma unroll+ for (uint j = 0; j < GR_NT; j++) {+ const float8 x = acc[j * GR_MT + m] * inv_c;+#if GR_KPERM+ // T is stored K-permuted for the 4-bit decode UP_PROJ+ const float8 xs = intel_sub_group_shuffle(x, GR_KP(lane));+ const float8 t = xs * GR_SIGMOID(xs);+#else+ const float8 t = x * GR_SIGMOID(x);+#endif+ const ushort8 tu = as_ushort8(convert_half8_rte(t));+ ushort tmp[8];+ vstore8(tu, 0, tmp);+ // T is an internal buffer (64 B aligned): rows past num_tokens are dropped by the 2D store.+ intel_sub_group_2d_block_write_16b_8r16x1c((__global void*)t_out, GR_LOWRANK * 2, num_tokens, GR_LOWRANK * 2, (int2)(n0 + 16 * j, t0 + m * 8), tmp);+ }+ }+#endif+}++#endif // GR_Q_SHARE++#elif GR_PIPELINE_STAGE == 2+#if GR_Q_SHARE+// ---------------------------------------------------------------------------------------------------------------+// UP_PROJ with a work-group shared dequantization (see DOWN_PROJ): GR_Q_ST token subgroups on one 16-channel tile of all+// branches; every iteration each subgroup dequantizes one K32 slice of all GR_BRANCHES weight tiles into SLM. No split-K.+// JIT: GR_LOWRANK, GR_UP_TM, GR_UP_KSPLIT (1), GR_Q_ST.+// gws = [(D / 16) * GR_Q_ST * 16, ceil(ceil(tokens / TM) / GR_Q_ST), 1], lws = [GR_Q_ST * 16, 1, 1].+// ---------------------------------------------------------------------------------------------------------------+#define GR_MT (GR_UP_TM / 8)+#define GR_NSL (GR_LOWRANK / 32)+#define GR_ITERS ((GR_NSL + GR_Q_ST - 1) / GR_Q_ST)+#define GR_BUF_U (GR_Q_ST * GR_BRANCHES * 256)++#if GR_CD % 32 != 0 || GR_LOWRANK % 32 != 0 || GR_HIDDEN % 16 != 0 || GR_UP_KSPLIT != 1+ #error "gr_read_pipeline.cl: C*D and L must be multiples of 32, D of 16, and the shared UP_PROJ has no split-K"+#endif++#define GR_UPS_MMA(AT, BLO, BHI) \+ { \+ unroll_for (uint m_ = 0; m_ < GR_MT; m_++) { \+ const short8 av_ = as_short8(vload8(m_, (AT))); \+ unroll_for (uint c_ = 0; c_ < GR_BRANCHES; c_++) { \+ acc[c_ * GR_MT + m_] = GR_MAD(av_, as_int8((BLO)[c_]), acc[c_ * GR_MT + m_]); \+ } \+ } \+ unroll_for (uint m_ = 0; m_ < GR_MT; m_++) { \+ const short8 av_ = as_short8(vload8(GR_MT + m_, (AT))); \+ unroll_for (uint c_ = 0; c_ < GR_BRANCHES; c_++) { \+ acc[c_ * GR_MT + m_] = GR_MAD(av_, as_int8((BHI)[c_]), acc[c_ * GR_MT + m_]); \+ } \+ } \+ }++REQD_SUB_GROUP_SIZE(16)+KERNEL(gr_up_proj_dpas)(const __global ushort* t_in,+ const __global uchar* w_up,+ const __global ushort* w_scale,+ const __global uchar* w_zp,+ const __global ushort* rbar,+ __global ushort* mixed,+ uint num_tokens) {+ __local uint slm[2 * GR_BUF_U] __attribute__((aligned(64)));+ const uint lane = get_sub_group_local_id();+ const uint tk = get_sub_group_id();+ const uint d0 = get_group_id(0) * 16;+ if (d0 >= GR_HIDDEN) {+ return;+ }+ const uint t0 = (get_group_id(1) * GR_Q_ST + tk) * GR_UP_TM;++ const __global uchar* brow[GR_BRANCHES];+#pragma unroll+ for (uint c = 0; c < GR_BRANCHES; c++) {+ brow[c] = w_up + (size_t)(c * GR_HIDDEN + d0 + lane) * GR_WU_RB;+ }+ float8 acc[GR_BRANCHES * GR_MT];+#pragma unroll+ for (uint i = 0; i < GR_BRANCHES * GR_MT; i++) {+ acc[i] = (float8)(0.0f);+ }+#if GR_WU_PERCH+ half2 scv[GR_BRANCHES];+ half2 zpv[GR_BRANCHES];+ unroll_for (uint c_ = 0; c_ < GR_BRANCHES; c_++) {+ scv[c_] = GR_WQ_SCALE2(w_scale, 0, GR_CD, c_ * GR_HIDDEN + d0);+ zpv[c_] = GR_WQ_ZP2(w_zp, 0, GR_CD, c_ * GR_HIDDEN + d0, lane);+ }+#endif++ ushort at0[2 * GR_UP_TM];+ for (uint it = 0; it < GR_ITERS; it++) {+ __local uint* sb = slm + (it & 1) * GR_BUF_U;+ const uint sl = it * GR_Q_ST + tk;+ if (sl < GR_NSL) {+ const uint k = sl * 32;+ unroll_for (uint c_ = 0; c_ < GR_BRANCHES; c_++) {+ uint rw[GR_WQ_RAW_PER_K32];+ GR_WQ_LOAD_RAW(rw, GR_WQ_RAW_PER_K32, brow[c_], k);+#if GR_WU_PERCH+ const uint16 b = GR_WQ_DEQ32(rw, 0, zpv[c_], scv[c_]);+#else+ const half2 scv = GR_WQ_SCALE2(w_scale, GR_WQ_G(sl, GR_WU_GS32), GR_CD, c_ * GR_HIDDEN + d0);+ const half2 zpv = GR_WQ_ZP2(w_zp, GR_WQ_G(sl, GR_WU_GS32), GR_CD, c_ * GR_HIDDEN + d0, lane);+ const uint16 b = GR_WQ_DEQ32(rw, 0, zpv, scv);+#endif+ GR_BLOCK_WRITEN_SLM(uint, 8, sb + (tk * GR_BRANCHES + c_) * 256, 0, b.lo);+ GR_BLOCK_WRITEN_SLM(uint, 8, sb + (tk * GR_BRANCHES + c_) * 256 + 128, 0, b.hi);+ }+ }+ barrier(CLK_LOCAL_MEM_FENCE);+ const uint nsl = min((uint)GR_Q_ST, (uint)(GR_NSL - it * GR_Q_ST));+ unroll_for (uint s_ = 0; s_ < GR_Q_ST; s_++) {+ if (s_ < nsl) {+ GR_RD2D(GR_UP_TM, t_in, GR_LOWRANK * 2, num_tokens, GR_LOWRANK * 2, (it * GR_Q_ST + s_) * 32, t0, at0);+ uint8 blo[GR_BRANCHES];+ uint8 bhi[GR_BRANCHES];+ unroll_for (uint c_ = 0; c_ < GR_BRANCHES; c_++) {+ blo[c_] = BLOCK_READN_SLM(uint, 8, (const __local uint*)(sb + (s_ * GR_BRANCHES + c_) * 256), 0);+ bhi[c_] = BLOCK_READN_SLM(uint, 8, (const __local uint*)(sb + (s_ * GR_BRANCHES + c_) * 256 + 128), 0);+ }+ GR_UPS_MMA(at0, blo, bhi);+ }+ }+ }++ ushort rt[GR_BRANCHES][GR_MT][8];+#pragma unroll+ for (uint c = 0; c < GR_BRANCHES; c++) {+#pragma unroll+ for (uint m = 0; m < GR_MT; m++) {+ GR_RD2D1(8, rbar, GR_CD * 2, num_tokens, GR_CD * 2, c * GR_HIDDEN + d0, t0 + m * 8, rt[c][m]);+ }+ }+ float8 mix[GR_MT];+#pragma unroll+ for (uint m = 0; m < GR_MT; m++) {+ mix[m] = (float8)(0.0f);+ }+#pragma unroll+ for (uint c = 0; c < GR_BRANCHES; c++) {+#pragma unroll+ for (uint m = 0; m < GR_MT; m++) {+ mix[m] += GR_SIGMOID(acc[c * GR_MT + m]) * convert_float8(as_half8(vload8(0, rt[c][m])));+ }+ }+#pragma unroll+ for (uint m = 0; m < GR_MT; m++) {+ const ushort8 ou = as_ushort8(convert_half8_rte(mix[m] * GR_INV_C));+ ushort tmp[8];+ vstore8(ou, 0, tmp);+#pragma unroll+ for (uint i = 0; i < 8; i++) {+ const uint tok = t0 + m * 8 + i;+ if (tok < num_tokens) {+ intel_sub_group_block_write_us(mixed + (size_t)tok * GR_HIDDEN + d0, tmp[i]);+ }+ }+ }+}++#else // GR_Q_SHARE == 0+#if GR_UP_BSPLIT+// ---------------------------------------------------------------------------------------------------------------+// UP_PROJ of the 4-bit decode GEMMs (GR_KPERM): one subgroup per branch of a 16-channel tile walks the whole low rank (lane =+// W_up row); the C read-gated branch partials of the mix meet in SLM. JIT: GR_LOWRANK, GR_UP_TM, GR_WU_*.+// gws = [(D / 16) * C * 16, ceil(tokens / TM), 1], lws = [C * 16, 1, 1]+// ---------------------------------------------------------------------------------------------------------------+#define GR_MT (GR_UP_TM / 8)+#if GR_W_TYPE != GR_WT_U4 || !GR_KPERM || GR_LOWRANK % GR_WU_KCH != 0+ #error "gr_read_pipeline.cl: the branch-split UP_PROJ is the 4-bit decode kernel"+#endif+// scale / (bias + zp) of the groups of the chunk at KK (one entry per K32 slice) for the subgroup's branch+#define GR_UPB_LDSZ(SC, ZZ, KK) \+ unroll_for (uint s_ = 0; s_ < GR_WU_KCH / 32; s_++) { \+ const uint zb_ = GR_WQ_G(((KK) >> 5) + s_, GR_WU_GS32) * GR_CD + cb * GR_HIDDEN + d0; \+ SC[s_] = convert_float(as_half(intel_sub_group_block_read_us(w_scale + zb_))); \+ ZZ[s_] = GR_WQ_BIAS + (float)GR_WQ_ZPAT(w_zp, zb_ + lane); \+ }++REQD_SUB_GROUP_SIZE(16)+KERNEL(gr_up_proj_dpas)(const __global ushort* t_in,+ const __global uchar* w_up,+ const __global ushort* w_scale,+ const __global uchar* w_zp,+ const __global ushort* rbar,+ __global ushort* mixed,+ uint num_tokens) {+ __local float slm[GR_BRANCHES * GR_MT * 128] __attribute__((aligned(64)));+ const uint lane = get_sub_group_local_id();+ const uint cb = get_sub_group_id();+ const uint d0 = get_group_id(0) * 16;+ const uint t0 = get_group_id(1) * GR_UP_TM;+ if (d0 >= GR_HIDDEN || t0 >= num_tokens) {+ return;+ }+ const __global uchar* brow = w_up + (size_t)(cb * GR_HIDDEN + d0 + lane) * GR_WU_RB;+ const int8 wq_ones = as_int8((uint8)(GR_WQ_ONES_U | ((num_tokens + lane) >> 31)));+ // A . (bias + q) and the A row sums of the current group; scale / zp are applied once per group+ float8 acc[GR_MT];+ float8 tq[GR_MT];+ float8 rs[GR_MT];+ unroll_for (uint m_ = 0; m_ < GR_MT; m_++) {+ acc[m_] = (float8)(0.0f);+ tq[m_] = (float8)(0.0f);+ rs[m_] = (float8)(0.0f);+ }++ // the raw bytes and scale / zp of the next chunk are in flight while the current one is consumed+ uint rw[GR_WU_NRAW];+ GR_WQ_LOAD_RAW(rw, GR_WU_NRAW, brow, 0);+ float scf[GR_WU_KCH / 32];+ float zzf[GR_WU_KCH / 32];+ GR_UPB_LDSZ(scf, zzf, 0);+ for (uint k = 0; k < GR_LOWRANK; k += GR_WU_KCH) {+#if GR_WU_KCH < GR_LOWRANK+ uint rwn[GR_WU_NRAW];+ const uint kn = min(k + GR_WU_KCH, (uint)(GR_LOWRANK - GR_WU_KCH));+ GR_WQ_LOAD_RAW(rwn, GR_WU_NRAW, brow, kn);+ float scn[GR_WU_KCH / 32];+ float zzn[GR_WU_KCH / 32];+ GR_UPB_LDSZ(scn, zzn, kn);+#endif+ unroll_for (uint s_ = 0; s_ < GR_WU_KCH / 32; s_++) {+ ushort at0[2 * GR_UP_TM];+ GR_RD2D(GR_UP_TM, t_in, GR_LOWRANK * 2, num_tokens, GR_LOWRANK * 2, k + 32 * s_, t0, at0);+ const uint16 b = GR_WQ_U4P32(rw, s_ * GR_WQ_RAW_PER_K32);+ unroll_for (uint m_ = 0; m_ < GR_MT; m_++) {+ const short8 alo = as_short8(vload8(m_, at0));+ const short8 ahi = as_short8(vload8(GR_MT + m_, at0));+ tq[m_] = GR_MAD(alo, as_int8(b.lo), tq[m_]);+ tq[m_] = GR_MAD(ahi, as_int8(b.hi), tq[m_]);+ rs[m_] = GR_MAD(alo, wq_ones, rs[m_]);+ rs[m_] = GR_MAD(ahi, wq_ones, rs[m_]);+ }+ const uint sl_ = (k >> 5) + s_;+ if ((sl_ + 1) % GR_WU_GS32 == 0 || sl_ + 1 == GR_LOWRANK / 32) {+ unroll_for (uint m_ = 0; m_ < GR_MT; m_++) {+ acc[m_] = fma((float8)(scf[s_]), fma((float8)(-zzf[s_]), rs[m_], tq[m_]), acc[m_]);+ tq[m_] = (float8)(0.0f);+ rs[m_] = (float8)(0.0f);+ }+ }+ }+#if GR_WU_KCH < GR_LOWRANK+ unroll_for (uint i_ = 0; i_ < GR_WU_NRAW; i_++) {+ rw[i_] = rwn[i_];+ }+ unroll_for (uint s_ = 0; s_ < GR_WU_KCH / 32; s_++) {+ scf[s_] = scn[s_];+ zzf[s_] = zzn[s_];+ }+#endif+ }++ // branch partial of the mix: sigmoid(read gate) * Rbar, Rbar stored K-permuted (channel d0 + lane at GR_KQ(lane))+ unroll_for (uint m_ = 0; m_ < GR_MT; m_++) {+ ushort rt[8];+ GR_RD2D1(8, rbar, GR_CD * 2, num_tokens, GR_CD * 2, cb * GR_HIDDEN + d0, t0 + m_ * 8, rt);+ const float8 rv = intel_sub_group_shuffle(convert_float8(as_half8(vload8(0, rt))), GR_KQ(lane));+ FUNC_CALL(gr_st8)(slm + (cb * GR_MT + m_) * 128, GR_SIGMOID(acc[m_]) * rv);+ }+ barrier(CLK_LOCAL_MEM_FENCE);+ if (cb != 0) {+ return;+ }+ unroll_for (uint m_ = 0; m_ < GR_MT; m_++) {+ float8 mix = FUNC_CALL(gr_ld8)(slm + m_ * 128);+ unroll_for (uint c_ = 1; c_ < GR_BRANCHES; c_++) {+ mix += FUNC_CALL(gr_ld8)(slm + (c_ * GR_MT + m_) * 128);+ }+ const ushort8 ou = as_ushort8(convert_half8_rte(mix * GR_INV_C));+ ushort tmp[8];+ vstore8(ou, 0, tmp);+ unroll_for (uint i_ = 0; i_ < 8; i_++) {+ const uint tok = t0 + m_ * 8 + i_;+ if (tok < num_tokens) {+ intel_sub_group_block_write_us(mixed + (size_t)tok * GR_HIDDEN + d0, tmp[i_]);+ }+ }+ }+}++#else // GR_UP_BSPLIT == 0+// ---------------------------------------------------------------------------------------------------------------+// UP_PROJ. JIT: GR_LOWRANK, GR_UP_TM, GR_UP_KSPLIT. One subgroup owns TM tokens x 16 channels x all branches, so the+// read gate never leaves registers.+// KSPLIT > 1: gws = [(D / 16) * KSPLIT * 16, NY, 1], lws = [KSPLIT * 16, 1, 1]+// KSPLIT == 1: gws = [(D / 16) * 16, ceil(NY / lws_y) * lws_y, 1], lws = [16, lws_y, 1]+// ---------------------------------------------------------------------------------------------------------------+#define GR_MT (GR_UP_TM / 8)+#define GR_KPT (GR_LOWRANK / GR_UP_KSPLIT)+#define GR_NACC ((GR_BRANCHES + GR_WQ_FOLD) * GR_MT) // + the row sums of the folded u8 zero point++#if GR_CD % 32 != 0 || GR_LOWRANK % 32 != 0 || GR_KPT % 32 != 0 || GR_HIDDEN % 16 != 0+ #error "gr_read_pipeline.cl: C*D and L must be multiples of 32, D of 16"+#endif+#if GR_W_TYPE != GR_WT_F16 && (GR_KPT % GR_WU_KCH != 0)+ #error "gr_read_pipeline.cl: the per-subgroup K range must be a multiple of the weight load width"+#endif++#if GR_W_TYPE == GR_WT_F16+#define GR_UP_LDB(dst, c, KK) dst = vload16(0, (const __global uint*)(brow[c] + (KK)))++#define GR_UP_LOAD(AT, B, KK) { GR_RD2D(GR_UP_TM, t_in, GR_LOWRANK * 2, num_tokens, GR_LOWRANK * 2, (KK), t0, AT); unroll_for (uint c_ = 0; c_ < GR_BRANCHES; c_++) { GR_UP_LDB(B[c_], c_, KK); } }+#endif++#define GR_UP_MMA_TO(ACC, AT, B) \+ { \+ unroll_for (uint m_ = 0; m_ < GR_MT; m_++) { \+ const short8 av_ = as_short8(vload8(m_, (AT))); \+ unroll_for (uint c_ = 0; c_ < GR_BRANCHES; c_++) { \+ (ACC)[c_ * GR_MT + m_] = GR_MAD(av_, as_int8((B)[c_].lo), (ACC)[c_ * GR_MT + m_]); \+ } \+ } \+ unroll_for (uint m_ = 0; m_ < GR_MT; m_++) { \+ const short8 av_ = as_short8(vload8(GR_MT + m_, (AT))); \+ unroll_for (uint c_ = 0; c_ < GR_BRANCHES; c_++) { \+ (ACC)[c_ * GR_MT + m_] = GR_MAD(av_, as_int8((B)[c_].hi), (ACC)[c_ * GR_MT + m_]); \+ } \+ } \+ }+#define GR_UP_MMA(AT, B) GR_UP_MMA_TO(acc, AT, B)++#if GR_W_TYPE != GR_WT_F16+#define GR_UP_RS_TO(RS, AT) \+ { \+ unroll_for (uint m_ = 0; m_ < GR_MT; m_++) { \+ (RS)[m_] = GR_MAD(as_short8(vload8(m_, (AT))), wq_ones, (RS)[m_]); \+ (RS)[m_] = GR_MAD(as_short8(vload8(GR_MT + m_, (AT))), wq_ones, (RS)[m_]); \+ } \+ }+#endif+#if GR_WQ_FOLD+#define GR_UP_RS(AT) GR_UP_RS_TO(acc + GR_BRANCHES * GR_MT, AT)+#endif++REQD_SUB_GROUP_SIZE(16)+KERNEL(gr_up_proj_dpas)(const __global ushort* t_in,+#if GR_W_TYPE == GR_WT_F16+ const __global ushort* w_up,+#else+ const __global uchar* w_up,+ const __global ushort* w_scale,+ const __global uchar* w_zp,+#endif+ const __global ushort* rbar,+ __global ushort* mixed,+ uint num_tokens) {+#if GR_UP_KSPLIT > 1+ __local float slm[GR_UP_KSPLIT * GR_NACC * 128] __attribute__((aligned(64)));+ const uint kid = get_sub_group_id();+#else+ const uint kid = 0;+#endif+ const uint lane = get_sub_group_local_id();+ const uint d0 = get_group_id(0) * 16;+ const uint t0 = get_global_id(1) * GR_UP_TM;+ if (d0 >= GR_HIDDEN || t0 >= num_tokens) {+ return;+ }++#if GR_W_TYPE == GR_WT_F16+ const __global ushort* brow[GR_BRANCHES];+#else+ const __global uchar* brow[GR_BRANCHES];+#endif+#pragma unroll+ for (uint c = 0; c < GR_BRANCHES; c++) {+#if GR_W_TYPE == GR_WT_F16+ brow[c] = w_up + (size_t)(c * GR_HIDDEN + d0 + lane) * GR_LOWRANK;+#else+ brow[c] = w_up + (size_t)(c * GR_HIDDEN + d0 + lane) * GR_WU_RB;+#endif+ }++ float8 acc[GR_NACC];+#pragma unroll+ for (uint i = 0; i < GR_NACC; i++) {+ acc[i] = (float8)(0.0f);+ }+#if GR_W_TYPE != GR_WT_F16+ const int8 wq_ones = as_int8((uint8)(GR_WQ_ONES_U | ((num_tokens + lane) >> 31)));+#endif++ // residual tiles of the mix (8 tokens per dpas tile, one 2D block read each); only the reducing subgroup needs them+ ushort rt[GR_BRANCHES][GR_MT][8];+#define GR_UP_LDRT() \+ if (kid == 0) { \+ unroll_for (uint c_ = 0; c_ < GR_BRANCHES; c_++) { \+ unroll_for (uint m_ = 0; m_ < GR_MT; m_++) { \+ GR_RD2D1(8, rbar, GR_CD * 2, num_tokens, GR_CD * 2, c_ * GR_HIDDEN + d0, t0 + m_ * 8, rt[c_][m_]); \+ } \+ } \+ }++ const uint k_begin = kid * GR_KPT;+ const uint k_end = k_begin + GR_KPT;+ uint16 b0[GR_BRANCHES];+#if GR_W_TYPE == GR_WT_F16+ ushort at0[2 * GR_UP_TM];+ for (uint k = k_begin; k < k_end; k += 32) {+ GR_UP_LOAD(at0, b0, k);+ GR_UP_MMA(at0, b0);+ }+#else+#define GR_UP_LDA(AT, KK) GR_RD2D(GR_UP_TM, t_in, GR_LOWRANK * 2, num_tokens, GR_LOWRANK * 2, (KK), t0, AT)+#if !GR_WQ_FOLD+// scale / (bias + zp) of the groups of the chunk at KK (one entry per K32 slice)+#define GR_UP_LDSZ(SC, ZZ, KK) \+ unroll_for (uint s_ = 0; s_ < GR_WU_KCH / 32; s_++) { \+ unroll_for (uint c_ = 0; c_ < GR_BRANCHES; c_++) { \+ const uint zb_ = GR_WQ_G(((KK) >> 5) + s_, GR_WU_GS32) * GR_CD + c_ * GR_HIDDEN + d0; \+ SC[c_][s_] = convert_float(as_half(intel_sub_group_block_read_us(w_scale + zb_))); \+ ZZ[c_][s_] = GR_WQ_BIAS + (float)GR_WQ_ZPAT(w_zp, zb_ + lane); \+ } \+ }+#endif+ // the first weight chunk, its activation tiles (and scale / zp) are in flight before the loop+ uint rw[GR_BRANCHES][GR_WU_NRAW];+ unroll_for (uint c_ = 0; c_ < GR_BRANCHES; c_++) {+ GR_WQ_LOAD_RAW(rw[c_], GR_WU_NRAW, brow[c_], k_begin);+ }+#if GR_APF+ ushort atc[GR_WU_KCH / 32][2 * GR_UP_TM];+ unroll_for (uint s_ = 0; s_ < GR_WU_KCH / 32; s_++) {+ GR_UP_LDA(atc[s_], k_begin + 32 * s_);+ }+#endif+#if !GR_WQ_FOLD+ float scf[GR_BRANCHES][GR_WU_KCH / 32];+ float zzf[GR_BRANCHES][GR_WU_KCH / 32];+ GR_UP_LDSZ(scf, zzf, k_begin);+ // A . (bias + q) and the A row sums of the current group; scale / zp are applied once per group+ float8 tq[GR_BRANCHES * GR_MT];+ float8 rs[GR_MT];+ unroll_for (uint i_ = 0; i_ < GR_BRANCHES * GR_MT; i_++) {+ tq[i_] = (float8)(0.0f);+ }+ unroll_for (uint m_ = 0; m_ < GR_MT; m_++) {+ rs[m_] = (float8)(0.0f);+ }+#endif+#if GR_WQ_FOLD+ float sf[GR_BRANCHES];+ float zf[GR_BRANCHES];+ unroll_for (uint c_ = 0; c_ < GR_BRANCHES; c_++) {+ sf[c_] = GR_WQ_SCALEF(w_scale, c_ * GR_HIDDEN + d0);+ zf[c_] = GR_WQ_ZPF(w_zp, c_ * GR_HIDDEN + d0, lane);+ }+#endif+ for (uint k = k_begin; k < k_end; k += GR_WU_KCH) {+#if GR_WU_KCH < GR_KPT+ uint rwn[GR_BRANCHES][GR_WU_NRAW];+ const uint kn = min(k + GR_WU_KCH, k_end - GR_WU_KCH);+ unroll_for (uint c_ = 0; c_ < GR_BRANCHES; c_++) {+ GR_WQ_LOAD_RAW(rwn[c_], GR_WU_NRAW, brow[c_], kn);+ }+#if GR_APF+ ushort atn[GR_WU_KCH / 32][2 * GR_UP_TM];+ unroll_for (uint s_ = 0; s_ < GR_WU_KCH / 32; s_++) {+ GR_UP_LDA(atn[s_], kn + 32 * s_);+ }+#endif+#if !GR_WQ_FOLD+ float scn[GR_BRANCHES][GR_WU_KCH / 32];+ float zzn[GR_BRANCHES][GR_WU_KCH / 32];+ GR_UP_LDSZ(scn, zzn, kn);+#endif+#endif+ unroll_for (uint s_ = 0; s_ < GR_WU_KCH / 32; s_++) {+#if GR_APF+ const ushort* at0 = atc[s_];+#else+ ushort at0[2 * GR_UP_TM];+ GR_UP_LDA(at0, k + 32 * s_);+#endif+ unroll_for (uint c_ = 0; c_ < GR_BRANCHES; c_++) {+#if GR_WQ_FOLD+ b0[c_] = GR_WQ_U8B32(rw[c_], s_ * GR_WQ_RAW_PER_K32);+#else+ b0[c_] = GR_WQ_GB32(rw[c_], s_ * GR_WQ_RAW_PER_K32);+#endif+ }+#if GR_WQ_FOLD+ GR_UP_MMA(at0, b0);+ GR_UP_RS(at0);+#else+ // acc += scale * (A . (bias + q) - (bias + zp) * rowsum(A)) per quantization group, see DOWN_PROJ+ GR_UP_MMA_TO(tq, at0, b0);+ GR_UP_RS_TO(rs, at0);+ const uint sl_ = (k >> 5) + s_;+ if ((sl_ + 1) % GR_WU_GS32 == 0 || sl_ + 1 == (k_end >> 5)) {+ unroll_for (uint c_ = 0; c_ < GR_BRANCHES; c_++) {+ unroll_for (uint m_ = 0; m_ < GR_MT; m_++) {+ acc[c_ * GR_MT + m_] = fma((float8)(scf[c_][s_]), fma((float8)(-zzf[c_][s_]), rs[m_], tq[c_ * GR_MT + m_]), acc[c_ * GR_MT + m_]);+ tq[c_ * GR_MT + m_] = (float8)(0.0f);+ }+ }+ unroll_for (uint m_ = 0; m_ < GR_MT; m_++) {+ rs[m_] = (float8)(0.0f);+ }+ }+#endif+ }+#if GR_WU_KCH < GR_KPT+ unroll_for (uint s_ = 0; s_ < GR_WU_KCH / 32; s_++) {+#if GR_APF+ unroll_for (uint i_ = 0; i_ < 2 * GR_UP_TM; i_++) {+ atc[s_][i_] = atn[s_][i_];+ }+#endif+#if !GR_WQ_FOLD+ unroll_for (uint c_ = 0; c_ < GR_BRANCHES; c_++) {+ scf[c_][s_] = scn[c_][s_];+ zzf[c_][s_] = zzn[c_][s_];+ }+#endif+ }+ unroll_for (uint c_ = 0; c_ < GR_BRANCHES; c_++) {+ unroll_for (uint i_ = 0; i_ < GR_WU_NRAW; i_++) {+ rw[c_][i_] = rwn[c_][i_];+ }+ }+#endif+ }+#endif+ GR_UP_LDRT();++#if GR_UP_KSPLIT > 1+#pragma unroll+ for (uint i = 0; i < GR_NACC; i++) {+ FUNC_CALL(gr_st8)(slm + (kid * GR_NACC + i) * 128, acc[i]);+ }+ barrier(CLK_LOCAL_MEM_FENCE);+ // subgroup i sums accumulator i over the K split into the slot of split 0+ for (uint i = kid; i < GR_NACC; i += GR_UP_KSPLIT) {+ float8 s = FUNC_CALL(gr_ld8)(slm + i * 128);+ unroll_for (uint p = 1; p < GR_UP_KSPLIT; p++) {+ s += FUNC_CALL(gr_ld8)(slm + (p * GR_NACC + i) * 128);+ }+ FUNC_CALL(gr_st8)(slm + i * 128, s);+ }+ barrier(CLK_LOCAL_MEM_FENCE);+ if (kid != 0) {+ return;+ }+#pragma unroll+ for (uint i = 0; i < GR_NACC; i++) {+ acc[i] = FUNC_CALL(gr_ld8)(slm + i * 128);+ }+#endif+#if GR_WQ_FOLD+#pragma unroll+ for (uint c = 0; c < GR_BRANCHES; c++) {+#pragma unroll+ for (uint m = 0; m < GR_MT; m++) {+ acc[c * GR_MT + m] = (acc[c * GR_MT + m] - zf[c] * acc[GR_BRANCHES * GR_MT + m]) * sf[c];+ }+ }+#endif++ float8 mix[GR_MT];+#pragma unroll+ for (uint m = 0; m < GR_MT; m++) {+ mix[m] = (float8)(0.0f);+ }+#pragma unroll+ for (uint c = 0; c < GR_BRANCHES; c++) {+#pragma unroll+ for (uint m = 0; m < GR_MT; m++) {+ mix[m] += GR_SIGMOID(acc[c * GR_MT + m]) * convert_float8(as_half8(vload8(0, rt[c][m])));+ }+ }++#pragma unroll+ for (uint m = 0; m < GR_MT; m++) {+ const ushort8 ou = as_ushort8(convert_half8_rte(mix[m] * GR_INV_C));+ ushort tmp[8];+ vstore8(ou, 0, tmp);+#pragma unroll+ for (uint i = 0; i < 8; i++) {+ const uint tok = t0 + m * 8 + i;+ if (tok < num_tokens) {+ intel_sub_group_block_write_us(mixed + (size_t)tok * GR_HIDDEN + d0, tmp[i]);+ }+ }+ }+}++#endif // GR_UP_BSPLIT+#endif // GR_Q_SHARE++#else+# error "gr_read_pipeline.cl: GR_PIPELINE_STAGE must be 0, 1 or 2"+#endifdiff --git a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/gr_write.cl b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/gr_write.clnew file mode 100644index 00000000000..be9ba220c84--- /dev/null+++ b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/gr_write.cl@@ -0,0 +1,39 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++// GatedResidual WRITE / COMBINE: R'[row, c, d] = R[row, c, d] + S[row, c] * Y[row, d]+//+// One subgroup per (d-tile, row); the branch loop sits inside the kernel so Y and the gate vector are read once.+// JIT: GR_BRANCHES, GR_HIDDEN, GR_WRITE_TILE (halves per subgroup, divides GR_HIDDEN), GR_WRITE_NV (= GR_WRITE_TILE / 16).+// Dispatch: gws = [ceil(D / TILE) * 16, rows, 1], lws = [16, 1, 1].++#include "gr_common.cl"++#if GR_BRANCHES != 4+ #error "gr_write.cl: only 4 branches are supported"+#endif++REQD_SUB_GROUP_SIZE(16)+KERNEL(gr_write)(const __global ushort* residual, const __global ushort* sublayer_y, const __global ushort* write_gate, __global ushort* residual_out, uint num_rows) {+ const uint d0 = get_group_id(0) * GR_WRITE_TILE;+ const uint row = get_group_id(1);+ if (d0 >= GR_HIDDEN || row >= num_rows) {+ return;+ }++ const float4 gate = convert_float4(as_half4(vload4(0, write_gate + (size_t)row * GR_BRANCHES)));+ const GR_FT(GR_WRITE_NV) y = GR_LDF(GR_WRITE_NV, sublayer_y + (size_t)row * GR_HIDDEN + d0);++ // All branch loads are issued before the first store: residual_out may alias residual (in-place), which would otherwise+ // keep the compiler from moving the next load above the previous store.+ const size_t base = (size_t)row * GR_BRANCHES * GR_HIDDEN + d0;+ GR_UT(GR_WRITE_NV) r[GR_BRANCHES];+ __attribute__((opencl_unroll_hint)) for (uint c = 0; c < GR_BRANCHES; c++) {+ r[c] = GR_BRU(GR_WRITE_NV, residual + base + c * GR_HIDDEN);+ }+ __attribute__((opencl_unroll_hint)) for (uint c = 0; c < GR_BRANCHES; c++) {+ const float g = c == 0 ? gate.s0 : c == 1 ? gate.s1 : c == 2 ? gate.s2 : gate.s3;+ GR_STF(GR_WRITE_NV, residual_out + base + c * GR_HIDDEN, GR_U2F(GR_WRITE_NV, r[c]) + g * y);+ }+}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 b6e882db44b..46880094631 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@@ -9,6 +9,8 @@ set(GPU_OCL_V2_IMPL_SOURCES${CMAKE_CURRENT_LIST_DIR}/ctc_loss.hpp${CMAKE_CURRENT_LIST_DIR}/gated_delta_net_ref.cpp${CMAKE_CURRENT_LIST_DIR}/gated_delta_net_ref.hpp+ ${CMAKE_CURRENT_LIST_DIR}/gated_residual/gated_residual.cpp+ ${CMAKE_CURRENT_LIST_DIR}/gated_residual/gated_residual.hpp${CMAKE_CURRENT_LIST_DIR}/gather_matmul/gather_matmul.cpp${CMAKE_CURRENT_LIST_DIR}/gather_matmul/gather_matmul_gen_micro.cpp${CMAKE_CURRENT_LIST_DIR}/gather_matmul/gather_matmul_gen_micro.hpp@@ -136,6 +138,11 @@ set(GPU_OCL_V2_KERNEL_SOURCES${CMAKE_CURRENT_LIST_DIR}/group_normalization_bfyx_opt.cl${CMAKE_CURRENT_LIST_DIR}/group_normalization_fsv16.cl${CMAKE_CURRENT_LIST_DIR}/group_normalization_ref.cl+ ${CMAKE_CURRENT_LIST_DIR}/gr_common.cl+ ${CMAKE_CURRENT_LIST_DIR}/gr_read.cl+ ${CMAKE_CURRENT_LIST_DIR}/gr_read_dpas.cl+ ${CMAKE_CURRENT_LIST_DIR}/gr_read_pipeline.cl+ ${CMAKE_CURRENT_LIST_DIR}/gr_write.cl${CMAKE_CURRENT_LIST_DIR}/lora_horizontal_fused.cl${CMAKE_CURRENT_LIST_DIR}/lora_opt.cl${CMAKE_CURRENT_LIST_DIR}/lora_ref.cldiff --git a/src/plugins/intel_gpu/src/graph/include/gated_residual_inst.h b/src/plugins/intel_gpu/src/graph/include/gated_residual_inst.hnew file mode 100644index 00000000000..db790848e4b--- /dev/null+++ b/src/plugins/intel_gpu/src/graph/include/gated_residual_inst.h@@ -0,0 +1,46 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#pragma once++#include <string>++#include "intel_gpu/primitives/gated_residual.hpp"+#include "primitive_inst.h"++namespace cldnn {++template <>+struct typed_program_node<gated_residual> : public typed_program_node_base<gated_residual> {+ using parent = typed_program_node_base<gated_residual>;++public:+ using parent::parent;++ program_node& input(size_t index = 0) const {+ return get_dependency(index);+ }+ std::vector<size_t> get_shape_infer_dependencies() const override {+ return {};+ }+};+using gated_residual_node = typed_program_node<gated_residual>;++template <>+class typed_primitive_inst<gated_residual> : public typed_primitive_inst_base<gated_residual> {+ using parent = typed_primitive_inst_base<gated_residual>;+ using parent::parent;++public:+ template <typename ShapeType>+ static std::vector<layout> calc_output_layouts(const gated_residual_node& node, const kernel_impl_params& impl_params);+ static layout calc_output_layout(const gated_residual_node& node, const kernel_impl_params& impl_params);++ static std::string to_string(const gated_residual_node& node);+ typed_primitive_inst(network& network, const gated_residual_node& node);+};++using gated_residual_inst = typed_primitive_inst<gated_residual>;++} // namespace cldnndiff --git a/src/plugins/intel_gpu/src/graph/registry/gated_residual_impls.cpp b/src/plugins/intel_gpu/src/graph/registry/gated_residual_impls.cppnew file mode 100644index 00000000000..22ff309da83--- /dev/null+++ b/src/plugins/intel_gpu/src/graph/registry/gated_residual_impls.cpp@@ -0,0 +1,27 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "intel_gpu/primitives/gated_residual.hpp"+#include "primitive_inst.h"+#include "registry.hpp"++#if OV_GPU_WITH_OCL+# include "impls/ocl_v2/gated_residual/gated_residual.hpp"+#endif++namespace ov::intel_gpu {++using namespace cldnn;++const std::vector<std::shared_ptr<cldnn::ImplementationManager>>& Registry<gated_residual>::get_implementations() {+ static const std::vector<std::shared_ptr<ImplementationManager>> impls = {+#if OV_GPU_WITH_OCL+ OV_GPU_CREATE_INSTANCE_OCL(ocl::GatedResidualImplementationManager, shape_types::any)+#endif+ };++ return impls;+}++} // namespace ov::intel_gpudiff --git a/src/plugins/intel_gpu/src/graph/registry/registry.hpp b/src/plugins/intel_gpu/src/graph/registry/registry.hppindex c3d21bd232d..6bbabba1a83 100644--- a/src/plugins/intel_gpu/src/graph/registry/registry.hpp+++ b/src/plugins/intel_gpu/src/graph/registry/registry.hpp@@ -195,11 +195,11 @@ REGISTER_IMPLS(gather_matmul);REGISTER_IMPLS(mlir_primitive);#endifREGISTER_IMPLS(grouped_matmul);+REGISTER_IMPLS(gated_residual);REGISTER_IMPLS(paged_qsa_indexer);REGISTER_IMPLS(qsa_indexer);REGISTER_IMPLS(sparse_pa);REGISTER_IMPLS(sparse_sdpa);-REGISTER_DEFAULT_IMPLS(assign, CPU_S, CPU_D);REGISTER_DEFAULT_IMPLS(read_value, CPU_S, CPU_D);REGISTER_DEFAULT_IMPLS(condition, COMMON_S, COMMON_D);diff --git a/src/plugins/intel_gpu/src/graph/sources.cmake b/src/plugins/intel_gpu/src/graph/sources.cmakeindex 18d2ef8bb0f..86003ef5faa 100644--- a/src/plugins/intel_gpu/src/graph/sources.cmake+++ b/src/plugins/intel_gpu/src/graph/sources.cmake@@ -56,6 +56,7 @@ set(GPU_GRAPH_SOURCES${CMAKE_CURRENT_LIST_DIR}/fake_convert.cpp${CMAKE_CURRENT_LIST_DIR}/fully_connected.cpp${CMAKE_CURRENT_LIST_DIR}/gated_delta_net.cpp+ ${CMAKE_CURRENT_LIST_DIR}/gated_residual.cpp${CMAKE_CURRENT_LIST_DIR}/gather.cpp${CMAKE_CURRENT_LIST_DIR}/gather_elements.cpp${CMAKE_CURRENT_LIST_DIR}/gather_matmul.cpp@@ -136,6 +137,7 @@ set(GPU_GRAPH_SOURCES${CMAKE_CURRENT_LIST_DIR}/include/fake_convert_inst.h${CMAKE_CURRENT_LIST_DIR}/include/fully_connected_inst.h${CMAKE_CURRENT_LIST_DIR}/include/gated_delta_net_inst.h+ ${CMAKE_CURRENT_LIST_DIR}/include/gated_residual_inst.h${CMAKE_CURRENT_LIST_DIR}/include/gather_elements_inst.h${CMAKE_CURRENT_LIST_DIR}/include/gather_inst.h${CMAKE_CURRENT_LIST_DIR}/include/gather_matmul_inst.h@@ -308,6 +310,7 @@ set(GPU_GRAPH_SOURCES${CMAKE_CURRENT_LIST_DIR}/registry/fake_convert_impls.cpp${CMAKE_CURRENT_LIST_DIR}/registry/fully_connected_impls.cpp${CMAKE_CURRENT_LIST_DIR}/registry/gated_delta_net_impls.cpp+ ${CMAKE_CURRENT_LIST_DIR}/registry/gated_residual_impls.cpp${CMAKE_CURRENT_LIST_DIR}/registry/gather_impls.cpp${CMAKE_CURRENT_LIST_DIR}/registry/gather_matmul_impls.cpp${CMAKE_CURRENT_LIST_DIR}/registry/gather_nd_impls.cppdiff --git a/src/plugins/intel_gpu/src/plugin/ops/gated_residual.cpp b/src/plugins/intel_gpu/src/plugin/ops/gated_residual.cppnew file mode 100644index 00000000000..6b7d22fbca5--- /dev/null+++ b/src/plugins/intel_gpu/src/plugin/ops/gated_residual.cpp@@ -0,0 +1,37 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "intel_gpu/op/gated_residual.hpp"++#include "intel_gpu/plugin/common_utils.hpp"+#include "intel_gpu/plugin/program_builder.hpp"+#include "intel_gpu/primitives/gated_residual.hpp"++namespace ov::op::internal {+using ov::intel_gpu::op::GatedResidual;+} // namespace ov::op::internal++namespace ov::intel_gpu {++static void CreateGatedResidualOp(ProgramBuilder& p, const std::shared_ptr<ov::intel_gpu::op::GatedResidual>& op) {+ const auto inputs = p.GetInputInfo(op);+ const auto layer_name = layer_type_name_ID(op);+ const auto layout = op->get_read_layout();+ OPENVINO_ASSERT(op->get_mode() == op::GatedResidual::Mode::WRITE || !layout || !layout->compressed || op->get_scale_gn(),+ "[GPU] ",+ layer_name,+ ": compressed GatedResidual scales must be converted to the [G, N] kernel layout (ConvertGatedResidualScaleLayout)");++ cldnn::gated_residual+ prim(layer_name, inputs, op->get_mode(), op->get_hc_count(), op->get_hidden_size(), op->get_lowrank(), op->get_epsilon(), op->get_produce_write_gate());++ prim.num_outputs = op->get_output_size();+ prim.output_data_types = get_output_data_types(op);++ p.add_primitive(*op, prim);+}++REGISTER_FACTORY_IMPL(internal, GatedResidual);++} // namespace ov::intel_gpudiff --git a/src/plugins/intel_gpu/src/plugin/transformations/convert_gated_residual_scale_layout.cpp b/src/plugins/intel_gpu/src/plugin/transformations/convert_gated_residual_scale_layout.cppnew file mode 100644index 00000000000..fa64258a7a4--- /dev/null+++ b/src/plugins/intel_gpu/src/plugin/transformations/convert_gated_residual_scale_layout.cpp@@ -0,0 +1,115 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "convert_gated_residual_scale_layout.hpp"++#include <cstdint>+#include <memory>+#include <vector>++#include "intel_gpu/op/gated_residual.hpp"+#include "openvino/core/graph_util.hpp"+#include "openvino/core/rt_info.hpp"+#include "openvino/op/constant.hpp"+#include "openvino/pass/pattern/op/wrap_type.hpp"+#include "transformations/utils/utils.hpp"++namespace ov::intel_gpu {++namespace {++/// [N, G] -> [G, N]; nullptr when `src` is not a rank-2 Constant.+std::shared_ptr<ov::op::v0::Constant> transpose_to_gn(const ov::Output<ov::Node>& src) {+ const auto c = ov::as_type_ptr<ov::op::v0::Constant>(src.get_node_shared_ptr());+ if (!c || c->get_shape().size() != 2) {+ return nullptr;+ }+ const size_t N = c->get_shape()[0];+ const size_t G = c->get_shape()[1];+ const auto et = c->get_element_type();+ if (et == ov::element::f16) {+ const auto ng = c->cast_vector<ov::float16>();+ std::vector<ov::float16> gn(ng.size());+ for (size_t n = 0; n < N; ++n) {+ for (size_t g = 0; g < G; ++g) {+ gn[(g * N) + n] = ng[(n * G) + g];+ }+ }+ return ov::op::v0::Constant::create(et, ov::Shape{G, N}, gn);+ }+ // 4 / 8-bit zero points of the weight type (4-bit ones are unpacked here and packed again by Constant::create)+ const auto ng = c->cast_vector<int32_t>();+ std::vector<int32_t> gn(ng.size());+ for (size_t n = 0; n < N; ++n) {+ for (size_t g = 0; g < G; ++g) {+ gn[(g * N) + n] = ng[(n * G) + g];+ }+ }+ return ov::op::v0::Constant::create(et, ov::Shape{G, N}, gn);+}++} // namespace++ConvertGatedResidualScaleLayout::ConvertGatedResidualScaleLayout() {+ using namespace ov::pass::pattern;+ // Only compressed READ ops that still carry the [N, G] scale / zero point layout.+ auto is_nong_compressed_read = [](const ov::Output<ov::Node>& output) {+ const auto gr = ov::as_type_ptr<ov::intel_gpu::op::GatedResidual>(output.get_node_shared_ptr());+ if (!gr || gr->get_scale_gn() || gr->get_mode() != ov::intel_gpu::op::GatedResidual::Mode::READ) {+ return false;+ }+ const auto layout = gr->get_read_layout();+ return layout && layout->compressed;+ };+ auto gr_m = wrap_type<ov::intel_gpu::op::GatedResidual>(is_nong_compressed_read);++ ov::matcher_pass_callback callback = [](Matcher& m) {+ const auto gr = ov::as_type_ptr<ov::intel_gpu::op::GatedResidual>(m.get_match_root());+ const auto layout = gr->get_read_layout();++ using Idx = ov::intel_gpu::op::GatedResidual::ReadInputIdx;+ std::vector<size_t> indices{Idx::SCALE_DOWN, Idx::SCALE_UP};+ if (layout->has_zp) {+ indices.push_back(Idx::ZP_DOWN);+ indices.push_back(Idx::ZP_UP);+ }+ if (layout->write_gate) {+ indices.push_back(layout->scale_inject);+ if (layout->has_zp) {+ indices.push_back(layout->zp_inject);+ }+ }++ // All or nothing: the op has one layout flag for every scale / zero point.+ ov::OutputVector inputs = gr->input_values();+ ov::NodeVector new_consts;+ for (const size_t i : indices) {+ const auto t = transpose_to_gn(inputs[i]);+ if (!t) {+ return false;+ }+ inputs[i] = t->output(0);+ new_consts.push_back(t);+ }++ auto new_gr = std::make_shared<ov::intel_gpu::op::GatedResidual>(inputs,+ gr->get_mode(),+ gr->get_hc_count(),+ gr->get_hidden_size(),+ gr->get_lowrank(),+ gr->get_epsilon(),+ gr->get_produce_write_gate(),+ /*scale_gn=*/true);+ new_gr->set_friendly_name(gr->get_friendly_name());+ ov::copy_runtime_info(gr, new_consts);+ ov::copy_runtime_info(gr, new_gr);+ ov::replace_node(gr, new_gr);+ return true;+ };++ auto m = std::make_shared<Matcher>(gr_m, "ConvertGatedResidualScaleLayout");+ this->register_matcher(m, callback);+}++} // namespace ov::intel_gpudiff --git a/src/plugins/intel_gpu/src/plugin/transformations/convert_gated_residual_scale_layout.hpp b/src/plugins/intel_gpu/src/plugin/transformations/convert_gated_residual_scale_layout.hppnew file mode 100644index 00000000000..7de4c67dd6a--- /dev/null+++ b/src/plugins/intel_gpu/src/plugin/transformations/convert_gated_residual_scale_layout.hpp@@ -0,0 +1,20 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#pragma once++#include "openvino/pass/matcher_pass.hpp"++namespace ov::intel_gpu {++/// @brief Converts the Constant scales / zero points of a compressed GatedResidual READ from the operation layout [N, G]+/// to the [G, N] layout the GPU kernels read (N contiguous: one sub-group block read gives every lane the scale of its own+/// output channel). The transposed constants are folded at compile time and the op is re-created with `scale_gn` set.+class ConvertGatedResidualScaleLayout : public ov::pass::MatcherPass {+public:+ OPENVINO_MATCHER_PASS_RTTI("ConvertGatedResidualScaleLayout");+ ConvertGatedResidualScaleLayout();+};++} // namespace ov::intel_gpudiff --git a/src/plugins/intel_gpu/src/plugin/transformations/gated_residual_fusion.cpp b/src/plugins/intel_gpu/src/plugin/transformations/gated_residual_fusion.cppnew file mode 100644index 00000000000..d605873ce9e--- /dev/null+++ b/src/plugins/intel_gpu/src/plugin/transformations/gated_residual_fusion.cpp@@ -0,0 +1,826 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "gated_residual_fusion.hpp"++#include <algorithm>+#include <cmath>+#include <memory>+#include <optional>+#include <vector>++#include "compressed_weights_pattern.hpp"+#include "intel_gpu/op/gated_residual.hpp"+#include "intel_gpu/primitives/gated_residual_caps.hpp"+#include "openvino/core/graph_util.hpp"+#include "openvino/core/rt_info.hpp"+#include "openvino/core/rt_info/weightless_caching_attributes.hpp"+#include "openvino/op/add.hpp"+#include "openvino/op/constant.hpp"+#include "openvino/op/convert.hpp"+#include "openvino/op/divide.hpp"+#include "openvino/op/matmul.hpp"+#include "openvino/op/multiply.hpp"+#include "openvino/op/power.hpp"+#include "openvino/op/reduce_mean.hpp"+#include "openvino/op/reduce_sum.hpp"+#include "openvino/op/reshape.hpp"+#include "openvino/op/sigmoid.hpp"+#include "openvino/op/sqrt.hpp"+#include "openvino/op/subtract.hpp"+#include "openvino/op/swish.hpp"+#include "openvino/op/transpose.hpp"+#include "openvino/op/unsqueeze.hpp"+#include "openvino/pass/pattern/matcher.hpp"+#include "openvino/pass/pattern/op/or.hpp"+#include "openvino/pass/pattern/op/wrap_type.hpp"+#include "openvino/util/pp.hpp"+#include "ov_ops/rms.hpp"++namespace ov::intel_gpu {++namespace {++namespace caps = cldnn::gated_residual_caps;++/// Compressed-weight checkpoints store scalars as `Convert(f16-Constant)`; peel the Convert to find the underlying constant.+ov::Output<ov::Node> resolve_constant_source(ov::Output<ov::Node> out) {+ while (auto convert = ov::as_type_ptr<ov::op::v0::Convert>(out.get_node_shared_ptr())) {+ out = convert->input_value(0);+ }+ return out;+}++/// Reads a constant that must hold exactly one value.+bool get_scalar_f32(const ov::Output<ov::Node>& out, float& value) {+ auto c = ov::as_type_ptr<ov::op::v0::Constant>(resolve_constant_source(out).get_node_shared_ptr());+ if (!c) {+ return false;+ }+ const auto v = c->cast_vector<float>();+ if (v.size() != 1) {+ return false;+ }+ value = v[0];+ return true;+}++bool close(float a, float b) {+ return std::fabs(a - b) <= 1e-5F * std::max(1.0F, std::fabs(b));+}++bool get_i64_vector(const ov::Output<ov::Node>& out, std::vector<int64_t>& value) {+ auto c = ov::as_type_ptr<ov::op::v0::Constant>(resolve_constant_source(out).get_node_shared_ptr());+ if (!c) {+ return false;+ }+ value = c->cast_vector<int64_t>();+ return true;+}++/// Reshapes a constant-like output to a flat [count] tensor when it is not already flat.+ov::Output<ov::Node> flatten_to(const ov::Output<ov::Node>& src, size_t count, ov::NodeVector& new_ops) {+ const auto& ps = src.get_partial_shape();+ if (ps.is_static() && ps.size() == 1 && static_cast<size_t>(ps[0].get_length()) == count) {+ return src;+ }+ auto target = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, {static_cast<int64_t>(count)});+ auto reshape = std::make_shared<ov::op::v1::Reshape>(src, target, false);+ new_ops.push_back(target);+ new_ops.push_back(reshape);+ return reshape->output(0);+}++/// The kernels always read a gain; a normalization whose gain of ones was folded away gets an explicit one.+ov::Output<ov::Node> make_unit_gain(size_t count, ov::NodeVector& new_ops) {+ auto gain = ov::op::v0::Constant::create(ov::element::f16, ov::Shape{count}, std::vector<ov::float16>(count, ov::float16(1.0F)));+ new_ops.push_back(gain);+ return gain->output(0);+}++bool has_element_count(const ov::PartialShape& ps, size_t count) {+ return ps.is_static() && ov::shape_size(ps.to_shape()) == count;+}++/// A [*, C, 1] view of the write gate with a static C. Matching-time predicate (not just a callback check) so that the+/// commutative Multiply binds the gate and Y views the right way round instead of accepting the first swapped binding.+bool is_gate_view(const ov::Output<ov::Node>& out) {+ const auto& ps = out.get_partial_shape();+ return ps.rank().is_static() && ps.size() >= 2 && ps[ps.size() - 1].is_static() && ps[ps.size() - 1].get_length() == 1 && ps[ps.size() - 2].is_static();+}++/// A [*, 1, D] view of the sub-layer output with a static D.+bool is_y_view(const ov::Output<ov::Node>& out) {+ const auto& ps = out.get_partial_shape();+ return ps.rank().is_static() && ps.size() >= 2 && ps[ps.size() - 2].is_static() && ps[ps.size() - 2].get_length() == 1 && ps[ps.size() - 1].is_static();+}++/// MatMul with the weights stored as [out, in] (transpose_b), as the kernels read them.+bool is_weight_matmul(const ov::Output<ov::Node>& out) {+ const auto mm = ov::as_type_ptr<ov::op::v0::MatMul>(out.get_node_shared_ptr());+ return mm && !mm->get_transpose_a() && mm->get_transpose_b();+}++/// `ps` has the rank of `ref` and equal static or both dynamic leading dimensions. A static 1 against a dynamic dimension may be a+/// broadcast, which the row-wise WRITE kernel does not model.+bool has_same_leading_dims(const ov::PartialShape& ps, const ov::PartialShape& ref) {+ if (ps.rank().is_dynamic() || ref.rank().is_dynamic() || ps.size() != ref.size()) {+ return false;+ }+ for (size_t i = 0; i + 1 < ps.size(); ++i) {+ const bool both_static = ps[i].is_static() && ref[i].is_static();+ if (both_static ? ps[i] != ref[i] : (ps[i].is_static() || ref[i].is_static())) {+ return false;+ }+ }+ return true;+}++/// The kernels are f16-only; fusing an f32 (or other) subgraph would produce a node with+/// no available GPU implementation at all, turning a working decomposed graph into a hard+/// compile failure.+bool is_f16(const ov::Output<ov::Node>& out) {+ return out.get_element_type() == ov::element::f16;+}++/// The input of a binary node that is not `x`, when `x` is one of its two inputs.+std::optional<ov::Output<ov::Node>> other_operand(const std::shared_ptr<ov::Node>& node, const ov::Output<ov::Node>& x) {+ if (node->input_value(0) == x) {+ return node->input_value(1);+ }+ if (node->input_value(1) == x) {+ return node->input_value(0);+ }+ return std::nullopt;+}++/// Reads the [..., C, D] branch split from a Reshape's inferred output shape, so rank-4+/// [B, L, C, D] splits and ShapeOf-built (non-Constant) targets of dynamic models qualify.+bool get_branch_split(const ov::Output<ov::Node>& split, size_t& C, size_t& D) {+ const auto& ps = split.get_partial_shape();+ if (ps.rank().is_dynamic() || ps.size() < 3 || ps[ps.size() - 2].is_dynamic() || ps[ps.size() - 1].is_dynamic()) {+ return false;+ }+ C = static_cast<size_t>(ps[ps.size() - 2].get_length());+ D = static_cast<size_t>(ps[ps.size() - 1].get_length());+ return true;+}++/// A W_down / W_up decompression subgraph (NNCF INT4 / INT8, symmetric or asymmetric) split into its parts: the weights as [N, K]+/// and the scale / zero point in the layout of the GatedResidual operation.+struct CompressedWeight {+ ov::Output<ov::Node> weights; // Constant i4/u4/i8/u8 [N, K], K contiguous (a metadata-only reshape of the checkpoint constant)+ ov::Output<ov::Node> scale; // Constant f16 [N, G]+ ov::Output<ov::Node> zp; // Constant of the weight type (4-bit packed) [N, G]; empty without zero points+ ov::element::Type type; // weight element type+ size_t bits = 0; // 4 or 8+ size_t groups = 0; // group count G (scale / zp columns), the group size is K / G++ bool has_zp() const {+ return zp.get_node() != nullptr;+ }+};++/// Parses `w` as Constant(i4/u4/i8/u8) -> Convert [-> Subtract(zp)] -> Multiply(scale) [-> Reshape] of an [N, K] weight. Anything+/// else returns nullopt and the caller keeps feeding the decompressed f16 tensor (then a plain f16 GatedResidual).+/// A scalar zero point of 0, or of 2^(bits - 1) on unsigned weights (older NNCF symmetric u4 / u8), is the symmetric form: the+/// latter is converted to the equivalent signed weights without zero point by flipping the sign bit of every element.+/// Rejected: transposed [K, N] weights, an extra scale multiply, non-Constant weights / scale / zp, a scalar scale, other scalar+/// zero points and group sizes that caps::is_group_size_supported() refuses.+std::optional<CompressedWeight> match_compressed_weight(const ov::Output<ov::Node>& w, size_t N, size_t K) {+ using namespace ov::pass::pattern;+ FC_COMPRESSED_WEIGHT_PATTERN+ ov::pass::pattern::Matcher matcher(compressed_weights_input_m);+ if (!matcher.match(w)) {+ return std::nullopt;+ }+ const auto& pm = matcher.get_pattern_value_map();+ bool has_zp = pm.count(sub_const_m) != 0;+ if (pm.count(transpose_m) != 0 || pm.count(mul2_m) != 0 || pm.count(weights_const_m) == 0 || pm.count(mul_const_m) == 0) {+ return std::nullopt;+ }+ auto weights = ov::as_type_ptr<ov::op::v0::Constant>(pm.at(weights_const_m).get_node_shared_ptr());+ auto zp = has_zp ? ov::as_type_ptr<ov::op::v0::Constant>(pm.at(sub_const_m).get_node_shared_ptr()) : nullptr;+ auto scale = ov::as_type_ptr<ov::op::v0::Constant>(pm.at(mul_const_m).get_node_shared_ptr());+ if (!weights || !scale || (has_zp && !zp)) {+ return std::nullopt;+ }+ auto wt = weights->get_element_type();+ if (!op::GatedResidual::is_compressed_weight_type(wt)) {+ return std::nullopt;+ }+ if (has_zp && !op::GatedResidual::is_compressed_weight_type(zp->get_element_type())) {+ return std::nullopt;+ }+ const size_t bits = wt.bitwidth();+ bool flip_to_signed = false;+ if (has_zp && ov::shape_size(zp->get_shape()) == 1) {+ const int32_t v = zp->cast_vector<int32_t>()[0];+ flip_to_signed = !wt.is_signed() && v == (1 << (bits - 1));+ if (v == 0 || flip_to_signed) {+ has_zp = false;+ }+ }+ const auto& ws = weights->get_shape();+ const auto& ss = scale->get_shape();+ size_t G = 0;+ if (ws.size() == 3) {+ G = ws[1];+ if (ws[0] != N || G == 0 || ws[2] * G != K || ss != ov::Shape{N, G, 1}) {+ return std::nullopt;+ }+ } else if (ws.size() == 2) {+ G = 1;+ if (ws[0] != N || ws[1] != K || ss != ov::Shape{N, 1}) {+ return std::nullopt;+ }+ } else {+ return std::nullopt;+ }+ if ((has_zp && zp->get_shape() != ss) || !caps::is_group_size_supported(K, caps::derive_group_size(K, G))) {+ return std::nullopt;+ }++ // scale / zp stay [N, G] as in the checkpoint (the operation layout); ConvertGatedResidualScaleLayout turns them into the+ // kernels' [G, N] later. The zero point must be representable in the weight type.+ const auto scale_ng_const = ov::op::v0::Constant::create(ov::element::f16, ov::Shape{N, G}, scale->cast_vector<ov::float16>());+ ov::Output<ov::Node> zp_ng_const;+ if (has_zp) {+ const int32_t zp_min = wt.is_signed() ? -(1 << (bits - 1)) : 0;+ const int32_t zp_max = wt.is_signed() ? (1 << (bits - 1)) - 1 : (1 << bits) - 1;+ const auto zp_ng = zp->cast_vector<int32_t>();+ for (const int32_t v : zp_ng) {+ if (v < zp_min || v > zp_max) {+ return std::nullopt;+ }+ }+ zp_ng_const = ov::op::v0::Constant::create(wt, ov::Shape{N, G}, zp_ng)->output(0);+ }++ std::shared_ptr<ov::op::v0::Constant> weights_2d;+ if (flip_to_signed) {+ // q - 2^(bits - 1) is the sign-bit flip of every element, so the weights keep their bytes up to that bit+ const auto* src = static_cast<const uint8_t*>(weights->get_data_ptr());+ std::vector<uint8_t> flipped(weights->get_byte_size());+ const uint8_t mask = bits == 4 ? 0x88 : 0x80;+ for (size_t i = 0; i < flipped.size(); ++i) {+ flipped[i] = src[i] ^ mask;+ }+ wt = bits == 4 ? ov::element::i4 : ov::element::i8;+ // No weightless cache attribute: the flipped bytes differ from the ones in the weights file.+ weights_2d = std::make_shared<ov::op::v0::Constant>(wt, ov::Shape{N, K}, flipped.data());+ } else {+ weights_2d = std::make_shared<ov::op::v0::Constant>(*weights, ov::Shape{N, K});+ ov::copy_weightless_cache_attr(weights, weights_2d);+ }+ CompressedWeight result;+ result.weights = weights_2d->output(0);+ result.scale = scale_ng_const->output(0);+ result.zp = zp_ng_const;+ result.type = wt;+ result.bits = bits;+ result.groups = G;+ return result;+}++/// The write-gate branch that hangs off the same Rbar as the READ: S = 2 * sigmoid(MatMul(Rbar, W_inject, transpose_b) / C).+struct WriteGateBranch {+ ov::Output<ov::Node> w_inject; // [C, C*D] with the 1/C scale taken out of the weights+ ov::Output<ov::Node> gate; // S, [.., C]+ ov::NodeVector nodes; // the matched MatMul / scale / Sigmoid / Multiply(2)+};++/// Finds the write-gate branch among the consumers of `rbar`. Every node of the chain except the last must have a single+/// consumer, otherwise removing the chain would change what other nodes see. The 1/C scale is either an explicit+/// Multiply(1/C) / Divide(C) after the MatMul or folded into W_inject.+std::optional<WriteGateBranch> match_write_gate_branch(const ov::Output<ov::Node>& rbar, const std::shared_ptr<ov::Node>& read_matmul, size_t C, size_t D) {+ const float inv_c = 1.0F / static_cast<float>(C);+ auto single_consumer = [](const ov::Output<ov::Node>& out) -> std::shared_ptr<ov::Node> {+ const auto targets = out.get_target_inputs();+ return targets.size() == 1 ? targets.begin()->get_node()->shared_from_this() : nullptr;+ };++ for (const auto& target : rbar.get_target_inputs()) {+ auto mm = ov::as_type_ptr<ov::op::v0::MatMul>(target.get_node()->shared_from_this());+ if (!mm || mm == read_matmul || target.get_index() != 0 || !is_weight_matmul(mm->output(0))) {+ continue;+ }+ const auto& w_ps = mm->input_value(1).get_partial_shape();+ if (w_ps.is_dynamic() || w_ps.size() != 2 || static_cast<size_t>(w_ps[0].get_length()) != C || static_cast<size_t>(w_ps[1].get_length()) != C * D) {+ continue;+ }++ WriteGateBranch branch;+ branch.w_inject = mm->input_value(1);+ branch.nodes.push_back(mm);+ ov::Output<ov::Node> x = mm->output(0);+ auto next = single_consumer(x);+ if (!next) {+ continue;+ }++ float scale = 0.0F;+ bool scaled = false;+ if (auto mul = ov::as_type_ptr<ov::op::v1::Multiply>(next)) {+ const auto other = other_operand(mul, x);+ scaled = other && get_scalar_f32(*other, scale) && close(scale, inv_c);+ } else if (auto div = ov::as_type_ptr<ov::op::v1::Divide>(next)) {+ scaled = div->input_value(0) == x && get_scalar_f32(div->input_value(1), scale) && close(scale, static_cast<float>(C));+ }+ if (scaled) {+ branch.nodes.push_back(next);+ x = next->output(0);+ next = single_consumer(x);+ } else if (auto folded = ov::as_type_ptr<ov::op::v1::Multiply>(branch.w_inject.get_node_shared_ptr())) {+ for (size_t i = 0; i < 2 && !scaled; ++i) {+ if (get_scalar_f32(folded->input_value(1 - i), scale) && close(scale, inv_c)) {+ branch.w_inject = folded->input_value(i);+ scaled = true;+ }+ }+ }+ if (!scaled || !next) {+ continue;+ }++ auto sigmoid = ov::as_type_ptr<ov::op::v0::Sigmoid>(next);+ if (!sigmoid) {+ continue;+ }+ branch.nodes.push_back(sigmoid);+ x = sigmoid->output(0);+ auto times_two = ov::as_type_ptr<ov::op::v1::Multiply>(single_consumer(x));+ float two = 0.0F;+ const auto other = times_two ? other_operand(times_two, x) : std::nullopt;+ if (!other || !get_scalar_f32(*other, two) || !close(two, 2.0F)) {+ continue;+ }+ branch.nodes.push_back(times_two);+ branch.gate = times_two->output(0);+ return branch;+ }+ return std::nullopt;+}++} // namespace++// ===========================================================================+// GR READ / MIX+// ===========================================================================+GatedResidualReadFusion::GatedResidualReadFusion(bool systolic) {+ using namespace ov::pass;+ using namespace ov::pass::pattern;++ auto residual = any_input();+ auto residual_3d = wrap_type<ov::op::v1::Reshape>({residual, any_input()});++ // normalization: a fused RMS op, or the decomposed RMSNorm form+ // (Power -> ReduceMean -> Add(eps) -> Sqrt -> Divide -> Multiply) that some+ // checkpoints still export the gain as a separate `1 + w` fold on top of.+ auto norm_fused = wrap_type<ov::op::internal::RMS>({residual_3d, any_input()});+ auto rbar_fused = wrap_type<ov::op::v1::Reshape>({norm_fused, any_input()});++ auto sq = wrap_type<ov::op::v1::Power>({residual_3d, any_input()});+ auto mean = wrap_type<ov::op::v1::ReduceMean>({sq, any_input()});+ auto biased = wrap_type<ov::op::v1::Add>({mean, any_input()});+ auto rms_val = wrap_type<ov::op::v0::Sqrt>({biased});+ // 1 / sqrt(.): Divide(1, sqrt) as exported, or Power(sqrt, -1) once Divide has been converted.+ auto inv_rms_div = wrap_type<ov::op::v1::Divide>({any_input(), rms_val});+ auto inv_rms_pow = wrap_type<ov::op::v1::Power>({rms_val, any_input()});+ auto inv_rms = inv_rms_div | inv_rms_pow;+ auto normalized = wrap_type<ov::op::v1::Multiply>({residual_3d, inv_rms});+ auto normalized_flat = wrap_type<ov::op::v1::Reshape>({normalized, any_input()});+ // The gain is whatever multiplies the flattened normalized value: an explicit `1 + w` Add+ // or, once constants are folded, a plain Constant. Its size is verified in the callback.+ auto decomposed_gain = any_input();+ auto rbar_decomposed = wrap_type<ov::op::v1::Multiply>({normalized_flat, decomposed_gain});++ // RMSFusion (earlier in the GPU pipeline) turns the gain-less normalization into a+ // single-input RMS; the `1 + w` gain is then applied after the flattening Reshape.+ auto norm_nogamma = wrap_type<ov::op::internal::RMS>({residual_3d});+ auto nogamma_flat = wrap_type<ov::op::v1::Reshape>({norm_nogamma, any_input()});+ auto gain_nogamma = any_input();+ auto rbar_nogamma = wrap_type<ov::op::v1::Multiply>({nogamma_flat, gain_nogamma});++ // A gain of ones is folded away by the exporter, so the flattened normalization feeds the GEMM directly.+ auto rbar = rbar_fused | rbar_decomposed | rbar_nogamma | nogamma_flat | normalized_flat;++ auto low = wrap_type<ov::op::v0::MatMul>({rbar, any_input()}, is_weight_matmul);+ // The 1/C scale sits after the down projection as exported, or on W_down itself once an+ // earlier pass has pushed the scalar into the weights; the callback proves either form.+ auto low_scaled = optional<ov::op::v1::Multiply>({low, any_input()});+ auto activation = wrap_type<ov::op::v4::Swish>({low_scaled});+ auto up = wrap_type<ov::op::v0::MatMul>({activation, any_input()}, is_weight_matmul);+ auto read_gate = wrap_type<ov::op::v0::Sigmoid>({up});++ // Canonical form: both flat, reshaped to [*, C, D] only afterwards.+ auto weighted = wrap_type<ov::op::v1::Multiply>({read_gate, rbar});++ // branch reduction: ReduceSum + an explicit 1/C Multiply (root), or a+ // ReduceMean that already folds the 1/C scaling into the reduction itself. In the+ // ReduceMean form both operands are reshaped to [*, C, D] *before* multiplying.+ auto weighted_3d = wrap_type<ov::op::v1::Reshape>({weighted, any_input()});+ auto reduced_sum = wrap_type<ov::op::v1::ReduceSum>({weighted_3d, any_input()});+ // The kernels are f16-only, see is_f16().+ auto mixed = wrap_type<ov::op::v1::Multiply>({reduced_sum, any_input()}, type_matches(ov::element::f16));++ auto gate_split = wrap_type<ov::op::v1::Reshape>({read_gate, any_input()});+ auto rbar_split = wrap_type<ov::op::v1::Reshape>({rbar, any_input()});+ auto weighted_split = wrap_type<ov::op::v1::Multiply>({gate_split, rbar_split});+ auto reduced_mean = wrap_type<ov::op::v1::ReduceMean>({weighted_split, any_input()}, type_matches(ov::element::f16));++ auto root_pattern = mixed | reduced_mean;++ ov::matcher_pass_callback callback = [OV_CAPTURE_CPY_AND_THIS](ov::pass::pattern::Matcher& m) {+ const auto& pm = m.get_pattern_value_map();+ auto root = m.get_match_root();+ if (transformation_callback(root)) {+ return false;+ }++ const bool is_fused_norm = pm.count(norm_fused) > 0;+ const bool is_nogamma_norm = pm.count(norm_nogamma) > 0;+ const bool is_decomposed_norm = pm.count(normalized_flat) > 0;+ if (!is_fused_norm && !is_decomposed_norm && !is_nogamma_norm) {+ return false;+ }+ const bool root_is_mixed = pm.count(mixed) > 0;++ auto residual_out = pm.at(residual);+ auto low_mm = ov::as_type_ptr<ov::op::v0::MatMul>(pm.at(low).get_node_shared_ptr());+ auto up_mm = ov::as_type_ptr<ov::op::v0::MatMul>(pm.at(up).get_node_shared_ptr());+ if (!low_mm || !up_mm) {+ return false;+ }++ // branch geometry must be static and provable+ size_t C = 0;+ size_t D = 0;+ if (!get_branch_split(pm.at(residual_3d), C, D)) {+ // The paged attention transformation leaves the first residual without a static width, so the split has no+ // static C either; W_down [L, C*D] proves it.+ const auto& split_ps = pm.at(residual_3d).get_partial_shape();+ const auto& w_down_shape = low_mm->get_input_partial_shape(1);+ if (split_ps.rank().is_dynamic() || split_ps.size() < 3 || split_ps[split_ps.size() - 1].is_dynamic() || w_down_shape.rank().is_dynamic() ||+ w_down_shape.size() != 2 || w_down_shape[1].is_dynamic()) {+ return false;+ }+ D = static_cast<size_t>(split_ps[split_ps.size() - 1].get_length());+ if (D == 0 || static_cast<size_t>(w_down_shape[1].get_length()) % D != 0) {+ return false;+ }+ C = static_cast<size_t>(w_down_shape[1].get_length()) / D;+ }+ if (C != caps::supported_hc_count || D == 0) {+ return false;+ }++ const auto& residual_ps = residual_out.get_partial_shape();+ if (residual_ps.rank().is_dynamic() || !residual_ps[residual_ps.size() - 1].compatible(static_cast<int64_t>(C * D))) {+ return false;+ }++ // the reduction must run over the branch axis+ auto reduce_node = root_is_mixed ? pm.at(reduced_sum).get_node_shared_ptr() : root;+ std::vector<int64_t> reduce_axes;+ if (!get_i64_vector(reduce_node->input_value(1), reduce_axes) || reduce_axes.size() != 1) {+ return false;+ }+ const auto& reduce_ps = reduce_node->input_value(0).get_partial_shape();+ if (reduce_ps.rank().is_dynamic()) {+ return false;+ }+ const auto reduce_input_rank = static_cast<int64_t>(reduce_ps.size());+ const int64_t branch_axis = reduce_axes[0] < 0 ? reduce_axes[0] + reduce_input_rank : reduce_axes[0];+ if (branch_axis != reduce_input_rank - 2) {+ return false;+ }++ // both 1/C scalings are model semantics; the branch-mix one is either an+ // explicit Multiply (ReduceSum form) or implicit in a ReduceMean (root).+ const float inv_c = 1.0F / static_cast<float>(C);+ // The kernel applies 1/C itself, so it needs the unscaled W_down.+ auto w_down = low_mm->input_value(1);+ if (pm.count(low_scaled) != 0) {+ float low_scale = 0.0F;+ const auto scale = other_operand(pm.at(low_scaled).get_node_shared_ptr(), pm.at(low));+ if (!scale || !get_scalar_f32(*scale, low_scale) || !close(low_scale, inv_c)) {+ return false;+ }+ } else {+ auto scaled_weight = ov::as_type_ptr<ov::op::v1::Multiply>(w_down.get_node_shared_ptr());+ bool unscaled = false;+ for (size_t i = 0; scaled_weight && i < 2 && !unscaled; ++i) {+ float weight_scale = 0.0F;+ if (get_scalar_f32(scaled_weight->input_value(1 - i), weight_scale) && close(weight_scale, inv_c)) {+ w_down = scaled_weight->input_value(i);+ unscaled = true;+ }+ }+ if (!unscaled) {+ return false;+ }+ }+ if (root_is_mixed) {+ float mix_scale = 0.0F;+ const auto scale = other_operand(root, pm.at(reduced_sum));+ if (!scale || !get_scalar_f32(*scale, mix_scale) || !close(mix_scale, inv_c)) {+ return false;+ }+ }++ const auto w_up = up_mm->input_value(1);+ const auto& w_down_ps = w_down.get_partial_shape();+ const auto& w_up_ps = w_up.get_partial_shape();+ if (w_down_ps.is_dynamic() || w_up_ps.is_dynamic() || w_down_ps.size() != 2 || w_up_ps.size() != 2) {+ return false;+ }+ const auto L = static_cast<size_t>(w_down_ps[0].get_length());+ if (static_cast<size_t>(w_down_ps[1].get_length()) != C * D || static_cast<size_t>(w_up_ps[0].get_length()) != C * D ||+ static_cast<size_t>(w_up_ps[1].get_length()) != L) {+ return false;+ }+ if (!caps::is_geometry_supported(op::GatedResidual::Mode::READ, C, D, L, systolic)) {+ return false;+ }++ // i4 / u4 and i8 / u8 weights with a supported group size, with or without zero points, are fed to the kernels as they are;+ // W_down and W_up must be compressed the same way, otherwise the decompressed f16 tensors are used.+ ov::OutputVector weight_inputs = {w_down, w_up};+ std::optional<CompressedWeight> compressed_down;+ const auto cd = match_compressed_weight(w_down, L, C * D);+ const auto cu = match_compressed_weight(w_up, C * D, L);+ if (cd && cu && cd->type == cu->type && cd->has_zp() == cu->has_zp() && caps::is_matrix_compression_supported(cd->bits, L, C * D, cd->groups) &&+ caps::is_matrix_compression_supported(cu->bits, C * D, L, cu->groups)) {+ weight_inputs = {cd->weights, cu->weights, cd->scale, cu->scale};+ if (cd->has_zp()) {+ weight_inputs.push_back(cd->zp);+ weight_inputs.push_back(cu->zp);+ }+ compressed_down = cd;+ }++ ov::NodeVector new_ops;+ ov::Output<ov::Node> gain_flat;+ float epsilon = 0.0F;++ if (is_fused_norm) {+ auto rms_node = ov::as_type_ptr<ov::op::internal::RMS>(pm.at(norm_fused).get_node_shared_ptr());+ if (!rms_node) {+ return false;+ }+ // the grouped norm must be per branch (gain width C*D or D)+ const auto gain = rms_node->input_value(1);+ if (!has_element_count(gain.get_partial_shape(), C * D)) {+ // A [D]-wide gain would be a valid branch-shared gain, but the kernels+ // expects the expanded [C*D] form; leave such graphs untouched.+ return false;+ }+ gain_flat = flatten_to(gain, C * D, new_ops);+ epsilon = static_cast<float>(rms_node->get_epsilon());+ } else if (is_nogamma_norm) {+ auto rms_node = ov::as_type_ptr<ov::op::internal::RMS>(pm.at(norm_nogamma).get_node_shared_ptr());+ if (!rms_node) {+ return false;+ }+ if (pm.count(gain_nogamma) > 0) {+ const auto gain = pm.at(gain_nogamma);+ if (!has_element_count(gain.get_partial_shape(), C * D)) {+ return false;+ }+ gain_flat = flatten_to(gain, C * D, new_ops);+ } else {+ gain_flat = make_unit_gain(C * D, new_ops);+ }+ epsilon = static_cast<float>(rms_node->get_epsilon());+ } else {+ // Decomposed RMSNorm: Power(2) -> ReduceMean -> Add(eps) -> Sqrt -> Divide(1,.) -> Multiply.+ // The mean must be the per-branch mean over the last (D) axis with keep_dims, otherwise+ // the grouped norm is not what the fused kernel computes.+ auto mean_node = ov::as_type_ptr<ov::op::v1::ReduceMean>(pm.at(mean).get_node_shared_ptr());+ std::vector<int64_t> mean_axes;+ const auto& sq_ps = pm.at(sq).get_partial_shape();+ if (sq_ps.rank().is_dynamic()) {+ return false;+ }+ const auto sq_rank = static_cast<int64_t>(sq_ps.size());+ if (!mean_node || !mean_node->get_keep_dims() || !get_i64_vector(mean_node->input_value(1), mean_axes) || mean_axes.size() != 1 ||+ (mean_axes[0] != -1 && mean_axes[0] != sq_rank - 1)) {+ return false;+ }+ float exponent = 0.0F;+ if (!get_scalar_f32(pm.at(sq).get_node_shared_ptr()->input_value(1), exponent) || !close(exponent, 2.0F)) {+ return false;+ }+ float numerator = 0.0F;+ if (pm.count(inv_rms_div) != 0) {+ if (!get_scalar_f32(pm.at(inv_rms_div).get_node_shared_ptr()->input_value(0), numerator) || !close(numerator, 1.0F)) {+ return false;+ }+ } else if (!get_scalar_f32(pm.at(inv_rms_pow).get_node_shared_ptr()->input_value(1), numerator) || !close(numerator, -1.0F)) {+ return false;+ }+ const auto eps_input = other_operand(pm.at(biased).get_node_shared_ptr(), pm.at(mean));+ if (!eps_input || !get_scalar_f32(*eps_input, epsilon)) {+ return false;+ }+ // The gain operand already includes any `1 + w` fold; the op takes it as is.+ if (pm.count(decomposed_gain) > 0) {+ const auto gain = pm.at(decomposed_gain);+ if (!has_element_count(gain.get_partial_shape(), C * D)) {+ return false;+ }+ gain_flat = flatten_to(gain, C * D, new_ops);+ } else {+ gain_flat = make_unit_gain(C * D, new_ops);+ }+ }++ // The op reads the gain and floating-point weights as the residual's type, and the kernels are f16-only.+ if (!is_f16(residual_out) || !is_f16(gain_flat) || (!compressed_down && (!is_f16(w_down) || !is_f16(w_up)))) {+ return false;+ }++ ov::OutputVector gr_inputs{residual_out, gain_flat};+ gr_inputs.insert(gr_inputs.end(), weight_inputs.begin(), weight_inputs.end());++ // The write gate hangs off the same Rbar. It is fused only when its weights have the same form as W_down / W_up (f16,+ // or compressed the same way); otherwise the branch stays in the graph and only the READ is fused.+ auto gate_branch = match_write_gate_branch(low_mm->input_value(0), low_mm, C, D);+ ov::OutputVector gate_inputs;+ if (gate_branch && is_f16(gate_branch->gate)) {+ if (compressed_down) {+ const auto ci = match_compressed_weight(gate_branch->w_inject, C, C * D);+ if (ci && ci->type == compressed_down->type && ci->has_zp() == compressed_down->has_zp() &&+ caps::is_row_compression_supported(ci->bits, C * D, ci->groups)) {+ gate_inputs = {ci->weights, ci->scale};+ if (ci->has_zp()) {+ gate_inputs.push_back(ci->zp);+ }+ }+ } else if (is_f16(gate_branch->w_inject)) {+ gate_inputs = {gate_branch->w_inject};+ }+ }++ auto make_gr = [&](bool with_gate) {+ ov::OutputVector inputs = gr_inputs;+ if (with_gate) {+ inputs.insert(inputs.end(), gate_inputs.begin(), gate_inputs.end());+ }+ return std::make_shared<op::GatedResidual>(inputs,+ op::GatedResidual::Mode::READ,+ C,+ D,+ L,+ epsilon,+ /*produce_write_gate=*/with_gate);+ };+ bool with_gate = !gate_inputs.empty();+ auto gr = make_gr(with_gate);+ if (with_gate && !gr->get_output_partial_shape(1).compatible(gate_branch->gate.get_partial_shape())) {+ with_gate = false;+ gr = make_gr(false);+ }+ // A split that also flattens leading axes (e.g. [B, L, C*D] -> [-1, C, D]) would+ // change the output rank, which the fused op cannot reproduce.+ if (!gr->get_output_partial_shape(0).compatible(root->get_output_partial_shape(0))) {+ return false;+ }+ gr->set_friendly_name(root->get_friendly_name());+ new_ops.push_back(gr);+ if (compressed_down) {+ // The repacked constants may carry a weightless cache attribute, so copy_runtime_info would not pick them up as inputs.+ for (size_t i = op::GatedResidual::ReadInputIdx::W_DOWN; i < gr->get_input_size(); ++i) {+ new_ops.push_back(gr->get_input_node_shared_ptr(i));+ }+ }++ // One call: a second one would overwrite the fused names merged onto `gr` by the first.+ auto fused_nodes = m.get_matched_nodes();+ if (with_gate) {+ fused_nodes.insert(fused_nodes.end(), gate_branch->nodes.begin(), gate_branch->nodes.end());+ }+ ov::copy_runtime_info(fused_nodes, new_ops);+ if (with_gate) {+ gate_branch->gate.replace(gr->output(1));+ }+ ov::replace_node(root, ov::OutputVector{gr->output(0)});+ return true;+ };++ auto matcher = std::make_shared<ov::pass::pattern::Matcher>(root_pattern, "GatedResidualReadFusion");+ this->register_matcher(matcher, callback);+}++// ===========================================================================+// GR WRITE / COMBINE+// ===========================================================================+GatedResidualWriteFusion::GatedResidualWriteFusion() {+ using namespace ov::pass;+ using namespace ov::pass::pattern;++ auto write_gate = any_input(); // S: [T, C], produced by 2 * sigmoid(W_inject * Rbar / C)+ // The gate broadcasts as [*, C, 1] and Y as [*, 1, D]; both wrappers are structurally identical (Reshape-or-Unsqueeze+ // of a generic input), so the shape predicates are what lets the commutative Multiply bind the operands the right way round.+ auto gate_3d = wrap_type<ov::op::v1::Reshape, ov::op::v0::Unsqueeze>({write_gate, any_input()}, is_gate_view);++ auto y_src = any_input();+ auto y_3d = wrap_type<ov::op::v1::Reshape, ov::op::v0::Unsqueeze>({y_src, any_input()}, is_y_view);++ auto scaled = wrap_type<ov::op::v1::Multiply>({gate_3d, y_3d});++ // Case A (canonical): Add happens in the split [*, C, D] domain and a single+ // trailing reshape flattens the result back to [*, C*D] (this is the root).+ auto residual_3d = wrap_type<ov::op::v1::Reshape>({any_input(), any_input()});+ auto updated_a = wrap_type<ov::op::v1::Add>({residual_3d, scaled});+ // The kernels are f16-only, see is_f16().+ auto result_a = wrap_type<ov::op::v1::Reshape>({updated_a, any_input()}, type_matches(ov::element::f16));++ // Case B: `scaled` is flattened first and added directly to an already-flat+ // residual stream; any reshape back to split form happens *after* the Add and is+ // left untouched by this pass (the fused op's WRITE output is always flat).+ auto scaled_flat = wrap_type<ov::op::v1::Reshape>({scaled, any_input()});+ auto residual_flat = any_input();+ auto updated_b = wrap_type<ov::op::v1::Add>({residual_flat, scaled_flat}, type_matches(ov::element::f16));++ auto root_pattern = result_a | updated_b;++ ov::matcher_pass_callback callback = [OV_CAPTURE_CPY_AND_THIS](ov::pass::pattern::Matcher& m) {+ const auto& pm = m.get_pattern_value_map();+ auto root = m.get_match_root();+ if (transformation_callback(root)) {+ return false;+ }++ // Branch geometry from how the gate [*, C, 1] and Y [*, 1, D] views broadcast; the view predicates proved their shapes.+ const auto& gate_ps = pm.at(gate_3d).get_partial_shape();+ const auto& y_ps = pm.at(y_3d).get_partial_shape();+ const auto C = static_cast<size_t>(gate_ps[gate_ps.size() - 2].get_length());+ const auto D = static_cast<size_t>(y_ps[y_ps.size() - 1].get_length());+ if (!caps::is_geometry_supported(op::GatedResidual::Mode::WRITE, C, D, 0, false)) {+ return false;+ }++ // The kernel reads Y as [*, D] and the gate as [*, C]; the 3D views above only+ // prove a broadcast, not that the sources are not themselves already split.+ const auto& y_src_ps = pm.at(y_src).get_partial_shape();+ const auto& gate_src_ps = pm.at(write_gate).get_partial_shape();+ if (y_src_ps.rank().is_dynamic() || gate_src_ps.rank().is_dynamic() || y_src_ps.size() < 1 || gate_src_ps.size() < 1 ||+ y_src_ps[y_src_ps.size() - 1] != static_cast<int64_t>(D) || gate_src_ps[gate_src_ps.size() - 1] != static_cast<int64_t>(C)) {+ return false;+ }++ ov::Output<ov::Node> residual_out;+ const ov::Output<ov::Node> y_out = pm.at(y_src);+ const ov::Output<ov::Node> gate_out = pm.at(write_gate);++ if (pm.count(result_a) != 0) {+ // Case A: residual_3d's own split additionally proves the geometry matches+ // the one derived from gate/y above.+ size_t split_c = 0;+ size_t split_d = 0;+ if (!get_branch_split(pm.at(residual_3d), split_c, split_d) || split_c != C || split_d != D) {+ return false;+ }+ residual_out = pm.at(residual_3d).get_node_shared_ptr()->input_value(0);+ } else if (pm.count(updated_b) != 0) {+ residual_out = pm.at(residual_flat);+ } else {+ return false;+ }++ // See GatedResidualReadFusion: a residual without a static width is proven by Y and the gate here.+ const auto& residual_ps = residual_out.get_partial_shape();+ if (residual_ps.rank().is_dynamic() || !residual_ps[residual_ps.size() - 1].compatible(static_cast<int64_t>(C * D))) {+ return false;+ }++ // The kernel walks the residual's rows, so Y and the gate must share its leading dimensions.+ if (!has_same_leading_dims(y_src_ps, residual_ps) || !has_same_leading_dims(gate_src_ps, residual_ps)) {+ return false;+ }++ auto gr = std::make_shared<op::GatedResidual>(ov::OutputVector{residual_out, y_out, gate_out},+ op::GatedResidual::Mode::WRITE,+ C,+ D,+ /*lowrank=*/0,+ /*epsilon=*/0.0F,+ /*produce_write_gate=*/false);+ if (!gr->get_output_partial_shape(0).compatible(root->get_output_partial_shape(0))) {+ return false;+ }+ gr->set_friendly_name(root->get_friendly_name());++ ov::copy_runtime_info(m.get_matched_nodes(), gr);+ ov::replace_node(root, gr);+ return true;+ };++ auto matcher = std::make_shared<ov::pass::pattern::Matcher>(root_pattern, "GatedResidualWriteFusion");+ this->register_matcher(matcher, callback);+}++} // namespace ov::intel_gpudiff --git a/src/plugins/intel_gpu/src/plugin/transformations/gated_residual_fusion.hpp b/src/plugins/intel_gpu/src/plugin/transformations/gated_residual_fusion.hppnew file mode 100644index 00000000000..febbd0d1d85--- /dev/null+++ b/src/plugins/intel_gpu/src/plugin/transformations/gated_residual_fusion.hpp@@ -0,0 +1,64 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#pragma once++#include "openvino/pass/graph_rewrite.hpp"+#include "openvino/pass/matcher_pass.hpp"++namespace ov::intel_gpu {++/// @brief Recognizes the Gated Residual READ / MIX pattern and replaces+/// it with ov::intel_gpu::op::GatedResidual.+///+/// Canonical sub-graph (all activations are token-major [T, C*D]):+/// r3 = Reshape(R, [T, C, D])+/// n3 = RMS(r3, gamma, eps) // branch-wise grouped RMSNorm, width D+/// rbar = Reshape(n3, [T, C*D])+/// low = MatMul(rbar, W_down, transpose_b) // W_down: [L, C*D]+/// act = Swish(low * 1/C)+/// up = MatMul(act, W_up, transpose_b) // W_up: [C*D, L]+/// wm = Sigmoid(up) * rbar+/// mixed = ReduceSum(Reshape(wm, [T, C, D]), axis=1) * 1/C+///+/// The pass refuses to fuse (and leaves the generic graph untouched) unless it can prove:+/// * C is static and equal to 4 (first supported branch count);+/// * the grouped-norm width is exactly D, i.e. the norm is per branch, not over C*D;+/// * the reduce axis is the branch axis;+/// * both 1/C scalings are present;+/// * no other consumer would observe a semantic change.+class GatedResidualReadFusion : public ov::pass::MatcherPass {+public:+ OPENVINO_MATCHER_PASS_RTTI("GatedResidualReadFusion");+ /// @param systolic the device runs the dpas READ kernels: lifts the geometry limits of the scalar kernel. Compressed+ /// decompression subgraphs of W_down / W_up / W_inject are fused into the compressed forms on either kernel.+ explicit GatedResidualReadFusion(bool systolic = false);+};++/// @brief Recognizes the Gated Residual WRITE / COMBINE pattern.+///+/// Canonical sub-graph:+/// inj = MatMul(rbar, W_inject, transpose_b) // W_inject: [C, C*D]+/// S = 2 * Sigmoid(inj * 1/C) // per-branch scalar gate in (0, 2)+/// R' = Reshape(Reshape(R, [T,C,D]) + Reshape(S,[T,C,1]) * Reshape(Y,[T,1,D]), [T, C*D])+///+/// The gate `S` is consumed as an opaque [*, C] input; the `2 * Sigmoid(...)` that produces+/// it stays outside the fused op.+class GatedResidualWriteFusion : public ov::pass::MatcherPass {+public:+ OPENVINO_MATCHER_PASS_RTTI("GatedResidualWriteFusion");+ GatedResidualWriteFusion();+};++/// @brief Convenience container running both Gated Residual pattern transformations.+class GatedResidualFusion : public ov::pass::GraphRewrite {+public:+ OPENVINO_GRAPH_REWRITE_RTTI("GatedResidualFusion");+ explicit GatedResidualFusion(bool systolic = false) {+ add_matcher<GatedResidualReadFusion>(systolic);+ add_matcher<GatedResidualWriteFusion>();+ }+};++} // namespace ov::intel_gpudiff --git a/src/plugins/intel_gpu/src/plugin/transformations/op/gated_residual.cpp b/src/plugins/intel_gpu/src/plugin/transformations/op/gated_residual.cppnew file mode 100644index 00000000000..766b3776c59--- /dev/null+++ b/src/plugins/intel_gpu/src/plugin/transformations/op/gated_residual.cpp@@ -0,0 +1,297 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "intel_gpu/op/gated_residual.hpp"++namespace ov::intel_gpu::op {++namespace {++/// Rank is dynamic, or last dimension is dynamic, or it equals `expected`.+bool last_dim_matches(const ov::PartialShape& ps, size_t expected) {+ return ps.rank().is_dynamic() || (ps.rank().get_length() > 0 && ps[ps.rank().get_length() - 1].compatible(static_cast<int64_t>(expected)));+}++/// Rank-2 weight [rows, cols] where each static dimension must match.+bool matrix_matches(const ov::PartialShape& ps, size_t rows, size_t cols) {+ return ps.rank().is_dynamic() ||+ (ps.rank().get_length() == 2 && ps[0].compatible(static_cast<int64_t>(rows)) && ps[1].compatible(static_cast<int64_t>(cols)));+}++/// Same rank as `ref` and compatible leading (all but the last) dimensions.+bool leading_dims_match(const ov::PartialShape& ps, const ov::PartialShape& ref) {+ if (ps.rank().is_dynamic() || ref.rank().is_dynamic()) {+ return true;+ }+ if (ps.size() != ref.size()) {+ return false;+ }+ for (size_t i = 0; i + 1 < ps.size(); ++i) {+ if (!ps[i].compatible(ref[i])) {+ return false;+ }+ }+ return true;+}++} // namespace++GatedResidual::GatedResidual(const ov::OutputVector& args,+ Mode mode,+ size_t hc_count,+ size_t hidden_size,+ size_t lowrank,+ float epsilon,+ bool produce_write_gate,+ bool scale_gn)+ : Op(args),+ m_mode(mode),+ m_hc_count(hc_count),+ m_hidden_size(hidden_size),+ m_lowrank(lowrank),+ m_epsilon(epsilon),+ m_produce_write_gate(produce_write_gate),+ m_scale_gn(scale_gn) {+ constructor_validate_and_infer_types();+}++bool GatedResidual::visit_attributes(ov::AttributeVisitor& visitor) {+ auto mode = static_cast<int64_t>(m_mode);+ visitor.on_attribute("mode", mode);+ m_mode = static_cast<Mode>(mode);+ visitor.on_attribute("hc_count", m_hc_count);+ visitor.on_attribute("hidden_size", m_hidden_size);+ visitor.on_attribute("lowrank", m_lowrank);+ visitor.on_attribute("epsilon", m_epsilon);+ visitor.on_attribute("produce_write_gate", m_produce_write_gate);+ visitor.on_attribute("scale_gn", m_scale_gn);+ return true;+}++void GatedResidual::validate_and_infer_types() {+ const auto input_size = get_input_size();+ const auto out_et = get_input_element_type(0);++ NODE_VALIDATION_CHECK(this,+ m_mode == Mode::READ || m_mode == Mode::WRITE,+ "GatedResidual mode must be READ (0) or WRITE (1), got ",+ static_cast<int32_t>(m_mode));+ NODE_VALIDATION_CHECK(this, m_hc_count > 0, "GatedResidual requires a positive branch count C.");+ NODE_VALIDATION_CHECK(this, m_hidden_size > 0, "GatedResidual requires a positive hidden size D.");+ NODE_VALIDATION_CHECK(this, out_et.is_dynamic() || out_et.is_real(), "GatedResidual residual must have a floating-point element type, got ", out_et);++ const auto& residual_ps = get_input_partial_shape(0);+ NODE_VALIDATION_CHECK(this,+ residual_ps.rank().is_dynamic() || residual_ps.rank().get_length() >= 2,+ "GatedResidual requires the residual input rank to be at least 2.");+ NODE_VALIDATION_CHECK(this,+ last_dim_matches(residual_ps, m_hc_count * m_hidden_size),+ "GatedResidual residual last dimension must be C*D = ",+ m_hc_count * m_hidden_size,+ ", got ",+ residual_ps);++ if (m_mode == Mode::WRITE) {+ NODE_VALIDATION_CHECK(this, input_size == 3, "GatedResidual (WRITE) expects 3 inputs, got ", input_size);+ NODE_VALIDATION_CHECK(this,+ last_dim_matches(get_input_partial_shape(WriteInputIdx::SUBLAYER_Y), m_hidden_size),+ "GatedResidual (WRITE) sub-layer output last dimension must be D = ",+ m_hidden_size);+ NODE_VALIDATION_CHECK(this,+ last_dim_matches(get_input_partial_shape(WriteInputIdx::WRITE_GATE), m_hc_count),+ "GatedResidual (WRITE) write gate last dimension must be C = ",+ m_hc_count);+ // The kernel walks the residual's rows only.+ NODE_VALIDATION_CHECK(this,+ leading_dims_match(get_input_partial_shape(WriteInputIdx::SUBLAYER_Y), residual_ps),+ "GatedResidual (WRITE) sub-layer output must have the residual's rank and leading dimensions, got ",+ get_input_partial_shape(WriteInputIdx::SUBLAYER_Y),+ " for residual ",+ residual_ps);+ NODE_VALIDATION_CHECK(this,+ leading_dims_match(get_input_partial_shape(WriteInputIdx::WRITE_GATE), residual_ps),+ "GatedResidual (WRITE) write gate must have the residual's rank and leading dimensions, got ",+ get_input_partial_shape(WriteInputIdx::WRITE_GATE),+ " for residual ",+ residual_ps);+ auto merged_et = out_et;+ for (size_t i = 1; i < input_size; ++i) {+ NODE_VALIDATION_CHECK(this,+ ov::element::Type::merge(merged_et, merged_et, get_input_element_type(i)),+ "GatedResidual (WRITE) inputs must share the residual element type.");+ }+ // R' has exactly the residual layout, its width is known even when the residual's is not.+ set_output_type(0, merged_et, infer_output_shapes(m_mode, m_hc_count, m_hidden_size, m_produce_write_gate, residual_ps)[0]);+ return;+ }++ // READ+ const auto layout = read_layout(input_size, m_produce_write_gate);+ NODE_VALIDATION_CHECK(this,+ layout.has_value(),+ "GatedResidual (READ) expects 4 inputs (5 with W_inject), 6 / 8 with compressed weights (without / with zero "+ "points), or 8 / 11 with compressed weights and W_inject, got ",+ input_size);+ const bool compressed = layout->compressed;+ const bool has_zp = layout->has_zp;+ NODE_VALIDATION_CHECK(this, m_lowrank > 0, "GatedResidual (READ) requires a positive low rank L.");++ const size_t cd = m_hc_count * m_hidden_size;+ // Norm weight and floating-point weights are read as the residual's element type.+ const auto check_residual_type = [&](size_t idx, const char* name) {+ auto et = out_et;+ NODE_VALIDATION_CHECK(this,+ ov::element::Type::merge(et, et, get_input_element_type(idx)),+ "GatedResidual ",+ name,+ " must have the residual element type ",+ out_et,+ ", got ",+ get_input_element_type(idx));+ };+ check_residual_type(ReadInputIdx::NORM_WEIGHT, "norm weight");+ const auto& gain_ps = get_input_partial_shape(ReadInputIdx::NORM_WEIGHT);+ NODE_VALIDATION_CHECK(this,+ gain_ps.rank().is_dynamic() || (gain_ps.rank().get_length() == 1 && gain_ps[0].compatible(static_cast<int64_t>(cd))),+ "GatedResidual norm weight must have shape [C*D] = [",+ cd,+ "], got ",+ gain_ps);+ NODE_VALIDATION_CHECK(this,+ matrix_matches(get_input_partial_shape(ReadInputIdx::W_DOWN), m_lowrank, cd),+ "GatedResidual W_down must have shape [L, C*D] = [",+ m_lowrank,+ ", ",+ cd,+ "], got ",+ get_input_partial_shape(ReadInputIdx::W_DOWN));+ NODE_VALIDATION_CHECK(this,+ matrix_matches(get_input_partial_shape(ReadInputIdx::W_UP), cd, m_lowrank),+ "GatedResidual W_up must have shape [C*D, L] = [",+ cd,+ ", ",+ m_lowrank,+ "], got ",+ get_input_partial_shape(ReadInputIdx::W_UP));++ const auto wd_et = get_input_element_type(ReadInputIdx::W_DOWN);+ const auto wu_et = get_input_element_type(ReadInputIdx::W_UP);+ NODE_VALIDATION_CHECK(this,+ wd_et.is_dynamic() || wu_et.is_dynamic() || wd_et == wu_et,+ "GatedResidual W_down and W_up must share one element type, got ",+ wd_et,+ " and ",+ wu_et);+ const bool wd_quant = is_compressed_weight_type(wd_et);+ NODE_VALIDATION_CHECK(this,+ wd_et.is_dynamic() || (compressed == wd_quant),+ "GatedResidual takes i4/u4/i8/u8 weights exactly with the compressed input forms.");+ if (!compressed) {+ check_residual_type(ReadInputIdx::W_DOWN, "W_down");+ check_residual_type(ReadInputIdx::W_UP, "W_up");+ } else {+ // scale/zp are [N, G] (or [G, N] with scale_gn); the group size along K is K / G (not an attribute).+ const size_t n_axis = m_scale_gn ? 1 : 0;+ const size_t g_axis = m_scale_gn ? 0 : 1;+ auto check_group = [&](size_t scale_idx, size_t zp_idx, size_t n, size_t k, const char* name) {+ const auto& sps = get_input_partial_shape(scale_idx);+ NODE_VALIDATION_CHECK(this,+ sps.rank().is_dynamic() || (sps.rank().get_length() == 2 && sps[n_axis].compatible(static_cast<int64_t>(n))),+ "GatedResidual ",+ name,+ " scale must have shape ",+ m_scale_gn ? "[G, " : "[",+ n,+ m_scale_gn ? "]" : ", G]",+ ", got ",+ sps);+ NODE_VALIDATION_CHECK(this,+ get_input_element_type(scale_idx).is_dynamic() || get_input_element_type(scale_idx) == ov::element::f16,+ "GatedResidual ",+ name,+ " scale must be f16.");+ if (has_zp) {+ const auto& zps = get_input_partial_shape(zp_idx);+ NODE_VALIDATION_CHECK(this,+ zps.rank().is_dynamic() || sps.rank().is_dynamic() || zps == sps,+ "GatedResidual ",+ name,+ " zero point must match the scale shape, got ",+ zps);+ NODE_VALIDATION_CHECK(this,+ get_input_element_type(zp_idx).is_dynamic() || get_input_element_type(zp_idx) == wd_et,+ "GatedResidual ",+ name,+ " zero point must have the weight element type ",+ wd_et);+ }+ if (sps.rank().is_static() && sps[g_axis].is_static()) {+ const auto g = static_cast<size_t>(sps[g_axis].get_length());+ NODE_VALIDATION_CHECK(this, g != 0 && k % g == 0, "GatedResidual ", name, ": K = ", k, " is not divisible by the scale group count G = ", g);+ }+ };+ check_group(ReadInputIdx::SCALE_DOWN, ReadInputIdx::ZP_DOWN, m_lowrank, cd, "W_down");+ check_group(ReadInputIdx::SCALE_UP, ReadInputIdx::ZP_UP, cd, m_lowrank, "W_up");+ if (m_produce_write_gate) {+ NODE_VALIDATION_CHECK(this,+ get_input_element_type(layout->w_inject).is_dynamic() || get_input_element_type(layout->w_inject) == wd_et,+ "GatedResidual W_inject must have the weight element type ",+ wd_et);+ check_group(layout->scale_inject, layout->zp_inject, m_hc_count, cd, "W_inject");+ }+ }+ if (m_produce_write_gate) {+ const size_t inject_idx = layout->w_inject;+ if (!compressed) {+ const auto inject_et = get_input_element_type(inject_idx);+ NODE_VALIDATION_CHECK(this,+ inject_et.is_dynamic() || !is_compressed_weight_type(inject_et),+ "GatedResidual takes an i4/u4/i8/u8 W_inject exactly with the compressed input forms.");+ check_residual_type(inject_idx, "W_inject");+ }+ NODE_VALIDATION_CHECK(this,+ matrix_matches(get_input_partial_shape(inject_idx), m_hc_count, cd),+ "GatedResidual W_inject must have shape [C, C*D] = [",+ m_hc_count,+ ", ",+ cd,+ "], got ",+ get_input_partial_shape(inject_idx));+ }++ const auto output_shapes = infer_output_shapes(m_mode, m_hc_count, m_hidden_size, m_produce_write_gate, residual_ps);+ set_output_size(output_shapes.size());+ for (size_t i = 0; i < output_shapes.size(); ++i) {+ set_output_type(i, out_et, output_shapes[i]);+ }+}++std::vector<ov::PartialShape> GatedResidual::infer_output_shapes(Mode mode,+ size_t hc_count,+ size_t hidden_size,+ bool produce_write_gate,+ const ov::PartialShape& residual_ps) {+ const auto with_last_dim = [&](size_t dim) {+ auto ps = residual_ps;+ if (ps.rank().is_static() && ps.size() > 0) {+ ps[ps.size() - 1] = ov::Dimension(static_cast<int64_t>(dim));+ }+ return ps;+ };+ if (mode == Mode::WRITE) {+ return {with_last_dim(hc_count * hidden_size)};+ }+ std::vector<ov::PartialShape> shapes{with_last_dim(hidden_size)};+ if (produce_write_gate) {+ shapes.push_back(with_last_dim(hc_count));+ }+ return shapes;+}++std::shared_ptr<Node> GatedResidual::clone_with_new_inputs(const ov::OutputVector& new_args) const {+ check_new_args_count(this, new_args);+ return std::make_shared<GatedResidual>(new_args, m_mode, m_hc_count, m_hidden_size, m_lowrank, m_epsilon, m_produce_write_gate, m_scale_gn);+}++} // namespace ov::intel_gpu::opdiff --git a/src/plugins/intel_gpu/src/plugin/transformations_pipeline.cpp b/src/plugins/intel_gpu/src/plugin/transformations_pipeline.cppindex 04812bc1e47..56d47982bab 100644--- a/src/plugins/intel_gpu/src/plugin/transformations_pipeline.cpp+++ b/src/plugins/intel_gpu/src/plugin/transformations_pipeline.cpp@@ -91,6 +91,7 @@#include "plugin/transformations/clamp_fp16_output.hpp"#include "plugin/transformations/convert_convolution.hpp"#include "plugin/transformations/convert_fc_to_compressed.hpp"+#include "plugin/transformations/convert_gated_residual_scale_layout.hpp"#include "transformations/op_conversions/convert_grouped_matmul_to_compressed.hpp"#include "plugin/transformations/convert_matmul_to_fc.hpp"#include "plugin/transformations/fuse_moe_shared_expert.hpp"@@ -113,6 +114,7 @@#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/gated_residual_fusion.hpp"#include "plugin/transformations/group_query_attention_decomposition.hpp"#include "plugin/transformations/increase_position_ids_precision.hpp"#include "plugin/transformations/indirect_kv_cache.hpp"@@ -127,6 +129,7 @@#include "plugin/transformations/stateless_kv_fusion.hpp"#include "plugin/transformations/swoosh_fusion.hpp"#include "intel_gpu/op/fully_connected.hpp"+#include "intel_gpu/primitives/gated_residual_caps.hpp"#include "transformations/common_optimizations/move_fc_reshape_to_weights.hpp"#include "plugin/transformations/optimize_subsequent_reshapes.hpp"#include "plugin/transformations/print_model_statistics.hpp"@@ -928,6 +931,16 @@ void TransformationsPipeline::apply_activation_scaling_transformations(const stdmanager.register_pass<ov::intel_gpu::FuseAtan2Decomposed>();manager.register_pass<ov::intel_gpu::SwooshFusion>();manager.register_pass<ov::intel_gpu::SwiGluFusionWithClamp>();++ // GatedResidual kernel (scalar included) needs the OpenCL subgroup extensions, else a fused node has no implementation.+ // The fusion also hides the Add / MatMul ops that the activation scaling has to rescale, so it is skipped then.+ const bool fp16_activation_scaling = config.get_activations_scale_factor() > 0.F && infer_precision == ov::element::f16;+ if (cldnn::gated_residual_caps::is_device_supported(device_info) && !fp16_activation_scaling) {+ manager.register_pass<ov::intel_gpu::GatedResidualFusion>(cldnn::gated_residual_caps::uses_dpas_kernels(device_info, config));+ // The fusion keeps the scales / zero points in the operation layout [N, G]; the kernels read [G, N].+ manager.register_pass<ov::intel_gpu::ConvertGatedResidualScaleLayout>();+ }+// This Validate is needed for proper data type propagation after applying IncreasePositionIdsPrecision passmanager.register_pass<ov::pass::Validate>();diff --git a/src/plugins/intel_gpu/src/runtime/execution_config.cpp b/src/plugins/intel_gpu/src/runtime/execution_config.cppindex 2ebf6b6fda9..afff2177717 100644--- a/src/plugins/intel_gpu/src/runtime/execution_config.cpp+++ b/src/plugins/intel_gpu/src/runtime/execution_config.cpp@@ -5,6 +5,7 @@#include <algorithm>#include <cstdlib>+#include "intel_gpu/op/gated_residual.hpp"#include "intel_gpu/op/indirect_sdpa.hpp"#include "intel_gpu/op/kv_cache.hpp"#include "intel_gpu/op/sdpa.hpp"@@ -79,6 +80,11 @@ bool requires_new_shape_infer(const std::shared_ptr<ov::Node>& op) {return true;}+ // A READ with a write gate has two outputs, which the legacy shape inference cannot address by port.+ if (ov::is_type<ov::intel_gpu::op::GatedResidual>(op)) {+ return true;+ }+if (ov::is_type<ov::op::internal::GatedDeltaNet>(op) || ov::is_type<ov::op::internal::SelectiveSSM>(op) ||ov::is_type<ov::op::internal::PagedSelectiveSSM>(op)) {return true;diff --git a/src/plugins/intel_gpu/tests/unit/sources.cmake b/src/plugins/intel_gpu/tests/unit/sources.cmakeindex 274618c05da..7255d491d94 100644--- a/src/plugins/intel_gpu/tests/unit/sources.cmake+++ b/src/plugins/intel_gpu/tests/unit/sources.cmake@@ -203,6 +203,7 @@ set(GPU_UNIT_TESTS_SRCS${CMAKE_CURRENT_LIST_DIR}/test_cases/fully_connected_gpu_test.cpp${CMAKE_CURRENT_LIST_DIR}/test_cases/fully_connected_weights_layout_test.cpp${CMAKE_CURRENT_LIST_DIR}/test_cases/gated_delta_net.cpp+ ${CMAKE_CURRENT_LIST_DIR}/test_cases/gated_residual_gpu_test.cpp${CMAKE_CURRENT_LIST_DIR}/test_cases/gather_elements_gpu_test.cpp${CMAKE_CURRENT_LIST_DIR}/test_cases/gather_gpu_test.cpp${CMAKE_CURRENT_LIST_DIR}/test_cases/gather_nd_gpu_test.cpp@@ -359,6 +360,7 @@ set(GPU_UNIT_TESTS_SRCS${CMAKE_CURRENT_LIST_DIR}/transformations/move_fc_reshape_to_weights.cpp${CMAKE_CURRENT_LIST_DIR}/transformations/optimize_subsequent_reshapes_test.cpp${CMAKE_CURRENT_LIST_DIR}/transformations/preserve_single_selective_ssm_output_test.cpp+ ${CMAKE_CURRENT_LIST_DIR}/transformations/gated_residual_fusion_test.cpp${CMAKE_CURRENT_LIST_DIR}/transformations/reduce_fc_dimensions_test.cpp${CMAKE_CURRENT_LIST_DIR}/transformations/remove_fq_before_dw_conv_test.cpp${CMAKE_CURRENT_LIST_DIR}/transformations/scale_down_gated_mlp_input_test.cpp@@ -484,6 +486,9 @@ set(GPU_UNIT_TESTS_TRANSFORMATIONS_SRCS${CMAKE_HOME_DIRECTORY}/src/plugins/intel_gpu/src/plugin/transformations/preserve_single_selective_ssm_output.hpp${CMAKE_HOME_DIRECTORY}/src/plugins/intel_gpu/src/plugin/transformations/print_model_statistics.cpp${CMAKE_HOME_DIRECTORY}/src/plugins/intel_gpu/src/plugin/transformations/print_model_statistics.hpp+ ${CMAKE_HOME_DIRECTORY}/src/plugins/intel_gpu/src/plugin/transformations/convert_gated_residual_scale_layout.cpp+ ${CMAKE_HOME_DIRECTORY}/src/plugins/intel_gpu/src/plugin/transformations/gated_residual_fusion.cpp+ ${CMAKE_HOME_DIRECTORY}/src/plugins/intel_gpu/src/plugin/transformations/gated_residual_fusion.hpp${CMAKE_HOME_DIRECTORY}/src/plugins/intel_gpu/src/plugin/transformations/reduce_fc_dimensions.cpp${CMAKE_HOME_DIRECTORY}/src/plugins/intel_gpu/src/plugin/transformations/reduce_fc_dimensions.hpp${CMAKE_HOME_DIRECTORY}/src/plugins/intel_gpu/src/plugin/transformations/remove_fq_before_dw_conv.cpp@@ -507,6 +512,7 @@ set(GPU_UNIT_TESTS_TRANSFORMATIONS_SRCS${CMAKE_HOME_DIRECTORY}/src/plugins/intel_gpu/src/plugin/transformations/op/convolution.cpp${CMAKE_HOME_DIRECTORY}/src/plugins/intel_gpu/src/plugin/transformations/op/fully_connected.cpp${CMAKE_HOME_DIRECTORY}/src/plugins/intel_gpu/src/plugin/transformations/op/fully_connected_compressed.cpp+ ${CMAKE_HOME_DIRECTORY}/src/plugins/intel_gpu/src/plugin/transformations/op/gated_residual.cpp${CMAKE_HOME_DIRECTORY}/src/plugins/intel_gpu/src/plugin/transformations/op/gemm.cpp${CMAKE_HOME_DIRECTORY}/src/plugins/intel_gpu/src/plugin/transformations/op/grouped_space_to_depth.cpp${CMAKE_HOME_DIRECTORY}/src/plugins/intel_gpu/src/plugin/transformations/op/indirect_gemm.cppdiff --git a/src/plugins/intel_gpu/tests/unit/test_cases/gated_residual_gpu_test.cpp b/src/plugins/intel_gpu/tests/unit/test_cases/gated_residual_gpu_test.cppnew file mode 100644index 00000000000..d0fa4cd6a34--- /dev/null+++ b/src/plugins/intel_gpu/tests/unit/test_cases/gated_residual_gpu_test.cpp@@ -0,0 +1,2147 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//+// Unit tests for the gated_residual primitive.+//+// Covered:+// - READ / MIX: per-branch, per-channel comparison with an FP32 reference, including+// the branch-wise grouped RMSNorm, the 1/C inside SiLU(W_down * Rbar / C) and the+// branch mean;+// - the optional write gate produced by READ: 2 * sigmoid(W_inject * Rbar / C), and+// that it stays inside (0, 2);+// - WRITE / COMBINE: R'_c = R_c + S_c * Y for both in-place and out-of-place buffers;+// - the READ without a write gate, which is the model-tail mixer that replaces the usual final norm.++#include <algorithm>+#include <cmath>+#include <cstddef>+#include <intel_gpu/primitives/data.hpp>+#include <intel_gpu/primitives/gated_residual.hpp>+#include <intel_gpu/primitives/input_layout.hpp>+#include <iostream>+#include <memory>+#include <random>+#include <sstream>+#include <string>+#include <tuple>+#include <vector>++#include "gated_residual_inst.h"+#include "intel_gpu/op/gated_residual.hpp"+#include "intel_gpu/plugin/remote_context.hpp"+#include "intel_gpu/plugin/transformations_pipeline.hpp"+#include "intel_gpu/primitives/gated_residual_caps.hpp"+#include "intel_gpu/runtime/debug_configuration.hpp"+#include "intel_gpu/runtime/device_query.hpp"+#include "openvino/op/add.hpp"+#include "openvino/op/constant.hpp"+#include "openvino/op/convert.hpp"+#include "openvino/op/divide.hpp"+#include "openvino/op/matmul.hpp"+#include "openvino/op/multiply.hpp"+#include "openvino/op/parameter.hpp"+#include "openvino/op/power.hpp"+#include "openvino/op/reduce_mean.hpp"+#include "openvino/op/reduce_sum.hpp"+#include "openvino/op/reshape.hpp"+#include "openvino/op/result.hpp"+#include "openvino/op/sigmoid.hpp"+#include "openvino/op/sqrt.hpp"+#include "openvino/op/subtract.hpp"+#include "openvino/op/swish.hpp"+#include "openvino/runtime/core.hpp"+#include "random_generator.hpp"+#include "test_utils.h"++using namespace cldnn;+using namespace ::tests;+namespace caps = cldnn::gated_residual_caps;++namespace {++constexpr size_t kBranches = 4;++/// The device of the test engine (--device_suffix) for tests that compile through ov::Core.+std::string test_device_name() {+ const int id = cldnn::device_query::device_id;+ return id >= 0 ? "GPU." + std::to_string(id) : "GPU";+}+bool gr_available() {+ return caps::is_device_supported(get_test_engine().get_device_info());+}++/// The test networks' config after finalization, i.e. with the GPU_GR_* debug options read from the environment.+ExecutionConfig finalized_test_config() {+ auto& engine = get_test_engine();+ ExecutionConfig config = get_test_default_config(engine);+ config.finalize(engine);+ return config;+}++bool gr_systolic() {+ return caps::uses_dpas_kernels(get_test_engine().get_device_info(), finalized_test_config());+}++float sigmoidf(float x) {+ return 1.0f / (1.0f + std::exp(-x));+}++struct gr_ref_params {+ size_t rows = 0;+ size_t C = kBranches;+ size_t D = 0;+ size_t L = 0;+ float eps = 1e-6f;+};++/// Reference branch-wise grouped RMSNorm: each branch normalizes over its own D channels.+std::vector<float> reference_rbar(const gr_ref_params& p, const std::vector<float>& residual, const std::vector<float>& gain) {+ std::vector<float> rbar(p.rows * p.C * p.D, 0.0f);+ for (size_t row = 0; row < p.rows; row++) {+ for (size_t c = 0; c < p.C; c++) {+ double sumsq = 0.0;+ for (size_t d = 0; d < p.D; d++) {+ const float v = residual[row * p.C * p.D + c * p.D + d];+ sumsq += static_cast<double>(v) * v;+ }+ const float inv = 1.0f / std::sqrt(static_cast<float>(sumsq / p.D) + p.eps);+ for (size_t d = 0; d < p.D; d++) {+ const size_t idx = row * p.C * p.D + c * p.D + d;+ const float g = gain[c * p.D + d];+ rbar[idx] = residual[idx] * inv * g;+ }+ }+ }+ return rbar;+}++void reference_read(const gr_ref_params& p,+ const std::vector<float>& residual,+ const std::vector<float>& gain,+ const std::vector<float>& w_down, // [L, C*D]+ const std::vector<float>& w_up, // [C*D, L]+ const std::vector<float>* w_inject, // [C, C*D] or null+ std::vector<float>& mixed,+ std::vector<float>& write_gate) {+ const auto rbar = reference_rbar(p, residual, gain);+ const size_t CD = p.C * p.D;+ const float inv_c = 1.0f / static_cast<float>(p.C);++ mixed.assign(p.rows * p.D, 0.0f);+ if (w_inject != nullptr) {+ write_gate.assign(p.rows * p.C, 0.0f);+ }++ for (size_t row = 0; row < p.rows; row++) {+ const float* rb = rbar.data() + row * CD;++ std::vector<float> t(p.L, 0.0f);+ for (size_t l = 0; l < p.L; l++) {+ double acc = 0.0;+ for (size_t k = 0; k < CD; k++) {+ acc += static_cast<double>(w_down[l * CD + k]) * rb[k];+ }+ const float x = static_cast<float>(acc) * inv_c;+ t[l] = x * sigmoidf(x); // SiLU+ }++ for (size_t d = 0; d < p.D; d++) {+ double acc = 0.0;+ for (size_t c = 0; c < p.C; c++) {+ double logit = 0.0;+ for (size_t l = 0; l < p.L; l++) {+ logit += static_cast<double>(w_up[(c * p.D + d) * p.L + l]) * t[l];+ }+ acc += static_cast<double>(sigmoidf(static_cast<float>(logit))) * rb[c * p.D + d];+ }+ mixed[row * p.D + d] = static_cast<float>(acc) * inv_c;+ }++ if (w_inject != nullptr) {+ for (size_t c = 0; c < p.C; c++) {+ double acc = 0.0;+ for (size_t k = 0; k < CD; k++) {+ acc += static_cast<double>((*w_inject)[c * CD + k]) * rb[k];+ }+ write_gate[row * p.C + c] = 2.0f * sigmoidf(static_cast<float>(acc) * inv_c);+ }+ }+ }+}++std::vector<ov::float16> to_f16(const std::vector<float>& src) {+ std::vector<ov::float16> dst(src.size());+ for (size_t i = 0; i < src.size(); i++) {+ dst[i] = ov::float16(src[i]);+ }+ return dst;+}++/// tests::random_generator only accepts integer bounds, so values are drawn from+/// [-1, 1] with 1/16 resolution and rescaled/shifted here.+std::vector<float> random_vec(tests::random_generator& rg, size_t count, float scale, float bias = 0.0f) {+ auto v = rg.generate_random_1d<float>(count, -1, 1, 16);+ std::vector<float> out(v.begin(), v.end());+ for (auto& x : out) {+ x = x * scale + bias;+ }+ return out;+}++memory::ptr make_f16(engine& eng, const ov::PartialShape& shape, const std::vector<float>& data) {+ auto mem = eng.allocate_memory(layout{shape, data_types::f16, format::bfyx});+ set_values(mem, to_f16(data));+ return mem;+}++/// Stages the last execution of `id` dispatched, named after their kernels' entry points.+std::vector<std::string> executed_stages(network& net, const primitive_id& id) {+ const auto inst = net.get_primitive(id);+ std::istringstream entries(inst->get_impl()->get_kernels_dump_info(*inst->get_impl_params()).get_entries());+ std::vector<std::string> names;+ for (std::string kernel; entries >> kernel;) {+ auto starts_with = [&](const char* prefix) {+ return kernel.rfind(prefix, 0) == 0;+ };+ if (starts_with("gr_write_")) {+ names.emplace_back("WRITE");+ } else if (starts_with("gr_read_pipeline_rbar")) {+ names.emplace_back("RBAR");+ } else if (starts_with("gr_read_pipeline_down")) {+ names.emplace_back("DOWN_PROJ");+ } else if (starts_with("gr_read_pipeline_up")) {+ names.emplace_back("UP_PROJ");+ } else if (starts_with("gr_read_pipeline_gate")) {+ names.emplace_back("GATE");+ } else if (starts_with("gr_read_dpas_")) {+ names.emplace_back("READ_DPAS");+ } else if (starts_with("gr_read_")) {+ names.emplace_back("READ");+ } else if (starts_with("gr_common_")) {+ names.emplace_back("DEQUANT");+ } else {+ names.push_back(kernel);+ }+ }+ return names;+}++/// With C = 4, C*D is always a multiple of 64, so only L decides the DPAS READ path. Above+/// 4 rows per EU (and D % 32 == 0) the single-kernel gr_read_dpas.cl replaces the 3-kernel+/// pipeline, whose DOWN_PROJ carries the write gate and UP_PROJ the branch mix. Devices without Xe2+ systolic+/// arrays always run the scalar gr_read.cl.+std::vector<std::string> pipeline_stages() {+ return {"RBAR", "DOWN_PROJ", "UP_PROJ"};+}++std::vector<std::string> expected_read_stages(size_t rows, size_t D, size_t L) {+ if (!caps::uses_dpas_read(L, gr_systolic())) {+ return {"READ"};+ }+ const size_t eu = get_test_engine().get_device_info().execution_units_count;+ if (D % 32 == 0 && rows > 4 * eu) {+ return {"READ_DPAS"};+ }+ return pipeline_stages();+}++struct gr_read_case {+ size_t rows;+ size_t D;+ size_t L;+ bool produce_write_gate;+ bool is_caching_test = false;+};++class gated_residual_read_test : public ::testing::TestWithParam<gr_read_case> {};++TEST_P(gated_residual_read_test, matches_fp32_reference) {+ if (!gr_available()) {+ GTEST_SKIP() << "no GatedResidual implementation is available on this device";+ }++ const auto tc = GetParam();+ if (!caps::is_geometry_supported(gated_residual::Mode::READ, 4, tc.D, tc.L, gr_systolic())) {+ GTEST_SKIP() << "the geometry needs the systolic READ kernels";+ }+ gr_ref_params p;+ p.rows = tc.rows;+ p.D = tc.D;+ p.L = tc.L;++ tests::random_generator rg;+ rg.set_seed(GET_SUITE_NAME);++ const size_t CD = p.C * p.D;+ const auto residual = random_vec(rg, p.rows * CD, 1.0f);+ // Gain in [0.5, 1.5].+ const auto gain = random_vec(rg, CD, 0.5f, 1.0f);+ const auto w_down = random_vec(rg, p.L * CD, 0.1f);+ const auto w_up = random_vec(rg, CD * p.L, 0.1f);+ const auto w_inject = random_vec(rg, p.C * CD, 0.1f);++ std::vector<float> ref_mixed;+ std::vector<float> ref_gate;+ reference_read(p, residual, gain, w_down, w_up, tc.produce_write_gate ? &w_inject : nullptr, ref_mixed, ref_gate);++ auto& engine = get_test_engine();+ auto residual_mem = make_f16(engine, {static_cast<int64_t>(p.rows), static_cast<int64_t>(CD)}, residual);+ auto gain_mem = make_f16(engine, {static_cast<int64_t>(CD)}, gain);+ auto wdown_mem = make_f16(engine, {static_cast<int64_t>(p.L), static_cast<int64_t>(CD)}, w_down);+ auto wup_mem = make_f16(engine, {static_cast<int64_t>(CD), static_cast<int64_t>(p.L)}, w_up);+ auto winject_mem = make_f16(engine, {static_cast<int64_t>(p.C), static_cast<int64_t>(CD)}, w_inject);++ topology topology;+ topology.add(input_layout("residual", residual_mem->get_layout()));+ topology.add(data("gain", gain_mem));+ topology.add(data("w_down", wdown_mem));+ topology.add(data("w_up", wup_mem));++ std::vector<input_info> inputs = {input_info("residual"), input_info("gain"), input_info("w_down"), input_info("w_up")};+ if (tc.produce_write_gate) {+ topology.add(data("w_inject", winject_mem));+ inputs.emplace_back("w_inject");+ }++ gated_residual prim("gr_read", inputs, gated_residual::Mode::READ, p.C, p.D, p.L, p.eps, tc.produce_write_gate);+ topology.add(prim);++ ExecutionConfig config = get_test_default_config(engine);+ config.set_property(ov::intel_gpu::optimize_data(true));+ config.set_property(ov::intel_gpu::allow_new_shape_infer(true));+ network::ptr network = get_network(engine, topology, config, get_test_stream_ptr(), tc.is_caching_test);+ network->set_input_data("residual", residual_mem);++ auto outputs = network->execute();+ ASSERT_TRUE(outputs.count("gr_read") > 0);++ cldnn::mem_lock<ov::float16> mixed_out(outputs.at("gr_read").get_memory(), get_test_stream());+ EXPECT_EQ(executed_stages(*network, "gr_read"), expected_read_stages(p.rows, p.D, p.L));+ ASSERT_EQ(mixed_out.size(), ref_mixed.size());+ float mixed_err = 0.0f;+ for (size_t i = 0; i < ref_mixed.size(); i++) {+ ASSERT_NEAR(static_cast<float>(mixed_out[i]), ref_mixed[i], 2e-2f) << "mixed mismatch at " << i;+ mixed_err = std::max(mixed_err, std::abs(static_cast<float>(mixed_out[i]) - ref_mixed[i]));+ }+ std::cout << "GR_F16_ACC rows=" << p.rows << " D=" << p.D << " L=" << p.L << " err_vs_fp32_ref=" << mixed_err;++ if (tc.produce_write_gate) {+ // Secondary outputs are reached through the instance, not the result map.+ auto inst = network->get_primitive("gr_read");+ cldnn::mem_lock<ov::float16> gate_out(inst->output_memory_ptr(1), get_test_stream());+ ASSERT_EQ(gate_out.size(), ref_gate.size());+ float gate_err = 0.0f;+ for (size_t i = 0; i < ref_gate.size(); i++) {+ const float v = static_cast<float>(gate_out[i]);+ // 2 * sigmoid(x) lives in (0, 2); a (0, 1) clamp would be a semantic bug.+ ASSERT_GT(v, 0.0f);+ ASSERT_LT(v, 2.0f);+ ASSERT_NEAR(v, ref_gate[i], 2e-2f) << "write gate mismatch at " << i;+ gate_err = std::max(gate_err, std::abs(v - ref_gate[i]));+ }+ std::cout << " gate_err_vs_fp32_ref=" << gate_err;+ }+ std::cout << std::endl;+}++INSTANTIATE_TEST_SUITE_P(smoke,+ gated_residual_read_test,+ ::testing::Values(gr_read_case{1, 64, 16, false},+ gr_read_case{1, 64, 16, true},+ gr_read_case{7, 128, 32, true},+ gr_read_case{16, 32, 16, true},+ // Below: C*D and L allow the dpas paths, so these route+ // through RBAR -> DOWN_PROJ[+write gate] ->+ // UP_PROJ[+branch mix] instead of gr_read.cl. Up to 32+ // rows the decode tiling is used, up to 4 rows per EU the mid+ // (split-K wide) tiling, above it the wide one.+ gr_read_case{32, 64, 32, true}, // exact token-tile boundary+ gr_read_case{37, 96, 32, false}, // partial last token tile, no write gate+ gr_read_case{41, 48, 64, true}, // partial tile; D=48, split-K over 6 K steps+ gr_read_case{48, 64, 32, false}, // three full N-tiles+ gr_read_case{3, 32, 32, true}, // narrowest D+ gr_read_case{1, 640, 320, true}, // production width, decode+ gr_read_case{17, 640, 320, true}, // production width, prefill with a partial tile+ gr_read_case{193, 32, 32, true}, // mid tiling+ gr_read_case{200, 64, 32, true}, // mid tiling, partial 32-token tile+ gr_read_case{300, 48, 64, false}, // mid tiling, D=48 column tiles+ gr_read_case{17, 2560, 320, true}, // wide, decode tiling+ gr_read_case{1, 5120, 640, true}, // wider (C*D > 16384, L > 512), decode+ gr_read_case{17, 5120, 640, true}, // wider, prefill with a partial tile+ gr_read_case{1000, 64, 32, true}, // wide tiling / single kernel (> 4 rows per EU)+ gr_read_case{777, 48, 64, false}, // wide tiling, partial tiles (D % 32 != 0)+ gr_read_case{1111, 128, 64, true}, // single kernel, partial 32-row tile+ // L=16 keeps these on gr_read.cl; above 32 rows one work-group owns+ // several rows, the last group only partially filled.+ gr_read_case{37, 64, 16, true},+ gr_read_case{100, 48, 16, false},+ gr_read_case{65, 2560, 16, true}, // real width: 4 rows per work-group+ // The model tail mixer: READ without a write gate.+ gr_read_case{4, 64, 16, false}, // scalar gr_read+ gr_read_case{17, 64, 32, false}, // DPAS pipeline, decode tiling+ gr_read_case{250, 64, 32, false}, // DPAS pipeline, mid tiling+ gr_read_case{1100, 64, 32, false}, // DPAS pipeline, wide tiling+ // Model cache: the primitive is exported and imported before it runs.+ gr_read_case{19, 64, 32, true, true}, // DPAS pipeline with a write gate (two outputs)+ gr_read_case{5, 64, 16, true, true}, // scalar gr_read+ gr_read_case{1000, 64, 32, false, true}, // single kernel+ gr_read_case{1, 640, 320, true, true})); // decode tiling++// --- compressed weights: u4 (group 32) / u8 (per-channel), asymmetric ------------------------------------------------------++bool gr_compression_available() {+ return gr_systolic();+}++/// One quantized [N, K] weight matrix with its [G, N] scale / optional zp and the exact f16 tensor the decompression graph produces.+struct quant_matrix {+ size_t N = 0;+ size_t K = 0;+ size_t G = 0;+ bool u4 = false; // 4-bit (group 32), otherwise 8-bit (per-channel)+ bool is_signed = false;+ bool has_zp = true;+ std::vector<uint8_t> q; // [N * K] raw element bits (two's complement for the signed types)+ std::vector<uint8_t> zp; // [G * N] raw element bits, empty without zero points+ std::vector<float> scale; // [G * N], f16 values+ std::vector<float> dequant; // [N * K] = half(half(q - zp) * scale)++ data_types type() const {+ return u4 ? (is_signed ? data_types::i4 : data_types::u4) : (is_signed ? data_types::i8 : data_types::u8);+ }++ int value(uint8_t raw) const {+ if (!is_signed) {+ return raw;+ }+ return u4 ? static_cast<int>(raw ^ 8) - 8 : static_cast<int>(static_cast<int8_t>(raw));+ }+};++/// group == 0: the default of the bit width (32 for 4-bit, per-channel for 8-bit); kPerChannel: group size == K; otherwise the+/// requested group size when it divides K, else the default (W_up has a different K than W_down / W_inject).+constexpr size_t kPerChannel = static_cast<size_t>(-1);++quant_matrix make_quant_matrix(std::mt19937& gen, size_t N, size_t K, bool u4, bool is_signed = false, bool has_zp = true, size_t group = 0) {+ quant_matrix m;+ m.N = N;+ m.K = K;+ m.u4 = u4;+ m.is_signed = is_signed;+ m.has_zp = has_zp;+ size_t gs = u4 ? 32 : K;+ if (group == kPerChannel) {+ gs = K;+ } else if (group != 0 && K % group == 0) {+ gs = group;+ }+ m.G = K / gs;+ m.q.resize(N * K);+ m.zp.resize(has_zp ? m.G * N : 0);+ m.scale.resize(m.G * N);+ m.dequant.resize(N * K);+ // unsigned weights without a zero point are all positive: a smaller scale keeps the activations in the f16 range+ const float scale_div = (!has_zp && !is_signed ? 8.0f : 1.0f) * (u4 ? 512.0f : 2048.0f);+ for (size_t i = 0; i < m.G * N; i++) {+ if (has_zp) {+ if (u4) {+ m.zp[i] = static_cast<uint8_t>(gen() % 16);+ } else {+ m.zp[i] = is_signed ? static_cast<uint8_t>(static_cast<int8_t>(static_cast<int>(gen() % 60) - 30)) : static_cast<uint8_t>(100 + gen() % 60);+ }+ }+ m.scale[i] = static_cast<float>(ov::float16(static_cast<float>(1 + gen() % 8) / scale_div));+ }+ for (size_t n = 0; n < N; n++) {+ for (size_t k = 0; k < K; k++) {+ const size_t g = k / gs;+ const uint8_t q = static_cast<uint8_t>(gen() % (u4 ? 16 : 256));+ m.q[n * K + k] = q;+ const int zp = has_zp ? m.value(m.zp[g * N + n]) : 0;+ const float diff = static_cast<float>(ov::float16(static_cast<float>(m.value(q) - zp)));+ m.dequant[n * K + k] = static_cast<float>(ov::float16(diff * m.scale[g * N + n]));+ }+ }+ return m;+}++memory::ptr make_quant_weights(engine& eng, const quant_matrix& m) {+ auto mem = eng.allocate_memory(layout{ov::PartialShape{static_cast<int64_t>(m.N), static_cast<int64_t>(m.K)}, m.type(), format::bfyx});+ cldnn::mem_lock<uint8_t> lock(mem, get_test_stream());+ if (m.u4) {+ for (size_t i = 0; i < m.q.size(); i += 2) {+ lock[i / 2] = static_cast<uint8_t>((m.q[i] & 0xF) | (m.q[i + 1] << 4)); // low nibble = even k+ }+ } else {+ std::copy(m.q.begin(), m.q.end(), lock.begin());+ }+ return mem;+}++memory::ptr make_quant_zp(engine& eng, const quant_matrix& m) {+ auto mem = eng.allocate_memory(layout{ov::PartialShape{static_cast<int64_t>(m.G), static_cast<int64_t>(m.N)}, m.type(), format::bfyx});+ cldnn::mem_lock<uint8_t> lock(mem, get_test_stream());+ if (m.u4) {+ for (size_t i = 0; i < m.zp.size(); i += 2) {+ lock[i / 2] = static_cast<uint8_t>((m.zp[i] & 0xF) | (m.zp[i + 1] << 4)); // low nibble = even index+ }+ } else {+ std::copy(m.zp.begin(), m.zp.end(), lock.begin());+ }+ return mem;+}++/// f16 scale tensor [G, N] of a quantized matrix.+memory::ptr make_quant_scale(engine& eng, const quant_matrix& m) {+ return make_f16(eng, {static_cast<int64_t>(m.G), static_cast<int64_t>(m.N)}, m.scale);+}++struct gr_run_result {+ std::vector<ov::float16> mixed;+ std::vector<ov::float16> gate; // only with a write gate+ std::vector<std::string> stages;+};++/// Runs a READ gated_residual whose weight inputs (from index 2 on) are the given memories. With `write_gate` the+/// last inputs are W_inject (f16, or compressed followed by its scale and optional zp) and output 1 is read back.+gr_run_result run_gr_read(const gr_ref_params& p,+ const std::vector<float>& residual,+ const std::vector<float>& gain,+ const std::vector<memory::ptr>& weights,+ bool write_gate = false,+ const std::string& path = "",+ bool is_caching_test = false) {+ auto& engine = get_test_engine();+ const size_t CD = p.C * p.D;+ auto residual_mem = make_f16(engine, {static_cast<int64_t>(p.rows), static_cast<int64_t>(CD)}, residual);+ topology topology;+ topology.add(input_layout("residual", residual_mem->get_layout()));+ topology.add(data("gain", make_f16(engine, {static_cast<int64_t>(CD)}, gain)));+ std::vector<input_info> inputs = {input_info("residual"), input_info("gain")};+ for (size_t i = 0; i < weights.size(); i++) {+ const std::string id = "w" + std::to_string(i);+ topology.add(data(id, weights[i]));+ inputs.emplace_back(id);+ }+ topology.add(gated_residual("gr", inputs, gated_residual::Mode::READ, p.C, p.D, p.L, p.eps, write_gate));++ ExecutionConfig config = get_test_default_config(engine);+ config.set_property(ov::intel_gpu::optimize_data(true));+ config.set_property(ov::intel_gpu::allow_new_shape_infer(true));+#ifdef GPU_DEBUG_CONFIG+ if (!path.empty()) {+ config.set_property(ov::intel_gpu::gr_kernel_selection(path));+ }+#endif+ network::ptr network = get_network(engine, topology, config, get_test_stream_ptr(), is_caching_test);+ network->set_input_data("residual", residual_mem);+ auto outputs = network->execute();+ gr_run_result result;+ cldnn::mem_lock<ov::float16> out(outputs.at("gr").get_memory(), get_test_stream());+ result.mixed.assign(out.begin(), out.end());+ if (write_gate) {+ cldnn::mem_lock<ov::float16> gate(network->get_primitive("gr")->output_memory_ptr(1), get_test_stream());+ result.gate.assign(gate.begin(), gate.end());+ }+ result.stages = executed_stages(*network, "gr");+ return result;+}++struct gr_quant_case {+ size_t rows;+ size_t D;+ size_t L;+ bool u4; // 4-bit weights, otherwise 8-bit+ bool write_gate = false;+ bool is_signed = false;+ bool has_zp = true;+ size_t group = 0; // see make_quant_matrix+ bool scalar = false; // the scalar gr_read.cl (GPU_GR_KERNEL_SELECTION=scalar), which dequantizes in registers too+ bool is_caching_test = false;+};++size_t scratch_limit_bytes() {+ return GPU_DEBUG_VALUE_OR(finalized_test_config().get_gr_scratch_limit_mb(), size_t{256}) << 20;+}++size_t pd_min_rows() {+ const int64_t rows = GPU_DEBUG_VALUE_OR(finalized_test_config().get_gr_pd_row_threshold(), int64_t{-1});+ return rows >= 0 ? static_cast<size_t>(rows) : 5 * static_cast<size_t>(get_test_engine().get_device_info().execution_units_count);+}++class gated_residual_quant_test : public ::testing::TestWithParam<gr_quant_case> {};++/// Largest |a - b| over two equally long vectors.+template <typename T>+float max_abs_diff(const std::vector<T>& a, const std::vector<float>& b) {+ float m = 0.0f;+ for (size_t i = 0; i < b.size(); i++) {+ m = std::max(m, std::abs(static_cast<float>(a[i]) - b[i]));+ }+ return m;+}++// The kernels dequantize in registers with the arithmetic of the decompression graph, so the result must equal the f16 path+// fed with the decompressed weights bit for bit (same tiling, same accumulation order), and match the fp32 reference.+TEST_P(gated_residual_quant_test, matches_decompressed_f16_path) {+ const auto tc = GetParam();+ if (!(tc.scalar ? gr_available() : gr_compression_available())) {+ GTEST_SKIP() << "compressed GatedResidual weights need an Xe2+ systolic GPU or the scalar kernel";+ }+#ifndef GPU_DEBUG_CONFIG+ if (tc.scalar) {+ GTEST_SKIP() << "GPU_GR_KERNEL_SELECTION is a debug option";+ }+#endif+ gr_ref_params p;+ p.rows = tc.rows;+ p.D = tc.D;+ p.L = tc.L;+ const size_t CD = p.C * p.D;++ tests::random_generator rg;+ rg.set_seed(GET_SUITE_NAME);+ std::mt19937 gen(1234 + static_cast<uint32_t>(tc.rows * 7 + tc.D + tc.L + (tc.u4 ? 1 : 0) + (tc.is_signed ? 2 : 0) + (tc.has_zp ? 0 : 4) + tc.group));+ const auto residual = random_vec(rg, p.rows * CD, 1.0f);+ const auto gain = random_vec(rg, CD, 0.5f, 1.0f);+ const auto wd = make_quant_matrix(gen, p.L, CD, tc.u4, tc.is_signed, tc.has_zp, tc.group);+ const auto wu = make_quant_matrix(gen, CD, p.L, tc.u4, tc.is_signed, tc.has_zp, tc.group);+ // W_inject: C rows only, compressed like W_down / W_up+ const auto wi = make_quant_matrix(gen, p.C, CD, tc.u4, tc.is_signed, tc.has_zp, tc.group);++ auto& engine = get_test_engine();+ std::vector<memory::ptr> f16_weights = {make_f16(engine, {static_cast<int64_t>(p.L), static_cast<int64_t>(CD)}, wd.dequant),+ make_f16(engine, {static_cast<int64_t>(CD), static_cast<int64_t>(p.L)}, wu.dequant)};+ std::vector<memory::ptr> q_weights = {make_quant_weights(engine, wd),+ make_quant_weights(engine, wu),+ make_quant_scale(engine, wd),+ make_quant_scale(engine, wu)};+ if (tc.has_zp) {+ q_weights.push_back(make_quant_zp(engine, wd));+ q_weights.push_back(make_quant_zp(engine, wu));+ }+ if (tc.write_gate) {+ f16_weights.push_back(make_f16(engine, {static_cast<int64_t>(p.C), static_cast<int64_t>(CD)}, wi.dequant));+ q_weights.push_back(make_quant_weights(engine, wi));+ q_weights.push_back(make_quant_scale(engine, wi));+ if (tc.has_zp) {+ q_weights.push_back(make_quant_zp(engine, wi));+ }+ }+ const auto f16_run = run_gr_read(p, residual, gain, f16_weights, tc.write_gate, tc.scalar ? "scalar" : "", tc.is_caching_test);+ const auto q_run = run_gr_read(p, residual, gain, q_weights, tc.write_gate, tc.scalar ? "scalar" : "", tc.is_caching_test);++ // compressed weights use the 3-dispatch pipeline unless its Rbar scratch exceeds the limit+ const auto expected = tc.scalar ? std::vector<std::string>{"READ"} : expected_read_stages(p.rows, p.D, p.L);+ EXPECT_EQ(f16_run.stages, expected);+ const bool single_q = p.D % 32 == 0 && p.rows * p.C * p.D * 2 > scratch_limit_bytes();+ // The compressed single kernel has no write-gate tile: with a write gate that regime predequantizes as well.+ const bool predequant = p.rows > pd_min_rows() || (tc.write_gate && single_q);+ std::vector<std::string> expected_q;+ if (tc.scalar) {+ // one kernel, the weights are dequantized in registers+ expected_q = expected;+ } else if (predequant) {+ // both matrices (and W_inject) are dequantized into f16 scratch and the f16 kernels (f16 routing) run on them+ expected_q = {"DEQUANT", "DEQUANT"};+ if (tc.write_gate) {+ expected_q.emplace_back("DEQUANT");+ }+ expected_q.insert(expected_q.end(), expected.begin(), expected.end());+ } else if (single_q) {+ expected_q = {"READ_DPAS"};+ } else if (p.rows <= 32) {+ // decode: the write gate is a column tile of the compressed DOWN_PROJ+ expected_q = pipeline_stages();+ } else {+ // W_inject is dequantized first; the write gate is its own dispatch between RBAR and DOWN_PROJ+ if (tc.write_gate) {+ expected_q.emplace_back("DEQUANT");+ }+ expected_q.emplace_back("RBAR");+ if (tc.write_gate) {+ expected_q.emplace_back("GATE");+ }+ expected_q.insert(expected_q.end(), {"DOWN_PROJ", "UP_PROJ"});+ }+ EXPECT_EQ(q_run.stages, expected_q);++ std::vector<float> ref_mixed;+ std::vector<float> ref_gate;+ reference_read(p, residual, gain, wd.dequant, wu.dequant, tc.write_gate ? &wi.dequant : nullptr, ref_mixed, ref_gate);+ ASSERT_EQ(q_run.mixed.size(), ref_mixed.size());+ ASSERT_EQ(f16_run.mixed.size(), ref_mixed.size());+ // The compressed kernels share work differently (split-K factors, single kernel vs pipeline), so only the accumulation+ // order differs from the f16 path fed with the decompressed weights: the results agree to a few f16 ulps.+ size_t bit_diffs = 0;+ float max_diff = 0.0f;+ for (size_t i = 0; i < ref_mixed.size(); i++) {+ ASSERT_NEAR(static_cast<float>(q_run.mixed[i]), ref_mixed[i], 2e-2f) << "mixed mismatch at " << i;+ bit_diffs += q_run.mixed[i].to_bits() != f16_run.mixed[i].to_bits() ? 1 : 0;+ max_diff = std::max(max_diff, std::abs(static_cast<float>(q_run.mixed[i]) - static_cast<float>(f16_run.mixed[i])));+ }+ std::cout << "GR_QUANT_ACC rows=" << p.rows << " D=" << p.D << " L=" << p.L << " " << (tc.is_signed ? "i" : "u") << (tc.u4 ? "4" : "8")+ << " g_down=" << CD / wd.G << " g_up=" << p.L / wu.G << (tc.has_zp ? "" : " nozp") << (tc.write_gate ? " gate" : "")+ << " differing_elems=" << bit_diffs << "/" << ref_mixed.size() << " max_abs_diff_vs_f16=" << max_diff+ << " err_vs_fp32_ref: f16=" << max_abs_diff(f16_run.mixed, ref_mixed) << " q=" << max_abs_diff(q_run.mixed, ref_mixed);+ if (tc.write_gate) {+ std::cout << " gate_f16=" << max_abs_diff(f16_run.gate, ref_gate) << " gate_q=" << max_abs_diff(q_run.gate, ref_gate);+ }+ std::cout << std::endl;+ // the scalar kernel runs the same code on both inputs: bit-exact+ EXPECT_LE(max_diff, tc.scalar ? 0.0f : 4e-3f) << "compressed and decompressed-f16 outputs differ";++ if (tc.write_gate) {+ ASSERT_EQ(q_run.gate.size(), ref_gate.size());+ ASSERT_EQ(f16_run.gate.size(), ref_gate.size());+ float gate_diff = 0.0f;+ for (size_t i = 0; i < ref_gate.size(); i++) {+ const float v = static_cast<float>(q_run.gate[i]);+ // 2 * sigmoid(x) lives in [0, 2] (f16 rounds a saturated gate to the bound); a (0, 1) clamp would be a semantic bug.+ ASSERT_GE(v, 0.0f);+ ASSERT_LE(v, 2.0f);+ ASSERT_NEAR(v, ref_gate[i], 2e-2f) << "write gate mismatch at " << i;+ gate_diff = std::max(gate_diff, std::abs(v - static_cast<float>(f16_run.gate[i])));+ }+ EXPECT_LE(gate_diff, tc.scalar ? 0.0f : 4e-3f) << "compressed and decompressed-f16 write gates differ";+ }+}++// Each kernel route (gemv <= 8 rows, decode, mid, predequantized / single kernel) is covered with the dtype / write-gate / zero-point+// combinations spread over small shapes; production widths only keep a few representative cases.+INSTANTIATE_TEST_SUITE_P(smoke,+ gated_residual_quant_test,+ ::testing::Values(+ // gemv / decode+ gr_quant_case{1, 64, 32, true}, // one K32 group of W_up+ gr_quant_case{1, 64, 32, false, true},+ gr_quant_case{7, 128, 32, true, true},+ gr_quant_case{7, 128, 32, false},+ gr_quant_case{32, 96, 32, true}, // D % 64 != 0: narrow raw loads+ gr_quant_case{37, 96, 64, false, true},+ // mid tiling+ gr_quant_case{33, 128, 64, true, true},+ gr_quant_case{200, 64, 32, false, true},+ gr_quant_case{250, 64, 32, true},+ // single kernel / predequantization+ gr_quant_case{1000, 64, 32, true, true},+ gr_quant_case{1000, 64, 32, false},+ gr_quant_case{1111, 128, 64, true}, // partial 32-row tile+ // production widths+ gr_quant_case{1, 640, 320, true, true},+ gr_quant_case{1, 640, 320, false},+ gr_quant_case{8, 640, 320, true},+ gr_quant_case{8, 640, 320, false, true},+ gr_quant_case{17, 640, 320, true, true},+ gr_quant_case{17, 640, 320, false},+ gr_quant_case{257, 640, 320, false, true}, // mid tiling+ gr_quant_case{700, 640, 320, true},+ gr_quant_case{1, 2560, 320, true, true}, // real width+ gr_quant_case{8, 2560, 320, false},+ gr_quant_case{17, 2560, 320, true, true},+ gr_quant_case{17, 2560, 320, false},+ gr_quant_case{100, 2560, 320, true},+ gr_quant_case{2000, 2560, 320, true, true}, // the only very large cases+ gr_quant_case{2000, 2560, 320, false},+ // RBAR splits the 5120-wide branch rows across subgroups at decode+ gr_quant_case{1, 5120, 640, true, true},+ gr_quant_case{17, 5120, 640, false},+ // signed weights (i4 / i8) with zero points+ gr_quant_case{1, 64, 32, true, false, true},+ gr_quant_case{7, 128, 32, false, true, true},+ gr_quant_case{33, 128, 64, false, false, true},+ gr_quant_case{250, 64, 32, false, true, true},+ gr_quant_case{1000, 64, 32, true, true, true},+ gr_quant_case{17, 640, 320, true, true, true},+ gr_quant_case{1, 2560, 320, false, true, true},+ // no zero points (the zero point is 0), unsigned and signed+ gr_quant_case{1, 64, 32, true, false, false, false},+ gr_quant_case{7, 128, 32, false, true, true, false},+ gr_quant_case{33, 128, 64, true, true, true, false},+ gr_quant_case{250, 64, 32, false, false, false, false},+ gr_quant_case{1000, 64, 32, true, true, true, false},+ gr_quant_case{17, 640, 320, true, true, false, false},+ gr_quant_case{1, 2560, 320, false, true, false, false},+ // Model cache: the primitive is exported and imported before it runs.+ gr_quant_case{17, 640, 320, true, true, false, true, 0, false, true}, // u4 with zero points and a write gate+ gr_quant_case{17, 640, 320, true, false, false, false, 0, false, true}, // u4 without zero points+ gr_quant_case{200, 64, 32, false, true, true, true, 0, false, true}, // i8 with a write gate, mid tiling+ gr_quant_case{1000, 64, 32, true, false, false, true, 0, false, true})); // predequantized weights++/// 32 / 64 / 128 and per-channel group sizes of both bit widths on every kernel path; W_up keeps the default group size when it does+/// not divide its K (= L).+std::vector<gr_quant_case> group_size_cases() {+ struct shape {+ size_t rows;+ size_t D;+ size_t L;+ bool write_gate;+ };+ // gemv, mid (shared dequantization), predequantized, production widths: the group size only changes the dequantization+ const std::vector<shape> shapes = {{1, 64, 32, false}, {33, 128, 64, true}, {17, 640, 320, false}, {1000, 64, 32, false}, {1, 2560, 320, true}};+ std::vector<gr_quant_case> cases;+ for (const size_t group : {size_t{32}, size_t{64}, size_t{128}, kPerChannel}) {+ for (const bool u4 : {true, false}) {+ for (const auto& s : shapes) {+ // The bit width's default group size is already exercised by the main list.+ const bool is_default = (group == 32 && u4) || (group == kPerChannel && !u4);+ if (is_default) {+ continue;+ }+ cases.push_back({s.rows, s.D, s.L, u4, s.write_gate, false, true, group});+ }+ }+ }+ // signed weights and weights without zero points+ for (const size_t group : {size_t{64}, size_t{128}}) {+ for (const bool u4 : {true, false}) {+ cases.push_back({17, 640, 320, u4, true, true, false, group});+ cases.push_back({1, 2560, 320, u4, false, true, true, group});+ }+ }+ // L = 640 divides by 64 / 128, so W_up really uses the group size too instead of falling back to the default+ for (const size_t group : {size_t{64}, size_t{128}}) {+ for (const bool u4 : {true, false}) {+ for (const size_t rows : {size_t{1}, size_t{17}, size_t{1000}}) {+ cases.push_back({rows, 640, 640, u4, true, false, true, group});+ }+ }+ }+ return cases;+}++INSTANTIATE_TEST_SUITE_P(smoke_group_sizes, gated_residual_quant_test, ::testing::ValuesIn(group_size_cases()));++/// The scalar gr_read.cl (GPU_GR_KERNEL_SELECTION=scalar, as on a device without systolic arrays) dequantizes in registers too: both weight+/// widths, group sizes, zero points, signedness and the compressed write gate (L <= 512, C * D <= 16384).+std::vector<gr_quant_case> scalar_cases() {+ std::vector<gr_quant_case> cases;+ for (const bool u4 : {true, false}) {+ for (const size_t rows : {size_t{1}, size_t{20}}) {+ for (const size_t group : {size_t{0}, size_t{64}, kPerChannel}) {+ cases.push_back({rows, 128, 64, u4, false, false, true, group, true});+ }+ }+ // write gate, signed weights, no zero points, a partial row tile+ cases.push_back({5, 64, 32, u4, true, false, true, 0, true});+ cases.push_back({20, 96, 64, u4, true, true, false, 0, true});+ cases.push_back({9, 64, 32, u4, false, true, true, 0, true});+ cases.push_back({33, 48, 32, u4, false, false, false, 0, true});+ // production widths+ cases.push_back({17, 640, 320, u4, true, false, true, 0, true});+ cases.push_back({40, 2560, 320, u4, false, true, true, 0, true});+ }+ return cases;+}++INSTANTIATE_TEST_SUITE_P(smoke_scalar, gated_residual_quant_test, ::testing::ValuesIn(scalar_cases()));++/// R'_c = R_c + S_c * Y+std::vector<float> reference_write(size_t rows,+ size_t C,+ size_t D,+ const std::vector<float>& residual,+ const std::vector<float>& y,+ const std::vector<float>& gate) {+ const size_t CD = C * D;+ std::vector<float> ref(rows * CD, 0.0f);+ for (size_t row = 0; row < rows; row++) {+ for (size_t c = 0; c < C; c++) {+ for (size_t d = 0; d < D; d++) {+ ref[row * CD + c * D + d] = residual[row * CD + c * D + d] + gate[row * C + c] * y[row * D + d];+ }+ }+ }+ return ref;+}++// --- input range and JIT constants: every READ route against the fp32 reference ----------------------------------------------++/// kConst256: residual = gain = 256 with zero weights, i.e. mixed = 0.5 * Rbar = 128 and write gate = 1 exactly, while R * gain+/// (65536) does not fit in half. kLarge: random residual up to 2048 and gain in [24, 40], R * gain up to ~82k, random weights.+enum class GrInput { kNormal, kLarge, kConst256 };++struct gr_range_case {+ size_t rows; // 0: enough rows for the single kernel (also above the compressed predequantization threshold)+ size_t L; // 16 keeps the scalar gr_read.cl+ bool write_gate;+ bool u4; // compressed W_down / W_up / W_inject (u4, group 32, zp), otherwise f16+ GrInput input;+ float eps;+ std::string path; // GPU_GR_KERNEL_SELECTION, empty = automatic routing+};++class gated_residual_read_range_test : public ::testing::TestWithParam<gr_range_case> {};++TEST_P(gated_residual_read_range_test, matches_fp32_reference) {+ const auto tc = GetParam();+ if (!(tc.u4 ? gr_compression_available() : gr_available())) {+ GTEST_SKIP() << "GatedResidual (with compressed weights) is not available on this device";+ }+#ifndef GPU_DEBUG_CONFIG+ if (!tc.path.empty()) {+ GTEST_SKIP() << "GPU_GR_KERNEL_SELECTION is a debug option";+ }+#endif+ const size_t D = 64;+ if (!caps::is_geometry_supported(gated_residual::Mode::READ, kBranches, D, tc.L, gr_systolic())) {+ GTEST_SKIP() << "the geometry needs the systolic READ kernels";+ }+ gr_ref_params p;+ p.rows = tc.rows != 0 ? tc.rows : std::max(4 * static_cast<size_t>(get_test_engine().get_device_info().execution_units_count), pd_min_rows()) + 37;+ p.D = D;+ p.L = tc.L;+ p.eps = tc.eps;+ const size_t CD = p.C * p.D;++ tests::random_generator rg;+ rg.set_seed(GET_SUITE_NAME);+ std::mt19937 gen(4321 + static_cast<uint32_t>(p.rows + tc.L));+ std::vector<float> residual;+ std::vector<float> gain;+ switch (tc.input) {+ case GrInput::kNormal:+ residual = random_vec(rg, p.rows * CD, 1.0f);+ gain = random_vec(rg, CD, 0.5f, 1.0f);+ break;+ case GrInput::kLarge:+ residual = random_vec(rg, p.rows * CD, 2048.0f);+ gain = random_vec(rg, CD, 8.0f, 32.0f);+ break;+ case GrInput::kConst256:+ residual.assign(p.rows * CD, 256.0f);+ gain.assign(CD, 256.0f);+ break;+ }+ const bool zero_weights = tc.input == GrInput::kConst256;++ // [N, K] weights: f16 values and, for u4, the matching compressed matrix (q == zp for zero weights)+ auto make_weight = [&](size_t N, size_t K, std::vector<float>& values, std::vector<memory::ptr>& q_inputs) {+ auto& engine = get_test_engine();+ if (!tc.u4) {+ values = zero_weights ? std::vector<float>(N * K, 0.0f) : random_vec(rg, N * K, 0.1f);+ return make_f16(engine, {static_cast<int64_t>(N), static_cast<int64_t>(K)}, values);+ }+ auto m = make_quant_matrix(gen, N, K, /*u4=*/true);+ if (zero_weights) {+ for (size_t n = 0; n < N; n++) {+ for (size_t k = 0; k < K; k++) {+ m.q[n * K + k] = m.zp[(k / (K / m.G)) * N + n];+ m.dequant[n * K + k] = 0.0f;+ }+ }+ }+ values = m.dequant;+ q_inputs.push_back(make_quant_scale(engine, m));+ q_inputs.push_back(make_quant_zp(engine, m));+ return make_quant_weights(engine, m);+ };+ std::vector<float> wd, wu, wi;+ std::vector<memory::ptr> sz_dn, sz_up, sz_inj; // [scale, zp] of each compressed matrix+ std::vector<memory::ptr> weights = {make_weight(p.L, CD, wd, sz_dn), make_weight(CD, p.L, wu, sz_up)};+ if (tc.u4) {+ weights.insert(weights.end(), {sz_dn[0], sz_up[0], sz_dn[1], sz_up[1]});+ }+ if (tc.write_gate) {+ weights.push_back(make_weight(p.C, CD, wi, sz_inj));+ weights.insert(weights.end(), sz_inj.begin(), sz_inj.end());+ }++ std::vector<float> ref_mixed;+ std::vector<float> ref_gate;+ reference_read(p, residual, gain, wd, wu, tc.write_gate ? &wi : nullptr, ref_mixed, ref_gate);+ const auto run = run_gr_read(p, residual, gain, weights, tc.write_gate, tc.path);+ if (gr_systolic() && (tc.path == "single" || (tc.path.empty() && tc.rows == 0))) {+ ASSERT_FALSE(run.stages.empty());+ EXPECT_EQ(run.stages.back(), "READ_DPAS");+ }++ auto check = [](const std::vector<ov::float16>& out, const std::vector<float>& ref, const char* what) {+ ASSERT_EQ(out.size(), ref.size());+ float err = 0.0f;+ for (size_t i = 0; i < ref.size(); i++) {+ const float v = static_cast<float>(out[i]);+ ASSERT_TRUE(std::isfinite(v)) << what << " is not finite at " << i;+ ASSERT_NEAR(v, ref[i], 2e-2f + 4e-3f * std::abs(ref[i])) << what << " mismatch at " << i;+ err = std::max(err, std::abs(v - ref[i]));+ }+ std::cout << " " << what << "_err=" << err;+ };+ std::cout << "GR_RANGE rows=" << p.rows << " L=" << p.L << " eps=" << p.eps << " stages=";+ for (const auto& s : run.stages) {+ std::cout << s << ",";+ }+ check(run.mixed, ref_mixed, "mixed");+ if (tc.write_gate) {+ check(run.gate, ref_gate, "gate");+ }+ std::cout << std::endl;+}++std::string gr_range_case_name(const ::testing::TestParamInfo<gr_range_case>& info) {+ const auto& c = info.param;+ static const char* inputs[] = {"normal", "large", "const256"};+ std::ostringstream name;+ name << (c.rows == 0 ? std::string("single_rows") : "rows" + std::to_string(c.rows)) << "_L" << c.L << (c.write_gate ? "_gate" : "")+ << (c.u4 ? "_u4" : "_f16") << "_" << inputs[static_cast<int>(c.input)] << "_eps" << static_cast<int>(c.eps >= 1.0f ? c.eps : 0.0f)+ << (c.path.empty() ? "" : "_" + c.path);+ return name.str();+}++INSTANTIATE_TEST_SUITE_P(smoke,+ gated_residual_read_range_test,+ ::testing::Values(+ // R * gain beyond the f16 range, Rbar within it+ gr_range_case{0, 32, true, false, GrInput::kConst256, 1e-6f, ""}, // single kernel+ gr_range_case{0, 32, false, false, GrInput::kConst256, 1e-6f, ""}, // single kernel, no write gate+ gr_range_case{0, 32, false, true, GrInput::kConst256, 1e-6f, ""}, // u4: predequantized single kernel+ gr_range_case{0, 32, true, false, GrInput::kLarge, 1e-6f, ""}, // single kernel+ gr_range_case{0, 32, false, true, GrInput::kLarge, 1e-6f, ""}, // u4: predequantized single kernel+ gr_range_case{0, 32, true, false, GrInput::kLarge, 1e-6f, "ocl3"}, // pipeline on the same rows+ gr_range_case{300, 32, true, false, GrInput::kLarge, 1e-6f, "single"},+ gr_range_case{17, 32, true, false, GrInput::kLarge, 1e-6f, ""}, // pipeline, decode tiling+ gr_range_case{37, 16, true, false, GrInput::kLarge, 1e-6f, ""}, // scalar gr_read+ // integral epsilon values ("1f" is not an OpenCL floating constant)+ gr_range_case{0, 32, true, false, GrInput::kNormal, 1.0f, ""}, // single kernel+ gr_range_case{17, 32, true, false, GrInput::kNormal, 1.0f, ""}, // pipeline+ gr_range_case{5, 16, true, false, GrInput::kNormal, 100.0f, ""}, // scalar gr_read+ gr_range_case{3, 32, false, true, GrInput::kNormal, 1.0f, ""}), // u4 gemv+ gr_range_case_name);++struct gr_write_case {+ size_t rows;+ size_t D;+ bool is_caching_test = false;+};++class gated_residual_write_test : public ::testing::TestWithParam<gr_write_case> {};++TEST_P(gated_residual_write_test, combines_branches) {+ if (!gr_available()) {+ GTEST_SKIP() << "no GatedResidual implementation is available on this device";+ }++ const size_t rows = GetParam().rows;+ const size_t C = kBranches;+ const size_t D = GetParam().D;+ const size_t CD = C * D;++ tests::random_generator rg;+ rg.set_seed(GET_SUITE_NAME);++ const auto residual = random_vec(rg, rows * CD, 1.0f);+ const auto y = random_vec(rg, rows * D, 1.0f);+ const auto gate = random_vec(rg, rows * C, 1.0f, 1.0f);++ const auto ref = reference_write(rows, C, D, residual, y, gate);++ auto& engine = get_test_engine();+ auto residual_mem = make_f16(engine, {static_cast<int64_t>(rows), static_cast<int64_t>(CD)}, residual);+ auto y_mem = make_f16(engine, {static_cast<int64_t>(rows), static_cast<int64_t>(D)}, y);+ auto gate_mem = make_f16(engine, {static_cast<int64_t>(rows), static_cast<int64_t>(C)}, gate);++ topology topology;+ topology.add(input_layout("residual", residual_mem->get_layout()));+ topology.add(input_layout("y", y_mem->get_layout()));+ topology.add(input_layout("gate", gate_mem->get_layout()));+ topology.add(gated_residual("gr_write", {input_info("residual"), input_info("y"), input_info("gate")}, gated_residual::Mode::WRITE, C, D, 0, 1e-6f, false));++ ExecutionConfig config = get_test_default_config(engine);+ config.set_property(ov::intel_gpu::optimize_data(true));+ config.set_property(ov::intel_gpu::allow_new_shape_infer(true));+ network::ptr network = get_network(engine, topology, config, get_test_stream_ptr(), GetParam().is_caching_test);+ network->set_input_data("residual", residual_mem);+ network->set_input_data("y", y_mem);+ network->set_input_data("gate", gate_mem);++ auto outputs = network->execute();+ cldnn::mem_lock<ov::float16> out(outputs.at("gr_write").get_memory(), get_test_stream());+ EXPECT_EQ(executed_stages(*network, "gr_write"), std::vector<std::string>{"WRITE"});+ ASSERT_EQ(out.size(), ref.size());+ for (size_t i = 0; i < ref.size(); i++) {+ ASSERT_NEAR(static_cast<float>(out[i]), ref[i], 1e-2f) << "residual update mismatch at " << i;+ }+}++// D=48 is a multiple of 16 but not of 32 or 64, so gr_best_tile() falls back to GR_WRITE_TILE=16; D=64 and 256 use the wide tile.+INSTANTIATE_TEST_SUITE_P(+ smoke,+ gated_residual_write_test,+ ::testing::Values(gr_write_case{5, 64}, gr_write_case{9, 48}, gr_write_case{37, 256}, gr_write_case{33, 5120}, gr_write_case{37, 256, true}));++// A cached dynamic READ holds the stages of every row-count route; the imported network has to run each of them.+// decode, mid and wide tilings, then the single kernel, and back (entry 4 is also the static row count)+const std::vector<size_t> kRowRoutes = {5, 37, 1, 300, 1500, 2};++struct gr_caching_case {+ bool u4;+ bool write_gate;+ bool dynamic;+};++class gated_residual_caching_test : public ::testing::TestWithParam<gr_caching_case> {};++TEST_P(gated_residual_caching_test, imported_network_runs_every_row_route) {+ const auto tc = GetParam();+ if (!(tc.u4 ? gr_compression_available() : gr_available())) {+ GTEST_SKIP() << "no GatedResidual implementation is available on this device";+ }++ const size_t C = kBranches;+ const size_t D = 64;+ const size_t L = 32;+ const size_t CD = C * D;++ tests::random_generator rg;+ rg.set_seed(GET_SUITE_NAME);+ const auto gain = random_vec(rg, CD, 0.5f, 1.0f);+ std::mt19937 gen(4321);+ const auto wd = make_quant_matrix(gen, L, CD, true, false, true, 0);+ const auto wu = make_quant_matrix(gen, CD, L, true, false, true, 0);+ const auto wi = make_quant_matrix(gen, C, CD, true, false, true, 0);+ // f16 weights, or the decompressed values of the u4 weights (the reference is the same either way)+ const auto w_down = tc.u4 ? wd.dequant : random_vec(rg, L * CD, 0.1f);+ const auto w_up = tc.u4 ? wu.dequant : random_vec(rg, CD * L, 0.1f);+ const auto w_inject = tc.u4 ? wi.dequant : random_vec(rg, C * CD, 0.1f);++ auto& engine = get_test_engine();+ topology topology;+ const int64_t rows_dim = tc.dynamic ? -1 : static_cast<int64_t>(kRowRoutes[4]);+ topology.add(input_layout("residual", layout{ov::PartialShape{rows_dim, static_cast<int64_t>(CD)}, data_types::f16, format::bfyx}));+ topology.add(data("gain", make_f16(engine, {static_cast<int64_t>(CD)}, gain)));+ std::vector<input_info> inputs = {input_info("residual"), input_info("gain")};+ auto add_weight = [&](const std::string& id, memory::ptr mem) {+ topology.add(data(id, mem));+ inputs.emplace_back(id);+ };+ if (tc.u4) {+ add_weight("w_down", make_quant_weights(engine, wd));+ add_weight("w_up", make_quant_weights(engine, wu));+ add_weight("s_down", make_quant_scale(engine, wd));+ add_weight("s_up", make_quant_scale(engine, wu));+ add_weight("z_down", make_quant_zp(engine, wd));+ add_weight("z_up", make_quant_zp(engine, wu));+ if (tc.write_gate) {+ add_weight("w_inject", make_quant_weights(engine, wi));+ add_weight("s_inject", make_quant_scale(engine, wi));+ add_weight("z_inject", make_quant_zp(engine, wi));+ }+ } else {+ add_weight("w_down", make_f16(engine, {static_cast<int64_t>(L), static_cast<int64_t>(CD)}, w_down));+ add_weight("w_up", make_f16(engine, {static_cast<int64_t>(CD), static_cast<int64_t>(L)}, w_up));+ if (tc.write_gate) {+ add_weight("w_inject", make_f16(engine, {static_cast<int64_t>(C), static_cast<int64_t>(CD)}, w_inject));+ }+ }+ topology.add(gated_residual("gr", inputs, gated_residual::Mode::READ, C, D, L, 1e-6f, tc.write_gate));++ ExecutionConfig config = get_test_default_config(engine);+ config.set_property(ov::intel_gpu::optimize_data(true));+ config.set_property(ov::intel_gpu::allow_new_shape_infer(true));+ network::ptr network = get_network(engine, topology, config, get_test_stream_ptr(), true);++ // decode, mid and wide tilings, then the single kernel, and back+ for (const size_t rows : tc.dynamic ? kRowRoutes : std::vector<size_t>{kRowRoutes[4]}) {+ gr_ref_params p;+ p.rows = rows;+ p.D = D;+ p.L = L;+ const auto residual = random_vec(rg, rows * CD, 1.0f);+ std::vector<float> ref_mixed;+ std::vector<float> ref_gate;+ reference_read(p, residual, gain, w_down, w_up, tc.write_gate ? &w_inject : nullptr, ref_mixed, ref_gate);++ network->set_input_data("residual", make_f16(engine, {static_cast<int64_t>(rows), static_cast<int64_t>(CD)}, residual));+ auto outputs = network->execute();+ // A dynamic output buffer may be larger than the shape of this run, so check the layout and read the used part only.+ const auto inst = network->get_primitive("gr");+ ASSERT_EQ(inst->get_output_layout(0).get_partial_shape(), (ov::PartialShape{static_cast<int64_t>(rows), static_cast<int64_t>(D)})) << "rows=" << rows;+ cldnn::mem_lock<ov::float16> mixed(outputs.at("gr").get_memory(), get_test_stream());+ ASSERT_GE(mixed.size(), ref_mixed.size()) << "rows=" << rows;+ for (size_t i = 0; i < ref_mixed.size(); i++) {+ ASSERT_NEAR(static_cast<float>(mixed[i]), ref_mixed[i], 2e-2f) << "mixed mismatch at rows=" << rows << " index=" << i;+ }+ if (tc.write_gate) {+ ASSERT_EQ(inst->get_output_layout(1).get_partial_shape(), (ov::PartialShape{static_cast<int64_t>(rows), static_cast<int64_t>(C)}))+ << "rows=" << rows;+ cldnn::mem_lock<ov::float16> gate(inst->output_memory_ptr(1), get_test_stream());+ ASSERT_GE(gate.size(), ref_gate.size()) << "rows=" << rows;+ for (size_t i = 0; i < ref_gate.size(); i++) {+ ASSERT_NEAR(static_cast<float>(gate[i]), ref_gate[i], 2e-2f) << "write gate mismatch at rows=" << rows << " index=" << i;+ }+ }+ }+}++INSTANTIATE_TEST_SUITE_P(smoke,+ gated_residual_caching_test,+ ::testing::Values(gr_caching_case{false, true, true}, gr_caching_case{true, false, true}, gr_caching_case{true, false, false}));++// --- ov::Model / ov::Core level tests (plugin pipeline, dynamic rows) ----------+//+// The tests above go through the raw cldnn::topology/network API, i.e. they bypass+// ov::Model -> ProgramBuilder -> CreateGatedResidualOp. The tests below build a tiny ov::Model with a directly-constructed+// ov::intel_gpu::op::GatedResidual node (no pattern fusion involved) and run it through ov::Core::compile_model on the test device and+// ov::InferRequest::infer() with changing row counts on one compiled model.+// Dynamic row counts on one compiled model / infer request: the dispatch data must be recomputed for every shape.+struct gr_dynamic_read_case {+ size_t L;+ bool write_gate;+ std::vector<size_t> rows;+};++class gated_residual_dynamic_read_test : public ::testing::TestWithParam<gr_dynamic_read_case> {};++TEST_P(gated_residual_dynamic_read_test, ov_model_reuses_dispatch_data) {+ if (!gr_available()) {+ GTEST_SKIP() << "no GatedResidual implementation is available on this device";+ }++ ov::Core core;+ const auto& tc = GetParam();+ const size_t C = kBranches;+ const size_t D = 64;+ const size_t L = tc.L;+ const size_t CD = C * D;++ auto residual_p = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::PartialShape{-1, static_cast<int64_t>(CD)});+ auto gain_p = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::Shape{CD});+ auto w_down_p = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::Shape{L, CD});+ auto w_up_p = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::Shape{CD, L});+ ov::ParameterVector params{residual_p, gain_p, w_down_p, w_up_p};+ if (tc.write_gate) {+ params.push_back(std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::Shape{C, CD}));+ }++ ov::OutputVector inputs(params.begin(), params.end());+ auto gr = std::make_shared<ov::intel_gpu::op::GatedResidual>(inputs, ov::intel_gpu::op::GatedResidual::Mode::READ, C, D, L, 1e-6f, tc.write_gate);+ ov::ResultVector results{std::make_shared<ov::op::v0::Result>(gr->output(0))};+ if (tc.write_gate) {+ results.push_back(std::make_shared<ov::op::v0::Result>(gr->output(1)));+ }+ auto model = std::make_shared<ov::Model>(results, params);++ ov::CompiledModel compiled;+ OV_ASSERT_NO_THROW(compiled = core.compile_model(model, test_device_name()));+ auto infer_request = compiled.create_infer_request();++ tests::random_generator rg;+ rg.set_seed(GET_SUITE_NAME);+ const auto gain = random_vec(rg, CD, 0.5f, 1.0f);+ const auto w_down = random_vec(rg, L * CD, 0.1f);+ const auto w_up = random_vec(rg, CD * L, 0.1f);+ const auto w_inject = tc.write_gate ? random_vec(rg, C * CD, 0.1f) : std::vector<float>{};++ auto fill_tensor = [](ov::Tensor tensor, const std::vector<float>& data) {+ auto* dst = tensor.data<ov::float16>();+ ASSERT_EQ(tensor.get_size(), data.size());+ for (size_t i = 0; i < data.size(); i++) {+ dst[i] = ov::float16(data[i]);+ }+ };+ fill_tensor(infer_request.get_input_tensor(1), gain);+ fill_tensor(infer_request.get_input_tensor(2), w_down);+ fill_tensor(infer_request.get_input_tensor(3), w_up);+ if (tc.write_gate) {+ fill_tensor(infer_request.get_input_tensor(4), w_inject);+ }++ for (const size_t rows : tc.rows) {+ tests::random_generator input_rg;+ input_rg.set_seed(static_cast<uint32_t>(rows));+ const auto residual = random_vec(input_rg, rows * CD, 1.0f);+ ov::Tensor residual_tensor(ov::element::f16, ov::Shape{rows, CD});+ fill_tensor(residual_tensor, residual);+ infer_request.set_tensor(residual_p, residual_tensor);++ gr_ref_params p;+ p.rows = rows;+ p.C = C;+ p.D = D;+ p.L = L;+ std::vector<float> ref_mixed;+ std::vector<float> ref_gate;+ reference_read(p, residual, gain, w_down, w_up, tc.write_gate ? &w_inject : nullptr, ref_mixed, ref_gate);++ OV_ASSERT_NO_THROW(infer_request.infer());+ const auto mixed = infer_request.get_output_tensor(0);+ const auto* mixed_data = mixed.data<ov::float16>();+ ASSERT_EQ(mixed.get_size(), ref_mixed.size());+ for (size_t i = 0; i < ref_mixed.size(); i++) {+ ASSERT_NEAR(static_cast<float>(mixed_data[i]), ref_mixed[i], 2e-2f) << "mixed mismatch at rows=" << rows << " index=" << i;+ }+ if (tc.write_gate) {+ const auto gate = infer_request.get_output_tensor(1);+ const auto* gate_data = gate.data<ov::float16>();+ ASSERT_EQ(gate.get_size(), ref_gate.size());+ for (size_t i = 0; i < ref_gate.size(); i++) {+ ASSERT_NEAR(static_cast<float>(gate_data[i]), ref_gate[i], 2e-2f) << "write gate mismatch at rows=" << rows << " index=" << i;+ }+ }+ }+}++INSTANTIATE_TEST_SUITE_P(smoke,+ gated_residual_dynamic_read_test,+ ::testing::Values(+ // DPAS pipeline: walks the decode, mid and wide tilings and back again+ gr_dynamic_read_case{32, true, {5, 37, 1, 300, 1500, 2}},+ // L=16 is not a multiple of 32, so the scalar gr_read.cl stage runs instead+ gr_dynamic_read_case{16, false, {3, 41, 1, 100, 2}}));++// Dynamic row counts on one compiled model / infer request for GrWriteGenerator's dispatch-data path (gr_write.cl).+struct gr_dynamic_write_case {+ size_t D;+};++class gated_residual_dynamic_write_test : public ::testing::TestWithParam<gr_dynamic_write_case> {};++TEST_P(gated_residual_dynamic_write_test, ov_model_reuses_dispatch_data) {+ if (!gr_available()) {+ GTEST_SKIP() << "no GatedResidual implementation is available on this device";+ }++ ov::Core core;+ const size_t C = kBranches;+ const size_t D = GetParam().D;+ const size_t CD = C * D;++ auto residual_p = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::PartialShape{-1, static_cast<int64_t>(CD)});+ auto y_p = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::PartialShape{-1, static_cast<int64_t>(D)});+ auto gate_p = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::PartialShape{-1, static_cast<int64_t>(C)});++ auto gr = std::make_shared<ov::intel_gpu::op::GatedResidual>(ov::OutputVector{residual_p, y_p, gate_p},+ ov::intel_gpu::op::GatedResidual::Mode::WRITE,+ C,+ D,+ /*lowrank=*/0,+ /*epsilon=*/0.0f,+ /*produce_write_gate=*/false);+ auto result = std::make_shared<ov::op::v0::Result>(gr);+ auto model = std::make_shared<ov::Model>(ov::ResultVector{result}, ov::ParameterVector{residual_p, y_p, gate_p});++ ov::CompiledModel compiled;+ OV_ASSERT_NO_THROW(compiled = core.compile_model(model, test_device_name()));+ auto infer_request = compiled.create_infer_request();++ auto fill_tensor = [](ov::Tensor tensor, const std::vector<float>& data) {+ auto* dst = tensor.data<ov::float16>();+ ASSERT_EQ(tensor.get_size(), data.size());+ for (size_t i = 0; i < data.size(); i++) {+ dst[i] = ov::float16(data[i]);+ }+ };++ for (const size_t rows : {size_t{5}, size_t{37}, size_t{1}}) {+ tests::random_generator rg;+ rg.set_seed(static_cast<uint32_t>(rows) + 2000);+ const auto residual = random_vec(rg, rows * CD, 1.0f);+ const auto y = random_vec(rg, rows * D, 1.0f);+ const auto gate = random_vec(rg, rows * C, 1.0f, 1.0f);++ ov::Tensor residual_tensor(ov::element::f16, ov::Shape{rows, CD});+ ov::Tensor y_tensor(ov::element::f16, ov::Shape{rows, D});+ ov::Tensor gate_tensor(ov::element::f16, ov::Shape{rows, C});+ fill_tensor(residual_tensor, residual);+ fill_tensor(y_tensor, y);+ fill_tensor(gate_tensor, gate);+ infer_request.set_tensor(residual_p, residual_tensor);+ infer_request.set_tensor(y_p, y_tensor);+ infer_request.set_tensor(gate_p, gate_tensor);++ const auto ref = reference_write(rows, C, D, residual, y, gate);++ OV_ASSERT_NO_THROW(infer_request.infer());+ const auto out_tensor = infer_request.get_output_tensor(0);+ const auto* out = out_tensor.data<ov::float16>();+ ASSERT_EQ(out_tensor.get_size(), ref.size());+ for (size_t i = 0; i < ref.size(); i++) {+ ASSERT_NEAR(static_cast<float>(out[i]), ref[i], 1e-2f) << "residual update mismatch at rows=" << rows << " index=" << i;+ }+ }+}++// D = 256 is hidden_size / C.+INSTANTIATE_TEST_SUITE_P(smoke, gated_residual_dynamic_write_test, ::testing::Values(gr_dynamic_write_case{64}, gr_dynamic_write_case{256}));++// Equivalence of the decomposed source graph and the fused kernel: the decomposed READ/MIX+// model is compiled through the normal plugin pipeline (which must fuse it into a single+// gated_residual node) and compared against the FP32 reference of the *decomposed* math.+// With the write gate (2 * sigmoid(Rbar . W_inject^T / C), on the same Rbar as the READ) the gate branch is fused into the READ as well:+// one gated_residual node with two outputs, no MatMul left, and both outputs match the FP32 reference. A fully static model+// compiles without the new shape inference unless an op requires it, which the two-output READ does.+class gated_residual_decomposed_read_test : public ::testing::TestWithParam<std::tuple<bool, bool>> {};++TEST_P(gated_residual_decomposed_read_test, fuses_and_matches_reference) {+ if (!gr_available()) {+ GTEST_SKIP() << "no GatedResidual implementation is available on this device";+ }+ const bool with_write_gate = std::get<0>(GetParam());+ const bool static_rows = std::get<1>(GetParam());+ if (static_rows && !get_test_engine().get_device_info().supports_immad) {+ // Without immad a static f16 ReduceSum is converted to a Pooling before the fusion runs; dynamic shapes are not.+ GTEST_SKIP() << "static-shape GatedResidual fusion is not available without immad";+ }++ const size_t C = kBranches;+ const size_t D = 64;+ const size_t L = 32;+ const size_t CD = C * D;+ const float eps = 1e-5f;+ const auto et = ov::element::f16;++ tests::random_generator rg;+ rg.set_seed(GET_SUITE_NAME);+ const auto gain_w = random_vec(rg, CD, 0.25f);+ const auto w_down = random_vec(rg, L * CD, 0.1f);+ const auto w_up = random_vec(rg, CD * L, 0.1f);+ const auto w_inject = with_write_gate ? random_vec(rg, C * CD, 0.1f) : std::vector<float>{};++ auto i64 = [](std::vector<int64_t> v) {+ return ov::op::v0::Constant::create(ov::element::i64, ov::Shape{v.size()}, v);+ };+ auto scalar = [&](float v) {+ return ov::op::v0::Constant::create(et, ov::Shape{}, {v});+ };+ auto f16_param = [&](const ov::Shape& shape) {+ return std::make_shared<ov::op::v0::Parameter>(et, shape);+ };++ // Gain and weights are model inputs so ConstantFolding cannot fold the 1/C scale into W_down+ // (real checkpoints keep their compressed weights opaque in the same way).+ constexpr int64_t kStaticRows = 64;+ auto residual_p = std::make_shared<ov::op::v0::Parameter>(et, ov::PartialShape{static_rows ? kStaticRows : -1, static_cast<int64_t>(CD)});+ auto gain_p = f16_param(ov::Shape{CD});+ auto w_down_p = f16_param(ov::Shape{L, CD});+ auto w_up_p = f16_param(ov::Shape{CD, L});+ ov::ParameterVector params{residual_p, gain_p, w_down_p, w_up_p};+ auto r3 = std::make_shared<ov::op::v1::Reshape>(residual_p, i64({-1, static_cast<int64_t>(C), static_cast<int64_t>(D)}), false);+ auto sq = std::make_shared<ov::op::v1::Power>(r3, scalar(2.0f));+ auto mean = std::make_shared<ov::op::v1::ReduceMean>(sq, i64({-1}), true);+ auto rms = std::make_shared<ov::op::v0::Sqrt>(std::make_shared<ov::op::v1::Add>(mean, scalar(eps)));+ auto inv_rms = std::make_shared<ov::op::v1::Divide>(scalar(1.0f), rms);+ auto normalized = std::make_shared<ov::op::v1::Multiply>(r3, inv_rms);+ auto normalized_flat = std::make_shared<ov::op::v1::Reshape>(normalized, i64({-1, static_cast<int64_t>(CD)}), false);+ auto gain = std::make_shared<ov::op::v1::Add>(gain_p, scalar(1.0f));+ auto rbar = std::make_shared<ov::op::v1::Multiply>(normalized_flat, gain);++ auto low = std::make_shared<ov::op::v0::MatMul>(rbar, w_down_p, false, true);+ auto act = std::make_shared<ov::op::v4::Swish>(std::make_shared<ov::op::v1::Multiply>(low, scalar(1.0f / static_cast<float>(C))));+ auto up = std::make_shared<ov::op::v0::MatMul>(act, w_up_p, false, true);+ auto weighted = std::make_shared<ov::op::v1::Multiply>(std::make_shared<ov::op::v0::Sigmoid>(up), rbar);+ auto weighted3 = std::make_shared<ov::op::v1::Reshape>(weighted, i64({-1, static_cast<int64_t>(C), static_cast<int64_t>(D)}), false);+ auto mixed =+ std::make_shared<ov::op::v1::Multiply>(std::make_shared<ov::op::v1::ReduceSum>(weighted3, i64({1}), false), scalar(1.0f / static_cast<float>(C)));++ ov::OutputVector outputs{mixed};+ if (with_write_gate) {+ auto w_inject_p = f16_param(ov::Shape{C, CD});+ params.push_back(w_inject_p);+ auto inject = std::make_shared<ov::op::v0::MatMul>(rbar, w_inject_p, false, true);+ auto inject_scaled = std::make_shared<ov::op::v1::Multiply>(inject, scalar(1.0f / static_cast<float>(C)));+ outputs.push_back(std::make_shared<ov::op::v1::Multiply>(std::make_shared<ov::op::v0::Sigmoid>(inject_scaled), scalar(2.0f)));+ }+ auto model = std::make_shared<ov::Model>(outputs, params);++ ov::Core core;+ ov::CompiledModel compiled;+ OV_ASSERT_NO_THROW(compiled = core.compile_model(model, test_device_name()));+ size_t fused_nodes = 0;+ size_t gemm_nodes = 0;+ std::string runtime_layers;+ for (const auto& op : compiled.get_runtime_model()->get_ops()) {+ const auto it = op->get_rt_info().find("layerType");+ const auto layer_type = it != op->get_rt_info().end() ? it->second.as<std::string>() : std::string("?");+ if (layer_type == "GatedResidual" || layer_type == "gated_residual") {+ fused_nodes++;+ }+ if (layer_type == "FullyConnected" || layer_type == "fully_connected" || layer_type == "Gemm" || layer_type == "gemm") {+ gemm_nodes++;+ }+ runtime_layers += layer_type + " ";+ }+ EXPECT_EQ(fused_nodes, 1u) << "decomposed READ graph was not fused into one gated_residual; runtime layers: " << runtime_layers;+ EXPECT_EQ(gemm_nodes, 0u) << "a MatMul is left; runtime layers: " << runtime_layers;++ auto infer_request = compiled.create_infer_request();+ auto fill = [](ov::Tensor tensor, const std::vector<float>& data) {+ auto* dst = tensor.data<ov::float16>();+ ASSERT_EQ(tensor.get_size(), data.size());+ for (size_t i = 0; i < data.size(); i++) {+ dst[i] = ov::float16(data[i]);+ }+ };+ fill(infer_request.get_input_tensor(1), gain_w);+ fill(infer_request.get_input_tensor(2), w_down);+ fill(infer_request.get_input_tensor(3), w_up);+ if (with_write_gate) {+ fill(infer_request.get_input_tensor(4), w_inject);+ }+ const auto row_counts = static_rows ? std::vector<size_t>{kStaticRows} : std::vector<size_t>{3, 64, 700};+ for (const size_t rows : row_counts) {+ tests::random_generator input_rg;+ input_rg.set_seed(static_cast<uint32_t>(rows));+ const auto residual = random_vec(input_rg, rows * CD, 1.0f);+ ov::Tensor residual_tensor(et, ov::Shape{rows, CD});+ fill(residual_tensor, residual);+ infer_request.set_tensor(residual_p, residual_tensor);++ std::vector<float> gain_folded(gain_w);+ for (auto& g : gain_folded) {+ g += 1.0f;+ }+ gr_ref_params p;+ p.rows = rows;+ p.C = C;+ p.D = D;+ p.L = L;+ p.eps = eps;+ std::vector<float> ref_mixed;+ std::vector<float> ref_gate;+ reference_read(p, residual, gain_folded, w_down, w_up, with_write_gate ? &w_inject : nullptr, ref_mixed, ref_gate);++ OV_ASSERT_NO_THROW(infer_request.infer());+ const auto mixed_tensor = infer_request.get_output_tensor(0);+ const auto* mixed_data = mixed_tensor.data<ov::float16>();+ ASSERT_EQ(mixed_tensor.get_size(), ref_mixed.size());+ for (size_t i = 0; i < ref_mixed.size(); i++) {+ ASSERT_NEAR(static_cast<float>(mixed_data[i]), ref_mixed[i], 2e-2f) << "mixed mismatch at rows=" << rows << " index=" << i;+ }+ if (with_write_gate) {+ const auto gate_tensor = infer_request.get_output_tensor(1);+ const auto* gate_data = gate_tensor.data<ov::float16>();+ ASSERT_EQ(gate_tensor.get_size(), ref_gate.size());+ for (size_t i = 0; i < ref_gate.size(); i++) {+ ASSERT_NEAR(static_cast<float>(gate_data[i]), ref_gate[i], 2e-2f) << "write gate mismatch at rows=" << rows << " index=" << i;+ }+ }+ }+}++INSTANTIATE_TEST_SUITE_P(smoke, gated_residual_decomposed_read_test, ::testing::Combine(::testing::Bool(), ::testing::Bool()));++// End to end check of the compressed scale / zero point layout: a GatedResidual READ op carrying the operation layout ([N, G] scales /+// zero points, scale_gn = false) is compiled through the normal plugin pipeline, where ConvertGatedResidualScaleLayout turns them into+// the [G, N] the kernels read. The result must match the FP32 reference computed from the dequantized weights. The op is built+// directly so the conversion is checked on its own; gated_residual_decomposed_quant_test below covers fusion + conversion.+struct gr_e2e_quant_case {+ size_t D;+ size_t L;+ bool u4;+ bool is_signed;+ bool has_zp;+ size_t group; // 0: default of the bit width, kPerChannel, or a group size+ bool write_gate;+};++class gated_residual_e2e_quant_test : public ::testing::TestWithParam<gr_e2e_quant_case> {+public:+ static std::string PrintToStringParamName(const testing::TestParamInfo<gr_e2e_quant_case>& info) {+ const auto& c = info.param;+ std::ostringstream os;+ os << "D" << c.D << "_L" << c.L << (c.u4 ? "_4bit" : "_8bit") << (c.is_signed ? "_signed" : "_unsigned") << (c.has_zp ? "_zp" : "_nozp");+ os << (c.group == kPerChannel ? "_perchannel" : (c.group == 0 ? "_defgroup" : "_g" + std::to_string(c.group)));+ os << (c.write_gate ? "_gate" : "");+ return os.str();+ }+};++TEST_P(gated_residual_e2e_quant_test, compressed_ir_matches_reference) {+ if (!gr_compression_available()) {+ GTEST_SKIP() << "compressed GatedResidual is not available on this device";+ }+ const auto tc = GetParam();+ const size_t C = kBranches;+ const size_t D = tc.D;+ const size_t L = tc.L;+ const size_t CD = C * D;+ const float eps = 1e-5f;+ const auto et = ov::element::f16;+ const auto wt = tc.u4 ? (tc.is_signed ? ov::element::i4 : ov::element::u4) : (tc.is_signed ? ov::element::i8 : ov::element::u8);++ std::mt19937 gen(static_cast<uint32_t>(D * 131 + L * 7 + (tc.u4 ? 3 : 0) + (tc.is_signed ? 5 : 0) + (tc.has_zp ? 11 : 0) + tc.group));+ const auto m_down = make_quant_matrix(gen, L, CD, tc.u4, tc.is_signed, tc.has_zp, tc.group);+ const auto m_up = make_quant_matrix(gen, CD, L, tc.u4, tc.is_signed, tc.has_zp, tc.group);+ const auto m_inject = make_quant_matrix(gen, C, CD, tc.u4, tc.is_signed, tc.has_zp, tc.group);++ // q / zp / scale of quant_matrix are [N, K] row-major / [G, N]; the op takes zp / scale as [N, G].+ auto weights_const = [&](const quant_matrix& m) {+ std::vector<int> q(m.N * m.K);+ for (size_t i = 0; i < q.size(); i++) {+ q[i] = m.value(m.q[i]);+ }+ return ov::op::v0::Constant::create(wt, ov::Shape{m.N, m.K}, q);+ };+ auto scale_const = [&](const quant_matrix& m) {+ std::vector<float> scale(m.N * m.G);+ for (size_t n = 0; n < m.N; n++) {+ for (size_t g = 0; g < m.G; g++) {+ scale[n * m.G + g] = m.scale[g * m.N + n];+ }+ }+ return ov::op::v0::Constant::create(et, ov::Shape{m.N, m.G}, scale);+ };+ auto zp_const = [&](const quant_matrix& m) {+ std::vector<int> zp(m.N * m.G);+ for (size_t n = 0; n < m.N; n++) {+ for (size_t g = 0; g < m.G; g++) {+ zp[n * m.G + g] = m.value(m.zp[g * m.N + n]);+ }+ }+ return ov::op::v0::Constant::create(wt, ov::Shape{m.N, m.G}, zp);+ };++ tests::random_generator rg;+ rg.set_seed(GET_SUITE_NAME);+ const auto gain_w = random_vec(rg, CD, 0.25f);+ std::vector<float> gain_folded(gain_w);+ for (auto& g : gain_folded) {+ g += 1.0f;+ }++ auto residual_p = std::make_shared<ov::op::v0::Parameter>(et, ov::PartialShape{-1, static_cast<int64_t>(CD)});+ auto gain_p = std::make_shared<ov::op::v0::Parameter>(et, ov::Shape{CD});+ ov::OutputVector inputs{residual_p, gain_p, weights_const(m_down), weights_const(m_up), scale_const(m_down), scale_const(m_up)};+ if (tc.has_zp) {+ inputs.push_back(zp_const(m_down));+ inputs.push_back(zp_const(m_up));+ }+ if (tc.write_gate) {+ inputs.push_back(weights_const(m_inject));+ inputs.push_back(scale_const(m_inject));+ if (tc.has_zp) {+ inputs.push_back(zp_const(m_inject));+ }+ }+ auto gr = std::make_shared<ov::intel_gpu::op::GatedResidual>(inputs,+ ov::intel_gpu::op::GatedResidual::Mode::READ,+ C,+ D,+ L,+ eps,+ tc.write_gate,+ /*scale_gn=*/false);+ ov::ResultVector results{std::make_shared<ov::op::v0::Result>(gr->output(0))};+ if (tc.write_gate) {+ results.push_back(std::make_shared<ov::op::v0::Result>(gr->output(1)));+ }+ auto model = std::make_shared<ov::Model>(results, ov::ParameterVector{residual_p, gain_p});++ ov::Core core;+ ov::CompiledModel compiled;+ OV_ASSERT_NO_THROW(compiled = core.compile_model(model, test_device_name()));+ size_t fused_nodes = 0;+ size_t gemm_nodes = 0;+ std::string runtime_layers;+ for (const auto& op : compiled.get_runtime_model()->get_ops()) {+ const auto it = op->get_rt_info().find("layerType");+ const auto layer_type = it != op->get_rt_info().end() ? it->second.as<std::string>() : std::string("?");+ if (layer_type == "GatedResidual" || layer_type == "gated_residual") {+ fused_nodes++;+ }+ if (layer_type == "FullyConnected" || layer_type == "fully_connected" || layer_type == "Gemm" || layer_type == "gemm") {+ gemm_nodes++;+ }+ runtime_layers += layer_type + " ";+ }+ ASSERT_EQ(fused_nodes, 1u) << "expected one gated_residual node; runtime layers: " << runtime_layers;+ EXPECT_EQ(gemm_nodes, 0u) << "a MatMul is left; runtime layers: " << runtime_layers;++ auto infer_request = compiled.create_infer_request();+ auto fill = [](ov::Tensor tensor, const std::vector<float>& data) {+ auto* dst = tensor.data<ov::float16>();+ ASSERT_EQ(tensor.get_size(), data.size());+ for (size_t i = 0; i < data.size(); i++) {+ dst[i] = ov::float16(data[i]);+ }+ };+ {+ ov::Tensor gain_tensor(et, ov::Shape{CD});+ fill(gain_tensor, gain_folded);+ infer_request.set_tensor(gain_p, gain_tensor);+ }+ for (const size_t rows : {3, 64}) {+ tests::random_generator input_rg;+ input_rg.set_seed(static_cast<uint32_t>(rows));+ const auto residual = random_vec(input_rg, rows * CD, 1.0f);+ ov::Tensor residual_tensor(et, ov::Shape{rows, CD});+ fill(residual_tensor, residual);+ infer_request.set_tensor(residual_p, residual_tensor);++ gr_ref_params p;+ p.rows = rows;+ p.C = C;+ p.D = D;+ p.L = L;+ p.eps = eps;+ std::vector<float> ref_mixed;+ std::vector<float> ref_gate;+ reference_read(p, residual, gain_folded, m_down.dequant, m_up.dequant, tc.write_gate ? &m_inject.dequant : nullptr, ref_mixed, ref_gate);++ OV_ASSERT_NO_THROW(infer_request.infer());+ const auto mixed_tensor = infer_request.get_output_tensor(0);+ const auto* mixed_data = mixed_tensor.data<ov::float16>();+ ASSERT_EQ(mixed_tensor.get_size(), ref_mixed.size());+ for (size_t i = 0; i < ref_mixed.size(); i++) {+ ASSERT_NEAR(static_cast<float>(mixed_data[i]), ref_mixed[i], 2e-2f) << "mixed mismatch at rows=" << rows << " index=" << i;+ }+ if (tc.write_gate) {+ const auto gate_tensor = infer_request.get_output_tensor(1);+ const auto* gate_data = gate_tensor.data<ov::float16>();+ ASSERT_EQ(gate_tensor.get_size(), ref_gate.size());+ for (size_t i = 0; i < ref_gate.size(); i++) {+ ASSERT_NEAR(static_cast<float>(gate_data[i]), ref_gate[i], 2e-2f) << "write gate mismatch at rows=" << rows << " index=" << i;+ }+ }+ }+}++// 4-bit default group (32): G_down = 8 / 12, G_up = 1 (K = L); 8-bit per channel: G = 1; an explicit group of 64 and per-channel 4-bit+// give another G > 1 / G = 1 mix. D = 96 makes C*D = 384, so N is not a power of two.+INSTANTIATE_TEST_SUITE_P(smoke,+ gated_residual_e2e_quant_test,+ ::testing::Values(gr_e2e_quant_case{64, 32, true, false, true, 0, false},+ gr_e2e_quant_case{64, 32, true, false, true, 0, true},+ gr_e2e_quant_case{64, 32, true, true, true, 0, true},+ gr_e2e_quant_case{64, 32, true, false, false, 0, true},+ gr_e2e_quant_case{64, 32, true, true, false, 0, false},+ gr_e2e_quant_case{96, 64, true, false, true, 0, true},+ gr_e2e_quant_case{96, 64, true, true, true, 64, false},+ gr_e2e_quant_case{96, 64, true, false, true, kPerChannel, true},+ gr_e2e_quant_case{64, 32, false, false, true, 0, true},+ gr_e2e_quant_case{64, 32, false, true, true, 0, false},+ gr_e2e_quant_case{96, 64, false, false, false, 0, true},+ gr_e2e_quant_case{96, 64, false, true, false, 0, false}),+ gated_residual_e2e_quant_test::PrintToStringParamName);++// Full pipeline on a compressed decomposed READ in the form the model exporter produces: rank-3 activations [B, T, C*D], each weight+// decompressed by Convert -> (Subtract zp) -> Multiply(scale [N, G, 1]) -> Reshape [N, K] (no Reshape for G = 1), and the 1/C of+// the down / inject projections as Divide(Const [1, 1, 1]) after the MatMul. The graph must fuse into one gated_residual that keeps+// the weights compressed (W_inject too with the write gate), ConvertGatedResidualScaleLayout must turn the [N, G] scales / zero+// points into [G, N], and the outputs must match the FP32 reference of the dequantized weights.+// Rank-2 activations are not covered: there MatMulMultiplyFusion folds the [1, 1] 1/C into W_down and the GPU pipeline then moves it+// below the decompression Reshape, which the fusion does not look through.+struct gr_decomposed_quant_case {+ size_t D;+ size_t L;+ bool u4;+ bool is_signed;+ bool has_zp;+ size_t group; // see make_quant_matrix+ bool write_gate;+ bool divide; // 1/C as Divide(Const [1, 1, 1] = C) like the exporter, otherwise Multiply(scalar 1/C)+};++class gated_residual_decomposed_quant_test : public ::testing::TestWithParam<gr_decomposed_quant_case> {+public:+ static std::string PrintToStringParamName(const testing::TestParamInfo<gr_decomposed_quant_case>& info) {+ const auto& c = info.param;+ std::ostringstream os;+ os << "D" << c.D << "_L" << c.L << (c.u4 ? "_4bit" : "_8bit") << (c.is_signed ? "_signed" : "_unsigned") << (c.has_zp ? "_zp" : "_nozp");+ os << (c.group == kPerChannel ? "_perchannel" : (c.group == 0 ? "_defgroup" : "_g" + std::to_string(c.group)));+ os << (c.write_gate ? "_gate" : "") << (c.divide ? "_div111" : "_mulscalar");+ return os.str();+ }+};++TEST_P(gated_residual_decomposed_quant_test, fuses_compressed_and_matches_reference) {+ if (!gr_compression_available()) {+ GTEST_SKIP() << "compressed GatedResidual is not available on this device";+ }+ const auto tc = GetParam();+ const size_t C = kBranches;+ const size_t D = tc.D;+ const size_t L = tc.L;+ const size_t CD = C * D;+ const auto iC = static_cast<int64_t>(C);+ const auto iD = static_cast<int64_t>(D);+ const auto iCD = static_cast<int64_t>(CD);+ const float eps = 1e-6f;+ const auto et = ov::element::f16;+ const auto wt = tc.u4 ? (tc.is_signed ? ov::element::i4 : ov::element::u4) : (tc.is_signed ? ov::element::i8 : ov::element::u8);++ std::mt19937 gen(static_cast<uint32_t>(D * 131 + L * 7 + (tc.u4 ? 3 : 0) + (tc.is_signed ? 5 : 0) + (tc.has_zp ? 11 : 0) + tc.group + 17));+ const auto m_down = make_quant_matrix(gen, L, CD, tc.u4, tc.is_signed, tc.has_zp, tc.group);+ const auto m_up = make_quant_matrix(gen, CD, L, tc.u4, tc.is_signed, tc.has_zp, tc.group);+ const auto m_inject = make_quant_matrix(gen, C, CD, tc.u4, tc.is_signed, tc.has_zp, tc.group);++ auto i64 = [](std::vector<int64_t> v) {+ return ov::op::v0::Constant::create(ov::element::i64, ov::Shape{v.size()}, v);+ };+ auto scalar = [&](float v) {+ return ov::op::v0::Constant::create(et, ov::Shape{}, {v});+ };+ // The exporter's decompression subgraph; quant_matrix keeps scale / zp as [G, N], the IR stores them as [N, G, 1].+ auto decompress = [&](const quant_matrix& m) -> ov::Output<ov::Node> {+ const size_t gs = m.K / m.G;+ const ov::Shape w_shape = m.G == 1 ? ov::Shape{m.N, m.K} : ov::Shape{m.N, m.G, gs};+ const ov::Shape s_shape = m.G == 1 ? ov::Shape{m.N, 1} : ov::Shape{m.N, m.G, 1};+ std::vector<int> q(m.N * m.K);+ for (size_t i = 0; i < q.size(); i++) {+ q[i] = m.value(m.q[i]);+ }+ std::vector<float> scale(m.N * m.G);+ std::vector<int> zp(m.N * m.G);+ for (size_t n = 0; n < m.N; n++) {+ for (size_t g = 0; g < m.G; g++) {+ scale[n * m.G + g] = m.scale[g * m.N + n];+ zp[n * m.G + g] = m.has_zp ? m.value(m.zp[g * m.N + n]) : 0;+ }+ }+ ov::Output<ov::Node> x = std::make_shared<ov::op::v0::Convert>(ov::op::v0::Constant::create(wt, w_shape, q), et);+ if (m.has_zp) {+ x = std::make_shared<ov::op::v1::Subtract>(x, std::make_shared<ov::op::v0::Convert>(ov::op::v0::Constant::create(wt, s_shape, zp), et));+ }+ x = std::make_shared<ov::op::v1::Multiply>(x, ov::op::v0::Constant::create(et, s_shape, scale));+ if (m.G != 1) {+ x = std::make_shared<ov::op::v1::Reshape>(x, i64({static_cast<int64_t>(m.N), static_cast<int64_t>(m.K)}), false);+ }+ return x;+ };+ auto scale_by_inv_c = [&](const ov::Output<ov::Node>& x) -> ov::Output<ov::Node> {+ if (tc.divide) {+ return std::make_shared<ov::op::v1::Divide>(x, ov::op::v0::Constant::create(et, ov::Shape{1, 1, 1}, {static_cast<float>(C)}));+ }+ return std::make_shared<ov::op::v1::Multiply>(x, scalar(1.0f / static_cast<float>(C)));+ };++ tests::random_generator rg;+ rg.set_seed(GET_SUITE_NAME);+ const auto gain_w = random_vec(rg, CD, 0.25f);+ std::vector<float> gain_folded(gain_w);+ for (auto& g : gain_folded) {+ g += 1.0f;+ }++ auto residual_p = std::make_shared<ov::op::v0::Parameter>(et, ov::PartialShape{-1, -1, iCD});+ auto gain_p = std::make_shared<ov::op::v0::Parameter>(et, ov::Shape{CD});+ auto split = [&](const ov::Output<ov::Node>& x) {+ return std::make_shared<ov::op::v1::Reshape>(x, i64({0, 0, iC, iD}), true);+ };+ auto r4 = split(residual_p);+ auto sq = std::make_shared<ov::op::v1::Power>(r4, scalar(2.0f));+ auto mean = std::make_shared<ov::op::v1::ReduceMean>(sq, i64({-1}), true);+ auto rms = std::make_shared<ov::op::v0::Sqrt>(std::make_shared<ov::op::v1::Add>(mean, scalar(eps)));+ auto inv_rms = std::make_shared<ov::op::v1::Divide>(scalar(1.0f), rms);+ auto normalized = std::make_shared<ov::op::v1::Multiply>(r4, inv_rms);+ auto normalized_flat = std::make_shared<ov::op::v1::Reshape>(normalized, i64({0, 0, iCD}), true);+ auto rbar = std::make_shared<ov::op::v1::Multiply>(normalized_flat, std::make_shared<ov::op::v1::Add>(gain_p, scalar(1.0f)));++ auto low = scale_by_inv_c(std::make_shared<ov::op::v0::MatMul>(rbar, decompress(m_down), false, true));+ auto up = std::make_shared<ov::op::v0::MatMul>(std::make_shared<ov::op::v4::Swish>(low), decompress(m_up), false, true);+ auto weighted = std::make_shared<ov::op::v1::Multiply>(split(std::make_shared<ov::op::v0::Sigmoid>(up)), split(rbar));+ auto mixed = std::make_shared<ov::op::v1::ReduceMean>(weighted, i64({-2}), false);++ ov::OutputVector outputs{mixed};+ if (tc.write_gate) {+ auto inject = scale_by_inv_c(std::make_shared<ov::op::v0::MatMul>(rbar, decompress(m_inject), false, true));+ outputs.push_back(std::make_shared<ov::op::v1::Multiply>(std::make_shared<ov::op::v0::Sigmoid>(inject), scalar(2.0f)));+ }+ auto model = std::make_shared<ov::Model>(outputs, ov::ParameterVector{residual_p, gain_p});++ ov::Core core;+ ov::CompiledModel compiled;+ OV_ASSERT_NO_THROW(compiled = core.compile_model(model, test_device_name(), ov::hint::inference_precision(ov::element::f16)));+ size_t fused_nodes = 0;+ size_t gemm_nodes = 0;+ std::string runtime_layers;+ for (const auto& op : compiled.get_runtime_model()->get_ops()) {+ const auto it = op->get_rt_info().find("layerType");+ const auto layer_type = it != op->get_rt_info().end() ? it->second.as<std::string>() : std::string("?");+ if (layer_type == "GatedResidual" || layer_type == "gated_residual") {+ fused_nodes++;+ }+ if (layer_type == "FullyConnected" || layer_type == "fully_connected" || layer_type == "Gemm" || layer_type == "gemm") {+ gemm_nodes++;+ }+ runtime_layers += layer_type + " ";+ }+ ASSERT_EQ(fused_nodes, 1u) << "the compressed READ was not fused into one gated_residual; runtime layers: " << runtime_layers;+ EXPECT_EQ(gemm_nodes, 0u) << "a MatMul is left; runtime layers: " << runtime_layers;++ // The runtime model hides constant inputs, so the weight form is checked on the plugin's transformation pipeline: the op must take+ // the compressed weights (W_inject too) and the scales / zero points converted to [G, N].+ {+ auto transformed = model->clone();+ auto& engine = get_test_engine();+ auto context = std::make_shared<ov::intel_gpu::RemoteContextImpl>("GPU", std::vector<cldnn::device::ptr>{engine.get_device()});+ auto config = get_test_default_config(engine);+ config.set_user_property(ov::hint::inference_precision(ov::element::f16));+ config.finalize(context.get(), transformed.get());+ ov::intel_gpu::TransformationsPipeline(config, context).apply(transformed);+ std::shared_ptr<ov::intel_gpu::op::GatedResidual> gr;+ for (const auto& node : transformed->get_ordered_ops()) {+ if (auto candidate = ov::as_type_ptr<ov::intel_gpu::op::GatedResidual>(node)) {+ ASSERT_EQ(gr, nullptr) << "more than one GatedResidual";+ gr = candidate;+ }+ }+ ASSERT_NE(gr, nullptr);+ using Idx = ov::intel_gpu::op::GatedResidual::ReadInputIdx;+ // residual, gain, W_down, W_up, scale_down, scale_up [, zp_down, zp_up] [, W_inject, scale_inject [, zp_inject]]+ const size_t expected_inputs = 6 + (tc.has_zp ? 2 : 0) + (tc.write_gate ? (tc.has_zp ? 3 : 2) : 0);+ ASSERT_EQ(gr->get_input_size(), expected_inputs) << "the fused op does not take the compressed weights";+ EXPECT_EQ(gr->get_produce_write_gate(), tc.write_gate);+ EXPECT_TRUE(gr->get_scale_gn()) << "the scales were not converted to [G, N]";+ // [G, N] scale / zero point constants must hold the values of the [N, G, 1] IR constants+ auto check_group_major = [&](size_t scale_idx, size_t zp_idx, const quant_matrix& m, const char* name) {+ auto scale = ov::as_type_ptr<ov::op::v0::Constant>(gr->get_input_node_shared_ptr(scale_idx));+ ASSERT_NE(scale, nullptr) << name;+ ASSERT_EQ(scale->get_shape(), (ov::Shape{m.G, m.N})) << name;+ const auto sv = scale->cast_vector<float>();+ for (size_t i = 0; i < sv.size(); i++) {+ ASSERT_EQ(sv[i], m.scale[i]) << name << " scale at " << i;+ }+ if (m.has_zp) {+ auto zp = ov::as_type_ptr<ov::op::v0::Constant>(gr->get_input_node_shared_ptr(zp_idx));+ ASSERT_NE(zp, nullptr) << name;+ ASSERT_EQ(zp->get_shape(), (ov::Shape{m.G, m.N})) << name;+ ASSERT_EQ(zp->get_element_type(), wt) << name;+ const auto zv = zp->cast_vector<int>();+ for (size_t i = 0; i < zv.size(); i++) {+ ASSERT_EQ(zv[i], m.value(m.zp[i])) << name << " zero point at " << i;+ }+ }+ };+ EXPECT_EQ(gr->get_input_element_type(Idx::W_DOWN), wt);+ EXPECT_EQ(gr->get_input_element_type(Idx::W_UP), wt);+ check_group_major(Idx::SCALE_DOWN, Idx::ZP_DOWN, m_down, "W_down");+ check_group_major(Idx::SCALE_UP, Idx::ZP_UP, m_up, "W_up");+ if (tc.write_gate) {+ const size_t w_inject = tc.has_zp ? 8 : 6;+ EXPECT_EQ(gr->get_input_element_type(w_inject), wt);+ check_group_major(w_inject + 1, w_inject + 2, m_inject, "W_inject");+ }+ }++ auto infer_request = compiled.create_infer_request();+ auto fill = [](ov::Tensor tensor, const std::vector<float>& data) {+ auto* dst = tensor.data<ov::float16>();+ ASSERT_EQ(tensor.get_size(), data.size());+ for (size_t i = 0; i < data.size(); i++) {+ dst[i] = ov::float16(data[i]);+ }+ };+ {+ ov::Tensor gain_tensor(et, ov::Shape{CD});+ fill(gain_tensor, gain_w);+ infer_request.set_tensor(gain_p, gain_tensor);+ }+ for (const size_t rows : {3, 64}) {+ tests::random_generator input_rg;+ input_rg.set_seed(static_cast<uint32_t>(rows));+ const auto residual = random_vec(input_rg, rows * CD, 1.0f);+ ov::Tensor residual_tensor(et, ov::Shape{1, rows, CD});+ fill(residual_tensor, residual);+ infer_request.set_tensor(residual_p, residual_tensor);++ gr_ref_params p;+ p.rows = rows;+ p.C = C;+ p.D = D;+ p.L = L;+ p.eps = eps;+ std::vector<float> ref_mixed;+ std::vector<float> ref_gate;+ reference_read(p, residual, gain_folded, m_down.dequant, m_up.dequant, tc.write_gate ? &m_inject.dequant : nullptr, ref_mixed, ref_gate);++ OV_ASSERT_NO_THROW(infer_request.infer());+ const auto mixed_tensor = infer_request.get_output_tensor(0);+ EXPECT_EQ(mixed_tensor.get_shape(), (ov::Shape{1, rows, D}));+ const auto* mixed_data = mixed_tensor.data<ov::float16>();+ ASSERT_EQ(mixed_tensor.get_size(), ref_mixed.size());+ for (size_t i = 0; i < ref_mixed.size(); i++) {+ ASSERT_NEAR(static_cast<float>(mixed_data[i]), ref_mixed[i], 2e-2f) << "mixed mismatch at rows=" << rows << " index=" << i;+ }+ if (tc.write_gate) {+ const auto gate_tensor = infer_request.get_output_tensor(1);+ EXPECT_EQ(gate_tensor.get_shape(), (ov::Shape{1, rows, C}));+ const auto* gate_data = gate_tensor.data<ov::float16>();+ ASSERT_EQ(gate_tensor.get_size(), ref_gate.size());+ for (size_t i = 0; i < ref_gate.size(); i++) {+ ASSERT_NEAR(static_cast<float>(gate_data[i]), ref_gate[i], 2e-2f) << "write gate mismatch at rows=" << rows << " index=" << i;+ }+ }+ }+}++// The first case is the common exported form: u4 with zero points and group 128 (G_down = G_inject = C*D / 128; W_up has K = L, which+// 128 does not divide, so it keeps the default group 32), the write gate and Divide(Const [1, 1, 1]). The others vary the group count+// (incl. G = 1), the zero points, the bit width and the 1/C form.+INSTANTIATE_TEST_SUITE_P(smoke,+ gated_residual_decomposed_quant_test,+ ::testing::Values(gr_decomposed_quant_case{128, 64, true, false, true, 128, true, true},+ gr_decomposed_quant_case{128, 64, true, false, true, 128, false, true},+ gr_decomposed_quant_case{128, 64, true, false, true, 128, true, false},+ gr_decomposed_quant_case{64, 32, true, false, true, 0, true, true},+ gr_decomposed_quant_case{64, 32, true, true, false, 0, true, true},+ gr_decomposed_quant_case{96, 64, true, false, true, 64, true, true},+ gr_decomposed_quant_case{96, 64, true, false, true, kPerChannel, true, true},+ gr_decomposed_quant_case{128, 64, false, false, true, 128, true, true},+ gr_decomposed_quant_case{64, 32, false, true, false, 0, false, true}),+ gated_residual_decomposed_quant_test::PrintToStringParamName);++// --- Residual width at run time ------------------------------------------------------------------------------------------------+//+// With a dynamic last dimension the residual's width is only known at run time. A residual whose width is not hc_count * hidden_size has+// to be rejected before any kernel runs: the kernels take their row count from the element count of the residual while the outputs are+// sized from its leading dimensions, so a wider residual would make them write past the end of the outputs.+constexpr size_t kWidthD = 64;+constexpr size_t kWidthL = 32;++/// [1, rows, width]+ov::PartialShape width_shape(size_t rows, size_t width) {+ return ov::PartialShape{1, static_cast<int64_t>(rows), static_cast<int64_t>(width)};+}++struct gr_width_model {+ network::ptr net;+ std::vector<float> gain;+ std::vector<float> w_down;+ std::vector<float> w_up;+};++gr_width_model make_dynamic_width_model(engine& eng, gated_residual::Mode mode, tests::random_generator& rg) {+ const size_t C = kBranches;+ const size_t D = kWidthD;+ const size_t L = kWidthL;+ const size_t CD = C * D;+ const auto iD = static_cast<int64_t>(D);+ const auto iC = static_cast<int64_t>(C);+ gr_width_model m;+ topology topology;+ topology.add(input_layout("residual", layout{ov::PartialShape{-1, -1, -1}, data_types::f16, format::bfyx}));+ if (mode == gated_residual::Mode::READ) {+ m.gain = random_vec(rg, CD, 0.5f, 1.0f);+ m.w_down = random_vec(rg, L * CD, 0.1f);+ m.w_up = random_vec(rg, CD * L, 0.1f);+ topology.add(data("gain", make_f16(eng, {static_cast<int64_t>(CD)}, m.gain)));+ topology.add(data("w_down", make_f16(eng, {static_cast<int64_t>(L), static_cast<int64_t>(CD)}, m.w_down)));+ topology.add(data("w_up", make_f16(eng, {static_cast<int64_t>(CD), static_cast<int64_t>(L)}, m.w_up)));+ topology.add(gated_residual("gr",+ {input_info("residual"), input_info("gain"), input_info("w_down"), input_info("w_up")},+ gated_residual::Mode::READ,+ C,+ D,+ L,+ 1e-6f,+ false));+ } else {+ topology.add(input_layout("y", layout{ov::PartialShape{-1, -1, iD}, data_types::f16, format::bfyx}));+ topology.add(input_layout("gate", layout{ov::PartialShape{-1, -1, iC}, data_types::f16, format::bfyx}));+ topology.add(gated_residual("gr", {input_info("residual"), input_info("y"), input_info("gate")}, gated_residual::Mode::WRITE, C, D, 0, 1e-6f, false));+ }+ ExecutionConfig config = get_test_default_config(eng);+ config.set_property(ov::intel_gpu::optimize_data(true));+ config.set_property(ov::intel_gpu::allow_new_shape_infer(true));+ m.net = get_network(eng, topology, config, get_test_stream_ptr(), false);+ return m;+}++class gated_residual_runtime_width_test : public ::testing::TestWithParam<gated_residual::Mode> {+public:+ static std::string PrintToStringParamName(const testing::TestParamInfo<gated_residual::Mode>& info) {+ return info.param == gated_residual::Mode::READ ? "read" : "write";+ }+};++TEST_P(gated_residual_runtime_width_test, rejects_residual_wider_than_hc_count_times_hidden_size) {+ if (!gr_available()) {+ GTEST_SKIP() << "no GatedResidual implementation is available on this device";+ }+ const auto mode = GetParam();+ const bool read = mode == gated_residual::Mode::READ;+ const size_t C = kBranches;+ const size_t D = kWidthD;+ const size_t CD = C * D;+ constexpr size_t rows = 2;+ constexpr float marker = 1234.0f;++ auto& engine = get_test_engine();+ tests::random_generator rg;+ rg.set_seed(GET_SUITE_NAME);+ auto model = make_dynamic_width_model(engine, mode, rg);++ // The output is the start of a larger buffer filled with a marker, so a write past the declared output can be seen.+ const size_t out_width = read ? D : CD;+ const size_t guarded_count = 16 * rows * out_width;+ auto guarded = engine.allocate_memory(layout{ov::PartialShape{static_cast<int64_t>(guarded_count)}, data_types::f16, format::bfyx});+ set_values(guarded, to_f16(std::vector<float>(guarded_count, marker)));+ model.net->set_output_memory("gr", engine.reinterpret_buffer(*guarded, layout{width_shape(rows, out_width), data_types::f16, format::bfyx}));++ // Twice the width: the element count is that of 2 * rows rows of C*D, while the leading dimensions say `rows`.+ model.net->set_input_data("residual", make_f16(engine, width_shape(rows, 2 * CD), random_vec(rg, rows * 2 * CD, 1.0f)));+ if (!read) {+ // Y and the gate have a row per element-count row, so only the width check can reject the residual.+ model.net->set_input_data("y", make_f16(engine, width_shape(2 * rows, D), random_vec(rg, 2 * rows * D, 1.0f)));+ model.net->set_input_data("gate", make_f16(engine, width_shape(2 * rows, C), random_vec(rg, 2 * rows * C, 1.0f, 1.0f)));+ }++ std::string error;+ try {+ model.net->execute();+ } catch (const std::exception& e) {+ error = e.what();+ }+ EXPECT_NE(error.find("width must equal"), std::string::npos) << "the wider residual was not rejected; error: '" << error << "'";++ cldnn::mem_lock<ov::float16> lock(guarded, get_test_stream());+ size_t written = 0;+ for (size_t i = 0; i < guarded_count; i++) {+ if (static_cast<float>(lock[i]) != marker) {+ written++;+ }+ }+ EXPECT_EQ(written, 0u) << "elements of the output buffer were written although the residual was rejected";+}++// The width check must not reject a residual of the expected width whose last dimension is only known at run time.+TEST_P(gated_residual_runtime_width_test, runs_residual_of_the_expected_width) {+ if (!gr_available()) {+ GTEST_SKIP() << "no GatedResidual implementation is available on this device";+ }+ const auto mode = GetParam();+ const bool read = mode == gated_residual::Mode::READ;+ const size_t C = kBranches;+ const size_t D = kWidthD;+ const size_t CD = C * D;+ constexpr size_t rows = 3;++ auto& engine = get_test_engine();+ tests::random_generator rg;+ rg.set_seed(GET_SUITE_NAME);+ auto model = make_dynamic_width_model(engine, mode, rg);++ const auto residual = random_vec(rg, rows * CD, 1.0f);+ model.net->set_input_data("residual", make_f16(engine, width_shape(rows, CD), residual));+ std::vector<float> expected;+ if (read) {+ gr_ref_params p;+ p.rows = rows;+ p.D = D;+ p.L = kWidthL;+ std::vector<float> gate;+ reference_read(p, residual, model.gain, model.w_down, model.w_up, nullptr, expected, gate);+ } else {+ const auto y = random_vec(rg, rows * D, 1.0f);+ const auto gate = random_vec(rg, rows * C, 1.0f, 1.0f);+ model.net->set_input_data("y", make_f16(engine, width_shape(rows, D), y));+ model.net->set_input_data("gate", make_f16(engine, width_shape(rows, C), gate));+ expected = reference_write(rows, C, D, residual, y, gate);+ }++ auto outputs = model.net->execute();+ ASSERT_EQ(model.net->get_primitive("gr")->get_output_layout(0).get_partial_shape(), width_shape(rows, read ? D : CD));+ cldnn::mem_lock<ov::float16> out(outputs.at("gr").get_memory(), get_test_stream());+ ASSERT_GE(out.size(), expected.size());+ for (size_t i = 0; i < expected.size(); i++) {+ ASSERT_NEAR(static_cast<float>(out[i]), expected[i], 2e-2f) << "mismatch at index " << i;+ }+}++INSTANTIATE_TEST_SUITE_P(smoke,+ gated_residual_runtime_width_test,+ ::testing::Values(gated_residual::Mode::READ, gated_residual::Mode::WRITE),+ gated_residual_runtime_width_test::PrintToStringParamName);++} // namespacediff --git a/src/plugins/intel_gpu/tests/unit/test_cases/qsa_ops_gpu_test.cpp b/src/plugins/intel_gpu/tests/unit/test_cases/qsa_ops_gpu_test.cppindex 1bdcda3f551..80f75ac6021 100644--- a/src/plugins/intel_gpu/tests/unit/test_cases/qsa_ops_gpu_test.cpp+++ b/src/plugins/intel_gpu/tests/unit/test_cases/qsa_ops_gpu_test.cpp@@ -6,7 +6,7 @@//// Covered:// - Paged and dense indexer + attention pairs against a CPU reference, both with toy-// dims and with the Qwen3.8-Flash-Next shape (config.json): H_iq=4, D_idx=128,+// dims and with a large GQA shape: H_iq=4, D_idx=128,// H_ik=1, r=4, budget 2048 tokens (block_topk=512), rotary 64, Hq=24, Hkv=2, Dh=256,// page 16. The GPU's top-k selection is validated against the reference scores with// an fp16 tolerance, and the attention output is then compared using that selection,@@ -104,9 +104,9 @@ struct split_dims {size_t Dv = 16;};-/// Qwen3.8-Flash-Next (config.json text_config). The indexer reuses the attention RoPE, so+/// Large GQA configuration. The indexer reuses the attention RoPE, so/// rotary = head_dim (256) * partial_rotary_factor (0.25); block_topk = indexer_budget / r.-split_dims qwen38_dims() {+split_dims gqa_dims() {split_dims d;d.Hiq = 4;d.Di = 128;@@ -124,7 +124,7 @@ split_dims qwen38_dims() {/// Plain DPAS attention with one worker and 4 heads per tile; GQA-DPAS needs Dh % 128 == 0.split_dims non_gqa_dpas_dims() {- auto d = qwen38_dims();+ auto d = gqa_dims();d.Dh = 64;d.Dv = 64;return d;@@ -132,7 +132,7 @@ split_dims non_gqa_dpas_dims() {/// n_rep = 32 exceeds GQA-DPAS's limit of 16; plain DPAS needs 4 workers and 8 heads per tile.split_dims wide_group_dims() {- auto d = qwen38_dims();+ auto d = gqa_dims();d.Hq = 32;d.Hkv = 1;return d;@@ -1652,38 +1652,33 @@ const route decode_scalar{IndexerPath::Decode, AttnPath::Scalar};const route decode_split{IndexerPath::Decode, AttnPath::Split};const route fused_scalar{IndexerPath::Fused, AttnPath::Scalar};-// Decode batches: Q2 score_partition + top-k, Q3 GQA-DPAS (qwen38 dims).-TEST(qsa_ops_gpu_test, qwen38_paged_batch_decode_matches_reference) {- run_paged_batch_test(qwen38_dims(), {{2100, 1}, {2600, 1}, {3071, 1}}, decode_gqa, 3e-3f);+// Decode batches: Q2 score_partition + top-k, Q3 GQA-DPAS (GQA dims).+TEST(qsa_ops_gpu_test, gqa_paged_batch_decode_matches_reference) {+ run_paged_batch_test(gqa_dims(), {{2051, 1}, {2100, 1}, {2300, 1}}, decode_gqa, 3e-3f);}-TEST(qsa_ops_gpu_test, qwen38_dense_batch_decode_matches_reference) {- run_dense_batch_test(qwen38_dims(), 3, 3071, 1, decode_gqa, 3e-3f);+TEST(qsa_ops_gpu_test, gqa_dense_batch_decode_matches_reference) {+ run_dense_batch_test(gqa_dims(), 3, 2051, 1, decode_gqa, 3e-3f);}// Same, with a one-row BLOCK_SCORES budget. The paged scratch row is sized from the page table-// (past_lens stay in GPU memory), i.e. the whole 1948-block pool, so only one row fits per+// (past_lens stay in GPU memory), i.e. the whole page pool, so only one row fits per// chunk: 3 chunks of one sequence each.-TEST(qsa_ops_gpu_test, qwen38_paged_batch_decode_chunked_scores_match_reference) {+TEST(qsa_ops_gpu_test, gqa_paged_batch_decode_chunked_scores_match_reference) {scoped_score_budget budget("1");- run_paged_batch_test(qwen38_dims(), {{2100, 1}, {2600, 1}, {3071, 1}}, {IndexerPath::Decode, AttnPath::GqaSplit, 3}, 3e-3f);+ run_paged_batch_test(gqa_dims(), {{2051, 1}, {2100, 1}, {2300, 1}}, {IndexerPath::Decode, AttnPath::GqaSplit, 3}, 3e-3f);}-TEST(qsa_ops_gpu_test, qwen38_dense_batch_decode_chunked_scores_match_reference) {- scoped_score_budget budget("1");- run_dense_batch_test(qwen38_dims(), 3, 3071, 1, {IndexerPath::Decode, AttnPath::GqaSplit, 3}, 3e-3f);-}--// Budget of exactly two 768-block rows: a full chunk followed by a partial one.-TEST(qsa_ops_gpu_test, qwen38_dense_batch_decode_partial_last_chunk_matches_reference) {+// Budget of two rows: a full chunk followed by a partial one.+TEST(qsa_ops_gpu_test, gqa_dense_batch_decode_partial_last_chunk_matches_reference) {scoped_score_budget budget("6144");- run_dense_batch_test(qwen38_dims(), 3, 3071, 1, {IndexerPath::Decode, AttnPath::GqaSplit, 2}, 3e-3f);+ run_dense_batch_test(gqa_dims(), 3, 2051, 1, {IndexerPath::Decode, AttnPath::GqaSplit, 2}, 3e-3f);}-// Mixed batches (decode + prefill sequences in one call): dpas Q2 with qwen38 dims, the+// Mixed batches (decode + prefill sequences in one call): dpas Q2 with GQA dims, the// fused non-dpas Q2 with the toy dims (Di = 16 fails the dpas score gate).-TEST(qsa_ops_gpu_test, qwen38_paged_batch_mixed_matches_reference) {- run_paged_batch_test(qwen38_dims(), {{2100, 1}, {1990, 64}, {2500, 1}}, dpas_gqa, 3e-3f);+TEST(qsa_ops_gpu_test, gqa_paged_batch_mixed_matches_reference) {+ run_paged_batch_test(gqa_dims(), {{2100, 1}, {1990, 64}, {2060, 1}}, dpas_gqa, 3e-3f);}TEST(qsa_ops_gpu_test, paged_batch_mixed_fused_score_topk_matches_reference) {@@ -1694,15 +1689,6 @@ TEST(qsa_ops_gpu_test, paged_batch_decode_toy_dims_matches_reference) {run_paged_batch_test(split_dims{}, {{20, 1}, {37, 1}, {63, 1}}, decode_split, 2e-2f);}-// Toy dims have no GQA-DPAS, so long decode takes the split + reduce fallback.-TEST(qsa_ops_gpu_test, paged_batch_long_decode_split_fallback_matches_reference) {- run_paged_batch_test(split_dims{}, {{2100, 1}, {2500, 1}}, decode_split, 2e-2f);-}--TEST(qsa_ops_gpu_test, dense_batch_long_decode_split_fallback_matches_reference) {- run_dense_batch_test(split_dims{}, 2, 2100, 1, decode_split, 2e-2f);-}-// ---------------------------------------------------------------------------// Multi-batch dense rows of different key lengths: K/V of shorter rows are left-padded// (logical key j at S - key_length + j), and rows shorter than L are fresh, left-padded@@ -1719,20 +1705,20 @@ TEST(qsa_ops_gpu_test, dense_batch_ragged_decode_scalar_matches_reference) {}TEST(qsa_ops_gpu_test, dense_batch_ragged_long_decode_split_matches_reference) {- run_dense_batch_test(split_dims{}, {{2100, 1}, {15, 1}}, decode_split, 2e-2f);+ run_dense_batch_test(split_dims{}, {{2051, 1}, {15, 1}}, decode_split, 2e-2f);}// Padding spans whole and partial 16-query tiles of the plain DPAS kernel.TEST(qsa_ops_gpu_test, dense_batch_left_padding_plain_dpas_matches_reference) {- run_dense_batch_test(non_gqa_dpas_dims(), {{2100, 33}, {0, 9}, {0, 20}}, dpas_dpas, 3e-3f);+ run_dense_batch_test(non_gqa_dpas_dims(), {{2051, 33}, {0, 9}, {0, 20}}, dpas_dpas, 3e-3f);}-TEST(qsa_ops_gpu_test, qwen38_dense_batch_left_padding_prefill_matches_reference) {- run_dense_batch_test(qwen38_dims(), {{4032, 64}, {0, 40}, {0, 64}}, dpas_gqa, 3e-3f);+TEST(qsa_ops_gpu_test, gqa_dense_batch_left_padding_prefill_matches_reference) {+ run_dense_batch_test(gqa_dims(), {{2044, 64}, {0, 40}, {0, 64}}, dpas_gqa, 3e-3f);}-TEST(qsa_ops_gpu_test, qwen38_dense_batch_ragged_decode_matches_reference) {- run_dense_batch_test(qwen38_dims(), {{3071, 1}, {15, 1}, {2050, 1}}, decode_gqa, 3e-3f);+TEST(qsa_ops_gpu_test, gqa_dense_batch_ragged_decode_matches_reference) {+ run_dense_batch_test(gqa_dims(), {{2100, 1}, {15, 1}, {2051, 1}}, decode_gqa, 3e-3f);}// ---------------------------------------------------------------------------@@ -1744,19 +1730,11 @@ TEST(qsa_ops_gpu_test, dense_state_carries_across_calls) {run_dense_state_chain_test(split_dims{}, {37, 1, 1, 6, 1, 3, 2}, 2e-2f);}-TEST(qsa_ops_gpu_test, qwen38_dense_state_carries_across_calls) {- run_dense_state_chain_test(qwen38_dims(), {2050, 1, 1, 17, 1}, 3e-3f);+TEST(qsa_ops_gpu_test, gqa_dense_state_carries_across_calls) {+ run_dense_state_chain_test(gqa_dims(), {2050, 1, 1, 17, 1}, 3e-3f);}// Toy Dh = 16 is below the 64-byte DPAS row minimum, so prefill takes the scalar Q3 kernel.-TEST(qsa_ops_gpu_test, paged_pair_matches_reference) {- run_pair_test(true, split_dims{}, 20, 44, Positions::Sequential, fused_scalar, 2e-2f);-}--TEST(qsa_ops_gpu_test, dense_pair_matches_reference) {- run_pair_test(false, split_dims{}, 20, 44, Positions::Sequential, fused_scalar, 2e-2f);-}-TEST(qsa_ops_gpu_test, paged_pair_mrope_positions_match_reference) {run_pair_test(true, split_dims{}, 22, 42, Positions::MRoPELike, fused_scalar, 2e-2f);}@@ -1765,36 +1743,32 @@ TEST(qsa_ops_gpu_test, dense_pair_mrope_positions_match_reference) {run_pair_test(false, split_dims{}, 22, 42, Positions::MRoPELike, fused_scalar, 2e-2f);}-// Qwen3.8-Flash-Next shapes: decode one token over a long history (partial last block+// Large GQA shapes: decode one token over a long history (partial last block// completed by this call), and a 64-token prefill chunk on top of a cached prefix.-TEST(qsa_ops_gpu_test, qwen38_paged_decode_matches_reference) {- run_pair_test(true, qwen38_dims(), 8191, 1, Positions::Sequential, decode_gqa, 3e-3f);+TEST(qsa_ops_gpu_test, gqa_paged_decode_matches_reference) {+ run_pair_test(true, gqa_dims(), 2103, 1, Positions::Sequential, decode_gqa, 3e-3f);}-TEST(qsa_ops_gpu_test, qwen38_paged_prefill_matches_reference) {- run_pair_test(true, qwen38_dims(), 4032, 64, Positions::Sequential, dpas_gqa, 3e-3f);+TEST(qsa_ops_gpu_test, gqa_paged_prefill_mrope_matches_reference) {+ run_pair_test(true, gqa_dims(), 2046, 66, Positions::MRoPELike, dpas_gqa, 3e-3f);}-TEST(qsa_ops_gpu_test, qwen38_paged_prefill_mrope_matches_reference) {- run_pair_test(true, qwen38_dims(), 4030, 66, Positions::MRoPELike, dpas_gqa, 3e-3f);+TEST(qsa_ops_gpu_test, gqa_dense_decode_matches_reference) {+ run_pair_test(false, gqa_dims(), 2103, 1, Positions::Sequential, decode_gqa, 3e-3f);}-TEST(qsa_ops_gpu_test, qwen38_dense_decode_matches_reference) {- run_pair_test(false, qwen38_dims(), 8191, 1, Positions::Sequential, decode_gqa, 3e-3f);-}--TEST(qsa_ops_gpu_test, qwen38_dense_prefill_matches_reference) {- run_pair_test(false, qwen38_dims(), 4032, 64, Positions::Sequential, dpas_gqa, 3e-3f);+TEST(qsa_ops_gpu_test, gqa_dense_prefill_matches_reference) {+ run_pair_test(false, gqa_dims(), 2044, 64, Positions::Sequential, dpas_gqa, 3e-3f);}// Prefill rows on both sides of the top-k boundary (510..514 complete blocks vs K = 512):// one top-k dispatch mixes select-all rows with real selections.-TEST(qsa_ops_gpu_test, qwen38_paged_prefill_crossing_topk_boundary_matches_reference) {- run_pair_test(true, qwen38_dims(), 2040, 17, Positions::Sequential, dpas_gqa, 3e-3f);+TEST(qsa_ops_gpu_test, gqa_paged_prefill_crossing_topk_boundary_matches_reference) {+ run_pair_test(true, gqa_dims(), 2040, 17, Positions::Sequential, dpas_gqa, 3e-3f);}-TEST(qsa_ops_gpu_test, qwen38_dense_prefill_crossing_topk_boundary_matches_reference) {- run_pair_test(false, qwen38_dims(), 2040, 17, Positions::Sequential, dpas_gqa, 3e-3f);+TEST(qsa_ops_gpu_test, gqa_dense_prefill_crossing_topk_boundary_matches_reference) {+ run_pair_test(false, gqa_dims(), 2040, 17, Positions::Sequential, dpas_gqa, 3e-3f);}// ---------------------------------------------------------------------------@@ -1802,34 +1776,34 @@ TEST(qsa_ops_gpu_test, qwen38_dense_prefill_crossing_topk_boundary_matches_refer// without reading scores and early tokens attend to the causal tail only.// ----------------------------------------------------------------------------TEST(qsa_ops_gpu_test, qwen38_paged_short_prefill_selects_every_block) {- run_full_selection_pair_test(true, qwen38_dims(), 0, 17, dpas_gqa, 3e-3f);+TEST(qsa_ops_gpu_test, gqa_paged_short_prefill_selects_every_block) {+ run_full_selection_pair_test(true, gqa_dims(), 0, 17, dpas_gqa, 3e-3f);}-TEST(qsa_ops_gpu_test, qwen38_dense_short_prefill_selects_every_block) {- run_full_selection_pair_test(false, qwen38_dims(), 0, 17, dpas_gqa, 3e-3f);+TEST(qsa_ops_gpu_test, gqa_dense_short_prefill_selects_every_block) {+ run_full_selection_pair_test(false, gqa_dims(), 0, 17, dpas_gqa, 3e-3f);}-TEST(qsa_ops_gpu_test, qwen38_paged_short_decode_selects_every_block) {- run_full_selection_pair_test(true, qwen38_dims(), 15, 1, decode_gqa, 3e-3f);+TEST(qsa_ops_gpu_test, gqa_paged_short_decode_selects_every_block) {+ run_full_selection_pair_test(true, gqa_dims(), 15, 1, decode_gqa, 3e-3f);}-TEST(qsa_ops_gpu_test, qwen38_dense_short_decode_selects_every_block) {- run_full_selection_pair_test(false, qwen38_dims(), 15, 1, decode_gqa, 3e-3f);+TEST(qsa_ops_gpu_test, gqa_dense_short_decode_selects_every_block) {+ run_full_selection_pair_test(false, gqa_dims(), 15, 1, decode_gqa, 3e-3f);}// One decode batch with 4, exactly 512 (score bypass) and 513 (scored) complete blocks.-TEST(qsa_ops_gpu_test, qwen38_paged_batch_decode_around_topk_boundary_matches_reference) {- run_paged_batch_test(qwen38_dims(), {{15, 1}, {2047, 1}, {2051, 1}}, decode_gqa, 3e-3f);+TEST(qsa_ops_gpu_test, gqa_paged_batch_decode_around_topk_boundary_matches_reference) {+ run_paged_batch_test(gqa_dims(), {{15, 1}, {2047, 1}, {2051, 1}}, decode_gqa, 3e-3f);}-TEST(qsa_ops_gpu_test, qwen38_dense_batch_decode_at_topk_boundary_matches_reference) {- run_dense_batch_test(qwen38_dims(), 2, 2047, 1, decode_gqa, 3e-3f);+TEST(qsa_ops_gpu_test, gqa_dense_batch_decode_at_topk_boundary_matches_reference) {+ run_dense_batch_test(gqa_dims(), 2, 2047, 1, decode_gqa, 3e-3f);}// Short decode, a long decode and a fresh prefill sequence in one call.-TEST(qsa_ops_gpu_test, qwen38_paged_batch_mixed_short_and_long_matches_reference) {- run_paged_batch_test(qwen38_dims(), {{15, 1}, {2100, 1}, {0, 17}}, dpas_gqa, 3e-3f);+TEST(qsa_ops_gpu_test, gqa_paged_batch_mixed_short_and_long_matches_reference) {+ run_paged_batch_test(gqa_dims(), {{15, 1}, {2051, 1}, {0, 17}}, dpas_gqa, 3e-3f);}// ---------------------------------------------------------------------------@@ -1838,32 +1812,24 @@ TEST(qsa_ops_gpu_test, qwen38_paged_batch_mixed_short_and_long_matches_reference// ---------------------------------------------------------------------------TEST(qsa_ops_gpu_test, paged_pair_plain_dpas_attention_matches_reference) {- run_pair_test(true, non_gqa_dpas_dims(), 2100, 17, Positions::Sequential, dpas_dpas, 3e-3f);+ run_pair_test(true, non_gqa_dpas_dims(), 2051, 17, Positions::Sequential, dpas_dpas, 3e-3f);}TEST(qsa_ops_gpu_test, dense_pair_plain_dpas_attention_matches_reference) {- run_pair_test(false, non_gqa_dpas_dims(), 2100, 17, Positions::Sequential, dpas_dpas, 3e-3f);+ run_pair_test(false, non_gqa_dpas_dims(), 2051, 17, Positions::Sequential, dpas_dpas, 3e-3f);}TEST(qsa_ops_gpu_test, paged_pair_plain_dpas_four_workers_matches_reference) {- run_pair_test(true, wide_group_dims(), 2100, 16, Positions::Sequential, dpas_dpas, 3e-3f);-}--TEST(qsa_ops_gpu_test, dense_pair_plain_dpas_four_workers_matches_reference) {- run_pair_test(false, wide_group_dims(), 2100, 16, Positions::Sequential, dpas_dpas, 3e-3f);+ run_pair_test(true, wide_group_dims(), 2051, 16, Positions::Sequential, dpas_dpas, 3e-3f);}TEST(qsa_ops_gpu_test, paged_pair_plain_dpas_one_head_per_tile_matches_reference) {- run_pair_test(true, mha_dpas_dims(), 2100, 17, Positions::Sequential, dpas_dpas, 3e-3f);-}--TEST(qsa_ops_gpu_test, dense_pair_plain_dpas_one_head_per_tile_matches_reference) {- run_pair_test(false, mha_dpas_dims(), 2100, 17, Positions::Sequential, dpas_dpas, 3e-3f);+ run_pair_test(true, mha_dpas_dims(), 2051, 17, Positions::Sequential, dpas_dpas, 3e-3f);}// Per-sequence query tiles: two single-token decode tiles plus a 16 + 1 prefill.TEST(qsa_ops_gpu_test, paged_batch_mixed_plain_dpas_attention_matches_reference) {- run_paged_batch_test(non_gqa_dpas_dims(), {{15, 1}, {2100, 1}, {2040, 17}}, dpas_dpas, 3e-3f);+ run_paged_batch_test(non_gqa_dpas_dims(), {{15, 1}, {2051, 1}, {2040, 17}}, dpas_dpas, 3e-3f);}// ---------------------------------------------------------------------------@@ -1871,11 +1837,7 @@ TEST(qsa_ops_gpu_test, paged_batch_mixed_plain_dpas_attention_matches_reference)// splits; dense compares the whole K length (past_len + 1) with 2048.// ----------------------------------------------------------------------------TEST(qsa_ops_gpu_test, paged_batch_short_decode_uses_split) {- run_paged_batch_test(non_gqa_dpas_dims(), {{2047, 1}, {3000, 1}}, decode_split, 3e-3f);-}--TEST(qsa_ops_gpu_test, paged_batch_long_decode_uses_split) {+TEST(qsa_ops_gpu_test, paged_batch_decode_uses_split) {run_paged_batch_test(non_gqa_dpas_dims(), {{2048, 1}, {3000, 1}}, decode_split, 3e-3f);}@@ -1904,11 +1866,7 @@ TEST(qsa_ops_gpu_test, paged_pair_large_magnitude_inputs_stay_finite_and_accurat// of elements with closely competing logits -- this is expected floating-point// behavior, not a kernel bug, and a tighter bound here would be testing summation// order, not correctness.- run_pair_test(true, qwen38_dims(), 4032, 64, Positions::Sequential, dpas_gqa, /*rtol=*/1e-2f, /*atol=*/1e-2f, /*scale=*/3.0f);-}--TEST(qsa_ops_gpu_test, dense_pair_large_magnitude_inputs_stay_finite_and_accurate) {- run_pair_test(false, qwen38_dims(), 4032, 64, Positions::Sequential, dpas_gqa, /*rtol=*/1e-2f, /*atol=*/1e-2f, /*scale=*/3.0f);+ run_pair_test(true, gqa_dims(), 2044, 64, Positions::Sequential, dpas_gqa, /*rtol=*/1e-2f, /*atol=*/1e-2f, /*scale=*/3.0f);}TEST(qsa_ops_gpu_test, paged_pair_dominant_outlier_component_stays_accurate) {@@ -1918,10 +1876,10 @@ TEST(qsa_ops_gpu_test, paged_pair_dominant_outlier_component_stays_accurate) {if (!qsa_ops_available()) {GTEST_SKIP() << "Intel subgroup extensions are not supported on this device";}- const auto d = qwen38_dims();+ const auto d = gqa_dims();auto& engine = get_test_engine();tests::random_generator rg(GET_SUITE_NAME);- auto ref = make_split_reference(rg, d, 4032, 64, Positions::Sequential);+ auto ref = make_split_reference(rg, d, 2044, 64, Positions::Sequential);ref.index_query_cur[0] = static_cast<float>(ov::float16(40.0f));ref.raw_index_keys_all[0] = static_cast<float>(ov::float16(40.0f));ref.summary_memo.clear();@@ -1932,10 +1890,10 @@ TEST(qsa_ops_gpu_test, dense_pair_dominant_outlier_component_stays_accurate) {if (!qsa_ops_available()) {GTEST_SKIP() << "Intel subgroup extensions are not supported on this device";}- const auto d = qwen38_dims();+ const auto d = gqa_dims();auto& engine = get_test_engine();tests::random_generator rg(GET_SUITE_NAME);- auto ref = make_split_reference(rg, d, 4032, 64, Positions::Sequential);+ auto ref = make_split_reference(rg, d, 2044, 64, Positions::Sequential);ref.index_query_cur[0] = static_cast<float>(ov::float16(40.0f));ref.raw_index_keys_all[0] = static_cast<float>(ov::float16(40.0f));ref.summary_memo.clear();@@ -1944,12 +1902,14 @@ TEST(qsa_ops_gpu_test, dense_pair_dominant_outlier_component_stays_accurate) {// Many more blocks than the prefill cases above: checks that per-block summary error and// online-softmax accumulation error do not grow with the number of terms summed.-TEST(qsa_ops_gpu_test, qwen38_paged_long_context_accumulation_matches_reference) {- run_pair_test(true, qwen38_dims(), 8192, 128, Positions::Sequential, dpas_gqa, 3e-3f);+// More than 2048 complete blocks: the prefill top-k uses its widest work-group (16 subgroups), and+// per-block summary / online-softmax accumulation error must not grow with the number of terms.+TEST(qsa_ops_gpu_test, gqa_paged_long_context_accumulation_matches_reference) {+ run_pair_test(true, gqa_dims(), 8192, 17, Positions::Sequential, dpas_gqa, 3e-3f);}-TEST(qsa_ops_gpu_test, qwen38_dense_long_context_accumulation_matches_reference) {- run_pair_test(false, qwen38_dims(), 8192, 128, Positions::Sequential, dpas_gqa, 3e-3f);+TEST(qsa_ops_gpu_test, gqa_dense_long_context_accumulation_matches_reference) {+ run_pair_test(false, gqa_dims(), 8192, 17, Positions::Sequential, dpas_gqa, 3e-3f);}// ---------------------------------------------------------------------------@@ -2024,7 +1984,7 @@ std::vector<dynamic_step> toy_dynamic_steps(bool paged) {const route decode = paged ? decode_split : decode_scalar;return {{0, 37, fused_scalar}, {37, 1, decode}, {38, 1, decode}, {39, 6, fused_scalar}, {45, 1, decode}};}-const std::vector<dynamic_step> qwen38_dynamic_steps = {{2100, 17, dpas_gqa}, {2117, 1, decode_gqa}, {2118, 1, decode_gqa}, {40, 9, dpas_gqa}};+const std::vector<dynamic_step> gqa_dynamic_steps = {{2051, 17, dpas_gqa}, {2068, 1, decode_gqa}, {2069, 1, decode_gqa}, {40, 9, dpas_gqa}};TEST(qsa_ops_gpu_test, paged_pair_dynamic_shapes_reuse_one_network) {run_dynamic_pair_test(true, split_dims{}, toy_dynamic_steps(true), 2e-3f);@@ -2034,12 +1994,12 @@ TEST(qsa_ops_gpu_test, dense_pair_dynamic_shapes_reuse_one_network) {run_dynamic_pair_test(false, split_dims{}, toy_dynamic_steps(false), 2e-3f);}-TEST(qsa_ops_gpu_test, qwen38_paged_pair_dynamic_shapes_reuse_one_network) {- run_dynamic_pair_test(true, qwen38_dims(), qwen38_dynamic_steps, 3e-3f);+TEST(qsa_ops_gpu_test, gqa_paged_pair_dynamic_shapes_reuse_one_network) {+ run_dynamic_pair_test(true, gqa_dims(), gqa_dynamic_steps, 3e-3f);}-TEST(qsa_ops_gpu_test, qwen38_dense_pair_dynamic_shapes_reuse_one_network) {- run_dynamic_pair_test(false, qwen38_dims(), qwen38_dynamic_steps, 3e-3f);+TEST(qsa_ops_gpu_test, gqa_dense_pair_dynamic_shapes_reuse_one_network) {+ run_dynamic_pair_test(false, gqa_dims(), gqa_dynamic_steps, 3e-3f);}// ---------------------------------------------------------------------------@@ -2162,12 +2122,12 @@ TEST(qsa_ops_gpu_test, dense_attention_plain_dpas_reads_padded_kv) {run_padded_kv_attention_test(d, 37, 20, 13, 5, AttnPath::Dpas, 3e-3f);}-TEST(qsa_ops_gpu_test, qwen38_dense_attention_gqa_dpas_reads_padded_kv) {- run_padded_kv_attention_test(qwen38_dims(), 37, 5, 9, 17, AttnPath::GqaDpas, 3e-3f);+TEST(qsa_ops_gpu_test, gqa_dense_attention_gqa_dpas_reads_padded_kv) {+ run_padded_kv_attention_test(gqa_dims(), 37, 5, 9, 17, AttnPath::GqaDpas, 3e-3f);}-TEST(qsa_ops_gpu_test, qwen38_dense_attention_gqa_split_reads_padded_kv) {- run_padded_kv_attention_test(qwen38_dims(), 40, 1, 9, 17, AttnPath::GqaSplit, 3e-3f);+TEST(qsa_ops_gpu_test, gqa_dense_attention_gqa_split_reads_padded_kv) {+ run_padded_kv_attention_test(gqa_dims(), 40, 1, 9, 17, AttnPath::GqaSplit, 3e-3f);}// ---------------------------------------------------------------------------@@ -2279,11 +2239,11 @@ void run_sparse_sdpa_kv_cache_model_test(const split_dims& d, const std::vector<}TEST(qsa_ops_gpu_test, sparse_sdpa_reads_kv_cache_across_infer_calls) {- run_sparse_sdpa_kv_cache_model_test(two_kv_head_dims(), {37, 1, 1, 6, 1, 2003, 1, 1}, 2e-3f);+ run_sparse_sdpa_kv_cache_model_test(two_kv_head_dims(), {37, 1, 1, 6, 1, 2003, 1}, 2e-3f);}-TEST(qsa_ops_gpu_test, qwen38_sparse_sdpa_reads_kv_cache_across_infer_calls) {- run_sparse_sdpa_kv_cache_model_test(qwen38_dims(), {37, 1, 1, 9, 1}, 3e-3f);+TEST(qsa_ops_gpu_test, gqa_sparse_sdpa_reads_kv_cache_across_infer_calls) {+ run_sparse_sdpa_kv_cache_model_test(gqa_dims(), {37, 1, 1, 9, 1}, 3e-3f);}// ---------------------------------------------------------------------------@@ -2500,10 +2460,7 @@ TEST_P(QSAIndexerPluginTest, AbsorbsQueryPreprocessingBeforeLowering) {EXPECT_NO_THROW(core.compile_model(model, "GPU", ov::hint::inference_precision(ov::element::f16)));}-INSTANTIATE_TEST_SUITE_P(QSA,- QSAIndexerPluginTest,- ::testing::Bool(),- ([](const ::testing::TestParamInfo<bool>& info) {+INSTANTIATE_TEST_SUITE_P(QSA, QSAIndexerPluginTest, ::testing::Bool(), ([](const ::testing::TestParamInfo<bool>& info) {return info.param ? "Paged" : "Dense";}));@@ -2871,7 +2828,7 @@ TEST(qsa_ops_gpu_test, plugin_rejects_unsupported_indexer_heads_and_precision) {// ---------------------------------------------------------------------------// Performance (DISABLED_ by default). Wall-clock per synchronous execute(), which-// includes host dispatch and plan uploads, with Qwen3.8-Flash-Next shapes. The traffic+// includes host dispatch and plan uploads, with Large GQA shapes. The traffic// estimate assumes no cache reuse across query tokens, so prefill GB/s is an upper bound.// ---------------------------------------------------------------------------@@ -2938,12 +2895,12 @@ void print_perf(const char* op, const perf_case& c, const perf_timing& t, doubleclass qsa_ops_perf : public ::testing::TestWithParam<perf_case> {};-TEST_P(qsa_ops_perf, qwen38) {+TEST_P(qsa_ops_perf, gqa) {if (!qsa_ops_available()) {GTEST_SKIP() << "Intel subgroup extensions are not supported on this device";}const auto c = GetParam();- auto d = qwen38_dims();+ auto d = gqa_dims();if (c.no_dpas_score) {d.Di = 16;d.rotary = 8;@@ -3008,7 +2965,7 @@ INSTANTIATE_TEST_SUITE_P(DISABLED_qsa_ops_perf,});// Per-kernel sweep driver for external GPU tracing (e.g. onetrace -d): one dense (QSAIndexer +-// SparseSDPA) or paged (PagedQSAIndexer + SparsePA) pair with Qwen3.8 dims, configured via the+// SparseSDPA) or paged (PagedQSAIndexer + SparsePA) pair with large-GQA dims, configured via the// environment: QSA_PERF_IMPL=dense|paged, QSA_PERF_PHASE=prefill|decode, QSA_PERF_B, QSA_PERF_LEN// (prompt length / history length), QSA_PERF_ITERS, QSA_PERF_WARMUP, QSA_PERF_FLUSH_MB (writes// that many MiB between iterations to evict L2), QSA_PERF_STAGES (comma list of pair|indexer|attention, default pair).@@ -3048,9 +3005,9 @@ TEST(qsa_ops_perf_sweep, DISABLED_pair) {const std::string out_id = stage == Stage::IndexerOnly ? "indexer" : "attn";std::unique_ptr<network> net;if (impl == "paged") {- net = build_paged_network(engine, paged_inputs_synthetic(qwen38_dims(), past, q_len, batch), stage);+ net = build_paged_network(engine, paged_inputs_synthetic(gqa_dims(), past, q_len, batch), stage);} else {- net = build_dense_network(engine, dense_inputs_synthetic(qwen38_dims(), past, q_len, batch), stage);+ net = build_dense_network(engine, dense_inputs_synthetic(gqa_dims(), past, q_len, batch), stage);}auto run_once = [&]() {if (flush) {diff --git a/src/plugins/intel_gpu/tests/unit/test_cases/sparse_pa_kvq_gpu_test.cpp b/src/plugins/intel_gpu/tests/unit/test_cases/sparse_pa_kvq_gpu_test.cppindex ffdebbb6c23..c9c4e490890 100644--- a/src/plugins/intel_gpu/tests/unit/test_cases/sparse_pa_kvq_gpu_test.cpp+++ b/src/plugins/intel_gpu/tests/unit/test_cases/sparse_pa_kvq_gpu_test.cpp@@ -267,7 +267,7 @@ struct dims {size_t Hq = 24, Hkv = 2, Dh = 256, Dv = 256, r = 4, page = 16, topk = 512;};-dims qwen38() {+dims gqa() {return {};}dims toy() {@@ -774,28 +774,31 @@ std::vector<kvq_case> all_cases() {auto add = [&](const char* dn, const dims& d, const KVQuant& k, const KVQuant& v, std::vector<seq_spec> seqs) {cases.push_back({case_name(dn, k, v, seqs), d, k, v, std::move(seqs)});};- const std::vector<std::vector<seq_spec>> scenarios = {{{0, 37}}, {{21, 1}}, {{123, 45}}, {{2051, 1}}, {{40, 1}, {0, 70}, {17, 3}}};+ const std::vector<std::vector<seq_spec>> scenarios = {{{21, 1}}, {{123, 45}}, {{40, 1}, {0, 70}, {17, 3}}};+ // Long decode (more complete blocks than topk): one token-mode and one channel-mode format.+ const std::vector<seq_spec> long_decode = {{2051, 1}};+ add("gqa", gqa(), token_quant(8, false), token_quant(8, false), long_decode);+ add("gqa", gqa(), channel_quant(4, false, 16), token_quant(4, false), long_decode);for (const auto& seqs : scenarios) {// Token-mode keys, both bit widths and both symmetries.- add("qwen", qwen38(), token_quant(8, false), token_quant(8, false), seqs);- add("qwen", qwen38(), token_quant(4, true), token_quant(4, true), seqs);+ add("gqa", gqa(), token_quant(8, false), token_quant(8, false), seqs);+ add("gqa", gqa(), token_quant(4, true), token_quant(4, true), seqs);// BY_CHANNEL keys.- add("qwen", qwen38(), channel_quant(8, false, 16), token_quant(8, false), seqs);- add("qwen", qwen38(), channel_quant(4, false, 16), token_quant(4, false), seqs);- add("qwen", qwen38(), channel_quant(8, true, 16), token_quant(8, true), seqs);+ add("gqa", gqa(), channel_quant(8, false, 16), token_quant(8, false), seqs);+ add("gqa", gqa(), channel_quant(4, false, 16), token_quant(4, false), seqs);+ add("gqa", gqa(), channel_quant(8, true, 16), token_quant(8, true), seqs);}// Page 32 with 32-token groups, and the scalar kernels (head size 64 -> no GQA-DPAS for quantized caches).- dims wide_page = qwen38();+ dims wide_page = gqa();wide_page.page = 32;- for (const auto& seqs : {std::vector<seq_spec>{{0, 100}}, std::vector<seq_spec>{{33, 1}}, std::vector<seq_spec>{{70, 40}}}) {- add("qwenpage32", wide_page, channel_quant(8, false, 32), token_quant(8, false), seqs);- add("qwenpage32", wide_page, channel_quant(4, true, 32), token_quant(4, true), seqs);+ for (const auto& seqs : {std::vector<seq_spec>{{0, 100}}, std::vector<seq_spec>{{33, 1}}}) {+ add("gqapage32", wide_page, channel_quant(8, false, 32), token_quant(8, false), seqs);+ add("gqapage32", wide_page, channel_quant(4, true, 32), token_quant(4, true), seqs);}// Head size 128: GQA-DPAS workers load 32-channel slices (16-byte 4-bit rows per message).- dims d128 = qwen38();+ dims d128 = gqa();d128.Dh = d128.Dv = 128;- for (const auto& seqs :- {std::vector<seq_spec>{{0, 37}}, std::vector<seq_spec>{{21, 1}}, std::vector<seq_spec>{{123, 45}}, std::vector<seq_spec>{{40, 1}, {0, 70}, {17, 3}}}) {+ for (const auto& seqs : {std::vector<seq_spec>{{21, 1}}, std::vector<seq_spec>{{40, 1}, {0, 70}, {17, 3}}}) {add("d128", d128, token_quant(8, false), token_quant(8, false), seqs);add("d128", d128, token_quant(4, true), token_quant(4, true), seqs);add("d128", d128, channel_quant(8, false, 16), token_quant(8, false), seqs);@@ -818,7 +821,7 @@ TEST(sparse_pa_kvq_mixed, f16_key_quantized_value) {if (!ocl_available()) {GTEST_SKIP() << "Intel subgroup extensions are not supported on this device";}- const auto c = make_case(qwen38(), KVQuant{}, token_quant(8, false), {{123, 45}}, 7);+ const auto c = make_case(gqa(), KVQuant{}, token_quant(8, false), {{123, 45}}, 7);const auto& d = c.d;quant_pages vhist(c.vq, c.total_pages, d.Hkv, d.page, d.Dv);cpu_write_range(vhist, c, 0, c.value_hist[0], d.Dv, 0, 123);@@ -1108,18 +1111,18 @@ void run_dense_case(const dense_case& tc, const char* name) {EXPECT_LT(e_q.mean_abs / ref_mean, tc.k.bits == 4 ? 0.5 : 0.03) << name;}-TEST(sparse_sdpa_kvq, qwen_decode_left_padded) {+TEST(sparse_sdpa_kvq, gqa_decode_left_padded) {if (!ocl_available()) {GTEST_SKIP() << "Intel subgroup extensions are not supported on this device";}- run_dense_case({qwen38(), {2051, 1500}, 1}, "qwen_decode_2x");+ run_dense_case({gqa(), {2051, 100}, 1}, "gqa_decode_2x");}-TEST(sparse_sdpa_kvq, qwen_prefill_left_padded) {+TEST(sparse_sdpa_kvq, gqa_prefill_left_padded) {if (!ocl_available()) {GTEST_SKIP() << "Intel subgroup extensions are not supported on this device";}- run_dense_case({qwen38(), {300, 211}, 150}, "qwen_prefill_2x");+ run_dense_case({gqa(), {300, 211}, 150}, "gqa_prefill_2x");}TEST(sparse_sdpa_kvq, toy_scalar_kernel) {@@ -1152,10 +1155,10 @@ std::vector<dense_format_case> dense_format_cases() {std::vector<size_t> key_len;size_t q_len;};- dims d128 = qwen38();+ dims d128 = gqa();d128.Dh = d128.Dv = 128;- const std::vector<scenario> scenarios = {{"qwen_decode", qwen38(), {2051, 1500}, 1},- {"qwen_prefill", qwen38(), {300, 211}, 150},+ const std::vector<scenario> scenarios = {{"gqa_decode", gqa(), {2051, 100}, 1},+ {"gqa_prefill", gqa(), {300, 211}, 150},{"d128_decode", d128, {500}, 1},{"toy_prefill", toy(), {90, 61}, 7},{"toy_decode", toy(), {120}, 1}};@@ -1195,12 +1198,12 @@ struct perf_case {class sparse_pa_kvq_perf : public ::testing::TestWithParam<perf_case> {};-TEST_P(sparse_pa_kvq_perf, qwen38) {+TEST_P(sparse_pa_kvq_perf, gqa) {if (!ocl_available()) {GTEST_SKIP() << "Intel subgroup extensions are not supported on this device";}const auto& pc = GetParam();- dims perf_dims = qwen38();+ dims perf_dims = gqa();perf_dims.page = pc.page;const auto c = make_case(perf_dims, pc.k, pc.v, {{pc.past, pc.q_len}}, 3);const auto& d = c.d;diff --git a/src/plugins/intel_gpu/tests/unit/transformations/gated_residual_fusion_test.cpp b/src/plugins/intel_gpu/tests/unit/transformations/gated_residual_fusion_test.cppnew file mode 100644index 00000000000..8f998e4de6f--- /dev/null+++ b/src/plugins/intel_gpu/tests/unit/transformations/gated_residual_fusion_test.cpp@@ -0,0 +1,1762 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "plugin/transformations/gated_residual_fusion.hpp"++#include <gtest/gtest.h>++#include <cmath>+#include <functional>+#include <memory>+#include <optional>++#include "common_test_utils/ov_test_utils.hpp"+#include "intel_gpu/op/gated_residual.hpp"+#include "intel_gpu/primitives/gated_residual_caps.hpp"+#include "openvino/core/except.hpp"+#include "openvino/core/model.hpp"+#include "openvino/core/rt_info/weightless_caching_attributes.hpp"+#include "openvino/op/add.hpp"+#include "openvino/op/concat.hpp"+#include "openvino/op/constant.hpp"+#include "openvino/op/convert.hpp"+#include "openvino/op/divide.hpp"+#include "openvino/op/gather.hpp"+#include "openvino/op/matmul.hpp"+#include "openvino/op/minimum.hpp"+#include "openvino/op/multiply.hpp"+#include "openvino/op/parameter.hpp"+#include "openvino/op/power.hpp"+#include "openvino/op/reduce_mean.hpp"+#include "openvino/op/reduce_sum.hpp"+#include "openvino/op/reshape.hpp"+#include "openvino/op/shape_of.hpp"+#include "openvino/op/sigmoid.hpp"+#include "openvino/op/sqrt.hpp"+#include "openvino/op/subtract.hpp"+#include "openvino/op/swish.hpp"+#include "openvino/op/unsqueeze.hpp"+#include "openvino/pass/manager.hpp"+#include "ov_ops/rms.hpp"+#include "plugin/transformations/convert_gated_residual_scale_layout.hpp"+#include "transformations/init_node_info.hpp"+#include "transformations/rt_info/fused_names_attribute.hpp"++using namespace testing;+using namespace ov::intel_gpu;+namespace caps = cldnn::gated_residual_caps;++namespace {++constexpr int64_t C = 4;+constexpr int64_t D = 64;+constexpr int64_t L = 16;+constexpr int64_t T = 8;+constexpr float EPS = 1e-6f;++std::shared_ptr<ov::op::v1::Reshape> reshape_to(const ov::Output<ov::Node>& src, const std::vector<int64_t>& shape) {+ auto target = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{shape.size()}, shape);+ return std::make_shared<ov::op::v1::Reshape>(src, target, false);+}++std::shared_ptr<ov::op::v1::Multiply> multiply(const ov::Output<ov::Node>& a, const ov::Output<ov::Node>& b, bool swap_operands) {+ return swap_operands ? std::make_shared<ov::op::v1::Multiply>(b, a) : std::make_shared<ov::op::v1::Multiply>(a, b);+}++/// Builds the canonical GR READ sub-graph and returns the final `mixed` node.+std::shared_ptr<ov::Node> build_gr_read(const std::shared_ptr<ov::op::v0::Parameter>& residual,+ float low_scale,+ float mix_scale,+ int64_t branches,+ const ov::element::Type& et = ov::element::f16,+ bool with_gain = true,+ bool swap_operands = false,+ bool scalar_first_low = false,+ bool scalar_first_mix = false) {+ auto r3 = reshape_to(residual, {-1, branches, D});+ // The gain is per (branch, channel): shape [C, D], i.e. C independent groups of width D.+ auto gamma = ov::op::v0::Constant::create(et, ov::Shape{static_cast<size_t>(branches), static_cast<size_t>(D)}, std::vector<float>(branches * D, 1.0f));+ std::shared_ptr<ov::Node> rms = with_gain ? std::make_shared<ov::op::internal::RMS>(r3, gamma, EPS) : std::make_shared<ov::op::internal::RMS>(r3, EPS);+ auto rbar = reshape_to(rms, {-1, branches * D});++ auto w_down = ov::op::v0::Constant::create(et, ov::Shape{L, static_cast<size_t>(branches * D)}, std::vector<float>(L * branches * D, 0.01f));+ auto low = std::make_shared<ov::op::v0::MatMul>(rbar, w_down, false, true);+ auto low_scaled = multiply(low, ov::op::v0::Constant::create(et, ov::Shape{}, {low_scale}), scalar_first_low);+ auto act = std::make_shared<ov::op::v4::Swish>(low_scaled);++ auto w_up = ov::op::v0::Constant::create(et, ov::Shape{static_cast<size_t>(branches * D), L}, std::vector<float>(branches * D * L, 0.01f));+ auto up = std::make_shared<ov::op::v0::MatMul>(act, w_up, false, true);+ auto gate = std::make_shared<ov::op::v0::Sigmoid>(up);+ auto weighted = multiply(gate, rbar, swap_operands);++ auto weighted3 = reshape_to(weighted, {-1, branches, D});+ auto reduced = std::make_shared<ov::op::v1::ReduceSum>(weighted3, ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, {1}), false);+ return multiply(reduced, ov::op::v0::Constant::create(et, ov::Shape{}, {mix_scale}), scalar_first_mix);+}++/// Builds the GR READ sub-graph in the *decomposed* form emitted by checkpoints that+/// were exported before RMS-fusion ran: Power -> ReduceMean -> Add(eps) -> Sqrt ->+/// Divide -> Multiply for the norm, an explicit `gain + 1` fold, and a ReduceMean+/// (rather than ReduceSum + Multiply) for the branch mix.+std::shared_ptr<ov::Node> build_gr_read_decomposed(const std::shared_ptr<ov::op::v0::Parameter>& residual,+ float low_scale,+ int64_t branches,+ bool with_gain = true,+ bool swap_operands = false,+ std::optional<float> inv_rms_exponent = std::nullopt,+ bool swap_eps = false) {+ auto r3 = reshape_to(residual, {-1, branches, D});+ auto sq = std::make_shared<ov::op::v1::Power>(r3, ov::op::v0::Constant::create(ov::element::f16, ov::Shape{}, {2.0f}));+ auto mean = std::make_shared<ov::op::v1::ReduceMean>(sq, ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, {-1}), true);+ auto eps = ov::op::v0::Constant::create(ov::element::f16, ov::Shape{}, {EPS});+ auto biased = swap_eps ? std::make_shared<ov::op::v1::Add>(eps, mean) : std::make_shared<ov::op::v1::Add>(mean, eps);+ auto rms = std::make_shared<ov::op::v0::Sqrt>(biased);+ // 1 / sqrt(.) as Divide(1, sqrt) or, once Divide is converted, Power(sqrt, e)+ std::shared_ptr<ov::Node> inv_rms =+ inv_rms_exponent ? std::static_pointer_cast<ov::Node>(+ std::make_shared<ov::op::v1::Power>(rms, ov::op::v0::Constant::create(ov::element::f16, ov::Shape{}, {*inv_rms_exponent})))+ : std::static_pointer_cast<ov::Node>(+ std::make_shared<ov::op::v1::Divide>(ov::op::v0::Constant::create(ov::element::f16, ov::Shape{}, {1.0f}), rms));+ auto normalized = multiply(r3, inv_rms, swap_operands);+ auto normalized_flat = reshape_to(normalized, {-1, branches * D});+ auto gain_raw = ov::op::v0::Constant::create(ov::element::f16, ov::Shape{static_cast<size_t>(branches * D)}, std::vector<float>(branches * D, 0.0f));+ auto gain_plus_one = std::make_shared<ov::op::v1::Add>(gain_raw, ov::op::v0::Constant::create(ov::element::f16, ov::Shape{}, {1.0f}));+ auto rbar = with_gain ? std::static_pointer_cast<ov::Node>(multiply(normalized_flat, gain_plus_one, swap_operands))+ : std::static_pointer_cast<ov::Node>(normalized_flat);++ auto w_down = ov::op::v0::Constant::create(ov::element::f16, ov::Shape{L, static_cast<size_t>(branches * D)}, std::vector<float>(L * branches * D, 0.01f));+ auto low = std::make_shared<ov::op::v0::MatMul>(rbar, w_down, false, true);+ auto low_scaled = std::make_shared<ov::op::v1::Multiply>(low, ov::op::v0::Constant::create(ov::element::f16, ov::Shape{}, {low_scale}));+ auto act = std::make_shared<ov::op::v4::Swish>(low_scaled);++ auto w_up = ov::op::v0::Constant::create(ov::element::f16, ov::Shape{static_cast<size_t>(branches * D), L}, std::vector<float>(branches * D * L, 0.01f));+ auto up = std::make_shared<ov::op::v0::MatMul>(act, w_up, false, true);+ auto gate = std::make_shared<ov::op::v0::Sigmoid>(up);++ auto gate_split = reshape_to(gate, {-1, branches, D});+ auto rbar_split = reshape_to(rbar, {-1, branches, D});+ auto weighted = multiply(gate_split, rbar_split, swap_operands);+ return std::make_shared<ov::op::v1::ReduceMean>(weighted, ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, {1}), false);+}++size_t count_gated_residual(const std::shared_ptr<ov::Model>& model) {+ size_t count = 0;+ for (const auto& node : model->get_ops()) {+ if (ov::as_type_ptr<op::GatedResidual>(node)) {+ count++;+ }+ }+ return count;+}++using split_fn = std::function<ov::Output<ov::Node>(const ov::Output<ov::Node>&, const std::vector<int64_t>&)>;++/// [B, L, X] -> [B, L, tail...] with a target built from ShapeOf, as dynamic exporters emit it.+ov::Output<ov::Node> shape_of_split(const ov::Output<ov::Node>& src, const std::vector<int64_t>& tail) {+ auto shape = std::make_shared<ov::op::v3::ShapeOf>(src, ov::element::i64);+ auto lead = std::make_shared<ov::op::v8::Gather>(shape,+ ov::op::v0::Constant::create(ov::element::i64, ov::Shape{2}, {0, 1}),+ ov::op::v0::Constant::create(ov::element::i64, ov::Shape{}, {0}));+ auto tail_c = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{tail.size()}, tail);+ auto target = std::make_shared<ov::op::v0::Concat>(ov::OutputVector{lead, tail_c}, 0);+ return std::make_shared<ov::op::v1::Reshape>(src, target, false);+}++/// [B, L, X] -> [B, L, tail...] via a special_zero Constant target.+ov::Output<ov::Node> zero_split(const ov::Output<ov::Node>& src, const std::vector<int64_t>& tail) {+ std::vector<int64_t> target = {0, 0};+ target.insert(target.end(), tail.begin(), tail.end());+ auto c = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{target.size()}, target);+ return std::make_shared<ov::op::v1::Reshape>(src, c, true);+}++/// GR READ over a rank-3 [B, L, C*D] residual; `split` produces the rank-4 branch views.+std::shared_ptr<ov::Node> build_gr_read_rank3(const std::shared_ptr<ov::op::v0::Parameter>& residual, const split_fn& split) {+ auto r4 = split(residual, {C, D});+ auto gamma = ov::op::v0::Constant::create(ov::element::f16, ov::Shape{C, D}, std::vector<float>(C * D, 1.0f));+ auto rms = std::make_shared<ov::op::internal::RMS>(r4, gamma, EPS);+ auto rbar = zero_split(rms, {C * D});++ auto w_down = ov::op::v0::Constant::create(ov::element::f16, ov::Shape{L, C * D}, std::vector<float>(L * C * D, 0.01f));+ auto low = std::make_shared<ov::op::v0::MatMul>(rbar, w_down, false, true);+ auto low_scaled = std::make_shared<ov::op::v1::Multiply>(low, ov::op::v0::Constant::create(ov::element::f16, ov::Shape{}, {1.0f / C}));+ auto act = std::make_shared<ov::op::v4::Swish>(low_scaled);+ auto w_up = ov::op::v0::Constant::create(ov::element::f16, ov::Shape{C * D, L}, std::vector<float>(C * D * L, 0.01f));+ auto up = std::make_shared<ov::op::v0::MatMul>(act, w_up, false, true);+ auto gate = std::make_shared<ov::op::v0::Sigmoid>(up);+ auto weighted = std::make_shared<ov::op::v1::Multiply>(gate, rbar);++ auto weighted4 = split(weighted, {C, D});+ auto reduced = std::make_shared<ov::op::v1::ReduceSum>(weighted4, ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, {-2}), false);+ return std::make_shared<ov::op::v1::Multiply>(reduced, ov::op::v0::Constant::create(ov::element::f16, ov::Shape{}, {1.0f / C}));+}++constexpr int64_t LQ = 32; // compressed weights need L % 32 == 0++/// NNCF-style decompression: u4 with `group` < K is Constant[N,G,group] -> Convert -> [Subtract(Convert(zp[N,G,1]))] ->+/// Multiply(scale[N,G,1]) -> Reshape[N,K]; per-channel (group == K) has no Reshape and [N,1] scale / zp. `with_zp` false is the+/// symmetric form without the Subtract; `scalar_zp` >= 0 makes the zero point a scalar of that value.+ov::Output<ov::Node>+make_decompressed(const ov::element::Type& wt, size_t N, size_t K, size_t group, bool scalar_scale = false, bool with_zp = true, int scalar_zp = -1) {+ const size_t G = K / group;+ const bool grouped = group != K;+ const ov::Shape wshape = grouped ? ov::Shape{N, G, group} : ov::Shape{N, K};+ const ov::Shape sshape = grouped ? ov::Shape{N, G, 1} : ov::Shape{N, 1};+ auto w = ov::op::v0::Constant::create(wt, wshape, std::vector<int>(ov::shape_size(wshape), 3));+ std::shared_ptr<ov::Node> dq = std::make_shared<ov::op::v0::Convert>(w, ov::element::f16);+ if (with_zp) {+ const ov::Shape zshape = scalar_zp >= 0 ? ov::Shape{} : sshape;+ auto zp = ov::op::v0::Constant::create(wt, zshape, std::vector<int>(ov::shape_size(zshape), scalar_zp >= 0 ? scalar_zp : 1));+ auto zpf = std::make_shared<ov::op::v0::Convert>(zp, ov::element::f16);+ dq = std::make_shared<ov::op::v1::Subtract>(dq, zpf);+ }+ const ov::Shape scshape = scalar_scale ? ov::Shape{} : sshape;+ auto sc = ov::op::v0::Constant::create(ov::element::f16, scshape, std::vector<float>(ov::shape_size(scshape), 0.01f));+ auto mul = std::make_shared<ov::op::v1::Multiply>(dq, sc);+ if (!grouped) {+ return mul;+ }+ return reshape_to(mul, {static_cast<int64_t>(N), static_cast<int64_t>(K)});+}++/// The canonical GR READ sub-graph with caller-provided W_down [LQ, C*D] / W_up [C*D, LQ] producers. `rbar_out` receives the+/// normalized residual so that tests can hang a write-gate branch off it.+std::shared_ptr<ov::Node> build_gr_read_with_weights(const std::shared_ptr<ov::op::v0::Parameter>& residual,+ const ov::Output<ov::Node>& w_down,+ const ov::Output<ov::Node>& w_up,+ ov::Output<ov::Node>* rbar_out = nullptr,+ bool fold_down_scale = false,+ float down_scale = 1.0f / C) {+ auto r3 = reshape_to(residual, {-1, C, D});+ auto gamma = ov::op::v0::Constant::create(ov::element::f16, ov::Shape{static_cast<size_t>(C), static_cast<size_t>(D)}, std::vector<float>(C * D, 1.0f));+ auto rms = std::make_shared<ov::op::internal::RMS>(r3, gamma, EPS);+ auto rbar = reshape_to(rms, {-1, C * D});+ if (rbar_out != nullptr) {+ *rbar_out = rbar->output(0);+ }+ // The down scale is either applied after the projection or already folded into W_down.+ auto down_scale_const = ov::op::v0::Constant::create(ov::element::f16, ov::Shape{}, {down_scale});+ std::shared_ptr<ov::Node> act;+ if (fold_down_scale) {+ auto scaled_w_down = std::make_shared<ov::op::v1::Multiply>(w_down, down_scale_const);+ act = std::make_shared<ov::op::v4::Swish>(std::make_shared<ov::op::v0::MatMul>(rbar, scaled_w_down, false, true));+ } else {+ auto low = std::make_shared<ov::op::v0::MatMul>(rbar, w_down, false, true);+ act = std::make_shared<ov::op::v4::Swish>(std::make_shared<ov::op::v1::Multiply>(low, down_scale_const));+ }+ auto up = std::make_shared<ov::op::v0::MatMul>(act, w_up, false, true);+ auto gate = std::make_shared<ov::op::v0::Sigmoid>(up);+ auto weighted = std::make_shared<ov::op::v1::Multiply>(gate, rbar);+ auto weighted3 = reshape_to(weighted, {-1, C, D});+ auto reduced = std::make_shared<ov::op::v1::ReduceSum>(weighted3, ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, {1}), false);+ return std::make_shared<ov::op::v1::Multiply>(reduced, ov::op::v0::Constant::create(ov::element::f16, ov::Shape{}, {1.0f / C}));+}++std::shared_ptr<op::GatedResidual> run_read_fusion(const ov::Output<ov::Node>& w_down, const ov::Output<ov::Node>& w_up, bool systolic) {+ auto residual = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::PartialShape{T, C * D});+ auto mixed = build_gr_read_with_weights(residual, w_down, w_up);+ auto model = std::make_shared<ov::Model>(ov::OutputVector{mixed}, ov::ParameterVector{residual});+ ov::pass::Manager manager;+ manager.register_pass<GatedResidualReadFusion>(systolic);+ manager.run_passes(model);+ std::shared_ptr<op::GatedResidual> found;+ for (const auto& node : model->get_ops()) {+ if (auto gr = ov::as_type_ptr<op::GatedResidual>(node)) {+ found = gr;+ }+ }+ return found;+}++void expect_compressed(const std::shared_ptr<op::GatedResidual>& gr, const ov::element::Type& wt, size_t groups_down, size_t groups_up, bool has_zp = true) {+ ASSERT_NE(gr, nullptr);+ ASSERT_EQ(gr->get_input_size(), has_zp ? 8u : 6u);+ EXPECT_EQ(gr->get_input_element_type(op::GatedResidual::ReadInputIdx::W_DOWN), wt);+ EXPECT_EQ(gr->get_input_element_type(op::GatedResidual::ReadInputIdx::W_UP), wt);+ EXPECT_EQ(gr->get_input_shape(op::GatedResidual::ReadInputIdx::W_DOWN), (ov::Shape{static_cast<size_t>(LQ), static_cast<size_t>(C * D)}));+ EXPECT_EQ(gr->get_input_shape(op::GatedResidual::ReadInputIdx::W_UP), (ov::Shape{static_cast<size_t>(C * D), static_cast<size_t>(LQ)}));+ EXPECT_EQ(gr->get_input_element_type(op::GatedResidual::ReadInputIdx::SCALE_DOWN), ov::element::f16);+ EXPECT_EQ(gr->get_input_shape(op::GatedResidual::ReadInputIdx::SCALE_DOWN), (ov::Shape{static_cast<size_t>(LQ), groups_down}));+ EXPECT_EQ(gr->get_input_shape(op::GatedResidual::ReadInputIdx::SCALE_UP), (ov::Shape{static_cast<size_t>(C * D), groups_up}));+ if (has_zp) {+ EXPECT_EQ(gr->get_input_element_type(op::GatedResidual::ReadInputIdx::ZP_DOWN), wt);+ EXPECT_EQ(gr->get_input_element_type(op::GatedResidual::ReadInputIdx::ZP_UP), wt);+ EXPECT_EQ(gr->get_input_shape(op::GatedResidual::ReadInputIdx::ZP_UP), (ov::Shape{static_cast<size_t>(C * D), groups_up}));+ }+}++} // namespace++TEST(gated_residual_fusion, gated_residual_read_is_fused) {+ auto residual = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::PartialShape{T, C * D});+ auto mixed = build_gr_read(residual, 1.0f / C, 1.0f / C, C);+ auto model = std::make_shared<ov::Model>(ov::OutputVector{mixed}, ov::ParameterVector{residual});++ ov::pass::Manager manager;+ manager.register_pass<GatedResidualReadFusion>();+ manager.run_passes(model);++ ASSERT_EQ(count_gated_residual(model), 1u);+ for (const auto& node : model->get_ops()) {+ auto gr = ov::as_type_ptr<op::GatedResidual>(node);+ if (!gr) {+ continue;+ }+ EXPECT_EQ(gr->get_mode(), op::GatedResidual::Mode::READ);+ EXPECT_EQ(gr->get_hc_count(), static_cast<size_t>(C));+ EXPECT_EQ(gr->get_hidden_size(), static_cast<size_t>(D));+ EXPECT_EQ(gr->get_lowrank(), static_cast<size_t>(L));+ EXPECT_FALSE(gr->get_produce_write_gate());+ EXPECT_EQ(gr->get_output_partial_shape(0), (ov::PartialShape{T, D}));+ }+}++TEST(gated_residual_fusion, gated_residual_read_requires_both_inv_c_scalings) {+ // The 1/C inside SiLU(W_down * Rbar / C) is model semantics, not a foldable constant.+ auto residual = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::PartialShape{T, C * D});+ auto mixed = build_gr_read(residual, 1.0f, 1.0f / C, C);+ auto model = std::make_shared<ov::Model>(ov::OutputVector{mixed}, ov::ParameterVector{residual});++ ov::pass::Manager manager;+ manager.register_pass<GatedResidualReadFusion>();+ manager.run_passes(model);++ ASSERT_EQ(count_gated_residual(model), 0u) << "the generic graph must be preserved when 1/C is missing";+}++TEST(gated_residual_fusion, scale_behind_minimum_is_not_a_constant) {+ // min(1/C, x) equals 1/C only for some runtime x: the generic graph must be kept.+ auto residual = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::PartialShape{T, C * D});+ auto limit = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::Shape{});+ auto mixed = build_gr_read(residual, 1.0f / C, 1.0f / C, C);+ mixed->input(1).replace_source_output(std::make_shared<ov::op::v1::Minimum>(mixed->input_value(1), limit));+ auto model = std::make_shared<ov::Model>(ov::OutputVector{mixed}, ov::ParameterVector{residual, limit});++ ov::pass::Manager manager;+ manager.register_pass<GatedResidualReadFusion>();+ manager.run_passes(model);++ ASSERT_EQ(count_gated_residual(model), 0u);+}++TEST(gated_residual_fusion, gated_residual_read_rejects_unsupported_branch_count) {+ constexpr int64_t branches = 2;+ auto residual = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::PartialShape{T, branches * D});+ auto mixed = build_gr_read(residual, 1.0f / branches, 1.0f / branches, branches);+ auto model = std::make_shared<ov::Model>(ov::OutputVector{mixed}, ov::ParameterVector{residual});++ ov::pass::Manager manager;+ manager.register_pass<GatedResidualReadFusion>();+ manager.run_passes(model);++ ASSERT_EQ(count_gated_residual(model), 0u) << "only C == 4 is supported by the first version";+}++TEST(gated_residual_fusion, gated_residual_read_decomposed_form_is_fused) {+ // Mirrors the graph shape actually emitted by the model export:+ // decomposed RMSNorm (no fused ov::op::internal::RMS) and a ReduceMean-based+ // branch mix (no trailing 1/C Multiply).+ auto residual = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::PartialShape{T, C * D});+ auto mixed = build_gr_read_decomposed(residual, 1.0f / C, C);+ auto model = std::make_shared<ov::Model>(ov::OutputVector{mixed}, ov::ParameterVector{residual});++ ov::pass::Manager manager;+ manager.register_pass<GatedResidualReadFusion>();+ manager.run_passes(model);++ ASSERT_EQ(count_gated_residual(model), 1u);+ for (const auto& node : model->get_ops()) {+ auto gr = ov::as_type_ptr<op::GatedResidual>(node);+ if (!gr) {+ continue;+ }+ EXPECT_EQ(gr->get_mode(), op::GatedResidual::Mode::READ);+ EXPECT_EQ(gr->get_hc_count(), static_cast<size_t>(C));+ EXPECT_EQ(gr->get_hidden_size(), static_cast<size_t>(D));+ EXPECT_EQ(gr->get_lowrank(), static_cast<size_t>(L));+ EXPECT_FALSE(gr->get_produce_write_gate());+ EXPECT_EQ(gr->get_output_partial_shape(0), (ov::PartialShape{T, D}));+ }+}++// The commutative Multiply / Add nodes of the patterns are matched in either operand order.+TEST(gated_residual_fusion, gated_residual_read_operand_order_is_irrelevant) {+ for (const bool decomposed : {false, true}) {+ auto residual = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::PartialShape{T, C * D});+ auto mixed = decomposed ? build_gr_read_decomposed(residual, 1.0f / C, C, true, true)+ : build_gr_read(residual, 1.0f / C, 1.0f / C, C, ov::element::f16, true, true);+ auto model = std::make_shared<ov::Model>(ov::OutputVector{mixed}, ov::ParameterVector{residual});++ ov::pass::Manager manager;+ manager.register_pass<GatedResidualReadFusion>();+ manager.run_passes(model);++ ASSERT_EQ(count_gated_residual(model), 1u) << (decomposed ? "decomposed" : "fused_rms");+ }+}++// The 1/C scalars are read by operand, not by position.+TEST(gated_residual_fusion, gated_residual_read_scalar_operand_position_is_irrelevant) {+ for (const auto& [down_first, mix_first] : {std::pair<bool, bool>{true, false}, std::pair<bool, bool>{false, true}}) {+ auto residual = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::PartialShape{T, C * D});+ auto mixed = build_gr_read(residual, 1.0f / C, 1.0f / C, C, ov::element::f16, true, false, down_first, mix_first);+ auto model = std::make_shared<ov::Model>(ov::OutputVector{mixed}, ov::ParameterVector{residual});++ ov::pass::Manager manager;+ manager.register_pass<GatedResidualReadFusion>();+ manager.run_passes(model);++ ASSERT_EQ(count_gated_residual(model), 1u) << (down_first ? "down scale" : "mix scale");+ }+}++class gated_residual_fusion_folded_gain : public ::testing::TestWithParam<bool> {};++// An exporter folds a gain of ones away, leaving the bare (fused or decomposed) normalization in front of the GEMM.+TEST_P(gated_residual_fusion_folded_gain, gated_residual_read_gets_a_unit_gain) {+ auto residual = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::PartialShape{T, C * D});+ auto mixed = GetParam() ? build_gr_read_decomposed(residual, 1.0f / C, C, false) : build_gr_read(residual, 1.0f / C, 1.0f / C, C, ov::element::f16, false);+ auto model = std::make_shared<ov::Model>(ov::OutputVector{mixed}, ov::ParameterVector{residual});++ ov::pass::Manager manager;+ manager.register_pass<GatedResidualReadFusion>();+ manager.run_passes(model);++ ASSERT_EQ(count_gated_residual(model), 1u);+ for (const auto& node : model->get_ops()) {+ auto gr = ov::as_type_ptr<op::GatedResidual>(node);+ if (!gr) {+ continue;+ }+ auto gain = ov::as_type_ptr<ov::op::v0::Constant>(gr->get_input_node_shared_ptr(op::GatedResidual::ReadInputIdx::NORM_WEIGHT));+ ASSERT_NE(gain, nullptr);+ EXPECT_EQ(gain->get_shape(), (ov::Shape{static_cast<size_t>(C * D)}));+ EXPECT_EQ(gain->cast_vector<float>(), std::vector<float>(C * D, 1.0f));+ }+}++INSTANTIATE_TEST_SUITE_P(smoke, gated_residual_fusion_folded_gain, ::testing::Values(false, true), [](const ::testing::TestParamInfo<bool>& info) {+ return info.param ? std::string("decomposed") : std::string("fused_rms");+});++TEST(gated_residual_fusion, gated_residual_write_is_fused) {+ auto residual = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::PartialShape{T, C * D});+ auto y = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::PartialShape{T, D});+ auto s = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::PartialShape{T, C});++ auto s3 = reshape_to(s, {-1, C, 1});+ auto y3 = reshape_to(y, {-1, 1, D});+ auto scaled = std::make_shared<ov::op::v1::Multiply>(s3, y3);+ auto r3 = reshape_to(residual, {-1, C, D});+ auto added = std::make_shared<ov::op::v1::Add>(r3, scaled);+ auto out = reshape_to(added, {-1, C * D});++ auto model = std::make_shared<ov::Model>(ov::OutputVector{out}, ov::ParameterVector{residual, y, s});++ ov::pass::Manager manager;+ manager.register_pass<GatedResidualWriteFusion>();+ manager.run_passes(model);++ ASSERT_EQ(count_gated_residual(model), 1u);+ for (const auto& node : model->get_ops()) {+ auto gr = ov::as_type_ptr<op::GatedResidual>(node);+ if (!gr) {+ continue;+ }+ EXPECT_EQ(gr->get_mode(), op::GatedResidual::Mode::WRITE);+ EXPECT_EQ(gr->get_hc_count(), static_cast<size_t>(C));+ EXPECT_EQ(gr->get_hidden_size(), static_cast<size_t>(D));+ EXPECT_EQ(gr->get_output_partial_shape(0), (ov::PartialShape{T, C * D}));+ }+}++TEST(gated_residual_fusion, gated_residual_write_rejects_wrong_broadcast_axis) {+ // Broadcasting the gate along the channel axis instead of the branch axis is a+ // different operator and must not be fused. The graph itself stays valid so that+ // the matcher - not shape inference - is what rejects it.+ auto residual = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::PartialShape{T, C * D});+ auto y = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::PartialShape{T, D});+ auto s = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::PartialShape{T, D});++ auto s3 = reshape_to(s, {-1, 1, D}); // channel-wise gate, not [T, C, 1]+ auto y3 = reshape_to(y, {-1, 1, D});+ auto scaled = std::make_shared<ov::op::v1::Multiply>(s3, y3);+ auto r3 = reshape_to(residual, {-1, C, D});+ auto added = std::make_shared<ov::op::v1::Add>(r3, scaled);+ auto out = reshape_to(added, {-1, C * D});++ auto model = std::make_shared<ov::Model>(ov::OutputVector{out}, ov::ParameterVector{residual, y, s});++ ov::pass::Manager manager;+ manager.register_pass<GatedResidualWriteFusion>();+ manager.run_passes(model);++ ASSERT_EQ(count_gated_residual(model), 0u);+}++TEST(gated_residual_fusion, gated_residual_write_rejects_mismatched_rows) {+ // Y broadcasts over the rows ([1, D] against [T, C*D]), which the row-wise kernel does not model.+ auto residual = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::PartialShape{T, C * D});+ auto y = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::PartialShape{1, D});+ auto s = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::PartialShape{T, C});++ auto s3 = reshape_to(s, {-1, C, 1});+ auto y3 = reshape_to(y, {-1, 1, D});+ auto scaled = std::make_shared<ov::op::v1::Multiply>(s3, y3);+ auto r3 = reshape_to(residual, {-1, C, D});+ auto added = std::make_shared<ov::op::v1::Add>(r3, scaled);+ auto out = reshape_to(added, {-1, C * D});++ auto model = std::make_shared<ov::Model>(ov::OutputVector{out}, ov::ParameterVector{residual, y, s});++ ov::pass::Manager manager;+ manager.register_pass<GatedResidualWriteFusion>();+ manager.run_passes(model);++ ASSERT_EQ(count_gated_residual(model), 0u);+}++TEST(gated_residual_fusion, gated_residual_write_op_rejects_mismatched_rows) {+ auto residual = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::PartialShape{T, C * D});+ auto y = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::PartialShape{T + 1, D});+ auto s = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::PartialShape{T, C});+ EXPECT_THROW(static_cast<void>(std::make_shared<op::GatedResidual>(ov::OutputVector{residual, y, s},+ op::GatedResidual::Mode::WRITE,+ static_cast<size_t>(C),+ static_cast<size_t>(D),+ 0,+ EPS,+ false)),+ ov::NodeValidationFailure);+}++TEST(gated_residual_fusion, gated_residual_write_rejects_static_one_against_dynamic_rows) {+ // [1, 1, D] against a dynamic [?, ?, C*D] residual is a broadcast the row-wise kernel would read out of bounds.+ auto residual = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::PartialShape{-1, -1, C * D});+ auto y = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::PartialShape{1, 1, D});+ auto s = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::PartialShape{-1, -1, C});++ auto s4 = std::make_shared<ov::op::v0::Unsqueeze>(s, ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, {3}));+ auto y4 = std::make_shared<ov::op::v0::Unsqueeze>(y, ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, {2}));+ auto scaled = std::make_shared<ov::op::v1::Multiply>(s4, y4);+ auto added = std::make_shared<ov::op::v1::Add>(zero_split(residual, {C, D}), scaled);+ auto out = zero_split(added, {C * D});++ auto model = std::make_shared<ov::Model>(ov::OutputVector{out}, ov::ParameterVector{residual, y, s});++ ov::pass::Manager manager;+ manager.register_pass<GatedResidualWriteFusion>();+ manager.run_passes(model);++ ASSERT_EQ(count_gated_residual(model), 0u);+}++TEST(gated_residual_fusion, gated_residual_write_op_leaves_dynamic_row_equality_to_the_runtime_check) {+ // Only the matcher refuses the possible broadcast: a later Validate after shape refinement must not fail on a dynamic residual.+ auto residual = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::PartialShape{-1, -1, C * D});+ auto y = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::PartialShape{1, 1, D});+ auto s = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::PartialShape{-1, -1, C});+ EXPECT_NO_THROW(static_cast<void>(std::make_shared<op::GatedResidual>(ov::OutputVector{residual, y, s},+ op::GatedResidual::Mode::WRITE,+ static_cast<size_t>(C),+ static_cast<size_t>(D),+ 0,+ EPS,+ false)));+}++TEST(gated_residual_fusion, gated_residual_write_decomposed_form_is_fused) {+ // Mirrors the real export: the gate/y are broadcast to 3D via Unsqueeze (not+ // Reshape), and the Add happens in the flat [*, C*D] domain against an+ // already-flat residual, with the split-form reshape appearing *after* the Add.+ auto residual = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::PartialShape{T, C * D});+ auto y = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::PartialShape{T, D});+ auto s = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::PartialShape{T, C});++ auto gate_3d = std::make_shared<ov::op::v0::Unsqueeze>(s, ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, {2}));+ auto y_3d = std::make_shared<ov::op::v0::Unsqueeze>(y, ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, {1}));+ auto scaled = std::make_shared<ov::op::v1::Multiply>(y_3d, gate_3d);+ auto scaled_flat = reshape_to(scaled, {-1, C * D});+ auto updated = std::make_shared<ov::op::v1::Add>(residual, scaled_flat);+ // A leftover reshape back to split form, left untouched by the fusion.+ auto out = reshape_to(updated, {-1, C, D});++ auto model = std::make_shared<ov::Model>(ov::OutputVector{out}, ov::ParameterVector{residual, y, s});++ ov::pass::Manager manager;+ manager.register_pass<GatedResidualWriteFusion>();+ manager.run_passes(model);++ ASSERT_EQ(count_gated_residual(model), 1u);+ for (const auto& node : model->get_ops()) {+ auto gr = ov::as_type_ptr<op::GatedResidual>(node);+ if (!gr) {+ continue;+ }+ EXPECT_EQ(gr->get_mode(), op::GatedResidual::Mode::WRITE);+ EXPECT_EQ(gr->get_hc_count(), static_cast<size_t>(C));+ EXPECT_EQ(gr->get_hidden_size(), static_cast<size_t>(D));+ EXPECT_EQ(gr->get_output_partial_shape(0), (ov::PartialShape{T, C * D}));+ }+}++TEST(gated_residual_fusion, gated_residual_write_operand_order_is_irrelevant) {+ for (const bool flat_add : {false, true}) {+ auto residual = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::PartialShape{T, C * D});+ auto y = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::PartialShape{T, D});+ auto s = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::PartialShape{T, C});++ auto scaled = std::make_shared<ov::op::v1::Multiply>(reshape_to(y, {-1, 1, D}), reshape_to(s, {-1, C, 1}));+ // Case A adds in the split domain, case B against an already-flat residual; the scaled term comes first in both.+ auto out = flat_add ? ov::Output<ov::Node>(std::make_shared<ov::op::v1::Add>(reshape_to(scaled, {-1, C * D}), residual))+ : ov::Output<ov::Node>(reshape_to(std::make_shared<ov::op::v1::Add>(scaled, reshape_to(residual, {-1, C, D})), {-1, C * D}));+ auto model = std::make_shared<ov::Model>(ov::OutputVector{out}, ov::ParameterVector{residual, y, s});++ ov::pass::Manager manager;+ manager.register_pass<GatedResidualWriteFusion>();+ manager.run_passes(model);++ ASSERT_EQ(count_gated_residual(model), 1u) << (flat_add ? "flat add" : "split add");+ }+}++class gated_residual_fusion_dynamic_split : public ::testing::TestWithParam<bool> {};++TEST_P(gated_residual_fusion_dynamic_split, gated_residual_read_rank3_dynamic_is_fused) {+ const split_fn split = GetParam() ? split_fn(shape_of_split) : split_fn(zero_split);+ auto residual = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::PartialShape{-1, -1, C * D});+ auto mixed = build_gr_read_rank3(residual, split);+ auto model = std::make_shared<ov::Model>(ov::OutputVector{mixed}, ov::ParameterVector{residual});++ ov::pass::Manager manager;+ manager.register_pass<GatedResidualReadFusion>();+ manager.run_passes(model);++ ASSERT_EQ(count_gated_residual(model), 1u);+ for (const auto& node : model->get_ops()) {+ if (auto gr = ov::as_type_ptr<op::GatedResidual>(node)) {+ EXPECT_EQ(gr->get_hc_count(), static_cast<size_t>(C));+ EXPECT_EQ(gr->get_hidden_size(), static_cast<size_t>(D));+ EXPECT_EQ(gr->get_output_partial_shape(0), (ov::PartialShape{-1, -1, D}));+ }+ }+}++TEST_P(gated_residual_fusion_dynamic_split, gated_residual_write_rank3_dynamic_is_fused) {+ const split_fn split = GetParam() ? split_fn(shape_of_split) : split_fn(zero_split);+ auto residual = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::PartialShape{-1, -1, C * D});+ auto y = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::PartialShape{-1, -1, D});+ auto s = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::PartialShape{-1, -1, C});++ auto s4 = std::make_shared<ov::op::v0::Unsqueeze>(s, ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, {3}));+ auto y4 = std::make_shared<ov::op::v0::Unsqueeze>(y, ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, {2}));+ auto scaled = std::make_shared<ov::op::v1::Multiply>(s4, y4);+ auto r4 = split(residual, {C, D});+ auto added = std::make_shared<ov::op::v1::Add>(r4, scaled);+ auto out = zero_split(added, {C * D});++ auto model = std::make_shared<ov::Model>(ov::OutputVector{out}, ov::ParameterVector{residual, y, s});++ ov::pass::Manager manager;+ manager.register_pass<GatedResidualWriteFusion>();+ manager.run_passes(model);++ ASSERT_EQ(count_gated_residual(model), 1u);+ for (const auto& node : model->get_ops()) {+ if (auto gr = ov::as_type_ptr<op::GatedResidual>(node)) {+ EXPECT_EQ(gr->get_mode(), op::GatedResidual::Mode::WRITE);+ EXPECT_EQ(gr->get_output_partial_shape(0), (ov::PartialShape{-1, -1, C * D}));+ }+ }+}++INSTANTIATE_TEST_SUITE_P(smoke, gated_residual_fusion_dynamic_split, ::testing::Values(false, true), [](const ::testing::TestParamInfo<bool>& info) {+ return info.param ? std::string("shape_of_target") : std::string("constant_target");+});++TEST(gated_residual_fusion, gated_residual_read_rejects_rank_changing_split) {+ // [B, L, C*D] -> [-1, C, D] flattens B and L; the fused op would keep them.+ auto residual = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::PartialShape{2, T, C * D});+ auto mixed = build_gr_read(residual, 1.0f / C, 1.0f / C, C);+ auto model = std::make_shared<ov::Model>(ov::OutputVector{mixed}, ov::ParameterVector{residual});++ ov::pass::Manager manager;+ manager.register_pass<GatedResidualReadFusion>();+ manager.run_passes(model);++ ASSERT_EQ(count_gated_residual(model), 0u);+}++TEST(gated_residual_fusion, gated_residual_read_rejects_f32) {+ // The kernels are f16-only; an f32 pattern must stay decomposed rather than be+ // fused into a node with no available GPU implementation.+ auto residual = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape{T, C * D});+ auto mixed = build_gr_read(residual, 1.0f / C, 1.0f / C, C, ov::element::f32);+ auto model = std::make_shared<ov::Model>(ov::OutputVector{mixed}, ov::ParameterVector{residual});++ ov::pass::Manager manager;+ manager.register_pass<GatedResidualReadFusion>();+ manager.run_passes(model);++ ASSERT_EQ(count_gated_residual(model), 0u);+}++TEST(gated_residual_fusion, gated_residual_write_rejects_f32) {+ auto residual = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape{T, C * D});+ auto y = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape{T, D});+ auto s = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape{T, C});++ auto s3 = reshape_to(s, {-1, C, 1});+ auto y3 = reshape_to(y, {-1, 1, D});+ auto scaled = std::make_shared<ov::op::v1::Multiply>(s3, y3);+ auto r3 = reshape_to(residual, {-1, C, D});+ auto added = std::make_shared<ov::op::v1::Add>(r3, scaled);+ auto out = reshape_to(added, {-1, C * D});++ auto model = std::make_shared<ov::Model>(ov::OutputVector{out}, ov::ParameterVector{residual, y, s});++ ov::pass::Manager manager;+ manager.register_pass<GatedResidualWriteFusion>();+ manager.run_passes(model);++ ASSERT_EQ(count_gated_residual(model), 0u);+}++// 4-bit weights use groups of 32 along K, 8-bit weights are per-channel.+TEST(gated_residual_fusion, compressed_weights_are_fused) {+ struct compressed_form {+ ov::element::Type type;+ size_t group_down;+ size_t group_up;+ };+ const size_t cd = C * D;+ const size_t lq = static_cast<size_t>(LQ);+ for (const auto& f : {compressed_form{ov::element::u4, 32, 32},+ compressed_form{ov::element::u8, cd, lq},+ compressed_form{ov::element::i4, 32, 32},+ compressed_form{ov::element::i8, cd, lq}}) {+ auto gr = run_read_fusion(make_decompressed(f.type, LQ, cd, f.group_down), make_decompressed(f.type, cd, LQ, f.group_up), true);+ expect_compressed(gr, f.type, cd / f.group_down, lq / f.group_up);+ }+}++TEST(gated_residual_fusion, compressed_weights_without_zero_points_are_fused_with_six_inputs) {+ const size_t cd = C * D;+ for (const auto& wt : {ov::element::u4, ov::element::i4}) {+ expect_compressed(run_read_fusion(make_decompressed(wt, LQ, cd, 32, false, false), make_decompressed(wt, cd, LQ, 32, false, false), true),+ wt,+ cd / 32,+ LQ / 32,+ false);+ }+ for (const auto& wt : {ov::element::u8, ov::element::i8}) {+ expect_compressed(run_read_fusion(make_decompressed(wt, LQ, cd, cd, false, false), make_decompressed(wt, cd, LQ, LQ, false, false), true),+ wt,+ 1,+ 1,+ false);+ }+}++TEST(gated_residual_fusion, compressed_weights_must_agree_on_type_and_zero_points) {+ const size_t cd = C * D;+ // W_down has zero points, W_up has none+ auto mixed_zp = run_read_fusion(make_decompressed(ov::element::u4, LQ, cd, 32), make_decompressed(ov::element::u4, cd, LQ, 32, false, false), true);+ ASSERT_NE(mixed_zp, nullptr);+ EXPECT_EQ(mixed_zp->get_input_size(), 4u);+ // signed and unsigned 4-bit weights are different element types+ auto mixed_sign = run_read_fusion(make_decompressed(ov::element::i4, LQ, cd, 32), make_decompressed(ov::element::u4, cd, LQ, 32), true);+ ASSERT_NE(mixed_sign, nullptr);+ EXPECT_EQ(mixed_sign->get_input_size(), 4u);+}++TEST(gated_residual_fusion, scalar_symmetric_zero_point_is_the_signed_form_without_zero_points) {+ const size_t cd = C * D;+ // unsigned weights with the scalar zero point 2^(bits - 1) (older NNCF symmetric) become i4 / i8 without zero points, q - zp unchanged+ auto u4 =+ run_read_fusion(make_decompressed(ov::element::u4, LQ, cd, 32, false, true, 8), make_decompressed(ov::element::u4, cd, LQ, 32, false, true, 8), true);+ expect_compressed(u4, ov::element::i4, cd / 32, LQ / 32, false);+ auto u4_w = ov::as_type_ptr<ov::op::v0::Constant>(u4->get_input_node_shared_ptr(op::GatedResidual::ReadInputIdx::W_DOWN));+ ASSERT_NE(u4_w, nullptr);+ for (const auto v : u4_w->cast_vector<int32_t>()) {+ ASSERT_EQ(v, 3 - 8);+ }+ auto u8 = run_read_fusion(make_decompressed(ov::element::u8, LQ, cd, cd, false, true, 128),+ make_decompressed(ov::element::u8, cd, LQ, LQ, false, true, 128),+ true);+ expect_compressed(u8, ov::element::i8, 1, 1, false);+ auto u8_w = ov::as_type_ptr<ov::op::v0::Constant>(u8->get_input_node_shared_ptr(op::GatedResidual::ReadInputIdx::W_UP));+ ASSERT_NE(u8_w, nullptr);+ for (const auto v : u8_w->cast_vector<int32_t>()) {+ ASSERT_EQ(v, 3 - 128);+ }+ // a scalar zero point of 0 is the symmetric form of any weight type and keeps it+ expect_compressed(+ run_read_fusion(make_decompressed(ov::element::u4, LQ, cd, 32, false, true, 0), make_decompressed(ov::element::u4, cd, LQ, 32, false, true, 0), true),+ ov::element::u4,+ cd / 32,+ LQ / 32,+ false);+ // any other scalar zero point is not supported+ auto other =+ run_read_fusion(make_decompressed(ov::element::u4, LQ, cd, 32, false, true, 5), make_decompressed(ov::element::u4, cd, LQ, 32, false, true, 5), true);+ ASSERT_NE(other, nullptr);+ EXPECT_EQ(other->get_input_size(), 4u);+ // a scalar 2^(bits - 1) on signed weights is a real zero point, not the symmetric form+ auto signed_zp =+ run_read_fusion(make_decompressed(ov::element::i4, LQ, cd, 32, false, true, 4), make_decompressed(ov::element::i4, cd, LQ, 32, false, true, 4), true);+ ASSERT_NE(signed_zp, nullptr);+ EXPECT_EQ(signed_zp->get_input_size(), 4u);+}++TEST(gated_residual_fusion, compressed_scale_keeps_the_operation_layout) {+ const size_t cd = C * D;+ const size_t g = cd / 32;+ // scale[n, g] = n * 10 + g+ std::vector<float> scale_ng(LQ * g);+ for (size_t n = 0; n < static_cast<size_t>(LQ); n++) {+ for (size_t i = 0; i < g; i++) {+ scale_ng[n * g + i] = static_cast<float>(n * 10 + i);+ }+ }+ auto w = ov::op::v0::Constant::create(ov::element::u4, ov::Shape{static_cast<size_t>(LQ), g, 32}, std::vector<int>(LQ * cd, 3));+ auto wf = std::make_shared<ov::op::v0::Convert>(w, ov::element::f16);+ auto zp = ov::op::v0::Constant::create(ov::element::u4, ov::Shape{static_cast<size_t>(LQ), g, 1}, std::vector<int>(LQ * g, 1));+ auto sub = std::make_shared<ov::op::v1::Subtract>(wf, std::make_shared<ov::op::v0::Convert>(zp, ov::element::f16));+ auto sc = ov::op::v0::Constant::create(ov::element::f16, ov::Shape{static_cast<size_t>(LQ), g, 1}, scale_ng);+ auto w_down = reshape_to(std::make_shared<ov::op::v1::Multiply>(sub, sc), {LQ, static_cast<int64_t>(cd)});+ auto gr = run_read_fusion(w_down, make_decompressed(ov::element::u4, cd, LQ, 32), true);+ expect_compressed(gr, ov::element::u4, g, LQ / 32);+ auto scale = ov::as_type_ptr<ov::op::v0::Constant>(gr->get_input_node_shared_ptr(op::GatedResidual::ReadInputIdx::SCALE_DOWN));+ ASSERT_NE(scale, nullptr);+ EXPECT_EQ(scale->get_shape(), (ov::Shape{static_cast<size_t>(LQ), g}));+ EXPECT_EQ(scale->cast_vector<float>(), scale_ng) << "the fusion passes the checkpoint's [N, G] scale through";+}++TEST(gated_residual_scale_layout, scales_and_zero_points_are_transposed_to_group_major) {+ const size_t cd = C * D;+ const size_t g = cd / 32;+ const auto n_down = static_cast<size_t>(LQ);+ auto residual = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::PartialShape{T, C * D});+ auto mixed = build_gr_read_with_weights(residual, make_decompressed(ov::element::u4, LQ, cd, 32), make_decompressed(ov::element::u4, cd, LQ, 32));+ auto model = std::make_shared<ov::Model>(ov::OutputVector{mixed}, ov::ParameterVector{residual});+ ov::pass::Manager manager;+ manager.register_pass<GatedResidualReadFusion>(true);+ manager.run_passes(model);+ std::shared_ptr<op::GatedResidual> before;+ for (const auto& node : model->get_ops()) {+ if (auto gr = ov::as_type_ptr<op::GatedResidual>(node)) {+ before = gr;+ }+ }+ ASSERT_NE(before, nullptr);+ ASSERT_FALSE(before->get_scale_gn());+ using Idx = op::GatedResidual::ReadInputIdx;+ const auto scale_ng = ov::as_type_ptr<ov::op::v0::Constant>(before->get_input_node_shared_ptr(Idx::SCALE_DOWN))->cast_vector<float>();+ const auto zp_ng = ov::as_type_ptr<ov::op::v0::Constant>(before->get_input_node_shared_ptr(Idx::ZP_DOWN))->cast_vector<int32_t>();+ const auto scale_up_ng = ov::as_type_ptr<ov::op::v0::Constant>(before->get_input_node_shared_ptr(Idx::SCALE_UP))->cast_vector<float>();++ ov::pass::Manager convert;+ convert.register_pass<ConvertGatedResidualScaleLayout>();+ convert.run_passes(model);+ std::shared_ptr<op::GatedResidual> gr;+ for (const auto& node : model->get_ops()) {+ if (auto found = ov::as_type_ptr<op::GatedResidual>(node)) {+ gr = found;+ }+ }+ ASSERT_NE(gr, nullptr);+ EXPECT_TRUE(gr->get_scale_gn());+ EXPECT_EQ(gr->get_input_shape(Idx::SCALE_DOWN), (ov::Shape{g, n_down}));+ EXPECT_EQ(gr->get_input_shape(Idx::ZP_DOWN), (ov::Shape{g, n_down}));+ EXPECT_EQ(gr->get_input_shape(Idx::SCALE_UP), (ov::Shape{1, cd}));+ EXPECT_EQ(gr->get_input_shape(Idx::ZP_UP), (ov::Shape{1, cd}));+ const auto scale = ov::as_type_ptr<ov::op::v0::Constant>(gr->get_input_node_shared_ptr(Idx::SCALE_DOWN))->cast_vector<float>();+ const auto zp = ov::as_type_ptr<ov::op::v0::Constant>(gr->get_input_node_shared_ptr(Idx::ZP_DOWN))->cast_vector<int32_t>();+ for (size_t i = 0; i < g; i++) {+ for (size_t n = 0; n < n_down; n++) {+ ASSERT_EQ(scale[i * n_down + n], scale_ng[n * g + i]);+ ASSERT_EQ(zp[i * n_down + n], zp_ng[n * g + i]);+ }+ }+ // G = 1: [N, 1] and [1, N] have the same element order+ EXPECT_EQ(ov::as_type_ptr<ov::op::v0::Constant>(gr->get_input_node_shared_ptr(Idx::SCALE_UP))->cast_vector<float>(), scale_up_ng);++ // a second run leaves the op alone+ ov::pass::Manager again;+ again.register_pass<ConvertGatedResidualScaleLayout>();+ EXPECT_FALSE(again.run_passes(model));+}++TEST(gated_residual_geometry, systolic_kernels_lift_the_scalar_limits) {+ using Mode = op::GatedResidual::Mode;+ // D = 5120 (C*D = 20480), L = 640+ EXPECT_TRUE(caps::is_geometry_supported(Mode::READ, 4, 5120, 640, true));+ EXPECT_FALSE(caps::is_geometry_supported(Mode::READ, 4, 5120, 640, false));+ EXPECT_FALSE(caps::is_geometry_supported(Mode::READ, 4, 2560, 640, false)) << "L is kept in registers by the scalar kernel";+ EXPECT_FALSE(caps::is_geometry_supported(Mode::READ, 4, 5120, 512, false)) << "C*D is kept in SLM by the scalar kernel";+ EXPECT_TRUE(caps::is_geometry_supported(Mode::READ, 4, 64, 16, true)) << "the scalar kernel is still there";+ EXPECT_FALSE(caps::is_geometry_supported(Mode::READ, 4, 64, 8, true));+ EXPECT_TRUE(caps::is_geometry_supported(Mode::WRITE, 4, 5120, 0, false)) << "no SLM in WRITE";+ EXPECT_FALSE(caps::is_geometry_supported(Mode::WRITE, 3, 64, 0, false));+}++TEST(gated_residual_fusion, compressed_weights_are_fused_without_systolic_arrays) {+ const size_t cd = C * D;+ // the scalar gr_read.cl dequantizes the compressed weights too+ expect_compressed(run_read_fusion(make_decompressed(ov::element::u4, LQ, cd, 32), make_decompressed(ov::element::u4, cd, LQ, 32), false),+ ov::element::u4,+ cd / 32,+ LQ / 32);+ expect_compressed(run_read_fusion(make_decompressed(ov::element::u8, LQ, cd, cd), make_decompressed(ov::element::u8, cd, LQ, LQ), false),+ ov::element::u8,+ 1,+ 1);+}++TEST(gated_residual_fusion, compressed_rejects_unsupported_quantization) {+ const size_t cd = C * D;+ // W_down and W_up must be compressed the same way+ auto mixed = run_read_fusion(make_decompressed(ov::element::u4, LQ, cd, 32), make_decompressed(ov::element::u8, cd, LQ, LQ), true);+ ASSERT_NE(mixed, nullptr);+ EXPECT_EQ(mixed->get_input_size(), 4u);+ // scalar scale is not a per-(group, channel) tensor+ auto scalar = run_read_fusion(make_decompressed(ov::element::u8, LQ, cd, cd, true), make_decompressed(ov::element::u8, cd, LQ, LQ), true);+ ASSERT_NE(scalar, nullptr);+ EXPECT_EQ(scalar->get_input_size(), 4u);+}++TEST(gated_residual_fusion, compressed_group_sizes_are_multiples_of_32) {+ const size_t cd = C * D;+ // W_down [LQ, cd] takes 32 / 64 / 128 / per-channel (K = 256); W_up [cd, LQ] has K = 32, i.e. one group of 32+ for (const auto& wt : {ov::element::u4, ov::element::i4, ov::element::u8, ov::element::i8}) {+ for (const size_t group : {size_t{32}, size_t{64}, size_t{128}, cd}) {+ auto gr = run_read_fusion(make_decompressed(wt, LQ, cd, group), make_decompressed(wt, cd, LQ, 32), true);+ expect_compressed(gr, wt, cd / group, 1);+ }+ }+}++TEST(gated_residual_fusion, compressed_group_size_is_derived_from_the_shapes) {+ const size_t cd = C * D;+ // group size 16 is not a multiple of 32+ auto g16 = run_read_fusion(make_decompressed(ov::element::u4, LQ, cd, 16), make_decompressed(ov::element::u4, cd, LQ, 16), true);+ ASSERT_NE(g16, nullptr);+ EXPECT_EQ(g16->get_input_size(), 4u);+ auto u8_g16 = run_read_fusion(make_decompressed(ov::element::u8, LQ, cd, 16), make_decompressed(ov::element::u8, cd, LQ, 16), true);+ ASSERT_NE(u8_g16, nullptr);+ EXPECT_EQ(u8_g16->get_input_size(), 4u);+}++namespace {++/// A compressed READ op whose scale / zp group counts are chosen by the caller (the group size is K / G); 8 inputs, 6 without+/// zero points.+std::shared_ptr<op::GatedResidual> make_compressed_op(const ov::element::Type& wt, size_t g_down, size_t g_up, bool has_zp = true) {+ const size_t cd = C * D;+ const auto lq = static_cast<size_t>(LQ);+ auto param = [](const ov::element::Type& et, const ov::Shape& shape) {+ return std::make_shared<ov::op::v0::Parameter>(et, shape);+ };+ ov::OutputVector inputs{param(ov::element::f16, {static_cast<size_t>(T), cd}),+ param(ov::element::f16, {cd}),+ param(wt, {lq, cd}),+ param(wt, {cd, lq}),+ param(ov::element::f16, {g_down, lq}),+ param(ov::element::f16, {g_up, cd})};+ if (has_zp) {+ inputs.push_back(param(wt, {g_down, lq}));+ inputs.push_back(param(wt, {g_up, cd}));+ }+ return std::make_shared<op::GatedResidual>(inputs,+ op::GatedResidual::Mode::READ,+ static_cast<size_t>(C),+ static_cast<size_t>(D),+ lq,+ EPS,+ false,+ /*scale_gn=*/true);+}++} // namespace++TEST(gated_residual_read_layout, input_forms) {+ using Op = op::GatedResidual;+ // without a write gate: 4 floating-point, 6 compressed, 8 compressed with zero points+ EXPECT_FALSE(Op::read_layout(4, false)->compressed);+ EXPECT_TRUE(Op::read_layout(6, false)->compressed);+ EXPECT_FALSE(Op::read_layout(6, false)->has_zp);+ EXPECT_TRUE(Op::read_layout(8, false)->has_zp);+ EXPECT_FALSE(Op::read_layout(5, false).has_value());+ EXPECT_FALSE(Op::read_layout(7, false).has_value());+ // with a write gate: 5 floating-point, 8 compressed, 11 compressed with zero points; W_inject is always last+ const auto f16 = Op::read_layout(5, true);+ ASSERT_TRUE(f16.has_value());+ EXPECT_FALSE(f16->compressed);+ EXPECT_EQ(f16->w_inject, 4u);+ const auto sym = Op::read_layout(8, true);+ ASSERT_TRUE(sym.has_value());+ EXPECT_TRUE(sym->compressed);+ EXPECT_FALSE(sym->has_zp);+ EXPECT_EQ(sym->w_inject, 6u);+ EXPECT_EQ(sym->scale_inject, 7u);+ const auto asym = Op::read_layout(11, true);+ ASSERT_TRUE(asym.has_value());+ EXPECT_TRUE(asym->has_zp);+ EXPECT_EQ(asym->w_inject, 8u);+ EXPECT_EQ(asym->scale_inject, 9u);+ EXPECT_EQ(asym->zp_inject, 10u);+ EXPECT_FALSE(Op::read_layout(6, true).has_value());+ EXPECT_FALSE(Op::read_layout(4, true).has_value());+}++TEST(gated_residual_group_size, op_validates_the_zero_point_type) {+ const size_t cd = C * D;+ const size_t lq = static_cast<size_t>(LQ);+ auto param = [](const ov::element::Type& et, const ov::Shape& shape) {+ return std::make_shared<ov::op::v0::Parameter>(et, shape);+ };+ ov::OutputVector inputs{param(ov::element::f16, {static_cast<size_t>(T), cd}),+ param(ov::element::f16, {cd}),+ param(ov::element::i4, {lq, cd}),+ param(ov::element::i4, {cd, lq}),+ param(ov::element::f16, {cd / 32, lq}),+ param(ov::element::f16, {lq / 32, cd}),+ param(ov::element::u4, {cd / 32, lq}),+ param(ov::element::u4, {lq / 32, cd})};+ EXPECT_THROW(static_cast<void>(std::make_shared<op::GatedResidual>(inputs, op::GatedResidual::Mode::READ, C, D, LQ, EPS, false, true)),+ ov::NodeValidationFailure)+ << "the zero point must have the weight element type";+}++TEST(gated_residual_group_size, derive_group_size) {+ EXPECT_EQ(caps::derive_group_size(256, 8), 32u);+ EXPECT_EQ(caps::derive_group_size(256, 1), 256u);+ EXPECT_EQ(caps::derive_group_size(256, 0), 0u) << "no scale groups";+ EXPECT_EQ(caps::derive_group_size(256, 7), 0u) << "K is not divisible by G";+}++TEST(gated_residual_group_size, supported_group_sizes) {+ EXPECT_TRUE(caps::is_group_size_supported(256, 32));+ EXPECT_TRUE(caps::is_group_size_supported(256, 64));+ EXPECT_TRUE(caps::is_group_size_supported(256, 128));+ EXPECT_TRUE(caps::is_group_size_supported(256, 256)) << "per-channel";+ EXPECT_TRUE(caps::is_group_size_supported(320, 160)) << "a multiple of 32 that divides K";+ EXPECT_FALSE(caps::is_group_size_supported(256, 16));+ EXPECT_FALSE(caps::is_group_size_supported(256, 48)) << "not a multiple of 32";+ EXPECT_FALSE(caps::is_group_size_supported(256, 96)) << "does not divide K";+ EXPECT_FALSE(caps::is_group_size_supported(320, 128)) << "does not divide K";+ EXPECT_FALSE(caps::is_group_size_supported(256, 512)) << "larger than K";+ EXPECT_FALSE(caps::is_group_size_supported(256, 0));+}++TEST(gated_residual_group_size, matrix_compression_support_uses_k_over_g) {+ // W_down [32, 256], W_up [256, 32]+ for (const size_t bits : {size_t{4}, size_t{8}}) {+ for (const size_t g_down : {size_t{8}, size_t{4}, size_t{2}, size_t{1}}) {+ EXPECT_TRUE(caps::is_matrix_compression_supported(bits, 32, 256, g_down)) << bits << " bits, " << g_down << " groups";+ }+ EXPECT_TRUE(caps::is_matrix_compression_supported(bits, 256, 32, 1));+ EXPECT_FALSE(caps::is_matrix_compression_supported(bits, 32, 256, 16)) << "W_down group size 16";+ EXPECT_FALSE(caps::is_matrix_compression_supported(bits, 256, 32, 2)) << "W_up group size 16";+ EXPECT_FALSE(caps::is_matrix_compression_supported(bits, 32, 256, 7)) << "K not divisible by G";+ EXPECT_FALSE(caps::is_matrix_compression_supported(bits, 32, 256, 0));+ EXPECT_FALSE(caps::is_matrix_compression_supported(bits, 4, 256, 1)) << "N % 16";+ }+}++TEST(gated_residual_group_size, row_compression_support_has_no_row_count_rule) {+ // W_inject [C = 4, K = 256]: N is not a multiple of 16, the group rules are those of W_down / W_up+ for (const size_t bits : {size_t{4}, size_t{8}}) {+ for (const size_t g : {size_t{8}, size_t{4}, size_t{2}, size_t{1}}) {+ EXPECT_TRUE(caps::is_row_compression_supported(bits, 256, g)) << bits << " bits, " << g << " groups";+ }+ EXPECT_FALSE(caps::is_row_compression_supported(bits, 256, 16)) << "group size 16";+ EXPECT_FALSE(caps::is_row_compression_supported(bits, 256, 7)) << "K not divisible by G";+ EXPECT_FALSE(caps::is_row_compression_supported(bits, 48, 1)) << "K % 32";+ }+ EXPECT_FALSE(caps::is_row_compression_supported(2, 256, 8)) << "bits";+}++TEST(gated_residual_group_size, op_accepts_supported_group_sizes) {+ const size_t cd = C * D;+ const size_t lq = static_cast<size_t>(LQ);+ for (const bool has_zp : {true, false}) {+ for (const auto& wt : {ov::element::u4, ov::element::i4, ov::element::u8, ov::element::i8}) {+ for (const size_t group : {size_t{32}, size_t{64}, size_t{128}, cd}) {+ // W_up keeps its K32 groups for the smallest W_down group size, per-channel otherwise+ const size_t g_up = group == 32 ? lq / 32 : 1;+ std::shared_ptr<op::GatedResidual> gr;+ ASSERT_NO_THROW(gr = make_compressed_op(wt, cd / group, g_up, has_zp)) << wt << " group " << group;+ EXPECT_EQ(gr->get_input_size(), has_zp ? 8u : 6u);+ }+ }+ }+}++TEST(gated_residual_group_size, op_rejects_only_indivisible_group_counts) {+ const size_t cd = C * D;+ const size_t lq = static_cast<size_t>(LQ);+ for (const auto& wt : {ov::element::u4, ov::element::u8}) {+ EXPECT_THROW(make_compressed_op(wt, 7, 1), ov::NodeValidationFailure) << "K not divisible by G";+ EXPECT_THROW(make_compressed_op(wt, cd / 32, 3), ov::NodeValidationFailure) << "K not divisible by G";+ // what the kernels support is the impl's and the fusion's business, not the op's+ EXPECT_NO_THROW(make_compressed_op(wt, cd / 16, 1)) << "W_down group size 16";+ EXPECT_NO_THROW(make_compressed_op(wt, cd / 32, lq / 16)) << "W_up group size 16";+ }+}++namespace {++/// A compressed READ op with a compressed W_inject (11 inputs, 8 without zero points); g_inject is the group count of W_inject's+/// scale / zp.+std::shared_ptr<op::GatedResidual> make_compressed_gate_op(const ov::element::Type& wt,+ size_t g_down,+ size_t g_up,+ size_t g_inject,+ const ov::element::Type& inject_wt,+ const ov::Shape& scale_inject_tail,+ bool has_zp = true) {+ const size_t cd = C * D;+ const auto lq = static_cast<size_t>(LQ);+ const auto c = static_cast<size_t>(C);+ auto param = [](const ov::element::Type& et, const ov::Shape& shape) {+ return std::make_shared<ov::op::v0::Parameter>(et, shape);+ };+ ov::Shape scale_inject{g_inject};+ scale_inject.insert(scale_inject.end(), scale_inject_tail.begin(), scale_inject_tail.end());+ ov::OutputVector inputs{param(ov::element::f16, {static_cast<size_t>(T), cd}),+ param(ov::element::f16, {cd}),+ param(wt, {lq, cd}),+ param(wt, {cd, lq}),+ param(ov::element::f16, {g_down, lq}),+ param(ov::element::f16, {g_up, cd})};+ if (has_zp) {+ inputs.push_back(param(wt, {g_down, lq}));+ inputs.push_back(param(wt, {g_up, cd}));+ }+ inputs.push_back(param(inject_wt, {c, cd}));+ inputs.push_back(param(ov::element::f16, scale_inject));+ if (has_zp) {+ inputs.push_back(param(inject_wt, scale_inject));+ }+ return std::make_shared<op::GatedResidual>(inputs, op::GatedResidual::Mode::READ, c, static_cast<size_t>(D), lq, EPS, true, /*scale_gn=*/true);+}++} // namespace++TEST(gated_residual_write_gate_op, compressed_write_gate_has_eleven_inputs) {+ const size_t cd = C * D;+ const size_t lq = static_cast<size_t>(LQ);+ const auto c = static_cast<size_t>(C);+ std::shared_ptr<op::GatedResidual> u4;+ ASSERT_NO_THROW(u4 = make_compressed_gate_op(ov::element::u4, cd / 32, lq / 32, cd / 32, ov::element::u4, {c}));+ EXPECT_EQ(u4->get_input_size(), 11u);+ ASSERT_EQ(u4->get_output_size(), 2u);+ EXPECT_EQ(u4->get_output_partial_shape(0), (ov::PartialShape{T, D}));+ EXPECT_EQ(u4->get_output_partial_shape(1), (ov::PartialShape{T, C}));+ EXPECT_EQ(u4->get_output_element_type(0), ov::element::f16);+ EXPECT_EQ(u4->get_output_element_type(1), ov::element::f16);+ EXPECT_NO_THROW(make_compressed_gate_op(ov::element::u8, 1, 1, 1, ov::element::u8, {c}));+ // signed weights, and no zero points at all (8 inputs: W_inject, scale_inject right after the scales)+ EXPECT_NO_THROW(make_compressed_gate_op(ov::element::i4, cd / 32, lq / 32, cd / 32, ov::element::i4, {c}));+ EXPECT_NO_THROW(make_compressed_gate_op(ov::element::i8, 1, 1, 1, ov::element::i8, {c}));+ auto sym = make_compressed_gate_op(ov::element::u4, cd / 32, lq / 32, cd / 32, ov::element::u4, {c}, false);+ EXPECT_EQ(sym->get_input_size(), 8u);+ ASSERT_EQ(sym->get_output_size(), 2u);+ EXPECT_EQ(sym->get_output_partial_shape(1), (ov::PartialShape{T, C}));+}++TEST(gated_residual_write_gate_op, compressed_write_gate_rejects_inconsistent_inputs) {+ const size_t cd = C * D;+ const size_t lq = static_cast<size_t>(LQ);+ const auto c = static_cast<size_t>(C);+ EXPECT_THROW(make_compressed_gate_op(ov::element::u4, cd / 32, lq / 32, cd / 32, ov::element::u8, {c}), ov::NodeValidationFailure)+ << "W_inject must have the element type of W_down / W_up";+ EXPECT_THROW(make_compressed_gate_op(ov::element::u4, cd / 32, lq / 32, cd / 32, ov::element::u4, {c + 1}), ov::NodeValidationFailure)+ << "scale_inject must have C columns";+ EXPECT_THROW(make_compressed_gate_op(ov::element::u4, cd / 32, lq / 32, 7, ov::element::u4, {c}), ov::NodeValidationFailure)+ << "W_inject K not divisible by G";+}++TEST(gated_residual_write_gate_op, f16_write_gate_keeps_five_inputs) {+ const size_t cd = C * D;+ auto param = [](const ov::element::Type& et, const ov::Shape& shape) {+ return std::make_shared<ov::op::v0::Parameter>(et, shape);+ };+ ov::OutputVector inputs{param(ov::element::f16, {static_cast<size_t>(T), cd}),+ param(ov::element::f16, {cd}),+ param(ov::element::f16, {static_cast<size_t>(LQ), cd}),+ param(ov::element::f16, {cd, static_cast<size_t>(LQ)}),+ param(ov::element::f16, {static_cast<size_t>(C), cd})};+ auto gr = std::make_shared<op::GatedResidual>(inputs, op::GatedResidual::Mode::READ, C, D, LQ, EPS, true);+ EXPECT_EQ(gr->get_output_size(), 2u);+ EXPECT_EQ(gr->get_output_partial_shape(0), (ov::PartialShape{T, D}));+ // a compressed-weight W_inject needs the full 11-input form+ inputs.back() = param(ov::element::u4, {static_cast<size_t>(C), cd});+ EXPECT_THROW(static_cast<void>(std::make_shared<op::GatedResidual>(inputs, op::GatedResidual::Mode::READ, C, D, LQ, EPS, true)), ov::NodeValidationFailure);+}++namespace {++enum class GateScale { multiply, divide, folded };++/// S = 2 * sigmoid(MatMul(Rbar, W_inject, transpose_b) / C) with the 1/C written as a Multiply, a Divide or folded into W_inject.+/// `scale` is the constant as written (1/C for multiply / folded, C for divide).+ov::Output<ov::Node> build_write_gate(const ov::Output<ov::Node>& rbar,+ const ov::Output<ov::Node>& w_inject,+ GateScale form = GateScale::multiply,+ float scale = 1.0f / C,+ float times = 2.0f) {+ auto f16_const = [](float v) {+ return ov::op::v0::Constant::create(ov::element::f16, ov::Shape{}, {v});+ };+ std::shared_ptr<ov::Node> x;+ switch (form) {+ case GateScale::multiply:+ x = std::make_shared<ov::op::v1::Multiply>(std::make_shared<ov::op::v0::MatMul>(rbar, w_inject, false, true), f16_const(scale));+ break;+ case GateScale::divide:+ x = std::make_shared<ov::op::v1::Divide>(std::make_shared<ov::op::v0::MatMul>(rbar, w_inject, false, true), f16_const(scale));+ break;+ case GateScale::folded:+ x = std::make_shared<ov::op::v0::MatMul>(rbar, std::make_shared<ov::op::v1::Multiply>(w_inject, f16_const(scale)), false, true);+ break;+ }+ return std::make_shared<ov::op::v1::Multiply>(std::make_shared<ov::op::v0::Sigmoid>(x), f16_const(times))->output(0);+}++ov::Output<ov::Node> f16_inject_weights() {+ return ov::op::v0::Constant::create(ov::element::f16, ov::Shape{static_cast<size_t>(C), static_cast<size_t>(C * D)}, std::vector<float>(C * C * D, 0.02f));+}++using gate_fn = std::function<ov::Output<ov::Node>(const ov::Output<ov::Node>& residual, const ov::Output<ov::Node>& rbar)>;++struct GateFusion {+ std::shared_ptr<ov::Model> model;+ std::shared_ptr<op::GatedResidual> gr;+};++/// READ sub-graph plus the write-gate branch built by `make_gate`; the model outputs are {mixed, S, extra...}.+GateFusion run_gate_fusion(const ov::Output<ov::Node>& w_down,+ const ov::Output<ov::Node>& w_up,+ const gate_fn& make_gate,+ bool allow_compressed,+ const std::function<ov::OutputVector(const ov::Output<ov::Node>& rbar)>& extra_outputs = nullptr) {+ auto residual = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::PartialShape{T, C * D});+ ov::Output<ov::Node> rbar;+ auto mixed = build_gr_read_with_weights(residual, w_down, w_up, &rbar);+ ov::OutputVector outputs{mixed, make_gate(residual, rbar)};+ if (extra_outputs) {+ const auto extra = extra_outputs(rbar);+ outputs.insert(outputs.end(), extra.begin(), extra.end());+ }+ GateFusion result;+ result.model = std::make_shared<ov::Model>(outputs, ov::ParameterVector{residual});+ ov::pass::Manager manager;+ manager.register_pass<GatedResidualReadFusion>(allow_compressed);+ manager.run_passes(result.model);+ for (const auto& node : result.model->get_ops()) {+ if (auto gr = ov::as_type_ptr<op::GatedResidual>(node)) {+ result.gr = gr;+ }+ }+ return result;+}++void expect_gate_fused(const GateFusion& r, size_t inputs) {+ ASSERT_NE(r.gr, nullptr);+ EXPECT_EQ(r.gr->get_input_size(), inputs);+ EXPECT_TRUE(r.gr->get_produce_write_gate());+ ASSERT_EQ(r.gr->get_output_size(), 2u);+ EXPECT_EQ(r.gr->get_output_partial_shape(1), (ov::PartialShape{T, C}));+ // both model outputs come from the fused op, and no MatMul / Sigmoid of the write-gate branch is left+ const auto mixed_src = r.model->get_results()[0]->input_value(0);+ const auto gate_src = r.model->get_results()[1]->input_value(0);+ EXPECT_EQ(mixed_src.get_node(), r.gr.get());+ EXPECT_EQ(mixed_src.get_index(), 0u);+ EXPECT_EQ(gate_src.get_node(), r.gr.get());+ EXPECT_EQ(gate_src.get_index(), 1u);+ for (const auto& node : r.model->get_ops()) {+ EXPECT_EQ(ov::as_type_ptr<ov::op::v0::MatMul>(node), nullptr);+ EXPECT_EQ(ov::as_type_ptr<ov::op::v0::Sigmoid>(node), nullptr);+ }+}++void expect_gate_not_fused(const GateFusion& r, size_t inputs) {+ ASSERT_NE(r.gr, nullptr) << "the READ itself must still be fused";+ EXPECT_EQ(r.gr->get_input_size(), inputs);+ EXPECT_FALSE(r.gr->get_produce_write_gate());+ EXPECT_EQ(r.gr->get_output_size(), 1u);+ EXPECT_NE(r.model->get_results()[1]->input_value(0).get_node(), r.gr.get());+}++gate_fn gate_on_rbar(GateScale form = GateScale::multiply, float scale = 1.0f / C, float times = 2.0f) {+ return [=](const ov::Output<ov::Node>&, const ov::Output<ov::Node>& rbar) {+ return build_write_gate(rbar, f16_inject_weights(), form, scale, times);+ };+}++std::pair<ov::Output<ov::Node>, ov::Output<ov::Node>> f16_read_weights() {+ return {+ ov::op::v0::Constant::create(ov::element::f16, ov::Shape{static_cast<size_t>(LQ), static_cast<size_t>(C * D)}, std::vector<float>(LQ * C * D, 0.01f)),+ ov::op::v0::Constant::create(ov::element::f16, ov::Shape{static_cast<size_t>(C * D), static_cast<size_t>(LQ)}, std::vector<float>(LQ * C * D, 0.01f))};+}++} // namespace++TEST(gated_residual_fusion_write_gate, multiply_and_divide_scales_are_fused) {+ const auto [w_down, w_up] = f16_read_weights();+ expect_gate_fused(run_gate_fusion(w_down, w_up, gate_on_rbar(), false), 5u);+ expect_gate_fused(run_gate_fusion(w_down, w_up, gate_on_rbar(GateScale::divide, static_cast<float>(C)), false), 5u);+}++TEST(gated_residual_fusion_write_gate, scale_folded_into_w_inject_is_fused) {+ const auto [w_down, w_up] = f16_read_weights();+ auto r = run_gate_fusion(w_down, w_up, gate_on_rbar(GateScale::folded), false);+ expect_gate_fused(r, 5u);+ // the fused op reads the unscaled W_inject: the 1/C is applied inside the kernel+ auto w_inject = ov::as_type_ptr<ov::op::v0::Constant>(r.gr->get_input_node_shared_ptr(r.gr->get_read_layout()->w_inject));+ EXPECT_NE(w_inject, nullptr);+}++TEST(gated_residual_fusion_write_gate, write_gate_feeds_the_write_fusion) {+ const auto [w_down, w_up] = f16_read_weights();+ auto residual = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::PartialShape{T, C * D});+ ov::Output<ov::Node> rbar;+ auto mixed = build_gr_read_with_weights(residual, w_down, w_up, &rbar);+ auto gate = build_write_gate(rbar, f16_inject_weights());+ // R' = R + S * Y, canonical case A+ auto y = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::PartialShape{T, D});+ auto r3 = reshape_to(residual, {-1, C, D});+ auto s3 = reshape_to(gate, {-1, C, 1});+ auto y3 = reshape_to(y, {-1, 1, D});+ auto updated = reshape_to(std::make_shared<ov::op::v1::Add>(r3, std::make_shared<ov::op::v1::Multiply>(s3, y3)), {-1, C * D});+ auto model = std::make_shared<ov::Model>(ov::OutputVector{mixed, updated}, ov::ParameterVector{residual, y});+ ov::pass::Manager manager;+ manager.register_pass<GatedResidualFusion>(false);+ manager.run_passes(model);++ std::shared_ptr<op::GatedResidual> read;+ std::shared_ptr<op::GatedResidual> write;+ for (const auto& node : model->get_ops()) {+ if (auto gr = ov::as_type_ptr<op::GatedResidual>(node)) {+ (gr->get_mode() == op::GatedResidual::Mode::READ ? read : write) = gr;+ }+ }+ ASSERT_NE(read, nullptr);+ ASSERT_NE(write, nullptr);+ EXPECT_TRUE(read->get_produce_write_gate());+ EXPECT_EQ(write->input_value(op::GatedResidual::WriteInputIdx::WRITE_GATE).get_node(), read.get());+}++TEST(gated_residual_fusion_write_gate, wrong_branch_scale_leaves_the_gate_in_the_graph) {+ const auto [w_down, w_up] = f16_read_weights();+ expect_gate_not_fused(run_gate_fusion(w_down, w_up, gate_on_rbar(GateScale::multiply, 1.0f / (C + 1)), false), 4u);+ expect_gate_not_fused(run_gate_fusion(w_down, w_up, gate_on_rbar(GateScale::divide, static_cast<float>(C + 1)), false), 4u);+}++TEST(gated_residual_fusion_write_gate, wrong_gate_range_leaves_the_gate_in_the_graph) {+ const auto [w_down, w_up] = f16_read_weights();+ // a plain sigmoid or 2 * sigmoid scaled differently is not the write gate+ expect_gate_not_fused(run_gate_fusion(w_down, w_up, gate_on_rbar(GateScale::multiply, 1.0f / C, 1.0f), false), 4u);+ expect_gate_not_fused(run_gate_fusion(w_down, w_up, gate_on_rbar(GateScale::multiply, 1.0f / C, 3.0f), false), 4u);+}++TEST(gated_residual_fusion_write_gate, branch_on_another_normalization_is_not_fused) {+ const auto [w_down, w_up] = f16_read_weights();+ // the inject MatMul reads its own RMS of the residual, not the Rbar of the READ+ gate_fn other_rbar = [](const ov::Output<ov::Node>& residual, const ov::Output<ov::Node>&) {+ auto r3 = reshape_to(residual, {-1, C, D});+ auto rms = std::make_shared<ov::op::internal::RMS>(r3, EPS);+ return build_write_gate(reshape_to(rms, {-1, C * D}), f16_inject_weights());+ };+ expect_gate_not_fused(run_gate_fusion(w_down, w_up, other_rbar, false), 4u);+}++TEST(gated_residual_fusion_write_gate, transposed_or_misshaped_w_inject_is_not_fused) {+ const auto [w_down, w_up] = f16_read_weights();+ gate_fn misshaped = [](const ov::Output<ov::Node>&, const ov::Output<ov::Node>& rbar) {+ auto w = ov::op::v0::Constant::create(ov::element::f16,+ ov::Shape{static_cast<size_t>(C + 4), static_cast<size_t>(C * D)},+ std::vector<float>((C + 4) * C * D, 0.02f));+ return build_write_gate(rbar, w);+ };+ auto r = run_gate_fusion(w_down, w_up, misshaped, false);+ ASSERT_NE(r.gr, nullptr);+ EXPECT_FALSE(r.gr->get_produce_write_gate());+}++TEST(gated_residual_fusion_write_gate, gate_chain_with_other_consumers_is_not_fused) {+ const auto [w_down, w_up] = f16_read_weights();+ // the raw inject MatMul is also a model output, so it cannot be removed+ ov::Output<ov::Node> inject_mm;+ gate_fn make_gate = [&](const ov::Output<ov::Node>&, const ov::Output<ov::Node>& rbar) {+ auto mm = std::make_shared<ov::op::v0::MatMul>(rbar, f16_inject_weights(), false, true);+ inject_mm = mm->output(0);+ auto scaled = std::make_shared<ov::op::v1::Multiply>(mm, ov::op::v0::Constant::create(ov::element::f16, ov::Shape{}, {1.0f / C}));+ auto sig = std::make_shared<ov::op::v0::Sigmoid>(scaled);+ return std::make_shared<ov::op::v1::Multiply>(sig, ov::op::v0::Constant::create(ov::element::f16, ov::Shape{}, {2.0f}))->output(0);+ };+ auto r = run_gate_fusion(w_down, w_up, make_gate, false, [&](const ov::Output<ov::Node>&) {+ return ov::OutputVector{inject_mm};+ });+ ASSERT_NE(r.gr, nullptr);+ EXPECT_FALSE(r.gr->get_produce_write_gate());+}++TEST(gated_residual_fusion_write_gate, compressed_weights_take_a_compressed_w_inject) {+ const size_t cd = C * D;+ const auto c = static_cast<size_t>(C);+ const auto lq = static_cast<size_t>(LQ);+ struct Case {+ ov::element::Type wt;+ size_t group_k_cd; // group size along C*D (W_down, W_inject)+ size_t group_k_l; // group size along L (W_up)+ bool has_zp;+ };+ for (const auto& tc : {Case{ov::element::u4, 32, 32, true},+ Case{ov::element::u8, cd, lq, true},+ Case{ov::element::i4, 32, 32, true},+ Case{ov::element::i8, cd, lq, true},+ Case{ov::element::u4, 32, 32, false},+ Case{ov::element::i8, cd, lq, false}}) {+ gate_fn make_gate = [&](const ov::Output<ov::Node>&, const ov::Output<ov::Node>& rbar) {+ return build_write_gate(rbar, make_decompressed(tc.wt, c, cd, tc.group_k_cd, false, tc.has_zp));+ };+ auto r = run_gate_fusion(make_decompressed(tc.wt, lq, cd, tc.group_k_cd, false, tc.has_zp),+ make_decompressed(tc.wt, cd, lq, tc.group_k_l, false, tc.has_zp),+ make_gate,+ true);+ expect_gate_fused(r, tc.has_zp ? 11u : 8u);+ const auto layout = r.gr->get_read_layout();+ ASSERT_TRUE(layout.has_value());+ EXPECT_EQ(layout->has_zp, tc.has_zp);+ EXPECT_EQ(r.gr->get_input_element_type(layout->w_inject), tc.wt);+ EXPECT_EQ(r.gr->get_input_shape(layout->w_inject), (ov::Shape{c, cd}));+ EXPECT_EQ(r.gr->get_input_element_type(layout->scale_inject), ov::element::f16);+ EXPECT_EQ(r.gr->get_input_shape(layout->scale_inject), (ov::Shape{c, cd / tc.group_k_cd}));+ if (tc.has_zp) {+ EXPECT_EQ(r.gr->get_input_element_type(layout->zp_inject), tc.wt);+ EXPECT_EQ(r.gr->get_input_shape(layout->zp_inject), (ov::Shape{c, cd / tc.group_k_cd}));+ }+ }+}++TEST(gated_residual_fusion_write_gate, compressed_read_with_f16_or_mismatched_w_inject_fuses_only_the_read) {+ const size_t cd = C * D;+ const auto c = static_cast<size_t>(C);+ // W_inject stays an f16 tensor while W_down / W_up are compressed+ auto f16_inject = run_gate_fusion(make_decompressed(ov::element::u4, LQ, cd, 32), make_decompressed(ov::element::u4, cd, LQ, 32), gate_on_rbar(), true);+ expect_gate_not_fused(f16_inject, 8u);+ // W_inject uses another weight type than W_down / W_up+ gate_fn u8_inject = [&](const ov::Output<ov::Node>&, const ov::Output<ov::Node>& rbar) {+ return build_write_gate(rbar, make_decompressed(ov::element::u8, c, cd, cd));+ };+ expect_gate_not_fused(run_gate_fusion(make_decompressed(ov::element::u4, LQ, cd, 32), make_decompressed(ov::element::u4, cd, LQ, 32), u8_inject, true), 8u);+ // W_inject with an unsupported group size+ gate_fn g16_inject = [&](const ov::Output<ov::Node>&, const ov::Output<ov::Node>& rbar) {+ return build_write_gate(rbar, make_decompressed(ov::element::u4, c, cd, 16));+ };+ expect_gate_not_fused(run_gate_fusion(make_decompressed(ov::element::u4, LQ, cd, 32), make_decompressed(ov::element::u4, cd, LQ, 32), g16_inject, true),+ 8u);+ // W_inject may use another group size than W_down / W_up+ gate_fn g128_inject = [&](const ov::Output<ov::Node>&, const ov::Output<ov::Node>& rbar) {+ return build_write_gate(rbar, make_decompressed(ov::element::u4, c, cd, 128));+ };+ expect_gate_fused(run_gate_fusion(make_decompressed(ov::element::u4, LQ, cd, 32), make_decompressed(ov::element::u4, cd, LQ, 32), g128_inject, true), 11u);+}++TEST(gated_residual_fusion_write_gate, compressed_w_inject_with_f16_read_weights_uses_the_decompressed_tensor) {+ const size_t cd = C * D;+ const auto c = static_cast<size_t>(C);+ const auto [w_down, w_up] = f16_read_weights();+ gate_fn compressed_inject = [&](const ov::Output<ov::Node>&, const ov::Output<ov::Node>& rbar) {+ return build_write_gate(rbar, make_decompressed(ov::element::u4, c, cd, 32));+ };+ expect_gate_fused(run_gate_fusion(w_down, w_up, compressed_inject, true), 5u);+}++TEST(gated_residual_fusion_write_gate, a_projection_that_is_not_a_write_gate_stays_a_read_without_the_gate) {+ const auto [w_down, w_up] = f16_read_weights();+ // an extra MatMul on Rbar without the sigmoid gate chain must not turn the READ into one that produces a write gate+ gate_fn raw_projection = [](const ov::Output<ov::Node>&, const ov::Output<ov::Node>& rbar) {+ return std::make_shared<ov::op::v0::MatMul>(rbar, f16_inject_weights(), false, true)->output(0);+ };+ const auto r = run_gate_fusion(w_down, w_up, raw_projection, false);+ ASSERT_NE(r.gr, nullptr);+ EXPECT_EQ(r.gr->get_mode(), op::GatedResidual::Mode::READ);+ EXPECT_FALSE(r.gr->get_produce_write_gate());+}++TEST(gated_residual_fusion_write_gate, a_matched_gate_with_unsupported_weights_is_a_read_without_the_gate_output) {+ const size_t cd = C * D;+ const auto r = run_gate_fusion(make_decompressed(ov::element::u4, LQ, cd, 32), make_decompressed(ov::element::u4, cd, LQ, 32), gate_on_rbar(), true);+ expect_gate_not_fused(r, 8u);+ EXPECT_EQ(r.gr->get_mode(), op::GatedResidual::Mode::READ);+}++TEST(gated_residual_fusion_write_gate, repacked_weight_constants_carry_the_fused_names) {+ const size_t cd = C * D;+ auto residual = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::PartialShape{T, C * D});+ ov::Output<ov::Node> rbar;+ auto mixed = build_gr_read_with_weights(residual, make_decompressed(ov::element::u4, LQ, cd, 32), make_decompressed(ov::element::u4, cd, LQ, 32), &rbar);+ auto gate = build_write_gate(rbar, make_decompressed(ov::element::u4, static_cast<size_t>(C), cd, 32));+ auto model = std::make_shared<ov::Model>(ov::OutputVector{mixed, gate}, ov::ParameterVector{residual});+ // As read from an IR with the weightless cache enabled: the repacked weights inherit this attribute.+ for (const auto& node : model->get_ops()) {+ if (ov::is_type<ov::op::v0::Constant>(node) && node->get_element_type() == ov::element::u4) {+ node->get_rt_info()[ov::WeightlessCacheAttribute::get_type_info_static()] =+ ov::WeightlessCacheAttribute(ov::shape_size(node->get_shape()) / 2, 0, ov::element::u4);+ }+ }+ ov::pass::Manager manager;+ manager.register_pass<ov::pass::InitNodeInfo>();+ manager.register_pass<GatedResidualReadFusion>(true);+ manager.run_passes(model);++ std::shared_ptr<op::GatedResidual> gr;+ for (const auto& node : model->get_ops()) {+ if (auto candidate = ov::as_type_ptr<op::GatedResidual>(node)) {+ gr = candidate;+ }+ }+ ASSERT_NE(gr, nullptr);+ ASSERT_TRUE(gr->get_produce_write_gate());+ for (size_t i = op::GatedResidual::ReadInputIdx::W_DOWN; i < gr->get_input_size(); ++i) {+ const auto input = gr->get_input_node_shared_ptr(i);+ EXPECT_FALSE(ov::getFusedNamesVector(input).empty()) << "input " << i;+ }+}++// ---------------------------------------------------------------------------+// Dynamic branch count, folded / swapped scalars and decomposed RMS variants+// ---------------------------------------------------------------------------+namespace {++/// GR READ over a rank-3 residual whose branch split has a dynamic C ([B, L, C*D] -> [B, L, ?, D]), as the paged attention+/// transformation leaves it; `w_cols` is the width of W_down / the height of W_up, i.e. the C*D the pass has to derive C from.+std::shared_ptr<ov::Node> build_gr_read_dynamic_branches(const std::shared_ptr<ov::op::v0::Parameter>& residual, int64_t w_cols) {+ auto r4 = zero_split(residual, {-1, D});+ auto gamma = ov::op::v0::Constant::create(ov::element::f16, ov::Shape{static_cast<size_t>(C), static_cast<size_t>(D)}, std::vector<float>(C * D, 1.0f));+ auto rms = std::make_shared<ov::op::internal::RMS>(r4, gamma, EPS);+ auto rbar = zero_split(rms, {-1});++ auto w_down =+ ov::op::v0::Constant::create(ov::element::f16, ov::Shape{static_cast<size_t>(L), static_cast<size_t>(w_cols)}, std::vector<float>(L * w_cols, 0.01f));+ auto low = std::make_shared<ov::op::v0::MatMul>(rbar, w_down, false, true);+ auto act = std::make_shared<ov::op::v4::Swish>(+ std::make_shared<ov::op::v1::Multiply>(low, ov::op::v0::Constant::create(ov::element::f16, ov::Shape{}, {1.0f / C})));+ auto w_up =+ ov::op::v0::Constant::create(ov::element::f16, ov::Shape{static_cast<size_t>(w_cols), static_cast<size_t>(L)}, std::vector<float>(w_cols * L, 0.01f));+ auto gate = std::make_shared<ov::op::v0::Sigmoid>(std::make_shared<ov::op::v0::MatMul>(act, w_up, false, true));+ auto weighted4 = zero_split(std::make_shared<ov::op::v1::Multiply>(gate, rbar), {-1, D});+ auto reduced = std::make_shared<ov::op::v1::ReduceSum>(weighted4, ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, {-2}), false);+ return std::make_shared<ov::op::v1::Multiply>(reduced, ov::op::v0::Constant::create(ov::element::f16, ov::Shape{}, {1.0f / C}));+}++size_t fused_read_count(const std::shared_ptr<ov::Node>& mixed, const std::shared_ptr<ov::op::v0::Parameter>& residual) {+ auto model = std::make_shared<ov::Model>(ov::OutputVector{mixed}, ov::ParameterVector{residual});+ ov::pass::Manager manager;+ manager.register_pass<GatedResidualReadFusion>();+ manager.run_passes(model);+ return count_gated_residual(model);+}++} // namespace++TEST(gated_residual_fusion, branch_count_is_derived_from_w_down_when_the_split_width_is_dynamic) {+ auto residual = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::PartialShape{-1, -1, -1});+ auto model = std::make_shared<ov::Model>(ov::OutputVector{build_gr_read_dynamic_branches(residual, C * D)}, ov::ParameterVector{residual});+ ov::pass::Manager manager;+ manager.register_pass<GatedResidualReadFusion>();+ manager.run_passes(model);++ ASSERT_EQ(count_gated_residual(model), 1u);+ for (const auto& node : model->get_ops()) {+ if (auto gr = ov::as_type_ptr<op::GatedResidual>(node)) {+ EXPECT_EQ(gr->get_hc_count(), static_cast<size_t>(C));+ EXPECT_EQ(gr->get_hidden_size(), static_cast<size_t>(D));+ EXPECT_EQ(gr->get_output_partial_shape(0), (ov::PartialShape{-1, -1, D}));+ }+ }+}++TEST(gated_residual_fusion, derived_branch_count_must_be_supported) {+ auto residual = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::PartialShape{-1, -1, -1});+ // C = 128 / 64 = 2 is not a supported branch count+ EXPECT_EQ(fused_read_count(build_gr_read_dynamic_branches(residual, 2 * D), residual), 0u);+}++TEST(gated_residual_fusion, down_scale_folded_into_w_down_reaches_the_kernel_unscaled) {+ const auto [w_down, w_up] = f16_read_weights();+ auto residual = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::PartialShape{T, C * D});+ auto mixed = build_gr_read_with_weights(residual, w_down, w_up, nullptr, true);+ auto model = std::make_shared<ov::Model>(ov::OutputVector{mixed}, ov::ParameterVector{residual});+ ov::pass::Manager manager;+ manager.register_pass<GatedResidualReadFusion>();+ manager.run_passes(model);++ ASSERT_EQ(count_gated_residual(model), 1u);+ for (const auto& node : model->get_ops()) {+ if (auto gr = ov::as_type_ptr<op::GatedResidual>(node)) {+ EXPECT_EQ(gr->get_input_node_ptr(op::GatedResidual::ReadInputIdx::W_DOWN), w_down.get_node());+ }+ }+}++TEST(gated_residual_fusion, down_scale_folded_into_w_down_must_be_inv_c) {+ const auto [w_down, w_up] = f16_read_weights();+ auto residual = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::PartialShape{T, C * D});+ auto mixed = build_gr_read_with_weights(residual, w_down, w_up, nullptr, true, 0.5f);+ EXPECT_EQ(fused_read_count(mixed, residual), 0u);+}++TEST(gated_residual_fusion, decomposed_power_inverse_rms_is_fused) {+ auto residual = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::PartialShape{T, C * D});+ EXPECT_EQ(fused_read_count(build_gr_read_decomposed(residual, 1.0f / C, C, true, false, -1.0f), residual), 1u);+}++TEST(gated_residual_fusion, decomposed_power_inverse_rms_rejects_other_exponents) {+ auto residual = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::PartialShape{T, C * D});+ for (const float exponent : {-0.5f, 1.0f, -2.0f}) {+ EXPECT_EQ(fused_read_count(build_gr_read_decomposed(residual, 1.0f / C, C, true, false, exponent), residual), 0u) << exponent;+ }+}++TEST(gated_residual_fusion, decomposed_epsilon_may_be_the_first_add_operand) {+ auto residual = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::PartialShape{T, C * D});+ auto model = std::make_shared<ov::Model>(ov::OutputVector{build_gr_read_decomposed(residual, 1.0f / C, C, true, false, std::nullopt, true)},+ ov::ParameterVector{residual});+ ov::pass::Manager manager;+ manager.register_pass<GatedResidualReadFusion>();+ manager.run_passes(model);++ ASSERT_EQ(count_gated_residual(model), 1u);+ for (const auto& node : model->get_ops()) {+ if (auto gr = ov::as_type_ptr<op::GatedResidual>(node)) {+ EXPECT_FLOAT_EQ(gr->get_epsilon(), static_cast<float>(ov::float16(EPS)));+ }+ }+}++TEST(gated_residual_fusion, op_reads_norm_weight_and_float_weights_as_the_residual_type) {+ auto make = [](const ov::element::Type& gain_et, const ov::element::Type& weight_et) {+ auto residual = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::PartialShape{T, C * D});+ auto gain = std::make_shared<ov::op::v0::Parameter>(gain_et, ov::PartialShape{C * D});+ auto w_down = std::make_shared<ov::op::v0::Parameter>(weight_et, ov::PartialShape{L, C * D});+ auto w_up = std::make_shared<ov::op::v0::Parameter>(weight_et, ov::PartialShape{C * D, L});+ return std::make_shared<op::GatedResidual>(ov::OutputVector{residual, gain, w_down, w_up},+ op::GatedResidual::Mode::READ,+ static_cast<size_t>(C),+ static_cast<size_t>(D),+ static_cast<size_t>(L),+ EPS,+ false);+ };+ EXPECT_NO_THROW(static_cast<void>(make(ov::element::f16, ov::element::f16)));+ EXPECT_THROW(static_cast<void>(make(ov::element::f32, ov::element::f16)), ov::NodeValidationFailure);+ EXPECT_THROW(static_cast<void>(make(ov::element::f16, ov::element::f32)), ov::NodeValidationFailure);+}++TEST(gated_residual_fusion, op_rejects_an_unknown_mode) {+ auto residual = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::PartialShape{T, C * D});+ auto gain = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::PartialShape{C * D});+ auto w_down = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::PartialShape{L, C * D});+ auto w_up = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::PartialShape{C * D, L});+ // 2 was FINAL_MIX, now a READ without a write gate+ EXPECT_THROW(static_cast<void>(std::make_shared<op::GatedResidual>(ov::OutputVector{residual, gain, w_down, w_up},+ static_cast<op::GatedResidual::Mode>(2),+ static_cast<size_t>(C),+ static_cast<size_t>(D),+ static_cast<size_t>(L),+ EPS,+ false)),+ ov::NodeValidationFailure);+}++// ---------------------------------------------------------------------------+// Reference-model comparisons: rewiring, constants, attributes and runtime info of the fused graph+// ---------------------------------------------------------------------------+TEST_F(TransformationTestsF, gated_residual_write_matches_the_reference_graph) {+ {+ auto residual = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::PartialShape{T, C * D});+ auto y = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::PartialShape{T, D});+ auto s = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::PartialShape{T, C});+ auto scaled = std::make_shared<ov::op::v1::Multiply>(reshape_to(s, {-1, C, 1}), reshape_to(y, {-1, 1, D}));+ auto out = reshape_to(std::make_shared<ov::op::v1::Add>(reshape_to(residual, {-1, C, D}), scaled), {-1, C * D});+ model = std::make_shared<ov::Model>(ov::OutputVector{out}, ov::ParameterVector{residual, y, s});+ manager.register_pass<GatedResidualWriteFusion>();+ }+ {+ auto residual = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::PartialShape{T, C * D});+ auto y = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::PartialShape{T, D});+ auto s = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::PartialShape{T, C});+ auto gr = std::make_shared<op::GatedResidual>(ov::OutputVector{residual, y, s},+ op::GatedResidual::Mode::WRITE,+ static_cast<size_t>(C),+ static_cast<size_t>(D),+ 0,+ 0.0f,+ false);+ model_ref = std::make_shared<ov::Model>(ov::OutputVector{gr}, ov::ParameterVector{residual, y, s});+ }+ comparator.enable(FunctionsComparator::CmpValues::ATTRIBUTES);+ comparator.enable(FunctionsComparator::CmpValues::CONST_VALUES);+}++TEST_F(TransformationTestsF, gated_residual_read_matches_the_reference_graph) {+ {+ auto residual = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::PartialShape{T, C * D});+ model = std::make_shared<ov::Model>(ov::OutputVector{build_gr_read(residual, 1.0f / C, 1.0f / C, C)}, ov::ParameterVector{residual});+ manager.register_pass<GatedResidualReadFusion>();+ }+ {+ auto residual = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::PartialShape{T, C * D});+ auto gamma = ov::op::v0::Constant::create(ov::element::f16, ov::Shape{static_cast<size_t>(C), static_cast<size_t>(D)}, std::vector<float>(C * D, 1.0f));+ auto gain = reshape_to(gamma, {C * D});+ auto w_down =+ ov::op::v0::Constant::create(ov::element::f16, ov::Shape{static_cast<size_t>(L), static_cast<size_t>(C * D)}, std::vector<float>(L * C * D, 0.01f));+ auto w_up =+ ov::op::v0::Constant::create(ov::element::f16, ov::Shape{static_cast<size_t>(C * D), static_cast<size_t>(L)}, std::vector<float>(C * D * L, 0.01f));+ auto gr = std::make_shared<op::GatedResidual>(ov::OutputVector{residual, gain, w_down, w_up},+ op::GatedResidual::Mode::READ,+ static_cast<size_t>(C),+ static_cast<size_t>(D),+ static_cast<size_t>(L),+ EPS,+ false);+ model_ref = std::make_shared<ov::Model>(ov::OutputVector{gr}, ov::ParameterVector{residual});+ }+ comparator.enable(FunctionsComparator::CmpValues::ATTRIBUTES);+ comparator.enable(FunctionsComparator::CmpValues::CONST_VALUES);+}++TEST_F(TransformationTestsF, gated_residual_read_with_write_gate_matches_the_reference_graph) {+ {+ const auto [w_down, w_up] = f16_read_weights();+ auto residual = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::PartialShape{T, C * D});+ ov::Output<ov::Node> rbar;+ auto mixed = build_gr_read_with_weights(residual, w_down, w_up, &rbar);+ model = std::make_shared<ov::Model>(ov::OutputVector{mixed, build_write_gate(rbar, f16_inject_weights())}, ov::ParameterVector{residual});+ manager.register_pass<GatedResidualReadFusion>();+ }+ {+ const auto [w_down, w_up] = f16_read_weights();+ auto residual = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::PartialShape{T, C * D});+ auto gamma = ov::op::v0::Constant::create(ov::element::f16, ov::Shape{static_cast<size_t>(C), static_cast<size_t>(D)}, std::vector<float>(C * D, 1.0f));+ auto gr = std::make_shared<op::GatedResidual>(ov::OutputVector{residual, reshape_to(gamma, {C * D}), w_down, w_up, f16_inject_weights()},+ op::GatedResidual::Mode::READ,+ static_cast<size_t>(C),+ static_cast<size_t>(D),+ static_cast<size_t>(LQ),+ EPS,+ true);+ model_ref = std::make_shared<ov::Model>(ov::OutputVector{gr->output(0), gr->output(1)}, ov::ParameterVector{residual});+ }+ // Both results used to come from different nodes but now share the single fused op, which can keep only one name.+ disable_result_friendly_names_check();+ comparator.enable(FunctionsComparator::CmpValues::ATTRIBUTES);+ comparator.enable(FunctionsComparator::CmpValues::CONST_VALUES);+}