Download guac_coder/trace.py from npc-worldwide/guac-coder: direct link, hf CLI and curl.
- Browser
- Download file 17.8 kB
-
https://huggingface.co/npc-worldwide/guac-coder/resolve/main/guac_coder/trace.py
- Command line
-
hf download hf://npc-worldwide/guac-coder/guac_coder/trace.py
-
curl -L -o trace.py https://huggingface.co/npc-worldwide/guac-coder/resolve/main/guac_coder/trace.py
17.8 kB
| """Trace generation against a local Ollama server. | |
| This is the data-collection half of the loop: run a small local model over the | |
| guac-coder research tasks, keep every raw response, and score it with the same | |
| 13-rule reward set the trainer optimizes. The output is a JSONL of traces plus a | |
| summary, designed to be re-run and diffed as the rules are iterated on. | |
| No third-party HTTP dependency: talks to Ollama's /api/generate via urllib. | |
| """ | |
| import hashlib | |
| import json | |
| import logging | |
| import os | |
| import re | |
| import time | |
| import urllib.error | |
| import urllib.request | |
| from typing import Any, Dict, Iterator, List, Optional, Tuple | |
| from guac_coder.data import build_prompt, load_research_tasks | |
| logger = logging.getLogger("guac_coder.trace") | |
| DEFAULT_BASE_URL = "http://localhost:11434" | |
| DEFAULT_NUM_PREDICT = 1024 | |
| _PY_FENCE = re.compile(r"```(?:python|py)?\s*\n(.*?)```", re.DOTALL) | |
| def extract_code(text: str) -> Tuple[str, str]: | |
| """Pull the Python implementation out of a model response. | |
| Returns (code, source) where source is one of 'fence', 'whole_text' or | |
| 'empty'. Fenced blocks are preferred; the largest fence wins because small | |
| models often emit an example snippet before the real answer. | |
| """ | |
| if not text or not text.strip(): | |
| return "", "empty" | |
| fences = _PY_FENCE.findall(text) | |
| if fences: | |
| best = max(fences, key=len) | |
| if best.strip(): | |
| return best.strip(), "fence" | |
| stripped = text.strip() | |
| # Truncated generations often leave an opening fence with no close. | |
| # [ \t]*\n? rather than \s*\n: \s* is greedy and would swallow the very | |
| # newline the pattern then requires, making this branch unreachable. | |
| unterminated = re.match(r"^```(?:python|py)?[ \t]*\n?(.*)$", stripped, re.DOTALL) | |
| if unterminated: | |
| body = unterminated.group(1).strip() | |
| if body: | |
| return body, "fence_unterminated" | |
| looks_python = any(marker in stripped for marker in ("import ", "def ", "class ", "print(")) | |
| if looks_python: | |
| return stripped, "whole_text" | |
| return "", "empty" | |
| def _post(url: str, payload: Dict[str, Any], timeout: float) -> Dict[str, Any]: | |
| data = json.dumps(payload).encode("utf-8") | |
| req = urllib.request.Request(url, data=data, headers={"Content-Type": "application/json"}) | |
| with urllib.request.urlopen(req, timeout=timeout) as resp: | |
| return json.loads(resp.read().decode("utf-8")) | |
| def list_models(base_url: str = DEFAULT_BASE_URL, timeout: float = 10.0) -> List[str]: | |
| """Return the model names available on the Ollama server.""" | |
| try: | |
| with urllib.request.urlopen(f"{base_url}/api/tags", timeout=timeout) as resp: | |
| payload = json.loads(resp.read().decode("utf-8")) | |
| except (urllib.error.URLError, OSError) as exc: | |
| raise RuntimeError(f"Ollama not reachable at {base_url}: {exc}") from exc | |
| return [m.get("name", "") for m in payload.get("models", [])] | |
| def require_models(models: List[str], base_url: str = DEFAULT_BASE_URL) -> None: | |
| """Raise a helpful error listing any models missing from the server.""" | |
| available = list_models(base_url) | |
| missing = [m for m in models if m not in available] | |
| if missing: | |
| raise RuntimeError( | |
| f"model(s) not present in Ollama: {missing}. " | |
| f"Available: {', '.join(available[:10])}. Pull with: ollama pull <model>" | |
| ) | |
| def generate( | |
| model: str, | |
| prompt: str, | |
| base_url: str = DEFAULT_BASE_URL, | |
| num_predict: int = DEFAULT_NUM_PREDICT, | |
| temperature: float = 0.8, | |
| seed: Optional[int] = None, | |
| think: Optional[bool] = False, | |
| timeout: float = 600.0, | |
| retries: int = 2, | |
| ) -> Dict[str, Any]: | |
| """Generate one completion and return text plus timing metadata. | |
| ``think=False`` disables reasoning traces on models that have them; those | |
| traces consume the whole token budget and leave nothing for the code. | |
| """ | |
| options: Dict[str, Any] = { | |
| "num_predict": num_predict, | |
| "temperature": temperature, | |
| } | |
| if seed is not None: | |
| options["seed"] = seed | |
| payload: Dict[str, Any] = { | |
| "model": model, | |
| "prompt": prompt, | |
| "stream": False, | |
| "options": options, | |
| } | |
| if think is not None: | |
| payload["think"] = think | |
| last_exc: Optional[Exception] = None | |
| for attempt in range(retries + 1): | |
| started = time.time() | |
| try: | |
| raw = _post(f"{base_url}/api/generate", payload, timeout) | |
| elapsed = time.time() - started | |
| eval_count = raw.get("eval_count") or 0 | |
| eval_ns = raw.get("eval_duration") or 0 | |
| return { | |
| "response": raw.get("response", "") or "", | |
| "num_predict": num_predict, | |
| "thinking": raw.get("thinking", "") or "", | |
| "done_reason": raw.get("done_reason"), | |
| "eval_count": eval_count, | |
| "prompt_eval_count": raw.get("prompt_eval_count"), | |
| "total_ms": round(elapsed * 1000, 1), | |
| "tokens_per_sec": (round(eval_count / (eval_ns / 1e9), 2) if eval_ns else None), | |
| } | |
| except urllib.error.HTTPError as exc: | |
| body = exc.read().decode("utf-8", "replace")[:300] | |
| # Older servers reject the unknown 'think' field; retry without it. | |
| if "think" in body and "think" in payload: | |
| logger.warning("server rejected 'think'; retrying without it") | |
| payload.pop("think", None) | |
| continue | |
| last_exc = RuntimeError(f"HTTP {exc.code}: {body}") | |
| except (urllib.error.URLError, OSError, json.JSONDecodeError) as exc: | |
| last_exc = exc | |
| if attempt < retries: | |
| time.sleep(1.5 * (attempt + 1)) | |
| raise RuntimeError(f"generation failed for {model}: {last_exc}") | |
| def _trace_id( | |
| model: str, | |
| task_id: int, | |
| sample_index: int, | |
| seed: Optional[int] = None, | |
| num_predict: Optional[int] = None, | |
| ) -> str: | |
| """Stable id for one planned generation. | |
| Seed and token budget are part of the id: changing either produces a | |
| genuinely different generation, so it must not be treated as already done | |
| when resuming. Without this, a run configured with different sampling | |
| silently reuses stale rows. | |
| """ | |
| raw = f"{model}|{task_id}|{sample_index}|{seed}|{num_predict}".encode("utf-8") | |
| return hashlib.sha1(raw).hexdigest()[:16] | |
| def make_trace( | |
| model: str, | |
| task: str, | |
| task_id: int, | |
| sample_index: int, | |
| gen: Dict[str, Any], | |
| seed: Optional[int] = None, | |
| reward_cfg: Optional[Any] = None, | |
| rater: str = "static", | |
| ) -> Dict[str, Any]: | |
| """Bundle one generation into a scored trace record. | |
| ``rater`` selects the scoring backend (see | |
| :func:`guac_coder.training.score_completion`): ``"static"`` (default), | |
| ``"decision"`` (Ollama decision model such as ``clef``) or ``"llm"``. | |
| The rater used is recorded on every trace so result files stay comparable. | |
| """ | |
| code, source = extract_code(gen.get("response", "")) | |
| if code: | |
| from guac_coder.config import RewardConfig | |
| from guac_coder.training import score_completion | |
| cfg = reward_cfg or RewardConfig(rater=rater) | |
| total, details = score_completion(code, lambda **kwargs: {}, cfg, rater=rater) | |
| rules = details.get("rules", {}) | |
| else: | |
| rules = {} | |
| total = None | |
| thinking = gen.get("thinking", "") or "" | |
| if code: | |
| empty_reason = None | |
| elif thinking: | |
| empty_reason = "budget_exhausted_in_thinking" | |
| else: | |
| empty_reason = "no_text" | |
| return { | |
| "trace_id": _trace_id(model, task_id, sample_index, seed, gen.get("num_predict")), | |
| "model": model, | |
| "task_id": task_id, | |
| "sample_index": sample_index, | |
| "seed": seed, | |
| "task": task, | |
| "raw_response": gen.get("response", ""), | |
| "thinking": thinking, | |
| "thinking_chars": len(thinking), | |
| "empty_reason": empty_reason, | |
| "code": code, | |
| "code_source": source, | |
| "code_chars": len(code), | |
| "total_reward": total, | |
| "rater": rater, | |
| "rules": rules, | |
| "done_reason": gen.get("done_reason"), | |
| "eval_count": gen.get("eval_count"), | |
| "num_predict": gen.get("num_predict"), | |
| "total_ms": gen.get("total_ms"), | |
| "tokens_per_sec": gen.get("tokens_per_sec"), | |
| } | |
| def collect_traces( | |
| models: List[str], | |
| tasks: Optional[List[str]] = None, | |
| n_samples: int = 1, | |
| base_url: str = DEFAULT_BASE_URL, | |
| num_predict: int = DEFAULT_NUM_PREDICT, | |
| temperature: float = 0.8, | |
| seed: Optional[int] = None, | |
| think: Optional[bool] = False, | |
| timeout: float = 600.0, | |
| rater: str = "static", | |
| reward_cfg: Optional[Any] = None, | |
| ) -> Iterator[Dict[str, Any]]: | |
| """Yield scored traces for every (model, task, sample) combination. | |
| ``rater`` chooses the scoring backend: ``"static"`` (default, the 13 | |
| regex/AST rules), ``"decision"`` (Ollama decision model such as ``clef``) | |
| or ``"llm"``. | |
| """ | |
| tasks = tasks if tasks is not None else load_research_tasks() | |
| for model in models: | |
| for task_id, task in enumerate(tasks): | |
| prompt = build_prompt(task) | |
| for sample_index in range(n_samples): | |
| sample_seed = (seed + sample_index) if seed is not None else None | |
| gen = generate( | |
| model=model, | |
| prompt=prompt, | |
| base_url=base_url, | |
| num_predict=num_predict, | |
| temperature=temperature, | |
| seed=sample_seed, | |
| think=think, | |
| timeout=timeout, | |
| ) | |
| trace = make_trace( | |
| model, | |
| task, | |
| task_id, | |
| sample_index, | |
| gen, | |
| seed=sample_seed, | |
| reward_cfg=reward_cfg, | |
| rater=rater, | |
| ) | |
| logger.info( | |
| "%s task=%d sample=%d reward=%s chars=%d %sms", | |
| model, | |
| task_id, | |
| sample_index, | |
| "None" if trace["total_reward"] is None else f"{trace['total_reward']:+.3f}", | |
| trace["code_chars"], | |
| trace["total_ms"], | |
| ) | |
| yield trace | |
| def _load_done(traces_path: str) -> set: | |
| """Trace ids already present on disk, so runs can resume.""" | |
| done = set() | |
| if not os.path.isfile(traces_path): | |
| return done | |
| with open(traces_path, "r", encoding="utf-8") as fh: | |
| for line in fh: | |
| line = line.strip() | |
| if not line: | |
| continue | |
| try: | |
| done.add(json.loads(line)["trace_id"]) | |
| except (json.JSONDecodeError, KeyError): | |
| continue | |
| return done | |
| def summarize(traces: List[Dict[str, Any]]) -> Dict[str, Any]: | |
| """Aggregate traces into per-model reward statistics and per-rule means.""" | |
| by_model: Dict[str, List[Dict[str, Any]]] = {} | |
| for t in traces: | |
| by_model.setdefault(t["model"], []).append(t) | |
| summary: Dict[str, Any] = {"n_traces": len(traces), "models": {}} | |
| for model, rows in by_model.items(): | |
| scored = [r for r in rows if r.get("total_reward") is not None] | |
| totals = [r["total_reward"] for r in scored] | |
| sources: Dict[str, int] = {} | |
| for r in rows: | |
| sources[r["code_source"]] = sources.get(r["code_source"], 0) + 1 | |
| rule_stats: Dict[str, Dict[str, float]] = {} | |
| if scored: | |
| for key in sorted(scored[0]["rules"]): | |
| vals = [r["rules"][key] for r in scored] | |
| fired = sum(1 for v in vals if v != 0) | |
| rule_stats[key] = { | |
| "mean": round(sum(vals) / len(vals), 4), | |
| "fired_frac": round(fired / len(vals), 3), | |
| } | |
| mean_total = sum(totals) / len(totals) if totals else None | |
| std_total = 0.0 | |
| if len(totals) > 1: | |
| std_total = (sum((x - mean_total) ** 2 for x in totals) / len(totals)) ** 0.5 | |
| summary["models"][model] = { | |
| "n": len(rows), | |
| "n_scored": len(scored), | |
| "code_sources": sources, | |
| "empty_reasons": { | |
| k: sum(1 for r in rows if r.get("empty_reason") == k) | |
| for k in ("no_text", "budget_exhausted_in_thinking") | |
| if any(r.get("empty_reason") == k for r in rows) | |
| }, | |
| "mean_reward": round(mean_total, 4) if mean_total is not None else None, | |
| "std_reward": round(std_total, 4), | |
| "min_reward": round(min(totals), 4) if totals else None, | |
| "max_reward": round(max(totals), 4) if totals else None, | |
| "mean_code_chars": ( | |
| round(sum(r["code_chars"] for r in rows) / len(rows), 1) if rows else 0 | |
| ), | |
| "rules": rule_stats, | |
| } | |
| return summary | |
| def run_experiment( | |
| models: List[str], | |
| output_dir: str = "./traces", | |
| tasks: Optional[List[str]] = None, | |
| n_samples: int = 1, | |
| base_url: str = DEFAULT_BASE_URL, | |
| num_predict: int = DEFAULT_NUM_PREDICT, | |
| temperature: float = 0.8, | |
| seed: Optional[int] = None, | |
| think: Optional[bool] = False, | |
| timeout: float = 600.0, | |
| resume: bool = True, | |
| model_overrides: Optional[Dict[str, Dict[str, Any]]] = None, | |
| rater: str = "static", | |
| reward_cfg: Optional[Any] = None, | |
| ) -> Dict[str, Any]: | |
| """Run trace collection, writing JSONL incrementally and a summary at the end. | |
| Traces are appended one line at a time so a crash keeps prior work; with | |
| ``resume=True`` an interrupted run continues where it left off. | |
| ``model_overrides`` maps a model name to per-model settings (``num_predict``, | |
| ``think``, ``temperature``, ``timeout``). Required in practice: thinking | |
| models need a far larger token budget than non-thinking ones, and forcing | |
| ``think=False`` on a thinking model yields silent empty responses. | |
| """ | |
| model_overrides = model_overrides or {} | |
| require_models(models, base_url) | |
| os.makedirs(output_dir, exist_ok=True) | |
| slug = "_".join(m.replace("/", "-").replace(":", "-") for m in models) | |
| if rater != "static": | |
| slug = f"{slug}_rater-{rater}" | |
| traces_path = os.path.join(output_dir, f"traces_{slug}.jsonl") | |
| summary_path = os.path.join(output_dir, f"summary_{slug}.json") | |
| done = _load_done(traces_path) if resume else set() | |
| if done: | |
| logger.info("Resuming: %d traces already on disk", len(done)) | |
| tasks = tasks if tasks is not None else load_research_tasks() | |
| written = 0 | |
| with open(traces_path, "a", encoding="utf-8") as fh: | |
| for model in models: | |
| for task_id, task in enumerate(tasks): | |
| for sample_index in range(n_samples): | |
| prompt = build_prompt(task) | |
| ov = model_overrides.get(model, {}) | |
| eff_seed = (seed + sample_index) if seed is not None else None | |
| eff_np = ov.get("num_predict", num_predict) | |
| tid = _trace_id(model, task_id, sample_index, eff_seed, eff_np) | |
| if tid in done: | |
| continue | |
| gen = generate( | |
| model=model, | |
| prompt=prompt, | |
| base_url=base_url, | |
| num_predict=ov.get("num_predict", num_predict), | |
| temperature=ov.get("temperature", temperature), | |
| # Vary the seed per sample: a fixed seed makes repeated | |
| # samples byte-identical regardless of temperature, | |
| # which leaves a GRPO group with zero advantage spread. | |
| seed=eff_seed, | |
| think=ov.get("think", think), | |
| timeout=ov.get("timeout", timeout), | |
| ) | |
| trace = make_trace( | |
| model, | |
| task, | |
| task_id, | |
| sample_index, | |
| gen, | |
| seed=eff_seed, | |
| reward_cfg=reward_cfg, | |
| rater=rater, | |
| ) | |
| fh.write(json.dumps(trace) + "\n") | |
| fh.flush() | |
| written += 1 | |
| logger.info( | |
| "%s task=%d sample=%d reward=%s chars=%d %sms", | |
| model, | |
| task_id, | |
| sample_index, | |
| ( | |
| "None" | |
| if trace["total_reward"] is None | |
| else f"{trace['total_reward']:+.3f}" | |
| ), | |
| trace["code_chars"], | |
| trace["total_ms"], | |
| ) | |
| all_traces = [] | |
| with open(traces_path, "r", encoding="utf-8") as fh: | |
| for line in fh: | |
| line = line.strip() | |
| if line: | |
| all_traces.append(json.loads(line)) | |
| summary = summarize(all_traces) | |
| summary["traces_path"] = traces_path | |
| summary["new_traces_this_run"] = written | |
| summary["rater"] = rater | |
| if rater == "decision": | |
| summary["decision_model"] = getattr(reward_cfg, "decision_model", None) | |
| with open(summary_path, "w", encoding="utf-8") as fh: | |
| json.dump(summary, fh, indent=2) | |
| logger.info("Wrote %d new traces to %s", written, traces_path) | |
| logger.info("Summary: %s", summary_path) | |
| return summary | |