File size: 6,859 Bytes
575b0ec
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Reasoning-step segmentation and exact character -> token alignment.

A response is partitioned into contiguous segments that cover every character:
  segment 0..T-1 : reasoning steps (any preamble before "Step 1:" is merged into the first step)
  segment T      : the terminal segment (the "Final answer:" line and anything after it)
Steps are delimited by "Step k:" markers (as in skill_dynamics.scoring.segment). When a
response has no markers, paragraphs separated by blank lines are used instead and
`marker_found` is False, so the fallback rate can be monitored.
"""

import re
from dataclasses import dataclass, field

# Line openers seen in real samples: "Step 1:", "Step 1.", "**Step 1:**", "**Step 1**:", "### Step 1:",
# "- Step 1:", "*Step 1:*". The final answer may also carry a step marker ("Step 6: Final answer: ...").
_OPEN = r"^[ \t]*(?:[-+>][ \t]*)?(?:#{1,6}[ \t]*)?(?:\*{1,2}|_{1,2})?[ \t]*"
_EMPH = r"[ \t]*(?:\*{1,2}|_{1,2})?[ \t]*"
STEP_RE = re.compile(r"(?im)" + _OPEN + r"Step[ \t]+(\d+)" + _EMPH + r"[:.](?:[ \t]*(?:\*{1,2}|_{1,2}))?")
FINAL_PREFIX = _OPEN + r"(?:Step[ \t]+\d+" + _EMPH + r"[:.]" + _EMPH + r")?Final answer" + _EMPH + r":"
FINAL_RE = re.compile(r"(?im)" + FINAL_PREFIX)


@dataclass
class Segmentation:
    text: str
    steps: list = field(default_factory=list)   # [(char_start, char_end)] covering [0, final_start)
    final_start: int = 0                        # start of the terminal segment
    marker_found: bool = True
    content_start: int = 0                      # first step marker (preamble excluded), as in skill_dynamics
    content_token: int = 0                      # token index of content_start (set by response_segments)

    @property
    def num_steps(self):
        return len(self.steps)

    def step_texts(self):
        return [self.text[a:b] for a, b in self.steps]

    def bounds(self):
        """Segment boundaries: steps then the terminal segment, covering the whole text."""
        return [*self.steps, (self.final_start, len(self.text))]


def segment(text):
    final = None
    for match in FINAL_RE.finditer(text):
        final = match
    stop = final.start() if final else len(text)
    body = text[:stop]
    marks = [m for m in STEP_RE.finditer(body)]
    starts = []
    for m in marks:
        if not starts or m.start() > starts[-1]:
            starts.append(m.start())
    marker_found = bool(starts)
    if not marker_found:
        # paragraphs start at their line start (with any indentation), where tokenizers put a token edge
        starts = [len(body[:m.start()].rstrip(" \t")) for m in re.finditer(r"(?s)\S.*?(?=\n[ \t]*\n|\Z)", body)]
    # Drop empty steps, merge any preamble into the first step.
    bounds = []
    for i, start in enumerate(starts):
        end = starts[i + 1] if i + 1 < len(starts) else stop
        if body[start:end].strip():
            bounds.append([start, end])
    content_start = bounds[0][0] if bounds else 0
    if bounds:
        bounds[0][0] = 0
        bounds[-1][1] = stop
    return Segmentation(text=text, steps=[tuple(b) for b in bounds], final_start=stop if bounds else 0,
                        marker_found=marker_found, content_start=content_start)


def _byte_decoder():
    # GPT-2 / tiktoken-style byte-level BPE alphabet (used by Qwen2.5 and Llama-3 tokenizers).
    bs = list(range(ord("!"), ord("~") + 1)) + list(range(ord("¡"), ord("¬") + 1)) + list(range(ord("®"), ord("ÿ") + 1))
    cs = bs[:]
    n = 0
    for b in range(256):
        if b not in bs:
            bs.append(b)
            cs.append(256 + n)
            n += 1
    return {chr(c): b for b, c in zip(bs, cs)}


_BYTE_DECODER = _byte_decoder()


def token_char_offsets(tokenizer, ids):
    """Character offset of each token boundary in decode(ids, skip_special_tokens=True,
    clean_up_tokenization_spaces=False). Returns (text, offsets) with len(offsets) == len(ids)+1."""
    text = tokenizer.decode(ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)
    special = set(getattr(tokenizer, "all_special_ids", []) or [])
    pieces = tokenizer.convert_ids_to_tokens(list(ids))
    try:
        byte_lens = []
        for tid, piece in zip(ids, pieces):
            if tid in special or piece is None:
                byte_lens.append(0)
            else:
                byte_lens.append(len(bytes(_BYTE_DECODER[ch] for ch in piece)))
        data = text.encode("utf-8")
        if sum(byte_lens) != len(data):
            raise ValueError("byte-level reconstruction mismatch")
        # Map every byte boundary to a character boundary (bytes inside a multi-byte char map
        # to the start of that char's next boundary, so spans never split a character).
        char_at_byte = [0] * (len(data) + 1)
        pos = 0
        for ci, ch in enumerate(text):
            width = len(ch.encode("utf-8"))
            for k in range(width):
                char_at_byte[pos + k] = ci if k == 0 else ci + 1
            pos += width
        char_at_byte[len(data)] = len(text)
        offsets, acc = [0], 0
        for length in byte_lens:
            acc += length
            offsets.append(char_at_byte[acc])
        return text, offsets
    except (KeyError, ValueError):
        offsets = [len(tokenizer.decode(ids[:i], skip_special_tokens=True, clean_up_tokenization_spaces=False))
                   for i in range(len(ids) + 1)]
        return text, offsets


def char_spans_to_token_spans(offsets, char_spans):
    """Map contiguous character spans to contiguous token spans [t0, t1). A token belongs to the
    span containing its first character; spans that receive no token are returned empty."""
    import bisect
    n_tokens = len(offsets) - 1
    starts = [offsets[i] for i in range(n_tokens)]
    out = []
    for a, b in char_spans:
        t0 = bisect.bisect_left(starts, a)
        t1 = bisect.bisect_left(starts, b)
        out.append((t0, t1))
    return out


def response_segments(tokenizer, ids):
    """Segmentation of a generated response plus token spans for every segment (steps + terminal).
    Tokens are assigned in order, so spans tile [0, len(ids)) exactly. Also returns the token index
    where reasoning content starts (first step marker), used by the spectral features."""
    text, offsets = token_char_offsets(tokenizer, ids)
    seg = segment(text)
    spans = char_spans_to_token_spans(offsets, seg.bounds())
    if spans:
        spans[-1] = (spans[-1][0], len(ids))
        spans = [(spans[i][0], spans[i + 1][0]) for i in range(len(spans) - 1)] + [spans[-1]]
        if spans[0][0] != 0:
            spans[0] = (0, spans[0][1])
    content_tok = char_spans_to_token_spans(offsets, [(seg.content_start, seg.content_start)])[0][0]
    if seg.num_steps:
        content_tok = min(content_tok, max(spans[0][1] - 1, 0))
    seg.content_token = content_tok
    return seg, spans