Skip to main content

arrow_schema/extension/canonical/
variable_shape_tensor.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
3// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements
4
5//! VariableShapeTensor
6//!
7//! <https://arrow.apache.org/docs/format/CanonicalExtensions.html#variable-shape-tensor>
8
9use serde_core::de::{self, MapAccess, Visitor};
10use serde_core::{Deserialize, Deserializer, Serialize, Serializer};
11use std::fmt;
12
13use crate::{ArrowError, DataType, Field, extension::ExtensionType};
14
15/// The extension type for `VariableShapeTensor`.
16///
17/// Extension name: `arrow.variable_shape_tensor`.
18///
19/// The storage type of the extension is: StructArray where struct is composed
20/// of data and shape fields describing a single tensor per row:
21/// - `data` is a List holding tensor elements (each list element is a single
22///   tensor). The List’s value type is the value type of the tensor, such as
23///   an integer or floating-point type.
24/// - `shape` is a `FixedSizeList<int32>[ndim]` of the tensor shape where the
25///   size of the list `ndim` is equal to the number of dimensions of the
26///   tensor.
27///
28/// Extension type parameters:
29/// `value_type`: the Arrow data type of individual tensor elements.
30///
31/// Optional parameters describing the logical layout:
32/// - `dim_names`: explicit names to tensor dimensions as an array. The length
33///   of it should be equal to the shape length and equal to the number of
34///   dimensions.
35///   `dim_names` can be used if the dimensions have well-known names and they
36///   map to the physical layout (row-major).
37/// - `permutation`: indices of the desired ordering of the original
38///   dimensions, defined as an array.
39///   The indices contain a permutation of the values `[0, 1, .., N-1]` where
40///   `N` is the number of dimensions. The permutation indicates which
41///   dimension of the logical layout corresponds to which dimension of the
42///   physical tensor (the i-th dimension of the logical view corresponds to
43///   the dimension with number `permutations[i]` of the physical tensor).
44///   Permutation can be useful in case the logical order of the tensor is a
45///   permutation of the physical order (row-major).
46///   When logical and physical layout are equal, the permutation will always
47///   be (`[0, 1, .., N-1]`) and can therefore be left out.
48/// - `uniform_shape`: sizes of individual tensor’s dimensions which are
49///   guaranteed to stay constant in uniform dimensions and can vary in non-
50///   uniform dimensions. This holds over all tensors in the array. Sizes in
51///   uniform dimensions are represented with int32 values, while sizes of the
52///   non-uniform dimensions are not known in advance and are represented with
53///   null. If `uniform_shape` is not provided it is assumed that all
54///   dimensions are non-uniform. An array containing a tensor with shape (2,
55///   3, 4) and whose first and last dimensions are uniform would have
56///   `uniform_shape` (2, null, 4). This allows for interpreting the tensor
57///   correctly without accounting for uniform dimensions while still
58///   permitting optional optimizations that take advantage of the uniformity.
59///
60/// <https://arrow.apache.org/docs/format/CanonicalExtensions.html#variable-shape-tensor>
61#[derive(Debug, Clone, PartialEq)]
62pub struct VariableShapeTensor {
63    /// The data type of individual tensor elements.
64    value_type: DataType,
65
66    /// The number of dimensions of the tensor.
67    dimensions: usize,
68
69    /// The metadata of this extension type.
70    metadata: VariableShapeTensorMetadata,
71}
72
73impl VariableShapeTensor {
74    /// Returns a new variable shape tensor extension type.
75    ///
76    /// # Error
77    ///
78    /// Return an error if the provided dimension names, permutations or
79    /// uniform shapes are invalid.
80    pub fn try_new(
81        value_type: DataType,
82        dimensions: usize,
83        dimension_names: Option<Vec<String>>,
84        permutations: Option<Vec<usize>>,
85        uniform_shapes: Option<Vec<Option<i32>>>,
86    ) -> Result<Self, ArrowError> {
87        // TODO: are all data types are suitable as value type?
88        VariableShapeTensorMetadata::try_new(
89            dimensions,
90            dimension_names,
91            permutations,
92            uniform_shapes,
93        )
94        .map(|metadata| Self {
95            value_type,
96            dimensions,
97            metadata,
98        })
99    }
100
101    // Unlike `supports_data_type`, this needs no tensor instance. Borrowing metadata
102    // and returning the element type and rank lets `try_new` reuse validation without
103    // cloning metadata, while `validate` can check it without constructing a tensor.
104    fn validate_impl<'a>(
105        data_type: &'a DataType,
106        metadata: &VariableShapeTensorMetadata,
107    ) -> Result<(&'a DataType, usize), ArrowError> {
108        match data_type {
109            DataType::Struct(fields)
110                if fields.len() == 2
111                    && matches!(fields.find("data"), Some((0, _)))
112                    && matches!(fields.find("shape"), Some((1, _))) =>
113            {
114                let shape_field = &fields[1];
115                match shape_field.data_type() {
116                    DataType::FixedSizeList(_, list_size) => {
117                        let dimensions = usize::try_from(*list_size).expect("conversion failed");
118                        metadata.validate(dimensions)?;
119                        let data_field = &fields[0];
120                        match data_field.data_type() {
121                            DataType::List(field) => Ok((field.data_type(), dimensions)),
122                            data_type => Err(ArrowError::InvalidArgumentError(format!(
123                                "VariableShapeTensor data type mismatch, expected List for data field, found {data_type}"
124                            ))),
125                        }
126                    }
127                    data_type => Err(ArrowError::InvalidArgumentError(format!(
128                        "VariableShapeTensor data type mismatch, expected FixedSizeList for shape field, found {data_type}"
129                    ))),
130                }
131            }
132            data_type => Err(ArrowError::InvalidArgumentError(format!(
133                "VariableShapeTensor data type mismatch, expected Struct with 2 fields (data and shape), found {data_type}"
134            ))),
135        }
136    }
137
138    /// Returns the value type of the individual tensor elements.
139    pub fn value_type(&self) -> &DataType {
140        &self.value_type
141    }
142
143    /// Returns the number of dimensions  in this variable shape tensor.
144    pub fn dimensions(&self) -> usize {
145        self.dimensions
146    }
147
148    /// Returns the names of the dimensions in this variable shape tensor, if
149    /// set.
150    pub fn dimension_names(&self) -> Option<&[String]> {
151        self.metadata.dimension_names()
152    }
153
154    /// Returns the indices of the desired ordering of the original
155    /// dimensions, if set.
156    pub fn permutations(&self) -> Option<&[usize]> {
157        self.metadata.permutations()
158    }
159
160    /// Returns sizes of individual tensor’s dimensions which are guaranteed
161    /// to stay constant in uniform dimensions and can vary in non-uniform
162    /// dimensions.
163    pub fn uniform_shapes(&self) -> Option<&[Option<i32>]> {
164        self.metadata.uniform_shapes()
165    }
166}
167
168/// Extension type metadata for [`VariableShapeTensor`].
169#[derive(Debug, Clone, PartialEq)]
170pub struct VariableShapeTensorMetadata {
171    /// Explicit names to tensor dimensions.
172    dim_names: Option<Vec<String>>,
173
174    /// Indices of the desired ordering of the original dimensions.
175    permutations: Option<Vec<usize>>,
176
177    /// Sizes of individual tensor's dimensions which are guaranteed to stay
178    /// constant in uniform dimensions and can vary in non-uniform dimensions.
179    uniform_shape: Option<Vec<Option<i32>>>,
180}
181
182impl Serialize for VariableShapeTensorMetadata {
183    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
184    where
185        S: Serializer,
186    {
187        use serde_core::ser::SerializeStruct;
188        let mut state = serializer.serialize_struct("VariableShapeTensorMetadata", 3)?;
189        state.serialize_field("dim_names", &self.dim_names)?;
190        state.serialize_field("permutations", &self.permutations)?;
191        state.serialize_field("uniform_shape", &self.uniform_shape)?;
192        state.end()
193    }
194}
195
196#[derive(Debug)]
197enum MetadataField {
198    DimNames,
199    Permutations,
200    UniformShape,
201}
202
203struct MetadataFieldVisitor;
204
205impl Visitor<'_> for MetadataFieldVisitor {
206    type Value = MetadataField;
207
208    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
209        formatter.write_str("`dim_names`, `permutations`, or `uniform_shape`")
210    }
211
212    fn visit_str<E>(self, value: &str) -> Result<MetadataField, E>
213    where
214        E: de::Error,
215    {
216        match value {
217            "dim_names" => Ok(MetadataField::DimNames),
218            "permutations" => Ok(MetadataField::Permutations),
219            "uniform_shape" => Ok(MetadataField::UniformShape),
220            _ => Err(de::Error::unknown_field(
221                value,
222                &["dim_names", "permutations", "uniform_shape"],
223            )),
224        }
225    }
226}
227
228impl<'de> Deserialize<'de> for MetadataField {
229    fn deserialize<D>(deserializer: D) -> Result<MetadataField, D::Error>
230    where
231        D: Deserializer<'de>,
232    {
233        deserializer.deserialize_identifier(MetadataFieldVisitor)
234    }
235}
236
237struct VariableShapeTensorMetadataVisitor;
238
239impl<'de> Visitor<'de> for VariableShapeTensorMetadataVisitor {
240    type Value = VariableShapeTensorMetadata;
241
242    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
243        formatter.write_str("struct VariableShapeTensorMetadata")
244    }
245
246    fn visit_seq<V>(self, mut seq: V) -> Result<VariableShapeTensorMetadata, V::Error>
247    where
248        V: de::SeqAccess<'de>,
249    {
250        let dim_names = seq
251            .next_element()?
252            .ok_or_else(|| de::Error::invalid_length(0, &self))?;
253        let permutations = seq
254            .next_element()?
255            .ok_or_else(|| de::Error::invalid_length(1, &self))?;
256        let uniform_shape = seq
257            .next_element()?
258            .ok_or_else(|| de::Error::invalid_length(2, &self))?;
259        Ok(VariableShapeTensorMetadata {
260            dim_names,
261            permutations,
262            uniform_shape,
263        })
264    }
265
266    fn visit_map<V>(self, mut map: V) -> Result<VariableShapeTensorMetadata, V::Error>
267    where
268        V: MapAccess<'de>,
269    {
270        let mut dim_names = None;
271        let mut permutations = None;
272        let mut uniform_shape = None;
273
274        while let Some(key) = map.next_key()? {
275            match key {
276                MetadataField::DimNames => {
277                    if dim_names.is_some() {
278                        return Err(de::Error::duplicate_field("dim_names"));
279                    }
280                    dim_names = Some(map.next_value()?);
281                }
282                MetadataField::Permutations => {
283                    if permutations.is_some() {
284                        return Err(de::Error::duplicate_field("permutations"));
285                    }
286                    permutations = Some(map.next_value()?);
287                }
288                MetadataField::UniformShape => {
289                    if uniform_shape.is_some() {
290                        return Err(de::Error::duplicate_field("uniform_shape"));
291                    }
292                    uniform_shape = Some(map.next_value()?);
293                }
294            }
295        }
296
297        Ok(VariableShapeTensorMetadata {
298            dim_names,
299            permutations,
300            uniform_shape,
301        })
302    }
303}
304
305impl<'de> Deserialize<'de> for VariableShapeTensorMetadata {
306    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
307    where
308        D: Deserializer<'de>,
309    {
310        deserializer.deserialize_struct(
311            "VariableShapeTensorMetadata",
312            &["dim_names", "permutations", "uniform_shape"],
313            VariableShapeTensorMetadataVisitor,
314        )
315    }
316}
317
318impl VariableShapeTensorMetadata {
319    /// Returns metadata for a variable shape tensor extension type.
320    ///
321    /// # Error
322    ///
323    /// Return an error if the provided dimension names, permutations or
324    /// uniform shapes are invalid.
325    pub fn try_new(
326        dimensions: usize,
327        dimension_names: Option<Vec<String>>,
328        permutations: Option<Vec<usize>>,
329        uniform_shapes: Option<Vec<Option<i32>>>,
330    ) -> Result<Self, ArrowError> {
331        let metadata = Self {
332            dim_names: dimension_names,
333            permutations,
334            uniform_shape: uniform_shapes,
335        };
336        metadata.validate(dimensions)?;
337        Ok(metadata)
338    }
339
340    fn validate(&self, dimensions: usize) -> Result<(), ArrowError> {
341        if let Some(dimension_names) = &self.dim_names
342            && dimension_names.len() != dimensions
343        {
344            return Err(ArrowError::InvalidArgumentError(format!(
345                "VariableShapeTensor dimension names size mismatch, expected {dimensions}, found {}",
346                dimension_names.len()
347            )));
348        }
349
350        if let Some(permutations) = &self.permutations {
351            if permutations.len() != dimensions {
352                return Err(ArrowError::InvalidArgumentError(format!(
353                    "VariableShapeTensor permutations size mismatch, expected {dimensions}, found {}",
354                    permutations.len()
355                )));
356            }
357            let mut sorted_permutations = permutations.clone();
358            sorted_permutations.sort_unstable();
359            if (0..dimensions)
360                .zip(sorted_permutations)
361                .any(|(a, b)| a != b)
362            {
363                return Err(ArrowError::InvalidArgumentError(format!(
364                    "VariableShapeTensor permutations invalid, expected a permutation of [0, 1, .., N-1], where N is the number of dimensions: {dimensions}"
365                )));
366            }
367        }
368
369        if let Some(uniform_shapes) = &self.uniform_shape
370            && uniform_shapes.len() != dimensions
371        {
372            return Err(ArrowError::InvalidArgumentError(format!(
373                "VariableShapeTensor uniform shapes size mismatch, expected {dimensions}, found {}",
374                uniform_shapes.len()
375            )));
376        }
377
378        Ok(())
379    }
380
381    /// Returns the names of the dimensions in this variable shape tensor, if
382    /// set.
383    pub fn dimension_names(&self) -> Option<&[String]> {
384        self.dim_names.as_ref().map(AsRef::as_ref)
385    }
386
387    /// Returns the indices of the desired ordering of the original dimensions,
388    /// if set.
389    pub fn permutations(&self) -> Option<&[usize]> {
390        self.permutations.as_ref().map(AsRef::as_ref)
391    }
392
393    /// Returns sizes of individual tensor’s dimensions which are guaranteed
394    /// to stay constant in uniform dimensions and can vary in non-uniform
395    /// dimensions.
396    pub fn uniform_shapes(&self) -> Option<&[Option<i32>]> {
397        self.uniform_shape.as_ref().map(AsRef::as_ref)
398    }
399}
400
401impl ExtensionType for VariableShapeTensor {
402    const NAME: &'static str = "arrow.variable_shape_tensor";
403
404    type Metadata = VariableShapeTensorMetadata;
405
406    fn metadata(&self) -> &Self::Metadata {
407        &self.metadata
408    }
409
410    fn serialize_metadata(&self) -> Option<String> {
411        Some(serde_json::to_string(self.metadata()).expect("metadata serialization"))
412    }
413
414    fn deserialize_metadata(metadata: Option<&str>) -> Result<Self::Metadata, ArrowError> {
415        metadata.map_or_else(
416            || {
417                Err(ArrowError::InvalidArgumentError(
418                    "VariableShapeTensor extension types requires metadata".to_owned(),
419                ))
420            },
421            |value| {
422                serde_json::from_str(value).map_err(|e| {
423                    ArrowError::InvalidArgumentError(format!(
424                        "VariableShapeTensor metadata deserialization failed: {e}"
425                    ))
426                })
427            },
428        )
429    }
430
431    fn supports_data_type(&self, data_type: &DataType) -> Result<(), ArrowError> {
432        let expected = DataType::Struct(
433            [
434                Field::new_list(
435                    "data",
436                    Field::new_list_field(self.value_type.clone(), false),
437                    false,
438                ),
439                Field::new(
440                    "shape",
441                    DataType::new_fixed_size_list(
442                        DataType::Int32,
443                        i32::try_from(self.dimensions()).expect("overflow"),
444                        false,
445                    ),
446                    false,
447                ),
448            ]
449            .into_iter()
450            .collect(),
451        );
452        data_type
453            .equals_datatype(&expected)
454            .then_some(())
455            .ok_or_else(|| {
456                ArrowError::InvalidArgumentError(format!(
457                    "VariableShapeTensor data type mismatch, expected {expected}, found {data_type}"
458                ))
459            })
460    }
461
462    fn try_new(data_type: &DataType, metadata: Self::Metadata) -> Result<Self, ArrowError> {
463        let (value_type, dimensions) = Self::validate_impl(data_type, &metadata)?;
464        Ok(Self {
465            value_type: value_type.clone(),
466            dimensions,
467            metadata,
468        })
469    }
470
471    fn validate(data_type: &DataType, metadata: Self::Metadata) -> Result<(), ArrowError> {
472        Self::validate_impl(data_type, &metadata).map(|_| ())
473    }
474}
475
476#[cfg(test)]
477mod tests {
478    #[cfg(feature = "canonical_extension_types")]
479    use crate::extension::CanonicalExtensionType;
480    use crate::{
481        Field,
482        extension::{EXTENSION_TYPE_METADATA_KEY, EXTENSION_TYPE_NAME_KEY},
483    };
484
485    use super::*;
486
487    #[test]
488    fn valid() -> Result<(), ArrowError> {
489        let variable_shape_tensor = VariableShapeTensor::try_new(
490            DataType::Float32,
491            3,
492            Some(vec!["C".to_owned(), "H".to_owned(), "W".to_owned()]),
493            Some(vec![2, 0, 1]),
494            Some(vec![Some(400), None, Some(3)]),
495        )?;
496        let mut field = Field::new_struct(
497            "",
498            vec![
499                Field::new_list(
500                    "data",
501                    Field::new_list_field(DataType::Float32, false),
502                    false,
503                ),
504                Field::new_fixed_size_list(
505                    "shape",
506                    Field::new("", DataType::Int32, false),
507                    3,
508                    false,
509                ),
510            ],
511            false,
512        );
513        field.try_with_extension_type(variable_shape_tensor.clone())?;
514        assert!(field.has_valid_extension_type::<VariableShapeTensor>());
515        assert_eq!(
516            field.try_extension_type::<VariableShapeTensor>()?,
517            variable_shape_tensor
518        );
519        #[cfg(feature = "canonical_extension_types")]
520        assert_eq!(
521            field.try_canonical_extension_type()?,
522            CanonicalExtensionType::VariableShapeTensor(variable_shape_tensor)
523        );
524        Ok(())
525    }
526
527    #[test]
528    #[should_panic(expected = "Extension type name missing")]
529    fn missing_name() {
530        let field = Field::new_struct(
531            "",
532            vec![
533                Field::new_list(
534                    "data",
535                    Field::new_list_field(DataType::Float32, false),
536                    false,
537                ),
538                Field::new_fixed_size_list(
539                    "shape",
540                    Field::new("", DataType::Int32, false),
541                    3,
542                    false,
543                ),
544            ],
545            false,
546        )
547        .with_metadata([(EXTENSION_TYPE_METADATA_KEY, "{}")]);
548        field.extension_type::<VariableShapeTensor>();
549    }
550
551    #[test]
552    #[should_panic(expected = "VariableShapeTensor data type mismatch, expected Struct")]
553    fn invalid_type() {
554        let variable_shape_tensor =
555            VariableShapeTensor::try_new(DataType::Int32, 3, None, None, None).unwrap();
556        let field = Field::new_struct(
557            "",
558            vec![
559                Field::new_list(
560                    "data",
561                    Field::new_list_field(DataType::Float32, false),
562                    false,
563                ),
564                Field::new_fixed_size_list(
565                    "shape",
566                    Field::new("", DataType::Int32, false),
567                    3,
568                    false,
569                ),
570            ],
571            false,
572        );
573        field.with_extension_type(variable_shape_tensor);
574    }
575
576    #[test]
577    #[should_panic(expected = "VariableShapeTensor extension types requires metadata")]
578    fn missing_metadata() {
579        let field = Field::new_struct(
580            "",
581            vec![
582                Field::new_list(
583                    "data",
584                    Field::new_list_field(DataType::Float32, false),
585                    false,
586                ),
587                Field::new_fixed_size_list(
588                    "shape",
589                    Field::new("", DataType::Int32, false),
590                    3,
591                    false,
592                ),
593            ],
594            false,
595        )
596        .with_metadata([(EXTENSION_TYPE_NAME_KEY, VariableShapeTensor::NAME)]);
597        field.extension_type::<VariableShapeTensor>();
598    }
599
600    #[test]
601    #[should_panic(expected = "VariableShapeTensor metadata deserialization failed: invalid type:")]
602    fn invalid_metadata() {
603        let field = Field::new_struct(
604            "",
605            vec![
606                Field::new_list(
607                    "data",
608                    Field::new_list_field(DataType::Float32, false),
609                    false,
610                ),
611                Field::new_fixed_size_list(
612                    "shape",
613                    Field::new("", DataType::Int32, false),
614                    3,
615                    false,
616                ),
617            ],
618            false,
619        )
620        .with_metadata([
621            (EXTENSION_TYPE_NAME_KEY, VariableShapeTensor::NAME),
622            (
623                EXTENSION_TYPE_METADATA_KEY,
624                r#"{ "dim_names": [1, null, 3, 4] }"#,
625            ),
626        ]);
627        field.extension_type::<VariableShapeTensor>();
628    }
629
630    #[test]
631    fn invalid_deserialized_metadata() -> Result<(), ArrowError> {
632        let data_type = DataType::Struct(
633            vec![
634                Field::new_list(
635                    "data",
636                    Field::new_list_field(DataType::Float32, false),
637                    false,
638                ),
639                Field::new_fixed_size_list(
640                    "shape",
641                    Field::new_list_field(DataType::Int32, false),
642                    2,
643                    false,
644                ),
645            ]
646            .into(),
647        );
648        let metadata =
649            VariableShapeTensor::deserialize_metadata(Some(r#"{"dim_names":["height"]}"#))?;
650        for result in [
651            VariableShapeTensor::validate(&data_type, metadata.clone()),
652            <VariableShapeTensor as ExtensionType>::try_new(&data_type, metadata).map(|_| ()),
653        ] {
654            assert!(
655                matches!(&result, Err(ArrowError::InvalidArgumentError(message)) if message.contains("dimension names size mismatch")),
656                "expected dimension names size mismatch, got {result:?}"
657            );
658        }
659        Ok(())
660    }
661
662    #[test]
663    #[should_panic(
664        expected = "VariableShapeTensor dimension names size mismatch, expected 3, found 2"
665    )]
666    fn invalid_metadata_dimension_names() {
667        VariableShapeTensor::try_new(
668            DataType::Float32,
669            3,
670            Some(vec!["a".to_owned(), "b".to_owned()]),
671            None,
672            None,
673        )
674        .unwrap();
675    }
676
677    #[test]
678    #[should_panic(
679        expected = "VariableShapeTensor permutations size mismatch, expected 3, found 2"
680    )]
681    fn invalid_metadata_permutations_len() {
682        VariableShapeTensor::try_new(DataType::Float32, 3, None, Some(vec![1, 0]), None).unwrap();
683    }
684
685    #[test]
686    #[should_panic(
687        expected = "VariableShapeTensor permutations invalid, expected a permutation of [0, 1, .., N-1], where N is the number of dimensions: 3"
688    )]
689    fn invalid_metadata_permutations_values() {
690        VariableShapeTensor::try_new(DataType::Float32, 3, None, Some(vec![4, 3, 2]), None)
691            .unwrap();
692    }
693
694    #[test]
695    #[should_panic(
696        expected = "VariableShapeTensor uniform shapes size mismatch, expected 3, found 2"
697    )]
698    fn invalid_metadata_uniform_shapes() {
699        VariableShapeTensor::try_new(DataType::Float32, 3, None, None, Some(vec![None, Some(1)]))
700            .unwrap();
701    }
702}