feat: per-signature LM router (lm[<SigName>] config blocks + predict factory)
His ask: one general construction door so a signature's model/settings change by editing config alone — no call-site ifs, now or ever after. lm[ExtractSignature]: as a config.yaml sibling of lm: (provider: inherits base_url + transport ceiling; model: builds a dedicated cached LM; other keys -> per-call lm_kwargs through Predict config, honored by dspy 3.4.1 _forward_preprocess). predict() is the door: the 13 construction sites swapped mechanically. First block shipped: ExtractSignature max_tokens=1800 (the 4096 cap was 3x headroom that only extended the worst case on slow local models — the 40-min arithmetic). run.log reports active blocks at startup. TDD: tests/lm_signature_router.py 5/5 (parse, no-block defaults, settings-only override, dedicated+cached LM, provenance listing).
This commit is contained in:
@@ -24,6 +24,16 @@ lm:
|
|||||||
read_timeout_s: 300 # glm answers EXTRACT in ~3s; 300s bounds a wedged call
|
read_timeout_s: 300 # glm answers EXTRACT in ~3s; 300s bounds a wedged call
|
||||||
num_retries: 2 # cloud retries are cheap
|
num_retries: 2 # cloud retries are cheap
|
||||||
|
|
||||||
|
# per-signature settings: lm[<SignatureName>] overrides the active provider's
|
||||||
|
# settings for that stage ONLY (model/max_tokens/temperature/...). provider:
|
||||||
|
# selects which provider block inherits base_url + transport ceiling; model:
|
||||||
|
# builds a dedicated cached LM for that stage. No block -> run defaults.
|
||||||
|
lm[ExtractSignature]:
|
||||||
|
provider: local
|
||||||
|
max_tokens: 1800 # EXTRACT output is facts+quotes: ~120 tok/fact;
|
||||||
|
# 4096 was 3x headroom that only extended hangs
|
||||||
|
# on slow local models (the 40-min arithmetic)
|
||||||
|
|
||||||
budget:
|
budget:
|
||||||
max_llm_calls: 80 # per FLOOP run (children get a slice; fan-outs multiply
|
max_llm_calls: 80 # per FLOOP run (children get a slice; fan-outs multiply
|
||||||
# entity questions — a 3-river fan needs ~3x a scalar)
|
# entity questions — a 3-river fan needs ~3x a scalar)
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ import re
|
|||||||
from enum import Enum
|
from enum import Enum
|
||||||
|
|
||||||
import dspy
|
import dspy
|
||||||
|
from floop.llm import predict
|
||||||
from pydantic import BaseModel
|
from pydantic import BaseModel
|
||||||
|
|
||||||
from .state import AnswerType
|
from .state import AnswerType
|
||||||
@@ -135,12 +136,12 @@ class FloopModules:
|
|||||||
"""All LLM entry points of the draft. Each returns a dspy.Prediction."""
|
"""All LLM entry points of the draft. Each returns a dspy.Prediction."""
|
||||||
|
|
||||||
def __init__(self) -> None:
|
def __init__(self) -> None:
|
||||||
self.init = dspy.Predict(InitSignature)
|
self.init = predict(InitSignature)
|
||||||
self.route = dspy.Predict(RouteSignature)
|
self.route = predict(RouteSignature)
|
||||||
self.expert = dspy.Predict(ExpertSignature)
|
self.expert = predict(ExpertSignature)
|
||||||
self.missing = dspy.Predict(MissingSignature)
|
self.missing = predict(MissingSignature)
|
||||||
self.answer = dspy.Predict(AnswerSignature)
|
self.answer = predict(AnswerSignature)
|
||||||
self.mask = dspy.Predict(EntityMaskSignature)
|
self.mask = predict(EntityMaskSignature)
|
||||||
|
|
||||||
def init_decompose(self, question: str) -> tuple[list[dict], str]:
|
def init_decompose(self, question: str) -> tuple[list[dict], str]:
|
||||||
"""(parsed subquestions, raw model output). The machine decides what
|
"""(parsed subquestions, raw model output). The machine decides what
|
||||||
|
|||||||
@@ -233,6 +233,75 @@ def install_prompt_log(streams) -> None:
|
|||||||
_ACTIVE: "dspy.LM | None" = None
|
_ACTIVE: "dspy.LM | None" = None
|
||||||
_PROMPT_LOG: "PromptLogCallback | None" = None
|
_PROMPT_LOG: "PromptLogCallback | None" = None
|
||||||
|
|
||||||
|
# per-signature dedicated LMs (lm[<SigName>] blocks with a model override),
|
||||||
|
# keyed f"{provider}:{model}" — ONE LM per provider+model, built once
|
||||||
|
_SIGNATURE_LMS: dict[str, "dspy.LM"] = {}
|
||||||
|
|
||||||
|
|
||||||
|
def _signature_settings(sig) -> dict:
|
||||||
|
"""The lm[<SignatureName>] block for a signature, or {} when absent."""
|
||||||
|
name = getattr(sig, "__name__", None) or str(sig)
|
||||||
|
return _load_yaml().get(f"lm[{name}]") or {}
|
||||||
|
|
||||||
|
|
||||||
|
def signature_overrides() -> dict[str, dict]:
|
||||||
|
"""Every lm[<SigName>] block in config.yaml, by signature name.
|
||||||
|
|
||||||
|
For the run.log provenance line: which stages run with dedicated
|
||||||
|
settings today, visible at startup.
|
||||||
|
"""
|
||||||
|
return {k[3:-1]: v for k, v in _load_yaml().items()
|
||||||
|
if k.startswith("lm[") and k.endswith("]")}
|
||||||
|
|
||||||
|
|
||||||
|
def predict(signature, **extra_config):
|
||||||
|
"""dspy.Predict construction honoring per-signature config blocks.
|
||||||
|
|
||||||
|
A `lm[<SignatureName>]:` block in config.yaml (sibling of `lm:`) may
|
||||||
|
carry: provider (which provider block to inherit base_url + transport
|
||||||
|
ceiling from — defaults to the active provider), model, max_tokens,
|
||||||
|
temperature, and any other dspy.LM kwarg. Settings WITHOUT a model
|
||||||
|
travel as per-call lm_kwargs through Predict's own config (dspy 3.4.1
|
||||||
|
merges self.config into the request — verified on the wire); a model:
|
||||||
|
override builds ONE dedicated cached dspy.LM (same provider ceiling,
|
||||||
|
its own model id) bound to the Predict instance. No block -> a plain
|
||||||
|
dspy.Predict with the run defaults, untouched.
|
||||||
|
|
||||||
|
This is the ONE construction door: swapping dspy.Predict(...) for
|
||||||
|
predict(...) here means a signature's model/settings change by
|
||||||
|
editing config alone — no call-site ifs, now or ever after.
|
||||||
|
"""
|
||||||
|
import dspy
|
||||||
|
block = _signature_settings(signature)
|
||||||
|
if not block:
|
||||||
|
return dspy.Predict(signature, **extra_config)
|
||||||
|
cfg = _load_yaml()["lm"]
|
||||||
|
provider = block.get("provider") or cfg.get("default")
|
||||||
|
base = cfg[provider]
|
||||||
|
settings = {k: v for k, v in block.items() if k != "provider"}
|
||||||
|
model = settings.pop("model", None)
|
||||||
|
if model is None:
|
||||||
|
return dspy.Predict(signature, **settings, **extra_config)
|
||||||
|
key = f"{provider}:{model}"
|
||||||
|
if key not in _SIGNATURE_LMS:
|
||||||
|
kwargs: dict = {
|
||||||
|
"model": f"openai/{model}",
|
||||||
|
"base_url": base["base_url"],
|
||||||
|
"api_base": base["base_url"],
|
||||||
|
"max_tokens": settings.pop("max_tokens", base["max_tokens"]),
|
||||||
|
"temperature": settings.pop("temperature", base["temperature"]),
|
||||||
|
"api_key": os.environ.get(base.get("api_key_env", ""), "empty"),
|
||||||
|
}
|
||||||
|
if base.get("read_timeout_s"):
|
||||||
|
kwargs["timeout"] = float(base["read_timeout_s"])
|
||||||
|
if base.get("num_retries") is not None:
|
||||||
|
kwargs["num_retries"] = int(base["num_retries"])
|
||||||
|
kwargs.update(settings) # any other block keys pass through
|
||||||
|
_SIGNATURE_LMS[key] = dspy.LM(**kwargs)
|
||||||
|
inst = dspy.Predict(signature, **extra_config)
|
||||||
|
inst.lm = _SIGNATURE_LMS[key]
|
||||||
|
return inst
|
||||||
|
|
||||||
|
|
||||||
def active_lm() -> "dspy.LM":
|
def active_lm() -> "dspy.LM":
|
||||||
"""The configured dspy.LM, configuring it lazily if needed (baseline mode uses it raw)."""
|
"""The configured dspy.LM, configuring it lazily if needed (baseline mode uses it raw)."""
|
||||||
|
|||||||
@@ -25,6 +25,7 @@ import time
|
|||||||
from dataclasses import dataclass
|
from dataclasses import dataclass
|
||||||
|
|
||||||
import dspy
|
import dspy
|
||||||
|
from floop.llm import predict
|
||||||
|
|
||||||
from .checks import check_candidate, quote_containment
|
from .checks import check_candidate, quote_containment
|
||||||
from .chunker import chunk_page
|
from .chunker import chunk_page
|
||||||
@@ -174,12 +175,12 @@ class KnowledgeExpert:
|
|||||||
self.store = store or KnowledgeStore(self.cfg.kb_path)
|
self.store = store or KnowledgeStore(self.cfg.kb_path)
|
||||||
self.client = client or WikipediaClient()
|
self.client = client or WikipediaClient()
|
||||||
self.streams = streams
|
self.streams = streams
|
||||||
self.extract = dspy.Predict(ExtractSignature)
|
self.extract = predict(ExtractSignature)
|
||||||
self.answer = dspy.Predict(AnswerFromKG)
|
self.answer = predict(AnswerFromKG)
|
||||||
self.select_table = dspy.Predict(SelectTableSignature)
|
self.select_table = predict(SelectTableSignature)
|
||||||
self.verify_count = dspy.Predict(VerifyCountSignature)
|
self.verify_count = predict(VerifyCountSignature)
|
||||||
self.skim_promote = dspy.Predict(SkimPromoteSignature)
|
self.skim_promote = predict(SkimPromoteSignature)
|
||||||
self.skim_tables = dspy.Predict(SkimTableSignature)
|
self.skim_tables = predict(SkimTableSignature)
|
||||||
self._checked = 0
|
self._checked = 0
|
||||||
self._merged = 0
|
self._merged = 0
|
||||||
# semantic probe: cached question vector for this call (the probe
|
# semantic probe: cached question vector for this call (the probe
|
||||||
@@ -304,7 +305,7 @@ class KnowledgeExpert:
|
|||||||
from .prover import evaluate, re_execute, validate_query
|
from .prover import evaluate, re_execute, validate_query
|
||||||
from .translate_dsl import TranslateToDSL
|
from .translate_dsl import TranslateToDSL
|
||||||
if not hasattr(self, "translate_dsl"):
|
if not hasattr(self, "translate_dsl"):
|
||||||
self.translate_dsl = dspy.Predict(TranslateToDSL)
|
self.translate_dsl = predict(TranslateToDSL)
|
||||||
rels = [r[0] for r in self.store.db.execute(
|
rels = [r[0] for r in self.store.db.execute(
|
||||||
"SELECT DISTINCT rel FROM edges WHERE retracted=0 "
|
"SELECT DISTINCT rel FROM edges WHERE retracted=0 "
|
||||||
"ORDER BY rel LIMIT 200").fetchall()]
|
"ORDER BY rel LIMIT 200").fetchall()]
|
||||||
|
|||||||
@@ -98,6 +98,12 @@ def main() -> None:
|
|||||||
f"baseline={baseline} no_cache={no_cache} "
|
f"baseline={baseline} no_cache={no_cache} "
|
||||||
f"read_timeout_s={lm_info.get('read_timeout_s')} "
|
f"read_timeout_s={lm_info.get('read_timeout_s')} "
|
||||||
f"num_retries={lm_info.get('num_retries')}")
|
f"num_retries={lm_info.get('num_retries')}")
|
||||||
|
from floop.llm import signature_overrides
|
||||||
|
ov = signature_overrides()
|
||||||
|
if ov:
|
||||||
|
streams.log(f"signature_overrides: "
|
||||||
|
+ ", ".join(f"{name}[{', '.join(f'{k}={v}' for k, v in blk.items())}]"
|
||||||
|
for name, blk in sorted(ov.items())))
|
||||||
|
|
||||||
if baseline:
|
if baseline:
|
||||||
answer = run_baseline(question, streams)
|
answer = run_baseline(question, streams)
|
||||||
|
|||||||
@@ -0,0 +1,113 @@
|
|||||||
|
"""The per-signature LM router tests (lm[<SignatureName>] config blocks).
|
||||||
|
|
||||||
|
Law: any dspy.Signature may carry its own settings block in config.yaml —
|
||||||
|
`lm[ExtractSignature]:` — inheriting its provider's transport ceiling and
|
||||||
|
overriding model/max_tokens/temperature. The factory `floop.llm.predict()`
|
||||||
|
applies the block at CONSTRUCTION: no call-site if's; a signature can
|
||||||
|
change model by editing config alone, forever after (his ask, 26/10: one
|
||||||
|
general function so no more config edits mid-code as the pipeline grows).
|
||||||
|
|
||||||
|
Pinned:
|
||||||
|
1. The config block parses and carries only the intended overrides.
|
||||||
|
2. predict() with no block -> plain dspy.Predict (defaults, untouched).
|
||||||
|
3. predict() with a settings-only block -> Predict whose config carries
|
||||||
|
the overrides (dspy merges self.config as lm_kwargs per call —
|
||||||
|
verified against dspy 3.4.1 _forward_preprocess).
|
||||||
|
4. predict() with a model: override -> Predict bound to a DEDICATED
|
||||||
|
cached dspy.LM (same provider base_url/ceiling, its own model); a
|
||||||
|
second predict() returns the SAME LM object (no rebuild per call).
|
||||||
|
5. A block for a signature that is never constructed breaks nothing.
|
||||||
|
6. signature_overrides() lists the active blocks for the run.log line.
|
||||||
|
|
||||||
|
Run: .venv/bin/python tests/lm_signature_router.py
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||||
|
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||||
|
|
||||||
|
import floop.llm as llm
|
||||||
|
from floop.llm import predict, signature_overrides
|
||||||
|
from knowledge.extract import ExtractSignature
|
||||||
|
from floop.dspy_modules import InitSignature
|
||||||
|
|
||||||
|
|
||||||
|
def test_config_block_parses():
|
||||||
|
"""config.yaml carries lm[ExtractSignature] with the intended override."""
|
||||||
|
import yaml
|
||||||
|
cfg = yaml.safe_load((Path(__file__).resolve().parent.parent
|
||||||
|
/ "config.yaml").read_text())
|
||||||
|
assert "lm[ExtractSignature]" in cfg, (
|
||||||
|
"the per-signature block must be a top-level key `lm[<SigName>]`")
|
||||||
|
block = cfg["lm[ExtractSignature]"]
|
||||||
|
assert block.get("max_tokens") == 1800, block
|
||||||
|
assert "model" not in block, "no model override yet (his call: default)"
|
||||||
|
assert "lm[NoSuchSignature]" not in cfg
|
||||||
|
print("ok: config.yaml carries the lm[ExtractSignature] block, model-free")
|
||||||
|
|
||||||
|
|
||||||
|
def test_no_block_means_plain_predict():
|
||||||
|
"""A signature without a block gets the defaults, untouched."""
|
||||||
|
p = predict(InitSignature)
|
||||||
|
assert type(p).__name__ == "Predict"
|
||||||
|
assert not p.config, f"no overrides expected, got {p.config}"
|
||||||
|
assert p.lm is None, "no dedicated LM without a model override"
|
||||||
|
print("ok: no block -> plain dspy.Predict, defaults untouched")
|
||||||
|
|
||||||
|
|
||||||
|
def test_settings_block_becomes_predict_config():
|
||||||
|
"""Settings-only block -> per-call lm_kwargs (dspy honors self.config)."""
|
||||||
|
p = predict(ExtractSignature)
|
||||||
|
assert p.config.get("max_tokens") == 1800, p.config
|
||||||
|
assert p.lm is None, "settings-only block must not build a new LM"
|
||||||
|
print("ok: lm[ExtractSignature].max_tokens -> Predict config (lm_kwargs)")
|
||||||
|
|
||||||
|
|
||||||
|
def test_model_override_builds_dedicated_cached_lm():
|
||||||
|
"""A model: override binds a dedicated LM; the factory caches it."""
|
||||||
|
orig_load = llm._load_yaml
|
||||||
|
llm._load_yaml = lambda: { # noqa: E731 — monkeypatch, test-only
|
||||||
|
"lm": {"default": "local",
|
||||||
|
"local": {"base_url": "http://127.0.0.1:11435/v1",
|
||||||
|
"model": "qwen3.8-27b-uc-64k:latest",
|
||||||
|
"max_tokens": 4096, "temperature": 0.0,
|
||||||
|
"read_timeout_s": 1800, "num_retries": 1}},
|
||||||
|
"lm[InitSignature]": {"provider": "local", "model": "qwen3.8:27b",
|
||||||
|
"max_tokens": 1024},
|
||||||
|
}
|
||||||
|
llm._SIGNATURE_LMS.clear()
|
||||||
|
try:
|
||||||
|
p = predict(InitSignature)
|
||||||
|
assert p.lm is not None, "model override must bind a dedicated LM"
|
||||||
|
assert p.lm.model == "openai/qwen3.8:27b", p.lm.model
|
||||||
|
assert p.lm.kwargs["timeout"] == 1800, "inherits provider ceiling"
|
||||||
|
assert p.lm.kwargs["max_tokens"] == 1024, "block max_tokens on the LM"
|
||||||
|
assert not p.config, "dedicated LM carries the settings, not config"
|
||||||
|
# cached: a second construction reuses the SAME LM object
|
||||||
|
p2 = predict(InitSignature)
|
||||||
|
assert p2.lm is p.lm, "the factory must cache LMs per provider+model"
|
||||||
|
finally:
|
||||||
|
llm._load_yaml = orig_load
|
||||||
|
llm._SIGNATURE_LMS.clear()
|
||||||
|
print("ok: model override -> dedicated cached LM (provider ceiling inherited)")
|
||||||
|
|
||||||
|
|
||||||
|
def test_signature_overrides_lists_active_blocks():
|
||||||
|
ov = signature_overrides()
|
||||||
|
block = ov.get("ExtractSignature")
|
||||||
|
assert block and block.get("max_tokens") == 1800 and block.get("provider") == "local", ov
|
||||||
|
assert "NoSuchSignature" not in ov
|
||||||
|
print(f"ok: signature_overrides lists active blocks: {list(ov)}")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
test_config_block_parses()
|
||||||
|
test_no_block_means_plain_predict()
|
||||||
|
test_settings_block_becomes_predict_config()
|
||||||
|
test_model_override_builds_dedicated_cached_lm()
|
||||||
|
test_signature_overrides_lists_active_blocks()
|
||||||
|
print("\nlm_signature_router: 5/5 ok")
|
||||||
Reference in New Issue
Block a user