ExecuTorch 的 CUDA 后端导出与激活内存拷贝控制

介绍 ExecuTorch 面向 NVIDIA GPU 的 CUDA 后端,说明其借助 AOTInductor 生成 CUDA 内核、用 Triton 生成 GEMM 等算子,并给出导出模型、构建运行时以及控制输入输出拷贝的配置要点。

## CUDA 后端软件[#](<https://docs.pytorch.org/executorch/stable/backends/cuda/cuda-overview.html#cuda-backend>) CUDA后端是用于在NVIDIA GPU上运行模型的ExecuTorch解决方案,它可以发挥杠杆作用. [AOT 介绍器](<https://pytorch.org/docs/stable/torch.compiler_aot_inductor.html>) 编译器,以生成优化的 CUDA 内核,并使用 libtorch 无执行,并使用 [特里通语Name](<https://triton-lang.org/>) 用于高性能的GPU内核生成. ## 特征[#](<https://docs.pytorch.org/executorch/stable/backends/cuda/cuda-overview.html#features>) - **优化 GPU 执行**: 使用 AOT 介导器为模型操作员生成高度优化的CUDA内核 - **Triton 内核支持**:Leverages Triton for GEMM(通用矩阵乘法),演化,和SDPA(比例点-Product recent)内核. - **量化支持**: INT4 重量量化,采用瓦片包装格式,用于改进性能和减少内存足迹 - **横线**: 支持 Linux 和 Windows 平台 - **多个模式支持**: 各种模型的作品,包括LLMS、视觉语言模型和音频模型 ## 目标所需资源[#](<https://docs.pytorch.org/executorch/stable/backends/cuda/cuda-overview.html#target-requirements>) 以下是运行CUDA授权的ExecuTorch型号的要求: - **硬件**: NVIDIA GPU 具有CUDA计算能力. - **CUDA 工具包**: CUDA 11 .x 或较晚(CUDA 12 .x 推荐). - **操作系统**: Linux 或 视窗 - **司机**: PyTorch - 兼容的 NVIDIA GPU 驱动程序安装 ## 发展要求[#](<https://docs.pytorch.org/executorch/stable/backends/cuda/cuda-overview.html#development-requirements>) 要使用 CUDA 后端开发并导出模型: - **Python 键**: Python 3.8 + (韩语). - **PyTorch**: PyTorch 配有 CUDA 支持 - **ExecuTorch**: 安装 ExecuTorch 后端支持 CUDA ## 使用 CUDA 后端[#](<https://docs.pytorch.org/executorch/stable/backends/cuda/cuda-overview.html#using-the-cuda-backend>) ### 用 Python API 导出模型[#](<https://docs.pytorch.org/executorch/stable/backends/cuda/cuda-overview.html#exporting-models-with-python-api>) CUDA后端使用 `CudaBackend` 财务报告和财务报告 `CudaPartitioner` 分类以导出模型。这里有一个完整的示例: ``` import torch from executorch.backends.cuda.cuda_backend import CudaBackend from executorch.backends.cuda.cuda_partitioner import CudaPartitioner from executorch.exir import EdgeCompileConfig, to_edge_transform_and_lower from executorch.extension.export_util.utils import save_pte_program # Configure edge compilation edge_compile_config = EdgeCompileConfig( _check_ir_validity=False, _skip_dim_order=True, ) # Define your model model = YourModel().eval() example_inputs = (torch.randn(1, 3, 224, 224),) # Export the model using torch.export exported_program = torch.export.export(model, example_inputs) # Create the CUDA partitioner partitioner = CudaPartitioner( [CudaBackend.generate_method_name_compile_spec(model_name)] ) # Add decompositions for Triton to generate kernels exported_program = exported_program.run_decompositions({ torch.ops.aten.conv1d.default: conv1d_to_conv2d, }) # Lower to ExecuTorch with CUDA backend et_program = to_edge_transform_and_lower( exported_program, partitioner=[partitioner], compile_config=edge_compile_config, ) # Convert to executable program and save exec_program = et_program.to_executorch() save_pte_program(exec_program, model_name, "./output_dir") ``` 此生成 `.pte` 财务报告和财务报告 `.ptd` 可以在 CUDA 设备上执行的文件。 关于完整的实例,请参见: [CUDA 导出脚本](<https://github.com/pytorch/executorch/blob/main/examples/cuda/scripts/export.py>). --- ## 运行时间集成[#](<https://docs.pytorch.org/executorch/stable/backends/cuda/cuda-overview.html#runtime-integration>) 要运行设备上的模型,请使用标准的 ExecuTorch 运行时间 API. See [在设备上运行](<https://docs.pytorch.org/executorch/stable/backends/cuda/cuda-overview.html#getting-started.md#running-on-device>) 以获取更多信息。 从源头建时,通过 `-DEXECUTORCH_BUILD_CUDA=ON` 当配置 CMake 构建以编译 CUDA 后端时. ``` # CMakeLists.txt add_subdirectory("executorch") ... target_link_libraries( my_target PRIVATE executorch extension_module_static extension_tensor aoti_cuda_backend) ``` 除了连接目标外,不需要再使用后端。 `.pte` 财务报告和财务报告 `.ptd` 文件将自动运行在注册的后端。 --- ## 激活内存:谁拥有GPU副本[#](<https://docs.pytorch.org/executorch/stable/backends/cuda/cuda-overview.html#activation-memory-who-owns-the-gpu-copies>) 一个 CUDA 模型必须将其输入数据以某种方式输入到 GPU 上。有两种方式,您在导出时选择一种方式 。 **默认: 您的运行时间副本 。** 在每次代表输入前插入一个 host-to-device 副本, 在每次代表输出后插入一个 device-to-host 副本。 您通过普通的 CPU 载数, 运行时间会移动数据 : ``` exec_program = et_program.to_executorch() ``` ``` # CPU tensors. The runtime copies them to the GPU and copies results back. outputs = method([torch.randn(4, 64)]) ``` 这是最简单的选项, 也是正确的默认。 费用是每个呼叫中每个方向的复制 。 **选择出局:直接交出GPU内存.** 如果您的数据已经在设备上, 这些副本会被浪费。 关闭它们, 而输入占位符则被当作设备内存 : ``` from executorch.exir import ExecutorchBackendConfig from executorch.exir.passes import MemoryPlanningPass from executorch.exir.passes.propagate_device_config import PropagateDeviceConfig exec_program = et_program.to_executorch( ExecutorchBackendConfig( propagate_device_config=PropagateDeviceConfig( skip_h2d_for_method_inputs=True, skip_d2h_for_method_outputs=True, ), enable_non_cpu_memory_planning=True, # Required alongside the skips. Memory planning reserves a buffer for graph inputs and # outputs by default, and the runtime fills a planned input by copying the caller's # memory into that buffer, which reintroduces the copy you just asked to skip. On device # memory that copy is a host memcpy into a device pointer, which is undefined. memory_planning_pass=MemoryPlanningPass( alloc_graph_input=False, alloc_graph_output=False ), ) ) ``` ``` # Now the tensors must already be on the GPU. Passing CPU tensors is a caller error. outputs = method([torch.randn(4, 64, device="cuda")]) ``` 输出也停留在设备上,这是当您的管道的下一阶段也在GPU上时你想要的. ### 值得我们知道的事情[#](<https://docs.pytorch.org/executorch/stable/backends/cuda/cuda-overview.html#things-worth-knowing>) **两旗独立.** 只需在 GPU 上生成数据但想要结果返回主机,或者只想要输出副本以反向显示,即可跳过输入副本. **两面旗帜都需要 `enable_non_cpu_memory_planning=True`.** 默认为 `True`,所以将其排除在外,上面的片段明确规定,它只是为了使要求变得明显。 `False` 请求跳过或升起一个 `ValueError`,因为复制插入发生在设备感知内存规划期间. **两面旗帜也需要计划外的图表输入和产出**,通过 `MemoryPlanningPass(alloc_graph_input=False, alloc_graph_output=False)` 如上所示。没有它,程序仍然保留自己的缓冲器和运行时间复制件,所以复制件会在运行时返回。在设备内存上,复制件是一个主机memcpy输入设备指针,这个指针是未定义的,所以程序崩溃而不是返回错误的答案。 **per-method选择在外侧配置上,而不是在旗帜上.** 传递命令 `PropagateDeviceConfig` 键入方法名称 : ``` ExecutorchBackendConfig( propagate_device_config={ "forward": PropagateDeviceConfig( skip_h2d_for_method_inputs=True, skip_d2h_for_method_outputs=True ), "forward_from_host": PropagateDeviceConfig(), }, ... ) ``` 不要传递命令给 `skip_h2d_for_method_inputs` 因此,任何非空洞的指令都能够使每个方法的跳过,而不管它里面的值是什么。 **选择被烤进 `.pte`.** 一个带有副本输出的程序预期主机的百分数; 一个没有它们导出的程序预期设备的百分数。 通过错误的种类是呼叫器错误,而不是运行时间正确的东西,所以两者在运行时间是不可互换的 。 **从C++来看,这是同一个合同。** 如果复制件被跳过, 输入必须是代表将接受为设备驻地的对调器。 有两种方法可以构建一个, 这取决于数据已经存在何处。 如果数据已经存在于设备内存中,请用 `from_blob` ,然后将设备命名为紧贴在scalar 类型之后。没有复制任何设备 : ``` auto input = from_blob(device_data, {rows, columns}, ScalarType::Float, DeviceType::CUDA); auto result = module.forward(input); ``` 这是当数据的制作方是另一个GPU内核,一个写给GPU的相机或视频解码器,或者一个您保存在设备上的更早的模型时使用的路径. `from_blob` 不分配或迁移任何东西,所以指针必须在您命名的设备上真正有效,并且它必须超过抗热器。 如果数据从主机开始, `clone_tensor_ptr_to` 在设备上分配并复制,花费一次传输: ``` auto host_input = make_tensor_ptr({rows, columns}, std::move(data)); auto input = clone_tensor_ptr_to(host_input, DeviceType::CUDA); auto result = module.forward(input); ``` 设备参数默认为 `DeviceType::CPU` 在不使用自定义删除器的超载中,所以是一个普通的 `from_blob(host_ptr, sizes, type)` 仍然表示主机内存。 删除器超载需要设备命名 。 在移交设备指针时将设备留在 CPU 上, 生成一个由 CPU 标记的显示器, 代表拒绝 。 **代表如何决定一个抗压器是装置常住。** 两次检查,按此顺序进行。 `device_type` 必须是 `CUDA`然后,因为那个标签只是一种说法, 代表呼叫 `cudaPointerGetAttributes` 在数据指针上,并需要内存真的 `cudaMemoryTypeDevice` 或 时 间 `cudaMemoryTypeManaged`由主机内存支撑的 CUDA 标记的拉伸器被夹住 而不是腐蚀运行 。 在默认导出时,通过一个普通主机的按数器代替,运行时间处理传输. --- ## 实例[#](<https://docs.pytorch.org/executorch/stable/backends/cuda/cuda-overview.html#examples>) 完整的 end-to-end 用 CUDA 后端导出和运行模型的例子,请参见: - [低声](<https://github.com/pytorch/executorch/blob/main/examples/models/whisper/README.md>) ——音频转录模型,支持CUDA - [挥霍器](<https://github.com/pytorch/executorch/blob/main/examples/models/voxtral/README.md>) ——有CUDA支持的音频多式联运模型. - [宝石3color](<https://github.com/pytorch/executorch/blob/main/examples/models/gemma3/README.md>) ——有CUDA支持的远景语言模型. 这些例子显示了整个工作流程,包括模式导出、量化选项、建设跑者以及运行时间执行。 ExecuTorch提供Makefile目标用于构建这些示例跑车: ``` make whisper-cuda # Build Whisper runner with CUDA make voxtral-cuda # Build Voxtral runner with CUDA make gemma3-cuda # Build Gemma3 runner with CUDA ```

查看原始来源