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 |
|---|---|---|---|---|---|---|
imgclsmob | imgclsmob-master/keras_/kerascv/models/shufflenet.py | """
ShuffleNet for ImageNet-1K, implemented in Keras.
Original paper: 'ShuffleNet: An Extremely Efficient Convolutional Neural Network for Mobile Devices,'
https://arxiv.org/abs/1707.01083.
"""
__all__ = ['shufflenet', 'shufflenet_g1_w1', 'shufflenet_g2_w1', 'shufflenet_g3_w1', 'shufflenet_g4_w1',
... | 15,527 | 30.689796 | 120 | py |
imgclsmob | imgclsmob-master/keras_/kerascv/models/common.py | """
Common routines for models in Keras.
"""
__all__ = ['round_channels', 'HSwish', 'is_channels_first', 'get_channel_axis', 'update_keras_shape', 'flatten',
'batchnorm', 'lrn', 'maxpool2d', 'avgpool2d', 'conv2d', 'conv1x1', 'conv3x3', 'depthwise_conv3x3',
'conv_block', 'conv1x1_block', 'conv... | 47,316 | 29.44852 | 120 | py |
imgclsmob | imgclsmob-master/keras_/kerascv/models/model_store.py | """
Model store which provides pretrained models.
"""
__all__ = ['get_model_file', 'load_model', 'download_model']
import os
import zipfile
import logging
import hashlib
import warnings
import numpy as np
import h5py
from keras import backend as K
from keras.engine.saving import load_attributes_from_hdf5_group
_... | 27,367 | 49.869888 | 116 | py |
imgclsmob | imgclsmob-master/keras_/kerascv/models/zfnet.py | """
ZFNet for ImageNet-1K, implemented in Keras.
Original paper: 'Visualizing and Understanding Convolutional Networks,' https://arxiv.org/abs/1311.2901.
"""
__all__ = ['zfnet', 'zfnetb']
import os
from .common import is_channels_first
from .alexnet import alexnet_model
def get_zfnet(version="a",
... | 3,608 | 27.872 | 115 | py |
imgclsmob | imgclsmob-master/keras_/kerascv/models/darknet53.py | """
DarkNet-53 for ImageNet-1K, implemented in Keras.
Original source: 'YOLOv3: An Incremental Improvement,' https://arxiv.org/abs/1804.02767.
"""
__all__ = ['darknet53_model', 'darknet53']
import os
from keras import layers as nn
from keras.models import Model
from .common import conv1x1_block, conv3x3_block... | 6,500 | 28.684932 | 115 | py |
imgclsmob | imgclsmob-master/keras_/kerascv/models/mobilenet.py | """
MobileNet & FD-MobileNet for ImageNet-1K, implemented in Keras.
Original papers:
- 'MobileNets: Efficient Convolutional Neural Networks for Mobile Vision Applications,'
https://arxiv.org/abs/1704.04861.
- 'FD-MobileNet: Improved MobileNet with A Fast Downsampling Strategy,' https://arxiv.org/... | 11,133 | 32.136905 | 119 | py |
imgclsmob | imgclsmob-master/keras_/kerascv/models/darknet.py | """
DarkNet for ImageNet-1K, implemented in Keras.
Original source: 'Darknet: Open source neural networks in c,' https://github.com/pjreddie/darknet.
"""
__all__ = ['darknet', 'darknet_ref', 'darknet_tiny', 'darknet19']
import os
from keras import layers as nn
from keras.models import Model
from .common impor... | 8,104 | 29.935115 | 116 | py |
imgclsmob | imgclsmob-master/keras_/kerascv/models/alexnet.py | """
AlexNet for ImageNet-1K, implemented in Keras.
Original paper: 'One weird trick for parallelizing convolutional neural networks,'
https://arxiv.org/abs/1404.5997.
"""
__all__ = ['alexnet_model', 'alexnet', 'alexnetb']
import os
from keras import layers as nn
from keras.models import Model
from .common... | 9,197 | 27.301538 | 115 | py |
ZOC | ZOC-main/cifarplus_eval.py | import argparse
import torch
from transformers import BertGenerationTokenizer, BertGenerationDecoder, BertGenerationConfig
import os
from dataloaders.ZO_Clip_loaders import cifarplus_loader
from clip.simple_tokenizer import SimpleTokenizer as clip_tokenizer
from tqdm import tqdm
import copy
import numpy as np
from skle... | 7,866 | 46.969512 | 122 | py |
ZOC | ZOC-main/cifar10_eval.py | import argparse
import torch
import os
from tqdm import tqdm
import numpy as np
from transformers import BertGenerationTokenizer, BertGenerationDecoder, BertGenerationConfig
from dataloaders.ZO_Clip_loaders import cifar10_single_isolated_class_loader
from clip.simple_tokenizer import SimpleTokenizer as clip_tokenizer
f... | 6,916 | 51.007519 | 122 | py |
ZOC | ZOC-main/tinyimagenet_eval.py | import argparse
import torch
from transformers import BertGenerationTokenizer, BertGenerationDecoder, BertGenerationConfig
import os
from dataloaders.ZO_Clip_loaders import tinyimage_single_isolated_class_loader
from clip.simple_tokenizer import SimpleTokenizer as clip_tokenizer
from tqdm import tqdm
import numpy as np... | 5,965 | 44.892308 | 122 | py |
ZOC | ZOC-main/train_decoder.py | import argparse
import torch
from transformers import BertGenerationTokenizer, BertGenerationDecoder, BertGenerationConfig
import os
from dataloaders.coco_full_loader import get_loader
from clip.simple_tokenizer import SimpleTokenizer as clip_tokenizer
from transformers import AdamW
from tqdm import tqdm
def train_de... | 5,162 | 45.513514 | 110 | py |
ZOC | ZOC-main/cifar100_eval.py | import argparse
import torch
from transformers import BertGenerationTokenizer, BertGenerationDecoder, BertGenerationConfig
import os
from dataloaders.ZO_Clip_loaders import cifar100_single_isolated_class_loader
from clip.simple_tokenizer import SimpleTokenizer as clip_tokenizer
from tqdm import tqdm
import numpy as np
... | 6,168 | 45.037313 | 144 | py |
ZOC | ZOC-main/dataloaders/ZO_Clip_loaders.py | from torch.utils.data import DataLoader, Dataset
import numpy as np
import os
from torchvision.datasets import CIFAR10, CIFAR100
from torchvision.transforms import Compose, Resize, CenterCrop, ToTensor, Normalize, ToPILImage
from PIL import Image
from torchvision.datasets import ImageFolder
import glob
class cifar10_... | 12,638 | 46.515038 | 122 | py |
ZOC | ZOC-main/dataloaders/coco_full_loader.py | from torch.utils.data import DataLoader, TensorDataset
import torch
import numpy as np
import os
from torchvision.datasets import CocoDetection
from torchvision.transforms import Compose, Resize, CenterCrop, ToTensor, Normalize
from PIL import Image
from tqdm import tqdm
from transformers import BertGenerationTokenizer... | 6,133 | 43.129496 | 137 | py |
cppflow | cppflow-master/examples/load_frozen_graph/create_model.py | #!/usr/bin/env python
"""
Example for a load frozen tf graph functionality.
"""
# MIT License
#
# Copyright (c) 2021 Daisuke Kato
# Copyright (c) 2021 Paul
# Copyright (c) 2022 Sergio Izquierdo
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated docume... | 2,376 | 36.140625 | 79 | py |
cppflow | cppflow-master/examples/load_model/create_model.py | #!/usr/bin/env python
"""
Example for a load model functionality.
"""
# MIT License
#
# Copyright (c) 2019 Sergio Izquierdo
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without rest... | 1,787 | 34.76 | 79 | py |
cppflow | cppflow-master/examples/efficientnet/create_model.py | #!/usr/bin/env python
"""
Example for create model functionality.
"""
# MIT License
#
# Copyright (c) 2020 Sergio Izquierdo
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without rest... | 1,575 | 34.818182 | 79 | py |
cppflow | cppflow-master/examples/multi_input_output/create_model.py | #!/usr/bin/env python
"""
Example for a multiple inputs and outputs functionality.
"""
# MIT License
#
# Copyright (c) 2020 Sergio Izquierdo
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Soft... | 2,144 | 36.631579 | 79 | py |
BOExplain | BOExplain-main/boexplain/optuna/setup.py | import os
import sys
import pkg_resources
from setuptools import find_packages
from setuptools import setup
from typing import Dict
from typing import List
from typing import Optional
def get_version() -> str:
version_filepath = os.path.join(os.path.dirname(__file__), "optuna", "version.py")
with open(vers... | 5,283 | 28.032967 | 99 | py |
SPMC_VideoSR | SPMC_VideoSR-master/modules/utils.py |
import tensorflow as tf
def weight_from_caffe(caffenet):
def func(shape, dtype):
sc = tf.get_variable_scope()
name = sc.name.split('/')[-1]
print 'init: ', name, shape, caffenet.params[name][0].data.shape
return tf.transpose(caffenet.params[name][0].data, perm=[2 ,3 ,1 ,0])
ret... | 527 | 25.4 | 77 | py |
CLOSURE | CLOSURE-master/vr/utils.py | #!/usr/bin/env python3
# This code is released under the MIT License in association with the following paper:
#
# CLOSURE: Assessing Systematic Generalization of CLEVR Models (https://arxiv.org/abs/1912.05783).
#
# Full copyright and license information (including third party attribution) in the NOTICE file (https://g... | 6,077 | 32.58011 | 138 | py |
CLOSURE | CLOSURE-master/vr/data.py | #!/usr/bin/env python3
# This code is released under the MIT License in association with the following paper:
#
# CLOSURE: Assessing Systematic Generalization of CLEVR Models (https://arxiv.org/abs/1912.05783).
#
# Full copyright and license information (including third party attribution) in the NOTICE file (https://g... | 9,208 | 37.85654 | 138 | py |
CLOSURE | CLOSURE-master/vr/models/seq2seq_att.py | #!/usr/bin/env python3
# This code is released under the MIT License in association with the following paper:
#
# CLOSURE: Assessing Systematic Generalization of CLEVR Models (https://arxiv.org/abs/1912.05783).
#
# Full copyright and license information (including third party attribution) in the NOTICE file (https://g... | 8,941 | 38.566372 | 138 | py |
CLOSURE | CLOSURE-master/vr/models/baselines.py | #!/usr/bin/env python3
# This code is released under the MIT License in association with the following paper:
#
# CLOSURE: Assessing Systematic Generalization of CLEVR Models (https://arxiv.org/abs/1912.05783).
#
# Full copyright and license information (including third party attribution) in the NOTICE file (https://g... | 8,657 | 34.052632 | 138 | py |
CLOSURE | CLOSURE-master/vr/models/filmed_net.py | #!/usr/bin/env python3
import math
import pprint
from termcolor import colored
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
import torchvision.models
from vr.models.layers import init_modules, GlobalAveragePool, Flatten
from vr.models.layers import build_class... | 19,181 | 42.202703 | 133 | py |
CLOSURE | CLOSURE-master/vr/models/seq2seq.py | #!/usr/bin/env python3
# This code is released under the MIT License in association with the following paper:
#
# CLOSURE: Assessing Systematic Generalization of CLEVR Models (https://arxiv.org/abs/1912.05783).
#
# Full copyright and license information (including third party attribution) in the NOTICE file (https://g... | 7,657 | 38.885417 | 138 | py |
CLOSURE | CLOSURE-master/vr/models/layers.py | #!/usr/bin/env python3
# This code is released under the MIT License in association with the following paper:
#
# CLOSURE: Assessing Systematic Generalization of CLEVR Models (https://arxiv.org/abs/1912.05783).
#
# Full copyright and license information (including third party attribution) in the NOTICE file (https://g... | 9,120 | 36.228571 | 138 | py |
CLOSURE | CLOSURE-master/vr/models/maced_net.py | #!/usr/bin/env python3
import numpy as np
import math
import pprint
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
import torchvision.models
import math
from torch.nn.init import kaiming_normal, kaiming_uniform, xavier_uniform, xavier_normal, constant
from vr.mo... | 21,616 | 37.809695 | 119 | py |
CLOSURE | CLOSURE-master/vr/models/convlstm.py | #!/usr/bin/env python3
import torch
import torch.nn as nn
from torch.autograd import Variable
from vr.models.layers import (build_classifier,
build_stem,
init_modules)
class ConvLSTM(nn.Module):
def __init__(self,
vocab,
... | 2,782 | 35.142857 | 73 | py |
CLOSURE | CLOSURE-master/vr/models/film_gen.py | #!/usr/bin/env python3
import torch
import torch.cuda
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence
from vr.models.layers import init_modules
from torch.nn.init import uniform_, xavier_uniform_, consta... | 13,957 | 39.34104 | 131 | py |
CLOSURE | CLOSURE-master/vr/models/module_net.py | #!/usr/bin/env python3
# This code is released under the MIT License in association with the following paper:
#
# CLOSURE: Assessing Systematic Generalization of CLEVR Models (https://arxiv.org/abs/1912.05783).
#
# Full copyright and license information (including third party attribution) in the NOTICE file (https://g... | 15,132 | 40.803867 | 138 | py |
CLOSURE | CLOSURE-master/vr/ns_vqa/parser.py | import torch
import torch.nn as nn
from torch.autograd import Variable
from . import create_seq2seq_net, TrainOptions
class Seq2seqParser(nn.Module):
"""Model interface for seq2seq parser"""
def __init__(self, vocab):
super().__init__()
self.opt = TrainOptions().parse()
self.vocab = ... | 4,059 | 37.301887 | 106 | py |
CLOSURE | CLOSURE-master/vr/ns_vqa/base_rnn.py | import torch.nn as nn
class BaseRNN(nn.Module):
"""Base RNN module"""
def __init__(self, vocab_size, max_len, hidden_size, input_dropout_p,
dropout_p, n_layers, rnn_cell):
super(BaseRNN, self).__init__()
self.vocab_size = vocab_size
self.max_len = max_le... | 829 | 28.642857 | 74 | py |
CLOSURE | CLOSURE-master/vr/ns_vqa/base_options.py | import os
import argparse
import numpy as np
import torch
class BaseOptions():
"""Base option class"""
def __init__(self):
self.parser = argparse.ArgumentParser()
self.parser.add_argument('--run_dir', default='_scratch/test_run', type=str, help='experiment directory')
self.parser.add... | 3,439 | 45.486486 | 125 | py |
CLOSURE | CLOSURE-master/vr/ns_vqa/seq2seq.py | import torch
import torch.nn as nn
class Seq2seq(nn.Module):
"""Seq2seq model module
To do: add docstring to methods
"""
def __init__(self, encoder, decoder):
super(Seq2seq, self).__init__()
self.encoder = encoder
self.decoder = decoder
def forward(self, x, y, input_lengt... | 1,700 | 42.615385 | 131 | py |
CLOSURE | CLOSURE-master/vr/ns_vqa/utils.py | import os
import json
import numpy as np
import torch
def mkdirs(paths):
if isinstance(paths, list):
for path in paths:
if not os.path.exists(path):
os.makedirs(path)
else:
if not os.path.exists(paths):
os.makedirs(paths)
def invert_dict(d):
return {... | 2,041 | 31.935484 | 85 | py |
CLOSURE | CLOSURE-master/vr/ns_vqa/encoder.py | import torch.nn as nn
from .base_rnn import BaseRNN
class Encoder(BaseRNN):
"""Encoder RNN module"""
def __init__(self, vocab_size, max_len, word_vec_dim, hidden_size, n_layers,
input_dropout_p=0., dropout_p=0., bidirectional=False, rnn_cell='lstm',
variable_lengths=False, w... | 1,726 | 44.447368 | 119 | py |
CLOSURE | CLOSURE-master/vr/ns_vqa/clevr_executor.py | import torch
import random
import json
CLEVR_COLORS = ['blue', 'brown', 'cyan', 'gray', 'green', 'purple', 'red', 'yellow']
CLEVR_MATERIALS = ['rubber', 'metal']
CLEVR_SHAPES = ['cube', 'cylinder', 'sphere']
CLEVR_SIZES = ['large', 'small']
CLEVR_ANSWER_CANDIDATES = {
'count': ['0', '1', '2', '3', '4', '5', '6'... | 15,787 | 32.378436 | 125 | py |
CLOSURE | CLOSURE-master/vr/ns_vqa/decoder.py | import numpy as np
import torch
import torch.nn as nn
from torch.autograd import Variable
import torch.nn.functional as F
from .base_rnn import BaseRNN
from .attention import Attention
def logical_or(x, y):
return (x + y).clamp_(0, 1)
def logical_not(x):
return x == 0
class Decoder(BaseRNN):
"""Decod... | 4,566 | 39.061404 | 132 | py |
CLOSURE | CLOSURE-master/vr/ns_vqa/attention.py | import torch
import torch.nn as nn
import torch.nn.functional as F
class Attention(nn.Module):
"""Attention layer"""
def __init__(self, dim, use_weight=False, hidden_size=512):
super(Attention, self).__init__()
self.use_weight = use_weight
self.hidden_size = hidden_size
if use... | 1,804 | 38.23913 | 149 | py |
CLOSURE | CLOSURE-master/scripts/run_pg.py | # This code is released under the MIT License in association with the following paper:
#
# CLOSURE: Assessing Systematic Generalization of CLEVR Models (https://arxiv.org/abs/1912.05783).
#
# Full copyright and license information (including third party attribution) in the NOTICE file (https://github.com/rizar/CLOSURE/... | 5,036 | 29.713415 | 138 | py |
CLOSURE | CLOSURE-master/scripts/train_model.py | #!/usr/bin/env python3
# This code is released under the MIT License in association with the following paper:
#
# CLOSURE: Assessing Systematic Generalization of CLEVR Models (https://arxiv.org/abs/1912.05783).
#
# Full copyright and license information (including third party attribution) in the NOTICE file (https://gi... | 60,588 | 45.642802 | 138 | py |
CLOSURE | CLOSURE-master/scripts/run_model.py | # This code is released under the MIT License in association with the following paper:
#
# CLOSURE: Assessing Systematic Generalization of CLEVR Models (https://arxiv.org/abs/1912.05783).
#
# Full copyright and license information (including third party attribution) in the NOTICE file (https://github.com/rizar/CLOSURE/... | 11,896 | 36.648734 | 138 | py |
Tiny-NewsRec | Tiny-NewsRec-main/Tiny-NewsRec/dataloader.py | import sys
import traceback
import logging
import random
from queue import Queue
from concurrent.futures import ThreadPoolExecutor
import numpy as np
import torch
from torch.utils.data import IterableDataset
from streaming import StreamSampler
def news_sample(news, ratio):
if ratio > len(news):
return new... | 11,565 | 35.71746 | 130 | py |
Tiny-NewsRec | Tiny-NewsRec-main/Tiny-NewsRec/utils.py | import logging
import os
import sys
import torch
import numpy as np
import argparse
import re
from tnlrv3.modeling import TuringNLRv3ForSequenceClassification
from tnlrv3.configuration_tnlrv3 import TuringNLRv3Config
from tnlrv3.tokenization_tnlrv3 import TuringNLRv3Tokenizer
from transformers import BertTokenizer, B... | 4,173 | 27.589041 | 94 | py |
Tiny-NewsRec | Tiny-NewsRec-main/Tiny-NewsRec/run.py | import numpy as np
import torch
import logging
from tqdm.auto import tqdm
import torch.optim as optim
import utils
import os
from pathlib import Path
import random
from dataloader import DataLoaderTrain, DataLoaderTest
from torch.utils.data import Dataset, DataLoader
from streaming import get_stat, get_worker_files
imp... | 15,933 | 32.687104 | 118 | py |
Tiny-NewsRec | Tiny-NewsRec-main/Tiny-NewsRec/parameters.py | import argparse
import utils
import logging
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument("--mode",
type=str,
default="train",
choices=['train', 'test', 'get_teacher_emb'])
parser.add_argument(
"--tr... | 4,778 | 37.232 | 99 | py |
Tiny-NewsRec | Tiny-NewsRec-main/Tiny-NewsRec/model_bert_2.py | import numpy as np
import torch
from torch import nn
from utils import MODEL_CLASSES
class AttentionPooling(nn.Module):
def __init__(self, emb_size, hidden_size):
super(AttentionPooling, self).__init__()
self.att_fc1 = nn.Linear(emb_size, hidden_size)
self.att_fc2 = nn.Linear(hidden_size, ... | 8,043 | 36.588785 | 84 | py |
Tiny-NewsRec | Tiny-NewsRec-main/Tiny-NewsRec/model_bert.py | import numpy as np
import torch
from torch import nn
import torch.nn.functional as F
from utils import MODEL_CLASSES
class AttentionPooling(nn.Module):
def __init__(self, emb_size, hidden_size):
super(AttentionPooling, self).__init__()
self.att_fc1 = nn.Linear(emb_size, hidden_size)
self.... | 12,966 | 41.375817 | 141 | py |
Tiny-NewsRec | Tiny-NewsRec-main/Tiny-NewsRec/tnlrv3/convert_state_dict.py | import torch
import logging
from transformers.modeling_utils import cached_path, WEIGHTS_NAME, TF2_WEIGHTS_NAME, TF_WEIGHTS_NAME
logger = logging.getLogger(__name__)
def get_checkpoint_from_transformer_cache(
archive_file, pretrained_model_name_or_path, pretrained_model_archive_map,
cache_dir, force... | 3,162 | 40.077922 | 109 | py |
Tiny-NewsRec | Tiny-NewsRec-main/Tiny-NewsRec/tnlrv3/s2s_loader.py | import numpy as np
from random import randint
import logging
import torch
import torch.utils.data
logger = logging.getLogger(__name__)
def get_random_word(vocab_words):
i = randint(0, len(vocab_words)-1)
return vocab_words[i]
def batch_list_to_batch_tensors(batch):
batch_tensors = []
for x in zip... | 5,318 | 32.878981 | 90 | py |
Tiny-NewsRec | Tiny-NewsRec-main/Tiny-NewsRec/tnlrv3/modeling.py | from __future__ import absolute_import, division, print_function, unicode_literals
import logging
import math
import os
import torch
from torch import nn
from torch.nn.modules.loss import _Loss
import torch.nn.functional as F
from transformers.modeling_bert import \
BertPreTrainedModel, BertSelfOutput, BertInter... | 37,949 | 46.319202 | 146 | py |
Tiny-NewsRec | Tiny-NewsRec-main/Tiny-NewsRec/tnlrv3/utils.py | from __future__ import absolute_import, division, print_function
import logging
import os
import json
import random
import glob
import torch
import tqdm
import array
import collections
import torch.utils.data
from transformers.file_utils import WEIGHTS_NAME
try:
import lmdb
except:
pass
OPTIM_NAME = "optimize... | 14,533 | 35.888325 | 119 | py |
Tiny-NewsRec | Tiny-NewsRec-main/Tiny-NewsRec/tnlrv3/modeling_decoding.py | # coding=utf-8
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import copy
import json
import math
import logging
import numpy as np
import torch
from torch import nn
from torch.nn import CrossEntropyLoss
import torch.nn.functional as F
from tor... | 67,538 | 44.944898 | 139 | py |
Tiny-NewsRec | Tiny-NewsRec-main/PLM-NR/dataloader.py | import sys
import traceback
import logging
import random
from queue import Queue
from concurrent.futures import ThreadPoolExecutor
import numpy as np
import torch
from torch.utils.data import IterableDataset
from streaming import StreamSampler
class DataLoaderTrain(IterableDataset):
def __init__(self,
... | 10,287 | 34.84669 | 92 | py |
Tiny-NewsRec | Tiny-NewsRec-main/PLM-NR/utils.py | import logging
import os
import sys
import torch
import numpy as np
import argparse
import re
from tnlrv3.modeling import TuringNLRv3ForSequenceClassification
from tnlrv3.configuration_tnlrv3 import TuringNLRv3Config
from tnlrv3.tokenization_tnlrv3 import TuringNLRv3Tokenizer
from transformers import BertTokenizer, B... | 4,173 | 27.589041 | 94 | py |
Tiny-NewsRec | Tiny-NewsRec-main/PLM-NR/run.py | import numpy as np
import torch
import logging
from tqdm.auto import tqdm
import torch.optim as optim
import utils
import os
from pathlib import Path
import random
from dataloader import DataLoaderTrain, DataLoaderTest
from torch.utils.data import Dataset, DataLoader
from streaming import get_stat, get_worker_files
fr... | 12,540 | 32.265252 | 97 | py |
Tiny-NewsRec | Tiny-NewsRec-main/PLM-NR/parameters.py | import argparse
import utils
import logging
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument("--mode",
type=str,
default="train",
choices=['train', 'test'])
parser.add_argument(
"--train_data_dir",
... | 4,252 | 32.753968 | 83 | py |
Tiny-NewsRec | Tiny-NewsRec-main/PLM-NR/model_bert.py | import numpy as np
import torch
from torch import nn
from utils import MODEL_CLASSES
class AttentionPooling(nn.Module):
def __init__(self, emb_size, hidden_size):
super(AttentionPooling, self).__init__()
self.att_fc1 = nn.Linear(emb_size, hidden_size)
self.att_fc2 = nn.Linear(hidden_size,... | 8,077 | 37.836538 | 99 | py |
Tiny-NewsRec | Tiny-NewsRec-main/PLM-NR/tnlrv3/convert_state_dict.py | import torch
import logging
from transformers.modeling_utils import cached_path, WEIGHTS_NAME, TF2_WEIGHTS_NAME, TF_WEIGHTS_NAME
logger = logging.getLogger(__name__)
def get_checkpoint_from_transformer_cache(
archive_file, pretrained_model_name_or_path, pretrained_model_archive_map,
cache_dir, force... | 3,162 | 40.077922 | 109 | py |
Tiny-NewsRec | Tiny-NewsRec-main/PLM-NR/tnlrv3/s2s_loader.py | import numpy as np
from random import randint
import logging
import torch
import torch.utils.data
logger = logging.getLogger(__name__)
def get_random_word(vocab_words):
i = randint(0, len(vocab_words)-1)
return vocab_words[i]
def batch_list_to_batch_tensors(batch):
batch_tensors = []
for x in zip... | 5,318 | 32.878981 | 90 | py |
Tiny-NewsRec | Tiny-NewsRec-main/PLM-NR/tnlrv3/modeling.py | from __future__ import absolute_import, division, print_function, unicode_literals
import logging
import math
import os
import torch
from torch import nn
from torch.nn.modules.loss import _Loss
import torch.nn.functional as F
from transformers.modeling_bert import \
BertPreTrainedModel, BertSelfOutput, BertInter... | 38,964 | 44.360885 | 146 | py |
Tiny-NewsRec | Tiny-NewsRec-main/PLM-NR/tnlrv3/utils.py | from __future__ import absolute_import, division, print_function
import logging
import os
import json
import random
import glob
import torch
import tqdm
import array
import collections
import torch.utils.data
from transformers.file_utils import WEIGHTS_NAME
try:
import lmdb
except:
pass
OPTIM_NAME = "optimize... | 14,533 | 35.888325 | 119 | py |
Tiny-NewsRec | Tiny-NewsRec-main/PLM-NR/tnlrv3/modeling_decoding.py | # coding=utf-8
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import copy
import json
import math
import logging
import numpy as np
import torch
from torch import nn
from torch.nn import CrossEntropyLoss
import torch.nn.functional as F
from tor... | 67,538 | 44.944898 | 139 | py |
DDOD | DDOD-main/setup.py | #!/usr/bin/env python
import os
from setuptools import find_packages, setup
import torch
from torch.utils.cpp_extension import (BuildExtension, CppExtension,
CUDAExtension)
def readme():
with open('README.md', encoding='utf-8') as f:
content = f.read()
return co... | 5,899 | 35.196319 | 125 | py |
DDOD | DDOD-main/coco_cfg/atss_r50_1x.py | fp16 = dict(loss_scale=512.)
model = dict(
type='ATSS',
backbone=dict(
type='ResNet',
depth=50,
num_stages=4,
out_indices=(0, 1, 2, 3),
frozen_stages=1,
norm_cfg=dict(type='BN', requires_grad=True),
norm_eval=True,
style='pytorch',
init_cfg... | 4,154 | 29.777778 | 99 | py |
DDOD | DDOD-main/coco_cfg/ddod_r50_1x.py | fp16 = dict(loss_scale=512.)
model = dict(
type='ATSS',
backbone=dict(
type='ResNet',
depth=50,
num_stages=4,
out_indices=(0, 1, 2, 3),
frozen_stages=1,
norm_cfg=dict(type='BN', requires_grad=True),
norm_eval=True,
style='pytorch',
init_cfg... | 4,226 | 30.080882 | 99 | py |
DDOD | DDOD-main/coco_cfg/ddod_r50_1x_fcos.py | fp16 = dict(loss_scale=512.)
model = dict(
type='ATSS',
backbone=dict(
type='ResNet',
depth=50,
num_stages=4,
out_indices=(0, 1, 2, 3),
frozen_stages=1,
norm_cfg=dict(type='BN', requires_grad=True),
norm_eval=True,
style='pytorch',
init_cfg... | 4,374 | 30.028369 | 99 | py |
DDOD | DDOD-main/tools/test.py | import argparse
import os
import os.path as osp
import time
import warnings
import mmcv
import torch
from mmcv import Config, DictAction
from mmcv.cnn import fuse_conv_bn
from mmcv.parallel import MMDataParallel, MMDistributedDataParallel
from mmcv.runner import (get_dist_info, init_dist, load_checkpoint,
... | 9,315 | 38.142857 | 79 | py |
DDOD | DDOD-main/tools/train.py | import argparse
import copy
import os
import os.path as osp
import time
import warnings
import mmcv
import torch
from mmcv import Config, DictAction
from mmcv.runner import get_dist_info, init_dist
from mmcv.utils import get_git_hash
from mmdet import __version__
from mmdet.apis import set_random_seed, train_detector... | 6,914 | 35.587302 | 79 | py |
DDOD | DDOD-main/tools/deployment/mmdet2torchserve.py | 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 ImportError:
package_model = None
def mmdet2t... | 3,645 | 32.145455 | 78 | py |
DDOD | DDOD-main/tools/deployment/onnx2tensorrt.py | import argparse
import os
import os.path as osp
import warnings
import numpy as np
import onnx
import torch
from mmcv import Config
from mmcv.tensorrt import is_tensorrt_plugin_loaded, onnx2trt, save_trt_engine
from mmdet.core.export import preprocess_example_input
from mmdet.core.export.model_wrappers import (ONNXRu... | 8,467 | 32.338583 | 78 | py |
DDOD | DDOD-main/tools/deployment/mmdet_handler.py | import base64
import os
import mmcv
import torch
from ts.torch_handler.base_handler import BaseHandler
from mmdet.apis import inference_detector, init_detector
class MMdetHandler(BaseHandler):
threshold = 0.5
def initialize(self, context):
properties = context.system_properties
self.map_loc... | 2,462 | 34.185714 | 79 | py |
DDOD | DDOD-main/tools/deployment/pytorch2onnx.py | import argparse
import os.path as osp
import warnings
from functools import partial
import numpy as np
import onnx
import torch
from mmcv import Config, DictAction
from mmdet.core.export import build_model_from_cfg, preprocess_example_input
from mmdet.core.export.model_wrappers import ONNXRuntimeDetector
def pytorc... | 10,374 | 32.905229 | 79 | py |
DDOD | DDOD-main/tools/model_converters/selfsup2mmdet.py | import argparse
from collections import OrderedDict
import torch
def moco_convert(src, dst):
"""Convert keys in pycls pretrained moco models to mmdet style."""
# load caffe model
moco_model = torch.load(src)
blobs = moco_model['state_dict']
# convert to pytorch style
state_dict = OrderedDict(... | 1,195 | 27.47619 | 74 | py |
DDOD | DDOD-main/tools/model_converters/publish_model.py | import argparse
import subprocess
import torch
def parse_args():
parser = argparse.ArgumentParser(
description='Process a checkpoint to be published')
parser.add_argument('in_file', help='input checkpoint filename')
parser.add_argument('out_file', help='output checkpoint filename')
args = par... | 1,253 | 28.162791 | 78 | py |
DDOD | DDOD-main/tools/model_converters/regnet2mmdet.py | import argparse
from collections import OrderedDict
import torch
def convert_stem(model_key, model_weight, state_dict, converted_names):
new_key = model_key.replace('stem.conv', 'conv1')
new_key = new_key.replace('stem.bn', 'bn1')
state_dict[new_key] = model_weight
converted_names.add(model_key)
... | 3,015 | 32.511111 | 77 | py |
DDOD | DDOD-main/tools/model_converters/upgrade_model_version.py | import argparse
import re
import tempfile
from collections import OrderedDict
import torch
from mmcv import Config
def is_head(key):
valid_head_list = [
'bbox_head', 'mask_head', 'semantic_head', 'grid_head', 'mask_iou_head'
]
return any(key.startswith(h) for h in valid_head_list)
def parse_co... | 6,800 | 31.385714 | 79 | py |
DDOD | DDOD-main/tools/model_converters/upgrade_ssd_version.py | import argparse
import tempfile
from collections import OrderedDict
import torch
from mmcv import Config
def parse_config(config_strings):
temp_file = tempfile.NamedTemporaryFile()
config_path = f'{temp_file.name}.py'
with open(config_path, 'w') as f:
f.write(config_strings)
config = Config.... | 1,741 | 29.034483 | 78 | py |
DDOD | DDOD-main/tools/model_converters/detectron2pytorch.py | import argparse
from collections import OrderedDict
import mmcv
import torch
arch_settings = {50: (3, 4, 6, 3), 101: (3, 4, 23, 3)}
def convert_bn(blobs, state_dict, caffe_name, torch_name, converted_names):
# detectron replace bn with affine channel layer
state_dict[torch_name + '.bias'] = torch.from_numpy... | 3,530 | 41.542169 | 78 | py |
DDOD | DDOD-main/tools/analysis_tools/benchmark.py | import argparse
import os
import time
import torch
from mmcv import Config, DictAction
from mmcv.cnn import fuse_conv_bn
from mmcv.parallel import MMDistributedDataParallel
from mmcv.runner import init_dist, load_checkpoint, wrap_fp16_model
from mmdet.datasets import (build_dataloader, build_dataset,
... | 4,795 | 32.538462 | 78 | py |
DDOD | DDOD-main/tools/analysis_tools/get_flops.py | import argparse
import torch
from mmcv import Config, DictAction
from mmdet.models import build_detector
try:
from mmcv.cnn import get_model_complexity_info
except ImportError:
raise ImportError('Please upgrade mmcv to >0.6.2')
def parse_args():
parser = argparse.ArgumentParser(description='Train a det... | 2,566 | 30.304878 | 79 | py |
DDOD | DDOD-main/tools/analysis_tools/test_robustness.py | import argparse
import copy
import os
import os.path as osp
import mmcv
import torch
from mmcv import DictAction
from mmcv.parallel import MMDataParallel, MMDistributedDataParallel
from mmcv.runner import (get_dist_info, init_dist, load_checkpoint,
wrap_fp16_model)
from pycocotools.coco import... | 15,373 | 38.319693 | 79 | py |
DDOD | DDOD-main/crowd_code/utils/SGD_bias.py | import torch
from torch.optim.optimizer import Optimizer, required
class SGD(Optimizer):
"""Implements stochastic gradient descent (optionally with momentum).
Args:
params (iterable): iterable of parameters to optimize or dicts defining
parameter groups
lr (float): learning rate
... | 2,777 | 39.26087 | 88 | py |
DDOD | DDOD-main/.dev_scripts/benchmark_filter.py | import argparse
import os
import os.path as osp
def parse_args():
parser = argparse.ArgumentParser(description='Filter configs to train')
parser.add_argument(
'--basic-arch',
action='store_true',
help='to train models in basic arch')
parser.add_argument(
'--datasets', actio... | 7,048 | 41.209581 | 92 | py |
DDOD | DDOD-main/.dev_scripts/gather_models.py | import argparse
import glob
import json
import os.path as osp
import shutil
import subprocess
from collections import OrderedDict
import mmcv
import torch
import yaml
def ordered_yaml_dump(data, stream=None, Dumper=yaml.SafeDumper, **kwds):
class OrderedDumper(Dumper):
pass
def _dict_representer(du... | 9,240 | 34.817829 | 79 | py |
DDOD | DDOD-main/.dev_scripts/benchmark_inference_fps.py | import argparse
import os
import os.path as osp
import mmcv
from mmcv import Config, DictAction
from mmcv.runner import init_dist
from tools.analysis_tools.benchmark import measure_inferense_speed
def parse_args():
parser = argparse.ArgumentParser(
description='MMDet benchmark a model of FPS')
parser... | 3,578 | 37.074468 | 79 | py |
DDOD | DDOD-main/.dev_scripts/batch_test_list.py | # yapf: disable
atss = dict(
config='configs/atss/atss_r50_fpn_1x_coco.py',
checkpoint='atss_r50_fpn_1x_coco_20200209-985f7bd0.pth',
eval='bbox',
metric=dict(bbox_mAP=39.4),
)
autoassign = dict(
config='configs/autoassign/autoassign_r50_fpn_8x2_1x_coco.py',
checkpoint='auto_assign_r50_fpn_1x_coc... | 12,184 | 34.318841 | 117 | py |
DDOD | DDOD-main/tests/test_runtime/async_benchmark.py | import asyncio
import os
import shutil
import urllib
import mmcv
import torch
from mmdet.apis import (async_inference_detector, inference_detector,
init_detector)
from mmdet.utils.contextmanagers import concurrent
from mmdet.utils.profiling import profile_time
async def main():
"""Benchm... | 3,167 | 30.058824 | 77 | py |
DDOD | DDOD-main/tests/test_runtime/test_async.py | """Tests for async interface."""
import asyncio
import os
import sys
import asynctest
import mmcv
import torch
from mmdet.apis import async_inference_detector, init_detector
if sys.version_info >= (3, 7):
from mmdet.utils.contextmanagers import concurrent
class AsyncTestCase(asynctest.TestCase):
use_defau... | 2,560 | 29.855422 | 75 | py |
DDOD | DDOD-main/tests/test_runtime/test_config.py | from os.path import dirname, exists, join, relpath
from unittest.mock import Mock
import pytest
import torch
from mmcv.runner import build_optimizer
from mmdet.core import BitmapMasks, PolygonMasks
from mmdet.datasets.builder import DATASETS
from mmdet.datasets.utils import NumClassCheckHook
def _get_config_directo... | 17,127 | 39.112412 | 79 | py |
DDOD | DDOD-main/tests/test_runtime/test_eval_hook.py | import os.path as osp
import tempfile
import unittest.mock as mock
from collections import OrderedDict
from unittest.mock import MagicMock, patch
import pytest
import torch
import torch.nn as nn
from mmcv.runner import EpochBasedRunner, build_optimizer
from mmcv.utils import get_logger
from torch.utils.data import Dat... | 8,542 | 32.900794 | 79 | py |
DDOD | DDOD-main/tests/test_runtime/test_fp16.py | import numpy as np
import pytest
import torch
import torch.nn as nn
from mmcv.runner import auto_fp16, force_fp32
from mmcv.runner.fp16_utils import cast_tensor_type
def test_cast_tensor_type():
inputs = torch.FloatTensor([5.])
src_type = torch.float32
dst_type = torch.int32
outputs = cast_tensor_type... | 9,698 | 31.222591 | 75 | py |
DDOD | DDOD-main/tests/test_models/test_loss.py | import pytest
import torch
from mmdet.models.losses import (BalancedL1Loss, BoundedIoULoss, CIoULoss,
CrossEntropyLoss, DIoULoss,
DistributionFocalLoss, FocalLoss,
GaussianFocalLoss, GIoULoss, IoULoss, L1Loss,
... | 3,668 | 34.970588 | 79 | py |
DDOD | DDOD-main/tests/test_models/test_forward.py | """pytest tests/test_forward.py."""
import copy
from os.path import dirname, exists, join
import numpy as np
import pytest
import torch
def _get_config_directory():
"""Find the predefined detector config directory."""
try:
# Assume we are running in the source mmdetection repo
repo_dpath = di... | 19,749 | 30.701445 | 110 | py |
DDOD | DDOD-main/tests/test_models/test_necks.py | import pytest
import torch
from torch.nn.modules.batchnorm import _BatchNorm
from mmdet.models.necks import (FPN, ChannelMapper, CTResNetNeck,
DilatedEncoder, SSDNeck, YOLOV3Neck)
def test_fpn():
"""Tests fpn."""
s = 64
in_channels = [8, 16, 32, 64]
feat_sizes = [s // ... | 12,179 | 31.393617 | 79 | py |
DDOD | DDOD-main/tests/test_models/test_backbones/test_hourglass.py | import pytest
import torch
from mmdet.models.backbones.hourglass import HourglassNet
def test_hourglass_backbone():
with pytest.raises(AssertionError):
# HourglassNet's num_stacks should larger than 0
HourglassNet(num_stacks=0)
with pytest.raises(AssertionError):
# len(stage_channels... | 1,301 | 27.933333 | 65 | py |
DDOD | DDOD-main/tests/test_models/test_backbones/test_res2net.py | import pytest
import torch
from mmdet.models.backbones import Res2Net
from mmdet.models.backbones.res2net import Bottle2neck
from .utils import is_block
def test_res2net_bottle2neck():
with pytest.raises(AssertionError):
# Style must be in ['pytorch', 'caffe']
Bottle2neck(64, 64, base_width=26, s... | 1,961 | 30.142857 | 72 | py |
DDOD | DDOD-main/tests/test_models/test_backbones/test_resnet.py | import pytest
import torch
from mmcv import assert_params_all_zeros
from mmcv.ops import DeformConv2dPack
from torch.nn.modules import AvgPool2d, GroupNorm
from torch.nn.modules.batchnorm import _BatchNorm
from mmdet.models.backbones import ResNet, ResNetV1d
from mmdet.models.backbones.resnet import BasicBlock, Bottle... | 23,501 | 34.235382 | 78 | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.