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
intel-extension-for-pytorch
intel-extension-for-pytorch-master/intel_extension_for_pytorch/quantization/_quantization_state_utils.py
import dataclasses from typing import Callable, Tuple, Any, List, Optional, Dict import torch import torch.nn.functional as F import torch.nn.quantized.dynamic as nnqd from intel_extension_for_pytorch.nn.functional import interaction import intel_extension_for_pytorch._C as core functions_supported_by_quantization = ...
20,844
36.969035
120
py
intel-extension-for-pytorch
intel-extension-for-pytorch-master/intel_extension_for_pytorch/quantization/_module_swap_utils.py
from typing import Dict, Callable, Any, Optional import torch import torch.nn as nn from torch.ao.quantization import swap_module import torch.nn.quantized.dynamic as nnqd from torch.quantization.qconfig import QConfig # Default map for swapping dynamic modules DEFAULT_DYNAMIC_QUANT_MODULE_MAPPINGS: Dict[Callable, A...
3,210
31.434343
86
py
intel-extension-for-pytorch
intel-extension-for-pytorch-master/intel_extension_for_pytorch/quantization/_quantize.py
import copy import functools import os import warnings import torch from torch.ao.quantization import PlaceholderObserver, QConfig, QConfigMapping from torch.ao.quantization.quantization_mappings import ( get_default_dynamic_quant_module_mappings, ) import torch.fx.experimental.optimization as optimization from to...
14,603
38.684783
124
py
intel-extension-for-pytorch
intel-extension-for-pytorch-master/intel_extension_for_pytorch/fx/concat_linear.py
import torch import torch.nn as nn import torch.fx as fx import torch.fx.experimental.optimization as optimization import _operator import copy import warnings def concat_linear(model: fx.GraphModule, inplace=False) -> fx.GraphModule: def concat(compatible_layers, modules): if len(compatible_layers) < 2: ...
9,423
41.071429
114
py
Seq2Sick
Seq2Sick-master/opts.py
import argparse from onmt.modules.SRU import CheckSRU def model_opts(parser): """ These options are passed to the construction of the model. Be careful with these as they will be used during translation. """ # Embedding Options group = parser.add_argument_group('Model-Embeddings') group.a...
28,909
48.588336
88
py
Seq2Sick
Seq2Sick-master/attack.py
#!/usr/bin/env python from __future__ import division, unicode_literals import os import argparse import math import codecs import torch from torch.autograd import Variable import numpy as np from itertools import count import onmt.io import onmt.translate import onmt import onmt.ModelConstructor import onmt.modules ...
13,084
40.805112
212
py
Seq2Sick
Seq2Sick-master/translate.py
#!/usr/bin/env python from __future__ import division, unicode_literals import os import argparse import math import codecs import torch from itertools import count import onmt.io import onmt.translate import onmt import onmt.ModelConstructor import onmt.modules import opts parser = argparse.ArgumentParser( des...
3,842
31.846154
74
py
Seq2Sick
Seq2Sick-master/train.py
#!/usr/bin/env python from __future__ import division import argparse import glob import os import sys import random import torch import torch.nn as nn from torch import cuda import onmt import onmt.io import onmt.Models import onmt.ModelConstructor import onmt.modules from onmt.Utils import use_gpu import opts p...
11,059
30.781609
78
py
Seq2Sick
Seq2Sick-master/preprocess.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import argparse import codecs import os import glob import sys import torch import onmt.io import opts def check_existing_pt_files(opt): # We will use glob.glob() to find sharded {train|valid}.[0-9]*.pt # when training, so check to avoid tampering with existing...
7,222
33.070755
78
py
Seq2Sick
Seq2Sick-master/tools/embeddings_to_torch.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import print_function from __future__ import division import six import sys import numpy as np import argparse import torch parser = argparse.ArgumentParser(description='embeddings_to_torch.py') parser.add_argument('-emb_file', required=True, ...
3,313
33.884211
74
py
Seq2Sick
Seq2Sick-master/tools/extract_embeddings.py
from __future__ import division import torch import argparse import opts import onmt import onmt.ModelConstructor import onmt.io from onmt.Utils import use_gpu parser = argparse.ArgumentParser(description='translate.py') parser.add_argument('-model', required=True, help='Path to model .pt file') p...
2,422
31.743243
73
py
Seq2Sick
Seq2Sick-master/onmt/Loss.py
""" This file handles the details of the loss function during training. This includes: LossComputeBase and the standard NMTLossCompute, and sharded loss compute stuff. """ from __future__ import division import torch import torch.nn as nn from torch.autograd import Variable import onmt import onmt.io ...
9,843
36.716475
79
py
Seq2Sick
Seq2Sick-master/onmt/Utils.py
import torch def aeq(*args): """ Assert all arguments have the same value """ arguments = (arg for arg in args) first = next(arguments) assert all(arg == first for arg in arguments), \ "Not all arguments have the same value: " + str(args) def sequence_mask(lengths, max_len=None): ...
726
24.068966
62
py
Seq2Sick
Seq2Sick-master/onmt/ModelConstructor.py
""" This file is for models creation, which consults options and creates each encoder and decoder accordingly. """ import torch import torch.nn as nn import onmt import onmt.io import onmt.Models import onmt.modules from onmt.Models import NMTModel, MeanEncoder, RNNEncoder, \ StdRNNDecoder, Inp...
8,731
37.808889
77
py
Seq2Sick
Seq2Sick-master/onmt/Trainer.py
from __future__ import division """ This is the loadable seq2seq trainer library that is in charge of training details, loss compute, and statistics. See train.py for a use case of this library. Note!!! To make this a general library, we implement *only* mechanism things here(i.e. what to do), and leave the strategy t...
8,234
32.612245
79
py
Seq2Sick
Seq2Sick-master/onmt/Optim.py
import torch.optim as optim from torch.nn.utils import clip_grad_norm class Optim(object): """ Controller class for optimization. Mostly a thin wrapper for `optim`, but also useful for implementing rate scheduling beyond what is currently available. Also implements necessary methods for training R...
4,202
38.280374
77
py
Seq2Sick
Seq2Sick-master/onmt/Models.py
from __future__ import division import torch import torch.nn as nn from torch.autograd import Variable from torch.nn.utils.rnn import pack_padded_sequence as pack from torch.nn.utils.rnn import pad_packed_sequence as unpack import onmt from onmt.Utils import aeq class EncoderBase(nn.Module): """ Base encoder...
22,339
34.801282
79
py
Seq2Sick
Seq2Sick-master/onmt/modules/ConvMultiStepAttention.py
import torch import torch.nn as nn import torch.nn.functional as F from onmt.Utils import aeq SCALE_WEIGHT = 0.5 ** 0.5 def seq_linear(linear, x): # linear transform for 3-d tensor batch, hidden_size, length, _ = x.size() h = linear(torch.transpose(x, 1, 2).contiguous().view( batch * length, hid...
2,611
34.780822
77
py
Seq2Sick
Seq2Sick-master/onmt/modules/Transformer.py
""" Implementation of "Attention is All You Need" """ import torch import torch.nn as nn from torch.autograd import Variable import numpy as np import onmt from onmt.Models import EncoderBase from onmt.Models import DecoderState from onmt.Utils import aeq MAX_SIZE = 5000 class PositionwiseFeedForward(nn.Module): ...
12,494
37.684211
79
py
Seq2Sick
Seq2Sick-master/onmt/modules/Embeddings.py
import torch import torch.nn as nn from torch.autograd import Variable from onmt.modules import BottleLinear, Elementwise from onmt.Utils import aeq class PositionalEncoding(nn.Module): def __init__(self, dropout, dim, max_len=5000): pe = torch.arange(0, max_len).unsqueeze(1).expand(max_len, dim) ...
6,674
37.142857
77
py
Seq2Sick
Seq2Sick-master/onmt/modules/CopyGenerator.py
import torch.nn as nn import torch.nn.functional as F import torch import torch.cuda import onmt import onmt.io from onmt.Utils import aeq class CopyGenerator(nn.Module): """ Generator module that additionally considers copying words directly from the source. """ def __init__(self, opt, src_dict,...
5,166
34.881944
79
py
Seq2Sick
Seq2Sick-master/onmt/modules/StackedRNN.py
import torch import torch.nn as nn class StackedLSTM(nn.Module): """ Our own implementation of stacked LSTM. Needed for the decoder, because we do input feeding. """ def __init__(self, num_layers, input_size, rnn_size, dropout): super(StackedLSTM, self).__init__() self.dropout = nn...
1,755
28.266667
66
py
Seq2Sick
Seq2Sick-master/onmt/modules/MultiHeadedAttn.py
import math import torch import torch.nn as nn from torch.autograd import Variable from onmt.Utils import aeq from onmt.modules.UtilClass import BottleLinear, BottleSoftmax class MultiHeadedAttention(nn.Module): ''' Multi-Head Attention module from "Attention is All You Need". ''' def __init__(se...
3,828
34.453704
74
py
Seq2Sick
Seq2Sick-master/onmt/modules/Gate.py
""" Context gate is a decoder module that takes as input the previous word embedding, the current decoder state and the attention state, and produces a gate. The gate can be used to select the input from the target side context (decoder state), from the source context (attention state) or both. """ import torch import ...
3,600
38.571429
78
py
Seq2Sick
Seq2Sick-master/onmt/modules/UtilClass.py
import torch import torch.nn as nn class Bottle(nn.Module): def forward(self, input): if len(input.size()) <= 2: return super(Bottle, self).forward(input) size = input.size()[:2] out = super(Bottle, self).forward(input.view(size[0]*size[1], -1)) ...
2,769
30.123596
78
py
Seq2Sick
Seq2Sick-master/onmt/modules/StructuredAttention.py
import torch.nn as nn import torch import torch.cuda from torch.autograd import Variable class MatrixTree(nn.Module): """Implementation of the matrix-tree theorem for computing marginals of non-projective dependency parsing. This attention layer is used in the paper "Learning Structured Text Representatio...
1,597
32.291667
77
py
Seq2Sick
Seq2Sick-master/onmt/modules/Conv2Conv.py
""" Implementation of "Convolutional Sequence to Sequence Learning" """ import torch import torch.nn as nn import torch.nn.init as init import torch.nn.functional as F from torch.autograd import Variable import onmt.modules from onmt.modules.WeightNorm import WeightNormConv2d from onmt.Models import EncoderBase from o...
8,735
36.016949
79
py
Seq2Sick
Seq2Sick-master/onmt/modules/GlobalAttention.py
import torch import torch.nn as nn from onmt.modules.UtilClass import BottleLinear from onmt.Utils import aeq, sequence_mask class GlobalAttention(nn.Module): """ Global attention takes a matrix and a query vector. It then computes a parameterized convex combination of the matrix based on the input q...
7,024
31.224771
79
py
Seq2Sick
Seq2Sick-master/onmt/modules/SRU.py
""" Implementation of "Training RNNs as Fast as CNNs". TODO: turn to pytorch's implementation when it is available. This implementation is adpoted from the author of the paper: https://github.com/taolei87/sru/blob/master/cuda_functional.py. """ # flake8: noqa import subprocess import platform import os import re impo...
23,334
36.57649
79
py
Seq2Sick
Seq2Sick-master/onmt/modules/WeightNorm.py
""" Implementation of "Weight Normalization: A Simple Reparameterization to Accelerate Training of Deep Neural Networks" As a reparameterization method, weight normalization is same as BatchNormalization, but it doesn't depend on minibatch. """ import torch import torch.nn as nn import torch.nn.functional as F from tor...
9,574
39.231092
78
py
Seq2Sick
Seq2Sick-master/onmt/modules/AudioEncoder.py
import math import torch.nn as nn import torch.nn.functional as F class AudioEncoder(nn.Module): """ Encoder recurrent neural network for Images. """ def __init__(self, num_layers, bidirectional, rnn_size, dropout, sample_rate, window_size): """ Args: num_l...
2,327
33.746269
73
py
Seq2Sick
Seq2Sick-master/onmt/modules/ImageEncoder.py
import torch.nn as nn import torch.nn.functional as F import torch from torch.autograd import Variable class ImageEncoder(nn.Module): """ Encoder recurrent neural network for Images. """ def __init__(self, num_layers, bidirectional, rnn_size, dropout): """ Args: num_layers ...
4,023
36.962264
76
py
Seq2Sick
Seq2Sick-master/onmt/io/IO.py
# -*- coding: utf-8 -*- import os import codecs from collections import Counter, defaultdict from itertools import chain, count import torch import torchtext.data import torchtext.vocab from onmt.Utils import aeq PAD_WORD = '<blank>' UNK = 0 BOS_WORD = '<s>' EOS_WORD = '</s>' def _getstate(self): return dict...
21,995
34.477419
78
py
Seq2Sick
Seq2Sick-master/onmt/io/TextDataset.py
# -*- coding: utf-8 -*- from collections import Counter import io import sys import torch import torchtext from onmt.Utils import aeq from onmt.io.IO import ONMTDatasetBase, _join_dicts, _peek,\ _construct_example_fromlist, extract_features class TextDataset(ONMTDatasetBase): """ Dataset...
8,181
36.87963
78
py
Seq2Sick
Seq2Sick-master/onmt/translate/Beam.py
from __future__ import division import torch """ Class for managing the internals of the beam search process. Takes care of beams, back pointers, and scores. """ class Beam(object): def __init__(self, size, pad, bos, eos, n_best=1, cuda=False, global_scorer=None): se...
5,514
32.834356
79
py
Seq2Sick
Seq2Sick-master/onmt/translate/Translator.py
import torch from torch.autograd import Variable import onmt.translate.Beam import onmt.io class Translator(object): def __init__(self, model, fields, beam_size, n_best, max_length, global_scorer, copy_attn, cuda, beam_trace): self.model...
11,549
38.02027
92
py
Seq2Sick
Seq2Sick-master/onmt/translate/Translation.py
from __future__ import division, unicode_literals import torch import onmt.io class TranslationBuilder(object): def __init__(self, data, fields, n_best, replace_unk, has_tgt): self.data = data self.fields = fields self.n_best = n_best self.replace_unk = replace_unk self.ha...
7,063
35.225641
106
py
DGP
DGP-master/docs/source/conf.py
# Configuration file for the Sphinx documentation builder. # # For the full list of built-in configuration values, see the documentation: # https://www.sphinx-doc.org/en/master/usage/configuration.html import os import sys sys.path.insert(0, os.path.abspath("../..")) # -- Project information --------------------------...
1,227
32.189189
87
py
SeConvNet
SeConvNet-main/model.py
import tensorflow as tf from tensorflow import keras from tensorflow.keras import Input from tensorflow.keras.layers import Conv2D, Activation,BatchNormalization, Add import numpy as np #define SeConv block: class SeConv_block(keras.layers.Layer): def __init__(self, kernel_size, input_channels, **kwargs): ...
3,615
38.304348
175
py
SeConvNet
SeConvNet-main/train.py
import argparse import numpy as np from tensorflow import keras from tensorflow.math import reduce_sum, square import os from model import SeConvNet from SPN import SPN from data_generator import data_gen parser = argparse.ArgumentParser() parser.add_argument('--noise_density', default=0.95, type=float, help='noise d...
2,919
39
185
py
icd-coding-benchmark
icd-coding-benchmark-main/app.py
#!/usr/bin/env python """ The interactive demo of ICD coding benchmark (prototype) """ import argparse import copy import csv import numpy as np import pandas as pd import seaborn as sns import streamlit as st import torch from captum.attr import LayerIntegratedGradients from anemic.modules.preprocessors import C...
13,915
33.877193
80
py
icd-coding-benchmark
icd-coding-benchmark-main/run.py
# Imports import argparse import os import pandas import torch from torchsummaryX import summary from anemic.utils.configuration import Config from anemic.utils.import_related_ops import pandas_related_ops from anemic.utils.mapper import ConfigMapper from anemic.utils.misc import seed pandas_related_ops() # Comman...
2,156
23.793103
80
py
icd-coding-benchmark
icd-coding-benchmark-main/anemic/modules/losses.py
"""All criterion functions.""" import json import os import torch import torch.nn.functional as F from torch.autograd import Variable from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from anemic.utils.file_loaders import load_json from anemic.utils.mapper import ConfigMapper ConfigMapper.map("losses...
2,635
30.759036
80
py
icd-coding-benchmark
icd-coding-benchmark-main/anemic/modules/schedulers.py
from torch.optim.lr_scheduler import ( CosineAnnealingLR, CosineAnnealingWarmRestarts, CyclicLR, LambdaLR, ReduceLROnPlateau, StepLR, ) from transformers import get_linear_schedule_with_warmup from anemic.utils.mapper import ConfigMapper ConfigMapper.map("schedulers", "step")(StepLR) ConfigMap...
674
28.347826
66
py
icd-coding-benchmark
icd-coding-benchmark-main/anemic/modules/optimizers.py
"""Method containing activation functions""" from torch.optim import SGD, Adam, AdamW from anemic.utils.mapper import ConfigMapper ConfigMapper.map("optimizers", "adam")(Adam) ConfigMapper.map("optimizers", "adam_w")(AdamW) ConfigMapper.map("optimizers", "sgd")(SGD)
269
29
47
py
icd-coding-benchmark
icd-coding-benchmark-main/anemic/modules/activations.py
import torch.nn as nn from anemic.utils.mapper import ConfigMapper ConfigMapper.map("activations", "relu")(nn.ReLU) ConfigMapper.map("activations", "logsoftmax")(nn.LogSoftmax) ConfigMapper.map("activations", "softmax")(nn.Softmax)
234
28.375
60
py
icd-coding-benchmark
icd-coding-benchmark-main/anemic/models/multirescnn.py
""" ICD Coding from Clinical Text Using Multi-Filter Residual Convolutional Neural Network, 2020 https://github.com/foxlf823/Multi-Filter-Residual-Convolutional-Neural-Network """ from math import floor import torch import torch.nn as nn import torch.nn.functional as F from torch.nn.init import xavier_uniform_ as xav...
8,926
30.10453
79
py
icd-coding-benchmark
icd-coding-benchmark-main/anemic/models/dcan.py
import copy import torch import torch.nn as nn import torch.nn.functional as F from torch.nn.init import xavier_uniform_ from torch.nn.utils import weight_norm as weight_norm_ from anemic.utils.mapper import ConfigMapper from anemic.utils.text_loggers import get_logger logger = get_logger(__name__) @ConfigMapper.m...
20,705
39.759843
115
py
icd-coding-benchmark
icd-coding-benchmark-main/anemic/models/transicd.py
import math import torch import torch.nn as nn from torch.autograd import Variable from anemic.utils.mapper import ConfigMapper from anemic.utils.text_loggers import get_logger logger = get_logger(__name__) @ConfigMapper.map("models", "transicd") class TransICD(nn.Module): def __init__(self, config): s...
10,178
37.411321
115
py
icd-coding-benchmark
icd-coding-benchmark-main/anemic/models/caml.py
""" CAML model (Mullenbach et al. 2018) https://github.com/jamesmullenbach/caml-mimic """ from math import floor import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable from torch.nn.init import xavier_uniform from anemic.utils.mapper import C...
9,333
33.828358
80
py
icd-coding-benchmark
icd-coding-benchmark-main/anemic/models/fusion.py
""" Fusion model (Luo et al. 2021) https://github.com/machinelearning4health/Fusion-Towards-Automated-ICD-Coding """ from math import floor import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from torch.nn.init import xavier_uniform_ as xavier_uniform from anemic.utils.mappe...
19,129
35.507634
81
py
icd-coding-benchmark
icd-coding-benchmark-main/anemic/datasets/base_dataset.py
import os import numpy as np import pandas as pd import torch from torch.utils.data import Dataset from anemic.utils.file_loaders import load_csv_as_df, load_json from anemic.utils.mapper import ConfigMapper from anemic.utils.text_loggers import get_logger logger = get_logger(__name__) @ConfigMapper.map("datasets"...
3,753
32.81982
80
py
icd-coding-benchmark
icd-coding-benchmark-main/anemic/utils/checkpoint_savers.py
""" Checkpoint Saver """ import json import os import torch from anemic.modules.metrics import load_metric from anemic.utils.file_loaders import load_json, save_json from anemic.utils.mapper import ConfigMapper from anemic.utils.text_loggers import get_logger logger = get_logger(__name__) @ConfigMapper.map("ch...
7,043
34.044776
78
py
icd-coding-benchmark
icd-coding-benchmark-main/anemic/utils/misc.py
"""Miscellaneous utility functions.""" import copy import itertools import random import numpy as np import torch def seed(value=42): """Set random seed for everything. Args: value (int): Seed """ np.random.seed(value) torch.manual_seed(value) torch.backends.cudnn.deterministic = Tr...
6,349
28.812207
80
py
icd-coding-benchmark
icd-coding-benchmark-main/anemic/utils/graph_writers.py
import json import os import torch from torch.utils.tensorboard import SummaryWriter from anemic.utils.mapper import ConfigMapper from anemic.utils.text_loggers import get_logger logger = get_logger(__name__) class GraphWriterBase: def __init__(self, config): self.config = config def writer_scalar...
1,279
26.234043
78
py
icd-coding-benchmark
icd-coding-benchmark-main/anemic/trainers/base_trainer.py
import math import os import numpy as np import torch from torch.optim.lr_scheduler import ReduceLROnPlateau from torch.utils.data import DataLoader from tqdm import tqdm from anemic.modules.metrics import load_metric from anemic.utils.configuration import Config from anemic.utils.file_loaders import save_json from a...
16,526
39.211679
80
py
pykg2vec
pykg2vec-master/pykg2vec/models/Domain.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Domain module for building Knowledge Graphs """ from torch.nn import Embedding class NamedEmbedding(Embedding): """ Associate embeddings with human-readable names""" def __init__(self, name, *args, **kwargs): super(NamedEmbedding, self).__init__(*args,...
418
22.277778
61
py
pykg2vec
pykg2vec-master/pykg2vec/models/pairwise.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import torch import torch.nn as nn import torch.nn.functional as F import numpy as np from pykg2vec.models.KGMeta import PairwiseModel from pykg2vec.models.Domain import NamedEmbedding from pykg2vec.utils.criterion import Criterion class TransE(PairwiseModel): """ ...
46,920
40.050744
286
py
pykg2vec
pykg2vec-master/pykg2vec/models/projection.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import torch import torch.nn as nn import torch.nn.functional as F import numpy as np from pykg2vec.models.KGMeta import ProjectionModel from pykg2vec.models.Domain import NamedEmbedding from pykg2vec.utils.criterion import Criterion class ConvE(ProjectionModel): """ ...
30,964
40.452477
479
py
pykg2vec
pykg2vec-master/pykg2vec/models/pointwise.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import torch import torch.nn as nn import numpy as np from numpy.random import RandomState from pykg2vec.models.KGMeta import PointwiseModel from pykg2vec.models.Domain import NamedEmbedding from pykg2vec.utils.criterion import Criterion class ANALOGY(PointwiseModel): ...
48,166
41.475309
178
py
pykg2vec
pykg2vec-master/pykg2vec/models/KGMeta.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Knowledge Graph Meta Class ==================================== It provides Abstract class for the Knowledge graph models. """ from pykg2vec.common import TrainingStrategy from abc import ABCMeta import torch.nn as nn class Model: """ Meta Class for knowledge gra...
2,497
29.839506
76
py
pykg2vec
pykg2vec-master/pykg2vec/test/test_generator.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ This module is for testing unit functions of generator """ import torch from pykg2vec.data.generator import Generator from pykg2vec.common import Importer, KGEArgParser from pykg2vec.data.kgcontroller import KnowledgeGraph def test_generator_projection(): """Functi...
2,641
30.082353
77
py
pykg2vec
pykg2vec-master/pykg2vec/utils/riemannian_optimizer.py
import torch from torch.optim.optimizer import Optimizer class RiemannianOptimizer(Optimizer): """Riemannian stochastic gradient descent""" def __init__(self, params, lr, param_names): defaults = dict(lr=lr) super(RiemannianOptimizer, self).__init__(params, defaults) self.param_names ...
2,205
35.163934
93
py
pykg2vec
pykg2vec-master/pykg2vec/utils/visualization.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ This module is for visualizing the results """ import os import seaborn import torch import numpy as np import matplotlib.pyplot as plt import networkx as nx import pandas as pd from sklearn.manifold import TSNE from matplotlib import colors as mcolors from pykg2vec.ut...
19,354
40.893939
202
py
pykg2vec
pykg2vec-master/pykg2vec/utils/evaluator.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ This module is for evaluating the results """ import os import timeit import torch import numpy as np import pandas as pd from pykg2vec.utils.logger import Logger from tqdm import tqdm class MetricCalculator: ''' MetricCalculator aims to 1) address...
13,276
38.632836
164
py
pykg2vec
pykg2vec-master/pykg2vec/utils/criterion.py
import torch import torch.nn as nn import torch.nn.functional as F class Criterion: """Utility for calculating KGE losses Loss Functions in Knowledge Graph Embedding Models http://ceur-ws.org/Vol-2377/paper_1.pdf """ @staticmethod def pariwise_logistic(pos_preds, neg_preds, neg_rate, a...
1,926
34.036364
89
py
pykg2vec
pykg2vec-master/pykg2vec/utils/trainer.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import warnings import torch import torch.optim as optim import numpy as np import pandas as pd from tqdm import tqdm from pathlib import Path from pykg2vec.utils.evaluator import Evaluator from pykg2vec.utils.visualization import Visualization from pykg2vec.util...
19,650
39.85447
127
py
pykg2vec
pykg2vec-master/pykg2vec/data/generator.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ This module is for generating the batch data for training and testing. """ import torch import numpy as np from multiprocessing import Process, Queue from pykg2vec.common import TrainingStrategy def raw_data_generator(command_queue, raw_queue, config): """Function ...
11,620
35.775316
143
py
BertGen
BertGen-master/external/pytorch_pretrained_bert/optimization.py
# coding=utf-8 # Copyright 2018 The Google AI Language Team Authors and The HugginFace Inc. team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENS...
6,803
40.742331
116
py
BertGen
BertGen-master/external/pytorch_pretrained_bert/optimization_openai.py
# coding=utf-8 # Copyright 2018 The Open AI Team Authors and The HugginFace Inc. team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # U...
5,661
39.156028
116
py
BertGen
BertGen-master/external/pytorch_pretrained_bert/__main__.py
# coding: utf8 def main(): import sys if (len(sys.argv) != 4 and len(sys.argv) != 5) or sys.argv[1] not in [ "convert_tf_checkpoint_to_pytorch", "convert_openai_checkpoint", "convert_transfo_xl_checkpoint", "convert_gpt2_checkpoint", ]: print( "Should be used ...
4,393
51.309524
145
py
BertGen
BertGen-master/external/pytorch_pretrained_bert/convert_gpt2_checkpoint_to_pytorch.py
# coding=utf-8 # Copyright 2018 The HugginFace Inc. team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable ...
3,046
40.739726
111
py
BertGen
BertGen-master/external/pytorch_pretrained_bert/convert_openai_checkpoint_to_pytorch.py
# coding=utf-8 # Copyright 2018 The HugginFace Inc. team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable ...
3,141
42.041096
118
py
BertGen
BertGen-master/external/pytorch_pretrained_bert/modeling.py
# coding=utf-8 # Copyright 2018 The Google AI Language Team Authors and The HugginFace Inc. team. # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy...
60,198
48.18219
139
py
BertGen
BertGen-master/external/pytorch_pretrained_bert/modeling_gpt2.py
# coding=utf-8 # Copyright 2018 The OpenAI Team Authors and HugginFace Inc. team. # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License ...
29,887
42.632117
146
py
BertGen
BertGen-master/external/pytorch_pretrained_bert/modeling_openai.py
# coding=utf-8 # Copyright 2018 The OpenAI Team Authors and HugginFace Inc. team. # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License ...
37,647
45.421702
152
py
BertGen
BertGen-master/external/pytorch_pretrained_bert/convert_transfo_xl_checkpoint_to_pytorch.py
# coding=utf-8 # Copyright 2018 The HugginFace Inc. team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable ...
5,642
47.230769
121
py
BertGen
BertGen-master/external/pytorch_pretrained_bert/file_utils.py
""" Utilities for working with the local dataset cache. This file is adapted from the AllenNLP library at https://github.com/allenai/allennlp Copyright by the AllenNLP authors. """ from __future__ import (absolute_import, division, print_function, unicode_literals) import json import logging import os import shutil im...
8,280
32.124
112
py
BertGen
BertGen-master/external/pytorch_pretrained_bert/convert_tf_checkpoint_to_pytorch.py
# coding=utf-8 # Copyright 2018 The HugginFace Inc. team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable ...
2,538
39.301587
109
py
BertGen
BertGen-master/external/pytorch_pretrained_bert/modeling_transfo_xl.py
# coding=utf-8 # Copyright 2018 Google AI, Google Brain and Carnegie Mellon University Authors and the HugginFace Inc. team. # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the Licen...
58,702
41.476845
131
py
BertGen
BertGen-master/external/pytorch_pretrained_bert/tokenization_transfo_xl.py
# coding=utf-8 # Copyright 2018 Google AI, Google Brain and Carnegie Mellon University Authors and the HugginFace Inc. team. # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the Licen...
24,851
35.927192
109
py
BertGen
BertGen-master/external/pytorch_pretrained_bert/modeling_transfo_xl_utilities.py
# coding=utf-8 # Copyright 2018 Google AI, Google Brain and Carnegie Mellon University Authors and the HugginFace Inc. team. # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the Licen...
16,113
38.985112
132
py
BertGen
BertGen-master/common/lr_scheduler.py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. from bisect import bisect_right import torch # FIXME ideally this would be achieved with a CombinedLRScheduler, # separating MultiStepLR with WarmupLR # but the current LRScheduler design doesn't allow it class WarmupMultiStepLR(torch.optim.lr_s...
1,810
33.169811
80
py
BertGen
BertGen-master/common/fast_rcnn.py
import torch import torch.nn as nn import torch.nn.functional as F import torch.utils.model_zoo as model_zoo from common.backbone.resnet.resnet import * from common.backbone.resnet.resnet import Bottleneck, BasicBlock from common.backbone.resnet.resnet import model_urls from common.lib.roi_pooling.roi_pool import ROI...
10,223
49.117647
155
py
BertGen
BertGen-master/common/visual_linguistic_bert.py
import torch import torch.nn as nn from external.pytorch_pretrained_bert.modeling import BertLayerNorm, BertEncoder, BertPooler, ACT2FN, BertOnlyMLMHead # todo: add this to config NUM_SPECIAL_WORDS = 1000 class BaseModel(nn.Module): def __init__(self, config, **kwargs): self.config = config super...
43,500
49.700466
139
py
BertGen
BertGen-master/common/module.py
from collections import namedtuple from typing import Dict import torch import torch.nn as nn import torch.nn.functional as F class Module(nn.Module): def __init__(self, config): super(Module, self).__init__() self.config = config def init_weight(self): raise NotImplementedError() ...
1,786
26.921875
65
py
BertGen
BertGen-master/common/trainer.py
import os import time from collections import namedtuple import torch try: from apex import amp from apex.amp import _amp_state except ImportError: pass #raise ImportError("Please install apex from https://www.github.com/nvidia/apex if you want to use fp16.") # Parameter to pass to batch_end_callback ...
7,661
37.31
122
py
BertGen
BertGen-master/common/backbone/resnet/resnet.py
""" Modified from torchvision, but exposes features from different stages """ import torch.nn as nn import torch.utils.model_zoo as model_zoo import torch import warnings __all__ = ['ResNet', 'resnet18', 'resnet34', 'resnet50', 'resnet101', 'resnet152'] model_urls = { 'resnet18': 'https://download.pyt...
17,247
40.461538
135
py
BertGen
BertGen-master/common/callbacks/epoch_end_callbacks/checkpoint.py
import torch class Checkpoint(object): def __init__(self, prefix, frequent): super(Checkpoint, self).__init__() self.prefix = prefix self.frequent = frequent def __call__(self, epoch_num, net, optimizer, writer, validation_monitor=None): if (epoch_num + 1) % self.frequent == 0...
1,119
42.076923
87
py
BertGen
BertGen-master/common/nlp/misc.py
import torch import random def get_align_matrix(aligned_ids, sparse=False, device=None, dtype=torch.float32): """ Get aligned matrix for feature alignment in sentence embedding :param aligned_ids: list, aligned_ids[k] means original index of k-th token :param sparse: whether to return sparse matrix ...
2,726
30.344828
104
py
BertGen
BertGen-master/common/nlp/time_distributed.py
""" A wrapper that unrolls the second (time) dimension of a tensor into the first (batch) dimension, applies some other ``Module``, and then rolls the time dimension back up. """ import torch class TimeDistributed(torch.nn.Module): """ Given an input shaped like ``(batch_size, time_steps, [rest])`` and a ``M...
2,245
42.192308
99
py
BertGen
BertGen-master/common/nlp/encoder_base.py
from typing import Tuple, Union, Optional, Callable import torch from torch.nn.utils.rnn import pack_padded_sequence, PackedSequence # We have two types here for the state, because storing the state in something # which is Iterable (like a tuple, below), is helpful for internal manipulation # - however, the states are...
18,404
52.502907
109
py
BertGen
BertGen-master/common/nlp/bert_encoder_wrapper.py
import torch import torch.nn as nn from external.pytorch_pretrained_bert.modeling import BertEncoder, BertLayerNorm class BertEncoderWrapper(nn.Module): def __init__(self, bert_config, input_size, output_all_encoded_layers=False): super(BertEncoderWrapper, self).__init__() self.bert_config = bert_...
3,207
49.125
112
py
BertGen
BertGen-master/common/nlp/input_variational_dropout.py
import torch class InputVariationalDropout(torch.nn.Dropout): """ Apply the dropout technique in Gal and Ghahramani, "Dropout as a Bayesian Approximation: Representing Model Uncertainty in Deep Learning" (https://arxiv.org/abs/1506.02142) to a 3D tensor. This module accepts a 3D tensor of shape ``...
1,324
37.970588
98
py
BertGen
BertGen-master/common/nlp/roberta/utils.py
from __future__ import (absolute_import, division, print_function, unicode_literals) import sys import os try: from functools import lru_cache except ImportError: # Just a dummy decorator to get the checks to run on python2 # because honestly I don't want to support a byte-level un...
40,379
45.736111
380
py
BertGen
BertGen-master/common/nlp/roberta/modeling_roberta.py
# coding=utf-8 # Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team. # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a cop...
17,448
53.021672
134
py
BertGen
BertGen-master/common/nlp/bert/optimization.py
# coding=utf-8 # Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICEN...
8,633
44.925532
130
py
BertGen
BertGen-master/common/metrics/eval_metric.py
import torch import torch.distributed as distributed class EvalMetric(object): """Base class for all evaluation metrics. .. note:: This is a base class that provides common metric interfaces. One should not use this class directly, but instead create new metric classes that extend it. ...
2,371
33.376812
80
py
BertGen
BertGen-master/common/metrics/pretrain_metrics.py
import torch from .eval_metric import EvalMetric class LossLogger(EvalMetric): def __init__(self, output_name, display_name=None, allreduce=False, num_replicas=1): self.output_name = output_name if display_name is None: display_name = output_name super(LossLogg...
6,797
40.2
131
py
BertGen
BertGen-master/common/metrics/composite_eval_metric.py
import numpy as np from .eval_metric import EvalMetric import torch class CompositeEvalMetric(EvalMetric): """Manages multiple evaluation metrics. Args: metrics (list of EvalMetric): List of child metrics. name (str): Name of this metric instance for display. """ def __init__(self, met...
2,153
29.771429
80
py