|
| 1 | +from neurobench.metrics.abstract.workload_metric import AccumulatedMetric |
| 2 | +from collections import defaultdict |
| 3 | +import torch |
| 4 | + |
| 5 | + |
| 6 | +class ActivationSparsityByLayer(AccumulatedMetric): |
| 7 | + """ |
| 8 | + Sparsity layer-wise of model activations. |
| 9 | +
|
| 10 | + Calculated as the number of zero activations over the number of activations layer by |
| 11 | + layer, over all timesteps, samples in data. |
| 12 | +
|
| 13 | + """ |
| 14 | + |
| 15 | + def __init__(self): |
| 16 | + """Initialize the ActivationSparsityByLayer metric.""" |
| 17 | + self.layer_sparsity = defaultdict(float) |
| 18 | + self.layer_neuro_num = defaultdict(int) |
| 19 | + self.layer_spike_num = defaultdict(int) |
| 20 | + |
| 21 | + def reset(self): |
| 22 | + """Reset the metric.""" |
| 23 | + self.layer_sparsity = defaultdict(float) |
| 24 | + self.layer_neuro_num = defaultdict(int) |
| 25 | + self.layer_spike_num = defaultdict(int) |
| 26 | + |
| 27 | + def __call__(self, model, preds, data): |
| 28 | + """ |
| 29 | + Compute activation sparsity layer by layer. |
| 30 | +
|
| 31 | + Args: |
| 32 | + model: A NeuroBenchModel. |
| 33 | + preds: A tensor of model predictions. |
| 34 | + data: A tuple of data and labels. |
| 35 | + Returns: |
| 36 | + float: Activation sparsity |
| 37 | +
|
| 38 | + """ |
| 39 | + |
| 40 | + for hook in model.activation_hooks: |
| 41 | + name = hook.name |
| 42 | + if name is None: |
| 43 | + continue |
| 44 | + for output in hook.activation_outputs: |
| 45 | + spike_num, neuro_num = torch.count_nonzero( |
| 46 | + output.dequantize() if output.is_quantized else output |
| 47 | + ).item(), torch.numel(output) |
| 48 | + |
| 49 | + self.layer_spike_num[name] += spike_num |
| 50 | + self.layer_neuro_num[name] += neuro_num |
| 51 | + |
| 52 | + return self.compute() |
| 53 | + |
| 54 | + def compute(self): |
| 55 | + """Compute the activation sparsity layer by layer.""" |
| 56 | + for key in self.layer_neuro_num: |
| 57 | + sparsity = ( |
| 58 | + (self.layer_neuro_num[key] - self.layer_spike_num[key]) |
| 59 | + / self.layer_neuro_num[key] |
| 60 | + if self.layer_neuro_num[key] != 0 |
| 61 | + else 0.0 |
| 62 | + ) |
| 63 | + self.layer_sparsity[key] = sparsity |
| 64 | + return dict(self.layer_sparsity) |
0 commit comments