code stringlengths 17 6.64M |
|---|
def _expand_binary_labels(labels, label_weights, label_channels):
bin_labels = labels.new_full((labels.size(0), label_channels), 0)
inds = torch.nonzero((labels >= 1)).squeeze()
if (inds.numel() > 0):
bin_labels[(inds, (labels[inds] - 1))] = 1
if (label_weights is None):
bin_label_weig... |
def binary_cross_entropy(pred, label, weight=None, reduction='mean', avg_factor=None):
if (pred.dim() != label.dim()):
(label, weight) = _expand_binary_labels(label, weight, pred.size((- 1)))
if (weight is not None):
weight = weight.float()
loss = F.binary_cross_entropy_with_logits(pred, l... |
def mask_cross_entropy(pred, target, label, reduction='mean', avg_factor=None):
assert ((reduction == 'mean') and (avg_factor is None))
num_rois = pred.size()[0]
inds = torch.arange(0, num_rois, dtype=torch.long, device=pred.device)
pred_slice = pred[(inds, label)].squeeze(1)
return F.binary_cross... |
@LOSSES.register_module
class CrossEntropyLoss(nn.Module):
def __init__(self, use_sigmoid=False, use_mask=False, reduction='mean', loss_weight=1.0):
super(CrossEntropyLoss, self).__init__()
assert ((use_sigmoid is False) or (use_mask is False))
self.use_sigmoid = use_sigmoid
self.... |
def py_sigmoid_focal_loss(pred, target, weight=None, gamma=2.0, alpha=0.25, reduction='mean', avg_factor=None):
pred_sigmoid = pred.sigmoid()
target = target.type_as(pred)
pt = (((1 - pred_sigmoid) * target) + (pred_sigmoid * (1 - target)))
focal_weight = (((alpha * target) + ((1 - alpha) * (1 - targe... |
def sigmoid_focal_loss(pred, target, weight=None, gamma=2.0, alpha=0.25, reduction='mean', avg_factor=None):
loss = _sigmoid_focal_loss(pred, target, gamma, alpha)
if (weight is not None):
weight = weight.view((- 1), 1)
loss = weight_reduce_loss(loss, weight, reduction, avg_factor)
return loss... |
@LOSSES.register_module
class FocalLoss(nn.Module):
def __init__(self, use_sigmoid=True, gamma=2.0, alpha=0.25, reduction='mean', loss_weight=1.0):
super(FocalLoss, self).__init__()
assert (use_sigmoid is True), 'Only sigmoid focal loss supported now.'
self.use_sigmoid = use_sigmoid
... |
def _expand_binary_labels(labels, label_weights, label_channels):
bin_labels = labels.new_full((labels.size(0), label_channels), 0)
inds = torch.nonzero((labels >= 1)).squeeze()
if (inds.numel() > 0):
bin_labels[(inds, (labels[inds] - 1))] = 1
bin_label_weights = label_weights.view((- 1), 1).e... |
@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.\n ... |
@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 (int)... |
@weighted_loss
def mse_loss(pred, target):
return F.mse_loss(pred, target, reduction='none')
|
@LOSSES.register_module
class MSELoss(nn.Module):
def __init__(self, reduction='mean', loss_weight=1.0):
super().__init__()
self.reduction = reduction
self.loss_weight = loss_weight
def forward(self, pred, target, weight=None, avg_factor=None):
loss = (self.loss_weight * mse_... |
@weighted_loss
def smooth_l1_loss(pred, target, beta=1.0):
assert (beta > 0)
assert ((pred.size() == target.size()) and (target.numel() > 0))
diff = torch.abs((pred - target))
loss = torch.where((diff < beta), (((0.5 * diff) * diff) / beta), (diff - (0.5 * beta)))
return loss
|
@LOSSES.register_module
class SmoothL1Loss(nn.Module):
def __init__(self, beta=1.0, reduction='mean', loss_weight=1.0):
super(SmoothL1Loss, self).__init__()
self.beta = beta
self.reduction = reduction
self.loss_weight = loss_weight
def forward(self, pred, target, weight=None,... |
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... |
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 losses of PyTorch.\n avg_factor (float... |
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\... |
@HEADS.register_module
class FusedSemanticHead(nn.Module):
'Multi-level fused semantic segmentation head.\n\n in_1 -> 1x1 conv ---\n |\n in_2 -> 1x1 conv -- |\n ||\n in_3 -> 1x1 conv - ||\n ||| /-> 1x1 conv (mask predictio... |
@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, self.... |
@NECKS.register_module
class BFP(nn.Module):
"BFP (Balanced Feature Pyrmamids)\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), see\... |
@NECKS.register_module
class FPN(nn.Module):
"Feature Pyramid Network.\n\n This is an implementation of - Feature Pyramid Networks for Object\n Detection (https://arxiv.org/abs/1612.03144)\n\n Args:\n in_channels (List[int]):\n number of input channels per scale\n\n out_channels ... |
@NECKS.register_module
class HRFPN(nn.Module):
'HRFPN (High Resolution Feature Pyrmamids)\n\n arXiv: https://arxiv.org/abs/1904.04514\n\n Args:\n in_channels (list): number of channels for each branch.\n out_channels (int): output channels of feature pyramids.\n num_outs (int): number o... |
class MergingCell(nn.Module):
def __init__(self, channels=256, with_conv=True, norm_cfg=None):
super(MergingCell, self).__init__()
self.with_conv = with_conv
if self.with_conv:
self.conv_out = ConvModule(channels, channels, 3, padding=1, norm_cfg=norm_cfg, order=('act', 'conv'... |
class SumCell(MergingCell):
def _binary_op(self, x1, x2):
return (x1 + x2)
|
class GPCell(MergingCell):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.global_pool = nn.AdaptiveAvgPool2d((1, 1))
def _binary_op(self, x1, x2):
x2_att = self.global_pool(x2).sigmoid()
return (x2 + (x2_att * x1))
|
@NECKS.register_module
class NASFPN(nn.Module):
'NAS-FPN.\n\n NAS-FPN: Learning Scalable Feature Pyramid Architecture for Object\n Detection. (https://arxiv.org/abs/1904.07392)\n '
def __init__(self, in_channels, out_channels, num_outs, stack_times, start_level=0, end_level=(- 1), add_extra_convs=Fa... |
@SHARED_HEADS.register_module
class ResLayer(nn.Module):
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):
super(ResLayer, self).__init__()
self.norm_eval = norm_eval
self.norm_... |
def bias_init_with_prob(prior_prob):
'initialize conv/fc bias value according to giving probablity.'
bias_init = float((- np.log(((1 - prior_prob) / prior_prob))))
return bias_init
|
def build_activation_layer(cfg):
'Build activation layer.\n\n Args:\n cfg (dict): cfg should contain:\n type (str): Identify activation layer type.\n layer args: args needed to instantiate a activation layer.\n\n Returns:\n layer (nn.Module): Created activation layer\n ... |
class _AffineGridGenerator(Function):
@staticmethod
def forward(ctx, theta, size, align_corners):
ctx.save_for_backward(theta)
ctx.size = size
ctx.align_corners = align_corners
func = affine_grid_cuda.affine_grid_generator_forward
output = func(theta, size, align_corne... |
def affine_grid(theta, size, align_corners=False):
if (torch.__version__ >= '1.3'):
return F.affine_grid(theta, size, align_corners)
elif align_corners:
return F.affine_grid(theta, size)
else:
if (not theta.is_floating_point()):
raise ValueError('Expected theta to have ... |
class CARAFENaiveFunction(Function):
@staticmethod
def forward(ctx, features, masks, kernel_size, group_size, scale_factor):
assert (scale_factor >= 1)
assert (masks.size(1) == ((kernel_size * kernel_size) * group_size))
assert (masks.size((- 1)) == (features.size((- 1)) * scale_facto... |
class CARAFENaive(Module):
def __init__(self, kernel_size, group_size, scale_factor):
super(CARAFENaive, self).__init__()
assert (isinstance(kernel_size, int) and isinstance(group_size, int) and isinstance(scale_factor, int))
self.kernel_size = kernel_size
self.group_size = group_... |
class CARAFEFunction(Function):
@staticmethod
def forward(ctx, features, masks, kernel_size, group_size, scale_factor):
assert (scale_factor >= 1)
assert (masks.size(1) == ((kernel_size * kernel_size) * group_size))
assert (masks.size((- 1)) == (features.size((- 1)) * scale_factor))
... |
class CARAFE(Module):
' CARAFE: Content-Aware ReAssembly of FEatures\n\n Please refer to https://arxiv.org/abs/1905.02188 for more details.\n\n Args:\n kernel_size (int): reassemble kernel size\n group_size (int): reassemble group size\n scale_factor (int): upsample ratio\n\n Returns... |
class CARAFEPack(nn.Module):
'A unified package of CARAFE upsampler that contains: 1) channel\n compressor 2) content encoder 3) CARAFE op.\n\n Official implementation of ICCV 2019 paper\n CARAFE: Content-Aware ReAssembly of FEatures\n Please refer to https://arxiv.org/abs/1905.02188 for more details.... |
def last_zero_init(m):
if isinstance(m, nn.Sequential):
constant_init(m[(- 1)], val=0)
else:
constant_init(m, val=0)
|
class ContextBlock(nn.Module):
def __init__(self, inplanes, ratio, pooling_type='att', fusion_types=('channel_add',)):
super(ContextBlock, self).__init__()
assert (pooling_type in ['avg', 'att'])
assert isinstance(fusion_types, (list, tuple))
valid_fusion_types = ['channel_add', '... |
def build_conv_layer(cfg, *args, **kwargs):
'Build convolution layer.\n\n Args:\n cfg (None or dict): cfg should contain:\n type (str): identify conv layer type.\n layer args: args needed to instantiate a conv layer.\n\n Returns:\n layer (nn.Module): created conv layer\n ... |
class ConvModule(nn.Module):
'A conv block that contains conv/norm/activation layers.\n\n Args:\n in_channels (int): Same as nn.Conv2d.\n out_channels (int): Same as nn.Conv2d.\n kernel_size (int or tuple[int]): Same as nn.Conv2d.\n stride (int or tuple[int]): Same as nn.Conv2d.\n ... |
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... |
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=dilation, groups=groups, bias=bias)
... |
class DeformRoIPoolingFunction(Function):
@staticmethod
def forward(ctx, data, rois, offset, spatial_scale, out_size, out_channels, no_trans, group_size=1, part_size=None, sample_per_part=4, trans_std=0.0):
(out_h, out_w) = _pair(out_size)
assert (isinstance(out_h, int) and isinstance(out_w, ... |
class DeformRoIPooling(nn.Module):
def __init__(self, spatial_scale, out_size, out_channels, no_trans, group_size=1, part_size=None, sample_per_part=4, trans_std=0.0):
super(DeformRoIPooling, self).__init__()
self.spatial_scale = spatial_scale
self.out_size = _pair(out_size)
self.... |
class DeformRoIPoolingPack(DeformRoIPooling):
def __init__(self, spatial_scale, out_size, out_channels, no_trans, group_size=1, part_size=None, sample_per_part=4, trans_std=0.0, num_offset_fcs=3, deform_fc_channels=1024):
super(DeformRoIPoolingPack, self).__init__(spatial_scale, out_size, out_channels, n... |
class ModulatedDeformRoIPoolingPack(DeformRoIPooling):
def __init__(self, spatial_scale, out_size, out_channels, no_trans, group_size=1, part_size=None, sample_per_part=4, trans_std=0.0, num_offset_fcs=3, num_mask_fcs=2, deform_fc_channels=1024):
super(ModulatedDeformRoIPoolingPack, self).__init__(spatia... |
class _GridSampler(Function):
@staticmethod
def forward(ctx, input, grid, mode_enum, padding_mode_enum, align_corners):
ctx.save_for_backward(input, grid)
ctx.mode_enum = mode_enum
ctx.padding_mode_enum = padding_mode_enum
ctx.align_corners = align_corners
if input.is_... |
def grid_sample(input, grid, mode='bilinear', padding_mode='zeros', align_corners=False):
if (torch.__version__ >= '1.3'):
return F.grid_sample(input, grid, mode, padding_mode, align_corners)
elif align_corners:
return F.grid_sample(input, grid, mode, padding_mode)
else:
assert (mo... |
class NonLocal2D(nn.Module):
'Non-local module.\n\n See https://arxiv.org/abs/1711.07971 for details.\n\n Args:\n in_channels (int): Channels of the input feature map.\n reduction (int): Channel reduction ratio.\n use_scale (bool): Whether to scale pairwise_weight by 1/inter_channels.\n... |
def build_norm_layer(cfg, num_features, postfix=''):
'Build normalization layer.\n\n Args:\n cfg (dict): cfg should contain:\n type (str): identify norm layer type.\n layer args: args needed to instantiate a norm layer.\n requires_grad (bool): [optional] whether stop gra... |
class RoIAlignFunction(Function):
@staticmethod
def forward(ctx, features, rois, out_size, spatial_scale, sample_num=0, aligned=True):
(out_h, out_w) = _pair(out_size)
assert (isinstance(out_h, int) and isinstance(out_w, int))
ctx.spatial_scale = spatial_scale
ctx.sample_num =... |
class RoIAlign(nn.Module):
def __init__(self, out_size, spatial_scale, sample_num=0, use_torchvision=False, aligned=False):
"\n Args:\n out_size (tuple): h, w\n spatial_scale (float): scale the input boxes by this number\n sample_num (int): number of inputs samples... |
class RoIPoolFunction(Function):
@staticmethod
def forward(ctx, features, rois, out_size, spatial_scale):
assert features.is_cuda
(out_h, out_w) = _pair(out_size)
assert (isinstance(out_h, int) and isinstance(out_w, int))
ctx.save_for_backward(rois)
num_channels = feat... |
class RoIPool(nn.Module):
def __init__(self, out_size, spatial_scale, use_torchvision=False):
super(RoIPool, self).__init__()
self.out_size = _pair(out_size)
self.spatial_scale = float(spatial_scale)
self.use_torchvision = use_torchvision
def forward(self, features, rois):
... |
class Scale(nn.Module):
'A learnable scale parameter.'
def __init__(self, scale=1.0):
super(Scale, self).__init__()
self.scale = nn.Parameter(torch.tensor(scale, dtype=torch.float))
def forward(self, x):
return (x * self.scale)
|
class SigmoidFocalLossFunction(Function):
@staticmethod
def forward(ctx, input, target, gamma=2.0, alpha=0.25):
ctx.save_for_backward(input, target)
num_classes = input.shape[1]
ctx.num_classes = num_classes
ctx.gamma = gamma
ctx.alpha = alpha
loss = sigmoid_fo... |
class SigmoidFocalLoss(nn.Module):
def __init__(self, gamma, alpha):
super(SigmoidFocalLoss, self).__init__()
self.gamma = gamma
self.alpha = alpha
def forward(self, logits, targets):
assert logits.is_cuda
loss = sigmoid_focal_loss(logits, targets, self.gamma, self.al... |
class PixelShufflePack(nn.Module):
'Pixel Shuffle upsample layer.\n\n Args:\n in_channels (int): Number of input channels\n out_channels (int): Number of output channels\n scale_factor (int): Upsample ratio\n upsample_kernel (int): Kernel size of Conv layer to expand the channels\n\... |
def build_upsample_layer(cfg):
'Build upsample layer.\n\n Args:\n cfg (dict): cfg should contain:\n type (str): Identify upsample layer type.\n upsample ratio (int): Upsample ratio\n layer args: args needed to instantiate a upsample layer.\n\n Returns:\n layer ... |
def collect_env():
env_info = {}
env_info['sys.platform'] = sys.platform
env_info['Python'] = sys.version.replace('\n', '')
cuda_available = torch.cuda.is_available()
env_info['CUDA available'] = cuda_available
if cuda_available:
from torch.utils.cpp_extension import CUDA_HOME
... |
def get_model_complexity_info(model, input_res, print_per_layer_stat=True, as_strings=True, input_constructor=None, ost=sys.stdout):
assert (type(input_res) is tuple)
assert (len(input_res) >= 2)
flops_model = add_flops_counting_methods(model)
flops_model.eval().start_flops_count()
if input_constr... |
def flops_to_string(flops, units='GMac', precision=2):
if (units is None):
if ((flops // (10 ** 9)) > 0):
return (str(round((flops / (10.0 ** 9)), precision)) + ' GMac')
elif ((flops // (10 ** 6)) > 0):
return (str(round((flops / (10.0 ** 6)), precision)) + ' MMac')
... |
def params_to_string(params_num):
"converting number to string.\n\n :param float params_num: number\n :returns str: number\n\n >>> params_to_string(1e9)\n '1000.0 M'\n >>> params_to_string(2e5)\n '200.0 k'\n >>> params_to_string(3e-9)\n '3e-09'\n "
if ((params_num // (10 ** 6)) > 0)... |
def print_model_with_flops(model, units='GMac', precision=3, ost=sys.stdout):
total_flops = model.compute_average_flops_cost()
def accumulate_flops(self):
if is_supported_instance(self):
return (self.__flops__ / model.__batch_counter__)
else:
sum = 0
for m ... |
def get_model_parameters_number(model):
params_num = sum((p.numel() for p in model.parameters() if p.requires_grad))
return params_num
|
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):
'A method that will be available after add_flops_counting_methods() is\n called on a desired net object.\n\n Returns current mean flops consumption per image.\n '
batches_count = self.__batch_counter__
flops_sum = 0
for module in self.modules():
i... |
def start_flops_count(self):
'A method that will be available after add_flops_counting_methods() is\n called on a desired net object.\n\n Activates the computation of mean flops consumption per image. Call it\n before you run the network.\n '
add_batch_counter_hook_function(self)
self.apply(ad... |
def stop_flops_count(self):
'A method that will be available after add_flops_counting_methods() is\n called on a desired net object.\n\n Stops computing the mean flops consumption per image. Call whenever you\n want to pause the computation.\n '
remove_batch_counter_hook_function(self)
self.ap... |
def reset_flops_count(self):
'A method that will be available after add_flops_counting_methods() is\n called on a desired net object.\n\n Resets statistics computed so far.\n '
add_batch_counter_variables_or_reset(self)
self.apply(add_flops_counter_variable_or_reset)
|
def add_flops_mask(module, mask):
def add_flops_mask_func(module):
if isinstance(module, torch.nn.Conv2d):
module.__mask__ = mask
module.apply(add_flops_mask_func)
|
def remove_flops_mask(module):
module.apply(add_flops_mask_variable_or_reset)
|
def is_supported_instance(module):
for mod in hook_mapping:
if issubclass(type(module), mod):
return True
return False
|
def empty_flops_counter_hook(module, input, output):
module.__flops__ += 0
|
def upsample_flops_counter_hook(module, input, output):
output_size = output[0]
batch_size = output_size.shape[0]
output_elements_count = batch_size
for val in output_size.shape[1:]:
output_elements_count *= val
module.__flops__ += int(output_elements_count)
|
def relu_flops_counter_hook(module, input, output):
active_elements_count = output.numel()
module.__flops__ += int(active_elements_count)
|
def linear_flops_counter_hook(module, input, output):
input = input[0]
batch_size = input.shape[0]
module.__flops__ += int(((batch_size * input.shape[1]) * output.shape[1]))
|
def pool_flops_counter_hook(module, input, output):
input = input[0]
module.__flops__ += int(np.prod(input.shape))
|
def bn_flops_counter_hook(module, input, output):
input = input[0]
batch_flops = np.prod(input.shape)
if module.affine:
batch_flops *= 2
module.__flops__ += int(batch_flops)
|
def gn_flops_counter_hook(module, input, output):
elems = np.prod(input[0].shape)
batch_flops = (3 * elems)
if module.affine:
batch_flops += elems
module.__flops__ += int(batch_flops)
|
def deconv_flops_counter_hook(conv_module, input, output):
input = input[0]
batch_size = input.shape[0]
(input_height, input_width) = input.shape[2:]
(kernel_height, kernel_width) = conv_module.kernel_size
in_channels = conv_module.in_channels
out_channels = conv_module.out_channels
groups... |
def conv_flops_counter_hook(conv_module, input, output):
input = input[0]
batch_size = input.shape[0]
output_dims = list(output.shape[2:])
kernel_dims = list(conv_module.kernel_size)
in_channels = conv_module.in_channels
out_channels = conv_module.out_channels
groups = conv_module.groups
... |
def batch_counter_hook(module, input, output):
batch_size = 1
if (len(input) > 0):
input = input[0]
batch_size = len(input)
else:
print('Warning! No positional inputs found for a module, assuming batch size is 1.')
module.__batch_counter__ += batch_size
|
def add_batch_counter_variables_or_reset(module):
module.__batch_counter__ = 0
|
def add_batch_counter_hook_function(module):
if hasattr(module, '__batch_counter_handle__'):
return
handle = module.register_forward_hook(batch_counter_hook)
module.__batch_counter_handle__ = handle
|
def remove_batch_counter_hook_function(module):
if hasattr(module, '__batch_counter_handle__'):
module.__batch_counter_handle__.remove()
del module.__batch_counter_handle__
|
def add_flops_counter_variable_or_reset(module):
if is_supported_instance(module):
module.__flops__ = 0
|
def add_flops_counter_hook_function(module):
if is_supported_instance(module):
if hasattr(module, '__flops_handle__'):
return
for (mod_type, counter_hook) in hook_mapping.items():
if issubclass(type(module), mod_type):
handle = module.register_forward_hook(c... |
def remove_flops_counter_hook_function(module):
if is_supported_instance(module):
if hasattr(module, '__flops_handle__'):
module.__flops_handle__.remove()
del module.__flops_handle__
|
def add_flops_mask_variable_or_reset(module):
if is_supported_instance(module):
module.__mask__ = None
|
def get_root_logger(log_file=None, log_level=logging.INFO):
'Get the root logger.\n\n The logger will be initialized if it has not been initialized. By default a\n StreamHandler will be added. If `log_file` is specified, a FileHandler will\n also be added. The name of the root logger is the top-level pac... |
def print_log(msg, logger=None, level=logging.INFO):
'Print a log message.\n\n Args:\n msg (str): The message to be logged.\n logger (logging.Logger | str | None): The logger to be used. Some\n special loggers are:\n - "root": the root logger obtained with `get_root_logger()... |
class Registry(object):
def __init__(self, name):
self._name = name
self._module_dict = dict()
def __repr__(self):
format_str = (self.__class__.__name__ + '(name={}, items={})'.format(self._name, list(self._module_dict.keys())))
return format_str
@property
def name(s... |
def build_from_cfg(cfg, registry, default_args=None):
'Build a module from config dict.\n\n Args:\n cfg (dict): Config dict. It should at least contain the key "type".\n registry (:obj:`Registry`): The registry to search the type from.\n default_args (dict, optional): Default initializatio... |
class NiceRepr(object):
'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__``,... |
def readme():
with open('README.md', encoding='utf-8') as f:
content = f.read()
return content
|
def get_git_hash():
def _minimal_ext_cmd(cmd):
env = {}
for k in ['SYSTEMROOT', 'PATH', 'HOME']:
v = os.environ.get(k)
if (v is not None):
env[k] = v
env['LANGUAGE'] = 'C'
env['LANG'] = 'C'
env['LC_ALL'] = 'C'
out = subproces... |
def get_hash():
if os.path.exists('.git'):
sha = get_git_hash()[:7]
elif os.path.exists(version_file):
try:
from mmdet.version import __version__
sha = __version__.split('+')[(- 1)]
except ImportError:
raise ImportError('Unable to get git version')
... |
def write_version_py():
content = "# GENERATED VERSION FILE\n# TIME: {}\n\n__version__ = '{}'\nshort_version = '{}'\n"
sha = get_hash()
VERSION = ((SHORT_VERSION + '+') + sha)
with open(version_file, 'w') as f:
f.write(content.format(time.asctime(), VERSION, SHORT_VERSION))
|
def get_version():
with open(version_file, 'r') as f:
exec(compile(f.read(), version_file, 'exec'))
return locals()['__version__']
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.