python_code
stringlengths
0
290k
repo_name
stringclasses
30 values
file_path
stringlengths
6
125
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
from typing import List from overrides import overrides import spacy from allennlp.common import Registrable from allennlp.common.util import get_spacy_model class SentenceSplitter(Registrable): """ A `SentenceSplitter` splits strings into sentences. """ default_implementation = "spacy" def sp...
allennlp-master
allennlp/data/tokenizers/sentence_splitter.py
import copy import logging from typing import Any, Dict, List, Optional, Tuple, Iterable from overrides import overrides from transformers import PreTrainedTokenizer from allennlp.common.util import sanitize_wordpiece from allennlp.data.tokenizers.token_class import Token from allennlp.data.tokenizers.tokenizer impor...
allennlp-master
allennlp/data/tokenizers/pretrained_transformer_tokenizer.py
""" This module contains various classes for performing tokenization. """ from allennlp.data.tokenizers.token_class import Token from allennlp.data.tokenizers.tokenizer import Tokenizer from allennlp.data.tokenizers.spacy_tokenizer import SpacyTokenizer from allennlp.data.tokenizers.letters_digits_tokenizer import Let...
allennlp-master
allennlp/data/tokenizers/__init__.py
from typing import List, Optional from overrides import overrides import spacy from spacy.tokens import Doc from allennlp.common.util import get_spacy_model from allennlp.data.tokenizers.token_class import Token from allennlp.data.tokenizers.tokenizer import Tokenizer @Tokenizer.register("spacy") class SpacyTokeniz...
allennlp-master
allennlp/data/tokenizers/spacy_tokenizer.py
from typing import List, Optional import logging from allennlp.common import Registrable from allennlp.data.tokenizers.token_class import Token logger = logging.getLogger(__name__) class Tokenizer(Registrable): """ A `Tokenizer` splits strings of text into tokens. Typically, this either splits text into ...
allennlp-master
allennlp/data/tokenizers/tokenizer.py
from typing import List from overrides import overrides from allennlp.data.tokenizers.token_class import Token from allennlp.data.tokenizers.tokenizer import Tokenizer @Tokenizer.register("whitespace") @Tokenizer.register("just_spaces") class WhitespaceTokenizer(Tokenizer): """ A `Tokenizer` that assumes yo...
allennlp-master
allennlp/data/tokenizers/whitespace_tokenizer.py
import re from typing import List from overrides import overrides from allennlp.data.tokenizers.token_class import Token from allennlp.data.tokenizers.tokenizer import Tokenizer @Tokenizer.register("letters_digits") class LettersDigitsTokenizer(Tokenizer): """ A `Tokenizer` which keeps runs of (unicode) let...
allennlp-master
allennlp/data/tokenizers/letters_digits_tokenizer.py
from typing import List, Union from overrides import overrides from allennlp.data.tokenizers.token_class import Token from allennlp.data.tokenizers.tokenizer import Tokenizer @Tokenizer.register("character") class CharacterTokenizer(Tokenizer): """ A `CharacterTokenizer` splits strings into character tokens...
allennlp-master
allennlp/data/tokenizers/character_tokenizer.py
from dataclasses import dataclass from typing import Optional @dataclass(init=False, repr=False) class Token: """ A simple token representation, keeping track of the token's text, offset in the passage it was taken from, POS tag, dependency relation, and similar information. These fields match spacy's ...
allennlp-master
allennlp/data/tokenizers/token_class.py
from typing import Dict, List, Sequence, Iterable import itertools import logging from overrides import overrides from allennlp.common.checks import ConfigurationError from allennlp.common.file_utils import cached_path from allennlp.data.dataset_readers.dataset_reader import DatasetReader from allennlp.data.dataset_r...
allennlp-master
allennlp/data/dataset_readers/conll2003.py
from typing import Dict, Mapping, Iterable import json from allennlp.common.checks import ConfigurationError from allennlp.data.dataset_readers.dataset_reader import DatasetReader from allennlp.data.fields import MetadataField from allennlp.data.instance import Instance _VALID_SCHEMES = {"round_robin", "all_at_once"}...
allennlp-master
allennlp/data/dataset_readers/interleaving_dataset_reader.py
import logging from typing import Dict, List from overrides import overrides from allennlp.common.file_utils import cached_path from allennlp.data.dataset_readers.dataset_reader import DatasetReader from allennlp.data.instance import Instance from allennlp.data.fields import Field, TextField, ListField, IndexField fr...
allennlp-master
allennlp/data/dataset_readers/babi.py
from typing import Dict, List import logging from overrides import overrides from allennlp.common.file_utils import cached_path from allennlp.data.dataset_readers.dataset_reader import DatasetReader from allennlp.data.fields import TextField, SequenceLabelField, MetadataField, Field from allennlp.data.instance import...
allennlp-master
allennlp/data/dataset_readers/sequence_tagging.py
""" A :class:`~allennlp.data.dataset_readers.dataset_reader.DatasetReader` reads a file and converts it to a collection of :class:`~allennlp.data.instance.Instance` s. The various subclasses know how to read specific filetypes and produce datasets in the formats required by specific models. """ from allennlp.data.dat...
allennlp-master
allennlp/data/dataset_readers/__init__.py
from typing import Dict, List, Union import logging import json from overrides import overrides from allennlp.common.file_utils import cached_path from allennlp.data.dataset_readers.dataset_reader import DatasetReader from allennlp.data.fields import LabelField, TextField, Field, ListField from allennlp.data.instance i...
allennlp-master
allennlp/data/dataset_readers/text_classification_json.py