PyTorch in C++ with LibTorch
The same training loop in C++ on the GPU, and why its loss falls in a perfectly straight line.
- Map each line of a PyTorch training loop to its LibTorch equivalent
- Build a LibTorch program with CMake and move it to the GPU
- Predict the speed of L1-loss training from the gradient alone
LibTorch is PyTorch’s C++ library — the same tensor engine and autograd, without Python. It matters wherever Python is unwelcome: inside a robot’s control loop, a game engine, or a latency-critical server. The repository rebuilds lesson 2’s linear regression in C++, and the translation is almost mechanical.
class LinearRegression : public torch::nn::Module {
public:
LinearRegression(int64_t in_dim, int64_t out_dim) {
linear = register_module("linear", torch::nn::Linear(in_dim, out_dim));
}
torch::Tensor forward(torch::Tensor x) { return linear->forward(x); }
private:
torch::nn::Linear linear{nullptr};
};
register_module is the C++ spelling of assigning a layer to self: it is how parameters() finds the weights. The training loop is lesson 2’s five steps, word for word:
optimizer.zero_grad();
auto outputs = linear_model->forward(inps.unsqueeze(0));
auto loss = torch::l1_loss(outputs.squeeze(), tgts);
loss.backward();
optimizer.step();
Building it
LibTorch ships its own CMake package, so the CMakeLists.txt is short:
find_package(Torch REQUIRED)
add_executable(linear_regression linear_regression.cpp)
target_link_libraries(linear_regression "${TORCH_LIBRARIES}")
mkdir build && cd build
cmake -DCMAKE_PREFIX_PATH=/path/to/libtorch ..
cmake --build . --config Release
./linear_regression
The program picks its device at run time with torch::cuda::is_available() and moves both the data and the model with .to(device). The HPC readme in 01_linear_regression/ covers loading CUDA and compiler modules on a cluster, and verify/verify_torch.cpp lists the GPUs LibTorch can see — worth running first when a build misbehaves.
A loss that falls in a straight line
The readme records the loss every 1,000 epochs on the GPU:
Most loss curves bend. This one is straight, and the reason is the L1 loss. Its gradient does not depend on how large the error is, only on its sign: \(\frac{\partial}{\partial e}\vert e\vert = \operatorname{sign}(e)\). With the loss averaged over two outputs, each step moves every output towards its target by the same amount:
\[\Delta = \eta_{\text{eff}} \cdot \tfrac{1}{2}\,\big(\lVert \mathbf{x} \rVert^2 + 1\big)\]where the \(\lVert\mathbf{x}\rVert^2\) comes from the weights and the 1 from the bias. Momentum 0.9 makes the effective learning rate \(\eta_{\text{eff}} = \eta / (1 - 0.9) = 10^{-4}\). With seed 42, Python’s torch.rand(3) gives \(\mathbf{x} \approx (0.882, 0.915, 0.383)\), so \(\lVert\mathbf{x}\rVert^2 \approx 1.762\) and the loss should fall by \(1000 \cdot 10^{-4} \cdot \tfrac{1}{2} \cdot 2.762 = 0.138\) every 1,000 epochs — exactly the slope in the log, which also confirms that LibTorch’s CPU generator produced the same three numbers.
The bend at the end has the same explanation. Once an output reaches its target, its error’s sign flips back and forth each step and that output stops contributing to the steady fall. The final predictions are 1.0000 2.0000, the targets exactly.
Try it yourself. Switch the loss to torch::mse_loss and predict the shape of the new curve before running it. (Hint: the gradient of \(e^2\) shrinks with \(e\).) Then remove the .momentum(0.9) option and check that the L1 slope drops by a factor of ten.