0xSero commited on
Commit
9a56869
·
verified ·
1 Parent(s): e638e51

Upload folder using huggingface_hub

Browse files
Files changed (2) hide show
  1. scripts/run_autoround.py +95 -0
  2. scripts/run_reap.py +115 -0
scripts/run_autoround.py ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ AutoRound W4A16 Quantization for GLM-4.7 REAP models
4
+
5
+ This script quantizes a REAP-pruned GLM-4.7 model to INT4 weights using Intel's AutoRound.
6
+ Reduces model size by ~4x while maintaining quality.
7
+
8
+ Requirements:
9
+ pip install auto-round
10
+
11
+ Usage:
12
+ python run_autoround.py --model-path ./GLM-4.7-REAP-50 --output-dir ./GLM-4.7-REAP-50-W4A16
13
+ """
14
+
15
+ import argparse
16
+ import subprocess
17
+ import sys
18
+ from pathlib import Path
19
+
20
+
21
+ def main():
22
+ parser = argparse.ArgumentParser(description="AutoRound W4A16 quantization")
23
+ parser.add_argument("--model-path", type=str, required=True,
24
+ help="Path to REAP-pruned model")
25
+ parser.add_argument("--output-dir", type=str, default=None,
26
+ help="Output directory (default: {model-path}-W4A16)")
27
+ parser.add_argument("--bits", type=int, default=4,
28
+ help="Weight bit width (default: 4)")
29
+ parser.add_argument("--group-size", type=int, default=128,
30
+ help="Quantization group size (default: 128)")
31
+ parser.add_argument("--format", type=str, default="auto_gptq",
32
+ choices=["auto_gptq", "auto_awq", "auto_round"],
33
+ help="Output format (default: auto_gptq)")
34
+ parser.add_argument("--iters", type=int, default=200,
35
+ help="Optimization iterations (default: 200)")
36
+
37
+ args = parser.parse_args()
38
+
39
+ # Validate
40
+ if not Path(args.model_path).exists():
41
+ print(f"ERROR: Model path not found: {args.model_path}")
42
+ sys.exit(1)
43
+
44
+ # Build output directory
45
+ if args.output_dir is None:
46
+ args.output_dir = f"{args.model_path}-W{args.bits}A16"
47
+
48
+ Path(args.output_dir).mkdir(parents=True, exist_ok=True)
49
+
50
+ # Get model size info
51
+ model_size_gb = sum(f.stat().st_size for f in Path(args.model_path).rglob("*.safetensors")) / (1024**3)
52
+ expected_output_gb = model_size_gb / 4 # ~4x compression for W4
53
+
54
+ print("=" * 60)
55
+ print(f"AutoRound W{args.bits}A16 Quantization")
56
+ print("=" * 60)
57
+ print(f"Input Model: {args.model_path}")
58
+ print(f"Input Size: {model_size_gb:.1f} GB")
59
+ print(f"Output: {args.output_dir}")
60
+ print(f"Expected Output Size: ~{expected_output_gb:.1f} GB")
61
+ print(f"Config: {args.bits}-bit, group_size={args.group_size}, format={args.format}")
62
+ print("=" * 60)
63
+ print("\nThis will take ~2-3 hours for a 92-layer MoE model...")
64
+ print()
65
+
66
+ # Build command
67
+ cmd = [
68
+ "auto-round",
69
+ "--model", args.model_path,
70
+ "--bits", str(args.bits),
71
+ "--group_size", str(args.group_size),
72
+ "--format", args.format,
73
+ "--output_dir", args.output_dir,
74
+ "--iters", str(args.iters),
75
+ ]
76
+
77
+ result = subprocess.run(cmd)
78
+
79
+ if result.returncode == 0:
80
+ # Calculate actual output size
81
+ output_size_gb = sum(f.stat().st_size for f in Path(args.output_dir).rglob("*.safetensors")) / (1024**3)
82
+ compression = model_size_gb / output_size_gb if output_size_gb > 0 else 0
83
+
84
+ print("\n" + "=" * 60)
85
+ print("AutoRound quantization complete!")
86
+ print(f"Output: {args.output_dir}")
87
+ print(f"Output Size: {output_size_gb:.1f} GB ({compression:.1f}x compression)")
88
+ print("=" * 60)
89
+ else:
90
+ print(f"\nERROR: AutoRound failed with code {result.returncode}")
91
+ sys.exit(1)
92
+
93
+
94
+ if __name__ == "__main__":
95
+ main()
scripts/run_reap.py ADDED
@@ -0,0 +1,115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ REAP (Router-Experts Activation Pruning) for GLM-4.7 MoE
4
+
5
+ This script prunes MoE experts from GLM-4.7 using the REAP methodology from Cerebras.
6
+ Requires: https://github.com/Cerebras/reap (or fork with GLM support)
7
+
8
+ Usage:
9
+ python run_reap.py --compression-ratio 0.50 --model-path /path/to/GLM-4.7
10
+
11
+ For observation reuse (instant pruning at different ratios):
12
+ python run_reap.py --compression-ratio 0.35 --reuse-observations observations_1360_angular-seed_42.pt
13
+ """
14
+
15
+ import argparse
16
+ import subprocess
17
+ import sys
18
+ from pathlib import Path
19
+
20
+
21
+ def main():
22
+ parser = argparse.ArgumentParser(description="REAP pruning for GLM-4.7")
23
+ parser.add_argument("--model-path", type=str, required=True,
24
+ help="Path to GLM-4.7 model")
25
+ parser.add_argument("--compression-ratio", type=float, required=True,
26
+ help="Compression ratio (0.30 = keep 70%, 0.50 = keep 50%)")
27
+ parser.add_argument("--output-dir", type=str, default=None,
28
+ help="Output directory (default: auto-generated)")
29
+ parser.add_argument("--dataset", type=str,
30
+ default="0xSero/glm47-reap-calibration-v2",
31
+ help="Calibration dataset")
32
+ parser.add_argument("--samples", type=int, default=1360,
33
+ help="Number of calibration samples")
34
+ parser.add_argument("--seed", type=int, default=42,
35
+ help="Random seed")
36
+ parser.add_argument("--distance", type=str, default="angular",
37
+ choices=["angular", "cosine", "euclidean"],
38
+ help="Distance measure for expert clustering")
39
+ parser.add_argument("--reuse-observations", type=str, default=None,
40
+ help="Path to pre-computed observations file for instant pruning")
41
+ parser.add_argument("--reap-repo", type=str, default="./reap",
42
+ help="Path to REAP repository")
43
+
44
+ args = parser.parse_args()
45
+
46
+ # Validate
47
+ if not Path(args.model_path).exists():
48
+ print(f"ERROR: Model path not found: {args.model_path}")
49
+ sys.exit(1)
50
+
51
+ reap_script = Path(args.reap_repo) / "src" / "reap" / "prune.py"
52
+ if not reap_script.exists():
53
+ print(f"ERROR: REAP prune.py not found at: {reap_script}")
54
+ print("Clone the REAP repo: git clone https://github.com/Cerebras/reap")
55
+ sys.exit(1)
56
+
57
+ # Build output directory name
58
+ if args.output_dir is None:
59
+ ratio_pct = int(args.compression_ratio * 100)
60
+ args.output_dir = f"./GLM-4.7-REAP-{ratio_pct}"
61
+
62
+ Path(args.output_dir).mkdir(parents=True, exist_ok=True)
63
+
64
+ # Build command
65
+ cmd = [
66
+ sys.executable, str(reap_script),
67
+ "--model-name", args.model_path,
68
+ "--dataset-name", args.dataset,
69
+ "--compression-ratio", str(args.compression_ratio),
70
+ "--prune-method", "reap",
71
+ "--seed", str(args.seed),
72
+ "--do-eval", "false",
73
+ "--profile", "false",
74
+ "--samples_per_category", str(args.samples),
75
+ "--model_max_length", "2048",
76
+ "--distance_measure", args.distance,
77
+ "--record_pruning_metrics_only", "true",
78
+ "--output_file_name", f"observations_{args.samples}_{args.distance}-seed_{args.seed}.pt",
79
+ ]
80
+
81
+ if args.reuse_observations:
82
+ cmd.extend(["--load_observations", args.reuse_observations])
83
+ print(f"Reusing observations from: {args.reuse_observations}")
84
+ print("This enables instant pruning without re-running calibration!")
85
+
86
+ print("=" * 60)
87
+ print(f"REAP Pruning: GLM-4.7 @ {args.compression_ratio*100:.0f}% compression")
88
+ print("=" * 60)
89
+ print(f"Model: {args.model_path}")
90
+ print(f"Output: {args.output_dir}")
91
+ print(f"Dataset: {args.dataset} ({args.samples} samples)")
92
+ print(f"Distance: {args.distance}")
93
+ print("=" * 60)
94
+
95
+ # Run REAP
96
+ env = {
97
+ **dict(__import__('os').environ),
98
+ "CUDA_VISIBLE_DEVICES": "0,1,2,3,4,5,6,7",
99
+ "PYTORCH_CUDA_ALLOC_CONF": "expandable_segments:True",
100
+ }
101
+
102
+ result = subprocess.run(cmd, env=env)
103
+
104
+ if result.returncode == 0:
105
+ print("\n" + "=" * 60)
106
+ print("REAP pruning complete!")
107
+ print(f"Pruned model saved to: {args.output_dir}")
108
+ print("=" * 60)
109
+ else:
110
+ print(f"\nERROR: REAP failed with code {result.returncode}")
111
+ sys.exit(1)
112
+
113
+
114
+ if __name__ == "__main__":
115
+ main()