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 |
|---|---|---|---|---|---|---|
QCRNet | QCRNet-main/CRNet_LA/dataset/cost2100.py | import os
import numpy as np
import scipy.io as sio
import torch
from torch.utils.data import DataLoader, TensorDataset
__all__ = ['Cost2100DataLoader']
class Cost2100DataLoader(object):
r""" PyTorch DataLoader for COST2100 dataset.
"""
def __init__(self, root, batch_size, num_workers, pin_memory, scena... | 2,570 | 39.809524 | 84 | py |
QCRNet | QCRNet-main/CRNet_LA/models/quantization.py | import torch
from torch import nn
import math
NORM = 1
def loss(x, y):
z = x - y
return torch.norm(z)
class quant(torch.autograd.Function):
@staticmethod
def forward(ctx, x, num_levels, thrs, levels):
y = torch.zeros_like(x)
y_zeros = torch.zeros_like(x)
for i in range(num_le... | 2,985 | 28.27451 | 106 | py |
QCRNet | QCRNet-main/CRNet_LA/models/crnet.py | r""" The proposed CRNet
"""
import torch
import torch.nn as nn
import sys
from collections import OrderedDict
#import quantization
from .quantization import Quantization
sys.path.append("..")
from utils import logger
import scipy.io as io
import numpy as np
import os
__all__ = ["crnet"]
class ConvBN(nn.Sequential)... | 5,169 | 32.79085 | 107 | py |
QCRNet | QCRNet-main/CRNet_LA/utils/statics.py | import torch
__all__ = ['AverageMeter', 'evaluator']
class AverageMeter(object):
r"""Computes and stores the average and current value
Imported from https://github.com/pytorch/examples/blob/master/imagenet/main.py#L247-L262
"""
def __init__(self, name):
self.reset()
self.val = 0
... | 2,431 | 31.864865 | 98 | py |
QCRNet | QCRNet-main/CRNet_LA/utils/scheduler.py | import math
from torch.optim.lr_scheduler import _LRScheduler
__all__ = ['WarmUpCosineAnnealingLR', 'FakeLR']
class WarmUpCosineAnnealingLR(_LRScheduler):
def __init__(self, optimizer, T_max, T_warmup, eta_min=0, last_epoch=-1):
self.T_max = T_max
self.T_warmup = T_warmup
self.eta_min = e... | 955 | 33.142857 | 104 | py |
QCRNet | QCRNet-main/CRNet_LA/utils/init.py | import os
import random
import thop
import torch
from models import crnet
from utils import logger, line_seg
__all__ = ["init_device", "init_model"]
def init_device(seed=None, cpu=None, gpu=None, affinity=None):
# set the CPU affinity
if affinity is not None:
os.system(f'taskset -p {affinity} {os.ge... | 2,269 | 30.09589 | 79 | py |
QCRNet | QCRNet-main/CRNet_LA/utils/solver.py | import time
import os
import torch
import math
from collections import namedtuple
from utils import logger
from utils.statics import AverageMeter, evaluator
__all__ = [ 'Tester']
field = ('nmse', 'rho', 'epoch','SNR')
Result = namedtuple('Result', field, defaults=(None,) * len(field))
class Tester:
r""" The ... | 2,496 | 31.855263 | 127 | py |
RDF-to-Text | RDF-to-Text-master/Encoder_Decoder.py | from __future__ import unicode_literals, print_function, division
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence
from utils import config
import torch_geometric
from torch_geometric.nn import GCNConv, NNConv
import numpy as np... | 46,649 | 43.301994 | 125 | py |
RDF-to-Text | RDF-to-Text-master/GTRModel.py | from beam_search_PG import Beam, sort_beams
from torch_geometric.data import DataLoader
from Encoder_Decoder import Encoder, Decoder, ReduceState, GCNEncoder, GCNEncoder0, GTREncoder, GTREncoder2
from utils import config
import torch
import torch_geometric
import numpy as np
use_cuda = config.use_cuda and torch.cuda.i... | 15,767 | 50.029126 | 122 | py |
RDF-to-Text | RDF-to-Text-master/data_loader.py | import nltk
import json
import torch
import torch.utils.data as data
import pickle as pkl
from torch_geometric.data import Data
from utils import config
import numpy as np
class Dataset(data.Dataset):
"""Custom data.Dataset compatible with data.DataLoader."""
def __init__(self, data_path, word2id, max_enc_step... | 36,654 | 39.682575 | 111 | py |
RDF-to-Text | RDF-to-Text-master/main_PG.py | import os
import time
# import yaml
import json
import random
import torch
import torch.optim as optim
from collections import namedtuple
import math
import sys
from data_loader import get_loader, get_gcn_loader, get_gcn_lstm_loader, \
get_gtr_loader, get_gcn_gtr_loader
from torch_geometric.data import DataLoader
... | 10,132 | 43.248908 | 173 | py |
RDF-to-Text | RDF-to-Text-master/LSTMModel.py | from beam_search_PG import Beam, sort_beams
from torch_geometric.data import DataLoader
from Encoder_Decoder import Encoder, Decoder, ReduceState, GCNEncoder
from utils import config
import torch
use_cuda = config.use_cuda and torch.cuda.is_available()
class LSTMModel(object):
def __init__(self, model_file_path=N... | 13,144 | 48.603774 | 123 | py |
RDF-to-Text | RDF-to-Text-master/beam_search_PG.py | from __future__ import unicode_literals, print_function, division
import sys
# reload(sys)
# sys.setdefaultencoding('utf8')
import os
import time
import torch
from torch.autograd import Variable
# from data_util.batcher import Batcher
# from data_util.data import Vocab
# from data_util import data, config
# from d... | 8,222 | 38.157143 | 116 | py |
RDF-to-Text | RDF-to-Text-master/GCNGTR2Model.py | from beam_search_PG import Beam, sort_beams
from torch_geometric.data import DataLoader
from Encoder_Decoder import Encoder, Decoder, ReduceState, GCNEncoder, GCNEncoder0, GTREncoder2
from utils import config
import torch
import torch_geometric
use_cuda = config.use_cuda and torch.cuda.is_available()
class GCNGTR2Mod... | 20,379 | 49.320988 | 141 | py |
RDF-to-Text | RDF-to-Text-master/GCNModel.py | from beam_search_PG import Beam, sort_beams
from torch_geometric.data import DataLoader
from Encoder_Decoder import Encoder, Decoder, ReduceState, GCNEncoder, GCNEncoder0
from utils import config
import torch
import torch_geometric
use_cuda = config.use_cuda and torch.cuda.is_available()
class GCNModel(object):
d... | 14,294 | 48.982517 | 137 | py |
RDF-to-Text | RDF-to-Text-master/webnlg_eval_scripts/webnlg2_gcnonmt_input.py | """
Laura Perez
networkx documentation:
https://networkx.github.io/documentation/networkx-1.10/reference/classes.multidigraph.html#networkx.MultiDiGraph
"""
import networkx as nx
import re
import sys
import getopt
import pickle as pkl
from collections import defaultdict
from benchmark_reader import Benchmark
from we... | 14,675 | 41.662791 | 142 | py |
RDF-to-Text | RDF-to-Text-master/webnlg_eval_scripts/webnlg_gcnonmt_input.py | """
Laura Perez
networkx documentation:
https://networkx.github.io/documentation/networkx-1.10/reference/classes.multidigraph.html#networkx.MultiDiGraph
"""
import networkx as nx
import re
import sys
import getopt
from collections import defaultdict
from benchmark_reader import Benchmark
from webnlg_baseline_input i... | 14,922 | 41.155367 | 142 | py |
RDF-to-Text | RDF-to-Text-master/webnlg_eval_scripts/webnlg_re_input.py | import sys
import getopt
import json
import torch
import onmt.inputters as inputters
import os
def gen_re_files2(inputdir,vocab_file_path,data_type):
'''
:param inputdir: e.g. absolute path
:param vocab_file_path: e.g. 'data/GCN_DATA_DELEX.vocab.pt'
:param data_type: e.g. 'gcn'
:return:
'''
... | 12,654 | 34.951705 | 140 | py |
Uni-Encoder | Uni-Encoder-main/uni_encoder.py | import torch
import torch.nn as nn
import os
import math
from transformers import (
BertTokenizer,
BertConfig,
BertForPreTraining,
BertModel,
AdamW,
WEIGHTS_NAME,
CONFIG_NAME,
)
from torch.nn.utils.rnn import pad_sequence
import torch.nn.functional as F
class U... | 6,107 | 43.911765 | 125 | py |
Uni-Encoder | Uni-Encoder-main/persona-chat/train_dist.py | import os
import math
import torch
import numpy as np
import random
from argparse import ArgumentParser
from pprint import pformat
from torch.nn.parallel import DataParallel
from torch.nn.parallel import DistributedDataParallel, DataParallel
from torch.optim.lr_scheduler import LambdaLR
import sys
sys.path.append("..")... | 15,639 | 35.456876 | 137 | py |
Uni-Encoder | Uni-Encoder-main/persona-chat/test.py | from argparse import ArgumentParser
from rank import Ranker
import torch
import json
import math
import os
from tqdm import tqdm
os.environ['CUDA_VISIBLE_DEVICES']='0'
parser = ArgumentParser()
parser.add_argument(
"--model_checkpoint",
type=str,
default="models/",
help="Path or URL of the model",
)
par... | 1,686 | 24.953846 | 75 | py |
Uni-Encoder | Uni-Encoder-main/persona-chat/rank.py | import random
import numpy as np
from itertools import chain
from argparse import ArgumentParser
import torch
import torch.nn.functional as F
from torch.nn.utils.rnn import pad_sequence
import sys
import os
sys.path.append("..")
from uni_encoder import *
from torch.nn.parallel import DataParallel
SPECIAL_TOKENS = ["[C... | 5,695 | 34.378882 | 104 | py |
Uni-Encoder | Uni-Encoder-main/persona-chat/utils/dataloader.py | import torch
from transformers import cached_path
import json
from utils.dataset import CUSTdataset
from torch.utils.data import DataLoader
from torch.utils.data.distributed import DistributedSampler
def get_data(tokenizer, dataset_path, dataset_cache, logger):
cache_dir = "cache/dataset_cache_" + type(tokenizer).... | 2,347 | 35.123077 | 83 | py |
Uni-Encoder | Uni-Encoder-main/persona-chat/utils/dataset.py | import torch
from torch.utils.data import Dataset
from itertools import chain
from transformers import DataCollatorForLanguageModeling
from torch.nn.utils.rnn import pad_sequence
SPECIAL_TOKENS = ["[CLS]", "[SEP]", "[unused1]", "[unused2]"]
class CUSTdataset(Dataset):
def __init__(self, data, tokenizer, use_in_... | 7,821 | 38.306533 | 125 | py |
Uni-Encoder | Uni-Encoder-main/ubuntu/train_dist.py | import os
import math
import torch
import numpy as np
import random
from argparse import ArgumentParser
from pprint import pformat
from torch.nn.parallel import DataParallel
from torch.nn.parallel import DistributedDataParallel, DataParallel
from torch.optim.lr_scheduler import LambdaLR
import sys
sys.path.append("..")... | 17,080 | 36.623348 | 144 | py |
Uni-Encoder | Uni-Encoder-main/ubuntu/test.py | from argparse import ArgumentParser
from rank import Ranker
import torch
import json
import os
from tqdm import tqdm
os.environ['CUDA_VISIBLE_DEVICES']='6'
parser = ArgumentParser()
parser.add_argument(
"--model_checkpoint",
type=str,
default="models/",
help="Path or URL of the model",
)
parser.add_arg... | 1,905 | 24.756757 | 75 | py |
Uni-Encoder | Uni-Encoder-main/ubuntu/rank.py | import random
import numpy as np
from itertools import chain
from argparse import ArgumentParser
import torch
import torch.nn.functional as F
from torch.nn.utils.rnn import pad_sequence
import sys
import os
sys.path.append("..")
from uni_encoder import *
from torch.nn.parallel import DataParallel
SPECIAL_TOKENS = ["[C... | 6,585 | 34.408602 | 122 | py |
Uni-Encoder | Uni-Encoder-main/ubuntu/utils/dataloader.py | import torch
from transformers import cached_path
import json
from utils.dataset import CUSTdataset
from torch.utils.data import DataLoader
from torch.utils.data.distributed import DistributedSampler
def get_data(tokenizer, dataset_path, dataset_cache, logger):
cache_dir = "cache/dataset_cache_" + type(tokenizer).... | 2,347 | 35.123077 | 83 | py |
Uni-Encoder | Uni-Encoder-main/ubuntu/utils/dataset.py | import torch
from torch.utils.data import Dataset
from itertools import chain
from transformers import DataCollatorForLanguageModeling
from torch.nn.utils.rnn import pad_sequence
SPECIAL_TOKENS = ["[CLS]", "[SEP]", "[unused1]", "[unused2]"]
class CUSTdataset(Dataset):
def __init__(self, data, tokenizer, use_in_... | 8,601 | 38.278539 | 125 | py |
Uni-Encoder | Uni-Encoder-main/douban/train_dist.py | import os
import math
import torch
import numpy as np
import random
from argparse import ArgumentParser
from pprint import pformat
from torch.nn.parallel import DataParallel
from torch.nn.parallel import DistributedDataParallel, DataParallel
from torch.optim.lr_scheduler import LambdaLR, CosineAnnealingLR
import sys
sy... | 16,446 | 36.042793 | 137 | py |
Uni-Encoder | Uni-Encoder-main/douban/test.py | from argparse import ArgumentParser
from rank import Ranker
import torch
import json
import math
import os
from tqdm import tqdm
os.environ['CUDA_VISIBLE_DEVICES']='0'
parser = ArgumentParser()
parser.add_argument(
"--model_checkpoint",
type=str,
default="models/",
help="Path or URL of the model",
)
par... | 3,449 | 26.165354 | 75 | py |
Uni-Encoder | Uni-Encoder-main/douban/rank.py | import random
import numpy as np
from itertools import chain
from argparse import ArgumentParser
import torch
import torch.nn.functional as F
from torch.nn.utils.rnn import pad_sequence
import sys
import os
sys.path.append("..")
from uni_encoder import *
from torch.nn.parallel import DataParallel
SPECIAL_TOKENS = ["[... | 6,690 | 34.402116 | 122 | py |
Uni-Encoder | Uni-Encoder-main/douban/utils/dataloader.py | import torch
from transformers import cached_path
import json
from utils.dataset import CUSTdataset
from torch.utils.data import DataLoader, dataset
from torch.utils.data.distributed import DistributedSampler
def get_data(tokenizer, dataset_path, dataset_cache, logger):
cache_dir = "cache/dataset_cache_" + type(to... | 2,473 | 34.855072 | 83 | py |
Uni-Encoder | Uni-Encoder-main/douban/utils/dataset.py | import torch
from torch.utils.data import Dataset
from itertools import chain
from transformers import DataCollatorForLanguageModeling
from torch.nn.utils.rnn import pad_sequence
SPECIAL_TOKENS = ["[CLS]", "[SEP]", "[unused1]", "[unused2]"]
class CUSTdataset(Dataset):
def __init__(self, data, tokenizer, use_in_... | 11,316 | 40.454212 | 155 | py |
CROWN-IBP | CROWN-IBP-master/model_defs_gowal.py | ## Copyright (C) 2019, Huan Zhang <huan@huan-zhang.com>
## Hongge Chen <chenhg@mit.edu>
## Chaowei Xiao <xiaocw@umich.edu>
##
## This program is licenced under the BSD 2-Clause License,
## contained in the LICENCE file in this directory.
##
# from convex_adversarial import Dens... | 1,314 | 27.586957 | 64 | py |
CROWN-IBP | CROWN-IBP-master/model_defs.py | ## Copyright (C) 2019, Huan Zhang <huan@huan-zhang.com>
## Hongge Chen <chenhg@mit.edu>
## Chaowei Xiao <xiaocw@umich.edu>
##
## This program is licenced under the BSD 2-Clause License,
## contained in the LICENCE file in this directory.
##
# from convex_adversarial import Dens... | 10,549 | 33.818482 | 200 | py |
CROWN-IBP | CROWN-IBP-master/argparser.py | ## Copyright (C) 2019, Huan Zhang <huan@huan-zhang.com>
## Hongge Chen <chenhg@mit.edu>
## Chaowei Xiao <xiaocw@umich.edu>
##
## This program is licenced under the BSD 2-Clause License,
## contained in the LICENCE file in this directory.
##
import os
import torch
import random
i... | 2,073 | 26.653333 | 131 | py |
CROWN-IBP | CROWN-IBP-master/bound_layers.py | ## Copyright (C) 2019, Huan Zhang <huan@huan-zhang.com>
## Hongge Chen <chenhg@mit.edu>
## Chaowei Xiao <xiaocw@umich.edu>
##
## This program is licenced under the BSD 2-Clause License,
## contained in the LICENCE file in this directory.
##
import torch
import numpy as np
from t... | 22,770 | 46.737945 | 245 | py |
CROWN-IBP | CROWN-IBP-master/config.py | ## Copyright (C) 2019, Huan Zhang <huan@huan-zhang.com>
## Hongge Chen <chenhg@mit.edu>
## Chaowei Xiao <xiaocw@umich.edu>
##
## This program is licenced under the BSD 2-Clause License,
## contained in the LICENCE file in this directory.
##
import os
import json
import glob
impo... | 9,040 | 38.828194 | 143 | py |
CROWN-IBP | CROWN-IBP-master/datasets.py | ## Copyright (C) 2019, Huan Zhang <huan@huan-zhang.com>
## Hongge Chen <chenhg@mit.edu>
## Chaowei Xiao <xiaocw@umich.edu>
##
## This program is licenced under the BSD 2-Clause License,
## contained in the LICENCE file in this directory.
##
import multiprocessing
import torch
fr... | 6,919 | 42.797468 | 175 | py |
CROWN-IBP | CROWN-IBP-master/eval.py | ## Copyright (C) 2019, Huan Zhang <huan@huan-zhang.com>
## Hongge Chen <chenhg@mit.edu>
## Chaowei Xiao <xiaocw@umich.edu>
##
## This program is licenced under the BSD 2-Clause License,
## contained in the LICENCE file in this directory.
##
import sys
import copy
import torch
im... | 3,232 | 40.448718 | 168 | py |
CROWN-IBP | CROWN-IBP-master/converter.py | ## Copyright (C) 2019, Huan Zhang <huan@huan-zhang.com>
## Hongge Chen <chenhg@mit.edu>
## Chaowei Xiao <xiaocw@umich.edu>
##
## This program is licenced under the BSD 2-Clause License,
## contained in the LICENCE file in this directory.
##
import sys
import copy
import torch
fr... | 1,104 | 31.5 | 117 | py |
CROWN-IBP | CROWN-IBP-master/train.py | ## Copyright (C) 2019, Huan Zhang <huan@huan-zhang.com>
## Hongge Chen <chenhg@mit.edu>
## Chaowei Xiao <xiaocw@umich.edu>
##
## This program is licenced under the BSD 2-Clause License,
## contained in the LICENCE file in this directory.
##
import sys
import copy
import torch
fr... | 24,080 | 48.960581 | 243 | py |
CROWN-IBP | CROWN-IBP-master/converter/keras2torch.py | #!/usr/bin/env python3
import numpy as np
import torch
import torch.nn as nn
import torchvision.transforms as transforms
import torchvision.datasets as datasets
import torch.nn.functional as F
import tensorflow as tf
from tensorflow.keras.layers import Dense as TFDense, Activation as TFActivation, Flatten as TFFlatte... | 2,513 | 33.916667 | 113 | py |
CROWN-IBP | CROWN-IBP-master/converter/torch2keras.py | #!/usr/bin/env python3
import numpy as np
import torch
import torch.nn as nn
import torchvision.transforms as transforms
import torchvision.datasets as datasets
import torch.nn.functional as F
import tensorflow as tf
from tensorflow.keras.layers import Dense as TFDense, Activation as TFActivation, Flatten as TFFlatte... | 4,155 | 37.12844 | 153 | py |
CROWN-IBP | CROWN-IBP-master/converter/mnist_cifar_models.py | #!/usr/bin/env python3
## mnist_cifar_models.py
##
## Model definition for MNIST and CIFAR
##
## Copyright (C) 2018, Huan Zhang <huan@huan-zhang.com> and contributors
##
## This program is licenced under the BSD 2-Clause License,
## contained in the LICENCE file in this directory.
## See CREDITS for a list of contrib... | 7,902 | 42.905556 | 219 | py |
CROWN-IBP | CROWN-IBP-master/convex_adversarial/dual_network.py | import torch
import torch.nn as nn
import torch.optim as optim
from torch.autograd import Variable
from .utils import Dense, DenseSequential
from .dual_inputs import select_input
from .dual_layers import select_layer
import warnings
class DualNetwork(nn.Module):
def __init__(self, net, X, epsilon,
... | 7,717 | 35.234742 | 120 | py |
CROWN-IBP | CROWN-IBP-master/convex_adversarial/dual_layers.py | import torch
import torch.nn as nn
import torch.nn.functional as F
import warnings
from .dual import DualLayer
from .utils import full_bias, Dense
def select_layer(layer, dual_net, X, proj, norm_type, in_f, out_f, zsi,
zl=None, zu=None):
if isinstance(layer, nn.Linear):
return DualLinear... | 16,378 | 29.275416 | 138 | py |
CROWN-IBP | CROWN-IBP-master/convex_adversarial/dual_inputs.py | import torch
import torch.nn as nn
from .dual import DualObject
def select_input(X, epsilon, proj, norm, bounded_input, l, u):
if proj is not None and norm=='l1_median' and X[0].numel() > proj:
if bounded_input:
return InfBallProjBounded(X,epsilon,proj, l, u)
else:
return... | 9,172 | 32.724265 | 92 | py |
CROWN-IBP | CROWN-IBP-master/convex_adversarial/dual.py | import torch.nn as nn
from abc import ABCMeta, abstractmethod
class DualObject(nn.Module, metaclass=ABCMeta):
def __init__(self):
""" Initialize a dual layer by initializing the variables needed to
compute this layer's contribution to the upper and lower bounds.
In the paper, if this o... | 1,722 | 34.163265 | 80 | py |
CROWN-IBP | CROWN-IBP-master/convex_adversarial/utils.py | import torch.nn as nn
###########################################
# Helper function to extract fully #
# shaped bias terms #
###########################################
def full_bias(l, n=None):
# expands the bias to the proper size. For convolutional layers, a full
# output dime... | 3,974 | 33.267241 | 98 | py |
SCALEX | SCALEX-main/scalex/data.py | #!/usr/bin/env python
"""
# Author: Xiong Lei
# Created Time : Wed 26 Dec 2018 03:46:19 PM CST
# File Name: data.py
# Description:
"""
import os
import numpy as np
import pandas as pd
import scipy
from scipy.sparse import issparse, csr
import torch
from torch.utils.data import Dataset
from torch.utils.data.sampler im... | 19,796 | 31.242671 | 194 | py |
SCALEX | SCALEX-main/scalex/function.py | #!/usr/bin/env python
"""
# Author: Xiong Lei
# Created Time : Tue 29 Sep 2020 01:41:23 PM CST
# File Name: function.py
# Description:
"""
import torch
import numpy as np
import os
import scanpy as sc
from anndata import AnnData
from typing import Union, List
from .data import load_data
from .net.vae import VAE
fro... | 9,992 | 33.697917 | 168 | py |
SCALEX | SCALEX-main/scalex/net/layer.py | #!/usr/bin/env python
"""
# Author: Xiong Lei
# Created Time : Mon 19 Aug 2019 02:25:11 PM CST
# File Name: layer.py
# Description:
"""
import math
import numpy as np
import torch
from torch import nn as nn
import torch.nn.functional as F
from torch.distributions import Normal
from torch.nn.parameter import Paramete... | 5,616 | 25.247664 | 117 | py |
SCALEX | SCALEX-main/scalex/net/loss.py | #!/usr/bin/env python
"""
# Author: Xiong Lei
# Created Time : Mon 21 Jan 2019 03:00:26 PM CST
# File Name: loss.py
# Description:
"""
import torch
from torch.distributions import Normal, kl_divergence
def kl_div(mu, var):
return kl_divergence(Normal(mu, var.sqrt()),
Normal(torch.zeros_... | 514 | 23.52381 | 102 | py |
SCALEX | SCALEX-main/scalex/net/utils.py | #!/usr/bin/env python
"""
# Author: Xiong Lei
# Created Time : Mon 18 Nov 2019 01:25:24 PM CST
# File Name: utils.py
# Description:
"""
import numpy as np
import torch
def onehot(y, n):
"""
Make the input tensor one hot tensors
Parameters
----------
y
input tensors
n
nu... | 2,324 | 24.833333 | 92 | py |
SCALEX | SCALEX-main/scalex/net/vae.py | #!/usr/bin/env python
"""
# Author: Xiong Lei
# Created Time : Mon 18 Nov 2019 01:16:06 PM CST
# File Name: vae.py
# Description:
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from tqdm.autonotebook import trange
from tqdm.contrib import tenumerate
from collections import d... | 6,675 | 33.412371 | 161 | py |
SCALEX | SCALEX-main/docs/source/conf.py | # Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Path setup --------------------------------------------------------------
# If ex... | 3,190 | 31.232323 | 85 | py |
AttentiveNAS | AttentiveNAS-main/test_attentive_nas.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
import argparse
import builtins
import math
import os
import random
import shutil
import time
import warnings
import sys
from datetime import date
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.backends.cudnn as cudnn
imp... | 2,509 | 30.375 | 106 | py |
AttentiveNAS | AttentiveNAS-main/train_attentive_nas.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
import argparse
import builtins
import math
import os
import random
import shutil
import time
import warnings
import sys
import operator
from datetime import date
import torch
import torch.nn as nn
#from torch.utils.tensorboard import SummaryWrite... | 13,311 | 33.848168 | 165 | py |
AttentiveNAS | AttentiveNAS-main/solver/lr_scheduler.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
import torch
import math
from bisect import bisect_right
from typing import List
class WarmupCosineLR(torch.optim.lr_scheduler._LRScheduler):
def __init__(self,
optimizer,
max_iters,
warmup_factor = 0.001,
warm... | 4,404 | 30.464286 | 132 | py |
AttentiveNAS | AttentiveNAS-main/solver/build.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
import torch
import torch.nn as nn
from .lr_scheduler import WarmupCosineLR, WarmupMultiStepLR, WarmupLinearDecayLR, ConstantLR
def build_optimizer(args, model):
"""
Build an optimizer from config.
"""
no_wd_params, wd_params ... | 3,806 | 35.961165 | 102 | py |
AttentiveNAS | AttentiveNAS-main/models/attentive_nas_dynamic_model.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
# Implementation adapted from OFA: https://github.com/mit-han-lab/once-for-all
import copy
import random
import collections
import math
import torch
import torch.nn as nn
from .modules.dynamic_layers import DynamicMBConvLayer, DynamicConvBnActLay... | 19,793 | 40.151767 | 150 | py |
AttentiveNAS | AttentiveNAS-main/models/attentive_nas_static_model.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
# adapted from OFA: https://github.com/mit-han-lab/once-for-all
import torch
import torch.nn as nn
from torch.autograd import Variable
import torch.nn.functional as F
import math
from .modules.static_layers import set_layer_from_config, MBInverte... | 3,198 | 32.322917 | 165 | py |
AttentiveNAS | AttentiveNAS-main/models/modules/dynamic_layers.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
# adapted from OFA: https://github.com/mit-han-lab/once-for-all
from collections import OrderedDict
import copy
import torch
import torch.nn as nn
import torch.nn.functional as F
from .static_layers import MBInvertedConvLayer, ConvBnActLayer, Lin... | 15,681 | 38.903308 | 152 | py |
AttentiveNAS | AttentiveNAS-main/models/modules/static_layers.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
# adapted from OFA: https://github.com/mit-han-lab/once-for-all
from collections import OrderedDict
import torch.nn as nn
from .nn_utils import get_same_padding, build_activation, make_divisible, drop_connect
from .nn_base import MyModule
from .act... | 12,039 | 30.76781 | 131 | py |
AttentiveNAS | AttentiveNAS-main/models/modules/activations.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
# adapted from OFA: https://github.com/mit-han-lab/once-for-all
import torch
import torch.nn as nn
import torch.nn.functional as F
# A memory-efficient implementation of Swish function
class SwishImplementation(torch.autograd.Function):
@stati... | 1,405 | 24.107143 | 70 | py |
AttentiveNAS | AttentiveNAS-main/models/modules/dynamic_ops.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
# adapted from OFA: https://github.com/mit-han-lab/once-for-all
from torch.autograd.function import Function
import torch.nn.functional as F
from torch.nn.parameter import Parameter
import torch.nn as nn
import torch
from torch.nn.modules._function... | 10,822 | 39.234201 | 106 | py |
AttentiveNAS | AttentiveNAS-main/models/modules/nn_base.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
# adapted from OFA: https://github.com/mit-han-lab/once-for-all
import math
import torch
import torch.nn as nn
try:
from fvcore.common.file_io import PathManager
except:
pass
class MyModule(nn.Module):
def forward(self, x):
... | 4,767 | 30.576159 | 113 | py |
AttentiveNAS | AttentiveNAS-main/models/modules/nn_utils.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
# adapted from OFA: https://github.com/mit-han-lab/once-for-all
import torch.nn as nn
from .activations import *
def make_divisible(v, divisor=8, min_value=1):
"""
forked from slim:
https://github.com/tensorflow/models/blob/\
0344... | 3,431 | 29.918919 | 96 | py |
AttentiveNAS | AttentiveNAS-main/evaluate/attentive_nas_eval.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.distributed as dist
import torch.optim
import torch.multiprocessing as mp
import torch.utils.data
import torch.utils.data.distributed
imp... | 3,414 | 33.846939 | 84 | py |
AttentiveNAS | AttentiveNAS-main/evaluate/imagenet_eval.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.distributed as dist
import torch.optim
import torch.multiprocessing as mp
import torch.utils.data
import torch.utils.data.distributed
impo... | 2,900 | 29.861702 | 92 | py |
AttentiveNAS | AttentiveNAS-main/utils/comm.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
import functools
import logging
import pickle
import torch
import torch.distributed as dist
def get_world_size():
if not dist.is_available():
return 1
if not dist.is_initialized():
return 1
return dist.get_world_size()... | 1,723 | 21.986667 | 84 | py |
AttentiveNAS | AttentiveNAS-main/utils/progress.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
import sys
import torch
import torch.nn as nn
class AverageMeter(object):
"""Computes and stores the average and current value"""
def __init__(self, name, fmt=':f'):
self.name = name
self.fmt = fmt
self.reset()
... | 1,980 | 27.3 | 88 | py |
AttentiveNAS | AttentiveNAS-main/utils/saver.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
from copy import deepcopy
import torch
import os
import shutil
import joblib
def copy_file(source_path, target_path):
shutil.copyfile(source_path, target_path)
def save_acc_predictor(args, acc_predictor):
args.curr_acc_predictor_path = o... | 2,934 | 35.234568 | 112 | py |
AttentiveNAS | AttentiveNAS-main/utils/flops_counter.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
# Implementation adapted from OFA - https://github.com/mit-han-lab/once-for-all
import torch
import torch.nn as nn
import copy
multiply_adds = 1
def count_convNd(m, _, y):
cin = m.in_channels
kernel_ops = m.weight.size()[2] * m.weight.... | 2,840 | 24.141593 | 79 | py |
AttentiveNAS | AttentiveNAS-main/utils/loss_ops.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
# Implementation adapted from Slimmable - https://github.com/JiahuiYu/slimmable_networks
import torch
class CrossEntropyLossSoft(torch.nn.modules.loss._Loss):
""" inplace distillation for image classification """
def forward(self, output, ... | 2,695 | 38.072464 | 88 | py |
AttentiveNAS | AttentiveNAS-main/data/data_loader.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
from __future__ import print_function
import torch
import torchvision.transforms.functional as F
from torchvision import datasets, transforms
from torch.utils.data import Dataset
import math
import sys
import random
from PIL import Image
from tor... | 2,709 | 31.261905 | 134 | py |
AttentiveNAS | AttentiveNAS-main/data/auto_augment_tf.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
""" Auto Augment
Implementation adapted from timm: https://github.com/rwightman/pytorch-image-models
"""
import random
import math
from PIL import Image, ImageOps, ImageEnhance
import PIL
_PIL_VER = tuple([int(x) for x in PIL.__version__.split('... | 13,406 | 32.185644 | 105 | py |
AttentiveNAS | AttentiveNAS-main/data/data_transform.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
import torch
from PIL import Image
import numpy as np
import torchvision.transforms as transforms
from .auto_augment_tf import (
auto_augment_policy,
AutoAugment,
)
IMAGENET_PIXEL_MEAN = [123.675, 116.280, 103.530]
IMAGENET_PIXEL_STD = [... | 3,266 | 28.432432 | 114 | py |
GDN | GDN-main/main.py | # -*- coding: utf-8 -*-
import pandas as pd
import numpy as np
import torch
import matplotlib.pyplot as plt
from torch.utils.data import DataLoader, random_split, Subset
from sklearn.preprocessing import MinMaxScaler
from util.env import get_device, set_device
from util.preprocess import build_loc_net, construct_data... | 9,214 | 34.171756 | 158 | py |
GDN | GDN-main/test.py | import numpy as np
import torch
import matplotlib.pyplot as plt
import torch.nn as nn
import time
from util.time import *
from util.env import *
import argparse
import matplotlib.pyplot as plt
from torch.utils.data import Dataset, DataLoader
import pandas as pd
import torch.nn.functional as F
from util.data import *... | 2,146 | 24.559524 | 99 | py |
GDN | GDN-main/train.py | import numpy as np
import torch
import matplotlib.pyplot as plt
import torch.nn as nn
import time
from util.time import *
from util.env import *
from sklearn.metrics import mean_squared_error
from test import *
import torch.nn.functional as F
import numpy as np
from evaluate import get_best_performance_data, get_val_pe... | 2,772 | 23.539823 | 194 | py |
GDN | GDN-main/models/GDN.py | import numpy as np
import torch
import matplotlib.pyplot as plt
import torch.nn as nn
import time
from util.time import *
from util.env import *
from torch_geometric.nn import GCNConv, GATConv, EdgeConv
import math
import torch.nn.functional as F
from .graph_layer import GraphLayer
def get_batch_edge_index(org_edge_... | 5,833 | 30.031915 | 123 | py |
GDN | GDN-main/models/graph_layer.py | import torch
from torch.nn import Parameter, Linear, Sequential, BatchNorm1d, ReLU
import torch.nn.functional as F
from torch_geometric.nn.conv import MessagePassing
from torch_geometric.utils import remove_self_loops, add_self_loops, softmax
from torch_geometric.nn.inits import glorot, zeros
import time
import math
... | 4,113 | 31.912 | 84 | py |
GDN | GDN-main/util/env.py | import torch
import numpy as np
_device = None
def get_device():
# return torch.device('cuda' if torch.cuda.is_available() else 'cpu')
return _device
def set_device(dev):
global _device
_device = dev
def init_work(worker_id, seed):
np.random.seed(seed + worker_id)
| 290 | 17.1875 | 73 | py |
GDN | GDN-main/datasets/TimeDataset.py | import torch
from torch.utils.data import Dataset, DataLoader
import torch.nn.functional as F
from sklearn.preprocessing import MinMaxScaler, StandardScaler
import numpy as np
class TimeDataset(Dataset):
def __init__(self, raw_data, edge_index, mode='train', config = None):
self.raw_data = raw_data
... | 1,762 | 21.316456 | 111 | py |
udvd | udvd-main/raw_train.py | import argparse
import logging
import sys
import torch
import torchvision
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.tensorboard import SummaryWriter
import data, models, utils
def main(args):
device = torch.device('cuda:0') if torch.cuda.is_available() else torch.device('cpu')
u... | 15,241 | 52.108014 | 208 | py |
udvd | udvd-main/electron_train.py | import argparse
import logging
import sys
import torch
import torchvision
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.tensorboard import SummaryWriter
import data, models, utils
def main(args):
device = torch.device('cuda:0') if torch.cuda.is_available() else torch.device('cpu')
u... | 11,370 | 47.594017 | 195 | py |
udvd | udvd-main/data.py | import os
import os.path
import cv2
import glob
import h5py
from PIL import Image
import skimage
import skimage.io
import numpy as np
import pandas as pd
import torch
from torchvision import transforms
import torchvision.transforms.functional as TF
import utils
DATASET_REGISTRY = {}
def build_dataset(name, *args,... | 33,142 | 39.418293 | 152 | py |
udvd | udvd-main/single_train.py | import argparse
import logging
import sys
import torch
import torchvision
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.tensorboard import SummaryWriter
import data, models, utils
def main(args):
device = torch.device('cuda:0') if torch.cuda.is_available() else torch.device('cpu')
u... | 15,821 | 53.747405 | 403 | py |
udvd | udvd-main/fluoro_train.py | import argparse
import logging
import sys
import torch
import torchvision
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.tensorboard import SummaryWriter
import data, models, utils
def main(args):
device = torch.device('cuda:0') if torch.cuda.is_available() else torch.device('cpu')
u... | 9,468 | 45.64532 | 204 | py |
udvd | udvd-main/train.py | import argparse
import logging
import sys
import torch
import torchvision
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.tensorboard import SummaryWriter
import data, models, utils
def main(args):
device = torch.device('cuda:0') if torch.cuda.is_available() else torch.device('cpu')
u... | 13,195 | 49.174905 | 207 | py |
udvd | udvd-main/models/fastdvdnet.py | # FastDVDnet model definition take from their official github repository
# https://github.com/m-tassano/fastdvdnet
"""
Definition of the FastDVDnet model
Copyright (C) 2019, Matias Tassano <matias.tassano@parisdescartes.fr>
This program is free software: you can use, modify and/or
redistribute it under the terms of th... | 7,298 | 34.779412 | 97 | py |
udvd | udvd-main/models/__init__.py | import importlib
import os
import torch.nn as nn
from .fastdvdnet import *
MODEL_REGISTRY = {}
def build_model(args):
return MODEL_REGISTRY[args.model].build_model(args)
def register_model(name):
"""Decorator to register a new model"""
def register_model_cls(cls):
if name in MODEL_REGISTRY:
... | 871 | 26.25 | 82 | py |
udvd | udvd-main/models/udvd.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from models import register_model
class crop(nn.Module):
def __init__(self):
super().__init__()
def forward(self, x):
N, C, H, W = x.shape
x = x[0:N, 0:C, 0:H-1, 0:W]
return x
class shift(nn.Module):
def _... | 12,679 | 35.228571 | 161 | py |
udvd | udvd-main/utils/post_processing.py | import torch
import torch.nn.functional as F
import numpy as np
import matplotlib.pyplot as plt
import skimage.restoration as skr
def post_process(output, input, number=0, model="blind-spot-net" ,sigma=25, device="cpu"):
if (model == "blind-spot-net"
or model == "blind-video-net"
or model == "blind... | 2,010 | 45.767442 | 122 | py |
udvd | udvd-main/utils/loss_funtions.py | import torch
import torch.nn.functional as F
import skimage.restoration as skr
def loss_function(output, truth, mode="loglike", sigma=25, device="cpu"):
if(mode == "mse"):
loss = F.mse_loss(output, truth, reduction="sum") / (truth.size(0) * 2)
elif(mode == "loglike"):
eps = 1e-5
N,C,H,W... | 1,409 | 46 | 119 | py |
udvd | udvd-main/utils/train_utils.py | import argparse
import os
import logging
import numpy as np
import random
import sys
import torch
import torch.nn as nn
import torch.nn.functional as F
from datetime import datetime
from torch.serialization import default_restore_location
import sys
sys.path.append('../')
import models
def add_logging_arguments(pars... | 8,602 | 46.010929 | 127 | py |
udvd | udvd-main/utils/test_metrics.py | import torch
import numpy as np
import matplotlib.pyplot as plt
import glob
import os
import cv2
from utils import get_noise, ssim, psnr
metrics_key = ['psnr', 'psnr_delta', 'ssim', 'ssim_delta'];
def tensor_to_image(torch_image, low=0.0, high = 1.0, clamp = True):
if clamp:
torch_image = torch.clamp(torch_image, ... | 3,216 | 23.937984 | 115 | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.