OpenVINO™ is an open source toolkit for optimizing and deploying AI inference
C++ aicomputer-visiondeep-learningdeploy-aidiffusion-modelsgenerative-aigood-first-issueinferencellm-inferencenatural-language-processingnlpopenvinooptimize-aiperformance-boostrecommendation-systemspeech-recognitionstable-diffusiontransformersyolo
[NPUW] Rescale fp16-overflowing QDQ regions before collapsing them (#39609)
Raymond Ngun4a77175613a2
diff --git a/src/plugins/intel_npu/src/plugin/npuw/gqa_compiled_model.cpp b/src/plugins/intel_npu/src/plugin/npuw/gqa_compiled_model.cppindex 446d1ca8f55..570bf785247 100644--- a/src/plugins/intel_npu/src/plugin/npuw/gqa_compiled_model.cpp+++ b/src/plugins/intel_npu/src/plugin/npuw/gqa_compiled_model.cpp@@ -335,6 +335,8 @@ ov::npuw::GQACompiledModel::PreparedState ov::npuw::GQACompiledModel::prepare(coconv_to_matmul.run_on_model(model);// Collapse FakeQuantize-based QDQ chains when requested.if (prepared_properties.at(std::string(::intel_npu::NPUW_UNQDQ::key())).as<bool>()) {+ ov::npuw::RescaleFP16OverflowQDQ rescale_fp16_overflow;+ rescale_fp16_overflow.run_on_model(model);ov::npuw::CollapseUNQDQ collapse_unqdq;collapse_unqdq.run_on_model(model);}diff --git a/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/collapse_unqdq.cpp b/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/collapse_unqdq.cppindex c762305689f..143372be6e9 100644--- a/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/collapse_unqdq.cpp+++ b/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/collapse_unqdq.cpp@@ -4,20 +4,33 @@#include "collapse_unqdq.hpp"+#include <algorithm>#include <cmath>#include <memory>#include <optional>#include <string>+#include <vector>+#include "../logging.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/constant.hpp"#include "openvino/op/convert.hpp"+#include "openvino/op/divide.hpp"#include "openvino/op/fake_quantize.hpp"+#include "openvino/op/matmul.hpp"+#include "openvino/op/maximum.hpp"#include "openvino/op/multiply.hpp"+#include "openvino/op/normalize_l2.hpp"+#include "openvino/op/power.hpp"+#include "openvino/op/reduce_sum.hpp"+#include "openvino/op/sqrt.hpp"#include "openvino/op/subtract.hpp"#include "openvino/pass/matcher_pass.hpp"#include "openvino/pass/pattern/op/optional.hpp"+#include "openvino/pass/pattern/op/or.hpp"#include "openvino/pass/pattern/op/wrap_type.hpp"#include "transformations/utils/utils.hpp"@@ -72,6 +85,185 @@ bool is_identity_quantizer_without_zp(const ov::Output<ov::Node>& in_low_n,return isclose(*in_low, scaled_out_low) && isclose(*in_high, scaled_out_high);}+constexpr float kF16Max = 65504.f;+// Calibrated ranges are not hard bounds, so keep one binade of headroom below the f16 maximum.+constexpr float kRescaleTarget = 32768.f;++// FakeQuantize(input) -> Convert (quantize) -> Convert (dequantize) -> [Subtract (zero point)] -> Multiply (scale).+// Shared by CollapseUNQDQ and the rescale guards so both agree on what a removable chain is. Multiply is+// commutative, so the matcher also accepts Multiply(scale, Subtract).+struct UNQDQPattern {+ std::shared_ptr<ov::Node> input;+ std::shared_ptr<ov::Node> in_low;+ std::shared_ptr<ov::Node> in_high;+ std::shared_ptr<ov::Node> out_low;+ std::shared_ptr<ov::Node> out_high;+ std::shared_ptr<ov::Node> fake_q;+ std::shared_ptr<ov::Node> cvt_dq;+ std::shared_ptr<ov::Node> subtract;+ std::shared_ptr<ov::Node> scale;+ std::shared_ptr<ov::Node> multiply;+};++UNQDQPattern make_unqdq_pattern(const std::shared_ptr<ov::Node>& input = opp::any_input()) {+ UNQDQPattern p;+ p.input = input;+ p.in_low = opp::any_input();+ p.in_high = opp::any_input();+ p.out_low = opp::any_input();+ p.out_high = opp::any_input();+ p.fake_q = opp::wrap_type<ov::op::v0::FakeQuantize>({p.input, p.in_low, p.in_high, p.out_low, p.out_high});+ auto cvt_q = opp::wrap_type<ov::op::v0::Convert>({p.fake_q});+ p.cvt_dq = opp::wrap_type<ov::op::v0::Convert>({cvt_q});+ p.subtract = opp::optional<ov::op::v1::Subtract>({p.cvt_dq, opp::any_input()});+ p.scale = opp::any_input();+ p.multiply = opp::wrap_type<ov::op::v1::Multiply>({p.subtract, p.scale});+ return p;+}++// True if the matched chain is one CollapseUNQDQ may replace with its FQ input.+bool is_collapsible(const opp::PatternValueMap& map, const UNQDQPattern& p) {+ // A broadcasting zero point or scale makes the chain non-shape-preserving.+ if (map.at(p.multiply).get_partial_shape() != map.at(p.input).get_partial_shape()) {+ return false;+ }+ return map.count(p.subtract) || is_identity_quantizer_without_zp(map.at(p.in_low),+ map.at(p.in_high),+ map.at(p.out_low),+ map.at(p.out_high),+ map.at(p.scale));+}++std::shared_ptr<ov::Node> single_consumer(const std::shared_ptr<ov::Node>& node) {+ if (!node) {+ return nullptr;+ }+ const auto targets = node->output(0).get_target_inputs();+ return targets.size() == 1 ? targets.begin()->get_node()->shared_from_this() : nullptr;+}++// Returns the Multiply ending the chain that CollapseUNQDQ replaces with the FQ input, or nullptr if+// `fq` does not start such a chain with a single consumer at each step.+std::shared_ptr<ov::Node> unqdq_chain_end(const std::shared_ptr<ov::Node>& fq, const UNQDQPattern& pattern) {+ auto multiply = single_consumer(single_consumer(single_consumer(fq)));+ if (ov::is_type<ov::op::v1::Subtract>(multiply)) {+ multiply = single_consumer(multiply);+ }+ if (!multiply) {+ return nullptr;+ }+ opp::Matcher matcher(pattern.multiply);+ if (!matcher.match(multiply->output(0)) ||+ matcher.get_pattern_value_map().at(pattern.fake_q).get_node() != fq.get() ||+ !is_collapsible(matcher.get_pattern_value_map(), pattern)) {+ return nullptr;+ }+ return multiply;+}++// True if `value` is the zero-point Subtract or, with the Subtract absent, the dequantize Convert of+// a chain. A factor inserted after it would complete the pattern, and CollapseUNQDQ would then drop+// the factor along with the chain.+bool is_dequantize_subtract(const ov::Output<ov::Node>& value, const UNQDQPattern& pattern) {+ return (ov::is_type<ov::op::v1::Subtract>(value.get_node()) && opp::Matcher(pattern.subtract).match(value)) ||+ opp::Matcher(pattern.cvt_dq).match(value);+}++// True if `multiply` is the dequantize scale of a chain CollapseUNQDQ would remove, which would+// also drop or block a factor inserted between its Subtract and itself.+bool is_dequantize_multiply(const std::shared_ptr<ov::Node>& multiply, const UNQDQPattern& pattern) {+ opp::Matcher matcher(pattern.multiply);+ return matcher.match(multiply->output(0)) && is_collapsible(matcher.get_pattern_value_map(), pattern);+}++float fq_range(const std::shared_ptr<ov::op::v0::FakeQuantize>& fq) {+ float range = 0.f;+ for (std::size_t idx : {1u, 2u}) {+ const auto bound = ov::util::get_constant_from_source(fq->input_value(idx));+ if (!bound) {+ return 0.f;+ }+ for (float v : bound->cast_vector<float>()) {+ range = std::max(range, std::fabs(v));+ }+ }+ return range;+}++// The region this pass rescales: UNQDQ -> MatMul -> UNQDQ -> L2 normalization, where the+// normalization is NormalizeL2 or the ONNX LpNormalization (p = 2) decomposition+// Divide(x, Sqrt(Add|Maximum(ReduceSum(Power(x, 2)), eps))). Both are invariant to a factor s on x+// once eps is scaled by s^2.+struct OverflowPattern {+ UNQDQPattern in;+ std::shared_ptr<ov::Node> matmul;+ UNQDQPattern out;+ std::shared_ptr<ov::Node> norm;+ std::shared_ptr<ov::Node> power;+ std::shared_ptr<ov::Node> eps;+ std::shared_ptr<ov::Node> divide;+ std::shared_ptr<ov::Node> root;+};++OverflowPattern make_overflow_pattern() {+ OverflowPattern p;+ p.in = make_unqdq_pattern();+ p.matmul = opp::wrap_type<ov::op::v0::MatMul>({p.in.multiply, opp::any_input()});+ p.out = make_unqdq_pattern(p.matmul);+ p.norm = opp::wrap_type<ov::op::v0::NormalizeL2>({p.out.multiply, opp::any_input()});+ p.power = opp::wrap_type<ov::op::v1::Power>({p.out.multiply, opp::wrap_type<ov::op::v0::Constant>()});+ const auto sum = opp::wrap_type<ov::op::v1::ReduceSum>({p.power, opp::any_input()});+ p.eps = opp::wrap_type<ov::op::v1::Add, ov::op::v1::Maximum>({sum, opp::wrap_type<ov::op::v0::Constant>()});+ const auto sqrt = opp::wrap_type<ov::op::v0::Sqrt>({p.eps});+ p.divide = opp::wrap_type<ov::op::v1::Divide>({p.out.multiply, sqrt});+ p.root = std::make_shared<opp::op::Or>(ov::OutputVector{p.norm, p.divide});+ return p;+}++bool has_single_consumer(const std::shared_ptr<ov::Node>& node) {+ return node->output(0).get_target_inputs().size() == 1;+}++// The matched values must feed nothing else, or the factor would leak past the normalization+bool is_isolated(const OverflowPattern& p, const ov::pass::pattern::PatternValueMap& map) {+ const auto node = [&](const std::shared_ptr<ov::Node>& pattern) {+ return map.at(pattern).get_node_shared_ptr();+ };+ const auto in_end = node(p.in.multiply);+ const auto out_end = node(p.out.multiply);+ if (unqdq_chain_end(node(p.in.fake_q), p.in) != in_end || !has_single_consumer(in_end) ||+ !has_single_consumer(node(p.matmul)) || unqdq_chain_end(node(p.out.fake_q), p.out) != out_end) {+ return false;+ }+ if (map.count(p.norm)) {+ return has_single_consumer(out_end);+ }+ // Decomposed form: x feeds only the Divide and the Power, and each step in between has one consumer+ const auto power = node(p.power);+ const auto exponent = ov::as_type_ptr<ov::op::v0::Constant>(power->get_input_node_shared_ptr(1));+ return out_end->output(0).get_target_inputs().size() == 2 &&+ node(p.divide)->input_value(0) == power->input_value(0) && has_single_consumer(power) &&+ has_single_consumer(power->get_output_target_inputs(0).begin()->get_node()->shared_from_this()) &&+ has_single_consumer(node(p.eps)) &&+ has_single_consumer(node(p.eps)->get_output_target_inputs(0).begin()->get_node()->shared_from_this()) &&+ exponent->cast_vector<float>() == std::vector<float>{2.f};+}++// Returns eps * eps_scale as a Constant of the same type and shape, or nullptr if any value is not+// exactly representable there.+std::shared_ptr<ov::op::v0::Constant> scale_eps(const ov::Output<ov::Node>& eps, double eps_scale) {+ const auto value = ov::util::get_constant_from_source(eps);+ if (!value) {+ return nullptr;+ }+ auto values = value->cast_vector<double>();+ for (auto& v : values) {+ v *= eps_scale;+ }+ auto scaled = ov::op::v0::Constant::create(value->get_element_type(), value->get_shape(), values);+ return scaled->cast_vector<double>() == values ? scaled : nullptr;+}+} // namespaceclass CollapseUNQDQChain final : public ov::pass::MatcherPass {@@ -79,41 +271,16 @@ public:OPENVINO_MATCHER_PASS_RTTI("ov::npuw::CollapseUNQDQChain");CollapseUNQDQChain() {- // Pattern:- // FakeQuantize(input, ...)- // → Convert (quantize, e.g. to u16)- // → Convert (dequantize, back to f32)- // → [Subtract (zero-point)] (optional: dropped for zero ZP)- // → Multiply (scale) ← anchor- auto input = opp::any_input();- auto fq_in_low = opp::any_input();- auto fq_in_high = opp::any_input();- auto fq_out_low = opp::any_input();- auto fq_out_high = opp::any_input();- auto fake_q = opp::wrap_type<ov::op::v0::FakeQuantize>({input, fq_in_low, fq_in_high, fq_out_low, fq_out_high});- auto cvt_q = opp::wrap_type<ov::op::v0::Convert>({fake_q});- auto cvt_dq = opp::wrap_type<ov::op::v0::Convert>({cvt_q});- auto subtract = opp::optional<ov::op::v1::Subtract>({cvt_dq, opp::any_input()});- auto scale = opp::any_input();- auto multiply = opp::wrap_type<ov::op::v1::Multiply>({subtract, scale});-- // Note: use [=] so pattern nodes stay alive inside the callback.+ const auto pattern = make_unqdq_pattern();++ // Note: capture by value so pattern nodes stay alive inside the callback.ov::matcher_pass_callback callback = [=](opp::Matcher& m) {auto& node_to_output = m.get_pattern_value_map();const auto matched_multiply = ov::as_type_ptr<ov::op::v1::Multiply>(m.get_match_root());- const auto matched_input = node_to_output.at(input);+ const auto matched_input = node_to_output.at(pattern.input);- // A broadcasting zero point or scale makes the chain non-shape-preserving.- if (matched_multiply->get_output_partial_shape(0) != matched_input.get_partial_shape()) {- return false;- }-- if (!node_to_output.count(subtract) && !is_identity_quantizer_without_zp(node_to_output.at(fq_in_low),- node_to_output.at(fq_in_high),- node_to_output.at(fq_out_low),- node_to_output.at(fq_out_high),- node_to_output.at(scale))) {+ if (!is_collapsible(node_to_output, pattern)) {return false;}@@ -125,10 +292,104 @@ public:return true;};- register_matcher(std::make_shared<opp::Matcher>(multiply, "CollapseUNQDQChain"), callback);+ register_matcher(std::make_shared<opp::Matcher>(pattern.multiply, "CollapseUNQDQChain"), callback);}};ov::npuw::CollapseUNQDQ::CollapseUNQDQ() {add_matcher<CollapseUNQDQChain>();}++bool ov::npuw::RescaleFP16OverflowQDQ::run_on_model(const std::shared_ptr<ov::Model>& model) {+ const auto p = make_overflow_pattern();+ bool changed = false;+ for (auto&& node : model->get_ordered_ops()) {+ opp::Matcher matcher(p.root);+ if (!matcher.match(node->output(0))) {+ continue;+ }+ const auto& map = matcher.get_pattern_value_map();+ if (!is_isolated(p, map)) {+ continue;+ }+ const auto fq_in = ov::as_type_ptr<ov::op::v0::FakeQuantize>(map.at(p.in.fake_q).get_node_shared_ptr());+ const auto fq_out = ov::as_type_ptr<ov::op::v0::FakeQuantize>(map.at(p.out.fake_q).get_node_shared_ptr());+ const float range_in = fq_range(fq_in);+ const float range_out = fq_range(fq_out);+ if (!std::isfinite(range_in) || !std::isfinite(range_out) || !(std::max(range_in, range_out) > kF16Max)) {+ continue;+ }++ // If the first chain overflows, its producer already does, so the factor goes on the+ // producer's input; otherwise on the MatMul input. Weights sit on MatMul input 1.+ const bool scale_producer = range_in > kF16Max;+ const auto matmul = map.at(p.matmul).get_node_shared_ptr();+ const auto producer = scale_producer ? fq_in->get_input_node_shared_ptr(0) : matmul;+ if (scale_producer && (!has_single_consumer(producer) || !((ov::is_type<ov::op::v1::Multiply>(producer) &&+ !is_dequantize_multiply(producer, p.in)) ||+ ov::is_type<ov::op::v0::MatMul>(producer)))) {+ continue;+ }+ auto input = producer->input(0);+ if (!input.get_element_type().is_real() || is_dequantize_subtract(input.get_source_output(), p.in)) {+ continue;+ }+ const float range = scale_producer ? std::max(range_in, range_out) : range_out;++ // Validate every new value before touching the graph+ const int k = static_cast<int>(std::ceil(std::log2(range / kRescaleTarget)));+ const double scale = std::ldexp(1.0, -k);+ const auto factor = ov::op::v0::Constant::create(input.get_element_type(), ov::Shape{}, {scale});+ if (factor->cast_vector<double>()[0] != scale) {+ LOG_DEBUG("RescaleFP16OverflowQDQ: 2^-" << k << " is not representable in " << input.get_element_type());+ continue;+ }+ const double eps_scale = scale * scale;+ const auto norm = map.count(p.norm)+ ? ov::as_type_ptr<ov::op::v0::NormalizeL2>(map.at(p.norm).get_node_shared_ptr())+ : nullptr;+ const auto eps_node = norm ? nullptr : map.at(p.eps).get_node_shared_ptr();+ const auto scaled_eps = norm ? nullptr : scale_eps(eps_node->input_value(1), eps_scale);+ const double norm_eps = norm ? norm->get_eps() * eps_scale : 0.0;+ if (norm ? static_cast<double>(static_cast<float>(norm_eps)) != norm_eps : !scaled_eps) {+ LOG_DEBUG("RescaleFP16OverflowQDQ: eps after " << producer->get_friendly_name()+ << " is not representable after scaling");+ continue;+ }++ // Scale eps by s^2 so the normalization stays exact for small activations too+ if (norm) {+ const auto scaled_norm = std::make_shared<ov::op::v0::NormalizeL2>(norm->input_value(0),+ norm->input_value(1),+ static_cast<float>(norm_eps),+ norm->get_eps_mode());+ scaled_norm->set_friendly_name(norm->get_friendly_name());+ ov::copy_runtime_info(norm, scaled_norm);+ ov::replace_node(norm, scaled_norm);+ } else {+ scaled_eps->set_friendly_name(eps_node->get_friendly_name() + "/fp16_rescaled_eps");+ ov::copy_runtime_info(eps_node->get_input_node_shared_ptr(1), scaled_eps);+ eps_node->input(1).replace_source_output(scaled_eps);+ }++ factor->set_friendly_name(producer->get_friendly_name() + "/fp16_rescale_factor");+ const auto multiply = std::make_shared<ov::op::v1::Multiply>(input.get_source_output(), factor);+ multiply->set_friendly_name(producer->get_friendly_name() + "/fp16_rescale");+ ov::copy_runtime_info(producer, {factor, multiply});+ input.replace_source_output(multiply);+ // The FQ bounds stay as calibrated and would quantize the scaled values on a 2^k coarser grid,+ // so remove both chains here, as CollapseUNQDQ does+ for (const auto& [fq, end] :+ {std::pair{fq_in, map.at(p.in.multiply)}, std::pair{fq_out, map.at(p.out.multiply)}}) {+ const auto chain_end = end.get_node_shared_ptr();+ ov::replace_node(chain_end,+ ov::OutputVector{preserve_output_type(fq->input_value(0),+ chain_end->get_output_element_type(0),+ chain_end->get_friendly_name())});+ }+ LOG_INFO("RescaleFP16OverflowQDQ: scaled " << producer->get_friendly_name() << " by 2^-" << k << " for range "+ << range);+ changed = true;+ }+ return changed;+}diff --git a/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/collapse_unqdq.hpp b/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/collapse_unqdq.hppindex ed0d0544047..6e40f8234a1 100644--- a/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/collapse_unqdq.hpp+++ b/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/collapse_unqdq.hpp@@ -14,4 +14,17 @@ public:CollapseUNQDQ();};+// FakeQuantize ranges are the only record of how large an activation gets, and CollapseUNQDQ+// drops them, so run this first. Only the chain UNQDQ -> MatMul -> UNQDQ -> L2 normalization is+// handled, with every intermediate value feeding only the next step. If either FQ range exceeds the+// f16 maximum, the MatMul input (or the input of the first chain's producer, if that chain+// overflows too) is scaled by 2^-k; the normalization cancels the factor once its eps is scaled by+// 2^-2k. Both chains are collapsed together with the rescale, since their calibrated FQ bounds would+// no longer fit the scaled values; the rest of the model is left for CollapseUNQDQ.+class RescaleFP16OverflowQDQ : public ov::pass::ModelPass {+public:+ OPENVINO_MODEL_PASS_RTTI("ov::npuw::RescaleFP16OverflowQDQ");+ bool run_on_model(const std::shared_ptr<ov::Model>& model) override;+};+} // namespace ov::npuwdiff --git a/src/plugins/intel_npu/tests/unit/npuw/pipeline_passes/collapse_unqdq_test.cpp b/src/plugins/intel_npu/tests/unit/npuw/pipeline_passes/collapse_unqdq_test.cppindex 93b14e6e071..0e74b659371 100644--- a/src/plugins/intel_npu/tests/unit/npuw/pipeline_passes/collapse_unqdq_test.cpp+++ b/src/plugins/intel_npu/tests/unit/npuw/pipeline_passes/collapse_unqdq_test.cpp@@ -9,18 +9,29 @@#include <algorithm>#include <gtest/gtest.h>+#include <cmath>++#include "common_test_utils/ov_test_utils.hpp"#include "openvino/core/validation_util.hpp"#include "openvino/op/convolution.hpp"+#include "openvino/op/add.hpp"#include "openvino/op/constant.hpp"#include "openvino/op/convert.hpp"+#include "openvino/op/divide.hpp"#include "openvino/op/fake_quantize.hpp"#include "openvino/op/matmul.hpp"#include "openvino/op/multiply.hpp"+#include "openvino/op/normalize_l2.hpp"#include "openvino/op/parameter.hpp"+#include "openvino/op/power.hpp"+#include "openvino/op/reduce_sum.hpp"#include "openvino/op/reshape.hpp"#include "openvino/op/result.hpp"+#include "openvino/op/sqrt.hpp"#include "openvino/op/subtract.hpp"#include "openvino/op/transpose.hpp"+#include "openvino/pass/manager.hpp"+#include "openvino/runtime/tensor.hpp"namespace {@@ -375,4 +386,325 @@ TEST(CollapseUNQDQPassTest, ConvToMatMulAndUNQDQOrderDoesNotMatter) {}}+constexpr float kOverflowRange = 950796.0f;+constexpr float kEps = 1e-7f;++ov::Output<ov::Node> add_unqdq(const ov::Output<ov::Node>& input, float range, bool swapped_multiply = false) {+ auto fake_quantize = std::make_shared<ov::op::v0::FakeQuantize>(+ input,+ ov::op::v0::Constant::create(ov::element::f32, ov::Shape{}, {-range}),+ ov::op::v0::Constant::create(ov::element::f32, ov::Shape{}, {range}),+ ov::op::v0::Constant::create(ov::element::f32, ov::Shape{}, {0.0f}),+ ov::op::v0::Constant::create(ov::element::f32, ov::Shape{}, {65535.0f}),+ 65536);+ auto quantized_convert = std::make_shared<ov::op::v0::Convert>(fake_quantize, ov::element::u16);+ auto dequantized_convert = std::make_shared<ov::op::v0::Convert>(quantized_convert, ov::element::f32);+ auto subtract =+ std::make_shared<ov::op::v1::Subtract>(dequantized_convert,+ ov::op::v0::Constant::create(ov::element::f32, ov::Shape{}, {32768.0f}));+ auto scale = ov::op::v0::Constant::create(ov::element::f32, ov::Shape{}, {range / 32768.0f});+ return swapped_multiply ? std::make_shared<ov::op::v1::Multiply>(scale, subtract)+ : std::make_shared<ov::op::v1::Multiply>(subtract, scale);+}++ov::Output<ov::Node> rescale(const ov::Output<ov::Node>& input, int k) {+ return std::make_shared<ov::op::v1::Multiply>(+ input,+ ov::op::v0::Constant::create(input.get_element_type(), ov::Shape{}, {std::ldexp(1.0f, -k)}));+}++std::shared_ptr<ov::Node> add_l2_normalize(const ov::Output<ov::Node>& x, bool decomposed, int k) {+ const float eps = kEps * std::ldexp(1.0f, -2 * k);+ auto axes = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, {1});+ if (!decomposed) {+ return std::make_shared<ov::op::v0::NormalizeL2>(x, axes, eps, ov::op::EpsMode::ADD);+ }+ auto square =+ std::make_shared<ov::op::v1::Power>(x, ov::op::v0::Constant::create(ov::element::f32, ov::Shape{}, {2.0f}));+ auto sum = std::make_shared<ov::op::v1::ReduceSum>(square, axes, true);+ auto add =+ std::make_shared<ov::op::v1::Add>(sum, ov::op::v0::Constant::create(ov::element::f32, ov::Shape{}, {eps}));+ return std::make_shared<ov::op::v1::Divide>(x, std::make_shared<ov::op::v0::Sqrt>(add));+}++// Mirrors an MLP feeding a post-norm: Mul_1 -> FQ -> down_proj -> FQ -> L2 normalization+struct MlpOptions {+ float mul_range = kOverflowRange / 4;+ float down_range = kOverflowRange;+ bool decomposed_l2 = false;+ bool residual_add = false;+ bool reshape_before_norm = false;+ bool swapped_multiply = false;+ ov::element::Type type = ov::element::f32;+ // Reference graph state+ int k = 0; // exponent RescaleFP16OverflowQDQ applied, 0 if it left the model alone+ bool collapsed = false; // CollapseUNQDQ ran; RescaleFP16OverflowQDQ collapses the region itself when k != 0+};++std::shared_ptr<ov::Model> build_overflow_mlp_model(const MlpOptions& o) {+ auto up = std::make_shared<ov::op::v0::Parameter>(o.type, ov::Shape{1, 4});+ auto gate = std::make_shared<ov::op::v0::Parameter>(o.type, ov::Shape{1, 4});+ ov::ParameterVector params{up, gate};+ // The first overflowing FQ in topological order decides where the factor goes+ const bool scale_mul = o.k && o.mul_range > 65504.0f;+ const bool scale_down = o.k && !scale_mul;+ const auto qdq = [&](const ov::Output<ov::Node>& input, float range) -> ov::Output<ov::Node> {+ if (!o.collapsed && !o.k) {+ return add_unqdq(input, range, o.swapped_multiply);+ }+ if (input.get_element_type() != ov::element::f32) {+ return std::make_shared<ov::op::v0::Convert>(input, ov::element::f32);+ }+ return input;+ };++ auto mul = std::make_shared<ov::op::v1::Multiply>(scale_mul ? rescale(up, o.k) : up, gate);+ ov::Output<ov::Node> down_input = qdq(mul, o.mul_range);+ auto down = std::make_shared<ov::op::v0::MatMul>(+ scale_down ? rescale(down_input, o.k) : down_input,+ ov::op::v0::Constant::create(ov::element::f32, ov::Shape{4, 4}, std::vector<float>(16, 1.0f)));+ ov::Output<ov::Node> x = qdq(down, o.down_range);+ if (o.residual_add) {+ auto residual = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::Shape{1, 4});+ params.push_back(residual);+ x = std::make_shared<ov::op::v1::Add>(x, residual);+ }+ if (o.reshape_before_norm) {+ x = std::make_shared<ov::op::v1::Reshape>(x,+ ov::op::v0::Constant::create(ov::element::i64, ov::Shape{2}, {1, 4}),+ false);+ }+ return std::make_shared<ov::Model>(+ ov::ResultVector{std::make_shared<ov::op::v0::Result>(add_l2_normalize(x, o.decomposed_l2, o.k))},+ params,+ "overflow_mlp_model");+}++template <class F>+std::shared_ptr<ov::Model> build_mlp(F&& set) {+ MlpOptions options;+ set(options);+ return build_overflow_mlp_model(options);+}++class RescaleFP16OverflowQDQTest : public TransformationTestsF {+protected:+ void SetUp() override {+ TransformationTestsF::SetUp();+ comparator.enable(FunctionsComparator::CmpValues::CONST_VALUES);+ comparator.enable(FunctionsComparator::CmpValues::ATTRIBUTES);+ }+};++TEST_F(RescaleFP16OverflowQDQTest, ScalesRegionEndingInNormalizeL2) {+ model = build_overflow_mlp_model(MlpOptions{});+ manager.register_pass<ov::npuw::RescaleFP16OverflowQDQ>();+ // 950796 / 2^5 = 29712 is the first value under the 32768 target; eps follows with 2^-10+ model_ref = build_mlp([](MlpOptions& o) {+ o.k = 5;+ });+}++TEST_F(RescaleFP16OverflowQDQTest, ScalesRegionEndingInDecomposedL2Normalize) {+ model = build_mlp([](MlpOptions& o) {+ o.decomposed_l2 = true;+ });+ manager.register_pass<ov::npuw::RescaleFP16OverflowQDQ>();+ model_ref = build_mlp([](MlpOptions& o) {+ o.decomposed_l2 = true;+ o.k = 5;+ });+}++TEST_F(RescaleFP16OverflowQDQTest, ScalesSwappedDequantizeMultiply) {+ model = build_mlp([](MlpOptions& o) {+ o.swapped_multiply = true;+ });+ manager.register_pass<ov::npuw::RescaleFP16OverflowQDQ>();+ model_ref = build_mlp([](MlpOptions& o) {+ o.swapped_multiply = true;+ o.k = 5;+ });+}++TEST_F(RescaleFP16OverflowQDQTest, SecondRunKeepsModel) {+ model = build_overflow_mlp_model(MlpOptions{});+ manager.register_pass<ov::npuw::RescaleFP16OverflowQDQ>();+ manager.register_pass<ov::npuw::RescaleFP16OverflowQDQ>();+ model_ref = build_mlp([](MlpOptions& o) {+ o.k = 5;+ });+}++TEST_F(RescaleFP16OverflowQDQTest, ScalesMatMulInputThenCollapses) {+ model = build_mlp([](MlpOptions& o) {+ o.mul_range = 100.0f;+ });+ manager.register_pass<ov::npuw::RescaleFP16OverflowQDQ>();+ manager.register_pass<ov::npuw::CollapseUNQDQ>();+ model_ref = build_mlp([](MlpOptions& o) {+ o.mul_range = 100.0f;+ o.k = 5;+ o.collapsed = true;+ });+}++TEST_F(RescaleFP16OverflowQDQTest, KeepsRegionWithResidualAdd) {+ model = build_mlp([](MlpOptions& o) {+ o.residual_add = true;+ });+ manager.register_pass<ov::npuw::RescaleFP16OverflowQDQ>();+}++TEST_F(RescaleFP16OverflowQDQTest, KeepsRegionWithReshapeBeforeNorm) {+ model = build_mlp([](MlpOptions& o) {+ o.reshape_before_norm = true;+ });+ manager.register_pass<ov::npuw::RescaleFP16OverflowQDQ>();+}++TEST_F(RescaleFP16OverflowQDQTest, KeepsRegionWithoutMatMul) {+ auto up = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::Shape{1, 4});+ auto gate = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::Shape{1, 4});+ auto mul = std::make_shared<ov::op::v1::Multiply>(up, gate);+ auto norm = add_l2_normalize(add_unqdq(mul, kOverflowRange), false, 0);+ model = std::make_shared<ov::Model>(ov::ResultVector{std::make_shared<ov::op::v0::Result>(norm)},+ ov::ParameterVector{up, gate},+ "no_matmul_model");+ manager.register_pass<ov::npuw::RescaleFP16OverflowQDQ>();+}++TEST_F(RescaleFP16OverflowQDQTest, KeepsRangesWithinF16) {+ model = build_mlp([](MlpOptions& o) {+ o.mul_range = 15000.0f;+ o.down_range = 60000.0f;+ });+ manager.register_pass<ov::npuw::RescaleFP16OverflowQDQ>();+}++TEST_F(RescaleFP16OverflowQDQTest, KeepsFactorThatRoundsToZero) {+ // 2^40 needs 2^-25, which is below the smallest f16 subnormal+ model = build_mlp([](MlpOptions& o) {+ o.mul_range = 0x1p40f;+ o.down_range = 60000.0f;+ o.type = ov::element::f16;+ });+ manager.register_pass<ov::npuw::RescaleFP16OverflowQDQ>();+}++TEST_F(RescaleFP16OverflowQDQTest, KeepsRequantizedDequantizeOutput) {+ auto input = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::Shape{1, 4});+ auto norm = add_l2_normalize(add_unqdq(add_unqdq(input, 100.0f), kOverflowRange), false, 0);+ model = std::make_shared<ov::Model>(ov::ResultVector{std::make_shared<ov::op::v0::Result>(norm)},+ ov::ParameterVector{input},+ "requantize_model");+ manager.register_pass<ov::npuw::RescaleFP16OverflowQDQ>();+}++TEST_F(RescaleFP16OverflowQDQTest, KeepsScaledPowerExponent) {+ // The producer also feeds the exponent of a sum of squares, so scaling it would change the power+ auto y = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::Shape{1, 4});+ auto two =+ std::make_shared<ov::op::v1::Multiply>(ov::op::v0::Constant::create(ov::element::f32, ov::Shape{}, {1.0f}),+ ov::op::v0::Constant::create(ov::element::f32, ov::Shape{}, {2.0f}));+ auto axes = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, {1});+ auto sum = std::make_shared<ov::op::v1::ReduceSum>(std::make_shared<ov::op::v1::Power>(y, two), axes, true);+ auto add =+ std::make_shared<ov::op::v1::Add>(sum, ov::op::v0::Constant::create(ov::element::f32, ov::Shape{}, {kEps}));+ auto norm_y = std::make_shared<ov::op::v1::Divide>(y, std::make_shared<ov::op::v0::Sqrt>(add));+ auto two_2d =+ std::make_shared<ov::op::v1::Reshape>(add_unqdq(two, kOverflowRange),+ ov::op::v0::Constant::create(ov::element::i64, ov::Shape{2}, {1, 1}),+ false);+ auto norm_two = add_l2_normalize(two_2d, false, 0);+ model = std::make_shared<ov::Model>(+ ov::ResultVector{std::make_shared<ov::op::v0::Result>(norm_y), std::make_shared<ov::op::v0::Result>(norm_two)},+ ov::ParameterVector{y},+ "power_exponent_model");+ manager.register_pass<ov::npuw::RescaleFP16OverflowQDQ>();+ manager.register_pass<ov::npuw::CollapseUNQDQ>();+ model_ref = model->clone();+ ov::pass::Manager collapse;+ collapse.register_pass<ov::npuw::CollapseUNQDQ>();+ collapse.run_passes(model_ref);+}++TEST_F(RescaleFP16OverflowQDQTest, KeepsMatMulWithDequantizedInput) {+ // A factor on the MatMul input would complete the input chain, and CollapseUNQDQ would drop it+ const auto build = [](bool collapsed) {+ auto input = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::Shape{1, 4});+ auto fake_quantize = std::make_shared<ov::op::v0::FakeQuantize>(+ input,+ ov::op::v0::Constant::create(ov::element::f32, ov::Shape{}, {-100.0f}),+ ov::op::v0::Constant::create(ov::element::f32, ov::Shape{}, {100.0f}),+ ov::op::v0::Constant::create(ov::element::f32, ov::Shape{}, {0.0f}),+ ov::op::v0::Constant::create(ov::element::f32, ov::Shape{}, {65535.0f}),+ 65536);+ auto dequantized = std::make_shared<ov::op::v0::Convert>(+ std::make_shared<ov::op::v0::Convert>(fake_quantize, ov::element::u16),+ ov::element::f32);+ auto subtract = std::make_shared<ov::op::v1::Subtract>(+ dequantized,+ ov::op::v0::Constant::create(ov::element::f32, ov::Shape{}, {32768.0f}));+ ov::Output<ov::Node> down = std::make_shared<ov::op::v0::MatMul>(+ subtract,+ ov::op::v0::Constant::create(ov::element::f32, ov::Shape{4, 4}, std::vector<float>(16, 1.0f)));+ if (!collapsed) {+ down = add_unqdq(down, kOverflowRange);+ }+ return std::make_shared<ov::Model>(+ ov::ResultVector{std::make_shared<ov::op::v0::Result>(add_l2_normalize(down, false, 0))},+ ov::ParameterVector{input},+ "dequantized_matmul_model");+ };+ model = build(false);+ manager.register_pass<ov::npuw::RescaleFP16OverflowQDQ>();+ manager.register_pass<ov::npuw::CollapseUNQDQ>();+ model_ref = build(true);+}++// After CollapseUNQDQ the factor must cancel in the normalization, including for activations small+// enough that eps matters, and must not create inf/NaN for f16 inputs that become subnormal+TEST(RescaleFP16OverflowQDQNumericTest, MatchesCollapseOnlyOutput) {+ const auto run = [](bool rescale, const ov::element::Type& type, float value) {+ const auto model = build_mlp([&](MlpOptions& o) {+ o.decomposed_l2 = true;+ o.type = type;+ });+ ov::pass::Manager manager;+ if (rescale) {+ manager.register_pass<ov::npuw::RescaleFP16OverflowQDQ>();+ }+ manager.register_pass<ov::npuw::CollapseUNQDQ>();+ manager.run_passes(model);+ ov::TensorVector inputs;+ for (auto&& param : model->get_parameters()) {+ inputs.emplace_back(param->get_element_type(), param->get_shape());+ if (param->get_element_type() == ov::element::f16) {+ std::fill_n(inputs.back().data<ov::float16>(), inputs.back().get_size(), ov::float16(value));+ } else {+ std::fill_n(inputs.back().data<float>(), inputs.back().get_size(), value);+ }+ }+ ov::TensorVector outputs{ov::Tensor(ov::element::f32, ov::Shape{1, 4})};+ EXPECT_TRUE(model->evaluate(outputs, inputs));+ return std::vector<float>(outputs[0].data<float>(), outputs[0].data<float>() + outputs[0].get_size());+ };+ // In f16 the factor raises the subnormal threshold by 2^k, so tiny products lose precision; they must+ // still stay finite. Values that remain normal after scaling must match.+ for (const auto& type : {ov::element::f32, ov::element::f16}) {+ for (float value : {0.0f, 1e-3f, 1e-2f, 1.0f, 200.0f}) {+ const auto expected = run(false, type, value);+ const auto actual = run(true, type, value);+ const bool exact = type == ov::element::f32 || value == 0.0f || value >= 1.0f;+ for (std::size_t i = 0; i < expected.size(); ++i) {+ ASSERT_TRUE(std::isfinite(actual[i])) << type << " value=" << value;+ if (exact) {+ EXPECT_NEAR(actual[i], expected[i], 1e-5f * std::fabs(expected[i])) << type << " value=" << value;+ }+ }+ }+ }+}+} // namespace