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 |
|---|---|---|---|---|---|---|
pytorch-metric-learning | pytorch-metric-learning-master/tests/losses/test_losses_without_labels.py | import unittest
import torch
from pytorch_metric_learning import losses
from pytorch_metric_learning.miners import MultiSimilarityMiner, TripletMarginMiner
from pytorch_metric_learning.utils.loss_and_miner_utils import get_all_pairs_indices
from .. import TEST_DEVICE
def get_compatible_losses():
return [
... | 2,710 | 34.671053 | 86 | py |
pytorch-metric-learning | pytorch-metric-learning-master/tests/losses/test_vicreg_loss.py | import unittest
import torch
import torch.nn.functional as F
from pytorch_metric_learning.losses import VICRegLoss
from .. import TEST_DEVICE, TEST_DTYPES
HYPERPARAMETERS = [[25, 25, 1, 1e-4], [10, 10, 2, 1e-5], [5, 5, 5, 1e-6]]
class TestVICRegLoss(unittest.TestCase):
def test_vicreg_loss(self):
torc... | 2,582 | 36.985294 | 81 | py |
pytorch-metric-learning | pytorch-metric-learning-master/tests/losses/test_proxy_nca_loss.py | import unittest
import torch
from pytorch_metric_learning.losses import ProxyNCALoss
from .. import TEST_DEVICE, TEST_DTYPES
from ..zzz_testing_utils.testing_utils import angle_to_coord
class TestProxyNCALoss(unittest.TestCase):
def test_proxy_nca_loss(self):
torch.manual_seed(14892)
for dtype ... | 2,262 | 37.355932 | 82 | py |
pytorch-metric-learning | pytorch-metric-learning-master/tests/losses/test_arcface_loss.py | import unittest
import numpy as np
import torch
import torch.nn.functional as F
from pytorch_metric_learning.losses import ArcFaceLoss
from .. import TEST_DEVICE, TEST_DTYPES
from ..zzz_testing_utils.testing_utils import angle_to_coord
class TestArcFaceLoss(unittest.TestCase):
def test_arcface_loss(self):
... | 2,132 | 33.403226 | 87 | py |
pytorch-metric-learning | pytorch-metric-learning-master/tests/losses/test_lifted_structure_loss.py | import unittest
import torch
from pytorch_metric_learning.losses import (
GeneralizedLiftedStructureLoss,
LiftedStructureLoss,
)
from .. import TEST_DEVICE, TEST_DTYPES
from ..zzz_testing_utils.testing_utils import angle_to_coord
class TestLiftedStructure(unittest.TestCase):
def test_lifted_structure_l... | 6,206 | 33.104396 | 88 | py |
pytorch-metric-learning | pytorch-metric-learning-master/tests/trainers/test_key_checking.py | import copy
import logging
import unittest
import torch
from torchvision import datasets
from pytorch_metric_learning.losses import NTXentLoss, TripletMarginLoss
from pytorch_metric_learning.trainers import (
DeepAdversarialMetricLearning,
MetricLossOnly,
TrainWithClassifier,
TwoStreamMetricLoss,
)
fr... | 2,678 | 30.892857 | 72 | py |
pytorch-metric-learning | pytorch-metric-learning-master/tests/trainers/test_metric_loss_only.py | import logging
import os
import shutil
import unittest
import numpy as np
import torch
from torchvision import datasets, transforms
from pytorch_metric_learning.losses import NTXentLoss
from pytorch_metric_learning.reducers import AvgNonZeroReducer
from pytorch_metric_learning.samplers import MPerClassSampler
from py... | 9,629 | 37.674699 | 106 | py |
BRITS | BRITS-master/main.py | import copy
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.optim.lr_scheduler import StepLR
import numpy as np
import time
import utils
import models
import argparse
import data_loader
import pandas as pd
import ujson as json
from sklearn import metrics
fro... | 2,615 | 24.90099 | 141 | py |
BRITS | BRITS-master/data_loader.py | import os
import time
import ujson as json
import numpy as np
import pandas as pd
import torch
import torch.nn as nn
from torch.utils.data import Dataset, DataLoader
class MySet(Dataset):
def __init__(self):
super(MySet, self).__init__()
self.content = open('./json/json').readlines()
ind... | 2,247 | 33.060606 | 131 | py |
BRITS | BRITS-master/utils.py | import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
from torch.autograd import Variable
import pandas as pd
def to_var(var):
if torch.is_tensor(var):
var = Variable(var)
if torch.cuda.is_available():
var = var.cuda()
return var
if... | 922 | 23.289474 | 78 | py |
BRITS | BRITS-master/models/brits_i.py | import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.autograd import Variable
from torch.nn.parameter import Parameter
import math
import utils
import argparse
import data_loader
import rits_i
from sklearn import metrics
from ipdb import set_trace
SEQ_LEN = 36
R... | 2,102 | 23.172414 | 86 | py |
BRITS | BRITS-master/models/rits_i.py | import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.autograd import Variable
from torch.nn.parameter import Parameter
import math
import utils
import argparse
import data_loader
from ipdb import set_trace
from sklearn import metrics
SEQ_LEN = 49
RNN_HID_SIZE = 6... | 3,862 | 27.19708 | 116 | py |
BRITS | BRITS-master/models/rits.py | import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.autograd import Variable
from torch.nn.parameter import Parameter
import math
import utils
import argparse
import data_loader
from ipdb import set_trace
from sklearn import metrics
SEQ_LEN = 49
RNN_HID_SIZE = 6... | 5,649 | 29.213904 | 116 | py |
BRITS | BRITS-master/models/brits.py | import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.autograd import Variable
from torch.nn.parameter import Parameter
import math
import utils
import argparse
import data_loader
import rits
from sklearn import metrics
from ipdb import set_trace
SEQ_LEN = 36
RNN... | 2,096 | 23.103448 | 86 | py |
FaceQAN | FaceQAN-main/src/symmetry.py |
import torch
from torchvision.transforms import transforms
from PIL import Image
def symmetry_estimation(model: torch.nn.Module, image_transform: transforms.Compose, image: Image.Image) -> float:
"""Perfroms the symmetry estimation step from the FaceQAN paper, estimating the effect of head pose on the final qual... | 932 | 36.32 | 130 | py |
FaceQAN | FaceQAN-main/src/bim_attack.py |
import torch
from util import batch_n_noise as attack_initialization
def basic_iterative_method(model: torch.nn.Module, image : torch.Tensor, eps : float=0.001, iter : int=5, batch_size : int=10) -> None:
"""Performs the Basic Iterative Method over FGSM
Args:
model (torch.nn.Module): Face Embedder... | 1,710 | 31.903846 | 135 | py |
FaceQAN | FaceQAN-main/src/util.py |
from collections import OrderedDict
import numpy as np
import torch
from models.Normalize import Normalize
def F(Si : list, sf : float, p : int=5) -> float:
"""Implementation of the aggregation function presented in the FaceQAN paper
Args:
Si (list): List of adversarial similarities.
sf (f... | 2,342 | 31.541667 | 131 | py |
FaceQAN | FaceQAN-main/src/calculate_qs.py |
import sys
sys.path.append("./")
import argparse
import os
import pickle
from PIL import Image
import torch
from torchvision.transforms import transforms
from util import F, load_cosface, add_norm_to_model
from bim_attack import basic_iterative_method as BIM
from symmetry import symmetry_estimation
def __calculat... | 5,418 | 46.535088 | 183 | py |
FaceQAN | FaceQAN-main/src/models/Normalize.py |
import torch
from torchvision.transforms import transforms
class Normalize(torch.nn.Module):
def __init__(self, mean, std):
super(Normalize, self).__init__()
self.mean = torch.tensor(mean).cuda()
self.std = torch.tensor(std).cuda()
def forward(self, input):
x = input
... | 394 | 27.214286 | 65 | py |
FaceQAN | FaceQAN-main/src/models/iresnet.py | import torch
from torch import nn
from torch.utils.checkpoint import checkpoint
"""
CODE SOURCE : https://github.com/deepinsight/insightface/blob/master/recognition/arcface_torch/backbones/iresnet.py
"""
__all__ = ['iresnet18', 'iresnet34', 'iresnet50', 'iresnet100', 'iresnet200']
using_ckpt = False
def conv3x3... | 7,732 | 36 | 119 | py |
hmm-backprop | hmm-backprop-master/setup.py | from setuptools import setup
from torch.utils.cpp_extension import BuildExtension, CppExtension
setup(
name='hmm_forward_cpp',
ext_modules=[
CppExtension('hmm_forward_cpp', ['hmm_forward.cpp', 'log_matmul_kernel.cu']),
],
cmdclass={
'build_ext': BuildExtension
})
| 306 | 22.615385 | 85 | py |
hmm-backprop | hmm-backprop-master/hmm_forward.py | from torch.autograd import Function
import torch
import hmm_forward_cpp
class HMMForward(Function):
@staticmethod
def forward(ctx, potential, lengths, mask):
"""
potential : (B, T, N, N)
The potential for computing messages.
lengths : (B, N)
The lengths in a bat... | 1,053 | 33 | 79 | py |
visualsem | visualsem-master/visualsem_dataset_nodes.py | import sys
import os
import json
import torch
from torch.utils.data import Dataset
from utils import load_visualsem_bnids
class VisualSemNodesDataset(torch.utils.data.Dataset):
"""
Dataset class that can be used to iterate all nodes in VisualSem (linking all data available in a node).
Nodes are as... | 3,429 | 40.325301 | 112 | py |
visualsem | visualsem-master/process_glosses_with_sentencebert.py | import torch
import sys
import os
import random
import json
from collections import defaultdict
import h5py
from sentence_transformers import SentenceTransformer, util
import numpy
import tqdm
from itertools import zip_longest
import argparse
from utils import grouper, load_sentences, load_bnids, load_visualsem_bnids
... | 6,319 | 51.231405 | 138 | py |
visualsem | visualsem-master/combine_sentencebert_glosses.py | import sys
import os
import argparse
from utils import load_bnids
import h5py
if __name__=="__main__":
path_to_glosses = os.path.join(os.path.dirname(os.path.realpath(__file__)), "dataset", "gloss_files")
strategies_list = ['all', 'top8']
# For more details and discussion on VisualSem gloss quality/covera... | 3,837 | 54.623188 | 147 | py |
visualsem | visualsem-master/retrieval_gloss_paper.py | import argparse
import torch
import sys
import os
import json
from collections import defaultdict
import h5py
from sentence_transformers import SentenceTransformer, util
import numpy
import pandas
import tqdm
from itertools import zip_longest
from utils import grouper, load_sentences, load_bnids, load_visualsem_bnids
i... | 11,909 | 50.782609 | 216 | py |
visualsem | visualsem-master/utils.py | import sys
import os
import json
from collections import defaultdict
import tqdm
from itertools import zip_longest
import torch
def grouper(n, iterable, fillvalue=None):
"grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
args = [iter(iterable)] * n
return zip_longest(fillvalue=fillvalue, *args)
def load_sente... | 2,609 | 31.625 | 154 | py |
visualsem | visualsem-master/retrieval_images.py | import sys, os
import json
from collections import defaultdict
import tqdm
import argparse
import numpy
import torch
from clip import clip
from PIL import Image
import spacy
#from spacy.lang.en import English
nlp = spacy.load("en_core_web_trf")
# Create a Tokenizer with the default settings for English
# including punc... | 18,738 | 48.054974 | 151 | py |
visualsem | visualsem-master/retrieval_gloss.py | import argparse
import torch
import sys
import os
import json
from collections import defaultdict
import h5py
from sentence_transformers import SentenceTransformer, util
import numpy
import tqdm
from itertools import zip_longest
from utils import grouper, load_sentences, load_bnids, load_visualsem_bnids
def retrieve_... | 8,020 | 51.084416 | 134 | py |
visualsem | visualsem-master/visualsem_dataset_tuples.py | import sys
import os
import json
import torch
from torch.utils.data import Dataset
class VisualSemTuplesDataset(torch.utils.data.Dataset):
"""
Dataset class that can be used to iterate all tuples in VisualSem.
Each tuple consists of a (h, r, t) entry denoting that
head node `h` is related ... | 1,654 | 32.1 | 86 | py |
visualsem | visualsem-master/dataset_creation/resnet.py | import torch
import torch.nn as nn
from torchvision.models import resnet152
class ResNet152(nn.Module):
def __init__(self):
super().__init__()
resnet = resnet152(pretrained=True)
# Freeze the network
for parameter in resnet.parameters():
parameter.requires_grad = False
... | 538 | 23.5 | 45 | py |
visualsem | visualsem-master/dataset_creation/vgg.py | import torch
import torch.nn as nn
from torchvision.models import vgg19_bn
class VGG19_BN(nn.Module): # With batch normalization
def __init__(self):
super().__init__()
vgg = vgg19_bn(pretrained=True)
# Freeze the network
for parameter in vgg.parameters():
parameter.req... | 634 | 26.608696 | 58 | py |
visualsem | visualsem-master/dataset_creation/lenet.py | #https://github.com/kuangliu/pytorch-cifar/blob/master/models/lenet.py
'''LeNet in PyTorch.'''
import torch.nn as nn
import torch.nn.functional as F
import torch
import torch.optim as optim
class LeNet(nn.Module):
def __init__(self, width=300): # Initialize lenet according to architecture + image width
sup... | 1,128 | 33.212121 | 93 | py |
visualsem | visualsem-master/dataset_creation/forward_pass.py | from torchvision import transforms
from PIL import Image, ImageFile
ImageFile.LOAD_TRUNCATED_IMAGES = True
import torch
import numpy as np
import glob, os
import argparse
from load_data import load_image, get_data
from tqdm import tqdm
from lenet import LeNet
from resnet import ResNet152
from vgg import VGG19_BN
import... | 3,693 | 42.97619 | 170 | py |
visualsem | visualsem-master/dataset_creation/load_data.py | from torchvision import transforms
from PIL import Image
import torch
import numpy as np
import glob, os
def load_image(image_path, width=300, height=300, resize=False, transform=None):
"""Load an image and convert it to a torch tensor.
Input:
- Path to the image
- Desired width of... | 2,511 | 35.941176 | 105 | py |
fewshotlocal | fewshotlocal-master/helpful_files/training.py | import numpy as np
import torch
from copy import deepcopy
from PIL import Image
from torch.utils.data import Sampler
def load_transform(path, boxdict, transform, flipping, masking):
# Load the image
flip = (torch.rand(1)>.5).item()
with open(path, 'rb') as f:
p = Image.open(f)
p = p.conver... | 4,390 | 37.182609 | 111 | py |
fewshotlocal | fewshotlocal-master/helpful_files/testing.py | import numpy as np
import torch
import pylab as pl
from time import sleep
from IPython import display
from copy import deepcopy
from PIL import Image
from torch.utils.data import Sampler
from helpful_files.networks import fbpredict, predict
def load_transform(path, boxdict, transform, masking):
# Load the image
... | 7,786 | 31.177686 | 131 | py |
fewshotlocal | fewshotlocal-master/helpful_files/networks.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.parameter import Parameter
class Block(nn.Module):
def __init__(self, insize, outsize):
super(Block, self).__init__()
self.layers = nn.Sequential(
nn.Conv2d(insize, outsize, kernel_size=3, padding=1, bias=... | 10,375 | 38.603053 | 117 | py |
GeoDiff | GeoDiff-main/eval_covmat.py.py | import os
import argparse
import pickle
import torch
from utils.datasets import PackedConformationDataset
from utils.evaluation.covmat import CovMatEvaluator, print_covmat_results
from utils.misc import *
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('path', type=str)
... | 1,449 | 28.591837 | 83 | py |
GeoDiff | GeoDiff-main/test.py | import os
import argparse
import pickle
import yaml
import torch
from glob import glob
from tqdm.auto import tqdm
from easydict import EasyDict
from models.epsnet import *
from utils.datasets import *
from utils.transforms import *
from utils.misc import *
def num_confs(num:str):
if num.endswith('x'):
re... | 6,050 | 37.297468 | 108 | py |
GeoDiff | GeoDiff-main/eval_prop.py | import os
import pickle
import argparse
import torch
import numpy as np
from psikit import Psikit
from tqdm.auto import tqdm
from easydict import EasyDict
from torch_geometric.data import Data
from utils.datasets import PackedConformationDataset
from utils.chem import set_rdmol_positions
class PropertyCalculator(obj... | 5,248 | 29.876471 | 113 | py |
GeoDiff | GeoDiff-main/train.py | import os
import shutil
import argparse
import yaml
from easydict import EasyDict
from tqdm.auto import tqdm
from glob import glob
import torch
import torch.utils.tensorboard
from torch.nn.utils import clip_grad_norm_
from torch_geometric.data import DataLoader
from models.epsnet import get_model
from utils.datasets i... | 7,796 | 41.145946 | 176 | py |
GeoDiff | GeoDiff-main/models/common.py | # coding=utf-8
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch_geometric.nn import radius_graph, radius
from torch_scatter import scatter_mean, scatter_add, scatter_max
from torch_sparse import coalesce
from torch_geometric.utils import to_dense_adj, dense_to_sparse
from utils.chem import... | 10,634 | 34.687919 | 117 | py |
GeoDiff | GeoDiff-main/models/geometry.py | import torch
from torch_scatter import scatter_add
def get_distance(pos, edge_index):
return (pos[edge_index[0]] - pos[edge_index[1]]).norm(dim=-1)
def eq_transform(score_d, pos, edge_index, edge_length):
N = pos.size(0)
dd_dr = (1. / edge_length) * (pos[edge_index[0]] - pos[edge_index[1]]) # (E, 3)
... | 2,014 | 32.032787 | 117 | py |
GeoDiff | GeoDiff-main/models/epsnet/diffusion.py | import os, time
import math
import numpy as np
import torch
def get_timestep_embedding(timesteps, embedding_dim):
"""
This matches the implementation in Denoising Diffusion Probabilistic Models:
From Fairseq.
Build sinusoidal embeddings.
This matches the implementation in tensor2tensor, but differ... | 2,091 | 32.206349 | 87 | py |
GeoDiff | GeoDiff-main/models/epsnet/dualenc.py | import torch
from torch import nn
from torch_scatter import scatter_add, scatter_mean
from torch_scatter import scatter
from torch_geometric.data import Data, Batch
import numpy as np
from numpy import pi as PI
from tqdm.auto import tqdm
from utils.chem import BOND_TYPES
from ..common import MultiLayerPerceptron, asse... | 30,482 | 46.187307 | 156 | py |
GeoDiff | GeoDiff-main/models/encoder/gin.py | # coding=utf-8
from typing import Callable, Union
from torch_geometric.typing import OptPairTensor, Adj, OptTensor, Size
import torch
from torch import Tensor
import torch.nn as nn
import torch.nn.functional as F
from torch_sparse import SparseTensor, matmul
from torch_geometric.nn.conv import MessagePassing
from ..c... | 4,016 | 32.198347 | 104 | py |
GeoDiff | GeoDiff-main/models/encoder/coarse.py | import torch
from torch.nn import Module
from torch_scatter import scatter_add, scatter_mean, scatter_max
from ..common import coarse_grain, batch_to_natoms, get_complete_graph
from .schnet import SchNetEncoder, GaussianSmearing
class CoarseGrainingEncoder(Module):
def __init__(self, hidden_channels, num_filter... | 1,679 | 31.941176 | 102 | py |
GeoDiff | GeoDiff-main/models/encoder/schnet.py | import torch
import torch.nn.functional as F
from torch.nn import Module, Sequential, ModuleList, Linear, Embedding
from torch_geometric.nn import MessagePassing, radius_graph
from torch_sparse import coalesce
from torch_geometric.data import Data
from torch_geometric.utils import to_dense_adj, dense_to_sparse
from mat... | 5,295 | 33.842105 | 98 | py |
GeoDiff | GeoDiff-main/models/encoder/edge.py | import torch
import torch.nn.functional as F
from torch.nn import Module, Sequential, ModuleList, Linear, Embedding
from torch_geometric.nn import MessagePassing, radius_graph
from torch_sparse import coalesce
from torch_geometric.data import Data
from torch_geometric.utils import to_dense_adj, dense_to_sparse
from mat... | 2,596 | 34.575342 | 132 | py |
GeoDiff | GeoDiff-main/utils/misc.py | import os
import time
import random
import logging
import torch
import numpy as np
from glob import glob
from logging import Logger
from tqdm.auto import tqdm
from torch_geometric.data import Batch
class BlackHole(object):
def __setattr__(self, name, value):
pass
def __call__(self, *args, **kwargs):
... | 2,760 | 25.805825 | 102 | py |
GeoDiff | GeoDiff-main/utils/chem.py | from copy import deepcopy
import torch
from torchvision.transforms.functional import to_tensor
import rdkit
import rdkit.Chem.Draw
from rdkit import Chem
from rdkit.Chem import rdDepictor as DP
from rdkit.Chem import PeriodicTable as PT
from rdkit.Chem import rdMolAlign as MA
from rdkit.Chem.rdchem import BondType as B... | 3,650 | 25.266187 | 87 | py |
GeoDiff | GeoDiff-main/utils/datasets.py | import os
import pickle
import copy
import json
from collections import defaultdict
import numpy as np
import random
import torch
from torch_geometric.data import Data, Dataset, Batch
from torch_geometric.utils import to_networkx
from torch_scatter import scatter
#from torch.utils.data import Dataset
import rdkit
f... | 34,889 | 33.613095 | 169 | py |
GeoDiff | GeoDiff-main/utils/common.py | import copy
import warnings
import numpy as np
import torch
import torch.nn as nn
from torch_geometric.data import Data, Batch
#customize exp lr scheduler with min lr
class ExponentialLR_with_minLr(torch.optim.lr_scheduler.ExponentialLR):
def __init__(self, optimizer, gamma, min_lr=1e-4, last_epoch=-1, verbose=F... | 2,468 | 31.064935 | 97 | py |
GeoDiff | GeoDiff-main/utils/transforms.py | import copy
import torch
from torch_geometric.data import Data
from torch_geometric.transforms import Compose
from torch_geometric.utils import to_dense_adj, dense_to_sparse
from torch_sparse import coalesce
from .chem import BOND_TYPES, BOND_NAMES, get_atom_symbol
class AddHigherOrderEdges(object):
def __init_... | 5,885 | 35.110429 | 134 | py |
GeoDiff | GeoDiff-main/utils/evaluation/covmat.py | import torch
import numpy as np
import pandas as pd
import multiprocessing as mp
from torch_geometric.data import Data
from functools import partial
from easydict import EasyDict
from tqdm.auto import tqdm
from rdkit import Chem
from rdkit.Chem.rdForceFieldHelpers import MMFFOptimizeMolecule
from ..chem import set_rd... | 5,397 | 38.115942 | 117 | py |
DataFree | DataFree-main/train_scratch.py | import argparse
import os
import random
import time
import warnings
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.distributed as dist
import torch.optim
import torch.multiprocessing as mp
import torch.utils.data
import torch.utils.data.distributed
from da... | 16,965 | 45.482192 | 197 | py |
DataFree | DataFree-main/registry.py | from datafree.models import classifiers, deeplab
from torchvision import datasets, transforms as T
from datafree.utils import sync_transforms as sT
from PIL import PngImagePlugin
LARGE_ENOUGH_NUMBER = 100
PngImagePlugin.MAX_TEXT_CHUNK = LARGE_ENOUGH_NUMBER * (1024**2)
import os
import torch
import torchvision
import... | 15,485 | 42.016667 | 159 | py |
DataFree | DataFree-main/datafree_kd.py | import argparse
from math import gamma
import os
import random
import shutil
import time
from datetime import timedelta
import warnings
import registry
import datafree
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.nn.parallel
import torch.backends.cudnn as cudnn
i... | 43,067 | 49.787736 | 394 | py |
DataFree | DataFree-main/vanilla_kd.py | import argparse
import os
import random
import shutil
import time
import warnings
from datetime import timedelta
import registry
import datafree
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.distributed as dist
import torch.optim
import torch.multiproces... | 20,470 | 48.327711 | 215 | py |
DataFree | DataFree-main/datafree/hooks.py | import torch
import torch.nn as nn
import torch.nn.functional as F
def register_hooks(modules):
hooks = []
for m in modules:
hooks.append( FeatureHook(m) )
return hooks
class InstanceMeanHook(object):
def __init__(self, module):
self.hook = module.register_forward_hook(self.hook_fn)
... | 2,918 | 29.092784 | 94 | py |
DataFree | DataFree-main/datafree/evaluators.py | from tqdm import tqdm
import torch.nn.functional as F
import torch
from . import metrics
class Evaluator(object):
def __init__(self, metric, dataloader):
self.dataloader = dataloader
self.metric = metric
# self.logit_kl_metric = logit_kl_metric
def eval(self, model, device=None, progr... | 6,206 | 38.535032 | 107 | py |
DataFree | DataFree-main/datafree/criterions.py | import torch
import torch.nn.functional as F
import torch.nn as nn
def kldiv( logits, targets, T=1.0, reduction='batchmean'):
q = F.log_softmax(logits/T, dim=1)
p = F.softmax( targets/T, dim=1 )
return F.kl_div( q, p, reduction=reduction ) * (T*T)
class KLDiv(nn.Module):
def __init__(self, T=1.0, redu... | 1,993 | 38.88 | 118 | py |
DataFree | DataFree-main/datafree/rep_transfer.py | import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
class HintLoss(nn.Module):
"""Convolutional regression for FitNet"""
def __init__(self, s_shapes, t_shapes, use_relu=False, loss_fn=F.mse_loss):
super(HintLoss, self).__init__()
self.use_relu = use_relu
... | 7,293 | 38.427027 | 111 | py |
DataFree | DataFree-main/datafree/synthesis/base.py | import torch
import torch.nn as nn
from abc import ABC, abstractclassmethod
from typing import Dict
class BaseSynthesis(ABC):
def __init__(self, teacher, student):
super(BaseSynthesis, self).__init__()
self.teacher = teacher
self.student = student
@abstractclassmethod
def synth... | 670 | 28.173913 | 100 | py |
DataFree | DataFree-main/datafree/synthesis/dfme.py | import torch
import torch.nn as nn
import torch.nn.functional as F
import random
from .base import BaseSynthesis
from datafree.criterions import kldiv
from datafree.utils import ImagePool, DataIter, estimate_gradient_objective, compute_gradient, clip_images
class DFMESynthesizer(BaseSynthesis):
def __init__(self,... | 3,071 | 42.267606 | 374 | py |
DataFree | DataFree-main/datafree/synthesis/pretrained_G.py | import torch
from .base import BaseSynthesis
from datafree.utils import UnlabelBufferDataset, ImagePool, DataIter
import torchvision.transforms as T
# from datafree.models.score_sde import sampling, configs
# from datafree.models.score_sde.sampling import (ReverseDiffusionPredictor,
# LangevinCo... | 5,838 | 44.976378 | 260 | py |
DataFree | DataFree-main/datafree/synthesis/deepinversion.py | import torch
import torch.nn as nn
import torch.nn.functional as F
import random
from .base import BaseSynthesis
from datafree.hooks import DeepInversionHook
from datafree.criterions import jsdiv, get_image_prior_losses
from datafree.utils import ImagePool, DataIter, clip_images
def jitter_and_flip(inputs_jit, lim=1.... | 5,602 | 39.309353 | 118 | py |
DataFree | DataFree-main/datafree/synthesis/zskd.py | import torch
import torch.nn as nn
import torch.nn.functional as F
import random
from torch.distributions import Dirichlet
from .base import BaseSynthesis
from .deepinversion import jitter_and_flip
from datafree.utils import ImagePool, clip_images, DataIter
def compute_simiarity(x, scale=1.0):
x = F.normalize(x, ... | 3,972 | 40.385417 | 233 | py |
DataFree | DataFree-main/datafree/synthesis/contrastive.py | import datafree
from typing import Generator
import torch
from torch import optim
import torch.nn as nn
import torch.nn.functional as F
import random
from .base import BaseSynthesis
from datafree.hooks import DeepInversionHook, InstanceMeanHook
from datafree.criterions import jsdiv, get_image_prior_losses, kldiv
from ... | 15,425 | 41.731302 | 134 | py |
DataFree | DataFree-main/datafree/synthesis/generative.py | import torch
import torch.nn as nn
import torch.nn.functional as F
import random
from .base import BaseSynthesis
from datafree.hooks import DeepInversionHook
from datafree.criterions import kldiv, get_image_prior_losses
from datafree.utils import ImagePool, DataIter, clip_images
class GenerativeSynthesizer(BaseSynthe... | 3,369 | 39.60241 | 130 | py |
DataFree | DataFree-main/datafree/synthesis/softtarget.py | from inspect import signature
from attr import has
import torch
from torch import nn
import torch.nn.functional as F
import random
from .base import BaseSynthesis
from datafree.utils import ImagePool, DataIter, clip_images
from .deepinversion import jitter_and_flip
class SoftTargetSynthesizer(BaseSynthesis):
def ... | 5,956 | 40.368056 | 118 | py |
DataFree | DataFree-main/datafree/synthesis/cudfkd.py | from torch import nn
import torch
import torch.nn.functional as F
import random
import os
import shutil
from .base import BaseSynthesis
import datafree
from datafree.hooks import DeepInversionHook
from datafree.utils import ImagePool, DataIter, clip_images
from datafree.criterions import jsdiv, kldiv
from datafree.dat... | 7,293 | 38.427027 | 372 | py |
DataFree | DataFree-main/datafree/models/generator.py | import torch
import torch.nn as nn
import torch.nn.functional as F
class Flatten(nn.Module):
def __init__(self):
super(Flatten, self).__init__()
def forward(self, x):
return torch.flatten(x, 1)
class Generator(nn.Module): # Used for tiny resnet or wider-resnet, mainly for cifar10
def __in... | 18,576 | 35.568898 | 147 | py |
DataFree | DataFree-main/datafree/models/stylegan_generator.py | # python3.7
"""Contains the implementation of generator described in StyleGAN.
Paper: https://arxiv.org/pdf/1812.04948.pdf
Official TensorFlow implementation: https://github.com/NVlabs/stylegan
"""
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.distributed as dis... | 36,146 | 41.129371 | 80 | py |
DataFree | DataFree-main/datafree/models/deeplab/_deeplab.py | import torch
from torch import nn
from torch.nn import functional as F
from .utils import _SimpleSegmentationModel
__all__ = ["DeepLabV3"]
class DeepLabV3(_SimpleSegmentationModel):
"""
Implements DeepLabV3 model from
`"Rethinking Atrous Convolution for Semantic Image Segmentation"
<https://arxiv.o... | 6,709 | 36.696629 | 157 | py |
DataFree | DataFree-main/datafree/models/deeplab/utils.py | import torch
import torch.nn as nn
import numpy as np
import torch.nn.functional as F
from collections import OrderedDict
class _SimpleSegmentationModel(nn.Module):
def __init__(self, backbone, classifier):
super(_SimpleSegmentationModel, self).__init__()
self.backbone = backbone
self.class... | 2,990 | 37.844156 | 89 | py |
DataFree | DataFree-main/datafree/models/deeplab/backbone/resnet.py | import torch
import torch.nn as nn
from torchvision.models.utils import load_state_dict_from_url
__all__ = ['ResNet', 'resnet18', 'resnet34', 'resnet50', 'resnet101',
'resnet152', 'resnext50_32x4d', 'resnext101_32x8d',
'wide_resnet50_2', 'wide_resnet101_2']
model_urls = {
'resnet18': 'http... | 13,574 | 38.462209 | 107 | py |
DataFree | DataFree-main/datafree/models/deeplab/backbone/mobilenetv2.py | from torch import nn
from torchvision.models.utils import load_state_dict_from_url
import torch.nn.functional as F
__all__ = ['MobileNetV2', 'mobilenet_v2']
model_urls = {
'mobilenet_v2': 'https://download.pytorch.org/models/mobilenet_v2-b0353104.pth',
}
def _make_divisible(v, divisor, min_value=None):
"""... | 6,922 | 35.824468 | 123 | py |
DataFree | DataFree-main/datafree/models/glow/glow_g.py | import math
import torch
import torch.nn as nn
from .module import (
Conv2d,
Conv2dZeros,
ActNorm2d,
InvertibleConv1x1,
Permute2d,
LinearZeros,
SqueezeLayer,
Split2d,
gaussian_likelihood,
gaussian_sample,
)
from .utils import split_feature, uniform_binning_correction
def get_... | 9,470 | 28.689655 | 87 | py |
DataFree | DataFree-main/datafree/models/glow/utils.py | import math
import torch
def compute_same_pad(kernel_size, stride):
if isinstance(kernel_size, int):
kernel_size = [kernel_size]
if isinstance(stride, int):
stride = [stride]
assert len(stride) == len(
kernel_size
), "Pass kernel size and stride both as int, or both as equal ... | 1,204 | 25.777778 | 82 | py |
DataFree | DataFree-main/datafree/models/glow/module.py | import math
import torch
import torch.nn as nn
import torch.nn.functional as F
from .utils import split_feature, compute_same_pad
def gaussian_p(mean, logs, x):
"""
lnL = -1/2 * { ln|Var| + ((X - Mu)^T)(Var^-1)(X - Mu) + kln(2*PI) }
k = 1 (Independent)
Var = logs ** 2
"""
c =... | 11,244 | 28.056848 | 87 | py |
DataFree | DataFree-main/datafree/models/score_sde/sampling.py | # Copyright 2020 The Google Research Authors.
#
# 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 agree... | 17,554 | 36.192797 | 116 | py |
DataFree | DataFree-main/datafree/models/score_sde/datasets.py | """Return training and evaluation/test datasets from config files."""
import jax
import tensorflow as tf
import tensorflow_datasets as tfds
def get_data_scaler(config):
"""Data normalizer. Assume data are always in [0, 1]."""
if config.data.centered:
# Rescale to [-1, 1]
return lambda x: x * 2. - 1.
els... | 6,607 | 35.711111 | 99 | py |
DataFree | DataFree-main/datafree/models/score_sde/sde_lib.py | """Abstract SDE classes, Reverse SDE, and VE/VP SDEs."""
import abc
import torch
import numpy as np
class SDE(abc.ABC):
"""SDE abstract class. Functions are designed for a mini-batch of inputs."""
def __init__(self, N):
"""Construct an SDE.
Args:
N: number of discretization time steps.
"""
... | 7,544 | 29.922131 | 123 | py |
DataFree | DataFree-main/datafree/models/score_sde/models/up_or_down_sampling.py | """Layers used for up-sampling or down-sampling images.
Many functions are ported from https://github.com/NVlabs/stylegan2.
"""
import torch.nn as nn
import torch
import torch.nn.functional as F
import numpy as np
import sys
sys.path.append('/data/lijingru/DataFree/datafree/models/score_sde')
from op import upfirdn2d... | 8,980 | 33.542308 | 91 | py |
DataFree | DataFree-main/datafree/models/score_sde/models/utils.py | # coding=utf-8
# Copyright 2020 The Google Research Authors.
#
# 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 applicab... | 5,764 | 29.183246 | 105 | py |
DataFree | DataFree-main/datafree/models/score_sde/models/layers.py | # coding=utf-8
# Copyright 2020 The Google Research Authors.
#
# 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 applicab... | 22,687 | 33.271903 | 112 | py |
DataFree | DataFree-main/datafree/models/score_sde/models/ddpm.py | # coding=utf-8
# Copyright 2020 The Google Research Authors.
#
# 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 applicab... | 6,082 | 32.423077 | 113 | py |
DataFree | DataFree-main/datafree/models/score_sde/models/ncsnv2.py | # coding=utf-8
# Copyright 2020 The Google Research Authors.
#
# 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 applicab... | 16,043 | 37.567308 | 120 | py |
DataFree | DataFree-main/datafree/models/score_sde/models/normalization.py | # coding=utf-8
# Copyright 2020 The Google Research Authors.
#
# 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 applicab... | 7,657 | 34.453704 | 106 | py |
DataFree | DataFree-main/datafree/models/score_sde/models/ema.py | # Modified from https://raw.githubusercontent.com/fadel/pytorch_ema/master/torch_ema/ema.py
from __future__ import division
from __future__ import unicode_literals
import torch
# Partially based on: https://github.com/tensorflow/tensorflow/blob/r1.13/tensorflow/python/training/moving_averages.py
class ExponentialMo... | 3,414 | 33.846939 | 119 | py |
DataFree | DataFree-main/datafree/models/score_sde/models/ncsnpp.py | # coding=utf-8
# Copyright 2020 The Google Research Authors.
#
# 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 applicab... | 13,653 | 34.743455 | 113 | py |
DataFree | DataFree-main/datafree/models/score_sde/models/layerspp.py | # coding=utf-8
# Copyright 2020 The Google Research Authors.
#
# 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 applicab... | 9,001 | 31.734545 | 99 | py |
DataFree | DataFree-main/datafree/models/score_sde/configs/default_cifar10_configs.py | # import sys
import ml_collections
import torch
def get_default_configs():
config = ml_collections.ConfigDict()
# training
config.training = training = ml_collections.ConfigDict()
config.training.batch_size = 128
training.n_iters = 1300001
training.snapshot_freq = 50000
training.log_freq = 50
trainin... | 1,961 | 25.513514 | 94 | py |
DataFree | DataFree-main/datafree/models/score_sde/configs/default_celeba_configs.py | import ml_collections
import torch
def get_default_configs():
config = ml_collections.ConfigDict()
# training
config.training = training = ml_collections.ConfigDict()
config.training.batch_size = 128
training.n_iters = 1300001
training.snapshot_freq = 50000
training.log_freq = 50
training.eval_freq = ... | 1,947 | 26.055556 | 94 | py |
DataFree | DataFree-main/datafree/models/score_sde/configs/default_lsun_configs.py | import ml_collections
import torch
def get_default_configs():
config = ml_collections.ConfigDict()
# training
config.training = training = ml_collections.ConfigDict()
config.training.batch_size = 64
training.n_iters = 2400001
training.snapshot_freq = 50000
training.log_freq = 50
training.eval_freq = 1... | 1,944 | 26.013889 | 94 | py |
DataFree | DataFree-main/datafree/models/score_sde/configs/ve/ffhq_ncsnpp_continuous.py | # coding=utf-8
# Copyright 2020 The Google Research Authors.
#
# 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 applicab... | 3,229 | 28.099099 | 94 | py |
DataFree | DataFree-main/datafree/models/score_sde/configs/ve/celebahq_ncsnpp_continuous.py | # coding=utf-8
# Copyright 2020 The Google Research Authors.
#
# 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 applicab... | 3,184 | 27.693694 | 94 | py |
DataFree | DataFree-main/datafree/models/score_sde/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__)
# print('*******1')
upfirdn2d_op = load(
"upfirdn2d",
sources=[
os.path.join(module_path, "upfirdn2d.cpp"),
os.pat... | 5,712 | 27.142857 | 108 | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.