From b2cd9494012c41adea1341ea004a6ca04e5eb38f Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Wed, 2 Dec 2026 23:34:49 +0100 Subject: [PATCH] ling32: --vision-max-pixels goes with the picture flags when pictures are off or the engine reads none --- terminal/serve/ling32_kind.py | 2 +- terminal/serve/test_ling32_mtp.py | 545 +++---- terminal/strata_cli/launch/runner.py | 4 +- terminal/tests/terminal/test_ling32_launch.py | 1365 +++++++++-------- 4 files changed, 959 insertions(+), 957 deletions(-) diff --git a/terminal/serve/ling32_kind.py b/terminal/serve/ling32_kind.py index 819ed09224..9165baf3cf 100644 --- a/terminal/serve/ling32_kind.py +++ b/terminal/serve/ling32_kind.py @@ -155,7 +155,7 @@ def _vision_args(args: list, exe, cfg, announce: bool) -> list: return ling32_family.with_pixel_cap(args, backend) # a CPU-encoder backend downscales a big picture to about 1 MP (its cost grows with the patches squared) out, i = [], 0 while i < len(args): - if args[i] in ("--vision", "--vision-device"): + if args[i] in ("--vision", "--vision-device", "--vision-max-pixels"): i += 2 if i + 1 < len(args) and not str(args[i + 1]).startswith("--") else 1 continue out.append(args[i]) diff --git a/terminal/serve/test_ling32_mtp.py b/terminal/serve/test_ling32_mtp.py index d99289f24a..ea69a05e84 100644 --- a/terminal/serve/test_ling32_mtp.py +++ b/terminal/serve/test_ling32_mtp.py @@ -1,272 +1,273 @@ -"""The MTP sidecar through serve (L32-MTP: the upstream model's multi-token-prediction layer as the drafter, `--mtp FILE --spec mtp --spec-adaptive`, INFO `spec=mtp`): - -- the run config's `ling32_mtp` (a path) becomes the engine's flags at the start, only when the file is there and the engine says `mtp=1`; the flags are NOT in the config's arguments (Control would - read `--mtp ` as Flash-Next's draft layer); -- `/metrics` (`engine.ling32.mtp`) and `/v1/status` say that MTP is on, the last request's acceptance, tokens per verify and K, and the totals of drafts accepted / offered; -- an engine without the capability, or a missing file, starts without it, with one log line; a request is answered either way. - -The engine is tools/ling32_mock_engine.py (it knows `--mtp`, `--spec mtp`, `spec=mtp`, the STAT keys and the DONE draft counts). - - python -m pytest serve/test_ling32_mtp.py -""" -from __future__ import annotations - -import sys -import tempfile -import unittest -from pathlib import Path - -TERMINAL = Path(__file__).resolve().parents[1] -if str(TERMINAL) not in sys.path: - sys.path.insert(0, str(TERMINAL)) - -from serve import ling32_kind # noqa: E402 -from serve.test_ling32_serve_e2e import Harness, ROLE_END, get_json, post_json # noqa: E402 - -REPLY = "Hello there." + ROLE_END -MTP_ENV = {"LING32_MOCK_CAPS": "mtp=1", "LING32_MOCK_MTP": "accept=0.87 tok_per_verify=1.9 k=2 drafts=30/40"} - - -def sidecar(td: Path) -> Path: - p = td / "Ling-3.2-Air-MTP.strata" - p.write_bytes(b"STRATA\x00\x01" + b"\x00" * 64) - return p - - -def mtp_harness(td, **kw): - td = Path(td) - return Harness(td, [REPLY] * 4, env={**MTP_ENV, **kw.pop("env", {})}, cfg_extra={"ling32_mtp": str(sidecar(td)), **kw.pop("cfg_extra", {})}, **kw) - - -class ServeWithMtp(unittest.TestCase): - def test_the_sidecar_makes_the_engine_start_with_spec_mtp(self): - with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as td, mtp_harness(td) as h: - st = get_json(h.base + "/v1/status")["ling32"] - self.assertEqual(st["spec"], "mtp") - self.assertTrue(st["mtp"]["on"]) - r = post_json(f"{h.base}/v1/chat/completions", {"model": "ling-3.2-air", "max_tokens": 32, "messages": [{"role": "user", "content": "Say hi"}]}) - self.assertEqual(r["choices"][0]["message"]["content"], "Hello there.") - - def test_acceptance_tokens_per_verify_and_k_are_in_the_stats(self): - with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as td, mtp_harness(td) as h: - for _ in range(2): - post_json(f"{h.base}/v1/chat/completions", {"max_tokens": 32, "messages": [{"role": "user", "content": "Say hi"}]}) - for view in (get_json(h.base + "/v1/status")["ling32"], get_json(h.base + "/metrics")["engine"]["ling32"]): - m = view["mtp"] - self.assertEqual((m["on"], m["acceptance"], m["tokens_per_verify"], m["k"]), (True, 0.87, 1.9, 2.0)) - self.assertEqual((m["drafts_accepted_total"], m["drafts_offered_total"]), (60, 80)) # two requests: 30 of 40 each - self.assertEqual(m["acceptance_total"], 0.75) - self.assertEqual(view["last_request"]["spec_accept"], 0.87) - self.assertEqual(view["last_request"]["tokens_per_verify"], 1.9) - - def test_the_prometheus_counters_carry_the_drafts(self): - import urllib.request - with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as td, mtp_harness(td) as h: - post_json(f"{h.base}/v1/chat/completions", {"max_tokens": 32, "messages": [{"role": "user", "content": "x"}]}) - with urllib.request.urlopen(h.base + "/metrics/prometheus", timeout=10) as r: - text = r.read().decode("utf-8") - self.assertIn("strata:drafts_accepted_total 30", text.replace("{}", "")) - - def test_the_spec_block_ceiling_of_the_config_reaches_the_engine(self): - with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as td, mtp_harness(td, cfg_extra={"ling32_spec_block": 2}) as h: - self.assertEqual(get_json(h.base + "/v1/status")["ling32"]["spec"], "mtp") - - def test_without_the_config_key_there_is_no_mtp(self): - with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as td, Harness(Path(td), [REPLY], env=MTP_ENV) as h: - st = get_json(h.base + "/v1/status")["ling32"] - self.assertEqual(st["spec"], "off") - self.assertFalse(st["mtp"]["on"]) - self.assertIsNone(st["mtp"]["acceptance_total"]) - - -class WithoutThePieces(unittest.TestCase): - def test_an_engine_that_cannot_take_the_sidecar_starts_without_it(self): - with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as td, mtp_harness(td, env={"LING32_MOCK_CAPS": ""}) as h: - st = get_json(h.base + "/v1/status")["ling32"] - self.assertEqual(st["spec"], "off") - r = post_json(f"{h.base}/v1/chat/completions", {"max_tokens": 32, "messages": [{"role": "user", "content": "x"}]}) - self.assertEqual(r["choices"][0]["message"]["content"], "Hello there.") - - def test_a_missing_file_starts_without_it(self): - with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as td: - h = mtp_harness(td, cfg_extra={"ling32_mtp": str(Path(td) / "gone" / "Ling-3.2-Air-MTP.strata")}) - with h: - self.assertEqual(get_json(h.base + "/v1/status")["ling32"]["spec"], "off") - - -class EngineArgs(unittest.TestCase): - def setUp(self): - import os - self._probes = dict(ling32_kind._PROBES) - ling32_kind._PROBES.clear() - self._env = dict(os.environ) - - def tearDown(self): - import os - ling32_kind._PROBES.clear() - ling32_kind._PROBES.update(self._probes) - os.environ.clear() - os.environ.update(self._env) - - def exe(self, td: Path): - import os - mock = TERMINAL / "tools" / "ling32_mock_engine.py" - exe = td / ("strata-ling32.bat" if os.name == "nt" else "strata-ling32") - exe.write_text(f'@echo off\r\n"{sys.executable}" "{mock}" %*\r\n' if os.name == "nt" else f'#!/bin/sh\nexec "{sys.executable}" "{mock}" "$@"\n', encoding="utf-8") - exe.chmod(0o755) - return str(exe) - - def cfg(self, td: Path, **extra): - model = td / "Ling-3.2-Air-SQ-96.strata" - model.write_bytes(b"STRATA\x00\x01") - return {"arch": "ling32", "args": ["--model", str(model), "--ctx", "8192", "--tier", "hybrid"], "ling32_mtp": str(sidecar(td)), **extra} - - def test_the_flags_are_made_from_the_config_key_in_a_fixed_order(self): - import os - with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as td: - os.environ["LING32_MOCK_CAPS"] = "mtp=1" - cfg = self.cfg(Path(td), ling32_spec_block=3) - args = ling32_kind.engine_args(cfg, self.exe(Path(td)), announce=False) - at = args.index("--mtp") - self.assertEqual(args[at:], ["--mtp", cfg["ling32_mtp"], "--spec", "mtp", "--spec-adaptive", "--spec-block", "3"]) - self.assertEqual(args[:6], cfg["args"]) # the person's and the launcher's arguments first, untouched - self.assertNotIn("--mtp", cfg["args"]) # and the config itself never holds the flag - - def test_every_backend_gets_the_same_mtp_flags_when_the_engine_says_mtp_1(self): - import os - with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as td: - os.environ["LING32_MOCK_CAPS"] = "" # an engine that says "no MTP" to the probe: no flags, on Metal too - cfg = self.cfg(Path(td), backend="metal") - self.assertNotIn("--mtp", ling32_kind.engine_args(cfg, self.exe(Path(td)), announce=False)) - os.environ["LING32_MOCK_CAPS"] = "mtp=1" - args = ling32_kind.engine_args(cfg, self.exe(Path(td)), announce=False) - self.assertEqual(args[args.index("--mtp"):], ["--mtp", cfg["ling32_mtp"], "--spec", "mtp", "--spec-adaptive"]) - cfg2 = self.cfg(Path(td), backend="hip") - os.environ["LING32_MOCK_CAPS"] = "mtp=1" - args2 = ling32_kind.engine_args(cfg2, self.exe(Path(td)), announce=False) - self.assertEqual(args2[args2.index("--mtp"):], ["--mtp", cfg2["ling32_mtp"], "--spec", "mtp", "--spec-adaptive"]) - - def test_a_cpu_encoder_backend_downscales_big_pictures_to_one_megapixel(self): - import os - with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as td: - os.environ["LING32_MOCK_CAPS"] = "images=1" - vis = str(Path(td) / "Ling-3.2-Air-Vision.strata") - - def args_for(backend, extra=()): - cfg = self.cfg(Path(td), **({"backend": backend} if backend else {})) - cfg["args"] = [*cfg["args"], "--vision", vis, *extra] - cfg.pop("ling32_mtp") - return ling32_kind.engine_args(cfg, self.exe(Path(td)), announce=False) - for backend in ("metal", "sycl"): - a = args_for(backend) - self.assertEqual(a[a.index("--vision-max-pixels"):], ["--vision-max-pixels", "1000000"], backend) - a = args_for("cuda", ["--vision-device", "cpu"]) # any --vision-device cpu - self.assertEqual(a[a.index("--vision-max-pixels") + 1], "1000000") - for backend in ("cuda", "hip", None): # the GPU encoder stays uncapped (the model's own limit) - self.assertNotIn("--vision-max-pixels", args_for(backend), backend) - self.assertNotIn("--vision-max-pixels", args_for("cuda", ["--vision-device", "gpu"])) - a = args_for("metal", ["--vision-max-pixels", "2000000"]) # the person's own cap wins, no second one - self.assertEqual(a.count("--vision-max-pixels"), 1) - self.assertEqual(a[a.index("--vision-max-pixels") + 1], "2000000") - cfg = self.cfg(Path(td), backend="metal") # pictures off: nothing to cap - self.assertNotIn("--vision-max-pixels", ling32_kind.engine_args(cfg, self.exe(Path(td)), announce=False)) - os.environ["LING32_MOCK_CAPS"] = "" # an engine that reads no pictures: the picture flags go, the cap never comes - self.assertNotIn("--vision-max-pixels", args_for("metal")) - - def test_the_capability_is_mtp_1_in_the_info_line(self): - self.assertTrue(ling32_kind.has_mtp({"mtp": "1"})) - self.assertFalse(ling32_kind.has_mtp({"drafter": "none"})) - self.assertFalse(ling32_kind.has_mtp({"mtp": "0"})) - self.assertFalse(ling32_kind.has_mtp(None)) - - def test_a_spec_the_person_wrote_is_theirs(self): - import os - with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as td: - os.environ["LING32_MOCK_CAPS"] = "mtp=1" - cfg = self.cfg(Path(td)) - cfg["args"] += ["--spec", "mtp"] - args = ling32_kind.engine_args(cfg, self.exe(Path(td)), announce=False) - self.assertEqual(args.count("--spec"), 1) - self.assertNotIn("--mtp", args) - - # ---- `--mtp auto` (the default): the engine decides at start (`--mtp-auto FILE`); `on` forces it (`--mtp FILE`) - def test_auto_makes_mtp_auto_flags_when_the_engine_can_decide_and_on_forces(self): - import os - with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as td: - os.environ["LING32_MOCK_CAPS"] = "mtp=1 mtp_auto=1" - for mode, flag in (("auto", "--mtp-auto"), ("on", "--mtp")): - cfg = self.cfg(Path(td), ling32_mtp_mode=mode) - args = ling32_kind.engine_args(cfg, self.exe(Path(td)), announce=False) - self.assertEqual(args[args.index(flag):], [flag, cfg["ling32_mtp"], "--spec", "mtp", "--spec-adaptive"]) - self.assertEqual(args.count("--mtp") + args.count("--mtp-auto"), 1) - cfg = self.cfg(Path(td)) # no mode key: auto (the new default) - self.assertIn("--mtp-auto", ling32_kind.engine_args(cfg, self.exe(Path(td)), announce=False)) - cfg = self.cfg(Path(td), ling32_mtp_mode="nonsense") - self.assertIn("--mtp-auto", ling32_kind.engine_args(cfg, self.exe(Path(td)), announce=False)) - - def test_auto_with_an_engine_that_cannot_decide(self): - import os - with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as td: - os.environ["LING32_MOCK_CAPS"] = "mtp=1" # says mtp=1 but not mtp_auto=1: an older engine - tier_b = ling32_kind.engine_args(self.cfg(Path(td), ling32_mtp_mode="auto", ling32_plan_tier="B"), self.exe(Path(td)), announce=False) - self.assertNotIn("--mtp", tier_b) - self.assertNotIn("--mtp-auto", tier_b) # not tier A: the sidecar does not surely pay, so none - tier_c = ling32_kind.engine_args(self.cfg(Path(td), ling32_mtp_mode="auto", ling32_plan_tier="C"), self.exe(Path(td)), announce=False) - self.assertNotIn("--mtp", tier_c) - a = ling32_kind.engine_args(self.cfg(Path(td), ling32_mtp_mode="auto", ling32_plan_tier="A"), self.exe(Path(td)), announce=False) - self.assertIn("--mtp", a) # tier A: it surely pays - m = ling32_kind.engine_args(self.cfg(Path(td), ling32_mtp_mode="auto", backend="metal"), self.exe(Path(td)), announce=False) - self.assertIn("--mtp", m) # one memory pool (a Mac): it pays - legacy = ling32_kind.engine_args(self.cfg(Path(td)), self.exe(Path(td)), announce=False) - self.assertIn("--mtp", legacy) # a config written before the word: forced, as then - forced = ling32_kind.engine_args(self.cfg(Path(td), ling32_mtp_mode="on", ling32_plan_tier="B"), self.exe(Path(td)), announce=False) - self.assertIn("--mtp", forced) - - def test_a_hand_written_mtp_auto_is_theirs(self): - import os - with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as td: - os.environ["LING32_MOCK_CAPS"] = "mtp=1 mtp_auto=1" - cfg = self.cfg(Path(td)) - cfg["args"] += ["--mtp-auto", "x.strata"] - args = ling32_kind.engine_args(cfg, self.exe(Path(td)), announce=False) - self.assertEqual(args.count("--mtp-auto"), 1) - self.assertNotIn("--mtp", args) - - def test_the_capability_is_mtp_auto_1_in_the_info_line(self): - self.assertTrue(ling32_kind.has_mtp_auto({"mtp": "1", "mtp_auto": "1"})) - self.assertFalse(ling32_kind.has_mtp_auto({"mtp": "1"})) - self.assertFalse(ling32_kind.has_mtp_auto(None)) - got = ling32_kind.parse_info("arch=ling32 layers=42 vocab=157184 drafter=none mtp=1 mtp_auto=1 images=1 tiers=A,B,C") - self.assertEqual((got["mtp"], got["mtp_auto"]), ("1", "1")) - - def test_the_status_says_what_was_chosen_and_why_from_measured_keys_only(self): - from strata_control import ling32_fit - v = ling32_kind.stats_view({"spec": "mtp", "h2d_gbps": "46.0"}, {}, {}, args=["--mtp-auto", "m", "--spec", "mtp"]) - self.assertEqual((v["h2d_gbps"], v["mtp"]["mode"], v["mtp"]["line"]), (46.0, "auto", "MTP: on (auto: link 46 GB/s)")) - v = ling32_kind.stats_view({"spec": "off", "h2d_gbps": "24.4"}, {}, {}, args=["--mtp-auto", "m"]) - self.assertEqual(v["mtp"]["line"], "MTP: off (auto: 24 GB/s link: no gain)") - self.assertFalse(v["mtp"]["on"]) - v = ling32_kind.stats_view({"spec": "off", "h2d_gbps": "0.0"}, {}, {}, args=["--mtp-auto", "m"]) - self.assertEqual(v["mtp"]["line"], "MTP: off (auto)") # not measured (tier A, no tier store): no figure is made up - v = ling32_kind.stats_view({"spec": "mtp"}, {}, {}, args=["--mtp-auto", "m"]) - self.assertEqual(v["mtp"]["line"], "MTP: on (auto)") - v = ling32_kind.stats_view({"spec": "mtp"}, {}, {}, args=["--mtp", "m"]) - self.assertEqual((v["mtp"]["mode"], v["mtp"]["line"]), ("on", "MTP: on (forced)")) - v = ling32_kind.stats_view({"spec": "off"}, {}, {}, args=["--model", "x"]) # no sidecar asked for: nothing to say - self.assertEqual((v["mtp"]["mode"], v["mtp"]["line"], v["h2d_gbps"]), (None, None, None)) - self.assertEqual(ling32_fit.mtp_status_line("mtp", 53.5), "MTP: on (auto: link 54 GB/s)") - self.assertFalse(any(ch.isdigit() for ch in ling32_fit.MTP_AUTO_NOTE.replace("32 GB/s", ""))) # the plan's note carries no speed figure but the engine's threshold - - def test_stats_view_without_an_engine_is_safe(self): - v = ling32_kind.stats_view(None, None, None) - self.assertEqual(v["mtp"], {"on": False, "acceptance": None, "tokens_per_verify": None, "k": None, "drafts_accepted_total": 0, "drafts_offered_total": 0, "acceptance_total": None, - "mode": None, "line": None}) - self.assertIsNone(v["h2d_gbps"]) - - def test_the_stat_line_with_spec_keys(self): - got = ling32_kind.parse_stat("STAT prefetch_hit=0 decode_tps=61.5 spec_accept=0.87 tok_per_verify=1.9 spec_k=3") - self.assertEqual((got["spec_accept"], got["tok_per_verify"], got["spec_k"]), (0.87, 1.9, 3.0)) - - -if __name__ == "__main__": - unittest.main() +"""The MTP sidecar through serve (L32-MTP: the upstream model's multi-token-prediction layer as the drafter, `--mtp FILE --spec mtp --spec-adaptive`, INFO `spec=mtp`): + +- the run config's `ling32_mtp` (a path) becomes the engine's flags at the start, only when the file is there and the engine says `mtp=1`; the flags are NOT in the config's arguments (Control would + read `--mtp ` as Flash-Next's draft layer); +- `/metrics` (`engine.ling32.mtp`) and `/v1/status` say that MTP is on, the last request's acceptance, tokens per verify and K, and the totals of drafts accepted / offered; +- an engine without the capability, or a missing file, starts without it, with one log line; a request is answered either way. + +The engine is tools/ling32_mock_engine.py (it knows `--mtp`, `--spec mtp`, `spec=mtp`, the STAT keys and the DONE draft counts). + + python -m pytest serve/test_ling32_mtp.py +""" +from __future__ import annotations + +import sys +import tempfile +import unittest +from pathlib import Path + +TERMINAL = Path(__file__).resolve().parents[1] +if str(TERMINAL) not in sys.path: + sys.path.insert(0, str(TERMINAL)) + +from serve import ling32_kind # noqa: E402 +from serve.test_ling32_serve_e2e import Harness, ROLE_END, get_json, post_json # noqa: E402 + +REPLY = "Hello there." + ROLE_END +MTP_ENV = {"LING32_MOCK_CAPS": "mtp=1", "LING32_MOCK_MTP": "accept=0.87 tok_per_verify=1.9 k=2 drafts=30/40"} + + +def sidecar(td: Path) -> Path: + p = td / "Ling-3.2-Air-MTP.strata" + p.write_bytes(b"STRATA\x00\x01" + b"\x00" * 64) + return p + + +def mtp_harness(td, **kw): + td = Path(td) + return Harness(td, [REPLY] * 4, env={**MTP_ENV, **kw.pop("env", {})}, cfg_extra={"ling32_mtp": str(sidecar(td)), **kw.pop("cfg_extra", {})}, **kw) + + +class ServeWithMtp(unittest.TestCase): + def test_the_sidecar_makes_the_engine_start_with_spec_mtp(self): + with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as td, mtp_harness(td) as h: + st = get_json(h.base + "/v1/status")["ling32"] + self.assertEqual(st["spec"], "mtp") + self.assertTrue(st["mtp"]["on"]) + r = post_json(f"{h.base}/v1/chat/completions", {"model": "ling-3.2-air", "max_tokens": 32, "messages": [{"role": "user", "content": "Say hi"}]}) + self.assertEqual(r["choices"][0]["message"]["content"], "Hello there.") + + def test_acceptance_tokens_per_verify_and_k_are_in_the_stats(self): + with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as td, mtp_harness(td) as h: + for _ in range(2): + post_json(f"{h.base}/v1/chat/completions", {"max_tokens": 32, "messages": [{"role": "user", "content": "Say hi"}]}) + for view in (get_json(h.base + "/v1/status")["ling32"], get_json(h.base + "/metrics")["engine"]["ling32"]): + m = view["mtp"] + self.assertEqual((m["on"], m["acceptance"], m["tokens_per_verify"], m["k"]), (True, 0.87, 1.9, 2.0)) + self.assertEqual((m["drafts_accepted_total"], m["drafts_offered_total"]), (60, 80)) # two requests: 30 of 40 each + self.assertEqual(m["acceptance_total"], 0.75) + self.assertEqual(view["last_request"]["spec_accept"], 0.87) + self.assertEqual(view["last_request"]["tokens_per_verify"], 1.9) + + def test_the_prometheus_counters_carry_the_drafts(self): + import urllib.request + with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as td, mtp_harness(td) as h: + post_json(f"{h.base}/v1/chat/completions", {"max_tokens": 32, "messages": [{"role": "user", "content": "x"}]}) + with urllib.request.urlopen(h.base + "/metrics/prometheus", timeout=10) as r: + text = r.read().decode("utf-8") + self.assertIn("strata:drafts_accepted_total 30", text.replace("{}", "")) + + def test_the_spec_block_ceiling_of_the_config_reaches_the_engine(self): + with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as td, mtp_harness(td, cfg_extra={"ling32_spec_block": 2}) as h: + self.assertEqual(get_json(h.base + "/v1/status")["ling32"]["spec"], "mtp") + + def test_without_the_config_key_there_is_no_mtp(self): + with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as td, Harness(Path(td), [REPLY], env=MTP_ENV) as h: + st = get_json(h.base + "/v1/status")["ling32"] + self.assertEqual(st["spec"], "off") + self.assertFalse(st["mtp"]["on"]) + self.assertIsNone(st["mtp"]["acceptance_total"]) + + +class WithoutThePieces(unittest.TestCase): + def test_an_engine_that_cannot_take_the_sidecar_starts_without_it(self): + with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as td, mtp_harness(td, env={"LING32_MOCK_CAPS": ""}) as h: + st = get_json(h.base + "/v1/status")["ling32"] + self.assertEqual(st["spec"], "off") + r = post_json(f"{h.base}/v1/chat/completions", {"max_tokens": 32, "messages": [{"role": "user", "content": "x"}]}) + self.assertEqual(r["choices"][0]["message"]["content"], "Hello there.") + + def test_a_missing_file_starts_without_it(self): + with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as td: + h = mtp_harness(td, cfg_extra={"ling32_mtp": str(Path(td) / "gone" / "Ling-3.2-Air-MTP.strata")}) + with h: + self.assertEqual(get_json(h.base + "/v1/status")["ling32"]["spec"], "off") + + +class EngineArgs(unittest.TestCase): + def setUp(self): + import os + self._probes = dict(ling32_kind._PROBES) + ling32_kind._PROBES.clear() + self._env = dict(os.environ) + + def tearDown(self): + import os + ling32_kind._PROBES.clear() + ling32_kind._PROBES.update(self._probes) + os.environ.clear() + os.environ.update(self._env) + + def exe(self, td: Path): + import os + mock = TERMINAL / "tools" / "ling32_mock_engine.py" + exe = td / ("strata-ling32.bat" if os.name == "nt" else "strata-ling32") + exe.write_text(f'@echo off\r\n"{sys.executable}" "{mock}" %*\r\n' if os.name == "nt" else f'#!/bin/sh\nexec "{sys.executable}" "{mock}" "$@"\n', encoding="utf-8") + exe.chmod(0o755) + return str(exe) + + def cfg(self, td: Path, **extra): + model = td / "Ling-3.2-Air-SQ-96.strata" + model.write_bytes(b"STRATA\x00\x01") + return {"arch": "ling32", "args": ["--model", str(model), "--ctx", "8192", "--tier", "hybrid"], "ling32_mtp": str(sidecar(td)), **extra} + + def test_the_flags_are_made_from_the_config_key_in_a_fixed_order(self): + import os + with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as td: + os.environ["LING32_MOCK_CAPS"] = "mtp=1" + cfg = self.cfg(Path(td), ling32_spec_block=3) + args = ling32_kind.engine_args(cfg, self.exe(Path(td)), announce=False) + at = args.index("--mtp") + self.assertEqual(args[at:], ["--mtp", cfg["ling32_mtp"], "--spec", "mtp", "--spec-adaptive", "--spec-block", "3"]) + self.assertEqual(args[:6], cfg["args"]) # the person's and the launcher's arguments first, untouched + self.assertNotIn("--mtp", cfg["args"]) # and the config itself never holds the flag + + def test_every_backend_gets_the_same_mtp_flags_when_the_engine_says_mtp_1(self): + import os + with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as td: + os.environ["LING32_MOCK_CAPS"] = "" # an engine that says "no MTP" to the probe: no flags, on Metal too + cfg = self.cfg(Path(td), backend="metal") + self.assertNotIn("--mtp", ling32_kind.engine_args(cfg, self.exe(Path(td)), announce=False)) + os.environ["LING32_MOCK_CAPS"] = "mtp=1" + args = ling32_kind.engine_args(cfg, self.exe(Path(td)), announce=False) + self.assertEqual(args[args.index("--mtp"):], ["--mtp", cfg["ling32_mtp"], "--spec", "mtp", "--spec-adaptive"]) + cfg2 = self.cfg(Path(td), backend="hip") + os.environ["LING32_MOCK_CAPS"] = "mtp=1" + args2 = ling32_kind.engine_args(cfg2, self.exe(Path(td)), announce=False) + self.assertEqual(args2[args2.index("--mtp"):], ["--mtp", cfg2["ling32_mtp"], "--spec", "mtp", "--spec-adaptive"]) + + def test_a_cpu_encoder_backend_downscales_big_pictures_to_one_megapixel(self): + import os + with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as td: + os.environ["LING32_MOCK_CAPS"] = "images=1" + vis = str(Path(td) / "Ling-3.2-Air-Vision.strata") + + def args_for(backend, extra=()): + cfg = self.cfg(Path(td), **({"backend": backend} if backend else {})) + cfg["args"] = [*cfg["args"], "--vision", vis, *extra] + cfg.pop("ling32_mtp") + return ling32_kind.engine_args(cfg, self.exe(Path(td)), announce=False) + for backend in ("metal", "sycl"): + a = args_for(backend) + self.assertEqual(a[a.index("--vision-max-pixels"):], ["--vision-max-pixels", "1000000"], backend) + a = args_for("cuda", ["--vision-device", "cpu"]) # any --vision-device cpu + self.assertEqual(a[a.index("--vision-max-pixels") + 1], "1000000") + for backend in ("cuda", "hip", None): # the GPU encoder stays uncapped (the model's own limit) + self.assertNotIn("--vision-max-pixels", args_for(backend), backend) + self.assertNotIn("--vision-max-pixels", args_for("cuda", ["--vision-device", "gpu"])) + a = args_for("metal", ["--vision-max-pixels", "2000000"]) # the person's own cap wins, no second one + self.assertEqual(a.count("--vision-max-pixels"), 1) + self.assertEqual(a[a.index("--vision-max-pixels") + 1], "2000000") + cfg = self.cfg(Path(td), backend="metal") # pictures off: nothing to cap + self.assertNotIn("--vision-max-pixels", ling32_kind.engine_args(cfg, self.exe(Path(td)), announce=False)) + os.environ["LING32_MOCK_CAPS"] = "" # an engine that reads no pictures: the picture flags go, the cap never comes + self.assertNotIn("--vision-max-pixels", args_for("metal")) + self.assertNotIn("--vision-max-pixels", args_for("metal", ["--vision-max-pixels", "1000000"])) # a config that already holds the cap loses it with the shard + + def test_the_capability_is_mtp_1_in_the_info_line(self): + self.assertTrue(ling32_kind.has_mtp({"mtp": "1"})) + self.assertFalse(ling32_kind.has_mtp({"drafter": "none"})) + self.assertFalse(ling32_kind.has_mtp({"mtp": "0"})) + self.assertFalse(ling32_kind.has_mtp(None)) + + def test_a_spec_the_person_wrote_is_theirs(self): + import os + with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as td: + os.environ["LING32_MOCK_CAPS"] = "mtp=1" + cfg = self.cfg(Path(td)) + cfg["args"] += ["--spec", "mtp"] + args = ling32_kind.engine_args(cfg, self.exe(Path(td)), announce=False) + self.assertEqual(args.count("--spec"), 1) + self.assertNotIn("--mtp", args) + + # ---- `--mtp auto` (the default): the engine decides at start (`--mtp-auto FILE`); `on` forces it (`--mtp FILE`) + def test_auto_makes_mtp_auto_flags_when_the_engine_can_decide_and_on_forces(self): + import os + with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as td: + os.environ["LING32_MOCK_CAPS"] = "mtp=1 mtp_auto=1" + for mode, flag in (("auto", "--mtp-auto"), ("on", "--mtp")): + cfg = self.cfg(Path(td), ling32_mtp_mode=mode) + args = ling32_kind.engine_args(cfg, self.exe(Path(td)), announce=False) + self.assertEqual(args[args.index(flag):], [flag, cfg["ling32_mtp"], "--spec", "mtp", "--spec-adaptive"]) + self.assertEqual(args.count("--mtp") + args.count("--mtp-auto"), 1) + cfg = self.cfg(Path(td)) # no mode key: auto (the new default) + self.assertIn("--mtp-auto", ling32_kind.engine_args(cfg, self.exe(Path(td)), announce=False)) + cfg = self.cfg(Path(td), ling32_mtp_mode="nonsense") + self.assertIn("--mtp-auto", ling32_kind.engine_args(cfg, self.exe(Path(td)), announce=False)) + + def test_auto_with_an_engine_that_cannot_decide(self): + import os + with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as td: + os.environ["LING32_MOCK_CAPS"] = "mtp=1" # says mtp=1 but not mtp_auto=1: an older engine + tier_b = ling32_kind.engine_args(self.cfg(Path(td), ling32_mtp_mode="auto", ling32_plan_tier="B"), self.exe(Path(td)), announce=False) + self.assertNotIn("--mtp", tier_b) + self.assertNotIn("--mtp-auto", tier_b) # not tier A: the sidecar does not surely pay, so none + tier_c = ling32_kind.engine_args(self.cfg(Path(td), ling32_mtp_mode="auto", ling32_plan_tier="C"), self.exe(Path(td)), announce=False) + self.assertNotIn("--mtp", tier_c) + a = ling32_kind.engine_args(self.cfg(Path(td), ling32_mtp_mode="auto", ling32_plan_tier="A"), self.exe(Path(td)), announce=False) + self.assertIn("--mtp", a) # tier A: it surely pays + m = ling32_kind.engine_args(self.cfg(Path(td), ling32_mtp_mode="auto", backend="metal"), self.exe(Path(td)), announce=False) + self.assertIn("--mtp", m) # one memory pool (a Mac): it pays + legacy = ling32_kind.engine_args(self.cfg(Path(td)), self.exe(Path(td)), announce=False) + self.assertIn("--mtp", legacy) # a config written before the word: forced, as then + forced = ling32_kind.engine_args(self.cfg(Path(td), ling32_mtp_mode="on", ling32_plan_tier="B"), self.exe(Path(td)), announce=False) + self.assertIn("--mtp", forced) + + def test_a_hand_written_mtp_auto_is_theirs(self): + import os + with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as td: + os.environ["LING32_MOCK_CAPS"] = "mtp=1 mtp_auto=1" + cfg = self.cfg(Path(td)) + cfg["args"] += ["--mtp-auto", "x.strata"] + args = ling32_kind.engine_args(cfg, self.exe(Path(td)), announce=False) + self.assertEqual(args.count("--mtp-auto"), 1) + self.assertNotIn("--mtp", args) + + def test_the_capability_is_mtp_auto_1_in_the_info_line(self): + self.assertTrue(ling32_kind.has_mtp_auto({"mtp": "1", "mtp_auto": "1"})) + self.assertFalse(ling32_kind.has_mtp_auto({"mtp": "1"})) + self.assertFalse(ling32_kind.has_mtp_auto(None)) + got = ling32_kind.parse_info("arch=ling32 layers=42 vocab=157184 drafter=none mtp=1 mtp_auto=1 images=1 tiers=A,B,C") + self.assertEqual((got["mtp"], got["mtp_auto"]), ("1", "1")) + + def test_the_status_says_what_was_chosen_and_why_from_measured_keys_only(self): + from strata_control import ling32_fit + v = ling32_kind.stats_view({"spec": "mtp", "h2d_gbps": "46.0"}, {}, {}, args=["--mtp-auto", "m", "--spec", "mtp"]) + self.assertEqual((v["h2d_gbps"], v["mtp"]["mode"], v["mtp"]["line"]), (46.0, "auto", "MTP: on (auto: link 46 GB/s)")) + v = ling32_kind.stats_view({"spec": "off", "h2d_gbps": "24.4"}, {}, {}, args=["--mtp-auto", "m"]) + self.assertEqual(v["mtp"]["line"], "MTP: off (auto: 24 GB/s link: no gain)") + self.assertFalse(v["mtp"]["on"]) + v = ling32_kind.stats_view({"spec": "off", "h2d_gbps": "0.0"}, {}, {}, args=["--mtp-auto", "m"]) + self.assertEqual(v["mtp"]["line"], "MTP: off (auto)") # not measured (tier A, no tier store): no figure is made up + v = ling32_kind.stats_view({"spec": "mtp"}, {}, {}, args=["--mtp-auto", "m"]) + self.assertEqual(v["mtp"]["line"], "MTP: on (auto)") + v = ling32_kind.stats_view({"spec": "mtp"}, {}, {}, args=["--mtp", "m"]) + self.assertEqual((v["mtp"]["mode"], v["mtp"]["line"]), ("on", "MTP: on (forced)")) + v = ling32_kind.stats_view({"spec": "off"}, {}, {}, args=["--model", "x"]) # no sidecar asked for: nothing to say + self.assertEqual((v["mtp"]["mode"], v["mtp"]["line"], v["h2d_gbps"]), (None, None, None)) + self.assertEqual(ling32_fit.mtp_status_line("mtp", 53.5), "MTP: on (auto: link 54 GB/s)") + self.assertFalse(any(ch.isdigit() for ch in ling32_fit.MTP_AUTO_NOTE.replace("32 GB/s", ""))) # the plan's note carries no speed figure but the engine's threshold + + def test_stats_view_without_an_engine_is_safe(self): + v = ling32_kind.stats_view(None, None, None) + self.assertEqual(v["mtp"], {"on": False, "acceptance": None, "tokens_per_verify": None, "k": None, "drafts_accepted_total": 0, "drafts_offered_total": 0, "acceptance_total": None, + "mode": None, "line": None}) + self.assertIsNone(v["h2d_gbps"]) + + def test_the_stat_line_with_spec_keys(self): + got = ling32_kind.parse_stat("STAT prefetch_hit=0 decode_tps=61.5 spec_accept=0.87 tok_per_verify=1.9 spec_k=3") + self.assertEqual((got["spec_accept"], got["tok_per_verify"], got["spec_k"]), (0.87, 1.9, 3.0)) + + +if __name__ == "__main__": + unittest.main() diff --git a/terminal/strata_cli/launch/runner.py b/terminal/strata_cli/launch/runner.py index 83b8ca6d2e..679bbf7412 100644 --- a/terminal/strata_cli/launch/runner.py +++ b/terminal/strata_cli/launch/runner.py @@ -329,7 +329,7 @@ def apply_choices(cfg: dict, s: S.LaunchSettings) -> dict: if s.context: put("--ctx", str(int(s.context))) if s.vision in ("off", "no"): - for flag in ("--vision", "--vision-device"): + for flag in ("--vision", "--vision-device", "--vision-max-pixels"): while flag in args: at = args.index(flag) del args[at:at + (2 if at + 1 < len(args) and not args[at + 1].startswith("--") else 1)] @@ -873,7 +873,7 @@ def derive_config(base: dict, s: S.LaunchSettings, *, bool_flags: frozenset[str] if isinstance(cfg.get("args"), list): # pictures: off takes the Vision shard out of this start; gpu / cpu name the encoder's device (only with a shard to read) cargs = [str(a) for a in cfg["args"]] if s.vision in ("off", "no"): - for flag in ("--vision", "--vision-device"): + for flag in ("--vision", "--vision-device", "--vision-max-pixels"): while flag in cargs: at = cargs.index(flag) del cargs[at:at + (2 if at + 1 < len(cargs) and not cargs[at + 1].startswith("--") else 1)] diff --git a/terminal/tests/terminal/test_ling32_launch.py b/terminal/tests/terminal/test_ling32_launch.py index 6dd3eb7df7..912e8758f7 100644 --- a/terminal/tests/terminal/test_ling32_launch.py +++ b/terminal/tests/terminal/test_ling32_launch.py @@ -1,682 +1,683 @@ -"""`strata launch` for Ling-3.2-Air: its engine is the component strata-ling32 (shape "ling32"), the Flash-Next steps leave it alone, and the flags ---thinking / --tier / --turbo-ssd / --vram-budget-gib / --ram-budget-gib / --cpu-coexec reach the run config the way the engine and serve read them -(strata_cli/launch/{cmd,runner,settings}.py, strata_control/ling32_family.py and ling32_fit.py).""" - -from __future__ import annotations - -import argparse -import os -import tempfile -import unittest -from pathlib import Path -from unittest import mock - -from strata_cli.launch import cmd as C -from strata_cli.launch import runner as R -from strata_cli.launch import settings as S -from strata_control import ling32_family, ling32_fit, tune_knobs - -BASE = {"exe": "component:strata-ling32", "arch": "ling32", "model_name": "ling-3.2-air-sq-96", "port": 8095, "drafting": "off", "thinking": "off", - "args": ["--model", "C:/m/Ling-3.2-Air-SQ-96.strata", "--ctx", "32768", "--chunk", "256", "--tc", "16", "--tc-moe", "128", "--graph", "--mla-kernel", "simt"]} - - -def runner_for(family: str | None, **kw) -> R.Runner: - r = object.__new__(R.Runner) - r.s = S.LaunchSettings(family=family, **kw) - return r - - -def derive(**kw) -> dict: - return R.derive_config(BASE, S.LaunchSettings(family="ling-3.2-air", port=8123, **kw), bool_flags=tune_knobs.BOOL_FLAGS, log="x.log") - - -def value(args, flag): - return args[args.index(flag) + 1] if flag in args and args.index(flag) + 1 < len(args) else None - - -class Which(unittest.TestCase): - def test_the_shape_is_ling32_only_for_ling(self): - self.assertEqual(runner_for("ling-3.2-air").model_shape(), "ling32") - self.assertTrue(runner_for("ling-3.2-air").is_ling32()) - self.assertTrue(runner_for("ling-3.2-air").is_native_strata_family()) - self.assertFalse(runner_for("qwen").is_ling32()) - self.assertFalse(runner_for("hy4-flash").is_ling32()) - with mock.patch.object(R.Runner, "catalog", create=True) as cat: - cat.strata.setup_module.return_value = mock.Mock(FAMILIES={"qwen": {}}, LING32_FAMILIES={"ling-3.2-air": {"title": "inclusionAI Ling-3.2-Air"}}, HY4_FAMILIES={}, INKLING_FAMILIES={}) - self.assertEqual(runner_for("ling-3.2-air").model_title(), "inclusionAI Ling-3.2-Air") - - def test_the_shape_engine_is_a_known_component(self): - from strata_control import shape_engine, updater - self.assertEqual(shape_engine.component_id("ling32"), "strata-ling32") - self.assertIn("ling32", shape_engine.CUSTOM_SHAPES) - self.assertEqual(shape_engine.exe_name("ling32", target="linux-x86_64"), "strata-ling32") - self.assertEqual(shape_engine.exe_name("ling32", target="windows-x86_64"), "strata-ling32.exe") - self.assertEqual(updater._config_component_id(BASE), "strata-ling32") - self.assertEqual(updater._config_component_id({"exe": "component:strata-engine", "arch": "ling32", "args": []}), "strata-ling32") - self.assertEqual(updater._config_component_id({"args": ["--model", "C:/m/Ling-3.2-Air-SQ-96.strata"]}), "strata-ling32") - self.assertEqual(updater._config_component_id({"args": ["--native", "C:/m/Hy4-Flash-SQ-64.strata"]}), "strata-hy4") - - -class EngineVersion(unittest.TestCase): - """Control installs the engine component only after `strata-ling32 --version` names itself (shape_engine._test_start; `strata-ling32 0.2.24` is what L32-SPEC's aa648c8b8 prints).""" - - def start(self, stdout: str, code: int = 0): - import subprocess - from strata_control import shape_engine - done = mock.Mock(stdout=stdout, stderr="", returncode=code) - with mock.patch.object(subprocess, "run", return_value=done) as run: - result = shape_engine._test_start(Path("/x/strata-ling32"), shape="ling32") - self.assertEqual(run.call_args[0][0][1:], ["--version"]) - return result - - def test_the_engine_that_names_itself_is_accepted(self): - self.assertEqual(self.start("strata-ling32 0.2.24\n"), (True, "strata-ling32 0.2.24")) - - def test_another_program_or_a_failure_is_refused(self): - from strata_control import shape_engine - self.assertEqual(self.start("strata-hy4 0.2.24\n"), (False, shape_engine.NO_SHAPE_ANSWER)) - self.assertEqual(self.start("strata 0.2.24\n"), (False, shape_engine.NO_SHAPE_ANSWER)) - ok, why = self.start("strata-ling32: unknown option --version\n", code=2) # an engine before --version (f-ling32-int-serve 8735db1ab) - self.assertFalse(ok) - self.assertTrue(why) - - -class Steps(unittest.TestCase): - def test_the_flash_next_steps_are_skipped(self): - r = runner_for("ling-3.2-air") - self.assertIsNone(r.ensure_drafter(Path("x.json"))) - self.assertEqual(r.fetch_missing_drafter(Path("x.json")), Path("x.json")) - with mock.patch.object(R.Runner, "stop_own_server_for_tuning") as stop, mock.patch.object(R.Runner, "emit"): - r.tune() - stop.assert_not_called() - self.assertTrue(r.drafting_plan_line().startswith("Drafting: MTP sidecar")) # its own MTP sidecar, not a Flash-Next drafter - - def test_the_setup_arguments_carry_no_flash_next_flags(self): - r = runner_for("ling-3.2-air", model="SQ-96", context=32768, kv="int8", vision="off") - r._catalog = mock.Mock() - r._catalog.resolve.side_effect = lambda model, fam: (fam, model) - r.feed = None - r.move_data = False - r.existing_data_dir = lambda: None - r.installed_card_args = lambda: [] - args = r.setup_args() - self.assertEqual(value(args, "--family"), "ling-3.2-air") - for flag in ("--mtp", "--drafter", "--draft-vocab"): - self.assertNotIn(flag, args) - - -class Config(unittest.TestCase): - def test_derive_config_keeps_the_engine_and_its_arguments(self): - cfg = derive() - self.assertEqual(cfg["exe"], "component:strata-ling32") - self.assertEqual(cfg["arch"], "ling32") - self.assertEqual(cfg["port"], 8123) - for flag in ("--model", "--ctx", "--chunk", "--tc", "--tc-moe", "--graph", "--mla-kernel"): - self.assertIn(flag, cfg["args"]) - for flag in ("--tier", "--turbo-ssd", "--vram-budget-gib", "--ram-budget-gib", "--cpu-coexec", "--spec", "--mtp", "--draft", "--batch"): - self.assertNotIn(flag, cfg["args"]) # nothing the person did not ask for: the engine plans by itself - self.assertNotIn("mtp", cfg) - self.assertEqual(cfg["thinking"], "off") - - def test_thinking_goes_to_the_config_not_to_the_engine(self): - cfg = derive(thinking="on") - self.assertEqual(cfg["thinking"], "on") - self.assertNotIn("--thinking", cfg["args"]) - self.assertEqual(derive(thinking="off")["thinking"], "off") - - def test_tier_and_budgets_become_engine_flags(self): - cfg = derive(tier="C", vram_budget=10.0, ram_budget=16.0) - self.assertEqual(value(cfg["args"], "--tier"), "nvme") - self.assertEqual(value(cfg["args"], "--vram-budget-gib"), "10") - self.assertEqual(value(cfg["args"], "--ram-budget-gib"), "16") - self.assertNotIn("--turbo-ssd", cfg["args"]) - self.assertEqual(value(derive(tier="A")["args"], "--tier"), "vram") - self.assertEqual(value(derive(tier="B")["args"], "--tier"), "hybrid") - self.assertNotIn("--tier", derive(tier="auto")["args"]) - - def test_turbo_ssd_is_opt_in_and_only_then_present(self): - self.assertNotIn("--turbo-ssd", derive()["args"]) - self.assertIn("--turbo-ssd", derive(tier="C", turbo_ssd=True)["args"]) - - def test_cpu_coexec_comes_through_the_advanced_table(self): - cfg = derive(extra={"--cpu-coexec": "4"}) - self.assertEqual(value(cfg["args"], "--cpu-coexec"), "4") - - def test_prefetch_keeps_its_word(self): - # found on the real engine (z440 smoke, case b): `--set prefetch=on` used to become a bare --prefetch that swallowed the next flag ("unknown option hybrid") - args = derive(tier="B", extra={"--prefetch": "on"})["args"] - self.assertEqual(value(args, "--prefetch"), "on") - self.assertEqual(value(args, "--tier"), "hybrid") - self.assertEqual(value(derive(extra={"--prefetch": "off"})["args"], "--prefetch"), "off") # the engine's own word: --prefetch off turns the lookahead prefetch off - - def test_a_tier_of_an_earlier_run_is_replaced_not_doubled(self): - base = {**BASE, "args": BASE["args"] + ["--tier", "hybrid"]} - cfg = R.derive_config(base, S.LaunchSettings(family="ling-3.2-air", tier="C"), bool_flags=tune_knobs.BOOL_FLAGS, log="x.log") - self.assertEqual(cfg["args"].count("--tier"), 1) - self.assertEqual(value(cfg["args"], "--tier"), "nvme") - - def test_other_families_ignore_the_ling_choices(self): - base = {"exe": "component:strata-hy4", "arch": "hy4flash", "model_name": "hy4-flash-sq-64", "port": 8095, "drafting": "off", "args": ["--native", "a.strata"]} - cfg = R.derive_config(base, S.LaunchSettings(family="hy4-flash", tier="C", thinking="on", turbo_ssd=True), bool_flags=tune_knobs.BOOL_FLAGS, log="x.log") - self.assertNotIn("--tier", cfg["args"]) - self.assertNotIn("--turbo-ssd", cfg["args"]) - self.assertNotIn("thinking", cfg) - - -VBASE = {**BASE, "args": BASE["args"] + ["--vision", "C:/m/Ling-3.2-Air-Vision.strata"]} - - -class Pictures(unittest.TestCase): - """Picture input (L32-VISION): the Vision shard is in the run config's engine arguments by default; --vision off takes it out, gpu / cpu name the encoder's device.""" - - def test_apply_choices_uses_ctx_and_the_vision_flags_not_hy4s(self): - out = R.apply_choices(VBASE, S.LaunchSettings(family="ling-3.2-air", context=65536)) - self.assertEqual(value(out["args"], "--ctx"), "65536") - self.assertNotIn("--max-context", out["args"]) # the engine would refuse it - self.assertIn("--vision", out["args"]) - off = R.apply_choices({**VBASE, "args": VBASE["args"] + ["--vision-device", "gpu"]}, S.LaunchSettings(family="ling-3.2-air", vision="off")) - self.assertNotIn("--vision", off["args"]) - self.assertNotIn("--vision-device", off["args"]) - self.assertNotIn("C:/m/Ling-3.2-Air-Vision.strata", off["args"]) - self.assertEqual(value(R.apply_choices(VBASE, S.LaunchSettings(family="ling-3.2-air", vision="cpu"))["args"], "--vision-device"), "cpu") - self.assertNotIn("--vision-device", R.apply_choices(BASE, S.LaunchSettings(family="ling-3.2-air", vision="cpu"))["args"]) # no shard, no device word - - def test_derive_config_keeps_the_shard_by_default_and_follows_the_choice(self): - base = derive_with(VBASE, S.LaunchSettings(family="ling-3.2-air")) - self.assertEqual(value(base["args"], "--vision"), "C:/m/Ling-3.2-Air-Vision.strata") - self.assertNotIn("--vision-device", base["args"]) - self.assertEqual(value(derive_with(VBASE, S.LaunchSettings(family="ling-3.2-air", vision="gpu"))["args"], "--vision-device"), "gpu") - self.assertEqual(value(derive_with(VBASE, S.LaunchSettings(family="ling-3.2-air", vision="on"))["args"], "--vision"), "C:/m/Ling-3.2-Air-Vision.strata") - off = derive_with(VBASE, S.LaunchSettings(family="ling-3.2-air", vision="off"))["args"] - self.assertNotIn("--vision", off) - - def test_setup_is_told_the_picture_word(self): - self.assertEqual(runner_with_vision("on").vision_word(), "yes") - self.assertEqual(runner_with_vision("gpu").vision_word(), "gpu") # the encoder's device reaches setup for Ling - self.assertEqual(runner_with_vision("cpu").vision_word(), "cpu") - self.assertEqual(runner_with_vision("off").vision_word(), "no") - - def test_pictures_are_on_when_nobody_chose(self): - r = runner_for("ling-3.2-air") - r._catalog = mock.Mock() - row = mock.Mock(images=True, family="ling-3.2-air", model="SQ-96", custom=False) - r._catalog.rows.return_value = [row] - r.s.model = "SQ-96" - self.assertEqual(r.resolved_vision(), "on") - r2 = runner_for("ling-3.2-air", model="SQ-96") - r2._catalog = mock.Mock() - r2._catalog.rows.return_value = [mock.Mock(images=False, family="ling-3.2-air", model="SQ-96", custom=False)] - self.assertEqual(r2.resolved_vision(), "off") - - def test_the_catalog_says_pictures_work_for_ling(self): - from strata_cli.launch.catalog import Catalog - with tempfile.TemporaryDirectory() as d: - cat = Catalog(src=Path(__file__).resolve().parents[2], root=Path(d)) - self.assertEqual(cat.picture_default(True, "ling-3.2-air"), "on") - self.assertEqual(cat.reader_state("ling-3.2-air"), "present") - self.assertFalse(cat.pictures_not_on_card("ling-3.2-air")) - - -def derive_with(base: dict, s) -> dict: - return R.derive_config(base, s, bool_flags=tune_knobs.BOOL_FLAGS, log="x.log") - - -def runner_with_vision(word: str) -> R.Runner: - r = runner_for("ling-3.2-air", model="SQ-96", vision=word) - r._catalog = mock.Mock() - return r - - -class Mtp(unittest.TestCase): - """`--mtp on|off` for Ling-3.2-Air: the sidecar's path is the run config's key `ling32_mtp` (serve makes `--mtp FILE --spec mtp --spec-adaptive` from it); the flags never sit in the arguments, - where Control would read `--mtp ` as Flash-Next's draft layer.""" - - def setUp(self): # the test sidecars are a few bytes: no pin to check them against - patcher = mock.patch.dict(ling32_family.MTP_PINS, {}, clear=True) - patcher.start() - self.addCleanup(patcher.stop) - - def with_sidecar(self, td: str): - m = Path(td) / "Ling-3.2-Air-SQ-96.strata" - m.write_bytes(b"x") - side = Path(td) / ling32_family.MTP_FILE - side.write_bytes(b"y") - return {**BASE, "args": ["--model", str(m), *BASE["args"][2:]]}, side - - def test_on_puts_the_sidecar_in_the_config_when_it_is_there(self): - with tempfile.TemporaryDirectory() as td: - base, side = self.with_sidecar(td) - cfg = R.derive_config(base, S.LaunchSettings(family="ling-3.2-air", mtp="on"), bool_flags=tune_knobs.BOOL_FLAGS, log="x.log") - self.assertEqual(cfg["ling32_mtp"], str(side)) - for flag in ("--mtp", "--spec", "--spec-adaptive"): - self.assertNotIn(flag, cfg["args"]) - self.assertNotIn("mtp", cfg) # Flash-Next's own key is never written for Ling - self.assertEqual(R.derive_config(base, S.LaunchSettings(family="ling-3.2-air"), bool_flags=tune_knobs.BOOL_FLAGS, log="x.log").get("ling32_mtp"), None) # nothing said: off for now - - def test_auto_and_on_write_the_mode_next_to_the_path_and_off_takes_both_out(self): - with tempfile.TemporaryDirectory() as td: - base, side = self.with_sidecar(td) - d = lambda **kw: R.derive_config(base, S.LaunchSettings(family="ling-3.2-air", **kw), bool_flags=tune_knobs.BOOL_FLAGS, log="x.log") - on, auto = d(mtp="on"), d(mtp="auto") - self.assertEqual((on["ling32_mtp"], on[ling32_family.MTP_MODE_KEY]), (str(side), "on")) # forced: --mtp FILE - self.assertEqual((auto["ling32_mtp"], auto[ling32_family.MTP_MODE_KEY]), (str(side), "auto")) # the engine decides: --mtp-auto FILE - for cfg in (on, auto): - for flag in ("--mtp", "--mtp-auto", "--spec", "--spec-adaptive"): - self.assertNotIn(flag, cfg["args"]) - off = R.derive_config({**base, "ling32_mtp": str(side), ling32_family.MTP_MODE_KEY: "auto"}, S.LaunchSettings(family="ling-3.2-air", mtp="off"), - bool_flags=tune_knobs.BOOL_FLAGS, log="x.log") - self.assertNotIn("ling32_mtp", off) - self.assertNotIn(ling32_family.MTP_MODE_KEY, off) - self.assertEqual(S.MTP_MODES, ("on", "off", "auto")) - - def test_off_takes_it_out_and_on_without_a_file_adds_nothing(self): - with tempfile.TemporaryDirectory() as td: - base, side = self.with_sidecar(td) - base = {**base, "ling32_mtp": str(side)} - off = R.derive_config(base, S.LaunchSettings(family="ling-3.2-air", mtp="off"), bool_flags=tune_knobs.BOOL_FLAGS, log="x.log") - self.assertNotIn("ling32_mtp", off) - side.unlink() - none = R.derive_config({k: v for k, v in base.items() if k != "ling32_mtp"}, S.LaunchSettings(family="ling-3.2-air", mtp="on"), bool_flags=tune_knobs.BOOL_FLAGS, log="x.log") - self.assertNotIn("ling32_mtp", none) - - def test_setup_is_told_and_a_changed_choice_runs_setup_again(self): - r = runner_for("ling-3.2-air", model="SQ-96", context=32768, vision="off", mtp="on") - r._catalog = mock.Mock() - r._catalog.resolve.side_effect = lambda model, fam: (fam, model) - r.feed = None - r.move_data = False - r.existing_data_dir = lambda: None - r.installed_card_args = lambda: [] - r.resolved_drafting = lambda fam: "off" # Flash-Next's drafting word must not decide for Ling - args = r.setup_args() - self.assertEqual(value(args, "--mtp"), "on") - self.assertTrue(R.desc_matches({"context": 32768, "images": "off", "mtp": "on"}, S.LaunchSettings(family="ling-3.2-air", context=32768, vision="off", mtp="on"))) - self.assertFalse(R.desc_matches({"context": 32768, "images": "off", "mtp": "off"}, S.LaunchSettings(family="ling-3.2-air", context=32768, vision="off", mtp="on"))) - self.assertTrue(R.desc_matches({"context": 32768, "images": "off", "mtp": "off"}, S.LaunchSettings(family="ling-3.2-air", context=32768, vision="off"))) # nothing said: as installed - - def test_the_notice_says_what_it_is_and_the_licence(self): - out = S.check_ling32(S.LaunchSettings(family="ling-3.2-air", mtp="on"), vram_gb=96, ram_gb=128) - text = " ".join(n.text for n in out) - self.assertIn("multi-token-prediction", text) - self.assertIn("several tokens per step", text) - self.assertIn("MIT", text) - self.assertIn("inclusionAI/Ling-3.2-air", text) - tiered = " ".join(n.text for n in S.check_ling32(S.LaunchSettings(family="ling-3.2-air", mtp="on"), vram_gb=8, ram_gb=16)) - self.assertIn("several tokens per step", tiered) - self.assertNotIn("4.3", text + tiered) - self.assertNotIn("break-even", text + tiered) - self.assertFalse(any("MTP" in n.text for n in S.check_ling32(S.LaunchSettings(family="ling-3.2-air"), vram_gb=96, ram_gb=128))) - other = S.check_ling32(S.LaunchSettings(family="qwen", mtp="on"), vram_gb=24, ram_gb=64) - self.assertEqual(other, []) # --mtp on is the Qwen draft layer's flag too: it says nothing about Ling there - - def test_the_launcher_says_nothing_extra_for_the_default_and_the_story_when_asked_for(self): - """On by default (tier A): part of the plan, no extra notice. Asked for by hand with --mtp on: what it is and the licence, in every tier. --mtp off: nothing.""" - text = lambda vram, ram, **kw: " ".join(n.text for n in S.check_ling32(S.LaunchSettings(family="ling-3.2-air", **kw), vram_gb=vram, ram_gb=ram)) - for vram, ram in ((96, 128), (24, 128), (24, 16)): - self.assertNotIn("multi-token", text(vram, ram)) - self.assertIn("multi-token", text(vram, ram, mtp="on")) - self.assertNotIn("multi-token", text(vram, ram, mtp="off")) - - def test_a_card_of_12_gb_or_less_says_why_when_mtp_is_asked_for(self): - text = lambda vram, **kw: " ".join(n.text for n in S.check_ling32(S.LaunchSettings(family="ling-3.2-air", **kw), vram_gb=vram, ram_gb=64)) - self.assertIn(ling32_fit.MTP_SMALL_CARD_NOTE, text(8, mtp="on")) - self.assertIn(ling32_fit.MTP_SMALL_CARD_NOTE, text(12, mtp="on")) - self.assertNotIn(ling32_fit.MTP_SMALL_CARD_NOTE, text(16, mtp="on")) - for vram in (8, 12, 16, 96): - self.assertNotIn("multi-token", text(vram)) # nothing said: no MTP text at all - self.assertNotIn("multi-token", text(vram, mtp="off")) - self.assertNotIn(ling32_fit.MTP_SMALL_CARD_NOTE, " ".join(n.text for n in S.check_ling32(S.LaunchSettings(family="ling-3.2-air", mtp="on"), vram_gb=8, ram_gb=64, unified=True))) - - def test_the_planner_counts_it_from_the_settings(self): - with_mtp = S.check_ling32(S.LaunchSettings(family="ling-3.2-air", mtp="on"), vram_gb=24, ram_gb=64) - self.assertTrue(with_mtp) - - -class Flags(unittest.TestCase): - def parse(self, *argv): - ap = argparse.ArgumentParser() - C.add_parsers(ap.add_subparsers(dest="cmd")) - return ap.parse_args(["launch", *argv]) - - def test_the_flags_parse(self): - a = self.parse("--family", "ling-3.2-air", "--thinking", "on", "--tier", "c", "--vram-budget-gib", "12", "--ram-budget-gib", "24.5", "--turbo-ssd", "--cpu-coexec", "4") - self.assertEqual((a.thinking, a.tier, a.vram_budget_gib, a.ram_budget_gib, a.turbo_ssd, a.cpu_coexec), ("on", "C", 12.0, 24.5, True, 4)) - b = self.parse("--tier", "AUTO") - self.assertEqual(b.tier, "auto") - self.assertFalse(self.parse().turbo_ssd) - - def test_bad_values_are_refused_in_plain_words(self): - for argv in (("--tier", "D"), ("--thinking", "maybe"), ("--vram-budget-gib", "0"), ("--vram-budget-gib", "lots")): - with self.assertRaises(SystemExit): - with mock.patch("sys.stderr"): - self.parse(*argv) - - def test_the_help_says_what_turbo_ssd_costs(self): - ap = argparse.ArgumentParser() - C.add_parsers(ap.add_subparsers(dest="cmd")) - sub = [a for a in ap._actions if isinstance(a, argparse._SubParsersAction)][0].choices["launch"] - self.assertIn("faster, may change answers", " ".join(sub.format_help().split())) - - def test_flags_text_is_copyable(self): - s = S.LaunchSettings(family="ling-3.2-air", model="SQ-96", thinking="on", tier="C", vram_budget=12.0, ram_budget=24.0, turbo_ssd=True) - text = S.flags_text(s) - for part in ("--thinking on", "--tier C", "--vram-budget-gib 12", "--ram-budget-gib 24", "--turbo-ssd"): - self.assertIn(part, text) - self.assertNotIn("--tier", S.flags_text(S.LaunchSettings(family="ling-3.2-air", model="SQ-96", tier="auto"))) - - def test_settings_round_trip_in_a_preset(self): - s = S.LaunchSettings(family="ling-3.2-air", thinking="on", tier="B", vram_budget=8.0, turbo_ssd=True) - back = S.LaunchSettings.from_dict(s.to_dict()) - self.assertEqual((back.thinking, back.tier, back.vram_budget, back.turbo_ssd), ("on", "B", 8.0, True)) - self.assertIsNone(S.LaunchSettings.from_dict({"family": "qwen"}).thinking) - - -class Notices(unittest.TestCase): - def test_a_ling_flag_on_another_model_is_said(self): - out = S.check_ling32(S.LaunchSettings(family="qwen", tier="C", turbo_ssd=True), vram_gb=24, ram_gb=64) - self.assertEqual(len(out), 1) - self.assertIn("--tier", out[0].text) - self.assertIn("Ling-3.2-Air only", out[0].text) - self.assertEqual(S.check_ling32(S.LaunchSettings(family="qwen"), vram_gb=24, ram_gb=64), []) - - def test_the_tier_and_its_speed_are_said_when_not_all_resident(self): - a = S.check_ling32(S.LaunchSettings(family="ling-3.2-air"), vram_gb=96, ram_gb=128) - self.assertEqual(a, []) - c = S.check_ling32(S.LaunchSettings(family="ling-3.2-air"), vram_gb=8, ram_gb=16) - self.assertEqual(len(c), 1) - self.assertIn("Memory tier C", c[0].text) - self.assertIn("slow", c[0].text) - b = S.check_ling32(S.LaunchSettings(family="ling-3.2-air"), vram_gb=24, ram_gb=96) - self.assertIn("Memory tier B", b[0].text) - - def test_turbo_ssd_says_faster_may_change_answers(self): - out = S.check_ling32(S.LaunchSettings(family="ling-3.2-air", turbo_ssd=True), vram_gb=8, ram_gb=16) - self.assertTrue(any("faster, may change answers" in n.text for n in out)) - none = S.check_ling32(S.LaunchSettings(family="ling-3.2-air", turbo_ssd=True), vram_gb=96, ram_gb=128) - self.assertTrue(any("changes nothing" in n.text for n in none)) - - def test_an_impossible_tier_is_a_warning_not_a_crash(self): - out = S.check_ling32(S.LaunchSettings(family="ling-3.2-air", tier="A"), vram_gb=24, ram_gb=64) - self.assertEqual(len(out), 1) - self.assertIn("--tier vram", out[0].text) - - def test_other_makes_of_card_are_told(self): - def words(vendor): - return " ".join(n.text for n in S.check_ling32(S.LaunchSettings(family="ling-3.2-air"), vram_gb=24, ram_gb=96, vendor=vendor)) - self.assertIn("tested on Radeon RX 9070 and Strix Halo", words("amd")) # AMD has an engine now: tested cards named, the rest "unverified" - self.assertNotIn("will not start", words("amd")) - self.assertIn("no Intel engine yet", words("intel")) - self.assertIn("128 GB or more", words("apple")) # a Mac keeps the whole model in memory: the recommendation, never a refusal - self.assertIn("none of them", words("someone-else")) - for vendor in ("nvidia", "cuda", None): - self.assertNotIn("Ling-3.2-Air on", words(vendor)) - self.assertNotIn("Ling-3.2-Air runs on", words(vendor)) - - def test_backends_flags_and_gfx_support(self): - self.assertEqual(ling32_family.BACKENDS, ("cuda", "hip", "metal")) - self.assertEqual(ling32_family.backend_of(), "cuda") - self.assertEqual(ling32_family.backend_of(hip=True), "hip") - self.assertEqual(ling32_family.backend_of(darwin=True), "metal") - self.assertEqual(ling32_family.backend_of(sycl=True), "sycl") - self.assertEqual(ling32_family.ENGINE_FLAGS["hip"], ["--graph"]) # not the NVIDIA-tuned --tc / --mla-kernel - self.assertEqual(ling32_family.ENGINE_FLAGS["metal"], []) - self.assertEqual(ling32_family.MTP_ENGINE_FLAGS["metal"], ling32_family.MTP_ENGINE_FLAGS["cuda"]) # one command line on every backend - self.assertEqual(ling32_family.hip_support("gfx1151:sramecc-:xnack-")[0], "tested") - self.assertEqual(ling32_family.hip_support("gfx1201")[0], "tested") - self.assertEqual(ling32_family.hip_support("gfx1100")[0], "compiled") - self.assertEqual(ling32_family.hip_support("gfx1031")[0], "compiled") - self.assertEqual(ling32_family.hip_support("gfx906")[0], "unsupported") # an Instinct MI50 / Radeon VII (gfx906): no engine code - self.assertEqual(ling32_family.hip_support(None)[0], "unsupported") - - def test_the_default_context_is_128k_like_every_model(self): - self.assertEqual(ling32_family.DEFAULT_CONTEXT, 131072) - self.assertEqual(ling32_fit.plan(24, 96)["ctx"], 131072) - - def test_parallel_is_one(self): - self.assertEqual(S.max_parallel("ling-3.2-air"), 1) - out = S.check_parallel(S.LaunchSettings(family="ling-3.2-air", parallel=4), vram_gb=24) - self.assertEqual(len(out), 1) - self.assertIn("one request at a time", out[0].text) - - -class CatalogAndRows(unittest.TestCase): - def setUp(self): - self._env = mock.patch.dict(os.environ, {"STRATA_LING32_SHOW": "1"}) - self._env.start() - self.addCleanup(self._env.stop) - - def test_catalog_resolve_and_names_include_ling(self): - from strata_cli.launch.catalog import Catalog - with tempfile.TemporaryDirectory() as d: - cat = Catalog(src=Path(__file__).resolve().parents[2], root=Path(d)) - self.assertEqual(cat.resolve("SQ-96", "ling-3.2-air"), ("ling-3.2-air", "SQ-96")) - self.assertEqual(cat.model_name_of("ling-3.2-air", "SQ-96"), "ling-3.2-air-sq-96") - self.assertEqual(cat.tag_of("ling-3.2-air", "SQ-96"), "ling-3.2-air-sq-96") - self.assertEqual(cat.model_folder(Path(d), "ling-3.2-air", "SQ-96"), Path(d) / "models" / "ling-3.2-air") - self.assertEqual(cat.contexts_for("ling-3.2-air"), ling32_family.CONTEXTS) - self.assertAlmostEqual(cat.kv_gb(131072, family="ling-3.2-air"), 131072 * 16128 / 1e9) - - def test_the_model_list_has_the_one_ling_size(self): - from tools import strata_mcp # noqa: F401 (the install tool the catalog reads) - from strata_cli.launch.catalog import Catalog - with tempfile.TemporaryDirectory() as d: - cat = Catalog(src=Path(__file__).resolve().parents[2], root=Path(d)) - _models, families, _ctx, _src = cat.tables() - self.assertIn("ling-3.2-air", families) - self.assertTrue(families["ling-3.2-air"].get("ling32")) - size = cat.strata.own_size("ling-3.2-air", "SQ-96") - self.assertEqual(size["download_gb"], 88.7) # the model, the Vision shard and the MTP sidecar - self.assertTrue(size["vision"]) - row = cat.strata.ling32_fit_row("SQ-96", 16.0, [{"vram_gb": 8.0}]) - self.assertEqual(row["tier"], "C") - self.assertEqual(row["mode"], "cross_tier_ssd") - self.assertEqual(cat.strata.ling32_fit_row("SQ-96", 128.0, [{"vram_gb": 96.0}])["mode"], "ram_vram_zero_ssd") - - -class FamilyData(unittest.TestCase): - def test_files_sizes_and_sources(self): - self.assertEqual(ling32_family.size_of("Ling-3.2-Air-SQ-96.strata"), 86_845_456_384) - self.assertEqual(ling32_family.size_of("Ling-3.2-Air-Vision.strata"), 869_351_424) - self.assertEqual(ling32_family.sha256_of("Ling-3.2-Air-SQ-96.strata"), "856c29768eda280d7a2b29e593e8c74188d6e4b34aab73bc698a47e14fb06be1") - self.assertEqual(ling32_family.size_of("Ling-3.2-Air-MTP.strata"), 990_724_096) - self.assertEqual(ling32_family.sha256_of("Ling-3.2-Air-MTP.strata"), "049a033704ea10716521759387fafca84527fb1157e19cff478a3f7d5a34089d") - self.assertEqual(ling32_family.files_of(), ["Ling-3.2-Air-SQ-96.strata", "Ling-3.2-Air-Vision.strata", "Ling-3.2-Air-MTP.strata"]) # pictures and MTP are on by default - self.assertEqual(ling32_family.files_of(vision=False, mtp=False), ["Ling-3.2-Air-SQ-96.strata"]) - self.assertEqual(ling32_family.files_of(mtp=False), ["Ling-3.2-Air-SQ-96.strata", "Ling-3.2-Air-Vision.strata"]) - self.assertEqual(ling32_family.files_of("SQ-96", True, True), ["Ling-3.2-Air-SQ-96.strata", "Ling-3.2-Air-Vision.strata", "Ling-3.2-Air-MTP.strata"]) - self.assertEqual(ling32_family.model_key(), "ling-3.2-air-sq-96") - self.assertEqual(ling32_family.build_of_model_name("ling-3.2-air"), "SQ-96") - self.assertIsNone(ling32_family.build_of_model_name("hy4-flash-sq-96")) - - def test_the_mtp_sidecar_data(self): - self.assertEqual(ling32_family.MTP_FILE, "Ling-3.2-Air-MTP.strata") - self.assertFalse(hasattr(ling32_family, "MTP_S4_FILE")) # no S4 variant ships (L32-MTP: +0.66 GB for 0.6 points of acceptance) - self.assertIs(ling32_family.DEFAULT_MTP, True) # the owner's decision (2026-12-01): on by default, in tier A; --mtp off turns it off - self.assertFalse(hasattr(ling32_family, "DEFAULT_DRAFTER") or hasattr(ling32_family, "DRAFTERS")) # no DFly for Ling - self.assertEqual(ling32_family.MTP_PINS, {ling32_family.MTP_FILE: (990_724_096, "049a033704ea10716521759387fafca84527fb1157e19cff478a3f7d5a34089d")}) - self.assertEqual(ling32_family.mtp_pin(ling32_family.MTP_FILE), (990_724_096, "049a033704ea10716521759387fafca84527fb1157e19cff478a3f7d5a34089d")) - self.assertEqual(ling32_fit.MTP_SIDECAR_BYTES, 990_724_096) - self.assertEqual(ling32_family.FILES[ling32_family.MTP_FILE], ling32_family.MTP_PINS[ling32_family.MTP_FILE]) # in the download set, the one pin - self.assertEqual(ling32_family.files_of(vision=False, mtp=False), [ling32_family.MODEL_FILE]) - lic = ling32_family.mtp_license(None) - self.assertEqual(lic["spdx"], "MIT") - self.assertIn("inclusionAI/Ling-3.2-air", lic["attribution"]) - self.assertIn("ff099487f6f57165e6fa9386ad61fddfafc78b76", lic["attribution"]) - self.assertIn("MIT", ling32_family.LICENSE_NOTE) # shown where the model's licence is shown - - def test_the_licence_of_a_file_that_cannot_be_read_is_the_family_words(self): - with tempfile.TemporaryDirectory() as d: - f = Path(d) / ling32_family.MTP_FILE - f.write_bytes(b"not a strata file") - self.assertEqual(ling32_family.mtp_license(f), ling32_family.mtp_license(None)) - - def test_find_mtp_takes_only_the_pinned_size(self): - with tempfile.TemporaryDirectory() as d: - model = Path(d) / ling32_family.MODEL_FILE - self.assertIsNone(ling32_family.find_mtp(model)) - (Path(d) / ling32_family.MTP_FILE).write_bytes(b"a part of it") - self.assertIsNone(ling32_family.find_mtp(model)) # not the pinned size: a cut-off copy is not used - with mock.patch.dict(ling32_family.MTP_PINS, {ling32_family.MTP_FILE: (12, "0" * 64)}): - self.assertEqual(ling32_family.find_mtp(model).name, ling32_family.MTP_FILE) - self.assertEqual(ling32_family.find_mtp(None, [d]).name, ling32_family.MTP_FILE) - with mock.patch.dict(ling32_family.MTP_PINS, {}, clear=True): # nothing pinned: used where it is - self.assertEqual(ling32_family.find_mtp(model).name, ling32_family.MTP_FILE) - - def test_the_mac_memory_floor_is_one_constant_and_the_texts_follow_it(self): - self.assertEqual(ling32_family.METAL_MIN_RAM_GIB, 120.0) # owner decision pending (recommended 128 GB, 2026-12-02) - self.assertEqual(ling32_family.metal_min_ram_words(), "128 GB") - with mock.patch.object(ling32_family, "METAL_MIN_RAM_GIB", 96.0): - self.assertEqual(ling32_family.metal_min_ram_words(), "96 GB") - apple = " ".join(n.text for n in S.check_ling32(S.LaunchSettings(family="ling-3.2-air"), vram_gb=None, ram_gb=96, vendor="apple")) - self.assertIn("96 GB", apple) - apple = " ".join(n.text for n in S.check_ling32(S.LaunchSettings(family="ling-3.2-air"), vram_gb=None, ram_gb=128, vendor="apple")) - self.assertIn("128 GB", apple) - - def test_a_small_mac_gets_a_warning_and_is_started_anyway(self): - want = "Ling runs best on a Mac with 128 GB or more; with less memory it may not load or be very slow." - self.assertEqual(ling32_family.metal_ram_advice(), want) - for ram, low in ((64, True), (96, True), (119.9, True), (120, False), (128, False), (None, False), (0, False)): - self.assertEqual(ling32_family.metal_ram_below_advice(ram), low, ram) - notes = S.check_ling32(S.LaunchSettings(family="ling-3.2-air"), vram_gb=None, ram_gb=ram, vendor="apple") - apple = [n for n in notes if "on a Mac" in n.text] - self.assertEqual(len(apple), 1) - self.assertIn(want, apple[0].text) - self.assertEqual("started anyway" in apple[0].next, low, ram) - self.assertEqual([n for n in notes if "Memory tier" in n.text or "cannot" in n.text.lower()], [], ram) # none of the PC tier notices, no refusal - - def test_the_mac_engine_says_it_in_plain_words_and_the_text_follows_the_constant(self): - src = (Path(__file__).resolve().parents[3] / "engine" / "src" / "ling32" / "metal" / "ling32_metal_main.cpp").read_text(encoding="utf-8") - self.assertIn(f"Ling runs best on a Mac with {ling32_family.metal_min_ram_words()} or more; with less memory it may not load or be very slow", src) - self.assertIn("std::atexit(loading_failed_note)", src) # the runtime's exit(4) is followed by the plain note - self.assertIn("g_loading = false; // the model and the engine buffers are made", src) - - def test_the_release_is_one_word_in_the_shipped_sources_file(self): - import json as _json - with tempfile.TemporaryDirectory() as d: - f = Path(d) / "ling32-sources.json" - src = [{"kind": "http-parts", "base": "https://huggingface.co/strata-engine/Ling-3.2-Air-Strata/resolve/main"}] - f.write_text(_json.dumps({"released": False, "sources": src}), encoding="utf-8") - self.assertFalse(ling32_family.released(f)) - self.assertEqual(ling32_family.sources(env={}, shipped=f), []) # prepared but ignored - f.write_text(_json.dumps({"released": True, "sources": src}), encoding="utf-8") - self.assertTrue(ling32_family.released(f)) - self.assertEqual([(s["kind"], s["base"]) for s in ling32_family.sources(env={}, shipped=f)], [("http-parts", src[0]["base"])]) - f.write_text(_json.dumps({"sources": src}), encoding="utf-8") # no word: not released - self.assertFalse(ling32_family.released(f)) - self.assertEqual(ling32_family.sources(env={}, shipped=f), []) - f.write_text(_json.dumps({"released": "yes", "sources": src}), encoding="utf-8") # only the real true counts - self.assertFalse(ling32_family.released(f)) - f.write_text("not json", encoding="utf-8") - self.assertFalse(ling32_family.released(f)) - # a source set by hand works before the release, and comes first - f.write_text(_json.dumps({"released": True, "sources": src}), encoding="utf-8") - got = ling32_family.sources(env={ling32_family.SOURCE_ENV: "https://r2.example/x"}, shipped=f) - self.assertEqual([s["base"] for s in got], ["https://r2.example/x", src[0]["base"]]) - shipped = _json.loads(ling32_family.SOURCES_FILE.read_text(encoding="utf-8")) - self.assertIs(shipped["released"], False) # the file in the repository is not released - self.assertEqual(shipped["sources"][0]["base"], "https://huggingface.co/strata-engine/Ling-3.2-Air-Strata/resolve/main") - self.assertEqual(ling32_family.sources(env={}), []) # so nothing is offered by default - - def test_the_intel_switch_turns_the_no_engine_warning_into_the_normal_flow(self): - def intel_notes(): - return " ".join(n.text for n in S.check_ling32(S.LaunchSettings(family="ling-3.2-air"), vram_gb=16.0, ram_gb=64.0, vendor="intel")) - self.assertFalse(ling32_family.sycl_available()) # until L32-SYCL's package is in the feed - self.assertIn("no Intel engine yet", intel_notes()) - with mock.patch.object(ling32_family, "SYCL_ENGINE_SHIPPED", True): - self.assertTrue(ling32_family.sycl_available()) - self.assertNotIn("no Intel engine yet", intel_notes()) - def notes(name, mtp=None): - return S.check_ling32(S.LaunchSettings(family="ling-3.2-air", mtp=mtp), vram_gb=16.0, ram_gb=64.0, vendor="intel", cards=[{"vendor": "intel", "name": name}]) - b70 = notes("Intel Arc Pro B70 Graphics") - self.assertEqual([n for n in b70 if "on Intel Arc:" in n.text], []) # the tested card: no card line - self.assertEqual(len([n for n in b70 if "without MTP" in n.text]), 1) # MTP is not verified on Intel: said once - self.assertEqual([n for n in notes("Intel Arc Pro B70 Graphics", mtp="on") if "without MTP" in n.text], []) - a750 = notes("Intel Arc A750 Graphics") - self.assertEqual(len([n for n in a750 if "on Intel Arc:" in n.text]), 1) - self.assertIn("not run on it", " ".join(n.text for n in a750)) - self.assertIn("sycl", ling32_family.ENGINE_FLAGS) - self.assertIn("sycl", ling32_family.MTP_ENGINE_FLAGS) - self.assertEqual(ling32_family.backend_of(sycl=True), "sycl") - - def test_128k_is_the_default_context_everywhere(self): - from strata_control import default_context - self.assertEqual(ling32_family.DEFAULT_CONTEXT, 131072) - self.assertEqual(ling32_fit.DEFAULT_CONTEXT, default_context.DEFAULT_CONTEXT) - self.assertEqual(default_context.pick(ling32_family.CONTEXTS), 131072) - self.assertEqual(ling32_fit.plan(96.0, 128.0)["ctx"], 131072) # the planner with no context asked for - self.assertEqual(S.parse_context("128k"), 131072) - - def test_old_nvidia_cards_get_one_honest_line_and_no_switch(self): - def notes(cards, vendor="nvidia"): - return S.check_ling32(S.LaunchSettings(family="ling-3.2-air"), vram_gb=8.0, ram_gb=64.0, vendor=vendor, cards=cards) - pascal = {"name": "GeForce GTX 1070 Ti", "arch": 61, "vendor": "nvidia"} - volta = {"name": "Tesla V100-SXM2-32GB", "arch": "sm_70", "vendor": "nvidia"} - for cards in ([pascal], [volta], [pascal, volta], [{"name": "Tesla P100", "arch": "6.0"}]): - lines = [n for n in notes(cards) if "tensor cores" in n.text] - self.assertEqual(len(lines), 1, cards) - self.assertIn("plain kernels", lines[0].text) - self.assertNotIn("experimental", lines[0].text.lower() + lines[0].next.lower()) # no opt-in word: it starts as it is - self.assertEqual(lines[0].level, "warn") # a line, never an error - self.assertNotRegex(lines[0].text + lines[0].next, r"\d+(\.\d+)? ?tok") # no speed number in the text - self.assertIn("GTX 1070 Ti", [n for n in notes([pascal, volta]) if "tensor cores" in n.text][0].text) - for cards in ([], None, [{"name": "RTX 3060", "arch": 86}], [{"name": "RTX 2080 Ti", "arch": 75}], [{"name": "Radeon", "arch": 61, "vendor": "amd"}]): - self.assertEqual([n for n in notes(cards) if "tensor cores" in n.text], [], cards) - self.assertEqual([n for n in notes([pascal], vendor="amd") if "tensor cores" in n.text], []) - - def test_the_part_helpers_size_resume_and_append(self): - self.assertEqual(ling32_family.part_sizes(20480, 8192), [8192, 8192, 4096]) - self.assertEqual(ling32_family.part_sizes(8192, 8192), [8192]) - real = ling32_family.part_sizes(ling32_family.FILES[ling32_family.MODEL_FILE][0]) - self.assertEqual((len(real), real[0], sum(real)), (2, ling32_family.PART_BYTES, ling32_family.FILES[ling32_family.MODEL_FILE][0])) # 42 GiB and the rest, as uploaded - with tempfile.TemporaryDirectory() as d: - j = Path(d) / "m.joining" - sizes = [8192, 8192, 4096] - self.assertEqual(ling32_family.join_resume(j, sizes), 0) # no file - j.write_bytes(b"a" * (8192 + 100)) - self.assertEqual(ling32_family.join_resume(j, sizes), 1) # a part was being appended: cut back to the whole part - self.assertEqual(j.stat().st_size, 8192) - j.write_bytes(b"a" * 20480) - self.assertEqual(ling32_family.join_resume(j, sizes), 3) # all parts in - j.write_bytes(b"a" * 20481) - self.assertEqual(ling32_family.join_resume(j, sizes), 0) # longer than the file can be: not ours, removed - self.assertFalse(j.exists()) - j.write_bytes(b"a" * 50) - self.assertEqual(ling32_family.join_resume(j, sizes), 0) # not even the first part: removed - self.assertFalse(j.exists()) - p = Path(d) / "p" - p.write_bytes(b"xyz" * 10) - self.assertEqual(ling32_family.append_part(j, p, chunk=7), 30) - self.assertEqual(ling32_family.append_part(j, p, chunk=7), 30) - self.assertEqual(j.read_bytes(), b"xyz" * 20) - - def test_nothing_is_published_by_default(self): - self.assertEqual(ling32_family.sources(env={}), []) - got = ling32_family.sources(env={"STRATA_LING32_SOURCE": "https://example.invalid/m/"}) - self.assertEqual(got[0]["base"], "https://example.invalid/m") - self.assertEqual(ling32_family.urls_for("Ling-3.2-Air-SQ-96.strata", got[0]), ["https://example.invalid/m/Ling-3.2-Air-SQ-96.strata"]) - self.assertEqual(ling32_family.sources(env={}, cfg={"ling32_source": "ftp://x"}), []) - shipped = (Path(__file__).resolve().parents[2] / "data" / "ling32-sources.json").read_text(encoding="utf-8") - self.assertIn('"released": false', shipped) # the release switch: not released, so the prepared sources are ignored - hf_base = "https://huggingface.co/strata-engine/Ling-3.2-Air-Strata/resolve/main" # the one prepared source: the (private until the release) Hugging Face repo, no key or other host - self.assertEqual(shipped.count(hf_base), 1) - body = shipped.lower().replace(hf_base.lower(), "").replace('"http-parts"', "").replace('"note"', "") - import json as _json - self.assertEqual(_json.loads(shipped)["sources"], [{"kind": "http-parts", "base": hf_base}]) - for secret in ("http", "key", "token", "secret"): - self.assertNotIn(f'"{secret}', body) - - def test_local_files_need_the_pinned_size(self): - with tempfile.TemporaryDirectory() as d: - (Path(d) / "Ling-3.2-Air-SQ-96.strata").write_bytes(b"short") - self.assertEqual(ling32_family.local_files(d), {}) - - def test_manifest_words_name_the_family_before_the_size_guess(self): - from strata_control import strata_manifest as M - self.assertEqual(M.family_from_hints("Ling-3.2-Air-SQ-96.strata", 86_845_456_384), "ling-3.2-air") # not HY-4 Flash, whose size class it shares - self.assertEqual(M.family_from_hints("Hy4-Flash-SQ-96.strata", 89_577_742_336), "hy4-flash") - self.assertEqual(M.family_of_manifest({"strata_family": "bailing_moe_v3", "config": {"model_type": "bailing_moe_v3_vl"}}), "ling-3.2-air") - self.assertEqual(M.family_of_manifest({"arch": "ling32"}), "ling-3.2-air") - - -if __name__ == "__main__": - unittest.main() +"""`strata launch` for Ling-3.2-Air: its engine is the component strata-ling32 (shape "ling32"), the Flash-Next steps leave it alone, and the flags +--thinking / --tier / --turbo-ssd / --vram-budget-gib / --ram-budget-gib / --cpu-coexec reach the run config the way the engine and serve read them +(strata_cli/launch/{cmd,runner,settings}.py, strata_control/ling32_family.py and ling32_fit.py).""" + +from __future__ import annotations + +import argparse +import os +import tempfile +import unittest +from pathlib import Path +from unittest import mock + +from strata_cli.launch import cmd as C +from strata_cli.launch import runner as R +from strata_cli.launch import settings as S +from strata_control import ling32_family, ling32_fit, tune_knobs + +BASE = {"exe": "component:strata-ling32", "arch": "ling32", "model_name": "ling-3.2-air-sq-96", "port": 8095, "drafting": "off", "thinking": "off", + "args": ["--model", "C:/m/Ling-3.2-Air-SQ-96.strata", "--ctx", "32768", "--chunk", "256", "--tc", "16", "--tc-moe", "128", "--graph", "--mla-kernel", "simt"]} + + +def runner_for(family: str | None, **kw) -> R.Runner: + r = object.__new__(R.Runner) + r.s = S.LaunchSettings(family=family, **kw) + return r + + +def derive(**kw) -> dict: + return R.derive_config(BASE, S.LaunchSettings(family="ling-3.2-air", port=8123, **kw), bool_flags=tune_knobs.BOOL_FLAGS, log="x.log") + + +def value(args, flag): + return args[args.index(flag) + 1] if flag in args and args.index(flag) + 1 < len(args) else None + + +class Which(unittest.TestCase): + def test_the_shape_is_ling32_only_for_ling(self): + self.assertEqual(runner_for("ling-3.2-air").model_shape(), "ling32") + self.assertTrue(runner_for("ling-3.2-air").is_ling32()) + self.assertTrue(runner_for("ling-3.2-air").is_native_strata_family()) + self.assertFalse(runner_for("qwen").is_ling32()) + self.assertFalse(runner_for("hy4-flash").is_ling32()) + with mock.patch.object(R.Runner, "catalog", create=True) as cat: + cat.strata.setup_module.return_value = mock.Mock(FAMILIES={"qwen": {}}, LING32_FAMILIES={"ling-3.2-air": {"title": "inclusionAI Ling-3.2-Air"}}, HY4_FAMILIES={}, INKLING_FAMILIES={}) + self.assertEqual(runner_for("ling-3.2-air").model_title(), "inclusionAI Ling-3.2-Air") + + def test_the_shape_engine_is_a_known_component(self): + from strata_control import shape_engine, updater + self.assertEqual(shape_engine.component_id("ling32"), "strata-ling32") + self.assertIn("ling32", shape_engine.CUSTOM_SHAPES) + self.assertEqual(shape_engine.exe_name("ling32", target="linux-x86_64"), "strata-ling32") + self.assertEqual(shape_engine.exe_name("ling32", target="windows-x86_64"), "strata-ling32.exe") + self.assertEqual(updater._config_component_id(BASE), "strata-ling32") + self.assertEqual(updater._config_component_id({"exe": "component:strata-engine", "arch": "ling32", "args": []}), "strata-ling32") + self.assertEqual(updater._config_component_id({"args": ["--model", "C:/m/Ling-3.2-Air-SQ-96.strata"]}), "strata-ling32") + self.assertEqual(updater._config_component_id({"args": ["--native", "C:/m/Hy4-Flash-SQ-64.strata"]}), "strata-hy4") + + +class EngineVersion(unittest.TestCase): + """Control installs the engine component only after `strata-ling32 --version` names itself (shape_engine._test_start; `strata-ling32 0.2.24` is what L32-SPEC's aa648c8b8 prints).""" + + def start(self, stdout: str, code: int = 0): + import subprocess + from strata_control import shape_engine + done = mock.Mock(stdout=stdout, stderr="", returncode=code) + with mock.patch.object(subprocess, "run", return_value=done) as run: + result = shape_engine._test_start(Path("/x/strata-ling32"), shape="ling32") + self.assertEqual(run.call_args[0][0][1:], ["--version"]) + return result + + def test_the_engine_that_names_itself_is_accepted(self): + self.assertEqual(self.start("strata-ling32 0.2.24\n"), (True, "strata-ling32 0.2.24")) + + def test_another_program_or_a_failure_is_refused(self): + from strata_control import shape_engine + self.assertEqual(self.start("strata-hy4 0.2.24\n"), (False, shape_engine.NO_SHAPE_ANSWER)) + self.assertEqual(self.start("strata 0.2.24\n"), (False, shape_engine.NO_SHAPE_ANSWER)) + ok, why = self.start("strata-ling32: unknown option --version\n", code=2) # an engine before --version (f-ling32-int-serve 8735db1ab) + self.assertFalse(ok) + self.assertTrue(why) + + +class Steps(unittest.TestCase): + def test_the_flash_next_steps_are_skipped(self): + r = runner_for("ling-3.2-air") + self.assertIsNone(r.ensure_drafter(Path("x.json"))) + self.assertEqual(r.fetch_missing_drafter(Path("x.json")), Path("x.json")) + with mock.patch.object(R.Runner, "stop_own_server_for_tuning") as stop, mock.patch.object(R.Runner, "emit"): + r.tune() + stop.assert_not_called() + self.assertTrue(r.drafting_plan_line().startswith("Drafting: MTP sidecar")) # its own MTP sidecar, not a Flash-Next drafter + + def test_the_setup_arguments_carry_no_flash_next_flags(self): + r = runner_for("ling-3.2-air", model="SQ-96", context=32768, kv="int8", vision="off") + r._catalog = mock.Mock() + r._catalog.resolve.side_effect = lambda model, fam: (fam, model) + r.feed = None + r.move_data = False + r.existing_data_dir = lambda: None + r.installed_card_args = lambda: [] + args = r.setup_args() + self.assertEqual(value(args, "--family"), "ling-3.2-air") + for flag in ("--mtp", "--drafter", "--draft-vocab"): + self.assertNotIn(flag, args) + + +class Config(unittest.TestCase): + def test_derive_config_keeps_the_engine_and_its_arguments(self): + cfg = derive() + self.assertEqual(cfg["exe"], "component:strata-ling32") + self.assertEqual(cfg["arch"], "ling32") + self.assertEqual(cfg["port"], 8123) + for flag in ("--model", "--ctx", "--chunk", "--tc", "--tc-moe", "--graph", "--mla-kernel"): + self.assertIn(flag, cfg["args"]) + for flag in ("--tier", "--turbo-ssd", "--vram-budget-gib", "--ram-budget-gib", "--cpu-coexec", "--spec", "--mtp", "--draft", "--batch"): + self.assertNotIn(flag, cfg["args"]) # nothing the person did not ask for: the engine plans by itself + self.assertNotIn("mtp", cfg) + self.assertEqual(cfg["thinking"], "off") + + def test_thinking_goes_to_the_config_not_to_the_engine(self): + cfg = derive(thinking="on") + self.assertEqual(cfg["thinking"], "on") + self.assertNotIn("--thinking", cfg["args"]) + self.assertEqual(derive(thinking="off")["thinking"], "off") + + def test_tier_and_budgets_become_engine_flags(self): + cfg = derive(tier="C", vram_budget=10.0, ram_budget=16.0) + self.assertEqual(value(cfg["args"], "--tier"), "nvme") + self.assertEqual(value(cfg["args"], "--vram-budget-gib"), "10") + self.assertEqual(value(cfg["args"], "--ram-budget-gib"), "16") + self.assertNotIn("--turbo-ssd", cfg["args"]) + self.assertEqual(value(derive(tier="A")["args"], "--tier"), "vram") + self.assertEqual(value(derive(tier="B")["args"], "--tier"), "hybrid") + self.assertNotIn("--tier", derive(tier="auto")["args"]) + + def test_turbo_ssd_is_opt_in_and_only_then_present(self): + self.assertNotIn("--turbo-ssd", derive()["args"]) + self.assertIn("--turbo-ssd", derive(tier="C", turbo_ssd=True)["args"]) + + def test_cpu_coexec_comes_through_the_advanced_table(self): + cfg = derive(extra={"--cpu-coexec": "4"}) + self.assertEqual(value(cfg["args"], "--cpu-coexec"), "4") + + def test_prefetch_keeps_its_word(self): + # found on the real engine (z440 smoke, case b): `--set prefetch=on` used to become a bare --prefetch that swallowed the next flag ("unknown option hybrid") + args = derive(tier="B", extra={"--prefetch": "on"})["args"] + self.assertEqual(value(args, "--prefetch"), "on") + self.assertEqual(value(args, "--tier"), "hybrid") + self.assertEqual(value(derive(extra={"--prefetch": "off"})["args"], "--prefetch"), "off") # the engine's own word: --prefetch off turns the lookahead prefetch off + + def test_a_tier_of_an_earlier_run_is_replaced_not_doubled(self): + base = {**BASE, "args": BASE["args"] + ["--tier", "hybrid"]} + cfg = R.derive_config(base, S.LaunchSettings(family="ling-3.2-air", tier="C"), bool_flags=tune_knobs.BOOL_FLAGS, log="x.log") + self.assertEqual(cfg["args"].count("--tier"), 1) + self.assertEqual(value(cfg["args"], "--tier"), "nvme") + + def test_other_families_ignore_the_ling_choices(self): + base = {"exe": "component:strata-hy4", "arch": "hy4flash", "model_name": "hy4-flash-sq-64", "port": 8095, "drafting": "off", "args": ["--native", "a.strata"]} + cfg = R.derive_config(base, S.LaunchSettings(family="hy4-flash", tier="C", thinking="on", turbo_ssd=True), bool_flags=tune_knobs.BOOL_FLAGS, log="x.log") + self.assertNotIn("--tier", cfg["args"]) + self.assertNotIn("--turbo-ssd", cfg["args"]) + self.assertNotIn("thinking", cfg) + + +VBASE = {**BASE, "args": BASE["args"] + ["--vision", "C:/m/Ling-3.2-Air-Vision.strata"]} + + +class Pictures(unittest.TestCase): + """Picture input (L32-VISION): the Vision shard is in the run config's engine arguments by default; --vision off takes it out, gpu / cpu name the encoder's device.""" + + def test_apply_choices_uses_ctx_and_the_vision_flags_not_hy4s(self): + out = R.apply_choices(VBASE, S.LaunchSettings(family="ling-3.2-air", context=65536)) + self.assertEqual(value(out["args"], "--ctx"), "65536") + self.assertNotIn("--max-context", out["args"]) # the engine would refuse it + self.assertIn("--vision", out["args"]) + off = R.apply_choices({**VBASE, "args": VBASE["args"] + ["--vision-device", "gpu", "--vision-max-pixels", "1000000"]}, S.LaunchSettings(family="ling-3.2-air", vision="off")) + self.assertNotIn("--vision", off["args"]) + self.assertNotIn("--vision-device", off["args"]) + self.assertNotIn("--vision-max-pixels", off["args"]) # the CPU encoder's pixel cap goes with the pictures (an engine without pictures does not know the flag) + self.assertNotIn("C:/m/Ling-3.2-Air-Vision.strata", off["args"]) + self.assertEqual(value(R.apply_choices(VBASE, S.LaunchSettings(family="ling-3.2-air", vision="cpu"))["args"], "--vision-device"), "cpu") + self.assertNotIn("--vision-device", R.apply_choices(BASE, S.LaunchSettings(family="ling-3.2-air", vision="cpu"))["args"]) # no shard, no device word + + def test_derive_config_keeps_the_shard_by_default_and_follows_the_choice(self): + base = derive_with(VBASE, S.LaunchSettings(family="ling-3.2-air")) + self.assertEqual(value(base["args"], "--vision"), "C:/m/Ling-3.2-Air-Vision.strata") + self.assertNotIn("--vision-device", base["args"]) + self.assertEqual(value(derive_with(VBASE, S.LaunchSettings(family="ling-3.2-air", vision="gpu"))["args"], "--vision-device"), "gpu") + self.assertEqual(value(derive_with(VBASE, S.LaunchSettings(family="ling-3.2-air", vision="on"))["args"], "--vision"), "C:/m/Ling-3.2-Air-Vision.strata") + off = derive_with(VBASE, S.LaunchSettings(family="ling-3.2-air", vision="off"))["args"] + self.assertNotIn("--vision", off) + + def test_setup_is_told_the_picture_word(self): + self.assertEqual(runner_with_vision("on").vision_word(), "yes") + self.assertEqual(runner_with_vision("gpu").vision_word(), "gpu") # the encoder's device reaches setup for Ling + self.assertEqual(runner_with_vision("cpu").vision_word(), "cpu") + self.assertEqual(runner_with_vision("off").vision_word(), "no") + + def test_pictures_are_on_when_nobody_chose(self): + r = runner_for("ling-3.2-air") + r._catalog = mock.Mock() + row = mock.Mock(images=True, family="ling-3.2-air", model="SQ-96", custom=False) + r._catalog.rows.return_value = [row] + r.s.model = "SQ-96" + self.assertEqual(r.resolved_vision(), "on") + r2 = runner_for("ling-3.2-air", model="SQ-96") + r2._catalog = mock.Mock() + r2._catalog.rows.return_value = [mock.Mock(images=False, family="ling-3.2-air", model="SQ-96", custom=False)] + self.assertEqual(r2.resolved_vision(), "off") + + def test_the_catalog_says_pictures_work_for_ling(self): + from strata_cli.launch.catalog import Catalog + with tempfile.TemporaryDirectory() as d: + cat = Catalog(src=Path(__file__).resolve().parents[2], root=Path(d)) + self.assertEqual(cat.picture_default(True, "ling-3.2-air"), "on") + self.assertEqual(cat.reader_state("ling-3.2-air"), "present") + self.assertFalse(cat.pictures_not_on_card("ling-3.2-air")) + + +def derive_with(base: dict, s) -> dict: + return R.derive_config(base, s, bool_flags=tune_knobs.BOOL_FLAGS, log="x.log") + + +def runner_with_vision(word: str) -> R.Runner: + r = runner_for("ling-3.2-air", model="SQ-96", vision=word) + r._catalog = mock.Mock() + return r + + +class Mtp(unittest.TestCase): + """`--mtp on|off` for Ling-3.2-Air: the sidecar's path is the run config's key `ling32_mtp` (serve makes `--mtp FILE --spec mtp --spec-adaptive` from it); the flags never sit in the arguments, + where Control would read `--mtp ` as Flash-Next's draft layer.""" + + def setUp(self): # the test sidecars are a few bytes: no pin to check them against + patcher = mock.patch.dict(ling32_family.MTP_PINS, {}, clear=True) + patcher.start() + self.addCleanup(patcher.stop) + + def with_sidecar(self, td: str): + m = Path(td) / "Ling-3.2-Air-SQ-96.strata" + m.write_bytes(b"x") + side = Path(td) / ling32_family.MTP_FILE + side.write_bytes(b"y") + return {**BASE, "args": ["--model", str(m), *BASE["args"][2:]]}, side + + def test_on_puts_the_sidecar_in_the_config_when_it_is_there(self): + with tempfile.TemporaryDirectory() as td: + base, side = self.with_sidecar(td) + cfg = R.derive_config(base, S.LaunchSettings(family="ling-3.2-air", mtp="on"), bool_flags=tune_knobs.BOOL_FLAGS, log="x.log") + self.assertEqual(cfg["ling32_mtp"], str(side)) + for flag in ("--mtp", "--spec", "--spec-adaptive"): + self.assertNotIn(flag, cfg["args"]) + self.assertNotIn("mtp", cfg) # Flash-Next's own key is never written for Ling + self.assertEqual(R.derive_config(base, S.LaunchSettings(family="ling-3.2-air"), bool_flags=tune_knobs.BOOL_FLAGS, log="x.log").get("ling32_mtp"), None) # nothing said: off for now + + def test_auto_and_on_write_the_mode_next_to_the_path_and_off_takes_both_out(self): + with tempfile.TemporaryDirectory() as td: + base, side = self.with_sidecar(td) + d = lambda **kw: R.derive_config(base, S.LaunchSettings(family="ling-3.2-air", **kw), bool_flags=tune_knobs.BOOL_FLAGS, log="x.log") + on, auto = d(mtp="on"), d(mtp="auto") + self.assertEqual((on["ling32_mtp"], on[ling32_family.MTP_MODE_KEY]), (str(side), "on")) # forced: --mtp FILE + self.assertEqual((auto["ling32_mtp"], auto[ling32_family.MTP_MODE_KEY]), (str(side), "auto")) # the engine decides: --mtp-auto FILE + for cfg in (on, auto): + for flag in ("--mtp", "--mtp-auto", "--spec", "--spec-adaptive"): + self.assertNotIn(flag, cfg["args"]) + off = R.derive_config({**base, "ling32_mtp": str(side), ling32_family.MTP_MODE_KEY: "auto"}, S.LaunchSettings(family="ling-3.2-air", mtp="off"), + bool_flags=tune_knobs.BOOL_FLAGS, log="x.log") + self.assertNotIn("ling32_mtp", off) + self.assertNotIn(ling32_family.MTP_MODE_KEY, off) + self.assertEqual(S.MTP_MODES, ("on", "off", "auto")) + + def test_off_takes_it_out_and_on_without_a_file_adds_nothing(self): + with tempfile.TemporaryDirectory() as td: + base, side = self.with_sidecar(td) + base = {**base, "ling32_mtp": str(side)} + off = R.derive_config(base, S.LaunchSettings(family="ling-3.2-air", mtp="off"), bool_flags=tune_knobs.BOOL_FLAGS, log="x.log") + self.assertNotIn("ling32_mtp", off) + side.unlink() + none = R.derive_config({k: v for k, v in base.items() if k != "ling32_mtp"}, S.LaunchSettings(family="ling-3.2-air", mtp="on"), bool_flags=tune_knobs.BOOL_FLAGS, log="x.log") + self.assertNotIn("ling32_mtp", none) + + def test_setup_is_told_and_a_changed_choice_runs_setup_again(self): + r = runner_for("ling-3.2-air", model="SQ-96", context=32768, vision="off", mtp="on") + r._catalog = mock.Mock() + r._catalog.resolve.side_effect = lambda model, fam: (fam, model) + r.feed = None + r.move_data = False + r.existing_data_dir = lambda: None + r.installed_card_args = lambda: [] + r.resolved_drafting = lambda fam: "off" # Flash-Next's drafting word must not decide for Ling + args = r.setup_args() + self.assertEqual(value(args, "--mtp"), "on") + self.assertTrue(R.desc_matches({"context": 32768, "images": "off", "mtp": "on"}, S.LaunchSettings(family="ling-3.2-air", context=32768, vision="off", mtp="on"))) + self.assertFalse(R.desc_matches({"context": 32768, "images": "off", "mtp": "off"}, S.LaunchSettings(family="ling-3.2-air", context=32768, vision="off", mtp="on"))) + self.assertTrue(R.desc_matches({"context": 32768, "images": "off", "mtp": "off"}, S.LaunchSettings(family="ling-3.2-air", context=32768, vision="off"))) # nothing said: as installed + + def test_the_notice_says_what_it_is_and_the_licence(self): + out = S.check_ling32(S.LaunchSettings(family="ling-3.2-air", mtp="on"), vram_gb=96, ram_gb=128) + text = " ".join(n.text for n in out) + self.assertIn("multi-token-prediction", text) + self.assertIn("several tokens per step", text) + self.assertIn("MIT", text) + self.assertIn("inclusionAI/Ling-3.2-air", text) + tiered = " ".join(n.text for n in S.check_ling32(S.LaunchSettings(family="ling-3.2-air", mtp="on"), vram_gb=8, ram_gb=16)) + self.assertIn("several tokens per step", tiered) + self.assertNotIn("4.3", text + tiered) + self.assertNotIn("break-even", text + tiered) + self.assertFalse(any("MTP" in n.text for n in S.check_ling32(S.LaunchSettings(family="ling-3.2-air"), vram_gb=96, ram_gb=128))) + other = S.check_ling32(S.LaunchSettings(family="qwen", mtp="on"), vram_gb=24, ram_gb=64) + self.assertEqual(other, []) # --mtp on is the Qwen draft layer's flag too: it says nothing about Ling there + + def test_the_launcher_says_nothing_extra_for_the_default_and_the_story_when_asked_for(self): + """On by default (tier A): part of the plan, no extra notice. Asked for by hand with --mtp on: what it is and the licence, in every tier. --mtp off: nothing.""" + text = lambda vram, ram, **kw: " ".join(n.text for n in S.check_ling32(S.LaunchSettings(family="ling-3.2-air", **kw), vram_gb=vram, ram_gb=ram)) + for vram, ram in ((96, 128), (24, 128), (24, 16)): + self.assertNotIn("multi-token", text(vram, ram)) + self.assertIn("multi-token", text(vram, ram, mtp="on")) + self.assertNotIn("multi-token", text(vram, ram, mtp="off")) + + def test_a_card_of_12_gb_or_less_says_why_when_mtp_is_asked_for(self): + text = lambda vram, **kw: " ".join(n.text for n in S.check_ling32(S.LaunchSettings(family="ling-3.2-air", **kw), vram_gb=vram, ram_gb=64)) + self.assertIn(ling32_fit.MTP_SMALL_CARD_NOTE, text(8, mtp="on")) + self.assertIn(ling32_fit.MTP_SMALL_CARD_NOTE, text(12, mtp="on")) + self.assertNotIn(ling32_fit.MTP_SMALL_CARD_NOTE, text(16, mtp="on")) + for vram in (8, 12, 16, 96): + self.assertNotIn("multi-token", text(vram)) # nothing said: no MTP text at all + self.assertNotIn("multi-token", text(vram, mtp="off")) + self.assertNotIn(ling32_fit.MTP_SMALL_CARD_NOTE, " ".join(n.text for n in S.check_ling32(S.LaunchSettings(family="ling-3.2-air", mtp="on"), vram_gb=8, ram_gb=64, unified=True))) + + def test_the_planner_counts_it_from_the_settings(self): + with_mtp = S.check_ling32(S.LaunchSettings(family="ling-3.2-air", mtp="on"), vram_gb=24, ram_gb=64) + self.assertTrue(with_mtp) + + +class Flags(unittest.TestCase): + def parse(self, *argv): + ap = argparse.ArgumentParser() + C.add_parsers(ap.add_subparsers(dest="cmd")) + return ap.parse_args(["launch", *argv]) + + def test_the_flags_parse(self): + a = self.parse("--family", "ling-3.2-air", "--thinking", "on", "--tier", "c", "--vram-budget-gib", "12", "--ram-budget-gib", "24.5", "--turbo-ssd", "--cpu-coexec", "4") + self.assertEqual((a.thinking, a.tier, a.vram_budget_gib, a.ram_budget_gib, a.turbo_ssd, a.cpu_coexec), ("on", "C", 12.0, 24.5, True, 4)) + b = self.parse("--tier", "AUTO") + self.assertEqual(b.tier, "auto") + self.assertFalse(self.parse().turbo_ssd) + + def test_bad_values_are_refused_in_plain_words(self): + for argv in (("--tier", "D"), ("--thinking", "maybe"), ("--vram-budget-gib", "0"), ("--vram-budget-gib", "lots")): + with self.assertRaises(SystemExit): + with mock.patch("sys.stderr"): + self.parse(*argv) + + def test_the_help_says_what_turbo_ssd_costs(self): + ap = argparse.ArgumentParser() + C.add_parsers(ap.add_subparsers(dest="cmd")) + sub = [a for a in ap._actions if isinstance(a, argparse._SubParsersAction)][0].choices["launch"] + self.assertIn("faster, may change answers", " ".join(sub.format_help().split())) + + def test_flags_text_is_copyable(self): + s = S.LaunchSettings(family="ling-3.2-air", model="SQ-96", thinking="on", tier="C", vram_budget=12.0, ram_budget=24.0, turbo_ssd=True) + text = S.flags_text(s) + for part in ("--thinking on", "--tier C", "--vram-budget-gib 12", "--ram-budget-gib 24", "--turbo-ssd"): + self.assertIn(part, text) + self.assertNotIn("--tier", S.flags_text(S.LaunchSettings(family="ling-3.2-air", model="SQ-96", tier="auto"))) + + def test_settings_round_trip_in_a_preset(self): + s = S.LaunchSettings(family="ling-3.2-air", thinking="on", tier="B", vram_budget=8.0, turbo_ssd=True) + back = S.LaunchSettings.from_dict(s.to_dict()) + self.assertEqual((back.thinking, back.tier, back.vram_budget, back.turbo_ssd), ("on", "B", 8.0, True)) + self.assertIsNone(S.LaunchSettings.from_dict({"family": "qwen"}).thinking) + + +class Notices(unittest.TestCase): + def test_a_ling_flag_on_another_model_is_said(self): + out = S.check_ling32(S.LaunchSettings(family="qwen", tier="C", turbo_ssd=True), vram_gb=24, ram_gb=64) + self.assertEqual(len(out), 1) + self.assertIn("--tier", out[0].text) + self.assertIn("Ling-3.2-Air only", out[0].text) + self.assertEqual(S.check_ling32(S.LaunchSettings(family="qwen"), vram_gb=24, ram_gb=64), []) + + def test_the_tier_and_its_speed_are_said_when_not_all_resident(self): + a = S.check_ling32(S.LaunchSettings(family="ling-3.2-air"), vram_gb=96, ram_gb=128) + self.assertEqual(a, []) + c = S.check_ling32(S.LaunchSettings(family="ling-3.2-air"), vram_gb=8, ram_gb=16) + self.assertEqual(len(c), 1) + self.assertIn("Memory tier C", c[0].text) + self.assertIn("slow", c[0].text) + b = S.check_ling32(S.LaunchSettings(family="ling-3.2-air"), vram_gb=24, ram_gb=96) + self.assertIn("Memory tier B", b[0].text) + + def test_turbo_ssd_says_faster_may_change_answers(self): + out = S.check_ling32(S.LaunchSettings(family="ling-3.2-air", turbo_ssd=True), vram_gb=8, ram_gb=16) + self.assertTrue(any("faster, may change answers" in n.text for n in out)) + none = S.check_ling32(S.LaunchSettings(family="ling-3.2-air", turbo_ssd=True), vram_gb=96, ram_gb=128) + self.assertTrue(any("changes nothing" in n.text for n in none)) + + def test_an_impossible_tier_is_a_warning_not_a_crash(self): + out = S.check_ling32(S.LaunchSettings(family="ling-3.2-air", tier="A"), vram_gb=24, ram_gb=64) + self.assertEqual(len(out), 1) + self.assertIn("--tier vram", out[0].text) + + def test_other_makes_of_card_are_told(self): + def words(vendor): + return " ".join(n.text for n in S.check_ling32(S.LaunchSettings(family="ling-3.2-air"), vram_gb=24, ram_gb=96, vendor=vendor)) + self.assertIn("tested on Radeon RX 9070 and Strix Halo", words("amd")) # AMD has an engine now: tested cards named, the rest "unverified" + self.assertNotIn("will not start", words("amd")) + self.assertIn("no Intel engine yet", words("intel")) + self.assertIn("128 GB or more", words("apple")) # a Mac keeps the whole model in memory: the recommendation, never a refusal + self.assertIn("none of them", words("someone-else")) + for vendor in ("nvidia", "cuda", None): + self.assertNotIn("Ling-3.2-Air on", words(vendor)) + self.assertNotIn("Ling-3.2-Air runs on", words(vendor)) + + def test_backends_flags_and_gfx_support(self): + self.assertEqual(ling32_family.BACKENDS, ("cuda", "hip", "metal")) + self.assertEqual(ling32_family.backend_of(), "cuda") + self.assertEqual(ling32_family.backend_of(hip=True), "hip") + self.assertEqual(ling32_family.backend_of(darwin=True), "metal") + self.assertEqual(ling32_family.backend_of(sycl=True), "sycl") + self.assertEqual(ling32_family.ENGINE_FLAGS["hip"], ["--graph"]) # not the NVIDIA-tuned --tc / --mla-kernel + self.assertEqual(ling32_family.ENGINE_FLAGS["metal"], []) + self.assertEqual(ling32_family.MTP_ENGINE_FLAGS["metal"], ling32_family.MTP_ENGINE_FLAGS["cuda"]) # one command line on every backend + self.assertEqual(ling32_family.hip_support("gfx1151:sramecc-:xnack-")[0], "tested") + self.assertEqual(ling32_family.hip_support("gfx1201")[0], "tested") + self.assertEqual(ling32_family.hip_support("gfx1100")[0], "compiled") + self.assertEqual(ling32_family.hip_support("gfx1031")[0], "compiled") + self.assertEqual(ling32_family.hip_support("gfx906")[0], "unsupported") # an Instinct MI50 / Radeon VII (gfx906): no engine code + self.assertEqual(ling32_family.hip_support(None)[0], "unsupported") + + def test_the_default_context_is_128k_like_every_model(self): + self.assertEqual(ling32_family.DEFAULT_CONTEXT, 131072) + self.assertEqual(ling32_fit.plan(24, 96)["ctx"], 131072) + + def test_parallel_is_one(self): + self.assertEqual(S.max_parallel("ling-3.2-air"), 1) + out = S.check_parallel(S.LaunchSettings(family="ling-3.2-air", parallel=4), vram_gb=24) + self.assertEqual(len(out), 1) + self.assertIn("one request at a time", out[0].text) + + +class CatalogAndRows(unittest.TestCase): + def setUp(self): + self._env = mock.patch.dict(os.environ, {"STRATA_LING32_SHOW": "1"}) + self._env.start() + self.addCleanup(self._env.stop) + + def test_catalog_resolve_and_names_include_ling(self): + from strata_cli.launch.catalog import Catalog + with tempfile.TemporaryDirectory() as d: + cat = Catalog(src=Path(__file__).resolve().parents[2], root=Path(d)) + self.assertEqual(cat.resolve("SQ-96", "ling-3.2-air"), ("ling-3.2-air", "SQ-96")) + self.assertEqual(cat.model_name_of("ling-3.2-air", "SQ-96"), "ling-3.2-air-sq-96") + self.assertEqual(cat.tag_of("ling-3.2-air", "SQ-96"), "ling-3.2-air-sq-96") + self.assertEqual(cat.model_folder(Path(d), "ling-3.2-air", "SQ-96"), Path(d) / "models" / "ling-3.2-air") + self.assertEqual(cat.contexts_for("ling-3.2-air"), ling32_family.CONTEXTS) + self.assertAlmostEqual(cat.kv_gb(131072, family="ling-3.2-air"), 131072 * 16128 / 1e9) + + def test_the_model_list_has_the_one_ling_size(self): + from tools import strata_mcp # noqa: F401 (the install tool the catalog reads) + from strata_cli.launch.catalog import Catalog + with tempfile.TemporaryDirectory() as d: + cat = Catalog(src=Path(__file__).resolve().parents[2], root=Path(d)) + _models, families, _ctx, _src = cat.tables() + self.assertIn("ling-3.2-air", families) + self.assertTrue(families["ling-3.2-air"].get("ling32")) + size = cat.strata.own_size("ling-3.2-air", "SQ-96") + self.assertEqual(size["download_gb"], 88.7) # the model, the Vision shard and the MTP sidecar + self.assertTrue(size["vision"]) + row = cat.strata.ling32_fit_row("SQ-96", 16.0, [{"vram_gb": 8.0}]) + self.assertEqual(row["tier"], "C") + self.assertEqual(row["mode"], "cross_tier_ssd") + self.assertEqual(cat.strata.ling32_fit_row("SQ-96", 128.0, [{"vram_gb": 96.0}])["mode"], "ram_vram_zero_ssd") + + +class FamilyData(unittest.TestCase): + def test_files_sizes_and_sources(self): + self.assertEqual(ling32_family.size_of("Ling-3.2-Air-SQ-96.strata"), 86_845_456_384) + self.assertEqual(ling32_family.size_of("Ling-3.2-Air-Vision.strata"), 869_351_424) + self.assertEqual(ling32_family.sha256_of("Ling-3.2-Air-SQ-96.strata"), "856c29768eda280d7a2b29e593e8c74188d6e4b34aab73bc698a47e14fb06be1") + self.assertEqual(ling32_family.size_of("Ling-3.2-Air-MTP.strata"), 990_724_096) + self.assertEqual(ling32_family.sha256_of("Ling-3.2-Air-MTP.strata"), "049a033704ea10716521759387fafca84527fb1157e19cff478a3f7d5a34089d") + self.assertEqual(ling32_family.files_of(), ["Ling-3.2-Air-SQ-96.strata", "Ling-3.2-Air-Vision.strata", "Ling-3.2-Air-MTP.strata"]) # pictures and MTP are on by default + self.assertEqual(ling32_family.files_of(vision=False, mtp=False), ["Ling-3.2-Air-SQ-96.strata"]) + self.assertEqual(ling32_family.files_of(mtp=False), ["Ling-3.2-Air-SQ-96.strata", "Ling-3.2-Air-Vision.strata"]) + self.assertEqual(ling32_family.files_of("SQ-96", True, True), ["Ling-3.2-Air-SQ-96.strata", "Ling-3.2-Air-Vision.strata", "Ling-3.2-Air-MTP.strata"]) + self.assertEqual(ling32_family.model_key(), "ling-3.2-air-sq-96") + self.assertEqual(ling32_family.build_of_model_name("ling-3.2-air"), "SQ-96") + self.assertIsNone(ling32_family.build_of_model_name("hy4-flash-sq-96")) + + def test_the_mtp_sidecar_data(self): + self.assertEqual(ling32_family.MTP_FILE, "Ling-3.2-Air-MTP.strata") + self.assertFalse(hasattr(ling32_family, "MTP_S4_FILE")) # no S4 variant ships (L32-MTP: +0.66 GB for 0.6 points of acceptance) + self.assertIs(ling32_family.DEFAULT_MTP, True) # the owner's decision (2026-12-01): on by default, in tier A; --mtp off turns it off + self.assertFalse(hasattr(ling32_family, "DEFAULT_DRAFTER") or hasattr(ling32_family, "DRAFTERS")) # no DFly for Ling + self.assertEqual(ling32_family.MTP_PINS, {ling32_family.MTP_FILE: (990_724_096, "049a033704ea10716521759387fafca84527fb1157e19cff478a3f7d5a34089d")}) + self.assertEqual(ling32_family.mtp_pin(ling32_family.MTP_FILE), (990_724_096, "049a033704ea10716521759387fafca84527fb1157e19cff478a3f7d5a34089d")) + self.assertEqual(ling32_fit.MTP_SIDECAR_BYTES, 990_724_096) + self.assertEqual(ling32_family.FILES[ling32_family.MTP_FILE], ling32_family.MTP_PINS[ling32_family.MTP_FILE]) # in the download set, the one pin + self.assertEqual(ling32_family.files_of(vision=False, mtp=False), [ling32_family.MODEL_FILE]) + lic = ling32_family.mtp_license(None) + self.assertEqual(lic["spdx"], "MIT") + self.assertIn("inclusionAI/Ling-3.2-air", lic["attribution"]) + self.assertIn("ff099487f6f57165e6fa9386ad61fddfafc78b76", lic["attribution"]) + self.assertIn("MIT", ling32_family.LICENSE_NOTE) # shown where the model's licence is shown + + def test_the_licence_of_a_file_that_cannot_be_read_is_the_family_words(self): + with tempfile.TemporaryDirectory() as d: + f = Path(d) / ling32_family.MTP_FILE + f.write_bytes(b"not a strata file") + self.assertEqual(ling32_family.mtp_license(f), ling32_family.mtp_license(None)) + + def test_find_mtp_takes_only_the_pinned_size(self): + with tempfile.TemporaryDirectory() as d: + model = Path(d) / ling32_family.MODEL_FILE + self.assertIsNone(ling32_family.find_mtp(model)) + (Path(d) / ling32_family.MTP_FILE).write_bytes(b"a part of it") + self.assertIsNone(ling32_family.find_mtp(model)) # not the pinned size: a cut-off copy is not used + with mock.patch.dict(ling32_family.MTP_PINS, {ling32_family.MTP_FILE: (12, "0" * 64)}): + self.assertEqual(ling32_family.find_mtp(model).name, ling32_family.MTP_FILE) + self.assertEqual(ling32_family.find_mtp(None, [d]).name, ling32_family.MTP_FILE) + with mock.patch.dict(ling32_family.MTP_PINS, {}, clear=True): # nothing pinned: used where it is + self.assertEqual(ling32_family.find_mtp(model).name, ling32_family.MTP_FILE) + + def test_the_mac_memory_floor_is_one_constant_and_the_texts_follow_it(self): + self.assertEqual(ling32_family.METAL_MIN_RAM_GIB, 120.0) # owner decision pending (recommended 128 GB, 2026-12-02) + self.assertEqual(ling32_family.metal_min_ram_words(), "128 GB") + with mock.patch.object(ling32_family, "METAL_MIN_RAM_GIB", 96.0): + self.assertEqual(ling32_family.metal_min_ram_words(), "96 GB") + apple = " ".join(n.text for n in S.check_ling32(S.LaunchSettings(family="ling-3.2-air"), vram_gb=None, ram_gb=96, vendor="apple")) + self.assertIn("96 GB", apple) + apple = " ".join(n.text for n in S.check_ling32(S.LaunchSettings(family="ling-3.2-air"), vram_gb=None, ram_gb=128, vendor="apple")) + self.assertIn("128 GB", apple) + + def test_a_small_mac_gets_a_warning_and_is_started_anyway(self): + want = "Ling runs best on a Mac with 128 GB or more; with less memory it may not load or be very slow." + self.assertEqual(ling32_family.metal_ram_advice(), want) + for ram, low in ((64, True), (96, True), (119.9, True), (120, False), (128, False), (None, False), (0, False)): + self.assertEqual(ling32_family.metal_ram_below_advice(ram), low, ram) + notes = S.check_ling32(S.LaunchSettings(family="ling-3.2-air"), vram_gb=None, ram_gb=ram, vendor="apple") + apple = [n for n in notes if "on a Mac" in n.text] + self.assertEqual(len(apple), 1) + self.assertIn(want, apple[0].text) + self.assertEqual("started anyway" in apple[0].next, low, ram) + self.assertEqual([n for n in notes if "Memory tier" in n.text or "cannot" in n.text.lower()], [], ram) # none of the PC tier notices, no refusal + + def test_the_mac_engine_says_it_in_plain_words_and_the_text_follows_the_constant(self): + src = (Path(__file__).resolve().parents[3] / "engine" / "src" / "ling32" / "metal" / "ling32_metal_main.cpp").read_text(encoding="utf-8") + self.assertIn(f"Ling runs best on a Mac with {ling32_family.metal_min_ram_words()} or more; with less memory it may not load or be very slow", src) + self.assertIn("std::atexit(loading_failed_note)", src) # the runtime's exit(4) is followed by the plain note + self.assertIn("g_loading = false; // the model and the engine buffers are made", src) + + def test_the_release_is_one_word_in_the_shipped_sources_file(self): + import json as _json + with tempfile.TemporaryDirectory() as d: + f = Path(d) / "ling32-sources.json" + src = [{"kind": "http-parts", "base": "https://huggingface.co/strata-engine/Ling-3.2-Air-Strata/resolve/main"}] + f.write_text(_json.dumps({"released": False, "sources": src}), encoding="utf-8") + self.assertFalse(ling32_family.released(f)) + self.assertEqual(ling32_family.sources(env={}, shipped=f), []) # prepared but ignored + f.write_text(_json.dumps({"released": True, "sources": src}), encoding="utf-8") + self.assertTrue(ling32_family.released(f)) + self.assertEqual([(s["kind"], s["base"]) for s in ling32_family.sources(env={}, shipped=f)], [("http-parts", src[0]["base"])]) + f.write_text(_json.dumps({"sources": src}), encoding="utf-8") # no word: not released + self.assertFalse(ling32_family.released(f)) + self.assertEqual(ling32_family.sources(env={}, shipped=f), []) + f.write_text(_json.dumps({"released": "yes", "sources": src}), encoding="utf-8") # only the real true counts + self.assertFalse(ling32_family.released(f)) + f.write_text("not json", encoding="utf-8") + self.assertFalse(ling32_family.released(f)) + # a source set by hand works before the release, and comes first + f.write_text(_json.dumps({"released": True, "sources": src}), encoding="utf-8") + got = ling32_family.sources(env={ling32_family.SOURCE_ENV: "https://r2.example/x"}, shipped=f) + self.assertEqual([s["base"] for s in got], ["https://r2.example/x", src[0]["base"]]) + shipped = _json.loads(ling32_family.SOURCES_FILE.read_text(encoding="utf-8")) + self.assertIs(shipped["released"], False) # the file in the repository is not released + self.assertEqual(shipped["sources"][0]["base"], "https://huggingface.co/strata-engine/Ling-3.2-Air-Strata/resolve/main") + self.assertEqual(ling32_family.sources(env={}), []) # so nothing is offered by default + + def test_the_intel_switch_turns_the_no_engine_warning_into_the_normal_flow(self): + def intel_notes(): + return " ".join(n.text for n in S.check_ling32(S.LaunchSettings(family="ling-3.2-air"), vram_gb=16.0, ram_gb=64.0, vendor="intel")) + self.assertFalse(ling32_family.sycl_available()) # until L32-SYCL's package is in the feed + self.assertIn("no Intel engine yet", intel_notes()) + with mock.patch.object(ling32_family, "SYCL_ENGINE_SHIPPED", True): + self.assertTrue(ling32_family.sycl_available()) + self.assertNotIn("no Intel engine yet", intel_notes()) + def notes(name, mtp=None): + return S.check_ling32(S.LaunchSettings(family="ling-3.2-air", mtp=mtp), vram_gb=16.0, ram_gb=64.0, vendor="intel", cards=[{"vendor": "intel", "name": name}]) + b70 = notes("Intel Arc Pro B70 Graphics") + self.assertEqual([n for n in b70 if "on Intel Arc:" in n.text], []) # the tested card: no card line + self.assertEqual(len([n for n in b70 if "without MTP" in n.text]), 1) # MTP is not verified on Intel: said once + self.assertEqual([n for n in notes("Intel Arc Pro B70 Graphics", mtp="on") if "without MTP" in n.text], []) + a750 = notes("Intel Arc A750 Graphics") + self.assertEqual(len([n for n in a750 if "on Intel Arc:" in n.text]), 1) + self.assertIn("not run on it", " ".join(n.text for n in a750)) + self.assertIn("sycl", ling32_family.ENGINE_FLAGS) + self.assertIn("sycl", ling32_family.MTP_ENGINE_FLAGS) + self.assertEqual(ling32_family.backend_of(sycl=True), "sycl") + + def test_128k_is_the_default_context_everywhere(self): + from strata_control import default_context + self.assertEqual(ling32_family.DEFAULT_CONTEXT, 131072) + self.assertEqual(ling32_fit.DEFAULT_CONTEXT, default_context.DEFAULT_CONTEXT) + self.assertEqual(default_context.pick(ling32_family.CONTEXTS), 131072) + self.assertEqual(ling32_fit.plan(96.0, 128.0)["ctx"], 131072) # the planner with no context asked for + self.assertEqual(S.parse_context("128k"), 131072) + + def test_old_nvidia_cards_get_one_honest_line_and_no_switch(self): + def notes(cards, vendor="nvidia"): + return S.check_ling32(S.LaunchSettings(family="ling-3.2-air"), vram_gb=8.0, ram_gb=64.0, vendor=vendor, cards=cards) + pascal = {"name": "GeForce GTX 1070 Ti", "arch": 61, "vendor": "nvidia"} + volta = {"name": "Tesla V100-SXM2-32GB", "arch": "sm_70", "vendor": "nvidia"} + for cards in ([pascal], [volta], [pascal, volta], [{"name": "Tesla P100", "arch": "6.0"}]): + lines = [n for n in notes(cards) if "tensor cores" in n.text] + self.assertEqual(len(lines), 1, cards) + self.assertIn("plain kernels", lines[0].text) + self.assertNotIn("experimental", lines[0].text.lower() + lines[0].next.lower()) # no opt-in word: it starts as it is + self.assertEqual(lines[0].level, "warn") # a line, never an error + self.assertNotRegex(lines[0].text + lines[0].next, r"\d+(\.\d+)? ?tok") # no speed number in the text + self.assertIn("GTX 1070 Ti", [n for n in notes([pascal, volta]) if "tensor cores" in n.text][0].text) + for cards in ([], None, [{"name": "RTX 3060", "arch": 86}], [{"name": "RTX 2080 Ti", "arch": 75}], [{"name": "Radeon", "arch": 61, "vendor": "amd"}]): + self.assertEqual([n for n in notes(cards) if "tensor cores" in n.text], [], cards) + self.assertEqual([n for n in notes([pascal], vendor="amd") if "tensor cores" in n.text], []) + + def test_the_part_helpers_size_resume_and_append(self): + self.assertEqual(ling32_family.part_sizes(20480, 8192), [8192, 8192, 4096]) + self.assertEqual(ling32_family.part_sizes(8192, 8192), [8192]) + real = ling32_family.part_sizes(ling32_family.FILES[ling32_family.MODEL_FILE][0]) + self.assertEqual((len(real), real[0], sum(real)), (2, ling32_family.PART_BYTES, ling32_family.FILES[ling32_family.MODEL_FILE][0])) # 42 GiB and the rest, as uploaded + with tempfile.TemporaryDirectory() as d: + j = Path(d) / "m.joining" + sizes = [8192, 8192, 4096] + self.assertEqual(ling32_family.join_resume(j, sizes), 0) # no file + j.write_bytes(b"a" * (8192 + 100)) + self.assertEqual(ling32_family.join_resume(j, sizes), 1) # a part was being appended: cut back to the whole part + self.assertEqual(j.stat().st_size, 8192) + j.write_bytes(b"a" * 20480) + self.assertEqual(ling32_family.join_resume(j, sizes), 3) # all parts in + j.write_bytes(b"a" * 20481) + self.assertEqual(ling32_family.join_resume(j, sizes), 0) # longer than the file can be: not ours, removed + self.assertFalse(j.exists()) + j.write_bytes(b"a" * 50) + self.assertEqual(ling32_family.join_resume(j, sizes), 0) # not even the first part: removed + self.assertFalse(j.exists()) + p = Path(d) / "p" + p.write_bytes(b"xyz" * 10) + self.assertEqual(ling32_family.append_part(j, p, chunk=7), 30) + self.assertEqual(ling32_family.append_part(j, p, chunk=7), 30) + self.assertEqual(j.read_bytes(), b"xyz" * 20) + + def test_nothing_is_published_by_default(self): + self.assertEqual(ling32_family.sources(env={}), []) + got = ling32_family.sources(env={"STRATA_LING32_SOURCE": "https://example.invalid/m/"}) + self.assertEqual(got[0]["base"], "https://example.invalid/m") + self.assertEqual(ling32_family.urls_for("Ling-3.2-Air-SQ-96.strata", got[0]), ["https://example.invalid/m/Ling-3.2-Air-SQ-96.strata"]) + self.assertEqual(ling32_family.sources(env={}, cfg={"ling32_source": "ftp://x"}), []) + shipped = (Path(__file__).resolve().parents[2] / "data" / "ling32-sources.json").read_text(encoding="utf-8") + self.assertIn('"released": false', shipped) # the release switch: not released, so the prepared sources are ignored + hf_base = "https://huggingface.co/strata-engine/Ling-3.2-Air-Strata/resolve/main" # the one prepared source: the (private until the release) Hugging Face repo, no key or other host + self.assertEqual(shipped.count(hf_base), 1) + body = shipped.lower().replace(hf_base.lower(), "").replace('"http-parts"', "").replace('"note"', "") + import json as _json + self.assertEqual(_json.loads(shipped)["sources"], [{"kind": "http-parts", "base": hf_base}]) + for secret in ("http", "key", "token", "secret"): + self.assertNotIn(f'"{secret}', body) + + def test_local_files_need_the_pinned_size(self): + with tempfile.TemporaryDirectory() as d: + (Path(d) / "Ling-3.2-Air-SQ-96.strata").write_bytes(b"short") + self.assertEqual(ling32_family.local_files(d), {}) + + def test_manifest_words_name_the_family_before_the_size_guess(self): + from strata_control import strata_manifest as M + self.assertEqual(M.family_from_hints("Ling-3.2-Air-SQ-96.strata", 86_845_456_384), "ling-3.2-air") # not HY-4 Flash, whose size class it shares + self.assertEqual(M.family_from_hints("Hy4-Flash-SQ-96.strata", 89_577_742_336), "hy4-flash") + self.assertEqual(M.family_of_manifest({"strata_family": "bailing_moe_v3", "config": {"model_type": "bailing_moe_v3_vl"}}), "ling-3.2-air") + self.assertEqual(M.family_of_manifest({"arch": "ling32"}), "ling-3.2-air") + + +if __name__ == "__main__": + unittest.main()