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
Transpose/Permute/Concat/To_f16 optimization (#30899)
Ding Zhangc8f8ab77db2c
diff --git a/src/plugins/intel_npu/src/plugin/CMakeLists.txt b/src/plugins/intel_npu/src/plugin/CMakeLists.txtindex 87846dbe43f..3f6a205ecb5 100644--- a/src/plugins/intel_npu/src/plugin/CMakeLists.txt+++ b/src/plugins/intel_npu/src/plugin/CMakeLists.txt@@ -50,7 +50,7 @@ cross_compiled_file(${TARGET_NAME}ARCH AVX2 ANYnpuw/util_xarch.cppAPI npuw/util_xarch.hpp- NAME unpack_i4i8 unpack_u4i8 unpack_i4f16 unpack_i4f16_scale unpack_i4f16_z unpack_u4f16 unpack_u4f16_scale_zp unpack_u4f16_asymm_zp unpack_u4f16_z unpack_u4f32 unpack_i8f16 unpack_i8f16_scale unpack_u8f16 to_f16 copy_row_as_column+ NAME unpack_i4i8 unpack_u4i8 unpack_i4f16 unpack_i4f16_scale unpack_i4f16_z unpack_u4f16 unpack_u4f16_scale_zp unpack_u4f16_asymm_zp unpack_u4f16_z unpack_u4f32 unpack_i8f16 unpack_i8f16_scale unpack_u8f16 to_f16 copy_row_as_column transpose_i4 transpose_f16 transpose_f32NAMESPACE ov::npuw::util::XARCH)diff --git a/src/plugins/intel_npu/src/plugin/npuw/util.cpp b/src/plugins/intel_npu/src/plugin/npuw/util.cppindex bb3db2123e6..83a2ab4c038 100644--- a/src/plugins/intel_npu/src/plugin/npuw/util.cpp+++ b/src/plugins/intel_npu/src/plugin/npuw/util.cpp@@ -633,43 +633,25 @@ ov::Tensor ov::npuw::util::transpose(const ov::Tensor& t) {const auto IN_ROWS = shape[0] * shape[1];const auto IN_COLS = shape[2];- for (std::size_t i = 0; i < IN_ROWS; i++) {- for (std::size_t j = 0; j < IN_COLS; j++) {- switch (t.get_element_type()) {- case ov::element::i4:- twrite_4b(tnew, tread_4b(t, i, j, IN_COLS), j, i, IN_ROWS);- break;- case ov::element::f32:- twrite<float>(tnew, tread<float>(t, i, j, IN_COLS), j, i, IN_ROWS);- break;- default:- NPUW_ASSERT(false && "Element type is not supported yet");- }- }- }- return tnew;-}-template <typename T>-void permute120(const ov::Tensor& src, ov::Tensor& dst) {- const ov::Shape src_shape = src.get_shape();- const ov::Shape dst_shape = dst.get_shape();- NPUW_ASSERT(src_shape.size() == 3); // Yes, so far only transpose 3D tensors-- const T* pSrc = static_cast<const T*>(src.data());- T* pDst = static_cast<T*>(dst.data());-- // DSTs [b,r,c] map to SRC's [r,c,b]-- for (std::size_t b = 0; b < dst_shape[0]; b++) {- for (std::size_t r = 0; r < dst_shape[1]; r++) {- for (std::size_t c = 0; c < dst_shape[2]; c++) {- auto dst_idx = b * dst_shape[1] * dst_shape[2] + r * dst_shape[2] + c;- auto src_idx = r * src_shape[1] * src_shape[2] + c * src_shape[1] + b;- pDst[dst_idx] = pSrc[src_idx];- }- }+ switch (t.get_element_type()) {+ case ov::element::i4: {+ NPUW_ASSERT(shape[2] % 2 == 0);+ const uint8_t* src = static_cast<const uint8_t*>(t.data());+ uint8_t* dst = static_cast<uint8_t*>(tnew.data());+ ov::npuw::util::XARCH::transpose_i4(src, dst, IN_ROWS, IN_COLS);+ break;+ }+ case ov::element::f32: {+ const float* src = static_cast<const float*>(t.data());+ float* dst = static_cast<float*>(tnew.data());+ ov::npuw::util::XARCH::transpose_f32(src, dst, IN_ROWS, IN_COLS);+ break;}+ default:+ NPUW_ASSERT(false && "Element type is not supported yet");+ }+ return tnew;}ov::Tensor ov::npuw::util::permute(const ov::Tensor& t, const std::vector<std::size_t>& axes) {@@ -683,76 +665,90 @@ ov::Tensor ov::npuw::util::permute(const ov::Tensor& t, const std::vector<std::st.get_element_type() == ov::element::f16);ov::Shape tshape = {shape[0], shape[2], shape[1]};ov::Tensor tnew(t.get_element_type(), tshape);-- for (std::size_t p = 0; p < shape[0]; p++) {- for (std::size_t r = 0; r < shape[1]; r++) {- for (std::size_t c = 0; c < shape[2]; c++) {- switch (t.get_element_type()) {- case ov::element::i4:- twrite_4b(tnew, tread_4b(t, p * shape[1] + r, c, shape[2]), p * shape[2] + c, r, shape[1]);- break;- case ov::element::f32:- twrite<float>(tnew,- tread<float>(t, p * shape[1] + r, c, shape[2]),- p * shape[2] + c,- r,- shape[1]);- break;- case ov::element::f16:- twrite<uint16_t>(tnew,- tread<uint16_t>(t, p * shape[1] + r, c, shape[2]),- p * shape[2] + c,- r,- shape[1]);- break;- default:- NPUW_ASSERT(false && "Element type is not supported yet");- }- }- }+ switch (t.get_element_type()) {+ case ov::element::i4: {+ NPUW_ASSERT(shape[2] % 2 == 0);+ const uint8_t* src = static_cast<const uint8_t*>(t.data());+ uint8_t* dst = static_cast<uint8_t*>(tnew.data());+ ov::parallel_for(shape[0], [&](size_t p) {+ const uint8_t* src_ptr = src + p * shape[1] * shape[2];+ uint8_t* dst_ptr = dst + p * shape[1] * shape[2];+ ov::npuw::util::XARCH::transpose_i4(src_ptr, dst_ptr, shape[1], shape[2]);+ });+ break;+ }+ case ov::element::f32: {+ const float* src = static_cast<const float*>(t.data());+ float* dst = static_cast<float*>(tnew.data());+ ov::parallel_for(shape[0], [&](size_t p) {+ const float* src_ptr = src + p * shape[1] * shape[2];+ float* dst_ptr = dst + p * shape[1] * shape[2];+ ov::npuw::util::XARCH::transpose_f32(src_ptr, dst_ptr, shape[1], shape[2]);+ });+ break;+ }+ case ov::element::f16: {+ const uint16_t* src = static_cast<const uint16_t*>(t.data());+ uint16_t* dst = static_cast<uint16_t*>(tnew.data());+ ov::parallel_for(shape[0], [&](size_t p) {+ const uint16_t* src_ptr = src + p * shape[1] * shape[2];+ uint16_t* dst_ptr = dst + p * shape[1] * shape[2];+ ov::npuw::util::XARCH::transpose_f16(src_ptr, dst_ptr, shape[1], shape[2]);+ });+ break;+ }+ default:+ NPUW_ASSERT(false && "Element type is not supported yet");}return tnew;} else if (axes[0] == 1 && axes[1] == 0 && axes[2] == 2) {NPUW_ASSERT(t.get_element_type() == ov::element::i4 || t.get_element_type() == ov::element::f16);ov::Shape tshape = {shape[1], shape[0], shape[2]};ov::Tensor tnew(t.get_element_type(), tshape);-- // Iterate over output tensor coordinates- for (std::size_t p = 0; p < tshape[0]; p++) {- for (std::size_t r = 0; r < tshape[1]; r++) {- for (std::size_t c = 0; c < tshape[2]; c++) {- switch (t.get_element_type()) {- case ov::element::i4:- twrite_4b(tnew,- tread_4b(t, r, p * shape[2] + c, shape[1] * shape[2]),- p * tshape[1] + r,- c,- tshape[2]);- break;- case ov::element::f16:- twrite<uint16_t>(tnew,- tread<uint16_t>(t, r, p * shape[2] + c, shape[1] * shape[2]),- p * tshape[1] + r,- c,- tshape[2]);- break;- default:- NPUW_ASSERT(false && "Element type is not supported yet");- }+ switch (t.get_element_type()) {+ case ov::element::i4: {+ NPUW_ASSERT(shape[2] % 2 == 0);+ const uint8_t* src = static_cast<const uint8_t*>(t.data());+ uint8_t* dst = static_cast<uint8_t*>(tnew.data());+ for (size_t p = 0; p < shape[0]; ++p) {+ for (size_t r = 0; r < shape[1]; ++r) {+ std::copy_n(&src[(p * shape[1] * shape[2] + r * shape[2]) / 2],+ shape[2] / 2,+ &dst[(r * shape[0] * shape[2] + p * shape[2]) / 2]);}}+ break;+ }+ case ov::element::f16: {+ const uint16_t* src = static_cast<const uint16_t*>(t.data());+ uint16_t* dst = static_cast<uint16_t*>(tnew.data());+ ov::parallel_for2d(shape[0], shape[1], [&](size_t p, size_t r) {+ const size_t src_off = (p * shape[1] + r) * shape[2];+ const size_t dst_off = (r * shape[0] + p) * shape[2];+ std::copy_n(src + src_off, shape[2], dst + dst_off);+ });+ break;+ }+ default:+ NPUW_ASSERT(false && "Element type is not supported yet");}return tnew;} else if (axes[0] == 1 && axes[1] == 2 && axes[2] == 0) {ov::Shape tshape = {shape[1], shape[2], shape[0]};ov::Tensor tnew(t.get_element_type(), tshape);switch (t.get_element_type()) {- case ov::element::f32:- permute120<uint32_t>(t, tnew);+ case ov::element::f32: {+ const float* src = static_cast<const float*>(t.data());+ float* dst = static_cast<float*>(tnew.data());+ ov::npuw::util::XARCH::transpose_f32(src, dst, shape[0], shape[1] * shape[2]);break;- case ov::element::f16:- permute120<uint16_t>(t, tnew);+ }+ case ov::element::f16: {+ const uint16_t* src = static_cast<const uint16_t*>(t.data());+ uint16_t* dst = static_cast<uint16_t*>(tnew.data());+ ov::npuw::util::XARCH::transpose_f16(src, dst, shape[0], shape[1] * shape[2]);break;+ }default:NPUW_ASSERT(false && "Element type is not supported yet");}@@ -768,7 +764,6 @@ ov::Tensor ov::npuw::util::concat(const std::vector<ov::Tensor>& tt, std::size_tconst auto type = tt.front().get_element_type();auto shape = tt.front().get_shape();std::size_t new_dim = 0;-std::vector<std::size_t> offsets;std::vector<std::size_t> lens;for (auto&& t : tt) {@@ -793,24 +788,26 @@ ov::Tensor ov::npuw::util::concat(const std::vector<ov::Tensor>& tt, std::size_tuint8_t* pDst = static_cast<uint8_t*>(tnew.data());const bool is_4bit = (type == ov::element::i4 || type == ov::element::u4);- for (std::size_t t_idx = 0; t_idx < tt.size(); t_idx++) {+ ov::parallel_for(tt.size(), [&](size_t t_idx) {const uint8_t* pSrc = static_cast<const uint8_t*>(tt[t_idx].data());const auto copy_size = lens[t_idx] * shape[1] * shape[2];const auto copy_len = is_4bit ? copy_size / 2 : copy_size * type.size();- std::copy_n(pSrc, copy_len, pDst);- pDst += copy_len;- }+ const auto dst_offset =+ is_4bit ? offsets[t_idx] * shape[1] * shape[2] / 2 : offsets[t_idx] * shape[1] * shape[2] * type.size();+ uint8_t* pDstIdx = pDst + dst_offset;++ std::copy_n(pSrc, copy_len, pDstIdx);+ });return tnew;} else if (axis == 2) {ov::Tensor tnew(tt.front().get_element_type(), shape);uint8_t* pDst = static_cast<uint8_t*>(tnew.data());const bool is_4bit = (type == ov::element::i4 || type == ov::element::u4);- for (std::size_t t_idx = 0; t_idx < tt.size(); t_idx++) {+ ov::parallel_for(tt.size(), [&](size_t t_idx) {const auto& t_src = tt[t_idx];-for (std::size_t r = 0; r < shape[0] * shape[1]; r++) {const auto r_offset = is_4bit ? new_dim * r / 2 : new_dim * r * type.size();const auto c_offset = is_4bit ? offsets[t_idx] / 2 : offsets[t_idx] * type.size();@@ -823,7 +820,7 @@ ov::Tensor ov::npuw::util::concat(const std::vector<ov::Tensor>& tt, std::size_tstd::copy_n(pSrcRow, copy_len, pDstRow);}- }+ });return tnew;} else {NPUW_ASSERT(false && "Not supported yet");diff --git a/src/plugins/intel_npu/src/plugin/npuw/util_xarch.cpp b/src/plugins/intel_npu/src/plugin/npuw/util_xarch.cppindex 5d516a4a059..09b25b51b48 100644--- a/src/plugins/intel_npu/src/plugin/npuw/util_xarch.cpp+++ b/src/plugins/intel_npu/src/plugin/npuw/util_xarch.cpp@@ -39,6 +39,23 @@ inline int8_t upc(int8_t h) {return h | (-((h & (1 << 3)) >> 3) & (-8));}+inline int32_t pack_4bit_avx2_reduction(__m256i ymm) {+ __m256i mask = _mm256_set1_epi32(0xF);+ ymm = _mm256_and_si256(ymm, mask);++ __m256i shifts = _mm256_set_epi32(28, 24, 20, 16, 12, 8, 4, 0);+ ymm = _mm256_sllv_epi32(ymm, shifts);++ __m128i low = _mm256_castsi256_si128(ymm);+ __m128i high = _mm256_extracti128_si256(ymm, 1);+ low = _mm_add_epi32(low, high);++ low = _mm_add_epi32(low, _mm_srli_si128(low, 8));+ low = _mm_add_epi32(low, _mm_srli_si128(low, 4));++ return _mm_cvtsi128_si32(low);+}+// NOTE: This routine implements the NEW ORDER# define avx2_i4toi8(vinput, vout0, vout1) \{ \@@ -1413,15 +1430,16 @@ ov::Tensor ov::npuw::util::XARCH::to_f16(const ov::Tensor& t) {#if defined(HAVE_AVX2)const float* psrc = t.data<float>();uint8_t* pdst = static_cast<uint8_t*>(tnew.data());+ const std::size_t nblocks = t.get_size() / 8;- for (std::size_t i = 0; i < t.get_size() / 8; i++) {- __m256 vsrc = _mm256_loadu_ps(psrc);+ ov::parallel_for(nblocks, [&](std::size_t i) {+ const float* psrc_block = psrc + i * 8;+ uint8_t* pdst_block = pdst + i * 16; // 8 * 2 bytes for f16+ __m256 vsrc = _mm256_loadu_ps(psrc_block);__m128i vout = _mm256_cvtps_ph(vsrc, _MM_FROUND_TO_NEAREST_INT);- __m128i* pout = reinterpret_cast<__m128i*>(pdst);+ __m128i* pout = reinterpret_cast<__m128i*>(pdst_block);_mm_storeu_si128(pout, vout);- psrc += 8; // offset in sizeof(float)- pdst += (8 * 2); // offset in bytes- }+ });#elseOPENVINO_THROW("AVX2 support is necessary but it's not enabled!");#endif@@ -1473,3 +1491,133 @@ void ov::npuw::util::XARCH::copy_row_as_column(const ov::SoPtr<ov::ITensor>& frofrom->copy_to(to._ptr);#endif}++void ov::npuw::util::XARCH::transpose_i4(const uint8_t* src, uint8_t* dst, size_t rows, size_t cols) {+#if defined(HAVE_AVX2)+ size_t c_step = 8;+ size_t r_step = 8;++ size_t cols32 = cols / c_step;+ size_t rows32 = rows / r_step;++ // lambda: get int32 pointer for each row of src.+ auto get_src_int32 = [&](size_t r, size_t c, size_t i) {+ return reinterpret_cast<const int32_t*>(&src[(r * r_step + i) * (cols / 2)])[c];+ };+ // lambda: get int32 pointer for each column of dst.+ auto get_dst_int32 = [&](size_t r, size_t c, size_t i) {+ return reinterpret_cast<int32_t*>(&dst[(c * c_step + i) * (rows / 2)]) + r;+ };++ // Main block processing.+ for (size_t c = 0; c < cols32; ++c) {+ for (size_t r = 0; r < rows32; ++r) {+ // For each row of src, recalculate the pointer.+ __m256i column = _mm256_set_epi32(get_src_int32(r, c, 7),+ get_src_int32(r, c, 6),+ get_src_int32(r, c, 5),+ get_src_int32(r, c, 4),+ get_src_int32(r, c, 3),+ get_src_int32(r, c, 2),+ get_src_int32(r, c, 1),+ get_src_int32(r, c, 0));++ for (int i = 0; i < 8; ++i) {+ __m256i shifted = _mm256_srli_epi32(column, 4 * i);+ *get_dst_int32(r, c, i) = pack_4bit_avx2_reduction(shifted);+ }+ }+ }++ size_t tail_cols = cols % c_step;+ size_t tail_rows = rows % r_step;++ auto naive_transpose = [&](size_t r_start, size_t r_end, size_t c_start, size_t c_end) {+ for (size_t r = r_start; r < r_end; ++r) {+ for (size_t c = c_start; c < c_end; ++c) {+ size_t src_idx = r * cols + c;+ uint8_t val = (src[src_idx / 2] >> ((src_idx % 2) * 4)) & 0x0F;+ size_t dst_idx = c * rows + r;+ dst[dst_idx / 2] &= (dst_idx % 2 == 0) ? 0xF0 : 0x0F;+ dst[dst_idx / 2] |= (dst_idx % 2 == 0) ? (val & 0x0F) : ((val & 0x0F) << 4);+ }+ }+ };++ if (tail_cols > 0) {+ naive_transpose(0, rows - tail_rows, cols - tail_cols, cols);+ }+ if (tail_rows > 0) {+ naive_transpose(rows - tail_rows, rows, 0, cols - tail_cols);+ }+ if (tail_cols > 0 && tail_rows > 0) {+ naive_transpose(rows - tail_rows, rows, cols - tail_cols, cols);+ }+#else+ OPENVINO_THROW("AVX2 support is necessary but it's not enabled!");+#endif+}++void ov::npuw::util::XARCH::transpose_f16(const uint16_t* src, uint16_t* dst, size_t rows, size_t cols) {+#if defined(HAVE_AVX2)+ const size_t blockSize = 16; // AVX2 can handle 8 floats per register.+ ov::parallel_for(cols, [&](size_t c) {+ size_t r = 0;+ for (; r + blockSize <= rows; r += blockSize) {+ // Gather 8 elements from column j, rows i..i+7+ __m256i gathered = _mm256_set_epi16(src[(r + 15) * cols + c],+ src[(r + 14) * cols + c],+ src[(r + 13) * cols + c],+ src[(r + 12) * cols + c],+ src[(r + 11) * cols + c],+ src[(r + 10) * cols + c],+ src[(r + 9) * cols + c],+ src[(r + 8) * cols + c],+ src[(r + 7) * cols + c],+ src[(r + 6) * cols + c],+ src[(r + 5) * cols + c],+ src[(r + 4) * cols + c],+ src[(r + 3) * cols + c],+ src[(r + 2) * cols + c],+ src[(r + 1) * cols + c],+ src[(r + 0) * cols + c]);++ // Store this column as a row in transposed matrix+ _mm256_storeu_si256(reinterpret_cast<__m256i*>(dst + c * rows + r), gathered);+ }+ for (; r < rows; ++r) {+ dst[c * rows + r] = src[r * cols + c];+ }+ });+#else+ OPENVINO_THROW("AVX2 support is necessary but it's not enabled!");+#endif+}++void ov::npuw::util::XARCH::transpose_f32(const float* src, float* dst, size_t rows, size_t cols) {+#if defined(HAVE_AVX2)+ const size_t blockSize = 8; // AVX2 can handle 8 floats per register.+ ov::parallel_for(cols, [&](size_t c) {+ size_t r = 0;+ for (; r + blockSize <= rows; r += blockSize) {+ // Gather 8 elements from column j, rows i..i+7+ __m256 gathered = _mm256_set_ps(src[(r + 7) * cols + c],+ src[(r + 6) * cols + c],+ src[(r + 5) * cols + c],+ src[(r + 4) * cols + c],+ src[(r + 3) * cols + c],+ src[(r + 2) * cols + c],+ src[(r + 1) * cols + c],+ src[(r + 0) * cols + c]);++ // Store this column as a row in transposed matrix+ _mm256_storeu_ps(&dst[c * rows + r], gathered);+ }+ for (; r < rows; ++r) {+ dst[c * rows + r] = src[r * cols + c];+ }+ });+#else+ OPENVINO_THROW("AVX2 support is necessary but it's not enabled!");+#endif+}diff --git a/src/plugins/intel_npu/src/plugin/npuw/util_xarch.hpp b/src/plugins/intel_npu/src/plugin/npuw/util_xarch.hppindex 9148ba0106f..0c2e8ee1d80 100644--- a/src/plugins/intel_npu/src/plugin/npuw/util_xarch.hpp+++ b/src/plugins/intel_npu/src/plugin/npuw/util_xarch.hpp@@ -84,6 +84,10 @@ ov::Tensor to_f16(const ov::Tensor& t);void copy_row_as_column(const ov::SoPtr<ov::ITensor>& from, const ov::SoPtr<ov::ITensor>& to);+void transpose_i4(const uint8_t* src, uint8_t* dst, size_t rows, size_t cols);+void transpose_f16(const uint16_t* src, uint16_t* dst, size_t rows, size_t cols);+void transpose_f32(const float* src, float* dst, size_t rows, size_t cols);+} // namespace XARCH} // namespace util} // namespace npuwdiff --git a/src/plugins/intel_npu/tests/unit/npuw/permute.cpp b/src/plugins/intel_npu/tests/unit/npuw/permute.cppnew file mode 100644index 00000000000..522ef2a64b1--- /dev/null+++ b/src/plugins/intel_npu/tests/unit/npuw/permute.cpp@@ -0,0 +1,256 @@+// Copyright (C) 2024 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#ifdef HAVE_AVX2+# include "permute.hpp"++namespace details {++// Permute function.+template <typename T, bool Int4 = false>+void permute(const T* input, T* output, const std::vector<size_t>& dims, const std::vector<size_t>& order) {+ static_assert(!Int4 || (Int4 && std::is_same_v<T, uint8_t>), "For int4 data input data must be of type uint8_t");++ size_t ndim = dims.size();+ assert(order.size() == ndim);++ // Compute new dims.+ std::vector<size_t> new_dims = details::reorder(dims, order);++ // Compute strides.+ std::vector<size_t> old_strides = details::compute_strides(dims);+ std::vector<size_t> new_strides = details::compute_strides(new_dims);++ size_t total = std::accumulate(dims.begin(), dims.end(), size_t(1), std::multiplies<size_t>());++ // For each index in output, compute corresponding input index.+ // Use a flat index and unravel it to multi-index in new order, then map to old order.+ for (size_t out_idx = 0; out_idx < total; ++out_idx) {+ // Unravel out_idx to multi-index in new_dims.+ std::vector<size_t> new_multi(ndim);+ size_t tmp = out_idx;+ for (size_t i = 0; i < ndim; ++i) {+ new_multi[i] = tmp / new_strides[i];+ tmp = tmp % new_strides[i];+ }+ // Map new_multi to old_multi.+ std::vector<size_t> old_multi(ndim);+ for (size_t i = 0; i < ndim; ++i)+ old_multi[order[i]] = new_multi[i];++ // Compute flat input index.+ size_t in_idx = 0;+ for (size_t i = 0; i < ndim; ++i)+ in_idx += old_multi[i] * old_strides[i];++ if constexpr (Int4) {+ uint8_t in_byte = input[in_idx / 2];+ uint8_t in_val = (in_idx % 2 == 0) ? (in_byte & 0x0F) : ((in_byte >> 4) & 0x0F);++ size_t out_byte_idx = out_idx / 2;+ if (out_idx % 2 == 0) {+ output[out_byte_idx] = (output[out_byte_idx] & 0xF0) | (in_val & 0x0F);+ } else {+ output[out_byte_idx] = (output[out_byte_idx] & 0x0F) | ((in_val & 0x0F) << 4);+ }+ } else {+ output[out_idx] = input[in_idx];+ }+ }+}++} // namespace details++namespace {++void PermuteTestsBase::make_input() {+ size_t nElements = shape_size(input_shape);++ ASSERT_EQ((type.bitwidth() * nElements) % 8, 0)+ << "Input len has to be byte boundary aligned, but was " << type.bitwidth() * nElements << " bits";+ const size_t nBytes = type.bitwidth() * nElements / 8;++ input.resize(nBytes);+ ref_output.resize(nBytes);+ output.resize(nBytes);++ std::fill(ref_output.begin(), ref_output.end(), 0);+ std::fill(output.begin(), output.end(), 0);++ std::mt19937 rng(42); // Fixed seed for reproducibility+ std::uniform_int_distribution<int> dist(0, 100);++ for (size_t i = 0; i < nBytes; ++i) {+ input[i] = static_cast<int8_t>(dist(rng));+ }++ inTensor = ov::Tensor(type, input_shape, input.data());+}++void PermuteTestsBase::SetUp(const PermuteTestsParams& getParam) {+ ShapesInitializer shapeInit;++ std::tie(type, shapeInit, axes) = getParam;++ std::vector<int> input;+ shapeInit(input);++ input_shape = ov::Shape{input.begin(), input.end()};++ make_input();++ make_ref_output();+}++std::string PermuteTestsBase::ToString() const {+ std::ostringstream result;+ result << (isNegative() ? "NEGATIVE_" : "") << "[";++ for (size_t i = 0; i != input_shape.size(); i++) {+ result << input_shape[i] << ((i + 1 == input_shape.size()) ? "" : "x");+ }+ result << "]"+ << "_type_" << type;++ result << "_axis";++ for (size_t i = 0; i < axes.size(); i++) {+ result << "_" << axes[i];+ }++ return result.str();+}++/**+ * Negative test cases has to be carefully reviewed, to still remain positive runs at some points+ * @return+ */+bool PermuteTestsBase::isNegative() const {+ return false;+}++void PermuteTestsBase::make_ref_output() {+ std::vector<size_t> dims(input_shape.begin(), input_shape.end());+ if (type == ov::element::f16) {+ details::permute<uint16_t>(reinterpret_cast<const uint16_t*>(input.data()),+ reinterpret_cast<uint16_t*>(ref_output.data()),+ dims,+ axes);+ } else if (type == ov::element::f32) {+ details::permute<float>(reinterpret_cast<const float*>(input.data()),+ reinterpret_cast<float*>(ref_output.data()),+ dims,+ axes);+ } else if (type == ov::element::i4) {+ details::permute<uint8_t, true>(reinterpret_cast<const uint8_t*>(input.data()),+ reinterpret_cast<uint8_t*>(ref_output.data()),+ dims,+ axes);+ } else {+ throw std::runtime_error("Unsupported element type in PermuteTestsBase::make_ref_output");+ }+}++TEST_P(PermuteTests, permute) {+ ASSERT_NO_THROW_WITH_MESSAGE(outTensor = ov::npuw::util::permute(inTensor, axes));+ int8_t* dst = static_cast<int8_t*>(outTensor.data());+ output = std::vector<int8_t>(dst, dst + output.size());+ ASSERT_TRUE(details::ArraysMatch(output, ref_output));+}++const auto TestCases201 = ::testing::Combine(+ ::testing::ValuesIn({ov::element::Type_t::i4, ov::element::Type_t::f32}),+ ::details::ShapesIn({Tensors{input={1, 2, 4};+}+, Tensors {+ input = {1, 10, 128};+}+, Tensors {+ input = {1, 16, 256};+}+, Tensors {+ input = {1, 16, 300};+}+}),+::testing::ValuesIn(+ {+ std::vector<std::size_t>({2, 0, 1})+}+)+);++INSTANTIATE_TEST_SUITE_P(PermuteTests201, PermuteTests, TestCases201, PermuteTests::getTestCaseName);++const auto TestCases021 = ::testing::Combine(+ ::testing::ValuesIn({ov::element::Type_t::i4, ov::element::Type_t::f16, ov::element::Type_t::f32}),+ ::details::ShapesIn({Tensors{input={1, 10, 16};+}+, Tensors {+ input = {1, 10, 128};+}+, Tensors {+ input = {1, 16, 256};+}+, Tensors {+ input = {1, 16, 300};+}+}),+::testing::ValuesIn(+ {+ std::vector<std::size_t>({0, 2, 1})+}+)+);++INSTANTIATE_TEST_SUITE_P(PermuteTests021, PermuteTests, TestCases021, PermuteTests::getTestCaseName);++const auto TestCases102 = ::testing::Combine(+ ::testing::ValuesIn({ov::element::Type_t::i4, ov::element::Type_t::f16}),+ ::details::ShapesIn({Tensors{input={1, 10, 16};+}+, Tensors {+ input = {1, 10, 128};+}+, Tensors {+ input = {1, 16, 256};+}+, Tensors {+ input = {1, 16, 300};+}+}),+::testing::ValuesIn(+ {+ std::vector<std::size_t>({1, 0, 2})+}+)+);++INSTANTIATE_TEST_SUITE_P(PermuteTests102, PermuteTests, TestCases102, PermuteTests::getTestCaseName);++const auto TestCases120 = ::testing::Combine(+ ::testing::ValuesIn({ov::element::Type_t::f16, ov::element::Type_t::f32}),+ ::details::ShapesIn({Tensors{input={1, 10, 16};+}+, Tensors {+ input = {1, 10, 128};+}+, Tensors {+ input = {1, 16, 256};+}+, Tensors {+ input = {1, 16, 300};+}+}),+::testing::ValuesIn(+ {+ std::vector<std::size_t>({1, 2, 0})+}+)+);++INSTANTIATE_TEST_SUITE_P(PermuteTests120, PermuteTests, TestCases120, PermuteTests::getTestCaseName);++} // anonymous namespace++#endif // __AVX2__diff --git a/src/plugins/intel_npu/tests/unit/npuw/permute.hpp b/src/plugins/intel_npu/tests/unit/npuw/permute.hppnew file mode 100644index 00000000000..488b21f9db7--- /dev/null+++ b/src/plugins/intel_npu/tests/unit/npuw/permute.hpp@@ -0,0 +1,67 @@+// Copyright (C) 2024 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include <gmock/gmock-matchers.h>+#include <gtest/gtest.h>+#include <immintrin.h>++#include <array>+#include <cstdint>+#include <iomanip>+#include <iostream>+#include <random>++#include "openvino/runtime/make_tensor.hpp"+#include "openvino/runtime/tensor.hpp"+#include "test_utils.hpp"+#include "util.hpp"++namespace {++using PermuteTestsParams = std::tuple<ov::element::Type_t, // Precision+ ShapesInitializer, // input_shape+ std::vector<std::size_t> // axes+ >;++class PermuteTestsBase {+protected:+ ov::element::Type type;+ ov::Tensor inTensor;+ ov::Tensor outTensor;++ std::vector<std::size_t> axes;++ std::vector<int8_t> input;+ std::vector<int8_t> output;+ std::vector<int8_t> ref_output;+ ov::Shape input_shape;++ void make_input();++public:+ void SetUp(const PermuteTestsParams& getParam);+ std::string ToString() const;+ virtual bool isNegative() const;+ virtual void make_ref_output();+};++template <class T>+class PermuteTestsTmpl : public ::testing::Test, public T, public ::testing::WithParamInterface<PermuteTestsParams> {+protected:+ void SetUp() override {+ T::SetUp(GetParam());+ }++public:+ static std::string getTestCaseName(const testing::TestParamInfo<PermuteTestsParams>& obj) {+ T _bt;+ _bt.SetUp(obj.param);+ return _bt.ToString();+ }+};++using PermuteTests = PermuteTestsTmpl<PermuteTestsBase>;+class PermuteTestsRef : public PermuteTests {};++} // anonymous namespacediff --git a/src/plugins/intel_npu/tests/unit/npuw/test_utils.cpp b/src/plugins/intel_npu/tests/unit/npuw/test_utils.cppnew file mode 100644index 00000000000..10c4c9abf31--- /dev/null+++ b/src/plugins/intel_npu/tests/unit/npuw/test_utils.cpp@@ -0,0 +1,63 @@+// Copyright (C) 2024 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "test_utils.hpp"++/// Read a 4-bit value from packed int4 array+uint8_t details::read_4b(const uint8_t* data, size_t r, size_t c, size_t cols) {+ size_t idx = r * cols + c;+ uint8_t byte = data[idx / 2];+ return (idx % 2 == 0) ? (byte & 0x0F) : (byte >> 4);+}++// Write a 4-bit value to packed int4 array+void details::write_4b(uint8_t* data, uint8_t val, size_t r, size_t c, size_t cols) {+ size_t idx = r * cols + c;+ // uint8_t* byte = data + idx;+ uint8_t& byte = data[idx / 2];+ if (idx % 2 == 0) {+ byte = (byte & 0xF0) | (val & 0x0F);+ } else {+ byte = (byte & 0x0F) | ((val & 0x0F) << 4);+ }+}++::testing::AssertionResult details::ArraysMatch(const std::vector<int8_t>& actual,+ const std::vector<int8_t>& expected) {+ if (actual.size() != expected.size()) {+ return ::testing::AssertionFailure()+ << "Size mismatch: actual.size()=" << actual.size() << ", expected.size()=" << expected.size();+ }+ for (size_t i = 0; i < expected.size(); ++i) {+ if (actual[i] != expected[i]) {+ return ::testing::AssertionFailure()+ << "Mismatch at index " << i << ": actual=" << static_cast<int>(actual[i])+ << ", expected=" << static_cast<int>(expected[i]);+ }+ }+ return ::testing::AssertionSuccess();+}++std::vector<size_t> details::compute_strides(const std::vector<size_t>& dims) {+ std::vector<size_t> strides(dims.size());+ size_t stride = 1;+ for (size_t i = dims.size(); i > 0; --i) {+ strides[i - 1] = stride;+ stride *= dims[i - 1];+ }+ return strides;+}++std::vector<size_t> details::reorder(const std::vector<size_t>& dims, const std::vector<size_t>& order) {+ std::vector<size_t> new_dims(dims.size());+ for (size_t i = 0; i < dims.size(); ++i)+ new_dims[i] = dims[order[i]];++ return new_dims;+}++::testing::internal::ParamGenerator<typename std::vector<ShapesInitializer>::value_type> details::ShapesIn(+ const std::vector<ShapesInitializer>& container) {+ return ::testing::ValuesIn(container.begin(), container.end());+}diff --git a/src/plugins/intel_npu/tests/unit/npuw/test_utils.hpp b/src/plugins/intel_npu/tests/unit/npuw/test_utils.hppnew file mode 100644index 00000000000..1e3ad9409e9--- /dev/null+++ b/src/plugins/intel_npu/tests/unit/npuw/test_utils.hpp@@ -0,0 +1,50 @@+// Copyright (C) 2024 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include <gmock/gmock-matchers.h>+#include <immintrin.h>++#include <array>+#include <cstdint>+#include <iomanip>++#define ASSERT_NO_THROW_WITH_MESSAGE(code) \+ do { \+ try { \+ code; \+ } catch (const std::exception& ex) { \+ FAIL() << ex.what(); \+ } catch (...) { \+ FAIL() << "Unknown exception"; \+ } \+ } while (0)++#define ASSERT_NO_THROW_IF(condition, code) \+ do { \+ if (condition) { \+ ASSERT_NO_THROW_WITH_MESSAGE(code); \+ } else { \+ ASSERT_ANY_THROW(code); \+ } \+ } while (0);++#define Tensors [](std::vector<int> & input)++using ShapesInitializer = std::function<void(std::vector<int>&)>;++namespace details {++uint8_t read_4b(const uint8_t* data, size_t r, size_t c, size_t cols);+void write_4b(uint8_t* data, uint8_t val, size_t r, size_t c, size_t cols);++::testing::AssertionResult ArraysMatch(const std::vector<int8_t>& actual, const std::vector<int8_t>& expected);++std::vector<size_t> compute_strides(const std::vector<size_t>& dims);++std::vector<size_t> reorder(const std::vector<size_t>& dims, const std::vector<size_t>& order);++::testing::internal::ParamGenerator<typename std::vector<ShapesInitializer>::value_type> ShapesIn(+ const std::vector<ShapesInitializer>& container);++} // namespace detailsdiff --git a/src/plugins/intel_npu/tests/unit/npuw/transpose.cpp b/src/plugins/intel_npu/tests/unit/npuw/transpose.cppnew file mode 100644index 00000000000..67daabc8741--- /dev/null+++ b/src/plugins/intel_npu/tests/unit/npuw/transpose.cpp@@ -0,0 +1,119 @@+// Copyright (C) 2024 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#ifdef HAVE_AVX2+# include "transpose.hpp"++namespace {++void TransposeTestsBase::make_input() {+ size_t nElements = shape_size(input_shape);++ ASSERT_EQ((type.bitwidth() * nElements) % 8, 0)+ << "Input len has to be byte boundary aligned, but was " << type.bitwidth() * nElements << " bits";+ const size_t nBytes = type.bitwidth() * nElements / 8;++ input.resize(nBytes);+ ref_output.resize(nBytes);+ output.resize(nBytes);++ std::fill(ref_output.begin(), ref_output.end(), 0);+ std::fill(output.begin(), output.end(), 0);++ std::mt19937 rng(42); // Fixed seed for reproducibility+ std::uniform_int_distribution<int> dist(0, 100);++ for (size_t i = 0; i < nBytes; ++i) {+ input[i] = static_cast<int8_t>(dist(rng));+ }++ inTensor = ov::Tensor(type, input_shape, input.data());+}++void TransposeTestsBase::SetUp(const TransposeTestsParams& getParam) {+ ShapesInitializer shapeInit;++ std::tie(type, shapeInit) = getParam;++ std::vector<int> input;+ shapeInit(input);++ input_shape = ov::Shape{input.begin(), input.end()};++ make_input();++ make_ref_output();+}++std::string TransposeTestsBase::ToString() const {+ std::ostringstream result;+ result << (isNegative() ? "NEGATIVE_" : "") << "[";++ for (size_t i = 0; i != input_shape.size(); i++) {+ result << input_shape[i] << ((i + 1 == input_shape.size()) ? "" : "x");+ }+ result << "]"+ << "_type_" << type;++ return result.str();+}++/**+ * Negative test cases has to be carefully reviewed, to still remain positive runs at some points+ * @return+ */+bool TransposeTestsBase::isNegative() const {+ return false;+}++void TransposeTestsBase::make_ref_output() {+ auto rows = input_shape[0] * input_shape[1];+ auto cols = input_shape[2];++ for (size_t i = 0; i < rows; ++i) {+ for (size_t j = 0; j < cols; ++j) {+ if (type == ov::element::i4) {+ uint8_t val = details::read_4b(reinterpret_cast<const uint8_t*>(input.data()), i, j, cols);+ details::write_4b(reinterpret_cast<uint8_t*>(ref_output.data()), val, j, i, rows);+ } else if (type == ov::element::f16) {+ const uint16_t* input_ptr = reinterpret_cast<const uint16_t*>(input.data());+ uint16_t* output_ptr = reinterpret_cast<uint16_t*>(ref_output.data());+ output_ptr[j * rows + i] = input_ptr[i * cols + j];+ } else if (type == ov::element::f32) {+ const float* input_ptr = reinterpret_cast<const float*>(input.data());+ float* output_ptr = reinterpret_cast<float*>(ref_output.data());+ output_ptr[j * rows + i] = input_ptr[i * cols + j];+ }+ }+ }+}++TEST_P(TransposeTests, transpose) {+ ASSERT_NO_THROW_WITH_MESSAGE(outTensor = ov::npuw::util::transpose(inTensor));+ int8_t* dst = static_cast<int8_t*>(outTensor.data());+ output = std::vector<int8_t>(dst, dst + output.size());+ ASSERT_TRUE(details::ArraysMatch(output, ref_output));+}++const auto TestCases = ::testing::Combine(+ ::testing::ValuesIn({ov::element::Type_t::i4, ov::element::Type_t::f32}),+ ::details::ShapesIn({Tensors{input={1, 10, 16};+}+, Tensors {+ input = {1, 10, 128};+}+, Tensors {+ input = {1, 16, 256};+}+, Tensors {+ input = {1, 16, 300};+}+})+);++INSTANTIATE_TEST_SUITE_P(TransposeTests, TransposeTests, TestCases, TransposeTests::getTestCaseName);++} // anonymous namespace++#endif // __AVX2__diff --git a/src/plugins/intel_npu/tests/unit/npuw/transpose.hpp b/src/plugins/intel_npu/tests/unit/npuw/transpose.hppnew file mode 100644index 00000000000..235aa545d10--- /dev/null+++ b/src/plugins/intel_npu/tests/unit/npuw/transpose.hpp@@ -0,0 +1,66 @@+// Copyright (C) 2024 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include <gmock/gmock-matchers.h>+#include <gtest/gtest.h>+#include <immintrin.h>++#include <array>+#include <cstdint>+#include <iomanip>+#include <iostream>+#include <random>++#include "openvino/runtime/make_tensor.hpp"+#include "openvino/runtime/tensor.hpp"+#include "test_utils.hpp"+#include "util.hpp"++namespace {++using TransposeTestsParams = std::tuple<ov::element::Type_t, // Precision+ ShapesInitializer // input_shape+ >;++class TransposeTestsBase {+protected:+ ov::element::Type type;+ ov::Tensor inTensor;+ ov::Tensor outTensor;++ std::vector<int8_t> input;+ std::vector<int8_t> output;+ std::vector<int8_t> ref_output;+ ov::Shape input_shape;++ void make_input();++public:+ void SetUp(const TransposeTestsParams& getParam);+ std::string ToString() const;+ virtual bool isNegative() const;+ virtual void make_ref_output();+};++template <class T>+class TransposeTestsTmpl : public ::testing::Test,+ public T,+ public ::testing::WithParamInterface<TransposeTestsParams> {+protected:+ void SetUp() override {+ T::SetUp(GetParam());+ }++public:+ static std::string getTestCaseName(const testing::TestParamInfo<TransposeTestsParams>& obj) {+ T _bt;+ _bt.SetUp(obj.param);+ return _bt.ToString();+ }+};++using TransposeTests = TransposeTestsTmpl<TransposeTestsBase>;+class TransposeTestsRef : public TransposeTests {};++} // anonymous namespace