From 3704f57495a16225a34a63bbb80a732a1b251c20 Mon Sep 17 00:00:00 2001 From: Berk Geveci Date: Sat, 5 Dec 2026 11:22:52 -0500 Subject: [PATCH] Plan: device memory, copies on other devices, accounting and spilling (#469, #387) Replaces the wiki's device memory plan: spilling becomes dropping a device copy of an array whose host copy is current, the accounting is #462's made public, and Jeff Lee's review on #387 is answered decision by decision. --- docs/design/plans/device-memory.md | 426 +++++++++++++++++++++++++++++ docs/design/plans/index.md | 1 + mkdocs.yml | 1 + 3 files changed, 428 insertions(+) create mode 100644 docs/design/plans/device-memory.md diff --git a/docs/design/plans/device-memory.md b/docs/design/plans/device-memory.md new file mode 100644 index 000000000..b15e38efe --- /dev/null +++ b/docs/design/plans/device-memory.md @@ -0,0 +1,426 @@ +# Device memory: copies on other devices, accounting and spilling + +**Status: proposed.** Issues [#469](https://github.com/Kitware/tack/issues/469) +and [#387](https://github.com/Kitware/tack/issues/387), 2026-12-05. This plan +replaces the wiki's +[Device memory plan](https://github.com/Kitware/tack/wiki/Device-memory-plan) +(2026-11-08). It answers Jeff Lee's review of that plan on #387, and recasts its +spilling as one case of #469's copies. Related: +[#451](https://github.com/Kitware/tack/issues/451), the case that needs copies. + +## Summary + +Today an array lives on one device. Using it from another means `to_device`, a +new array that nothing tracks. When a GPU runs out of memory, the allocation +fails after one retry. + +This plan gives each allocation optional **copies** on other devices, each +stamped with the revision it copied, the way Viskores' `ArrayHandle` keeps a +buffer per device. A copy is current while its stamp matches the array's +revision. A write makes every other copy stale at no cost, since Tack already +counts writes. Three things follow from that one model: + +- **Read access from another device.** `a.on("cpu")` is a read-only array over + the CPU copy, made on first use. A launch can run on a device that is not the + arrays' home and take their copies. This is what #451 needs: finishing a GPU + advection run's last few particles on the CPU, without a second dataset and a + second locator. +- **Spilling (#387) is dropping a device copy.** Under memory pressure, Tack + frees the device memory of an array whose host copy is current, first making + that copy if it has to. Restoring copies it back and keeps the host copy, which + is still current, instead of freeing it. +- **Unified memory falls out.** On Metal, the CPU "copy" is the same memory: an + alias that only waits for queued launches. On integrated GPUs, spilling is off, + as Jeff's review asked. + +Accounting stays the one design #462 merged (`runtime/memory_stats`, the cut +filters' plan's D1), made public and extended to copies, caches and spills. + +## What changed since the wiki plan + +- **The accounting's first step is merged** (#462, 2026-11-19). Every array Tack + allocates is counted per device where `_allocate` and `_empty_for_mpi` make + it, with a peak and `reset_peak`, on every backend Warp included. The count is + private. +- **Array views are merged** (#393). `a[i:j]` is a buffer of a subclass of its + root's class (`_View`, `lang/array.py`) whose `_device_ptr` is the root's + pointer plus an offset, **copied when the view is made**. Moving the root's + memory would leave every view pointing at freed memory. The wiki plan said + "check when views merge"; [D5](#d5-a-view-reads-its-roots-pointer-at-use) + decides it. +- **#469** proposed copies, and said the plan should cover both. +- **Jeff's review** on #387 (2026-11-12). Each point is answered below; the + table under [Review](#jeffs-review) maps them. + +## What happens today + +- **Allocation.** Every array's storage comes from `tack.empty`, through + `_allocate` (`lang/array.py`). Every GPU backend raises `DeviceMemoryError` + when an allocation runs out. `_allocate` then collects Python's garbage, waits + for the device so deferred frees complete, empties the backend's cache + (`release_memory`: HIP's buffer cache, Metal's pool), and tries once more. If + that fails, the error reaches the caller, usually from a temporary deep inside + a filter. +- **Counting.** `memory_stats` counts the bytes each array asked for + (`DeviceBuffer.nbytes`) while its buffer lives. It does not count memory from + outside (`wrap_ptr`, `array_from_ptr`, imports without a copy), a block while + it waits in a cache, the scalar packs, or hardware texture images. A view is + counted once, with its root. +- **Revisions.** `DeviceBuffer.version` counts every write Tack makes: host + writes (`Array._check_writable`) and every launch that may store to the array + (`check_writable_arrays`). Views share their root's count. + `tack.arrays._revision` turns it into a token, which a `CellLocator` records to + know it is stale. +- **Choosing the device.** `dispatch.launch_backend` runs a launch on the default + device if it can address every array, else on the arrays' device. Two memory + domains raise `ValueError`. `with device:` changes the default, but the arrays + still win: inside `with tack.device("cpu")`, a kernel given CUDA arrays runs on + CUDA. Library code relies on this (`on_inputs_device`, and about fifteen `with + device:` blocks in tack-dataset). +- **Where pointers are read.** On CUDA, HIP and Level Zero, a launch reads each + array's `buffer.device_ptr`. So do native reductions, texture uploads and + device-to-device copies; the buffers' own methods (`from_numpy`, `to_numpy`, + `read_range`, `fill_bytes`) read `_device_ptr`. Every operation is queued in + order on one stream (CUDA, HIP) or one in-order command list (Level Zero) per + device. +- **Memory Tack cannot move:** arrays wrapping someone else's pointer + (`wrap_ptr`, DLPack imports), memory handed out (DLPack export, + `export_memory`, `share()`, VTK's `copy=False`), MPI buffers + (`allocate_mpi_array`), the scalar packs, and texture images. +- **Derived data** (faces, edges, point links, locators, cell geometry) stays on + the device as long as its dataset lives. + +## Decisions + +### D1. Copies belong to the allocation, stamped with its revision + +Each root buffer (an allocation, not a view) may hold copies of its contents on +other memory domains: a small table from memory domain to `(buffer, stamp)`. A +copy is **current** when its stamp equals the root's `version`. Writes do no work +for copies: the count they already bump makes the others stale. + +- **Copies are read-only.** A write goes to the home buffer, as today. Nothing + writes through a copy, so there is never more than one buffer to reconcile. +- **A copy is made on first use and refreshed when stale.** Refreshing copies + the whole allocation again. Tracking dirty ranges is not worth it yet. +- **A view reads its root's copy** at its own offset, so views need no table of + their own. +- **What has no copies:** the memory Tack cannot move (above). An array that + wraps outside memory may still have copies made *of* it on other devices. + Writes Tack does not see (through DLPack, `wrap_ptr`, `export_memory`) leave + copies stale without bumping the count, as they already leave locators. The + docs say so; `Array.touch()` (bump the count by hand) is offered for callers + who write that way. + +*Recommended.* + +### D2. Read access: `Array.on(device)` + +`a.on(device)` returns a read-only `Array` on `device` over the current copy, +making or refreshing it first. It holds the copy's buffer, so a later write or +restore never frees memory under it; the copy just stops being current, like a +snapshot. Read-only arrays and their checks exist already (`array_from_ptr`'s +default): a kernel that may store to one raises. + +- `a.on(home)` is `a` itself, as `to_device` returns `a` when its memory is + usable there. +- `to_device` keeps its meaning (an independent, writable array), but makes it + from a current copy when there is one, saving the transfer. +- A `SoaArray` takes `on` per component, as it takes `to_device`. + +The name is open. `on` reads well at call sites (`positions.on("cpu")`) and +does not suggest the copy is independent, which `copy_to` would. + +*Recommended.* + +### D3. A launch on a device that is not the arrays' home: opt in + +Copies should not change where existing code runs. Library code relies on the +arrays winning over the default device ([What happens today](#what-happens-today)), +so making `with device:` pick the device and copy the arrays would change about +fifteen blocks in tack-dataset at once. So the new behaviour is opt-in: + +```python +with tack.run_on("cpu"): + advect(data, particles, steps) +``` + +Inside `tack.run_on(device)`, every launch runs on `device`. An array it cannot +address is bound through its copy there (D1), made or refreshed as needed, +including arrays a device class holds: template expansion substitutes copies +where it now raises (`check_devices`). Arrays the launch may store to must be +addressable on `device`, since copies are read-only; anything else raises the +read-only error with a remedy (`to_device` the outputs). New arrays inside the +block are made on `device`, as under `with device:`. + +For #451 that is: the mesh, velocity and locator stay on the GPU and are read +through CPU copies; the few particles' state is moved with `to_device`. + +Considered: +- **`with device:` picks the device.** Simpler, but a silent change to library + code that relies on the arrays winning. +- **Copies by argument only** (`kernel(a.on("cpu"), ...)`). Needs nothing new in + dispatch, but cannot reach the arrays inside a dataset or a locator, which is + the point of #451. + +*Recommended: `tack.run_on`.* + +### D4. Unified memory: alias on Metal, real copies elsewhere for now + +- **Metal.** A Metal buffer is host memory. Its CPU copy is a CPU buffer over the + same memory (`MetalBuffer`'s contents), always current, made once. Reading it + waits for the queued launches that may write it, as every `MetalBuffer` host + access already does. Spilling is off. +- **Integrated GPUs** (CUDA `CU_DEVICE_ATTRIBUTE_INTEGRATED`, such as the DGX + Spark's GB10; HIP `hipDeviceAttributeIntegrated`, such as MI300A; Level Zero + `ZE_DEVICE_PROPERTY_FLAG_INTEGRATED`, Intel's integrated GPUs). Device memory + is host memory there, so spilling only copies within the same RAM, and the + driver's free memory is the system's. **Spilling is off** on them, as Jeff + asked. Accounting still runs. Copies are real copies at first, which is + correct everywhere. Aliasing them needs the host to address device + allocations, which depends on the driver (pageable-memory access through the + host's page tables on CUDA, `hipMalloc` on an APU, Level Zero's shared + allocations). That is a later step, once measured on such a machine. +- **Discrete GPUs:** real copies, and spilling on. + +*Recommended.* + +### D5. A view reads its root's pointer at use + +On CUDA, HIP and Level Zero, `_View` gets a `_device_ptr` property: the root's +current pointer plus the view's offset. The buffers' methods already read +`_device_ptr`, so they follow the root without change. Spilling and restoring +then work on roots alone, and every view sees the result. + +Considered: **a root with live views is never spilled.** Simpler, but the AMR +level buffers (#458) are exactly that: one large root per level, viewed box by +box, and they would never spill. + +The cost is one attribute read and an add per view argument per launch. It is +measured with the fast path's other costs (D9). + +*Recommended.* + +### D6. Residency: one backend lock for everything that reads a device pointer + +Jeff's review: the wiki plan kept a launch's arrays resident during `execute` +only. Native reductions, texture uploads, DLPack export and `share()` also read +`device_ptr` and then use it. If a spill runs between the read and the use +(another thread allocating, or an allocation inside the operation), the pointer +is freed. + +The rule: **a buffer is resident and cannot be spilled from the moment its +pointer is read until the operation using it is queued.** Once queued, a later +spill's copy-out is queued after it, and the free is stream-ordered, so the +queued work completes against live memory. + +Each of CUDA, HIP and Level Zero takes one backend lock (`_residency`, reentrant) +around reading pointers and queueing, in: + +- `execute`, around binding arguments and `_launch`; +- native reductions; +- texture uploads; +- device-to-device copies and fills; +- DLPack export and `share()`, which also mark the buffer handed out, so never + spillable again (as today's exclusions say). + +Spilling and restoring take the same lock. Level Zero already holds a +backend-wide reentrant `_launch_lock` over launches, reductions and copies; it +becomes the residency lock. CUDA and HIP hold a per-variant `dispatch_lock`, +which does not exclude a spill from another thread, so they gain the backend +lock. An uncontended reentrant lock costs 0.065 µs a `with` block (CPython +3.13, the M1 Max); D9 measures it in the fast path. + +*Recommended.* + +### D7. What spilling drops, and when + +Spilling frees device memory on a discrete GPU. It drops, in order: + +1. **device copies of arrays whose home is elsewhere** (made for `run_on` or + `on`): nothing is lost; +2. **home device buffers whose host copy is current:** nothing to copy; +3. **the least recently used home device buffers:** copied to a host copy + first, then freed. + +Within each class, least recently used first. Each root keeps a counter its +backend advances on every use (each pointer read, each host access). The backend +keeps its spillable roots in a weak registry. + +**When:** +- **Without a budget,** spilling runs when an allocation fails: in `_allocate`, + after today's garbage collection and cache release, Tack spills until the + allocation succeeds or nothing is left, and only then raises + `DeviceMemoryError`. +- **With a budget** (D8), it runs before an allocation would take Tack's arrays + past it. + +**What is never spilled:** the memory Tack cannot move, and the arrays of the +operation being prepared (held under D6's lock while it allocates the others). +Derived data is spilled like any other array, not dropped and recomputed (berk's +choice in the wiki plan). + +**A spilled array:** +- The copy out is queued on Tack's stream (`cuMemcpyDtoHAsync`, + `hipMemcpyDtoHAsync`, Level Zero's list), followed by a wait. (Jeff: the wiki + plan's "a copy into pageable memory waits for the queued work" holds for the + legacy default stream, not necessarily for Tack's.) +- Host reads (`numpy()`, `read_range`, `a[i]`) read the host copy, and leave the + array spilled. Host writes write the host copy and bump the revision, so the + host copy becomes the current one and the array stays spilled. +- Only the device restores: a pointer read (D6) allocates (which may spill + others), copies the host copy in, and **keeps the host copy** as a current read + copy, until the next write makes it stale. This changes the wiki plan, which + freed it. +- The host copy is ordinary host memory, not pinned (berk's choice). `on("cpu")` + of a spilled array reads it, like any current copy (D2): a snapshot that holds + its buffer, so the wiki plan's rule that a host copy is never handed out is no + longer needed. + +**Limits:** one operation's arrays must still fit on the device. A buffer +spilled and restored over and over is slow but correct; the accounting counts +spills and restores, so it shows. + +*Recommended.* + +### D8. The budget: Tack's arrays, in bytes or as a fraction + +`tack.set_memory_budget(limit, device=None)` limits what **Tack's arrays** hold +on a device. `limit` is bytes, or a fraction in `(0, 1]` of the driver's free +memory at the call (Jeff's suggestion), turned into bytes then. `None` removes +it. The docs say plainly that the budget covers Tack's arrays only, not memory +PyTorch, VTK or another process holds on the same GPU: the driver's free memory +shows that, and the fraction is the way to leave room for it. + +*Recommended.* + +### D9. Accounting: one design, public + +The accounting is `memory_stats` (D1 of the cut filters' plan, merged in #462), +not a second one. This plan makes it public and adds what spilling needs: + +| quantity | meaning | +|---|---| +| `live` | bytes of Tack's live arrays on the device: home buffers resident there, and copies made there. Not caches. | +| `peak` | the most `live` has been since the last reset | +| `copies` | the part of `live` that is copies of arrays whose home is another device | +| `cached` | bytes Tack's caches keep for reuse, reported separately (HIP's buffer cache, Metal's pool; on CUDA the pool's reserve beyond use) | +| `spilled` | bytes of arrays homed here whose device memory is freed, held on the host | +| `spills`, `restores` | counts since the last reset | +| `device_free`, `device_total` | the driver's answer, where it has one | + +Jeff asked whether `in_use` and `peak` include the caches: they do not. Tests +want live arrays only, so `live` and `peak` are those, and `cached` is reported +beside them. + +The API: +- `tack.memory_info(device=None)`: these as a small named record. +- `tack.reset_peak_memory(device=None)`. +- A scope for one block's peak: + + ```python + with tack.memory_peak() as peak: + td.extract_surface(data) + print(peak.bytes) + ``` + +**Warp** (Jeff's question): counted already, since its `allocate_array` goes +through `_allocate`; no copies of Warp arrays and no spilling on Warp, whose +memory and stream are Warp's own. + +**Cost on the warm path.** The fast path (`_fast_resolve`) gains, per array +argument: the residency check (one attribute test), the use counter, and under +`run_on` the copy lookup. Views add D5's pointer read. The target is no +measurable change outside `run_on`, measured with +`docs/design/specialization-and-caching.md`'s warm-call benchmark before and +after. + +*Recommended.* + +### D10. Debug mode checks copies and pointers + +`tack.set_debug(True)` (Jeff's suggestion for testing "never a spilled pointer"): + +- every pointer bound to a launch is checked against its buffer's resident + pointer, so a launch on a spilled or freed pointer raises at once instead of + computing garbage; +- every copy bound through `run_on` is checked current. + +An `on()` array is not checked when read: a snapshot may be stale by design +(D2). + +*Recommended.* + +## Jeff's review + +| Review point | Where | +|---|---| +| Unified memory: spilling off on integrated devices, accounting on | [D4](#d4-unified-memory-alias-on-metal-real-copies-elsewhere-for-now) | +| One accounting, not two; the plan in `docs/design/plans/` | [D9](#d9-accounting-one-design-public); this page | +| Pinning must cover every `device_ptr` user, under the spilling lock | [D6](#d6-residency-one-backend-lock-for-everything-that-reads-a-device-pointer) | +| The spill copy queued on Tack's stream, then a wait | [D7](#d7-what-spilling-drops-and-when) | +| What `in_use` and `peak` count | [D9](#d9-accounting-one-design-public) | +| The budget versus other libraries | [D8](#d8-the-budget-tacks-arrays-in-bytes-or-as-a-fraction) | +| Warp in or out | [D9](#d9-accounting-one-design-public) | +| A debug check for spilled pointers | [D10](#d10-debug-mode-checks-copies-and-pointers) | + +## Considered and not taken + +- **CUDA managed memory, HIP's `hipMallocManaged`.** The driver would page + instead of Tack, but faults cost per access and are hard to predict, support + varies (Windows WDDM, AMD's XNACK, Level Zero's shared memory), and it would + change every allocation, the memory handed to other libraries included. +- **Dropping derived data instead of spilling it.** Recomputing is sometimes + cheaper than a round trip, but spilling every array alike is simpler and + predictable. +- **Pinned host memory for host copies.** Faster and asynchronous, but limited + and costly to allocate. Ordinary memory first; pinned if spills dominate. +- **Writable copies** (several current copies, written anywhere, reconciled). + Viskores does this, and it is what makes its `ArrayHandle` hard to reason + about. Read-only copies cover #451 and spilling. + +## Open questions + +- **The name** of `on` (D2) and `run_on` (D3). +- **Host memory under pressure.** Copies and spills use host memory without a + limit. A host budget can come later if it matters. +- **Copies across GPUs.** The model allows a CUDA copy of a HIP array, but the + path goes through the host. Peer copies are not planned. +- **A copy outliving its use.** Copies stay until the array dies, a write makes + them stale and spilling drops them, or `release_memory` is called. Whether + stale copies should be freed eagerly is a measurement question. + +## Steps + +1. **Accounting, public** (D9). `tack.memory_info`, `reset_peak_memory`, + `memory_peak`; `cached` from each backend's cache; the driver's free and + total; integrated-device detection. Docs and tests. +2. **Copies and `on`** (D1, D2, D4's Metal alias). The copy table on root + buffers, stamps, refresh; `on`; `to_device` from a current copy; + `Array.touch()`. Tests on every backend: a write makes copies stale, `on` + snapshots, Metal's alias waits for launches. +3. **`run_on`** (D3). Copies bound in dispatch and in template expansion; the + read-only error with its remedy; the fast path's cost measured (D9). Then + #451's CPU tail on it, measured against `data.to_device("cpu")` (0.27 s of + copies and over 1 GB on AhmedML today). +4. **Residency** (D5, D6). Views' pointers through their roots; the backend lock + in every pointer reader; debug checks (D10). +5. **Spilling on a failed allocation** (D7) on CUDA, HIP and Level Zero; off on + integrated devices and Metal. +6. **The budget** (D8). +7. **Validation on the GPUs.** AhmedML's sweep under a budget well below its + peak (for example 8 GB on the RTX 6000 Ada): every step completes, the outputs + match those without a budget, and the cost is measured. The M6 dataset on a + 16 GB GPU. HIP and Level Zero through their machines' tickets. An integrated + device (GB10 or MI300A) with spilling off. + +Steps 1 and 2 are independent. Step 3 needs 2. Step 5 needs 2 and 4. + +## Related + +- [#386](https://github.com/Kitware/tack/issues/386): the GPU backends clear + every new buffer. Independent, but it touches the same allocation code. +- [#462](https://github.com/Kitware/tack/pull/462): the allocation count this + plan makes public. +- [#393](https://github.com/Kitware/tack/pull/393): array views, whose pointers + D5 changes. diff --git a/docs/design/plans/index.md b/docs/design/plans/index.md index 8ce6c837b..11d278f9f 100644 --- a/docs/design/plans/index.md +++ b/docs/design/plans/index.md @@ -30,3 +30,4 @@ recommendation, so a review can answer "yes", "no" or "other" per decision. | [Inspecting device-class objects](inspect-template.md) | [#324](https://github.com/Kitware/tack/issues/324) | Done | | [Mutation rules, stage 1](mutation-rules.md) | [#323](https://github.com/Kitware/tack/issues/323) | Accepted | | [Field quantities](field-quantities.md) | [#467](https://github.com/Kitware/tack/issues/467) | Proposed | +| [Device memory: copies, accounting and spilling](device-memory.md) | [#469](https://github.com/Kitware/tack/issues/469), [#387](https://github.com/Kitware/tack/issues/387) | Proposed | diff --git a/mkdocs.yml b/mkdocs.yml index d14d0f327..2a425ac39 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -253,6 +253,7 @@ nav: - Inspecting device-class objects: design/plans/inspect-template.md - Mutation rules, stage 1: design/plans/mutation-rules.md - Field quantities: design/plans/field-quantities.md + - Device memory: design/plans/device-memory.md - Contracts: contracts/index.md - Dataset API design: vis-guide/design/dataset-api.md - Polyhedra: vis-guide/design/polyhedra.md