text
stringlengths
81
112k
Split a line of text into words and labels. Labels must start with the prefix used to create the model (__label__ by default). def get_line(self, text, on_unicode_error='strict'): """ Split a line of text into words and labels. Labels must start with the prefix used to create the model ...
Quantize the model reducing the size of the model and it's memory footprint. def quantize( self, input=None, qout=False, cutoff=0, retrain=False, epoch=None, lr=None, thread=None, verbose=None, dsub=2, qnorm=False ): ...
Parameters ---------- inputs : ``PackedSequence``, required. A batch first ``PackedSequence`` to run the stacked LSTM over. initial_state : Tuple[torch.Tensor, torch.Tensor], optional, (default = None) A tuple (state, memory) representing the initial hidden state and memo...
Converts a List of pairs (regex, params) into an RegularizerApplicator. This list should look like [["regex1", {"type": "l2", "alpha": 0.01}], ["regex2", "l1"]] where each parameter receives the penalty corresponding to the first regex that matches its name (which may be no regex and h...
List default first if it exists def list_available(cls) -> List[str]: """List default first if it exists""" keys = list(Registrable._registry[cls].keys()) default = cls.default_implementation if default is None: return keys elif default not in keys: mess...
Sanitize turns PyTorch and Numpy types into basic Python types so they can be serialized into JSON. def sanitize(x: Any) -> Any: # pylint: disable=invalid-name,too-many-return-statements """ Sanitize turns PyTorch and Numpy types into basic Python types so they can be serialized into JSON. """ ...
Takes a list and groups it into sublists of size ``count``, using ``default_value`` to pad the list at the end if the list is not divisable by ``count``. For example: >>> group_by_count([1, 2, 3, 4, 5, 6, 7], 3, 0) [[1, 2, 3], [4, 5, 6], [7, 0, 0]] This is a short method, but it's complicated and ...
Takes an iterator and batches the individual instances into lists of the specified size. The last list may be smaller if there are instances left over. def lazy_groups_of(iterator: Iterator[A], group_size: int) -> Iterator[List[A]]: """ Takes an iterator and batches the individual instances into lists of t...
Take a list of objects and pads it to the desired length, returning the padded list. The original list is not modified. Parameters ---------- sequence : List A list of objects to be padded. desired_length : int Maximum length of each sequence. Longer sequences are truncated to thi...
Returns a new dictionary with noise added to every key in ``dictionary``. The noise is uniformly distributed within ``noise_param`` percent of the value for every value in the dictionary. def add_noise_to_dict_values(dictionary: Dict[A, float], noise_param: float) -> Dict[A, float]: """ Returns a new ...
Matches a namespace pattern against a namespace string. For example, ``*tags`` matches ``passage_tags`` and ``question_tags`` and ``tokens`` matches ``tokens`` but not ``stemmed_tokens``. def namespace_match(pattern: str, namespace: str): """ Matches a namespace pattern against a namespace string. Fo...
Sets random seeds for reproducible experiments. This may not work as expected if you use this from within a python project in which you have already imported Pytorch. If you use the scripts/run_model.py entry point to training models with this library, your experiments should be reasonably reproducible. If ...
This function configures 3 global logging attributes - streaming stdout and stderr to a file as well as the terminal, setting the formatting for the python logging library and setting the interval frequency for the Tqdm progress bar. Note that this function does not set the logging level, which is set in `...
This function closes any open file handles and logs set up by `prepare_global_logging`. Parameters ---------- stdout_handler : ``logging.FileHandler``, required. The file handler returned from `prepare_global_logging`, attached to the global logger. def cleanup_global_logging(stdout_handler: loggi...
In order to avoid loading spacy models a whole bunch of times, we'll save references to them, keyed by the options we used to create the spacy model, so any particular configuration only gets loaded once. def get_spacy_model(spacy_model_name: str, pos_tags: bool, parse: bool, ner: bool) -> SpacyModelType: ...
Import all submodules under the given package. Primarily useful so that people using AllenNLP as a library can specify their own custom packages and have their custom classes get loaded and registered. def import_submodules(package_name: str) -> None: """ Import all submodules under the given packa...
Get peak memory usage for this process, as measured by max-resident-set size: https://unix.stackexchange.com/questions/30940/getrusage-system-call-what-is-maximum-resident-set-size Only works on OSX and Linux, returns 0.0 otherwise. def peak_memory_mb() -> float: """ Get peak memory usage for thi...
Get the current GPU memory usage. Based on https://discuss.pytorch.org/t/access-gpu-memory-usage-in-pytorch/3192/4 Returns ------- ``Dict[int, int]`` Keys are device ids as integers. Values are memory usage as integers in MB. Returns an empty ``dict`` if GPUs are not available. ...
An Iterable may be a list or a generator. This ensures we get a list without making an unnecessary copy. def ensure_list(iterable: Iterable[A]) -> List[A]: """ An Iterable may be a list or a generator. This ensures we get a list without making an unnecessary copy. """ if isinstance(iterable, li...
Takes an action index, updates checklist and returns an updated state. def update(self, action: torch.Tensor) -> 'ChecklistStatelet': """ Takes an action index, updates checklist and returns an updated state. """ checklist_addition = (self.terminal_actions == action).float() new...
Finds the production rule matching the filter function in the given type's valid action list, and removes it. If there is more than one matching function, we crash. def _remove_action_from_type(valid_actions: Dict[str, List[str]], type_: str, f...
Parameters ---------- inputs : ``torch.FloatTensor``, required. A tensor of shape (batch_size, num_timesteps, input_size) to apply the LSTM over. batch_lengths : ``List[int]``, required. A list of length batch_size containing the lengths of the sequences in ba...
Determine the URL corresponding to Python object This code is from https://github.com/numpy/numpy/blob/master/doc/source/conf.py#L290 and https://github.com/Lasagne/Lasagne/pull/262 def linkcode_resolve(domain, info): """ Determine the URL corresponding to Python object This code is from ht...
Encodes the question and table, computes a linking between the two, and constructs an initial RnnStatelet and LambdaGrammarStatelet for each batch instance to pass to the decoder. We take ``outputs`` as a parameter here and `modify` it, adding things that we want to visualize in a demo....
This method returns the indices of each entity's neighbors. A tensor is accepted as a parameter for copying purposes. Parameters ---------- worlds : ``List[WikiTablesWorld]`` num_entities : ``int`` tensor : ``torch.Tensor`` Used for copying the constructed li...
Produces a tensor with shape ``(batch_size, num_entities)`` that encodes each entity's type. In addition, a map from a flattened entity index to type is returned to combine entity type operations into one method. Parameters ---------- worlds : ``List[WikiTablesWorld]`` n...
Produces the probability of an entity given a question word and type. The logic below separates the entities by type since the softmax normalization term sums over entities of a single type. Parameters ---------- worlds : ``List[WikiTablesWorld]`` linking_scores : ``torc...
We track three metrics here: 1. dpd_acc, which is the percentage of the time that our best output action sequence is in the set of action sequences provided by DPD. This is an easy-to-compute lower bound on denotation accuracy for the set of examples where we actually have DPD outp...
This method creates the LambdaGrammarStatelet object that's used for decoding. Part of creating that is creating the `valid_actions` dictionary, which contains embedded representations of all of the valid actions. So, we create that here as well. The way we represent the valid expansions is a...
Does common things for validation time: computing logical form accuracy (which is expensive and unnecessary during training), adding visualization info to the output dictionary, etc. This doesn't return anything; instead it `modifies` the given ``outputs`` dictionary, and calls metrics on ``sel...
This method overrides ``Model.decode``, which gets called after ``Model.forward``, at test time, to finalize predictions. This is (confusingly) a separate notion from the "decoder" in "encoder/decoder", where that decoder logic lives in the ``TransitionFunction``. This method trims the output ...
Gets the logits of desired terminal actions yet to be produced by the decoder, and returns them for the decoder to add to the prior action logits, biasing the model towards predicting missing linked actions. def _get_linked_logits_addition(checklist_state: ChecklistStatelet, ...
Given a query (which is typically the decoder hidden state), compute an attention over the output of the question encoder, and return a weighted sum of the question representations given this attention. We also return the attention weights themselves. This is a simple computation, but we have ...
Walk over action space to collect completed paths of at most ``self._max_path_length`` steps. def _walk(self) -> None: """ Walk over action space to collect completed paths of at most ``self._max_path_length`` steps. """ # Buffer of NTs to expand, previous actions incomplete_pat...
Check that all the instances have the same types. def _check_types(self) -> None: """ Check that all the instances have the same types. """ all_instance_fields_and_types: List[Dict[str, str]] = [{k: v.__class__.__name__ for...
Gets the maximum padding lengths from all ``Instances`` in this batch. Each ``Instance`` has multiple ``Fields``, and each ``Field`` could have multiple things that need padding. We look at all fields in all instances, and find the max values for each (field_name, padding_key) pair, returning t...
This method converts this ``Batch`` into a set of pytorch Tensors that can be passed through a model. In order for the tensors to be valid tensors, all ``Instances`` in this batch need to be padded to the same lengths wherever padding is necessary, so we do that first, then we combine all of th...
Based on the current utterance, return a dictionary where the keys are the strings in the database that map to lists of the token indices that they are linked to. def get_strings_from_utterance(tokenized_utterance: List[Token]) -> Dict[str, List[int]]: """ Based on the current utterance, return a dictionar...
We create a new ``Grammar`` object from the one in ``AtisSqlTableContext``, that also has the new entities that are extracted from the utterance. Stitching together the expressions to form the grammar is a little tedious here, but it is worth it because we don't have to create a new grammar from...
When we add a new expression, there may be other expressions that refer to it, and we need to update those to point to the new expression. def _update_expression_reference(self, # pylint: disable=no-self-use grammar: Grammar, parent_expr...
This is a helper method for generating sequences, since we often want a list of expressions with whitespaces between them. def _get_sequence_with_spacing(self, # pylint: disable=no-self-use new_grammar, expressions: List[Expression], ...
This is a helper method for adding different types of numbers (eg. starting time ranges) as entities. We first go through all utterances in the interaction and find the numbers of a certain type and add them to the set ``all_numbers``, which is initialized with default values. We want to add all numbers...
This method gets entities from the current utterance finds which tokens they are linked to. The entities are divided into two main groups, ``numbers`` and ``strings``. We rely on these entities later for updating the valid actions and the grammar. def _get_linked_entities(self) -> Dict[str, Dict[str, T...
Return a sorted list of strings representing all possible actions of the form: nonterminal -> [right_hand_side] def all_possible_actions(self) -> List[str]: """ Return a sorted list of strings representing all possible actions of the form: nonterminal -> [right_hand_side] """ ...
When we first get the entities and the linking scores in ``_get_linked_entities`` we represent as dictionaries for easier updates to the grammar and valid actions. In this method, we flatten them for the model so that the entities are represented as a list, and the linking scores are a 2D numpy ...
Creates a Flask app that serves up a simple configuration wizard. def make_app(include_packages: Sequence[str] = ()) -> Flask: """ Creates a Flask app that serves up a simple configuration wizard. """ # Load modules for package_name in include_packages: import_submodules(package_name) ...
Just converts from an ``argparse.Namespace`` object to string paths. def train_model_from_args(args: argparse.Namespace): """ Just converts from an ``argparse.Namespace`` object to string paths. """ train_model_from_file(args.param_path, args.serialization_dir, ...
A wrapper around :func:`train_model` which loads the params from a file. Parameters ---------- parameter_filename : ``str`` A json parameter file specifying an AllenNLP experiment. serialization_dir : ``str`` The directory in which to save results and logs. We just pass this along to ...
Trains the model specified in the given :class:`Params` object, using the data and training parameters also specified in that object, and saves the results in ``serialization_dir``. Parameters ---------- params : ``Params`` A parameter object specifying an AllenNLP Experiment. serialization...
Performs division and handles divide-by-zero. On zero-division, sets the corresponding result elements to zero. def _prf_divide(numerator, denominator): """Performs division and handles divide-by-zero. On zero-division, sets the corresponding result elements to zero. """ result = numerator / deno...
One sentence per line, formatted like The###DET dog###NN ate###V the###DET apple###NN Returns a list of pairs (tokenized_sentence, tags) def load_data(file_path: str) -> Tuple[List[str], List[str]]: """ One sentence per line, formatted like The###DET dog###NN ate###V the###DET apple###NN...
max_vocab_size limits the size of the vocabulary, not including the @@UNKNOWN@@ token. max_vocab_size is allowed to be either an int or a Dict[str, int] (or nothing). But it could also be a string representing an int (in the case of environment variable substitution). So we need some complex logic to handl...
Persist this Vocabulary to files so it can be reloaded later. Each namespace corresponds to one file. Parameters ---------- directory : ``str`` The directory where we save the serialized vocabulary. def save_to_files(self, directory: str) -> None: """ Persis...
Loads a ``Vocabulary`` that was serialized using ``save_to_files``. Parameters ---------- directory : ``str`` The directory containing the serialized vocabulary. def from_files(cls, directory: str) -> 'Vocabulary': """ Loads a ``Vocabulary`` that was serialized usin...
If you already have a vocabulary file for a trained model somewhere, and you really want to use that vocabulary file instead of just setting the vocabulary from a dataset, for whatever reason, you can do that with this method. You must specify the namespace to use, and we assume that you want t...
Constructs a vocabulary given a collection of `Instances` and some parameters. We count all of the vocabulary items in the instances, then pass those counts and the other parameters, to :func:`__init__`. See that method for a description of what the other parameters do. def from_instances(cls,...
There are two possible ways to build a vocabulary; from a collection of instances, using :func:`Vocabulary.from_instances`, or from a pre-saved vocabulary, using :func:`Vocabulary.from_files`. You can also extend pre-saved vocabulary with collection of instances using this method. This m...
This method can be used for extending already generated vocabulary. It takes same parameters as Vocabulary initializer. The token2index and indextotoken mappings of calling vocabulary will be retained. It is an inplace operation so None will be returned. def _extend(self, counte...
Extends an already generated vocabulary using a collection of instances. def extend_from_instances(self, params: Params, instances: Iterable['adi.Instance'] = ()) -> None: """ Extends an already generated vocabulary using a collection of insta...
Returns whether or not there are padding and OOV tokens added to the given namespace. def is_padded(self, namespace: str) -> bool: """ Returns whether or not there are padding and OOV tokens added to the given namespace. """ return self._index_to_token[namespace][0] == self._padding_tok...
Adds ``token`` to the index, if it is not already present. Either way, we return the index of the token. def add_token_to_namespace(self, token: str, namespace: str = 'tokens') -> int: """ Adds ``token`` to the index, if it is not already present. Either way, we return the index of th...
Computes the regularization penalty for the model. Returns 0 if the model was not configured to use regularization. def get_regularization_penalty(self) -> Union[float, torch.Tensor]: """ Computes the regularization penalty for the model. Returns 0 if the model was not configured to use...
Takes an :class:`~allennlp.data.instance.Instance`, which typically has raw text in it, converts that text into arrays using this model's :class:`Vocabulary`, passes those arrays through :func:`self.forward()` and :func:`self.decode()` (which by default does nothing) and returns the result. Bef...
Takes a list of :class:`~allennlp.data.instance.Instance`s, converts that text into arrays using this model's :class:`Vocabulary`, passes those arrays through :func:`self.forward()` and :func:`self.decode()` (which by default does nothing) and returns the result. Before returning the result, w...
Takes the result of :func:`forward` and runs inference / decoding / whatever post-processing you need to do your model. The intent is that ``model.forward()`` should produce potentials or probabilities, and then ``model.decode()`` can take those results and run some kind of beam search or const...
This method checks the device of the model parameters to determine the cuda_device this model should be run on for predictions. If there are no parameters, it returns -1. Returns ------- The cuda device this model should run on for predictions. def _get_prediction_device(self) -> int:...
This method warns once if a user implements a model which returns a dictionary with values which we are unable to split back up into elements of the batch. This is controlled by a class attribute ``_warn_for_unseperable_batches`` because it would be extremely verbose otherwise. def _maybe_warn_...
Instantiates an already-trained model, based on the experiment configuration and some optional overrides. def _load(cls, config: Params, serialization_dir: str, weights_file: str = None, cuda_device: int = -1) -> 'Model': """ Instantiates ...
Instantiates an already-trained model, based on the experiment configuration and some optional overrides. Parameters ---------- config: Params The configuration that was used to train the model. It should definitely have a `model` section, and should probably hav...
Iterates through all embedding modules in the model and assures it can embed with the extended vocab. This is required in fine-tuning or transfer learning scenarios where model was trained with original vocabulary but during fine-tuning/tranfer-learning, it will have it work with extended vocabu...
Returns an agenda that can be used guide search. Parameters ---------- conservative : ``bool`` Setting this flag will return a subset of the agenda items that correspond to high confidence lexical matches. You'll need this if you are going to use this agenda to ...
Takes a logical form, and the list of target values as strings from the original lisp string, and returns True iff the logical form executes to the target list, using the official WikiTableQuestions evaluation script. def evaluate_logical_form(self, logical_form: str, target_list: List[str]) -> bool: ...
Select function takes a list of rows and a column name and returns a list of strings as in cells. def select_string(self, rows: List[Row], column: StringColumn) -> List[str]: """ Select function takes a list of rows and a column name and returns a list of strings as in cells. ""...
Select function takes a row (as a list) and a column name and returns the number in that column. If multiple rows are given, will return the first number that is not None. def select_number(self, rows: List[Row], column: NumberColumn) -> Number: """ Select function takes a row (as a list) and a...
Select function takes a row as a list and a column name and returns the date in that column. def select_date(self, rows: List[Row], column: DateColumn) -> Date: """ Select function takes a row as a list and a column name and returns the date in that column. """ dates: List[Date] = [] ...
Takes a row and a column and returns a list of rows from the full set of rows that contain the same value under the given column as the given row. def same_as(self, rows: List[Row], column: Column) -> List[Row]: """ Takes a row and a column and returns a list of rows from the full set of rows t...
Takes three numbers and returns a ``Date`` object whose year, month, and day are the three numbers in that order. def date(self, year: Number, month: Number, day: Number) -> Date: """ Takes three numbers and returns a ``Date`` object whose year, month, and day are the three numbers in t...
Takes an expression that evaluates to a list of rows, and returns the first one in that list. def first(self, rows: List[Row]) -> List[Row]: """ Takes an expression that evaluates to a list of rows, and returns the first one in that list. """ if not rows: log...
Takes an expression that evaluates to a list of rows, and returns the last one in that list. def last(self, rows: List[Row]) -> List[Row]: """ Takes an expression that evaluates to a list of rows, and returns the last one in that list. """ if not rows: logger...
Takes an expression that evaluates to a single row, and returns the row that occurs before the input row in the original set of rows. If the input row happens to be the top row, we will return an empty list. def previous(self, rows: List[Row]) -> List[Row]: """ Takes an expression that ...
Takes an expression that evaluates to a single row, and returns the row that occurs after the input row in the original set of rows. If the input row happens to be the last row, we will return an empty list. def next(self, rows: List[Row]) -> List[Row]: """ Takes an expression that eval...
Takes a list of rows and a column and returns the most frequent values (one or more) under that column in those rows. def mode_string(self, rows: List[Row], column: StringColumn) -> List[str]: """ Takes a list of rows and a column and returns the most frequent values (one or more) under ...
Takes a list of rows and a column and returns the most frequent value under that column in those rows. def mode_number(self, rows: List[Row], column: NumberColumn) -> Number: """ Takes a list of rows and a column and returns the most frequent value under that column in those rows. ...
Takes a list of rows and a column and returns the most frequent value under that column in those rows. def mode_date(self, rows: List[Row], column: DateColumn) -> Date: """ Takes a list of rows and a column and returns the most frequent value under that column in those rows. """...
Takes a list of rows and a column name and returns a list containing a single row (dict from columns to cells) that has the maximum numerical value in the given column. We return a list instead of a single dict to be consistent with the return type of ``select`` and ``all_rows``. def argmax(sel...
Takes a list of rows and a column and returns a list containing a single row (dict from columns to cells) that has the minimum numerical value in the given column. We return a list instead of a single dict to be consistent with the return type of ``select`` and ``all_rows``. def argmin(self, ro...
Takes a list of rows and a column and returns the max of the values under that column in those rows. def max_date(self, rows: List[Row], column: DateColumn) -> Date: """ Takes a list of rows and a column and returns the max of the values under that column in those rows. """ ...
Takes a list of rows and a column and returns the max of the values under that column in those rows. def max_number(self, rows: List[Row], column: NumberColumn) -> Number: """ Takes a list of rows and a column and returns the max of the values under that column in those rows. ""...
Takes a list of rows and a column and returns the mean of the values under that column in those rows. def average(self, rows: List[Row], column: NumberColumn) -> Number: """ Takes a list of rows and a column and returns the mean of the values under that column in those rows. """...
Takes a two rows and a number column and returns the difference between the values under that column in those two rows. def diff(self, first_row: List[Row], second_row: List[Row], column: NumberColumn) -> Number: """ Takes a two rows and a number column and returns the difference between the va...
Takes a row and returns its index in the full list of rows. If the row does not occur in the table (which should never happen because this function will only be called with a row that is the result of applying one or more functions on the table rows), the method returns -1. def _get_row_index(self, row...
This function will be called on nodes of a logical form tree, which are either non-terminal symbols that can be expanded or terminal symbols that must be leaf nodes. Returns ``True`` if the given symbol is a terminal symbol. def is_terminal(self, symbol: str) -> bool: """ This function...
For a given action, returns at most ``max_num_paths`` paths to the root (production with ``START_SYMBOL``) that are not longer than ``max_path_length``. def get_paths_to_root(self, action: str, max_path_length: int = 20, beam_size: i...
Returns a mapping from each `MultiMatchNamedBasicType` to all the `NamedBasicTypes` that it matches. def get_multi_match_mapping(self) -> Dict[Type, List[Type]]: """ Returns a mapping from each `MultiMatchNamedBasicType` to all the `NamedBasicTypes` that it matches. """ ...
Takes a logical form as a string, maps its tokens using the mapping and returns a parsed expression. Parameters ---------- logical_form : ``str`` Logical form to parse remove_var_function : ``bool`` (optional) ``var`` is a special function that some languages use...
Returns the sequence of actions (as strings) that resulted in the given expression. def get_action_sequence(self, expression: Expression) -> List[str]: """ Returns the sequence of actions (as strings) that resulted in the given expression. """ # Starting with the type of the whole expre...
Takes an action sequence and constructs a logical form from it. This is useful if you want to get a logical form from a decoded sequence of actions generated by a transition based semantic parser. Parameters ---------- action_sequence : ``List[str]`` The sequence of ...
Given a current node in the logical form tree, and a list of actions in an action sequence, this method fills in the children of the current node from the action sequence, then returns whatever actions are left. For example, we could get a node with type ``c``, and an action sequence that begin...
Takes a type signature and infers the number of arguments the corresponding function takes. Examples: e -> 0 <r,e> -> 1 <e,<e,t>> -> 2 <b,<<b,#1>,<#1,b>>> -> 3 def _infer_num_arguments(cls, type_signature: str) -> int: """ Takes a type signature a...
``nested_expression`` is the result of parsing a logical form in Lisp format. We process it recursively and return a string in the format that NLTK's ``LogicParser`` would understand. def _process_nested_expression(self, nested_expression) -> str: """ ``nested_expression`` is the result...