mcy98's picture
Upload folder using huggingface_hub
d7ff85b verified
Raw History Blame Contribute Delete
22.9 kB
import unittest
import copy
import torch
import torch.nn as nn
import canonical as C
import generated as G
# -----------------------
# Minimal helper layers/blocks (unchanged)
# -----------------------
class SimpleRMSNorm(nn.Module):
"""RMSNorm-like mock: only has a 1D weight parameter."""
def __init__(self, dim):
super().__init__()
self.weight = nn.Parameter(torch.linspace(0.1, 1.0, steps=dim))
class MiniMHA(nn.Module):
"""
Minimal multi-head attention mock:
q_proj/k_proj/v_proj: Linear(hidden->hidden)
o_proj: Linear(hidden->hidden)
attributes: num_heads, hidden_size
Pruning semantics align with canonical/generation HFAttentionPrunner.prune_out_channels
"""
def __init__(self, hidden_size=8, num_heads=4, bias=True):
super().__init__()
assert hidden_size % num_heads == 0
self.hidden_size = hidden_size
self.num_heads = num_heads
self.q_proj = nn.Linear(hidden_size, hidden_size, bias=bias)
self.k_proj = nn.Linear(hidden_size, hidden_size, bias=bias)
self.v_proj = nn.Linear(hidden_size, hidden_size, bias=bias)
self.o_proj = nn.Linear(hidden_size, hidden_size, bias=bias)
def tensors_allclose(a: torch.Tensor, b: torch.Tensor, rtol=1e-6, atol=1e-8) -> bool:
return torch.allclose(a, b, rtol=rtol, atol=atol)
# -----------------------
# Adapter helpers (unchanged)
# -----------------------
def adapt_prune_norm_channels(mod, layer_object, indices_to_prune):
return mod.hf_rmsnorm_pruner.prune_out_channels(layer_object, indices_to_prune)
def adapt_prune_attention_channels(mod, attention_block_object, indices_to_prune):
return mod.hf_attention_pruner.prune_out_channels(attention_block_object, indices_to_prune)
def adapt_prune_linear_out_channels(mod, linear_layer_object, indices_to_prune):
return mod.hf_linear_pruner.prune_out_channels(linear_layer_object, indices_to_prune)
def adapt_prune_linear_in_channels(mod, linear_layer_object, indices_to_prune):
return mod.hf_linear_pruner.prune_in_channels(linear_layer_object, indices_to_prune)
class _DummyTarget:
def __init__(self, module):
self.module = module
class _DummyDep:
def __init__(self, module, handler):
self.target = _DummyTarget(module)
self.handler = handler
def _build_group_for_linear_out(mod, layer, indices):
return [(_DummyDep(layer, mod.hf_linear_pruner.prune_out_channels), indices)]
def _build_group_for_linear_in(mod, layer, indices):
return [(_DummyDep(layer, mod.hf_linear_pruner.prune_in_channels), indices)]
def _build_group_for_norm(mod, norm_layer, indices):
return [(_DummyDep(norm_layer, mod.hf_rmsnorm_pruner.prune_out_channels), indices)]
def _build_group_for_attention(mod, attn_block, indices):
return [(_DummyDep(attn_block, mod.hf_attention_pruner.prune_out_channels), indices)]
def adapt_calculate_magnitude_importance(mod, group_list, p=2, reduction_strategy="sum"):
"""
group_list: List[(layer_object, indices)]
"""
converted = []
for layer, indices in group_list:
if isinstance(layer, SimpleRMSNorm):
converted += _build_group_for_norm(mod, layer, indices)
elif isinstance(layer, MiniMHA):
converted += _build_group_for_attention(mod, layer, indices)
elif isinstance(layer, nn.Linear):
converted += _build_group_for_linear_out(mod, layer, indices)
else:
converted += _build_group_for_linear_out(mod, layer, indices)
imp = mod.MagnitudeImportance(p=p, group_reduction=reduction_strategy)
scores = imp(group=converted)
return scores.detach().cpu() if isinstance(scores, torch.Tensor) else torch.as_tensor(scores)
def adapt_calculate_taylor_importance(mod, group_list, reduction_strategy="sum", taylor_mode="vectorize"):
converted = []
for layer, indices in group_list:
if isinstance(layer, SimpleRMSNorm):
converted += _build_group_for_norm(mod, layer, indices)
elif isinstance(layer, MiniMHA):
converted += _build_group_for_attention(mod, layer, indices)
elif isinstance(layer, nn.Linear):
converted += _build_group_for_linear_out(mod, layer, indices)
else:
converted += _build_group_for_linear_out(mod, layer, indices)
imp = mod.TaylorImportance(group_reduction=reduction_strategy, taylor=taylor_mode)
scores = imp(group=converted)
return scores.detach().cpu() if isinstance(scores, torch.Tensor) else torch.as_tensor(scores)
# -----------------------
# Expanded Test Suite (revised for >80% coverage)
# -----------------------
class TestLLMPrunerFunctionalEquivalence(unittest.TestCase):
def setUp(self):
torch.manual_seed(0)
# ---------- RMSNorm ----------
def test_prune_norm_channels_equivalence(self):
dim = 10
indices = [1, 3, 7]
base = SimpleRMSNorm(dim)
can_obj = copy.deepcopy(base)
gen_obj = copy.deepcopy(base)
can_out = adapt_prune_norm_channels(C, can_obj, indices)
gen_out = adapt_prune_norm_channels(G, gen_obj, indices)
self.assertEqual(can_out.weight.shape, gen_out.weight.shape)
self.assertTrue(tensors_allclose(can_out.weight, gen_out.weight))
# get_in/out_channels equivalence
self.assertEqual(C.hf_rmsnorm_pruner.get_out_channels(can_out), G.hf_rmsnorm_pruner.get_out_channels(gen_out))
self.assertEqual(C.hf_rmsnorm_pruner.get_in_channels(can_out), G.hf_rmsnorm_pruner.get_in_channels(gen_out))
def test_prune_norm_channels_noop(self):
dim = 6
indices = []
base = SimpleRMSNorm(dim)
can_obj = copy.deepcopy(base)
gen_obj = copy.deepcopy(base)
can_out = adapt_prune_norm_channels(C, can_obj, indices)
gen_out = adapt_prune_norm_channels(G, gen_obj, indices)
self.assertEqual(can_out.weight.shape[0], dim)
self.assertEqual(gen_out.weight.shape[0], dim)
self.assertTrue(tensors_allclose(can_out.weight, gen_out.weight))
self.assertEqual(can_out.weight.dtype, gen_out.weight.dtype)
def test_prune_norm_channels_full(self):
dim = 5
indices = list(range(dim)) # full prune
base = SimpleRMSNorm(dim)
can_obj = copy.deepcopy(base)
gen_obj = copy.deepcopy(base)
can_out = adapt_prune_norm_channels(C, can_obj, indices)
gen_out = adapt_prune_norm_channels(G, gen_obj, indices)
self.assertEqual(can_out.weight.numel(), 0)
self.assertEqual(gen_out.weight.numel(), 0)
self.assertTrue(tensors_allclose(can_out.weight, gen_out.weight))
# ---------- Linear: OUT ----------
def test_prune_linear_out_channels_equivalence(self):
layer = nn.Linear(5, 7, bias=True)
indices = [0, 2, 5]
can_layer = copy.deepcopy(layer)
gen_layer = copy.deepcopy(layer)
can_res = adapt_prune_linear_out_channels(C, can_layer, indices)
gen_res = adapt_prune_linear_out_channels(G, gen_layer, indices)
self.assertEqual(can_res.out_features, gen_res.out_features)
self.assertEqual(can_res.weight.shape, gen_res.weight.shape)
self.assertTrue(tensors_allclose(can_res.weight, gen_res.weight))
if can_res.bias is not None or gen_res.bias is not None:
self.assertIsNotNone(can_res.bias)
self.assertIsNotNone(gen_res.bias)
self.assertTrue(tensors_allclose(can_res.bias, gen_res.bias))
# Getter coverage
self.assertEqual(C.hf_linear_pruner.get_out_channels(can_res), G.hf_linear_pruner.get_out_channels(gen_res))
def test_prune_linear_out_channels_noop(self):
layer = nn.Linear(4, 6, bias=False)
indices = []
can_layer = copy.deepcopy(layer)
gen_layer = copy.deepcopy(layer)
can_res = adapt_prune_linear_out_channels(C, can_layer, indices)
gen_res = adapt_prune_linear_out_channels(G, gen_layer, indices)
self.assertEqual(can_res.out_features, 6)
self.assertEqual(gen_res.out_features, 6)
self.assertTrue(tensors_allclose(can_res.weight, gen_res.weight))
def test_prune_linear_out_channels_near_full_and_unsorted_dups(self):
layer = nn.Linear(3, 4, bias=True)
# Leave at least one row so merging has a destination; keep duplicates/unsorted
indices = [3, 1, 1] # prunes 2 unique rows (1,3) -> leaves rows {0,2}
can_layer = copy.deepcopy(layer)
gen_layer = copy.deepcopy(layer)
can_res = adapt_prune_linear_out_channels(C, can_layer, indices)
gen_res = adapt_prune_linear_out_channels(G, gen_layer, indices)
self.assertEqual(can_res.out_features, gen_res.out_features)
self.assertTrue(tensors_allclose(can_res.weight, gen_res.weight))
self.assertTrue(tensors_allclose(can_res.bias, gen_res.bias))
# ---------- Linear: IN ----------
def test_prune_linear_in_channels_equivalence(self):
layer = nn.Linear(8, 5, bias=True)
indices = [1, 4, 6]
can_layer = copy.deepcopy(layer)
gen_layer = copy.deepcopy(layer)
can_res = adapt_prune_linear_in_channels(C, can_layer, indices)
gen_res = adapt_prune_linear_in_channels(G, gen_layer, indices)
self.assertEqual(can_res.in_features, gen_res.in_features)
self.assertEqual(can_res.weight.shape, gen_res.weight.shape)
self.assertTrue(tensors_allclose(can_res.weight, gen_res.weight))
if can_res.bias is not None or gen_res.bias is not None:
self.assertIsNotNone(can_res.bias)
self.assertIsNotNone(gen_res.bias)
self.assertEqual(can_res.bias.shape, gen_res.bias.shape)
self.assertTrue(tensors_allclose(can_res.bias, gen_res.bias))
# Getter coverage
self.assertEqual(C.hf_linear_pruner.get_in_channels(can_res), G.hf_linear_pruner.get_in_channels(gen_res))
def test_prune_linear_in_channels_noop(self):
layer = nn.Linear(6, 4, bias=True)
indices = []
can_layer = copy.deepcopy(layer)
gen_layer = copy.deepcopy(layer)
can_res = adapt_prune_linear_in_channels(C, can_layer, indices)
gen_res = adapt_prune_linear_in_channels(G, gen_layer, indices)
self.assertEqual(can_res.in_features, 6)
self.assertEqual(gen_res.in_features, 6)
self.assertTrue(tensors_allclose(can_res.weight, gen_res.weight))
self.assertTrue(tensors_allclose(can_res.bias, gen_res.bias))
def test_prune_linear_in_channels_near_full(self):
layer = nn.Linear(5, 3, bias=False)
# prune 4 of 5, leave one column to avoid empty sim/argmax
indices = [0, 1, 2, 3]
can_layer = copy.deepcopy(layer)
gen_layer = copy.deepcopy(layer)
can_res = adapt_prune_linear_in_channels(C, can_layer, indices)
gen_res = adapt_prune_linear_in_channels(G, gen_layer, indices)
self.assertEqual(can_res.in_features, 1)
self.assertEqual(gen_res.in_features, 1)
self.assertEqual(can_res.weight.shape[1], 1)
self.assertEqual(gen_res.weight.shape[1], 1)
self.assertTrue(tensors_allclose(can_res.weight, gen_res.weight))
# ---------- Attention ----------
def test_prune_attention_channels_equivalence(self):
block = MiniMHA(hidden_size=8, num_heads=4, bias=True)
indices = [0, 1, 4, 5] # multiple of num_heads
can_block = copy.deepcopy(block)
gen_block = copy.deepcopy(block)
can_res = adapt_prune_attention_channels(C, can_block, indices)
gen_res = adapt_prune_attention_channels(G, gen_block, indices)
# Shapes should match across sub-layers
self.assertEqual(can_res.o_proj.weight.shape, gen_res.o_proj.weight.shape)
self.assertEqual(can_res.q_proj.weight.shape, gen_res.q_proj.weight.shape)
self.assertEqual(can_res.k_proj.weight.shape, gen_res.k_proj.weight.shape)
self.assertEqual(can_res.v_proj.weight.shape, gen_res.v_proj.weight.shape)
# Compare weights & biases
for name in ["o_proj", "q_proj", "k_proj", "v_proj"]:
cw = getattr(can_res, name).weight
gw = getattr(gen_res, name).weight
self.assertTrue(tensors_allclose(cw, gw), f"{name}.weight mismatch")
cb = getattr(can_res, name).bias
gb = getattr(gen_res, name).bias
if cb is None or gb is None:
self.assertIs(cb is None, gb is None, f"{name} bias None/state mismatch")
else:
self.assertTrue(tensors_allclose(cb, gb), f"{name}.bias mismatch")
# Getter coverage for attention
self.assertEqual(C.hf_attention_pruner.get_out_channels(can_res), G.hf_attention_pruner.get_out_channels(gen_res))
self.assertEqual(C.hf_attention_pruner.get_in_channels(can_res), G.hf_attention_pruner.get_in_channels(gen_res))
def test_prune_attention_channels_noop(self):
block = MiniMHA(hidden_size=12, num_heads=3, bias=False)
indices = []
can_block = copy.deepcopy(block)
gen_block = copy.deepcopy(block)
can_res = adapt_prune_attention_channels(C, can_block, indices)
gen_res = adapt_prune_attention_channels(G, gen_block, indices)
# all weights should be identical
for name in ["o_proj", "q_proj", "k_proj", "v_proj"]:
self.assertTrue(tensors_allclose(getattr(can_res, name).weight, getattr(gen_res, name).weight))
def test_prune_attention_channels_invalid_multiple(self):
block = MiniMHA(hidden_size=8, num_heads=4)
indices = [0, 1, 2] # not multiple of 4
can_block = copy.deepcopy(block)
gen_block = copy.deepcopy(block)
with self.assertRaises(Exception):
adapt_prune_attention_channels(C, can_block, indices)
with self.assertRaises(Exception):
adapt_prune_attention_channels(G, gen_block, indices)
def test_prune_attention_channels_all_heads(self):
block = MiniMHA(hidden_size=8, num_heads=4)
# prune all hidden channels (multiple of num_heads) — attention code supports 0-width safely
indices = list(range(block.hidden_size))
can_block = copy.deepcopy(block)
gen_block = copy.deepcopy(block)
can_res = adapt_prune_attention_channels(C, can_block, indices)
gen_res = adapt_prune_attention_channels(G, gen_block, indices)
self.assertEqual(can_res.o_proj.out_features, 0)
self.assertEqual(gen_res.o_proj.out_features, 0)
self.assertEqual(can_res.q_proj.in_features, 0)
self.assertEqual(gen_res.q_proj.in_features, 0)
for name in ["o_proj", "q_proj", "k_proj", "v_proj"]:
self.assertEqual(getattr(can_res, name).weight.numel(), 0)
self.assertEqual(getattr(gen_res, name).weight.numel(), 0)
self.assertTrue(tensors_allclose(getattr(can_res, name).weight, getattr(gen_res, name).weight))
# ---------- Magnitude Importance ----------
def test_calculate_magnitude_importance_norm(self):
norm = SimpleRMSNorm(dim=9)
indices = [0, 3, 6]
group_list = [(norm, indices)]
can_scores = adapt_calculate_magnitude_importance(C, group_list, p=2, reduction_strategy="sum")
gen_scores = adapt_calculate_magnitude_importance(G, group_list, p=2, reduction_strategy="sum")
self.assertEqual(can_scores.shape, gen_scores.shape)
self.assertTrue(tensors_allclose(can_scores, gen_scores))
def test_calculate_magnitude_importance_linear_out(self):
lin = nn.Linear(6, 5, bias=True)
indices = [1, 2, 4] # treat as OUT channels for test
group_list = [(lin, indices)]
can_scores = adapt_calculate_magnitude_importance(C, group_list, p=2, reduction_strategy="sum")
gen_scores = adapt_calculate_magnitude_importance(G, group_list, p=2, reduction_strategy="sum")
self.assertEqual(can_scores.shape, gen_scores.shape)
self.assertTrue(tensors_allclose(can_scores, gen_scores))
def test_magnitude_importance_alignment_and_reductions(self):
# Use sufficient out_features to hold both index groups (4 and 8)
lin = nn.Linear(10, 12, bias=False)
idx_a = [0, 2, 4, 6] # length 4
idx_b = [0, 1, 2, 3, 4, 5, 6, 7] # length 8 (multiple of 4)
for p in [1, 2]:
for red in ["mean", "max", "prod", "first", None]:
group_list = [(lin, idx_a), (lin, idx_b)]
can_scores = adapt_calculate_magnitude_importance(C, group_list, p=p, reduction_strategy=red)
gen_scores = adapt_calculate_magnitude_importance(G, group_list, p=p, reduction_strategy=red)
self.assertEqual(can_scores.shape, gen_scores.shape)
self.assertTrue(tensors_allclose(can_scores, gen_scores), f"p={p}, red={red}")
def test_magnitude_importance_attention_path(self):
block = MiniMHA(hidden_size=8, num_heads=4, bias=True)
indices = [0, 1, 4, 5]
group_list = [(block, indices)]
can_scores = adapt_calculate_magnitude_importance(C, group_list, p=2, reduction_strategy="sum")
gen_scores = adapt_calculate_magnitude_importance(G, group_list, p=2, reduction_strategy="sum")
self.assertEqual(can_scores.shape, gen_scores.shape)
self.assertTrue(tensors_allclose(can_scores, gen_scores))
# ---------- Taylor Importance ----------
def _make_linear_with_grads(self, in_f=6, out_f=5, batch=4):
layer = nn.Linear(in_f, out_f, bias=True)
layer.train()
x = torch.randn(batch, in_f)
target = torch.randn(batch, out_f)
out = layer(x)
loss = torch.mean((out - target) ** 2)
loss.backward()
# attach acc_grad for param_* modes
layer.weight.acc_grad = torch.ones_like(layer.weight) * 0.5
return layer
def _attach_attn_grads(self, block: MiniMHA):
for name in ["q_proj", "k_proj", "v_proj", "o_proj"]:
w = getattr(block, name).weight
w.grad = torch.randn_like(w)
w.acc_grad = torch.ones_like(w) * 0.25
def _attach_norm_grads(self, norm: SimpleRMSNorm):
# Provide both grad and acc_grad attributes
norm.weight.grad = torch.randn_like(norm.weight)
norm.weight.acc_grad = torch.ones_like(norm.weight) * 0.33
def test_calculate_taylor_importance_vectorize_linear_out(self):
layer = self._make_linear_with_grads(in_f=6, out_f=5, batch=4)
indices = [0, 2, 4] # OUT channel indices
group_list = [(layer, indices)]
can_scores = adapt_calculate_taylor_importance(C, group_list, reduction_strategy="sum", taylor_mode="vectorize")
gen_scores = adapt_calculate_taylor_importance(G, group_list, reduction_strategy="sum", taylor_mode="vectorize")
self.assertEqual(can_scores.shape, gen_scores.shape)
self.assertTrue(tensors_allclose(can_scores, gen_scores))
def test_calculate_taylor_importance_param_second_and_mix_linear_out(self):
layer = self._make_linear_with_grads(in_f=7, out_f=6, batch=3)
indices = [1, 3, 5]
group_list = [(layer, indices)]
for mode in ["param_second", "param_mix"]:
can_scores = adapt_calculate_taylor_importance(C, group_list, reduction_strategy="mean", taylor_mode=mode)
gen_scores = adapt_calculate_taylor_importance(G, group_list, reduction_strategy="mean", taylor_mode=mode)
self.assertEqual(can_scores.shape, gen_scores.shape)
self.assertTrue(tensors_allclose(can_scores, gen_scores), f"mode={mode}")
def test_calculate_taylor_importance_attention_vectorize(self):
block = MiniMHA(hidden_size=8, num_heads=4, bias=True)
self._attach_attn_grads(block)
indices = [0, 1, 4, 5]
group_list = [(block, indices)]
can_scores = adapt_calculate_taylor_importance(C, group_list, reduction_strategy="sum", taylor_mode="vectorize")
gen_scores = adapt_calculate_taylor_importance(G, group_list, reduction_strategy="sum", taylor_mode="vectorize")
self.assertEqual(can_scores.shape, gen_scores.shape)
self.assertTrue(tensors_allclose(can_scores, gen_scores))
@unittest.skip("Skipped: canonical TaylorImportance has a known bug in attention param_* path for q/k/v ('param' logic).")
def test_calculate_taylor_importance_attention_param_second(self):
block = MiniMHA(hidden_size=12, num_heads=3, bias=False)
self._attach_attn_grads(block)
indices = [0, 1, 2, 6, 7, 8] # multiple of heads
group_list = [(block, indices)]
can_scores = adapt_calculate_taylor_importance(C, group_list, reduction_strategy="max", taylor_mode="param_second")
gen_scores = adapt_calculate_taylor_importance(G, group_list, reduction_strategy="max", taylor_mode="param_second")
self.assertEqual(can_scores.shape, gen_scores.shape)
self.assertTrue(tensors_allclose(can_scores, gen_scores))
def test_taylor_rmsnorm_vectorize_and_param_second(self):
norm = SimpleRMSNorm(dim=8)
self._attach_norm_grads(norm)
indices = [0, 2, 4, 6]
group_list = [(norm, indices)]
# vectorize
can_vec = adapt_calculate_taylor_importance(C, group_list, reduction_strategy="sum", taylor_mode="vectorize")
gen_vec = adapt_calculate_taylor_importance(G, group_list, reduction_strategy="sum", taylor_mode="vectorize")
self.assertEqual(can_vec.shape, gen_vec.shape)
self.assertTrue(tensors_allclose(can_vec, gen_vec))
# param_second
can_second = adapt_calculate_taylor_importance(C, group_list, reduction_strategy="sum", taylor_mode="param_second")
gen_second = adapt_calculate_taylor_importance(G, group_list, reduction_strategy="sum", taylor_mode="param_second")
self.assertEqual(can_second.shape, gen_second.shape)
self.assertTrue(tensors_allclose(can_second, gen_second))
def test_taylor_reduction_second_row_selection(self):
# Build two groups to produce stacked [2 x N] and select "second" row via reduction
layer = self._make_linear_with_grads(in_f=6, out_f=6, batch=4)
idx_a = [0, 2, 4] # group 1
idx_b = [1, 3, 5] # group 2 (same length)
group_list = [(layer, idx_a), (layer, idx_b)]
can_scores = adapt_calculate_taylor_importance(C, group_list, reduction_strategy="second", taylor_mode="vectorize")
gen_scores = adapt_calculate_taylor_importance(G, group_list, reduction_strategy="second", taylor_mode="vectorize")
self.assertEqual(can_scores.shape, gen_scores.shape)
self.assertTrue(tensors_allclose(can_scores, gen_scores))
if __name__ == "__main__":
unittest.main()