"""utils — v8b (dense Qwen3-8B).""" import json, logging, os, sys from typing import Dict, List import numpy as np import torch def think_segment(text: str) -> str: """Return only the ... reasoning content. Same semantics as stage-00 _extract_thinking: cut at the first , strip a leading . If no is present (the model never closed the block, e.g. on collapse), the whole text is treated as the thinking segment. Used so that ALL eval-side counting (tokens, reflection markers, chars, repetition) is measured strictly inside the think block — the same object the steering direction was learned on. Answer grading still runs on the FULL output, since the boxed answer lives after . """ if "" in text: text = text.split("", 1)[0] s = text.strip() if s.startswith(""): s = s[len(""):] return s.strip() def json_safe(obj): if isinstance(obj, dict): return {json_safe(k): json_safe(v) for k, v in obj.items()} if isinstance(obj, (list, tuple)): return [json_safe(v) for v in obj] if isinstance(obj, np.integer): return int(obj) if isinstance(obj, np.floating): return float(obj) if isinstance(obj, np.bool_): return bool(obj) if isinstance(obj, np.ndarray): return obj.tolist() if isinstance(obj, torch.Tensor): return obj.tolist() return obj def write_json(obj, path: str): os.makedirs(os.path.dirname(path), exist_ok=True) with open(path, "w", encoding="utf-8") as f: json.dump(json_safe(obj), f, indent=2, ensure_ascii=False) def read_json(path: str): with open(path, "r", encoding="utf-8") as f: return json.load(f) def read_jsonl(path: str) -> List[Dict]: out = [] with open(path, "r", encoding="utf-8") as f: for line in f: line = line.strip() if line: out.append(json.loads(line)) return out def write_jsonl(items: List[Dict], path: str): os.makedirs(os.path.dirname(path), exist_ok=True) with open(path, "w", encoding="utf-8") as f: for it in items: f.write(json.dumps(json_safe(it), ensure_ascii=False) + "\n") def append_jsonl(item: Dict, path: str): os.makedirs(os.path.dirname(path), exist_ok=True) with open(path, "a", encoding="utf-8") as f: f.write(json.dumps(json_safe(item), ensure_ascii=False) + "\n") def setup_logger(name: str, log_file: str = None, level=logging.INFO): logger = logging.getLogger(name) logger.setLevel(level) logger.handlers = [] fmt = logging.Formatter( "%(asctime)s | %(levelname)-5s | %(name)s | %(message)s", datefmt="%H:%M:%S", ) ch = logging.StreamHandler(sys.stdout) ch.setLevel(level) ch.setFormatter(fmt) logger.addHandler(ch) if log_file: os.makedirs(os.path.dirname(log_file), exist_ok=True) fh = logging.FileHandler(log_file, mode="a", encoding="utf-8") fh.setLevel(level) fh.setFormatter(fmt) logger.addHandler(fh) return logger def get_device() -> str: return "cuda" if torch.cuda.is_available() else "cpu" def load_model_and_tokenizer(device: str = "cuda"): from transformers import AutoModelForCausalLM, AutoTokenizer from configs.paths import MODEL_PATH tok = AutoTokenizer.from_pretrained(MODEL_PATH, trust_remote_code=True) model = AutoModelForCausalLM.from_pretrained( MODEL_PATH, torch_dtype=torch.bfloat16, device_map=device, trust_remote_code=True, ) model.eval() return model, tok def build_chat_prompt(tokenizer, problem: str, enable_thinking: bool = True, system: str = "You are a helpful math assistant.") -> str: msgs = [ {"role": "system", "content": system}, {"role": "user", "content": problem}, ] return tokenizer.apply_chat_template( msgs, tokenize=False, add_generation_prompt=True, enable_thinking=enable_thinking, )