repo
stringlengths
2
99
file
stringlengths
13
225
code
stringlengths
0
18.3M
file_length
int64
0
18.3M
avg_line_length
float64
0
1.36M
max_line_length
int64
0
4.26M
extension_type
stringclasses
1 value
Paddle
Paddle-master/paddle/gserver/tests/img_conv_exconv.py
# Copyright (c) 2016 PaddlePaddle Authors. 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 at # # http://www.apache.org/licenses/LICENSE-2.0 # #Unless required by applicabl...
957
28.9375
73
py
Paddle
Paddle-master/paddle/gserver/tests/pyDataProvider.py
# Copyright (c) 2016 PaddlePaddle Authors. 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 at # # http://www.apache.org/licenses/LICENSE-2.0 # #Unless required by applicabl...
4,664
30.734694
73
py
Paddle
Paddle-master/doc/fluid/api/gen_doc.py
# Copyright (c) 2018 PaddlePaddle Authors. 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 at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by app...
3,426
30.154545
80
py
Paddle
Paddle-master/doc/fluid/dev/src/fc.py
# Copyright (c) 2018 PaddlePaddle Authors. 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 at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by app...
3,759
44.853659
101
py
Paddle
Paddle-master/doc/v2/faq/local/src/reduce_min_pool_size.py
# Copyright (c) 2018 PaddlePaddle Authors. 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 at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by app...
871
38.636364
76
py
Paddle
Paddle-master/doc/v2/faq/local/src/word2vec_dataprovider.py
# Copyright (c) 2018 PaddlePaddle Authors. 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 at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by app...
949
37
76
py
Paddle
Paddle-master/doc/v2/faq/local/src/word2vec_config.py
# Copyright (c) 2018 PaddlePaddle Authors. 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 at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by app...
1,095
39.592593
74
py
Paddle
Paddle-master/doc/v2/getstarted/concepts/src/infer.py
# Copyright (c) 2018 PaddlePaddle Authors. 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 at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by app...
1,231
36.333333
76
py
Paddle
Paddle-master/doc/v2/getstarted/concepts/src/train.py
# Copyright (c) 2018 PaddlePaddle Authors. 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 at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by app...
2,336
31.458333
80
py
Paddle
Paddle-master/doc/v2/howto/cluster/multi_cluster/src/k8s_train/start_paddle.py
#!/usr/bin/python # Copyright (c) 2016 PaddlePaddle Authors. 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 at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless ...
5,637
31.97076
76
py
Paddle
Paddle-master/doc/v2/howto/cluster/src/word2vec/api_train_v2.py
# Copyright (c) 2018 PaddlePaddle Authors. 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 at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by app...
4,208
35.6
79
py
Paddle
Paddle-master/doc/v2/howto/cluster/src/word2vec/api_train_v2_cluster.py
# Copyright (c) 2018 PaddlePaddle Authors. 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 at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by app...
5,340
37.702899
80
py
Paddle
Paddle-master/doc/v2/howto/cluster/src/word2vec/prepare.py
# Copyright (c) 2018 PaddlePaddle Authors. 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 at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by app...
1,727
29.857143
77
py
Paddle
Paddle-master/go/pserver/client/c/test/test_train.py
# Copyright (c) 2018 PaddlePaddle Authors. 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 at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by app...
3,406
36.855556
76
py
Paddle
Paddle-master/go/pserver/client/c/test/test_mnist.py
# Copyright (c) 2018 PaddlePaddle Authors. 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 at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by app...
5,239
34.890411
80
py
atari-irl
atari-irl-master/atari_irl/optimizers.py
from baselines.ppo2.ppo2 import Model, constfn from .sampling import PPOBatch, PPOSample import numpy as np from collections import namedtuple """ Heavily based on the ppo2 implementation found in the OpenAI baselines library, particularly the ppo_trainsteps function. """ BatchingConfig = namedtuple('BatchingInfo'...
4,263
32.574803
86
py
atari-irl
atari-irl-master/atari_irl/training.py
import numpy as np from baselines import logger from baselines.common import explained_variance from baselines.ppo2.ppo2 import safemean from baselines.ppo2 import ppo2 from . import policies from .sampling import PPOBatchSampler, DummyAlgo from .optimizers import PPOOptimizer, make_batching_config from collections ...
7,735
32.634783
87
py
atari-irl
atari-irl-master/atari_irl/utils.py
""" This may all be thrown away soonish, but I could imagine keeping these design patterns in some form or other. I hope that most of our patches to the baselines + gym code can happen in this library, and not need to move into other parts of the code. Desiderata: - Not introduce too many dependencies over Adam's pat...
7,278
31.066079
120
py
atari-irl
atari-irl-master/atari_irl/sampling.py
import numpy as np import tensorflow as tf from . import utils from collections import namedtuple, deque from rllab.misc.overrides import overrides from rllab.sampler.base import BaseSampler from sandbox.rocky.tf.samplers.vectorized_sampler import VectorizedSampler from baselines.ppo2 import ppo2 """ Heavily based o...
19,581
34.53902
105
py
atari-irl
atari-irl-master/atari_irl/policies.py
import numpy as np from baselines.ppo2.ppo2 import Model from . import environments from .utils import one_hot import os import os.path as osp import joblib class Policy: """ Lets us save, restore, and step a policy forward Plausibly we'll want to start passing a SerializationContext argument instead...
6,559
34.846995
123
py
atari-irl
atari-irl-master/atari_irl/environments.py
import pickle import numpy as np import tensorflow as tf from rllab.envs.base import Env from rllab.envs.gym_env import convert_gym_space from baselines.common.vec_env import VecEnvWrapper from baselines.common.vec_env.vec_normalize import VecNormalize from baselines.common.vec_env.vec_frame_stack import VecFrameStack ...
15,534
27.821892
94
py
atari-irl
atari-irl-master/atari_irl/__init__.py
from . import utils, training, policies, environments, irl, sampling, encoding
78
78
78
py
atari-irl
atari-irl-master/atari_irl/encoding.py
from atari_irl import utils import tensorflow as tf import numpy as np import joblib import os.path as osp from baselines.a2c.utils import conv, fc, conv_to_fc from baselines.ppo2 import ppo2 from collections import deque def batch_norm(name, x): shape = (1, *x.shape[1:]) with tf.variable_scope(name): ...
19,671
36.541985
103
py
atari-irl
atari-irl-master/atari_irl/irl.py
import tensorflow as tf import numpy as np import pickle from rllab.misc import logger from rllab.baselines.zero_baseline import ZeroBaseline from rllab.misc.overrides import overrides from sandbox.rocky.tf.envs.base import TfEnv from rllab.core.serializable import Serializable from sandbox.rocky.tf.policies.base imp...
40,339
35.407942
129
py
atari-irl
atari-irl-master/atari_irl/behavioral_cloning.py
from atari_irl import encoding, utils import tensorflow as tf import joblib from airl.models.architectures import relu_net import os.path as osp import numpy as np from gym.spaces import Discrete from baselines.common.distributions import make_pdtype cnn_fn = lambda obs_tensor, n_actions: encoding.dcgan_cnn(obs_tensor...
4,034
36.361111
100
py
atari-irl
atari-irl-master/scripts/train_airl.py
from atari_irl import utils, environments, irl from arguments import add_atari_args, add_trajectory_args, add_irl_args, env_context_for_args import argparse from baselines import logger import tensorflow as tf import pickle import joblib from baselines.ppo2.policies import CnnPolicy, MlpPolicy from atari_irl.irl import...
2,290
33.712121
93
py
atari-irl
atari-irl-master/scripts/train_ae.py
from atari_irl import utils, encoding import tensorflow as tf import numpy as np import matplotlib.pyplot as plt from collections import deque from baselines.ppo2 import ppo2 import joblib import os.path as osp import argparse parser = argparse.ArgumentParser( formatter_class=argparse.ArgumentDefaultsHelpFormatter...
3,580
32.157407
98
py
atari-irl
atari-irl-master/scripts/arguments.py
#from atari_irl import utils, environments, training, policies, irl from atari_irl import utils, environments def add_bool_feature(parser, name, default=True): feature_parser = parser.add_mutually_exclusive_group(required=False) feature_parser.add_argument('--' + name, dest=name, action='store_true') feat...
4,330
31.320896
102
py
atari-irl
atari-irl-master/scripts/trajectory_to_gif.py
import numpy as np import pickle from matplotlib.animation import FuncAnimation import matplotlib.pyplot as plt import argparse def make_gif(traj, fname, title=''): fig, ax = plt.subplots(figsize=(2, 2)) def update(i): if i % 20 == 0: print(i) im_normed = traj[i] ax.imshow(...
1,064
28.583333
93
py
atari-irl
atari-irl-master/scripts/train_expert.py
from atari_irl import utils, training, policies import argparse from arguments import add_atari_args, add_expert_args, env_context_for_args, tf_context_for_args from baselines.ppo2.policies import MlpPolicy, CnnPolicy import os.path as osp import os def train_expert(args): utils.logger.configure() with tf_con...
1,935
34.851852
96
py
atari-irl
atari-irl-master/scripts/generate_trajectories.py
from atari_irl import utils, policies, environments, irl, training, sampling, behavioral_cloning import pickle from arguments import add_atari_args, add_trajectory_args, add_expert_args, tf_context_for_args, env_context_for_args import argparse import tensorflow as tf import joblib from baselines.ppo2.policies import C...
3,171
37.216867
117
py
atari-irl
atari-irl-master/scripts/cache_trajectories.py
from atari_irl import sampling, irl, utils from arguments import add_atari_args, add_trajectory_args, add_irl_args, env_context_for_args import argparse from baselines import logger import tensorflow as tf import numpy as np import pickle import joblib from baselines.ppo2.policies import CnnPolicy, MlpPolicy from atari...
3,211
35.089888
94
py
atari-irl
atari-irl-master/scripts/train_clone.py
import argparse import tensorflow as tf from atari_irl import utils, behavioral_cloning import os.path as osp import joblib from arguments import add_atari_args, add_trajectory_args, add_expert_args, tf_context_for_args, env_context_for_args if __name__ == '__main__': parser = argparse.ArgumentParser( form...
1,942
32.5
117
py
atari-irl
atari-irl-master/scripts/run_irl_policy.py
from atari_irl import utils, environments, irl import pickle from arguments import add_atari_args, add_trajectory_args, add_irl_args, tf_context_for_args, env_context_for_args import argparse import tensorflow as tf from sandbox.rocky.tf.envs.base import TfEnv def run_irl_policy(args): with tf_context_for_args(ar...
1,006
30.46875
114
py
atari-irl
atari-irl-master/tests/test_irl.py
from atari_irl import irl, utils, environments, policies, training, sampling import tensorflow as tf import numpy as np import pickle from baselines.ppo2 import ppo2 def assert_trajectory_formatted(samples): print(f"Found {len(samples)} trajectories") for sample in samples: assert 'observations' in s...
10,559
43.1841
98
py
data-to-text-hierarchical
data-to-text-hierarchical-master/create-experiment.py
import pkg_resources import argparse import shutil import os if __name__ == '__main__': parser = argparse.ArgumentParser(description="Create an experiment folder") parser.add_argument('--name', dest='name', required=True) args = parser.parse_args() folder = pkg_resources.resource_filename(__...
974
28.545455
87
py
data-to-text-hierarchical
data-to-text-hierarchical-master/average-checkpoints.py
"""This file is nearly word-for-word taken from the folder tools in OpenNMT""" import pkg_resources import argparse import torch import os def average_checkpoints(checkpoint_files): vocab = None opt = None avg_model = None avg_generator = None for i, checkpoint_file in enumerate(checkpoint_fi...
1,847
33.867925
100
py
data-to-text-hierarchical
data-to-text-hierarchical-master/translate.py
#!/usr/bin/env python from onmt.bin.translate import main if __name__ == "__main__": main()
98
13.142857
35
py
data-to-text-hierarchical
data-to-text-hierarchical-master/batch_translate.py
import subprocess import functools import argparse import torch import os import re partial_shell= = functools.partial(subprocess.run, shell=True, stdout=subprocess.PIPE) def shell(cmd): """Execute cmd as if from the command line""" completed_process = partial_shell(cmd) ...
434
23.166667
62
py
data-to-text-hierarchical
data-to-text-hierarchical-master/train.py
#!/usr/bin/env python from onmt.bin.train import main if __name__ == "__main__": main()
94
12.571429
31
py
data-to-text-hierarchical
data-to-text-hierarchical-master/preprocess.py
#!/usr/bin/env python from onmt.bin.preprocess import main if __name__ == "__main__": main()
99
13.285714
36
py
data-to-text-hierarchical
data-to-text-hierarchical-master/data/make-dataset.py
""" In this file we build the RotoWire dataset so that it can be used in OpenNMT and it can be used by our proposed hierarchical model. All tables are represented as a sequence, where every ENT_SIZE tokens are one entity, so that seq.view(ENT_SIZE, -1) separates all entities. Each entity starts with <ent> token, for l...
6,186
36.49697
90
py
data-to-text-hierarchical
data-to-text-hierarchical-master/onmt/opts.py
""" Implementation of all available options """ from __future__ import print_function import configargparse from onmt.models.sru import CheckSRU def config_opts(parser): parser.add('-config', '--config', required=False, is_config_file_arg=True, help='config file path') parser.add('-save_config...
42,843
51.893827
118
py
data-to-text-hierarchical
data-to-text-hierarchical-master/onmt/train_single.py
#!/usr/bin/env python """Training on a single process.""" import os import torch from onmt.inputters.inputter import build_dataset_iter, \ load_old_vocab, old_style_vocab, build_dataset_iter_multiple from onmt.model_builder import build_model from onmt.utils.optimizers import Optimizer from onmt.utils.misc import...
4,977
32.863946
79
py
data-to-text-hierarchical
data-to-text-hierarchical-master/onmt/model_builder.py
""" This file is for models creation, which consults options and creates each encoder and decoder accordingly. """ import re import torch import torch.nn as nn from torch.nn.init import xavier_uniform_ import onmt.inputters as inputters import onmt.modules from onmt.encoders import str2enc from onmt.decoders import s...
9,581
34.227941
81
py
data-to-text-hierarchical
data-to-text-hierarchical-master/onmt/__init__.py
""" Main entry point of the ONMT library """ from __future__ import division, print_function import onmt.inputters import onmt.encoders import onmt.decoders import onmt.models import onmt.utils import onmt.modules from onmt.trainer import Trainer import sys import onmt.utils.optimizers onmt.utils.optimizers.Optim = on...
615
25.782609
69
py
data-to-text-hierarchical
data-to-text-hierarchical-master/onmt/trainer.py
""" 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 ...
18,735
39.292473
79
py
data-to-text-hierarchical
data-to-text-hierarchical-master/onmt/inputters/text_dataset.py
# -*- coding: utf-8 -*- from functools import partial import six import torch from torchtext.data import Field, RawField from onmt.inputters.datareader_base import DataReaderBase class TextDataReader(DataReaderBase): def read(self, sequences, side, _dir=None): """Read text data from disk. Args:...
6,904
34.410256
77
py
data-to-text-hierarchical
data-to-text-hierarchical-master/onmt/inputters/dataset_base.py
# coding: utf-8 from itertools import chain, starmap from collections import Counter import torch from torchtext.data import Dataset as TorchtextDataset from torchtext.data import Example from torchtext.vocab import Vocab def _join_dicts(*args): """ Args: dictionaries with disjoint keys. Return...
6,865
40.612121
78
py
data-to-text-hierarchical
data-to-text-hierarchical-master/onmt/inputters/datareader_base.py
# coding: utf-8 # several data readers need optional dependencies. There's no # appropriate builtin exception class MissingDependencyException(Exception): pass class DataReaderBase(object): """Read data from file system and yield as dicts. Raises: onmt.inputters.datareader_base.MissingDependenc...
1,286
26.978261
75
py
data-to-text-hierarchical
data-to-text-hierarchical-master/onmt/inputters/inputter.py
# -*- coding: utf-8 -*- import glob import os import codecs import math from collections import Counter, defaultdict from itertools import chain, cycle import torch import torchtext.data from torchtext.data import Field, RawField, LabelField from torchtext.vocab import Vocab from torchtext.data.utils import RandomShu...
31,503
35.590012
79
py
data-to-text-hierarchical
data-to-text-hierarchical-master/onmt/inputters/audio_dataset.py
# -*- coding: utf-8 -*- import os from tqdm import tqdm import torch from torchtext.data import Field from onmt.inputters.datareader_base import DataReaderBase # imports of datatype-specific dependencies try: import torchaudio import librosa import numpy as np except ImportError: torchaudio, librosa,...
8,459
36.93722
79
py
data-to-text-hierarchical
data-to-text-hierarchical-master/onmt/inputters/image_dataset.py
# -*- coding: utf-8 -*- import os import torch from torchtext.data import Field from onmt.inputters.datareader_base import DataReaderBase # domain specific dependencies try: from PIL import Image from torchvision import transforms import cv2 except ImportError: Image, transforms, cv2 = None, None, N...
3,378
30.579439
77
py
data-to-text-hierarchical
data-to-text-hierarchical-master/onmt/inputters/__init__.py
"""Module defining inputters. Inputters implement the logic of transforming raw data to vectorized inputs, e.g., from a line of text to a sequence of embeddings. """ from onmt.inputters.inputter import \ load_old_vocab, get_fields, OrderedIterator, \ build_vocab, old_style_vocab, filter_example from onmt.input...
1,267
39.903226
77
py
data-to-text-hierarchical
data-to-text-hierarchical-master/onmt/inputters/vec_dataset.py
import os import torch from torchtext.data import Field from onmt.inputters.datareader_base import DataReaderBase try: import numpy as np except ImportError: np = None class VecDataReader(DataReaderBase): """Read feature vector data from disk. Raises: onmt.inputters.datareader_base.MissingD...
5,447
35.32
78
py
data-to-text-hierarchical
data-to-text-hierarchical-master/onmt/modules/sparse_losses.py
import torch import torch.nn as nn from torch.autograd import Function from onmt.modules.sparse_activations import _threshold_and_support from onmt.utils.misc import aeq class SparsemaxLossFunction(Function): @staticmethod def forward(ctx, input, target): """ input (FloatTensor): ``(n, num_cl...
2,804
35.428571
78
py
data-to-text-hierarchical
data-to-text-hierarchical-master/onmt/modules/sparse_activations.py
""" An implementation of sparsemax (Martins & Astudillo, 2016). See :cite:`DBLP:journals/corr/MartinsA16` for detailed description. By Ben Peters and Vlad Niculae """ import torch from torch.autograd import Function import torch.nn as nn def _make_ix_like(input, dim=0): d = input.size(dim) rho = torch.arang...
2,649
26.040816
78
py
data-to-text-hierarchical
data-to-text-hierarchical-master/onmt/modules/structured_attention.py
import torch.nn as nn import torch import torch.cuda 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 Representations" :cite:`DBLP:journals/corr/Li...
1,414
35.282051
77
py
data-to-text-hierarchical
data-to-text-hierarchical-master/onmt/modules/util_class.py
""" Misc classes """ import torch import torch.nn as nn # At the moment this class is only used by embeddings.Embeddings look-up tables class Elementwise(nn.ModuleList): """ A simple network container. Parameters are a list of modules. Inputs are a 3d Tensor whose last dimension is the same length ...
1,486
29.346939
79
py
data-to-text-hierarchical
data-to-text-hierarchical-master/onmt/modules/hierarchical_attention.py
from ..utils.misc import aeq from .sparse_activations import sparsemax from torch.nn.utils.rnn import pad_sequence import torch import onmt class ContainsNaN(Exception): pass def _check_for_nan(tensor, msg=''): if (tensor!=tensor).any(): raise ContainsNaN(msg) def _check_sizes(tensor, *si...
10,134
36.537037
94
py
data-to-text-hierarchical
data-to-text-hierarchical-master/onmt/modules/conv_multi_step_attention.py
""" Multi Step Attention for CNN """ import torch import torch.nn as nn import torch.nn.functional as F from onmt.utils.misc 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...
2,865
34.382716
79
py
data-to-text-hierarchical
data-to-text-hierarchical-master/onmt/modules/average_attn.py
# -*- coding: utf-8 -*- """Average Attention module.""" import torch import torch.nn as nn from onmt.modules.position_ffn import PositionwiseFeedForward class AverageAttention(nn.Module): """ Average Attention module from "Accelerating Neural Transformer via an Average Attention Network" :cite:`DBLP...
4,227
36.75
79
py
data-to-text-hierarchical
data-to-text-hierarchical-master/onmt/modules/copy_generator.py
import torch import torch.nn as nn from onmt.utils.misc import aeq from onmt.utils.loss import NMTLossCompute def collapse_copy_scores(scores, batch, tgt_vocab, src_vocabs=None, batch_dim=1, batch_offset=None): """ Given scores from an expanded dictionary corresponeding to a batc...
9,415
34.938931
79
py
data-to-text-hierarchical
data-to-text-hierarchical-master/onmt/modules/self_attention.py
""" Custom reimplementation of torch.nn.MultiHeadAttention It's actually the same module, with more or less flewibility at times, and a more flexible use of the mask (different mask per element of the batch) """ from torch._jit_internal import weak_module, weak_script_method from torch.nn.init import constant_ from to...
5,556
43.103175
109
py
data-to-text-hierarchical
data-to-text-hierarchical-master/onmt/modules/embeddings.py
""" Embeddings module """ import math import warnings import torch import torch.nn as nn from onmt.modules.util_class import Elementwise class PositionalEncoding(nn.Module): """Sinusoidal positional encoding for non-recurrent neural networks. Implementation based on "Attention Is All You Need" :cite:`D...
10,689
36.640845
79
py
data-to-text-hierarchical
data-to-text-hierarchical-master/onmt/modules/global_attention.py
"""Global attention modules (Luong / Bahdanau)""" import torch import torch.nn as nn import torch.nn.functional as F from onmt.modules.sparse_activations import sparsemax from onmt.utils.misc import aeq, sequence_mask # This class is mainly used by decoder.py for RNNs but also # by the CNN / transformer decoder when ...
7,827
33.333333
79
py
data-to-text-hierarchical
data-to-text-hierarchical-master/onmt/modules/glu.py
"""Comes directly from fairseq""" import torch, math class Downsample(torch.nn.Module): """ Selects every nth element along the last dim, where n is the index """ def __init__(self, in_dim, step): super().__init__() self._step = step self._in_dim = in_dim if in...
2,916
37.893333
92
py
data-to-text-hierarchical
data-to-text-hierarchical-master/onmt/modules/__init__.py
""" Attention and normalization modules """ from onmt.modules.util_class import Elementwise from onmt.modules.gate import context_gate_factory, ContextGate from onmt.modules.global_attention import GlobalAttention from onmt.modules.hierarchical_attention import HierarchicalAttention from onmt.modules.conv_multi_step_...
1,297
50.92
75
py
data-to-text-hierarchical
data-to-text-hierarchical-master/onmt/modules/gate.py
""" ContextGate module """ import torch import torch.nn as nn def context_gate_factory(gate_type, embeddings_size, decoder_size, attention_size, output_size): """Returns the correct ContextGate class""" gate_types = {'source': SourceContextGate, 'target': TargetCont...
3,635
38.521739
79
py
data-to-text-hierarchical
data-to-text-hierarchical-master/onmt/modules/weight_norm.py
""" Weights normalization modules """ import torch import torch.nn as nn import torch.nn.functional as F from torch.nn import Parameter def get_var_maybe_avg(namespace, var_name, training, polyak_decay): """ utility for retrieving polyak averaged params Update average """ v = getattr(namespace, ...
9,775
38.578947
78
py
data-to-text-hierarchical
data-to-text-hierarchical-master/onmt/modules/position_ffn.py
"""Position feed-forward network from "Attention is All You Need".""" import torch.nn as nn class PositionwiseFeedForward(nn.Module): """ A two-layer Feed-Forward-Network with residual layer norm. Args: d_model (int): the size of input for the first-layer of the FFN. d_ff (int): the hidden l...
1,308
30.166667
73
py
data-to-text-hierarchical
data-to-text-hierarchical-master/onmt/modules/multi_headed_attn.py
""" Multi-Head Attention module """ import math import torch import torch.nn as nn from onmt.utils.misc import generate_relative_positions_matrix,\ relative_matmul # from onmt.utils.misc import aeq class MultiHeadedAttention(nn.Module): """Multi-Head Attention module from "Attention i...
8,133
34.212121
77
py
data-to-text-hierarchical
data-to-text-hierarchical-master/onmt/modules/table_embeddings.py
import torch class TableEmbeddings(torch.nn.Module): """ Now that I think about it, we can do more efficiently than rewritting the onmt module. I will in the future but for now this code works as is, so I won't chance breaking it! These embeddings follow the table structure: a table is an uno...
4,278
37.54955
79
py
data-to-text-hierarchical
data-to-text-hierarchical-master/onmt/models/stacked_rnn.py
""" Implementation of ONMT RNN for Input Feeding Decoding """ 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): ...
1,994
29.227273
66
py
data-to-text-hierarchical
data-to-text-hierarchical-master/onmt/models/model.py
""" Onmt NMT Model base class definition """ import torch.nn as nn class NMTModel(nn.Module): """ Core trainable object in OpenNMT. Implements a trainable interface for a simple, generic encoder + decoder model. Args: encoder (onmt.encoders.EncoderBase): an encoder object decoder (onmt.de...
2,218
37.929825
77
py
data-to-text-hierarchical
data-to-text-hierarchical-master/onmt/models/__init__.py
"""Module defining models.""" from onmt.models.model_saver import build_model_saver, ModelSaver from onmt.models.model import NMTModel __all__ = ["build_model_saver", "ModelSaver", "NMTModel"]
194
31.5
65
py
data-to-text-hierarchical
data-to-text-hierarchical-master/onmt/models/model_saver.py
import os import torch from collections import deque from onmt.utils.logging import logger from copy import deepcopy def build_model_saver(model_opt, opt, model, fields, optim): model_saver = ModelSaver(opt.save_model, model, model_opt, ...
4,230
30.340741
79
py
data-to-text-hierarchical
data-to-text-hierarchical-master/onmt/models/sru.py
""" SRU Implementation """ # flake8: noqa import subprocess import platform import os import re import configargparse import torch import torch.nn as nn from torch.autograd import Function from collections import namedtuple # For command-line option parsing class CheckSRU(configargparse.Action): def __init__(sel...
24,302
36.27454
81
py
data-to-text-hierarchical
data-to-text-hierarchical-master/onmt/bin/average_models.py
#!/usr/bin/env python import argparse import torch def average_models(model_files, fp32=False): vocab = None opt = None avg_model = None avg_generator = None for i, model_file in enumerate(model_files): m = torch.load(model_file, map_location='cpu') model_weights = m['model'] ...
1,665
29.290909
79
py
data-to-text-hierarchical
data-to-text-hierarchical-master/onmt/bin/server.py
#!/usr/bin/env python import configargparse from flask import Flask, jsonify, request from onmt.translate import TranslationServer, ServerModelError STATUS_OK = "ok" STATUS_ERROR = "error" def start(config_file, url_root="./translator", host="0.0.0.0", port=5000, debug=True):...
4,328
30.369565
79
py
data-to-text-hierarchical
data-to-text-hierarchical-master/onmt/bin/translate.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import unicode_literals from onmt.utils.logging import init_logger from onmt.utils.misc import split_corpus from onmt.translate.translator import build_translator import onmt.opts as opts from onmt.utils.parse import ArgumentParser def translate(opt): ...
1,308
23.698113
60
py
data-to-text-hierarchical
data-to-text-hierarchical-master/onmt/bin/__init__.py
0
0
0
py
data-to-text-hierarchical
data-to-text-hierarchical-master/onmt/bin/train.py
#!/usr/bin/env python """Train models.""" import os import signal import torch import onmt.opts as opts import onmt.utils.distributed from onmt.utils.misc import set_random_seed from onmt.utils.logging import init_logger, logger from onmt.train_single import main as single_main from onmt.utils.parse import ArgumentPa...
6,849
31.77512
79
py
data-to-text-hierarchical
data-to-text-hierarchical-master/onmt/bin/preprocess.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Pre-process Data / features files and build vocabulary """ import codecs import glob import gc import torch from collections import Counter, defaultdict from onmt.utils.logging import init_logger, logger from onmt.utils.misc import split_corpus import onmt.inputter...
11,018
35.97651
76
py
data-to-text-hierarchical
data-to-text-hierarchical-master/onmt/decoders/transformer.py
""" Implementation of "Attention is All You Need" """ import torch import torch.nn as nn from onmt.decoders.decoder import DecoderBase from onmt.modules import MultiHeadedAttention, AverageAttention from onmt.modules.position_ffn import PositionwiseFeedForward from onmt.utils.misc import sequence_mask class Transfo...
12,530
38.282132
79
py
data-to-text-hierarchical
data-to-text-hierarchical-master/onmt/decoders/decoder.py
import torch import torch.nn as nn from onmt.models.stacked_rnn import StackedLSTM, StackedGRU from onmt.modules import context_gate_factory, GlobalAttention from onmt.utils.rnn_factory import rnn_factory from onmt.utils.misc import aeq class DecoderBase(nn.Module): """Abstract class for decoders. Args: ...
15,510
34.172336
79
py
data-to-text-hierarchical
data-to-text-hierarchical-master/onmt/decoders/__init__.py
"""Module defining decoders.""" from onmt.decoders.decoder import DecoderBase, InputFeedRNNDecoder, \ StdRNNDecoder from onmt.decoders.transformer import TransformerDecoder from onmt.decoders.cnn_decoder import CNNDecoder from onmt.decoders.hierarchical_decoder import HierarchicalRNNDecoder str2dec = {"rnn": StdR...
620
40.4
78
py
data-to-text-hierarchical
data-to-text-hierarchical-master/onmt/decoders/ensemble.py
"""Ensemble decoding. Decodes using multiple models simultaneously, combining their prediction distributions by averaging. All models in the ensemble must share a target vocabulary. """ import torch import torch.nn as nn from onmt.encoders.encoder import EncoderBase from onmt.decoders.decoder import DecoderBase from...
5,956
37.432258
79
py
data-to-text-hierarchical
data-to-text-hierarchical-master/onmt/decoders/cnn_decoder.py
"""Implementation of the CNN Decoder part of "Convolutional Sequence to Sequence Learning" """ import torch import torch.nn as nn from onmt.modules import ConvMultiStepAttention, GlobalAttention from onmt.utils.cnn_factory import shape_transform, GatedConv from onmt.decoders.decoder import DecoderBase SCALE_WEIGHT = ...
4,890
35.5
78
py
data-to-text-hierarchical
data-to-text-hierarchical-master/onmt/decoders/hierarchical_decoder.py
"""Same as normal RNNDecoder but using hierarchical attention""" import torch from .decoder import RNNDecoderBase from ..modules import HierarchicalAttention from ..models.stacked_rnn import StackedLSTM, StackedGRU from ..utils.rnn_factory import rnn_factory from ..utils.misc import aeq, nwise, sequence_mask from torc...
10,819
36.439446
90
py
data-to-text-hierarchical
data-to-text-hierarchical-master/onmt/tests/test_copy_generator.py
import unittest from onmt.modules.copy_generator import CopyGenerator, CopyGeneratorLoss import itertools from copy import deepcopy import torch from torch.nn.functional import softmax from onmt.tests.utils_for_tests import product_dict class TestCopyGenerator(unittest.TestCase): INIT_CASES = list(product_dict...
5,518
39.284672
79
py
data-to-text-hierarchical
data-to-text-hierarchical-master/onmt/tests/test_text_dataset.py
import unittest from onmt.inputters.text_dataset import TextMultiField, TextDataReader import itertools import os from copy import deepcopy from torchtext.data import Field from onmt.tests.utils_for_tests import product_dict class TestTextMultiField(unittest.TestCase): INIT_CASES = list(product_dict( b...
7,251
39.741573
76
py
data-to-text-hierarchical
data-to-text-hierarchical-master/onmt/tests/test_simple.py
import onmt def test_load(): onmt pass
49
6.142857
16
py
data-to-text-hierarchical
data-to-text-hierarchical-master/onmt/tests/test_beam_search.py
import unittest from onmt.translate.beam_search import BeamSearch, GNMTGlobalScorer from copy import deepcopy import torch class GlobalScorerStub(object): alpha = 0 beta = 0 def __init__(self): self.length_penalty = lambda x, alpha: 1. self.cov_penalty = lambda cov, beta: torch.zeros( ...
27,033
46.345009
79
py
data-to-text-hierarchical
data-to-text-hierarchical-master/onmt/tests/test_translation_server.py
import unittest from onmt.translate.translation_server import ServerModel, TranslationServer import os from six import string_types from textwrap import dedent import torch from onmt.translate.translator import Translator TEST_DIR = os.path.dirname(os.path.abspath(__file__)) class TestServerModel(unittest.TestCa...
8,233
34.339056
77
py
data-to-text-hierarchical
data-to-text-hierarchical-master/onmt/tests/test_greedy_search.py
import unittest from onmt.translate.greedy_search import GreedySearch import torch class TestGreedySearch(unittest.TestCase): BATCH_SZ = 3 INP_SEQ_LEN = 53 DEAD_SCORE = -1e20 BLOCKED_SCORE = -10e20 def test_doesnt_predict_eos_if_shorter_than_min_len(self): # batch 0 will always predict ...
9,200
41.400922
78
py
data-to-text-hierarchical
data-to-text-hierarchical-master/onmt/tests/test_models.py
import copy import unittest import math import torch import onmt import onmt.inputters import onmt.opts from onmt.model_builder import build_embeddings, \ build_encoder, build_decoder from onmt.encoders.image_encoder import ImageEncoder from onmt.encoders.audio_encoder import AudioEncoder from onmt.utils.parse im...
11,557
34.563077
76
py
data-to-text-hierarchical
data-to-text-hierarchical-master/onmt/tests/utils_for_tests.py
import itertools def product_dict(**kwargs): keys = kwargs.keys() vals = kwargs.values() for instance in itertools.product(*vals): yield dict(zip(keys, instance))
185
19.666667
45
py
data-to-text-hierarchical
data-to-text-hierarchical-master/onmt/tests/test_preprocess.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import print_function import configargparse import copy import unittest import glob import os import codecs import onmt import onmt.inputters import onmt.opts import onmt.bin.preprocess as preprocess parser = configargparse.ArgumentParser(description='pr...
6,455
35.474576
76
py
data-to-text-hierarchical
data-to-text-hierarchical-master/onmt/tests/test_image_dataset.py
import unittest from onmt.inputters.image_dataset import ImageDataReader import os import shutil import cv2 import numpy as np import torch class TestImageDataReader(unittest.TestCase): # this test touches the file system, so it could be considered an # integration test _THIS_DIR = os.path.dirname(os.pa...
3,641
38.16129
76
py