libtorch
libtorch 是 PyTorch 的 C++ 实现版本,可以认为所有的pytorch底层都是由c++实现,而pytorch的所有C++实现就叫libtorch,也就是我们在pytorch官网getstart页面下载的c++pytorch版本。我们用python写的pytorch神经网络代码都会通过pybind11将python转换为libtorch的C++代码。
[官方文档](PyTorch C++ API — PyTorch main documentation)
libtorch由以下几部分组成:
- ATen: The foundational tensor and mathematical operation library on which all else is built.
- Autograd: Augments ATen with automatic differentiation.
- C++ Frontend: High level constructs for training and evaluation of machine learning models.
- TorchScript: An interface to the TorchScript JIT compiler and interpreter.
- C++ Extensions: A means of extending the Python API with custom C++ and CUDA routines.
libtorch C++ Frontend可以看作是 PyTorch Python Frontend(也就是dataset, dataloader, torch.nn那一套)的 C++ 版本,为机器学习和神经网络提供自动微分和各种更高级别的抽象。具体而言,它由以下组件组成:
Component | Description |
---|---|
torch::Tensor |
Automatically differentiable, efficient CPU and GPU enabled tensors |
torch::nn |
A collection of composable modules for neural network modeling |
torch::optim |
Optimization algorithms like SGD, Adam or RMSprop to train your models |
torch::data |
Datasets, data pipelines and multi-threaded, asynchronous data loader |
torch::serialize |
A serialization API for storing and loading model checkpoints |
torch::python |
Glue to bind your C++ models into Python |
torch::jit |
Pure C++ access to the TorchScript JIT compiler |
可以简单的认为 C++ Frontend调用ATen、Autograd、TorchScript 和 C++ Extensions,为用户提供了libtorch的C++用户API,下图清晰展示了 C++ Frontend、ATen、Autograd、TorchScript 和 C++ Extensions 之间的交互关系:
关键关系说明:
C++ Frontend 是核心用户接口
- 直接调用其他所有组件
- 提供类似 Python 的编程体验
- 示例:
model->forward()
触发 ATen 操作和 Autograd 记录
ATen 是计算基础
- 所有组件最终都依赖 ATen 执行计算
- 提供跨硬件(CPU/GPU)的统一接口
Autograd 实现自动微分
- 在 ATen 操作上构建计算图
- C++ Frontend 训练时自动调用
- 支持自定义梯度(通过 C++ Extensions)
TorchScript 桥接 Python/C++
- 序列化模型依赖 ATen 操作定义
- C++ Frontend 直接加载运行
C++ Extensions 扩展系统
- 使用 ATen API 实现自定义操作
- 可集成到 Autograd(定义反向传播)
- 可注册到 TorchScript(模型中使用)
典型工作流示例:
训练流程:
部署流程:
此图展示了 PyTorch C++ 生态中各组件的协作关系,其中:
- C++ Frontend 是用户入口点
- ATen 是计算基石
- Autograd 提供训练能力
- TorchScript 实现跨平台部署
- C++ Extensions 允许底层扩展
所有组件最终通过硬件后端执行实际计算。