Code
stringlengths
103
85.9k
Summary
listlengths
0
94
Please provide a description of the function:def peak_memory_mb() -> float: if resource is None or sys.platform not in ('linux', 'darwin'): return 0.0 # TODO(joelgrus): For whatever, our pinned version 0.521 of mypy does not like # next line, but later versions (e.g. 0.530) are fine with it. O...
[ "\n Get peak memory usage for this process, as measured by\n max-resident-set size:\n\n https://unix.stackexchange.com/questions/30940/getrusage-system-call-what-is-maximum-resident-set-size\n\n Only works on OSX and Linux, returns 0.0 otherwise.\n " ]
Please provide a description of the function:def gpu_memory_mb() -> Dict[int, int]: # pylint: disable=bare-except try: result = subprocess.check_output(['nvidia-smi', '--query-gpu=memory.used', '--format=csv,nounits,noheader'], ...
[ "\n Get the current GPU memory usage.\n Based on https://discuss.pytorch.org/t/access-gpu-memory-usage-in-pytorch/3192/4\n\n Returns\n -------\n ``Dict[int, int]``\n Keys are device ids as integers.\n Values are memory usage as integers in MB.\n Returns an empty ``dict`` if GPUs ...
Please provide a description of the function:def ensure_list(iterable: Iterable[A]) -> List[A]: if isinstance(iterable, list): return iterable else: return list(iterable)
[ "\n An Iterable may be a list or a generator.\n This ensures we get a list without making an unnecessary copy.\n " ]
Please provide a description of the function:def update(self, action: torch.Tensor) -> 'ChecklistStatelet': checklist_addition = (self.terminal_actions == action).float() new_checklist = self.checklist + checklist_addition new_checklist_state = ChecklistStatelet(terminal_actions=self.te...
[ "\n Takes an action index, updates checklist and returns an updated state.\n " ]
Please provide a description of the function:def _remove_action_from_type(valid_actions: Dict[str, List[str]], type_: str, filter_function: Callable[[str], bool]) -> None: action_list = valid_actions[type_] matching_action_index ...
[ "\n Finds the production rule matching the filter function in the given type's valid action\n list, and removes it. If there is more than one matching function, we crash.\n " ]
Please provide a description of the function:def forward(self, # pylint: disable=arguments-differ inputs: torch.FloatTensor, batch_lengths: List[int], initial_state: Optional[Tuple[torch.Tensor, torch.Tensor]] = None): batch_size = inputs.size()[0] ...
[ "\n Parameters\n ----------\n inputs : ``torch.FloatTensor``, required.\n A tensor of shape (batch_size, num_timesteps, input_size)\n to apply the LSTM over.\n batch_lengths : ``List[int]``, required.\n A list of length batch_size containing the lengths o...
Please provide a description of the function:def linkcode_resolve(domain, info): if domain != 'py': return None modname = info['module'] fullname = info['fullname'] submod = sys.modules.get(modname) if submod is None: return None obj = submod for part in fullname.spli...
[ "\n Determine the URL corresponding to Python object\n This code is from\n https://github.com/numpy/numpy/blob/master/doc/source/conf.py#L290\n and https://github.com/Lasagne/Lasagne/pull/262\n " ]
Please provide a description of the function:def _get_initial_rnn_and_grammar_state(self, question: Dict[str, torch.LongTensor], table: Dict[str, torch.LongTensor], world: List[WikiTablesWorl...
[ "\n Encodes the question and table, computes a linking between the two, and constructs an\n initial RnnStatelet and LambdaGrammarStatelet for each batch instance to pass to the\n decoder.\n\n We take ``outputs`` as a parameter here and `modify` it, adding things that we want to\n ...
Please provide a description of the function:def _get_neighbor_indices(worlds: List[WikiTablesWorld], num_entities: int, tensor: torch.Tensor) -> torch.LongTensor: num_neighbors = 0 for world in worlds: for entity in world...
[ "\n This method returns the indices of each entity's neighbors. A tensor\n is accepted as a parameter for copying purposes.\n\n Parameters\n ----------\n worlds : ``List[WikiTablesWorld]``\n num_entities : ``int``\n tensor : ``torch.Tensor``\n Used for cop...
Please provide a description of the function:def _get_type_vector(worlds: List[WikiTablesWorld], num_entities: int, tensor: torch.Tensor) -> Tuple[torch.LongTensor, Dict[int, int]]: entity_types = {} batch_types = [] for batch_index, wor...
[ "\n Produces a tensor with shape ``(batch_size, num_entities)`` that encodes each entity's\n type. In addition, a map from a flattened entity index to type is returned to combine\n entity type operations into one method.\n\n Parameters\n ----------\n worlds : ``List[WikiTab...
Please provide a description of the function:def _get_linking_probabilities(self, worlds: List[WikiTablesWorld], linking_scores: torch.FloatTensor, question_mask: torch.LongTensor, ...
[ "\n Produces the probability of an entity given a question word and type. The logic below\n separates the entities by type since the softmax normalization term sums over entities\n of a single type.\n\n Parameters\n ----------\n worlds : ``List[WikiTablesWorld]``\n l...
Please provide a description of the function:def get_metrics(self, reset: bool = False) -> Dict[str, float]: return { 'dpd_acc': self._action_sequence_accuracy.get_metric(reset), 'denotation_acc': self._denotation_accuracy.get_metric(reset), 'lf_percent':...
[ "\n We track three metrics here:\n\n 1. dpd_acc, which is the percentage of the time that our best output action sequence is\n in the set of action sequences provided by DPD. This is an easy-to-compute lower bound\n on denotation accuracy for the set of examples where we act...
Please provide a description of the function:def _create_grammar_state(self, world: WikiTablesWorld, possible_actions: List[ProductionRule], linking_scores: torch.Tensor, entity_types: torch.Tensor) -...
[ "\n This method creates the LambdaGrammarStatelet object that's used for decoding. Part of\n creating that is creating the `valid_actions` dictionary, which contains embedded\n representations of all of the valid actions. So, we create that here as well.\n\n The way we represent the va...
Please provide a description of the function:def _compute_validation_outputs(self, actions: List[List[ProductionRule]], best_final_states: Mapping[int, Sequence[GrammarBasedState]], world: List[WikiTablesWorld], ...
[ "\n Does common things for validation time: computing logical form accuracy (which is expensive\n and unnecessary during training), adding visualization info to the output dictionary, etc.\n\n This doesn't return anything; instead it `modifies` the given ``outputs`` dictionary, and\n cal...
Please provide a description of the function:def decode(self, output_dict: Dict[str, torch.Tensor]) -> Dict[str, torch.Tensor]: action_mapping = output_dict['action_mapping'] best_actions = output_dict["best_action_sequence"] debug_infos = output_dict['debug_info'] batch_action_...
[ "\n This method overrides ``Model.decode``, which gets called after ``Model.forward``, at test\n time, to finalize predictions. This is (confusingly) a separate notion from the \"decoder\"\n in \"encoder/decoder\", where that decoder logic lives in the ``TransitionFunction``.\n\n This m...
Please provide a description of the function:def _get_linked_logits_addition(checklist_state: ChecklistStatelet, action_ids: List[int], action_logits: torch.Tensor) -> torch.Tensor: # Our basic approach here will be to figure out w...
[ "\n Gets the logits of desired terminal actions yet to be produced by the decoder, and\n returns them for the decoder to add to the prior action logits, biasing the model towards\n predicting missing linked actions.\n " ]
Please provide a description of the function:def attend_on_question(self, query: torch.Tensor, encoder_outputs: torch.Tensor, encoder_output_mask: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]: # (group_size, question...
[ "\n Given a query (which is typically the decoder hidden state), compute an attention over the\n output of the question encoder, and return a weighted sum of the question representations\n given this attention. We also return the attention weights themselves.\n\n This is a simple comput...
Please provide a description of the function:def _walk(self) -> None: # Buffer of NTs to expand, previous actions incomplete_paths = [([str(type_)], [f"{START_SYMBOL} -> {type_}"]) for type_ in self._world.get_valid_starting_types()] self._completed_paths = ...
[ "\n Walk over action space to collect completed paths of at most ``self._max_path_length`` steps.\n " ]
Please provide a description of the function:def _check_types(self) -> None: all_instance_fields_and_types: List[Dict[str, str]] = [{k: v.__class__.__name__ for k, v in x.fields.items()} ...
[ "\n Check that all the instances have the same types.\n " ]
Please provide a description of the function:def get_padding_lengths(self) -> Dict[str, Dict[str, int]]: padding_lengths: Dict[str, Dict[str, int]] = defaultdict(dict) all_instance_lengths: List[Dict[str, Dict[str, int]]] = [instance.get_padding_lengths() ...
[ "\n Gets the maximum padding lengths from all ``Instances`` in this batch. Each ``Instance``\n has multiple ``Fields``, and each ``Field`` could have multiple things that need padding.\n We look at all fields in all instances, and find the max values for each (field_name,\n padding_key)...
Please provide a description of the function:def as_tensor_dict(self, padding_lengths: Dict[str, Dict[str, int]] = None, verbose: bool = False) -> Dict[str, Union[torch.Tensor, Dict[str, torch.Tensor]]]: # This complex return type is actually predefined elsewhere as...
[ "\n This method converts this ``Batch`` into a set of pytorch Tensors that can be passed\n through a model. In order for the tensors to be valid tensors, all ``Instances`` in this\n batch need to be padded to the same lengths wherever padding is necessary, so we do that\n first, then we...
Please provide a description of the function:def get_strings_from_utterance(tokenized_utterance: List[Token]) -> Dict[str, List[int]]: string_linking_scores: Dict[str, List[int]] = defaultdict(list) for index, token in enumerate(tokenized_utterance): for string in ATIS_TRIGGER_DICT.get(token.text....
[ "\n Based on the current utterance, return a dictionary where the keys are the strings in\n the database that map to lists of the token indices that they are linked to.\n " ]
Please provide a description of the function:def _update_grammar(self): # This will give us a shallow copy. We have to be careful here because the ``Grammar`` object # contains ``Expression`` objects that have tuples containing the members of that expression. # We have to create new su...
[ "\n We create a new ``Grammar`` object from the one in ``AtisSqlTableContext``, that also\n has the new entities that are extracted from the utterance. Stitching together the expressions\n to form the grammar is a little tedious here, but it is worth it because we don't have to create\n ...
Please provide a description of the function:def _update_expression_reference(self, # pylint: disable=no-self-use grammar: Grammar, parent_expression_nonterminal: str, child_expression_nonterminal: str) -> Non...
[ "\n When we add a new expression, there may be other expressions that refer to\n it, and we need to update those to point to the new expression.\n " ]
Please provide a description of the function:def _get_sequence_with_spacing(self, # pylint: disable=no-self-use new_grammar, expressions: List[Expression], name: str = '') -> Sequence: expressions =...
[ "\n This is a helper method for generating sequences, since we often want a list of expressions\n with whitespaces between them.\n " ]
Please provide a description of the function:def add_to_number_linking_scores(self, all_numbers: Set[str], number_linking_scores: Dict[str, Tuple[str, str, List[int]]], get_number_linking_dict: Callable[[str, ...
[ "\n This is a helper method for adding different types of numbers (eg. starting time ranges) as entities.\n We first go through all utterances in the interaction and find the numbers of a certain type and add\n them to the set ``all_numbers``, which is initialized with default values. We want t...
Please provide a description of the function:def _get_linked_entities(self) -> Dict[str, Dict[str, Tuple[str, str, List[int]]]]: current_tokenized_utterance = [] if not self.tokenized_utterances \ else self.tokenized_utterances[-1] # We generate a dictionary where the key is th...
[ "\n This method gets entities from the current utterance finds which tokens they are linked to.\n The entities are divided into two main groups, ``numbers`` and ``strings``. We rely on these\n entities later for updating the valid actions and the grammar.\n " ]
Please provide a description of the function:def all_possible_actions(self) -> List[str]: all_actions = set() for _, action_list in self.valid_actions.items(): for action in action_list: all_actions.add(action) return sorted(all_actions)
[ "\n Return a sorted list of strings representing all possible actions\n of the form: nonterminal -> [right_hand_side]\n " ]
Please provide a description of the function:def _flatten_entities(self) -> Tuple[List[str], numpy.ndarray]: entities = [] linking_scores = [] for entity in sorted(self.linked_entities['number']): entities.append(entity) linking_scores.append(self.linked_entities...
[ "\n When we first get the entities and the linking scores in ``_get_linked_entities``\n we represent as dictionaries for easier updates to the grammar and valid actions.\n In this method, we flatten them for the model so that the entities are represented as\n a list, and the linking scor...
Please provide a description of the function:def make_app(include_packages: Sequence[str] = ()) -> Flask: # Load modules for package_name in include_packages: import_submodules(package_name) app = Flask(__name__) # pylint: disable=invalid-name @app.errorhandler(ServerError) def handl...
[ "\n Creates a Flask app that serves up a simple configuration wizard.\n ", "\n There are basically two things that can happen here.\n If this method is called with a ``Registrable`` class (e.g. ``Model``),\n it should return the list of possible ``Model`` subclasses.\n If it is c...
Please provide a description of the function:def train_model_from_args(args: argparse.Namespace): train_model_from_file(args.param_path, args.serialization_dir, args.overrides, args.file_friendly_logging, ar...
[ "\n Just converts from an ``argparse.Namespace`` object to string paths.\n " ]
Please provide a description of the function:def train_model_from_file(parameter_filename: str, serialization_dir: str, overrides: str = "", file_friendly_logging: bool = False, recover: bool = False, ...
[ "\n A wrapper around :func:`train_model` which loads the params from a file.\n\n Parameters\n ----------\n parameter_filename : ``str``\n A json parameter file specifying an AllenNLP experiment.\n serialization_dir : ``str``\n The directory in which to save results and logs. We just pas...
Please provide a description of the function:def train_model(params: Params, serialization_dir: str, file_friendly_logging: bool = False, recover: bool = False, force: bool = False, cache_directory: str = None, cache_prefix:...
[ "\n Trains the model specified in the given :class:`Params` object, using the data and training\n parameters also specified in that object, and saves the results in ``serialization_dir``.\n\n Parameters\n ----------\n params : ``Params``\n A parameter object specifying an AllenNLP Experiment.\...
Please provide a description of the function:def _prf_divide(numerator, denominator): result = numerator / denominator mask = denominator == 0.0 if not mask.any(): return result # remove nan result[mask] = 0.0 return result
[ "Performs division and handles divide-by-zero.\n\n On zero-division, sets the corresponding result elements to zero.\n " ]
Please provide a description of the function:def load_data(file_path: str) -> Tuple[List[str], List[str]]: data = [] with open(file_path) as f: for line in f: pairs = line.strip().split() sentence, tags = zip(*(pair.split("###") for pair in pairs)) data.append((...
[ "\n One sentence per line, formatted like\n\n The###DET dog###NN ate###V the###DET apple###NN\n\n Returns a list of pairs (tokenized_sentence, tags)\n " ]
Please provide a description of the function:def pop_max_vocab_size(params: Params) -> Union[int, Dict[str, int]]: size = params.pop("max_vocab_size", None) if isinstance(size, Params): # This is the Dict[str, int] case. return size.as_dict() elif size is not None: # This is th...
[ "\n max_vocab_size limits the size of the vocabulary, not including the @@UNKNOWN@@ token.\n\n max_vocab_size is allowed to be either an int or a Dict[str, int] (or nothing).\n But it could also be a string representing an int (in the case of environment variable\n substitution). So we need some complex...
Please provide a description of the function:def save_to_files(self, directory: str) -> None: os.makedirs(directory, exist_ok=True) if os.listdir(directory): logging.warning("vocabulary serialization directory %s is not empty", directory) with codecs.open(os.path.join(direc...
[ "\n Persist this Vocabulary to files so it can be reloaded later.\n Each namespace corresponds to one file.\n\n Parameters\n ----------\n directory : ``str``\n The directory where we save the serialized vocabulary.\n " ]
Please provide a description of the function:def from_files(cls, directory: str) -> 'Vocabulary': logger.info("Loading token dictionary from %s.", directory) with codecs.open(os.path.join(directory, NAMESPACE_PADDING_FILE), 'r', 'utf-8') as namespace_file: non_padded_namespaces = [n...
[ "\n Loads a ``Vocabulary`` that was serialized using ``save_to_files``.\n\n Parameters\n ----------\n directory : ``str``\n The directory containing the serialized vocabulary.\n " ]
Please provide a description of the function:def set_from_file(self, filename: str, is_padded: bool = True, oov_token: str = DEFAULT_OOV_TOKEN, namespace: str = "tokens"): if is_padded: self._token_to_in...
[ "\n If you already have a vocabulary file for a trained model somewhere, and you really want to\n use that vocabulary file instead of just setting the vocabulary from a dataset, for\n whatever reason, you can do that with this method. You must specify the namespace to use,\n and we assu...
Please provide a description of the function:def from_instances(cls, instances: Iterable['adi.Instance'], min_count: Dict[str, int] = None, max_vocab_size: Union[int, Dict[str, int]] = None, non_padded_namespaces: Iterable[str] ...
[ "\n Constructs a vocabulary given a collection of `Instances` and some parameters.\n We count all of the vocabulary items in the instances, then pass those counts\n and the other parameters, to :func:`__init__`. See that method for a description\n of what the other parameters do.\n ...
Please provide a description of the function:def from_params(cls, params: Params, instances: Iterable['adi.Instance'] = None): # type: ignore # pylint: disable=arguments-differ # Vocabulary is ``Registrable`` so that you can configure a custom subclass, # but (unlike most of our regist...
[ "\n There are two possible ways to build a vocabulary; from a\n collection of instances, using :func:`Vocabulary.from_instances`, or\n from a pre-saved vocabulary, using :func:`Vocabulary.from_files`.\n You can also extend pre-saved vocabulary with collection of instances\n using ...
Please provide a description of the function:def _extend(self, counter: Dict[str, Dict[str, int]] = None, min_count: Dict[str, int] = None, max_vocab_size: Union[int, Dict[str, int]] = None, non_padded_namespaces: Iterable[str] = DEFAULT_NON_PADDED_NAMESPA...
[ "\n This method can be used for extending already generated vocabulary.\n It takes same parameters as Vocabulary initializer. The token2index\n and indextotoken mappings of calling vocabulary will be retained.\n It is an inplace operation so None will be returned.\n " ]
Please provide a description of the function:def extend_from_instances(self, params: Params, instances: Iterable['adi.Instance'] = ()) -> None: min_count = params.pop("min_count", None) max_vocab_size = pop_max_vocab_size(params) ...
[ "\n Extends an already generated vocabulary using a collection of instances.\n " ]
Please provide a description of the function:def is_padded(self, namespace: str) -> bool: return self._index_to_token[namespace][0] == self._padding_token
[ "\n Returns whether or not there are padding and OOV tokens added to the given namespace.\n " ]
Please provide a description of the function:def add_token_to_namespace(self, token: str, namespace: str = 'tokens') -> int: if not isinstance(token, str): raise ValueError("Vocabulary tokens must be strings, or saving and loading will break." " Got %s (with ty...
[ "\n Adds ``token`` to the index, if it is not already present. Either way, we return the index of\n the token.\n " ]
Please provide a description of the function:def get_regularization_penalty(self) -> Union[float, torch.Tensor]: if self._regularizer is None: return 0.0 else: return self._regularizer(self)
[ "\n Computes the regularization penalty for the model.\n Returns 0 if the model was not configured to use regularization.\n " ]
Please provide a description of the function:def forward_on_instance(self, instance: Instance) -> Dict[str, numpy.ndarray]: return self.forward_on_instances([instance])[0]
[ "\n Takes an :class:`~allennlp.data.instance.Instance`, which typically has raw text in it,\n converts that text into arrays using this model's :class:`Vocabulary`, passes those arrays\n through :func:`self.forward()` and :func:`self.decode()` (which by default does nothing)\n and return...
Please provide a description of the function:def forward_on_instances(self, instances: List[Instance]) -> List[Dict[str, numpy.ndarray]]: batch_size = len(instances) with torch.no_grad(): cuda_device = self._get_prediction_device() dataset = ...
[ "\n Takes a list of :class:`~allennlp.data.instance.Instance`s, converts that text into\n arrays using this model's :class:`Vocabulary`, passes those arrays through\n :func:`self.forward()` and :func:`self.decode()` (which by default does nothing)\n and returns the result. Before retur...
Please provide a description of the function:def decode(self, output_dict: Dict[str, torch.Tensor]) -> Dict[str, torch.Tensor]: # pylint: disable=no-self-use return output_dict
[ "\n Takes the result of :func:`forward` and runs inference / decoding / whatever\n post-processing you need to do your model. The intent is that ``model.forward()`` should\n produce potentials or probabilities, and then ``model.decode()`` can take those results and\n run some kind of be...
Please provide a description of the function:def _get_prediction_device(self) -> int: devices = {util.get_device_of(param) for param in self.parameters()} if len(devices) > 1: devices_string = ", ".join(str(x) for x in devices) raise ConfigurationError(f"Parameters have...
[ "\n This method checks the device of the model parameters to determine the cuda_device\n this model should be run on for predictions. If there are no parameters, it returns -1.\n\n Returns\n -------\n The cuda device this model should run on for predictions.\n " ]
Please provide a description of the function:def _maybe_warn_for_unseparable_batches(self, output_key: str): if output_key not in self._warn_for_unseparable_batches: logger.warning(f"Encountered the {output_key} key in the model's return dictionary which " "could...
[ "\n This method warns once if a user implements a model which returns a dictionary with\n values which we are unable to split back up into elements of the batch. This is controlled\n by a class attribute ``_warn_for_unseperable_batches`` because it would be extremely verbose\n otherwise....
Please provide a description of the function:def _load(cls, config: Params, serialization_dir: str, weights_file: str = None, cuda_device: int = -1) -> 'Model': weights_file = weights_file or os.path.join(serialization_dir, _DEFAULT_WEIGHTS) ...
[ "\n Instantiates an already-trained model, based on the experiment\n configuration and some optional overrides.\n " ]
Please provide a description of the function:def load(cls, config: Params, serialization_dir: str, weights_file: str = None, cuda_device: int = -1) -> 'Model': # Peak at the class of the model. model_type = config["model"]["type"] # ...
[ "\n Instantiates an already-trained model, based on the experiment\n configuration and some optional overrides.\n\n Parameters\n ----------\n config: Params\n The configuration that was used to train the model. It should definitely\n have a `model` section, a...
Please provide a description of the function:def extend_embedder_vocab(self, embedding_sources_mapping: Dict[str, str] = None) -> None: # self.named_modules() gives all sub-modules (including nested children) # The path nesting is already separated by ".": eg. parent_module_name.child_module_na...
[ "\n Iterates through all embedding modules in the model and assures it can embed\n with the extended vocab. This is required in fine-tuning or transfer learning\n scenarios where model was trained with original vocabulary but during\n fine-tuning/tranfer-learning, it will have it work wi...
Please provide a description of the function:def get_agenda(self, conservative: bool = False): agenda_items = [] question_tokens = [token.text for token in self.table_context.question_tokens] question = " ".join(question_tokens) added_number_filters = False ...
[ "\n Returns an agenda that can be used guide search.\n\n Parameters\n ----------\n conservative : ``bool``\n Setting this flag will return a subset of the agenda items that correspond to high\n confidence lexical matches. You'll need this if you are going to use thi...
Please provide a description of the function:def evaluate_logical_form(self, logical_form: str, target_list: List[str]) -> bool: normalized_target_list = [TableQuestionContext.normalize_string(value) for value in target_list] target_value_list = evaluator.to_va...
[ "\n Takes a logical form, and the list of target values as strings from the original lisp\n string, and returns True iff the logical form executes to the target list, using the\n official WikiTableQuestions evaluation script.\n " ]
Please provide a description of the function:def select_string(self, rows: List[Row], column: StringColumn) -> List[str]: return [str(row.values[column.name]) for row in rows if row.values[column.name] is not None]
[ "\n Select function takes a list of rows and a column name and returns a list of strings as\n in cells.\n " ]
Please provide a description of the function:def select_number(self, rows: List[Row], column: NumberColumn) -> Number: numbers: List[float] = [] for row in rows: cell_value = row.values[column.name] if isinstance(cell_value, float): numbers.append(cell_va...
[ "\n Select function takes a row (as a list) and a column name and returns the number in that\n column. If multiple rows are given, will return the first number that is not None.\n " ]
Please provide a description of the function:def select_date(self, rows: List[Row], column: DateColumn) -> Date: dates: List[Date] = [] for row in rows: cell_value = row.values[column.name] if isinstance(cell_value, Date): dates.append(cell_value) ...
[ "\n Select function takes a row as a list and a column name and returns the date in that column.\n " ]
Please provide a description of the function:def same_as(self, rows: List[Row], column: Column) -> List[Row]: cell_value = rows[0].values[column.name] return_list = [] for table_row in self.table_data: if table_row.values[column.name] == cell_value: return_li...
[ "\n Takes a row and a column and returns a list of rows from the full set of rows that contain\n the same value under the given column as the given row.\n " ]
Please provide a description of the function:def date(self, year: Number, month: Number, day: Number) -> Date: return Date(year, month, day)
[ "\n Takes three numbers and returns a ``Date`` object whose year, month, and day are the three\n numbers in that order.\n " ]
Please provide a description of the function:def first(self, rows: List[Row]) -> List[Row]: if not rows: logger.warning("Trying to get first row from an empty list") return [] return [rows[0]]
[ "\n Takes an expression that evaluates to a list of rows, and returns the first one in that\n list.\n " ]
Please provide a description of the function:def last(self, rows: List[Row]) -> List[Row]: if not rows: logger.warning("Trying to get last row from an empty list") return [] return [rows[-1]]
[ "\n Takes an expression that evaluates to a list of rows, and returns the last one in that\n list.\n " ]
Please provide a description of the function:def previous(self, rows: List[Row]) -> List[Row]: if not rows: return [] input_row_index = self._get_row_index(rows[0]) if input_row_index > 0: return [self.table_data[input_row_index - 1]] return []
[ "\n Takes an expression that evaluates to a single row, and returns the row that occurs before\n the input row in the original set of rows. If the input row happens to be the top row, we\n will return an empty list.\n " ]
Please provide a description of the function:def next(self, rows: List[Row]) -> List[Row]: if not rows: return [] input_row_index = self._get_row_index(rows[0]) if input_row_index < len(self.table_data) - 1 and input_row_index != -1: return [self.table_data[input...
[ "\n Takes an expression that evaluates to a single row, and returns the row that occurs after\n the input row in the original set of rows. If the input row happens to be the last row, we\n will return an empty list.\n " ]
Please provide a description of the function:def mode_string(self, rows: List[Row], column: StringColumn) -> List[str]: most_frequent_list = self._get_most_frequent_values(rows, column) if not most_frequent_list: return [] if not all([isinstance(value, str) for value in most...
[ "\n Takes a list of rows and a column and returns the most frequent values (one or more) under\n that column in those rows.\n " ]
Please provide a description of the function:def mode_number(self, rows: List[Row], column: NumberColumn) -> Number: most_frequent_list = self._get_most_frequent_values(rows, column) if not most_frequent_list: return 0.0 # type: ignore most_frequent_value = most_frequent_li...
[ "\n Takes a list of rows and a column and returns the most frequent value under\n that column in those rows.\n " ]
Please provide a description of the function:def mode_date(self, rows: List[Row], column: DateColumn) -> Date: most_frequent_list = self._get_most_frequent_values(rows, column) if not most_frequent_list: return Date(-1, -1, -1) most_frequent_value = most_frequent_list[0] ...
[ "\n Takes a list of rows and a column and returns the most frequent value under\n that column in those rows.\n " ]
Please provide a description of the function:def argmax(self, rows: List[Row], column: ComparableColumn) -> List[Row]: if not rows: return [] value_row_pairs = [(row.values[column.name], row) for row in rows] if not value_row_pairs: return [] # Returns a ...
[ "\n Takes a list of rows and a column name and returns a list containing a single row (dict from\n columns to cells) that has the maximum numerical value in the given column. We return a list\n instead of a single dict to be consistent with the return type of ``select`` and\n ``all_rows`...
Please provide a description of the function:def argmin(self, rows: List[Row], column: ComparableColumn) -> List[Row]: if not rows: return [] value_row_pairs = [(row.values[column.name], row) for row in rows] if not value_row_pairs: return [] # Returns a ...
[ "\n Takes a list of rows and a column and returns a list containing a single row (dict from\n columns to cells) that has the minimum numerical value in the given column. We return a list\n instead of a single dict to be consistent with the return type of ``select`` and\n ``all_rows``.\n ...
Please provide a description of the function:def max_date(self, rows: List[Row], column: DateColumn) -> Date: cell_values = [row.values[column.name] for row in rows] if not cell_values: return Date(-1, -1, -1) if not all([isinstance(value, Date) for value in cell_values]): ...
[ "\n Takes a list of rows and a column and returns the max of the values under that column in\n those rows.\n " ]
Please provide a description of the function:def max_number(self, rows: List[Row], column: NumberColumn) -> Number: cell_values = [row.values[column.name] for row in rows] if not cell_values: return 0.0 # type: ignore if not all([isinstance(value, Number) for value in cell_...
[ "\n Takes a list of rows and a column and returns the max of the values under that column in\n those rows.\n " ]
Please provide a description of the function:def average(self, rows: List[Row], column: NumberColumn) -> Number: cell_values = [row.values[column.name] for row in rows] if not cell_values: return 0.0 # type: ignore return sum(cell_values) / len(cell_values)
[ "\n Takes a list of rows and a column and returns the mean of the values under that column in\n those rows.\n " ]
Please provide a description of the function:def diff(self, first_row: List[Row], second_row: List[Row], column: NumberColumn) -> Number: if not first_row or not second_row: return 0.0 # type: ignore first_value = first_row[0].values[column.name] second_value = second_row[0...
[ "\n Takes a two rows and a number column and returns the difference between the values under\n that column in those two rows.\n " ]
Please provide a description of the function:def _get_row_index(self, row: Row) -> int: row_index = -1 for index, table_row in enumerate(self.table_data): if table_row.values == row.values: row_index = index break return row_index
[ "\n Takes a row and returns its index in the full list of rows. If the row does not occur in the\n table (which should never happen because this function will only be called with a row that\n is the result of applying one or more functions on the table rows), the method returns -1.\n " ]
Please provide a description of the function:def is_terminal(self, symbol: str) -> bool: # We special-case 'lambda' here because it behaves weirdly in action sequences. return (symbol in self.global_name_mapping or symbol in self.local_name_mapping or 'lambda' in...
[ "\n This function will be called on nodes of a logical form tree, which are either non-terminal\n symbols that can be expanded or terminal symbols that must be leaf nodes. Returns ``True``\n if the given symbol is a terminal symbol.\n " ]
Please provide a description of the function:def get_paths_to_root(self, action: str, max_path_length: int = 20, beam_size: int = 30, max_num_paths: int = 10) -> List[List[str]]: action_left_side, _ ...
[ "\n For a given action, returns at most ``max_num_paths`` paths to the root (production with\n ``START_SYMBOL``) that are not longer than ``max_path_length``.\n " ]
Please provide a description of the function:def get_multi_match_mapping(self) -> Dict[Type, List[Type]]: if self._multi_match_mapping is None: self._multi_match_mapping = {} basic_types = self.get_basic_types() for basic_type in basic_types: if isins...
[ "\n Returns a mapping from each `MultiMatchNamedBasicType` to all the `NamedBasicTypes` that it\n matches.\n " ]
Please provide a description of the function:def parse_logical_form(self, logical_form: str, remove_var_function: bool = True) -> Expression: if not logical_form.startswith("("): logical_form = f"({logical_form})" if remove_var_f...
[ "\n Takes a logical form as a string, maps its tokens using the mapping and returns a parsed expression.\n\n Parameters\n ----------\n logical_form : ``str``\n Logical form to parse\n remove_var_function : ``bool`` (optional)\n ``var`` is a special function t...
Please provide a description of the function:def get_action_sequence(self, expression: Expression) -> List[str]: # Starting with the type of the whole expression return self._get_transitions(expression, [f"{types.START_TYPE} -> {expression.type}"])
[ "\n Returns the sequence of actions (as strings) that resulted in the given expression.\n " ]
Please provide a description of the function:def get_logical_form(self, action_sequence: List[str], add_var_function: bool = True) -> str: # Basic outline: we assume that the bracketing that we get in the RHS of each action is the # correct brac...
[ "\n Takes an action sequence and constructs a logical form from it. This is useful if you want\n to get a logical form from a decoded sequence of actions generated by a transition based\n semantic parser.\n\n Parameters\n ----------\n action_sequence : ``List[str]``\n ...
Please provide a description of the function:def _construct_node_from_actions(self, current_node: Tree, remaining_actions: List[List[str]], add_var_function: bool) -> List[List[str]]: if not r...
[ "\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 _infer_num_arguments(cls, type_signature: str) -> int: if not "<" in type_signature: return 0 # We need to find the return type from the signature. We do that by removing the outer most # angular brackets and traversing the re...
[ "\n Takes a type signature and infers the number of arguments the corresponding function takes.\n Examples:\n e -> 0\n <r,e> -> 1\n <e,<e,t>> -> 2\n <b,<<b,#1>,<#1,b>>> -> 3\n " ]
Please provide a description of the function:def _process_nested_expression(self, nested_expression) -> str: expression_is_list = isinstance(nested_expression, list) expression_size = len(nested_expression) if expression_is_list and expression_size == 1 and isinstance(nested_expression[...
[ "\n ``nested_expression`` is the result of parsing a logical form in Lisp format.\n We process it recursively and return a string in the format that NLTK's ``LogicParser``\n would understand.\n " ]
Please provide a description of the function:def _add_name_mapping(self, name: str, translated_name: str, name_type: Type = None): self.local_name_mapping[name] = translated_name self.reverse_name_mapping[translated_name] = name if name_type: self.local_type_signatures[trans...
[ "\n Utility method to add a name and its translation to the local name mapping, and the corresponding\n signature, if available to the local type signatures. This method also updates the reverse name\n mapping.\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): if not isinstance(inputs, PackedSequence): raise ConfigurationError(...
[ "\n Parameters\n ----------\n inputs : PackedSequence, required.\n A tensor of shape (batch_size, num_timesteps, input_size)\n to apply the LSTM over.\n\n initial_state : Tuple[torch.Tensor, torch.Tensor], optional, (default = None)\n A tuple (state, memo...
Please provide a description of the function:def _create_sempre_executor(self) -> None: if self._executor_process: return # It'd be much nicer to just use `cached_path` for these files. However, the SEMPRE jar # that we're using expects to find these files in a particular ...
[ "\n Creates a server running SEMPRE that we can send logical forms to for evaluation. This\n uses inter-process communication, because SEMPRE is java code. We also need to be careful\n to clean up the process when our program exits.\n " ]
Please provide a description of the function:def b_cubed(clusters, mention_to_gold): numerator, denominator = 0, 0 for cluster in clusters: if len(cluster) == 1: continue gold_counts = Counter() correct = 0 for mention in cluster: ...
[ "\n Averaged per-mention precision and recall.\n <https://pdfs.semanticscholar.org/cfe3/c24695f1c14b78a5b8e95bcbd1c666140fd1.pdf>\n " ]
Please provide a description of the function:def muc(clusters, mention_to_gold): true_p, all_p = 0, 0 for cluster in clusters: all_p += len(cluster) - 1 true_p += len(cluster) linked = set() for mention in cluster: if mention in me...
[ "\n Counts the mentions in each predicted cluster which need to be re-allocated in\n order for each predicted cluster to be contained by the respective gold cluster.\n <http://aclweb.org/anthology/M/M95/M95-1005.pdf>\n " ]
Please provide a description of the function:def phi4(gold_clustering, predicted_clustering): return 2 * len([mention for mention in gold_clustering if mention in predicted_clustering]) \ / float(len(gold_clustering) + len(predicted_clustering))
[ "\n Subroutine for ceafe. Computes the mention F measure between gold and\n predicted mentions in a cluster.\n " ]
Please provide a description of the function:def ceafe(clusters, gold_clusters): clusters = [cluster for cluster in clusters if len(cluster) != 1] scores = np.zeros((len(gold_clusters), len(clusters))) for i, gold_cluster in enumerate(gold_clusters): for j, cluster in enumer...
[ "\n Computes the Constrained EntityAlignment F-Measure (CEAF) for evaluating coreference.\n Gold and predicted mentions are aligned into clusterings which maximise a metric - in\n this case, the F measure between gold and predicted clusters.\n\n <https://www.semanticscholar.org/paper/On...
Please provide a description of the function:def take_action(self, production_rule: str) -> 'GrammarStatelet': 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. Updating the non-terminal stack involves popping\n the n...
Please provide a description of the function:def sparse_clip_norm(parameters, max_norm, norm_type=2) -> float: # pylint: disable=invalid-name,protected-access parameters = list(filter(lambda p: p.grad is not None, parameters)) max_norm = float(max_norm) norm_type = float(norm_type) if norm_type...
[ "Clips gradient norm of an iterable of parameters.\n\n The norm is computed over all gradients together, as if they were\n concatenated into a single vector. Gradients are modified in-place.\n Supports sparse gradients.\n\n Parameters\n ----------\n parameters : ``(Iterable[torch.Tensor])``\n ...
Please provide a description of the function:def move_optimizer_to_cuda(optimizer): for param_group in optimizer.param_groups: for param in param_group['params']: if param.is_cuda: param_state = optimizer.state[param] for k in param_state.keys(): ...
[ "\n Move the optimizer state to GPU, if necessary.\n After calling, any parameter specific state in the optimizer\n will be located on the same device as the parameter.\n " ]
Please provide a description of the function:def get_batch_size(batch: Union[Dict, torch.Tensor]) -> int: if isinstance(batch, torch.Tensor): return batch.size(0) # type: ignore elif isinstance(batch, Dict): return get_batch_size(next(iter(batch.values()))) else: return 0
[ "\n Returns the size of the batch dimension. Assumes a well-formed batch,\n returns 0 otherwise.\n " ]
Please provide a description of the function:def time_to_str(timestamp: int) -> str: datetimestamp = datetime.datetime.fromtimestamp(timestamp) return '{:04d}-{:02d}-{:02d}-{:02d}-{:02d}-{:02d}'.format( datetimestamp.year, datetimestamp.month, datetimestamp.day, datetimestamp.hour, ...
[ "\n Convert seconds past Epoch to human readable string.\n " ]
Please provide a description of the function:def str_to_time(time_str: str) -> datetime.datetime: pieces: Any = [int(piece) for piece in time_str.split('-')] return datetime.datetime(*pieces)
[ "\n Convert human readable string to datetime.datetime.\n " ]
Please provide a description of the function:def datasets_from_params(params: Params, cache_directory: str = None, cache_prefix: str = None) -> Dict[str, Iterable[Instance]]: dataset_reader_params = params.pop('dataset_reader') validation_dataset_reader_par...
[ "\n Load all the datasets specified by the config.\n\n Parameters\n ----------\n params : ``Params``\n cache_directory : ``str``, optional\n If given, we will instruct the ``DatasetReaders`` that we construct to cache their\n instances in this location (or read their instances from cach...
Please provide a description of the function:def create_serialization_dir( params: Params, serialization_dir: str, recover: bool, force: bool) -> None: if recover and force: raise ConfigurationError("Illegal arguments: both force and recover are true.") if os.path.e...
[ "\n This function creates the serialization directory if it doesn't exist. If it already exists\n and is non-empty, then it verifies that we're recovering from a training with an identical configuration.\n\n Parameters\n ----------\n params: ``Params``\n A parameter object specifying an Allen...
Please provide a description of the function:def data_parallel(batch_group: List[TensorDict], model: Model, cuda_devices: List) -> Dict[str, torch.Tensor]: assert len(batch_group) <= len(cuda_devices) moved = [nn_util.move_to_device(batch, device) for batch...
[ "\n Performs a forward pass using multiple GPUs. This is a simplification\n of torch.nn.parallel.data_parallel to support the allennlp model\n interface.\n " ]