python_code
stringlengths
0
290k
repo_name
stringclasses
30 values
file_path
stringlengths
6
125
from setuptools import find_packages, setup # PEP0440 compatible formatted version, see: # https://www.python.org/dev/peps/pep-0440/ # # release markers: # X.Y # X.Y.Z # For bugfix releases # # pre-release markers: # X.YaN # Alpha release # X.YbN # Beta release # X.YrcN # Release Candidate # X.Y ...
allennlp-master
setup.py
allennlp-master
test_fixtures/__init__.py
from d.d import D
allennlp-master
test_fixtures/plugins/d/__init__.py
import argparse from overrides import overrides from allennlp.commands import Subcommand def do_nothing(_): pass @Subcommand.register("d") class D(Subcommand): @overrides def add_subparser(self, parser: argparse._SubParsersAction) -> argparse.ArgumentParser: subparser = parser.add_parser(self....
allennlp-master
test_fixtures/plugins/d/d.py
import os _MAJOR = "1" _MINOR = "3" # On master and in a nightly release the patch should be one ahead of the last # released build. _PATCH = "0" # This is mainly for nightly builds which have the suffix ".dev$DATE". See # https://semver.org/#is-v123-a-semantic-version for the semantics. _SUFFIX = os.environ.get("ALLE...
allennlp-master
allennlp/version.py
# Make sure that allennlp is running on Python 3.6.1 or later # (to avoid running into this bug: https://bugs.python.org/issue29246) import sys if sys.version_info < (3, 6, 1): raise RuntimeError("AllenNLP requires Python 3.6.1 or later") # We get a lot of these spurious warnings, # see https://github.com/Continu...
allennlp-master
allennlp/__init__.py
#!/usr/bin/env python import logging import os import sys if os.environ.get("ALLENNLP_DEBUG"): LEVEL = logging.DEBUG else: level_name = os.environ.get("ALLENNLP_LOG_LEVEL", "INFO") LEVEL = logging._nameToLevel.get(level_name, logging.INFO) sys.path.insert(0, os.path.dirname(os.path.abspath(os.path.join(__...
allennlp-master
allennlp/__main__.py
allennlp-master
allennlp/tools/__init__.py
import os from allennlp.common.file_utils import CACHE_DIRECTORY from allennlp.common.file_utils import filename_to_url def main(): print(f"Looking for datasets in {CACHE_DIRECTORY}...") if not os.path.exists(CACHE_DIRECTORY): print("Directory does not exist.") print("No cached datasets found...
allennlp-master
allennlp/tools/inspect_cache.py
#! /usr/bin/env python """ Helper script for modifying config.json files that are locked inside model.tar.gz archives. This is useful if you need to rename things or add or remove values, usually because of changes to the library. This script will untar the archive to a temp directory, launch an editor to modify the c...
allennlp-master
allennlp/tools/archive_surgery.py
import argparse import gzip import os import torch from allennlp.common.checks import ConfigurationError from allennlp.data import Token, Vocabulary from allennlp.data.token_indexers import ELMoTokenCharactersIndexer from allennlp.data.vocabulary import DEFAULT_OOV_TOKEN from allennlp.modules.elmo import _ElmoCharact...
allennlp-master
allennlp/tools/create_elmo_embeddings_from_vocab.py
""" Assorted utilities for working with neural networks in AllenNLP. """ import copy import json import logging from collections import defaultdict from typing import Any, Dict, List, Optional, Sequence, Tuple, TypeVar, Union import math import numpy import torch from allennlp.common.checks import ConfigurationError...
allennlp-master
allennlp/nn/util.py
""" An `Activation` is just a function that takes some parameters and returns an element-wise activation function. For the most part we just use [PyTorch activations](https://pytorch.org/docs/master/nn.html#non-linear-activations). Here we provide a thin wrapper to allow registering them and instantiating them `from_pa...
allennlp-master
allennlp/nn/activations.py
from allennlp.nn.activations import Activation from allennlp.nn.initializers import Initializer, InitializerApplicator from allennlp.nn.regularizers import RegularizerApplicator
allennlp-master
allennlp/nn/__init__.py
from inspect import signature from typing import List, Callable, Tuple, Dict, cast, TypeVar import warnings from overrides import overrides import torch from allennlp.common import FromParams, Registrable from allennlp.common.checks import ConfigurationError from allennlp.nn.util import min_value_of_dtype StateType...
allennlp-master
allennlp/nn/beam_search.py
""" An initializer is just a PyTorch function. Here we implement a proxy class that allows us to register them and supply any additional function arguments (for example, the `mean` and `std` of a normal initializer) as named arguments to the constructor. The available initialization functions are * ["normal"](https:/...
allennlp-master
allennlp/nn/initializers.py
from typing import List, Set, Tuple, Dict import numpy from allennlp.common.checks import ConfigurationError def decode_mst( energy: numpy.ndarray, length: int, has_labels: bool = True ) -> Tuple[numpy.ndarray, numpy.ndarray]: """ Note: Counter to typical intuition, this function decodes the _maximum_ ...
allennlp-master
allennlp/nn/chu_liu_edmonds.py
import re from typing import List, Tuple import torch from allennlp.common import FromParams from allennlp.nn.regularizers.regularizer import Regularizer class RegularizerApplicator(FromParams): """ Applies regularizers to the parameters of a Module based on regex matches. """ def __init__(self, re...
allennlp-master
allennlp/nn/regularizers/regularizer_applicator.py
""" This module contains classes representing regularization schemes as well as a class for applying regularization to parameters. """ from allennlp.nn.regularizers.regularizer import Regularizer from allennlp.nn.regularizers.regularizers import L1Regularizer from allennlp.nn.regularizers.regularizers import L2Regular...
allennlp-master
allennlp/nn/regularizers/__init__.py
import torch from allennlp.nn.regularizers.regularizer import Regularizer @Regularizer.register("l1") class L1Regularizer(Regularizer): """ Represents a penalty proportional to the sum of the absolute values of the parameters Registered as a `Regularizer` with name "l1". """ def __init__(self, ...
allennlp-master
allennlp/nn/regularizers/regularizers.py
import torch from allennlp.common import Registrable class Regularizer(Registrable): """ An abstract class representing a regularizer. It must implement call, returning a scalar tensor. """ default_implementation = "l2" def __call__(self, parameter: torch.Tensor) -> torch.Tensor: ra...
allennlp-master
allennlp/nn/regularizers/regularizer.py
from typing import Optional, Iterable, Dict, Any from allennlp.common.checks import ConfigurationError class MetricTracker: """ This class tracks a metric during training for the dual purposes of early stopping and for knowing whether the current value is the best so far. It mimics the PyTorch `state...
allennlp-master
allennlp/training/metric_tracker.py
import os from contextlib import contextmanager from typing import Any, Dict, Iterator, Tuple from allennlp.models import Model from allennlp.training.checkpointer import Checkpointer from allennlp.training.trainer import Trainer @Trainer.register("no_op") class NoOpTrainer(Trainer): """ Registered as a `Tra...
allennlp-master
allennlp/training/no_op_trainer.py
""" Helper functions for Trainers """ import datetime import logging import os import shutil import json from os import PathLike from typing import Any, Dict, Iterable, Optional, Union, Tuple, Set, List, TYPE_CHECKING from collections import Counter import torch # import torch.distributed as dist from torch.utils.dat...
allennlp-master
allennlp/training/util.py
from typing import Iterable, Tuple, Optional import torch from allennlp.common.registrable import Registrable NamedParameter = Tuple[str, torch.Tensor] class MovingAverage(Registrable): """ Tracks a moving average of model parameters. """ default_implementation = "exponential" def __init__(se...
allennlp-master
allennlp/training/moving_average.py
from typing import Union, Dict, Any, List, Tuple, Optional import logging import os import re import shutil import time import torch import allennlp from allennlp.common import Registrable from allennlp.nn import util as nn_util from allennlp.training import util as training_util logger = logging.getLogger(__name__...
allennlp-master
allennlp/training/checkpointer.py
from allennlp.training.checkpointer import Checkpointer from allennlp.training.tensorboard_writer import TensorboardWriter from allennlp.training.no_op_trainer import NoOpTrainer from allennlp.training.trainer import ( Trainer, GradientDescentTrainer, BatchCallback, EpochCallback, TrainerCallback, ...
allennlp-master
allennlp/training/__init__.py
""" AllenNLP just uses [PyTorch optimizers](https://pytorch.org/docs/master/optim.html), with a thin wrapper to allow registering them and instantiating them `from_params`. The available optimizers are * [adadelta](https://pytorch.org/docs/master/optim.html#torch.optim.Adadelta) * [adagrad](https://pytorch.org/docs/m...
allennlp-master
allennlp/training/optimizers.py
from typing import Dict, Any import torch class Scheduler: """ A `Scheduler` is a generalization of PyTorch learning rate schedulers. A scheduler can be used to update any field in an optimizer's parameter groups, not just the learning rate. During training using the AllenNLP `Trainer`, this is...
allennlp-master
allennlp/training/scheduler.py
import datetime import logging import math import os import re import time import traceback from contextlib import contextmanager from typing import Any, Callable, Dict, Iterator, List, Optional, Tuple, Type, Union from allennlp.common.util import int_to_device import torch import torch.distributed as dist from torch...
allennlp-master
allennlp/training/trainer.py
from typing import Any, Callable, Dict, List, Optional, Set import logging import os from tensorboardX import SummaryWriter import torch from allennlp.common.from_params import FromParams from allennlp.data.dataloader import TensorDict from allennlp.nn import util as nn_util from allennlp.training.optimizers import O...
allennlp-master
allennlp/training/tensorboard_writer.py
from typing import Optional from overrides import overrides import torch import torch.distributed as dist import scipy.stats as stats from allennlp.common.util import is_distributed from allennlp.training.metrics.metric import Metric @Metric.register("spearman_correlation") class SpearmanCorrelation(Metric): ""...
allennlp-master
allennlp/training/metrics/spearman_correlation.py
from typing import Optional from overrides import overrides import torch import torch.distributed as dist from allennlp.common.util import is_distributed from allennlp.training.metrics.metric import Metric @Metric.register("mean_absolute_error") class MeanAbsoluteError(Metric): """ This `Metric` calculates ...
allennlp-master
allennlp/training/metrics/mean_absolute_error.py
from typing import Dict from allennlp.training.metrics.metric import Metric from allennlp.training.metrics.fbeta_measure import FBetaMeasure @Metric.register("f1") class F1Measure(FBetaMeasure): """ Computes Precision, Recall and F1 with respect to a given `positive_label`. For example, for a BIO tagging...
allennlp-master
allennlp/training/metrics/f1_measure.py
import logging from typing import Optional import math import numpy as np from overrides import overrides import torch # import torch.distributed as dist from allennlp.common.util import is_distributed from allennlp.training.metrics.covariance import Covariance from allennlp.training.metrics.metric import Metric l...
allennlp-master
allennlp/training/metrics/pearson_correlation.py
from collections import Counter import math from typing import Iterable, Tuple, Dict, Set from overrides import overrides import torch import torch.distributed as dist from allennlp.common.util import is_distributed from allennlp.training.metrics.metric import Metric @Metric.register("bleu") class BLEU(Metric): ...
allennlp-master
allennlp/training/metrics/bleu.py
from typing import Optional from overrides import overrides import torch import torch.distributed as dist from allennlp.common.util import is_distributed from allennlp.training.metrics.metric import Metric @Metric.register("boolean_accuracy") class BooleanAccuracy(Metric): """ Just checks batch-equality of ...
allennlp-master
allennlp/training/metrics/boolean_accuracy.py
from typing import List, Optional, Union import torch import torch.distributed as dist from overrides import overrides from allennlp.common.util import is_distributed from allennlp.common.checks import ConfigurationError from allennlp.training.metrics.metric import Metric @Metric.register("fbeta") class FBetaMeasur...
allennlp-master
allennlp/training/metrics/fbeta_measure.py
from overrides import overrides import math from allennlp.training.metrics.average import Average from allennlp.training.metrics.metric import Metric @Metric.register("perplexity") class Perplexity(Average): """ Perplexity is a common metric used for evaluating how well a language model predicts a sample...
allennlp-master
allennlp/training/metrics/perplexity.py
import logging from typing import Optional from overrides import overrides import torch # import torch.distributed as dist from allennlp.common.util import is_distributed from allennlp.training.metrics.metric import Metric logger = logging.getLogger(__name__) @Metric.register("covariance") class Covariance(Metric...
allennlp-master
allennlp/training/metrics/covariance.py
from collections import defaultdict from typing import Tuple, Dict, Set from overrides import overrides import torch import torch.distributed as dist from allennlp.common.util import is_distributed from allennlp.training.metrics.metric import Metric @Metric.register("rouge") class ROUGE(Metric): """ Recall-...
allennlp-master
allennlp/training/metrics/rouge.py
""" A `~allennlp.training.metrics.metric.Metric` is some quantity or quantities that can be accumulated during training or evaluation; for example, accuracy or F1 score. """ from allennlp.training.metrics.attachment_scores import AttachmentScores from allennlp.training.metrics.average import Average from allennlp.trai...
allennlp-master
allennlp/training/metrics/__init__.py
from typing import Optional import sys from overrides import overrides import torch import torch.distributed as dist from allennlp.common.util import is_distributed from allennlp.common.checks import ConfigurationError from allennlp.training.metrics.metric import Metric @Metric.register("unigram_recall") class Uni...
allennlp-master
allennlp/training/metrics/unigram_recall.py
from typing import List, Optional import torch import torch.distributed as dist from overrides import overrides from allennlp.common.checks import ConfigurationError from allennlp.common.util import is_distributed from allennlp.training.metrics import FBetaMeasure from allennlp.training.metrics.metric import Metric ...
allennlp-master
allennlp/training/metrics/fbeta_multi_label_measure.py
from typing import Optional, List from overrides import overrides import torch import torch.distributed as dist from allennlp.common.util import is_distributed from allennlp.training.metrics.metric import Metric @Metric.register("attachment_scores") class AttachmentScores(Metric): """ Computes labeled and u...
allennlp-master
allennlp/training/metrics/attachment_scores.py
from typing import Dict, Iterable, Optional, Any import torch from allennlp.common.registrable import Registrable class Metric(Registrable): """ A very general abstract class representing a metric which can be accumulated. """ supports_distributed = False def __call__( self, predic...
allennlp-master
allennlp/training/metrics/metric.py
from overrides import overrides import torch import torch.distributed as dist from allennlp.common.util import is_distributed from allennlp.training.metrics.metric import Metric @Metric.register("average") class Average(Metric): """ This [`Metric`](./metric.md) breaks with the typical `Metric` API and just ...
allennlp-master
allennlp/training/metrics/average.py
from typing import Optional from overrides import overrides import torch import torch.distributed as dist from allennlp.common.util import is_distributed from allennlp.common.checks import ConfigurationError from allennlp.training.metrics.metric import Metric @Metric.register("categorical_accuracy") class Categoric...
allennlp-master
allennlp/training/metrics/categorical_accuracy.py
from typing import List import logging import os import tempfile import subprocess import shutil from overrides import overrides from nltk import Tree import torch import torch.distributed as dist from allennlp.common.util import is_distributed from allennlp.common.checks import ConfigurationError from allennlp.trai...
allennlp-master
allennlp/training/metrics/evalb_bracketing_scorer.py
from typing import Optional from overrides import overrides import torch import torch.distributed as dist from allennlp.common.util import is_distributed from allennlp.training.metrics.metric import Metric @Metric.register("entropy") class Entropy(Metric): def __init__(self) -> None: self._entropy = 0.0...
allennlp-master
allennlp/training/metrics/entropy.py
from typing import Optional from overrides import overrides import torch import torch.distributed as dist from allennlp.common.util import is_distributed from allennlp.common.checks import ConfigurationError from allennlp.training.metrics.metric import Metric @Metric.register("sequence_accuracy") class SequenceAccu...
allennlp-master
allennlp/training/metrics/sequence_accuracy.py
from typing import Dict, List, Optional, Set, Callable from collections import defaultdict import torch from allennlp.common.util import is_distributed from allennlp.common.checks import ConfigurationError from allennlp.nn.util import get_lengths_from_binary_sequence_mask from allennlp.data.vocabulary import Vocabula...
allennlp-master
allennlp/training/metrics/span_based_f1_measure.py
from typing import Optional from overrides import overrides import torch import torch.distributed as dist from sklearn import metrics from allennlp.common.util import is_distributed from allennlp.common.checks import ConfigurationError from allennlp.training.metrics.metric import Metric @Metric.register("auc") clas...
allennlp-master
allennlp/training/metrics/auc.py
from overrides import overrides import torch from allennlp.training.learning_rate_schedulers.learning_rate_scheduler import LearningRateScheduler @LearningRateScheduler.register("polynomial_decay") class PolynomialDecay(LearningRateScheduler): """ Implements polynomial decay Learning rate scheduling. The lea...
allennlp-master
allennlp/training/learning_rate_schedulers/polynomial_decay.py
import logging from overrides import overrides import numpy as np import torch from allennlp.training.learning_rate_schedulers.learning_rate_scheduler import LearningRateScheduler logger = logging.getLogger(__name__) @LearningRateScheduler.register("cosine") class CosineWithRestarts(LearningRateScheduler): ""...
allennlp-master
allennlp/training/learning_rate_schedulers/cosine.py
import logging from typing import List, Optional from overrides import overrides import torch from allennlp.training.learning_rate_schedulers.learning_rate_scheduler import LearningRateScheduler logger = logging.getLogger(__name__) @LearningRateScheduler.register("slanted_triangular") class SlantedTriangular(Lear...
allennlp-master
allennlp/training/learning_rate_schedulers/slanted_triangular.py
""" AllenNLP uses most `PyTorch learning rate schedulers <https://pytorch.org/docs/master/optim.html#how-to-adjust-learning-rate>`_, with a thin wrapper to allow registering them and instantiating them `from_params`. The available learning rate schedulers from PyTorch are * `"step" <https://pytorch.org/docs/master/op...
allennlp-master
allennlp/training/learning_rate_schedulers/__init__.py
from overrides import overrides import torch from allennlp.training.learning_rate_schedulers.learning_rate_scheduler import LearningRateScheduler @LearningRateScheduler.register("noam") class NoamLR(LearningRateScheduler): """ Implements the Noam Learning rate schedule. This corresponds to increasing the lea...
allennlp-master
allennlp/training/learning_rate_schedulers/noam.py
from typing import Any, Dict, List, Union from overrides import overrides import torch from allennlp.common.checks import ConfigurationError from allennlp.common.registrable import Registrable from allennlp.training.scheduler import Scheduler from allennlp.training.optimizers import Optimizer class LearningRateSche...
allennlp-master
allennlp/training/learning_rate_schedulers/learning_rate_scheduler.py
from typing import Dict, Any, List, Tuple, Optional from overrides import overrides import torch from allennlp.common.lazy import Lazy from allennlp.training.learning_rate_schedulers.learning_rate_scheduler import LearningRateScheduler @LearningRateScheduler.register("combined") class CombinedLearningRateScheduler(...
allennlp-master
allennlp/training/learning_rate_schedulers/combined.py
import torch from allennlp.training.learning_rate_schedulers import PolynomialDecay from allennlp.training.learning_rate_schedulers.learning_rate_scheduler import LearningRateScheduler @LearningRateScheduler.register("linear_with_warmup") class LinearWithWarmup(PolynomialDecay): """ Implements a learning rat...
allennlp-master
allennlp/training/learning_rate_schedulers/linear_with_warmup.py
import torch from allennlp.training.momentum_schedulers.momentum_scheduler import MomentumScheduler @MomentumScheduler.register("inverted_triangular") class InvertedTriangular(MomentumScheduler): """ Adjust momentum during training according to an inverted triangle-like schedule. The momentum starts off...
allennlp-master
allennlp/training/momentum_schedulers/inverted_triangular.py
import torch from allennlp.common.registrable import Registrable from allennlp.training.scheduler import Scheduler class MomentumScheduler(Scheduler, Registrable): def __init__(self, optimizer: torch.optim.Optimizer, last_epoch: int = -1) -> None: super().__init__(optimizer, "momentum", last_epoch) ...
allennlp-master
allennlp/training/momentum_schedulers/momentum_scheduler.py
from allennlp.training.momentum_schedulers.momentum_scheduler import MomentumScheduler from allennlp.training.momentum_schedulers.inverted_triangular import InvertedTriangular
allennlp-master
allennlp/training/momentum_schedulers/__init__.py
from typing import List, Iterator, Dict, Tuple, Any, Type, Union import logging import json import re from contextlib import contextmanager from pathlib import Path import numpy import torch from torch.utils.hooks import RemovableHandle from torch import Tensor from torch import backends from allennlp.common import R...
allennlp-master
allennlp/predictors/predictor.py
""" A `Predictor` is a wrapper for an AllenNLP `Model` that makes JSON predictions using JSON inputs. If you want to serve up a model through the web service (or using `allennlp.commands.predict`), you'll need a `Predictor` that wraps it. """ from allennlp.predictors.predictor import Predictor from allennlp.predictors....
allennlp-master
allennlp/predictors/__init__.py
from typing import List, Dict from overrides import overrides import numpy from allennlp.common.util import JsonDict from allennlp.data import DatasetReader, Instance from allennlp.data.fields import FlagField, TextField, SequenceLabelField from allennlp.data.tokenizers.spacy_tokenizer import SpacyTokenizer from alle...
allennlp-master
allennlp/predictors/sentence_tagger.py
from typing import List, Dict from overrides import overrides import numpy from allennlp.common.util import JsonDict from allennlp.data import Instance from allennlp.predictors.predictor import Predictor from allennlp.data.fields import LabelField from allennlp.data.tokenizers.spacy_tokenizer import SpacyTokenizer ...
allennlp-master
allennlp/predictors/text_classifier.py
from typing import Dict, Optional, List, Any import numpy from overrides import overrides import torch from torch.nn.modules.linear import Linear import torch.nn.functional as F from allennlp.common.checks import check_dimensions_match, ConfigurationError from allennlp.data import TextFieldTensors, Vocabulary from al...
allennlp-master
allennlp/models/simple_tagger.py
""" These submodules contain the classes for AllenNLP models, all of which are subclasses of `Model`. """ from allennlp.models.model import Model from allennlp.models.archival import archive_model, load_archive, Archive from allennlp.models.simple_tagger import SimpleTagger from allennlp.models.basic_classifier import...
allennlp-master
allennlp/models/__init__.py
""" `Model` is an abstract class representing an AllenNLP model. """ import logging import os from os import PathLike import re from typing import Dict, List, Set, Type, Optional, Union import numpy import torch from allennlp.common.checks import ConfigurationError from allennlp.common.params import Params, remove_k...
allennlp-master
allennlp/models/model.py
from typing import Dict, Optional from overrides import overrides import torch from allennlp.data import TextFieldTensors, Vocabulary from allennlp.models.model import Model from allennlp.modules import FeedForward, Seq2SeqEncoder, Seq2VecEncoder, TextFieldEmbedder from allennlp.nn import InitializerApplicator, util ...
allennlp-master
allennlp/models/basic_classifier.py
""" Helper functions for archiving models and restoring archived models. """ from os import PathLike from typing import NamedTuple, Union, Dict, Any, List, Optional import logging import os import tempfile import tarfile import shutil from pathlib import Path from contextlib import contextmanager import glob from torc...
allennlp-master
allennlp/models/archival.py
""" # Plugin management. AllenNLP supports loading "plugins" dynamically. A plugin is just a Python package that provides custom registered classes or additional `allennlp` subcommands. In order for AllenNLP to find your plugins, you have to create either a local plugins file named `.allennlp_plugins` in the director...
allennlp-master
allennlp/common/plugins.py
import logging from logging import Filter import os from os import PathLike from typing import Union import sys class AllenNlpLogger(logging.Logger): """ A custom subclass of 'logging.Logger' that keeps a set of messages to implement {debug,info,etc.}_once() methods. """ def __init__(self, name)...
allennlp-master
allennlp/common/logging.py
import copy import json import logging import os import zlib from collections import OrderedDict from collections.abc import MutableMapping from os import PathLike from typing import Any, Dict, List, Union, Optional from overrides import overrides # _jsonnet doesn't work on Windows, so we have to use fakes. try: ...
allennlp-master
allennlp/common/params.py
import logging from typing import NamedTuple, Optional, Dict, Tuple import transformers from transformers import AutoModel logger = logging.getLogger(__name__) class TransformerSpec(NamedTuple): model_name: str override_weights_file: Optional[str] = None override_weights_strip_prefix: Optional[str] = No...
allennlp-master
allennlp/common/cached_transformers.py
""" Various utilities that don't fit anywhere else. """ import hashlib import io import pickle from datetime import timedelta import importlib import json import logging import os import pkgutil import random import sys from contextlib import contextmanager from itertools import islice, zip_longest from pathlib import ...
allennlp-master
allennlp/common/util.py
import collections.abc from copy import deepcopy from pathlib import Path from typing import ( Any, Callable, cast, Dict, Iterable, List, Mapping, Set, Tuple, Type, TypeVar, Union, ) import inspect import logging from allennlp.common.checks import ConfigurationError from...
allennlp-master
allennlp/common/from_params.py
""" Functions and exceptions for checking that AllenNLP and its models are configured correctly. """ import logging import re import subprocess from typing import List, Union import torch from torch import cuda logger = logging.getLogger(__name__) class ConfigurationError(Exception): """ The exception raise...
allennlp-master
allennlp/common/checks.py
from allennlp.common.from_params import FromParams from allennlp.common.lazy import Lazy from allennlp.common.params import Params from allennlp.common.registrable import Registrable from allennlp.common.tqdm import Tqdm from allennlp.common.util import JsonDict
allennlp-master
allennlp/common/__init__.py
""" `allennlp.common.registrable.Registrable` is a "mixin" for endowing any base class with a named registry for its subclasses and a decorator for registering them. """ from collections import defaultdict from typing import TypeVar, Type, Callable, Dict, List, Optional, Tuple import importlib import logging from alle...
allennlp-master
allennlp/common/registrable.py
""" `allennlp.common.tqdm.Tqdm` wraps tqdm so we can add configurable global defaults for certain tqdm parameters. """ import logging from allennlp.common import logging as common_logging import sys from time import time from typing import Optional try: SHELL = str(type(get_ipython())) # type:ignore # noqa: F821 ...
allennlp-master
allennlp/common/tqdm.py
""" Utilities for working with the local dataset cache. """ import glob import os import logging import tempfile import json from collections import defaultdict from dataclasses import dataclass, asdict from datetime import timedelta from fnmatch import fnmatch from os import PathLike from urllib.parse import urlparse...
allennlp-master
allennlp/common/file_utils.py
import inspect from typing import Callable, Generic, TypeVar, Type, Union from allennlp.common.params import Params T = TypeVar("T") class Lazy(Generic[T]): """ This class is for use when constructing objects using `FromParams`, when an argument to a constructor has a _sequential dependency_ with anoth...
allennlp-master
allennlp/common/lazy.py
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