| """ |
| Stage 01 (v8b): Capture hidden states from CONTRASTIVE CoT pairs (dense). |
| |
| Reads each pair (problem, high_reflection_cot, low_reflection_cot) from |
| RAW_COTS_PATH. For each CoT: |
| - Forward pass with output_hidden_states=True. |
| - Sample SAMPLES_PER_COT positions uniformly across the sequence. |
| - Label sampled positions 1 for high-reflection, 0 for low. |
| |
| Qwen3-8B is dense, so there is no expert routing to capture. |
| |
| Saves per-layer tensors to p.ACTIVATIONS. Resume: skip if it exists. |
| """ |
| import argparse, os, sys |
| sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) |
|
|
| import torch |
| from configs import get_config |
| from configs.paths import RAW_COTS_PATH, LOG_DIR, dim_paths, ensure_dirs |
| from src.contrastive_capture import collect_contrastive_activations |
| from src.utils import ( |
| get_device, load_model_and_tokenizer, read_jsonl, setup_logger, |
| ) |
|
|
|
|
| def main(): |
| ap = argparse.ArgumentParser() |
| ap.add_argument("--dimension", default="monitoring") |
| ap.add_argument("--n-train", type=int, default=None) |
| ap.add_argument("--samples-per-cot", type=int, default=None) |
| ap.add_argument("--max-seq-len", type=int, default=None) |
| ap.add_argument("--force", action="store_true") |
| args = ap.parse_args() |
|
|
| ensure_dirs(args.dimension) |
| cfg = get_config(args.dimension) |
| p = dim_paths(args.dimension) |
| n_train = args.n_train or cfg.N_TRAIN_COTS |
| samples_per_cot = args.samples_per_cot or cfg.SAMPLES_PER_COT |
| max_seq_len = args.max_seq_len or cfg.MAX_SEQ_LEN_FOR_CAPTURE |
|
|
| log = setup_logger("01_capture", os.path.join(LOG_DIR, f"01_capture_{cfg.NAME}.log")) |
| log.info("=" * 70) |
| log.info(f"Stage 01 [{cfg.NAME}] (v8b dense capture)") |
| log.info(f" RAW_COTS_PATH = {RAW_COTS_PATH}") |
| log.info(f" n_train = {n_train}") |
| log.info(f" samples_per_cot = {samples_per_cot}") |
| log.info(f" max_seq_len = {max_seq_len}") |
| log.info(f" TARGET_LAYERS = {cfg.TARGET_LAYERS}") |
| log.info("=" * 70) |
|
|
| if os.path.exists(p.ACTIVATIONS) and not args.force: |
| try: |
| blob = torch.load(p.ACTIVATIONS, map_location="cpu", weights_only=False) |
| log.info(f" [resume] {p.ACTIVATIONS} exists " |
| f"({len(blob.get('per_layer', {}))} layers) — SKIP. " |
| f"Use --force to recompute.") |
| return |
| except Exception as e: |
| log.warning(f" [resume] unreadable ({e}); recomputing") |
|
|
| if not os.path.exists(RAW_COTS_PATH): |
| log.error(f"raw_cots not found: {RAW_COTS_PATH}. Run stage 00 first.") |
| sys.exit(1) |
|
|
| raw = read_jsonl(RAW_COTS_PATH) |
| pairs = [r for r in raw |
| if r.get("high_reflection_cot") and r.get("low_reflection_cot")][:n_train] |
| log.info(f" loaded {len(pairs)} contrastive pairs") |
| if len(pairs) < 10: |
| log.error("Too few pairs to learn a stable direction; aborting.") |
| sys.exit(2) |
|
|
| device = get_device() |
| log.info("Loading model...") |
| model, tokenizer = load_model_and_tokenizer(device=device) |
|
|
| log.info("Capturing contrastive activations...") |
| per_layer, stats = collect_contrastive_activations( |
| model, tokenizer, pairs, cfg.TARGET_LAYERS, device, |
| samples_per_cot=samples_per_cot, |
| max_seq_len=max_seq_len, |
| skip_head=16, logger=log, |
| ) |
| log.info(f" pos={stats['pos']}, neg={stats['neg']}") |
| if stats["pos"] < 100 or stats["neg"] < 100: |
| log.warning("Very few captured positions; signal may be weak.") |
|
|
| save = { |
| "dimension": cfg.NAME, |
| "stats": stats, |
| "n_pairs": len(pairs), |
| "target_layers": cfg.TARGET_LAYERS, |
| "samples_per_cot": samples_per_cot, |
| "per_layer": { |
| int(L): { |
| "acts": per_layer[L]["acts"], |
| "labels": per_layer[L]["labels"], |
| } |
| for L in per_layer |
| }, |
| } |
| tmp = p.ACTIVATIONS + ".tmp" |
| torch.save(save, tmp) |
| os.replace(tmp, p.ACTIVATIONS) |
| log.info(f"Saved {p.ACTIVATIONS}. Done.") |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|