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.

docs(shortlist): name the non-finite row that cached_embed_fn stores

aashish254ac0e68a7da46
diff --git a/laya/shortlist.py b/laya/shortlist.py
index 67d1030c..4cf8a0e6 100644
--- a/laya/shortlist.py
+++ b/laya/shortlist.py
@@ -300,15 +300,22 @@ def cached_embed_fn(
embed_fn = cached_embed_fn(embed_fn_from_agent(agent))
- leaves the first call unchanged and reduces each repeat call to embedding the new
- query alone.
+ leaves the first call's embedder work unchanged and reduces each repeat call to
+ embedding the new query alone.
Lookups are exact string matches. Texts missing from the cache are deduplicated and
embedded in a single ``embed_fn`` call, so a cold cache costs the same number of
batched calls as the unwrapped function. Rows are stored as float32; the cache holds
at most ``maxsize`` strings and then evicts the least recently used entry, bounding
memory at about ``maxsize * dim * 4`` bytes. Nothing is cached when ``embed_fn``
- raises or returns a bad shape.
+ raises or returns a bad shape. A non-finite value is not a bad shape: ``NaN``,
+ ``inf`` and ``-inf`` become ``0.0`` on the way in, the same replacement
+ :func:`_embeddings` makes for an unwrapped embedder, and the repaired row is then
+ *cached*. One transient ``NaN`` in an option's embedding therefore ranks that option
+ as a zero vector on every later request until ``cache_clear()``, while the unwrapped
+ embedder would simply re-embed it -- shortlist membership can differ between the two
+ on the second call. The float32 storage shows in the scores too: a wrapped first
+ call can differ from the unwrapped one in its last digits.
The wrapper is safe to share between threads: the lock covers only cache reads and
writes, never the embedding call. The returned callable carries ``cache_info()`` --
diff --git a/tests/test_shortlist.py b/tests/test_shortlist.py
index d62329da..128f3db8 100644
--- a/tests/test_shortlist.py
+++ b/tests/test_shortlist.py
@@ -658,6 +658,53 @@ check_raises("cache/bad shape raises", lambda: bad_cached(["alpha", "beta"]))
check("cache/bad shape caches nothing", bad_cached.cache_info()["size"], 0)
+class NonFiniteEmbed:
+ """`alpha` embeds NaN on the first call and the query vector on every later one.
+
+ A transient NaN is the case the "bad shape" pair above does not cover: the row is
+ shape-valid, so it is not refused -- `nan_to_num` rewrites it to zeros on the way in,
+ exactly as `_embeddings` does for an unwrapped embedder. The difference is that the
+ wrapper then *stores* the repaired row, so the rewrite outlives the call that caused
+ it, while the unwrapped path re-embeds and recovers on its own.
+ """
+
+ def __init__(self):
+ self.calls = []
+
+ def __call__(self, texts):
+ self.calls.append(list(texts))
+ first = len(self.calls) == 1
+ return [[float("nan"), float("nan")] if (first and text == "alpha")
+ else ([1.0, 0.0] if text in ("pay me", "alpha") else [0.8, 0.2])
+ for text in texts]
+
+
+nf_embed = NonFiniteEmbed()
+nf_cached = cached_embed_fn(nf_embed)
+check_true("cache/non-finite row is stored, not refused",
+ np.array_equal(nf_cached(["alpha"])[0], [0.0, 0.0]) and nf_cached.cache_info()["size"] == 1)
+nf_cached(["alpha"]) # served from the cache, so still the repaired row
+check("cache/repaired row is sticky", len(nf_embed.calls), 1)
+nf_cached.cache_clear()
+check_true("cache/clear drops the repaired row", np.allclose(nf_cached(["alpha"]), [[1.0, 0.0]]))
+
+# The consequence a caller actually sees: shortlist membership, not just the numbers.
+NF_CRITERIA = {"alpha": None, "beta": None}
+raw_embed = NonFiniteEmbed()
+raw = (shortlist_choice("pay me", NF_CRITERIA, raw_embed, k=1),
+ shortlist_choice("pay me", NF_CRITERIA, raw_embed, k=1))
+wrapped_embed = NonFiniteEmbed()
+wrapped_fn = cached_embed_fn(wrapped_embed)
+sticky = (shortlist_choice("pay me", NF_CRITERIA, wrapped_fn, k=1),
+ shortlist_choice("pay me", NF_CRITERIA, wrapped_fn, k=1))
+check("cache/unwrapped second call recovers the finite row", raw, (["beta"], ["alpha"]))
+check("cache/wrapped second call keeps the zeroed row", sticky, (["beta"], ["beta"]))
+check("cache/wrapped ranking embedded once", len(wrapped_embed.calls), 1)
+wrapped_fn.cache_clear()
+check("cache/clearing it restores the unwrapped ranking",
+ shortlist_choice("pay me", NF_CRITERIA, wrapped_fn, k=1), ["alpha"])
+
+
class FakeTensor:
"""Mimics the detach().float().cpu().numpy() chain of a torch tensor."""