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 允許底層擴展
所有組件最終通過硬件后端執行實際計算。