loaderx 2.8.22__cp312-abi3-win_amd64.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.
- loaderx/__init__.py +33 -0
- loaderx/_dlpack.pyd +0 -0
- loaderx/_sampler.pyd +0 -0
- loaderx/_store.pyd +0 -0
- loaderx/allocator.py +262 -0
- loaderx/backend/__init__.py +36 -0
- loaderx/backend/_linux_dmabuf.py +180 -0
- loaderx/backend/amdgpu/__init__.py +10 -0
- loaderx/backend/amdgpu/_backend.py +157 -0
- loaderx/backend/amdgpu/_hip.py +531 -0
- loaderx/backend/cpu.py +61 -0
- loaderx/converter.py +243 -0
- loaderx/dataloader.py +240 -0
- loaderx/dtypes.py +139 -0
- loaderx/sampler.py +77 -0
- loaderx/zrecord.py +941 -0
- loaderx-2.8.22.dist-info/METADATA +1141 -0
- loaderx-2.8.22.dist-info/RECORD +21 -0
- loaderx-2.8.22.dist-info/WHEEL +5 -0
- loaderx-2.8.22.dist-info/licenses/LICENSE +21 -0
- loaderx-2.8.22.dist-info/top_level.txt +1 -0
loaderx/__init__.py
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
"""loaderx: a data loader over typed, ordered zrecord sequences.
|
|
2
|
+
|
|
3
|
+
The common allocation and loading entry points are exposed here; domain-specific
|
|
4
|
+
APIs remain in their own modules:
|
|
5
|
+
|
|
6
|
+
from loaderx import Allocator, Loader
|
|
7
|
+
from loaderx import dtypes
|
|
8
|
+
from loaderx.converter import convert, huggingface
|
|
9
|
+
from loaderx.zrecord import (
|
|
10
|
+
DLTensor, DenseStore, DenseWriter, RaggedStore, RaggedWriter,
|
|
11
|
+
RaggedBatch, ZrecordError,
|
|
12
|
+
)
|
|
13
|
+
from loaderx.sampler import Sampler
|
|
14
|
+
|
|
15
|
+
``dtypes`` is the canonical NumPy/ml_dtypes catalog supported by Loaderx's
|
|
16
|
+
DLPack contract. ``converter`` owns offline remote ingestion into completed
|
|
17
|
+
Zrecord streams. ``zrecord`` exposes the ``DLTensor`` / ``RaggedBatch`` transfer
|
|
18
|
+
contracts, the standalone ``train_dict`` step for Zrecord Views, and the
|
|
19
|
+
rebuildable typed ``DenseStore`` / ``DenseWriter`` / ``RaggedStore`` /
|
|
20
|
+
``RaggedWriter`` classes.
|
|
21
|
+
Constructing a Writer creates a container, while constructing a Store opens a
|
|
22
|
+
read-only container. ``close`` is the sole public publication boundary.
|
|
23
|
+
``dataloader`` composes named streams from positional placement views. ``Loader``
|
|
24
|
+
draws one global batch and materializes one shard through each view; it runs
|
|
25
|
+
synchronously with ``workers=0`` or overlaps gather and transform with positive
|
|
26
|
+
workers while ``prefetch`` adds independent ahead-batch capacity.
|
|
27
|
+
"""
|
|
28
|
+
|
|
29
|
+
from .allocator import Allocation, Allocator
|
|
30
|
+
from .dataloader import Loader
|
|
31
|
+
from . import dtypes
|
|
32
|
+
|
|
33
|
+
__all__ = ["Allocation", "Allocator", "Loader", "dtypes"]
|
loaderx/_dlpack.pyd
ADDED
|
Binary file
|
loaderx/_sampler.pyd
ADDED
|
Binary file
|
loaderx/_store.pyd
ADDED
|
Binary file
|
loaderx/allocator.py
ADDED
|
@@ -0,0 +1,262 @@
|
|
|
1
|
+
"""The common allocator and allocation lifecycle."""
|
|
2
|
+
|
|
3
|
+
import operator
|
|
4
|
+
import threading
|
|
5
|
+
|
|
6
|
+
import numpy as np
|
|
7
|
+
|
|
8
|
+
from .backend import _create_backend
|
|
9
|
+
from .dtypes import _normalize as _normalize_dtype
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def _positive_power_of_two(value, name):
|
|
13
|
+
if isinstance(value, (bool, np.bool_)):
|
|
14
|
+
raise TypeError(f"{name} must be an integer")
|
|
15
|
+
try:
|
|
16
|
+
value = operator.index(value)
|
|
17
|
+
except TypeError:
|
|
18
|
+
raise TypeError(f"{name} must be an integer") from None
|
|
19
|
+
if value < 1 or value & (value - 1):
|
|
20
|
+
raise ValueError(f"{name} must be a positive power of two")
|
|
21
|
+
return value
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _nonnegative_size(value):
|
|
25
|
+
if isinstance(value, (bool, np.bool_)):
|
|
26
|
+
raise TypeError("size must be an integer")
|
|
27
|
+
try:
|
|
28
|
+
value = operator.index(value)
|
|
29
|
+
except TypeError:
|
|
30
|
+
raise TypeError("size must be an integer") from None
|
|
31
|
+
if value < 0:
|
|
32
|
+
raise ValueError("size must be non-negative")
|
|
33
|
+
return value
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _device_id(value):
|
|
37
|
+
if isinstance(value, (bool, np.bool_)):
|
|
38
|
+
raise TypeError("device_id must be an integer")
|
|
39
|
+
try:
|
|
40
|
+
value = operator.index(value)
|
|
41
|
+
except TypeError:
|
|
42
|
+
raise TypeError("device_id must be an integer") from None
|
|
43
|
+
if value < 0:
|
|
44
|
+
raise ValueError("device_id must be non-negative")
|
|
45
|
+
return value
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _device_type(value):
|
|
49
|
+
if not isinstance(value, str):
|
|
50
|
+
raise TypeError("device_type must be a string")
|
|
51
|
+
value = value.lower()
|
|
52
|
+
if not value:
|
|
53
|
+
raise ValueError("device_type must be non-empty")
|
|
54
|
+
return value
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
class Allocation:
|
|
58
|
+
"""One exclusive allocator reservation retained by its output tensors."""
|
|
59
|
+
|
|
60
|
+
def __init__(self, allocator, region):
|
|
61
|
+
self._allocator = allocator
|
|
62
|
+
self._region = region
|
|
63
|
+
|
|
64
|
+
@property
|
|
65
|
+
def size(self):
|
|
66
|
+
return self._region.size
|
|
67
|
+
|
|
68
|
+
@property
|
|
69
|
+
def alignment(self):
|
|
70
|
+
return self._region.alignment
|
|
71
|
+
|
|
72
|
+
@property
|
|
73
|
+
def device(self):
|
|
74
|
+
return self._region.device
|
|
75
|
+
|
|
76
|
+
@property
|
|
77
|
+
def device_pointer(self):
|
|
78
|
+
return self._region.device_pointer
|
|
79
|
+
|
|
80
|
+
@property
|
|
81
|
+
def owner_base_ptr(self):
|
|
82
|
+
return self._region.owner_base_ptr
|
|
83
|
+
|
|
84
|
+
def view(self, dtype, shape, offset=0):
|
|
85
|
+
if self._region is None:
|
|
86
|
+
raise RuntimeError("allocation is released")
|
|
87
|
+
return self._region.view(_normalize_dtype(dtype), shape, offset)
|
|
88
|
+
|
|
89
|
+
def close(self):
|
|
90
|
+
allocator, self._allocator = self._allocator, None
|
|
91
|
+
region, self._region = self._region, None
|
|
92
|
+
if allocator is not None:
|
|
93
|
+
allocator._release(region)
|
|
94
|
+
|
|
95
|
+
def __enter__(self):
|
|
96
|
+
return self
|
|
97
|
+
|
|
98
|
+
def __exit__(self, exc_type, exc_value, traceback):
|
|
99
|
+
self.close()
|
|
100
|
+
|
|
101
|
+
def __del__(self):
|
|
102
|
+
try:
|
|
103
|
+
self.close()
|
|
104
|
+
except BaseException:
|
|
105
|
+
pass
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
class Allocator:
|
|
109
|
+
"""Manage one bounded pool for a named backend and device id.
|
|
110
|
+
|
|
111
|
+
The pool is shared by all views bound to this device allocator. View
|
|
112
|
+
request history belongs to the view; this object only owns physical
|
|
113
|
+
regions and the aggregate idle-byte budget.
|
|
114
|
+
"""
|
|
115
|
+
|
|
116
|
+
def __init__(self, device_type, device_id=0, *, minimum_size=None,
|
|
117
|
+
pool_size=None, _backend=None):
|
|
118
|
+
self._device_type = _device_type(device_type)
|
|
119
|
+
self._device_id = _device_id(device_id)
|
|
120
|
+
if _backend is None:
|
|
121
|
+
_backend = _create_backend(self._device_type, self._device_id)
|
|
122
|
+
self._backend = _backend
|
|
123
|
+
self._device = tuple(self._backend.device)
|
|
124
|
+
if minimum_size is None:
|
|
125
|
+
minimum_size = self._backend.minimum_size
|
|
126
|
+
self._minimum_size = _nonnegative_size(minimum_size)
|
|
127
|
+
if pool_size is None:
|
|
128
|
+
pool_size = self._backend.pool_size
|
|
129
|
+
self._pool_size = _nonnegative_size(pool_size)
|
|
130
|
+
self._free = []
|
|
131
|
+
self._cached_bytes = 0
|
|
132
|
+
self._closed = False
|
|
133
|
+
self._lock = threading.Lock()
|
|
134
|
+
|
|
135
|
+
@property
|
|
136
|
+
def device_type(self):
|
|
137
|
+
return self._device_type
|
|
138
|
+
|
|
139
|
+
@property
|
|
140
|
+
def device_id(self):
|
|
141
|
+
return self._device_id
|
|
142
|
+
|
|
143
|
+
@property
|
|
144
|
+
def device(self):
|
|
145
|
+
"""The immutable DLPack device identity of this allocator."""
|
|
146
|
+
return self._device
|
|
147
|
+
|
|
148
|
+
@property
|
|
149
|
+
def pool_size(self):
|
|
150
|
+
"""Maximum bytes retained by this allocator's idle pool."""
|
|
151
|
+
return self._pool_size
|
|
152
|
+
|
|
153
|
+
@property
|
|
154
|
+
def minimum_size(self):
|
|
155
|
+
"""Smallest allocation capacity required by this backend."""
|
|
156
|
+
return self._minimum_size
|
|
157
|
+
|
|
158
|
+
def size_class(self, size):
|
|
159
|
+
"""Return the backend-aware class covering a requested byte size."""
|
|
160
|
+
size = _nonnegative_size(size)
|
|
161
|
+
size = max(size, self._minimum_size)
|
|
162
|
+
return 1 << (size - 1).bit_length()
|
|
163
|
+
|
|
164
|
+
@property
|
|
165
|
+
def cached_bytes(self):
|
|
166
|
+
"""Bytes currently retained by the idle pool."""
|
|
167
|
+
with self._lock:
|
|
168
|
+
return self._cached_bytes
|
|
169
|
+
|
|
170
|
+
def _release_regions(self, regions):
|
|
171
|
+
error = None
|
|
172
|
+
for region in regions:
|
|
173
|
+
try:
|
|
174
|
+
self._backend.release(region)
|
|
175
|
+
except BaseException as exc:
|
|
176
|
+
if error is None:
|
|
177
|
+
error = exc
|
|
178
|
+
if error is not None:
|
|
179
|
+
raise error
|
|
180
|
+
|
|
181
|
+
def acquire(self, size, alignment=16):
|
|
182
|
+
size = _nonnegative_size(size)
|
|
183
|
+
alignment = _positive_power_of_two(alignment, "alignment")
|
|
184
|
+
requested_class = self.size_class(size)
|
|
185
|
+
with self._lock:
|
|
186
|
+
if self._closed:
|
|
187
|
+
raise RuntimeError("allocator is closed")
|
|
188
|
+
suitable = [
|
|
189
|
+
(region.size, i) for i, region in enumerate(self._free)
|
|
190
|
+
if region.size >= size and region.alignment >= alignment
|
|
191
|
+
]
|
|
192
|
+
if suitable:
|
|
193
|
+
_capacity, index = min(suitable)
|
|
194
|
+
region = self._free.pop(index)
|
|
195
|
+
self._cached_bytes -= region.size
|
|
196
|
+
return Allocation(self, region)
|
|
197
|
+
try:
|
|
198
|
+
region = self._allocate(requested_class, alignment)
|
|
199
|
+
except Exception:
|
|
200
|
+
free, self._free = self._free, []
|
|
201
|
+
self._cached_bytes = 0
|
|
202
|
+
if not free:
|
|
203
|
+
raise
|
|
204
|
+
self._release_regions(free)
|
|
205
|
+
region = self._allocate(requested_class, alignment)
|
|
206
|
+
if region.size < requested_class or region.alignment < alignment:
|
|
207
|
+
self._backend.release(region)
|
|
208
|
+
raise RuntimeError(
|
|
209
|
+
"allocator returned an undersized or unaligned region"
|
|
210
|
+
)
|
|
211
|
+
if tuple(region.device) != self.device:
|
|
212
|
+
self._backend.release(region)
|
|
213
|
+
raise RuntimeError(
|
|
214
|
+
"allocator returned a region for the wrong device"
|
|
215
|
+
)
|
|
216
|
+
return Allocation(self, region)
|
|
217
|
+
|
|
218
|
+
def _allocate(self, size, alignment):
|
|
219
|
+
return self._backend.allocate(size, alignment)
|
|
220
|
+
|
|
221
|
+
def _release(self, region):
|
|
222
|
+
evicted = []
|
|
223
|
+
with self._lock:
|
|
224
|
+
retain = not self._closed and region.size <= self._pool_size
|
|
225
|
+
if retain:
|
|
226
|
+
while (
|
|
227
|
+
self._free
|
|
228
|
+
and self._cached_bytes + region.size > self._pool_size
|
|
229
|
+
):
|
|
230
|
+
old = self._free.pop(0)
|
|
231
|
+
self._cached_bytes -= old.size
|
|
232
|
+
evicted.append(old)
|
|
233
|
+
self._free.append(region)
|
|
234
|
+
self._cached_bytes += region.size
|
|
235
|
+
if evicted:
|
|
236
|
+
self._release_regions(evicted)
|
|
237
|
+
if not retain:
|
|
238
|
+
self._backend.release(region)
|
|
239
|
+
|
|
240
|
+
def close(self):
|
|
241
|
+
with self._lock:
|
|
242
|
+
if self._closed:
|
|
243
|
+
return
|
|
244
|
+
self._closed = True
|
|
245
|
+
free, self._free = self._free, []
|
|
246
|
+
self._cached_bytes = 0
|
|
247
|
+
self._release_regions(free)
|
|
248
|
+
|
|
249
|
+
def __enter__(self):
|
|
250
|
+
return self
|
|
251
|
+
|
|
252
|
+
def __exit__(self, exc_type, exc_value, traceback):
|
|
253
|
+
self.close()
|
|
254
|
+
|
|
255
|
+
def __del__(self):
|
|
256
|
+
try:
|
|
257
|
+
self.close()
|
|
258
|
+
except BaseException:
|
|
259
|
+
pass
|
|
260
|
+
|
|
261
|
+
|
|
262
|
+
__all__ = ["Allocation", "Allocator"]
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
"""Device-specific Region backends used by the common Allocator."""
|
|
2
|
+
|
|
3
|
+
import importlib
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
_BACKENDS = {}
|
|
7
|
+
_BUILTINS = {
|
|
8
|
+
"cpu": ".cpu",
|
|
9
|
+
"amdgpu": ".amdgpu",
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def _register_backend(name, factory):
|
|
14
|
+
current = _BACKENDS.get(name)
|
|
15
|
+
if current is not None and current is not factory:
|
|
16
|
+
raise RuntimeError(f"backend {name!r} is already registered")
|
|
17
|
+
_BACKENDS[name] = factory
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def _create_backend(name, device_id):
|
|
21
|
+
factory = _BACKENDS.get(name)
|
|
22
|
+
if factory is None:
|
|
23
|
+
module_name = _BUILTINS.get(name)
|
|
24
|
+
if module_name is None:
|
|
25
|
+
supported = ", ".join(sorted(_BUILTINS))
|
|
26
|
+
raise ValueError(
|
|
27
|
+
f"unsupported device_type {name!r}; expected one of {supported}"
|
|
28
|
+
)
|
|
29
|
+
importlib.import_module(module_name, __name__)
|
|
30
|
+
factory = _BACKENDS.get(name)
|
|
31
|
+
if factory is None:
|
|
32
|
+
raise RuntimeError(f"backend {name!r} did not register itself")
|
|
33
|
+
return factory(device_id)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
__all__ = []
|
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
"""Ownership for a CPU-mapped Linux dma-buf."""
|
|
2
|
+
|
|
3
|
+
import mmap
|
|
4
|
+
import os
|
|
5
|
+
import threading
|
|
6
|
+
import weakref
|
|
7
|
+
|
|
8
|
+
import numpy as np
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
_regions = {}
|
|
12
|
+
_regions_lock = threading.Lock()
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def _register_region(region):
|
|
16
|
+
with _regions_lock:
|
|
17
|
+
regions = _regions.get(region.device)
|
|
18
|
+
if regions is None:
|
|
19
|
+
regions = _regions[region.device] = weakref.WeakSet()
|
|
20
|
+
regions.add(region)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _unregister_region(region):
|
|
24
|
+
with _regions_lock:
|
|
25
|
+
regions = _regions.get(region.device)
|
|
26
|
+
if regions is None:
|
|
27
|
+
return
|
|
28
|
+
regions.discard(region)
|
|
29
|
+
if not regions:
|
|
30
|
+
_regions.pop(region.device, None)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _device_region(device, pointer, size):
|
|
34
|
+
"""Find a Loaderx-owned region and offset covering a device range."""
|
|
35
|
+
end = pointer + size
|
|
36
|
+
with _regions_lock:
|
|
37
|
+
for region in tuple(_regions.get(tuple(device), ())):
|
|
38
|
+
start = region.device_pointer
|
|
39
|
+
if (not region._closed and start <= pointer and
|
|
40
|
+
end <= start + region.size):
|
|
41
|
+
return region, pointer - start
|
|
42
|
+
return None
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class _MappedDMABufRegion:
|
|
46
|
+
"""Own one device-bound CPU mapping of a dma-buf ``fd``.
|
|
47
|
+
|
|
48
|
+
The ``fd`` is duplicated on construction, so the caller keeps its own
|
|
49
|
+
ownership. ``size`` is the byte span to map and ``offset`` the file offset
|
|
50
|
+
within the dma-buf. ``device`` is the immutable DLPack device identity for
|
|
51
|
+
every tensor derived from the region. ``view(dtype, shape)`` exposes the
|
|
52
|
+
mapped device pages to CPU code.
|
|
53
|
+
"""
|
|
54
|
+
|
|
55
|
+
def __init__(
|
|
56
|
+
self, fd, size, device_type, device_id=0, offset=0, *,
|
|
57
|
+
writable=True,
|
|
58
|
+
):
|
|
59
|
+
if size < 0:
|
|
60
|
+
raise ValueError("dma-buf region size must be non-negative")
|
|
61
|
+
if offset < 0:
|
|
62
|
+
raise ValueError("dma-buf mapping offset must be non-negative")
|
|
63
|
+
self._fd = os.dup(fd)
|
|
64
|
+
self.size = size
|
|
65
|
+
self._device = (device_type, device_id)
|
|
66
|
+
self._closed = False
|
|
67
|
+
self._mapped = None
|
|
68
|
+
self._device_pointer = 0
|
|
69
|
+
self._owner_base_ptr = 0
|
|
70
|
+
self._pointer_owner = None
|
|
71
|
+
try:
|
|
72
|
+
protection = mmap.PROT_READ
|
|
73
|
+
if writable:
|
|
74
|
+
protection |= mmap.PROT_WRITE
|
|
75
|
+
self._mapped = mmap.mmap(
|
|
76
|
+
self._fd, size, mmap.MAP_SHARED,
|
|
77
|
+
protection, offset=offset,
|
|
78
|
+
)
|
|
79
|
+
except BaseException:
|
|
80
|
+
os.close(self._fd)
|
|
81
|
+
raise
|
|
82
|
+
self._owner_base_ptr = self.view(
|
|
83
|
+
np.uint8, (self.size,),
|
|
84
|
+
).__array_interface__["data"][0]
|
|
85
|
+
self.alignment = self._owner_base_ptr & -self._owner_base_ptr
|
|
86
|
+
|
|
87
|
+
@property
|
|
88
|
+
def fd(self):
|
|
89
|
+
return self._fd
|
|
90
|
+
|
|
91
|
+
@property
|
|
92
|
+
def device(self):
|
|
93
|
+
"""Immutable ``(DLPack device type, logical device id)`` binding."""
|
|
94
|
+
return self._device
|
|
95
|
+
|
|
96
|
+
@property
|
|
97
|
+
def device_type(self):
|
|
98
|
+
return self._device[0]
|
|
99
|
+
|
|
100
|
+
@property
|
|
101
|
+
def device_id(self):
|
|
102
|
+
return self._device[1]
|
|
103
|
+
|
|
104
|
+
@property
|
|
105
|
+
def device_pointer(self):
|
|
106
|
+
return self._device_pointer
|
|
107
|
+
|
|
108
|
+
@property
|
|
109
|
+
def owner_base_ptr(self):
|
|
110
|
+
return self._owner_base_ptr
|
|
111
|
+
|
|
112
|
+
def bind_device_pointer(self, pointer, *, owner=None):
|
|
113
|
+
"""Bind and publish the framework-visible device pointer."""
|
|
114
|
+
if self._closed:
|
|
115
|
+
raise RuntimeError("cannot bind a closed dma-buf region")
|
|
116
|
+
pointer = int(pointer)
|
|
117
|
+
if pointer <= 0:
|
|
118
|
+
raise ValueError("device pointer must be non-zero")
|
|
119
|
+
if self._device_pointer:
|
|
120
|
+
raise RuntimeError("dma-buf region already has a device pointer")
|
|
121
|
+
self._device_pointer = pointer
|
|
122
|
+
self.alignment = min(self.alignment, pointer & -pointer)
|
|
123
|
+
self._pointer_owner = owner
|
|
124
|
+
_register_region(self)
|
|
125
|
+
|
|
126
|
+
def view(self, dtype, shape, offset=0):
|
|
127
|
+
"""A numpy view of the mapped bytes.
|
|
128
|
+
|
|
129
|
+
The region may be larger than this gather needs (a borrowed buffer is
|
|
130
|
+
reused across batches); only the leading ``count`` elements at ``offset``
|
|
131
|
+
are viewed.
|
|
132
|
+
"""
|
|
133
|
+
if self._closed:
|
|
134
|
+
raise RuntimeError("dma-buf region is closed")
|
|
135
|
+
if offset < 0:
|
|
136
|
+
raise ValueError("offset must be non-negative")
|
|
137
|
+
count = int(np.prod(shape))
|
|
138
|
+
needed = count * np.dtype(dtype).itemsize
|
|
139
|
+
if offset + needed > self.size:
|
|
140
|
+
raise ValueError(
|
|
141
|
+
f"dma-buf region holds {self.size} bytes, view at offset "
|
|
142
|
+
f"{offset} needs {needed}"
|
|
143
|
+
)
|
|
144
|
+
return np.frombuffer(
|
|
145
|
+
self._mapped, dtype=dtype, count=count, offset=offset,
|
|
146
|
+
).reshape(shape)
|
|
147
|
+
|
|
148
|
+
def close(self):
|
|
149
|
+
"""Release the pointer owner, mapping, and duplicated descriptor."""
|
|
150
|
+
if self._closed:
|
|
151
|
+
return
|
|
152
|
+
self._closed = True
|
|
153
|
+
if self._device_pointer:
|
|
154
|
+
_unregister_region(self)
|
|
155
|
+
owner, self._pointer_owner = self._pointer_owner, None
|
|
156
|
+
try:
|
|
157
|
+
if owner is not None:
|
|
158
|
+
owner.close()
|
|
159
|
+
finally:
|
|
160
|
+
self._device_pointer = 0
|
|
161
|
+
self._owner_base_ptr = 0
|
|
162
|
+
self._mapped = None
|
|
163
|
+
if self._fd >= 0:
|
|
164
|
+
os.close(self._fd)
|
|
165
|
+
self._fd = -1
|
|
166
|
+
|
|
167
|
+
def __del__(self):
|
|
168
|
+
try:
|
|
169
|
+
self.close()
|
|
170
|
+
except BaseException:
|
|
171
|
+
pass
|
|
172
|
+
|
|
173
|
+
def __repr__(self):
|
|
174
|
+
return (
|
|
175
|
+
f"_MappedDMABufRegion(size={self.size}, device={self.device}, "
|
|
176
|
+
f"closed={self._closed})"
|
|
177
|
+
)
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
__all__ = []
|
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
"""Linux AMDGPU allocation exported to HIP through dma-buf."""
|
|
2
|
+
|
|
3
|
+
import fcntl
|
|
4
|
+
import glob
|
|
5
|
+
import os
|
|
6
|
+
import struct
|
|
7
|
+
|
|
8
|
+
from ..._dlpack import kDLROCM
|
|
9
|
+
from .._linux_dmabuf import _MappedDMABufRegion
|
|
10
|
+
from ._hip import (
|
|
11
|
+
_device_by_pci_bus_id,
|
|
12
|
+
_device_pci_bus_id,
|
|
13
|
+
_gpu_pointer,
|
|
14
|
+
_load_hip,
|
|
15
|
+
_pci_bdf,
|
|
16
|
+
)
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
_DRM_IOCTL_BASE = ord("d")
|
|
20
|
+
_DRM_AMDGPU_GEM_CREATE = 0x40
|
|
21
|
+
_DRM_PRIME_HANDLE_TO_FD = 0x2D
|
|
22
|
+
_DRM_IOC_READWRITE = 3
|
|
23
|
+
_DRM_IOC_DIRSHIFT = 30
|
|
24
|
+
_DRM_IOC_TYPESHIFT = 8
|
|
25
|
+
_DRM_IOC_SIZESHIFT = 16
|
|
26
|
+
_AMDGPU_GEM_DOMAIN_GTT = 0x00000002
|
|
27
|
+
_AMDGPU_GEM_DOMAIN_VRAM = 0x00000004
|
|
28
|
+
_AMDGPU_GEM_CREATE_CPU_ACCESS_REQUIRED = 1 << 0
|
|
29
|
+
_AMDGPU_GEM_CPU_ACCESSIBLE_DOMAINS = (
|
|
30
|
+
_AMDGPU_GEM_DOMAIN_GTT | _AMDGPU_GEM_DOMAIN_VRAM
|
|
31
|
+
)
|
|
32
|
+
|
|
33
|
+
_DRM_AMDGPU_GEM_CREATE_REQ = (
|
|
34
|
+
(_DRM_IOC_READWRITE << _DRM_IOC_DIRSHIFT)
|
|
35
|
+
| (32 << _DRM_IOC_SIZESHIFT)
|
|
36
|
+
| (_DRM_IOCTL_BASE << _DRM_IOC_TYPESHIFT)
|
|
37
|
+
| _DRM_AMDGPU_GEM_CREATE
|
|
38
|
+
)
|
|
39
|
+
_DRM_PRIME_HANDLE_TO_FD_REQ = (
|
|
40
|
+
(_DRM_IOC_READWRITE << _DRM_IOC_DIRSHIFT)
|
|
41
|
+
| (12 << _DRM_IOC_SIZESHIFT)
|
|
42
|
+
| (_DRM_IOCTL_BASE << _DRM_IOC_TYPESHIFT)
|
|
43
|
+
| _DRM_PRIME_HANDLE_TO_FD
|
|
44
|
+
)
|
|
45
|
+
|
|
46
|
+
# drm_amdgpu_gem_create is a 32-byte union whose output handle overlaps input.
|
|
47
|
+
_GEM_CREATE = struct.Struct("<QQQQ")
|
|
48
|
+
_PRIME = struct.Struct("<IIi")
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def _render_node_info(path):
|
|
52
|
+
"""Return the PCI BDF for an amdgpu render node."""
|
|
53
|
+
name = os.path.basename(os.path.normpath(path))
|
|
54
|
+
if not name.startswith("renderD") or not name[7:].isdigit():
|
|
55
|
+
raise OSError(f"{path!r} is not a render-node path")
|
|
56
|
+
try:
|
|
57
|
+
with open(f"/sys/class/drm/{name}/device/uevent") as file:
|
|
58
|
+
fields = dict(
|
|
59
|
+
line.rstrip("\n").split("=", 1)
|
|
60
|
+
for line in file if "=" in line
|
|
61
|
+
)
|
|
62
|
+
except OSError as exc:
|
|
63
|
+
raise OSError(f"cannot inspect render node {path!r}: {exc}") from exc
|
|
64
|
+
if fields.get("DRIVER") != "amdgpu":
|
|
65
|
+
raise OSError(f"render node {path!r} is not driven by amdgpu")
|
|
66
|
+
slot = fields.get("PCI_SLOT_NAME")
|
|
67
|
+
if not slot:
|
|
68
|
+
raise OSError(f"render node {path!r} has no PCI_SLOT_NAME")
|
|
69
|
+
return _pci_bdf(slot)
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def _resolve_render_node(device):
|
|
73
|
+
"""Resolve a HIP logical id or render-node path to both representations."""
|
|
74
|
+
if device is None:
|
|
75
|
+
device = 0
|
|
76
|
+
elif not isinstance(device, (int, str)) or isinstance(device, bool):
|
|
77
|
+
raise TypeError(
|
|
78
|
+
"device must be a HIP logical device id, a render-node path, or None"
|
|
79
|
+
)
|
|
80
|
+
hip = _load_hip()
|
|
81
|
+
if isinstance(device, int):
|
|
82
|
+
if device < 0:
|
|
83
|
+
raise ValueError("HIP device id must be non-negative")
|
|
84
|
+
bus_id = _device_pci_bus_id(hip, device)
|
|
85
|
+
for path in sorted(glob.glob("/dev/dri/renderD*")):
|
|
86
|
+
try:
|
|
87
|
+
if _render_node_info(path) == bus_id:
|
|
88
|
+
return path, device
|
|
89
|
+
except OSError:
|
|
90
|
+
continue
|
|
91
|
+
raise OSError(
|
|
92
|
+
f"no amdgpu render node found for HIP device {device} ({bus_id})"
|
|
93
|
+
)
|
|
94
|
+
if not os.path.exists(device):
|
|
95
|
+
raise OSError(f"render node {device!r} does not exist")
|
|
96
|
+
bus_id = _render_node_info(device)
|
|
97
|
+
return device, _device_by_pci_bus_id(hip, bus_id)
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def _allocate_region(size, render_node, device_id, alignment=4096):
|
|
101
|
+
node = os.open(render_node, os.O_RDWR | os.O_CLOEXEC)
|
|
102
|
+
try:
|
|
103
|
+
create = bytearray(_GEM_CREATE.pack(
|
|
104
|
+
size, max(4096, alignment), _AMDGPU_GEM_CPU_ACCESSIBLE_DOMAINS,
|
|
105
|
+
_AMDGPU_GEM_CREATE_CPU_ACCESS_REQUIRED,
|
|
106
|
+
))
|
|
107
|
+
fcntl.ioctl(node, _DRM_AMDGPU_GEM_CREATE_REQ, create, True)
|
|
108
|
+
handle = _GEM_CREATE.unpack(create)[0] & 0xFFFFFFFF
|
|
109
|
+
prime = bytearray(_PRIME.pack(handle, os.O_RDWR, 0))
|
|
110
|
+
fcntl.ioctl(node, _DRM_PRIME_HANDLE_TO_FD_REQ, prime, True)
|
|
111
|
+
dma_fd = _PRIME.unpack(prime)[2]
|
|
112
|
+
finally:
|
|
113
|
+
os.close(node)
|
|
114
|
+
try:
|
|
115
|
+
region = _MappedDMABufRegion(dma_fd, size, kDLROCM, device_id)
|
|
116
|
+
finally:
|
|
117
|
+
os.close(dma_fd)
|
|
118
|
+
try:
|
|
119
|
+
_gpu_pointer(region)
|
|
120
|
+
except BaseException:
|
|
121
|
+
region.close()
|
|
122
|
+
raise
|
|
123
|
+
return region
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
class _AMDGPUBackend:
|
|
127
|
+
"""Pooled Linux AMDGPU Region backend for one HIP logical device.
|
|
128
|
+
|
|
129
|
+
Store writes each allocation through its CPU mapping, while Torch and JAX
|
|
130
|
+
consume the same allocation through its HIP pointer and DLPack. The amdgpu
|
|
131
|
+
driver owns physical placement; Loaderx uses one path for integrated and
|
|
132
|
+
discrete GPUs and does not expose kernel memory domains.
|
|
133
|
+
"""
|
|
134
|
+
|
|
135
|
+
minimum_size = 4096
|
|
136
|
+
pool_size = 1 << 30
|
|
137
|
+
|
|
138
|
+
def __init__(self, render_node, device_id):
|
|
139
|
+
self._render_node = render_node
|
|
140
|
+
self.device = (kDLROCM, device_id)
|
|
141
|
+
|
|
142
|
+
def allocate(self, size, alignment):
|
|
143
|
+
return _allocate_region(
|
|
144
|
+
size, self._render_node, self.device[1], alignment,
|
|
145
|
+
)
|
|
146
|
+
|
|
147
|
+
@staticmethod
|
|
148
|
+
def release(region):
|
|
149
|
+
region.close()
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def _create(device_id):
|
|
153
|
+
render_node, resolved_id = _resolve_render_node(device_id)
|
|
154
|
+
return _AMDGPUBackend(render_node, resolved_id)
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
__all__ = []
|