Code
stringlengths
103
85.9k
Summary
listlengths
0
94
Please provide a description of the function:def rescale_gradients(model: Model, grad_norm: Optional[float] = None) -> Optional[float]: if grad_norm: parameters_to_clip = [p for p in model.parameters() if p.grad is not None] return sparse_clip_norm(parameters_to_cl...
[ "\n Performs gradient rescaling. Is a no-op if gradient rescaling is not enabled.\n " ]
Please provide a description of the function:def get_metrics(model: Model, total_loss: float, num_batches: int, reset: bool = False) -> Dict[str, float]: metrics = model.get_metrics(reset=reset) metrics["loss"] = float(total_loss / num_batches) if num_batches > 0 else 0.0 return metrics
[ "\n Gets the metrics but sets ``\"loss\"`` to\n the total loss divided by the ``num_batches`` so that\n the ``\"loss\"`` metric is \"average loss per batch\".\n " ]
Please provide a description of the function:def parse_requirements() -> Tuple[PackagesType, PackagesType, Set[str]]: essential_packages: PackagesType = {} other_packages: PackagesType = {} duplicates: Set[str] = set() with open("requirements.txt", "r") as req_file: section: str = "" ...
[ "Parse all dependencies out of the requirements.txt file." ]
Please provide a description of the function:def parse_setup() -> Tuple[PackagesType, PackagesType, Set[str], Set[str]]: essential_packages: PackagesType = {} test_packages: PackagesType = {} essential_duplicates: Set[str] = set() test_duplicates: Set[str] = set() with open('setup.py') as setu...
[ "Parse all dependencies out of the setup.py script.", "install_requires=\\[[\\s\\n]*['\"](.*?)['\"],?[\\s\\n]*\\]", "['\"],[\\s\\n]+['\"]", "tests_require=\\[[\\s\\n]*['\"](.*?)['\"],?[\\s\\n]*\\]", "['\"],[\\s\\n]+['\"]" ]
Please provide a description of the function: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]]: ...
[ "\n Given a sentence, return all token spans within the sentence. Spans are `inclusive`.\n Additionally, you can provide a maximum and minimum span width, which will be used\n to exclude spans outside of this range.\n\n Finally, you can provide a function mapping ``List[T] -> bool``, which will\n be ...
Please provide a description of the function:def bio_tags_to_spans(tag_sequence: List[str], classes_to_ignore: List[str] = None) -> List[TypedStringSpan]: classes_to_ignore = classes_to_ignore or [] spans: Set[Tuple[str, Tuple[int, int]]] = set() span_start = 0 span_end = 0 ...
[ "\n Given a sequence corresponding to BIO tags, extracts spans.\n Spans are inclusive and can be of zero length, representing a single word span.\n Ill-formed spans are also included (i.e those which do not start with a \"B-LABEL\"),\n as otherwise it is possible to get a perfect precision score whilst ...
Please provide a description of the function:def iob1_tags_to_spans(tag_sequence: List[str], classes_to_ignore: List[str] = None) -> List[TypedStringSpan]: classes_to_ignore = classes_to_ignore or [] spans: Set[Tuple[str, Tuple[int, int]]] = set() span_start = 0 span_end = 0 ...
[ "\n Given a sequence corresponding to IOB1 tags, extracts spans.\n Spans are inclusive and can be of zero length, representing a single word span.\n Ill-formed spans are also included (i.e., those where \"B-LABEL\" is not preceded\n by \"I-LABEL\" or \"B-LABEL\").\n\n Parameters\n ----------\n ...
Please provide a description of the function:def bioul_tags_to_spans(tag_sequence: List[str], classes_to_ignore: List[str] = None) -> List[TypedStringSpan]: spans = [] classes_to_ignore = classes_to_ignore or [] index = 0 while index < len(tag_sequence): label = tag_...
[ "\n Given a sequence corresponding to BIOUL tags, extracts spans.\n Spans are inclusive and can be of zero length, representing a single word span.\n Ill-formed spans are not allowed and will raise ``InvalidTagSequence``.\n This function works properly when the spans are unlabeled (i.e., your labels are...
Please provide a description of the function:def to_bioul(tag_sequence: List[str], encoding: str = "IOB1") -> List[str]: if not encoding in {"IOB1", "BIO"}: raise ConfigurationError(f"Invalid encoding {encoding} passed to 'to_bioul'.") # pylint: disable=len-as-condition def replace_label(full...
[ "\n Given a tag sequence encoded with IOB1 labels, recode to BIOUL.\n\n In the IOB1 scheme, I is a token inside a span, O is a token outside\n a span and B is the beginning of span immediately following another\n span of the same type.\n\n In the BIO scheme, I is a token inside a span, O is a token o...
Please provide a description of the function:def bmes_tags_to_spans(tag_sequence: List[str], classes_to_ignore: List[str] = None) -> List[TypedStringSpan]: def extract_bmes_tag_label(text): bmes_tag = text[0] label = text[2:] return bmes_tag, label spans: Li...
[ "\n Given a sequence corresponding to BMES tags, extracts spans.\n Spans are inclusive and can be of zero length, representing a single word span.\n Ill-formed spans are also included (i.e those which do not start with a \"B-LABEL\"),\n as otherwise it is possible to get a perfect precision score whilst...
Please provide a description of the function:def dry_run_from_args(args: argparse.Namespace): parameter_path = args.param_path serialization_dir = args.serialization_dir overrides = args.overrides params = Params.from_file(parameter_path, overrides) dry_run_from_params(params, serialization_d...
[ "\n Just converts from an ``argparse.Namespace`` object to params.\n " ]
Please provide a description of the function:def search(self, initial_state: State, transition_function: TransitionFunction) -> Dict[int, List[State]]: finished_states: Dict[int, List[State]] = defaultdict(list) states = [initial_state] step_num = 0 ...
[ "\n Parameters\n ----------\n initial_state : ``State``\n The starting state of our search. This is assumed to be `batched`, and our beam search\n is batch-aware - we'll keep ``beam_size`` states around for each instance in the batch.\n transition_function : ``Tran...
Please provide a description of the function:def url_ok(match_tuple: MatchTuple) -> bool: try: result = requests.get(match_tuple.link, timeout=5) return result.ok except (requests.ConnectionError, requests.Timeout): return False
[ "Check if a URL is reachable." ]
Please provide a description of the function:def path_ok(match_tuple: MatchTuple) -> bool: relative_path = match_tuple.link.split("#")[0] full_path = os.path.join(os.path.dirname(str(match_tuple.source)), relative_path) return os.path.exists(full_path)
[ "Check if a file in this repository exists." ]
Please provide a description of the function:def infer_and_cast(value: Any): # pylint: disable=too-many-return-statements if isinstance(value, (int, float, bool)): # Already one of our desired types, so leave as is. return value elif isinstance(value, list): # Recursively call o...
[ "\n In some cases we'll be feeding params dicts to functions we don't own;\n for example, PyTorch optimizers. In that case we can't use ``pop_int``\n or similar to force casts (which means you can't specify ``int`` parameters\n using environment variables). This function takes something that looks JSON-...
Please provide a description of the function:def _environment_variables() -> Dict[str, str]: return {key: value for key, value in os.environ.items() if _is_encodable(value)}
[ "\n Wraps `os.environ` to filter out non-encodable values.\n " ]
Please provide a description of the function:def unflatten(flat_dict: Dict[str, Any]) -> Dict[str, Any]: unflat: Dict[str, Any] = {} for compound_key, value in flat_dict.items(): curr_dict = unflat parts = compound_key.split(".") for key in parts[:-1]: curr_value = curr...
[ "\n Given a \"flattened\" dict with compound keys, e.g.\n {\"a.b\": 0}\n unflatten it:\n {\"a\": {\"b\": 0}}\n " ]
Please provide a description of the function:def with_fallback(preferred: Dict[str, Any], fallback: Dict[str, Any]) -> Dict[str, Any]: def merge(preferred_value: Any, fallback_value: Any) -> Any: if isinstance(preferred_value, dict) and isinstance(fallback_value, dict): return with_fallback...
[ "\n Deep merge two dicts, preferring values from `preferred`.\n " ]
Please provide a description of the function:def pop_choice(params: Dict[str, Any], key: str, choices: List[Any], default_to_first_choice: bool = False, history: str = "?.") -> Any: value = Params(params, history).pop_choice(key, choices, default_to_f...
[ "\n Performs the same function as :func:`Params.pop_choice`, but is required in order to deal with\n places that the Params object is not welcome, such as inside Keras layers. See the docstring\n of that method for more detail on how this function works.\n\n This method adds a ``history`` parameter, in...
Please provide a description of the function:def add_file_to_archive(self, name: str) -> None: if not self.loading_from_archive: self.files_to_archive[f"{self.history}{name}"] = cached_path(self.get(name))
[ "\n Any class in its ``from_params`` method can request that some of its\n input files be added to the archive by calling this method.\n\n For example, if some class ``A`` had an ``input_file`` parameter, it could call\n\n ```\n params.add_file_to_archive(\"input_file\")\n ...
Please provide a description of the function:def pop(self, key: str, default: Any = DEFAULT) -> Any: if default is self.DEFAULT: try: value = self.params.pop(key) except KeyError: raise ConfigurationError("key \"{}\" is required at location \"{}\"...
[ "\n Performs the functionality associated with dict.pop(key), along with checking for\n returned dictionaries, replacing them with Param objects with an updated history.\n\n If ``key`` is not present in the dictionary, and no default was specified, we raise a\n ``ConfigurationError``, in...
Please provide a description of the function:def pop_int(self, key: str, default: Any = DEFAULT) -> int: value = self.pop(key, default) if value is None: return None else: return int(value)
[ "\n Performs a pop and coerces to an int.\n " ]
Please provide a description of the function:def pop_float(self, key: str, default: Any = DEFAULT) -> float: value = self.pop(key, default) if value is None: return None else: return float(value)
[ "\n Performs a pop and coerces to a float.\n " ]
Please provide a description of the function:def pop_bool(self, key: str, default: Any = DEFAULT) -> bool: value = self.pop(key, default) if value is None: return None elif isinstance(value, bool): return value elif value == "true": return Tru...
[ "\n Performs a pop and coerces to a bool.\n " ]
Please provide a description of the function:def get(self, key: str, default: Any = DEFAULT): if default is self.DEFAULT: try: value = self.params.get(key) except KeyError: raise ConfigurationError("key \"{}\" is required at location \"{}\"".forma...
[ "\n Performs the functionality associated with dict.get(key) but also checks for returned\n dicts and returns a Params object in their place with an updated history.\n " ]
Please provide a description of the function:def pop_choice(self, key: str, choices: List[Any], default_to_first_choice: bool = False) -> Any: default = choices[0] if default_to_first_choice else self.DEFAULT value = self.pop(key, default) if value not in choices: key_str = ...
[ "\n Gets the value of ``key`` in the ``params`` dictionary, ensuring that the value is one of\n the given choices. Note that this `pops` the key from params, modifying the dictionary,\n consistent with how parameters are processed in this codebase.\n\n Parameters\n ----------\n ...
Please provide a description of the function:def as_dict(self, quiet: bool = False, infer_type_and_cast: bool = False): if infer_type_and_cast: params_as_dict = infer_and_cast(self.params) else: params_as_dict = self.params if quiet: return params_as...
[ "\n Sometimes we need to just represent the parameters as a dict, for instance when we pass\n them to PyTorch code.\n\n Parameters\n ----------\n quiet: bool, optional (default = False)\n Whether to log the parameters before returning them as a dict.\n infer_type...
Please provide a description of the function:def as_flat_dict(self): flat_params = {} def recurse(parameters, path): for key, value in parameters.items(): newpath = path + [key] if isinstance(value, dict): recurse(value, newpath) ...
[ "\n Returns the parameters of a flat dictionary from keys to values.\n Nested structure is collapsed with periods.\n " ]
Please provide a description of the function:def assert_empty(self, class_name: str): if self.params: raise ConfigurationError("Extra parameters passed to {}: {}".format(class_name, self.params))
[ "\n Raises a ``ConfigurationError`` if ``self.params`` is not empty. We take ``class_name`` as\n an argument so that the error message gives some idea of where an error happened, if there\n was one. ``class_name`` should be the name of the `calling` class, the one that got extra\n para...
Please provide a description of the function:def from_file(params_file: str, params_overrides: str = "", ext_vars: dict = None) -> 'Params': if ext_vars is None: ext_vars = {} # redirect to cache, if necessary params_file = cached_path(params_file) ext_vars = {**_en...
[ "\n Load a `Params` object from a configuration file.\n\n Parameters\n ----------\n params_file : ``str``\n The path to the configuration file to load.\n params_overrides : ``str``, optional\n A dict of overrides that can be applied to final object.\n ...
Please provide a description of the function:def as_ordered_dict(self, preference_orders: List[List[str]] = None) -> OrderedDict: params_dict = self.as_dict(quiet=True) if not preference_orders: preference_orders = [] preference_orders.append(["dataset_reader", "iterator...
[ "\n Returns Ordered Dict of Params from list of partial order preferences.\n\n Parameters\n ----------\n preference_orders: List[List[str]], optional\n ``preference_orders`` is list of partial preference orders. [\"A\", \"B\", \"C\"] means\n \"A\" > \"B\" > \"C\". F...
Please provide a description of the function:def get_hash(self) -> str: return str(hash(json.dumps(self.params, sort_keys=True)))
[ "\n Returns a hash code representing the current state of this ``Params`` object. We don't\n want to implement ``__hash__`` because that has deeper python implications (and this is a\n mutable object), but this will give you a representation of the current state.\n " ]
Please provide a description of the function:def clear(self) -> None: self._best_so_far = None self._epochs_with_no_improvement = 0 self._is_best_so_far = True self._epoch_number = 0 self.best_epoch = None
[ "\n Clears out the tracked metrics, but keeps the patience and should_decrease settings.\n " ]
Please provide a description of the function:def state_dict(self) -> Dict[str, Any]: return { "best_so_far": self._best_so_far, "patience": self._patience, "epochs_with_no_improvement": self._epochs_with_no_improvement, "is_best_so_far": s...
[ "\n A ``Trainer`` can use this to serialize the state of the metric tracker.\n " ]
Please provide a description of the function:def add_metric(self, metric: float) -> None: new_best = ((self._best_so_far is None) or (self._should_decrease and metric < self._best_so_far) or (not self._should_decrease and metric > self._best_so_far)) if ...
[ "\n Record a new value of the metric and update the various things that depend on it.\n " ]
Please provide a description of the function:def add_metrics(self, metrics: Iterable[float]) -> None: for metric in metrics: self.add_metric(metric)
[ "\n Helper to add multiple metrics at once.\n " ]
Please provide a description of the function:def should_stop_early(self) -> bool: if self._patience is None: return False else: return self._epochs_with_no_improvement >= self._patience
[ "\n Returns true if improvement has stopped for long enough.\n " ]
Please provide a description of the function:def archive_model(serialization_dir: str, weights: str = _DEFAULT_WEIGHTS, files_to_archive: Dict[str, str] = None, archive_path: str = None) -> None: weights_file = os.path.join(serialization_dir, weights) i...
[ "\n Archive the model weights, its training configuration, and its\n vocabulary to `model.tar.gz`. Include the additional ``files_to_archive``\n if provided.\n\n Parameters\n ----------\n serialization_dir: ``str``\n The directory where the weights and vocabulary are written out.\n weigh...
Please provide a description of the function:def load_archive(archive_file: str, cuda_device: int = -1, overrides: str = "", weights_file: str = None) -> Archive: # redirect to the cache, if necessary resolved_archive_file = cached_path(archive_file) ...
[ "\n Instantiates an Archive from an archived `tar.gz` file.\n\n Parameters\n ----------\n archive_file: ``str``\n The archive file to load the model from.\n weights_file: ``str``, optional (default = None)\n The weights file to use. If unspecified, weights.th in the archive_file will b...
Please provide a description of the function:def extract_module(self, path: str, freeze: bool = True) -> Module: modules_dict = {path: module for path, module in self.model.named_modules()} module = modules_dict.get(path, None) if not module: raise ConfigurationError(f"You ...
[ "\n This method can be used to load a module from the pretrained model archive.\n\n It is also used implicitly in FromParams based construction. So instead of using standard\n params to construct a module, you can instead load a pretrained module from the model\n archive directly. For eg...
Please provide a description of the function:def _get_action_strings(cls, possible_actions: List[List[ProductionRule]], action_indices: Dict[int, List[List[int]]]) -> List[List[List[str]]]: all_action_strings: List[List[List[str]]] = [] ba...
[ "\n Takes a list of possible actions and indices of decoded actions into those possible actions\n for a batch and returns sequences of action strings. We assume ``action_indices`` is a dict\n mapping batch indices to k-best decoded sequence lists.\n " ]
Please provide a description of the function:def decode(self, output_dict: Dict[str, torch.Tensor]) -> Dict[str, torch.Tensor]: best_action_strings = output_dict["best_action_strings"] # Instantiating an empty world for getting logical forms. world = NlvrLanguage(set()) logical_...
[ "\n This method overrides ``Model.decode``, which gets called after ``Model.forward``, at test\n time, to finalize predictions. We only transform the action string sequences into logical\n forms here.\n " ]
Please provide a description of the function:def _check_state_denotations(self, state: GrammarBasedState, worlds: List[NlvrLanguage]) -> List[bool]: assert state.is_finished(), "Cannot compute denotations for unfinished states!" # Since this is a finished state, its group size must be 1. ...
[ "\n Returns whether action history in the state evaluates to the correct denotations over all\n worlds. Only defined when the state is finished.\n " ]
Please provide a description of the function:def find_learning_rate_from_args(args: argparse.Namespace) -> None: params = Params.from_file(args.param_path, args.overrides) find_learning_rate_model(params, args.serialization_dir, start_lr=args.start_lr, ...
[ "\n Start learning rate finder for given args\n " ]
Please provide a description of the function:def find_learning_rate_model(params: Params, serialization_dir: str, start_lr: float = 1e-5, end_lr: float = 10, num_batches: int = 100, linear_steps: bool = F...
[ "\n Runs learning rate search for given `num_batches` and saves the results in ``serialization_dir``\n\n Parameters\n ----------\n params : ``Params``\n A parameter object specifying an AllenNLP Experiment.\n serialization_dir : ``str``\n The directory in which to save results.\n sta...
Please provide a description of the function:def search_learning_rate(trainer: Trainer, start_lr: float = 1e-5, end_lr: float = 10, num_batches: int = 100, linear_steps: bool = False, stopping_fa...
[ "\n Runs training loop on the model using :class:`~allennlp.training.trainer.Trainer`\n increasing learning rate from ``start_lr`` to ``end_lr`` recording the losses.\n Parameters\n ----------\n trainer: :class:`~allennlp.training.trainer.Trainer`\n start_lr: ``float``\n The learning rate t...
Please provide a description of the function:def _smooth(values: List[float], beta: float) -> List[float]: avg_value = 0. smoothed = [] for i, value in enumerate(values): avg_value = beta * avg_value + (1 - beta) * value smoothed.append(avg_value / (1 - beta ** (i + 1))) return smoo...
[ " Exponential smoothing of values " ]
Please provide a description of the function:def forward(self, tensors: List[torch.Tensor], # pylint: disable=arguments-differ mask: torch.Tensor = None) -> torch.Tensor: if len(tensors) != self.mixture_size: raise ConfigurationError("{} tensors were passed, but the module ...
[ "\n Compute a weighted average of the ``tensors``. The input tensors an be any shape\n with at least two dimensions, but must all be the same shape.\n\n When ``do_layer_norm=True``, the ``mask`` is required input. If the ``tensors`` are\n dimensioned ``(dim_0, ..., dim_{n-1}, dim_n)``...
Please provide a description of the function:def predicate_with_side_args(side_arguments: List[str]) -> Callable: # pylint: disable=invalid-name def decorator(function: Callable) -> Callable: setattr(function, '_side_arguments', side_arguments) return predicate(function) return decorator
[ "\n Like :func:`predicate`, but used when some of the arguments to the function are meant to be\n provided by the decoder or other state, instead of from the language. For example, you might\n want to have a function use the decoder's attention over some input text when a terminal was\n predicted. Tha...
Please provide a description of the function:def nltk_tree_to_logical_form(tree: Tree) -> str: # nltk.Tree actually inherits from `list`, so you use `len()` to get the number of children. # We're going to be explicit about checking length, instead of using `if tree:`, just to avoid # any funny business...
[ "\n Given an ``nltk.Tree`` representing the syntax tree that generates a logical form, this method\n produces the actual (lisp-like) logical form, with all of the non-terminal symbols converted\n into the correct number of parentheses.\n\n This is used in the logic that converts action sequences back in...
Please provide a description of the function:def get_type(type_: Type) -> 'PredicateType': if is_callable(type_): callable_args = type_.__args__ argument_types = [PredicateType.get_type(t) for t in callable_args[:-1]] return_type = PredicateType.get_type(callable_arg...
[ "\n Converts a python ``Type`` (as you might get from a type annotation) into a\n ``PredicateType``. If the ``Type`` is callable, this will return a ``FunctionType``;\n otherwise, it will return a ``BasicType``.\n\n ``BasicTypes`` have a single ``name`` parameter - we typically get this...
Please provide a description of the function:def execute(self, logical_form: str): if not hasattr(self, '_functions'): raise RuntimeError("You must call super().__init__() in your Language constructor") logical_form = logical_form.replace(",", " ") expression = util.lisp_to_...
[ "Executes a logical form, using whatever predicates you have defined." ]
Please provide a description of the function:def execute_action_sequence(self, action_sequence: List[str], side_arguments: List[Dict] = None): # We'll strip off the first action, because it doesn't matter for execution. first_action = action_sequence[0] left_side = first_action.split(' ...
[ "\n Executes the program defined by an action sequence directly, without needing the overhead\n of translating to a logical form first. For any given program, :func:`execute` and this\n function are equivalent, they just take different representations of the program, so you\n can use wh...
Please provide a description of the function:def get_nonterminal_productions(self) -> Dict[str, List[str]]: if not self._nonterminal_productions: actions: Dict[str, Set[str]] = defaultdict(set) # If you didn't give us a set of valid start types, we'll assume all types we know ...
[ "\n Induces a grammar from the defined collection of predicates in this language and returns\n all productions in that grammar, keyed by the non-terminal they are expanding.\n\n This includes terminal productions implied by each predicate as well as productions for the\n `return type` of...
Please provide a description of the function:def all_possible_productions(self) -> List[str]: all_actions = set() for action_set in self.get_nonterminal_productions().values(): all_actions.update(action_set) return sorted(all_actions)
[ "\n Returns a sorted list of all production rules in the grammar induced by\n :func:`get_nonterminal_productions`.\n " ]
Please provide a description of the function:def logical_form_to_action_sequence(self, logical_form: str) -> List[str]: expression = util.lisp_to_nested_expression(logical_form) try: transitions, start_type = self._get_transitions(expression, expected_type=None) if self....
[ "\n Converts a logical form into a linearization of the production rules from its abstract\n syntax tree. The linearization is top-down, depth-first.\n\n Each production rule is formatted as \"LHS -> RHS\", where \"LHS\" is a single non-terminal\n type, and RHS is either a terminal or a...
Please provide a description of the function:def action_sequence_to_logical_form(self, action_sequence: List[str]) -> str: # Basic outline: we assume that the bracketing that we get in the RHS of each action is the # correct bracketing for reconstructing the logical form. This is true when the...
[ "\n Takes an action sequence as produced by :func:`logical_form_to_action_sequence`, which is a\n linearization of an abstract syntax tree, and reconstructs the logical form defined by that\n abstract syntax tree.\n " ]
Please provide a description of the function:def add_predicate(self, name: str, function: Callable, side_arguments: List[str] = None): side_arguments = side_arguments or [] signature = inspect.signature(function) argument_types = [param.annotation for name, param in signature.parameters...
[ "\n Adds a predicate to this domain language. Typically you do this with the ``@predicate``\n decorator on the methods in your class. But, if you need to for whatever reason, you can\n also call this function yourself with a (type-annotated) function to add it to your\n language.\n\n ...
Please provide a description of the function:def add_constant(self, name: str, value: Any, type_: Type = None): value_type = type_ if type_ else type(value) constant_type = PredicateType.get_type(value_type) self._functions[name] = lambda: value self._function_types[name].append...
[ "\n Adds a constant to this domain language. You would typically just pass in a list of\n constants to the ``super().__init__()`` call in your constructor, but you can also call\n this method to add constants if it is more convenient.\n\n Because we construct a grammar over this languag...
Please provide a description of the function:def is_nonterminal(self, symbol: str) -> bool: nonterminal_productions = self.get_nonterminal_productions() return symbol in nonterminal_productions
[ "\n Determines whether an input symbol is a valid non-terminal in the grammar.\n " ]
Please provide a description of the function:def _execute_expression(self, expression: Any): # pylint: disable=too-many-return-statements if isinstance(expression, list): if isinstance(expression[0], list): function = self._execute_expression(expression[0]) ...
[ "\n This does the bulk of the work of executing a logical form, recursively executing a single\n expression. Basically, if the expression is a function we know about, we evaluate its\n arguments then call the function. If it's a list, we evaluate all elements of the list.\n If it's a c...
Please provide a description of the function:def _execute_sequence(self, action_sequence: List[str], side_arguments: List[Dict]) -> Tuple[Any, List[str], List[Dict]]: first_action = action_sequence[0] remaining_actions = action_sequence[1:] ...
[ "\n This does the bulk of the work of :func:`execute_action_sequence`, recursively executing\n the functions it finds and trimming actions off of the action sequence. The return value\n is a tuple of (execution, remaining_actions), where the second value is necessary to handle\n the rec...
Please provide a description of the function:def _get_transitions(self, expression: Any, expected_type: PredicateType) -> Tuple[List[str], PredicateType]: if isinstance(expression, (list, tuple)): function_transitions, return_type, argument_types = self._get_function_transitions(expression[...
[ "\n This is used when converting a logical form into an action sequence. This piece\n recursively translates a lisp expression into an action sequence, making sure we match the\n expected type (or using the expected type to get the right type for constant expressions).\n " ]
Please provide a description of the function:def _get_function_transitions(self, expression: Union[str, List], expected_type: PredicateType) -> Tuple[List[str], PredicateType, ...
[ "\n A helper method for ``_get_transitions``. This gets the transitions for the predicate\n itself in a function call. If we only had simple functions (e.g., \"(add 2 3)\"), this would\n be pretty straightforward and we wouldn't need a separate method to handle it. We split it\n out i...
Please provide a description of the function:def _construct_node_from_actions(self, current_node: Tree, remaining_actions: List[List[str]]) -> List[List[str]]: if not remaining_actions: logger.error("No actions left t...
[ "\n Given a current node in the logical form tree, and a list of actions in an action sequence,\n this method fills in the children of the current node from the action sequence, then\n returns whatever actions are left.\n\n For example, we could get a node with type ``c``, and an action ...
Please provide a description of the function:def _choice(num_words: int, num_samples: int) -> Tuple[np.ndarray, int]: num_tries = 0 num_chosen = 0 def get_buffer() -> np.ndarray: log_samples = np.random.rand(num_samples) * np.log(num_words + 1) samples = np.exp(log_samples).astype('int...
[ "\n Chooses ``num_samples`` samples without replacement from [0, ..., num_words).\n Returns a tuple (samples, num_tries).\n " ]
Please provide a description of the function:def tokens_to_indices(self, tokens: List[Token], vocabulary: Vocabulary, index_name: str) -> Dict[str, List[TokenType]]: raise NotImplementedError
[ "\n Takes a list of tokens and converts them to one or more sets of indices.\n This could be just an ID for each token from the vocabulary.\n Or it could split each token into characters and return one ID per character.\n Or (for instance, in the case of byte-pair encoding) there might n...
Please provide a description of the function:def pad_token_sequence(self, tokens: Dict[str, List[TokenType]], desired_num_tokens: Dict[str, int], padding_lengths: Dict[str, int]) -> Dict[str, List[TokenType]]: raise NotImp...
[ "\n This method pads a list of tokens to ``desired_num_tokens`` and returns a padded copy of the\n input tokens. If the input token list is longer than ``desired_num_tokens`` then it will be\n truncated.\n\n ``padding_lengths`` is used to provide supplemental padding parameters which ar...
Please provide a description of the function:def canonicalize_clusters(clusters: DefaultDict[int, List[Tuple[int, int]]]) -> List[List[Tuple[int, int]]]: merged_clusters: List[Set[Tuple[int, int]]] = [] for cluster in clusters.values(): cluster_with_overlapping_mention = None for mention in...
[ "\n The CONLL 2012 data includes 2 annotated spans which are identical,\n but have different ids. This checks all clusters for spans which are\n identical, and if it finds any, merges the clusters containing the\n identical spans.\n " ]
Please provide a description of the function:def join_mwp(tags: List[str]) -> List[str]: ret = [] verb_flag = False for tag in tags: if "V" in tag: # Create a continuous 'V' BIO span prefix, _ = tag.split("-") if verb_flag: # Continue a verb l...
[ "\n Join multi-word predicates to a single\n predicate ('V') token.\n " ]
Please provide a description of the function:def make_oie_string(tokens: List[Token], tags: List[str]) -> str: frame = [] chunk = [] words = [token.text for token in tokens] for (token, tag) in zip(words, tags): if tag.startswith("I-"): chunk.append(token) else: ...
[ "\n Converts a list of model outputs (i.e., a list of lists of bio tags, each\n pertaining to a single word), returns an inline bracket representation of\n the prediction.\n " ]
Please provide a description of the function:def get_predicate_indices(tags: List[str]) -> List[int]: return [ind for ind, tag in enumerate(tags) if 'V' in tag]
[ "\n Return the word indices of a predicate in BIO tags.\n " ]
Please provide a description of the function:def get_predicate_text(sent_tokens: List[Token], tags: List[str]) -> str: return " ".join([sent_tokens[pred_id].text for pred_id in get_predicate_indices(tags)])
[ "\n Get the predicate in this prediction.\n " ]
Please provide a description of the function:def predicates_overlap(tags1: List[str], tags2: List[str]) -> bool: # Get predicate word indices from both predictions pred_ind1 = get_predicate_indices(tags1) pred_ind2 = get_predicate_indices(tags2) # Return if pred_ind1 pred_ind2 overlap return a...
[ "\n Tests whether the predicate in BIO tags1 overlap\n with those of tags2.\n " ]
Please provide a description of the function:def get_coherent_next_tag(prev_label: str, cur_label: str) -> str: if cur_label == "O": # Don't need to add prefix to an "O" label return "O" if prev_label == cur_label: return f"I-{cur_label}" else: return f"B-{cur_label}"
[ "\n Generate a coherent tag, given previous tag and current label.\n " ]
Please provide a description of the function:def merge_overlapping_predictions(tags1: List[str], tags2: List[str]) -> List[str]: ret_sequence = [] prev_label = "O" # Build a coherent sequence out of two # spans which predicates' overlap for tag1, tag2 in zip(tags1, tags2): label1 = ta...
[ "\n Merge two predictions into one. Assumes the predicate in tags1 overlap with\n the predicate of tags2.\n " ]
Please provide a description of the function:def consolidate_predictions(outputs: List[List[str]], sent_tokens: List[Token]) -> Dict[str, List[str]]: pred_dict: Dict[str, List[str]] = {} merged_outputs = [join_mwp(output) for output in outputs] predicate_texts = [get_predicate_text(sent_tokens, tags) ...
[ "\n Identify that certain predicates are part of a multiword predicate\n (e.g., \"decided to run\") in which case, we don't need to return\n the embedded predicate (\"run\").\n " ]
Please provide a description of the function:def sanitize_label(label: str) -> str: if "-" in label: prefix, suffix = label.split("-") suffix = suffix.split("(")[-1] return f"{prefix}-{suffix}" else: return label
[ "\n Sanitize a BIO label - this deals with OIE\n labels sometimes having some noise, as parentheses.\n " ]
Please provide a description of the function:def batch_to_ids(batch: List[List[str]]) -> torch.Tensor: instances = [] indexer = ELMoTokenCharactersIndexer() for sentence in batch: tokens = [Token(token) for token in sentence] field = TextField(tokens, {'charact...
[ "\n Converts a batch of tokenized sentences to a tensor representing the sentences with encoded characters\n (len(batch), max sentence length, max word length).\n\n Parameters\n ----------\n batch : ``List[List[str]]``, required\n A list of tokenized sentences.\n\n Returns\n -------\n ...
Please provide a description of the function:def forward(self, # pylint: disable=arguments-differ inputs: torch.Tensor, word_inputs: torch.Tensor = None) -> Dict[str, Union[torch.Tensor, List[torch.Tensor]]]: # reshape the input if needed original_shape = inpu...
[ "\n Parameters\n ----------\n inputs: ``torch.Tensor``, required.\n Shape ``(batch_size, timesteps, 50)`` of character ids representing the current batch.\n word_inputs : ``torch.Tensor``, required.\n If you passed a cached vocab, you can in addition pass a tensor of sh...
Please provide a description of the function:def forward(self, inputs: torch.Tensor) -> Dict[str, torch.Tensor]: # pylint: disable=arguments-differ # Add BOS/EOS mask = ((inputs > 0).long().sum(dim=-1) > 0).long() character_ids_with_bos_eos, mask_with_bos_eos = add_sentence_boundary_to...
[ "\n Compute context insensitive token embeddings for ELMo representations.\n\n Parameters\n ----------\n inputs: ``torch.Tensor``\n Shape ``(batch_size, sequence_length, 50)`` of character ids representing the\n current batch.\n\n Returns\n -------\n ...
Please provide a description of the function:def forward(self, # pylint: disable=arguments-differ inputs: torch.Tensor, word_inputs: torch.Tensor = None) -> Dict[str, Union[torch.Tensor, List[torch.Tensor]]]: if self._word_embedding is not None and word_inputs is not No...
[ "\n Parameters\n ----------\n inputs: ``torch.Tensor``, required.\n Shape ``(batch_size, timesteps, 50)`` of character ids representing the current batch.\n word_inputs : ``torch.Tensor``, required.\n If you passed a cached vocab, you can in addition pass a tensor o...
Please provide a description of the function:def create_cached_cnn_embeddings(self, tokens: List[str]) -> None: tokens = [ELMoCharacterMapper.bos_token, ELMoCharacterMapper.eos_token] + tokens timesteps = 32 batch_size = 32 chunked_tokens = lazy_groups_of(iter(tokens), timesteps...
[ "\n Given a list of tokens, this method precomputes word representations\n by running just the character convolutions and highway layers of elmo,\n essentially creating uncontextual word vectors. On subsequent forward passes,\n the word ids are looked up from an embedding, rather than be...
Please provide a description of the function:def normalize_text(text: str) -> str: return ' '.join([token for token in text.lower().strip(STRIPPED_CHARACTERS).split() if token not in IGNORED_TOKENS])
[ "\n Performs a normalization that is very similar to that done by the normalization functions in\n SQuAD and TriviaQA.\n\n This involves splitting and rejoining the text, and could be a somewhat expensive operation.\n " ]
Please provide a description of the function:def char_span_to_token_span(token_offsets: List[Tuple[int, int]], character_span: Tuple[int, int]) -> Tuple[Tuple[int, int], bool]: # We have token offsets into the passage from the tokenizer; we _should_ be able to just find # the to...
[ "\n Converts a character span from a passage into the corresponding token span in the tokenized\n version of the passage. If you pass in a character span that does not correspond to complete\n tokens in the tokenized version, we'll do our best, but the behavior is officially undefined.\n We return an e...
Please provide a description of the function:def find_valid_answer_spans(passage_tokens: List[Token], answer_texts: List[str]) -> List[Tuple[int, int]]: normalized_tokens = [token.text.lower().strip(STRIPPED_CHARACTERS) for token in passage_tokens] # Because there could be many ...
[ "\n Finds a list of token spans in ``passage_tokens`` that match the given ``answer_texts``. This\n tries to find all spans that would evaluate to correct given the SQuAD and TriviaQA official\n evaluation scripts, which do some normalization of the input text.\n\n Note that this could return duplicate...
Please provide a description of the function:def make_reading_comprehension_instance(question_tokens: List[Token], passage_tokens: List[Token], token_indexers: Dict[str, TokenIndexer], passage_text: s...
[ "\n Converts a question, a passage, and an optional answer (or answers) to an ``Instance`` for use\n in a reading comprehension model.\n\n Creates an ``Instance`` with at least these fields: ``question`` and ``passage``, both\n ``TextFields``; and ``metadata``, a ``MetadataField``. Additionally, if bot...
Please provide a description of the function:def make_reading_comprehension_instance_quac(question_list_tokens: List[List[Token]], passage_tokens: List[Token], token_indexers: Dict[str, TokenIndexer], ...
[ "\n Converts a question, a passage, and an optional answer (or answers) to an ``Instance`` for use\n in a reading comprehension model.\n\n Creates an ``Instance`` with at least these fields: ``question`` and ``passage``, both\n ``TextFields``; and ``metadata``, a ``MetadataField``. Additionally, if bot...
Please provide a description of the function:def handle_cannot(reference_answers: List[str]): num_cannot = 0 num_spans = 0 for ref in reference_answers: if ref == 'CANNOTANSWER': num_cannot += 1 else: num_spans += 1 if num_cannot >= num_spans: referen...
[ "\n Process a list of reference answers.\n If equal or more than half of the reference answers are \"CANNOTANSWER\", take it as gold.\n Otherwise, return answers that are not \"CANNOTANSWER\".\n " ]
Please provide a description of the function:def get_best_span(span_start_logits: torch.Tensor, span_end_logits: torch.Tensor) -> torch.Tensor: if span_start_logits.dim() != 2 or span_end_logits.dim() != 2: raise ValueError("Input shapes must be (batch_size, passage_length)") batch_size, passage_le...
[ "\n This acts the same as the static method ``BidirectionalAttentionFlow.get_best_span()``\n in ``allennlp/models/reading_comprehension/bidaf.py``. We keep it here so that users can\n directly import this function without the class.\n\n We call the inputs \"logits\" - they could either be unnormalized l...
Please provide a description of the function:def batch_split_words(self, sentences: List[str]) -> List[List[Token]]: return [self.split_words(sentence) for sentence in sentences]
[ "\n Spacy needs to do batch processing, or it can be really slow. This method lets you take\n advantage of that if you want. Default implementation is to just iterate of the sentences\n and call ``split_words``, but the ``SpacyWordSplitter`` will actually do batched\n processing.\n ...
Please provide a description of the function:def constrained_to(self, initial_sequence: torch.Tensor, keep_beam_details: bool = True) -> 'BeamSearch': return BeamSearch(self._beam_size, self._per_node_beam_size, initial_sequence, keep_beam_details)
[ "\n Return a new BeamSearch instance that's like this one but with the specified constraint.\n " ]
Please provide a description of the function:def search(self, num_steps: int, initial_state: StateType, transition_function: TransitionFunction, keep_final_unfinished_states: bool = True) -> Dict[int, List[StateType]]: finished_states: Dict[in...
[ "\n Parameters\n ----------\n num_steps : ``int``\n How many steps should we take in our search? This is an upper bound, as it's possible\n for the search to run out of valid actions before hitting this number, or for all\n states on the beam to finish.\n ...
Please provide a description of the function:def _normalize_answer(text: str) -> str: parts = [_white_space_fix(_remove_articles(_normalize_number(_remove_punc(_lower(token))))) for token in _tokenize(text)] parts = [part for part in parts if part.strip()] normalized = ' '.join(parts).str...
[ "Lower text and remove punctuation, articles and extra whitespace." ]
Please provide a description of the function:def _align_bags(predicted: List[Set[str]], gold: List[Set[str]]) -> List[float]: f1_scores = [] for gold_index, gold_item in enumerate(gold): max_f1 = 0.0 max_index = None best_alignment: Tuple[Set[str], Set[str]] = (set(), set()) ...
[ "\n Takes gold and predicted answer sets and first finds a greedy 1-1 alignment\n between them and gets maximum metric values over all the answers\n " ]
Please provide a description of the function:def get_metrics(predicted: Union[str, List[str], Tuple[str, ...]], gold: Union[str, List[str], Tuple[str, ...]]) -> Tuple[float, float]: predicted_bags = _answer_to_bags(predicted) gold_bags = _answer_to_bags(gold) exact_match = 1.0 if predi...
[ "\n Takes a predicted answer and a gold answer (that are both either a string or a list of\n strings), and returns exact match and the DROP F1 metric for the prediction. If you are\n writing a script for evaluating objects in memory (say, the output of predictions during\n validation, or while training...
Please provide a description of the function:def answer_json_to_strings(answer: Dict[str, Any]) -> Tuple[Tuple[str, ...], str]: if "number" in answer and answer["number"]: return tuple([str(answer["number"])]), "number" elif "spans" in answer and answer["spans"]: return tuple(answer["spans"...
[ "\n Takes an answer JSON blob from the DROP data release and converts it into strings used for\n evaluation.\n " ]
Please provide a description of the function:def evaluate_json(annotations: Dict[str, Any], predicted_answers: Dict[str, Any]) -> Tuple[float, float]: instance_exact_match = [] instance_f1 = [] # for each type as well type_to_em: Dict[str, List[float]] = defaultdict(list) type_to_f1: Dict[str, ...
[ "\n Takes gold annotations and predicted answers and evaluates the predictions for each question\n in the gold annotations. Both JSON dictionaries must have query_id keys, which are used to\n match predictions to gold annotations (note that these are somewhat deep in the JSON for the\n gold annotation...
Please provide a description of the function:def evaluate_prediction_file(prediction_path: str, gold_path: str) -> Tuple[float, float]: predicted_answers = json.load(open(prediction_path, encoding='utf-8')) annotations = json.load(open(gold_path, encoding='utf-8')) return evaluate_json(annotations, pre...
[ "\n Takes a prediction file and a gold file and evaluates the predictions for each question in the\n gold file. Both files must be json formatted and must have query_id keys, which are used to\n match predictions to gold annotations. The gold file is assumed to have the format of the dev\n set in the ...
Please provide a description of the function:def cache_data(self, cache_directory: str) -> None: self._cache_directory = pathlib.Path(cache_directory) os.makedirs(self._cache_directory, exist_ok=True)
[ "\n When you call this method, we will use this directory to store a cache of already-processed\n ``Instances`` in every file passed to :func:`read`, serialized as one string-formatted\n ``Instance`` per line. If the cache file for a given ``file_path`` exists, we read the\n ``Instances...