Datasets:
Download code/scale_export.py from rvashurin/coqar-clarifications: direct link, hf CLI and curl.
- Browser
- Download file 19.4 kB
-
https://huggingface.co/datasets/rvashurin/coqar-clarifications/resolve/main/code/scale_export.py
- Command line
-
hf download hf://datasets/rvashurin/coqar-clarifications/code/scale_export.py
-
curl -L -o scale_export.py https://huggingface.co/datasets/rvashurin/coqar-clarifications/resolve/main/code/scale_export.py
19.4 kB
| """Export paired CoQAR runs without model calls or silently dropping failures.""" | |
| from collections import Counter, defaultdict | |
| from datetime import datetime, timezone | |
| import hashlib | |
| import json | |
| import math | |
| from pathlib import Path | |
| import statistics | |
| from scale_client import read_calls, read_cost_summary | |
| def _hash(value): | |
| return hashlib.sha256(json.dumps(value, ensure_ascii=False, sort_keys=True, | |
| allow_nan=False).encode()).hexdigest() | |
| def _save(path, value): | |
| temporary = path.with_suffix(path.suffix + ".tmp") | |
| temporary.write_text(json.dumps(value, ensure_ascii=False, indent=2, allow_nan=False)) | |
| temporary.replace(path) | |
| def _call(identifier, by_id, story, question, stage, menu=None, selected_id=None): | |
| attempts = by_id.get(identifier, []) | |
| completed = [call for call in attempts if call.get("status") == "completed"] | |
| call = completed[0] if completed else None | |
| errors = ["multiple_completed_attempts"] if len(completed) > 1 else [] | |
| if call: | |
| request = call["request"] | |
| if _hash(request) != call.get("request_sha256"): | |
| errors.append("request_hash_mismatch") | |
| try: | |
| prefix = "Input JSON:\n" | |
| if not request["input"].startswith(prefix): | |
| raise ValueError("Unexpected input prefix") | |
| payload = json.loads(request["input"][len(prefix):]) | |
| if payload.get("story") != story or payload.get("question") != question: | |
| errors.append("input_story_or_question_mismatch") | |
| expected = {"story", "question"} | ({"menu", "selected_id"} if stage == "render" | |
| else {"samples"} if stage == "audit" else set()) | |
| if set(payload) != expected: | |
| errors.append("unexpected_model_visible_fields") | |
| if stage == "render" and (payload.get("menu") != menu | |
| or payload.get("selected_id") != selected_id): | |
| errors.append("render_menu_or_selection_mismatch") | |
| except (ValueError, TypeError, KeyError): | |
| errors.append("invalid_saved_input") | |
| try: | |
| if json.loads(call["text"]) != call.get("parsed"): | |
| errors.append("response_text_parsed_mismatch") | |
| except (ValueError, TypeError, KeyError): | |
| errors.append("invalid_saved_response_text") | |
| extracted = "".join(part.get("text", "") for item in call.get("response", {}).get("output", []) | |
| if item.get("type") == "message" for part in item.get("content", []) | |
| if part.get("type") == "output_text") | |
| if extracted != call.get("text"): | |
| errors.append("response_body_text_mismatch") | |
| return call, attempts, errors | |
| def _menu_errors(menu): | |
| if not isinstance(menu, dict): | |
| return ["missing_menu"] | |
| errors = [] | |
| items = menu.get("items", []) | |
| if not isinstance(items, list) or not 1 <= len(items) <= 5: | |
| return ["invalid_item_count"] | |
| if any(not isinstance(item, dict) for item in items): | |
| return ["invalid_item_type"] | |
| ids = [item.get("id") for item in items] | |
| if any(not isinstance(value, str) or not value for value in ids) or len(set(ids)) != len(ids): | |
| errors.append("invalid_item_ids") | |
| masses = [item.get("probability") for item in items] | |
| if any(type(p) not in (int, float) or not math.isfinite(p) or p < 0 for p in masses): | |
| errors.append("invalid_probabilities") | |
| elif not math.isclose(sum(masses), 1, abs_tol=0.02): | |
| errors.append("probabilities_do_not_sum_to_one") | |
| if menu.get("status") == "already_answerable": | |
| if not (menu.get("gap") == "" and menu.get("constraints") == [] | |
| and len(items) == 1 and ids == ["unchanged"] and masses == [1]): | |
| errors.append("already_answerable_contract") | |
| elif menu.get("status") != "underspecified" or "unchanged" in ids: | |
| errors.append("underspecified_contract") | |
| return errors | |
| def _audit_map(audit, expected): | |
| fields = {"sample_index": int, "answerable": bool, "answer": str, "answer_cluster": str, | |
| "contradiction": bool, "contradiction_evidence": str, "unrelated_addition": bool, | |
| "selected_state_compliant": bool, "evidence": str} | |
| items = audit.get("assessments", []) if isinstance(audit, dict) else [] | |
| valid = (isinstance(items, list) and len(items) == expected and all( | |
| isinstance(item, dict) and set(item) == set(fields) | |
| and all(type(item[key]) is kind for key, kind in fields.items()) for item in items)) | |
| if not valid or sorted(item["sample_index"] for item in items) != list(range(expected)): | |
| return {}, False | |
| return {item["sample_index"]: item for item in items}, True | |
| def export_run(run_dir: Path, metadata: dict, subset: dict, config: dict) -> dict: | |
| """Include every planned example/draw and every saved network attempt.""" | |
| run_dir = Path(run_dir) | |
| examples = subset["examples"] | |
| conditions = config.get("conditions", ["original", "modified"]) | |
| expected = config.get("samples_per_example", 5) | |
| jobs = {} | |
| for condition in conditions: | |
| for example in examples: | |
| name = hashlib.sha256(example["id"].encode()).hexdigest()[:24] + ".json" | |
| path = run_dir / "examples" / condition / name | |
| jobs[condition, example["id"]] = json.loads(path.read_text()) if path.exists() else {} | |
| calls = read_calls(run_dir / "api.sqlite") if (run_dir / "api.sqlite").exists() else [] | |
| by_id = defaultdict(list) | |
| for call in calls: | |
| by_id[call["id"]].append(call) | |
| temporary = run_dir / "requests.jsonl.tmp" | |
| with temporary.open("w") as handle: | |
| for call in calls: | |
| handle.write(json.dumps(call, ensure_ascii=False, allow_nan=False) + "\n") | |
| temporary.replace(run_dir / "requests.jsonl") | |
| source_path = Path(__file__).resolve().parent / config["source_path"] | |
| source = {row["id"]: row for row in json.loads(source_path.read_text())["data"]} | |
| summary = {"metadata": metadata, "exported_utc": datetime.now(timezone.utc).isoformat(), | |
| "configuration": config, "conditions": {}, "cost": read_cost_summary(run_dir / "api.sqlite") | |
| if calls else {}, "judgment_source": "Raw Luna audits; no human or Codex review", | |
| "limitations": ["Mechanical ablation does not guarantee unanswerability.", | |
| "Repeated question turns from one story are statistically dependent.", | |
| "Answer clusters, coherence, and state compliance are model judgments.", | |
| "Diversity is conditional on audited valid samples and may reflect judge error."]} | |
| for condition in conditions: | |
| exported, counts, question_metrics, all_errors = {}, Counter(), [], [] | |
| counts.update({key: 0 for key in ( | |
| "samples_recorded", "samples_completed_calls", "samples_valid_format_and_provenance", | |
| "samples_exactly_unchanged", "samples_raw_empty_addition", "samples_expected_noop_contract", | |
| "samples_business_contract_errors", "samples_provenance_errors", "samples_audited", | |
| "raw_audit_complete_and_coherent", "raw_audit_contradictions", "raw_audit_state_compliant", | |
| "raw_audit_complete_and_state_compliant", "audit_answerable_evidence_not_exact_substring")}) | |
| distinct, disagreement = [], [] | |
| for example in examples: | |
| eid, question = example["id"], example["question"] | |
| story = example[condition + "_story"] | |
| job = jobs[condition, eid] | |
| prefix = f"{metadata['experiment_fingerprint'][:12]}/{condition}/{eid}" | |
| provenance = [] | |
| raw = source.get(example["story_id"], {}) | |
| raw_question = next((q for q in raw.get("questions", []) | |
| if q["turn_id"] == example["turn_id"]), {}) | |
| if raw.get("story") != example["original_story"] or question not in raw_question.get("paraphrase", []): | |
| provenance.append("source_story_or_question_mismatch") | |
| if job and (job.get("id") != eid or job.get("input_story") != story | |
| or job.get("question") != question or job.get("condition") != condition): | |
| provenance.append("job_input_mismatch") | |
| if job and job.get("metadata", {}).get("experiment_fingerprint") != metadata["experiment_fingerprint"]: | |
| provenance.append("job_experiment_mismatch") | |
| menu = job.get("menu") | |
| menu_call, menu_attempts, menu_check = _call(job.get("menu_call_id", prefix + "/menu"), by_id, story, question, "menu") | |
| menu_errors = _menu_errors(menu) | |
| if menu_call and menu_call.get("parsed") != menu: | |
| menu_check.append("menu_response_mismatch") | |
| counts["jobs_recorded"] += bool(job) | |
| counts["jobs_marked_complete"] += bool(job.get("complete")) | |
| counts["menus_completed"] += bool(menu_call) | |
| counts["menu_business_contract_valid"] += bool(menu_call and not menu_errors) | |
| counts["menus_already_answerable"] += bool(isinstance(menu, dict) and menu.get("status") == "already_answerable") | |
| counts["menus_already_answerable_contract_valid"] += bool( | |
| isinstance(menu, dict) and menu.get("status") == "already_answerable" and not menu_errors) | |
| audit_call, audit_attempts, audit_check = _call(job.get("audit_call_id", prefix + "/audit"), by_id, story, question, "audit") | |
| audit = job.get("audit") | |
| assessments, audit_valid = _audit_map(audit, expected) | |
| if audit_call and audit_call.get("parsed") != audit: | |
| audit_check.append("audit_response_mismatch") | |
| audit_valid = bool(audit_valid and audit_call and not audit_check) | |
| counts["audit_groups_valid_schema"] += audit_valid | |
| actual = {sample["sample_index"]: sample for sample in job.get("samples", [])} | |
| if len(actual) != len(job.get("samples", [])) or any(i not in range(expected) for i in actual): | |
| provenance.append("duplicate_or_invalid_sample_indices") | |
| clarifications, clusters, compliant_clusters, unchanged = [], [], [], 0 | |
| for index in range(expected): | |
| sample = actual.get(index, {"sample_index": index, "missing": True}) | |
| call, attempts, checks = _call(sample.get("api_call_id", prefix + f"/sample/{index}"), by_id, story, question, | |
| "render", menu, sample.get("selected_id")) | |
| raw_value = call.get("parsed") if call else None | |
| value = raw_value if isinstance(raw_value, dict) else {} | |
| addition = value.get("addition") | |
| business = [] | |
| if call and (value.get("status") == "already_answerable" and addition != "" | |
| or value.get("status") == "completed" and not str(addition or "").strip()): | |
| business.append("render_status_addition_contract") | |
| if call and (not isinstance(menu, dict) or sample.get("selected_id") not in | |
| [item.get("id") for item in menu.get("items", [])]): | |
| checks.append("selected_item_missing") | |
| mismatch = (sample["raw_parsed"] != raw_value if "raw_parsed" in sample else | |
| sample.get("addition") != addition or sample.get("status") != value.get("status")) | |
| if call and not sample.get("missing") and mismatch: | |
| checks.append("sample_parsed_response_mismatch") | |
| shape = (set(value) == {"status", "addition", "justification"} | |
| and value.get("status") in ("completed", "already_answerable") | |
| and isinstance(addition, str) and isinstance(value.get("justification"), str)) | |
| if shape and not sample.get("missing"): | |
| reconstructed = story + ("\n\n" + addition.strip() if addition.strip() else "") | |
| if sample.get("clarified_story") != reconstructed: | |
| checks.append("clarified_story_reconstruction_mismatch") | |
| valid = bool(call and shape and sample.get("valid_format") and not checks and not provenance and not menu_check) | |
| exact = bool(valid and sample.get("clarified_story") == story) | |
| unchanged += exact | |
| counts["samples_recorded"] += not sample.get("missing", False) | |
| counts["samples_completed_calls"] += bool(call) | |
| counts["samples_valid_format_and_provenance"] += valid | |
| counts["samples_exactly_unchanged"] += exact | |
| counts["samples_raw_empty_addition"] += bool(call and addition == "") | |
| counts["samples_expected_noop_contract"] += bool(valid and exact and addition == "" | |
| and value.get("status") == "already_answerable") | |
| counts["samples_business_contract_errors"] += bool(business) | |
| counts["samples_provenance_errors"] += bool(checks or provenance) | |
| assessment = assessments.get(index) if audit_valid else None | |
| evidence_match = None | |
| if assessment: | |
| counts["samples_audited"] += 1 | |
| complete = valid and assessment["answerable"] and not assessment["contradiction"] | |
| counts["raw_audit_complete_and_coherent"] += complete | |
| counts["raw_audit_contradictions"] += assessment["contradiction"] | |
| counts["raw_audit_state_compliant"] += assessment["selected_state_compliant"] | |
| counts["raw_audit_complete_and_state_compliant"] += complete and assessment["selected_state_compliant"] | |
| evidence_match = bool(assessment["evidence"] and assessment["evidence"] in sample.get("clarified_story", "")) | |
| counts["audit_answerable_evidence_not_exact_substring"] += assessment["answerable"] and not evidence_match | |
| if complete: | |
| clusters.append(assessment["answer_cluster"]) | |
| if assessment["selected_state_compliant"]: | |
| compliant_clusters.append(assessment["answer_cluster"]) | |
| clarifications.append({**sample, "generation_call": call, "generation_attempts": attempts, | |
| "provenance_errors": checks, "business_contract_errors": business, | |
| "audit_assessment": assessment, "audit_evidence_is_exact_substring": evidence_match}) | |
| counts["questions_all_outputs_exactly_unchanged"] += unchanged == expected | |
| hist = Counter(clusters) | |
| distinct.append(len(hist)) | |
| n = len(clusters) | |
| pair = 1 - sum(c * (c - 1) for c in hist.values()) / (n * (n - 1)) if n >= 2 else None | |
| if pair is not None: | |
| disagreement.append(pair) | |
| question_metrics.append({"id": eid, "raw_complete_answers": n, "answer_clusters": dict(hist), | |
| "pairwise_disagreement": pair, "complete_state_compliant": len(compliant_clusters)}) | |
| errors = [*job.get("errors", []), *provenance, *menu_check, *audit_check] | |
| counts["groups_provenance_errors"] += bool(provenance or menu_check or audit_check) | |
| all_errors.extend({"id": eid, "error": error} for error in errors) | |
| exported[eid] = {"original_story": example["original_story"], "modified_story": example["modified_story"], | |
| "input_story": story, "question": question, "removed_sentences": example["removed_sentences"], | |
| "applied_removed_sentences": example["removed_sentences"] if condition == "modified" else [], | |
| "flags": example["flags"], "missing": not bool(job), | |
| "interpretation_stage": {"menu": menu, "call": menu_call, "attempts": menu_attempts, | |
| "business_contract_errors": menu_errors}, | |
| "clarifications": clarifications, "audit": audit, "audit_call": audit_call, | |
| "audit_attempts": audit_attempts, "errors": errors} | |
| planned = len(examples) * expected | |
| audit_planned = condition == "modified" and config.get("audit_damaged_outputs", True) | |
| summary["conditions"][condition] = {"expected_examples": len(examples), "expected_samples": planned, | |
| "counts": dict(counts), "missing_samples": planned - counts["samples_recorded"], | |
| "unaudited_samples": planned - counts["samples_audited"], | |
| "audit_planned": audit_planned, | |
| "raw_complete_fraction_of_planned": counts["raw_audit_complete_and_coherent"] / planned if audit_planned else None, | |
| "mean_distinct_raw_complete_answers": statistics.mean(distinct) if audit_planned else None, | |
| "mean_pairwise_disagreement": statistics.mean(disagreement) if disagreement else None, | |
| "questions_with_two_raw_complete_answers": len(disagreement), "per_question": question_metrics, | |
| "errors": all_errors} | |
| _save(run_dir / f"{condition}_validation.json", {"metadata": metadata, "condition": condition, | |
| "samples": exported, "errors": all_errors}) | |
| _save(run_dir / "summary.json", summary) | |
| lines = ["# CoQAR dev: paired two-step v2 run", "", "All planned examples and draws are retained, including missing or failed outputs.", "", | |
| "Judgments below are raw Luna audits, without human or Codex corrections. Exact unchanged counts are mechanical checks.", "", | |
| "| Condition | Planned draws | Recorded | Valid format + provenance | Exactly unchanged | Audited | Raw complete + coherent |", "|---|---:|---:|---:|---:|---:|---:|"] | |
| for condition, metrics in summary["conditions"].items(): | |
| c = metrics["counts"] | |
| complete = c.get("raw_audit_complete_and_coherent", 0) if metrics["audit_planned"] else "not audited" | |
| lines.append(f"| {condition} | {metrics['expected_samples']} | {c.get('samples_recorded', 0)} | {c.get('samples_valid_format_and_provenance', 0)} | {c.get('samples_exactly_unchanged', 0)} | {c.get('samples_audited', 0)} | {complete} |") | |
| cost = summary["cost"] | |
| lines += ["", f"Known token cost: ${cost.get('known_cost_usd', 0):.6f}. Conservative accounted amount: ${cost.get('accounted_usd', 0):.6f}, including input premium and unresolved reservations.", "", | |
| "Input sentence deletion does not guarantee missing evidence. Completion and diversity judgments are exploratory model measurements. Unaudited samples contribute no successes to the planned-draw fraction; their outcomes remain unknown.", "", | |
| "[Original validation](original_validation.json) · [Damaged validation](modified_validation.json) · [Full metrics](summary.json) · [Every request attempt](requests.jsonl)"] | |
| path = run_dir / "report.md" | |
| path.write_text("\n".join(lines) + "\n") | |
| return summary | |