code
stringlengths
17
6.64M
@HEADS.register_module() class PanopticFPNHead(BaseSemanticHead): 'PanopticFPNHead used in Panoptic FPN.\n\n In this head, the number of output channels is ``num_stuff_classes\n + 1``, including all stuff classes and one thing class. The stuff\n classes will be reset from ``0`` to ``num_stuff_classes - 1...
class BasePanopticFusionHead(BaseModule, metaclass=ABCMeta): 'Base class for panoptic heads.' def __init__(self, num_things_classes=80, num_stuff_classes=53, test_cfg=None, loss_panoptic=None, init_cfg=None, **kwargs): super(BasePanopticFusionHead, self).__init__(init_cfg) self.num_things_cla...
def adaptive_avg_pool2d(input, output_size): 'Handle empty batch dimension to adaptive_avg_pool2d.\n\n Args:\n input (tensor): 4D tensor.\n output_size (int, tuple[int,int]): the target output size.\n ' if ((input.numel() == 0) and obsolete_torch_version(TORCH_VERSION, (1, 9))): if...
class AdaptiveAvgPool2d(nn.AdaptiveAvgPool2d): 'Handle empty batch dimension to AdaptiveAvgPool2d.' def forward(self, x): if ((x.numel() == 0) and obsolete_torch_version(TORCH_VERSION, (1, 9))): output_size = self.output_size if isinstance(output_size, int): ou...
def build_transformer(cfg, default_args=None): 'Builder for Transformer.' return build_from_cfg(cfg, TRANSFORMER, default_args)
def build_linear_layer(cfg, *args, **kwargs): 'Build linear layer.\n Args:\n cfg (None or dict): The linear layer config, which should contain:\n - type (str): Layer type.\n - layer args: Args needed to instantiate an linear layer.\n args (argument list): Arguments passed to...
class ConvUpsample(BaseModule): 'ConvUpsample performs 2x upsampling after Conv.\n\n There are several `ConvModule` layers. In the first few layers, upsampling\n will be applied after each layer of convolution. The number of upsampling\n must be no more than the number of ConvModule layers.\n\n Args:\...
class DarknetBottleneck(BaseModule): "The basic bottleneck block used in Darknet.\n\n Each ResBlock consists of two ConvModules and the input is added to the\n final output. Each ConvModule is composed of Conv, BN, and LeakyReLU.\n The first convLayer has filter size of 1x1 and the second one has the\n ...
class CSPLayer(BaseModule): "Cross Stage Partial Layer.\n\n Args:\n in_channels (int): The input channels of the CSP layer.\n out_channels (int): The output channels of the CSP layer.\n expand_ratio (float): Ratio to adjust the number of channels of the\n hidden layer. Default: ...
class InvertedResidual(BaseModule): "Inverted Residual Block.\n\n Args:\n in_channels (int): The input channels of this Module.\n out_channels (int): The output channels of this Module.\n mid_channels (int): The input channels of the depthwise convolution.\n kernel_size (int): The k...
def make_divisible(value, divisor, min_value=None, min_ratio=0.9): 'Make divisible function.\n\n This function rounds the channel number to the nearest value that can be\n divisible by the divisor. It is taken from the original tf repo. It ensures\n that all layers have a channel number that is divisible...
@LINEAR_LAYERS.register_module(name='NormedLinear') class NormedLinear(nn.Linear): 'Normalized Linear Layer.\n\n Args:\n tempeature (float, optional): Tempeature term. Default to 20.\n power (int, optional): Power term. Default to 1.0.\n eps (float, optional): The minimal value of divisor ...
@CONV_LAYERS.register_module(name='NormedConv2d') class NormedConv2d(nn.Conv2d): 'Normalized Conv2d Layer.\n\n Args:\n tempeature (float, optional): Tempeature term. Default to 20.\n power (int, optional): Power term. Default to 1.0.\n eps (float, optional): The minimal value of divisor to...
def preprocess_panoptic_gt(gt_labels, gt_masks, gt_semantic_seg, num_things, num_stuff): 'Preprocess the ground truth for a image.\n\n Args:\n gt_labels (Tensor): Ground truth labels of each bbox,\n with shape (num_gts, ).\n gt_masks (BitmapMasks): Ground truth masks of each instances\...
class ResLayer(Sequential): "ResLayer to build ResNet style backbone.\n\n Args:\n block (nn.Module): block used to build ResLayer.\n inplanes (int): inplanes of block.\n planes (int): planes of block.\n num_blocks (int): number of blocks.\n stride (int): stride of the first b...
class SimplifiedBasicBlock(BaseModule): 'Simplified version of original basic residual block. This is used in\n `SCNet <https://arxiv.org/abs/2012.10150>`_.\n\n - Norm layer is now optional\n - Last ReLU in forward function is removed\n ' expansion = 1 def __init__(self, inplanes, planes, str...
class SELayer(BaseModule): "Squeeze-and-Excitation Module.\n\n Args:\n channels (int): The input (and output) channels of the SE layer.\n ratio (int): Squeeze ratio in SELayer, the intermediate channel will be\n ``int(channels/ratio)``. Default: 16.\n conv_cfg (None or dict): Co...
class DyReLU(BaseModule): "Dynamic ReLU (DyReLU) module.\n\n See `Dynamic ReLU <https://arxiv.org/abs/2003.10027>`_ for details.\n Current implementation is specialized for task-aware attention in DyHead.\n HSigmoid arguments in default act_cfg follow DyHead official code.\n https://github.com/microso...
def collect_env(): 'Collect the information of the running environments.' env_info = collect_base_env() env_info['MMDetection'] = ((mmdet.__version__ + '+') + get_git_hash()[:7]) return env_info
def get_root_logger(log_file=None, log_level=logging.INFO): 'Get root logger.\n\n Args:\n log_file (str, optional): File path of log. Defaults to None.\n log_level (int, optional): The level of logger.\n Defaults to logging.INFO.\n\n Returns:\n :obj:`logging.Logger`: The obta...
def find_latest_checkpoint(path, suffix='pth'): 'Find the latest checkpoint from the working directory.\n\n Args:\n path(str): The path to find checkpoints.\n suffix(str): File extension.\n Defaults to pth.\n\n Returns:\n latest_path(str | None): File path of the latest check...
def setup_multi_processes(cfg): 'Setup multi-processing environment variables.' if (platform.system() != 'Windows'): mp_start_method = cfg.get('mp_start_method', 'fork') current_method = mp.get_start_method(allow_none=True) if ((current_method is not None) and (current_method != mp_sta...
class NiceRepr(): 'Inherit from this class and define ``__nice__`` to "nicely" print your\n objects.\n\n Defines ``__str__`` and ``__repr__`` in terms of ``__nice__`` function\n Classes that inherit from :class:`NiceRepr` should redefine ``__nice__``.\n If the inheriting class has a ``__len__``, metho...
def ensure_rng(rng=None): 'Coerces input into a random number generator.\n\n If the input is None, then a global random state is returned.\n\n If the input is a numeric value, then that is used as a seed to construct a\n random state. Otherwise the input is returned as-is.\n\n Adapted from [1]_.\n\n ...
def parse_version_info(version_str): version_info = [] for x in version_str.split('.'): if x.isdigit(): version_info.append(int(x)) elif (x.find('rc') != (- 1)): patch_version = x.split('rc') version_info.append(int(patch_version[0])) version_inf...
def check_installation(): 'Check whether mmcv-full has been installed successfully.' np_boxes1 = np.asarray([[1.0, 1.0, 3.0, 4.0, 0.5], [2.0, 2.0, 3.0, 4.0, 0.6], [7.0, 7.0, 8.0, 8.0, 0.4]], dtype=np.float32) np_boxes2 = np.asarray([[0.0, 2.0, 2.0, 5.0, 0.3], [2.0, 1.0, 3.0, 3.0, 0.5], [5.0, 5.0, 6.0, 7.0...
class Model(nn.Module): def __init__(self): super(Model, self).__init__() self.conv1 = nn.Conv2d(3, 6, 5) self.pool = nn.MaxPool2d(2, 2) self.conv2 = nn.Conv2d(6, 16, 5) self.fc1 = nn.Linear(((16 * 5) * 5), 120) self.fc2 = nn.Linear(120, 84) self.fc3 = nn.L...
def quantize(arr, min_val, max_val, levels, dtype=np.int64): 'Quantize an array of (-inf, inf) to [0, levels-1].\n\n Args:\n arr (ndarray): Input array.\n min_val (scalar): Minimum value to be clipped.\n max_val (scalar): Maximum value to be clipped.\n levels (int): Quantization lev...
def dequantize(arr, min_val, max_val, levels, dtype=np.float64): 'Dequantize an array.\n\n Args:\n arr (ndarray): Input array.\n min_val (scalar): Minimum value to be clipped.\n max_val (scalar): Maximum value to be clipped.\n levels (int): Quantization levels.\n dtype (np.ty...
class AlexNet(nn.Module): 'AlexNet backbone.\n\n Args:\n num_classes (int): number of classes for classification.\n ' def __init__(self, num_classes=(- 1)): super(AlexNet, self).__init__() self.num_classes = num_classes self.features = nn.Sequential(nn.Conv2d(3, 64, kerne...
@ACTIVATION_LAYERS.register_module(name='Clip') @ACTIVATION_LAYERS.register_module() class Clamp(nn.Module): 'Clamp activation layer.\n\n This activation function is to clamp the feature map value within\n :math:`[min, max]`. More details can be found in ``torch.clamp()``.\n\n Args:\n min (Number ...
class GELU(nn.Module): 'Applies the Gaussian Error Linear Units function:\n\n .. math::\n \\text{GELU}(x) = x * \\Phi(x)\n where :math:`\\Phi(x)` is the Cumulative Distribution Function for\n Gaussian Distribution.\n\n Shape:\n - Input: :math:`(N, *)` where `*` means, any number of addit...
def build_activation_layer(cfg): 'Build activation layer.\n\n Args:\n cfg (dict): The activation layer config, which should contain:\n\n - type (str): Layer type.\n - layer args: Args needed to instantiate an activation layer.\n\n Returns:\n nn.Module: Created activation ...
def last_zero_init(m): if isinstance(m, nn.Sequential): constant_init(m[(- 1)], val=0) else: constant_init(m, val=0)
@PLUGIN_LAYERS.register_module() class ContextBlock(nn.Module): "ContextBlock module in GCNet.\n\n See 'GCNet: Non-local Networks Meet Squeeze-Excitation Networks and Beyond'\n (https://arxiv.org/abs/1904.11492) for details.\n\n Args:\n in_channels (int): Channels of the input feature map.\n ...
def build_conv_layer(cfg, *args, **kwargs): 'Build convolution layer.\n\n Args:\n cfg (None or dict): The conv layer config, which should contain:\n - type (str): Layer type.\n - layer args: Args needed to instantiate an conv layer.\n args (argument list): Arguments passed t...
@CONV_LAYERS.register_module() class Conv2dAdaptivePadding(nn.Conv2d): 'Implementation of 2D convolution in tensorflow with `padding` as "same",\n which applies padding to input (if needed) so that input image gets fully\n covered by filter and stride you specified. For stride 1, this will ensure\n that ...
@PLUGIN_LAYERS.register_module() class ConvModule(nn.Module): 'A conv block that bundles conv/norm/activation layers.\n\n This block simplifies the usage of convolution layers, which are commonly\n used with a norm layer (e.g., BatchNorm) and activation layer (e.g., ReLU).\n It is based upon three build ...
def conv_ws_2d(input, weight, bias=None, stride=1, padding=0, dilation=1, groups=1, eps=1e-05): c_in = weight.size(0) weight_flat = weight.view(c_in, (- 1)) mean = weight_flat.mean(dim=1, keepdim=True).view(c_in, 1, 1, 1) std = weight_flat.std(dim=1, keepdim=True).view(c_in, 1, 1, 1) weight = ((we...
@CONV_LAYERS.register_module('ConvWS') class ConvWS2d(nn.Conv2d): def __init__(self, in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, bias=True, eps=1e-05): super(ConvWS2d, self).__init__(in_channels, out_channels, kernel_size, stride=stride, padding=padding, dilation=di...
@CONV_LAYERS.register_module(name='ConvAWS') class ConvAWS2d(nn.Conv2d): 'AWS (Adaptive Weight Standardization)\n\n This is a variant of Weight Standardization\n (https://arxiv.org/pdf/1903.10520.pdf)\n It is used in DetectoRS to avoid NaN\n (https://arxiv.org/pdf/2006.02334.pdf)\n\n Args:\n ...
class DepthwiseSeparableConvModule(nn.Module): "Depthwise separable convolution module.\n\n See https://arxiv.org/pdf/1704.04861.pdf for details.\n\n This module can replace a ConvModule with the conv block replaced by two\n conv block: depthwise conv block and pointwise conv block. The depthwise\n co...
def drop_path(x, drop_prob=0.0, training=False): 'Drop paths (Stochastic Depth) per sample (when applied in main path of\n residual blocks).\n\n We follow the implementation\n https://github.com/rwightman/pytorch-image-models/blob/a2727c1bf78ba0d7b5727f5f95e37fb7f8866b1f/timm/models/layers/drop.py # noq...
@DROPOUT_LAYERS.register_module() class DropPath(nn.Module): 'Drop paths (Stochastic Depth) per sample (when applied in main path of\n residual blocks).\n\n We follow the implementation\n https://github.com/rwightman/pytorch-image-models/blob/a2727c1bf78ba0d7b5727f5f95e37fb7f8866b1f/timm/models/layers/d...
@DROPOUT_LAYERS.register_module() class Dropout(nn.Dropout): 'A wrapper for ``torch.nn.Dropout``, We rename the ``p`` of\n ``torch.nn.Dropout`` to ``drop_prob`` so as to be consistent with\n ``DropPath``\n\n Args:\n drop_prob (float): Probability of the elements to be\n zeroed. Default:...
def build_dropout(cfg, default_args=None): 'Builder for drop out layers.' return build_from_cfg(cfg, DROPOUT_LAYERS, default_args)
@ACTIVATION_LAYERS.register_module() class HSigmoid(nn.Module): 'Hard Sigmoid Module. Apply the hard sigmoid function:\n Hsigmoid(x) = min(max((x + bias) / divisor, min_value), max_value)\n Default: Hsigmoid(x) = min(max((x + 3) / 6, 0), 1)\n\n Note:\n In MMCV v1.4.4, we modified the default value...
class HSwish(nn.Module): 'Hard Swish Module.\n\n This module applies the hard swish function:\n\n .. math::\n Hswish(x) = x * ReLU6(x + 3) / 6\n\n Args:\n inplace (bool): can optionally do the operation in-place.\n Default: False.\n\n Returns:\n Tensor: The output tenso...
class _NonLocalNd(nn.Module, metaclass=ABCMeta): 'Basic Non-local module.\n\n This module is proposed in\n "Non-local Neural Networks"\n Paper reference: https://arxiv.org/abs/1711.07971\n Code reference: https://github.com/AlexHex7/Non-local_pytorch\n\n Args:\n in_channels (int): Channels o...
class NonLocal1d(_NonLocalNd): "1D Non-local module.\n\n Args:\n in_channels (int): Same as `NonLocalND`.\n sub_sample (bool): Whether to apply max pooling after pairwise\n function (Note that the `sub_sample` is applied on spatial only).\n Default: False.\n conv_cfg ...
@PLUGIN_LAYERS.register_module() class NonLocal2d(_NonLocalNd): "2D Non-local module.\n\n Args:\n in_channels (int): Same as `NonLocalND`.\n sub_sample (bool): Whether to apply max pooling after pairwise\n function (Note that the `sub_sample` is applied on spatial only).\n D...
class NonLocal3d(_NonLocalNd): "3D Non-local module.\n\n Args:\n in_channels (int): Same as `NonLocalND`.\n sub_sample (bool): Whether to apply max pooling after pairwise\n function (Note that the `sub_sample` is applied on spatial only).\n Default: False.\n conv_cfg ...
def infer_abbr(class_type): 'Infer abbreviation from the class name.\n\n When we build a norm layer with `build_norm_layer()`, we want to preserve\n the norm type in variable names, e.g, self.bn1, self.gn. This method will\n infer the abbreviation to map class types to abbreviations.\n\n Rule 1: If th...
def build_norm_layer(cfg, num_features, postfix=''): 'Build normalization layer.\n\n Args:\n cfg (dict): The norm layer config, which should contain:\n\n - type (str): Layer type.\n - layer args: Args needed to instantiate a norm layer.\n - requires_grad (bool, optional)...
def is_norm(layer, exclude=None): 'Check if a layer is a normalization layer.\n\n Args:\n layer (nn.Module): The layer to be checked.\n exclude (type | tuple[type]): Types to be excluded.\n\n Returns:\n bool: Whether the layer is a norm layer.\n ' if (exclude is not None): ...
def build_padding_layer(cfg, *args, **kwargs): 'Build padding layer.\n\n Args:\n cfg (None or dict): The padding layer config, which should contain:\n - type (str): Layer type.\n - layer args: Args needed to instantiate a padding layer.\n\n Returns:\n nn.Module: Created p...
def infer_abbr(class_type): 'Infer abbreviation from the class name.\n\n This method will infer the abbreviation to map class types to\n abbreviations.\n\n Rule 1: If the class has the property "abbr", return the property.\n Rule 2: Otherwise, the abbreviation falls back to snake case of class\n na...
def build_plugin_layer(cfg, postfix='', **kwargs): "Build plugin layer.\n\n Args:\n cfg (None or dict): cfg should contain:\n\n - type (str): identify plugin layer type.\n - layer args: args needed to instantiate a plugin layer.\n postfix (int, str): appended into norm abbre...
class Scale(nn.Module): 'A learnable scale parameter.\n\n This layer scales the input by a learnable factor. It multiplies a\n learnable scale parameter of shape (1,) with input of any shape.\n\n Args:\n scale (float): Initial value of scale factor. Default: 1.0\n ' def __init__(self, scal...
@ACTIVATION_LAYERS.register_module() class Swish(nn.Module): 'Swish Module.\n\n This module applies the swish function:\n\n .. math::\n Swish(x) = x * Sigmoid(x)\n\n Returns:\n Tensor: The output tensor.\n ' def __init__(self): super(Swish, self).__init__() def forward(...
def build_positional_encoding(cfg, default_args=None): 'Builder for Position Encoding.' return build_from_cfg(cfg, POSITIONAL_ENCODING, default_args)
def build_attention(cfg, default_args=None): 'Builder for attention.' return build_from_cfg(cfg, ATTENTION, default_args)
def build_feedforward_network(cfg, default_args=None): 'Builder for feed-forward network (FFN).' return build_from_cfg(cfg, FEEDFORWARD_NETWORK, default_args)
def build_transformer_layer(cfg, default_args=None): 'Builder for transformer layer.' return build_from_cfg(cfg, TRANSFORMER_LAYER, default_args)
def build_transformer_layer_sequence(cfg, default_args=None): 'Builder for transformer encoder and transformer decoder.' return build_from_cfg(cfg, TRANSFORMER_LAYER_SEQUENCE, default_args)
class AdaptivePadding(nn.Module): 'Applies padding adaptively to the input.\n\n This module can make input get fully covered by filter\n you specified. It support two modes "same" and "corner". The\n "same" mode is same with "SAME" padding mode in TensorFlow, pad\n zero around input. The "corner" mod...
class PatchEmbed(BaseModule): 'Image to Patch Embedding.\n\n We use a conv layer to implement PatchEmbed.\n\n Args:\n in_channels (int): The num of input channels. Default: 3\n embed_dims (int): The dimensions of embedding. Default: 768\n conv_type (str): The type of convolution\n ...
class PatchMerging(BaseModule): 'Merge patch feature map.\n\n This layer groups feature map by kernel_size, and applies norm and linear\n layers to the grouped feature map ((used in Swin Transformer)).\n Our implementation uses `nn.Unfold` to\n merge patches, which is about 25% faster than the origina...
@ATTENTION.register_module() class MultiheadAttention(BaseModule): 'A wrapper for ``torch.nn.MultiheadAttention``.\n\n This module implements MultiheadAttention with identity connection,\n and positional encoding is also passed as input.\n\n Args:\n embed_dims (int): The embedding dimension.\n ...
@FEEDFORWARD_NETWORK.register_module() class FFN(BaseModule): "Implements feed-forward networks (FFNs) with identity connection.\n\n Args:\n embed_dims (int): The feature dimension. Same as\n `MultiheadAttention`. Defaults: 256.\n feedforward_channels (int): The hidden dimension of FFN...
@TRANSFORMER_LAYER.register_module() class BaseTransformerLayer(BaseModule): "Base `TransformerLayer` for vision transformer.\n\n It can be built from `mmcv.ConfigDict` and support more flexible\n customization, for example, using any number of `FFN or LN ` and\n use different kinds of `attention` by spe...
@TRANSFORMER_LAYER_SEQUENCE.register_module() class TransformerLayerSequence(BaseModule): 'Base class for TransformerEncoder and TransformerDecoder in vision\n transformer.\n\n As base-class of Encoder and Decoder in vision transformer.\n Support customization such as specifying different kind\n of `t...
@UPSAMPLE_LAYERS.register_module(name='pixel_shuffle') class PixelShufflePack(nn.Module): 'Pixel Shuffle upsample layer.\n\n This module packs `F.pixel_shuffle()` and a nn.Conv2d module together to\n achieve a simple upsampling with pixel shuffle.\n\n Args:\n in_channels (int): Number of input cha...
def build_upsample_layer(cfg, *args, **kwargs): 'Build upsample layer.\n\n Args:\n cfg (dict): The upsample layer config, which should contain:\n\n - type (str): Layer type.\n - scale_factor (int): Upsample ratio, which is not applicable to\n deconv.\n - lay...
def obsolete_torch_version(torch_version, version_threshold): return ((torch_version == 'parrots') or (torch_version <= version_threshold))
class NewEmptyTensorOp(torch.autograd.Function): @staticmethod def forward(ctx, x, new_shape): ctx.shape = x.shape return x.new_empty(new_shape) @staticmethod def backward(ctx, grad): shape = ctx.shape return (NewEmptyTensorOp.apply(grad, shape), None)
@CONV_LAYERS.register_module('Conv', force=True) class Conv2d(nn.Conv2d): def forward(self, x): if ((x.numel() == 0) and obsolete_torch_version(TORCH_VERSION, (1, 4))): out_shape = [x.shape[0], self.out_channels] for (i, k, p, s, d) in zip(x.shape[(- 2):], self.kernel_size, self.p...
@CONV_LAYERS.register_module('Conv3d', force=True) class Conv3d(nn.Conv3d): def forward(self, x): if ((x.numel() == 0) and obsolete_torch_version(TORCH_VERSION, (1, 4))): out_shape = [x.shape[0], self.out_channels] for (i, k, p, s, d) in zip(x.shape[(- 3):], self.kernel_size, self...
@CONV_LAYERS.register_module() @CONV_LAYERS.register_module('deconv') @UPSAMPLE_LAYERS.register_module('deconv', force=True) class ConvTranspose2d(nn.ConvTranspose2d): def forward(self, x): if ((x.numel() == 0) and obsolete_torch_version(TORCH_VERSION, (1, 4))): out_shape = [x.shape[0], self....
@CONV_LAYERS.register_module() @CONV_LAYERS.register_module('deconv3d') @UPSAMPLE_LAYERS.register_module('deconv3d', force=True) class ConvTranspose3d(nn.ConvTranspose3d): def forward(self, x): if ((x.numel() == 0) and obsolete_torch_version(TORCH_VERSION, (1, 4))): out_shape = [x.shape[0], s...
class MaxPool2d(nn.MaxPool2d): def forward(self, x): if ((x.numel() == 0) and obsolete_torch_version(TORCH_VERSION, (1, 9))): out_shape = list(x.shape[:2]) for (i, k, p, s, d) in zip(x.shape[(- 2):], _pair(self.kernel_size), _pair(self.padding), _pair(self.stride), _pair(self.dila...
class MaxPool3d(nn.MaxPool3d): def forward(self, x): if ((x.numel() == 0) and obsolete_torch_version(TORCH_VERSION, (1, 9))): out_shape = list(x.shape[:2]) for (i, k, p, s, d) in zip(x.shape[(- 3):], _triple(self.kernel_size), _triple(self.padding), _triple(self.stride), _triple(s...
class Linear(torch.nn.Linear): def forward(self, x): if ((x.numel() == 0) and obsolete_torch_version(TORCH_VERSION, (1, 5))): out_shape = [x.shape[0], self.out_features] empty = NewEmptyTensorOp.apply(x, out_shape) if self.training: dummy = (sum((x.view...
def build_model_from_cfg(cfg, registry, default_args=None): 'Build a PyTorch model from config dict(s). Different from\n ``build_from_cfg``, if cfg is a list, a ``nn.Sequential`` will be built.\n\n Args:\n cfg (dict, list[dict]): The config of modules, is is either a config\n dict or a lis...
def conv3x3(in_planes, out_planes, stride=1, dilation=1): '3x3 convolution with padding.' return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=dilation, dilation=dilation, bias=False)
class BasicBlock(nn.Module): expansion = 1 def __init__(self, inplanes, planes, stride=1, dilation=1, downsample=None, style='pytorch', with_cp=False): super(BasicBlock, self).__init__() assert (style in ['pytorch', 'caffe']) self.conv1 = conv3x3(inplanes, planes, stride, dilation) ...
class Bottleneck(nn.Module): expansion = 4 def __init__(self, inplanes, planes, stride=1, dilation=1, downsample=None, style='pytorch', with_cp=False): 'Bottleneck block.\n\n If style is "pytorch", the stride-two layer is the 3x3 conv layer, if\n it is "caffe", the stride-two layer is t...
def make_res_layer(block, inplanes, planes, blocks, stride=1, dilation=1, style='pytorch', with_cp=False): downsample = None if ((stride != 1) or (inplanes != (planes * block.expansion))): downsample = nn.Sequential(nn.Conv2d(inplanes, (planes * block.expansion), kernel_size=1, stride=stride, bias=Fal...
class ResNet(nn.Module): 'ResNet backbone.\n\n Args:\n depth (int): Depth of resnet, from {18, 34, 50, 101, 152}.\n num_stages (int): Resnet stages, normally 4.\n strides (Sequence[int]): Strides of the first block of each stage.\n dilations (Sequence[int]): Dilation of each stage.\...
def get_model_complexity_info(model, input_shape, print_per_layer_stat=True, as_strings=True, input_constructor=None, flush=False, ost=sys.stdout): 'Get complexity information of a model.\n\n This method can calculate FLOPs and parameter counts of a model with\n corresponding input shape. It can also print ...
def flops_to_string(flops, units='GFLOPs', precision=2): "Convert FLOPs number into a string.\n\n Note that Here we take a multiply-add counts as one FLOP.\n\n Args:\n flops (float): FLOPs number to be converted.\n units (str | None): Converted FLOPs units. Options are None, 'GFLOPs',\n ...
def params_to_string(num_params, units=None, precision=2): "Convert parameter number into a string.\n\n Args:\n num_params (float): Parameter number to be converted.\n units (str | None): Converted FLOPs units. Options are None, 'M',\n 'K' and ''. If set to None, it will automatically ...
def print_model_with_flops(model, total_flops, total_params, units='GFLOPs', precision=3, ost=sys.stdout, flush=False): "Print a model with FLOPs for each layer.\n\n Args:\n model (nn.Module): The model to be printed.\n total_flops (float): Total FLOPs of the model.\n total_params (float):...
def get_model_parameters_number(model): 'Calculate parameter number of a model.\n\n Args:\n model (nn.module): The model for parameter number calculation.\n\n Returns:\n float: Parameter number of the model.\n ' num_params = sum((p.numel() for p in model.parameters() if p.requires_grad)...
def add_flops_counting_methods(net_main_module): net_main_module.start_flops_count = start_flops_count.__get__(net_main_module) net_main_module.stop_flops_count = stop_flops_count.__get__(net_main_module) net_main_module.reset_flops_count = reset_flops_count.__get__(net_main_module) net_main_module.co...
def compute_average_flops_cost(self): 'Compute average FLOPs cost.\n\n A method to compute average FLOPs cost, which will be available after\n `add_flops_counting_methods()` is called on a desired net object.\n\n Returns:\n float: Current mean flops consumption per image.\n ' batches_count ...
def start_flops_count(self): 'Activate the computation of mean flops consumption per image.\n\n A method to activate the computation of mean flops consumption per image.\n which will be available after ``add_flops_counting_methods()`` is called on\n a desired net object. It should be called before runnin...
def stop_flops_count(self): 'Stop computing the mean flops consumption per image.\n\n A method to stop computing the mean flops consumption per image, which will\n be available after ``add_flops_counting_methods()`` is called on a desired\n net object. It can be called to pause the computation whenever.\...
def reset_flops_count(self): 'Reset statistics computed so far.\n\n A method to Reset computed statistics, which will be available after\n `add_flops_counting_methods()` is called on a desired net object.\n ' add_batch_counter_variables_or_reset(self) self.apply(add_flops_counter_variable_or_rese...
def empty_flops_counter_hook(module, input, output): module.__flops__ += 0