partition
stringclasses
3 values
func_name
stringlengths
1
134
docstring
stringlengths
1
46.9k
path
stringlengths
4
223
original_string
stringlengths
75
104k
code
stringlengths
75
104k
docstring_tokens
listlengths
1
1.97k
repo
stringlengths
7
55
language
stringclasses
1 value
url
stringlengths
87
315
code_tokens
listlengths
19
28.4k
sha
stringlengths
40
40
train
NlvrLanguage.touch_object
Returns all objects that touch the given set of objects.
allennlp/semparse/domain_languages/nlvr_language.py
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...
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...
[ "Returns", "all", "objects", "that", "touch", "the", "given", "set", "of", "objects", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/domain_languages/nlvr_language.py#L329-L341
[ "def", "touch_object", "(", "self", ",", "objects", ":", "Set", "[", "Object", "]", ")", "->", "Set", "[", "Object", "]", ":", "objects_per_box", "=", "self", ".", "_separate_objects_by_boxes", "(", "objects", ")", "return_set", "=", "set", "(", ")", "fo...
648a36f77db7e45784c047176074f98534c76636
train
NlvrLanguage.top
Return the topmost objects (i.e. minimum y_loc). The comparison is done separately for each box.
allennlp/semparse/domain_languages/nlvr_language.py
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...
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", "topmost", "objects", "(", "i", ".", "e", ".", "minimum", "y_loc", ")", ".", "The", "comparison", "is", "done", "separately", "for", "each", "box", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/domain_languages/nlvr_language.py#L344-L354
[ "def", "top", "(", "self", ",", "objects", ":", "Set", "[", "Object", "]", ")", "->", "Set", "[", "Object", "]", ":", "objects_per_box", "=", "self", ".", "_separate_objects_by_boxes", "(", "objects", ")", "return_set", ":", "Set", "[", "Object", "]", ...
648a36f77db7e45784c047176074f98534c76636
train
NlvrLanguage.bottom
Return the bottom most objects(i.e. maximum y_loc). The comparison is done separately for each box.
allennlp/semparse/domain_languages/nlvr_language.py
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...
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...
[ "Return", "the", "bottom", "most", "objects", "(", "i", ".", "e", ".", "maximum", "y_loc", ")", ".", "The", "comparison", "is", "done", "separately", "for", "each", "box", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/domain_languages/nlvr_language.py#L357-L367
[ "def", "bottom", "(", "self", ",", "objects", ":", "Set", "[", "Object", "]", ")", "->", "Set", "[", "Object", "]", ":", "objects_per_box", "=", "self", ".", "_separate_objects_by_boxes", "(", "objects", ")", "return_set", ":", "Set", "[", "Object", "]",...
648a36f77db7e45784c047176074f98534c76636
train
NlvrLanguage.above
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.
allennlp/semparse/domain_languages/nlvr_language.py
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...
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", "above", "the", "given", "objects", ".", "That", "is", "if", "the", "input", "is", "a", "set", "of", "two", "objects", "one", "in", "each", "box", "we", "will", "r...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/domain_languages/nlvr_language.py#L370-L384
[ "def", "above", "(", "self", ",", "objects", ":", "Set", "[", "Object", "]", ")", "->", "Set", "[", "Object", "]", ":", "objects_per_box", "=", "self", ".", "_separate_objects_by_boxes", "(", "objects", ")", "return_set", "=", "set", "(", ")", "for", "...
648a36f77db7e45784c047176074f98534c76636
train
NlvrLanguage.below
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.
allennlp/semparse/domain_languages/nlvr_language.py
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...
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", "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", "r...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/domain_languages/nlvr_language.py#L387-L401
[ "def", "below", "(", "self", ",", "objects", ":", "Set", "[", "Object", "]", ")", "->", "Set", "[", "Object", "]", ":", "objects_per_box", "=", "self", ".", "_separate_objects_by_boxes", "(", "objects", ")", "return_set", "=", "set", "(", ")", "for", "...
648a36f77db7e45784c047176074f98534c76636
train
NlvrLanguage._objects_touch_each_other
Returns true iff the objects touch each other.
allennlp/semparse/domain_languages/nlvr_language.py
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 ...
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 ...
[ "Returns", "true", "iff", "the", "objects", "touch", "each", "other", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/domain_languages/nlvr_language.py#L654-L666
[ "def", "_objects_touch_each_other", "(", "self", ",", "object1", ":", "Object", ",", "object2", ":", "Object", ")", "->", "bool", ":", "in_vertical_range", "=", "object1", ".", "y_loc", "<=", "object2", ".", "y_loc", "+", "object2", ".", "size", "and", "ob...
648a36f77db7e45784c047176074f98534c76636
train
NlvrLanguage._separate_objects_by_boxes
Given a set of objects, separate them by the boxes they belong to and return a dict.
allennlp/semparse/domain_languages/nlvr_language.py
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 ...
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 ...
[ "Given", "a", "set", "of", "objects", "separate", "them", "by", "the", "boxes", "they", "belong", "to", "and", "return", "a", "dict", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/domain_languages/nlvr_language.py#L668-L677
[ "def", "_separate_objects_by_boxes", "(", "self", ",", "objects", ":", "Set", "[", "Object", "]", ")", "->", "Dict", "[", "Box", ",", "List", "[", "Object", "]", "]", ":", "objects_per_box", ":", "Dict", "[", "Box", ",", "List", "[", "Object", "]", "...
648a36f77db7e45784c047176074f98534c76636
train
NlvrLanguage._get_objects_with_same_attribute
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.
allennlp/semparse/domain_languages/nlvr_language.py
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 ...
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 ...
[ "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", ".", "...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/domain_languages/nlvr_language.py#L679-L695
[ "def", "_get_objects_with_same_attribute", "(", "self", ",", "objects", ":", "Set", "[", "Object", "]", ",", "attribute_function", ":", "Callable", "[", "[", "Object", "]", ",", "str", "]", ")", "->", "Set", "[", "Object", "]", ":", "objects_of_attribute", ...
648a36f77db7e45784c047176074f98534c76636
train
has_tensor
Given a possibly complex data structure, check if it has any torch.Tensors in it.
allennlp/nn/util.py
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,...
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", "possibly", "complex", "data", "structure", "check", "if", "it", "has", "any", "torch", ".", "Tensors", "in", "it", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/nn/util.py#L20-L32
[ "def", "has_tensor", "(", "obj", ")", "->", "bool", ":", "if", "isinstance", "(", "obj", ",", "torch", ".", "Tensor", ")", ":", "return", "True", "elif", "isinstance", "(", "obj", ",", "dict", ")", ":", "return", "any", "(", "has_tensor", "(", "value...
648a36f77db7e45784c047176074f98534c76636
train
move_to_device
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).
allennlp/nn/util.py
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)...
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)...
[ "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", ")", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/nn/util.py#L35-L51
[ "def", "move_to_device", "(", "obj", ",", "cuda_device", ":", "int", ")", ":", "if", "cuda_device", "<", "0", "or", "not", "has_tensor", "(", "obj", ")", ":", "return", "obj", "elif", "isinstance", "(", "obj", ",", "torch", ".", "Tensor", ")", ":", "...
648a36f77db7e45784c047176074f98534c76636
train
clamp_tensor
Supports sparse and dense tensors. Returns a tensor with values clamped between the provided minimum and maximum, without modifying the original tensor.
allennlp/nn/util.py
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...
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...
[ "Supports", "sparse", "and", "dense", "tensors", ".", "Returns", "a", "tensor", "with", "values", "clamped", "between", "the", "provided", "minimum", "and", "maximum", "without", "modifying", "the", "original", "tensor", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/nn/util.py#L54-L66
[ "def", "clamp_tensor", "(", "tensor", ",", "minimum", ",", "maximum", ")", ":", "if", "tensor", ".", "is_sparse", ":", "coalesced_tensor", "=", "tensor", ".", "coalesce", "(", ")", "# pylint: disable=protected-access", "coalesced_tensor", ".", "_values", "(", ")...
648a36f77db7e45784c047176074f98534c76636
train
batch_tensor_dicts
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. Parameters ---------- tensor_dicts : ``List[Dict[str, torch.Tensor]]`` The list of tensor dictionaries to batch. ...
allennlp/nn/util.py
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...
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...
[ "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"...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/nn/util.py#L69-L93
[ "def", "batch_tensor_dicts", "(", "tensor_dicts", ":", "List", "[", "Dict", "[", "str", ",", "torch", ".", "Tensor", "]", "]", ",", "remove_trailing_dimension", ":", "bool", "=", "False", ")", "->", "Dict", "[", "str", ",", "torch", ".", "Tensor", "]", ...
648a36f77db7e45784c047176074f98534c76636
train
get_mask_from_sequence_lengths
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]]``. ...
allennlp/nn/util.py
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 ...
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 ...
[ "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", "...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/nn/util.py#L115-L129
[ "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_lengt...
648a36f77db7e45784c047176074f98534c76636
train
sort_batch_by_length
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 tensor representing the lengths of some dimension of the tensor which we want to sort b...
allennlp/nn/util.py
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...
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...
[ "Sort", "a", "batch", "first", "tensor", "by", "some", "specified", "lengths", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/nn/util.py#L132-L169
[ "def", "sort_batch_by_length", "(", "tensor", ":", "torch", ".", "Tensor", ",", "sequence_lengths", ":", "torch", ".", "Tensor", ")", ":", "if", "not", "isinstance", "(", "tensor", ",", "torch", ".", "Tensor", ")", "or", "not", "isinstance", "(", "sequence...
648a36f77db7e45784c047176074f98534c76636
train
get_final_encoder_states
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 sequenc...
allennlp/nn/util.py
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...
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...
[ "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", ...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/nn/util.py#L172-L202
[ "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...
648a36f77db7e45784c047176074f98534c76636
train
get_dropout_mask
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. Parameters ----------...
allennlp/nn/util.py
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...
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...
[ "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", "...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/nn/util.py#L205-L228
[ "def", "get_dropout_mask", "(", "dropout_probability", ":", "float", ",", "tensor_for_masking", ":", "torch", ".", "Tensor", ")", ":", "binary_mask", "=", "(", "torch", ".", "rand", "(", "tensor_for_masking", ".", "size", "(", ")", ")", ">", "dropout_probabili...
648a36f77db7e45784c047176074f98534c76636
train
masked_softmax
``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. ``vector`` can have an arbitrary number of ...
allennlp/nn/util.py
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 `...
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", ".", "softmax", "(", "vector", ")", "does", "not", "work", "if", "some", "elements", "of", "vector", "should", "be", "masked", ".", "This", "performs", "a", "softmax", "on", "just", "the", "non", "-", "masked", "p...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/nn/util.py#L231-L269
[ "def", "masked_softmax", "(", "vector", ":", "torch", ".", "Tensor", ",", "mask", ":", "torch", ".", "Tensor", ",", "dim", ":", "int", "=", "-", "1", ",", "memory_efficient", ":", "bool", "=", "False", ",", "mask_fill_value", ":", "float", "=", "-", ...
648a36f77db7e45784c047176074f98534c76636
train
masked_log_softmax
``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. ``vector`` can have an arbitrar...
allennlp/nn/util.py
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...
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...
[ "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", "-", "maske...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/nn/util.py#L272-L303
[ "def", "masked_log_softmax", "(", "vector", ":", "torch", ".", "Tensor", ",", "mask", ":", "torch", ".", "Tensor", ",", "dim", ":", "int", "=", "-", "1", ")", "->", "torch", ".", "Tensor", ":", "if", "mask", "is", "not", "None", ":", "mask", "=", ...
648a36f77db7e45784c047176074f98534c76636
train
masked_max
To calculate max along certain dimensions on masked values Parameters ---------- vector : ``torch.Tensor`` The vector to calculate max, assume unmasked parts are already zeros mask : ``torch.Tensor`` The mask of the vector. It must be broadcastable with vector. dim : ``int`` ...
allennlp/nn/util.py
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`...
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", "max", "along", "certain", "dimensions", "on", "masked", "values" ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/nn/util.py#L306-L334
[ "def", "masked_max", "(", "vector", ":", "torch", ".", "Tensor", ",", "mask", ":", "torch", ".", "Tensor", ",", "dim", ":", "int", ",", "keepdim", ":", "bool", "=", "False", ",", "min_val", ":", "float", "=", "-", "1e7", ")", "->", "torch", ".", ...
648a36f77db7e45784c047176074f98534c76636
train
masked_mean
To calculate mean along certain dimensions on masked values Parameters ---------- vector : ``torch.Tensor`` The vector to calculate mean. mask : ``torch.Tensor`` The mask of the vector. It must be broadcastable with vector. dim : ``int`` The dimension to calculate mean k...
allennlp/nn/util.py
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...
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...
[ "To", "calculate", "mean", "along", "certain", "dimensions", "on", "masked", "values" ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/nn/util.py#L337-L367
[ "def", "masked_mean", "(", "vector", ":", "torch", ".", "Tensor", ",", "mask", ":", "torch", ".", "Tensor", ",", "dim", ":", "int", ",", "keepdim", ":", "bool", "=", "False", ",", "eps", ":", "float", "=", "1e-8", ")", "->", "torch", ".", "Tensor",...
648a36f77db7e45784c047176074f98534c76636
train
masked_flip
Flips a padded tensor along the time dimension without affecting masked entries. Parameters ---------- padded_sequence : ``torch.Tensor`` The tensor to flip along the time dimension. Assumed to be of dimensions (batch size, num timesteps, ...) sequence_lengths : ...
allennlp/nn/util.py
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...
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...
[ "Flips", "a", "padded", "tensor", "along", "the", "time", "dimension", "without", "affecting", "masked", "entries", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/nn/util.py#L370-L392
[ "def", "masked_flip", "(", "padded_sequence", ":", "torch", ".", "Tensor", ",", "sequence_lengths", ":", "List", "[", "int", "]", ")", "->", "torch", ".", "Tensor", ":", "assert", "padded_sequence", ".", "size", "(", "0", ")", "==", "len", "(", "sequence...
648a36f77db7e45784c047176074f98534c76636
train
viterbi_decode
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. Parameters ---------- tag_sequence : torch.Tenso...
allennlp/nn/util.py
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...
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...
[ "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",...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/nn/util.py#L395-L478
[ "def", "viterbi_decode", "(", "tag_sequence", ":", "torch", ".", "Tensor", ",", "transition_matrix", ":", "torch", ".", "Tensor", ",", "tag_observations", ":", "Optional", "[", "List", "[", "int", "]", "]", "=", "None", ")", ":", "sequence_length", ",", "n...
648a36f77db7e45784c047176074f98534c76636
train
get_text_field_mask
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``. If ``num_w...
allennlp/nn/util.py
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`...
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", "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", ...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/nn/util.py#L481-L527
[ "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", ":",...
648a36f77db7e45784c047176074f98534c76636
train
weighted_sum
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. Note that while we call this a "matrix" of vectors and an attentio...
allennlp/nn/util.py
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...
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...
[ "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"...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/nn/util.py#L530-L566
[ "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 ...
648a36f77db7e45784c047176074f98534c76636
train
sequence_cross_entropy_with_logits
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 th...
allennlp/nn/util.py
def sequence_cross_entropy_with_logits(logits: torch.FloatTensor, targets: torch.LongTensor, weights: torch.FloatTensor, average: str = "batch", label_smoothing: fl...
def sequence_cross_entropy_with_logits(logits: torch.FloatTensor, targets: torch.LongTensor, weights: torch.FloatTensor, average: str = "batch", label_smoothing: fl...
[ "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", ...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/nn/util.py#L569-L648
[ "def", "sequence_cross_entropy_with_logits", "(", "logits", ":", "torch", ".", "FloatTensor", ",", "targets", ":", "torch", ".", "LongTensor", ",", "weights", ":", "torch", ".", "FloatTensor", ",", "average", ":", "str", "=", "\"batch\"", ",", "label_smoothing",...
648a36f77db7e45784c047176074f98534c76636
train
replace_masked_values
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. This just does ``tensor.masked_fill()``, except the pytorch ...
allennlp/nn/util.py
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...
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...
[ "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", "...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/nn/util.py#L651-L663
[ "def", "replace_masked_values", "(", "tensor", ":", "torch", ".", "Tensor", ",", "mask", ":", "torch", ".", "Tensor", ",", "replace_with", ":", "float", ")", "->", "torch", ".", "Tensor", ":", "if", "tensor", ".", "dim", "(", ")", "!=", "mask", ".", ...
648a36f77db7e45784c047176074f98534c76636
train
tensors_equal
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....
allennlp/nn/util.py
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...
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...
[ "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"...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/nn/util.py#L666-L699
[ "def", "tensors_equal", "(", "tensor1", ":", "torch", ".", "Tensor", ",", "tensor2", ":", "torch", ".", "Tensor", ",", "tolerance", ":", "float", "=", "1e-12", ")", "->", "bool", ":", "# pylint: disable=too-many-return-statements", "if", "isinstance", "(", "te...
648a36f77db7e45784c047176074f98534c76636
train
device_mapping
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.
allennlp/nn/util.py
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...
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...
[ "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", ...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/nn/util.py#L702-L715
[ "def", "device_mapping", "(", "cuda_device", ":", "int", ")", ":", "def", "inner_device_mapping", "(", "storage", ":", "torch", ".", "Storage", ",", "location", ")", "->", "torch", ".", "Storage", ":", "# pylint: disable=unused-argument", "if", "cuda_device", ">...
648a36f77db7e45784c047176074f98534c76636
train
combine_tensors
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"``. We allow the following kinds of combinations: ``x``, ``x*y``, ``x+y``, ``x-y``, and ``x/...
allennlp/nn/util.py
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"`...
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"`...
[ "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", ...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/nn/util.py#L718-L746
[ "def", "combine_tensors", "(", "combination", ":", "str", ",", "tensors", ":", "List", "[", "torch", ".", "Tensor", "]", ")", "->", "torch", ".", "Tensor", ":", "if", "len", "(", "tensors", ")", ">", "9", ":", "raise", "ConfigurationError", "(", "\"Dou...
648a36f77db7e45784c047176074f98534c76636
train
_rindex
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 index associated to the position of the last item equal to obj
allennlp/nn/util.py
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...
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...
[ "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", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/nn/util.py#L749-L767
[ "def", "_rindex", "(", "sequence", ":", "Sequence", "[", "T", "]", ",", "obj", ":", "T", ")", "->", "int", ":", "for", "i", "in", "range", "(", "len", "(", "sequence", ")", "-", "1", ",", "-", "1", ",", "-", "1", ")", ":", "if", "sequence", ...
648a36f77db7e45784c047176074f98534c76636
train
combine_tensors_and_multiply
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 w...
allennlp/nn/util.py
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...
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...
[ "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", "instanti...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/nn/util.py#L792-L829
[ "def", "combine_tensors_and_multiply", "(", "combination", ":", "str", ",", "tensors", ":", "List", "[", "torch", ".", "Tensor", "]", ",", "weights", ":", "torch", ".", "nn", ".", "Parameter", ")", "->", "torch", ".", "Tensor", ":", "if", "len", "(", "...
648a36f77db7e45784c047176074f98534c76636
train
get_combined_dim
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``. Parameters ...
allennlp/nn/util.py
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 ...
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 ...
[ "For", "use", "with", ":", "func", ":", "combine_tensors", ".", "This", "function", "computes", "the", "resultant", "dimension", "when", "calling", "combine_tensors", "(", "combination", "tensors", ")", "when", "the", "tensor", "dimension", "is", "known", ".", ...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/nn/util.py#L882-L901
[ "def", "get_combined_dim", "(", "combination", ":", "str", ",", "tensor_dims", ":", "List", "[", "int", "]", ")", "->", "int", ":", "if", "len", "(", "tensor_dims", ")", ">", "9", ":", "raise", "ConfigurationError", "(", "\"Double-digit tensor lists not curren...
648a36f77db7e45784c047176074f98534c76636
train
logsumexp
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. Parameters ---------- tensor : torch.FloatTensor, required. A tensor of arbitrary size. dim : ...
allennlp/nn/util.py
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...
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...
[ "A", "numerically", "stable", "computation", "of", "logsumexp", ".", "This", "is", "mathematically", "equivalent", "to", "tensor", ".", "exp", "()", ".", "sum", "(", "dim", "keep", "=", "keepdim", ")", ".", "log", "()", ".", "This", "function", "is", "ty...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/nn/util.py#L919-L941
[ "def", "logsumexp", "(", "tensor", ":", "torch", ".", "Tensor", ",", "dim", ":", "int", "=", "-", "1", ",", "keepdim", ":", "bool", "=", "False", ")", "->", "torch", ".", "Tensor", ":", "max_score", ",", "_", "=", "tensor", ".", "max", "(", "dim"...
648a36f77db7e45784c047176074f98534c76636
train
flatten_and_batch_shift_indices
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...
allennlp/nn/util.py
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...
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...
[ "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"...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/nn/util.py#L954-L995
[ "def", "flatten_and_batch_shift_indices", "(", "indices", ":", "torch", ".", "Tensor", ",", "sequence_length", ":", "int", ")", "->", "torch", ".", "Tensor", ":", "# Shape: (batch_size)", "offsets", "=", "get_range_vector", "(", "indices", ".", "size", "(", "0",...
648a36f77db7e45784c047176074f98534c76636
train
batched_index_select
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)``. This function returns selected values in the target with respect to the provided indices, which have size ``(b...
allennlp/nn/util.py
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 ...
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", "(", "batch_size", "d_1", "...", "d_n", ")", "indexes", "into", "the", "sequence", "dimension", "(", "dimension", "2", ")", "of", "the", "target", "which", "has", "size", "(", "batch_size", "sequence_length", "embeddi...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/nn/util.py#L998-L1049
[ "def", "batched_index_select", "(", "target", ":", "torch", ".", "Tensor", ",", "indices", ":", "torch", ".", "LongTensor", ",", "flattened_indices", ":", "Optional", "[", "torch", ".", "LongTensor", "]", "=", "None", ")", "->", "torch", ".", "Tensor", ":"...
648a36f77db7e45784c047176074f98534c76636
train
flattened_index_select
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...
allennlp/nn/util.py
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...
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...
[ "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", "sequenc...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/nn/util.py#L1052-L1081
[ "def", "flattened_index_select", "(", "target", ":", "torch", ".", "Tensor", ",", "indices", ":", "torch", ".", "LongTensor", ")", "->", "torch", ".", "Tensor", ":", "if", "indices", ".", "dim", "(", ")", "!=", "2", ":", "raise", "ConfigurationError", "(...
648a36f77db7e45784c047176074f98534c76636
train
get_range_vector
Returns a range vector with the desired size, starting at 0. The CUDA implementation is meant to avoid copy data from CPU to GPU.
allennlp/nn/util.py
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 ...
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 ...
[ "Returns", "a", "range", "vector", "with", "the", "desired", "size", "starting", "at", "0", ".", "The", "CUDA", "implementation", "is", "meant", "to", "avoid", "copy", "data", "from", "CPU", "to", "GPU", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/nn/util.py#L1084-L1092
[ "def", "get_range_vector", "(", "size", ":", "int", ",", "device", ":", "int", ")", "->", "torch", ".", "Tensor", ":", "if", "device", ">", "-", "1", ":", "return", "torch", ".", "cuda", ".", "LongTensor", "(", "size", ",", "device", "=", "device", ...
648a36f77db7e45784c047176074f98534c76636
train
bucket_values
Places the given values (designed for distances) into ``num_total_buckets``semi-logscale buckets, with ``num_identity_buckets`` of these capturing single values. The default settings will bucket values into the following buckets: [0, 1, 2, 3, 4, 5-7, 8-15, 16-31, 32-63, 64+]. Parameters ----------...
allennlp/nn/util.py
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...
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...
[ "Places", "the", "given", "values", "(", "designed", "for", "distances", ")", "into", "num_total_buckets", "semi", "-", "logscale", "buckets", "with", "num_identity_buckets", "of", "these", "capturing", "single", "values", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/nn/util.py#L1095-L1132
[ "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 ...
648a36f77db7e45784c047176074f98534c76636
train
add_sentence_boundary_token_ids
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. Returns both the new tens...
allennlp/nn/util.py
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...
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...
[ "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", ...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/nn/util.py#L1135-L1189
[ "def", "add_sentence_boundary_token_ids", "(", "tensor", ":", "torch", ".", "Tensor", ",", "mask", ":", "torch", ".", "Tensor", ",", "sentence_begin_token", ":", "Any", ",", "sentence_end_token", ":", "Any", ")", "->", "Tuple", "[", "torch", ".", "Tensor", "...
648a36f77db7e45784c047176074f98534c76636
train
remove_sentence_boundaries
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...
allennlp/nn/util.py
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...
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...
[ "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", "sh...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/nn/util.py#L1192-L1232
[ "def", "remove_sentence_boundaries", "(", "tensor", ":", "torch", ".", "Tensor", ",", "mask", ":", "torch", ".", "Tensor", ")", "->", "Tuple", "[", "torch", ".", "Tensor", ",", "torch", ".", "Tensor", "]", ":", "# TODO: matthewp, profile this transfer", "seque...
648a36f77db7e45784c047176074f98534c76636
train
add_positional_features
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>`_ . Adds sinusoids of different frequencies to a ``Tensor``. A sinusoid of a different fr...
allennlp/nn/util.py
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:/...
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:/...
[ "Implements", "the", "frequency", "-", "based", "positional", "encoding", "described", "in", "Attention", "is", "all", "you", "Need", "<https", ":", "//", "www", ".", "semanticscholar", ".", "org", "/", "paper", "/", "Attention", "-", "Is", "-", "All", "-"...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/nn/util.py#L1235-L1286
[ "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",...
648a36f77db7e45784c047176074f98534c76636
train
clone
Produce N identical layers.
allennlp/nn/util.py
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)])
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)])
[ "Produce", "N", "identical", "layers", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/nn/util.py#L1289-L1291
[ "def", "clone", "(", "module", ":", "torch", ".", "nn", ".", "Module", ",", "num_copies", ":", "int", ")", "->", "torch", ".", "nn", ".", "ModuleList", ":", "return", "torch", ".", "nn", ".", "ModuleList", "(", "[", "copy", ".", "deepcopy", "(", "m...
648a36f77db7e45784c047176074f98534c76636
train
combine_initial_dims
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.
allennlp/nn/util.py
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: ...
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", "(", "possibly", "higher", "order", ")", "tensor", "of", "ids", "with", "shape", "(", "d1", "...", "dn", "sequence_length", ")", "Return", "a", "view", "that", "s", "(", "d1", "*", "...", "*", "dn", "sequence_length", ")", ".", "If", "o...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/nn/util.py#L1294-L1304
[ "def", "combine_initial_dims", "(", "tensor", ":", "torch", ".", "Tensor", ")", "->", "torch", ".", "Tensor", ":", "if", "tensor", ".", "dim", "(", ")", "<=", "2", ":", "return", "tensor", "else", ":", "return", "tensor", ".", "view", "(", "-", "1", ...
648a36f77db7e45784c047176074f98534c76636
train
uncombine_initial_dims
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.
allennlp/nn/util.py
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 ...
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 ...
[ "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", ...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/nn/util.py#L1307-L1321
[ "def", "uncombine_initial_dims", "(", "tensor", ":", "torch", ".", "Tensor", ",", "original_size", ":", "torch", ".", "Size", ")", "->", "torch", ".", "Tensor", ":", "if", "len", "(", "original_size", ")", "<=", "2", ":", "return", "tensor", "else", ":",...
648a36f77db7e45784c047176074f98534c76636
train
TableQuestionContext._string_in_table
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.
allennlp/semparse/contexts/table_question_context.py
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...
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...
[ "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", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/contexts/table_question_context.py#L342-L357
[ "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", "i...
648a36f77db7e45784c047176074f98534c76636
train
TableQuestionContext.normalize_string
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 canoni...
allennlp/semparse/contexts/table_question_context.py
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``. ...
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``. ...
[ "These", "are", "the", "transformation", "rules", "used", "to", "normalize", "cell", "in", "column", "names", "in", "Sempre", ".", "See", "edu", ".", "stanford", ".", "nlp", ".", "sempre", ".", "tables", ".", "StringNormalizationUtils", ".", "characterNormaliz...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/contexts/table_question_context.py#L400-L437
[ "def", "normalize_string", "(", "string", ":", "str", ")", "->", "str", ":", "# Normalization rules from Sempre", "# \\u201A -> ,", "string", "=", "re", ".", "sub", "(", "\"‚\", ", "\"", "\", ", "s", "ring)", "", "string", "=", "re", ".", "sub", "(", "\"„\...
648a36f77db7e45784c047176074f98534c76636
train
lisp_to_nested_expression
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']].
allennlp/semparse/util.py
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 = [...
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 = [...
[ "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...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/util.py#L4-L23
[ "def", "lisp_to_nested_expression", "(", "lisp_string", ":", "str", ")", "->", "List", ":", "stack", ":", "List", "=", "[", "]", "current_expression", ":", "List", "=", "[", "]", "tokens", "=", "lisp_string", ".", "split", "(", ")", "for", "token", "in",...
648a36f77db7e45784c047176074f98534c76636
train
ElmoEmbedder.batch_to_embeddings
Parameters ---------- batch : ``List[List[str]]``, required A list of tokenized sentences. Returns ------- A tuple of tensors, the first representing activations (batch_size, 3, num_timesteps, 1024) and the second a mask (batch_size, num_timesteps).
allennlp/commands/elmo.py
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...
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...
[ "Parameters", "----------", "batch", ":", "List", "[", "List", "[", "str", "]]", "required", "A", "list", "of", "tokenized", "sentences", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/commands/elmo.py#L171-L201
[ "def", "batch_to_embeddings", "(", "self", ",", "batch", ":", "List", "[", "List", "[", "str", "]", "]", ")", "->", "Tuple", "[", "torch", ".", "Tensor", ",", "torch", ".", "Tensor", "]", ":", "character_ids", "=", "batch_to_ids", "(", "batch", ")", ...
648a36f77db7e45784c047176074f98534c76636
train
ElmoEmbedder.embed_sentence
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 ---------- sentence : ``List[str]``, required A tokenize...
allennlp/commands/elmo.py
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 ...
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", "single", "tokenized", "sentence", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/commands/elmo.py#L203-L220
[ "def", "embed_sentence", "(", "self", ",", "sentence", ":", "List", "[", "str", "]", ")", "->", "numpy", ".", "ndarray", ":", "return", "self", ".", "embed_batch", "(", "[", "sentence", "]", ")", "[", "0", "]" ]
648a36f77db7e45784c047176074f98534c76636
train
ElmoEmbedder.embed_batch
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. Parameters ---------- batch : ``List[List[str]]``, required A li...
allennlp/commands/elmo.py
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...
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", "batch", "of", "tokenized", "sentences", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/commands/elmo.py#L222-L254
[ "def", "embed_batch", "(", "self", ",", "batch", ":", "List", "[", "List", "[", "str", "]", "]", ")", "->", "List", "[", "numpy", ".", "ndarray", "]", ":", "elmo_embeddings", "=", "[", "]", "# Batches with only an empty sentence will throw an exception inside Al...
648a36f77db7e45784c047176074f98534c76636
train
ElmoEmbedder.embed_sentences
Computes the ELMo embeddings for a iterable of sentences. Please note that ELMo has internal state and will give different results for the same input. See the comment under the class definition. Parameters ---------- sentences : ``Iterable[List[str]]``, required An ...
allennlp/commands/elmo.py
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...
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", "the", "ELMo", "embeddings", "for", "a", "iterable", "of", "sentences", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/commands/elmo.py#L256-L277
[ "def", "embed_sentences", "(", "self", ",", "sentences", ":", "Iterable", "[", "List", "[", "str", "]", "]", ",", "batch_size", ":", "int", "=", "DEFAULT_BATCH_SIZE", ")", "->", "Iterable", "[", "numpy", ".", "ndarray", "]", ":", "for", "batch", "in", ...
648a36f77db7e45784c047176074f98534c76636
train
ElmoEmbedder.embed_file
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. Parameters ---------- ...
allennlp/commands/elmo.py
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: ...
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: ...
[ "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", ...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/commands/elmo.py#L279-L365
[ "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...
648a36f77db7e45784c047176074f98534c76636
train
Instance.add_field
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.
allennlp/data/instance.py
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]...
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]...
[ "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", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/data/instance.py#L41-L49
[ "def", "add_field", "(", "self", ",", "field_name", ":", "str", ",", "field", ":", "Field", ",", "vocab", ":", "Vocabulary", "=", "None", ")", "->", "None", ":", "self", ".", "fields", "[", "field_name", "]", "=", "field", "if", "self", ".", "indexed...
648a36f77db7e45784c047176074f98534c76636
train
Instance.count_vocab_items
Increments counts in the given ``counter`` for all of the vocabulary items in all of the ``Fields`` in this ``Instance``.
allennlp/data/instance.py
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)
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)
[ "Increments", "counts", "in", "the", "given", "counter", "for", "all", "of", "the", "vocabulary", "items", "in", "all", "of", "the", "Fields", "in", "this", "Instance", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/data/instance.py#L51-L57
[ "def", "count_vocab_items", "(", "self", ",", "counter", ":", "Dict", "[", "str", ",", "Dict", "[", "str", ",", "int", "]", "]", ")", ":", "for", "field", "in", "self", ".", "fields", ".", "values", "(", ")", ":", "field", ".", "count_vocab_items", ...
648a36f77db7e45784c047176074f98534c76636
train
Instance.index_fields
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. ...
allennlp/data/instance.py
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...
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...
[ "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",...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/data/instance.py#L59-L72
[ "def", "index_fields", "(", "self", ",", "vocab", ":", "Vocabulary", ")", "->", "None", ":", "if", "not", "self", ".", "indexed", ":", "self", ".", "indexed", "=", "True", "for", "field", "in", "self", ".", "fields", ".", "values", "(", ")", ":", "...
648a36f77db7e45784c047176074f98534c76636
train
Instance.get_padding_lengths
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.
allennlp/data/instance.py
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...
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...
[ "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", ...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/data/instance.py#L74-L82
[ "def", "get_padding_lengths", "(", "self", ")", "->", "Dict", "[", "str", ",", "Dict", "[", "str", ",", "int", "]", "]", ":", "lengths", "=", "{", "}", "for", "field_name", ",", "field", "in", "self", ".", "fields", ".", "items", "(", ")", ":", "...
648a36f77db7e45784c047176074f98534c76636
train
Instance.as_tensor_dict
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. If ``padding_lengths`` is omitted, we will call ``...
allennlp/data/instance.py
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 ...
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 ...
[ "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", ":", "fu...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/data/instance.py#L84-L98
[ "def", "as_tensor_dict", "(", "self", ",", "padding_lengths", ":", "Dict", "[", "str", ",", "Dict", "[", "str", ",", "int", "]", "]", "=", "None", ")", "->", "Dict", "[", "str", ",", "DataArray", "]", ":", "padding_lengths", "=", "padding_lengths", "or...
648a36f77db7e45784c047176074f98534c76636
train
full_name
Return the full name (including module) of the given class.
allennlp/common/configuration.py
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...
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...
[ "Return", "the", "full", "name", "(", "including", "module", ")", "of", "the", "given", "class", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/common/configuration.py#L34-L62
[ "def", "full_name", "(", "cla55", ":", "Optional", "[", "type", "]", ")", "->", "str", ":", "# Special case to handle None:", "if", "cla55", "is", "None", ":", "return", "\"?\"", "if", "issubclass", "(", "cla55", ",", "Initializer", ")", "and", "cla55", "n...
648a36f77db7e45784c047176074f98534c76636
train
_get_config_type
Find the name (if any) that a subclass was registered under. We do this simply by iterating through the registry until we find it.
allennlp/common/configuration.py
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...
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...
[ "Find", "the", "name", "(", "if", "any", ")", "that", "a", "subclass", "was", "registered", "under", ".", "We", "do", "this", "simply", "by", "iterating", "through", "the", "registry", "until", "we", "find", "it", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/common/configuration.py#L168-L193
[ "def", "_get_config_type", "(", "cla55", ":", "type", ")", "->", "Optional", "[", "str", "]", ":", "# Special handling for pytorch RNN types:", "if", "cla55", "==", "torch", ".", "nn", ".", "RNN", ":", "return", "\"rnn\"", "elif", "cla55", "==", "torch", "."...
648a36f77db7e45784c047176074f98534c76636
train
_docspec_comments
Inspect the docstring and get the comments for each parameter.
allennlp/common/configuration.py
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 ...
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 ...
[ "Inspect", "the", "docstring", "and", "get", "the", "comments", "for", "each", "parameter", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/common/configuration.py#L195-L221
[ "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__'"...
648a36f77db7e45784c047176074f98534c76636
train
_auto_config
Create the ``Config`` for a class by reflecting on its ``__init__`` method and applying a few hacks.
allennlp/common/configuration.py
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 ...
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 ...
[ "Create", "the", "Config", "for", "a", "class", "by", "reflecting", "on", "its", "__init__", "method", "and", "applying", "a", "few", "hacks", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/common/configuration.py#L223-L295
[ "def", "_auto_config", "(", "cla55", ":", "Type", "[", "T", "]", ")", "->", "Config", "[", "T", "]", ":", "typ3", "=", "_get_config_type", "(", "cla55", ")", "# Don't include self, or vocab", "names_to_ignore", "=", "{", "\"self\"", ",", "\"vocab\"", "}", ...
648a36f77db7e45784c047176074f98534c76636
train
render_config
Pretty-print a config in sort-of-JSON+comments.
allennlp/common/configuration.py
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) ...
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) ...
[ "Pretty", "-", "print", "a", "config", "in", "sort", "-", "of", "-", "JSON", "+", "comments", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/common/configuration.py#L298-L315
[ "def", "render_config", "(", "config", ":", "Config", ",", "indent", ":", "str", "=", "\"\"", ")", "->", "str", ":", "# Add four spaces to the indent.", "new_indent", "=", "indent", "+", "\" \"", "return", "\"\"", ".", "join", "(", "[", "# opening brace + n...
648a36f77db7e45784c047176074f98534c76636
train
_render
Render a single config item, with the provided indent
allennlp/common/configuration.py
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...
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...
[ "Render", "a", "single", "config", "item", "with", "the", "provided", "indent" ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/common/configuration.py#L355-L377
[ "def", "_render", "(", "item", ":", "ConfigItem", ",", "indent", ":", "str", "=", "\"\"", ")", "->", "str", ":", "optional", "=", "item", ".", "default_value", "!=", "_NO_DEFAULT", "if", "is_configurable", "(", "item", ".", "annotation", ")", ":", "rende...
648a36f77db7e45784c047176074f98534c76636
train
_valid_choices
Return a mapping {registered_name -> subclass_name} for the registered subclasses of `cla55`.
allennlp/common/configuration.py
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"...
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"...
[ "Return", "a", "mapping", "{", "registered_name", "-", ">", "subclass_name", "}", "for", "the", "registered", "subclasses", "of", "cla55", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/common/configuration.py#L427-L444
[ "def", "_valid_choices", "(", "cla55", ":", "type", ")", "->", "Dict", "[", "str", ",", "str", "]", ":", "valid_choices", ":", "Dict", "[", "str", ",", "str", "]", "=", "{", "}", "if", "cla55", "not", "in", "Registrable", ".", "_registry", ":", "ra...
648a36f77db7e45784c047176074f98534c76636
train
url_to_filename
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.
allennlp/common/file_utils.py
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...
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...
[ "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", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/common/file_utils.py#L39-L54
[ "def", "url_to_filename", "(", "url", ":", "str", ",", "etag", ":", "str", "=", "None", ")", "->", "str", ":", "url_bytes", "=", "url", ".", "encode", "(", "'utf-8'", ")", "url_hash", "=", "sha256", "(", "url_bytes", ")", "filename", "=", "url_hash", ...
648a36f77db7e45784c047176074f98534c76636
train
filename_to_url
Return the url and etag (which may be ``None``) stored for `filename`. Raise ``FileNotFoundError`` if `filename` or its stored metadata do not exist.
allennlp/common/file_utils.py
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...
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...
[ "Return", "the", "url", "and", "etag", "(", "which", "may", "be", "None", ")", "stored", "for", "filename", ".", "Raise", "FileNotFoundError", "if", "filename", "or", "its", "stored", "metadata", "do", "not", "exist", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/common/file_utils.py#L57-L78
[ "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", ...
648a36f77db7e45784c047176074f98534c76636
train
cached_path
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.
allennlp/common/file_utils.py
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...
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", "which", ".", "If", "it", "s", "a", "URL", "download", "the", "file", "and", "cache", "it", "and", "return", "the", "path", "to...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/common/file_utils.py#L81-L107
[ "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", "("...
648a36f77db7e45784c047176074f98534c76636
train
is_url_or_existing_file
Given something that might be a URL (or might be a local path), determine check if it's url or an existing file path.
allennlp/common/file_utils.py
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...
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...
[ "Given", "something", "that", "might", "be", "a", "URL", "(", "or", "might", "be", "a", "local", "path", ")", "determine", "check", "if", "it", "s", "url", "or", "an", "existing", "file", "path", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/common/file_utils.py#L109-L118
[ "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", ".", "expan...
648a36f77db7e45784c047176074f98534c76636
train
split_s3_path
Split a full s3 path into the bucket name and path.
allennlp/common/file_utils.py
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...
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...
[ "Split", "a", "full", "s3", "path", "into", "the", "bucket", "name", "and", "path", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/common/file_utils.py#L120-L130
[ "def", "split_s3_path", "(", "url", ":", "str", ")", "->", "Tuple", "[", "str", ",", "str", "]", ":", "parsed", "=", "urlparse", "(", "url", ")", "if", "not", "parsed", ".", "netloc", "or", "not", "parsed", ".", "path", ":", "raise", "ValueError", ...
648a36f77db7e45784c047176074f98534c76636
train
s3_request
Wrapper function for s3 requests in order to create more helpful error messages.
allennlp/common/file_utils.py
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...
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...
[ "Wrapper", "function", "for", "s3", "requests", "in", "order", "to", "create", "more", "helpful", "error", "messages", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/common/file_utils.py#L133-L149
[ "def", "s3_request", "(", "func", ":", "Callable", ")", ":", "@", "wraps", "(", "func", ")", "def", "wrapper", "(", "url", ":", "str", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "try", ":", "return", "func", "(", "url", ",", "*", "arg...
648a36f77db7e45784c047176074f98534c76636
train
s3_etag
Check ETag on S3 object.
allennlp/common/file_utils.py
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
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
[ "Check", "ETag", "on", "S3", "object", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/common/file_utils.py#L153-L158
[ "def", "s3_etag", "(", "url", ":", "str", ")", "->", "Optional", "[", "str", "]", ":", "s3_resource", "=", "boto3", ".", "resource", "(", "\"s3\"", ")", "bucket_name", ",", "s3_path", "=", "split_s3_path", "(", "url", ")", "s3_object", "=", "s3_resource"...
648a36f77db7e45784c047176074f98534c76636
train
s3_get
Pull a file directly from S3.
allennlp/common/file_utils.py
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)
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)
[ "Pull", "a", "file", "directly", "from", "S3", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/common/file_utils.py#L162-L166
[ "def", "s3_get", "(", "url", ":", "str", ",", "temp_file", ":", "IO", ")", "->", "None", ":", "s3_resource", "=", "boto3", ".", "resource", "(", "\"s3\"", ")", "bucket_name", ",", "s3_path", "=", "split_s3_path", "(", "url", ")", "s3_resource", ".", "B...
648a36f77db7e45784c047176074f98534c76636
train
get_from_cache
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.
allennlp/common/file_utils.py
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...
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...
[ "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", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/common/file_utils.py#L182-L236
[ "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", "=", ...
648a36f77db7e45784c047176074f98534c76636
train
read_set_from_file
Extract a de-duped collection (set) of text from a file. Expected file format is one item per line.
allennlp/common/file_utils.py
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...
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...
[ "Extract", "a", "de", "-", "duped", "collection", "(", "set", ")", "of", "text", "from", "a", "file", ".", "Expected", "file", "format", "is", "one", "item", "per", "line", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/common/file_utils.py#L239-L248
[ "def", "read_set_from_file", "(", "filename", ":", "str", ")", "->", "Set", "[", "str", "]", ":", "collection", "=", "set", "(", ")", "with", "open", "(", "filename", ",", "'r'", ")", "as", "file_", ":", "for", "line", "in", "file_", ":", "collection...
648a36f77db7e45784c047176074f98534c76636
train
main
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_id}}.json`` for datasets which use cross validation. ...
scripts/reformat_text2sql_data.py
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...
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...
[ "Processes", "the", "text2sql", "data", "into", "the", "following", "directory", "structure", ":" ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/scripts/reformat_text2sql_data.py#L38-L91
[ "def", "main", "(", "output_directory", ":", "int", ",", "data", ":", "str", ")", "->", "None", ":", "json_files", "=", "glob", ".", "glob", "(", "os", ".", "path", ".", "join", "(", "data", ",", "\"*.json\"", ")", ")", "for", "dataset", "in", "jso...
648a36f77db7e45784c047176074f98534c76636
train
ResidualWithLayerDropout.forward
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. Parameters ---------- layer_input ``torch.FloatTensor`` re...
allennlp/modules/residual_with_layer_dropout.py
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...
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...
[ "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...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/modules/residual_with_layer_dropout.py#L21-L59
[ "def", "forward", "(", "self", ",", "layer_input", ":", "torch", ".", "Tensor", ",", "layer_output", ":", "torch", ".", "Tensor", ",", "layer_index", ":", "int", "=", "None", ",", "total_layers", ":", "int", "=", "None", ")", "->", "torch", ".", "Tenso...
648a36f77db7e45784c047176074f98534c76636
train
ArgExtremeType.resolve
See ``PlaceholderType.resolve``
allennlp/semparse/type_declarations/wikitables_lambda_dcs.py
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_...
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" ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/type_declarations/wikitables_lambda_dcs.py#L83-L123
[ "def", "resolve", "(", "self", ",", "other", ":", "Type", ")", "->", "Optional", "[", "Type", "]", ":", "if", "not", "isinstance", "(", "other", ",", "NltkComplexType", ")", ":", "return", "None", "expected_second", "=", "ComplexType", "(", "NUMBER_TYPE", ...
648a36f77db7e45784c047176074f98534c76636
train
CountType.resolve
See ``PlaceholderType.resolve``
allennlp/semparse/type_declarations/wikitables_lambda_dcs.py
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)
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)
[ "See", "PlaceholderType", ".", "resolve" ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/type_declarations/wikitables_lambda_dcs.py#L149-L156
[ "def", "resolve", "(", "self", ",", "other", ":", "Type", ")", "->", "Type", ":", "if", "not", "isinstance", "(", "other", ",", "NltkComplexType", ")", ":", "return", "None", "resolved_second", "=", "NUMBER_TYPE", ".", "resolve", "(", "other", ".", "seco...
648a36f77db7e45784c047176074f98534c76636
train
process_data
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, "...
scripts/nlvr/get_nlvr_logical_forms.py
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...
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...
[ "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", "f...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/scripts/nlvr/get_nlvr_logical_forms.py#L32-L104
[ "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", ":"...
648a36f77db7e45784c047176074f98534c76636
train
SentenceSplitter.batch_split_sentences
This method lets you take advantage of spacy's batch processing. Default implementation is to just iterate over the texts and call ``split_sentences``.
allennlp/data/tokenizers/sentence_splitter.py
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...
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...
[ "This", "method", "lets", "you", "take", "advantage", "of", "spacy", "s", "batch", "processing", ".", "Default", "implementation", "is", "to", "just", "iterate", "over", "the", "texts", "and", "call", "split_sentences", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/data/tokenizers/sentence_splitter.py#L22-L27
[ "def", "batch_split_sentences", "(", "self", ",", "texts", ":", "List", "[", "str", "]", ")", "->", "List", "[", "List", "[", "str", "]", "]", ":", "return", "[", "self", ".", "split_sentences", "(", "text", ")", "for", "text", "in", "texts", "]" ]
648a36f77db7e45784c047176074f98534c76636
train
Ontonotes.dataset_iterator
An iterator over the entire dataset, yielding all sentences processed.
allennlp/data/dataset_readers/dataset_utils/ontonotes.py
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)
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", "over", "the", "entire", "dataset", "yielding", "all", "sentences", "processed", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/data/dataset_readers/dataset_utils/ontonotes.py#L176-L181
[ "def", "dataset_iterator", "(", "self", ",", "file_path", ":", "str", ")", "->", "Iterator", "[", "OntonotesSentence", "]", ":", "for", "conll_file", "in", "self", ".", "dataset_path_iterator", "(", "file_path", ")", ":", "yield", "from", "self", ".", "sente...
648a36f77db7e45784c047176074f98534c76636
train
Ontonotes.dataset_path_iterator
An iterator returning file_paths in a directory containing CONLL-formatted files.
allennlp/data/dataset_readers/dataset_utils/ontonotes.py
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))...
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", "returning", "file_paths", "in", "a", "directory", "containing", "CONLL", "-", "formatted", "files", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/data/dataset_readers/dataset_utils/ontonotes.py#L184-L198
[ "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", ...
648a36f77db7e45784c047176074f98534c76636
train
Ontonotes.dataset_document_iterator
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.
allennlp/data/dataset_readers/dataset_utils/ontonotes.py
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...
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", "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",...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/data/dataset_readers/dataset_utils/ontonotes.py#L200-L225
[ "def", "dataset_document_iterator", "(", "self", ",", "file_path", ":", "str", ")", "->", "Iterator", "[", "List", "[", "OntonotesSentence", "]", "]", ":", "with", "codecs", ".", "open", "(", "file_path", ",", "'r'", ",", "encoding", "=", "'utf8'", ")", ...
648a36f77db7e45784c047176074f98534c76636
train
Ontonotes.sentence_iterator
An iterator over the sentences in an individual CONLL formatted file.
allennlp/data/dataset_readers/dataset_utils/ontonotes.py
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
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
[ "An", "iterator", "over", "the", "sentences", "in", "an", "individual", "CONLL", "formatted", "file", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/data/dataset_readers/dataset_utils/ontonotes.py#L227-L233
[ "def", "sentence_iterator", "(", "self", ",", "file_path", ":", "str", ")", "->", "Iterator", "[", "OntonotesSentence", "]", ":", "for", "document", "in", "self", ".", "dataset_document_iterator", "(", "file_path", ")", ":", "for", "sentence", "in", "document"...
648a36f77db7e45784c047176074f98534c76636
train
Ontonotes._process_coref_span_annotations_for_word
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. Parameters ---------- label : ``str`` The coref label for this word. w...
allennlp/data/dataset_readers/dataset_utils/ontonotes.py
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...
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...
[ "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", "muta...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/data/dataset_readers/dataset_utils/ontonotes.py#L362-L408
[ "def", "_process_coref_span_annotations_for_word", "(", "label", ":", "str", ",", "word_index", ":", "int", ",", "clusters", ":", "DefaultDict", "[", "int", ",", "List", "[", "Tuple", "[", "int", ",", "int", "]", "]", "]", ",", "coref_stacks", ":", "Defaul...
648a36f77db7e45784c047176074f98534c76636
train
Ontonotes._process_span_annotations_for_word
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. Parameters ---------- annotations: ``List[str]`` A list of labels to compute BIO tags for. span_labels : ``L...
allennlp/data/dataset_readers/dataset_utils/ontonotes.py
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...
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...
[ "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", "." ...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/data/dataset_readers/dataset_utils/ontonotes.py#L411-L449
[ "def", "_process_span_annotations_for_word", "(", "annotations", ":", "List", "[", "str", "]", ",", "span_labels", ":", "List", "[", "List", "[", "str", "]", "]", ",", "current_span_labels", ":", "List", "[", "Optional", "[", "str", "]", "]", ")", "->", ...
648a36f77db7e45784c047176074f98534c76636
train
print_results_from_args
Prints results from an ``argparse.Namespace`` object.
allennlp/commands/print_results.py
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: ...
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: ...
[ "Prints", "results", "from", "an", "argparse", ".", "Namespace", "object", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/commands/print_results.py#L66-L88
[ "def", "print_results_from_args", "(", "args", ":", "argparse", ".", "Namespace", ")", ":", "path", "=", "args", ".", "path", "metrics_name", "=", "args", ".", "metrics_filename", "keys", "=", "args", ".", "keys", "results_dict", "=", "{", "}", "for", "roo...
648a36f77db7e45784c047176074f98534c76636
train
InputVariationalDropout.forward
Apply dropout to input tensor. Parameters ---------- input_tensor: ``torch.FloatTensor`` A tensor of shape ``(batch_size, num_timesteps, embedding_dim)`` Returns ------- output: ``torch.FloatTensor`` A tensor of shape ``(batch_size, num_timesteps...
allennlp/modules/input_variational_dropout.py
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 ------- ...
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 ------- ...
[ "Apply", "dropout", "to", "input", "tensor", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/modules/input_variational_dropout.py#L13-L34
[ "def", "forward", "(", "self", ",", "input_tensor", ")", ":", "# pylint: disable=arguments-differ", "ones", "=", "input_tensor", ".", "data", ".", "new_ones", "(", "input_tensor", ".", "shape", "[", "0", "]", ",", "input_tensor", ".", "shape", "[", "-", "1",...
648a36f77db7e45784c047176074f98534c76636
train
Metric.get_metric
Compute and return the metric. Optionally also call :func:`self.reset`.
allennlp/training/metrics/metric.py
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
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
[ "Compute", "and", "return", "the", "metric", ".", "Optionally", "also", "call", ":", "func", ":", "self", ".", "reset", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/training/metrics/metric.py#L29-L33
[ "def", "get_metric", "(", "self", ",", "reset", ":", "bool", ")", "->", "Union", "[", "float", ",", "Tuple", "[", "float", ",", "...", "]", ",", "Dict", "[", "str", ",", "float", "]", ",", "Dict", "[", "str", ",", "List", "[", "float", "]", "]"...
648a36f77db7e45784c047176074f98534c76636
train
Metric.unwrap_to_tensors
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.
allennlp/training/metrics/metric.py
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...
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...
[ "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", ".", "Thi...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/training/metrics/metric.py#L42-L49
[ "def", "unwrap_to_tensors", "(", "*", "tensors", ":", "torch", ".", "Tensor", ")", ":", "return", "(", "x", ".", "detach", "(", ")", ".", "cpu", "(", ")", "if", "isinstance", "(", "x", ",", "torch", ".", "Tensor", ")", "else", "x", "for", "x", "i...
648a36f77db7e45784c047176074f98534c76636
train
replace_variables
Replaces abstract variables in text with their concrete counterparts.
allennlp/data/dataset_readers/dataset_utils/text2sql_utils.py
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...
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...
[ "Replaces", "abstract", "variables", "in", "text", "with", "their", "concrete", "counterparts", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/data/dataset_readers/dataset_utils/text2sql_utils.py#L65-L80
[ "def", "replace_variables", "(", "sentence", ":", "List", "[", "str", "]", ",", "sentence_variables", ":", "Dict", "[", "str", ",", "str", "]", ")", "->", "Tuple", "[", "List", "[", "str", "]", ",", "List", "[", "str", "]", "]", ":", "tokens", "=",...
648a36f77db7e45784c047176074f98534c76636
train
clean_and_split_sql
Cleans up and unifies a SQL query. This involves unifying quoted strings and splitting brackets which aren't formatted consistently in the data.
allennlp/data/dataset_readers/dataset_utils/text2sql_utils.py
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('"',...
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('"',...
[ "Cleans", "up", "and", "unifies", "a", "SQL", "query", ".", "This", "involves", "unifying", "quoted", "strings", "and", "splitting", "brackets", "which", "aren", "t", "formatted", "consistently", "in", "the", "data", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/data/dataset_readers/dataset_utils/text2sql_utils.py#L89-L102
[ "def", "clean_and_split_sql", "(", "sql", ":", "str", ")", "->", "List", "[", "str", "]", ":", "sql_tokens", ":", "List", "[", "str", "]", "=", "[", "]", "for", "token", "in", "sql", ".", "strip", "(", ")", ".", "split", "(", ")", ":", "token", ...
648a36f77db7e45784c047176074f98534c76636
train
resolve_primary_keys_in_schema
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 re...
allennlp/data/dataset_readers/dataset_utils/text2sql_utils.py
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 ...
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 ...
[ "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...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/data/dataset_readers/dataset_utils/text2sql_utils.py#L104-L121
[ "def", "resolve_primary_keys_in_schema", "(", "sql_tokens", ":", "List", "[", "str", "]", ",", "schema", ":", "Dict", "[", "str", ",", "List", "[", "TableColumn", "]", "]", ")", "->", "List", "[", "str", "]", ":", "primary_keys_for_tables", "=", "{", "na...
648a36f77db7e45784c047176074f98534c76636
train
read_dataset_schema
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 a...
allennlp/data/dataset_readers/dataset_utils/text2sql_utils.py
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...
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...
[ "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", ...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/data/dataset_readers/dataset_utils/text2sql_utils.py#L152-L184
[ "def", "read_dataset_schema", "(", "schema_path", ":", "str", ")", "->", "Dict", "[", "str", ",", "List", "[", "TableColumn", "]", "]", ":", "schema", ":", "Dict", "[", "str", ",", "List", "[", "TableColumn", "]", "]", "=", "defaultdict", "(", "list", ...
648a36f77db7e45784c047176074f98534c76636
train
process_sql_data
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``. Parameters ---------- data : ``JsonDict`` use_all_sql : ``bool``, optional (default = False) Whether to use all of the sq...
allennlp/data/dataset_readers/dataset_utils/text2sql_utils.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...
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...
[ "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", ...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/data/dataset_readers/dataset_utils/text2sql_utils.py#L187-L258
[ "def", "process_sql_data", "(", "data", ":", "List", "[", "JsonDict", "]", ",", "use_all_sql", ":", "bool", "=", "False", ",", "use_all_queries", ":", "bool", "=", "False", ",", "remove_unneeded_aliases", ":", "bool", "=", "False", ",", "schema", ":", "Dic...
648a36f77db7e45784c047176074f98534c76636
train
_EncoderBase.sort_and_run_forward
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_st...
allennlp/modules/encoder_base.py
def sort_and_run_forward(self, module: Callable[[PackedSequence, Optional[RnnState]], Tuple[Union[PackedSequence, torch.Tensor], RnnState]], inputs: torch.Tensor, mask: torch.Tensor, ...
def sort_and_run_forward(self, module: Callable[[PackedSequence, Optional[RnnState]], Tuple[Union[PackedSequence, torch.Tensor], RnnState]], inputs: torch.Tensor, mask: torch.Tensor, ...
[ "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", "provide...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/modules/encoder_base.py#L32-L118
[ "def", "sort_and_run_forward", "(", "self", ",", "module", ":", "Callable", "[", "[", "PackedSequence", ",", "Optional", "[", "RnnState", "]", "]", ",", "Tuple", "[", "Union", "[", "PackedSequence", ",", "torch", ".", "Tensor", "]", ",", "RnnState", "]", ...
648a36f77db7e45784c047176074f98534c76636
train
_EncoderBase._get_initial_states
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 bat...
allennlp/modules/encoder_base.py
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...
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...
[ "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"...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/modules/encoder_base.py#L120-L205
[ "def", "_get_initial_states", "(", "self", ",", "batch_size", ":", "int", ",", "num_valid", ":", "int", ",", "sorting_indices", ":", "torch", ".", "LongTensor", ")", "->", "Optional", "[", "RnnState", "]", ":", "# We don't know the state sizes the first time calling...
648a36f77db7e45784c047176074f98534c76636
train
_EncoderBase._update_states
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. Fina...
allennlp/modules/encoder_base.py
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...
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...
[ "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", ...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/modules/encoder_base.py#L207-L282
[ "def", "_update_states", "(", "self", ",", "final_states", ":", "RnnStateStorage", ",", "restoration_indices", ":", "torch", ".", "LongTensor", ")", "->", "None", ":", "# TODO(Mark): seems weird to sort here, but append zeros in the subclasses.", "# which way around is best?", ...
648a36f77db7e45784c047176074f98534c76636
train
construct_prefix_tree
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 val...
allennlp/state_machines/util.py
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 ...
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 ...
[ "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", ...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/state_machines/util.py#L7-L47
[ "def", "construct_prefix_tree", "(", "targets", ":", "Union", "[", "torch", ".", "Tensor", ",", "List", "[", "List", "[", "List", "[", "int", "]", "]", "]", "]", ",", "target_mask", ":", "Optional", "[", "torch", ".", "Tensor", "]", "=", "None", ")",...
648a36f77db7e45784c047176074f98534c76636
train
to_value
Convert the string to Value object. Args: original_string (basestring): Original string corenlp_value (basestring): Optional value returned from CoreNLP Returns: Value
allennlp/tools/wikitables_evaluator.py
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): # ...
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): # ...
[ "Convert", "the", "string", "to", "Value", "object", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/tools/wikitables_evaluator.py#L252-L278
[ "def", "to_value", "(", "original_string", ",", "corenlp_value", "=", "None", ")", ":", "if", "isinstance", "(", "original_string", ",", "Value", ")", ":", "# Already a Value", "return", "original_string", "if", "not", "corenlp_value", ":", "corenlp_value", "=", ...
648a36f77db7e45784c047176074f98534c76636