Download scripts/run_passk_sampled_autostop.py from Ilikemechuri/rwkv_doomloop_experiment: direct link, hf CLI and curl.
- Browser
- Download file 29.1 kB
-
https://huggingface.co/Ilikemechuri/rwkv_doomloop_experiment/resolve/main/scripts/run_passk_sampled_autostop.py
- Command line
-
hf download hf://Ilikemechuri/rwkv_doomloop_experiment/scripts/run_passk_sampled_autostop.py
-
curl -L -o run_passk_sampled_autostop.py https://huggingface.co/Ilikemechuri/rwkv_doomloop_experiment/resolve/main/scripts/run_passk_sampled_autostop.py
29.1 kB
| #!/usr/bin/env python | |
| """Sample pass@k generations with token-level doom-loop stopping and diagnostics.""" | |
| import argparse | |
| import csv | |
| import json | |
| import math | |
| import re | |
| import time | |
| from datetime import datetime, timezone | |
| from pathlib import Path | |
| import torch | |
| from transformers import ( | |
| AutoModelForCausalLM, | |
| AutoTokenizer, | |
| StoppingCriteria, | |
| StoppingCriteriaList, | |
| ) | |
| ROOT = Path("/workspace/rwkv_doomloop_experiment") | |
| USER_PROMPT = ( | |
| "Find the number of ways to place a digit in each cell of a 2x3 grid so that " | |
| "the sum of the two numbers formed by reading left to right is $999$, and " | |
| "the sum of the three numbers formed by reading top to bottom is $99$. " | |
| "The grid below is an example of such an arrangement because " | |
| "$8+991=999$ and $9+9+81=99$.\n" | |
| r"\[\begin{array}{|c|c|c|} \hline 0 & 0 & 8 \\ \hline " | |
| r"9 & 9 & 1 \\ \hline \end{array}\]" | |
| ) | |
| MAX_NEW_TOKENS = 4096 | |
| TEMPERATURE = 1.0 | |
| TOP_P = 0.95 | |
| BASE_SEED = 260927 | |
| ANSWER = 45 | |
| MODEL_SPECS = [ | |
| { | |
| "key": "rwkv_1_5b", | |
| "kind": "rwkv", | |
| "model_id": "RWKV/RWKV7-G1j-1.5B-20260831", | |
| "revision": "2c18b29ab7fbece25ff6112281eea0fa41fcb30f", | |
| "path": Path( | |
| "/workspace/.hf_home/hub/models--RWKV--RWKV7-G1j-1.5B-20260831" | |
| "/snapshots/2c18b29ab7fbece25ff6112281eea0fa41fcb30f" | |
| ), | |
| "run_dir": "11_rwkv_1_5b_pass10_sampled_autostop", | |
| }, | |
| { | |
| "key": "rwkv_2_9b", | |
| "kind": "rwkv", | |
| "model_id": "RWKV/RWKV7-G1j-2.9B-20260831", | |
| "revision": "c6202c9e1b5de80640fa487b112da621067967ad", | |
| "path": ROOT / "models" / "RWKV7-G1j-2.9B-20260831", | |
| "run_dir": "12_rwkv_2_9b_pass10_sampled_autostop", | |
| }, | |
| { | |
| "key": "olmo2_1b", | |
| "kind": "olmo", | |
| "model_id": "allenai/OLMo-2-0425-1B-Instruct", | |
| "revision": "48d788eca847d4d7548f375ad03d3c9312f6139e", | |
| "path": ROOT / "models" / "OLMo-2-0425-1B-Instruct", | |
| "run_dir": "13_olmo2_1b_pass10_sampled_autostop", | |
| }, | |
| { | |
| "key": "qwen3_5_2b_base", | |
| "kind": "causal", | |
| "model_id": "Qwen/Qwen3.5-2B-Base", | |
| "revision": "b1485b2fa6dfa1287294f269f5fb618e03d52d7c", | |
| "path": ROOT / "models" / "Qwen3.5-2B-Base", | |
| "run_dir": "14_qwen3_5_2b_base_pass10_sampled_autostop", | |
| }, | |
| ] | |
| def logits_metrics(logits): | |
| logits = logits.float() | |
| log_probs = torch.log_softmax(logits, dim=-1) | |
| probs = log_probs.exp() | |
| top = torch.topk(logits, k=2) | |
| finite = torch.isfinite(log_probs) | |
| entropy_terms = torch.where(finite, probs * log_probs, torch.zeros_like(probs)) | |
| return { | |
| "top1_probability": probs[top.indices[0]], | |
| "entropy_nats": -entropy_terms.sum(), | |
| "top1_top2_margin": top.values[0] - top.values[1], | |
| "top1_token_id": top.indices[0], | |
| } | |
| def rolling_dup8_rate(tokens, window=64, n=8): | |
| tail = tokens[-window:] | |
| grams = [tuple(tail[i : i + n]) for i in range(max(0, len(tail) - n + 1))] | |
| if not grams: | |
| return 0.0 | |
| return (len(grams) - len(set(grams))) / len(grams) | |
| class DoomLoopStoppingCriteria(StoppingCriteria): | |
| """Stop on a duplicated 48-token span, a short triple-cycle, or sustained repetition.""" | |
| def __init__(self, prompt_len, prompt_ids, context_budget=None): | |
| self.prompt_len = prompt_len | |
| self.prompt_ngram_sets = { | |
| span: { | |
| tuple(prompt_ids[start : start + span]) | |
| for start in range(max(0, len(prompt_ids) - span + 1)) | |
| } | |
| for span in (96, 64, 48, 32) | |
| } | |
| self.context_budget = context_budget | |
| self.event = None | |
| self.high_dup_checkpoints = 0 | |
| self.last_checked = 0 | |
| self.last_indexed = 0 | |
| self.last_pruned = 0 | |
| self.span_lengths = (96, 64, 48, 32) | |
| self.span_occurrences = {span: {} for span in self.span_lengths} | |
| def _index_new_spans(self, tokens, history=1024): | |
| for end in range(self.last_indexed + 1, len(tokens) + 1): | |
| for span in self.span_lengths: | |
| if end < span: | |
| continue | |
| start = end - span | |
| gram = tuple(tokens[start:end]) | |
| positions = self.span_occurrences[span].setdefault(gram, []) | |
| positions.append(start) | |
| self.last_indexed = len(tokens) | |
| if len(tokens) - self.last_pruned >= 128: | |
| for span in self.span_lengths: | |
| earliest = max(0, len(tokens) - span - history) | |
| entries = self.span_occurrences[span] | |
| for gram, starts in list(entries.items()): | |
| kept = [start for start in starts if start >= earliest] | |
| if kept: | |
| entries[gram] = kept | |
| else: | |
| del entries[gram] | |
| self.last_pruned = len(tokens) | |
| def _exact_suffix_repeat(self, tokens, history=1024): | |
| for span in self.span_lengths: | |
| if len(tokens) < 2 * span: | |
| continue | |
| current_start = len(tokens) - span | |
| suffix = tuple(tokens[current_start:]) | |
| # Repeating text supplied by the user (for example, the example grid) | |
| # is not sufficient evidence of a generated loop. | |
| if suffix in self.prompt_ngram_sets[span]: | |
| continue | |
| starts = self.span_occurrences[span].get(suffix, []) | |
| earliest = max(0, current_start - history) | |
| prior = [] | |
| for start in reversed(starts): | |
| if start >= current_start or start < earliest: | |
| continue | |
| if not prior or prior[-1] - start >= span: | |
| prior.append(start) | |
| required_prior_occurrences = 1 if span >= 64 else 2 | |
| if len(prior) >= required_prior_occurrences: | |
| return { | |
| "detector": "exact_repeated_span", | |
| "repeated_span_tokens": span, | |
| "prior_start_steps": [start + 1 for start in reversed(prior)], | |
| "first_start_step": min(prior) + 1, | |
| "repeat_start_step": current_start + 1, | |
| "prior_occurrences_required": required_prior_occurrences, | |
| } | |
| return None | |
| def _short_cycle(self, tokens): | |
| # Three consecutive copies make short periodic text an unambiguous loop signal. | |
| for period in range(8, 48): | |
| if len(tokens) < 3 * period: | |
| continue | |
| tail = tokens[-3 * period :] | |
| block = tail[:period] | |
| if tail[period : 2 * period] == block and tail[2 * period :] == block: | |
| return {"detector": "three_copy_cycle", "cycle_period_tokens": period} | |
| return None | |
| def __call__(self, input_ids, scores, **kwargs): | |
| tokens = input_ids[0, self.prompt_len :].tolist() | |
| if self.context_budget is not None and len(tokens) >= self.context_budget: | |
| self.event = { | |
| "detector": "model_context_limit", | |
| "context_budget_response_tokens": self.context_budget, | |
| "detected_after_tokens": len(tokens), | |
| } | |
| return torch.tensor([True], dtype=torch.bool, device=input_ids.device) | |
| # Inspect every fourth token; this bounds overhead and detection latency. | |
| if len(tokens) % 4 != 0 or len(tokens) == self.last_checked: | |
| return torch.tensor([False], dtype=torch.bool, device=input_ids.device) | |
| self.last_checked = len(tokens) | |
| self._index_new_spans(tokens) | |
| event = self._exact_suffix_repeat(tokens) | |
| if event is None: | |
| event = self._short_cycle(tokens) | |
| dup8 = rolling_dup8_rate(tokens) | |
| if dup8 >= 0.55: | |
| self.high_dup_checkpoints += 1 | |
| else: | |
| self.high_dup_checkpoints = 0 | |
| if event is None and self.high_dup_checkpoints >= 2: | |
| event = {"detector": "sustained_8gram_repetition", "rolling_dup8_rate_64": dup8} | |
| if event is not None: | |
| event["detected_after_tokens"] = len(tokens) | |
| event["rolling_dup8_rate_64"] = dup8 | |
| self.event = event | |
| return torch.tensor([True], dtype=torch.bool, device=input_ids.device) | |
| return torch.tensor([False], dtype=torch.bool, device=input_ids.device) | |
| def make_state_capture(model): | |
| rows = [] | |
| previous_states = None | |
| def capture(_module, _inputs, output): | |
| nonlocal previous_states | |
| state = getattr(output, "state", None) | |
| if state is None and isinstance(output, (tuple, list)) and len(output) > 1: | |
| state = output[1] | |
| if state is None: | |
| raise RuntimeError("RWKV base-model output did not contain recurrent state") | |
| current = [] | |
| wkv_rms, att_rms, ffn_rms = [], [], [] | |
| wkv_delta_sq, att_delta_sq, ffn_delta_sq = [], [], [] | |
| for layer_idx in range(len(state.layers)): | |
| att, ffn, wkv = (x.detach() for x in state.read(layer_idx)) | |
| layer = (att, ffn, wkv) | |
| current.append(layer) | |
| att_rms.append(att.float().square().mean().sqrt()) | |
| ffn_rms.append(ffn.float().square().mean().sqrt()) | |
| wkv_rms.append(wkv.float().square().mean().sqrt()) | |
| prev = previous_states[layer_idx] if previous_states is not None else tuple( | |
| torch.zeros_like(x) for x in layer | |
| ) | |
| att_delta_sq.append((att.float() - prev[0].float()).square().mean()) | |
| ffn_delta_sq.append((ffn.float() - prev[1].float()).square().mean()) | |
| wkv_delta_sq.append((wkv.float() - prev[2].float()).square().mean()) | |
| def delta_rms(values): | |
| return torch.stack(values).mean().sqrt().item() | |
| row = { | |
| "wkv_rms_mean": torch.stack(wkv_rms).mean().item(), | |
| "wkv_rms_max": torch.stack(wkv_rms).max().item(), | |
| "att_shift_rms_mean": torch.stack(att_rms).mean().item(), | |
| "att_shift_rms_max": torch.stack(att_rms).max().item(), | |
| "ffn_shift_rms_mean": torch.stack(ffn_rms).mean().item(), | |
| "ffn_shift_rms_max": torch.stack(ffn_rms).max().item(), | |
| "wkv_delta_rms": delta_rms(wkv_delta_sq), | |
| "att_shift_delta_rms": delta_rms(att_delta_sq), | |
| "ffn_shift_delta_rms": delta_rms(ffn_delta_sq), | |
| } | |
| rows.append(row) | |
| previous_states = [tuple(value.clone() for value in layer) for layer in current] | |
| return model.rwkv7.register_forward_hook(capture), rows | |
| def write_csv(path, rows): | |
| if not rows: | |
| return | |
| with path.open("w", encoding="utf-8-sig", newline="") as stream: | |
| writer = csv.DictWriter(stream, fieldnames=list(rows[0])) | |
| writer.writeheader() | |
| writer.writerows(rows) | |
| def grade_answer(text): | |
| tail = text[-1500:] | |
| patterns = [ | |
| re.compile( | |
| r"(?:number of ways|ways|arrangements|possibilities|answer|total|count)" | |
| r"[^\n]{0,100}\b45\b", | |
| re.IGNORECASE, | |
| ), | |
| re.compile( | |
| r"\b45\b[^\n]{0,50}(?:ways|arrangements|grids|possibilities)", | |
| re.IGNORECASE, | |
| ), | |
| ] | |
| match = next((pattern.search(tail) for pattern in patterns if pattern.search(tail)), None) | |
| return { | |
| "target_answer": ANSWER, | |
| "automatic_answer_match": match is not None, | |
| "grader": "explicit 45 near a count/ways term in final 1500 characters", | |
| "matched_text": match.group(0) if match else None, | |
| } | |
| def load_model(spec): | |
| if not spec["path"].exists(): | |
| raise FileNotFoundError(f"Model snapshot not present: {spec['path']}") | |
| tokenizer = AutoTokenizer.from_pretrained( | |
| spec["path"], trust_remote_code=(spec["kind"] == "rwkv"), local_files_only=True | |
| ) | |
| model = AutoModelForCausalLM.from_pretrained( | |
| spec["path"], | |
| trust_remote_code=(spec["kind"] == "rwkv"), | |
| dtype=torch.bfloat16, | |
| low_cpu_mem_usage=True, | |
| local_files_only=True, | |
| ).to("cuda") | |
| model.eval() | |
| return model, tokenizer | |
| def run_sample(model, tokenizer, spec, sample_idx, k, resume=True): | |
| out_dir = ROOT / "runs" / spec["run_dir"] / f"sample_{sample_idx:02d}" | |
| out_dir.mkdir(parents=True, exist_ok=True) | |
| summary_path = out_dir / "summary.json" | |
| if resume and summary_path.exists(): | |
| return json.loads(summary_path.read_text(encoding="utf-8")) | |
| seed = BASE_SEED + sample_idx | |
| torch.manual_seed(seed) | |
| torch.cuda.manual_seed_all(seed) | |
| messages = [{"role": "user", "content": USER_PROMPT}] | |
| template_kwargs = { | |
| "tokenize": True, | |
| "add_generation_prompt": True, | |
| "return_dict": True, | |
| "return_tensors": "pt", | |
| } | |
| if spec["kind"] == "rwkv": | |
| template_kwargs["thinking"] = False | |
| encoded = tokenizer.apply_chat_template(messages, **template_kwargs).to("cuda") | |
| prompt_len = encoded["input_ids"].shape[-1] | |
| configured_context = getattr(model.config, "max_position_embeddings", None) | |
| context_budget = ( | |
| max(0, int(configured_context) - prompt_len) | |
| if configured_context is not None | |
| else None | |
| ) | |
| prompt_ids = encoded["input_ids"][0].detach().cpu().tolist() | |
| detector = DoomLoopStoppingCriteria( | |
| prompt_len, prompt_ids, context_budget=context_budget | |
| ) | |
| raw_rows = [] | |
| def capture_raw(_module, _inputs, output): | |
| if isinstance(output, tuple): | |
| output = output[0] | |
| values = logits_metrics(output[0, -1, :].detach()) | |
| raw_rows.append({key: value.item() for key, value in values.items()}) | |
| logit_hook = model.get_output_embeddings().register_forward_hook(capture_raw) | |
| state_hook, state_rows = (make_state_capture(model) if spec["kind"] == "rwkv" else (None, [])) | |
| generation_args = { | |
| **encoded, | |
| "do_sample": True, | |
| "temperature": TEMPERATURE, | |
| "top_p": TOP_P, | |
| "top_k": None, | |
| "num_beams": 1, | |
| "max_new_tokens": MAX_NEW_TOKENS, | |
| "eos_token_id": tokenizer.eos_token_id, | |
| "pad_token_id": tokenizer.pad_token_id or tokenizer.eos_token_id, | |
| "repetition_penalty": 1.0, | |
| "stopping_criteria": StoppingCriteriaList([detector]), | |
| "use_cache": True, | |
| "return_dict_in_generate": True, | |
| "output_scores": True, | |
| } | |
| if spec["kind"] == "rwkv": | |
| generation_args.update({"stop_strings": ["\n\nUser:"], "tokenizer": tokenizer}) | |
| started = time.time() | |
| print( | |
| json.dumps( | |
| { | |
| "event": "sample_started", | |
| "model_key": spec["key"], | |
| "sample": sample_idx, | |
| "k": k, | |
| "seed": seed, | |
| "prompt_tokens": prompt_len, | |
| } | |
| ), | |
| flush=True, | |
| ) | |
| try: | |
| with torch.inference_mode(): | |
| result = model.generate(**generation_args) | |
| finally: | |
| logit_hook.remove() | |
| if state_hook is not None: | |
| state_hook.remove() | |
| generated_ids = result.sequences[0, prompt_len:].detach().cpu().tolist() | |
| generated_text = tokenizer.decode( | |
| generated_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False | |
| ) | |
| stop_string_hit = "\n\nUser:" in generated_text | |
| if stop_string_hit: | |
| generated_text = generated_text.split("\n\nUser:", 1)[0] | |
| if len(raw_rows) != len(generated_ids) or len(result.scores) != len(generated_ids): | |
| raise RuntimeError( | |
| f"step mismatch for {spec['key']} sample {sample_idx}: ids={len(generated_ids)}, " | |
| f"raw={len(raw_rows)}, processed={len(result.scores)}" | |
| ) | |
| if spec["kind"] == "rwkv" and len(state_rows) != len(generated_ids): | |
| raise RuntimeError( | |
| f"state mismatch for {spec['key']} sample {sample_idx}: " | |
| f"ids={len(generated_ids)}, state={len(state_rows)}" | |
| ) | |
| token_rows = [] | |
| for step, (token_id, raw, score) in enumerate( | |
| zip(generated_ids, raw_rows, result.scores), start=1 | |
| ): | |
| processed = logits_metrics(score[0].detach()) | |
| row = { | |
| "predicts_response_token_step": step, | |
| "context_generated_tokens": step - 1, | |
| "generated_token_id": token_id, | |
| "generated_piece": tokenizer.convert_ids_to_tokens(token_id), | |
| "raw_top1_probability": raw["top1_probability"], | |
| "raw_entropy_nats": raw["entropy_nats"], | |
| "raw_top1_top2_margin": raw["top1_top2_margin"], | |
| "raw_top1_token_id": raw["top1_token_id"], | |
| "sampled_top1_probability": processed["top1_probability"].item(), | |
| "sampled_entropy_nats": processed["entropy_nats"].item(), | |
| "sampled_top1_top2_margin": processed["top1_top2_margin"].item(), | |
| "sampled_argmax_token_id": processed["top1_token_id"].item(), | |
| "sampled_argmax_matches_generated": int( | |
| processed["top1_token_id"].item() == token_id | |
| ), | |
| "rolling_dup8_rate_64": rolling_dup8_rate(generated_ids[:step]), | |
| } | |
| if spec["kind"] == "rwkv": | |
| row.update(state_rows[step - 1]) | |
| token_rows.append(row) | |
| eos_hit = bool(generated_ids and generated_ids[-1] == tokenizer.eos_token_id) | |
| if detector.event is not None: | |
| terminal_reason = ( | |
| "context_window_limit" | |
| if detector.event["detector"] == "model_context_limit" | |
| else "doom_loop_detected" | |
| ) | |
| elif eos_hit: | |
| terminal_reason = "eos" | |
| elif stop_string_hit: | |
| terminal_reason = "rwkv_stop_string" | |
| elif len(generated_ids) >= MAX_NEW_TOKENS: | |
| terminal_reason = "max_new_tokens_reached" | |
| else: | |
| terminal_reason = "other_stopping_criterion" | |
| grade = grade_answer(generated_text) | |
| raw_top = [row["raw_top1_probability"] for row in token_rows] | |
| raw_entropy = [row["raw_entropy_nats"] for row in token_rows] | |
| summary = { | |
| "model_key": spec["key"], | |
| "model_id": spec["model_id"], | |
| "model_revision": spec["revision"], | |
| "sample_index": sample_idx, | |
| "requested_k": k, | |
| "seed": seed, | |
| "do_sample": True, | |
| "temperature": TEMPERATURE, | |
| "top_p": TOP_P, | |
| "top_k": None, | |
| "repetition_penalty": 1.0, | |
| "system_message": None, | |
| "user_prompt": USER_PROMPT, | |
| "thinking": False if spec["kind"] == "rwkv" else None, | |
| "prompt_tokens": prompt_len, | |
| "requested_max_new_tokens": MAX_NEW_TOKENS, | |
| "generated_tokens": len(generated_ids), | |
| "terminal_reason": terminal_reason, | |
| "doom_loop_event": detector.event, | |
| "eos_emitted": eos_hit, | |
| "stop_string_emitted": stop_string_hit, | |
| "automatic_answer_match": grade["automatic_answer_match"], | |
| "answer_grader": grade, | |
| "rolling_dup8_mean": sum(row["rolling_dup8_rate_64"] for row in token_rows) | |
| / max(1, len(token_rows)), | |
| "rolling_dup8_max": max( | |
| (row["rolling_dup8_rate_64"] for row in token_rows), default=0.0 | |
| ), | |
| "mean_raw_top1_probability": sum(raw_top) / max(1, len(raw_top)), | |
| "mean_raw_entropy_nats": sum(raw_entropy) / max(1, len(raw_entropy)), | |
| "final_raw_top1_probability": raw_top[-1] if raw_top else None, | |
| "final_raw_entropy_nats": raw_entropy[-1] if raw_entropy else None, | |
| "elapsed_seconds": time.time() - started, | |
| "generated_at_utc": datetime.now(timezone.utc).isoformat(), | |
| } | |
| if spec["kind"] == "rwkv" and token_rows: | |
| summary.update( | |
| { | |
| "mean_wkv_rms": sum(row["wkv_rms_mean"] for row in token_rows) | |
| / len(token_rows), | |
| "final_wkv_rms": token_rows[-1]["wkv_rms_mean"], | |
| "mean_attention_shift_rms": sum( | |
| row["att_shift_rms_mean"] for row in token_rows | |
| ) | |
| / len(token_rows), | |
| "mean_ffn_shift_rms": sum(row["ffn_shift_rms_mean"] for row in token_rows) | |
| / len(token_rows), | |
| } | |
| ) | |
| (out_dir / "generation.txt").write_text(generated_text, encoding="utf-8") | |
| (out_dir / "messages.json").write_text( | |
| json.dumps(messages, ensure_ascii=False, indent=2) + "\n", encoding="utf-8" | |
| ) | |
| (out_dir / "summary.json").write_text( | |
| json.dumps(summary, ensure_ascii=False, indent=2) + "\n", encoding="utf-8" | |
| ) | |
| (out_dir / "run_config.json").write_text( | |
| json.dumps( | |
| { | |
| **summary, | |
| "chat_template": tokenizer.chat_template, | |
| "doom_loop_policy": { | |
| "check_frequency_tokens": 4, | |
| "exact_repeat": "non-overlapping suffix 96 or 64 tokens repeated once, or 48 or 32 tokens repeated twice (three occurrences total), within previous 1024 generated tokens; spans also present in the user prompt are excluded", | |
| "short_cycle": "three consecutive identical copies of a cycle with period 8-47 tokens", | |
| "rolling_repetition": "rolling duplicate 8-gram rate >= 0.55 at two checked checkpoints", | |
| "context_window": "stop before exceeding model.config.max_position_embeddings when present", | |
| }, | |
| "rwkv_state_capture": "RWKV base-model forward hook reads WKV, attention-shift, and FFN-shift state after each decode forward", | |
| "raw_logit_capture": "lm_head forward hook before sampling temperature/top-p", | |
| }, | |
| ensure_ascii=False, | |
| indent=2, | |
| ) | |
| + "\n", | |
| encoding="utf-8", | |
| ) | |
| write_csv(out_dir / "token_metrics.csv", token_rows) | |
| print( | |
| json.dumps( | |
| { | |
| "event": "sample_finished", | |
| "model_key": spec["key"], | |
| "sample": sample_idx, | |
| "generated_tokens": len(generated_ids), | |
| "terminal_reason": terminal_reason, | |
| "doom_loop_event": detector.event, | |
| "automatic_answer_match": grade["automatic_answer_match"], | |
| "elapsed_seconds": summary["elapsed_seconds"], | |
| }, | |
| ensure_ascii=False, | |
| ), | |
| flush=True, | |
| ) | |
| del result, encoded, token_rows | |
| torch.cuda.empty_cache() | |
| return summary | |
| def pass_at_k(n, correct, k): | |
| if n < k: | |
| return None | |
| if n - correct < k: | |
| return 1.0 | |
| fail_probability = 1.0 | |
| for index in range(k): | |
| fail_probability *= (n - correct - index) / (n - index) | |
| return 1.0 - fail_probability | |
| def aggregate_model(spec, k): | |
| base = ROOT / "runs" / spec["run_dir"] | |
| summaries = [] | |
| for sample_idx in range(1, k + 1): | |
| path = base / f"sample_{sample_idx:02d}" / "summary.json" | |
| if path.exists(): | |
| summaries.append(json.loads(path.read_text(encoding="utf-8"))) | |
| count = len(summaries) | |
| correct = sum(bool(row["automatic_answer_match"]) for row in summaries) | |
| return { | |
| "model_key": spec["key"], | |
| "model_id": spec["model_id"], | |
| "model_revision": spec["revision"], | |
| "requested_k": k, | |
| "completed_samples": count, | |
| "correct_samples": correct, | |
| "pass_at_1_empirical": correct / count if count else None, | |
| "pass_at_k_estimate": pass_at_k(count, correct, k), | |
| "doom_loop_samples": sum( | |
| row["terminal_reason"] == "doom_loop_detected" for row in summaries | |
| ), | |
| "eos_samples": sum(row["terminal_reason"] == "eos" for row in summaries), | |
| "max_token_cap_samples": sum( | |
| row["terminal_reason"] == "max_new_tokens_reached" for row in summaries | |
| ), | |
| "mean_generated_tokens": ( | |
| sum(row["generated_tokens"] for row in summaries) / count if count else None | |
| ), | |
| "mean_raw_entropy_nats": ( | |
| sum(row["mean_raw_entropy_nats"] for row in summaries) / count if count else None | |
| ), | |
| "mean_wkv_rms": ( | |
| sum(row["mean_wkv_rms"] for row in summaries if "mean_wkv_rms" in row) | |
| / max(1, sum("mean_wkv_rms" in row for row in summaries)) | |
| if spec["kind"] == "rwkv" | |
| else None | |
| ), | |
| "samples": summaries, | |
| } | |
| def main(): | |
| parser = argparse.ArgumentParser() | |
| parser.add_argument("--k", type=int, default=10) | |
| parser.add_argument("--model", choices=[spec["key"] for spec in MODEL_SPECS]) | |
| parser.add_argument("--no-resume", action="store_true") | |
| args = parser.parse_args() | |
| if args.k <= 0: | |
| raise ValueError("k must be a positive integer") | |
| if not torch.cuda.is_available(): | |
| raise RuntimeError("CUDA is required for this experiment") | |
| specs = [spec for spec in MODEL_SPECS if args.model is None or spec["key"] == args.model] | |
| for spec in specs: | |
| base = ROOT / "runs" / spec["run_dir"] | |
| if not args.no_resume and all( | |
| (base / f"sample_{sample_idx:02d}" / "summary.json").exists() | |
| for sample_idx in range(1, args.k + 1) | |
| ): | |
| aggregate = aggregate_model(spec, args.k) | |
| base.mkdir(parents=True, exist_ok=True) | |
| (base / "passk_summary.json").write_text( | |
| json.dumps(aggregate, ensure_ascii=False, indent=2) + "\n", encoding="utf-8" | |
| ) | |
| continue | |
| print( | |
| json.dumps( | |
| { | |
| "event": "model_loading", | |
| "model_key": spec["key"], | |
| "model_id": spec["model_id"], | |
| "revision": spec["revision"], | |
| "k": args.k, | |
| } | |
| ), | |
| flush=True, | |
| ) | |
| model, tokenizer = load_model(spec) | |
| for sample_idx in range(1, args.k + 1): | |
| run_sample(model, tokenizer, spec, sample_idx, args.k, resume=not args.no_resume) | |
| del model, tokenizer | |
| torch.cuda.empty_cache() | |
| torch.cuda.synchronize() | |
| aggregate = aggregate_model(spec, args.k) | |
| base.mkdir(parents=True, exist_ok=True) | |
| (base / "passk_summary.json").write_text( | |
| json.dumps(aggregate, ensure_ascii=False, indent=2) + "\n", encoding="utf-8" | |
| ) | |
| print( | |
| json.dumps( | |
| { | |
| "event": "model_finished", | |
| "model_key": spec["key"], | |
| "completed_samples": aggregate["completed_samples"], | |
| "correct_samples": aggregate["correct_samples"], | |
| "pass_at_k_estimate": aggregate["pass_at_k_estimate"], | |
| "doom_loop_samples": aggregate["doom_loop_samples"], | |
| } | |
| ), | |
| flush=True, | |
| ) | |
| aggregates = [aggregate_model(spec, args.k) for spec in specs] | |
| root_dir = ROOT / "runs" / f"passk_{args.k}_sampled_autostop" | |
| root_dir.mkdir(parents=True, exist_ok=True) | |
| payload = { | |
| "experiment": "sampled pass@k for the 2x3 digit grid count problem", | |
| "k": args.k, | |
| "correct_answer": ANSWER, | |
| "answer_grader": "explicit 45 near a count/ways term in final 1500 characters", | |
| "manual_answer_audit": "See manual_answer_audit.md. The automatic string matcher is not a complete semantic correctness grader.", | |
| "sampling": { | |
| "do_sample": True, | |
| "temperature": TEMPERATURE, | |
| "top_p": TOP_P, | |
| "top_k": None, | |
| }, | |
| "max_new_tokens_per_sample": MAX_NEW_TOKENS, | |
| "system_message": None, | |
| "prompt": USER_PROMPT, | |
| "models": aggregates, | |
| } | |
| (root_dir / "passk_summary.json").write_text( | |
| json.dumps(payload, ensure_ascii=False, indent=2) + "\n", encoding="utf-8" | |
| ) | |
| rows = [{key: value for key, value in row.items() if key != "samples"} for row in aggregates] | |
| write_csv(root_dir / "passk_summary.csv", rows) | |
| sample_rows = [] | |
| for model in aggregates: | |
| for sample in model["samples"]: | |
| sample_rows.append( | |
| { | |
| "model_key": model["model_key"], | |
| "model_id": model["model_id"], | |
| "sample_index": sample["sample_index"], | |
| "seed": sample["seed"], | |
| "automatic_answer_match": sample["automatic_answer_match"], | |
| "generated_tokens": sample["generated_tokens"], | |
| "terminal_reason": sample["terminal_reason"], | |
| "doom_loop_event": json.dumps(sample["doom_loop_event"], ensure_ascii=False) | |
| if sample["doom_loop_event"] | |
| else "", | |
| "mean_raw_top1_probability": sample["mean_raw_top1_probability"], | |
| "mean_raw_entropy_nats": sample["mean_raw_entropy_nats"], | |
| "mean_wkv_rms": sample.get("mean_wkv_rms"), | |
| "elapsed_seconds": sample["elapsed_seconds"], | |
| } | |
| ) | |
| write_csv(root_dir / "sample_results.csv", sample_rows) | |
| if __name__ == "__main__": | |
| main() | |