Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 16 additions & 1 deletion .github/workflows/build_kernel.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,22 @@ jobs:
run: nix-shell -p nix-info --run "nix-info -m"

- name: Build all example kernels
run: nix build -L ./examples/kernels#ci-build-cuda
run: |
args=()
pin=kernels-ci-relu-compiler-cache-${{ matrix.arch }}
# Use the pin API since older Cachix clients lack pins get.
if seed=$(curl -fsSL --max-time 15 https://app.cachix.org/api/v1/cache/huggingface/pin |
jq -er --arg pin "$pin" '.[] | select(.name == $pin and (.lastRevision.orphaned | not)) | .lastRevision.storePath') &&
[[ "$seed" == /nix/store/*-relu-torch-ext-compilerCache ]] &&
nix copy --from https://huggingface.cachix.org "$seed"; then
args=(--override-input compiler-cache-seed "path:$seed")
fi
nix build -L --no-write-lock-file "${args[@]}" ./examples/kernels#ci-build-cuda
if [ "${{ github.ref }}" = refs/heads/main ] &&
cache=$(nix build --no-write-lock-file --no-link --print-out-paths "${args[@]}" ./examples/kernels#reluCompilerCache) &&
cachix push huggingface "$cache"; then
cachix pin huggingface "$pin" "$cache" --keep-revisions 1 || true
fi
- name: Build all kernel builder test kernels
run: nix build -L ./nix-builder/tests/kernels#ci-build-cuda -o result-tests
- name: Build and test kernel builder test SDKs
Expand Down
24 changes: 24 additions & 0 deletions docs/source/builder/build.md
Original file line number Diff line number Diff line change
Expand Up @@ -274,3 +274,27 @@ because there is no GPU available in the build sandbox.
Generating a kernel's public API symbols (`symbols.json`) also requires
importing the kernel. So, when the `get_kernel` check is disabled, the build
variants will not contain a `symbols.json` file.

## Reusing CUDA compilation in CI (experimental)

Set `cudaCompilerCache = { };` in the arguments to
`kernel-builder.lib.genKernelFlakeOutputs` to produce a `compilerCache` output
alongside each supported redistributable variant. This enables the cache for
Torch CUDA builds on Linux with CUDA 12.5 or newer and a matching ptxas version;
other builds are unchanged.
The default, `cudaCompilerCache = null`, disables caching.

On a subsequent build, supply the previous variant's cache output, for example
`cudaCompilerCache."torch213-cu126-x86_64-linux" = previous.compilerCache;`
where `previous` is the corresponding earlier build derivation. The cache is
copied into the writable build output, never modified in the Nix store.
CI can distribute this output using its existing trusted Nix binary cache.
Use a Nix store input, rather than a plain string containing a store path.
The ReLU example takes its seed from a non-flake input, which CI can supply
with `--override-input compiler-cache-seed path:/nix/store/…-compilerCache`
without impure evaluation.

NVCC still runs preprocessing, host compilation, and linking normally. Only
recognized CUDA frontend and device compilation stages use sccache; unsupported
stage invocations run uncached. No kernel sources need to be partitioned or
changed. Cache seeds must come from trusted builds, just like binary substitutes.
18 changes: 16 additions & 2 deletions examples/kernels/flake.nix
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,17 @@

inputs = {
kernel-builder.url = "path:../..";
compiler-cache-seed = {
follows = "";
flake = false;
};
};

outputs =
{
self,
kernel-builder,
compiler-cache-seed,
}:
let
inherit (kernel-builder.inputs) flake-utils nixpkgs;
Expand All @@ -30,7 +35,7 @@
;

# All example kernels to build in CI.
ciKernels = [
ciKernels = system: [
# This test should check the capabilities of the oldest supported CUDA.
{
name = "relu-kernel";
Expand All @@ -54,6 +59,8 @@
{
name = "relu-kernel-cu13";
path = ./relu;
cudaCompilerCache."torch${torchVersion}-${cuda13Version}-${system}" =
if compiler-cache-seed ? outputs then null else compiler-cache-seed.outPath;
drv =
sys: out: out.packages.${sys}.redistributable.${"torch${torchVersion}-${cuda13Version}-${sys}"};
checkCudaCapabilities = [
Expand Down Expand Up @@ -324,7 +331,6 @@
}
];

ciKernelOutputs = mkKernelOutputs' ciKernels;
ciRocmKernelOutputs = mkKernelOutputs' ciRocmKernels;
ciXpuKernelOutputs = mkKernelOutputs' ciXpuKernels;
ciTpuKernelOutputs = mkKernelOutputs' ciTpuKernels;
Expand All @@ -338,12 +344,17 @@

mkCiBuild' = mkCiBuild pkgs system;

ciKernelOutputs = mkKernelOutputs' (ciKernels system);
ci-build-cuda = mkCiBuild' "ci-kernels-cuda" ciKernelOutputs;
ci-build-rocm = mkCiBuild' "ci-kernels-rocm" ciRocmKernelOutputs;
ci-build-xpu = mkCiBuild' "ci-kernels-xpu" ciXpuKernelOutputs;
ci-build-tpu = mkCiBuild' "ci-kernels-tpu" ciTpuKernelOutputs;
ci-build-metal = mkCiBuild' "ci-kernels-metal" ciMetalKernelOutputs;
ci-build-cpu = mkCiBuild' "ci-kernels-cpu" ciCpuKernelOutputs;

reluKernel = pkgs.lib.findFirst (
kernel: kernel.name == "relu-kernel-cu13"
) (throw "ReLU example is missing from CI kernels") ciKernelOutputs;
in
{
packages = {
Expand All @@ -356,6 +367,9 @@
ci-build-cpu
;
default = ci-build-cuda;
}
// pkgs.lib.optionalAttrs pkgs.stdenv.hostPlatform.isLinux {
reluCompilerCache = (reluKernel.drv system reluKernel.outputs).compilerCache;
};
}
);
Expand Down
8 changes: 8 additions & 0 deletions examples/kernels/relu/flake.nix
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,23 @@

inputs = {
kernel-builder.url = "path:../../..";
compiler-cache-seed = {
follows = "";
flake = false;
};
};

outputs =
{
self,
kernel-builder,
compiler-cache-seed,
}:
kernel-builder.lib.genKernelFlakeOutputs {
inherit self;
path = ./.;
# The default follows the root flake; CI overrides it with a cache directory.
cudaCompilerCache."torch213-cu132-x86_64-linux" =
if compiler-cache-seed ? outputs then null else compiler-cache-seed.outPath;
};
}
11 changes: 10 additions & 1 deletion flake.nix
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,9 @@
# load the part with this functionality.
doGetKernelCheck ? true,

# Null disables caching, otherwise cache seeds by build variant.
cudaCompilerCache ? null,

pythonCheckInputs ? pkgs: [ ],
pythonNativeCheckInputs ? pkgs: [ ],
torchVersions ? _: torchVersions',
Expand All @@ -131,7 +134,13 @@
pythonCheckInputs
pythonNativeCheckInputs
;
build = buildPerSystem.${system};
build =
if cudaCompilerCache == null then
buildPerSystem.${system}
else
nixpkgs.legacyPackages.${system}.callPackage ./nix-builder/lib/build.nix {
inherit cudaCompilerCache;
};
buildSets = buildSetsPerSystem.${system} or [ ];
}
);
Expand Down
12 changes: 12 additions & 0 deletions nix-builder/lib/build.nix
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
{
lib,
pkgs,
cudaCompilerCache ? null,

# Every `buildSets` argument is a list of build sets. Each build set is
# a attrset of the form
Expand Down Expand Up @@ -32,6 +33,9 @@ let
builtins.readFile ../../kernel-builder/src/rocm_supported_archs.json
);
in
assert lib.assertMsg (
cudaCompilerCache == null || builtins.isAttrs cudaCompilerCache
) "cudaCompilerCache must be null or an attribute set of cache seeds by build variant";
rec {
# Source set function to create a fileset for a path
mkSourceSet = import ./source-set.nix { inherit lib; };
Expand Down Expand Up @@ -320,6 +324,14 @@ rec {

inherit torchStableAbiVersion;

cudaCompilerCache =
if cudaCompilerCache == null then
null
else
{
seed = cudaCompilerCache.${variants.kernelVariant kernelConfig} or null;
};

buildLayout = kernelConfig.buildLayout;
kernelName = kernelConfig.name;
doAbiCheck = true;
Expand Down
28 changes: 26 additions & 2 deletions nix-builder/lib/extension/torch/arch.nix
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
cmakeNvccThreadsHook,
hipccThreadsHook,
cuda_nvcc,
mkCudaCompilerCache,
generate-symbols-hook,
get-kernel-check,
hash-kernel-hook,
Expand Down Expand Up @@ -43,6 +44,9 @@
{
buildConfig,

# Null disables compiler caching. Otherwise the seed may be null for a cold build.
cudaCompilerCache ? null,

# Whether to do ABI checks.
doAbiCheck ? true,

Expand Down Expand Up @@ -132,10 +136,25 @@ let

cpuSupport = buildConfig.cpu or false;

in
# CUDA 12.5 introduced CICC_PATH in nvcc.profile. Do not cache mixed
# CUDA driver and ptxas toolchains.
cacheEnabled =
cudaCompilerCache != null
&& cudaSupport
&& lib.versionAtLeast cuda_nvcc.version "12.5"
&& (buildConfig.ptxasVersion or buildConfig.cudaVersion) == buildConfig.cudaVersion
&& lib.versions.majorMinor cuda_nvcc.version == buildConfig.cudaVersion
&& stdenv.hostPlatform.isLinux;
cache = mkCudaCompilerCache cuda_nvcc;
cacheSeed = cudaCompilerCache.seed or null;

in
assert lib.assertMsg (
!cacheEnabled || cacheSeed == null || builtins.hasContext (toString cacheSeed)
) "A CUDA compiler cache seed must be a Nix store input (e.g. previous.compilerCache)";
stdenv.mkDerivation (prevAttrs: {
name = "${kernelName}-torch-ext";
outputs = [ "out" ] ++ lib.optional cacheEnabled "compilerCache";

inherit
buildLayout
Expand Down Expand Up @@ -208,8 +227,9 @@ stdenv.mkDerivation (prevAttrs: {
]
++ lib.optionals cudaSupport [
cmakeNvccThreadsHook
cuda_nvcc
(if cacheEnabled then cache.compiler else cuda_nvcc)
]
++ lib.optionals cacheEnabled [ cache.hook ]
++ lib.optionals rocmSupport [
hipccThreadsHook
clr
Expand Down Expand Up @@ -271,6 +291,10 @@ stdenv.mkDerivation (prevAttrs: {
// lib.optionalAttrs cudaSupport {
CUDAToolkit_ROOT = "${lib.getDev cudaPackages.cuda_nvcc}";
}
// lib.optionalAttrs cacheEnabled {
cudaCompilerCacheSalt = "${variant}-${cache.salt}-${torch}";
cudaCompilerCacheSeed = if cacheSeed == null then "" else toString cacheSeed;
}
// lib.optionalAttrs xpuSupport {
MKLROOT = oneapi-torch-dev;
SYCL_ROOT = oneapi-torch-dev;
Expand Down
2 changes: 2 additions & 0 deletions nix-builder/overlay.nix
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,8 @@ final: prev:
# Make the source for a package from our cargo workspace.
mkKernelsRustSrc = final.callPackage ./pkgs/mk-kernels-rust-src { };

mkCudaCompilerCache = final.callPackage ./pkgs/cuda-compiler-cache { };

nvtx = final.callPackage ./pkgs/nvtx { };

metal-cpp = final.callPackage ./pkgs/metal-cpp { };
Expand Down
111 changes: 111 additions & 0 deletions nix-builder/pkgs/cuda-compiler-cache/cuda-cache-stage.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
# The driver has already preprocessed the source for this architecture. Only
# cache the known single-input CUDA compilation stages, not host compilation.
real=$1
shift
args=("$@")
passthrough() { exec "$real" "${args[@]}"; }

[[ ${KERNEL_CUDA_CACHE_ACTIVE:-} == 1 ]] || passthrough

tool=${real##*/}
case "$tool" in
ptxas) suffix=.ptx ;;
cicc) suffix=.cpp1.ii ;;
cudafe++) suffix=.cpp4.ii ;;
*) passthrough ;;
esac

# The sccache adapters reconstruct commands on misses. Restrict each adapter
# to the argument and artifact layout emitted by the tested driver.
declare -A options=()
input=
genModuleId=0
while (( $# )); do
case "$tool:$1" in
cicc:--orig_src_path_name|cudafe++:--orig_src_path_name|\
cicc:--orig_src_file_name|cudafe++:--orig_src_file_name|\
cicc:--gen_c_file_name|cudafe++:--gen_c_file_name|\
cicc:--stub_file_name|cudafe++:--stub_file_name|\
cicc:--module_id_file_name|cudafe++:--module_id_file_name|\
cicc:--gen_device_file_name|cicc:--include_file_name|cicc:-arch|cicc:-o|ptxas:-o)
(( $# >= 2 )) || passthrough
[[ -z ${options[$1]+set} && -n $2 && $2 != -* && $2 != *"$suffix" ]] || passthrough
options[$1]=$2
shift
;;
cudafe++:--gen_module_id_file)
(( genModuleId == 0 )) || passthrough
genModuleId=1
;;
ptxas:-arch=sm_[0-9]*|ptxas:-m64|ptxas:--compile-only|ptxas:-c|ptxas:-v|ptxas:--verbose|\
cicc:--gnu_version=[0-9]*|cudafe++:--gnu_version=[0-9]*|\
cicc:--c++17|cudafe++:--c++17|cicc:--c++20|cudafe++:--c++20|\
cicc:--c++14|cudafe++:--c++14|cicc:--c++11|cudafe++:--c++11|\
cicc:--display_error_number|cudafe++:--display_error_number|\
cicc:--static-host-stub|cudafe++:--static-host-stub|\
cicc:--device-hidden-visibility|cudafe++:--device-hidden-visibility|\
cicc:--allow_managed|cudafe++:--allow_managed|\
cicc:--extended-lambda|cudafe++:--extended-lambda|\
cicc:--relaxed_constexpr|cudafe++:--relaxed_constexpr|\
cicc:-m64|cudafe++:--m64|cudafe++:--parse_templates|\
cicc:--no-version-ident|cicc:-ftz=[01]|cicc:-prec_div=[01]|cicc:-prec_sqrt=[01]|\
cicc:-fmad=[01]|cicc:-fast-math|cicc:--gen_div_approx_ftz|cicc:-tused|\
cicc:-extra-device-vectorization|cicc:--device-c|cudafe++:--device-c|\
cicc:--diag_suppress=*|cudafe++:--diag_suppress=*|\
cicc:--diag_warn=*|cudafe++:--diag_warn=*|cicc:--diag_error=*|cudafe++:--diag_error=*)
;;
*:*"$suffix")
[[ -z $input && $1 == /* && -f $1 ]] || passthrough
# The cudafe adapter expects the input to be the final argument.
[[ $tool != cudafe++ || $# == 1 ]] || passthrough
input=$1
;;
*) passthrough ;;
esac
shift
done

[[ -n $input ]] || passthrough
outputs=()
case "$tool" in
ptxas)
outputs=("${options[-o]:-}")
;;
cicc)
moduleId=${options[--module_id_file_name]:-}
[[ -f $moduleId && $moduleId != *:* ]] || passthrough
outputs=("${options[-o]:-}" "${options[--gen_c_file_name]:-}" \
"${options[--stub_file_name]:-}" "${options[--gen_device_file_name]:-}")
;;
cudafe++)
(( genModuleId == 1 )) || passthrough
outputs=("${options[--gen_c_file_name]:-}" "${options[--module_id_file_name]:-}")
;;
esac

# All produced artifacts belong to the launcher's private intermediate directory.
for out in "${outputs[@]}"; do
[[ -n $out && ${out%/*} == "${input%/*}" ]] || passthrough
done

# The front ends receive the original source in addition to the preprocessed
# input. For cicc, the module ID is also an input produced by cudafe++.
if [[ $tool != ptxas ]]; then
source=${options[--orig_src_path_name]:-}
[[ -f $source && $source != *:* ]] || passthrough
export SCCACHE_EXTRAFILES="$source"
if [[ $tool == cicc ]]; then
export SCCACHE_EXTRAFILES="$source:$moduleId"
fi
fi

# Hash the complete command, including output paths that sccache normally
# ignores, and the paths used by the CUDA tools to resolve their own inputs.
export SCCACHE_C_CUSTOM_CACHE_BUSTER=$(printf '%s\0' \
"$SCCACHE_C_CUSTOM_CACHE_BUSTER" "$PWD" "${NVVMIR_LIBRARY_DIR:-}" \
"${LD_LIBRARY_PATH:-}" "${SOURCE_DATE_EPOCH:-}" "${args[@]}" | sha256sum | cut -d' ' -f1)

sccache "$real" "${args[@]}" || passthrough
for out in "${outputs[@]}"; do
[[ -f $out ]] || passthrough
done
Loading
Loading