Skip to content

armgit / laya

Public Imported from GitHub
0

Non-autoregressive System 1 decision engine. Typed choice, score and yes/no decisions over any text in a single forward pass, in 100+ languages, with a router that picks the right checkpoint per request.

feat(router): let LAYA_SHA256_DIGESTS name each checkpoint

Aashish9655978c75f9
diff --git a/laya/router.py b/laya/router.py
index f9021143..58772c00 100644
--- a/laya/router.py
+++ b/laya/router.py
@@ -174,6 +174,47 @@ def _english_from_code(value: Any) -> Optional[bool]:
return primary in _ENGLISH_SUBTAGS
+def _digests_from_env(models: Dict[str, Any]) -> Dict[str, Optional[Dict[str, str]]]:
+ """Turn `LAYA_SHA256_DIGESTS` into per-checkpoint digest maps when it names models.
+
+ The variable has two shapes, and the value types say which. A flat
+ `{artifact: digest}` map is `laya.revisions.verify_digests`'s own reading -- the same
+ files checked on every checkpoint the process loads -- and is returned as `{}` here so
+ that path stays untouched. A nested `{model: {artifact: digest}}` map pins each
+ checkpoint with its own files, which is what a server holding several resident needs:
+ the bundled repository ships a separate `model.safetensors` per checkpoint, so one flat
+ map can only ever match one of them and refuses the rest at startup.
+
+ A checkpoint the nested map does not name is returned as `{}`, meaning deliberately
+ unpinned: `Agent` falls back to the environment when given `None`, and reading a
+ model-keyed map as an artifact map fails with `cannot verify 'english': no such file`.
+ Keys are normalised exactly as `Router(sha256_digests=...)` normalises them, so `en`
+ names `english` and a name core does not know raises here rather than quietly leaving
+ that checkpoint unverified. Unset, empty or unparseable input returns `{}`:
+ `laya.revisions` reports a malformed value in its own words.
+ """
+ raw = os.environ.get("LAYA_SHA256_DIGESTS", "").strip()
+ if not raw:
+ return {}
+ try:
+ data = json.loads(raw)
+ except ValueError:
+ return {}
+ if not isinstance(data, dict) or not data:
+ return {}
+ values = list(data.values())
+ if all(isinstance(v, str) for v in values):
+ return {} # flat: laya.revisions already applies it
+ if not all(isinstance(v, dict) for v in values):
+ raise ValueError("LAYA_SHA256_DIGESTS must be either {artifact: digest} for every "
+ "checkpoint or {model: {artifact: digest}} per checkpoint; %s mixes "
+ "the two or holds a value that is neither" % sorted(data))
+ per_model = {normalise_name(k): v for k, v in data.items()}
+ for name in models:
+ per_model.setdefault(normalise_name(name), {})
+ return per_model
+
+
class Router(HookRegistry):
"""Lazily loads Laya checkpoints and sends each request to the right one.
@@ -207,14 +248,21 @@ class Router(HookRegistry):
which is useful when standalone repositories were reviewed at different commits.
Without either, huggingface_hub's normal default and existing offline cache are used.
- Artifact digests are opt-in and only ever per model: `sha256_digests={"english": {...}}`
+ Artifact digests are opt-in and always per model: `sha256_digests={"english": {...}}`
passes that `{path relative to the checkpoint dir: hexdigest}` map to the `Agent` that
loads it, so a tampered or substituted weight file is refused before it is parsed. There
is no Router-wide equivalent of `revision` because digests, unlike a commit SHA, are not
shareable: the bundled repository ships a separate `model.safetensors` for each of
`english`, `multilingual` and `typed-decisions`, so one flat map can only ever match one
- of them. A model listed with `None` or `{}` is loaded unverified, which also masks the
- `LAYA_SHA256_DIGESTS` environment default for that one checkpoint.
+ of them. A model listed with `None` or `{}` is loaded unverified.
+
+ The same split is available to a process configured only by environment: when
+ `LAYA_SHA256_DIGESTS` holds a model-keyed map (`{"english": {...}, "multilingual": {...}}`)
+ this seeds it per checkpoint, so a server that keeps several resident can pin each with its
+ own digests instead of refusing to start on the second one. A flat `LAYA_SHA256_DIGESTS`
+ keeps its existing meaning, applied by `laya.revisions` to every checkpoint the process
+ loads, which is right for a single-checkpoint one. An argument entry wins over the
+ environment for the model it names.
Hooks are opt-in and run at the Router level: `on_route` sees the routing decision,
`on_load` / `on_evict` see model lifecycle, and `on_predict_start` / `on_predict_end`
@@ -267,11 +315,14 @@ class Router(HookRegistry):
self.revisions: Dict[str, Optional[str]] = {
normalise_name(k): v for k, v in (revisions or {}).items()
}
- # Per checkpoint SHA-256 map. Keyed and normalised exactly like `revisions`, so a
- # misspelled model name fails here rather than leaving that checkpoint unverified.
- self.sha256_digests: Dict[str, Optional[Dict[str, str]]] = {
+ # Per checkpoint SHA-256 map: seeded from a model-named `LAYA_SHA256_DIGESTS`, then
+ # overridden checkpoint by checkpoint by the argument. Keyed and normalised exactly like
+ # `revisions`, so a misspelled model name fails here rather than leaving that checkpoint
+ # unverified.
+ self.sha256_digests: Dict[str, Optional[Dict[str, str]]] = _digests_from_env(self.models)
+ self.sha256_digests.update({
normalise_name(k): v for k, v in (sha256_digests or {}).items()
- }
+ })
self.max_loaded = max(1, int(max_loaded))
self.default = normalise_name(default)
self.auto_task_detection = bool(auto_task_detection)
diff --git a/tests/test_revision_pinning.py b/tests/test_revision_pinning.py
index e113a4bf..b2aa6ce6 100644
--- a/tests/test_revision_pinning.py
+++ b/tests/test_revision_pinning.py
@@ -293,6 +293,119 @@ class RouterDigestEndToEndTests(unittest.TestCase):
with patch.dict(os.environ, env):
self._assert_past_the_digest_gate(router, "multilingual")
+ def test_nested_environment_pins_both_checkpoints(self):
+ """The shape a server with two resident checkpoints has to write.
+
+ Before this, `LAYA_SHA256_DIGESTS` was read only by `laya.revisions`, which treats every
+ key as a path -- so a model-named map failed with `cannot verify 'english': no such file`
+ on the *first* checkpoint and the flat map refused the second one.
+ """
+ with self._env({"english": {"model.safetensors": self.digests["english"]},
+ "multilingual": {"model.safetensors": self.digests["multilingual"]}}):
+ router = self._router({})
+ self._assert_past_the_digest_gate(router, "english")
+ self._assert_past_the_digest_gate(router, "multilingual")
+
+ def test_nested_environment_fails_only_the_checkpoint_it_calls_out(self):
+ with self._env({"english": {"model.safetensors": self.digests["english"]},
+ "multilingual": {"model.safetensors": "0" * 64}}):
+ router = self._router({})
+ self._assert_past_the_digest_gate(router, "english")
+ with self.assertRaises(ValueError) as cm:
+ router.load("multilingual")
+ self.assertIn("SHA-256 mismatch", str(cm.exception))
+
+ def test_nested_environment_leaves_an_unnamed_checkpoint_unpinned(self):
+ # `multilingual` is a resident model that the map does not name. It has to be loaded
+ # unverified, not handed the model-named map as if "english" were one of its files.
+ with self._env({"english": {"model.safetensors": self.digests["english"]}}):
+ router = self._router({})
+ self._assert_past_the_digest_gate(router, "english")
+ self._assert_past_the_digest_gate(router, "multilingual")
+
+ def _env(self, per_model):
+ return patch.dict(os.environ, {"LAYA_SHA256_DIGESTS": json.dumps(per_model)})
+
+
+class RouterEnvDigestTests(unittest.TestCase):
+ """How `Router` reads the two shapes of `LAYA_SHA256_DIGESTS`.
+
+ `serve.build_router()` builds its Router from the environment and nothing else, so the
+ environment is the only channel a container, a compose stack or a `services.laya-serve`
+ host has. These pin down which shape `Router` takes over and which it leaves to
+ `laya.revisions`, without weights: the `Agent` builds are captured, not run.
+ """
+
+ ENGLISH = {"model.safetensors": "a" * 64}
+ MULTI = {"model.safetensors": "b" * 64}
+
+ def _capture(self):
+ import laya.agent
+
+ captured: list = []
+
+ class FakeAgent:
+ def __init__(self, repo, **kwargs):
+ captured.append(kwargs)
+
+ return patch.object(laya.agent, "Agent", FakeAgent), captured
+
+ def _env(self, value):
+ return patch.dict(os.environ, {"LAYA_SHA256_DIGESTS": value})
+
+ def test_flat_map_is_left_to_revisions(self):
+ with self._env(json.dumps({"model.safetensors": "a" * 64})):
+ router = Router()
+ self.assertEqual(router.sha256_digests, {})
+ capture, captured = self._capture()
+ with capture:
+ router.load("english")
+ self.assertNotIn("expected_sha256", captured[0])
+
+ def test_nested_map_is_split_per_checkpoint(self):
+ with self._env(json.dumps({"english": self.ENGLISH, "multilingual": self.MULTI})):
+ capture, captured = self._capture()
+ with capture:
+ router = Router()
+ self.assertEqual(sorted(router.sha256_digests),
+ ["english", "multilingual", "typed-decisions"])
+ for name in ("english", "multilingual", "typed-decisions"):
+ router.load(name)
+ self.assertEqual(captured[0]["expected_sha256"], self.ENGLISH)
+ self.assertEqual(captured[1]["expected_sha256"], self.MULTI)
+ # Named by neither the map nor the caller: explicitly unpinned, so `Agent` does not
+ # fall back to an environment value keyed by model names.
+ self.assertEqual(captured[2]["expected_sha256"], {})
+
+ def test_nested_map_keys_are_normalised(self):
+ with self._env(json.dumps({"en": self.ENGLISH})):
+ self.assertEqual(Router().sha256_digests["english"], self.ENGLISH)
+
+ def test_argument_wins_for_the_checkpoint_it_names(self):
+ with self._env(json.dumps({"english": self.ENGLISH, "multilingual": self.MULTI})):
+ router = Router(sha256_digests={"english": {"model.safetensors": "c" * 64}})
+ self.assertEqual(router.sha256_digests["english"], {"model.safetensors": "c" * 64})
+ self.assertEqual(router.sha256_digests["multilingual"], self.MULTI)
+
+ def test_misspelled_key_in_the_environment_fails_at_construction(self):
+ with self._env(json.dumps({"engligh": self.ENGLISH})):
+ with self.assertRaises(ValueError):
+ Router()
+
+ def test_mixed_artifact_and_model_keys_fail_rather_than_guess(self):
+ env = json.dumps({"model.safetensors": "a" * 64, "english": self.ENGLISH})
+ with self._env(env):
+ with self.assertRaises(ValueError) as cm:
+ Router()
+ self.assertIn("LAYA_SHA256_DIGESTS", str(cm.exception))
+
+ def test_unparseable_environment_is_not_this_layers_error(self):
+ # `laya.revisions.verify_digests` owns the message a malformed value gets; a Router
+ # that repeated it would be a second copy of a rule it does not enforce.
+ for value in ("", " ", "{not json", "[]", '"digests"', "{}"):
+ with self._env(value):
+ self.assertEqual(Router().sha256_digests, {}, value)
+
if __name__ == "__main__":
unittest.main()