Skip to content

MoE compaction scripts: 67GB → 6.5GB proven on 5090 (#492) - #539

Merged
joelteply merged 1 commit into
mainfrom
feature/compaction-scripts-v2
Mar 26, 2026
Merged

joelteply merged 1 commit into
mainfrom
feature/compaction-scripts-v2

Conversation

@joelteply

Copy link
Copy Markdown
Contributor

Expert profiler + pruner. 256→167 experts (80% routing coverage). 10.3x compression BF16. Q4 target: ~1.7GB. Fits a phone.

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.
Copilot AI review requested due to automatic review settings March 26, 2026 19:50
@joelteply
joelteply merged commit 546b590 into main Mar 26, 2026
@joelteply
joelteply deleted the feature/compaction-scripts-v2 branch March 26, 2026 19:50

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.py to collect expert activation statistics using output_router_logits=True.
  • Introduces prune_experts.py to 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.

Comment on lines +48 to +53
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

Copilot AI Mar 26, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copilot uses AI. Check for mistakes.
Comment on lines +23 to +31
# 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)

Copilot AI Mar 26, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copilot uses AI. Check for mistakes.
Comment on lines +7 to +8

MODEL = "/home/joel/.continuum/models/qwen3.5-35b-a3b-opus"

Copilot AI Mar 26, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Suggested change
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

Copilot uses AI. Check for mistakes.
Comment on lines +28 to +72
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)

Copilot AI Mar 26, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Suggested change
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)

Copilot uses AI. Check for mistakes.
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]

Copilot AI Mar 26, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Suggested change
# 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)

Copilot uses AI. Check for mistakes.
Comment on lines +54 to +56
for shard_path in shard_files:
tensors = load_file(str(shard_path), device="cpu")
for name in tensors.keys():

Copilot AI Mar 26, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copilot uses AI. Check for mistakes.
Comment on lines +196 to +199
config["text_config"]["_pruning_coverage_pct"] = round(
sum(1 for _ in keep_ids) / num_experts_original * 100, 1
)

Copilot AI Mar 26, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

_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.

Suggested change
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

Copilot uses AI. Check for mistakes.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants