INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Returns all objects that touch the given set of objects.
def touch_object(self, objects: Set[Object]) -> Set[Object]: """ Returns all objects that touch the given set of objects. """ objects_per_box = self._separate_objects_by_boxes(objects) return_set = set() for box, box_objects in objects_per_box.items(): candida...
Return the topmost objects ( i. e. minimum y_loc ). The comparison is done separately for each box.
def top(self, objects: Set[Object]) -> Set[Object]: """ Return the topmost objects (i.e. minimum y_loc). The comparison is done separately for each box. """ objects_per_box = self._separate_objects_by_boxes(objects) return_set: Set[Object] = set() for _, box_objec...
Return the bottom most objects ( i. e. maximum y_loc ). The comparison is done separately for each box.
def bottom(self, objects: Set[Object]) -> Set[Object]: """ Return the bottom most objects(i.e. maximum y_loc). The comparison is done separately for each box. """ objects_per_box = self._separate_objects_by_boxes(objects) return_set: Set[Object] = set() for _, box...
Returns the set of objects in the same boxes that are above the given objects. That is if the input is a set of two objects one in each box we will return a union of the objects above the first object in the first box and those above the second object in the second box.
def above(self, objects: Set[Object]) -> Set[Object]: """ Returns the set of objects in the same boxes that are above the given objects. That is, if the input is a set of two objects, one in each box, we will return a union of the objects above the first object in the first box, and thos...
Returns the set of objects in the same boxes that are below the given objects. That is if the input is a set of two objects one in each box we will return a union of the objects below the first object in the first box and those below the second object in the second box.
def below(self, objects: Set[Object]) -> Set[Object]: """ Returns the set of objects in the same boxes that are below the given objects. That is, if the input is a set of two objects, one in each box, we will return a union of the objects below the first object in the first box, and thos...
Returns true iff the objects touch each other.
def _objects_touch_each_other(self, object1: Object, object2: Object) -> bool: """ Returns true iff the objects touch each other. """ in_vertical_range = object1.y_loc <= object2.y_loc + object2.size and \ object1.y_loc + object1.size >= object2.y_loc ...
Given a set of objects separate them by the boxes they belong to and return a dict.
def _separate_objects_by_boxes(self, objects: Set[Object]) -> Dict[Box, List[Object]]: """ Given a set of objects, separate them by the boxes they belong to and return a dict. """ objects_per_box: Dict[Box, List[Object]] = defaultdict(list) for box in self.boxes: for ...
Returns the set of objects for which the attribute function returns an attribute value that is most frequent in the initial set if the frequency is greater than 1. If not all objects have different attribute values and this method returns an empty set.
def _get_objects_with_same_attribute(self, objects: Set[Object], attribute_function: Callable[[Object], str]) -> Set[Object]: """ Returns the set of objects for which the attribute function returns an attribute value that ...
Given a possibly complex data structure check if it has any torch. Tensors in it.
def has_tensor(obj) -> bool: """ Given a possibly complex data structure, check if it has any torch.Tensors in it. """ if isinstance(obj, torch.Tensor): return True elif isinstance(obj, dict): return any(has_tensor(value) for value in obj.values()) elif isinstance(obj, (list,...
Given a structure ( possibly ) containing Tensors on the CPU move all the Tensors to the specified GPU ( or do nothing if they should be on the CPU ).
def move_to_device(obj, cuda_device: int): """ Given a structure (possibly) containing Tensors on the CPU, move all the Tensors to the specified GPU (or do nothing, if they should be on the CPU). """ if cuda_device < 0 or not has_tensor(obj): return obj elif isinstance(obj, torch.Tensor)...
Supports sparse and dense tensors. Returns a tensor with values clamped between the provided minimum and maximum without modifying the original tensor.
def clamp_tensor(tensor, minimum, maximum): """ Supports sparse and dense tensors. Returns a tensor with values clamped between the provided minimum and maximum, without modifying the original tensor. """ if tensor.is_sparse: coalesced_tensor = tensor.coalesce() # pylint: disable...
Takes a list of tensor dictionaries where each dictionary is assumed to have matching keys and returns a single dictionary with all tensors with the same key batched together.
def batch_tensor_dicts(tensor_dicts: List[Dict[str, torch.Tensor]], remove_trailing_dimension: bool = False) -> Dict[str, torch.Tensor]: """ Takes a list of tensor dictionaries, where each dictionary is assumed to have matching keys, and returns a single dictionary with all tensors wi...
Given a variable of shape ( batch_size ) that represents the sequence lengths of each batch element this function returns a ( batch_size max_length ) mask variable. For example if our input was [ 2 2 3 ] with a max_length of 4 we d return [[ 1 1 0 0 ] [ 1 1 0 0 ] [ 1 1 1 0 ]].
def get_mask_from_sequence_lengths(sequence_lengths: torch.Tensor, max_length: int) -> torch.Tensor: """ Given a variable of shape ``(batch_size,)`` that represents the sequence lengths of each batch element, this function returns a ``(batch_size, max_length)`` mask variable. For example, if our input ...
Sort a batch first tensor by some specified lengths.
def sort_batch_by_length(tensor: torch.Tensor, sequence_lengths: torch.Tensor): """ Sort a batch first tensor by some specified lengths. Parameters ---------- tensor : torch.FloatTensor, required. A batch first Pytorch tensor. sequence_lengths : torch.LongTensor, required. A ten...
Given the output from a Seq2SeqEncoder with shape ( batch_size sequence_length encoding_dim ) this method returns the final hidden state for each element of the batch giving a tensor of shape ( batch_size encoding_dim ). This is not as simple as encoder_outputs [: - 1 ] because the sequences could have different length...
def get_final_encoder_states(encoder_outputs: torch.Tensor, mask: torch.Tensor, bidirectional: bool = False) -> torch.Tensor: """ Given the output from a ``Seq2SeqEncoder``, with shape ``(batch_size, sequence_length, encoding_dim)``, this method retu...
Computes and returns an element - wise dropout mask for a given tensor where each element in the mask is dropped out with probability dropout_probability. Note that the mask is NOT applied to the tensor - the tensor is passed to retain the correct CUDA tensor type for the mask.
def get_dropout_mask(dropout_probability: float, tensor_for_masking: torch.Tensor): """ Computes and returns an element-wise dropout mask for a given tensor, where each element in the mask is dropped out with probability dropout_probability. Note that the mask is NOT applied to the tensor - the tensor i...
torch. nn. functional. softmax ( vector ) does not work if some elements of vector should be masked. This performs a softmax on just the non - masked portions of vector. Passing None in for the mask is also acceptable ; you ll just get a regular softmax.
def masked_softmax(vector: torch.Tensor, mask: torch.Tensor, dim: int = -1, memory_efficient: bool = False, mask_fill_value: float = -1e32) -> torch.Tensor: """ ``torch.nn.functional.softmax(vector)`` does not work if some elements of `...
torch. nn. functional. log_softmax ( vector ) does not work if some elements of vector should be masked. This performs a log_softmax on just the non - masked portions of vector. Passing None in for the mask is also acceptable ; you ll just get a regular log_softmax.
def masked_log_softmax(vector: torch.Tensor, mask: torch.Tensor, dim: int = -1) -> torch.Tensor: """ ``torch.nn.functional.log_softmax(vector)`` does not work if some elements of ``vector`` should be masked. This performs a log_softmax on just the non-masked portions of ``vector``. Passing ``None`` in...
To calculate max along certain dimensions on masked values
def masked_max(vector: torch.Tensor, mask: torch.Tensor, dim: int, keepdim: bool = False, min_val: float = -1e7) -> torch.Tensor: """ To calculate max along certain dimensions on masked values Parameters ---------- vector : ``torch.Tensor`...
To calculate mean along certain dimensions on masked values
def masked_mean(vector: torch.Tensor, mask: torch.Tensor, dim: int, keepdim: bool = False, eps: float = 1e-8) -> torch.Tensor: """ To calculate mean along certain dimensions on masked values Parameters ---------- vector : ``torch.Tenso...
Flips a padded tensor along the time dimension without affecting masked entries.
def masked_flip(padded_sequence: torch.Tensor, sequence_lengths: List[int]) -> torch.Tensor: """ Flips a padded tensor along the time dimension without affecting masked entries. Parameters ---------- padded_sequence : ``torch.Tensor`` The tensor to flip a...
Perform Viterbi decoding in log space over a sequence given a transition matrix specifying pairwise ( transition ) potentials between tags and a matrix of shape ( sequence_length num_tags ) specifying unary potentials for possible tags per timestep.
def viterbi_decode(tag_sequence: torch.Tensor, transition_matrix: torch.Tensor, tag_observations: Optional[List[int]] = None): """ Perform Viterbi decoding in log space over a sequence given a transition matrix specifying pairwise (transition) potentials between tags an...
Takes the dictionary of tensors produced by a TextField and returns a mask with 0 where the tokens are padding and 1 otherwise. We also handle TextFields wrapped by an arbitrary number of ListFields where the number of wrapping ListFields is given by num_wrapping_dims.
def get_text_field_mask(text_field_tensors: Dict[str, torch.Tensor], num_wrapping_dims: int = 0) -> torch.LongTensor: """ Takes the dictionary of tensors produced by a ``TextField`` and returns a mask with 0 where the tokens are padding, and 1 otherwise. We also handle ``TextFields`...
Takes a matrix of vectors and a set of weights over the rows in the matrix ( which we call an attention vector ) and returns a weighted sum of the rows in the matrix. This is the typical computation performed after an attention mechanism.
def weighted_sum(matrix: torch.Tensor, attention: torch.Tensor) -> torch.Tensor: """ Takes a matrix of vectors and a set of weights over the rows in the matrix (which we call an "attention" vector), and returns a weighted sum of the rows in the matrix. This is the typical computation performed after an...
Computes the cross entropy loss of a sequence weighted with respect to some user provided weights. Note that the weighting here is not the same as in the: func: torch. nn. CrossEntropyLoss () criterion which is weighting classes ; here we are weighting the loss contribution from particular elements in the sequence. Thi...
def sequence_cross_entropy_with_logits(logits: torch.FloatTensor, targets: torch.LongTensor, weights: torch.FloatTensor, average: str = "batch", label_smoothing: fl...
Replaces all masked values in tensor with replace_with. mask must be broadcastable to the same shape as tensor. We require that tensor. dim () == mask. dim () as otherwise we won t know which dimensions of the mask to unsqueeze.
def replace_masked_values(tensor: torch.Tensor, mask: torch.Tensor, replace_with: float) -> torch.Tensor: """ Replaces all masked values in ``tensor`` with ``replace_with``. ``mask`` must be broadcastable to the same shape as ``tensor``. We require that ``tensor.dim() == mask.dim()``, as otherwise we w...
A check for tensor equality ( by value ). We make sure that the tensors have the same shape then check all of the entries in the tensor for equality. We additionally allow the input tensors to be lists or dictionaries where we then do the above check on every position in the list/ item in the dictionary. If we find obj...
def tensors_equal(tensor1: torch.Tensor, tensor2: torch.Tensor, tolerance: float = 1e-12) -> bool: """ A check for tensor equality (by value). We make sure that the tensors have the same shape, then check all of the entries in the tensor for equality. We additionally allow the input tensors to be list...
In order to torch. load () a GPU - trained model onto a CPU ( or specific GPU ) you have to supply a map_location function. Call this with the desired cuda_device to get the function that torch. load () needs.
def device_mapping(cuda_device: int): """ In order to `torch.load()` a GPU-trained model onto a CPU (or specific GPU), you have to supply a `map_location` function. Call this with the desired `cuda_device` to get the function that `torch.load()` needs. """ def inner_device_mapping(storage: torc...
Combines a list of tensors using element - wise operations and concatenation specified by a combination string. The string refers to ( 1 - indexed ) positions in the input tensor list and looks like 1 2 1 + 2 3 - 1.
def combine_tensors(combination: str, tensors: List[torch.Tensor]) -> torch.Tensor: """ Combines a list of tensors using element-wise operations and concatenation, specified by a ``combination`` string. The string refers to (1-indexed) positions in the input tensor list, and looks like ``"1,2,1+2,3-1"`...
Return zero - based index in the sequence of the last item whose value is equal to obj. Raises a ValueError if there is no such item.
def _rindex(sequence: Sequence[T], obj: T) -> int: """ Return zero-based index in the sequence of the last item whose value is equal to obj. Raises a ValueError if there is no such item. Parameters ---------- sequence : ``Sequence[T]`` obj : ``T`` Returns ------- zero-based in...
Like: func: combine_tensors but does a weighted ( linear ) multiplication while combining. This is a separate function from combine_tensors because we try to avoid instantiating large intermediate tensors during the combination which is possible because we know that we re going to be multiplying by a weight vector in t...
def combine_tensors_and_multiply(combination: str, tensors: List[torch.Tensor], weights: torch.nn.Parameter) -> torch.Tensor: """ Like :func:`combine_tensors`, but does a weighted (linear) multiplication while combining. This is a separate fu...
For use with: func: combine_tensors. This function computes the resultant dimension when calling combine_tensors ( combination tensors ) when the tensor dimension is known. This is necessary for knowing the sizes of weight matrices when building models that use combine_tensors.
def get_combined_dim(combination: str, tensor_dims: List[int]) -> int: """ For use with :func:`combine_tensors`. This function computes the resultant dimension when calling ``combine_tensors(combination, tensors)``, when the tensor dimension is known. This is necessary for knowing the sizes of weight ...
A numerically stable computation of logsumexp. This is mathematically equivalent to tensor. exp (). sum ( dim keep = keepdim ). log (). This function is typically used for summing log probabilities.
def logsumexp(tensor: torch.Tensor, dim: int = -1, keepdim: bool = False) -> torch.Tensor: """ A numerically stable computation of logsumexp. This is mathematically equivalent to `tensor.exp().sum(dim, keep=keepdim).log()`. This function is typically used for summing log pro...
This is a subroutine for: func: ~batched_index_select. The given indices of size ( batch_size d_1... d_n ) indexes into dimension 2 of a target tensor which has size ( batch_size sequence_length embedding_size ). This function returns a vector that correctly indexes into the flattened target. The sequence length of the...
def flatten_and_batch_shift_indices(indices: torch.Tensor, sequence_length: int) -> torch.Tensor: """ This is a subroutine for :func:`~batched_index_select`. The given ``indices`` of size ``(batch_size, d_1, ..., d_n)`` indexes into dimension 2 of a target tensor, which h...
The given indices of size ( batch_size d_1... d_n ) indexes into the sequence dimension ( dimension 2 ) of the target which has size ( batch_size sequence_length embedding_size ).
def batched_index_select(target: torch.Tensor, indices: torch.LongTensor, flattened_indices: Optional[torch.LongTensor] = None) -> torch.Tensor: """ The given ``indices`` of size ``(batch_size, d_1, ..., d_n)`` indexes into the sequence dimension (dimension ...
The given indices of size ( set_size subset_size ) specifies subsets of the target that each of the set_size rows should select. The target has size ( batch_size sequence_length embedding_size ) and the resulting selected tensor has size ( batch_size set_size subset_size embedding_size ).
def flattened_index_select(target: torch.Tensor, indices: torch.LongTensor) -> torch.Tensor: """ The given ``indices`` of size ``(set_size, subset_size)`` specifies subsets of the ``target`` that each of the set_size rows should select. The `target` has size ``(batch_size, seq...
Returns a range vector with the desired size starting at 0. The CUDA implementation is meant to avoid copy data from CPU to GPU.
def get_range_vector(size: int, device: int) -> torch.Tensor: """ Returns a range vector with the desired size, starting at 0. The CUDA implementation is meant to avoid copy data from CPU to GPU. """ if device > -1: return torch.cuda.LongTensor(size, device=device).fill_(1).cumsum(0) - 1 ...
Places the given values ( designed for distances ) into num_total_buckets semi - logscale buckets with num_identity_buckets of these capturing single values.
def bucket_values(distances: torch.Tensor, num_identity_buckets: int = 4, num_total_buckets: int = 10) -> torch.Tensor: """ Places the given values (designed for distances) into ``num_total_buckets``semi-logscale buckets, with ``num_identity_buckets`` of these capturing s...
Add begin/ end of sentence tokens to the batch of sentences. Given a batch of sentences with size ( batch_size timesteps ) or ( batch_size timesteps dim ) this returns a tensor of shape ( batch_size timesteps + 2 ) or ( batch_size timesteps + 2 dim ) respectively.
def add_sentence_boundary_token_ids(tensor: torch.Tensor, mask: torch.Tensor, sentence_begin_token: Any, sentence_end_token: Any) -> Tuple[torch.Tensor, torch.Tensor]: """ Add begin/end of sentence tokens...
Remove begin/ end of sentence embeddings from the batch of sentences. Given a batch of sentences with size ( batch_size timesteps dim ) this returns a tensor of shape ( batch_size timesteps - 2 dim ) after removing the beginning and end sentence markers. The sentences are assumed to be padded on the right with the begi...
def remove_sentence_boundaries(tensor: torch.Tensor, mask: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]: """ Remove begin/end of sentence embeddings from the batch of sentences. Given a batch of sentences with size ``(batch_size, timesteps, dim)`` this returns a tens...
Implements the frequency - based positional encoding described in Attention is all you Need <https:// www. semanticscholar. org/ paper/ Attention - Is - All - You - Need - Vaswani - Shazeer/ 0737da0767d77606169cbf4187b83e1ab62f6077 > _.
def add_positional_features(tensor: torch.Tensor, min_timescale: float = 1.0, max_timescale: float = 1.0e4): # pylint: disable=line-too-long """ Implements the frequency-based positional encoding described in `Attention is all you Need <https:/...
Produce N identical layers.
def clone(module: torch.nn.Module, num_copies: int) -> torch.nn.ModuleList: """Produce N identical layers.""" return torch.nn.ModuleList([copy.deepcopy(module) for _ in range(num_copies)])
Given a ( possibly higher order ) tensor of ids with shape ( d1... dn sequence_length ) Return a view that s ( d1 *... * dn sequence_length ). If original tensor is 1 - d or 2 - d return it as is.
def combine_initial_dims(tensor: torch.Tensor) -> torch.Tensor: """ Given a (possibly higher order) tensor of ids with shape (d1, ..., dn, sequence_length) Return a view that's (d1 * ... * dn, sequence_length). If original tensor is 1-d or 2-d, return it as is. """ if tensor.dim() <= 2: ...
Given a tensor of embeddings with shape ( d1 *... * dn sequence_length embedding_dim ) and the original shape ( d1... dn sequence_length ) return the reshaped tensor of embeddings with shape ( d1... dn sequence_length embedding_dim ). If original size is 1 - d or 2 - d return it as is.
def uncombine_initial_dims(tensor: torch.Tensor, original_size: torch.Size) -> torch.Tensor: """ Given a tensor of embeddings with shape (d1 * ... * dn, sequence_length, embedding_dim) and the original shape (d1, ..., dn, sequence_length), return the reshaped tensor of embeddings with shape ...
Checks if the string occurs in the table and if it does returns the names of the columns under which it occurs. If it does not returns an empty list.
def _string_in_table(self, candidate: str) -> List[str]: """ Checks if the string occurs in the table, and if it does, returns the names of the columns under which it occurs. If it does not, returns an empty list. """ candidate_column_names: List[str] = [] # First check i...
These are the transformation rules used to normalize cell in column names in Sempre. See edu. stanford. nlp. sempre. tables. StringNormalizationUtils. characterNormalize and edu. stanford. nlp. sempre. tables. TableTypeSystem. canonicalizeName. We reproduce those rules here to normalize and canonicalize cells and colum...
def normalize_string(string: str) -> str: """ These are the transformation rules used to normalize cell in column names in Sempre. See ``edu.stanford.nlp.sempre.tables.StringNormalizationUtils.characterNormalize`` and ``edu.stanford.nlp.sempre.tables.TableTypeSystem.canonicalizeName``. ...
Takes a logical form as a lisp string and returns a nested list representation of the lisp. For example ( count ( division first )) would get mapped to [ count [ division first ]].
def lisp_to_nested_expression(lisp_string: str) -> List: """ Takes a logical form as a lisp string and returns a nested list representation of the lisp. For example, "(count (division first))" would get mapped to ['count', ['division', 'first']]. """ stack: List = [] current_expression: List = [...
Parameters ---------- batch: List [ List [ str ]] required A list of tokenized sentences.
def batch_to_embeddings(self, batch: List[List[str]]) -> Tuple[torch.Tensor, torch.Tensor]: """ Parameters ---------- batch : ``List[List[str]]``, required A list of tokenized sentences. Returns ------- A tuple of tensors, the first representing a...
Computes the ELMo embeddings for a single tokenized sentence.
def embed_sentence(self, sentence: List[str]) -> numpy.ndarray: """ Computes the ELMo embeddings for a single tokenized sentence. Please note that ELMo has internal state and will give different results for the same input. See the comment under the class definition. Parameters ...
Computes the ELMo embeddings for a batch of tokenized sentences.
def embed_batch(self, batch: List[List[str]]) -> List[numpy.ndarray]: """ Computes the ELMo embeddings for a batch of tokenized sentences. Please note that ELMo has internal state and will give different results for the same input. See the comment under the class definition. Pa...
Computes the ELMo embeddings for a iterable of sentences.
def embed_sentences(self, sentences: Iterable[List[str]], batch_size: int = DEFAULT_BATCH_SIZE) -> Iterable[numpy.ndarray]: """ Computes the ELMo embeddings for a iterable of sentences. Please note that ELMo has internal state and will give differ...
Computes ELMo embeddings from an input_file where each line contains a sentence tokenized by whitespace. The ELMo embeddings are written out in HDF5 format where each sentence embedding is saved in a dataset with the line number in the original file as the key.
def embed_file(self, input_file: IO, output_file_path: str, output_format: str = "all", batch_size: int = DEFAULT_BATCH_SIZE, forget_sentences: bool = False, use_sentence_keys: bool = False) -> None: ...
Add the field to the existing fields mapping. If we have already indexed the Instance then we also index field so it is necessary to supply the vocab.
def add_field(self, field_name: str, field: Field, vocab: Vocabulary = None) -> None: """ Add the field to the existing fields mapping. If we have already indexed the Instance, then we also index `field`, so it is necessary to supply the vocab. """ self.fields[field_name]...
Increments counts in the given counter for all of the vocabulary items in all of the Fields in this Instance.
def count_vocab_items(self, counter: Dict[str, Dict[str, int]]): """ Increments counts in the given ``counter`` for all of the vocabulary items in all of the ``Fields`` in this ``Instance``. """ for field in self.fields.values(): field.count_vocab_items(counter)
Indexes all fields in this Instance using the provided Vocabulary. This mutates the current object it does not return a new Instance. A DataIterator will call this on each pass through a dataset ; we use the indexed flag to make sure that indexing only happens once.
def index_fields(self, vocab: Vocabulary) -> None: """ Indexes all fields in this ``Instance`` using the provided ``Vocabulary``. This `mutates` the current object, it does not return a new ``Instance``. A ``DataIterator`` will call this on each pass through a dataset; we use the ``index...
Returns a dictionary of padding lengths keyed by field name. Each Field returns a mapping from padding keys to actual lengths and we just key that dictionary by field name.
def get_padding_lengths(self) -> Dict[str, Dict[str, int]]: """ Returns a dictionary of padding lengths, keyed by field name. Each ``Field`` returns a mapping from padding keys to actual lengths, and we just key that dictionary by field name. """ lengths = {} for field_n...
Pads each Field in this instance to the lengths given in padding_lengths ( which is keyed by field name then by padding key the same as the return value in: func: get_padding_lengths ) returning a list of torch tensors for each field.
def as_tensor_dict(self, padding_lengths: Dict[str, Dict[str, int]] = None) -> Dict[str, DataArray]: """ Pads each ``Field`` in this instance to the lengths given in ``padding_lengths`` (which is keyed by field name, then by padding key, the same as the return value in ...
Return the full name ( including module ) of the given class.
def full_name(cla55: Optional[type]) -> str: """ Return the full name (including module) of the given class. """ # Special case to handle None: if cla55 is None: return "?" if issubclass(cla55, Initializer) and cla55 not in [Initializer, PretrainedModelInitializer]: init_fn = cl...
Find the name ( if any ) that a subclass was registered under. We do this simply by iterating through the registry until we find it.
def _get_config_type(cla55: type) -> Optional[str]: """ Find the name (if any) that a subclass was registered under. We do this simply by iterating through the registry until we find it. """ # Special handling for pytorch RNN types: if cla55 == torch.nn.RNN: return "rnn" elif cla...
Inspect the docstring and get the comments for each parameter.
def _docspec_comments(obj) -> Dict[str, str]: """ Inspect the docstring and get the comments for each parameter. """ # Sometimes our docstring is on the class, and sometimes it's on the initializer, # so we've got to check both. class_docstring = getattr(obj, '__doc__', None) init_docstring ...
Create the Config for a class by reflecting on its __init__ method and applying a few hacks.
def _auto_config(cla55: Type[T]) -> Config[T]: """ Create the ``Config`` for a class by reflecting on its ``__init__`` method and applying a few hacks. """ typ3 = _get_config_type(cla55) # Don't include self, or vocab names_to_ignore = {"self", "vocab"} # Hack for RNNs if cla55 in ...
Pretty - print a config in sort - of - JSON + comments.
def render_config(config: Config, indent: str = "") -> str: """ Pretty-print a config in sort-of-JSON+comments. """ # Add four spaces to the indent. new_indent = indent + " " return "".join([ # opening brace + newline "{\n", # "type": "...", (if present) ...
Render a single config item with the provided indent
def _render(item: ConfigItem, indent: str = "") -> str: """ Render a single config item, with the provided indent """ optional = item.default_value != _NO_DEFAULT if is_configurable(item.annotation): rendered_annotation = f"{item.annotation} (configurable)" else: rendered_annota...
Return a mapping { registered_name - > subclass_name } for the registered subclasses of cla55.
def _valid_choices(cla55: type) -> Dict[str, str]: """ Return a mapping {registered_name -> subclass_name} for the registered subclasses of `cla55`. """ valid_choices: Dict[str, str] = {} if cla55 not in Registrable._registry: raise ValueError(f"{cla55} is not a known Registrable class"...
Convert url into a hashed filename in a repeatable way. If etag is specified append its hash to the url s delimited by a period.
def url_to_filename(url: str, etag: str = None) -> str: """ Convert `url` into a hashed filename in a repeatable way. If `etag` is specified, append its hash to the url's, delimited by a period. """ url_bytes = url.encode('utf-8') url_hash = sha256(url_bytes) filename = url_hash.hexdiges...
Return the url and etag ( which may be None ) stored for filename. Raise FileNotFoundError if filename or its stored metadata do not exist.
def filename_to_url(filename: str, cache_dir: str = None) -> Tuple[str, str]: """ Return the url and etag (which may be ``None``) stored for `filename`. Raise ``FileNotFoundError`` if `filename` or its stored metadata do not exist. """ if cache_dir is None: cache_dir = CACHE_DIRECTORY c...
Given something that might be a URL ( or might be a local path ) determine which. If it s a URL download the file and cache it and return the path to the cached file. If it s already a local path make sure the file exists and then return the path.
def cached_path(url_or_filename: Union[str, Path], cache_dir: str = None) -> str: """ Given something that might be a URL (or might be a local path), determine which. If it's a URL, download the file and cache it, and return the path to the cached file. If it's already a local path, make sure the fi...
Given something that might be a URL ( or might be a local path ) determine check if it s url or an existing file path.
def is_url_or_existing_file(url_or_filename: Union[str, Path, None]) -> bool: """ Given something that might be a URL (or might be a local path), determine check if it's url or an existing file path. """ if url_or_filename is None: return False url_or_filename = os.path.expanduser(str(ur...
Split a full s3 path into the bucket name and path.
def split_s3_path(url: str) -> Tuple[str, str]: """Split a full s3 path into the bucket name and path.""" parsed = urlparse(url) if not parsed.netloc or not parsed.path: raise ValueError("bad s3 path {}".format(url)) bucket_name = parsed.netloc s3_path = parsed.path # Remove '/' at begin...
Wrapper function for s3 requests in order to create more helpful error messages.
def s3_request(func: Callable): """ Wrapper function for s3 requests in order to create more helpful error messages. """ @wraps(func) def wrapper(url: str, *args, **kwargs): try: return func(url, *args, **kwargs) except ClientError as exc: if int(exc.resp...
Check ETag on S3 object.
def s3_etag(url: str) -> Optional[str]: """Check ETag on S3 object.""" s3_resource = boto3.resource("s3") bucket_name, s3_path = split_s3_path(url) s3_object = s3_resource.Object(bucket_name, s3_path) return s3_object.e_tag
Pull a file directly from S3.
def s3_get(url: str, temp_file: IO) -> None: """Pull a file directly from S3.""" s3_resource = boto3.resource("s3") bucket_name, s3_path = split_s3_path(url) s3_resource.Bucket(bucket_name).download_fileobj(s3_path, temp_file)
Given a URL look for the corresponding dataset in the local cache. If it s not there download it. Then return the path to the cached file.
def get_from_cache(url: str, cache_dir: str = None) -> str: """ Given a URL, look for the corresponding dataset in the local cache. If it's not there, download it. Then return the path to the cached file. """ if cache_dir is None: cache_dir = CACHE_DIRECTORY os.makedirs(cache_dir, exist...
Extract a de - duped collection ( set ) of text from a file. Expected file format is one item per line.
def read_set_from_file(filename: str) -> Set[str]: """ Extract a de-duped collection (set) of text from a file. Expected file format is one item per line. """ collection = set() with open(filename, 'r') as file_: for line in file_: collection.add(line.rstrip()) return col...
Processes the text2sql data into the following directory structure:
def main(output_directory: int, data: str) -> None: """ Processes the text2sql data into the following directory structure: ``dataset/{query_split, question_split}/{train,dev,test}.json`` for datasets which have train, dev and test splits, or: ``dataset/{query_split, question_split}/{split_{split...
Apply dropout to this layer for this whole mini - batch. dropout_prob = layer_index/ total_layers * undecayed_dropout_prob if layer_idx and total_layers is specified else it will use the undecayed_dropout_prob directly.
def forward(self, layer_input: torch.Tensor, layer_output: torch.Tensor, layer_index: int = None, total_layers: int = None) -> torch.Tensor: # pylint: disable=arguments-differ """ Apply dropout to this layer, for this whole mini-bat...
See PlaceholderType. resolve
def resolve(self, other: Type) -> Optional[Type]: """See ``PlaceholderType.resolve``""" if not isinstance(other, NltkComplexType): return None expected_second = ComplexType(NUMBER_TYPE, ComplexType(ANY_TYPE, ComplexType(ComplexType(ANY_TYPE, ANY_...
See PlaceholderType. resolve
def resolve(self, other: Type) -> Type: """See ``PlaceholderType.resolve``""" if not isinstance(other, NltkComplexType): return None resolved_second = NUMBER_TYPE.resolve(other.second) if not resolved_second: return None return CountType(other.first)
Reads an NLVR dataset and returns a JSON representation containing sentences labels correct and incorrect logical forms. The output will contain at most max_num_logical_forms logical forms each in both correct and incorrect lists. The output format is: [ { id: str label: str sentence: str correct: List [ str ] incorrec...
def process_data(input_file: str, output_file: str, max_path_length: int, max_num_logical_forms: int, ignore_agenda: bool, write_sequences: bool) -> None: """ Reads an NLVR dataset and returns a JSON representation containing s...
This method lets you take advantage of spacy s batch processing. Default implementation is to just iterate over the texts and call split_sentences.
def batch_split_sentences(self, texts: List[str]) -> List[List[str]]: """ This method lets you take advantage of spacy's batch processing. Default implementation is to just iterate over the texts and call ``split_sentences``. """ return [self.split_sentences(text) for text in tex...
An iterator over the entire dataset yielding all sentences processed.
def dataset_iterator(self, file_path: str) -> Iterator[OntonotesSentence]: """ An iterator over the entire dataset, yielding all sentences processed. """ for conll_file in self.dataset_path_iterator(file_path): yield from self.sentence_iterator(conll_file)
An iterator returning file_paths in a directory containing CONLL - formatted files.
def dataset_path_iterator(file_path: str) -> Iterator[str]: """ An iterator returning file_paths in a directory containing CONLL-formatted files. """ logger.info("Reading CONLL sentences from dataset files at: %s", file_path) for root, _, files in list(os.walk(file_path))...
An iterator over CONLL formatted files which yields documents regardless of the number of document annotations in a particular file. This is useful for conll data which has been preprocessed such as the preprocessing which takes place for the 2012 CONLL Coreference Resolution task.
def dataset_document_iterator(self, file_path: str) -> Iterator[List[OntonotesSentence]]: """ An iterator over CONLL formatted files which yields documents, regardless of the number of document annotations in a particular file. This is useful for conll data which has been preprocessed, s...
An iterator over the sentences in an individual CONLL formatted file.
def sentence_iterator(self, file_path: str) -> Iterator[OntonotesSentence]: """ An iterator over the sentences in an individual CONLL formatted file. """ for document in self.dataset_document_iterator(file_path): for sentence in document: yield sentence
For a given coref label add it to a currently open span ( s ) complete a span ( s ) or ignore it if it is outside of all spans. This method mutates the clusters and coref_stacks dictionaries.
def _process_coref_span_annotations_for_word(label: str, word_index: int, clusters: DefaultDict[int, List[Tuple[int, int]]], coref_stacks: DefaultDict[int, List[int]]) -> No...
Given a sequence of different label types for a single word and the current span label we are inside compute the BIO tag for each label and append to a list.
def _process_span_annotations_for_word(annotations: List[str], span_labels: List[List[str]], current_span_labels: List[Optional[str]]) -> None: """ Given a sequence of different label types for a single word and the cu...
Prints results from an argparse. Namespace object.
def print_results_from_args(args: argparse.Namespace): """ Prints results from an ``argparse.Namespace`` object. """ path = args.path metrics_name = args.metrics_filename keys = args.keys results_dict = {} for root, _, files in os.walk(path): if metrics_name in files: ...
Apply dropout to input tensor.
def forward(self, input_tensor): # pylint: disable=arguments-differ """ Apply dropout to input tensor. Parameters ---------- input_tensor: ``torch.FloatTensor`` A tensor of shape ``(batch_size, num_timesteps, embedding_dim)`` Returns ------- ...
Compute and return the metric. Optionally also call: func: self. reset.
def get_metric(self, reset: bool) -> Union[float, Tuple[float, ...], Dict[str, float], Dict[str, List[float]]]: """ Compute and return the metric. Optionally also call :func:`self.reset`. """ raise NotImplementedError
If you actually passed gradient - tracking Tensors to a Metric there will be a huge memory leak because it will prevent garbage collection for the computation graph. This method ensures that you re using tensors directly and that they are on the CPU.
def unwrap_to_tensors(*tensors: torch.Tensor): """ If you actually passed gradient-tracking Tensors to a Metric, there will be a huge memory leak, because it will prevent garbage collection for the computation graph. This method ensures that you're using tensors directly and that they ar...
Replaces abstract variables in text with their concrete counterparts.
def replace_variables(sentence: List[str], sentence_variables: Dict[str, str]) -> Tuple[List[str], List[str]]: """ Replaces abstract variables in text with their concrete counterparts. """ tokens = [] tags = [] for token in sentence: if token not in sentence_variabl...
Cleans up and unifies a SQL query. This involves unifying quoted strings and splitting brackets which aren t formatted consistently in the data.
def clean_and_split_sql(sql: str) -> List[str]: """ Cleans up and unifies a SQL query. This involves unifying quoted strings and splitting brackets which aren't formatted consistently in the data. """ sql_tokens: List[str] = [] for token in sql.strip().split(): token = token.replace('"',...
Some examples in the text2sql datasets use ID as a column reference to the column of a table which has a primary key. This causes problems if you are trying to constrain a grammar to only produce the column names directly because you don t know what ID refers to. So instead of dealing with that we just replace it.
def resolve_primary_keys_in_schema(sql_tokens: List[str], schema: Dict[str, List[TableColumn]]) -> List[str]: """ Some examples in the text2sql datasets use ID as a column reference to the column of a table which has a primary key. This causes problems if you are trying ...
Reads a schema from the text2sql data returning a dictionary mapping table names to their columns and respective types. This handles columns in an arbitrary order and also allows either { Table Field } or { Table Field } Name as headers because both appear in the data. It also uppercases table and column names if they ...
def read_dataset_schema(schema_path: str) -> Dict[str, List[TableColumn]]: """ Reads a schema from the text2sql data, returning a dictionary mapping table names to their columns and respective types. This handles columns in an arbitrary order and also allows either ``{Table, Field}`` or ``{Table, Fi...
A utility function for reading in text2sql data. The blob is the result of loading the json from a file produced by the script scripts/ reformat_text2sql_data. py.
def process_sql_data(data: List[JsonDict], use_all_sql: bool = False, use_all_queries: bool = False, remove_unneeded_aliases: bool = False, schema: Dict[str, List[TableColumn]] = None) -> Iterable[SqlData]: """ A utility functio...
This function exists because Pytorch RNNs require that their inputs be sorted before being passed as input. As all of our Seq2xxxEncoders use this functionality it is provided in a base class. This method can be called on any module which takes as input a PackedSequence and some hidden_state which can either be a tuple...
def sort_and_run_forward(self, module: Callable[[PackedSequence, Optional[RnnState]], Tuple[Union[PackedSequence, torch.Tensor], RnnState]], inputs: torch.Tensor, mask: torch.Tensor, ...
Returns an initial state for use in an RNN. Additionally this method handles the batch size changing across calls by mutating the state to append initial states for new elements in the batch. Finally it also handles sorting the states with respect to the sequence lengths of elements in the batch and removing rows which...
def _get_initial_states(self, batch_size: int, num_valid: int, sorting_indices: torch.LongTensor) -> Optional[RnnState]: """ Returns an initial state for use in an RNN. Additionally, this method handles the batch...
After the RNN has run forward the states need to be updated. This method just sets the state to the updated new state performing several pieces of book - keeping along the way - namely unsorting the states and ensuring that the states of completely padded sequences are not updated. Finally it also detaches the state va...
def _update_states(self, final_states: RnnStateStorage, restoration_indices: torch.LongTensor) -> None: """ After the RNN has run forward, the states need to be updated. This method just sets the state to the updated new state, performing sev...
Takes a list of valid target action sequences and creates a mapping from all possible ( valid ) action prefixes to allowed actions given that prefix. While the method is called construct_prefix_tree we re actually returning a map that has as keys the paths to all internal nodes of the trie and as values all of the outg...
def construct_prefix_tree(targets: Union[torch.Tensor, List[List[List[int]]]], target_mask: Optional[torch.Tensor] = None) -> List[Dict[Tuple[int, ...], Set[int]]]: """ Takes a list of valid target action sequences and creates a mapping from all possible (valid) action prefixes to ...
Convert the string to Value object.
def to_value(original_string, corenlp_value=None): """Convert the string to Value object. Args: original_string (basestring): Original string corenlp_value (basestring): Optional value returned from CoreNLP Returns: Value """ if isinstance(original_string, Value): # ...