diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index fa7b613..4b26712 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -105,6 +105,20 @@ jobs: git -C "$ROOT" apply "$GITHUB_WORKSPACE/docker/patches/mlx-cuda-conv-plan-fallback.patch" python3 docker/test_mlx_conv_fallback.py --source "$SOURCE" + - name: Test MLX JIT CCCL install-dir patch + run: | + ROOT="$RUNNER_TEMP/mlx-jit-cccl" + mkdir -p "$ROOT/mlx/backend/cuda" + for FILE in CMakeLists.txt dirs.cpp; do + curl --fail --location --max-time 30 \ + "https://raw.githubusercontent.com/ml-explore/mlx/7a1d4f5c12ac82f4b4d0a6e71538d89ca0605247/mlx/backend/cuda/$FILE" \ + -o "$ROOT/mlx/backend/cuda/$FILE" + done + python3 docker/test_mlx_jit_cccl.py --source "$ROOT" --expect-broken + git -C "$ROOT" apply --check "$GITHUB_WORKSPACE/docker/patches/mlx-cuda-jit-cccl-install-dir.patch" + git -C "$ROOT" apply "$GITHUB_WORKSPACE/docker/patches/mlx-cuda-jit-cccl-install-dir.patch" + python3 docker/test_mlx_jit_cccl.py --source "$ROOT" + image-python: name: Image Python dependencies runs-on: ubuntu-latest diff --git a/docker/README.md b/docker/README.md index dd39431..b58b4fa 100644 --- a/docker/README.md +++ b/docker/README.md @@ -260,6 +260,18 @@ methods before and after patching. On an otherwise idle CUDA host, run See [dense grid memory checks](../docs/performance.md#dense-grid-memory-checks) for the GPU acceptance command and memory attribution. +`MIXLAB_MLX_CUDA_JIT_CCCL_FIX=1` marks a base whose MLX runtime-compiled +kernels always find MLX's own CCCL headers. `libmlx` is a static archive, so +MLX looks for them relative to the executable; a binary outside `/usr/local` +(any `go test` binary, or `mixlab` built elsewhere) used the CUDA toolkit's +older CCCL instead, which lacks `cuda::std::rint` and broke QAT and other fused +kernels on first compile. The patch compiles in the installed +`/usr/local/include/cccl` as the fallback; the executable-relative lookup still +comes first. `python3 docker/test_mlx_jit_cccl.py --source ` checks the +pinned CMake and `dirs.cpp` before and after patching, and the base and +architecture builds run `docker/test_mlx_jit_cccl_probe.cpp` against the +installed archive with NVRTC (no GPU needed), including a toolkit-only control. + ### Layer 1: Base image (CUDA + Go + MLX) Compiles MLX from source with CUDA backend for sm_80 (A100). diff --git a/docker/addarch.Dockerfile b/docker/addarch.Dockerfile index 8f5fd58..7fa9672 100644 --- a/docker/addarch.Dockerfile +++ b/docker/addarch.Dockerfile @@ -22,11 +22,13 @@ ARG ARCHS="80;86" ARG MLX_VERSION=v0.32.0 ARG MLX_COMMIT=7a1d4f5c12ac82f4b4d0a6e71538d89ca0605247 +COPY docker/test_mlx_jit_cccl_probe.cpp /tmp/test_mlx_jit_cccl_probe.cpp RUN test "${MIXLAB_MLX_BUILD_VERSION}" = "${MLX_VERSION}" \ && test "${MIXLAB_MLX_CUDA_WORKER_FIX}" = "1" \ && test "${MIXLAB_MLX_CONV_TRANSPOSE_GRAD_FIX}" = "1" \ && test "${MIXLAB_MLX_CUDA_ALLOCATOR_FIX}" = "2" \ && test "${MIXLAB_MLX_CUDA_CONV_PLAN_FIX}" = "1" \ + && test "${MIXLAB_MLX_CUDA_JIT_CCCL_FIX}" = "1" \ && test "${MIXLAB_MLX_BUILD_COMMIT}" = "${MLX_COMMIT}" \ && test "$(git -C /opt/mlx rev-parse HEAD)" = "${MLX_COMMIT}" \ && cd /opt/mlx/build \ @@ -34,6 +36,11 @@ RUN test "${MIXLAB_MLX_BUILD_VERSION}" = "${MLX_VERSION}" \ -DMLX_CUDA_ARCHITECTURES="${ARCHS}" -DCMAKE_BUILD_TYPE=Release -G Ninja \ && grep -Eq '^NCCL_LIBRARIES:FILEPATH=.*/libnccl' CMakeCache.txt \ && ninja -j4 \ - && ninja install + && ninja install \ + && mkdir -p /tmp/mlx-jit-cccl && cd /tmp/mlx-jit-cccl \ + && ar x /usr/local/lib/libmlx.a dirs.cpp.o \ + && g++ -std=c++17 /tmp/test_mlx_jit_cccl_probe.cpp dirs.cpp.o -I/usr/local/cuda/include \ + -L/usr/local/cuda/lib64 -Wl,-rpath,/usr/local/cuda/lib64 -lnvrtc -o probe \ + && ./probe /usr/local/include/cccl /usr/local/cuda/include WORKDIR /app diff --git a/docker/app.Dockerfile b/docker/app.Dockerfile index 39c4de9..4e74d2f 100644 --- a/docker/app.Dockerfile +++ b/docker/app.Dockerfile @@ -22,6 +22,8 @@ RUN test "${MIXLAB_MLX_CUDA_ALLOCATOR_FIX}" = "2" \ || { echo "Rebuild the MLX CUDA base and architecture tiers with the allocator reclaim fix" >&2; exit 1; } RUN test "${MIXLAB_MLX_CUDA_CONV_PLAN_FIX}" = "1" \ || { echo "Rebuild the MLX CUDA base and architecture tiers with the strict convolution plan fix" >&2; exit 1; } +RUN test "${MIXLAB_MLX_CUDA_JIT_CCCL_FIX}" = "1" \ + || { echo "Rebuild the MLX CUDA base and architecture tiers with the JIT CCCL install-dir fix" >&2; exit 1; } WORKDIR /app RUN apt-get update && apt-get install -y --no-install-recommends \ diff --git a/docker/base.Dockerfile b/docker/base.Dockerfile index 7b497b4..fa2d0d7 100644 --- a/docker/base.Dockerfile +++ b/docker/base.Dockerfile @@ -85,6 +85,17 @@ RUN python3 /tmp/test_mlx_allocator.py --source /opt/mlx/mlx/backend/cuda/alloca && python3 /tmp/test_mlx_allocator_retry.py --source /opt/mlx/mlx/backend/cuda/allocator.cpp ENV MIXLAB_MLX_CUDA_ALLOCATOR_FIX=2 +# A static libmlx finds its CCCL headers relative to the executable, so JIT +# kernels in binaries outside /usr/local (go test binaries) used the toolkit's +# CCCL 2.7, which lacks cuda::std::rint. Compile in the installed CCCL path. +COPY docker/patches/mlx-cuda-jit-cccl-install-dir.patch /tmp/mlx-cuda-jit-cccl-install-dir.patch +COPY docker/test_mlx_jit_cccl.py /tmp/test_mlx_jit_cccl.py +COPY docker/test_mlx_jit_cccl_probe.cpp /tmp/test_mlx_jit_cccl_probe.cpp +RUN python3 /tmp/test_mlx_jit_cccl.py --source /opt/mlx --expect-broken \ + && git -C /opt/mlx apply --check /tmp/mlx-cuda-jit-cccl-install-dir.patch \ + && git -C /opt/mlx apply /tmp/mlx-cuda-jit-cccl-install-dir.patch \ + && python3 /tmp/test_mlx_jit_cccl.py --source /opt/mlx + # Build MLX with sm_80 ONLY — minimal first tier. # KEEP the build directory for incremental arch additions. RUN cd /opt/mlx \ @@ -93,6 +104,12 @@ RUN cd /opt/mlx \ -DMLX_CUDA_ARCHITECTURES="80" -DCMAKE_BUILD_TYPE=Release -G Ninja \ && grep -Eq '^NCCL_LIBRARIES:FILEPATH=.*/libnccl' CMakeCache.txt \ && ninja -j4 \ - && ninja install + && ninja install \ + && mkdir -p /tmp/mlx-jit-cccl && cd /tmp/mlx-jit-cccl \ + && ar x /usr/local/lib/libmlx.a dirs.cpp.o \ + && g++ -std=c++17 /tmp/test_mlx_jit_cccl_probe.cpp dirs.cpp.o -I/usr/local/cuda/include \ + -L/usr/local/cuda/lib64 -Wl,-rpath,/usr/local/cuda/lib64 -lnvrtc -o probe \ + && ./probe /usr/local/include/cccl /usr/local/cuda/include +ENV MIXLAB_MLX_CUDA_JIT_CCCL_FIX=1 WORKDIR /app diff --git a/docker/patches/mlx-cuda-jit-cccl-install-dir.patch b/docker/patches/mlx-cuda-jit-cccl-install-dir.patch new file mode 100644 index 0000000..362304b --- /dev/null +++ b/docker/patches/mlx-cuda-jit-cccl-install-dir.patch @@ -0,0 +1,19 @@ +diff --git a/mlx/backend/cuda/CMakeLists.txt b/mlx/backend/cuda/CMakeLists.txt +index 065220e..5d3f2e5 100644 +--- a/mlx/backend/cuda/CMakeLists.txt ++++ b/mlx/backend/cuda/CMakeLists.txt +@@ -241,6 +241,14 @@ install(DIRECTORY ${cccl_SOURCE_DIR}/include/nv + if(MLX_BUILD_TESTS) + target_compile_definitions(mlx_dirs + PRIVATE MLX_CCCL_DIR="${cccl_SOURCE_DIR}/include") ++else() ++ # A static libmlx locates headers relative to the executable, so a binary ++ # outside the install prefix (such as a go test binary) would otherwise ++ # compile JIT kernels against the CUDA toolkit's older CCCL. Name the ++ # installed copy written by the install rules above. ++ include(GNUInstallDirs) ++ target_compile_definitions( ++ mlx_dirs PRIVATE MLX_CCCL_DIR="${CMAKE_INSTALL_FULL_INCLUDEDIR}/cccl") + endif() + + # Use fixed version of NVTX. diff --git a/docker/test_mlx_jit_cccl.py b/docker/test_mlx_jit_cccl.py new file mode 100644 index 0000000..a13d6d2 --- /dev/null +++ b/docker/test_mlx_jit_cccl.py @@ -0,0 +1,93 @@ +"""CPU-only test of where MLX's CUDA JIT looks for CCCL when it cannot find headers +next to the executable. + +Configures the pinned mlx/backend/cuda/CMakeLists.txt block that defines +MLX_CCCL_DIR into a scratch project, builds MLX's real dirs.cpp, and prints +cccl_dir(). Upstream defines it only for test builds, so a binary outside the +install prefix (a static libmlx resolves headers relative to the executable) +compiles JIT kernels against the CUDA toolkit's older CCCL. +""" + +import argparse +from pathlib import Path +import subprocess +import tempfile + + +START = "# The binary of C++ tests will not be installed" +END = "# Use fixed version of NVTX." + +MAIN = r""" +#include +namespace mlx::core::cu { +const char* cccl_dir(); +} +int main() { + const char* dir = mlx::core::cu::cccl_dir(); + std::printf("%s\n", dir ? dir : "(null)"); +} +""" + + +def extract_block(cmake): + text = cmake.read_text() + if text.count(START) != 1 or text.count(END) != 1: + raise SystemExit(f"{cmake}: expected exactly one MLX_CCCL_DIR block between fixed markers") + block = text[text.index(START):text.index(END)] + if "MLX_CCCL_DIR" not in block: + raise SystemExit(f"{cmake}: marker block no longer defines MLX_CCCL_DIR") + return block + + +def cccl_dir(source, block, build_tests, work): + project = work / ("tests-on" if build_tests else "tests-off") + project.mkdir() + (project / "main.cpp").write_text(MAIN) + (project / "CMakeLists.txt").write_text(f""" +cmake_minimum_required(VERSION 3.20) +project(mlx_jit_cccl_probe CXX) +set(CMAKE_CXX_STANDARD 17) +set(MLX_BUILD_TESTS {"ON" if build_tests else "OFF"}) +set(cccl_SOURCE_DIR "/mlx-build/_deps/cccl-src") +add_library(mlx_dirs OBJECT "{source / 'mlx/backend/cuda/dirs.cpp'}") +{block} +add_executable(probe main.cpp $) +""") + build = project / "build" + prefix = work / "prefix" + for cmd in (["cmake", "-S", str(project), "-B", str(build), f"-DCMAKE_INSTALL_PREFIX={prefix}"], + ["cmake", "--build", str(build)]): + result = subprocess.run(cmd, capture_output=True, text=True) + if result.returncode != 0: + raise SystemExit(f"{' '.join(cmd)} failed:\n{result.stdout}{result.stderr}") + out = subprocess.run([str(build / "probe")], check=True, capture_output=True, text=True) + return out.stdout.strip(), f"{prefix}/include/cccl" + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--source", type=Path, required=True, help="MLX source root") + parser.add_argument("--expect-broken", action="store_true", + help="assert the unpatched behaviour: no fallback outside test builds") + args = parser.parse_args() + source = args.source.resolve() + block = extract_block(source / "mlx/backend/cuda/CMakeLists.txt") + with tempfile.TemporaryDirectory() as tmp: + work = Path(tmp) + release, installed = cccl_dir(source, block, False, work) + tests, _ = cccl_dir(source, block, True, work) + # Test builds keep upstream's source-tree path either way. + if tests != "/mlx-build/_deps/cccl-src/include": + raise SystemExit(f"test build cccl_dir() = {tests!r}, want the CCCL source include dir") + if args.expect_broken: + if release != "(null)": + raise SystemExit(f"expected no fallback outside test builds, got {release!r}") + print("unpatched: non-test builds have no CCCL fallback (JIT can use the toolkit's CCCL)") + return + if release != installed: + raise SystemExit(f"non-test cccl_dir() = {release!r}, want installed headers {installed!r}") + print(f"patched: non-test builds fall back to {release}") + + +if __name__ == "__main__": + main() diff --git a/docker/test_mlx_jit_cccl_probe.cpp b/docker/test_mlx_jit_cccl_probe.cpp new file mode 100644 index 0000000..d40c597 --- /dev/null +++ b/docker/test_mlx_jit_cccl_probe.cpp @@ -0,0 +1,82 @@ +// GPU-free check of the installed static libmlx: its compiled-in CCCL fallback +// must name headers that NVRTC can use for cuda::std::rint, and the CUDA +// toolkit's own CCCL alone must not (the control that proves the check bites). +// +// Link only the archive member under test; the rest of libmlx needs the CUDA +// runtime. Build: ar x /usr/local/lib/libmlx.a dirs.cpp.o && g++ -std=c++17 \ +// test_mlx_jit_cccl_probe.cpp dirs.cpp.o -I/usr/local/cuda/include \ +// -L/usr/local/cuda/lib64 -lnvrtc +// Run: probe + +#include + +#include +#include +#include + +namespace mlx::core::cu { +const char* cccl_dir(); +} + +namespace { + +const char* kKernel = R"( +#include +#if !defined(CCCL_VERSION) || CCCL_VERSION < 3000000 +#error "CCCL older than 3.0 has no cuda::std::rint under NVRTC" +#endif +extern "C" __global__ void round_kernel(float* x) { x[0] = cuda::std::rint(x[0]); } +)"; + +bool compiles(const std::vector& include_dirs, std::string& log) { + nvrtcProgram prog; + if (nvrtcCreateProgram(&prog, kKernel, "probe.cu", 0, nullptr, nullptr) != NVRTC_SUCCESS) { + log = "nvrtcCreateProgram failed"; + return false; + } + std::vector args = {"--gpu-architecture=compute_80", "-std=c++17"}; + for (const auto& dir : include_dirs) { + args.push_back("--include-path=" + dir); + } + std::vector argv; + for (const auto& arg : args) { + argv.push_back(arg.c_str()); + } + const bool ok = nvrtcCompileProgram(prog, static_cast(argv.size()), argv.data()) == NVRTC_SUCCESS; + size_t size = 0; + nvrtcGetProgramLogSize(prog, &size); + log.assign(size, '\0'); + if (size > 0) { + nvrtcGetProgramLog(prog, log.data()); + } + nvrtcDestroyProgram(&prog); + return ok; +} + +} // namespace + +int main(int argc, char** argv) { + if (argc != 3) { + std::fprintf(stderr, "usage: %s \n", argv[0]); + return 2; + } + const std::string expected = argv[1]; + const std::string toolkit = argv[2]; + const char* dir = mlx::core::cu::cccl_dir(); + if (!dir || expected != dir) { + std::fprintf(stderr, "libmlx cccl_dir() = %s, want %s\n", dir ? dir : "(null)", expected.c_str()); + return 1; + } + std::string log; + // MLX passes the CCCL directory before the toolkit include directory. + if (!compiles({dir, toolkit}, log)) { + std::fprintf(stderr, "cuda::std::rint failed with libmlx's CCCL fallback:\n%s\n", log.c_str()); + return 1; + } + if (compiles({toolkit}, log)) { + std::fprintf(stderr, "control compiled with toolkit CCCL only; the probe no longer detects the defect\n"); + return 1; + } + std::printf("libmlx CCCL fallback %s compiles cuda::std::rint; toolkit-only control fails as expected\n", dir); + return 0; +} diff --git a/gpu/mlx_dependency_contract_test.go b/gpu/mlx_dependency_contract_test.go index 74ad079..39a0156 100644 --- a/gpu/mlx_dependency_contract_test.go +++ b/gpu/mlx_dependency_contract_test.go @@ -20,6 +20,11 @@ func TestCUDAImagePinsDistributedCapableMLX(t *testing.T) { "MIXLAB_MLX_CONV_TRANSPOSE_GRAD_FIX=1", "MIXLAB_MLX_CUDA_ALLOCATOR_FIX=2", "MIXLAB_MLX_CUDA_CONV_PLAN_FIX=1", + "MIXLAB_MLX_CUDA_JIT_CCCL_FIX=1", + "python3 /tmp/test_mlx_jit_cccl.py --source /opt/mlx --expect-broken", + "git -C /opt/mlx apply --check /tmp/mlx-cuda-jit-cccl-install-dir.patch", + "git -C /opt/mlx apply /tmp/mlx-cuda-jit-cccl-install-dir.patch", + "/tmp/test_mlx_jit_cccl_probe.cpp", "git -C /opt/mlx apply --check /tmp/mlx-cuda-conv-plan-fallback.patch", "python3 /tmp/test_mlx_conv_fallback.py --source /opt/mlx/mlx/backend/cuda/conv.cpp --expect-broken", "python3 /tmp/test_mlx_allocator_retry.py --source /opt/mlx/mlx/backend/cuda/allocator.cpp", @@ -45,6 +50,8 @@ func TestCUDAImagePinsDistributedCapableMLX(t *testing.T) { "MIXLAB_MLX_CONV_TRANSPOSE_GRAD_FIX", "MIXLAB_MLX_CUDA_ALLOCATOR_FIX", "MIXLAB_MLX_CUDA_CONV_PLAN_FIX", + `test "${MIXLAB_MLX_CUDA_JIT_CCCL_FIX}" = "1"`, + "/tmp/test_mlx_jit_cccl_probe.cpp", "NCCL_LIBRARIES:FILEPATH", } { if !strings.Contains(addarch, required) { @@ -86,6 +93,9 @@ func TestCUDAImagePinsDistributedCapableMLX(t *testing.T) { } } app := readRepositoryFile(t, "../docker/app.Dockerfile") + if !strings.Contains(app, `test "${MIXLAB_MLX_CUDA_JIT_CCCL_FIX}" = "1"`) { + t.Fatal("app image must reject an MLX base whose JIT can fall back to the toolkit's CCCL") + } if !strings.Contains(app, `test "${MIXLAB_MLX_CUDA_CONV_PLAN_FIX}" = "1"`) { t.Fatal("app image must reject an MLX base without strict convolution fallback") } @@ -118,6 +128,15 @@ func TestCUDAConvolutionFallbackPatchIsCoveredInCI(t *testing.T) { } } +func TestCUDAJITCCCLPatchIsCoveredInCI(t *testing.T) { + ci := readRepositoryFile(t, "../.github/workflows/ci.yml") + for _, required := range []string{"mlx-cuda-jit-cccl-install-dir.patch", "test_mlx_jit_cccl.py", "--expect-broken", pinnedMLXCommit + "/mlx/backend/cuda/$FILE", "CMakeLists.txt dirs.cpp"} { + if !strings.Contains(ci, required) { + t.Errorf("CI missing %s", required) + } + } +} + func TestCUDAJITDispatchUsesBackendDevice(t *testing.T) { dispatch := readRepositoryFile(t, "cuda_kernel_dispatch.cpp") if !strings.Contains(dispatch, "mx::cu::device(stream.device)") {