INSTRUCTION stringlengths 1 46.3k | RESPONSE stringlengths 75 80.2k |
|---|---|
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... | def forward(self, # pylint: disable=arguments-differ
inputs: PackedSequence,
initial_state: Optional[Tuple[torch.Tensor, torch.Tensor]] = None) -> \
Tuple[Union[torch.Tensor, PackedSequence], Tuple[torch.Tensor, torch.Tensor]]:
"""
Parameters
--------... |
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... | def substitute_any_type(type_: Type, basic_types: Set[BasicType]) -> List[Type]:
"""
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, ... |
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... | def _get_complex_type_production(complex_type: ComplexType,
multi_match_mapping: Dict[Type, List[Type]]) -> List[Tuple[Type, str]]:
"""
Takes a complex type (without any placeholders), gets its return values, and returns productions
(perhaps each with multiple arguments) tha... |
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... | def get_valid_actions(name_mapping: Dict[str, str],
type_signatures: Dict[str, Type],
basic_types: Set[Type],
multi_match_mapping: Dict[Type, List[Type]] = None,
valid_starting_types: Set[Type] = None,
num_nest... |
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... | def return_type(self) -> Type:
"""
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 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... | def argument_types(self) -> List[Type]:
"""
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-or... |
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
complex type with each of those basic types.
"""
substitutions = []
for first_type in substitute_any_type(sel... |
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_second = other.second.resolve(oth... |
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.resolve(other.second.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... | def _set_type(self, other_type: Type = ANY_TYPE, signature=None) -> None:
"""
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 ... |
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_norm: float) -> None:
"""
Send the mean and std of all parameters and gradients to tensorboard, as well
... |
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_learning_rate:
# optimizer stores lr info keyed by par... |
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:
self.add_train_histogram("parameter_histogram/" ... |
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 all of the train metrics (and validation metrics, if provided) to tensorboard.
... |
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 entries) for an answer
"""
output = []
nl_world = {}
if wo... |
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 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.
"""... |
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)``
... | def multi_perspective_match(vector1: torch.Tensor,
vector2: torch.Tensor,
weight: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
"""
Calculate multi-perspective cosine matching between time-steps of vectors
of the same length.
Parameters
... |
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... | def multi_perspective_match_pairwise(vector1: torch.Tensor,
vector2: torch.Tensor,
weight: torch.Tensor,
eps: float = 1e-8) -> torch.Tensor:
"""
Calculate multi-perspective cosine matching between each... |
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 ... | def forward(self,
context_1: torch.Tensor,
mask_1: torch.Tensor,
context_2: torch.Tensor,
mask_2: torch.Tensor) -> Tuple[List[torch.Tensor], List[torch.Tensor]]:
# pylint: disable=arguments-differ
"""
Given the forward (or backward)... |
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... | def parse_example_line(lisp_string: str) -> Dict:
"""
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>))
... |
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)
"""
# Remove "a:" prefixes from attributes (hack)
logical_form = re.sub(r"\(a:", r"(", lf_raw)
pars... |
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
params = Params.from_file(parameter_path, overrides)
make_vo... |
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],
indices_of_approximate_words: Set[int]) -> Dict[str, List[int]]:
"""
Given an utterance, we get the numbers that correspond to times and convert them to
values t... |
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: int = 1993) -> List[datetime]:
"""
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 n... |
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 get_numbers_from_utterance(utterance: str, tokenized_utterance: List[Token]) -> Dict[str, List[int]]:
"""
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 ... |
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_FOUR]
elif int(digit) % 12 == 0:
return [0, 1200, 2400]
return [int(di... |
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]:
"""
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`... |
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 ... | def _time_regex_match(regex: str,
utterance: str,
char_offset_to_token_index: Dict[int, int],
map_match_to_query_value: Callable[[str], List[int]],
indices_of_approximate_words: Set[int]) -> Dict[str, List[int]]:
r"""
Given ... |
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:
"""
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... |
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.
"""
grammar_string = '\n'.join([f"{nonterminal} = {' / '.join(right_hand_side)}"
... |
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_valid_actions(grammar: Grammar,
keywords_to_uppercase: List[str] = None) -> Dict[str, List[str]]:
"""
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 tabl... |
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... | def format_action(nonterminal: str,
right_hand_side: str,
is_string: bool = False,
is_number: bool = False,
keywords_to_uppercase: List[str] = None) -> str:
"""
This function formats an action as it appears in models. It
splits producti... |
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']:
nonterminal = f'{node.expr.name} -> '
if isinstance(node.expr, Literal):
... |
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 right.
"""
method = getattr(self, 'visit_' + node.expr_name, self.generic_visit)
# Call that method, and show where i... |
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... | def forward(self,
input_ids: torch.LongTensor,
offsets: torch.LongTensor = None,
token_type_ids: torch.LongTensor = None) -> torch.Tensor:
"""
Parameters
----------
input_ids : ``torch.LongTensor``
The (batch_size, ..., max_sequ... |
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
... | def update_grammar_to_be_variable_free(grammar_dictionary: Dict[str, List[str]]):
"""
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 ... |
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 ... | def update_grammar_with_untyped_entities(grammar_dictionary: Dict[str, List[str]]) -> None:
"""
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 ou... |
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 of their own, so they override _load.
"""
model_params = config.get... |
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 = text.replace('´', "'")
text = re.sub(r'''(-+|~+|!+|"+|;+|... |
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[str, Subcommand] = {}) -> None:
"""
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, unle... |
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`` 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.
"""
... |
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... | def main(vocab_path: str,
elmo_config_path: str,
elmo_weights_path: str,
output_dir: str,
batch_size: int,
device: int,
use_custom_oov_token: bool = False):
"""
Creates ELMo word representations from a vocabulary file. These
word representations are _ind... |
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: disable=invalid-sequence-index
vocab: Vocabulary,
padding_noise: float = 0.0) -> List[Instance]:
"""
Sorts the instances by their padding lengths, using the ... |
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_compatible(setup, answer_0):
if self._check_quarels_compatible(setup, answe... |
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 the configured model.
"""
inputs = ''.join(_SINGLE_INPUT_TEMPLATE.substitute(field_name=field_name)
for field... |
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).... | def make_app(predictor: Predictor,
field_names: List[str] = None,
static_dir: str = None,
sanitizer: Callable[[JsonDict], JsonDict] = None,
title: str = "AllenNLP Demo") -> Flask:
"""
Creates a Flask app that serves up the provided ``Predictor``
along with... |
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 docstring for a
description of what we're returning here.
"""
actions = self._valid_actions[self._nonterminal_stack[-... |
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 ... | def take_action(self, production_rule: str) -> 'LambdaGrammarStatelet':
"""
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... |
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... | 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_
spanning tree.
Decode the optimal MST tree with the Chu-Liu-Edmonds algorithm for... |
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``,... | def chu_liu_edmonds(length: int,
score_matrix: numpy.ndarray,
current_nodes: List[bool],
final_edges: Dict[int, int],
old_input: numpy.ndarray,
old_output: numpy.ndarray,
representatives: List[Set[int... |
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, parameter in self._parameters:
self._backups[name].copy_(parameter.data)
parameter.data.copy_(... |
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, tensor_2: torch.Tensor) -> torch.Tensor:
# pylint: disable=arguments-differ
"""
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 dimensi... |
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... | def _prune_beam(states: List[State],
beam_size: int,
sort_states: bool = False) -> List[State]:
"""
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 ... |
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 states for each batch instance based on model scores. We return
at most ``self._max_num_decoded_sequences`` number of sequences per instance.
"""
batch_... |
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... | def _read_embeddings_from_text_file(file_uri: str,
embedding_dim: int,
vocab: Vocabulary,
namespace: str = "tokens") -> torch.FloatTensor:
"""
Read pre-trained word vectors from an eventually compressed t... |
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,
namespace: str = "tokens") -> torch.FloatTensor:
"""
Reads from a hdf5 formatted file. The embedding matrix is assumed to
... |
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 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. """
fields = line.split(' ')
if 1 <= len... |
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_state: ChecklistStatelet,
action_ids: List[int],
action_embeddings: torch.Tensor) -> torch.Tensor:
"""
Gets the embeddings o... |
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: DataIterator,
shuffle: bool,
index: int) -> None:
"""
Pulls at most ``max_instances_in_memory`` from the input_queue,
groups them in... |
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 = 0
while num_epochs is None or epoch < num_epochs:
epoc... |
Returns a list of valid actions for each element of the group. | def get_valid_actions(self) -> List[Dict[str, Tuple[torch.Tensor, torch.Tensor, List[int]]]]:
"""
Returns a list of valid actions for each element of the group.
"""
return [state.get_valid_actions() for state in self.grammar_state] |
A worker that pulls filenames off the input queue, uses the dataset reader
to read them, and places the generated instances on the output queue.
When there are no filenames left on the input queue, it puts its ``index``
on the output queue and doesn't do anything else. | def _worker(reader: DatasetReader,
input_queue: Queue,
output_queue: Queue,
index: int) -> None:
"""
A worker that pulls filenames off the input queue, uses the dataset reader
to read them, and places the generated instances on the output queue.
When there are no file... |
Given labels and a constraint type, returns the allowed transitions. It will
additionally include transitions for the start and end states, which are used
by the conditional random field.
Parameters
----------
constraint_type : ``str``, required
Indicates which constraint to apply. Current ... | def allowed_transitions(constraint_type: str, labels: Dict[int, str]) -> List[Tuple[int, int]]:
"""
Given labels and a constraint type, returns the allowed transitions. It will
additionally include transitions for the start and end states, which are used
by the conditional random field.
Parameters
... |
Given a constraint type and strings ``from_tag`` and ``to_tag`` that
represent the origin and destination of the transition, return whether
the transition is allowed under the given constraint type.
Parameters
----------
constraint_type : ``str``, required
Indicates which constraint to appl... | def is_transition_allowed(constraint_type: str,
from_tag: str,
from_entity: str,
to_tag: str,
to_entity: str):
"""
Given a constraint type and strings ``from_tag`` and ``to_tag`` that
represent the origin... |
Computes the (batch_size,) denominator term for the log-likelihood, which is the
sum of the likelihoods across all possible state sequences. | def _input_likelihood(self, logits: torch.Tensor, mask: torch.Tensor) -> torch.Tensor:
"""
Computes the (batch_size,) denominator term for the log-likelihood, which is the
sum of the likelihoods across all possible state sequences.
"""
batch_size, sequence_length, num_tags = logi... |
Computes the numerator term for the log-likelihood, which is just score(inputs, tags) | def _joint_likelihood(self,
logits: torch.Tensor,
tags: torch.Tensor,
mask: torch.LongTensor) -> torch.Tensor:
"""
Computes the numerator term for the log-likelihood, which is just score(inputs, tags)
"""
batch... |
Computes the log likelihood. | def forward(self,
inputs: torch.Tensor,
tags: torch.Tensor,
mask: torch.ByteTensor = None) -> torch.Tensor:
"""
Computes the log likelihood.
"""
# pylint: disable=arguments-differ
if mask is None:
mask = torch.ones(*tags... |
Uses viterbi algorithm to find most likely tags for the given inputs.
If constraints are applied, disallows all other transitions. | def viterbi_tags(self,
logits: torch.Tensor,
mask: torch.Tensor) -> List[Tuple[List[int], float]]:
"""
Uses viterbi algorithm to find most likely tags for the given inputs.
If constraints are applied, disallows all other transitions.
"""
... |
Given a starting state and a step function, apply beam search to find the
most likely target sequences.
Notes
-----
If your step function returns ``-inf`` for some log probabilities
(like if you're using a masked log-softmax) then some of the "best"
sequences returned ma... | def search(self,
start_predictions: torch.Tensor,
start_state: StateType,
step: StepFunctionType) -> Tuple[torch.Tensor, torch.Tensor]:
"""
Given a starting state and a step function, apply beam search to find the
most likely target sequences.
... |
Parameters
----------
data_directory : str, required.
The path to the data directory of https://github.com/jkkummerfeld/text2sql-data
which has been preprocessed using scripts/reformat_text2sql_data.py.
dataset : str, optional.
The dataset to parse. By default all are parsed.
fil... | def main(data_directory: int, dataset: str = None, filter_by: str = None, verbose: bool = False) -> None:
"""
Parameters
----------
data_directory : str, required.
The path to the data directory of https://github.com/jkkummerfeld/text2sql-data
which has been preprocessed using scripts/re... |
Checks whether the provided obj takes a certain arg.
If it's a class, we're really checking whether its constructor does.
If it's a function or method, we're checking the object itself.
Otherwise, we raise an error. | def takes_arg(obj, arg: str) -> bool:
"""
Checks whether the provided obj takes a certain arg.
If it's a class, we're really checking whether its constructor does.
If it's a function or method, we're checking the object itself.
Otherwise, we raise an error.
"""
if inspect.isclass(obj):
... |
Checks whether a provided object takes in any positional arguments.
Similar to takes_arg, we do this for both the __init__ function of
the class or a function / method
Otherwise, we raise an error | def takes_kwargs(obj) -> bool:
"""
Checks whether a provided object takes in any positional arguments.
Similar to takes_arg, we do this for both the __init__ function of
the class or a function / method
Otherwise, we raise an error
"""
if inspect.isclass(obj):
signature = inspect.sig... |
Optional[X] annotations are actually represented as Union[X, NoneType].
For our purposes, the "Optional" part is not interesting, so here we
throw it away. | def remove_optional(annotation: type):
"""
Optional[X] annotations are actually represented as Union[X, NoneType].
For our purposes, the "Optional" part is not interesting, so here we
throw it away.
"""
origin = getattr(annotation, '__origin__', None)
args = getattr(annotation, '__args__', (... |
Given some class, a `Params` object, and potentially other keyword arguments,
create a dict of keyword args suitable for passing to the class's constructor.
The function does this by finding the class's constructor, matching the constructor
arguments to entries in the `params` object, and instantiating val... | def create_kwargs(cls: Type[T], params: Params, **extras) -> Dict[str, Any]:
"""
Given some class, a `Params` object, and potentially other keyword arguments,
create a dict of keyword args suitable for passing to the class's constructor.
The function does this by finding the class's constructor, matchi... |
Given a dictionary of extra arguments, returns a dictionary of
kwargs that actually are a part of the signature of the cls.from_params
(or cls) method. | def create_extras(cls: Type[T],
extras: Dict[str, Any]) -> Dict[str, Any]:
"""
Given a dictionary of extra arguments, returns a dictionary of
kwargs that actually are a part of the signature of the cls.from_params
(or cls) method.
"""
subextras: Dict[str, Any] = {}
if hasat... |
Does the work of actually constructing an individual argument for :func:`create_kwargs`.
Here we're in the inner loop of iterating over the parameters to a particular constructor,
trying to construct just one of them. The information we get for that parameter is its name,
its type annotation, and its defa... | def construct_arg(cls: Type[T], # pylint: disable=inconsistent-return-statements,too-many-return-statements
param_name: str,
annotation: Type,
default: Any,
params: Params,
**extras) -> Any:
"""
Does the work of actually c... |
This is the automatic implementation of `from_params`. Any class that subclasses `FromParams`
(or `Registrable`, which itself subclasses `FromParams`) gets this implementation for free.
If you want your class to be instantiated from params in the "obvious" way -- pop off parameters
and hand them... | def from_params(cls: Type[T], params: Params, **extras) -> T:
"""
This is the automatic implementation of `from_params`. Any class that subclasses `FromParams`
(or `Registrable`, which itself subclasses `FromParams`) gets this implementation for free.
If you want your class to be instant... |
The main method in the ``TransitionFunction`` API. This function defines the computation
done at each step of decoding and returns a ranked list of next states.
The input state is `grouped`, to allow for efficient computation, but the output states
should all have a ``group_size`` of 1, to mak... | def take_step(self,
state: StateType,
max_actions: int = None,
allowed_actions: List[Set] = None) -> List[StateType]:
"""
The main method in the ``TransitionFunction`` API. This function defines the computation
done at each step of decoding ... |
In PyTorch 1.0, Tensor._sparse_mask was changed to Tensor.sparse_mask.
This wrapper allows AllenNLP to (temporarily) work with both 1.0 and 0.4.1. | def _safe_sparse_mask(tensor: torch.Tensor, mask: torch.Tensor) -> torch.Tensor:
"""
In PyTorch 1.0, Tensor._sparse_mask was changed to Tensor.sparse_mask.
This wrapper allows AllenNLP to (temporarily) work with both 1.0 and 0.4.1.
"""
# pylint: disable=protected-access
try:
return tenso... |
Parses a chunk of text in the SemEval SDP format.
Each word in the sentence is returned as a dictionary with the following
format:
'id': '1',
'form': 'Pierre',
'lemma': 'Pierre',
'pos': 'NNP',
'head': '2', # Note that this is the `syntactic` head.
'deprel': 'nn',
'top': '-',
'... | def parse_sentence(sentence_blob: str) -> Tuple[List[Dict[str, str]], List[Tuple[int, int]], List[str]]:
"""
Parses a chunk of text in the SemEval SDP format.
Each word in the sentence is returned as a dictionary with the following
format:
'id': '1',
'form': 'Pierre',
'lemma': 'Pierre',
... |
Just converts from an ``argparse.Namespace`` object to string paths. | def fine_tune_model_from_args(args: argparse.Namespace):
"""
Just converts from an ``argparse.Namespace`` object to string paths.
"""
fine_tune_model_from_file_paths(model_archive_path=args.model_archive,
config_file=args.config_file,
... |
Disambiguates single GPU and multiple GPU settings for cuda_device param. | def parse_cuda_device(cuda_device: Union[str, int, List[int]]) -> Union[int, List[int]]:
"""
Disambiguates single GPU and multiple GPU settings for cuda_device param.
"""
def from_list(strings):
if len(strings) > 1:
return [int(d) for d in strings]
elif len(strings) == 1:
... |
A wrapper around :func:`fine_tune_model` which loads the model archive from a file.
Parameters
----------
model_archive_path : ``str``
Path to a saved model archive that is the result of running the ``train`` command.
config_file : ``str``
A configuration file specifying how to continue... | def fine_tune_model_from_file_paths(model_archive_path: str,
config_file: str,
serialization_dir: str,
overrides: str = "",
extend_vocab: bool = False,
... |
Fine tunes the given model, using a set of parameters that is largely identical to those used
for :func:`~allennlp.commands.train.train_model`, except that the ``model`` section is ignored,
if it is present (as we are already given a ``Model`` here).
The main difference between the logic done here and the ... | def fine_tune_model(model: Model,
params: Params,
serialization_dir: str,
extend_vocab: bool = False,
file_friendly_logging: bool = False,
batch_weight_key: str = "",
embedding_sources_mapping: Dict[s... |
Extracts the top-k scoring items with respect to the scorer. We additionally return
the indices of the top-k in their original order, not ordered by score, so that downstream
components can rely on the original ordering (e.g., for knowing what spans are valid
antecedents in a coreference resolut... | def forward(self, # pylint: disable=arguments-differ
embeddings: torch.FloatTensor,
mask: torch.LongTensor,
num_items_to_keep: Union[int, torch.LongTensor]) -> Tuple[torch.FloatTensor, torch.LongTensor,
... |
Add the epoch number to the batch instances as a MetadataField. | def add_epoch_number(batch: Batch, epoch: int) -> Batch:
"""
Add the epoch number to the batch instances as a MetadataField.
"""
for instance in batch.instances:
instance.fields['epoch_num'] = MetadataField(epoch)
return batch |
Take the next `max_instances` instances from the given dataset.
If `max_instances` is `None`, then just take all instances from the dataset.
If `max_instances` is not `None`, each call resumes where the previous one
left off, and when you get to the end of the dataset you start again from the be... | def _take_instances(self,
instances: Iterable[Instance],
max_instances: Optional[int] = None) -> Iterator[Instance]:
"""
Take the next `max_instances` instances from the given dataset.
If `max_instances` is `None`, then just take all instances from... |
Breaks the dataset into "memory-sized" lists of instances,
which it yields up one at a time until it gets through a full epoch.
For example, if the dataset is already an in-memory list, and each epoch
represents one pass through the dataset, it just yields back the dataset.
Whereas if t... | def _memory_sized_lists(self,
instances: Iterable[Instance]) -> Iterable[List[Instance]]:
"""
Breaks the dataset into "memory-sized" lists of instances,
which it yields up one at a time until it gets through a full epoch.
For example, if the dataset is alread... |
If self._maximum_samples_per_batch is specified, then split the batch
into smaller sub-batches if it exceeds the maximum size.
Parameters
----------
batch_instances : ``Iterable[Instance]``
A candidate batch.
excess : ``Deque[Instance]``
Instances that we... | def _ensure_batch_is_sufficiently_small(
self,
batch_instances: Iterable[Instance],
excess: Deque[Instance]) -> List[List[Instance]]:
"""
If self._maximum_samples_per_batch is specified, then split the batch
into smaller sub-batches if it exceeds the maximum s... |
Returns the number of batches that ``dataset`` will be split into; if you want to track
progress through the batch with the generator produced by ``__call__``, this could be
useful. | def get_num_batches(self, instances: Iterable[Instance]) -> int:
"""
Returns the number of batches that ``dataset`` will be split into; if you want to track
progress through the batch with the generator produced by ``__call__``, this could be
useful.
"""
if is_lazy(instan... |
This method should return one epoch worth of batches. | def _create_batches(self, instances: Iterable[Instance], shuffle: bool) -> Iterable[Batch]:
"""
This method should return one epoch worth of batches.
"""
raise NotImplementedError |
TQDM and requests use carriage returns to get the training line to update for each batch
without adding more lines to the terminal output. Displaying those in a file won't work
correctly, so we'll just make sure that each batch shows up on its one line.
:param message: the message to permute
:return: t... | def replace_cr_with_newline(message: str):
"""
TQDM and requests use carriage returns to get the training line to update for each batch
without adding more lines to the terminal output. Displaying those in a file won't work
correctly, so we'll just make sure that each batch shows up on its one line.
... |
Converts a list of JSON objects into a list of :class:`~allennlp.data.instance.Instance`s.
By default, this expects that a "batch" consists of a list of JSON blobs which would
individually be predicted by :func:`predict_json`. In order to use this method for
batch prediction, :func:`_json_to_ins... | def _batch_json_to_instances(self, json_dicts: List[JsonDict]) -> List[Instance]:
"""
Converts a list of JSON objects into a list of :class:`~allennlp.data.instance.Instance`s.
By default, this expects that a "batch" consists of a list of JSON blobs which would
individually be predicted ... |
Context manager that captures the internal-module outputs of
this predictor's model. The idea is that you could use it as follows:
.. code-block:: python
with predictor.capture_model_internals() as internals:
outputs = predictor.predict_json(inputs)
return {**o... | def capture_model_internals(self) -> Iterator[dict]:
"""
Context manager that captures the internal-module outputs of
this predictor's model. The idea is that you could use it as follows:
.. code-block:: python
with predictor.capture_model_internals() as internals:
... |
Instantiate a :class:`Predictor` from an archive path.
If you need more detailed configuration options, such as running the predictor on the GPU,
please use `from_archive`.
Parameters
----------
archive_path The path to the archive.
Returns
-------
A Pr... | def from_path(cls, archive_path: str, predictor_name: str = None) -> 'Predictor':
"""
Instantiate a :class:`Predictor` from an archive path.
If you need more detailed configuration options, such as running the predictor on the GPU,
please use `from_archive`.
Parameters
... |
Instantiate a :class:`Predictor` from an :class:`~allennlp.models.archival.Archive`;
that is, from the result of training a model. Optionally specify which `Predictor`
subclass; otherwise, the default one for the model will be used. | def from_archive(cls, archive: Archive, predictor_name: str = None) -> 'Predictor':
"""
Instantiate a :class:`Predictor` from an :class:`~allennlp.models.archival.Archive`;
that is, from the result of training a model. Optionally specify which `Predictor`
subclass; otherwise, the default... |
Compute 'Scaled Dot Product Attention | def attention(query: torch.Tensor,
key: torch.Tensor,
value: torch.Tensor,
mask: torch.Tensor = None,
dropout: Callable = None) -> Tuple[torch.Tensor, torch.Tensor]:
"""Compute 'Scaled Dot Product Attention'"""
d_k = query.size(-1)
scores = torch.matmu... |
Mask out subsequent positions. | def subsequent_mask(size: int, device: str = 'cpu') -> torch.Tensor:
"""Mask out subsequent positions."""
mask = torch.tril(torch.ones(size, size, device=device, dtype=torch.int32)).unsqueeze(0)
return mask |
Helper: Construct a model from hyperparameters. | def make_model(num_layers: int = 6,
input_size: int = 512, # Attention size
hidden_size: int = 2048, # FF layer size
heads: int = 8,
dropout: float = 0.1,
return_all_layers: bool = False) -> TransformerEncoder:
"""Helper: Construct a model... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.