onnx L2 范数

onnx L2 范数#

%cd ../../..
import set_env
from d2py.utils.file import mkdir
temp_dir = ".temp"
mkdir(temp_dir)
/media/pc/data/lxw/ai/tvm-book/doc/tutorials/frontend
import torch
from torch import nn

class Model(nn.Module):
    def forward(self, x):
        x = torch.norm(x, p=2, keepdim=True)
        return x

shape = 1, 3, 32, 32
x = torch.rand(*shape)

torch_model = Model()
# 导出模型
output_name = "L2"
torch.onnx.export(
    torch_model,               # torch 模型
    x,                         # 模型输入或者对于多个输入,使用元组
    f"{temp_dir}/{output_name}.onnx",               # 模型保存的位置(可以是文件或类似文件的对象)
    export_params=True,        # 将训练后的参数权重存储在模型文件内
    opset_version=17,          # 导出模型的 ONNX 版本
    do_constant_folding=True,  # 是否执行常量折叠以进行优化
    verbose=True,
    input_names = ['data'],    # 模型的输入名称
    output_names = ['output'], # 模型的输出名称
    dynamic_axes={'data' : {0 : 'batch_size'},    # 可变长度的轴
                  'output' : {0 : 'batch_size'}}
)
Exported graph: graph(%data : Float(*, 3, 32, 32, strides=[3072, 1024, 32, 1], requires_grad=0, device=cpu)):
  %/Constant_output_0 : Long(1, strides=[1], device=cpu) = onnx::Constant[value={-1}, onnx_name="/Constant"](), scope: __main__.Model:: # /media/pc/data/tmp/cache/conda/envs/xin/lib/python3.12/site-packages/torch/functional.py:1626:0
  %/Reshape_output_0 : Float(*, device=cpu) = onnx::Reshape[allowzero=0, onnx_name="/Reshape"](%data, %/Constant_output_0), scope: __main__.Model:: # /media/pc/data/tmp/cache/conda/envs/xin/lib/python3.12/site-packages/torch/functional.py:1626:0
  %output : Float(requires_grad=0, device=cpu) = onnx::ReduceL2[keepdims=0, onnx_name="/ReduceL2"](%/Reshape_output_0), scope: __main__.Model:: # /media/pc/data/tmp/cache/conda/envs/xin/lib/python3.12/site-packages/torch/functional.py:1626:0
  return (%output)

import onnx
import tvm
from tvm import relay
onnx_model = onnx.load(f"{temp_dir}/{output_name}.onnx")
mod, params = relay.frontend.from_onnx(onnx_model, {"data": shape}, freeze_params=True)
# with tvm.transform.PassContext(opt_level=3):
#     mod = relay.quantize.prerequisite_optimize(mod, params)
mod.show()
def @main(%data: Tensor[(1, 3, 32, 32), float32] /* ty=Tensor[(1, 3, 32, 32), float32] span=/Reshape.data:0:0 */) -> float32 {
  %0 = reshape(%data, newshape=[-1]) /* ty=Tensor[(3072), float32] span=/Reshape:0:0 */;
  %1 = multiply(%0, %0) /* ty=Tensor[(3072), float32] span=/ReduceL2:0:0 */;
  %2 = sum(%1, axis=[0]) /* ty=float32 span=/ReduceL2:0:0 */;
  sqrt(%2) /* ty=float32 span=/ReduceL2:0:0 */
}
with tvm.transform.PassContext(opt_level=3):
    with relay.quantize.qconfig(
        skip_conv_layers=[],
        # calibrate_mode="kl_divergence", 
        weight_scale="max",
        # round_for_shift=True,
        # rounding="TONEAREST", # "UPWARD" or "TONEAREST"
        # calibrate_skip_layers=[],
        skip_dense_layer=False,
        # partition_conversions="fully_integral"
    ):
        qmod = relay.quantize.quantize(mod, params)
qmod.show()
def @main(%data: Tensor[(1, 3, 32, 32), float32] /* ty=Tensor[(1, 3, 32, 32), float32] span=/Reshape.data:0:0 */) -> float32 {
  %0 = reshape(%data, newshape=[-1]) /* ty=Tensor[(3072), float32] span=/Reshape:0:0 */;
  %1 = multiply(%0, %0) /* ty=Tensor[(3072), float32] span=/ReduceL2:0:0 */;
  %2 = sum(%1, axis=[0]) /* ty=float32 span=/ReduceL2:0:0 */;
  sqrt(%2) /* ty=float32 span=/ReduceL2:0:0 */
}