""" StepProbe: Step Alignment Aligns the step sequences from a full-precision model and a quantized model for the same problem, enabling step-by-step comparison even when the two traces have different numbers of steps or different boundaries. Methods: 1. DTW (Dynamic Time Warping) on step embeddings 2. Longest Common Subsequence on step text 3. Index-based (simple 1:1 matching by position) """ import difflib from dataclasses import dataclass from typing import List, Tuple, Optional import numpy as np @dataclass class StepAlignment: """A single aligned pair of steps.""" ref_index: Optional[int] # index in reference (FP16), None if insertion hyp_index: Optional[int] # index in hypothesis (quantized), None if deletion ref_text: str hyp_text: str similarity: float # 0.0 - 1.0 alignment_type: str # "match" | "substitution" | "insertion" | "deletion" def text_similarity(a: str, b: str) -> float: """Compute text similarity between two step strings using SequenceMatcher.""" if not a and not b: return 1.0 if not a or not b: return 0.0 return difflib.SequenceMatcher(None, a.lower(), b.lower()).ratio() def align_by_index(ref_steps: List[dict], hyp_steps: List[dict]) -> List[StepAlignment]: """ Simple index-based alignment: pair step i with step i. Good when both traces have similar structure. """ alignments = [] max_len = max(len(ref_steps), len(hyp_steps)) for i in range(max_len): ref = ref_steps[i] if i < len(ref_steps) else None hyp = hyp_steps[i] if i < len(hyp_steps) else None ref_text = ref["text"] if ref else "" hyp_text = hyp["text"] if hyp else "" if ref and hyp: sim = text_similarity(ref_text, hyp_text) atype = "match" if sim > 0.8 else "substitution" elif ref and not hyp: sim = 0.0 atype = "deletion" else: sim = 0.0 atype = "insertion" alignments.append(StepAlignment( ref_index=ref["index"] if ref else None, hyp_index=hyp["index"] if hyp else None, ref_text=ref_text, hyp_text=hyp_text, similarity=sim, alignment_type=atype, )) return alignments def align_by_dtw(ref_steps: List[dict], hyp_steps: List[dict]) -> List[StepAlignment]: """ Dynamic Time Warping alignment using text similarity as cost. Better for traces with different numbers of steps. """ n = len(ref_steps) m = len(hyp_steps) if n == 0 and m == 0: return [] if n == 0: return [StepAlignment(None, h["index"], "", h["text"], 0.0, "insertion") for h in hyp_steps] if m == 0: return [StepAlignment(r["index"], None, r["text"], "", 0.0, "deletion") for r in ref_steps] # Compute cost matrix (1 - similarity) cost = np.zeros((n + 1, m + 1)) cost[0, :] = np.arange(m + 1) cost[:, 0] = np.arange(n + 1) sim_matrix = np.zeros((n, m)) for i in range(n): for j in range(m): sim_matrix[i, j] = text_similarity(ref_steps[i]["text"], hyp_steps[j]["text"]) for i in range(1, n + 1): for j in range(1, m + 1): sub_cost = cost[i - 1, j - 1] + (1.0 - sim_matrix[i - 1, j - 1]) del_cost = cost[i - 1, j] + 1.0 ins_cost = cost[i, j - 1] + 1.0 cost[i, j] = min(sub_cost, del_cost, ins_cost) # Traceback alignments = [] i, j = n, m while i > 0 or j > 0: if i > 0 and j > 0: sub_cost = cost[i - 1, j - 1] + (1.0 - sim_matrix[i - 1, j - 1]) del_cost = cost[i - 1, j] + 1.0 ins_cost = cost[i, j - 1] + 1.0 min_cost = min(sub_cost, del_cost, ins_cost) if min_cost == sub_cost: sim = sim_matrix[i - 1, j - 1] atype = "match" if sim > 0.8 else "substitution" alignments.append(StepAlignment( ref_index=ref_steps[i - 1]["index"], hyp_index=hyp_steps[j - 1]["index"], ref_text=ref_steps[i - 1]["text"], hyp_text=hyp_steps[j - 1]["text"], similarity=sim, alignment_type=atype, )) i -= 1 j -= 1 elif min_cost == del_cost: alignments.append(StepAlignment( ref_index=ref_steps[i - 1]["index"], hyp_index=None, ref_text=ref_steps[i - 1]["text"], hyp_text="", similarity=0.0, alignment_type="deletion", )) i -= 1 else: alignments.append(StepAlignment( ref_index=None, hyp_index=hyp_steps[j - 1]["index"], ref_text="", hyp_text=hyp_steps[j - 1]["text"], similarity=0.0, alignment_type="insertion", )) j -= 1 elif i > 0: alignments.append(StepAlignment( ref_index=ref_steps[i - 1]["index"], hyp_index=None, ref_text=ref_steps[i - 1]["text"], hyp_text="", similarity=0.0, alignment_type="deletion", )) i -= 1 else: alignments.append(StepAlignment( ref_index=None, hyp_index=hyp_steps[j - 1]["index"], ref_text="", hyp_text=hyp_steps[j - 1]["text"], similarity=0.0, alignment_type="insertion", )) j -= 1 alignments.reverse() return alignments def align_steps( ref_steps: List[dict], hyp_steps: List[dict], method: str = "dtw", ) -> List[StepAlignment]: """ Align reference (FP16) and hypothesis (quantized) step sequences. Args: ref_steps: List of step dicts from the full-precision model hyp_steps: List of step dicts from the quantized model method: "dtw" or "index" Returns: List of StepAlignment objects """ if method == "index": return align_by_index(ref_steps, hyp_steps) elif method == "dtw": return align_by_dtw(ref_steps, hyp_steps) else: raise ValueError(f"Unknown alignment method: {method}. Use 'dtw' or 'index'.") def alignment_summary(alignments: List[StepAlignment]) -> dict: """Compute summary statistics for an alignment.""" n = len(alignments) if n == 0: return {"n_aligned": 0} types = [a.alignment_type for a in alignments] sims = [a.similarity for a in alignments if a.alignment_type in ("match", "substitution")] return { "n_aligned": n, "n_match": types.count("match"), "n_substitution": types.count("substitution"), "n_insertion": types.count("insertion"), "n_deletion": types.count("deletion"), "avg_similarity": float(np.mean(sims)) if sims else 0.0, "min_similarity": float(np.min(sims)) if sims else 0.0, } def format_alignment(alignments: List[StepAlignment], max_text_len: int = 60) -> str: """Format an alignment for human-readable display.""" lines = [] lines.append(f"{'Type':<14} {'Ref#':<6} {'Hyp#':<6} {'Sim':<6} {'Ref Text':<{max_text_len}} {'Hyp Text'}") lines.append("-" * (14 + 6 + 6 + 6 + max_text_len * 2 + 5)) for a in alignments: ref_idx = str(a.ref_index) if a.ref_index is not None else "-" hyp_idx = str(a.hyp_index) if a.hyp_index is not None else "-" ref_t = a.ref_text[:max_text_len].replace("\n", " ") hyp_t = a.hyp_text[:max_text_len].replace("\n", " ") lines.append(f"{a.alignment_type:<14} {ref_idx:<6} {hyp_idx:<6} {a.similarity:<6.2f} {ref_t:<{max_text_len}} {hyp_t}") return "\n".join(lines)