INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
This method returns the indices of each entity s neighbors. A tensor is accepted as a parameter for copying purposes. | def _get_neighbor_indices(worlds: List[WikiTablesWorld],
num_entities: int,
tensor: torch.Tensor) -> torch.LongTensor:
"""
This method returns the indices of each entity's neighbors. A tensor
is accepted as a parameter for copying purpo... |
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. | def _get_type_vector(worlds: List[WikiTablesWorld],
num_entities: int,
tensor: torch.Tensor) -> Tuple[torch.LongTensor, Dict[int, int]]:
"""
Produces a tensor with shape ``(batch_size, num_entities)`` that encodes each entity's
type. In addition,... |
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. | def _get_linking_probabilities(self,
worlds: List[WikiTablesWorld],
linking_scores: torch.FloatTensor,
question_mask: torch.LongTensor,
entity_type_dict: Dict[int, int]) -> torch.F... |
We track three metrics here: | def get_metrics(self, reset: bool = False) -> Dict[str, float]:
"""
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
... |
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. | def _create_grammar_state(self,
world: WikiTablesWorld,
possible_actions: List[ProductionRule],
linking_scores: torch.Tensor,
entity_types: torch.Tensor) -> LambdaGrammarStatelet:
"""
... |
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. | def _compute_validation_outputs(self,
actions: List[List[ProductionRule]],
best_final_states: Mapping[int, Sequence[GrammarBasedState]],
world: List[WikiTablesWorld],
example_l... |
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. | def decode(self, output_dict: Dict[str, torch.Tensor]) -> Dict[str, torch.Tensor]:
"""
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... |
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,
action_ids: List[int],
action_logits: torch.Tensor) -> torch.Tensor:
"""
Gets the logits of desired terminal actions yet to be produced by the decoder, and
... |
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. | def attend_on_question(self,
query: torch.Tensor,
encoder_outputs: torch.Tensor,
encoder_output_mask: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
"""
Given a query (which is typically the decoder hidden state), comp... |
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_paths = [([str(type_)], [f"{START_SYMBOL} -> {type_}"]) for type_ in
s... |
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 k, v in x.fields.items()}
... |
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 them in a dictionary. | def get_padding_lengths(self) -> Dict[str, Dict[str, int]]:
"""
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 ... |
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 the tensors for each field in each ins... | def as_tensor_dict(self,
padding_lengths: Dict[str, Dict[str, int]] = None,
verbose: bool = False) -> Dict[str, Union[torch.Tensor, Dict[str, torch.Tensor]]]:
# This complex return type is actually predefined elsewhere as a DataArray,
# but we can't use it b... |
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 dictionary where the keys are the strings in
the database that map to lists of the token indices that they are linked to.
"""
string_linking_scores: Dict[str, List[i... |
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 scratch. Creating a new grammar i... | def _update_grammar(self):
"""
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 ... |
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_expression_nonterminal: str,
child_expression_nonterminal: str) -> None:
"""
When we add a new 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],
name: str = '') -> Sequence:
"""
This is a helper method for generating sequences, since... |
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 that occur in the ... | def add_to_number_linking_scores(self,
all_numbers: Set[str],
number_linking_scores: Dict[str, Tuple[str, str, List[int]]],
get_number_linking_dict: Callable[[str, List[Token]],
... |
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, Tuple[str, str, List[int]]]]:
"""
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 ... |
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]
"""
all_actions = set()
for _, action_list in self.valid_actions.items():
for action in action_list... |
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 array of shape ( num_entities ... | def _flatten_entities(self) -> Tuple[List[str], numpy.ndarray]:
"""
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 th... |
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)
app = Flask(__name__) # pylint: disable=invalid-name
@app.err... |
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,
args.overrides,
args.file_friendl... |
A wrapper around: func: train_model which loads the params from a file. | def train_model_from_file(parameter_filename: str,
serialization_dir: str,
overrides: str = "",
file_friendly_logging: bool = False,
recover: bool = False,
force: bool = False,
... |
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. | def train_model(params: Params,
serialization_dir: str,
file_friendly_logging: bool = False,
recover: bool = False,
force: bool = False,
cache_directory: str = None,
cache_prefix: str = None) -> Model:
"""
Trains the... |
Performs division and handles divide - by - 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 / denominator
mask = denominator == 0.0
if not mask.any():
return result
# remove nan
result[mask] ... |
One sentence per line formatted like | 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
Returns a list of pairs (tokenized_sentence, tags)
"""
data = []
with open(file_path) as f:
for line in f:
pairs ... |
max_vocab_size limits the size of the vocabulary not including the @@UNKNOWN@@ token. | def pop_max_vocab_size(params: Params) -> Union[int, Dict[str, int]]:
"""
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... |
Persist this Vocabulary to files so it can be reloaded later. Each namespace corresponds to one file. | def save_to_files(self, directory: str) -> None:
"""
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.
... |
Loads a Vocabulary that was serialized using save_to_files. | def from_files(cls, directory: str) -> 'Vocabulary':
"""
Loads a ``Vocabulary`` that was serialized using ``save_to_files``.
Parameters
----------
directory : ``str``
The directory containing the serialized vocabulary.
"""
logger.info("Loading token d... |
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 to use padding and OOV tokens ... | def set_from_file(self,
filename: str,
is_padded: bool = True,
oov_token: str = DEFAULT_OOV_TOKEN,
namespace: str = "tokens"):
"""
If you already have a vocabulary file for a trained model somewhere, and you really w... |
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,
instances: Iterable['adi.Instance'],
min_count: Dict[str, int] = None,
max_vocab_size: Union[int, Dict[str, int]] = None,
non_padded_namespaces: Iterable[str] = DEFAULT_NON_PADDED_NAMESPACES,
... |
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 method wraps these options allo... | def from_params(cls, params: Params, instances: Iterable['adi.Instance'] = None): # type: ignore
"""
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_f... |
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,
counter: Dict[str, Dict[str, int]] = None,
min_count: Dict[str, int] = None,
max_vocab_size: Union[int, Dict[str, int]] = None,
non_padded_namespaces: Iterable[str] = DEFAULT_NON_PADDED_NAMESPACES,
pretrained_files: Option... |
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 instances.
"""
min_count = params.pop("min_count", None)
... |
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_token |
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
the token.
"""
if not isinstance(token, str):
raise ValueError("Vocabulary tokens must be... |
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 regularization.
"""
if self._regularizer is None:
return 0.0
else:
return se... |
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. Before returning the resul... | def forward_on_instance(self, instance: Instance) -> Dict[str, numpy.ndarray]:
"""
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.forwar... |
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 we convert any torch. Te... | def forward_on_instances(self,
instances: List[Instance]) -> List[Dict[str, numpy.ndarray]]:
"""
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
:f... |
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 constrained inference or whatever is... | def decode(self, output_dict: Dict[str, torch.Tensor]) -> Dict[str, torch.Tensor]:
"""
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 probabilitie... |
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. | def _get_prediction_device(self) -> int:
"""
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 ... |
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_for_unseparable_batches(self, output_key: str):
"""
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_... |
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 an already-trained model, based on the experiment
configuration and some optional overrides.
"""
... |
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 an already-trained model, based on the experiment
configuration and some optional overrides.
Parameters... |
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 vocabulary ( original + ... | def extend_embedder_vocab(self, embedding_sources_mapping: Dict[str, str] = None) -> None:
"""
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... |
Returns an agenda that can be used guide search. | def get_agenda(self,
conservative: bool = False):
"""
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
conf... |
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:
"""
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 e... |
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.
"""
return [str(row.values[column.name]) for row in rows if row.values[column.name] is not None] |
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 column name and returns the number in that
column. If multiple rows are given, will return the first number that is not None.
"""
numbers: List[float] = []
... |
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] = []
for row in rows:
cell_value = row.values[column.name]
if isinsta... |
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 that contain
the same value under the given column as the given row.
"""
cell_value = rows[0].values[column.name]
return_list... |
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 that order.
"""
return Date(year, month, day) |
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:
logger.warning("Trying to get first row from an empty list")
return []
return [rows[0]... |
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.warning("Trying to get last row from an empty list")
return []
return [rows[-1]] |
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 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.
"""
if not... |
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 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.
"""
if not row... |
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
that column in those rows.
"""
most_frequent_list = self._get_most_frequent_values(rows, column)
if no... |
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.
"""
most_frequent_list = self._get_most_frequent_values(rows, column)
if not most_frequent_li... |
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.
"""
most_frequent_list = self._get_most_frequent_values(rows, column)
if not most_frequent_list:
... |
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(self, rows: List[Row], column: ComparableColumn) -> List[Row]:
"""
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... |
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, rows: List[Row], column: ComparableColumn) -> List[Row]:
"""
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 b... |
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.
"""
cell_values = [row.values[column.name] for row in rows]
if not cell_values:
return Dat... |
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.
"""
cell_values = [row.values[column.name] for row in rows]
if not cell_values:
retu... |
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.
"""
cell_values = [row.values[column.name] for row in rows]
if not cell_values:
return... |
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 values under
that column in those two rows.
"""
if not first_row or not second_row:
return 0.0 ... |
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: Row) -> int:
"""
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 ta... |
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 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.
"""
... |
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: int = 30,
max_num_paths: int = 10) -> List[List[str]]:
"""
For a given action, returns at most ``max_num_paths`` paths to... |
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.
"""
if self._multi_match_mapping is None:
self._multi_match_mapping = {}
basic_types = sel... |
Takes a logical form as a string maps its tokens using the mapping and returns a parsed expression. | def parse_logical_form(self,
logical_form: str,
remove_var_function: bool = True) -> Expression:
"""
Takes a logical form as a string, maps its tokens using the mapping and returns a parsed expression.
Parameters
----------
l... |
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 expression
return self._get_transitions(expression,
... |
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. | def get_logical_form(self,
action_sequence: List[str],
add_var_function: bool = True) -> str:
"""
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 ... |
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. | def _construct_node_from_actions(self,
current_node: Tree,
remaining_actions: List[List[str]],
add_var_function: bool) -> List[List[str]]:
"""
Given a current node in the logical form tree, and... |
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 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
"""
if no... |
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 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.
"""
expression_is_li... |
Utility method to add a name and its translation to the local name mapping and the corresponding signature if available to the local type signatures. This method also updates the reverse name mapping. | def _add_name_mapping(self, name: str, translated_name: str, name_type: Type = None):
"""
Utility method to add a name and its translation to the local name mapping, and the corresponding
signature, if available to the local type signatures. This method also updates the reverse name
mapp... |
Parameters ---------- inputs: PackedSequence required. A tensor of shape ( batch_size num_timesteps input_size ) to apply the LSTM over. | def forward(self, # pylint: disable=arguments-differ
inputs: PackedSequence,
initial_state: Optional[Tuple[torch.Tensor, torch.Tensor]] = None):
"""
Parameters
----------
inputs : PackedSequence, required.
A tensor of shape (batch_size, num_ti... |
Creates a server running SEMPRE that we can send logical forms to for evaluation. This uses inter - process communication because SEMPRE is java code. We also need to be careful to clean up the process when our program exits. | def _create_sempre_executor(self) -> None:
"""
Creates a server running SEMPRE that we can send logical forms to for evaluation. This
uses inter-process communication, because SEMPRE is java code. We also need to be careful
to clean up the process when our program exits.
"""
... |
Averaged per - mention precision and recall. <https:// pdfs. semanticscholar. org/ cfe3/ c24695f1c14b78a5b8e95bcbd1c666140fd1. pdf > | def b_cubed(clusters, mention_to_gold):
"""
Averaged per-mention precision and recall.
<https://pdfs.semanticscholar.org/cfe3/c24695f1c14b78a5b8e95bcbd1c666140fd1.pdf>
"""
numerator, denominator = 0, 0
for cluster in clusters:
if len(cluster) == 1:
... |
Counts the mentions in each predicted cluster which need to be re - allocated in order for each predicted cluster to be contained by the respective gold cluster. <http:// aclweb. org/ anthology/ M/ M95/ M95 - 1005. pdf > | def muc(clusters, mention_to_gold):
"""
Counts the mentions in each predicted cluster which need to be re-allocated in
order for each predicted cluster to be contained by the respective gold cluster.
<http://aclweb.org/anthology/M/M95/M95-1005.pdf>
"""
true_p, all_p = 0, ... |
Subroutine for ceafe. Computes the mention F measure between gold and predicted mentions in a cluster. | def phi4(gold_clustering, predicted_clustering):
"""
Subroutine for ceafe. Computes the mention F measure between gold and
predicted mentions in a cluster.
"""
return 2 * len([mention for mention in gold_clustering if mention in predicted_clustering]) \
/ float(len... |
Computes the Constrained EntityAlignment F - Measure ( CEAF ) for evaluating coreference. Gold and predicted mentions are aligned into clusterings which maximise a metric - in this case the F measure between gold and predicted clusters. | def ceafe(clusters, gold_clusters):
"""
Computes the Constrained EntityAlignment F-Measure (CEAF) for evaluating coreference.
Gold and predicted mentions are aligned into clusterings which maximise a metric - in
this case, the F measure between gold and predicted clusters.
<htt... |
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. | def take_action(self, production_rule: str) -> 'GrammarStatelet':
"""
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... |
Clips gradient norm of an iterable of parameters. | def sparse_clip_norm(parameters, max_norm, norm_type=2) -> float:
"""Clips gradient norm of an iterable of parameters.
The norm is computed over all gradients together, as if they were
concatenated into a single vector. Gradients are modified in-place.
Supports sparse gradients.
Parameters
---... |
Move the optimizer state to GPU if necessary. After calling any parameter specific state in the optimizer will be located on the same device as the parameter. | def move_optimizer_to_cuda(optimizer):
"""
Move the optimizer state to GPU, if necessary.
After calling, any parameter specific state in the optimizer
will be located on the same device as the parameter.
"""
for param_group in optimizer.param_groups:
for param in param_group['params']:
... |
Returns the size of the batch dimension. Assumes a well - formed batch returns 0 otherwise. | def get_batch_size(batch: Union[Dict, torch.Tensor]) -> int:
"""
Returns the size of the batch dimension. Assumes a well-formed batch,
returns 0 otherwise.
"""
if isinstance(batch, torch.Tensor):
return batch.size(0) # type: ignore
elif isinstance(batch, Dict):
return get_batch_s... |
Convert seconds past Epoch to human readable string. | def time_to_str(timestamp: int) -> str:
"""
Convert seconds past Epoch to human readable string.
"""
datetimestamp = datetime.datetime.fromtimestamp(timestamp)
return '{:04d}-{:02d}-{:02d}-{:02d}-{:02d}-{:02d}'.format(
datetimestamp.year, datetimestamp.month, datetimestamp.day,
... |
Convert human readable string to datetime. datetime. | def str_to_time(time_str: str) -> datetime.datetime:
"""
Convert human readable string to datetime.datetime.
"""
pieces: Any = [int(piece) for piece in time_str.split('-')]
return datetime.datetime(*pieces) |
Load all the datasets specified by the config. | def datasets_from_params(params: Params,
cache_directory: str = None,
cache_prefix: str = None) -> Dict[str, Iterable[Instance]]:
"""
Load all the datasets specified by the config.
Parameters
----------
params : ``Params``
cache_directory : ``st... |
This function creates the serialization directory if it doesn t exist. If it already exists and is non - empty then it verifies that we re recovering from a training with an identical configuration. | def create_serialization_dir(
params: Params,
serialization_dir: str,
recover: bool,
force: bool) -> None:
"""
This function creates the serialization directory if it doesn't exist. If it already exists
and is non-empty, then it verifies that we're recovering from a training... |
Performs a forward pass using multiple GPUs. This is a simplification of torch. nn. parallel. data_parallel to support the allennlp model interface. | def data_parallel(batch_group: List[TensorDict],
model: Model,
cuda_devices: List) -> Dict[str, torch.Tensor]:
"""
Performs a forward pass using multiple GPUs. This is a simplification
of torch.nn.parallel.data_parallel to support the allennlp model
interface.
""... |
Performs gradient rescaling. Is a no - op if gradient rescaling is not enabled. | def rescale_gradients(model: Model, grad_norm: Optional[float] = None) -> Optional[float]:
"""
Performs gradient rescaling. Is a no-op if gradient rescaling is not enabled.
"""
if grad_norm:
parameters_to_clip = [p for p in model.parameters()
if p.grad is not None]
... |
Gets the metrics but sets loss to the total loss divided by the num_batches so that the loss metric is average loss per batch. | def get_metrics(model: Model, total_loss: float, num_batches: int, reset: bool = False) -> Dict[str, float]:
"""
Gets the metrics but sets ``"loss"`` to
the total loss divided by the ``num_batches`` so that
the ``"loss"`` metric is "average loss per batch".
"""
metrics = model.get_metrics(reset=... |
Parse all dependencies out of the requirements. txt file. | def parse_requirements() -> Tuple[PackagesType, PackagesType, Set[str]]:
"""Parse all dependencies out of the requirements.txt file."""
essential_packages: PackagesType = {}
other_packages: PackagesType = {}
duplicates: Set[str] = set()
with open("requirements.txt", "r") as req_file:
section... |
Parse all dependencies out of the setup. py script. | def parse_setup() -> Tuple[PackagesType, PackagesType, Set[str], Set[str]]:
"""Parse all dependencies out of the setup.py script."""
essential_packages: PackagesType = {}
test_packages: PackagesType = {}
essential_duplicates: Set[str] = set()
test_duplicates: Set[str] = set()
with open('setup.p... |
Given a sentence return all token spans within the sentence. Spans are inclusive. Additionally you can provide a maximum and minimum span width which will be used to exclude spans outside of this range. | def enumerate_spans(sentence: List[T],
offset: int = 0,
max_span_width: int = None,
min_span_width: int = 1,
filter_function: Callable[[List[T]], bool] = None) -> List[Tuple[int, int]]:
"""
Given a sentence, return all token spans w... |
Given a sequence corresponding to BIO tags extracts spans. Spans are inclusive and can be of zero length representing a single word span. Ill - formed spans are also included ( i. e those which do not start with a B - LABEL ) as otherwise it is possible to get a perfect precision score whilst still predicting ill - for... | def bio_tags_to_spans(tag_sequence: List[str],
classes_to_ignore: List[str] = None) -> List[TypedStringSpan]:
"""
Given a sequence corresponding to BIO tags, extracts spans.
Spans are inclusive and can be of zero length, representing a single word span.
Ill-formed spans are also in... |
Given a sequence corresponding to IOB1 tags extracts spans. Spans are inclusive and can be of zero length representing a single word span. Ill - formed spans are also included ( i. e. those where B - LABEL is not preceded by I - LABEL or B - LABEL ). | def iob1_tags_to_spans(tag_sequence: List[str],
classes_to_ignore: List[str] = None) -> List[TypedStringSpan]:
"""
Given a sequence corresponding to IOB1 tags, extracts spans.
Spans are inclusive and can be of zero length, representing a single word span.
Ill-formed spans are also... |
Given a sequence corresponding to BIOUL tags extracts spans. Spans are inclusive and can be of zero length representing a single word span. Ill - formed spans are not allowed and will raise InvalidTagSequence. This function works properly when the spans are unlabeled ( i. e. your labels are simply B I O U and L ). | def bioul_tags_to_spans(tag_sequence: List[str],
classes_to_ignore: List[str] = None) -> List[TypedStringSpan]:
"""
Given a sequence corresponding to BIOUL tags, extracts spans.
Spans are inclusive and can be of zero length, representing a single word span.
Ill-formed spans are n... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.