Code stringlengths 103 85.9k | Summary listlengths 0 94 |
|---|---|
Please provide a description of the function:def read(self, file_path: str) -> Iterable[Instance]:
lazy = getattr(self, 'lazy', None)
if lazy is None:
logger.warning("DatasetReader.lazy is not set, "
"did you forget to call the superclass constructor?")
... | [
"\n Returns an ``Iterable`` containing all the instances\n in the specified dataset.\n\n If ``self.lazy`` is False, this calls ``self._read()``,\n ensures that the result is a list, then returns the resulting list.\n\n If ``self.lazy`` is True, this returns an object whose\n ... |
Please provide a description of the function:def restore_checkpoint(self) -> Tuple[Dict[str, Any], Dict[str, Any]]:
latest_checkpoint = self.find_latest_checkpoint()
if latest_checkpoint is None:
# No checkpoint to restore, start at 0
return {}, {}
model_path, ... | [
"\n Restores a model from a serialization_dir to the last saved checkpoint.\n This includes a training state (typically consisting of an epoch count and optimizer state),\n which is serialized separately from model parameters. This function should only be used to\n continue training - i... |
Please provide a description of the function:def write_to_conll_eval_file(prediction_file: TextIO,
gold_file: TextIO,
verb_index: Optional[int],
sentence: List[str],
prediction: List[str],
... | [
"\n Prints predicate argument predictions and gold labels for a single verbal\n predicate in a sentence to two provided file references.\n\n Parameters\n ----------\n prediction_file : TextIO, required.\n A file reference to print predictions to.\n gold_file : TextIO, required.\n A f... |
Please provide a description of the function:def convert_bio_tags_to_conll_format(labels: List[str]):
sentence_length = len(labels)
conll_labels = []
for i, label in enumerate(labels):
if label == "O":
conll_labels.append("*")
continue
new_label = "*"
# A... | [
"\n Converts BIO formatted SRL tags to the format required for evaluation with the\n official CONLL 2005 perl script. Spans are represented by bracketed labels,\n with the labels of words inside spans being the same as those outside spans.\n Beginning spans always have a opening bracket and a closing as... |
Please provide a description of the function:def get_agenda_for_sentence(self, sentence: str) -> List[str]:
agenda = []
sentence = sentence.lower()
if sentence.startswith("there is a box") or sentence.startswith("there is a tower "):
agenda.append(self.terminal_productions["... | [
"\n Given a ``sentence``, returns a list of actions the sentence triggers as an ``agenda``. The\n ``agenda`` can be used while by a parser to guide the decoder. sequences as possible. This\n is a simplistic mapping at this point, and can be expanded.\n\n Parameters\n ----------\n... |
Please provide a description of the function:def _get_number_productions(sentence: str) -> List[str]:
# The mapping here is very simple and limited, which also shouldn't be a problem
# because numbers seem to be represented fairly regularly.
number_strings = {"one": "1", "two": "2", "th... | [
"\n Gathers all the numbers in the sentence, and returns productions that lead to them.\n "
] |
Please provide a description of the function:def same_color(self, objects: Set[Object]) -> Set[Object]:
return self._get_objects_with_same_attribute(objects, lambda x: x.color) | [
"\n Filters the set of objects, and returns those objects whose color is the most frequent\n color in the initial set of objects, if the highest frequency is greater than 1, or an\n empty set otherwise.\n\n This is an unusual name for what the method does, but just as ``blue`` filters ob... |
Please provide a description of the function:def same_shape(self, objects: Set[Object]) -> Set[Object]:
return self._get_objects_with_same_attribute(objects, lambda x: x.shape) | [
"\n Filters the set of objects, and returns those objects whose color is the most frequent\n color in the initial set of objects, if the highest frequency is greater than 1, or an\n empty set otherwise.\n\n This is an unusual name for what the method does, but just as ``triangle`` filter... |
Please provide a description of the function:def touch_object(self, objects: Set[Object]) -> Set[Object]:
objects_per_box = self._separate_objects_by_boxes(objects)
return_set = set()
for box, box_objects in objects_per_box.items():
candidate_objects = box.objects
... | [
"\n Returns all objects that touch the given set of objects.\n "
] |
Please provide a description of the function:def top(self, objects: Set[Object]) -> Set[Object]:
objects_per_box = self._separate_objects_by_boxes(objects)
return_set: Set[Object] = set()
for _, box_objects in objects_per_box.items():
min_y_loc = min([obj.y_loc for obj in bo... | [
"\n Return the topmost objects (i.e. minimum y_loc). The comparison is done separately for each\n box.\n "
] |
Please provide a description of the function:def bottom(self, objects: Set[Object]) -> Set[Object]:
objects_per_box = self._separate_objects_by_boxes(objects)
return_set: Set[Object] = set()
for _, box_objects in objects_per_box.items():
max_y_loc = max([obj.y_loc for obj in... | [
"\n Return the bottom most objects(i.e. maximum y_loc). The comparison is done separately for\n each box.\n "
] |
Please provide a description of the function:def above(self, objects: Set[Object]) -> Set[Object]:
objects_per_box = self._separate_objects_by_boxes(objects)
return_set = set()
for box in objects_per_box:
# min_y_loc corresponds to the top-most object.
min_y_loc ... | [
"\n Returns the set of objects in the same boxes that are above the given objects. That is, if\n the input is a set of two objects, one in each box, we will return a union of the objects\n above the first object in the first box, and those above the second object in the second box.\n "
] |
Please provide a description of the function:def below(self, objects: Set[Object]) -> Set[Object]:
objects_per_box = self._separate_objects_by_boxes(objects)
return_set = set()
for box in objects_per_box:
# max_y_loc corresponds to the bottom-most object.
max_y_l... | [
"\n Returns the set of objects in the same boxes that are below the given objects. That is, if\n the input is a set of two objects, one in each box, we will return a union of the objects\n below the first object in the first box, and those below the second object in the second box.\n "
] |
Please provide a description of the function:def _objects_touch_each_other(self, object1: Object, object2: Object) -> bool:
in_vertical_range = object1.y_loc <= object2.y_loc + object2.size and \
object1.y_loc + object1.size >= object2.y_loc
in_horizantal_range = obj... | [
"\n Returns true iff the objects touch each other.\n "
] |
Please provide a description of the function:def _separate_objects_by_boxes(self, objects: Set[Object]) -> Dict[Box, List[Object]]:
objects_per_box: Dict[Box, List[Object]] = defaultdict(list)
for box in self.boxes:
for object_ in objects:
if object_ in box.objects:
... | [
"\n Given a set of objects, separate them by the boxes they belong to and return a dict.\n "
] |
Please provide a description of the function:def _get_objects_with_same_attribute(self,
objects: Set[Object],
attribute_function: Callable[[Object], str]) -> Set[Object]:
objects_of_attribute: Dict[str, Set[Object]] = def... | [
"\n Returns the set of objects for which the attribute function returns an attribute value that\n is most frequent in the initial set, if the frequency is greater than 1. If not, all\n objects have different attribute values, and this method returns an empty set.\n "
] |
Please provide a description of the function:def has_tensor(obj) -> bool:
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, tuple)):
return any(has_tensor(item) for item i... | [
"\n Given a possibly complex data structure,\n check if it has any torch.Tensors in it.\n "
] |
Please provide a description of the function:def move_to_device(obj, cuda_device: int):
if cuda_device < 0 or not has_tensor(obj):
return obj
elif isinstance(obj, torch.Tensor):
return obj.cuda(cuda_device)
elif isinstance(obj, dict):
return {key: move_to_device(value, cuda_devi... | [
"\n Given a structure (possibly) containing Tensors on the CPU,\n move all the Tensors to the specified GPU (or do nothing, if they should be on the CPU).\n "
] |
Please provide a description of the function:def clamp_tensor(tensor, minimum, maximum):
if tensor.is_sparse:
coalesced_tensor = tensor.coalesce()
# pylint: disable=protected-access
coalesced_tensor._values().clamp_(minimum, maximum)
return coalesced_tensor
else:
ret... | [
"\n Supports sparse and dense tensors.\n Returns a tensor with values clamped between the provided minimum and maximum,\n without modifying the original tensor.\n "
] |
Please provide a description of the function:def batch_tensor_dicts(tensor_dicts: List[Dict[str, torch.Tensor]],
remove_trailing_dimension: bool = False) -> Dict[str, torch.Tensor]:
key_to_tensors: Dict[str, List[torch.Tensor]] = defaultdict(list)
for tensor_dict in tensor_dicts:
... | [
"\n Takes a list of tensor dictionaries, where each dictionary is assumed to have matching keys,\n and returns a single dictionary with all tensors with the same key batched together.\n\n Parameters\n ----------\n tensor_dicts : ``List[Dict[str, torch.Tensor]]``\n The list of tensor dictionari... |
Please provide a description of the function:def get_mask_from_sequence_lengths(sequence_lengths: torch.Tensor, max_length: int) -> torch.Tensor:
# (batch_size, max_length)
ones = sequence_lengths.new_ones(sequence_lengths.size(0), max_length)
range_tensor = ones.cumsum(dim=1)
return (sequence_leng... | [
"\n Given a variable of shape ``(batch_size,)`` that represents the sequence lengths of each batch\n element, this function returns a ``(batch_size, max_length)`` mask variable. For example, if\n our input was ``[2, 2, 3]``, with a ``max_length`` of 4, we'd return\n ``[[1, 1, 0, 0], [1, 1, 0, 0], [1, 1... |
Please provide a description of the function:def sort_batch_by_length(tensor: torch.Tensor, sequence_lengths: torch.Tensor):
if not isinstance(tensor, torch.Tensor) or not isinstance(sequence_lengths, torch.Tensor):
raise ConfigurationError("Both the tensor and sequence lengths must be torch.Tensors."... | [
"\n Sort a batch first tensor by some specified lengths.\n\n Parameters\n ----------\n tensor : torch.FloatTensor, required.\n A batch first Pytorch tensor.\n sequence_lengths : torch.LongTensor, required.\n A tensor representing the lengths of some dimension of the tensor which\n ... |
Please provide a description of the function:def get_final_encoder_states(encoder_outputs: torch.Tensor,
mask: torch.Tensor,
bidirectional: bool = False) -> torch.Tensor:
# These are the indices of the last words in the sequences (i.e. length sans paddi... | [
"\n Given the output from a ``Seq2SeqEncoder``, with shape ``(batch_size, sequence_length,\n encoding_dim)``, this method returns the final hidden state for each element of the batch,\n giving a tensor of shape ``(batch_size, encoding_dim)``. This is not as simple as\n ``encoder_outputs[:, -1]``, becau... |
Please provide a description of the function:def get_dropout_mask(dropout_probability: float, tensor_for_masking: torch.Tensor):
binary_mask = (torch.rand(tensor_for_masking.size()) > dropout_probability).to(tensor_for_masking.device)
# Scale mask by 1/keep_prob to preserve output statistics.
dropout_m... | [
"\n Computes and returns an element-wise dropout mask for a given tensor, where\n each element in the mask is dropped out with probability dropout_probability.\n Note that the mask is NOT applied to the tensor - the tensor is passed to retain\n the correct CUDA tensor type for the mask.\n\n Parameter... |
Please provide a description of the function:def masked_softmax(vector: torch.Tensor,
mask: torch.Tensor,
dim: int = -1,
memory_efficient: bool = False,
mask_fill_value: float = -1e32) -> torch.Tensor:
if mask is None:
result =... | [
"\n ``torch.nn.functional.softmax(vector)`` does not work if some elements of ``vector`` should be\n masked. This performs a softmax on just the non-masked portions of ``vector``. Passing\n ``None`` in for the mask is also acceptable; you'll just get a regular softmax.\n\n ``vector`` can have an arbit... |
Please provide a description of the function:def masked_log_softmax(vector: torch.Tensor, mask: torch.Tensor, dim: int = -1) -> torch.Tensor:
if mask is not None:
mask = mask.float()
while mask.dim() < vector.dim():
mask = mask.unsqueeze(1)
# vector + mask.log() is an easy w... | [
"\n ``torch.nn.functional.log_softmax(vector)`` does not work if some elements of ``vector`` should be\n masked. This performs a log_softmax on just the non-masked portions of ``vector``. Passing\n ``None`` in for the mask is also acceptable; you'll just get a regular log_softmax.\n\n ``vector`` can h... |
Please provide a description of the function:def masked_max(vector: torch.Tensor,
mask: torch.Tensor,
dim: int,
keepdim: bool = False,
min_val: float = -1e7) -> torch.Tensor:
one_minus_mask = (1.0 - mask).byte()
replaced_vector = vector.masked_fil... | [
"\n To calculate max along certain dimensions on masked values\n\n Parameters\n ----------\n vector : ``torch.Tensor``\n The vector to calculate max, assume unmasked parts are already zeros\n mask : ``torch.Tensor``\n The mask of the vector. It must be broadcastable with vector.\n di... |
Please provide a description of the function:def masked_mean(vector: torch.Tensor,
mask: torch.Tensor,
dim: int,
keepdim: bool = False,
eps: float = 1e-8) -> torch.Tensor:
one_minus_mask = (1.0 - mask).byte()
replaced_vector = vector.masked_fi... | [
"\n To calculate mean along certain dimensions on masked values\n\n Parameters\n ----------\n vector : ``torch.Tensor``\n The vector to calculate mean.\n mask : ``torch.Tensor``\n The mask of the vector. It must be broadcastable with vector.\n dim : ``int``\n The dimension to ... |
Please provide a description of the function:def masked_flip(padded_sequence: torch.Tensor,
sequence_lengths: List[int]) -> torch.Tensor:
assert padded_sequence.size(0) == len(sequence_lengths), \
f'sequence_lengths length ${len(sequence_lengths)} does not match batch size ${padded_sequ... | [
"\n Flips a padded tensor along the time dimension without affecting masked entries.\n\n Parameters\n ----------\n padded_sequence : ``torch.Tensor``\n The tensor to flip along the time dimension.\n Assumed to be of dimensions (batch size, num timesteps, ...)\n ... |
Please provide a description of the function:def viterbi_decode(tag_sequence: torch.Tensor,
transition_matrix: torch.Tensor,
tag_observations: Optional[List[int]] = None):
sequence_length, num_tags = list(tag_sequence.size())
if tag_observations:
if len(tag_obs... | [
"\n Perform Viterbi decoding in log space over a sequence given a transition matrix\n specifying pairwise (transition) potentials between tags and a matrix of shape\n (sequence_length, num_tags) specifying unary potentials for possible tags per\n timestep.\n\n Parameters\n ----------\n tag_sequ... |
Please provide a description of the function:def get_text_field_mask(text_field_tensors: Dict[str, torch.Tensor],
num_wrapping_dims: int = 0) -> torch.LongTensor:
if "mask" in text_field_tensors:
return text_field_tensors["mask"]
tensor_dims = [(tensor.dim(), tensor) for te... | [
"\n Takes the dictionary of tensors produced by a ``TextField`` and returns a mask\n with 0 where the tokens are padding, and 1 otherwise. We also handle ``TextFields``\n wrapped by an arbitrary number of ``ListFields``, where the number of wrapping ``ListFields``\n is given by ``num_wrapping_dims``.\n... |
Please provide a description of the function:def weighted_sum(matrix: torch.Tensor, attention: torch.Tensor) -> torch.Tensor:
# We'll special-case a few settings here, where there are efficient (but poorly-named)
# operations in pytorch that already do the computation we need.
if attention.dim() == 2 a... | [
"\n Takes a matrix of vectors and a set of weights over the rows in the matrix (which we call an\n \"attention\" vector), and returns a weighted sum of the rows in the matrix. This is the typical\n computation performed after an attention mechanism.\n\n Note that while we call this a \"matrix\" of vect... |
Please provide a description of the function:def sequence_cross_entropy_with_logits(logits: torch.FloatTensor,
targets: torch.LongTensor,
weights: torch.FloatTensor,
average: str = "batch",
... | [
"\n Computes the cross entropy loss of a sequence, weighted with respect to\n some user provided weights. Note that the weighting here is not the same as\n in the :func:`torch.nn.CrossEntropyLoss()` criterion, which is weighting\n classes; here we are weighting the loss contribution from particular elem... |
Please provide a description of the function:def replace_masked_values(tensor: torch.Tensor, mask: torch.Tensor, replace_with: float) -> torch.Tensor:
if tensor.dim() != mask.dim():
raise ConfigurationError("tensor.dim() (%d) != mask.dim() (%d)" % (tensor.dim(), mask.dim()))
return tensor.masked_fi... | [
"\n Replaces all masked values in ``tensor`` with ``replace_with``. ``mask`` must be broadcastable\n to the same shape as ``tensor``. We require that ``tensor.dim() == mask.dim()``, as otherwise we\n won't know which dimensions of the mask to unsqueeze.\n\n This just does ``tensor.masked_fill()``, exce... |
Please provide a description of the function:def tensors_equal(tensor1: torch.Tensor, tensor2: torch.Tensor, tolerance: float = 1e-12) -> bool:
# pylint: disable=too-many-return-statements
if isinstance(tensor1, (list, tuple)):
if not isinstance(tensor2, (list, tuple)) or len(tensor1) != len(tensor... | [
"\n A check for tensor equality (by value). We make sure that the tensors have the same shape,\n then check all of the entries in the tensor for equality. We additionally allow the input\n tensors to be lists or dictionaries, where we then do the above check on every position in the\n list / item in t... |
Please provide a description of the function:def device_mapping(cuda_device: int):
def inner_device_mapping(storage: torch.Storage, location) -> torch.Storage: # pylint: disable=unused-argument
if cuda_device >= 0:
return storage.cuda(cuda_device)
else:
return storage
... | [
"\n In order to `torch.load()` a GPU-trained model onto a CPU (or specific GPU),\n you have to supply a `map_location` function. Call this with\n the desired `cuda_device` to get the function that `torch.load()` needs.\n "
] |
Please provide a description of the function:def combine_tensors(combination: str, tensors: List[torch.Tensor]) -> torch.Tensor:
if len(tensors) > 9:
raise ConfigurationError("Double-digit tensor lists not currently supported")
combination = combination.replace('x', '1').replace('y', '2')
to_co... | [
"\n Combines a list of tensors using element-wise operations and concatenation, specified by a\n ``combination`` string. The string refers to (1-indexed) positions in the input tensor list,\n and looks like ``\"1,2,1+2,3-1\"``.\n\n We allow the following kinds of combinations: ``x``, ``x*y``, ``x+y``, ... |
Please provide a description of the function:def _rindex(sequence: Sequence[T], obj: T) -> int:
for i in range(len(sequence) - 1, -1, -1):
if sequence[i] == obj:
return i
raise ValueError(f"Unable to find {obj} in sequence {sequence}.") | [
"\n Return zero-based index in the sequence of the last item whose value is equal to obj. Raises a\n ValueError if there is no such item.\n\n Parameters\n ----------\n sequence : ``Sequence[T]``\n obj : ``T``\n\n Returns\n -------\n zero-based index associated to the position of the last... |
Please provide a description of the function:def combine_tensors_and_multiply(combination: str,
tensors: List[torch.Tensor],
weights: torch.nn.Parameter) -> torch.Tensor:
if len(tensors) > 9:
raise ConfigurationError("Double-digit tensor... | [
"\n Like :func:`combine_tensors`, but does a weighted (linear) multiplication while combining.\n This is a separate function from ``combine_tensors`` because we try to avoid instantiating\n large intermediate tensors during the combination, which is possible because we know that we're\n going to be mult... |
Please provide a description of the function:def get_combined_dim(combination: str, tensor_dims: List[int]) -> int:
if len(tensor_dims) > 9:
raise ConfigurationError("Double-digit tensor lists not currently supported")
combination = combination.replace('x', '1').replace('y', '2')
return sum([_g... | [
"\n For use with :func:`combine_tensors`. This function computes the resultant dimension when\n calling ``combine_tensors(combination, tensors)``, when the tensor dimension is known. This is\n necessary for knowing the sizes of weight matrices when building models that use\n ``combine_tensors``.\n\n ... |
Please provide a description of the function:def logsumexp(tensor: torch.Tensor,
dim: int = -1,
keepdim: bool = False) -> torch.Tensor:
max_score, _ = tensor.max(dim, keepdim=keepdim)
if keepdim:
stable_vec = tensor - max_score
else:
stable_vec = tensor - max... | [
"\n A numerically stable computation of logsumexp. This is mathematically equivalent to\n `tensor.exp().sum(dim, keep=keepdim).log()`. This function is typically used for summing log\n probabilities.\n\n Parameters\n ----------\n tensor : torch.FloatTensor, required.\n A tensor of arbitrar... |
Please provide a description of the function:def flatten_and_batch_shift_indices(indices: torch.Tensor,
sequence_length: int) -> torch.Tensor:
# Shape: (batch_size)
offsets = get_range_vector(indices.size(0), get_device_of(indices)) * sequence_length
for _ in range(l... | [
"\n This is a subroutine for :func:`~batched_index_select`. The given ``indices`` of size\n ``(batch_size, d_1, ..., d_n)`` indexes into dimension 2 of a target tensor, which has size\n ``(batch_size, sequence_length, embedding_size)``. This function returns a vector that\n correctly indexes into the fl... |
Please provide a description of the function:def batched_index_select(target: torch.Tensor,
indices: torch.LongTensor,
flattened_indices: Optional[torch.LongTensor] = None) -> torch.Tensor:
if flattened_indices is None:
# Shape: (batch_size * d_1 * ... ... | [
"\n The given ``indices`` of size ``(batch_size, d_1, ..., d_n)`` indexes into the sequence\n dimension (dimension 2) of the target, which has size ``(batch_size, sequence_length,\n embedding_size)``.\n\n This function returns selected values in the target with respect to the provided indices, which\n ... |
Please provide a description of the function:def flattened_index_select(target: torch.Tensor,
indices: torch.LongTensor) -> torch.Tensor:
if indices.dim() != 2:
raise ConfigurationError("Indices passed to flattened_index_select had shape {} but "
... | [
"\n The given ``indices`` of size ``(set_size, subset_size)`` specifies subsets of the ``target``\n that each of the set_size rows should select. The `target` has size\n ``(batch_size, sequence_length, embedding_size)``, and the resulting selected tensor has size\n ``(batch_size, set_size, subset_size, ... |
Please provide a description of the function:def get_range_vector(size: int, device: int) -> torch.Tensor:
if device > -1:
return torch.cuda.LongTensor(size, device=device).fill_(1).cumsum(0) - 1
else:
return torch.arange(0, size, dtype=torch.long) | [
"\n Returns a range vector with the desired size, starting at 0. The CUDA implementation\n is meant to avoid copy data from CPU to GPU.\n "
] |
Please provide a description of the function:def bucket_values(distances: torch.Tensor,
num_identity_buckets: int = 4,
num_total_buckets: int = 10) -> torch.Tensor:
# Chunk the values into semi-logscale buckets using .floor().
# This is a semi-logscale bucketing because ... | [
"\n Places the given values (designed for distances) into ``num_total_buckets``semi-logscale\n buckets, with ``num_identity_buckets`` of these capturing single values.\n\n The default settings will bucket values into the following buckets:\n [0, 1, 2, 3, 4, 5-7, 8-15, 16-31, 32-63, 64+].\n\n Paramete... |
Please provide a description of the function: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]:... | [
"\n Add begin/end of sentence tokens to the batch of sentences.\n Given a batch of sentences with size ``(batch_size, timesteps)`` or\n ``(batch_size, timesteps, dim)`` this returns a tensor of shape\n ``(batch_size, timesteps + 2)`` or ``(batch_size, timesteps + 2, dim)`` respectively.\n\n Returns b... |
Please provide a description of the function:def remove_sentence_boundaries(tensor: torch.Tensor,
mask: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
# TODO: matthewp, profile this transfer
sequence_lengths = mask.sum(dim=1).detach().cpu().numpy()
tensor_shape = lis... | [
"\n Remove begin/end of sentence embeddings from the batch of sentences.\n Given a batch of sentences with size ``(batch_size, timesteps, dim)``\n this returns a tensor of shape ``(batch_size, timesteps - 2, dim)`` after removing\n the beginning and end sentence markers. The sentences are assumed to be... |
Please provide a description of the function:def add_positional_features(tensor: torch.Tensor,
min_timescale: float = 1.0,
max_timescale: float = 1.0e4):
# pylint: disable=line-too-long
_, timesteps, hidden_dim = tensor.size()
timestep_range = ge... | [
"\n Implements the frequency-based positional encoding described\n in `Attention is all you Need\n <https://www.semanticscholar.org/paper/Attention-Is-All-You-Need-Vaswani-Shazeer/0737da0767d77606169cbf4187b83e1ab62f6077>`_ .\n\n Adds sinusoids of different frequencies to a ``Tensor``. A sinusoid of a\n... |
Please provide a description of the function:def clone(module: torch.nn.Module, num_copies: int) -> torch.nn.ModuleList:
return torch.nn.ModuleList([copy.deepcopy(module) for _ in range(num_copies)]) | [
"Produce N identical layers."
] |
Please provide a description of the function:def combine_initial_dims(tensor: torch.Tensor) -> torch.Tensor:
if tensor.dim() <= 2:
return tensor
else:
return tensor.view(-1, tensor.size(-1)) | [
"\n Given a (possibly higher order) tensor of ids with shape\n (d1, ..., dn, sequence_length)\n Return a view that's (d1 * ... * dn, sequence_length).\n If original tensor is 1-d or 2-d, return it as is.\n "
] |
Please provide a description of the function:def uncombine_initial_dims(tensor: torch.Tensor, original_size: torch.Size) -> torch.Tensor:
if len(original_size) <= 2:
return tensor
else:
view_args = list(original_size) + [tensor.size(-1)]
return tensor.view(*view_args) | [
"\n Given a tensor of embeddings with shape\n (d1 * ... * dn, sequence_length, embedding_dim)\n and the original shape\n (d1, ..., dn, sequence_length),\n return the reshaped tensor of embeddings with shape\n (d1, ..., dn, sequence_length, embedding_dim).\n If original size is 1-d or 2-d, retur... |
Please provide a description of the function:def _string_in_table(self, candidate: str) -> List[str]:
candidate_column_names: List[str] = []
# First check if the entire candidate occurs as a cell.
if candidate in self._string_column_mapping:
candidate_column_names = self._st... | [
"\n Checks if the string occurs in the table, and if it does, returns the names of the columns\n under which it occurs. If it does not, returns an empty list.\n "
] |
Please provide a description of the function:def normalize_string(string: str) -> str:
# Normalization rules from Sempre
# \u201A -> ,
string = re.sub("‚", ",", string)
string = re.sub("„", ",,", string)
string = re.sub("[·・]", ".", string)
string = re.sub("…", "... | [
"\n These are the transformation rules used to normalize cell in column names in Sempre. See\n ``edu.stanford.nlp.sempre.tables.StringNormalizationUtils.characterNormalize`` and\n ``edu.stanford.nlp.sempre.tables.TableTypeSystem.canonicalizeName``. We reproduce those\n rules here to no... |
Please provide a description of the function:def lisp_to_nested_expression(lisp_string: str) -> List:
stack: List = []
current_expression: List = []
tokens = lisp_string.split()
for token in tokens:
while token[0] == '(':
nested_expression: List = []
current_expressi... | [
"\n Takes a logical form as a lisp string and returns a nested list representation of the lisp.\n For example, \"(count (division first))\" would get mapped to ['count', ['division', 'first']].\n "
] |
Please provide a description of the function:def batch_to_embeddings(self, batch: List[List[str]]) -> Tuple[torch.Tensor, torch.Tensor]:
character_ids = batch_to_ids(batch)
if self.cuda_device >= 0:
character_ids = character_ids.cuda(device=self.cuda_device)
bilm_output = s... | [
"\n Parameters\n ----------\n batch : ``List[List[str]]``, required\n A list of tokenized sentences.\n\n Returns\n -------\n A tuple of tensors, the first representing activations (batch_size, 3, num_timesteps, 1024) and\n the second a mask (batch_size... |
Please provide a description of the function:def embed_sentence(self, sentence: List[str]) -> numpy.ndarray:
return self.embed_batch([sentence])[0] | [
"\n Computes the ELMo embeddings for a single tokenized sentence.\n\n Please note that ELMo has internal state and will give different results for the same input.\n See the comment under the class definition.\n\n Parameters\n ----------\n sentence : ``List[str]``, required\... |
Please provide a description of the function:def embed_batch(self, batch: List[List[str]]) -> List[numpy.ndarray]:
elmo_embeddings = []
# Batches with only an empty sentence will throw an exception inside AllenNLP, so we handle this case
# and return an empty embedding instead.
... | [
"\n Computes the ELMo embeddings for a batch of tokenized sentences.\n\n Please note that ELMo has internal state and will give different results for the same input.\n See the comment under the class definition.\n\n Parameters\n ----------\n batch : ``List[List[str]]``, req... |
Please provide a description of the function:def embed_sentences(self,
sentences: Iterable[List[str]],
batch_size: int = DEFAULT_BATCH_SIZE) -> Iterable[numpy.ndarray]:
for batch in lazy_groups_of(iter(sentences), batch_size):
yield from self.... | [
"\n Computes the ELMo embeddings for a iterable of sentences.\n\n Please note that ELMo has internal state and will give different results for the same input.\n See the comment under the class definition.\n\n Parameters\n ----------\n sentences : ``Iterable[List[str]]``, re... |
Please provide a description of the function: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... | [
"\n Computes ELMo embeddings from an input_file where each line contains a sentence tokenized by whitespace.\n The ELMo embeddings are written out in HDF5 format, where each sentence embedding\n is saved in a dataset with the line number in the original file as the key.\n\n Parameters\n ... |
Please provide a description of the function:def add_field(self, field_name: str, field: Field, vocab: Vocabulary = None) -> None:
self.fields[field_name] = field
if self.indexed:
field.index(vocab) | [
"\n Add the field to the existing fields mapping.\n If we have already indexed the Instance, then we also index `field`, so\n it is necessary to supply the vocab.\n "
] |
Please provide a description of the function:def count_vocab_items(self, counter: Dict[str, Dict[str, int]]):
for field in self.fields.values():
field.count_vocab_items(counter) | [
"\n Increments counts in the given ``counter`` for all of the vocabulary items in all of the\n ``Fields`` in this ``Instance``.\n "
] |
Please provide a description of the function:def index_fields(self, vocab: Vocabulary) -> None:
if not self.indexed:
self.indexed = True
for field in self.fields.values():
field.index(vocab) | [
"\n Indexes all fields in this ``Instance`` using the provided ``Vocabulary``.\n This `mutates` the current object, it does not return a new ``Instance``.\n A ``DataIterator`` will call this on each pass through a dataset; we use the ``indexed``\n flag to make sure that indexing only hap... |
Please provide a description of the function:def get_padding_lengths(self) -> Dict[str, Dict[str, int]]:
lengths = {}
for field_name, field in self.fields.items():
lengths[field_name] = field.get_padding_lengths()
return lengths | [
"\n Returns a dictionary of padding lengths, keyed by field name. Each ``Field`` returns a\n mapping from padding keys to actual lengths, and we just key that dictionary by field name.\n "
] |
Please provide a description of the function:def as_tensor_dict(self,
padding_lengths: Dict[str, Dict[str, int]] = None) -> Dict[str, DataArray]:
padding_lengths = padding_lengths or self.get_padding_lengths()
tensors = {}
for field_name, field in self.fields.item... | [
"\n Pads each ``Field`` in this instance to the lengths given in ``padding_lengths`` (which is\n keyed by field name, then by padding key, the same as the return value in\n :func:`get_padding_lengths`), returning a list of torch tensors for each field.\n\n If ``padding_lengths`` is omitt... |
Please provide a description of the function:def full_name(cla55: Optional[type]) -> str:
# Special case to handle None:
if cla55 is None:
return "?"
if issubclass(cla55, Initializer) and cla55 not in [Initializer, PretrainedModelInitializer]:
init_fn = cla55()._init_function
r... | [
"\n Return the full name (including module) of the given class.\n ",
"Dict[{full_name(key_type)}, {full_name(value_type)}]",
"{_remove_prefix(str(origin))}[{\", \".join(full_name(arg) for arg in args)}]",
"Optional[{full_name(args[0])}]",
"Union[{\", \".join(full_name(arg) for arg in args)}]"
] |
Please provide a description of the function:def _get_config_type(cla55: type) -> Optional[str]:
# Special handling for pytorch RNN types:
if cla55 == torch.nn.RNN:
return "rnn"
elif cla55 == torch.nn.LSTM:
return "lstm"
elif cla55 == torch.nn.GRU:
return "gru"
for subc... | [
"\n Find the name (if any) that a subclass was registered under.\n We do this simply by iterating through the registry until we\n find it.\n "
] |
Please provide a description of the function:def _docspec_comments(obj) -> Dict[str, str]:
# 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 = getattr(obj.__init__, '__doc__'... | [
"\n Inspect the docstring and get the comments for each parameter.\n "
] |
Please provide a description of the function:def _auto_config(cla55: Type[T]) -> Config[T]:
typ3 = _get_config_type(cla55)
# Don't include self, or vocab
names_to_ignore = {"self", "vocab"}
# Hack for RNNs
if cla55 in [torch.nn.RNN, torch.nn.LSTM, torch.nn.GRU]:
cla55 = torch.nn.RNNBa... | [
"\n Create the ``Config`` for a class by reflecting on its ``__init__``\n method and applying a few hacks.\n "
] |
Please provide a description of the function:def render_config(config: Config, indent: str = "") -> str:
# Add four spaces to the indent.
new_indent = indent + " "
return "".join([
# opening brace + newline
"{\n",
# "type": "...", (if present)
f'{new_... | [
"\n Pretty-print a config in sort-of-JSON+comments.\n "
] |
Please provide a description of the function:def _render(item: ConfigItem, indent: str = "") -> str:
optional = item.default_value != _NO_DEFAULT
if is_configurable(item.annotation):
rendered_annotation = f"{item.annotation} (configurable)"
else:
rendered_annotation = str(item.annotati... | [
"\n Render a single config item, with the provided indent\n "
] |
Please provide a description of the function:def _valid_choices(cla55: type) -> Dict[str, str]:
valid_choices: Dict[str, str] = {}
if cla55 not in Registrable._registry:
raise ValueError(f"{cla55} is not a known Registrable class")
for name, subclass in Registrable._registry[cla55].items():
... | [
"\n Return a mapping {registered_name -> subclass_name}\n for the registered subclasses of `cla55`.\n "
] |
Please provide a description of the function:def url_to_filename(url: str, etag: str = None) -> str:
url_bytes = url.encode('utf-8')
url_hash = sha256(url_bytes)
filename = url_hash.hexdigest()
if etag:
etag_bytes = etag.encode('utf-8')
etag_hash = sha256(etag_bytes)
filena... | [
"\n Convert `url` into a hashed filename in a repeatable way.\n If `etag` is specified, append its hash to the url's, delimited\n by a period.\n "
] |
Please provide a description of the function:def filename_to_url(filename: str, cache_dir: str = None) -> Tuple[str, str]:
if cache_dir is None:
cache_dir = CACHE_DIRECTORY
cache_path = os.path.join(cache_dir, filename)
if not os.path.exists(cache_path):
raise FileNotFoundError("file {... | [
"\n Return the url and etag (which may be ``None``) stored for `filename`.\n Raise ``FileNotFoundError`` if `filename` or its stored metadata do not exist.\n "
] |
Please provide a description of the function:def cached_path(url_or_filename: Union[str, Path], cache_dir: str = None) -> str:
if cache_dir is None:
cache_dir = CACHE_DIRECTORY
if isinstance(url_or_filename, Path):
url_or_filename = str(url_or_filename)
url_or_filename = os.path.expand... | [
"\n Given something that might be a URL (or might be a local path),\n determine which. If it's a URL, download the file and cache it, and\n return the path to the cached file. If it's already a local path,\n make sure the file exists and then return the path.\n "
] |
Please provide a description of the function:def is_url_or_existing_file(url_or_filename: Union[str, Path, None]) -> bool:
if url_or_filename is None:
return False
url_or_filename = os.path.expanduser(str(url_or_filename))
parsed = urlparse(url_or_filename)
return parsed.scheme in ('http', ... | [
"\n Given something that might be a URL (or might be a local path),\n determine check if it's url or an existing file path.\n "
] |
Please provide a description of the function:def split_s3_path(url: str) -> Tuple[str, str]:
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 beginning of path... | [
"Split a full s3 path into the bucket name and path."
] |
Please provide a description of the function:def s3_request(func: Callable):
@wraps(func)
def wrapper(url: str, *args, **kwargs):
try:
return func(url, *args, **kwargs)
except ClientError as exc:
if int(exc.response["Error"]["Code"]) == 404:
raise Fi... | [
"\n Wrapper function for s3 requests in order to create more helpful error\n messages.\n "
] |
Please provide a description of the function:def s3_etag(url: str) -> Optional[str]:
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 | [
"Check ETag on S3 object."
] |
Please provide a description of the function:def s3_get(url: str, temp_file: IO) -> None:
s3_resource = boto3.resource("s3")
bucket_name, s3_path = split_s3_path(url)
s3_resource.Bucket(bucket_name).download_fileobj(s3_path, temp_file) | [
"Pull a file directly from S3."
] |
Please provide a description of the function:def get_from_cache(url: str, cache_dir: str = None) -> str:
if cache_dir is None:
cache_dir = CACHE_DIRECTORY
os.makedirs(cache_dir, exist_ok=True)
# Get eTag to add to filename, if it exists.
if url.startswith("s3://"):
etag = s3_etag(... | [
"\n Given a URL, look for the corresponding dataset in the local cache.\n If it's not there, download it. Then return the path to the cached file.\n "
] |
Please provide a description of the function:def read_set_from_file(filename: str) -> Set[str]:
collection = set()
with open(filename, 'r') as file_:
for line in file_:
collection.add(line.rstrip())
return collection | [
"\n Extract a de-duped collection (set) of text from a file.\n Expected file format is one item per line.\n "
] |
Please provide a description of the function:def main(output_directory: int, data: str) -> None:
json_files = glob.glob(os.path.join(data, "*.json"))
for dataset in json_files:
dataset_name = os.path.basename(dataset)[:-5]
print(f"Processing dataset: {dataset} into query and question "
... | [
"\n Processes the text2sql data into the following directory structure:\n\n ``dataset/{query_split, question_split}/{train,dev,test}.json``\n\n for datasets which have train, dev and test splits, or:\n\n ``dataset/{query_split, question_split}/{split_{split_id}}.json``\n\n for datasets which use cros... |
Please provide a description of the function:def resolve(self, other: Type) -> Optional[Type]:
if not isinstance(other, NltkComplexType):
return None
expected_second = ComplexType(NUMBER_TYPE,
ComplexType(ANY_TYPE, ComplexType(ComplexType(ANY_TY... | [
"See ``PlaceholderType.resolve``"
] |
Please provide a description of the function:def resolve(self, other: Type) -> Type:
if not isinstance(other, NltkComplexType):
return None
resolved_second = NUMBER_TYPE.resolve(other.second)
if not resolved_second:
return None
return CountType(other.firs... | [
"See ``PlaceholderType.resolve``"
] |
Please provide a description of the function: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:
processed_data: JsonDict =... | [
"\n Reads an NLVR dataset and returns a JSON representation containing sentences, labels, correct and\n incorrect logical forms. The output will contain at most `max_num_logical_forms` logical forms\n each in both correct and incorrect lists. The output format is:\n ``[{\"id\": str, \"label\": str, ... |
Please provide a description of the function:def batch_split_sentences(self, texts: List[str]) -> List[List[str]]:
return [self.split_sentences(text) for text in texts] | [
"\n This method lets you take advantage of spacy's batch processing.\n Default implementation is to just iterate over the texts and call ``split_sentences``.\n "
] |
Please provide a description of the function:def dataset_iterator(self, file_path: str) -> Iterator[OntonotesSentence]:
for conll_file in self.dataset_path_iterator(file_path):
yield from self.sentence_iterator(conll_file) | [
"\n An iterator over the entire dataset, yielding all sentences processed.\n "
] |
Please provide a description of the function:def dataset_path_iterator(file_path: str) -> Iterator[str]:
logger.info("Reading CONLL sentences from dataset files at: %s", file_path)
for root, _, files in list(os.walk(file_path)):
for data_file in files:
# These are a ... | [
"\n An iterator returning file_paths in a directory\n containing CONLL-formatted files.\n "
] |
Please provide a description of the function:def dataset_document_iterator(self, file_path: str) -> Iterator[List[OntonotesSentence]]:
with codecs.open(file_path, 'r', encoding='utf8') as open_file:
conll_rows = []
document: List[OntonotesSentence] = []
for line in o... | [
"\n An iterator over CONLL formatted files which yields documents, regardless\n of the number of document annotations in a particular file. This is useful\n for conll data which has been preprocessed, such as the preprocessing which\n takes place for the 2012 CONLL Coreference Resolution... |
Please provide a description of the function:def sentence_iterator(self, file_path: str) -> Iterator[OntonotesSentence]:
for document in self.dataset_document_iterator(file_path):
for sentence in document:
yield sentence | [
"\n An iterator over the sentences in an individual CONLL formatted file.\n "
] |
Please provide a description of the function:def _process_coref_span_annotations_for_word(label: str,
word_index: int,
clusters: DefaultDict[int, List[Tuple[int, int]]],
cor... | [
"\n For a given coref label, add it to a currently open span(s), complete a span(s) or\n ignore it, if it is outside of all spans. This method mutates the clusters and coref_stacks\n dictionaries.\n\n Parameters\n ----------\n label : ``str``\n The coref label fo... |
Please provide a description of the function:def _process_span_annotations_for_word(annotations: List[str],
span_labels: List[List[str]],
current_span_labels: List[Optional[str]]) -> None:
for annotation_index, annota... | [
"\n Given a sequence of different label types for a single word and the current\n span label we are inside, compute the BIO tag for each label and append to a list.\n\n Parameters\n ----------\n annotations: ``List[str]``\n A list of labels to compute BIO tags for.\n ... |
Please provide a description of the function:def print_results_from_args(args: argparse.Namespace):
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:
full_name = os.path.j... | [
"\n Prints results from an ``argparse.Namespace`` object.\n "
] |
Please provide a description of the function:def forward(self, input_tensor):
# pylint: disable=arguments-differ
ones = input_tensor.data.new_ones(input_tensor.shape[0], input_tensor.shape[-1])
dropout_mask = torch.nn.functional.dropout(ones, self.p, self.training, inplace=False)
... | [
"\n Apply dropout to input tensor.\n\n Parameters\n ----------\n input_tensor: ``torch.FloatTensor``\n A tensor of shape ``(batch_size, num_timesteps, embedding_dim)``\n\n Returns\n -------\n output: ``torch.FloatTensor``\n A tensor of shape ``(... |
Please provide a description of the function:def get_metric(self, reset: bool) -> Union[float, Tuple[float, ...], Dict[str, float], Dict[str, List[float]]]:
raise NotImplementedError | [
"\n Compute and return the metric. Optionally also call :func:`self.reset`.\n "
] |
Please provide a description of the function:def unwrap_to_tensors(*tensors: torch.Tensor):
return (x.detach().cpu() if isinstance(x, torch.Tensor) else x for x in tensors) | [
"\n If you actually passed gradient-tracking Tensors to a Metric, there will be\n a huge memory leak, because it will prevent garbage collection for the computation\n graph. This method ensures that you're using tensors directly and that they are on\n the CPU.\n "
] |
Please provide a description of the function:def replace_variables(sentence: List[str],
sentence_variables: Dict[str, str]) -> Tuple[List[str], List[str]]:
tokens = []
tags = []
for token in sentence:
if token not in sentence_variables:
tokens.append(token)
... | [
"\n Replaces abstract variables in text with their concrete counterparts.\n "
] |
Please provide a description of the function:def clean_and_split_sql(sql: str) -> List[str]:
sql_tokens: List[str] = []
for token in sql.strip().split():
token = token.replace('"', "'").replace("%", "")
if token.endswith("(") and len(token) > 1:
sql_tokens.extend(split_table_and... | [
"\n Cleans up and unifies a SQL query. This involves unifying quoted strings\n and splitting brackets which aren't formatted consistently in the data.\n "
] |
Please provide a description of the function:def resolve_primary_keys_in_schema(sql_tokens: List[str],
schema: Dict[str, List[TableColumn]]) -> List[str]:
primary_keys_for_tables = {name: max(columns, key=lambda x: x.is_primary_key).name
for nam... | [
"\n Some examples in the text2sql datasets use ID as a column reference to the\n column of a table which has a primary key. This causes problems if you are trying\n to constrain a grammar to only produce the column names directly, because you don't\n know what ID refers to. So instead of dealing with th... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.