diffusers-dynamic-offloader 0.1.0rc2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (28) hide show
  1. ddo_native_check.py +44 -0
  2. ddo_vmm_bootstrap.py +142 -0
  3. diffusers_dynamic_offloader/__init__.py +116 -0
  4. diffusers_dynamic_offloader/allocation_diagnostics.py +96 -0
  5. diffusers_dynamic_offloader/auxiliary_sources.py +126 -0
  6. diffusers_dynamic_offloader/backend.py +166 -0
  7. diffusers_dynamic_offloader/device_cache.py +60 -0
  8. diffusers_dynamic_offloader/dynamic_offload.py +3919 -0
  9. diffusers_dynamic_offloader/float8_compile.py +77 -0
  10. diffusers_dynamic_offloader/float8_loading.py +130 -0
  11. diffusers_dynamic_offloader/host_cache.py +101 -0
  12. diffusers_dynamic_offloader/host_memory.py +70 -0
  13. diffusers_dynamic_offloader/linear_convolution.py +105 -0
  14. diffusers_dynamic_offloader/metrics.py +217 -0
  15. diffusers_dynamic_offloader/metrics_journal.py +66 -0
  16. diffusers_dynamic_offloader/operator_diagnostics.py +167 -0
  17. diffusers_dynamic_offloader/profiles.py +495 -0
  18. diffusers_dynamic_offloader/quantized_sources.py +58 -0
  19. diffusers_dynamic_offloader/timing.py +129 -0
  20. diffusers_dynamic_offloader/vmm_model_arena.py +277 -0
  21. diffusers_dynamic_offloader/vmm_weight_store.py +840 -0
  22. diffusers_dynamic_offloader/weight_source_metadata.py +81 -0
  23. diffusers_dynamic_offloader/windows_file_reader.py +106 -0
  24. diffusers_dynamic_offloader-0.1.0rc2.dist-info/METADATA +90 -0
  25. diffusers_dynamic_offloader-0.1.0rc2.dist-info/RECORD +28 -0
  26. diffusers_dynamic_offloader-0.1.0rc2.dist-info/WHEEL +5 -0
  27. diffusers_dynamic_offloader-0.1.0rc2.dist-info/licenses/LICENSE +201 -0
  28. diffusers_dynamic_offloader-0.1.0rc2.dist-info/top_level.txt +3 -0
@@ -0,0 +1,840 @@
1
+ """Optional CUDA VMM-backed storage for immutable, dense model weights.
2
+
3
+ The store deliberately owns only a small, explicit part of memory management:
4
+ stable virtual-address slots and their physical CUDA mappings. It does not
5
+ replace PyTorch's allocator or expose unmapped storage to a caller.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import ctypes
11
+ import mmap
12
+ import os
13
+ import threading
14
+ import time
15
+ from contextlib import AbstractContextManager
16
+ from dataclasses import dataclass
17
+ from pathlib import Path
18
+ from typing import TYPE_CHECKING, Any
19
+
20
+ if TYPE_CHECKING:
21
+ import torch
22
+
23
+
24
+ def _cuda_modules() -> tuple[Any, Any, Any]:
25
+ try:
26
+ from cuda.bindings import driver
27
+ from cuda.core import Buffer, Device
28
+ except ImportError as error: # pragma: no cover - depends on optional extra.
29
+ raise RuntimeError(
30
+ "CUDA VMM support requires the 'vmm' extra: pip install 'diffusers-dynamic-offloader[vmm]'."
31
+ ) from error
32
+ return driver, Buffer, Device
33
+
34
+
35
+ def _require_success(result: tuple[Any, ...], operation: str) -> tuple[Any, ...]:
36
+ driver, _, _ = _cuda_modules()
37
+ if result[0] != driver.CUresult.CUDA_SUCCESS:
38
+ raise RuntimeError(f"{operation} failed: {result[0]}")
39
+ return result[1:]
40
+
41
+
42
+ def _round_up(value: int, multiple: int) -> int:
43
+ return ((value + multiple - 1) // multiple) * multiple
44
+
45
+
46
+ @dataclass
47
+ class VmmWeightStoreStats:
48
+ reserved_bytes: int = 0
49
+ resident_bytes: int = 0
50
+ materializations: int = 0
51
+ evictions: int = 0
52
+ copied_bytes: int = 0
53
+
54
+
55
+ @dataclass(frozen=True)
56
+ class PinnedStagingPoolStats:
57
+ """Host-side transport timings for the bounded VMM staging ring."""
58
+
59
+ slot_reuse_wait_seconds: float = 0.0
60
+ slot_reuse_waits: int = 0
61
+ source_copy_seconds: float = 0.0
62
+ source_copy_bytes: int = 0
63
+ shard_read_seconds: float = 0.0
64
+ shard_read_bytes: int = 0
65
+
66
+
67
+ class _VmmWeightSlot:
68
+ def __init__(self, key: str, address: Any, size: int) -> None:
69
+ self.key = key
70
+ self.address = address
71
+ self.size = size
72
+ self.handle: Any | None = None
73
+ self.buffer: Any | None = None
74
+ self.storage: torch.Tensor | None = None
75
+ self.active_leases = 0
76
+ self.last_used = 0.0
77
+ self.last_event: Any | None = None
78
+
79
+ @property
80
+ def is_mapped(self) -> bool:
81
+ return self.handle is not None
82
+
83
+
84
+ class VmmWeightLease(AbstractContextManager):
85
+ """A scoped, CUDA-ordered view of one materialized immutable weight."""
86
+
87
+ def __init__(self, store: VmmWeightStore, slot: _VmmWeightSlot, tensor: torch.Tensor) -> None:
88
+ self._store = store
89
+ self._slot = slot
90
+ self.tensor = tensor
91
+
92
+ def __enter__(self) -> torch.Tensor:
93
+ return self.tensor
94
+
95
+ def __exit__(self, exc_type, exc_value, traceback) -> None:
96
+ self._store.release(self._slot.key)
97
+
98
+
99
+ class _WindowsRegisteredVirtualBuffer:
100
+ """One contiguous Windows host allocation registered once with CUDA.
101
+
102
+ This deliberately owns a bounded staging slot, not model-weight storage.
103
+ The raw address is valid for direct ``cuMemcpyHtoDAsync`` while the slot's
104
+ CUDA event is outstanding.
105
+ """
106
+
107
+ _MEM_COMMIT = 0x1000
108
+ _MEM_RESERVE = 0x2000
109
+ _MEM_RELEASE = 0x8000
110
+ _PAGE_READWRITE = 0x04
111
+
112
+ def __init__(self, size_bytes: int) -> None:
113
+ import torch
114
+
115
+ if os.name != "nt":
116
+ raise RuntimeError("Registered virtual host buffers are Windows-only")
117
+ self.size_bytes = size_bytes
118
+ self._kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
119
+ self._kernel32.VirtualAlloc.argtypes = (ctypes.c_void_p, ctypes.c_size_t, ctypes.c_ulong, ctypes.c_ulong)
120
+ self._kernel32.VirtualAlloc.restype = ctypes.c_void_p
121
+ self._kernel32.VirtualFree.argtypes = (ctypes.c_void_p, ctypes.c_size_t, ctypes.c_ulong)
122
+ self._kernel32.VirtualFree.restype = ctypes.c_int
123
+ address = self._kernel32.VirtualAlloc(
124
+ None, size_bytes, self._MEM_RESERVE | self._MEM_COMMIT, self._PAGE_READWRITE
125
+ )
126
+ if not address:
127
+ raise ctypes.WinError(ctypes.get_last_error())
128
+ self.address = int(address)
129
+ self._raw = (ctypes.c_ubyte * size_bytes).from_address(self.address)
130
+ self.tensor = torch.frombuffer(self._raw, dtype=torch.uint8)
131
+ self._registered = False
132
+ try:
133
+ driver, _, _ = _cuda_modules()
134
+ _require_success(
135
+ driver.cuMemHostRegister(self.address, size_bytes, driver.CU_MEMHOSTREGISTER_PORTABLE),
136
+ "cuMemHostRegister(virtual staging buffer)",
137
+ )
138
+ self._registered = True
139
+ except BaseException:
140
+ self.close()
141
+ raise
142
+
143
+ def close(self) -> None:
144
+ if self.address == 0:
145
+ return
146
+ if self._registered:
147
+ driver, _, _ = _cuda_modules()
148
+ _require_success(driver.cuMemHostUnregister(self.address), "cuMemHostUnregister(virtual staging buffer)")
149
+ self._registered = False
150
+ self.tensor = None
151
+ self._raw = None
152
+ address = self.address
153
+ self.address = 0
154
+ if not self._kernel32.VirtualFree(ctypes.c_void_p(address), 0, self._MEM_RELEASE):
155
+ raise ctypes.WinError(ctypes.get_last_error())
156
+
157
+
158
+ class PinnedStagingPool:
159
+ """Small ring of bounded pinned buffers for asynchronous weight uploads.
160
+
161
+ One buffer makes a next-group prefetch synchronize the upload of the
162
+ current group before CUDA can start computing it. Two slots let the
163
+ prefetch stream overlap that next upload with current-group compute while
164
+ keeping host-pinned memory explicitly bounded.
165
+ """
166
+
167
+ def __init__(
168
+ self,
169
+ size_bytes: int,
170
+ slots: int = 2,
171
+ *,
172
+ registered_virtual_host: bool = False,
173
+ windows_file_read_chunk_bytes: int = 2 * 1024**2,
174
+ ) -> None:
175
+ import torch
176
+
177
+ if size_bytes <= 0:
178
+ raise ValueError("Pinned staging buffer size must be positive")
179
+ if slots <= 0:
180
+ raise ValueError("Pinned staging slot count must be positive")
181
+ if windows_file_read_chunk_bytes <= 0:
182
+ raise ValueError("Windows file-read chunk size must be positive")
183
+ self.size_bytes = size_bytes
184
+ self.slots = slots
185
+ self._virtual_buffers: list[_WindowsRegisteredVirtualBuffer] = []
186
+ if registered_virtual_host:
187
+ if os.name != "nt":
188
+ raise RuntimeError("Registered virtual host transport is Windows-only")
189
+ try:
190
+ self._virtual_buffers = [_WindowsRegisteredVirtualBuffer(size_bytes) for _ in range(slots)]
191
+ self._buffers = [buffer.tensor for buffer in self._virtual_buffers]
192
+ except BaseException:
193
+ for buffer in reversed(self._virtual_buffers):
194
+ buffer.close()
195
+ self._virtual_buffers.clear()
196
+ raise
197
+ else:
198
+ self._buffers = [torch.empty(size_bytes, dtype=torch.uint8, device="cpu", pin_memory=True) for _ in range(slots)]
199
+ self._ready_events: list[Any | None] = [None] * slots
200
+ self._stats = PinnedStagingPoolStats()
201
+ self._next_slot = 0
202
+ self._active_slot: int | None = None
203
+ self._offset = 0
204
+ self._checkpoint_files: dict[Path, Any] = {}
205
+ self._checkpoint_maps: dict[Path, mmap.mmap] = {}
206
+ self._file_lock = threading.Lock()
207
+ self._windows_file_reader = None
208
+ if os.name == "nt":
209
+ from .windows_file_reader import WindowsPinnedFileReader
210
+
211
+ self._windows_file_reader = WindowsPinnedFileReader(chunk_bytes=windows_file_read_chunk_bytes)
212
+
213
+ def begin_upload(self) -> None:
214
+ """Acquire the next ring slot, waiting only when that slot is reused."""
215
+ slot = self._next_slot
216
+ self._next_slot = (slot + 1) % self.slots
217
+ event = self._ready_events[slot]
218
+ if event is not None:
219
+ start = time.perf_counter()
220
+ event.synchronize()
221
+ self._stats = PinnedStagingPoolStats(
222
+ slot_reuse_wait_seconds=self._stats.slot_reuse_wait_seconds + time.perf_counter() - start,
223
+ slot_reuse_waits=self._stats.slot_reuse_waits + 1,
224
+ source_copy_seconds=self._stats.source_copy_seconds,
225
+ source_copy_bytes=self._stats.source_copy_bytes,
226
+ shard_read_seconds=self._stats.shard_read_seconds,
227
+ shard_read_bytes=self._stats.shard_read_bytes,
228
+ )
229
+ self._active_slot = slot
230
+ self._offset = 0
231
+
232
+ @property
233
+ def next_slot_ready(self) -> bool:
234
+ """Whether a speculative upload can acquire its next slot without waiting."""
235
+
236
+ if self._active_slot is not None:
237
+ return False
238
+ event = self._ready_events[self._next_slot]
239
+ return event is None or event.query()
240
+
241
+ def _active_buffer(self) -> Any:
242
+ if self._active_slot is None:
243
+ raise RuntimeError("Call begin_upload before staging VMM data")
244
+ return self._buffers[self._active_slot]
245
+
246
+ def stage(self, source: torch.Tensor) -> torch.Tensor:
247
+ if source.device.type != "cpu" or not source.is_contiguous():
248
+ raise ValueError("Pinned staging accepts contiguous CPU tensors only")
249
+ size_bytes = source.numel() * source.element_size()
250
+ end = self._offset + size_bytes
251
+ if end > self.size_bytes:
252
+ raise RuntimeError(
253
+ f"Pinned staging buffer is too small: need {end / 1024**2:.1f} MiB, "
254
+ f"have {self.size_bytes / 1024**2:.1f} MiB"
255
+ )
256
+ storage = self._active_buffer()[self._offset : end]
257
+ staged = storage.view(dtype=source.dtype).view(source.shape)
258
+ start = time.perf_counter()
259
+ staged.copy_(source)
260
+ self._stats = PinnedStagingPoolStats(
261
+ slot_reuse_wait_seconds=self._stats.slot_reuse_wait_seconds,
262
+ slot_reuse_waits=self._stats.slot_reuse_waits,
263
+ source_copy_seconds=self._stats.source_copy_seconds + time.perf_counter() - start,
264
+ source_copy_bytes=self._stats.source_copy_bytes + size_bytes,
265
+ shard_read_seconds=self._stats.shard_read_seconds,
266
+ shard_read_bytes=self._stats.shard_read_bytes,
267
+ )
268
+ self._offset = end
269
+ return staged
270
+
271
+ def stage_file_slice(self, source: torch.Tensor, file_slice: "SafetensorFileSlice") -> torch.Tensor:
272
+ """Read one checkpoint byte range directly into the active pinned slot."""
273
+ source_device = getattr(source, "device", None)
274
+ source_contiguous = getattr(source, "is_contiguous", None)
275
+ if ((source_device is not None and source_device.type != "cpu") or (
276
+ callable(source_contiguous) and not source_contiguous()
277
+ )):
278
+ raise ValueError("Pinned file staging accepts contiguous CPU tensors only")
279
+ size_bytes = source.numel() * source.element_size()
280
+ if size_bytes != file_slice.size_bytes:
281
+ raise ValueError("Safetensor slice size does not match the source tensor")
282
+ end = self._offset + size_bytes
283
+ if end > self.size_bytes:
284
+ raise RuntimeError(
285
+ f"Pinned staging buffer is too small: need {end / 1024**2:.1f} MiB, "
286
+ f"have {self.size_bytes / 1024**2:.1f} MiB"
287
+ )
288
+ storage = self._active_buffer()[self._offset : end]
289
+ self._read_file_slice(file_slice, storage)
290
+ staged = storage.view(dtype=source.dtype).view(source.shape)
291
+ self._offset = end
292
+ return staged
293
+
294
+ def stage_file_slices(self, entries: list[tuple[torch.Tensor, "SafetensorFileSlice"]]) -> list[torch.Tensor]:
295
+ """Stage packed slices, joining adjacent ranges in the same shard."""
296
+ if not entries:
297
+ return []
298
+ start = self._offset
299
+ runs: list[tuple[SafetensorFileSlice, int, int]] = []
300
+ staged: list[torch.Tensor] = []
301
+ for source, file_slice in entries:
302
+ source_device = getattr(source, "device", None)
303
+ source_contiguous = getattr(source, "is_contiguous", None)
304
+ if ((source_device is not None and source_device.type != "cpu") or (
305
+ callable(source_contiguous) and not source_contiguous()
306
+ )):
307
+ raise ValueError("Pinned file staging accepts contiguous CPU tensors only")
308
+ size_bytes = source.numel() * source.element_size()
309
+ if size_bytes != file_slice.size_bytes:
310
+ raise ValueError("Safetensor slice size does not match the source tensor")
311
+ end = self._offset + size_bytes
312
+ if end > self.size_bytes:
313
+ raise RuntimeError(
314
+ f"Pinned staging buffer is too small: need {end / 1024**2:.1f} MiB, "
315
+ f"have {self.size_bytes / 1024**2:.1f} MiB"
316
+ )
317
+ if (
318
+ runs
319
+ and runs[-1][0].path == file_slice.path
320
+ and runs[-1][0].offset_bytes + runs[-1][2] == file_slice.offset_bytes
321
+ and runs[-1][1] + runs[-1][2] == self._offset
322
+ ):
323
+ previous_slice, destination_offset, run_bytes = runs[-1]
324
+ runs[-1] = (previous_slice, destination_offset, run_bytes + size_bytes)
325
+ else:
326
+ runs.append((file_slice, self._offset, size_bytes))
327
+ staged.append(self._active_buffer()[self._offset : end].view(dtype=source.dtype).view(source.shape))
328
+ self._offset = end
329
+ for file_slice, destination_offset, run_bytes in runs:
330
+ self._read_file_slice(
331
+ SafetensorFileSlice(file_slice.path, file_slice.offset_bytes, run_bytes),
332
+ self._active_buffer()[destination_offset : destination_offset + run_bytes],
333
+ )
334
+ assert self._offset - start == sum(file_slice.size_bytes for _source, file_slice in entries)
335
+ return staged
336
+
337
+ def stage_file_slices_async(
338
+ self, entries: list[tuple[torch.Tensor, "SafetensorFileSlice"]]
339
+ ) -> tuple[list[torch.Tensor], list[Any]]:
340
+ """Reserve one slot and start shard reads without blocking its consumer.
341
+
342
+ The caller owns the returned futures and must wait for them before
343
+ placing a CUDA DMA on this slot, then call :meth:`mark_upload` as
344
+ usual. Non-Windows transports deliberately retain the synchronous
345
+ path because their mmap fallback is already local and deterministic.
346
+ """
347
+
348
+ if self._windows_file_reader is None:
349
+ return self.stage_file_slices(entries), []
350
+ if not entries:
351
+ return [], []
352
+ start = self._offset
353
+ runs: list[tuple[SafetensorFileSlice, int, int]] = []
354
+ staged: list[torch.Tensor] = []
355
+ for source, file_slice in entries:
356
+ size_bytes = source.numel() * source.element_size()
357
+ if size_bytes != file_slice.size_bytes:
358
+ raise ValueError("Safetensor slice size does not match the source tensor")
359
+ end = self._offset + size_bytes
360
+ if end > self.size_bytes:
361
+ raise RuntimeError("Pinned staging buffer is too small for asynchronous file staging")
362
+ if (
363
+ runs
364
+ and runs[-1][0].path == file_slice.path
365
+ and runs[-1][0].offset_bytes + runs[-1][2] == file_slice.offset_bytes
366
+ and runs[-1][1] + runs[-1][2] == self._offset
367
+ ):
368
+ previous_slice, destination_offset, run_bytes = runs[-1]
369
+ runs[-1] = (previous_slice, destination_offset, run_bytes + size_bytes)
370
+ else:
371
+ runs.append((file_slice, self._offset, size_bytes))
372
+ staged.append(self._active_buffer()[self._offset : end].view(dtype=source.dtype).view(source.shape))
373
+ self._offset = end
374
+ futures = [
375
+ self._windows_file_reader.read_at_async(
376
+ file_slice.path,
377
+ file_slice.offset_bytes,
378
+ self._active_buffer()[destination_offset : destination_offset + run_bytes].data_ptr(),
379
+ run_bytes,
380
+ )
381
+ for file_slice, destination_offset, run_bytes in runs
382
+ ]
383
+ assert self._offset - start == sum(file_slice.size_bytes for _source, file_slice in entries)
384
+ return staged, futures
385
+
386
+ def _read_file_slice(self, file_slice: "SafetensorFileSlice", storage: torch.Tensor) -> None:
387
+ start = time.perf_counter()
388
+ if self._windows_file_reader is not None:
389
+ self._windows_file_reader.read_at(
390
+ file_slice.path,
391
+ file_slice.offset_bytes,
392
+ storage.data_ptr(),
393
+ file_slice.size_bytes,
394
+ )
395
+ self._record_shard_read(file_slice.size_bytes, time.perf_counter() - start)
396
+ return
397
+ target = memoryview(storage.numpy()).cast("B")
398
+ with self._file_lock:
399
+ mapped = self._checkpoint_maps.get(file_slice.path)
400
+ if mapped is None:
401
+ checkpoint = open(file_slice.path, "rb", buffering=0) # noqa: SIM115 - mapping owns this handle until close.
402
+ mapped = mmap.mmap(checkpoint.fileno(), 0, access=mmap.ACCESS_READ)
403
+ self._checkpoint_files[file_slice.path] = checkpoint
404
+ self._checkpoint_maps[file_slice.path] = mapped
405
+ end = file_slice.offset_bytes + file_slice.size_bytes
406
+ if end > mapped.size():
407
+ raise OSError("safetensor slice exceeds mapped shard")
408
+ target[:] = mapped[file_slice.offset_bytes:end]
409
+ read = file_slice.size_bytes
410
+ if read != file_slice.size_bytes:
411
+ raise OSError(
412
+ f"Short safetensor read from {file_slice.path!s}: expected {file_slice.size_bytes}, got {read}"
413
+ )
414
+ self._record_shard_read(file_slice.size_bytes, time.perf_counter() - start)
415
+
416
+ def _record_shard_read(self, size_bytes: int, seconds: float) -> None:
417
+ self._stats = PinnedStagingPoolStats(
418
+ slot_reuse_wait_seconds=self._stats.slot_reuse_wait_seconds,
419
+ slot_reuse_waits=self._stats.slot_reuse_waits,
420
+ source_copy_seconds=self._stats.source_copy_seconds,
421
+ source_copy_bytes=self._stats.source_copy_bytes,
422
+ shard_read_seconds=self._stats.shard_read_seconds + seconds,
423
+ shard_read_bytes=self._stats.shard_read_bytes + size_bytes,
424
+ )
425
+
426
+ @property
427
+ def transport_stats(self) -> PinnedStagingPoolStats:
428
+ """Return a stable snapshot; timings are host-wall-clock measurements."""
429
+ return self._stats
430
+
431
+ def mark_upload(self, event: Any) -> None:
432
+ if self._active_slot is None:
433
+ raise RuntimeError("Cannot mark a VMM upload without an active staging slot")
434
+ self._ready_events[self._active_slot] = event
435
+ self._active_slot = None
436
+
437
+ @property
438
+ def has_active_upload(self) -> bool:
439
+ """Whether the current materialization borrowed a staging slot.
440
+
441
+ A resident VMM group is acquired again on later denoise steps without
442
+ staging another host upload. Driver-DMA paths likewise bypass the
443
+ pool. Keeping this state explicit prevents either path from trying to
444
+ retire a slot that it never acquired.
445
+ """
446
+ return self._active_slot is not None
447
+
448
+ @property
449
+ def packed_bytes(self) -> torch.Tensor:
450
+ return self._active_buffer()[: self._offset]
451
+
452
+ @property
453
+ def uses_windows_overlapped_file_io(self) -> bool:
454
+ return self._windows_file_reader is not None
455
+
456
+ @property
457
+ def uses_registered_virtual_host(self) -> bool:
458
+ return bool(self._virtual_buffers)
459
+
460
+ def close(self) -> None:
461
+ if self._windows_file_reader is not None:
462
+ self._windows_file_reader.close()
463
+ self._windows_file_reader = None
464
+ with self._file_lock:
465
+ for mapped in self._checkpoint_maps.values():
466
+ mapped.close()
467
+ self._checkpoint_maps.clear()
468
+ for checkpoint in self._checkpoint_files.values():
469
+ checkpoint.close()
470
+ self._checkpoint_files.clear()
471
+ for buffer in reversed(self._virtual_buffers):
472
+ buffer.close()
473
+ self._virtual_buffers.clear()
474
+ self._buffers.clear()
475
+
476
+
477
+ @dataclass(frozen=True)
478
+ class SafetensorFileSlice:
479
+ """Byte range of a tensor payload in one local safetensors file."""
480
+
481
+ path: Path
482
+ offset_bytes: int
483
+ size_bytes: int
484
+ shape: tuple[int, ...] | None = None
485
+ dtype: str | None = None
486
+
487
+
488
+ class SafetensorSliceRegistry:
489
+ """Maps CPU storage addresses to immutable, shard-local file descriptors.
490
+
491
+ The registry deliberately keeps neither a tensor nor a mapped file alive:
492
+ its entries contain only a storage address, byte count, and frozen
493
+ :class:`SafetensorFileSlice`. The transport owns file mappings and must
494
+ close them separately before this registry is discarded.
495
+ """
496
+
497
+ def __init__(self) -> None:
498
+ self._slices: dict[tuple[int, int], SafetensorFileSlice] = {}
499
+ self._closed = False
500
+
501
+ def bind(self, tensor: torch.Tensor, file_slice: SafetensorFileSlice) -> bool:
502
+ self._require_open()
503
+ if tensor.device.type != "cpu" or not tensor.is_contiguous():
504
+ return False
505
+ size_bytes = tensor.numel() * tensor.element_size()
506
+ if size_bytes != file_slice.size_bytes:
507
+ return False
508
+ if file_slice.shape is not None and tuple(tensor.shape) != file_slice.shape:
509
+ return False
510
+ dtype_names = {
511
+ "BOOL": "torch.bool", "U8": "torch.uint8", "I8": "torch.int8",
512
+ "I16": "torch.int16", "I32": "torch.int32", "I64": "torch.int64",
513
+ "F16": "torch.float16", "BF16": "torch.bfloat16",
514
+ "F32": "torch.float32", "F64": "torch.float64",
515
+ "F8_E4M3": "torch.float8_e4m3fn", "F8_E5M2": "torch.float8_e5m2",
516
+ }
517
+ if file_slice.dtype is not None and dtype_names.get(file_slice.dtype) != str(tensor.dtype):
518
+ return False
519
+ key = (tensor.data_ptr(), size_bytes)
520
+ if key in self._slices and self._slices[key] != file_slice:
521
+ return False
522
+ self._slices[key] = file_slice
523
+ return True
524
+
525
+ def lookup(self, tensor: torch.Tensor) -> SafetensorFileSlice | None:
526
+ self._require_open()
527
+ return self._slices.get((tensor.data_ptr(), tensor.numel() * tensor.element_size()))
528
+
529
+ def rebind_many(self, replacements) -> None:
530
+ """Atomically relocate associations after value-preserving CPU copies.
531
+
532
+ The caller owns tensor/value equivalence and exclusive lifecycle access.
533
+ Immutable file descriptors do not change; validation failure leaves the
534
+ original associations intact. No tensor is retained by this registry.
535
+ """
536
+ self._require_open()
537
+ candidate = SafetensorSliceRegistry()
538
+ candidate._slices = dict(self._slices)
539
+ pending = []
540
+ for old, new in replacements:
541
+ descriptor = self.lookup(old)
542
+ if descriptor is None:
543
+ raise ValueError("Cannot relocate a tensor without source provenance")
544
+ pending.append((new, descriptor))
545
+ candidate._slices.pop((old.data_ptr(), old.numel() * old.element_size()), None)
546
+ for new, descriptor in pending:
547
+ if not candidate.bind(new, descriptor):
548
+ raise ValueError("Relocated CPU storage conflicts with source metadata")
549
+ self._slices = candidate._slices
550
+
551
+ @property
552
+ def descriptor_count(self) -> int:
553
+ return len(self._slices)
554
+
555
+ @property
556
+ def descriptor_bytes(self) -> int:
557
+ return sum(file_slice.size_bytes for file_slice in self._slices.values())
558
+
559
+ @property
560
+ def closed(self) -> bool:
561
+ return self._closed
562
+
563
+ def close(self) -> None:
564
+ """Drop all descriptors without retaining CPU tensor storage."""
565
+ self._slices.clear()
566
+ self._closed = True
567
+
568
+ def _require_open(self) -> None:
569
+ if self._closed:
570
+ raise RuntimeError("Safetensor slice registry is closed")
571
+
572
+
573
+ class RegisteredHostWeightRegistry:
574
+ """Bounded registration of immutable CPU weight storage for direct CUDA DMA.
575
+
576
+ Unlike ``Tensor.pin_memory()``, registration does not create a second host
577
+ copy. Each successful registration is retained until the VMM runtime is
578
+ detached, so an upload stream can use ``cuMemcpyHtoDAsync`` with the
579
+ original safetensor/PyTorch storage.
580
+ """
581
+
582
+ def __init__(self, device_id: int, *, max_bytes: int) -> None:
583
+ import torch
584
+
585
+ driver, _, Device = _cuda_modules()
586
+ torch.empty(1, device=f"cuda:{device_id}")
587
+ Device(device_id).set_current()
588
+ _require_success(driver.cuInit(0), "cuInit")
589
+ (device,) = _require_success(driver.cuDeviceGet(device_id), "cuDeviceGet")
590
+ (readonly_supported,) = _require_success(
591
+ driver.cuDeviceGetAttribute(
592
+ driver.CUdevice_attribute.CU_DEVICE_ATTRIBUTE_READ_ONLY_HOST_REGISTER_SUPPORTED,
593
+ device,
594
+ ),
595
+ "cuDeviceGetAttribute(READ_ONLY_HOST_REGISTER_SUPPORTED)",
596
+ )
597
+ self._readonly_supported = bool(readonly_supported)
598
+ if max_bytes <= 0:
599
+ raise ValueError("Registered host cache budget must be positive")
600
+ self.max_bytes = int(max_bytes)
601
+ self.registered_bytes = 0
602
+ self.skipped_bytes = 0
603
+ self._registrations: dict[tuple[int, int], tuple[torch.Tensor, bool]] = {}
604
+ self._budget_skips: set[tuple[int, int]] = set()
605
+ self._lock = threading.RLock()
606
+
607
+ def register(self, source: torch.Tensor) -> bool:
608
+ """Register ``source`` in place; return false if CUDA rejects it."""
609
+ if source.device.type != "cpu" or not source.is_contiguous():
610
+ return False
611
+ size_bytes = source.numel() * source.element_size()
612
+ if size_bytes <= 0:
613
+ return True
614
+ key = (source.data_ptr(), size_bytes)
615
+ with self._lock:
616
+ if key in self._registrations:
617
+ return True
618
+ if self.registered_bytes + size_bytes > self.max_bytes:
619
+ if key not in self._budget_skips:
620
+ self._budget_skips.add(key)
621
+ self.skipped_bytes += size_bytes
622
+ return False
623
+ driver, _, _ = _cuda_modules()
624
+ flags = driver.CU_MEMHOSTREGISTER_PORTABLE
625
+ if self._readonly_supported:
626
+ flags |= driver.CU_MEMHOSTREGISTER_READ_ONLY
627
+ result = driver.cuMemHostRegister(source.data_ptr(), size_bytes, flags)
628
+ if result[0] == driver.CUresult.CUDA_ERROR_HOST_MEMORY_ALREADY_REGISTERED:
629
+ # Adjacent safetensor views can share an OS page. CUDA rejects
630
+ # the duplicate registration, but the range is already usable
631
+ # for direct copies. Do not unregister a range we do not own.
632
+ self._registrations[key] = (source, False)
633
+ self.registered_bytes += size_bytes
634
+ return True
635
+ if result[0] != driver.CUresult.CUDA_SUCCESS:
636
+ return False
637
+ self._registrations[key] = (source, True)
638
+ self.registered_bytes += size_bytes
639
+ return True
640
+
641
+ def contains(self, source: torch.Tensor) -> bool:
642
+ return (source.data_ptr(), source.numel() * source.element_size()) in self._registrations
643
+
644
+ def close(self) -> None:
645
+ driver, _, _ = _cuda_modules()
646
+ with self._lock:
647
+ for (pointer, _size), (_source, owned) in self._registrations.items():
648
+ if owned:
649
+ _require_success(driver.cuMemHostUnregister(pointer), "cuMemHostUnregister")
650
+ self._registrations.clear()
651
+ self._budget_skips.clear()
652
+ self.registered_bytes = 0
653
+ self.skipped_bytes = 0
654
+
655
+
656
+ class VmmWeightStore:
657
+ """Private VMM cache with stable addresses and bounded resident backing.
658
+
659
+ Callers must keep a leased tensor only inside its context. Eviction waits
660
+ for the release event, then unmaps its physical backing while retaining the
661
+ slot's virtual address for a later materialization.
662
+ """
663
+
664
+ def __init__(self, device_id: int = 0, max_resident_bytes: int = 0) -> None:
665
+ import torch
666
+
667
+ if not torch.cuda.is_available():
668
+ raise RuntimeError("PyTorch CUDA is unavailable.")
669
+ if max_resident_bytes < 0:
670
+ raise ValueError("max_resident_bytes must be non-negative")
671
+ driver, _, Device = _cuda_modules()
672
+ torch.empty(1, device=f"cuda:{device_id}")
673
+ Device(device_id).set_current()
674
+ _require_success(driver.cuInit(0), "cuInit")
675
+ (device,) = _require_success(driver.cuDeviceGet(device_id), "cuDeviceGet")
676
+ (supported,) = _require_success(
677
+ driver.cuDeviceGetAttribute(
678
+ driver.CUdevice_attribute.CU_DEVICE_ATTRIBUTE_VIRTUAL_MEMORY_MANAGEMENT_SUPPORTED,
679
+ device,
680
+ ),
681
+ "cuDeviceGetAttribute(VMM)",
682
+ )
683
+ if not supported:
684
+ raise RuntimeError(f"CUDA device {device_id} does not support virtual memory management.")
685
+
686
+ prop = driver.CUmemAllocationProp()
687
+ prop.type = driver.CUmemAllocationType.CU_MEM_ALLOCATION_TYPE_PINNED
688
+ prop.location.type = driver.CUmemLocationType.CU_MEM_LOCATION_TYPE_DEVICE
689
+ prop.location.id = device_id
690
+ prop.requestedHandleTypes = driver.CUmemAllocationHandleType.CU_MEM_HANDLE_TYPE_NONE
691
+ (granularity,) = _require_success(
692
+ driver.cuMemGetAllocationGranularity(
693
+ prop, driver.CUmemAllocationGranularity_flags.CU_MEM_ALLOC_GRANULARITY_MINIMUM
694
+ ),
695
+ "cuMemGetAllocationGranularity",
696
+ )
697
+ self.device_id = device_id
698
+ self.max_resident_bytes = max_resident_bytes
699
+ self.granularity = int(granularity)
700
+ self._prop = prop
701
+ self._slots: dict[str, _VmmWeightSlot] = {}
702
+ self._stats = VmmWeightStoreStats()
703
+ self._lock = threading.RLock()
704
+
705
+ @property
706
+ def stats(self) -> VmmWeightStoreStats:
707
+ with self._lock:
708
+ return VmmWeightStoreStats(**self._stats.__dict__)
709
+
710
+ def reserve(self, key: str, size_bytes: int) -> None:
711
+ if not key:
712
+ raise ValueError("VMM slot key must not be empty")
713
+ if size_bytes <= 0:
714
+ raise ValueError("VMM slot size must be positive")
715
+ driver, _, _ = _cuda_modules()
716
+ with self._lock:
717
+ existing = self._slots.get(key)
718
+ if existing is not None:
719
+ if existing.size < size_bytes:
720
+ raise ValueError(f"Existing VMM slot {key!r} is smaller than the requested weight")
721
+ return
722
+ size = _round_up(size_bytes, self.granularity)
723
+ (address,) = _require_success(
724
+ driver.cuMemAddressReserve(size, self.granularity, 0, 0), "cuMemAddressReserve"
725
+ )
726
+ self._slots[key] = _VmmWeightSlot(key, address, size)
727
+ self._stats.reserved_bytes += size
728
+
729
+ def acquire(self, key: str, source: torch.Tensor, *, stream: Any | None = None) -> VmmWeightLease:
730
+ """Return a leased CUDA view, copying ``source`` only when first mapped."""
731
+ import torch
732
+
733
+ if source.device.type != "cpu":
734
+ raise ValueError("VmmWeightStore source weights must stay on CPU")
735
+ if not source.is_contiguous():
736
+ raise ValueError("VmmWeightStore source weights must be contiguous")
737
+ size_bytes = source.numel() * source.element_size()
738
+ self.reserve(key, size_bytes)
739
+ with self._lock:
740
+ slot = self._slots[key]
741
+ copy_stream = stream or torch.cuda.current_stream(self.device_id)
742
+ if slot.last_event is not None:
743
+ copy_stream.wait_event(slot.last_event)
744
+ if not slot.is_mapped:
745
+ self._ensure_capacity(slot.size)
746
+ self._map(slot)
747
+ typed = slot.storage.view(dtype=source.dtype)[: source.numel()].view(source.shape)
748
+ with torch.cuda.stream(copy_stream):
749
+ typed.copy_(source, non_blocking=source.is_pinned())
750
+ self._stats.materializations += 1
751
+ self._stats.copied_bytes += size_bytes
752
+ else:
753
+ typed = slot.storage.view(dtype=source.dtype)[: source.numel()].view(source.shape)
754
+ slot.active_leases += 1
755
+ slot.last_used = time.monotonic()
756
+ return VmmWeightLease(self, slot, typed)
757
+
758
+ def release(self, key: str) -> None:
759
+ import torch
760
+
761
+ with self._lock:
762
+ slot = self._slots[key]
763
+ if slot.active_leases <= 0:
764
+ raise RuntimeError(f"VMM slot {key!r} was released without an active lease")
765
+ slot.active_leases -= 1
766
+ slot.last_used = time.monotonic()
767
+ if slot.active_leases == 0:
768
+ slot.last_event = torch.cuda.Event()
769
+ slot.last_event.record(torch.cuda.current_stream(self.device_id))
770
+
771
+ def evict(self, key: str) -> bool:
772
+ with self._lock:
773
+ slot = self._slots[key]
774
+ if not slot.is_mapped:
775
+ return False
776
+ if slot.active_leases:
777
+ return False
778
+ if slot.last_event is not None:
779
+ slot.last_event.synchronize()
780
+ self._unmap(slot)
781
+ return True
782
+
783
+ def close(self) -> None:
784
+ driver, _, _ = _cuda_modules()
785
+ with self._lock:
786
+ for slot in list(self._slots.values()):
787
+ if slot.is_mapped:
788
+ if slot.active_leases:
789
+ raise RuntimeError(f"Cannot close VMM store with active lease {slot.key!r}")
790
+ if slot.last_event is not None:
791
+ slot.last_event.synchronize()
792
+ self._unmap(slot)
793
+ _require_success(driver.cuMemAddressFree(slot.address, slot.size), "cuMemAddressFree")
794
+ self._slots.clear()
795
+
796
+ def _ensure_capacity(self, required_bytes: int) -> None:
797
+ if self.max_resident_bytes <= 0:
798
+ return
799
+ while self._stats.resident_bytes + required_bytes > self.max_resident_bytes:
800
+ candidates = sorted(
801
+ (slot for slot in self._slots.values() if slot.is_mapped and not slot.active_leases),
802
+ key=lambda slot: slot.last_used,
803
+ )
804
+ if not candidates:
805
+ raise RuntimeError("VMM resident budget is too small for the requested weight")
806
+ self.evict(candidates[0].key)
807
+
808
+ def _map(self, slot: _VmmWeightSlot) -> None:
809
+ import torch
810
+
811
+ driver, Buffer, _ = _cuda_modules()
812
+ (handle,) = _require_success(driver.cuMemCreate(slot.size, self._prop, 0), "cuMemCreate")
813
+ try:
814
+ _require_success(driver.cuMemMap(slot.address, slot.size, 0, handle, 0), "cuMemMap")
815
+ access = driver.CUmemAccessDesc()
816
+ access.location.type = driver.CUmemLocationType.CU_MEM_LOCATION_TYPE_DEVICE
817
+ access.location.id = self.device_id
818
+ access.flags = driver.CUmemAccess_flags.CU_MEM_ACCESS_FLAGS_PROT_READWRITE
819
+ _require_success(driver.cuMemSetAccess(slot.address, slot.size, [access], 1), "cuMemSetAccess")
820
+ except BaseException:
821
+ driver.cuMemRelease(handle)
822
+ raise
823
+ slot.handle = handle
824
+ slot.buffer = Buffer.from_handle(slot.address, slot.size, owner=slot)
825
+ slot.storage = torch.from_dlpack(slot.buffer)
826
+ self._stats.resident_bytes += slot.size
827
+
828
+ def _unmap(self, slot: _VmmWeightSlot) -> None:
829
+ import gc
830
+
831
+ driver, _, _ = _cuda_modules()
832
+ slot.storage = None
833
+ slot.buffer = None
834
+ gc.collect()
835
+ _require_success(driver.cuMemUnmap(slot.address, slot.size), "cuMemUnmap")
836
+ _require_success(driver.cuMemRelease(slot.handle), "cuMemRelease")
837
+ slot.handle = None
838
+ slot.last_event = None
839
+ self._stats.resident_bytes -= slot.size
840
+ self._stats.evictions += 1