code stringlengths 17 6.64M |
|---|
@mmcv.jit(derivate=True, coderize=True)
@weighted_loss
def quality_focal_loss(pred, target, beta=2.0):
'Quality Focal Loss (QFL) is from `Generalized Focal Loss: Learning\n Qualified and Distributed Bounding Boxes for Dense Object Detection\n <https://arxiv.org/abs/2006.04388>`_.\n\n Args:\n pred ... |
@weighted_loss
def quality_focal_loss_with_prob(pred, target, beta=2.0):
'Quality Focal Loss (QFL) is from `Generalized Focal Loss: Learning\n Qualified and Distributed Bounding Boxes for Dense Object Detection\n <https://arxiv.org/abs/2006.04388>`_.\n Different from `quality_focal_loss`, this function a... |
@mmcv.jit(derivate=True, coderize=True)
@weighted_loss
def distribution_focal_loss(pred, label):
'Distribution Focal Loss (DFL) is from `Generalized Focal Loss: Learning\n Qualified and Distributed Bounding Boxes for Dense Object Detection\n <https://arxiv.org/abs/2006.04388>`_.\n\n Args:\n pred (... |
@LOSSES.register_module()
class QualityFocalLoss(nn.Module):
'Quality Focal Loss (QFL) is a variant of `Generalized Focal Loss:\n Learning Qualified and Distributed Bounding Boxes for Dense Object\n Detection <https://arxiv.org/abs/2006.04388>`_.\n\n Args:\n use_sigmoid (bool): Whether sigmoid ope... |
@LOSSES.register_module()
class DistributionFocalLoss(nn.Module):
"Distribution Focal Loss (DFL) is a variant of `Generalized Focal Loss:\n Learning Qualified and Distributed Bounding Boxes for Dense Object\n Detection <https://arxiv.org/abs/2006.04388>`_.\n\n Args:\n reduction (str): Options are ... |
def _expand_onehot_labels(labels, label_weights, label_channels):
bin_labels = labels.new_full((labels.size(0), label_channels), 0)
inds = torch.nonzero(((labels >= 0) & (labels < label_channels)), as_tuple=False).squeeze()
if (inds.numel() > 0):
bin_labels[(inds, labels[inds])] = 1
bin_label_... |
@LOSSES.register_module()
class GHMC(nn.Module):
'GHM Classification Loss.\n\n Details of the theorem can be viewed in the paper\n `Gradient Harmonized Single-stage Detector\n <https://arxiv.org/abs/1811.05181>`_.\n\n Args:\n bins (int): Number of the unit regions for distribution calculation.\... |
@LOSSES.register_module()
class GHMR(nn.Module):
'GHM Regression Loss.\n\n Details of the theorem can be viewed in the paper\n `Gradient Harmonized Single-stage Detector\n <https://arxiv.org/abs/1811.05181>`_.\n\n Args:\n mu (float): The parameter for the Authentic Smooth L1 loss.\n bins... |
@mmcv.jit(derivate=True, coderize=True)
@weighted_loss
def knowledge_distillation_kl_div_loss(pred, soft_label, T, detach_target=True):
'Loss function for knowledge distilling using KL divergence.\n\n Args:\n pred (Tensor): Predicted logits with shape (N, n + 1).\n soft_label (Tensor): Target log... |
@LOSSES.register_module()
class KnowledgeDistillationKLDivLoss(nn.Module):
"Loss function for knowledge distilling using KL divergence.\n\n Args:\n reduction (str): Options are `'none'`, `'mean'` and `'sum'`.\n loss_weight (float): Loss weight of current loss.\n T (int): Temperature for di... |
@weighted_loss
def mse_loss(pred, target):
'Warpper of mse loss.'
return F.mse_loss(pred, target, reduction='none')
|
@LOSSES.register_module()
class MSELoss(nn.Module):
'MSELoss.\n\n Args:\n reduction (str, optional): The method that reduces the loss to a\n scalar. Options are "none", "mean" and "sum".\n loss_weight (float, optional): The weight of the loss. Defaults to 1.0\n '
def __init__(s... |
@mmcv.jit(derivate=True, coderize=True)
@weighted_loss
def smooth_l1_loss(pred, target, beta=1.0):
'Smooth L1 loss.\n\n Args:\n pred (torch.Tensor): The prediction.\n target (torch.Tensor): The learning target of the prediction.\n beta (float, optional): The threshold in the piecewise func... |
@mmcv.jit(derivate=True, coderize=True)
@weighted_loss
def l1_loss(pred, target):
'L1 loss.\n\n Args:\n pred (torch.Tensor): The prediction.\n target (torch.Tensor): The learning target of the prediction.\n\n Returns:\n torch.Tensor: Calculated loss\n '
if (target.numel() == 0):
... |
@LOSSES.register_module()
class SmoothL1Loss(nn.Module):
'Smooth L1 loss.\n\n Args:\n beta (float, optional): The threshold in the piecewise function.\n Defaults to 1.0.\n reduction (str, optional): The method to reduce the loss.\n Options are "none", "mean" and "sum". Defau... |
@LOSSES.register_module()
class L1Loss(nn.Module):
'L1 loss.\n\n Args:\n reduction (str, optional): The method to reduce the loss.\n Options are "none", "mean" and "sum".\n loss_weight (float, optional): The weight of loss.\n '
def __init__(self, reduction='mean', loss_weight=1... |
def reduce_loss(loss, reduction):
'Reduce loss as specified.\n\n Args:\n loss (Tensor): Elementwise loss tensor.\n reduction (str): Options are "none", "mean" and "sum".\n\n Return:\n Tensor: Reduced loss tensor.\n '
reduction_enum = F._Reduction.get_enum(reduction)
if (reduc... |
@mmcv.jit(derivate=True, coderize=True)
def weight_reduce_loss(loss, weight=None, reduction='mean', avg_factor=None):
'Apply element-wise weight and reduce loss.\n\n Args:\n loss (Tensor): Element-wise loss.\n weight (Tensor): Element-wise weights.\n reduction (str): Same as built-in losse... |
def weighted_loss(loss_func):
"Create a weighted version of a given loss function.\n\n To use this decorator, the loss function must have the signature like\n `loss_func(pred, target, **kwargs)`. The function only needs to compute\n element-wise loss without any reduction. This decorator will add weight\... |
@mmcv.jit(derivate=True, coderize=True)
def varifocal_loss(pred, target, weight=None, alpha=0.75, gamma=2.0, iou_weighted=True, reduction='mean', avg_factor=None):
'`Varifocal Loss <https://arxiv.org/abs/2008.13367>`_\n\n Args:\n pred (torch.Tensor): The prediction with shape (N, C), C is the\n ... |
@LOSSES.register_module()
class VarifocalLoss(nn.Module):
def __init__(self, use_sigmoid=True, alpha=0.75, gamma=2.0, iou_weighted=True, reduction='mean', loss_weight=1.0):
'`Varifocal Loss <https://arxiv.org/abs/2008.13367>`_\n\n Args:\n use_sigmoid (bool, optional): Whether the predic... |
@NECKS.register_module()
class BFP(BaseModule):
"BFP (Balanced Feature Pyramids)\n\n BFP takes multi-level features as inputs and gather them into a single one,\n then refine the gathered feature and scatter the refined results to\n multi-level features. This module is used in Libra R-CNN (CVPR 2019), se... |
@NECKS.register_module()
class ChannelMapper(BaseModule):
"Channel Mapper to reduce/increase channels of backbone features.\n\n This is used to reduce/increase channels of backbone features.\n\n Args:\n in_channels (List[int]): Number of input channels per scale.\n out_channels (int): Number o... |
class Bottleneck(nn.Module):
'Bottleneck block for DilatedEncoder used in `YOLOF.\n\n <https://arxiv.org/abs/2103.09460>`.\n\n The Bottleneck contains three ConvLayers and one residual connection.\n\n Args:\n in_channels (int): The number of input channels.\n mid_channels (int): The number ... |
@NECKS.register_module()
class DilatedEncoder(nn.Module):
'Dilated Encoder for YOLOF <https://arxiv.org/abs/2103.09460>`.\n\n This module contains two types of components:\n - the original FPN lateral convolution layer and fpn convolution layer,\n which are 1x1 conv + 3x3 conv\n - th... |
class Transition(BaseModule):
'Base class for transition.\n\n Args:\n in_channels (int): Number of input channels.\n out_channels (int): Number of output channels.\n '
def __init__(self, in_channels, out_channels, init_cfg=None):
super().__init__(init_cfg)
self.in_channels... |
class UpInterpolationConv(Transition):
'A transition used for up-sampling.\n\n Up-sample the input by interpolation then refines the feature by\n a convolution layer.\n\n Args:\n in_channels (int): Number of input channels.\n out_channels (int): Number of output channels.\n scale_fac... |
class LastConv(Transition):
'A transition used for refining the output of the last stage.\n\n Args:\n in_channels (int): Number of input channels.\n out_channels (int): Number of output channels.\n num_inputs (int): Number of inputs of the FPN features.\n kernel_size (int): Kernel s... |
@NECKS.register_module()
class FPG(BaseModule):
"FPG.\n\n Implementation of `Feature Pyramid Grids (FPG)\n <https://arxiv.org/abs/2004.03580>`_.\n This implementation only gives the basic structure stated in the paper.\n But users can implement different type of transitions to fully explore the\n t... |
@NECKS.register_module()
class FPN(BaseModule):
"Feature Pyramid Network.\n\n This is an implementation of paper `Feature Pyramid Networks for Object\n Detection <https://arxiv.org/abs/1612.03144>`_.\n\n Args:\n in_channels (List[int]): Number of input channels per scale.\n out_channels (in... |
@NECKS.register_module()
class HRFPN(BaseModule):
'HRFPN (High Resolution Feature Pyramids)\n\n paper: `High-Resolution Representations for Labeling Pixels and Regions\n <https://arxiv.org/abs/1904.04514>`_.\n\n Args:\n in_channels (list): number of channels for each branch.\n out_channels ... |
@NECKS.register_module()
class NASFPN(BaseModule):
'NAS-FPN.\n\n Implementation of `NAS-FPN: Learning Scalable Feature Pyramid Architecture\n for Object Detection <https://arxiv.org/abs/1904.07392>`_\n\n Args:\n in_channels (List[int]): Number of input channels per scale.\n out_channels (in... |
@NECKS.register_module()
class NASFCOS_FPN(BaseModule):
'FPN structure in NASFPN.\n\n Implementation of paper `NAS-FCOS: Fast Neural Architecture Search for\n Object Detection <https://arxiv.org/abs/1906.04423>`_\n\n Args:\n in_channels (List[int]): Number of input channels per scale.\n out... |
@NECKS.register_module()
class PAFPN(FPN):
"Path Aggregation Network for Instance Segmentation.\n\n This is an implementation of the `PAFPN in Path Aggregation Network\n <https://arxiv.org/abs/1803.01534>`_.\n\n Args:\n in_channels (List[int]): Number of input channels per scale.\n out_chan... |
class ASPP(BaseModule):
'ASPP (Atrous Spatial Pyramid Pooling)\n\n This is an implementation of the ASPP module used in DetectoRS\n (https://arxiv.org/pdf/2006.02334.pdf)\n\n Args:\n in_channels (int): Number of input channels.\n out_channels (int): Number of channels produced by this modul... |
@NECKS.register_module()
class RFP(FPN):
'RFP (Recursive Feature Pyramid)\n\n This is an implementation of RFP in `DetectoRS\n <https://arxiv.org/pdf/2006.02334.pdf>`_. Different from standard FPN, the\n input of RFP should be multi level features along with origin input image\n of backbone.\n\n Ar... |
class DetectionBlock(BaseModule):
"Detection block in YOLO neck.\n\n Let out_channels = n, the DetectionBlock contains:\n Six ConvLayers, 1 Conv2D Layer and 1 YoloLayer.\n The first 6 ConvLayers are formed the following way:\n 1x1xn, 3x3x2n, 1x1xn, 3x3x2n, 1x1xn, 3x3x2n.\n The Conv2D layer is 1... |
@NECKS.register_module()
class YOLOV3Neck(BaseModule):
"The neck of YOLOV3.\n\n It can be treated as a simplified version of FPN. It\n will take the result from Darknet backbone and do some upsampling and\n concatenation. It will finally output the detection result.\n\n Note:\n The input feats ... |
@NECKS.register_module()
class YOLOXPAFPN(BaseModule):
"Path Aggregation Network used in YOLOX.\n\n Args:\n in_channels (List[int]): Number of input channels per scale.\n out_channels (int): Number of output channels (used at each scale)\n num_csp_blocks (int): Number of bottlenecks in CSP... |
@PLUGIN_LAYERS.register_module()
class DropBlock(nn.Module):
'Randomly drop some regions of feature maps.\n\n Please refer to the method proposed in `DropBlock\n <https://arxiv.org/abs/1810.12890>`_ for details.\n\n Args:\n drop_prob (float): The probability of dropping each block.\n bloc... |
class BaseRoIHead(BaseModule, metaclass=ABCMeta):
'Base class for RoIHeads.'
def __init__(self, bbox_roi_extractor=None, bbox_head=None, mask_roi_extractor=None, mask_head=None, shared_head=None, train_cfg=None, test_cfg=None, pretrained=None, init_cfg=None):
super(BaseRoIHead, self).__init__(init_cf... |
@HEADS.register_module()
class ConvFCBBoxHead(BBoxHead):
'More general bbox head, with shared conv and fc layers and two optional\n separated branches.\n\n .. code-block:: none\n\n /-> cls convs -> cls fcs -> cls\n shared convs -> shared fcs\n ... |
@HEADS.register_module()
class Shared2FCBBoxHead(ConvFCBBoxHead):
def __init__(self, fc_out_channels=1024, *args, **kwargs):
super(Shared2FCBBoxHead, self).__init__(*args, num_shared_convs=0, num_shared_fcs=2, num_cls_convs=0, num_cls_fcs=0, num_reg_convs=0, num_reg_fcs=0, fc_out_channels=fc_out_channels... |
@HEADS.register_module()
class Shared4Conv1FCBBoxHead(ConvFCBBoxHead):
def __init__(self, fc_out_channels=1024, *args, **kwargs):
super(Shared4Conv1FCBBoxHead, self).__init__(*args, num_shared_convs=4, num_shared_fcs=1, num_cls_convs=0, num_cls_fcs=0, num_reg_convs=0, num_reg_fcs=0, fc_out_channels=fc_ou... |
class BasicResBlock(BaseModule):
'Basic residual block.\n\n This block is a little different from the block in the ResNet backbone.\n The kernel size of conv1 is 1 in this block while 3 in ResNet BasicBlock.\n\n Args:\n in_channels (int): Channels of the input feature map.\n out_channels (i... |
@HEADS.register_module()
class DoubleConvFCBBoxHead(BBoxHead):
'Bbox head used in Double-Head R-CNN\n\n .. code-block:: none\n\n /-> cls\n /-> shared convs ->\n \\-> reg\n roi features\n ... |
@HEADS.register_module()
class SCNetBBoxHead(ConvFCBBoxHead):
'BBox head for `SCNet <https://arxiv.org/abs/2012.10150>`_.\n\n This inherits ``ConvFCBBoxHead`` with modified forward() function, allow us\n to get intermediate shared feature.\n '
def _forward_shared(self, x):
'Forward function ... |
@HEADS.register_module()
class DoubleHeadRoIHead(StandardRoIHead):
'RoI head for Double Head RCNN.\n\n https://arxiv.org/abs/1904.06493\n '
def __init__(self, reg_roi_scale_factor, **kwargs):
super(DoubleHeadRoIHead, self).__init__(**kwargs)
self.reg_roi_scale_factor = reg_roi_scale_fac... |
@HEADS.register_module()
class CoarseMaskHead(FCNMaskHead):
'Coarse mask head used in PointRend.\n\n Compared with standard ``FCNMaskHead``, ``CoarseMaskHead`` will downsample\n the input feature map instead of upsample it.\n\n Args:\n num_convs (int): Number of conv layers in the head. Default: 0... |
@HEADS.register_module()
class DynamicMaskHead(FCNMaskHead):
'Dynamic Mask Head for\n `Instances as Queries <http://arxiv.org/abs/2105.01928>`_\n\n Args:\n num_convs (int): Number of convolution layer.\n Defaults to 4.\n roi_feat_size (int): The output size of RoI extractor,\n ... |
@HEADS.register_module()
class FeatureRelayHead(BaseModule):
'Feature Relay Head used in `SCNet <https://arxiv.org/abs/2012.10150>`_.\n\n Args:\n in_channels (int, optional): number of input channels. Default: 256.\n conv_out_channels (int, optional): number of output channels before\n ... |
@HEADS.register_module()
class FusedSemanticHead(BaseModule):
'Multi-level fused semantic segmentation head.\n\n .. code-block:: none\n\n in_1 -> 1x1 conv ---\n |\n in_2 -> 1x1 conv -- |\n ||\n in_3 -> 1x1 conv - ||\n ... |
@HEADS.register_module()
class GlobalContextHead(BaseModule):
'Global context head used in `SCNet <https://arxiv.org/abs/2012.10150>`_.\n\n Args:\n num_convs (int, optional): number of convolutional layer in GlbCtxHead.\n Default: 4.\n in_channels (int, optional): number of input chann... |
@HEADS.register_module()
class HTCMaskHead(FCNMaskHead):
def __init__(self, with_conv_res=True, *args, **kwargs):
super(HTCMaskHead, self).__init__(*args, **kwargs)
self.with_conv_res = with_conv_res
if self.with_conv_res:
self.conv_res = ConvModule(self.conv_out_channels, sel... |
@HEADS.register_module()
class SCNetMaskHead(FCNMaskHead):
'Mask head for `SCNet <https://arxiv.org/abs/2012.10150>`_.\n\n Args:\n conv_to_res (bool, optional): if True, change the conv layers to\n ``SimplifiedBasicBlock``.\n '
def __init__(self, conv_to_res=True, **kwargs):
s... |
@HEADS.register_module()
class SCNetSemanticHead(FusedSemanticHead):
'Mask head for `SCNet <https://arxiv.org/abs/2012.10150>`_.\n\n Args:\n conv_to_res (bool, optional): if True, change the conv layers to\n ``SimplifiedBasicBlock``.\n '
def __init__(self, conv_to_res=True, **kwargs):... |
@HEADS.register_module()
class PISARoIHead(StandardRoIHead):
'The RoI head for `Prime Sample Attention in Object Detection\n <https://arxiv.org/abs/1904.04821>`_.'
def forward_train(self, x, img_metas, proposal_list, gt_bboxes, gt_labels, gt_bboxes_ignore=None, gt_masks=None):
"Forward function fo... |
@SHARED_HEADS.register_module()
class ResLayer(BaseModule):
def __init__(self, depth, stage=3, stride=2, dilation=1, style='pytorch', norm_cfg=dict(type='BN', requires_grad=True), norm_eval=True, with_cp=False, dcn=None, pretrained=None, init_cfg=None):
super(ResLayer, self).__init__(init_cfg)
se... |
@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... |
@DETECTORS.register_module()
class DDQRCNN(TwoStageDetector):
def forward_train(self, img, img_metas, gt_bboxes, gt_labels, gt_bboxes_ignore=None, gt_masks=None, proposals=None, **kwargs):
batch_input_shape = tuple(img[0].size()[(- 2):])
for img_meta in img_metas:
img_meta['batch_inpu... |
def padding_to(inputs, max=300):
if (max is None):
return inputs
num_padding = (max - len(inputs))
if (inputs.dim() > 1):
padding = inputs.new_zeros(num_padding, *inputs.size()[1:], dtype=inputs.dtype)
else:
padding = inputs.new_zeros(num_padding, dtype=inputs.dtype)
inputs... |
def align_tensor(inputs, max_len=None):
if (max_len is None):
max_len = max([len(item) for item in inputs])
return torch.stack([padding_to(item, max_len) for item in inputs])
|
def parse_args():
parser = argparse.ArgumentParser(description='MMDet test (and eval) a model')
parser.add_argument('config', help='test config file path')
parser.add_argument('checkpoint', help='checkpoint file')
parser.add_argument('--work-dir', help='the directory to save the file containing evalua... |
def replace_ceph_backend(cfg):
cfg_pretty_text = cfg.pretty_text
replace_strs = "file_client_args = dict(\n backend='petrel',\n path_mapping=dict({\n '.data/INPLACEHOLD/': 's3://openmmlab/datasets/detection/INPLACEHOLD/',\n 'd... |
def main():
args = parse_args()
assert (args.out or args.eval or args.format_only or args.show or args.show_dir), 'Please specify at least one operation (save/eval/format/show the results / save the results) with the argument "--out", "--eval", "--format-only", "--show" or "--show-dir"'
if (args.eval and ... |
def parse_args():
parser = argparse.ArgumentParser(description='Train a detector')
parser.add_argument('config', help='train config file path')
parser.add_argument('--work-dir', help='the dir to save logs and models')
parser.add_argument('--resume-from', help='the checkpoint file to resume from')
... |
def get_device():
'Returns an available device, cpu, cuda or mlu.'
is_device_available = {'cuda': torch.cuda.is_available()}
device_list = [k for (k, v) in is_device_available.items() if v]
return (device_list[0] if (len(device_list) == 1) else 'cpu')
|
def replace_ceph_backend(cfg):
cfg_pretty_text = cfg.pretty_text
replace_strs = "file_client_args = dict(\n backend='petrel',\n path_mapping=dict({\n '.data/INPLACEHOLD/': 's3://openmmlab/datasets/detection/INPLACEHOLD/',\n 'd... |
def main():
args = parse_args()
cfg = Config.fromfile(args.config)
if args.ceph:
cfg = replace_ceph_backend(cfg)
if (args.cfg_options is not None):
for (k, v) in args.cfg_options.items():
if v.startswith('dict'):
args.cfg_options[k] = eval(v)
cfg.mer... |
def _activation_summary(x):
'Helper to create summaries for activations.\n\n Creates a summary that provides a histogram of activations.\n Creates a summary that measures the sparsity of activations.\n\n Args:\n x: Tensor\n Returns:\n nothing\n '
tensor_name = re.sub(('%s_[0-9]*/' % TOWER_NAME), ''... |
def _variable_on_cpu(name, shape, initializer):
'Helper to create a Variable stored on CPU memory.\n\n Args:\n name: name of the variable\n shape: list of ints\n initializer: initializer for Variable\n\n Returns:\n Variable Tensor\n '
with tf.device('/cpu:0'):
dtype = (tf.float16 if FLA... |
def _variable_with_weight_decay(name, shape, stddev, wd):
'Helper to create an initialized Variable with weight decay.\n\n Note that the Variable is initialized with a truncated normal distribution.\n A weight decay is added only if one is specified.\n\n Args:\n name: name of the variable\n shape: list o... |
def distorted_inputs():
'Construct distorted input for CIFAR training using the Reader ops.\n\n Returns:\n images: Images. 4D tensor of [batch_size, IMAGE_SIZE, IMAGE_SIZE, 3] size.\n labels: Labels. 1D tensor of [batch_size] size.\n\n Raises:\n ValueError: If no data_dir\n '
if (not FLAGS.data_di... |
def inputs(eval_data):
'Construct input for CIFAR evaluation using the Reader ops.\n\n Args:\n eval_data: bool, indicating if one should use the train or eval data set.\n\n Returns:\n images: Images. 4D tensor of [batch_size, IMAGE_SIZE, IMAGE_SIZE, 3] size.\n labels: Labels. 1D tensor of [batch_size] ... |
def inference(images):
'Build the CIFAR-10 model.\n\n Args:\n images: Images returned from distorted_inputs() or inputs().\n\n Returns:\n Logits.\n '
with tf.variable_scope('conv1') as scope:
kernel = _variable_with_weight_decay('weights', shape=[5, 5, 3, 64], stddev=0.05, wd=0.0)
con... |
def loss(logits, labels):
'Add L2Loss to all the trainable variables.\n\n Add summary for "Loss" and "Loss/avg".\n Args:\n logits: Logits from inference().\n labels: Labels from distorted_inputs or inputs(). 1-D tensor\n of shape [batch_size]\n\n Returns:\n Loss tensor of type float.\n '
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.