• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1import operator_benchmark as op_bench
2
3import torch
4from torch import nn
5from torch.ao import pruning
6
7
8"""Microbenchmarks for sparsifier."""
9
10sparse_configs_short = op_bench.config_list(
11    attr_names=["M", "SL", "SBS", "ZPB"],
12    attrs=[
13        [(32, 16), 0.3, (4, 1), 2],
14        [(32, 16), 0.6, (1, 4), 4],
15        [(17, 23), 0.9, (1, 1), 1],
16    ],
17    tags=("short",),
18)
19
20sparse_configs_long = op_bench.cross_product_configs(
21    M=((128, 128), (255, 324)),  # Mask shape
22    SL=(0.0, 1.0, 0.3, 0.6, 0.9, 0.99),  # Sparsity level
23    SBS=((1, 4), (1, 8), (4, 1), (8, 1)),  # Sparse block shape
24    ZPB=(0, 1, 2, 3, 4, None),  # Zeros per block
25    tags=("long",),
26)
27
28
29class WeightNormSparsifierBenchmark(op_bench.TorchBenchmarkBase):
30    def init(self, M, SL, SBS, ZPB):
31        weight = torch.ones(M)
32        model = nn.Module()
33        model.register_buffer("weight", weight)
34
35        sparse_config = [{"tensor_fqn": "weight"}]
36        self.sparsifier = pruning.WeightNormSparsifier(
37            sparsity_level=SL,
38            sparse_block_shape=SBS,
39            zeros_per_block=ZPB,
40        )
41        self.sparsifier.prepare(model, config=sparse_config)
42        self.inputs = {}  # All benchmarks need inputs :)
43        self.set_module_name("weight_norm_sparsifier_step")
44
45    def forward(self):
46        self.sparsifier.step()
47
48
49all_tests = sparse_configs_short + sparse_configs_long
50op_bench.generate_pt_test(all_tests, WeightNormSparsifierBenchmark)
51
52
53if __name__ == "__main__":
54    op_bench.benchmark_runner.main()
55