StepProbe / stepprobe /utils.py
Akiyue's picture
Add files using upload-large-folder tool
1e59964 verified
Raw
History Blame Contribute Delete
4.43 kB
"""
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))