Skip to content

OpenVINO™ is an open source toolkit for optimizing and deploying AI inference

54.6 KB
Raw Blame
// Copyright (C) 2018-2026 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//

#include "partitioning/patterns/pre_compute.hpp"

#include <gtest/gtest.h>

#include <algorithm>
#include <cstring>
#include <memory>
#include <sstream>
#include <string>
#include <tuple>
#include <vector>

#include "common_test_utils/ov_test_utils.hpp"
#include "openvino/core/except.hpp"
#include "openvino/core/graph_util.hpp"
#include "openvino/op/ops.hpp"
#include "orc.hpp"

namespace {

std::shared_ptr<ov::Model> make_longrope_v5_model(const std::vector<float>& short_factor_values,
                                                  const std::vector<float>& long_factor_values,
                                                  const std::vector<float>& multiply_values,
                                                  const std::vector<float>& power_values,
                                                  int32_t cond_offset = 1,
                                                  bool with_broadcast = true) {
    auto data = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::Shape{1, 4, 2});
    auto position_ids =
        std::make_shared<ov::op::v0::Parameter>(ov::element::i32, with_broadcast ? ov::Shape{2, 1} : ov::Shape{1, 4});

    auto short_factor =
        ov::op::v0::Constant::create(ov::element::f32, ov::Shape{short_factor_values.size()}, short_factor_values);
    auto long_factor =
        ov::op::v0::Constant::create(ov::element::f32, ov::Shape{long_factor_values.size()}, long_factor_values);
    auto multiply_const =
        ov::op::v0::Constant::create(ov::element::f32, ov::Shape{multiply_values.size()}, multiply_values);
    auto power_const = ov::op::v0::Constant::create(ov::element::f32, ov::Shape{power_values.size()}, power_values);

    auto reduce_axes = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{2}, {0, 1});
    auto red_max = std::make_shared<ov::op::v1::ReduceMax>(position_ids, reduce_axes, false);
    auto offset_i32 = ov::op::v0::Constant::create(ov::element::i32, ov::Shape{}, {cond_offset});
    auto add = std::make_shared<ov::op::v1::Add>(red_max, offset_i32);
    auto max_pos = ov::op::v0::Constant::create(ov::element::i32, ov::Shape{}, {4});
    auto greater = std::make_shared<ov::op::v1::Greater>(add, max_pos);

    auto select = std::make_shared<ov::op::v1::Select>(greater, long_factor, short_factor);
    auto multiply = std::make_shared<ov::op::v1::Multiply>(select, multiply_const);
    auto power = std::make_shared<ov::op::v1::Power>(multiply, power_const);

    auto unsqueeze_axis0 = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, {0});
    auto unsqueeze_axis1 = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, {1});
    auto unsqueeze_axis2 = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, {2});
    auto unsq0 = std::make_shared<ov::op::v0::Unsqueeze>(power, unsqueeze_axis0);
    auto unsq1 = std::make_shared<ov::op::v0::Unsqueeze>(unsq0, with_broadcast ? unsqueeze_axis0 : unsqueeze_axis2);

    ov::Output<ov::Node> frequency_input = unsq1;
    if (with_broadcast) {
        auto shape_of = std::make_shared<ov::op::v3::ShapeOf>(data);
        auto gather_idx0 = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, {0});
        auto axis0 = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{}, {0});
        auto gather = std::make_shared<ov::op::v8::Gather>(shape_of, gather_idx0, axis0);
        auto seq_len = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, {4});
        auto rotary_dims = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, {2});
        auto concat_1 = std::make_shared<ov::op::v0::Concat>(ov::OutputVector{gather, seq_len, rotary_dims}, 0);
        frequency_input = std::make_shared<ov::op::v3::Broadcast>(unsq1, concat_1);
    }

    auto pos_unsq =
        std::make_shared<ov::op::v0::Unsqueeze>(position_ids, with_broadcast ? unsqueeze_axis0 : unsqueeze_axis1);
    auto pos_fp32 = std::make_shared<ov::op::v0::Convert>(pos_unsq, ov::element::f32);
    auto matmul = std::make_shared<ov::op::v0::MatMul>(frequency_input, pos_fp32);

    auto transpose_order = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{3}, {0, 2, 1});
    auto transpose = std::make_shared<ov::op::v1::Transpose>(matmul, transpose_order);
    auto zeros = ov::op::v0::Constant::create(ov::element::f32, ov::Shape{1, 1, 4}, {0.0f, 0.0f, 0.0f, 0.0f});
    auto concat_2 = with_broadcast ? std::make_shared<ov::op::v0::Concat>(ov::OutputVector{transpose, zeros}, 1)
                                   : std::make_shared<ov::op::v0::Concat>(ov::OutputVector{transpose, transpose}, -1);

    auto sin = std::make_shared<ov::op::v0::Sin>(concat_2);
    auto cos = std::make_shared<ov::op::v0::Cos>(concat_2);

    sin->set_friendly_name("sin_out");
    cos->set_friendly_name("cos_out");

    auto sin_res = std::make_shared<ov::op::v0::Result>(sin);
    auto cos_res = std::make_shared<ov::op::v0::Result>(cos);
    return std::make_shared<ov::Model>(
        ov::ResultVector{sin_res, cos_res},
        with_broadcast ? ov::ParameterVector{data, position_ids} : ov::ParameterVector{position_ids},
        "longrope_v5_test_model");
}

// Builds a minimal model matching the older LongRopePatternPhi: the Select picks
// between two ready-made inverse-frequency constants on
// max(position_ids) + 1 <= original_max_position_embeddings.
std::shared_ptr<ov::Model> make_longrope_phi_model(const std::vector<float>& inv_freq_short_values,
                                                   const std::vector<float>& inv_freq_long_values,
                                                   int32_t context_limit,
                                                   int32_t cond_offset = 1,
                                                   bool with_broadcast = true) {
    auto data = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::Shape{1, 4, 2});
    auto position_ids =
        std::make_shared<ov::op::v0::Parameter>(ov::element::i32, with_broadcast ? ov::Shape{2, 1} : ov::Shape{1, 4});

    auto inv_freq_short =
        ov::op::v0::Constant::create(ov::element::f32, ov::Shape{inv_freq_short_values.size()}, inv_freq_short_values);
    auto inv_freq_long =
        ov::op::v0::Constant::create(ov::element::f32, ov::Shape{inv_freq_long_values.size()}, inv_freq_long_values);

    auto reduce_axes = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{2}, {0, 1});
    auto red_max = std::make_shared<ov::op::v1::ReduceMax>(position_ids, reduce_axes, false);
    auto offset_i32 = ov::op::v0::Constant::create(ov::element::i32, ov::Shape{}, {cond_offset});
    auto add = std::make_shared<ov::op::v1::Add>(red_max, offset_i32);
    auto limit = ov::op::v0::Constant::create(ov::element::i32, ov::Shape{}, {context_limit});
    auto leq = std::make_shared<ov::op::v1::LessEqual>(add, limit);

    auto select = std::make_shared<ov::op::v1::Select>(leq, inv_freq_short, inv_freq_long);

    auto unsqueeze_axis0 = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, {0});
    auto unsqueeze_axis1 = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, {1});
    auto unsqueeze_axis2 = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, {2});
    auto unsq0 = std::make_shared<ov::op::v0::Unsqueeze>(select, unsqueeze_axis0);
    auto unsq1 = std::make_shared<ov::op::v0::Unsqueeze>(unsq0, with_broadcast ? unsqueeze_axis0 : unsqueeze_axis2);

    ov::Output<ov::Node> frequency_input = unsq1;
    if (with_broadcast) {
        auto shape_of = std::make_shared<ov::op::v3::ShapeOf>(data);
        auto gather_idx0 = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, {0});
        auto axis0 = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{}, {0});
        auto gather = std::make_shared<ov::op::v8::Gather>(shape_of, gather_idx0, axis0);
        auto seq_len = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, {4});
        auto rotary_dims = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, {2});
        auto concat_1 = std::make_shared<ov::op::v0::Concat>(ov::OutputVector{gather, seq_len, rotary_dims}, 0);
        frequency_input = std::make_shared<ov::op::v3::Broadcast>(unsq1, concat_1);
    }

    auto pos_unsq =
        std::make_shared<ov::op::v0::Unsqueeze>(position_ids, with_broadcast ? unsqueeze_axis0 : unsqueeze_axis1);
    auto pos_fp32 = std::make_shared<ov::op::v0::Convert>(pos_unsq, ov::element::f32);
    auto matmul = std::make_shared<ov::op::v0::MatMul>(frequency_input, pos_fp32);

    auto transpose_order = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{3}, {0, 2, 1});
    auto transpose = std::make_shared<ov::op::v1::Transpose>(matmul, transpose_order);
    auto zeros = ov::op::v0::Constant::create(ov::element::f32, ov::Shape{1, 1, 4}, {0.0f, 0.0f, 0.0f, 0.0f});
    auto concat_2 = with_broadcast ? std::make_shared<ov::op::v0::Concat>(ov::OutputVector{transpose, zeros}, 1)
                                   : std::make_shared<ov::op::v0::Concat>(ov::OutputVector{transpose, transpose}, -1);

    auto sin = std::make_shared<ov::op::v0::Sin>(concat_2);
    auto cos = std::make_shared<ov::op::v0::Cos>(concat_2);

    return std::make_shared<ov::Model>(
        ov::ResultVector{std::make_shared<ov::op::v0::Result>(sin), std::make_shared<ov::op::v0::Result>(cos)},
        with_broadcast ? ov::ParameterVector{data, position_ids} : ov::ParameterVector{position_ids},
        "longrope_phi_test_model");
}

// Builds a minimal RoPE model matching RopePatternLLama2.
// When with_concat2=true (LLama2 style): Transpose → Concat_2 → Sin/Cos, duplicate_freqs=true.
// When with_concat2=false (GPT style):   Transpose → Sin/Cos directly, duplicate_freqs=false.
std::shared_ptr<ov::Model> make_rope_model(bool with_concat2) {
    auto data = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::Shape{1, 4, 4});
    auto position_ids = std::make_shared<ov::op::v0::Parameter>(ov::element::i64, ov::Shape{1, 4});

    // inv_freq: constant [1, half_dim=2, 1]
    auto inv_freq = ov::op::v0::Constant::create(ov::element::f32, ov::Shape{1, 2, 1}, {0.5f, 0.1f});

    // ShapeOf → Gather(batch dim) → Concat_1 (broadcast target shape)
    auto shape_of = std::make_shared<ov::op::v3::ShapeOf>(data);
    auto gather_idx = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, {0});
    auto gather_axis = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{}, {0});
    auto gather = std::make_shared<ov::op::v8::Gather>(shape_of, gather_idx, gather_axis);
    auto ndims_const = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, {2});
    auto one_const = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, {1});
    auto concat_1 = std::make_shared<ov::op::v0::Concat>(ov::OutputVector{gather, ndims_const, one_const}, 0);

    // Broadcast inv_freq to [1,2,1], MatMul with position_ids → Transpose
    auto broadcast = std::make_shared<ov::op::v3::Broadcast>(inv_freq, concat_1);
    auto unsq_axis = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, {1});
    auto unsqueeze = std::make_shared<ov::op::v0::Unsqueeze>(position_ids, unsq_axis);
    auto convert = std::make_shared<ov::op::v0::Convert>(unsqueeze, ov::element::f32);
    auto matmul = std::make_shared<ov::op::v0::MatMul>(broadcast, convert);  // [1,2,4]
    auto perm = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{3}, std::vector<int64_t>{0, 2, 1});
    auto transpose = std::make_shared<ov::op::v1::Transpose>(matmul, perm);  // [1,4,2]

    // Sin/Cos either via Concat_2 (LLama2's torch.cat([freqs, freqs], -1), i.e. transpose
    // concatenated with itself) or directly (GPT)
    ov::Output<ov::Node> sin_cos_input = transpose->output(0);
    if (with_concat2) {
        sin_cos_input = std::make_shared<ov::op::v0::Concat>(ov::OutputVector{transpose, transpose}, -1)->output(0);
    }

    auto sin = std::make_shared<ov::op::v0::Sin>(sin_cos_input);
    auto cos = std::make_shared<ov::op::v0::Cos>(sin_cos_input);

    return std::make_shared<ov::Model>(
        ov::ResultVector{std::make_shared<ov::op::v0::Result>(sin), std::make_shared<ov::op::v0::Result>(cos)},
        ov::ParameterVector{data, position_ids},
        with_concat2 ? "llama2_rope_test_model" : "gpt_rope_test_model");
}

// Builds a Gemma 4-style model with hybrid attention, it has multiple independent RoPE blocks.
// `result_order`, as (block index, is_cos) pairs, lets a test pick a non-default Results
// ordering; empty means the natural per-block (sin_i, cos_i) grouping.
std::shared_ptr<ov::Model> make_multi_rope_model(const std::vector<std::vector<float>>& inv_freqs,
                                                 const std::vector<std::pair<size_t, bool>>& result_order = {}) {
    auto data = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::Shape{1, 4, 4});
    auto position_ids = std::make_shared<ov::op::v0::Parameter>(ov::element::i64, ov::Shape{1, 4});

    // Shared shape-compute chain (ShapeOf->Gather->Concat_1).
    auto shape_of = std::make_shared<ov::op::v3::ShapeOf>(data);
    auto gather_idx = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, {0});
    auto gather_axis = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{}, {0});
    auto gather = std::make_shared<ov::op::v8::Gather>(shape_of, gather_idx, gather_axis);
    auto ndims_const = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, {2});
    auto one_const = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, {1});
    auto concat_1 = std::make_shared<ov::op::v0::Concat>(ov::OutputVector{gather, ndims_const, one_const}, 0);

    // Shared position_ids branch (Unsqueeze->Convert).
    auto unsq_axis = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, {1});
    auto unsqueeze = std::make_shared<ov::op::v0::Unsqueeze>(position_ids, unsq_axis);
    auto convert = std::make_shared<ov::op::v0::Convert>(unsqueeze, ov::element::f32);

    std::vector<ov::Output<ov::Node>> sin_outs(inv_freqs.size());
    std::vector<ov::Output<ov::Node>> cos_outs(inv_freqs.size());
    for (size_t i = 0; i < inv_freqs.size(); ++i) {
        const auto& freqs = inv_freqs[i];
        auto inv_freq = ov::op::v0::Constant::create(ov::element::f32, ov::Shape{1, freqs.size(), 1}, freqs);

        auto broadcast = std::make_shared<ov::op::v3::Broadcast>(inv_freq, concat_1);
        auto matmul = std::make_shared<ov::op::v0::MatMul>(broadcast, convert);  // [1, freqs.size(), 4]
        auto perm = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{3}, std::vector<int64_t>{0, 2, 1});
        auto transpose = std::make_shared<ov::op::v1::Transpose>(matmul, perm);  // [1, 4, freqs.size()]

        auto concat_2 = std::make_shared<ov::op::v0::Concat>(ov::OutputVector{transpose, transpose}, -1);

        auto sin = std::make_shared<ov::op::v0::Sin>(concat_2);
        auto cos = std::make_shared<ov::op::v0::Cos>(concat_2);
        sin->set_friendly_name("sin_" + std::to_string(i));
        cos->set_friendly_name("cos_" + std::to_string(i));

        sin_outs[i] = sin->output(0);
        cos_outs[i] = cos->output(0);
    }

    ov::ResultVector results;
    if (result_order.empty()) {
        for (size_t i = 0; i < inv_freqs.size(); ++i) {
            results.push_back(std::make_shared<ov::op::v0::Result>(sin_outs[i]));
            results.push_back(std::make_shared<ov::op::v0::Result>(cos_outs[i]));
        }
    } else {
        for (const auto& entry : result_order) {
            results.push_back(
                std::make_shared<ov::op::v0::Result>(entry.second ? cos_outs[entry.first] : sin_outs[entry.first]));
        }
    }

    return std::make_shared<ov::Model>(results, ov::ParameterVector{data, position_ids}, "multi_rope_test_model");
}

// A model with one full RoPE block (Sin+Cos) plus a second, independent Cos with no Sin partner.
std::shared_ptr<ov::Model> make_rope_model_with_lone_cos(const std::vector<float>& paired_freqs,
                                                         const std::vector<float>& lone_cos_freqs) {
    auto model = make_multi_rope_model({paired_freqs, lone_cos_freqs});

    // Drop the second block's Sin result, turning it into a Cos-only chain.
    auto results = model->get_results();
    model->remove_result(results[2]);  // sin_1
    return model;
}

// Same as make_rope_model(/*with_concat2=*/true), but the Concat's 2nd input is zeros instead
// of a duplicate of the transpose output - e.g. partial-rotary models that pad rather than
// duplicate. The matcher must not mistake this for freq duplication.
std::shared_ptr<ov::Model> make_rope_model_non_duplicating_concat() {
    auto data = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::Shape{1, 4, 4});
    auto position_ids = std::make_shared<ov::op::v0::Parameter>(ov::element::i64, ov::Shape{1, 4});

    auto inv_freq = ov::op::v0::Constant::create(ov::element::f32, ov::Shape{1, 2, 1}, {0.5f, 0.1f});

    auto shape_of = std::make_shared<ov::op::v3::ShapeOf>(data);
    auto gather_idx = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, {0});
    auto gather_axis = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{}, {0});
    auto gather = std::make_shared<ov::op::v8::Gather>(shape_of, gather_idx, gather_axis);
    auto ndims_const = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, {2});
    auto one_const = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, {1});
    auto concat_1 = std::make_shared<ov::op::v0::Concat>(ov::OutputVector{gather, ndims_const, one_const}, 0);

    auto broadcast = std::make_shared<ov::op::v3::Broadcast>(inv_freq, concat_1);
    auto unsq_axis = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, {1});
    auto unsqueeze = std::make_shared<ov::op::v0::Unsqueeze>(position_ids, unsq_axis);
    auto convert = std::make_shared<ov::op::v0::Convert>(unsqueeze, ov::element::f32);
    auto matmul = std::make_shared<ov::op::v0::MatMul>(broadcast, convert);
    auto perm = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{3}, std::vector<int64_t>{0, 2, 1});
    auto transpose = std::make_shared<ov::op::v1::Transpose>(matmul, perm);

    auto zeros = ov::op::v0::Constant::create(ov::element::f32, ov::Shape{1, 4, 2}, std::vector<float>(8, 0.f));
    auto concat_2 = std::make_shared<ov::op::v0::Concat>(ov::OutputVector{transpose, zeros}, -1);

    auto sin = std::make_shared<ov::op::v0::Sin>(concat_2);
    auto cos = std::make_shared<ov::op::v0::Cos>(concat_2);

    return std::make_shared<ov::Model>(
        ov::ResultVector{std::make_shared<ov::op::v0::Result>(sin), std::make_shared<ov::op::v0::Result>(cos)},
        ov::ParameterVector{data, position_ids},
        "non_duplicating_concat_rope_test_model");
}

// Builds a RoPE model matching make_rope_model's two flavours, but where inv_freq is
// already exported pre-broadcast to its final [1, half_dim, 1] shape, with no live
// Broadcast node (and no ShapeOf->Gather->Concat shape-compute chain feeding it) - as
// seen e.g. on Qwen3, where the exporter folds the broadcast away.
std::shared_ptr<ov::Model> make_rope_model_no_broadcast(bool with_concat2) {
    auto position_ids = std::make_shared<ov::op::v0::Parameter>(ov::element::i64, ov::Shape{1, 4});

    // inv_freq already shaped as if Broadcast had run: [1, half_dim=2, 1]
    auto inv_freq = ov::op::v0::Constant::create(ov::element::f32, ov::Shape{1, 2, 1}, {0.5f, 0.1f});

    auto unsq_axis = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, {1});
    auto unsqueeze = std::make_shared<ov::op::v0::Unsqueeze>(position_ids, unsq_axis);
    auto convert = std::make_shared<ov::op::v0::Convert>(unsqueeze, ov::element::f32);
    auto matmul = std::make_shared<ov::op::v0::MatMul>(inv_freq, convert);  // [1,2,4]
    auto perm = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{3}, std::vector<int64_t>{0, 2, 1});
    auto transpose = std::make_shared<ov::op::v1::Transpose>(matmul, perm);  // [1,4,2]

    ov::Output<ov::Node> sin_cos_input = transpose->output(0);
    if (with_concat2) {
        sin_cos_input = std::make_shared<ov::op::v0::Concat>(ov::OutputVector{transpose, transpose}, -1)->output(0);
    }

    auto sin = std::make_shared<ov::op::v0::Sin>(sin_cos_input);
    auto cos = std::make_shared<ov::op::v0::Cos>(sin_cos_input);

    return std::make_shared<ov::Model>(
        ov::ResultVector{std::make_shared<ov::op::v0::Result>(sin), std::make_shared<ov::op::v0::Result>(cos)},
        ov::ParameterVector{position_ids},
        with_concat2 ? "llama2_rope_no_broadcast_test_model" : "gpt_rope_no_broadcast_test_model");
}

// Same as make_rope_model_no_broadcast(/*with_concat2=*/true), but inv_freq has a real (non-
// singleton) leading batch dim - a shape the "no live Broadcast" fallback never validates.
// Without a validity check, makeCosSinCache would flatten this into the frequency axis and
// silently corrupt the LUT's shape, so the matcher must leave Sin/Cos untouched instead.
std::shared_ptr<ov::Model> make_rope_model_no_broadcast_extra_batch_dim() {
    auto position_ids = std::make_shared<ov::op::v0::Parameter>(ov::element::i64, ov::Shape{1, 4});

    // inv_freq shaped [2, 2, 1] - batch=2, not the expected singleton batch dim.
    auto inv_freq = ov::op::v0::Constant::create(ov::element::f32, ov::Shape{2, 2, 1}, {0.5f, 0.1f, 0.5f, 0.1f});

    auto unsq_axis = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, {1});
    auto unsqueeze = std::make_shared<ov::op::v0::Unsqueeze>(position_ids, unsq_axis);
    auto convert = std::make_shared<ov::op::v0::Convert>(unsqueeze, ov::element::f32);
    auto matmul = std::make_shared<ov::op::v0::MatMul>(inv_freq, convert);  // [2,2,4]
    auto perm = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{3}, std::vector<int64_t>{0, 2, 1});
    auto transpose = std::make_shared<ov::op::v1::Transpose>(matmul, perm);  // [2,4,2]

    auto concat_2 = std::make_shared<ov::op::v0::Concat>(ov::OutputVector{transpose, transpose}, -1);

    auto sin = std::make_shared<ov::op::v0::Sin>(concat_2);
    auto cos = std::make_shared<ov::op::v0::Cos>(concat_2);

    return std::make_shared<ov::Model>(
        ov::ResultVector{std::make_shared<ov::op::v0::Result>(sin), std::make_shared<ov::op::v0::Result>(cos)},
        ov::ParameterVector{position_ids},
        "llama2_rope_no_broadcast_extra_batch_dim_test_model");
}

bool has_input_name(const std::shared_ptr<ov::Model>& model, const std::string& name) {
    const auto inputs = model->inputs();
    return std::any_of(inputs.begin(), inputs.end(), [&name](const auto& input) {
        const auto& names = input.get_names();
        return std::any_of(names.begin(), names.end(), [&name](const auto& candidate) {
            return candidate == name;
        });
    });
}

size_t count_ops_of_type_sin_cos(const std::shared_ptr<ov::Model>& model) {
    const auto& ops = model->get_ops();
    return static_cast<size_t>(std::count_if(ops.begin(), ops.end(), [](const auto& op) {
        return ov::is_type<ov::op::v0::Sin>(op) || ov::is_type<ov::op::v0::Cos>(op);
    }));
}

// Every LongRoPE model, old or new pattern, must end up with the same shape of result:
// no Sin/Cos and no Select left, and two named cos/sin inputs instead.
void expect_longrope_lut_inputs(const std::shared_ptr<ov::Model>& model) {
    EXPECT_EQ(count_ops_of_type_sin_cos(model), 0u);
    const auto& ops = model->get_ops();
    EXPECT_EQ(std::count_if(ops.begin(),
                            ops.end(),
                            [](const auto& op) {
                                return ov::is_type<ov::op::v1::Select>(op);
                            }),
              0)
        << "the short/long Select is decided on the host now";
    EXPECT_TRUE(has_input_name(model, ov::npuw::patterns::pre_compute::longrope_cos_input));
    EXPECT_TRUE(has_input_name(model, ov::npuw::patterns::pre_compute::longrope_sin_input));
    EXPECT_FALSE(has_input_name(model, "npuw_longrope_input"));
}

TEST(PreComputeTest, RopeCacheTransformsLongRopeV5Pattern) {
    auto model = make_longrope_v5_model({1.0f, 2.0f}, {4.0f, 5.0f}, {0.5f, 1.0f}, {2.0f});

    ov::npuw::patterns::pre_compute::RopeCache pass(/*max_prompt_len=*/16);
    ASSERT_NO_THROW(pass.run_on_model(model));

    expect_longrope_lut_inputs(model);

    const auto& tables = pass.host_tables();
    EXPECT_EQ(tables.max_len, 16u);
    EXPECT_EQ(tables.rotary_ndims, 4u);  // 2 factors, mirrored
    // short = (factor * multiply) ^ power, long likewise
    EXPECT_EQ(tables.inv_freq_short, (std::vector<float>{0.25f, 4.0f}));
    EXPECT_EQ(tables.inv_freq_long, (std::vector<float>{4.0f, 25.0f}));
}

TEST(PreComputeTest, RopeCacheTransformsLongRopePhiPattern) {
    auto model = make_longrope_phi_model({0.5f, 0.25f}, {0.1f, 0.05f}, /*context_limit=*/4096);

    ov::npuw::patterns::pre_compute::RopeCache pass(/*max_prompt_len=*/16);
    ASSERT_NO_THROW(pass.run_on_model(model));

    expect_longrope_lut_inputs(model);

    const auto& tables = pass.host_tables();
    EXPECT_EQ(tables.max_len, 16u);
    EXPECT_EQ(tables.rotary_ndims, 4u);
    // The old pattern's constants already are the inverse frequencies.
    EXPECT_EQ(tables.inv_freq_short, (std::vector<float>{0.5f, 0.25f}));
    EXPECT_EQ(tables.inv_freq_long, (std::vector<float>{0.1f, 0.05f}));
}

namespace pc = ov::npuw::patterns::pre_compute;

std::shared_ptr<ov::Model> make_longrope_no_broadcast_model(bool v5) {
    return v5 ? make_longrope_v5_model({1.0f, 2.0f}, {4.0f, 5.0f}, {0.5f, 1.0f}, {2.0f}, 1, false)
              : make_longrope_phi_model({0.5f, 0.25f}, {0.1f, 0.05f}, 4096, 1, false);
}

std::shared_ptr<ov::op::v0::Concat> get_longrope_frequency_concat(const std::shared_ptr<ov::Model>& model) {
    return ov::as_type_ptr<ov::op::v0::Concat>(
        model->get_results()[0]->input_value(0).get_node()->input_value(0).get_node_shared_ptr());
}

void set_longrope_transpose_order(const std::shared_ptr<ov::Model>& model,
                                  const ov::element::Type& type,
                                  const std::vector<int64_t>& order) {
    auto concat = get_longrope_frequency_concat(model);
    ASSERT_TRUE(concat);
    auto transpose = ov::as_type_ptr<ov::op::v1::Transpose>(concat->input_value(0).get_node_shared_ptr());
    ASSERT_TRUE(transpose);
    transpose->input(1).replace_source_output(ov::op::v0::Constant::create(type, ov::Shape{3}, order));
    model->validate_nodes_and_infer_types();
}

std::shared_ptr<ov::Model> make_longrope_cache_reference(const std::shared_ptr<ov::Model>& original,
                                                         size_t max_prompt_len,
                                                         size_t rotary_ndims) {
    auto position_ids =
        std::make_shared<ov::op::v0::Parameter>(ov::element::i32, original->get_parameters()[0]->get_partial_shape());
    position_ids->output(0).set_names(original->get_parameters()[0]->output(0).get_names());
    const ov::Shape lut_shape{1, max_prompt_len, rotary_ndims};
    auto cos = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, lut_shape);
    auto sin = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, lut_shape);
    cos->set_friendly_name(pc::longrope_cos_input);
    sin->set_friendly_name(pc::longrope_sin_input);
    cos->output(0).set_names({pc::longrope_cos_input});
    sin->output(0).set_names({pc::longrope_sin_input});
    auto axis = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, {1});
    auto gather_cos = std::make_shared<ov::op::v8::Gather>(cos, position_ids, axis);
    auto gather_sin = std::make_shared<ov::op::v8::Gather>(sin, position_ids, axis);
    auto convert_cos = std::make_shared<ov::op::v0::Convert>(gather_cos, ov::element::f32);
    auto convert_sin = std::make_shared<ov::op::v0::Convert>(gather_sin, ov::element::f32);
    auto squeeze_cos = std::make_shared<ov::op::v0::Squeeze>(convert_cos, axis);
    auto squeeze_sin = std::make_shared<ov::op::v0::Squeeze>(convert_sin, axis);
    auto sin_result = std::make_shared<ov::op::v0::Result>(squeeze_sin);
    auto cos_result = std::make_shared<ov::op::v0::Result>(squeeze_cos);
    sin_result->set_friendly_name(original->get_results()[0]->get_friendly_name());
    cos_result->set_friendly_name(original->get_results()[1]->get_friendly_name());
    return std::make_shared<ov::Model>(ov::ResultVector{sin_result, cos_result},
                                       ov::ParameterVector{position_ids, cos, sin});
}

class LongRopeCacheTest : public TransformationTestsF {
protected:
    void SetUp() override {
        TransformationTestsF::SetUp();
        comparator.enable(FunctionsComparator::CONST_VALUES);
        comparator.enable(FunctionsComparator::ATTRIBUTES);
        pass = manager.register_pass<pc::RopeCache>(16);
        // The cache rewrite does not copy runtime info to the new Gather/Convert/Squeeze nodes.
        disable_rt_info_check();
    }

    void TearDown() override {
        TransformationTestsF::TearDown();
        const auto& tables = pass->host_tables();
        EXPECT_EQ(tables.max_len, expected_tables.max_len);
        EXPECT_EQ(tables.rotary_ndims, expected_tables.rotary_ndims);
        EXPECT_EQ(tables.inv_freq_short, expected_tables.inv_freq_short);
        EXPECT_EQ(tables.inv_freq_long, expected_tables.inv_freq_long);
        if (expected_tables.rotary_ndims != 0) {
            EXPECT_TRUE(has_input_name(model, pc::longrope_cos_input));
            EXPECT_TRUE(has_input_name(model, pc::longrope_sin_input));
            EXPECT_FALSE(has_input_name(model, "npuw_longrope_input"));
        }
    }

    void expect_cache(const std::vector<float>& short_freq, const std::vector<float>& long_freq) {
        expected_tables.max_len = 16;
        expected_tables.rotary_ndims = 2 * short_freq.size();
        expected_tables.inv_freq_short = short_freq;
        expected_tables.inv_freq_long = long_freq;
        model->get_parameters()[0]->output(0).set_names({"position_ids"});
        model_ref = make_longrope_cache_reference(model, expected_tables.max_len, expected_tables.rotary_ndims);
        comparator.enable(FunctionsComparator::TENSOR_NAMES);
        // The existing rewrite replaces Sin/Cos names with new Squeeze names.
        disable_result_friendly_names_check();
    }

    std::shared_ptr<pc::RopeCache> pass;
    pc::LongRopeCosSin expected_tables;
};

TEST_F(LongRopeCacheTest, RopeCacheTransformsLongRopeV5PatternWithoutBroadcastChain) {
    model = make_longrope_v5_model(std::vector<float>(48, 1.0f),
                                   std::vector<float>(48, 4.0f),
                                   std::vector<float>(48, 0.5f),
                                   {2.0f},
                                   /*cond_offset=*/1,
                                   /*with_broadcast=*/false);
    EXPECT_EQ(model->get_output_shape(0), (ov::Shape{1, 4, 96}));
    expect_cache(std::vector<float>(48, 0.25f), std::vector<float>(48, 4.0f));
}

TEST_F(LongRopeCacheTest, RopeCacheTransformsLongRopePhiPatternWithoutBroadcastChain) {
    model = make_longrope_no_broadcast_model(false);
    EXPECT_EQ(model->get_output_shape(0), (ov::Shape{1, 4, 4}));
    expect_cache({0.5f, 0.25f}, {0.1f, 0.05f});
}

class LongRopeCacheVariantTest : public LongRopeCacheTest, public testing::WithParamInterface<bool> {};

TEST_P(LongRopeCacheVariantTest, RopeCacheLeavesLongRopeNonDuplicatingConcatUntouched) {
    model = make_longrope_no_broadcast_model(GetParam());
    auto concat = get_longrope_frequency_concat(model);
    ASSERT_TRUE(concat);
    ASSERT_EQ(concat->input_value(0).get_shape(), (ov::Shape{1, 4, 2}));
    auto zeros = ov::op::v0::Constant::create(ov::element::f32, ov::Shape{1, 4, 2}, std::vector<float>(8, 0.0f));
    concat->input(1).replace_source_output(zeros);
    ASSERT_NO_THROW(model->validate_nodes_and_infer_types());
    EXPECT_FALSE(pc::extract_longrope_context_limit(model).has_value());
}

TEST_P(LongRopeCacheVariantTest, RopeCacheLeavesLongRopeTransposedAWithoutBroadcastUntouched) {
    model = make_longrope_no_broadcast_model(GetParam());
    auto concat = get_longrope_frequency_concat(model);
    ASSERT_TRUE(concat);
    auto transpose = ov::as_type_ptr<ov::op::v1::Transpose>(concat->input_value(0).get_node_shared_ptr());
    ASSERT_TRUE(transpose);
    auto matmul = ov::as_type_ptr<ov::op::v0::MatMul>(transpose->input_value(0).get_node_shared_ptr());
    ASSERT_TRUE(matmul);
    auto pos_unsqueeze =
        ov::as_type_ptr<ov::op::v0::Unsqueeze>(matmul->input_value(1).get_node()->input_value(0).get_node_shared_ptr());
    ASSERT_TRUE(pos_unsqueeze);
    model->get_parameters()[0]->set_partial_shape(ov::Shape{1, 2});
    pos_unsqueeze->input(1).replace_source_output(ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, {2}));
    matmul->set_transpose_a(true);
    ASSERT_NO_THROW(model->validate_nodes_and_infer_types());
    EXPECT_EQ(matmul->get_input_shape(0), (ov::Shape{1, 2, 1}));
    EXPECT_EQ(model->get_output_shape(0), (ov::Shape{1, 1, 2}));
    EXPECT_EQ(model->get_output_shape(1), (ov::Shape{1, 1, 2}));
    EXPECT_FALSE(pc::extract_longrope_context_limit(model).has_value());
}

INSTANTIATE_TEST_SUITE_P(LongRope,
                         LongRopeCacheVariantTest,
                         testing::Bool(),
                         [](const testing::TestParamInfo<bool>& info) {
                             return info.param ? "V5" : "Phi";
                         });

using LongRopeAxisParams = std::tuple<bool, int64_t>;
class LongRopeCacheConcatAxisTest : public LongRopeCacheTest, public testing::WithParamInterface<LongRopeAxisParams> {};

TEST_P(LongRopeCacheConcatAxisTest, RopeCacheLeavesLongRopeWrongConcatAxisUntouched) {
    const auto [v5, axis] = GetParam();
    model = make_longrope_no_broadcast_model(v5);
    auto concat = get_longrope_frequency_concat(model);
    ASSERT_TRUE(concat);
    ASSERT_EQ(concat->input_value(0), concat->input_value(1));
    concat->set_axis(axis);
    ASSERT_NO_THROW(model->validate_nodes_and_infer_types());
    const auto output_shape = axis == 0 ? ov::Shape{2, 4, 2} : ov::Shape{1, 8, 2};
    EXPECT_EQ(model->get_output_shape(0), output_shape);
    EXPECT_EQ(model->get_output_shape(1), output_shape);
    EXPECT_FALSE(pc::extract_longrope_context_limit(model).has_value());
}

INSTANTIATE_TEST_SUITE_P(LongRope,
                         LongRopeCacheConcatAxisTest,
                         testing::Combine(testing::Bool(), testing::Values(0, 1)),
                         [](const testing::TestParamInfo<LongRopeAxisParams>& info) {
                             return std::string(std::get<0>(info.param) ? "V5" : "Phi") + "_Axis" +
                                    std::to_string(std::get<1>(info.param));
                         });

TEST_F(LongRopeCacheTest, RopeCacheTransformsLongRopeV5PositiveLastConcatAxisWithoutBroadcastChain) {
    model = make_longrope_no_broadcast_model(true);
    auto concat = get_longrope_frequency_concat(model);
    ASSERT_TRUE(concat);
    concat->set_axis(2);
    ASSERT_NO_THROW(model->validate_nodes_and_infer_types());
    EXPECT_EQ(pc::extract_longrope_context_limit(model), std::optional<uint64_t>{4u});
    expect_cache({0.25f, 4.0f}, {4.0f, 25.0f});
}

TEST_F(LongRopeCacheTest, RopeCacheTransformsLongRopeV5SingleFrequencyAndQueryWithoutBroadcastChain) {
    model = make_longrope_v5_model({1.0f}, {4.0f}, {0.5f}, {2.0f}, 1, false);
    model->get_parameters()[0]->set_partial_shape(ov::Shape{1, 1});
    ASSERT_NO_THROW(model->validate_nodes_and_infer_types());
    EXPECT_EQ(model->get_output_shape(0), (ov::Shape{1, 1, 2}));
    EXPECT_EQ(pc::extract_longrope_context_limit(model), std::optional<uint64_t>{4u});
    expect_cache({0.25f}, {4.0f});
}

TEST_F(LongRopeCacheTest, RopeCacheTransformsLongRopeV5I32TransposeOrderWithoutBroadcastChain) {
    model = make_longrope_no_broadcast_model(true);
    ASSERT_NO_THROW(set_longrope_transpose_order(model, ov::element::i32, {0, 2, 1}));
    EXPECT_EQ(pc::extract_longrope_context_limit(model), std::optional<uint64_t>{4u});
    expect_cache({0.25f, 4.0f}, {4.0f, 25.0f});
}

using LongRopeSizeParams = std::tuple<bool, size_t>;
class LongRopeCacheTransposeTest : public LongRopeCacheTest, public testing::WithParamInterface<LongRopeSizeParams> {};

TEST_P(LongRopeCacheTransposeTest, RopeCacheLeavesLongRopeIdentityTransposeUntouched) {
    const auto [v5, sequence_length] = GetParam();
    model = make_longrope_no_broadcast_model(v5);
    model->get_parameters()[0]->set_partial_shape(ov::Shape{1, sequence_length});
    ASSERT_NO_THROW(set_longrope_transpose_order(model, ov::element::i64, {0, 1, 2}));
    EXPECT_EQ(model->get_output_shape(0), (ov::Shape{1, 2, 2 * sequence_length}));
    EXPECT_EQ(model->get_output_shape(1), (ov::Shape{1, 2, 2 * sequence_length}));
    EXPECT_FALSE(pc::extract_longrope_context_limit(model).has_value());
}

INSTANTIATE_TEST_SUITE_P(LongRope,
                         LongRopeCacheTransposeTest,
                         testing::Combine(testing::Bool(), testing::Values(4u, 2u)),
                         [](const testing::TestParamInfo<LongRopeSizeParams>& info) {
                             return std::string(std::get<0>(info.param) ? "V5" : "Phi") + "_Sequence" +
                                    std::to_string(std::get<1>(info.param));
                         });

TEST(PreComputeTest, ExtractLongRopeContextLimitWithoutBroadcastChain) {
    namespace pc = ov::npuw::patterns::pre_compute;

    auto v5 = make_longrope_v5_model({1.0f, 2.0f},
                                     {4.0f, 5.0f},
                                     {0.5f, 1.0f},
                                     {2.0f},
                                     /*cond_offset=*/1,
                                     /*with_broadcast=*/false);
    EXPECT_EQ(pc::extract_longrope_context_limit(v5), std::optional<uint64_t>{4u});

    auto phi = make_longrope_phi_model({0.5f, 0.25f},
                                       {0.1f, 0.05f},
                                       /*context_limit=*/4096,
                                       /*cond_offset=*/1,
                                       /*with_broadcast=*/false);
    EXPECT_EQ(pc::extract_longrope_context_limit(phi), std::optional<uint64_t>{4096u});
}

class LongRopeCacheBatchTest : public LongRopeCacheTest, public testing::WithParamInterface<LongRopeSizeParams> {};

TEST_P(LongRopeCacheBatchTest, RopeCacheLeavesLongRopeNonSingletonBatchUntouched) {
    const auto [v5, frequency_count] = GetParam();
    const std::vector<float> short_values(2 * frequency_count, 0.5f);
    const std::vector<float> long_values(2 * frequency_count, 0.1f);
    model = v5 ? make_longrope_v5_model(short_values, long_values, short_values, {-1.0f}, 1, false)
               : make_longrope_phi_model(short_values, long_values, 4096, 1, false);
    const auto ops = model->get_ops();
    for (const auto& op : ops) {
        if (ov::is_type<ov::op::v0::MatMul>(op)) {
            // Bypass both optional Unsqueezes; the constants below already have [2, N, 1] shape.
            auto frequencies = op->input_value(0).get_node()->input_value(0).get_node()->input_value(0);
            op->input(0).replace_source_output(frequencies);
        }
        if (auto constant = ov::as_type_ptr<ov::op::v0::Constant>(op)) {
            if (constant->get_element_type() == ov::element::f32 &&
                constant->get_shape() == ov::Shape{2 * frequency_count}) {
                ov::replace_node(constant,
                                 ov::op::v0::Constant::create(ov::element::f32,
                                                              ov::Shape{2, frequency_count, 1},
                                                              constant->cast_vector<float>()));
            }
        }
    }
    ASSERT_NO_THROW(model->validate_nodes_and_infer_types());
    EXPECT_FALSE(pc::extract_longrope_context_limit(model).has_value());
}

INSTANTIATE_TEST_SUITE_P(LongRope,
                         LongRopeCacheBatchTest,
                         testing::Combine(testing::Bool(), testing::Values(1u, 2u)),
                         [](const testing::TestParamInfo<LongRopeSizeParams>& info) {
                             return std::string(std::get<0>(info.param) ? "V5" : "Phi") + "_Frequencies" +
                                    std::to_string(std::get<1>(info.param));
                         });

TEST(PreComputeTest, ExtractLongRopeContextLimitFromBothPatterns) {
    namespace pc = ov::npuw::patterns::pre_compute;

    auto v5 = make_longrope_v5_model({1.0f, 2.0f}, {4.0f, 5.0f}, {0.5f, 1.0f}, {2.0f});
    EXPECT_EQ(pc::extract_longrope_context_limit(v5), std::optional<uint64_t>{4u});

    auto phi = make_longrope_phi_model({0.5f, 0.25f}, {0.1f, 0.05f}, /*context_limit=*/4096);
    EXPECT_EQ(pc::extract_longrope_context_limit(phi), std::optional<uint64_t>{4096u});

    auto plain = make_rope_model(/*with_concat2=*/true);
    EXPECT_FALSE(pc::extract_longrope_context_limit(plain).has_value());
}

// Both modes live in one tensor, short rows first. Views must be dense and, when the
// long half is absent, both modes must resolve to the same rows.
TEST(PreComputeTest, LongRopeCosSinTableLayout) {
    ov::npuw::patterns::pre_compute::LongRopeCosSin tables;
    tables.max_len = 8;
    tables.rotary_ndims = 4;
    tables.inv_freq_short = {0.5f, 0.25f};
    tables.inv_freq_long = {0.1f, 0.05f};

    tables.has_long = true;
    tables.rebuild_tables();
    ASSERT_TRUE(tables.is_valid());
    EXPECT_EQ(tables.cos.get_shape(), (ov::Shape{1, 16, 4}));
    EXPECT_EQ(tables.sin.get_shape(), (ov::Shape{1, 16, 4}));

    auto short_rows = tables.cos_rows(/*lut_len=*/5, /*is_long=*/false);
    auto long_rows = tables.cos_rows(/*lut_len=*/5, /*is_long=*/true);
    EXPECT_EQ(short_rows.get_shape(), (ov::Shape{1, 5, 4}));
    EXPECT_TRUE(short_rows.is_continuous());
    EXPECT_TRUE(long_rows.is_continuous());
    EXPECT_EQ(short_rows.data<ov::float16>(), tables.cos.data<ov::float16>());
    EXPECT_EQ(long_rows.data<ov::float16>(), tables.cos.data<ov::float16>() + 8 * 4);
    // Row 1 differs between modes because the frequencies do.
    EXPECT_NE(static_cast<float>(short_rows.data<ov::float16>()[4]),
              static_cast<float>(long_rows.data<ov::float16>()[4]));

    // Long half dropped: half the memory, and both modes bind the short rows.
    tables.has_long = false;
    tables.rebuild_tables();
    ASSERT_TRUE(tables.is_valid());
    EXPECT_EQ(tables.cos.get_shape(), (ov::Shape{1, 8, 4}));
    EXPECT_EQ(tables.cos_rows(5, true).data<ov::float16>(), tables.cos_rows(5, false).data<ov::float16>());
}

// The host re-evaluates the mode as max(position_ids) >= context_limit, which only
// matches the graph when the compared sum adds exactly 1. Anything else must be
// refused instead of silently binding the wrong coefficients.
TEST(PreComputeTest, RopeCacheRejectsUnexpectedConditionOffset) {
    namespace pc = ov::npuw::patterns::pre_compute;

    auto v5 = make_longrope_v5_model({1.0f, 2.0f}, {4.0f, 5.0f}, {0.5f, 1.0f}, {2.0f}, /*cond_offset=*/2);
    EXPECT_THROW(pc::extract_longrope_context_limit(v5), ov::AssertFailure);
    EXPECT_THROW(pc::RopeCache(/*max_prompt_len=*/16).run_on_model(v5), ov::AssertFailure);

    auto phi = make_longrope_phi_model({0.5f, 0.25f}, {0.1f, 0.05f}, /*context_limit=*/4096, /*cond_offset=*/0);
    EXPECT_THROW(pc::extract_longrope_context_limit(phi), ov::AssertFailure);
    EXPECT_THROW(pc::RopeCache(/*max_prompt_len=*/16).run_on_model(phi), ov::AssertFailure);
}

// The npuw_lr_cos/npuw_lr_sin inputs of an imported blob are bound to tables that are
// regenerated from the serialized metadata, so a round trip must reproduce them exactly.
TEST(PreComputeTest, LongRopeCosSinSerializationRoundTrip) {
    using ov::npuw::orc::Stream;

    for (bool has_long : {true, false}) {
        ov::npuw::patterns::pre_compute::LongRopeCosSin src;
        src.max_len = 12;
        src.rotary_ndims = 4;
        src.has_long = has_long;
        src.inv_freq_short = {0.5f, 0.25f};
        src.inv_freq_long = {0.1f, 0.05f};
        src.rebuild_tables();
        ASSERT_TRUE(src.is_valid());

        std::stringstream ss;
        auto writer = Stream::writer(ss);
        writer & src;

        ov::npuw::patterns::pre_compute::LongRopeCosSin dst;
        auto reader = Stream::reader(ss);
        reader & dst;

        EXPECT_EQ(dst.max_len, src.max_len);
        EXPECT_EQ(dst.rotary_ndims, src.rotary_ndims);
        EXPECT_EQ(dst.has_long, src.has_long);
        EXPECT_EQ(dst.inv_freq_short, src.inv_freq_short);
        EXPECT_EQ(dst.inv_freq_long, src.inv_freq_long);

        // serialize() rebuilds the tensors on read - they must come back byte-identical.
        ASSERT_TRUE(dst.is_valid()) << "imported tables must be usable without re-running RopeCache";
        ASSERT_EQ(dst.cos.get_shape(), src.cos.get_shape());
        ASSERT_EQ(dst.sin.get_shape(), src.sin.get_shape());
        EXPECT_EQ(std::memcmp(dst.cos.data(), src.cos.data(), src.cos.get_byte_size()), 0);
        EXPECT_EQ(std::memcmp(dst.sin.data(), src.sin.data(), src.sin.get_byte_size()), 0);

        EXPECT_EQ(dst.cos_rows(5, true).get_shape(), (ov::Shape{1, 5, 4}));
        EXPECT_EQ(dst.cos_rows(5, true).data<ov::float16>() == dst.cos_rows(5, false).data<ov::float16>(), !has_long);
    }
}

// A model with no LongRoPE leaves the tables empty; that must survive a round trip too,
// and must not fabricate tensors on import.
TEST(PreComputeTest, LongRopeCosSinSerializationRoundTripEmpty) {
    using ov::npuw::orc::Stream;

    ov::npuw::patterns::pre_compute::LongRopeCosSin src;
    std::stringstream ss;
    auto writer = Stream::writer(ss);
    writer & src;

    ov::npuw::patterns::pre_compute::LongRopeCosSin dst;
    dst.max_len = 7;  // must be overwritten by the read
    auto reader = Stream::reader(ss);
    reader & dst;

    EXPECT_EQ(dst.max_len, 0u);
    EXPECT_EQ(dst.rotary_ndims, 0u);
    EXPECT_FALSE(dst.has_long);
    EXPECT_FALSE(dst.is_valid());
}

TEST(PreComputeTest, RopeCacheThrowsOnMismatchedFactorSizesInLongRopeV5) {
    // multiply has scalar shape {1}: graph is valid by broadcast, but calculate_freq requires exact size match.
    auto model = make_longrope_v5_model({1.0f, 2.0f}, {4.0f, 5.0f}, {1.0f}, {1.0f});
    ov::npuw::patterns::pre_compute::RopeCache pass(/*max_prompt_len=*/16);

    EXPECT_THROW(pass.run_on_model(model), ov::AssertFailure);
}

TEST(PreComputeTest, RopeCacheThrowsOnNonScalarPowerInLongRopeV5) {
    auto model = make_longrope_v5_model({1.0f, 2.0f}, {4.0f, 5.0f}, {1.0f, 2.0f}, {1.0f, 2.0f});
    ov::npuw::patterns::pre_compute::RopeCache pass(/*max_prompt_len=*/16);

    EXPECT_THROW(pass.run_on_model(model), ov::AssertFailure);
}

// Verifies that the merged RopePatternLLama2 correctly detects and removes the
// LLama2-style sin/cos subgraph (with Concat_2 present, duplicate_freqs=true).
TEST(PreComputeTest, RopeCacheTransformsLLama2Pattern) {
    auto model = make_rope_model(/*with_concat2=*/true);

    ov::npuw::patterns::pre_compute::RopeCache pass(/*max_prompt_len=*/16);
    ASSERT_NO_THROW(pass.run_on_model(model));

    const auto& ops = model->get_ops();
    const auto sin_count = std::count_if(ops.begin(), ops.end(), [](const auto& op) {
        return ov::is_type<ov::op::v0::Sin>(op);
    });
    const auto cos_count = std::count_if(ops.begin(), ops.end(), [](const auto& op) {
        return ov::is_type<ov::op::v0::Cos>(op);
    });

    EXPECT_EQ(sin_count, 0) << "Sin should be replaced by Gather from the duplicated LUT";
    EXPECT_EQ(cos_count, 0) << "Cos should be replaced by Gather from the duplicated LUT";
}

// Verifies that the merged RopePatternLLama2 correctly detects and removes the
// GPT-style sin/cos subgraph (Concat_2 absent, duplicate_freqs=false).
TEST(PreComputeTest, RopeCacheTransformsGPTPattern) {
    auto model = make_rope_model(/*with_concat2=*/false);

    ov::npuw::patterns::pre_compute::RopeCache pass(/*max_prompt_len=*/16);
    ASSERT_NO_THROW(pass.run_on_model(model));

    const auto& ops = model->get_ops();
    const auto sin_count = std::count_if(ops.begin(), ops.end(), [](const auto& op) {
        return ov::is_type<ov::op::v0::Sin>(op);
    });
    const auto cos_count = std::count_if(ops.begin(), ops.end(), [](const auto& op) {
        return ov::is_type<ov::op::v0::Cos>(op);
    });

    EXPECT_EQ(sin_count, 0) << "Sin should be replaced by Gather from the non-duplicated LUT";
    EXPECT_EQ(cos_count, 0) << "Cos should be replaced by Gather from the non-duplicated LUT";
}

// A model can contain more than one independent RoPE block (e.g. Gemma 4's hybrid attention)
// and every block must be cached, not just the first.
TEST(PreComputeTest, RopeCacheTransformsTwoIndependentRopeBlocks) {
    auto model = make_multi_rope_model({{0.5f, 0.1f}, {0.2f, 0.05f}});

    ov::npuw::patterns::pre_compute::RopeCache pass(/*max_prompt_len=*/16);
    ASSERT_NO_THROW(pass.run_on_model(model));

    EXPECT_EQ(count_ops_of_type_sin_cos(model), 0u) << "both RoPE blocks must be cached, not just the first";

    const auto& ops = model->get_ops();
    const auto gather_count = std::count_if(ops.begin(), ops.end(), [](const auto& op) {
        return ov::is_type<ov::op::v8::Gather>(op);
    });
    EXPECT_EQ(gather_count, 4u) << "one Gather for cos and one for sin, per block";

    // Each block must get its own cache, not accidentally share one.
    std::vector<const ov::op::v0::Constant*> caches;
    for (const auto& op : ops) {
        if (auto gather_op = ov::as_type_ptr<ov::op::v8::Gather>(op)) {
            if (auto cache = ov::as_type_ptr<ov::op::v0::Constant>(gather_op->input_value(0).get_node_shared_ptr())) {
                caches.push_back(cache.get());
            }
        }
    }
    ASSERT_EQ(caches.size(), 4u);
    for (size_t i = 0; i < caches.size(); ++i) {
        for (size_t j = i + 1; j < caches.size(); ++j) {
            EXPECT_NE(std::memcmp(caches[i]->get_data_ptr(), caches[j]->get_data_ptr(), caches[i]->get_byte_size()), 0)
                << "cache constants " << i << " and " << j << " are unexpectedly identical";
        }
    }
}

// Reads the f16 cache row a Result's Squeeze->Convert->Gather chain was bound to.
std::vector<float> read_cache_row(const ov::Output<ov::Node>& result_input, size_t row) {
    auto convert = result_input.get_node()->input_value(0).get_node();
    auto gather = convert->input_value(0).get_node();
    auto cache = ov::as_type_ptr<ov::op::v0::Constant>(gather->input_value(0).get_node_shared_ptr());
    OPENVINO_ASSERT(cache, "Expected a cache Constant feeding the Gather");

    const auto* data = cache->get_data_ptr<ov::float16>();
    const auto rotary_ndims = cache->get_shape().back();
    std::vector<float> values(rotary_ndims);
    for (size_t k = 0; k < rotary_ndims; ++k) {
        values[k] = static_cast<float>(data[row * rotary_ndims + k]);
    }
    return values;
}

// Match pairing must key off the shared input node, not vector index - MultiMatcher doesn't
// guarantee a block's Sin and Cos land at the same index. Results are ordered here so naive
// index-based pairing would cross-wire the two blocks' caches.
TEST(PreComputeTest, RopeCacheTransformsTwoIndependentRopeBlocksWithScrambledMatchOrder) {
    auto model = make_multi_rope_model({{0.5f, 0.1f}, {0.2f, 0.05f}},
                                       /*result_order=*/{{0, false}, {1, false}, {1, true}, {0, true}});

    ov::npuw::patterns::pre_compute::RopeCache pass(/*max_prompt_len=*/16);
    ASSERT_NO_THROW(pass.run_on_model(model));

    const auto& results = model->get_results();
    auto sin0 = read_cache_row(results[0]->input_value(0), /*row=*/1);
    auto sin1 = read_cache_row(results[1]->input_value(0), /*row=*/1);
    auto cos1 = read_cache_row(results[2]->input_value(0), /*row=*/1);
    auto cos0 = read_cache_row(results[3]->input_value(0), /*row=*/1);

    for (size_t k = 0; k < sin0.size(); ++k) {
        EXPECT_NEAR(cos0[k] * cos0[k] + sin0[k] * sin0[k], 1.0f, 0.01f) << "block 0 cos/sin mismatch at " << k;
        EXPECT_NEAR(cos1[k] * cos1[k] + sin1[k] * sin1[k], 1.0f, 0.01f) << "block 1 cos/sin mismatch at " << k;
    }
}

// A pattern match without its sin/cos counterpart (e.g. an unrelated Cos-only computation that
// coincidentally matches the same antecedent chain) must be left in place, not rejected.
TEST(PreComputeTest, RopeCacheLeavesUnpairedCosUntouched) {
    auto model = make_rope_model_with_lone_cos({0.5f, 0.1f}, {0.2f, 0.05f});

    ov::npuw::patterns::pre_compute::RopeCache pass(/*max_prompt_len=*/16);
    ASSERT_NO_THROW(pass.run_on_model(model));

    const auto& ops = model->get_ops();
    EXPECT_EQ(std::count_if(ops.begin(),
                            ops.end(),
                            [](const auto& op) {
                                return ov::is_type<ov::op::v0::Sin>(op);
                            }),
              0)
        << "the paired Sin must be cached away";
    EXPECT_EQ(std::count_if(ops.begin(),
                            ops.end(),
                            [](const auto& op) {
                                return ov::is_type<ov::op::v0::Cos>(op);
                            }),
              1)
        << "only the lone, unpaired Cos should remain";
}

// Qwen3-style export: inv_freq is already a pre-broadcast Constant, no live Broadcast
// node and no ShapeOf->Gather->Concat chain feeding it. The matcher must still fire via
// the optional Broadcast's fallback to matching inv_freq's output directly.
TEST(PreComputeTest, RopeCacheTransformsLLama2PatternWithoutBroadcastChain) {
    auto model = make_rope_model_no_broadcast(/*with_concat2=*/true);

    ov::npuw::patterns::pre_compute::RopeCache pass(/*max_prompt_len=*/16);
    ASSERT_NO_THROW(pass.run_on_model(model));

    EXPECT_EQ(count_ops_of_type_sin_cos(model), 0u) << "Sin/Cos should be replaced by Gather from the LUT";
}

TEST(PreComputeTest, RopeCacheTransformsGPTPatternWithoutBroadcastChain) {
    auto model = make_rope_model_no_broadcast(/*with_concat2=*/false);

    ov::npuw::patterns::pre_compute::RopeCache pass(/*max_prompt_len=*/16);
    ASSERT_NO_THROW(pass.run_on_model(model));

    EXPECT_EQ(count_ops_of_type_sin_cos(model), 0u) << "Sin/Cos should be replaced by Gather from the LUT";
}

// When the Broadcast is bypassed, inv_freq must still have only the supported singleton
// batch dim - anything else (e.g. a real batch dim) would be silently flattened into the
// frequency axis by makeCosSinCache, corrupting the LUT's shape. The matcher must leave
// Sin/Cos untouched rather than misfire on such a constant.
TEST(PreComputeTest, RopeCacheLeavesNonSingletonBatchInvFreqUntouched) {
    auto model = make_rope_model_no_broadcast_extra_batch_dim();

    ov::npuw::patterns::pre_compute::RopeCache pass(/*max_prompt_len=*/16);
    ASSERT_NO_THROW(pass.run_on_model(model));

    EXPECT_EQ(count_ops_of_type_sin_cos(model), 2u) << "Sin/Cos must stay as-is, not be wrongly replaced by the LUT";
}

// A Concat following Transpose whose 2nd input isn't the same tensor (e.g. zero-padding for
// partial-rotary models) must not be mistaken for freq duplication - the LUT's second half
// would otherwise be wrong. The matcher must leave Sin/Cos untouched rather than misfire.
TEST(PreComputeTest, RopeCacheLeavesNonDuplicatingConcatUntouched) {
    auto model = make_rope_model_non_duplicating_concat();

    ov::npuw::patterns::pre_compute::RopeCache pass(/*max_prompt_len=*/16);
    ASSERT_NO_THROW(pass.run_on_model(model));

    EXPECT_EQ(count_ops_of_type_sin_cos(model), 2u) << "Sin/Cos must stay as-is, not be wrongly replaced by the LUT";
}

}  // namespace