| """Regex-step activation capture — v8b, 32B-like mode. |
| |
| This is closer to the QwQ-32B regex route: |
| |
| regex is NOT the token label itself. |
| regex only locates reflection steps. |
| Positive tokens are sampled from the whole regex-hit step/segment. |
| Negative tokens are sampled from clean non-reflection steps/segments. |
| |
| Compared with marker-token mode: |
| old 8B: positive = regex marker token +/- window, negative = non-marker token, 1:1 |
| this: positive = reflection-step all-token sample, negative = non-reflection-step all-token sample, default 1:2 |
| |
| The function signature is unchanged, so scripts/01/02/03 do not need structural edits. |
| """ |
| from typing import Dict, List, Tuple |
| import os |
| import re |
| import torch |
| from tqdm import tqdm |
|
|
|
|
| def _sample_even(xs: List[int], n: int) -> List[int]: |
| if n <= 0 or not xs: |
| return [] |
| if len(xs) <= n: |
| return list(xs) |
| step = len(xs) / float(n) |
| return [xs[min(len(xs) - 1, int(i * step))] for i in range(n)] |
|
|
|
|
| def _merge_ranges(ranges): |
| if not ranges: |
| return [] |
| ranges = sorted((int(a), int(b)) for a, b in ranges if int(b) > int(a)) |
| merged = [] |
| for a, b in ranges: |
| if not merged or a > merged[-1][1]: |
| merged.append([a, b]) |
| else: |
| merged[-1][1] = max(merged[-1][1], b) |
| return [(a, b) for a, b in merged] |
|
|
|
|
| def _overlap(a, b, c, d): |
| return a < d and c < b |
|
|
|
|
| def _in_any_range(a, b, ranges): |
| for c, d in ranges: |
| if _overlap(a, b, c, d): |
| return True |
| return False |
|
|
|
|
| def _expand_hit_to_step(text: str, start: int, end: int, |
| left_chars: int = 420, |
| right_chars: int = 780): |
| """Expand regex hit to a local reasoning step. |
| |
| Boundary priority: |
| 1. nearby newline / paragraph boundary |
| 2. nearby sentence punctuation |
| 3. char-window fallback |
| |
| This avoids capturing only 'wait'/'maybe' tokens, while also avoiding |
| whole-CoT capture that would OOM. |
| """ |
| n = len(text) |
| start = max(0, min(start, n)) |
| end = max(start, min(end, n)) |
|
|
| left_floor = max(0, start - left_chars) |
| right_ceil = min(n, end + right_chars) |
|
|
| |
| left_candidates = [left_floor] |
| for pat in [r"\n\s*\n", r"\n", r"(?<=[\.\!\?。!?])\s+"]: |
| last = None |
| for m in re.finditer(pat, text[left_floor:start]): |
| last = m |
| if last is not None: |
| left_candidates.append(left_floor + last.end()) |
| seg_start = max(left_candidates) |
|
|
| |
| right_candidates = [right_ceil] |
| suffix = text[end:right_ceil] |
| for pat in [r"\n\s*\n", r"\n", r"(?<=[\.\!\?。!?])\s+"]: |
| m = re.search(pat, suffix) |
| if m is not None: |
| right_candidates.append(end + m.end()) |
| seg_end = min(right_candidates) |
|
|
| if seg_end <= seg_start: |
| seg_start, seg_end = left_floor, right_ceil |
| return seg_start, seg_end |
|
|
|
|
| def _basic_segments(text: str, max_len: int = 900): |
| """Return coarse line/sentence segments for negative sampling.""" |
| segs = [] |
| n = len(text) |
| i = 0 |
| while i < n: |
| |
| while i < n and text[i].isspace(): |
| i += 1 |
| if i >= n: |
| break |
|
|
| |
| j_new = text.find("\n", i) |
| if j_new == -1: |
| j_new = n |
|
|
| chunk_start, chunk_end = i, j_new |
| |
| if chunk_end - chunk_start <= max_len: |
| segs.append((chunk_start, chunk_end)) |
| else: |
| k = chunk_start |
| while k < chunk_end: |
| sub_end = min(chunk_end, k + max_len) |
| window = text[k:sub_end] |
| |
| cut = None |
| for m in re.finditer(r"[\.\!\?。!?]\s+", window): |
| cut = m.end() |
| if cut is not None and k + cut > k + 40: |
| sub_end = k + cut |
| segs.append((k, sub_end)) |
| k = sub_end |
|
|
| i = j_new + 1 |
|
|
| return [(a, b) for a, b in segs if b > a] |
|
|
|
|
| def _token_positions_by_ranges(offsets, ranges, skip_head: int): |
| pos = [] |
| for i, off in enumerate(offsets): |
| if i < skip_head: |
| continue |
| if off is None: |
| continue |
| try: |
| a, b = int(off[0]), int(off[1]) |
| except Exception: |
| continue |
| if b <= a: |
| continue |
| if _in_any_range(a, b, ranges): |
| pos.append(i) |
| return pos |
|
|
|
|
| def collect_contrastive_activations( |
| model, tokenizer, pairs: List[dict], layers: List[int], device: str, |
| samples_per_cot: int = 64, max_seq_len: int = 4096, |
| skip_head: int = 16, logger=None, |
| ) -> Tuple[Dict[int, Dict[str, torch.Tensor]], Dict[str, int]]: |
| from configs import get_config |
| from src.detectors import BehaviorDetector |
| from src.utils import think_segment |
|
|
| cfg = get_config("monitoring") |
| detector = BehaviorDetector(cfg) |
|
|
| |
| |
| |
| pos_per_cot = int(os.environ.get("REGEX_POS_PER_COT", str(samples_per_cot))) |
| neg_multiplier = float(os.environ.get("REGEX_NEG_MULTIPLIER", "2.0")) |
| step_left = int(os.environ.get("REGEX_STEP_LEFT_CHARS", "420")) |
| step_right = int(os.environ.get("REGEX_STEP_RIGHT_CHARS", "780")) |
| max_segment_len = int(os.environ.get("REGEX_MAX_SEGMENT_CHARS", "900")) |
|
|
| model.eval() |
| per_layer_acts = {L: [] for L in layers} |
| per_layer_labels = {L: [] for L in layers} |
|
|
| total_pos = 0 |
| total_neg = 0 |
| total_pos_all = 0 |
| total_neg_all = 0 |
| texts_seen = 0 |
| texts_used = 0 |
| skipped_no_regex = 0 |
| skipped_no_negative = 0 |
|
|
| if logger: |
| logger.info(" regex capture mode = 32B-like step/segment all-token") |
| logger.info(f" REGEX_POS_PER_COT = {pos_per_cot}") |
| logger.info(f" REGEX_NEG_MULTIPLIER = {neg_multiplier}") |
| logger.info(f" step expansion chars = left {step_left}, right {step_right}") |
| logger.info(f" max negative segment chars = {max_segment_len}") |
|
|
| def _forward_one(text: str): |
| nonlocal total_pos, total_neg, total_pos_all, total_neg_all |
| nonlocal texts_seen, texts_used, skipped_no_regex, skipped_no_negative |
|
|
| text = think_segment(text or "") |
| if not text: |
| return |
| texts_seen += 1 |
|
|
| det = detector.detect(text) |
| spans = det.get("spans", []) |
| if not spans: |
| skipped_no_regex += 1 |
| return |
|
|
| |
| pos_ranges = [] |
| for sp in spans: |
| s, e = int(sp.get("start", -1)), int(sp.get("end", -1)) |
| if s >= 0 and e > s: |
| pos_ranges.append( |
| _expand_hit_to_step( |
| text, s, e, |
| left_chars=step_left, |
| right_chars=step_right, |
| ) |
| ) |
| pos_ranges = _merge_ranges(pos_ranges) |
| if not pos_ranges: |
| skipped_no_regex += 1 |
| return |
|
|
| |
| neg_ranges = [] |
| for a, b in _basic_segments(text, max_len=max_segment_len): |
| if not _in_any_range(a, b, pos_ranges): |
| neg_ranges.append((a, b)) |
| neg_ranges = _merge_ranges(neg_ranges) |
|
|
| try: |
| enc = tokenizer( |
| text, |
| return_tensors=None, |
| add_special_tokens=False, |
| truncation=True, |
| max_length=max_seq_len, |
| return_offsets_mapping=True, |
| ) |
| ids = enc["input_ids"] |
| offsets = enc.get("offset_mapping") |
| except TypeError: |
| |
| |
| return |
|
|
| if offsets is None or len(ids) < skip_head + 4: |
| return |
|
|
| pos_all = _token_positions_by_ranges(offsets, pos_ranges, skip_head) |
| neg_all = _token_positions_by_ranges(offsets, neg_ranges, skip_head) |
|
|
| if not pos_all: |
| skipped_no_regex += 1 |
| return |
| if not neg_all: |
| skipped_no_negative += 1 |
| return |
|
|
| pos = _sample_even(pos_all, pos_per_cot) |
| neg_cap = max(1, int(round(len(pos) * neg_multiplier))) |
| neg = _sample_even(neg_all, neg_cap) |
|
|
| if not pos or not neg: |
| return |
|
|
| positions = pos + neg |
| labels = torch.tensor([1] * len(pos) + [0] * len(neg), dtype=torch.long) |
|
|
| input_ids = torch.tensor([ids], device=device) |
| with torch.no_grad(): |
| outputs = model(input_ids, output_hidden_states=True) |
|
|
| for L in layers: |
| if L + 1 >= len(outputs.hidden_states): |
| continue |
| hs = outputs.hidden_states[L + 1][0].float().cpu() |
| per_layer_acts[L].append(hs[positions]) |
| per_layer_labels[L].append(labels) |
|
|
| total_pos += len(pos) |
| total_neg += len(neg) |
| total_pos_all += len(pos_all) |
| total_neg_all += len(neg_all) |
| texts_used += 1 |
|
|
| for pair in tqdm(pairs, desc=" Regex-step capture"): |
| |
| _forward_one(pair.get("high_reflection_cot") or pair.get("cot") or pair.get("text") or "") |
| _forward_one(pair.get("low_reflection_cot") or "") |
|
|
| out = {} |
| for L in layers: |
| if not per_layer_acts[L]: |
| continue |
| out[L] = { |
| "acts": torch.cat(per_layer_acts[L], dim=0), |
| "labels": torch.cat(per_layer_labels[L], dim=0), |
| } |
| if logger: |
| labels = out[L]["labels"] |
| logger.info( |
| f" L{L:>2}: captured {labels.numel()} step tokens " |
| f"(+:{int((labels == 1).sum())} -:{int((labels == 0).sum())})" |
| ) |
|
|
| return out, { |
| "pos": int(total_pos), |
| "neg": int(total_neg), |
| "pos_all_before_sampling": int(total_pos_all), |
| "neg_all_before_sampling": int(total_neg_all), |
| "texts_seen": int(texts_seen), |
| "texts_used": int(texts_used), |
| "texts_skipped_no_regex": int(skipped_no_regex), |
| "texts_skipped_no_negative": int(skipped_no_negative), |
| "label_source": "32b_like_regex_step_segment_all_token_sampling", |
| "pos_per_cot": int(pos_per_cot), |
| "neg_multiplier": float(neg_multiplier), |
| "step_left_chars": int(step_left), |
| "step_right_chars": int(step_right), |
| } |
|
|