|
| 1 | +from abc import ABC, abstractmethod |
| 2 | +from dataclasses import dataclass |
| 3 | +from typing import Dict, List, Sequence |
| 4 | + |
| 5 | +from executorch.exir._serialize._cord import Cord |
| 6 | + |
| 7 | +from executorch.exir.schema import ScalarType |
| 8 | + |
| 9 | + |
| 10 | +@dataclass |
| 11 | +class TensorLayout: |
| 12 | + """ |
| 13 | + Tensor layout information for externally-serialized tensors. |
| 14 | + """ |
| 15 | + |
| 16 | + scalar_type: ScalarType |
| 17 | + dim_sizes: List[int] |
| 18 | + dim_order: List[bytes] |
| 19 | + |
| 20 | + |
| 21 | +@dataclass |
| 22 | +class SerializationInfo: |
| 23 | + # A sequence of tensor data buffers. |
| 24 | + tensor_buffers: Sequence[bytes] |
| 25 | + |
| 26 | + # A map from tensor name (fqn) to tensor index inside `tensor_buffers`. |
| 27 | + fqn_to_buffer_index: Dict[str, int] |
| 28 | + |
| 29 | + # A map from tensor name (fqn) to TensorLayout. |
| 30 | + fqn_to_tensor_layout: Dict[str, TensorLayout] |
| 31 | + |
| 32 | + |
| 33 | +class DataSerializer(ABC): |
| 34 | + """Serializes and deserializes FQN-tagged tensor data. |
| 35 | +
|
| 36 | + This base class enables serialization into different formats. See |
| 37 | + executorch/extension/flat_tensor/ for an example. |
| 38 | + """ |
| 39 | + |
| 40 | + @abstractmethod |
| 41 | + def __init__(self) -> None: |
| 42 | + """ |
| 43 | + This initializer may be overridden in derived classes to hold |
| 44 | + the data required for serialization, eg. configurations. |
| 45 | + """ |
| 46 | + pass |
| 47 | + |
| 48 | + @abstractmethod |
| 49 | + def serialize_tensors( |
| 50 | + self, |
| 51 | + serialization_info: SerializationInfo, |
| 52 | + ) -> Cord: |
| 53 | + """ |
| 54 | + Serializes a list of tensors emitted by ExecuTorch into a binary blob. |
| 55 | +
|
| 56 | + Args: |
| 57 | + serialization_info: the tensor buffers and tensor layout |
| 58 | + information required for serialization. |
| 59 | +
|
| 60 | + Returns: |
| 61 | + A binary blob that contains the serialized data. |
| 62 | + """ |
| 63 | + raise NotImplementedError("serialize_data") |
| 64 | + |
| 65 | + @abstractmethod |
| 66 | + def deserialize_tensors(self, blob: Cord) -> SerializationInfo: |
| 67 | + """ |
| 68 | + Deserializes a blob into a list of tensors. Reverses the effect of |
| 69 | + serialize_tensors. |
| 70 | +
|
| 71 | + Args: |
| 72 | + blob: A binary blob that contains the serialized data. |
| 73 | +
|
| 74 | + Returns: |
| 75 | + SerializationInfo: tensor buffers and tensor layout information |
| 76 | + deserialized from `blob`. |
| 77 | + """ |
| 78 | + raise NotImplementedError("deserialize_data") |
0 commit comments