text
stringlengths
81
112k
See ``PlaceholderType.resolve`` def resolve(self, other: Type) -> Optional[Type]: """See ``PlaceholderType.resolve``""" if not isinstance(other, NltkComplexType): return None expected_second = ComplexType(NUMBER_TYPE, ComplexType(ANY_TYPE, Compl...
See ``PlaceholderType.resolve`` def resolve(self, other: Type) -> Type: """See ``PlaceholderType.resolve``""" if not isinstance(other, NltkComplexType): return None resolved_second = NUMBER_TYPE.resolve(other.second) if not resolved_second: return None re...
Reads an NLVR dataset and returns a JSON representation containing sentences, labels, correct and incorrect logical forms. The output will contain at most `max_num_logical_forms` logical forms each in both correct and incorrect lists. The output format is: ``[{"id": str, "label": str, "sentence": str, "...
This method lets you take advantage of spacy's batch processing. Default implementation is to just iterate over the texts and call ``split_sentences``. def batch_split_sentences(self, texts: List[str]) -> List[List[str]]: """ This method lets you take advantage of spacy's batch processing. ...
An iterator over the entire dataset, yielding all sentences processed. def dataset_iterator(self, file_path: str) -> Iterator[OntonotesSentence]: """ An iterator over the entire dataset, yielding all sentences processed. """ for conll_file in self.dataset_path_iterator(file_path): ...
An iterator returning file_paths in a directory containing CONLL-formatted files. def dataset_path_iterator(file_path: str) -> Iterator[str]: """ An iterator returning file_paths in a directory containing CONLL-formatted files. """ logger.info("Reading CONLL sentences fr...
An iterator over CONLL formatted files which yields documents, regardless of the number of document annotations in a particular file. This is useful for conll data which has been preprocessed, such as the preprocessing which takes place for the 2012 CONLL Coreference Resolution task. def datase...
An iterator over the sentences in an individual CONLL formatted file. def sentence_iterator(self, file_path: str) -> Iterator[OntonotesSentence]: """ An iterator over the sentences in an individual CONLL formatted file. """ for document in self.dataset_document_iterator(file_path): ...
For a given coref label, add it to a currently open span(s), complete a span(s) or ignore it, if it is outside of all spans. This method mutates the clusters and coref_stacks dictionaries. Parameters ---------- label : ``str`` The coref label for this word. w...
Given a sequence of different label types for a single word and the current span label we are inside, compute the BIO tag for each label and append to a list. Parameters ---------- annotations: ``List[str]`` A list of labels to compute BIO tags for. span_labels : ``L...
Prints results from an ``argparse.Namespace`` object. def print_results_from_args(args: argparse.Namespace): """ Prints results from an ``argparse.Namespace`` object. """ path = args.path metrics_name = args.metrics_filename keys = args.keys results_dict = {} for root, _, files in os.w...
Apply dropout to input tensor. Parameters ---------- input_tensor: ``torch.FloatTensor`` A tensor of shape ``(batch_size, num_timesteps, embedding_dim)`` Returns ------- output: ``torch.FloatTensor`` A tensor of shape ``(batch_size, num_timesteps...
Compute and return the metric. Optionally also call :func:`self.reset`. def get_metric(self, reset: bool) -> Union[float, Tuple[float, ...], Dict[str, float], Dict[str, List[float]]]: """ Compute and return the metric. Optionally also call :func:`self.reset`. """ raise NotImplementedErr...
If you actually passed gradient-tracking Tensors to a Metric, there will be a huge memory leak, because it will prevent garbage collection for the computation graph. This method ensures that you're using tensors directly and that they are on the CPU. def unwrap_to_tensors(*tensors: torch.Tensor...
Replaces abstract variables in text with their concrete counterparts. def replace_variables(sentence: List[str], sentence_variables: Dict[str, str]) -> Tuple[List[str], List[str]]: """ Replaces abstract variables in text with their concrete counterparts. """ tokens = [] tags =...
Cleans up and unifies a SQL query. This involves unifying quoted strings and splitting brackets which aren't formatted consistently in the data. def clean_and_split_sql(sql: str) -> List[str]: """ Cleans up and unifies a SQL query. This involves unifying quoted strings and splitting brackets which aren...
Some examples in the text2sql datasets use ID as a column reference to the column of a table which has a primary key. This causes problems if you are trying to constrain a grammar to only produce the column names directly, because you don't know what ID refers to. So instead of dealing with that, we just re...
Reads a schema from the text2sql data, returning a dictionary mapping table names to their columns and respective types. This handles columns in an arbitrary order and also allows either ``{Table, Field}`` or ``{Table, Field} Name`` as headers, because both appear in the data. It also uppercases table a...
A utility function for reading in text2sql data. The blob is the result of loading the json from a file produced by the script ``scripts/reformat_text2sql_data.py``. Parameters ---------- data : ``JsonDict`` use_all_sql : ``bool``, optional (default = False) Whether to use all of the sq...
This function exists because Pytorch RNNs require that their inputs be sorted before being passed as input. As all of our Seq2xxxEncoders use this functionality, it is provided in a base class. This method can be called on any module which takes as input a ``PackedSequence`` and some ``hidden_st...
Returns an initial state for use in an RNN. Additionally, this method handles the batch size changing across calls by mutating the state to append initial states for new elements in the batch. Finally, it also handles sorting the states with respect to the sequence lengths of elements in the bat...
After the RNN has run forward, the states need to be updated. This method just sets the state to the updated new state, performing several pieces of book-keeping along the way - namely, unsorting the states and ensuring that the states of completely padded sequences are not updated. Fina...
Takes a list of valid target action sequences and creates a mapping from all possible (valid) action prefixes to allowed actions given that prefix. While the method is called ``construct_prefix_tree``, we're actually returning a map that has as keys the paths to `all internal nodes of the trie`, and as val...
Convert the string to Value object. Args: original_string (basestring): Original string corenlp_value (basestring): Optional value returned from CoreNLP Returns: Value def to_value(original_string, corenlp_value=None): """Convert the string to Value object. Args: origi...
Convert a list of strings to a list of Values Args: original_strings (list[basestring]) corenlp_values (list[basestring or None]) Returns: list[Value] def to_value_list(original_strings, corenlp_values=None): """Convert a list of strings to a list of Values Args: origi...
Return True if the predicted denotation is correct. Args: target_values (list[Value]) predicted_values (list[Value]) Returns: bool def check_denotation(target_values, predicted_values): """Return True if the predicted denotation is correct. Args: target_values (list[Va...
Try to parse into a number. Return: the number (int or float) if successful; otherwise None. def parse(text): """Try to parse into a number. Return: the number (int or float) if successful; otherwise None. """ try: return int(text) e...
Try to parse into a date. Return: tuple (year, month, date) if successful; otherwise None. def parse(text): """Try to parse into a date. Return: tuple (year, month, date) if successful; otherwise None. """ try: ymd = text.lower().split('-') ...
Given a sequence tensor, extract spans and return representations of them. Span representation can be computed in many different ways, such as concatenation of the start and end spans, attention over the vectors contained inside the span, etc. Parameters ---------- seque...
serialization_directory : str, required. The directory containing the serialized weights. device: int, default = -1 The device to run the evaluation on. data: str, default = None The data to evaluate on. By default, we use the validation data from the original experiment. pre...
Takes an initial state object, a means of transitioning from state to state, and a supervision signal, and uses the supervision to train the transition function to pick "good" states. This function should typically return a ``loss`` key during training, which the ``Model`` will use as i...
Returns the state of the scheduler as a ``dict``. def state_dict(self) -> Dict[str, Any]: """ Returns the state of the scheduler as a ``dict``. """ return {key: value for key, value in self.__dict__.items() if key != 'optimizer'}
Load the schedulers state. Parameters ---------- state_dict : ``Dict[str, Any]`` Scheduler state. Should be an object returned from a call to ``state_dict``. def load_state_dict(self, state_dict: Dict[str, Any]) -> None: """ Load the schedulers state. Param...
Parameters ---------- text_field_input : ``Dict[str, torch.Tensor]`` A dictionary that was the output of a call to ``TextField.as_tensor``. Each tensor in here is assumed to have a shape roughly similar to ``(batch_size, sequence_length)`` (perhaps with an extra trai...
Identifies the best prediction given the results from the submodels. Parameters ---------- subresults : List[Dict[str, torch.Tensor]] Results of each submodel. Returns ------- The index of the best submodel. def ensemble(subresults: List[Dict[str, torch.Tensor]]) -> torch.Tensor: ...
Parameters ---------- inputs : ``torch.Tensor``, required. A Tensor of shape ``(batch_size, sequence_length, hidden_size)``. mask : ``torch.LongTensor``, required. A binary mask of shape ``(batch_size, sequence_length)`` representing the non-padded elements in...
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 ...
Load the pre-trained weights from the file. def load_weights(self, weight_file: str) -> None: """ Load the pre-trained weights from the file. """ requires_grad = self.requires_grad with h5py.File(cached_path(weight_file), 'r') as fin: for i_layer, lstms in enumerate...
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...
Takes a type and a set of basic types, and substitutes all instances of ANY_TYPE with all possible basic types and returns a list with all possible combinations. Note that this substitution is unconstrained. That is, If you have a type with placeholders, <#1,#1> for example, this may substitute the placeh...
Takes a complex type (without any placeholders), gets its return values, and returns productions (perhaps each with multiple arguments) that produce the return values. This method also takes care of ``MultiMatchNamedBasicTypes``. If one of the arguments or the return types is a multi match type, it gets al...
Generates all the valid actions starting from each non-terminal. For terminals of a specific type, we simply add a production from the type to the terminal. For all terminal `functions`, we additionally add a rule that allows their return type to be generated from an application of the function. For exampl...
Gives the final return type for this function. If the function takes a single argument, this is just ``self.second``. If the function takes multiple arguments and returns a basic type, this should be the final ``.second`` after following all complex types. That is the implementation here in t...
Gives the types of all arguments to this function. For functions returning a basic type, we grab all ``.first`` types until ``.second`` is no longer a ``ComplexType``. That logic is implemented here in the base class. If you have a higher-order function that returns a function itself, you nee...
Takes a set of ``BasicTypes`` and replaces any instances of ``ANY_TYPE`` inside this complex type with each of those basic types. def substitute_any_type(self, basic_types: Set[BasicType]) -> List[Type]: """ Takes a set of ``BasicTypes`` and replaces any instances of ``ANY_TYPE`` inside this ...
See ``PlaceholderType.resolve`` def resolve(self, other) -> Optional[Type]: """See ``PlaceholderType.resolve``""" if not isinstance(other, NltkComplexType): return None other_first = other.first.resolve(other.second) if not other_first: return None other_...
See ``PlaceholderType.resolve`` def resolve(self, other: Type) -> Optional[Type]: """See ``PlaceholderType.resolve``""" if not isinstance(other, NltkComplexType): return None if not isinstance(other.second, NltkComplexType): return None other_first = other.first....
We override this method to do just one thing on top of ``ApplicationExpression._set_type``. In lambda expressions of the form /x F(x), where the function is F and the argument is x, we can use the type of F to infer the type of x. That is, if F is of type <a, b>, we can resolve the type of x aga...
Send the mean and std of all parameters and gradients to tensorboard, as well as logging the average gradient norm. def log_parameter_and_gradient_statistics(self, # pylint: disable=invalid-name model: Model, batch_grad...
Send current parameter specific learning rates to tensorboard def log_learning_rates(self, model: Model, optimizer: torch.optim.Optimizer): """ Send current parameter specific learning rates to tensorboard """ if self._should_log_lea...
Send histograms of parameters to tensorboard. def log_histograms(self, model: Model, histogram_parameters: Set[str]) -> None: """ Send histograms of parameters to tensorboard. """ for name, param in model.named_parameters(): if name in histogram_parameters: s...
Sends all of the train metrics (and validation metrics, if provided) to tensorboard. def log_metrics(self, train_metrics: dict, val_metrics: dict = None, epoch: int = None, log_to_console: bool = False) -> None: """ Sends a...
Create explanation (as a list of header/content entries) for an answer def get_explanation(logical_form: str, world_extractions: JsonDict, answer_index: int, world: QuarelWorld) -> List[JsonDict]: """ Create explanation (as a list of header/content en...
Use stemming to attempt alignment between extracted world and given world literals. If more words align to one world vs the other, it's considered aligned. def align_entities(extracted: List[str], literals: JsonDict, stemmer: NltkPorterStemmer) -> List[str]: """ Use st...
Calculate multi-perspective cosine matching between time-steps of vectors of the same length. Parameters ---------- vector1 : ``torch.Tensor`` A tensor of shape ``(batch, seq_len, hidden_size)`` vector2 : ``torch.Tensor`` A tensor of shape ``(batch, seq_len or 1, hidden_size)`` ...
Calculate multi-perspective cosine matching between each time step of one vector and each time step of another vector. Parameters ---------- vector1 : ``torch.Tensor`` A tensor of shape ``(batch, seq_len1, hidden_size)`` vector2 : ``torch.Tensor`` A tensor of shape ``(batch, seq_len...
Given the forward (or backward) representations of sentence1 and sentence2, apply four bilateral matching functions between them in one direction. Parameters ---------- context_1 : ``torch.Tensor`` Tensor of shape (batch_size, seq_len1, hidden_dim) representing the encoding ...
Training data in WikitableQuestions comes with examples in the form of lisp strings in the format: (example (id <example-id>) (utterance <question>) (context (graph tables.TableKnowledgeGraph <table-filename>)) (targetValue (list (description <answer1>) (descri...
Just converts from an ``argparse.Namespace`` object to params. def make_vocab_from_args(args: argparse.Namespace): """ Just converts from an ``argparse.Namespace`` object to params. """ parameter_path = args.param_path overrides = args.overrides serialization_dir = args.serialization_dir p...
Very basic model for executing friction logical forms. For now returns answer index (or -1 if no answer can be concluded) def execute(self, lf_raw: str) -> int: """ Very basic model for executing friction logical forms. For now returns answer index (or -1 if no answer can be concluded) ...
Given an utterance, we get the numbers that correspond to times and convert them to values that may appear in the query. For example: convert ``7pm`` to ``1900``. def get_times_from_utterance(utterance: str, char_offset_to_token_index: Dict[int, int], indic...
When the year is not explicitly mentioned in the utterance, the query assumes that it is 1993 so we do the same here. If there is no mention of the month or day then we do not return any dates from the utterance. def get_date_from_utterance(tokenized_utterance: List[Token], year: in...
Given an utterance, this function finds all the numbers that are in the action space. Since we need to keep track of linking scores, we represent the numbers as a dictionary, where the keys are the string representation of the number and the values are lists of the token indices that triggers that number. def ...
Given a digit in the utterance, return a list of the times that it corresponds to. def digit_to_query_time(digit: str) -> List[int]: """ Given a digit in the utterance, return a list of the times that it corresponds to. """ if len(digit) > 2: return [int(digit), int(digit) + TWELVE_TO_TWENTY_FO...
Given a list of times that follow a word such as ``about``, we return a list of times that could appear in the query as a result of this. For example if ``about 7pm`` appears in the utterance, then we also want to add ``1830`` and ``1930``. def get_approximate_times(times: List[int]) -> List[int]: """ ...
r""" Given a regex for matching times in the utterance, we want to convert the matches to the values that appear in the query and token indices they correspond to. ``char_offset_to_token_index`` is a dictionary that maps from the character offset to the token index, we use this to look up what token a ...
We evaluate here whether the predicted query and the query label evaluate to the exact same table. This method is only called by the subprocess, so we just exit with 1 if it is correct and 0 otherwise. def _evaluate_sql_query_subprocess(self, predicted_query: str, sql_query_labels: List[str]) -> int: ...
Formats a dictionary of production rules into the string format expected by the Parsimonious Grammar class. def format_grammar_string(grammar_dictionary: Dict[str, List[str]]) -> str: """ Formats a dictionary of production rules into the string format expected by the Parsimonious Grammar class. """...
We initialize the valid actions with the global actions. These include the valid actions that result from the grammar and also those that result from the tables provided. The keys represent the nonterminals in the grammar and the values are lists of the valid actions of that nonterminal. def initialize_val...
This function formats an action as it appears in models. It splits productions based on the special `ws` and `wsp` rules, which are used in grammars to denote whitespace, and then rejoins these tokens a formatted, comma separated list. Importantly, note that it `does not` split on spaces in the gram...
For each node, we accumulate the rules that generated its children in a list. def add_action(self, node: Node) -> None: """ For each node, we accumulate the rules that generated its children in a list. """ if node.expr.name and node.expr.name not in ['ws', 'wsp']: nontermina...
See the ``NodeVisitor`` visit method. This just changes the order in which we visit nonterminals from right to left to left to right. def visit(self, node): """ See the ``NodeVisitor`` visit method. This just changes the order in which we visit nonterminals from right to left to left to...
Parameters ---------- input_ids : ``torch.LongTensor`` The (batch_size, ..., max_sequence_length) tensor of wordpiece ids. offsets : ``torch.LongTensor``, optional The BERT embeddings are one per wordpiece. However it's possible/likely you might want one per o...
SQL is a predominately variable free language in terms of simple usage, in the sense that most queries do not create references to variables which are not already static tables in a dataset. However, it is possible to do this via derived tables. If we don't require this functionality, we can tighten the ...
Variables can be treated as numbers or strings if their type can be inferred - however, that can be difficult, so instead, we can just treat them all as values and be a bit looser on the typing we allow in our grammar. Here we just remove all references to number and string from the grammar, replacing them ...
Ensembles don't have vocabularies or weights of their own, so they override _load. def _load(cls, config: Params, serialization_dir: str, weights_file: str = None, cuda_device: int = -1) -> 'Model': """ Ensembles don't have vocabularies or weights...
Apply text standardization following original implementation. def text_standardize(text): """ Apply text standardization following original implementation. """ text = text.replace('—', '-') text = text.replace('–', '-') text = text.replace('―', '-') text = text.replace('…', '...') text ...
The :mod:`~allennlp.run` command only knows about the registered classes in the ``allennlp`` codebase. In particular, once you start creating your own ``Model`` s and so forth, it won't work for them, unless you use the ``--include-package`` flag. def main(prog: str = None, subcommand_overrides: Dict[...
The ``TextField`` has a list of ``Tokens``, and each ``Token`` gets converted into arrays by (potentially) several ``TokenIndexers``. This method gets the max length (over tokens) associated with each of these arrays. def get_padding_lengths(self) -> Dict[str, int]: """ The ``TextField...
Creates ELMo word representations from a vocabulary file. These word representations are _independent_ - they are the result of running the CNN and Highway layers of the ELMo model, but not the Bidirectional LSTM. ELMo requires 2 additional tokens: <S> and </S>. The first token in this file is assumed t...
Sorts the instances by their padding lengths, using the keys in ``sorting_keys`` (in the order in which they are provided). ``sorting_keys`` is a list of ``(field_name, padding_key)`` tuples. def sort_by_padding(instances: List[Instance], sorting_keys: List[Tuple[str, str]], # pylint: dis...
Take the question and check if it is compatible with either of the answer choices. def infer(self, setup: QuaRelType, answer_0: QuaRelType, answer_1: QuaRelType) -> int: """ Take the question and check if it is compatible with either of the answer choices. """ if self._check_quarels_com...
Creates a Flask app that serves up the provided ``Predictor`` along with a front-end for interacting with it. If you want to use the built-in bare-bones HTML, you must provide the field names for the inputs (which will be used both as labels and as the keys in the JSON that gets sent to the predictor)....
Returns bare bones HTML for serving up an input form with the specified fields that can render predictions from the configured model. def _html(title: str, field_names: List[str]) -> str: """ Returns bare bones HTML for serving up an input form with the specified fields that can render predictions from...
Returns the valid actions in the current grammar state. See the class docstring for a description of what we're returning here. def get_valid_actions(self) -> Dict[str, Tuple[torch.Tensor, torch.Tensor, List[int]]]: """ Returns the valid actions in the current grammar state. See the class doc...
Takes an action in the current grammar state, returning a new grammar state with whatever updates are necessary. The production rule is assumed to be formatted as "LHS -> RHS". This will update the non-terminal stack and the context-dependent actions. Updating the non-terminal stack involves ...
Note: Counter to typical intuition, this function decodes the _maximum_ spanning tree. Decode the optimal MST tree with the Chu-Liu-Edmonds algorithm for maximum spanning arborescences on graphs. Parameters ---------- energy : ``numpy.ndarray``, required. A tensor with shape (num_label...
Applies the chu-liu-edmonds algorithm recursively to a graph with edge weights defined by score_matrix. Note that this function operates in place, so variables will be modified. Parameters ---------- length : ``int``, required. The number of nodes. score_matrix : ``numpy.ndarray``,...
Replace all the parameter values with the averages. Save the current parameter values to restore later. def assign_average_value(self) -> None: """ Replace all the parameter values with the averages. Save the current parameter values to restore later. """ for name, param...
Restore the backed-up (non-average) parameter values. def restore(self) -> None: """ Restore the backed-up (non-average) parameter values. """ for name, parameter in self._parameters: parameter.data.copy_(self._backups[name])
Takes two tensors of the same shape, such as ``(batch_size, length_1, length_2, embedding_dim)``. Computes a (possibly parameterized) similarity on the final dimension and returns a tensor with one less dimension, such as ``(batch_size, length_1, length_2)``. def forward(self, tensor_1: torch.Tensor, ...
This method can be used to prune the set of unfinished states on a beam or finished states at the end of search. In the former case, the states need not be sorted because the all come from the same decoding step, which does the sorting. However, if the states are finished and this method is call...
Returns the best finished states for each batch instance based on model scores. We return at most ``self._max_num_decoded_sequences`` number of sequences per instance. def _get_best_final_states(self, finished_states: List[StateType]) -> Dict[int, List[StateType]]: """ Returns the best finished...
Returns and embedding matrix for the given vocabulary using the pretrained embeddings contained in the given file. Embeddings for tokens not found in the pretrained embedding file are randomly initialized using a normal distribution with mean and standard deviation equal to those of the pretrained embedding...
Read pre-trained word vectors from an eventually compressed text file, possibly contained inside an archive with multiple files. The text file is assumed to be utf-8 encoded with space-separated fields: [word] [dim 1] [dim 2] ... Lines that contain more numerical tokens than ``embedding_dim`` raise a warni...
Reads from a hdf5 formatted file. The embedding matrix is assumed to be keyed by 'embedding' and of size ``(num_tokens, embedding_dim)``. def _read_embeddings_from_hdf5(embeddings_filename: str, embedding_dim: int, vocab: Vocabulary, ...
This function takes in input a string and if it contains 1 or 2 integers, it assumes the largest one it the number of tokens. Returns None if the line doesn't match that pattern. def _get_num_tokens_from_first_line(line: str) -> Optional[int]: """ This function takes in input a string and if it contain...
Gets the embeddings of desired terminal actions yet to be produced by the decoder, and returns their sum for the decoder to add it to the predicted embedding to bias the prediction towards missing actions. def _get_predicted_embedding_addition(self, checklist_s...
Pulls at most ``max_instances_in_memory`` from the input_queue, groups them into batches of size ``batch_size``, converts them to ``TensorDict`` s, and puts them on the ``output_queue``. def _create_tensor_dicts(input_queue: Queue, output_queue: Queue, iterator...
Reads Instances from the iterable and puts them in the input_queue. def _queuer(instances: Iterable[Instance], input_queue: Queue, num_workers: int, num_epochs: Optional[int]) -> None: """ Reads Instances from the iterable and puts them in the input_queue. """ epoch ...