Code
stringlengths
103
85.9k
Summary
listlengths
0
94
Please provide a description of the function:def read_dataset_schema(schema_path: str) -> Dict[str, List[TableColumn]]: schema: Dict[str, List[TableColumn]] = defaultdict(list) for i, line in enumerate(open(schema_path, "r")): if i == 0: header = [x.strip() for x in line.split(",")] ...
[ "\n Reads a schema from the text2sql data, returning a dictionary\n mapping table names to their columns and respective types.\n This handles columns in an arbitrary order and also allows\n either ``{Table, Field}`` or ``{Table, Field} Name`` as headers,\n because both appear in the data. It also upp...
Please provide a description of the function:def process_sql_data(data: List[JsonDict], use_all_sql: bool = False, use_all_queries: bool = False, remove_unneeded_aliases: bool = False, schema: Dict[str, List[TableColumn]] = None) -> Ite...
[ "\n A utility function for reading in text2sql data. The blob is\n the result of loading the json from a file produced by the script\n ``scripts/reformat_text2sql_data.py``.\n\n Parameters\n ----------\n data : ``JsonDict``\n use_all_sql : ``bool``, optional (default = False)\n Whether t...
Please provide a description of the function:def sort_and_run_forward(self, module: Callable[[PackedSequence, Optional[RnnState]], Tuple[Union[PackedSequence, torch.Tensor], RnnState]], inputs: torch.Tensor, ...
[ "\n This function exists because Pytorch RNNs require that their inputs be sorted\n before being passed as input. As all of our Seq2xxxEncoders use this functionality,\n it is provided in a base class. This method can be called on any module which\n takes as input a ``PackedSequence`` an...
Please provide a description of the function:def _get_initial_states(self, batch_size: int, num_valid: int, sorting_indices: torch.LongTensor) -> Optional[RnnState]: # We don't know the state sizes the first time callin...
[ "\n Returns an initial state for use in an RNN. Additionally, this method handles\n the batch size changing across calls by mutating the state to append initial states\n for new elements in the batch. Finally, it also handles sorting the states\n with respect to the sequence lengths of e...
Please provide a description of the function:def _update_states(self, final_states: RnnStateStorage, restoration_indices: torch.LongTensor) -> None: # TODO(Mark): seems weird to sort here, but append zeros in the subclasses. # which way around is be...
[ "\n After the RNN has run forward, the states need to be updated.\n This method just sets the state to the updated new state, performing\n several pieces of book-keeping along the way - namely, unsorting the\n states and ensuring that the states of completely padded sequences are\n ...
Please provide a description of the function:def construct_prefix_tree(targets: Union[torch.Tensor, List[List[List[int]]]], target_mask: Optional[torch.Tensor] = None) -> List[Dict[Tuple[int, ...], Set[int]]]: batched_allowed_transitions: List[Dict[Tuple[int, ...], Set[int]]] = [] ...
[ "\n Takes a list of valid target action sequences and creates a mapping from all possible\n (valid) action prefixes to allowed actions given that prefix. While the method is called\n ``construct_prefix_tree``, we're actually returning a map that has as keys the paths to\n `all internal nodes of the tri...
Please provide a description of the function:def to_value(original_string, corenlp_value=None): if isinstance(original_string, Value): # Already a Value return original_string if not corenlp_value: corenlp_value = original_string # Number? amount = NumberValue.parse(corenlp_...
[ "Convert the string to Value object.\n\n Args:\n original_string (basestring): Original string\n corenlp_value (basestring): Optional value returned from CoreNLP\n Returns:\n Value\n " ]
Please provide a description of the function:def to_value_list(original_strings, corenlp_values=None): assert isinstance(original_strings, (list, tuple, set)) if corenlp_values is not None: assert isinstance(corenlp_values, (list, tuple, set)) assert len(original_strings) == len(corenlp_val...
[ "Convert a list of strings to a list of Values\n\n Args:\n original_strings (list[basestring])\n corenlp_values (list[basestring or None])\n Returns:\n list[Value]\n " ]
Please provide a description of the function:def check_denotation(target_values, predicted_values): # Check size if len(target_values) != len(predicted_values): return False # Check items for target in target_values: if not any(target.match(pred) for pred in predicted_values): ...
[ "Return True if the predicted denotation is correct.\n\n Args:\n target_values (list[Value])\n predicted_values (list[Value])\n Returns:\n bool\n " ]
Please provide a description of the function:def parse(text): try: return int(text) except ValueError: try: amount = float(text) assert not isnan(amount) and not isinf(amount) return amount except (ValueError, A...
[ "Try to parse into a number.\n\n Return:\n the number (int or float) if successful; otherwise None.\n " ]
Please provide a description of the function:def parse(text): try: ymd = text.lower().split('-') assert len(ymd) == 3 year = -1 if ymd[0] in ('xx', 'xxxx') else int(ymd[0]) month = -1 if ymd[1] == 'xx' else int(ymd[1]) day = -1 if ymd[2] == 'x...
[ "Try to parse into a date.\n\n Return:\n tuple (year, month, date) if successful; otherwise None.\n " ]
Please provide a description of the function: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): ...
[ "\n Given a sequence tensor, extract spans and return representations of\n them. Span representation can be computed in many different ways,\n such as concatenation of the start and end spans, attention over the\n vectors contained inside the span, etc.\n\n Parameters\n ---...
Please provide a description of the function:def main(serialization_directory: int, device: int, data: str, prefix: str, domain: str = None): config = Params.from_file(os.path.join(serialization_directory, "config.json")) if domain is not None: # Hack to allow e...
[ "\n serialization_directory : str, required.\n The directory containing the serialized weights.\n device: int, default = -1\n The device to run the evaluation on.\n data: str, default = None\n The data to evaluate on. By default, we use the validation data from\n the original ex...
Please provide a description of the function:def decode(self, initial_state: State, transition_function: TransitionFunction, supervision: SupervisionType) -> Dict[str, torch.Tensor]: raise NotImplementedError
[ "\n Takes an initial state object, a means of transitioning from state to state, and a\n supervision signal, and uses the supervision to train the transition function to pick\n \"good\" states.\n\n This function should typically return a ``loss`` key during training, which the ``Model``\...
Please provide a description of the function:def state_dict(self) -> Dict[str, Any]: return {key: value for key, value in self.__dict__.items() if key != 'optimizer'}
[ "\n Returns the state of the scheduler as a ``dict``.\n " ]
Please provide a description of the function:def load_state_dict(self, state_dict: Dict[str, Any]) -> None: self.__dict__.update(state_dict)
[ "\n Load the schedulers state.\n\n Parameters\n ----------\n state_dict : ``Dict[str, Any]``\n Scheduler state. Should be an object returned from a call to ``state_dict``.\n " ]
Please provide a description of the function:def forward(self, # pylint: disable=arguments-differ text_field_input: Dict[str, torch.Tensor], num_wrapping_dims: int = 0) -> torch.Tensor: raise NotImplementedError
[ "\n Parameters\n ----------\n text_field_input : ``Dict[str, torch.Tensor]``\n A dictionary that was the output of a call to ``TextField.as_tensor``. Each tensor in\n here is assumed to have a shape roughly similar to ``(batch_size, sequence_length)``\n (perhap...
Please provide a description of the function:def ensemble(subresults: List[Dict[str, torch.Tensor]]) -> torch.Tensor: # Choose the highest average confidence span. span_start_probs = sum(subresult['span_start_probs'] for subresult in subresults) / len(subresults) span_end_probs = sum(subresult['span_...
[ "\n Identifies the best prediction given the results from the submodels.\n\n Parameters\n ----------\n subresults : List[Dict[str, torch.Tensor]]\n Results of each submodel.\n\n Returns\n -------\n The index of the best submodel.\n " ]
Please provide a description of the function:def forward(self, # pylint: disable=arguments-differ inputs: torch.Tensor, mask: torch.LongTensor) -> torch.Tensor: batch_size, total_sequence_length = mask.size() stacked_sequence_output, final_states, restoration_in...
[ "\n Parameters\n ----------\n inputs : ``torch.Tensor``, required.\n A Tensor of shape ``(batch_size, sequence_length, hidden_size)``.\n mask : ``torch.LongTensor``, required.\n A binary mask of shape ``(batch_size, sequence_length)`` representing the\n n...
Please provide a description of the function:def _lstm_forward(self, inputs: PackedSequence, initial_state: Optional[Tuple[torch.Tensor, torch.Tensor]] = None) -> \ Tuple[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]: if initial_state is None: ...
[ "\n Parameters\n ----------\n inputs : ``PackedSequence``, required.\n A batch first ``PackedSequence`` to run the stacked LSTM over.\n initial_state : ``Tuple[torch.Tensor, torch.Tensor]``, optional, (default = None)\n A tuple (state, memory) representing the initi...
Please provide a description of the function:def load_weights(self, weight_file: str) -> None: 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, self.backward_layers...
[ "\n Load the pre-trained weights from the file.\n " ]
Please provide a description of the function: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]]: ...
[ "\n Parameters\n ----------\n inputs : ``PackedSequence``, required.\n A batch first ``PackedSequence`` to run the stacked LSTM over.\n initial_state : Tuple[torch.Tensor, torch.Tensor], optional, (default = None)\n A tuple (state, memory) representing the initial h...
Please provide a description of the function:def substitute_any_type(type_: Type, basic_types: Set[BasicType]) -> List[Type]: if type_ == ANY_TYPE: return list(basic_types) if isinstance(type_, BasicType): return [type_] # If we've made it this far, we have a ComplexType, and we can jus...
[ "\n Takes a type and a set of basic types, and substitutes all instances of ANY_TYPE with all\n possible basic types and returns a list with all possible combinations. Note that this\n substitution is unconstrained. That is, If you have a type with placeholders, <#1,#1> for\n example, this may substit...
Please provide a description of the function:def _get_complex_type_production(complex_type: ComplexType, multi_match_mapping: Dict[Type, List[Type]]) -> List[Tuple[Type, str]]: return_type = complex_type.return_type() if isinstance(return_type, MultiMatchNamedBasicType): ...
[ "\n Takes a complex type (without any placeholders), gets its return values, and returns productions\n (perhaps each with multiple arguments) that produce the return values. This method also takes\n care of ``MultiMatchNamedBasicTypes``. If one of the arguments or the return types is a multi\n match ty...
Please provide a description of 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...
[ "\n Generates all the valid actions starting from each non-terminal. For terminals of a specific\n type, we simply add a production from the type to the terminal. For all terminal `functions`,\n we additionally add a rule that allows their return type to be generated from an application of\n the functio...
Please provide a description of the function:def return_type(self) -> Type: return_type = self.second while isinstance(return_type, ComplexType): return_type = return_type.second return return_type
[ "\n Gives the final return type for this function. If the function takes a single argument,\n this is just ``self.second``. If the function takes multiple arguments and returns a basic\n type, this should be the final ``.second`` after following all complex types. That is the\n implem...
Please provide a description of the function:def argument_types(self) -> List[Type]: arguments = [self.first] remaining_type = self.second while isinstance(remaining_type, ComplexType): arguments.append(remaining_type.first) remaining_type = remaining_type.second...
[ "\n Gives the types of all arguments to this function. For functions returning a basic type,\n we grab all ``.first`` types until ``.second`` is no longer a ``ComplexType``. That logic\n is implemented here in the base class. If you have a higher-order function that returns a\n functi...
Please provide a description of the function:def substitute_any_type(self, basic_types: Set[BasicType]) -> List[Type]: substitutions = [] for first_type in substitute_any_type(self.first, basic_types): for second_type in substitute_any_type(self.second, basic_types): ...
[ "\n Takes a set of ``BasicTypes`` and replaces any instances of ``ANY_TYPE`` inside this\n complex type with each of those basic types.\n " ]
Please provide a description of the function:def resolve(self, other) -> Optional[Type]: if not isinstance(other, NltkComplexType): return None other_first = other.first.resolve(other.second) if not other_first: return None other_second = other.second.res...
[ "See ``PlaceholderType.resolve``" ]
Please provide a description of the function:def resolve(self, other: Type) -> Optional[Type]: if not isinstance(other, NltkComplexType): return None if not isinstance(other.second, NltkComplexType): return None other_first = other.first.resolve(other.second.firs...
[ "See ``PlaceholderType.resolve``" ]
Please provide a description of the function:def _set_type(self, other_type: Type = ANY_TYPE, signature=None) -> None: super(DynamicTypeApplicationExpression, self)._set_type(other_type, signature) # TODO(pradeep): Assuming the mapping of "var" function is "V". Do something better. if i...
[ "\n We override this method to do just one thing on top of ``ApplicationExpression._set_type``.\n In lambda expressions of the form /x F(x), where the function is F and the argument is x,\n we can use the type of F to infer the type of x. That is, if F is of type <a, b>, we can\n resolve...
Please provide a description of the function:def log_parameter_and_gradient_statistics(self, # pylint: disable=invalid-name model: Model, batch_grad_norm: float) -> None: if self._should_log_parameter_statistics...
[ "\n Send the mean and std of all parameters and gradients to tensorboard, as well\n as logging the average gradient norm.\n " ]
Please provide a description of the function:def log_learning_rates(self, model: Model, optimizer: torch.optim.Optimizer): if self._should_log_learning_rate: # optimizer stores lr info keyed by parameter tensor # we want to l...
[ "\n Send current parameter specific learning rates to tensorboard\n " ]
Please provide a description of the function:def log_histograms(self, model: Model, histogram_parameters: Set[str]) -> None: for name, param in model.named_parameters(): if name in histogram_parameters: self.add_train_histogram("parameter_histogram/" + name, param)
[ "\n Send histograms of parameters to tensorboard.\n " ]
Please provide a description of the function:def log_metrics(self, train_metrics: dict, val_metrics: dict = None, epoch: int = None, log_to_console: bool = False) -> None: metric_names = set(train_metrics.keys()) if...
[ "\n Sends all of the train metrics (and validation metrics, if provided) to tensorboard.\n " ]
Please provide a description of the function:def get_explanation(logical_form: str, world_extractions: JsonDict, answer_index: int, world: QuarelWorld) -> List[JsonDict]: output = [] nl_world = {} if world_extractions['world1'] != "N/A" and wo...
[ "\n Create explanation (as a list of header/content entries) for an answer\n " ]
Please provide a description of the function:def align_entities(extracted: List[str], literals: JsonDict, stemmer: NltkPorterStemmer) -> List[str]: literal_keys = list(literals.keys()) literal_values = list(literals.values()) overlaps = [get_stem_overlaps(extract, ...
[ "\n Use stemming to attempt alignment between extracted world and given world literals.\n If more words align to one world vs the other, it's considered aligned.\n " ]
Please provide a description of the function:def multi_perspective_match(vector1: torch.Tensor, vector2: torch.Tensor, weight: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]: assert vector1.size(0) == vector2.size(0) assert weight.size(1) == vecto...
[ "\n Calculate multi-perspective cosine matching between time-steps of vectors\n of the same length.\n\n Parameters\n ----------\n vector1 : ``torch.Tensor``\n A tensor of shape ``(batch, seq_len, hidden_size)``\n vector2 : ``torch.Tensor``\n A tensor of shape ``(batch, seq_len or 1, ...
Please provide a description of the function:def multi_perspective_match_pairwise(vector1: torch.Tensor, vector2: torch.Tensor, weight: torch.Tensor, eps: float = 1e-8) -> torch.Tensor: num_perspectiv...
[ "\n Calculate multi-perspective cosine matching between each time step of\n one vector and each time step of another vector.\n\n Parameters\n ----------\n vector1 : ``torch.Tensor``\n A tensor of shape ``(batch, seq_len1, hidden_size)``\n vector2 : ``torch.Tensor``\n A tensor of shap...
Please provide a description of the function: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 ...
[ "\n Given the forward (or backward) representations of sentence1 and sentence2, apply four bilateral\n matching functions between them in one direction.\n\n Parameters\n ----------\n context_1 : ``torch.Tensor``\n Tensor of shape (batch_size, seq_len1, hidden_dim) repre...
Please provide a description of the function:def parse_example_line(lisp_string: str) -> Dict: id_piece, rest = lisp_string.split(') (utterance "') example_id = id_piece.split('(id ')[1] question, rest = rest.split('") (context (graph tables.TableKnowledgeGraph ') table_filename, rest = rest.split(...
[ "\n Training data in WikitableQuestions comes with examples in the form of lisp strings in the format:\n (example (id <example-id>)\n (utterance <question>)\n (context (graph tables.TableKnowledgeGraph <table-filename>))\n (targetValue (list (description <an...
Please provide a description of the function:def make_vocab_from_args(args: argparse.Namespace): parameter_path = args.param_path overrides = args.overrides serialization_dir = args.serialization_dir params = Params.from_file(parameter_path, overrides) make_vocab_from_params(params, serializa...
[ "\n Just converts from an ``argparse.Namespace`` object to params.\n " ]
Please provide a description of the function:def execute(self, lf_raw: str) -> int: # Remove "a:" prefixes from attributes (hack) logical_form = re.sub(r"\(a:", r"(", lf_raw) parse = semparse_util.lisp_to_nested_expression(logical_form) if len(parse) < 2: return -1 ...
[ "\n Very basic model for executing friction logical forms. For now returns answer index (or\n -1 if no answer can be concluded)\n " ]
Please provide a description of the function: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]]: pm_linking_dict = _time_regex_match(r'\d+pm', ...
[ "\n Given an utterance, we get the numbers that correspond to times and convert them to\n values that may appear in the query. For example: convert ``7pm`` to ``1900``.\n " ]
Please provide a description of the function:def get_date_from_utterance(tokenized_utterance: List[Token], year: int = 1993) -> List[datetime]: dates = [] utterance = ' '.join([token.text for token in tokenized_utterance]) year_result = re.findall(r'199[0-4]', utterance) ...
[ "\n When the year is not explicitly mentioned in the utterance, the query assumes that\n it is 1993 so we do the same here. If there is no mention of the month or day then\n we do not return any dates from the utterance.\n " ]
Please provide a description of the function:def get_numbers_from_utterance(utterance: str, tokenized_utterance: List[Token]) -> Dict[str, List[int]]: # When we use a regex to find numbers or strings, we need a mapping from # the character to which token triggered it. char_offset_to_token_index = {toke...
[ "\n Given an utterance, this function finds all the numbers that are in the action space. Since we need to\n keep track of linking scores, we represent the numbers as a dictionary, where the keys are the string\n representation of the number and the values are lists of the token indices that triggers that ...
Please provide a description of the function:def digit_to_query_time(digit: str) -> List[int]: if len(digit) > 2: return [int(digit), int(digit) + TWELVE_TO_TWENTY_FOUR] elif int(digit) % 12 == 0: return [0, 1200, 2400] return [int(digit) * HOUR_TO_TWENTY_FOUR, (int(digit) *...
[ "\n Given a digit in the utterance, return a list of the times that it corresponds to.\n " ]
Please provide a description of the function:def get_approximate_times(times: List[int]) -> List[int]: approximate_times = [] for time in times: hour = int(time/HOUR_TO_TWENTY_FOUR) % 24 minute = time % HOUR_TO_TWENTY_FOUR approximate_time = datetime.now() approximate_time =...
[ "\n Given a list of times that follow a word such as ``about``,\n we return a list of times that could appear in the query as a result\n of this. For example if ``about 7pm`` appears in the utterance, then\n we also want to add ``1830`` and ``1930``.\n " ]
Please provide a description of the function: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])...
[ "\n Given a regex for matching times in the utterance, we want to convert the matches\n to the values that appear in the query and token indices they correspond to.\n\n ``char_offset_to_token_index`` is a dictionary that maps from the character offset to\n the token index, we use this to look up what to...
Please provide a description of the function:def _evaluate_sql_query_subprocess(self, predicted_query: str, sql_query_labels: List[str]) -> int: postprocessed_predicted_query = self.postprocess_query_sqlite(predicted_query) try: self._cursor.execute(postprocessed_predicted_query) ...
[ "\n We evaluate here whether the predicted query and the query label evaluate to the\n exact same table. This method is only called by the subprocess, so we just exit with\n 1 if it is correct and 0 otherwise.\n " ]
Please provide a description of the function:def format_grammar_string(grammar_dictionary: Dict[str, List[str]]) -> str: grammar_string = '\n'.join([f"{nonterminal} = {' / '.join(right_hand_side)}" for nonterminal, right_hand_side in grammar_dictionary.items()]) return gramm...
[ "\n Formats a dictionary of production rules into the string format expected\n by the Parsimonious Grammar class.\n " ]
Please provide a description of the function:def initialize_valid_actions(grammar: Grammar, keywords_to_uppercase: List[str] = None) -> Dict[str, List[str]]: valid_actions: Dict[str, Set[str]] = defaultdict(set) for key in grammar: rhs = grammar[key] # Sequenc...
[ "\n We initialize the valid actions with the global actions. These include the\n valid actions that result from the grammar and also those that result from\n the tables provided. The keys represent the nonterminals in the grammar\n and the values are lists of the valid actions of that nonterminal.\n ...
Please provide a description of the function:def format_action(nonterminal: str, right_hand_side: str, is_string: bool = False, is_number: bool = False, keywords_to_uppercase: List[str] = None) -> str: keywords_to_uppercase = keywords_to_u...
[ "\n This function formats an action as it appears in models. It\n splits productions based on the special `ws` and `wsp` rules,\n which are used in grammars to denote whitespace, and then\n rejoins these tokens a formatted, comma separated list.\n Importantly, note that it `does not` split on spaces ...
Please provide a description of the function:def add_action(self, node: Node) -> None: if node.expr.name and node.expr.name not in ['ws', 'wsp']: nonterminal = f'{node.expr.name} -> ' if isinstance(node.expr, Literal): right_hand_side = f'["{node.text}"]' ...
[ "\n For each node, we accumulate the rules that generated its children in a list.\n " ]
Please provide a description of the function:def visit(self, node): method = getattr(self, 'visit_' + node.expr_name, self.generic_visit) # Call that method, and show where in the tree it failed if it blows # up. try: # Changing this to reverse here! ret...
[ "\n See the ``NodeVisitor`` visit method. This just changes the order in which\n we visit nonterminals from right to left to left to right.\n " ]
Please provide a description of the function:def forward(self, input_ids: torch.LongTensor, offsets: torch.LongTensor = None, token_type_ids: torch.LongTensor = None) -> torch.Tensor: # pylint: disable=arguments-differ if token_type_ids is None: ...
[ "\n Parameters\n ----------\n input_ids : ``torch.LongTensor``\n The (batch_size, ..., max_sequence_length) tensor of wordpiece ids.\n offsets : ``torch.LongTensor``, optional\n The BERT embeddings are one per wordpiece. However it's possible/likely\n you...
Please provide a description of the function:def update_grammar_to_be_variable_free(grammar_dictionary: Dict[str, List[str]]): # Tables in variable free grammars cannot be aliased, so we # remove this functionality from the grammar. grammar_dictionary["select_result"] = ['"*"', '(table_name ws ".*")',...
[ "\n SQL is a predominately variable free language in terms of simple usage, in the\n sense that most queries do not create references to variables which are not\n already static tables in a dataset. However, it is possible to do this via\n derived tables. If we don't require this functionality, we can t...
Please provide a description of the function:def update_grammar_with_untyped_entities(grammar_dictionary: Dict[str, List[str]]) -> None: grammar_dictionary["string_set_vals"] = ['(value ws "," ws string_set_vals)', 'value'] grammar_dictionary["value"].remove('string') grammar_dictionary["value"].remove...
[ "\n Variables can be treated as numbers or strings if their type can be inferred -\n however, that can be difficult, so instead, we can just treat them all as values\n and be a bit looser on the typing we allow in our grammar. Here we just remove\n all references to number and string from the grammar, r...
Please provide a description of the function:def _load(cls, config: Params, serialization_dir: str, weights_file: str = None, cuda_device: int = -1) -> 'Model': model_params = config.get('model') # The experiment config tells us how to _t...
[ "\n Ensembles don't have vocabularies or weights of their own, so they override _load.\n " ]
Please provide a description of the function:def text_standardize(text): text = text.replace('—', '-') text = text.replace('–', '-') text = text.replace('―', '-') text = text.replace('…', '...') text = text.replace('´', "'") text = re.sub(r'''(-+|~+|!+|"+|;+|\?+|\++|,+|\)+|\(+|\\+|\/+|\*+|\...
[ "\n Apply text standardization following original implementation.\n " ]
Please provide a description of the function:def main(prog: str = None, subcommand_overrides: Dict[str, Subcommand] = {}) -> None: # pylint: disable=dangerous-default-value parser = ArgumentParserWithDefaults(description="Run AllenNLP", usage='%(prog)s', prog=prog) parser.add_argument('--versi...
[ "\n The :mod:`~allennlp.run` command only knows about the registered classes in the ``allennlp``\n codebase. In particular, once you start creating your own ``Model`` s and so forth, it won't\n work for them, unless you use the ``--include-package`` flag.\n " ]
Please provide a description of the function:def get_padding_lengths(self) -> Dict[str, int]: # Our basic outline: we will iterate over `TokenIndexers`, and aggregate lengths over tokens # for each indexer separately. Then we will combine the results for each indexer into a single # di...
[ "\n The ``TextField`` has a list of ``Tokens``, and each ``Token`` gets converted into arrays by\n (potentially) several ``TokenIndexers``. This method gets the max length (over tokens)\n associated with each of these arrays.\n " ]
Please provide a description of the function: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): # Load the vocabulary words and convert to char ids ...
[ "\n Creates ELMo word representations from a vocabulary file. These\n word representations are _independent_ - they are the result of running\n the CNN and Highway layers of the ELMo model, but not the Bidirectional LSTM.\n ELMo requires 2 additional tokens: <S> and </S>. The first token\n in this fi...
Please provide a description of the function: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]: instances_with...
[ "\n Sorts the instances by their padding lengths, using the keys in\n ``sorting_keys`` (in the order in which they are provided). ``sorting_keys`` is a list of\n ``(field_name, padding_key)`` tuples.\n " ]
Please provide a description of the function:def infer(self, setup: QuaRelType, answer_0: QuaRelType, answer_1: QuaRelType) -> int: if self._check_quarels_compatible(setup, answer_0): if self._check_quarels_compatible(setup, answer_1): # Found two answers ret...
[ "\n Take the question and check if it is compatible with either of the answer choices.\n " ]
Please provide a description of the function:def make_app(predictor: Predictor, field_names: List[str] = None, static_dir: str = None, sanitizer: Callable[[JsonDict], JsonDict] = None, title: str = "AllenNLP Demo") -> Flask: if static_dir is not None: ...
[ "\n Creates a Flask app that serves up the provided ``Predictor``\n along with a front-end for interacting with it.\n\n If you want to use the built-in bare-bones HTML, you must provide the\n field names for the inputs (which will be used both as labels\n and as the keys in the JSON that gets sent to...
Please provide a description of the function:def _html(title: str, field_names: List[str]) -> str: inputs = ''.join(_SINGLE_INPUT_TEMPLATE.substitute(field_name=field_name) for field_name in field_names) quoted_field_names = [f"'{field_name}'" for field_name in field_names] quoted...
[ "\n Returns bare bones HTML for serving up an input form with the\n specified fields that can render predictions from the configured model.\n " ]
Please provide a description of the function:def get_valid_actions(self) -> Dict[str, Tuple[torch.Tensor, torch.Tensor, List[int]]]: actions = self._valid_actions[self._nonterminal_stack[-1]] context_actions = [] for type_, variable in self._lambda_stacks: if self._nontermin...
[ "\n Returns the valid actions in the current grammar state. See the class docstring for a\n description of what we're returning here.\n " ]
Please provide a description of the function:def take_action(self, production_rule: str) -> 'LambdaGrammarStatelet': left_side, right_side = production_rule.split(' -> ') assert self._nonterminal_stack[-1] == left_side, (f"Tried to expand {self._nonterminal_stack[-1]}" ...
[ "\n Takes an action in the current grammar state, returning a new grammar state with whatever\n updates are necessary. The production rule is assumed to be formatted as \"LHS -> RHS\".\n\n This will update the non-terminal stack and the context-dependent actions. Updating the\n non-ter...
Please provide a description of the function:def decode_mst(energy: numpy.ndarray, length: int, has_labels: bool = True) -> Tuple[numpy.ndarray, numpy.ndarray]: if has_labels and energy.ndim != 3: raise ConfigurationError("The dimension of the energy array is not equal to ...
[ "\n Note: Counter to typical intuition, this function decodes the _maximum_\n spanning tree.\n\n Decode the optimal MST tree with the Chu-Liu-Edmonds algorithm for\n maximum spanning arborescences on graphs.\n\n Parameters\n ----------\n energy : ``numpy.ndarray``, required.\n A tensor w...
Please provide a description of the function: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, ...
[ "\n Applies the chu-liu-edmonds algorithm recursively\n to a graph with edge weights defined by score_matrix.\n\n Note that this function operates in place, so variables\n will be modified.\n\n Parameters\n ----------\n length : ``int``, required.\n The number of nodes.\n score_matrix...
Please provide a description of the function:def assign_average_value(self) -> None: for name, parameter in self._parameters: self._backups[name].copy_(parameter.data) parameter.data.copy_(self._shadows[name])
[ "\n Replace all the parameter values with the averages.\n Save the current parameter values to restore later.\n " ]
Please provide a description of the function:def restore(self) -> None: for name, parameter in self._parameters: parameter.data.copy_(self._backups[name])
[ "\n Restore the backed-up (non-average) parameter values.\n " ]
Please provide a description of the function:def forward(self, tensor_1: torch.Tensor, tensor_2: torch.Tensor) -> torch.Tensor: # pylint: disable=arguments-differ raise NotImplementedError
[ "\n Takes two tensors of the same shape, such as ``(batch_size, length_1, length_2,\n embedding_dim)``. Computes a (possibly parameterized) similarity on the final dimension\n and returns a tensor with one less dimension, such as ``(batch_size, length_1, length_2)``.\n " ]
Please provide a description of the function:def _prune_beam(states: List[State], beam_size: int, sort_states: bool = False) -> List[State]: states_by_batch_index: Dict[int, List[State]] = defaultdict(list) for state in states: assert len(stat...
[ "\n This method can be used to prune the set of unfinished states on a beam or finished states\n at the end of search. In the former case, the states need not be sorted because the all come\n from the same decoding step, which does the sorting. However, if the states are finished and\n t...
Please provide a description of the function:def _get_best_final_states(self, finished_states: List[StateType]) -> Dict[int, List[StateType]]: batch_states: Dict[int, List[StateType]] = defaultdict(list) for state in finished_states: batch_states[state.batch_indices[0]].append(state...
[ "\n Returns the best finished states for each batch instance based on model scores. We return\n at most ``self._max_num_decoded_sequences`` number of sequences per instance.\n " ]
Please provide a description of the function:def _read_pretrained_embeddings_file(file_uri: str, embedding_dim: int, vocab: Vocabulary, namespace: str = "tokens") -> torch.FloatTensor: file_ext = get_...
[ "\n Returns and embedding matrix for the given vocabulary using the pretrained embeddings\n contained in the given file. Embeddings for tokens not found in the pretrained embedding file\n are randomly initialized using a normal distribution with mean and standard deviation equal to\n those of the pretra...
Please provide a description of the function:def _read_embeddings_from_text_file(file_uri: str, embedding_dim: int, vocab: Vocabulary, namespace: str = "tokens") -> torch.FloatTensor: tokens_to_keep = se...
[ "\n Read pre-trained word vectors from an eventually compressed text file, possibly contained\n inside an archive with multiple files. The text file is assumed to be utf-8 encoded with\n space-separated fields: [word] [dim 1] [dim 2] ...\n\n Lines that contain more numerical tokens than ``embedding_dim`...
Please provide a description of the function:def _read_embeddings_from_hdf5(embeddings_filename: str, embedding_dim: int, vocab: Vocabulary, namespace: str = "tokens") -> torch.FloatTensor: with h5py.File(embeddings_fi...
[ "\n Reads from a hdf5 formatted file. The embedding matrix is assumed to\n be keyed by 'embedding' and of size ``(num_tokens, embedding_dim)``.\n " ]
Please provide a description of the function:def _get_num_tokens_from_first_line(line: str) -> Optional[int]: fields = line.split(' ') if 1 <= len(fields) <= 2: try: int_fields = [int(x) for x in fields] except ValueError: return None ...
[ " This function takes in input a string and if it contains 1 or 2 integers, it assumes the\n largest one it the number of tokens. Returns None if the line doesn't match that pattern. " ]
Please provide a description of the function:def _get_predicted_embedding_addition(self, checklist_state: ChecklistStatelet, action_ids: List[int], action_embeddings: torch.Tensor) -> torch.Tens...
[ "\n Gets the embeddings of desired terminal actions yet to be produced by the decoder, and\n returns their sum for the decoder to add it to the predicted embedding to bias the\n prediction towards missing actions.\n " ]
Please provide a description of the function:def _create_tensor_dicts(input_queue: Queue, output_queue: Queue, iterator: DataIterator, shuffle: bool, index: int) -> None: def instances() -> Iterator[Instance]: ...
[ "\n Pulls at most ``max_instances_in_memory`` from the input_queue,\n groups them into batches of size ``batch_size``, converts them\n to ``TensorDict`` s, and puts them on the ``output_queue``.\n " ]
Please provide a description of the function:def _queuer(instances: Iterable[Instance], input_queue: Queue, num_workers: int, num_epochs: Optional[int]) -> None: epoch = 0 while num_epochs is None or epoch < num_epochs: epoch += 1 for instance in instanc...
[ "\n Reads Instances from the iterable and puts them in the input_queue.\n " ]
Please provide a description of the function:def get_valid_actions(self) -> List[Dict[str, Tuple[torch.Tensor, torch.Tensor, List[int]]]]: return [state.get_valid_actions() for state in self.grammar_state]
[ "\n Returns a list of valid actions for each element of the group.\n " ]
Please provide a description of the function:def _worker(reader: DatasetReader, input_queue: Queue, output_queue: Queue, index: int) -> None: # Keep going until you get a file_path that's None. while True: file_path = input_queue.get() if file_path is Non...
[ "\n A worker that pulls filenames off the input queue, uses the dataset reader\n to read them, and places the generated instances on the output queue.\n When there are no filenames left on the input queue, it puts its ``index``\n on the output queue and doesn't do anything else.\n " ]
Please provide a description of the function:def allowed_transitions(constraint_type: str, labels: Dict[int, str]) -> List[Tuple[int, int]]: num_labels = len(labels) start_tag = num_labels end_tag = num_labels + 1 labels_with_boundaries = list(labels.items()) + [(start_tag, "START"), (end_tag, "END...
[ "\n Given labels and a constraint type, returns the allowed transitions. It will\n additionally include transitions for the start and end states, which are used\n by the conditional random field.\n\n Parameters\n ----------\n constraint_type : ``str``, required\n Indicates which constraint ...
Please provide a description of the function:def is_transition_allowed(constraint_type: str, from_tag: str, from_entity: str, to_tag: str, to_entity: str): # pylint: disable=too-many-return-statements if...
[ "\n Given a constraint type and strings ``from_tag`` and ``to_tag`` that\n represent the origin and destination of the transition, return whether\n the transition is allowed under the given constraint type.\n\n Parameters\n ----------\n constraint_type : ``str``, required\n Indicates which ...
Please provide a description of the function:def _input_likelihood(self, logits: torch.Tensor, mask: torch.Tensor) -> torch.Tensor: batch_size, sequence_length, num_tags = logits.size() # Transpose batch size and sequence dimensions mask = mask.float().transpose(0, 1).contiguous() ...
[ "\n Computes the (batch_size,) denominator term for the log-likelihood, which is the\n sum of the likelihoods across all possible state sequences.\n " ]
Please provide a description of the function:def _joint_likelihood(self, logits: torch.Tensor, tags: torch.Tensor, mask: torch.LongTensor) -> torch.Tensor: batch_size, sequence_length, _ = logits.data.shape # Transpo...
[ "\n Computes the numerator term for the log-likelihood, which is just score(inputs, tags)\n " ]
Please provide a description of the function:def forward(self, inputs: torch.Tensor, tags: torch.Tensor, mask: torch.ByteTensor = None) -> torch.Tensor: # pylint: disable=arguments-differ if mask is None: mask = torch.ones(*tags.size()...
[ "\n Computes the log likelihood.\n " ]
Please provide a description of the function:def viterbi_tags(self, logits: torch.Tensor, mask: torch.Tensor) -> List[Tuple[List[int], float]]: _, max_seq_length, num_tags = logits.size() # Get the tensors out of the variables logits, mask = lo...
[ "\n Uses viterbi algorithm to find most likely tags for the given inputs.\n If constraints are applied, disallows all other transitions.\n " ]
Please provide a description of the function:def search(self, start_predictions: torch.Tensor, start_state: StateType, step: StepFunctionType) -> Tuple[torch.Tensor, torch.Tensor]: batch_size = start_predictions.size()[0] # List of (batch_size, beam...
[ "\n Given a starting state and a step function, apply beam search to find the\n most likely target sequences.\n\n Notes\n -----\n If your step function returns ``-inf`` for some log probabilities\n (like if you're using a masked log-softmax) then some of the \"best\"\n ...
Please provide a description of the function:def main(data_directory: int, dataset: str = None, filter_by: str = None, verbose: bool = False) -> None: directory_dict = {path: files for path, names, files in os.walk(data_directory) if files} for directory, data_files in directory_dict.items(): if "...
[ "\n Parameters\n ----------\n data_directory : str, required.\n The path to the data directory of https://github.com/jkkummerfeld/text2sql-data\n which has been preprocessed using scripts/reformat_text2sql_data.py.\n dataset : str, optional.\n The dataset to parse. By default all ar...
Please provide a description of the function:def takes_arg(obj, arg: str) -> bool: if inspect.isclass(obj): signature = inspect.signature(obj.__init__) elif inspect.ismethod(obj) or inspect.isfunction(obj): signature = inspect.signature(obj) else: raise ConfigurationError(f"obje...
[ "\n Checks whether the provided obj takes a certain arg.\n If it's a class, we're really checking whether its constructor does.\n If it's a function or method, we're checking the object itself.\n Otherwise, we raise an error.\n " ]
Please provide a description of the function:def takes_kwargs(obj) -> bool: if inspect.isclass(obj): signature = inspect.signature(obj.__init__) elif inspect.ismethod(obj) or inspect.isfunction(obj): signature = inspect.signature(obj) else: raise ConfigurationError(f"object {obj...
[ "\n Checks whether a provided object takes in any positional arguments.\n Similar to takes_arg, we do this for both the __init__ function of\n the class or a function / method\n Otherwise, we raise an error\n " ]
Please provide a description of the function:def remove_optional(annotation: type): origin = getattr(annotation, '__origin__', None) args = getattr(annotation, '__args__', ()) if origin == Union and len(args) == 2 and args[1] == type(None): return args[0] else: return annotation
[ "\n Optional[X] annotations are actually represented as Union[X, NoneType].\n For our purposes, the \"Optional\" part is not interesting, so here we\n throw it away.\n " ]
Please provide a description of the function:def create_kwargs(cls: Type[T], params: Params, **extras) -> Dict[str, Any]: # Get the signature of the constructor. signature = inspect.signature(cls.__init__) kwargs: Dict[str, Any] = {} # Iterate over all the constructor parameters and their annotati...
[ "\n Given some class, a `Params` object, and potentially other keyword arguments,\n create a dict of keyword args suitable for passing to the class's constructor.\n\n The function does this by finding the class's constructor, matching the constructor\n arguments to entries in the `params` object, and in...
Please provide a description of the function:def create_extras(cls: Type[T], extras: Dict[str, Any]) -> Dict[str, Any]: subextras: Dict[str, Any] = {} if hasattr(cls, "from_params"): from_params_method = cls.from_params # type: ignore else: # In some rare cases, we ge...
[ "\n Given a dictionary of extra arguments, returns a dictionary of\n kwargs that actually are a part of the signature of the cls.from_params\n (or cls) method.\n " ]
Please provide a description of the function: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) ->...
[ "\n Does the work of actually constructing an individual argument for :func:`create_kwargs`.\n\n Here we're in the inner loop of iterating over the parameters to a particular constructor,\n trying to construct just one of them. The information we get for that parameter is its name,\n its type annotatio...
Please provide a description of the function:def from_params(cls: Type[T], params: Params, **extras) -> T: # pylint: disable=protected-access from allennlp.common.registrable import Registrable # import here to avoid circular imports logger.info(f"instantiating class {cls} from params...
[ "\n This is the automatic implementation of `from_params`. Any class that subclasses `FromParams`\n (or `Registrable`, which itself subclasses `FromParams`) gets this implementation for free.\n If you want your class to be instantiated from params in the \"obvious\" way -- pop off parameters\n ...