Skip to content

CUDA needs a maintained device-resident corpus path for dynamic CPU/GPU programs on WSL2 #1066

Closed as not planned

Description

@SiliconState

What Bend should do

Add a maintained CUDA memory mode for devices where managed memory exists but CU_DEVICE_ATTRIBUTE_CONCURRENT_MANAGED_ACCESS == 0 notably NVIDIA CUDA under WSL2 that keeps the Bend corpus in VRAM and synchronizes only state the host actually reads or writes.

The goal is not to optimize selected benchmark winners. It is to make long-lived, dynamic Bend programs viable when they repeatedly alternate:

host mutates a device-built graph
-> ! device rewrite/fold
-> host consumes and rebuilds parts
-> ! again

A production design should preserve normal Bend semantics across arbitrary repeated CPU/GPU seams and should avoid copying every potentially live word at each ! boundary. Possible implementations include explicit dirty chunks/pages, generated write barriers, or another upstream-owned ownership protocol. If demand paging is used, CUDA calls should run on a helper thread rather than directly from a SIGSEGV handler.

This request is specifically for the existing NVIDIA CUDA lane. It complements #891: that issue proved the device-corpus and dirty-chunk approach on AMD/HIP, but was declined for main because the team lacked AMD hardware. The same architectural limitation and solution have now been independently reproduced on an RTX 5090 through CUDA.

Why

Stock Bend's CUDA runtime requires concurrent managed access. WSL2 reports:

CU_DEVICE_ATTRIBUTE_MANAGED_MEMORY             1
CU_DEVICE_ATTRIBUTE_CONCURRENT_MANAGED_ACCESS  0

So stock Bend refuses the device and silently runs ! on CPU unless GPU use is forced, in which case it reports no device. A serialized host-attached managed-memory mode is semantically workable but not useful: on 11 of 16 upstream runtime benchmarks it was 45x to 547x slower than CPU-16 because kernels read host memory over the WSL/PCIe path.

I then implemented a research-only CUDA twin on upstream commit b7ebee9217c8813067e200b0c0c9153a3be31c5e:

  • keep the normal host corpus;
  • allocate an equal corpus in VRAM with cuMemAlloc;
  • copy the header, live ring slots/counters, static image, heap under the bump and live bank entries up before each ! turn;
  • run every pass against the VRAM pointer;
  • copy the same regions down after the turn.

This is an intentionally simple eager implementation, not a proposed production patch. It establishes that WSL can fully execute Bend's CUDA kernels when the corpus is actually in VRAM:

  • all 16 bench/runtime outputs matched CPU/pinned outputs;
  • GPU beat CPU-16 on 9/16 cases;
  • strongest measured wins were gameoflife 3.20x, nbody 2.69x and mandelbrot 2.27x;
  • geometric mean was still about 10% slower than CPU-16 because eager synchronization dominates dynamic/irregular cases.

The decisive dynamic test was a single process with ten ! turns. A depth-16 tree alternated between a host-only sequential rebuild (every node replaced, including reused heap slots) and a device mirror (every node rewritten), followed by a marked fold. CPU and GPU both printed:

854543159

The CUDA statistics were:

10 turns, 0.092 s in turns, 0.089 s copying 610.3 MB

So 96.7% of GPU-turn time was synchronization, not computation. Whole execution was 0.227 s versus 0.006 s for the already-built CPU binary. This is the real dynamic workload problem: adding more kernels or tuning launch geometry cannot recover time spent copying mutable runtime state at every boundary.

Additional bounded experiments:

  • A three-turn merkle run moved 691.3 MB and spent 147 of 155 ms of turn time copying (~95%).
  • Fully pinned transfers were much faster, but registering 768 MB cost about 190 ms and cuMemHostAlloc(768MB) cost about 318 ms; a short dynamic process cannot amortize either.
  • Lazy registration halved copy time but paid ~47 ms registration inside the turns and did not beat the eager best.
  • Adjacent host registrations do not merge for a transfer whose first page is pinned under this WSL/DXG driver; boundary-sensitive schemes failed with CUDA_ERROR_INVALID_VALUE.
  • Skipping heap download is unsound: host evaluation writes freed/reused words (TERM_HOLE, allocator updates) below the old bump.
  • Ring data was already contiguous; merging copy ranges did not reduce bytes.
  • The .gpu module is a cubin/fatbin, so load-time PTX JIT was not the missing cost.

#891's later dirty-chunk HIP result is the important positive evidence: reducing tree-radix from 3.7 GB copied to 17 MB turned several losses into wins and supported repeated host mutation. Its author also identified the production concern: calling HIP copy APIs directly in a SIGSEGV handler is not POSIX-safe; a helper-thread design is the clean version.

What I am asking upstream to own is the abstraction boundary, not this local twin:

  1. A device-resident corpus mode in the CUDA lane for non-concurrent managed-memory devices.
  2. Correct repeated host/device mutation, including frees/reuse below the bump and multiple ! turns in one process.
  3. Dirty-range synchronization or another mechanism whose cost scales with host-touched state, not the whole live heap.
  4. Explicit diagnostics/telemetry for lane selection and transfer volume, so silent CPU fallback and copy-bound execution are visible.
  5. Tests with dynamic graph/tree mutation around multiple ! calls, not only one-shot static kernels.

Without this, WSL users can either get silent CPU execution, catastrophically slow host-backed kernels, or maintain a large out-of-tree copying runtime. The last option is what we tested and are deliberately stopping: it proves the need, but it is too complex and too eager to be the solution.

Environment and evidence scope

  • RTX 5090 (sm_120), NVIDIA driver 610.62
  • Ubuntu 26.04 / WSL2, kernel 6.18.33.2-microsoft-standard-WSL2
  • CUDA 13.1 / NVRTC 13.1.115, clang 21.1.8
  • CUDA twin source base: b7ebee9217c8813067e200b0c0c9153a3be31c5e
  • Current upstream main inspected: 47bed75adedd6d6dd811721905f06569bf465f85
  • Every GPU attempt was serialized, heap-capped, timeout-bounded, and checked against CPU output; VRAM returned to 0 MiB after runs.

Activity

  1. SiliconState commented on Sep 25, 2026

    @SiliconState
    Author

    Complete ten-turn dynamic reproducer used for the 610.3 MB / 96.7% copy measurement:

    # Dynamic host/device seam stress used for Bend issue #1066.
    # Ten ! turns alternate with host rebuilding of a device-built tree.
    import Base
    
    type Tr is Data:
      Lf{v: U32}
      Nd{l: Tr, r: Tr}
    
    def gen(+n: Nat, +x: U32) -> Tr:
      match n:
        case 0n:
          Lf{x}
        case 1n+p:
          l r = gen(p, U32.shl(x)) gen(p, U32.inc(U32.shl(x)))
          Nd{l, r}
    
    def sum(t: Tr) -> U32:
      match t:
        case Lf{v}:
          v
        case Nd{l, r}:
          a b = sum(l) sum(r)
          U32.add(U32.xor(U32.mul(a, 2654435761), b), 7)
    
    # Host-only sequential rebuild: replacement nodes reuse freed heap slots.
    def bump(t: Tr) -> Tr:
      match t:
        case Lf{v}:
          Lf{U32.inc(v)}
        case Nd{l, r}:
          x = bump(l)
          y = bump(r)
          Nd{x, y}
    
    # Device rewrite of every node.
    def flip(t: Tr) -> Tr:
      match t:
        case Lf{v}:
          Lf{v}
        case Nd{l, r}:
          a b = flip(l) flip(r)
          Nd{b, a}
    
    def main() -> IO(Unit):
      t0  = gen!(16n, 1)
      t1  = bump(t0)
      t2  = flip!(t1)
      t3  = bump(t2)
      t4  = flip!(t3)
      t5  = bump(t4)
      t6  = flip!(t5)
      t7  = bump(t6)
      t8  = flip!(t7)
      t9  = bump(t8)
      t10 = flip!(t9)
      t11 = bump(t10)
      t12 = flip!(t11)
      t13 = bump(t12)
      t14 = flip!(t13)
      t15 = bump(t14)
      t16 = flip!(t15)
      t17 = bump(t16)
      IO.print(U32.show(sum!(t17)))
    
    #|854543159

    Related scheduler defect: #1065 shows that opening the parallel host pool can silently suppress later marked GPU turns (3 expected, 1 observed).

  2. SiliconState commented on Sep 25, 2026

    @SiliconState
    Author

    Evidence correction and scope clarification after reviewing this report:

    • My statement that the same architectural limitation and solution had been independently reproduced on CUDA was too strong. The CUDA experiment demonstrated an eager VRAM twin, exact final outputs on the tested corpus, and its synchronization cost. I have not implemented or validated a dirty-range CUDA solution.
    • The ten-turn reproducer densely rebuilds the tree on the host and rewrites it on the device. Dirty tracking alone need not materially reduce its transfer volume. Sparse mutation, dense mutation, and longer device-resident phases require separate correctness and performance validation. This test establishes a limitation of the eager implementation, not a universal speedup from a proposed replacement.
    • The runtime counter divides bytes by 2^20 but prints MB. The quoted 610.3 and 691.3 figures are MiB, not decimal MB; the raw excerpts are otherwise unchanged.
    • The counters are rounded to milliseconds. 89/92 ms supports approximately 97% of instrumented GPU-turn time in copy calls, not a precisely measured 96.7% and not that fraction of whole-process execution time.

    The observed outputs and dispatch counts are unchanged. The live CUDA evidence remains on b7ebee9217c8813067e200b0c0c9153a3be31c5e; inspecting 47bed75adedd6d6dd811721905f06569bf465f85 was not a live current-main CUDA reproduction.

    The request remains for an upstream-owned, correct and observable dynamic CUDA execution path on non-concurrent-managed-memory devices. Dirty ranges are one candidate mechanism, not a demonstrated fix or a requirement to adopt this out-of-tree patch. The separate dispatch defect is tracked in #1065.

  3. costamatheus97 commented on Sep 25, 2026

    @costamatheus97
    Contributor

    For reference, the mechanism this asks for already exists end to end on the HIP lane. It's more than the eager twin plus dirty chunks from #891: it's the full lazy protocol, with its coherence laws modelled in Bend. It's on my fork's main:

    How it works:

    • Lazy download. When a ! call ends, nothing is copied down eagerly. Every chunk (256 KB) the device may have written is mprotect-ed on the host and downloaded on first touch. A ! call's result is usually a few words, so most chunks are never fetched.
    • Device-side write map. A device store into memory that existed before the call marks its chunk. The host only has to invalidate marked chunks, plus chunks from the ceiling up. This covers the freed-and-reused-slot case you describe: tracking by the bump alone is unsound, which is why the device marks.
    • Dirty-only upload. The host's first write to a clean chunk traps and marks it dirty. The next call uploads only dirty chunks, plus the live ring slots, counters and bank entries.
    • Prefetch. Per call site, the chunks the host touched after the previous run of the same ! are fetched eagerly when the call ends, which avoids a fault per chunk on repeated loops.
    • Copies are batched through a staging buffer and a single mover kernel, and hot ranges are pinned once they've paid for themselves.

    On the package workloads I profiled (scan, histogram and sort over 4M keys), a steady ! call moves about 1 MB each way. The 16 MB input stays resident across calls and never crosses the bus again. Your 10-turn test would still move a lot, since the host really rebuilds every node, but that's the workload's own cost, not the design's floor.

    Only a thin layer is CUDA- or HIP-specific: allocation, copies, events, and host pinning/registration. The chunk states, the fault and prefetch logic, the write-map marking in device stores and the ring and bank sync are lane-agnostic. So I think the cleanest upstream form is a shared twin layer that both lanes call, rather than a second copy inside the CUDA runtime. That also keeps it within the source-size budget.

    Your specific findings:

    • Pinned registration cost (768 MB at ~190 ms, cuMemHostAlloc at ~318 ms). Don't pin the corpus. In my local performance branch (haven't pushed that yet), large uploads go through a small double-buffered pinned staging pipe (8 MB), allocated off the critical path. That took first-call uploads well below what pageable copies cost, with no large registration (cold calls 2.9 → 0.8 ms for an empty call).
    • Copy APIs inside the SIGSEGV handler. Still open on my side too. The HIP fault handler calls hipMemcpy directly. A helper thread that the handler wakes and waits on is the clean form. Any upstream version should do that from the start.
    • The A parallel host phase makes later ! calls silently run on CPU instead of GPU #1065 dependency. Downloads happen in whole chunks. So the twin is mutating memory while a call runs, and host workers must not write into achunk the device wrote while that chunk is downloaded over their writes. Today the IO boundary provides that quiescence implicitly. A fix for A parallel host phase makes later ! calls silently run on CPU instead of GPU #1065 that routes ! tasks from pool workers to the GPU owner therefore also needs to park the pool for the duration of the call. The two changes should be designed together.

    I'm happy to help extract the shared layer and wire the CUDA side, though I can't test on NVIDIA hardware myself.

  4. SiliconState commented on Sep 26, 2026

    @SiliconState
    Author

    Thanks, @costamatheus97. That's useful, especially the device-side write map and the helper-thread point.

    A CUDA version now exists as PR #1078 (not mine): a lazy twin with 2 MiB chunks, trap-driven download and dirty-only upload. On this issue's ten-turn repro (RTX 5090, WSL2, --gpu 512MB) it prints 854543159 in 10 GPU turns and moves 181.5 MiB up and 184.0 MiB down (365.5 MiB), with about 70 ms in copy calls. My eager twin moved 610.3 MiB on b7ebee9. The bases and counters differ, so that's only indicative. As you predicted, the dense rebuild still moves a lot. Its fault handler still calls cuMemcpyDtoH directly (its review notes say so), so the helper-thread form is still open.

    Your #1065 point applies to #1078 as well: its twin relies on the host never running during a turn, which holds today because a turn only starts from corpus_eval's seam loop, before that evaluation hands anything to the pool. A dispatch fix has to keep host workers parked while a turn runs.

    Keeping this open until an upstream design is accepted.

  5. VictorTaelin commented on Sep 27, 2026

    @VictorTaelin
    Contributor

    Thanks for the investigation. We will not add this, for capacity reasons. CUDA's ! needs concurrent managed access, which WSL2 devices lack, and a device-resident copy of the corpus is a second memory model we cannot maintain. --gpu on will name the missing capability instead of saying "no GPU" (#1064). WONTFIX.txt: "! runs on the CPU on WSL2 GPUs (#1066)".

    Note: an AI wrote this reply after I made the decision. If anything here is wrong, reply and I will review it myself.

  6. added
    wontfix
    on Sep 27, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    wontfix

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions