hypercache-io 0.9.0b1__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.
@@ -0,0 +1,247 @@
1
+ """
2
+ Native Safetensors, Hugging Face, and vLLM Zero-Copy Loader for HyperCache.
3
+
4
+ Parses the Safetensors binary header directly from HyperCache's striped NVMe or
5
+ POSIX shared memory blocks and reconstructs PyTorch tensors with zero intermediate
6
+ serialization overhead.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import json
12
+ import struct
13
+ from typing import Any, Dict, Iterator, List, Optional, Tuple
14
+
15
+ from hypercache.fsspec_fs import HyperCacheFileSystem
16
+
17
+ _DTYPE_MAP = {
18
+ "F64": ("float64", 8),
19
+ "F32": ("float32", 4),
20
+ "F16": ("float16", 2),
21
+ "BF16": ("bfloat16", 2),
22
+ "I64": ("int64", 8),
23
+ "I32": ("int32", 4),
24
+ "I16": ("int16", 2),
25
+ "I8": ("int8", 1),
26
+ "U8": ("uint8", 1),
27
+ "BOOL": ("bool", 1),
28
+ }
29
+
30
+
31
+ def parse_safetensors_header(raw_header_and_len: bytes) -> Tuple[int, Dict[str, Any]]:
32
+ """
33
+ Parses the 8-byte little-endian header size and JSON metadata from a Safetensors stream.
34
+ Returns (data_start_offset, header_dict).
35
+ """
36
+ if len(raw_header_and_len) < 8:
37
+ raise ValueError("Invalid safetensors file: fewer than 8 bytes")
38
+ (header_len,) = struct.unpack("<Q", raw_header_and_len[:8])
39
+ header_json = raw_header_and_len[8 : 8 + header_len].decode("utf-8")
40
+ return 8 + header_len, json.loads(header_json)
41
+
42
+
43
+ def load_safetensors_state_dict(
44
+ uri: str,
45
+ device: str = "cpu",
46
+ socket_path: Optional[str] = None,
47
+ prefer_gds: bool = True,
48
+ pinned: bool = False,
49
+ tensor_names: Optional[List[str]] = None,
50
+ ) -> Dict[str, Any]:
51
+ """
52
+ Loads a `.safetensors` checkpoint from `hypercache://` into a dictionary of PyTorch tensors
53
+ (or raw memoryviews if PyTorch is not installed) using zero-copy DMA reads.
54
+
55
+ If `tensor_names` is specified, only the requested tensors are read from the striped
56
+ NVMe/RAM pool (selective tensor slicing for tensor-parallel / pipeline-parallel workers).
57
+ """
58
+ fs = HyperCacheFileSystem(socket_path=socket_path, prefer_gds=prefer_gds)
59
+ state_dict: Dict[str, Any] = {}
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 fs.open(uri, "rb", pinned=pinned) as f:
69
+ len_bytes = bytes(f.read(8))
70
+ if len(len_bytes) < 8:
71
+ raise ValueError(f"Safetensors file {uri} is truncated (< 8 bytes)")
72
+ (header_len,) = struct.unpack("<Q", len_bytes)
73
+ header_bytes = bytes(f.read(header_len))
74
+ header = json.loads(header_bytes.decode("utf-8"))
75
+ data_base_offset = 8 + header_len
76
+
77
+ selected_keys = [
78
+ k for k in header.keys()
79
+ if k != "__metadata__" and (tensor_names is None or k in tensor_names)
80
+ ]
81
+
82
+ # If loading all tensors, perform a single contiguous high-queue-depth DMA read
83
+ if tensor_names is None:
84
+ f.seek(data_base_offset)
85
+ payload_buf = f.read()
86
+ payload_view = memoryview(payload_buf)
87
+
88
+ for name in selected_keys:
89
+ meta = header[name]
90
+ dtype_code = meta["dtype"]
91
+ shape = meta["shape"]
92
+ start_rel, end_rel = meta["data_offsets"]
93
+ tensor_slice = payload_view[start_rel:end_rel]
94
+
95
+ if has_torch:
96
+ torch_dtype_name, _ = _DTYPE_MAP.get(dtype_code, ("uint8", 1))
97
+ torch_dtype = getattr(torch, torch_dtype_name)
98
+ if len(tensor_slice) == 0:
99
+ t = torch.empty(shape, dtype=torch_dtype, device=device)
100
+ else:
101
+ t = torch.frombuffer(bytearray(tensor_slice), dtype=torch_dtype).reshape(shape)
102
+ if device != "cpu":
103
+ t = t.to(device)
104
+ state_dict[name] = t
105
+ else:
106
+ state_dict[name] = bytes(tensor_slice)
107
+ else:
108
+ # Selective byte-range read for only the requested tensors
109
+ for name in selected_keys:
110
+ meta = header[name]
111
+ dtype_code = meta["dtype"]
112
+ shape = meta["shape"]
113
+ start_rel, end_rel = meta["data_offsets"]
114
+ byte_len = end_rel - start_rel
115
+
116
+ f.seek(data_base_offset + start_rel)
117
+ raw_slice = f.read(byte_len)
118
+
119
+ if has_torch:
120
+ torch_dtype_name, _ = _DTYPE_MAP.get(dtype_code, ("uint8", 1))
121
+ torch_dtype = getattr(torch, torch_dtype_name)
122
+ if byte_len == 0:
123
+ t = torch.empty(shape, dtype=torch_dtype, device=device)
124
+ else:
125
+ t = torch.frombuffer(bytearray(raw_slice), dtype=torch_dtype).reshape(shape)
126
+ if device != "cpu":
127
+ t = t.to(device)
128
+ state_dict[name] = t
129
+ else:
130
+ state_dict[name] = bytes(raw_slice)
131
+
132
+ return state_dict
133
+
134
+
135
+ def save_safetensors_state_dict(
136
+ state_dict: Dict[str, Any],
137
+ uri: str,
138
+ metadata: Optional[Dict[str, str]] = None,
139
+ socket_path: Optional[str] = None,
140
+ tier: Optional[str] = None,
141
+ write_through: bool = False,
142
+ pinned: bool = False,
143
+ ) -> int:
144
+ """
145
+ Serializes a dictionary of PyTorch tensors (or raw byte buffers) into Safetensors format
146
+ and streams it in 4 MiB chunks directly to HyperCache.
147
+ """
148
+ try:
149
+ import torch
150
+ has_torch = True
151
+ except ImportError:
152
+ torch = None # type: ignore
153
+ has_torch = False
154
+
155
+ reverse_dtype = {v[0]: k for k, v in _DTYPE_MAP.items()}
156
+ header: Dict[str, Any] = {}
157
+ if metadata:
158
+ header["__metadata__"] = metadata
159
+
160
+ tensor_payloads: List[bytes] = []
161
+ current_offset = 0
162
+
163
+ for name, val in state_dict.items():
164
+ if has_torch and isinstance(val, torch.Tensor):
165
+ t_cpu = val.detach().contiguous().cpu()
166
+ dtype_str = str(t_cpu.dtype).replace("torch.", "")
167
+ st_dtype = reverse_dtype.get(dtype_str, "U8")
168
+ shape = list(t_cpu.shape)
169
+ raw_bytes = bytes(
170
+ (ctypes_buf := t_cpu.numpy().tobytes())
171
+ if t_cpu.dtype != torch.bfloat16
172
+ else t_cpu.view(torch.uint16).numpy().tobytes()
173
+ )
174
+ elif isinstance(val, (bytes, bytearray, memoryview)):
175
+ raw_bytes = bytes(val)
176
+ st_dtype = "U8"
177
+ shape = [len(raw_bytes)]
178
+ else:
179
+ raise TypeError(f"Unsupported value type for safetensors export: {type(val)}")
180
+
181
+ end_offset = current_offset + len(raw_bytes)
182
+ header[name] = {
183
+ "dtype": st_dtype,
184
+ "shape": shape,
185
+ "data_offsets": [current_offset, end_offset],
186
+ }
187
+ tensor_payloads.append(raw_bytes)
188
+ current_offset = end_offset
189
+
190
+ header_bytes = json.dumps(header, separators=(",", ":")).encode("utf-8")
191
+ # Pad header to 8-byte alignment per Safetensors spec
192
+ pad_len = (8 - (len(header_bytes) % 8)) % 8
193
+ if pad_len > 0:
194
+ header_bytes += b" " * pad_len
195
+
196
+ prefix = struct.pack("<Q", len(header_bytes)) + header_bytes
197
+
198
+ fs = HyperCacheFileSystem(socket_path=socket_path, prefer_gds=False)
199
+ total_written = 0
200
+ with fs.open(uri, "wb", tier=tier, write_through=write_through, pinned=pinned) as wf:
201
+ wf.write(prefix)
202
+ total_written += len(prefix)
203
+ for buf in tensor_payloads:
204
+ wf.write(buf)
205
+ total_written += len(buf)
206
+
207
+ return total_written
208
+
209
+
210
+ class HyperCachevLLMWeightLoader:
211
+ """
212
+ High-throughput weight shard loader for vLLM and Hugging Face multi-shard checkpoints.
213
+ Supports concurrent shard pre-warming, cache pinning, and selective tensor-parallel slicing.
214
+ """
215
+
216
+ def __init__(
217
+ self,
218
+ socket_path: Optional[str] = None,
219
+ prefer_gds: bool = True,
220
+ pin_base_weights: bool = True,
221
+ ):
222
+ self.socket_path = socket_path
223
+ self.prefer_gds = prefer_gds
224
+ self.pin_base_weights = pin_base_weights
225
+ self.fs = HyperCacheFileSystem(socket_path=socket_path, prefer_gds=prefer_gds)
226
+
227
+ def iter_shard_tensors(
228
+ self,
229
+ shard_uris: List[str],
230
+ device: str = "cpu",
231
+ tensor_filter: Optional[List[str]] = None,
232
+ ) -> Iterator[Tuple[str, Any]]:
233
+ """
234
+ Iterates over one or more `.safetensors` shards in HyperCache, yielding `(name, tensor)`
235
+ pairs directly for vLLM `model.load_weights(...)`.
236
+ """
237
+ for uri in shard_uris:
238
+ tensors = load_safetensors_state_dict(
239
+ uri=uri,
240
+ device=device,
241
+ socket_path=self.socket_path,
242
+ prefer_gds=self.prefer_gds,
243
+ pinned=self.pin_base_weights,
244
+ tensor_names=tensor_filter,
245
+ )
246
+ for name, tensor in tensors.items():
247
+ yield name, tensor
hypercache/kv_store.py ADDED
@@ -0,0 +1,151 @@
1
+ """
2
+ HyperCache KV-Cache Prefix Block Store (`HyperCacheKVStore`).
3
+
4
+ Provides a content-addressed key-value block interface over HyperCache's Tier-1
5
+ Host RAM (`/dev/shm` / HugePages) and Tier-2 Striped NVMe engine, enabling
6
+ plug-and-play KV-cache offloading for LMCache, vLLM prefix caching, and
7
+ NVIDIA Dynamo KVBM.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import hashlib
13
+ from typing import Any, Optional, Sequence, Union
14
+
15
+ from hypercache.client import HyperCacheClient
16
+ from hypercache.datapath import DirectBlockWriter, get_data_reader
17
+
18
+
19
+ class HyperCacheKVStore:
20
+ """
21
+ Content-addressed KV-Cache Block Store backed by HyperCache Tier 1 (RAM) and Tier 2 (NVMe).
22
+ """
23
+
24
+ KV_URI_PREFIX = "hypercache://kv_cache"
25
+
26
+ def __init__(
27
+ self,
28
+ socket_path: Optional[str] = None,
29
+ default_tier: str = "ram",
30
+ prefer_gds: bool = True,
31
+ write_through: bool = False,
32
+ ):
33
+ self.socket_path = socket_path
34
+ self.default_tier = default_tier
35
+ self.prefer_gds = prefer_gds
36
+ self.write_through = write_through
37
+ self._client = HyperCacheClient(socket_path=socket_path)
38
+ self._reader = get_data_reader(prefer_gds=prefer_gds)
39
+ self._writer = DirectBlockWriter()
40
+
41
+ @staticmethod
42
+ def compute_prefix_hash(
43
+ token_ids: Sequence[int],
44
+ model_id: str = "default",
45
+ layer_idx: Optional[int] = None,
46
+ ) -> str:
47
+ """
48
+ Computes a deterministic SHA-256 content-addressed key for a token prefix chunk.
49
+ """
50
+ h = hashlib.sha256()
51
+ h.update(model_id.encode("utf-8"))
52
+ h.update(b"::")
53
+ if layer_idx is not None:
54
+ h.update(f"layer_{layer_idx}::".encode("utf-8"))
55
+ h.update(",".join(str(t) for t in token_ids).encode("utf-8"))
56
+ return h.hexdigest()
57
+
58
+ def _make_uri(self, block_key: str) -> str:
59
+ if block_key.startswith("hypercache://"):
60
+ return block_key
61
+ return f"{self.KV_URI_PREFIX}/{block_key}.kv"
62
+
63
+ def put_kv_block(
64
+ self,
65
+ block_key: str,
66
+ kv_data: Union[bytes, bytearray, memoryview, Any],
67
+ tier: Optional[str] = None,
68
+ pinned: bool = False,
69
+ ) -> bool:
70
+ """
71
+ Stores a KV-cache tensor or byte block into HyperCache Tier-1 RAM or Tier-2 NVMe.
72
+ """
73
+ uri = self._make_uri(block_key)
74
+ target_tier = tier or self.default_tier
75
+
76
+ if isinstance(kv_data, (bytes, bytearray, memoryview)):
77
+ raw_bytes = bytes(kv_data)
78
+ else:
79
+ try:
80
+ import torch
81
+ if isinstance(kv_data, torch.Tensor):
82
+ t_cpu = kv_data.detach().contiguous().cpu()
83
+ raw_bytes = (
84
+ t_cpu.numpy().tobytes()
85
+ if t_cpu.dtype != torch.bfloat16
86
+ else t_cpu.view(torch.uint16).numpy().tobytes()
87
+ )
88
+ else:
89
+ raise TypeError(f"Unsupported kv_data type: {type(kv_data)}")
90
+ except ImportError as e:
91
+ raise TypeError("kv_data must be bytes-like when PyTorch is unavailable") from e
92
+
93
+ stage_res = self._client.stage_write(
94
+ uri=uri,
95
+ size_bytes=len(raw_bytes),
96
+ tier=target_tier,
97
+ is_leader=False,
98
+ auto_flush_s3=False,
99
+ write_through=self.write_through,
100
+ pinned=pinned,
101
+ )
102
+ if not stage_res.is_staged:
103
+ return False
104
+
105
+ self._writer.write_chunks(stage_res.chunk_layout, raw_bytes)
106
+ return self._client.commit_write(uri, write_through=self.write_through)
107
+
108
+ def get_kv_block(
109
+ self,
110
+ block_key: str,
111
+ out_tensor: Optional[Any] = None,
112
+ ) -> Optional[Union[bytes, Any]]:
113
+ """
114
+ Retrieves a KV-cache block by key. If `out_tensor` (a pre-allocated CPU or CUDA
115
+ PyTorch tensor) is provided, copies directly into `out_tensor` and returns it.
116
+ Returns `None` on cache miss.
117
+ """
118
+ uri = self._make_uri(block_key)
119
+ loc = self._client.locate(uri, auto_ingest=False)
120
+ if not loc.is_hit:
121
+ return None
122
+
123
+ if out_tensor is not None:
124
+ try:
125
+ import torch
126
+ if isinstance(out_tensor, torch.Tensor):
127
+ if out_tensor.is_cuda:
128
+ self._reader.read_into_gpu(
129
+ loc.chunk_layout,
130
+ start_offset=0,
131
+ length=loc.object_size,
132
+ gpu_buffer=out_tensor.view(torch.uint8).reshape(-1),
133
+ )
134
+ else:
135
+ raw = self._reader.read_range(loc.chunk_layout, 0, loc.object_size)
136
+ src = torch.frombuffer(bytearray(raw), dtype=out_tensor.dtype).reshape(out_tensor.shape)
137
+ out_tensor.copy_(src)
138
+ return out_tensor
139
+ except ImportError:
140
+ pass
141
+
142
+ return bytes(self._reader.read_range(loc.chunk_layout, 0, loc.object_size))
143
+
144
+ def exists_kv_block(self, block_key: str) -> bool:
145
+ uri = self._make_uri(block_key)
146
+ return self._client.locate(uri, auto_ingest=False).is_hit
147
+
148
+ def close(self) -> None:
149
+ self._reader.close()
150
+ self._writer.close()
151
+ self._client.close()
hypercache/pipeline.py ADDED
@@ -0,0 +1,182 @@
1
+ """
2
+ HyperCache Layer-by-Layer Pipelined Loader & Compute-I/O Overlap Engine.
3
+
4
+ Enables sub-100ms perceived cold starts for LLM inference by:
5
+ 1. Immediately loading the Embedding & Layer 0 into GPU VRAM / Host RAM.
6
+ 2. Beginning model forward pass execution without waiting for the full 70B model.
7
+ 3. Concurrently prefetching Layer i+1 in a background worker while the GPU executes Layer i.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import logging
13
+ import queue
14
+ import threading
15
+ import time
16
+ from concurrent.futures import Future, ThreadPoolExecutor
17
+ from dataclasses import dataclass
18
+ from typing import Any, Dict, Generator, Iterator, List, Optional, Tuple
19
+
20
+ from hypercache.client import HyperCacheClient, LocateResult
21
+ from hypercache.datapath import ChunkLocation, DataReader, get_data_reader
22
+
23
+ logger = logging.getLogger("hypercache.pipeline")
24
+
25
+
26
+ @dataclass
27
+ class LayerDescriptor:
28
+ """Represents a logical layer within a serialized model checkpoint."""
29
+ layer_idx: int
30
+ name: str
31
+ start_offset: int
32
+ length: int
33
+
34
+
35
+ class HyperCachePipelinedLoader:
36
+ """
37
+ Pipelined, compute-overlapped model loader for streaming transformer weights.
38
+ """
39
+
40
+ def __init__(
41
+ self,
42
+ uri: str,
43
+ socket_path: Optional[str] = None,
44
+ layer_size_bytes: int = 64 * 1024 * 1024, # 64 MiB default per layer
45
+ num_layers: Optional[int] = None,
46
+ prefer_gds: bool = True,
47
+ prefetch_ahead: int = 1,
48
+ ):
49
+ self.uri = uri
50
+ self.layer_size_bytes = layer_size_bytes
51
+ self.num_layers = num_layers
52
+ self.prefer_gds = prefer_gds
53
+ self.prefetch_ahead = max(1, prefetch_ahead)
54
+
55
+ self._client = HyperCacheClient(socket_path=socket_path)
56
+ self._reader: DataReader = get_data_reader(prefer_gds=prefer_gds)
57
+ self._executor = ThreadPoolExecutor(max_workers=2, thread_name_prefix="HyperCachePipelinedPrefetch")
58
+
59
+ # 1. Locate object
60
+ self.locate_result: LocateResult = self._client.locate(self.uri, auto_ingest=True)
61
+ if not self.locate_result.is_hit:
62
+ raise FileNotFoundError(
63
+ f"Could not locate {self.uri} in HyperCache: {self.locate_result.error_message or 'MISS'}"
64
+ )
65
+
66
+ self.total_size = self.locate_result.object_size
67
+ self.chunk_layout = self.locate_result.chunk_layout
68
+
69
+ # 2. Build layer descriptors
70
+ self.layers: List[LayerDescriptor] = self._partition_layers()
71
+ self._prefetch_futures: Dict[int, Future] = {}
72
+
73
+ def _partition_layers(self) -> List[LayerDescriptor]:
74
+ """Divides object byte range into sequential layer descriptors."""
75
+ layers = []
76
+ if self.num_layers is not None and self.num_layers > 0:
77
+ size_per_layer = max(1, self.total_size // self.num_layers)
78
+ for i in range(self.num_layers):
79
+ start = i * size_per_layer
80
+ length = (self.total_size - start) if i == self.num_layers - 1 else size_per_layer
81
+ name = "embedding" if i == 0 else f"layer_{i-1}"
82
+ layers.append(LayerDescriptor(layer_idx=i, name=name, start_offset=start, length=length))
83
+ else:
84
+ current_offset = 0
85
+ idx = 0
86
+ while current_offset < self.total_size:
87
+ length = min(self.layer_size_bytes, self.total_size - current_offset)
88
+ name = "embedding" if idx == 0 else f"layer_{idx-1}"
89
+ layers.append(LayerDescriptor(layer_idx=idx, name=name, start_offset=current_offset, length=length))
90
+ current_offset += length
91
+ idx += 1
92
+ return layers
93
+
94
+ def _read_layer_bytes(self, layer: LayerDescriptor) -> bytes:
95
+ """Reads layer bytes from local NVMe/RAM block pool."""
96
+ return self._reader.read_range(
97
+ self.chunk_layout,
98
+ start_offset=layer.start_offset,
99
+ length=layer.length,
100
+ )
101
+
102
+ def load_initial_layer(self) -> Tuple[LayerDescriptor, bytes]:
103
+ """
104
+ Synchronously loads Layer 0 / Embedding and triggers background prefetching for Layer 1.
105
+ Unblocks the inference engine in ~20-50 ms.
106
+ """
107
+ if not self.layers:
108
+ raise ValueError("No layers found in model.")
109
+
110
+ first_layer = self.layers[0]
111
+ data = self._read_layer_bytes(first_layer)
112
+
113
+ # Trigger prefetching for subsequent layer(s)
114
+ for i in range(1, min(1 + self.prefetch_ahead, len(self.layers))):
115
+ self.trigger_prefetch(i)
116
+
117
+ return first_layer, data
118
+
119
+ def trigger_prefetch(self, layer_idx: int) -> None:
120
+ """Schedules asynchronous background DMA fetch for layer_idx."""
121
+ if layer_idx < len(self.layers) and layer_idx not in self._prefetch_futures:
122
+ layer = self.layers[layer_idx]
123
+ self._prefetch_futures[layer_idx] = self._executor.submit(self._read_layer_bytes, layer)
124
+
125
+ def get_layer(self, layer_idx: int) -> Tuple[LayerDescriptor, bytes]:
126
+ """
127
+ Retrieves a layer payload, waiting on background prefetch if currently in flight.
128
+ """
129
+ if layer_idx >= len(self.layers):
130
+ raise IndexError(f"Layer index {layer_idx} out of range (total: {len(self.layers)})")
131
+
132
+ layer = self.layers[layer_idx]
133
+
134
+ # Trigger prefetch for layer_idx + prefetch_ahead
135
+ target_prefetch = layer_idx + self.prefetch_ahead
136
+ if target_prefetch < len(self.layers):
137
+ self.trigger_prefetch(target_prefetch)
138
+
139
+ if layer_idx in self._prefetch_futures:
140
+ future = self._prefetch_futures.pop(layer_idx)
141
+ data = future.result()
142
+ else:
143
+ data = self._read_layer_bytes(layer)
144
+
145
+ return layer, data
146
+
147
+ def stream_layers(self) -> Generator[Tuple[LayerDescriptor, bytes], None, None]:
148
+ """
149
+ Sequential generator yielding (LayerDescriptor, bytes) while overlapping I/O.
150
+ """
151
+ # Prefetch initial layers
152
+ for i in range(min(self.prefetch_ahead, len(self.layers))):
153
+ self.trigger_prefetch(i)
154
+
155
+ for i in range(len(self.layers)):
156
+ yield self.get_layer(i)
157
+
158
+ def close(self) -> None:
159
+ self._executor.shutdown(wait=False)
160
+ self._reader.close()
161
+ self._client.close()
162
+
163
+ def __enter__(self) -> HyperCachePipelinedLoader:
164
+ return self
165
+
166
+ def __exit__(self, exc_type, exc_val, exc_tb) -> None:
167
+ self.close()
168
+
169
+
170
+ def pipeline_load(
171
+ uri: str,
172
+ socket_path: Optional[str] = None,
173
+ layer_size_bytes: int = 64 * 1024 * 1024,
174
+ num_layers: Optional[int] = None,
175
+ ) -> HyperCachePipelinedLoader:
176
+ """Convenience helper to initialize a HyperCache pipelined streaming loader."""
177
+ return HyperCachePipelinedLoader(
178
+ uri=uri,
179
+ socket_path=socket_path,
180
+ layer_size_bytes=layer_size_bytes,
181
+ num_layers=num_layers,
182
+ )
@@ -0,0 +1,115 @@
1
+ Metadata-Version: 2.4
2
+ Name: hypercache-io
3
+ Version: 0.9.0b1
4
+ Summary: HyperCache: Host-Local NVMe Caching and Zero-Copy Direct Block DMA / GPUDirect Storage Acceleration for AI Workloads
5
+ Author: Looe Labs
6
+ License: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/looelabs/hypercache
8
+ Project-URL: Repository, https://github.com/looelabs/hypercache
9
+ Project-URL: Issues, https://github.com/looelabs/hypercache/issues
10
+ Keywords: ai,pytorch,safetensors,vllm,nvme,gpudirect,cache,s3,fsspec
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Intended Audience :: Science/Research
14
+ Classifier: Intended Audience :: System Administrators
15
+ Classifier: License :: OSI Approved :: Apache Software License
16
+ Classifier: Operating System :: POSIX :: Linux
17
+ Classifier: Programming Language :: Python :: 3
18
+ Classifier: Programming Language :: Python :: 3.9
19
+ Classifier: Programming Language :: Python :: 3.10
20
+ Classifier: Programming Language :: Python :: 3.11
21
+ Classifier: Programming Language :: Python :: 3.12
22
+ Classifier: Programming Language :: Rust
23
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
24
+ Classifier: Topic :: System :: Filesystems
25
+ Requires-Python: >=3.9
26
+ Description-Content-Type: text/markdown
27
+ Requires-Dist: fsspec>=2023.1.0
28
+ Requires-Dist: numpy>=1.22.0
29
+ Provides-Extra: gpu
30
+ Requires-Dist: kvikio-cu12>=24.0.0; extra == "gpu"
31
+ Requires-Dist: cupy-cuda12x>=12.0.0; extra == "gpu"
32
+ Requires-Dist: torch>=2.0.0; extra == "gpu"
33
+ Requires-Dist: numpy>=1.22.0; extra == "gpu"
34
+ Provides-Extra: dev
35
+ Requires-Dist: torch>=2.0.0; extra == "dev"
36
+ Requires-Dist: safetensors>=0.4.0; extra == "dev"
37
+ Requires-Dist: boto3>=1.28.0; extra == "dev"
38
+ Requires-Dist: requests>=2.28.0; extra == "dev"
39
+ Requires-Dist: pytest>=7.0.0; extra == "dev"
40
+ Requires-Dist: numpy>=1.22.0; extra == "dev"
41
+
42
+ # HyperCache Python Client & Data Plane (`client-py`)
43
+
44
+ The `hypercache` Python package integrates transparently into AI training and inference pipelines (PyTorch, Hugging Face, Safetensors) to provide **zero-copy Direct Block DMA / GPUDirect Storage (GDS)** checkpoint loading.
45
+
46
+ ---
47
+
48
+ ## Key Features
49
+
50
+ - **Transparent `hypercache://` Protocol**: Seamless `fsspec` filesystem implementation.
51
+ - **Dual Direct / Buffered Handles**: Uses `O_DIRECT` with sector/page-aligned DMA buffers for maximum hardware read throughput (up to **~7 GB/s** per PCIe Gen 4 NVMe and **~14 GB/s** per PCIe Gen 5 NVMe), with automatic transparent fallback for arbitrary unaligned byte slices.
52
+ - **Sub-Millisecond Metadata**: Resolves physical drive offsets from the local HyperCache control plane daemon in **< 1 ms** over Unix Domain Sockets.
53
+ - **Zero-Copy GPU Direct**: Direct DMA transfers bypassing host CPU and Linux page cache.
54
+
55
+ ---
56
+
57
+ ## Installation
58
+
59
+ ```bash
60
+ # Install from PyPI (imports as `import hypercache`)
61
+ pip install hypercache-io
62
+
63
+ # Or install in editable mode from the repository
64
+ cd client-py
65
+ pip install -e .
66
+
67
+ # Optional GPU Direct Storage acceleration dependencies
68
+ pip install "hypercache-io[gpu]" --extra-index-url https://pypi.nvidia.com
69
+ ```
70
+
71
+ ---
72
+
73
+ ## Usage Examples
74
+
75
+ ### 1. PyTorch & Safetensors Loading
76
+ ```python
77
+ import torch
78
+ import safetensors.torch
79
+ from hypercache.fsspec_fs import register_hypercache_fsspec
80
+
81
+ # Automatically registers hypercache:// protocol
82
+ register_hypercache_fsspec()
83
+
84
+ # Load tensors directly from striped NVMe storage into VRAM/Host memory
85
+ with open("hypercache://models/llama-3/weights.safetensors", "rb") as f:
86
+ tensors = safetensors.torch.load(f.read())
87
+ ```
88
+
89
+ ### 2. Direct Python Client API
90
+ ```python
91
+ from hypercache.client import HyperCacheClient
92
+ from hypercache.datapath import get_data_reader
93
+
94
+ # Connect to local Control Plane Daemon (auto-resolves /run/hypercache/hypercache.sock)
95
+ client = HyperCacheClient()
96
+
97
+ # Check daemon health & discovered drives
98
+ devices = client.get_devices()
99
+ print(f"Discovered {len(devices)} active striped devices.")
100
+
101
+ # Locate checkpoint
102
+ layout = client.locate("hypercache://models/llama-3/weights.safetensors", auto_ingest=True)
103
+ if layout.is_hit:
104
+ reader = get_data_reader()
105
+ data = reader.read_chunks(layout.chunk_layout, layout.object_size)
106
+ print(f"Read {len(data)/(1024*1024):.2f} MiB at hardware line rate!")
107
+ ```
108
+
109
+ ---
110
+
111
+ ## Running Unit Tests
112
+
113
+ ```bash
114
+ pytest tests/
115
+ ```