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
CoMP
CoMP-main/comp/pl/comp.py
import logging import pytorch_lightning as pl import torch import torch.distributions as dist LARGE_NEGATIVE = -10000000.0 LOGGER = logging.getLogger(__name__) LOGGER.setLevel(logging.INFO) def pairwise_label_mask(m: torch.Tensor) -> torch.Tensor: """ Convert a batch_size x n_classes tensor, where each row ...
5,207
31.962025
102
py
CoMP
CoMP-main/comp/pl/cvae.py
import logging import pytorch_lightning as pl import torch import torch.distributions as tdist from comp.nn.loss import GroupwiseMMD, RBF LOGGER = logging.getLogger(__name__) LOGGER.setLevel(logging.INFO) class CVAE(pl.LightningModule): """Conditional VAE with flexible encoder and decoder""" def __init__(...
3,219
30.568627
87
py
CoMP
CoMP-main/comp/pl/trainer.py
from pytorch_lightning.callbacks import EarlyStopping, LambdaCallback, ModelCheckpoint from pytorch_lightning.loggers import TensorBoardLogger from pytorch_lightning.trainer import Trainer def create_trainer( output_dir, num_epochs, gpus, checkpoint_metric_name, checkpoint_save_k=1, checkpoint...
1,797
32.296296
101
py
CoMP
CoMP-main/comp/data/loaders.py
import logging import os import pandas as pd from sklearn.preprocessing import OneHotEncoder import torch from torch.utils.data import ( DataLoader, TensorDataset, random_split, ) LOGGER = logging.getLogger(__name__) LOGGER.setLevel(logging.INFO) def extract_labels(metadata_df, use_cuda): labels = t...
2,356
27.39759
90
py
bitwise-weight-training
bitwise-weight-training-main/localFunctions.py
import tensorflow as tf import uuid def fill_with_predefined(src): def initializer(shape, dtype=None): return tf.Variable(src, dtype=dtype, name=uuid.uuid4().hex) return initializer def activate(x, activationtype): if activationtype is None: return x if 'relu' in activationtype: ...
1,032
18.490566
67
py
bitwise-weight-training
bitwise-weight-training-main/ResNetBuilder.py
import tensorflow import tensorflow.keras from tensorflow.keras.layers import AveragePooling2D, Input, Flatten from tensorflow.keras.layers import BatchNormalization, Activation from tensorflow.keras.models import Model from localLayers import QuantizedConv2D, QuantizedDense from localFunctions import activate def re...
5,834
37.642384
148
py
bitwise-weight-training
bitwise-weight-training-main/localLayers.py
import utils import tensorflow as tf from tensorflow.keras.layers import Layer from tensorflow.keras import backend as KB from localFunctions import to_bit, to_sign, activate, fill_with_predefined import numpy as np def calc_scaling_factor(k, target): current_std = np.std(k) if current_std == 0: prin...
11,711
38.302013
153
py
bitwise-weight-training
bitwise-weight-training-main/Trainer.py
import argparse import os parser = argparse.ArgumentParser() parser.add_argument('--gpu', type=int, default=0) args = parser.parse_args() os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' # or any {'0', '1', '2'} os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID" os.environ["CUDA_VISIBLE_DEVICES"] = str(args.gpu) import utils, ...
21,152
37.320652
175
py
stylegan-v
stylegan-v-master/src/legacy.py
# 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, reproduction, disclosure or # distribution of this software and re...
16,515
50.451713
154
py
stylegan-v
stylegan-v-master/src/train.py
# 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, reproduction, disclosure or # distribution of this software and rel...
20,428
43.997797
207
py
stylegan-v
stylegan-v-master/src/training/mocogan.py
import functools from typing import Tuple, List, Dict import numpy as np from torch import Tensor import torch import torch.nn as nn from omegaconf import DictConfig, OmegaConf from src.torch_utils import persistence from src.training.networks import Discriminator as ImageDiscriminator #-----------------------------...
10,780
35.545763
160
py
stylegan-v
stylegan-v-master/src/training/logging.py
import os from typing import List, Callable, Optional, Dict from multiprocessing.pool import ThreadPool from PIL import Image import torch from torch import Tensor import numpy as np import cv2 from tqdm import tqdm from torchvision import utils import torchvision.transforms.functional as TVF #-----------------------...
6,110
41.734266
132
py
stylegan-v
stylegan-v-master/src/training/loss.py
# 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, reproduction, disclosure or # distribution of this software and re...
9,892
55.210227
164
py
stylegan-v
stylegan-v-master/src/training/augment.py
# 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, reproduction, disclosure or # distribution of this software and re...
26,649
59.983982
366
py
stylegan-v
stylegan-v-master/src/training/dataset.py
# 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, reproduction, disclosure or # distribution of this software and re...
20,180
39.605634
198
py
stylegan-v
stylegan-v-master/src/training/networks.py
# 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, reproduction, disclosure or # distribution of this software and re...
34,316
49.764793
159
py
stylegan-v
stylegan-v-master/src/training/layers.py
import random from typing import Dict, Optional, Tuple import torch import torch.nn as nn import torch.nn.functional as F import numpy as np from omegaconf import DictConfig from src.torch_utils import persistence from src.torch_utils.ops import bias_act, upfirdn2d, conv2d_resample from src.torch_utils import misc #...
19,389
42.184855
164
py
stylegan-v
stylegan-v-master/src/training/training_loop.py
# 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, reproduction, disclosure or # distribution of this software and re...
30,166
51.647469
195
py
stylegan-v
stylegan-v-master/src/training/motion.py
from typing import Dict import numpy as np import torch import torch.nn as nn from omegaconf import DictConfig from src.torch_utils import misc from src.torch_utils import persistence from src.training.layers import ( MappingNetwork, EqLRConv1d, FullyConnectedLayer, ) #-----------------------------------...
12,147
52.991111
173
py
stylegan-v
stylegan-v-master/src/torch_utils/custom_ops.py
# 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, reproduction, disclosure or # distribution of this software and rel...
5,644
43.448819
146
py
stylegan-v
stylegan-v-master/src/torch_utils/training_stats.py
# 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, reproduction, disclosure or # distribution of this software and rel...
10,716
38.840149
118
py
stylegan-v
stylegan-v-master/src/torch_utils/persistence.py
# 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, reproduction, disclosure or # distribution of this software and re...
9,721
37.579365
144
py
stylegan-v
stylegan-v-master/src/torch_utils/misc.py
# 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, reproduction, disclosure or # distribution of this software and re...
11,817
41.974545
145
py
stylegan-v
stylegan-v-master/src/torch_utils/ops/bias_act.py
# 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, reproduction, disclosure or # distribution of this software and rel...
10,056
46.215962
185
py
stylegan-v
stylegan-v-master/src/torch_utils/ops/grid_sample_gradfix.py
# 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, reproduction, disclosure or # distribution of this software and rel...
3,299
38.285714
138
py
stylegan-v
stylegan-v-master/src/torch_utils/ops/conv2d_gradfix.py
# 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, reproduction, disclosure or # distribution of this software and rel...
7,685
43.947368
197
py
stylegan-v
stylegan-v-master/src/torch_utils/ops/upfirdn2d.py
# 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, reproduction, disclosure or # distribution of this software and rel...
16,287
41.306494
157
py
stylegan-v
stylegan-v-master/src/torch_utils/ops/conv2d_resample.py
# 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, reproduction, disclosure or # distribution of this software and rel...
7,591
47.356688
130
py
stylegan-v
stylegan-v-master/src/torch_utils/ops/fma.py
# 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, reproduction, disclosure or # distribution of this software and rel...
2,034
32.360656
105
py
stylegan-v
stylegan-v-master/src/deps/facial_recognition/model_irse.py
""" Copy-pasted from https://github.com/orpatashnik/StyleCLIP/tree/main/models/facial_recognition/model_irse.py """ from torch.nn import Linear, Conv2d, BatchNorm1d, BatchNorm2d, PReLU, Dropout, Sequential, Module from .helpers import get_blocks, Flatten, bottleneck_IR, bottleneck_IR_SE, l2_norm """ Modified Backbone ...
3,427
37.516854
107
py
stylegan-v
stylegan-v-master/src/deps/facial_recognition/helpers.py
""" Copy-pasted from https://github.com/orpatashnik/StyleCLIP/tree/main/models/facial_recognition/helpers.py """ from collections import namedtuple import torch from torch.nn import Conv2d, BatchNorm2d, PReLU, ReLU, Sigmoid, MaxPool2d, AdaptiveAvgPool2d, Sequential, Module """ ArcFace implementation from [TreB1eN](ht...
4,234
33.153226
112
py
stylegan-v
stylegan-v-master/src/infra/launch.py
""" Run a __reproducible__ experiment on __allocated__ resources It submits a slurm job(s) with the given hyperparams which will then execute `slurm_job.py` This is the main entry-point """ import os import subprocess import re import hydra from omegaconf import DictConfig, OmegaConf from pathlib import Path from sr...
4,736
41.294643
173
py
stylegan-v
stylegan-v-master/src/scripts/convert_videos_to_frames.py
""" Converts a dataset of mp4 videos into a dataset of video frames I.e. a directory of mp4 files becomes a directory of directories of frames This speeds up loading during training because we do not need """ import os from typing import List import argparse from pathlib import Path from multiprocessing import Pool fro...
3,975
36.509434
137
py
stylegan-v
stylegan-v-master/src/scripts/generate.py
"""Generates a dataset of images using pretrained network pickle.""" import sys; sys.path.extend(['.', 'src']) import os import json import random import warnings import click from src import dnnlib import numpy as np import torch from tqdm import tqdm from omegaconf import OmegaConf import legacy from src.training....
7,858
50.366013
180
py
stylegan-v
stylegan-v-master/src/scripts/calc_metrics_for_dataset.py
# 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, reproduction, disclosure or # distribution of this software and rel...
6,770
38.829412
146
py
stylegan-v
stylegan-v-master/src/scripts/project.py
""" Given a dataset of images, it (optionally crops it) and embeds into the model Also optionally generates random videos from the found w """ import sys; sys.path.extend(['.', 'src']) import os import re import json import random from typing import List, Optional, Callable from typing import List from PIL import Ima...
20,765
42.2625
146
py
stylegan-v
stylegan-v-master/src/scripts/profile_model.py
""" This script computes imgs/sec for a generator in the eval mode for different batch sizes """ import sys; sys.path.extend(['..', '.', 'src']) import time import numpy as np import torch import torch.nn as nn import hydra from hydra.experimental import initialize from omegaconf import DictConfig, OmegaConf from tqdm...
3,655
33.819048
153
py
stylegan-v
stylegan-v-master/src/scripts/frames_to_video_grid.py
""" Converts a directory of video frames into an mp4-grid """ import sys; sys.path.extend(['.']) import os import argparse import random import numpy as np import torch from torch import Tensor import torchvision.transforms.functional as TVF from torchvision import utils from PIL import Image from tqdm import tqdm imp...
3,209
39.632911
166
py
stylegan-v
stylegan-v-master/src/scripts/clip_edit.py
# import sys; sys.path.extend(['.', 'src', '/home/skoroki/StyleCLIP']) import argparse import math import os from typing import List import json import re import random import yaml import itertools import torchvision from torch import optim from PIL import Image import click import numpy as np import torch from tqdm i...
15,919
38.405941
161
py
stylegan-v
stylegan-v-master/src/scripts/convert_video_to_dataset.py
""" Converts a dataset of mp4 videos into a dataset of video frames I.e. a directory of mp4 files becomes a directory of directories of frames This speeds up loading during training because we do not need """ import os from typing import List import argparse from pathlib import Path from multiprocessing import Pool fro...
3,759
41.727273
168
py
stylegan-v
stylegan-v-master/src/scripts/calc_metrics.py
# 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, reproduction, disclosure or # distribution of this software and rel...
11,305
44.043825
145
py
stylegan-v
stylegan-v-master/src/metrics/metric_utils.py
# 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, reproduction, disclosure or # distribution of this software and re...
14,787
43.542169
153
py
stylegan-v
stylegan-v-master/src/metrics/frechet_video_distance.py
""" Frechet Video Distance (FVD). Matches the original tensorflow implementation from https://github.com/google-research/google-research/blob/master/frechet_video_distance/frechet_video_distance.py up to the upsampling operation. Note that this tf.hub I3D model is different from the one released in the I3D repo. """ i...
3,074
50.25
125
py
stylegan-v
stylegan-v-master/src/metrics/kernel_inception_distance.py
# 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, reproduction, disclosure or # distribution of this software and re...
2,335
48.702128
118
py
stylegan-v
stylegan-v-master/src/metrics/video_inception_score.py
"""Inception Score (IS) from the paper "Improved techniques for training GANs". Matches the original implementation by Salimans et al. at https://github.com/openai/improved-gan/blob/master/inception_score/model.py""" import numpy as np from . import metric_utils #------------------------------------------------------...
2,482
44.145455
126
py
stylegan-v
stylegan-v-master/src/metrics/inception_score.py
# 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, reproduction, disclosure or # distribution of this software and re...
2,236
45.604167
126
py
stylegan-v
stylegan-v-master/src/metrics/metric_main.py
# 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, reproduction, disclosure or # distribution of this software and re...
5,800
36.425806
128
py
DenseCL
DenseCL-main/tools/folder2lmdb_imagenet.py
# coding: utf-8 import argparse import os import os.path as osp from PIL import Image import six import lmdb import pyarrow as pa import numpy as np import torch.utils.data as data from torch.utils.data import DataLoader from torchvision.datasets import ImageFolder def is_valid_file(filename): x = "/".join(file...
4,892
27.614035
84
py
DenseCL
DenseCL-main/tools/test.py
import argparse import importlib import os import os.path as osp import time import mmcv import torch from mmcv.parallel import MMDataParallel, MMDistributedDataParallel from mmcv.runner import get_dist_info, init_dist, load_checkpoint from openselfsup.datasets import build_dataloader, build_dataset from openselfsup....
3,944
31.073171
83
py
DenseCL
DenseCL-main/tools/extract.py
import argparse import importlib import numpy as np import os import os.path as osp import time import mmcv import torch from mmcv.parallel import MMDataParallel, MMDistributedDataParallel from mmcv.runner import get_dist_info, init_dist, load_checkpoint from openselfsup.utils import dist_forward_collect, nondist_for...
6,703
35.63388
77
py
DenseCL
DenseCL-main/tools/upgrade_models.py
import torch import argparse def parse_args(): parser = argparse.ArgumentParser() parser.add_argument('checkpoint', help='checkpoint file') parser.add_argument( '--save-path', type=str, required=True, help='destination file name') args = parser.parse_args() return args def main(): ar...
712
24.464286
77
py
DenseCL
DenseCL-main/tools/folder2lmdb_coco.py
# coding: utf-8 import argparse import os import os.path as osp import lmdb import pyarrow as pa import json import torch.utils.data as data from torch.utils.data import DataLoader class COCODataset(data.Dataset): """ pass. """ def __init__(self, infos, dpath): file_names = list() ...
3,476
25.953488
82
py
DenseCL
DenseCL-main/tools/extract_backbone_weights.py
import torch import argparse def parse_args(): parser = argparse.ArgumentParser( description='This script extracts backbone weights from a checkpoint') parser.add_argument('checkpoint', help='checkpoint file') parser.add_argument( 'output', type=str, help='destination file name') args ...
948
28.65625
78
py
DenseCL
DenseCL-main/tools/train.py
from __future__ import division import argparse import importlib import os import os.path as osp import time import mmcv import torch from mmcv import Config from mmcv.runner import init_dist from openselfsup import __version__ from openselfsup.apis import set_random_seed, train_model from openselfsup.datasets import...
4,838
32.839161
77
py
DenseCL
DenseCL-main/benchmarks/detection/convert-pretrain-to-detectron2.py
#!/usr/bin/env python # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved import pickle as pkl import sys import torch if __name__ == "__main__": input = sys.argv[1] obj = torch.load(input, map_location="cpu") obj = obj["state_dict"] newmodel = {} for k, v in obj.items(): ...
980
25.513514
70
py
DenseCL
DenseCL-main/benchmarks/detection/train_net.py
#!/usr/bin/env python # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved import os from detectron2.checkpoint import DetectionCheckpointer from detectron2.config import get_cfg from detectron2.engine import DefaultTrainer, default_argument_parser, default_setup, launch from detectron2.evaluation i...
2,755
31.423529
135
py
DenseCL
DenseCL-main/openselfsup/apis/inference.py
import warnings import matplotlib.pyplot as plt import cv2 import mmcv import random from PIL import Image import numpy as np import torch from mmcv.runner import load_checkpoint from mmcv.parallel import collate, scatter from openselfsup.models import build_model from openselfsup.utils import build_from_cfg from o...
2,568
29.223529
79
py
DenseCL
DenseCL-main/openselfsup/apis/train.py
import random import re from collections import OrderedDict import numpy as np import torch import torch.distributed as dist from mmcv.parallel import MMDataParallel, MMDistributedDataParallel from mmcv.runner import DistSamplerSeedHook, Runner, obj_from_dict from openselfsup.datasets import build_dataloader from ope...
10,222
34.870175
87
py
DenseCL
DenseCL-main/openselfsup/third_party/clustering.py
# This file is modified from # https://github.com/facebookresearch/deepcluster/blob/master/clustering.py import time import numpy as np import faiss import torch __all__ = ['Kmeans', 'PIC'] def preprocess_features(npdata, pca): """Preprocess an array of features. Args: npdata (np.array N * ndim): fe...
9,309
29.12945
84
py
DenseCL
DenseCL-main/openselfsup/models/densecl.py
import torch import torch.nn as nn from openselfsup.utils import print_log from . import builder from .registry import MODELS @MODELS.register_module class DenseCL(nn.Module): '''DenseCL. Part of the code is borrowed from: "https://github.com/facebookresearch/moco/blob/master/moco/builder.py". '...
9,158
34.777344
119
py
DenseCL
DenseCL-main/openselfsup/models/classification.py
import numpy as np import torch.nn as nn from openselfsup.utils import print_log from . import builder from .registry import MODELS from .utils import Sobel @MODELS.register_module class Classification(nn.Module): """Simple image classification. Args: backbone (dict): Config dict for module of bac...
3,370
31.413462
85
py
DenseCL
DenseCL-main/openselfsup/models/simclr.py
import torch import torch.nn as nn from openselfsup.utils import print_log from . import builder from .registry import MODELS from .utils import GatherLayer @MODELS.register_module class SimCLR(nn.Module): """SimCLR. Implementation of "A Simple Framework for Contrastive Learning of Visual Representatio...
3,961
35.018182
88
py
DenseCL
DenseCL-main/openselfsup/models/rotation_pred.py
import torch import torch.nn as nn from openselfsup.utils import print_log from . import builder from .registry import MODELS @MODELS.register_module class RotationPred(nn.Module): """Rotation prediction. Implementation of "Unsupervised Representation Learning by Predicting Image Rotations (https://arx...
3,294
33.684211
79
py
DenseCL
DenseCL-main/openselfsup/models/deepcluster.py
import numpy as np import torch import torch.nn as nn from openselfsup.utils import print_log from . import builder from .registry import MODELS from .utils import Sobel @MODELS.register_module class DeepCluster(nn.Module): """DeepCluster. Implementation of "Deep Clustering for Unsupervised Learning o...
4,526
33.557252
88
py
DenseCL
DenseCL-main/openselfsup/models/relative_loc.py
import torch import torch.nn as nn from openselfsup.utils import print_log from . import builder from .registry import MODELS @MODELS.register_module class RelativeLoc(nn.Module): """Relative patch location. Implementation of "Unsupervised Visual Representation Learning by Context Prediction (https://a...
3,948
35.564815
88
py
DenseCL
DenseCL-main/openselfsup/models/moco.py
import torch import torch.nn as nn from openselfsup.utils import print_log from . import builder from .registry import MODELS @MODELS.register_module class MOCO(nn.Module): """MOCO. Implementation of "Momentum Contrast for Unsupervised Visual Representation Learning (https://arxiv.org/abs/1911.05722)"....
7,486
33.187215
88
py
DenseCL
DenseCL-main/openselfsup/models/npid.py
import torch import torch.nn as nn from openselfsup.utils import print_log from . import builder from .registry import MODELS @MODELS.register_module class NPID(nn.Module): """NPID. Implementation of "Unsupervised Feature Learning via Non-parametric Instance Discrimination (https://arxiv.org/abs/1805.0...
4,658
34.564885
88
py
DenseCL
DenseCL-main/openselfsup/models/byol.py
import torch import torch.nn as nn from openselfsup.utils import print_log from . import builder from .registry import MODELS @MODELS.register_module class BYOL(nn.Module): """BYOL. Implementation of "Bootstrap Your Own Latent: A New Approach to Self-Supervised Learning (https://arxiv.org/abs/2006.0773...
4,172
36.594595
88
py
DenseCL
DenseCL-main/openselfsup/models/builder.py
from torch import nn from openselfsup.utils import build_from_cfg from .registry import (BACKBONES, MODELS, NECKS, HEADS, MEMORIES, LOSSES) def build(cfg, registry, default_args=None): """Build a module. Args: cfg (dict, list[dict]): The config of modules, it is either a dict or a list o...
1,274
21.368421
77
py
DenseCL
DenseCL-main/openselfsup/models/odc.py
import numpy as np import torch import torch.nn as nn from openselfsup.utils import print_log from . import builder from .registry import MODELS from .utils import Sobel @MODELS.register_module class ODC(nn.Module): """ODC. Official implementation of "Online Deep Clustering for Unsupervised Representati...
5,322
34.966216
88
py
DenseCL
DenseCL-main/openselfsup/models/necks.py
import torch import torch.nn as nn from packaging import version from mmcv.cnn import kaiming_init, normal_init from .registry import NECKS from .utils import build_norm_layer def _init_weights(module, init_linear='normal', std=0.01, bias=0.): assert init_linear in ['normal', 'kaiming'], \ "Undefined ini...
12,802
31.168342
85
py
DenseCL
DenseCL-main/openselfsup/models/memories/simple_memory.py
import torch import torch.nn as nn import torch.distributed as dist from mmcv.runner import get_dist_info from openselfsup.utils import AliasMethod from ..registry import MEMORIES @MEMORIES.register_module class SimpleMemory(nn.Module): """Simple memory bank for NPID. Args: length (int): Number of f...
2,305
33.939394
77
py
DenseCL
DenseCL-main/openselfsup/models/memories/odc_memory.py
import numpy as np from sklearn.cluster import KMeans import torch import torch.nn as nn import torch.distributed as dist from mmcv.runner import get_dist_info from ..registry import MEMORIES @MEMORIES.register_module class ODCMemory(nn.Module): """Memory modules for ODC. Args: length (int): Number...
10,441
43.623932
81
py
DenseCL
DenseCL-main/openselfsup/models/utils/multi_pooling.py
import torch.nn as nn class MultiPooling(nn.Module): """Pooling layers for features from multiple depth.""" POOL_PARAMS = { 'resnet50': [ dict(kernel_size=10, stride=10, padding=4), dict(kernel_size=16, stride=8, padding=0), dict(kernel_size=13, stride=5, padding=0...
1,280
31.846154
66
py
DenseCL
DenseCL-main/openselfsup/models/utils/norm.py
import torch.nn as nn norm_cfg = { # format: layer_type: (abbreviation, module) 'BN': ('bn', nn.BatchNorm2d), 'SyncBN': ('bn', nn.SyncBatchNorm), 'GN': ('gn', nn.GroupNorm), # and potentially 'SN' } def build_norm_layer(cfg, num_features, postfix=''): """Build normalization layer. Args: ...
1,684
29.089286
74
py
DenseCL
DenseCL-main/openselfsup/models/utils/scale.py
import torch import torch.nn as nn class Scale(nn.Module): """A learnable scale parameter.""" def __init__(self, scale=1.0): super(Scale, self).__init__() self.scale = nn.Parameter(torch.tensor(scale, dtype=torch.float)) def forward(self, x): return x * self.scale
305
20.857143
73
py
DenseCL
DenseCL-main/openselfsup/models/utils/sobel.py
import torch import torch.nn as nn class Sobel(nn.Module): """Sobel layer.""" def __init__(self): super(Sobel, self).__init__() grayscale = nn.Conv2d(3, 1, kernel_size=1, stride=1, padding=0) grayscale.weight.data.fill_(1.0 / 3.0) grayscale.bias.data.zero_() sobel_filt...
840
32.64
74
py
DenseCL
DenseCL-main/openselfsup/models/utils/conv_ws.py
import torch.nn as nn import torch.nn.functional as F def conv_ws_2d(input, weight, bias=None, stride=1, padding=0, dilation=1, groups=1, eps=1e-5): c_in = weight.size(0) weight_flat = weight.view(c_in, -1...
1,335
27.425532
79
py
DenseCL
DenseCL-main/openselfsup/models/utils/conv_module.py
import warnings import torch.nn as nn from mmcv.cnn import constant_init, kaiming_init from .conv_ws import ConvWS2d from .norm import build_norm_layer conv_cfg = { 'Conv': nn.Conv2d, 'ConvWS': ConvWS2d, } def build_conv_layer(cfg, *args, **kwargs): """Build convolution layer. Args: cfg (N...
5,723
33.902439
78
py
DenseCL
DenseCL-main/openselfsup/models/utils/bbox.py
import torch def bbox_overlaps(bboxes1, bboxes2, mode='iou', is_aligned=False): """Calculate overlap between two set of bboxes. If ``is_aligned`` is ``False``, then calculate the ious between each bbox of bboxes1 and bboxes2, otherwise the ious between each aligned pair of bboxes1 and bboxes2. Arg...
3,071
36.012048
79
py
DenseCL
DenseCL-main/openselfsup/models/utils/accuracy.py
import torch.nn as nn def accuracy(pred, target, topk=1): assert isinstance(topk, (int, tuple)) if isinstance(topk, int): topk = (topk, ) return_single = True else: return_single = False maxk = max(topk) _, pred_label = pred.topk(maxk, dim=1) pred_label = pred_label.t(...
801
24.0625
69
py
DenseCL
DenseCL-main/openselfsup/models/utils/gather_layer.py
import torch import torch.distributed as dist class GatherLayer(torch.autograd.Function): """Gather tensors from all process, supporting backward propagation. """ @staticmethod def forward(ctx, input): ctx.save_for_backward(input) output = [torch.zeros_like(input) \ for _ ...
618
25.913043
72
py
DenseCL
DenseCL-main/openselfsup/models/backbones/resnet.py
import torch.nn as nn import torch.utils.checkpoint as cp from mmcv.cnn import constant_init, kaiming_init from mmcv.runner import load_checkpoint from torch.nn.modules.batchnorm import _BatchNorm from openselfsup.utils import get_root_logger from ..registry import BACKBONES from ..utils import build_conv_layer, build...
13,648
30.74186
79
py
DenseCL
DenseCL-main/openselfsup/models/backbones/resnext.py
import math import torch.nn as nn from ..registry import BACKBONES from ..utils import build_conv_layer, build_norm_layer from .resnet import Bottleneck as _Bottleneck from .resnet import ResNet class Bottleneck(_Bottleneck): def __init__(self, inplanes, planes, groups=1, base_width=4, **kwargs): """Bo...
7,594
33.058296
79
py
DenseCL
DenseCL-main/openselfsup/models/heads/contrastive_head.py
import torch import torch.nn as nn from ..registry import HEADS @HEADS.register_module class ContrastiveHead(nn.Module): """Head for contrastive learning. Args: temperature (float): The temperature hyper-parameter that controls the concentration level of the distribution. Def...
1,060
26.205128
65
py
DenseCL
DenseCL-main/openselfsup/models/heads/cls_head.py
import torch.nn as nn from mmcv.cnn import kaiming_init, normal_init from ..utils import accuracy from ..registry import HEADS @HEADS.register_module class ClsHead(nn.Module): """Simplest classifier head, with only one fc layer. """ def __init__(self, with_avg_pool=False, ...
2,119
33.754098
78
py
DenseCL
DenseCL-main/openselfsup/models/heads/contrastive_weight_head.py
import torch import torch.nn as nn from ..registry import HEADS @HEADS.register_module class ContrastiveWeightHead(nn.Module): '''Head for contrastive learning. ''' def __init__(self, temperature=0.1): super(ContrastiveWeightHead, self).__init__() self.criterion = nn.CrossEntropyLoss() ...
885
25.848485
60
py
DenseCL
DenseCL-main/openselfsup/models/heads/multi_cls_head.py
import torch.nn as nn from ..utils import accuracy from ..registry import HEADS from ..utils import build_norm_layer, MultiPooling @HEADS.register_module class MultiClsHead(nn.Module): """Multiple classifier heads. """ FEAT_CHANNELS = {'resnet50': [64, 256, 512, 1024, 2048]} FEAT_LAST_UNPOOL = {'res...
2,682
32.962025
78
py
DenseCL
DenseCL-main/openselfsup/models/heads/latent_pred_head.py
import torch import torch.nn as nn from mmcv.cnn import normal_init from ..registry import HEADS from .. import builder @HEADS.register_module class LatentPredictHead(nn.Module): """Head for contrastive learning. """ def __init__(self, predictor, size_average=True): super(LatentPredictHead, self)...
2,048
28.695652
72
py
DenseCL
DenseCL-main/openselfsup/datasets/base.py
from abc import ABCMeta, abstractmethod import torch from torch.utils.data import Dataset from openselfsup.utils import print_log, build_from_cfg from torchvision.transforms import Compose from .registry import DATASETS, PIPELINES from .builder import build_datasource class BaseDataset(Dataset, metaclass=ABCMeta)...
1,056
26.102564
76
py
DenseCL
DenseCL-main/openselfsup/datasets/classification.py
import torch from openselfsup.utils import print_log from .registry import DATASETS from .base import BaseDataset @DATASETS.register_module class ClassificationDataset(BaseDataset): """Dataset for classification. """ def __init__(self, data_source, pipeline): super(ClassificationDataset, self)....
1,435
33.190476
74
py
DenseCL
DenseCL-main/openselfsup/datasets/rotation_pred.py
import torch from PIL import Image from .registry import DATASETS from .base import BaseDataset def rotate(img): """Rotate input image with 0, 90, 180, and 270 degrees. Args: img (Tensor): input image of shape (C, H, W). Returns: list[Tensor]: A list of four rotated images. """ ...
1,288
27.021739
78
py
DenseCL
DenseCL-main/openselfsup/datasets/relative_loc.py
from openselfsup.utils import build_from_cfg import torch from PIL import Image from torchvision.transforms import Compose, RandomCrop import torchvision.transforms.functional as TF from .registry import DATASETS, PIPELINES from .base import BaseDataset def image_to_patches(img): """Crop split_per_side x split_...
2,327
34.272727
94
py
DenseCL
DenseCL-main/openselfsup/datasets/dataset_wrappers.py
import numpy as np from torch.utils.data.dataset import ConcatDataset as _ConcatDataset from .registry import DATASETS @DATASETS.register_module class ConcatDataset(_ConcatDataset): """A wrapper of concatenated dataset. Same as :obj:`torch.utils.data.dataset.ConcatDataset`, but concat the group flag for...
1,639
28.285714
78
py
DenseCL
DenseCL-main/openselfsup/datasets/byol.py
import torch from torch.utils.data import Dataset from openselfsup.utils import build_from_cfg from torchvision.transforms import Compose from .registry import DATASETS, PIPELINES from .builder import build_datasource @DATASETS.register_module class BYOLDataset(Dataset): """Dataset for BYOL. """ def _...
1,076
28.916667
74
py
DenseCL
DenseCL-main/openselfsup/datasets/contrastive.py
import torch from PIL import Image from .registry import DATASETS from .base import BaseDataset @DATASETS.register_module class ContrastiveDataset(BaseDataset): """Dataset for contrastive learning methods that forward two views of the image at a time (MoCo, SimCLR). """ def __init__(self, data_so...
972
32.551724
78
py
DenseCL
DenseCL-main/openselfsup/datasets/data_sources/coco_lmdb.py
# coding: utf-8 import os.path as osp from PIL import Image import six import lmdb import pyarrow as pa import torch.utils.data as data from ..registry import DATASOURCES def loads_pyarrow(buf): """ Args: buf: the output of `dumps`. """ return pa.deserialize(buf) @DATASOURCES.register_modu...
1,890
25.263889
109
py
DenseCL
DenseCL-main/openselfsup/datasets/data_sources/imagenet_lmdb.py
# coding: utf-8 import os.path as osp from PIL import Image import six import lmdb import pyarrow as pa import torch.utils.data as data from ..registry import DATASOURCES def loads_pyarrow(buf): """ Args: buf: the output of `dumps`. """ return pa.deserialize(buf) @DATASOURCES.register_modul...
2,079
26.368421
109
py
DenseCL
DenseCL-main/openselfsup/datasets/data_sources/cifar.py
from PIL import Image from torchvision.datasets import CIFAR10, CIFAR100 from ..registry import DATASOURCES @DATASOURCES.register_module class Cifar10(object): CLASSES = [ 'airplane', 'automobile', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck' ] def __init__(self, root...
1,614
27.839286
71
py
DenseCL
DenseCL-main/openselfsup/datasets/loader/sampler.py
from __future__ import division import math import numpy as np import torch from mmcv.runner import get_dist_info from torch.utils.data import DistributedSampler as _DistributedSampler from torch.utils.data import Sampler class DistributedSampler(_DistributedSampler): def __init__(self, dataset...
10,628
34.079208
92
py