interplane.Get Omega
Read in your language

omega-helix

This project has not described itself yet.

Brought by drakestapleton

branch main Branches Tags History

omega-helix / tools / distill / teachers.py

449 lines · 16395 bytes Raw Blame History
1"""Multi-teacher discovery, OpenAI-compatible HTTP client, local Helix & trace teachers.
2
3Supports localhost serving stacks (omega-router :18090, q36-serve :18091, ollm CPU :18098,
4Ollama :11434, vLLM :8000, llama.cpp :8080, LM Studio :1234), local pure-Omega Helix
5checkpoints (`ollm-univ sample` / `dkemit`), and offline JSONL trace replay.
6
7Python 3 standard library only — zero third-party deps, zero telemetry.
8"""
9
10from __future__ import annotations
11
12import hashlib
13import json
14import subprocess
15import time
16import urllib.error
17import urllib.request
18from pathlib import Path
19from typing import Any
20
21from .harvest import harvest_paths, read_ollmdk01_header
22from .verifiers import verify_record
23
24DEFAULT_LOCAL_ENDPOINTS: list[dict[str, str]] = [
25 {"name": "omega-router", "base_url": "http://127.0.0.1:18090/v1"},
26 {"name": "q36-serve", "base_url": "http://127.0.0.1:18091/v1"},
27 {"name": "ollm-cpu", "base_url": "http://127.0.0.1:18098/v1"},
28 {"name": "ollama", "base_url": "http://127.0.0.1:11434/v1"},
29 {"name": "vllm", "base_url": "http://127.0.0.1:8000/v1"},
30 {"name": "llama-cpp", "base_url": "http://127.0.0.1:8080/v1"},
31 {"name": "lm-studio", "base_url": "http://127.0.0.1:1234/v1"},
32]
33
34
35def _extract_choice_text(choice: dict[str, Any]) -> str:
36 msg = choice.get("message")
37 if isinstance(msg, dict):
38 content = msg.get("content")
39 if isinstance(content, str):
40 return content
41 if isinstance(content, list):
42 return "".join(
43 str(p.get("text", "")) for p in content if isinstance(p, dict)
44 )
45 if isinstance(choice.get("text"), str):
46 return choice["text"]
47 return ""
48
49
50def _extract_logprobs(choice: dict[str, Any]) -> list[dict[str, Any]] | None:
51 lp = choice.get("logprobs")
52 if not isinstance(lp, dict):
53 return None
54 content = lp.get("content")
55 if not isinstance(content, list) or not content:
56 return None
57 out: list[dict[str, Any]] = []
58 for item in content:
59 if not isinstance(item, dict):
60 continue
61 top = item.get("top_logprobs")
62 tops: list[dict[str, Any]] = []
63 if isinstance(top, list):
64 for t in top:
65 if isinstance(t, dict) and "token" in t and "logprob" in t:
66 tops.append({"token": str(t["token"]), "logprob": float(t["logprob"])})
67 out.append({
68 "token": str(item.get("token", "")),
69 "logprob": float(item.get("logprob", 0.0)),
70 "top_logprobs": tops,
71 })
72 return out or None
73
74
75def probe_local_teachers(
76 endpoints: list[dict[str, str]] | None = None,
77 timeout: float = 0.6,
78) -> list[dict[str, Any]]:
79 """Fast non-blocking probe of localhost OpenAI-compatible open-source model servers."""
80 targets = endpoints or DEFAULT_LOCAL_ENDPOINTS
81 results: list[dict[str, Any]] = []
82 for ep in targets:
83 name = str(ep.get("name") or ep.get("base_url") or "local")
84 base_url = str(ep["base_url"]).rstrip("/")
85 url = f"{base_url}/models"
86 t0 = time.monotonic()
87 reachable = False
88 models: list[str] = []
89 err_msg = ""
90 req = urllib.request.Request(url, method="GET", headers={"Accept": "application/json"})
91 try:
92 with urllib.request.urlopen(req, timeout=timeout) as resp:
93 raw = resp.read().decode("utf-8", errors="replace")
94 reachable = 200 <= resp.status < 300
95 doc = json.loads(raw) if raw else {}
96 data = doc.get("data") if isinstance(doc, dict) else None
97 if isinstance(data, list):
98 models = [str(m["id"]) for m in data if isinstance(m, dict) and m.get("id")]
99 except urllib.error.HTTPError as exc:
100 err_msg = f"HTTP {exc.code}"
101 except Exception as exc:
102 err_msg = str(exc)
103 results.append({
104 "name": name,
105 "base_url": base_url,
106 "reachable": reachable,
107 "models": models,
108 "latency_ms": round((time.monotonic() - t0) * 1000.0, 2),
109 "error": err_msg if not reachable else "",
110 })
111 return results
112
113
114class TeacherAdapter:
115 name: str = "teacher"
116 provider: str = "base"
117
118 def generate(
119 self,
120 messages: list[dict[str, str]],
121 *,
122 max_tokens: int = 256,
123 temperature: float = 0.7,
124 top_logprobs: int = 0,
125 ) -> dict[str, Any]:
126 raise NotImplementedError
127
128
129class OpenAICompatTeacher(TeacherAdapter):
130 """Pure stdlib client for any OpenAI-compatible teacher (/v1/chat/completions)."""
131
132 def __init__(
133 self,
134 base_url: str,
135 model: str,
136 *,
137 name: str = "",
138 api_key: str = "",
139 timeout: float = 60.0,
140 request_logprobs: bool = True,
141 ) -> None:
142 self.base_url = base_url.rstrip("/")
143 if not self.base_url.endswith("/v1"):
144 self.base_url = f"{self.base_url}/v1"
145 self.model = model
146 self.name = name or f"openai:{model}"
147 self.provider = "openai_compat"
148 self.api_key = api_key
149 self.timeout = float(timeout)
150 self.request_logprobs = bool(request_logprobs)
151
152 def generate(
153 self,
154 messages: list[dict[str, str]],
155 *,
156 max_tokens: int = 256,
157 temperature: float = 0.7,
158 top_logprobs: int = 0,
159 ) -> dict[str, Any]:
160 payload: dict[str, Any] = {
161 "model": self.model,
162 "messages": messages,
163 "max_tokens": int(max_tokens),
164 "temperature": float(temperature),
165 "stream": False,
166 }
167 if self.request_logprobs and top_logprobs > 0:
168 payload["logprobs"] = True
169 payload["top_logprobs"] = min(20, int(top_logprobs))
170
171 headers = {"Content-Type": "application/json", "Accept": "application/json"}
172 if self.api_key:
173 headers["Authorization"] = f"Bearer {self.api_key}"
174
175 req = urllib.request.Request(
176 f"{self.base_url}/chat/completions",
177 data=json.dumps(payload).encode("utf-8"),
178 headers=headers,
179 method="POST",
180 )
181 t0 = time.monotonic()
182 with urllib.request.urlopen(req, timeout=self.timeout) as resp:
183 raw = resp.read().decode("utf-8")
184 latency_ms = round((time.monotonic() - t0) * 1000.0, 2)
185 doc = json.loads(raw)
186 choices = doc.get("choices") or []
187 if not choices or not isinstance(choices[0], dict):
188 raise RuntimeError(f"{self.base_url}: response missing choices")
189 c0 = choices[0]
190 return {
191 "text": _extract_choice_text(c0),
192 "model": str(doc.get("model") or self.model),
193 "provider": self.provider,
194 "teacher_name": self.name,
195 "logprobs": _extract_logprobs(c0),
196 "latency_ms": latency_ms,
197 }
198
199
200class LocalHelixTeacher(TeacherAdapter):
201 """Wraps a local pure-Omega `ollm-univ` checkpoint for text sampling and `dkemit`."""
202
203 def __init__(
204 self,
205 ckpt_path: str | Path,
206 ollm_univ_bin: str | Path,
207 *,
208 name: str = "",
209 seed: int = 42,
210 ) -> None:
211 self.ckpt_path = Path(ckpt_path).expanduser().resolve()
212 self.ollm_univ_bin = Path(ollm_univ_bin).expanduser().resolve()
213 self.name = name or f"helix:{self.ckpt_path.name}"
214 self.provider = "local_helix"
215 self.seed = int(seed)
216
217 def generate(
218 self,
219 messages: list[dict[str, str]],
220 *,
221 max_tokens: int = 32,
222 temperature: float = 0.8,
223 top_logprobs: int = 0,
224 ) -> dict[str, Any]:
225 prompt_text = "\n".join(m.get("content", "") for m in messages if m.get("content")).strip()
226 raw_prompt = prompt_text.encode("utf-8")[:64] or b"hello"
227 # Seeded u8 sample using hex/token IDs accepted by ollm-univ sample
228 tok_ids = [str(b) for b in raw_prompt[:8]]
229 temp_milli = max(1, int(round(temperature * 1000)))
230 top_k = max(0, int(top_logprobs))
231 t0 = time.monotonic()
232 res = subprocess.run(
233 [
234 str(self.ollm_univ_bin),
235 "sample",
236 str(self.ckpt_path),
237 str(max(1, int(max_tokens))),
238 str(temp_milli),
239 str(top_k),
240 str(self.seed),
241 *tok_ids,
242 ],
243 capture_output=True,
244 text=True,
245 timeout=30,
246 check=False,
247 )
248 latency_ms = round((time.monotonic() - t0) * 1000.0, 2)
249 if res.returncode != 0:
250 raise RuntimeError(f"ollm-univ sample failed (rc={res.returncode}): {res.stderr.strip()}")
251 gen_toks: list[int] = []
252 for ln in res.stdout.splitlines():
253 parts = ln.split()
254 if len(parts) >= 2 and parts[0] == "S":
255 gen_toks = [int(x) for x in parts[1:]]
256 break
257 decoded = bytes(t & 0xFF for t in gen_toks).decode("utf-8", errors="replace")
258 return {
259 "text": decoded,
260 "tokens": gen_toks,
261 "model": self.ckpt_path.name,
262 "provider": self.provider,
263 "teacher_name": self.name,
264 "logprobs": None,
265 "latency_ms": latency_ms,
266 }
267
268 def emit_dk(
269 self,
270 tokens_bin: str | Path,
271 out_dk: str | Path,
272 *,
273 K: int = 8,
274 temp: float = 1.5,
275 max_seqs: int | None = None,
276 ) -> dict[str, Any]:
277 temp_milli = max(1, int(round(float(temp) * 1000)))
278 argv = [
279 str(self.ollm_univ_bin),
280 "dkemit",
281 str(self.ckpt_path),
282 str(Path(tokens_bin).expanduser().resolve()),
283 str(Path(out_dk).expanduser().resolve()),
284 str(int(K)),
285 str(temp_milli),
286 ]
287 if max_seqs is not None and int(max_seqs) > 0:
288 argv.append(str(int(max_seqs)))
289 res = subprocess.run(argv, capture_output=True, text=True, timeout=120, check=False)
290 if res.returncode != 0:
291 raise RuntimeError(f"ollm-univ dkemit failed (rc={res.returncode}): {res.stderr.strip()}")
292 return read_ollmdk01_header(out_dk)
293
294
295class TraceReplayTeacher(TeacherAdapter):
296 """Offline zero-network teacher replaying recorded JSONL/OpenWALDO assistant traces."""
297
298 def __init__(self, trace_paths: list[str | Path], *, name: str = "trace-replay") -> None:
299 self.trace_paths = [Path(p).expanduser().resolve() for p in trace_paths]
300 self.name = name
301 self.provider = "trace_replay"
302 harvested = harvest_paths(self.trace_paths)
303 self.records = harvested["records"]
304 self._cursor = 0
305 self._by_prompt: dict[str, dict[str, Any]] = {}
306 for rec in self.records:
307 msgs = rec.get("messages") or []
308 user_txt = "\n".join(m["content"] for m in msgs if m["role"] == "user").strip()
309 if user_txt:
310 self._by_prompt.setdefault(user_txt, rec)
311
312 def generate(
313 self,
314 messages: list[dict[str, str]],
315 *,
316 max_tokens: int = 256,
317 temperature: float = 0.0,
318 top_logprobs: int = 0,
319 ) -> dict[str, Any]:
320 if not self.records:
321 raise RuntimeError("TraceReplayTeacher has zero records")
322 t0 = time.monotonic()
323 user_txt = "\n".join(m.get("content", "") for m in messages if m.get("role") == "user").strip()
324 rec = self._by_prompt.get(user_txt)
325 if rec is None:
326 rec = self.records[self._cursor % len(self.records)]
327 self._cursor += 1
328 return {
329 "text": str(rec.get("assistant_text") or rec["text"]),
330 "model": str(rec.get("teacher_model") or self.name),
331 "provider": self.provider,
332 "teacher_name": self.name,
333 "logprobs": rec.get("logprobs"),
334 "latency_ms": round((time.monotonic() - t0) * 1000.0, 2),
335 }
336
337
338class TeacherRouter:
339 """Multi-teacher routing (`round_robin`, `ensemble_best_of`, `fallback`) + telemetry."""
340
341 def __init__(
342 self,
343 teachers: list[TeacherAdapter],
344 *,
345 strategy: str = "round_robin",
346 verifiers: list[str] | tuple[str, ...] = ("nonempty",),
347 ) -> None:
348 if not teachers:
349 raise ValueError("TeacherRouter requires at least one teacher")
350 if strategy not in ("round_robin", "ensemble_best_of", "fallback"):
351 raise ValueError(f"unsupported router strategy {strategy!r}")
352 self.teachers = list(teachers)
353 self.strategy = strategy
354 self.verifiers = list(verifiers)
355 self._idx = 0
356 self.stats: dict[str, dict[str, Any]] = {
357 t.name: {"calls": 0, "passes": 0, "errors": 0, "total_latency_ms": 0.0}
358 for t in self.teachers
359 }
360
361 def generate_best(
362 self,
363 messages: list[dict[str, str]],
364 *,
365 max_tokens: int = 256,
366 temperature: float = 0.7,
367 top_logprobs: int = 0,
368 ) -> dict[str, Any]:
369 if self.strategy == "round_robin":
370 teacher = self.teachers[self._idx % len(self.teachers)]
371 self._idx += 1
372 return self._call_and_score(teacher, messages, max_tokens=max_tokens, temperature=temperature, top_logprobs=top_logprobs)
373
374 if self.strategy == "fallback":
375 last_err: Exception | None = None
376 for teacher in self.teachers:
377 try:
378 out = self._call_and_score(teacher, messages, max_tokens=max_tokens, temperature=temperature, top_logprobs=top_logprobs)
379 if out["verification"]["passed"]:
380 return out
381 last_out = out
382 except Exception as exc:
383 last_err = exc
384 continue
385 if "last_out" in locals():
386 return last_out
387 raise RuntimeError(f"all fallback teachers failed: {last_err}")
388
389 # ensemble_best_of: query every teacher and select highest verification score (then latency)
390 candidates: list[dict[str, Any]] = []
391 last_err = None
392 for teacher in self.teachers:
393 try:
394 candidates.append(
395 self._call_and_score(teacher, messages, max_tokens=max_tokens, temperature=temperature, top_logprobs=top_logprobs)
396 )
397 except Exception as exc:
398 last_err = exc
399 if not candidates:
400 raise RuntimeError(f"all ensemble teachers failed: {last_err}")
401 candidates.sort(key=lambda c: (-float(c["verification"]["score"]), float(c.get("latency_ms", 0.0))))
402 best = dict(candidates[0])
403 best["ensemble_candidates"] = len(candidates)
404 return best
405
406 def _call_and_score(
407 self,
408 teacher: TeacherAdapter,
409 messages: list[dict[str, str]],
410 *,
411 max_tokens: int,
412 temperature: float,
413 top_logprobs: int,
414 ) -> dict[str, Any]:
415 st = self.stats[teacher.name]
416 st["calls"] += 1
417 try:
418 res = teacher.generate(
419 messages,
420 max_tokens=max_tokens,
421 temperature=temperature,
422 top_logprobs=top_logprobs,
423 )
424 except Exception:
425 st["errors"] += 1
426 raise
427 st["total_latency_ms"] += float(res.get("latency_ms", 0.0))
428 ver = verify_record(res.get("text", ""), self.verifiers)
429 if ver["passed"]:
430 st["passes"] += 1
431 out = dict(res)
432 out["verification"] = ver
433 out["sha256"] = hashlib.sha256(str(res.get("text", "")).encode("utf-8")).hexdigest()
434 return out
435
436 def summary(self) -> list[dict[str, Any]]:
437 out: list[dict[str, Any]] = []
438 for t in self.teachers:
439 st = self.stats[t.name]
440 calls = st["calls"]
441 out.append({
442 "name": t.name,
443 "provider": t.provider,
444 "calls": calls,
445 "passes": st["passes"],
446 "errors": st["errors"],
447 "avg_latency_ms": round(st["total_latency_ms"] / calls, 2) if calls else 0.0,
448 })
449 return out