Download code/src/analyze_001b_response_diagnostics.py from PratikBuilds/modelclinic-experiment-001: direct link, hf CLI and curl.
- Browser
- Download file 11 kB
-
https://huggingface.co/datasets/PratikBuilds/modelclinic-experiment-001/resolve/main/code/src/analyze_001b_response_diagnostics.py
- Command line
-
hf download hf://datasets/PratikBuilds/modelclinic-experiment-001/code/src/analyze_001b_response_diagnostics.py
-
curl -L -o analyze_001b_response_diagnostics.py https://huggingface.co/datasets/PratikBuilds/modelclinic-experiment-001/resolve/main/code/src/analyze_001b_response_diagnostics.py
11 kB
| """Summarize lengths, stopping, and an exploratory 8-gram proxy for 001B. | |
| The repetition proxy uses the complete generated token-ID sequence in each | |
| record. At positions 255, 511, 767, ... it computes the duplicate fraction of | |
| 8-grams in the trailing 512 tokens, then reports the maximum sampled value for | |
| that response. This matches ``direction_discovery.repeated_ngram_fraction`` | |
| and is descriptive only; it is not a validated loop or productivity label. | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import csv | |
| import json | |
| import statistics | |
| from collections import Counter, defaultdict | |
| from pathlib import Path | |
| from typing import Any | |
| CONDITIONS = ( | |
| "base", | |
| "edited", | |
| "published_constant", | |
| "independent_constant", | |
| "norm_matched_random", | |
| "rank1_activation_dependent", | |
| ) | |
| HELDOUT_ROWS = (2, 167, 180, 184, 187, 204, 236, 374, 419, 495) | |
| def duplicate_fraction(token_ids: list[int], *, ngram: int = 8) -> float: | |
| grams = [tuple(token_ids[i : i + ngram]) for i in range(max(0, len(token_ids) - ngram + 1))] | |
| return 1.0 - len(set(grams)) / len(grams) if grams else 0.0 | |
| def response_metrics(record: dict[str, Any]) -> dict[str, Any]: | |
| token_ids = [int(token_id) for token_id in record["generated_token_ids"]] | |
| if len(token_ids) != int(record["tokens"]): | |
| raise ValueError( | |
| f"source row {record.get('source_row')}: tokens disagrees with generated_token_ids length" | |
| ) | |
| if not isinstance(record.get("response"), str): | |
| raise ValueError(f"source row {record.get('source_row')}: missing full decoded response") | |
| windows = [] | |
| for position in range(255, len(token_ids), 256): | |
| left = max(0, position - 512 + 1) | |
| windows.append(duplicate_fraction(token_ids[left : position + 1])) | |
| full_grams = [ | |
| tuple(token_ids[i : i + 8]) | |
| for i in range(max(0, len(token_ids) - 8 + 1)) | |
| ] | |
| return { | |
| "full_response_duplicate_8gram_fraction": duplicate_fraction(token_ids), | |
| "max_sampled_trailing512_duplicate_8gram_fraction": max(windows, default=0.0), | |
| "max_full_response_8gram_frequency": max(Counter(full_grams).values(), default=0), | |
| "n_sampled_trailing_windows": len(windows), | |
| } | |
| def read_records(root: Path) -> list[dict[str, Any]]: | |
| records = [] | |
| for condition in CONDITIONS: | |
| for seed in (0, 1): | |
| directory = root / condition / f"seed{seed}" / "records" | |
| paths = sorted(directory.glob("*.json")) | |
| if len(paths) != 10: | |
| raise ValueError(f"expected 10 records in {directory}; found {len(paths)}") | |
| for path in paths: | |
| record = json.loads(path.read_text(encoding="utf-8")) | |
| if record.get("condition") != condition or int(record.get("seed", -1)) != seed: | |
| raise ValueError(f"record metadata disagrees with path: {path}") | |
| if record.get("status") != "complete" or record.get("error") is not None: | |
| raise ValueError(f"record is incomplete or errored: {path}") | |
| record["_path"] = str(path) | |
| record.update(response_metrics(record)) | |
| records.append(record) | |
| expected = { | |
| (condition, source_row, seed) | |
| for condition in CONDITIONS | |
| for source_row in HELDOUT_ROWS | |
| for seed in (0, 1) | |
| } | |
| keys = { | |
| (record["condition"], int(record["source_row"]), int(record["seed"])) | |
| for record in records | |
| } | |
| if len(records) != 120 or keys != expected: | |
| missing = sorted(expected - keys) | |
| unexpected = sorted(keys - expected) | |
| raise ValueError( | |
| f"held-out key mismatch: {len(records)} records, " | |
| f"{len(missing)} missing and {len(unexpected)} unexpected keys" | |
| ) | |
| return records | |
| def write_csv(path: Path, rows: list[dict[str, Any]]) -> None: | |
| if not rows: | |
| raise ValueError(f"cannot write empty diagnostics: {path}") | |
| with path.open("w", newline="", encoding="utf-8") as handle: | |
| writer = csv.DictWriter(handle, fieldnames=list(rows[0])) | |
| writer.writeheader() | |
| writer.writerows(rows) | |
| def summarize(records: list[dict[str, Any]]) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]: | |
| by_condition: dict[str, list[dict[str, Any]]] = defaultdict(list) | |
| by_question: dict[int, dict[str, dict[int, dict[str, Any]]]] = defaultdict( | |
| lambda: defaultdict(dict) | |
| ) | |
| for record in records: | |
| by_condition[record["condition"]].append(record) | |
| by_question[int(record["source_row"])][record["condition"]][int(record["seed"])] = record | |
| condition_rows = [] | |
| for condition in CONDITIONS: | |
| group = by_condition[condition] | |
| lengths = [int(record["tokens"]) for record in group] | |
| statuses = Counter(record["score"].get("status", "missing") for record in group) | |
| finishes = Counter(record.get("finish_reason", "missing") for record in group) | |
| max_repetition = [ | |
| float(record["max_sampled_trailing512_duplicate_8gram_fraction"]) | |
| for record in group | |
| ] | |
| full_repetition = [ | |
| float(record["full_response_duplicate_8gram_fraction"]) for record in group | |
| ] | |
| condition_rows.append( | |
| { | |
| "condition": condition, | |
| "n": len(group), | |
| "correct": statuses["correct"], | |
| "incorrect": statuses["incorrect"], | |
| "unresolved": statuses["unresolved"], | |
| "natural_stop_finish_reason_stop": finishes["stop"], | |
| "token_cap_finish_reason_length": finishes["length"], | |
| "wall_time_finish_reason": finishes["wall_time"], | |
| "mean_tokens": round(statistics.mean(lengths), 3), | |
| "median_tokens": round(statistics.median(lengths), 3), | |
| "max_tokens": max(lengths), | |
| "mean_max_trailing512_duplicate8_fraction": round( | |
| statistics.mean(max_repetition), 6 | |
| ), | |
| "median_max_trailing512_duplicate8_fraction": round( | |
| statistics.median(max_repetition), 6 | |
| ), | |
| "n_max_window_duplicate8_fraction_ge_0_5": sum( | |
| value >= 0.5 for value in max_repetition | |
| ), | |
| "mean_full_response_duplicate8_fraction": round( | |
| statistics.mean(full_repetition), 6 | |
| ), | |
| "mean_max_full_response_8gram_frequency": round( | |
| statistics.mean( | |
| int(record["max_full_response_8gram_frequency"]) for record in group | |
| ), | |
| 3, | |
| ), | |
| "eos_id_in_output_metadata_true": sum( | |
| bool(record.get("eos_id_in_output")) for record in group | |
| ), | |
| } | |
| ) | |
| question_rows = [] | |
| for row in sorted(by_question): | |
| output: dict[str, Any] = {"source_row": row} | |
| for condition in CONDITIONS: | |
| seeds = by_question[row][condition] | |
| statuses = [str(seeds[seed]["score"].get("status", "missing")) for seed in (0, 1)] | |
| output[f"{condition}_seed0"] = statuses[0] | |
| output[f"{condition}_seed1"] = statuses[1] | |
| output[f"{condition}_correct_of_2"] = sum(status == "correct" for status in statuses) | |
| question_rows.append(output) | |
| return condition_rows, question_rows | |
| def main() -> None: | |
| parser = argparse.ArgumentParser() | |
| parser.add_argument("--records-root", required=True, type=Path) | |
| parser.add_argument("--output-dir", required=True, type=Path) | |
| args = parser.parse_args() | |
| records = read_records(args.records_root) | |
| args.output_dir.mkdir(parents=True, exist_ok=True) | |
| record_fields = ( | |
| "source_row", | |
| "seed", | |
| "condition", | |
| "candidate_id", | |
| "score_status", | |
| "tokens", | |
| "finish_reason", | |
| "truncated", | |
| "wall_time_truncated", | |
| "eos_id_in_output", | |
| "elapsed_seconds", | |
| "full_response_duplicate_8gram_fraction", | |
| "max_sampled_trailing512_duplicate_8gram_fraction", | |
| "max_full_response_8gram_frequency", | |
| "n_sampled_trailing_windows", | |
| ) | |
| record_rows = [] | |
| for record in sorted( | |
| records, key=lambda item: (item["condition"], int(item["source_row"]), int(item["seed"])) | |
| ): | |
| record_rows.append( | |
| { | |
| "source_row": record["source_row"], | |
| "seed": record["seed"], | |
| "condition": record["condition"], | |
| "candidate_id": record.get("candidate_id"), | |
| "score_status": record.get("score", {}).get("status"), | |
| "tokens": record["tokens"], | |
| "finish_reason": record.get("finish_reason"), | |
| "truncated": record.get("truncated"), | |
| "wall_time_truncated": record.get("wall_time_truncated"), | |
| "eos_id_in_output": record.get("eos_id_in_output"), | |
| "elapsed_seconds": record.get("elapsed_seconds"), | |
| **{ | |
| key: record[key] | |
| for key in record_fields[11:] | |
| }, | |
| } | |
| ) | |
| condition_rows, question_rows = summarize(records) | |
| write_csv(args.output_dir / "heldout_response_diagnostics_by_record.csv", record_rows) | |
| write_csv(args.output_dir / "heldout_response_diagnostics_by_condition.csv", condition_rows) | |
| write_csv(args.output_dir / "heldout_response_diagnostics_per_question.csv", question_rows) | |
| (args.output_dir / "heldout_response_diagnostics.json").write_text( | |
| json.dumps( | |
| { | |
| "record_count": len(records), | |
| "records_root": str(args.records_root), | |
| "repetition_metric": { | |
| "input": "full generated_token_ids from each complete response record", | |
| "local": "duplicate 8-gram fraction in trailing 512 token window, sampled at positions 255, 511, 767, ...; report maximum per response", | |
| "global": "duplicate 8-gram fraction over all contiguous 8-grams in the full response", | |
| "interpretation": "exploratory descriptive proxy only; not a validated loop or productivity label", | |
| }, | |
| "conditions": condition_rows, | |
| "per_question": question_rows, | |
| }, | |
| indent=2, | |
| ensure_ascii=False, | |
| ) | |
| + "\n", | |
| encoding="utf-8", | |
| ) | |
| print(f"validated_records={len(records)}") | |
| print(f"output_dir={args.output_dir}") | |
| if __name__ == "__main__": | |
| main() | |