Implement power-of-two VMem allocator
- [x] Explore codebase structure and existing allocators
- [x] Implement
VMemPow2Allocatoriniris/allocators/vmem_pow2_allocator.py - [x] Update
iris/allocators/__init__.pyto exportVMemPow2Allocator - [x] Update
iris/symmetric_heap.pyto supportallocator_type="vmem_pow2" - [x] Create
tests/unittests/test_vmem_pow2_allocator.pywith comprehensive tests - [x] Run linting with ruff — passes cleanly
- [x] Run tests — all 24 new tests pass (both ranks), all 2255 existing tests pass
- [x] Address all 12 review comments from @mawad-amd:
- [x] Bug 1: OOM check in
import_external_tensorusesaligned_export_size(export called first) - [x] Bug 2:
owns_tensorchecksdata_ptr()range for all tensors; zero-element tensors no longer unconditionally claimed - [x] Bug 3: GC auto-free via
weakref.finalizeontensor.untyped_storage()(survivesreshape()/other view ops) +_pending_freedeque (avoids lock-reentry deadlock) - [x] Bug 4: Physical memory renewed at reuse time —
_remap_free_blockreleases oldmem_unmap+mem_release, creates newmem_create+mem_map, then restoresmem_set_access(base_va, cumulative, ...)— releasing at free time is incompatible with ROCm's requirement thathipMemSetAccessmust start frombase_va(calling on sub-ranges gives HIP error 1) - [x] Design 5:
_CUDAArrayInterfacedefined once at module level - [x] Design 6:
_element_size()with module-level_DTYPE_ELEMENT_SIZEcache - [x] Design 7: FD leak in
import_external_tensorfixed withtry/finally - [x] Design 8: Unused
va_multiplierparameter removed - [x] Test 9:
test_vmem_pow2_oom— RuntimeError on VA exhaustion - [x] Test 10:
test_vmem_pow2_thread_safety— 4 threads × 20 alloc/free cycles - [x] Test 11:
test_vmem_pow2_close+test_vmem_pow2_close_disables_finalizers - [x] Test 12: All
print()calls removed from tests
- [x] Bug 1: OOM check in
- [x] Generation counter added to segment API:
get_allocation_segments()returns(offset, size, va, generation)4-tuples; symmetric_heap uses(offset, size, generation)as dedup key, handles stale peer mappings - [x]
vmem_allocator.pyreturnsgeneration=0in segments (backward compatible) - [x] Code review — 4 minor comments addressed (comment clarity,
ptr==0note, deque thread-safety note) - [x] CodeQL scan — 0 alerts
Original prompt
This section details on the original issue you should resolve
<issue_title>Implement power-of-two vmem allocator</issue_title> <issue_description>Implement a new virtual memory power of two allocator. Allocator must support as symmetric api</issue_description>
<agent_instructions>You have access to AMD gpu. Make sure everything is tested and working </agent_instructions>
Comments on the Issue (you are @copilot in this section)
- Fixes ROCm/iris#440
✨ Let Copilot coding agent set things up for you — coding agent works faster and does higher quality work when set up for your repo.
@copilot Please address the following issues in this PR:
Critical Bugs
-
import_external_tensorOOM check mismatch: The OOM check on line 390 usesaligned_size(derived fromalloc_size) but the actual mapping on line 403 usesaligned_export_size(derived fromexport_size). These can differ, so the check may pass but the mapping could still exceed the heap, or vice versa. The check should usealigned_export_size. -
owns_tensorincorrectly claims zero-element tensors:owns_tensorreturnsTrueunconditionally for any zero-element tensor, even ones not allocated by this allocator. Atorch.zeros(0, device="cuda")created externally would be incorrectly claimed as owned. This can break routing logic that depends onowns_tensor. -
No GC-based auto-free: Tensors that go out of scope leak their VA block permanently — the block is never returned to the free list until the entire allocator is
close()'d. The allocator should use a weak-reference finalizer (e.g.,weakref.refwith a callback) on returned tensors to automatically return blocks to the free list when the tensor is garbage collected. Users should not be required to manually callallocator.free(t)for normal usage. -
Physical memory not released on
free(): Currentlyfree()only does bookkeeping — the physical memory (mem_createhandle) stays mapped, permanently holding VRAM for blocks that aren't in use. Onfree(), the allocator should callmem_unmapandmem_releaseto return physical memory to the system while keeping the VA offset on the free list for reuse. On re-allocation from the free list, callmem_create+mem_mapagain to back the reserved VA with fresh physical memory. Thecumulative_mapped_size/mem_set_accesslogic will need adjustment to handle gaps in the physical mapping. The DMA-BUF concern can be handled by re-exporting segments after reallocation rather than assuming all segments are always physically present.
Design Issues
-
_CUDAArrayInterfaceclass redefined on every call: The inner class_CUDAArrayInterfaceis redefined inside bothallocate()andimport_external_tensor()on every invocation. Define it once at module level or as a nested class of the allocator. -
Inefficient
element_sizecomputation:torch.tensor([], dtype=dtype).element_size()creates a temporary tensor on every allocation just to get the element size. Cache this or use a more efficient approach. -
File descriptor leak in
import_external_tensor: If an exception occurs betweenexport_dmabuf_handleandos.close(dmabuf_fd), the fd leaks. Wrap intry/finally. -
Unused
va_multiplierparameter: The constructor acceptsva_multiplierbut never uses it. Either implement it or remove it.
Testing Gaps
- No test for OOM / heap exhaustion — the
RuntimeErroron VA space exhaustion is untested. - No test for thread safety — given the
Lock, concurrent allocation/free should be tested. - No test for
close()/ resource cleanup — theclose()and__del__paths are untested. - Tests use
print()for pass reporting — remove prints; rely on pytest assertions.
@copilot Please address the following issues in this PR:
Critical Bugs...
All 12 issues addressed in commit 17edd0b. Key points:
Critical bugs:
- OOM check in
import_external_tensornow usesaligned_export_size(export called first, then check) owns_tensorchecksdata_ptr()range for all tensors — zero-element tensors no longer unconditionally claimed- GC auto-free via
weakref.finalizeontensor.untyped_storage()(not the Python wrapper, which doesn't survive.reshape()) +_pending_freedeque to avoid lock-reentry deadlock - Physical memory is renewed at reuse time:
_remap_free_blockreleases the old handle (mem_unmap+mem_release) and creates fresh physical memory (mem_create+mem_map) at the same VA, then restoresmem_set_access(base_va, cumulative_size, …). Releasing atfree()time is incompatible with ROCm's requirement thathipMemSetAccessmust start frombase_va— calling it on arbitrary sub-ranges gives HIP error 1 (invalid argument), so VA ranges must always stay gap-free
Design improvements: _CUDAArrayInterface at module level, _element_size() cache, try/finally fd guard, va_multiplier removed
Segment API: get_allocation_segments() now returns (offset, size, va, generation) 4-tuples; _remap_free_block increments the generation; symmetric_heap replaces the _peer_imported_segments set with _peer_segment_generations dict and handles stale peer mappings (unmap old, remap new, re-set access)
New tests: OOM, thread safety, close(), GC auto-free, generation counter, zero-element owns_tensor check; all print() calls removed
All 24 new tests pass on 2 ranks; all 2255 existing tests pass.