From efb53ddf9ceb83f7b1db449129adbc7b3bec6415 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Thu, 24 Sep 2026 00:41:48 +0200 Subject: [PATCH] feat(svc-ai-litellm): measure each served model's generation rate The router already ranked routes on traits.speed, but nothing ever set one. No catalogue carries a rate, because a rate is a property of this machine under this load rather than of the model, and a hand-written number in services.yml would be a guess that rots. The deploy now measures it. After the gateway is warm, measure_speed.py asks it which models it serves and sends router_speed_samples requests to each model that has no rate yet, discarding the first as a cold load and taking the median of the rest. The result is stored on the stack host and rendered back into model_info.traits.speed on the same deploy, so the gateway restarts once with the numbers it just produced. The stored file is read back with slurp rather than lookup('file'), because the config directory lives on the stack host and a lookup reads the controller. A model that already carries a rate sends no request at all. Re-measuring everything every deploy would produce results the tolerance discards anyway, and that traffic is the entire live surface of this step: what can hang, what can fail the deploy, and what the deploy waits for. router_speed_remeasure discards the stored numbers once, for the case where the hardware under them changed. Two budgets bound a run. A measured request may take router_speed_timeout; the discarded first request gets upstream_timeout instead, because it pays the model load and holding it to the sample budget would time out exactly the models worth measuring. Exceeding a budget abandons that model, not the deploy, and the model keeps whatever rate it had. Every matrix variant overrides the sample count to 1, where the single sample is kept rather than discarded: a CI round proves that the measurement, the store and the re-render ran, not what the rate was on a shared runner. Co-Authored-By: Claude Opus 5 (1M context) --- .../038-system-one-model-router.md | 19 ++ .../files/python/measure_speed.py | 158 +++++++++++++ roles/svc-ai-litellm/meta/services.yml | 3 + roles/svc-ai-litellm/meta/variants.yml | 3 + roles/svc-ai-litellm/tasks/00_core.yml | 19 ++ roles/svc-ai-litellm/tasks/01_keys.yml | 6 + roles/svc-ai-litellm/tasks/02_speed.yml | 31 +++ roles/svc-ai-litellm/templates/config.yaml.j2 | 11 +- roles/svc-ai-litellm/vars/main.yml | 4 + .../files/test_measure_speed.py | 222 ++++++++++++++++++ .../templates/test_config_model_list.py | 48 +++- 11 files changed, 520 insertions(+), 4 deletions(-) create mode 100644 roles/svc-ai-litellm/files/python/measure_speed.py create mode 100644 roles/svc-ai-litellm/tasks/02_speed.yml create mode 100644 tests/unit/python/roles/svc-ai-litellm/files/test_measure_speed.py diff --git a/docs/requirements/038-system-one-model-router.md b/docs/requirements/038-system-one-model-router.md index 37babe3257..9dcf5fbffa 100644 --- a/docs/requirements/038-system-one-model-router.md +++ b/docs/requirements/038-system-one-model-router.md @@ -58,6 +58,18 @@ These choices are settled at requirement creation time and bound the implementat Weights are a preference because the operator is the only one who knows what this deployment is for. A cluster whose local models are toys wants `speed` high; a cluster billing a provider per token wants `cost` high; a cluster handling client data leaves `locality` where it is. Encoding one of those as the rule would be this project guessing. +10. **Speed is measured at deploy time, not declared, and only for a model that has no rate yet.** A rate is a property of this machine under this load, not of the model, so no catalogue carries one and a hand-written number in `services.yml` would be a guess that rots. After the gateway is warm, [measure_speed.py](../../roles/svc-ai-litellm/files/python/measure_speed.py) asks it which models it serves and sends `services.litellm.router_speed_samples` (12) requests to each unranked one, discarding the first as a cold load and taking the median of the rest as output tokens per second. + + A model that already carries a rate is not measured at all. Re-measuring everything on every deploy would send traffic whose result the tolerance below discards anyway, and that traffic is the entire live surface of this step: it is what can hang, what can fail the deploy, and what the deploy waits for. `services.litellm.router_speed_remeasure` discards the stored numbers once, for the case where the hardware under them changed. + + The result is stored on the stack host and rendered back into `model_info.traits.speed` on the same deploy, so the gateway restarts once with the numbers it just produced. A re-measured rate that moved less than 10% keeps its stored value, because no two runs measure the same machine and an unclamped result would restart the gateway for nothing. A model the measurement could not reach keeps its stored rate rather than losing it, so one bad minute does not unrank a model against its peers. + + Two budgets bound the step. A measured request may take `services.litellm.router_speed_timeout` (60s); the discarded first request gets `services.litellm.upstream_timeout` instead, because it pays the model load and holding it to the sample budget would time out exactly the models worth measuring. A request that exceeds its budget raises, which abandons that model rather than the deploy. + + Every matrix variant overrides the sample count to 1. At that setting the single sample is kept rather than discarded as cold, because what a CI round proves is that the measurement, the store and the re-render ran, not what the rate was on a shared runner. + + A declared `traits.speed` still wins, because a declaration is the operator overriding the measurement and the next deploy must not overwrite it back. + ## Component Roles The router sits inside the gateway. No consumer learns a second endpoint. @@ -80,6 +92,7 @@ flowchart TB keep["local_reason()
drop remote when it must stay in"] dec["decide()
weighted score, ties by alias"] weights["router_weights
locality, cost, speed"] + rates["measure_speed.py
12 requests per model at deploy"] end subgraph sys2["System II candidates"] @@ -89,6 +102,7 @@ flowchart TB consumer --> hook --> caps --> elig --> keep --> dec weights --> dec + rates -->|traits.speed| caps dec -->|chosen alias| sys2 small & remote -->|completion| consumer ``` @@ -109,6 +123,10 @@ flowchart TB | Each factor carries the weight `services.yml` gives it, and a zero weight removes it | the same test, rendering the hook with the shipped weights and with a single-factor one | | No weighting sends a restricted request out of the cluster | the same test, weighting speed alone with the fallback switch on | | The shipped weights keep locality worth at least the other factors combined | the same test, reading them out of [meta/services.yml](../../roles/svc-ai-litellm/meta/services.yml) rather than repeating them | +| A measured rate reaches `traits.speed`, and a declared one outranks it | [test_config_model_list.py](../../tests/unit/python/roles/svc-ai-litellm/templates/test_config_model_list.py) | +| The cold first sample is discarded, one slow sample does not move the median, and an unreachable model keeps its rate | [test_measure_speed.py](../../tests/unit/python/roles/svc-ai-litellm/files/test_measure_speed.py) | +| A model that already carries a rate sends no request, and the remeasure switch sends them again | the same test | +| The cold first request gets the longer budget, and a single-sample run keeps its one measurement | the same test | | The alias is served and is not read as a route without a backend | [probe.py](../../roles/svc-ai-litellm/files/test/probe.py), run on every gateway deploy | | The alias routes rather than falling back, proven by the model that answers | [probe.py](../../roles/svc-ai-litellm/files/test/probe.py), on every gateway deploy that serves more than one declared window | | A consumer selecting `auto` receives a completion | [test-system-one-router.js](../../roles/web-app-openwebui/files/playwright/test-system-one-router.js) | @@ -123,6 +141,7 @@ flowchart TB - [x] A model entry declares none of what the catalog already states, and a route's price follows from whether it is local, mocked or keyed. - [x] The same request picks the same model twice, with no inference and no download on any path. - [x] Every routing factor carries a 0..1 weight in `services.litellm.router_weights`, a zero weight removes the factor, and no weighting lets a restricted request reach a remote model. +- [ ] The deploy sends `services.litellm.router_speed_samples` requests to each served model, and the measured rates reach `model_info.traits.speed` in the rendered config on the same deploy. - [x] The routing probe treats the alias as served rather than as a route without a backend, and fails when the gateway withholds it. - [ ] A request naming `auto` returns a completion whose served model is one of the eligible candidates, verified through the gateway with a consumer virtual key. The CLI probe sends a prompt the smallest declared window cannot hold and fails when the answer names the alias itself or a model whose window is too small. - [ ] A Playwright spec verifies that selecting `auto` in Open WebUI returns an answer. diff --git a/roles/svc-ai-litellm/files/python/measure_speed.py b/roles/svc-ai-litellm/files/python/measure_speed.py new file mode 100644 index 0000000000..912589c347 --- /dev/null +++ b/roles/svc-ai-litellm/files/python/measure_speed.py @@ -0,0 +1,158 @@ +"""Measure how fast each served model generates, so the router can rank them. + +The router scores a route on locality, price and speed. The first two are +declared or catalogued; speed has no source at all, because it is a property of +this machine under this load and not of the model. So it is measured here, +against the gateway that will serve the traffic. + +Only a model without a stored rate is measured. A deploy that re-measured +everything would send requests whose results the tolerance below discards +anyway, and that traffic is the whole live surface of this script. + +The result is a per-model median of output tokens per second, printed as JSON +for the deploy to store and render back into ``model_info.traits.speed``. + +Environment: + LITELLM_MK: master key the gateway accepts. + LITELLM_PORT: port the gateway listens on inside its own container. + LITELLM_SAMPLES: requests per model; above one, the first is discarded. + LITELLM_TIMEOUT: seconds one measured request may take. + LITELLM_WARMUP: seconds the discarded first request may take. + LITELLM_EXCLUDE: alias to skip, namely the router's own. + LITELLM_REMEASURE: non-empty to re-measure models that already have a rate. + LITELLM_PREVIOUS: the JSON of the last measurement. +""" + +from __future__ import annotations + +import json +import os +import statistics +import sys +import time +import urllib.error +import urllib.request + +MASTER_KEY = os.environ["LITELLM_MK"] +PORT = os.environ["LITELLM_PORT"] +SAMPLES = int(os.environ["LITELLM_SAMPLES"]) +TIMEOUT = float(os.environ["LITELLM_TIMEOUT"]) +WARMUP_TIMEOUT = float(os.environ["LITELLM_WARMUP"]) +EXCLUDE = os.environ.get("LITELLM_EXCLUDE") or "" +REMEASURE = bool(os.environ.get("LITELLM_REMEASURE")) +PREVIOUS = json.loads(os.environ.get("LITELLM_PREVIOUS") or "{}") + +LISTING_TIMEOUT = 30 +MAX_TOKENS = 64 +PROMPT = "Count from one to twenty in words." +TOLERANCE = 0.10 + + +def call(path, payload=None, timeout=LISTING_TIMEOUT): + """One gateway call, decoded. + + Args: + path: the API path below the gateway root. + payload: a mapping to POST, or None to GET. + timeout: seconds the call may take. + + Returns: + The decoded response body. + """ + request = urllib.request.Request( + f"http://127.0.0.1:{PORT}{path}", + data=json.dumps(payload).encode() if payload else None, + headers={ + "Authorization": f"Bearer {MASTER_KEY}", + "Content-Type": "application/json", + }, + method="POST" if payload else "GET", + ) + with urllib.request.urlopen(request, timeout=timeout) as response: # noqa: S310 fixed internal http origin + return json.loads(response.read()) + + +def sample(model, timeout): + """Output tokens per second for one request, or None if it yielded none.""" + started = time.monotonic() + body = call( + "/v1/chat/completions", + { + "model": model, + "messages": [{"role": "user", "content": PROMPT}], + "max_tokens": MAX_TOKENS, + }, + timeout, + ) + elapsed = time.monotonic() - started + tokens = (body.get("usage") or {}).get("completion_tokens") or 0 + if not tokens or elapsed <= 0: + return None + return tokens / elapsed + + +def measure(model): + """The median rate over the samples, discarding the first as a cold load. + + A backend that has never answered this model pays its load cost on the + first call, which is not the rate a later caller will see, and that call + gets the longer budget for the same reason. The median then absorbs + whatever else the machine was doing during one sample. + + A single-sample run keeps its one measurement rather than discarding it and + returning nothing: at that setting the number is worth less than the proof + that the path ran at all. + """ + warmup = 1 if SAMPLES > 1 else 0 + rates = [] + for index in range(SAMPLES): + cold = index < warmup + rate = sample(model, WARMUP_TIMEOUT if cold else TIMEOUT) + if rate is not None and not cold: + rates.append(rate) + return statistics.median(rates) if rates else None + + +def settled(model, measured): + """The measurement, or the stored one when the move is within tolerance.""" + stored = PREVIOUS.get(model) + if stored and abs(measured - stored) <= TOLERANCE * stored: + return stored + return round(measured, 2) + + +def rank(model): + """This model's rate, measuring only when it has none to fall back on.""" + if model in PREVIOUS and not REMEASURE: + print(f"KEPT {model}: {PREVIOUS[model]} tok/s", file=sys.stderr) + return PREVIOUS[model] + try: + measured = measure(model) + except (urllib.error.URLError, OSError, ValueError) as error: + measured, why = None, type(error).__name__ + else: + why = "no request produced output tokens" + if measured is None: + print(f"SKIPPED {model}: {why}", file=sys.stderr) + return PREVIOUS.get(model) + rate = settled(model, measured) + print(f"MEASURED {model}: {rate} tok/s", file=sys.stderr) + return rate + + +def main(): + served = [ + entry["id"] + for entry in call("/v1/models").get("data") or [] + if entry.get("id") and entry["id"] != EXCLUDE + ] + speeds = {} + for model in served: + rate = rank(model) + if rate is not None: + speeds[model] = rate + print(json.dumps(speeds, indent=2, sort_keys=True)) + + +if __name__ == "__main__": + main() diff --git a/roles/svc-ai-litellm/meta/services.yml b/roles/svc-ai-litellm/meta/services.yml index e16a766eed..a483e3bf10 100644 --- a/roles/svc-ai-litellm/meta/services.yml +++ b/roles/svc-ai-litellm/meta/services.yml @@ -21,6 +21,9 @@ litellm: locality: 1.0 cost: 0.6 speed: 0.4 + router_speed_samples: 12 + router_speed_timeout: 60 + router_speed_remeasure: false remote_models: - alias: openai/gpt-4o-mini model: openai/gpt-4o-mini diff --git a/roles/svc-ai-litellm/meta/variants.yml b/roles/svc-ai-litellm/meta/variants.yml index dffcaa957b..06be44c947 100644 --- a/roles/svc-ai-litellm/meta/variants.yml +++ b/roles/svc-ai-litellm/meta/variants.yml @@ -19,6 +19,7 @@ postgres: shared: true litellm: + router_speed_samples: 1 remote_models: - alias: mock/deterministic provider: mock @@ -35,6 +36,7 @@ enabled: false shared: false # nocheck: variants-static-override backup shared stays literally true litellm: + router_speed_samples: 1 remote_models: - alias: mock/deterministic provider: mock @@ -52,6 +54,7 @@ postgres: shared: true litellm: + router_speed_samples: 1 remote_models: - alias: mock/deterministic provider: mock diff --git a/roles/svc-ai-litellm/tasks/00_core.yml b/roles/svc-ai-litellm/tasks/00_core.yml index a3edca746a..44a57461cc 100644 --- a/roles/svc-ai-litellm/tasks/00_core.yml +++ b/roles/svc-ai-litellm/tasks/00_core.yml @@ -24,6 +24,25 @@ '{{ AI_MOCK_PROVIDER }}' answers from its own declared response and needs no key. quiet: true +- name: "🔍 Look for the rates the last deploy measured" + ansible.builtin.stat: + path: "{{ LITELLM_SPEED_PATH_HOST }}" + delegate_to: "{{ STACK_HOST }}" + run_once: true + register: litellm_speed_file + +- name: "📥 Read the rates the last deploy measured" + ansible.builtin.slurp: + src: "{{ LITELLM_SPEED_PATH_HOST }}" + delegate_to: "{{ STACK_HOST }}" + run_once: true + register: litellm_speed_stored + when: litellm_speed_file.stat.exists + +- name: "🧮 Rank this render on those rates" + ansible.builtin.set_fact: + LITELLM_MEASURED_SPEED: "{{ (litellm_speed_stored.content | b64decode | from_json) if litellm_speed_file.stat.exists else {} }}" + - name: "📄 Render LiteLLM gateway config (local + swarm peers)" ansible.builtin.include_tasks: file: "{{ lookup('path_absolute', 'roles/sys-svc-compose/tasks/utils/render_replicated_templates.yml') }}" diff --git a/roles/svc-ai-litellm/tasks/01_keys.yml b/roles/svc-ai-litellm/tasks/01_keys.yml index bd43ae8eb5..9e4abb3919 100644 --- a/roles/svc-ai-litellm/tasks/01_keys.yml +++ b/roles/svc-ai-litellm/tasks/01_keys.yml @@ -49,3 +49,9 @@ no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" delegate_to: "{{ LITELLM_HOST_NODE }}" when: LITELLM_CHAT_MODEL_SERVED | bool + +- name: "⏱️ Rank the served models on measured generation speed" + ansible.builtin.include_tasks: 02_speed.yml + when: + - LITELLM_ROUTER_ALIAS | length > 0 + - LITELLM_CHAT_MODEL_SERVED | bool diff --git a/roles/svc-ai-litellm/tasks/02_speed.yml b/roles/svc-ai-litellm/tasks/02_speed.yml new file mode 100644 index 0000000000..4d80852e4d --- /dev/null +++ b/roles/svc-ai-litellm/tasks/02_speed.yml @@ -0,0 +1,31 @@ +--- +- name: "⏱️ Measure how fast each served model generates" + ansible.builtin.shell: | # nocheck: container-exec-resolver runtime-resolved CID, delegated to the hosting node + container exec -i -e LITELLM_MK={{ LITELLM_MASTER_KEY | quote }} -e LITELLM_PORT={{ LITELLM_PORT | quote }} -e LITELLM_SAMPLES={{ LITELLM_ROUTER_SPEED_SAMPLES | quote }} -e LITELLM_TIMEOUT={{ LITELLM_ROUTER_SPEED_TIMEOUT | quote }} -e LITELLM_WARMUP={{ LITELLM_UPSTREAM_TIMEOUT | quote }} -e LITELLM_EXCLUDE={{ LITELLM_ROUTER_ALIAS | quote }} -e LITELLM_REMEASURE={{ LITELLM_ROUTER_SPEED_REMEASURE | bool | ternary('1', '') | quote }} -e LITELLM_PREVIOUS={{ LITELLM_MEASURED_SPEED | to_json | quote }} {{ LITELLM_LOCAL_CID | quote }} python3 -c {{ lookup('file', lookup('path_absolute', 'roles/svc-ai-litellm/files/python/measure_speed.py')) | quote }} + register: litellm_speed_result + retries: 3 + delay: 5 + until: litellm_speed_result.rc == 0 + changed_when: false + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" + delegate_to: "{{ LITELLM_HOST_NODE }}" + +- name: "📈 Store the measured rates for the next deploy" + ansible.builtin.copy: + content: "{{ litellm_speed_result.stdout }}\n" + dest: "{{ LITELLM_SPEED_PATH_HOST }}" + mode: "0644" + delegate_to: "{{ STACK_HOST }}" + run_once: true + +- name: "🧮 Rank the gateway on the rates just measured" + ansible.builtin.set_fact: + LITELLM_MEASURED_SPEED: "{{ litellm_speed_result.stdout | from_json }}" + +- name: "📄 Re-render the gateway config with the measured rates" + ansible.builtin.include_tasks: + file: "{{ lookup('path_absolute', 'roles/sys-svc-compose/tasks/utils/render_replicated_templates.yml') }}" + vars: + role_templates: + - src: "config.yaml.j2" + dest: "{{ LITELLM_CONFIG_PATH_HOST }}" diff --git a/roles/svc-ai-litellm/templates/config.yaml.j2 b/roles/svc-ai-litellm/templates/config.yaml.j2 index 8842a3735a..2a985c26e8 100644 --- a/roles/svc-ai-litellm/templates/config.yaml.j2 +++ b/roles/svc-ai-litellm/templates/config.yaml.j2 @@ -10,21 +10,26 @@ router_alias=LITELLM_ROUTER_ALIAS) %} model_list:{{ ' []' if not _routes else '' }} {% for _route in _routes %} +{% set _traits = _route.traits or {} %} +{% set _speed = _route.alias in LITELLM_MEASURED_SPEED and 'speed' not in _traits %} - model_name: {{ _route.alias | to_json }} litellm_params: {% for _key, _value in _route.params.items() %} {{ _key }}: {{ _value | to_json }} {% endfor %} -{% if _route.context or _route.traits %} +{% if _route.context or _traits or _speed %} model_info: {% if _route.context %} max_input_tokens: {{ _route.context }} {% endif %} -{% if _route.traits %} +{% if _traits or _speed %} traits: -{% for _trait, _value in _route.traits.items() %} +{% for _trait, _value in _traits.items() %} {{ _trait }}: {{ _value | to_json }} {% endfor %} +{% if _speed %} + speed: {{ LITELLM_MEASURED_SPEED[_route.alias] | to_json }} +{% endif %} {% endif %} {% endif %} {% endfor %} diff --git a/roles/svc-ai-litellm/vars/main.yml b/roles/svc-ai-litellm/vars/main.yml index e417b28da2..e18c1c3209 100644 --- a/roles/svc-ai-litellm/vars/main.yml +++ b/roles/svc-ai-litellm/vars/main.yml @@ -10,7 +10,11 @@ LITELLM_UPSTREAM_TIMEOUT: "{{ lookup('config', application_id, 'services.litellm LITELLM_ROUTER_ALIAS: "{{ lookup('config', application_id, 'services.litellm.router_alias') }}" LITELLM_ROUTER_REMOTE_FALLBACK: "{{ lookup('config', application_id, 'services.litellm.router_remote_fallback') }}" LITELLM_ROUTER_WEIGHTS: "{{ lookup('config', application_id, 'services.litellm.router_weights') }}" +LITELLM_ROUTER_SPEED_SAMPLES: "{{ lookup('config', application_id, 'services.litellm.router_speed_samples') }}" +LITELLM_ROUTER_SPEED_TIMEOUT: "{{ lookup('config', application_id, 'services.litellm.router_speed_timeout') }}" +LITELLM_ROUTER_SPEED_REMEASURE: "{{ lookup('config', application_id, 'services.litellm.router_speed_remeasure') }}" LITELLM_ROUTER_HOOK_PATH_HOST: "{{ [ lookup('container', application_id, 'directories.config'), 'router_hook.py' ] | path_join }}" +LITELLM_SPEED_PATH_HOST: "{{ [ lookup('container', application_id, 'directories.config'), 'measured_speed.json' ] | path_join }}" LITELLM_CONFIG_PATH_HOST: "{{ [ lookup('container', application_id, 'directories.config'), 'config.yaml' ] | path_join }}" LITELLM_CONFIG_PATH_DOCKER: "{{ lookup('volume', application_id, 'litellm_config').target }}" LITELLM_PROVIDER_KEYS: diff --git a/tests/unit/python/roles/svc-ai-litellm/files/test_measure_speed.py b/tests/unit/python/roles/svc-ai-litellm/files/test_measure_speed.py new file mode 100644 index 0000000000..35a1962f2c --- /dev/null +++ b/tests/unit/python/roles/svc-ai-litellm/files/test_measure_speed.py @@ -0,0 +1,222 @@ +"""The deploy measures a rate per model, because no catalogue carries one. + +Speed is a property of this machine under this load, not of the model, so the +numbers the router ranks on come from requests the deploy actually sent. These +cases pin what the script does with them: it measures only a model that has no +rate yet, discards the cold first sample, takes a median rather than a mean, +refuses to rewrite a rate that barely moved, and never drops a model because +one deploy could not reach it. +""" + +from __future__ import annotations + +import importlib.util +import io +import json +import unittest +from contextlib import redirect_stdout +from typing import ClassVar, Self +from unittest.mock import patch + +from . import PROJECT_ROOT + +SCRIPT_PATH = PROJECT_ROOT / "roles/svc-ai-litellm/files/python/measure_speed.py" + +SAMPLE_TIMEOUT = 60.0 +WARMUP_TIMEOUT = 240.0 + +ENVIRONMENT = { + "LITELLM_MK": "sk-master-key", + "LITELLM_PORT": "4000", + "LITELLM_SAMPLES": "12", + "LITELLM_TIMEOUT": str(SAMPLE_TIMEOUT), + "LITELLM_WARMUP": str(WARMUP_TIMEOUT), + "LITELLM_EXCLUDE": "auto", + "LITELLM_REMEASURE": "", + "LITELLM_PREVIOUS": "{}", +} + + +class FakeResponse: + def __init__(self, body: bytes) -> None: + self.body = body + + def __enter__(self) -> Self: + return self + + def __exit__(self, *exc_info: object) -> bool: + return False + + def read(self) -> bytes: + return self.body + + +class Gateway: + """A gateway that answers /v1/models and bills each completion a duration. + + Args: + served: the model ids /v1/models publishes. + durations: model -> the seconds each successive call takes; the last + value repeats once the list runs out. + tokens: completion tokens every answer reports. + """ + + def __init__(self, served, durations, tokens=60) -> None: + self.served = served + self.durations = durations + self.tokens = tokens + self.clock = 0.0 + self.calls: dict[str, int] = {} + self.timeouts: dict[str, list[float]] = {} + + def urlopen(self, request, timeout=None) -> FakeResponse: + if request.full_url.endswith("/v1/models"): + return FakeResponse( + json.dumps({"data": [{"id": name} for name in self.served]}).encode() + ) + model = json.loads(request.data.decode())["model"] + index = self.calls.get(model, 0) + self.calls[model] = index + 1 + self.timeouts.setdefault(model, []).append(timeout) + schedule = self.durations[model] + self.clock += schedule[min(index, len(schedule) - 1)] + return FakeResponse( + json.dumps({"usage": {"completion_tokens": self.tokens}}).encode() + ) + + def monotonic(self) -> float: + return self.clock + + +def run(gateway, **environment): + """The script against *gateway*, returning the JSON it printed.""" + spec = importlib.util.spec_from_file_location("measure_speed", SCRIPT_PATH) + module = importlib.util.module_from_spec(spec) + with ( + patch.dict("os.environ", {**ENVIRONMENT, **environment}, clear=False), + patch("urllib.request.urlopen", gateway.urlopen), + patch("time.monotonic", gateway.monotonic), + redirect_stdout(io.StringIO()) as captured, + ): + spec.loader.exec_module(module) + module.main() + return json.loads(captured.getvalue()) + + +class TestMeasureSpeed(unittest.TestCase): + def test_a_rate_is_output_tokens_over_the_wall_clock(self) -> None: + gateway = Gateway(["m"], {"m": [2.0]}, tokens=60) + self.assertEqual(run(gateway)["m"], 30.0) + + def test_it_sends_the_configured_number_of_requests(self) -> None: + gateway = Gateway(["m"], {"m": [2.0]}) + run(gateway, LITELLM_SAMPLES="12") + self.assertEqual(gateway.calls["m"], 12) + + def test_the_cold_first_sample_is_discarded(self) -> None: + gateway = Gateway(["m"], {"m": [600.0, 2.0]}, tokens=60) + self.assertEqual( + run(gateway)["m"], + 30.0, + "a backend pays its load cost on the first call, which is not the " + "rate any later caller sees", + ) + + def test_the_cold_first_sample_gets_the_longer_budget(self) -> None: + gateway = Gateway(["m"], {"m": [2.0]}, tokens=60) + run(gateway) + self.assertEqual( + gateway.timeouts["m"][:2], + [WARMUP_TIMEOUT, SAMPLE_TIMEOUT], + "the cold call pays the model load, so holding it to the sample " + "budget would time out exactly the models worth measuring", + ) + + def test_one_slow_sample_does_not_move_the_median(self) -> None: + schedule = [600.0] + [2.0] * 5 + [120.0] + [2.0] * 5 + gateway = Gateway(["m"], {"m": schedule}, tokens=60) + self.assertEqual(run(gateway)["m"], 30.0) + + def test_a_single_sample_keeps_its_own_measurement(self) -> None: + gateway = Gateway(["m"], {"m": [2.0]}, tokens=60) + self.assertEqual( + run(gateway, LITELLM_SAMPLES="1")["m"], + 30.0, + "discarding the only sample would return nothing; at this setting " + "the number is worth less than the proof that the path ran", + ) + + def test_the_router_alias_is_not_measured(self) -> None: + gateway = Gateway(["auto", "m"], {"m": [2.0]}) + self.assertEqual(list(run(gateway)), ["m"]) + + def test_every_served_model_gets_its_own_rate(self) -> None: + gateway = Gateway(["slow", "fast"], {"slow": [6.0], "fast": [1.0]}, tokens=60) + self.assertEqual(run(gateway), {"slow": 10.0, "fast": 60.0}) + + +class TestOnlyUnrankedIsMeasured(unittest.TestCase): + """The traffic is the live surface, so a stored rate sends none of it.""" + + STORED: ClassVar[dict] = {"m": 31.0} + + def test_a_model_that_already_has_a_rate_is_not_measured(self) -> None: + gateway = Gateway(["m"], {"m": [2.0]}, tokens=60) + measured = run(gateway, LITELLM_PREVIOUS=json.dumps(self.STORED)) + self.assertEqual(gateway.calls.get("m", 0), 0) + self.assertEqual(measured["m"], 31.0) + + def test_an_unranked_model_beside_a_ranked_one_is_measured(self) -> None: + gateway = Gateway(["m", "new"], {"m": [2.0], "new": [1.0]}, tokens=60) + measured = run(gateway, LITELLM_PREVIOUS=json.dumps(self.STORED)) + self.assertEqual(gateway.calls.get("m", 0), 0) + self.assertEqual(measured, {"m": 31.0, "new": 60.0}) + + def test_the_remeasure_switch_sends_the_requests_again(self) -> None: + gateway = Gateway(["m"], {"m": [2.0]}, tokens=60) + run(gateway, LITELLM_PREVIOUS=json.dumps(self.STORED), LITELLM_REMEASURE="1") + self.assertEqual(gateway.calls["m"], 12) + + +class TestRemeasuring(unittest.TestCase): + """Only a re-measurement can move a stored number, and barely moving does not.""" + + def remeasure(self, gateway, stored): + return run(gateway, LITELLM_PREVIOUS=json.dumps(stored), LITELLM_REMEASURE="1") + + def test_a_rate_within_tolerance_keeps_the_stored_number(self) -> None: + gateway = Gateway(["m"], {"m": [2.0]}, tokens=60) + self.assertEqual( + self.remeasure(gateway, {"m": 31.0})["m"], + 31.0, + "an unclamped result rewrites the config and restarts the gateway " + "on every deploy, because no two runs measure the same machine", + ) + + def test_a_rate_beyond_tolerance_replaces_the_stored_number(self) -> None: + gateway = Gateway(["m"], {"m": [2.0]}, tokens=60) + self.assertEqual(self.remeasure(gateway, {"m": 10.0})["m"], 30.0) + + def test_a_model_that_cannot_be_reached_keeps_its_stored_rate(self) -> None: + gateway = Gateway(["m"], {"m": [2.0]}) + listing = gateway.urlopen + + def refuse(request, timeout=None): + if request.full_url.endswith("/v1/models"): + return listing(request, timeout) + raise OSError("connection refused") + + gateway.urlopen = refuse + self.assertEqual( + self.remeasure(gateway, {"m": 12.5})["m"], + 12.5, + "one bad minute must not unrank a model against its peers", + ) + + def test_a_model_that_answers_no_tokens_is_left_unranked(self) -> None: + gateway = Gateway(["m"], {"m": [2.0]}, tokens=0) + self.assertEqual(run(gateway), {}) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/roles/svc-ai-litellm/templates/test_config_model_list.py b/tests/unit/python/roles/svc-ai-litellm/templates/test_config_model_list.py index 87c9371a59..73a3990f76 100644 --- a/tests/unit/python/roles/svc-ai-litellm/templates/test_config_model_list.py +++ b/tests/unit/python/roles/svc-ai-litellm/templates/test_config_model_list.py @@ -67,7 +67,13 @@ def _stub_lookup(ollama_models, lmstudio_models): def render( - *, ollama=(), lmstudio=(), keys=None, remote_models=REMOTE_MODELS, router_alias="" + *, + ollama=(), + lmstudio=(), + keys=None, + remote_models=REMOTE_MODELS, + router_alias="", + measured_speed=None, ): """The rendered config as a parsed mapping. @@ -78,6 +84,8 @@ def render( remote_models: the services.litellm.remote_models list in effect. router_alias: the router's alias; empty publishes no router route, which is what every case that predates the router expects. + measured_speed: alias -> tokens per second from the last deploy's + measurement; empty means nothing has been measured yet. """ env = Environment(undefined=StrictUndefined, autoescape=False) # noqa: S701 - YAML, not markup env.filters["bool"] = _ansible_bool @@ -96,6 +104,7 @@ def render( LITELLM_SERVED_PROVIDERS=[name for name, key in (keys or {}).items() if key] + [MOCK["provider"]], LITELLM_ROUTER_ALIAS=router_alias, + LITELLM_MEASURED_SPEED=measured_speed or {}, ) return yaml.safe_load( rendered @@ -311,6 +320,43 @@ class TestTraits(unittest.TestCase): self.assertEqual(info["traits"], {"tools": True}) +class TestMeasuredSpeed(unittest.TestCase): + """A rate has no catalogue, so the deploy measures it and renders it back.""" + + def _entry(self, **kwargs): + return (render(ollama=[SHARED], **kwargs).get("model_list") or [])[0] + + def test_a_measured_rate_becomes_a_trait(self) -> None: + alias = self._entry()["model_name"] + entry = self._entry(measured_speed={alias: 41.7}) + self.assertEqual(entry["model_info"]["traits"], {"speed": 41.7}) + + def test_a_measured_rate_joins_the_declared_traits(self) -> None: + config = render( + ollama=[{**SHARED, "traits": {"tools": True}}], + measured_speed={SHARED["alias"]: 41.7}, + ) + traits = (config.get("model_list") or [])[0]["model_info"]["traits"] + self.assertEqual(traits, {"tools": True, "speed": 41.7}) + + def test_a_declared_rate_outranks_the_measured_one(self) -> None: + config = render( + ollama=[{**SHARED, "traits": {"speed": 5}}], + measured_speed={SHARED["alias"]: 41.7}, + ) + traits = (config.get("model_list") or [])[0]["model_info"]["traits"] + self.assertEqual( + traits, + {"speed": 5}, + "a declaration is the operator overriding the measurement, so the " + "measurement must not overwrite it back on the next deploy", + ) + + def test_a_rate_for_a_model_that_is_gone_publishes_nothing(self) -> None: + entry = self._entry(measured_speed={"a-model-nobody-serves": 41.7}) + self.assertNotIn("model_info", entry) + + class TestHookRegistration(unittest.TestCase): """The callback string and the mounted file are one name in two files."""