Download faisi/W4-01-external-baselines/src/baselines/playbook_evolution.py from ppJustin/micro: direct link, hf CLI and curl.
- Browser
- Download file 14.3 kB
-
https://huggingface.co/datasets/ppJustin/micro/resolve/main/faisi/W4-01-external-baselines/src/baselines/playbook_evolution.py
- Command line
-
hf download hf://datasets/ppJustin/micro/faisi/W4-01-external-baselines/src/baselines/playbook_evolution.py
-
curl -L -o playbook_evolution.py https://huggingface.co/datasets/ppJustin/micro/resolve/main/faisi/W4-01-external-baselines/src/baselines/playbook_evolution.py
14.3 kB
| """Two frozen prompt-selection rounds and a train-dev-only mid-run refresh.""" | |
| import argparse | |
| import asyncio | |
| from concurrent.futures import ThreadPoolExecutor | |
| import hashlib | |
| import json | |
| from pathlib import Path | |
| import random | |
| import re | |
| import subprocess | |
| import time | |
| import httpx | |
| SCHEMA = { | |
| "type": "object", | |
| "properties": {"text": {"type": "string"}}, | |
| "required": ["text"], | |
| "additionalProperties": False, | |
| } | |
| CATEGORY = re.compile( | |
| r"(?i)(?:\b(?:case[-_][0-9a-f]{8,}|(?:SVC|INST|HOST)_\d+|EVID_[A-Z0-9]+|" | |
| r"openrca|trainticket|propagation_bench)\b|https?://|\b\d{1,3}(?:\.\d{1,3}){3}\b)" | |
| ) | |
| COMMON_NOUNS = {"service", "host", "node", "instance"} | |
| SYSTEM = """Write ONLY a general-purpose operational playbook for a diagnosis agent using anonymous tools. | |
| Return JSON with one text field. Aim for 180 to 300 tokens; 400 is the hard limit. | |
| Use only generic words for entities such as service, instance, and host. Never name real or anonymous | |
| components, datasets, software products, cases, infrastructure addresses, or trace evidence IDs. | |
| The observations below are examples from training cases. Extract general evidence-gathering | |
| strategies and do not imitate identities, precise measurements, or example outcomes. | |
| Use the six public tool names when useful. The call graph is not the fault propagation direction. | |
| The agent has at most 20 normal turns; include a defensible way to finish with a rooted acyclic chain. | |
| Prefer concrete decision rules about metrics, onset order, caller/callee evidence and rival explanations. | |
| Keep the baseline tool and submission protocol intact. Never claim to know the hidden diagnosis. | |
| """ | |
| ANGLES = ( | |
| "Prioritize detecting when the most severe alert is a downstream symptom.", | |
| "Prioritize confirming earliest observed anomalies while accounting for noisy onset signals.", | |
| "Prioritize cross-service edge evidence and latency attribution.", | |
| "Prioritize inspecting a small set of competing cause hypotheses efficiently.", | |
| "Prioritize distinguishing host, instance, and service effects through ownership and topology.", | |
| "Prioritize integrating metrics and event evidence with a short defensible propagation chain.", | |
| ) | |
| def assemble(spec, index, attempt): | |
| rng = random.Random(42 + 1000 * spec["round"] + 17 * index + attempt) | |
| sample = rng.sample(spec["examples"], min(2, len(spec["examples"]))) | |
| paragraphs = [ANGLES[index]] | |
| if spec["incumbent"]: | |
| paragraphs.extend( | |
| ( | |
| "Revise this current playbook using the evidence below.", | |
| spec["incumbent"], | |
| ) | |
| ) | |
| if attempt: | |
| paragraphs.append( | |
| "Use plain generic nouns and short sentences. Remove all names or identifier-like examples." | |
| ) | |
| paragraphs.append(json.dumps(sample, separators=(",", ":"))) | |
| return "\n".join(paragraphs) | |
| async def generate(model_name, round_dir, attempt, indexes): | |
| if any( | |
| Path(p).exists() | |
| for p in ( | |
| "/data/snapshots", | |
| "/data/vault", | |
| "/data/train_roots.json", | |
| "/verified", | |
| ) | |
| ): | |
| raise ValueError("unexpected_synthesis_mounts") | |
| spec = json.loads(Path("/state/data/evolution.json").read_bytes()) | |
| transport = httpx.AsyncHTTPTransport(uds="/model_server.sock") | |
| async with httpx.AsyncClient( | |
| transport=transport, base_url="http://local", timeout=180 | |
| ) as client: | |
| async def one(index): | |
| payload = { | |
| "model": model_name, | |
| "messages": [ | |
| {"role": "system", "content": SYSTEM}, | |
| {"role": "user", "content": assemble(spec, index, attempt)}, | |
| ], | |
| "temperature": 0.7, | |
| "top_p": 0.95, | |
| "top_k": 20, | |
| "repetition_penalty": 1.05, | |
| "max_tokens": 640, | |
| "seed": 42000 + 100 * spec["round"] + 10 * attempt + index, | |
| "response_format": { | |
| "type": "json_schema", | |
| "json_schema": { | |
| "name": "playbook", | |
| "strict": True, | |
| "schema": SCHEMA, | |
| }, | |
| }, | |
| } | |
| response = ( | |
| (await client.post("/v1/chat/completions", json=payload)) | |
| .raise_for_status() | |
| .json() | |
| ) | |
| choice = response["choices"][0] | |
| text = None | |
| if choice["finish_reason"] == "stop": | |
| try: | |
| text = json.loads(choice["message"]["content"])["text"] | |
| except (json.JSONDecodeError, KeyError, TypeError): | |
| pass | |
| (round_dir / f"draft-{index}.json").write_text( | |
| json.dumps( | |
| { | |
| "text": text, | |
| "finish": choice["finish_reason"], | |
| "seed": payload["seed"], | |
| } | |
| ) | |
| + "\n" | |
| ) | |
| await asyncio.gather(*(one(i) for i in indexes)) | |
| def check_text(text, names, tokenizers): | |
| if not isinstance(text, str) or not text.strip() or CATEGORY.search(text): | |
| return None | |
| if any(not ch.isprintable() and ch not in "\n\t" for ch in text): | |
| return None | |
| normalized = text.casefold() | |
| # Require token boundaries so a known short entity does not match a longer word. | |
| def found(name): | |
| return name in normalized and re.search( | |
| r"(?<![\w/-])" + re.escape(name) + r"(?![\w/-])", normalized | |
| ) | |
| if any(found(name) for name in names if name not in COMMON_NOUNS): | |
| return None | |
| counts = [len(t.encode(text, add_special_tokens=False).ids) for t in tokenizers] | |
| return max(counts) if 1 <= max(counts) <= 400 else None | |
| def score_dev(stage, expected): | |
| rows = [ | |
| json.loads(l) | |
| for l in (stage / "trainhome/episodes.jsonl").read_bytes().splitlines() | |
| ] | |
| inventory = {(r["dataset"], r["case_id"]) for r in rows} | |
| if ( | |
| inventory != expected | |
| or len(rows) != len(expected) | |
| or any(r["phase"] != "train" or r["seed"] != 42 for r in rows) | |
| ): | |
| raise ValueError("wrong_dev_cohort") | |
| return sum(r["root_hit"] for r in rows), rows | |
| def refresh_examples(rows): | |
| from baselines.prepare import compact | |
| from checkers.context_api import TrajectoryContext | |
| bad = [r for r in rows if r["root_hit"] is False] | |
| good = [r for r in rows if r["root_hit"] is True] | |
| rng = random.Random(42) | |
| rng.shuffle(bad) | |
| rng.shuffle(good) | |
| if not bad: | |
| return [{"hit": compact(TrajectoryContext.from_trace(r))} for r in good[:12]] | |
| return [ | |
| { | |
| "miss": compact(TrajectoryContext.from_trace(row)), | |
| **( | |
| {"hit": compact(TrajectoryContext.from_trace(good[i % len(good)]))} | |
| if good | |
| else {} | |
| ), | |
| } | |
| for i, row in enumerate(bad[:24]) | |
| ] | |
| def optimize( | |
| base, module, models_root, scorer_model, scorer_socket, coder_socket, phase | |
| ): | |
| from tokenizers import Tokenizer | |
| base = base.resolve(strict=True) | |
| expected = { | |
| tuple(case) | |
| for case in json.loads((base / "views/dev/allowlists.json").read_bytes())[ | |
| "train" | |
| ] | |
| } | |
| private = base / "private" | |
| tokenizer = [ | |
| Tokenizer.from_file( | |
| str(models_root / f"Qwen2.5-{size}-Instruct" / "tokenizer.json") | |
| ) | |
| for size in ("7B", "14B") | |
| ] | |
| names = json.loads((private / "disallowed_entity_names.json").read_bytes()) | |
| rounds = base / "prompt_rounds" | |
| rounds.mkdir(exist_ok=True) | |
| results = [] | |
| winner_text = "" | |
| incumbent_hits = -1 | |
| def evaluate(path, text): | |
| path.mkdir(parents=True, exist_ok=True) | |
| data = path / "data" | |
| data.mkdir(exist_ok=True) | |
| (data / "playbook.txt").write_text(text + "\n") | |
| log = path / "launcher.log" | |
| with log.open("w") as stream: | |
| subprocess.run( | |
| [ | |
| "bash", | |
| str(module / "run_baseline.sh"), | |
| str(base), | |
| str(path), | |
| str(scorer_model), | |
| "dev", | |
| str(scorer_socket), | |
| "26" if phase == "refresh" else "0", | |
| "--concurrency", | |
| "48", | |
| ], | |
| stdout=stream, | |
| stderr=subprocess.STDOUT, | |
| check=True, | |
| ) | |
| return score_dev(path, expected) | |
| if phase == "refresh": | |
| winner_text = (private / "playbook_p1.txt").read_text().strip() | |
| incumbent_hits, rows = evaluate(rounds / "refresh" / "incumbent", winner_text) | |
| samples = refresh_examples(rows) | |
| n_rounds = (3,) | |
| else: | |
| samples = json.loads((private / "induction.json").read_bytes()) | |
| n_rounds = (1, 2) | |
| for index in n_rounds: | |
| stage = rounds / f"round{index}" | |
| stage.mkdir(exist_ok=True) | |
| (stage / "data").mkdir(exist_ok=True) | |
| (stage / "trainhome").mkdir(exist_ok=True) | |
| previous = incumbent_hits | |
| spec = {"round": index, "examples": samples, "incumbent": winner_text} | |
| (stage / "data/evolution.json").write_text( | |
| json.dumps(spec, separators=(",", ":")) | |
| ) | |
| accepted = {} | |
| started = time.monotonic() | |
| for attempt in range(8): | |
| missing = [n for n in range(6) if n not in accepted] | |
| if not missing: | |
| break | |
| with (stage / "generation.log").open("a") as stream: | |
| subprocess.run( | |
| [ | |
| "bash", | |
| str(module / "generate_playbook.sh"), | |
| str(stage), | |
| str(coder_socket), | |
| str(attempt), | |
| *map(str, missing), | |
| ], | |
| stdout=stream, | |
| stderr=subprocess.STDOUT, | |
| check=True, | |
| ) | |
| for n in missing: | |
| draft = json.loads((stage / f"trainhome/draft-{n}.json").read_bytes()) | |
| text = draft["text"] | |
| if not isinstance(text, str): | |
| continue | |
| text = text.strip() | |
| count = check_text(text, names, tokenizer) | |
| if count is not None and text not in { | |
| entry["text"] for entry in accepted.values() | |
| }: | |
| accepted[n] = { | |
| "text": text, | |
| "tokens": count, | |
| "seed": draft["seed"], | |
| "retry": attempt, | |
| } | |
| print( | |
| json.dumps( | |
| {"round": index, "validated_candidate_slots": len(accepted)} | |
| ), | |
| flush=True, | |
| ) | |
| if len(accepted) != 6: | |
| raise ValueError("incomplete_sanitized_playbook_round") | |
| def evaluate_candidate(key): | |
| draft = accepted[key] | |
| hits, rows = evaluate(stage / f"candidate-{key}", draft["text"]) | |
| return { | |
| "slot": key, | |
| "tokens": draft["tokens"], | |
| "seed": draft["seed"], | |
| "retry": draft["retry"], | |
| "dev_hits": hits, | |
| "invalid_count": sum(r["submission"] is None for r in rows), | |
| "sha256": hashlib.sha256((draft["text"] + "\n").encode()).hexdigest(), | |
| } | |
| with ThreadPoolExecutor(max_workers=2) as pool: | |
| stats = list(pool.map(evaluate_candidate, sorted(accepted))) | |
| best = max(stats, key=lambda r: (r["dev_hits"], -r["slot"])) | |
| selected = None | |
| if best["dev_hits"] > incumbent_hits: | |
| selected = best["slot"] | |
| incumbent_hits = best["dev_hits"] | |
| winner_text = accepted[selected]["text"] | |
| results.append( | |
| { | |
| "round": index, | |
| "dev_cases": 124, | |
| "incumbent_dev_hits": None if previous < 0 else previous, | |
| "candidates": stats, | |
| "winning_candidate_slot": selected, | |
| "selected_dev_hits": incumbent_hits, | |
| "elapsed_s": time.monotonic() - started, | |
| } | |
| ) | |
| print(json.dumps(results[-1]), flush=True) | |
| output = "p2" if phase == "refresh" else "p1" | |
| (private / f"playbook_{output}.txt").write_text(winner_text + "\n") | |
| (base / f"{output}_selection.json").write_text( | |
| json.dumps( | |
| { | |
| "rounds": results, | |
| "token_count": check_text(winner_text, names, tokenizer), | |
| "dev_hits": incumbent_hits, | |
| "evolution_test_payloads_read": 0, | |
| "evolution_ground_truth_vault_reads": 0, | |
| "scope": "post_step26_dev_errors" | |
| if phase == "refresh" | |
| else "497 historical induction cases", | |
| }, | |
| indent=2, | |
| allow_nan=False, | |
| ) | |
| + "\n" | |
| ) | |
| if __name__ == "__main__": | |
| p = argparse.ArgumentParser(description=__doc__) | |
| sub = p.add_subparsers(dest="command", required=True) | |
| g = sub.add_parser("generate") | |
| g.add_argument("model_name") | |
| g.add_argument("attempt", type=int) | |
| g.add_argument("indexes", type=int, nargs="+") | |
| o = sub.add_parser("optimize") | |
| for name in ( | |
| "base", | |
| "module", | |
| "models-root", | |
| "scorer-model", | |
| "scorer-socket", | |
| "coder-socket", | |
| ): | |
| o.add_argument("--" + name, type=Path, required=True) | |
| o.add_argument("--phase", choices=("frozen", "refresh"), required=True) | |
| a = p.parse_args() | |
| if a.command == "generate": | |
| asyncio.run(generate(a.model_name, Path("/state/train"), a.attempt, a.indexes)) | |
| else: | |
| optimize( | |
| a.base, | |
| a.module.resolve(), | |
| a.models_root, | |
| a.scorer_model, | |
| a.scorer_socket, | |
| a.coder_socket, | |
| a.phase, | |
| ) | |