File size: 8,052 Bytes
1e59964
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
"""
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)