Skip to content

PackedTensor #2258

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 4 commits into from
Closed
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
130 changes: 127 additions & 3 deletions onnxscript/ir/_core.py
Original file line number Diff line number Diff line change
Expand Up @@ -379,9 +379,10 @@

Args:
value: The backing data of the tensor. It can be a numpy array compatible object or a DLPack compatible object.
When the dtype is not one of the numpy native dtypes, the value needs
to be ``uint8`` for 4-bit and 8-bit data types, and ``uint16`` for bfloat16
when the value is a numpy array; ``dtype`` must be specified in this case.
When the dtype is not one of the numpy native dtypes, the value can
be ``uint8`` (unpacked) or ml_dtypes types for 4-bit and 8-bit data types,
and ``uint16`` or ml_dtype.bfloat16 for bfloat16 when the value is a numpy array;
``dtype`` must be specified in this case.
dtype: The data type of the tensor. It can be None only when value is a numpy array.
Users are responsible for making sure the dtype matches the value when value is not a numpy array.
shape: The shape of the tensor. If None, the shape is obtained from the value.
Expand Down Expand Up @@ -955,6 +956,129 @@
return self._evaluate().tobytes()


class PackedTensor(TensorBase, _protocols.TensorProtocol, Generic[TArrayCompatible]): # pylint: disable=too-many-ancestors
"""A tensor that stores 4bit datatypes in packed format."""

__slots__ = (
"_dtype",
"_raw",
"_shape",
)

def __init__(
self,
value: TArrayCompatible,
dtype: _enums.DataType,
*,
shape: Shape,
name: str | None = None,
doc_string: str | None = None,
metadata_props: dict[str, str] | None = None,
) -> None:
"""Initialize a tensor.

Args:
value: The backing data of the tensor. It can be a numpy array compatible object or a DLPack compatible object.
The value MUST be in ``uint8`` packed format, or in one of the ml_dtypes dtypes, which
will be packed when constructing the tensor.
dtype: The data type of the tensor. Must be one of INT4, UINT4, FLOAT4E2M1.
shape: The shape of the tensor.
name: The name of the tensor.
doc_string: The documentation string.
metadata_props: The metadata properties.

Raises:
TypeError: If the value is not a numpy array compatible or a DLPack compatible object.
TypeError: If the value is a numpy array and the dtype is not uint8 or one of the ml_dtypes dtypes.
"""
super().__init__(name=name, doc_string=doc_string, metadata_props=metadata_props)

Check warning on line 994 in onnxscript/ir/_core.py

View check run for this annotation

Codecov / codecov/patch

onnxscript/ir/_core.py#L994

Added line #L994 was not covered by tests
if not _compatible_with_numpy(value) and not _compatible_with_dlpack(value):
raise TypeError(f"Expected an array compatible object, got {type(value)}")
self._shape = shape
self._shape.freeze()

Check warning on line 998 in onnxscript/ir/_core.py

View check run for this annotation

Codecov / codecov/patch

onnxscript/ir/_core.py#L996-L998

Added lines #L996 - L998 were not covered by tests
if dtype.itemsize != 0.5:
raise TypeError(

Check warning on line 1000 in onnxscript/ir/_core.py

View check run for this annotation

Codecov / codecov/patch

onnxscript/ir/_core.py#L1000

Added line #L1000 was not covered by tests
f"PackedTensor only supports INT4, UINT4, FLOAT4E2M1, but got {dtype}"
)
self._dtype = dtype

Check warning on line 1003 in onnxscript/ir/_core.py

View check run for this annotation

Codecov / codecov/patch

onnxscript/ir/_core.py#L1003

Added line #L1003 was not covered by tests

if isinstance(value, np.ndarray):
if value.dtype == ml_dtypes.float4_e2m1fn or value.dtype == ml_dtypes.uint4 or value.dtype == ml_dtypes.int4:

Check notice

Code scanning / lintrunner

PYLINT/R1714 Note

Consider merging these comparisons with 'in' by using 'value.dtype in (ml_dtypes.float4_e2m1fn, ml_dtypes.uint4, ml_dtypes.int4)'. Use a set instead if elements are hashable. (consider-using-in)
See consider-using-in. To disable, use # pylint: disable=consider-using-in
# Pack the array into uint8
value = _type_casting.pack_int4(value)

Check failure

Code scanning / lintrunner

MYPY/assignment Error

Incompatible types in assignment (expression has type "ndarray[Any, dtype[unsignedinteger[_8Bit]]]", variable has type "TArrayCompatible") To disable, use # type: ignore[assignment]
self._raw = value

Check warning on line 1009 in onnxscript/ir/_core.py

View check run for this annotation

Codecov / codecov/patch

onnxscript/ir/_core.py#L1008-L1009

Added lines #L1008 - L1009 were not covered by tests

def __array__(self, dtype: Any = None) -> np.ndarray:
return self.numpy()

Check warning on line 1012 in onnxscript/ir/_core.py

View check run for this annotation

Codecov / codecov/patch

onnxscript/ir/_core.py#L1012

Added line #L1012 was not covered by tests

def __dlpack__(self, *, stream: Any = None) -> Any:
if _compatible_with_dlpack(self._raw):
return self._raw.__dlpack__(stream=stream)
return self.__array__().__dlpack__(stream=stream)

Check warning on line 1017 in onnxscript/ir/_core.py

View check run for this annotation

Codecov / codecov/patch

onnxscript/ir/_core.py#L1016-L1017

Added lines #L1016 - L1017 were not covered by tests

def __dlpack_device__(self) -> tuple[int, int]:
if _compatible_with_dlpack(self._raw):
return self._raw.__dlpack_device__()
return self.__array__().__dlpack_device__()

Check warning on line 1022 in onnxscript/ir/_core.py

View check run for this annotation

Codecov / codecov/patch

onnxscript/ir/_core.py#L1021-L1022

Added lines #L1021 - L1022 were not covered by tests

def __repr__(self) -> str:
return f"{self._repr_base()}({self._raw!r}, name={self.name!r})"

Check warning on line 1025 in onnxscript/ir/_core.py

View check run for this annotation

Codecov / codecov/patch

onnxscript/ir/_core.py#L1025

Added line #L1025 was not covered by tests

@property
def dtype(self) -> _enums.DataType:
"""The data type of the tensor. Immutable."""
return self._dtype

Check warning on line 1030 in onnxscript/ir/_core.py

View check run for this annotation

Codecov / codecov/patch

onnxscript/ir/_core.py#L1030

Added line #L1030 was not covered by tests

@property
def shape(self) -> Shape:
"""The shape of the tensor. Immutable."""
return self._shape

Check warning on line 1035 in onnxscript/ir/_core.py

View check run for this annotation

Codecov / codecov/patch

onnxscript/ir/_core.py#L1035

Added line #L1035 was not covered by tests

@property
def raw(self) -> TArrayCompatible:
"""Backing data of the tensor. Immutable."""
return self._raw # type: ignore[return-value]

Check warning on line 1040 in onnxscript/ir/_core.py

View check run for this annotation

Codecov / codecov/patch

onnxscript/ir/_core.py#L1040

Added line #L1040 was not covered by tests

def numpy(self) -> np.ndarray:
"""Return the tensor as a numpy array.

When the data type is not supported by numpy, the dtypes from the ``ml_dtype``
package are used. The values can be reinterpreted as bit representations
using the ``.view()`` method.
"""
if isinstance(self._raw, np.ndarray) or _compatible_with_numpy(self._raw):
array = self._raw.__array__(dtype)

Check failure

Code scanning / lintrunner

PYLINT/E0602 Error

Undefined variable 'dtype' (undefined-variable)
See undefined-variable. To disable, use # pylint: disable=undefined-variable

Check failure

Code scanning / lintrunner

RUFF/F821 Error

Check failure

Code scanning / lintrunner

MYPY/name-defined Error

Name "dtype" is not defined To disable, use # type: ignore[name-defined]
assert _compatible_with_dlpack(self._raw), (

Check warning on line 1051 in onnxscript/ir/_core.py

View check run for this annotation

Codecov / codecov/patch

onnxscript/ir/_core.py#L1050-L1051

Added lines #L1050 - L1051 were not covered by tests
f"Bug: Expected DLPack or Numpy compatible objects, got {type(self._raw)}"
)
array = np.from_dlpack(self._raw)

Check warning on line 1054 in onnxscript/ir/_core.py

View check run for this annotation

Codecov / codecov/patch

onnxscript/ir/_core.py#L1054

Added line #L1054 was not covered by tests
# ONNX IR returns the unpacked arrays
if self.dtype == _enums.DataType.INT4:
return _type_casting.unpack_int4(array, self.shape.numpy())

Check warning on line 1057 in onnxscript/ir/_core.py

View check run for this annotation

Codecov / codecov/patch

onnxscript/ir/_core.py#L1057

Added line #L1057 was not covered by tests
if self.dtype == _enums.DataType.UINT4:
return _type_casting.unpack_uint4(array, self.shape.numpy())

Check warning on line 1059 in onnxscript/ir/_core.py

View check run for this annotation

Codecov / codecov/patch

onnxscript/ir/_core.py#L1059

Added line #L1059 was not covered by tests
if self.dtype == _enums.DataType.FLOAT4E2M1:
return _type_casting.unpack_float4e2m1(array, self.shape.numpy())
raise TypeError(

Check warning on line 1062 in onnxscript/ir/_core.py

View check run for this annotation

Codecov / codecov/patch

onnxscript/ir/_core.py#L1061-L1062

Added lines #L1061 - L1062 were not covered by tests
f"PackedTensor only supports INT4, UINT4, FLOAT4E2M1, but got {self.dtype}"
)

def numpy_packed(self) -> npt.NDArray[np.uint8]:
"""Return the tensor as a packed array."""
return np.asarray(self._raw, dtype=np.uint8)

Check warning on line 1068 in onnxscript/ir/_core.py

View check run for this annotation

Codecov / codecov/patch

onnxscript/ir/_core.py#L1068

Added line #L1068 was not covered by tests

def tobytes(self) -> bytes:
"""Returns the value as bytes encoded in little endian.

Override this method for more efficient serialization when the raw
value is not a numpy array.
"""
array = self.numpy()

Check warning on line 1076 in onnxscript/ir/_core.py

View check run for this annotation

Codecov / codecov/patch

onnxscript/ir/_core.py#L1076

Added line #L1076 was not covered by tests
if not _IS_LITTLE_ENDIAN:
array = array.view(array.dtype.newbyteorder("<"))
return array.tobytes()

Check warning on line 1079 in onnxscript/ir/_core.py

View check run for this annotation

Codecov / codecov/patch

onnxscript/ir/_core.py#L1078-L1079

Added lines #L1078 - L1079 were not covered by tests


class SymbolicDim(_protocols.SymbolicDimProtocol, _display.PrettyPrintable):
"""Immutable symbolic dimension that can be shared across multiple shapes."""

Expand Down
Loading