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
| import torch import torch.nn as nn import numpy as np from typing import Callable, Dict, List from scipy import stats
class SensitivityMetrics: """ 论文对比的13种层间量化敏感度指标 分为4类: 1. 权重统计(4种)- 基于权重分布 2. 梯度方法(3种)- 基于反向传播梯度 3. 激活统计(3种)- 基于输出分布 4. 信息论(3种)- 基于信息论度量 """ @staticmethod def weight_l2_norm(layer: nn.Module) -> float: """1. 权重L2范数""" return torch.norm(layer.weight).item() @staticmethod def weight_max_abs(layer: nn.Module) -> float: """2. 权重最大绝对值""" return layer.weight.abs().max().item() @staticmethod def weight_std(layer: nn.Module) -> float: """3. 权重标准差""" return layer.weight.std().item() @staticmethod def weight_kurtosis(layer: nn.Module) -> float: """4. 权重峰度""" w = layer.weight.flatten().detach().numpy() return float(stats.kurtosis(w)) @staticmethod def gradient_norm( layer: nn.Module, loss_fn: Callable, x: torch.Tensor, y: torch.Tensor ) -> float: """5. 梯度范数(需反向传播)""" layer.weight.requires_grad = True out = layer(x) loss = loss_fn(out, y) loss.backward() grad_norm = layer.weight.grad.norm().item() layer.weight.requires_grad = False return grad_norm @staticmethod def gradient_max( layer: nn.Module, loss_fn: Callable, x: torch.Tensor, y: torch.Tensor ) -> float: """6. 梯度最大值""" layer.weight.requires_grad = True out = layer(x) loss = loss_fn(out, y) loss.backward() grad_max = layer.weight.grad.abs().max().item() layer.weight.requires_grad = False return grad_max @staticmethod def gradient_mean( layer: nn.Module, loss_fn: Callable, x: torch.Tensor, y: torch.Tensor ) -> float: """7. 梯度均值""" layer.weight.requires_grad = True out = layer(x) loss = loss_fn(out, y) loss.backward() grad_mean = layer.weight.grad.abs().mean().item() layer.weight.requires_grad = False return grad_mean @staticmethod def activation_l2(fp32_out: torch.Tensor, int8_out: torch.Tensor) -> float: """8. 激活L2距离""" return torch.norm(fp32_out - int8_out).item() @staticmethod def activation_cosine(fp32_out: torch.Tensor, int8_out: torch.Tensor) -> float: """9. 激活余弦相似度""" cos = torch.nn.functional.cosine_similarity( fp32_out.flatten().unsqueeze(0), int8_out.flatten().unsqueeze(0) ) return (1 - cos).item() @staticmethod def activation_mse(fp32_out: torch.Tensor, int8_out: torch.Tensor) -> float: """10. 激活MSE""" return torch.nn.functional.mse_loss(fp32_out, int8_out).item() @staticmethod def kl_divergence(fp32_out: torch.Tensor, int8_out: torch.Tensor) -> float: """11. KL散度""" p = torch.softmax(fp32_out.flatten(), dim=0) q = torch.softmax(int8_out.flatten(), dim=0) kl = (p * (p / (q + 1e-8) + 1e-8).log()).sum().item() return kl @staticmethod def jensen_shannon_divergence( fp32_out: torch.Tensor, int8_out: torch.Tensor ) -> float: """ 12. Jensen-Shannon散度(JSD)⭐ 论文核心发现:JSD是唯一在所有4×8=32种配置中 零灾难性失败的指标 """ p = torch.softmax(fp32_out.flatten().float(), dim=0) q = torch.softmax(int8_out.flatten().float(), dim=0) m = 0.5 * (p + q) def kl(a, b): return (a * (a / (b + 1e-10) + 1e-10).log()).sum().item() jsd = 0.5 * kl(p, m) + 0.5 * kl(q, m) return jsd @staticmethod def wasserstein_distance( fp32_out: torch.Tensor, int8_out: torch.Tensor ) -> float: """13. Wasserstein距离""" p = torch.softmax(fp32_out.flatten().float(), dim=0) q = torch.softmax(int8_out.flatten().float(), dim=0) cdf_p = torch.cumsum(p, dim=0) cdf_q = torch.cumsum(q, dim=0) return torch.norm(cdf_p - cdf_q).item()
def compute_all_metrics( layer: nn.Module, fp32_out: torch.Tensor, int8_out: torch.Tensor, loss_fn=None, sample_input=None, sample_target=None ) -> Dict[str, float]: """计算13种敏感度指标""" metrics = SensitivityMetrics() results = {} results['weight_l2'] = metrics.weight_l2_norm(layer) results['weight_max'] = metrics.weight_max_abs(layer) results['weight_std'] = metrics.weight_std(layer) results['weight_kurtosis'] = metrics.weight_kurtosis(layer) if loss_fn is not None and sample_input is not None: results['grad_norm'] = metrics.gradient_norm( layer, loss_fn, sample_input, sample_target) results['grad_max'] = metrics.gradient_max( layer, loss_fn, sample_input, sample_target) results['grad_mean'] = metrics.gradient_mean( layer, loss_fn, sample_input, sample_target) results['act_l2'] = metrics.activation_l2(fp32_out, int8_out) results['act_cosine'] = metrics.activation_cosine(fp32_out, int8_out) results['act_mse'] = metrics.activation_mse(fp32_out, int8_out) results['kl_div'] = metrics.kl_divergence(fp32_out, int8_out) results['jsd'] = metrics.jensen_shannon_divergence(fp32_out, int8_out) results['wasserstein'] = metrics.wasserstein_distance(fp32_out, int8_out) return results
if __name__ == "__main__": layer = nn.Linear(256, 128) x = torch.randn(4, 256) fp32_out = layer(x) scale = fp32_out.abs().max() / 127 int8_out = torch.round(fp32_out / scale) * scale metrics = compute_all_metrics(layer, fp32_out, int8_out) print("13种敏感度指标:") print("-" * 40) for name, value in metrics.items(): print(f" {name:20s}: {value:.6f}") print(f"\n⭐ JSD (Jensen-Shannon): {metrics['jsd']:.6f}") print(" → 唯一零灾难性失败指标")
|