code stringlengths 17 6.64M |
|---|
def rotated_feature_align(features, best_rbboxes, spatial_scale=(1 / 8), points=1):
return RotatedFeatureAlignFunction.apply(features, best_rbboxes, spatial_scale, points)
|
@CONV_LAYERS.register_module(name='SAC')
class SAConv2d(ConvAWS2d):
"SAC (Switchable Atrous Convolution)\n\n This is an implementation of `DetectoRS: Detecting Objects with Recursive\n Feature Pyramid and Switchable Atrous Convolution\n <https://arxiv.org/abs/2006.02334>`_.\n\n Args:\n in_chann... |
def _calculate_fan_in_and_fan_out_hwio(tensor):
dimensions = tensor.ndimension()
if (dimensions < 2):
raise ValueError('fan in and fan out can not be computed for tensorwith fewer than 2 dimensions')
if (dimensions == 2):
fan_in = tensor.size((- 2))
fan_out = tensor.size((- 1))
... |
class SparseConvolution(SparseModule):
def __init__(self, ndim, in_channels, out_channels, kernel_size=3, stride=1, padding=0, dilation=1, groups=1, bias=True, subm=False, output_padding=0, transposed=False, inverse=False, indice_key=None, fused_bn=False):
super(SparseConvolution, self).__init__()
... |
@CONV_LAYERS.register_module()
class SparseConv2d(SparseConvolution):
def __init__(self, in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, bias=True, indice_key=None):
super(SparseConv2d, self).__init__(2, in_channels, out_channels, kernel_size, stride, padding, dilation,... |
@CONV_LAYERS.register_module()
class SparseConv3d(SparseConvolution):
def __init__(self, in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, bias=True, indice_key=None):
super(SparseConv3d, self).__init__(3, in_channels, out_channels, kernel_size, stride, padding, dilation,... |
@CONV_LAYERS.register_module()
class SparseConv4d(SparseConvolution):
def __init__(self, in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, bias=True, indice_key=None):
super(SparseConv4d, self).__init__(4, in_channels, out_channels, kernel_size, stride, padding, dilation,... |
@CONV_LAYERS.register_module()
class SparseConvTranspose2d(SparseConvolution):
def __init__(self, in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, bias=True, indice_key=None):
super(SparseConvTranspose2d, self).__init__(2, in_channels, out_channels, kernel_size, stride, ... |
@CONV_LAYERS.register_module()
class SparseConvTranspose3d(SparseConvolution):
def __init__(self, in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, bias=True, indice_key=None):
super(SparseConvTranspose3d, self).__init__(3, in_channels, out_channels, kernel_size, stride, ... |
@CONV_LAYERS.register_module()
class SparseInverseConv2d(SparseConvolution):
def __init__(self, in_channels, out_channels, kernel_size, indice_key=None, bias=True):
super(SparseInverseConv2d, self).__init__(2, in_channels, out_channels, kernel_size, bias=bias, inverse=True, indice_key=indice_key)
|
@CONV_LAYERS.register_module()
class SparseInverseConv3d(SparseConvolution):
def __init__(self, in_channels, out_channels, kernel_size, indice_key=None, bias=True):
super(SparseInverseConv3d, self).__init__(3, in_channels, out_channels, kernel_size, bias=bias, inverse=True, indice_key=indice_key)
|
@CONV_LAYERS.register_module()
class SubMConv2d(SparseConvolution):
def __init__(self, in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, bias=True, indice_key=None):
super(SubMConv2d, self).__init__(2, in_channels, out_channels, kernel_size, stride, padding, dilation, gro... |
@CONV_LAYERS.register_module()
class SubMConv3d(SparseConvolution):
def __init__(self, in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, bias=True, indice_key=None):
super(SubMConv3d, self).__init__(3, in_channels, out_channels, kernel_size, stride, padding, dilation, gro... |
@CONV_LAYERS.register_module()
class SubMConv4d(SparseConvolution):
def __init__(self, in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, bias=True, indice_key=None):
super(SubMConv4d, self).__init__(4, in_channels, out_channels, kernel_size, stride, padding, dilation, gro... |
class SparseConvFunction(Function):
'Sparse Convolution.\n\n Please refer to `SECOND <https://www.mdpi.com/1424-8220/18/10/3337>`_ for\n more details.\n '
@staticmethod
def forward(ctx, features, filters, indice_pairs, indice_pair_num, num_activate_out):
'\n Args:\n fea... |
class SparseInverseConvFunction(Function):
@staticmethod
def forward(ctx, features, filters, indice_pairs, indice_pair_num, num_activate_out):
'\n Args:\n features (torch.Tensor): Features that needs to convolute.\n filters (torch.nn.parameter.Parameter): Convolution filt... |
class SubMConvFunction(Function):
@staticmethod
def forward(ctx, features, filters, indice_pairs, indice_pair_num, num_activate_out):
'\n Args:\n features (torch.Tensor): Features that needs to convolute.\n filters (torch.nn.parameter.Parameter): Convolution filters.\n ... |
class SparseMaxPoolFunction(Function):
@staticmethod
def forward(ctx, features, indice_pairs, indice_pair_num, num_activate_out):
'\n Args:\n features (torch.Tensor): Features that needs to convolute.\n indice_pairs (torch.Tensor): Indice pairs between inputs locations\n ... |
def is_spconv_module(module):
spconv_modules = (SparseModule,)
return isinstance(module, spconv_modules)
|
def is_sparse_conv(module):
from .sparse_conv import SparseConvolution
return isinstance(module, SparseConvolution)
|
def _mean_update(vals, m_vals, t):
outputs = []
if (not isinstance(vals, list)):
vals = [vals]
if (not isinstance(m_vals, list)):
m_vals = [m_vals]
for (val, m_val) in zip(vals, m_vals):
output = (((t / float((t + 1))) * m_val) + ((1 / float((t + 1))) * val))
outputs.ap... |
class SparseModule(nn.Module):
'place holder, All module subclass from this will take sptensor in\n SparseSequential.'
pass
|
class SparseSequential(SparseModule):
"A sequential container.\n Modules will be added to it in the order they are passed in the\n constructor.\n Alternatively, an ordered dict of modules can also be passed in.\n\n To make it easier to understand, given is a small example::\n\n Example:\n >>... |
class ToDense(SparseModule):
'convert SparseConvTensor to NCHW dense tensor.'
def forward(self, x: SparseConvTensor):
return x.dense()
|
class RemoveGrid(SparseModule):
'remove pre-allocated grid buffer.'
def forward(self, x: SparseConvTensor):
x.grid = None
return x
|
def get_conv_output_size(input_size, kernel_size, stride, padding, dilation):
ndim = len(input_size)
output_size = []
for i in range(ndim):
size = (((((input_size[i] + (2 * padding[i])) - (dilation[i] * (kernel_size[i] - 1))) - 1) // stride[i]) + 1)
if (kernel_size[i] == (- 1)):
... |
def get_deconv_output_size(input_size, kernel_size, stride, padding, dilation, output_padding):
ndim = len(input_size)
output_size = []
for i in range(ndim):
if (kernel_size[i] == (- 1)):
raise ValueError("deconv don't support kernel_size < 0")
size = (((((input_size[i] - 1) * ... |
def get_indice_pairs(indices, batch_size, spatial_shape, ksize=3, stride=1, padding=0, dilation=1, out_padding=0, subm=False, transpose=False, grid=None):
ndim = (indices.shape[1] - 1)
if (not isinstance(ksize, (list, tuple))):
ksize = ([ksize] * ndim)
if (not isinstance(stride, (list, tuple))):
... |
def indice_conv(features, filters, indice_pairs, indice_pair_num, num_activate_out, inverse=False, subm=False):
if ((filters.dtype == torch.float32) or (filters.dtype == torch.half)):
return ext_module.indice_conv_forward(features, filters, indice_pairs, indice_pair_num, num_activate_out, int(inverse), in... |
def fused_indice_conv(features, filters, bias, indice_pairs, indice_pair_num, num_activate_out, inverse, subm):
if ((features.dtype == torch.half) or (filters.dtypes == torch.float32)):
func = ext_module.fused_indice_conv_forward
else:
raise NotImplementedError
return func(features, filter... |
def indice_conv_backward(features, filters, out_bp, indice_pairs, indice_pair_num, inverse=False, subm=False):
if ((filters.dtype == torch.float32) or (filters.dtype == torch.half)):
return ext_module.indice_conv_backward(features, filters, out_bp, indice_pairs, indice_pair_num, int(inverse), int(subm))
... |
def indice_maxpool(features, indice_pairs, indice_pair_num, num_activate_out):
if ((features.dtype == torch.float32) or (features.dtype == torch.half)):
return ext_module.indice_maxpool_forward(features, indice_pairs, indice_pair_num, num_activate_out)
else:
raise NotImplementedError
|
def indice_maxpool_backward(features, out_features, out_bp, indice_pairs, indice_pair_num):
if ((features.dtype == torch.float32) or (features.dtype == torch.half)):
return ext_module.indice_maxpool_backward(features, out_features, out_bp, indice_pairs, indice_pair_num)
else:
raise NotImplemen... |
class SparseMaxPool(SparseModule):
def __init__(self, ndim, kernel_size, stride=1, padding=0, dilation=1, subm=False):
super(SparseMaxPool, self).__init__()
if (not isinstance(kernel_size, (list, tuple))):
kernel_size = ([kernel_size] * ndim)
if (not isinstance(stride, (list, ... |
class SparseMaxPool2d(SparseMaxPool):
def __init__(self, kernel_size, stride=1, padding=0, dilation=1):
super(SparseMaxPool2d, self).__init__(2, kernel_size, stride, padding, dilation)
|
class SparseMaxPool3d(SparseMaxPool):
def __init__(self, kernel_size, stride=1, padding=0, dilation=1):
super(SparseMaxPool3d, self).__init__(3, kernel_size, stride, padding, dilation)
|
class SyncBatchNormFunction(Function):
@staticmethod
def symbolic(g, input, running_mean, running_var, weight, bias, momentum, eps, group, group_size, stats_mode):
return g.op('mmcv::MMCVSyncBatchNorm', input, running_mean, running_var, weight, bias, momentum_f=momentum, eps_f=eps, group_i=group, gro... |
@NORM_LAYERS.register_module(name='MMSyncBN')
class SyncBatchNorm(Module):
"Synchronized Batch Normalization.\n\n Args:\n num_features (int): number of features/chennels in input tensor\n eps (float, optional): a value added to the denominator for numerical\n stability. Defaults to 1e-... |
class ThreeInterpolate(Function):
'Performs weighted linear interpolation on 3 features.\n\n Please refer to `Paper of PointNet++ <https://arxiv.org/abs/1706.02413>`_\n for more details.\n '
@staticmethod
def forward(ctx, features: torch.Tensor, indices: torch.Tensor, weight: torch.Tensor) -> to... |
class ThreeNN(Function):
'Find the top-3 nearest neighbors of the target set from the source set.\n\n Please refer to `Paper of PointNet++ <https://arxiv.org/abs/1706.02413>`_\n for more details.\n '
@staticmethod
def forward(ctx, target: torch.Tensor, source: torch.Tensor) -> Tuple[(torch.Tenso... |
class TINShiftFunction(Function):
@staticmethod
def forward(ctx, input, shift):
C = input.size(2)
num_segments = shift.size(1)
if (((C // num_segments) <= 0) or ((C % num_segments) != 0)):
raise ValueError(f'C should be a multiple of num_segments, but got C={C} and num_seg... |
class TINShift(nn.Module):
'Temporal Interlace Shift.\n\n Temporal Interlace shift is a differentiable temporal-wise frame shifting\n which is proposed in "Temporal Interlacing Network"\n\n Please refer to `Temporal Interlacing Network\n <https://arxiv.org/abs/2001.06499>`_ for more details.\n\n Co... |
class _Voxelization(Function):
@staticmethod
def forward(ctx, points, voxel_size, coors_range, max_points=35, max_voxels=20000, deterministic=True):
'Convert kitti points(N, >=3) to voxels.\n\n Args:\n points (torch.Tensor): [N, ndim]. Points[:, :3] contain xyz points\n ... |
class Voxelization(nn.Module):
'Convert kitti points(N, >=3) to voxels.\n\n Please refer to `Point-Voxel CNN for Efficient 3D Deep Learning\n <https://arxiv.org/abs/1907.03739>`_ for more details.\n\n Args:\n voxel_size (tuple or float): The size of voxel with the shape of [3].\n point_clou... |
def scatter(input, devices, streams=None):
'Scatters tensor across multiple GPUs.'
if (streams is None):
streams = ([None] * len(devices))
if isinstance(input, list):
chunk_size = (((len(input) - 1) // len(devices)) + 1)
outputs = [scatter(input[i], [devices[(i // chunk_size)]], [s... |
def synchronize_stream(output, devices, streams):
if isinstance(output, list):
chunk_size = (len(output) // len(devices))
for i in range(len(devices)):
for j in range(chunk_size):
synchronize_stream(output[((i * chunk_size) + j)], [devices[i]], [streams[i]])
elif is... |
def get_input_device(input):
if isinstance(input, list):
for item in input:
input_device = get_input_device(item)
if (input_device != (- 1)):
return input_device
return (- 1)
elif isinstance(input, torch.Tensor):
return (input.get_device() if inp... |
class Scatter():
@staticmethod
def forward(target_gpus, input):
input_device = get_input_device(input)
streams = None
if ((input_device == (- 1)) and (target_gpus != [(- 1)])):
streams = [_get_stream(device) for device in target_gpus]
outputs = scatter(input, targe... |
def collate(batch, samples_per_gpu=1):
'Puts each data field into a tensor/DataContainer with outer dimension\n batch size.\n\n Extend default_collate to add support for\n :type:`~mmcv.parallel.DataContainer`. There are 3 cases.\n\n 1. cpu_only = True, e.g., meta data\n 2. cpu_only = False, stack =... |
def assert_tensor_type(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
if (not isinstance(args[0].data, torch.Tensor)):
raise AttributeError(f'{args[0].__class__.__name__} has no attribute {func.__name__} for type {args[0].datatype}')
return func(*args, **kwargs)
r... |
class DataContainer():
'A container for any type of objects.\n\n Typically tensors will be stacked in the collate function and sliced along\n some dimension in the scatter function. This behavior has some limitations.\n 1. All tensors have to be the same size.\n 2. Types are limited (numpy array or Te... |
class MMDataParallel(DataParallel):
'The DataParallel module that supports DataContainer.\n\n MMDataParallel has two main differences with PyTorch DataParallel:\n\n - It supports a custom type :class:`DataContainer` which allows more\n flexible control of input data during both GPU and CPU inference.\n... |
class MMDistributedDataParallel(DistributedDataParallel):
'The DDP module that supports DataContainer.\n\n MMDDP has two main differences with PyTorch DDP:\n\n - It supports a custom type :class:`DataContainer` which allows more\n flexible control of input data.\n - It implement two APIs ``train_ste... |
@MODULE_WRAPPERS.register_module()
class MMDistributedDataParallel(nn.Module):
def __init__(self, module, dim=0, broadcast_buffers=True, bucket_cap_mb=25):
super(MMDistributedDataParallel, self).__init__()
self.module = module
self.dim = dim
self.broadcast_buffers = broadcast_buff... |
def scatter(inputs, target_gpus, dim=0):
'Scatter inputs to target gpus.\n\n The only difference from original :func:`scatter` is to add support for\n :type:`~mmcv.parallel.DataContainer`.\n '
def scatter_map(obj):
if isinstance(obj, torch.Tensor):
if (target_gpus != [(- 1)]):
... |
def scatter_kwargs(inputs, kwargs, target_gpus, dim=0):
'Scatter with support for kwargs dictionary.'
inputs = (scatter(inputs, target_gpus, dim) if inputs else [])
kwargs = (scatter(kwargs, target_gpus, dim) if kwargs else [])
if (len(inputs) < len(kwargs)):
inputs.extend([() for _ in range((... |
def is_module_wrapper(module):
'Check if a module is a module wrapper.\n\n The following 3 modules in MMCV (and their subclasses) are regarded as\n module wrappers: DataParallel, DistributedDataParallel,\n MMDistributedDataParallel (the deprecated version). You may add you own\n module wrapper by regi... |
class BaseModule(nn.Module, metaclass=ABCMeta):
'Base module for all modules in openmmlab.\n\n ``BaseModule`` is a wrapper of ``torch.nn.Module`` with additional\n functionality of parameter initialization. Compared with\n ``torch.nn.Module``, ``BaseModule`` mainly adds three attributes.\n\n - ``init_... |
class Sequential(BaseModule, nn.Sequential):
'Sequential module in openmmlab.\n\n Args:\n init_cfg (dict, optional): Initialization config dict.\n '
def __init__(self, *args, init_cfg=None):
BaseModule.__init__(self, init_cfg)
nn.Sequential.__init__(self, *args)
|
class ModuleList(BaseModule, nn.ModuleList):
'ModuleList in openmmlab.\n\n Args:\n modules (iterable, optional): an iterable of modules to add.\n init_cfg (dict, optional): Initialization config dict.\n '
def __init__(self, modules=None, init_cfg=None):
BaseModule.__init__(self, i... |
class ModuleDict(BaseModule, nn.ModuleDict):
'ModuleDict in openmmlab.\n\n Args:\n modules (dict, optional): a mapping (dictionary) of (string: module)\n or an iterable of key-value pairs of type (string, module).\n init_cfg (dict, optional): Initialization config dict.\n '
def... |
class BaseRunner(metaclass=ABCMeta):
'The base class of Runner, a training helper for PyTorch.\n\n All subclasses should implement the following APIs:\n\n - ``run()``\n - ``train()``\n - ``val()``\n - ``save_checkpoint()``\n\n Args:\n model (:obj:`torch.nn.Module`): The model to be run.\n... |
def build_runner_constructor(cfg):
return RUNNER_BUILDERS.build(cfg)
|
def build_runner(cfg, default_args=None):
runner_cfg = copy.deepcopy(cfg)
constructor_type = runner_cfg.pop('constructor', 'DefaultRunnerConstructor')
runner_constructor = build_runner_constructor(dict(type=constructor_type, runner_cfg=runner_cfg, default_args=default_args))
runner = runner_constructo... |
def _get_mmcv_home():
mmcv_home = os.path.expanduser(os.getenv(ENV_MMCV_HOME, os.path.join(os.getenv(ENV_XDG_CACHE_HOME, DEFAULT_CACHE_DIR), 'mmcv')))
mkdir_or_exist(mmcv_home)
return mmcv_home
|
def load_state_dict(module, state_dict, strict=False, logger=None):
"Load state_dict to a module.\n\n This method is modified from :meth:`torch.nn.Module.load_state_dict`.\n Default value for ``strict`` is set to ``False`` and the message for\n param mismatch will be shown even if strict is False.\n\n ... |
def get_torchvision_models():
model_urls = dict()
for (_, name, ispkg) in pkgutil.walk_packages(torchvision.models.__path__):
if ispkg:
continue
_zoo = import_module(f'torchvision.models.{name}')
if hasattr(_zoo, 'model_urls'):
_urls = getattr(_zoo, 'model_urls'... |
def get_external_models():
mmcv_home = _get_mmcv_home()
default_json_path = osp.join(mmcv.__path__[0], 'model_zoo/open_mmlab.json')
default_urls = load_file(default_json_path)
assert isinstance(default_urls, dict)
external_json_path = osp.join(mmcv_home, 'open_mmlab.json')
if osp.exists(extern... |
def get_mmcls_models():
mmcls_json_path = osp.join(mmcv.__path__[0], 'model_zoo/mmcls.json')
mmcls_urls = load_file(mmcls_json_path)
return mmcls_urls
|
def get_deprecated_model_names():
deprecate_json_path = osp.join(mmcv.__path__[0], 'model_zoo/deprecated.json')
deprecate_urls = load_file(deprecate_json_path)
assert isinstance(deprecate_urls, dict)
return deprecate_urls
|
def _process_mmcls_checkpoint(checkpoint):
if ('state_dict' in checkpoint):
state_dict = checkpoint['state_dict']
else:
state_dict = checkpoint
new_state_dict = OrderedDict()
for (k, v) in state_dict.items():
if k.startswith('backbone.'):
new_state_dict[k[9:]] = v
... |
class CheckpointLoader():
'A general checkpoint loader to manage all schemes.'
_schemes = {}
@classmethod
def _register_scheme(cls, prefixes, loader, force=False):
if isinstance(prefixes, str):
prefixes = [prefixes]
else:
assert isinstance(prefixes, (list, tupl... |
@CheckpointLoader.register_scheme(prefixes='')
def load_from_local(filename, map_location):
'load checkpoint by local file path.\n\n Args:\n filename (str): local checkpoint file path\n map_location (str, optional): Same as :func:`torch.load`.\n\n Returns:\n dict or OrderedDict: The loa... |
@CheckpointLoader.register_scheme(prefixes=('http://', 'https://'))
def load_from_http(filename, map_location=None, model_dir=None):
'load checkpoint through HTTP or HTTPS scheme path. In distributed\n setting, this function only download checkpoint at local rank 0.\n\n Args:\n filename (str): checkp... |
@CheckpointLoader.register_scheme(prefixes='pavi://')
def load_from_pavi(filename, map_location=None):
'load checkpoint through the file path prefixed with pavi. In distributed\n setting, this function download ckpt at all ranks to different temporary\n directories.\n\n Args:\n filename (str): che... |
@CheckpointLoader.register_scheme(prefixes='(\\S+\\:)?s3://')
def load_from_ceph(filename, map_location=None, backend='petrel'):
"load checkpoint through the file path prefixed with s3. In distributed\n setting, this function download ckpt at all ranks to different temporary\n directories.\n\n Note:\n ... |
@CheckpointLoader.register_scheme(prefixes=('modelzoo://', 'torchvision://'))
def load_from_torchvision(filename, map_location=None):
'load checkpoint through the file path prefixed with modelzoo or\n torchvision.\n\n Args:\n filename (str): checkpoint file path with modelzoo or\n torchvis... |
@CheckpointLoader.register_scheme(prefixes=('open-mmlab://', 'openmmlab://'))
def load_from_openmmlab(filename, map_location=None):
'load checkpoint through the file path prefixed with open-mmlab or\n openmmlab.\n\n Args:\n filename (str): checkpoint file path with open-mmlab or\n openmmlab pr... |
@CheckpointLoader.register_scheme(prefixes='mmcls://')
def load_from_mmcls(filename, map_location=None):
'load checkpoint through the file path prefixed with mmcls.\n\n Args:\n filename (str): checkpoint file path with mmcls prefix\n map_location (str, optional): Same as :func:`torch.load`.\n\n ... |
def _load_checkpoint(filename, map_location=None, logger=None):
'Load checkpoint from somewhere (modelzoo, file, url).\n\n Args:\n filename (str): Accept local filepath, URL, ``torchvision://xxx``,\n ``open-mmlab://xxx``. Please refer to ``docs/model_zoo.md`` for\n details.\n ... |
def _load_checkpoint_with_prefix(prefix, filename, map_location=None):
'Load partial pretrained model with specific prefix.\n\n Args:\n prefix (str): The prefix of sub-module.\n filename (str): Accept local filepath, URL, ``torchvision://xxx``,\n ``open-mmlab://xxx``. Please refer to `... |
def load_checkpoint(model, filename, map_location=None, strict=False, logger=None, revise_keys=[('^module\\.', '')]):
"Load checkpoint from a file or URI.\n\n Args:\n model (Module): Module to load checkpoint.\n filename (str): Accept local filepath, URL, ``torchvision://xxx``,\n ``ope... |
def weights_to_cpu(state_dict):
'Copy a model state_dict to cpu.\n\n Args:\n state_dict (OrderedDict): Model weights on GPU.\n\n Returns:\n OrderedDict: Model weights on GPU.\n '
state_dict_cpu = OrderedDict()
for (key, val) in state_dict.items():
state_dict_cpu[key] = val.c... |
def _save_to_state_dict(module, destination, prefix, keep_vars):
'Saves module state to `destination` dictionary.\n\n This method is modified from :meth:`torch.nn.Module._save_to_state_dict`.\n\n Args:\n module (nn.Module): The module to generate state_dict.\n destination (dict): A dict where ... |
def get_state_dict(module, destination=None, prefix='', keep_vars=False):
'Returns a dictionary containing a whole state of the module.\n\n Both parameters and persistent buffers (e.g. running averages) are\n included. Keys are corresponding parameter and buffer names.\n\n This method is modified from :m... |
def save_checkpoint(model, filename, optimizer=None, meta=None, file_client_args=None):
'Save checkpoint to file.\n\n The checkpoint will have 3 fields: ``meta``, ``state_dict`` and\n ``optimizer``. By default ``meta`` will contain version and time info.\n\n Args:\n model (Module): Module whose pa... |
@RUNNER_BUILDERS.register_module()
class DefaultRunnerConstructor():
"Default constructor for runners.\n\n Custom existing `Runner` like `EpocBasedRunner` though `RunnerConstructor`.\n For example, We can inject some new properties and functions for `Runner`.\n\n Example:\n >>> from mmcv.runner im... |
def init_dist(launcher, backend='nccl', **kwargs):
if (mp.get_start_method(allow_none=True) is None):
mp.set_start_method('spawn')
if (launcher == 'pytorch'):
_init_dist_pytorch(backend, **kwargs)
elif (launcher == 'mpi'):
_init_dist_mpi(backend, **kwargs)
elif (launcher == 'sl... |
def _init_dist_pytorch(backend, **kwargs):
rank = int(os.environ['RANK'])
num_gpus = torch.cuda.device_count()
torch.cuda.set_device((rank % num_gpus))
dist.init_process_group(backend=backend, **kwargs)
|
def _init_dist_mpi(backend, **kwargs):
rank = int(os.environ['OMPI_COMM_WORLD_RANK'])
num_gpus = torch.cuda.device_count()
torch.cuda.set_device((rank % num_gpus))
dist.init_process_group(backend=backend, **kwargs)
|
def _init_dist_slurm(backend, port=None):
'Initialize slurm distributed training environment.\n\n If argument ``port`` is not specified, then the master port will be system\n environment variable ``MASTER_PORT``. If ``MASTER_PORT`` is not in system\n environment variable, then a default port ``29500`` wi... |
def get_dist_info():
if (dist.is_available() and dist.is_initialized()):
rank = dist.get_rank()
world_size = dist.get_world_size()
else:
rank = 0
world_size = 1
return (rank, world_size)
|
def master_only(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
(rank, _) = get_dist_info()
if (rank == 0):
return func(*args, **kwargs)
return wrapper
|
def allreduce_params(params, coalesce=True, bucket_size_mb=(- 1)):
'Allreduce parameters.\n\n Args:\n params (list[torch.Parameters]): List of parameters or buffers of a\n model.\n coalesce (bool, optional): Whether allreduce parameters as a whole.\n Defaults to True.\n ... |
def allreduce_grads(params, coalesce=True, bucket_size_mb=(- 1)):
'Allreduce gradients.\n\n Args:\n params (list[torch.Parameters]): List of parameters of a model\n coalesce (bool, optional): Whether allreduce parameters as a whole.\n Defaults to True.\n bucket_size_mb (int, opt... |
def _allreduce_coalesced(tensors, world_size, bucket_size_mb=(- 1)):
if (bucket_size_mb > 0):
bucket_size_bytes = ((bucket_size_mb * 1024) * 1024)
buckets = _take_tensors(tensors, bucket_size_bytes)
else:
buckets = OrderedDict()
for tensor in tensors:
tp = tensor.ty... |
@RUNNERS.register_module()
class EpochBasedRunner(BaseRunner):
'Epoch-based Runner.\n\n This runner train models epoch by epoch.\n '
def run_iter(self, data_batch, train_mode, **kwargs):
if (self.batch_processor is not None):
outputs = self.batch_processor(self.model, data_batch, tr... |
@RUNNERS.register_module()
class Runner(EpochBasedRunner):
'Deprecated name of EpochBasedRunner.'
def __init__(self, *args, **kwargs):
warnings.warn('Runner was deprecated, please use EpochBasedRunner instead', DeprecationWarning)
super().__init__(*args, **kwargs)
|
def cast_tensor_type(inputs, src_type, dst_type):
'Recursively convert Tensor in inputs from src_type to dst_type.\n\n Note:\n In v1.4.4 and later, ``cast_tersor_type`` will only convert the\n torch.Tensor which is consistent with ``src_type`` to the ``dst_type``.\n Before v1.4.4, it ignor... |
def auto_fp16(apply_to=None, out_fp32=False):
"Decorator to enable fp16 training automatically.\n\n This decorator is useful when you write custom modules and want to support\n mixed precision training. If inputs arguments are fp32 tensors, they will\n be converted to fp16 automatically. Arguments other ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.