// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #include "core/common/span_utils.h" #include "core/framework/data_types.h" #include "core/graph/onnx_protobuf.h" #include "core/graph/constants.h" #include "core/framework/op_kernel.h" #include "core/framework/sparse_tensor.h" #include "core/framework/tensorprotoutils.h" #include "core/framework/sparse_utils.h" #include "core/framework/data_transfer.h" #include "core/graph/model.h" #include "core/session/inference_session.h" #include "test/providers/provider_test_utils.h" #include "asserts.h" #include "test/unittest_util/framework_test_utils.h" #include "file_util.h" #include "default_providers.h" #include "gtest/gtest.h" #include "gmock/gmock.h" #include "core/util/math_cpuonly.h" #include using namespace ONNX_NAMESPACE; using namespace onnxruntime::common; namespace onnxruntime { namespace test { template inline int64_t vector_len(const std::vector& v) { return static_cast(v.size()); } // This file contains sample implementations of several ops with sparse-tensor inputs/outputs. // Each op is implemented as a struct with the following signature: // struct SparseOp { // static std::string OpName(); // static ONNX_NAMESPACE::OpSchema OpSchema(); // class OpKernelImpl final : public OpKernel {...}; // static KernelDefBuilder KernelDef(); // } // op SparseFromCOO struct SparseFromCOO { static std::string OpName() { return "SparseFromCOO"; }; static ONNX_NAMESPACE::OpSchema OpSchema() { ONNX_NAMESPACE::OpSchema schema; schema.SetDoc(R"DOC( This operator constructs a sparse tensor from three tensors that provide a COO (coordinate) representation. )DOC") .Input( 0, "values", "A 1-dimensional tensor of shape [NNZ] that holds all non-zero values", "T1", OpSchema::Single) .Input( 1, "indices", "A 2-dimensional tensor of shape [NNZ,d] that holds the (d) indices of non-zero values", "T2", OpSchema::Single) .Input( 2, "shape", "A 1-dimensional tensor of shape [d] that holds the shape of the underlying dense tensor", "T2", OpSchema::Single) .Output( 0, "sparse_rep", "A sparse representation of the tensor", "T", OpSchema::Single) .TypeConstraint( "T1", {"tensor(int64)"}, "Type of the values (input tensor)") .TypeConstraint( "T2", {"tensor(int64)"}, "Type of index tensor and shape") .TypeConstraint( "T", {"sparse_tensor(int64)"}, "Output type"); return schema; } /** * @brief An implementation of the SparseFromCOO op. */ class OpKernelImpl final : public OpKernel { public: OpKernelImpl(const OpKernelInfo& info) : OpKernel{info} {} Status Compute(OpKernelContext* ctx) const override { ORT_ENFORCE(ctx->InputCount() == 3, "Expecting 3 inputs"); const Tensor& values = *ctx->Input(0); const Tensor& indices = *ctx->Input(1); const Tensor& shape_tensor = *ctx->Input(2); // values and indices should be 1-dimensional tensors const TensorShape& val_shape = values.Shape(); const TensorShape& ind_shape = indices.Shape(); const TensorShape& shape_shape = shape_tensor.Shape(); const auto nnz = val_shape.Size(); ORT_ENFORCE(val_shape.NumDimensions() == 1, "Values must be a 1-dimensional tensor."); ORT_ENFORCE(ind_shape.NumDimensions() == 1U || ind_shape.NumDimensions() == 2U, "Indices must be a 1-D or 2-D tensor."); if (ind_shape.NumDimensions() == 1) { ORT_ENFORCE(ind_shape[0] == nnz, "Indices must have [NNZ] shape."); } else { ORT_ENFORCE(ind_shape[0] == nnz, "Indices must have [NNZ,2] shape."); ORT_ENFORCE(ind_shape[1] == 2U, "Indices must have [NNZ,2] shape."); } ORT_ENFORCE(shape_shape.NumDimensions() == 1, "Shape must be a 1-dimensional tensor."); TensorShape shape(shape_tensor.Data(), shape_shape.Size()); #if !defined(DISABLE_SPARSE_TENSORS) SparseTensor* output = ctx->OutputSparse(0, shape); ORT_ENFORCE(output != nullptr); const auto& dtm = Info().GetDataTransferManager(); const auto* data_transfer = dtm.GetDataTransfer(OrtDevice(), output->Location().device); ORT_ENFORCE(data_transfer != nullptr, "Can not find corresponding data transfer"); ORT_THROW_IF_ERROR(output->MakeCooData(*data_transfer, OrtMemoryInfo(), static_cast(val_shape.Size()), values.DataRaw(), indices.DataAsSpan())); #endif return Status::OK(); } }; static KernelDefBuilder KernelDef() { KernelDefBuilder def; def.SetName(SparseFromCOO::OpName()) #if !defined(DISABLE_SPARSE_TENSORS) .TypeConstraint("T", DataTypeImpl::GetSparseTensorType()) #endif .TypeConstraint("T1", DataTypeImpl::GetTensorType()) .TypeConstraint("T2", DataTypeImpl::GetTensorType()); return def; } }; // op SparseAbs struct SparseAbs { static const std::string OpName() { return "SparseAbs"; }; // The ONNX schema for SparseAbs: static ONNX_NAMESPACE::OpSchema OpSchema() { ONNX_NAMESPACE::OpSchema schema; schema.SetDoc(R"DOC( This operator applies the Abs op element-wise to the input sparse-tensor. )DOC") .Input( 0, "input", "Input sparse tensor", "T", OpSchema::Single) .Output( 0, "output", "Output sparse tensor", "T", OpSchema::Single) .TypeConstraint( "T", {"sparse_tensor(int64)"}, "Input and Output type"); return schema; } // A kernel implementation of SparseAbs: class OpKernelImpl final : public OpKernel { public: OpKernelImpl(const OpKernelInfo& info) : OpKernel{info} {} Status Compute(OpKernelContext* ctx) const override { ORT_ENFORCE(ctx->InputCount() == 1, "Expecting 1 input"); #if !defined(DISABLE_SPARSE_TENSORS) const SparseTensor* input = ctx->Input(0); const auto* input_values = input->Values().Data(); const auto nnz = input->NumValues(); const auto& shape = input->DenseShape(); auto input_coo_view = input->AsCoo(); // Allocate/get output-tensor: SparseTensor* output = ctx->OutputSparse(0, shape); auto output_mutator = output->MakeCooData(nnz, static_cast(input_coo_view.Indices().Shape().Size())); // compute output values: auto* output_values = output_mutator.Values().MutableData(); for (size_t i = 0; i < nnz; ++i) output_values[i] = std::abs(input_values[i]); // Currently, there is no way to share the indices/shape between two sparse-tensors. // So, we copy indices/shape from input to output. // TODO: Extend allocation-planner to enable such sharing. const auto& input_indices = input_coo_view.Indices(); memcpy(output_mutator.Indices().MutableData(), input_indices.Data(), input_indices.SizeInBytes()); #endif return Status::OK(); } }; // A KernelDefBuilder for SparseAbs: static KernelDefBuilder KernelDef() { KernelDefBuilder def; #if !defined(DISABLE_SPARSE_TENSORS) def.SetName(OpName()) .TypeConstraint("T", DataTypeImpl::GetSparseTensorType()); #endif return def; } }; // op SparseToValues struct SparseToValues { static const std::string OpName() { return "SparseToValues"; }; static ONNX_NAMESPACE::OpSchema OpSchema() { ONNX_NAMESPACE::OpSchema schema; schema.SetDoc("Return the non-zero values in a sparse tensor (as a dense tensor).") .Input( 0, "sparse_rep", "Input sparse tensor.", "T1", OpSchema::Single) .Output( 0, "values", "A single dimensional tensor that holds non-zero values in the input", "T2", OpSchema::Single) .TypeConstraint( "T1", {"sparse_tensor(int64)"}, "Only int64 is allowed") .TypeConstraint( "T2", {"tensor(int64)"}, "Type of the values component"); return schema; } // A kernel implementation of SparseToValues class OpKernelImpl final : public OpKernel { public: OpKernelImpl(const OpKernelInfo& info) : OpKernel{info} {} Status Compute(OpKernelContext* ctx) const override { ORT_ENFORCE(ctx->InputCount() == 1, "Expecting a single SparseTensorSample input"); #if !defined(DISABLE_SPARSE_TENSORS) const SparseTensor* sparse_input = ctx->Input(0); const auto* values = sparse_input->Values().Data(); auto nnz = sparse_input->Values().Shape().Size(); TensorShape output_shape{nnz}; Tensor* output = ctx->Output(0, output_shape); int64_t* output_data = output->MutableData(); ORT_ENFORCE(output_data != nullptr); memcpy(output_data, values, sparse_input->Values().SizeInBytes()); #endif return Status::OK(); } }; // A KernelDefBuilder for SparseToValues static KernelDefBuilder KernelDef() { KernelDefBuilder def; #if !defined(DISABLE_SPARSE_TENSORS) def.SetName(OpName()) .TypeConstraint("T1", DataTypeImpl::GetSparseTensorType()) .TypeConstraint("T2", DataTypeImpl::GetTensorType()); #endif return def; } }; using Action = std::function; class SparseTensorTests : public testing::Test { protected: InferenceSession session_object; std::shared_ptr registry; std::unique_ptr model; std::vector schemas; std::vector register_actions; std::vector types; SparseTensorTests() : session_object(SessionOptions(), GetEnvironment()), registry(std::make_shared()) { } void SetUp() override { ASSERT_STATUS_OK(session_object.RegisterCustomRegistry(registry)); } template void Add() { auto schema = Op::OpSchema(); schema.SetName(Op::OpName()); schema.SetDomain(onnxruntime::kMLDomain); schema.SinceVersion(10); schemas.push_back(schema); Action register_kernel = [](CustomRegistry* registry2) { auto kernel_def_builder = Op::KernelDef(); kernel_def_builder .SetDomain(onnxruntime::kMLDomain) .SinceVersion(10) .Provider(onnxruntime::kCpuExecutionProvider); KernelCreateFn kernel_create_fn = [](FuncManager&, const OpKernelInfo& info, std::unique_ptr& out) { out = std::make_unique(info); return Status::OK(); }; ASSERT_STATUS_OK(registry2->RegisterCustomKernel(kernel_def_builder, kernel_create_fn)); }; register_actions.push_back(register_kernel); } void RegisterOps() { ASSERT_STATUS_OK(registry->RegisterOpSet(schemas, onnxruntime::kMLDomain, 10, 11)); for (auto& registerop : register_actions) registerop(registry.get()); } void BuildModel() { IOnnxRuntimeOpSchemaRegistryList custom_schema_registries = {registry->GetOpschemaRegistry()}; model.reset(new Model("SparseTensorTest", false, ModelMetaData(), PathString(), custom_schema_registries, {}, {}, DefaultLoggingManager().DefaultLogger())); } void SerializeAndLoad() { // Serialize model and deserialize it back std::string serialized_model; auto model_proto = model->ToProto(); EXPECT_TRUE(model_proto.SerializeToString(&serialized_model)); std::stringstream sstr(serialized_model); ASSERT_STATUS_OK(session_object.Load(sstr)); ASSERT_STATUS_OK(session_object.Initialize()); } #if !defined(DISABLE_SPARSE_TENSORS) NodeArg* Sparse(const std::string& name) { types.push_back(*DataTypeImpl::GetSparseTensorType()->GetTypeProto()); Graph& graph = model->MainGraph(); auto& arg = graph.GetOrCreateNodeArg(name, &types.back()); return &arg; } #endif NodeArg* Dense(const std::string& name) { types.push_back(*DataTypeImpl::GetTensorType()->GetTypeProto()); Graph& graph = model->MainGraph(); auto& arg = graph.GetOrCreateNodeArg(name, &types.back()); return &arg; } void Node(const std::string& op, const std::vector inputs, const std::vector outputs) { Graph& graph = model->MainGraph(); auto& node = graph.AddNode("", op, "", inputs, outputs, nullptr, onnxruntime::kMLDomain); node.SetExecutionProviderType(onnxruntime::kCpuExecutionProvider); } OrtValue Constant(const std::vector& elts) { const std::vector shape{static_cast(elts.size())}; return Constant(elts, shape); } OrtValue Constant(const std::vector& elts, const std::vector& shape) { OrtValue mlvalue; CreateMLValue(TestCPUExecutionProvider()->CreatePreferredAllocators()[0], shape, elts, &mlvalue); return mlvalue; } NameMLValMap feeds; void AddInput(NodeArg* arg, const std::vector& value) { feeds[arg->Name()] = Constant(value); } void AddInput(NodeArg* arg, const std::vector& value, const std::vector& shape) { feeds[arg->Name()] = Constant(value, shape); } void ExpectEq(OrtValue val1, OrtValue val2) { // Restricted to case where val1 and val2 are int64_t tensors auto& tensor1 = val1.Get(); auto& tensor2 = val2.Get(); EXPECT_EQ(tensor1.Shape().Size(), tensor2.Shape().Size()); auto* data1 = tensor1.Data(); auto* data2 = tensor2.Data(); for (int64_t i = 0, limit = tensor1.Shape().Size(); i < limit; ++i) { EXPECT_EQ(data1[i], data2[i]); } } void ExpectEq(OrtValue val1, const std::vector& data2) { // Restricted to case where val1 is an int64_t tensor auto& tensor1 = val1.Get(); EXPECT_EQ(static_cast(tensor1.Shape().Size()), data2.size()); auto* data1 = tensor1.Data(); for (int64_t i = 0, limit = tensor1.Shape().Size(); i < limit; ++i) { EXPECT_EQ(data1[i], data2[i]); } } std::vector output_names; std::vector expected_output; void ExpectOutput(NodeArg* arg, const std::vector& value) { output_names.push_back(arg->Name()); expected_output.push_back(Constant(value)); } void RunTest() { RunOptions run_options; std::vector fetches; ASSERT_STATUS_OK(session_object.Run(run_options, feeds, output_names, &fetches)); ASSERT_EQ(expected_output.size(), fetches.size()); for (size_t i = 0; i < fetches.size(); ++i) { ExpectEq(fetches[i], expected_output[i]); } } }; #if !defined(DISABLE_SPARSE_TENSORS) // Test ops SparseFromCOO, SparseAbs, and SparseToValues. // Tests 1-dimensional int64 sparse tensor. TEST_F(SparseTensorTests, Test1) { // Register ops Add(); Add(); Add(); RegisterOps(); // Build model/graph BuildModel(); // Node: create a sparse tensor from COO components: // sparse1 <- SparseFromCOO(values, indices, shape) auto values = Dense("values"); // a dense tensor containing non-zero-values auto indices = Dense("indices"); // a dense tensor containing indices of non-zero-values auto shape = Dense("shape"); // a dense tensor representing shape auto sparse1 = Sparse("sparse1"); // a sparse tensor created from above Node(SparseFromCOO::OpName(), {values, indices, shape}, {sparse1}); // Node:apply SparseAbs op // sparse2 <- SparseAbs(sparse1) auto sparse2 = Sparse("sparse2"); Node(SparseAbs::OpName(), {sparse1}, {sparse2}); // Node: Extract non-zero values from sparse2 // output <- SparseToValues(sparse2) auto output = Dense("output"); Node(SparseToValues::OpName(), {sparse2}, {output}); // Check graph, serialize it and deserialize it back Graph& graph = model->MainGraph(); ASSERT_STATUS_OK(graph.Resolve()); SerializeAndLoad(); // Run the model AddInput(values, {-99, 2}); AddInput(indices, {1, 4}, {2}); AddInput(shape, {5}); ExpectOutput(output, {99, 2}); RunTest(); } // Test ops SparseFromCOO, SparseAbs, and SparseToValues. // Tests 2-dimensional int64 sparse tensor. TEST_F(SparseTensorTests, Test2) { // Register ops Add(); Add(); Add(); RegisterOps(); // Build model/graph BuildModel(); // Node: create a sparse tensor from COO components: // sparse1 <- SparseFromCOO(values, indices, shape) auto values = Dense("values"); // a dense tensor containing non-zero-values auto indices = Dense("indices"); // a dense tensor containing indices of non-zero-values auto shape = Dense("shape"); // a dense tensor representing shape auto sparse1 = Sparse("sparse1"); // a sparse tensor created from above Node(SparseFromCOO::OpName(), {values, indices, shape}, {sparse1}); // Node:apply SparseAbs op // sparse2 <- SparseAbs(sparse1) auto sparse2 = Sparse("sparse2"); Node(SparseAbs::OpName(), {sparse1}, {sparse2}); // Node: Extract non-zero values from sparse2 // output <- SparseToValues(sparse2) auto output = Dense("output"); Node(SparseToValues::OpName(), {sparse2}, {output}); // Check graph, serialize it and deserialize it back Graph& graph = model->MainGraph(); ASSERT_STATUS_OK(graph.Resolve()); SerializeAndLoad(); // Run the model AddInput(values, {-99, 2}); AddInput(indices, {1, 1, 4, 4}, {2, 2}); AddInput(shape, {5, 5}); ExpectOutput(output, {99, 2}); RunTest(); } TEST(SparseCrcsFormatTests, Test1) { // const std::vector input_data = { // 0, 1, 2, 0, 0, 0, 3, 4, 5, // 6, 7, 8, 0, 0, 0, 9, 10, 11, // 12, 13, 14, 0, 0, 0, 15, 16, 17, // 0, 0, 0, 18, 19, 20, 21, 22, 23, // 0, 0, 0, 24, 25, 26, 27, 28, 29, // 0, 0, 0, 30, 31, 32, 33, 34, 35, // 36, 37, 38, 39, 40, 41, 0, 0, 0, // 42, 43, 44, 45, 46, 47, 0, 0, 0, // 48, 49, 50, 51, 52, 53, 0, 0, 0}; auto* cpu_provider = TestCPUExecutionProvider(); auto cpu_transfer = cpu_provider->GetDataTransfer(); TensorShape dense_shape{9, 9}; std::vector values = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53}; TensorShape values_shape{vector_len(values)}; // Row major std::vector inner_indices = { 1, 2, 6, 7, 8, 0, 1, 2, 6, 7, 8, 0, 1, 2, 6, 7, 8, 3, 4, 5, 6, 7, 8, 3, 4, 5, 6, 7, 8, 3, 4, 5, 6, 7, 8, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5}; ASSERT_EQ(values.size(), inner_indices.size()); std::vector outer_indices = { 0, 5, 11, 17, 23, 29, 35, 41, 47, 53}; ASSERT_EQ(9U + 1U, outer_indices.size()); // Test owning instance auto default_allocator = TestCPUExecutionProvider()->CreatePreferredAllocators()[0]; SparseTensor tensor_alloc(DataTypeImpl::GetType(), dense_shape, default_allocator); ASSERT_EQ(tensor_alloc.DenseShape(), dense_shape); ASSERT_STATUS_OK(tensor_alloc.MakeCsrData(*cpu_transfer, OrtMemoryInfo(), values.size(), values.data(), gsl::make_span(inner_indices), gsl::make_span(outer_indices))); ASSERT_EQ(values.size(), tensor_alloc.NumValues()); ASSERT_EQ(0, memcmp(tensor_alloc.Values().Data(), values.data(), tensor_alloc.Values().SizeInBytes())); { auto csr_view = tensor_alloc.AsCsr(); const Tensor& inner = csr_view.Inner(); const Tensor& outer = csr_view.Outer(); ASSERT_EQ(inner.Shape().Size(), vector_len(inner_indices)); ASSERT_EQ(outer.Shape().Size(), vector_len(outer_indices)); ASSERT_EQ(0, memcmp(inner.Data(), inner_indices.data(), inner.SizeInBytes())); ASSERT_EQ(0, memcmp(outer.Data(), outer_indices.data(), outer.SizeInBytes())); } OrtMemoryInfo mem_info; SparseTensor tensor_wrap(DataTypeImpl::GetType(), dense_shape, {vector_len(values)}, values.data(), mem_info); ASSERT_EQ(tensor_wrap.DenseShape(), dense_shape); ASSERT_STATUS_OK(tensor_wrap.UseCsrIndices(gsl::make_span(inner_indices), gsl::make_span(outer_indices))); ASSERT_EQ(values.size(), tensor_wrap.NumValues()); ASSERT_EQ(0, memcmp(tensor_alloc.Values().Data(), tensor_wrap.Values().Data(), values.size() * sizeof(float))); auto csr_alloc = tensor_alloc.AsCsr(); auto csr_wrap = tensor_wrap.AsCsr(); ASSERT_EQ(0, memcmp(csr_alloc.Inner().Data(), csr_wrap.Inner().Data(), inner_indices.size() * sizeof(int64_t))); ASSERT_EQ(0, memcmp(csr_alloc.Outer().Data(), csr_wrap.Outer().Data(), outer_indices.size() * sizeof(int64_t))); } #endif // !defined(DISABLE_SPARSE_TENSORS) // Code below depends on the values being size 4 template static std::vector CreateValues() { return {1, 2, 3, 4}; } /* std::string support in the future template <> std::vector CreateValues() { return {"one", "two", "three", "four"}; } */ template <> std::vector CreateValues() { return {BFloat16(1.f), BFloat16(2.f), BFloat16(3.f), BFloat16(4.f)}; } template <> std::vector CreateValues() { return {MLFloat16(1.f), MLFloat16(2.f), MLFloat16(3.f), MLFloat16(4.f)}; } template static void CreateTensorWithExternalData( TensorProto_DataType type, const std::vector& test_data, std::basic_string& filename, TensorProto& tensor_proto) { size_t size_in_bytes = test_data.size() * sizeof(T); std::vector le_data; le_data.resize(size_in_bytes); auto src_span = gsl::make_span(test_data.data(), test_data.size()); auto dst_span = gsl::make_span(le_data.data(), le_data.size()); ASSERT_STATUS_OK(onnxruntime::utils::WriteLittleEndian(src_span, dst_span)); // Create external data FILE* fp; CreateTestFile(fp, filename); ASSERT_EQ(size_in_bytes, fwrite(le_data.data(), 1, size_in_bytes, fp)); ASSERT_EQ(0, fclose(fp)); // set the tensor_proto to reference this external data onnx::StringStringEntryProto* location = tensor_proto.mutable_external_data()->Add(); location->set_key("location"); location->set_value(ToUTF8String(filename)); tensor_proto.set_data_location(onnx::TensorProto_DataLocation_EXTERNAL); tensor_proto.set_data_type(type); } namespace { void insert_indices_data(bool indices_1D, size_t values_size, size_t shape_size, std::vector& indices_data, TensorProto& indices_tp) { if (indices_1D) { indices_data = {2, 5, 6, 10}; indices_tp.add_dims(indices_data.size()); } else { // indices are shape {NNZ, rank} so convert flattened values of 2, 5, 6 and 10 to rank 3 values indices_tp.add_dims(values_size); indices_tp.add_dims(shape_size); indices_data = { 0, 1, 0, 0, 2, 1, 1, 0, 0, 1, 2, 0}; } } template struct InsertIndices { void operator()(bool indices_1D, size_t values_size, size_t shape_size, TensorProto& indices_tp) const { static_assert(std::is_integral_v, "indices data must be integral data type"); static_assert(std::is_signed_v, "indices must be signed data type"); std::vector indices_data; insert_indices_data(indices_1D, values_size, shape_size, indices_data, indices_tp); indices_tp.set_data_type(utils::ToTensorProtoElementType()); if constexpr (sizeof(T) == sizeof(int8_t)) { indices_tp.mutable_raw_data()->assign(reinterpret_cast(indices_data.data()), indices_data.size()); } else { // Conversion on the fly to the target data type std::vector indices(indices_data.cbegin(), indices_data.cend()); indices_tp.mutable_raw_data()->assign(reinterpret_cast(indices.data()), indices.size() * sizeof(T)); if constexpr (endian::native != endian::little) { utils::ConvertRawDataInTensorProto(indices_tp); } } } }; using SupportedIndicesTypeList = onnxruntime::TypeList; } // namespace template static NodeProto CreateConstantNode(bool indices_1D, int32_t indices_type, std::function& values, TensorProto& tp)> inserter, std::vector& expected_data) { NodeProto constant_node; constant_node.set_op_type("Constant"); constant_node.add_output("dense_tensor_output"); std::vector values = CreateValues(); std::vector shape{2, 3, 2}; AttributeProto& attrib = *constant_node.mutable_attribute()->Add(); attrib.set_name("sparse_value"); attrib.set_type(AttributeProto_AttributeType_SPARSE_TENSOR); SparseTensorProto& stp = *attrib.mutable_sparse_tensor(); stp.mutable_dims()->Add(shape.cbegin(), shape.cend()); TensorProto& indices_tp = *stp.mutable_indices(); utils::MLTypeCallDispatcherFromTypeList type_disp(indices_type); type_disp.Invoke(indices_1D, values.size(), shape.size(), indices_tp); expected_data.resize(2 * 3 * 2); expected_data[2] = values[0]; expected_data[5] = values[1]; expected_data[6] = values[2]; expected_data[10] = values[3]; stp.mutable_values()->add_dims(values.size()); inserter(values, *stp.mutable_values()); return constant_node; } template static NodeProto CreateConstantNodeAllZeros(bool indices_1D, std::vector& expected_data) { NodeProto constant_node; constant_node.set_op_type("Constant"); constant_node.add_output("dense_tensor_output"); const std::array shape{2, 3, 2}; AttributeProto& attrib = *constant_node.mutable_attribute()->Add(); attrib.set_name("sparse_value_all_zeros"); attrib.set_type(AttributeProto_AttributeType_SPARSE_TENSOR); SparseTensorProto& stp = *attrib.mutable_sparse_tensor(); stp.mutable_dims()->Add(shape.cbegin(), shape.cend()); TensorProto& indices_tp = *stp.mutable_indices(); if (indices_1D) { indices_tp.add_dims(0); } else { // indices are shape {NNZ, rank} so convert flattened values of 2, 5, 6 and 10 to rank 3 values indices_tp.add_dims(0); indices_tp.add_dims(3); } indices_tp.set_data_type(ONNX_NAMESPACE::TensorProto_DataType_INT64); // Must be all zeros expected_data.resize(2 * 3 * 2); auto& mutable_values = *stp.mutable_values(); mutable_values.set_name("all_zeros"); mutable_values.set_data_type(utils::ToTensorProtoElementType()); mutable_values.add_dims(0); return constant_node; } template static void TestConversion(bool use_1D_indices, int32_t indices_type, std::function& values, TensorProto& tp)> inserter, std::function expected, const TensorProto& actual)> checker) { std::vector expected; auto node = CreateConstantNode(use_1D_indices, indices_type, inserter, expected); TensorProto dense; // Path is required for loading external data (if any) // When path is empty it will look for the data in current dir ASSERT_STATUS_OK(utils::ConstantNodeProtoToTensorProto(node, std::filesystem::path(), dense)); gsl::span expected_span = gsl::make_span(expected.data(), expected.size()); checker(expected_span, dense); } template static void TestConversionAllZeros(bool use_1D_indices, std::function expected, const TensorProto& actual)> checker) { std::vector expected; auto node = CreateConstantNodeAllZeros(use_1D_indices, expected); TensorProto dense; // Path is required for loading external data (if any) // When path is empty it will look for the data in current dir ASSERT_STATUS_OK(utils::ConstantNodeProtoToTensorProto(node, std::filesystem::path(), dense)); gsl::span expected_span = gsl::make_span(expected.data(), expected.size()); checker(expected_span, dense); } template static void TestConversion( std::function& values, TensorProto& tp)> inserter, std::function expected, const TensorProto& actual)> checker) { std::vector indices_types{ TensorProto_DataType_INT8, TensorProto_DataType_INT16, TensorProto_DataType_INT32, TensorProto_DataType_INT64}; for (auto dt : indices_types) { TestConversion(true, dt, inserter, checker); TestConversion(false, dt, inserter, checker); } TestConversionAllZeros(true, checker); TestConversionAllZeros(false, checker); } template static void RawDataWriter(const std::vector& values, TensorProto& tp, TensorProto_DataType datatype) { tp.set_data_type(datatype); utils::SetRawDataInTensorProto(tp, values.data(), values.size() * sizeof(T)); } int64_t ActualSize(const TensorProto& actual) { int64_t actual_size = 1; for (const auto dim : actual.dims()) { actual_size *= dim; } return actual_size; } template static void RawDataChecker(gsl::span expected, TensorProto actual) { int64_t actual_size = ActualSize(actual); // raw data is LE, might need to convert it if constexpr (endian::native != endian::little) { onnxruntime::utils::ConvertRawDataInTensorProto(actual); } const T* raw_data = reinterpret_cast(actual.raw_data().data()); auto actual_span = gsl::make_span(raw_data, actual_size); ASSERT_THAT(actual_span, testing::ContainerEq(expected)); } template <> void RawDataChecker(gsl::span expected_bfloat, TensorProto actual) { int64_t actual_size = ActualSize(actual); // raw data is LE, might need to convert it if constexpr (endian::native != endian::little) { onnxruntime::utils::ConvertRawDataInTensorProto(actual); } auto expected = ReinterpretAsSpan(expected_bfloat); const uint16_t* raw_data = reinterpret_cast(actual.raw_data().data()); auto actual_span = gsl::make_span(raw_data, actual_size); ASSERT_THAT(actual_span, testing::ContainerEq(expected)); } template <> void RawDataChecker(gsl::span expected_bfloat, TensorProto actual) { int64_t actual_size = ActualSize(actual); // raw data is LE, might need to convert it if constexpr (endian::native != endian::little) { onnxruntime::utils::ConvertRawDataInTensorProto(actual); } auto expected = ReinterpretAsSpan(expected_bfloat); const uint16_t* raw_data = reinterpret_cast(actual.raw_data().data()); auto actual_span = gsl::make_span(raw_data, actual_size); ASSERT_THAT(actual_span, testing::ContainerEq(expected)); } TEST(SparseTensorConversionTests, TestConstantNodeConversion) { TestConversion( [](const std::vector& values, TensorProto& tp) { tp.set_data_type(TensorProto_DataType_FLOAT); tp.mutable_float_data()->Add(values.cbegin(), values.cend()); }, RawDataChecker); TestConversion( [](const std::vector& values, TensorProto& tp) { tp.set_data_type(TensorProto_DataType_DOUBLE); tp.mutable_double_data()->Add(values.cbegin(), values.cend()); }, RawDataChecker); TestConversion( [](const std::vector& values, TensorProto& tp) { tp.set_data_type(TensorProto_DataType_BFLOAT16); for (auto v : values) { tp.mutable_int32_data()->Add(v.val); } }, RawDataChecker); TestConversion( [](const std::vector& values, TensorProto& tp) { tp.set_data_type(TensorProto_DataType_FLOAT16); for (auto v : values) { tp.mutable_int32_data()->Add(v.val); } }, RawDataChecker); TestConversion( [](const std::vector& values, TensorProto& tp) { tp.set_data_type(TensorProto_DataType_INT16); tp.mutable_int32_data()->Add(values.cbegin(), values.cend()); }, RawDataChecker); TestConversion( [](const std::vector& values, TensorProto& tp) { tp.set_data_type(TensorProto_DataType_UINT16); tp.mutable_int32_data()->Add(values.cbegin(), values.cend()); }, RawDataChecker); TestConversion( [](const std::vector& values, TensorProto& tp) { tp.set_data_type(TensorProto_DataType_INT32); tp.mutable_int32_data()->Add(values.cbegin(), values.cend()); }, RawDataChecker); TestConversion( [](const std::vector& values, TensorProto& tp) { tp.set_data_type(TensorProto_DataType_UINT32); tp.mutable_uint64_data()->Add(values.cbegin(), values.cend()); }, RawDataChecker); // Test all zeros case TestConversion( [](const std::vector& values, TensorProto& tp) { tp.set_data_type(TensorProto_DataType_INT64); tp.mutable_int64_data()->Add(values.cbegin(), values.cend()); }, RawDataChecker); TestConversion( [](const std::vector& values, TensorProto& tp) { tp.set_data_type(TensorProto_DataType_UINT64); tp.mutable_uint64_data()->Add(values.cbegin(), values.cend()); }, RawDataChecker); TestConversion( [](const std::vector& values, TensorProto& tp) { tp.set_data_type(TensorProto_DataType_INT8); tp.mutable_int32_data()->Add(values.cbegin(), values.cend()); }, RawDataChecker); TestConversion( [](const std::vector& values, TensorProto& tp) { RawDataWriter(values, tp, TensorProto_DataType_UINT8); }, RawDataChecker); // Test constant node conversion for SparseTensor with external data PathString tensor_filename(ORT_TSTR("tensor_XXXXXX")); TestConversion( true, TensorProto_DataType_INT64, [&tensor_filename](const std::vector& values, TensorProto& tp) { CreateTensorWithExternalData(TensorProto_DataType_FLOAT, values, tensor_filename, tp); }, RawDataChecker); DeleteFileFromDisk(tensor_filename.c_str()); } /// Dense to Sparse conversion tests #if !defined(DISABLE_SPARSE_TENSORS) #if !defined(ORT_MINIMAL_BUILD) template static std::vector CreateSparseValues(size_t indices_start) { std::vector result(indices_start + 2); result[indices_start] = 2; result[indices_start + 1] = 3; return result; } /* std::string support in the future template <> std::vector CreateSparseValues() { return {"", "two", "three", ""}; } */ template <> std::vector CreateSparseValues(size_t indices_start) { std::vector result(indices_start + 2); result[indices_start] = BFloat16(2.f); result[indices_start + 1] = BFloat16(3.f); return result; } template <> std::vector CreateSparseValues(size_t indices_start) { std::vector result(indices_start + 2); result[indices_start] = MLFloat16(2.f); result[indices_start + 1] = MLFloat16(3.f); return result; } template static std::vector CreateSparseValuesAllZeros() { return {0, 0, 0, 0}; } template <> std::vector CreateSparseValuesAllZeros() { return {BFloat16(0.f), BFloat16(0.f), BFloat16(0.f), BFloat16(0.f)}; } template <> std::vector CreateSparseValuesAllZeros() { return {MLFloat16(0.f), MLFloat16(0.f), MLFloat16(0.f), MLFloat16(0.f)}; } template TensorProto CreateDenseTensor(size_t indices_start, std::function& values, TensorProto& tp)> inserter, std::vector& expected_values, std::vector& expected_indicies) { TensorProto result; std::vector values = CreateSparseValues(indices_start); auto ind_start = static_cast(indices_start); expected_indicies = {ind_start, ind_start + 1}; for (const auto& ind : expected_indicies) { expected_values.push_back(values[ind]); } inserter(values, result); result.add_dims(static_cast(values.size())); return result; } template TensorProto CreateDenseTensorAllZeros(std::function& values, TensorProto& tp)> inserter) { TensorProto result; std::vector values = CreateSparseValuesAllZeros(); inserter(values, result); result.add_dims(static_cast(values.size())); return result; } int64_t ActualSize(const SparseTensorProto& actual) { int64_t actual_size = 1; for (const auto dim : actual.values().dims()) { actual_size *= dim; } return actual_size; } template static void RawSparseDataChecker(gsl::span expected_values, gsl::span expected_indicies, const SparseTensorProto& actual) { const int64_t actual_size = ActualSize(actual); auto actual_values = actual.values(); // raw data is LE, might need to convert it if constexpr (endian::native != endian::little) { onnxruntime::utils::ConvertRawDataInTensorProto(actual_values); } const T* raw_data = reinterpret_cast(actual_values.raw_data().data()); auto actual_span = gsl::make_span(raw_data, actual_size); ASSERT_THAT(actual_span, testing::ContainerEq(expected_values)); SparseIndicesChecker(actual.indices(), expected_indicies); } template <> void RawSparseDataChecker(gsl::span expected_bfloat, gsl::span expected_indicies, const SparseTensorProto& actual) { const int64_t actual_size = ActualSize(actual); auto actual_values = actual.values(); // raw data is LE, might need to convert it if constexpr (endian::native != endian::little) { onnxruntime::utils::ConvertRawDataInTensorProto(actual_values); } static_assert(sizeof(uint16_t) == sizeof(BFloat16), "Expecting equal sizes"); auto expected = ReinterpretAsSpan(expected_bfloat); const uint16_t* raw_data = reinterpret_cast(actual_values.raw_data().data()); auto actual_span = gsl::make_span(raw_data, actual_size); ASSERT_THAT(actual_span, testing::ContainerEq(expected)); SparseIndicesChecker(actual.indices(), expected_indicies); } template <> void RawSparseDataChecker(gsl::span expected_bfloat, gsl::span expected_indicies, const SparseTensorProto& actual) { const int64_t actual_size = ActualSize(actual); auto actual_values = actual.values(); // raw data is LE, might need to convert it if constexpr (endian::native != endian::little) { onnxruntime::utils::ConvertRawDataInTensorProto(actual_values); } static_assert(sizeof(uint16_t) == sizeof(MLFloat16), "Expecting equal sizes"); auto expected = ReinterpretAsSpan(expected_bfloat); const uint16_t* raw_data = reinterpret_cast(actual_values.raw_data().data()); auto actual_span = gsl::make_span(raw_data, actual_size); ASSERT_THAT(actual_span, testing::ContainerEq(expected)); SparseIndicesChecker(actual.indices(), expected_indicies); } template static Status TestDenseToSparseConversionValues(size_t indices_start, std::function& values, TensorProto& tp)> inserter, std::function expected, gsl::span expected_indicies, const SparseTensorProto& actual)> checker) { std::vector expected_values; std::vector expected_indicies; // Path is required for loading external data // Using empty path here since the data is not external std::filesystem::path model_path; TensorProto dense_tensor = CreateDenseTensor(indices_start, inserter, expected_values, expected_indicies); SparseTensorProto sparse_tensor; ORT_RETURN_IF_ERROR(utils::DenseTensorToSparseTensorProto(dense_tensor, model_path, sparse_tensor)); gsl::span expected_values_span = gsl::make_span(expected_values.data(), expected_values.size()); gsl::span expected_ind_span = gsl::make_span(expected_indicies.data(), expected_indicies.size()); checker(expected_values_span, expected_ind_span, sparse_tensor); return Status::OK(); } template static Status TestDenseAllZerosToSparseConversion( std::function& values, TensorProto& tp)> inserter, std::function expected, gsl::span expected_indicies, const SparseTensorProto& actual)> checker) { std::vector expected_values; std::vector expected_indicies; // Path is required for loading external data // Using empty path here since the data is not external std::filesystem::path model_path; TensorProto dense_tensor = CreateDenseTensorAllZeros(inserter); SparseTensorProto sparse_tensor; ORT_RETURN_IF_ERROR(utils::DenseTensorToSparseTensorProto(dense_tensor, model_path, sparse_tensor)); gsl::span expected_values_span = gsl::make_span(expected_values.data(), expected_values.size()); gsl::span expected_ind_span = gsl::make_span(expected_indicies.data(), expected_indicies.size()); checker(expected_values_span, expected_ind_span, sparse_tensor); return Status::OK(); } template static Status TestDenseToSparseConversion(size_t indices_start, std::function& values, TensorProto& tp)> inserter, std::function expected, gsl::span expected_indicies, const SparseTensorProto& actual)> checker) { ORT_RETURN_IF_ERROR(TestDenseToSparseConversionValues(indices_start, inserter, checker)); return TestDenseAllZerosToSparseConversion(inserter, checker); } TEST(SparseTensorConversionTests, TestDenseToSparseConversion) { // This one will test indices that are less than max int8 value // which should result in int8 indices ASSERT_STATUS_OK(TestDenseToSparseConversion( 20U, [](const std::vector& values, TensorProto& tp) { tp.set_data_type(TensorProto_DataType_FLOAT); tp.set_name("dense_float"); tp.mutable_float_data()->Add(values.cbegin(), values.cend()); }, RawSparseDataChecker)); // This one will test indices that are max(int8) < ind < max(int16) value // which should result in int16 indices ASSERT_STATUS_OK(TestDenseToSparseConversion( static_cast(std::numeric_limits::max()) + 20U, [](const std::vector& values, TensorProto& tp) { tp.set_data_type(TensorProto_DataType_DOUBLE); tp.set_name("dense_double"); tp.mutable_double_data()->Add(values.cbegin(), values.cend()); }, RawSparseDataChecker)); // This one will test indices that are max(int16) < ind < max(int32) value // which should result in int32 indices ASSERT_STATUS_OK(TestDenseToSparseConversion( static_cast(std::numeric_limits::max()) + 20U, [](const std::vector& values, TensorProto& tp) { tp.set_data_type(TensorProto_DataType_BFLOAT16); tp.set_name("dense_bfloat16"); for (auto v : values) { tp.mutable_int32_data()->Add(v.val); } }, RawSparseDataChecker)); // Protobuf can not hold anything more than 2Gb and it overflows. Can't test 64-bit indices // on conversion unless explicitly created. // which should result in int32 indices ASSERT_STATUS_OK(TestDenseToSparseConversion( 20U, [](const std::vector& values, TensorProto& tp) { tp.set_data_type(TensorProto_DataType_FLOAT16); tp.set_name("dense_float16"); for (auto v : values) { tp.mutable_int32_data()->Add(v.val); } }, RawSparseDataChecker)); ASSERT_STATUS_OK(TestDenseToSparseConversion( 20U, [](const std::vector& values, TensorProto& tp) { tp.set_name("dense_int16"); tp.set_data_type(TensorProto_DataType_INT16); tp.mutable_int32_data()->Add(values.cbegin(), values.cend()); }, RawSparseDataChecker)); ASSERT_STATUS_OK(TestDenseToSparseConversion( 20U, [](const std::vector& values, TensorProto& tp) { tp.set_name("dense_uint16"); tp.set_data_type(TensorProto_DataType_UINT16); tp.mutable_int32_data()->Add(values.cbegin(), values.cend()); }, RawSparseDataChecker)); ASSERT_STATUS_OK(TestDenseToSparseConversion( 20U, [](const std::vector& values, TensorProto& tp) { tp.set_name("dense_int32"); tp.set_data_type(TensorProto_DataType_INT32); tp.mutable_int32_data()->Add(values.cbegin(), values.cend()); }, RawSparseDataChecker)); ASSERT_STATUS_OK(TestDenseToSparseConversion( 20U, [](const std::vector& values, TensorProto& tp) { tp.set_name("dense_uint32"); tp.set_data_type(TensorProto_DataType_UINT32); tp.mutable_uint64_data()->Add(values.cbegin(), values.cend()); }, RawSparseDataChecker)); ASSERT_STATUS_OK(TestDenseToSparseConversion( 20U, [](const std::vector& values, TensorProto& tp) { tp.set_name("dense_int64"); tp.set_data_type(TensorProto_DataType_INT64); tp.mutable_int64_data()->Add(values.cbegin(), values.cend()); }, RawSparseDataChecker)); ASSERT_STATUS_OK(TestDenseToSparseConversion( 20U, [](const std::vector& values, TensorProto& tp) { tp.set_name("dense_uint64"); tp.set_data_type(TensorProto_DataType_UINT64); tp.mutable_uint64_data()->Add(values.cbegin(), values.cend()); }, RawSparseDataChecker)); ASSERT_STATUS_OK(TestDenseToSparseConversion( 20U, [](const std::vector& values, TensorProto& tp) { tp.set_name("dense_int8"); tp.set_data_type(TensorProto_DataType_INT8); tp.mutable_int32_data()->Add(values.cbegin(), values.cend()); }, RawSparseDataChecker)); ASSERT_STATUS_OK(TestDenseToSparseConversion( 20U, [](const std::vector& values, TensorProto& tp) { tp.set_name("dense_int64"); RawDataWriter(values, tp, TensorProto_DataType_UINT8); }, RawSparseDataChecker)); } TEST(SparseTensorConversionTests, CsrConversion) { auto* cpu_provider = TestCPUExecutionProvider(); auto cpu_allocator = cpu_provider->CreatePreferredAllocators()[0]; const TensorShape dense_shape{3, 3}; std::vector dense_data = { 0, 0, 1, 1, 0, 1, 0, 0, 0}; std::vector dense_data_str = { "", "", "1", "1", "", "1", "", "", ""}; std::vector dense_data_all_zeros = { 0, 0, 0, 0, 0, 0, 0, 0, 0}; const std::vector expected_values = {1, 1, 1}; const std::vector expected_values_str = {"1", "1", "1"}; const char* const strings[] = {"1", "1", "1"}; const std::vector expected_inner = {2, 0, 2}; const std::vector expected_outer = {0, 1, 3, 3}; DataTransferManager dtm; { auto cpu_transfer = cpu_provider->GetDataTransfer(); ASSERT_STATUS_OK(dtm.RegisterDataTransfer(std::move(cpu_transfer))); } { { // Test CSR initialization of 100% sparse tensor, passing 0 in the shape SparseTensor fully_sparse(DataTypeImpl::GetType(), TensorShape{3, 3}, cpu_allocator); ASSERT_STATUS_OK(fully_sparse.MakeCsrData(*cpu_provider->GetDataTransfer(), cpu_allocator->Info(), 0U, nullptr, gsl::span(), gsl::span())); ASSERT_EQ(fully_sparse.Format(), SparseFormat::kCsrc); ASSERT_EQ(0, fully_sparse.RequiredAllocationSize()); ASSERT_EQ(0U, fully_sparse.NumValues()); ASSERT_EQ(1U, fully_sparse.Values().Shape().GetDims().size()); ASSERT_EQ(0, fully_sparse.Values().Shape().Size()); ASSERT_TRUE(fully_sparse.Values().DataAsSpan().empty()); auto csr_view = fully_sparse.AsCsr(); const auto& inner = csr_view.Inner(); ASSERT_EQ(0, inner.Shape().Size()); ASSERT_EQ(1U, inner.Shape().GetDims().size()); ASSERT_TRUE(inner.DataAsSpan().empty()); const auto& outer = csr_view.Outer(); ASSERT_EQ(0, outer.Shape().Size()); ASSERT_EQ(1U, outer.Shape().GetDims().size()); ASSERT_TRUE(outer.DataAsSpan().empty()); } { // Test CSR initialization of 100% sparse tensor, passing 0 in the shape SparseTensor fully_sparse(DataTypeImpl::GetType(), TensorShape{3, 3}, TensorShape{0}, nullptr, cpu_allocator->Info()); ASSERT_STATUS_OK(fully_sparse.UseCsrIndices(gsl::span(), gsl::span())); ASSERT_EQ(fully_sparse.Format(), SparseFormat::kCsrc); ASSERT_EQ(0, fully_sparse.RequiredAllocationSize()); ASSERT_EQ(0U, fully_sparse.NumValues()); ASSERT_EQ(1U, fully_sparse.Values().Shape().GetDims().size()); ASSERT_EQ(0, fully_sparse.Values().Shape().Size()); ASSERT_TRUE(fully_sparse.Values().DataAsSpan().empty()); auto csr_view = fully_sparse.AsCsr(); const auto& inner = csr_view.Inner(); ASSERT_EQ(0, inner.Shape().Size()); ASSERT_EQ(1U, inner.Shape().GetDims().size()); ASSERT_TRUE(inner.DataAsSpan().empty()); const auto& outer = csr_view.Outer(); ASSERT_EQ(0, outer.Shape().Size()); ASSERT_EQ(1U, outer.Shape().GetDims().size()); ASSERT_TRUE(outer.DataAsSpan().empty()); } } Tensor dense_cpu_src(DataTypeImpl::GetType(), dense_shape, dense_data.data(), cpu_allocator->Info()); { // test where both src and destination are on CPU SparseTensor dst; ASSERT_STATUS_OK(sparse_utils::DenseTensorToSparseCsr(dtm, dense_cpu_src, cpu_allocator, cpu_allocator, dst)); ASSERT_EQ(dst.Format(), SparseFormat::kCsrc); ASSERT_EQ(dense_cpu_src.DataType(), dst.DataType()); ASSERT_EQ(dense_cpu_src.Shape(), dst.DenseShape()); ASSERT_EQ(dst.NumValues(), expected_values.size()); auto values = dst.Values().DataAsSpan(); ASSERT_TRUE(std::equal(expected_values.cbegin(), expected_values.cend(), values.begin(), values.end())); auto csr_view = dst.AsCsr(); auto inner = csr_view.Inner().DataAsSpan(); ASSERT_EQ(expected_inner.size(), inner.size()); ASSERT_TRUE(std::equal(expected_inner.cbegin(), expected_inner.cend(), inner.begin(), inner.end())); auto outer = csr_view.Outer().DataAsSpan(); ASSERT_EQ(expected_outer.size(), outer.size()); ASSERT_TRUE(std::equal(expected_outer.cbegin(), expected_outer.cend(), outer.begin(), outer.end())); // Let's convert back to make sure we get the original Tensor dense_dst; const SparseTensor& sparse_src = dst; ASSERT_STATUS_OK(sparse_utils::SparseCsrToDenseTensor(dtm, sparse_src, cpu_allocator, cpu_allocator, dense_dst)); ASSERT_EQ(dense_dst.DataType(), sparse_src.DataType()); ASSERT_EQ(dense_dst.Shape(), sparse_src.DenseShape()); ASSERT_EQ(dense_dst.Shape().Size(), vector_len(dense_data)); auto dense_values_dst = dense_dst.DataAsSpan(); ASSERT_EQ(dense_values_dst.size(), dense_data.size()); ASSERT_TRUE(std::equal(dense_values_dst.begin(), dense_values_dst.end(), dense_data.cbegin(), dense_data.cend())); } // Strings test { Tensor str_cpu_src(DataTypeImpl::GetType(), dense_shape, dense_data_str.data(), cpu_allocator->Info()); SparseTensor dst; ASSERT_STATUS_OK(sparse_utils::DenseTensorToSparseCsr(dtm, str_cpu_src, cpu_allocator, cpu_allocator, dst)); ASSERT_EQ(dst.Format(), SparseFormat::kCsrc); ASSERT_EQ(str_cpu_src.DataType(), dst.DataType()); ASSERT_EQ(str_cpu_src.Shape(), dst.DenseShape()); ASSERT_EQ(dst.NumValues(), expected_values_str.size()); auto values = dst.Values().DataAsSpan(); ASSERT_TRUE(std::equal(expected_values_str.cbegin(), expected_values_str.cend(), values.begin(), values.end())); auto csr_view = dst.AsCsr(); auto inner = csr_view.Inner().DataAsSpan(); ASSERT_EQ(expected_inner.size(), inner.size()); ASSERT_TRUE(std::equal(expected_inner.cbegin(), expected_inner.cend(), inner.begin(), inner.end())); auto outer = csr_view.Outer().DataAsSpan(); ASSERT_EQ(expected_outer.size(), outer.size()); ASSERT_TRUE(std::equal(expected_outer.cbegin(), expected_outer.cend(), outer.begin(), outer.end())); // Let's convert back to make sure we get the original Tensor dense_dst; const SparseTensor& sparse_src = dst; ASSERT_STATUS_OK(sparse_utils::SparseCsrToDenseTensor(dtm, sparse_src, cpu_allocator, cpu_allocator, dense_dst)); ASSERT_EQ(dense_dst.DataType(), sparse_src.DataType()); ASSERT_EQ(dense_dst.Shape(), sparse_src.DenseShape()); ASSERT_EQ(dense_dst.Shape().Size(), vector_len(dense_data_str)); auto dense_values_dst = dense_dst.DataAsSpan(); ASSERT_EQ(dense_values_dst.size(), dense_data.size()); ASSERT_TRUE(std::equal(dense_values_dst.begin(), dense_values_dst.end(), dense_data_str.cbegin(), dense_data_str.cend())); } { // Use MakeCsrStrings() SparseTensor str_cpu_src(DataTypeImpl::GetType(), dense_shape, cpu_allocator); ASSERT_STATUS_OK(str_cpu_src.MakeCsrStrings(expected_values_str.size(), strings, gsl::make_span(expected_inner), gsl::make_span(expected_outer))); ASSERT_EQ(str_cpu_src.Format(), SparseFormat::kCsrc); ASSERT_TRUE(str_cpu_src.IsDataTypeString()); ASSERT_EQ(str_cpu_src.DenseShape(), dense_shape); ASSERT_EQ(str_cpu_src.NumValues(), expected_values_str.size()); auto values = str_cpu_src.Values().DataAsSpan(); ASSERT_TRUE(std::equal(expected_values_str.cbegin(), expected_values_str.cend(), values.begin(), values.end())); auto csr_view = str_cpu_src.AsCsr(); auto inner = csr_view.Inner().DataAsSpan(); ASSERT_EQ(expected_inner.size(), inner.size()); ASSERT_TRUE(std::equal(expected_inner.cbegin(), expected_inner.cend(), inner.begin(), inner.end())); auto outer = csr_view.Outer().DataAsSpan(); ASSERT_EQ(expected_outer.size(), outer.size()); ASSERT_TRUE(std::equal(expected_outer.cbegin(), expected_outer.cend(), outer.begin(), outer.end())); } #ifdef USE_CUDA auto cuda_provider = DefaultCudaExecutionProvider(); auto cuda_allocator = cuda_provider->CreatePreferredAllocators()[0]; { auto cuda_transfer = cuda_provider->GetDataTransfer(); ASSERT_STATUS_OK(dtm.RegisterDataTransfer(std::move(cuda_transfer))); } { // test where source is on GPU and destination is on CPU SparseTensor sparse_dst; ASSERT_STATUS_OK(sparse_utils::DenseTensorToSparseCsr(dtm, dense_cpu_src, cpu_allocator, cuda_allocator, sparse_dst)); ASSERT_EQ(dense_cpu_src.DataType(), sparse_dst.DataType()); ASSERT_EQ(dense_cpu_src.Shape(), sparse_dst.DenseShape()); Tensor gpu_dense_dst; ASSERT_STATUS_OK(sparse_utils::SparseCsrToDenseTensor(dtm, sparse_dst, cpu_allocator, cuda_allocator, gpu_dense_dst)); ASSERT_EQ(gpu_dense_dst.DataType(), sparse_dst.DataType()); ASSERT_EQ(gpu_dense_dst.Shape(), sparse_dst.DenseShape()); // Make a copy for examination Tensor cpu_dense_dst(gpu_dense_dst.DataType(), gpu_dense_dst.Shape(), cpu_allocator); ASSERT_STATUS_OK(dtm.CopyTensor(gpu_dense_dst, cpu_dense_dst)); ASSERT_EQ(cpu_dense_dst.Shape().Size(), vector_len(dense_data)); auto dense_dst_data = cpu_dense_dst.DataAsSpan(); ASSERT_EQ(dense_dst_data.size(), dense_data.size()); ASSERT_TRUE(std::equal(dense_dst_data.begin(), dense_dst_data.end(), dense_data.cbegin(), dense_data.cend())); } { // Test cases when it is all zeros Tensor dense_cpu_src_all_zeros(DataTypeImpl::GetType(), dense_shape, dense_data_all_zeros.data(), cpu_allocator->Info()); SparseTensor sparse_dst; ASSERT_STATUS_OK(sparse_utils::DenseTensorToSparseCsr(dtm, dense_cpu_src_all_zeros, cpu_allocator, cuda_allocator, sparse_dst)); ASSERT_EQ(sparse_dst.Format(), SparseFormat::kCsrc); ASSERT_EQ(dense_cpu_src.DataType(), sparse_dst.DataType()); ASSERT_EQ(dense_cpu_src.Shape(), sparse_dst.DenseShape()); auto csr_view = sparse_dst.AsCsr(); auto inner_indices = csr_view.Inner().DataAsSpan(); ASSERT_TRUE(inner_indices.empty()); auto outer_indices = csr_view.Outer().DataAsSpan(); ASSERT_TRUE(outer_indices.empty()); Tensor gpu_dense_dst; ASSERT_STATUS_OK(sparse_utils::SparseCsrToDenseTensor(dtm, sparse_dst, cpu_allocator, cuda_allocator, gpu_dense_dst)); ASSERT_EQ(gpu_dense_dst.DataType(), sparse_dst.DataType()); ASSERT_EQ(gpu_dense_dst.Shape(), sparse_dst.DenseShape()); // Make a copy for examination Tensor cpu_dense_dst(gpu_dense_dst.DataType(), gpu_dense_dst.Shape(), cpu_allocator); ASSERT_STATUS_OK(dtm.CopyTensor(gpu_dense_dst, cpu_dense_dst)); auto dense_dst_data = cpu_dense_dst.DataAsSpan(); ASSERT_EQ(dense_dst_data.size(), dense_data_all_zeros.size()); ASSERT_TRUE(std::equal(dense_dst_data.begin(), dense_dst_data.end(), dense_data_all_zeros.cbegin(), dense_data_all_zeros.cend())); } #endif } TEST(SparseTensorConversionTests, CooConversion) { auto* cpu_provider = TestCPUExecutionProvider(); auto cpu_allocator = cpu_provider->CreatePreferredAllocators()[0]; const TensorShapeVector dense_shape{3, 3}; std::vector dense_data = { 0, 0, 1, 1, 0, 1, 0, 0, 0}; std::vector dense_data_str = { "", "", "1", "1", "", "1", "", "", ""}; std::vector dense_data_all_zeros = { 0, 0, 0, 0, 0, 0, 0, 0, 0}; const std::vector expected_values = {1, 1, 1}; const std::vector expected_values_str = {"1", "1", "1"}; const char* const strings[] = {"1", "1", "1"}; const std::vector expected_linear_indices = {2, 3, 5}; const std::vector expected_2d_indices = {0, 2, 1, 0, 1, 2}; DataTransferManager dtm; { auto cpu_transfer = cpu_provider->GetDataTransfer(); ASSERT_STATUS_OK(dtm.RegisterDataTransfer(std::move(cpu_transfer))); } { // Test COO initialization of 100% sparse tensor, passing 0 in the shape SparseTensor fully_sparse(DataTypeImpl::GetType(), TensorShape{3, 3}, cpu_allocator); ASSERT_STATUS_OK(fully_sparse.MakeCooData(*cpu_provider->GetDataTransfer(), cpu_allocator->Info(), 0, nullptr, gsl::span())); ASSERT_EQ(fully_sparse.Format(), SparseFormat::kCoo); ASSERT_EQ(0, fully_sparse.RequiredAllocationSize()); ASSERT_EQ(0U, fully_sparse.NumValues()); ASSERT_EQ(1U, fully_sparse.Values().Shape().GetDims().size()); ASSERT_EQ(0, fully_sparse.Values().Shape().Size()); ASSERT_TRUE(fully_sparse.Values().DataAsSpan().empty()); auto coo_view = fully_sparse.AsCoo(); const auto& indices = coo_view.Indices(); ASSERT_EQ(0, indices.Shape().Size()); // For fully sparse we assume a 2-D indices. ASSERT_EQ(2U, indices.Shape().GetDims().size()); ASSERT_TRUE(indices.DataAsSpan().empty()); } { // Test COO initialization of 100% sparse tensor, passing 0 in the shape SparseTensor fully_sparse(DataTypeImpl::GetType(), TensorShape{3, 3}, TensorShape{0}, nullptr, cpu_allocator->Info()); ASSERT_STATUS_OK(fully_sparse.UseCooIndices(gsl::span())); ASSERT_EQ(fully_sparse.Format(), SparseFormat::kCoo); ASSERT_EQ(0, fully_sparse.RequiredAllocationSize()); ASSERT_EQ(0U, fully_sparse.NumValues()); ASSERT_EQ(1U, fully_sparse.Values().Shape().GetDims().size()); ASSERT_EQ(0, fully_sparse.Values().Shape().Size()); ASSERT_TRUE(fully_sparse.Values().DataAsSpan().empty()); auto coo_view = fully_sparse.AsCoo(); const auto& indices = coo_view.Indices(); ASSERT_EQ(0, indices.Shape().Size()); // For fully sparse we assume a 2-D indices. ASSERT_EQ(2U, indices.Shape().GetDims().size()); ASSERT_TRUE(indices.DataAsSpan().empty()); } Tensor dense_cpu_src(DataTypeImpl::GetType(), dense_shape, dense_data.data(), cpu_allocator->Info()); { // test where both src and destination are on CPU. Linear index. SparseTensor dst; ASSERT_STATUS_OK(sparse_utils::DenseTensorToSparseCoo(dtm, dense_cpu_src, cpu_allocator, cpu_allocator, true, dst)); ASSERT_EQ(dst.Format(), SparseFormat::kCoo); ASSERT_EQ(dense_cpu_src.DataType(), dst.DataType()); ASSERT_EQ(dense_cpu_src.Shape(), dst.DenseShape()); ASSERT_EQ(dst.NumValues(), expected_values.size()); auto values = dst.Values().DataAsSpan(); ASSERT_TRUE(std::equal(expected_values.cbegin(), expected_values.cend(), values.begin(), values.end())); auto coo_view = dst.AsCoo(); ASSERT_EQ(coo_view.Indices().Shape().GetDims().size(), 1U); auto indices = coo_view.Indices().DataAsSpan(); ASSERT_EQ(indices.size(), expected_linear_indices.size()); ASSERT_TRUE(std::equal(indices.begin(), indices.end(), expected_linear_indices.cbegin(), expected_linear_indices.cend())); // Now convert back to dense Tensor dense_dst; const SparseTensor& sparse_src = dst; ASSERT_STATUS_OK(sparse_utils::SparseCooToDenseTensor(dtm, sparse_src, cpu_allocator, cpu_allocator, dense_dst)); ASSERT_EQ(dense_dst.DataType(), sparse_src.DataType()); ASSERT_EQ(dense_dst.Shape(), sparse_src.DenseShape()); auto dense_values_dst = dense_dst.DataAsSpan(); ASSERT_EQ(dense_values_dst.size(), dense_data.size()); ASSERT_TRUE(std::equal(dense_values_dst.begin(), dense_values_dst.end(), dense_data.cbegin(), dense_data.cend())); } // String test { Tensor dense_cpu_str(DataTypeImpl::GetType(), dense_shape, dense_data_str.data(), cpu_allocator->Info()); SparseTensor dst; ASSERT_STATUS_OK(sparse_utils::DenseTensorToSparseCoo(dtm, dense_cpu_str, cpu_allocator, cpu_allocator, true, dst)); ASSERT_EQ(dst.Format(), SparseFormat::kCoo); ASSERT_EQ(dense_cpu_str.DataType(), dst.DataType()); ASSERT_EQ(dense_cpu_str.Shape(), dst.DenseShape()); ASSERT_EQ(dst.NumValues(), expected_values_str.size()); auto values = dst.Values().DataAsSpan(); ASSERT_TRUE(std::equal(expected_values_str.cbegin(), expected_values_str.cend(), values.begin(), values.end())); auto coo_view = dst.AsCoo(); ASSERT_EQ(coo_view.Indices().Shape().GetDims().size(), 1U); auto indices = coo_view.Indices().DataAsSpan(); ASSERT_EQ(indices.size(), expected_linear_indices.size()); ASSERT_TRUE(std::equal(indices.begin(), indices.end(), expected_linear_indices.cbegin(), expected_linear_indices.cend())); // Now convert back to dense Tensor dense_dst; const SparseTensor& sparse_src = dst; ASSERT_STATUS_OK(sparse_utils::SparseCooToDenseTensor(dtm, sparse_src, cpu_allocator, cpu_allocator, dense_dst)); ASSERT_EQ(dense_dst.DataType(), sparse_src.DataType()); ASSERT_EQ(dense_dst.Shape(), sparse_src.DenseShape()); auto dense_values_dst = dense_dst.DataAsSpan(); ASSERT_EQ(dense_values_dst.size(), dense_data_str.size()); ASSERT_TRUE(std::equal(dense_values_dst.begin(), dense_values_dst.end(), dense_data_str.cbegin(), dense_data_str.cend())); } { // Use MakeCooStrings() SparseTensor str_cpu_src(DataTypeImpl::GetType(), dense_shape, cpu_allocator); ASSERT_STATUS_OK(str_cpu_src.MakeCooStrings(expected_values_str.size(), strings, gsl::make_span(expected_linear_indices))); ASSERT_EQ(str_cpu_src.Format(), SparseFormat::kCoo); ASSERT_TRUE(str_cpu_src.IsDataTypeString()); ASSERT_EQ(str_cpu_src.DenseShape(), TensorShape(dense_shape)); ASSERT_EQ(str_cpu_src.NumValues(), expected_values_str.size()); auto values = str_cpu_src.Values().DataAsSpan(); ASSERT_TRUE(std::equal(expected_values_str.cbegin(), expected_values_str.cend(), values.begin(), values.end())); auto coo_view = str_cpu_src.AsCoo(); auto indices = coo_view.Indices().DataAsSpan(); ASSERT_EQ(expected_linear_indices.size(), indices.size()); ASSERT_TRUE(std::equal(expected_linear_indices.cbegin(), expected_linear_indices.cend(), indices.begin(), indices.end())); } { // test where both src and destination are on CPU. 2-D index SparseTensor dst; ASSERT_STATUS_OK(sparse_utils::DenseTensorToSparseCoo(dtm, dense_cpu_src, cpu_allocator, cpu_allocator, false, dst)); ASSERT_EQ(dst.Format(), SparseFormat::kCoo); ASSERT_EQ(dense_cpu_src.DataType(), dst.DataType()); ASSERT_EQ(dense_cpu_src.Shape(), dst.DenseShape()); ASSERT_EQ(dst.NumValues(), expected_values.size()); auto values = dst.Values().DataAsSpan(); ASSERT_TRUE(std::equal(expected_values.cbegin(), expected_values.cend(), values.begin(), values.end())); auto coo_view = dst.AsCoo(); ASSERT_EQ(coo_view.Indices().Shape().GetDims().size(), 2U); auto indices = coo_view.Indices().DataAsSpan(); ASSERT_EQ(indices.size(), expected_2d_indices.size()); ASSERT_TRUE(std::equal(indices.begin(), indices.end(), expected_2d_indices.cbegin(), expected_2d_indices.cend())); // Now convert back to dense Tensor dense_dst; const SparseTensor& sparse_src = dst; ASSERT_STATUS_OK(sparse_utils::SparseCooToDenseTensor(dtm, sparse_src, cpu_allocator, cpu_allocator, dense_dst)); ASSERT_EQ(dense_dst.DataType(), sparse_src.DataType()); ASSERT_EQ(dense_dst.Shape(), sparse_src.DenseShape()); auto dense_values_dst = dense_dst.DataAsSpan(); ASSERT_EQ(dense_values_dst.size(), dense_data.size()); ASSERT_TRUE(std::equal(dense_values_dst.begin(), dense_values_dst.end(), dense_data.cbegin(), dense_data.cend())); } #ifdef USE_CUDA auto cuda_provider = DefaultCudaExecutionProvider(); auto cuda_allocator = cuda_provider->CreatePreferredAllocators()[0]; { auto cuda_transfer = cuda_provider->GetDataTransfer(); ASSERT_STATUS_OK(dtm.RegisterDataTransfer(std::move(cuda_transfer))); } { // test where source is on GPU and destination is on GPU SparseTensor sparse_dst; ASSERT_STATUS_OK(sparse_utils::DenseTensorToSparseCoo(dtm, dense_cpu_src, cpu_allocator, cuda_allocator, false, sparse_dst)); ASSERT_EQ(sparse_dst.Format(), SparseFormat::kCoo); ASSERT_EQ(dense_cpu_src.DataType(), sparse_dst.DataType()); ASSERT_EQ(dense_cpu_src.Shape(), sparse_dst.DenseShape()); auto coo_view = sparse_dst.AsCoo(); ASSERT_EQ(coo_view.Indices().Shape().GetDims().size(), 2U); auto indices = coo_view.Indices().DataAsSpan(); ASSERT_EQ(indices.size(), expected_2d_indices.size()); Tensor gpu_dense_dst; ASSERT_STATUS_OK(sparse_utils::SparseCooToDenseTensor(dtm, sparse_dst, cpu_allocator, cuda_allocator, gpu_dense_dst)); ASSERT_EQ(gpu_dense_dst.DataType(), sparse_dst.DataType()); ASSERT_EQ(gpu_dense_dst.Shape(), sparse_dst.DenseShape()); // Make a copy for examination Tensor cpu_dense_dst(gpu_dense_dst.DataType(), gpu_dense_dst.Shape(), cpu_allocator); ASSERT_STATUS_OK(dtm.CopyTensor(gpu_dense_dst, cpu_dense_dst)); auto dense_dst_data = cpu_dense_dst.DataAsSpan(); ASSERT_EQ(dense_dst_data.size(), dense_data.size()); ASSERT_TRUE(std::equal(dense_dst_data.begin(), dense_dst_data.end(), dense_data.cbegin(), dense_data.cend())); } { // Test cases when it is all zeros Tensor dense_cpu_src_all_zeros(DataTypeImpl::GetType(), dense_shape, dense_data_all_zeros.data(), cpu_allocator->Info()); SparseTensor sparse_dst; ASSERT_STATUS_OK(sparse_utils::DenseTensorToSparseCoo(dtm, dense_cpu_src_all_zeros, cpu_allocator, cuda_allocator, false, sparse_dst)); ASSERT_EQ(sparse_dst.Format(), SparseFormat::kCoo); ASSERT_EQ(dense_cpu_src.DataType(), sparse_dst.DataType()); ASSERT_EQ(dense_cpu_src.Shape(), sparse_dst.DenseShape()); auto coo_view = sparse_dst.AsCoo(); ASSERT_EQ(coo_view.Indices().Shape().GetDims().size(), 2U); auto indices = coo_view.Indices().DataAsSpan(); ASSERT_TRUE(indices.empty()); Tensor gpu_dense_dst; ASSERT_STATUS_OK(sparse_utils::SparseCooToDenseTensor(dtm, sparse_dst, cpu_allocator, cuda_allocator, gpu_dense_dst)); ASSERT_EQ(gpu_dense_dst.DataType(), sparse_dst.DataType()); ASSERT_EQ(gpu_dense_dst.Shape(), sparse_dst.DenseShape()); // Make a copy for examination Tensor cpu_dense_dst(gpu_dense_dst.DataType(), gpu_dense_dst.Shape(), cpu_allocator); ASSERT_STATUS_OK(dtm.CopyTensor(gpu_dense_dst, cpu_dense_dst)); auto dense_dst_data = cpu_dense_dst.DataAsSpan(); ASSERT_EQ(dense_dst_data.size(), dense_data_all_zeros.size()); ASSERT_TRUE(std::equal(dense_dst_data.begin(), dense_dst_data.end(), dense_data_all_zeros.cbegin(), dense_data_all_zeros.cend())); } #endif } #endif // !ORT_MINIMAL_BUILD TEST(SparseTensorConversionTests, BlockSparse) { auto* cpu_provider = TestCPUExecutionProvider(); auto cpu_allocator = cpu_provider->CreatePreferredAllocators()[0]; DataTransferManager dtm; { auto cpu_transfer = cpu_provider->GetDataTransfer(); ASSERT_STATUS_OK(dtm.RegisterDataTransfer(std::move(cpu_transfer))); } { // Fully sparse SparseTensor fully_sparse(DataTypeImpl::GetType(), TensorShape{3, 3}, cpu_allocator); ASSERT_STATUS_OK(fully_sparse.MakeBlockSparseData(*cpu_provider->GetDataTransfer(), cpu_allocator->Info(), TensorShape{0}, nullptr, TensorShape{0}, nullptr)); ASSERT_EQ(fully_sparse.Format(), SparseFormat::kBlockSparse); ASSERT_EQ(0, fully_sparse.RequiredAllocationSize()); ASSERT_EQ(0U, fully_sparse.NumValues()); ASSERT_EQ(1U, fully_sparse.Values().Shape().GetDims().size()); ASSERT_EQ(0, fully_sparse.Values().Shape().Size()); ASSERT_TRUE(fully_sparse.Values().DataAsSpan().empty()); auto blocksparse_view = fully_sparse.AsBlockSparse(); const auto& indices = blocksparse_view.Indices(); ASSERT_EQ(0, indices.Shape().Size()); ASSERT_EQ(1U, indices.Shape().GetDims().size()); ASSERT_TRUE(indices.DataAsSpan().empty()); } { // Fully sparse SparseTensor fully_sparse(DataTypeImpl::GetType(), TensorShape{3, 3}, TensorShape{0}, nullptr, cpu_allocator->Info()); ASSERT_STATUS_OK(fully_sparse.UseBlockSparseIndices(TensorShape{0}, nullptr)); ASSERT_EQ(fully_sparse.Format(), SparseFormat::kBlockSparse); ASSERT_EQ(0, fully_sparse.RequiredAllocationSize()); ASSERT_EQ(0U, fully_sparse.NumValues()); ASSERT_EQ(1U, fully_sparse.Values().Shape().GetDims().size()); ASSERT_EQ(0, fully_sparse.Values().Shape().Size()); ASSERT_TRUE(fully_sparse.Values().DataAsSpan().empty()); auto blocksparse_view = fully_sparse.AsBlockSparse(); const auto& indices = blocksparse_view.Indices(); ASSERT_EQ(0, indices.Shape().Size()); ASSERT_EQ(1U, indices.Shape().GetDims().size()); ASSERT_TRUE(indices.DataAsSpan().empty()); } const TensorShape dense_shape{8, 8}; constexpr int64_t block_size = 2; const TensorShape values_shape{2, block_size, block_size}; // Two dense blocks std::vector data_blocks{ 1, 2, 3, 4, 5, 6, 7, 8}; const char* const strings[] = { "1", "2", "3", "4", "5", "6", "7", "8"}; const std::string expected_strings[] = { "1", "2", "3", "4", "5", "6", "7", "8"}; const TensorShape indices_shape{2, 2}; // two blocks by two coordinates // (0, 0), (0,1) std::vector blocksparse_indices = { 0, 0, 0, 1}; { // Test instantiation only SparseTensor own_buffer_tensor(DataTypeImpl::GetType(), dense_shape, cpu_allocator); ASSERT_STATUS_OK(own_buffer_tensor.MakeBlockSparseData(*cpu_provider->GetDataTransfer(), cpu_allocator->Info(), values_shape, data_blocks.data(), indices_shape, blocksparse_indices.data())); ASSERT_EQ(own_buffer_tensor.Format(), SparseFormat::kBlockSparse); ASSERT_EQ(dense_shape, own_buffer_tensor.DenseShape()); ASSERT_EQ(data_blocks.size(), own_buffer_tensor.NumValues()); ASSERT_EQ(values_shape, own_buffer_tensor.Values().Shape()); auto data_span = own_buffer_tensor.Values().DataAsSpan(); ASSERT_EQ(data_blocks.size(), data_span.size()); ASSERT_TRUE(std::equal(data_blocks.cbegin(), data_blocks.cend(), data_span.begin(), data_span.end())); auto block_sparse = own_buffer_tensor.AsBlockSparse(); const auto& indices = block_sparse.Indices(); ASSERT_EQ(indices_shape, indices.Shape()); auto indices_span = indices.DataAsSpan(); ASSERT_TRUE(std::equal(blocksparse_indices.cbegin(), blocksparse_indices.cend(), indices_span.begin(), indices_span.end())); } { // Test instantiation only SparseTensor user_buffer_tensor(DataTypeImpl::GetType(), dense_shape, values_shape, data_blocks.data(), cpu_allocator->Info()); ASSERT_STATUS_OK(user_buffer_tensor.UseBlockSparseIndices(indices_shape, blocksparse_indices.data())); ASSERT_EQ(user_buffer_tensor.Format(), SparseFormat::kBlockSparse); ASSERT_EQ(dense_shape, user_buffer_tensor.DenseShape()); ASSERT_EQ(data_blocks.size(), user_buffer_tensor.NumValues()); ASSERT_EQ(values_shape, user_buffer_tensor.Values().Shape()); auto data_span = user_buffer_tensor.Values().DataAsSpan(); ASSERT_EQ(data_blocks.size(), data_span.size()); ASSERT_TRUE(std::equal(data_blocks.cbegin(), data_blocks.cend(), data_span.begin(), data_span.end())); auto block_sparse = user_buffer_tensor.AsBlockSparse(); const auto& indices = block_sparse.Indices(); ASSERT_EQ(indices_shape, indices.Shape()); auto indices_span = indices.DataAsSpan(); ASSERT_TRUE(std::equal(blocksparse_indices.cbegin(), blocksparse_indices.cend(), indices_span.begin(), indices_span.end())); } { // Use MakeBlockSparseStrings() SparseTensor own_buffer_tensor(DataTypeImpl::GetType(), dense_shape, cpu_allocator); ASSERT_STATUS_OK(own_buffer_tensor.MakeBlockSparseStrings(values_shape, strings, indices_shape, blocksparse_indices.data())); ASSERT_TRUE(own_buffer_tensor.IsDataTypeString()); ASSERT_EQ(own_buffer_tensor.Format(), SparseFormat::kBlockSparse); ASSERT_EQ(dense_shape, own_buffer_tensor.DenseShape()); ASSERT_EQ(data_blocks.size(), own_buffer_tensor.NumValues()); ASSERT_EQ(values_shape, own_buffer_tensor.Values().Shape()); auto data_span = own_buffer_tensor.Values().DataAsSpan(); auto expected_span = gsl::make_span(expected_strings); ASSERT_EQ(expected_span.size(), data_span.size()); ASSERT_TRUE(std::equal(expected_span.begin(), expected_span.end(), data_span.begin(), data_span.end())); auto block_sparse = own_buffer_tensor.AsBlockSparse(); const auto& indices = block_sparse.Indices(); ASSERT_EQ(indices_shape, indices.Shape()); auto indices_span = indices.DataAsSpan(); ASSERT_TRUE(std::equal(blocksparse_indices.cbegin(), blocksparse_indices.cend(), indices_span.begin(), indices_span.end())); } } template void TestSparseToDenseConversion(gsl::span dense_shape, const std::vector& values, gsl::span indices, gsl::span indices_shape, bool raw_data_indices, const std::vector& expected_dense_data) { ONNX_NAMESPACE::SparseTensorProto sparse_proto; for (auto dim : dense_shape) { sparse_proto.add_dims(dim); } // Create values tensor auto* values_tensor = sparse_proto.mutable_values(); values_tensor->set_name("values"); // Simplification: assuming float/int32 for now based on T if constexpr (std::is_same_v) { values_tensor->set_data_type(ONNX_NAMESPACE::TensorProto_DataType_FLOAT); for (float v : values) values_tensor->add_float_data(v); } else if constexpr (std::is_same_v) { values_tensor->set_data_type(ONNX_NAMESPACE::TensorProto_DataType_INT32); for (int32_t v : values) values_tensor->add_int32_data(v); } // Set values shape [NNZ] values_tensor->add_dims(values.size()); // Create indices tensor auto* indices_tensor = sparse_proto.mutable_indices(); indices_tensor->set_name("indices"); indices_tensor->set_data_type(ONNX_NAMESPACE::TensorProto_DataType_INT64); if constexpr (std::is_same_v) { indices_tensor->set_data_type(ONNX_NAMESPACE::TensorProto_DataType_INT8); if (raw_data_indices) { onnxruntime::utils::SetRawDataInTensorProto(*indices_tensor, indices.data(), indices.size() * sizeof(I)); } else { for (auto idx : indices) { indices_tensor->add_int32_data(static_cast(idx)); // indices are stored in int32_data for types < int32 } } } else if constexpr (std::is_same_v) { indices_tensor->set_data_type(ONNX_NAMESPACE::TensorProto_DataType_INT16); if (raw_data_indices) { onnxruntime::utils::SetRawDataInTensorProto(*indices_tensor, indices.data(), indices.size() * sizeof(I)); } else { for (auto idx : indices) { indices_tensor->add_int32_data(static_cast(idx)); } } } else if constexpr (std::is_same_v) { indices_tensor->set_data_type(ONNX_NAMESPACE::TensorProto_DataType_INT32); if (raw_data_indices) { onnxruntime::utils::SetRawDataInTensorProto(*indices_tensor, indices.data(), indices.size() * sizeof(I)); } else { for (auto idx : indices) { indices_tensor->add_int32_data(idx); } } } else if constexpr (std::is_same_v) { indices_tensor->set_data_type(ONNX_NAMESPACE::TensorProto_DataType_INT64); if (raw_data_indices) { onnxruntime::utils::SetRawDataInTensorProto(*indices_tensor, indices.data(), indices.size() * sizeof(I)); } else { for (auto idx : indices) { indices_tensor->add_int64_data(idx); } } } for (auto dim : indices_shape) { indices_tensor->add_dims(dim); } ONNX_NAMESPACE::TensorProto dense_proto; std::filesystem::path model_path; // empty path ASSERT_STATUS_OK(utils::SparseTensorProtoToDenseTensorProto(sparse_proto, model_path, dense_proto)); // Verify dense proto ASSERT_EQ(dense_proto.dims_size(), dense_shape.size()); for (size_t i = 0; i < (size_t)dense_shape.size(); ++i) { ASSERT_EQ(dense_proto.dims(static_cast(i)), dense_shape[i]); } std::vector unpacked_data(expected_dense_data.size()); ASSERT_STATUS_OK(utils::UnpackTensor(dense_proto, model_path, unpacked_data.data(), unpacked_data.size())); EXPECT_EQ(unpacked_data, expected_dense_data); } TEST(SparseTensorConversionTests, SparseTensorProtoToDense_Rank1Indices64) { // Dense Shape: [2, 2] -> 4 elements // Indices: [0, 3] (linear) // Values: [1.0, 2.0] // Expected: [1.0, 0.0, 0.0, 2.0] std::vector dense_shape = {2, 2}; std::vector values = {1.0f, 2.0f}; std::vector indices = {0, 3}; std::vector indices_shape = {2}; // [NNZ] std::vector expected = {1.0f, 0.0f, 0.0f, 2.0f}; TestSparseToDenseConversion(dense_shape, values, indices, indices_shape, false, expected); TestSparseToDenseConversion(dense_shape, values, indices, indices_shape, true, expected); } TEST(SparseTensorConversionTests, SparseTensorProtoToDense_RejectsMismatchedValuesCardinality) { SparseTensorProto sparse; sparse.add_dims(1); auto* values = sparse.mutable_values(); values->set_name("mismatched_values"); values->set_data_type(TensorProto_DataType_INT64); values->add_dims(1); values->add_int64_data(1); values->add_int64_data(2); auto* indices = sparse.mutable_indices(); indices->set_data_type(TensorProto_DataType_INT64); indices->add_dims(1); indices->add_int64_data(0); TensorProto dense; std::filesystem::path model_path; ASSERT_STATUS_NOT_OK_AND_HAS_SUBSTR( utils::SparseTensorProtoToDenseTensorProto(sparse, model_path, dense), "data field count (2) does not match expected count from shape (1)"); } TEST(SparseTensorConversionTests, SparseTensorProtoToDense_RejectsValuesForZeroElementTensor) { SparseTensorProto sparse; sparse.add_dims(0); auto* values = sparse.mutable_values(); values->set_name("zero_element_values"); values->set_data_type(TensorProto_DataType_FLOAT); values->add_dims(0); values->add_float_data(1.0f); auto* indices = sparse.mutable_indices(); indices->set_data_type(TensorProto_DataType_INT64); indices->add_dims(0); TensorProto dense; std::filesystem::path model_path; ASSERT_STATUS_NOT_OK_AND_HAS_SUBSTR( utils::SparseTensorProtoToDenseTensorProto(sparse, model_path, dense), "data field count (1) does not match expected count from shape (0)"); } #if !defined(DISABLE_FLOAT8_TYPES) TEST(SparseTensorConversionTests, SparseTensorProtoToDense_RejectsFloat8E8M0) { SparseTensorProto sparse; sparse.add_dims(2); auto* values = sparse.mutable_values(); values->set_name("float8e8m0_values"); values->set_data_type(TensorProto_DataType_FLOAT8E8M0); values->add_dims(1); values->add_int32_data(0x7f); auto* indices = sparse.mutable_indices(); indices->set_data_type(TensorProto_DataType_INT64); indices->add_dims(1); indices->add_int64_data(0); TensorProto dense; std::filesystem::path model_path; ASSERT_STATUS_NOT_OK_AND_HAS_SUBSTR( utils::SparseTensorProtoToDenseTensorProto(sparse, model_path, dense), "FLOAT8E8M0 values are unsupported because the type has no zero representation"); } #endif TEST(SparseTensorConversionTests, SparseTensorProtoToDense_Complex64) { SparseTensorProto sparse; sparse.add_dims(2); auto* values = sparse.mutable_values(); values->set_name("complex64_values"); values->set_data_type(TensorProto_DataType_COMPLEX64); values->add_dims(1); values->add_float_data(1.0f); values->add_float_data(2.0f); auto* indices = sparse.mutable_indices(); indices->set_data_type(TensorProto_DataType_INT64); indices->add_dims(1); indices->add_int64_data(0); TensorProto dense; std::filesystem::path model_path; ASSERT_STATUS_OK(utils::SparseTensorProtoToDenseTensorProto(sparse, model_path, dense)); const std::array expected{1.0f, 2.0f, 0.0f, 0.0f}; ASSERT_EQ(dense.raw_data().size(), expected.size() * sizeof(float)); EXPECT_EQ(0, memcmp(dense.raw_data().data(), expected.data(), dense.raw_data().size())); } TEST(SparseTensorConversionTests, SparseTensorProtoToDense_Complex128) { SparseTensorProto sparse; sparse.add_dims(2); auto* values = sparse.mutable_values(); values->set_name("complex128_values"); values->set_data_type(TensorProto_DataType_COMPLEX128); values->add_dims(1); values->add_double_data(1.0); values->add_double_data(2.0); auto* indices = sparse.mutable_indices(); indices->set_data_type(TensorProto_DataType_INT64); indices->add_dims(1); indices->add_int64_data(0); TensorProto dense; std::filesystem::path model_path; ASSERT_STATUS_OK(utils::SparseTensorProtoToDenseTensorProto(sparse, model_path, dense)); const std::array expected{1.0, 2.0, 0.0, 0.0}; ASSERT_EQ(dense.raw_data().size(), expected.size() * sizeof(double)); EXPECT_EQ(0, memcmp(dense.raw_data().data(), expected.data(), dense.raw_data().size())); } TEST(SparseTensorConversionTests, SparseTensorProtoToDense_Rank1Indices32) { // Dense Shape: [2, 2] -> 4 elements // Indices: [0, 3] (linear) // Values: [1.0, 2.0] // Expected: [1.0, 0.0, 0.0, 2.0] std::vector dense_shape = {2, 2}; std::vector values = {1.0f, 2.0f}; std::vector indices = {0, 3}; std::vector indices_shape = {2}; // [NNZ] std::vector expected = {1.0f, 0.0f, 0.0f, 2.0f}; TestSparseToDenseConversion(dense_shape, values, indices, indices_shape, false, expected); TestSparseToDenseConversion(dense_shape, values, indices, indices_shape, true, expected); } TEST(SparseTensorConversionTests, SparseTensorProtoToDense_Rank1Indices16) { // Dense Shape: [2, 2] -> 4 elements // Indices: [0, 3] (linear) // Values: [1.0, 2.0] // Expected: [1.0, 0.0, 0.0, 2.0] std::vector dense_shape = {2, 2}; std::vector values = {1.0f, 2.0f}; std::vector indices = {0, 3}; std::vector indices_shape = {2}; // [NNZ] std::vector expected = {1.0f, 0.0f, 0.0f, 2.0f}; TestSparseToDenseConversion(dense_shape, values, indices, indices_shape, false, expected); TestSparseToDenseConversion(dense_shape, values, indices, indices_shape, true, expected); } TEST(SparseTensorConversionTests, SparseTensorProtoToDense_Rank1Indices8) { // Dense Shape: [2, 2] -> 4 elements // Indices: [0, 3] (linear) // Values: [1.0, 2.0] // Expected: [1.0, 0.0, 0.0, 2.0] std::vector dense_shape = {2, 2}; std::vector values = {1.0f, 2.0f}; std::vector indices = {0, 3}; std::vector indices_shape = {2}; // [NNZ] std::vector expected = {1.0f, 0.0f, 0.0f, 2.0f}; TestSparseToDenseConversion(dense_shape, values, indices, indices_shape, false, expected); TestSparseToDenseConversion(dense_shape, values, indices, indices_shape, true, expected); } TEST(SparseTensorConversionTests, SparseTensorProtoToDense_Rank2Indices_COO) { // Dense Shape: [3, 3] -> 9 elements // Indices: [[0, 0], [1, 1], [2, 2]] -> flattened: 0,0, 1,1, 2,2 // Shape: [3, 2] (NNZ=3, Rank=2) // Values: [10, 20, 30] // Expected: [10, 0, 0, 0, 20, 0, 0, 0, 30] std::vector dense_shape = {3, 3}; std::vector values = {10, 20, 30}; std::vector indices = {0, 0, 1, 1, 2, 2}; std::vector indices_shape = {3, 2}; std::vector expected = { 10, 0, 0, 0, 20, 0, 0, 0, 30}; TestSparseToDenseConversion(dense_shape, values, indices, indices_shape, false, expected); TestSparseToDenseConversion(dense_shape, values, indices, indices_shape, true, expected); } TEST(SparseTensorConversionTests, SparseTensorProtoToDense_OutOfBounds_Rank1) { // Dense size 4 // Index 5 -> Out of bounds ONNX_NAMESPACE::SparseTensorProto sparse; sparse.mutable_values()->set_name("test_tensor"); sparse.add_dims(4); auto* val = sparse.mutable_values(); val->add_dims(1); val->set_data_type(ONNX_NAMESPACE::TensorProto_DataType_FLOAT); val->add_float_data(1.0f); auto* ind = sparse.mutable_indices(); ind->add_dims(1); ind->set_data_type(ONNX_NAMESPACE::TensorProto_DataType_INT64); ind->add_int64_data(5); // Out of bounds ONNX_NAMESPACE::TensorProto dense; auto status = utils::SparseTensorProtoToDenseTensorProto(sparse, {}, dense); EXPECT_FALSE(status.IsOK()); EXPECT_THAT(status.ErrorMessage(), testing::HasSubstr("Sparse tensor: test_tensor index is out of bounds")); } TEST(SparseTensorConversionTests, SparseTensorProtoToDense_OutOfBounds_Rank2) { // Dense Shape [2, 2] -> linear 0..3 // Index [2, 0] -> linear 4 -> Out of bounds ONNX_NAMESPACE::SparseTensorProto sparse; sparse.mutable_values()->set_name("test_tensor"); sparse.add_dims(2); sparse.add_dims(2); auto* val = sparse.mutable_values(); val->add_dims(1); val->set_data_type(ONNX_NAMESPACE::TensorProto_DataType_FLOAT); val->add_float_data(1.0f); auto* ind = sparse.mutable_indices(); ind->add_dims(1); // NNZ=1 ind->add_dims(2); // Rank=2 ind->set_data_type(ONNX_NAMESPACE::TensorProto_DataType_INT64); ind->add_int64_data(2); ind->add_int64_data(0); ONNX_NAMESPACE::TensorProto dense; auto status = utils::SparseTensorProtoToDenseTensorProto(sparse, {}, dense); EXPECT_FALSE(status.IsOK()); EXPECT_THAT(status.ErrorMessage(), testing::HasSubstr("Sparse tensor: test_tensor index is out of bounds")); } TEST(SparseTensorConversionTests, SparseTensorProtoToDense_OutOfBounds_Rank2_Dim1) { // Dense Shape [2, 2] // Index [0, 2] -> 2 is out of bounds for the 2nd dimension (size 2) ONNX_NAMESPACE::SparseTensorProto sparse; sparse.mutable_values()->set_name("test_tensor_dim1_oob"); sparse.add_dims(2); sparse.add_dims(2); auto* val = sparse.mutable_values(); val->add_dims(1); val->set_data_type(ONNX_NAMESPACE::TensorProto_DataType_FLOAT); val->add_float_data(1.0f); auto* ind = sparse.mutable_indices(); ind->add_dims(1); // NNZ=1 ind->add_dims(2); // Rank=2 ind->set_data_type(ONNX_NAMESPACE::TensorProto_DataType_INT64); ind->add_int64_data(0); ind->add_int64_data(2); // Out of bounds for dim 1 ONNX_NAMESPACE::TensorProto dense; auto status = utils::SparseTensorProtoToDenseTensorProto(sparse, {}, dense); EXPECT_FALSE(status.IsOK()); EXPECT_THAT(status.ErrorMessage(), testing::HasSubstr("Sparse tensor: test_tensor_dim1_oob index is out of bounds")); } TEST(SparseTensorConversionTests, SparseTensorProtoToDense_InvalidValuesRank) { ONNX_NAMESPACE::SparseTensorProto sparse; sparse.mutable_values()->set_name("test_tensor"); sparse.add_dims(10); auto* val = sparse.mutable_values(); // Set values rank to 2 (invalid) val->add_dims(1); val->add_dims(1); val->set_data_type(ONNX_NAMESPACE::TensorProto_DataType_FLOAT); val->add_float_data(1.0f); auto* ind = sparse.mutable_indices(); ind->add_dims(1); ind->set_data_type(ONNX_NAMESPACE::TensorProto_DataType_INT64); ind->add_int64_data(0); ONNX_NAMESPACE::TensorProto dense; auto status = utils::SparseTensorProtoToDenseTensorProto(sparse, {}, dense); EXPECT_FALSE(status.IsOK()); EXPECT_THAT(status.ErrorMessage(), testing::HasSubstr("Sparse tensor: test_tensor values should be rank 1")); } TEST(SparseTensorConversionTests, SparseTensorProtoToDense_NegativeValuesShape) { ONNX_NAMESPACE::SparseTensorProto sparse; sparse.mutable_values()->set_name("test_tensor"); sparse.add_dims(10); // Dense shape auto* val = sparse.mutable_values(); val->add_dims(-5); // Negative dimension in values val->set_data_type(ONNX_NAMESPACE::TensorProto_DataType_FLOAT); val->add_float_data(1.0f); auto* ind = sparse.mutable_indices(); ind->add_dims(1); ind->set_data_type(ONNX_NAMESPACE::TensorProto_DataType_INT64); ind->add_int64_data(0); ONNX_NAMESPACE::TensorProto dense; auto status = utils::SparseTensorProtoToDenseTensorProto(sparse, {}, dense); EXPECT_FALSE(status.IsOK()); EXPECT_THAT(status.ErrorMessage(), testing::HasSubstr("Sparse tensor: test_tensor tensor dims expected to be non-negative")); } TEST(SparseTensorConversionTests, SparseTensorProtoToDense_NegativeDenseShape) { ONNX_NAMESPACE::SparseTensorProto sparse; sparse.mutable_values()->set_name("test_tensor"); sparse.add_dims(10); sparse.add_dims(-2); // Negative dimension in dense shape auto* val = sparse.mutable_values(); val->add_dims(1); val->set_data_type(ONNX_NAMESPACE::TensorProto_DataType_FLOAT); val->add_float_data(1.0f); auto* ind = sparse.mutable_indices(); ind->add_dims(1); ind->set_data_type(ONNX_NAMESPACE::TensorProto_DataType_INT64); ind->add_int64_data(0); ONNX_NAMESPACE::TensorProto dense; auto status = utils::SparseTensorProtoToDenseTensorProto(sparse, {}, dense); EXPECT_FALSE(status.IsOK()); EXPECT_THAT(status.ErrorMessage(), testing::HasSubstr("Sparse tensor: test_tensor dense dims expected to be non-negative")); } TEST(SparseTensorConversionTests, SparseTensorProtoToDense_ExcessiveDenseSize) { ONNX_NAMESPACE::SparseTensorProto sparse; const size_t excessive_element_count = utils::kMaxEmbeddedInitializerSizeInBytes / sizeof(float) + 1; sparse.add_dims(narrow(excessive_element_count)); auto* values = sparse.mutable_values(); values->set_name("test_tensor"); values->add_dims(1); values->set_data_type(ONNX_NAMESPACE::TensorProto_DataType_FLOAT); values->add_float_data(1.0f); auto* indices = sparse.mutable_indices(); indices->add_dims(1); indices->set_data_type(ONNX_NAMESPACE::TensorProto_DataType_INT64); indices->add_int64_data(0); ONNX_NAMESPACE::TensorProto dense; auto status = utils::SparseTensorProtoToDenseTensorProto(sparse, {}, dense); EXPECT_FALSE(status.IsOK()); EXPECT_THAT(status.ErrorMessage(), testing::HasSubstr("dense data size")); } TEST(SparseTensorConversionTests, SparseTensorProtoToDense_InvalidValuesRank_Zero) { ONNX_NAMESPACE::SparseTensorProto sparse; sparse.mutable_values()->set_name("test_tensor_val_rank_0"); sparse.add_dims(10); auto* val = sparse.mutable_values(); // No dims added -> Rank 0 (Scalar) val->set_data_type(ONNX_NAMESPACE::TensorProto_DataType_FLOAT); val->add_float_data(1.0f); auto* ind = sparse.mutable_indices(); ind->add_dims(1); ind->set_data_type(ONNX_NAMESPACE::TensorProto_DataType_INT64); ind->add_int64_data(0); ONNX_NAMESPACE::TensorProto dense; auto status = utils::SparseTensorProtoToDenseTensorProto(sparse, {}, dense); EXPECT_FALSE(status.IsOK()); EXPECT_THAT(status.ErrorMessage(), testing::HasSubstr("Sparse tensor: test_tensor_val_rank_0 values should be rank 1")); } TEST(SparseTensorConversionTests, SparseTensorProtoToDense_ValuesSizeMismatch) { // Case where the actual data in 'values' doesn't match the dimension specified in 'values' ONNX_NAMESPACE::SparseTensorProto sparse; sparse.mutable_values()->set_name("test_tensor_val_size_mismatch"); sparse.add_dims(10); auto* val = sparse.mutable_values(); val->add_dims(2); // Claiming 2 elements val->set_data_type(ONNX_NAMESPACE::TensorProto_DataType_FLOAT); val->add_float_data(1.0f); // Only added 1 element, this should fail during UnpackInitializerData or subsequent checks depending on where it's caught // Note: UnpackTensor checks if size matches. auto* ind = sparse.mutable_indices(); ind->add_dims(2); ind->set_data_type(ONNX_NAMESPACE::TensorProto_DataType_INT64); ind->add_int64_data(0); ind->add_int64_data(1); ONNX_NAMESPACE::TensorProto dense; auto status = utils::SparseTensorProtoToDenseTensorProto(sparse, {}, dense); EXPECT_FALSE(status.IsOK()); EXPECT_THAT(status.ErrorMessage(), testing::HasSubstr("data field count")); } TEST(SparseTensorConversionTests, SparseTensorProtoToDense_ValuesSizeMismatch_RawData) { // Case where raw data size doesn't match the shape size * element size ONNX_NAMESPACE::SparseTensorProto sparse; sparse.mutable_values()->set_name("test_tensor_val_size_mismatch_raw"); sparse.add_dims(10); auto* val = sparse.mutable_values(); val->add_dims(2); // Claiming 2 elements val->set_data_type(ONNX_NAMESPACE::TensorProto_DataType_FLOAT); // 1 float is 4 bytes. We provide 4 bytes, but claim 2 elements (8 bytes needed). float raw_val = 1.0f; onnxruntime::utils::SetRawDataInTensorProto(*val, &raw_val, sizeof(float)); auto* ind = sparse.mutable_indices(); ind->add_dims(2); ind->set_data_type(ONNX_NAMESPACE::TensorProto_DataType_INT64); ind->add_int64_data(0); ind->add_int64_data(1); ONNX_NAMESPACE::TensorProto dense; auto status = utils::SparseTensorProtoToDenseTensorProto(sparse, {}, dense); EXPECT_FALSE(status.IsOK()); EXPECT_THAT(status.ErrorMessage(), testing::HasSubstr("raw_data size")); } // Tests for SparseTensorProtoToDenseTensorProto with negative indices (model-loading path) TEST(SparseTensorConversionTests, SparseTensorProtoToDense_NegativeIndex_Rank1) { // Dense size 4 // Index -1 -> negative, out of bounds ONNX_NAMESPACE::SparseTensorProto sparse; sparse.mutable_values()->set_name("test_neg_idx"); sparse.add_dims(4); auto* val = sparse.mutable_values(); val->add_dims(1); val->set_data_type(ONNX_NAMESPACE::TensorProto_DataType_FLOAT); val->add_float_data(1.0f); auto* ind = sparse.mutable_indices(); ind->add_dims(1); ind->set_data_type(ONNX_NAMESPACE::TensorProto_DataType_INT64); ind->add_int64_data(-1); ONNX_NAMESPACE::TensorProto dense; auto status = utils::SparseTensorProtoToDenseTensorProto(sparse, {}, dense); EXPECT_FALSE(status.IsOK()); EXPECT_THAT(status.ErrorMessage(), testing::HasSubstr("index is out of bounds")); } TEST(SparseTensorConversionTests, SparseTensorProtoToDense_NegativeIndex_Rank2) { // Dense Shape [3, 3] // Index [-1, 0] -> negative row, out of bounds ONNX_NAMESPACE::SparseTensorProto sparse; sparse.mutable_values()->set_name("test_neg_idx_2d"); sparse.add_dims(3); sparse.add_dims(3); auto* val = sparse.mutable_values(); val->add_dims(1); val->set_data_type(ONNX_NAMESPACE::TensorProto_DataType_FLOAT); val->add_float_data(1.0f); auto* ind = sparse.mutable_indices(); ind->add_dims(1); ind->add_dims(2); ind->set_data_type(ONNX_NAMESPACE::TensorProto_DataType_INT64); ind->add_int64_data(-1); ind->add_int64_data(0); ONNX_NAMESPACE::TensorProto dense; auto status = utils::SparseTensorProtoToDenseTensorProto(sparse, {}, dense); EXPECT_FALSE(status.IsOK()); EXPECT_THAT(status.ErrorMessage(), testing::HasSubstr("index is out of bounds")); } // Tests for SparseCooToDenseTensor and SparseCsrToDenseTensor (sparse_utils.cc paths) TEST(SparseTensorConversionTests, SparseCooToDense_NegativeLinearIndex) { auto* cpu_provider = TestCPUExecutionProvider(); auto cpu_allocator = cpu_provider->CreatePreferredAllocators()[0]; DataTransferManager dtm; ASSERT_STATUS_OK(dtm.RegisterDataTransfer(cpu_provider->GetDataTransfer())); // Create a SparseTensor with COO format and a negative linear index SparseTensor src(DataTypeImpl::GetType(), TensorShape{3, 3}, cpu_allocator); std::vector values = {1, 2, 3}; std::vector bad_indices = {-1, 3, 5}; // -1 is invalid ASSERT_STATUS_OK(src.MakeCooData(*cpu_provider->GetDataTransfer(), cpu_allocator->Info(), values.size(), values.data(), gsl::make_span(bad_indices))); Tensor dense_dst; auto status = sparse_utils::SparseCooToDenseTensor(dtm, src, cpu_allocator, cpu_allocator, dense_dst); EXPECT_FALSE(status.IsOK()); EXPECT_THAT(status.ErrorMessage(), testing::HasSubstr("Invalid COO index")); } TEST(SparseTensorConversionTests, SparseCooToDense_UpperBoundLinearIndex) { auto* cpu_provider = TestCPUExecutionProvider(); auto cpu_allocator = cpu_provider->CreatePreferredAllocators()[0]; DataTransferManager dtm; ASSERT_STATUS_OK(dtm.RegisterDataTransfer(cpu_provider->GetDataTransfer())); // Dense 3x3 = 9 elements. Index 9 is out of bounds (valid: 0-8) SparseTensor src(DataTypeImpl::GetType(), TensorShape{3, 3}, cpu_allocator); std::vector values = {1, 2, 3}; std::vector bad_indices = {0, 3, 9}; ASSERT_STATUS_OK(src.MakeCooData(*cpu_provider->GetDataTransfer(), cpu_allocator->Info(), values.size(), values.data(), gsl::make_span(bad_indices))); Tensor dense_dst; auto status = sparse_utils::SparseCooToDenseTensor(dtm, src, cpu_allocator, cpu_allocator, dense_dst); EXPECT_FALSE(status.IsOK()); EXPECT_THAT(status.ErrorMessage(), testing::HasSubstr("Invalid COO index")); } TEST(SparseTensorConversionTests, SparseCooToDense_Negative2DIndex) { auto* cpu_provider = TestCPUExecutionProvider(); auto cpu_allocator = cpu_provider->CreatePreferredAllocators()[0]; DataTransferManager dtm; ASSERT_STATUS_OK(dtm.RegisterDataTransfer(cpu_provider->GetDataTransfer())); // 2D indices: (-1, 0) is invalid SparseTensor src(DataTypeImpl::GetType(), TensorShape{3, 3}, cpu_allocator); std::vector values = {1, 2}; std::vector bad_indices = {-1, 0, 1, 1}; // 2D, first entry has negative row ASSERT_STATUS_OK(src.MakeCooData(*cpu_provider->GetDataTransfer(), cpu_allocator->Info(), values.size(), values.data(), gsl::make_span(bad_indices))); Tensor dense_dst; auto status = sparse_utils::SparseCooToDenseTensor(dtm, src, cpu_allocator, cpu_allocator, dense_dst); EXPECT_FALSE(status.IsOK()); EXPECT_THAT(status.ErrorMessage(), testing::HasSubstr("Invalid COO 2D index")); } TEST(SparseTensorConversionTests, SparseCsrToDense_NegativeColumnIndex) { auto* cpu_provider = TestCPUExecutionProvider(); auto cpu_allocator = cpu_provider->CreatePreferredAllocators()[0]; DataTransferManager dtm; ASSERT_STATUS_OK(dtm.RegisterDataTransfer(cpu_provider->GetDataTransfer())); // 3x3 dense, CSR with a negative column index SparseTensor src(DataTypeImpl::GetType(), TensorShape{3, 3}, cpu_allocator); std::vector values = {1, 2, 3}; std::vector inner = {-1, 0, 2}; // -1 is invalid column std::vector outer = {0, 1, 2, 3}; ASSERT_STATUS_OK(src.MakeCsrData(*cpu_provider->GetDataTransfer(), cpu_allocator->Info(), values.size(), values.data(), gsl::make_span(inner), gsl::make_span(outer))); Tensor dense_dst; auto status = sparse_utils::SparseCsrToDenseTensor(dtm, src, cpu_allocator, cpu_allocator, dense_dst); EXPECT_FALSE(status.IsOK()); EXPECT_THAT(status.ErrorMessage(), testing::HasSubstr("Invalid CSR column index")); } TEST(SparseTensorConversionTests, SparseCsrToDense_ColumnIndexOutOfBounds) { auto* cpu_provider = TestCPUExecutionProvider(); auto cpu_allocator = cpu_provider->CreatePreferredAllocators()[0]; DataTransferManager dtm; ASSERT_STATUS_OK(dtm.RegisterDataTransfer(cpu_provider->GetDataTransfer())); // 3x3 dense, CSR with column index 3 (valid: 0-2) SparseTensor src(DataTypeImpl::GetType(), TensorShape{3, 3}, cpu_allocator); std::vector values = {1, 2, 3}; std::vector inner = {1, 3, 1}; // 3 is out of bounds for 3 columns std::vector outer = {0, 1, 2, 3}; ASSERT_STATUS_OK(src.MakeCsrData(*cpu_provider->GetDataTransfer(), cpu_allocator->Info(), values.size(), values.data(), gsl::make_span(inner), gsl::make_span(outer))); Tensor dense_dst; auto status = sparse_utils::SparseCsrToDenseTensor(dtm, src, cpu_allocator, cpu_allocator, dense_dst); EXPECT_FALSE(status.IsOK()); EXPECT_THAT(status.ErrorMessage(), testing::HasSubstr("Invalid CSR column index")); } // Regression test: SparseCsrToDenseTensor must use correct source index for each // non-zero value. Previously src_idx was never incremented, so all entries got values[0]. // Using distinct values exposes this bug. TEST(SparseTensorConversionTests, SparseCsrToDense_DistinctValuesRoundtrip) { auto* cpu_provider = TestCPUExecutionProvider(); auto cpu_allocator = cpu_provider->CreatePreferredAllocators()[0]; DataTransferManager dtm; ASSERT_STATUS_OK(dtm.RegisterDataTransfer(cpu_provider->GetDataTransfer())); // 3x3 dense matrix: // 0 0 10 // 20 0 30 // 0 0 0 // CSR: values={10, 20, 30}, inner(col)={2, 0, 2}, outer={0, 1, 3, 3} SparseTensor src(DataTypeImpl::GetType(), TensorShape{3, 3}, cpu_allocator); std::vector values = {10, 20, 30}; std::vector inner = {2, 0, 2}; std::vector outer = {0, 1, 3, 3}; ASSERT_STATUS_OK(src.MakeCsrData(*cpu_provider->GetDataTransfer(), cpu_allocator->Info(), values.size(), values.data(), gsl::make_span(inner), gsl::make_span(outer))); Tensor dense_dst; ASSERT_STATUS_OK(sparse_utils::SparseCsrToDenseTensor(dtm, src, cpu_allocator, cpu_allocator, dense_dst)); std::vector expected_dense = { 0, 0, 10, 20, 0, 30, 0, 0, 0}; auto dense_span = dense_dst.DataAsSpan(); ASSERT_EQ(dense_span.size(), expected_dense.size()); for (size_t i = 0; i < expected_dense.size(); ++i) { EXPECT_EQ(dense_span[i], expected_dense[i]) << "Mismatch at index " << i; } } // Test that COO 2D validation catches out-of-range column even when // the linearized index would be in bounds. E.g., for a 3x3 matrix, // (row=0, col=4) gives linear index 4 which is in [0,9), but col=4 >= cols=3. TEST(SparseTensorConversionTests, SparseCooToDense_2DColumnOutOfRange) { auto* cpu_provider = TestCPUExecutionProvider(); auto cpu_allocator = cpu_provider->CreatePreferredAllocators()[0]; DataTransferManager dtm; ASSERT_STATUS_OK(dtm.RegisterDataTransfer(cpu_provider->GetDataTransfer())); SparseTensor src(DataTypeImpl::GetType(), TensorShape{3, 3}, cpu_allocator); std::vector values = {1}; // (row=0, col=4): linear index = 0*3+4 = 4, valid linear but col >= cols std::vector bad_indices = {0, 4}; ASSERT_STATUS_OK(src.MakeCooData(*cpu_provider->GetDataTransfer(), cpu_allocator->Info(), values.size(), values.data(), gsl::make_span(bad_indices))); Tensor dense_dst; auto status = sparse_utils::SparseCooToDenseTensor(dtm, src, cpu_allocator, cpu_allocator, dense_dst); EXPECT_FALSE(status.IsOK()); EXPECT_THAT(status.ErrorMessage(), testing::HasSubstr("Invalid COO 2D index")); } // Test that COO 2D validation catches out-of-range row. TEST(SparseTensorConversionTests, SparseCooToDense_2DRowOutOfRange) { auto* cpu_provider = TestCPUExecutionProvider(); auto cpu_allocator = cpu_provider->CreatePreferredAllocators()[0]; DataTransferManager dtm; ASSERT_STATUS_OK(dtm.RegisterDataTransfer(cpu_provider->GetDataTransfer())); SparseTensor src(DataTypeImpl::GetType(), TensorShape{3, 3}, cpu_allocator); std::vector values = {1}; // (row=3, col=0): row >= rows std::vector bad_indices = {3, 0}; ASSERT_STATUS_OK(src.MakeCooData(*cpu_provider->GetDataTransfer(), cpu_allocator->Info(), values.size(), values.data(), gsl::make_span(bad_indices))); Tensor dense_dst; auto status = sparse_utils::SparseCooToDenseTensor(dtm, src, cpu_allocator, cpu_allocator, dense_dst); EXPECT_FALSE(status.IsOK()); EXPECT_THAT(status.ErrorMessage(), testing::HasSubstr("Invalid COO 2D index")); } // Positive tests for SparseTensorProtoToDenseTensorProto with external data. // These verify end-to-end conversion succeeds when values and/or indices are stored // in legitimate external files within the model directory. // Helper: write data to a temp file and configure a TensorProto to reference it as external data. // The file is created in the current working directory using CreateTestFile. // The ScopedFileDeleter is assigned immediately after file creation to ensure cleanup on any failure. template static void SetupExternalDataTensor(TensorProto_DataType type, const std::vector& data, PathString& filename, TensorProto& tensor_proto, ScopedFileDeleter& file_deleter) { size_t size_in_bytes = data.size() * sizeof(T); std::vector le_data(size_in_bytes); auto src_span = gsl::make_span(data.data(), data.size()); auto dst_span = gsl::make_span(le_data.data(), le_data.size()); ASSERT_STATUS_OK(onnxruntime::utils::WriteLittleEndian(src_span, dst_span)); FILE* fp; CreateTestFile(fp, filename); file_deleter = ScopedFileDeleter(filename); ASSERT_EQ(size_in_bytes, fwrite(le_data.data(), 1, size_in_bytes, fp)); ASSERT_EQ(0, fclose(fp)); tensor_proto.set_data_type(type); tensor_proto.set_data_location(TensorProto_DataLocation_EXTERNAL); auto* loc = tensor_proto.mutable_external_data()->Add(); loc->set_key("location"); loc->set_value(ToUTF8String(filename)); auto* len = tensor_proto.mutable_external_data()->Add(); len->set_key("length"); len->set_value(std::to_string(size_in_bytes)); } // External values + inline indices (INT64), rank-1 COO. TEST(SparseTensorConversionTests, SparseTensorProtoToDense_ExternalValues_InlineIndices) { // Dense shape [2, 3] = 6 elements. // NNZ=3 values at linear indices [0, 2, 5]. // Expected dense: [1.0, 0, 2.0, 0, 0, 3.0] std::vector values = {1.0f, 2.0f, 3.0f}; PathString values_file(ORT_TSTR("ext_val_XXXXXX")); SparseTensorProto sparse; sparse.add_dims(2); sparse.add_dims(3); ScopedFileDeleter values_deleter; SetupExternalDataTensor(TensorProto_DataType_FLOAT, values, values_file, *sparse.mutable_values(), values_deleter); sparse.mutable_values()->set_name("ext_values_test"); sparse.mutable_values()->add_dims(3); // NNZ auto* indices = sparse.mutable_indices(); indices->set_data_type(TensorProto_DataType_INT64); indices->add_dims(3); indices->add_int64_data(0); indices->add_int64_data(2); indices->add_int64_data(5); // model_path in CWD so external files are within the model directory std::filesystem::path model_path = std::filesystem::current_path() / "model.onnx"; TensorProto dense; ASSERT_STATUS_OK(utils::SparseTensorProtoToDenseTensorProto(sparse, model_path, dense)); ASSERT_EQ(dense.dims_size(), 2); EXPECT_EQ(dense.dims(0), 2); EXPECT_EQ(dense.dims(1), 3); std::vector unpacked(6); ASSERT_STATUS_OK(utils::UnpackTensor(dense, model_path, unpacked.data(), unpacked.size())); std::vector expected = {1.0f, 0.0f, 2.0f, 0.0f, 0.0f, 3.0f}; EXPECT_EQ(unpacked, expected); } // Inline values + external indices (INT64), rank-1 COO. TEST(SparseTensorConversionTests, SparseTensorProtoToDense_InlineValues_ExternalIndicesInt64) { // Dense shape [4] = 4 elements. // NNZ=2 at indices [1, 3]. // Expected dense: [0, 10.0, 0, 20.0] std::vector indices_data = {1, 3}; PathString indices_file(ORT_TSTR("ext_idx_XXXXXX")); SparseTensorProto sparse; sparse.add_dims(4); auto* values = sparse.mutable_values(); values->set_name("ext_indices_test"); values->set_data_type(TensorProto_DataType_FLOAT); values->add_dims(2); values->add_float_data(10.0f); values->add_float_data(20.0f); ScopedFileDeleter indices_deleter; SetupExternalDataTensor(TensorProto_DataType_INT64, indices_data, indices_file, *sparse.mutable_indices(), indices_deleter); sparse.mutable_indices()->add_dims(2); std::filesystem::path model_path = std::filesystem::current_path() / "model.onnx"; TensorProto dense; ASSERT_STATUS_OK(utils::SparseTensorProtoToDenseTensorProto(sparse, model_path, dense)); std::vector unpacked(4); ASSERT_STATUS_OK(utils::UnpackTensor(dense, model_path, unpacked.data(), unpacked.size())); std::vector expected = {0.0f, 10.0f, 0.0f, 20.0f}; EXPECT_EQ(unpacked, expected); } // Inline values + external indices (INT32), rank-1 COO. TEST(SparseTensorConversionTests, SparseTensorProtoToDense_InlineValues_ExternalIndicesInt32) { std::vector indices_data = {0, 3}; PathString indices_file(ORT_TSTR("ext_i32_XXXXXX")); SparseTensorProto sparse; sparse.add_dims(2); sparse.add_dims(2); auto* values = sparse.mutable_values(); values->set_name("ext_int32_idx_test"); values->set_data_type(TensorProto_DataType_FLOAT); values->add_dims(2); values->add_float_data(5.0f); values->add_float_data(6.0f); ScopedFileDeleter indices_deleter; SetupExternalDataTensor(TensorProto_DataType_INT32, indices_data, indices_file, *sparse.mutable_indices(), indices_deleter); sparse.mutable_indices()->add_dims(2); std::filesystem::path model_path = std::filesystem::current_path() / "model.onnx"; TensorProto dense; ASSERT_STATUS_OK(utils::SparseTensorProtoToDenseTensorProto(sparse, model_path, dense)); std::vector unpacked(4); ASSERT_STATUS_OK(utils::UnpackTensor(dense, model_path, unpacked.data(), unpacked.size())); std::vector expected = {5.0f, 0.0f, 0.0f, 6.0f}; EXPECT_EQ(unpacked, expected); } // Inline values + external indices (INT16), rank-1 COO. TEST(SparseTensorConversionTests, SparseTensorProtoToDense_InlineValues_ExternalIndicesInt16) { std::vector indices_data = {1, 2}; PathString indices_file(ORT_TSTR("ext_i16_XXXXXX")); SparseTensorProto sparse; sparse.add_dims(4); auto* values = sparse.mutable_values(); values->set_name("ext_int16_idx_test"); values->set_data_type(TensorProto_DataType_FLOAT); values->add_dims(2); values->add_float_data(7.0f); values->add_float_data(8.0f); ScopedFileDeleter indices_deleter; SetupExternalDataTensor(TensorProto_DataType_INT16, indices_data, indices_file, *sparse.mutable_indices(), indices_deleter); sparse.mutable_indices()->add_dims(2); std::filesystem::path model_path = std::filesystem::current_path() / "model.onnx"; TensorProto dense; ASSERT_STATUS_OK(utils::SparseTensorProtoToDenseTensorProto(sparse, model_path, dense)); std::vector unpacked(4); ASSERT_STATUS_OK(utils::UnpackTensor(dense, model_path, unpacked.data(), unpacked.size())); std::vector expected = {0.0f, 7.0f, 8.0f, 0.0f}; EXPECT_EQ(unpacked, expected); } // Inline values + external indices (INT8), rank-1 COO. TEST(SparseTensorConversionTests, SparseTensorProtoToDense_InlineValues_ExternalIndicesInt8) { std::vector indices_data = {0, 2}; PathString indices_file(ORT_TSTR("ext_i8_XXXXXX")); SparseTensorProto sparse; sparse.add_dims(3); auto* values = sparse.mutable_values(); values->set_name("ext_int8_idx_test"); values->set_data_type(TensorProto_DataType_FLOAT); values->add_dims(2); values->add_float_data(9.0f); values->add_float_data(11.0f); ScopedFileDeleter indices_deleter; SetupExternalDataTensor(TensorProto_DataType_INT8, indices_data, indices_file, *sparse.mutable_indices(), indices_deleter); sparse.mutable_indices()->add_dims(2); std::filesystem::path model_path = std::filesystem::current_path() / "model.onnx"; TensorProto dense; ASSERT_STATUS_OK(utils::SparseTensorProtoToDenseTensorProto(sparse, model_path, dense)); std::vector unpacked(3); ASSERT_STATUS_OK(utils::UnpackTensor(dense, model_path, unpacked.data(), unpacked.size())); std::vector expected = {9.0f, 0.0f, 11.0f}; EXPECT_EQ(unpacked, expected); } // Both external values and external indices (INT64), rank-1 COO. TEST(SparseTensorConversionTests, SparseTensorProtoToDense_ExternalValues_ExternalIndicesInt64) { // Dense shape [3, 2] = 6 elements. // NNZ=2 at linear indices [1, 4]. // Expected dense: [0, 100.0, 0, 0, 200.0, 0] std::vector values_data = {100.0f, 200.0f}; std::vector indices_data = {1, 4}; PathString values_file(ORT_TSTR("ext_bv_XXXXXX")); PathString indices_file(ORT_TSTR("ext_bi_XXXXXX")); SparseTensorProto sparse; sparse.add_dims(3); sparse.add_dims(2); ScopedFileDeleter values_deleter; SetupExternalDataTensor(TensorProto_DataType_FLOAT, values_data, values_file, *sparse.mutable_values(), values_deleter); sparse.mutable_values()->set_name("ext_both_test"); sparse.mutable_values()->add_dims(2); ScopedFileDeleter indices_deleter; SetupExternalDataTensor(TensorProto_DataType_INT64, indices_data, indices_file, *sparse.mutable_indices(), indices_deleter); sparse.mutable_indices()->add_dims(2); std::filesystem::path model_path = std::filesystem::current_path() / "model.onnx"; TensorProto dense; ASSERT_STATUS_OK(utils::SparseTensorProtoToDenseTensorProto(sparse, model_path, dense)); ASSERT_EQ(dense.dims_size(), 2); EXPECT_EQ(dense.dims(0), 3); EXPECT_EQ(dense.dims(1), 2); std::vector unpacked(6); ASSERT_STATUS_OK(utils::UnpackTensor(dense, model_path, unpacked.data(), unpacked.size())); std::vector expected = {0.0f, 100.0f, 0.0f, 0.0f, 200.0f, 0.0f}; EXPECT_EQ(unpacked, expected); } // Both external values and external indices (INT64), rank-2 COO indices. TEST(SparseTensorConversionTests, SparseTensorProtoToDense_ExternalValues_ExternalIndicesInt64_Rank2) { // Dense shape [3, 3] = 9 elements. // NNZ=2 with 2D indices: [[0, 2], [2, 0]] -> positions (0,2)=2, (2,0)=6. // Expected dense: [0, 0, 50.0, 0, 0, 0, 60.0, 0, 0] std::vector values_data = {50.0f, 60.0f}; // Rank-2 indices: flattened as [row0, col0, row1, col1] std::vector indices_data = {0, 2, 2, 0}; PathString values_file(ORT_TSTR("ext_r2v_XXXXXX")); PathString indices_file(ORT_TSTR("ext_r2i_XXXXXX")); SparseTensorProto sparse; sparse.add_dims(3); sparse.add_dims(3); ScopedFileDeleter values_deleter; SetupExternalDataTensor(TensorProto_DataType_FLOAT, values_data, values_file, *sparse.mutable_values(), values_deleter); sparse.mutable_values()->set_name("ext_rank2_test"); sparse.mutable_values()->add_dims(2); // NNZ ScopedFileDeleter indices_deleter; SetupExternalDataTensor(TensorProto_DataType_INT64, indices_data, indices_file, *sparse.mutable_indices(), indices_deleter); sparse.mutable_indices()->add_dims(2); // NNZ sparse.mutable_indices()->add_dims(2); // rank of dense tensor std::filesystem::path model_path = std::filesystem::current_path() / "model.onnx"; TensorProto dense; ASSERT_STATUS_OK(utils::SparseTensorProtoToDenseTensorProto(sparse, model_path, dense)); std::vector unpacked(9); ASSERT_STATUS_OK(utils::UnpackTensor(dense, model_path, unpacked.data(), unpacked.size())); std::vector expected = {0.0f, 0.0f, 50.0f, 0.0f, 0.0f, 0.0f, 60.0f, 0.0f, 0.0f}; EXPECT_EQ(unpacked, expected); } TEST(SparseTensorConversionTests, SparseTensorProtoToDense_RejectsZeroElementStringValues) { SparseTensorProto sparse; sparse.add_dims(0); auto* values = sparse.mutable_values(); values->set_name("zero_string"); values->set_data_type(TensorProto_DataType_STRING); values->add_dims(0); values->add_string_data("unexpected"); auto* indices = sparse.mutable_indices(); indices->set_data_type(TensorProto_DataType_INT64); indices->add_dims(0); indices->set_raw_data(""); TensorProto dense; std::filesystem::path model_path; ASSERT_STATUS_NOT_OK_AND_HAS_SUBSTR( utils::SparseTensorProtoToDenseTensorProto(sparse, model_path, dense), "Unsupported sparse tensor data type"); } #endif // !defined(DISABLE_SPARSE_TENSORS) } // namespace test } // namespace onnxruntime