File size: 65,589 Bytes
add457a |
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 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 |
# Copyright (C) 2020 NVIDIA Corporation. All rights reserved.
#
# This work is made available under the Nvidia Source Code License-NC.
# To view a copy of this license, check out LICENSE.md
import functools
from torch import nn
from torch.nn import Upsample as NearestUpsample
from torch.utils.checkpoint import checkpoint
from .conv import (Conv1dBlock, Conv2dBlock, Conv3dBlock, HyperConv2dBlock,
LinearBlock, MultiOutConv2dBlock, PartialConv2dBlock,
PartialConv3dBlock)
class _BaseResBlock(nn.Module):
r"""An abstract class for residual blocks.
"""
def __init__(self, in_channels, out_channels, kernel_size,
padding, dilation, groups, bias, padding_mode,
weight_norm_type, weight_norm_params,
activation_norm_type, activation_norm_params,
skip_activation_norm, skip_nonlinearity,
nonlinearity, inplace_nonlinearity, apply_noise,
hidden_channels_equal_out_channels,
order, block, learn_shortcut):
super().__init__()
if order == 'pre_act':
order = 'NACNAC'
if isinstance(bias, bool):
# The bias for conv_block_0, conv_block_1, and conv_block_s.
biases = [bias, bias, bias]
elif isinstance(bias, list):
if len(bias) == 3:
biases = bias
else:
raise ValueError('Bias list must be 3.')
else:
raise ValueError('Bias must be either an integer or s list.')
self.learn_shortcut = (in_channels != out_channels) or learn_shortcut
if len(order) > 6 or len(order) < 5:
raise ValueError('order must be either 5 or 6 characters')
if hidden_channels_equal_out_channels:
hidden_channels = out_channels
else:
hidden_channels = min(in_channels, out_channels)
# Parameters that are specific for convolutions.
conv_main_params = {}
conv_skip_params = {}
if block != LinearBlock:
conv_base_params = dict(stride=1, dilation=dilation,
groups=groups, padding_mode=padding_mode)
conv_main_params.update(conv_base_params)
conv_main_params.update(
dict(kernel_size=kernel_size,
activation_norm_type=activation_norm_type,
activation_norm_params=activation_norm_params,
padding=padding))
conv_skip_params.update(conv_base_params)
conv_skip_params.update(dict(kernel_size=1))
if skip_activation_norm:
conv_skip_params.update(
dict(activation_norm_type=activation_norm_type,
activation_norm_params=activation_norm_params))
# Other parameters.
other_params = dict(weight_norm_type=weight_norm_type,
weight_norm_params=weight_norm_params,
apply_noise=apply_noise)
# Residual branch.
if order.find('A') < order.find('C') and \
(activation_norm_type == '' or activation_norm_type == 'none'):
# Nonlinearity is the first operation in the residual path.
# In-place nonlinearity will modify the input variable and cause
# backward error.
first_inplace = False
else:
first_inplace = inplace_nonlinearity
self.conv_block_0 = block(in_channels, hidden_channels,
bias=biases[0],
nonlinearity=nonlinearity,
order=order[0:3],
inplace_nonlinearity=first_inplace,
**conv_main_params,
**other_params)
self.conv_block_1 = block(hidden_channels, out_channels,
bias=biases[1],
nonlinearity=nonlinearity,
order=order[3:],
inplace_nonlinearity=inplace_nonlinearity,
**conv_main_params,
**other_params)
# Shortcut branch.
if self.learn_shortcut:
if skip_nonlinearity:
skip_nonlinearity_type = nonlinearity
else:
skip_nonlinearity_type = ''
self.conv_block_s = block(in_channels, out_channels,
bias=biases[2],
nonlinearity=skip_nonlinearity_type,
order=order[0:3],
**conv_skip_params,
**other_params)
# Whether this block expects conditional inputs.
self.conditional = \
getattr(self.conv_block_0, 'conditional', False) or \
getattr(self.conv_block_1, 'conditional', False)
def conv_blocks(self, x, *cond_inputs, **kw_cond_inputs):
r"""Returns the output of the residual branch.
Args:
x (tensor): Input tensor.
cond_inputs (list of tensors) : Conditional input tensors.
kw_cond_inputs (dict) : Keyword conditional inputs.
Returns:
dx (tensor): Output tensor.
"""
dx = self.conv_block_0(x, *cond_inputs, **kw_cond_inputs)
dx = self.conv_block_1(dx, *cond_inputs, **kw_cond_inputs)
return dx
def forward(self, x, *cond_inputs, do_checkpoint=False, **kw_cond_inputs):
r"""
Args:
x (tensor): Input tensor.
cond_inputs (list of tensors) : Conditional input tensors.
do_checkpoint (bool, optional, default=``False``) If ``True``,
trade compute for memory by checkpointing the model.
kw_cond_inputs (dict) : Keyword conditional inputs.
Returns:
output (tensor): Output tensor.
"""
if do_checkpoint:
dx = checkpoint(self.conv_blocks, x, *cond_inputs, **kw_cond_inputs)
else:
dx = self.conv_blocks(x, *cond_inputs, **kw_cond_inputs)
if self.learn_shortcut:
x_shortcut = self.conv_block_s(x, *cond_inputs, **kw_cond_inputs)
else:
x_shortcut = x
output = x_shortcut + dx
return output
class ResLinearBlock(_BaseResBlock):
r"""Residual block with full-connected layers.
Args:
in_channels (int) : Number of channels in the input tensor.
out_channels (int) : Number of channels in the output tensor.
weight_norm_type (str, optional, default='none'):
Type of weight normalization.
``'none'``, ``'spectral'``, ``'weight'``
or ``'weight_demod'``.
weight_norm_params (obj, optional, default=None):
Parameters of weight normalization.
If not ``None``, ``weight_norm_params.__dict__`` will be used as
keyword arguments when initializing weight normalization.
activation_norm_type (str, optional, default='none'):
Type of activation normalization.
``'none'``, ``'instance'``, ``'batch'``, ``'sync_batch'``,
``'layer'``, ``'layer_2d'``, ``'group'``, ``'adaptive'``,
``'spatially_adaptive'`` or ``'hyper_spatially_adaptive'``.
activation_norm_params (obj, optional, default=None):
Parameters of activation normalization.
If not ``None``, ``activation_norm_params.__dict__`` will be used as
keyword arguments when initializing activation normalization.
skip_activation_norm (bool, optional, default=True): If ``True`` and
``learn_shortcut`` is also ``True``, applies activation norm to the
learned shortcut connection.
skip_nonlinearity (bool, optional, default=True): If ``True`` and
``learn_shortcut`` is also ``True``, applies nonlinearity to the
learned shortcut connection.
nonlinearity (str, optional, default='none'):
Type of nonlinear activation function in the residual link.
``'none'``, ``'relu'``, ``'leakyrelu'``, ``'prelu'``,
``'tanh'`` , ``'sigmoid'`` or ``'softmax'``.
inplace_nonlinearity (bool, optional, default=False): If ``True``,
set ``inplace=True`` when initializing the nonlinearity layers.
apply_noise (bool, optional, default=False): If ``True``, add
Gaussian noise with learnable magnitude after the
fully-connected layer.
hidden_channels_equal_out_channels (bool, optional, default=False):
If ``True``, set the hidden channel number to be equal to the
output channel number. If ``False``, the hidden channel number
equals to the smaller of the input channel number and the
output channel number.
order (str, optional, default='CNACNA'): Order of operations
in the residual link.
``'C'``: fully-connected,
``'N'``: normalization,
``'A'``: nonlinear activation.
learn_shortcut (bool, optional, default=False): If ``True``, always use
a convolutional shortcut instead of an identity one, otherwise only
use a convolutional one if input and output have different number of
channels.
"""
def __init__(self, in_channels, out_channels, bias=True,
weight_norm_type='none', weight_norm_params=None,
activation_norm_type='none', activation_norm_params=None,
skip_activation_norm=True, skip_nonlinearity=False,
nonlinearity='leakyrelu', inplace_nonlinearity=False,
apply_noise=False, hidden_channels_equal_out_channels=False,
order='CNACNA', learn_shortcut=False):
super().__init__(in_channels, out_channels, None, None,
None, None, bias, None,
weight_norm_type, weight_norm_params,
activation_norm_type, activation_norm_params,
skip_activation_norm, skip_nonlinearity,
nonlinearity, inplace_nonlinearity,
apply_noise, hidden_channels_equal_out_channels,
order, LinearBlock, learn_shortcut)
class Res1dBlock(_BaseResBlock):
r"""Residual block for 1D input.
Args:
in_channels (int) : Number of channels in the input tensor.
out_channels (int) : Number of channels in the output tensor.
kernel_size (int, optional, default=3): Kernel size for the
convolutional filters in the residual link.
padding (int, optional, default=1): Padding size.
dilation (int, optional, default=1): Dilation factor.
groups (int, optional, default=1): Number of convolutional/linear
groups.
padding_mode (string, optional, default='zeros'): Type of padding:
``'zeros'``, ``'reflect'``, ``'replicate'`` or ``'circular'``.
weight_norm_type (str, optional, default='none'):
Type of weight normalization.
``'none'``, ``'spectral'``, ``'weight'``
or ``'weight_demod'``.
weight_norm_params (obj, optional, default=None):
Parameters of weight normalization.
If not ``None``, ``weight_norm_params.__dict__`` will be used as
keyword arguments when initializing weight normalization.
activation_norm_type (str, optional, default='none'):
Type of activation normalization.
``'none'``, ``'instance'``, ``'batch'``, ``'sync_batch'``,
``'layer'``, ``'layer_2d'``, ``'group'``, ``'adaptive'``,
``'spatially_adaptive'`` or ``'hyper_spatially_adaptive'``.
activation_norm_params (obj, optional, default=None):
Parameters of activation normalization.
If not ``None``, ``activation_norm_params.__dict__`` will be used as
keyword arguments when initializing activation normalization.
skip_activation_norm (bool, optional, default=True): If ``True`` and
``learn_shortcut`` is also ``True``, applies activation norm to the
learned shortcut connection.
skip_nonlinearity (bool, optional, default=True): If ``True`` and
``learn_shortcut`` is also ``True``, applies nonlinearity to the
learned shortcut connection.
nonlinearity (str, optional, default='none'):
Type of nonlinear activation function in the residual link.
``'none'``, ``'relu'``, ``'leakyrelu'``, ``'prelu'``,
``'tanh'`` , ``'sigmoid'`` or ``'softmax'``.
inplace_nonlinearity (bool, optional, default=False): If ``True``,
set ``inplace=True`` when initializing the nonlinearity layers.
apply_noise (bool, optional, default=False): If ``True``, adds
Gaussian noise with learnable magnitude to the convolution output.
hidden_channels_equal_out_channels (bool, optional, default=False):
If ``True``, set the hidden channel number to be equal to the
output channel number. If ``False``, the hidden channel number
equals to the smaller of the input channel number and the
output channel number.
order (str, optional, default='CNACNA'): Order of operations
in the residual link.
``'C'``: convolution,
``'N'``: normalization,
``'A'``: nonlinear activation.
learn_shortcut (bool, optional, default=False): If ``True``, always use
a convolutional shortcut instead of an identity one, otherwise only
use a convolutional one if input and output have different number of
channels.
"""
def __init__(self, in_channels, out_channels, kernel_size=3,
padding=1, dilation=1, groups=1, bias=True,
padding_mode='zeros',
weight_norm_type='none', weight_norm_params=None,
activation_norm_type='none', activation_norm_params=None,
skip_activation_norm=True, skip_nonlinearity=False,
nonlinearity='leakyrelu', inplace_nonlinearity=False,
apply_noise=False, hidden_channels_equal_out_channels=False,
order='CNACNA', learn_shortcut=False):
super().__init__(in_channels, out_channels, kernel_size, padding,
dilation, groups, bias, padding_mode,
weight_norm_type, weight_norm_params,
activation_norm_type, activation_norm_params,
skip_activation_norm, skip_nonlinearity,
nonlinearity, inplace_nonlinearity, apply_noise,
hidden_channels_equal_out_channels,
order, Conv1dBlock, learn_shortcut)
class Res2dBlock(_BaseResBlock):
r"""Residual block for 2D input.
Args:
in_channels (int) : Number of channels in the input tensor.
out_channels (int) : Number of channels in the output tensor.
kernel_size (int, optional, default=3): Kernel size for the
convolutional filters in the residual link.
padding (int, optional, default=1): Padding size.
dilation (int, optional, default=1): Dilation factor.
groups (int, optional, default=1): Number of convolutional/linear
groups.
padding_mode (string, optional, default='zeros'): Type of padding:
``'zeros'``, ``'reflect'``, ``'replicate'`` or ``'circular'``.
weight_norm_type (str, optional, default='none'):
Type of weight normalization.
``'none'``, ``'spectral'``, ``'weight'``
or ``'weight_demod'``.
weight_norm_params (obj, optional, default=None):
Parameters of weight normalization.
If not ``None``, ``weight_norm_params.__dict__`` will be used as
keyword arguments when initializing weight normalization.
activation_norm_type (str, optional, default='none'):
Type of activation normalization.
``'none'``, ``'instance'``, ``'batch'``, ``'sync_batch'``,
``'layer'``, ``'layer_2d'``, ``'group'``, ``'adaptive'``,
``'spatially_adaptive'`` or ``'hyper_spatially_adaptive'``.
activation_norm_params (obj, optional, default=None):
Parameters of activation normalization.
If not ``None``, ``activation_norm_params.__dict__`` will be used as
keyword arguments when initializing activation normalization.
skip_activation_norm (bool, optional, default=True): If ``True`` and
``learn_shortcut`` is also ``True``, applies activation norm to the
learned shortcut connection.
skip_nonlinearity (bool, optional, default=True): If ``True`` and
``learn_shortcut`` is also ``True``, applies nonlinearity to the
learned shortcut connection.
nonlinearity (str, optional, default='none'):
Type of nonlinear activation function in the residual link.
``'none'``, ``'relu'``, ``'leakyrelu'``, ``'prelu'``,
``'tanh'`` , ``'sigmoid'`` or ``'softmax'``.
inplace_nonlinearity (bool, optional, default=False): If ``True``,
set ``inplace=True`` when initializing the nonlinearity layers.
apply_noise (bool, optional, default=False): If ``True``, adds
Gaussian noise with learnable magnitude to the convolution output.
hidden_channels_equal_out_channels (bool, optional, default=False):
If ``True``, set the hidden channel number to be equal to the
output channel number. If ``False``, the hidden channel number
equals to the smaller of the input channel number and the
output channel number.
order (str, optional, default='CNACNA'): Order of operations
in the residual link.
``'C'``: convolution,
``'N'``: normalization,
``'A'``: nonlinear activation.
learn_shortcut (bool, optional, default=False): If ``True``, always use
a convolutional shortcut instead of an identity one, otherwise only
use a convolutional one if input and output have different number of
channels.
"""
def __init__(self, in_channels, out_channels, kernel_size=3,
padding=1, dilation=1, groups=1, bias=True,
padding_mode='zeros',
weight_norm_type='none', weight_norm_params=None,
activation_norm_type='none', activation_norm_params=None,
skip_activation_norm=True, skip_nonlinearity=False,
nonlinearity='leakyrelu', inplace_nonlinearity=False,
apply_noise=False, hidden_channels_equal_out_channels=False,
order='CNACNA', learn_shortcut=False):
super().__init__(in_channels, out_channels, kernel_size, padding,
dilation, groups, bias, padding_mode,
weight_norm_type, weight_norm_params,
activation_norm_type, activation_norm_params,
skip_activation_norm, skip_nonlinearity,
nonlinearity, inplace_nonlinearity, apply_noise,
hidden_channels_equal_out_channels,
order, Conv2dBlock, learn_shortcut)
class Res3dBlock(_BaseResBlock):
r"""Residual block for 3D input.
Args:
in_channels (int) : Number of channels in the input tensor.
out_channels (int) : Number of channels in the output tensor.
kernel_size (int, optional, default=3): Kernel size for the
convolutional filters in the residual link.
padding (int, optional, default=1): Padding size.
dilation (int, optional, default=1): Dilation factor.
groups (int, optional, default=1): Number of convolutional/linear
groups.
padding_mode (string, optional, default='zeros'): Type of padding:
``'zeros'``, ``'reflect'``, ``'replicate'`` or ``'circular'``.
weight_norm_type (str, optional, default='none'):
Type of weight normalization.
``'none'``, ``'spectral'``, ``'weight'``
or ``'weight_demod'``.
weight_norm_params (obj, optional, default=None):
Parameters of weight normalization.
If not ``None``, ``weight_norm_params.__dict__`` will be used as
keyword arguments when initializing weight normalization.
activation_norm_type (str, optional, default='none'):
Type of activation normalization.
``'none'``, ``'instance'``, ``'batch'``, ``'sync_batch'``,
``'layer'``, ``'layer_2d'``, ``'group'``, ``'adaptive'``,
``'spatially_adaptive'`` or ``'hyper_spatially_adaptive'``.
activation_norm_params (obj, optional, default=None):
Parameters of activation normalization.
If not ``None``, ``activation_norm_params.__dict__`` will be used as
keyword arguments when initializing activation normalization.
skip_activation_norm (bool, optional, default=True): If ``True`` and
``learn_shortcut`` is also ``True``, applies activation norm to the
learned shortcut connection.
skip_nonlinearity (bool, optional, default=True): If ``True`` and
``learn_shortcut`` is also ``True``, applies nonlinearity to the
learned shortcut connection.
nonlinearity (str, optional, default='none'):
Type of nonlinear activation function in the residual link.
``'none'``, ``'relu'``, ``'leakyrelu'``, ``'prelu'``,
``'tanh'`` , ``'sigmoid'`` or ``'softmax'``.
inplace_nonlinearity (bool, optional, default=False): If ``True``,
set ``inplace=True`` when initializing the nonlinearity layers.
apply_noise (bool, optional, default=False): If ``True``, adds
Gaussian noise with learnable magnitude to the convolution output.
hidden_channels_equal_out_channels (bool, optional, default=False):
If ``True``, set the hidden channel number to be equal to the
output channel number. If ``False``, the hidden channel number
equals to the smaller of the input channel number and the
output channel number.
order (str, optional, default='CNACNA'): Order of operations
in the residual link.
``'C'``: convolution,
``'N'``: normalization,
``'A'``: nonlinear activation.
learn_shortcut (bool, optional, default=False): If ``True``, always use
a convolutional shortcut instead of an identity one, otherwise only
use a convolutional one if input and output have different number of
channels.
"""
def __init__(self, in_channels, out_channels, kernel_size=3,
padding=1, dilation=1, groups=1, bias=True,
padding_mode='zeros',
weight_norm_type='none', weight_norm_params=None,
activation_norm_type='none', activation_norm_params=None,
skip_activation_norm=True, skip_nonlinearity=False,
nonlinearity='leakyrelu', inplace_nonlinearity=False,
apply_noise=False, hidden_channels_equal_out_channels=False,
order='CNACNA', learn_shortcut=False):
super().__init__(in_channels, out_channels, kernel_size, padding,
dilation, groups, bias, padding_mode,
weight_norm_type, weight_norm_params,
activation_norm_type, activation_norm_params,
skip_activation_norm, skip_nonlinearity,
nonlinearity, inplace_nonlinearity, apply_noise,
hidden_channels_equal_out_channels,
order, Conv3dBlock, learn_shortcut)
class _BaseHyperResBlock(_BaseResBlock):
r"""An abstract class for hyper residual blocks.
"""
def __init__(self, in_channels, out_channels, kernel_size,
padding, dilation, groups, bias, padding_mode,
weight_norm_type, weight_norm_params,
activation_norm_type, activation_norm_params,
skip_activation_norm, skip_nonlinearity,
nonlinearity, inplace_nonlinearity, apply_noise,
hidden_channels_equal_out_channels,
order,
is_hyper_conv, is_hyper_norm, block, learn_shortcut):
block = functools.partial(block,
is_hyper_conv=is_hyper_conv,
is_hyper_norm=is_hyper_norm)
super().__init__(in_channels, out_channels, kernel_size, padding,
dilation, groups, bias, padding_mode,
weight_norm_type, weight_norm_params,
activation_norm_type, activation_norm_params,
skip_activation_norm, skip_nonlinearity,
nonlinearity, inplace_nonlinearity, apply_noise,
hidden_channels_equal_out_channels,
order, block, learn_shortcut)
def forward(self, x, *cond_inputs, conv_weights=(None,) * 3,
norm_weights=(None,) * 3, **kw_cond_inputs):
r"""
Args:
x (tensor): Input tensor.
cond_inputs (list of tensors) : Conditional input tensors.
conv_weights (list of tensors): Convolution weights for
three convolutional layers respectively.
norm_weights (list of tensors): Normalization weights for
three convolutional layers respectively.
kw_cond_inputs (dict) : Keyword conditional inputs.
Returns:
output (tensor): Output tensor.
"""
dx = self.conv_block_0(x, *cond_inputs, conv_weights=conv_weights[0],
norm_weights=norm_weights[0])
dx = self.conv_block_1(dx, *cond_inputs, conv_weights=conv_weights[1],
norm_weights=norm_weights[1])
if self.learn_shortcut:
x_shortcut = self.conv_block_s(x, *cond_inputs,
conv_weights=conv_weights[2],
norm_weights=norm_weights[2])
else:
x_shortcut = x
output = x_shortcut + dx
return output
class HyperRes2dBlock(_BaseHyperResBlock):
r"""Hyper residual block for 2D input.
Args:
in_channels (int) : Number of channels in the input tensor.
out_channels (int) : Number of channels in the output tensor.
kernel_size (int, optional, default=3): Kernel size for the
convolutional filters in the residual link.
padding (int, optional, default=1): Padding size.
dilation (int, optional, default=1): Dilation factor.
groups (int, optional, default=1): Number of convolutional/linear
groups.
padding_mode (string, optional, default='zeros'): Type of padding:
``'zeros'``, ``'reflect'``, ``'replicate'`` or ``'circular'``.
weight_norm_type (str, optional, default='none'):
Type of weight normalization.
``'none'``, ``'spectral'``, ``'weight'``
or ``'weight_demod'``.
weight_norm_params (obj, optional, default=None):
Parameters of weight normalization.
If not ``None``, ``weight_norm_params.__dict__`` will be used as
keyword arguments when initializing weight normalization.
activation_norm_type (str, optional, default='none'):
Type of activation normalization.
``'none'``, ``'instance'``, ``'batch'``, ``'sync_batch'``,
``'layer'``, ``'layer_2d'``, ``'group'``, ``'adaptive'``,
``'spatially_adaptive'`` or ``'hyper_spatially_adaptive'``.
activation_norm_params (obj, optional, default=None):
Parameters of activation normalization.
If not ``None``, ``activation_norm_params.__dict__`` will be used as
keyword arguments when initializing activation normalization.
skip_activation_norm (bool, optional, default=True): If ``True`` and
``learn_shortcut`` is also ``True``, applies activation norm to the
learned shortcut connection.
skip_nonlinearity (bool, optional, default=True): If ``True`` and
``learn_shortcut`` is also ``True``, applies nonlinearity to the
learned shortcut connection.
nonlinearity (str, optional, default='none'):
Type of nonlinear activation function in the residual link.
``'none'``, ``'relu'``, ``'leakyrelu'``, ``'prelu'``,
``'tanh'`` , ``'sigmoid'`` or ``'softmax'``.
inplace_nonlinearity (bool, optional, default=False): If ``True``,
set ``inplace=True`` when initializing the nonlinearity layers.
apply_noise (bool, optional, default=False): If ``True``, adds
Gaussian noise with learnable magnitude to the convolution output.
hidden_channels_equal_out_channels (bool, optional, default=False):
If ``True``, set the hidden channel number to be equal to the
output channel number. If ``False``, the hidden channel number
equals to the smaller of the input channel number and the
output channel number.
order (str, optional, default='CNACNA'): Order of operations
in the residual link.
``'C'``: convolution,
``'N'``: normalization,
``'A'``: nonlinear activation.
is_hyper_conv (bool, optional, default=False): If ``True``, use
``HyperConv2d``, otherwise use ``torch.nn.Conv2d``.
is_hyper_norm (bool, optional, default=False): If ``True``, use
hyper normalizations.
learn_shortcut (bool, optional, default=False): If ``True``, always use
a convolutional shortcut instead of an identity one, otherwise only
use a convolutional one if input and output have different number of
channels.
"""
def __init__(self, in_channels, out_channels, kernel_size=3,
padding=1, dilation=1, groups=1, bias=True,
padding_mode='zeros',
weight_norm_type='', weight_norm_params=None,
activation_norm_type='', activation_norm_params=None,
skip_activation_norm=True, skip_nonlinearity=False,
nonlinearity='leakyrelu', inplace_nonlinearity=False,
apply_noise=False, hidden_channels_equal_out_channels=False,
order='CNACNA', is_hyper_conv=False, is_hyper_norm=False,
learn_shortcut=False):
super().__init__(in_channels, out_channels, kernel_size, padding,
dilation, groups, bias, padding_mode,
weight_norm_type, weight_norm_params,
activation_norm_type, activation_norm_params,
skip_activation_norm, skip_nonlinearity,
nonlinearity, inplace_nonlinearity, apply_noise,
hidden_channels_equal_out_channels,
order, is_hyper_conv, is_hyper_norm,
HyperConv2dBlock, learn_shortcut)
class _BaseDownResBlock(_BaseResBlock):
r"""An abstract class for residual blocks with downsampling.
"""
def __init__(self, in_channels, out_channels, kernel_size,
padding, dilation, groups, bias, padding_mode,
weight_norm_type, weight_norm_params,
activation_norm_type, activation_norm_params,
skip_activation_norm, skip_nonlinearity,
nonlinearity, inplace_nonlinearity,
apply_noise, hidden_channels_equal_out_channels,
order, block, pooling, down_factor, learn_shortcut):
super().__init__(in_channels, out_channels, kernel_size, padding,
dilation, groups, bias, padding_mode,
weight_norm_type, weight_norm_params,
activation_norm_type, activation_norm_params,
skip_activation_norm, skip_nonlinearity,
nonlinearity, inplace_nonlinearity,
apply_noise, hidden_channels_equal_out_channels,
order, block, learn_shortcut)
self.pooling = pooling(down_factor)
def forward(self, x, *cond_inputs):
r"""
Args:
x (tensor) : Input tensor.
cond_inputs (list of tensors) : conditional input.
Returns:
output (tensor) : Output tensor.
"""
dx = self.conv_block_0(x, *cond_inputs)
dx = self.conv_block_1(dx, *cond_inputs)
dx = self.pooling(dx)
if self.learn_shortcut:
x_shortcut = self.conv_block_s(x, *cond_inputs)
else:
x_shortcut = x
x_shortcut = self.pooling(x_shortcut)
output = x_shortcut + dx
return output
class DownRes2dBlock(_BaseDownResBlock):
r"""Residual block for 2D input with downsampling.
Args:
in_channels (int) : Number of channels in the input tensor.
out_channels (int) : Number of channels in the output tensor.
kernel_size (int, optional, default=3): Kernel size for the
convolutional filters in the residual link.
padding (int, optional, default=1): Padding size.
dilation (int, optional, default=1): Dilation factor.
groups (int, optional, default=1): Number of convolutional/linear
groups.
padding_mode (string, optional, default='zeros'): Type of padding:
``'zeros'``, ``'reflect'``, ``'replicate'`` or ``'circular'``.
weight_norm_type (str, optional, default='none'):
Type of weight normalization.
``'none'``, ``'spectral'``, ``'weight'``
or ``'weight_demod'``.
weight_norm_params (obj, optional, default=None):
Parameters of weight normalization.
If not ``None``, ``weight_norm_params.__dict__`` will be used as
keyword arguments when initializing weight normalization.
activation_norm_type (str, optional, default='none'):
Type of activation normalization.
``'none'``, ``'instance'``, ``'batch'``, ``'sync_batch'``,
``'layer'``, ``'layer_2d'``, ``'group'``, ``'adaptive'``,
``'spatially_adaptive'`` or ``'hyper_spatially_adaptive'``.
activation_norm_params (obj, optional, default=None):
Parameters of activation normalization.
If not ``None``, ``activation_norm_params.__dict__`` will be used as
keyword arguments when initializing activation normalization.
skip_activation_norm (bool, optional, default=True): If ``True`` and
``learn_shortcut`` is also ``True``, applies activation norm to the
learned shortcut connection.
skip_nonlinearity (bool, optional, default=True): If ``True`` and
``learn_shortcut`` is also ``True``, applies nonlinearity to the
learned shortcut connection.
nonlinearity (str, optional, default='none'):
Type of nonlinear activation function in the residual link.
``'none'``, ``'relu'``, ``'leakyrelu'``, ``'prelu'``,
``'tanh'`` , ``'sigmoid'`` or ``'softmax'``.
inplace_nonlinearity (bool, optional, default=False): If ``True``,
set ``inplace=True`` when initializing the nonlinearity layers.
apply_noise (bool, optional, default=False): If ``True``, adds
Gaussian noise with learnable magnitude to the convolution output.
hidden_channels_equal_out_channels (bool, optional, default=False):
If ``True``, set the hidden channel number to be equal to the
output channel number. If ``False``, the hidden channel number
equals to the smaller of the input channel number and the
output channel number.
order (str, optional, default='CNACNA'): Order of operations
in the residual link.
``'C'``: convolution,
``'N'``: normalization,
``'A'``: nonlinear activation.
pooling (class, optional, default=nn.AvgPool2d): Pytorch pooling
layer to be used.
down_factor (int, optional, default=2): Downsampling factor.
learn_shortcut (bool, optional, default=False): If ``True``, always use
a convolutional shortcut instead of an identity one, otherwise only
use a convolutional one if input and output have different number of
channels.
"""
def __init__(self, in_channels, out_channels, kernel_size=3,
padding=1, dilation=1, groups=1, bias=True,
padding_mode='zeros',
weight_norm_type='none', weight_norm_params=None,
activation_norm_type='none', activation_norm_params=None,
skip_activation_norm=True, skip_nonlinearity=False,
nonlinearity='leakyrelu', inplace_nonlinearity=False,
apply_noise=False, hidden_channels_equal_out_channels=False,
order='CNACNA', pooling=nn.AvgPool2d, down_factor=2,
learn_shortcut=False):
super().__init__(in_channels, out_channels, kernel_size, padding,
dilation, groups, bias, padding_mode,
weight_norm_type, weight_norm_params,
activation_norm_type, activation_norm_params,
skip_activation_norm, skip_nonlinearity,
nonlinearity, inplace_nonlinearity, apply_noise,
hidden_channels_equal_out_channels,
order, Conv2dBlock, pooling,
down_factor, learn_shortcut)
class _BaseUpResBlock(_BaseResBlock):
r"""An abstract class for residual blocks with upsampling.
"""
def __init__(self, in_channels, out_channels, kernel_size,
padding, dilation, groups, bias, padding_mode,
weight_norm_type, weight_norm_params,
activation_norm_type, activation_norm_params,
skip_activation_norm, skip_nonlinearity,
nonlinearity, inplace_nonlinearity,
apply_noise, hidden_channels_equal_out_channels,
order, block, upsample, up_factor, learn_shortcut):
super().__init__(in_channels, out_channels, kernel_size, padding,
dilation, groups, bias, padding_mode,
weight_norm_type, weight_norm_params,
activation_norm_type, activation_norm_params,
skip_activation_norm, skip_nonlinearity,
nonlinearity, inplace_nonlinearity,
apply_noise, hidden_channels_equal_out_channels,
order, block, learn_shortcut)
self.order = order
self.upsample = upsample(scale_factor=up_factor)
def forward(self, x, *cond_inputs):
r"""Implementation of the up residual block forward function.
If the order is 'NAC' for the first residual block, we will first
do the activation norm and nonlinearity, in the original resolution.
We will then upsample the activation map to a higher resolution. We
then do the convolution.
It is is other orders, then we first do the whole processing and
then upsample.
Args:
x (tensor) : Input tensor.
cond_inputs (list of tensors) : Conditional input.
Returns:
output (tensor) : Output tensor.
"""
# In this particular upsample residual block operation, we first
# upsample the skip connection.
if self.learn_shortcut:
x_shortcut = self.upsample(x)
x_shortcut = self.conv_block_s(x_shortcut, *cond_inputs)
else:
x_shortcut = self.upsample(x)
if self.order[0:3] == 'NAC':
for ix, layer in enumerate(self.conv_block_0.layers.values()):
if getattr(layer, 'conditional', False):
x = layer(x, *cond_inputs)
else:
x = layer(x)
if ix == 1:
x = self.upsample(x)
else:
x = self.conv_block_0(x, *cond_inputs)
x = self.upsample(x)
x = self.conv_block_1(x, *cond_inputs)
output = x_shortcut + x
return output
class UpRes2dBlock(_BaseUpResBlock):
r"""Residual block for 2D input with downsampling.
Args:
in_channels (int) : Number of channels in the input tensor.
out_channels (int) : Number of channels in the output tensor.
kernel_size (int, optional, default=3): Kernel size for the
convolutional filters in the residual link.
padding (int, optional, default=1): Padding size.
dilation (int, optional, default=1): Dilation factor.
groups (int, optional, default=1): Number of convolutional/linear
groups.
padding_mode (string, optional, default='zeros'): Type of padding:
``'zeros'``, ``'reflect'``, ``'replicate'`` or ``'circular'``.
weight_norm_type (str, optional, default='none'):
Type of weight normalization.
``'none'``, ``'spectral'``, ``'weight'``
or ``'weight_demod'``.
weight_norm_params (obj, optional, default=None):
Parameters of weight normalization.
If not ``None``, ``weight_norm_params.__dict__`` will be used as
keyword arguments when initializing weight normalization.
activation_norm_type (str, optional, default='none'):
Type of activation normalization.
``'none'``, ``'instance'``, ``'batch'``, ``'sync_batch'``,
``'layer'``, ``'layer_2d'``, ``'group'``, ``'adaptive'``,
``'spatially_adaptive'`` or ``'hyper_spatially_adaptive'``.
activation_norm_params (obj, optional, default=None):
Parameters of activation normalization.
If not ``None``, ``activation_norm_params.__dict__`` will be used as
keyword arguments when initializing activation normalization.
skip_activation_norm (bool, optional, default=True): If ``True`` and
``learn_shortcut`` is also ``True``, applies activation norm to the
learned shortcut connection.
skip_nonlinearity (bool, optional, default=True): If ``True`` and
``learn_shortcut`` is also ``True``, applies nonlinearity to the
learned shortcut connection.
nonlinearity (str, optional, default='none'):
Type of nonlinear activation function in the residual link.
``'none'``, ``'relu'``, ``'leakyrelu'``, ``'prelu'``,
``'tanh'`` , ``'sigmoid'`` or ``'softmax'``.
inplace_nonlinearity (bool, optional, default=False): If ``True``,
set ``inplace=True`` when initializing the nonlinearity layers.
apply_noise (bool, optional, default=False): If ``True``, adds
Gaussian noise with learnable magnitude to the convolution output.
hidden_channels_equal_out_channels (bool, optional, default=False):
If ``True``, set the hidden channel number to be equal to the
output channel number. If ``False``, the hidden channel number
equals to the smaller of the input channel number and the
output channel number.
order (str, optional, default='CNACNA'): Order of operations
in the residual link.
``'C'``: convolution,
``'N'``: normalization,
``'A'``: nonlinear activation.
upsample (class, optional, default=NearestUpsample): PPytorch
upsampling layer to be used.
up_factor (int, optional, default=2): Upsampling factor.
learn_shortcut (bool, optional, default=False): If ``True``, always use
a convolutional shortcut instead of an identity one, otherwise only
use a convolutional one if input and output have different number of
channels.
"""
def __init__(self, in_channels, out_channels, kernel_size=3,
padding=1, dilation=1, groups=1, bias=True,
padding_mode='zeros',
weight_norm_type='none', weight_norm_params=None,
activation_norm_type='none', activation_norm_params=None,
skip_activation_norm=True, skip_nonlinearity=False,
nonlinearity='leakyrelu', inplace_nonlinearity=False,
apply_noise=False, hidden_channels_equal_out_channels=False,
order='CNACNA', upsample=NearestUpsample, up_factor=2,
learn_shortcut=False):
super().__init__(in_channels, out_channels, kernel_size, padding,
dilation, groups, bias, padding_mode,
weight_norm_type, weight_norm_params,
activation_norm_type, activation_norm_params,
skip_activation_norm, skip_nonlinearity,
nonlinearity, inplace_nonlinearity,
apply_noise, hidden_channels_equal_out_channels,
order, Conv2dBlock,
upsample, up_factor, learn_shortcut)
class _BasePartialResBlock(_BaseResBlock):
r"""An abstract class for residual blocks with partial convolution.
"""
def __init__(self, in_channels, out_channels, kernel_size,
padding, dilation, groups, bias, padding_mode,
weight_norm_type, weight_norm_params,
activation_norm_type, activation_norm_params,
skip_activation_norm, skip_nonlinearity,
nonlinearity, inplace_nonlinearity,
multi_channel, return_mask,
apply_noise, hidden_channels_equal_out_channels,
order, block, learn_shortcut):
block = functools.partial(block,
multi_channel=multi_channel,
return_mask=return_mask)
self.partial_conv = True
super().__init__(in_channels, out_channels, kernel_size, padding,
dilation, groups, bias, padding_mode,
weight_norm_type, weight_norm_params,
activation_norm_type, activation_norm_params,
skip_activation_norm, skip_nonlinearity,
nonlinearity, inplace_nonlinearity,
apply_noise, hidden_channels_equal_out_channels,
order, block, learn_shortcut)
def forward(self, x, *cond_inputs, mask_in=None, **kw_cond_inputs):
r"""
Args:
x (tensor): Input tensor.
cond_inputs (list of tensors) : Conditional input tensors.
mask_in (tensor, optional, default=``None``) If not ``None``,
it masks the valid input region.
kw_cond_inputs (dict) : Keyword conditional inputs.
Returns:
(tuple):
- output (tensor): Output tensor.
- mask_out (tensor, optional): Masks the valid output region.
"""
if self.conv_block_0.layers.conv.return_mask:
dx, mask_out = self.conv_block_0(x, *cond_inputs,
mask_in=mask_in, **kw_cond_inputs)
dx, mask_out = self.conv_block_1(dx, *cond_inputs,
mask_in=mask_out, **kw_cond_inputs)
else:
dx = self.conv_block_0(x, *cond_inputs,
mask_in=mask_in, **kw_cond_inputs)
dx = self.conv_block_1(dx, *cond_inputs,
mask_in=mask_in, **kw_cond_inputs)
mask_out = None
if self.learn_shortcut:
x_shortcut = self.conv_block_s(x, mask_in=mask_in, *cond_inputs,
**kw_cond_inputs)
if type(x_shortcut) == tuple:
x_shortcut, _ = x_shortcut
else:
x_shortcut = x
output = x_shortcut + dx
if mask_out is not None:
return output, mask_out
return output
class PartialRes2dBlock(_BasePartialResBlock):
r"""Residual block for 2D input with partial convolution.
Args:
in_channels (int) : Number of channels in the input tensor.
out_channels (int) : Number of channels in the output tensor.
kernel_size (int, optional, default=3): Kernel size for the
convolutional filters in the residual link.
padding (int, optional, default=1): Padding size.
dilation (int, optional, default=1): Dilation factor.
groups (int, optional, default=1): Number of convolutional/linear
groups.
padding_mode (string, optional, default='zeros'): Type of padding:
``'zeros'``, ``'reflect'``, ``'replicate'`` or ``'circular'``.
weight_norm_type (str, optional, default='none'):
Type of weight normalization.
``'none'``, ``'spectral'``, ``'weight'``
or ``'weight_demod'``.
weight_norm_params (obj, optional, default=None):
Parameters of weight normalization.
If not ``None``, ``weight_norm_params.__dict__`` will be used as
keyword arguments when initializing weight normalization.
activation_norm_type (str, optional, default='none'):
Type of activation normalization.
``'none'``, ``'instance'``, ``'batch'``, ``'sync_batch'``,
``'layer'``, ``'layer_2d'``, ``'group'``, ``'adaptive'``,
``'spatially_adaptive'`` or ``'hyper_spatially_adaptive'``.
activation_norm_params (obj, optional, default=None):
Parameters of activation normalization.
If not ``None``, ``activation_norm_params.__dict__`` will be used as
keyword arguments when initializing activation normalization.
skip_activation_norm (bool, optional, default=True): If ``True`` and
``learn_shortcut`` is also ``True``, applies activation norm to the
learned shortcut connection.
skip_nonlinearity (bool, optional, default=True): If ``True`` and
``learn_shortcut`` is also ``True``, applies nonlinearity to the
learned shortcut connection.
nonlinearity (str, optional, default='none'):
Type of nonlinear activation function in the residual link.
``'none'``, ``'relu'``, ``'leakyrelu'``, ``'prelu'``,
``'tanh'`` , ``'sigmoid'`` or ``'softmax'``.
inplace_nonlinearity (bool, optional, default=False): If ``True``,
set ``inplace=True`` when initializing the nonlinearity layers.
apply_noise (bool, optional, default=False): If ``True``, adds
Gaussian noise with learnable magnitude to the convolution output.
hidden_channels_equal_out_channels (bool, optional, default=False):
If ``True``, set the hidden channel number to be equal to the
output channel number. If ``False``, the hidden channel number
equals to the smaller of the input channel number and the
output channel number.
order (str, optional, default='CNACNA'): Order of operations
in the residual link.
``'C'``: convolution,
``'N'``: normalization,
``'A'``: nonlinear activation.
learn_shortcut (bool, optional, default=False): If ``True``, always use
a convolutional shortcut instead of an identity one, otherwise only
use a convolutional one if input and output have different number of
channels.
"""
def __init__(self, in_channels, out_channels, kernel_size=3,
padding=1, dilation=1, groups=1, bias=True,
padding_mode='zeros',
weight_norm_type='none', weight_norm_params=None,
activation_norm_type='none', activation_norm_params=None,
skip_activation_norm=True, skip_nonlinearity=False,
nonlinearity='leakyrelu', inplace_nonlinearity=False,
multi_channel=False, return_mask=True,
apply_noise=False,
hidden_channels_equal_out_channels=False,
order='CNACNA', learn_shortcut=False):
super().__init__(in_channels, out_channels, kernel_size, padding,
dilation, groups, bias, padding_mode,
weight_norm_type, weight_norm_params,
activation_norm_type, activation_norm_params,
skip_activation_norm, skip_nonlinearity,
nonlinearity, inplace_nonlinearity,
multi_channel, return_mask,
apply_noise, hidden_channels_equal_out_channels,
order, PartialConv2dBlock, learn_shortcut)
class PartialRes3dBlock(_BasePartialResBlock):
r"""Residual block for 3D input with partial convolution.
Args:
in_channels (int) : Number of channels in the input tensor.
out_channels (int) : Number of channels in the output tensor.
kernel_size (int, optional, default=3): Kernel size for the
convolutional filters in the residual link.
padding (int, optional, default=1): Padding size.
dilation (int, optional, default=1): Dilation factor.
groups (int, optional, default=1): Number of convolutional/linear
groups.
padding_mode (string, optional, default='zeros'): Type of padding:
``'zeros'``, ``'reflect'``, ``'replicate'`` or ``'circular'``.
weight_norm_type (str, optional, default='none'):
Type of weight normalization.
``'none'``, ``'spectral'``, ``'weight'``
or ``'weight_demod'``.
weight_norm_params (obj, optional, default=None):
Parameters of weight normalization.
If not ``None``, ``weight_norm_params.__dict__`` will be used as
keyword arguments when initializing weight normalization.
activation_norm_type (str, optional, default='none'):
Type of activation normalization.
``'none'``, ``'instance'``, ``'batch'``, ``'sync_batch'``,
``'layer'``, ``'layer_2d'``, ``'group'``, ``'adaptive'``,
``'spatially_adaptive'`` or ``'hyper_spatially_adaptive'``.
activation_norm_params (obj, optional, default=None):
Parameters of activation normalization.
If not ``None``, ``activation_norm_params.__dict__`` will be used as
keyword arguments when initializing activation normalization.
skip_activation_norm (bool, optional, default=True): If ``True`` and
``learn_shortcut`` is also ``True``, applies activation norm to the
learned shortcut connection.
skip_nonlinearity (bool, optional, default=True): If ``True`` and
``learn_shortcut`` is also ``True``, applies nonlinearity to the
learned shortcut connection.
nonlinearity (str, optional, default='none'):
Type of nonlinear activation function in the residual link.
``'none'``, ``'relu'``, ``'leakyrelu'``, ``'prelu'``,
``'tanh'`` , ``'sigmoid'`` or ``'softmax'``.
inplace_nonlinearity (bool, optional, default=False): If ``True``,
set ``inplace=True`` when initializing the nonlinearity layers.
apply_noise (bool, optional, default=False): If ``True``, adds
Gaussian noise with learnable magnitude to the convolution output.
hidden_channels_equal_out_channels (bool, optional, default=False):
If ``True``, set the hidden channel number to be equal to the
output channel number. If ``False``, the hidden channel number
equals to the smaller of the input channel number and the
output channel number.
order (str, optional, default='CNACNA'): Order of operations
in the residual link.
``'C'``: convolution,
``'N'``: normalization,
``'A'``: nonlinear activation.
learn_shortcut (bool, optional, default=False): If ``True``, always use
a convolutional shortcut instead of an identity one, otherwise only
use a convolutional one if input and output have different number of
channels.
"""
def __init__(self, in_channels, out_channels, kernel_size=3,
padding=1, dilation=1, groups=1, bias=True,
padding_mode='zeros',
weight_norm_type='none', weight_norm_params=None,
activation_norm_type='none', activation_norm_params=None,
skip_activation_norm=True, skip_nonlinearity=False,
nonlinearity='leakyrelu', inplace_nonlinearity=False,
multi_channel=False, return_mask=True,
apply_noise=False, hidden_channels_equal_out_channels=False,
order='CNACNA', learn_shortcut=False):
super().__init__(in_channels, out_channels, kernel_size, padding,
dilation, groups, bias, padding_mode,
weight_norm_type, weight_norm_params,
activation_norm_type, activation_norm_params,
skip_activation_norm, skip_nonlinearity,
nonlinearity, inplace_nonlinearity,
multi_channel, return_mask,
apply_noise, hidden_channels_equal_out_channels,
order, PartialConv3dBlock, learn_shortcut)
class _BaseMultiOutResBlock(_BaseResBlock):
r"""An abstract class for residual blocks that can returns multiple outputs.
"""
def __init__(self, in_channels, out_channels, kernel_size,
padding, dilation, groups, bias, padding_mode,
weight_norm_type, weight_norm_params,
activation_norm_type, activation_norm_params,
skip_activation_norm, skip_nonlinearity,
nonlinearity, inplace_nonlinearity,
apply_noise, hidden_channels_equal_out_channels,
order, block, learn_shortcut):
self.multiple_outputs = True
super().__init__(in_channels, out_channels, kernel_size, padding,
dilation, groups, bias, padding_mode,
weight_norm_type, weight_norm_params,
activation_norm_type, activation_norm_params,
skip_activation_norm, skip_nonlinearity,
nonlinearity, inplace_nonlinearity, apply_noise,
hidden_channels_equal_out_channels,
order, block, learn_shortcut)
def forward(self, x, *cond_inputs):
r"""
Args:
x (tensor): Input tensor.
cond_inputs (list of tensors) : Conditional input tensors.
Returns:
(tuple):
- output (tensor): Output tensor.
- aux_outputs_0 (tensor): Auxiliary output of the first block.
- aux_outputs_1 (tensor): Auxiliary output of the second block.
"""
dx, aux_outputs_0 = self.conv_block_0(x, *cond_inputs)
dx, aux_outputs_1 = self.conv_block_1(dx, *cond_inputs)
if self.learn_shortcut:
# We are not using the auxiliary outputs of self.conv_block_s.
x_shortcut, _ = self.conv_block_s(x, *cond_inputs)
else:
x_shortcut = x
output = x_shortcut + dx
return output, aux_outputs_0, aux_outputs_1
class MultiOutRes2dBlock(_BaseMultiOutResBlock):
r"""Residual block for 2D input. It can return multiple outputs, if some
layers in the block return more than one output.
Args:
in_channels (int) : Number of channels in the input tensor.
out_channels (int) : Number of channels in the output tensor.
kernel_size (int, optional, default=3): Kernel size for the
convolutional filters in the residual link.
padding (int, optional, default=1): Padding size.
dilation (int, optional, default=1): Dilation factor.
groups (int, optional, default=1): Number of convolutional/linear
groups.
padding_mode (string, optional, default='zeros'): Type of padding:
``'zeros'``, ``'reflect'``, ``'replicate'`` or ``'circular'``.
weight_norm_type (str, optional, default='none'):
Type of weight normalization.
``'none'``, ``'spectral'``, ``'weight'``
or ``'weight_demod'``.
weight_norm_params (obj, optional, default=None):
Parameters of weight normalization.
If not ``None``, ``weight_norm_params.__dict__`` will be used as
keyword arguments when initializing weight normalization.
activation_norm_type (str, optional, default='none'):
Type of activation normalization.
``'none'``, ``'instance'``, ``'batch'``, ``'sync_batch'``,
``'layer'``, ``'layer_2d'``, ``'group'``, ``'adaptive'``,
``'spatially_adaptive'`` or ``'hyper_spatially_adaptive'``.
activation_norm_params (obj, optional, default=None):
Parameters of activation normalization.
If not ``None``, ``activation_norm_params.__dict__`` will be used as
keyword arguments when initializing activation normalization.
skip_activation_norm (bool, optional, default=True): If ``True`` and
``learn_shortcut`` is also ``True``, applies activation norm to the
learned shortcut connection.
skip_nonlinearity (bool, optional, default=True): If ``True`` and
``learn_shortcut`` is also ``True``, applies nonlinearity to the
learned shortcut connection.
nonlinearity (str, optional, default='none'):
Type of nonlinear activation function in the residual link.
``'none'``, ``'relu'``, ``'leakyrelu'``, ``'prelu'``,
``'tanh'`` , ``'sigmoid'`` or ``'softmax'``.
inplace_nonlinearity (bool, optional, default=False): If ``True``,
set ``inplace=True`` when initializing the nonlinearity layers.
apply_noise (bool, optional, default=False): If ``True``, adds
Gaussian noise with learnable magnitude to the convolution output.
hidden_channels_equal_out_channels (bool, optional, default=False):
If ``True``, set the hidden channel number to be equal to the
output channel number. If ``False``, the hidden channel number
equals to the smaller of the input channel number and the
output channel number.
order (str, optional, default='CNACNA'): Order of operations
in the residual link.
``'C'``: convolution,
``'N'``: normalization,
``'A'``: nonlinear activation.
learn_shortcut (bool, optional, default=False): If ``True``, always use
a convolutional shortcut instead of an identity one, otherwise only
use a convolutional one if input and output have different number of
channels.
"""
def __init__(self, in_channels, out_channels, kernel_size=3,
padding=1, dilation=1, groups=1, bias=True,
padding_mode='zeros',
weight_norm_type='none', weight_norm_params=None,
activation_norm_type='none', activation_norm_params=None,
skip_activation_norm=True, skip_nonlinearity=False,
nonlinearity='leakyrelu', inplace_nonlinearity=False,
apply_noise=False, hidden_channels_equal_out_channels=False,
order='CNACNA', learn_shortcut=False):
super().__init__(in_channels, out_channels, kernel_size, padding,
dilation, groups, bias, padding_mode,
weight_norm_type, weight_norm_params,
activation_norm_type, activation_norm_params,
skip_activation_norm, skip_nonlinearity,
nonlinearity, inplace_nonlinearity,
apply_noise, hidden_channels_equal_out_channels,
order, MultiOutConv2dBlock, learn_shortcut)
|