Rust in Everything
← 返回课程目录
📄doc

Candle 0.11 CustomOp 双向实战:Rayon CPU 路径、原生 .metal 着色器与 bwd 反向注册

1. Candle 0.11 扩展自定义算子的三段式契约

与 Burn + CubeCL 用统一 Rust DSL 编译到多后端不同,/docs/candle 采用的是**显式多后端回调(Explicit Backend Dispatch)**架构。当你为一个二元算子(如 RMSNorm(x, w)、SwiGLU(gate, up))实现 CustomOp2,或为三元算子(如 RoPE(x, cos, sin))实现 CustomOp3 时,Candle 让你按需填写四个方法:

  1. cpu_fwd:接收 &CpuStorage 与 &Layout,校验连续性后直接拿到裸 &[f32] 切片,搭配 rayon::par_chunks_mut 榨干多核 CPU 与自动 SIMD 向量化;
  2. metal_fwd:接收 &MetalStorage 与 &Layout,直接拿到底层 MTLBuffer 句柄,编译并派发原生 Metal Shading Language (.metal) 计算内核;
  3. cuda_fwd:在 NVIDIA 显卡上可通过 cudarc 载入编译好的 .ptx 模块;
  4. bwd:接收前向输入张量、输出张量与上游梯度 grad_res,返回 (Option<Tensor>, Option<Tensor>, ...),直接挂入 Candle 的 BackpropOp 自动微分链!

2. 零外部构建工具:把 .metal 着色器内嵌进纯 Rust 二进制并缓存 ComputePipeline

很多开发者以为写 Metal 着色器一定要配 Xcode 工程或 build.rs 调 xcrun metal 预编译 .metallib。其实在 Candle 0.11.0 中,MetalDevice 直接暴露了运行时即时编译 API(new_library_with_source),你可以把 .metal 源码作为 const FUSED_MSL_SOURCE: &str 静态内嵌在 Rust 二进制里,首次调用时编译一次并缓存在 OnceLock<Mutex<HashMap<...>>> 中,后续每次派发零编译开销!

以 fused_rmsnorm_f32 原生 MSL 着色器为例,它与上一课的 CubeCL 内核采用完全对称的 256 线程片上 threadgroup float shared[256] 树形归约:

kernel void fused_rmsnorm_f32(
  device const float* x [[buffer(0)]],
  device const float* w [[buffer(1)]],
  device float* out [[buffer(2)]],
  constant RmsParams& p [[buffer(3)]],
  uint row [[threadgroup_position_in_grid]],
  uint tid [[thread_position_in_threadgroup]],
  uint tg_size [[threads_per_threadgroup]]
) {
  if (row >= p.rows) return;
  threadgroup float shared[256];
  uint base = row * p.dim;
  float acc = 0.0f;
  for (uint col = tid; col < p.dim; col += tg_size) {
    float v = x[base + col];
    acc += v * v;
  }
  shared[tid] = acc;
  threadgroup_barrier(mem_flags::mem_threadgroup);
  for (uint stride = tg_size >> 1; stride > 0; stride >>= 1) {
    if (tid < stride) shared[tid] += shared[tid + stride];
    threadgroup_barrier(mem_flags::mem_threadgroup);
  }
  float inv_rms = rsqrt(shared[0] / float(p.dim) + p.eps);
  for (uint col = tid; col < p.dim; col += tg_size) {
    out[base + col] = x[base + col] * inv_rms * w[col];
  }
}

而在 Rust 侧的 metal_fwd 里,只需 15 行代码即可安全完成池化输出缓冲分配(device.new_buffer)、指令编码器获取(CommandsGuard::as_ref())与网格派发:

let out_buf = device.new_buffer(elem_count, DType::F32, "fused_rmsnorm_out")?;
let params = RmsParams { rows: rows as u32, dim: dim as u32, eps: self.eps };
let guard = device.command_encoder()?;
let encoder = guard.as_ref();
encoder.set_compute_pipeline_state(&pl);
encoder.set_input_buffer(0, Some(s1.buffer()), l1.start_offset() * 4);
encoder.set_input_buffer(1, Some(s2.buffer()), l2.start_offset() * 4);
encoder.set_output_buffer(2, Some(&out_buf), 0);
encoder.set_bytes(3, &params);
encoder.dispatch_thread_groups(
  MTLSize { width: rows, height: 1, depth: 1 },
  MTLSize { width: 256, height: 1, depth: 1 },
);
drop(guard); // 先释放借用 device 的 CommandsGuard,再把 device 所有权移入 MetalStorage
Ok((MetalStorage::new(out_buf, device, elem_count, DType::F32), l1.shape().clone()))
💡TIP

借用检查器小细节:device.command_encoder()? 返回的 CommandsGuard<'_> 持有对 device 的不可变借用;必须在构造 MetalStorage::new(out_buf, device, ...) 前显式 drop(guard) 结束编码器作用域,Rust 编译器就会在编译期保证指令编码完毕后才交还存储对象!


3. 注册 bwd 反向回调与另一处 Candle 0.11.0 Metal 实测避坑

CustomOp2::bwd 与 CustomOp3::bwd 可以直接复用张量原语甚至反向调用同一个 CustomOp:

  • CandleFusedRoPE::bwd:正交转置只需一句 grad_out.apply_op3(cos, &sin.neg()?, CandleFusedRoPE { seq_len }),反向传播自动享受手写 .metal 融合加速!
  • CandleFusedSwiGlu::bwd(实测踩坑!): 最初我们在 bwd 中调用了 candle_nn::ops::sigmoid(gate)?,在 CPU 上全绿,切到 Metal 立刻报错: Metal error: no metal implementation for sigmoid! 解法:改用 Candle Metal 原生支持的基础原语组合 let sig = (gate.neg()?.exp()? + 1.0)?.recip()?;,在 CPU / Metal / CUDA 三端均以 <= 2.38e-7 精度通过 PyTorch 黄金对账。

4. 正面交锋:CubeCL #[cube] vs 原生 .metal 着色器谁更香?

我们在同一台 Apple Silicon 机器、同一形状 4096 × 2048 FP32 上把两种手写方案拉出来正面 PK,结果令人深思:

对比维度CubeCL 0.11 #[cube(launch)](纯 Rust)Candle CustomOp + 原生 .metal(MSL)
冷启动首次编译耗时8.18 ~ 13.55 ms(CubeCL IR → MSL → Metal Pipeline)1.32 ~ 2.03 ms(直通 Apple Metal 编译器,快 6×)
RMSNorm 稳态延迟 / 带宽0.1667 ms / 402.68 GB/s0.2006 ms / 334.58 GB/s
SwiGLU 稳态延迟 / 带宽0.2653 ms / 379.46 GB/s0.2812 ms / 358.01 GB/s
RoPE 稳态延迟 / 带宽0.1726 ms / 394.90 GB/s0.1901 ms / 358.59 GB/s
跨平台移植成本零修改直接编译到 NVIDIA L4 CUDA!仅限 Apple Metal;上 NVIDIA 需另写 .cu / PTX
CPU 回退能力Burn 自带 Flex / CubeCL CPU手写 Rayon cpu_fwd(RoPE 50.22 GB/s,比 PyTorch CPU 快 2.54×!)

工程架构结论:

  1. 为什么 CubeCL #[cube] 在 Apple Metal 上稳态反而比我们手写的 .metal 更快(402.68 GB/s vs 334.58 GB/s)? 核心原因有二:一是 CubeCL 的 CubeTensor 运行期缓冲区复用与 wgpu-msl 命令队列批提交开销极低;二是 CubeCL 编译器对 #[comptime] dim 做了常量折叠与地址算术优化(将 row * 2048 编译为移位指令 row << 11),而我们的 MSL RmsParams 将 dim 放在运行期 constant buffer 中!
  2. 何时选 CubeCL,何时选原生 .metal / .cu?
    • 95% 的跨平台自定义融合算子(RMSNorm、RoPE、SwiGLU、Gated DeltaNet 分块内核)首选 CubeCL #[cube]:一份 Rust 代码同时在 Apple Metal 与 NVIDIA CUDA 上打满 80%+ 硬件带宽,零维护分裂;
    • 只有当你需要压榨某一特定硬件的专有指令(如 Apple Silicon simdgroup_matrix 或 NVIDIA Hopper WGMMA / TMA),或者你的主干推理引擎本身锁定在 Candle 上且需要 1–2 ms 极速冷启动时,才针对性编写原生 .metal / .ptx CustomOp。

下一课,我们将交付 rie-train v0.6.0,汇总 Apple Metal 与云端 NVIDIA L4 CUDA 的完整双端融合算子实测账单!

需登录才能记录进度

💬 关联讨论

加载中...