Reduce Model Lab replay overhead

This commit is contained in:
firestar5683
2026-11-15 18:17:10 -06:00
parent 098deaf3fd
commit d021cb21a0
7 changed files with 541 additions and 2 deletions
@@ -0,0 +1,63 @@
from collections import OrderedDict
from contextlib import contextmanager
from threading import RLock
import weakref
class WeakLayoutMemo:
def __init__(self, original, capacity=1024):
if capacity < 1:
raise ValueError('Layout cache must be bounded and nonempty')
self.original = original
self.capacity = capacity
self.entries = OrderedDict()
self.lock = RLock()
self.hits = self.misses = 0
self.owner = weakref.ref(self)
def __call__(self, node):
owner = self.owner
def removed(key):
if (cache := owner()) is not None:
with cache.lock:
cache.entries.pop(key, None)
key = weakref.ref(node, removed)
with self.lock:
if key in self.entries:
entry = self.entries[key]
if entry is None:
self.entries.move_to_end(key)
self.hits += 1
return None
base, offset = entry
if (resolved := base()) is not None:
self.entries.move_to_end(key)
self.hits += 1
return resolved, offset
del self.entries[key]
self.misses += 1
result = self.original(node)
self.entries[key] = None if result is None else (weakref.ref(result[0]), result[1])
if len(self.entries) > self.capacity:
self.entries.popitem(last=False)
return result
def clear(self):
with self.lock:
self.entries.clear()
@contextmanager
def installed(self):
from tinygrad.uop.ops import UOp
if UOp.contiguous_view is not self.original:
yield
return
memo = self
def replay(self):
return memo(self)
UOp.contiguous_view = replay
try:
yield
finally:
if UOp.contiguous_view is replay:
UOp.contiguous_view = self.original
@@ -0,0 +1,73 @@
from collections import OrderedDict
from tinygrad.tensor import Tensor
from tinygrad.engine import jit as jit_module
from tinygrad.helpers import disable_gc
class AdmittedReplay:
"""Reuse validated bindings only while the exact captured graph and input UOps remain unchanged."""
def __init__(self, jit):
self.jit = jit
self.cache = OrderedDict()
self.epoch = None
def __getattr__(self, name):
return getattr(self.jit, name)
def clear(self):
self.cache.clear()
self.epoch = None
def reset(self):
self.clear()
return self.jit.reset()
@disable_gc()
def __call__(self, *args, **kwargs):
try:
return self._run(*args, **kwargs)
except Exception:
self.clear()
raise
def _run(self, *args, **kwargs):
captured = self.jit.captured
epoch = (captured, captured._linear) if captured is not None else None
if self.epoch is None or epoch is None or any(a is not b for a, b in zip(epoch, self.epoch, strict=True)):
self.clear()
self.epoch = epoch
if (args or not kwargs or any(value.__class__ is not Tensor for value in kwargs.values()) or
captured is None or self.jit.cnt < 2 or not jit_module.JIT or jit_module.capturing):
return self.jit(*args, **kwargs)
ordered = tuple(sorted(kwargs.items()))
key = tuple((name, id(value), id(value.uop)) for name, value in ordered)
if (entry := self.cache.get(key)) is not None:
tensors, uops, names, info, inputs, variables = entry
if (tuple(captured.expected_names) == names and tuple(captured.expected_input_info) == info and
all(value is old and value.uop is uop and uop.is_realized
for (_, value), old, uop in zip(ordered, tensors, uops, strict=True))):
self.cache.move_to_end(key)
result = captured(inputs, variables)
self.jit.cnt += 1
return result
del self.cache[key]
result = self.jit(*args, **kwargs)
inputs, variables, names, info = jit_module._prepare_jit_inputs((), kwargs)
if not variables and self.jit.captured is captured and captured.expected_names == names and captured.expected_input_info == info:
self.cache[key] = (tuple(value for _, value in ordered), tuple(value.uop for _, value in ordered),
tuple(names), tuple(info), inputs, variables)
if len(self.cache) > 32:
self.cache.popitem(last=False)
return result
def enable_replay(model):
replays = []
for name in ('warp_enqueue', 'run_policy'):
jit = getattr(model, name)
if type(jit) is jit_module._TinyJit:
replay = AdmittedReplay(jit)
setattr(model, name, replay)
replays.append(replay)
model._laboratory_replays = tuple(replays)
@@ -1,4 +1,5 @@
from collections.abc import Callable
from contextlib import nullcontext
from dataclasses import dataclass
from pathlib import Path
@@ -57,8 +58,20 @@ class LaboratoryPair:
self.chestnut = True
self.model_id = f"{lateral.model_id}+{longitudinal.model_id}"
self._last_outputs = None
self._layout_cache = None
def _clear_replays(self):
if self._layout_cache is not None:
self._layout_cache.clear()
for model in (self.lateral, self.longitudinal):
for replay in getattr(model, "_laboratory_replays", ()):
replay.clear()
def run(self, bufs, transforms, inputs, after_enqueue=None):
with self._layout_cache.installed() if self._layout_cache is not None else nullcontext():
return self._run(bufs, transforms, inputs, after_enqueue)
def _run(self, bufs, transforms, inputs, after_enqueue=None):
if self.failed:
raise RuntimeError("Model Laboratory pair failed; load a fallback before continuing")
try:
@@ -74,6 +87,7 @@ class LaboratoryPair:
self._last_outputs = lateral, longitudinal
return compose_model_outputs(lateral, longitudinal)
except Exception:
self._clear_replays()
self.failed = True
self.lateral.last_warp = self.longitudinal.last_warp = None
raise
@@ -89,6 +103,7 @@ class LaboratoryPair:
for value, model in zip(self._last_outputs, (self.lateral, self.longitudinal), strict=True)]
return log.ModelDataV2.Action(**hybrid_action_values(*actions))
except Exception:
self._clear_replays()
self.failed = True
raise
@@ -110,6 +125,7 @@ class LaboratoryPair:
return LaboratoryFrame(composed, action,
(self.lateral_role, self.longitudinal_role))
except Exception:
self._clear_replays()
self.failed = True
self.lateral.last_warp = self.longitudinal.last_warp = None
raise
@@ -139,5 +155,13 @@ def load_laboratory_pair(cam_w: int, cam_h: int, config: dict, *, root: Path = R
source.get('_source_contract') is None else None)
loaded.append(load_verified_model(cam_w, cam_h, Path(role['path']), role['version'], role['chestnut'],
role['model_id'], role['sha256'], root=root, coherent_warp=coherent))
if coherent is not None:
from openpilot.starpilot.models.laboratory_replay import enable_replay
enable_replay(loaded[-1][0])
contracts.append(role['source_contract'])
return LaboratoryPair(loaded[0][0], loaded[1][0], loaded[0][1], loaded[1][1], tuple(contracts))
pair = LaboratoryPair(loaded[0][0], loaded[1][0], loaded[0][1], loaded[1][1], tuple(contracts))
if all(source.get('artifact_format') == LEGACY_ABI and source.get('_source_contract') is None for source in contracts):
from tinygrad.uop.ops import UOp
from openpilot.starpilot.models.laboratory_layout import WeakLayoutMemo
pair._layout_cache = WeakLayoutMemo(UOp.contiguous_view)
return pair
+2
View File
@@ -224,6 +224,8 @@ class CatalogModelState:
self.warp_copied = None
def _reset_state(self) -> None:
for replay in getattr(self, "_laboratory_replays", ()):
replay.clear()
from openpilot.starpilot.models.compile import make_stateful_input_queues, make_supercombo_input_queues, make_split_input_queues
if self.onnx_history:
@@ -0,0 +1,179 @@
from concurrent.futures import ThreadPoolExecutor
from contextlib import contextmanager
from functools import lru_cache
import gc
import time
import unittest
import weakref
import numpy as np
from tinygrad import Tensor
from tinygrad.uop.ops import UOp
from openpilot.starpilot.models.laboratory_layout import WeakLayoutMemo
ORIGINAL = UOp.contiguous_view
@contextmanager
def installed(cache):
def replay(self):
return cache(self)
UOp.contiguous_view = replay
try:
yield
finally:
UOp.contiguous_view = ORIGINAL
class TestWeakLayout(unittest.TestCase):
def test_real_view_layouts_match_original(self):
cache = WeakLayoutMemo(ORIGINAL)
base = Tensor(np.arange(256, dtype=np.float32).reshape(16, 16), device='NPY').realize()
views = [base, base.reshape(256), base[1:8], base.reshape(256)[3:91], base.transpose(), base[:, ::2]]
for view in views:
expected = ORIGINAL(view.uop)
for _ in range(3):
actual = cache(view.uop)
self.assertEqual(actual, expected)
if actual is not None:
assert expected is not None
self.assertIs(actual[0], expected[0])
self.assertGreater(cache.hits, 0)
def test_storage_rebind_is_fresh(self):
cache = WeakLayoutMemo(ORIGINAL)
base = Tensor(np.arange(16, dtype=np.float32), device='NPY').realize()
view = base[2:8]
with installed(cache):
first = view.uop.buffer.ensure_allocated()
np.testing.assert_array_equal(first.numpy(), np.arange(2, 8, dtype=np.float32))
storage = base.uop.base.buffer
storage.deallocate()
storage.allocate(opaque=np.arange(16, dtype=np.float32) + 100)
second = view.uop.buffer.ensure_allocated()
self.assertIsNot(first, second)
np.testing.assert_array_equal(second.numpy(), np.arange(2, 8, dtype=np.float32) + 100)
def test_noncontiguous_buffers_still_refuse(self):
cache = WeakLayoutMemo(ORIGINAL)
view = Tensor(np.arange(32, dtype=np.float32), device='NPY').realize()[::2]
with installed(cache):
for _ in range(3):
self.assertIsNone(view.uop.contiguous_view())
with self.assertRaises(RuntimeError):
_ = view.uop.buffer
def test_capacity_is_bounded_with_live_graphs(self):
cache = WeakLayoutMemo(ORIGINAL, capacity=16)
base = Tensor(np.arange(512, dtype=np.float32), device='NPY').realize()
views = [base[i:i + 32] for i in range(100)]
for view in views:
self.assertEqual(cache(view.uop), ORIGINAL(view.uop))
self.assertEqual(len(cache.entries), 16)
self.assertEqual(cache(views[0].uop), ORIGINAL(views[0].uop))
self.assertEqual(len(cache.entries), 16)
def test_closed_graph_not_retained(self):
cache = WeakLayoutMemo(ORIGINAL)
def run():
base = Tensor(np.arange(37, dtype=np.float32), device='NPY').realize()
view = base[7:19]
cache(view.uop)
return weakref.ref(view.uop)
node = run()
gc.collect()
self.assertIsNone(node())
self.assertEqual(len(cache.entries), 0)
def test_previous_strong_cache_retains_closed_graph_until_clear(self):
cache = lru_cache(maxsize=1024)(ORIGINAL)
def run():
view = Tensor(np.arange(41, dtype=np.float32), device='NPY').realize()[3:22]
cache(view.uop)
return weakref.ref(view.uop)
node = run()
gc.collect()
self.assertIsNotNone(node())
cache.cache_clear()
gc.collect()
self.assertIsNone(node())
def test_replacement_graph_uses_current_layout(self):
cache = WeakLayoutMemo(ORIGINAL)
base = Tensor(np.arange(64, dtype=np.float32), device='NPY').realize()
before = base[1:17]
after = base[9:25]
self.assertEqual(cache(before.uop), ORIGINAL(before.uop))
self.assertEqual(cache(after.uop), ORIGINAL(after.uop))
self.assertNotEqual(cache(before.uop)[1], cache(after.uop)[1])
def test_parallel_lookups_and_eviction_preserve_results(self):
cache = WeakLayoutMemo(ORIGINAL, capacity=8)
base = Tensor(np.arange(128, dtype=np.float32), device='NPY').realize()
views = [base[i:i + 16] for i in range(16)]
expected = [ORIGINAL(view.uop) for view in views]
def read(index):
result = cache(views[index % 16].uop)
self.assertEqual(result, expected[index % 16])
with ThreadPoolExecutor(max_workers=4) as pool:
list(pool.map(read, range(300)))
self.assertLessEqual(len(cache.entries), 8)
def test_original_failures_are_not_cached(self):
def original(node):
raise RuntimeError('original refusal')
cache = WeakLayoutMemo(original)
tensor = Tensor(np.arange(4), device='NPY').realize()
for _ in range(2):
with self.assertRaisesRegex(RuntimeError, 'original refusal'):
cache(tensor.uop)
self.assertEqual(len(cache.entries), 0)
def test_layout_microbenchmark(self):
cache = WeakLayoutMemo(ORIGINAL)
base = Tensor(np.arange(4096, dtype=np.float32), device='NPY').realize()
views = [base[i:i + 128].uop for i in range(32)]
for node in views:
self.assertEqual(cache(node), ORIGINAL(node))
results = {}
for label, operation in [('original', ORIGINAL), ('weak_memo', cache)]:
began = time.perf_counter_ns()
for i in range(2000):
operation(views[i % 32])
results[label] = (time.perf_counter_ns() - began) / 2000
print('HOST_LAYOUT_NS_PER_CALL', results)
def test_product_scope_restores_original_after_failure(self):
cache = WeakLayoutMemo(ORIGINAL)
with self.assertRaisesRegex(RuntimeError, 'frame failed'):
with cache.installed():
self.assertIsNot(UOp.contiguous_view, ORIGINAL)
raise RuntimeError('frame failed')
self.assertIs(UOp.contiguous_view, ORIGINAL)
def test_product_scope_does_not_replace_foreign_hook(self):
cache = WeakLayoutMemo(ORIGINAL)
def foreign(self):
return ORIGINAL(self)
UOp.contiguous_view = foreign
try:
with cache.installed():
self.assertIs(UOp.contiguous_view, foreign)
self.assertIs(UOp.contiguous_view, foreign)
finally:
UOp.contiguous_view = ORIGINAL
def test_actual_pair_scope_and_failure_clear_metadata(self):
from openpilot.starpilot.models.tests import test_laboratory_runner as callers
pair = callers.make_pair()
cache = WeakLayoutMemo(ORIGINAL)
pair._layout_cache = cache
tensor = Tensor(np.arange(16), device='NPY').realize()
cache(tensor.uop)
self.assertTrue(cache.entries)
pair.lateral.run_policy.side_effect = RuntimeError('frame failed')
with self.assertRaisesRegex(RuntimeError, 'frame failed'):
callers.TestLaboratoryFrame.run_frame(pair)
self.assertIs(UOp.contiguous_view, ORIGINAL)
self.assertFalse(cache.entries)
@@ -0,0 +1,198 @@
import gc
from types import SimpleNamespace
import unittest
from unittest.mock import Mock, patch
import weakref
import numpy as np
from tinygrad import Tensor, TinyJit, Context
from tinygrad.engine.jit import JitError
from openpilot.starpilot.models.laboratory_replay import AdmittedReplay, enable_replay
from openpilot.starpilot.models.tests import test_laboratory_runner as pair_tests
from openpilot.starpilot.models.tests.test_shared_camera_warp import make_runner
class TestAdmittedReplay(unittest.TestCase):
@staticmethod
def ready():
x = Tensor(np.arange(8, dtype=np.float32)).realize()
jit = TinyJit(lambda x: (x + 1).realize())
jit(x=x)
jit(x=x)
replay = AdmittedReplay(jit)
replay(x=x)
return x, jit, replay
def test_current_data_is_read_on_every_cached_call(self):
x, jit, replay = self.ready()
for offset in (3, 19, -4):
x.assign(Tensor(np.arange(8, dtype=np.float32) + offset)).realize()
np.testing.assert_array_equal(replay(x=x).numpy(), np.arange(8, dtype=np.float32) + offset + 1)
self.assertEqual(len(replay.cache), 1)
self.assertEqual(jit.cnt, 6)
def test_hit_skips_only_repeated_input_preparation(self):
x, jit, replay = self.ready()
from tinygrad.engine import jit as module
with patch.object(module, '_prepare_jit_inputs', side_effect=AssertionError('metadata recomputed')):
np.testing.assert_array_equal(replay(x=x).numpy(), np.arange(8) + 1)
self.assertEqual(jit.cnt, 4)
def test_changed_inputs_preserve_original_admission_and_results(self):
values = ({'other': Tensor(np.zeros(8, dtype=np.float32)).realize()},
{'x': Tensor(np.arange(9, dtype=np.float32)).realize()},
{'x': Tensor(np.arange(8, dtype=np.int32)).realize()})
for kwargs in values:
with self.subTest(kwargs=kwargs):
_, jit, replay = self.ready()
count = jit.cnt
try:
expected = jit(**kwargs).numpy().copy()
except JitError as error:
with self.assertRaisesRegex(JitError, str(error).split(':')[0]):
replay(**kwargs)
self.assertEqual(jit.cnt, count)
self.assertEqual(len(replay.cache), 0)
else:
np.testing.assert_array_equal(replay(**kwargs).numpy(), expected)
def test_duplicate_inputs_are_still_rejected(self):
x = Tensor.ones(8).realize()
y = Tensor.zeros(8).realize()
jit = TinyJit(lambda x, y: (x + y).realize())
jit(x=x, y=y)
jit(x=x, y=y)
replay = AdmittedReplay(jit)
replay(x=x, y=y)
with self.assertRaisesRegex(JitError, 'duplicate'):
replay(x=x, y=x)
self.assertEqual(len(replay.cache), 0)
def test_replaced_uop_uses_original_validation(self):
x, jit, replay = self.ready()
x.uop = Tensor(np.arange(9, dtype=np.float32) + 17).realize().uop
from tinygrad.engine import jit as module
expected = jit(x=x).numpy().copy()
with patch.object(module, '_prepare_jit_inputs', wraps=module._prepare_jit_inputs) as prepare:
np.testing.assert_array_equal(replay(x=x).numpy(), expected)
self.assertGreaterEqual(prepare.call_count, 1)
def test_capture_replacement_invalidates_bindings(self):
x, jit, replay = self.ready()
other = TinyJit(lambda x: (x * 3).realize())
other(x=x)
other(x=x)
jit.captured = other.captured
np.testing.assert_array_equal(replay(x=x).numpy(), np.arange(8) * 3)
self.assertEqual(len(replay.cache), 1)
def test_capture_reset_uses_normal_capture_again(self):
x, jit, replay = self.ready()
replay.reset()
self.assertEqual(len(replay.cache), 0)
np.testing.assert_array_equal(replay(x=x).numpy(), np.arange(8) + 1)
self.assertEqual(len(replay.cache), 0)
self.assertEqual(jit.cnt, 1)
def test_failed_native_call_does_not_increment_or_retain_bindings(self):
x, jit, replay = self.ready()
count = jit.cnt
with patch.object(type(jit.captured), '__call__', side_effect=RuntimeError('native failure')):
with self.assertRaisesRegex(RuntimeError, 'native failure'):
replay(x=x)
self.assertEqual(jit.cnt, count)
self.assertEqual(len(replay.cache), 0)
def test_disabled_jit_and_capture_use_original_path(self):
x, jit, replay = self.ready()
with Context(JIT=0):
np.testing.assert_array_equal(replay(x=x).numpy(), np.arange(8) + 1)
with patch('tinygrad.engine.jit.capturing', [object()]):
with patch.object(type(jit), '__call__', return_value='original') as original:
self.assertEqual(replay(x=x), 'original')
original.assert_called_once()
def test_cache_is_bounded_and_clear_releases_input_tensors(self):
x, jit, replay = self.ready()
for _ in range(40):
replay(x=Tensor.ones(8).realize())
self.assertEqual(len(replay.cache), 32)
value = Tensor.ones(8).realize()
ref = weakref.ref(value)
replay(x=value)
del value
gc.collect()
self.assertIsNotNone(ref())
replay.clear()
gc.collect()
self.assertIsNone(ref())
def test_enable_only_wraps_actual_jits(self):
x, jit, replay = self.ready()
policy = Mock()
model = SimpleNamespace(warp_enqueue=jit, run_policy=policy)
enable_replay(model)
self.assertIsInstance(model.warp_enqueue, AdmittedReplay)
self.assertIs(model.run_policy, policy)
self.assertEqual(model._laboratory_replays, (model.warp_enqueue,))
def test_actual_model_reset_clears_bindings_before_new_queues(self):
model = make_runner()
cache = Mock()
model._laboratory_replays = (cache,)
old = model.input_queues
model._reset_state()
cache.clear.assert_called_once()
self.assertIsNot(model.input_queues, old)
def test_actual_pair_failure_clears_both_roles(self):
for stage in ('enqueue', 'action'):
pair = pair_tests.make_pair()
caches = [Mock(), Mock()]
pair.lateral._laboratory_replays = (caches[0],)
pair.longitudinal._laboratory_replays = (caches[1],)
if stage == 'enqueue':
pair.lateral.run_policy.side_effect = RuntimeError('policy failure')
else:
pair.longitudinal._parse.return_value['action'] = np.zeros((1, 3))
with self.assertRaises((RuntimeError, ValueError)):
pair_tests.TestLaboratoryFrame.run_frame(pair)
self.assertTrue(pair.failed)
for cache in caches:
self.assertGreaterEqual(cache.clear.call_count, 1)
def test_reallocated_input_storage_uses_current_bytes(self):
x, jit, replay = self.ready()
values = np.arange(8, dtype=np.float32) + 31
buffer = x.uop.base.buffer
buffer.deallocate()
buffer.allocate()
buffer.copy_from(Tensor(values).realize().uop.base.buffer)
np.testing.assert_array_equal(replay(x=x).numpy(), values + 1)
def test_mutated_capture_contract_is_not_hidden_by_cache(self):
x, jit, replay = self.ready()
jit.captured.expected_names = ['other']
count = jit.cnt
with self.assertRaises(JitError):
replay(x=x)
self.assertEqual(jit.cnt, count)
self.assertEqual(len(replay.cache), 0)
def test_replaced_capture_linear_invalidates_bindings(self):
x, jit, replay = self.ready()
from tinygrad.engine import jit as module
jit.captured._linear = jit.captured._linear.replace(tag='replacement')
with patch.object(module, '_prepare_jit_inputs', wraps=module._prepare_jit_inputs) as prepare:
np.testing.assert_array_equal(replay(x=x).numpy(), np.arange(8) + 1)
self.assertGreaterEqual(prepare.call_count, 1)
def test_deallocated_input_returns_to_original_admission(self):
x, jit, replay = self.ready()
x.uop.base.buffer.deallocate()
with patch.object(type(jit), '__call__', side_effect=JitError('original input admission')) as original:
with self.assertRaisesRegex(JitError, 'original input admission'):
replay(x=x)
original.assert_called_once()
self.assertEqual(len(replay.cache), 0)
+1 -1
View File
@@ -1 +1 @@
{"protected_inventory_sha256": "e5ab82265b6c98d7a8b8f8b98ef919d4ef6ae868b9da45e762ca2b1e465a05e7", "schema_version": 1}
{"protected_inventory_sha256": "f8320fbea132063837a264d2cd0b91a0baafb644d717a212eb33fdd13b0d567d", "schema_version": 1}