hypercache-io 0.9.0__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.
hypercache/datapath.py ADDED
@@ -0,0 +1,466 @@
1
+ """
2
+ HyperCache Zero-Copy Data Plane & GDS Reader Module.
3
+
4
+ Responsible for executing direct hardware DMA reads from raw NVMe block devices
5
+ (e.g., /dev/nvme0n1) into GPU VRAM (via kvikio.CuFile) or host memory.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import logging
11
+ import mmap
12
+ import os
13
+ import threading
14
+ from concurrent.futures import ThreadPoolExecutor
15
+ from dataclasses import dataclass
16
+ from typing import Any, Dict, List, Optional, Tuple, Union
17
+
18
+ logger = logging.getLogger("hypercache.datapath")
19
+
20
+ # Attempt importing kvikio for GPUDirect Storage (GDS)
21
+ _KVIKIO_AVAILABLE = False
22
+ _CUDA_AVAILABLE = False
23
+
24
+ try:
25
+ import kvikio
26
+ import kvikio.cufile
27
+ _KVIKIO_AVAILABLE = True
28
+ except (ImportError, Exception) as e:
29
+ logger.debug(f"kvikio is not available: {e}. Falling back to DirectBlockReader.")
30
+
31
+ try:
32
+ import torch
33
+ if torch.cuda.is_available():
34
+ _CUDA_AVAILABLE = True
35
+ except (ImportError, Exception):
36
+ pass
37
+
38
+
39
+ @dataclass(frozen=True)
40
+ class ChunkLocation:
41
+ """Represents the physical location of a striped chunk on a block device or shared memory."""
42
+ device: str
43
+ offset: int
44
+ length: int
45
+ tier: str = "nvme"
46
+
47
+ @classmethod
48
+ def from_dict(cls, data: dict) -> ChunkLocation:
49
+ return cls(
50
+ device=str(data["device"]),
51
+ offset=int(data["offset"]),
52
+ length=int(data["length"]),
53
+ tier=str(data.get("tier", "nvme")).lower(),
54
+ )
55
+
56
+ def to_dict(self) -> dict:
57
+ return {
58
+ "device": self.device,
59
+ "offset": self.offset,
60
+ "length": self.length,
61
+ "tier": self.tier,
62
+ }
63
+
64
+
65
+ class DataReader:
66
+ """Base interface for reading striped chunks from physical block devices."""
67
+
68
+ def read_range(
69
+ self,
70
+ chunk_layout: List[ChunkLocation],
71
+ start_offset: int,
72
+ length: int,
73
+ ) -> bytes:
74
+ """Reads a byte range [start_offset, start_offset + length) from the striped layout."""
75
+ raise NotImplementedError
76
+
77
+ def read_into_gpu(
78
+ self,
79
+ chunk_layout: List[ChunkLocation],
80
+ start_offset: int,
81
+ length: int,
82
+ gpu_buffer: Any,
83
+ ) -> int:
84
+ """Reads directly into GPU VRAM via GPUDirect Storage zero-copy DMA."""
85
+ raise NotImplementedError
86
+
87
+ def close(self) -> None:
88
+ """Close all open hardware device handles."""
89
+ pass
90
+
91
+
92
+ class DirectBlockReader(DataReader):
93
+ """
94
+ Direct Block Reader using os.pread on Linux block devices / mock backing files.
95
+ Serves as the high-speed CPU reader and fallback/testing harness.
96
+ Uses multi-threaded I/O submission to saturate SSD controller queue depth.
97
+ """
98
+
99
+ def __init__(self, max_workers: Optional[int] = None):
100
+ self._fd_cache: Dict[str, Tuple[Optional[int], int]] = {}
101
+ self._lock = threading.Lock()
102
+ self._closed = False
103
+ if max_workers is None:
104
+ max_workers = min(64, max(16, (os.cpu_count() or 4) * 4))
105
+ self._max_workers = max_workers
106
+ self._executor = ThreadPoolExecutor(max_workers=max_workers)
107
+
108
+ def _get_fds(self, device_path: str) -> Tuple[Optional[int], int]:
109
+ if device_path in self._fd_cache:
110
+ return self._fd_cache[device_path]
111
+ with self._lock:
112
+ if device_path not in self._fd_cache:
113
+ try:
114
+ fd_buffered = os.open(device_path, os.O_RDONLY)
115
+ except OSError as e:
116
+ logger.error(f"Failed to open device {device_path}: {e}")
117
+ raise
118
+
119
+ fd_direct = None
120
+ if hasattr(os, "O_DIRECT"):
121
+ try:
122
+ fd_direct = os.open(device_path, os.O_RDONLY | os.O_DIRECT)
123
+ except OSError:
124
+ pass
125
+
126
+ self._fd_cache[device_path] = (fd_direct, fd_buffered)
127
+ return self._fd_cache[device_path]
128
+
129
+ def read_range_into(
130
+ self,
131
+ chunk_layout: List[ChunkLocation],
132
+ start_offset: int,
133
+ length: int,
134
+ target_buffer: Any,
135
+ target_offset: int = 0,
136
+ ) -> int:
137
+ """Reads directly into a pre-allocated bytearray or memoryview with parallel Queue Depth submission."""
138
+ if length <= 0 or not chunk_layout:
139
+ return 0
140
+
141
+ current_virtual_offset = 0
142
+ view = memoryview(target_buffer)
143
+ tasks = []
144
+
145
+ for chunk in chunk_layout:
146
+ chunk_start = current_virtual_offset
147
+ chunk_end = current_virtual_offset + chunk.length
148
+ current_virtual_offset = chunk_end
149
+
150
+ # Check if this chunk overlaps with the requested range [start_offset, start_offset + length)
151
+ range_end = start_offset + length
152
+ if chunk_end <= start_offset or chunk_start >= range_end:
153
+ continue
154
+
155
+ # Calculate slice within this chunk
156
+ overlap_start = max(start_offset, chunk_start)
157
+ overlap_end = min(range_end, chunk_end)
158
+ overlap_len = overlap_end - overlap_start
159
+
160
+ offset_in_chunk = overlap_start - chunk_start
161
+ physical_device_offset = chunk.offset + offset_in_chunk
162
+
163
+ dest_pos = target_offset + (overlap_start - start_offset)
164
+ tasks.append((chunk.device, overlap_len, physical_device_offset, dest_pos))
165
+
166
+ if not tasks:
167
+ return 0
168
+
169
+ def _read_task(t):
170
+ dev_path, overlap_len, phys_offset, dest_pos = t
171
+ target_slice = view[dest_pos : dest_pos + overlap_len]
172
+
173
+ if dev_path.endswith(".shm") or "/shm" in dev_path:
174
+ try:
175
+ with open(dev_path, "rb") as f:
176
+ with mmap.mmap(f.fileno(), 0, flags=mmap.MAP_SHARED, prot=mmap.PROT_READ) as mm:
177
+ target_slice[:] = mm[phys_offset : phys_offset + overlap_len]
178
+ return overlap_len
179
+ except OSError as e:
180
+ logger.error(f"Failed reading SHM chunk {dev_path}: {e}")
181
+ raise
182
+
183
+ fd_direct, fd_buffered = self._get_fds(dev_path)
184
+
185
+ # Try direct DMA first if O_DIRECT is active and offsets are sector aligned
186
+ if fd_direct is not None and hasattr(os, "preadv") and overlap_len % 512 == 0 and phys_offset % 512 == 0:
187
+ try:
188
+ n = os.preadv(fd_direct, [target_slice], phys_offset)
189
+ if n == overlap_len:
190
+ return n
191
+ except OSError:
192
+ pass
193
+
194
+ # Robust fallback to buffered handle
195
+ if hasattr(os, "preadv"):
196
+ try:
197
+ n = os.preadv(fd_buffered, [target_slice], phys_offset)
198
+ if n == overlap_len:
199
+ return n
200
+ except OSError:
201
+ pass
202
+
203
+ chunk_data = os.pread(fd_buffered, overlap_len, phys_offset)
204
+ if len(chunk_data) != overlap_len:
205
+ raise IOError(
206
+ f"Short read at offset {phys_offset}: "
207
+ f"expected {overlap_len} bytes, got {len(chunk_data)}"
208
+ )
209
+ target_slice[:] = chunk_data
210
+ return len(chunk_data)
211
+
212
+ if len(tasks) == 1:
213
+ return _read_task(tasks[0])
214
+
215
+ # Parallel chunk I/O across SSD queue depth
216
+ results = list(self._executor.map(_read_task, tasks))
217
+ return sum(results)
218
+
219
+ def read_range(
220
+ self,
221
+ chunk_layout: List[ChunkLocation],
222
+ start_offset: int,
223
+ length: int,
224
+ ) -> Any:
225
+ if length <= 0 or not chunk_layout:
226
+ return b""
227
+
228
+ # Allocate page-aligned zero-copy buffer for multi-megabyte reads
229
+ if length >= 1024 * 1024:
230
+ result = mmap.mmap(-1, length)
231
+ else:
232
+ result = bytearray(length)
233
+
234
+ bytes_copied = self.read_range_into(chunk_layout, start_offset, length, result, 0)
235
+ return result[:bytes_copied] if bytes_copied < length else result
236
+
237
+ def read_into_gpu(
238
+ self,
239
+ chunk_layout: List[ChunkLocation],
240
+ start_offset: int,
241
+ length: int,
242
+ gpu_buffer: Any,
243
+ ) -> int:
244
+ """Fallback when GDS is unavailable: host read followed by HtoD copy."""
245
+ data = self.read_range(chunk_layout, start_offset, length)
246
+ try:
247
+ import torch
248
+ if isinstance(gpu_buffer, torch.Tensor):
249
+ # Copy host bytes into tensor
250
+ host_tensor = torch.frombuffer(data, dtype=torch.uint8)
251
+ gpu_buffer[:len(data)].copy_(host_tensor.to(gpu_buffer.device))
252
+ return len(data)
253
+ except Exception as e:
254
+ logger.warning(f"Could not copy into GPU tensor directly: {e}")
255
+ return len(data)
256
+
257
+ def close(self) -> None:
258
+ with self._lock:
259
+ self._closed = True
260
+ for fd_direct, fd_buffered in self._fd_cache.values():
261
+ if fd_direct is not None:
262
+ try:
263
+ os.close(fd_direct)
264
+ except Exception:
265
+ pass
266
+ try:
267
+ os.close(fd_buffered)
268
+ except Exception:
269
+ pass
270
+ self._fd_cache.clear()
271
+ self._executor.shutdown(wait=False)
272
+
273
+
274
+ class GDSReader(DataReader):
275
+ """
276
+ GPUDirect Storage (GDS) Zero-Copy Reader.
277
+ Uses kvikio.CuFile to execute direct DMA transfers from NVMe block devices to GPU VRAM.
278
+ """
279
+
280
+ def __init__(self):
281
+ if not _KVIKIO_AVAILABLE:
282
+ raise RuntimeError("kvikio is not installed. Cannot initialize GDSReader.")
283
+ self._cufile_cache: Dict[str, Any] = {}
284
+ self._fallback_reader = DirectBlockReader()
285
+
286
+ def _get_cufile(self, device_path: str) -> Any:
287
+ if device_path not in self._cufile_cache:
288
+ # kvikio.CuFile opens the physical block device (e.g. /dev/nvme0n1)
289
+ cf = kvikio.CuFile(device_path, flags="r")
290
+ self._cufile_cache[device_path] = cf
291
+ return self._cufile_cache[device_path]
292
+
293
+ def read_range(
294
+ self,
295
+ chunk_layout: List[ChunkLocation],
296
+ start_offset: int,
297
+ length: int,
298
+ ) -> bytes:
299
+ # For CPU bytes requests, fallback to DirectBlockReader
300
+ return self._fallback_reader.read_range(chunk_layout, start_offset, length)
301
+
302
+ def read_into_gpu(
303
+ self,
304
+ chunk_layout: List[ChunkLocation],
305
+ start_offset: int,
306
+ length: int,
307
+ gpu_buffer: Any,
308
+ ) -> int:
309
+ """
310
+ Executes GPUDirect reads directly into the GPU memory buffer (CuPy or PyTorch tensor).
311
+ Bypasses the host CPU entirely.
312
+ """
313
+ if length <= 0 or not chunk_layout:
314
+ return 0
315
+
316
+ current_virtual_offset = 0
317
+ bytes_transferred = 0
318
+ range_end = start_offset + length
319
+
320
+ for chunk in chunk_layout:
321
+ chunk_start = current_virtual_offset
322
+ chunk_end = current_virtual_offset + chunk.length
323
+ current_virtual_offset = chunk_end
324
+
325
+ if chunk_end <= start_offset or chunk_start >= range_end:
326
+ continue
327
+
328
+ overlap_start = max(start_offset, chunk_start)
329
+ overlap_end = min(range_end, chunk_end)
330
+ overlap_len = overlap_end - overlap_start
331
+
332
+ offset_in_chunk = overlap_start - chunk_start
333
+ physical_device_offset = chunk.offset + offset_in_chunk
334
+ dest_offset = overlap_start - start_offset
335
+
336
+ cufile = self._get_cufile(chunk.device)
337
+
338
+ # Extract GPU buffer pointer/slice
339
+ # kvikio accepts GPU buffers (CuPy array, PyTorch CUDA tensor, or ctypes pointer)
340
+ target_slice = gpu_buffer[dest_offset : dest_offset + overlap_len]
341
+ read_bytes = cufile.pread(target_slice, size=overlap_len, file_offset=physical_device_offset)
342
+
343
+ if read_bytes != overlap_len:
344
+ raise IOError(
345
+ f"GDS pread mismatch on {chunk.device}: expected {overlap_len} bytes, read {read_bytes}"
346
+ )
347
+
348
+ bytes_transferred += read_bytes
349
+ if bytes_transferred >= length:
350
+ break
351
+
352
+ return bytes_transferred
353
+
354
+ def close(self) -> None:
355
+ for cf in self._cufile_cache.values():
356
+ try:
357
+ cf.close()
358
+ except Exception:
359
+ pass
360
+ self._cufile_cache.clear()
361
+ self._fallback_reader.close()
362
+
363
+
364
+ _SHARED_READERS: Dict[bool, DataReader] = {}
365
+ _SHARED_READER_LOCK = threading.Lock()
366
+
367
+
368
+ def get_data_reader(prefer_gds: bool = True) -> DataReader:
369
+ """
370
+ Factory to return the optimal shared DataReader based on hardware environment.
371
+ Reuses open block-device file descriptors and DMA thread pools across requests.
372
+ """
373
+ with _SHARED_READER_LOCK:
374
+ existing = _SHARED_READERS.get(prefer_gds)
375
+ if existing is not None and not getattr(existing, "_closed", False):
376
+ return existing
377
+
378
+ if prefer_gds and _KVIKIO_AVAILABLE and _CUDA_AVAILABLE:
379
+ try:
380
+ reader: DataReader = GDSReader()
381
+ _SHARED_READERS[prefer_gds] = reader
382
+ return reader
383
+ except Exception as e:
384
+ logger.warning(f"Failed to initialize GDSReader: {e}. Falling back to DirectBlockReader.")
385
+ reader = DirectBlockReader()
386
+ _SHARED_READERS[prefer_gds] = reader
387
+ return reader
388
+
389
+
390
+ class DirectBlockWriter:
391
+ """
392
+ Direct Block Writer for write-back and write-through caching.
393
+ Writes byte slices to striped physical NVMe block devices or POSIX shared memory chunks.
394
+ """
395
+
396
+ def __init__(self, max_workers: Optional[int] = None):
397
+ self._fd_cache: Dict[str, int] = {}
398
+ if max_workers is None:
399
+ max_workers = min(64, max(16, (os.cpu_count() or 4) * 4))
400
+ self._max_workers = max_workers
401
+ self._executor = ThreadPoolExecutor(max_workers=max_workers)
402
+
403
+ def _get_write_fd(self, device_path: str) -> int:
404
+ if device_path not in self._fd_cache:
405
+ try:
406
+ fd = os.open(device_path, os.O_RDWR)
407
+ self._fd_cache[device_path] = fd
408
+ except OSError as e:
409
+ logger.error(f"Failed to open device {device_path} for write: {e}")
410
+ raise
411
+ return self._fd_cache[device_path]
412
+
413
+ def _write_ram_chunk(self, target_path: str, chunk_data: bytes) -> None:
414
+ os.makedirs(os.path.dirname(os.path.abspath(target_path)), exist_ok=True)
415
+ with open(target_path, "wb") as f:
416
+ f.write(chunk_data)
417
+
418
+ def write_chunks(
419
+ self,
420
+ chunk_layout: List[ChunkLocation],
421
+ data: Union[bytes, bytearray, memoryview],
422
+ ) -> int:
423
+ """Writes data slices directly to physical block devices / shm files across the striped layout."""
424
+ if not chunk_layout or not data:
425
+ return 0
426
+
427
+ view = memoryview(data)
428
+ total_len = len(view)
429
+ current_virtual_offset = 0
430
+ tasks = []
431
+
432
+ for chunk in chunk_layout:
433
+ chunk_start = current_virtual_offset
434
+ chunk_end = current_virtual_offset + chunk.length
435
+ current_virtual_offset = chunk_end
436
+
437
+ if chunk_start >= total_len:
438
+ break
439
+
440
+ slice_end = min(chunk_end, total_len)
441
+ slice_bytes = bytes(view[chunk_start:slice_end])
442
+
443
+ if chunk.tier == "ram":
444
+ tasks.append(self._executor.submit(self._write_ram_chunk, chunk.device, slice_bytes))
445
+ else:
446
+ fd = self._get_write_fd(chunk.device)
447
+ tasks.append(
448
+ self._executor.submit(os.pwrite, fd, slice_bytes, chunk.offset)
449
+ )
450
+
451
+ # Wait for all chunks to write
452
+ for t in tasks:
453
+ t.result()
454
+
455
+ return total_len
456
+
457
+ def close(self) -> None:
458
+ for fd in self._fd_cache.values():
459
+ try:
460
+ os.fsync(fd)
461
+ os.close(fd)
462
+ except Exception:
463
+ pass
464
+ self._fd_cache.clear()
465
+ self._executor.shutdown(wait=False)
466
+