mirror of
https://github.com/Niko1221/Strata.git
synced 2026-12-04 07:18:50 +00:00
ling32: --vision-max-pixels goes with the picture flags when pictures are off or the engine reads none
This commit is contained in:
1 parent
5611fbfe75
commit
b2cd949401
4 files changed
+959
-957
No files matched your search
@@ -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])
|
||||
|
||||
+273
-272
@@ -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 <folder>` 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 <folder>` 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()
|
||||
@@ -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)]
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
Reference in new issue
Block a user