Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Studio: refuse Laya choice questions whose options would be cut short (#14558)

Nilay817a81810980
diff --git a/studio/backend/core/systemone/laya_runtime.py b/studio/backend/core/systemone/laya_runtime.py
index 891f3d65342..268e10c17b8 100644
--- a/studio/backend/core/systemone/laya_runtime.py
+++ b/studio/backend/core/systemone/laya_runtime.py
@@ -1649,9 +1649,19 @@ def _head(agent, question: dict[str, Any], max_len: int, head_max_len: int):
key = json.dumps(question, ensure_ascii = False)
if key not in cache:
internal = agent._to_internal(question)
- ids, markers = build_sequence(agent.tok, "", internal, max_len, head_max_len)
- if len(markers) != len(render_options(internal)):
- raise ValueError("question options exceed head_max_len=%d" % head_max_len)
+ tok = agent.tok
+ options = [" " + o.replace(tok.mask_token, " ") for o in render_options(internal)]
+ sizes = [1 + min(48, len(tok(o, add_special_tokens = False)["input_ids"])) for o in options]
+ # build_sequence's rule: past this budget, each option keeps only its share of it.
+ budget = head_max_len - 16
+ share = max(4, budget // len(sizes))
+ if sum(sizes) > budget and max(sizes) > share:
+ raise ValueError(
+ f"options would be cut short to fit Laya's {budget}-token option budget"
+ )
+ ids, markers = build_sequence(tok, "", internal, max_len, head_max_len)
+ if len(markers) != len(sizes):
+ raise ValueError(f"options exceed the Laya context window ({max_len} tokens)")
if len(cache) >= _HEAD_CACHE_SIZE:
cache.clear()
cache[key] = (ids, markers, internal)
@@ -1672,11 +1682,8 @@ def _predict(agent, state, questions: dict[str, dict[str, Any]]) -> tuple[dict[s
for name in names:
try:
heads.append(_head(agent, questions[name], max_len, head_max_len))
- except ValueError:
- raise ValueError(
- f"Question {name!r} options exceed the Laya context window ({max_len} tokens). "
- "Use fewer or shorter criteria."
- ) from None
+ except ValueError as exc:
+ raise ValueError(f"Question {name!r} {exc}. Use fewer or shorter criteria.") from None
room = max(0, max_len - min(len(ids) for ids, _, _ in heads))
state_ids, state_cut = _state_ids(agent.tok, state, room)
items, truncated = [], False
diff --git a/studio/backend/tests/test_systemone.py b/studio/backend/tests/test_systemone.py
index a5cc56c4749..2af1a194a7c 100644
--- a/studio/backend/tests/test_systemone.py
+++ b/studio/backend/tests/test_systemone.py
@@ -1169,7 +1169,7 @@ def test_real_laya_answers_through_the_route(client, monkeypatch):
)
assert options_response.status_code == 422
message = options_response.json()["detail"]["message"]
- assert "route" in message and "context window" in message and "criteria" in message
+ assert "route" in message and "cut short" in message and "criteria" in message
assert "answers" not in options_response.json()
assert _post(client).status_code == 200
@@ -1197,6 +1197,58 @@ def test_long_state_is_tokenized_only_as_far_as_the_model_reads():
assert max(tok.calls) < 100_000
+_CHARGED = "the customer was charged twice and wants the money back"
+
+
+ "options, description, status, refusal",
+ [
+ (14, _CHARGED, 200, None),
+ # 16 options of 11 tokens fill the budget exactly.
+ (16, _CHARGED.replace(" the money", " money"), 200, None),
+ (15, _CHARGED, 422, "cut short to fit Laya's 176-token option budget"),
+ (40, _CHARGED, 422, "cut short to fit Laya's 176-token option budget"),
+ (40, None, 200, None),
+ (100, None, 200, None),
+ (255, None, 422, "context window"),
+ ],
+)
+def test_choice_options_laya_would_cut_short_are_refused(
+ client, monkeypatch, options, description, status, refusal
+):
+ np = pytest.importorskip("numpy")
+ pytest.importorskip("torch")
+ tok = WordTokenizer()
+ tok.mask_token_id, tok.cls_token_id, tok.sep_token_id = 1, 2, 3
+ agent = SimpleNamespace(
+ tok = tok,
+ cfg = {"max_len": 512, "head_max_len": 192},
+ _to_internal = laya_runtime._laya().Agent._to_internal,
+ temperature = [1.0, 1.0, 1.0],
+ temperature_by_options = {},
+ )
+ monkeypatch.setattr(laya_runtime, "_load_checkpoint", lambda c: (agent, "cpu"))
+ monkeypatch.setattr(laya_runtime, "_predict", _REAL_PREDICT)
+ monkeypatch.setattr(
+ laya_runtime, "_forward", lambda agent, items: (np.zeros((len(items), 256)), 1)
+ )
+ question = {
+ "type": "choice",
+ "instructions": "Which queue should handle this ticket?",
+ "criteria": {f"team_{i}": description for i in range(options)},
+ }
+ internal = agent._to_internal(question)
+ build = laya_runtime._laya().common.build_sequence
+ cut = build(tok, "", internal, 10**6, 192)[0] != build(tok, "", internal, 10**6, 10**6)[0]
+ assert cut == ("cut short" in (refusal or ""))
+ response = _post(client, questions = {"route": question})
+ assert response.status_code == status, response.text
+ if refusal:
+ message = response.json()["detail"]["message"]
+ assert "'route'" in message and refusal in message
+ assert "answers" not in response.json()
+
+
@pytest.mark.parametrize("words, cut", [(900, False), (901, True), (5000, True)])
def test_state_cut_matches_the_full_tokenization(words, cut):
pytest.importorskip("torch")
diff --git a/tests/test_moe_autotune_cache_validate.py b/tests/test_moe_autotune_cache_validate.py
index b3df981d187..621718ce413 100644
--- a/tests/test_moe_autotune_cache_validate.py
+++ b/tests/test_moe_autotune_cache_validate.py
@@ -65,9 +65,10 @@ def _configs(fwd, dx, dw):
KernelConfigBackward_dX,
KernelConfigForward,
)
-
def kw(t):
- return dict(zip(("BLOCK_SIZE_M", "BLOCK_SIZE_N", "BLOCK_SIZE_K", "num_warps", "num_stages"), t))
+ return dict(
+ zip(("BLOCK_SIZE_M", "BLOCK_SIZE_N", "BLOCK_SIZE_K", "num_warps", "num_stages"), t)
+ )
return (
KernelConfigForward(**kw(fwd)),
@@ -93,7 +94,12 @@ class _Autotune:
return _configs(SMALL, SMALL, SMALL)
-def _legacy_key(dims, dtype = torch.bfloat16, capability = (8, 6), seq_len = 8192):
+def _legacy_key(
+ dims,
+ dtype = torch.bfloat16,
+ capability = (8, 6),
+ seq_len = 8192,
+):
key_data = dict(
num_experts = dims["num_experts"],
hidden_dim = dims["hidden_dim"],
@@ -123,9 +129,7 @@ def test_legacy_unversioned_cache_file_is_ignored(ac, monkeypatch):
payload = _legacy_payload(legacy)
cache_dir = Path(ac._get_cache_file_path("x")).parent
legacy_file = cache_dir / f"{_legacy_key(DIMS)}.json"
- current_key = ac._get_cache_key(
- dtype = torch.bfloat16, device_capability = (8, 6), **DIMS
- )
+ current_key = ac._get_cache_key(dtype = torch.bfloat16, device_capability = (8, 6), **DIMS)
for path in {legacy_file, Path(ac._get_cache_file_path(current_key))}:
path.write_text(json.dumps(payload), encoding = "utf-8")