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 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092
|
# Owner(s): ["module: unknown"]
import copy
import logging
import random
import torch
from torch import nn
from torch.ao.pruning._experimental.pruner import (
BaseStructuredSparsifier,
FakeStructuredSparsity,
FPGMPruner,
LSTMSaliencyPruner,
SaliencyPruner,
)
from torch.nn.utils import parametrize
from torch.testing._internal.common_pruning import (
Conv2dActivation,
Conv2dBias,
Conv2dPadBias,
Conv2dPool,
Conv2dPoolFlatten,
Conv2dPoolFlattenFunctional,
LinearActivation,
LinearActivationFunctional,
LinearBias,
LSTMLayerNormLinearModel,
LSTMLinearModel,
rows_are_subset,
SimpleConv2d,
SimpleLinear,
)
from torch.testing._internal.common_utils import skipIfTorchDynamo, TestCase
logging.basicConfig(
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging.INFO
)
DEVICES = {
torch.device("cpu"),
torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu"),
}
class SimplePruner(BaseStructuredSparsifier):
def update_mask(self, module, tensor_name, **kwargs):
getattr(module.parametrizations, tensor_name)[0].mask[1] = False
class ImplementedPruner(BaseStructuredSparsifier):
def update_mask(self, module, tensor_name, **kwargs):
"""Prunes 1/3 of the weight output channels, so resulting module has 33.3% pruning"""
num_rows = len(module.parametrizations[tensor_name][0].mask)
prune = random.sample(list(range(num_rows)), num_rows // 3)
module.parametrizations[tensor_name][0].mask[prune] = False
class BottomHalfLSTMPruner(BaseStructuredSparsifier):
"""
Pruner that will remove the bottom half of the rows.
This is primarily meant for testing purposes
"""
def update_mask(self, module, tensor_name, **kwargs):
for p in getattr(module.parametrizations, tensor_name):
if isinstance(p, FakeStructuredSparsity):
mask = p.mask
masks = torch.split(mask, len(mask) // 4)
for small in masks:
num = len(small)
small[num // 2 :] = False
new_mask = torch.cat(masks)
mask.data = new_mask.data
class TestSaliencyPruner(TestCase):
def test_saliency_pruner_update_mask(self):
"""Test that we prune out the row with the lowest saliency (first row)"""
model = SimpleLinear()
with torch.no_grad():
model.linear1.weight = nn.Parameter(
torch.Tensor([[1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3], [4, 4, 4, 4]])
)
pruning_config = [{"tensor_fqn": "linear1.weight", "sparsity_level": 0.5}]
pruner = SaliencyPruner({})
pruner.prepare(model, pruning_config)
pruner.enable_mask_update = True
pruner.step()
pruned_model = pruner.prune()
expected = torch.Tensor([[3, 3, 3, 3], [4, 4, 4, 4]])
pruned = pruned_model.linear1.weight
assert expected.shape == pruned.shape
assert torch.isclose(expected, pruned, rtol=1e-05, atol=1e-07).all()
def test_lstm_saliency_pruner_update_mask(self):
model = LSTMLinearModel(
input_dim=2,
hidden_dim=2,
output_dim=2,
num_layers=1,
)
manual_weights = torch.Tensor(
[[1, 1], [2, 2], [2, 2], [1, 1], [-1, -1], [-2, -2], [-2, -2], [-1, -1]]
)
with torch.no_grad():
model.lstm.weight_ih_l0 = nn.Parameter(manual_weights)
model.lstm.weight_hh_l0 = nn.Parameter(torch.Tensor(manual_weights))
model.lstm.bias_ih_l0 = nn.Parameter(manual_weights[:, 0])
model.lstm.bias_hh_l0 = nn.Parameter(manual_weights[:, 0])
config = [
{"tensor_fqn": "lstm.weight_ih_l0"},
{"tensor_fqn": "lstm.weight_hh_l0"},
]
lstm_input = torch.ones((1, 2))
fx_pruner = LSTMSaliencyPruner({"sparsity_level": 0.5})
fx_pruner.prepare(model, config)
fx_pruner.enable_mask_update = True
fx_pruner.step()
model.eval()
pruned_model = fx_pruner.prune()
pruned_model.eval()
# make sure both models run
model(lstm_input)
pruned_model(lstm_input)
# make sure lowest saliency rows are pruned
expected = torch.Tensor([[2, 2], [2, 2], [-2, -2], [-2, -2]])
pruned = model.lstm.weight_ih_l0
assert expected.shape == pruned.shape
assert torch.isclose(expected, pruned, rtol=1e-05, atol=1e-07).all()
expected = torch.Tensor([[2], [2], [-2], [-2]])
pruned = model.lstm.weight_hh_l0
assert expected.shape == pruned.shape
assert torch.isclose(expected, pruned, rtol=1e-05, atol=1e-07).all()
expected = torch.Tensor([2, 2, -2, -2])
for pruned in [model.lstm.bias_ih_l0, model.lstm.bias_hh_l0]:
assert expected.shape == pruned.shape
assert torch.isclose(expected, pruned, rtol=1e-05, atol=1e-07).all()
class TestBaseStructuredSparsifier(TestCase):
def _check_pruner_prepared(self, model, pruner, device):
for config in pruner.groups:
module = config["module"]
assert module.weight.device.type == device.type
# Check mask exists
assert config["tensor_fqn"] in pruner.state
# Check parametrization exists and is correct
assert parametrize.is_parametrized(module)
assert hasattr(module, "parametrizations")
# Assume that this is the 1st/only parametrization
assert type(module.parametrizations.weight[0]) == FakeStructuredSparsity
def _check_pruner_valid_before_step(self, model, pruner, device):
for config in pruner.groups:
modules = []
if type(config["module"]) is tuple:
modules.extend(config["module"])
else:
module = config["module"]
modules.append(module)
for module in modules:
assert module.weight.device.type == device.type
assert module.parametrizations.weight[0].mask.dtype == torch.bool
def _check_pruner_valid_after_step(self, model, pruner, mask, device):
for config in pruner.groups:
modules = []
if type(config["module"]) is tuple:
modules.extend(config["module"])
else:
module = config["module"]
modules.append(module)
for module in modules:
assert module.weight.device.type == device.type
total = module.parametrizations.weight[0].mask.numel()
assert (
module.parametrizations.weight[0].mask.count_nonzero()
== total - mask
)
def _test_constructor_on_device(self, model, device):
self.assertRaisesRegex(
TypeError,
"BaseStructuredSparsifier.*update_mask",
BaseStructuredSparsifier,
)
model1 = copy.deepcopy(model).to(device)
pruner = SimplePruner(None)
pruner.prepare(model1, None)
pruner.enable_mask_update = True
for g in pruner.groups:
module = g["module"]
assert module.weight.device.type == device.type
assert len(pruner.groups) == 5
pruner.step()
# Can instantiate the model with configs
model2 = copy.deepcopy(model).to(device)
pruner = SimplePruner({"test": 3})
pruner.prepare(model2, [{"tensor_fqn": "seq.0.weight"}])
assert len(pruner.groups) == 1
assert pruner.groups[0]["module_fqn"] == "seq.0"
assert "test" in pruner.groups[0]
assert pruner.groups[0]["test"] == 3
def test_constructor(self):
model = SimpleLinear()
for device in DEVICES:
self._test_constructor_on_device(model, torch.device(device))
def _test_prepare_linear_on_device(self, model, device):
model = copy.deepcopy(model).to(device)
x = torch.ones(128, 7, device=device)
pruner = SimplePruner(None)
pruner.prepare(model, None)
self._check_pruner_prepared(model, pruner, device)
assert model(x).shape == (128, 10)
def test_prepare_linear(self):
models = [
SimpleLinear(),
LinearBias(),
LinearActivation(),
LinearActivationFunctional(),
] # without and with bias
for device in DEVICES:
for model in models:
self._test_prepare_linear_on_device(model, torch.device(device))
def _test_prepare_conv2d_on_device(self, model, expected_shape, config, device):
x = torch.ones((1, 1, 28, 28), device=device)
pruner = SimplePruner(None)
pruner.prepare(model, config)
self._check_pruner_prepared(model, pruner, device)
assert model(x).shape == expected_shape
def test_prepare_conv2d(self):
models = [
SimpleConv2d(),
Conv2dBias(),
Conv2dActivation(),
Conv2dPadBias(),
Conv2dPool(),
]
shapes = [
(1, 52, 20, 20),
(1, 52, 18, 18),
(1, 52, 18, 18),
(1, 52, 24, 24),
(1, 52, 3, 3),
]
configs = [None, None, None, None, None]
for device in DEVICES:
for model, shape, config in zip(models, shapes, configs):
model = model.to(device)
self._test_prepare_conv2d_on_device(
model, shape, config, torch.device(device)
)
def _test_step_linear_on_device(self, model, device):
model = model.to(device)
x = torch.ones(7, 7, device=device)
pruner = SimplePruner(None)
pruner.prepare(model, None)
pruner.enable_mask_update = True
self._check_pruner_valid_before_step(model, pruner, device)
pruner.step()
self._check_pruner_valid_after_step(model, pruner, 1, device)
def test_step_linear(self):
models = [
SimpleLinear(),
LinearBias(),
LinearActivation(),
LinearActivationFunctional(),
]
for device in DEVICES:
for model in models:
self._test_step_linear_on_device(model, torch.device(device))
def _test_step_conv2d_on_device(self, model, expected_shape, config, device):
model = model.to(device)
x = torch.ones((1, 1, 28, 28), device=device)
pruner = SimplePruner(None)
pruner.prepare(model, config)
pruner.enable_mask_update = True
self._check_pruner_valid_before_step(model, pruner, device)
pruner.step()
self._check_pruner_valid_after_step(model, pruner, 1, device)
assert model(x).shape == expected_shape
@skipIfTorchDynamo("TorchDynamo fails with unknown reason")
def test_step_conv2d(self):
models = [
SimpleConv2d(),
Conv2dBias(),
Conv2dActivation(),
Conv2dPadBias(),
Conv2dPool(),
]
shapes = [
(1, 52, 20, 20),
(1, 52, 18, 18),
(1, 52, 18, 18),
(1, 52, 24, 24),
(1, 52, 3, 3),
]
configs = [None, None, None, None, None]
for device in DEVICES:
for model, shape, config in zip(models, shapes, configs):
self._test_step_conv2d_on_device(
model, shape, config, torch.device(device)
)
def _check_pruner_pruned(self, model, pruner, device):
for config in pruner.groups:
module = config["module"]
assert not hasattr(module, "parametrizations")
assert not hasattr(module, "mask")
def _test_linear_on_device(
self, model, config, expected_shape, device, also_prune_bias
):
model = model.to(device)
model.eval()
num_original_params = sum(p.numel() for p in model.parameters())
x = torch.ones(128, 7, device=device)
pruner = ImplementedPruner({"prune_bias": also_prune_bias})
pruner.prepare(model, config)
pruner.enable_mask_update = True
pruner.step()
y_expected = model(x)
assert y_expected.shape == (128, 10)
self._check_pruner_prepared(model, pruner, device)
# Pruning step
pruned = pruner.prune()
y_pruned = pruned(x)
num_pruned_params = sum(p.numel() for p in pruned.parameters())
assert y_pruned.shape == expected_shape
self._check_pruner_pruned(model, pruner, device)
if y_pruned.shape == y_expected.shape:
assert torch.isclose(y_expected, y_pruned, rtol=1e-05, atol=1e-07).all()
assert num_pruned_params < num_original_params
def test_prune_linear_linear(self):
r"""test pruning linear-> linear modules"""
configs, shapes = [], []
configs.append(
[
{"tensor_fqn": "seq.0.weight"},
{"tensor_fqn": "seq.1.weight"},
{"tensor_fqn": "seq.2.weight"},
]
)
shapes.append((128, 10))
configs.append(
[
{"tensor_fqn": "seq.0.weight"},
{"tensor_fqn": "seq.1.weight"},
{"tensor_fqn": "seq.2.weight"},
{"tensor_fqn": "linear1.weight"},
]
)
shapes.append((128, 10))
configs.append(
[
{"tensor_fqn": "seq.0.weight"},
{"tensor_fqn": "seq.2.weight"},
]
)
shapes.append((128, 10))
for device in DEVICES:
for also_prune_bias in [True, False]:
for config, shape in zip(configs, shapes):
self._test_linear_on_device(
SimpleLinear(),
config,
shape,
torch.device(device),
also_prune_bias,
)
def test_prune_linear_bias_linear(self):
# linear(bias) -> linear(no bias)
configs, shapes = [], []
configs.append(
[
{"tensor_fqn": "seq.0.weight"},
{"tensor_fqn": "seq.1.weight"},
]
)
shapes.append((128, 10))
# linear(bias) -> linear(bias)
configs.append(
[
{"tensor_fqn": "seq.2.weight"},
{"tensor_fqn": "seq.3.weight"},
]
)
shapes.append((128, 10))
# linear(no bias) -> linear(bias)
configs.append(
[
{"tensor_fqn": "seq.0.weight"},
{"tensor_fqn": "seq.1.weight"},
{"tensor_fqn": "seq.2.weight"},
]
)
shapes.append((128, 10))
for device in DEVICES:
for also_prune_bias in [True, False]:
for config, shape in zip(configs, shapes):
self._test_linear_on_device(
LinearBias(),
config,
shape,
torch.device(device),
also_prune_bias,
)
def test_prune_linear_activation_linear(self):
config = [
{"tensor_fqn": "seq.0.weight"},
{"tensor_fqn": "seq.2.weight"},
{"tensor_fqn": "seq.4.weight"},
{"tensor_fqn": "linear1.weight"},
]
shape = (128, 10)
for device in DEVICES:
for also_prune_bias in [True, False]:
# test version with nn.Modules
self._test_linear_on_device(
LinearActivation(),
config,
shape,
torch.device(device),
also_prune_bias,
)
# test functional version
self._test_linear_on_device(
LinearActivationFunctional(),
config,
shape,
torch.device(device),
also_prune_bias,
)
def _test_conv2d_on_device(
self, model, config, x, expected_shape, device, also_prune_bias
):
model = model.to(device)
num_original_params = sum(p.numel() for p in model.parameters())
model.eval()
pruner = ImplementedPruner({"prune_bias": also_prune_bias})
pruner.prepare(model, config)
pruner.enable_mask_update = True
pruner.step()
y_expected = model(x)
assert y_expected.shape == expected_shape
self._check_pruner_prepared(model, pruner, device)
# Fusion step
pruned = pruner.prune()
y_pruned = pruned(x)
num_pruned_params = sum(p.numel() for p in pruned.parameters())
assert y_pruned.shape == expected_shape
self._check_pruner_pruned(model, pruner, device)
if y_pruned.shape == y_expected.shape:
# TODO This rtol is a little high, need to double check if something specific is causing this to fail
assert torch.isclose(
y_expected,
y_pruned,
rtol=1e-3,
atol=1e-3,
).all(), f"fail for {type(model)}"
# only time this should be equal is when all layers have padding and we can't prune
assert num_pruned_params <= num_original_params
def test_prune_conv2d_conv2d(self):
configs, shapes = [], []
# all within sequential blocks
configs.append(
[
{"tensor_fqn": "seq.0.weight"},
]
)
shapes.append((1, 52, 20, 20))
# prune across sequential blocks
configs.append(
[
{"tensor_fqn": "seq.0.weight"},
{"tensor_fqn": "seq.1.weight"},
{"tensor_fqn": "conv2d1.weight"},
]
)
shapes.append((1, 52, 20, 20))
for device in DEVICES:
x = torch.ones((1, 1, 28, 28), device=device)
for also_prune_bias in [True, False]:
for config, shape in zip(configs, shapes):
self._test_conv2d_on_device(
SimpleConv2d(),
config,
x,
shape,
torch.device(device),
also_prune_bias,
)
def test_prune_conv2d_bias_conv2d(self):
# Conv2d with Bias and no Activation
configs, shapes = [], []
# conv2d(bias) -> conv2d(bias)
configs.append(
[
{"tensor_fqn": "seq.0.weight"},
{"tensor_fqn": "seq.1.weight"},
]
)
shapes.append((1, 52, 18, 18))
# conv2d(no bias) -> conv2d(bias)
configs.append(
[
{"tensor_fqn": "seq.0.weight"},
{"tensor_fqn": "seq.1.weight"},
{"tensor_fqn": "conv2d1.weight"},
]
)
shapes.append((1, 52, 18, 18))
# conv2d(bias) -> conv2d(no bias)
configs.append(
[
{"tensor_fqn": "seq.0.weight"},
{"tensor_fqn": "seq.1.weight"},
{"tensor_fqn": "seq.2.weight"},
]
)
shapes.append((1, 52, 18, 18))
for device in DEVICES:
x = torch.ones((1, 1, 28, 28), device=device)
for also_prune_bias in [True, False]:
for config, shape in zip(configs, shapes):
self._test_conv2d_on_device(
Conv2dBias(),
config,
x,
shape,
torch.device(device),
also_prune_bias,
)
def test_prune_conv2d_activation_conv2d(self):
# Conv2d with Activation and no Bias
configs, shapes = [], []
# conv2d(no bias) -> activation -> conv2d(no bias)
configs.append(
[
{"tensor_fqn": "seq.4.weight"},
]
)
shapes.append((1, 52, 18, 18))
# conv2d(bias) -> activation -> conv2d(bias)
configs.append(
[
{"tensor_fqn": "seq.0.weight"},
{"tensor_fqn": "seq.2.weight"},
]
)
shapes.append((1, 52, 18, 18))
# conv2d(bias) -> activation -> conv2d(no bias)
configs.append(
[
{"tensor_fqn": "seq.2.weight"},
{"tensor_fqn": "seq.4.weight"},
]
)
shapes.append((1, 52, 18, 18))
# conv2d(no bias) -> activation -> conv2d(bias)
configs.append(
[
{"tensor_fqn": "conv2d1.weight"},
]
)
shapes.append((1, 52, 18, 18))
for device in DEVICES:
x = torch.ones((1, 1, 28, 28), device=device)
for also_prune_bias in [True, False]:
for config, shape in zip(configs, shapes):
self._test_conv2d_on_device(
Conv2dActivation(),
config,
x,
shape,
torch.device(device),
also_prune_bias,
)
def test_prune_conv2d_padding_conv2d(self):
# Conv2d with Padded layers after Bias layers
configs, shapes = [], []
# conv(padded, bias) -> conv(padded, bias)
configs.append(
[
{"tensor_fqn": "seq.4.weight"},
]
)
shapes.append((1, 52, 24, 24))
# conv(no bias, no pad) -> conv(padded, bias)
configs.append(
[
{"tensor_fqn": "seq.2.weight"},
]
)
shapes.append((1, 52, 24, 24))
# conv(padded, bias) -> conv ( no bias ,no pad)
configs.append(
[
{"tensor_fqn": "seq.0.weight"},
]
)
shapes.append((1, 52, 24, 24))
# conv(pad, bias) -> conv(no pad, bias)
configs.append(
[
{"tensor_fqn": "seq.6.weight"},
]
)
shapes.append((1, 52, 24, 24))
# conv(no pad, bias) -> conv(pad, bias)
configs.append(
[
{"tensor_fqn": "seq.8.weight"},
]
)
shapes.append((1, 52, 24, 24))
for device in DEVICES:
x = torch.ones((1, 1, 28, 28), device=device)
for also_prune_bias in [True, False]:
for config, shape in zip(configs, shapes):
self._test_conv2d_on_device(
Conv2dPadBias(),
config,
x,
shape,
torch.device(device),
also_prune_bias,
)
def test_prune_conv2d_pool_conv2d(self):
# Conv2d with Pooling layers
config = [
{"tensor_fqn": "seq.0.weight"},
{"tensor_fqn": "seq.3.weight"},
{"tensor_fqn": "conv2d1.weight"},
{"tensor_fqn": "conv2d2.weight"},
]
shape = (1, 52, 3, 3)
for device in DEVICES:
x = torch.ones((1, 1, 28, 28), device=device)
for also_prune_bias in [True, False]:
self._test_conv2d_on_device(
Conv2dPool(),
config,
x,
shape,
torch.device(device),
also_prune_bias,
)
@skipIfTorchDynamo("TorchDynamo fails with unknown reason")
def test_complex_conv2d(self):
"""Test fusion for models that contain Conv2d & Linear modules.
Currently supports: Conv2d-Pool2d-Flatten-Linear, Skip-add"""
config = [
{"tensor_fqn": "seq.0.weight"},
{"tensor_fqn": "seq.3.weight"},
{"tensor_fqn": "conv2d1.weight"},
{"tensor_fqn": "conv2d2.weight"},
]
shape = (1, 13)
for device in DEVICES:
x = torch.ones((1, 1, 28, 28), device=device)
for also_prune_bias in [True, False]:
self._test_conv2d_on_device(
Conv2dPoolFlattenFunctional(),
config,
x,
shape,
torch.device(device),
also_prune_bias,
)
self._test_conv2d_on_device(
Conv2dPoolFlatten(),
config,
x,
shape,
torch.device(device),
also_prune_bias,
)
def test_prune_lstm_linear_multiple_layer(self):
"""
Test fusion support for LSTM(multi-layer) -> Linear
"""
model = LSTMLinearModel(
input_dim=8,
hidden_dim=8,
output_dim=8,
num_layers=2,
)
config = [
{"tensor_fqn": "lstm.weight_ih_l0"},
{"tensor_fqn": "lstm.weight_hh_l0"},
{"tensor_fqn": "lstm.weight_ih_l1"},
{"tensor_fqn": "lstm.weight_hh_l1"},
]
lstm_input = torch.ones((1, 8))
fx_pruner = BottomHalfLSTMPruner({"sparsity_level": 0.5})
fx_pruner.prepare(model, config)
fx_pruner.enable_mask_update = True
fx_pruner.step()
model.eval()
_, _ = model(lstm_input)
pruned_model = fx_pruner.prune()
pruned_model.eval()
_, _ = pruned_model(lstm_input)
expected_params = dict(model.named_parameters())
for name, param in model.named_parameters():
assert name in expected_params
# We cannot compare y_expected == y_pruned, as the 0 elements mess up the numerics
# Instead we check that the weights of the new LSTM are a subset of the weights of
# the old LSTM
assert rows_are_subset(param, expected_params[name])
del expected_params[name]
# assert we haven't deleted any keys
assert len(expected_params) == 0
def test_prune_lstm_linear_single_layer(self):
"""
Test fusion support for LSTM (single-layer) -> Linear
"""
model = LSTMLinearModel(
input_dim=8,
hidden_dim=8,
output_dim=8,
num_layers=1,
)
config = [
{"tensor_fqn": "lstm.weight_ih_l0"},
{"tensor_fqn": "lstm.weight_hh_l0"},
]
lstm_input = torch.ones((1, 8))
fx_pruner = BottomHalfLSTMPruner({"sparsity_level": 0.5})
fx_pruner.prepare(model, config)
fx_pruner.enable_mask_update = True
fx_pruner.step()
model.eval()
out_expected, lstm_out_expected = model(lstm_input)
pruned_model = fx_pruner.prune()
pruned_model.eval()
out_pruned, lstm_out_pruned = pruned_model(lstm_input)
r, c = lstm_out_expected.size()
# We cannot check that y_expected == y_pruned as usual because
# zeros vs. missing elements yield different numerical results.
# Instead that we check that the pruned elements are the first half of the results
# since we are using a BottomHalfLSTMPruner
assert torch.isclose(
lstm_out_expected[:, : c // 2], lstm_out_pruned, rtol=1e-05, atol=1e-07
).all()
# also check that output of linear is the same shape, this means we've resized
# linear columns correctly.
assert out_expected.shape == out_pruned.shape
def test_prune_lstm_layernorm_linear_multiple_layer(self):
"""
Test fusion support for LSTM(multi-layer) -> Linear
"""
model = LSTMLayerNormLinearModel(
input_dim=8,
output_dim=8,
hidden_dim=8,
num_layers=2,
)
config = [
{"tensor_fqn": "lstm.weight_ih_l0"},
{"tensor_fqn": "lstm.weight_hh_l0"},
{"tensor_fqn": "lstm.weight_ih_l1"},
{"tensor_fqn": "lstm.weight_hh_l1"},
]
lstm_input = torch.ones((1, 8))
fx_pruner = BottomHalfLSTMPruner({"sparsity_level": 0.5})
fx_pruner.prepare(model, config)
fx_pruner.enable_mask_update = True
fx_pruner.step()
model.eval()
_, _ = model(lstm_input)
pruned_model = fx_pruner.prune()
pruned_model.eval()
_, _ = pruned_model(lstm_input)
expected_params = dict(model.named_parameters())
for name, param in model.named_parameters():
assert name in expected_params
# We cannot compare y_expected == y_pruned, as the 0 elements mess up the numerics
# Instead we check that the weights of the new LSTM are a subset of the weights of
# the old LSTM
assert rows_are_subset(param, expected_params[name])
del expected_params[name]
# assert we haven't deleted any keys
assert len(expected_params) == 0
def test_prune_lstm_layernorm_linear_single_layer(self):
"""
Test fusion support for LSTM (single-layer) -> Linear
"""
model = LSTMLinearModel(
input_dim=8,
hidden_dim=8,
output_dim=8,
num_layers=1,
)
config = [
{"tensor_fqn": "lstm.weight_ih_l0"},
{"tensor_fqn": "lstm.weight_hh_l0"},
]
lstm_input = torch.ones((1, 8))
fx_pruner = BottomHalfLSTMPruner({"sparsity_level": 0.5})
fx_pruner.prepare(model, config)
fx_pruner.enable_mask_update = True
fx_pruner.step()
model.eval()
out_expected, lstm_out_expected = model(lstm_input)
pruned_model = fx_pruner.prune()
pruned_model.eval()
out_pruned, lstm_out_pruned = pruned_model(lstm_input)
r, c = lstm_out_expected.size()
# We cannot check that y_expected == y_pruned as usual because
# zeros vs. missing elements yield different numerical results.
# Instead that we check that the pruned elements are the first half of the results
# since we are using a BottomHalfLSTMPruner
assert torch.isclose(
lstm_out_expected[:, : c // 2], lstm_out_pruned, rtol=1e-05, atol=1e-07
).all()
# also check that output of linear is the same shape, this means we've resized
# linear columns correctly.
assert out_expected.shape == out_pruned.shape
class TestFPGMPruner(TestCase):
"""
Test case for the implementation of paper:
`Filter Pruning via Geometric Median for Deep Convolutional Neural Networks Acceleration <https://arxiv.org/abs/1811.00250>`_.
"""
class SimpleConvFPGM(nn.Module):
def __init__(self) -> None:
super().__init__()
self.conv2d1 = nn.Conv2d(
in_channels=1, out_channels=3, kernel_size=3, padding=1, bias=False
)
# Manually set the filter weights for demonstration purposes
"""
Three filters' weight are manually set to values 3.0, 2.0, and 0.1.
Different from the norm-based decision that prunes filter with value 0.1,
FPGM will prune the one with value 2.0.
"""
weights = torch.tensor([3.0, 2.0, 0.1]) # Weight weights for each filter
weights = weights[:, None, None, None] # broadcasting
self.conv2d1.weight.data.copy_(
torch.ones(self.conv2d1.weight.shape) * weights
)
# Second Convolutional Layer
self.conv2d2 = nn.Conv2d(
in_channels=3, out_channels=4, kernel_size=3, padding=1, bias=False
)
weights = torch.tensor([6.0, 7.0, 0.4, 0.5])
weights = weights[:, None, None, None]
self.conv2d2.weight.data.copy_(
torch.ones(self.conv2d2.weight.shape) * weights
)
def forward(self, x):
x = self.conv2d1(x)
x = self.conv2d2(x)
return x
def test_compute_distance(self, device="cpu"):
"""Test the distance computation function"""
model = TestFPGMPruner.SimpleConvFPGM().to(device)
pruner = FPGMPruner(0.3)
dist_conv1 = pruner._compute_distance(model.conv2d1.weight)
# compute the distance matrix using torch.cdist
flattened_filters = torch.Tensor(
[
[
3.0000,
3.0000,
3.0000,
3.0000,
3.0000,
3.0000,
3.0000,
3.0000,
3.0000,
],
[
2.0000,
2.0000,
2.0000,
2.0000,
2.0000,
2.0000,
2.0000,
2.0000,
2.0000,
],
[
0.1000,
0.1000,
0.1000,
0.1000,
0.1000,
0.1000,
0.1000,
0.1000,
0.1000,
],
]
)
"""
Expected distance matrix should have the following values:
[0.0000, 3.0000, 8.7000],
[3.0000, 0.0000, 5.7000],
[8.7000, 5.7000, 0.0000],
the distance should therefore be:
[11.7000, 8.7000, 14.4000]
"""
expected_dist_matrix_conv1 = torch.cdist(
flattened_filters, flattened_filters, p=2
)
expected_dist_conv1 = torch.sum(torch.abs(expected_dist_matrix_conv1), 1)
assert torch.isclose(
dist_conv1, expected_dist_conv1, rtol=1e-05, atol=1e-07
).all()
def _test_update_mask_on_single_layer(self, expected_conv1, device):
"""Test that pruning is conducted based on the pair-wise distance measurement instead of absolute norm value"""
# test pruning with one layer of conv2d
model = TestFPGMPruner.SimpleConvFPGM().to(device)
x = torch.ones((1, 1, 32, 32), device=device)
pruner = FPGMPruner(0.3)
config = [{"tensor_fqn": "conv2d1.weight"}]
pruner.prepare(model, config)
pruner.enable_mask_update = True
pruner.step()
assert (
pruner.groups[0]["module"].parametrizations.weight[0].mask[-1].item()
is not False
), "do not prune the least-norm filter"
# fusion step
pruned_model = pruner.prune()
pruned_y = pruned_model(x)
# assert shapes
expected_conv1 = expected_conv1.to(device)
assert pruned_y.shape == (1, 4, 32, 32)
assert pruned_model.conv2d1.weight.shape == expected_conv1.shape
assert pruned_model.conv2d2.weight.shape == (
4,
2,
3,
3,
), "conv2d2 should have input channel pruned"
# assert value
assert torch.isclose(
pruned_model.conv2d1.weight, expected_conv1, rtol=1e-05, atol=1e-07
).all()
def _test_update_mask_on_multiple_layer(
self, expected_conv1, expected_conv2, device
):
# the second setting
model = TestFPGMPruner.SimpleConvFPGM().to(device)
x = torch.ones((1, 1, 32, 32), device=device)
pruner = FPGMPruner(0.3)
config = [
{"tensor_fqn": "conv2d1.weight"},
{"tensor_fqn": "conv2d2.weight", "sparsity_level": 0.5},
]
pruner.prepare(model, config)
pruner.enable_mask_update = True
pruner.step()
# Get the masks for the two least-norm filters
mask1 = pruner.groups[0]["module"].parametrizations.weight[0].mask[-1]
mask2 = pruner.groups[0]["module"].parametrizations.weight[0].mask[-2]
# Check if either of the least-norm filters is not pruned
assert (
mask1.item() is not False or mask2.item() is not False
), "Do not prune all least-norm filters"
# fusion step
pruned_model = pruner.prune()
pruned_y = pruned_model(x)
# assert shapes
expected_conv1 = expected_conv1.to(device)
expected_conv2 = expected_conv2.to(device)
assert pruned_y.shape == (1, 2, 32, 32)
assert pruned_model.conv2d1.weight.shape == expected_conv1.shape
assert pruned_model.conv2d2.weight.shape == expected_conv2.shape
# assert values
assert torch.isclose(
pruned_model.conv2d1.weight, expected_conv1, rtol=1e-05, atol=1e-07
).all()
assert torch.isclose(
pruned_model.conv2d2.weight, expected_conv2, rtol=1e-05, atol=1e-07
).all()
def test_update_mask(self):
weights = torch.tensor([3.0, 0.1])
expected_conv1 = torch.ones((2, 1, 3, 3)) * weights[:, None, None, None]
weights = torch.tensor([7.0, 0.4])
expected_conv2 = torch.ones((2, 2, 3, 3)) * weights[:, None, None, None]
for device in DEVICES:
self._test_update_mask_on_single_layer(expected_conv1, device)
self._test_update_mask_on_multiple_layer(
expected_conv1, expected_conv2, device
)
|