Build a PyTorch ReLU kernel with Hugging Face Kernels

Build and load a PyTorch ReLU kernel for CPU and Metal with Hugging Face Kernels, Nix builds and automatic selection of local artifacts.

Player not loading? Watch on YouTube

The presenter walks through a ReLU kernel project using Hugging Face Kernels, then builds it and runs it from Python. The library standardizes how kernels are packaged and loaded. Compiled artifacts can live on the Hugging Face Hub, local disk or network storage, separate from installed Python packages.

The demo runs on an arm64 MacBook. It covers a CPU implementation with NEON intrinsics and Metal kernels for Apple GPUs, followed by PyTorch operation registration, a Python wrapper and build.toml configuration. CUDA and ROCm are omitted. The presenter explains that native PyTorch operation registration allows torch.compile to capture the operation, but does not demonstrate compilation with torch.compile.

The Nix-based kernel builder uses cached dependencies. After an initial cached build, the presenter makes a small change to trigger a rebuild. The outputs contain CPU and Metal artifacts for PyTorch 2.9 and 2.10. The walkthrough also explains how unique hashes prevent Python naming conflicts between kernel versions.

A final Python script calls get_local_kernel with the local artifact directory. The loader selects the PyTorch 2.10 Metal build for the demonstrated environment. Running ReLU turns negative tensor values into zero and leaves positive values unchanged.

The focus is packaging, building and runtime loading. Kernel implementation details receive a brief walkthrough, and publishing artifacts to the Hub is discussed rather than demonstrated.