Apache TVM 常用 CLI 命令与工具详解

详解 Apache TVM 命令行工具 tvmc 的版本脉络与 compile、run、tune 子命令用法,附 0.19 实测帮助全文与执行回显,并给出 0.27 下的替代方案。

Apache TVMApache TVM2026/10/12

Apache TVM 常用 CLI 命令与工具详解

Apache TVM 的官方命令行驱动是 tvmc(TVM compiler driver)。本文实测环境:Apache TVM 0.19.0(源码编译,含完整 tvmc)与 Apache TVM 0.27.0.post1(PyPI 预编译包),Python 3.10/3.11,x86_64 Linux。所有帮助文本与回显均为实测原文。

一、tvmc 的版本脉络(重要前提)

实测核实(对照 GitHub apache/tvm 各版本源码树):

版本线tvmc 是否随包提供
v0.19.0 及更早是,源码树含 python/tvm/driver/tvmc/
v0.20.0 ~ v0.24.0否,tvmc 已从源码树移除(这些版本也未发布 PyPI 包)
v0.25.0 及以上(PyPI 可安装)否,wheel 中无 tvmc

在 0.27.0.post1 的环境中实测验证:

/opt/tvm-venv/bin/tvmc --help
bash: /opt/tvm-venv/bin/tvmc: No such file or directory
/opt/tvm-venv/bin/python -m tvm.driver.tvmc --help
/opt/tvm-venv/bin/python: No module named tvm.driver.tvmc

结论:0.25+ 的 PyPI 包不含 tvmc。若必须使用 tvmc,需按第二节从官方源码包自行编译 0.19.0;若使用 0.27,请用第四节的原生 API 替代方案。

二、获取含 tvmc 的环境:源码编译 0.19.0(实测记录)

2.1 准备工具链

Ubuntu 22.04 实测:

apt-get update
DEBIAN_FRONTEND=noninteractive apt-get install -y build-essential cmake llvm-dev git
cmake --version | head -1
llvm-config --version
cmake version 3.22.1
14.0.0

2.2 获取源码

推荐官方 Release 源码包(含全部第三方依赖,无需拉取子模块):

wget https://github.com/apache/tvm/releases/download/v0.19.0/apache-tvm-src-v0.19.0.tar.gz -O /tmp/tvm019.tar.gz
mkdir -p /opt/tvm-src-019
tar xzf /tmp/tvm019.tar.gz -C /opt/tvm-src-019 --strip-components=1

实测源码包 109,335,329 字节,解压后 3rdparty/ 自带 dmlc-core、dlpack 等依赖目录。GitHub 下载受阻时可使用下载代理(实测 https://ghfast.top/ 前缀 27 秒拉完)。

2.3 编译安装

mkdir -p /opt/tvm-src-019/build
cd /opt/tvm-src-019/build
cmake .. -DUSE_LLVM=ON -DCMAKE_BUILD_TYPE=Release -DHIDE_PRIVATE_SYMBOLS=ON
cmake --build . -j8

实测 12 核服务器 8 并发约 8 分钟完成(861 个 CXX 编译单元),末尾输出:

[100%] Built target tvm_allvisible

2.4 搭配 Python 运行环境

tvmc 通过 python -m tvm.driver.tvmc 调用,依赖与运行时库共同生效:

python3 -m venv /opt/tvm019-venv
/opt/tvm019-venv/bin/pip install numpy attrs decorator psutil typing_extensions ml_dtypes onnx==1.15.0 cloudpickle tornado
cd /opt/tvm-src-019
PYTHONPATH=/opt/tvm-src-019/python /opt/tvm019-venv/bin/python -c "import tvm; print(tvm.__version__)"
0.19.0

两个实测踩坑点:

  1. onnx 必须钉在 1.15.0:0.19 的 ONNX 前端引用 onnx.mapping,onnx ≥ 1.16 已移除该模块,实测报错 ImportError: Unable to import onnx which is required No module named 'onnx.mapping'。
  2. tune 需要 cloudpickle:本地 tracker 走 popen_pool,实测缺依赖时报 ModuleNotFoundError: No module named 'cloudpickle'。

三、tvmc 子命令详解(0.19.0 实测)

3.1 主帮助

PYTHONPATH=/opt/tvm-src-019/python /opt/tvm019-venv/bin/python -m tvm.driver.tvmc --help
usage: tvmc [--config CONFIG] [-v] [--version] [-h] {run,tune,compile} ...

TVM compiler driver

options:
  --config CONFIG     configuration json file
  -v, --verbose       increase verbosity
  --version           print the version and exit
  -h, --help          show this help message and exit.

commands:
  {run,tune,compile}
    run               run a compiled module
    tune              auto-tune a model
    compile           compile a model.

TVMC - TVM driver command-line interface

--version 实测回显 0.19.0。三个子命令构成完整工作流:compile(编译模型)→ run(执行产物)→ tune(算子调优)。

3.2 tvmc compile

compile --help 全文较长(601 行,含每个 target 的专属参数组),核心参数实测摘录:

usage: tvmc compile [-h] ... [--model-format {keras,onnx,pb,tflite,pytorch,paddle,relay}]
                    [-o OUTPUT] [--target TARGET]
                    [--pass-config name=value] [--target-llvm-mcpu TARGET_LLVM_MCPU]
                    [--tuning-records PATH] [--executor EXECUTOR]
                    [--runtime RUNTIME] [-v] [-O [0-3]] [--input-shapes INPUT_SHAPES]
                    [--disabled-pass DISABLED_PASS] [--module-name MODULE_NAME] FILE

关键选项:

  • FILE:输入模型文件,--model-format 支持 keras/onnx/pb/tflite/pytorch/paddle/relay 七种格式。
  • --target:编译目标,如 llvm、llvm -mcpu=skylake-avx512(0.19 仍支持字符串形式)、复合目标 cuda,llvm。
  • -o:输出压缩包,默认 module.tar。
  • -O [0-3]:优化等级,默认 3。
  • --input-shapes:固定动态模型输入形状,格式 input_name:[dim1,dim2]。
  • --tuning-records:挂载 tune 产出的调优记录。
  • --executor:graph(默认,Graph Executor)或 aot(嵌入式首选)。
  • --dump-code asm,ll,tir,relay:导出中间产物用于学习与排查。

实测:编译一个 4×8 @ 8×16 的 Gemm ONNX 模型(onnx.helper 生成,tiny_gemm.onnx):

cd /root
PYTHONPATH=/opt/tvm-src-019/python /opt/tvm019-venv/bin/python -m tvm.driver.tvmc compile tiny_gemm.onnx --target llvm -o module.tar
/opt/tvm-src-019/python/tvm/relay/frontend/onnx.py:7234: UserWarning: Your model ir_version 14 is higher than the checker's (9).
  warnings.warn(str(e))
WARNING:autotvm:One or more operators have not been tuned. Please tune your model for better performance. Use DEBUG logging level to see more details.

产物:

-rw-r--r-- 1 root root 50K module.tar

两条警告均属正常:ir_version 提示模型 ONNX 版本较新(不影响编译);untuned 警告说明还没挂调优记录(见 3.4 节)。

3.3 tvmc run

run --help 全文如下:

usage: tvmc run [-h] [--device {cpu,cuda,cl,metal,vulkan,rocm}]
                [--fill-mode {zeros,ones,random}] [-i INPUTS] [-o OUTPUTS]
                [--print-time] [--print-top N] [--profile] [-v] [--end-to-end]
                [--repeat N] [--number N] [--rpc-key RPC_KEY]
                [--rpc-tracker RPC_TRACKER]
                PATH

positional arguments:
  PATH                  path to the compiled module file or to the project
                        directory if '--device micro' is selected.

options:
  -h, --help            show this help message and exit
  --device {cpu,cuda,cl,metal,vulkan,rocm}
                        target device to run the compiled module. Defaults to
                        'cpu'
  --fill-mode {zeros,ones,random}
                        fill all input tensors with values. In case
                        --inputs/-i is provided, they will take precedence
                        over --fill-mode. Any remaining inputs will be filled
                        using the chosen fill mode. Defaults to 'random'
  -i INPUTS, --inputs INPUTS
                        path to the .npz input file
  -o OUTPUTS, --outputs OUTPUTS
                        path to the .npz output file
  --print-time          record and print the execution time(s). Enabling
                        print-time will result in (1 + repeat * number)
                        executions of the model.
  --print-top N         print the top n values and indices of the output
                        tensor
  --profile             generate profiling data from the runtime execution.
                        Using --profile requires the Graph Executor Debug
                        enabled on TVM. Profiling may also have an impact on
                        inference time, making it take longer to be generated.
  -v, --verbose         increase verbosity.
  --end-to-end          Measure data transfers as well as model execution.
                        This can provide a more realistic performance
                        measurement in many cases. Requires '--print-time' to
                        be specified.
  --repeat N            How many times to repeat the run. Requires '--print-
                        time' to be specified. Defaults to '1'
  --number N            The number of runs to measure within each repeat.
                        Requires '--print-time' to be specified. Defaults to
                        '1'
  --rpc-key RPC_KEY     the RPC tracker key of the target device.
  --rpc-tracker RPC_TRACKER
                        hostname (required) and port (optional, defaults to
                        9090) of the RPC tracker, e.g. '192.168.0.100:9999'.

实测执行编译产物:

PYTHONPATH=/opt/tvm-src-019/python /opt/tvm019-venv/bin/python -m tvm.driver.tvmc run module.tar --fill-mode random -o outputs.npz --print-time
2026-10-12 13:41:16.699 INFO load_module /tmp/tmpxja5dsfx/mod.so
Execution time summary:
 mean (ms)   median (ms)    max (ms)     min (ms)     std (ms)
   0.0146       0.0146       0.0146       0.0146       0.0000

输出张量写入 outputs.npz,可用 NumPy 读取:np.load("outputs.npz"),键为输出名 output。

3.4 tvmc tune

tune --help 全文 601 行,主体与 compile 的 target 参数组一致,调优专属参数摘录:

  --early-stopping EARLY_STOPPING
                        minimum number of trials before early stopping
  --min-repeat-ms MIN_REPEAT_MS
                        minimum time to run each trial, in milliseconds.
                        Defaults to 0 on x86 and 1000 on all other targets
  --parallel PARALLEL   the maximum number of parallel devices to use when
  --timeout TIMEOUT     compilation timeout, in seconds
  --trials TRIALS       the maximum number of tuning trials to perform
  --tuning-records PATH
                        path to an auto-tuning log file by AutoTVM.

AutoScheduler options:
  AutoScheduler options, used when --enable-autoscheduler is provided
  --cache-line-bytes CACHE_LINE_BYTES
  --num-cores NUM_CORES
  --vector-unit-bytes VECTOR_UNIT_BYTES
  ...

AutoTVM options:
  --tuner {ga,gridsearch,random,xgb,xgb_knob,xgb_itervar,xgb_curve,xgb_rank,...}
                        type of tuner to use when tuning with autotvm.

实测(random 调优器避免 xgboost 依赖):

PYTHONPATH=/opt/tvm-src-019/python /opt/tvm019-venv/bin/python -m tvm.driver.tvmc tune tiny_gemm.onnx --target llvm --tuner random --trials 8 --early-stopping 4 --parallel 1 -o tuning_records.json
[Task  1/  2]  Current/Best:    0.09/   0.13 GFLOPS | Progress: (4/4) | 4.47 s Done.
[Task  2/  2]  Current/Best:   11.03/  11.66 GFLOPS | Progress: (4/4) | 2.77 s Done.

产出 tuning_records.json(实测 3.4K)。调优后重新编译:

PYTHONPATH=/opt/tvm-src-019/python /opt/tvm019-venv/bin/python -m tvm.driver.tvmc compile tiny_gemm.onnx --target llvm --tuning-records tuning_records.json -o module_tuned.tar

实测生成 module_tuned.tar(50K),此前 compile 阶段的 untuned 警告消失。

3.5 一次完整工作流小结

# 1. 调优(可选,建议先行)
tvmc tune model.onnx --target llvm --tuner random --trials 8 -o records.json
# 2. 编译(挂载调优记录)
tvmc compile model.onnx --target llvm --tuning-records records.json -o module.tar
# 3. 执行
tvmc run module.tar --fill-mode random --print-time

四、0.27 下的替代方案(实测)

PyPI 0.27 包自带两个轻量命令行工具(venv 的 bin/ 下):

  • tvm-ffi-config:查询 FFI 构建信息(如 tvm-ffi-config --libdir)。
  • tvm-ffi-stubgen:为 FFI 接口生成类型桩。

模型编译与推理在 0.27 中回归 Python API 主路径(tvm.relax.build + relax.VirtualMachine),完整示例见《Apache TVM 快速入门与集成示例》。实测等价关系:

tvmc 能力0.27 等价实现
tvmc compilerelax.build(onnx_frontend.from_onnx(onnx.load(p)), target="llvm")
tvmc runVirtualMachine(ex, dev)["main"](tvm.runtime.tensor(x, dev))
tvmc tunemeta-schedule / 体化调优(需 apache-tvm[all])
--executor aotrelax.build(mod, target, executor=Executor("aot"))

五、常见问题

**Q1:**装了 apache-tvm 却找不到 tvmc? 0.20.0 起 tvmc 被移除,PyPI 0.25+ 的包不含它。要么按第二节编译 0.19.0,要么迁移到 0.27 的 Relax API(第四节对照表)。

**Q2:**0.19 编译 ONNX 模型报 No module named 'onnx.mapping'? onnx 版本过新。实测 pip install onnx==1.15.0 后恢复。

**Q3:**tvmc tune 报 No module named 'cloudpickle'? 本地 tracker 依赖 cloudpickle,安装后重试;xgboost 类调优器还需 pip install xgboost,或改用 --tuner random。

Q4:tvmc run 报 --device micro 相关错误? --device micro 需要带 microTVM 专用工程目录;普通 tar 包直接用默认 --device cpu。

**Q5:**0.19 的 --target "llvm -mcpu=skylake-avx512" 在 0.27 报错? 0.27 已废弃 CLI 字符串形式,改用字典 {"kind": "llvm", "mcpu": "skylake-avx512"},详见《Apache TVM 配置参数详解》。

**Q6:**tvmc compile 的产物 module.tar 里是什么? mod.so(动态库)、mod.json(图描述)、参数文件;部署机只需 TVM runtime(或 min call 产物)即可加载,无需完整编译器。

六、参考链接