| """ |
| Stage 00 (v8b): Generate 200 CONTRASTIVE pairs of CoTs with Qwen3-8B. |
| |
| For each math problem, generate two CoTs from the same base model using |
| two different system prompts: |
| |
| HIGH-REFLECTION: encourage verification, second-guessing, strategy |
| switching, look-back. |
| LOW-REFLECTION: discourage second-guessing; commit to the first |
| approach and only verify at the very end. |
| |
| Both CoTs go to RAW_COTS_PATH as JSONL with fields: |
| problem, high_reflection_cot, low_reflection_cot, high_full, low_full |
| |
| Resume: skip problems already in RAW_COTS_PATH; append new ones. |
| """ |
| import argparse, json, os, sys, time, random |
| sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) |
|
|
| import torch |
| from tqdm import tqdm |
| from configs.paths import MATH_SOURCE_PATH, RAW_COTS_PATH, LOG_DIR, ensure_dirs |
| from src.utils import ( |
| build_chat_prompt, get_device, load_model_and_tokenizer, |
| read_jsonl, setup_logger, |
| ) |
|
|
| N_SAMPLE = 200 |
| MAX_TOKENS = 8192 |
| SEED = 42 |
|
|
| SYSTEM_HIGH = ( |
| "You are a careful math problem solver. Think step by step. " |
| "After each major step, briefly pause and ASK YOURSELF whether the " |
| "step is correct. If you are unsure, reconsider, try a different " |
| "approach, and verify your reasoning before continuing. Cross-check " |
| "intermediate results. After you reach an answer, look back over " |
| "your whole solution and confirm it makes sense." |
| ) |
| SYSTEM_LOW = ( |
| "You are a confident math problem solver. Think step by step. " |
| "Commit to the first reasonable approach you see and follow it " |
| "through without second-guessing. Do not revisit earlier steps. " |
| "Do not consider alternative methods. State your final answer " |
| "directly at the end." |
| ) |
|
|
|
|
| def get_problem(item): |
| for k in ("problem", "question", "query", "input"): |
| if k in item and item[k]: |
| return item[k] |
| return "" |
|
|
|
|
| def _gen(model, tokenizer, system: str, problem: str, device: str, max_new: int): |
| prompt = build_chat_prompt(tokenizer, problem, |
| enable_thinking=True, system=system) |
| inp = tokenizer(prompt, return_tensors="pt", |
| truncation=True, max_length=2048).to(device) |
| with torch.no_grad(): |
| out = model.generate( |
| **inp, max_new_tokens=max_new, do_sample=False, |
| temperature=1.0, top_p=1.0, |
| pad_token_id=tokenizer.eos_token_id, |
| ) |
| full = tokenizer.decode(out[0], skip_special_tokens=True) |
| prompt_text = tokenizer.decode(inp["input_ids"][0], skip_special_tokens=True) |
| if full.startswith(prompt_text): |
| return full[len(prompt_text):] |
| return full |
|
|
|
|
| def _extract_thinking(text: str) -> str: |
| if "</think>" in text: |
| text = text[:text.index("</think>")] |
| if text.strip().startswith("<think>"): |
| text = text.strip()[len("<think>"):] |
| return text.strip() |
|
|
|
|
| def main(): |
| ap = argparse.ArgumentParser() |
| ap.add_argument("--n-sample", type=int, default=N_SAMPLE) |
| ap.add_argument("--max-tokens", type=int, default=MAX_TOKENS) |
| ap.add_argument("--seed", type=int, default=SEED) |
| ap.add_argument("--force", action="store_true") |
| args = ap.parse_args() |
|
|
| ensure_dirs("monitoring") |
| log = setup_logger("00_gen_contrastive", |
| os.path.join(LOG_DIR, "00_gen_contrastive.log")) |
| log.info("=" * 70) |
| log.info(f"Stage 00 (v8b contrastive): generate {args.n_sample} CoT PAIRS") |
| log.info(f" MATH_SOURCE_PATH = {MATH_SOURCE_PATH}") |
| log.info(f" RAW_COTS_PATH = {RAW_COTS_PATH}") |
| log.info("=" * 70) |
|
|
| if not os.path.exists(MATH_SOURCE_PATH): |
| log.error(f"source problems not found: {MATH_SOURCE_PATH}"); sys.exit(1) |
|
|
| all_items = read_jsonl(MATH_SOURCE_PATH) |
| problems = [get_problem(it) for it in all_items if get_problem(it)] |
| random.seed(args.seed) |
| sampled = random.sample(problems, min(args.n_sample, len(problems))) |
| log.info(f" sampled {len(sampled)} problems") |
|
|
| existing = {} |
| if os.path.exists(RAW_COTS_PATH) and not args.force: |
| for rec in read_jsonl(RAW_COTS_PATH): |
| p = rec.get("problem") |
| if p and rec.get("high_reflection_cot") and rec.get("low_reflection_cot"): |
| existing[p] = rec |
| log.info(f" [resume] {len(existing)} pairs already on disk") |
|
|
| todo = [p for p in sampled if p not in existing] |
| log.info(f" to generate: {len(todo)}") |
| if not todo: |
| log.info("All pairs already generated — DONE.") |
| return |
|
|
| device = get_device() |
| log.info("Loading model...") |
| model, tokenizer = load_model_and_tokenizer(device=device) |
|
|
| out_fh = open(RAW_COTS_PATH, "a", encoding="utf-8") |
| for i, prob in enumerate(tqdm(todo, desc=" generate pairs")): |
| t0 = time.time() |
| try: |
| full_hi = _gen(model, tokenizer, SYSTEM_HIGH, prob, device, args.max_tokens) |
| full_lo = _gen(model, tokenizer, SYSTEM_LOW, prob, device, args.max_tokens) |
| hi = _extract_thinking(full_hi) |
| lo = _extract_thinking(full_lo) |
| rec = { |
| "problem": prob, |
| "high_reflection_cot": hi, |
| "low_reflection_cot": lo, |
| "high_full": full_hi, |
| "low_full": full_lo, |
| "gen_time_s": time.time() - t0, |
| } |
| out_fh.write(json.dumps(rec, ensure_ascii=False) + "\n") |
| out_fh.flush() |
| log.info(f" [{i+1}/{len(todo)}] hi_len={len(hi)} lo_len={len(lo)} " |
| f"t={time.time()-t0:.0f}s") |
| except Exception as e: |
| log.warning(f" [{i+1}] failed: {e}") |
| continue |
|
|
| out_fh.close() |
| log.info(f"Saved (appended) -> {RAW_COTS_PATH}") |
| log.info("Done.") |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|