在自定义 C++ 扩展中,如何确保 kernel 在指定 stream 上执行?
解读
国内一线厂(阿里、字节、华为昇腾、商汤等)在部署大模型时,普遍把“多 stream 并行”当作榨干 GPU 利用率的核心手段。面试官问这道题,不是想听你背 API,而是想确认三件事:
- 你是否真的在 C++ 扩展里写过 CUDA kernel,而不是只调 Python;
- 你是否理解 PyTorch stream 与 CUDA stream 的映射关系;
- 你是否能把“传 stream → 捕获 stream → 把 kernel 插到 stream”这三步做成线程安全、异常安全、且对 Python 用户透明的最佳实践。
如果答成“把 kernel 包进 at::cuda::CUDAStreamGuard 就完事”,只能拿 60 分;能把 c10::cuda::getCurrentCUDAStream 与 at::cuda::getStreamFromExternal 的区别、以及如何在自定义 autograd Function 里双向透传 stream,讲清楚才能拿到 90+。
知识点
- PyTorch stream 对象:Python 端
torch.cuda.Stream↔ C++ 端at::cuda::CUDAStream。 - 当前 stream 的获取:
at::cuda::getCurrentCUDAStream(device)返回线程局部当前流;c10::cuda::getStreamFromExternal(cudaStream_t, device)可把裸 CUDA 流包装成at::cuda::CUDAStream,用于跨框架混用。
- RAII 守卫:
at::cuda::CUDAStreamGuard guard(stream)把指定流设为当前,析构时自动回滚;OptionalCUDAStreamGuard支持空流。 - kernel 发射位置:在 guard 作用域内调用
<<<grid, block, 0, stream.stream()>>>,第三个参数 0 表示共享内存,第四个必须是cudaStream_t。 - autograd 的流一致性:如果自定义
torch::autograd::Function前后向都有 kernel,必须在ctx->save_for_backward之前把输入 tensor 的记录流(event)同步到计算流,否则 backward 可能跑在别的流上导致 SEGFAULT。 - 异常安全:kernel 发射后立刻
AT_CUDA_CHECK(cudaGetLastError()),并保证 C++ 异常抛出时 guard 能正常析构回滚。 - 编译与符号:使用
pybind11导出时,把cudaStream_t强转成uintptr_t传给 Python 不安全,正确做法是只传py::object(torch.cuda.Stream),在 C++ 端用THPUtils_unpackStream解析。
答案
步骤一:在 Python 端把流对象传进 C++
import torch
from my_ext import forward_cuda
stream = torch.cuda.Stream()
with torch.cuda.stream(stream):
out = forward_cuda(x, y) # x, y 是 CUDA tensor
步骤二:在 C++ 扩展里接收并守卫流
#include <torch/extension.h>
#include <ATen/cuda/CUDAContext.h>
#include <c10/cuda/CUDAStream.h>
torch::Tensor forward_cuda(torch::Tensor x, torch::Tensor y) {
TORCH_CHECK(x.is_cuda() && y.is_cuda(), "inputs must be CUDA");
auto device = x.device();
// 1. 取出 Python 端当前流
at::cuda::CUDAStream stream = at::cuda::getCurrentCUDAStream(device.index());
// 2. 用 RAII 保证 kernel 发射期间流不变
at::cuda::CUDAStreamGuard guard(stream);
// 3. 准备输出
auto out = torch::empty_like(x);
// 4. 发射 kernel
const int threads = 256;
const int blocks = (x.numel() + threads - 1) / threads;
my_kernel<<<blocks, threads, 0, stream.stream()>>>(
x.data_ptr<float>(),
y.data_ptr<float>(),
out.data_ptr<float>(),
x.numel());
// 5. 立即检查错误,异常安全
AT_CUDA_CHECK(cudaGetLastError());
return out;
}
步骤三(可选):在自定义 autograd Function 里同步流
class MyFunction : public torch::autograd::Function<MyFunction> {
public:
static torch::Tensor forward(
torch::autograd::AutogradContext* ctx,
torch::Tensor x, torch::Tensor y) {
auto stream = at::cuda::getCurrentCUDAStream(x.device().index());
at::cuda::CUDAStreamGuard guard(stream);
auto out = forward_cuda(x, y);
// 保存事件,保证 backward 用同一条流
auto event = at::cuda::CUDAEvent{};
event.record(stream);
ctx->save_for_backward({x, y});
ctx->saved_data["event"] = event;
return out;
}
static torch::autograd::tensor_list backward(
torch::autograd::AutogradContext* ctx,
torch::autograd::tensor_list grad_out) {
auto saved = ctx->get_saved_variables();
auto event = ctx->saved_data["event"].toCUDAEvent();
auto stream = at::cuda::getCurrentCUDAStream(saved[0].device().index());
event.block(stream); // 同步
...
}
};
至此,无论 Python 用户如何切换流、是否多线程,kernel 都能稳定跑在指定流上,且异常时能自动回滚。
拓展思考
- 多卡多流:在数据并行场景下,每个卡一条主计算流 + 一条通信流(NCCL),自定义 kernel 如何与 NCCL 流做 event 同步避免读写冲突?
- CUDA Graph 捕获:PyTorch 1.10+ 支持
torch.cuda.make_graphed_callables,但要求捕获区内所有 kernel 必须显式使用同一cudaStream_t。如果扩展里忘记把stream.stream()传进去,会导致cudaErrorStreamCaptureMismatch,如何在编译期用static_assert强制检查? - 昇腾/寒武纪:国内很多卡不是 CUDA 而是 CANN/MLU,框架换成
torch_npu、torch_mlu,stream 概念变为aclrtStream、cnrtQueue,如何写一份宏抽象,让同一套 C++ 扩展在 NVIDIA、昇腾、寒武纪上都保证“指定流执行”? - 线程安全:Python GIL 释放后,C++ 端可能被多个 Python 线程同时调用,如何保证
getCurrentCUDAStream拿到的是调用者线程的流,而不是被别的线程torch.cuda.set_stream篡改? - 性能调优:当 kernel 很小且发射频繁时,guard 的构造析构会成为热点,能否用
cudaStream_t缓存 +__forceinline__把开销降到 0?