File size: 11,152 Bytes
3e56913
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
"""Strict, mmap-backed reader for offline V-JEPA2 future targets.



Ported from simlingoCODE/simlingo_train/dataloader/future_cache.py (self-contained,

stdlib + numpy + torch only) so DriveVLA does not depend on the simlingo repo.



The cache identity is derived only from the canonical route and current frame:

the route id is the path relative to the last `simlingo` directory component,

so `simlingo_data/data/simlingo/<...>` (DriveVLA) and

`database/simlingo/data/simlingo/<...>` (simlingoCODE) resolve to identical ids.



Differences vs the original:

- `index_manifest_sha256` defaults to None (the pinned hash belongs to the J1

  b0 dataset manifest which does not apply to DriveVLA's sampling); teacher

  revision/sha256 pins are kept.

"""

from __future__ import annotations

from collections import OrderedDict
import hashlib
import json
import os
from pathlib import Path
from typing import Dict, Optional, Tuple

import numpy as np
import torch


CACHE_SCHEMA_VERSION = 2
TEACHER_REVISION = "b3c1679b7c34d3255ef3547f27c7b226aefab26f"
TEACHER_SHA256 = "25466aef85727d16546c6cf8c99f12fcfad9cbca8225d45f23685e2e025b786b"
STATE_SHAPE = (4, 64, 1024)
STATE_DTYPE = np.dtype("float16")
CLIP_OFFSETS = tuple(range(8))


def sha256_file(path: Path, chunk_size: int = 16 * 1024 * 1024) -> str:
    digest = hashlib.sha256()
    with path.open("rb") as handle:
        for chunk in iter(lambda: handle.read(chunk_size), b""):
            digest.update(chunk)
    return digest.hexdigest()


def canonical_route_id(measurement_path: str | os.PathLike) -> str:
    """Return a host-independent route id from ``.../route/measurements/NNNN``."""

    path = Path(os.fsdecode(measurement_path))
    route = path.parent.parent if path.suffix else path.parent
    parts = route.parts
    simlingo_positions = [index for index, part in enumerate(parts) if part == "simlingo"]
    if simlingo_positions:
        relative = parts[simlingo_positions[-1] + 1 :]
        if relative:
            return Path(*relative).as_posix()
    # This fallback is deterministic for synthetic tests and unusual mirrors;
    # formal cache generation records the resulting absolute id in metadata.
    return route.resolve().as_posix().lstrip("/")


def route_hash(route_id: str) -> str:
    return hashlib.sha256(route_id.encode("utf-8")).hexdigest()[:16]


def measurement_frame_index(measurement_path: str | os.PathLike) -> int:
    name = Path(os.fsdecode(measurement_path)).name
    # Handles both 0010.json.gz and a synthetic 0010 path.
    token = name.split(".", 1)[0]
    if not token.isdigit():
        raise ValueError(f"measurement filename does not contain a frame index: {name}")
    return int(token)


def cache_identity(measurement_path: str | os.PathLike) -> Tuple[str, int]:
    return route_hash(canonical_route_id(measurement_path)), measurement_frame_index(
        measurement_path
    )


class FutureStateCache:
    """Per-process LRU of route-level read-only numpy memory maps."""

    def __init__(

        self,

        root: str | os.PathLike,

        *,

        schema_version: int = CACHE_SCHEMA_VERSION,

        teacher_revision: str = TEACHER_REVISION,

        teacher_sha256: str = TEACHER_SHA256,

        index_manifest_sha256: Optional[str] = None,

        require: bool = True,

        allow_missing: bool = False,

        min_coverage: float = 0.999,

        lru_size: int = 8,

    ) -> None:
        self.root = Path(root)
        self.require = bool(require)
        self.allow_missing = bool(allow_missing)
        self.lru_size = int(lru_size)
        if self.lru_size <= 0:
            raise ValueError("future cache lru_size must be positive")
        manifest_path = self.root / "manifest.json"
        if not manifest_path.is_file():
            raise FileNotFoundError(f"future cache manifest is missing: {manifest_path}")
        with manifest_path.open("r", encoding="utf-8") as handle:
            self.manifest = json.load(handle)
        self._validate_manifest(
            schema_version=schema_version,
            teacher_revision=teacher_revision,
            teacher_sha256=teacher_sha256,
            index_manifest_sha256=index_manifest_sha256,
            min_coverage=min_coverage,
        )
        self.routes: Dict[str, Dict] = self.manifest["routes"]
        self._pid = os.getpid()
        self._handles: OrderedDict[str, Tuple[np.ndarray, np.ndarray, np.ndarray]] = (
            OrderedDict()
        )

    def _validate_manifest(

        self,

        *,

        schema_version: int,

        teacher_revision: str,

        teacher_sha256: str,

        index_manifest_sha256: Optional[str],

        min_coverage: float,

    ) -> None:
        manifest = self.manifest
        expected = {
            "schema_version": int(schema_version),
            "state_shape": list(STATE_SHAPE),
            "dtype": str(STATE_DTYPE),
            "clip_offsets": list(CLIP_OFFSETS),
        }
        for key, value in expected.items():
            if manifest.get(key) != value:
                raise RuntimeError(
                    f"future cache manifest {key} mismatch: {manifest.get(key)!r} != {value!r}"
                )
        teacher = manifest.get("teacher", {})
        if teacher.get("revision") != teacher_revision:
            raise RuntimeError("future cache teacher revision mismatch")
        if teacher.get("model_sha256") != teacher_sha256:
            raise RuntimeError("future cache teacher hash mismatch")
        if index_manifest_sha256 is not None and manifest.get("source", {}).get(
            "index_manifest_sha256"
        ) != index_manifest_sha256:
            raise RuntimeError("future cache pinned index manifest hash mismatch")
        if not isinstance(manifest.get("routes"), dict):
            raise RuntimeError("future cache manifest has no route mapping")
        if self.require:
            coverage_info = manifest.get("coverage", {})
            coverage = float(coverage_info.get("valid_fraction", -1.0))
            structurally_complete = (
                bool(coverage_info.get("passed", False))
                and int(coverage_info.get("missing_route_count", -1)) == 0
                and int(coverage_info.get("route_count", -1))
                == int(coverage_info.get("expected_route_count", -2))
                and int(coverage_info.get("sample_count", -1))
                == int(coverage_info.get("expected_sample_count", -2))
            )
            if not structurally_complete:
                raise RuntimeError("future cache manifest is not structurally complete")
            if coverage < float(min_coverage):
                raise RuntimeError(
                    f"future cache valid coverage {coverage:.6f} is below {min_coverage:.6f}"
                )

    @staticmethod
    def _close_handles(handles) -> None:
        for arrays in handles.values():
            for array in arrays:
                mmap = getattr(array, "_mmap", None)
                if mmap is not None:
                    mmap.close()

    def _reset_after_fork(self) -> None:
        if self._pid != os.getpid():
            self._handles = OrderedDict()
            self._pid = os.getpid()

    def _open_route(self, key: str) -> Optional[Tuple[np.ndarray, np.ndarray, np.ndarray]]:
        self._reset_after_fork()
        if key in self._handles:
            self._handles.move_to_end(key)
            return self._handles[key]
        entry = self.routes.get(key)
        if entry is None:
            return None
        route_dir = self.root / key
        metadata_path = route_dir / "metadata.json"
        if not metadata_path.is_file():
            raise RuntimeError(f"future cache route metadata is missing: {key}")
        expected_metadata_hash = entry.get("metadata_sha256")
        if not expected_metadata_hash or sha256_file(metadata_path) != expected_metadata_hash:
            raise RuntimeError(f"future cache route metadata hash mismatch: {key}")
        with metadata_path.open("r", encoding="utf-8") as handle:
            metadata = json.load(handle)
        if metadata.get("route_hash") != key or metadata.get("route_id") != entry.get("route_id"):
            raise RuntimeError(f"future cache route identity mismatch: {key}")
        states = np.load(route_dir / "states.npy", mmap_mode="r", allow_pickle=False)
        valid = np.load(route_dir / "valid.npy", mmap_mode="r", allow_pickle=False)
        frames = np.load(route_dir / "frame_index.npy", mmap_mode="r", allow_pickle=False)
        count = int(entry["count"])
        if states.shape != (count, *STATE_SHAPE) or states.dtype != STATE_DTYPE:
            raise RuntimeError(f"future cache states schema mismatch: {key}")
        if valid.shape != (count,) or valid.dtype != np.bool_:
            raise RuntimeError(f"future cache validity schema mismatch: {key}")
        if frames.shape != (count,) or frames.dtype != np.int32:
            raise RuntimeError(f"future cache frame index schema mismatch: {key}")
        if count > 1 and not bool(np.all(frames[:-1] < frames[1:])):
            raise RuntimeError(f"future cache frame indexes are not strictly sorted: {key}")
        self._handles[key] = (states, valid, frames)
        while len(self._handles) > self.lru_size:
            _, arrays = self._handles.popitem(last=False)
            self._close_handles({"evicted": arrays})
        return self._handles[key]

    def get(self, key: str, frame_index: int) -> Tuple[torch.Tensor, bool]:
        arrays = self._open_route(str(key))
        if arrays is None:
            if self.allow_missing:
                return torch.zeros(STATE_SHAPE, dtype=torch.float16), False
            raise KeyError(f"route {key} is absent from the future cache")
        states, valid, frames = arrays
        position = int(np.searchsorted(frames, int(frame_index)))
        if position >= len(frames) or int(frames[position]) != int(frame_index):
            if self.allow_missing:
                return torch.zeros(STATE_SHAPE, dtype=torch.float16), False
            raise KeyError(f"frame {frame_index} is absent from future cache route {key}")
        if not bool(valid[position]):
            return torch.zeros(STATE_SHAPE, dtype=torch.float16), False
        # Copy one sample, never the route. This avoids exposing a read-only
        # numpy mmap through a writable torch Tensor.
        state = torch.from_numpy(np.asarray(states[position]).copy())
        if state.shape != STATE_SHAPE or not bool(torch.isfinite(state).all()):
            raise RuntimeError(f"non-finite or malformed future state at {key}:{frame_index}")
        return state, True

    def close(self) -> None:
        self._close_handles(self._handles)
        self._handles.clear()

    def __del__(self):  # pragma: no cover - interpreter shutdown is nondeterministic
        try:
            self.close()
        except Exception:
            pass