Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 3 additions & 4 deletions cpp/src/arrow/extension/fixed_shape_tensor.cc
Original file line number Diff line number Diff line change
Expand Up @@ -200,15 +200,15 @@ Result<std::shared_ptr<Tensor>> FixedShapeTensorType::MakeTensor(
}

std::vector<int64_t> shape = ext_type.shape();
ARROW_ASSIGN_OR_RAISE(
auto strides, internal::ComputeStrides(ext_type.value_type(), shape, permutation));
Comment on lines +203 to +204
internal::Permute<int64_t>(permutation, &shape);

std::vector<std::string> dim_names = ext_type.dim_names();
if (!dim_names.empty()) {
internal::Permute<std::string>(permutation, &dim_names);
}

ARROW_ASSIGN_OR_RAISE(
auto strides, internal::ComputeStrides(ext_type.value_type(), shape, permutation));
ARROW_ASSIGN_OR_RAISE(const auto buffer, internal::SliceTensorBuffer(
*array, *ext_type.value_type(), shape));

Expand Down Expand Up @@ -340,10 +340,9 @@ Result<std::shared_ptr<Tensor>> FixedShapeTensorArray::ToTensorWithNulls() const
std::vector<int64_t> shape = ext_type.shape();
ARROW_ASSIGN_OR_RAISE(const int64_t cell_size, internal::ComputeShapeProduct(shape));
shape.insert(shape.begin(), 1, this->length());
internal::Permute<int64_t>(permutation, &shape);

ARROW_ASSIGN_OR_RAISE(auto tensor_strides,
internal::ComputeStrides(value_type, shape, permutation));
internal::Permute<int64_t>(permutation, &shape);

const auto& raw_buffer = this->storage()->data()->child_data[0]->buffers[1];
ARROW_ASSIGN_OR_RAISE(
Expand Down
48 changes: 46 additions & 2 deletions cpp/src/arrow/extension/tensor_extension_array_test.cc
Original file line number Diff line number Diff line change
Expand Up @@ -605,7 +605,7 @@ TEST_F(TestFixedShapeTensorType, ComputeStrides) {
ASSERT_EQ(ext_type_6->Serialize(), R"({"shape":[3,4,7],"permutation":[1,2,0]})");
auto ext_type_7 = internal::checked_pointer_cast<FixedShapeTensorType>(
fixed_shape_tensor(int32(), {3, 4, 7}, {2, 0, 1}, {}));
ASSERT_EQ(ext_type_7->strides(), (std::vector<int64_t>{4, 112, 16}));
ASSERT_EQ(ext_type_7->strides(), (std::vector<int64_t>{4, 112, 28}));
ASSERT_EQ(ext_type_7->Serialize(), R"({"shape":[3,4,7],"permutation":[2,0,1]})");
}

Expand Down Expand Up @@ -676,7 +676,7 @@ TEST_F(TestFixedShapeTensorType, GetTensor) {
// Get tensor from extension array with non-trivial permutation
ASSERT_OK_AND_ASSIGN(auto expected_permuted_tensor,
Tensor::Make(value_type_, Buffer::Wrap(element_values[i]),
{4, 3}, {8, 24}, {"y", "x"}));
{4, 3}, {8, 32}, {"y", "x"}));
ASSERT_OK_AND_ASSIGN(scalar, permuted_array->GetScalar(i));
ASSERT_OK_AND_ASSIGN(auto actual_permuted_tensor,
exact_permuted_ext_type->MakeTensor(
Expand Down Expand Up @@ -1002,6 +1002,50 @@ TEST_F(TestVariableShapeTensorType, ComputeStrides) {
ASSERT_TRUE(tensor->Equals(*t));
}

TEST_F(TestVariableShapeTensorType, ComputeStridesWithNonTrivialPermutation) {
auto permuted_ext_type = internal::checked_pointer_cast<VariableShapeTensorType>(
variable_shape_tensor(value_type_, ndim_, {1, 0, 2}, dim_names_, uniform_shape_));

auto shape = ArrayFromJSON(shape_type_, "[[2,3,1]]");
auto data = ArrayFromJSON(data_type_, "[[1,1,2,3,4,5]]");
std::vector<std::shared_ptr<Field>> fields = {field("data", data_type_),
field("shape", shape_type_)};
ASSERT_OK_AND_ASSIGN(auto storage_arr, StructArray::Make({data, shape}, fields));
auto ext_arr = ExtensionType::WrapArray(permuted_ext_type, storage_arr);
auto ext_array = std::static_pointer_cast<VariableShapeTensorArray>(ext_arr);

ASSERT_OK_AND_ASSIGN(auto scalar, ext_array->GetScalar(0));
ASSERT_OK_AND_ASSIGN(auto tensor,
permuted_ext_type->MakeTensor(
internal::checked_pointer_cast<ExtensionScalar>(scalar)));

ASSERT_EQ(tensor->shape(), (std::vector<int64_t>{3, 2, 1}));
ASSERT_EQ(tensor->strides(), (std::vector<int64_t>{sizeof(int64_t), sizeof(int64_t) * 3,
sizeof(int64_t)}));
ASSERT_EQ(tensor->dim_names(), (std::vector<std::string>{"y", "x", "z"}));

// Non-self-inverse 3-cycle permutation with distinct dimension sizes
auto cyclic_ext_type = internal::checked_pointer_cast<VariableShapeTensorType>(
variable_shape_tensor(value_type_, ndim_, {2, 0, 1}, dim_names_, {}));
auto cyclic_shape = ArrayFromJSON(shape_type_, "[[2,3,4]]");
auto cyclic_data = ArrayFromJSON(
data_type_, "[[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23]]");
ASSERT_OK_AND_ASSIGN(auto cyclic_storage,
StructArray::Make({cyclic_data, cyclic_shape}, fields));
auto cyclic_arr = std::static_pointer_cast<VariableShapeTensorArray>(
ExtensionType::WrapArray(cyclic_ext_type, cyclic_storage));
ASSERT_OK_AND_ASSIGN(auto cyclic_scalar, cyclic_arr->GetScalar(0));
ASSERT_OK_AND_ASSIGN(
auto cyclic_tensor,
cyclic_ext_type->MakeTensor(
internal::checked_pointer_cast<ExtensionScalar>(cyclic_scalar)));
ASSERT_EQ(cyclic_tensor->shape(), (std::vector<int64_t>{4, 2, 3}));
ASSERT_EQ(
cyclic_tensor->strides(),
(std::vector<int64_t>{sizeof(int64_t), sizeof(int64_t) * 12, sizeof(int64_t) * 4}));
ASSERT_EQ(cyclic_tensor->dim_names(), (std::vector<std::string>{"z", "x", "y"}));
}

TEST_F(TestVariableShapeTensorType, ToString) {
auto exact_ext_type =
internal::checked_pointer_cast<VariableShapeTensorType>(ext_type_);
Expand Down
18 changes: 7 additions & 11 deletions cpp/src/arrow/extension/tensor_internal.cc
Original file line number Diff line number Diff line change
Expand Up @@ -84,12 +84,10 @@ Result<std::vector<int64_t>> ComputeStrides(const std::shared_ptr<DataType>& val
int64_t remaining = 0;
if (!shape.empty() && shape[0] > 0) {
remaining = byte_width;
for (auto i : perm) {
if (i > 0) {
if (MultiplyWithOverflow(remaining, shape[i], &remaining)) {
return Status::Invalid(
"Strides computed from shape would not fit in 64-bit integer");
}
for (size_t i = 1; i < ndim; ++i) {
if (MultiplyWithOverflow(remaining, shape[i], &remaining)) {
return Status::Invalid(
"Strides computed from shape would not fit in 64-bit integer");
}
}
}
Expand All @@ -101,11 +99,9 @@ Result<std::vector<int64_t>> ComputeStrides(const std::shared_ptr<DataType>& val
}

strides.push_back(remaining);
for (auto i : perm) {
if (i > 0) {
remaining /= shape[i];
strides.push_back(remaining);
}
for (size_t i = 1; i < ndim; ++i) {
remaining /= shape[i];
strides.push_back(remaining);
}
Permute(perm, &strides);

Expand Down
2 changes: 2 additions & 0 deletions docs/source/python/api/arrays.rst
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,7 @@ may expose data type-specific methods or properties.
JsonArray
UuidArray
Bool8Array
VariableShapeTensorArray

.. _api.scalar:

Expand Down Expand Up @@ -165,6 +166,7 @@ classes may expose data type-specific methods or properties.
UnionScalar
ExtensionScalar
FixedShapeTensorScalar
VariableShapeTensorScalar
OpaqueScalar
JsonScalar
UuidScalar
Expand Down
2 changes: 2 additions & 0 deletions docs/source/python/api/datatypes.rst
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@ These should be used to create Arrow data types and schemas.
dictionary
run_end_encoded
fixed_shape_tensor
variable_shape_tensor
union
dense_union
sparse_union
Expand Down Expand Up @@ -142,6 +143,7 @@ implemented by PyArrow.
:toctree: ../generated/

FixedShapeTensorType
VariableShapeTensorType
OpaqueType
JsonType
UuidType
Expand Down
3 changes: 3 additions & 0 deletions python/pyarrow-stubs/__init__.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,8 @@ from pyarrow.lib import (
UnknownExtensionType as UnknownExtensionType,
UuidArray as UuidArray,
UuidType as UuidType,
VariableShapeTensorArray as VariableShapeTensorArray,
VariableShapeTensorType as VariableShapeTensorType,
VersionInfo as VersionInfo,
array as array,
binary as binary,
Expand Down Expand Up @@ -221,6 +223,7 @@ from pyarrow.lib import (
unregister_extension_type as unregister_extension_type,
utf8 as utf8,
uuid as uuid,
variable_shape_tensor as variable_shape_tensor,
)

from pyarrow import types as types
Expand Down
11 changes: 11 additions & 0 deletions python/pyarrow-stubs/__lib/array.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -608,6 +608,16 @@ class FixedShapeTensorArray(ExtensionArray):
@staticmethod
def from_tensor(tensor: Tensor) -> FixedShapeTensorArray: ...

class VariableShapeTensorArray(ExtensionArray):
@staticmethod
def from_numpy_ndarray(
obj: Sequence[NDArray[Any]],
dim_names: Sequence[str] | None = None,
permutation: Sequence[int] | None = None,
uniform_shape: Sequence[int | None] | None = None,
) -> VariableShapeTensorArray: ...
def to_numpy_ndarray_list(self) -> list[NDArray[Any] | None]: ...

class OpaqueArray(ExtensionArray): ...

class Bool8Array(ExtensionArray):
Expand Down Expand Up @@ -684,6 +694,7 @@ __all__ = [
"JsonArray",
"OpaqueArray",
"FixedShapeTensorArray",
"VariableShapeTensorArray",
"concat_arrays",
"_empty_array",
]
21 changes: 21 additions & 0 deletions python/pyarrow-stubs/__lib/types.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -263,6 +263,18 @@ class FixedShapeTensorType(BaseExtensionType):
@property
def permutation(self) -> list[int] | None: ...

class VariableShapeTensorType(BaseExtensionType):
@property
def value_type(self) -> DataType: ...
@property
def ndim(self) -> int: ...
@property
def dim_names(self) -> list[str] | None: ...
@property
def permutation(self) -> list[int] | None: ...
@property
def uniform_shape(self) -> list[int | None] | None: ...

class Bool8Type(BaseExtensionType): ...
class UuidType(BaseExtensionType): ...
class JsonType(BaseExtensionType): ...
Expand Down Expand Up @@ -562,6 +574,13 @@ def fixed_shape_tensor(
dim_names: Sequence[str] | None = None,
permutation: Sequence[int] | None = None,
) -> FixedShapeTensorType: ...
def variable_shape_tensor(
value_type: DataType,
ndim: int,
dim_names: Sequence[str] | None = None,
permutation: Sequence[int] | None = None,
uniform_shape: Sequence[int | None] | None = None,
) -> VariableShapeTensorType: ...
def bool8() -> Bool8Type: ...
def opaque(storage_type: DataType, type_name: str, vendor_name: str) -> OpaqueType: ...
def type_for_alias(name: str) -> DataType: ...
Expand Down Expand Up @@ -600,6 +619,7 @@ __all__ = [
"BaseExtensionType",
"ExtensionType",
"FixedShapeTensorType",
"VariableShapeTensorType",
"Bool8Type",
"UuidType",
"JsonType",
Expand Down Expand Up @@ -658,6 +678,7 @@ __all__ = [
"json_",
"uuid",
"fixed_shape_tensor",
"variable_shape_tensor",
"bool8",
"opaque",
"type_for_alias",
Expand Down
6 changes: 5 additions & 1 deletion python/pyarrow/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -180,6 +180,7 @@ def print_entry(label, value):
dictionary,
run_end_encoded,
bool8, fixed_shape_tensor, json_, opaque, uuid,
variable_shape_tensor,
field,
type_for_alias,
DataType, DictionaryType, StructType,
Expand All @@ -193,6 +194,7 @@ def print_entry(label, value):
RunEndEncodedType, Bool8Type, FixedShapeTensorType,
JsonType, OpaqueType, UuidType,
UnknownExtensionType,
VariableShapeTensorType,
register_extension_type, unregister_extension_type,
DictionaryMemo,
KeyValueMetadata,
Expand Down Expand Up @@ -229,6 +231,7 @@ def print_entry(label, value):
StructArray, ExtensionArray,
RunEndEncodedArray, Bool8Array, FixedShapeTensorArray,
JsonArray, OpaqueArray, UuidArray,
VariableShapeTensorArray,
scalar, NA, _NULL as NULL, Scalar,
NullScalar, BooleanScalar,
Int8Scalar, Int16Scalar, Int32Scalar, Int64Scalar,
Expand All @@ -246,7 +249,8 @@ def print_entry(label, value):
FixedSizeBinaryScalar, DictionaryScalar,
MapScalar, StructScalar, UnionScalar,
RunEndEncodedScalar, Bool8Scalar, ExtensionScalar,
FixedShapeTensorScalar, JsonScalar, OpaqueScalar, UuidScalar)
FixedShapeTensorScalar, JsonScalar, OpaqueScalar, UuidScalar,
VariableShapeTensorScalar)

# Buffers, allocation
from pyarrow.lib import (DeviceAllocationType, Device, MemoryManager,
Expand Down
Loading
Loading