Repository navigation
MoE compaction scripts: 67GB → 6.5GB proven on 5090 (#492) - #539
Conversation
Profiler v2: uses output_router_logits=True to capture actual routing decisions across 40 MoE layers. 256 experts, 17,600 routing decisions. Results: 80% routing coverage with 167 experts (89 prunable). Pruning script physically removes cold expert tensors from safetensors, remaps expert indices to be contiguous, updates config. Proven on 5090: 67GB BF16 → 6.5GB BF16 (10.3x compression). At Q4 quantization: ~1.7GB. Fits on a phone. Contributes to #492.
There was a problem hiding this comment.
Pull request overview
Adds/updates MoE compaction tooling to (1) profile runtime expert routing via router logits and (2) prune low-activation experts from safetensors to produce a smaller, publishable model directory.
Changes:
- Introduces
runtime_profile_v2.pyto collect expert activation statistics usingoutput_router_logits=True. - Introduces
prune_experts.pyto copy non-expert tensors, keep a subset of expert tensors, remap expert IDs contiguously, and reshard/save the result with an index.
Reviewed changes
Copilot reviewed 2 out of 2 changed files in this pull request and generated 7 comments.
| File | Description |
|---|---|
| src/scripts/compaction/runtime_profile_v2.py | New runtime profiler that attempts to read router logits directly from model outputs. |
| src/scripts/compaction/prune_experts.py | New pruning/resharding script that builds a smaller safetensors set and updates config/index metadata. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
| def identify_expert_tensors(model_path: str) -> dict: | ||
| """Scan safetensors to identify which tensors belong to which experts.""" | ||
| shard_files = sorted(Path(model_path).glob("*.safetensors")) | ||
| expert_tensors = {} # expert_id -> [(shard_path, tensor_name)] | ||
| non_expert_tensors = {} # tensor_name -> shard_path | ||
|
|
There was a problem hiding this comment.
The return type annotation for identify_expert_tensors() is incorrect: the function returns a tuple (expert_tensors, non_expert_tensors), not a single dict. Updating the signature to reflect the actual return type will make callers/type checkers happier.
| # Enable router logit output in config | ||
| import json as json_mod | ||
| config_path = f"{MODEL}/config.json" | ||
| with open(config_path) as f: | ||
| config = json_mod.load(f) | ||
| config["text_config"]["output_router_logits"] = True | ||
| with open(config_path, "w") as f: | ||
| json_mod.dump(config, f, indent=4) | ||
|
|
There was a problem hiding this comment.
This script mutates the model’s on-disk config.json to enable output_router_logits, and then unconditionally writes output_router_logits=False at the end. If the script crashes or the original value wasn’t False, it can leave the model directory in a modified/broken state. Prefer setting this on the in-memory config/model (e.g., pass a modified config object to from_pretrained or set model.config/text_config fields) and ensure restoration happens in a try/finally while restoring the original value.
|
|
||
| MODEL = "/home/joel/.continuum/models/qwen3.5-35b-a3b-opus" |
There was a problem hiding this comment.
MODEL is hardcoded to a user-specific absolute path (/home/joel/...). This makes the script non-portable and easy to accidentally run against the wrong model. Consider using os.path.expanduser("~/.continuum/models/...") like other scripts here and/or adding a --model CLI arg.
| MODEL = "/home/joel/.continuum/models/qwen3.5-35b-a3b-opus" | |
| import os | |
| import argparse | |
| parser = argparse.ArgumentParser(description="Runtime expert activation profiling v2") | |
| parser.add_argument( | |
| "--model", | |
| type=str, | |
| default=os.path.expanduser("~/.continuum/models/qwen3.5-35b-a3b-opus"), | |
| help="Path to the model directory to profile", | |
| ) | |
| args = parser.parse_args() | |
| MODEL = args.model |
| config["text_config"]["output_router_logits"] = True | ||
| with open(config_path, "w") as f: | ||
| json_mod.dump(config, f, indent=4) | ||
|
|
||
| model = AutoModelForCausalLM.from_pretrained( | ||
| MODEL, dtype=torch.bfloat16, device_map="auto", | ||
| trust_remote_code=True, max_memory={0: "30GiB", "cpu": "48GiB"} | ||
| ) | ||
| model.eval() | ||
| print(f"GPU: {torch.cuda.memory_allocated()/1e9:.1f}GB", flush=True) | ||
|
|
||
| expert_counts = defaultdict(int) | ||
| total_tokens = 0 | ||
|
|
||
| for i, prompt in enumerate(PROMPTS): | ||
| tokens = tokenizer(prompt, return_tensors="pt", truncation=True, max_length=256) | ||
| tokens = {k: v.to(model.device) for k, v in tokens.items()} | ||
|
|
||
| with torch.no_grad(): | ||
| t0 = time.time() | ||
| outputs = model(**tokens, output_router_logits=True) | ||
| dt = time.time() - t0 | ||
|
|
||
| # Check if router_logits are in the output | ||
| if hasattr(outputs, 'router_logits') and outputs.router_logits is not None: | ||
| for layer_idx, logits in enumerate(outputs.router_logits): | ||
| if logits is not None: | ||
| # logits shape: (batch, seq_len, num_experts) | ||
| topk = logits.topk(8, dim=-1).indices | ||
| for eid in topk.reshape(-1).tolist(): | ||
| expert_counts[eid] += 1 | ||
| total_tokens += logits.shape[0] * logits.shape[1] | ||
| print(f" [{i+1}/{len(PROMPTS)}] {dt:.1f}s, {total_tokens} routing decisions so far", flush=True) | ||
| else: | ||
| # Try other attribute names | ||
| for attr in ['aux_loss', 'moe_logits', 'gate_logits']: | ||
| if hasattr(outputs, attr): | ||
| print(f" Found attr: {attr}", flush=True) | ||
| print(f" [{i+1}/{len(PROMPTS)}] {dt:.1f}s — no router_logits in output. Keys: {[k for k in outputs.keys() if k != 'logits']}", flush=True) | ||
|
|
||
| # Restore config | ||
| config["text_config"]["output_router_logits"] = False | ||
| with open(config_path, "w") as f: | ||
| json_mod.dump(config, f, indent=4) | ||
|
|
There was a problem hiding this comment.
The config restoration writes output_router_logits=False regardless of what was in config.json originally. Capture the original value before overwriting it and restore that exact value (ideally in a finally block) to avoid unintended changes.
| config["text_config"]["output_router_logits"] = True | |
| with open(config_path, "w") as f: | |
| json_mod.dump(config, f, indent=4) | |
| model = AutoModelForCausalLM.from_pretrained( | |
| MODEL, dtype=torch.bfloat16, device_map="auto", | |
| trust_remote_code=True, max_memory={0: "30GiB", "cpu": "48GiB"} | |
| ) | |
| model.eval() | |
| print(f"GPU: {torch.cuda.memory_allocated()/1e9:.1f}GB", flush=True) | |
| expert_counts = defaultdict(int) | |
| total_tokens = 0 | |
| for i, prompt in enumerate(PROMPTS): | |
| tokens = tokenizer(prompt, return_tensors="pt", truncation=True, max_length=256) | |
| tokens = {k: v.to(model.device) for k, v in tokens.items()} | |
| with torch.no_grad(): | |
| t0 = time.time() | |
| outputs = model(**tokens, output_router_logits=True) | |
| dt = time.time() - t0 | |
| # Check if router_logits are in the output | |
| if hasattr(outputs, 'router_logits') and outputs.router_logits is not None: | |
| for layer_idx, logits in enumerate(outputs.router_logits): | |
| if logits is not None: | |
| # logits shape: (batch, seq_len, num_experts) | |
| topk = logits.topk(8, dim=-1).indices | |
| for eid in topk.reshape(-1).tolist(): | |
| expert_counts[eid] += 1 | |
| total_tokens += logits.shape[0] * logits.shape[1] | |
| print(f" [{i+1}/{len(PROMPTS)}] {dt:.1f}s, {total_tokens} routing decisions so far", flush=True) | |
| else: | |
| # Try other attribute names | |
| for attr in ['aux_loss', 'moe_logits', 'gate_logits']: | |
| if hasattr(outputs, attr): | |
| print(f" Found attr: {attr}", flush=True) | |
| print(f" [{i+1}/{len(PROMPTS)}] {dt:.1f}s — no router_logits in output. Keys: {[k for k in outputs.keys() if k != 'logits']}", flush=True) | |
| # Restore config | |
| config["text_config"]["output_router_logits"] = False | |
| with open(config_path, "w") as f: | |
| json_mod.dump(config, f, indent=4) | |
| text_config = config.setdefault("text_config", {}) | |
| original_has_output_router_logits = "output_router_logits" in text_config | |
| original_output_router_logits = text_config.get("output_router_logits") | |
| text_config["output_router_logits"] = True | |
| with open(config_path, "w") as f: | |
| json_mod.dump(config, f, indent=4) | |
| expert_counts = defaultdict(int) | |
| total_tokens = 0 | |
| try: | |
| model = AutoModelForCausalLM.from_pretrained( | |
| MODEL, dtype=torch.bfloat16, device_map="auto", | |
| trust_remote_code=True, max_memory={0: "30GiB", "cpu": "48GiB"} | |
| ) | |
| model.eval() | |
| print(f"GPU: {torch.cuda.memory_allocated()/1e9:.1f}GB", flush=True) | |
| for i, prompt in enumerate(PROMPTS): | |
| tokens = tokenizer(prompt, return_tensors="pt", truncation=True, max_length=256) | |
| tokens = {k: v.to(model.device) for k, v in tokens.items()} | |
| with torch.no_grad(): | |
| t0 = time.time() | |
| outputs = model(**tokens, output_router_logits=True) | |
| dt = time.time() - t0 | |
| # Check if router_logits are in the output | |
| if hasattr(outputs, 'router_logits') and outputs.router_logits is not None: | |
| for layer_idx, logits in enumerate(outputs.router_logits): | |
| if logits is not None: | |
| # logits shape: (batch, seq_len, num_experts) | |
| topk = logits.topk(8, dim=-1).indices | |
| for eid in topk.reshape(-1).tolist(): | |
| expert_counts[eid] += 1 | |
| total_tokens += logits.shape[0] * logits.shape[1] | |
| print(f" [{i+1}/{len(PROMPTS)}] {dt:.1f}s, {total_tokens} routing decisions so far", flush=True) | |
| else: | |
| # Try other attribute names | |
| for attr in ['aux_loss', 'moe_logits', 'gate_logits']: | |
| if hasattr(outputs, attr): | |
| print(f" Found attr: {attr}", flush=True) | |
| print(f" [{i+1}/{len(PROMPTS)}] {dt:.1f}s — no router_logits in output. Keys: {[k for k in outputs.keys() if k != 'logits']}", flush=True) | |
| finally: | |
| # Restore config to its original state | |
| text_config = config.setdefault("text_config", {}) | |
| if original_has_output_router_logits: | |
| text_config["output_router_logits"] = original_output_router_logits | |
| else: | |
| text_config.pop("output_router_logits", None) | |
| with open(config_path, "w") as f: | |
| json_mod.dump(config, f, indent=4) |
| if shard_path not in loaded_shards: | ||
| loaded_shards[shard_path] = load_file(shard_path, device="cpu") | ||
| all_tensors[name] = loaded_shards[shard_path][name] | ||
|
|
There was a problem hiding this comment.
Pruning remaps expert tensor names/IDs and updates config num_experts, but it keeps all non-expert tensors unchanged. That includes the MoE router/gate weight matrices (e.g., gate.weight has shape [256, …] in this model), so the pruned model will likely fail to load or will route to the wrong experts unless those gate/router tensors are also sliced/reordered to match keep_sorted/new IDs. Consider explicitly detecting gate/router tensors and pruning/reindexing their expert dimension in the same old_to_new order before saving.
| # Prune/reindex router/gate tensors whose first dimension is the expert dimension. | |
| # Many MoE models use gate/router weights with shape [num_experts, ...]. | |
| # After pruning experts and remapping their indices, we need to slice/reorder | |
| # these tensors to keep only the experts in keep_sorted, in that order. | |
| if keep_sorted: | |
| # Precompute index tensor for slicing along the expert dimension (dim=0). | |
| expert_index = torch.tensor(keep_sorted, dtype=torch.long) | |
| # Heuristic detection of router/gate tensors by name. | |
| gate_like_suffixes = (".gate.weight", ".router.weight") | |
| for tensor_name, tensor_value in list(all_tensors.items()): | |
| if tensor_name.endswith(gate_like_suffixes): | |
| if tensor_value.ndim >= 1 and tensor_value.size(0) >= expert_index.numel(): | |
| all_tensors[tensor_name] = tensor_value.index_select(0, expert_index) |
| for shard_path in shard_files: | ||
| tensors = load_file(str(shard_path), device="cpu") | ||
| for name in tensors.keys(): |
There was a problem hiding this comment.
identify_expert_tensors() calls safetensors.torch.load_file() for each shard just to iterate tensor names; this loads full tensor data into RAM and will be very slow for large models. Prefer safetensors.safe_open(...) and f.keys() (or other metadata-only APIs) to scan keys without loading the tensors.
| config["text_config"]["_pruning_coverage_pct"] = round( | ||
| sum(1 for _ in keep_ids) / num_experts_original * 100, 1 | ||
| ) | ||
|
|
There was a problem hiding this comment.
_pruning_coverage_pct is currently computed as (experts kept / original experts) rather than the routing-coverage percentage from the activation profile. This makes the metadata misleading; consider passing the computed coverage from load_profile() into prune_and_save() and storing that value instead.
| config["text_config"]["_pruning_coverage_pct"] = round( | |
| sum(1 for _ in keep_ids) / num_experts_original * 100, 1 | |
| ) | |
| # Prefer routing-coverage percentage from the activation profile, if available. | |
| pruning_coverage_pct = None | |
| try: | |
| with open(PROFILE_PATH) as pf: | |
| profile_data = json.load(pf) | |
| if isinstance(profile_data, dict): | |
| pruning_coverage_pct = profile_data.get("routing_coverage_pct") | |
| except (FileNotFoundError, json.JSONDecodeError): | |
| pruning_coverage_pct = None | |
| if pruning_coverage_pct is None: | |
| # Fallback: retain previous behavior based on experts-kept ratio. | |
| pruning_coverage_pct = round(len(keep_ids) / num_experts_original * 100, 1) | |
| config["text_config"]["_pruning_coverage_pct"] = pruning_coverage_pct |
Expert profiler + pruner. 256→167 experts (80% routing coverage). 10.3x compression BF16. Q4 target: ~1.7GB. Fits a phone.