hypercache-io 0.9.4__tar.gz → 0.10.0__tar.gz

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 (26) hide show
  1. {hypercache_io-0.9.4 → hypercache_io-0.10.0}/PKG-INFO +7 -1
  2. {hypercache_io-0.9.4 → hypercache_io-0.10.0}/README.md +6 -0
  3. {hypercache_io-0.9.4 → hypercache_io-0.10.0}/hypercache/__init__.py +1 -1
  4. {hypercache_io-0.9.4 → hypercache_io-0.10.0}/hypercache/client.py +29 -0
  5. {hypercache_io-0.9.4 → hypercache_io-0.10.0}/hypercache/datapath.py +115 -15
  6. hypercache_io-0.10.0/hypercache/kv_store.py +225 -0
  7. {hypercache_io-0.9.4 → hypercache_io-0.10.0}/hypercache/pipeline.py +10 -7
  8. {hypercache_io-0.9.4 → hypercache_io-0.10.0}/hypercache_io.egg-info/PKG-INFO +7 -1
  9. {hypercache_io-0.9.4 → hypercache_io-0.10.0}/hypercache_io.egg-info/SOURCES.txt +1 -0
  10. {hypercache_io-0.9.4 → hypercache_io-0.10.0}/pyproject.toml +1 -1
  11. hypercache_io-0.10.0/tests/test_direct_writer.py +254 -0
  12. {hypercache_io-0.9.4 → hypercache_io-0.10.0}/tests/test_integrations_and_kv.py +103 -8
  13. hypercache_io-0.9.4/hypercache/kv_store.py +0 -151
  14. {hypercache_io-0.9.4 → hypercache_io-0.10.0}/hypercache/fsspec_fs.py +0 -0
  15. {hypercache_io-0.9.4 → hypercache_io-0.10.0}/hypercache/integrations/__init__.py +0 -0
  16. {hypercache_io-0.9.4 → hypercache_io-0.10.0}/hypercache/integrations/dcp.py +0 -0
  17. {hypercache_io-0.9.4 → hypercache_io-0.10.0}/hypercache/integrations/safetensors_loader.py +0 -0
  18. {hypercache_io-0.9.4 → hypercache_io-0.10.0}/hypercache_io.egg-info/dependency_links.txt +0 -0
  19. {hypercache_io-0.9.4 → hypercache_io-0.10.0}/hypercache_io.egg-info/entry_points.txt +0 -0
  20. {hypercache_io-0.9.4 → hypercache_io-0.10.0}/hypercache_io.egg-info/requires.txt +0 -0
  21. {hypercache_io-0.9.4 → hypercache_io-0.10.0}/hypercache_io.egg-info/top_level.txt +0 -0
  22. {hypercache_io-0.9.4 → hypercache_io-0.10.0}/setup.cfg +0 -0
  23. {hypercache_io-0.9.4 → hypercache_io-0.10.0}/tests/test_client.py +0 -0
  24. {hypercache_io-0.9.4 → hypercache_io-0.10.0}/tests/test_fsspec.py +0 -0
  25. {hypercache_io-0.9.4 → hypercache_io-0.10.0}/tests/test_pipelined_and_numa.py +0 -0
  26. {hypercache_io-0.9.4 → hypercache_io-0.10.0}/tests/test_robustness.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: hypercache-io
3
- Version: 0.9.4
3
+ Version: 0.10.0
4
4
  Summary: HyperCache: Host-Local NVMe Caching and Zero-Copy Direct Block DMA / GPUDirect Storage Acceleration for AI Workloads
5
5
  Author: Looe Labs
6
6
  License: Apache-2.0
@@ -108,6 +108,12 @@ if layout.is_hit:
108
108
 
109
109
  ---
110
110
 
111
+ ## LMCache
112
+
113
+ The LMCache integration isn't part of this package. It's a separate Rust connector, covered in [`lmcache-connector/README.md`](../lmcache-connector/README.md). For code that manages its own KV blocks, use `HyperCacheKVStore` from this package.
114
+
115
+ ---
116
+
111
117
  ## Running Unit Tests
112
118
 
113
119
  ```bash
@@ -67,6 +67,12 @@ if layout.is_hit:
67
67
 
68
68
  ---
69
69
 
70
+ ## LMCache
71
+
72
+ The LMCache integration isn't part of this package. It's a separate Rust connector, covered in [`lmcache-connector/README.md`](../lmcache-connector/README.md). For code that manages its own KV blocks, use `HyperCacheKVStore` from this package.
73
+
74
+ ---
75
+
70
76
  ## Running Unit Tests
71
77
 
72
78
  ```bash
@@ -58,4 +58,4 @@ __all__ = [
58
58
  "HyperCacheDCPStorageReader",
59
59
  ]
60
60
 
61
- __version__ = "0.9.4"
61
+ __version__ = "0.10.0"
@@ -54,6 +54,8 @@ class LocateResult:
54
54
  error_message: Optional[str] = None
55
55
  # Layout generation reported by the daemon (changes whenever the URI is re-ingested or rewritten)
56
56
  generation: Optional[int] = None
57
+ # Write status reported by daemons that support it, such as "STAGED" or "LOCAL_ONLY"
58
+ sync_status: Optional[str] = None
57
59
 
58
60
  @property
59
61
  def is_hit(self) -> bool:
@@ -68,6 +70,9 @@ class StageWriteResult:
68
70
  chunk_layout: List[ChunkLocation]
69
71
  sync_status: str
70
72
  error_message: Optional[str] = None
73
+ # Layout generation of this staging. Pass it to commit_write so the commit is refused if
74
+ # another writer replaced the layout in the meantime.
75
+ generation: Optional[int] = None
71
76
 
72
77
  @property
73
78
  def is_staged(self) -> bool:
@@ -242,6 +247,7 @@ class HyperCacheClient:
242
247
  chunk_size=resp.get("chunk_size", 4194304),
243
248
  chunk_layout=chunk_layout,
244
249
  generation=resp.get("generation"),
250
+ sync_status=resp.get("sync_status"),
245
251
  )
246
252
  elif status == "MISS":
247
253
  return LocateResult(
@@ -368,6 +374,7 @@ class HyperCacheClient:
368
374
  chunk_size=resp.get("chunk_size", 4194304),
369
375
  chunk_layout=chunk_layout,
370
376
  sync_status=resp.get("sync_status", "STAGED"),
377
+ generation=resp.get("generation"),
371
378
  )
372
379
  else:
373
380
  err = resp.get("error_message", "Failed to stage write")
@@ -426,10 +433,20 @@ class HyperCacheClient:
426
433
  uri: str,
427
434
  sha256: Optional[str] = None,
428
435
  write_through: bool = False,
436
+ local_only: bool = False,
437
+ chunk_checksums: Optional[List[int]] = None,
438
+ generation: Optional[int] = None,
429
439
  ) -> bool:
430
440
  """
431
441
  Commits a staged write in the control plane, triggering background sync to S3 (write-back)
432
442
  or synchronously waiting for authoritative backend flush (write-through).
443
+
444
+ With local_only=True the object stays on this host: it is never flushed to a backend
445
+ and remains evictable. chunk_checksums records per-chunk CRC32 values for it, in layout
446
+ order, and generation (from stage_write) makes the daemon refuse the commit if the layout
447
+ was replaced since. A daemon without local-only support ignores all three and commits the
448
+ object for write-back; this returns False then, because the reply doesn't confirm
449
+ LOCAL_ONLY, but the object stays committed, so evict it if it must not reach the backend.
433
450
  """
434
451
  req = {
435
452
  "action": "commit_write",
@@ -438,6 +455,12 @@ class HyperCacheClient:
438
455
  }
439
456
  if sha256 is not None:
440
457
  req["sha256"] = sha256
458
+ if local_only:
459
+ req["local_only"] = True
460
+ if chunk_checksums is not None:
461
+ req["chunk_checksums"] = chunk_checksums
462
+ if generation is not None:
463
+ req["generation"] = generation
441
464
 
442
465
  # Commit hashes the staged data (when sha256 is given) and, for write-through, uploads it
443
466
  resp = self._send_request(req, timeout=self.ingest_timeout)
@@ -445,6 +468,12 @@ class HyperCacheClient:
445
468
  if status not in ("WRITECOMMITTED", "WRITE_COMMITTED"):
446
469
  logger.error(f"Commit of '{uri}' failed: {resp.get('error_message', 'unknown error')}")
447
470
  return False
471
+ if local_only and resp.get("sync_status") != "LOCAL_ONLY":
472
+ logger.error(
473
+ f"Commit of '{uri}' was not confirmed as LOCAL_ONLY "
474
+ f"(got {resp.get('sync_status')}); the daemon may predate local-only support"
475
+ )
476
+ return False
448
477
  return True
449
478
 
450
479
  def get_write_status(self, uri: str) -> dict:
@@ -7,9 +7,12 @@ Responsible for executing direct hardware DMA reads from raw NVMe block devices
7
7
 
8
8
  from __future__ import annotations
9
9
 
10
+ import ctypes
11
+ import errno
10
12
  import logging
11
13
  import mmap
12
14
  import os
15
+ import stat
13
16
  import threading
14
17
  import zlib
15
18
  from concurrent.futures import ThreadPoolExecutor
@@ -515,26 +518,109 @@ class DirectBlockWriter:
515
518
  """
516
519
  Direct Block Writer for write-back and write-through caching.
517
520
  Writes byte slices to striped physical NVMe block devices or POSIX shared memory chunks.
521
+
522
+ With direct_on_block_devices=True, writes to raw block devices use O_DIRECT. In testing on one
523
+ drive this raised both store speed and later read speed (benchmarks/results/lmcache_and_ttft.md).
524
+ Whatever O_DIRECT can't take goes through the page cache, so a write never fails because of it.
525
+ Callers must still commit, because the daemon's sync is what makes the data durable.
518
526
  """
519
527
 
520
- def __init__(self, max_workers: Optional[int] = None):
528
+ def __init__(self, max_workers: Optional[int] = None, direct_on_block_devices: bool = False):
521
529
  self._fd_cache: Dict[str, int] = {}
530
+ self._direct_fds: Dict[str, Optional[int]] = {}
531
+ self._direct_on_block_devices = direct_on_block_devices
532
+ self._fd_lock = threading.Lock()
522
533
  if max_workers is None:
523
534
  max_workers = min(64, max(16, (os.cpu_count() or 4) * 4))
524
535
  self._max_workers = max_workers
525
536
  self._executor = ThreadPoolExecutor(max_workers=max_workers)
526
537
 
527
538
  def _get_write_fd(self, device_path: str) -> int:
528
- if device_path not in self._fd_cache:
529
- try:
530
- fd = os.open(device_path, os.O_RDWR)
531
- self._fd_cache[device_path] = fd
532
- except OSError as e:
533
- logger.error(f"Failed to open device {device_path} for write: {e}")
539
+ with self._fd_lock:
540
+ if device_path not in self._fd_cache:
541
+ try:
542
+ fd = os.open(device_path, os.O_RDWR)
543
+ self._fd_cache[device_path] = fd
544
+ except OSError as e:
545
+ logger.error(f"Failed to open device {device_path} for write: {e}")
546
+ raise
547
+ return self._fd_cache[device_path]
548
+
549
+ @staticmethod
550
+ def _pwrite_all(fd: int, data: memoryview, offset: int) -> None:
551
+ # pwrite may write fewer bytes than asked, for example when the disk is nearly full
552
+ while len(data) > 0:
553
+ written = os.pwrite(fd, data, offset)
554
+ if written == 0:
555
+ raise IOError(f"Wrote 0 bytes at offset {offset}")
556
+ data = data[written:]
557
+ offset += written
558
+
559
+ @staticmethod
560
+ def _is_block_device(device_path: str) -> bool:
561
+ try:
562
+ return stat.S_ISBLK(os.stat(device_path).st_mode)
563
+ except OSError:
564
+ return False
565
+
566
+ @staticmethod
567
+ def _open_direct(device_path: str) -> int:
568
+ return os.open(device_path, os.O_RDWR | os.O_DIRECT)
569
+
570
+ @staticmethod
571
+ def _is_aligned(data: memoryview, block_size: int) -> bool:
572
+ # The address of a read-only buffer isn't available here, so treat it as unaligned
573
+ if data.readonly:
574
+ return False
575
+ return ctypes.addressof(ctypes.c_char.from_buffer(data)) % block_size == 0
576
+
577
+ def _get_direct_fd(self, device_path: str) -> Optional[int]:
578
+ if not self._direct_on_block_devices:
579
+ return None
580
+ with self._fd_lock:
581
+ if device_path not in self._direct_fds:
582
+ fd = None
583
+ if hasattr(os, "O_DIRECT") and self._is_block_device(device_path):
584
+ try:
585
+ fd = self._open_direct(device_path)
586
+ except OSError as e:
587
+ logger.debug(f"O_DIRECT is unavailable on {device_path}: {e}")
588
+ self._direct_fds[device_path] = fd
589
+ return self._direct_fds[device_path]
590
+
591
+ def _write_device_chunk(self, device_path: str, data: memoryview, offset: int) -> None:
592
+ direct_fd = self._get_direct_fd(device_path)
593
+ written = 0
594
+ if direct_fd is not None:
595
+ written = self._write_whole_blocks_direct(direct_fd, device_path, data, offset)
596
+ if written < len(data):
597
+ self._pwrite_all(self._get_write_fd(device_path), data[written:], offset + written)
598
+
599
+ def _write_whole_blocks_direct(self, fd: int, device_path: str, data: memoryview, offset: int) -> int:
600
+ """Writes as many whole blocks as O_DIRECT accepts. Returns the bytes written."""
601
+ block_size = logical_block_size(device_path)
602
+ whole = len(data) - len(data) % block_size
603
+ if whole == 0 or offset % block_size != 0:
604
+ return 0
605
+ source = data[:whole]
606
+ if not self._is_aligned(source, block_size):
607
+ # An mmap is page-aligned, and is freed along with the views of it
608
+ source = memoryview(mmap.mmap(-1, whole))
609
+ source[:] = data[:whole]
610
+ written = 0
611
+ try:
612
+ while written < whole:
613
+ count = os.pwrite(fd, source[written:], offset + written)
614
+ written += count
615
+ if count == 0 or count % block_size != 0:
616
+ break
617
+ except OSError as e:
618
+ if e.errno != errno.EINVAL:
534
619
  raise
535
- return self._fd_cache[device_path]
620
+ logger.debug(f"O_DIRECT write refused on {device_path}: {e}")
621
+ return written
536
622
 
537
- def _write_ram_chunk(self, target_path: str, chunk_data: bytes) -> None:
623
+ def _write_ram_chunk(self, target_path: str, chunk_data: Union[bytes, memoryview]) -> None:
538
624
  # The daemon creates staged RAM chunk files. Never create the directory here: if it is
539
625
  # missing, this process does not share /dev/shm with the daemon, and writing a private
540
626
  # copy would make the checkpoint silently disappear.
@@ -557,7 +643,7 @@ class DirectBlockWriter:
557
643
  if not chunk_layout or not data:
558
644
  return 0
559
645
 
560
- view = memoryview(data)
646
+ view = memoryview(data).cast("B")
561
647
  total_len = len(view)
562
648
  current_virtual_offset = 0
563
649
  tasks = []
@@ -571,19 +657,26 @@ class DirectBlockWriter:
571
657
  break
572
658
 
573
659
  slice_end = min(chunk_end, total_len)
574
- slice_bytes = bytes(view[chunk_start:slice_end])
660
+ # A view, not a copy: this method waits for every write before returning
661
+ slice_bytes = view[chunk_start:slice_end]
575
662
 
576
663
  if chunk.tier == "ram":
577
664
  tasks.append(self._executor.submit(self._write_ram_chunk, chunk.device, slice_bytes))
578
665
  else:
579
- fd = self._get_write_fd(chunk.device)
580
666
  tasks.append(
581
- self._executor.submit(os.pwrite, fd, slice_bytes, chunk.offset)
667
+ self._executor.submit(self._write_device_chunk, chunk.device, slice_bytes, chunk.offset)
582
668
  )
583
669
 
584
- # Wait for all chunks to write
670
+ # Wait for every chunk before raising: the caller may reuse or free `data` on an error,
671
+ # so no write may still be reading it then
672
+ errors = []
585
673
  for t in tasks:
586
- t.result()
674
+ try:
675
+ t.result()
676
+ except BaseException as e: # noqa: BLE001 - re-raised below after all writes end
677
+ errors.append(e)
678
+ if errors:
679
+ raise errors[0]
587
680
 
588
681
  return total_len
589
682
 
@@ -595,5 +688,12 @@ class DirectBlockWriter:
595
688
  except Exception:
596
689
  pass
597
690
  self._fd_cache.clear()
691
+ for fd in self._direct_fds.values():
692
+ if fd is not None:
693
+ try:
694
+ os.close(fd)
695
+ except Exception:
696
+ pass
697
+ self._direct_fds.clear()
598
698
  self._executor.shutdown(wait=False)
599
699
 
@@ -0,0 +1,225 @@
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.
6
+
7
+ This is a building block for code that manages its own KV-cache blocks. For LMCache,
8
+ use the connector in `lmcache-connector/`. There is no NVIDIA Dynamo KVBM integration.
9
+
10
+ Blocks stay on this host and remain evictable, unless write_through=True asks for a
11
+ synchronous backend flush.
12
+
13
+ Every block is checked against per-chunk CRC32 values on read, and a block whose state or
14
+ checksums can't be confirmed is a miss: a wrong block is never returned.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import hashlib
20
+ import logging
21
+ import zlib
22
+ from typing import Any, List, Optional, Sequence, Union
23
+
24
+ from hypercache.client import HyperCacheClient
25
+ from hypercache.datapath import ChunkLocation, DirectBlockWriter, get_data_reader
26
+
27
+ logger = logging.getLogger(__name__)
28
+
29
+ # States in which a block's data is complete and stays put: LOCAL_ONLY for normal blocks,
30
+ # SYNCED_BACKEND for write-through ones. Anything else (staged, being rewritten, unknown) is a miss.
31
+ _READABLE_STATES = ("LOCAL_ONLY", "SYNCED_BACKEND")
32
+
33
+
34
+ class HyperCacheKVStore:
35
+ """
36
+ Content-addressed KV-Cache Block Store backed by HyperCache Tier 1 (RAM) and Tier 2 (NVMe).
37
+ """
38
+
39
+ KV_URI_PREFIX = "hypercache://kv_cache"
40
+
41
+ def __init__(
42
+ self,
43
+ socket_path: Optional[str] = None,
44
+ default_tier: str = "ram",
45
+ prefer_gds: bool = True,
46
+ write_through: bool = False,
47
+ ):
48
+ self.socket_path = socket_path
49
+ self.default_tier = default_tier
50
+ self.prefer_gds = prefer_gds
51
+ self.write_through = write_through
52
+ self._client = HyperCacheClient(socket_path=socket_path)
53
+ self._reader = get_data_reader(prefer_gds=prefer_gds)
54
+ self._writer = DirectBlockWriter()
55
+
56
+ @staticmethod
57
+ def compute_prefix_hash(
58
+ token_ids: Sequence[int],
59
+ model_id: str = "default",
60
+ layer_idx: Optional[int] = None,
61
+ ) -> str:
62
+ """
63
+ Computes a deterministic SHA-256 content-addressed key for a token prefix chunk.
64
+ """
65
+ h = hashlib.sha256()
66
+ h.update(model_id.encode("utf-8"))
67
+ h.update(b"::")
68
+ if layer_idx is not None:
69
+ h.update(f"layer_{layer_idx}::".encode("utf-8"))
70
+ h.update(",".join(str(t) for t in token_ids).encode("utf-8"))
71
+ return h.hexdigest()
72
+
73
+ def _make_uri(self, block_key: str) -> str:
74
+ if block_key.startswith("hypercache://"):
75
+ return block_key
76
+ return f"{self.KV_URI_PREFIX}/{block_key}.kv"
77
+
78
+ def put_kv_block(
79
+ self,
80
+ block_key: str,
81
+ kv_data: Union[bytes, bytearray, memoryview, Any],
82
+ tier: Optional[str] = None,
83
+ pinned: bool = False,
84
+ ) -> bool:
85
+ """
86
+ Stores a KV-cache tensor or byte block into HyperCache Tier-1 RAM or Tier-2 NVMe.
87
+ """
88
+ uri = self._make_uri(block_key)
89
+ target_tier = tier or self.default_tier
90
+
91
+ if isinstance(kv_data, (bytes, bytearray, memoryview)):
92
+ raw_bytes = bytes(kv_data)
93
+ else:
94
+ try:
95
+ import torch
96
+ if isinstance(kv_data, torch.Tensor):
97
+ t_cpu = kv_data.detach().contiguous().cpu()
98
+ raw_bytes = (
99
+ t_cpu.numpy().tobytes()
100
+ if t_cpu.dtype != torch.bfloat16
101
+ else t_cpu.view(torch.uint16).numpy().tobytes()
102
+ )
103
+ else:
104
+ raise TypeError(f"Unsupported kv_data type: {type(kv_data)}")
105
+ except ImportError as e:
106
+ raise TypeError("kv_data must be bytes-like when PyTorch is unavailable") from e
107
+
108
+ stage_res = self._client.stage_write(
109
+ uri=uri,
110
+ size_bytes=len(raw_bytes),
111
+ tier=target_tier,
112
+ is_leader=False,
113
+ auto_flush_s3=False,
114
+ write_through=self.write_through,
115
+ pinned=pinned,
116
+ )
117
+ if not stage_res.is_staged:
118
+ return False
119
+
120
+ layout = stage_res.chunk_layout
121
+ try:
122
+ if sum(c.length for c in layout) != len(raw_bytes):
123
+ raise IOError(f"staged layout for {uri} does not match the block size")
124
+ self._writer.write_chunks(layout, raw_bytes)
125
+ if self.write_through:
126
+ # The daemon verifies the digest and records per-chunk CRCs from it
127
+ committed = self._client.commit_write(
128
+ uri, sha256=hashlib.sha256(raw_bytes).hexdigest(), write_through=True
129
+ )
130
+ else:
131
+ committed = self._client.commit_write(
132
+ uri,
133
+ local_only=True,
134
+ chunk_checksums=_chunk_crcs(layout, raw_bytes),
135
+ generation=stage_res.generation,
136
+ )
137
+ except Exception:
138
+ self._discard(uri)
139
+ raise
140
+ if not committed:
141
+ self._discard(uri)
142
+ return committed
143
+
144
+ def _discard(self, uri: str) -> None:
145
+ # A block that failed to store must not linger: it may be unwritten or not local-only
146
+ try:
147
+ self._client.evict(uri)
148
+ except Exception as e: # noqa: BLE001 - best effort; the block is unreadable anyway
149
+ logger.warning(f"Could not evict failed KV block {uri}: {e}")
150
+
151
+ def get_kv_block(
152
+ self,
153
+ block_key: str,
154
+ out_tensor: Optional[Any] = None,
155
+ ) -> Optional[Union[bytes, Any]]:
156
+ """
157
+ Retrieves a KV-cache block by key. If `out_tensor` (a pre-allocated CPU or CUDA
158
+ PyTorch tensor) is provided, copies directly into `out_tensor` and returns it.
159
+ Returns `None` on cache miss.
160
+ """
161
+ uri = self._make_uri(block_key)
162
+ loc = self._client.locate(uri, auto_ingest=False)
163
+ if not self._is_readable(loc):
164
+ return None
165
+ if out_tensor is not None and _nbytes(out_tensor) != loc.object_size:
166
+ # A buffer of another size can't hold this block; leave it untouched
167
+ return None
168
+
169
+ # Read to host memory and check every chunk before anything reaches the caller, so a
170
+ # stale or torn block is a miss rather than wrong data in out_tensor
171
+ try:
172
+ raw = bytes(self._reader.read_range(loc.chunk_layout, 0, loc.object_size))
173
+ except (IOError, OSError) as e:
174
+ logger.warning(f"KV block {uri} could not be read, treating it as a miss: {e}")
175
+ return None
176
+ if len(raw) != loc.object_size or _chunk_crcs(loc.chunk_layout, raw) != [
177
+ c.checksum for c in loc.chunk_layout
178
+ ]:
179
+ logger.warning(f"KV block {uri} failed its checksum, treating it as a miss")
180
+ return None
181
+
182
+ if out_tensor is not None:
183
+ import torch
184
+
185
+ src = torch.frombuffer(bytearray(raw), dtype=torch.uint8)
186
+ out_tensor.view(torch.uint8).reshape(-1).copy_(src)
187
+ return out_tensor
188
+ return raw
189
+
190
+ def exists_kv_block(self, block_key: str) -> bool:
191
+ uri = self._make_uri(block_key)
192
+ return self._is_readable(self._client.locate(uri, auto_ingest=False))
193
+
194
+ @staticmethod
195
+ def _is_readable(loc: Any) -> bool:
196
+ # Only a finished block whose every chunk has a recorded CRC can be verified. A staged
197
+ # layout is published before its data is written, and an old daemon reports no state.
198
+ layout = loc.chunk_layout or []
199
+ return (
200
+ loc.is_hit
201
+ and loc.sync_status in _READABLE_STATES
202
+ and bool(layout)
203
+ and all(c.checksum is not None for c in layout)
204
+ and sum(c.length for c in layout) == loc.object_size
205
+ )
206
+
207
+ def close(self) -> None:
208
+ self._reader.close()
209
+ self._writer.close()
210
+ self._client.close()
211
+
212
+
213
+ def _chunk_crcs(layout: List[ChunkLocation], data: bytes) -> List[int]:
214
+ """CRC32 of each chunk's slice of the block, in layout order."""
215
+ view = memoryview(data)
216
+ crcs = []
217
+ position = 0
218
+ for chunk in layout:
219
+ crcs.append(zlib.crc32(view[position : position + chunk.length]) & 0xFFFFFFFF)
220
+ position += chunk.length
221
+ return crcs
222
+
223
+
224
+ def _nbytes(tensor: Any) -> int:
225
+ return tensor.numel() * tensor.element_size()
@@ -1,10 +1,12 @@
1
1
  """
2
- HyperCache Layer-by-Layer Pipelined Loader & Compute-I/O Overlap Engine.
2
+ HyperCache layer-by-layer pipelined loader.
3
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.
4
+ Reads a model's byte ranges in order and prefetches the next ranges in the background. An
5
+ engine that can run layers as their weights arrive can use this to overlap compute with I/O.
6
+
7
+ This module only returns bytes. It does not know true layer boundaries unless the caller sets
8
+ `layers`, and it does not run the model. The first token needs every layer, so overlap saves at
9
+ most min(T_io, T_compute). See benchmarks/results/lmcache_and_ttft.md.
8
10
  """
9
11
 
10
12
  from __future__ import annotations
@@ -34,7 +36,7 @@ class LayerDescriptor:
34
36
 
35
37
  class HyperCachePipelinedLoader:
36
38
  """
37
- Pipelined, compute-overlapped model loader for streaming transformer weights.
39
+ Pipelined reader for streaming transformer weights in order.
38
40
  """
39
41
 
40
42
  def __init__(
@@ -102,7 +104,8 @@ class HyperCachePipelinedLoader:
102
104
  def load_initial_layer(self) -> Tuple[LayerDescriptor, bytes]:
103
105
  """
104
106
  Synchronously loads Layer 0 / Embedding and triggers background prefetching for Layer 1.
105
- Unblocks the inference engine in ~20-50 ms.
107
+ This takes as long as the first range takes to read: 880 ms for a 1 GB embedding table in
108
+ benchmarks/results/lmcache_and_ttft.md.
106
109
  """
107
110
  if not self.layers:
108
111
  raise ValueError("No layers found in model.")
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: hypercache-io
3
- Version: 0.9.4
3
+ Version: 0.10.0
4
4
  Summary: HyperCache: Host-Local NVMe Caching and Zero-Copy Direct Block DMA / GPUDirect Storage Acceleration for AI Workloads
5
5
  Author: Looe Labs
6
6
  License: Apache-2.0
@@ -108,6 +108,12 @@ if layout.is_hit:
108
108
 
109
109
  ---
110
110
 
111
+ ## LMCache
112
+
113
+ The LMCache integration isn't part of this package. It's a separate Rust connector, covered in [`lmcache-connector/README.md`](../lmcache-connector/README.md). For code that manages its own KV blocks, use `HyperCacheKVStore` from this package.
114
+
115
+ ---
116
+
111
117
  ## Running Unit Tests
112
118
 
113
119
  ```bash
@@ -16,6 +16,7 @@ hypercache_io.egg-info/entry_points.txt
16
16
  hypercache_io.egg-info/requires.txt
17
17
  hypercache_io.egg-info/top_level.txt
18
18
  tests/test_client.py
19
+ tests/test_direct_writer.py
19
20
  tests/test_fsspec.py
20
21
  tests/test_integrations_and_kv.py
21
22
  tests/test_pipelined_and_numa.py
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "hypercache-io"
7
- version = "0.9.4"
7
+ version = "0.10.0"
8
8
  description = "HyperCache: Host-Local NVMe Caching and Zero-Copy Direct Block DMA / GPUDirect Storage Acceleration for AI Workloads"
9
9
  readme = "README.md"
10
10
  license = { text = "Apache-2.0" }
@@ -0,0 +1,254 @@
1
+ """
2
+ Unit tests for DirectBlockWriter's O_DIRECT mode. They run anywhere, including macOS, by replacing
3
+ the direct file descriptor with a plain one and recording what each write was given. The last test
4
+ uses real O_DIRECT where the platform and filesystem support it.
5
+ """
6
+
7
+ import ctypes
8
+ import errno
9
+ import mmap
10
+ import os
11
+ import shutil
12
+ import tempfile
13
+ import unittest
14
+ from unittest import mock
15
+
16
+ from hypercache.datapath import ChunkLocation, DirectBlockWriter
17
+
18
+ BLOCK = 4096
19
+
20
+
21
+ def pattern(size, seed=7):
22
+ return bytes((i * seed + i // 251) % 256 for i in range(size))
23
+
24
+
25
+ def aligned_buffer(data, shift=0):
26
+ view = memoryview(mmap.mmap(-1, len(data) + shift + BLOCK))[shift : shift + len(data)]
27
+ view[:] = data
28
+ return view
29
+
30
+
31
+ class WriterTestCase(unittest.TestCase):
32
+ def setUp(self):
33
+ handle, self.path = tempfile.mkstemp()
34
+ os.ftruncate(handle, 64 * 1024 * 1024)
35
+ os.close(handle)
36
+ self.addCleanup(os.unlink, self.path)
37
+ self.direct_fds = []
38
+ self.direct_writes = []
39
+ self.real_pwrite = os.pwrite
40
+
41
+ def open_direct(path):
42
+ fd = os.open(path, os.O_RDWR)
43
+ self.direct_fds.append(fd)
44
+ return fd
45
+
46
+ for target, replacement in (
47
+ ("hypercache.datapath.DirectBlockWriter._is_block_device", staticmethod(lambda path: True)),
48
+ ("hypercache.datapath.DirectBlockWriter._open_direct", staticmethod(open_direct)),
49
+ ("hypercache.datapath.logical_block_size", lambda path: BLOCK),
50
+ ("hypercache.datapath.os.pwrite", self.spy_pwrite),
51
+ ):
52
+ patcher = mock.patch(target, replacement)
53
+ patcher.start()
54
+ self.addCleanup(patcher.stop)
55
+ if not hasattr(os, "O_DIRECT"):
56
+ patcher = mock.patch("hypercache.datapath.os.O_DIRECT", 0, create=True)
57
+ patcher.start()
58
+ self.addCleanup(patcher.stop)
59
+ self.writer = DirectBlockWriter(max_workers=4, direct_on_block_devices=True)
60
+ self.addCleanup(self.writer.close)
61
+
62
+ def spy_pwrite(self, fd, data, offset):
63
+ if fd in self.direct_fds:
64
+ address = ctypes.addressof(ctypes.c_char.from_buffer(data))
65
+ self.direct_writes.append((address % BLOCK, len(data), offset))
66
+ return self.real_pwrite(fd, data, offset)
67
+
68
+ def layout(self, *lengths, start=BLOCK):
69
+ chunks, offset = [], start
70
+ for length in lengths:
71
+ chunks.append(ChunkLocation(device=self.path, offset=offset, length=length))
72
+ offset += (length + BLOCK - 1) // BLOCK * BLOCK
73
+ return chunks
74
+
75
+ def on_disk(self, offset, length):
76
+ with open(self.path, "rb") as f:
77
+ f.seek(offset)
78
+ return f.read(length)
79
+
80
+ def assert_direct_writes_are_aligned(self):
81
+ self.assertTrue(self.direct_writes, "expected O_DIRECT to be used")
82
+ for address_remainder, length, offset in self.direct_writes:
83
+ self.assertEqual(address_remainder, 0)
84
+ self.assertEqual(length % BLOCK, 0)
85
+ self.assertEqual(offset % BLOCK, 0)
86
+
87
+ def test_aligned_buffer_goes_direct_across_chunks(self):
88
+ data = pattern(3 * 1024 * 1024)
89
+ self.writer.write_chunks(self.layout(1024 * 1024, 1024 * 1024, 1024 * 1024), aligned_buffer(data))
90
+ self.assertEqual(self.on_disk(BLOCK, len(data)), data)
91
+ self.assert_direct_writes_are_aligned()
92
+ self.assertEqual(sum(w[1] for w in self.direct_writes), len(data))
93
+
94
+ def test_unaligned_buffer_is_copied_to_an_aligned_one(self):
95
+ data = pattern(256 * 1024)
96
+ self.writer.write_chunks(self.layout(len(data)), aligned_buffer(data, shift=1))
97
+ self.assertEqual(self.on_disk(BLOCK, len(data)), data)
98
+ self.assert_direct_writes_are_aligned()
99
+
100
+ def test_read_only_bytes_are_supported(self):
101
+ data = pattern(64 * 1024)
102
+ self.writer.write_chunks(self.layout(len(data)), data)
103
+ self.assertEqual(self.on_disk(BLOCK, len(data)), data)
104
+ self.assert_direct_writes_are_aligned()
105
+
106
+ def test_partial_last_block_does_not_touch_its_neighbour(self):
107
+ neighbour_offset = BLOCK + 3 * BLOCK
108
+ with open(self.path, "r+b") as f:
109
+ f.seek(BLOCK + 2 * BLOCK + 100)
110
+ f.write(b"\xAB" * (neighbour_offset - (BLOCK + 2 * BLOCK + 100) + BLOCK))
111
+ data = pattern(2 * BLOCK + 100)
112
+ self.writer.write_chunks(self.layout(len(data)), aligned_buffer(data))
113
+ self.assertEqual(self.on_disk(BLOCK, len(data)), data)
114
+ self.assertEqual(self.on_disk(BLOCK + len(data), 8), b"\xAB" * 8)
115
+ self.assertEqual(self.on_disk(neighbour_offset, BLOCK), b"\xAB" * BLOCK)
116
+ self.assertEqual(sum(w[1] for w in self.direct_writes), 2 * BLOCK)
117
+ self.assert_direct_writes_are_aligned()
118
+
119
+ def test_less_than_a_block_never_goes_direct(self):
120
+ data = pattern(100)
121
+ self.writer.write_chunks(self.layout(100), aligned_buffer(data))
122
+ self.assertEqual(self.on_disk(BLOCK, 100), data)
123
+ self.assertEqual(self.direct_writes, [])
124
+
125
+ def test_unaligned_offset_never_goes_direct(self):
126
+ data = pattern(2 * BLOCK)
127
+ self.writer.write_chunks(self.layout(len(data), start=BLOCK + 512), aligned_buffer(data))
128
+ self.assertEqual(self.on_disk(BLOCK + 512, len(data)), data)
129
+ self.assertEqual(self.direct_writes, [])
130
+
131
+ def test_refused_direct_write_falls_back_to_the_page_cache(self):
132
+ data = pattern(16 * BLOCK)
133
+
134
+ def refuse(fd, buffer, offset):
135
+ if fd in self.direct_fds:
136
+ raise OSError(errno.EINVAL, "refused")
137
+ return self.real_pwrite(fd, buffer, offset)
138
+
139
+ with mock.patch("hypercache.datapath.os.pwrite", refuse):
140
+ self.writer.write_chunks(self.layout(len(data)), aligned_buffer(data))
141
+ self.assertEqual(self.on_disk(BLOCK, len(data)), data)
142
+
143
+ def test_short_direct_writes_complete_the_chunk(self):
144
+ for short in (BLOCK, BLOCK + 17):
145
+ with self.subTest(short=short):
146
+ data = pattern(16 * BLOCK, seed=short % 13 + 1)
147
+ calls = []
148
+
149
+ def one_short_write(fd, buffer, offset, short=short, calls=calls):
150
+ if fd in self.direct_fds and not calls:
151
+ calls.append(1)
152
+ return self.real_pwrite(fd, buffer[:short], offset)
153
+ return self.real_pwrite(fd, buffer, offset)
154
+
155
+ with mock.patch("hypercache.datapath.os.pwrite", one_short_write):
156
+ self.writer.write_chunks(self.layout(len(data)), aligned_buffer(data))
157
+ self.assertEqual(self.on_disk(BLOCK, len(data)), data)
158
+
159
+ def test_real_errors_are_reported(self):
160
+ def full(fd, buffer, offset):
161
+ raise OSError(errno.ENOSPC, "no space")
162
+
163
+ with mock.patch("hypercache.datapath.os.pwrite", full):
164
+ with self.assertRaises(OSError) as caught:
165
+ self.writer.write_chunks(self.layout(4 * BLOCK), aligned_buffer(pattern(4 * BLOCK)))
166
+ self.assertEqual(caught.exception.errno, errno.ENOSPC)
167
+
168
+ def test_a_write_that_makes_no_progress_is_an_error(self):
169
+ with mock.patch("hypercache.datapath.os.pwrite", lambda fd, buffer, offset: 0):
170
+ with self.assertRaises(IOError):
171
+ self.writer.write_chunks(self.layout(4 * BLOCK), aligned_buffer(pattern(4 * BLOCK)))
172
+
173
+ def test_off_by_default(self):
174
+ writer = DirectBlockWriter(max_workers=2)
175
+ self.addCleanup(writer.close)
176
+ data = pattern(4 * BLOCK)
177
+ writer.write_chunks(self.layout(len(data)), aligned_buffer(data))
178
+ self.assertEqual(self.on_disk(BLOCK, len(data)), data)
179
+ self.assertEqual(self.direct_writes, [])
180
+
181
+ def test_regular_files_are_not_direct(self):
182
+ with mock.patch("hypercache.datapath.DirectBlockWriter._is_block_device", staticmethod(lambda path: False)):
183
+ data = pattern(4 * BLOCK)
184
+ self.writer.write_chunks(self.layout(len(data)), aligned_buffer(data))
185
+ self.assertEqual(self.on_disk(BLOCK, len(data)), data)
186
+ self.assertEqual(self.direct_writes, [])
187
+
188
+ def test_failure_to_open_direct_uses_the_page_cache(self):
189
+ def cannot_open(path):
190
+ raise OSError(errno.EINVAL, "no O_DIRECT here")
191
+
192
+ with mock.patch("hypercache.datapath.DirectBlockWriter._open_direct", staticmethod(cannot_open)):
193
+ data = pattern(4 * BLOCK)
194
+ self.writer.write_chunks(self.layout(len(data)), aligned_buffer(data))
195
+ self.assertEqual(self.on_disk(BLOCK, len(data)), data)
196
+
197
+ def test_ram_chunks_never_go_direct(self):
198
+ target = self.path + ".ram"
199
+ self.addCleanup(lambda: os.path.exists(target) and os.unlink(target))
200
+ data = pattern(4 * BLOCK)
201
+ chunk = ChunkLocation(device=target, offset=0, length=len(data), tier="ram")
202
+ self.writer.write_chunks([chunk], aligned_buffer(data))
203
+ with open(target, "rb") as f:
204
+ self.assertEqual(f.read(), data)
205
+ self.assertEqual(self.direct_writes, [])
206
+
207
+
208
+ class RealDirectIOTest(unittest.TestCase):
209
+ @unittest.skipUnless(hasattr(os, "O_DIRECT"), "needs O_DIRECT")
210
+ def test_real_o_direct_or_fallback_writes_correct_bytes(self):
211
+ # Not every filesystem allows O_DIRECT. Either way, the bytes must be right.
212
+ directory = tempfile.mkdtemp(dir=os.getcwd())
213
+ self.addCleanup(shutil.rmtree, directory, ignore_errors=True)
214
+ path = os.path.join(directory, "device")
215
+ with open(path, "wb") as f:
216
+ f.truncate(8 * 1024 * 1024)
217
+ data = pattern(2 * 1024 * 1024 + 300)
218
+ layout = [ChunkLocation(device=path, offset=4096, length=len(data))]
219
+ with mock.patch("hypercache.datapath.DirectBlockWriter._is_block_device", staticmethod(lambda p: True)):
220
+ writer = DirectBlockWriter(max_workers=2, direct_on_block_devices=True)
221
+ writer.write_chunks(layout, aligned_buffer(data))
222
+ writer.close()
223
+ with open(path, "rb") as f:
224
+ f.seek(4096)
225
+ self.assertEqual(f.read(len(data)), data)
226
+
227
+
228
+
229
+ class WriteChunksErrorTest(unittest.TestCase):
230
+ def test_failed_chunk_waits_for_the_others(self):
231
+ # Review item 6: on an error, no other chunk write may still be reading the caller's buffer
232
+ import threading
233
+ import time
234
+
235
+ writer = DirectBlockWriter()
236
+ self.addCleanup(writer.close)
237
+ finished = []
238
+ lock = threading.Lock()
239
+
240
+ def write(device, data, offset):
241
+ if offset == 0:
242
+ raise IOError("device gone")
243
+ time.sleep(0.3)
244
+ with lock:
245
+ finished.append(offset)
246
+
247
+ layout = [ChunkLocation(device="/dev/fake", offset=i * BLOCK, length=BLOCK) for i in range(4)]
248
+ with mock.patch.object(writer, "_write_device_chunk", side_effect=write):
249
+ with self.assertRaises(IOError):
250
+ writer.write_chunks(layout, b"\0" * (4 * BLOCK))
251
+ self.assertEqual(sorted(finished), [BLOCK, 2 * BLOCK, 3 * BLOCK])
252
+
253
+ if __name__ == "__main__":
254
+ unittest.main()
@@ -33,6 +33,9 @@ class TestIntegrationsAndKVStore(unittest.TestCase):
33
33
  os.remove(cls.SOCKET_PATH)
34
34
 
35
35
  cls._catalog = {}
36
+ cls._generation = 0
37
+ cls.commits = []
38
+ cls.legacy_commit = False
36
39
  cls._next_offset = 4096
37
40
  cls._lock = threading.Lock()
38
41
  cls._server_sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
@@ -62,22 +65,47 @@ class TestIntegrationsAndKVStore(unittest.TestCase):
62
65
  size = int(req.get("size_bytes", 0))
63
66
  off = cls._next_offset
64
67
  cls._next_offset += ((size + 4095) // 4096) * 4096
65
- layout = [{"device": cls.ARENA_FILE, "offset": off, "length": size, "tier": "nvme"}]
66
- cls._catalog[uri] = {"size": size, "layout": layout}
68
+ # Two chunks when possible, so per-chunk CRCs are exercised
69
+ first = (size // 2 + 4095) // 4096 * 4096 if size > 4096 else size
70
+ layout = [{"device": cls.ARENA_FILE, "offset": off, "length": first, "tier": "nvme"}]
71
+ if size > first:
72
+ layout.append(
73
+ {"device": cls.ARENA_FILE, "offset": off + first, "length": size - first, "tier": "nvme"}
74
+ )
75
+ cls._generation += 1
76
+ cls._catalog[uri] = {
77
+ "size": size, "layout": layout, "status": "STAGED", "generation": cls._generation,
78
+ }
67
79
  resp = {
68
80
  "status": "WRITESTAGED",
69
81
  "object_size": size,
70
82
  "chunk_size": 4194304,
71
83
  "chunk_layout": layout,
72
84
  "sync_status": "STAGED",
85
+ "generation": cls._generation,
73
86
  }
74
87
  elif action == "commit_write":
75
- info = cls._catalog.get(uri, {"size": 0})
76
- resp = {
77
- "status": "WRITECOMMITTED",
78
- "object_size": info["size"],
79
- "sync_status": "COMMITTED",
80
- }
88
+ cls.commits.append(req)
89
+ info = cls._catalog.get(uri)
90
+ # The real daemon's local-only rules, unless acting as an old daemon
91
+ local_only = req.get("local_only") and not cls.legacy_commit
92
+ if info is None:
93
+ resp = {"status": "ERROR", "error_message": "not staged"}
94
+ elif local_only and req.get("generation") not in (None, info["generation"]):
95
+ resp = {"status": "ERROR", "error_message": "replaced since it was staged"}
96
+ elif local_only and info["status"] != "STAGED":
97
+ resp = {"status": "ERROR", "error_message": "not STAGED"}
98
+ else:
99
+ for chunk, crc in zip(info["layout"], req.get("chunk_checksums") or []):
100
+ chunk["checksum"] = crc
101
+ info["status"] = "LOCAL_ONLY" if local_only else "COMMITTED"
102
+ resp = {
103
+ "status": "WRITECOMMITTED",
104
+ "object_size": info["size"],
105
+ "sync_status": info["status"],
106
+ }
107
+ elif action == "evict":
108
+ resp = {"status": "EVICTED"} if cls._catalog.pop(uri, None) else {"status": "ERROR"}
81
109
  elif action in ("locate", "ingest"):
82
110
  if uri in cls._catalog:
83
111
  info = cls._catalog[uri]
@@ -86,6 +114,8 @@ class TestIntegrationsAndKVStore(unittest.TestCase):
86
114
  "object_size": info["size"],
87
115
  "chunk_size": 4194304,
88
116
  "chunk_layout": info["layout"],
117
+ "generation": info["generation"],
118
+ "sync_status": info["status"],
89
119
  }
90
120
  else:
91
121
  resp = {"status": "MISS"}
@@ -205,6 +235,71 @@ class TestIntegrationsAndKVStore(unittest.TestCase):
205
235
 
206
236
  fetched = kv.get_kv_block(block_key)
207
237
  self.assertEqual(fetched, kv_payload)
238
+ commit = self.commits[-1]
239
+ self.assertTrue(commit["local_only"])
240
+ self.assertEqual(len(commit["chunk_checksums"]), len(self._catalog[commit["uri"]]["layout"]))
241
+ self.assertIsNotNone(commit["generation"])
242
+ kv.close()
243
+
244
+ def _stored_block(self, name: str, payload: bytes):
245
+ kv = HyperCacheKVStore(socket_path=self.SOCKET_PATH, prefer_gds=False)
246
+ self.assertTrue(kv.put_kv_block(name, payload))
247
+ return kv, kv._make_uri(name)
248
+
249
+ def test_kv_corrupt_block_is_a_miss(self):
250
+ # Review item 2: data that changed under a block is never returned
251
+ payload = bytes(range(256)) * 64
252
+ kv, uri = self._stored_block("corrupt", payload)
253
+ chunk = self._catalog[uri]["layout"][1]
254
+ with open(self.ARENA_FILE, "r+b") as f:
255
+ f.seek(chunk["offset"] + 10)
256
+ f.write(b"\xff\xfe")
257
+ self.assertIsNone(kv.get_kv_block("corrupt"))
258
+ kv.close()
259
+
260
+ def test_kv_block_in_any_other_state_is_a_miss(self):
261
+ # Review item 2: staged, write-back and unknown-state blocks can't be verified
262
+ payload = b"x" * 10000
263
+ kv, uri = self._stored_block("states", payload)
264
+ info = self._catalog[uri]
265
+ for status in ("STAGED", "COMMITTED", "SYNCING_BACKEND", None):
266
+ info["status"] = status
267
+ self.assertFalse(kv.exists_kv_block("states"), status)
268
+ self.assertIsNone(kv.get_kv_block("states"), status)
269
+ info["status"] = "LOCAL_ONLY"
270
+ del info["layout"][0]["checksum"]
271
+ self.assertIsNone(kv.get_kv_block("states"), "a chunk without a CRC")
272
+ kv.close()
273
+
274
+ def test_kv_old_daemon_commit_fails_and_is_evicted(self):
275
+ # Review items 2 and 4: a commit not confirmed LOCAL_ONLY must not leave a block behind
276
+ kv = HyperCacheKVStore(socket_path=self.SOCKET_PATH, prefer_gds=False)
277
+ type(self).legacy_commit = True
278
+ try:
279
+ self.assertFalse(kv.put_kv_block("legacy", b"y" * 9000))
280
+ finally:
281
+ type(self).legacy_commit = False
282
+ self.assertNotIn(kv._make_uri("legacy"), self._catalog)
283
+ kv.close()
284
+
285
+ def test_kv_commit_of_a_replaced_layout_is_refused(self):
286
+ # Review item 3: a writer can't publish a layout another writer staged after it
287
+ kv = HyperCacheKVStore(socket_path=self.SOCKET_PATH, prefer_gds=False)
288
+ uri = kv._make_uri("race")
289
+ stage = kv._client.stage_write(uri, 8192, tier="nvme", auto_flush_s3=False)
290
+ kv._client.stage_write(uri, 8192, tier="nvme", auto_flush_s3=False)
291
+ self.assertFalse(kv._client.commit_write(uri, local_only=True, generation=stage.generation))
292
+ kv.close()
293
+
294
+ def test_kv_wrong_size_buffer_is_a_miss(self):
295
+ try:
296
+ import torch
297
+ except ImportError:
298
+ self.skipTest("needs torch")
299
+ kv, _ = self._stored_block("size", b"z" * 8192)
300
+ out = torch.full((100,), 7, dtype=torch.uint8)
301
+ self.assertIsNone(kv.get_kv_block("size", out_tensor=out))
302
+ self.assertTrue(bool((out == 7).all()))
208
303
  kv.close()
209
304
 
210
305
 
@@ -1,151 +0,0 @@
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()
File without changes