Spaces:
Sleeping
Sleeping
Create core/profiler.py
Browse files- core/profiler.py +39 -0
core/profiler.py
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
from collections import defaultdict
|
| 3 |
+
|
| 4 |
+
class ActivationProfiler:
|
| 5 |
+
def __init__(self, model):
|
| 6 |
+
self.model = model
|
| 7 |
+
self.stats = defaultdict(dict)
|
| 8 |
+
self.hooks = []
|
| 9 |
+
|
| 10 |
+
def hook_fn(self, name):
|
| 11 |
+
def hook(module, input, output):
|
| 12 |
+
act = output.detach().float()
|
| 13 |
+
std = act.std().item()
|
| 14 |
+
mean = act.mean().item()
|
| 15 |
+
min_val = act.min().item()
|
| 16 |
+
max_val = act.max().item()
|
| 17 |
+
outliers = (act.abs() > 3 * std).float().mean().item()
|
| 18 |
+
|
| 19 |
+
self.stats[name] = {
|
| 20 |
+
"mean": mean,
|
| 21 |
+
"std": std,
|
| 22 |
+
"min": min_val,
|
| 23 |
+
"max": max_val,
|
| 24 |
+
"outlier_ratio": outliers
|
| 25 |
+
}
|
| 26 |
+
return hook
|
| 27 |
+
|
| 28 |
+
def register(self):
|
| 29 |
+
for name, module in self.model.named_modules():
|
| 30 |
+
if "mlp" in name or "attn" in name:
|
| 31 |
+
h = module.register_forward_hook(self.hook_fn(name))
|
| 32 |
+
self.hooks.append(h)
|
| 33 |
+
|
| 34 |
+
def remove(self):
|
| 35 |
+
for h in self.hooks:
|
| 36 |
+
h.remove()
|
| 37 |
+
|
| 38 |
+
def get(self):
|
| 39 |
+
return self.stats
|