python_code stringlengths 0 187k | repo_name stringlengths 8 46 | file_path stringlengths 6 135 |
|---|---|---|
import copy
import json
from os import PathLike
import random
from typing import Any, Dict, Iterable, Set, Union
import torch
import numpy
from numpy.testing import assert_allclose
from allennlp.commands.train import train_model_from_file
from allennlp.common import Params
from allennlp.common.testing.test_case impor... | allennlp-master | allennlp/common/testing/model_test_case.py |
"""
Utilities and helpers for writing tests.
"""
from typing import Dict, Any, Optional, Union, Tuple, List
import torch
from torch.testing import assert_allclose
import pytest
from allennlp.common.testing.test_case import AllenNlpTestCase
from allennlp.common.testing.model_test_case import ModelTestCase
from allennlp... | allennlp-master | allennlp/common/testing/__init__.py |
import logging
import os
import pathlib
import shutil
import tempfile
from allennlp.common.checks import log_pytorch_version_info
TEST_DIR = tempfile.mkdtemp(prefix="allennlp_tests")
class AllenNlpTestCase:
"""
A custom testing class that disables some of the more verbose AllenNLP
logging and that creat... | allennlp-master | allennlp/common/testing/test_case.py |
from allennlp.predictors import TextClassifierPredictor
from allennlp.models.model import Model
import torch
class FakeModelForTestingInterpret(Model):
def __init__(self, vocab, max_tokens=7, num_labels=2):
super().__init__(vocab)
self._max_tokens = max_tokens
self.embedder = torch.nn.Embe... | allennlp-master | allennlp/common/testing/interpret_test.py |
import datetime
from typing import List, Dict, Any, Tuple, Callable
import torch
import torch.distributed as dist
import torch.multiprocessing as mp
from allennlp.common.checks import check_for_gpu
def init_process(
process_rank: int,
world_size: int,
distributed_device_ids: List[int],
func: Callable... | allennlp-master | allennlp/common/testing/distributed_test.py |
from allennlp.interpret.attackers.attacker import Attacker
from allennlp.interpret.saliency_interpreters.saliency_interpreter import SaliencyInterpreter
| allennlp-master | allennlp/interpret/__init__.py |
import math
from typing import List, Dict, Any
import numpy
import torch
from allennlp.common.util import JsonDict, sanitize
from allennlp.data import Instance
from allennlp.interpret.saliency_interpreters.saliency_interpreter import SaliencyInterpreter
from allennlp.nn import util
@SaliencyInterpreter.register("in... | allennlp-master | allennlp/interpret/saliency_interpreters/integrated_gradient.py |
from typing import List
import numpy
import torch
from allennlp.common import Registrable
from allennlp.common.util import JsonDict
from allennlp.nn import util
from allennlp.predictors import Predictor
class SaliencyInterpreter(Registrable):
"""
A `SaliencyInterpreter` interprets an AllenNLP Predictor's ou... | allennlp-master | allennlp/interpret/saliency_interpreters/saliency_interpreter.py |
import math
from typing import Dict, Any
import numpy
import torch
from allennlp.common.util import JsonDict, sanitize
from allennlp.data import Instance
from allennlp.interpret.saliency_interpreters.saliency_interpreter import SaliencyInterpreter
from allennlp.predictors import Predictor
@SaliencyInterpreter.regis... | allennlp-master | allennlp/interpret/saliency_interpreters/smooth_gradient.py |
import math
from typing import List
import numpy
import torch
from allennlp.common.util import JsonDict, sanitize
from allennlp.interpret.saliency_interpreters.saliency_interpreter import SaliencyInterpreter
from allennlp.nn import util
@SaliencyInterpreter.register("simple-gradient")
class SimpleGradient(SaliencyI... | allennlp-master | allennlp/interpret/saliency_interpreters/simple_gradient.py |
from allennlp.interpret.saliency_interpreters.saliency_interpreter import SaliencyInterpreter
from allennlp.interpret.saliency_interpreters.simple_gradient import SimpleGradient
from allennlp.interpret.saliency_interpreters.integrated_gradient import IntegratedGradient
from allennlp.interpret.saliency_interpreters.smoo... | allennlp-master | allennlp/interpret/saliency_interpreters/__init__.py |
from allennlp.interpret.attackers.attacker import Attacker
from allennlp.interpret.attackers.input_reduction import InputReduction
from allennlp.interpret.attackers.hotflip import Hotflip
| allennlp-master | allennlp/interpret/attackers/__init__.py |
from allennlp.common.util import JsonDict
from allennlp.data import Instance
def get_fields_to_compare(
inputs: JsonDict, instance: Instance, input_field_to_attack: str
) -> JsonDict:
"""
Gets a list of the fields that should be checked for equality after an attack is performed.
# Parameters
inp... | allennlp-master | allennlp/interpret/attackers/utils.py |
from copy import deepcopy
from typing import Dict, List, Tuple
import numpy
import torch
from allennlp.common.util import JsonDict, sanitize
from allennlp.data import Instance, Token
from allennlp.data.fields import TextField
from allennlp.data.token_indexers import (
ELMoTokenCharactersIndexer,
TokenCharacte... | allennlp-master | allennlp/interpret/attackers/hotflip.py |
from copy import deepcopy
from typing import List, Tuple
import heapq
import numpy as np
import torch
from allennlp.common.util import JsonDict, sanitize
from allennlp.data import Instance
from allennlp.data.fields import TextField, SequenceLabelField
from allennlp.interpret.attackers import utils
from allennlp.inter... | allennlp-master | allennlp/interpret/attackers/input_reduction.py |
from typing import List
from allennlp.common import Registrable
from allennlp.common.util import JsonDict
from allennlp.predictors import Predictor
class Attacker(Registrable):
"""
An `Attacker` will modify an input (e.g., add or delete tokens) to try to change an AllenNLP
Predictor's output in a desired... | allennlp-master | allennlp/interpret/attackers/attacker.py |
"""
Subcommand for building a vocabulary from a training config.
"""
import argparse
import json
import logging
import os
import tarfile
import tempfile
from overrides import overrides
from allennlp.commands.subcommand import Subcommand
from allennlp.common.file_utils import CacheFile
from allennlp.common.params imp... | allennlp-master | allennlp/commands/build_vocab.py |
"""
The `predict` subcommand allows you to make bulk JSON-to-JSON
or dataset to JSON predictions using a trained model and its
[`Predictor`](../predictors/predictor.md#predictor) wrapper.
"""
from typing import List, Iterator, Optional
import argparse
import sys
import json
from overrides import overrides
from allen... | allennlp-master | allennlp/commands/predict.py |
import argparse
import logging
import sys
from typing import Any, Optional, Tuple, Set
from overrides import overrides
from allennlp import __version__
from allennlp.commands.build_vocab import BuildVocab
from allennlp.commands.cached_path import CachedPath
from allennlp.commands.evaluate import Evaluate
from allennl... | allennlp-master | allennlp/commands/__init__.py |
"""
CLI to the the caching mechanism in `common.file_utils`.
"""
import argparse
import logging
from overrides import overrides
from allennlp.commands.subcommand import Subcommand
from allennlp.common.file_utils import (
cached_path,
CACHE_DIRECTORY,
inspect_cache,
remove_cache_entries,
)
logger = ... | allennlp-master | allennlp/commands/cached_path.py |
"""
The `print-results` subcommand allows you to print results from multiple
allennlp serialization directories to the console in a helpful csv format.
"""
import argparse
import json
import logging
import os
from overrides import overrides
from allennlp.commands.subcommand import Subcommand
logger = logging.getLog... | allennlp-master | allennlp/commands/print_results.py |
"""
The `train` subcommand can be used to train a model.
It requires a configuration file and a directory in
which to write the results.
"""
import argparse
import logging
import os
from os import PathLike
from typing import Any, Dict, List, Optional, Union
import warnings
import torch
import torch.distributed as dis... | allennlp-master | allennlp/commands/train.py |
"""
The `evaluate` subcommand can be used to
evaluate a trained model against a dataset
and report any metrics calculated by the model.
"""
import argparse
import json
import logging
from typing import Any, Dict
from overrides import overrides
from allennlp.commands.subcommand import Subcommand
from allennlp.common ... | allennlp-master | allennlp/commands/evaluate.py |
"""
Base class for subcommands under `allennlp.run`.
"""
import argparse
from typing import Callable, Dict, Optional, Type, TypeVar
from overrides import overrides
from allennlp.common import Registrable
T = TypeVar("T", bound="Subcommand")
class Subcommand(Registrable):
"""
An abstract class representin... | allennlp-master | allennlp/commands/subcommand.py |
"""
The `test-install` subcommand provides a programmatic way to verify
that AllenNLP has been successfully installed.
"""
import argparse
import logging
import pathlib
from overrides import overrides
import torch
import allennlp
from allennlp.common.util import import_module_and_submodules
from allennlp.commands.su... | allennlp-master | allennlp/commands/test_install.py |
"""
The `find-lr` subcommand can be used to find a good learning rate for a model.
It requires a configuration file and a directory in
which to write the results.
"""
import argparse
import logging
import math
import os
import re
from typing import List, Tuple
import itertools
from overrides import overrides
from al... | allennlp-master | allennlp/commands/find_learning_rate.py |
from typing import List
import torch
from torch.nn import ParameterList, Parameter
from allennlp.common.checks import ConfigurationError
from allennlp.nn import util
class ScalarMix(torch.nn.Module):
"""
Computes a parameterised scalar mixture of N tensors, `mixture = gamma * sum(s_k * tensor_k)`
where ... | allennlp-master | allennlp/modules/scalar_mix.py |
"""
A stacked LSTM with LSTM layers which alternate between going forwards over
the sequence and going backwards.
"""
from typing import Optional, Tuple, Union, List
import torch
from torch.nn.utils.rnn import PackedSequence
from allennlp.modules.augmented_lstm import AugmentedLstm
from allennlp.common.checks import C... | allennlp-master | allennlp/modules/stacked_alternating_lstm.py |
from typing import Tuple, Union, Optional, Callable, Any
import torch
from torch.nn.utils.rnn import pack_padded_sequence, PackedSequence
from allennlp.nn.util import get_lengths_from_binary_sequence_mask, sort_batch_by_length
# We have two types here for the state, because storing the state in something
# which is I... | allennlp-master | allennlp/modules/encoder_base.py |
"""
A maxout neural network.
"""
from typing import Sequence, Union
import torch
from allennlp.common.checks import ConfigurationError
from allennlp.common.registrable import FromParams
class Maxout(torch.nn.Module, FromParams):
"""
This `Module` is a maxout neural network.
# Parameters
input_dim ... | allennlp-master | allennlp/modules/maxout.py |
import json
import logging
import warnings
from typing import Any, Dict, List, Union
import numpy
import torch
from overrides import overrides
from torch.nn.modules import Dropout
from allennlp.common import FromParams
from allennlp.common.checks import ConfigurationError
from allennlp.common.file_utils import cached... | allennlp-master | allennlp/modules/elmo.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.
"""
from typing import List
from overrides import overrides
import torch
class TimeDistributed(torch.nn.Module):
"""
Given an input sha... | allennlp-master | allennlp/modules/time_distributed.py |
import torch
import numpy as np
class SoftmaxLoss(torch.nn.Module):
"""
Given some embeddings and some targets, applies a linear layer
to create logits over possible words and then returns the
negative log likelihood.
"""
def __init__(self, num_words: int, embedding_dim: int) -> None:
... | allennlp-master | allennlp/modules/softmax_loss.py |
"""
A feed-forward neural network.
"""
from typing import List, Union
import torch
from allennlp.common import FromParams
from allennlp.common.checks import ConfigurationError
from allennlp.nn import Activation
class FeedForward(torch.nn.Module, FromParams):
"""
This `Module` is a feed-forward neural networ... | allennlp-master | allennlp/modules/feedforward.py |
"""
Custom PyTorch
`Module <https://pytorch.org/docs/master/nn.html#torch.nn.Module>`_ s
that are used as components in AllenNLP `Model` s.
"""
from allennlp.modules.attention import Attention
from allennlp.modules.bimpm_matching import BiMpmMatching
from allennlp.modules.conditional_random_field import ConditionalRan... | allennlp-master | allennlp/modules/__init__.py |
# https://github.com/tensorflow/tensorflow/blob/r1.4/tensorflow/python/ops/nn_impl.py#L885
from typing import Set, Tuple
import numpy as np
import torch
from allennlp.common.checks import ConfigurationError
from allennlp.nn import util
def _choice(num_words: int, num_samples: int) -> Tuple[np.ndarray, int]:
""... | allennlp-master | allennlp/modules/sampled_softmax_loss.py |
import torch
class ResidualWithLayerDropout(torch.nn.Module):
"""
A residual connection with the layer dropout technique [Deep Networks with Stochastic
Depth](https://arxiv.org/pdf/1603.09382.pdf).
This module accepts the input and output of a layer, decides whether this layer should
be stochasti... | allennlp-master | allennlp/modules/residual_with_layer_dropout.py |
"""
Multi-perspective matching layer
"""
from typing import Tuple, List
import torch
import torch.nn as nn
import torch.nn.functional as F
from allennlp.common.checks import ConfigurationError
from allennlp.common.registrable import FromParams
from allennlp.nn.util import (
get_lengths_from_binary_sequence_mask,... | allennlp-master | allennlp/modules/bimpm_matching.py |
"""
Conditional random field
"""
from typing import List, Tuple, Dict, Union
import torch
from allennlp.common.checks import ConfigurationError
import allennlp.nn.util as util
VITERBI_DECODING = Tuple[List[int], float] # a list of tags, and a viterbi score
def allowed_transitions(constraint_type: str, labels: Dic... | allennlp-master | allennlp/modules/conditional_random_field.py |
from typing import Optional, Tuple, List
import torch
from torch.nn.utils.rnn import PackedSequence, pack_padded_sequence, pad_packed_sequence
from allennlp.modules.augmented_lstm import AugmentedLstm
from allennlp.modules.input_variational_dropout import InputVariationalDropout
from allennlp.common.checks import Confi... | allennlp-master | allennlp/modules/stacked_bidirectional_lstm.py |
"""
A [Highway layer](https://arxiv.org/abs/1505.00387) that does a gated combination of a linear
transformation and a non-linear transformation of its input.
"""
from typing import Callable
import torch
from overrides import overrides
class Highway(torch.nn.Module):
"""
A [Highway layer](https://arxiv.org/... | allennlp-master | allennlp/modules/highway.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 `(... | allennlp-master | allennlp/modules/input_variational_dropout.py |
import torch
from allennlp.nn import util
class MaskedLayerNorm(torch.nn.Module):
"""
See LayerNorm for details.
Note, however, that unlike LayerNorm this norm includes a batch component.
"""
def __init__(self, size: int, gamma0: float = 0.1) -> None:
super().__init__()
self.gam... | allennlp-master | allennlp/modules/masked_layer_norm.py |
"""
A stacked bidirectional LSTM with skip connections between layers.
"""
import warnings
from typing import List, Optional, Tuple, Any
import numpy
import torch
from torch.nn.utils.rnn import PackedSequence, pad_packed_sequence
from allennlp.common.checks import ConfigurationError
from allennlp.common.file_utils im... | allennlp-master | allennlp/modules/elmo_lstm.py |
"""
An LSTM with Recurrent Dropout, a hidden_state which is projected and
clipping on both the hidden state and the memory state of the LSTM.
"""
from typing import Optional, Tuple, List
import torch
from allennlp.nn.util import get_dropout_mask
from allennlp.nn.initializers import block_orthogonal
class LstmCellW... | allennlp-master | allennlp/modules/lstm_cell_with_projection.py |
"""
An LSTM with Recurrent Dropout and the option to use highway
connections between layers.
Based on PyText version (that was based on a previous AllenNLP version)
"""
from typing import Optional, Tuple
import torch
from allennlp.common.checks import ConfigurationError
from torch.nn.utils.rnn import PackedSequence, ... | allennlp-master | allennlp/modules/augmented_lstm.py |
import torch
from allennlp.nn import util
class LayerNorm(torch.nn.Module):
"""
An implementation of [Layer Normalization](
https://www.semanticscholar.org/paper/Layer-Normalization-Ba-Kiros/97fb4e3d45bb098e27e0071448b6152217bd35a5).
Layer Normalization stabilises the training of deep neural networ... | allennlp-master | allennlp/modules/layer_norm.py |
import torch
from allennlp.nn import Activation
class GatedSum(torch.nn.Module):
"""
This `Module` represents a gated sum of two tensors `a` and `b`. Specifically:
```
f = activation(W [a; b])
out = f * a + (1 - f) * b
```
# Parameters
input_dim : `int`, required
The dimensi... | allennlp-master | allennlp/modules/gated_sum.py |
from overrides import overrides
import torch
from typing import List
from allennlp.modules.seq2seq_encoders.seq2seq_encoder import Seq2SeqEncoder
@Seq2SeqEncoder.register("compose")
class ComposeEncoder(Seq2SeqEncoder):
"""This class can be used to compose several encoders in sequence.
Among other things, ... | allennlp-master | allennlp/modules/seq2seq_encoders/compose_encoder.py |
from allennlp.modules.encoder_base import _EncoderBase
from allennlp.common import Registrable
class Seq2SeqEncoder(_EncoderBase, Registrable):
"""
A `Seq2SeqEncoder` is a `Module` that takes as input a sequence of vectors and returns a
modified sequence of vectors. Input shape : `(batch_size, sequence_l... | allennlp-master | allennlp/modules/seq2seq_encoders/seq2seq_encoder.py |
from overrides import overrides
import torch
from torch.nn.utils.rnn import pad_packed_sequence
from allennlp.common.checks import ConfigurationError
from allennlp.modules.augmented_lstm import AugmentedLstm
from allennlp.modules.seq2seq_encoders.seq2seq_encoder import Seq2SeqEncoder
from allennlp.modules.stacked_alte... | allennlp-master | allennlp/modules/seq2seq_encoders/pytorch_seq2seq_wrapper.py |
import torch
from overrides import overrides
from allennlp.modules.feedforward import FeedForward
from allennlp.modules.seq2seq_encoders.seq2seq_encoder import Seq2SeqEncoder
@Seq2SeqEncoder.register("feedforward")
class FeedForwardEncoder(Seq2SeqEncoder):
"""
This class applies the `FeedForward` to each ite... | allennlp-master | allennlp/modules/seq2seq_encoders/feedforward_encoder.py |
from overrides import overrides
import torch
from allennlp.modules.seq2seq_encoders.seq2seq_encoder import Seq2SeqEncoder
@Seq2SeqEncoder.register("pass_through")
class PassThroughEncoder(Seq2SeqEncoder):
"""
This class allows you to specify skipping a `Seq2SeqEncoder` just
by changing a configuration fi... | allennlp-master | allennlp/modules/seq2seq_encoders/pass_through_encoder.py |
"""
Modules that transform a sequence of input vectors
into a sequence of output vectors.
Some are just basic wrappers around existing PyTorch modules,
others are AllenNLP modules.
The available Seq2Seq encoders are
- `"gru"` : allennlp.modules.seq2seq_encoders.GruSeq2SeqEncoder
- `"lstm"` : allennlp.modules.seq2seq_... | allennlp-master | allennlp/modules/seq2seq_encoders/__init__.py |
from typing import Optional
from overrides import overrides
import torch
from torch import nn
from allennlp.modules.seq2seq_encoders.seq2seq_encoder import Seq2SeqEncoder
from allennlp.nn.util import add_positional_features
@Seq2SeqEncoder.register("pytorch_transformer")
class PytorchTransformer(Seq2SeqEncoder):
... | allennlp-master | allennlp/modules/seq2seq_encoders/pytorch_transformer_wrapper.py |
from typing import Sequence, List
import math
import torch
from allennlp.common.checks import ConfigurationError
from allennlp.modules.seq2seq_encoders.seq2seq_encoder import Seq2SeqEncoder
class ResidualBlock(torch.nn.Module):
def __init__(
self,
input_dim: int,
layers: Sequence[Sequenc... | allennlp-master | allennlp/modules/seq2seq_encoders/gated_cnn_encoder.py |
"""
An *attention* module that computes the similarity between
an input vector and the rows of a matrix.
"""
import torch
from overrides import overrides
from allennlp.common.registrable import Registrable
from allennlp.nn.util import masked_softmax
class Attention(torch.nn.Module, Registrable):
"""
An `Att... | allennlp-master | allennlp/modules/attention/attention.py |
from overrides import overrides
import torch
from torch.nn.parameter import Parameter
from allennlp.modules.attention.attention import Attention
from allennlp.nn import Activation
@Attention.register("bilinear")
class BilinearAttention(Attention):
"""
Computes attention between a vector and a matrix using a ... | allennlp-master | allennlp/modules/attention/bilinear_attention.py |
from allennlp.modules.attention.attention import Attention
from allennlp.modules.attention.bilinear_attention import BilinearAttention
from allennlp.modules.attention.additive_attention import AdditiveAttention
from allennlp.modules.attention.cosine_attention import CosineAttention
from allennlp.modules.attention.dot_p... | allennlp-master | allennlp/modules/attention/__init__.py |
import torch
from overrides import overrides
from allennlp.modules.attention.attention import Attention
@Attention.register("dot_product")
class DotProductAttention(Attention):
"""
Computes attention between a vector and a matrix using dot product.
Registered as an `Attention` with name "dot_product".
... | allennlp-master | allennlp/modules/attention/dot_product_attention.py |
import torch
from overrides import overrides
from allennlp.modules.attention.attention import Attention
from allennlp.nn import util
@Attention.register("cosine")
class CosineAttention(Attention):
"""
Computes attention between a vector and a matrix using cosine similarity.
Registered as an `Attention` w... | allennlp-master | allennlp/modules/attention/cosine_attention.py |
import math
import torch
from torch.nn import Parameter
from overrides import overrides
from allennlp.modules.attention.attention import Attention
from allennlp.nn import util
from allennlp.nn.activations import Activation
@Attention.register("linear")
class LinearAttention(Attention):
"""
This `Attention` m... | allennlp-master | allennlp/modules/attention/linear_attention.py |
from overrides import overrides
import torch
from torch.nn.parameter import Parameter
from allennlp.modules.attention.attention import Attention
@Attention.register("additive")
class AdditiveAttention(Attention):
"""
Computes attention between a vector and a matrix using an additive attention function. This... | allennlp-master | allennlp/modules/attention/additive_attention.py |
from typing import Dict
import inspect
import torch
from overrides import overrides
from allennlp.common.checks import ConfigurationError
from allennlp.data import TextFieldTensors
from allennlp.modules.text_field_embedders.text_field_embedder import TextFieldEmbedder
from allennlp.modules.time_distributed import Tim... | allennlp-master | allennlp/modules/text_field_embedders/basic_text_field_embedder.py |
"""
A `TextFieldEmbedder` is a `Module` that takes as input the `dict` of NumPy arrays
produced by a `TextField` and returns as output an embedded representation of the tokens in that field.
"""
from allennlp.modules.text_field_embedders.text_field_embedder import TextFieldEmbedder
from allennlp.modules.text_field_emb... | allennlp-master | allennlp/modules/text_field_embedders/__init__.py |
import torch
from allennlp.common import Registrable
from allennlp.data import TextFieldTensors
class TextFieldEmbedder(torch.nn.Module, Registrable):
"""
A `TextFieldEmbedder` is a `Module` that takes as input the
[`DataArray`](../../data/fields/text_field.md) produced by a [`TextField`](../../data/fiel... | allennlp-master | allennlp/modules/text_field_embedders/text_field_embedder.py |
from overrides import overrides
import torch
from allennlp.modules.seq2vec_encoders.seq2vec_encoder import Seq2VecEncoder
from allennlp.nn.util import get_lengths_from_binary_sequence_mask
@Seq2VecEncoder.register("boe")
@Seq2VecEncoder.register("bag_of_embeddings")
class BagOfEmbeddingsEncoder(Seq2VecEncoder):
... | allennlp-master | allennlp/modules/seq2vec_encoders/boe_encoder.py |
from typing import Sequence, Dict, List, Callable
import torch
import numpy as np
from allennlp.common.checks import ConfigurationError
from allennlp.modules.layer_norm import LayerNorm
from allennlp.modules.highway import Highway
from allennlp.modules.seq2vec_encoders.seq2vec_encoder import Seq2VecEncoder
_VALID_PR... | allennlp-master | allennlp/modules/seq2vec_encoders/cnn_highway_encoder.py |
from overrides import overrides
import torch.nn
from allennlp.modules.seq2vec_encoders.seq2vec_encoder import Seq2VecEncoder
from allennlp.nn.util import get_final_encoder_states
@Seq2VecEncoder.register("cls_pooler")
class ClsPooler(Seq2VecEncoder):
"""
Just takes the first vector from a list of vectors (w... | allennlp-master | allennlp/modules/seq2vec_encoders/cls_pooler.py |
from allennlp.modules.encoder_base import _EncoderBase
from allennlp.common import Registrable
class Seq2VecEncoder(_EncoderBase, Registrable):
"""
A `Seq2VecEncoder` is a `Module` that takes as input a sequence of vectors and returns a
single vector. Input shape : `(batch_size, sequence_length, input_di... | allennlp-master | allennlp/modules/seq2vec_encoders/seq2vec_encoder.py |
from typing import Optional, Tuple
from overrides import overrides
import torch
from torch.nn import Conv1d, Linear
from allennlp.modules.seq2vec_encoders.seq2vec_encoder import Seq2VecEncoder
from allennlp.nn import Activation
from allennlp.nn.util import min_value_of_dtype
@Seq2VecEncoder.register("cnn")
class Cn... | allennlp-master | allennlp/modules/seq2vec_encoders/cnn_encoder.py |
from typing import Optional, Dict, Any
from overrides import overrides
import torch
import torch.nn
from allennlp.modules.seq2vec_encoders.seq2vec_encoder import Seq2VecEncoder
@Seq2VecEncoder.register("bert_pooler")
class BertPooler(Seq2VecEncoder):
"""
The pooling layer at the end of the BERT model. This... | allennlp-master | allennlp/modules/seq2vec_encoders/bert_pooler.py |
"""
Modules that transform a sequence of input vectors
into a single output vector.
Some are just basic wrappers around existing PyTorch modules,
others are AllenNLP modules.
The available Seq2Vec encoders are
* `"gru"` https://pytorch.org/docs/master/nn.html#torch.nn.GRU
* `"lstm"` https://pytorch.org/docs/master/nn... | allennlp-master | allennlp/modules/seq2vec_encoders/__init__.py |
import torch
from allennlp.common.checks import ConfigurationError
from allennlp.modules.augmented_lstm import AugmentedLstm
from allennlp.modules.seq2vec_encoders.seq2vec_encoder import Seq2VecEncoder
from allennlp.modules.stacked_alternating_lstm import StackedAlternatingLstm
from allennlp.modules.stacked_bidirectio... | allennlp-master | allennlp/modules/seq2vec_encoders/pytorch_seq2vec_wrapper.py |
import torch
from overrides import overrides
from allennlp.modules.span_extractors.span_extractor import SpanExtractor
from allennlp.modules.time_distributed import TimeDistributed
from allennlp.nn import util
@SpanExtractor.register("self_attentive")
class SelfAttentiveSpanExtractor(SpanExtractor):
"""
Comp... | allennlp-master | allennlp/modules/span_extractors/self_attentive_span_extractor.py |
from typing import Optional
import torch
from overrides import overrides
from torch.nn.parameter import Parameter
from allennlp.common.checks import ConfigurationError
from allennlp.modules.span_extractors.span_extractor import SpanExtractor
from allennlp.modules.token_embedders.embedding import Embedding
from allenn... | allennlp-master | allennlp/modules/span_extractors/bidirectional_endpoint_span_extractor.py |
from typing import Optional
import torch
from torch.nn.parameter import Parameter
from overrides import overrides
from allennlp.modules.span_extractors.span_extractor import SpanExtractor
from allennlp.modules.token_embedders.embedding import Embedding
from allennlp.nn import util
from allennlp.common.checks import C... | allennlp-master | allennlp/modules/span_extractors/endpoint_span_extractor.py |
from allennlp.modules.span_extractors.span_extractor import SpanExtractor
from allennlp.modules.span_extractors.endpoint_span_extractor import EndpointSpanExtractor
from allennlp.modules.span_extractors.self_attentive_span_extractor import (
SelfAttentiveSpanExtractor,
)
from allennlp.modules.span_extractors.bidire... | allennlp-master | allennlp/modules/span_extractors/__init__.py |
import torch
from overrides import overrides
from allennlp.common.registrable import Registrable
class SpanExtractor(torch.nn.Module, Registrable):
"""
Many NLP models deal with representations of spans inside a sentence.
SpanExtractors define methods for extracting and representing spans
from a sent... | allennlp-master | allennlp/modules/span_extractors/span_extractor.py |
import math
import torch
from torch.nn import Parameter
from overrides import overrides
from allennlp.nn import util
from allennlp.nn.activations import Activation
from allennlp.modules.matrix_attention.matrix_attention import MatrixAttention
@MatrixAttention.register("linear")
class LinearMatrixAttention(MatrixAtt... | allennlp-master | allennlp/modules/matrix_attention/linear_matrix_attention.py |
from overrides import overrides
import torch
from torch.nn.parameter import Parameter
from allennlp.modules.matrix_attention.matrix_attention import MatrixAttention
from allennlp.nn import Activation
@MatrixAttention.register("bilinear")
class BilinearMatrixAttention(MatrixAttention):
"""
Computes attention ... | allennlp-master | allennlp/modules/matrix_attention/bilinear_matrix_attention.py |
import torch
from overrides import overrides
from allennlp.modules.matrix_attention.matrix_attention import MatrixAttention
@MatrixAttention.register("dot_product")
class DotProductMatrixAttention(MatrixAttention):
"""
Computes attention between every entry in matrix_1 with every entry in matrix_2 using a do... | allennlp-master | allennlp/modules/matrix_attention/dot_product_matrix_attention.py |
import torch
from allennlp.common.registrable import Registrable
class MatrixAttention(torch.nn.Module, Registrable):
"""
`MatrixAttention` takes two matrices as input and returns a matrix of attentions.
We compute the similarity between each row in each matrix and return unnormalized similarity
sco... | allennlp-master | allennlp/modules/matrix_attention/matrix_attention.py |
from allennlp.modules.matrix_attention.matrix_attention import MatrixAttention
from allennlp.modules.matrix_attention.bilinear_matrix_attention import BilinearMatrixAttention
from allennlp.modules.matrix_attention.cosine_matrix_attention import CosineMatrixAttention
from allennlp.modules.matrix_attention.dot_product_ma... | allennlp-master | allennlp/modules/matrix_attention/__init__.py |
import torch
from overrides import overrides
from allennlp.modules.matrix_attention.matrix_attention import MatrixAttention
from allennlp.nn import util
@MatrixAttention.register("cosine")
class CosineMatrixAttention(MatrixAttention):
"""
Computes attention between every entry in matrix_1 with every entry in... | allennlp-master | allennlp/modules/matrix_attention/cosine_matrix_attention.py |
import math
from typing import Optional, Tuple, Dict, Any
from overrides import overrides
import torch
import torch.nn.functional as F
from transformers import XLNetConfig
from allennlp.data.tokenizers import PretrainedTransformerTokenizer
from allennlp.modules.scalar_mix import ScalarMix
from allennlp.modules.token... | allennlp-master | allennlp/modules/token_embedders/pretrained_transformer_embedder.py |
from typing import Optional, Dict, Any
from overrides import overrides
import torch
from allennlp.modules.token_embedders import PretrainedTransformerEmbedder, TokenEmbedder
from allennlp.nn import util
@TokenEmbedder.register("pretrained_transformer_mismatched")
class PretrainedTransformerMismatchedEmbedder(TokenE... | allennlp-master | allennlp/modules/token_embedders/pretrained_transformer_mismatched_embedder.py |
import io
import itertools
import logging
import re
import tarfile
import warnings
import zipfile
from typing import Any, cast, Iterator, NamedTuple, Optional, Sequence, Tuple, BinaryIO
import numpy
import torch
from overrides import overrides
from torch.nn.functional import embedding
from allennlp.common import Tqdm... | allennlp-master | allennlp/modules/token_embedders/embedding.py |
import torch
from allennlp.modules.token_embedders.embedding import Embedding
from allennlp.modules.seq2vec_encoders.seq2vec_encoder import Seq2VecEncoder
from allennlp.modules.time_distributed import TimeDistributed
from allennlp.modules.token_embedders.token_embedder import TokenEmbedder
@TokenEmbedder.register("c... | allennlp-master | allennlp/modules/token_embedders/token_characters_encoder.py |
"""
A `TokenEmbedder` is a `Module` that
embeds one-hot-encoded tokens as vectors.
"""
from allennlp.modules.token_embedders.token_embedder import TokenEmbedder
from allennlp.modules.token_embedders.embedding import Embedding
from allennlp.modules.token_embedders.token_characters_encoder import TokenCharactersEncoder
... | allennlp-master | allennlp/modules/token_embedders/__init__.py |
import torch
from allennlp.modules.token_embedders.token_embedder import TokenEmbedder
@TokenEmbedder.register("pass_through")
class PassThroughTokenEmbedder(TokenEmbedder):
"""
Assumes that the input is already vectorized in some way,
and just returns it.
Registered as a `TokenEmbedder` with name "p... | allennlp-master | allennlp/modules/token_embedders/pass_through_token_embedder.py |
import torch
from allennlp.modules.token_embedders.token_embedder import TokenEmbedder
@TokenEmbedder.register("empty")
class EmptyEmbedder(TokenEmbedder):
"""
Assumes you want to completely ignore the output of a `TokenIndexer` for some reason, and does
not return anything when asked to embed it.
Yo... | allennlp-master | allennlp/modules/token_embedders/empty_embedder.py |
import torch
from allennlp.common.checks import ConfigurationError
from allennlp.data import Vocabulary
from allennlp.modules.token_embedders.token_embedder import TokenEmbedder
from allennlp.nn.util import get_text_field_mask
@TokenEmbedder.register("bag_of_word_counts")
class BagOfWordCountsTokenEmbedder(TokenEmbe... | allennlp-master | allennlp/modules/token_embedders/bag_of_word_counts_token_embedder.py |
from typing import List
import torch
from allennlp.modules.token_embedders.token_embedder import TokenEmbedder
from allennlp.modules.elmo import Elmo
from allennlp.modules.time_distributed import TimeDistributed
@TokenEmbedder.register("elmo_token_embedder")
class ElmoTokenEmbedder(TokenEmbedder):
"""
Comput... | allennlp-master | allennlp/modules/token_embedders/elmo_token_embedder.py |
import torch
from allennlp.common import Registrable
class TokenEmbedder(torch.nn.Module, Registrable):
"""
A `TokenEmbedder` is a `Module` that takes as input a tensor with integer ids that have
been output from a [`TokenIndexer`](/api/data/token_indexers/token_indexer.md) and outputs
a vector per t... | allennlp-master | allennlp/modules/token_embedders/token_embedder.py |
from typing import Dict, MutableMapping, Mapping
from allennlp.data.fields.field import DataArray, Field
from allennlp.data.vocabulary import Vocabulary
class Instance(Mapping[str, Field]):
"""
An `Instance` is a collection of :class:`~allennlp.data.fields.field.Field` objects,
specifying the inputs and ... | allennlp-master | allennlp/data/instance.py |
"""
A :class:`Batch` represents a collection of `Instance` s to be fed
through a model.
"""
import logging
from collections import defaultdict
from typing import Dict, Iterable, Iterator, List, Union
import numpy
import torch
from allennlp.common.checks import ConfigurationError
from allennlp.common.util import ensu... | allennlp-master | allennlp/data/batch.py |
from allennlp.data.dataloader import DataLoader, PyTorchDataLoader, allennlp_collate
from allennlp.data.dataset_readers.dataset_reader import (
DatasetReader,
AllennlpDataset,
AllennlpLazyDataset,
)
from allennlp.data.fields.field import DataArray, Field
from allennlp.data.fields.text_field import TextField... | allennlp-master | allennlp/data/__init__.py |
from typing import List, Dict, Union, Iterator
import torch
from torch.utils import data
from allennlp.common.registrable import Registrable
from allennlp.common.lazy import Lazy
from allennlp.data.instance import Instance
from allennlp.data.batch import Batch
from allennlp.data.samplers import Sampler, BatchSampler
... | allennlp-master | allennlp/data/dataloader.py |
"""
A Vocabulary maps strings to integers, allowing for strings to be mapped to an
out-of-vocabulary token.
"""
import codecs
import copy
import logging
import os
import re
from collections import defaultdict
from typing import Any, Callable, Dict, Iterable, List, Optional, Set, Union, TYPE_CHECKING
from filelock imp... | allennlp-master | allennlp/data/vocabulary.py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.