Spaces:
Sleeping
Sleeping
Create core/stress.py
Browse files- core/stress.py +36 -0
core/stress.py
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import torch.nn.functional as F
|
| 3 |
+
from .quantizer import fake_quantize
|
| 4 |
+
|
| 5 |
+
def mse(a, b):
|
| 6 |
+
return F.mse_loss(a, b).item()
|
| 7 |
+
|
| 8 |
+
def kl(a, b):
|
| 9 |
+
a = torch.softmax(a.flatten(), dim=0)
|
| 10 |
+
b = torch.softmax(b.flatten(), dim=0)
|
| 11 |
+
return F.kl_div(a.log(), b, reduction="batchmean").item()
|
| 12 |
+
|
| 13 |
+
def quantize_module(module, bits):
|
| 14 |
+
original = {}
|
| 15 |
+
for name, param in module.named_parameters():
|
| 16 |
+
original[name] = param.data.clone()
|
| 17 |
+
param.data = fake_quantize(param.data, bits)
|
| 18 |
+
return original
|
| 19 |
+
|
| 20 |
+
def restore_module(module, original):
|
| 21 |
+
for name, param in module.named_parameters():
|
| 22 |
+
param.data = original[name]
|
| 23 |
+
|
| 24 |
+
def stress_layer(model, layer_name, inputs, bits=8):
|
| 25 |
+
with torch.no_grad():
|
| 26 |
+
baseline = model(**inputs).logits.detach()
|
| 27 |
+
|
| 28 |
+
module = dict(model.named_modules())[layer_name]
|
| 29 |
+
original = quantize_module(module, bits)
|
| 30 |
+
|
| 31 |
+
with torch.no_grad():
|
| 32 |
+
quant = model(**inputs).logits.detach()
|
| 33 |
+
|
| 34 |
+
restore_module(module, original)
|
| 35 |
+
|
| 36 |
+
return mse(baseline, quant), kl(baseline, quant)
|