#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Action, parameter, step, subtask, and part metrics for CAD-Drawer. The dataset is the sole source of ground truth. Prediction artifacts contribute only a global row index (_idx) and raw model text (prediction). Missing/unparseable/error rows remain in the fixed reference denominator. """ from collections import Counter, defaultdict import gzip import hashlib import json import os from pathlib import Path import re if __package__: from . import action_metrics, action_parser as action_runner else: import action_metrics import action_parser as action_runner CANONICAL_TEST_FINAL_SHA256 = ( "a0a9c3bd89641b33b4c45237157374f0db0e64711d6cf6a1260a419c47bdda7d" ) CANONICAL_TEST_FINAL_SLOTS = 29239 STRATIFIED_TEST_50_SHA256 = ( "ca1c3b0764f4774dca7b51d0b2bb9fd6660224d6e97e201974645895a45c5a32" ) STRATIFIED_TEST_50_SLOTS = 3352 HELDOUT_TEST_364_SHA256 = ( "991983a4945c1124ce067a521810ad7f04ef8fd65f8c5a6fc8ca1d2f95d8e9ec" ) HELDOUT_TEST_364_SLOTS = 25887 REGISTERED_DATASET_CONTRACTS = { "canonical_test_final_414": { "sha256": CANONICAL_TEST_FINAL_SHA256, "slots": CANONICAL_TEST_FINAL_SLOTS, "parts": 414, "canonical_full_test": True, }, "stratified_test_50_seed42": { "sha256": STRATIFIED_TEST_50_SHA256, "slots": STRATIFIED_TEST_50_SLOTS, "parts": 50, "canonical_full_test": False, }, "heldout_test_364_seed42_complement": { "sha256": HELDOUT_TEST_364_SHA256, "slots": HELDOUT_TEST_364_SLOTS, "parts": 364, "canonical_full_test": False, "model_selection_heldout": True, "complement_of": "stratified_test_50_seed42", }, } class ScoringError(RuntimeError): """Prediction artifact or reference contract is invalid.""" def identify_dataset_contract(records, dataset_hash): """Return a registered immutable benchmark contract, if one matches.""" part_count = len({ record.get("part_id") for record in records if record.get("part_id") is not None }) for name, contract in REGISTERED_DATASET_CONTRACTS.items(): if ( len(records) == contract["slots"] and part_count == contract["parts"] and dataset_hash == contract["sha256"] ): return {"name": name, **contract} return None def dataset_sha256(path, chunk_size=1024 * 1024): digest = hashlib.sha256() opener = gzip.open if Path(path).suffix.lower() == ".gz" else open with opener(path, "rb") as handle: while True: block = handle.read(chunk_size) if not block: break digest.update(block) return digest.hexdigest() def read_jsonl(path): rows = [] opener = gzip.open if Path(path).suffix.lower() == ".gz" else open with opener(path, "rt", encoding="utf-8") as handle: for line_number, line in enumerate(handle, 1): if not line.strip(): continue try: value = json.loads(line) except json.JSONDecodeError as exc: raise ScoringError( "%s:%d is invalid JSON: %s" % (path, line_number, exc)) from exc if not isinstance(value, dict): raise ScoringError( "%s:%d must contain a JSON object" % (path, line_number)) rows.append(value) return rows def reference_slice(records, start_index=0, limit=0): if isinstance(start_index, bool) or start_index < 0: raise ScoringError("start_index must be a non-negative integer") if isinstance(limit, bool) or limit < 0: raise ScoringError("limit must be a non-negative integer") if start_index > len(records): raise ScoringError( "start_index %d exceeds dataset size %d" % (start_index, len(records))) end_index = len(records) if limit: end_index = min(end_index, start_index + limit) return range(start_index, end_index) def reference_indices(records, start_index=0, limit=0, num_shards=1, shard_index=0): """Select a deterministic modulo shard from a canonical reference slice.""" if isinstance(num_shards, bool) or num_shards <= 0: raise ScoringError("num_shards must be a positive integer") if ( isinstance(shard_index, bool) or shard_index < 0 or shard_index >= num_shards ): raise ScoringError( "shard_index must be in [0, %d)" % num_shards) base = reference_slice( records, start_index=start_index, limit=limit) return [ index for index in base if index % num_shards == shard_index ] def load_prediction_map(path, allowed_indices): allowed = set(allowed_indices) predictions = {} for line_number, row in enumerate(read_jsonl(path), 1): if "_idx" not in row: raise ScoringError( "prediction record %d has no _idx" % line_number) index = row["_idx"] if isinstance(index, bool) or not isinstance(index, int): raise ScoringError( "prediction record %d has non-integer _idx=%r" % (line_number, index)) if index not in allowed: raise ScoringError( "prediction record %d has out-of-slice _idx=%d" % (line_number, index)) if index in predictions: raise ScoringError( "duplicate prediction _idx=%d (record %d)" % (index, line_number)) predictions[index] = row return predictions FORMAT_PATTERN = re.compile( r"^\s*]*>.*?\s*" r"]*>.*?\s*" r"]*>.*?\s*$", flags=re.IGNORECASE | re.DOTALL, ) def is_format_compliant(text): if not isinstance(text, str): return False if not FORMAT_PATTERN.fullmatch(text): return False lowered = text.lower() return all(lowered.count("<%s" % tag) == 1 for tag in ( "ui_reasoning", "action", "parameters")) def _empty_counts(): return { "slots": 0, "parseable": 0, "format_compliant": 0, "action_correct": 0, "parameter_correct": 0, "step_correct": 0, } def _with_rates(counts): result = dict(counts) denominator = counts["slots"] for numerator, rate_name in ( ("parseable", "parse_rate"), ("format_compliant", "format_compliance_rate"), ("action_correct", "action_accuracy"), ("parameter_correct", "parameter_accuracy"), ("step_correct", "step_accuracy"), ): result[rate_name] = ( counts[numerator] / denominator if denominator else None) return result def _record_part_fields(record): """Return the canonical identity fields for a complete part trajectory.""" return { "part_key": ( record.get("source_part_relpath") or record.get("part_id")), "part_id": record.get("part_id"), } def _record_subtask_fields(record): """Return the canonical fields needed to identify and order a subtask.""" present_task = record.get("present_task") if not isinstance(present_task, dict): present_task = {} task_progress = record.get("task_progress") if not isinstance(task_progress, dict): task_progress = {} return { "part_key": _record_part_fields(record)["part_key"], "task_id": ( present_task.get("task_id") or record.get("task_id")), "action_index_in_task": task_progress.get("action_index_in_task"), "total_actions_in_task": task_progress.get("total_actions_in_task"), } def build_subtask_contract(records): """Validate canonical subtask grouping and ordering for a dataset. A subtask is scoped by ``(part_key, task_id)``. ``part_key`` prefers the source-relative part path because task IDs restart for every part. This function does not inspect predictions; it validates only dataset metadata. Invalid metadata disables subtask-level metrics without changing slot-level Action/Parameter/Step scoring. """ groups = defaultdict(list) index_to_key = {} errors = [] for index, record in enumerate(records): present_task = record.get("present_task") nested_task_id = ( present_task.get("task_id") if isinstance(present_task, dict) else None) top_task_id = record.get("task_id") if ( nested_task_id is not None and top_task_id is not None and str(nested_task_id) != str(top_task_id) ): errors.append( "_idx=%d has conflicting nested/top-level task_id (%r/%r)" % ( index, nested_task_id, top_task_id)) continue fields = _record_subtask_fields(record) missing = [ name for name, value in fields.items() if value is None or value == "" ] if missing: errors.append( "_idx=%d missing %s" % (index, ",".join(missing))) continue action_index = fields["action_index_in_task"] total_actions = fields["total_actions_in_task"] if ( isinstance(action_index, bool) or not isinstance(action_index, int) or action_index <= 0 or isinstance(total_actions, bool) or not isinstance(total_actions, int) or total_actions <= 0 ): errors.append( "_idx=%d has invalid task progress (%r/%r)" % ( index, action_index, total_actions)) continue key = (str(fields["part_key"]), str(fields["task_id"])) groups[key].append({ "_idx": index, "action_index_in_task": action_index, "total_actions_in_task": total_actions, }) index_to_key[index] = key for key, rows in sorted(groups.items()): rows.sort(key=lambda item: item["_idx"]) declared_totals = { item["total_actions_in_task"] for item in rows} if len(declared_totals) != 1: errors.append( "subtask %r has inconsistent total_actions_in_task=%r" % ( key, sorted(declared_totals))) continue declared_total = next(iter(declared_totals)) observed_order = [ item["action_index_in_task"] for item in rows] expected_order = list(range(1, declared_total + 1)) if len(rows) != declared_total or observed_order != expected_order: errors.append( "subtask %r expected ordered actions %r but observed %r" % ( key, expected_order, observed_order)) global_indices = [item["_idx"] for item in rows] if global_indices != list(range( global_indices[0], global_indices[-1] + 1)): errors.append( "subtask %r is not contiguous in the dataset" % (key,)) return { "valid": not errors, "groups": groups, "index_to_key": index_to_key, "error_count": len(errors), "errors_preview": errors[:50], } def build_part_contract(records): """Validate canonical part grouping and global trajectory ordering.""" groups = defaultdict(list) index_to_key = {} errors = [] for index, record in enumerate(records): fields = _record_part_fields(record) part_key = fields["part_key"] if part_key is None or part_key == "": errors.append("_idx=%d missing part identity" % index) continue key = str(part_key) groups[key].append({ "_idx": index, "part_id": fields["part_id"], }) index_to_key[index] = key for key, rows in sorted(groups.items()): rows.sort(key=lambda item: item["_idx"]) global_indices = [item["_idx"] for item in rows] if global_indices != list(range( global_indices[0], global_indices[-1] + 1)): errors.append( "part %r is not contiguous in the dataset" % key) return { "valid": not errors, "groups": groups, "index_to_key": index_to_key, "error_count": len(errors), "errors_preview": errors[:50], } def _empty_subtask_metrics(): return { "subtasks_touched": 0, "complete_subtasks": 0, "partial_subtasks_excluded": 0, "successful_subtasks": 0, "subtask_exact_match": None, "prefix_correct_steps": 0, "complete_subtask_steps": 0, "subtask_prefix_completion_macro": None, "subtask_prefix_step_accuracy": None, "subtask_metrics_complete": False, } def _empty_part_metrics(): return { "parts_touched": 0, "complete_parts": 0, "partial_parts_excluded": 0, "successful_parts": 0, "part_exact_match": None, "step_correct_steps": 0, "prefix_correct_steps": 0, "complete_part_steps": 0, "part_step_accuracy_macro": None, "part_step_accuracy_micro": None, "part_prefix_completion_macro": None, "part_prefix_step_accuracy": None, "part_metrics_complete": False, } def _validate_reference(index, record): try: expected = action_runner.parse_model_output( action_runner.assistant_text(record)) except Exception as exc: raise ScoringError( "canonical reference _idx=%d cannot be parsed: %s" % (index, exc)) from exc label = record.get("label_action_type") if label is not None and label != expected.action: raise ScoringError( "canonical reference _idx=%d action label %r != parsed %r" % (index, label, expected.action)) return expected def _score_subtask_metrics(contract, selected_indices, details): """Aggregate per-slot step success into complete subtasks.""" result = _empty_subtask_metrics() result.update({ "subtask_contract_valid": contract["valid"], "subtask_contract_error_count": contract["error_count"], "subtask_contract_errors_preview": contract["errors_preview"], }) selected = set(selected_indices) detail_by_index = {item["_idx"]: item for item in details} complete_groups = [] partial_groups = [] for key, rows in contract["groups"].items(): group_indices = [item["_idx"] for item in rows] overlap = selected.intersection(group_indices) if not overlap: continue result["subtasks_touched"] += 1 if len(overlap) == len(group_indices): complete_groups.append((key, rows)) else: partial_groups.append((key, rows)) for index in overlap: detail_by_index[index]["subtask_metric_included"] = False detail_by_index[index]["subtask_partial_in_slice"] = True result["complete_subtasks"] = len(complete_groups) result["partial_subtasks_excluded"] = len(partial_groups) result["subtask_metrics_complete"] = ( contract["valid"] and not partial_groups) if not contract["valid"]: return result macro_prefix_sum = 0.0 for key, rows in complete_groups: flags = [ bool(detail_by_index[item["_idx"]]["step_success"]) for item in rows ] prefix_correct = 0 for flag in flags: if not flag: break prefix_correct += 1 successful = all(flags) total_steps = len(flags) prefix_fraction = ( prefix_correct / total_steps if total_steps else 0.0) result["successful_subtasks"] += int(successful) result["prefix_correct_steps"] += prefix_correct result["complete_subtask_steps"] += total_steps macro_prefix_sum += prefix_fraction for item in rows: detail = detail_by_index[item["_idx"]] detail.update({ "subtask_metric_included": True, "subtask_partial_in_slice": False, "subtask_success": successful, "subtask_prefix_correct_steps": prefix_correct, "subtask_prefix_completion": prefix_fraction, }) denominator = result["complete_subtasks"] if denominator: result["subtask_exact_match"] = ( result["successful_subtasks"] / denominator) result["subtask_prefix_completion_macro"] = ( macro_prefix_sum / denominator) step_denominator = result["complete_subtask_steps"] if step_denominator: result["subtask_prefix_step_accuracy"] = ( result["prefix_correct_steps"] / step_denominator) return result def _score_part_metrics(contract, selected_indices, details): """Aggregate per-slot correctness into complete part trajectories.""" result = _empty_part_metrics() result.update({ "part_contract_valid": contract["valid"], "part_contract_error_count": contract["error_count"], "part_contract_errors_preview": contract["errors_preview"], }) selected = set(selected_indices) detail_by_index = {item["_idx"]: item for item in details} complete_groups = [] partial_groups = [] for key, rows in contract["groups"].items(): group_indices = [item["_idx"] for item in rows] overlap = selected.intersection(group_indices) if not overlap: continue result["parts_touched"] += 1 if len(overlap) == len(group_indices): complete_groups.append((key, rows)) else: partial_groups.append((key, rows)) for index in overlap: detail_by_index[index]["part_metric_included"] = False detail_by_index[index]["part_partial_in_slice"] = True result["complete_parts"] = len(complete_groups) result["partial_parts_excluded"] = len(partial_groups) result["part_metrics_complete"] = ( contract["valid"] and not partial_groups) if not contract["valid"]: return result macro_step_sum = 0.0 macro_prefix_sum = 0.0 for key, rows in complete_groups: flags = [ bool(detail_by_index[item["_idx"]]["step_success"]) for item in rows ] correct_steps = sum(flags) prefix_correct = 0 for flag in flags: if not flag: break prefix_correct += 1 successful = all(flags) total_steps = len(flags) step_fraction = ( correct_steps / total_steps if total_steps else 0.0) prefix_fraction = ( prefix_correct / total_steps if total_steps else 0.0) result["successful_parts"] += int(successful) result["step_correct_steps"] += correct_steps result["prefix_correct_steps"] += prefix_correct result["complete_part_steps"] += total_steps macro_step_sum += step_fraction macro_prefix_sum += prefix_fraction for item in rows: detail = detail_by_index[item["_idx"]] detail.update({ "part_metric_included": True, "part_partial_in_slice": False, "part_success": successful, "part_total_steps": total_steps, "part_step_correct_steps": correct_steps, "part_step_accuracy": step_fraction, "part_prefix_correct_steps": prefix_correct, "part_prefix_completion": prefix_fraction, }) part_denominator = result["complete_parts"] if part_denominator: result["part_exact_match"] = ( result["successful_parts"] / part_denominator) result["part_step_accuracy_macro"] = ( macro_step_sum / part_denominator) result["part_prefix_completion_macro"] = ( macro_prefix_sum / part_denominator) step_denominator = result["complete_part_steps"] if step_denominator: result["part_step_accuracy_micro"] = ( result["step_correct_steps"] / step_denominator) result["part_prefix_step_accuracy"] = ( result["prefix_correct_steps"] / step_denominator) return result def score_predictions(dataset_path, prediction_path, start_index=0, limit=0, num_shards=1, shard_index=0): """Score a prediction JSONL against a fixed canonical reference slice.""" dataset_path = Path(dataset_path).resolve() prediction_path = Path(prediction_path).resolve() records = read_jsonl(dataset_path) subtask_contract = build_subtask_contract(records) part_contract = build_part_contract(records) index_list = reference_indices( records, start_index=start_index, limit=limit, num_shards=num_shards, shard_index=shard_index, ) predictions = load_prediction_map(prediction_path, index_list) overall = _empty_counts() by_action = defaultdict(_empty_counts) confusion = defaultdict(Counter) details = [] missing_indices = [] inference_error_slots = 0 for index in index_list: record = records[index] task_fields = _record_subtask_fields(record) expected = _validate_reference(index, record) action_name = expected.action overall["slots"] += 1 by_action[action_name]["slots"] += 1 prediction_row = predictions.get(index) prediction_text = ( prediction_row.get("prediction") if prediction_row is not None else None) if prediction_row is None: missing_indices.append(index) parse_error = "missing_prediction_record" generated = None else: inference_error = prediction_row.get("error") if inference_error: inference_error_slots += 1 prediction_text = None generated = None parse_error = "inference_error: %s" % inference_error else: parse_error = None try: generated = action_runner.parse_model_output( prediction_text) except Exception as exc: generated = None parse_error = str(exc) comparison = { "action_match": False, "parameter_match": False, "step_success": False, } pred_action = "" if prediction_row is None else "" if generated is not None: overall["parseable"] += 1 by_action[action_name]["parseable"] += 1 pred_action = generated.action comparison = action_metrics.compare_to_reference( generated, expected, record=record, screen_size=action_runner.EXPECTED_SCREEN) format_compliant = is_format_compliant(prediction_text) if format_compliant: overall["format_compliant"] += 1 by_action[action_name]["format_compliant"] += 1 for key, metric_name in ( ("action_match", "action_correct"), ("parameter_match", "parameter_correct"), ("step_success", "step_correct"), ): if comparison[key]: overall[metric_name] += 1 by_action[action_name][metric_name] += 1 confusion[action_name][pred_action] += 1 details.append({ "_idx": index, "part_id": record.get("part_id"), "part_key": task_fields["part_key"], "task_id": task_fields["task_id"], "action_index_in_task": task_fields["action_index_in_task"], "total_actions_in_task": task_fields["total_actions_in_task"], "gt_action": action_name, "pred_action": pred_action, "prediction_present": prediction_row is not None, "parse_ok": generated is not None, "parse_error": parse_error, "format_compliant": format_compliant, "action_match": comparison["action_match"], "parameter_match": comparison["parameter_match"], "step_success": comparison["step_success"], }) subtask_metrics = _score_subtask_metrics( subtask_contract, index_list, details) part_metrics = _score_part_metrics( part_contract, index_list, details) dataset_hash = dataset_sha256(dataset_path) coverage_complete = len(predictions) == len(index_list) full_dataset = ( start_index == 0 and limit == 0 and num_shards == 1 and len(index_list) == len(records)) dataset_contract = identify_dataset_contract(records, dataset_hash) dataset_contract_name = ( dataset_contract["name"] if dataset_contract else None) canonical_contract = bool( dataset_contract and dataset_contract["canonical_full_test"]) stratified_test_50_contract = ( dataset_contract_name == "stratified_test_50_seed42") heldout_test_364_contract = ( dataset_contract_name == "heldout_test_364_seed42_complement") registered_benchmark_metrics_valid = ( coverage_complete and full_dataset and dataset_contract is not None and inference_error_slots == 0 and subtask_metrics["subtask_metrics_complete"] and part_metrics["part_metrics_complete"]) summary = { "protocol": "cad_drawer_evaluation_v1", "metric_suite_version": "cad_drawer_l1_metrics_v4", "dataset": str(dataset_path), "dataset_sha256": dataset_hash, "prediction_file": str(prediction_path), "dataset_total_slots": len(records), "slice_start_index": start_index, "slice_end_index_exclusive": ( index_list[-1] + 1 if index_list else start_index), "reference_slots": len(index_list), "num_shards": num_shards, "shard_index": shard_index, "prediction_records": len(predictions), "missing_slots": len(missing_indices), "missing_indices_preview": missing_indices[:50], "inference_error_slots": inference_error_slots, "coverage_complete": coverage_complete, "evaluation_slice_complete": coverage_complete, "registered_dataset_contract": dataset_contract_name, "registered_dataset_contract_details": dataset_contract, "canonical_test_final_contract": canonical_contract, "stratified_test_50_contract": stratified_test_50_contract, "heldout_test_364_contract": heldout_test_364_contract, "inference_clean": inference_error_slots == 0, "registered_benchmark_metrics_valid": ( registered_benchmark_metrics_valid), "official_full_test_metrics_valid": ( registered_benchmark_metrics_valid and canonical_contract), "official_test_50_metrics_valid": ( registered_benchmark_metrics_valid and stratified_test_50_contract), "official_test_364_metrics_valid": ( registered_benchmark_metrics_valid and heldout_test_364_contract), "metrics": _with_rates(overall), "subtask_metrics": subtask_metrics, "part_metrics": part_metrics, "by_gt_action": { name: _with_rates(counts) for name, counts in sorted(by_action.items()) }, "action_confusion": { expected: dict(sorted(predicted.items())) for expected, predicted in sorted(confusion.items()) }, "definitions": { "action_accuracy": "predicted action equals the GT action", "parameter_accuracy": ( "parameters match under the GT action schema; independent " "from predicted action correctness"), "step_accuracy": ( "per-slot conjunction of action_match and parameter_match"), "subtask_exact_match": ( "fraction of complete reference subtasks whose every " "step is correct"), "subtask_prefix_completion_macro": ( "mean, with equal weight per complete subtask, of the " "consecutive correct prefix length divided by task length"), "subtask_prefix_step_accuracy": ( "total consecutive correct prefix slots divided by all slots " "in complete subtasks; longer subtasks receive more weight"), "subtask_scope": ( "subtasks are grouped by part identity and task_id; partial " "subtasks at a requested slice boundary are excluded and make " "subtask_metrics_complete false"), "part_step_accuracy_macro": ( "mean per-part fraction of independently correct reference " "steps; every complete part has equal weight"), "part_step_accuracy_micro": ( "total correct steps divided by all steps in complete parts; " "equivalent to overall step accuracy on a complete full run"), "part_prefix_completion_macro": ( "mean per-part fraction of consecutive correct steps before " "the first failure; every complete part has equal weight"), "part_prefix_step_accuracy": ( "total consecutive correct prefix steps divided by all steps " "in complete parts; longer parts receive more weight"), "part_exact_match": ( "fraction of complete reference part trajectories whose " "every step is correct"), "part_scope": ( "parts are grouped by source-relative part identity and must " "be contiguous; partial parts are excluded"), "parse_rate": ( "canonical FreeCAD action parser accepts the model output"), "denominator": ( "all canonical reference slots in the requested slice; " "missing, inference-error, and parse-error slots score zero"), }, } return summary, details def write_json(path, value): path = Path(path) path.parent.mkdir(parents=True, exist_ok=True) temporary = path.with_name( path.name + ".tmp.%d" % os.getpid()) with temporary.open("w", encoding="utf-8") as handle: json.dump(value, handle, ensure_ascii=False, indent=2) handle.write("\n") handle.flush() os.fsync(handle.fileno()) os.replace(temporary, path) def write_jsonl(path, rows): path = Path(path) path.parent.mkdir(parents=True, exist_ok=True) with path.open("w", encoding="utf-8") as handle: for row in rows: handle.write(json.dumps(row, ensure_ascii=False) + "\n")