code stringlengths 17 6.64M |
|---|
def force_fp32(apply_to=None, out_fp16=False):
"Decorator to convert input arguments to fp32 in force.\n\n This decorator is useful when you write custom modules and want to support\n mixed precision training. If there are some inputs that must be processed\n in fp32 mode, then this decorator can handle ... |
def allreduce_grads(params, coalesce=True, bucket_size_mb=(- 1)):
warnings.warning('"mmcv.runner.fp16_utils.allreduce_grads" is deprecated, and will be removed in v2.8. Please switch to "mmcv.runner.allreduce_grads', DeprecationWarning)
_allreduce_grads(params, coalesce=coalesce, bucket_size_mb=bucket_size_mb... |
def wrap_fp16_model(model):
'Wrap the FP32 model to FP16.\n\n If you are using PyTorch >= 1.6, torch.cuda.amp is used as the\n backend, otherwise, original mmcv implementation will be adopted.\n\n For PyTorch >= 1.6, this function will\n 1. Set fp16 flag inside the model to True.\n\n Otherwise:\n ... |
def patch_norm_fp32(module):
'Recursively convert normalization layers from FP16 to FP32.\n\n Args:\n module (nn.Module): The modules to be converted in FP16.\n\n Returns:\n nn.Module: The converted module, the normalization layers have been\n converted to FP32.\n '
if isinst... |
def patch_forward_method(func, src_type, dst_type, convert_output=True):
'Patch the forward method of a module.\n\n Args:\n func (callable): The original forward method.\n src_type (torch.dtype): Type of input arguments to be converted from.\n dst_type (torch.dtype): Type of input argument... |
class LossScaler():
'Class that manages loss scaling in mixed precision training which\n supports both dynamic or static mode.\n\n The implementation refers to\n https://github.com/NVIDIA/apex/blob/master/apex/fp16_utils/loss_scaler.py.\n Indirectly, by supplying ``mode=\'dynamic\'`` for dynamic loss ... |
@HOOKS.register_module()
class CheckpointHook(Hook):
'Save checkpoints periodically.\n\n Args:\n interval (int): The saving period. If ``by_epoch=True``, interval\n indicates epochs, otherwise it indicates iterations.\n Default: -1, which means "never".\n by_epoch (bool): Sa... |
@HOOKS.register_module()
class ClosureHook(Hook):
def __init__(self, fn_name, fn):
assert hasattr(self, fn_name)
assert callable(fn)
setattr(self, fn_name, fn)
|
@HOOKS.register_module()
class EMAHook(Hook):
'Exponential Moving Average Hook.\n\n Use Exponential Moving Average on all parameters of model in training\n process. All parameters have a ema backup, which update by the formula\n as below. EMAHook takes priority over EvalHook and CheckpointSaverHook.\n\n ... |
class EvalHook(Hook):
"Non-Distributed evaluation hook.\n\n This hook will regularly perform evaluation in a given interval when\n performing in non-distributed environment.\n\n Args:\n dataloader (DataLoader): A PyTorch dataloader, whose dataset has\n implemented ``evaluate`` function.... |
class DistEvalHook(EvalHook):
"Distributed evaluation hook.\n\n This hook will regularly perform evaluation in a given interval when\n performing in distributed environment.\n\n Args:\n dataloader (DataLoader): A PyTorch dataloader, whose dataset has\n implemented ``evaluate`` function.... |
class Hook():
stages = ('before_run', 'before_train_epoch', 'before_train_iter', 'after_train_iter', 'after_train_epoch', 'before_val_epoch', 'before_val_iter', 'after_val_iter', 'after_val_epoch', 'after_run')
def before_run(self, runner):
pass
def after_run(self, runner):
pass
def... |
@HOOKS.register_module()
class IterTimerHook(Hook):
def before_epoch(self, runner):
self.t = time.time()
def before_iter(self, runner):
runner.log_buffer.update({'data_time': (time.time() - self.t)})
def after_iter(self, runner):
runner.log_buffer.update({'time': (time.time() - ... |
class LoggerHook(Hook):
'Base class for logger hooks.\n\n Args:\n interval (int): Logging interval (every k iterations). Default 10.\n ignore_last (bool): Ignore the log of last iterations in each epoch\n if less than `interval`. Default True.\n reset_flag (bool): Whether to cle... |
@HOOKS.register_module()
class DvcliveLoggerHook(LoggerHook):
'Class to log metrics with dvclive.\n\n It requires `dvclive`_ to be installed.\n\n Args:\n model_file (str): Default None. If not None, after each epoch the\n model will be saved to {model_file}.\n interval (int): Loggin... |
@HOOKS.register_module()
class MlflowLoggerHook(LoggerHook):
'Class to log metrics and (optionally) a trained model to MLflow.\n\n It requires `MLflow`_ to be installed.\n\n Args:\n exp_name (str, optional): Name of the experiment to be used.\n Default None. If not None, set the active exp... |
@HOOKS.register_module()
class NeptuneLoggerHook(LoggerHook):
"Class to log metrics to NeptuneAI.\n\n It requires `Neptune`_ to be installed.\n\n Args:\n init_kwargs (dict): a dict contains the initialization keys as below:\n\n - project (str): Name of a project in a form of\n ... |
@HOOKS.register_module()
class PaviLoggerHook(LoggerHook):
"Class to visual model, log metrics (for internal use).\n\n Args:\n init_kwargs (dict): A dict contains the initialization keys.\n add_graph (bool): Whether to visual model. Default: False.\n add_last_ckpt (bool): Whether to save c... |
@HOOKS.register_module()
class SegmindLoggerHook(LoggerHook):
'Class to log metrics to Segmind.\n\n It requires `Segmind`_ to be installed.\n\n Args:\n interval (int): Logging interval (every k iterations). Default: 10.\n ignore_last (bool): Ignore the log of last iterations in each epoch\n ... |
@HOOKS.register_module()
class TensorboardLoggerHook(LoggerHook):
'Class to log metrics to Tensorboard.\n\n Args:\n log_dir (string): Save directory location. Default: None. If default\n values are used, directory location is ``runner.work_dir``/tf_logs.\n interval (int): Logging inter... |
@HOOKS.register_module()
class TextLoggerHook(LoggerHook):
"Logger hook in text.\n\n In this logger hook, the information will be printed on terminal and\n saved in json file.\n\n Args:\n by_epoch (bool, optional): Whether EpochBasedRunner is used.\n Default: True.\n interval (in... |
@HOOKS.register_module()
class WandbLoggerHook(LoggerHook):
"Class to log metrics with wandb.\n\n It requires `wandb`_ to be installed.\n\n\n Args:\n init_kwargs (dict): A dict contains the initialization keys. Check\n https://docs.wandb.ai/ref/python/init for more init arguments.\n ... |
class LrUpdaterHook(Hook):
"LR Scheduler in MMCV.\n\n Args:\n by_epoch (bool): LR changes epoch by epoch\n warmup (string): Type of warmup used. It can be None(use no warmup),\n 'constant', 'linear' or 'exp'\n warmup_iters (int): The number of iterations or epochs that warmup\n ... |
@HOOKS.register_module()
class FixedLrUpdaterHook(LrUpdaterHook):
def __init__(self, **kwargs):
super(FixedLrUpdaterHook, self).__init__(**kwargs)
def get_lr(self, runner, base_lr):
return base_lr
|
@HOOKS.register_module()
class StepLrUpdaterHook(LrUpdaterHook):
"Step LR scheduler with min_lr clipping.\n\n Args:\n step (int | list[int]): Step to decay the LR. If an int value is given,\n regard it as the decay interval. If a list is given, decay LR at\n these steps.\n g... |
@HOOKS.register_module()
class ExpLrUpdaterHook(LrUpdaterHook):
def __init__(self, gamma, **kwargs):
self.gamma = gamma
super(ExpLrUpdaterHook, self).__init__(**kwargs)
def get_lr(self, runner, base_lr):
progress = (runner.epoch if self.by_epoch else runner.iter)
return (base... |
@HOOKS.register_module()
class PolyLrUpdaterHook(LrUpdaterHook):
def __init__(self, power=1.0, min_lr=0.0, **kwargs):
self.power = power
self.min_lr = min_lr
super(PolyLrUpdaterHook, self).__init__(**kwargs)
def get_lr(self, runner, base_lr):
if self.by_epoch:
pro... |
@HOOKS.register_module()
class InvLrUpdaterHook(LrUpdaterHook):
def __init__(self, gamma, power=1.0, **kwargs):
self.gamma = gamma
self.power = power
super(InvLrUpdaterHook, self).__init__(**kwargs)
def get_lr(self, runner, base_lr):
progress = (runner.epoch if self.by_epoch ... |
@HOOKS.register_module()
class CosineAnnealingLrUpdaterHook(LrUpdaterHook):
def __init__(self, min_lr=None, min_lr_ratio=None, **kwargs):
assert ((min_lr is None) ^ (min_lr_ratio is None))
self.min_lr = min_lr
self.min_lr_ratio = min_lr_ratio
super(CosineAnnealingLrUpdaterHook, se... |
@HOOKS.register_module()
class FlatCosineAnnealingLrUpdaterHook(LrUpdaterHook):
'Flat + Cosine lr schedule.\n\n Modified from https://github.com/fastai/fastai/blob/master/fastai/callback/schedule.py#L128 # noqa: E501\n\n Args:\n start_percent (float): When to start annealing the learning rate\n ... |
@HOOKS.register_module()
class CosineRestartLrUpdaterHook(LrUpdaterHook):
'Cosine annealing with restarts learning rate scheme.\n\n Args:\n periods (list[int]): Periods for each cosine anneling cycle.\n restart_weights (list[float], optional): Restart weights at each\n restart iteratio... |
def get_position_from_periods(iteration, cumulative_periods):
'Get the position from a period list.\n\n It will return the index of the right-closest number in the period list.\n For example, the cumulative_periods = [100, 200, 300, 400],\n if iteration == 50, return 0;\n if iteration == 210, return 2... |
@HOOKS.register_module()
class CyclicLrUpdaterHook(LrUpdaterHook):
"Cyclic LR Scheduler.\n\n Implement the cyclical learning rate policy (CLR) described in\n https://arxiv.org/pdf/1506.01186.pdf\n\n Different from the original paper, we use cosine annealing rather than\n triangular policy inside a cyc... |
@HOOKS.register_module()
class OneCycleLrUpdaterHook(LrUpdaterHook):
"One Cycle LR Scheduler.\n\n The 1cycle learning rate policy changes the learning rate after every\n batch. The one cycle learning rate policy is described in\n https://arxiv.org/pdf/1708.07120.pdf\n\n Args:\n max_lr (float or... |
def annealing_cos(start, end, factor, weight=1):
'Calculate annealing cos learning rate.\n\n Cosine anneal from `weight * start + (1 - weight) * end` to `end` as\n percentage goes from 0.0 to 1.0.\n\n Args:\n start (float): The starting learning rate of the cosine annealing.\n end (float): ... |
def annealing_linear(start, end, factor):
'Calculate annealing linear learning rate.\n\n Linear anneal from `start` to `end` as percentage goes from 0.0 to 1.0.\n\n Args:\n start (float): The starting learning rate of the linear annealing.\n end (float): The ending learing rate of the linear a... |
def format_param(name, optim, param):
if isinstance(param, numbers.Number):
return ([param] * len(optim.param_groups))
elif isinstance(param, (list, tuple)):
if (len(param) != len(optim.param_groups)):
raise ValueError(f'expected {len(optim.param_groups)} values for {name}, got {le... |
@HOOKS.register_module()
class EmptyCacheHook(Hook):
def __init__(self, before_epoch=False, after_epoch=True, after_iter=False):
self._before_epoch = before_epoch
self._after_epoch = after_epoch
self._after_iter = after_iter
def after_iter(self, runner):
if self._after_iter:
... |
class MomentumUpdaterHook(Hook):
def __init__(self, by_epoch=True, warmup=None, warmup_iters=0, warmup_ratio=0.9):
if (warmup is not None):
if (warmup not in ['constant', 'linear', 'exp']):
raise ValueError(f'"{warmup}" is not a supported type for warming up, valid types are "... |
@HOOKS.register_module()
class StepMomentumUpdaterHook(MomentumUpdaterHook):
"Step momentum scheduler with min value clipping.\n\n Args:\n step (int | list[int]): Step to decay the momentum. If an int value is\n given, regard it as the decay interval. If a list is given, decay\n mo... |
@HOOKS.register_module()
class CosineAnnealingMomentumUpdaterHook(MomentumUpdaterHook):
def __init__(self, min_momentum=None, min_momentum_ratio=None, **kwargs):
assert ((min_momentum is None) ^ (min_momentum_ratio is None))
self.min_momentum = min_momentum
self.min_momentum_ratio = min_m... |
@HOOKS.register_module()
class CyclicMomentumUpdaterHook(MomentumUpdaterHook):
"Cyclic momentum Scheduler.\n\n Implement the cyclical momentum scheduler policy described in\n https://arxiv.org/pdf/1708.07120.pdf\n\n This momentum scheduler usually used together with the CyclicLRUpdater\n to improve th... |
@HOOKS.register_module()
class OneCycleMomentumUpdaterHook(MomentumUpdaterHook):
"OneCycle momentum Scheduler.\n\n This momentum scheduler usually used together with the OneCycleLrUpdater\n to improve the performance.\n\n Args:\n base_momentum (float or list): Lower momentum boundaries in the cycl... |
@HOOKS.register_module()
class OptimizerHook(Hook):
'A hook contains custom operations for the optimizer.\n\n Args:\n grad_clip (dict, optional): A config dict to control the clip_grad.\n Default: None.\n detect_anomalous_params (bool): This option is only used for\n debuggi... |
@HOOKS.register_module()
class GradientCumulativeOptimizerHook(OptimizerHook):
'Optimizer Hook implements multi-iters gradient cumulating.\n\n Args:\n cumulative_iters (int, optional): Num of gradient cumulative iters.\n The optimizer will step every `cumulative_iters` iters.\n Def... |
@HOOKS.register_module()
class ProfilerHook(Hook):
"Profiler to analyze performance during training.\n\n PyTorch Profiler is a tool that allows the collection of the performance\n metrics during the training. More details on Profiler can be found at\n https://pytorch.org/docs/1.8.1/profiler.html#torch.pr... |
@HOOKS.register_module()
class DistSamplerSeedHook(Hook):
'Data-loading sampler for distributed training.\n\n When distributed training, it is only useful in conjunction with\n :obj:`EpochBasedRunner`, while :obj:`IterBasedRunner` achieves the same\n purpose with :obj:`IterLoader`.\n '
def before... |
@HOOKS.register_module()
class SyncBuffersHook(Hook):
'Synchronize model buffers such as running_mean and running_var in BN at\n the end of each epoch.\n\n Args:\n distributed (bool): Whether distributed training is used. It is\n effective only for distributed training. Defaults to True.\n ... |
class IterLoader():
def __init__(self, dataloader):
self._dataloader = dataloader
self.iter_loader = iter(self._dataloader)
self._epoch = 0
@property
def epoch(self):
return self._epoch
def __next__(self):
try:
data = next(self.iter_loader)
... |
@RUNNERS.register_module()
class IterBasedRunner(BaseRunner):
'Iteration-based Runner.\n\n This runner train models iteration by iteration.\n '
def train(self, data_loader, **kwargs):
self.model.train()
self.mode = 'train'
self.data_loader = data_loader
self._epoch = dat... |
class LogBuffer():
def __init__(self):
self.val_history = OrderedDict()
self.n_history = OrderedDict()
self.output = OrderedDict()
self.ready = False
def clear(self):
self.val_history.clear()
self.n_history.clear()
self.clear_output()
def clear_ou... |
def register_torch_optimizers():
torch_optimizers = []
for module_name in dir(torch.optim):
if module_name.startswith('__'):
continue
_optim = getattr(torch.optim, module_name)
if (inspect.isclass(_optim) and issubclass(_optim, torch.optim.Optimizer)):
OPTIMIZER... |
def build_optimizer_constructor(cfg):
return build_from_cfg(cfg, OPTIMIZER_BUILDERS)
|
def build_optimizer(model, cfg):
optimizer_cfg = copy.deepcopy(cfg)
constructor_type = optimizer_cfg.pop('constructor', 'DefaultOptimizerConstructor')
paramwise_cfg = optimizer_cfg.pop('paramwise_cfg', None)
optim_constructor = build_optimizer_constructor(dict(type=constructor_type, optimizer_cfg=opti... |
@OPTIMIZER_BUILDERS.register_module()
class DefaultOptimizerConstructor():
"Default constructor for optimizers.\n\n By default each parameter share the same optimizer settings, and we\n provide an argument ``paramwise_cfg`` to specify parameter-wise settings.\n It is a dict and may contain the following ... |
class Priority(Enum):
'Hook priority levels.\n\n +--------------+------------+\n | Level | Value |\n +==============+============+\n | HIGHEST | 0 |\n +--------------+------------+\n | VERY_HIGH | 10 |\n +--------------+------------+\n | HIGH | ... |
def get_priority(priority):
'Get priority value.\n\n Args:\n priority (int or str or :obj:`Priority`): Priority.\n\n Returns:\n int: The priority value.\n '
if isinstance(priority, int):
if ((priority < 0) or (priority > 100)):
raise ValueError('priority must be betw... |
def get_host_info():
'Get hostname and username.\n\n Return empty string if exception raised, e.g. ``getpass.getuser()`` will\n lead to error in docker container\n '
host = ''
try:
host = f'{getuser()}@{gethostname()}'
except Exception as e:
warnings.warn(f'Host or user not fo... |
def get_time_str():
return time.strftime('%Y%m%d_%H%M%S', time.localtime())
|
def obj_from_dict(info, parent=None, default_args=None):
'Initialize an object from dict.\n\n The dict must contain the key "type", which indicates the object type, it\n can be either a string or type, such as "list" or ``list``. Remaining\n fields are treated as the arguments for constructing the object... |
def set_random_seed(seed, deterministic=False, use_rank_shift=False):
'Set random seed.\n\n Args:\n seed (int): Seed to be used.\n deterministic (bool): Whether to set the deterministic option for\n CUDNN backend, i.e., set `torch.backends.cudnn.deterministic`\n to True and ... |
def is_tensorrt_available():
try:
import tensorrt
del tensorrt
return True
except ModuleNotFoundError:
return False
|
def get_tensorrt_op_path():
'Get TensorRT plugins library path.'
(bright_style, reset_style) = ('\x1b[1m', '\x1b[0m')
(red_text, blue_text) = ('\x1b[31m', '\x1b[34m')
white_background = '\x1b[107m'
msg = ((white_background + bright_style) + red_text)
msg += 'DeprecationWarning: This function w... |
def is_tensorrt_plugin_loaded():
'Check if TensorRT plugins library is loaded or not.\n\n Returns:\n bool: plugin_is_loaded flag\n '
(bright_style, reset_style) = ('\x1b[1m', '\x1b[0m')
(red_text, blue_text) = ('\x1b[31m', '\x1b[34m')
white_background = '\x1b[107m'
msg = ((white_backg... |
def load_tensorrt_plugin():
'load TensorRT plugins library.'
(bright_style, reset_style) = ('\x1b[1m', '\x1b[0m')
(red_text, blue_text) = ('\x1b[31m', '\x1b[34m')
white_background = '\x1b[107m'
msg = ((white_background + bright_style) + red_text)
msg += 'DeprecationWarning: This function will ... |
def preprocess_onnx(onnx_model):
'Modify onnx model to match with TensorRT plugins in mmcv.\n\n There are some conflict between onnx node definition and TensorRT limit.\n This function perform preprocess on the onnx model to solve the conflicts.\n For example, onnx `attribute` is loaded in TensorRT on ho... |
def onnx2trt(onnx_model, opt_shape_dict, log_level=trt.Logger.ERROR, fp16_mode=False, max_workspace_size=0, device_id=0):
'Convert onnx model to tensorrt engine.\n\n Arguments:\n onnx_model (str or onnx.ModelProto): the onnx model to convert from\n opt_shape_dict (dict): the min/opt/max shape of ... |
def save_trt_engine(engine, path):
'Serialize TensorRT engine to disk.\n\n Arguments:\n engine (tensorrt.ICudaEngine): TensorRT engine to serialize\n path (str): disk path to write the engine\n '
(bright_style, reset_style) = ('\x1b[1m', '\x1b[0m')
(red_text, blue_text) = ('\x1b[31m', ... |
def load_trt_engine(path):
'Deserialize TensorRT engine from disk.\n\n Arguments:\n path (str): disk path to read the engine\n\n Returns:\n tensorrt.ICudaEngine: the TensorRT engine loaded from disk\n '
(bright_style, reset_style) = ('\x1b[1m', '\x1b[0m')
(red_text, blue_text) = ('\... |
def torch_dtype_from_trt(dtype):
'Convert pytorch dtype to TensorRT dtype.'
if (dtype == trt.bool):
return torch.bool
elif (dtype == trt.int8):
return torch.int8
elif (dtype == trt.int32):
return torch.int32
elif (dtype == trt.float16):
return torch.float16
elif... |
def torch_device_from_trt(device):
'Convert pytorch device to TensorRT device.'
if (device == trt.TensorLocation.DEVICE):
return torch.device('cuda')
elif (device == trt.TensorLocation.HOST):
return torch.device('cpu')
else:
return TypeError(('%s is not supported by torch' % de... |
class TRTWrapper(torch.nn.Module):
'TensorRT engine Wrapper.\n\n Arguments:\n engine (tensorrt.ICudaEngine): TensorRT engine to wrap\n input_names (list[str]): names of each inputs\n output_names (list[str]): names of each outputs\n\n Note:\n If the engine is converted from onnx ... |
class TRTWraper(TRTWrapper):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
warnings.warn('TRTWraper will be deprecated in future. Please use TRTWrapper instead', DeprecationWarning)
|
class ConfigDict(Dict):
def __missing__(self, name):
raise KeyError(name)
def __getattr__(self, name):
try:
value = super(ConfigDict, self).__getattr__(name)
except KeyError:
ex = AttributeError(f"'{self.__class__.__name__}' object has no attribute '{name}'")
... |
def add_args(parser, cfg, prefix=''):
for (k, v) in cfg.items():
if isinstance(v, str):
parser.add_argument((('--' + prefix) + k))
elif isinstance(v, int):
parser.add_argument((('--' + prefix) + k), type=int)
elif isinstance(v, float):
parser.add_argumen... |
class Config():
'A facility for config and config files.\n\n It supports common file formats as configs: python/json/yaml. The interface\n is the same as a dict object and also allows access config values as\n attributes.\n\n Example:\n >>> cfg = Config(dict(a=1, b=dict(b1=[0, 1])))\n >>... |
class DictAction(Action):
"\n argparse action to split an argument into KEY=VALUE form\n on the first = and append to a dictionary. List options can\n be passed as comma separated values, i.e 'KEY=V1,V2,V3', or with explicit\n brackets, i.e. 'KEY=[V1,V2,V3]'. It also support nested brackets to build\n... |
def collect_env():
'Collect the information of the running environments.\n\n Returns:\n dict: The environment information. The following fields are contained.\n\n - sys.platform: The variable of ``sys.platform``.\n - Python: Python version.\n - CUDA available: Bool, indi... |
def check_ops_exist():
ext_loader = pkgutil.find_loader('mmcv._ext')
return (ext_loader is not None)
|
def get_logger(name, log_file=None, log_level=logging.INFO, file_mode='w'):
'Initialize and get a logger by name.\n\n If the logger has not been initialized, this method will initialize the\n logger by adding one or two handlers, otherwise the initialized logger will\n be directly returned. During initia... |
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.\n Some special loggers are:\n - "silent": no message will be printed.\n - oth... |
def _ntuple(n):
def parse(x):
if isinstance(x, collections.abc.Iterable):
return x
return tuple(repeat(x, n))
return parse
|
def is_str(x):
'Whether the input is an string instance.\n\n Note: This method is deprecated since python 2 is no longer supported.\n '
return isinstance(x, str)
|
def import_modules_from_strings(imports, allow_failed_imports=False):
"Import modules from the given list of strings.\n\n Args:\n imports (list | str | None): The given module names to be imported.\n allow_failed_imports (bool): If True, the failed imports will return\n None. Otherwise... |
def iter_cast(inputs, dst_type, return_type=None):
'Cast elements of an iterable object into some type.\n\n Args:\n inputs (Iterable): The input object.\n dst_type (type): Destination type.\n return_type (type, optional): If specified, the output object will be\n converted to th... |
def list_cast(inputs, dst_type):
'Cast elements of an iterable object into a list of some type.\n\n A partial method of :func:`iter_cast`.\n '
return iter_cast(inputs, dst_type, return_type=list)
|
def tuple_cast(inputs, dst_type):
'Cast elements of an iterable object into a tuple of some type.\n\n A partial method of :func:`iter_cast`.\n '
return iter_cast(inputs, dst_type, return_type=tuple)
|
def is_seq_of(seq, expected_type, seq_type=None):
'Check whether it is a sequence of some type.\n\n Args:\n seq (Sequence): The sequence to be checked.\n expected_type (type): Expected type of sequence items.\n seq_type (type, optional): Expected sequence type.\n\n Returns:\n boo... |
def is_list_of(seq, expected_type):
'Check whether it is a list of some type.\n\n A partial method of :func:`is_seq_of`.\n '
return is_seq_of(seq, expected_type, seq_type=list)
|
def is_tuple_of(seq, expected_type):
'Check whether it is a tuple of some type.\n\n A partial method of :func:`is_seq_of`.\n '
return is_seq_of(seq, expected_type, seq_type=tuple)
|
def slice_list(in_list, lens):
'Slice a list into several sub lists by a list of given length.\n\n Args:\n in_list (list): The list to be sliced.\n lens(int or list): The expected length of each out list.\n\n Returns:\n list: A list of sliced list.\n '
if isinstance(lens, int):
... |
def concat_list(in_list):
'Concatenate a list of list into a single list.\n\n Args:\n in_list (list): The list of list to be merged.\n\n Returns:\n list: The concatenated flat list.\n '
return list(itertools.chain(*in_list))
|
def check_prerequisites(prerequisites, checker, msg_tmpl='Prerequisites "{}" are required in method "{}" but not found, please install them first.'):
'A decorator factory to check if prerequisites are satisfied.\n\n Args:\n prerequisites (str of list[str]): Prerequisites to be checked.\n checker ... |
def _check_py_package(package):
try:
import_module(package)
except ImportError:
return False
else:
return True
|
def _check_executable(cmd):
if (subprocess.call(f'which {cmd}', shell=True) != 0):
return False
else:
return True
|
def requires_package(prerequisites):
"A decorator to check if some python packages are installed.\n\n Example:\n >>> @requires_package('numpy')\n >>> func(arg1, args):\n >>> return numpy.zeros(1)\n array([0.])\n >>> @requires_package(['numpy', 'non_package'])\n >>>... |
def requires_executable(prerequisites):
"A decorator to check if some executable files are installed.\n\n Example:\n >>> @requires_executable('ffmpeg')\n >>> func(arg1, args):\n >>> print(1)\n 1\n "
return check_prerequisites(prerequisites, checker=_check_executable)
|
def deprecated_api_warning(name_dict, cls_name=None):
'A decorator to check if some arguments are deprecate and try to replace\n deprecate src_arg_name to dst_arg_name.\n\n Args:\n name_dict(dict):\n key (str): Deprecate argument names.\n val (str): Expected argument names.\n\n ... |
def is_method_overridden(method, base_class, derived_class):
'Check if a method of base class is overridden in derived class.\n\n Args:\n method (str): the method name to check.\n base_class (type): the class of the base class.\n derived_class (type | Any): the class or instance of the der... |
def has_method(obj: object, method: str) -> bool:
'Check whether the object has a method.\n\n Args:\n method (str): The method name to check.\n obj (object): The object to check.\n\n Returns:\n bool: True if the object has the method else False.\n '
return (hasattr(obj, method) a... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.