# bend-gpu-heap One effect, `Heap.home`, that moves Bend's GPU heap back to the CPU in a single bulk prefetch. It removes a cost a Bend 2 GPU program pays without seeing it: creating large arrays in memory that GPU kernels have touched. ```python import bend-gpu-heap@/heap.bend as HP ``` ```python # between a phase that ran GPU kernels and one that makes large arrays h : U32 <- HP.Heap.home(0) ``` ## Why In a native CUDA build (a program that uses `!`), Bend's heap is CUDA managed memory, and the runtime creates arrays on the CPU. Pages are moved to the CPU on demand, one page fault at a time: - heap memory a GPU kernel used, handed to a new array, comes back at about 2 s a GB; - memory never touched costs about 0.5 s a GB on first touch. `Heap.home` asks the driver to move the heap to the CPU in one `cuMemPrefetchAsync`, at about 10 GB/s for either kind; creating the arrays afterwards is cheap. Measured in a program that runs three models one after another in one process: the last model's arrays (2.6 GB) took 1.36 s to create in a fresh process, 5.6 s when the process had run that model once before (its memory reused after GPU kernels), and 0.28 s after `Heap.home`. Calling it before each of the three models took that program from 15.0 s to 12.0 s. ## API | Definition | What it does | | - | - | | `Heap.home(mib) -> IO(U32)` | moves the first `mib` MiB of the heap (all of it for 0) to the CPU; answers the MiB it covered | The call synchronizes the GPU before and after the prefetch. `HEAP_TRACE=1` prints each call's size and time on stderr. Where to call it: before a phase that creates large arrays, after a phase that ran GPU kernels. A phase that only computes on arrays already made does not need it. ## Requirements - A native CUDA build of a program that uses `!`; the JS stub throws. - CUDA 13 (`cuMemPrefetchAsync` with a `CUmemLocation`). - The C reads Bend runtime internals (`e.mem`, `gpu_dev`). Tested with Bend 2.0.40 only. Foreign code: nothing here is proved. `test/heap_test.bend` runs it after a GPU call and prints what it covered. MIT-0.