instruction
stringclasses
100 values
code
stringlengths
78
193k
response
stringlengths
259
170k
file
stringlengths
59
203
Generate docstrings for exported functions
# Copyright (c) OpenMMLab. All rights reserved. import numpy as np def quantize(arr, min_val, max_val, levels, dtype=np.int64): if not (isinstance(levels, int) and levels > 1): raise ValueError( f'levels must be a positive integer, but got {levels}') if min_val >= max_val: raise Va...
--- +++ @@ -3,6 +3,18 @@ def quantize(arr, min_val, max_val, levels, dtype=np.int64): + """Quantize an array of (-inf, inf) to [0, levels-1]. + + Args: + arr (ndarray): Input array. + min_val (scalar): Minimum value to be clipped. + max_val (scalar): Maximum value to be clipped. + ...
https://raw.githubusercontent.com/Mikubill/sd-webui-controlnet/HEAD/annotator/mmpkg/mmcv/arraymisc/quantization.py
Write docstrings for algorithm functions
# Copyright (c) OpenMMLab. All rights reserved. import torch import torch.nn as nn import torch.nn.functional as F from annotator.mmpkg.mmcv.utils import TORCH_VERSION, build_from_cfg, digit_version from .registry import ACTIVATION_LAYERS for module in [ nn.ReLU, nn.LeakyReLU, nn.PReLU, nn.RReLU, nn.ReLU6, nn...
--- +++ @@ -16,6 +16,17 @@ @ACTIVATION_LAYERS.register_module(name='Clip') @ACTIVATION_LAYERS.register_module() class Clamp(nn.Module): + """Clamp activation layer. + + This activation function is to clamp the feature map value within + :math:`[min, max]`. More details can be found in ``torch.clamp()``. + + ...
https://raw.githubusercontent.com/Mikubill/sd-webui-controlnet/HEAD/annotator/mmpkg/mmcv/cnn/bricks/activation.py
Fully document this Python code with docstrings
import sys import re import numpy as np import cv2 import torch def read_pfm(path): with open(path, "rb") as file: color = None width = None height = None scale = None endian = None header = file.readline().rstrip() if header.decode("ascii") == "PF": ...
--- +++ @@ -1,3 +1,4 @@+"""Utils for monoDepth.""" import sys import re import numpy as np @@ -6,6 +7,14 @@ def read_pfm(path): + """Read pfm file. + + Args: + path (str): path to file + + Returns: + tuple: (data, scale) + """ with open(path, "rb") as file: color = None ...
https://raw.githubusercontent.com/Mikubill/sd-webui-controlnet/HEAD/annotator/midas/utils.py
Replace inline comments with docstrings
# Copyright (c) OpenMMLab. All rights reserved. import copy import warnings import torch import torch.nn as nn from annotator.mmpkg.mmcv import ConfigDict, deprecated_api_warning from annotator.mmpkg.mmcv.cnn import Linear, build_activation_layer, build_norm_layer from annotator.mmpkg.mmcv.runner.base_module import B...
--- +++ @@ -31,27 +31,52 @@ def build_positional_encoding(cfg, default_args=None): + """Builder for Position Encoding.""" return build_from_cfg(cfg, POSITIONAL_ENCODING, default_args) def build_attention(cfg, default_args=None): + """Builder for attention.""" return build_from_cfg(cfg, ATTENTIO...
https://raw.githubusercontent.com/Mikubill/sd-webui-controlnet/HEAD/annotator/mmpkg/mmcv/cnn/bricks/transformer.py
Add docstrings following best practices
import torch.nn as nn import torch.nn as NN __all__ = ['ResNet', 'resnet18', 'resnet34', 'resnet50', 'resnet101', 'resnet152'] model_urls = { 'resnet18': 'https://download.pytorch.org/models/resnet18-5c106cde.pth', 'resnet34': 'https://download.pytorch.org/models/resnet34-333f7ec4.pth', 'resne...
--- +++ @@ -15,6 +15,7 @@ def conv3x3(in_planes, out_planes, stride=1): + """3x3 convolution with padding""" return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=False) @@ -152,27 +153,47 @@ def resnet18(pretrained=True, **kwargs): + """Constru...
https://raw.githubusercontent.com/Mikubill/sd-webui-controlnet/HEAD/annotator/leres/leres/Resnet.py
Add docstrings to improve code quality
# Copyright (c) OpenMMLab. All rights reserved. import torch.nn as nn import torch.nn.functional as F from ..utils import xavier_init from .registry import UPSAMPLE_LAYERS UPSAMPLE_LAYERS.register_module('nearest', module=nn.Upsample) UPSAMPLE_LAYERS.register_module('bilinear', module=nn.Upsample) @UPSAMPLE_LAYERS....
--- +++ @@ -11,6 +11,18 @@ @UPSAMPLE_LAYERS.register_module(name='pixel_shuffle') class PixelShufflePack(nn.Module): + """Pixel Shuffle upsample layer. + + This module packs `F.pixel_shuffle()` and a nn.Conv2d module together to + achieve a simple upsampling with pixel shuffle. + + Args: + in_chan...
https://raw.githubusercontent.com/Mikubill/sd-webui-controlnet/HEAD/annotator/mmpkg/mmcv/cnn/bricks/upsample.py
Add docstrings to meet PEP guidelines
''' M-LSD Copyright 2021-present NAVER Corp. Apache License v2.0 ''' import os import numpy as np import cv2 import torch from torch.nn import functional as F from modules import devices def deccode_output_score_and_ptss(tpMap, topk_n = 200, ksize = 5): b, c, h, w = tpMap.shape assert b==1, 'only support...
--- +++ @@ -1,3 +1,7 @@+''' +modified by lihaoweicv +pytorch version +''' ''' M-LSD @@ -14,6 +18,11 @@ def deccode_output_score_and_ptss(tpMap, topk_n = 200, ksize = 5): + ''' + tpMap: + center: tpMap[1, 0, :, :] + displacement: tpMap[1, 1:5, :, :] + ''' b, c, h, w = tpMap.shape assert...
https://raw.githubusercontent.com/Mikubill/sd-webui-controlnet/HEAD/annotator/mlsd/utils.py
Add docstrings following best practices
# Copyright (c) OpenMMLab. All rights reserved. import logging import torch.nn as nn import torch.utils.checkpoint as cp from .utils import constant_init, kaiming_init def conv3x3(in_planes, out_planes, stride=1, dilation=1): return nn.Conv2d( in_planes, out_planes, kernel_size=3, ...
--- +++ @@ -8,6 +8,7 @@ def conv3x3(in_planes, out_planes, stride=1, dilation=1): + """3x3 convolution with padding.""" return nn.Conv2d( in_planes, out_planes, @@ -71,6 +72,11 @@ downsample=None, style='pytorch', with_cp=False): + ...
https://raw.githubusercontent.com/Mikubill/sd-webui-controlnet/HEAD/annotator/mmpkg/mmcv/cnn/resnet.py
Generate consistent docstrings
# Copyright (c) OpenMMLab. All rights reserved. import inspect import os import os.path as osp import re import tempfile import warnings from abc import ABCMeta, abstractmethod from contextlib import contextmanager from pathlib import Path from typing import Iterable, Iterator, Optional, Tuple, Union from urllib.reques...
--- +++ @@ -17,6 +17,12 @@ class BaseStorageBackend(metaclass=ABCMeta): + """Abstract class of storage backends. + + All backends need to implement two apis: ``get()`` and ``get_text()``. + ``get()`` reads the file as a byte stream and ``get_text()`` reads the file + as texts. + """ # a flag t...
https://raw.githubusercontent.com/Mikubill/sd-webui-controlnet/HEAD/annotator/mmpkg/mmcv/fileio/file_client.py
Replace inline comments with docstrings
import torch import torch.nn as nn from .base_model import BaseModel from .blocks import FeatureFusionBlock, FeatureFusionBlock_custom, Interpolate, _make_encoder class MidasNet_small(BaseModel): def __init__(self, path=None, features=64, backbone="efficientnet_lite3", non_negative=True, exportable=True, channe...
--- +++ @@ -1,3 +1,7 @@+"""MidashNet: Network for monocular depth estimation trained by mixing several datasets. +This file contains code that is adapted from +https://github.com/thomasjpfan/pytorch_refinenet/blob/master/pytorch_refinenet/refinenet/refinenet_4cascade.py +""" import torch import torch.nn as nn @@ -6...
https://raw.githubusercontent.com/Mikubill/sd-webui-controlnet/HEAD/annotator/midas/midas/midas_net_custom.py
Write proper docstrings for these functions
# Copyright (c) OpenMMLab. All rights reserved. from io import StringIO from .file_client import FileClient def list_from_file(filename, prefix='', offset=0, max_num=0, encoding='utf-8', file_client_args=None): cnt = ...
--- +++ @@ -11,6 +11,33 @@ max_num=0, encoding='utf-8', file_client_args=None): + """Load a text file and parse the content as a list of strings. + + Note: + In v1.3.16 and later, ``list_from_file`` supports loading a text file + which can b...
https://raw.githubusercontent.com/Mikubill/sd-webui-controlnet/HEAD/annotator/mmpkg/mmcv/fileio/parse.py
Add docstrings for utility scripts
# Copyright (c) OpenMMLab. All rights reserved. import io import os.path as osp from pathlib import Path import cv2 import numpy as np from cv2 import (IMREAD_COLOR, IMREAD_GRAYSCALE, IMREAD_IGNORE_ORIENTATION, IMREAD_UNCHANGED) from annotator.mmpkg.mmcv.utils import check_file_exist, is_str, mkdir_o...
--- +++ @@ -41,6 +41,14 @@ def use_backend(backend): + """Select a backend for image decoding. + + Args: + backend (str): The image decoding backend type. Options are `cv2`, + `pillow`, `turbojpeg` (see https://github.com/lilohuang/PyTurboJPEG) + and `tifffile`. `turbojpeg` is faster but ...
https://raw.githubusercontent.com/Mikubill/sd-webui-controlnet/HEAD/annotator/mmpkg/mmcv/image/io.py
Document classes and their methods
import torch import torch.nn as nn from .vit import ( _make_pretrained_vitb_rn50_384, _make_pretrained_vitl16_384, _make_pretrained_vitb16_384, forward_vit, ) def _make_encoder(backbone, features, use_pretrained, groups=1, expand=False, exportable=True, hooks=None, use_vit_only=False, use_readout="ign...
--- +++ @@ -118,8 +118,16 @@ class Interpolate(nn.Module): + """Interpolation module. + """ def __init__(self, scale_factor, mode, align_corners=False): + """Init. + + Args: + scale_factor (float): scaling + mode (str): interpolation mode + """ super(...
https://raw.githubusercontent.com/Mikubill/sd-webui-controlnet/HEAD/annotator/midas/midas/blocks.py
Expand my code with proper documentation strings
# Copyright (c) OpenMMLab. All rights reserved. import cv2 import numpy as np def imconvert(img, src, dst): code = getattr(cv2, f'COLOR_{src.upper()}2{dst.upper()}') out_img = cv2.cvtColor(img, code) return out_img def bgr2gray(img, keepdim=False): out_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) ...
--- +++ @@ -4,12 +4,32 @@ def imconvert(img, src, dst): + """Convert an image from the src colorspace to dst colorspace. + + Args: + img (ndarray): The input image. + src (str): The source colorspace, e.g., 'rgb', 'hsv'. + dst (str): The destination colorspace, e.g., 'rgb', 'hsv'. + + ...
https://raw.githubusercontent.com/Mikubill/sd-webui-controlnet/HEAD/annotator/mmpkg/mmcv/image/colorspace.py
Fully document this Python code with docstrings
import numpy as np import cv2 import math def apply_min_size(sample, size, image_interpolation_method=cv2.INTER_AREA): shape = list(sample["disparity"].shape) if shape[0] >= size[0] and shape[1] >= size[1]: return sample scale = [0, 0] scale[0] = size[0] / shape[0] scale[1] = size[1] / s...
--- +++ @@ -4,6 +4,15 @@ def apply_min_size(sample, size, image_interpolation_method=cv2.INTER_AREA): + """Rezise the sample to ensure the given size. Keeps aspect ratio. + + Args: + sample (dict): sample + size (tuple): image size + + Returns: + tuple: new size + """ shape = l...
https://raw.githubusercontent.com/Mikubill/sd-webui-controlnet/HEAD/annotator/midas/midas/transforms.py
Document this code for team use
# Copyright (c) OpenMMLab. All rights reserved. import cv2 import numpy as np from ..utils import is_tuple_of from .colorspace import bgr2gray, gray2bgr def imnormalize(img, mean, std, to_rgb=True): img = img.copy().astype(np.float32) return imnormalize_(img, mean, std, to_rgb) def imnormalize_(img, mean, ...
--- +++ @@ -7,11 +7,33 @@ def imnormalize(img, mean, std, to_rgb=True): + """Normalize an image with mean and std. + + Args: + img (ndarray): Image to be normalized. + mean (ndarray): The mean to be used for normalize. + std (ndarray): The std to be used for normalize. + to_rgb (bo...
https://raw.githubusercontent.com/Mikubill/sd-webui-controlnet/HEAD/annotator/mmpkg/mmcv/image/photometric.py
Add docstrings for better understanding
# Copyright (c) OpenMMLab. All rights reserved. import numbers import cv2 import numpy as np from ..utils import to_2tuple from .io import imread_backend try: from PIL import Image except ImportError: Image = None def _scale_size(size, scale): if isinstance(scale, (float, int)): scale = (scale,...
--- +++ @@ -14,6 +14,15 @@ def _scale_size(size, scale): + """Rescale a size by a ratio. + + Args: + size (tuple[int]): (w, h). + scale (float | tuple(float)): Scaling factor. + + Returns: + tuple[int]: scaled size. + """ if isinstance(scale, (float, int)): scale = (sc...
https://raw.githubusercontent.com/Mikubill/sd-webui-controlnet/HEAD/annotator/mmpkg/mmcv/image/geometric.py
Add detailed documentation for each class
import torch import torch.nn as nn from .base_model import BaseModel from .blocks import FeatureFusionBlock, Interpolate, _make_encoder class MidasNet(BaseModel): def __init__(self, path=None, features=256, non_negative=True): print("Loading weights: ", path) super(MidasNet, self).__init__() ...
--- +++ @@ -1,3 +1,7 @@+"""MidashNet: Network for monocular depth estimation trained by mixing several datasets. +This file contains code that is adapted from +https://github.com/thomasjpfan/pytorch_refinenet/blob/master/pytorch_refinenet/refinenet/refinenet_4cascade.py +""" import torch import torch.nn as nn @@ -6...
https://raw.githubusercontent.com/Mikubill/sd-webui-controlnet/HEAD/annotator/midas/midas/midas_net.py
Add docstrings with type hints explained
from torch.autograd import Function from ..utils import ext_loader ext_module = ext_loader.load_ext( '_ext', ['assign_score_withk_forward', 'assign_score_withk_backward']) class AssignScoreWithK(Function): @staticmethod def forward(ctx, scores, point_features, ...
--- +++ @@ -7,6 +7,23 @@ class AssignScoreWithK(Function): + r"""Perform weighted sum to generate output features according to scores. + Modified from `PAConv <https://github.com/CVMI-Lab/PAConv/tree/main/ + scene_seg/lib/paconv_lib/src/gpu>`_. + + This is a memory-efficient CUDA implementation of assig...
https://raw.githubusercontent.com/Mikubill/sd-webui-controlnet/HEAD/annotator/mmpkg/mmcv/ops/assign_score_withk.py
Fill in missing docstrings in my code
# Copyright (c) OpenMMLab. All rights reserved. import torch from torch.autograd import Function from ..utils import ext_loader ext_module = ext_loader.load_ext('_ext', ['ball_query_forward']) class BallQuery(Function): @staticmethod def forward(ctx, min_radius: float, max_radius: float, sample_num: int, ...
--- +++ @@ -8,10 +8,23 @@ class BallQuery(Function): + """Find nearby points in spherical space.""" @staticmethod def forward(ctx, min_radius: float, max_radius: float, sample_num: int, xyz: torch.Tensor, center_xyz: torch.Tensor) -> torch.Tensor: + """ + Args: + ...
https://raw.githubusercontent.com/Mikubill/sd-webui-controlnet/HEAD/annotator/mmpkg/mmcv/ops/ball_query.py
Turn comments into proper docstrings
# Copyright (c) OpenMMLab. All rights reserved. import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Function from torch.nn.modules.module import Module from ..cnn import UPSAMPLE_LAYERS, normal_init, xavier_init from ..utils import ext_loader ext_module = ext_loader.load_ext(...
--- +++ @@ -178,6 +178,18 @@ class CARAFE(Module): + """ CARAFE: Content-Aware ReAssembly of FEatures + + Please refer to https://arxiv.org/abs/1905.02188 for more details. + + Args: + kernel_size (int): reassemble kernel size + group_size (int): reassemble group size + scale_factor (i...
https://raw.githubusercontent.com/Mikubill/sd-webui-controlnet/HEAD/annotator/mmpkg/mmcv/ops/carafe.py
Add docstrings to improve code quality
# Copyright (c) OpenMMLab. All rights reserved. # modified from # https://github.com/Megvii-BaseDetection/cvpods/blob/master/cvpods/layers/border_align.py import torch import torch.nn as nn from torch.autograd import Function from torch.autograd.function import once_differentiable from ..utils import ext_loader ext_...
--- +++ @@ -63,15 +63,47 @@ class BorderAlign(nn.Module): + r"""Border align pooling layer. + + Applies border_align over the input feature based on predicted bboxes. + The details were described in the paper + `BorderDet: Border Feature for Dense Object Detection + <https://arxiv.org/abs/2007.11056>...
https://raw.githubusercontent.com/Mikubill/sd-webui-controlnet/HEAD/annotator/mmpkg/mmcv/ops/border_align.py
Document functions with detailed explanations
# Copyright (c) OpenMMLab. All rights reserved. from abc import ABCMeta import torch import torch.nn as nn from ..utils import constant_init, normal_init from .conv_module import ConvModule from .registry import PLUGIN_LAYERS class _NonLocalNd(nn.Module, metaclass=ABCMeta): def __init__(self, ...
--- +++ @@ -10,6 +10,27 @@ class _NonLocalNd(nn.Module, metaclass=ABCMeta): + """Basic Non-local module. + + This module is proposed in + "Non-local Neural Networks" + Paper reference: https://arxiv.org/abs/1711.07971 + Code reference: https://github.com/AlexHex7/Non-local_pytorch + + Args: + ...
https://raw.githubusercontent.com/Mikubill/sd-webui-controlnet/HEAD/annotator/mmpkg/mmcv/cnn/bricks/non_local.py
Add docstrings to meet PEP guidelines
import torch from torch.autograd import Function from ..utils import ext_loader ext_module = ext_loader.load_ext('_ext', [ 'furthest_point_sampling_forward', 'furthest_point_sampling_with_dist_forward' ]) class FurthestPointSampling(Function): @staticmethod def forward(ctx, points_xyz: torch.Tensor...
--- +++ @@ -10,10 +10,20 @@ class FurthestPointSampling(Function): + """Uses iterative furthest point sampling to select a set of features whose + corresponding points have the furthest distance.""" @staticmethod def forward(ctx, points_xyz: torch.Tensor, num_points: int) -> torch...
https://raw.githubusercontent.com/Mikubill/sd-webui-controlnet/HEAD/annotator/mmpkg/mmcv/ops/furthest_point_sample.py
Generate docstrings for this script
# modified from https://github.com/rosinality/stylegan2-pytorch/blob/master/op/fused_act.py # noqa:E501 # Copyright (c) 2021, NVIDIA Corporation. All rights reserved. # NVIDIA Source Code License for StyleGAN2 with Adaptive Discriminator # Augmentation (ADA) # ==========================================================...
--- +++ @@ -106,6 +106,11 @@ class FusedBiasLeakyReLUFunctionBackward(Function): + """Calculate second order deviation. + + This function is to compute the second order deviation for the fused leaky + relu operation. + """ @staticmethod def forward(ctx, grad_output, out, negative_slope, scal...
https://raw.githubusercontent.com/Mikubill/sd-webui-controlnet/HEAD/annotator/mmpkg/mmcv/ops/fused_bias_leakyrelu.py
Generate consistent documentation across files
import torch from torch.autograd import Function from ..utils import ext_loader ext_module = ext_loader.load_ext('_ext', ['knn_forward']) class KNN(Function): @staticmethod def forward(ctx, k: int, xyz: torch.Tensor, center_xyz: torch.Tensor = None, ...
--- +++ @@ -7,6 +7,12 @@ class KNN(Function): + r"""KNN (CUDA) based on heap data structure. + Modified from `PAConv <https://github.com/CVMI-Lab/PAConv/tree/main/ + scene_seg/lib/pointops/src/knnquery_heap>`_. + + Find k-nearest points. + """ @staticmethod def forward(ctx, @@ -14,6 +20,2...
https://raw.githubusercontent.com/Mikubill/sd-webui-controlnet/HEAD/annotator/mmpkg/mmcv/ops/knn.py
Add docstrings for internal functions
import torch from torch.autograd import Function from ..utils import ext_loader ext_module = ext_loader.load_ext( '_ext', ['gather_points_forward', 'gather_points_backward']) class GatherPoints(Function): @staticmethod def forward(ctx, features: torch.Tensor, indices: torch.Tensor) -> t...
--- +++ @@ -8,10 +8,19 @@ class GatherPoints(Function): + """Gather points with given index.""" @staticmethod def forward(ctx, features: torch.Tensor, indices: torch.Tensor) -> torch.Tensor: + """ + Args: + features (Tensor): (B, C, N) features to gather. + ...
https://raw.githubusercontent.com/Mikubill/sd-webui-controlnet/HEAD/annotator/mmpkg/mmcv/ops/gather_points.py
Generate documentation strings for clarity
# Copyright (c) OpenMMLab. All rights reserved. from typing import Tuple import torch from torch import nn as nn from torch.autograd import Function from ..utils import ext_loader from .ball_query import ball_query from .knn import knn ext_module = ext_loader.load_ext( '_ext', ['group_points_forward', 'group_poi...
--- +++ @@ -14,6 +14,27 @@ class QueryAndGroup(nn.Module): + """Groups points with a ball query of radius. + + Args: + max_radius (float): The maximum radius of the balls. + If None is given, we will use kNN sampling instead of ball query. + sample_num (int): Maximum number of feature...
https://raw.githubusercontent.com/Mikubill/sd-webui-controlnet/HEAD/annotator/mmpkg/mmcv/ops/group_points.py
Add docstrings for internal functions
# Copyright (c) OpenMMLab. All rights reserved. import torch import torch.nn as nn from annotator.mmpkg.mmcv import build_from_cfg from .registry import DROPOUT_LAYERS def drop_path(x, drop_prob=0., training=False): if drop_prob == 0. or not training: return x keep_prob = 1 - drop_prob # handle t...
--- +++ @@ -7,6 +7,12 @@ def drop_path(x, drop_prob=0., training=False): + """Drop paths (Stochastic Depth) per sample (when applied in main path of + residual blocks). + + We follow the implementation + https://github.com/rwightman/pytorch-image-models/blob/a2727c1bf78ba0d7b5727f5f95e37fb7f8866b1f/timm...
https://raw.githubusercontent.com/Mikubill/sd-webui-controlnet/HEAD/annotator/mmpkg/mmcv/cnn/bricks/drop.py
Write Python docstrings for this snippet
import os import numpy as np import torch from annotator.mmpkg.mmcv.utils import deprecated_api_warning from ..utils import ext_loader ext_module = ext_loader.load_ext( '_ext', ['nms', 'softnms', 'nms_match', 'nms_rotated']) # This function is modified from: https://github.com/pytorch/vision/ class NMSop(torch...
--- +++ @@ -116,6 +116,38 @@ @deprecated_api_warning({'iou_thr': 'iou_threshold'}) def nms(boxes, scores, iou_threshold, offset=0, score_threshold=0, max_num=-1): + """Dispatch to either CPU or GPU NMS implementations. + + The input can be either torch tensor or numpy array. GPU NMS will be used + if the in...
https://raw.githubusercontent.com/Mikubill/sd-webui-controlnet/HEAD/annotator/mmpkg/mmcv/ops/nms.py
Write proper docstrings for these functions
# Modified from https://github.com/facebookresearch/detectron2/tree/master/projects/PointRend # noqa from os import path as osp import torch import torch.nn as nn import torch.nn.functional as F from torch.nn.modules.utils import _pair from torch.onnx.operators import shape_as_tensor def bilinear_grid_sample(im, g...
--- +++ @@ -10,6 +10,21 @@ def bilinear_grid_sample(im, grid, align_corners=False): + """Given an input and a flow-field grid, computes the output using input + values and pixel locations from grid. Supported only bilinear interpolation + method to sample the input pixels. + + Args: + im (torch.T...
https://raw.githubusercontent.com/Mikubill/sd-webui-controlnet/HEAD/annotator/mmpkg/mmcv/ops/point_sample.py
Generate consistent documentation across files
import inspect import platform from .registry import PLUGIN_LAYERS if platform.system() == 'Windows': import regex as re else: import re def infer_abbr(class_type): def camel2snack(word): word = re.sub(r'([A-Z]+)([A-Z][a-z])', r'\1_\2', word) word = re.sub(r'([a-z\d])([A-Z])', r'\1_\2'...
--- +++ @@ -10,8 +10,33 @@ def infer_abbr(class_type): + """Infer abbreviation from the class name. + + This method will infer the abbreviation to map class types to + abbreviations. + + Rule 1: If the class has the property "abbr", return the property. + Rule 2: Otherwise, the abbreviation falls bac...
https://raw.githubusercontent.com/Mikubill/sd-webui-controlnet/HEAD/annotator/mmpkg/mmcv/cnn/bricks/plugin.py
Generate NumPy-style docstrings
# Copyright (c) OpenMMLab. All rights reserved. import torch import torch.nn as nn from torch.autograd import Function from torch.autograd.function import once_differentiable from torch.nn.modules.utils import _pair from ..utils import deprecated_api_warning, ext_loader ext_module = ext_loader.load_ext('_ext', ...
--- +++ @@ -131,6 +131,41 @@ class RoIAlign(nn.Module): + """RoI align pooling layer. + + Args: + output_size (tuple): h, w + spatial_scale (float): scale the input boxes by this number + sampling_ratio (int): number of inputs samples to take for each + output sample. 0 to take...
https://raw.githubusercontent.com/Mikubill/sd-webui-controlnet/HEAD/annotator/mmpkg/mmcv/ops/roi_align.py
Create docstrings for reusable components
# Copyright (c) OpenMMLab. All rights reserved. import inspect import torch.nn as nn from annotator.mmpkg.mmcv.utils import is_tuple_of from annotator.mmpkg.mmcv.utils.parrots_wrapper import SyncBatchNorm, _BatchNorm, _InstanceNorm from .registry import NORM_LAYERS NORM_LAYERS.register_module('BN', module=nn.BatchNo...
--- +++ @@ -21,6 +21,27 @@ def infer_abbr(class_type): + """Infer abbreviation from the class name. + + When we build a norm layer with `build_norm_layer()`, we want to preserve + the norm type in variable names, e.g, self.bn1, self.gn. This method will + infer the abbreviation to map class types to abb...
https://raw.githubusercontent.com/Mikubill/sd-webui-controlnet/HEAD/annotator/mmpkg/mmcv/cnn/bricks/norm.py
Create docstrings for each class method
# Copyright (c) OpenMMLab. All rights reserved. # Code reference from "Temporal Interlacing Network" # https://github.com/deepcs233/TIN/blob/master/cuda_shift/rtc_wrap.py # Hao Shao, Shengju Qian, Yu Liu # shaoh19@mails.tsinghua.edu.cn, sjqian@cse.cuhk.edu.hk, yuliu@ee.cuhk.edu.hk import torch import torch.nn as nn fr...
--- +++ @@ -46,6 +46,23 @@ class TINShift(nn.Module): + """Temporal Interlace Shift. + + Temporal Interlace shift is a differentiable temporal-wise frame shifting + which is proposed in "Temporal Interlacing Network" + + Please refer to https://arxiv.org/abs/2001.06499 for more details. + Code is mod...
https://raw.githubusercontent.com/Mikubill/sd-webui-controlnet/HEAD/annotator/mmpkg/mmcv/ops/tin_shift.py
Write docstrings that follow conventions
# Copyright (c) OpenMMLab. All rights reserved. import torch from torch import nn as nn from torch.autograd import Function import annotator.mmpkg.mmcv as mmcv from ..utils import ext_loader ext_module = ext_loader.load_ext( '_ext', ['roiaware_pool3d_forward', 'roiaware_pool3d_backward']) class RoIAwarePool3d(n...
--- +++ @@ -11,6 +11,19 @@ class RoIAwarePool3d(nn.Module): + """Encode the geometry-specific features of each 3D proposal. + + Please refer to `PartA2 <https://arxiv.org/pdf/1907.03670.pdf>`_ for more + details. + + Args: + out_size (int or tuple): The size of output features. n or + ...
https://raw.githubusercontent.com/Mikubill/sd-webui-controlnet/HEAD/annotator/mmpkg/mmcv/ops/roiaware_pool3d.py
Add standardized docstrings across the file
from torch import nn as nn from torch.autograd import Function from ..utils import ext_loader ext_module = ext_loader.load_ext('_ext', ['roipoint_pool3d_forward']) class RoIPointPool3d(nn.Module): def __init__(self, num_sampled_points=512): super().__init__() self.num_sampled_points = num_sampl...
--- +++ @@ -7,12 +7,33 @@ class RoIPointPool3d(nn.Module): + """Encode the geometry-specific features of each 3D proposal. + + Please refer to `Paper of PartA2 <https://arxiv.org/pdf/1907.03670.pdf>`_ + for more details. + + Args: + num_sampled_points (int, optional): Number of samples in each ro...
https://raw.githubusercontent.com/Mikubill/sd-webui-controlnet/HEAD/annotator/mmpkg/mmcv/ops/roipoint_pool3d.py
Fill in missing docstrings in my code
# Copyright (c) OpenMMLab. All rights reserved. import torch from torch import nn from torch.autograd import Function from torch.nn.modules.utils import _pair from ..utils import ext_loader ext_module = ext_loader.load_ext( '_ext', ['dynamic_voxelize_forward', 'hard_voxelize_forward']) class _Voxelization(Funct...
--- +++ @@ -19,6 +19,31 @@ coors_range, max_points=35, max_voxels=20000): + """Convert kitti points(N, >=3) to voxels. + + Args: + points (torch.Tensor): [N, ndim]. Points[:, :3] contain xyz points + and points[:, 3:] contain othe...
https://raw.githubusercontent.com/Mikubill/sd-webui-controlnet/HEAD/annotator/mmpkg/mmcv/ops/voxelize.py
Improve my code by adding docstrings
# Copyright (c) OpenMMLab. All rights reserved. from itertools import chain from torch.nn.parallel import DataParallel from .scatter_gather import scatter_kwargs class MMDataParallel(DataParallel): def __init__(self, *args, dim=0, **kwargs): super(MMDataParallel, self).__init__(*args, dim=dim, **kwargs...
--- +++ @@ -7,12 +7,32 @@ class MMDataParallel(DataParallel): + """The DataParallel module that supports DataContainer. + + MMDataParallel has two main differences with PyTorch DataParallel: + + - It supports a custom type :class:`DataContainer` which allows more + flexible control of input data durin...
https://raw.githubusercontent.com/Mikubill/sd-webui-controlnet/HEAD/annotator/mmpkg/mmcv/parallel/data_parallel.py
Add docstrings that explain purpose and usage
# Copyright (c) OpenMMLab. All rights reserved. import copy import math import warnings import numpy as np import torch import torch.nn as nn from torch import Tensor from annotator.mmpkg.mmcv.utils import Registry, build_from_cfg, get_logger, print_log INITIALIZERS = Registry('initializer') def update_init_info(m...
--- +++ @@ -14,6 +14,15 @@ def update_init_info(module, init_info): + """Update the `_params_init_info` in the module if the value of parameters + are changed. + + Args: + module (obj:`nn.Module`): The module of PyTorch with a user-defined + attribute `_params_init_info` which records the...
https://raw.githubusercontent.com/Mikubill/sd-webui-controlnet/HEAD/annotator/mmpkg/mmcv/cnn/utils/weight_init.py
Write docstrings for algorithm functions
# Copyright (c) OpenMMLab. All rights reserved. import copy import warnings from abc import ABCMeta from collections import defaultdict from logging import FileHandler import torch.nn as nn from annotator.mmpkg.mmcv.runner.dist_utils import master_only from annotator.mmpkg.mmcv.utils.logging import get_logger, logger...
--- +++ @@ -12,8 +12,26 @@ class BaseModule(nn.Module, metaclass=ABCMeta): + """Base module for all modules in openmmlab. + + ``BaseModule`` is a wrapper of ``torch.nn.Module`` with additional + functionality of parameter initialization. Compared with + ``torch.nn.Module``, ``BaseModule`` mainly adds th...
https://raw.githubusercontent.com/Mikubill/sd-webui-controlnet/HEAD/annotator/mmpkg/mmcv/runner/base_module.py
Generate docstrings for script automation
# Copyright (c) OpenMMLab. All rights reserved. import copy import logging import os.path as osp import warnings from abc import ABCMeta, abstractmethod import torch from torch.optim import Optimizer import annotator.mmpkg.mmcv as mmcv from ..parallel import is_module_wrapper from .checkpoint import load_checkpoint f...
--- +++ @@ -19,6 +19,34 @@ class BaseRunner(metaclass=ABCMeta): + """The base class of Runner, a training helper for PyTorch. + + All subclasses should implement the following APIs: + + - ``run()`` + - ``train()`` + - ``val()`` + - ``save_checkpoint()`` + + Args: + model (:obj:`torch.nn....
https://raw.githubusercontent.com/Mikubill/sd-webui-controlnet/HEAD/annotator/mmpkg/mmcv/runner/base_runner.py
Add docstrings to improve readability
# Modified from flops-counter.pytorch by Vladislav Sovrasov # original repo: https://github.com/sovrasov/flops-counter.pytorch # MIT License # Copyright (c) 2018 Vladislav Sovrasov # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (th...
--- +++ @@ -40,6 +40,47 @@ input_constructor=None, flush=False, ost=sys.stdout): + """Get complexity information of a model. + + This method can calculate FLOPs and parameter counts of a model with + corresponding input...
https://raw.githubusercontent.com/Mikubill/sd-webui-controlnet/HEAD/annotator/mmpkg/mmcv/cnn/utils/flops_counter.py
Write docstrings for utility functions
# Copyright (c) OpenMMLab. All rights reserved. import io import os import os.path as osp import pkgutil import re import time import warnings from collections import OrderedDict from importlib import import_module from tempfile import TemporaryDirectory import torch import torchvision from torch.optim import Optimize...
--- +++ @@ -39,6 +39,21 @@ def load_state_dict(module, state_dict, strict=False, logger=None): + """Load state_dict to a module. + + This method is modified from :meth:`torch.nn.Module.load_state_dict`. + Default value for ``strict`` is set to ``False`` and the message for + param mismatch will be shown...
https://raw.githubusercontent.com/Mikubill/sd-webui-controlnet/HEAD/annotator/mmpkg/mmcv/runner/checkpoint.py
Generate helpful docstrings for debugging
# Copyright (c) OpenMMLab. All rights reserved. import functools import os import subprocess from collections import OrderedDict import torch import torch.multiprocessing as mp from torch import distributed as dist from torch._utils import (_flatten_dense_tensors, _take_tensors, _unflatten_de...
--- +++ @@ -41,6 +41,16 @@ def _init_dist_slurm(backend, port=None): + """Initialize slurm distributed training environment. + + If argument ``port`` is not specified, then the master port will be system + environment variable ``MASTER_PORT``. If ``MASTER_PORT`` is not in system + environment variable, ...
https://raw.githubusercontent.com/Mikubill/sd-webui-controlnet/HEAD/annotator/mmpkg/mmcv/runner/dist_utils.py
Fill in missing docstrings in my code
import torch import annotator.mmpkg.mmcv as mmcv class _BatchNormXd(torch.nn.modules.batchnorm._BatchNorm): def _check_input_dim(self, input): return def revert_sync_batchnorm(module): module_output = module module_checklist = [torch.nn.modules.batchnorm.SyncBatchNorm] if hasattr(mmcv, 'op...
--- +++ @@ -4,12 +4,34 @@ class _BatchNormXd(torch.nn.modules.batchnorm._BatchNorm): + """A general BatchNorm layer without input dimension check. + + Reproduced from @kapily's work: + (https://github.com/pytorch/pytorch/issues/41081#issuecomment-783961547) + The only difference between BatchNorm1d, Bat...
https://raw.githubusercontent.com/Mikubill/sd-webui-controlnet/HEAD/annotator/mmpkg/mmcv/cnn/utils/sync_bn.py
Add docstrings to improve readability
# Copyright (c) OpenMMLab. All rights reserved. import torch import torch.nn as nn def _fuse_conv_bn(conv, bn): conv_w = conv.weight conv_b = conv.bias if conv.bias is not None else torch.zeros_like( bn.running_mean) factor = bn.weight / torch.sqrt(bn.running_var + bn.eps) conv.weight = nn.Pa...
--- +++ @@ -4,6 +4,15 @@ def _fuse_conv_bn(conv, bn): + """Fuse conv and bn into one module. + + Args: + conv (nn.Module): Conv to be fused. + bn (nn.Module): BN to be fused. + + Returns: + nn.Module: Fused module. + """ conv_w = conv.weight conv_b = conv.bias if conv.bias...
https://raw.githubusercontent.com/Mikubill/sd-webui-controlnet/HEAD/annotator/mmpkg/mmcv/cnn/utils/fuse_conv_bn.py
Improve documentation using docstrings
# Copyright (c) OpenMMLab. All rights reserved. import os.path as osp import warnings from math import inf import torch.distributed as dist from torch.nn.modules.batchnorm import _BatchNorm from torch.utils.data import DataLoader from annotator.mmpkg.mmcv.fileio import FileClient from annotator.mmpkg.mmcv.utils impor...
--- +++ @@ -14,6 +14,61 @@ class EvalHook(Hook): + """Non-Distributed evaluation hook. + + This hook will regularly perform evaluation in a given interval when + performing in non-distributed environment. + + Args: + dataloader (DataLoader): A PyTorch dataloader, whose dataset has + im...
https://raw.githubusercontent.com/Mikubill/sd-webui-controlnet/HEAD/annotator/mmpkg/mmcv/runner/hooks/evaluation.py
Add docstrings for utility scripts
# Copyright (c) OpenMMLab. All rights reserved. from ...parallel import is_module_wrapper from ..hooks.hook import HOOKS, Hook @HOOKS.register_module() class EMAHook(Hook): def __init__(self, momentum=0.0002, interval=1, warm_up=100, resume_from...
--- +++ @@ -5,6 +5,26 @@ @HOOKS.register_module() class EMAHook(Hook): + r"""Exponential Moving Average Hook. + + Use Exponential Moving Average on all parameters of model in training + process. All parameters have a ema backup, which update by the formula + as below. EMAHook takes priority over EvalHook...
https://raw.githubusercontent.com/Mikubill/sd-webui-controlnet/HEAD/annotator/mmpkg/mmcv/runner/hooks/ema.py
Write beginner-friendly docstrings
# Copyright (c) OpenMMLab. All rights reserved. from io import BytesIO, StringIO from pathlib import Path from ..utils import is_list_of, is_str from .file_client import FileClient from .handlers import BaseFileHandler, JsonHandler, PickleHandler, YamlHandler file_handlers = { 'json': JsonHandler(), 'yaml': Y...
--- +++ @@ -16,6 +16,33 @@ def load(file, file_format=None, file_client_args=None, **kwargs): + """Load data from json/yaml/pickle files. + + This method provides a unified api for loading data from serialized files. + + Note: + In v1.3.16 and later, ``load`` supports loading data from serialized + ...
https://raw.githubusercontent.com/Mikubill/sd-webui-controlnet/HEAD/annotator/mmpkg/mmcv/fileio/io.py
Generate consistent docstrings
# Copyright (c) OpenMMLab. All rights reserved. import os.path as osp import warnings from annotator.mmpkg.mmcv.fileio import FileClient from ..dist_utils import allreduce_params, master_only from .hook import HOOKS, Hook @HOOKS.register_module() class CheckpointHook(Hook): def __init__(self, i...
--- +++ @@ -9,6 +9,44 @@ @HOOKS.register_module() class CheckpointHook(Hook): + """Save checkpoints periodically. + + Args: + interval (int): The saving period. If ``by_epoch=True``, interval + indicates epochs, otherwise it indicates iterations. + Default: -1, which means "never"....
https://raw.githubusercontent.com/Mikubill/sd-webui-controlnet/HEAD/annotator/mmpkg/mmcv/runner/hooks/checkpoint.py
Write docstrings for backend logic
# Copyright (c) OpenMMLab. All rights reserved. import annotator.mmpkg.mmcv as mmcv from .hook import HOOKS, Hook from .lr_updater import annealing_cos, annealing_linear, format_param class MomentumUpdaterHook(Hook): def __init__(self, by_epoch=True, warmup=None, ...
--- +++ @@ -152,6 +152,18 @@ @HOOKS.register_module() class StepMomentumUpdaterHook(MomentumUpdaterHook): + """Step momentum scheduler with min value clipping. + + Args: + step (int | list[int]): Step to decay the momentum. If an int value is + given, regard it as the decay interval. If a lis...
https://raw.githubusercontent.com/Mikubill/sd-webui-controlnet/HEAD/annotator/mmpkg/mmcv/runner/hooks/momentum_updater.py
Write docstrings for algorithm functions
# Copyright (c) OpenMMLab. All rights reserved. import torch import torch.nn as nn import torch.nn.functional as F from annotator.mmpkg.mmcv.cnn import PLUGIN_LAYERS, Scale def NEG_INF_DIAG(n, device): return torch.diag(torch.tensor(float('-inf')).to(device).repeat(n), 0) @PLUGIN_LAYERS.register_module() class...
--- +++ @@ -7,11 +7,39 @@ def NEG_INF_DIAG(n, device): + """Returns a diagonal matrix of size [n, n]. + + The diagonal are all "-inf". This is for avoiding calculating the + overlapped element in the Criss-Cross twice. + """ return torch.diag(torch.tensor(float('-inf')).to(device).repeat(n), 0) ...
https://raw.githubusercontent.com/Mikubill/sd-webui-controlnet/HEAD/annotator/mmpkg/mmcv/ops/cc_attention.py
Write docstrings for data processing functions
# Copyright (c) OpenMMLab. All rights reserved. from typing import Tuple, Union import torch import torch.nn as nn import torch.nn.functional as F from torch import Tensor from torch.autograd import Function from torch.autograd.function import once_differentiable from torch.nn.modules.utils import _pair, _single from...
--- +++ @@ -190,6 +190,38 @@ class DeformConv2d(nn.Module): + r"""Deformable 2D convolution. + + Applies a deformable 2D convolution over an input signal composed of + several input planes. DeformConv2d was described in the paper + `Deformable Convolutional Networks + <https://arxiv.org/pdf/1703.0621...
https://raw.githubusercontent.com/Mikubill/sd-webui-controlnet/HEAD/annotator/mmpkg/mmcv/ops/deform_conv.py
Replace inline comments with docstrings
# Copyright (c) OpenMMLab. All rights reserved. import numbers from math import cos, pi import annotator.mmpkg.mmcv as mmcv from .hook import HOOKS, Hook class LrUpdaterHook(Hook): def __init__(self, by_epoch=True, warmup=None, warmup_iters=0, ...
--- +++ @@ -7,6 +7,20 @@ class LrUpdaterHook(Hook): + """LR Scheduler in MMCV. + + Args: + by_epoch (bool): LR changes epoch by epoch + warmup (string): Type of warmup used. It can be None(use no warmup), + 'constant', 'linear' or 'exp' + warmup_iters (int): The number of itera...
https://raw.githubusercontent.com/Mikubill/sd-webui-controlnet/HEAD/annotator/mmpkg/mmcv/runner/hooks/lr_updater.py
Replace inline comments with docstrings
# Copyright (c) OpenMMLab. All rights reserved. import math import warnings import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd.function import Function, once_differentiable from annotator.mmpkg.mmcv import deprecated_api_warning from annotator.mmpkg.mmcv.cnn import constant_init, x...
--- +++ @@ -22,6 +22,26 @@ @staticmethod def forward(ctx, value, value_spatial_shapes, value_level_start_index, sampling_locations, attention_weights, im2col_step): + """GPU version of multi-scale deformable attention. + + Args: + value (Tensor): The value has shape + ...
https://raw.githubusercontent.com/Mikubill/sd-webui-controlnet/HEAD/annotator/mmpkg/mmcv/ops/multi_scale_deform_attn.py
Add verbose docstrings with examples
# Copyright (c) OpenMMLab. All rights reserved. import torch from torch import nn from torch.autograd import Function from ..utils import ext_loader ext_module = ext_loader.load_ext( '_ext', ['dynamic_point_to_voxel_forward', 'dynamic_point_to_voxel_backward']) class _DynamicScatter(Function): @staticm...
--- +++ @@ -14,6 +14,22 @@ @staticmethod def forward(ctx, feats, coors, reduce_type='max'): + """convert kitti points(N, >=3) to voxels. + + Args: + feats (torch.Tensor): [N, C]. Points features to be reduced + into voxels. + coors (torch.Tensor): [N, ndim]....
https://raw.githubusercontent.com/Mikubill/sd-webui-controlnet/HEAD/annotator/mmpkg/mmcv/ops/scatter_points.py
Add docstrings to clarify complex logic
import torch from ..utils import ext_loader ext_module = ext_loader.load_ext('_ext', [ 'points_in_boxes_part_forward', 'points_in_boxes_cpu_forward', 'points_in_boxes_all_forward' ]) def points_in_boxes_part(points, boxes): assert points.shape[0] == boxes.shape[0], \ 'Points and boxes should hav...
--- +++ @@ -9,6 +9,17 @@ def points_in_boxes_part(points, boxes): + """Find the box in which each point is (CUDA). + + Args: + points (torch.Tensor): [B, M, 3], [x, y, z] in LiDAR/DEPTH coordinate + boxes (torch.Tensor): [B, T, 7], + num_valid_boxes <= T, [x, y, z, x_size, y_size, z_s...
https://raw.githubusercontent.com/Mikubill/sd-webui-controlnet/HEAD/annotator/mmpkg/mmcv/ops/points_in_boxes.py
Create docstrings for each class method
# Copyright (c) OpenMMLab. All rights reserved. from enum import Enum class Priority(Enum): HIGHEST = 0 VERY_HIGH = 10 HIGH = 30 ABOVE_NORMAL = 40 NORMAL = 50 BELOW_NORMAL = 60 LOW = 70 VERY_LOW = 90 LOWEST = 100 def get_priority(priority): if isinstance(priority, int): ...
--- +++ @@ -3,6 +3,30 @@ class Priority(Enum): + """Hook priority levels. + + +--------------+------------+ + | Level | Value | + +==============+============+ + | HIGHEST | 0 | + +--------------+------------+ + | VERY_HIGH | 10 | + +--------------+------...
https://raw.githubusercontent.com/Mikubill/sd-webui-controlnet/HEAD/annotator/mmpkg/mmcv/runner/priority.py
Insert docstrings into my code
# Copyright (c) OpenMMLab. All rights reserved. import os.path as osp import subprocess import sys from collections import defaultdict import cv2 import torch import annotator.mmpkg.mmcv as mmcv from .parrots_wrapper import get_build_config def collect_env(): env_info = {} env_info['sys.platform'] = sys.pl...
--- +++ @@ -1,4 +1,5 @@ # Copyright (c) OpenMMLab. All rights reserved. +"""This file holding some environment constant for sharing by other files.""" import os.path as osp import subprocess @@ -13,6 +14,27 @@ def collect_env(): + """Collect the information of the running environments. + + Returns: + ...
https://raw.githubusercontent.com/Mikubill/sd-webui-controlnet/HEAD/annotator/mmpkg/mmcv/utils/env.py
Write docstrings describing each step
# Copyright (c) OpenMMLab. All rights reserved. import os import os.path as osp from pathlib import Path from .misc import is_str def is_filepath(x): return is_str(x) or isinstance(x, Path) def fopen(filepath, *args, **kwargs): if is_str(filepath): return open(filepath, *args, **kwargs) elif is...
--- +++ @@ -37,6 +37,20 @@ def scandir(dir_path, suffix=None, recursive=False, case_sensitive=True): + """Scan a directory to find the interested files. + + Args: + dir_path (str | obj:`Path`): Path of the directory. + suffix (str | tuple(str), optional): File suffix that we are + int...
https://raw.githubusercontent.com/Mikubill/sd-webui-controlnet/HEAD/annotator/mmpkg/mmcv/utils/path.py
Generate docstrings for exported functions
# Copyright (c) OpenMMLab. All rights reserved. import ast import copy import os import os.path as osp import platform import shutil import sys import tempfile import uuid import warnings from argparse import Action, ArgumentParser from collections import abc from importlib import import_module from addict import Dict...
--- +++ @@ -68,6 +68,29 @@ class Config: + """A facility for config and config files. + + It supports common file formats as configs: python/json/yaml. The interface + is the same as a dict object and also allows access config values as + attributes. + + Example: + >>> cfg = Config(dict(a=1, b...
https://raw.githubusercontent.com/Mikubill/sd-webui-controlnet/HEAD/annotator/mmpkg/mmcv/utils/config.py
Write beginner-friendly docstrings
# Copyright (c) OpenMMLab. All rights reserved. from time import time class TimerError(Exception): def __init__(self, message): self.message = message super(TimerError, self).__init__(message) class Timer: def __init__(self, start=True, print_tmpl=None): self._is_running = False ...
--- +++ @@ -10,6 +10,30 @@ class Timer: + """A flexible Timer class. + + :Example: + + >>> import time + >>> import annotator.mmpkg.mmcv as mmcv + >>> with mmcv.Timer(): + >>> # simulate a code block that will run for 1s + >>> time.sleep(1) + 1.000 + >>> with mmcv.Timer(print_tmpl...
https://raw.githubusercontent.com/Mikubill/sd-webui-controlnet/HEAD/annotator/mmpkg/mmcv/utils/timer.py
Create docstrings for API functions
from typing import Tuple import torch from torch.autograd import Function from ..utils import ext_loader ext_module = ext_loader.load_ext( '_ext', ['three_interpolate_forward', 'three_interpolate_backward']) class ThreeInterpolate(Function): @staticmethod def forward(ctx, features: torch.Tensor, indic...
--- +++ @@ -10,10 +10,26 @@ class ThreeInterpolate(Function): + """Performs weighted linear interpolation on 3 features. + + Please refer to `Paper of PointNet++ <https://arxiv.org/abs/1706.02413>`_ + for more details. + """ @staticmethod def forward(ctx, features: torch.Tensor, indices: tor...
https://raw.githubusercontent.com/Mikubill/sd-webui-controlnet/HEAD/annotator/mmpkg/mmcv/ops/three_interpolate.py
Document this script properly
# Copyright (c) OpenMMLab. All rights reserved. import inspect import warnings from functools import partial from .misc import is_seq_of def build_from_cfg(cfg, registry, default_args=None): if not isinstance(cfg, dict): raise TypeError(f'cfg must be a dict, but got {type(cfg)}') if 'type' not in cfg...
--- +++ @@ -7,6 +7,16 @@ def build_from_cfg(cfg, registry, default_args=None): + """Build a module from config dict. + + Args: + cfg (dict): Config dict. It should at least contain the key "type". + registry (:obj:`Registry`): The registry to search the type from. + default_args (dict, op...
https://raw.githubusercontent.com/Mikubill/sd-webui-controlnet/HEAD/annotator/mmpkg/mmcv/utils/registry.py
Write docstrings describing each step
# Copyright (c) OpenMMLab. All rights reserved. import os.path as osp import platform import shutil import time import warnings import torch from torch.optim import Optimizer import annotator.mmpkg.mmcv as mmcv from .base_runner import BaseRunner from .builder import RUNNERS from .checkpoint import save_checkpoint fr...
--- +++ @@ -46,6 +46,10 @@ @RUNNERS.register_module() class IterBasedRunner(BaseRunner): + """Iteration-based Runner. + + This runner train models iteration by iteration. + """ def train(self, data_loader, **kwargs): self.model.train() @@ -81,6 +85,16 @@ self._inner_iter += 1 ...
https://raw.githubusercontent.com/Mikubill/sd-webui-controlnet/HEAD/annotator/mmpkg/mmcv/runner/iter_based_runner.py
Add docstrings for production code
# Copyright (c) OpenMMLab. All rights reserved. import torch from ..utils import ext_loader ext_module = ext_loader.load_ext('_ext', [ 'iou3d_boxes_iou_bev_forward', 'iou3d_nms_forward', 'iou3d_nms_normal_forward' ]) def boxes_iou_bev(boxes_a, boxes_b): ans_iou = boxes_a.new_zeros( torch.Size((b...
--- +++ @@ -10,6 +10,15 @@ def boxes_iou_bev(boxes_a, boxes_b): + """Calculate boxes IoU in the Bird's Eye View. + + Args: + boxes_a (torch.Tensor): Input boxes a with shape (M, 5). + boxes_b (torch.Tensor): Input boxes b with shape (N, 5). + + Returns: + ans_iou (torch.Tensor): IoU re...
https://raw.githubusercontent.com/Mikubill/sd-webui-controlnet/HEAD/annotator/mmpkg/mmcv/ops/iou3d.py
Generate missing documentation strings
# Copyright (c) OpenMMLab. All rights reserved. import functools import warnings from collections import abc from inspect import getfullargspec import numpy as np import torch import torch.nn as nn from annotator.mmpkg.mmcv.utils import TORCH_VERSION, digit_version from .dist_utils import allreduce_grads as _allreduc...
--- +++ @@ -22,6 +22,16 @@ def cast_tensor_type(inputs, src_type, dst_type): + """Recursively convert Tensor in inputs from src_type to dst_type. + + Args: + inputs: Inputs that to be casted. + src_type (torch.dtype): Source type.. + dst_type (torch.dtype): Destination type. + + Return...
https://raw.githubusercontent.com/Mikubill/sd-webui-controlnet/HEAD/annotator/mmpkg/mmcv/runner/fp16_utils.py
Add docstrings explaining edge cases
# Copyright (c) OpenMMLab. All rights reserved. import os import random import sys import time import warnings from getpass import getuser from socket import gethostname import numpy as np import torch import annotator.mmpkg.mmcv as mmcv def get_host_info(): host = '' try: host = f'{getuser()}@{geth...
--- +++ @@ -14,6 +14,11 @@ def get_host_info(): + """Get hostname and username. + + Return empty string if exception raised, e.g. ``getpass.getuser()`` will + lead to error in docker container + """ host = '' try: host = f'{getuser()}@{gethostname()}' @@ -28,6 +33,22 @@ def obj_fr...
https://raw.githubusercontent.com/Mikubill/sd-webui-controlnet/HEAD/annotator/mmpkg/mmcv/runner/utils.py
Document all public functions with docstrings
# Copyright (c) OpenMMLab. All rights reserved. import os.path as osp from collections import OrderedDict import cv2 from cv2 import (CAP_PROP_FOURCC, CAP_PROP_FPS, CAP_PROP_FRAME_COUNT, CAP_PROP_FRAME_HEIGHT, CAP_PROP_FRAME_WIDTH, CAP_PROP_POS_FRAMES, VideoWriter_fourcc) from annota...
--- +++ @@ -40,6 +40,26 @@ class VideoReader: + """Video class with similar usage to a list object. + + This video warpper class provides convenient apis to access frames. + There exists an issue of OpenCV's VideoCapture class that jumping to a + certain frame may be inaccurate. It is fixed in this clas...
https://raw.githubusercontent.com/Mikubill/sd-webui-controlnet/HEAD/annotator/mmpkg/mmcv/video/io.py
Please document this code using docstrings
# Copyright (c) OpenMMLab. All rights reserved. import os.path as osp import platform import shutil import time import warnings import torch import annotator.mmpkg.mmcv as mmcv from .base_runner import BaseRunner from .builder import RUNNERS from .checkpoint import save_checkpoint from .utils import get_host_info @...
--- +++ @@ -16,6 +16,10 @@ @RUNNERS.register_module() class EpochBasedRunner(BaseRunner): + """Epoch-based Runner. + + This runner train models epoch by epoch. + """ def run_iter(self, data_batch, train_mode, **kwargs): if self.batch_processor is not None: @@ -66,6 +70,16 @@ self.cal...
https://raw.githubusercontent.com/Mikubill/sd-webui-controlnet/HEAD/annotator/mmpkg/mmcv/runner/epoch_based_runner.py
Create documentation for each function signature
from typing import List import torch from torch import nn as nn from annotator.mmpkg.mmcv.runner import force_fp32 from .furthest_point_sample import (furthest_point_sample, furthest_point_sample_with_dist) def calc_square_dist(point_feat_a, point_feat_b, norm=True): num_chan...
--- +++ @@ -9,6 +9,17 @@ def calc_square_dist(point_feat_a, point_feat_b, norm=True): + """Calculating square distance between a and b. + + Args: + point_feat_a (Tensor): (B, N, C) Feature vector of each point. + point_feat_b (Tensor): (B, M, C) Feature vector of each point. + norm (Bool,...
https://raw.githubusercontent.com/Mikubill/sd-webui-controlnet/HEAD/annotator/mmpkg/mmcv/ops/points_sampler.py
Create docstrings for all classes and functions
from typing import Tuple import torch from torch.autograd import Function from ..utils import ext_loader ext_module = ext_loader.load_ext('_ext', ['three_nn_forward']) class ThreeNN(Function): @staticmethod def forward(ctx, target: torch.Tensor, source: torch.Tensor) -> Tuple[torch.Tensor,...
--- +++ @@ -9,10 +9,26 @@ class ThreeNN(Function): + """Find the top-3 nearest neighbors of the target set from the source set. + + Please refer to `Paper of PointNet++ <https://arxiv.org/abs/1706.02413>`_ + for more details. + """ @staticmethod def forward(ctx, target: torch.Tensor, ...
https://raw.githubusercontent.com/Mikubill/sd-webui-controlnet/HEAD/annotator/mmpkg/mmcv/ops/three_nn.py
Add docstrings that explain inputs and outputs
# Copyright (c) OpenMMLab. All rights reserved. import torch from torch.nn.parallel._functions import Scatter as OrigScatter from ._functions import Scatter from .data_container import DataContainer def scatter(inputs, target_gpus, dim=0): def scatter_map(obj): if isinstance(obj, torch.Tensor): ...
--- +++ @@ -7,6 +7,11 @@ def scatter(inputs, target_gpus, dim=0): + """Scatter inputs to target gpus. + + The only difference from original :func:`scatter` is to add support for + :type:`~mmcv.parallel.DataContainer`. + """ def scatter_map(obj): if isinstance(obj, torch.Tensor): @@ -42,6...
https://raw.githubusercontent.com/Mikubill/sd-webui-controlnet/HEAD/annotator/mmpkg/mmcv/parallel/scatter_gather.py
Add docstrings with type hints explained
# Copyright (c) OpenMMLab. All rights reserved. import os import os.path as osp import subprocess import tempfile from annotator.mmpkg.mmcv.utils import requires_executable @requires_executable('ffmpeg') def convert_video(in_file, out_file, print_cmd=False, pre_o...
--- +++ @@ -13,6 +13,24 @@ print_cmd=False, pre_options='', **kwargs): + """Convert a video with ffmpeg. + + This provides a general api to ffmpeg, the executed command is:: + + `ffmpeg -y <pre_options> -i <in_file> <options> <out_file>` + + Option...
https://raw.githubusercontent.com/Mikubill/sd-webui-controlnet/HEAD/annotator/mmpkg/mmcv/video/processing.py
Add verbose docstrings with examples
# Copyright (c) OpenMMLab. All rights reserved. from enum import Enum import numpy as np from annotator.mmpkg.mmcv.utils import is_str class Color(Enum): red = (0, 0, 255) green = (0, 255, 0) blue = (255, 0, 0) cyan = (255, 255, 0) yellow = (0, 255, 255) magenta = (255, 0, 255) white = (...
--- +++ @@ -7,6 +7,10 @@ class Color(Enum): + """An enum that defines common colors. + + Contains red, green, blue, cyan, yellow, magenta, white and black. + """ red = (0, 0, 255) green = (0, 255, 0) blue = (255, 0, 0) @@ -18,6 +22,14 @@ def color_val(color): + """Convert various inpu...
https://raw.githubusercontent.com/Mikubill/sd-webui-controlnet/HEAD/annotator/mmpkg/mmcv/visualization/color.py
Generate consistent docstrings
# Copyright (c) OpenMMLab. All rights reserved. import cv2 import numpy as np from annotator.mmpkg.mmcv.image import imread, imwrite from .color import color_val def imshow(img, win_name='', wait_time=0): cv2.imshow(win_name, imread(img)) if wait_time == 0: # prevent from hanging if windows was closed ...
--- +++ @@ -7,6 +7,13 @@ def imshow(img, win_name='', wait_time=0): + """Show an image. + + Args: + img (str or ndarray): The image to be displayed. + win_name (str): The window name. + wait_time (int): Value of waitKey param. + """ cv2.imshow(win_name, imread(img)) if wait_t...
https://raw.githubusercontent.com/Mikubill/sd-webui-controlnet/HEAD/annotator/mmpkg/mmcv/visualization/image.py
Add docstrings to improve collaboration
import matplotlib.pyplot as plt import annotator.mmpkg.mmcv as mmcv import torch from annotator.mmpkg.mmcv.parallel import collate, scatter from annotator.mmpkg.mmcv.runner import load_checkpoint from annotator.mmpkg.mmseg.datasets.pipelines import Compose from annotator.mmpkg.mmseg.models import build_segmentor from ...
--- +++ @@ -10,6 +10,18 @@ def init_segmentor(config, checkpoint=None, device=devices.get_device_for("controlnet")): + """Initialize a segmentor from config file. + + Args: + config (str or :obj:`mmcv.Config`): Config file path or the config + object. + checkpoint (str, optional): Che...
https://raw.githubusercontent.com/Mikubill/sd-webui-controlnet/HEAD/annotator/mmpkg/mmseg/apis/inference.py
Generate consistent documentation across files
import annotator.mmpkg.mmcv as mmcv def cityscapes_classes(): return [ 'road', 'sidewalk', 'building', 'wall', 'fence', 'pole', 'traffic light', 'traffic sign', 'vegetation', 'terrain', 'sky', 'person', 'rider', 'car', 'truck', 'bus', 'train', 'motorcycle', 'bicycle' ] def ad...
--- +++ @@ -2,6 +2,7 @@ def cityscapes_classes(): + """Cityscapes class names for external use.""" return [ 'road', 'sidewalk', 'building', 'wall', 'fence', 'pole', 'traffic light', 'traffic sign', 'vegetation', 'terrain', 'sky', @@ -11,6 +12,7 @@ def ade_classes(): + """ADE20K clas...
https://raw.githubusercontent.com/Mikubill/sd-webui-controlnet/HEAD/annotator/mmpkg/mmseg/core/evaluation/class_names.py
Document functions with detailed explanations
from collections import OrderedDict import annotator.mmpkg.mmcv as mmcv import numpy as np import torch def f_score(precision, recall, beta=1): score = (1 + beta**2) * (precision * recall) / ( (beta**2 * precision) + recall) return score def intersect_and_union(pred_label, l...
--- +++ @@ -6,6 +6,17 @@ def f_score(precision, recall, beta=1): + """calcuate the f-score value. + + Args: + precision (float | torch.Tensor): The precision value. + recall (float | torch.Tensor): The recall value. + beta (int): Determines the weight of recall in the combined score. + ...
https://raw.githubusercontent.com/Mikubill/sd-webui-controlnet/HEAD/annotator/mmpkg/mmseg/core/evaluation/metrics.py
Generate documentation strings for clarity
import os.path as osp from annotator.mmpkg.mmcv.runner import DistEvalHook as _DistEvalHook from annotator.mmpkg.mmcv.runner import EvalHook as _EvalHook class EvalHook(_EvalHook): greater_keys = ['mIoU', 'mAcc', 'aAcc'] def __init__(self, *args, by_epoch=False, efficient_test=False, **kwargs): sup...
--- +++ @@ -5,6 +5,17 @@ class EvalHook(_EvalHook): + """Single GPU EvalHook, with efficient test support. + + Args: + by_epoch (bool): Determine perform evaluation by epoch or by iteration. + If set to True, it will perform by epoch. Otherwise, by iteration. + Default: False. + ...
https://raw.githubusercontent.com/Mikubill/sd-webui-controlnet/HEAD/annotator/mmpkg/mmseg/core/evaluation/eval_hooks.py
Add docstrings to improve collaboration
# Copyright (c) OpenMMLab. All rights reserved. from __future__ import division import numpy as np from annotator.mmpkg.mmcv.image import rgb2bgr from annotator.mmpkg.mmcv.video import flowread from .image import imshow def flowshow(flow, win_name='', wait_time=0): flow = flowread(flow) flow_img = flow2rgb(...
--- +++ @@ -9,12 +9,31 @@ def flowshow(flow, win_name='', wait_time=0): + """Show optical flow. + + Args: + flow (ndarray or str): The optical flow to be displayed. + win_name (str): The window name. + wait_time (int): Value of waitKey param. + """ flow = flowread(flow) flow_...
https://raw.githubusercontent.com/Mikubill/sd-webui-controlnet/HEAD/annotator/mmpkg/mmcv/visualization/optflow.py
Add docstrings to improve code quality
import torch import torch.nn.functional as F from ..builder import PIXEL_SAMPLERS from .base_pixel_sampler import BasePixelSampler @PIXEL_SAMPLERS.register_module() class OHEMPixelSampler(BasePixelSampler): def __init__(self, context, thresh=None, min_kept=100000): super(OHEMPixelSampler, self).__init__...
--- +++ @@ -7,6 +7,18 @@ @PIXEL_SAMPLERS.register_module() class OHEMPixelSampler(BasePixelSampler): + """Online Hard Example Mining Sampler for segmentation. + + Args: + context (nn.Module): The context of sampler, subclass of + :obj:`BaseDecodeHead`. + thresh (float, optional): The t...
https://raw.githubusercontent.com/Mikubill/sd-webui-controlnet/HEAD/annotator/mmpkg/mmseg/core/seg/sampler/ohem_pixel_sampler.py
Add standardized docstrings across the file
import os.path as osp import tempfile import annotator.mmpkg.mmcv as mmcv import numpy as np from annotator.mmpkg.mmcv.utils import print_log from PIL import Image from .builder import DATASETS from .custom import CustomDataset @DATASETS.register_module() class CityscapesDataset(CustomDataset): CLASSES = ('roa...
--- +++ @@ -12,6 +12,11 @@ @DATASETS.register_module() class CityscapesDataset(CustomDataset): + """Cityscapes dataset. + + The ``img_suffix`` is fixed to '_leftImg8bit.png' and ``seg_map_suffix`` is + fixed to '_gtFine_labelTrainIds.png' for Cityscapes dataset. + """ CLASSES = ('road', 'sidewalk'...
https://raw.githubusercontent.com/Mikubill/sd-webui-controlnet/HEAD/annotator/mmpkg/mmseg/datasets/cityscapes.py
Write docstrings for this repository
# Copyright (c) OpenMMLab. All rights reserved. import torch from torch.nn.parallel.distributed import (DistributedDataParallel, _find_tensors) from annotator.mmpkg.mmcv import print_log from annotator.mmpkg.mmcv.utils import TORCH_VERSION, digit_version from .scatter_gather ...
--- +++ @@ -9,6 +9,14 @@ class MMDistributedDataParallel(DistributedDataParallel): + """The DDP module that supports DataContainer. + + MMDDP has two main differences with PyTorch DDP: + + - It supports a custom type :class:`DataContainer` which allows more + flexible control of input data. + - It ...
https://raw.githubusercontent.com/Mikubill/sd-webui-controlnet/HEAD/annotator/mmpkg/mmcv/parallel/distributed.py
Document this module using docstrings
import os import os.path as osp from collections import OrderedDict from functools import reduce import annotator.mmpkg.mmcv as mmcv import numpy as np from annotator.mmpkg.mmcv.utils import print_log from torch.utils.data import Dataset from annotator.mmpkg.mmseg.core import eval_metrics from annotator.mmpkg.mmseg.u...
--- +++ @@ -16,6 +16,56 @@ @DATASETS.register_module() class CustomDataset(Dataset): + """Custom dataset for semantic segmentation. An example of file structure + is as followed. + + .. code-block:: none + + ├── data + │ ├── my_dataset + │ │ ├── img_dir + │ │ │ ├── tr...
https://raw.githubusercontent.com/Mikubill/sd-webui-controlnet/HEAD/annotator/mmpkg/mmseg/datasets/custom.py
Insert docstrings into my code
from torch.utils.data.dataset import ConcatDataset as _ConcatDataset from .builder import DATASETS @DATASETS.register_module() class ConcatDataset(_ConcatDataset): def __init__(self, datasets): super(ConcatDataset, self).__init__(datasets) self.CLASSES = datasets[0].CLASSES self.PALETTE ...
--- +++ @@ -5,6 +5,14 @@ @DATASETS.register_module() class ConcatDataset(_ConcatDataset): + """A wrapper of concatenated dataset. + + Same as :obj:`torch.utils.data.dataset.ConcatDataset`, but + concat the group flag for image aspect ratio. + + Args: + datasets (list[:obj:`Dataset`]): A list of da...
https://raw.githubusercontent.com/Mikubill/sd-webui-controlnet/HEAD/annotator/mmpkg/mmseg/datasets/dataset_wrappers.py
Generate documentation strings for clarity
import collections from annotator.mmpkg.mmcv.utils import build_from_cfg from ..builder import PIPELINES @PIPELINES.register_module() class Compose(object): def __init__(self, transforms): assert isinstance(transforms, collections.abc.Sequence) self.transforms = [] for transform in tran...
--- +++ @@ -7,6 +7,12 @@ @PIPELINES.register_module() class Compose(object): + """Compose multiple transforms sequentially. + + Args: + transforms (Sequence[dict | callable]): Sequence of transform object or + config dict to be composed. + """ def __init__(self, transforms): ...
https://raw.githubusercontent.com/Mikubill/sd-webui-controlnet/HEAD/annotator/mmpkg/mmseg/datasets/pipelines/compose.py
Add professional docstrings to my codebase
import os.path as osp import annotator.mmpkg.mmcv as mmcv import numpy as np from ..builder import PIPELINES @PIPELINES.register_module() class LoadImageFromFile(object): def __init__(self, to_float32=False, color_type='color', file_client_args=dict(backend='d...
--- +++ @@ -8,6 +8,25 @@ @PIPELINES.register_module() class LoadImageFromFile(object): + """Load an image from file. + + Required keys are "img_prefix" and "img_info" (a dict that must contain the + key "filename"). Added or updated keys are "filename", "img", "img_shape", + "ori_shape" (same as `img_sha...
https://raw.githubusercontent.com/Mikubill/sd-webui-controlnet/HEAD/annotator/mmpkg/mmseg/datasets/pipelines/loading.py
Add concise docstrings to each method
import os.path as osp from .builder import DATASETS from .custom import CustomDataset @DATASETS.register_module() class PascalContextDataset(CustomDataset): CLASSES = ('background', 'aeroplane', 'bag', 'bed', 'bedclothes', 'bench', 'bicycle', 'bird', 'boat', 'book', 'bottle', 'building', 'bus', ...
--- +++ @@ -6,6 +6,16 @@ @DATASETS.register_module() class PascalContextDataset(CustomDataset): + """PascalContext dataset. + + In segmentation map annotation for PascalContext, 0 stands for background, + which is included in 60 categories. ``reduce_zero_label`` is fixed to + False. The ``img_suffix`` is...
https://raw.githubusercontent.com/Mikubill/sd-webui-controlnet/HEAD/annotator/mmpkg/mmseg/datasets/pascal_context.py
Write docstrings for backend logic
from collections.abc import Sequence import annotator.mmpkg.mmcv as mmcv import numpy as np import torch from annotator.mmpkg.mmcv.parallel import DataContainer as DC from ..builder import PIPELINES def to_tensor(data): if isinstance(data, torch.Tensor): return data elif isinstance(data, np.ndarray...
--- +++ @@ -9,6 +9,15 @@ def to_tensor(data): + """Convert objects of various python types to :obj:`torch.Tensor`. + + Supported types are: :class:`numpy.ndarray`, :class:`torch.Tensor`, + :class:`Sequence`, :class:`int` and :class:`float`. + + Args: + data (torch.Tensor | numpy.ndarray | Sequenc...
https://raw.githubusercontent.com/Mikubill/sd-webui-controlnet/HEAD/annotator/mmpkg/mmseg/datasets/pipelines/formating.py
Add docstrings to improve code quality
import annotator.mmpkg.mmcv as mmcv import numpy as np from annotator.mmpkg.mmcv.utils import deprecated_api_warning, is_tuple_of from numpy import random from ..builder import PIPELINES @PIPELINES.register_module() class Resize(object): def __init__(self, img_scale=None, multi...
--- +++ @@ -8,6 +8,35 @@ @PIPELINES.register_module() class Resize(object): + """Resize images & seg. + + This transform resizes the input image to some scale. If the input dict + contains the key "scale", then the scale in the input dict is used, + otherwise the specified scale in the init method is use...
https://raw.githubusercontent.com/Mikubill/sd-webui-controlnet/HEAD/annotator/mmpkg/mmseg/datasets/pipelines/transforms.py
Document this module using docstrings
import torch import torch.nn as nn from annotator.mmpkg.mmcv.cnn import (ConvModule, DepthwiseSeparableConvModule, constant_init, kaiming_init) from torch.nn.modules.batchnorm import _BatchNorm from annotator.mmpkg.mmseg.models.decode_heads.psp_head import PPM from annotator.mmpkg.mmseg.ops impor...
--- +++ @@ -11,6 +11,20 @@ class LearningToDownsample(nn.Module): + """Learning to downsample module. + + Args: + in_channels (int): Number of input channels. + dw_channels (tuple[int]): Number of output channels of the first and + the second depthwise conv (dwconv) layers. + o...
https://raw.githubusercontent.com/Mikubill/sd-webui-controlnet/HEAD/annotator/mmpkg/mmseg/models/backbones/fast_scnn.py
Add docstrings including usage examples
import torch import torch.nn as nn import torch.utils.checkpoint as cp from annotator.mmpkg.mmcv.cnn import (ConvModule, build_conv_layer, build_norm_layer, constant_init, kaiming_init) from annotator.mmpkg.mmcv.runner import load_checkpoint from annotator.mmpkg.mmcv.utils.parrots_wrapper import _...
--- +++ @@ -11,6 +11,17 @@ class GlobalContextExtractor(nn.Module): + """Global Context Extractor for CGNet. + + This class is employed to refine the joint feature of both local feature + and surrounding context. + + Args: + channel (int): Number of input feature channels. + reduction (int...
https://raw.githubusercontent.com/Mikubill/sd-webui-controlnet/HEAD/annotator/mmpkg/mmseg/models/backbones/cgnet.py
Replace inline comments with docstrings
import math from annotator.mmpkg.mmcv.cnn import build_conv_layer, build_norm_layer from ..builder import BACKBONES from ..utils import ResLayer from .resnet import Bottleneck as _Bottleneck from .resnet import ResNet class Bottleneck(_Bottleneck): def __init__(self, inplanes, ...
--- +++ @@ -9,6 +9,11 @@ class Bottleneck(_Bottleneck): + """Bottleneck block for ResNeXt. + + If style is "pytorch", the stride-two layer is the 3x3 conv layer, if it is + "caffe", the stride-two layer is the first 1x1 conv layer. + """ def __init__(self, inplanes, @@ -80,6 +85...
https://raw.githubusercontent.com/Mikubill/sd-webui-controlnet/HEAD/annotator/mmpkg/mmseg/models/backbones/resnext.py
Add docstrings to meet PEP guidelines
# Copyright (c) OpenMMLab. All rights reserved. import numbers from abc import ABCMeta, abstractmethod import numpy as np import torch from ..hook import Hook class LoggerHook(Hook): __metaclass__ = ABCMeta def __init__(self, interval=10, ignore_last=True, ...
--- +++ @@ -9,6 +9,15 @@ class LoggerHook(Hook): + """Base class for logger hooks. + + Args: + interval (int): Logging interval (every k iterations). + ignore_last (bool): Ignore the log of last iterations in each epoch + if less than `interval`. + reset_flag (bool): Whether to...
https://raw.githubusercontent.com/Mikubill/sd-webui-controlnet/HEAD/annotator/mmpkg/mmcv/runner/hooks/logger/base.py
Write proper docstrings for these functions
import math import torch import torch.nn as nn import torch.nn.functional as F import torch.utils.checkpoint as cp from annotator.mmpkg.mmcv.cnn import build_conv_layer, build_norm_layer from ..builder import BACKBONES from ..utils import ResLayer from .resnet import Bottleneck as _Bottleneck from .resnet import ResN...
--- +++ @@ -13,6 +13,12 @@ class RSoftmax(nn.Module): + """Radix Softmax module in ``SplitAttentionConv2d``. + + Args: + radix (int): Radix of input. + groups (int): Groups of input. + """ def __init__(self, radix, groups): super().__init__() @@ -31,6 +37,23 @@ class Split...
https://raw.githubusercontent.com/Mikubill/sd-webui-controlnet/HEAD/annotator/mmpkg/mmseg/models/backbones/resnest.py
Add docstrings to clarify complex logic
import math import torch import torch.nn as nn import torch.nn.functional as F import torch.utils.checkpoint as cp from annotator.mmpkg.mmcv.cnn import (Conv2d, Linear, build_activation_layer, build_norm_layer, constant_init, kaiming_init, normal_init) from annotator.mmpkg.mmcv.runner import _lo...
--- +++ @@ -1,3 +1,5 @@+"""Modified from https://github.com/rwightman/pytorch-image- +models/blob/master/timm/models/vision_transformer.py.""" import math @@ -16,6 +18,20 @@ class Mlp(nn.Module): + """MLP layer for Encoder block. + + Args: + in_features(int): Input dimension for the first fully + ...
https://raw.githubusercontent.com/Mikubill/sd-webui-controlnet/HEAD/annotator/mmpkg/mmseg/models/backbones/vit.py
Write beginner-friendly docstrings
import logging import torch.nn as nn from annotator.mmpkg.mmcv.cnn import ConvModule, constant_init, kaiming_init from annotator.mmpkg.mmcv.runner import load_checkpoint from torch.nn.modules.batchnorm import _BatchNorm from ..builder import BACKBONES from ..utils import InvertedResidual, make_divisible @BACKBONES....
--- +++ @@ -11,6 +11,31 @@ @BACKBONES.register_module() class MobileNetV2(nn.Module): + """MobileNetV2 backbone. + + Args: + widen_factor (float): Width multiplier, multiply number of + channels in each layer by this amount. Default: 1.0. + strides (Sequence[int], optional): Strides of...
https://raw.githubusercontent.com/Mikubill/sd-webui-controlnet/HEAD/annotator/mmpkg/mmseg/models/backbones/mobilenet_v2.py
Please document this code using docstrings
import math import torch import torch.distributed as dist import torch.nn as nn import torch.nn.functional as F from annotator.mmpkg.mmcv.cnn import ConvModule from ..builder import HEADS from .decode_head import BaseDecodeHead def reduce_mean(tensor): if not (dist.is_available() and dist.is_initialized()): ...
--- +++ @@ -11,6 +11,7 @@ def reduce_mean(tensor): + """Reduce mean when distributed training.""" if not (dist.is_available() and dist.is_initialized()): return tensor tensor = tensor.clone() @@ -19,6 +20,13 @@ class EMAModule(nn.Module): + """Expectation Maximization Attention Module u...
https://raw.githubusercontent.com/Mikubill/sd-webui-controlnet/HEAD/annotator/mmpkg/mmseg/models/decode_heads/ema_head.py