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
[core] Allow strided/ROI tensors for low-precision types (#39547)
Pawel Raasz6f80337f9ccc
diff --git a/src/bindings/python/tests/test_runtime/test_tensor.py b/src/bindings/python/tests/test_runtime/test_tensor.pyindex 129446a7aa0..35a1c9bfebe 100644--- a/src/bindings/python/tests/test_runtime/test_tensor.py+++ b/src/bindings/python/tests/test_runtime/test_tensor.py@@ -376,37 +376,85 @@ def test_can_set_shape_other_dims():@pytest.mark.parametrize("ov_type",[- (ov.Type.u1),- (ov.Type.u2),- (ov.Type.u3),- (ov.Type.u4),- (ov.Type.u6),- (ov.Type.i4),+ ov.Type.u1,+ ov.Type.u2,+ ov.Type.u3,+ ov.Type.u4,+ ov.Type.u6,+ ov.Type.i4,],)def test_cannot_create_roi_from_packed_tensor(ov_type):ov_tensor = ov.Tensor(ov_type, [1, 3, 48, 48])with pytest.raises(RuntimeError) as e:ov.Tensor(ov_tensor, [0, 0, 24, 24], [1, 3, 48, 48])- assert "for types with bitwidths less then 8 bit" in str(e.value)+ assert "cannot slice the innermost dimension" in str(e.value)+++def test_roi_from_packed_tensor_when_strided_two_heads():+ ov_tensor = ov.Tensor(ov.Type.i4, [1, 2, 4095, 512])+ ov_tensor.data[:] = np.arange(ov_tensor.data.size, dtype=ov_tensor.data.dtype)++ roi_tensor = ov.Tensor(ov_tensor, [0, 0, 0, 0], [1, 2, 10, 512])++ assert list(roi_tensor.shape) == [1, 2, 10, 512]+ assert not roi_tensor.is_continuous()+ assert np.shares_memory(ov_tensor.data, roi_tensor.data)++ row_bytes = 512 * 4 // 8+ head_stride_bytes = 4095 * row_bytes+ assert roi_tensor.strides[1] == head_stride_bytes++ # roi_tensor.data is not usable directly here: for sub-byte types it is exposed as a flat+ # byte_size-length view, which does not reflect a strided (non-contiguous) layout. copy_to+ # goes through the real per-dimension strides instead, so use it to verify the content.+ dense_tensor = ov.Tensor(ov.Type.i4, [1, 2, 10, 512])+ roi_tensor.copy_to(dense_tensor)+ for head_idx in range(2):+ src_start = head_idx * head_stride_bytes+ dst_start = head_idx * 10 * row_bytes+ dst_slice = dense_tensor.data[dst_start: dst_start + 10 * row_bytes]+ src_slice = ov_tensor.data[src_start: src_start + 10 * row_bytes]+ assert np.array_equal(dst_slice, src_slice)+++def test_roi_from_packed_tensor_when_contiguous():+ ov_tensor = ov.Tensor(ov.Type.i4, [1, 1, 4095, 512])+ ov_tensor.data[:] = np.arange(ov_tensor.data.size, dtype=ov_tensor.data.dtype)++ roi_tensor = ov.Tensor(ov_tensor, [0, 0, 0, 0], [1, 1, 10, 512])++ assert list(roi_tensor.shape) == [1, 1, 10, 512]+ assert np.shares_memory(ov_tensor.data, roi_tensor.data)+ assert np.array_equal(roi_tensor.data, ov_tensor.data[: roi_tensor.byte_size])+++ ("ov_type", "row_bytes"),+ [+ (ov.Type.u1, 6),+ (ov.Type.u2, 12),+ (ov.Type.u4, 24),+ (ov.Type.i4, 24),+ ],+)+def test_can_get_strides_for_packed_tensor_with_aligned_row(ov_type, row_bytes):+ ov_tensor = ov.Tensor(ov_type, [1, 3, 48, 48])+ assert list(ov_tensor.get_strides())[-2] == row_bytes@pytest.mark.parametrize("ov_type",[- (ov.Type.u1),- (ov.Type.u2),(ov.Type.u3),- (ov.Type.u4),(ov.Type.u6),- (ov.Type.i4),],)def test_cannot_get_strides_for_packed_tensor(ov_type):ov_tensor = ov.Tensor(ov_type, [1, 3, 48, 48])with pytest.raises(RuntimeError) as e:ov_tensor.get_strides()- assert "Could not get strides for types with bitwidths less then 8 bit." in str(e.value)+ assert "Could not get strides" in str(e.value)@pytest.mark.parametrize(@@ -740,7 +788,7 @@ def test_copy_and_deepcopy(copy_func, should_share_data):(np.float32, (224, 224)),(np.int32, (224, 224)),(np.uint8, (224, 224, 3)),- (np.uint16, (224, 224)),],)+ (np.uint16, (224, 224))])def test_tensor_from_pillow(numpy_dtype, shape):from PIL import Imagediff --git a/src/core/dev_api/openvino/core/memory_util.hpp b/src/core/dev_api/openvino/core/memory_util.hppindex b383338cc1c..a16376cd1c5 100644--- a/src/core/dev_api/openvino/core/memory_util.hpp+++ b/src/core/dev_api/openvino/core/memory_util.hpp@@ -7,6 +7,7 @@#include <optional>#include "openvino/core/shape.hpp"+#include "openvino/core/strides.hpp"#include "openvino/core/type/element_type.hpp"namespace ov::util {@@ -65,4 +66,39 @@ constexpr size_t align_padding_size(size_t alignment, size_t pos) {return 0;}}++/**+ * @brief Checks if byte strides can be computed for a shape of given element type.+ *+ * @param type Element type.+ * @param shape Shape to check.+ * @return True if get_dense_byte_strides(type, shape) can be computed for this type/shape.+ */+OPENVINO_API bool can_compute_byte_strides(const element::Type& type, const Shape& shape);++/**+ * @brief Gets the default, densely packed, row-major byte strides for a shape of given element type -+ * the byte-granular counterpart of row_major_strides().+ *+ * @pre can_compute_byte_strides(type, shape) is true.+ * @param type Element type.+ * @param shape Shape to get strides for.+ * @return Byte strides, one per dimension of shape. The last entry is not used for addressing when+ * the element type is sub-byte.+ */+OPENVINO_API Strides get_dense_byte_strides(const element::Type& type, const Shape& shape);++/**+ * @brief Gets the shape, in bytes, to pair with get_dense_byte_strides() for the same type/shape.+ *+ * Only the last dimension changes (its packed byte count instead of element count); other dimensions+ * and byte-granular types are unchanged.+ *+ * Example: get_byte_memory_shape(u4, Shape{1, 2, 4095, 1, 512}) -> Shape{1, 2, 4095, 1, 256}.+ *+ * @param type Element type.+ * @param shape Shape in element units to convert.+ * @return Shape in byte units (same rank; only the last dimension may differ).+ */+OPENVINO_API Shape get_byte_memory_shape(const element::Type& type, const Shape& shape);} // namespace ov::utildiff --git a/src/core/src/memory_util.cpp b/src/core/src/memory_util.cppindex 1cc6aebf14c..9722fc11b16 100644--- a/src/core/src/memory_util.cpp+++ b/src/core/src/memory_util.cpp@@ -10,6 +10,8 @@namespace ov::util {namespace {+constexpr size_t bits_per_byte = 8;+size_t get_bit_memory_size(const element::Type& type, const size_t elements_count) {const auto bit_width = type.bitwidth();// Any 8 elements occupy exactly bit_width bytes, so ceil(elements_count * bit_width / 8) is taken in two steps@@ -62,4 +64,44 @@ size_t get_elements_capacity(const element::Type& type, const size_t memory_sizereturn memory_size / bytes_per_element;}}++bool can_compute_byte_strides(const element::Type& type, const Shape& shape) {+ const auto bitwidth = type.bitwidth();+ size_t row_bits;+ return bitwidth >= bits_per_byte ||+ (bitwidth > 0 && (bits_per_byte % bitwidth) == 0 && !shape.empty() &&+ !mul_overflow<size_t>(shape.back(), bitwidth, row_bits) && row_bits % bits_per_byte == 0);+}++Strides get_dense_byte_strides(const element::Type& type, const Shape& shape) {+ Strides strides(shape.size());+ if (!strides.empty()) {+ const auto bitwidth = type.bitwidth();+ strides.back() = shape.back() == 0 ? 0 : type.size();++ if (strides.size() > 1) {+ auto& row_byte_size = strides[strides.size() - 2];+ const auto is_sub_byte = bitwidth < bits_per_byte;+ OPENVINO_ASSERT(!mul_overflow<size_t>(shape.back(), is_sub_byte ? bitwidth : type.size(), row_byte_size));+ if (is_sub_byte) {+ row_byte_size /= bits_per_byte;+ }+ for (auto i = strides.size() - 2; i > 0; --i) {+ OPENVINO_ASSERT(!mul_overflow<size_t>(strides[i], shape[i], strides[i - 1]));+ }+ }+ }+ return strides;+}++Shape get_byte_memory_shape(const element::Type& type, const Shape& shape) {+ auto byte_shape = shape;+ const auto bitwidth = type.bitwidth();+ if (bitwidth < bits_per_byte && !byte_shape.empty()) {+ auto& last_dim = byte_shape.back();+ OPENVINO_ASSERT(!mul_overflow<size_t>(last_dim, bitwidth, last_dim));+ last_dim /= bits_per_byte;+ }+ return byte_shape;+}} // namespace ov::utildiff --git a/src/core/src/runtime/itensor.cpp b/src/core/src/runtime/itensor.cppindex 56a9f4d448f..f715f038998 100644--- a/src/core/src/runtime/itensor.cpp+++ b/src/core/src/runtime/itensor.cpp@@ -9,28 +9,12 @@#include "compare.hpp"#include "openvino/core/except.hpp"#include "openvino/core/memory_util.hpp"-#include "openvino/core/shape_util.hpp"#include "openvino/runtime/iremote_tensor.hpp"#include "openvino/runtime/make_tensor.hpp"#include "openvino/runtime/properties.hpp"namespace ov {-namespace {-Strides default_byte_strides(const Shape& shape, const element::Type& et) {- auto strides = Strides(shape.size());- if (!strides.empty()) {- strides.back() = et.size();- std::transform(shape.crbegin(),- shape.crend() - 1,- strides.rbegin(),- strides.rbegin() + 1,- std::multiplies<size_t>());- }- return strides;-}-} // namespace-ITensor::~ITensor() = default;size_t ITensor::get_size() const {@@ -42,14 +26,15 @@ size_t ITensor::get_byte_size() const {}bool ITensor::is_continuous() const {- if ((get_element_type().bitwidth() < 8) || get_size() == 0) {- // OpenVINO doesn't support strides for lp types+ const auto& type = get_element_type();+ const auto& shape = get_shape();+ if (shape_size(shape) == 0 || !util::can_compute_byte_strides(type, shape)) {return true;}const auto& strides = get_strides();auto stride = strides.rbegin();- const auto default_strides = default_byte_strides(get_shape(), get_element_type());+ const auto default_strides = util::get_dense_byte_strides(type, shape);auto default_stride = default_strides.rbegin();for (; stride != strides.rend(); ++stride, ++default_stride) {@@ -61,7 +46,7 @@ bool ITensor::is_continuous() const {const auto default_last = default_strides.rend();// It assumed that `default_strides' and `strides' have the same size, thus `default_stride' iterator is valid// coverity[deref_iterator:SUPPRESS]- return (default_stride == default_last) || (*default_stride < *stride && (get_shape()[0] == 1) &&+ return (default_stride == default_last) || (*default_stride < *stride && (shape[0] == 1) &&std::all_of(default_stride, default_last, cmp::Equal(*default_stride)));}@@ -72,14 +57,17 @@ void ITensor::copy_to(const std::shared_ptr<ov::ITensor>& dst) const {OPENVINO_ASSERT(dst, "Destination tensor was not initialized.");OPENVINO_ASSERT(!dynamic_cast<const ov::IRemoteTensor*>(this),"Default copy to doesn't support copy from remote tensor.");- OPENVINO_ASSERT(dst->get_element_type() == get_element_type(),++ const auto& type = get_element_type();+ const auto& shape = get_shape();++ OPENVINO_ASSERT(dst->get_element_type() == type,"Tensor element types are not equal. (src: ",- get_element_type(),+ type," != dst: ",dst->get_element_type(),")");- const auto& shape = get_shape();if (shape != dst->get_shape()) {dst->set_shape(shape);}@@ -93,6 +81,10 @@ void ITensor::copy_to(const std::shared_ptr<ov::ITensor>& dst) const {return;}+ if (shape_size(shape) == 0) {+ return;+ }+auto* src_data = static_cast<const uint8_t*>(data());auto* dst_data = static_cast<uint8_t*>(dst->data());ov::Strides src_strides{get_byte_size()};@@ -100,16 +92,19 @@ void ITensor::copy_to(const std::shared_ptr<ov::ITensor>& dst) const {ov::Shape cur_pos{0};ov::Shape max_pos{1};- if (get_element_type().bitwidth() < 8 || (get_strides() == dst->get_strides() && is_continuous()) ||+ if (!util::can_compute_byte_strides(type, shape) || (get_strides() == dst->get_strides() && is_continuous()) ||(is_scalar(shape) && is_scalar(dst->get_shape()))) {- // OpenVINO doesn't support strides for LP types- // or both tensors have default strides+ // byte strides are not representable for this LP type/shape or both tensors have default strides// Strides and positions already initialized} else {// Tensors have default strides- const auto& type = get_element_type();const auto shape_rank = shape.size();- const auto default_strides = default_byte_strides(shape, type);+ const auto default_strides = util::get_dense_byte_strides(type, shape);++ // for sub-byte types the last dimension's element count does not match its real byte+ // span (default_strides.back() is an unaddressable placeholder) - use its packed byte+ // count instead, so dimension counts below always line up with real byte strides+ const auto byte_shape = util::get_byte_memory_shape(type, shape);src_strides = get_strides();dst_strides = dst->get_strides();@@ -131,19 +126,25 @@ void ITensor::copy_to(const std::shared_ptr<ov::ITensor>& dst) const {dst_str.resize(strides_size + 1);max_pos.resize(strides_size + 1);cur_pos.resize(strides_size + 1);- // Dimensions after inverted_idx have default strides in both tensors,- // so they are copied as one block of default_strides[inverted_idx] bytes- // In case the innermost dimension is strided, the block is one element- const auto block_size = default_strides[inverted_idx];- src_str[strides_size] = block_size;- dst_str[strides_size] = block_size;- max_pos[strides_size] = 1;++ // In case of default continuous strides we can copy several elements+ // In other case only one element+ size_t dim = 1;+ size_t strides = type.size();++ if (strides_size < default_strides.size()) {+ strides = default_strides[strides_size];+ dim = byte_shape[strides_size];+ }+ src_str[strides_size] = strides;+ dst_str[strides_size] = strides;+ max_pos[strides_size] = dim;cur_pos[strides_size] = 0;}}src_str[inverted_idx] = src_strides[inverted_idx];dst_str[inverted_idx] = dst_strides[inverted_idx];- max_pos[inverted_idx] = shape[inverted_idx];+ max_pos[inverted_idx] = byte_shape[inverted_idx];cur_pos[inverted_idx] = 0;}src_strides = std::move(src_str);diff --git a/src/core/tests/memory_util.cpp b/src/core/tests/memory_util.cppindex 6a327807755..cfab58febf2 100644--- a/src/core/tests/memory_util.cpp+++ b/src/core/tests/memory_util.cpp@@ -237,4 +237,45 @@ TEST_P(AlignTest, align_padding_size) {EXPECT_EQ(pad, expected);}++TEST(memory_util, can_compute_byte_strides) {+ EXPECT_TRUE(ov::util::can_compute_byte_strides(element::f32, Shape{}));+ EXPECT_TRUE(ov::util::can_compute_byte_strides(element::f32, Shape{2, 3, 5}));+ // sub-byte types require the last dimension's packed row to end on a byte boundary+ EXPECT_TRUE(ov::util::can_compute_byte_strides(element::u4, Shape{2, 3, 8}));+ EXPECT_FALSE(ov::util::can_compute_byte_strides(element::u4, Shape{2, 3, 3}));+ EXPECT_TRUE(ov::util::can_compute_byte_strides(element::u1, Shape{8}));+ EXPECT_FALSE(ov::util::can_compute_byte_strides(element::u1, Shape{10}));++ // a bitwidth that does not evenly divide a byte can never be byte-aligned+ EXPECT_FALSE(ov::util::can_compute_byte_strides(element::u3, Shape{8}));++ // sub-byte scalar (rank 0) has no last dimension to align+ EXPECT_FALSE(ov::util::can_compute_byte_strides(element::u4, Shape{}));+}++TEST(memory_util, get_dense_byte_strides) {+ EXPECT_EQ(ov::util::get_dense_byte_strides(element::f32, Shape{2, 3, 5}), Strides({60, 20, 4}));++ // last dimension is one packed row (3 bytes); outer strides count whole rows+ EXPECT_EQ(ov::util::get_dense_byte_strides(element::u4, Shape{2, 3, 8}), Strides({12, 4, 1}));++ // zero-sized last dimension collapses all strides to 0+ EXPECT_EQ(ov::util::get_dense_byte_strides(element::u4, Shape{2, 3, 0}), Strides({0, 0, 0}));+}++TEST(memory_util, get_byte_memory_shape) {+ // byte-granular types are returned unchanged+ EXPECT_EQ(ov::util::get_byte_memory_shape(element::f32, Shape{2, 3, 5}), Shape({2, 3, 5}));++ // sub-byte types: last dimension becomes its packed byte count+ EXPECT_EQ(ov::util::get_byte_memory_shape(element::u4, Shape{2, 3, 8}), Shape({2, 3, 4}));+ EXPECT_EQ(ov::util::get_byte_memory_shape(element::u1, Shape{2, 16}), Shape({2, 2}));++ // higher rank: only the last dimension changes, every outer dimension is copied unchanged+ EXPECT_EQ(ov::util::get_byte_memory_shape(element::u4, Shape{1, 2, 4095, 1, 512}), Shape({1, 2, 4095, 1, 256}));++ // sub-byte scalar (rank 0) has no last dimension to convert+ EXPECT_EQ(ov::util::get_byte_memory_shape(element::u4, Shape{}), Shape{});+}} // namespace ov::testdiff --git a/src/core/tests/ov_tensor_test.cpp b/src/core/tests/ov_tensor_test.cppindex 2f57a0b1594..045e24509dc 100644--- a/src/core/tests/ov_tensor_test.cpp+++ b/src/core/tests/ov_tensor_test.cpp@@ -4,6 +4,7 @@#include <gmock/gmock.h>+#include <algorithm>#include <chrono>#include <cstdint>#include <cstring>@@ -730,6 +731,265 @@ TEST_F(OVTensorTest, tensorInt4DataAccess) {OV_ASSERT_NO_THROW(t.data());}+TEST_F(OVTensorTest, roiLpCropOuterDim) {+ ov::Tensor t{ov::element::i4, {4, 512}};+ auto* raw = reinterpret_cast<uint8_t*>(t.data());+ std::iota(raw, raw + t.get_byte_size(), uint8_t{0});++ ov::Tensor roi;+ OV_ASSERT_NO_THROW(roi = ov::Tensor(t, {1, 0}, {3, 512}));++ EXPECT_EQ(roi.get_shape(), ov::Shape({2, 512}));+ EXPECT_EQ(roi.get_element_type(), t.get_element_type());+ const auto expected_offset_bytes = 512 * 4 / 8;+ EXPECT_EQ(reinterpret_cast<const uint8_t*>(roi.data()) - reinterpret_cast<const uint8_t*>(t.data()),+ expected_offset_bytes);+ EXPECT_EQ(0, std::memcmp(roi.data(), raw + expected_offset_bytes, roi.get_byte_size()));+}++TEST_F(OVTensorTest, roiLpWindowFromStart) {+ ov::Tensor t{ov::element::i4, {1, 1, 4095, 512}};+ ov::Tensor roi;+ OV_ASSERT_NO_THROW(roi = ov::Tensor(t, {0, 0, 0, 0}, {1, 1, 10, 512}));++ EXPECT_EQ(roi.get_shape(), ov::Shape({1, 1, 10, 512}));+ EXPECT_EQ(roi.data(), t.data());+}++TEST_F(OVTensorTest, roiLpStridedTwoHeadsSucceeds) {+ ov::Tensor t{ov::element::i4, {1, 2, 4095, 512}};+ auto raw = reinterpret_cast<uint8_t*>(t.data());+ const size_t row_bytes = 512 * 4 / 8;+ const size_t head_stride_bytes = 4095 * row_bytes;+ // offset each head's pattern by a different constant so the two heads can never alias+ for (size_t i = 0; i < t.get_byte_size(); ++i) {+ raw[i] = static_cast<uint8_t>(i + i / head_stride_bytes);+ }++ ov::Tensor roi;+ OV_ASSERT_NO_THROW(roi = ov::Tensor(t, {0, 0, 0, 0}, {1, 2, 10, 512}));++ EXPECT_EQ(roi.get_shape(), ov::Shape({1, 2, 10, 512}));+ EXPECT_EQ(roi.get_strides(), t.get_strides());+ EXPECT_FALSE(roi.is_continuous());++ EXPECT_EQ(roi.get_strides()[1], head_stride_bytes);+ // guards against a future shape change making the two heads indistinguishable again+ ASSERT_NE(0, std::memcmp(raw, raw + head_stride_bytes, row_bytes));++ auto roi_data = reinterpret_cast<const uint8_t*>(roi.data());+ EXPECT_EQ(0, std::memcmp(roi_data, raw, 10 * row_bytes));+ EXPECT_EQ(0, std::memcmp(roi_data + head_stride_bytes, raw + head_stride_bytes, 10 * row_bytes));++ ov::Tensor dense{ov::element::i4, {1, 2, 10, 512}};+ OV_ASSERT_NO_THROW(roi.copy_to(dense));+ auto dense_data = reinterpret_cast<uint8_t*>(dense.data());+ EXPECT_EQ(0, std::memcmp(dense_data, raw, 10 * row_bytes));+ EXPECT_EQ(0, std::memcmp(dense_data + 10 * row_bytes, raw + head_stride_bytes, 10 * row_bytes));+}++TEST_F(OVTensorTest, roiLpCopyToStridedDestinationSucceeds) {+ ov::Tensor src_owner{ov::element::i4, {1, 2, 4095, 512}};+ auto src_raw = reinterpret_cast<uint8_t*>(src_owner.data());+ const size_t row_bytes = 512 * 4 / 8;+ const size_t src_head_stride_bytes = 4095 * row_bytes;+ for (size_t i = 0; i < src_owner.get_byte_size(); ++i) {+ src_raw[i] = static_cast<uint8_t>(i + i / src_head_stride_bytes);+ }+ ov::Tensor src;+ OV_ASSERT_NO_THROW(src = ov::Tensor(src_owner, {0, 0, 0, 0}, {1, 2, 10, 512}));++ ov::Tensor dst_owner{ov::element::i4, {1, 3, 4095, 512}};+ auto dst_owner_raw = reinterpret_cast<uint8_t*>(dst_owner.data());+ std::fill(dst_owner_raw, dst_owner_raw + dst_owner.get_byte_size(), uint8_t{0xFF});+ const size_t dst_head_stride_bytes = 4095 * row_bytes;++ ov::Tensor dst;+ // heads 1 and 2 of dst_owner - both src and dst are non-contiguous, with different strides+ OV_ASSERT_NO_THROW(dst = ov::Tensor(dst_owner, {0, 1, 0, 0}, {1, 3, 10, 512}));+ EXPECT_FALSE(dst.is_continuous());++ OV_ASSERT_NO_THROW(src.copy_to(dst));++ // head 0 of dst_owner is outside the destination ROI and must stay untouched+ EXPECT_EQ(dst_owner_raw[0], 0xFF);+ EXPECT_EQ(dst_owner_raw[dst_head_stride_bytes - 1], 0xFF);++ EXPECT_EQ(0, std::memcmp(dst_owner_raw + dst_head_stride_bytes, src_raw, 10 * row_bytes));+ // row just past the copied window must stay untouched+ EXPECT_EQ(dst_owner_raw[dst_head_stride_bytes + 10 * row_bytes], 0xFF);++ EXPECT_EQ(0,+ std::memcmp(dst_owner_raw + 2 * dst_head_stride_bytes, src_raw + src_head_stride_bytes, 10 * row_bytes));+ EXPECT_EQ(dst_owner_raw[2 * dst_head_stride_bytes + 10 * row_bytes], 0xFF);+}++TEST_F(OVTensorTest, roiLpCopyToDenseSourceStridedDestinationSucceeds) {+ ov::Tensor src{ov::element::i4, {1, 2, 10, 512}};+ auto src_raw = reinterpret_cast<uint8_t*>(src.data());+ const size_t row_bytes = 512 * 4 / 8;+ const size_t src_head_stride_bytes = 10 * row_bytes;+ for (size_t i = 0; i < src.get_byte_size(); ++i) {+ src_raw[i] = static_cast<uint8_t>(i + i / src_head_stride_bytes);+ }++ ov::Tensor dst_owner{ov::element::i4, {1, 2, 4095, 512}};+ auto dst_owner_raw = reinterpret_cast<uint8_t*>(dst_owner.data());+ std::fill(dst_owner_raw, dst_owner_raw + dst_owner.get_byte_size(), uint8_t{0xFF});+ const size_t dst_head_stride_bytes = 4095 * row_bytes;++ ov::Tensor dst;+ OV_ASSERT_NO_THROW(dst = ov::Tensor(dst_owner, {0, 0, 0, 0}, {1, 2, 10, 512}));+ EXPECT_FALSE(dst.is_continuous());++ OV_ASSERT_NO_THROW(src.copy_to(dst));++ EXPECT_EQ(0, std::memcmp(dst_owner_raw, src_raw, 10 * row_bytes));+ // row just past the copied window must stay untouched+ EXPECT_EQ(dst_owner_raw[10 * row_bytes], 0xFF);++ EXPECT_EQ(0, std::memcmp(dst_owner_raw + dst_head_stride_bytes, src_raw + src_head_stride_bytes, 10 * row_bytes));+ EXPECT_EQ(dst_owner_raw[dst_head_stride_bytes + 10 * row_bytes], 0xFF);+}++TEST_F(OVTensorTest, roiLpCopyToMismatchedElementTypeThrows) {+ ov::Tensor src{ov::element::i4, {2, 8}};+ ov::Tensor dst{ov::element::u4, {2, 8}};+ OV_EXPECT_THROW_HAS_SUBSTRING(src.copy_to(dst), ov::Exception, "Tensor element types are not equal");+}++TEST_F(OVTensorTest, roiLpCopyToUninitializedDestinationThrows) {+ ov::Tensor src{ov::element::i4, {2, 8}};+ ov::Tensor dst;+ OV_EXPECT_THROW_HAS_SUBSTRING(src.copy_to(dst), ov::Exception, "Destination tensor was not initialized");+}++TEST_F(OVTensorTest, roiLpCopyToExceedsDestinationCapacityThrows) {+ ov::Tensor src{ov::element::i4, {1, 2, 10, 512}};+ ov::Tensor dst_owner{ov::element::i4, {1, 2, 4095, 512}};+ ov::Tensor dst;+ // dst sits at the tail of dim2, leaving no room to grow to src's shape (10 rows needed, 5 available)+ OV_ASSERT_NO_THROW(dst = ov::Tensor(dst_owner, {0, 0, 4090, 0}, {1, 2, 4095, 512}));++ OV_EXPECT_THROW(src.copy_to(dst), ov::Exception, _);+}++TEST_F(OVTensorTest, roiLpCopyToZeroExtentMiddleDimDoesNotHang) {+ ov::Tensor owner{ov::element::i4, {2, 3, 8}};+ ov::Tensor src;+ OV_ASSERT_NO_THROW(src = ov::Tensor(owner, {0, 0, 0}, {2, 0, 8}));+ ASSERT_EQ(src.get_shape(), ov::Shape({2, 0, 8}));+ ASSERT_EQ(src.get_strides(), ov::Strides({12, 4, 1}));++ ov::Tensor dst{ov::element::i4, {1}};+ OV_ASSERT_NO_THROW(src.copy_to(dst));+ EXPECT_EQ(dst.get_shape(), ov::Shape({2, 0, 8}));+ EXPECT_EQ(dst.get_byte_size(), 0u);+ EXPECT_EQ(dst.get_strides(), ov::Strides({0, 4, 1}));+}++TEST_F(OVTensorTest, roiLpInnerDimSliceThrows) {+ ov::Tensor t{ov::element::i4, {2, 8}};+ OV_EXPECT_THROW_HAS_SUBSTRING((ov::Tensor{t, {0, 0}, {2, 4}}),+ ov::Exception,+ "cannot slice the innermost dimension");+}++TEST_F(OVTensorTest, roiLpNonContiguousThrows) {+ ov::Tensor t{ov::element::i4, {1, 2, 4095, 512}};+ // end[2] exceeds the owner's shape[2] (4095) - still rejected regardless of element type+ OV_EXPECT_THROW((ov::Tensor{t, {0, 0, 0, 0}, {1, 2, 4096, 512}}), ov::Exception, _);+}++TEST_F(OVTensorTest, roiLpUnsupportedBitwidthThrows) {+ ov::Tensor t3{ov::element::u3, {2, 8}};+ OV_EXPECT_THROW_HAS_SUBSTRING((ov::Tensor{t3, {0, 0}, {1, 8}}),+ ov::Exception,+ "Could not get strides for tensor type: u3");++ ov::Tensor t6{ov::element::u6, {2, 8}};+ OV_EXPECT_THROW_HAS_SUBSTRING((ov::Tensor{t6, {0, 0}, {1, 8}}),+ ov::Exception,+ "Could not get strides for tensor type: u6");+}++TEST_F(OVTensorTest, roiLpUnalignedInnerDimThrows) {+ ov::Tensor t{ov::element::i4, {1, 6, 5, 3}};+ OV_EXPECT_THROW_HAS_SUBSTRING((ov::Tensor{t, {0, 1, 2, 0}, {1, 5, 4, 3}}),+ ov::Exception,+ "Could not get strides for tensor type: i4, shape: [1,6,5,3]");+}++TEST_F(OVTensorTest, roiLpDirectStridedViewSucceeds) {+ constexpr size_t row_bytes = 512 * 4 / 8;+ constexpr size_t head_stride_bytes = 4095 * row_bytes;+ std::vector<uint8_t> buffer(2 * head_stride_bytes);+ // offset each head's pattern by a different constant so the two heads can never alias+ for (size_t i = 0; i < buffer.size(); ++i) {+ buffer[i] = static_cast<uint8_t>(i + i / head_stride_bytes);+ }++ const ov::Strides strides{2 * head_stride_bytes, head_stride_bytes, row_bytes, 1};+ ov::Tensor t;+ OV_ASSERT_NO_THROW(t = ov::Tensor(ov::element::i4, {1, 2, 10, 512}, buffer.data(), strides));++ EXPECT_EQ(t.get_strides(), strides);+ EXPECT_FALSE(t.is_continuous());++ auto data = reinterpret_cast<const uint8_t*>(t.data());+ EXPECT_EQ(0, std::memcmp(data, buffer.data(), 10 * row_bytes));+ EXPECT_EQ(0, std::memcmp(data + head_stride_bytes, buffer.data() + head_stride_bytes, 10 * row_bytes));++ ov::Tensor dense{ov::element::i4, {1, 2, 10, 512}};+ OV_ASSERT_NO_THROW(t.copy_to(dense));+ auto dense_data = reinterpret_cast<uint8_t*>(dense.data());+ EXPECT_EQ(0, std::memcmp(dense_data, buffer.data(), 10 * row_bytes));+ EXPECT_EQ(0, std::memcmp(dense_data + 10 * row_bytes, buffer.data() + head_stride_bytes, 10 * row_bytes));+}++TEST_F(OVTensorTest, roiLpDirectStridedViewRowTooSmallThrows) {+ constexpr size_t row_bytes = 512 * 4 / 8;+ std::vector<uint8_t> buffer(2 * 10 * row_bytes);+ const ov::Strides bad_strides{2 * 10 * row_bytes, 10 * row_bytes, row_bytes - 1, 1};+ OV_EXPECT_THROW((ov::Tensor(ov::element::i4, {1, 2, 10, 512}, buffer.data(), bad_strides)), ov::Exception, _);+}++TEST_F(OVTensorTest, roiLpDirectStridedViewWrongPlaceholderStrideThrows) {+ constexpr size_t row_bytes = 8 * 4 / 8; // i4, 8 elements per row -> 4 bytes+ std::vector<uint8_t> buffer(2 * row_bytes);+ const ov::Strides bad_strides{row_bytes, 2}; // last stride must be the dense placeholder (1), not 2+ OV_EXPECT_THROW((ov::Tensor(ov::element::i4, {2, 8}, buffer.data(), bad_strides)), ov::Exception, _);+}++TEST_F(OVTensorTest, roiLpDirectStridedViewWrongPlaceholderStride3DThrows) {+ constexpr size_t row_bytes = 8 * 4 / 8; // i4, 8 elements per row -> 4 bytes+ std::vector<uint8_t> buffer(2 * 4 * row_bytes);+ const ov::Strides bad_strides{4 * row_bytes, row_bytes, 2}; // last stride must be 1, not 2+ OV_EXPECT_THROW((ov::Tensor(ov::element::i4, {2, 4, 8}, buffer.data(), bad_strides)), ov::Exception, _);+}++TEST_F(OVTensorTest, stridedViewSetShapeRejectsUnalignedSubByteShape) {+ constexpr size_t row_bytes = 8 * 4 / 8;+ std::vector<uint8_t> buffer(2 * row_bytes);+ ov::Tensor t{ov::element::i4, {2, 8}, buffer.data(), ov::Strides{row_bytes, 1}};+ // shrinking the last dimension to 1 element (4 bits) is no longer byte-aligned+ OV_EXPECT_THROW(t.set_shape({2, 1}), ov::Exception, _);+}++TEST_F(OVTensorTest, roiSetShapeRejectsUnalignedSubByteInnerDim) {+ ov::Tensor owner{ov::element::i4, {4, 8}};+ ov::Tensor roi{owner, {0, 0}, {2, 8}};+ // shrinking the last dimension to 1 element (4 bits) is no longer byte-aligned+ OV_EXPECT_THROW(roi.set_shape({2, 1}), ov::Exception, _);+}++TEST_F(OVTensorTest, roiSetShapeRejectsUnalignedSubByteInnerDimWithRankExpansion) {+ ov::Tensor owner{ov::element::i4, {4, 8}};+ ov::Tensor roi{owner, {0, 0}, {2, 8}};+ // expanding rank must not bypass the innermost byte-alignment check+ OV_EXPECT_THROW(roi.set_shape({1, 2, 1}), ov::Exception, _);+}+TEST_F(OVTensorTest, makeRangeRoiBlobWrongSize) {ov::Tensor t{ov::element::f32, {1, 3, 4, 4}};ASSERT_THROW((ov::Tensor{t, {0, 0, 1, 1}, {1, 3, 5, 5}}), ov::Exception);diff --git a/src/inference/src/dev/make_tensor.cpp b/src/inference/src/dev/make_tensor.cppindex 7fd2bb46e30..941dcff166f 100644--- a/src/inference/src/dev/make_tensor.cpp+++ b/src/inference/src/dev/make_tensor.cpp@@ -42,6 +42,22 @@ Shape make_roi_shape(const Shape& tensor_shape, const Coordinate& begin, const Creturn roi_shape;}+// Computes the byte offset of a ROI inside its owner tensor.+size_t compute_roi_offset(const std::shared_ptr<ITensor>& owner, const Coordinate& begin, const Coordinate& end) {+ const auto& element_type = owner->get_element_type();+ if (element_type.bitwidth() < 8) {+ // sub-byte types: only the innermost dimension must be taken in full - every other dimension's+ // byte stride is always whole, so it may be an arbitrary sub-range+ const auto& shape = owner->get_shape();+ const auto is_inner_dim_full = !shape.empty() && begin.back() == 0 && end.back() == shape.back();+ OPENVINO_ASSERT(is_inner_dim_full, "ROI cannot slice the innermost dimension of a sub-byte tensor");+ }++ const auto& strides = owner->get_strides();+ return std::inner_product(begin.begin(), begin.end(), strides.begin(), static_cast<size_t>(0));+}+} // namespace+// Hints for the [offset, offset + size) range of a file mapping.class MappedRangeHints final : public util::IMemoryHints {public:@@ -63,7 +79,6 @@ private:size_t m_offset;size_t m_size;};-} // namespace/*** @brief View tensor to external memory@@ -137,9 +152,14 @@ public:}const Strides& get_strides() const override {- OPENVINO_ASSERT(m_element_type.bitwidth() >= 8,- "Could not get strides for types with bitwidths less then 8 bit. Tensor type: ",- m_element_type);+ const auto can_compute_byte_strides = util::can_compute_byte_strides(m_element_type, m_shape);+ OPENVINO_ASSERT(can_compute_byte_strides,+ "Could not get strides for tensor type: ",+ m_element_type,+ ", shape: ",+ m_shape,+ " - byte strides are only representable when the element bitwidth evenly divides a byte "+ "and the last dimension is byte-aligned");std::call_once(m_strides_once, &ViewTensor::update_strides, this);return m_strides;}@@ -168,18 +188,8 @@ protected:}void update_strides() const {- if (m_element_type.bitwidth() < 8)- return;-- auto& shape = get_shape();- if (m_strides.empty() && !shape.empty()) {- m_strides.resize(shape.size());- m_strides.back() = shape.back() == 0 ? 0 : m_element_type.size();- std::transform(shape.crbegin(),- shape.crend() - 1,- m_strides.rbegin(),- m_strides.rbegin() + 1,- std::multiplies<size_t>());+ if (m_strides.empty() && util::can_compute_byte_strides(m_element_type, get_shape())) {+ m_strides = util::get_dense_byte_strides(m_element_type, get_shape());}}@@ -248,16 +258,25 @@ class StridedViewTensor : public ViewTensor {public:StridedViewTensor(const element::Type element_type, const Shape& shape, void* ptr, const Strides& strides): ViewTensor{element_type, shape, ptr} {- OPENVINO_ASSERT(- get_element_type().bitwidth() >= 8,- "Could not create strided access tensor for types with bitwidths less then 8 bit. Tensor type: ",- get_element_type());+ const auto can_compute_byte_strides = util::can_compute_byte_strides(get_element_type(), shape);+ OPENVINO_ASSERT(can_compute_byte_strides,+ "Could not create strided access tensor for tensor type: ",+ get_element_type(),+ ", shape: ",+ shape,+ " - byte strides are only representable when the element bitwidth evenly divides a byte "+ "and the last dimension is byte-aligned");// Save default stridesauto shape_strides = get_strides();// Change stridesm_strides = strides;OPENVINO_ASSERT(m_shape.size() == m_strides.size());+ const auto is_sub_byte = get_element_type().bitwidth() < 8;+ const auto has_dense_inner_stride = !is_sub_byte || m_strides.back() == shape_strides.back();+ OPENVINO_ASSERT(has_dense_inner_stride,+ "Sub-byte tensor must keep the default innermost byte stride, got: ",+ m_strides);for (size_t i = 0; i < m_strides.size(); ++i) {OPENVINO_ASSERT(shape_strides[i] <= m_strides[i],"shape stride: ",@@ -269,13 +288,17 @@ public:shape_strides[i],", stride: ",m_strides[i]);- if (i) {- OPENVINO_ASSERT(m_strides[i - 1] >= m_strides[i] * shape[i],- "Strides: ",- m_strides,- " are incompatible with shapes: ",- m_shape);- }+ }++ // for sub-byte types the last dimension's stride is not addressable placeholder (already validated above),+ // so it is excluded from the overlap check between neighboring dimensions+ const auto overlap_check_end = is_sub_byte ? m_strides.size() - 1 : m_strides.size();+ for (size_t i = 1; i < overlap_check_end; ++i) {+ OPENVINO_ASSERT(m_strides[i - 1] >= m_strides[i] * shape[i],+ "Strides: ",+ m_strides,+ " are incompatible with shapes: ",+ m_shape);}}@@ -292,6 +315,8 @@ public:i," is not compatible.");}+ const auto can_compute_byte_strides = util::can_compute_byte_strides(get_element_type(), new_shape);+ OPENVINO_ASSERT(can_compute_byte_strides, "Byte strides are not representable for shape: ", new_shape);m_shape = std::move(new_shape);}};@@ -470,12 +495,7 @@ public:: m_owner{owner},m_shape{make_roi_shape(owner->get_shape(), begin, end)},m_capacity{m_shape},- m_offset{- std::inner_product(begin.begin(), begin.end(), m_owner->get_strides().begin(), static_cast<size_t>(0))} {- OPENVINO_ASSERT(m_owner->get_element_type().bitwidth() >= 8,- "ROI Tensor for types with bitwidths less than 8 bit is not implemented. Tensor type: ",- m_owner->get_element_type());- }+ m_offset{compute_roi_offset(owner, begin, end)} {}void set_shape(ov::Shape new_shape) {OPENVINO_ASSERT(new_shape.size() >= m_shape.size());@@ -499,6 +519,8 @@ public:new_shape," for ROI tensor! The expanding rank dimension(s) of ROI must be ones, but it is not at index: ",std::distance(new_shape.cbegin(), new_dim.base()) - 1);+ const auto can_compute_byte_strides = util::can_compute_byte_strides(m_owner->get_element_type(), new_shape);+ OPENVINO_ASSERT(can_compute_byte_strides, "Byte strides are not representable for shape: ", new_shape);m_shape = std::move(new_shape);}