instruction
stringclasses
100 values
code
stringlengths
78
193k
response
stringlengths
259
170k
file
stringlengths
59
203
Insert docstrings into my code
from collections import OrderedDict from dataclasses import dataclass, replace from functools import partial from typing import Any, Callable, Dict, Optional, Tuple import torch import torch.nn as nn from timm.data import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD from timm.layers import ClassifierHead, DropPath, ca...
--- +++ @@ -1,3 +1,21 @@+""" Normalization Free Nets. NFNet, NF-RegNet, NF-ResNet (pre-activation) Models + +Paper: `Characterizing signal propagation to close the performance gap in unnormalized ResNets` + - https://arxiv.org/abs/2101.08692 + +Paper: `High-Performance Large-Scale Image Recognition Without Normaliza...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/models/nfnet.py
Add concise docstrings to each method
# PiT # Copyright 2021-present NAVER Corp. # Apache License v2.0 import math import re from functools import partial from typing import List, Optional, Sequence, Tuple, Union, Type, Any import torch from torch import nn from timm.data import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD from timm.layers import trunc_n...
--- +++ @@ -1,3 +1,12 @@+""" Pooling-based Vision Transformer (PiT) in PyTorch + +A PyTorch implement of Pooling-based Vision Transformers as described in +'Rethinking Spatial Dimensions of Vision Transformers' - https://arxiv.org/abs/2103.16302 + +This code was adapted from the original version at https://github.com/n...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/models/pit.py
Improve my code by adding docstrings
import math from functools import partial from typing import Any, Dict, List, Optional, Tuple, Type, Union import torch import torch.nn as nn import torch.nn.functional as F from timm.data import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD from timm.layers import DropBlock2d, DropPath, AvgPool2dSame, BlurPool2d, Laye...
--- +++ @@ -1,3 +1,12 @@+"""PyTorch ResNet + +This started as a copy of https://github.com/pytorch/vision 'resnet.py' (BSD-3-Clause) with +additional dropout and dynamic global avg/max pool. + +ResNeXt, SE-ResNeXt, SENet, and MXNet Gluon stem/downsample variants, tiered stems added by Ross Wightman + +Copyright 2019, R...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/models/resnet.py
Add docstrings to improve collaboration
import math from typing import List, Optional, Tuple, Union, Type, Any import torch import torch.nn as nn from timm.data import IMAGENET_INCEPTION_MEAN, IMAGENET_INCEPTION_STD from timm.layers import Mlp, DropPath, calculate_drop_path_rates, trunc_normal_, _assert, to_2tuple, resample_abs_pos_embed from ._builder imp...
--- +++ @@ -1,3 +1,14 @@+""" Transformer in Transformer (TNT) in PyTorch + +A PyTorch implement of TNT as described in +'Transformer in Transformer' - https://arxiv.org/abs/2103.00112 + +The official mindspore code is released and available at +https://gitee.com/mindspore/mindspore/tree/master/model_zoo/research/cv/TNT...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/models/tnt.py
Annotate my code with docstrings
import math from typing import Callable, List, Optional, Tuple, Union, Type, Any import torch import torch.nn as nn import torch.nn.functional as F from timm.data import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD from timm.layers import DropPath, calculate_drop_path_rates, to_2tuple, to_ntuple, trunc_normal_, Layer...
--- +++ @@ -1,3 +1,19 @@+""" Pyramid Vision Transformer v2 + +@misc{wang2021pvtv2, + title={PVTv2: Improved Baselines with Pyramid Vision Transformer}, + author={Wenhai Wang and Enze Xie and Xiang Li and Deng-Ping Fan and Kaitao Song and Ding Liang and + Tong Lu and Ping Luo and Ling Shao}, + year...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/models/pvt_v2.py
Write docstrings for backend logic
from typing import Any, Dict, List, Optional, Type, Union, cast import torch import torch.nn as nn import torch.nn.functional as F from timm.data import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD from timm.layers import ClassifierHead from ._builder import build_model_with_cfg from ._features_fx import register_notr...
--- +++ @@ -1,3 +1,10 @@+"""VGG + +Adapted from https://github.com/pytorch/vision 'vgg.py' (BSD-3-Clause) with a few changes for +timm functionality. + +Copyright 2021 Ross Wightman +""" from typing import Any, Dict, List, Optional, Type, Union, cast import torch @@ -23,6 +30,10 @@ @register_notrace_module # rea...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/models/vgg.py
Add docstrings to incomplete code
from typing import List, Optional, Tuple, Union, Type import torch import torch.nn as nn from timm.data import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD from timm.layers import ConvNormAct, SeparableConvNormAct, BatchNormAct2d, ClassifierHead, DropPath, \ create_attn, create_norm_act_layer, calculate_drop_path...
--- +++ @@ -1,3 +1,15 @@+""" VoVNet (V1 & V2) + +Papers: +* `An Energy and GPU-Computation Efficient Backbone Network` - https://arxiv.org/abs/1904.09730 +* `CenterMask : Real-Time Anchor-Free Instance Segmentation` - https://arxiv.org/abs/1911.06667 + +Looked at https://github.com/youngwanLEE/vovnet-detectron2 & +htt...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/models/vovnet.py
Add concise docstrings to each method
from collections import OrderedDict from functools import partial from typing import Type import torch import torch.nn as nn from timm.layers import ConvNormAct, create_conv2d, create_pool2d, create_classifier from ._builder import build_model_with_cfg from ._registry import register_model, generate_default_cfgs __a...
--- +++ @@ -1,3 +1,10 @@+""" + pnasnet5large implementation grabbed from Cadene's pretrained models + Additional credit to https://github.com/creafz + + https://github.com/Cadene/pretrained-models.pytorch/blob/master/pretrainedmodels/models/pnasnet.py + +""" from collections import OrderedDict from functools import p...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/models/pnasnet.py
Add return value explanations in docstrings
__all__ = ['TinyVit'] import itertools from functools import partial from typing import Dict, List, Optional, Tuple, Union, Type, Any import torch import torch.nn as nn import torch.nn.functional as F from timm.data import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD from timm.layers import LayerNorm2d, NormMlpClass...
--- +++ @@ -1,3 +1,10 @@+""" TinyViT + +Paper: `TinyViT: Fast Pretraining Distillation for Small Vision Transformers` + - https://arxiv.org/abs/2207.10666 + +Adapted from official impl at https://github.com/microsoft/Cream/tree/main/TinyViT +""" __all__ = ['TinyVit'] @@ -288,10 +295,12 @@ return x ...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/models/tiny_vit.py
Replace inline comments with docstrings
import torch.jit import torch.nn as nn import torch.nn.functional as F from typing import Optional from timm.layers import create_classifier from ._builder import build_model_with_cfg from ._registry import register_model, generate_default_cfgs, register_model_deprecations __all__ = ['Xception'] class SeparableConv...
--- +++ @@ -1,3 +1,26 @@+""" +Ported to pytorch thanks to [tstandley](https://github.com/tstandley/Xception-PyTorch) + +@author: tstandley +Adapted by cadene + +Creates an Xception Model as defined in: + +Francois Chollet +Xception: Deep Learning with Depthwise Separable Convolutions +https://arxiv.org/pdf/1610.02357.p...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/models/xception.py
Add docstrings for utility scripts
# Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
--- +++ @@ -1,3 +1,20 @@+"""Pre-Activation ResNet v2 with GroupNorm and Weight Standardization. + +A PyTorch implementation of ResNetV2 adapted from the Google Big-Transfer (BiT) source code +at https://github.com/google-research/big_transfer to match timm interfaces. The BiT weights have +been included here as pretrai...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/models/resnetv2.py
Generate descriptive docstrings automatically
from typing import Optional, Type from torch import nn from timm.data import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD from timm.layers import SplitAttn from ._builder import build_model_with_cfg from ._registry import register_model, generate_default_cfgs from .resnet import ResNet class ResNestBottleneck(nn.Mod...
--- +++ @@ -1,3 +1,11 @@+""" ResNeSt Models + +Paper: `ResNeSt: Split-Attention Networks` - https://arxiv.org/abs/2004.08955 + +Adapted from original PyTorch impl w/ weights at https://github.com/zhanghang1989/ResNeSt by Hang Zhang + +Modified for torchscript compat, and consistency with timm by Ross Wightman +""" fro...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/models/resnest.py
Write docstrings that follow conventions
import fnmatch import logging from itertools import islice from typing import Collection, Optional from torch import nn as nn from timm.models import group_parameters _logger = logging.getLogger(__name__) def _matches_pattern(name: str, patterns: Collection[str]) -> bool: return any(fnmatch.fnmatch(name, patt...
--- +++ @@ -12,6 +12,7 @@ def _matches_pattern(name: str, patterns: Collection[str]) -> bool: + """Check if parameter name matches any pattern (supports wildcards).""" return any(fnmatch.fnmatch(name, pattern) for pattern in patterns) @@ -110,6 +111,10 @@ no_opt_scale: Optional[float] = None, ...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/optim/_param_groups.py
Add docstrings to meet PEP guidelines
import math from typing import Optional, Type import torch import torch.nn as nn from timm.data import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD from ._builder import build_model_with_cfg from ._registry import register_model, generate_default_cfgs from .resnet import ResNet __all__ = [] class Bottle2neck(nn.Mod...
--- +++ @@ -1,3 +1,7 @@+""" Res2Net and Res2NeXt +Adapted from Official Pytorch impl at: https://github.com/gasvn/Res2Net/ +Paper: `Res2Net: A New Multi-scale Backbone Architecture` - https://arxiv.org/abs/1904.01169 +""" import math from typing import Optional, Type @@ -13,6 +17,9 @@ class Bottle2neck(nn.Modul...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/models/res2net.py
Write docstrings for data processing functions
from typing import List, Optional, Tuple, Union, Type import torch import torch.nn as nn from timm.data import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD from timm.layers import SqueezeExcite, trunc_normal_, to_ntuple, to_2tuple from ._builder import build_model_with_cfg from ._features import feature_take_indices f...
--- +++ @@ -1,3 +1,19 @@+""" RepViT + +Paper: `RepViT: Revisiting Mobile CNN From ViT Perspective` + - https://arxiv.org/abs/2307.09283 + +@misc{wang2023repvit, + title={RepViT: Revisiting Mobile CNN From ViT Perspective}, + author={Ao Wang and Hui Chen and Zijia Lin and Hengjun Pu and Guiguang Ding}, + ...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/models/repvit.py
Create Google-style docstrings for my code
from functools import partial from math import ceil from typing import Any, Dict, List, Optional, Tuple, Type, Union import torch import torch.nn as nn from timm.data import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD from timm.layers import ClassifierHead, create_act_layer, ConvNormAct, DropPath, make_divisible, SE...
--- +++ @@ -1,3 +1,14 @@+""" ReXNet + +A PyTorch impl of `ReXNet: Diminishing Representational Bottleneck on Convolutional Neural Network` - +https://arxiv.org/abs/2007.00992 + +Adapted from original impl at https://github.com/clovaai/rexnet +Copyright (c) 2020-present NAVER Corp. MIT license + +Changes for timm, featu...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/models/rexnet.py
Document my Python code with docstrings
import logging from dataclasses import dataclass from functools import partial from typing import Any, Callable, Collection, Dict, List, Optional, Set, Tuple, Type, Union from fnmatch import fnmatch import importlib import torch import torch.nn as nn import torch.optim from ._param_groups import param_groups_layer_de...
--- +++ @@ -1,3 +1,7 @@+""" Optimizer Factory w/ custom Weight Decay & Layer Decay support + +Hacked together by / Copyright 2021 Ross Wightman +""" import logging from dataclasses import dataclass from functools import partial @@ -40,6 +44,7 @@ def _import_class(class_string: str) -> Type: + """Dynamically i...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/optim/_optim_factory.py
Annotate my code with docstrings
import math from dataclasses import dataclass, replace from functools import partial from typing import Any, Callable, Dict, List, Optional, Union, Tuple, Type import torch import torch.nn as nn from timm.data import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD from timm.layers import ClassifierHead, AvgPool2dSame, Co...
--- +++ @@ -1,3 +1,28 @@+"""RegNet X, Y, Z, and more + +Paper: `Designing Network Design Spaces` - https://arxiv.org/abs/2003.13678 +Original Impl: https://github.com/facebookresearch/pycls/blob/master/pycls/models/regnet.py + +Paper: `Fast and Accurate Model Scaling` - https://arxiv.org/abs/2103.06877 +Original Impl: ...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/models/regnet.py
Write docstrings that follow conventions
import math from typing import List, Optional, Tuple import torch from torch import Tensor from torch.optim.optimizer import Optimizer from ._types import ParamsT class AdamWLegacy(Optimizer): def __init__( self, params: ParamsT, lr: float = 1e-3, betas: Tuple[fl...
--- +++ @@ -1,3 +1,12 @@+""" AdamW Optimizer +Impl copied from PyTorch master + +References for added functionality: + Cautious Optimizers: https://arxiv.org/abs/2411.16085 + Why Gradients Rapidly Increase Near the End of Training: https://arxiv.org/abs/2506.02285 + +NOTE: This impl has been deprecated in favour ...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/optim/adamw.py
Add docstrings to improve code quality
import copy from functools import partial from typing import List, Optional, Tuple, Union, Type import torch import torch.nn as nn import torch.nn.functional as F from timm.data import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD from timm.layers import SelectAdaptivePool2d, Linear, make_divisible from ._builder impor...
--- +++ @@ -1,3 +1,9 @@+""" +An implementation of RepGhostNet Model as defined in: +RepGhost: A Hardware-Efficient Ghost Module via Re-parameterization. https://arxiv.org/abs/2211.06088 + +Original implementation: https://github.com/ChengpengChen/RepGhost +""" import copy from functools import partial from typing im...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/models/repghost.py
Add docstrings explaining edge cases
import math from collections import OrderedDict from typing import Type, Optional, Tuple import torch import torch.nn as nn import torch.nn.functional as F from timm.data import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD from timm.layers import create_classifier from ._builder import build_model_with_cfg from ._regi...
--- +++ @@ -1,3 +1,16 @@+""" +SEResNet implementation from Cadene's pretrained models +https://github.com/Cadene/pretrained-models.pytorch/blob/master/pretrainedmodels/models/senet.py +Additional credit to https://github.com/creafz + +Original model: https://github.com/hujie-frank/SENet + +ResNet code gently borrowed f...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/models/senet.py
Add docstrings for production code
# Copyright (c) 2022. Yuki Tatsunami # Licensed under the Apache License, Version 2.0 (the "License"); import math from functools import partial from itertools import accumulate from typing import List, Optional, Tuple, Type, Union import torch import torch.nn as nn from timm.data import IMAGENET_DEFAULT_MEAN, IMA...
--- +++ @@ -1,3 +1,8 @@+""" Sequencer + +Paper: `Sequencer: Deep LSTM for Image Classification` - https://arxiv.org/pdf/2205.01972.pdf + +""" # Copyright (c) 2022. Yuki Tatsunami # Licensed under the Apache License, Version 2.0 (the "License"); @@ -465,6 +470,7 @@ def checkpoint_filter_fn(state_dict, model): ...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/models/sequencer.py
Generate missing documentation strings
from typing import cast, List, Optional, Tuple, Union import torch from torch import Tensor from torch.optim.optimizer import Optimizer from ._types import ParamsT __all__ = ["Adopt", "adopt"] def _view_as_real(params, *state_and_grads): for i, p in enumerate(params): if torch.is_complex(p): ...
--- +++ @@ -1,3 +1,20 @@+""" ADOPT PyTorch Optimizer + +ADOPT: Modified Adam Can Converge with Any β2 with the Optimal Rate: https://arxiv.org/abs/2411.02853 + +Modified for reduced dependencies on PyTorch internals from original at: https://github.com/iShohei220/adopt + +@inproceedings{taniguchi2024adopt, + author={Ta...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/optim/adopt.py
Add docstrings for production code
from typing import List, Type import torch import torch.nn as nn from timm.data import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD from timm.layers import create_classifier from ._builder import build_model_with_cfg from ._registry import register_model, generate_default_cfgs __all__ = ['SelecSls'] # model_registry...
--- +++ @@ -1,3 +1,14 @@+"""PyTorch SelecSLS Net example for ImageNet Classification +License: CC BY 4.0 (https://creativecommons.org/licenses/by/4.0/legalcode) +Author: Dushyant Mehta (@mehtadushy) + +SelecSLS (core) Network Architecture as proposed in "XNect: Real-time Multi-person 3D +Human Pose Estimation with a Si...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/models/selecsls.py
Add docstrings to improve code quality
import torch from torch.optim.optimizer import Optimizer class Lars(Optimizer): def __init__( self, params, lr=1.0, momentum=0, dampening=0, weight_decay=0, nesterov=False, trust_coeff=0.001, eps=1e-8, trust_clip=False, alway...
--- +++ @@ -1,8 +1,36 @@+""" PyTorch LARS / LARC Optimizer + +An implementation of LARS (SGD) + LARC in PyTorch + +Based on: + * PyTorch SGD: https://github.com/pytorch/pytorch/blob/1.7/torch/optim/sgd.py#L100 + * NVIDIA APEX LARC: https://github.com/NVIDIA/apex/blob/master/apex/parallel/LARC.py + +Additional cleanup...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/optim/lars.py
Create documentation for each function signature
from typing import List, Optional, Tuple, Union import torch from torch import Tensor from torch.optim import Optimizer from ._types import ParamsT def _get_scalar_dtype(): return torch.float64 def _factored_dims( shape: Tuple[int, ...], factored: bool, min_dim_size_to_factor: int ) ->...
--- +++ @@ -1,3 +1,15 @@+""" Adafactor (Big Vision variant) for PyTorch + +Adapted from the implementation in big vision: https://github.com/google-research/big_vision + +Described in 'Scaling Vision Transformers': https://arxiv.org/abs/2106.04560 + +References for added functionality: + Cautious Optimizers: https:/...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/optim/adafactor_bv.py
Add standardized docstrings across the file
# Copyright (c) 2024 Bytedance Ltd. and/or its affiliates # SPDX-License-Identifier: Apache-2.0 import math from typing import Optional, Tuple import torch from torch.optim.optimizer import Optimizer from ._types import ParamsT def _mars_single_tensor_step( p: torch.Tensor, grad: torch.Tensor, ...
--- +++ @@ -1,3 +1,16 @@+""" PyTorch MARS Optimizer + +Code simplified from https://github.com/AGI-Arena/MARS + +Paper: MARS: Unleashing the Power of Variance Reduction for Training Large Models - https://arxiv.org/abs/2411.10438 + +@article{yuan2024mars, + title={MARS: Unleashing the Power of Variance Reduction for T...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/optim/mars.py
Add docstrings following best practices
from typing import Tuple from torch.optim import Optimizer import torch from ._types import ParamsT class LaProp(Optimizer): def __init__( self, params: ParamsT, lr: float = 4e-4, betas: Tuple[float, float] = (0.9, 0.999), eps: float = 1e-15, ...
--- +++ @@ -1,3 +1,21 @@+""" PyTorch impl of LaProp optimizer + +Code simplified from https://github.com/Z-T-WANG/LaProp-Optimizer, MIT License + +Paper: LaProp: Separating Momentum and Adaptivity in Adam, https://arxiv.org/abs/2002.04839 + +@article{ziyin2020laprop, + title={LaProp: a Better Way to Combine Momentum w...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/optim/laprop.py
Auto-generate documentation strings for this file
import torch class Adahessian(torch.optim.Optimizer): def __init__( self, params, lr=0.1, betas=(0.9, 0.999), eps=1e-8, weight_decay=0.0, hessian_power=1.0, update_each=1, n_samples=1, avg_conv...
--- +++ @@ -1,7 +1,27 @@+""" AdaHessian Optimizer + +Lifted from https://github.com/davda54/ada-hessian/blob/master/ada_hessian.py +Originally licensed MIT, Copyright 2020, David Samuel +""" import torch class Adahessian(torch.optim.Optimizer): + """ + Implements the AdaHessian algorithm from "ADAHESSIAN: A...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/optim/adahessian.py
Turn comments into proper docstrings
# Copyright 2021 Sea Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing,...
--- +++ @@ -1,3 +1,11 @@+""" Vision OutLOoker (VOLO) implementation + +Paper: `VOLO: Vision Outlooker for Visual Recognition` - https://arxiv.org/abs/2106.13112 + +Code adapted from official impl at https://github.com/sail-sg/volo, original copyright in comment below + +Modifications and additions for timm by / Copyrig...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/models/volo.py
Fully document this Python code with docstrings
# -------------------------------------------------------- # Swin Transformer V2 # Copyright (c) 2022 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by Ze Liu # -------------------------------------------------------- import math from functools import partial from typing import Any, Call...
--- +++ @@ -1,3 +1,11 @@+""" Swin Transformer V2 +A PyTorch impl of : `Swin Transformer V2: Scaling Up Capacity and Resolution` + - https://arxiv.org/abs/2111.09883 + +Code/weights from https://github.com/microsoft/Swin-Transformer, original copyright/license info below + +Modifications and additions for timm hacked...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/models/swin_transformer_v2.py
Create Google-style docstrings for my code
import math import torch from torch.optim.optimizer import Optimizer class AdaBelief(Optimizer): def __init__( self, params, lr=1e-3, betas=(0.9, 0.999), eps=1e-16, weight_decay=0, amsgrad=False, decoupled_decay=True,...
--- +++ @@ -4,6 +4,40 @@ class AdaBelief(Optimizer): + r"""Implements AdaBelief algorithm. Modified from Adam in PyTorch + + Arguments: + params (iterable): iterable of parameters to optimize or dicts defining + parameter groups + lr (float, optional): learning rate (default: 1e-3) + ...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/optim/adabelief.py
Add docstrings with type hints explained
import math from typing import List, Optional, Tuple import torch from torch import Tensor from ._types import ParamsT # Modified from github.com/pytorch/pytorch/blob/v1.12.1/torch/optim/adamw.py. class NAdamW(torch.optim.Optimizer): def __init__( self, params: ParamsT, lr: ...
--- +++ @@ -1,3 +1,13 @@+""" NAdamW Optimizer + +Based on simplified algorithm in https://github.com/mlcommons/algorithmic-efficiency/tree/main/baselines/nadamw + +Added multi-tensor (foreach) path. + +References for added functionality: + Cautious Optimizers: https://arxiv.org/abs/2411.16085 + Why Gradients Rapi...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/optim/nadamw.py
Generate docstrings for script automation
import logging from functools import partial from typing import Callable, List, Optional, Tuple, Type, Union import torch import torch.nn as nn import torch.nn.functional as F from timm.data import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD, IMAGENET_INCEPTION_MEAN, IMAGENET_INCEPTION_STD from timm.layers import ( ...
--- +++ @@ -1,3 +1,14 @@+""" Vision Transformer (ViT) in PyTorch + +A PyTorch implement of Vision Transformers as described in: + +'Exploring Plain Vision Transformer Backbones for Object Detection' + - https://arxiv.org/abs/2203.16527 + +'Segment Anything Model (SAM)' + - https://github.com/facebookresearch/segm...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/models/vision_transformer_sam.py
Add docstrings to improve collaboration
import math from dataclasses import dataclass, field from functools import partial from typing import Optional, Union, Tuple import torch import torch.nn as nn from timm.data import OPENAI_CLIP_MEAN, OPENAI_CLIP_STD from timm.layers import create_act_layer, get_norm_layer, get_norm_act_layer, create_conv2d, \ ma...
--- +++ @@ -1,3 +1,23 @@+""" ViTamin + +Paper: Designing Scalable Vison Models in the Vision-Language Era +A family of model weights on Huggingface: https://huggingface.co/collections/jienengchen/vitamin-family-661048126b72debdaca060bf + +@inproceedings{chen2024vitamin, + title={ViTamin: Designing Scalable Vision Mode...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/models/vitamin.py
Help me document legacy Python code
from typing import List, Optional import torch from torch import Tensor from torch.optim.optimizer import Optimizer try: from torch.optim.optimizer import _use_grad_for_differentiable, _default_to_fused_or_foreach has_recent_pt = True except ImportError: has_recent_pt = False from ._types import ParamsT ...
--- +++ @@ -1,3 +1,11 @@+""" SGD with decoupled weight-decay. + +References for added functionality: + Cautious Optimizers: https://arxiv.org/abs/2411.16085 + Why Gradients Rapidly Increase Near the End of Training: https://arxiv.org/abs/2506.02285 + +Hacked together by Ross Wightman +""" from typing import List...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/optim/sgdw.py
Add well-formatted docstrings
import torch from torch.optim import Optimizer from ._types import ParamsT class RMSpropTF(Optimizer): def __init__( self, params: ParamsT, lr: float = 1e-2, alpha: float = 0.9, eps: float = 1e-10, weight_decay: float = 0, mome...
--- +++ @@ -1,3 +1,15 @@+""" RMSProp modified to behave like Tensorflow impl + +Originally cut & paste from PyTorch RMSProp +https://github.com/pytorch/pytorch/blob/063946d2b3f3f1e953a2a3b54e0b34f1393de295/torch/optim/rmsprop.py +Licensed under BSD-Clause 3 (ish), https://github.com/pytorch/pytorch/blob/master/LICENSE ...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/optim/rmsprop_tf.py
Add minimal docstrings for each function
import torch from typing import Any, Dict, List, Optional, Tuple, Union from .scheduler import Scheduler class PlateauLRScheduler(Scheduler): def __init__( self, optimizer: torch.optim.Optimizer, decay_rate: float = 0.1, patience_t: int = 10, threshold...
--- +++ @@ -1,3 +1,9 @@+""" Plateau Scheduler + +Adapts PyTorch plateau scheduler and allows application of noise, warmup. + +Hacked together by / Copyright 2020 Ross Wightman +""" import torch from typing import Any, Dict, List, Optional, Tuple, Union @@ -5,6 +11,7 @@ class PlateauLRScheduler(Scheduler): + ...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/scheduler/plateau_lr.py
Add well-formatted docstrings
import logging import numbers from typing import List, Mapping, Optional, Sequence, Tuple, Union import torch try: from torch.distributed.tensor import DTensor has_dtensor = True except ImportError: has_dtensor = False from ._types import ParamsT from .adamw import adamw from .nadamw import nadamw _logge...
--- +++ @@ -1,3 +1,25 @@+""" Muon Optimizer + +Improved Muon optimizer implementation with flexible handling of high-dimensional tensors. + +Combines PyTorch-style structure with options for: +- Batched spatial processing for convolutions in addition to flatten +- Optional spatial normalization +- Selectable coefficien...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/optim/muon.py
Add docstrings to my Python code
from functools import partial from typing import Dict, Tuple, Type, Union import torch import torch.nn as nn from timm.data import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD from timm.layers import StdConv2dSame, StdConv2d, ConvNormAct, to_ntuple, HybridEmbed from ._builder import build_model_with_cfg from ._regist...
--- +++ @@ -1,3 +1,18 @@+""" Hybrid Vision Transformer (ViT) in PyTorch + +A PyTorch implement of the Hybrid Vision Transformers as described in: + +'An Image Is Worth 16 x 16 Words: Transformers for Image Recognition at Scale' + - https://arxiv.org/abs/2010.11929 + +`How to train your ViT? Data, Augmentation, and R...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/models/vision_transformer_hybrid.py
Add docstrings to improve readability
# Copyright (c) 2015-present, Facebook, Inc. # All rights reserved. import math from functools import partial from typing import List, Optional, Tuple, Union, Type, Any import torch import torch.nn as nn from timm.data import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD from timm.layers import DropPath, trunc_normal_...
--- +++ @@ -1,3 +1,13 @@+""" Cross-Covariance Image Transformer (XCiT) in PyTorch + +Paper: + - https://arxiv.org/abs/2106.09681 + +Same as the official implementation, with some minor adaptations, original copyright below + - https://github.com/facebookresearch/xcit/blob/master/xcit.py + +Modifications and addit...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/models/xcit.py
Help me comply with documentation standards
import torch from torch.optim.optimizer import Optimizer import math class NvNovoGrad(Optimizer): def __init__( self, params, lr=1e-3, betas=(0.95, 0.98), eps=1e-8, weight_decay=0, grad_averaging=False, amsgrad=False...
--- +++ @@ -1,3 +1,9 @@+""" Nvidia NovoGrad Optimizer. +Original impl by Nvidia from Jasper example: + - https://github.com/NVIDIA/DeepLearningExamples/blob/master/PyTorch/SpeechRecognition/Jasper +Paper: `Stochastic Gradient Methods with Layer-wise Adaptive Moments for Training of Deep Networks` + - https://arxi...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/optim/nvnovograd.py
Add concise docstrings to each method
import math import logging from typing import List, Tuple, Union import torch from .scheduler import Scheduler _logger = logging.getLogger(__name__) class PolyLRScheduler(Scheduler): def __init__( self, optimizer: torch.optim.Optimizer, t_initial: int, power: f...
--- +++ @@ -1,3 +1,9 @@+""" Polynomial Scheduler + +Polynomial LR schedule with warmup, noise. + +Hacked together by / Copyright 2021 Ross Wightman +""" import math import logging from typing import List, Tuple, Union @@ -11,6 +17,10 @@ class PolyLRScheduler(Scheduler): + """ Polynomial LR Scheduler w/ warmup...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/scheduler/poly_lr.py
Fill in missing docstrings in my code
# -------------------------------------------------------- # Swin Transformer # Copyright (c) 2021 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by Ze Liu # -------------------------------------------------------- import logging import math from typing import Any, Dict, Callable, List, ...
--- +++ @@ -1,3 +1,14 @@+""" Swin Transformer +A PyTorch impl of : `Swin Transformer: Hierarchical Vision Transformer using Shifted Windows` + - https://arxiv.org/pdf/2103.14030 + +Code/weights from https://github.com/microsoft/Swin-Transformer, original copyright/license info below + +S3 (AutoFormerV2, https://arxi...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/models/swin_transformer.py
Add docstrings including usage examples
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import math from typing import Optional, Tuple import torch from ._types import ParamsT class Adafactor(torch.optim.Optimizer): def __...
--- +++ @@ -1,3 +1,11 @@+""" Adafactor Optimizer + +Lifted from https://github.com/pytorch/fairseq/blob/master/fairseq/optim/adafactor.py + +Modified by Ross Wightman to fix some issues with factorization dims for non nn.Linear layers + +Original header/copyright below. +""" # Copyright (c) Facebook, Inc. and its affi...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/optim/adafactor.py
Document all endpoints with docstrings
import logging import math import numpy as np import torch from typing import Tuple, List, Union from .scheduler import Scheduler _logger = logging.getLogger(__name__) class CosineLRScheduler(Scheduler): def __init__( self, optimizer: torch.optim.Optimizer, t_initial: int, ...
--- +++ @@ -1,3 +1,9 @@+""" Cosine Scheduler + +Cosine LR schedule with warmup, cycle/restarts, noise, k-decay. + +Hacked together by / Copyright 2021 Ross Wightman +""" import logging import math import numpy as np @@ -11,6 +17,15 @@ class CosineLRScheduler(Scheduler): + """ + Cosine decay with restarts. ...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/scheduler/cosine_lr.py
Create Google-style docstrings for my code
import logging import math from functools import partial from typing import List, Optional, Tuple, Type, Union try: from typing import Literal except ImportError: from typing_extensions import Literal import torch import torch.nn as nn from torch.jit import Final from timm.data import IMAGENET_INCEPTION_MEAN...
--- +++ @@ -1,3 +1,9 @@+""" Relative Position Vision Transformer (ViT) in PyTorch + +NOTE: these models are experimental / WIP, expect changes + +Hacked together by / Copyright 2022, Ross Wightman +""" import logging import math from functools import partial @@ -220,6 +226,14 @@ class VisionTransformerRelPos(nn....
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/models/vision_transformer_relpos.py
Write docstrings describing functionality
import logging import string import random import warnings from typing import Any, Callable, Dict, Optional, Tuple, Union import numpy as np import torch try: # NOTE opt_einsum needed to avoid blowing up memory with einsum ops import opt_einsum import torch.backends.opt_einsum torch.backends.opt_einsum...
--- +++ @@ -1,3 +1,28 @@+""" PyTorch Implementation of the Kron (PSGD) optimizer + +This is a PSGD optimizer using a Kronecker-factored preconditioner. + +This impl was adapted from https://github.com/evanatyourservice/kron_torch +by Evan Walters, licensed CC-BY-4.0. + +Contributions to above also made by +* Lucas Nest...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/optim/kron.py
Generate missing documentation strings
# -------------------------------------------------------- # Swin Transformer V2 reimplementation # Copyright (c) 2021 Christoph Reich # Licensed under The MIT License [see LICENSE for details] # Written by Christoph Reich # -------------------------------------------------------- import logging import math from functo...
--- +++ @@ -1,3 +1,26 @@+""" Swin Transformer V2 + +A PyTorch impl of : `Swin Transformer V2: Scaling Up Capacity and Resolution` + - https://arxiv.org/pdf/2111.09883 + +Code adapted from https://github.com/ChristophReich1996/Swin-Transformer-V2, original copyright/license info below + +This implementation is experi...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/models/swin_transformer_v2_cr.py
Add return value explanations in docstrings
# Copyright 2022 Garena Online Private Limited # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agre...
--- +++ @@ -1,3 +1,10 @@+""" Adan Optimizer + +Adan: Adaptive Nesterov Momentum Algorithm for Faster Optimizing Deep Models[J]. arXiv preprint arXiv:2208.06677, 2022. + https://arxiv.org/abs/2208.06677 + +Implementation adapted from https://github.com/sail-sg/Adan +""" # Copyright 2022 Garena Online Private Limited...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/optim/adan.py
Write docstrings describing functionality
import math import torch from torch.optim.optimizer import Optimizer class NAdamLegacy(Optimizer): def __init__( self, params, lr=2e-3, betas=(0.9, 0.999), eps=1e-8, weight_decay=0, schedule_decay=4e-3, ): if not 0.0...
--- +++ @@ -5,6 +5,29 @@ class NAdamLegacy(Optimizer): + """Implements Nadam algorithm (a variant of Adam based on Nesterov momentum). + + NOTE: This impl has been deprecated in favour of torch.optim.NAdam and remains as a reference + + It has been proposed in `Incorporating Nesterov Momentum into Adam`__....
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/optim/nadam.py
Create documentation for each function signature
# Copyright 2023 Google Research. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law...
--- +++ @@ -1,3 +1,11 @@+""" Lion Optimizer +Paper: `Symbolic Discovery of Optimization Algorithms` - https://arxiv.org/abs/2302.06675 +Original Impl: https://github.com/google/automl/tree/master/lion + +References for added functionality: + Cautious Optimizers: https://arxiv.org/abs/2411.16085 + Why Gradients Ra...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/optim/lion.py
Can you add docstrings to this Python file?
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import math from typing import TYPE_CHECKING, Any, Callable, Optional import torch import torch.optim if TYPE_CHECKING: from torch.optim...
--- +++ @@ -1,3 +1,9 @@+""" PyTorch MADGRAD optimizer + +MADGRAD: https://arxiv.org/abs/2101.11075 + +Code from: https://github.com/facebookresearch/madgrad +""" # Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the @@ -16,6 +22,35 @@ class MADGRAD...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/optim/madgrad.py
Generate docstrings for script automation
import re from typing import Any, Dict, List, Optional, Set, Tuple, Type, Union import torch import torch.nn as nn import torch.nn.functional as F from timm.data import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD from timm.layers import DropPath, Linear, LayerType, to_2tuple, trunc_normal_ from ._builder import build...
--- +++ @@ -1,3 +1,15 @@+"""SwiftFormer +SwiftFormer: Efficient Additive Attention for Transformer-based Real-time Mobile Vision Applications +Code: https://github.com/Amshaker/SwiftFormer +Paper: https://arxiv.org/pdf/2303.15446 + +@InProceedings{Shaker_2023_ICCV, + author = {Shaker, Abdelrahman and Maaz, Muhamm...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/models/swiftformer.py
Add docstrings explaining edge cases
from functools import partial from typing import List, Dict, Type, Optional import torch import torch.nn as nn from timm.data import IMAGENET_INCEPTION_MEAN, IMAGENET_INCEPTION_STD from timm.layers import ClassifierHead, ConvNormAct, DropPath, PadType, create_conv2d, get_norm_act_layer from timm.layers.helpers import...
--- +++ @@ -1,3 +1,10 @@+"""Pytorch impl of Aligned Xception 41, 65, 71 + +This is a correct, from scratch impl of Aligned Xception (Deeplab) models compatible with TF weights at +https://github.com/tensorflow/models/blob/master/research/deeplab/g3doc/model_zoo.md + +Hacked together by / Copyright 2020 Ross Wightman +"...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/models/xception_aligned.py
Write beginner-friendly docstrings
import math import torch from torch.optim.optimizer import Optimizer class RAdamLegacy(Optimizer): def __init__( self, params, lr=1e-3, betas=(0.9, 0.999), eps=1e-8, weight_decay=0, ): defaults = dict( lr=lr, ...
--- +++ @@ -1,9 +1,19 @@+"""RAdam Optimizer. +Implementation lifted from: https://github.com/LiyuanLucasLiu/RAdam +Paper: `On the Variance of the Adaptive Learning Rate and Beyond` - https://arxiv.org/abs/1908.03265 + +NOTE: This impl has been deprecated in favour of torch.optim.RAdam and remains as a reference +""" i...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/optim/radam.py
Add docstrings for production code
# Copyright (c) 2021, Habana Labs Ltd. All rights reserved. # Copyright (c) 2019-2020, NVIDIA CORPORATION. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # htt...
--- +++ @@ -1,3 +1,23 @@+""" PyTorch Lamb optimizer w/ behaviour similar to NVIDIA FusedLamb + +This optimizer code was adapted from the following (starting with latest) +* https://github.com/HabanaAI/Model-References/blob/2b435114fe8e31f159b1d3063b8280ae37af7423/PyTorch/nlp/bert/pretraining/lamb.py +* https://github.c...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/optim/lamb.py
Add docstrings to make code maintainable
from typing import List, Optional, Union from torch.optim import Optimizer from .cosine_lr import CosineLRScheduler from .multistep_lr import MultiStepLRScheduler from .plateau_lr import PlateauLRScheduler from .poly_lr import PolyLRScheduler from .step_lr import StepLRScheduler from .tanh_lr import TanhLRScheduler ...
--- +++ @@ -1,3 +1,6 @@+""" Scheduler Factory +Hacked together by / Copyright 2021 Ross Wightman +""" from typing import List, Optional, Union from torch.optim import Optimizer @@ -11,6 +14,9 @@ def scheduler_kwargs(cfg, decreasing_metric: Optional[bool] = None): + """ cfg/argparse to kwargs helper + Conv...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/scheduler/scheduler_factory.py
Add docstrings for production code
import logging from typing import Callable, Dict, Optional, Union import torch import torch.nn as nn from .task import TrainingTask _logger = logging.getLogger(__name__) class ClassificationTask(TrainingTask): def __init__( self, model: nn.Module, criterion: Union[nn.Module...
--- +++ @@ -1,3 +1,4 @@+"""Classification training task.""" import logging from typing import Callable, Dict, Optional, Union @@ -10,6 +11,23 @@ class ClassificationTask(TrainingTask): + """Standard supervised classification task. + + Simple task that performs a forward pass through the model and computes...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/task/classification.py
Write proper docstrings for these functions
import fnmatch from copy import deepcopy import torch from torchvision.ops.misc import FrozenBatchNorm2d from timm.layers import BatchNormAct2d, SyncBatchNormAct, FrozenBatchNormAct2d,\ freeze_batch_norm_2d, unfreeze_batch_norm_2d from .model_ema import ModelEma def unwrap_model(model): if isinstance(model,...
--- +++ @@ -1,3 +1,7 @@+""" Model / state_dict utils + +Hacked together by / Copyright 2020 Ross Wightman +""" import fnmatch from copy import deepcopy @@ -26,18 +30,40 @@ def avg_sq_ch_mean(model, input, output): + """ calculate average channel square mean of output activations + """ return torch.me...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/utils/model.py
Write docstrings that follow conventions
import logging from typing import Dict, Optional, Union import torch import torch.nn as nn import torch.nn.functional as F from timm.models import create_model from timm.utils import unwrap_model from .task import TrainingTask _logger = logging.getLogger(__name__) class TokenDistillationTeacher(nn.Module): d...
--- +++ @@ -1,3 +1,4 @@+"""Token-based distillation training task for models with distillation heads.""" import logging from typing import Dict, Optional, Union @@ -14,6 +15,23 @@ class TokenDistillationTeacher(nn.Module): + """Wrapper for a teacher model used in token-based distillation. + + Creates and ...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/task/token_distillation.py
Add detailed documentation for each class
import logging from typing import Dict, Optional, Tuple, Union import torch import torch.nn as nn import torch.nn.functional as F from timm.models import create_model from timm.utils import unwrap_model from .task import TrainingTask _logger = logging.getLogger(__name__) class DistillationTeacher(nn.Module): ...
--- +++ @@ -1,3 +1,4 @@+"""Knowledge distillation training tasks and components.""" import logging from typing import Dict, Optional, Tuple, Union @@ -15,6 +16,23 @@ class DistillationTeacher(nn.Module): + """Wrapper for a teacher model used in knowledge distillation. + + Creates and manages a pre-trained...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/task/distillation.py
Add docstrings that explain inputs and outputs
import argparse import ast import re def natural_key(string_): return [int(s) if s.isdigit() else s for s in re.split(r'(\d+)', string_.lower())] def add_bool_arg(parser, name, default=False, help=''): dest_name = name.replace('-', '_') group = parser.add_mutually_exclusive_group(required=False) gro...
--- +++ @@ -1,9 +1,14 @@+""" Misc utils + +Hacked together by / Copyright 2020 Ross Wightman +""" import argparse import ast import re def natural_key(string_): + """See http://www.codinghorror.com/blog/archives/001018.html""" return [int(s) if s.isdigit() else s for s in re.split(r'(\d+)', string_.lowe...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/utils/misc.py
Create docstrings for each class method
from typing import Dict, Optional import torch import torch.nn as nn class TrainingTask(nn.Module): def __init__( self, device: Optional[torch.device] = None, dtype: Optional[torch.dtype] = None, verbose: bool = True, ): super().__init__() self...
--- +++ @@ -1,3 +1,9 @@+"""Base training task abstraction. + +This module provides the base TrainingTask class that encapsulates a complete +forward pass including loss computation. Tasks return a dictionary with loss +components and outputs for logging. +""" from typing import Dict, Optional import torch @@ -5,6 +...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/task/task.py
Improve documentation using docstrings
import logging import math import numpy as np import torch from typing import List, Tuple, Union from .scheduler import Scheduler _logger = logging.getLogger(__name__) class TanhLRScheduler(Scheduler): def __init__( self, optimizer: torch.optim.Optimizer, t_initial: int, ...
--- +++ @@ -1,3 +1,9 @@+""" TanH Scheduler + +TanH schedule with warmup, cycle/restarts, noise. + +Hacked together by / Copyright 2021 Ross Wightman +""" import logging import math import numpy as np @@ -11,6 +17,10 @@ class TanhLRScheduler(Scheduler): + """ + Hyberbolic-Tangent decay with restarts. + T...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/scheduler/tanh_lr.py
Write reusable docstrings
import logging from collections import OrderedDict from copy import deepcopy from typing import Optional import torch import torch.nn as nn _logger = logging.getLogger(__name__) class ModelEma: def __init__(self, model, decay=0.9999, device='', resume=''): # make a copy of the model for accumulating mov...
--- +++ @@ -1,3 +1,7 @@+""" Exponential Moving Average (EMA) of model updates + +Hacked together by / Copyright 2020 Ross Wightman +""" import logging from collections import OrderedDict from copy import deepcopy @@ -10,6 +14,27 @@ class ModelEma: + """ Model Exponential Moving Average (DEPRECATED) + + Kee...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/utils/model_ema.py
Document this code for team use
import abc from abc import ABC from typing import Any, Dict, List, Optional, Tuple, Union import torch class Scheduler(ABC): def __init__( self, optimizer: torch.optim.Optimizer, param_group_field: str, t_in_epochs: bool = True, noise_range_t: Union[Li...
--- +++ @@ -6,6 +6,23 @@ class Scheduler(ABC): + """ Parameter Scheduler Base Class + A scheduler base class that can be used to schedule any optimizer parameter groups. + + Unlike the builtin PyTorch schedulers, this is intended to be consistently called + * At the END of each epoch, before incrementin...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/scheduler/scheduler.py
Create Google-style docstrings for my code
class AverageMeter: def __init__(self): self.reset() def reset(self): self.val = 0 self.avg = 0 self.sum = 0 self.count = 0 def update(self, val, n=1): self.val = val self.sum += val * n self.count += n self.avg = self.sum / self.co...
--- +++ @@ -1,6 +1,11 @@+""" Eval metrics and related + +Hacked together by / Copyright 2020 Ross Wightman +""" class AverageMeter: + """Computes and stores the average and current value""" def __init__(self): self.reset() @@ -18,9 +23,10 @@ def accuracy(output, target, topk=(1,)): + """C...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/utils/metrics.py
Write documentation strings for class attributes
# Copyright (c) 2021, NVIDIA CORPORATION & AFFILIATES. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this sof...
--- +++ @@ -6,6 +6,7 @@ # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. +"""Generate images using pretrained network pickle.""" import os import re @@ -22,6 +23,10 @@ #------------------------------------------------...
https://raw.githubusercontent.com/XingangPan/DragGAN/HEAD/gen_images.py
Create structured documentation for my script
# Copyright (c) 2021, NVIDIA CORPORATION & AFFILIATES. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this sof...
--- +++ @@ -6,6 +6,7 @@ # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. +"""Miscellaneous utility classes and functions.""" import ctypes import fnmatch @@ -37,6 +38,7 @@ class EasyDict(dict): + """Convenience...
https://raw.githubusercontent.com/XingangPan/DragGAN/HEAD/dnnlib/util.py
Add detailed docstrings explaining each function
import math import torch from torch.nn import functional as F def init_weights(m, mean=0.0, std=0.01): classname = m.__class__.__name__ if classname.find("Conv") != -1: m.weight.data.normal_(mean, std) def get_padding(kernel_size, dilation=1): return int((kernel_size * dilation - dilation) / 2) ...
--- +++ @@ -26,6 +26,7 @@ def kl_divergence(m_p, logs_p, m_q, logs_q): + """KL(P||Q)""" kl = (logs_q - logs_p) - 0.5 kl += ( 0.5 * (torch.exp(2.0 * logs_p) + ((m_p - m_q) ** 2)) * torch.exp(-2.0 * logs_q) @@ -34,6 +35,7 @@ def rand_gumbel(shape): + """Sample from the Gumbel distribution...
https://raw.githubusercontent.com/myshell-ai/OpenVoice/HEAD/openvoice/commons.py
Add docstrings for internal functions
import gradio as gr import numpy as np from PIL import Image, ImageDraw class ImageMask(gr.components.Image): is_template = True def __init__(self, **kwargs): super().__init__(source="upload", tool="sketch", interactive=False, ...
--- +++ @@ -4,6 +4,9 @@ class ImageMask(gr.components.Image): + """ + Sets: source="canvas", tool="sketch" + """ is_template = True @@ -28,6 +31,8 @@ def get_valid_mask(mask: np.ndarray): + """Convert mask from gr.Image(0 to 255, RGBA) to binary mask. + """ if mask.ndim == 3: ...
https://raw.githubusercontent.com/XingangPan/DragGAN/HEAD/gradio_utils/utils.py
Add docstrings to improve code quality
import os import torch def set_jit_legacy(): # assert hasattr(torch._C, '_jit_set_profiling_executor'), "Old JIT behavior doesn't exist!" torch._C._jit_set_profiling_executor(False) torch._C._jit_set_profiling_mode(False) torch._C._jit_override_can_fuse_on_gpu(True) #torch._C._jit_set_texpr_f...
--- +++ @@ -1,9 +1,17 @@+""" JIT scripting/tracing utils + +Hacked together by / Copyright 2020 Ross Wightman +""" import os import torch def set_jit_legacy(): + """ Set JIT executor to legacy w/ support for op fusion + This is hopefully a temporary need in 1.5/1.5.1/1.6 to restore performance due to cha...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/utils/jit.py
Add docstrings following best practices
import math import torch from torch import nn from torch.nn import functional as F from openvoice import commons import logging logger = logging.getLogger(__name__) class LayerNorm(nn.Module): def __init__(self, channels, eps=1e-5): super().__init__() self.channels = channels self.eps = ...
--- +++ @@ -182,6 +182,10 @@ self.norm_layers_2.append(LayerNorm(hidden_channels)) def forward(self, x, x_mask, h, h_mask): + """ + x: decoder input + h: encoder output + """ self_attn_mask = commons.subsequent_mask(x_mask.size(2)).to( device=x.device...
https://raw.githubusercontent.com/myshell-ai/OpenVoice/HEAD/openvoice/attentions.py
Write docstrings that follow conventions
import re import json import numpy as np def get_hparams_from_file(config_path): with open(config_path, "r", encoding="utf-8") as f: data = f.read() config = json.loads(data) hparams = HParams(**config) return hparams class HParams: def __init__(self, **kwargs): for k, v in kwarg...
--- +++ @@ -83,6 +83,14 @@ return sentences def split_sentences_latin(text, min_len=10): + """Split Long sentences into list of short ones + + Args: + str: Input sentences. + + Returns: + List[str]: list of output sentences. + """ # deal with dirty sentences text = re.sub('[。!...
https://raw.githubusercontent.com/myshell-ai/OpenVoice/HEAD/openvoice/utils.py
Improve my code by adding docstrings
# Copyright (c) 2021, NVIDIA CORPORATION & AFFILIATES. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this sof...
--- +++ @@ -6,6 +6,7 @@ # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. +"""Converting legacy network pickle into the new format.""" import click import pickle @@ -294,6 +295,18 @@ @click.option('--dest', help='Outpu...
https://raw.githubusercontent.com/XingangPan/DragGAN/HEAD/legacy.py
Add docstrings with type hints explained
import torch import torch.utils.data from librosa.filters import mel as librosa_mel_fn MAX_WAV_VALUE = 32768.0 def dynamic_range_compression_torch(x, C=1, clip_val=1e-5): return torch.log(torch.clamp(x, min=clip_val) * C) def dynamic_range_decompression_torch(x, C=1): return torch.exp(x) / C def spectral...
--- +++ @@ -6,10 +6,20 @@ def dynamic_range_compression_torch(x, C=1, clip_val=1e-5): + """ + PARAMS + ------ + C: compression factor + """ return torch.log(torch.clamp(x, min=clip_val) * C) def dynamic_range_decompression_torch(x, C=1): + """ + PARAMS + ------ + C: compression ...
https://raw.githubusercontent.com/myshell-ai/OpenVoice/HEAD/openvoice/mel_processing.py
Provide clean and structured docstrings
import math def decay_batch_step(batch_size, num_intra_steps=2, no_odd=False): if batch_size <= 1: # return 0 for stopping value so easy to use in loop return 0 base_batch_size = int(2 ** (math.log(batch_size - 1) // math.log(2))) step_size = max(base_batch_size // num_intra_steps, 1) ...
--- +++ @@ -1,7 +1,23 @@+""" Batch size decay and retry helpers. + +Copyright 2022 Ross Wightman +""" import math def decay_batch_step(batch_size, num_intra_steps=2, no_odd=False): + """ power of two batch-size decay with intra steps + + Decay by stepping between powers of 2: + * determine power-of-2 flo...
https://raw.githubusercontent.com/huggingface/pytorch-image-models/HEAD/timm/utils/decay_batch.py
Generate missing documentation strings
from openvoice.text import cleaners from openvoice.text.symbols import symbols # Mappings from symbol to numeric ID and vice versa: _symbol_to_id = {s: i for i, s in enumerate(symbols)} _id_to_symbol = {i: s for i, s in enumerate(symbols)} def text_to_sequence(text, symbols, cleaner_names): sequence = [] symbol...
--- +++ @@ -1,58 +1,79 @@-from openvoice.text import cleaners -from openvoice.text.symbols import symbols - - -# Mappings from symbol to numeric ID and vice versa: -_symbol_to_id = {s: i for i, s in enumerate(symbols)} -_id_to_symbol = {i: s for i, s in enumerate(symbols)} - - -def text_to_sequence(text, symbols, clean...
https://raw.githubusercontent.com/myshell-ai/OpenVoice/HEAD/openvoice/text/__init__.py
Write docstrings for this repository
import random import torch class LatentCodesPool: def __init__(self, pool_size): self.pool_size = pool_size if self.pool_size > 0: # create an empty pool self.num_ws = 0 self.ws = [] def query(self, ws): if self.pool_size == 0: # if the buffer size is 0, do ...
--- +++ @@ -3,14 +3,30 @@ class LatentCodesPool: + """This class implements latent codes buffer that stores previously generated w latent codes. + This buffer enables us to update discriminators using a history of generated w's + rather than the ones produced by the latest encoder. + """ def __in...
https://raw.githubusercontent.com/XingangPan/DragGAN/HEAD/stylegan_human/pti/pti_models/e4e/latent_codes_pool.py
Add docstrings that explain logic
# Copyright (c) SenseTime Research. All rights reserved. # Copyright (c) 2019, NVIDIA Corporation. All rights reserved. # # This work is made available under the Nvidia Source Code License-NC. # To view a copy of this license, visit # https://nvlabs.github.io/stylegan2/license.html from collections import OrderedDic...
--- +++ @@ -6,6 +6,22 @@ # To view a copy of this license, visit # https://nvlabs.github.io/stylegan2/license.html +"""Helper for adding automatically tracked values to Tensorboard. + +Autosummary creates an identity op that internally keeps track of the input +values and automatically shows up in TensorBoard. The r...
https://raw.githubusercontent.com/XingangPan/DragGAN/HEAD/stylegan_human/dnnlib/tflib/autosummary.py
Add docstrings that explain purpose and usage
# Copyright (c) SenseTime Research. All rights reserved. # Copyright (c) 2019, NVIDIA Corporation. All rights reserved. # # This work is made available under the Nvidia Source Code License-NC. # To view a copy of this license, visit # https://nvlabs.github.io/stylegan2/license.html import os import numpy as np impor...
--- +++ @@ -6,6 +6,7 @@ # To view a copy of this license, visit # https://nvlabs.github.io/stylegan2/license.html +"""Custom TensorFlow ops for efficient bias and activation.""" import os import numpy as np @@ -33,6 +34,34 @@ #---------------------------------------------------------------------------- def fu...
https://raw.githubusercontent.com/XingangPan/DragGAN/HEAD/stylegan_human/dnnlib/tflib/ops/fused_bias_act.py
Document my Python code with docstrings
# Copyright (c) SenseTime Research. All rights reserved. # Copyright (c) 2019, NVIDIA Corporation. All rights reserved. # # This work is made available under the Nvidia Source Code License-NC. # To view a copy of this license, visit # https://nvlabs.github.io/stylegan2/license.html import numpy as np import tensorfl...
--- +++ @@ -6,6 +6,7 @@ # To view a copy of this license, visit # https://nvlabs.github.io/stylegan2/license.html +"""Helper wrapper for a Tensorflow optimizer.""" import numpy as np import tensorflow as tf @@ -27,6 +28,16 @@ import tensorflow.contrib.nccl as nccl_ops class Optimizer: + """A Wrapper fo...
https://raw.githubusercontent.com/XingangPan/DragGAN/HEAD/stylegan_human/dnnlib/tflib/optimizer.py
Help me comply with documentation standards
# Copyright (c) SenseTime Research. All rights reserved. # Copyright (c) 2019, NVIDIA Corporation. All rights reserved. # # This work is made available under the Nvidia Source Code License-NC. # To view a copy of this license, visit # https://nvlabs.github.io/stylegan2/license.html import types import inspect import...
--- +++ @@ -6,6 +6,7 @@ # To view a copy of this license, visit # https://nvlabs.github.io/stylegan2/license.html +"""Helper for managing networks.""" import types import inspect @@ -28,11 +29,48 @@ def import_handler(handler_func): + """Function decorator for declaring custom import handlers.""" _im...
https://raw.githubusercontent.com/XingangPan/DragGAN/HEAD/stylegan_human/dnnlib/tflib/network.py
Document this script properly
from collections import namedtuple import torch import torch.nn.functional as F from torch.nn import Conv2d, BatchNorm2d, PReLU, ReLU, Sigmoid, MaxPool2d, AdaptiveAvgPool2d, Sequential, Module """ ArcFace implementation from [TreB1eN](https://github.com/TreB1eN/InsightFace_Pytorch) """ class Flatten(Module): def...
--- +++ @@ -20,6 +20,7 @@ class Bottleneck(namedtuple('Block', ['in_channel', 'depth', 'stride'])): + """ A named tuple describing a ResNet block. """ def get_block(in_channel, depth, num_units, stride=2): @@ -120,5 +121,20 @@ def _upsample_add(x, y): + """Upsample and add two feature maps. + Args...
https://raw.githubusercontent.com/XingangPan/DragGAN/HEAD/stylegan_human/pti/pti_models/e4e/encoders/helpers.py
Write docstrings describing each step
# Copyright (c) SenseTime Research. All rights reserved. # Copyright (c) 2019, NVIDIA Corporation. All rights reserved. # # This work is made available under the Nvidia Source Code License-NC. # To view a copy of this license, visit # https://nvlabs.github.io/stylegan2/license.html import os import numpy as np impor...
--- +++ @@ -6,6 +6,7 @@ # To view a copy of this license, visit # https://nvlabs.github.io/stylegan2/license.html +"""Miscellaneous helper utils for Tensorflow.""" import os import numpy as np @@ -27,48 +28,58 @@ def run(*args, **kwargs) -> Any: + """Run the specified ops in the default session.""" a...
https://raw.githubusercontent.com/XingangPan/DragGAN/HEAD/stylegan_human/dnnlib/tflib/tfutil.py
Write documentation strings for class attributes
# Copyright (c) SenseTime Research. All rights reserved. # Copyright (c) 2019, NVIDIA Corporation. All rights reserved. # # This work is made available under the Nvidia Source Code License-NC. # To view a copy of this license, visit # https://nvlabs.github.io/stylegan2/license.html import os import numpy as np impor...
--- +++ @@ -6,6 +6,7 @@ # To view a copy of this license, visit # https://nvlabs.github.io/stylegan2/license.html +"""Custom TensorFlow ops for efficient resampling of 2D images.""" import os import numpy as np @@ -18,6 +19,43 @@ #---------------------------------------------------------------------------- de...
https://raw.githubusercontent.com/XingangPan/DragGAN/HEAD/stylegan_human/dnnlib/tflib/ops/upfirdn_2d.py
Write Python docstrings for this snippet
# Copyright (c) SenseTime Research. All rights reserved. # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduct...
--- +++ @@ -8,6 +8,7 @@ # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. +"""2D convolution with optional up/downsampling.""" import torch @@ -28,6 +29,8 @@ #----------------------------------------------------------...
https://raw.githubusercontent.com/XingangPan/DragGAN/HEAD/stylegan_human/torch_utils/ops/conv2d_resample.py
Write docstrings for algorithm functions
# Copyright (c) SenseTime Research. All rights reserved. # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduct...
--- +++ @@ -8,6 +8,7 @@ # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. +"""Custom PyTorch ops for efficient bias and activation.""" import os import warnings @@ -54,6 +55,35 @@ #-------------------------------------...
https://raw.githubusercontent.com/XingangPan/DragGAN/HEAD/stylegan_human/torch_utils/ops/bias_act.py
Write clean docstrings for readability
# Copyright (c) 2021, NVIDIA CORPORATION & AFFILIATES. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this sof...
--- +++ @@ -62,6 +62,61 @@ #---------------------------------------------------------------------------- def filtered_lrelu(x, fu=None, fd=None, b=None, up=1, down=1, padding=0, gain=np.sqrt(2), slope=0.2, clamp=None, flip_filter=False, impl='cuda'): + r"""Filtered leaky ReLU for a batch of 2D images. + + Perf...
https://raw.githubusercontent.com/XingangPan/DragGAN/HEAD/stylegan_human/torch_utils/ops/filtered_lrelu.py
Generate docstrings for each module
# Copyright (c) SenseTime Research. All rights reserved. # Copyright (c) 2021, NVIDIA CORPORATION & AFFILIATES. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any u...
--- +++ @@ -8,6 +8,8 @@ # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. +"""Train a GAN using the techniques described in the paper +"Alias-Free Generative Adversarial Networks".""" import os import click @@ -166,6 +...
https://raw.githubusercontent.com/XingangPan/DragGAN/HEAD/stylegan_human/training_scripts/sg3/train.py
Add docstrings to clarify complex logic
# Copyright (c) SenseTime Research. All rights reserved. # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduct...
--- +++ @@ -8,6 +8,7 @@ # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. +"""Custom PyTorch ops for efficient resampling of 2D images.""" import os import warnings @@ -71,6 +72,26 @@ #---------------------------------...
https://raw.githubusercontent.com/XingangPan/DragGAN/HEAD/stylegan_human/torch_utils/ops/upfirdn2d.py
Generate helpful docstrings for debugging
# Copyright (c) SenseTime Research. All rights reserved. # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduct...
--- +++ @@ -8,6 +8,8 @@ # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. +"""Train a GAN using the techniques described in the paper +"Training Generative Adversarial Networks with Limited Data".""" import os import c...
https://raw.githubusercontent.com/XingangPan/DragGAN/HEAD/stylegan_human/training_scripts/sg2/train.py
Write docstrings including parameters and return values
# Copyright (c) SenseTime Research. All rights reserved. import numpy as np import PIL import PIL.Image import scipy import scipy.ndimage import dlib import copy from PIL import Image def get_landmark(img, detector, predictor): # detector = dlib.get_frontal_face_detector() # dets, _, _ = detector.run(img, 1, ...
--- +++ @@ -10,6 +10,9 @@ from PIL import Image def get_landmark(img, detector, predictor): + """get landmark with dlib + :return: np.array shape=(68, 2) + """ # detector = dlib.get_frontal_face_detector() # dets, _, _ = detector.run(img, 1, -1) dets = detector(img, 1) @@ -29,6 +32,10 @@ ...
https://raw.githubusercontent.com/XingangPan/DragGAN/HEAD/stylegan_human/utils/face_alignment.py
Write docstrings describing functionality
import os import sys import json import requests from tqdm import tqdm def download_file(url: str, filename: str, download_dir: str): try: filepath = os.path.join(download_dir, filename) content_length = int(requests.head(url).headers.get("content-length", 0)) # If file already exists and...
--- +++ @@ -5,6 +5,7 @@ from tqdm import tqdm def download_file(url: str, filename: str, download_dir: str): + """Download a file if it does not already exist.""" try: filepath = os.path.join(download_dir, filename) @@ -54,6 +55,7 @@ print(f"An error occurred: {e}") def main(): + """...
https://raw.githubusercontent.com/XingangPan/DragGAN/HEAD/scripts/download_model.py
Add docstrings that explain logic
# Copyright (c) 2021, NVIDIA CORPORATION & AFFILIATES. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this sof...
--- +++ @@ -54,6 +54,61 @@ #---------------------------------------------------------------------------- def filtered_lrelu(x, fu=None, fd=None, b=None, up=1, down=1, padding=0, gain=np.sqrt(2), slope=0.2, clamp=None, flip_filter=False, impl='cuda'): + r"""Filtered leaky ReLU for a batch of 2D images. + + Perf...
https://raw.githubusercontent.com/XingangPan/DragGAN/HEAD/torch_utils/ops/filtered_lrelu.py
Add docstrings with type hints explained
# Copyright (c) 2021, NVIDIA CORPORATION & AFFILIATES. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this sof...
--- +++ @@ -6,6 +6,7 @@ # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. +"""Custom PyTorch ops for efficient resampling of 2D images.""" import os import numpy as np @@ -67,6 +68,26 @@ #------------------------------...
https://raw.githubusercontent.com/XingangPan/DragGAN/HEAD/torch_utils/ops/upfirdn2d.py
Add docstrings that explain purpose and usage
# Copyright (c) 2021, NVIDIA CORPORATION & AFFILIATES. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this sof...
--- +++ @@ -6,6 +6,7 @@ # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. +"""2D convolution with optional up/downsampling.""" import torch @@ -26,6 +27,8 @@ #----------------------------------------------------------...
https://raw.githubusercontent.com/XingangPan/DragGAN/HEAD/torch_utils/ops/conv2d_resample.py
Add docstrings for better understanding
# Copyright (c) 2021, NVIDIA CORPORATION & AFFILIATES. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this sof...
--- +++ @@ -6,6 +6,7 @@ # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. +"""Custom PyTorch ops for efficient bias and activation.""" import os import numpy as np @@ -49,6 +50,35 @@ #----------------------------------...
https://raw.githubusercontent.com/XingangPan/DragGAN/HEAD/torch_utils/ops/bias_act.py
Include argument descriptions in docstrings
# Copyright (c) SenseTime Research. All rights reserved. # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduct...
--- +++ @@ -8,6 +8,10 @@ # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. +"""Facilities for reporting and collecting training statistics across +multiple processes and devices. The interface is designed to minimize +sync...
https://raw.githubusercontent.com/XingangPan/DragGAN/HEAD/stylegan_human/torch_utils/training_stats.py