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/__init__.py +61 -0
- hypercache/client.py +456 -0
- hypercache/datapath.py +466 -0
- hypercache/fsspec_fs.py +457 -0
- hypercache/integrations/__init__.py +25 -0
- hypercache/integrations/dcp.py +147 -0
- hypercache/integrations/safetensors_loader.py +247 -0
- hypercache/kv_store.py +151 -0
- hypercache/pipeline.py +182 -0
- hypercache_io-0.9.0.dist-info/METADATA +115 -0
- hypercache_io-0.9.0.dist-info/RECORD +14 -0
- hypercache_io-0.9.0.dist-info/WHEEL +5 -0
- hypercache_io-0.9.0.dist-info/entry_points.txt +2 -0
- hypercache_io-0.9.0.dist-info/top_level.txt +1 -0
hypercache/fsspec_fs.py
ADDED
|
@@ -0,0 +1,457 @@
|
|
|
1
|
+
"""
|
|
2
|
+
HyperCache fsspec (AbstractFileSystem) Implementation.
|
|
3
|
+
|
|
4
|
+
Seamlessly intercepts hypercache:// URIs for PyTorch, Hugging Face, and Safetensors.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import io
|
|
10
|
+
import logging
|
|
11
|
+
import os
|
|
12
|
+
from typing import Any, Dict, List, Optional
|
|
13
|
+
|
|
14
|
+
import fsspec
|
|
15
|
+
from fsspec.spec import AbstractBufferedFile, AbstractFileSystem
|
|
16
|
+
|
|
17
|
+
from hypercache.client import HyperCacheClient, LocateResult, StageWriteResult
|
|
18
|
+
from hypercache.datapath import DataReader, DirectBlockWriter, get_data_reader
|
|
19
|
+
|
|
20
|
+
logger = logging.getLogger("hypercache.fsspec")
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class HyperCacheFile(io.RawIOBase):
|
|
24
|
+
"""
|
|
25
|
+
Seekable, readable Python stream backed by physical striped NVMe block devices.
|
|
26
|
+
"""
|
|
27
|
+
|
|
28
|
+
def __init__(
|
|
29
|
+
self,
|
|
30
|
+
fs: HyperCacheFileSystem,
|
|
31
|
+
uri: str,
|
|
32
|
+
locate_result: LocateResult,
|
|
33
|
+
reader: DataReader,
|
|
34
|
+
mode: str = "rb",
|
|
35
|
+
):
|
|
36
|
+
super().__init__()
|
|
37
|
+
self.fs = fs
|
|
38
|
+
self.uri = uri
|
|
39
|
+
self.locate_result = locate_result
|
|
40
|
+
self.reader = reader
|
|
41
|
+
self.mode = mode
|
|
42
|
+
self._pos = 0
|
|
43
|
+
self._size = locate_result.object_size
|
|
44
|
+
self._closed = False
|
|
45
|
+
|
|
46
|
+
def readable(self) -> bool:
|
|
47
|
+
return "r" in self.mode and not self._closed
|
|
48
|
+
|
|
49
|
+
def seekable(self) -> bool:
|
|
50
|
+
return not self._closed
|
|
51
|
+
|
|
52
|
+
def writable(self) -> bool:
|
|
53
|
+
return False
|
|
54
|
+
|
|
55
|
+
def tell(self) -> int:
|
|
56
|
+
return self._pos
|
|
57
|
+
|
|
58
|
+
def seek(self, offset: int, whence: int = io.SEEK_SET) -> int:
|
|
59
|
+
if self._closed:
|
|
60
|
+
raise ValueError("I/O operation on closed HyperCacheFile")
|
|
61
|
+
|
|
62
|
+
if whence == io.SEEK_SET:
|
|
63
|
+
new_pos = offset
|
|
64
|
+
elif whence == io.SEEK_CUR:
|
|
65
|
+
new_pos = self._pos + offset
|
|
66
|
+
elif whence == io.SEEK_END:
|
|
67
|
+
new_pos = self._size + offset
|
|
68
|
+
else:
|
|
69
|
+
raise ValueError(f"Invalid whence argument: {whence}")
|
|
70
|
+
|
|
71
|
+
if new_pos < 0:
|
|
72
|
+
raise ValueError(f"Negative seek position: {new_pos}")
|
|
73
|
+
|
|
74
|
+
self._pos = new_pos
|
|
75
|
+
return self._pos
|
|
76
|
+
|
|
77
|
+
def read(self, size: int = -1) -> bytes:
|
|
78
|
+
if self._closed:
|
|
79
|
+
raise ValueError("I/O operation on closed HyperCacheFile")
|
|
80
|
+
|
|
81
|
+
if self._pos >= self._size:
|
|
82
|
+
return b""
|
|
83
|
+
|
|
84
|
+
if size is None or size < 0:
|
|
85
|
+
bytes_to_read = self._size - self._pos
|
|
86
|
+
else:
|
|
87
|
+
bytes_to_read = min(size, self._size - self._pos)
|
|
88
|
+
|
|
89
|
+
if bytes_to_read <= 0:
|
|
90
|
+
return b""
|
|
91
|
+
|
|
92
|
+
data = self.reader.read_range(
|
|
93
|
+
self.locate_result.chunk_layout,
|
|
94
|
+
start_offset=self._pos,
|
|
95
|
+
length=bytes_to_read,
|
|
96
|
+
)
|
|
97
|
+
|
|
98
|
+
self._pos += len(data)
|
|
99
|
+
return data
|
|
100
|
+
|
|
101
|
+
def readinto(self, b: bytearray | memoryview) -> int:
|
|
102
|
+
if self._closed:
|
|
103
|
+
raise ValueError("I/O operation on closed HyperCacheFile")
|
|
104
|
+
|
|
105
|
+
if self._pos >= self._size:
|
|
106
|
+
return 0
|
|
107
|
+
|
|
108
|
+
bytes_to_read = min(len(b), self._size - self._pos)
|
|
109
|
+
if bytes_to_read <= 0:
|
|
110
|
+
return 0
|
|
111
|
+
|
|
112
|
+
if hasattr(self.reader, "read_range_into"):
|
|
113
|
+
n = self.reader.read_range_into(
|
|
114
|
+
self.locate_result.chunk_layout,
|
|
115
|
+
start_offset=self._pos,
|
|
116
|
+
length=bytes_to_read,
|
|
117
|
+
target_buffer=b,
|
|
118
|
+
target_offset=0,
|
|
119
|
+
)
|
|
120
|
+
else:
|
|
121
|
+
data = self.read(bytes_to_read)
|
|
122
|
+
n = len(data)
|
|
123
|
+
b[:n] = data
|
|
124
|
+
|
|
125
|
+
self._pos += n
|
|
126
|
+
return n
|
|
127
|
+
|
|
128
|
+
def read_into_gpu(self, gpu_tensor_or_buffer: Any, offset: int = 0, length: Optional[int] = None) -> int:
|
|
129
|
+
"""
|
|
130
|
+
Zero-copy GPUDirect read directly into GPU memory via kvikio.CuFile.
|
|
131
|
+
"""
|
|
132
|
+
if length is None:
|
|
133
|
+
length = self._size - offset
|
|
134
|
+
|
|
135
|
+
return self.reader.read_into_gpu(
|
|
136
|
+
self.locate_result.chunk_layout,
|
|
137
|
+
start_offset=offset,
|
|
138
|
+
length=length,
|
|
139
|
+
gpu_buffer=gpu_tensor_or_buffer,
|
|
140
|
+
)
|
|
141
|
+
|
|
142
|
+
def close(self) -> None:
|
|
143
|
+
if not self._closed:
|
|
144
|
+
self._closed = True
|
|
145
|
+
try:
|
|
146
|
+
self.fs._client.close()
|
|
147
|
+
except Exception:
|
|
148
|
+
pass
|
|
149
|
+
super().close()
|
|
150
|
+
|
|
151
|
+
def __enter__(self) -> HyperCacheFile:
|
|
152
|
+
return self
|
|
153
|
+
|
|
154
|
+
def __exit__(self, exc_type, exc_val, exc_tb) -> None:
|
|
155
|
+
self.close()
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
class HyperCacheWriteFile(io.RawIOBase):
|
|
159
|
+
"""
|
|
160
|
+
Writable Python stream backed by physical striped NVMe block devices or RAM,
|
|
161
|
+
supporting streaming 4 MiB chunk flushes and asynchronous write-back caching to S3/NFS.
|
|
162
|
+
Bounds host RAM buffer usage to 4 MiB even for multi-gigabyte checkpoints.
|
|
163
|
+
"""
|
|
164
|
+
|
|
165
|
+
DEFAULT_CHUNK_SIZE = 4 * 1024 * 1024
|
|
166
|
+
|
|
167
|
+
def __init__(
|
|
168
|
+
self,
|
|
169
|
+
fs: HyperCacheFileSystem,
|
|
170
|
+
uri: str,
|
|
171
|
+
client: HyperCacheClient,
|
|
172
|
+
tier: Optional[str] = None,
|
|
173
|
+
is_leader: bool = True,
|
|
174
|
+
auto_flush_s3: bool = True,
|
|
175
|
+
write_through: bool = False,
|
|
176
|
+
pinned: bool = False,
|
|
177
|
+
chunk_size: int = DEFAULT_CHUNK_SIZE,
|
|
178
|
+
mode: str = "wb",
|
|
179
|
+
):
|
|
180
|
+
super().__init__()
|
|
181
|
+
self.fs = fs
|
|
182
|
+
self.uri = uri
|
|
183
|
+
self.client = client
|
|
184
|
+
self.tier = tier
|
|
185
|
+
self.is_leader = is_leader
|
|
186
|
+
self.auto_flush_s3 = auto_flush_s3
|
|
187
|
+
self.write_through = write_through
|
|
188
|
+
self.pinned = pinned
|
|
189
|
+
self.chunk_size = chunk_size
|
|
190
|
+
self.mode = mode
|
|
191
|
+
self._buffer = bytearray()
|
|
192
|
+
self._flushed_bytes = 0
|
|
193
|
+
self._flushed_chunks: List[Any] = []
|
|
194
|
+
self._pos = 0
|
|
195
|
+
self._staged_initial = False
|
|
196
|
+
self._closed = False
|
|
197
|
+
self._writer = DirectBlockWriter()
|
|
198
|
+
|
|
199
|
+
def writable(self) -> bool:
|
|
200
|
+
return not self._closed
|
|
201
|
+
|
|
202
|
+
def readable(self) -> bool:
|
|
203
|
+
return False
|
|
204
|
+
|
|
205
|
+
def seekable(self) -> bool:
|
|
206
|
+
return not self._closed
|
|
207
|
+
|
|
208
|
+
def tell(self) -> int:
|
|
209
|
+
return self._pos
|
|
210
|
+
|
|
211
|
+
def seek(self, offset: int, whence: int = io.SEEK_SET) -> int:
|
|
212
|
+
if self._closed:
|
|
213
|
+
raise ValueError("I/O operation on closed HyperCacheWriteFile")
|
|
214
|
+
total_len = self._flushed_bytes + len(self._buffer)
|
|
215
|
+
if whence == io.SEEK_SET:
|
|
216
|
+
new_pos = offset
|
|
217
|
+
elif whence == io.SEEK_CUR:
|
|
218
|
+
new_pos = self._pos + offset
|
|
219
|
+
elif whence == io.SEEK_END:
|
|
220
|
+
new_pos = total_len + offset
|
|
221
|
+
else:
|
|
222
|
+
raise ValueError(f"Invalid whence: {whence}")
|
|
223
|
+
if new_pos < 0:
|
|
224
|
+
raise ValueError(f"Negative seek offset: {new_pos}")
|
|
225
|
+
self._pos = new_pos
|
|
226
|
+
return self._pos
|
|
227
|
+
|
|
228
|
+
def _flush_chunk_bytes(self, payload: bytes) -> None:
|
|
229
|
+
size = len(payload)
|
|
230
|
+
if size == 0:
|
|
231
|
+
return
|
|
232
|
+
if not self._staged_initial:
|
|
233
|
+
stage_res = self.client.stage_write(
|
|
234
|
+
uri=self.uri,
|
|
235
|
+
size_bytes=size,
|
|
236
|
+
tier=self.tier,
|
|
237
|
+
is_leader=self.is_leader,
|
|
238
|
+
auto_flush_s3=self.auto_flush_s3,
|
|
239
|
+
write_through=self.write_through,
|
|
240
|
+
pinned=self.pinned,
|
|
241
|
+
)
|
|
242
|
+
self._staged_initial = True
|
|
243
|
+
else:
|
|
244
|
+
stage_res = self.client.append_write(
|
|
245
|
+
uri=self.uri,
|
|
246
|
+
size_bytes=size,
|
|
247
|
+
tier=self.tier,
|
|
248
|
+
)
|
|
249
|
+
if not stage_res.is_staged:
|
|
250
|
+
raise IOError(f"Failed to stage/append write for {self.uri}: {stage_res.error_message}")
|
|
251
|
+
self._writer.write_chunks(stage_res.chunk_layout, payload)
|
|
252
|
+
self._flushed_chunks.extend(stage_res.chunk_layout)
|
|
253
|
+
self._flushed_bytes += size
|
|
254
|
+
|
|
255
|
+
def write(self, b: bytes | bytearray | memoryview) -> int:
|
|
256
|
+
if self._closed:
|
|
257
|
+
raise ValueError("I/O operation on closed HyperCacheWriteFile")
|
|
258
|
+
view = memoryview(b)
|
|
259
|
+
n = len(view)
|
|
260
|
+
if n == 0:
|
|
261
|
+
return 0
|
|
262
|
+
|
|
263
|
+
# If seeking backwards into already-flushed chunks (e.g. ZIP header patch),
|
|
264
|
+
# patch the physical chunk directly in-place.
|
|
265
|
+
curr_pos = self._pos
|
|
266
|
+
idx = 0
|
|
267
|
+
if curr_pos < self._flushed_bytes:
|
|
268
|
+
patch_end = min(curr_pos + n, self._flushed_bytes)
|
|
269
|
+
patch_len = patch_end - curr_pos
|
|
270
|
+
patch_bytes = bytes(view[:patch_len])
|
|
271
|
+
v_off = 0
|
|
272
|
+
for chunk in self._flushed_chunks:
|
|
273
|
+
c_start = v_off
|
|
274
|
+
c_end = v_off + chunk.length
|
|
275
|
+
v_off = c_end
|
|
276
|
+
if c_end <= curr_pos or c_start >= patch_end:
|
|
277
|
+
continue
|
|
278
|
+
ov_start = max(curr_pos, c_start)
|
|
279
|
+
ov_end = min(patch_end, c_end)
|
|
280
|
+
ov_len = ov_end - ov_start
|
|
281
|
+
sub_slice = patch_bytes[ov_start - curr_pos : ov_end - curr_pos]
|
|
282
|
+
if chunk.tier == "ram":
|
|
283
|
+
with open(chunk.device, "r+b") as rf:
|
|
284
|
+
rf.seek(chunk.offset + (ov_start - c_start))
|
|
285
|
+
rf.write(sub_slice)
|
|
286
|
+
else:
|
|
287
|
+
fd = self._writer._get_write_fd(chunk.device)
|
|
288
|
+
os.pwrite(fd, sub_slice, chunk.offset + (ov_start - c_start))
|
|
289
|
+
idx += patch_len
|
|
290
|
+
curr_pos += patch_len
|
|
291
|
+
|
|
292
|
+
# Write remaining bytes into the active tail buffer
|
|
293
|
+
if idx < n:
|
|
294
|
+
rem = view[idx:]
|
|
295
|
+
buf_offset = curr_pos - self._flushed_bytes
|
|
296
|
+
if buf_offset > len(self._buffer):
|
|
297
|
+
self._buffer.extend(b"\x00" * (buf_offset - len(self._buffer)))
|
|
298
|
+
end_offset = buf_offset + len(rem)
|
|
299
|
+
if end_offset <= len(self._buffer):
|
|
300
|
+
self._buffer[buf_offset:end_offset] = rem
|
|
301
|
+
elif buf_offset == len(self._buffer):
|
|
302
|
+
self._buffer.extend(rem)
|
|
303
|
+
else:
|
|
304
|
+
self._buffer[buf_offset:] = rem[: len(self._buffer) - buf_offset]
|
|
305
|
+
self._buffer.extend(rem[len(self._buffer) - buf_offset :])
|
|
306
|
+
curr_pos += len(rem)
|
|
307
|
+
|
|
308
|
+
self._pos = curr_pos
|
|
309
|
+
|
|
310
|
+
# Stream full 4 MiB chunks to NVMe/RAM immediately so buffer stays bounded
|
|
311
|
+
while len(self._buffer) >= self.chunk_size and self._pos == self._flushed_bytes + len(self._buffer):
|
|
312
|
+
chunk_payload = bytes(self._buffer[: self.chunk_size])
|
|
313
|
+
del self._buffer[: self.chunk_size]
|
|
314
|
+
self._flush_chunk_bytes(chunk_payload)
|
|
315
|
+
|
|
316
|
+
return n
|
|
317
|
+
|
|
318
|
+
def flush(self) -> None:
|
|
319
|
+
if self._closed:
|
|
320
|
+
return
|
|
321
|
+
while len(self._buffer) >= self.chunk_size and self._pos == self._flushed_bytes + len(self._buffer):
|
|
322
|
+
chunk_payload = bytes(self._buffer[: self.chunk_size])
|
|
323
|
+
del self._buffer[: self.chunk_size]
|
|
324
|
+
self._flush_chunk_bytes(chunk_payload)
|
|
325
|
+
|
|
326
|
+
def close(self) -> None:
|
|
327
|
+
if not self._closed:
|
|
328
|
+
self._closed = True
|
|
329
|
+
if len(self._buffer) > 0:
|
|
330
|
+
tail_payload = bytes(self._buffer)
|
|
331
|
+
self._buffer.clear()
|
|
332
|
+
self._flush_chunk_bytes(tail_payload)
|
|
333
|
+
|
|
334
|
+
if self._flushed_bytes > 0:
|
|
335
|
+
committed = self.client.commit_write(self.uri, write_through=self.write_through)
|
|
336
|
+
if not committed:
|
|
337
|
+
logger.warning(f"Failed to confirm commit write for {self.uri}")
|
|
338
|
+
|
|
339
|
+
self._writer.close()
|
|
340
|
+
super().close()
|
|
341
|
+
|
|
342
|
+
def __enter__(self) -> HyperCacheWriteFile:
|
|
343
|
+
return self
|
|
344
|
+
|
|
345
|
+
def __exit__(self, exc_type, exc_val, exc_tb) -> None:
|
|
346
|
+
self.close()
|
|
347
|
+
|
|
348
|
+
|
|
349
|
+
class HyperCacheFileSystem(AbstractFileSystem):
|
|
350
|
+
"""
|
|
351
|
+
fsspec Filesystem handler for hypercache:// protocol.
|
|
352
|
+
"""
|
|
353
|
+
|
|
354
|
+
protocol = "hypercache"
|
|
355
|
+
cachable = False
|
|
356
|
+
|
|
357
|
+
def __init__(
|
|
358
|
+
self,
|
|
359
|
+
socket_path: Optional[str] = None,
|
|
360
|
+
prefer_gds: bool = True,
|
|
361
|
+
auto_ingest: bool = True,
|
|
362
|
+
**storage_options: Any,
|
|
363
|
+
):
|
|
364
|
+
super().__init__(**storage_options)
|
|
365
|
+
self.socket_path = socket_path
|
|
366
|
+
self.prefer_gds = prefer_gds
|
|
367
|
+
self.auto_ingest = auto_ingest
|
|
368
|
+
self._client = HyperCacheClient(socket_path=socket_path)
|
|
369
|
+
self._reader = get_data_reader(prefer_gds=prefer_gds)
|
|
370
|
+
|
|
371
|
+
def _format_uri(self, path: str) -> str:
|
|
372
|
+
if path.startswith("hypercache://"):
|
|
373
|
+
return path
|
|
374
|
+
if path.startswith("s3://") or path.startswith("file://") or path.startswith("nfs://"):
|
|
375
|
+
return path
|
|
376
|
+
if path.startswith("/"):
|
|
377
|
+
return f"file://{path}"
|
|
378
|
+
clean_path = path.lstrip("/")
|
|
379
|
+
return f"hypercache://{clean_path}"
|
|
380
|
+
|
|
381
|
+
def _open(
|
|
382
|
+
self,
|
|
383
|
+
path: str,
|
|
384
|
+
mode: str = "rb",
|
|
385
|
+
block_size: Optional[int] = None,
|
|
386
|
+
autocommit: bool = True,
|
|
387
|
+
cache_options: Optional[dict] = None,
|
|
388
|
+
tier: Optional[str] = None,
|
|
389
|
+
is_leader: bool = True,
|
|
390
|
+
auto_flush_s3: bool = True,
|
|
391
|
+
write_through: bool = False,
|
|
392
|
+
pinned: bool = False,
|
|
393
|
+
**kwargs: Any,
|
|
394
|
+
) -> Any:
|
|
395
|
+
uri = self._format_uri(path)
|
|
396
|
+
|
|
397
|
+
if "w" in mode or "a" in mode:
|
|
398
|
+
return HyperCacheWriteFile(
|
|
399
|
+
fs=self,
|
|
400
|
+
uri=uri,
|
|
401
|
+
client=self._client,
|
|
402
|
+
tier=tier,
|
|
403
|
+
is_leader=is_leader,
|
|
404
|
+
auto_flush_s3=auto_flush_s3,
|
|
405
|
+
write_through=write_through,
|
|
406
|
+
pinned=pinned,
|
|
407
|
+
mode=mode,
|
|
408
|
+
)
|
|
409
|
+
|
|
410
|
+
locate_result = self._client.locate(uri, auto_ingest=self.auto_ingest, tier=tier, pinned=pinned)
|
|
411
|
+
|
|
412
|
+
if not locate_result.is_hit:
|
|
413
|
+
raise FileNotFoundError(
|
|
414
|
+
f"Could not locate object {uri} in HyperCache: {locate_result.error_message or 'Cache Miss'}"
|
|
415
|
+
)
|
|
416
|
+
|
|
417
|
+
return HyperCacheFile(
|
|
418
|
+
fs=self,
|
|
419
|
+
uri=uri,
|
|
420
|
+
locate_result=locate_result,
|
|
421
|
+
reader=self._reader,
|
|
422
|
+
mode=mode,
|
|
423
|
+
)
|
|
424
|
+
|
|
425
|
+
def info(self, path: str, **kwargs: Any) -> Dict[str, Any]:
|
|
426
|
+
uri = self._format_uri(path)
|
|
427
|
+
res = self._client.locate(uri, auto_ingest=self.auto_ingest)
|
|
428
|
+
if not res.is_hit:
|
|
429
|
+
raise FileNotFoundError(f"{uri} not found in HyperCache")
|
|
430
|
+
|
|
431
|
+
return {
|
|
432
|
+
"name": path,
|
|
433
|
+
"size": res.object_size,
|
|
434
|
+
"type": "file",
|
|
435
|
+
"chunk_count": len(res.chunk_layout),
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
def ls(self, path: str, detail: bool = False, **kwargs: Any) -> List[Any]:
|
|
439
|
+
info = self.info(path)
|
|
440
|
+
if detail:
|
|
441
|
+
return [info]
|
|
442
|
+
return [path]
|
|
443
|
+
|
|
444
|
+
def size(self, path: str) -> int:
|
|
445
|
+
return self.info(path)["size"]
|
|
446
|
+
|
|
447
|
+
def exists(self, path: str, **kwargs: Any) -> bool:
|
|
448
|
+
try:
|
|
449
|
+
uri = self._format_uri(path)
|
|
450
|
+
res = self._client.locate(uri, auto_ingest=False)
|
|
451
|
+
return res.is_hit
|
|
452
|
+
except Exception:
|
|
453
|
+
return False
|
|
454
|
+
|
|
455
|
+
|
|
456
|
+
# Register with fsspec
|
|
457
|
+
fsspec.register_implementation("hypercache", HyperCacheFileSystem, clobber=True)
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
"""
|
|
2
|
+
HyperCache Framework & Ecosystem Integrations.
|
|
3
|
+
|
|
4
|
+
Provides native zero-copy loaders and checkpoint adapters for:
|
|
5
|
+
- Safetensors / Hugging Face / vLLM (`safetensors_loader`)
|
|
6
|
+
- PyTorch Distributed Checkpoint / FSDP / DeepSpeed (`dcp`)
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from hypercache.integrations.dcp import (
|
|
10
|
+
HyperCacheDCPStorageReader,
|
|
11
|
+
HyperCacheDCPStorageWriter,
|
|
12
|
+
)
|
|
13
|
+
from hypercache.integrations.safetensors_loader import (
|
|
14
|
+
HyperCachevLLMWeightLoader,
|
|
15
|
+
load_safetensors_state_dict,
|
|
16
|
+
save_safetensors_state_dict,
|
|
17
|
+
)
|
|
18
|
+
|
|
19
|
+
__all__ = [
|
|
20
|
+
"load_safetensors_state_dict",
|
|
21
|
+
"save_safetensors_state_dict",
|
|
22
|
+
"HyperCachevLLMWeightLoader",
|
|
23
|
+
"HyperCacheDCPStorageWriter",
|
|
24
|
+
"HyperCacheDCPStorageReader",
|
|
25
|
+
]
|
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
"""
|
|
2
|
+
PyTorch Distributed Checkpoint (DCP / FSDP / DeepSpeed) Storage Adapter for HyperCache.
|
|
3
|
+
|
|
4
|
+
Allows multi-rank distributed training jobs to save and restore sharded checkpoints
|
|
5
|
+
(`shard_rank_00000.pt`, etc.) directly through HyperCache's Tier-1 RAM or Tier-2 NVMe
|
|
6
|
+
pool with asynchronous write-back to S3/NFS.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import io
|
|
12
|
+
import json
|
|
13
|
+
from typing import Any, Dict, List, Optional
|
|
14
|
+
|
|
15
|
+
from hypercache.fsspec_fs import HyperCacheFileSystem
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class HyperCacheDCPStorageWriter:
|
|
19
|
+
"""
|
|
20
|
+
Distributed Checkpoint StorageWriter backed by HyperCache.
|
|
21
|
+
Each rank writes its own shard (`{base_uri}/rank_{rank:05d}.pt`) into local NVMe/RAM
|
|
22
|
+
in milliseconds while background threads sync to authoritative storage.
|
|
23
|
+
"""
|
|
24
|
+
|
|
25
|
+
def __init__(
|
|
26
|
+
self,
|
|
27
|
+
base_uri: str,
|
|
28
|
+
rank: int = 0,
|
|
29
|
+
world_size: int = 1,
|
|
30
|
+
tier: Optional[str] = None,
|
|
31
|
+
write_through: bool = False,
|
|
32
|
+
socket_path: Optional[str] = None,
|
|
33
|
+
):
|
|
34
|
+
self.base_uri = base_uri.rstrip("/")
|
|
35
|
+
self.rank = rank
|
|
36
|
+
self.world_size = world_size
|
|
37
|
+
self.tier = tier
|
|
38
|
+
self.write_through = write_through
|
|
39
|
+
self.socket_path = socket_path
|
|
40
|
+
self.fs = HyperCacheFileSystem(socket_path=socket_path, prefer_gds=False)
|
|
41
|
+
|
|
42
|
+
def shard_uri(self, rank: Optional[int] = None) -> str:
|
|
43
|
+
r = self.rank if rank is None else rank
|
|
44
|
+
return f"{self.base_uri}/shard_rank_{r:05d}_of_{self.world_size:05d}.pt"
|
|
45
|
+
|
|
46
|
+
def metadata_uri(self) -> str:
|
|
47
|
+
return f"{self.base_uri}/.metadata.json"
|
|
48
|
+
|
|
49
|
+
def save_rank_shard(
|
|
50
|
+
self,
|
|
51
|
+
state_dict: Dict[str, Any],
|
|
52
|
+
extra_metadata: Optional[Dict[str, Any]] = None,
|
|
53
|
+
) -> str:
|
|
54
|
+
"""
|
|
55
|
+
Saves the current rank's FSDP/DeepSpeed shard to HyperCache.
|
|
56
|
+
If `rank == 0`, also writes the distributed checkpoint manifest `.metadata.json`.
|
|
57
|
+
"""
|
|
58
|
+
uri = self.shard_uri(self.rank)
|
|
59
|
+
is_leader = self.rank == 0
|
|
60
|
+
|
|
61
|
+
try:
|
|
62
|
+
import torch
|
|
63
|
+
has_torch = True
|
|
64
|
+
except ImportError:
|
|
65
|
+
torch = None # type: ignore
|
|
66
|
+
has_torch = False
|
|
67
|
+
|
|
68
|
+
with self.fs.open(
|
|
69
|
+
uri,
|
|
70
|
+
"wb",
|
|
71
|
+
tier=self.tier,
|
|
72
|
+
is_leader=is_leader,
|
|
73
|
+
write_through=self.write_through,
|
|
74
|
+
) as wf:
|
|
75
|
+
if has_torch:
|
|
76
|
+
torch.save(state_dict, wf)
|
|
77
|
+
else:
|
|
78
|
+
payload = json.dumps(
|
|
79
|
+
{k: list(v) if isinstance(v, (bytes, bytearray)) else v for k, v in state_dict.items()}
|
|
80
|
+
).encode("utf-8")
|
|
81
|
+
wf.write(payload)
|
|
82
|
+
|
|
83
|
+
if is_leader:
|
|
84
|
+
manifest = {
|
|
85
|
+
"world_size": self.world_size,
|
|
86
|
+
"shards": [self.shard_uri(r) for r in range(self.world_size)],
|
|
87
|
+
"extra_metadata": extra_metadata or {},
|
|
88
|
+
}
|
|
89
|
+
meta_bytes = json.dumps(manifest, indent=2).encode("utf-8")
|
|
90
|
+
with self.fs.open(
|
|
91
|
+
self.metadata_uri(),
|
|
92
|
+
"wb",
|
|
93
|
+
tier=self.tier,
|
|
94
|
+
is_leader=True,
|
|
95
|
+
write_through=self.write_through,
|
|
96
|
+
) as mf:
|
|
97
|
+
mf.write(meta_bytes)
|
|
98
|
+
|
|
99
|
+
return uri
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
class HyperCacheDCPStorageReader:
|
|
103
|
+
"""
|
|
104
|
+
Distributed Checkpoint StorageReader backed by HyperCache.
|
|
105
|
+
Restores per-rank FSDP/DeepSpeed shards using zero-copy Direct Block DMA.
|
|
106
|
+
"""
|
|
107
|
+
|
|
108
|
+
def __init__(
|
|
109
|
+
self,
|
|
110
|
+
base_uri: str,
|
|
111
|
+
rank: int = 0,
|
|
112
|
+
world_size: int = 1,
|
|
113
|
+
socket_path: Optional[str] = None,
|
|
114
|
+
prefer_gds: bool = True,
|
|
115
|
+
):
|
|
116
|
+
self.base_uri = base_uri.rstrip("/")
|
|
117
|
+
self.rank = rank
|
|
118
|
+
self.world_size = world_size
|
|
119
|
+
self.socket_path = socket_path
|
|
120
|
+
self.fs = HyperCacheFileSystem(socket_path=socket_path, prefer_gds=prefer_gds)
|
|
121
|
+
|
|
122
|
+
def shard_uri(self, rank: Optional[int] = None) -> str:
|
|
123
|
+
r = self.rank if rank is None else rank
|
|
124
|
+
return f"{self.base_uri}/shard_rank_{r:05d}_of_{self.world_size:05d}.pt"
|
|
125
|
+
|
|
126
|
+
def metadata_uri(self) -> str:
|
|
127
|
+
return f"{self.base_uri}/.metadata.json"
|
|
128
|
+
|
|
129
|
+
def read_metadata(self) -> Dict[str, Any]:
|
|
130
|
+
with self.fs.open(self.metadata_uri(), "rb") as mf:
|
|
131
|
+
return json.loads(bytes(mf.read()).decode("utf-8"))
|
|
132
|
+
|
|
133
|
+
def load_rank_shard(self, rank: Optional[int] = None, map_location: Any = "cpu") -> Dict[str, Any]:
|
|
134
|
+
uri = self.shard_uri(rank)
|
|
135
|
+
try:
|
|
136
|
+
import torch
|
|
137
|
+
has_torch = True
|
|
138
|
+
except ImportError:
|
|
139
|
+
torch = None # type: ignore
|
|
140
|
+
has_torch = False
|
|
141
|
+
|
|
142
|
+
with self.fs.open(uri, "rb") as rf:
|
|
143
|
+
if has_torch:
|
|
144
|
+
return torch.load(rf, map_location=map_location, weights_only=False)
|
|
145
|
+
else:
|
|
146
|
+
raw = bytes(rf.read()).decode("utf-8")
|
|
147
|
+
return json.loads(raw)
|