Skip to content

[IR] Implement __buffer__ for tensors #2241

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

Draft
wants to merge 22 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from 2 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
30 changes: 30 additions & 0 deletions onnxscript/ir/_core.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
from typing import (
AbstractSet,
Any,
BinaryIO,
Callable,
Collection,
Generic,
Expand Down Expand Up @@ -122,6 +123,24 @@
# Use math.ceil because when dtype is INT4, the itemsize is 0.5
return math.ceil(self.dtype.itemsize * self.size)

def tofile(self: _protocols.TensorProtocol, file: BinaryIO, /) -> None:
"""Write the tensor content as bytes to a file-like object."""
if self.dtype in {
_enums.DataType.INT4,
_enums.DataType.UINT4,
_enums.DataType.FLOAT4E2M1,
}:
# Packing is required. So we call tobytes() directly
file.write(self.tobytes())
return

# Otherwise use tofile from the numpy array
array = self.numpy()
assert self.dtype.itemsize == array.itemsize, "Bug: The itemsize should match"
if not _IS_LITTLE_ENDIAN:
array = array.view(array.dtype.newbyteorder("<"))
return array.tofile(file)

def display(self, *, page: bool = False) -> None:
rich = _display.require_rich()

Expand Down Expand Up @@ -699,6 +718,17 @@
length = self._length or self.nbytes
return self.raw[offset : offset + length]

def tofile(self, file: BinaryIO, /) -> None:
"""Write the tensor content as bytes to a file-like object."""
self._check_validity()
if self.raw is None:
self._load()
assert self.raw is not None
offset = self._offset or 0
length = self._length or self.nbytes
# FIXME avoid a copy
file.write(self.raw[offset : offset + length])

def valid(self) -> bool:
"""Check if the tensor is valid.

Expand Down
4 changes: 4 additions & 0 deletions onnxscript/ir/_protocols.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
import typing
from typing import (
Any,
BinaryIO,
Collection,
Iterable,
Iterator,
Expand Down Expand Up @@ -145,6 +146,9 @@ def tobytes(self) -> bytes:
"""Return the tensor as a byte string conformed to the ONNX specification, in little endian."""
...

def tofile(self, file: BinaryIO, /) -> None:
"""Write the tensor content as bytes to a file-like object."""


@typing.runtime_checkable
class ValueProtocol(Protocol):
Expand Down
Loading