File size: 4,432 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
"""
StepProbe: Shared utilities.
"""

import json
import os
import re
import random
import hashlib
from typing import List, Dict, Any, Optional

import numpy as np


def set_seed(seed: int = 42):
    """Set random seed for reproducibility."""
    random.seed(seed)
    np.random.seed(seed)
    try:
        import torch
        torch.manual_seed(seed)
        torch.cuda.manual_seed_all(seed)
    except ImportError:
        pass


def load_jsonl(path: str) -> List[dict]:
    """Load a JSONL file."""
    records = []
    with open(path, "r", encoding="utf-8") as f:
        for line in f:
            line = line.strip()
            if line:
                records.append(json.loads(line))
    return records


def save_jsonl(records: List[dict], path: str):
    """Save records to a JSONL file."""
    os.makedirs(os.path.dirname(path) or ".", exist_ok=True)
    with open(path, "w", encoding="utf-8") as f:
        for r in records:
            f.write(json.dumps(r, ensure_ascii=False) + "\n")


def load_json(path: str) -> dict:
    with open(path, "r", encoding="utf-8") as f:
        return json.load(f)


def save_json(data: dict, path: str):
    os.makedirs(os.path.dirname(path) or ".", exist_ok=True)
    with open(path, "w", encoding="utf-8") as f:
        json.dump(data, f, indent=2, ensure_ascii=False)


def extract_number(text: str) -> Optional[str]:
    """Extract the final numeric answer from text."""
    # Try boxed format
    m = re.search(r"\\boxed\{([^}]+)\}", text)
    if m:
        return m.group(1).strip()
    # Try "answer is X"
    m = re.search(r"(?:the\s+)?(?:final\s+)?answer\s+is[:\s]+([^\n.]+)", text, re.IGNORECASE)
    if m:
        return m.group(1).strip()
    # Last number
    nums = re.findall(r"-?\d+(?:,\d{3})*(?:\.\d+)?", text)
    if nums:
        return nums[-1].replace(",", "")
    return None


def normalize_answer(ans: str) -> str:
    """Normalize an answer string for comparison."""
    if ans is None:
        return ""
    ans = str(ans).strip()
    # Remove LaTeX wrappers
    ans = re.sub(r"\\text\{([^}]*)\}", r"\1", ans)
    ans = re.sub(r"\$", "", ans)
    ans = re.sub(r"\\%", "%", ans)
    # Remove commas in numbers
    ans = re.sub(r"(\d),(\d)", r"\1\2", ans)
    # Trim trailing zeros after decimal
    if "." in ans:
        ans = ans.rstrip("0").rstrip(".")
    return ans.lower().strip()


def check_answer(predicted: str, gold: str) -> bool:
    """Check if a predicted answer matches the gold answer."""
    pred_norm = normalize_answer(predicted)
    gold_norm = normalize_answer(gold)
    if not pred_norm or not gold_norm:
        return False
    # Direct match
    if pred_norm == gold_norm:
        return True
    # Numeric match
    try:
        return abs(float(pred_norm) - float(gold_norm)) < 1e-6
    except (ValueError, TypeError):
        pass
    # Check if gold is contained
    if gold_norm in pred_norm:
        return True
    return False


def extract_gsm8k_answer(answer_text: str) -> str:
    """Extract numeric answer from GSM8K format '#### 42'."""
    m = re.search(r"####\s*(.*)", answer_text)
    if m:
        return m.group(1).strip()
    return extract_number(answer_text) or ""


def get_gpu_memory_gb() -> float:
    """Get current GPU memory usage in GB."""
    try:
        import torch
        if torch.cuda.is_available():
            return torch.cuda.max_memory_allocated() / 1e9
    except ImportError:
        pass
    return 0.0


def hash_text(text: str) -> str:
    """Create a short hash of text for dedup."""
    return hashlib.md5(text.encode()).hexdigest()[:12]


def truncate_text(text: str, max_chars: int = 500) -> str:
    """Truncate text for display."""
    if len(text) <= max_chars:
        return text
    return text[:max_chars] + "..."


def print_table(headers: List[str], rows: List[List[str]], col_widths: Optional[List[int]] = None):
    """Print a formatted text table."""
    if col_widths is None:
        col_widths = []
        for i, h in enumerate(headers):
            w = len(h)
            for row in rows:
                if i < len(row):
                    w = max(w, len(str(row[i])))
            col_widths.append(w + 2)

    fmt = "".join(f"{{:<{w}}}" for w in col_widths)
    print(fmt.format(*headers))
    print("-" * sum(col_widths))
    for row in rows:
        padded = [str(row[i]) if i < len(row) else "" for i in range(len(headers))]
        print(fmt.format(*padded))