tvm.relax.frontend
用于构建 Relax 程序的前端,以及模型导入器
- tvm.relax.frontend.detach_params(mod: IRModule) Tuple[IRModule, Dict[str, List[NDArray]]]
将输入 IRModule 函数中的 “params” 属性分离为单独的参数字典。
- 参数:
mod (tvm.IRModule) – 要分离其函数 “param” 属性的 IRModule。
- 返回:
detached_mod (tvm.IRModule) – 分离后的 IRModule。
params_dict (Dict[str, List[tvm.nd.NDArray]]) – 分离的参数。字典键对应于输入 IRModule 中具有 “params” 属性的函数的名称。
tvm.relax.frontend.nn
一个类似 PyTorch 的 API,用于构建 IRModule。
- class tvm.relax.frontend.nn.Effect
Effect 是一种特殊的非用户界面类型,用于表示具有副作用的操作,例如 print。它用于表示计算的输出。
- emit_init(name_hint: str, builder: BlockBuilder) List[DataflowVar]
发射 effect 的初始化。此方法由编译器调用以初始化 effect。
- class tvm.relax.frontend.nn.Module
神经网络组件的基类。子类化它可以构建您的模型。模块可以使用常规属性赋值在树结构中相互嵌套。
- named_parameters(prefix: str = '') Iterator[Tuple[str, Parameter]]
此方法提供了一个模块参数的迭代器,同时生成参数名称及其对应的值。
- 参数:
prefix (str) – 要添加到所有参数名称的前缀。
- 生成:
(str, Parameter) - 包含名称和参数的元组
- parameters() Iterator[Parameter]
此方法提供了一个模块参数的迭代器,仅生成 Parameter 值。
- 生成:
Parameter - 模块的参数
- state_dict(*, prefix: str = '', destination: Dict[str, Parameter] | None = None) Dict[str, Parameter]
返回一个字典,其中包含对模块整个状态的引用。
- load_state_dict(state_dict: Dict[str, Parameter], strict: bool = True) Tuple[List[str], List[str]]
此函数将参数和缓冲区从 state_dict 复制到当前模块及其后代。如果 strict 设置为 True,则 state_dict 中的键必须与此模块的 state_dict() 函数返回的键完全匹配。
- export_tvm(spec: _spec.ModuleSpecType, debug: bool = False, allow_extern: bool = False) Tuple[IRModule, List[Tuple[str, Parameter]]] | Tuple[IRModule, List[Tuple[str, Parameter]], List[ExternModule]]
将模块导出到 TVM IRModule 和参数
- 参数:
spec (_spec.ModuleSpecType) – 一个字典,将每个输入名称映射到一个规范,该规范定义了输入形状和 dtype。
debug (bool) – 如果设置为 True,则导出的模块将支持 effects。这使得在图中进行打印等操作成为可能。
- 返回:
irmodule (tvm.ir.IRModule) – 模型转换后的 tvm IR 表示形式。
params (List[Tuple[str, Parameter]]) – 与模型权重相对应的参数列表。
ext_mods (List[nn.ExternModule]) – 模型中使用的 ExternModule 列表。
- class tvm.relax.frontend.nn.ModuleList(modules: List[Module])
在列表中保存子模块。
- append(module: Module)
将模块添加到 ModuleList 的末尾
- forward(x)
模块的前馈传递
- class tvm.relax.frontend.nn.Object(*, _expr: RelaxExpr, _name: str)
relax.Expr 之上的包装器,其 struct_info 是基本 ObjectStructInfo(而不是其任何子类)。Object 有效地表示非张量前端组件,例如 KV 缓存。
- class tvm.relax.frontend.nn.Parameter(shape: Sequence[int | str | PrimExpr], dtype: str | None = None)
参数表示神经网络层的权重。它是一个特殊的张量,可以绑定或不绑定到具体值。如果参数绑定到具体值,则称为绑定参数,否则称为未绑定参数。
- class tvm.relax.frontend.nn.Tensor(*, _expr: RelaxExpr)
relax.Expr 之上的包装器,其 struct_info 是 TensorStructInfo,提供更方便的访问形状和 dtype 信息。Tensor 始终是符号化的,并且不绑定到任何具体值。形状和 dtype 推理在张量创建时立即完成,即当算子应用于张量时,形状和 dtype 信息已可用。
- static from_const(data) Tensor
从 numpy 常量构造张量。
- static from_struct_info(struct_info: TensorStructInfo, name: str = 'tensor') Tensor
从 relax TensorStructInfo 构造 nn.Tensor
- static placeholder(shape: Sequence[int | str | PrimExpr], dtype: str, name: str = 'tensor') Tensor
创建具有给定形状和 dtype 的占位符张量。在通常情况下,用户永远不应直接创建占位符张量,唯一的例外是指示外部函数的返回值形状/dtype。
如果 shape 是字符串名称,我们创建一个符号形状 tvm.tir.Var(name, “int64”)。
- tvm.relax.frontend.nn.add_extern(mod: ExternModule) None
向导出器添加一个外部模块。
- class tvm.relax.frontend.nn.ExternModule(symbols: Dict[str, Callable])
外部模块的抽象基类。外部模块旨在帮助将用户手工编写的内核合并到导出的 TVM IRModule 中。
- load() Module
将外部模块加载到 TVM 运行时模块中。
- class tvm.relax.frontend.nn.ObjectModule(symbols: Dict[str, Callable], filepath: Path)
nn.ExternModule 的子类,允许用户提供要链接到编译产物中的对象 .o 文件;
- load() Module
将外部模块加载到 TVM 运行时模块中。
- class tvm.relax.frontend.nn.SourceModule(symbols: Dict[str, Callable], source_code: str | Path, source_format: str, compile_options: List[str] | None = None, compiler: str | None = None, output_format: str = 'obj')
nn.ExternModule 的子类。它编译 C++/CUDA 源代码并将它们链接到最终的 IRModule 中。
形状/数据类型推断。 nn.ExternModule 系统要求用户提供额外的信息才能工作,即 symbols。它是一个字典,将外部目标文件中的每个符号映射到其形状/数据类型推断函数。考虑一个函数 my_func 接受两个张量的情况,形状为 (x, y, 1) 的 a 和形状为 (y, z, 5) 的 b,并生成形状为 (x, y, z, 9) 的张量 c,形状/数据类型推断函数应如下所示
def shape_dtype_inference(a, b): x, y, _ = a.shape _, z, _ = b.shape return nn.Tensor.placeholder((x, y, z, 9), dtype="float32")
并且 symbols 字典应提供为
symbols={ "my_func": shape_dtype_inference, }
调用约定。 所有外部模块现在都遵循 “目标传递风格”(DPS)调用约定,这意味着返回的张量已由系统预先分配,并作为外部函数的参数传入。
重用上面的例子,my_func 的实现应在其签名中包含三个参数,其中张量使用来自 DLPack 的 DLTensor 表示,DLPack 是张量内存表示的事实标准。更多详情:https://github.com/dmlc/dlpack/blob/v0.8/include/dlpack/dlpack.h#L163-L206。
为了暴露符号,保证 TVM_DLL_EXPORT_TYPED_FUNC(symbol, function) 可用
// those headers are guaranteed to be available #include <dlpack/dlpack.h> #include <tvm/runtime/data_type.h> #include <tvm/runtime/packed_func.h> namespace { // anonymous namespace hides the symbol `_my_func_impl` from other translation units int _my_func_impl(DLTensor* a, DLTensor* b, DLTensor* c) { // `a` and `b` are inputs, and `c` is the output } } // expose symbol `my_func` instead of `_my_func_impl` TVM_DLL_EXPORT_TYPED_FUNC(my_func, _my_func_impl);
编译器Pass `AttachExternModules`。 引入它是为了在编译管道的任何阶段将 nn.ExternModule 列表附加到 IRModule 中,并将编译后的外部模块作为 `runtime.Module` 附加到 IRModule 的 `external_mods` 属性中。 tvm.compile 链接需要它,但有了这个 pass 的存在,源代码编译可以推迟到 TVM 编译的任意阶段。
注意事项。 需要在 export_tvm 期间精确调用一次 nn.add_extern 来注册外部模块。每个符号应该只注册一次,以避免潜在的冲突,否则会引发错误。
- static tvm_home() Path
查找 TVM 的 home 目录。如果设置了 TVM_HOME 环境变量,则使用它。否则,使用安装 tvm Python 包的目录。作为健全性检查,要求具有 include 和 3rdparty 作为直接子目录。
- 返回:
tvm_home – TVM 的 home 目录,并保证具有 include 和 3rdparty 作为直接子目录。
- 返回类型:
- static get_includes(tvm_pkg: List[str] | None = None) List[Path]
根据 tvm_home() 返回默认的 include 路径。默认情况下,它包括 TVM、DLPack 和 DMLC-Core。如果提供了 tvm_pkg,它还包括 tvm_home/3rdparty 下指定的软件包。
- 参数:
tvm_pkg (可选[List[str]]) – 要包含在 tvm_home/3rdparty 下的软件包列表。每个元素都应该是 tvm_home/3rdparty 的相对路径。
- 返回:
includes – include 路径列表。
- 返回类型:
List[pathlib.Path]
- static get_compile_options(source_format: str, tvm_pkg: List[str] | None = None) List[str]
根据 source_format 返回默认的编译选项,包括相对于 tvm_home() 的默认 include 路径、配置 DMLC-Core 的默认标志,并且默认情况下,它使用 “-O3” 和 “-std=c++17”。
- load() Module
将外部模块加载到 TVM 运行时模块中。
- class tvm.relax.frontend.nn.GELU
用于 GELU 激活层的 relax.frontend.nn.Module。
- class tvm.relax.frontend.nn.Conv1D(in_channels: int, out_channels: int, kernel_size: int, stride: int = 1, padding: int = 0, dilation: int = 1, groups: int = 1, bias: bool = True, dtype: str | None = None)
用于 conv1d 层的 relax.frontend.nn.Module。
- class tvm.relax.frontend.nn.Conv2D(in_channels: int, out_channels: int, kernel_size: List[int] | int, stride: int = 1, padding: int = 0, dilation: int = 1, groups: int = 1, bias: bool = True, dtype: str | None = None, data_layout: str = 'NCHW')
用于 conv2d 层的 relax.frontend.nn.Module。
- class tvm.relax.frontend.nn.Conv3D(in_channels: int, out_channels: int, kernel_size: List[int] | int, stride: List[int] | int = 1, padding: List[int] | int = 0, dilation: int = 1, groups: int = 1, bias: bool = True, dtype: str | None = None, data_layout: str = 'NCDHW')
用于 conv3d 层的 relax.frontend.nn.Module。
- class tvm.relax.frontend.nn.ConvTranspose1D(in_channels: int, out_channels: int, kernel_size: int, stride: int = 1, padding: int = 0, output_padding: int = 0, dilation: int = 1, groups: int = 1, bias: bool = True, dtype: str | None = None)
用于 ConvTranspose1D 层的 relax.frontend.nn.Module。
- class tvm.relax.frontend.nn.Embedding(num: int | str | PrimExpr, dim: int | str | PrimExpr, dtype: str | None = None)
用于 embedding 层的 relax.frontend.nn.Module。
- class tvm.relax.frontend.nn.GroupNorm(num_groups: int, num_channels: int, eps: float = 1e-05, affine: bool = True, dtype: str | None = None)
用于 group norm 层的 relax.frontend.nn.Module。
- class tvm.relax.frontend.nn.IOEffect
对 IO 副作用进行建模,例如,在屏幕上打印 NDArray 的内容,插入调试断点等。
- emit_init(name_hint, builder: BlockBuilder) List[DataflowVar]
发射 effect 的初始化。此方法由编译器调用以初始化 effect。
- class tvm.relax.frontend.nn.KVCache(init_seq_len: int, unit_shape: Sequence[int], dtype: str | None = None)
用于实现 KVCache 的 Effect。
- emit_init(name_hint: str, bb: BlockBuilder)
发出 KVCache effect 的初始化。
- 参数:
name_hint (str) – 初始化绑定的 Var 的名称提示。
bb (relax.BlockBuilder) – 要发出的 relax BlockBuilder。
- finalize() List[Var]
将 KVCache effect 最终确定为 relax.Function 的隐式返回值。
- 返回:
ret – 作为 KVCache 的输出 relax.Var。
- 返回类型:
List[rx.Var]
- to(dtype: str | None = None) None
将 KVCache effect 转换为特定的 dtype。
- 参数:
dtype (Optional[str]) – 要转换的目标数据类型。
- view(seq_len: Var) Tensor
查看 KVCache 中的最后一个元素。
- class tvm.relax.frontend.nn.LayerNorm(normalized_shape: int, eps: float | None = 1e-05, elementwise_affine: bool = True, dtype: str | None = None)
用于 Layer Normalization 的 relax.frontend.nn.Module
- class tvm.relax.frontend.nn.Linear(in_features: int | str | PrimExpr, out_features: int | str | PrimExpr, bias: bool = True, dtype: str | None = None, out_dtype: str | None = None)
用于 linear 层的 relax.frontend.nn.Module。
- forward(x: Tensor) Tensor
linear 层的前向方法。
- class tvm.relax.frontend.nn.ReLU
用于 ReLU 激活层的 relax.frontend.nn.Module。
- class tvm.relax.frontend.nn.RMSNorm(hidden_size: int, axes: int | List[int], epsilon: float = 1e-05, bias: bool = True, dtype: str | None = None)
用于 rms norm 层的 relax.frontend.nn.Module。
- class tvm.relax.frontend.nn.SiLU
用于 SiLU 激活层的 relax.frontend.nn.Module。
- class tvm.relax.frontend.nn.SubroutineMixin
生成一个 mixin
包含 tvm.relax.frontend.nn.Module 和 tvm.relax.testing.nn.Module 的通用逻辑。
- class tvm.relax.frontend.nn.Mutator
用于 nn.Module 转换的 mutator。用户可以重写 visit_* 方法以在不同的结构中应用转换,甚至可以重写 visit 方法来更改遍历的逻辑。
- class tvm.relax.frontend.nn.TypeVar(name, *constraints, bound=None, covariant=False, contravariant=False)
类型变量。
用法
T = TypeVar('T') # Can be anything A = TypeVar('A', str, bytes) # Must be str or bytes
类型变量的存在主要是为了静态类型检查器的好处。它们充当泛型类型的参数以及泛型函数定义的参数。有关泛型类型的更多信息,请参见 Generic 类。泛型函数的工作方式如下
- def repeat(x: T, n: int) -> List[T]
‘’’返回一个包含对 x 的 n 个引用的列表。’’’ return [x]*n
- def longest(x: A, y: A) -> A
‘’’返回两个字符串中最长的一个。’’’ return x if len(x) >= len(y) else y
后一个示例的签名本质上是 (str, str) -> str 和 (bytes, bytes) -> bytes 的重载。另请注意,如果参数是 str 的某些子类的实例,则返回类型仍然是普通的 str。
在运行时,isinstance(x, T) 和 issubclass(C, T) 将引发 TypeError。
使用 covariant=True 或 contravariant=True 定义的类型变量可用于声明协变或逆变泛型类型。有关更多详细信息,请参见 PEP 484。默认情况下,泛型类型在所有类型变量中都是不变的。
类型变量可以进行内省。例如:
T.__name__ == ‘T’ T.__constraints__ == () T.__covariant__ == False T.__contravariant__ = False A.__constraints__ == (str, bytes)
请注意,只有在全局范围内定义的类型变量才能被 pickle。
- tvm.relax.frontend.nn.add(a: Tensor, b: Tensor, name: str = 'add') Tensor
使用 numpy 风格广播的加法。
示例
c = add(a, b)
- tvm.relax.frontend.nn.argsort(data: Tensor, axis: int = -1, descending: bool = False, dtype: str = 'int32', name='argsort')
沿给定轴执行排序,并返回一个索引数组,该数组的形状与输入数组相同,该数组按排序顺序索引数据。
- tvm.relax.frontend.nn.broadcast_to(x: Tensor, shape: Sequence[int | PrimExpr], name: str = 'broadcast_to') Tensor
将张量广播到指定的形状。
- tvm.relax.frontend.nn.ccl_allgather(x: Tensor, num_workers: int, name='ccl_allgather')
CCL Allgather 运算符
- tvm.relax.frontend.nn.ccl_allreduce(x: Tensor, op_type: str = 'sum', in_group: bool = True, name='ccl_allreduce')
CCL Allreduce 算子
- tvm.relax.frontend.nn.ccl_broadcast_from_worker0(x: Tensor, name='broadcast_from_worker')
将数据从 worker-0 广播到所有其他 worker。
- tvm.relax.frontend.nn.chunk(x: Tensor, chunks: int, dim: int = 0, name: str = 'chunk') Tensor
沿维度 dim 将张量拆分为指定数量的块。
- tvm.relax.frontend.nn.conv1d(x: Tensor, weight: Tensor, bias: Tensor | None = None, stride: int | Tuple | None = 1, padding: int | Tuple | str | None = 0, dilation: int | Tuple | None = 1, groups: int | None = 1, name: str = 'conv1d') Tensor
1D 卷积。
此算子将权重作为 1D 卷积核,并将其与数据卷积以产生输出。
在默认情况下,当 data_layout 为 NCW,kernel_layout 为 OIW 时,conv1d 接收形状为 (batch_size, in_channels, width) 的数据张量和形状为 (channels, in_channels, kernel_w) 的权重张量,其中 kernel_w 是 W 核维度的长度,以生成具有以下规则的输出张量
\[\mbox{out}[b, c, x] = \sum_{dx, k} \mbox{data}[b, k, \mbox{strides} * x + dx] * \mbox{weight}[c, k, dx]\]在计算之前,填充和空洞分别应用于数据和权重。此算子接受数据布局规范。从语义上讲,该算子会将布局转换为规范布局(数据为 NCW,权重为 OIW),执行计算,然后转换为 out_layout。
- 参数:
- 返回:
result – 计算结果。
- 返回类型:
- tvm.relax.frontend.nn.conv1d_transpose(x: Tensor, weight: Tensor, bias: Tensor | None = None, stride: int | Tuple[int] | None = 1, padding: int | Tuple[int, ...] | None = 0, output_padding: int | Tuple[int] | None = 0, dilation: int | Tuple | None = 1, groups: int | None = 1, name: str = 'conv1d_transpose') Tensor
1D 转置卷积算子。
此算子可以看作是 conv1d 的梯度算子。
在 data_layout == “NCW” 和 kernel_layout == “IOW” 的简单情况下,可以解释输出形状。假设 data 的形状为 (N, in_channel, in_w),weight 的形状为 (in_channel, out_channel, weight_w),我们需要确保 in_channel % groups == 0。输出的形状将为 (N, out_channel * groups, out_w),其中
out_w = ((in_w - 1) * strides[0] + weight_w - 2 * padding[0] + output_padding[0])
- 参数:
data (Tensor) – 算子的输入数据。
weight (Tensor) – 权重张量。
padding (Union[int, Tuple[int, ...]]) – 卷积在输入两侧的填充。需要长度为 1 或 2。
output_padding (Union[int, Tuple[int, ...]], optional) – 用于消除输出形状的歧义。
groups (int) – 将输入拆分为组卷积的组数。输入和输出通道数应可被组数整除。
data_layout (str) – 输入的布局。
kernel_layout (str) – 权重的布局。
out_layout (Optional[str]) – 输出的布局。如果未指定,则与 data_layout 相同
out_dtype (Optional[Union[str, DataType]]) – 指定混合精度 conv2d 的输出数据类型。
- 返回:
result – 计算结果。
- 返回类型:
- tvm.relax.frontend.nn.conv2d(x: Tensor, weight: Tensor, bias: Tensor | None = None, stride: int | Tuple | None = 1, padding: int | Tuple | str | None = 0, dilation: int | Tuple | None = 1, groups: int | None = 1, data_layout: str | None = 'NCHW', name: str = 'conv2d') Tensor
对由多个输入平面组成的输入图像应用 2D 卷积
- 参数:
x (Tensor) – 形状为 [B, N, H, W] 的输入张量
weight (Tensor) – 形状为 [O, N/groups, kH, kW] 的滤波器
bias (Optional[Tensor]) – 可选的偏置张量,形状为 [O]。
stride (Optional[Union[int, Tuple]]) – 卷积核的步幅。可以是单个数字或 (sH, sW) 元组。
dilation (Optional[Union[int, Tuple]]) – 核元素之间的间距。可以是单个数字或 (dH, dW) 元组。
groups (Optional[int]) – 将输入拆分为多个组。
data_layout (Optional[str]) – 输入和输出数据的布局。
name (str) – 名称提示。
- 返回:
result – 计算结果,形状为 [B, O, oH, oW]。
- 返回类型:
- tvm.relax.frontend.nn.conv3d(x: Tensor, weight: Tensor, bias: Tensor | None = None, stride: int | Tuple | None = 1, padding: int | Tuple | str | None = 0, dilation: int | Tuple | None = 1, groups: int | None = 1, data_layout: str | None = 'NCDHW', name: str = 'conv3d') Tensor
对由多个输入平面组成的输入图像应用 3D 卷积
- 参数:
x (Tensor) – 形状为 [B, N, D, H, W] 的输入张量
weight (Tensor) – 形状为 [O, N/groups, kD, kH, kW] 的滤波器
bias (Optional[Tensor]) – 可选的偏置张量,形状为 [O]。
stride (Optional[Union[int, Tuple]]) – 卷积核的步长。 可以是单个数字或 (sD, sH, sW) 元组。
dilation (Optional[Union[int, Tuple]]) – 内核元素之间的间距。 可以是单个数字或 (dD, dH, dW) 元组。
groups (Optional[int]) – 将输入拆分为多个组。
data_layout (Optional[str]) – 输入和输出数据的可选布局。
name (str) – 名称提示。
- 返回:
result – 计算结果,形状为 [B, O, oD, oH, oW]。
- 返回类型:
- tvm.relax.frontend.nn.cumsum(data: Tensor, axis: int | None = None, dtype: str | None = None, exclusive: bool | None = None, name: str = 'cumsum') Tensor
Numpy 风格的 cumsum 运算。 返回给定轴上元素的累积包含和。
- 参数:
- 返回:
result – 结果的大小与数据相同,如果轴不是 None,则形状与数据相同。 如果轴为 None,则结果是一个 1 维数组。
- 返回类型:
示例
a = [[1, 2, 3], [4, 5, 6]] cumsum(a) # if axis is not provided, cumsum is done over the flattened input. -> [ 1, 3, 6, 10, 15, 21] cumsum(a, dtype="float32") -> [ 1., 3., 6., 10., 15., 21.] cumsum(a, axis=0) # sum over rows for each of the 3 columns -> [[1, 2, 3], [5, 7, 9]] cumsum(a, axis=1) -> [[ 1, 3, 6], [ 4, 9, 15]] a = [1, 0, 1, 0, 1, 1, 0] # a is a boolean array cumsum(a, dtype=int32) # dtype should be provided to get the expected results -> [1, 1, 2, 2, 3, 4, 4]
- tvm.relax.frontend.nn.debug_func(name: str, *args: Tensor | PrimExpr | int | float | str, _line_info: str | None = None)
在运行时 relax.Call 一个调试函数。 调试函数必须使用以下类型签名注册
@tvm.register_func(name_of_debug_func) def debug_func(lineno: str, arg_0, arg_1, ...) -> None: ...
- tvm.relax.frontend.nn.divide(a: Tensor, b: Tensor, name: str = 'divide') Tensor
具有 numpy 风格广播的除法。
示例
c = divide(a, b)
- tvm.relax.frontend.nn.empty(shape: Sequence[int | PrimExpr], dtype: str = 'float32', name: str = 'empty') Tensor
构造一个未初始化的张量,具有输入形状和 dtype。
- tvm.relax.frontend.nn.equal(a: Tensor, b: Tensor, name: str = 'equal') Tensor
用于 (lhs == rhs) 的广播元素级比较。
- tvm.relax.frontend.nn.exp(x: Tensor, name: str = 'exp') Tensor
应用指数函数。
\[\text{Exp}(x) = e^x\]注意
输入张量需要具有浮点 dtype
- tvm.relax.frontend.nn.extern(name: str, args: Sequence[Tensor | PrimExpr | int | float | str], out: OutType) OutType
在运行时调用外部函数。 外部函数必须使用 TVM_REGISTER_GLOBAL (C++) 或 tvm.register_func (Python) 在 “ TVM 运行时注册。
- tvm.relax.frontend.nn.full(shape: Sequence[int | PrimExpr], fill_value: Tensor, dtype: str = 'float32', name: str = 'full') Tensor
用标量值填充数组。
- tvm.relax.frontend.nn.gelu(x: Tensor, approximate: str | None = None, name: str = 'gelu') Tensor
应用高斯误差线性单元函数
\[\text{GeLU}(x) = 0.5 * x * (1 + \text{erf}(x * 0.5**0.5))\]其中 \(erf\) 是高斯误差函数。
- 参数:
- 返回:
result – 计算结果。
- 返回类型:
注意
输入张量需要具有浮点 dtype
- tvm.relax.frontend.nn.get_default_dtype() str
获取未指定时的默认参数 dtype。 默认情况下为 float32。
- 返回:
dtype – 默认 dtype
- 返回类型:
- tvm.relax.frontend.nn.get_timestep_embedding(x: Tensor, embedding_dim: int, flip_sin_to_cos: bool = False, downscale_freq_shift: float = 1, scale: float = 1, max_period: int = 10000, name: str = 'get_timestep_embedding') Tensor
时间步计算,如《Denoising Diffusion Probabilistic Models》中所述。
- tvm.relax.frontend.nn.greater(a: Tensor, b: Tensor, name: str = 'greater') Tensor
用于 (lhs > rhs) 的广播元素级比较。
- tvm.relax.frontend.nn.greater_equal(a: Tensor, b: Tensor, name: str = 'greater_equal') Tensor
用于 (lhs >= rhs) 的广播元素级比较。
- tvm.relax.frontend.nn.group_norm(x: Tensor, num_groups: int, weight: Tensor | None, bias: Tensor | None, eps: float = 1e-05, channel_axis: int = 1, axes: List[int] | None = None, name: str = 'group_norm') Tensor
对小批量输入应用组归一化,如论文 Group Normalization 中所述
\[y = \frac{x - \mathrm{E}[x]}{ \sqrt{\mathrm{relax.Var}[x] + \epsilon}} * \gamma + \beta\]
- tvm.relax.frontend.nn.interpolate(x: Tensor, size: int | Tuple[int] | None = None, scale_factor: float | Tuple[float] | None = None, mode: str = 'nearest', align_corners: bool | None = None, recompute_scale_factor: bool | None = None, antialias: bool | None = None, data_layout: str | None = 'NCHW', name: str = 'interpolate')
使用指定的模式调整张量大小。
- 参数:
x (Tensor) – 要调整大小的输入张量。
size (Optional[Union[int, Tuple[int]]]) – 请求的输出大小,size 和 scale_factor 只能指定一个。
scale_factor (Optional[Union[float, Tuple[float]]]) – 空间大小的乘数。
mode (str) – 用于采样的算法。
align_corners (Optional[bool]) – 如何映射采样前后的像素。
recompute_scale_factor (Optional[bool]) – 重新计算用于插值的 scale_factor。
antialias (Optional[bool]) – 对输出应用抗锯齿。
data_layout (Optional[str]) – 输入和输出数据的布局。
name (str) – 此操作的名称提示。
- 返回:
result – 具有请求形状的输出张量。
- 返回类型:
- tvm.relax.frontend.nn.layer_norm(x: Tensor, normalized_shape: int | List[int], weight: Tensor | None = None, bias: Tensor | None = None, eps: float = 1e-05, name: str = 'layer_norm') Tensor
层归一化 (Lei Ba 等人,2016)。对 n 维输入数组应用层归一化。此运算符接受 n 维输入数组,并使用给定轴对输入进行归一化
\[out = \frac{data - mean(data, axis)}{\sqrt{var(data, axis)+\epsilon}} * gamma + beta\]与批归一化不同,均值和方差是沿通道维度计算的。
假设输入在轴 1 上的大小为 k,则 gamma 和 beta 的形状均为 (k,)。
注意
此运算符可以在推理时被优化掉。
- tvm.relax.frontend.nn.less(a: Tensor, b: Tensor, name: str = 'less') Tensor
广播元素级比较 (lhs < rhs)。
- tvm.relax.frontend.nn.less_equal(a: Tensor, b: Tensor, name: str = 'less_equal') Tensor
广播元素级比较 (lhs <= rhs)。
- tvm.relax.frontend.nn.matmul(a: Tensor, b: Tensor, out_dtype: str | None = None, name: str = 'matmul') Tensor
两个张量的通用矩阵乘法,在批次维度上进行广播。
语义和输出形状推导规则在 https://data-apis.org/array-api/latest/API_specification/generated/array_api.matmul.html 中指定。
- 参数:
- 返回:
result – 计算结果。
- 返回类型:
示例
c = matmul(a, b)
- tvm.relax.frontend.nn.maximum(x1: Tensor, x2: Tensor, name: str = 'maximum')
元素级最大值
- 参数:
- 返回:
result – 计算结果。
- 返回类型:
示例
c = maximum(a, b)
- tvm.relax.frontend.nn.minimum(x1: Tensor, x2: Tensor, name: str = 'minimum')
元素级最小值
- 参数:
- 返回:
result – 计算结果。
- 返回类型:
示例
c = minimum(a, b)
- tvm.relax.frontend.nn.multinomial_from_uniform(prob: Tensor, uniform_sample: Tensor, sample_indices: Tensor | None = None, dtype: str = 'int64', name: str = 'multinomial_from_uniform')
返回一个张量,其中每行包含从张量 prob 的相应行中的多项概率分布中采样的索引。
注释
为了获得更好的 CPU 性能,请使用 ‘vm.builtin.multinomial_from_uniform’。为了获得准确的结果,请确保概率介于 0 和 1 之间,并且总和为 1。
- 参数:
prob (Tensor) – 形状为 (batch, vocab_size) 的 2-D 张量,表示概率分布。每一行都是一个批次的词汇表分布,其中:值范围为 [0, 1],表示每个词汇项的概率。每行中值的总和为 1,形成有效的分布。
uniform_sample (Tensor) – 均匀采样的 2-D 张量,形状为 (n, 1)。值范围为 0 到 1,表示均匀采样的概率。
sample_indices (Optional[Tensor]) – 形状为 [n, 1] 的 2-D 张量,指示要从中采样的特定概率分布。 sample_indices[i] 的值确定第 i 个 token 应从第 sample_indices[i] 个概率分布中采样。例如,如果有 3 个不同的概率分布,并且要求从每个分布中采样 2、3 和 4 个 token,则 sample_indices 将为 [0, 0, 1, 1, 1, 2, 2, 2, 2]。
dtype (str) – 输出张量的数据类型。
- 返回:
result – 计算出的张量,形状为 (n, 1)。
- 返回类型:
示例
prob = [[0.2, 0.3, 0.5], [0.3, 0.4, 0.3]] usample = [[0.4], [0.9]] sample_indices = [[0], [1]] multinomial_from_uniform(prob, usample) -> [[1], [2]] multinomial_from_uniform(prob, usample, sample_indices) -> [[1], [2]]
- tvm.relax.frontend.nn.multiply(a: Tensor, b: Tensor, name: str = 'mul') Tensor
具有 numpy 风格广播的乘法。
示例
c = multiply(a, b)
- tvm.relax.frontend.nn.negative(x: Tensor, name: str = 'neg') Tensor
输入张量的数值负数。
- tvm.relax.frontend.nn.not_equal(a: Tensor, b: Tensor, name: str = 'not_equal') Tensor
广播元素级比较 (lhs != rhs)。
- tvm.relax.frontend.nn.ones(shape: Sequence[int | PrimExpr], dtype: str = 'float32', name: str = 'ones') Tensor
构造一个全为零的张量,具有输入的形状和 dtype。
- tvm.relax.frontend.nn.pad(x: Tensor, pad: List[int], mode: str = 'constant', value: float = 0.0, name: str = 'pad') Tensor
对输入张量应用空间填充。
- tvm.relax.frontend.nn.permute(x: Tensor, axes: List[int] | None, name: str = 'permute') Tensor
置换输入张量的维度。
- tvm.relax.frontend.nn.permute_dims(x: Tensor, axes: List[int] | None = None, name: str = None) Tensor
置换数组的维度。
- tvm.relax.frontend.nn.print_(tensor: Tensor)
运行时调试打印 Tensor。
- tvm.relax.frontend.nn.relu(x: Tensor, name: str = 'relu') Tensor
整流线性单元 (ReLU) 激活函数。
\[ext{ReLU}(x) = ext{max}(x, 0)\]
- tvm.relax.frontend.nn.renormalize_top_p_top_k_prob(prob, sorted_prob, top_p, top_k)
在使用 top_p 和 top_k 进行过滤后,重新归一化概率,确保它们总和为 1。
注释
为了获得准确的结果,请确保概率介于 0 和 1 之间,并且总和为 1。
- tvm.relax.frontend.nn.repeat(x: Tensor, repeats: int, axis: int | None = None, name='repeat') Tensor
重复数组中的元素。
- 参数:
- 返回:
ret – 计算结果。
- 返回类型:
示例
np_x = numpy.array([[1, 2], [3, 4]]) x = Tensor.from_const(np_x) lv1 = repeat(x, repeats=2) # lv1 == [1, 1, 2, 2, 3, 3, 4, 4] lv2 = repeat(x, repeats=2, axis=1) # lv2 == [[1., 1., 2., 2.], # [3., 3., 4., 4.]]
- tvm.relax.frontend.nn.reshape(x: Tensor, shape: Sequence[int | PrimExpr], name='reshape') Tensor
重塑输入数组。
-1
通过使用输入维度的剩余部分来推断输出形状的维度,同时保持新数组的大小与输入数组相同。形状的维度最多可以有一个为 -1。x.shape = (2, 3, 4), shape = (6, 1, -1), result.shape = (6, 1, 4) x.shape = (2, 3, 4), shape = (3, -1, 8), result.shape = (3, 1, 8) x.shape = (2, 3, 4), shape = (-1,), result.shape = (24,)
- 参数:
- 返回:
result – 重塑后的结果。
- 返回类型:
注意
-1
推断仅在编译时执行。也就是说,在任何情况下,如果无法在编译时推断出-1
的维度长度,则会抛出错误。
- tvm.relax.frontend.nn.rms_norm(x: Tensor, weight: Tensor, axes: int | List[int], epsilon: float = 1e-05, name: str = 'rms_norm') Tensor
均方根归一化(Biao Zhang 等人,2019)。将均方根归一化应用于 n 维输入数组。此运算符接受 n 维输入数组,并使用给定的轴对输入进行归一化
\[out = \frac{data}{\sqrt{mean(data, axis)+\epsilon}} * weight\]
- tvm.relax.frontend.nn.sample_top_p_top_k_from_sorted_prob(sorted_prob: Tensor, sorted_index: Tensor, top_p: Tensor, top_k: Tensor, uniform_sample: Tensor, sample_indices: Tensor | None = None)
基于 top_p 和 top_k 标准,从已排序的概率张量中采样索引。
注释
为了获得准确的结果,请确保概率介于 0 和 1 之间,并且总和为 1。
- 参数:
sorted_prob (Tensor) – 一个 2-D 张量,形状为 (batch, vocab_size),包含按降序排列的概率。
sorted_index (Tensor) – 索引张量,形状为 (batch, vocab_size),对应于 sorted_prob。可能来自对原始概率张量应用降序 argsort。
top_p (Tensor) – 累积概率阈值,形状为 (batch, 1),用于 nucleus 采样。
top_k (Tensor) – 形状为 (batch, 1) 的张量,表示要考虑进行 top-k 采样的顶部概率的数量。
uniform_sample (Tensor) – 均匀采样的值,形状为 (n, 1),用于选择输出索引。
sample_indices (Optional[Tensor]) – 形状为 [n, 1] 的 2-D 张量,指示要从中采样的特定概率分布。 sample_indices[i] 的值确定第 i 个 token 应从第 sample_indices[i] 个概率分布中采样。例如,如果有 3 个不同的概率分布,并且要求从每个分布中采样 2、3 和 4 个 token,则 sample_indices 将为 [0, 0, 1, 1, 1, 2, 2, 2, 2]。
- 返回:
result – 选定的索引,形状为 (n, 1)。
- 返回类型:
示例
prob = [[0.1 , 0.4, 0.5], [0.3, 0.3, 0.4]] sorted_prob = [[0.5, 0.4, 0.1], [0.4, 0.3, 0.3]] sorted_index = [[2, 1, 0], [2, 0, 1]] top_p = [[0.6],[0.9]] top_k = [[3],[2]] uniform_sample = [[0.5], [0.6]] sample_indices = [[0], [1]] sample_top_p_top_k_from_sorted_prob( sorted_prob, sorted_index,top_p, top_k, uniform_sample, sample_indices) -> [2, 0]
- tvm.relax.frontend.nn.scaled_dot_product_attention(query: Tensor, key: Tensor, value: Tensor, attn_mask: Tensor | None = None, is_causal: bool | None = False, scale: float | None = None, name: str = 'scaled_dot_product_attention')
在提供的注意力查询、键和值上计算缩放的点积注意力。符合功能性 torch 实现。
- 参数:
query (Tensor) – 张量,表示形状为 [batch, seq_len, num_heads, head_size] 的当前注意力查找。
key (Tensor) – 张量,表示形状为 [batch, seq_len_kv, num_heads_kv, head_size] 的交叉注意力映射。
value (Tensor) – 张量,表示形状为 [batch, seq_len_kv, num_heads_kv, head_size_value] 的嵌入式注意力值。
attn_mask (Optional[Tensor]) – 注意力的可选掩码,尚不支持。
is_causal (Optional[bool]) – 如果设置,则使用因果注意力掩码。
scale (Optional[float]) – 应用于注意力的可选额外缩放参数。
name (str) – 此函数的名称提示。
- tvm.relax.frontend.nn.sigmoid(x: Tensor, name: str = 'sigmoid') Tensor
计算 sigmoid 函数。
\[\text{sigmoid}(x) = \frac{1}{1 + \exp(-x)}\]注意
输入张量需要具有浮点 dtype
- tvm.relax.frontend.nn.silu(x: Tensor, name: str = 'silu') Tensor
Sigmoid 线性单元函数
\[\text{SiLU}(x) = x * \text{sigmoid}(x)\]注意
输入张量需要具有浮点 dtype
- tvm.relax.frontend.nn.softmax(x: Tensor, axis: int = -1, name: str = 'softmax') Tensor
计算 softmax 函数。
\[\text{softmax}(x)_i = \frac{\exp(x_i)}{\sum_j \exp(x_j)}\]- 参数:
- 返回:
result – 计算结果。
- 返回类型:
注意
输入张量需要具有浮点 dtype
- tvm.relax.frontend.nn.sort(x: Tensor, axis: int = -1, descending: bool = False, name='sort')
沿给定轴执行排序,并返回排序后的数组。
- tvm.relax.frontend.nn.split(ary: Tensor, indices_or_sections: int | Sequence[int], axis: int = 0, name: str = 'split') Tuple[Tensor, ...]
将数组拆分为多个子数组。
- tvm.relax.frontend.nn.sqrt(x: Tensor, name: str = 'sqrt') Tensor
计算输入张量的逐元素平方根。
注意
输入张量需要具有浮点 dtype
- tvm.relax.frontend.nn.square(x: Tensor, name: str = 'square') Tensor
计算输入张量的逐元素平方。
- tvm.relax.frontend.nn.subtract(a: Tensor, b: Tensor, name: str = 'subtract') Tensor
使用 numpy 风格广播进行减法运算。
示例
c = subtract(a, b)
- tvm.relax.frontend.nn.sum(x: Tensor, axis: int | List[int] | None = None, keepdims: bool = False, name: str = 'sum') Tensor
计算给定轴上张量元素的总和。
- tvm.relax.frontend.nn.take(x: Tensor, indices: Tensor, axis: int | None = None, name='take') Tensor
沿轴从张量中提取元素。它的语义主要类似于 numpy.take (https://numpy.com.cn/doc/stable/reference/generated/numpy.take.html),它可以涵盖 torch.take (https://pytorch.ac.cn/docs/stable/generated/torch.take.html) 和 onnx.gather (https://github.com/onnx/onnx/blob/main/docs/Changelog.md#Gather-13)。
- tvm.relax.frontend.nn.tanh(x: Tensor, name: str = 'tanh') Tensor
应用双曲正切函数。
\[\text{Tanh}(x) = \frac{e^x - e^{-x}}{e^x + e^{-x}}\]注意
输入张量需要具有浮点 dtype
- tvm.relax.frontend.nn.tensor_expr_op(tensor_expr_func: Callable, name_hint: str, args: List[Tensor | Var | int], *, attrs: Dict[str, Any] | None = None)
使用 te 构建给定的 tensor_expr_func。
- tvm.relax.frontend.nn.tensor_ir_inplace_op(func: PrimFunc, name_hint: str, args: Tensor | Sequence[Tensor | ShapeExpr | PrimExpr], inplace_indices: int | List[int], out: OutType) OutType
使用给定的 PrimFunc 创建 call_tir_inplace 绑定
- 参数:
func (_tir.PrimFunc) – 要调用的 PrimFunc。
name_hint (str) – 名称提示。
args (Union[Tensor, Sequence[Union[Tensor, rx.ShapeExpr, _tir.PrimExpr]]]) – 传递给 PrimFunc 的参数。
inplace_indices (Union[int, List[int]]) – 指定哪些参数应用于原地计算。如果 inplace_indices 是单个整数,它将被转换为单例列表。假设 inplace_indices[i] = j,其中 j >= 0。那么第 i 个输出将是 args[j] 的别名。如果 inplace_indices[i] = -1,那么第 i 个输出将是新分配的张量。 inplace_indices 中至少有一个成员不能为 -1。
- 返回:
result – 结果张量
- 返回类型:
- tvm.relax.frontend.nn.tensor_ir_op(func: PrimFunc, name_hint: str, args: Tensor | Sequence[Tensor | ShapeExpr | PrimExpr], out: OutType) OutType
使用给定的 PrimFunc 创建 call_tir 绑定。
- tvm.relax.frontend.nn.topk(data: Tensor, k: int = 1, axis: int = -1, ret_type: str = 'both', largest: bool = True, dtype: str = 'int32', name: str = 'topk')
获取给定轴上输入张量中的前 k 个元素。
ret_type 指定返回类型,可以是 (“both”, “values”, “indices”) 之一。
- 参数:
data (Tensor) – 输入数据张量。
k (int) – 要选择的顶部元素的数量。如果 k < 1,则返回所有元素。
axis (int) – 用于对输入张量进行排序的轴。
ret_type (str) – 返回类型 [both, values, indices]。 “both”:同时返回前 k 个数据和索引。“values”:仅返回前 k 个数据。“indices”:仅返回前 k 个索引。
largest (bool) – 是否返回最大或最小元素。如果 largest 为 False,则返回 k 个最小元素。
dtype (str) – 索引输出的数据类型。
name (str) – 名称提示。
- 返回:
out – 计算结果。
- 返回类型:
- tvm.relax.frontend.nn.triu(x: Tensor, diagonal: int = 0, name: str = 'triu') Tensor
返回矩阵或一批矩阵的上三角部分。
- tvm.relax.frontend.nn.where(condition: Tensor, x1: Tensor, x2: Tensor, name: str = 'where') Tensor
根据条件的值从输入张量中选择元素。
对于给定的位置,如果 condition 为 True,则返回 x1 中的对应值,否则返回 x2 中的对应值。
tvm.relax.frontend.onnx
用于将 ONNX 图形转换为 Relax 图形的工具。
- tvm.relax.frontend.onnx.from_onnx(model: GraphProto, shape_dict: Dict[str, List] | None = None, dtype_dict: str | Dict)[str, str] | None = 'float32', opset: int | None = None, keep_params_in_input: bool = False, sanitize_input_names: bool = True) IRModule
将 ONNX 模型转换为等效的 Relax 函数。 ONNX 图形表示为 Python Protobuf 对象。
当前的实现假定输入模型是 ONNX v1.1.0 之后的版本。
- 参数:
model (protobuf object) – ONNX v1.1.0 之后的 ONNX ModelProto
shape_dict (dict of str to tuple, optional) – 图形的输入形状
opset (int, optional) – 覆盖自动检测到的 opset。这对于某些测试可能很有用。
keep_params_in_input (bool) – 如果为 True,参数将被视为输入变量。如果为 false,参数将被视为常量并直接折叠到图中。
sanitize_input_names (bool, optional) – 是否清理输入名称以确保它们是有效的 Relax 标识符。
- 返回:
mod – 用于编译的 relax 模块
- 返回类型:
tvm.IRModule
tvm.relax.frontend.stablehlo
StableHLO 前端,用于构建 Relax 程序,带有模型导入器
tvm.relax.frontend.torch
PyTorch 前端,用于构建 Relax 程序,带有模型导入器
- tvm.relax.frontend.torch.from_exported_program(exported_program: ExportedProgram, *, keep_params_as_input: bool = False, unwrap_unit_return_tuple: bool = False, no_bind_return_tuple: bool = False) IRModule
将 PyTorch ExportedProgram 转换为 Relax 程序
- 参数:
- 返回:
output – 导入结果 IRModule,其中函数 “main” 包含翻译后的逻辑。
- 返回类型:
tvm.IRModule
示例
用户可以使用 torch.export.export() 从 PyTorch 模型中提取 torch.export.ExportedProgram。以下代码展示了如何将 PyTorch 模型转换为 Relax 程序。
# Import the importer. import tvm from tvm.relax.frontend.torch import from_exported_program import torch from torch.export import export # Define the module class MyModule(torch.nn.Module): def __init__(self): super().__init__() self.linear = torch.nn.Linear(in_features=10, out_features=7, bias=True) def forward(self, input): return self.linear(input) # Instantiate the model and create the input info dict. torch_model = MyModule() # Use torch.export.export() to convert the PyTorch model into ExportedProgram. example_args = (torch.rand(128, 10, dtype=torch.float32),) exported_program = export(torch_model, args=example_args) # Use the importer to import the ExportedProgram to Relax. mod: tvm.IRModule = from_exported_program(exported_program)
- tvm.relax.frontend.torch.from_fx(model, input_info: List[Tuple)[Tuple[int], str]], *, keep_params_as_input: bool = False, unwrap_unit_return_tuple: bool = False, no_bind_return_tuple: bool = False, custom_convert_map: dict | None = None) IRModule
将 PyTorch FX GraphModule 转换为 Relax 程序
- 参数:
model (fx.GraphModule) – 要转换的 PyTorch FX GraphModule。
keep_params_as_input (bool) – 是否将模型参数保留为输入变量。
unwrap_unit_return_tuple (bool) – 一个布尔标志,指示当返回值为单元组时是否解包。当返回值不是单元组时,不会进行解包。
no_bind_return_tuple (bool) – 一个布尔标志,指示是否将返回元组绑定为 relax 变量。如果该标志为 true 且返回值是元组,则不会将其绑定到变量。
custom_convert_map (Dictionary of str to Relax op) – 与 TorchFXImporter.convert_map 格式相同的自定义 op 转换映射
- 返回:
output – 导入结果 IRModule,其中函数 “main” 包含翻译后的逻辑。如果 keep_params_as_input 为 true,“main” 函数将具有一个属性 “params”,其中包含输入模型的权重。可以使用 relax.frontend.detach_params 分离权重。
- 返回类型:
tvm.IRModule
示例
用户可以使用 FX tracer 或 dynamo.export() 从 PyTorch 模型中提取 fx.GraphModule。以下代码展示了如何将 PyTorch 模型转换为 Relax 程序。
# Import the importer. import numpy as np import torch from tvm.relax.frontend.torch_fx import from_fx from torch import _dynamo as dynamo # Define the module class MyModule(torch.nn.Module): def __init__(self): super().__init__() self.linear = torch.nn.Linear(in_features=10, out_features=7, bias=True) def forward(self, input): return self.linear(input) # Instantiate the model and create the input info dict. torch_model = MyModule() input_info = [((128, 10), "float32")] input_tensors = [ torch.astensor(np.random.randn(*shape).astype(dtype)) for shape, dtype in input_info ] # Use FX tracer to trace the PyTorch model. graph_module = fx.symbolic_trace(torch_model) # Use the dynamo.export() to export the PyTorch model to FX. try: graph_module = dynamo.export(torch_model, *input_tensors) except: raise RuntimeError("Failed to export the PyTorch model to FX.") # Use the importer to import the PyTorch model to Relax. mod: tvm.IRModule = from_fx(graph_module, input_info) # Print out the imported model. print(mod.script())
注释
对于给定的 PyTorch 模型,要在 FX 中查找模型输入的名称,可以使用
fx.symbolic_trace(model).graph.print_tabular()
打印 PyTorch 模块的表格表示,然后检查表格开头的占位符行。
- tvm.relax.frontend.torch.relax_dynamo(pipeline: Pass | None = None)
一个用于创建 relax 后端的辅助函数。
- 参数:
pipeline (Optional[tvm.transform.Pass]) – 要应用于 relax 模块的流水线,然后再发送到构建。
- 返回:
backend – relax dynamo 后端。
- 返回类型:
Callable[[torch.fx.GraphModule, List[torch.Tensor]], Callable]
- tvm.relax.frontend.torch.dynamo_capture_subgraphs(model, *params, **kwargs) IRModule
使用 torch.compile 将 PyTorch 模型的子图捕获到 IRModule 中。
- 参数:
model (torch.nn.Module) – 要捕获的 PyTorch 模型。
params (List[torch.Tensor]) – PyTorch 模型的参数。
keep_params_as_input (bool) – 是否将模型参数保留为捕获的 Relax 函数的输入变量。
- 返回:
output – 翻译的输出,包括翻译后的 IRModule。如果 keep_params_as_input 为 true,则 IRModule 中的函数将具有一个属性 “params”,其中包含输入模型的权重。可以使用 relax.frontend.detach_params 分离权重。
- 返回类型:
ImporterOutput