summaryrefslogtreecommitdiff
path: root/run_experiments.py
blob: 0cbcd67fe92a38b0ddf1d67fa38c756fa799ca68 (plain)
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
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
#!/usr/bin/env python3
# run_experiments.py
"""
Experiment Runner for RLVR Floating-Point Precision Study.

This script orchestrates the full experimental pipeline:
1. Training models with FP32 and bf16 precision across multiple seeds
2. Evaluating trained models on on-task and off-task benchmarks
3. Computing KL divergence and bf16 sparsity metrics

Usage:
    # Run full experiment
    python run_experiments.py --mode full
    
    # Run training only
    python run_experiments.py --mode train --precision_mode bf16 --seed 1
    
    # Run evaluation only
    python run_experiments.py --mode eval
    
    # Run analysis only
    python run_experiments.py --mode analyze
"""

import argparse
import json
import os
import subprocess
import sys
import logging
from typing import Dict, Any, List, Optional
from dataclasses import asdict
from concurrent.futures import ProcessPoolExecutor
import time

from config import (
    ExperimentConfig,
    make_training_config,
    make_precision_config,
    get_run_output_dir,
    get_checkpoint_path,
)

# Configure logging
logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
)
logger = logging.getLogger(__name__)


# ============================================================================
# Training Functions
# ============================================================================

def run_single_training(
    precision_mode: str,
    seed: int,
    config: ExperimentConfig,
    train_dataset_path: str,
    dry_run: bool = False
) -> Dict[str, Any]:
    """
    Run a single training job.
    
    Args:
        precision_mode: "fp32" or "bf16"
        seed: Random seed
        config: Experiment configuration
        train_dataset_path: Path to training data
        dry_run: If True, only print command without running
        
    Returns:
        Dictionary with job status
    """
    output_dir = get_run_output_dir(config.train_logs_dir, precision_mode, seed)
    
    cmd = [
        sys.executable,
        "train_rlvr.py",
        "--precision_mode", precision_mode,
        "--seed", str(seed),
        "--output_dir", output_dir,
        "--train_dataset_path", train_dataset_path,
        "--model_name", config.base_model_path,
    ]
    
    logger.info(f"Running training: {precision_mode} seed={seed}")
    logger.info(f"Command: {' '.join(cmd)}")
    
    if dry_run:
        return {
            "status": "dry_run",
            "precision_mode": precision_mode,
            "seed": seed,
            "output_dir": output_dir,
            "command": " ".join(cmd),
        }
    
    # Create output directory
    os.makedirs(output_dir, exist_ok=True)
    
    # Run training
    start_time = time.time()
    try:
        result = subprocess.run(
            cmd,
            capture_output=True,
            text=True,
            check=True
        )
        duration = time.time() - start_time
        
        return {
            "status": "success",
            "precision_mode": precision_mode,
            "seed": seed,
            "output_dir": output_dir,
            "duration_seconds": duration,
            "stdout": result.stdout[-1000:],  # Last 1000 chars
        }
    except subprocess.CalledProcessError as e:
        return {
            "status": "failed",
            "precision_mode": precision_mode,
            "seed": seed,
            "output_dir": output_dir,
            "error": str(e),
            "stderr": e.stderr[-1000:] if e.stderr else None,
        }


def run_all_training(
    config: ExperimentConfig,
    train_dataset_path: str,
    dry_run: bool = False,
    parallel: bool = False
) -> List[Dict[str, Any]]:
    """
    Run training for all precision modes and seeds.
    """
    jobs = []
    for precision_mode in config.precision_modes:
        for seed in config.seeds:
            jobs.append((precision_mode, seed))
    
    results = []
    
    if parallel and not dry_run:
        # Run in parallel (one job per GPU assumed)
        with ProcessPoolExecutor(max_workers=len(jobs)) as executor:
            futures = [
                executor.submit(
                    run_single_training,
                    pm, s, config, train_dataset_path, dry_run
                )
                for pm, s in jobs
            ]
            results = [f.result() for f in futures]
    else:
        # Run sequentially
        for precision_mode, seed in jobs:
            result = run_single_training(
                precision_mode, seed, config, train_dataset_path, dry_run
            )
            results.append(result)
    
    return results


# ============================================================================
# Evaluation Functions
# ============================================================================

def run_single_evaluation(
    precision_mode: str,
    seed: int,
    config: ExperimentConfig,
    eval_base: bool = True,
    dry_run: bool = False
) -> Dict[str, Any]:
    """
    Run evaluation for a single trained model.
    """
    run_dir = get_run_output_dir(config.train_logs_dir, precision_mode, seed)
    ft_ckpt = get_checkpoint_path(run_dir)
    output_path = os.path.join(
        config.eval_metrics_dir,
        f"{precision_mode}_seed{seed}.json"
    )
    
    cmd = [
        sys.executable,
        "eval_policy.py",
        "--base_ckpt", config.base_model_path,
        "--ft_ckpt", ft_ckpt,
        "--eval_tasks_config", config.eval_tasks_config_path,
        "--output_path", output_path,
    ]
    
    if eval_base:
        cmd.append("--eval_base")
    
    logger.info(f"Running evaluation: {precision_mode} seed={seed}")
    logger.info(f"Command: {' '.join(cmd)}")
    
    if dry_run:
        return {
            "status": "dry_run",
            "precision_mode": precision_mode,
            "seed": seed,
            "output_path": output_path,
            "command": " ".join(cmd),
        }
    
    # Create output directory
    os.makedirs(os.path.dirname(output_path), exist_ok=True)
    
    # Check if checkpoint exists
    if not os.path.exists(ft_ckpt):
        return {
            "status": "skipped",
            "precision_mode": precision_mode,
            "seed": seed,
            "reason": f"Checkpoint not found: {ft_ckpt}",
        }
    
    # Run evaluation
    start_time = time.time()
    try:
        result = subprocess.run(
            cmd,
            capture_output=True,
            text=True,
            check=True
        )
        duration = time.time() - start_time
        
        return {
            "status": "success",
            "precision_mode": precision_mode,
            "seed": seed,
            "output_path": output_path,
            "duration_seconds": duration,
        }
    except subprocess.CalledProcessError as e:
        return {
            "status": "failed",
            "precision_mode": precision_mode,
            "seed": seed,
            "error": str(e),
            "stderr": e.stderr[-1000:] if e.stderr else None,
        }


def run_all_evaluations(
    config: ExperimentConfig,
    eval_base: bool = True,
    dry_run: bool = False
) -> List[Dict[str, Any]]:
    """
    Run evaluation for all trained models.
    """
    results = []
    
    for precision_mode in config.precision_modes:
        for seed in config.seeds:
            result = run_single_evaluation(
                precision_mode, seed, config, eval_base, dry_run
            )
            results.append(result)
    
    return results


# ============================================================================
# bf16 Sparsity Analysis
# ============================================================================

def run_sparsity_analysis(
    config: ExperimentConfig,
    dry_run: bool = False
) -> List[Dict[str, Any]]:
    """
    Compute bf16 sparsity for all bf16 runs.
    """
    import torch
    from transformers import AutoModelForCausalLM
    from utils_bf16_sparsity import compute_bf16_sparsity, analyze_update_magnitudes
    
    results = []
    
    # Only analyze bf16 runs
    if "bf16" not in config.precision_modes:
        logger.info("No bf16 runs to analyze for sparsity")
        return results
    
    if dry_run:
        for seed in config.seeds:
            results.append({
                "status": "dry_run",
                "precision_mode": "bf16",
                "seed": seed,
            })
        return results
    
    # Load base model once
    logger.info(f"Loading base model: {config.base_model_path}")
    base_model = AutoModelForCausalLM.from_pretrained(
        config.base_model_path,
        torch_dtype=torch.float32,
        device_map="cpu"
    )
    
    for seed in config.seeds:
        run_dir = get_run_output_dir(config.train_logs_dir, "bf16", seed)
        ft_ckpt = get_checkpoint_path(run_dir)
        
        if not os.path.exists(ft_ckpt):
            results.append({
                "status": "skipped",
                "precision_mode": "bf16",
                "seed": seed,
                "reason": f"Checkpoint not found: {ft_ckpt}",
            })
            continue
        
        logger.info(f"Computing sparsity for bf16 seed={seed}")
        
        # Load finetuned model
        ft_model = AutoModelForCausalLM.from_pretrained(
            ft_ckpt,
            torch_dtype=torch.float32,
            device_map="cpu"
        )
        
        # Compute sparsity
        sparsity_result = compute_bf16_sparsity(
            base_model=base_model,
            finetuned_model=ft_model,
            eta=config.bf16_sparsity_eta,
            include_layer_stats=True
        )
        
        # Analyze update magnitudes
        magnitude_result = analyze_update_magnitudes(
            base_model=base_model,
            finetuned_model=ft_model
        )
        
        # Save results
        output_path = os.path.join(
            config.eval_metrics_dir,
            f"bf16_seed{seed}_sparsity.json"
        )
        os.makedirs(os.path.dirname(output_path), exist_ok=True)
        
        full_result = {
            "precision_mode": "bf16",
            "seed": seed,
            "sparsity": sparsity_result,
            "magnitudes": magnitude_result,
        }
        
        with open(output_path, "w") as f:
            # Convert layer_stats to serializable format
            serializable = {
                k: v for k, v in full_result.items()
            }
            if "layer_stats" in serializable.get("sparsity", {}):
                serializable["sparsity"]["layer_stats"] = {
                    k: {kk: vv for kk, vv in v.items() if kk != "shape"}
                    for k, v in serializable["sparsity"]["layer_stats"].items()
                }
            json.dump(serializable, f, indent=2, default=str)
        
        results.append({
            "status": "success",
            "precision_mode": "bf16",
            "seed": seed,
            "sparsity_percent": sparsity_result["sparsity_percent"],
            "output_path": output_path,
        })
        
        # Free memory
        del ft_model
    
    return results


# ============================================================================
# Main Entry Point
# ============================================================================

def parse_args() -> argparse.Namespace:
    """Parse command line arguments."""
    parser = argparse.ArgumentParser(
        description="Run RLVR floating-point precision experiments"
    )
    
    parser.add_argument(
        "--mode",
        type=str,
        default="full",
        choices=["full", "train", "eval", "analyze", "sparsity"],
        help="Execution mode"
    )
    
    # For single job mode
    parser.add_argument(
        "--precision_mode",
        type=str,
        choices=["fp32", "bf16"],
        help="Precision mode (for train mode)"
    )
    parser.add_argument(
        "--seed",
        type=int,
        help="Random seed (for train mode)"
    )
    
    # Paths
    parser.add_argument(
        "--train_dataset_path",
        type=str,
        default="./data/dm_train.json",
        help="Path to training dataset"
    )
    parser.add_argument(
        "--base_output_dir",
        type=str,
        default="./results",
        help="Base output directory"
    )
    parser.add_argument(
        "--eval_tasks_config",
        type=str,
        default="./configs/eval_tasks_config.json",
        help="Path to evaluation tasks config"
    )
    parser.add_argument(
        "--base_model",
        type=str,
        default="Qwen/Qwen2.5-Math-7B",
        help="Base model path or HuggingFace ID"
    )
    
    # Execution options
    parser.add_argument(
        "--dry_run",
        action="store_true",
        help="Print commands without executing"
    )
    parser.add_argument(
        "--parallel",
        action="store_true",
        help="Run training jobs in parallel"
    )
    parser.add_argument(
        "--seeds",
        type=int,
        nargs="+",
        default=[1, 2, 3, 4, 5],
        help="Seeds to use"
    )
    
    return parser.parse_args()


def main() -> None:
    """Main entry point."""
    args = parse_args()
    
    # Create experiment configuration
    config = ExperimentConfig(
        experiment_name="fp_precision_rlvr",
        seeds=args.seeds,
        precision_modes=["fp32", "bf16"],
        base_model_path=args.base_model,
        base_output_dir=args.base_output_dir,
        train_logs_dir=os.path.join(args.base_output_dir, "train_logs"),
        checkpoints_dir=os.path.join(args.base_output_dir, "checkpoints"),
        eval_metrics_dir=os.path.join(args.base_output_dir, "eval_metrics"),
        eval_tasks_config_path=args.eval_tasks_config,
    )
    
    # Create directories
    os.makedirs(config.train_logs_dir, exist_ok=True)
    os.makedirs(config.checkpoints_dir, exist_ok=True)
    os.makedirs(config.eval_metrics_dir, exist_ok=True)
    
    # Save experiment config
    config_path = os.path.join(args.base_output_dir, "experiment_config.json")
    with open(config_path, "w") as f:
        json.dump(asdict(config), f, indent=2)
    logger.info(f"Saved experiment config to {config_path}")
    
    # Execute based on mode
    if args.mode == "train":
        if args.precision_mode and args.seed:
            # Single training job
            result = run_single_training(
                args.precision_mode,
                args.seed,
                config,
                args.train_dataset_path,
                args.dry_run
            )
            print(json.dumps(result, indent=2))
        else:
            # All training jobs
            results = run_all_training(
                config,
                args.train_dataset_path,
                args.dry_run,
                args.parallel
            )
            print(json.dumps(results, indent=2))
    
    elif args.mode == "eval":
        results = run_all_evaluations(config, eval_base=True, dry_run=args.dry_run)
        print(json.dumps(results, indent=2))
    
    elif args.mode == "sparsity":
        results = run_sparsity_analysis(config, dry_run=args.dry_run)
        print(json.dumps(results, indent=2))
    
    elif args.mode == "analyze":
        # Run analysis script
        analyze_cmd = [
            sys.executable,
            "analyze_results.py",
            "--results_dir", config.eval_metrics_dir,
            "--output_dir", os.path.join(args.base_output_dir, "analysis"),
        ]
        if args.dry_run:
            print(f"Would run: {' '.join(analyze_cmd)}")
        else:
            subprocess.run(analyze_cmd, check=True)
    
    elif args.mode == "full":
        logger.info("="*60)
        logger.info("RUNNING FULL EXPERIMENT PIPELINE")
        logger.info("="*60)
        
        # Step 1: Training
        logger.info("\n" + "="*60)
        logger.info("STEP 1: Training")
        logger.info("="*60)
        train_results = run_all_training(
            config,
            args.train_dataset_path,
            args.dry_run,
            args.parallel
        )
        
        # Step 2: Evaluation
        logger.info("\n" + "="*60)
        logger.info("STEP 2: Evaluation")
        logger.info("="*60)
        eval_results = run_all_evaluations(config, dry_run=args.dry_run)
        
        # Step 3: Sparsity Analysis
        logger.info("\n" + "="*60)
        logger.info("STEP 3: Sparsity Analysis")
        logger.info("="*60)
        sparsity_results = run_sparsity_analysis(config, dry_run=args.dry_run)
        
        # Step 4: Results Analysis
        logger.info("\n" + "="*60)
        logger.info("STEP 4: Results Analysis")
        logger.info("="*60)
        if not args.dry_run:
            analyze_cmd = [
                sys.executable,
                "analyze_results.py",
                "--results_dir", config.eval_metrics_dir,
                "--output_dir", os.path.join(args.base_output_dir, "analysis"),
            ]
            subprocess.run(analyze_cmd, check=True)
        
        # Summary
        logger.info("\n" + "="*60)
        logger.info("EXPERIMENT COMPLETE")
        logger.info("="*60)
        
        all_results = {
            "training": train_results,
            "evaluation": eval_results,
            "sparsity": sparsity_results,
        }
        
        summary_path = os.path.join(args.base_output_dir, "experiment_summary.json")
        with open(summary_path, "w") as f:
            json.dump(all_results, f, indent=2)
        logger.info(f"Saved summary to {summary_path}")


if __name__ == "__main__":
    main()