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: Support asymmetric weights quantization (Opt B) (#26164)
Ujjayant Kadian5b99ebc04270
diff --git a/src/plugins/intel_npu/src/plugin/npuw/partitioning/partitioning.cpp b/src/plugins/intel_npu/src/plugin/npuw/partitioning/partitioning.cppindex bb1905b25ed..1325fc1f1d1 100644--- a/src/plugins/intel_npu/src/plugin/npuw/partitioning/partitioning.cpp+++ b/src/plugins/intel_npu/src/plugin/npuw/partitioning/partitioning.cpp@@ -1627,6 +1627,9 @@ void Partitioner::decompressionCutOff(const std::string& func_name) {// Phi-3 4SymW16A/GPTQrewr.add_matcher<ov::npuw::patterns::SymmZP::DCOFFPassCWAI3>(dcoff_mode, dcoff_type, std::ref(params_to));+ // Asymmetric zeropoints+ rewr.add_matcher<ov::npuw::patterns::AsymmZP::DCOFFPassReshape>(dcoff_mode, dcoff_type, std::ref(params_to));+rewr.run_on_model(f._model);ov::pass::Validate val;diff --git a/src/plugins/intel_npu/src/plugin/npuw/partitioning/patterns/dcoff.cpp b/src/plugins/intel_npu/src/plugin/npuw/partitioning/patterns/dcoff.cppindex 99ff93a6066..857bcd9c93b 100644--- a/src/plugins/intel_npu/src/plugin/npuw/partitioning/patterns/dcoff.cpp+++ b/src/plugins/intel_npu/src/plugin/npuw/partitioning/patterns/dcoff.cpp@@ -56,28 +56,48 @@ ClosureRemap build_remap(const Function& fbody, const DCOFFParams& params_to) {ClosureRemap m;+ using PPtr = std::shared_ptr<ov::op::v0::Parameter>;+ std::unordered_set<PPtr> ban_list;++ for (const auto& scale_pair : params_to.scales) {+ ban_list.insert(scale_pair.first);+ }++ for (const auto& zerop_pair : params_to.zerops_asymm) {+ ban_list.insert(zerop_pair.second);+ }+// FIXME: use indexed() here insteadfor (std::size_t i = fbody._param_offset; i < body_params.size(); i++) {- LOG_DEBUG("Checking the function parameter " << body_params[i]);+ const auto& param = body_params[i];+ LOG_DEBUG("Checking the function parameter " << param);LOG_BLOCK();// First find among scale factors...- auto pscale_iter = params_to.scales.find(body_params[i]);+ auto pscale_iter = params_to.scales.find(param);+ auto pzerop_iter = params_to.zerops_asymm.find(param);if (pscale_iter != params_to.scales.end()) {LOG_DEBUG("This is a Scale factor parameter, will be removed");auto& pscale_weight_param = pscale_iter->second;auto pscale_weight_pindex = fbody._model->get_parameter_index(pscale_weight_param);auto pscale_weight_cindex = pscale_weight_pindex - fbody._param_offset;m.scale_remap[pscale_weight_cindex] = i - fbody._param_offset;- m.params_to_remove.push_back(body_params[i]);- } else {+ m.params_to_remove.push_back(param);+ } else if (pzerop_iter != params_to.zerops_asymm.end()) {+ LOG_DEBUG("There is an Asymmetric zero point corresponding to this parameter, it will be removed");+ auto zerop_pindex = fbody._model->get_parameter_index(pzerop_iter->second);+ auto zerop_cindex = zerop_pindex - fbody._param_offset;+ m.zerop_remap[i - fbody._param_offset] = zerop_cindex;+ m.params_to_remove.push_back(pzerop_iter->second);+ m.closure_remap.push_back(i - fbody._param_offset);+ } else if (ban_list.find(param) == ban_list.end()) {+ // If it's not in the ban list, it's an OK parameter and should be keptLOG_DEBUG("This is an OK parameter, will be kept");- // n++ is the index of `i` herem.closure_remap.push_back(i - fbody._param_offset);}// Process zero points for parameters- auto zerop_iter = params_to.zerops.find(body_params[i]);+ auto zerop_iter = params_to.zerops.find(param);if (zerop_iter != params_to.zerops.end()) {LOG_DEBUG("This parameter requires zero point: " << zerop_iter->second);m.zero_points.push_back(ov::npuw::util::tensor_from_const(zerop_iter->second));@@ -85,7 +105,8 @@ ClosureRemap build_remap(const Function& fbody, const DCOFFParams& params_to) {m.zero_points.push_back(ov::Tensor());}}- NPUW_ASSERT((body_params.size() - fbody._param_offset) == (m.scale_remap.size() + m.closure_remap.size()));+ NPUW_ASSERT((body_params.size() - fbody._param_offset) ==+ (m.scale_remap.size() + m.closure_remap.size() + m.zerop_remap.size()));NPUW_ASSERT((body_params.size() - fbody._param_offset) == m.zero_points.size());LOG_DEBUG("DONE");@@ -105,7 +126,10 @@ void apply_remap(Subgraph& fcall, const ClosureRemap& m) {auto scale_iter = m.scale_remap.find(i);new_scales.push_back(scale_iter != m.scale_remap.end() ? fcall._closure[scale_iter->second] : ov::Tensor());- new_zerops.push_back(m.zero_points[i]);+ // Check for asymmetric zero points and add them to new_zerops+ auto zerop_iter = m.zerop_remap.find(i);+ const auto& zerop = zerop_iter != m.zerop_remap.end() ? fcall._closure[zerop_iter->second] : m.zero_points[i];+ new_zerops.push_back(zerop);}fcall._closure = std::move(new_closure);fcall._scales = std::move(new_scales);@@ -790,6 +814,112 @@ CWAI3::CWAI3(CWAI3::Results scales) {// Implementation TBD} // namespace SymmZP++//------------------------------------------------------------------------------+// Pattern: ASymmZP, weights with asymmetric quantization+//+namespace AsymmZP {+// As seen in asymmetric TinyLlama:+// Since it is ASymm, all zero points for all blocks have different+// values so they will be Parameters but not Constants.+//+// In the diagram below, pattern on the left is identified and+// is modified to pattern in the right if type is promoted to f16+//+// "tensor" "zero point" "scale"+// Parameter:A Parameter:B Parameter:C > Parameter:A+// u4 u4 f16 > f16 <Const>+// : : : > : :+// V : : > V V+// Convert Convert : > Reshape|Convert+// f16 f16 : >+// : : : >+// V V : >+// Subtract : >+// f16 : >+// : : >+// V V >+// Multiply >+// fp16 <Const> >+// : : >+// V V >+// Reshape|Convert >+// : >+// V >+//+DCOFFPassReshape::DCOFFPassReshape(DCOffMode dcoff_mode, ov::element::Type dcoff_type, DCOFFParamRef pref) {+ auto paramA = opp::wrap_type<ov::op::v0::Parameter>();+ auto paramB = opp::wrap_type<ov::op::v0::Parameter>();+ auto paramC = opp::wrap_type<ov::op::v0::Parameter>();+ auto cvtA = opp::wrap_type<ov::op::v0::Convert>({paramA});+ auto cvtB = opp::wrap_type<ov::op::v0::Convert>({paramB});+ auto subtr = opp::wrap_type<ov::op::v1::Subtract>({cvtA, cvtB});+ auto mulply = opp::wrap_type<ov::op::v1::Multiply>({subtr, paramC});++ auto scalar = opp::wrap_type<ov::op::v0::Constant>();+ auto reshpe = opp::wrap_type<ov::op::v1::Reshape>({mulply, scalar});++ auto callback = [=](ov::pass::pattern::Matcher& m) {+ auto& node_to_output = m.get_pattern_value_map();+ auto matched_nodeA = node_to_output.at(paramA).get_node_shared_ptr();+ auto matched_nodeB = node_to_output.at(paramB).get_node_shared_ptr();+ auto matched_nodeC = node_to_output.at(paramC).get_node_shared_ptr();++ NPUW_ASSERT(ov::op::util::is_parameter(matched_nodeA));+ NPUW_ASSERT(ov::op::util::is_parameter(matched_nodeB));+ NPUW_ASSERT(ov::op::util::is_parameter(matched_nodeC));++ auto matched_paramA = std::static_pointer_cast<ov::op::v0::Parameter>(matched_nodeA);+ auto matched_paramB = std::static_pointer_cast<ov::op::v0::Parameter>(matched_nodeB);+ auto matched_paramC = std::static_pointer_cast<ov::op::v0::Parameter>(matched_nodeC);++ if (ov::element::u4 == matched_paramA->get_element_type() &&+ ov::element::u4 == matched_paramB->get_element_type() &&+ ov::element::f16 == matched_paramC->get_element_type()) {+ LOG_DEBUG("Matched: " << matched_paramA << ", set element type to " << dcoff_type);+ matched_paramA->set_element_type(dcoff_type);++ if (dcoff_mode == DCOffMode::CAST_SCALE) {+ NPUW_ASSERT(dcoff_type == ov::element::f16);++ LOG_DEBUG("Matched: " << matched_paramB << " - value to remove...");+ LOG_DEBUG("Matched: " << matched_paramC << " - parameter to remove...");+ LOG_BLOCK();++ // Extra transformation here:+ // - remove Subtract + Multiply,+ // - mark paramC for removal.+ // Reshape will be reconnected to ParamA directly++ // Record mapping from the Scale coeff parameter to the Real weight parameter+ pref.get().zerops_asymm[matched_paramA] = matched_paramB;+ pref.get().scales[matched_paramC] = matched_paramA;++ // Disconnect Multiply and Convert from their outputs+ auto matched_mulply = node_to_output.at(mulply).get_node_shared_ptr();+ auto matched_convrt = node_to_output.at(cvtA).get_node_shared_ptr();+ auto drop_outputs = [](std::shared_ptr<ov::Node> node) {+ for (auto&& node_outputs : node->outputs()) {+ for (auto&& node_reader_port : node_outputs.get_target_inputs()) {+ node_outputs.remove_target_input(node_reader_port);+ }+ }+ };+ LOG_DEBUG("Dropping the connections...");+ drop_outputs(matched_mulply);+ drop_outputs(matched_convrt);++ LOG_DEBUG("Reconnecting the Root...");+ auto matched_reshpe = node_to_output.at(reshpe).get_node_shared_ptr();+ matched_reshpe->input(0).replace_source_output(matched_paramA);+ }+ LOG_DEBUG("Done");+ }+ return false; // root node hasn't changed+ };+ register_matcher(std::make_shared<opp::Matcher>(reshpe, "TagDCOFFReshape"), std::move(callback));+}+} // namespace AsymmZP} // namespace patterns} // namespace npuw} // namespace ovdiff --git a/src/plugins/intel_npu/src/plugin/npuw/partitioning/patterns/dcoff.hpp b/src/plugins/intel_npu/src/plugin/npuw/partitioning/patterns/dcoff.hppindex 83ed575f8af..c0b394616c6 100644--- a/src/plugins/intel_npu/src/plugin/npuw/partitioning/patterns/dcoff.hpp+++ b/src/plugins/intel_npu/src/plugin/npuw/partitioning/patterns/dcoff.hpp@@ -28,8 +28,9 @@ namespace patterns {struct DCOFFParams {using PPtr = std::shared_ptr<ov::op::v0::Parameter>;using CPtr = std::shared_ptr<ov::op::v0::Constant>;- std::unordered_map<PPtr, PPtr> scales; // Closures: a scaling factor -> orig tensor- std::unordered_map<PPtr, CPtr> zerops; // Closures: orig tensor -> a zero point (yes, a reverse...)+ std::unordered_map<PPtr, PPtr> scales; // Closures: a scaling factor -> orig tensor+ std::unordered_map<PPtr, CPtr> zerops; // Closures: orig tensor -> a zero point (yes, a reverse...)+ std::unordered_map<PPtr, PPtr> zerops_asymm; // Closures: orig tensor -> an asymmetric zerop parameter};using DCOFFParamRef = std::reference_wrapper<DCOFFParams>;@@ -37,6 +38,7 @@ using DCOFFParamRef = std::reference_wrapper<DCOFFParams>;struct ClosureRemap {std::vector<std::size_t> closure_remap; // [new closure index] -> orig closure idxstd::map<std::size_t, std::size_t> scale_remap; // orig closure idx -> orig scale idx+ std::map<std::size_t, std::size_t> zerop_remap; // orig closure idx -> orig asymm zero point idxov::ParameterVector params_to_remove;std::vector<ov::Tensor> zero_points; // zero points for closures, if needed@@ -160,6 +162,14 @@ public:} // namespace SymmZP+namespace AsymmZP {+class DCOFFPassReshape : public ov::pass::MatcherPass {+public:+ DCOFFPassReshape(DCOffMode dcoff_mode, ov::element::Type dcoff_type, DCOFFParamRef pref);+};++} // namespace AsymmZP+} // namespace patterns} // namespace npuw} // namespace ovdiff --git a/src/plugins/intel_npu/src/plugin/npuw/util.cpp b/src/plugins/intel_npu/src/plugin/npuw/util.cppindex 46bc874e560..fbfbcc5d35e 100644--- a/src/plugins/intel_npu/src/plugin/npuw/util.cpp+++ b/src/plugins/intel_npu/src/plugin/npuw/util.cpp@@ -860,6 +860,186 @@ void unpack_u4f16(const ov::SoPtr<ov::ITensor>& from,}}+void unpack_u4f16_asymm_zp(const ov::SoPtr<ov::ITensor>& from,+ const ov::SoPtr<ov::ITensor>& zerop,+ const ov::SoPtr<ov::ITensor>& scale,+ const ov::SoPtr<ov::ITensor>& to,+ const ov::npuw::util::UnpackOptions& unpack_options) {+ NPUW_ASSERT(from->is_continuous());+ NPUW_ASSERT(zerop->is_continuous());+ NPUW_ASSERT(scale->is_continuous());+ NPUW_ASSERT(to->is_continuous());+ NPUW_ASSERT(from->get_size() == to->get_size());++ const auto& from_shape = from->get_shape();+ NPUW_ASSERT(from_shape.back() % 64 == 0);++ // 3-channel (group-wise) scale factors are+ // supported.++ const auto& scale_shape = scale->get_shape();+ NPUW_ASSERT(scale_shape.size() == 3);+ if (scale_shape.size() == 3) {+ NPUW_ASSERT(scale_shape[0] == from_shape[0]);+ NPUW_ASSERT(scale_shape[1] == from_shape[1]);+ NPUW_ASSERT(scale_shape[2] == 1);+ }++ const auto& zerop_shape = zerop->get_shape();+ NPUW_ASSERT(zerop_shape.size() == 3);+ if (zerop_shape.size() == 3) {+ NPUW_ASSERT(zerop_shape[0] == from_shape[0]);+ NPUW_ASSERT(zerop_shape[1] == from_shape[1]);+ NPUW_ASSERT(zerop_shape[2] == 1);+ }++ const auto zerop_elem_type = zerop->get_element_type();+ const auto scale_elem_type = scale->get_element_type();+ NPUW_ASSERT(zerop_elem_type == ov::element::u4);+ NPUW_ASSERT(scale_elem_type == ov::element::f16);++ // This conversion combines u4tof32 and f32tof16. Here we+ // - read 256 bits (= 32 bytes, = 64 u4 elements)+ // - write 1024 bits (= 128 bytes, = 64 f16 elements)+ // per every iteration, what translates to (from->size() / 64) iterations++ const std::size_t total = to->get_size();+ const std::size_t stotal = scale->get_size();+ const std::size_t elementsPerScale = total / stotal;++ const uint8_t* const pSrc = static_cast<uint8_t*>(from->data()); // 2 x u4 elements+ const uint8_t* const pZer = static_cast<uint8_t*>(zerop->data()); // 2 x u4 element+ const int8_t* const pScl = static_cast<int8_t*>(scale->data()); // 1 x f16 element+ const int16_t* pDst = static_cast<int16_t*>(to->data()); // 1 x f16 element++ auto unpack_body = [pSrc, pDst, pScl, pZer, elementsPerScale, scale_elem_type, zerop_elem_type, stotal](+ std::size_t sindex,+ std::size_t stride) {+ // number of vectorized operations per scale+ size_t elementsPerScaleVectorized = elementsPerScale / 64;++ uint8_t const* pSrcLocal = pSrc + 32 * elementsPerScaleVectorized * sindex * stride;+ int8_t const* pSclLocal = pScl + scale_elem_type.size() * sindex * stride;+ uint8_t const* pZerLocal = pZer + zerop_elem_type.size() * sindex * stride / 2;+ int16_t* pDstLocal = const_cast<int16_t*>(pDst) + 64 * elementsPerScaleVectorized * sindex * stride;++ // if it is last iteration current stride can be smaller - lets check that+ sindex *= stride;+ const auto jobFinish = std::min(sindex + stride, stotal);++ for (; sindex < jobFinish; sindex++) {+ __m256 svalVec = avx2_load_scale(pSclLocal, scale_elem_type);+ __m256 zvalVec = _mm256_set1_ps(static_cast<float>((sindex % 2 == 0) ? lo4(*pZerLocal) : hi4(*pZerLocal)));++ for (std::size_t index = 0; index < elementsPerScale; index += 64) {+ __m128i* outv[] = {+ reinterpret_cast<__m128i*>(pDstLocal),+ reinterpret_cast<__m128i*>(pDstLocal + 8),+ reinterpret_cast<__m128i*>(pDstLocal + 16),+ reinterpret_cast<__m128i*>(pDstLocal + 24),+ reinterpret_cast<__m128i*>(pDstLocal + 32),+ reinterpret_cast<__m128i*>(pDstLocal + 40),+ reinterpret_cast<__m128i*>(pDstLocal + 48),+ reinterpret_cast<__m128i*>(pDstLocal + 56),+ };+ __m256i himask = _mm256_set1_epi8(static_cast<char>(0xF0));+ __m256i lomask = _mm256_set1_epi8(static_cast<char>(0x0F));++ // loading 256 bit u4 into unalligned memory , so 64 elements+ // cannot use aligned version here like _mm256_load_si256 - segfault even on unit tests+ __m256i xmmData = _mm256_lddqu_si256(reinterpret_cast<__m256i const*>(pSrcLocal));++ // unpacking with interleaving+ __m256i vht = _mm256_and_si256(xmmData, himask);+ __m256i xmmUnpackedLo = _mm256_srli_epi16(vht, 4); // 32 x i8+ __m256i xmmUnpackedHi = _mm256_and_si256(xmmData, lomask); // 32 x i8++ // need 4 portions of 8 x i8 elements+ __m128i unpacked32LoHi = _mm256_castsi256_si128(xmmUnpackedLo); // lower 16 x i8+ __m128i unpacked32LoLo = _mm256_extractf128_si256(xmmUnpackedLo, 1); // higher 16 x i8++ __m128i unpacked32HiHi = _mm256_castsi256_si128(xmmUnpackedHi); // lower 16 x i8+ __m128i unpacked32HiLo = _mm256_extractf128_si256(xmmUnpackedHi, 1); // higher 16 x i8++ // converting to 32 x f16+ __m128i f16LoLo[] = {avx2_u8tof16_hi(unpacked32LoLo, zvalVec, svalVec),+ avx2_u8tof16_lo(unpacked32LoLo, zvalVec, svalVec)};++ __m128i f16LoHi[] = {+ avx2_u8tof16_hi(unpacked32LoHi, zvalVec, svalVec),+ avx2_u8tof16_lo(unpacked32LoHi, zvalVec, svalVec),+ };++ __m128i f16HiLo[] = {avx2_u8tof16_hi(unpacked32HiLo, zvalVec, svalVec),+ avx2_u8tof16_lo(unpacked32HiLo, zvalVec, svalVec)};+ __m128i f16HiHi[] = {avx2_u8tof16_hi(unpacked32HiHi, zvalVec, svalVec),+ avx2_u8tof16_lo(unpacked32HiHi, zvalVec, svalVec)};++ // interleaving back+ __m128i interleaved[] = {_mm_unpacklo_epi16(f16HiHi[0], f16LoHi[0]),+ _mm_unpackhi_epi16(f16HiHi[0], f16LoHi[0]),+ _mm_unpacklo_epi16(f16HiHi[1], f16LoHi[1]),+ _mm_unpackhi_epi16(f16HiHi[1], f16LoHi[1]),+ _mm_unpacklo_epi16(f16HiLo[0], f16LoLo[0]),+ _mm_unpackhi_epi16(f16HiLo[0], f16LoLo[0]),+ _mm_unpacklo_epi16(f16HiLo[1], f16LoLo[1]),+ _mm_unpackhi_epi16(f16HiLo[1], f16LoLo[1])};++ // store the results+ _mm_storeu_si128(outv[0], interleaved[0]);+ _mm_storeu_si128(outv[1], interleaved[1]);+ _mm_storeu_si128(outv[2], interleaved[2]);+ _mm_storeu_si128(outv[3], interleaved[3]);+ _mm_storeu_si128(outv[4], interleaved[4]);+ _mm_storeu_si128(outv[5], interleaved[5]);+ _mm_storeu_si128(outv[6], interleaved[6]);+ _mm_storeu_si128(outv[7], interleaved[7]);++ pSrcLocal += 32; // shift pSrc only by 32 since it is 64 x u4+ pDstLocal += 64; // note pDst is int16_t, so 64 x f16 -> 64 elements+ } // for(index)+ pSclLocal += scale_elem_type.size();+ if (sindex % 2 == 1) {+ pZerLocal += zerop_elem_type.size();+ }+ } // for(sindex)+ };++ size_t stride{1};++ // since scaling is always 64 elements aligned operations, lets partition only in scale shape+ if (unpack_options.nPartitions) {+ std::size_t minPartitions;+ if (!unpack_options.bStrictPartitioning) {+ // some heuristics that every tbb thread workload has to have 2048 x intrinsics operations at least,+ // so in terms of stride, it should be nElementsPerscale/64 * 2048+ const auto nIntrinsicsPerScale = elementsPerScale / 64u;+ auto minScaleStride = 2048u / nIntrinsicsPerScale;+ minScaleStride = std::max<std::size_t>(1u, minScaleStride);+ minPartitions = stotal / minScaleStride;+ minPartitions = std::max<std::size_t>(1u, minPartitions);+ minPartitions = std::min(minPartitions, unpack_options.nPartitions);+ } else {+ minPartitions = unpack_options.nPartitions;+ }++ // calculating stride in scale elements space+ stride = static_cast<size_t>(stotal / minPartitions);+ }++ const size_t numWork = (stotal + stride - 1) / stride;++ if (unpack_options.bUseOvParallelFor) {+ ov::parallel_for(numWork, [unpack_body, stride](size_t index) {+ unpack_body(index, stride);+ });+ } else {+ for (std::size_t index = 0; index < numWork; index++) {+ unpack_body(index, stride);+ }+ }+}+void unpack_u4f16_z(const ov::SoPtr<ov::ITensor>& from,const ov::SoPtr<ov::ITensor>& zerop,const ov::SoPtr<ov::ITensor>& scale,@@ -1121,6 +1301,11 @@ void ov::npuw::util::unpack(const ov::SoPtr<ov::ITensor>& from,// - [32, 1, 4096].*[32, 128, 4096]// - [32, 1, 11008].*[32, 128, 11008]// - [86, 1, 4096].*[86, 128, 4096]+ // unpack_u4f16_asymm_zp:+ // - [256, 16, 1].*[256, 16, 128]+ // - [2048, 16, 1].*[2048, 16, 128]+ // - [5632, 16, 1].*[5632, 16, 128]+ // Zero Point Shapes: [256, 16, 1], [2048, 16, 1], [5632, 16, 1]// Unsupported Case for scale tensor:// - [s1, 1, s2, 1, s3]@@ -1132,7 +1317,11 @@ void ov::npuw::util::unpack(const ov::SoPtr<ov::ITensor>& from,unpack_u4f16_z(from, zerop, scale, to, unpack_options);} else if (scale_shape.size() == 3 && scale_shape[0] == from_shape[0] && scale_shape[1] == from_shape[1] &&scale_shape[2] == 1) {- unpack_u4f16(from, zerop, scale, to, unpack_options);+ if (zerop->get_size() == 1) {+ unpack_u4f16(from, zerop, scale, to, unpack_options);+ } else {+ unpack_u4f16_asymm_zp(from, zerop, scale, to, unpack_options);+ }} else if (scale_shape.size() == 2 && scale_shape[0] == from_shape[0] && scale_shape[1] == 1) {unpack_u4f16(from, zerop, scale, to, unpack_options);} else {