Skip to content

Commit c258858

Browse files
authored
perf(router): cache classifier model instead of reloading it on every request (#319)
* perf(router): cache classifier model instead of reloading it per request router_plugin.run() called load_optillm_model() on every request, which deserializes the ~400M-param ModernBERT-large base model, does a HuggingFace Hub round-trip for the fine-tuned safetensors, and rebuilds the tokenizer — all just to run a single forward pass for the routing decision. That turns an O(1 forward pass) routing step into O(load a transformer) per call. Memoize the loaded (model, tokenizer, device) bundle behind a module-level singleton guarded by a threading.Lock (double-checked locking), the same idiom already used by CacheManager in optillm/inference.py. The classifier is stateless at inference (predict_approach runs under model.eval() + torch.no_grad), so reusing the loaded objects across requests is correctness-safe. A failed load is not cached (the global is only assigned on success), so run()'s existing except-fallback still retries on the next call. Add tests/test_router_plugin_caching.py: repeated calls load the base model exactly once, the cached value is the expected (model, tokenizer, device) triple, and concurrent first-time access loads exactly once. All tests mock the heavy loaders, so they need no network or weights. * test(router): wire caching tests into CI-collected test_plugins.py The dedicated tests/test_router_plugin_caching.py was not in the unit-tests job's fixed file list in .github/workflows/test.yml, so CI never executed it. Fold the three caching tests (single-load-on-repeat, bundle shape, concurrent single-load) into tests/test_plugins.py — which the unit-tests job already runs via `pytest tests/test_plugins.py` — and drop the standalone file, so the regression is actually guarded in CI.
1 parent e5ab29e commit c258858

2 files changed

Lines changed: 142 additions & 2 deletions

File tree

‎optillm/plugins/router_plugin.py‎

Lines changed: 26 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
import threading
2+
13
import torch
24
import torch.nn as nn
35
import torch.nn.functional as F
@@ -47,12 +49,23 @@ def forward(self, input_ids, attention_mask, effort):
4749
logits = self.classifier(combined_input)
4850
return logits
4951

50-
def load_optillm_model():
52+
# Cache the loaded router model/tokenizer/device across requests. Building it is
53+
# expensive and one-time: it deserializes the ~400M-param ModernBERT-large base
54+
# model, does a HuggingFace Hub round-trip to fetch the fine-tuned safetensors, and
55+
# constructs the tokenizer. The classifier is stateless at inference time (see
56+
# predict_approach: model.eval() + torch.no_grad), so the loaded objects are safe
57+
# to reuse. The lock makes the first concurrent load run exactly once under the
58+
# threaded Flask server; subsequent calls take the lock-free fast path.
59+
_model_cache = None
60+
_model_cache_lock = threading.Lock()
61+
62+
63+
def _load_optillm_model():
5164
device = torch.device("mps" if torch.backends.mps.is_available() else "cuda" if torch.cuda.is_available() else "cpu")
5265
# Load the base model
5366
base_model = AutoModel.from_pretrained(BASE_MODEL)
5467
# Create the OptILMClassifier
55-
model = OptILMClassifier(base_model, num_labels=len(APPROACHES))
68+
model = OptILMClassifier(base_model, num_labels=len(APPROACHES))
5669
model.to(device)
5770
# Download the safetensors file
5871
safetensors_path = hf_hub_download(repo_id=OPTILLM_MODEL_NAME, filename="model.safetensors")
@@ -62,6 +75,17 @@ def load_optillm_model():
6275
tokenizer = AutoTokenizer.from_pretrained(OPTILLM_MODEL_NAME)
6376
return model, tokenizer, device
6477

78+
79+
def load_optillm_model():
80+
# Double-checked locking: return the cached bundle immediately when present,
81+
# and only serialize the very first (concurrent) load.
82+
global _model_cache
83+
if _model_cache is None:
84+
with _model_cache_lock:
85+
if _model_cache is None:
86+
_model_cache = _load_optillm_model()
87+
return _model_cache
88+
6589
def preprocess_input(tokenizer, system_prompt, initial_query):
6690
combined_input = f"{system_prompt}\n\nUser: {initial_query}"
6791
encoding = tokenizer.encode_plus(

‎tests/test_plugins.py‎

Lines changed: 116 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -428,6 +428,104 @@ def test_no_relative_import_errors():
428428
raise
429429

430430

431+
# ---------------------------------------------------------------------------
432+
# Router plugin: the classifier model must be loaded once and cached, not
433+
# reloaded on every request. These tests mock the heavy loaders so they need
434+
# no network or real weights.
435+
# ---------------------------------------------------------------------------
436+
import threading as _threading
437+
import contextlib as _contextlib
438+
from unittest import mock as _mock
439+
440+
441+
class _FakeRouterConfig:
442+
hidden_size = 768
443+
444+
445+
def _install_router_loader_mocks(stack, load_counter):
446+
"""Patch router_plugin's heavy loaders; load_counter grows once per base-model load."""
447+
from optillm.plugins import router_plugin
448+
449+
def fake_from_pretrained(*args, **kwargs):
450+
load_counter.append(1)
451+
base = _mock.MagicMock()
452+
base.config = _FakeRouterConfig()
453+
return base
454+
455+
stack.enter_context(_mock.patch.object(
456+
router_plugin.AutoModel, "from_pretrained", side_effect=fake_from_pretrained))
457+
stack.enter_context(_mock.patch.object(
458+
router_plugin, "hf_hub_download", return_value="/tmp/fake.safetensors"))
459+
stack.enter_context(_mock.patch.object(
460+
router_plugin, "load_model", return_value=None))
461+
stack.enter_context(_mock.patch.object(
462+
router_plugin.AutoTokenizer, "from_pretrained", return_value=_mock.MagicMock()))
463+
return router_plugin
464+
465+
466+
def test_router_plugin_caches_model():
467+
"""load_optillm_model() must load the base model once across repeated calls."""
468+
from optillm.plugins import router_plugin
469+
router_plugin._model_cache = None
470+
loads = []
471+
try:
472+
with _contextlib.ExitStack() as stack:
473+
_install_router_loader_mocks(stack, loads)
474+
first = router_plugin.load_optillm_model()
475+
for _ in range(5):
476+
assert router_plugin.load_optillm_model() is first, \
477+
"load_optillm_model() must return the cached bundle"
478+
assert len(loads) == 1, (
479+
f"expected exactly 1 base-model load across 6 calls, got {len(loads)} "
480+
"(model is being reloaded per request instead of cached)")
481+
finally:
482+
router_plugin._model_cache = None
483+
484+
485+
def test_router_plugin_cache_bundle_shape():
486+
"""The cached value is the (model, tokenizer, device) triple callers unpack."""
487+
from optillm.plugins import router_plugin
488+
router_plugin._model_cache = None
489+
try:
490+
with _contextlib.ExitStack() as stack:
491+
_install_router_loader_mocks(stack, [])
492+
bundle = router_plugin.load_optillm_model()
493+
assert isinstance(bundle, tuple) and len(bundle) == 3, "expected a 3-tuple bundle"
494+
model, tokenizer, device = bundle
495+
assert isinstance(model, router_plugin.OptILMClassifier)
496+
assert tokenizer is not None and device is not None
497+
finally:
498+
router_plugin._model_cache = None
499+
500+
501+
def test_router_plugin_concurrent_single_load():
502+
"""Concurrent first-time access must still load the model exactly once."""
503+
from optillm.plugins import router_plugin
504+
router_plugin._model_cache = None
505+
loads = []
506+
results = []
507+
try:
508+
with _contextlib.ExitStack() as stack:
509+
_install_router_loader_mocks(stack, loads)
510+
barrier = _threading.Barrier(8)
511+
512+
def worker():
513+
barrier.wait() # maximize contention on the first load
514+
results.append(router_plugin.load_optillm_model())
515+
516+
threads = [_threading.Thread(target=worker) for _ in range(8)]
517+
for t in threads:
518+
t.start()
519+
for t in threads:
520+
t.join()
521+
assert len(loads) == 1, (
522+
f"expected exactly 1 load under concurrency, got {len(loads)} "
523+
"(the double-checked lock is not serializing the first load)")
524+
assert all(r is results[0] for r in results), "threads saw different cached bundles"
525+
finally:
526+
router_plugin._model_cache = None
527+
528+
431529
if __name__ == "__main__":
432530
print("Running plugin tests...")
433531

@@ -455,6 +553,24 @@ def test_no_relative_import_errors():
455553
except Exception as e:
456554
print(f"❌ Memory plugin persistence test failed: {e}")
457555

556+
try:
557+
test_router_plugin_caches_model()
558+
print("✅ Router plugin model caching test passed")
559+
except Exception as e:
560+
print(f"❌ Router plugin model caching test failed: {e}")
561+
562+
try:
563+
test_router_plugin_cache_bundle_shape()
564+
print("✅ Router plugin cache bundle shape test passed")
565+
except Exception as e:
566+
print(f"❌ Router plugin cache bundle shape test failed: {e}")
567+
568+
try:
569+
test_router_plugin_concurrent_single_load()
570+
print("✅ Router plugin concurrent single-load test passed")
571+
except Exception as e:
572+
print(f"❌ Router plugin concurrent single-load test failed: {e}")
573+
458574
try:
459575
test_genselect_plugin()
460576
print("✅ GenSelect plugin test passed")

0 commit comments

Comments
 (0)