LazyTensor

class onnx_ir.LazyTensor(func, dtype, shape, *, cache=False, name=None, doc_string=None, metadata_props=None)

一个延迟评估函数以获取实际张量的张量。

此类接受一个返回 ir.TensorProtocol 的函数、一个 dtype 和一个 shape 参数。当调用 tobytes()numpy() 时,该函数将延迟评估以获取实际张量。

示例

>>> import numpy as np
>>> import onnx_ir as ir
>>> weights = np.array([[1, 2, 3]])
>>> def create_tensor():  # Delay applying transformations to the weights
...     weights_t = weights.transpose()
...     return ir.tensor(weights_t)
>>> lazy_tensor = ir.LazyTensor(create_tensor, dtype=ir.DataType.INT64, shape=ir.Shape([1, 3]))
>>> print(lazy_tensor.numpy())
[[1]
 [2]
 [3]]
参数:
  • func (Callable[[], _protocols.TensorProtocol])

  • dtype (_enums.DataType)

  • shape (Shape)

  • cache (bool)

  • name (str | None)

  • doc_string (str | None)

  • metadata_props (dict[str, str] | None)

func

返回实际张量的函数。

dtype

张量的数据类型。

shape

张量的形状。

cache

是否缓存函数结果。如果为 False,每次访问张量内容时都会调用该函数。如果为 True,则只调用一次函数并将结果缓存到内存中。默认值为 False。

name

张量的名称。

doc_string

文档字符串。

metadata_props

元数据属性。

cache
display(*, page=False)

漂亮地打印对象。

参数:

page (bool) – 是否分页输出。

返回类型:

property doc_string: str | None

文档字符串。

property dtype: DataType

张量的数据类型。不可变。

property meta: MetadataStore

用于中间分析的元数据存储。

如果您希望将元数据序列化为 ONNX proto,请写入 metadata_props

property metadata_props: dict[str, str]

张量的元数据属性。

元数据属性用于存储有关张量的附加信息。与 meta 不同,此属性被序列化为 ONNX 协议。

property name: str | None

张量的名称。

property nbytes: int

张量中的字节数。

numpy()[source]

将张量作为 numpy 数组返回。

返回类型:

ndarray

property raw: Callable[[], TensorProtocol]
property shape: Shape

张量的形状。不可变。

property size: int

张量中的元素数量。

tobytes()[source]

返回张量的字节。

返回类型:

bytes

tofile(file)[source]

将张量写入二进制文件。

此方法将张量的原始字节写入类文件对象。类文件对象必须具有接受字节的 write 方法。

在 0.1.11 版本中添加。

参数:

file – 具有接受字节的 write 方法的类文件对象。

返回类型: