Skip to content

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

[GPU] Generalize Sin/Cos angle precision handling to fix LTX-Video accuracy (#39308)

Paul Youngsoo Ahne2cd53117130
diff --git a/src/plugins/intel_gpu/src/plugin/transformations/increase_position_ids_precision.cpp b/src/plugins/intel_gpu/src/plugin/transformations/increase_position_ids_precision.cpp
index 2dbce80e40e..549c2242500 100644
--- a/src/plugins/intel_gpu/src/plugin/transformations/increase_position_ids_precision.cpp
+++ b/src/plugins/intel_gpu/src/plugin/transformations/increase_position_ids_precision.cpp
@@ -4,15 +4,23 @@
#include "increase_position_ids_precision.hpp"
+#include <algorithm>
+#include <cstddef>
+#include <map>
#include <set>
+#include <utility>
+#include <vector>
#include "intel_gpu/op/gemm.hpp"
+#include "intel_gpu/runtime/debug_configuration.hpp"
#include "openvino/core/graph_util.hpp"
#include "openvino/core/rt_info.hpp"
+#include "openvino/core/validation_util.hpp"
#include "openvino/op/add.hpp"
#include "openvino/op/broadcast.hpp"
#include "openvino/op/concat.hpp"
#include "openvino/op/constant.hpp"
+#include "openvino/op/convert.hpp"
#include "openvino/op/cos.hpp"
#include "openvino/op/gather.hpp"
#include "openvino/op/gather_nd.hpp"
@@ -30,19 +38,67 @@
#include "openvino/op/swish.hpp"
#include "openvino/op/transpose.hpp"
#include "openvino/op/unsqueeze.hpp"
+#include "openvino/op/util/multi_subgraph_base.hpp"
+#include "openvino/op/util/variable_extension.hpp"
#include "openvino/op/variadic_split.hpp"
+#include "openvino/pass/manager.hpp"
#include "openvino/pass/pattern/op/optional.hpp"
#include "openvino/pass/pattern/op/or.hpp"
#include "openvino/pass/pattern/op/wrap_type.hpp"
#include "ov_ops/rms.hpp"
#include "ov_ops/rotary_positional_embeddings.hpp"
#include "transformations/rt_info/disable_precision_conversion.hpp"
-#include "transformations/symbolic_transformations/symbolic_optimizations.hpp"
#include "transformations/utils/utils.hpp"
#include "utils.hpp"
namespace ov::intel_gpu {
+CollectSinCosConstantsForPrecisionPreservation::CollectSinCosConstantsForPrecisionPreservation(
+ const std::shared_ptr<ConstantSet>& constants)
+ : m_constants(constants) {
+ OPENVINO_ASSERT(m_constants, "CollectSinCosConstantsForPrecisionPreservation requires a shared Constant set");
+}
+
+bool CollectSinCosConstantsForPrecisionPreservation::run_on_model(const std::shared_ptr<ov::Model>& model) {
+ m_constants->clear();
+ std::unordered_set<const ov::Node*> visited;
+ ov::OutputVector pending;
+ for (const auto& node : model->get_ordered_ops()) {
+ if (ov::is_type_any_of<ov::op::v0::Sin, ov::op::v0::Cos>(node)) {
+ pending.push_back(node->input_value(0));
+ }
+ }
+
+ while (!pending.empty()) {
+ const auto output = pending.back();
+ pending.pop_back();
+ if (!output.get_element_type().is_real()) {
+ continue;
+ }
+ const auto node = output.get_node_shared_ptr();
+ if (!visited.insert(node.get()).second) {
+ continue;
+ }
+ if (ov::is_type<ov::op::v0::Constant>(node)) {
+ if (output.get_element_type() == ov::element::f32) {
+ m_constants->insert(node.get());
+ }
+ continue;
+ }
+
+ // Follow floating-point dependencies without an op allowlist, including through MatMul.
+ // Integer/bool inputs (e.g. shapes, axes and indices) end the path even if derived from floats.
+ // Only outer-graph input edges are followed; subgraph bodies are not traversed.
+ for (const auto& input : node->input_values()) {
+ if (input.get_element_type().is_real()) {
+ pending.push_back(input);
+ }
+ }
+ }
+
+ return false;
+}
+
IncreasePositionIdsPrecisionForRoPE::IncreasePositionIdsPrecisionForRoPE() {
using namespace ov::pass::pattern;
using ov::pass::pattern::op::Or;
@@ -116,7 +172,7 @@ IncreasePositionIdsPrecisionForRoPE::IncreasePositionIdsPrecisionForRoPE() {
insert_converts_after_if_needed(sin_node, rope_sin_et, output_idx);
}
}
- return true;
+ return is_changed;
};
auto m = std::make_shared<ov::pass::pattern::Matcher>(rope, "IncreasePositionIdsPrecisionForRoPE");
@@ -323,96 +379,305 @@ IncreasePositionIdsPrecisionForQwen3VL::IncreasePositionIdsPrecisionForQwen3VL()
this->register_matcher(m, callback);
}
-IncreasePositionIdsPrecisionForLtxVideo::IncreasePositionIdsPrecisionForLtxVideo() {
- using namespace ov::pass::pattern;
- using ov::pass::pattern::op::Or;
+namespace {
- // LTX-Video RoPE position encoding pattern (anchored on fused RoPE).
- // Handles two topology variants sharing the same upstream path.
+// TODO: Reassess the depth limit across other models when generalizing precision handling.
+constexpr size_t max_sincos_angle_depth = 50;
+
+// Rebuild the floating-point angle path shared by Sin/Cos in FP32.
+// Promoting only Sin/Cos inputs cannot recover FP16 rounding that occurred upstream.
+//
+// Phase 1: inspect floating-point dependencies, leaving integer/bool paths unchanged.
+// * Check rewrite eligibility and the depth limit before reconstruction.
+// Phase 2: prepare the FP32 path, reusing preserved FP32 Constants and bypassing floating downcasts.
+// * Enter FP32 at integer-to-float Converts or FP16 Parameters; lost leaf precision cannot be recovered.
+// Phase 3: prepare both Sin/Cos replacements before reconnecting either output.
+// * Restore their original output types for downstream users.
+bool increase_sincos_angle_precision(const std::shared_ptr<ov::Node>& sin, const std::shared_ptr<ov::Node>& cos) {
+ // Phase 1: inspect the upstream floating-point paths and check rewrite eligibility.
+ const ov::OutputVector angle_inputs{sin->input_value(0), cos->input_value(0)};
+
+ // Output keys preserve ports and deduplicate shared paths; only floating-point input ports are recorded.
+ std::map<ov::Output<ov::Node>, std::vector<size_t>> floating_input_ports;
+ bool has_required_arithmetic = false;
+ bool has_fp16_in_angle_path = false;
+
+ // Stack entry: (value, dependencies_processed); record each value after its dependencies.
+ std::vector<std::pair<ov::Output<ov::Node>, bool>> traversal_stack;
+ ov::OutputVector dependency_order;
+ std::map<ov::Output<ov::Node>, size_t> depths;
+
+ for (const auto& input_value : angle_inputs) {
+ traversal_stack.emplace_back(input_value, false);
+ }
+
+ // Iterative DFS avoids recursion limits and produces dependency-first reconstruction order.
+ // Example: A -> B -> Sin, A -> C -> Cos; the actual matcher requires a shared input.
+ // Stack top is left; F = inspect, T = record after dependencies.
//
- // model1 (original):
- // Multiply → Add(Constant) → Transpose → Reshape
- // → Sin → Transpose → Unsqueeze → Broadcast → GatherND → Transpose → Concat_sin
- // → Cos → Transpose → Unsqueeze → Broadcast → GatherND → Transpose → Concat_cos
- // → RoPE(x, Concat_cos, Concat_sin)
+ // Action | Stack (top first) | dependency_order
+ // -----------------|-------------------------|-----------------
+ // Push B, C | (C,F), (B,F) | []
+ // Inspect C | (A,F), (C,T), (B,F) | []
+ // Inspect A | (A,T), (C,T), (B,F) | []
+ // Record A | (C,T), (B,F) | [A]
+ // Record C | (B,F) | [A, C]
+ // Inspect B | (A,F), (B,T) | [A, C]
+ // Skip visited A | (B,T) | [A, C]
+ // Record B | [] | [A, C, B]
//
- // model2 (new topology):
- // Multiply → Add(Constant) → Transpose → Reshape
- // → Sin → Gather(Sin, Const, Const) → Concat(Broadcast, Gather) [sin_concat]
- // → Cos → Gather(Cos, Const, Const) → Concat(Broadcast, Gather) [cos_concat]
- // → RoPE(x, Concat_cos, Concat_sin)
-
- // Upstream: Multiply → Add(Constant) → Transpose → Reshape (same for both models)
- auto mul = wrap_type<ov::op::v1::Multiply>({any_input(), any_input()});
- auto add_constant = wrap_type<ov::op::v0::Constant>();
- auto add = wrap_type<ov::op::v1::Add>({mul, add_constant});
- auto transpose_up = wrap_type<ov::op::v1::Transpose>({add, any_input()});
- auto reshape = wrap_type<ov::op::v1::Reshape>({transpose_up, any_input()});
-
- // Sin and Cos nodes (shared between both model variants)
- auto sin = wrap_type<ov::op::v0::Sin>({reshape});
- auto cos = wrap_type<ov::op::v0::Cos>({reshape});
-
- // model1 sin path: Sin → Transpose → Unsqueeze → Broadcast → GatherND → Transpose → Concat
- auto sin_transpose = wrap_type<ov::op::v1::Transpose>({sin, any_input()});
- auto sin_unsqueeze = wrap_type<ov::op::v0::Unsqueeze>({sin_transpose, any_input()});
- auto sin_broadcast = wrap_type<ov::op::v3::Broadcast>({sin_unsqueeze, any_input()});
- auto sin_gathernd = wrap_type<ov::op::v8::GatherND>({sin_broadcast, any_input()});
- auto sin_transpose2 = wrap_type<ov::op::v1::Transpose>({sin_gathernd, any_input()});
- auto sin_concat_m1 = wrap_type<ov::op::v0::Concat>({any_input(), sin_transpose2});
-
- // model2 sin path: Sin → Gather → Concat
- auto sin_gather_m2 = wrap_type<ov::op::v8::Gather>({sin, any_input(), any_input()});
- auto sin_concat_m2 = wrap_type<ov::op::v0::Concat>({any_input(), sin_gather_m2});
-
- auto sin_concat = std::make_shared<Or>(OutputVector{sin_concat_m1, sin_concat_m2});
-
- // model1 cos path: Cos → Transpose → Unsqueeze → Broadcast → GatherND → Transpose → Concat
- auto cos_transpose = wrap_type<ov::op::v1::Transpose>({cos, any_input()});
- auto cos_unsqueeze = wrap_type<ov::op::v0::Unsqueeze>({cos_transpose, any_input()});
- auto cos_broadcast = wrap_type<ov::op::v3::Broadcast>({cos_unsqueeze, any_input()});
- auto cos_gathernd = wrap_type<ov::op::v8::GatherND>({cos_broadcast, any_input()});
- auto cos_transpose2 = wrap_type<ov::op::v1::Transpose>({cos_gathernd, any_input()});
- auto cos_concat_m1 = wrap_type<ov::op::v0::Concat>({any_input(), cos_transpose2});
-
- // model2 cos path: Cos → Gather → Concat
- auto cos_gather_m2 = wrap_type<ov::op::v8::Gather>({cos, any_input(), any_input()});
- auto cos_concat_m2 = wrap_type<ov::op::v0::Concat>({any_input(), cos_gather_m2});
-
- auto cos_concat = std::make_shared<Or>(OutputVector{cos_concat_m1, cos_concat_m2});
-
- // RoPE: input 0 = x, input 1 = cos_concat, input 2 = sin_concat
- auto rope = wrap_type<ov::op::internal::RoPE>({any_input(), cos_concat, sin_concat}, [](const ov::Output<ov::Node>& output) {
- auto node = ov::as_type_ptr<ov::op::internal::RoPE>(output.get_node_shared_ptr());
- return node && node->get_config().is_ltx_video;
- });
+ // Dependencies precede consumers; leaves from separate branches need not all come first.
+ while (!traversal_stack.empty()) {
+ const auto [input_value, dependencies_processed] = traversal_stack.back();
+ traversal_stack.pop_back();
+
+ if (dependencies_processed) {
+ // Input depths are ready here; leaves have depth 0 and shared paths use their longest dependency.
+ size_t depth = 0;
+ for (const auto port : floating_input_ports.at(input_value)) {
+ const auto input_depth = depths.at(input_value.get_node()->input_value(port));
+ OPENVINO_ASSERT(input_depth < dependency_order.size(), "Invalid Sin/Cos angle depth");
+ depth = std::max(depth, input_depth + 1);
+ }
+ depths.emplace(input_value, depth);
+ dependency_order.push_back(input_value);
+ continue;
+ }
+ if (floating_input_ports.count(input_value)) {
+ continue;
+ }
- ov::matcher_pass_callback callback = [=](ov::pass::pattern::Matcher& m) {
- const auto& pattern_map = m.get_pattern_value_map();
+ const auto node = input_value.get_node_shared_ptr();
- auto mul_node = ov::as_type_ptr<ov::op::v1::Multiply>(pattern_map.at(mul).get_node_shared_ptr());
- auto constant_node = ov::as_type_ptr<ov::op::v0::Constant>(pattern_map.at(add_constant).get_node_shared_ptr());
- auto cos_node = ov::as_type_ptr<ov::op::v0::Cos>(pattern_map.at(cos).get_node_shared_ptr());
- auto sin_node = ov::as_type_ptr<ov::op::v0::Sin>(pattern_map.at(sin).get_node_shared_ptr());
+ // This eligibility check is not a traversal allowlist or proof that the path only computes angles.
+ has_required_arithmetic |= ov::is_type_any_of<ov::op::v1::Add,
+ ov::op::v1::Multiply,
+ ov::op::v0::MatMul,
+ ov::intel_gpu::op::Gemm>(node);
- const auto desired_et = ov::element::f32;
- const auto original_et = mul_node->get_output_element_type(0);
- if (original_et == desired_et) {
+ const auto type = input_value.get_element_type();
+ has_fp16_in_angle_path |= type == ov::element::f16;
+
+ // Changing outer inputs alone cannot safely rebuild bodies or state/control dependencies.
+ if ((type != ov::element::f16 && type != ov::element::f32) ||
+ ov::is_type<ov::op::util::MultiSubGraphOp>(node) ||
+ std::dynamic_pointer_cast<ov::op::util::VariableExtension>(node) ||
+ !node->get_control_dependencies().empty()) {
+ GPU_DEBUG_LOG << "IncreasePositionIdsPrecisionForLtxVideo: unsupported angle output " << input_value
+ << "; leaving Sin/Cos unchanged" << std::endl;
return false;
}
- size_t input_idx = 0;
- bool is_changed = insert_converts_before_if_needed(mul_node, desired_et, input_idx);
- if (is_changed) {
- insert_converts_after_if_needed(constant_node, desired_et, input_idx);
- size_t output_idx = 0;
- insert_converts_after_if_needed(cos_node, original_et, output_idx);
- insert_converts_after_if_needed(sin_node, original_et, output_idx);
+ std::vector<size_t> ports;
+ for (size_t i = 0; i < node->get_input_size(); ++i) {
+ if (node->get_input_element_type(i).is_real()) {
+ ports.push_back(i);
+ }
}
- return true;
+
+ const bool is_leaf = ov::is_type_any_of<ov::op::v0::Constant, ov::op::v0::Parameter>(node);
+ const bool is_convert = ov::is_type<ov::op::v0::Convert>(node);
+
+ // Only an existing integer-to-float Convert may enter from an integer value path.
+ if ((!is_leaf && !is_convert && ports.empty()) ||
+ (is_convert && ports.empty() && !node->get_input_element_type(0).is_integral_number())) {
+ GPU_DEBUG_LOG << "IncreasePositionIdsPrecisionForLtxVideo: unsupported angle source " << input_value
+ << "; leaving Sin/Cos unchanged" << std::endl;
+ return false;
+ }
+
+ floating_input_ports.emplace(input_value, ports);
+ traversal_stack.emplace_back(input_value, true);
+ for (const auto port : ports) {
+ traversal_stack.emplace_back(input_value.get_node()->input_value(port), false);
+ }
+ }
+
+ if (!has_required_arithmetic) {
+ GPU_DEBUG_LOG << "IncreasePositionIdsPrecisionForLtxVideo: no angle arithmetic; leaving Sin/Cos unchanged"
+ << std::endl;
+ return false;
+ }
+
+ if (!has_fp16_in_angle_path) {
+ return false;
+ }
+
+ const auto max_depth = std::max(depths.at(angle_inputs[0]), depths.at(angle_inputs[1]));
+ if (max_depth > max_sincos_angle_depth) {
+ GPU_DEBUG_INFO << "[Warning] Skipping Sin/Cos FP32 precision rewrite: sin=" << sin->get_friendly_name()
+ << ",cos=" << cos->get_friendly_name()
+ << ",max_depth=" << max_depth << ",limit=" << max_sincos_angle_depth
+ << ". Retaining the original precision may affect accuracy." << std::endl;
+ return false;
+ }
+
+ // Phase 2: prepare the FP32 path in dependency-first order without changing live edges.
+ const auto copy_info = [](const std::shared_ptr<ov::Node>& source, const std::shared_ptr<ov::Node>& replacement) {
+ ov::copy_runtime_info(source, replacement);
+ replacement->set_friendly_name(source->get_friendly_name() + "/fp32_" + replacement->get_name());
};
- auto m = std::make_shared<ov::pass::pattern::Matcher>(rope, "IncreasePositionIdsPrecisionForLtxVideo");
+ // Map each original value to its counterpart in the FP32 path, including reused values.
+ // Example: A -> B -> Sin.
+ // 1. Prepare A's FP32 counterpart and record A -> A_fp32.
+ // 2. Look up A_fp32 when rebuilding B and use it as B's input.
+ // 3. Record B -> B_fp32, then use B_fp32 as the new Sin input.
+ // Shared values are prepared once; existing FP32 values can map to themselves.
+ // This prepares the replacement path without rewiring the original graph.
+ std::map<ov::Output<ov::Node>, ov::Output<ov::Node>> fp32_path_map;
+
+ for (const auto& original_value : dependency_order) {
+ if (fp32_path_map.count(original_value)) {
+ continue;
+ }
+
+ const auto original_node = original_value.get_node_shared_ptr();
+ const auto& original_floating_input_ports = floating_input_ports.at(original_value);
+
+ // Record original_value -> FP32 counterpart in fp32_path_map.
+ //
+ // Producer / condition | FP32 counterpart
+ // -----------------------------------|--------------------------
+ // Constant/Parameter (f32) | Reuse
+ // Constant (f16) | Fold its Convert(f32)
+ // Parameter (f16) | Convert(f32)
+ // Convert (Parameter(f16) -> f32) | Reuse
+ // Convert (other floating input) | Input's FP32 counterpart
+ // Convert (integer -> f32) | Reuse
+ // Convert (integer -> f16) | Convert integer to f32
+ if (ov::is_type_any_of<ov::op::v0::Constant, ov::op::v0::Parameter>(original_node)) {
+ if (original_value.get_element_type() == ov::element::f32) {
+ fp32_path_map.emplace(original_value, original_value);
+ } else {
+ std::shared_ptr<ov::Node> promoted = std::make_shared<ov::op::v0::Convert>(original_value, ov::element::f32);
+ if (ov::is_type<ov::op::v0::Constant>(original_node)) {
+ promoted = ov::util::get_constant_from_source(promoted);
+ OPENVINO_ASSERT(promoted, "Could not promote LTX angle Constant to FP32");
+ }
+
+ copy_info(original_node, promoted);
+ fp32_path_map.emplace(original_value, promoted->output(0));
+ }
+ } else if (ov::is_type<ov::op::v0::Convert>(original_node)) {
+ if (!original_floating_input_ports.empty()) {
+ const auto input = original_node->input_value(0);
+ if (original_value.get_element_type() == ov::element::f32 && input.get_element_type() == ov::element::f16 &&
+ ov::is_type<ov::op::v0::Parameter>(input.get_node())) {
+ // This is an irreducible input boundary, not recoverable FP16 arithmetic.
+ fp32_path_map.emplace(original_value, original_value);
+ } else {
+ fp32_path_map.emplace(original_value, fp32_path_map.at(input));
+ }
+ } else if (original_value.get_element_type() == ov::element::f32) {
+ fp32_path_map.emplace(original_value, original_value);
+ } else {
+ // Keep coordinate generation integer and enter FP32 at the existing Convert boundary.
+ auto converted = std::make_shared<ov::op::v0::Convert>(original_node->input_value(0), ov::element::f32);
+ copy_info(original_node, converted);
+ fp32_path_map.emplace(original_value, converted->output(0));
+ }
+ } else {
+ auto inputs = original_node->input_values();
+ for (const auto port : original_floating_input_ports) {
+ inputs[port] = fp32_path_map.at(inputs[port]);
+ }
+
+ if (original_value.get_element_type() == ov::element::f32 && inputs == original_node->input_values()) {
+ for (size_t i = 0; i < original_node->get_output_size(); ++i) {
+ fp32_path_map.emplace(original_node->output(i), original_node->output(i));
+ }
+ } else {
+ // Example: original A(FP32) -> Convert(FP16) -> C; new path A(FP32) -> C_fp32.
+ // Clone C with remapped FP32 inputs, leaving the original node and its edges unchanged.
+ const auto rebuilt = original_node->clone_with_new_inputs(inputs);
+ copy_info(original_node, rebuilt);
+
+ // Verify every sibling before recording any output of this shared clone.
+ for (size_t i = 0; i < original_node->get_output_size(); ++i) {
+ const auto expected = original_node->get_output_element_type(i).is_real()
+ ? ov::element::f32
+ : original_node->get_output_element_type(i);
+ if (rebuilt->get_output_element_type(i) != expected) {
+ GPU_DEBUG_LOG << "IncreasePositionIdsPrecisionForLtxVideo: incompatible rebuilt output "
+ << rebuilt->output(i) << "; leaving Sin/Cos unchanged" << std::endl;
+ return false;
+ }
+ }
+
+ for (size_t i = 0; i < original_node->get_output_size(); ++i) {
+ fp32_path_map.emplace(original_node->output(i), rebuilt->output(i));
+ }
+ }
+ }
+ }
+
+ if (fp32_path_map.at(angle_inputs[0]) == angle_inputs[0] &&
+ fp32_path_map.at(angle_inputs[1]) == angle_inputs[1]) {
+ return false;
+ }
+
+ // Phase 3: prepare both Sin/Cos replacements before reconnecting either output.
+ // Unrelated angle users keep their original edges.
+ ov::NodeVector replacement_nodes;
+ for (const auto& node : {sin, cos}) {
+ auto rebuilt = node->clone_with_new_inputs({fp32_path_map.at(node->input_value(0))});
+ copy_info(node, rebuilt);
+
+ if (node->get_output_element_type(0) != ov::element::f32) {
+ // Restore precision after Sin/Cos so downstream table and Concat inputs keep matching types.
+ auto boundary = std::make_shared<ov::op::v0::Convert>(rebuilt, node->get_output_element_type(0));
+ ov::copy_runtime_info(node, boundary);
+ rebuilt = boundary;
+ }
+
+ rebuilt->set_friendly_name(node->get_friendly_name());
+ replacement_nodes.push_back(rebuilt);
+ }
+
+ ov::replace_node(sin, replacement_nodes[0]);
+ ov::replace_node(cos, replacement_nodes[1]);
+ return true;
+}
+
+} // namespace
+
+IncreasePositionIdsPrecisionForLtxVideo::IncreasePositionIdsPrecisionForLtxVideo() {
+ using namespace ov::pass::pattern;
+ // Sin owns the rewrite; Cos is discovered from the exact same angle output.
+ auto sin = wrap_type<ov::op::v0::Sin>({any_input()});
+
+ ov::matcher_pass_callback callback = [=](ov::pass::pattern::Matcher& m) {
+ const auto sin_node = ov::as_type_ptr<ov::op::v0::Sin>(m.get_match_root());
+ std::shared_ptr<ov::Node> cos_node;
+ size_t sin_count = 0;
+ size_t cos_count = 0;
+ // TODO: Consider Sin/Cos branches with intervening nodes when generalizing precision handling.
+ // In the models checked so far, Sin and Cos directly share the same input.
+ // However, future models may have nodes between the branch point and Sin/Cos.
+ // Consider these cases when generalizing precision handling.
+ for (const auto& input : sin_node->input_value(0).get_target_inputs()) {
+ const auto consumer = input.get_node()->shared_from_this();
+ if (ov::is_type<ov::op::v0::Sin>(consumer)) {
+ ++sin_count;
+ } else if (ov::is_type<ov::op::v0::Cos>(consumer)) {
+ ++cos_count;
+ cos_node = consumer;
+ }
+ }
+ if (sin_count != 1 || cos_count != 1) {
+ GPU_DEBUG_LOG << "IncreasePositionIdsPrecisionForLtxVideo: missing or ambiguous Sin/Cos pair at "
+ << sin_node->input_value(0) << "; leaving graph unchanged" << std::endl;
+ return false;
+ }
+ // With no RoPE requirement, opt-out is evaluated on both actual trigonometric roots.
+ if (transformation_callback(sin_node) || transformation_callback(cos_node)) {
+ return false;
+ }
+ return increase_sincos_angle_precision(sin_node, cos_node);
+ };
+
+ auto m = std::make_shared<ov::pass::pattern::Matcher>(sin, "IncreasePositionIdsPrecisionForLtxVideo");
this->register_matcher(m, callback);
}
@@ -487,11 +752,11 @@ IncreasePositionIdsPrecisionForGPTOSS::IncreasePositionIdsPrecisionForGPTOSS() {
}
size_t idx = 0;
- insert_converts_before_if_needed(matmul_node, desired_et, idx);
- insert_converts_before_if_needed(mul_node1, desired_et, idx);
- insert_converts_before_if_needed(mul_node2, desired_et, idx);
+ bool is_changed = insert_converts_before_if_needed(matmul_node, desired_et, idx);
+ is_changed = insert_converts_before_if_needed(mul_node1, desired_et, idx) || is_changed;
+ is_changed = insert_converts_before_if_needed(mul_node2, desired_et, idx) || is_changed;
- return true;
+ return is_changed;
};
auto m = std::make_shared<ov::pass::pattern::Matcher>(rope_qk, "IncreasePositionIdsPrecisionForGPTOSS");
@@ -607,15 +872,25 @@ IncreasePositionIdsPrecisionForDirectMatMulSinCos::IncreasePositionIdsPrecisionF
IncreasePositionIdsPrecision::IncreasePositionIdsPrecision() = default;
bool IncreasePositionIdsPrecision::run_on_model(const std::shared_ptr<ov::Model>& model) {
- ov::pass::SymbolicOptimizations symbolic_optimizations(false, get_pass_config());
- auto symbolic_ctx_manager = symbolic_optimizations.get_manager();
- symbolic_ctx_manager->register_pass<IncreasePositionIdsPrecisionForDirectMatMulSinCos>();
- symbolic_ctx_manager->register_pass<IncreasePositionIdsPrecisionForRoPE>();
- symbolic_ctx_manager->register_pass<IncreasePositionIdsPrecisionForQwen25VL>();
- symbolic_ctx_manager->register_pass<IncreasePositionIdsPrecisionForQwen3VL>();
- symbolic_ctx_manager->register_pass<IncreasePositionIdsPrecisionForLtxVideo>();
- symbolic_ctx_manager->register_pass<IncreasePositionIdsPrecisionForGPTOSS>();
- return symbolic_optimizations.run_on_model(model);
+ ov::pass::Manager specialized_manager(*get_pass_config());
+ // The outer pipeline runs Validate, so disable validation after each internal pass.
+ specialized_manager.set_per_pass_validation(false);
+ specialized_manager.register_pass<IncreasePositionIdsPrecisionForDirectMatMulSinCos>();
+ specialized_manager.register_pass<IncreasePositionIdsPrecisionForRoPE>();
+ specialized_manager.register_pass<IncreasePositionIdsPrecisionForQwen25VL>();
+ specialized_manager.register_pass<IncreasePositionIdsPrecisionForQwen3VL>();
+ specialized_manager.register_pass<IncreasePositionIdsPrecisionForGPTOSS>();
+ // Temporary workaround: the generalized LTX pattern can rematch regions changed by specialized passes.
+ // Skip LTX for the entire model after any specialized change to avoid duplicate precision rewrites.
+ // TODO: Remove this gate once a unified general pass covers the specialized patterns without reprocessing.
+ if (specialized_manager.run_passes(model)) {
+ return true;
+ }
+
+ ov::pass::Manager ltx_manager(*get_pass_config());
+ ltx_manager.set_per_pass_validation(false);
+ ltx_manager.register_pass<IncreasePositionIdsPrecisionForLtxVideo>();
+ return ltx_manager.run_passes(model);
}
DisableFP16ComForGPTOSSROPEPattern::DisableFP16ComForGPTOSSROPEPattern() {
diff --git a/src/plugins/intel_gpu/src/plugin/transformations/increase_position_ids_precision.hpp b/src/plugins/intel_gpu/src/plugin/transformations/increase_position_ids_precision.hpp
index 8ca88535430..5a607c10325 100644
--- a/src/plugins/intel_gpu/src/plugin/transformations/increase_position_ids_precision.hpp
+++ b/src/plugins/intel_gpu/src/plugin/transformations/increase_position_ids_precision.hpp
@@ -4,10 +4,25 @@
#pragma once
+#include <memory>
+#include <unordered_set>
+
#include "openvino/pass/graph_rewrite.hpp"
namespace ov::intel_gpu {
+class CollectSinCosConstantsForPrecisionPreservation : public ov::pass::ModelPass {
+public:
+ OPENVINO_MODEL_PASS_RTTI("CollectSinCosConstantsForPrecisionPreservation");
+ using ConstantSet = std::unordered_set<const ov::Node*>;
+
+ explicit CollectSinCosConstantsForPrecisionPreservation(const std::shared_ptr<ConstantSet>& constants);
+ bool run_on_model(const std::shared_ptr<ov::Model>& model) override;
+
+private:
+ std::shared_ptr<ConstantSet> m_constants;
+};
+
class IncreasePositionIdsPrecisionForRoPE : public ov::pass::MatcherPass {
public:
OPENVINO_MATCHER_PASS_RTTI("IncreasePositionIdsPrecisionBase");
diff --git a/src/plugins/intel_gpu/src/plugin/transformations_pipeline.cpp b/src/plugins/intel_gpu/src/plugin/transformations_pipeline.cpp
index 5403388d7d0..3b5a80aa703 100644
--- a/src/plugins/intel_gpu/src/plugin/transformations_pipeline.cpp
+++ b/src/plugins/intel_gpu/src/plugin/transformations_pipeline.cpp
@@ -605,6 +605,29 @@ public:
};
namespace {
+
+bool skip_constant_precision_preservation(const std::shared_ptr<const ov::Node>& node,
+ const std::unordered_set<const ov::Node*>& sincos_constants) {
+ const auto targets = node->get_output_target_inputs(0);
+ const ov::Node* next_node = node.get();
+ if (!targets.empty()) {
+ next_node = targets.begin()->get_node();
+ }
+ if (ov::is_type<ov::op::v0::Convert>(next_node)) {
+ const auto convert_targets = next_node->get_output_target_inputs(0);
+ if (!convert_targets.empty()) {
+ next_node = convert_targets.begin()->get_node();
+ }
+ }
+ if (ov::is_type_any_of<ov::op::v0::MatMul,
+ ov::op::internal::MOE,
+ ov::op::internal::GatherMatmulCompressed,
+ ov::op::internal::GroupedMatMulCompressed>(next_node)) {
+ return false;
+ }
+ return sincos_constants.count(node.get()) == 0;
+}
+
// Detect whether the model contains a linear-attention (Mamba2 / Gated DeltaNet)
// block. Such hybrid-attention models have an SSM gated output whose activation
// has a wide dynamic range and is unstable under per-token INT8 dyn-quant; we
@@ -930,17 +953,12 @@ void TransformationsPipeline::apply(std::shared_ptr<ov::Model> func) {
manager.register_pass<ov::pass::BroadcastElementwiseFusion>();
manager.register_pass<ov::pass::BroadcastTransition>();
+ auto sincos_constants = std::make_shared<CollectSinCosConstantsForPrecisionPreservation::ConstantSet>();
+ manager.register_pass<CollectSinCosConstantsForPrecisionPreservation>(sincos_constants);
manager.register_pass<ov::pass::KeepConstantsPrecisionAndAddConverts>();
pass_config->set_callback<ov::pass::KeepConstantsPrecisionAndAddConverts>(
- [](const_node_ptr& node) -> bool {
- auto* next_node = node->get_output_target_inputs(0).begin()->get_node();
- if (is_type<ov::op::v0::Convert>(next_node)) {
- next_node = next_node->get_output_target_inputs(0).begin()->get_node();
- }
- return !is_type_any_of<ov::op::v0::MatMul,
- ov::op::internal::MOE,
- ov::op::internal::GatherMatmulCompressed,
- ov::op::internal::GroupedMatMulCompressed>(next_node);
+ [sincos_constants](const_node_ptr& node) -> bool {
+ return ov::intel_gpu::skip_constant_precision_preservation(node, *sincos_constants);
});
// Disable subtract folding only for the dGPUs to meet the requirements of oneDNN:
diff --git a/src/plugins/intel_gpu/tests/unit/transformations/increase_precision_test.cpp b/src/plugins/intel_gpu/tests/unit/transformations/increase_precision_test.cpp
index d3b2117ab3e..dff23eabb29 100644
--- a/src/plugins/intel_gpu/tests/unit/transformations/increase_precision_test.cpp
+++ b/src/plugins/intel_gpu/tests/unit/transformations/increase_precision_test.cpp
@@ -4,21 +4,33 @@
#include <gtest/gtest.h>
+#include <cmath>
#include <limits>
+#include <map>
#include <string>
#include <memory>
+#include <unordered_set>
+#include <utility>
+#include <vector>
#include "intel_gpu/op/gemm.hpp"
#include "ov_ops/rotary_positional_embeddings.hpp"
#include <openvino/pass/manager.hpp>
+#include <openvino/pass/constant_folding.hpp>
#include <openvino/core/model.hpp>
#include "openvino/core/coordinate_diff.hpp"
+#include "openvino/core/validation_util.hpp"
#include "openvino/core/type/element_type.hpp"
+#include "openvino/core/type/float16.hpp"
#include "openvino/op/constant.hpp"
+#include "openvino/op/convert.hpp"
+#include "openvino/op/parameter.hpp"
#include "openvino/op/concat.hpp"
#include "openvino/op/cos.hpp"
+#include "openvino/op/divide.hpp"
#include "openvino/op/multiply.hpp"
+#include "openvino/op/result.hpp"
#include "openvino/op/sin.hpp"
#include "openvino/op/reshape.hpp"
#include "openvino/op/squeeze.hpp"
@@ -37,15 +49,228 @@
#include "ov_ops/rms.hpp"
#include "openvino/op/split.hpp"
#include "openvino/op/scaled_dot_product_attention.hpp"
+#include "openvino/op/scatter_nd_update.hpp"
+#include "openvino/op/slice.hpp"
+#include "openvino/runtime/tensor.hpp"
#include <plugin/transformations/increase_position_ids_precision.hpp>
#include <plugin/transformations/increase_rms_input_precision.hpp>
#include <transformations/init_node_info.hpp>
+#include <transformations/convert_precision.hpp>
+#include <transformations/fp16_compression/mark_decompression_convert_constant_folding.hpp>
#include <transformations/utils/utils.hpp>
#include "openvino/pass/visualize_tree.hpp"
#include "common_test_utils/ov_test_utils.hpp"
+// Sin/Cos discovery helpers and regression tests.
+namespace {
+
+void run_discovery(const std::shared_ptr<ov::Model>& model, bool disabled = false) {
+ ov::pass::Manager manager;
+ manager.register_pass<ov::intel_gpu::IncreasePositionIdsPrecisionForLtxVideo>();
+ if (disabled) {
+ manager.get_pass_config()->set_callback<ov::intel_gpu::IncreasePositionIdsPrecisionForLtxVideo>(
+ [](const std::shared_ptr<const ov::Node>&) { return true; });
+ }
+ manager.run_passes(model);
+}
+
+void expect_fp32_pair(const std::shared_ptr<ov::Model>& model) {
+ ASSERT_NO_THROW(model->validate_nodes_and_infer_types());
+ ov::OutputVector angles;
+ for (size_t i = 0; i < 2; ++i) {
+ auto boundary = model->get_results()[i]->input_value(0).get_node_shared_ptr();
+ ASSERT_TRUE(ov::is_type<ov::op::v0::Convert>(boundary));
+ EXPECT_EQ(boundary->get_output_element_type(0), ov::element::f16);
+ const auto trig = boundary->input_value(0).get_node_shared_ptr();
+ if (i == 0) {
+ ASSERT_TRUE(ov::is_type<ov::op::v0::Sin>(trig));
+ } else {
+ ASSERT_TRUE(ov::is_type<ov::op::v0::Cos>(trig));
+ }
+ EXPECT_EQ(trig->get_output_element_type(0), ov::element::f32);
+ angles.push_back(trig->input_value(0));
+ }
+ ASSERT_EQ(angles[0], angles[1]);
+ const auto integer_inputs = [](const ov::Output<ov::Node>& root) {
+ std::map<ov::Output<ov::Node>, size_t> inputs;
+ std::unordered_set<const ov::Node*> visited;
+ ov::OutputVector pending{root};
+ while (!pending.empty()) {
+ const auto node = pending.back().get_node_shared_ptr();
+ pending.pop_back();
+ if (!visited.insert(node.get()).second) {
+ continue;
+ }
+ for (const auto& input : node->input_values()) {
+ if (input.get_element_type().is_real()) {
+ pending.push_back(input);
+ } else {
+ ++inputs[input];
+ }
+ }
+ }
+ return inputs;
+ };
+ EXPECT_EQ(integer_inputs(angles[0]), integer_inputs(model->get_results()[2]->input_value(0)));
+ std::unordered_set<const ov::Node*> visited;
+ while (!angles.empty()) {
+ const auto output = angles.back();
+ angles.pop_back();
+ EXPECT_EQ(output.get_element_type(), ov::element::f32) << output;
+ if (!visited.insert(output.get_node()).second) {
+ continue;
+ }
+ for (const auto& input : output.get_node()->input_values()) {
+ if (input.get_element_type().is_real()) {
+ if (input.get_element_type() == ov::element::f16 &&
+ ov::is_type<ov::op::v0::Parameter>(input.get_node())) {
+ EXPECT_TRUE(ov::is_type<ov::op::v0::Convert>(output.get_node()));
+ continue;
+ }
+ angles.push_back(input);
+ }
+ }
+ }
+}
+
+std::shared_ptr<ov::Model> make_pair(const ov::Output<ov::Node>& angle,
+ const ov::ParameterVector& parameters) {
+ auto sin = std::make_shared<ov::op::v0::Sin>(angle);
+ auto cos = std::make_shared<ov::op::v0::Cos>(angle);
+ return std::make_shared<ov::Model>(ov::OutputVector{sin, cos, angle}, parameters);
+}
+
+} // namespace
+
+TEST(IncreasePositionIdsLTXVideoDiscoveryTest, TimeEmbeddingAndLayoutVariantsWithoutRoPE) {
+ for (const bool layout : {false, true}) {
+ SCOPED_TRACE(layout);
+ auto coordinates = std::make_shared<ov::op::v0::Parameter>(ov::element::i64, ov::Shape{2});
+ auto positions = std::make_shared<ov::op::v0::Convert>(coordinates, ov::element::f16);
+ auto coefficient = ov::op::v0::Constant::create(ov::element::f32, ov::Shape{2}, {31415.927734f});
+ auto compressed = std::make_shared<ov::op::v0::Convert>(coefficient, ov::element::f16);
+ auto multiply = std::make_shared<ov::op::v1::Multiply>(positions, compressed);
+ ov::Output<ov::Node> angle = multiply;
+ if (layout) {
+ auto shape = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{2}, {1, 2});
+ angle = std::make_shared<ov::op::v1::Reshape>(angle, shape, false);
+ }
+ auto model = make_pair(angle, {coordinates});
+ auto table = std::make_shared<ov::op::v0::Concat>(
+ ov::OutputVector{model->get_results()[0]->input_value(0), model->get_results()[1]->input_value(0)},
+ -1);
+ model->add_results({std::make_shared<ov::op::v0::Result>(table)});
+ run_discovery(model);
+ expect_fp32_pair(model);
+ const auto nodes = model->get_ordered_ops();
+ run_discovery(model);
+ EXPECT_EQ(nodes, model->get_ordered_ops());
+ EXPECT_EQ(model->get_results()[2]->input_value(0), angle);
+ EXPECT_EQ(angle.get_element_type(), ov::element::f16);
+ EXPECT_EQ(table->get_output_element_type(0), ov::element::f16);
+ }
+}
+
+TEST(IncreasePositionIdsLTXVideoDiscoveryTest, IneligiblePairsAndFP32PathsStayUnchanged) {
+ for (const std::string mode : {"different", "different_port", "missing", "ambiguous", "ambiguous_sin",
+ "no_arithmetic", "fp32", "fp32_convert", "disabled", "cos_disabled", "bf16",
+ "fixed_gemm"}) {
+ SCOPED_TRACE(mode);
+ auto type = mode == "fp32" || mode == "fp32_convert" ? ov::element::f32 : ov::element::f16;
+ auto input = std::make_shared<ov::op::v0::Parameter>(type, ov::Shape{2});
+ auto constant = ov::op::v0::Constant::create(type, ov::Shape{2}, {2});
+ ov::Output<ov::Node> angle = std::make_shared<ov::op::v1::Add>(input, constant);
+ if (mode == "no_arithmetic") {
+ angle = input;
+ } else if (mode == "fp32_convert") {
+ angle = std::make_shared<ov::op::v0::Convert>(angle, ov::element::f32);
+ } else if (mode == "bf16") {
+ angle = std::make_shared<ov::op::v0::Convert>(angle, ov::element::bf16);
+ angle = std::make_shared<ov::op::v0::Convert>(angle, ov::element::f16);
+ } else if (mode == "fixed_gemm") {
+ angle = std::make_shared<ov::intel_gpu::op::Gemm>(
+ input, constant, std::vector<int64_t>{0}, std::vector<int64_t>{0}, std::vector<int64_t>{},
+ ov::element::f16);
+ }
+ auto model = make_pair(angle, {input});
+ if (mode == "different") {
+ model->get_results()[1]->input_value(0).get_node()->input(0).replace_source_output(input);
+ } else if (mode == "ambiguous") {
+ model->add_results({std::make_shared<ov::op::v0::Result>(std::make_shared<ov::op::v0::Cos>(angle))});
+ } else if (mode == "ambiguous_sin") {
+ model->add_results({std::make_shared<ov::op::v0::Result>(std::make_shared<ov::op::v0::Sin>(angle))});
+ } else if (mode == "missing") {
+ model = std::make_shared<ov::Model>(
+ ov::OutputVector{std::make_shared<ov::op::v0::Sin>(angle)}, ov::ParameterVector{input});
+ } else if (mode == "different_port") {
+ auto axis = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{}, {0});
+ auto split = std::make_shared<ov::op::v1::Split>(angle, axis, 2);
+ model->get_results()[0]->input_value(0).get_node()->input(0).replace_source_output(split->output(0));
+ model->get_results()[1]->input_value(0).get_node()->input(0).replace_source_output(split->output(1));
+ }
+ const auto nodes = model->get_ordered_ops();
+ if (mode == "cos_disabled") {
+ ov::pass::Manager manager;
+ manager.register_pass<ov::intel_gpu::IncreasePositionIdsPrecisionForLtxVideo>();
+ manager.get_pass_config()->set_callback<ov::intel_gpu::IncreasePositionIdsPrecisionForLtxVideo>(
+ [](const std::shared_ptr<const ov::Node>& node) { return ov::is_type<ov::op::v0::Cos>(node); });
+ manager.run_passes(model);
+ } else {
+ run_discovery(model, mode == "disabled");
+ }
+ EXPECT_EQ(nodes, model->get_ordered_ops());
+ EXPECT_NO_THROW(model->validate_nodes_and_infer_types());
+ }
+}
+
+// Discovery regressions through the enclosing pass and FP16 input boundaries.
+TEST(IncreasePositionIdsLTXVideoDiscoveryTest, PreservesInputBoundariesAndIsIdempotent) {
+ struct Case {
+ ov::element::Type angle_type;
+ bool fp16_parameter;
+ bool enclosing;
+ };
+ for (const auto& config : {Case{ov::element::f16, false, true},
+ Case{ov::element::f32, false, true},
+ Case{ov::element::f16, true, false},
+ Case{ov::element::f16, true, true}}) {
+ SCOPED_TRACE(::testing::Message() << "angle_type=" << config.angle_type
+ << ", fp16_parameter=" << config.fp16_parameter
+ << ", enclosing=" << config.enclosing);
+ const auto input_type = config.fp16_parameter ? ov::element::f16 : ov::element::i64;
+ auto input = std::make_shared<ov::op::v0::Parameter>(input_type, ov::Shape{2});
+ auto coefficient = ov::op::v0::Constant::create(config.angle_type, ov::Shape{2}, {2});
+ std::shared_ptr<ov::Node> angle;
+ if (config.fp16_parameter) {
+ angle = std::make_shared<ov::op::v1::Add>(input, coefficient);
+ } else {
+ auto converted = std::make_shared<ov::op::v0::Convert>(input, config.angle_type);
+ angle = std::make_shared<ov::op::v1::Multiply>(converted, coefficient);
+ }
+ auto model = make_pair(angle, {input});
+ const auto original = model->get_ordered_ops();
+ ov::pass::Manager manager;
+ if (config.enclosing) {
+ manager.register_pass<ov::intel_gpu::IncreasePositionIdsPrecision>();
+ } else {
+ manager.register_pass<ov::intel_gpu::IncreasePositionIdsPrecisionForLtxVideo>();
+ }
+ manager.run_passes(model);
+ if (config.angle_type == ov::element::f16) {
+ expect_fp32_pair(model);
+ } else {
+ EXPECT_EQ(original, model->get_ordered_ops());
+ }
+ const auto nodes = model->get_ordered_ops();
+ manager.run_passes(model);
+ EXPECT_EQ(nodes, model->get_ordered_ops());
+ EXPECT_EQ(input->get_output_element_type(0), input_type);
+ EXPECT_EQ(model->get_results()[2]->input_value(0), angle->output(0));
+ }
+}
+
using namespace testing;
using namespace ov::intel_gpu;
@@ -446,11 +671,13 @@ static void test_IncreasePositionIdsLTXVideo(std::shared_ptr<ov::Model>& model,
// Upstream with converts: Convert(f16→f32) before Multiply inputs, Convert on Add constant
auto convert_mul_in = std::make_shared<ov::op::v0::Convert>(param_mul_in, ov::element::f32);
auto mul_const = ov::op::v0::Constant::create(ov::element::f16, ov::Shape{1, 1, 64}, {3.14f});
- auto convert_mul_const = std::make_shared<ov::op::v0::Convert>(mul_const, ov::element::f32);
+ auto convert_mul_const = ov::util::get_constant_from_source(
+ std::make_shared<ov::op::v0::Convert>(mul_const, ov::element::f32));
auto multiply = std::make_shared<ov::op::v1::Multiply>(convert_mul_in, convert_mul_const);
auto add_const = ov::op::v0::Constant::create(ov::element::f16, ov::Shape{1, 1, 64}, {1e-6f});
- auto convert_add_const = std::make_shared<ov::op::v0::Convert>(add_const, ov::element::f32);
+ auto convert_add_const = ov::util::get_constant_from_source(
+ std::make_shared<ov::op::v0::Convert>(add_const, ov::element::f32));
auto add = std::make_shared<ov::op::v1::Add>(multiply, convert_add_const);
auto transpose_order = ov::op::v0::Constant::create(ov::element::i32, ov::Shape{3}, {0, 2, 1});
@@ -506,6 +733,8 @@ TEST_F(TransformationTestsF, IncreasePositionIdsLTXVideo_T) {
}
TEST_F(TransformationTestsF, IncreasePositionIdsLTXVideo_F) {
+ manager.get_pass_config()->set_callback<IncreasePositionIdsPrecisionForLtxVideo>(
+ [](const std::shared_ptr<const ov::Node>&) { return true; });
test_IncreasePositionIdsLTXVideo(model, model_ref, manager, comparator, false);
}
@@ -561,10 +790,12 @@ static void test_IncreasePositionIdsLTXVideoGather(std::shared_ptr<ov::Model>& m
// Upstream with f32 converts inserted by the pass
auto convert_mul_in = std::make_shared<ov::op::v0::Convert>(param_mul_in, ov::element::f32);
auto mul_const = ov::op::v0::Constant::create(ov::element::f16, ov::Shape{1, 1, 64}, {3.14f});
- auto convert_mul_const = std::make_shared<ov::op::v0::Convert>(mul_const, ov::element::f32);
+ auto convert_mul_const = ov::util::get_constant_from_source(
+ std::make_shared<ov::op::v0::Convert>(mul_const, ov::element::f32));
auto multiply = std::make_shared<ov::op::v1::Multiply>(convert_mul_in, convert_mul_const);
auto add_const = ov::op::v0::Constant::create(ov::element::f16, ov::Shape{1, 1, 64}, {1e-6f});
- auto convert_add_const = std::make_shared<ov::op::v0::Convert>(add_const, ov::element::f32);
+ auto convert_add_const = ov::util::get_constant_from_source(
+ std::make_shared<ov::op::v0::Convert>(add_const, ov::element::f32));
auto add = std::make_shared<ov::op::v1::Add>(multiply, convert_add_const);
auto transpose_order = ov::op::v0::Constant::create(ov::element::i32, ov::Shape{3}, {0, 2, 1});
auto transpose_up = std::make_shared<ov::op::v1::Transpose>(add, transpose_order);
@@ -604,9 +835,370 @@ TEST_F(TransformationTestsF, IncreasePositionIdsLTXVideoGather_T) {
}
TEST_F(TransformationTestsF, IncreasePositionIdsLTXVideoGather_F) {
+ manager.get_pass_config()->set_callback<IncreasePositionIdsPrecisionForLtxVideo>(
+ [](const std::shared_ptr<const ov::Node>&) { return true; });
test_IncreasePositionIdsLTXVideoGather(model, model_ref, manager, comparator, false);
}
+namespace {
+
+struct LtxAngleTestModel {
+ std::shared_ptr<ov::Model> model;
+ std::shared_ptr<ov::op::v0::Parameter> coordinates;
+ std::shared_ptr<ov::op::v0::Parameter> scale;
+ std::shared_ptr<ov::op::v0::Constant> coefficient;
+ std::shared_ptr<ov::op::v0::Constant> offset;
+ std::shared_ptr<ov::Node> coefficient_downcast;
+ std::shared_ptr<ov::Node> scatter;
+ std::shared_ptr<ov::Node> sin_consumer;
+ std::shared_ptr<ov::Node> cos_consumer;
+ std::shared_ptr<ov::Node> rope;
+};
+
+LtxAngleTestModel make_ltx_angle_test_model(bool fp32_trig = false,
+ bool gather_nd = false,
+ bool original_fp32 = false) {
+ LtxAngleTestModel graph;
+ auto coordinates = std::make_shared<ov::op::v0::Parameter>(ov::element::i64, ov::Shape{2});
+ auto scale = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::Shape{2});
+ auto x = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::Shape{1, 1, 4});
+ const auto value_type = original_fp32 ? ov::element::f32 : ov::element::f16;
+ auto positions = std::make_shared<ov::op::v0::Convert>(coordinates, value_type);
+ positions->set_friendly_name("ltx_positions");
+ auto scale_downcast = std::make_shared<ov::op::v0::Convert>(scale, value_type);
+ auto axis = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{}, {0});
+ auto gather = std::make_shared<ov::op::v8::Gather>(scale_downcast, coordinates, axis);
+ gather->set_friendly_name("ltx_scale_gather");
+ auto scaled = std::make_shared<ov::op::v1::Multiply>(positions, gather);
+ auto divisor = ov::op::v0::Constant::create(value_type, ov::Shape{}, {20});
+ auto divided = std::make_shared<ov::op::v1::Divide>(scaled, divisor);
+ divided->set_friendly_name("ltx_divide");
+ auto start = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, {0});
+ auto stop = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, {1});
+ auto step = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, {1});
+ auto updates = std::make_shared<ov::op::v8::Slice>(divided, start, stop, step);
+ auto scatter_indices = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1, 1}, {0});
+ graph.scatter = std::make_shared<ov::op::v3::ScatterNDUpdate>(positions, scatter_indices, updates);
+ graph.scatter->set_friendly_name("ltx_scatter");
+ auto concat = std::make_shared<ov::op::v0::Concat>(ov::OutputVector{graph.scatter, graph.scatter}, 0);
+ auto split = std::make_shared<ov::op::v1::Split>(concat, axis, 2);
+ split->set_friendly_name("ltx_split");
+ ov::Output<ov::Node> values = split->output(1);
+ const auto trig_type = (fp32_trig || original_fp32) ? ov::element::f32 : ov::element::f16;
+ if (!original_fp32) {
+ values = std::make_shared<ov::op::v0::Convert>(values, ov::element::f32);
+ if (!fp32_trig) {
+ values = std::make_shared<ov::op::v0::Convert>(values, ov::element::f16);
+ }
+ }
+ graph.coefficient = ov::op::v0::Constant::create(ov::element::f32, ov::Shape{2}, {31415.927734f});
+ graph.offset = ov::op::v0::Constant::create(ov::element::f32, ov::Shape{2}, {-15707.963867f});
+ graph.coefficient_downcast = graph.coefficient;
+ std::shared_ptr<ov::Node> offset_downcast = graph.offset;
+ if (!original_fp32) {
+ graph.coefficient_downcast = std::make_shared<ov::op::v0::Convert>(graph.coefficient, trig_type);
+ offset_downcast = std::make_shared<ov::op::v0::Convert>(graph.offset, trig_type);
+ }
+ auto multiply = std::make_shared<ov::op::v1::Multiply>(values, graph.coefficient_downcast);
+ auto add = std::make_shared<ov::op::v1::Add>(multiply, offset_downcast);
+ auto order = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, {0});
+ auto transpose = std::make_shared<ov::op::v1::Transpose>(add, order);
+ auto shape = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{3}, {1, 1, 2});
+ auto reshape = std::make_shared<ov::op::v1::Reshape>(transpose, shape, false);
+ auto sin = std::make_shared<ov::op::v0::Sin>(reshape);
+ auto cos = std::make_shared<ov::op::v0::Cos>(reshape);
+ const auto make_table_path = [&](const std::shared_ptr<ov::Node>& trig,
+ std::shared_ptr<ov::Node>& consumer) -> std::shared_ptr<ov::Node> {
+ if (!gather_nd) {
+ auto indices = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{2}, {0, 1});
+ auto table_axis = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{}, {-1});
+ consumer = std::make_shared<ov::op::v8::Gather>(trig, indices, table_axis);
+ return consumer;
+ }
+ auto indices = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1, 1}, {0});
+ consumer = std::make_shared<ov::op::v8::GatherND>(trig, indices);
+ return consumer;
+ };
+ const auto sin_values = make_table_path(sin, graph.sin_consumer);
+ const auto cos_values = make_table_path(cos, graph.cos_consumer);
+ auto padding = ov::op::v0::Constant::create(trig_type, ov::Shape{1, 1, 2}, {0});
+ auto sin_table = std::make_shared<ov::op::v0::Concat>(ov::OutputVector{padding, sin_values}, -1);
+ auto cos_table = std::make_shared<ov::op::v0::Concat>(ov::OutputVector{padding, cos_values}, -1);
+ ov::op::internal::RoPE::Config config;
+ config.is_ltx_video = true;
+ config.rotary_ndims = 4;
+ graph.rope = std::make_shared<ov::op::internal::RoPE>(ov::OutputVector{x, cos_table, sin_table}, config);
+ auto second_rope = graph.rope->clone_with_new_inputs(graph.rope->input_values());
+ ov::OutputVector outputs{graph.rope, second_rope};
+ if (!original_fp32) {
+ outputs.push_back(graph.scatter);
+ outputs.push_back(graph.coefficient_downcast);
+ }
+ graph.model = std::make_shared<ov::Model>(outputs, ov::ParameterVector{coordinates, scale, x});
+ graph.coordinates = coordinates;
+ graph.scale = scale;
+ return graph;
+}
+
+std::shared_ptr<ov::Node> find_ltx_fp32_node(const std::shared_ptr<ov::Model>& model, const std::string& name) {
+ for (const auto& node : model->get_ordered_ops()) {
+ if (node->get_friendly_name().find(name + "/fp32_") == 0) {
+ return node;
+ }
+ }
+ return nullptr;
+}
+
+bool skip_ltx_test_constant_precision_preservation(
+ const std::shared_ptr<const ov::Node>& node,
+ const CollectSinCosConstantsForPrecisionPreservation::ConstantSet& constants) {
+ const auto targets = node->get_output_target_inputs(0);
+ const ov::Node* next_node = node.get();
+ if (!targets.empty()) {
+ next_node = targets.begin()->get_node();
+ }
+ if (ov::is_type<ov::op::v0::Convert>(next_node)) {
+ const auto convert_targets = next_node->get_output_target_inputs(0);
+ if (!convert_targets.empty()) {
+ next_node = convert_targets.begin()->get_node();
+ }
+ }
+ return !ov::is_type<ov::op::v0::MatMul>(next_node) && constants.count(node.get()) == 0;
+}
+
+std::shared_ptr<CollectSinCosConstantsForPrecisionPreservation::ConstantSet> run_ltx_constant_precision_passes(
+ const std::shared_ptr<ov::Model>& model,
+ bool collect_constants = true) {
+ auto constants = std::make_shared<CollectSinCosConstantsForPrecisionPreservation::ConstantSet>();
+ ov::pass::Manager manager;
+ if (collect_constants) {
+ manager.register_pass<CollectSinCosConstantsForPrecisionPreservation>(constants);
+ }
+ manager.register_pass<ov::pass::KeepConstantsPrecisionAndAddConverts>();
+ manager.get_pass_config()->set_callback<ov::pass::KeepConstantsPrecisionAndAddConverts>(
+ [constants](const std::shared_ptr<const ov::Node>& node) {
+ return skip_ltx_test_constant_precision_preservation(node, *constants);
+ });
+ manager.register_pass<ov::pass::ConvertPrecision>(
+ precisions_map{{ov::element::f32, ov::element::f16}}, type_to_fuse_map{}, true, false, true);
+ manager.register_pass<ov::pass::ConstantFolding>();
+ manager.run_passes(model);
+ return constants;
+}
+
+ov::Output<ov::Node> get_ltx_angle(const std::shared_ptr<ov::Node>& consumer) {
+ auto trig = consumer->input_value(0).get_node_shared_ptr();
+ if (ov::is_type<ov::op::v0::Convert>(trig)) {
+ trig = trig->input_value(0).get_node_shared_ptr();
+ }
+ OPENVINO_ASSERT((ov::is_type_any_of<ov::op::v0::Sin, ov::op::v0::Cos>(trig)));
+ return trig->input_value(0);
+}
+
+void expect_ltx_angle_region_fp32(const LtxAngleTestModel& graph) {
+ const auto sin_angle = get_ltx_angle(graph.sin_consumer);
+ const auto cos_angle = get_ltx_angle(graph.cos_consumer);
+ EXPECT_EQ(sin_angle, cos_angle);
+ ov::OutputVector pending{sin_angle, cos_angle};
+ std::unordered_set<const ov::Node*> visited;
+ while (!pending.empty()) {
+ const auto output = pending.back();
+ pending.pop_back();
+ ASSERT_EQ(output.get_element_type(), ov::element::f32) << output;
+ const auto node = output.get_node_shared_ptr();
+ if (!visited.insert(node.get()).second) {
+ continue;
+ }
+ for (const auto& input : node->input_values()) {
+ if (input.get_element_type().is_real()) {
+ pending.push_back(input);
+ }
+ }
+ }
+}
+
+ov::Tensor evaluate_ltx_angle(const LtxAngleTestModel& graph) {
+ auto model = std::make_shared<ov::Model>(ov::OutputVector{get_ltx_angle(graph.sin_consumer)},
+ ov::ParameterVector{graph.coordinates, graph.scale});
+ ov::Tensor coordinates(ov::element::i64, ov::Shape{2});
+ coordinates.data<int64_t>()[0] = 0;
+ coordinates.data<int64_t>()[1] = 1;
+ ov::Tensor scale(ov::element::f32, ov::Shape{2});
+ scale.data<float>()[0] = 1.f;
+ scale.data<float>()[1] = 1.f;
+ ov::TensorVector outputs{ov::Tensor(ov::element::f32, ov::Shape{1, 1, 2})};
+ OPENVINO_ASSERT(model->evaluate(outputs, ov::TensorVector{coordinates, scale}), "LTX angle evaluation failed");
+ return outputs[0];
+}
+
+} // namespace
+
+TEST(IncreasePositionIdsLTXVideoCallbackTest, RemovesFP16RoundTripsFromAnglePaths) {
+ struct Case {
+ bool fp32_trig;
+ bool gather_nd;
+ };
+ for (const auto& config : {Case{false, false}, Case{false, true}, Case{true, false}}) {
+ SCOPED_TRACE(::testing::Message() << "fp32_trig=" << config.fp32_trig << ", gather_nd=" << config.gather_nd);
+ auto graph = make_ltx_angle_test_model(config.fp32_trig, config.gather_nd);
+ run_discovery(graph.model);
+ ASSERT_NO_THROW(graph.model->validate_nodes_and_infer_types());
+
+ auto sin = graph.sin_consumer->input_value(0).get_node_shared_ptr();
+ auto cos = graph.cos_consumer->input_value(0).get_node_shared_ptr();
+ if (!config.fp32_trig) {
+ ASSERT_TRUE(ov::is_type<ov::op::v0::Convert>(sin));
+ ASSERT_TRUE(ov::is_type<ov::op::v0::Convert>(cos));
+ EXPECT_EQ(sin->get_output_element_type(0), ov::element::f16);
+ EXPECT_EQ(cos->get_output_element_type(0), ov::element::f16);
+ sin = sin->input_value(0).get_node_shared_ptr();
+ cos = cos->input_value(0).get_node_shared_ptr();
+ }
+ ASSERT_TRUE(ov::is_type<ov::op::v0::Sin>(sin));
+ ASSERT_TRUE(ov::is_type<ov::op::v0::Cos>(cos));
+ EXPECT_EQ(sin->get_output_element_type(0), ov::element::f32);
+ EXPECT_EQ(cos->get_output_element_type(0), ov::element::f32);
+ expect_ltx_angle_region_fp32(graph);
+
+ const auto add = sin->input_value(0).get_node()->input_value(0).get_node()->input_value(0).get_node_shared_ptr();
+ ASSERT_TRUE(ov::is_type<ov::op::v1::Add>(add));
+ EXPECT_EQ(add->input_value(1), graph.offset->output(0));
+ const auto multiply = add->input_value(0).get_node_shared_ptr();
+ EXPECT_EQ(multiply->input_value(1), graph.coefficient->output(0));
+ EXPECT_EQ(multiply->input_value(0).get_index(), 1);
+ const auto split = multiply->input_value(0).get_node_shared_ptr();
+ ASSERT_TRUE(ov::is_type<ov::op::v1::Split>(split));
+ const auto concat = split->input_value(0).get_node_shared_ptr();
+ EXPECT_EQ(concat->input_value(0), concat->input_value(1));
+
+ const auto scatter = find_ltx_fp32_node(graph.model, "ltx_scatter");
+ ASSERT_NE(scatter, nullptr);
+ EXPECT_EQ(concat->input_value(0), scatter->output(0));
+ EXPECT_EQ(scatter->input_value(1), graph.scatter->input_value(1));
+ EXPECT_TRUE(ov::is_type<ov::op::v3::ScatterNDUpdate>(scatter));
+ const auto positions = scatter->input_value(0).get_node_shared_ptr();
+ ASSERT_TRUE(ov::is_type<ov::op::v0::Convert>(positions));
+ EXPECT_EQ(positions->input_value(0), graph.coordinates->output(0));
+ const auto gather = find_ltx_fp32_node(graph.model, "ltx_scale_gather");
+ ASSERT_NE(gather, nullptr);
+ EXPECT_EQ(gather->input_value(0), graph.scale->output(0));
+ EXPECT_EQ(gather->input_value(1), graph.coordinates->output(0));
+ EXPECT_EQ(gather->get_input_element_type(1), ov::element::i64);
+ EXPECT_EQ(gather->get_input_element_type(2), ov::element::i64);
+ const auto divide = find_ltx_fp32_node(graph.model, "ltx_divide");
+ ASSERT_NE(divide, nullptr);
+ ASSERT_TRUE(ov::is_type<ov::op::v0::Constant>(divide->input_value(1).get_node()));
+ EXPECT_EQ(graph.model->get_results()[2]->input_value(0), graph.scatter->output(0));
+ EXPECT_EQ(graph.model->get_results()[3]->input_value(0), graph.coefficient_downcast->output(0));
+ EXPECT_EQ(graph.scatter->get_output_element_type(0), ov::element::f16);
+ EXPECT_EQ(graph.coefficient_downcast->get_output_element_type(0),
+ config.fp32_trig ? ov::element::f32 : ov::element::f16);
+ EXPECT_EQ(graph.model->get_results()[0]->input_value(0), graph.rope->output(0));
+ EXPECT_TRUE(ov::is_type<ov::op::internal::RoPE>(graph.model->get_results()[1]->input_value(0).get_node()));
+
+ const auto nodes = graph.model->get_ordered_ops();
+ run_discovery(graph.model);
+ EXPECT_EQ(nodes, graph.model->get_ordered_ops());
+ }
+}
+
+TEST(IncreasePositionIdsLTXVideoCallbackTest, CollectsAndPreservesOriginalConstants) {
+ for (const bool gather_nd : {false, true}) {
+ SCOPED_TRACE(::testing::Message() << "gather_nd=" << gather_nd);
+ auto graph = make_ltx_angle_test_model(false, gather_nd, true);
+ auto unrelated_constant = ov::op::v0::Constant::create(ov::element::f32, ov::Shape{2}, {31415.927734f});
+ auto unrelated = std::make_shared<ov::op::v1::Multiply>(graph.scale, unrelated_constant);
+ auto result = std::make_shared<ov::op::v0::Result>(unrelated);
+ graph.model->add_results({result});
+ const auto coefficient_values = graph.coefficient->cast_vector<float>();
+ const auto offset_values = graph.offset->cast_vector<float>();
+
+ const auto constants = run_ltx_constant_precision_passes(graph.model);
+ EXPECT_EQ(constants->count(graph.coefficient.get()), 1);
+ EXPECT_EQ(constants->count(graph.offset.get()), 1);
+ EXPECT_EQ(constants->count(graph.scatter->input_value(1).get_node()), 0);
+ EXPECT_EQ(constants->count(unrelated_constant.get()), 0);
+ EXPECT_EQ(graph.coefficient->cast_vector<float>(), coefficient_values);
+ EXPECT_EQ(graph.offset->cast_vector<float>(), offset_values);
+
+ const auto angle = get_ltx_angle(graph.sin_consumer);
+ ASSERT_EQ(angle.get_element_type(), ov::element::f16);
+ const auto add = angle.get_node()->input_value(0).get_node()->input_value(0).get_node_shared_ptr();
+ ASSERT_TRUE(ov::is_type<ov::op::v1::Add>(add));
+ const auto multiply = add->input_value(0).get_node_shared_ptr();
+ ASSERT_TRUE(ov::is_type<ov::op::v1::Multiply>(multiply));
+ for (const auto& entry : {std::make_pair(multiply->input_value(1), graph.coefficient),
+ std::make_pair(add->input_value(1), graph.offset)}) {
+ const auto convert = ov::as_type_ptr<ov::op::v0::Convert>(entry.first.get_node_shared_ptr());
+ ASSERT_NE(convert, nullptr);
+ EXPECT_EQ(convert->get_output_element_type(0), ov::element::f16);
+ EXPECT_EQ(convert->input_value(0), entry.second->output(0));
+ EXPECT_EQ(entry.second->get_element_type(), ov::element::f32);
+ }
+
+ auto unrelated_output = result->input_value(0).get_node_shared_ptr();
+ if (ov::is_type<ov::op::v0::Convert>(unrelated_output)) {
+ unrelated_output = unrelated_output->input_value(0).get_node_shared_ptr();
+ }
+ ASSERT_TRUE(ov::is_type<ov::op::v1::Multiply>(unrelated_output));
+ const auto rounded = ov::util::get_constant_from_source(unrelated_output->input_value(1));
+ ASSERT_NE(rounded, nullptr);
+ EXPECT_EQ(rounded->get_element_type(), ov::element::f16);
+ EXPECT_EQ(rounded->cast_vector<float>()[0], static_cast<float>(ov::float16(coefficient_values[0])));
+ EXPECT_NE(rounded->cast_vector<float>()[0], coefficient_values[0]);
+ EXPECT_NO_THROW(graph.model->validate_nodes_and_infer_types());
+ }
+}
+
+TEST(IncreasePositionIdsLTXVideoCallbackTest, RestoresOriginalFP32Angles) {
+ for (const bool gather_nd : {false, true}) {
+ for (const bool collect_constants : {false, true}) {
+ SCOPED_TRACE(::testing::Message() << "gather_nd=" << gather_nd << ", collector=" << collect_constants);
+ auto graph = make_ltx_angle_test_model(false, gather_nd, true);
+ const auto reference = evaluate_ltx_angle(graph);
+ const auto coefficient_values = graph.coefficient->cast_vector<float>();
+ const auto offset_values = graph.offset->cast_vector<float>();
+
+ run_ltx_constant_precision_passes(graph.model, collect_constants);
+ run_discovery(graph.model);
+ ASSERT_NO_THROW(graph.model->validate_nodes_and_infer_types());
+ expect_ltx_angle_region_fp32(graph);
+ const auto angle = get_ltx_angle(graph.sin_consumer);
+ const auto add = angle.get_node()->input_value(0).get_node()->input_value(0).get_node_shared_ptr();
+ ASSERT_TRUE(ov::is_type<ov::op::v1::Add>(add));
+ const auto multiply = add->input_value(0).get_node_shared_ptr();
+ ASSERT_TRUE(ov::is_type<ov::op::v1::Multiply>(multiply));
+ const auto coefficient = ov::as_type_ptr<ov::op::v0::Constant>(multiply->input_value(1).get_node_shared_ptr());
+ const auto offset = ov::as_type_ptr<ov::op::v0::Constant>(add->input_value(1).get_node_shared_ptr());
+ ASSERT_NE(coefficient, nullptr);
+ ASSERT_NE(offset, nullptr);
+ EXPECT_EQ(coefficient->get_element_type(), ov::element::f32);
+ EXPECT_EQ(offset->get_element_type(), ov::element::f32);
+ const auto actual = evaluate_ltx_angle(graph);
+ ASSERT_EQ(actual.get_shape(), reference.get_shape());
+ if (collect_constants) {
+ EXPECT_EQ(coefficient, graph.coefficient);
+ EXPECT_EQ(offset, graph.offset);
+ EXPECT_EQ(coefficient->cast_vector<float>(), coefficient_values);
+ EXPECT_EQ(offset->cast_vector<float>(), offset_values);
+ for (size_t i = 0; i < actual.get_size(); ++i) {
+ EXPECT_FLOAT_EQ(actual.data<const float>()[i], reference.data<const float>()[i]);
+ }
+ } else {
+ const auto rounded_coefficient = static_cast<float>(ov::float16(coefficient_values[0]));
+ const auto rounded_offset = static_cast<float>(ov::float16(offset_values[0]));
+ EXPECT_EQ(coefficient->cast_vector<float>(), std::vector<float>(2, rounded_coefficient));
+ EXPECT_EQ(offset->cast_vector<float>(), std::vector<float>(2, rounded_offset));
+ EXPECT_FLOAT_EQ(actual.data<const float>()[0], rounded_offset);
+ EXPECT_FLOAT_EQ(actual.data<const float>()[1], rounded_coefficient + rounded_offset);
+ for (size_t i = 0; i < actual.get_size(); ++i) {
+ EXPECT_GT(std::abs(actual.data<const float>()[i] - reference.data<const float>()[i]), 1.f);
+ }
+ }
+ }
+ }
+}
+
TEST_F(TransformationTestsF, IncreasePositionIdsPrecisionForQwen25VL) {
{
auto position_ids = std::make_shared<ov::op::v0::Parameter>(ov::element::i64, ov::PartialShape{ 3, -1, -1 });