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 |
|---|---|---|---|---|---|---|
dsve-loc | dsve-loc-master/misc/model.py | """
****************** COPYRIGHT AND CONFIDENTIALITY INFORMATION ******************
Copyright (c) 2018 [Thomson Licensing]
All Rights Reserved
This program contains proprietary information which is a trade secret/business \
secret of [Thomson Licensing] and is protected, even if unpublished, under \
applicable Copyrigh... | 4,094 | 33.70339 | 118 | py |
dsve-loc | dsve-loc-master/misc/dataset.py | """
****************** COPYRIGHT AND CONFIDENTIALITY INFORMATION ******************
Copyright (c) 2018 [Thomson Licensing]
All Rights Reserved
This program contains proprietary information which is a trade secret/business \
secret of [Thomson Licensing] and is protected, even if unpublished, under \
applicable Copyrigh... | 8,944 | 33.805447 | 220 | py |
dsve-loc | dsve-loc-master/misc/weldonModel.py | """
****************** COPYRIGHT AND CONFIDENTIALITY INFORMATION ******************
Copyright (c) 2018 [Thomson Licensing]
All Rights Reserved
This program contains proprietary information which is a trade secret/business \
secret of [Thomson Licensing] and is protected, even if unpublished, under \
applicable Copyrigh... | 6,241 | 34.265537 | 101 | py |
VSL | VSL-main/model.py | """SGRAF model"""
from audioop import cross
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.backends.cudnn as cudnn
from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence
from torch.nn.utils.clip_grad import clip_grad_norm_
import numpy as np
from collections import... | 24,170 | 36.474419 | 123 | py |
VSL | VSL-main/data.py | """Data provider"""
import torch
import torch.utils.data as data
from sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer
import os
import nltk
import numpy as np
import h5py
class PrecompDataset(data.Dataset):
"""
Load precomputed captions and image features
Possible options: f30k_p... | 4,946 | 33.838028 | 83 | py |
VSL | VSL-main/eval_overall.py | """Evaluation"""
from __future__ import print_function
import os
from re import T
import sys
import time
import torch
import torch.nn as nn
import numpy as np
from data import get_test_loader
from vocab import Vocabulary, deserialize_vocab
from model import SGRAF
from collections import OrderedDict
# os.environ["CUD... | 12,677 | 35.747826 | 136 | py |
VSL | VSL-main/eval_single.py | """Evaluation"""
from __future__ import print_function
import os
from re import T
import sys
import time
import torch
import torch.nn as nn
import numpy as np
from data import get_test_loader
from vocab import Vocabulary, deserialize_vocab
from model import SGRAF
from collections import OrderedDict
# os.environ["CUD... | 10,656 | 33.377419 | 112 | py |
VSL | VSL-main/train.py | """
# Pytorch implementation for AAAI2021 paper from
# https://arxiv.org/pdf/2101.01368.
# "Similarity Reasoning and Filtration for Image-Text Matching"
# Haiwen Diao, Ying Zhang, Lin Ma, Huchuan Lu
#
# Writen by Haiwen Diao, 2020
"""
import os
import time
import shutil
import torch
import numpy
import data
import o... | 6,369 | 31.666667 | 103 | py |
IJCAI-23-PFedRec | IJCAI-23-PFedRec-main/engine.py | import torch
from torch.autograd import Variable
from tensorboardX import SummaryWriter
from utils import *
from metrics import MetronAtK
import random
import copy
from data import UserItemRatingDataset
from torch.utils.data import DataLoader
from collections import OrderedDict
class Engine(object):
"""Meta Engi... | 10,761 | 48.366972 | 134 | py |
IJCAI-23-PFedRec | IJCAI-23-PFedRec-main/mlp.py | import torch
from engine import Engine
class MLP(torch.nn.Module):
def __init__(self, config):
super(MLP, self).__init__()
self.config = config
self.num_items = config['num_items']
self.latent_dim = config['latent_dim']
self.embedding_item = torch.nn.Embedding(num_embeddin... | 1,143 | 29.105263 | 110 | py |
IJCAI-23-PFedRec | IJCAI-23-PFedRec-main/utils.py | """
Some handy functions for pytroch model training ...
"""
import torch
import logging
# Checkpoints
def save_checkpoint(model, model_dir):
torch.save(model.state_dict(), model_dir)
def resume_checkpoint(model, model_dir, device_id):
state_dict = torch.load(model_dir,
map_lo... | 1,190 | 28.775 | 126 | py |
IJCAI-23-PFedRec | IJCAI-23-PFedRec-main/data.py | import torch
import random
import pandas as pd
from copy import deepcopy
from torch.utils.data import DataLoader, Dataset
random.seed(0)
class UserItemRatingDataset(Dataset):
"""Wrapper, convert <user, item, rating> Tensor into Pytorch Dataset"""
def __init__(self, user_tensor, item_tensor, target_tensor):
... | 7,628 | 48.538961 | 192 | py |
D4RL | D4RL-master/d4rl/locomotion/generate_dataset.py | import numpy as np
import pickle
import gzip
import h5py
import argparse
from d4rl.locomotion import maze_env, ant, swimmer
from d4rl.locomotion.wrappers import NormalizedBoxEnv
from rlkit.torch.pytorch_util import set_gpu_mode
import torch
import skvideo.io
from PIL import Image
import os
def reset_data():
retur... | 5,553 | 31.863905 | 133 | py |
D4RL | D4RL-master/scripts/generation/generate_ant_maze_datasets.py | import numpy as np
import pickle
import gzip
import h5py
import argparse
from d4rl.locomotion import maze_env, ant, swimmer
from d4rl.locomotion.wrappers import NormalizedBoxEnv
import torch
from PIL import Image
import os
def reset_data():
return {'observations': [],
'actions': [],
'termi... | 5,833 | 32.337143 | 133 | py |
D4RL | D4RL-master/scripts/generation/mujoco/convert_buffer.py | import argparse
import re
import h5py
import torch
import numpy as np
itr_re = re.compile(r'itr_(?P<itr>[0-9]+).pkl')
def load(pklfile):
params = torch.load(pklfile)
env_infos = params['replay_buffer/env_infos']
results = {
'observations': params['replay_buffer/observations'],
'next_obse... | 1,519 | 31.340426 | 90 | py |
D4RL | D4RL-master/scripts/generation/mujoco/collect_data.py | import argparse
import re
import h5py
import torch
import gym
import d4rl
import numpy as np
from rlkit.torch import pytorch_util as ptu
itr_re = re.compile(r'itr_(?P<itr>[0-9]+).pkl')
def load(pklfile):
params = torch.load(pklfile)
return params['trainer/policy']
def get_pkl_itr(pklfile):
match = itr_... | 5,396 | 30.747059 | 124 | py |
ContrastiveSSLMusicAudio | ContrastiveSSLMusicAudio-main/utils/util_audio.py | import librosa
import torch, torchaudio
import torch.nn as nn
import numpy as np
class SoxEffectTransform(nn.Module):
def __init__(self, effects) :
super().__init__()
self.effects = effects
def forward(self, tensor: torch.Tensor, sample_rate: int):
return torchaudio.sox_effects.apply_e... | 2,658 | 36.450704 | 117 | py |
ContrastiveSSLMusicAudio | ContrastiveSSLMusicAudio-main/data/data_manager.py | import os, sys
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import traceback
from torch.utils.data import Dataset
from torch.utils.data import DataLoader
from data.data_handler import AudioHandler, DataInfoHandler
from data.data_config import DataConfig
from utils.util_audio import Sox... | 7,949 | 48.378882 | 137 | py |
ContrastiveSSLMusicAudio | ContrastiveSSLMusicAudio-main/data/data_handler.py | import os, sys
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from utils.util_data import *
from utils.util_audio import *
import torch, torchaudio
import os, random
class DataInfoHandler(object):
def __init__(self, config):
self.curr_dataset = config.params['CURR_DATASET']
... | 11,604 | 53.483568 | 183 | py |
ContrastiveSSLMusicAudio | ContrastiveSSLMusicAudio-main/model/emb_aggregators.py | """
Embedding Sequence Aggregation Modules.
- CPC module
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
class CPCModule(nn.Module):
# def __init__(self, timestep, batch_size, seq_len):
def __init__(self, config):
super(CPCModule, self).__init__()
# ... | 5,972 | 47.169355 | 173 | py |
ContrastiveSSLMusicAudio | ContrastiveSSLMusicAudio-main/model/contrastive_models.py | """
Contrastive algorithms
- Siamese network
- CPC network
"""
import sys
import os
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
sys.path.append(os.path.dirname(SCRIPT_DIR))
from model.audio_encoders import *
from model.emb_aggregators import *
from model.abstract_model import AbstractModel
from utils.util... | 29,366 | 45.320189 | 185 | py |
ContrastiveSSLMusicAudio | ContrastiveSSLMusicAudio-main/model/audio_encoders.py | """
Audio encoders
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
class MelConv5by5Enc(nn.Module):
"""
input (batch_size, channels, time, freq) : (batch_size, 1, 188, 96)
"""
def __init__(self, config):
super(MelConv5by5Enc, self).__init__()
... | 12,071 | 35.471299 | 164 | py |
pedalboard | pedalboard-master/tests/test_tensorflow.py | #! /usr/bin/env python
#
# Copyright 2021 Spotify AB
#
# Licensed under the GNU Public License, Version 3.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.gnu.org/licenses/gpl-3.0.html
#
# Unless required by applicable law... | 1,792 | 32.203704 | 89 | py |
mmpretrain | mmpretrain-master/tools/test.py | # Copyright (c) OpenMMLab. All rights reserved.
import argparse
import os
import warnings
from numbers import Number
import mmcv
import numpy as np
import torch
from mmcv import DictAction
from mmcv.runner import (get_dist_info, init_dist, load_checkpoint,
wrap_fp16_model)
from mmcls.apis imp... | 9,192 | 36.67623 | 79 | py |
mmpretrain | mmpretrain-master/tools/kfold-cross-valid.py | # Copyright (c) OpenMMLab. All rights reserved.
import argparse
import copy
import os
import os.path as osp
import time
import warnings
from datetime import datetime
from pathlib import Path
import mmcv
import torch
from mmcv import Config, DictAction
from mmcv.runner import get_dist_info, init_dist
from mmcls import... | 12,871 | 33.602151 | 101 | py |
mmpretrain | mmpretrain-master/tools/train.py | # Copyright (c) OpenMMLab. All rights reserved.
import argparse
import copy
import os
import os.path as osp
import time
import warnings
import mmcv
import torch
import torch.distributed as dist
from mmcv import Config, DictAction
from mmcv.runner import get_dist_info, init_dist
from mmcls import __version__
from mmcl... | 7,346 | 34.665049 | 79 | py |
mmpretrain | mmpretrain-master/tools/deployment/test_torchserver.py | # Copyright (c) OpenMMLab. All rights reserved.
from argparse import ArgumentParser
import numpy as np
import requests
from mmcls.apis import inference_model, init_model, show_result_pyplot
def parse_args():
parser = ArgumentParser()
parser.add_argument('img', help='Image file')
parser.add_argument('con... | 1,595 | 33.695652 | 79 | py |
mmpretrain | mmpretrain-master/tools/deployment/mmcls2torchserve.py | # Copyright (c) OpenMMLab. All rights reserved.
from argparse import ArgumentParser, Namespace
from pathlib import Path
from tempfile import TemporaryDirectory
import mmcv
try:
from model_archiver.model_packaging import package_model
from model_archiver.model_packaging_utils import ModelExportUtils
except Imp... | 3,706 | 32.098214 | 76 | py |
mmpretrain | mmpretrain-master/tools/deployment/onnx2tensorrt.py | # Copyright (c) OpenMMLab. All rights reserved.
import argparse
import os
import os.path as osp
import warnings
import numpy as np
def get_GiB(x: int):
"""return x GiB."""
return x * (1 << 30)
def onnx2tensorrt(onnx_file,
trt_file,
input_shape,
max_batc... | 4,951 | 30.74359 | 79 | py |
mmpretrain | mmpretrain-master/tools/deployment/pytorch2onnx.py | # Copyright (c) OpenMMLab. All rights reserved.
import argparse
import warnings
from functools import partial
import mmcv
import numpy as np
import onnxruntime as rt
import torch
from mmcv.onnx import register_extra_symbolics
from mmcv.runner import load_checkpoint
from mmcls.models import build_classifier
torch.man... | 7,783 | 32.407725 | 79 | py |
mmpretrain | mmpretrain-master/tools/deployment/pytorch2mlmodel.py | # Copyright (c) OpenMMLab. All rights reserved.
import argparse
import os
import os.path as osp
import warnings
from functools import partial
import mmcv
import numpy as np
import torch
from mmcv.runner import load_checkpoint
from torch import nn
from mmcls.models import build_classifier
torch.manual_seed(3)
try:
... | 5,342 | 32.186335 | 79 | py |
mmpretrain | mmpretrain-master/tools/deployment/mmcls_handler.py | # Copyright (c) OpenMMLab. All rights reserved.
import base64
import os
import mmcv
import torch
from ts.torch_handler.base_handler import BaseHandler
from mmcls.apis import inference_model, init_model
class MMclsHandler(BaseHandler):
def initialize(self, context):
properties = context.system_propertie... | 1,650 | 30.75 | 79 | py |
mmpretrain | mmpretrain-master/tools/deployment/pytorch2torchscript.py | # Copyright (c) OpenMMLab. All rights reserved.
import argparse
import os
import os.path as osp
from functools import partial
import mmcv
import numpy as np
import torch
from mmcv.runner import load_checkpoint
from torch import nn
from mmcls.models import build_classifier
torch.manual_seed(3)
def _demo_mm_inputs(i... | 4,364 | 30.178571 | 79 | py |
mmpretrain | mmpretrain-master/tools/convert_models/mobilenetv2_to_mmcls.py | # Copyright (c) OpenMMLab. All rights reserved.
import argparse
from collections import OrderedDict
import torch
def convert_conv1(model_key, model_weight, state_dict, converted_names):
if model_key.find('features.0.0') >= 0:
new_key = model_key.replace('features.0.0', 'backbone.conv1.conv')
else:
... | 4,732 | 33.801471 | 75 | py |
mmpretrain | mmpretrain-master/tools/convert_models/van2mmcls.py | # Copyright (c) OpenMMLab. All rights reserved.
import argparse
import os.path as osp
from collections import OrderedDict
import mmcv
import torch
from mmcv.runner import CheckpointLoader
def convert_van(ckpt):
new_ckpt = OrderedDict()
for k, v in list(ckpt.items()):
new_v = v
if k.startswi... | 1,867 | 27.30303 | 79 | py |
mmpretrain | mmpretrain-master/tools/convert_models/vgg_to_mmcls.py | # Copyright (c) OpenMMLab. All rights reserved.
import argparse
import os
from collections import OrderedDict
import torch
def get_layer_maps(layer_num, with_bn):
layer_maps = {'conv': {}, 'bn': {}}
if with_bn:
if layer_num == 11:
layer_idxs = [0, 4, 8, 11, 15, 18, 22, 25]
elif la... | 4,084 | 33.618644 | 75 | py |
mmpretrain | mmpretrain-master/tools/convert_models/mlpmixer_to_mmcls.py | # Copyright (c) OpenMMLab. All rights reserved.
import argparse
from pathlib import Path
import torch
def convert_weights(weight):
"""Weight Converter.
Converts the weights from timm to mmcls
Args:
weight (dict): weight dict from timm
Returns: converted weight dict for mmcls
"""
re... | 1,674 | 27.389831 | 73 | py |
mmpretrain | mmpretrain-master/tools/convert_models/hornet2mmcls.py | # Copyright (c) OpenMMLab. All rights reserved.
import argparse
import os.path as osp
from collections import OrderedDict
import mmcv
import torch
from mmcv.runner import CheckpointLoader
def convert_hornet(ckpt):
new_ckpt = OrderedDict()
for k, v in list(ckpt.items()):
new_v = v
if k.start... | 1,668 | 25.919355 | 79 | py |
mmpretrain | mmpretrain-master/tools/convert_models/publish_model.py | # Copyright (c) OpenMMLab. All rights reserved.
import argparse
import datetime
import subprocess
from pathlib import Path
import torch
from mmcv import digit_version
def parse_args():
parser = argparse.ArgumentParser(
description='Process a checkpoint to be published')
parser.add_argument('in_file',... | 1,746 | 30.196429 | 78 | py |
mmpretrain | mmpretrain-master/tools/convert_models/reparameterize_model.py | # Copyright (c) OpenMMLab. All rights reserved.
import argparse
from pathlib import Path
import torch
from mmcls.apis import init_model
from mmcls.models.classifiers import ImageClassifier
def convert_classifier_to_deploy(model, save_path):
print('Converting...')
assert hasattr(model, 'backbone') and \
... | 1,773 | 30.678571 | 75 | py |
mmpretrain | mmpretrain-master/tools/convert_models/shufflenetv2_to_mmcls.py | # Copyright (c) OpenMMLab. All rights reserved.
import argparse
from collections import OrderedDict
import torch
def convert_conv1(model_key, model_weight, state_dict, converted_names):
if model_key.find('conv1.0') >= 0:
new_key = model_key.replace('conv1.0', 'backbone.conv1.conv')
else:
new_... | 4,137 | 35.298246 | 74 | py |
mmpretrain | mmpretrain-master/tools/convert_models/efficientnet_to_mmcls.py | # Copyright (c) OpenMMLab. All rights reserved.
import argparse
import os
import numpy as np
import torch
from mmcv.runner import Sequential
from tensorflow.python.training import py_checkpoint_reader
from mmcls.models.backbones.efficientnet import EfficientNet
def tf2pth(v):
if v.ndim == 4:
return np.a... | 8,478 | 38.25463 | 76 | py |
mmpretrain | mmpretrain-master/tools/convert_models/repvgg_to_mmcls.py | # Copyright (c) OpenMMLab. All rights reserved.
import argparse
from collections import OrderedDict
from pathlib import Path
import torch
def convert(src, dst):
print('Converting...')
blobs = torch.load(src, map_location='cpu')
converted_state_dict = OrderedDict()
for key in blobs:
splited_k... | 1,940 | 30.819672 | 79 | py |
mmpretrain | mmpretrain-master/tools/convert_models/torchvision_to_mmcls.py | # Copyright (c) OpenMMLab. All rights reserved.
import argparse
from collections import OrderedDict
from pathlib import Path
import torch
def convert_resnet(src_dict, dst_dict):
"""convert resnet checkpoints from torchvision."""
for key, value in src_dict.items():
if not key.startswith('fc'):
... | 1,838 | 27.734375 | 75 | py |
mmpretrain | mmpretrain-master/tools/convert_models/reparameterize_repvgg.py | # Copyright (c) OpenMMLab. All rights reserved.
import argparse
import warnings
from pathlib import Path
import torch
from mmcls.apis import init_model
bright_style, reset_style = '\x1b[1m', '\x1b[0m'
red_text, blue_text = '\x1b[31m', '\x1b[34m'
white_background = '\x1b[107m'
msg = bright_style + red_text
msg += 'D... | 1,820 | 28.852459 | 75 | py |
mmpretrain | mmpretrain-master/tools/convert_models/twins2mmcls.py | # Copyright (c) OpenMMLab. All rights reserved.
import argparse
import os.path as osp
from collections import OrderedDict
import mmcv
import torch
from mmcv.runner import CheckpointLoader
def convert_twins(args, ckpt):
new_ckpt = OrderedDict()
for k, v in list(ckpt.items()):
new_v = v
if k.... | 2,186 | 28.554054 | 79 | py |
mmpretrain | mmpretrain-master/tools/visualizations/vis_lr.py | # Copyright (c) OpenMMLab. All rights reserved.
import argparse
import os.path as osp
import re
import time
from pathlib import Path
from pprint import pformat
import matplotlib.pyplot as plt
import mmcv
import torch.nn as nn
from mmcv import Config, DictAction, ProgressBar
from mmcv.runner import (EpochBasedRunner, I... | 11,486 | 33.289552 | 79 | py |
mmpretrain | mmpretrain-master/tools/visualizations/vis_cam.py | # Copyright (c) OpenMMLab. All rights reserved.
import argparse
import copy
import math
import pkg_resources
import re
from pathlib import Path
import mmcv
import numpy as np
from mmcv import Config, DictAction
from mmcv.utils import to_2tuple
from torch.nn import BatchNorm1d, BatchNorm2d, GroupNorm, LayerNorm
from m... | 13,554 | 36.969188 | 79 | py |
mmpretrain | mmpretrain-master/mmcls/apis/inference.py | # Copyright (c) OpenMMLab. All rights reserved.
import warnings
import mmcv
import numpy as np
import torch
from mmcv.parallel import collate, scatter
from mmcv.runner import load_checkpoint
from mmcls.datasets.pipelines import Compose
from mmcls.models import build_classifier
def init_model(config, checkpoint=None... | 4,340 | 34.876033 | 79 | py |
mmpretrain | mmpretrain-master/mmcls/apis/test.py | # Copyright (c) OpenMMLab. All rights reserved.
import os.path as osp
import pickle
import shutil
import tempfile
import time
import mmcv
import numpy as np
import torch
import torch.distributed as dist
from mmcv.image import tensor2imgs
from mmcv.runner import get_dist_info
def single_gpu_test(model,
... | 7,680 | 34.892523 | 79 | py |
mmpretrain | mmpretrain-master/mmcls/apis/train.py | # Copyright (c) OpenMMLab. All rights reserved.
import random
import warnings
import numpy as np
import torch
import torch.distributed as dist
from mmcv.runner import (DistSamplerSeedHook, Fp16OptimizerHook,
build_optimizer, build_runner, get_dist_info)
from mmcls.core import DistEvalHook, Di... | 8,420 | 34.987179 | 79 | py |
mmpretrain | mmpretrain-master/mmcls/core/evaluation/multilabel_eval_metrics.py | # Copyright (c) OpenMMLab. All rights reserved.
import warnings
import numpy as np
import torch
def average_performance(pred, target, thr=None, k=None):
"""Calculate CP, CR, CF1, OP, OR, OF1, where C stands for per-class
average, O stands for overall average, P stands for precision, R stands for
recall a... | 2,900 | 38.739726 | 79 | py |
mmpretrain | mmpretrain-master/mmcls/core/evaluation/eval_metrics.py | # Copyright (c) OpenMMLab. All rights reserved.
from numbers import Number
import numpy as np
import torch
from torch.nn.functional import one_hot
def calculate_confusion_matrix(pred, target):
"""Calculate confusion matrix according to the prediction and target.
Args:
pred (torch.Tensor | np.array):... | 11,223 | 42.169231 | 79 | py |
mmpretrain | mmpretrain-master/mmcls/core/evaluation/eval_hooks.py | # Copyright (c) OpenMMLab. All rights reserved.
import os.path as osp
import torch.distributed as dist
from mmcv.runner import DistEvalHook as BaseDistEvalHook
from mmcv.runner import EvalHook as BaseEvalHook
from torch.nn.modules.batchnorm import _BatchNorm
class EvalHook(BaseEvalHook):
"""Non-Distributed evalu... | 3,016 | 37.189873 | 76 | py |
mmpretrain | mmpretrain-master/mmcls/core/evaluation/mean_ap.py | # Copyright (c) OpenMMLab. All rights reserved.
import numpy as np
import torch
def average_precision(pred, target):
r"""Calculate the average precision for a single class.
AP summarizes a precision-recall curve as the weighted mean of maximum
precisions obtained for any r'>r, where r is the recall:
... | 2,414 | 31.2 | 79 | py |
mmpretrain | mmpretrain-master/mmcls/core/hook/precise_bn_hook.py | # Copyright (c) OpenMMLab. All rights reserved.
# Adapted from https://github.com/facebookresearch/pycls/blob/f8cd962737e33ce9e19b3083a33551da95c2d9c0/pycls/core/net.py # noqa: E501
# Original licence: Copyright (c) 2019 Facebook, Inc under the Apache License 2.0 # noqa: E501
import itertools
import logging
from typ... | 6,818 | 36.674033 | 134 | py |
mmpretrain | mmpretrain-master/mmcls/core/export/test.py | # Copyright (c) OpenMMLab. All rights reserved.
import warnings
import numpy as np
import onnxruntime as ort
import torch
from mmcls.models.classifiers import BaseClassifier
class ONNXRuntimeClassifier(BaseClassifier):
"""Wrapper for classifier's inference with ONNXRuntime."""
def __init__(self, onnx_file,... | 3,439 | 34.463918 | 71 | py |
mmpretrain | mmpretrain-master/mmcls/core/optimizers/lamb.py | """PyTorch Lamb optimizer w/ behaviour similar to NVIDIA FusedLamb.
This optimizer code was adapted from the following (starting with latest)
* https://github.com/HabanaAI/Model-References/blob/
2b435114fe8e31f159b1d3063b8280ae37af7423/PyTorch/nlp/bert/pretraining/lamb.py
* https://github.com/NVIDIA/DeepLearningExampl... | 9,651 | 41.333333 | 88 | py |
mmpretrain | mmpretrain-master/mmcls/core/utils/dist_utils.py | # Copyright (c) OpenMMLab. All rights reserved.
from collections import OrderedDict
import numpy as np
import torch
import torch.distributed as dist
from mmcv.runner import OptimizerHook, get_dist_info
from torch._utils import (_flatten_dense_tensors, _take_tensors,
_unflatten_dense_tensors)
... | 3,359 | 31.621359 | 75 | py |
mmpretrain | mmpretrain-master/mmcls/models/necks/gem.py | # Copyright (c) OpenMMLab. All rights reserved.
import torch
from torch import Tensor, nn
from torch.nn import functional as F
from torch.nn.parameter import Parameter
from ..builder import NECKS
def gem(x: Tensor, p: Parameter, eps: float = 1e-6, clamp=True) -> Tensor:
if clamp:
x = x.clamp(min=eps)
... | 1,785 | 32.074074 | 76 | py |
mmpretrain | mmpretrain-master/mmcls/models/necks/hr_fuse.py | # Copyright (c) OpenMMLab. All rights reserved.
import torch.nn as nn
from mmcv.cnn.bricks import ConvModule
from mmcv.runner import BaseModule
from ..backbones.resnet import Bottleneck, ResLayer
from ..builder import NECKS
@NECKS.register_module()
class HRFuseScales(BaseModule):
"""Fuse feature map of multiple ... | 2,969 | 34.357143 | 75 | py |
mmpretrain | mmpretrain-master/mmcls/models/necks/gap.py | # Copyright (c) OpenMMLab. All rights reserved.
import torch
import torch.nn as nn
from ..builder import NECKS
@NECKS.register_module()
class GlobalAveragePooling(nn.Module):
"""Global Average Pooling neck.
Note that we use `view` to remove extra channel after pooling. We do not
use `squeeze` as it will... | 1,492 | 31.456522 | 78 | py |
mmpretrain | mmpretrain-master/mmcls/models/classifiers/base.py | # Copyright (c) OpenMMLab. All rights reserved.
from abc import ABCMeta, abstractmethod
from collections import OrderedDict
from typing import Sequence
import mmcv
import torch
import torch.distributed as dist
from mmcv.runner import BaseModule, auto_fp16
from mmcls.core.visualization import imshow_infos
class Base... | 8,472 | 36.657778 | 79 | py |
mmpretrain | mmpretrain-master/mmcls/models/classifiers/image.py | # Copyright (c) OpenMMLab. All rights reserved.
from ..builder import CLASSIFIERS, build_backbone, build_head, build_neck
from ..heads import MultiLabelClsHead
from ..utils.augment import Augments
from .base import BaseClassifier
@CLASSIFIERS.register_module()
class ImageClassifier(BaseClassifier):
def __init__(... | 5,806 | 35.068323 | 108 | py |
mmpretrain | mmpretrain-master/mmcls/models/utils/layer_scale.py | # Copyright (c) OpenMMLab. All rights reserved.
import torch
from torch import nn
class LayerScale(nn.Module):
"""LayerScale layer.
Args:
dim (int): Dimension of input features.
inplace (bool): inplace: can optionally do the
operation in-place. Default: ``False``
data_form... | 1,250 | 33.75 | 74 | py |
mmpretrain | mmpretrain-master/mmcls/models/utils/embed.py | # Copyright (c) OpenMMLab. All rights reserved.
import warnings
from typing import Sequence
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from mmcv.cnn import build_conv_layer, build_norm_layer
from mmcv.cnn.bricks.transformer import AdaptivePadding
from mmcv.runner.base_module ... | 15,668 | 36.218527 | 79 | py |
mmpretrain | mmpretrain-master/mmcls/models/utils/se_layer.py | # Copyright (c) OpenMMLab. All rights reserved.
import mmcv
import torch.nn as nn
from mmcv.cnn import ConvModule
from mmcv.runner import BaseModule
from .make_divisible import make_divisible
class SELayer(BaseModule):
"""Squeeze-and-Excitation Module.
Args:
channels (int): The input (and output) ch... | 3,217 | 38.728395 | 77 | py |
mmpretrain | mmpretrain-master/mmcls/models/utils/position_encoding.py | # Copyright (c) OpenMMLab. All rights reserved.
import torch.nn as nn
from mmcv.runner.base_module import BaseModule
class ConditionalPositionEncoding(BaseModule):
"""The Conditional Position Encoding (CPE) module.
The CPE is the implementation of 'Conditional Positional Encodings
for Vision Transformers... | 1,357 | 31.333333 | 77 | py |
mmpretrain | mmpretrain-master/mmcls/models/utils/inverted_residual.py | # Copyright (c) OpenMMLab. All rights reserved.
import torch.nn as nn
import torch.utils.checkpoint as cp
from mmcv.cnn import ConvModule
from mmcv.cnn.bricks import DropPath
from mmcv.runner import BaseModule
from .se_layer import SELayer
class InvertedResidual(BaseModule):
"""Inverted Residual Block.
Args... | 4,170 | 32.103175 | 78 | py |
mmpretrain | mmpretrain-master/mmcls/models/utils/attention.py | # Copyright (c) OpenMMLab. All rights reserved.
import warnings
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from mmcv.cnn.bricks.registry import DROPOUT_LAYERS
from mmcv.cnn.bricks.transformer import build_dropout
from mmcv.cnn.utils.weight_init import trunc_normal_
from mmcv.... | 22,852 | 39.447788 | 89 | py |
mmpretrain | mmpretrain-master/mmcls/models/utils/helpers.py | # Copyright (c) OpenMMLab. All rights reserved.
import collections.abc
import warnings
from itertools import repeat
import torch
from mmcv.utils import digit_version
def is_tracing() -> bool:
"""Determine whether the model is called during the tracing of code with
``torch.jit.trace``."""
if digit_version... | 1,514 | 27.055556 | 78 | py |
mmpretrain | mmpretrain-master/mmcls/models/utils/channel_shuffle.py | # Copyright (c) OpenMMLab. All rights reserved.
import torch
def channel_shuffle(x, groups):
"""Channel Shuffle operation.
This function enables cross-group information flow for multiple groups
convolution layers.
Args:
x (Tensor): The input tensor.
groups (int): The number of groups... | 889 | 28.666667 | 74 | py |
mmpretrain | mmpretrain-master/mmcls/models/utils/augment/cutmix.py | # Copyright (c) OpenMMLab. All rights reserved.
from abc import ABCMeta, abstractmethod
import numpy as np
import torch
from .builder import AUGMENT
from .utils import one_hot_encoding
class BaseCutMixLayer(object, metaclass=ABCMeta):
"""Base class for CutMixLayer.
Args:
alpha (float): Parameters f... | 7,072 | 39.1875 | 79 | py |
mmpretrain | mmpretrain-master/mmcls/models/utils/augment/utils.py | # Copyright (c) OpenMMLab. All rights reserved.
import torch.nn.functional as F
def one_hot_encoding(gt, num_classes):
"""Change gt_label to one_hot encoding.
If the shape has 2 or more
dimensions, return it without encoding.
Args:
gt (Tensor): The gt label with shape (N,) or shape (N, */).
... | 720 | 27.84 | 67 | py |
mmpretrain | mmpretrain-master/mmcls/models/utils/augment/mixup.py | # Copyright (c) OpenMMLab. All rights reserved.
from abc import ABCMeta, abstractmethod
import numpy as np
import torch
from .builder import AUGMENT
from .utils import one_hot_encoding
class BaseMixupLayer(object, metaclass=ABCMeta):
"""Base class for MixupLayer.
Args:
alpha (float): Parameters for... | 2,657 | 31.814815 | 75 | py |
mmpretrain | mmpretrain-master/mmcls/models/utils/augment/resizemix.py | # Copyright (c) OpenMMLab. All rights reserved.
import numpy as np
import torch
import torch.nn.functional as F
from mmcls.models.utils.augment.builder import AUGMENT
from .cutmix import BatchCutMixLayer
from .utils import one_hot_encoding
@AUGMENT.register_module(name='BatchResizeMix')
class BatchResizeMixLayer(Bat... | 3,712 | 38.5 | 79 | py |
mmpretrain | mmpretrain-master/mmcls/models/utils/augment/augments.py | # Copyright (c) OpenMMLab. All rights reserved.
import random
import numpy as np
from .builder import build_augment
class Augments(object):
"""Data augments.
We implement some data augmentation methods, such as mixup, cutmix.
Args:
augments_cfg (list[`mmcv.ConfigDict`] | obj:`mmcv.ConfigDict`)... | 2,799 | 36.837838 | 79 | py |
mmpretrain | mmpretrain-master/mmcls/models/losses/label_smooth_loss.py | # Copyright (c) OpenMMLab. All rights reserved.
import torch
import torch.nn as nn
from ..builder import LOSSES
from .cross_entropy_loss import CrossEntropyLoss
from .utils import convert_to_one_hot
@LOSSES.register_module()
class LabelSmoothLoss(nn.Module):
r"""Initializer for the label smoothed cross entropy l... | 6,218 | 38.360759 | 79 | py |
mmpretrain | mmpretrain-master/mmcls/models/losses/asymmetric_loss.py | # Copyright (c) OpenMMLab. All rights reserved.
import torch
import torch.nn as nn
from ..builder import LOSSES
from .utils import convert_to_one_hot, weight_reduce_loss
def asymmetric_loss(pred,
target,
weight=None,
gamma_pos=1.0,
gamma... | 5,525 | 35.84 | 79 | py |
mmpretrain | mmpretrain-master/mmcls/models/losses/utils.py | # Copyright (c) OpenMMLab. All rights reserved.
import functools
import torch
import torch.nn.functional as F
def reduce_loss(loss, reduction):
"""Reduce loss as specified.
Args:
loss (Tensor): Elementwise loss tensor.
reduction (str): Options are "none", "mean" and "sum".
Return:
... | 3,694 | 29.791667 | 79 | py |
mmpretrain | mmpretrain-master/mmcls/models/losses/seesaw_loss.py | # Copyright (c) OpenMMLab. All rights reserved.
# migrate from mmdetection with modifications
import torch
import torch.nn as nn
import torch.nn.functional as F
from ..builder import LOSSES
from .utils import weight_reduce_loss
def seesaw_ce_loss(cls_score,
labels,
weight,
... | 6,721 | 37.632184 | 79 | py |
mmpretrain | mmpretrain-master/mmcls/models/losses/accuracy.py | # Copyright (c) OpenMMLab. All rights reserved.
import platform
from numbers import Number
import numpy as np
import torch
import torch.nn as nn
from mmcls.utils import auto_select_device
def accuracy_numpy(pred, target, topk=(1, ), thrs=0.):
if isinstance(thrs, Number):
thrs = (thrs, )
res_sing... | 5,162 | 32.745098 | 79 | py |
mmpretrain | mmpretrain-master/mmcls/models/losses/focal_loss.py | # Copyright (c) OpenMMLab. All rights reserved.
import torch.nn as nn
import torch.nn.functional as F
from ..builder import LOSSES
from .utils import convert_to_one_hot, weight_reduce_loss
def sigmoid_focal_loss(pred,
target,
weight=None,
gamma=2.0... | 4,275 | 35.547009 | 79 | py |
mmpretrain | mmpretrain-master/mmcls/models/losses/cross_entropy_loss.py | # Copyright (c) OpenMMLab. All rights reserved.
import torch.nn as nn
import torch.nn.functional as F
from ..builder import LOSSES
from .utils import weight_reduce_loss
def cross_entropy(pred,
label,
weight=None,
reduction='mean',
avg_factor=Non... | 7,550 | 34.957143 | 79 | py |
mmpretrain | mmpretrain-master/mmcls/models/backbones/hrnet.py | # Copyright (c) OpenMMLab. All rights reserved.
import torch.nn as nn
from mmcv.cnn import build_conv_layer, build_norm_layer
from mmcv.runner import BaseModule, ModuleList, Sequential
from torch.nn.modules.batchnorm import _BatchNorm
from ..builder import BACKBONES
from .resnet import BasicBlock, Bottleneck, ResLayer... | 23,384 | 40.462766 | 79 | py |
mmpretrain | mmpretrain-master/mmcls/models/backbones/mlp_mixer.py | # Copyright (c) OpenMMLab. All rights reserved.
from typing import Sequence
import torch.nn as nn
from mmcv.cnn import build_norm_layer
from mmcv.cnn.bricks.transformer import FFN, PatchEmbed
from mmcv.runner.base_module import BaseModule, ModuleList
from ..builder import BACKBONES
from ..utils import to_2tuple
from ... | 9,669 | 35.628788 | 79 | py |
mmpretrain | mmpretrain-master/mmcls/models/backbones/regnet.py | # Copyright (c) OpenMMLab. All rights reserved.
import numpy as np
import torch.nn as nn
from mmcv.cnn import build_conv_layer, build_norm_layer
from ..builder import BACKBONES
from .resnet import ResNet
from .resnext import Bottleneck
@BACKBONES.register_module()
class RegNet(ResNet):
"""RegNet backbone.
M... | 12,166 | 36.552469 | 79 | py |
mmpretrain | mmpretrain-master/mmcls/models/backbones/tnt.py | # Copyright (c) OpenMMLab. All rights reserved.
import math
import torch
import torch.nn as nn
from mmcv.cnn import build_norm_layer
from mmcv.cnn.bricks.transformer import FFN, MultiheadAttention
from mmcv.cnn.utils.weight_init import trunc_normal_
from mmcv.runner.base_module import BaseModule, ModuleList
from ..bu... | 14,530 | 38.379404 | 84 | py |
mmpretrain | mmpretrain-master/mmcls/models/backbones/mobilenet_v2.py | # Copyright (c) OpenMMLab. All rights reserved.
import torch.nn as nn
import torch.utils.checkpoint as cp
from mmcv.cnn import ConvModule
from mmcv.runner import BaseModule
from torch.nn.modules.batchnorm import _BatchNorm
from mmcls.models.utils import make_divisible
from ..builder import BACKBONES
from .base_backbon... | 9,588 | 35.184906 | 79 | py |
mmpretrain | mmpretrain-master/mmcls/models/backbones/efficientnet.py | # Copyright (c) OpenMMLab. All rights reserved.
import copy
import math
from functools import partial
import torch
import torch.nn as nn
import torch.utils.checkpoint as cp
from mmcv.cnn.bricks import ConvModule, DropPath
from mmcv.runner import BaseModule, Sequential
from mmcls.models.backbones.base_backbone import ... | 15,563 | 37.147059 | 79 | py |
mmpretrain | mmpretrain-master/mmcls/models/backbones/swin_transformer.py | # Copyright (c) OpenMMLab. All rights reserved.
from copy import deepcopy
from typing import Sequence
import numpy as np
import torch
import torch.nn as nn
import torch.utils.checkpoint as cp
from mmcv.cnn import build_norm_layer
from mmcv.cnn.bricks.transformer import FFN, PatchEmbed, PatchMerging
from mmcv.cnn.utils... | 22,280 | 39.584699 | 79 | py |
mmpretrain | mmpretrain-master/mmcls/models/backbones/shufflenet_v1.py | # Copyright (c) OpenMMLab. All rights reserved.
import torch
import torch.nn as nn
import torch.utils.checkpoint as cp
from mmcv.cnn import (ConvModule, build_activation_layer, constant_init,
normal_init)
from mmcv.runner import BaseModule
from torch.nn.modules.batchnorm import _BatchNorm
from mm... | 11,570 | 34.934783 | 78 | py |
mmpretrain | mmpretrain-master/mmcls/models/backbones/timm_backbone.py | # Copyright (c) OpenMMLab. All rights reserved.
try:
import timm
except ImportError:
timm = None
import warnings
from mmcv.cnn.bricks.registry import NORM_LAYERS
from ...utils import get_root_logger
from ..builder import BACKBONES
from .base_backbone import BaseBackbone
def print_timm_feature_info(feature_... | 4,303 | 37.088496 | 79 | py |
mmpretrain | mmpretrain-master/mmcls/models/backbones/resnet.py | # Copyright (c) OpenMMLab. All rights reserved.
import torch.nn as nn
import torch.utils.checkpoint as cp
from mmcv.cnn import (ConvModule, build_activation_layer, build_conv_layer,
build_norm_layer, constant_init)
from mmcv.cnn.bricks import DropPath
from mmcv.runner import BaseModule
from mmcv.... | 23,762 | 33.489115 | 79 | py |
mmpretrain | mmpretrain-master/mmcls/models/backbones/vgg.py | # Copyright (c) OpenMMLab. All rights reserved.
import torch.nn as nn
from mmcv.cnn import ConvModule
from mmcv.utils.parrots_wrapper import _BatchNorm
from ..builder import BACKBONES
from .base_backbone import BaseBackbone
def make_vgg_layer(in_channels,
out_channels,
num_block... | 6,739 | 35.630435 | 79 | py |
mmpretrain | mmpretrain-master/mmcls/models/backbones/mvit.py | # Copyright (c) OpenMMLab. All rights reserved.
from typing import Optional, Sequence
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from mmcv.cnn import build_norm_layer
from mmcv.cnn.bricks import DropPath
from mmcv.cnn.bricks.transformer import PatchEmbed, build_activation_lay... | 26,082 | 36.208274 | 79 | py |
mmpretrain | mmpretrain-master/mmcls/models/backbones/seresnet.py | # Copyright (c) OpenMMLab. All rights reserved.
import torch.utils.checkpoint as cp
from ..builder import BACKBONES
from ..utils.se_layer import SELayer
from .resnet import Bottleneck, ResLayer, ResNet
class SEBottleneck(Bottleneck):
"""SEBottleneck block for SEResNet.
Args:
in_channels (int): The i... | 4,605 | 35.555556 | 79 | py |
mmpretrain | mmpretrain-master/mmcls/models/backbones/repvgg.py | # Copyright (c) OpenMMLab. All rights reserved.
import torch
import torch.nn.functional as F
import torch.utils.checkpoint as cp
from mmcv.cnn import (ConvModule, build_activation_layer, build_conv_layer,
build_norm_layer)
from mmcv.runner import BaseModule, Sequential
from mmcv.utils.parrots_wrap... | 21,962 | 34.424194 | 79 | py |
mmpretrain | mmpretrain-master/mmcls/models/backbones/deit.py | # Copyright (c) OpenMMLab. All rights reserved.
import torch
import torch.nn as nn
from mmcv.cnn.utils.weight_init import trunc_normal_
from ..builder import BACKBONES
from .vision_transformer import VisionTransformer
@BACKBONES.register_module()
class DistilledVisionTransformer(VisionTransformer):
"""Distilled ... | 5,005 | 41.423729 | 79 | py |
mmpretrain | mmpretrain-master/mmcls/models/backbones/densenet.py | # Copyright (c) OpenMMLab. All rights reserved.
import math
from itertools import chain
from typing import Sequence
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.utils.checkpoint as cp
from mmcv.cnn.bricks import build_activation_layer, build_norm_layer
from torch.jit.annotations impo... | 12,012 | 35.075075 | 83 | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.