code stringlengths 17 6.64M |
|---|
class CSFI2(nn.Module):
'Cross-Scale Feature Integration between 1x and 2x features.\n\n Cross-Scale Feature Integration in Texture Transformer Network for\n Image Super-Resolution.\n It is cross-scale feature integration between 1x and 2x features.\n For example, `conv2to1` means conv layer f... |
class CSFI3(nn.Module):
'Cross-Scale Feature Integration between 1x, 2x, and 4x features.\n\n Cross-Scale Feature Integration in Texture Transformer Network for\n Image Super-Resolution.\n It is cross-scale feature integration between 1x and 2x features.\n For example, `conv2to1` means conv la... |
class MergeFeatures(nn.Module):
'Merge Features. Merge 1x, 2x, and 4x features.\n\n Final module of Texture Transformer Network for Image Super-Resolution.\n\n Args:\n mid_channels (int): Channel number of intermediate features\n out_channels (int): Number of channels in the output image\n ... |
@BACKBONES.register_module()
class TTSRNet(nn.Module):
"TTSR network structure (main-net) for reference-based super-resolution.\n\n Paper: Learning Texture Transformer Network for Image Super-Resolution\n\n Adapted from 'https://github.com/researchmm/TTSR.git'\n 'https://github.com/researchmm/TTSR'\n ... |
class BaseModel(nn.Module, metaclass=ABCMeta):
'Base model.\n\n All models should subclass it.\n All subclass should overwrite:\n\n ``init_weights``, supporting to initialize models.\n\n ``forward_train``, supporting to forward when training.\n\n ``forward_test``, supporting to forward ... |
def build(cfg, registry, default_args=None):
'Build module function.\n\n Args:\n cfg (dict): Configuration for building modules.\n registry (obj): ``registry`` object.\n default_args (dict, optional): Default arguments. Defaults to None.\n '
if isinstance(cfg, list):
modules... |
def build_backbone(cfg):
'Build backbone.\n\n Args:\n cfg (dict): Configuration for building backbone.\n '
return build(cfg, BACKBONES)
|
def build_component(cfg):
'Build component.\n\n Args:\n cfg (dict): Configuration for building component.\n '
return build(cfg, COMPONENTS)
|
def build_loss(cfg):
'Build loss.\n\n Args:\n cfg (dict): Configuration for building loss.\n '
return build(cfg, LOSSES)
|
def build_model(cfg, train_cfg=None, test_cfg=None):
'Build model.\n\n Args:\n cfg (dict): Configuration for building model.\n train_cfg (dict): Training configuration. Default: None.\n test_cfg (dict): Testing configuration. Default: None.\n '
return build(cfg, MODELS, dict(train_c... |
class ASPPPooling(nn.Sequential):
def __init__(self, in_channels, out_channels, conv_cfg, norm_cfg, act_cfg):
super().__init__(nn.AdaptiveAvgPool2d(1), ConvModule(in_channels, out_channels, 1, conv_cfg=conv_cfg, norm_cfg=norm_cfg, act_cfg=act_cfg))
def forward(self, x):
size = x.shape[(- 2):... |
class ASPP(nn.Module):
'ASPP module from DeepLabV3.\n\n The code is adopted from\n https://github.com/pytorch/vision/blob/master/torchvision/models/\n segmentation/deeplabv3.py\n\n For more information about the module:\n `"Rethinking Atrous Convolution for Semantic Image Segmentation"\n <https:... |
class ContextualAttentionModule(nn.Module):
'Contexture attention module.\n\n The details of this module can be found in:\n Generative Image Inpainting with Contextual Attention\n\n Args:\n unfold_raw_kernel_size (int): Kernel size used in unfolding raw\n feature. Default: 4.\n u... |
def pixel_unshuffle(x, scale):
'Down-sample by pixel unshuffle.\n\n Args:\n x (Tensor): Input tensor.\n scale (int): Scale factor.\n\n Returns:\n Tensor: Output tensor.\n '
(b, c, h, w) = x.shape
if (((h % scale) != 0) or ((w % scale) != 0)):
raise AssertionError(f'In... |
class SpatialTemporalEnsemble(nn.Module):
' Apply spatial and temporal ensemble and compute outputs\n\n Args:\n is_temporal_ensemble (bool, optional): Whether to apply ensemble\n temporally. If True, the sequence will also be flipped temporally.\n If the input is an image, this arg... |
class SimpleGatedConvModule(nn.Module):
'Simple Gated Convolutional Module.\n\n This module is a simple gated convolutional module. The detailed formula\n is:\n\n .. math::\n y = \\phi(conv1(x)) * \\sigma(conv2(x)),\n\n where `phi` is the feature activation function and `sigma` is the gate\n ... |
class GCAModule(nn.Module):
"Guided Contextual Attention Module.\n\n From https://arxiv.org/pdf/2001.04069.pdf.\n Based on https://github.com/nbei/Deep-Flow-Guided-Video-Inpainting.\n This module use image feature map to augment the alpha feature map with\n guided contextual attention score.\n\n Im... |
def generation_init_weights(module, init_type='normal', init_gain=0.02):
'Default initialization of network weights for image generation.\n\n By default, we use normal init, but xavier and kaiming might work\n better for some applications.\n\n Args:\n module (nn.Module): Module to be initialized.\... |
class GANImageBuffer():
'This class implements an image buffer that stores previously\n generated images.\n\n This buffer allows us to update the discriminator using a history of\n generated images rather than the ones produced by the latest generator\n to reduce model oscillation.\n\n Args:\n ... |
class UnetSkipConnectionBlock(nn.Module):
"Construct a Unet submodule with skip connections, with the following\n structure: downsampling - `submodule` - upsampling.\n\n Args:\n outer_channels (int): Number of channels at the outer conv layer.\n inner_channels (int): Number of channels at the ... |
class ResidualBlockWithDropout(nn.Module):
"Define a Residual Block with dropout layers.\n\n Ref:\n Deep Residual Learning for Image Recognition\n\n A residual block is a conv block with skip connections. A dropout layer is\n added between two common conv modules.\n\n Args:\n channels (int):... |
class ImgNormalize(nn.Conv2d):
'Normalize images with the given mean and std value.\n\n Based on Conv2d layer, can work in GPU.\n\n Args:\n pixel_range (float): Pixel range of feature.\n img_mean (Tuple[float]): Image mean of each channel.\n img_std (Tuple[float]): Image std of each cha... |
class LinearModule(nn.Module):
'A linear block that contains linear/norm/activation layers.\n\n For low level vision, we add spectral norm and padding layer.\n\n Args:\n in_features (int): Same as nn.Linear.\n out_features (int): Same as nn.Linear.\n bias (bool): Same as nn.Linear.\n ... |
class MaskConvModule(ConvModule):
'Mask convolution module.\n\n This is a simple wrapper for mask convolution like: \'partial conv\'.\n Convolutions in this module always need a mask as extra input.\n\n Args:\n in_channels (int): Same as nn.Conv2d.\n out_channels (int): Same as nn.Conv2d.\n... |
@CONV_LAYERS.register_module(name='PConv')
class PartialConv2d(nn.Conv2d):
'Implementation for partial convolution.\n\n Image Inpainting for Irregular Holes Using Partial Convolutions\n [https://arxiv.org/abs/1804.07723]\n\n Args:\n multi_channel (bool): If True, the mask is multi-channel. Otherwi... |
class DepthwiseSeparableConvModule(nn.Module):
"Depthwise separable convolution module.\n\n See https://arxiv.org/pdf/1704.04861.pdf for details.\n\n This module can replace a ConvModule with the conv block replaced by two\n conv block: depthwise conv block and pointwise conv block. The depthwise\n co... |
def default_init_weights(module, scale=1):
'Initialize network weights.\n\n Args:\n modules (nn.Module): Modules to be initialized.\n scale (float): Scale initialized weights, especially for residual\n blocks.\n '
for m in module.modules():
if isinstance(m, nn.Conv2d):
... |
def make_layer(block, num_blocks, **kwarg):
'Make layers by stacking the same blocks.\n\n Args:\n block (nn.module): nn.module class for basic block.\n num_blocks (int): number of blocks.\n\n Returns:\n nn.Sequential: Stacked blocks in nn.Sequential.\n '
layers = []
for _ in ... |
class ResidualBlockNoBN(nn.Module):
'Residual block without BN.\n\n It has a style of:\n\n ::\n\n ---Conv-ReLU-Conv-+-\n |________________|\n\n Args:\n mid_channels (int): Channel number of intermediate features.\n Default: 64.\n res_scale (float): Used to scale th... |
class PixelShufflePack(nn.Module):
' Pixel Shuffle upsample layer.\n\n Args:\n in_channels (int): Number of input channels.\n out_channels (int): Number of output channels.\n scale_factor (int): Upsample ratio.\n upsample_kernel (int): Kernel size of Conv layer to expand channels.\n... |
@COMPONENTS.register_module()
class DeepFillv1Discriminators(nn.Module):
'Discriminators used in DeepFillv1 model.\n\n In DeepFillv1 model, the discriminators are independent without any\n concatenation like Global&Local model. Thus, we call this model\n `DeepFillv1Discriminators`. There exist a global d... |
@COMPONENTS.register_module()
class GLDiscs(nn.Module):
'Discriminators in Global&Local\n\n This discriminator contains a local discriminator and a global\n discriminator as described in the original paper:\n Globally and locally Consistent Image Completion\n\n Args:\n global_disc_cfg (dict): C... |
class MaxFeature(nn.Module):
"Conv2d or Linear layer with max feature selector\n\n Generate feature maps with double channels, split them and select the max\n feature.\n\n Args:\n in_channels (int): Channel number of inputs.\n out_channels (int): Channel number of outputs.\n kern... |
@COMPONENTS.register_module()
class LightCNN(nn.Module):
'LightCNN discriminator with input size 128 x 128.\n\n It is used to train DICGAN.\n\n Args:\n in_channels (int): Channel number of inputs.\n '
def __init__(self, in_channels):
super().__init__()
self.features = nn.Seque... |
@COMPONENTS.register_module()
class ModifiedVGG(nn.Module):
'A modified VGG discriminator with input size 128 x 128.\n\n It is used to train SRGAN and ESRGAN.\n\n Args:\n in_channels (int): Channel number of inputs. Default: 3.\n mid_channels (int): Channel number of base intermediate features... |
@COMPONENTS.register_module()
class MultiLayerDiscriminator(nn.Module):
'Multilayer Discriminator.\n\n This is a commonly used structure with stacked multiply convolution layers.\n\n Args:\n in_channels (int): Input channel of the first input convolution.\n max_channels (int): The maximum chan... |
@COMPONENTS.register_module()
class PatchDiscriminator(nn.Module):
"A PatchGAN discriminator.\n\n Args:\n in_channels (int): Number of channels in input images.\n base_channels (int): Number of channels at the first conv layer.\n Default: 64.\n num_conv (int): Number of stacked ... |
@COMPONENTS.register_module()
class SoftMaskPatchDiscriminator(nn.Module):
"A Soft Mask-Guided PatchGAN discriminator.\n\n Args:\n in_channels (int): Number of channels in input images.\n base_channels (int, optional): Number of channels at the\n first conv layer. Default: 64.\n ... |
@COMPONENTS.register_module()
class TTSRDiscriminator(nn.Module):
'A discriminator for TTSR.\n\n Args:\n in_channels (int): Channel number of inputs. Default: 3.\n in_size (int): Size of input image. Default: 160.\n '
def __init__(self, in_channels=3, in_size=160):
super().__init_... |
@COMPONENTS.register_module()
class UNetDiscriminatorWithSpectralNorm(nn.Module):
'A U-Net discriminator with spectral normalization.\n\n Args:\n in_channels (int): Channel number of the input.\n mid_channels (int, optional): Channel number of the intermediate\n features. Default: 64.\... |
@COMPONENTS.register_module()
class DeepFillRefiner(nn.Module):
'Refiner used in DeepFill model.\n\n This implementation follows:\n Generative Image Inpainting with Contextual Attention.\n\n Args:\n encoder_attention (dict): Config dict for encoder used in branch\n with contextual atten... |
@COMPONENTS.register_module()
class MLPRefiner(nn.Module):
'Multilayer perceptrons (MLPs), refiner used in LIIF.\n\n Args:\n in_dim (int): Input dimension.\n out_dim (int): Output dimension.\n hidden_list (list[int]): List of hidden dimensions.\n '
def __init__(self, in_dim, out_di... |
@COMPONENTS.register_module()
class PlainRefiner(nn.Module):
'Simple refiner from Deep Image Matting.\n\n Args:\n conv_channels (int): Number of channels produced by the three main\n convolutional layer.\n loss_refine (dict): Config of the loss of the refiner. Default: None.\n p... |
def get_module_device(module):
'Get the device of a module.\n\n Args:\n module (nn.Module): A module contains the parameters.\n\n Returns:\n torch.device: The device of the module.\n '
try:
next(module.parameters())
except StopIteration:
raise ValueError('The input m... |
@torch.no_grad()
def get_mean_latent(generator, num_samples=4096, bs_per_repeat=1024):
'Get mean latent of W space in Style-based GANs.\n Args:\n generator (nn.Module): Generator of a Style-based GAN.\n num_samples (int, optional): Number of sample times. Defaults to 4096.\n bs_per_repeat ... |
@torch.no_grad()
def style_mixing(generator, n_source, n_target, inject_index=1, truncation_latent=None, truncation=0.7, style_channels=512, **kwargs):
device = get_module_device(generator)
source_code = torch.randn(n_source, style_channels).to(device)
target_code = torch.randn(n_target, style_channels).t... |
@COMPONENTS.register_module()
class LTE(nn.Module):
"Learnable Texture Extractor\n\n Based on pretrained VGG19. Generate features in 3 levels.\n\n Args:\n requires_grad (bool): Require grad or not. Default: True.\n pixel_range (float): Pixel range of geature. Default: 1.\n pretrained (s... |
@MODELS.register_module()
class AOTInpaintor(OneStageInpaintor):
'Inpaintor for AOT-GAN method.\n\n This inpaintor is implemented according to the paper:\n Aggregated Contextual Transformations for High-Resolution Image Inpainting\n '
def forward_train_d(self, data_batch, is_real, is_disc, mask):
... |
@MODELS.register_module()
class DeepFillv1Inpaintor(TwoStageInpaintor):
def get_module(self, model, module_name):
'Get an inner module from model.\n\n Since we will wrapper DDP for some model, we have to judge whether the\n module can be indexed directly.\n\n Args:\n model... |
@MODELS.register_module()
class GLInpaintor(OneStageInpaintor):
'Inpaintor for global&local method.\n\n This inpaintor is implemented according to the paper:\n Globally and Locally Consistent Image Completion\n\n Importantly, this inpaintor is an example for using custom training\n schedule based on `... |
@LOSSES.register_module()
class L1CompositionLoss(nn.Module):
"L1 composition loss.\n\n Args:\n loss_weight (float): Loss weight for L1 loss. Default: 1.0.\n reduction (str): Specifies the reduction to apply to the output.\n Supported choices are 'none' | 'mean' | 'sum'. Default: 'mean... |
@LOSSES.register_module()
class MSECompositionLoss(nn.Module):
"MSE (L2) composition loss.\n\n Args:\n loss_weight (float): Loss weight for MSE loss. Default: 1.0.\n reduction (str): Specifies the reduction to apply to the output.\n Supported choices are 'none' | 'mean' | 'sum'. Defaul... |
@LOSSES.register_module()
class CharbonnierCompLoss(nn.Module):
"Charbonnier composition loss.\n\n Args:\n loss_weight (float): Loss weight for L1 loss. Default: 1.0.\n reduction (str): Specifies the reduction to apply to the output.\n Supported choices are 'none' | 'mean' | 'sum'. Def... |
class LightCNNFeature(nn.Module):
'Feature of LightCNN.\n\n It is used to train DICGAN.\n '
def __init__(self) -> None:
super().__init__()
model = LightCNN(3)
self.features = nn.Sequential(*list(model.features.children()))
self.features.requires_grad_(False)
def for... |
@LOSSES.register_module()
class LightCNNFeatureLoss(nn.Module):
"Feature loss of DICGAN, based on LightCNN.\n\n Args:\n pretrained (str): Path for pretrained weights.\n loss_weight (float): Loss weight. Default: 1.0.\n criterion (str): Criterion type. Options are 'l1' and 'mse'.\n ... |
@LOSSES.register_module()
class GANLoss(nn.Module):
"Define GAN loss.\n\n Args:\n gan_type (str): Support 'vanilla', 'lsgan', 'wgan', 'hinge'.\n real_label_val (float): The value for real label. Default: 1.0.\n fake_label_val (float): The value for fake label. Default: 0.0.\n loss_w... |
@LOSSES.register_module()
class GaussianBlur(nn.Module):
'A Gaussian filter which blurs a given tensor with a two-dimensional\n gaussian kernel by convolving it along each channel. Batch operation\n is supported.\n\n This function is modified from kornia.filters.gaussian:\n `<https://kornia.readthedoc... |
def gradient_penalty_loss(discriminator, real_data, fake_data, mask=None):
'Calculate gradient penalty for wgan-gp.\n\n Args:\n discriminator (nn.Module): Network for the discriminator.\n real_data (Tensor): Real input data.\n fake_data (Tensor): Fake input data.\n mask (Tensor): Ma... |
@LOSSES.register_module()
class GradientPenaltyLoss(nn.Module):
'Gradient penalty loss for wgan-gp.\n\n Args:\n loss_weight (float): Loss weight. Default: 1.0.\n '
def __init__(self, loss_weight=1.0):
super().__init__()
self.loss_weight = loss_weight
def forward(self, discri... |
@LOSSES.register_module()
class DiscShiftLoss(nn.Module):
'Disc shift loss.\n\n Args:\n loss_weight (float, optional): Loss weight. Defaults to 1.0.\n '
def __init__(self, loss_weight=0.1):
super().__init__()
self.loss_weight = loss_weight
def forward(self, x):
... |
@LOSSES.register_module()
class GradientLoss(nn.Module):
"Gradient loss.\n\n Args:\n loss_weight (float): Loss weight for L1 loss. Default: 1.0.\n reduction (str): Specifies the reduction to apply to the output.\n Supported choices are 'none' | 'mean' | 'sum'. Default: 'mean'.\n "
... |
class PerceptualVGG(nn.Module):
"VGG network used in calculating perceptual loss.\n\n In this implementation, we allow users to choose whether use normalization\n in the input feature and the type of vgg network. Note that the pretrained\n path must fit the vgg type.\n\n Args:\n layer_name_list... |
@LOSSES.register_module()
class PerceptualLoss(nn.Module):
"Perceptual loss with commonly used style loss.\n\n Args:\n layers_weights (dict): The weight for each layer of vgg feature for\n perceptual loss. Here is an example: {'4': 1., '9': 1., '18': 1.},\n which means the 5th, 10t... |
@LOSSES.register_module()
class TransferalPerceptualLoss(nn.Module):
"Transferal perceptual loss.\n\n Args:\n loss_weight (float): Loss weight. Default: 1.0.\n use_attention (bool): If True, use soft-attention tensor. Default: True\n criterion (str): Criterion type. Options are 'l1' and 'm... |
def reduce_loss(loss, reduction):
'Reduce loss as specified.\n\n Args:\n loss (Tensor): Elementwise loss tensor.\n reduction (str): Options are "none", "mean" and "sum".\n\n Returns:\n Tensor: Reduced loss tensor.\n '
reduction_enum = F._Reduction.get_enum(reduction)
if (redu... |
def mask_reduce_loss(loss, weight=None, reduction='mean', sample_wise=False):
'Apply element-wise weight and reduce loss.\n\n Args:\n loss (Tensor): Element-wise loss.\n weight (Tensor): Element-wise weights. Default: None.\n reduction (str): Same as built-in losses of PyTorch. Options are... |
def masked_loss(loss_func):
"Create a masked version of a given loss function.\n\n To use this decorator, the loss function must have the signature like\n `loss_func(pred, target, **kwargs)`. The function only needs to compute\n element-wise loss without any reduction. This decorator will add weight\n ... |
@MODELS.register_module()
class GCA(BaseMattor):
'Guided Contextual Attention image matting model.\n\n https://arxiv.org/abs/2001.04069\n\n Args:\n backbone (dict): Config of backbone.\n train_cfg (dict): Config of training. In ``train_cfg``,\n ``train_backbone`` should be specified... |
@MODELS.register_module()
class IndexNet(BaseMattor):
"IndexNet matting model.\n\n This implementation follows:\n Indices Matter: Learning to Index for Deep Image Matting\n\n Args:\n backbone (dict): Config of backbone.\n train_cfg (dict): Config of training. In 'train_cfg', 'train_backbone... |
@MODELS.register_module()
class BasicRestorer(BaseModel):
'Basic model for image restoration.\n\n It must contain a generator that takes an image as inputs and outputs a\n restored image. It also has a pixel-wise loss for training.\n\n The subclasses should overwrite the function `forward_train`,\n `f... |
@MODELS.register_module()
class DIC(BasicRestorer):
'DIC model for Face Super-Resolution.\n\n Paper: Deep Face Super-Resolution with Iterative Collaboration between\n Attentive Recovery and Landmark Estimation.\n\n Args:\n generator (dict): Config for the generator.\n pixel_loss (dict):... |
@MODELS.register_module()
class EDVR(BasicRestorer):
'EDVR model for video super-resolution.\n\n EDVR: Video Restoration with Enhanced Deformable Convolutional Networks.\n\n Args:\n generator (dict): Config for the generator structure.\n pixel_loss (dict): Config for pixel-wise loss.\n ... |
@MODELS.register_module()
class ESRGAN(SRGAN):
'Enhanced SRGAN model for single image super-resolution.\n\n Ref:\n ESRGAN: Enhanced Super-Resolution Generative Adversarial Networks.\n It uses RaGAN for GAN updates:\n The relativistic discriminator: a key element missing from standard GAN.\n\n Args:... |
@MODELS.register_module()
class GLEAN(SRGAN):
'GLEAN model for single image super-resolution.\n\n This model is identical to SRGAN except that the output images are\n transformed from [-1, 1] to [0, 1].\n\n Paper:\n GLEAN: Generative Latent Bank for Large-Factor Image Super-Resolution.\n CVPR, 2021... |
@MODELS.register_module()
class LIIF(BasicRestorer):
'LIIF model for single image super-resolution.\n\n Paper: Learning Continuous Image Representation with\n Local Implicit Image Function\n\n Args:\n generator (dict): Config for the generator.\n pixel_loss (dict): Config for the pix... |
@MODELS.register_module()
class MFQEv2Restorer(BasicRestorer):
'MFQEv2 model for video quality enhancement.\n\n Args:\n generator (dict): Config for the generator structure.\n pixel_loss (dict): Config for pixel-wise loss.\n train_cfg (dict): Config for training. Default: None.\n te... |
@MODELS.register_module()
class RealBasicVSR(RealESRGAN):
'RealBasicVSR model for real-world video super-resolution.\n\n Ref:\n Investigating Tradeoffs in Real-World Video Super-Resolution, arXiv\n\n Args:\n generator (dict): Config for the generator.\n discriminator (dict, optional): Confi... |
@MODELS.register_module()
class RealESRGAN(SRGAN):
'Real-ESRGAN model for single image super-resolution.\n\n Ref:\n Real-ESRGAN: Training Real-World Blind Super-Resolution with Pure\n Synthetic Data, 2021.\n\n Args:\n generator (dict): Config for the generator.\n discriminator (dict, opt... |
@MODELS.register_module()
class SRGAN(BasicRestorer):
'SRGAN model for single image super-resolution.\n\n Ref:\n Photo-Realistic Single Image Super-Resolution Using a Generative\n Adversarial Network.\n\n Args:\n generator (dict): Config for the generator.\n discriminator (dict): Config ... |
@MODELS.register_module()
class STDF(BasicRestorer):
'STDF model for video restoration.\n\n It must contain a generator that takes an image as inputs and outputs a\n restored image. It also has a pixel-wise loss for training.\n\n The subclasses should overwrite the function `forward_train`,\n `forward... |
@MODELS.register_module()
class TTSR(BasicRestorer):
'TTSR model for Reference-based Image Super-Resolution.\n\n Paper: Learning Texture Transformer Network for Image Super-Resolution.\n\n Args:\n generator (dict): Config for the generator.\n extractor (dict): Config for the extractor.\n ... |
@MODELS.register_module()
class CycleGAN(BaseModel):
'CycleGAN model for unpaired image-to-image translation.\n\n Ref:\n Unpaired Image-to-Image Translation using Cycle-Consistent Adversarial\n Networks\n\n Args:\n generator (dict): Config for the generator.\n discriminator (dict): Confi... |
@MODELS.register_module()
class Pix2Pix(BaseModel):
'Pix2Pix model for paired image-to-image translation.\n\n Ref:\n Image-to-Image Translation with Conditional Adversarial Networks\n\n Args:\n generator (dict): Config for the generator.\n discriminator (dict): Config for the discriminator.... |
@COMPONENTS.register_module()
class SearchTransformer(nn.Module):
'Search texture reference by transformer.\n\n Include relevance embedding, hard-attention and soft-attention.\n\n '
def gather(self, inputs, dim, index):
'Hard Attention. Gathers values along an axis specified by dim.\n\n ... |
@MODELS.register_module()
class CAIN(BasicInterpolator):
'CAIN model for Video Interpolation.\n\n Paper: Channel Attention Is All You Need for Video Frame Interpolation\n Ref repo: https://github.com/myungsub/CAIN\n\n Args:\n generator (dict): Config for the generator structure.\n pixel_los... |
def modify_args():
for (i, v) in enumerate(sys.argv):
if (i == 0):
assert v.endswith('.py')
elif re.match('--\\w+_.*', v):
new_arg = v.replace('_', '-')
warnings.warn(f'command line argument {v} is deprecated, please use {new_arg} instead.', category=Deprecation... |
def collect_env():
'Collect the information of the running environments.'
env_info = collect_base_env()
env_info['MMEditing'] = f'{mmedit.__version__}+{get_git_hash()[:7]}'
return env_info
|
def get_root_logger(log_file=None, log_level=logging.INFO):
'Get the root logger.\n\n The logger will be initialized if it has not been initialized. By default a\n StreamHandler will be added. If `log_file` is specified, a FileHandler will\n also be added. The name of the root logger is the top-level pac... |
def setup_multi_processes(cfg):
'Setup multi-processing environment variables.'
if (platform.system() != 'Windows'):
mp_start_method = cfg.get('mp_start_method', 'fork')
current_method = mp.get_start_method(allow_none=True)
if ((current_method is not None) and (current_method != mp_sta... |
def parse_version_info(version_str):
ver_info = []
for x in version_str.split('.'):
if x.isdigit():
ver_info.append(int(x))
elif (x.find('rc') != (- 1)):
patch_version = x.split('rc')
ver_info.append(int(patch_version[0]))
ver_info.append(f'rc{pa... |
def readme():
with open('README.md', encoding='utf-8') as f:
content = f.read()
return content
|
def get_git_hash():
def _minimal_ext_cmd(cmd):
env = {}
for k in ['SYSTEMROOT', 'PATH', 'HOME']:
v = os.environ.get(k)
if (v is not None):
env[k] = v
env['LANGUAGE'] = 'C'
env['LANG'] = 'C'
env['LC_ALL'] = 'C'
out = subproces... |
def get_hash():
if os.path.exists('.git'):
sha = get_git_hash()[:7]
elif os.path.exists(version_file):
try:
from mmedit.version import __version__
sha = __version__.split('+')[(- 1)]
except ImportError:
raise ImportError('Unable to get git version')
... |
def get_version():
with open(version_file, 'r') as f:
exec(compile(f.read(), version_file, 'exec'))
return locals()['__version__']
|
def parse_requirements(fname='requirements.txt', with_version=True):
'Parse the package dependencies listed in a requirements file but strips\n specific versioning information.\n\n Args:\n fname (str): path to requirements file\n with_version (bool, default=False): if True include version spec... |
def add_mim_extention():
'Add extra files that are required to support MIM into the package.\n\n These files will be added by creating a symlink to the originals if the\n package is installed in `editable` mode (e.g. pip install -e .), or by\n copying from the originals otherwise.\n '
if ('develop... |
class TestGenerationDatasets():
@classmethod
def setup_class(cls):
cls.data_prefix = (Path(__file__).parent.parent.parent / 'data')
def test_base_generation_dataset(self):
class ToyDataset(BaseGenerationDataset):
'Toy dataset for testing Generation Dataset.'
def... |
class TestMattingDatasets():
@classmethod
def setup_class(cls):
cls.data_prefix = (Path(__file__).parent.parent.parent / 'data')
cls.ann_file = osp.join(cls.data_prefix, 'test_list.json')
cls.pipeline = [dict(type='LoadImageFromFile', key='alpha', flag='grayscale')]
def test_comp... |
def test_repeat_dataset():
class ToyDataset(Dataset):
def __init__(self):
super().__init__()
self.members = [1, 2, 3, 4, 5]
def __len__(self):
return len(self.members)
def __getitem__(self, idx):
return self.members[(idx % 5)]
toy_dat... |
def mock_open(*args, **kwargs):
"unittest.mock_open wrapper.\n\n unittest.mock_open doesn't support iteration. Wrap it to fix this bug.\n Reference: https://stackoverflow.com/a/41656192\n "
import unittest
f_open = unittest.mock.mock_open(*args, **kwargs)
f_open.return_value.__iter__ = (lambd... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.