INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Convert a list of strings to a list of Values
def to_value_list(original_strings, corenlp_values=None): """Convert a list of strings to a list of Values Args: original_strings (list[basestring]) corenlp_values (list[basestring or None]) Returns: list[Value] """ assert isinstance(original_strings, (list, tuple, set)) ...
Return True if the predicted denotation is correct.
def check_denotation(target_values, predicted_values): """Return True if the predicted denotation is correct. Args: target_values (list[Value]) predicted_values (list[Value]) Returns: bool """ # Check size if len(target_values) != len(predicted_values): return Fa...
Try to parse into a number.
def parse(text): """Try to parse into a number. Return: the number (int or float) if successful; otherwise None. """ try: return int(text) except ValueError: try: amount = float(text) assert not isnan(amount) an...
Try to parse into a date.
def parse(text): """Try to parse into a date. Return: tuple (year, month, date) if successful; otherwise None. """ try: ymd = text.lower().split('-') assert len(ymd) == 3 year = -1 if ymd[0] in ('xx', 'xxxx') else int(ymd[0]) m...
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.
def forward(self, # pylint: disable=arguments-differ sequence_tensor: torch.FloatTensor, span_indices: torch.LongTensor, sequence_mask: torch.LongTensor = None, span_indices_mask: torch.LongTensor = None): """ Given a sequence tensor, extra...
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. prefix: str default = The prefix to prepend to the ...
def main(serialization_directory: int, device: int, data: str, prefix: str, domain: str = None): """ serialization_directory : str, required. The directory containing the serialized weights. device: int, default = -1 The device to run the evaluation on. ...
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.
def decode(self, initial_state: State, transition_function: TransitionFunction, supervision: SupervisionType) -> Dict[str, torch.Tensor]: """ Takes an initial state object, a means of transitioning from state to state, and a supervision signal, and us...
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.
def load_state_dict(self, state_dict: Dict[str, Any]) -> None: """ Load the schedulers state. Parameters ---------- state_dict : ``Dict[str, Any]`` Scheduler state. Should be an object returned from a call to ``state_dict``. """ self.__dict__.update(s...
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 trailing dimension for the characters in each token ). num_wrapp...
def forward(self, # pylint: disable=arguments-differ text_field_input: Dict[str, torch.Tensor], num_wrapping_dims: int = 0) -> torch.Tensor: """ Parameters ---------- text_field_input : ``Dict[str, torch.Tensor]`` A dictionary that was the out...
Identifies the best prediction given the results from the submodels.
def ensemble(subresults: List[Dict[str, torch.Tensor]]) -> torch.Tensor: """ 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 sub...
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 each sequence in the batch.
def forward(self, # pylint: disable=arguments-differ inputs: torch.Tensor, mask: torch.LongTensor) -> torch.Tensor: """ Parameters ---------- inputs : ``torch.Tensor``, required. A Tensor of shape ``(batch_size, sequence_length, hidden_size)``...
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 memory of the LSTM with shape ( num_layers batch_size 2 * ...
def _lstm_forward(self, inputs: PackedSequence, initial_state: Optional[Tuple[torch.Tensor, torch.Tensor]] = None) -> \ Tuple[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]: """ Parameters ---------- inputs : ``PackedSequence``, r...
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( zip(self.forward_layers...
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 memory of the LSTM. Each tensor has shape ( 1 batch_size o...
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 placeholders with diffe...
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 all the substituti...
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 example the function ...
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 the base class. If you have a higher ...
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 need to override this method.
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 against a. We do this as the ad...
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.
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.
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.
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 > ) ( description <answer2 > )... )))
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>)) ...
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...
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...
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.
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 grammar string because these might...
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 original token. In that case offsets represents the indices of the des...
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 grammar because we...
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 with value.
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 to be an unknow...
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...
Creates a Flask app that serves up the provided Predictor along with a front - end for interacting with it.
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 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...
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.
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.
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.
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 called at the end of the search...
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_...
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 embeddings.
def _read_pretrained_embeddings_file(file_uri: str, embedding_dim: int, vocab: Vocabulary, namespace: str = "tokens") -> torch.FloatTensor: """ Returns and embedding matrix for the given vocabulary usi...
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 ]...
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.
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.
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.
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. filter_by: str optional Compute statist...
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.
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.
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 to your constructor with the sam...
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.
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.
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', ...
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: ...
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, ...
A wrapper around: func: fine_tune_model which loads the model archive from a file.
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 ).
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...