Skip to content

[CUDA] Move large host-built arrays to device memory - #4868

Merged
zcbenz merged 4 commits into
ml-explore:mainfrom
arcusbuilds:fix/cuda-host-memory-3861
Nov 28, 2026
Merged

zcbenz merged 4 commits into
ml-explore:mainfrom
arcusbuilds:fix/cuda-host-memory-3861

Conversation

@arcusbuilds

Copy link
Copy Markdown
Contributor

Fixes #3861

On platforms without managed memory (Windows, WSL, Tegra), arrays built from host data stayed in host memory, and the allocator could also hand a cached pinned host buffer to a GPU allocation. Either way, kernels read over PCIe, and a 4096x4096 matmul ran ~80x slower.

The allocator now skips host buffers when serving GPU allocations from the cache, and host-built arrays are copied to device memory once at creation. Tests added for both.

RTX 2000 Ada, Windows 11, CUDA 13.2: ~700 ms to 8.7-8.9 ms, matching the device case.

  • ☑️ I understand it is strictly prohibited to use AI to write PR description
  • AI usage disclosure: I used Claude to understand the codebase and to generate parts of the code. I reviewed and tested all of it.

@arcusbuilds arcusbuilds changed the title [CUDA] Do not reuse cached pinned host buffers for device allocations [CUDA] Fix slow host-built arrays on platforms without managed memory Nov 11, 2026
@arcusbuilds
arcusbuilds marked this pull request as ready for review November 11, 2026 18:45
@reevesc88

Copy link
Copy Markdown

@codex review

2 similar comments
@reevesc88

Copy link
Copy Markdown

@codex review

@reevesc88

Copy link
Copy Markdown

@codex review

@strayberry

strayberry commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

I ran into the same host-memory residency issue in my C++ inference project and already carry a local fix for direct device-memory imports and host/device cache separation. I tested this PR at 2f93509d6 against my downstream residency regression. It covers the core behavior I needed.

Independent Windows measurements:

  • RTX 4060 Ti 16 GiB, Windows 11/WDDM, driver 610.88, CUDA 13.0.48, MSVC 19.44; concurrentManagedAccess=0.
  • CPU+CUDA shared build. Both runtimes include the same [CUDA] Avoid releasing DXGI adapters during DLL teardown #4867 teardown fix; the A/B source difference is this PR.
  • FP32 matvec: [1, 8192] @ [8192, 4096], one retained 128 MiB weight matrix. Three fresh processes per runtime, three warmups and 16 measured iterations per path in each process, with output checks. Values below are medians of the three per-process means.
Path Baseline With #4868
Imported weights 10.5565 ms 0.593481 ms
Deliberately retained host-weight control 10.7107 ms 10.5831 ms

That is about 17.8x faster for this matvec. These are baseline-versus-your-PR results, not a comparison with my local implementation or an end-to-end model benchmark.

The downstream residency regression fails on the baseline and passes with this PR in all three runs. It also checks exact packed bytes, source-deleter completion, cross-thread/stream use, repeated allocation/reload, CPU-default imports, and explicit CPU readback. In a separate 256 MiB weight test, the live buffers move from host to device memory; process private bytes did not decrease, so I am not claiming lower host-memory usage.

I also found a Windows shared-library test-link problem. The DLL builds, but linking the exact tests/tests.cpp and tests/cuda_tests.cpp against it fails with LNK2019/LNK1120 for these unexported functions, even with MLX_EXPORT_ALL_SYMBOLS=ON:

mlx::core::cu::allocator()
mlx::core::cu::CudaAllocator::malloc_async(size_t, int, cudaStream_t)

This was a focused build of those test sources, not a full upstream test-suite build. The following test-only change avoids the internal function calls while preserving the host-cache reuse check:

diff --git a/tests/cuda_tests.cpp b/tests/cuda_tests.cpp
--- a/tests/cuda_tests.cpp
+++ b/tests/cuda_tests.cpp
@@ -133,19 +133,17 @@ TEST_CASE("test cached host buffer is not reused for device output") {
     return;
   }
   clear_cache();
-  auto& alloc = cu::allocator();
-  cudaStream_t stream;
-  REQUIRE_EQ(cudaStreamCreate(&stream), cudaSuccess);
   constexpr size_t size = 1 << 22;
-  // Put a host buffer into the size-keyed cache.
-  alloc.free(alloc.malloc(size));
-  auto buf = alloc.malloc_async(size, 0, stream);
+  {
+    auto host = allocator::malloc(size);
+  }
+  auto s = default_stream(Device::gpu);
+  auto output = zeros({static_cast<int>(size / sizeof(float))}, float32, s);
+  eval(output);
   CHECK_NE(
-      residency(static_cast<cu::CudaBuffer*>(buf.ptr())->data),
+      residency(static_cast<cu::CudaBuffer*>(output.buffer().ptr())->data),
       cudaMemoryTypeHost);
-  alloc.free(buf);
-  CHECK_EQ(cudaStreamSynchronize(stream), cudaSuccess);
-  CHECK_EQ(cudaStreamDestroy(stream), cudaSuccess);
+  synchronize(s);
 }
 
 TEST_CASE("test host data is moved to device memory") {

With this test change, all 6 cases / 26 assertions pass with your runtime in three consecutive runs. Against the baseline, the same tests still detect both residency failures in all three runs (4/6 cases and 24/26 assertions pass). No production code changes were needed.

@reevesc88

Copy link
Copy Markdown

@codex review

Please review current head 2f93509 for CUDA allocation correctness, host/device copies, cache reuse, lifetime, and tests on systems without managed memory.

Without concurrentManagedAccess (Windows, WSL, Tegra) host buffers are
cudaMallocHost memory. The buffer cache is keyed on size only, so a freed
host buffer could back a later device allocation and every kernel touching
it went over PCIe.

Refs ml-explore#3861
Without concurrentManagedAccess (Windows, WSL, Tegra) arrays created from
host data lived in cudaMallocHost memory for their lifetime, so kernels read
them over PCIe (matmul ~80x slower). Copy them to device memory when they
are imported, before any other thread can see them, including GGUF tensors.
The copy is synchronous on the allocator's free stream, so it does not wait
on queued kernels. Buffers under one page stay on the host, where a copy and
a sync cost more than reading them over PCIe. If the device is out of memory
the data stays on the host.

Fixes ml-explore#3861
Both cases fail without the previous two commits. They only run where host
memory is pinned (no concurrentManagedAccess), as with managed memory they
pass either way.
@zcbenz
zcbenz force-pushed the fix/cuda-host-memory-3861 branch 2 times, most recently from 653f325 to 88b72b3 Compare November 28, 2026 05:54
@zcbenz

zcbenz commented Nov 28, 2026

Copy link
Copy Markdown
Member

I pushed some changes to simplify the implementation and unify some inconsistent interfaces. Note that one change is that it no longer checks host buffer when reusing from buffer cache, which is very inefficient, and not necessary because the output buffers are always allocated on device memory. Please let me know if there are performance regressions.

@zcbenz
zcbenz force-pushed the fix/cuda-host-memory-3861 branch 3 times, most recently from a33beb0 to 17a5464 Compare November 28, 2026 06:16
@zcbenz

zcbenz commented Nov 28, 2026

Copy link
Copy Markdown
Member

Another change is that large arrays are always moved to device memory, even when the device has native unified memory, because from our experience unified memory can actually result in slower memory bandwidth on Blackwell hardwares and this is something that we actually wanted to fix long time ago.

@zcbenz
zcbenz force-pushed the fix/cuda-host-memory-3861 branch from 17a5464 to 5152afc Compare November 28, 2026 06:21
@zcbenz zcbenz changed the title [CUDA] Fix slow host-built arrays on platforms without managed memory [CUDA] Move large host-built arrays to device memory Nov 28, 2026
@zcbenz
zcbenz force-pushed the fix/cuda-host-memory-3861 branch from 5152afc to 79139e8 Compare November 28, 2026 06:32
@zcbenz
zcbenz merged commit 048620b into ml-explore:main Nov 28, 2026
24 checks passed
Brooooooklyn added a commit to mlx-node/mlx that referenced this pull request Nov 29, 2026
…aph limits, and Win32 NVRTC/PTX fixes

Adapted for upstream:
- ml-explore#4885: use private cache_memory_locked() and memory_limit_locked() while
  holding mutex_ in malloc_async()/free() to avoid recursive mutex deadlock,
  preserving overflow asserts.
- ml-explore#4868: preserve move_to_device_memory() / cuda_malloc_async() / cuda_free_async().
- ml-explore#4711: preserve debug track_allocation/untrack_allocation and registered_data_ptrs_.
- ml-explore#4706: preserve BIN_DIR macro and try/catch in delayload.cpp alongside
  resolve_bin_dir(), std::error_code guards, and unconditional nvrtc-builtins preload.
- ml-explore#4745: preserve force_single_root_/roots_/get_noop_kernel_ptr() in cuda/device.{h,cpp}.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

matmul ~36× slower than cuBLAS on Windows when data are allocated in host

4 participants