repo stringlengths 1 99 | file stringlengths 13 215 | code stringlengths 12 59.2M | file_length int64 12 59.2M | avg_line_length float64 3.82 1.48M | max_line_length int64 12 2.51M | extension_type stringclasses 1
value |
|---|---|---|---|---|---|---|
unified-generative-zoo | unified-generative-zoo-main/model/lib/eg3d/torch_utils/ops/fma.py | # SPDX-FileCopyrightText: Copyright (c) 2021-2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: LicenseRef-NvidiaProprietary
#
# NVIDIA CORPORATION, its affiliates and licensors retain all intellectual
# property and proprietary rights in and to this material, related
# documentation ... | 2,161 | 33.31746 | 105 | py |
unified-generative-zoo | unified-generative-zoo-main/model/lib/eg3d/viz/renderer.py | # SPDX-FileCopyrightText: Copyright (c) 2021-2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: LicenseRef-NvidiaProprietary
#
# NVIDIA CORPORATION, its affiliates and licensors retain all intellectual
# property and proprietary rights in and to this material, related
# documentation ... | 18,467 | 40.131403 | 164 | py |
unified-generative-zoo | unified-generative-zoo-main/model/lib/eg3d/metrics/metric_utils.py | # SPDX-FileCopyrightText: Copyright (c) 2021-2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: LicenseRef-NvidiaProprietary
#
# NVIDIA CORPORATION, its affiliates and licensors retain all intellectual
# property and proprietary rights in and to this material, related
# documentation ... | 12,059 | 41.765957 | 167 | py |
unified-generative-zoo | unified-generative-zoo-main/model/lib/eg3d/metrics/equivariance.py | # SPDX-FileCopyrightText: Copyright (c) 2021-2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: LicenseRef-NvidiaProprietary
#
# NVIDIA CORPORATION, its affiliates and licensors retain all intellectual
# property and proprietary rights in and to this material, related
# documentation ... | 10,982 | 39.677778 | 165 | py |
unified-generative-zoo | unified-generative-zoo-main/model/lib/eg3d/metrics/perceptual_path_length.py | # SPDX-FileCopyrightText: Copyright (c) 2021-2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: LicenseRef-NvidiaProprietary
#
# NVIDIA CORPORATION, its affiliates and licensors retain all intellectual
# property and proprietary rights in and to this material, related
# documentation ... | 5,370 | 40.960938 | 131 | py |
unified-generative-zoo | unified-generative-zoo-main/model/lib/eg3d/metrics/metric_main.py | # SPDX-FileCopyrightText: Copyright (c) 2021-2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: LicenseRef-NvidiaProprietary
#
# NVIDIA CORPORATION, its affiliates and licensors retain all intellectual
# property and proprietary rights in and to this material, related
# documentation ... | 5,789 | 36.115385 | 147 | py |
unified-generative-zoo | unified-generative-zoo-main/model/lib/eg3d/metrics/precision_recall.py | # SPDX-FileCopyrightText: Copyright (c) 2021-2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: LicenseRef-NvidiaProprietary
#
# NVIDIA CORPORATION, its affiliates and licensors retain all intellectual
# property and proprietary rights in and to this material, related
# documentation ... | 3,758 | 56.830769 | 159 | py |
unified-generative-zoo | unified-generative-zoo-main/model/lib/giraffe_hd/camera.py | import numpy as np
import torch
from scipy.spatial.transform import Rotation as Rot
def get_camera_mat(fov=49.13, invert=True):
# fov = 2 * arctan( sensor / (2 * focal))
# focal = (sensor / 2) * 1 / (tan(0.5 * fov))
# in our case, sensor = 2 as pixels are in [-1, 1]
focal = 1. / np.tan(0.5 * fov * np... | 3,265 | 27.649123 | 83 | py |
unified-generative-zoo | unified-generative-zoo-main/model/lib/giraffe_hd/model.py | import numpy as np
from scipy.spatial.transform import Rotation as Rot
from .camera import (
get_rotation_matrix,
get_camera_mat,
get_random_pose,
uvr_to_pose
)
import torch.nn as nn
import torch.nn.functional as F
import torch
from .common import (
arange_pixels, image_points_to_world, origin_to_wo... | 56,807 | 32.143524 | 127 | py |
unified-generative-zoo | unified-generative-zoo-main/model/lib/giraffe_hd/common.py | import torch
import numpy as np
import logging
logger_py = logging.getLogger(__name__)
def arange_pixels(resolution=(128, 128), batch_size=1, image_range=(-1., 1.),
subsample_to=None, invert_y_axis=False):
''' Arranges pixels for given resolution in range image_range.
The function returns t... | 7,421 | 33.52093 | 83 | py |
unified-generative-zoo | unified-generative-zoo-main/model/lib/giraffe_hd/op/conv2d_gradfix.py | import contextlib
import warnings
import torch
from torch import autograd
from torch.nn import functional as F
enabled = True
weight_gradients_disabled = False
@contextlib.contextmanager
def no_weight_gradients():
global weight_gradients_disabled
old = weight_gradients_disabled
weight_gradients_disable... | 6,379 | 26.982456 | 117 | py |
unified-generative-zoo | unified-generative-zoo-main/model/lib/giraffe_hd/op/upfirdn2d.py | import os
import torch
from torch.nn import functional as F
from torch.autograd import Function
from torch.utils.cpp_extension import load
module_path = os.path.dirname(__file__)
upfirdn2d_op = load(
"upfirdn2d",
sources=[
os.path.join(module_path, "upfirdn2d.cpp"),
os.path.join(module_path, ... | 5,672 | 27.223881 | 108 | py |
unified-generative-zoo | unified-generative-zoo-main/model/lib/giraffe_hd/op/fused_act.py | import os
import torch
from torch import nn
from torch.nn import functional as F
from torch.autograd import Function
from torch.utils.cpp_extension import load
module_path = os.path.dirname(__file__)
fused = load(
"fused",
sources=[
os.path.join(module_path, "fused_bias_act.cpp"),
os.path.joi... | 3,143 | 25.2 | 86 | py |
unified-generative-zoo | unified-generative-zoo-main/model/lib/diffae/renderer.py | from .config import *
def render_uncondition(conf: TrainConfig,
model: BeatGANsAutoencModel,
x_T,
sampler: Sampler,
latent_sampler: Sampler,
conds_mean=None,
conds_std=None,
... | 1,852 | 30.40678 | 78 | py |
unified-generative-zoo | unified-generative-zoo-main/model/lib/diffae/choices.py | from enum import Enum
from torch import nn
class TrainMode(Enum):
# manipulate mode = training the classifier
manipulate = 'manipulate'
# default trainin mode!
diffusion = 'diffusion'
# default latent training mode!
# fitting the a DDPM to a given latent
latent_diffusion = 'latentdiffusion... | 4,066 | 21.72067 | 84 | py |
unified-generative-zoo | unified-generative-zoo-main/model/lib/diffae/experiment.py | import copy
import json
import pytorch_lightning as pl
from pytorch_lightning import loggers as pl_loggers
from pytorch_lightning.callbacks import *
from torch.cuda import amp
from torch.utils.data.dataset import ConcatDataset, TensorDataset
from .dist_utils import *
from .renderer import *
class LitModel(pl.Lightn... | 13,629 | 34.774278 | 109 | py |
unified-generative-zoo | unified-generative-zoo-main/model/lib/diffae/dist_utils.py | from typing import List
from torch import distributed
def barrier():
if distributed.is_initialized():
distributed.barrier()
else:
pass
def broadcast(data, src):
if distributed.is_initialized():
distributed.broadcast(data, src)
else:
pass
def all_gather(data: List, s... | 804 | 18.166667 | 43 | py |
unified-generative-zoo | unified-generative-zoo-main/model/lib/diffae/config.py | from .model.unet import ScaleAt
from .model.latentnet import *
from .diffusion.resample import UniformSampler
from .diffusion.diffusion import space_timesteps
from typing import Tuple
from .config_base import BaseConfig
from .diffusion import *
from .diffusion.base import get_named_beta_schedule
from .model import *
f... | 14,269 | 38.41989 | 111 | py |
unified-generative-zoo | unified-generative-zoo-main/model/lib/diffae/diffusion/base.py | """
This code started out as a PyTorch port of Ho et al's diffusion models:
https://github.com/hojonathanho/diffusion/blob/1e0dceb3b3495bbe19116a5e1b3596cd0706c543/diffusion_tf/diffusion_utils_2.py
Docstrings have been added, as well as DDIM sampling and a new collection of beta schedules.
"""
from ..config_base impo... | 44,306 | 37.42758 | 129 | py |
unified-generative-zoo | unified-generative-zoo-main/model/lib/diffae/diffusion/resample.py | from abc import ABC, abstractmethod
import numpy as np
import torch as th
def create_named_schedule_sampler(name, diffusion):
"""
Create a ScheduleSampler from a library of pre-defined samplers.
:param name: the name of the sampler.
:param diffusion: the diffusion object to sample for.
"""
i... | 1,993 | 30.650794 | 78 | py |
unified-generative-zoo | unified-generative-zoo-main/model/lib/diffae/model/latentnet.py | import torch
from torch.nn import init
from .unet import *
class LatentNetType(Enum):
none = 'none'
# injecting inputs into the hidden layers
skip = 'skip'
class LatentNetReturn(NamedTuple):
pred: torch.Tensor = None
@dataclass
class MLPSkipNetConfig(BaseConfig):
"""
default MLP for the l... | 5,602 | 29.617486 | 71 | py |
unified-generative-zoo | unified-generative-zoo-main/model/lib/diffae/model/nn.py | """
Various utilities for neural networks.
"""
import math
import torch as th
import torch.nn as nn
import torch.utils.checkpoint
# PyTorch 1.7 has SiLU, but we support PyTorch 1.5.
class SiLU(nn.Module):
# @th.jit.script
def forward(self, x):
return x * th.sigmoid(x)
class GroupNorm32(nn.GroupNor... | 3,609 | 25.940299 | 90 | py |
unified-generative-zoo | unified-generative-zoo-main/model/lib/diffae/model/unet.py | from typing import NamedTuple, Tuple, Union
from .blocks import *
from .nn import (conv_nd, linear, normalization, timestep_embedding,
torch_checkpoint, zero_module)
@dataclass
class BeatGANsUNetConfig(BaseConfig):
image_size: int = 64
in_channels: int = 3
# base channels, will be multi... | 20,508 | 36.700368 | 124 | py |
unified-generative-zoo | unified-generative-zoo-main/model/lib/diffae/model/unet_autoenc.py | from torch import Tensor
from .latentnet import *
from .unet import *
from ..choices import *
@dataclass
class BeatGANsAutoencConfig(BeatGANsUNetConfig):
# number of style channels
enc_out_channels: int = 512
enc_attn_resolutions: Tuple[int] = None
enc_pool: str = 'depthconv'
enc_num_res_block: i... | 9,108 | 31.532143 | 81 | py |
unified-generative-zoo | unified-generative-zoo-main/model/lib/diffae/model/blocks.py | import math
from abc import abstractmethod
from dataclasses import dataclass
from numbers import Number
import torch as th
import torch.nn.functional as F
from ..choices import *
from ..config_base import BaseConfig
from torch import nn
from .nn import (avg_pool_nd, conv_nd, linear, normalization,
ti... | 18,668 | 31.867958 | 124 | py |
unified-generative-zoo | unified-generative-zoo-main/model/lib/diffaug/DiffAugment_pytorch.py | # Differentiable Augmentation for Data-Efficient GAN Training
# Shengyu Zhao, Zhijian Liu, Ji Lin, Jun-Yan Zhu, and Song Han
# https://arxiv.org/pdf/2006.10738
import torch
import torch.nn.functional as F
import numpy as np
def DiffAugment(x, policy='', channels_first=True):
if policy:
if not channels_fi... | 4,134 | 39.145631 | 110 | py |
unified-generative-zoo | unified-generative-zoo-main/model/lib/celeba/classifier.py | import torch
import torch.nn as nn
import torchvision
import torchvision.transforms as transforms
class ResNet50(nn.Module):
def __init__(self, n_classes=1, pretrained=True, hidden_size=2048, dropout=0.5):
super().__init__()
self.resnet = torchvision.models.resnet50(pretrained=pretrained)
... | 1,645 | 27.877193 | 122 | py |
unified-generative-zoo | unified-generative-zoo-main/model/lib/nvae/neural_ar_operations.py | # ---------------------------------------------------------------
# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
#
# This work is licensed under the NVIDIA Source Code License
# for NVAE. To view a copy of this license, see the LICENSE file.
# ------------------------------------------------------------... | 7,362 | 34.742718 | 120 | py |
unified-generative-zoo | unified-generative-zoo-main/model/lib/nvae/distributions.py | # ---------------------------------------------------------------
# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
#
# This work is licensed under the NVIDIA Source Code License
# for NVAE. To view a copy of this license, see the LICENSE file.
# ------------------------------------------------------------... | 10,497 | 45.657778 | 126 | py |
unified-generative-zoo | unified-generative-zoo-main/model/lib/nvae/evaluate.py | # ---------------------------------------------------------------
# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
#
# This work is licensed under the NVIDIA Source Code License
# for NVAE. To view a copy of this license, see the LICENSE file.
# ------------------------------------------------------------... | 8,326 | 43.768817 | 129 | py |
unified-generative-zoo | unified-generative-zoo-main/model/lib/nvae/utils.py | # ---------------------------------------------------------------
# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
#
# This work is licensed under the NVIDIA Source Code License
# for NVAE. To view a copy of this license, see the LICENSE file.
# ------------------------------------------------------------... | 15,405 | 34.662037 | 177 | py |
unified-generative-zoo | unified-generative-zoo-main/model/lib/nvae/model.py | # ---------------------------------------------------------------
# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
#
# This work is licensed under the NVIDIA Source Code License
# for NVAE. To view a copy of this license, see the LICENSE file.
# ------------------------------------------------------------... | 22,691 | 41.022222 | 122 | py |
unified-generative-zoo | unified-generative-zoo-main/model/lib/nvae/neural_operations.py | # ---------------------------------------------------------------
# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
#
# This work is licensed under the NVIDIA Source Code License
# for NVAE. To view a copy of this license, see the LICENSE file.
# ------------------------------------------------------------... | 11,176 | 33.819315 | 120 | py |
unified-generative-zoo | unified-generative-zoo-main/model/lib/nvae/thirdparty/inplaced_sync_batchnorm.py | # ---------------------------------------------------------------
# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
#
# This file has been modified from a file in the PyTorch library.
#
# Source:
# https://github.com/pytorch/pytorch/blob/881c1adfcd916b6cd5de91bc343eb86aff88cc80/torch/nn/modules/batchnorm.p... | 8,177 | 46.271676 | 120 | py |
unified-generative-zoo | unified-generative-zoo-main/model/lib/nvae/thirdparty/functions.py | # ---------------------------------------------------------------
# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
#
# This file has been modified from a file in the PyTorch library.
#
# Source:
# https://github.com/pytorch/pytorch/blob/2a54533c64c409b626b6c209ed78258f67aec194/torch/nn/modules/_functions.... | 4,967 | 36.074627 | 116 | py |
unified-generative-zoo | unified-generative-zoo-main/model/lib/nvae/thirdparty/adamax.py | # ---------------------------------------------------------------
# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
#
# This file has been modified from a file in the PyTorch library.
#
# Source:
# https://github.com/pytorch/pytorch/blob/6e2bb1c05442010aff90b413e21fce99f0393727/torch/optim/adamax.py
#
# Th... | 5,447 | 40.907692 | 104 | py |
unified-generative-zoo | unified-generative-zoo-main/model/lib/nvae/thirdparty/swish.py | # ---------------------------------------------------------------
# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
#
# This file has been modified from a file in the following repo
# (released under the Apache License 2.0).
#
# Source:
# https://github.com/ceshine/EfficientNet-PyTorch/blob/master/efficien... | 898 | 31.107143 | 91 | py |
unified-generative-zoo | unified-generative-zoo-main/model/lib/styleswin/models/discriminator.py | # Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
import math
import torch
from ..op import FusedLeakyReLU, upfirdn2d
from torch import nn
from torch.nn import functional as F
from torch.nn.utils import spectral_norm
from .basic_layers import (Blur, Downsample, EqualConv2d, EqualLinear,
... | 7,263 | 28.056 | 98 | py |
unified-generative-zoo | unified-generative-zoo-main/model/lib/styleswin/models/basic_layers.py | # Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
import math
import numpy as np
import torch
from ..op import fused_leaky_relu, upfirdn2d
from torch import nn
from torch.nn import functional as F
class Blur(nn.Module):
def __init__(self, kernel, pad, upsample_factor=1):
super()._... | 14,090 | 30.665169 | 108 | py |
unified-generative-zoo | unified-generative-zoo-main/model/lib/styleswin/models/generator.py | # Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
import math
import torch
import torch.utils.checkpoint as checkpoint
from timm.models.layers import to_2tuple, trunc_normal_
from torch import nn
from .basic_layers import (EqualLinear, PixelNorm,
SinusoidalPosi... | 25,546 | 37.943598 | 142 | py |
unified-generative-zoo | unified-generative-zoo-main/model/lib/styleswin/op/upfirdn2d.py | # Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
import os
import torch
from torch.nn import functional as F
from torch.autograd import Function
from torch.utils.cpp_extension import load
module_path = os.path.dirname(__file__)
upfirdn2d_op = load(
"upfirdn2d",
sources=[
os.p... | 5,584 | 26.648515 | 86 | py |
unified-generative-zoo | unified-generative-zoo-main/model/lib/styleswin/op/fused_act.py | # Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
import os
import torch
from torch import nn
from torch.nn import functional as F
from torch.autograd import Function
from torch.utils.cpp_extension import load
from torch.cuda.amp import custom_fwd, custom_bwd
module_path = os.path.dirname(__f... | 2,873 | 26.634615 | 83 | py |
unified-generative-zoo | unified-generative-zoo-main/model/lib/styleswin/utils/CRDiffAug.py | # Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
import torch
import torch.nn.functional as F
def CR_DiffAug(x, flip=True, translation=True, color=True, cutout=True):
if flip:
x = random_flip(x, 0.5)
if translation:
x = rand_translation(x, 1/8)
if color:
au... | 3,267 | 38.853659 | 110 | py |
unified-generative-zoo | unified-generative-zoo-main/model/lib/styleswin/utils/distributed.py | # Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
import pickle
import torch
from torch import distributed as dist
def get_rank():
if not dist.is_available():
return 0
if not dist.is_initialized():
return 0
return dist.get_rank()
def synchronize():
if not d... | 2,732 | 20.351563 | 76 | py |
unified-generative-zoo | unified-generative-zoo-main/model/gan_wrapper/styleswin_wrapper.py | import os
import torch
import torchvision.transforms as transforms
from ..lib.styleswin.models.generator import Generator
from ..model_utils import requires_grad
def prepare_styleswin(source_model_type):
pt_file_name = {
"ffhq256": "StyleSwin_FFHQ_256.pt",
"ffhq1024": "StyleSwin_FFHQ_102... | 2,998 | 29.292929 | 150 | py |
unified-generative-zoo | unified-generative-zoo-main/model/gan_wrapper/eg3d_wrapper.py | import os
import sys
sys.path.append(os.path.abspath('model/lib/eg3d'))
import torch
import torchvision.transforms as transforms
import numpy as np
from dnnlib.util import open_url
from legacy import load_network_pkl
from camera_utils import LookAtPoseSampler, FOV_to_intrinsics
from ..model_utils import requires_grad... | 2,722 | 33.0375 | 120 | py |
unified-generative-zoo | unified-generative-zoo-main/model/gan_wrapper/styleganxl_wrapper.py | import os
import sys
sys.path.append(os.path.abspath('model/lib/stylegan_xl'))
import torch
import torchvision.transforms as transforms
from dnnlib.util import open_url
from legacy import load_network_pkl
from ..model_utils import requires_grad
class StyleGANXLWrapper(torch.nn.Module):
def __init__(self, networ... | 1,318 | 27.06383 | 106 | py |
unified-generative-zoo | unified-generative-zoo-main/model/gan_wrapper/diffae_wrapper.py | import os
import torch
import torchvision.transforms as transforms
from ..lib.diffae.templates_latent import (
ffhq128_autoenc_latent,
ffhq256_autoenc_latent,
horse128_autoenc_latent,
bedroom128_autoenc_latent,
LitModel,
)
from ..lib.diffae.config import TrainConfig, Sampler, BeatGANsAutoencModel
f... | 5,166 | 30.895062 | 106 | py |
unified-generative-zoo | unified-generative-zoo-main/model/gan_wrapper/stylegan2_wrapper.py | import os
import torch
import torchvision.transforms as transforms
from ..lib.stylegan2.sg2_model import Generator
from ..model_utils import requires_grad
def prepare_stylegan(source_model_type):
pt_file_name = {
"ffhq": "ffhq.pt",
"cat": "afhqcat.pt",
"dog": "afhqdog.pt"... | 3,917 | 28.908397 | 106 | py |
unified-generative-zoo | unified-generative-zoo-main/model/gan_wrapper/giraffehd_wrapper.py | import argparse
import numpy as np
import torch
import torchvision.transforms as transforms
from ..lib.giraffe_hd.model import GIRAFFEHDGenerator
from ..model_utils import requires_grad
def prepare_ghq(source_model_type):
print('First of all, when the code changes, make sure that no part in the model is under n... | 4,202 | 36.526786 | 111 | py |
unified-generative-zoo | unified-generative-zoo-main/model/gan_wrapper/stylesdf_wrapper.py | import os
import torch
import torchvision.transforms as transforms
from ..lib.stylesdf.options import BaseOptions
from ..lib.stylesdf.model import Generator
from ..lib.stylesdf.utils import generate_camera_params
from ..model_utils import requires_grad
def prepare_stylesdf(source_model_type, sample_truncation):
... | 3,758 | 33.172727 | 126 | py |
unified-generative-zoo | unified-generative-zoo-main/model/gan_wrapper/nvae_wrapper_trunc.py | import os
import numpy as np
import torch
from torch.cuda.amp import autocast
from ..lib.nvae.model import AutoEncoder
from ..lib.nvae.utils import get_arch_cells
from ..lib.nvae.distributions import Normal, NormalDecoder, DiscMixLogistic
from ..model_utils import requires_grad
def prepare_nvae(source_model_type):
... | 6,445 | 33.655914 | 121 | py |
unified-generative-zoo | unified-generative-zoo-main/model/gan_wrapper/ddgan_wrapper.py | import argparse
import numpy as np
import torch
import torchvision.transforms as transforms
from ..lib.ddgan.score_sde.models.ncsnpp_generator_adagn import NCSNpp
from ..model_utils import requires_grad
def prepare_ddgan(source_model_type):
print('First of all, when the code changes, make sure that no part in t... | 11,542 | 35.878594 | 120 | py |
unified-generative-zoo | unified-generative-zoo-main/model/gan_wrapper/stylenerf_wrapper.py | import os
import sys
sys.path.append(os.path.abspath('model/lib/stylenerf'))
import torch
import torchvision.transforms as transforms
from dnnlib.util import open_url
from legacy import load_network_pkl
from renderer import Renderer
from ..model_utils import requires_grad
def prepare_stylenerf(source_model_type):
... | 2,572 | 27.910112 | 106 | py |
unified-generative-zoo | unified-generative-zoo-main/model/gan_wrapper/latentdiff_wrapper.py | import os
import sys
sys.path.append(os.path.abspath('model/lib/latentdiff'))
import glob
from omegaconf import OmegaConf
import numpy as np
import torch
import torchvision.transforms as transforms
import torch.nn.functional as F
from sample_diffusion import get_parser, load_model, DDIMSampler
from ..model_utils impor... | 11,047 | 38.038869 | 117 | py |
unified-generative-zoo | unified-generative-zoo-main/model/gan_wrapper/diffusion_stylegan2_wrapper.py | import os
import sys
sys.path.append(os.path.abspath('model/lib/diffusion_stylegan'))
import torch
import torchvision.transforms as transforms
from dnnlib.util import open_url
from legacy import load_network_pkl
from ..model_utils import requires_grad
def prepare_diffusion_stylegan2(source_model_type):
pt_file_n... | 1,645 | 27.877193 | 106 | py |
unified-generative-zoo | unified-generative-zoo-main/model/gan_wrapper/extended_adpm_wrapper.py | import os
import sys
sys.path.append(os.path.abspath('model/lib/extended_adpm'))
import math
import logging
import argparse
import numpy as np
import torch
import torch.nn as nn
import torchvision.transforms as transforms
import ml_collections
from misc import str2bool, parse_sde, parse_schedule
from core.diffusion.d... | 17,672 | 38.625561 | 184 | py |
ReSeND | ReSeND-main/train.py | import argparse
import torch
import torch.distributed as dist
from torchlars import LARS
from torch.nn.parallel import DistributedDataParallel as DDP
from torch import nn
from torch.nn import functional as F
from tqdm import tqdm
import numpy as np
import os
import sys
import ast
import time
import datetime
import mat... | 26,286 | 41.535599 | 182 | py |
ReSeND | ReSeND-main/models/relational_transformer.py | import math
import torch
import torch.nn as nn
import timm
from models.vision_transformer import Block, partial, _init_vit_weights, trunc_normal_, named_apply
class RelationalTransformer(nn.Module):
def __init__(self, input_dim, num_classes=1, embed_dim=768, depth=4, num_heads=12, mlp_ratio=4, qkv_bias=True, dr... | 3,002 | 36.5375 | 164 | py |
ReSeND | ReSeND-main/models/resnet.py | from torch import nn
from torchvision import models
class ResNetFc(nn.Module):
def __init__(self,device,network):
super(ResNetFc, self).__init__()
if network=='resnet18':
self.model_resnet = models.resnet18(pretrained=True)
elif network=='resnet50':
self.model_resn... | 2,627 | 30.285714 | 64 | py |
ReSeND | ReSeND-main/models/vision_transformer.py | """ Vision Transformer (ViT) in PyTorch
A PyTorch implement of 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 Regularization in Vision Transformers`
- https:... | 42,362 | 47.637199 | 140 | py |
ReSeND | ReSeND-main/models/data_helper.py | from os.path import join, dirname
import torch
import torch.utils.data as data
import torchvision.transforms as transforms
from timm.data.auto_augment import rand_augment_transform
from timm.data.random_erasing import RandomErasing
from PIL import Image,ImageFile
from random import sample
from models.create_pairs impor... | 8,408 | 35.402597 | 171 | py |
ReSeND | ReSeND-main/evals/eval.py | import os
import torch
import numpy as np
import torch.nn as nn
from tqdm import tqdm
from sklearn.metrics import roc_auc_score
from utils.dist_utils import all_gather
def stable_cumsum(arr, rtol=1e-05, atol=1e-08):
"""Use high precision for cumsum and check that final value matches sum
Parameters
------... | 13,727 | 36.203252 | 151 | py |
ReSeND | ReSeND-main/utils/dist_utils.py | import pickle
import torch
import torch.distributed as dist
def get_world_size():
if not dist.is_available():
return 1
if not dist.is_initialized():
return 1
return dist.get_world_size()
def all_gather(data):
"""
Run all_gather on arbitrary picklable data (not necessarily tensors)... | 1,667 | 28.785714 | 77 | py |
ReSeND | ReSeND-main/utils/utils.py | import torch
from tqdm import tqdm
def get_coreset_idx(
z_lib : torch.Tensor,
n : int = 1000,
eps : float = 0.90,
float16 : bool = True,
force_cpu : bool = False,
) -> torch.Tensor:
"""Returns n coreset idx for given z_lib.
Performance on AMD3700, 32GB RAM, RTX3080 (10GB):
CPU: 40... | 1,990 | 35.87037 | 104 | py |
ReSeND | ReSeND-main/utils/log_utils.py | import numpy as np
import math
import torch
from torch import nn
from tqdm import tqdm
class LogUnbuffered:
def __init__(self, args, stream, file):
self.args = args
self.stream = stream
self.file = file
def write(self, data):
if self.args.distributed and self.args.global_rank ... | 829 | 24.151515 | 87 | py |
ReSeND | ReSeND-main/utils/ckpt_utils.py | import torch
import os
def check_resume(resume_path):
if not os.path.isdir(resume_path):
return False
if not os.path.isfile(resume_path + "/last_checkpoint.txt"):
return False
return True
def resume(models_dict: dict, resume_path: str):
for key in models_dict.keys():
ckpt_di... | 1,963 | 30.174603 | 112 | py |
ReSeND | ReSeND-main/optimizer/optimizer_helper.py | from torch import optim
from torch.optim.lr_scheduler import _LRScheduler
from torch.optim.lr_scheduler import ReduceLROnPlateau
def get_optim_and_scheduler(modules: list, args, num_its, step_after, start_it, warmup_its):
init_lr = args.learning_rate
params = []
for m in modules:
params += list(... | 3,802 | 43.741176 | 152 | py |
SGN | SGN-master/main.py | # Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
import argparse
import time
import shutil
import os
os.environ["CUDA_VISIBLE_DEVICES"] = '1'
import os.path as osp
import csv
import numpy as np
np.random.seed(1337)
import torch
import torch.nn as nn
import torch.optim as o... | 8,886 | 31.083032 | 102 | py |
SGN | SGN-master/model.py | # Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from torch import nn
import torch
import math
class SGN(nn.Module):
def __init__(self, num_classes, dataset, seg, args, bias = True):
super(SGN, self).__init__()
self.dim1 = 256
self.dataset = dat... | 6,489 | 32.282051 | 88 | py |
SGN | SGN-master/data.py | # Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from torch.utils.data import Dataset, DataLoader
import os
import torch
import numpy as np
import h5py
import random
import os.path as osp
import sys
from six.moves import xrange
import math
import scipy.misc
if sys.version_in... | 9,516 | 33.733577 | 114 | py |
SGN | SGN-master/util.py | # Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
import os
import csv
import numpy as np
import matplotlib.pyplot as plt
import torch.nn as nn
import torch
import os.path as osp
def make_dir(dataset):
if dataset == 'NTU':
output_dir = os.path.join('./results/NTU... | 633 | 20.862069 | 59 | py |
SELFormer | SELFormer-main/get_moleculenet_embeddings.py | import os
from time import time
from fnmatch import fnmatch
import pandas as pd
from pandarallel import pandarallel
import to_selfies
import torch
from transformers import RobertaTokenizer, RobertaModel, RobertaConfig
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--dataset_path", required=T... | 4,133 | 36.926606 | 137 | py |
SELFormer | SELFormer-main/multilabel_class_pred.py | import os
import numpy as np
import pandas as pd
import torch
from simpletransformers.classification import MultiLabelClassificationModel
from prepare_finetuning_data import smiles_to_selfies
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--task", default="sider", help="task selection.")
parse... | 1,882 | 49.891892 | 184 | py |
SELFormer | SELFormer-main/get_embeddings.py | import os
os.environ["TOKENIZERS_PARALLELISM"] = "false"
os.environ["WANDB_DISABLED"] = "true"
os.environ["CUDA_VISIBLE_DEVICES"] = "0"
import pandas as pd
from pandarallel import pandarallel
from transformers import RobertaTokenizer, RobertaModel, RobertaConfig
import torch
df = pd.read_csv("./data/molecule_datase... | 1,367 | 35.972973 | 125 | py |
SELFormer | SELFormer-main/produce_embeddings.py |
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--selfies_dataset", required=True, metavar="/path/to/dataset/", help="Path of the input SEFLIES dataset.")
parser.add_argument("--model_file", required=True, metavar="/path/to/dataset/", help="Path of the pretrained model file.")
parser.add_argum... | 1,820 | 37.744681 | 127 | py |
SELFormer | SELFormer-main/train_regression_model.py | import os
os.environ["TOKENIZER_PARALLELISM"] = "false"
os.environ["WANDB_DISABLED"] = "true"
import numpy as np
import pandas as pd
import torch
from torch.nn import MSELoss
from torch.utils.data import Dataset
from transformers import BertPreTrainedModel, RobertaConfig, RobertaTokenizerFast
from transformers.mod... | 9,117 | 42.21327 | 280 | py |
SELFormer | SELFormer-main/roberta_model.py | import torch
from torch.utils.data.dataset import Dataset
import os
os.environ["TOKENIZERS_PARALLELISM"] = "false"
os.environ["WANDB_DISABLED"] = "true"
class CustomDataset(Dataset):
def __init__(self, df, tokenizer, MAX_LEN):
self.examples = []
for example in df.values:
x = tokeniz... | 3,398 | 35.159574 | 378 | py |
SELFormer | SELFormer-main/binary_class_pred.py | import os
import numpy as np
import pandas as pd
import torch
from torch.nn import CrossEntropyLoss
from torch.utils.data import Dataset
from transformers import BertPreTrainedModel, RobertaConfig, RobertaTokenizerFast
from transformers.models.roberta.modeling_roberta import (
RobertaClassificationHead,
Roberta... | 3,841 | 41.688889 | 189 | py |
SELFormer | SELFormer-main/train_classification_model.py | import os
os.environ["TOKENIZER_PARALLELISM"] = "false"
os.environ["WANDB_DISABLED"] = "true"
import numpy as np
import pandas as pd
import torch
from torch.nn import CrossEntropyLoss
from torch.utils.data import Dataset
from transformers import BertPreTrainedModel, RobertaConfig, RobertaTokenizerFast
from transfo... | 8,348 | 39.529126 | 279 | py |
SELFormer | SELFormer-main/regression_pred.py | import os
import numpy as np
import pandas as pd
import torch
from torch.nn import MSELoss
from torch.utils.data import Dataset
from transformers import BertPreTrainedModel, RobertaConfig, RobertaTokenizerFast
from transformers.models.roberta.modeling_roberta import (
RobertaClassificationHead,
RobertaConfig,
... | 3,863 | 39.673684 | 184 | py |
auraloss | auraloss-main/setup.py | #!/usr/bin/env python3
# Inspired from https://github.com/kennethreitz/setup.py
from pathlib import Path
from setuptools import setup, find_packages
NAME = "auraloss"
DESCRIPTION = "Audio-focused loss functions in PyTorch"
URL = "https://github.com/csteinmetz1/auraloss"
EMAIL = "c.j.steinmetz@qmul.ac.uk"
AUTHOR = "Ch... | 1,235 | 27.090909 | 84 | py |
auraloss | auraloss-main/auraloss/freq.py | import torch
import numpy as np
from typing import List, Any
from .utils import apply_reduction
from .perceptual import SumAndDifference, FIRFilter
class SpectralConvergenceLoss(torch.nn.Module):
"""Spectral convergence loss module.
See [Arik et al., 2018](https://arxiv.org/abs/1808.06719).
"""
def... | 21,505 | 34.429984 | 133 | py |
auraloss | auraloss-main/auraloss/utils.py | import torch
def apply_reduction(losses, reduction="none"):
"""Apply reduction to collection of losses."""
if reduction == "mean":
losses = losses.mean()
elif reduction == "sum":
losses = losses.sum()
return losses
| 249 | 21.727273 | 50 | py |
auraloss | auraloss-main/auraloss/time.py | import torch
from torch import Tensor as T
from .utils import apply_reduction
class ESRLoss(torch.nn.Module):
"""Error-to-signal ratio loss function module.
See [Wright & Välimäki, 2019](https://arxiv.org/abs/1911.08922).
Args:
reduction (string, optional): Specifies the reduction to apply to t... | 7,514 | 35.304348 | 98 | py |
auraloss | auraloss-main/auraloss/perceptual.py | import torch
import numpy as np
class SumAndDifference(torch.nn.Module):
"""Sum and difference signal extraction module."""
def __init__(self):
"""Initialize sum and difference extraction module."""
super(SumAndDifference, self).__init__()
def forward(self, x):
"""Calculate forwa... | 4,769 | 35.136364 | 109 | py |
auraloss | auraloss-main/examples/speech-denoise/train_denoise.py | import torch
import pytorch_lightning as pl
from argparse import ArgumentParser
from tcn import TCNModel
from data import LibriMixDataset
parser = ArgumentParser()
# add PROGRAM level args
parser.add_argument("--root_dir", type=str, default="./data")
parser.add_argument("--sample_rate", type=int, default=8000)
parse... | 1,643 | 28.357143 | 75 | py |
auraloss | auraloss-main/examples/speech-denoise/data.py | import os
import sys
import glob
import torch
import torchaudio
import numpy as np
import soundfile as sf
torchaudio.set_audio_backend("sox_io")
class LibriMixDataset(torch.utils.data.Dataset):
"""LibriMix dataset."""
def __init__(self, root_dir, subset="train", length=16384, noisy=False):
"""
... | 3,337 | 36.931818 | 112 | py |
auraloss | auraloss-main/examples/compressor/train_comp.py | import os
import glob
import torch
import pytorch_lightning as pl
from argparse import ArgumentParser
from tcn import TCNModel
from data import SignalTrainLA2ADataset
parser = ArgumentParser()
# add PROGRAM level args
parser.add_argument("--root_dir", type=str, default="./data")
parser.add_argument("--preload", type... | 2,673 | 26.854167 | 74 | py |
auraloss | auraloss-main/examples/compressor/_test_comp.py | import os
import glob
import json
import torch
import torchsummary
import pytorch_lightning as pl
from argparse import ArgumentParser
from tcn import TCNModel
from data import SignalTrainLA2ADataset
parser = ArgumentParser()
# add PROGRAM level args
parser.add_argument("--root_dir", type=str, default="./data")
parse... | 2,359 | 26.764706 | 86 | py |
auraloss | auraloss-main/examples/compressor/data.py | import os
import sys
import glob
import torch
import torchaudio
import numpy as np
import soundfile as sf
torchaudio.set_audio_backend("sox_io")
class SignalTrainLA2ADataset(torch.utils.data.Dataset):
"""SignalTrain LA2A dataset. Source: [10.5281/zenodo.3824876](https://zenodo.org/record/3824876)."""
def __... | 6,168 | 34.251429 | 117 | py |
auraloss | auraloss-main/examples/compressor/tcn.py | import os
import torch
import torchaudio
import numpy as np
import pytorch_lightning as pl
from argparse import ArgumentParser
import auraloss
def center_crop(x, shape):
start = (x.shape[-1] - shape[-1]) // 2
stop = start + shape[-1]
return x[..., start:stop]
class FiLM(torch.nn.Module):
def __init... | 14,033 | 33.823821 | 124 | py |
auraloss | auraloss-main/tests/test_auraloss.py | import math
import os
import torch
import auraloss
def test_mrstft():
target = torch.rand(8, 2, 44100)
pred = torch.rand(8, 2, 44100)
loss = auraloss.freq.MultiResolutionSTFTLoss()
res = loss(pred, target)
assert res is not None
def test_stft():
target = torch.rand(8, 2, 44100)
pred = t... | 4,998 | 24.120603 | 86 | py |
auraloss | auraloss-main/tests/manual_test_gpu.py | import torch
import auraloss
y_hat = torch.randn(2, 1, 131072)
y = torch.randn(2, 1, 131072)
loss_fn = auraloss.freq.MelSTFTLoss(44100)
loss_fn2 = auraloss.freq.MultiResolutionSTFTLoss()
# loss_fn.cuda()
y_hat = y_hat.cuda()
y = y.cuda()
loss = loss_fn2(y_hat, y)
loss = loss_fn(y_hat, y)
| 294 | 16.352941 | 50 | py |
auraloss | auraloss-main/tests/simple_train_gpu.py | import torch
import auraloss
import torchaudio
from tqdm import tqdm
def center_crop(x, length: int):
start = (x.shape[-1] - length) // 2
stop = start + length
return x[..., start:stop]
def causal_crop(x, length: int):
stop = x.shape[-1] - 1
start = stop - length
return x[..., start:stop]
... | 6,331 | 28.045872 | 124 | py |
RepDistiller | RepDistiller-master/train_student.py | """
the general training framework
"""
from __future__ import print_function
import os
import argparse
import socket
import time
import tensorboard_logger as tb_logger
import torch
import torch.optim as optim
import torch.nn as nn
import torch.backends.cudnn as cudnn
from models import model_dict
from models.util ... | 13,908 | 38.968391 | 118 | py |
RepDistiller | RepDistiller-master/train_teacher.py | from __future__ import print_function
import os
import argparse
import socket
import time
import tensorboard_logger as tb_logger
import torch
import torch.optim as optim
import torch.nn as nn
import torch.backends.cudnn as cudnn
from models import model_dict
from dataset.cifar100 import get_cifar100_dataloaders
fr... | 6,319 | 34.706215 | 118 | py |
RepDistiller | RepDistiller-master/dataset/cifar100.py | from __future__ import print_function
import os
import socket
import numpy as np
from torch.utils.data import DataLoader
from torchvision import datasets, transforms
from PIL import Image
"""
mean = {
'cifar100': (0.5071, 0.4867, 0.4408),
}
std = {
'cifar100': (0.2675, 0.2565, 0.2761),
}
"""
def get_data_f... | 7,927 | 33.77193 | 90 | py |
RepDistiller | RepDistiller-master/dataset/imagenet.py | """
get data loaders
"""
from __future__ import print_function
import os
import socket
import numpy as np
from torch.utils.data import DataLoader
from torchvision import datasets
from torchvision import transforms
def get_data_folder():
"""
return server-dependent path to store the data
"""
hostname ... | 8,053 | 32.983122 | 110 | py |
RepDistiller | RepDistiller-master/models/resnet.py | from __future__ import absolute_import
'''Resnet for cifar dataset.
Ported form
https://github.com/facebook/fb.resnet.torch
and
https://github.com/pytorch/vision/blob/master/torchvision/models/resnet.py
(c) YANG, Wei
'''
import torch.nn as nn
import torch.nn.functional as F
import math
__all__ = ['resnet']
def con... | 7,748 | 29.151751 | 116 | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.