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
to_value_list
Convert a list of strings to a list of Values Args: original_strings (list[basestring]) corenlp_values (list[basestring or None]) Returns: list[Value]
allennlp/tools/wikitables_evaluator.py
def to_value_list(original_strings, corenlp_values=None): """Convert a list of strings to a list of Values Args: original_strings (list[basestring]) corenlp_values (list[basestring or None]) Returns: list[Value] """ assert isinstance(original_strings, (list, tuple, set)) ...
def to_value_list(original_strings, corenlp_values=None): """Convert a list of strings to a list of Values Args: original_strings (list[basestring]) corenlp_values (list[basestring or None]) Returns: list[Value] """ assert isinstance(original_strings, (list, tuple, set)) ...
[ "Convert", "a", "list", "of", "strings", "to", "a", "list", "of", "Values" ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/tools/wikitables_evaluator.py#L280-L296
[ "def", "to_value_list", "(", "original_strings", ",", "corenlp_values", "=", "None", ")", ":", "assert", "isinstance", "(", "original_strings", ",", "(", "list", ",", "tuple", ",", "set", ")", ")", "if", "corenlp_values", "is", "not", "None", ":", "assert", ...
648a36f77db7e45784c047176074f98534c76636
train
check_denotation
Return True if the predicted denotation is correct. Args: target_values (list[Value]) predicted_values (list[Value]) Returns: bool
allennlp/tools/wikitables_evaluator.py
def check_denotation(target_values, predicted_values): """Return True if the predicted denotation is correct. Args: target_values (list[Value]) predicted_values (list[Value]) Returns: bool """ # Check size if len(target_values) != len(predicted_values): return Fa...
def check_denotation(target_values, predicted_values): """Return True if the predicted denotation is correct. Args: target_values (list[Value]) predicted_values (list[Value]) Returns: bool """ # Check size if len(target_values) != len(predicted_values): return Fa...
[ "Return", "True", "if", "the", "predicted", "denotation", "is", "correct", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/tools/wikitables_evaluator.py#L301-L317
[ "def", "check_denotation", "(", "target_values", ",", "predicted_values", ")", ":", "# Check size", "if", "len", "(", "target_values", ")", "!=", "len", "(", "predicted_values", ")", ":", "return", "False", "# Check items", "for", "target", "in", "target_values", ...
648a36f77db7e45784c047176074f98534c76636
train
NumberValue.parse
Try to parse into a number. Return: the number (int or float) if successful; otherwise None.
allennlp/tools/wikitables_evaluator.py
def parse(text): """Try to parse into a number. Return: the number (int or float) if successful; otherwise None. """ try: return int(text) except ValueError: try: amount = float(text) assert not isnan(amount) an...
def parse(text): """Try to parse into a number. Return: the number (int or float) if successful; otherwise None. """ try: return int(text) except ValueError: try: amount = float(text) assert not isnan(amount) an...
[ "Try", "to", "parse", "into", "a", "number", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/tools/wikitables_evaluator.py#L169-L183
[ "def", "parse", "(", "text", ")", ":", "try", ":", "return", "int", "(", "text", ")", "except", "ValueError", ":", "try", ":", "amount", "=", "float", "(", "text", ")", "assert", "not", "isnan", "(", "amount", ")", "and", "not", "isinf", "(", "amou...
648a36f77db7e45784c047176074f98534c76636
train
DateValue.parse
Try to parse into a date. Return: tuple (year, month, date) if successful; otherwise None.
allennlp/tools/wikitables_evaluator.py
def parse(text): """Try to parse into a date. Return: tuple (year, month, date) if successful; otherwise None. """ try: ymd = text.lower().split('-') assert len(ymd) == 3 year = -1 if ymd[0] in ('xx', 'xxxx') else int(ymd[0]) m...
def parse(text): """Try to parse into a date. Return: tuple (year, month, date) if successful; otherwise None. """ try: ymd = text.lower().split('-') assert len(ymd) == 3 year = -1 if ymd[0] in ('xx', 'xxxx') else int(ymd[0]) m...
[ "Try", "to", "parse", "into", "a", "date", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/tools/wikitables_evaluator.py#L230-L247
[ "def", "parse", "(", "text", ")", ":", "try", ":", "ymd", "=", "text", ".", "lower", "(", ")", ".", "split", "(", "'-'", ")", "assert", "len", "(", "ymd", ")", "==", "3", "year", "=", "-", "1", "if", "ymd", "[", "0", "]", "in", "(", "'xx'",...
648a36f77db7e45784c047176074f98534c76636
train
SpanExtractor.forward
Given a sequence tensor, extract spans and return representations of them. Span representation can be computed in many different ways, such as concatenation of the start and end spans, attention over the vectors contained inside the span, etc. Parameters ---------- seque...
allennlp/modules/span_extractors/span_extractor.py
def forward(self, # pylint: disable=arguments-differ sequence_tensor: torch.FloatTensor, span_indices: torch.LongTensor, sequence_mask: torch.LongTensor = None, span_indices_mask: torch.LongTensor = None): """ Given a sequence tensor, extra...
def forward(self, # pylint: disable=arguments-differ sequence_tensor: torch.FloatTensor, span_indices: torch.LongTensor, sequence_mask: torch.LongTensor = None, span_indices_mask: torch.LongTensor = None): """ Given a sequence tensor, extra...
[ "Given", "a", "sequence", "tensor", "extract", "spans", "and", "return", "representations", "of", "them", ".", "Span", "representation", "can", "be", "computed", "in", "many", "different", "ways", "such", "as", "concatenation", "of", "the", "start", "and", "en...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/modules/span_extractors/span_extractor.py#L19-L53
[ "def", "forward", "(", "self", ",", "# pylint: disable=arguments-differ", "sequence_tensor", ":", "torch", ".", "FloatTensor", ",", "span_indices", ":", "torch", ".", "LongTensor", ",", "sequence_mask", ":", "torch", ".", "LongTensor", "=", "None", ",", "span_indi...
648a36f77db7e45784c047176074f98534c76636
train
main
serialization_directory : str, required. The directory containing the serialized weights. device: int, default = -1 The device to run the evaluation on. data: str, default = None The data to evaluate on. By default, we use the validation data from the original experiment. pre...
scripts/write_srl_predictions_to_conll_format.py
def main(serialization_directory: int, device: int, data: str, prefix: str, domain: str = None): """ serialization_directory : str, required. The directory containing the serialized weights. device: int, default = -1 The device to run the evaluation on. ...
def main(serialization_directory: int, device: int, data: str, prefix: str, domain: str = None): """ serialization_directory : str, required. The directory containing the serialized weights. device: int, default = -1 The device to run the evaluation on. ...
[ "serialization_directory", ":", "str", "required", ".", "The", "directory", "containing", "the", "serialized", "weights", ".", "device", ":", "int", "default", "=", "-", "1", "The", "device", "to", "run", "the", "evaluation", "on", ".", "data", ":", "str", ...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/scripts/write_srl_predictions_to_conll_format.py#L18-L90
[ "def", "main", "(", "serialization_directory", ":", "int", ",", "device", ":", "int", ",", "data", ":", "str", ",", "prefix", ":", "str", ",", "domain", ":", "str", "=", "None", ")", ":", "config", "=", "Params", ".", "from_file", "(", "os", ".", "...
648a36f77db7e45784c047176074f98534c76636
train
DecoderTrainer.decode
Takes an initial state object, a means of transitioning from state to state, and a supervision signal, and uses the supervision to train the transition function to pick "good" states. This function should typically return a ``loss`` key during training, which the ``Model`` will use as i...
allennlp/state_machines/trainers/decoder_trainer.py
def decode(self, initial_state: State, transition_function: TransitionFunction, supervision: SupervisionType) -> Dict[str, torch.Tensor]: """ Takes an initial state object, a means of transitioning from state to state, and a supervision signal, and us...
def decode(self, initial_state: State, transition_function: TransitionFunction, supervision: SupervisionType) -> Dict[str, torch.Tensor]: """ Takes an initial state object, a means of transitioning from state to state, and a supervision signal, and us...
[ "Takes", "an", "initial", "state", "object", "a", "means", "of", "transitioning", "from", "state", "to", "state", "and", "a", "supervision", "signal", "and", "uses", "the", "supervision", "to", "train", "the", "transition", "function", "to", "pick", "good", ...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/state_machines/trainers/decoder_trainer.py#L24-L52
[ "def", "decode", "(", "self", ",", "initial_state", ":", "State", ",", "transition_function", ":", "TransitionFunction", ",", "supervision", ":", "SupervisionType", ")", "->", "Dict", "[", "str", ",", "torch", ".", "Tensor", "]", ":", "raise", "NotImplementedE...
648a36f77db7e45784c047176074f98534c76636
train
Scheduler.state_dict
Returns the state of the scheduler as a ``dict``.
allennlp/training/scheduler.py
def state_dict(self) -> Dict[str, Any]: """ Returns the state of the scheduler as a ``dict``. """ return {key: value for key, value in self.__dict__.items() if key != 'optimizer'}
def state_dict(self) -> Dict[str, Any]: """ Returns the state of the scheduler as a ``dict``. """ return {key: value for key, value in self.__dict__.items() if key != 'optimizer'}
[ "Returns", "the", "state", "of", "the", "scheduler", "as", "a", "dict", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/training/scheduler.py#L49-L53
[ "def", "state_dict", "(", "self", ")", "->", "Dict", "[", "str", ",", "Any", "]", ":", "return", "{", "key", ":", "value", "for", "key", ",", "value", "in", "self", ".", "__dict__", ".", "items", "(", ")", "if", "key", "!=", "'optimizer'", "}" ]
648a36f77db7e45784c047176074f98534c76636
train
Scheduler.load_state_dict
Load the schedulers state. Parameters ---------- state_dict : ``Dict[str, Any]`` Scheduler state. Should be an object returned from a call to ``state_dict``.
allennlp/training/scheduler.py
def load_state_dict(self, state_dict: Dict[str, Any]) -> None: """ Load the schedulers state. Parameters ---------- state_dict : ``Dict[str, Any]`` Scheduler state. Should be an object returned from a call to ``state_dict``. """ self.__dict__.update(s...
def load_state_dict(self, state_dict: Dict[str, Any]) -> None: """ Load the schedulers state. Parameters ---------- state_dict : ``Dict[str, Any]`` Scheduler state. Should be an object returned from a call to ``state_dict``. """ self.__dict__.update(s...
[ "Load", "the", "schedulers", "state", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/training/scheduler.py#L55-L64
[ "def", "load_state_dict", "(", "self", ",", "state_dict", ":", "Dict", "[", "str", ",", "Any", "]", ")", "->", "None", ":", "self", ".", "__dict__", ".", "update", "(", "state_dict", ")" ]
648a36f77db7e45784c047176074f98534c76636
train
TextFieldEmbedder.forward
Parameters ---------- text_field_input : ``Dict[str, torch.Tensor]`` A dictionary that was the output of a call to ``TextField.as_tensor``. Each tensor in here is assumed to have a shape roughly similar to ``(batch_size, sequence_length)`` (perhaps with an extra trai...
allennlp/modules/text_field_embedders/text_field_embedder.py
def forward(self, # pylint: disable=arguments-differ text_field_input: Dict[str, torch.Tensor], num_wrapping_dims: int = 0) -> torch.Tensor: """ Parameters ---------- text_field_input : ``Dict[str, torch.Tensor]`` A dictionary that was the out...
def forward(self, # pylint: disable=arguments-differ text_field_input: Dict[str, torch.Tensor], num_wrapping_dims: int = 0) -> torch.Tensor: """ Parameters ---------- text_field_input : ``Dict[str, torch.Tensor]`` A dictionary that was the out...
[ "Parameters", "----------", "text_field_input", ":", "Dict", "[", "str", "torch", ".", "Tensor", "]", "A", "dictionary", "that", "was", "the", "output", "of", "a", "call", "to", "TextField", ".", "as_tensor", ".", "Each", "tensor", "in", "here", "is", "ass...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/modules/text_field_embedders/text_field_embedder.py#L26-L42
[ "def", "forward", "(", "self", ",", "# pylint: disable=arguments-differ", "text_field_input", ":", "Dict", "[", "str", ",", "torch", ".", "Tensor", "]", ",", "num_wrapping_dims", ":", "int", "=", "0", ")", "->", "torch", ".", "Tensor", ":", "raise", "NotImpl...
648a36f77db7e45784c047176074f98534c76636
train
ensemble
Identifies the best prediction given the results from the submodels. Parameters ---------- subresults : List[Dict[str, torch.Tensor]] Results of each submodel. Returns ------- The index of the best submodel.
allennlp/models/reading_comprehension/bidaf_ensemble.py
def ensemble(subresults: List[Dict[str, torch.Tensor]]) -> torch.Tensor: """ Identifies the best prediction given the results from the submodels. Parameters ---------- subresults : List[Dict[str, torch.Tensor]] Results of each submodel. Returns ------- The index of the best sub...
def ensemble(subresults: List[Dict[str, torch.Tensor]]) -> torch.Tensor: """ Identifies the best prediction given the results from the submodels. Parameters ---------- subresults : List[Dict[str, torch.Tensor]] Results of each submodel. Returns ------- The index of the best sub...
[ "Identifies", "the", "best", "prediction", "given", "the", "results", "from", "the", "submodels", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/models/reading_comprehension/bidaf_ensemble.py#L124-L142
[ "def", "ensemble", "(", "subresults", ":", "List", "[", "Dict", "[", "str", ",", "torch", ".", "Tensor", "]", "]", ")", "->", "torch", ".", "Tensor", ":", "# Choose the highest average confidence span.", "span_start_probs", "=", "sum", "(", "subresult", "[", ...
648a36f77db7e45784c047176074f98534c76636
train
ElmoLstm.forward
Parameters ---------- inputs : ``torch.Tensor``, required. A Tensor of shape ``(batch_size, sequence_length, hidden_size)``. mask : ``torch.LongTensor``, required. A binary mask of shape ``(batch_size, sequence_length)`` representing the non-padded elements in...
allennlp/modules/elmo_lstm.py
def forward(self, # pylint: disable=arguments-differ inputs: torch.Tensor, mask: torch.LongTensor) -> torch.Tensor: """ Parameters ---------- inputs : ``torch.Tensor``, required. A Tensor of shape ``(batch_size, sequence_length, hidden_size)``...
def forward(self, # pylint: disable=arguments-differ inputs: torch.Tensor, mask: torch.LongTensor) -> torch.Tensor: """ Parameters ---------- inputs : ``torch.Tensor``, required. A Tensor of shape ``(batch_size, sequence_length, hidden_size)``...
[ "Parameters", "----------", "inputs", ":", "torch", ".", "Tensor", "required", ".", "A", "Tensor", "of", "shape", "(", "batch_size", "sequence_length", "hidden_size", ")", ".", "mask", ":", "torch", ".", "LongTensor", "required", ".", "A", "binary", "mask", ...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/modules/elmo_lstm.py#L104-L158
[ "def", "forward", "(", "self", ",", "# pylint: disable=arguments-differ", "inputs", ":", "torch", ".", "Tensor", ",", "mask", ":", "torch", ".", "LongTensor", ")", "->", "torch", ".", "Tensor", ":", "batch_size", ",", "total_sequence_length", "=", "mask", ".",...
648a36f77db7e45784c047176074f98534c76636
train
ElmoLstm._lstm_forward
Parameters ---------- inputs : ``PackedSequence``, required. A batch first ``PackedSequence`` to run the stacked LSTM over. initial_state : ``Tuple[torch.Tensor, torch.Tensor]``, optional, (default = None) A tuple (state, memory) representing the initial hidden state and ...
allennlp/modules/elmo_lstm.py
def _lstm_forward(self, inputs: PackedSequence, initial_state: Optional[Tuple[torch.Tensor, torch.Tensor]] = None) -> \ Tuple[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]: """ Parameters ---------- inputs : ``PackedSequence``, r...
def _lstm_forward(self, inputs: PackedSequence, initial_state: Optional[Tuple[torch.Tensor, torch.Tensor]] = None) -> \ Tuple[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]: """ Parameters ---------- inputs : ``PackedSequence``, r...
[ "Parameters", "----------", "inputs", ":", "PackedSequence", "required", ".", "A", "batch", "first", "PackedSequence", "to", "run", "the", "stacked", "LSTM", "over", ".", "initial_state", ":", "Tuple", "[", "torch", ".", "Tensor", "torch", ".", "Tensor", "]", ...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/modules/elmo_lstm.py#L160-L241
[ "def", "_lstm_forward", "(", "self", ",", "inputs", ":", "PackedSequence", ",", "initial_state", ":", "Optional", "[", "Tuple", "[", "torch", ".", "Tensor", ",", "torch", ".", "Tensor", "]", "]", "=", "None", ")", "->", "Tuple", "[", "torch", ".", "Ten...
648a36f77db7e45784c047176074f98534c76636
train
ElmoLstm.load_weights
Load the pre-trained weights from the file.
allennlp/modules/elmo_lstm.py
def load_weights(self, weight_file: str) -> None: """ Load the pre-trained weights from the file. """ requires_grad = self.requires_grad with h5py.File(cached_path(weight_file), 'r') as fin: for i_layer, lstms in enumerate( zip(self.forward_layers...
def load_weights(self, weight_file: str) -> None: """ Load the pre-trained weights from the file. """ requires_grad = self.requires_grad with h5py.File(cached_path(weight_file), 'r') as fin: for i_layer, lstms in enumerate( zip(self.forward_layers...
[ "Load", "the", "pre", "-", "trained", "weights", "from", "the", "file", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/modules/elmo_lstm.py#L243-L301
[ "def", "load_weights", "(", "self", ",", "weight_file", ":", "str", ")", "->", "None", ":", "requires_grad", "=", "self", ".", "requires_grad", "with", "h5py", ".", "File", "(", "cached_path", "(", "weight_file", ")", ",", "'r'", ")", "as", "fin", ":", ...
648a36f77db7e45784c047176074f98534c76636
train
StackedAlternatingLstm.forward
Parameters ---------- inputs : ``PackedSequence``, required. A batch first ``PackedSequence`` to run the stacked LSTM over. initial_state : Tuple[torch.Tensor, torch.Tensor], optional, (default = None) A tuple (state, memory) representing the initial hidden state and memo...
allennlp/modules/stacked_alternating_lstm.py
def forward(self, # pylint: disable=arguments-differ inputs: PackedSequence, initial_state: Optional[Tuple[torch.Tensor, torch.Tensor]] = None) -> \ Tuple[Union[torch.Tensor, PackedSequence], Tuple[torch.Tensor, torch.Tensor]]: """ Parameters --------...
def forward(self, # pylint: disable=arguments-differ inputs: PackedSequence, initial_state: Optional[Tuple[torch.Tensor, torch.Tensor]] = None) -> \ Tuple[Union[torch.Tensor, PackedSequence], Tuple[torch.Tensor, torch.Tensor]]: """ Parameters --------...
[ "Parameters", "----------", "inputs", ":", "PackedSequence", "required", ".", "A", "batch", "first", "PackedSequence", "to", "run", "the", "stacked", "LSTM", "over", ".", "initial_state", ":", "Tuple", "[", "torch", ".", "Tensor", "torch", ".", "Tensor", "]", ...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/modules/stacked_alternating_lstm.py#L72-L111
[ "def", "forward", "(", "self", ",", "# pylint: disable=arguments-differ", "inputs", ":", "PackedSequence", ",", "initial_state", ":", "Optional", "[", "Tuple", "[", "torch", ".", "Tensor", ",", "torch", ".", "Tensor", "]", "]", "=", "None", ")", "->", "Tuple...
648a36f77db7e45784c047176074f98534c76636
train
substitute_any_type
Takes a type and a set of basic types, and substitutes all instances of ANY_TYPE with all possible basic types and returns a list with all possible combinations. Note that this substitution is unconstrained. That is, If you have a type with placeholders, <#1,#1> for example, this may substitute the placeh...
allennlp/semparse/type_declarations/type_declaration.py
def substitute_any_type(type_: Type, basic_types: Set[BasicType]) -> List[Type]: """ Takes a type and a set of basic types, and substitutes all instances of ANY_TYPE with all possible basic types and returns a list with all possible combinations. Note that this substitution is unconstrained. That is, ...
def substitute_any_type(type_: Type, basic_types: Set[BasicType]) -> List[Type]: """ Takes a type and a set of basic types, and substitutes all instances of ANY_TYPE with all possible basic types and returns a list with all possible combinations. Note that this substitution is unconstrained. That is, ...
[ "Takes", "a", "type", "and", "a", "set", "of", "basic", "types", "and", "substitutes", "all", "instances", "of", "ANY_TYPE", "with", "all", "possible", "basic", "types", "and", "returns", "a", "list", "with", "all", "possible", "combinations", ".", "Note", ...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/type_declarations/type_declaration.py#L540-L554
[ "def", "substitute_any_type", "(", "type_", ":", "Type", ",", "basic_types", ":", "Set", "[", "BasicType", "]", ")", "->", "List", "[", "Type", "]", ":", "if", "type_", "==", "ANY_TYPE", ":", "return", "list", "(", "basic_types", ")", "if", "isinstance",...
648a36f77db7e45784c047176074f98534c76636
train
_get_complex_type_production
Takes a complex type (without any placeholders), gets its return values, and returns productions (perhaps each with multiple arguments) that produce the return values. This method also takes care of ``MultiMatchNamedBasicTypes``. If one of the arguments or the return types is a multi match type, it gets al...
allennlp/semparse/type_declarations/type_declaration.py
def _get_complex_type_production(complex_type: ComplexType, multi_match_mapping: Dict[Type, List[Type]]) -> List[Tuple[Type, str]]: """ Takes a complex type (without any placeholders), gets its return values, and returns productions (perhaps each with multiple arguments) tha...
def _get_complex_type_production(complex_type: ComplexType, multi_match_mapping: Dict[Type, List[Type]]) -> List[Tuple[Type, str]]: """ Takes a complex type (without any placeholders), gets its return values, and returns productions (perhaps each with multiple arguments) tha...
[ "Takes", "a", "complex", "type", "(", "without", "any", "placeholders", ")", "gets", "its", "return", "values", "and", "returns", "productions", "(", "perhaps", "each", "with", "multiple", "arguments", ")", "that", "produce", "the", "return", "values", ".", ...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/type_declarations/type_declaration.py#L561-L597
[ "def", "_get_complex_type_production", "(", "complex_type", ":", "ComplexType", ",", "multi_match_mapping", ":", "Dict", "[", "Type", ",", "List", "[", "Type", "]", "]", ")", "->", "List", "[", "Tuple", "[", "Type", ",", "str", "]", "]", ":", "return_type"...
648a36f77db7e45784c047176074f98534c76636
train
get_valid_actions
Generates all the valid actions starting from each non-terminal. For terminals of a specific type, we simply add a production from the type to the terminal. For all terminal `functions`, we additionally add a rule that allows their return type to be generated from an application of the function. For exampl...
allennlp/semparse/type_declarations/type_declaration.py
def get_valid_actions(name_mapping: Dict[str, str], type_signatures: Dict[str, Type], basic_types: Set[Type], multi_match_mapping: Dict[Type, List[Type]] = None, valid_starting_types: Set[Type] = None, num_nest...
def get_valid_actions(name_mapping: Dict[str, str], type_signatures: Dict[str, Type], basic_types: Set[Type], multi_match_mapping: Dict[Type, List[Type]] = None, valid_starting_types: Set[Type] = None, num_nest...
[ "Generates", "all", "the", "valid", "actions", "starting", "from", "each", "non", "-", "terminal", ".", "For", "terminals", "of", "a", "specific", "type", "we", "simply", "add", "a", "production", "from", "the", "type", "to", "the", "terminal", ".", "For",...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/type_declarations/type_declaration.py#L600-L692
[ "def", "get_valid_actions", "(", "name_mapping", ":", "Dict", "[", "str", ",", "str", "]", ",", "type_signatures", ":", "Dict", "[", "str", ",", "Type", "]", ",", "basic_types", ":", "Set", "[", "Type", "]", ",", "multi_match_mapping", ":", "Dict", "[", ...
648a36f77db7e45784c047176074f98534c76636
train
ComplexType.return_type
Gives the final return type for this function. If the function takes a single argument, this is just ``self.second``. If the function takes multiple arguments and returns a basic type, this should be the final ``.second`` after following all complex types. That is the implementation here in t...
allennlp/semparse/type_declarations/type_declaration.py
def return_type(self) -> Type: """ Gives the final return type for this function. If the function takes a single argument, this is just ``self.second``. If the function takes multiple arguments and returns a basic type, this should be the final ``.second`` after following all complex t...
def return_type(self) -> Type: """ Gives the final return type for this function. If the function takes a single argument, this is just ``self.second``. If the function takes multiple arguments and returns a basic type, this should be the final ``.second`` after following all complex t...
[ "Gives", "the", "final", "return", "type", "for", "this", "function", ".", "If", "the", "function", "takes", "a", "single", "argument", "this", "is", "just", "self", ".", "second", ".", "If", "the", "function", "takes", "multiple", "arguments", "and", "ret...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/type_declarations/type_declaration.py#L29-L40
[ "def", "return_type", "(", "self", ")", "->", "Type", ":", "return_type", "=", "self", ".", "second", "while", "isinstance", "(", "return_type", ",", "ComplexType", ")", ":", "return_type", "=", "return_type", ".", "second", "return", "return_type" ]
648a36f77db7e45784c047176074f98534c76636
train
ComplexType.argument_types
Gives the types of all arguments to this function. For functions returning a basic type, we grab all ``.first`` types until ``.second`` is no longer a ``ComplexType``. That logic is implemented here in the base class. If you have a higher-order function that returns a function itself, you nee...
allennlp/semparse/type_declarations/type_declaration.py
def argument_types(self) -> List[Type]: """ Gives the types of all arguments to this function. For functions returning a basic type, we grab all ``.first`` types until ``.second`` is no longer a ``ComplexType``. That logic is implemented here in the base class. If you have a higher-or...
def argument_types(self) -> List[Type]: """ Gives the types of all arguments to this function. For functions returning a basic type, we grab all ``.first`` types until ``.second`` is no longer a ``ComplexType``. That logic is implemented here in the base class. If you have a higher-or...
[ "Gives", "the", "types", "of", "all", "arguments", "to", "this", "function", ".", "For", "functions", "returning", "a", "basic", "type", "we", "grab", "all", ".", "first", "types", "until", ".", "second", "is", "no", "longer", "a", "ComplexType", ".", "T...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/type_declarations/type_declaration.py#L42-L54
[ "def", "argument_types", "(", "self", ")", "->", "List", "[", "Type", "]", ":", "arguments", "=", "[", "self", ".", "first", "]", "remaining_type", "=", "self", ".", "second", "while", "isinstance", "(", "remaining_type", ",", "ComplexType", ")", ":", "a...
648a36f77db7e45784c047176074f98534c76636
train
ComplexType.substitute_any_type
Takes a set of ``BasicTypes`` and replaces any instances of ``ANY_TYPE`` inside this complex type with each of those basic types.
allennlp/semparse/type_declarations/type_declaration.py
def substitute_any_type(self, basic_types: Set[BasicType]) -> List[Type]: """ Takes a set of ``BasicTypes`` and replaces any instances of ``ANY_TYPE`` inside this complex type with each of those basic types. """ substitutions = [] for first_type in substitute_any_type(sel...
def substitute_any_type(self, basic_types: Set[BasicType]) -> List[Type]: """ Takes a set of ``BasicTypes`` and replaces any instances of ``ANY_TYPE`` inside this complex type with each of those basic types. """ substitutions = [] for first_type in substitute_any_type(sel...
[ "Takes", "a", "set", "of", "BasicTypes", "and", "replaces", "any", "instances", "of", "ANY_TYPE", "inside", "this", "complex", "type", "with", "each", "of", "those", "basic", "types", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/type_declarations/type_declaration.py#L56-L65
[ "def", "substitute_any_type", "(", "self", ",", "basic_types", ":", "Set", "[", "BasicType", "]", ")", "->", "List", "[", "Type", "]", ":", "substitutions", "=", "[", "]", "for", "first_type", "in", "substitute_any_type", "(", "self", ".", "first", ",", ...
648a36f77db7e45784c047176074f98534c76636
train
UnaryOpType.resolve
See ``PlaceholderType.resolve``
allennlp/semparse/type_declarations/type_declaration.py
def resolve(self, other) -> Optional[Type]: """See ``PlaceholderType.resolve``""" if not isinstance(other, NltkComplexType): return None other_first = other.first.resolve(other.second) if not other_first: return None other_second = other.second.resolve(oth...
def resolve(self, other) -> Optional[Type]: """See ``PlaceholderType.resolve``""" if not isinstance(other, NltkComplexType): return None other_first = other.first.resolve(other.second) if not other_first: return None other_second = other.second.resolve(oth...
[ "See", "PlaceholderType", ".", "resolve" ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/type_declarations/type_declaration.py#L279-L289
[ "def", "resolve", "(", "self", ",", "other", ")", "->", "Optional", "[", "Type", "]", ":", "if", "not", "isinstance", "(", "other", ",", "NltkComplexType", ")", ":", "return", "None", "other_first", "=", "other", ".", "first", ".", "resolve", "(", "oth...
648a36f77db7e45784c047176074f98534c76636
train
BinaryOpType.resolve
See ``PlaceholderType.resolve``
allennlp/semparse/type_declarations/type_declaration.py
def resolve(self, other: Type) -> Optional[Type]: """See ``PlaceholderType.resolve``""" if not isinstance(other, NltkComplexType): return None if not isinstance(other.second, NltkComplexType): return None other_first = other.first.resolve(other.second.first) ...
def resolve(self, other: Type) -> Optional[Type]: """See ``PlaceholderType.resolve``""" if not isinstance(other, NltkComplexType): return None if not isinstance(other.second, NltkComplexType): return None other_first = other.first.resolve(other.second.first) ...
[ "See", "PlaceholderType", ".", "resolve" ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/type_declarations/type_declaration.py#L332-L347
[ "def", "resolve", "(", "self", ",", "other", ":", "Type", ")", "->", "Optional", "[", "Type", "]", ":", "if", "not", "isinstance", "(", "other", ",", "NltkComplexType", ")", ":", "return", "None", "if", "not", "isinstance", "(", "other", ".", "second",...
648a36f77db7e45784c047176074f98534c76636
train
DynamicTypeApplicationExpression._set_type
We override this method to do just one thing on top of ``ApplicationExpression._set_type``. In lambda expressions of the form /x F(x), where the function is F and the argument is x, we can use the type of F to infer the type of x. That is, if F is of type <a, b>, we can resolve the type of x aga...
allennlp/semparse/type_declarations/type_declaration.py
def _set_type(self, other_type: Type = ANY_TYPE, signature=None) -> None: """ We override this method to do just one thing on top of ``ApplicationExpression._set_type``. In lambda expressions of the form /x F(x), where the function is F and the argument is x, we can use the type of F to ...
def _set_type(self, other_type: Type = ANY_TYPE, signature=None) -> None: """ We override this method to do just one thing on top of ``ApplicationExpression._set_type``. In lambda expressions of the form /x F(x), where the function is F and the argument is x, we can use the type of F to ...
[ "We", "override", "this", "method", "to", "do", "just", "one", "thing", "on", "top", "of", "ApplicationExpression", ".", "_set_type", ".", "In", "lambda", "expressions", "of", "the", "form", "/", "x", "F", "(", "x", ")", "where", "the", "function", "is",...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/type_declarations/type_declaration.py#L412-L437
[ "def", "_set_type", "(", "self", ",", "other_type", ":", "Type", "=", "ANY_TYPE", ",", "signature", "=", "None", ")", "->", "None", ":", "super", "(", "DynamicTypeApplicationExpression", ",", "self", ")", ".", "_set_type", "(", "other_type", ",", "signature"...
648a36f77db7e45784c047176074f98534c76636
train
TensorboardWriter.log_parameter_and_gradient_statistics
Send the mean and std of all parameters and gradients to tensorboard, as well as logging the average gradient norm.
allennlp/training/tensorboard_writer.py
def log_parameter_and_gradient_statistics(self, # pylint: disable=invalid-name model: Model, batch_grad_norm: float) -> None: """ Send the mean and std of all parameters and gradients to tensorboard, as well ...
def log_parameter_and_gradient_statistics(self, # pylint: disable=invalid-name model: Model, batch_grad_norm: float) -> None: """ Send the mean and std of all parameters and gradients to tensorboard, as well ...
[ "Send", "the", "mean", "and", "std", "of", "all", "parameters", "and", "gradients", "to", "tensorboard", "as", "well", "as", "logging", "the", "average", "gradient", "norm", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/training/tensorboard_writer.py#L84-L112
[ "def", "log_parameter_and_gradient_statistics", "(", "self", ",", "# pylint: disable=invalid-name", "model", ":", "Model", ",", "batch_grad_norm", ":", "float", ")", "->", "None", ":", "if", "self", ".", "_should_log_parameter_statistics", ":", "# Log parameter values to ...
648a36f77db7e45784c047176074f98534c76636
train
TensorboardWriter.log_learning_rates
Send current parameter specific learning rates to tensorboard
allennlp/training/tensorboard_writer.py
def log_learning_rates(self, model: Model, optimizer: torch.optim.Optimizer): """ Send current parameter specific learning rates to tensorboard """ if self._should_log_learning_rate: # optimizer stores lr info keyed by par...
def log_learning_rates(self, model: Model, optimizer: torch.optim.Optimizer): """ Send current parameter specific learning rates to tensorboard """ if self._should_log_learning_rate: # optimizer stores lr info keyed by par...
[ "Send", "current", "parameter", "specific", "learning", "rates", "to", "tensorboard" ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/training/tensorboard_writer.py#L114-L131
[ "def", "log_learning_rates", "(", "self", ",", "model", ":", "Model", ",", "optimizer", ":", "torch", ".", "optim", ".", "Optimizer", ")", ":", "if", "self", ".", "_should_log_learning_rate", ":", "# optimizer stores lr info keyed by parameter tensor", "# we want to l...
648a36f77db7e45784c047176074f98534c76636
train
TensorboardWriter.log_histograms
Send histograms of parameters to tensorboard.
allennlp/training/tensorboard_writer.py
def log_histograms(self, model: Model, histogram_parameters: Set[str]) -> None: """ Send histograms of parameters to tensorboard. """ for name, param in model.named_parameters(): if name in histogram_parameters: self.add_train_histogram("parameter_histogram/" ...
def log_histograms(self, model: Model, histogram_parameters: Set[str]) -> None: """ Send histograms of parameters to tensorboard. """ for name, param in model.named_parameters(): if name in histogram_parameters: self.add_train_histogram("parameter_histogram/" ...
[ "Send", "histograms", "of", "parameters", "to", "tensorboard", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/training/tensorboard_writer.py#L133-L139
[ "def", "log_histograms", "(", "self", ",", "model", ":", "Model", ",", "histogram_parameters", ":", "Set", "[", "str", "]", ")", "->", "None", ":", "for", "name", ",", "param", "in", "model", ".", "named_parameters", "(", ")", ":", "if", "name", "in", ...
648a36f77db7e45784c047176074f98534c76636
train
TensorboardWriter.log_metrics
Sends all of the train metrics (and validation metrics, if provided) to tensorboard.
allennlp/training/tensorboard_writer.py
def log_metrics(self, train_metrics: dict, val_metrics: dict = None, epoch: int = None, log_to_console: bool = False) -> None: """ Sends all of the train metrics (and validation metrics, if provided) to tensorboard. ...
def log_metrics(self, train_metrics: dict, val_metrics: dict = None, epoch: int = None, log_to_console: bool = False) -> None: """ Sends all of the train metrics (and validation metrics, if provided) to tensorboard. ...
[ "Sends", "all", "of", "the", "train", "metrics", "(", "and", "validation", "metrics", "if", "provided", ")", "to", "tensorboard", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/training/tensorboard_writer.py#L141-L178
[ "def", "log_metrics", "(", "self", ",", "train_metrics", ":", "dict", ",", "val_metrics", ":", "dict", "=", "None", ",", "epoch", ":", "int", "=", "None", ",", "log_to_console", ":", "bool", "=", "False", ")", "->", "None", ":", "metric_names", "=", "s...
648a36f77db7e45784c047176074f98534c76636
train
get_explanation
Create explanation (as a list of header/content entries) for an answer
allennlp/semparse/contexts/quarel_utils.py
def get_explanation(logical_form: str, world_extractions: JsonDict, answer_index: int, world: QuarelWorld) -> List[JsonDict]: """ Create explanation (as a list of header/content entries) for an answer """ output = [] nl_world = {} if wo...
def get_explanation(logical_form: str, world_extractions: JsonDict, answer_index: int, world: QuarelWorld) -> List[JsonDict]: """ Create explanation (as a list of header/content entries) for an answer """ output = [] nl_world = {} if wo...
[ "Create", "explanation", "(", "as", "a", "list", "of", "header", "/", "content", "entries", ")", "for", "an", "answer" ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/contexts/quarel_utils.py#L126-L182
[ "def", "get_explanation", "(", "logical_form", ":", "str", ",", "world_extractions", ":", "JsonDict", ",", "answer_index", ":", "int", ",", "world", ":", "QuarelWorld", ")", "->", "List", "[", "JsonDict", "]", ":", "output", "=", "[", "]", "nl_world", "=",...
648a36f77db7e45784c047176074f98534c76636
train
align_entities
Use stemming to attempt alignment between extracted world and given world literals. If more words align to one world vs the other, it's considered aligned.
allennlp/semparse/contexts/quarel_utils.py
def align_entities(extracted: List[str], literals: JsonDict, stemmer: NltkPorterStemmer) -> List[str]: """ Use stemming to attempt alignment between extracted world and given world literals. If more words align to one world vs the other, it's considered aligned. """...
def align_entities(extracted: List[str], literals: JsonDict, stemmer: NltkPorterStemmer) -> List[str]: """ Use stemming to attempt alignment between extracted world and given world literals. If more words align to one world vs the other, it's considered aligned. """...
[ "Use", "stemming", "to", "attempt", "alignment", "between", "extracted", "world", "and", "given", "world", "literals", ".", "If", "more", "words", "align", "to", "one", "world", "vs", "the", "other", "it", "s", "considered", "aligned", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/contexts/quarel_utils.py#L360-L378
[ "def", "align_entities", "(", "extracted", ":", "List", "[", "str", "]", ",", "literals", ":", "JsonDict", ",", "stemmer", ":", "NltkPorterStemmer", ")", "->", "List", "[", "str", "]", ":", "literal_keys", "=", "list", "(", "literals", ".", "keys", "(", ...
648a36f77db7e45784c047176074f98534c76636
train
multi_perspective_match
Calculate multi-perspective cosine matching between time-steps of vectors of the same length. Parameters ---------- vector1 : ``torch.Tensor`` A tensor of shape ``(batch, seq_len, hidden_size)`` vector2 : ``torch.Tensor`` A tensor of shape ``(batch, seq_len or 1, hidden_size)`` ...
allennlp/modules/bimpm_matching.py
def multi_perspective_match(vector1: torch.Tensor, vector2: torch.Tensor, weight: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]: """ Calculate multi-perspective cosine matching between time-steps of vectors of the same length. Parameters ...
def multi_perspective_match(vector1: torch.Tensor, vector2: torch.Tensor, weight: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]: """ Calculate multi-perspective cosine matching between time-steps of vectors of the same length. Parameters ...
[ "Calculate", "multi", "-", "perspective", "cosine", "matching", "between", "time", "-", "steps", "of", "vectors", "of", "the", "same", "length", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/modules/bimpm_matching.py#L16-L53
[ "def", "multi_perspective_match", "(", "vector1", ":", "torch", ".", "Tensor", ",", "vector2", ":", "torch", ".", "Tensor", ",", "weight", ":", "torch", ".", "Tensor", ")", "->", "Tuple", "[", "torch", ".", "Tensor", ",", "torch", ".", "Tensor", "]", "...
648a36f77db7e45784c047176074f98534c76636
train
multi_perspective_match_pairwise
Calculate multi-perspective cosine matching between each time step of one vector and each time step of another vector. Parameters ---------- vector1 : ``torch.Tensor`` A tensor of shape ``(batch, seq_len1, hidden_size)`` vector2 : ``torch.Tensor`` A tensor of shape ``(batch, seq_len...
allennlp/modules/bimpm_matching.py
def multi_perspective_match_pairwise(vector1: torch.Tensor, vector2: torch.Tensor, weight: torch.Tensor, eps: float = 1e-8) -> torch.Tensor: """ Calculate multi-perspective cosine matching between each...
def multi_perspective_match_pairwise(vector1: torch.Tensor, vector2: torch.Tensor, weight: torch.Tensor, eps: float = 1e-8) -> torch.Tensor: """ Calculate multi-perspective cosine matching between each...
[ "Calculate", "multi", "-", "perspective", "cosine", "matching", "between", "each", "time", "step", "of", "one", "vector", "and", "each", "time", "step", "of", "another", "vector", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/modules/bimpm_matching.py#L56-L98
[ "def", "multi_perspective_match_pairwise", "(", "vector1", ":", "torch", ".", "Tensor", ",", "vector2", ":", "torch", ".", "Tensor", ",", "weight", ":", "torch", ".", "Tensor", ",", "eps", ":", "float", "=", "1e-8", ")", "->", "torch", ".", "Tensor", ":"...
648a36f77db7e45784c047176074f98534c76636
train
BiMpmMatching.forward
Given the forward (or backward) representations of sentence1 and sentence2, apply four bilateral matching functions between them in one direction. Parameters ---------- context_1 : ``torch.Tensor`` Tensor of shape (batch_size, seq_len1, hidden_dim) representing the encoding ...
allennlp/modules/bimpm_matching.py
def forward(self, context_1: torch.Tensor, mask_1: torch.Tensor, context_2: torch.Tensor, mask_2: torch.Tensor) -> Tuple[List[torch.Tensor], List[torch.Tensor]]: # pylint: disable=arguments-differ """ Given the forward (or backward)...
def forward(self, context_1: torch.Tensor, mask_1: torch.Tensor, context_2: torch.Tensor, mask_2: torch.Tensor) -> Tuple[List[torch.Tensor], List[torch.Tensor]]: # pylint: disable=arguments-differ """ Given the forward (or backward)...
[ "Given", "the", "forward", "(", "or", "backward", ")", "representations", "of", "sentence1", "and", "sentence2", "apply", "four", "bilateral", "matching", "functions", "between", "them", "in", "one", "direction", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/modules/bimpm_matching.py#L188-L361
[ "def", "forward", "(", "self", ",", "context_1", ":", "torch", ".", "Tensor", ",", "mask_1", ":", "torch", ".", "Tensor", ",", "context_2", ":", "torch", ".", "Tensor", ",", "mask_2", ":", "torch", ".", "Tensor", ")", "->", "Tuple", "[", "List", "[",...
648a36f77db7e45784c047176074f98534c76636
train
parse_example_line
Training data in WikitableQuestions comes with examples in the form of lisp strings in the format: (example (id <example-id>) (utterance <question>) (context (graph tables.TableKnowledgeGraph <table-filename>)) (targetValue (list (description <answer1>) (descri...
allennlp/data/dataset_readers/semantic_parsing/wikitables/util.py
def parse_example_line(lisp_string: str) -> Dict: """ Training data in WikitableQuestions comes with examples in the form of lisp strings in the format: (example (id <example-id>) (utterance <question>) (context (graph tables.TableKnowledgeGraph <table-filename>)) ...
def parse_example_line(lisp_string: str) -> Dict: """ Training data in WikitableQuestions comes with examples in the form of lisp strings in the format: (example (id <example-id>) (utterance <question>) (context (graph tables.TableKnowledgeGraph <table-filename>)) ...
[ "Training", "data", "in", "WikitableQuestions", "comes", "with", "examples", "in", "the", "form", "of", "lisp", "strings", "in", "the", "format", ":", "(", "example", "(", "id", "<example", "-", "id", ">", ")", "(", "utterance", "<question", ">", ")", "(...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/data/dataset_readers/semantic_parsing/wikitables/util.py#L3-L26
[ "def", "parse_example_line", "(", "lisp_string", ":", "str", ")", "->", "Dict", ":", "id_piece", ",", "rest", "=", "lisp_string", ".", "split", "(", "') (utterance \"'", ")", "example_id", "=", "id_piece", ".", "split", "(", "'(id '", ")", "[", "1", "]", ...
648a36f77db7e45784c047176074f98534c76636
train
make_vocab_from_args
Just converts from an ``argparse.Namespace`` object to params.
allennlp/commands/make_vocab.py
def make_vocab_from_args(args: argparse.Namespace): """ Just converts from an ``argparse.Namespace`` object to params. """ parameter_path = args.param_path overrides = args.overrides serialization_dir = args.serialization_dir params = Params.from_file(parameter_path, overrides) make_vo...
def make_vocab_from_args(args: argparse.Namespace): """ Just converts from an ``argparse.Namespace`` object to params. """ parameter_path = args.param_path overrides = args.overrides serialization_dir = args.serialization_dir params = Params.from_file(parameter_path, overrides) make_vo...
[ "Just", "converts", "from", "an", "argparse", ".", "Namespace", "object", "to", "params", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/commands/make_vocab.py#L67-L77
[ "def", "make_vocab_from_args", "(", "args", ":", "argparse", ".", "Namespace", ")", ":", "parameter_path", "=", "args", ".", "param_path", "overrides", "=", "args", ".", "overrides", "serialization_dir", "=", "args", ".", "serialization_dir", "params", "=", "Par...
648a36f77db7e45784c047176074f98534c76636
train
QuarelWorld.execute
Very basic model for executing friction logical forms. For now returns answer index (or -1 if no answer can be concluded)
allennlp/semparse/worlds/quarel_world.py
def execute(self, lf_raw: str) -> int: """ Very basic model for executing friction logical forms. For now returns answer index (or -1 if no answer can be concluded) """ # Remove "a:" prefixes from attributes (hack) logical_form = re.sub(r"\(a:", r"(", lf_raw) pars...
def execute(self, lf_raw: str) -> int: """ Very basic model for executing friction logical forms. For now returns answer index (or -1 if no answer can be concluded) """ # Remove "a:" prefixes from attributes (hack) logical_form = re.sub(r"\(a:", r"(", lf_raw) pars...
[ "Very", "basic", "model", "for", "executing", "friction", "logical", "forms", ".", "For", "now", "returns", "answer", "index", "(", "or", "-", "1", "if", "no", "answer", "can", "be", "concluded", ")" ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/worlds/quarel_world.py#L167-L182
[ "def", "execute", "(", "self", ",", "lf_raw", ":", "str", ")", "->", "int", ":", "# Remove \"a:\" prefixes from attributes (hack)", "logical_form", "=", "re", ".", "sub", "(", "r\"\\(a:\"", ",", "r\"(\"", ",", "lf_raw", ")", "parse", "=", "semparse_util", ".",...
648a36f77db7e45784c047176074f98534c76636
train
get_times_from_utterance
Given an utterance, we get the numbers that correspond to times and convert them to values that may appear in the query. For example: convert ``7pm`` to ``1900``.
allennlp/semparse/contexts/atis_tables.py
def get_times_from_utterance(utterance: str, char_offset_to_token_index: Dict[int, int], indices_of_approximate_words: Set[int]) -> Dict[str, List[int]]: """ Given an utterance, we get the numbers that correspond to times and convert them to values t...
def get_times_from_utterance(utterance: str, char_offset_to_token_index: Dict[int, int], indices_of_approximate_words: Set[int]) -> Dict[str, List[int]]: """ Given an utterance, we get the numbers that correspond to times and convert them to values t...
[ "Given", "an", "utterance", "we", "get", "the", "numbers", "that", "correspond", "to", "times", "and", "convert", "them", "to", "values", "that", "may", "appear", "in", "the", "query", ".", "For", "example", ":", "convert", "7pm", "to", "1900", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/contexts/atis_tables.py#L37-L77
[ "def", "get_times_from_utterance", "(", "utterance", ":", "str", ",", "char_offset_to_token_index", ":", "Dict", "[", "int", ",", "int", "]", ",", "indices_of_approximate_words", ":", "Set", "[", "int", "]", ")", "->", "Dict", "[", "str", ",", "List", "[", ...
648a36f77db7e45784c047176074f98534c76636
train
get_date_from_utterance
When the year is not explicitly mentioned in the utterance, the query assumes that it is 1993 so we do the same here. If there is no mention of the month or day then we do not return any dates from the utterance.
allennlp/semparse/contexts/atis_tables.py
def get_date_from_utterance(tokenized_utterance: List[Token], year: int = 1993) -> List[datetime]: """ When the year is not explicitly mentioned in the utterance, the query assumes that it is 1993 so we do the same here. If there is no mention of the month or day then we do n...
def get_date_from_utterance(tokenized_utterance: List[Token], year: int = 1993) -> List[datetime]: """ When the year is not explicitly mentioned in the utterance, the query assumes that it is 1993 so we do the same here. If there is no mention of the month or day then we do n...
[ "When", "the", "year", "is", "not", "explicitly", "mentioned", "in", "the", "utterance", "the", "query", "assumes", "that", "it", "is", "1993", "so", "we", "do", "the", "same", "here", ".", "If", "there", "is", "no", "mention", "of", "the", "month", "o...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/contexts/atis_tables.py#L79-L126
[ "def", "get_date_from_utterance", "(", "tokenized_utterance", ":", "List", "[", "Token", "]", ",", "year", ":", "int", "=", "1993", ")", "->", "List", "[", "datetime", "]", ":", "dates", "=", "[", "]", "utterance", "=", "' '", ".", "join", "(", "[", ...
648a36f77db7e45784c047176074f98534c76636
train
get_numbers_from_utterance
Given an utterance, this function finds all the numbers that are in the action space. Since we need to keep track of linking scores, we represent the numbers as a dictionary, where the keys are the string representation of the number and the values are lists of the token indices that triggers that number.
allennlp/semparse/contexts/atis_tables.py
def get_numbers_from_utterance(utterance: str, tokenized_utterance: List[Token]) -> Dict[str, List[int]]: """ Given an utterance, this function finds all the numbers that are in the action space. Since we need to keep track of linking scores, we represent the numbers as a dictionary, where the keys are the ...
def get_numbers_from_utterance(utterance: str, tokenized_utterance: List[Token]) -> Dict[str, List[int]]: """ Given an utterance, this function finds all the numbers that are in the action space. Since we need to keep track of linking scores, we represent the numbers as a dictionary, where the keys are the ...
[ "Given", "an", "utterance", "this", "function", "finds", "all", "the", "numbers", "that", "are", "in", "the", "action", "space", ".", "Since", "we", "need", "to", "keep", "track", "of", "linking", "scores", "we", "represent", "the", "numbers", "as", "a", ...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/contexts/atis_tables.py#L128-L170
[ "def", "get_numbers_from_utterance", "(", "utterance", ":", "str", ",", "tokenized_utterance", ":", "List", "[", "Token", "]", ")", "->", "Dict", "[", "str", ",", "List", "[", "int", "]", "]", ":", "# When we use a regex to find numbers or strings, we need a mapping...
648a36f77db7e45784c047176074f98534c76636
train
digit_to_query_time
Given a digit in the utterance, return a list of the times that it corresponds to.
allennlp/semparse/contexts/atis_tables.py
def digit_to_query_time(digit: str) -> List[int]: """ Given a digit in the utterance, return a list of the times that it corresponds to. """ if len(digit) > 2: return [int(digit), int(digit) + TWELVE_TO_TWENTY_FOUR] elif int(digit) % 12 == 0: return [0, 1200, 2400] return [int(di...
def digit_to_query_time(digit: str) -> List[int]: """ Given a digit in the utterance, return a list of the times that it corresponds to. """ if len(digit) > 2: return [int(digit), int(digit) + TWELVE_TO_TWENTY_FOUR] elif int(digit) % 12 == 0: return [0, 1200, 2400] return [int(di...
[ "Given", "a", "digit", "in", "the", "utterance", "return", "a", "list", "of", "the", "times", "that", "it", "corresponds", "to", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/contexts/atis_tables.py#L238-L247
[ "def", "digit_to_query_time", "(", "digit", ":", "str", ")", "->", "List", "[", "int", "]", ":", "if", "len", "(", "digit", ")", ">", "2", ":", "return", "[", "int", "(", "digit", ")", ",", "int", "(", "digit", ")", "+", "TWELVE_TO_TWENTY_FOUR", "]...
648a36f77db7e45784c047176074f98534c76636
train
get_approximate_times
Given a list of times that follow a word such as ``about``, we return a list of times that could appear in the query as a result of this. For example if ``about 7pm`` appears in the utterance, then we also want to add ``1830`` and ``1930``.
allennlp/semparse/contexts/atis_tables.py
def get_approximate_times(times: List[int]) -> List[int]: """ Given a list of times that follow a word such as ``about``, we return a list of times that could appear in the query as a result of this. For example if ``about 7pm`` appears in the utterance, then we also want to add ``1830`` and ``1930`...
def get_approximate_times(times: List[int]) -> List[int]: """ Given a list of times that follow a word such as ``about``, we return a list of times that could appear in the query as a result of this. For example if ``about 7pm`` appears in the utterance, then we also want to add ``1830`` and ``1930`...
[ "Given", "a", "list", "of", "times", "that", "follow", "a", "word", "such", "as", "about", "we", "return", "a", "list", "of", "times", "that", "could", "appear", "in", "the", "query", "as", "a", "result", "of", "this", ".", "For", "example", "if", "a...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/contexts/atis_tables.py#L249-L268
[ "def", "get_approximate_times", "(", "times", ":", "List", "[", "int", "]", ")", "->", "List", "[", "int", "]", ":", "approximate_times", "=", "[", "]", "for", "time", "in", "times", ":", "hour", "=", "int", "(", "time", "/", "HOUR_TO_TWENTY_FOUR", ")"...
648a36f77db7e45784c047176074f98534c76636
train
_time_regex_match
r""" Given a regex for matching times in the utterance, we want to convert the matches to the values that appear in the query and token indices they correspond to. ``char_offset_to_token_index`` is a dictionary that maps from the character offset to the token index, we use this to look up what token a ...
allennlp/semparse/contexts/atis_tables.py
def _time_regex_match(regex: str, utterance: str, char_offset_to_token_index: Dict[int, int], map_match_to_query_value: Callable[[str], List[int]], indices_of_approximate_words: Set[int]) -> Dict[str, List[int]]: r""" Given ...
def _time_regex_match(regex: str, utterance: str, char_offset_to_token_index: Dict[int, int], map_match_to_query_value: Callable[[str], List[int]], indices_of_approximate_words: Set[int]) -> Dict[str, List[int]]: r""" Given ...
[ "r", "Given", "a", "regex", "for", "matching", "times", "in", "the", "utterance", "we", "want", "to", "convert", "the", "matches", "to", "the", "values", "that", "appear", "in", "the", "query", "and", "token", "indices", "they", "correspond", "to", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/contexts/atis_tables.py#L270-L304
[ "def", "_time_regex_match", "(", "regex", ":", "str", ",", "utterance", ":", "str", ",", "char_offset_to_token_index", ":", "Dict", "[", "int", ",", "int", "]", ",", "map_match_to_query_value", ":", "Callable", "[", "[", "str", "]", ",", "List", "[", "int"...
648a36f77db7e45784c047176074f98534c76636
train
SqlExecutor._evaluate_sql_query_subprocess
We evaluate here whether the predicted query and the query label evaluate to the exact same table. This method is only called by the subprocess, so we just exit with 1 if it is correct and 0 otherwise.
allennlp/semparse/executors/sql_executor.py
def _evaluate_sql_query_subprocess(self, predicted_query: str, sql_query_labels: List[str]) -> int: """ We evaluate here whether the predicted query and the query label evaluate to the exact same table. This method is only called by the subprocess, so we just exit with 1 if it is correct...
def _evaluate_sql_query_subprocess(self, predicted_query: str, sql_query_labels: List[str]) -> int: """ We evaluate here whether the predicted query and the query label evaluate to the exact same table. This method is only called by the subprocess, so we just exit with 1 if it is correct...
[ "We", "evaluate", "here", "whether", "the", "predicted", "query", "and", "the", "query", "label", "evaluate", "to", "the", "exact", "same", "table", ".", "This", "method", "is", "only", "called", "by", "the", "subprocess", "so", "we", "just", "exit", "with...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/executors/sql_executor.py#L52-L79
[ "def", "_evaluate_sql_query_subprocess", "(", "self", ",", "predicted_query", ":", "str", ",", "sql_query_labels", ":", "List", "[", "str", "]", ")", "->", "int", ":", "postprocessed_predicted_query", "=", "self", ".", "postprocess_query_sqlite", "(", "predicted_que...
648a36f77db7e45784c047176074f98534c76636
train
format_grammar_string
Formats a dictionary of production rules into the string format expected by the Parsimonious Grammar class.
allennlp/semparse/contexts/sql_context_utils.py
def format_grammar_string(grammar_dictionary: Dict[str, List[str]]) -> str: """ Formats a dictionary of production rules into the string format expected by the Parsimonious Grammar class. """ grammar_string = '\n'.join([f"{nonterminal} = {' / '.join(right_hand_side)}" ...
def format_grammar_string(grammar_dictionary: Dict[str, List[str]]) -> str: """ Formats a dictionary of production rules into the string format expected by the Parsimonious Grammar class. """ grammar_string = '\n'.join([f"{nonterminal} = {' / '.join(right_hand_side)}" ...
[ "Formats", "a", "dictionary", "of", "production", "rules", "into", "the", "string", "format", "expected", "by", "the", "Parsimonious", "Grammar", "class", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/contexts/sql_context_utils.py#L16-L23
[ "def", "format_grammar_string", "(", "grammar_dictionary", ":", "Dict", "[", "str", ",", "List", "[", "str", "]", "]", ")", "->", "str", ":", "grammar_string", "=", "'\\n'", ".", "join", "(", "[", "f\"{nonterminal} = {' / '.join(right_hand_side)}\"", "for", "non...
648a36f77db7e45784c047176074f98534c76636
train
initialize_valid_actions
We initialize the valid actions with the global actions. These include the valid actions that result from the grammar and also those that result from the tables provided. The keys represent the nonterminals in the grammar and the values are lists of the valid actions of that nonterminal.
allennlp/semparse/contexts/sql_context_utils.py
def initialize_valid_actions(grammar: Grammar, keywords_to_uppercase: List[str] = None) -> Dict[str, List[str]]: """ We initialize the valid actions with the global actions. These include the valid actions that result from the grammar and also those that result from the tabl...
def initialize_valid_actions(grammar: Grammar, keywords_to_uppercase: List[str] = None) -> Dict[str, List[str]]: """ We initialize the valid actions with the global actions. These include the valid actions that result from the grammar and also those that result from the tabl...
[ "We", "initialize", "the", "valid", "actions", "with", "the", "global", "actions", ".", "These", "include", "the", "valid", "actions", "that", "result", "from", "the", "grammar", "and", "also", "those", "that", "result", "from", "the", "tables", "provided", ...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/contexts/sql_context_utils.py#L26-L61
[ "def", "initialize_valid_actions", "(", "grammar", ":", "Grammar", ",", "keywords_to_uppercase", ":", "List", "[", "str", "]", "=", "None", ")", "->", "Dict", "[", "str", ",", "List", "[", "str", "]", "]", ":", "valid_actions", ":", "Dict", "[", "str", ...
648a36f77db7e45784c047176074f98534c76636
train
format_action
This function formats an action as it appears in models. It splits productions based on the special `ws` and `wsp` rules, which are used in grammars to denote whitespace, and then rejoins these tokens a formatted, comma separated list. Importantly, note that it `does not` split on spaces in the gram...
allennlp/semparse/contexts/sql_context_utils.py
def format_action(nonterminal: str, right_hand_side: str, is_string: bool = False, is_number: bool = False, keywords_to_uppercase: List[str] = None) -> str: """ This function formats an action as it appears in models. It splits producti...
def format_action(nonterminal: str, right_hand_side: str, is_string: bool = False, is_number: bool = False, keywords_to_uppercase: List[str] = None) -> str: """ This function formats an action as it appears in models. It splits producti...
[ "This", "function", "formats", "an", "action", "as", "it", "appears", "in", "models", ".", "It", "splits", "productions", "based", "on", "the", "special", "ws", "and", "wsp", "rules", "which", "are", "used", "in", "grammars", "to", "denote", "whitespace", ...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/contexts/sql_context_utils.py#L64-L109
[ "def", "format_action", "(", "nonterminal", ":", "str", ",", "right_hand_side", ":", "str", ",", "is_string", ":", "bool", "=", "False", ",", "is_number", ":", "bool", "=", "False", ",", "keywords_to_uppercase", ":", "List", "[", "str", "]", "=", "None", ...
648a36f77db7e45784c047176074f98534c76636
train
SqlVisitor.add_action
For each node, we accumulate the rules that generated its children in a list.
allennlp/semparse/contexts/sql_context_utils.py
def add_action(self, node: Node) -> None: """ For each node, we accumulate the rules that generated its children in a list. """ if node.expr.name and node.expr.name not in ['ws', 'wsp']: nonterminal = f'{node.expr.name} -> ' if isinstance(node.expr, Literal): ...
def add_action(self, node: Node) -> None: """ For each node, we accumulate the rules that generated its children in a list. """ if node.expr.name and node.expr.name not in ['ws', 'wsp']: nonterminal = f'{node.expr.name} -> ' if isinstance(node.expr, Literal): ...
[ "For", "each", "node", "we", "accumulate", "the", "rules", "that", "generated", "its", "children", "in", "a", "list", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/contexts/sql_context_utils.py#L164-L191
[ "def", "add_action", "(", "self", ",", "node", ":", "Node", ")", "->", "None", ":", "if", "node", ".", "expr", ".", "name", "and", "node", ".", "expr", ".", "name", "not", "in", "[", "'ws'", ",", "'wsp'", "]", ":", "nonterminal", "=", "f'{node.expr...
648a36f77db7e45784c047176074f98534c76636
train
SqlVisitor.visit
See the ``NodeVisitor`` visit method. This just changes the order in which we visit nonterminals from right to left to left to right.
allennlp/semparse/contexts/sql_context_utils.py
def visit(self, node): """ See the ``NodeVisitor`` visit method. This just changes the order in which we visit nonterminals from right to left to left to right. """ method = getattr(self, 'visit_' + node.expr_name, self.generic_visit) # Call that method, and show where i...
def visit(self, node): """ See the ``NodeVisitor`` visit method. This just changes the order in which we visit nonterminals from right to left to left to right. """ method = getattr(self, 'visit_' + node.expr_name, self.generic_visit) # Call that method, and show where i...
[ "See", "the", "NodeVisitor", "visit", "method", ".", "This", "just", "changes", "the", "order", "in", "which", "we", "visit", "nonterminals", "from", "right", "to", "left", "to", "left", "to", "right", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/contexts/sql_context_utils.py#L194-L215
[ "def", "visit", "(", "self", ",", "node", ")", ":", "method", "=", "getattr", "(", "self", ",", "'visit_'", "+", "node", ".", "expr_name", ",", "self", ".", "generic_visit", ")", "# Call that method, and show where in the tree it failed if it blows", "# up.", "try...
648a36f77db7e45784c047176074f98534c76636
train
BertEmbedder.forward
Parameters ---------- input_ids : ``torch.LongTensor`` The (batch_size, ..., max_sequence_length) tensor of wordpiece ids. offsets : ``torch.LongTensor``, optional The BERT embeddings are one per wordpiece. However it's possible/likely you might want one per o...
allennlp/modules/token_embedders/bert_token_embedder.py
def forward(self, input_ids: torch.LongTensor, offsets: torch.LongTensor = None, token_type_ids: torch.LongTensor = None) -> torch.Tensor: """ Parameters ---------- input_ids : ``torch.LongTensor`` The (batch_size, ..., max_sequ...
def forward(self, input_ids: torch.LongTensor, offsets: torch.LongTensor = None, token_type_ids: torch.LongTensor = None) -> torch.Tensor: """ Parameters ---------- input_ids : ``torch.LongTensor`` The (batch_size, ..., max_sequ...
[ "Parameters", "----------", "input_ids", ":", "torch", ".", "LongTensor", "The", "(", "batch_size", "...", "max_sequence_length", ")", "tensor", "of", "wordpiece", "ids", ".", "offsets", ":", "torch", ".", "LongTensor", "optional", "The", "BERT", "embeddings", "...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/modules/token_embedders/bert_token_embedder.py#L51-L111
[ "def", "forward", "(", "self", ",", "input_ids", ":", "torch", ".", "LongTensor", ",", "offsets", ":", "torch", ".", "LongTensor", "=", "None", ",", "token_type_ids", ":", "torch", ".", "LongTensor", "=", "None", ")", "->", "torch", ".", "Tensor", ":", ...
648a36f77db7e45784c047176074f98534c76636
train
update_grammar_to_be_variable_free
SQL is a predominately variable free language in terms of simple usage, in the sense that most queries do not create references to variables which are not already static tables in a dataset. However, it is possible to do this via derived tables. If we don't require this functionality, we can tighten the ...
allennlp/semparse/contexts/text2sql_table_context.py
def update_grammar_to_be_variable_free(grammar_dictionary: Dict[str, List[str]]): """ SQL is a predominately variable free language in terms of simple usage, in the sense that most queries do not create references to variables which are not already static tables in a dataset. However, it is possible to ...
def update_grammar_to_be_variable_free(grammar_dictionary: Dict[str, List[str]]): """ SQL is a predominately variable free language in terms of simple usage, in the sense that most queries do not create references to variables which are not already static tables in a dataset. However, it is possible to ...
[ "SQL", "is", "a", "predominately", "variable", "free", "language", "in", "terms", "of", "simple", "usage", "in", "the", "sense", "that", "most", "queries", "do", "not", "create", "references", "to", "variables", "which", "are", "not", "already", "static", "t...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/contexts/text2sql_table_context.py#L145-L179
[ "def", "update_grammar_to_be_variable_free", "(", "grammar_dictionary", ":", "Dict", "[", "str", ",", "List", "[", "str", "]", "]", ")", ":", "# Tables in variable free grammars cannot be aliased, so we", "# remove this functionality from the grammar.", "grammar_dictionary", "[...
648a36f77db7e45784c047176074f98534c76636
train
update_grammar_with_untyped_entities
Variables can be treated as numbers or strings if their type can be inferred - however, that can be difficult, so instead, we can just treat them all as values and be a bit looser on the typing we allow in our grammar. Here we just remove all references to number and string from the grammar, replacing them ...
allennlp/semparse/contexts/text2sql_table_context.py
def update_grammar_with_untyped_entities(grammar_dictionary: Dict[str, List[str]]) -> None: """ Variables can be treated as numbers or strings if their type can be inferred - however, that can be difficult, so instead, we can just treat them all as values and be a bit looser on the typing we allow in ou...
def update_grammar_with_untyped_entities(grammar_dictionary: Dict[str, List[str]]) -> None: """ Variables can be treated as numbers or strings if their type can be inferred - however, that can be difficult, so instead, we can just treat them all as values and be a bit looser on the typing we allow in ou...
[ "Variables", "can", "be", "treated", "as", "numbers", "or", "strings", "if", "their", "type", "can", "be", "inferred", "-", "however", "that", "can", "be", "difficult", "so", "instead", "we", "can", "just", "treat", "them", "all", "as", "values", "and", ...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/contexts/text2sql_table_context.py#L181-L194
[ "def", "update_grammar_with_untyped_entities", "(", "grammar_dictionary", ":", "Dict", "[", "str", ",", "List", "[", "str", "]", "]", ")", "->", "None", ":", "grammar_dictionary", "[", "\"string_set_vals\"", "]", "=", "[", "'(value ws \",\" ws string_set_vals)'", ",...
648a36f77db7e45784c047176074f98534c76636
train
Ensemble._load
Ensembles don't have vocabularies or weights of their own, so they override _load.
allennlp/models/ensemble.py
def _load(cls, config: Params, serialization_dir: str, weights_file: str = None, cuda_device: int = -1) -> 'Model': """ Ensembles don't have vocabularies or weights of their own, so they override _load. """ model_params = config.get...
def _load(cls, config: Params, serialization_dir: str, weights_file: str = None, cuda_device: int = -1) -> 'Model': """ Ensembles don't have vocabularies or weights of their own, so they override _load. """ model_params = config.get...
[ "Ensembles", "don", "t", "have", "vocabularies", "or", "weights", "of", "their", "own", "so", "they", "override", "_load", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/models/ensemble.py#L34-L58
[ "def", "_load", "(", "cls", ",", "config", ":", "Params", ",", "serialization_dir", ":", "str", ",", "weights_file", ":", "str", "=", "None", ",", "cuda_device", ":", "int", "=", "-", "1", ")", "->", "'Model'", ":", "model_params", "=", "config", ".", ...
648a36f77db7e45784c047176074f98534c76636
train
text_standardize
Apply text standardization following original implementation.
allennlp/data/token_indexers/openai_transformer_byte_pair_indexer.py
def text_standardize(text): """ Apply text standardization following original implementation. """ text = text.replace('—', '-') text = text.replace('–', '-') text = text.replace('―', '-') text = text.replace('…', '...') text = text.replace('´', "'") text = re.sub(r'''(-+|~+|!+|"+|;+|...
def text_standardize(text): """ Apply text standardization following original implementation. """ text = text.replace('—', '-') text = text.replace('–', '-') text = text.replace('―', '-') text = text.replace('…', '...') text = text.replace('´', "'") text = re.sub(r'''(-+|~+|!+|"+|;+|...
[ "Apply", "text", "standardization", "following", "original", "implementation", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/data/token_indexers/openai_transformer_byte_pair_indexer.py#L15-L27
[ "def", "text_standardize", "(", "text", ")", ":", "text", "=", "text", ".", "replace", "(", "'—', ", "'", "')", "", "text", "=", "text", ".", "replace", "(", "'–', ", "'", "')", "", "text", "=", "text", ".", "replace", "(", "'―', ", "'", "')", ""...
648a36f77db7e45784c047176074f98534c76636
train
main
The :mod:`~allennlp.run` command only knows about the registered classes in the ``allennlp`` codebase. In particular, once you start creating your own ``Model`` s and so forth, it won't work for them, unless you use the ``--include-package`` flag.
allennlp/commands/__init__.py
def main(prog: str = None, subcommand_overrides: Dict[str, Subcommand] = {}) -> None: """ The :mod:`~allennlp.run` command only knows about the registered classes in the ``allennlp`` codebase. In particular, once you start creating your own ``Model`` s and so forth, it won't work for them, unle...
def main(prog: str = None, subcommand_overrides: Dict[str, Subcommand] = {}) -> None: """ The :mod:`~allennlp.run` command only knows about the registered classes in the ``allennlp`` codebase. In particular, once you start creating your own ``Model`` s and so forth, it won't work for them, unle...
[ "The", ":", "mod", ":", "~allennlp", ".", "run", "command", "only", "knows", "about", "the", "registered", "classes", "in", "the", "allennlp", "codebase", ".", "In", "particular", "once", "you", "start", "creating", "your", "own", "Model", "s", "and", "so"...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/commands/__init__.py#L52-L104
[ "def", "main", "(", "prog", ":", "str", "=", "None", ",", "subcommand_overrides", ":", "Dict", "[", "str", ",", "Subcommand", "]", "=", "{", "}", ")", "->", "None", ":", "# pylint: disable=dangerous-default-value", "parser", "=", "ArgumentParserWithDefaults", ...
648a36f77db7e45784c047176074f98534c76636
train
TextField.get_padding_lengths
The ``TextField`` has a list of ``Tokens``, and each ``Token`` gets converted into arrays by (potentially) several ``TokenIndexers``. This method gets the max length (over tokens) associated with each of these arrays.
allennlp/data/fields/text_field.py
def get_padding_lengths(self) -> Dict[str, int]: """ The ``TextField`` has a list of ``Tokens``, and each ``Token`` gets converted into arrays by (potentially) several ``TokenIndexers``. This method gets the max length (over tokens) associated with each of these arrays. """ ...
def get_padding_lengths(self) -> Dict[str, int]: """ The ``TextField`` has a list of ``Tokens``, and each ``Token`` gets converted into arrays by (potentially) several ``TokenIndexers``. This method gets the max length (over tokens) associated with each of these arrays. """ ...
[ "The", "TextField", "has", "a", "list", "of", "Tokens", "and", "each", "Token", "gets", "converted", "into", "arrays", "by", "(", "potentially", ")", "several", "TokenIndexers", ".", "This", "method", "gets", "the", "max", "length", "(", "over", "tokens", ...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/data/fields/text_field.py#L75-L125
[ "def", "get_padding_lengths", "(", "self", ")", "->", "Dict", "[", "str", ",", "int", "]", ":", "# Our basic outline: we will iterate over `TokenIndexers`, and aggregate lengths over tokens", "# for each indexer separately. Then we will combine the results for each indexer into a single...
648a36f77db7e45784c047176074f98534c76636
train
main
Creates ELMo word representations from a vocabulary file. These word representations are _independent_ - they are the result of running the CNN and Highway layers of the ELMo model, but not the Bidirectional LSTM. ELMo requires 2 additional tokens: <S> and </S>. The first token in this file is assumed t...
allennlp/tools/create_elmo_embeddings_from_vocab.py
def main(vocab_path: str, elmo_config_path: str, elmo_weights_path: str, output_dir: str, batch_size: int, device: int, use_custom_oov_token: bool = False): """ Creates ELMo word representations from a vocabulary file. These word representations are _ind...
def main(vocab_path: str, elmo_config_path: str, elmo_weights_path: str, output_dir: str, batch_size: int, device: int, use_custom_oov_token: bool = False): """ Creates ELMo word representations from a vocabulary file. These word representations are _ind...
[ "Creates", "ELMo", "word", "representations", "from", "a", "vocabulary", "file", ".", "These", "word", "representations", "are", "_independent_", "-", "they", "are", "the", "result", "of", "running", "the", "CNN", "and", "Highway", "layers", "of", "the", "ELMo...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/tools/create_elmo_embeddings_from_vocab.py#L16-L94
[ "def", "main", "(", "vocab_path", ":", "str", ",", "elmo_config_path", ":", "str", ",", "elmo_weights_path", ":", "str", ",", "output_dir", ":", "str", ",", "batch_size", ":", "int", ",", "device", ":", "int", ",", "use_custom_oov_token", ":", "bool", "=",...
648a36f77db7e45784c047176074f98534c76636
train
sort_by_padding
Sorts the instances by their padding lengths, using the keys in ``sorting_keys`` (in the order in which they are provided). ``sorting_keys`` is a list of ``(field_name, padding_key)`` tuples.
allennlp/data/iterators/bucket_iterator.py
def sort_by_padding(instances: List[Instance], sorting_keys: List[Tuple[str, str]], # pylint: disable=invalid-sequence-index vocab: Vocabulary, padding_noise: float = 0.0) -> List[Instance]: """ Sorts the instances by their padding lengths, using the ...
def sort_by_padding(instances: List[Instance], sorting_keys: List[Tuple[str, str]], # pylint: disable=invalid-sequence-index vocab: Vocabulary, padding_noise: float = 0.0) -> List[Instance]: """ Sorts the instances by their padding lengths, using the ...
[ "Sorts", "the", "instances", "by", "their", "padding", "lengths", "using", "the", "keys", "in", "sorting_keys", "(", "in", "the", "order", "in", "which", "they", "are", "provided", ")", ".", "sorting_keys", "is", "a", "list", "of", "(", "field_name", "padd...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/data/iterators/bucket_iterator.py#L17-L41
[ "def", "sort_by_padding", "(", "instances", ":", "List", "[", "Instance", "]", ",", "sorting_keys", ":", "List", "[", "Tuple", "[", "str", ",", "str", "]", "]", ",", "# pylint: disable=invalid-sequence-index", "vocab", ":", "Vocabulary", ",", "padding_noise", ...
648a36f77db7e45784c047176074f98534c76636
train
QuaRelLanguage.infer
Take the question and check if it is compatible with either of the answer choices.
allennlp/semparse/domain_languages/quarel_language.py
def infer(self, setup: QuaRelType, answer_0: QuaRelType, answer_1: QuaRelType) -> int: """ Take the question and check if it is compatible with either of the answer choices. """ if self._check_quarels_compatible(setup, answer_0): if self._check_quarels_compatible(setup, answe...
def infer(self, setup: QuaRelType, answer_0: QuaRelType, answer_1: QuaRelType) -> int: """ Take the question and check if it is compatible with either of the answer choices. """ if self._check_quarels_compatible(setup, answer_0): if self._check_quarels_compatible(setup, answe...
[ "Take", "the", "question", "and", "check", "if", "it", "is", "compatible", "with", "either", "of", "the", "answer", "choices", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/domain_languages/quarel_language.py#L97-L110
[ "def", "infer", "(", "self", ",", "setup", ":", "QuaRelType", ",", "answer_0", ":", "QuaRelType", ",", "answer_1", ":", "QuaRelType", ")", "->", "int", ":", "if", "self", ".", "_check_quarels_compatible", "(", "setup", ",", "answer_0", ")", ":", "if", "s...
648a36f77db7e45784c047176074f98534c76636
train
make_app
Creates a Flask app that serves up the provided ``Predictor`` along with a front-end for interacting with it. If you want to use the built-in bare-bones HTML, you must provide the field names for the inputs (which will be used both as labels and as the keys in the JSON that gets sent to the predictor)....
allennlp/service/server_simple.py
def make_app(predictor: Predictor, field_names: List[str] = None, static_dir: str = None, sanitizer: Callable[[JsonDict], JsonDict] = None, title: str = "AllenNLP Demo") -> Flask: """ Creates a Flask app that serves up the provided ``Predictor`` along with...
def make_app(predictor: Predictor, field_names: List[str] = None, static_dir: str = None, sanitizer: Callable[[JsonDict], JsonDict] = None, title: str = "AllenNLP Demo") -> Flask: """ Creates a Flask app that serves up the provided ``Predictor`` along with...
[ "Creates", "a", "Flask", "app", "that", "serves", "up", "the", "provided", "Predictor", "along", "with", "a", "front", "-", "end", "for", "interacting", "with", "it", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/service/server_simple.py#L53-L139
[ "def", "make_app", "(", "predictor", ":", "Predictor", ",", "field_names", ":", "List", "[", "str", "]", "=", "None", ",", "static_dir", ":", "str", "=", "None", ",", "sanitizer", ":", "Callable", "[", "[", "JsonDict", "]", ",", "JsonDict", "]", "=", ...
648a36f77db7e45784c047176074f98534c76636
train
_html
Returns bare bones HTML for serving up an input form with the specified fields that can render predictions from the configured model.
allennlp/service/server_simple.py
def _html(title: str, field_names: List[str]) -> str: """ Returns bare bones HTML for serving up an input form with the specified fields that can render predictions from the configured model. """ inputs = ''.join(_SINGLE_INPUT_TEMPLATE.substitute(field_name=field_name) for field...
def _html(title: str, field_names: List[str]) -> str: """ Returns bare bones HTML for serving up an input form with the specified fields that can render predictions from the configured model. """ inputs = ''.join(_SINGLE_INPUT_TEMPLATE.substitute(field_name=field_name) for field...
[ "Returns", "bare", "bones", "HTML", "for", "serving", "up", "an", "input", "form", "with", "the", "specified", "fields", "that", "can", "render", "predictions", "from", "the", "configured", "model", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/service/server_simple.py#L741-L755
[ "def", "_html", "(", "title", ":", "str", ",", "field_names", ":", "List", "[", "str", "]", ")", "->", "str", ":", "inputs", "=", "''", ".", "join", "(", "_SINGLE_INPUT_TEMPLATE", ".", "substitute", "(", "field_name", "=", "field_name", ")", "for", "fi...
648a36f77db7e45784c047176074f98534c76636
train
LambdaGrammarStatelet.get_valid_actions
Returns the valid actions in the current grammar state. See the class docstring for a description of what we're returning here.
allennlp/state_machines/states/lambda_grammar_statelet.py
def get_valid_actions(self) -> Dict[str, Tuple[torch.Tensor, torch.Tensor, List[int]]]: """ Returns the valid actions in the current grammar state. See the class docstring for a description of what we're returning here. """ actions = self._valid_actions[self._nonterminal_stack[-...
def get_valid_actions(self) -> Dict[str, Tuple[torch.Tensor, torch.Tensor, List[int]]]: """ Returns the valid actions in the current grammar state. See the class docstring for a description of what we're returning here. """ actions = self._valid_actions[self._nonterminal_stack[-...
[ "Returns", "the", "valid", "actions", "in", "the", "current", "grammar", "state", ".", "See", "the", "class", "docstring", "for", "a", "description", "of", "what", "we", "re", "returning", "here", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/state_machines/states/lambda_grammar_statelet.py#L77-L100
[ "def", "get_valid_actions", "(", "self", ")", "->", "Dict", "[", "str", ",", "Tuple", "[", "torch", ".", "Tensor", ",", "torch", ".", "Tensor", ",", "List", "[", "int", "]", "]", "]", ":", "actions", "=", "self", ".", "_valid_actions", "[", "self", ...
648a36f77db7e45784c047176074f98534c76636
train
LambdaGrammarStatelet.take_action
Takes an action in the current grammar state, returning a new grammar state with whatever updates are necessary. The production rule is assumed to be formatted as "LHS -> RHS". This will update the non-terminal stack and the context-dependent actions. Updating the non-terminal stack involves ...
allennlp/state_machines/states/lambda_grammar_statelet.py
def take_action(self, production_rule: str) -> 'LambdaGrammarStatelet': """ Takes an action in the current grammar state, returning a new grammar state with whatever updates are necessary. The production rule is assumed to be formatted as "LHS -> RHS". This will update the non-terminal...
def take_action(self, production_rule: str) -> 'LambdaGrammarStatelet': """ Takes an action in the current grammar state, returning a new grammar state with whatever updates are necessary. The production rule is assumed to be formatted as "LHS -> RHS". This will update the non-terminal...
[ "Takes", "an", "action", "in", "the", "current", "grammar", "state", "returning", "a", "new", "grammar", "state", "with", "whatever", "updates", "are", "necessary", ".", "The", "production", "rule", "is", "assumed", "to", "be", "formatted", "as", "LHS", "-",...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/state_machines/states/lambda_grammar_statelet.py#L102-L158
[ "def", "take_action", "(", "self", ",", "production_rule", ":", "str", ")", "->", "'LambdaGrammarStatelet'", ":", "left_side", ",", "right_side", "=", "production_rule", ".", "split", "(", "' -> '", ")", "assert", "self", ".", "_nonterminal_stack", "[", "-", "...
648a36f77db7e45784c047176074f98534c76636
train
decode_mst
Note: Counter to typical intuition, this function decodes the _maximum_ spanning tree. Decode the optimal MST tree with the Chu-Liu-Edmonds algorithm for maximum spanning arborescences on graphs. Parameters ---------- energy : ``numpy.ndarray``, required. A tensor with shape (num_label...
allennlp/nn/chu_liu_edmonds.py
def decode_mst(energy: numpy.ndarray, length: int, has_labels: bool = True) -> Tuple[numpy.ndarray, numpy.ndarray]: """ Note: Counter to typical intuition, this function decodes the _maximum_ spanning tree. Decode the optimal MST tree with the Chu-Liu-Edmonds algorithm for...
def decode_mst(energy: numpy.ndarray, length: int, has_labels: bool = True) -> Tuple[numpy.ndarray, numpy.ndarray]: """ Note: Counter to typical intuition, this function decodes the _maximum_ spanning tree. Decode the optimal MST tree with the Chu-Liu-Edmonds algorithm for...
[ "Note", ":", "Counter", "to", "typical", "intuition", "this", "function", "decodes", "the", "_maximum_", "spanning", "tree", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/nn/chu_liu_edmonds.py#L7-L85
[ "def", "decode_mst", "(", "energy", ":", "numpy", ".", "ndarray", ",", "length", ":", "int", ",", "has_labels", ":", "bool", "=", "True", ")", "->", "Tuple", "[", "numpy", ".", "ndarray", ",", "numpy", ".", "ndarray", "]", ":", "if", "has_labels", "a...
648a36f77db7e45784c047176074f98534c76636
train
chu_liu_edmonds
Applies the chu-liu-edmonds algorithm recursively to a graph with edge weights defined by score_matrix. Note that this function operates in place, so variables will be modified. Parameters ---------- length : ``int``, required. The number of nodes. score_matrix : ``numpy.ndarray``,...
allennlp/nn/chu_liu_edmonds.py
def chu_liu_edmonds(length: int, score_matrix: numpy.ndarray, current_nodes: List[bool], final_edges: Dict[int, int], old_input: numpy.ndarray, old_output: numpy.ndarray, representatives: List[Set[int...
def chu_liu_edmonds(length: int, score_matrix: numpy.ndarray, current_nodes: List[bool], final_edges: Dict[int, int], old_input: numpy.ndarray, old_output: numpy.ndarray, representatives: List[Set[int...
[ "Applies", "the", "chu", "-", "liu", "-", "edmonds", "algorithm", "recursively", "to", "a", "graph", "with", "edge", "weights", "defined", "by", "score_matrix", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/nn/chu_liu_edmonds.py#L87-L241
[ "def", "chu_liu_edmonds", "(", "length", ":", "int", ",", "score_matrix", ":", "numpy", ".", "ndarray", ",", "current_nodes", ":", "List", "[", "bool", "]", ",", "final_edges", ":", "Dict", "[", "int", ",", "int", "]", ",", "old_input", ":", "numpy", "...
648a36f77db7e45784c047176074f98534c76636
train
MovingAverage.assign_average_value
Replace all the parameter values with the averages. Save the current parameter values to restore later.
allennlp/training/moving_average.py
def assign_average_value(self) -> None: """ Replace all the parameter values with the averages. Save the current parameter values to restore later. """ for name, parameter in self._parameters: self._backups[name].copy_(parameter.data) parameter.data.copy_(...
def assign_average_value(self) -> None: """ Replace all the parameter values with the averages. Save the current parameter values to restore later. """ for name, parameter in self._parameters: self._backups[name].copy_(parameter.data) parameter.data.copy_(...
[ "Replace", "all", "the", "parameter", "values", "with", "the", "averages", ".", "Save", "the", "current", "parameter", "values", "to", "restore", "later", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/training/moving_average.py#L27-L34
[ "def", "assign_average_value", "(", "self", ")", "->", "None", ":", "for", "name", ",", "parameter", "in", "self", ".", "_parameters", ":", "self", ".", "_backups", "[", "name", "]", ".", "copy_", "(", "parameter", ".", "data", ")", "parameter", ".", "...
648a36f77db7e45784c047176074f98534c76636
train
MovingAverage.restore
Restore the backed-up (non-average) parameter values.
allennlp/training/moving_average.py
def restore(self) -> None: """ Restore the backed-up (non-average) parameter values. """ for name, parameter in self._parameters: parameter.data.copy_(self._backups[name])
def restore(self) -> None: """ Restore the backed-up (non-average) parameter values. """ for name, parameter in self._parameters: parameter.data.copy_(self._backups[name])
[ "Restore", "the", "backed", "-", "up", "(", "non", "-", "average", ")", "parameter", "values", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/training/moving_average.py#L36-L41
[ "def", "restore", "(", "self", ")", "->", "None", ":", "for", "name", ",", "parameter", "in", "self", ".", "_parameters", ":", "parameter", ".", "data", ".", "copy_", "(", "self", ".", "_backups", "[", "name", "]", ")" ]
648a36f77db7e45784c047176074f98534c76636
train
SimilarityFunction.forward
Takes two tensors of the same shape, such as ``(batch_size, length_1, length_2, embedding_dim)``. Computes a (possibly parameterized) similarity on the final dimension and returns a tensor with one less dimension, such as ``(batch_size, length_1, length_2)``.
allennlp/modules/similarity_functions/similarity_function.py
def forward(self, tensor_1: torch.Tensor, tensor_2: torch.Tensor) -> torch.Tensor: # pylint: disable=arguments-differ """ Takes two tensors of the same shape, such as ``(batch_size, length_1, length_2, embedding_dim)``. Computes a (possibly parameterized) similarity on the final dimensi...
def forward(self, tensor_1: torch.Tensor, tensor_2: torch.Tensor) -> torch.Tensor: # pylint: disable=arguments-differ """ Takes two tensors of the same shape, such as ``(batch_size, length_1, length_2, embedding_dim)``. Computes a (possibly parameterized) similarity on the final dimensi...
[ "Takes", "two", "tensors", "of", "the", "same", "shape", "such", "as", "(", "batch_size", "length_1", "length_2", "embedding_dim", ")", ".", "Computes", "a", "(", "possibly", "parameterized", ")", "similarity", "on", "the", "final", "dimension", "and", "return...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/modules/similarity_functions/similarity_function.py#L23-L30
[ "def", "forward", "(", "self", ",", "tensor_1", ":", "torch", ".", "Tensor", ",", "tensor_2", ":", "torch", ".", "Tensor", ")", "->", "torch", ".", "Tensor", ":", "# pylint: disable=arguments-differ", "raise", "NotImplementedError" ]
648a36f77db7e45784c047176074f98534c76636
train
ExpectedRiskMinimization._prune_beam
This method can be used to prune the set of unfinished states on a beam or finished states at the end of search. In the former case, the states need not be sorted because the all come from the same decoding step, which does the sorting. However, if the states are finished and this method is call...
allennlp/state_machines/trainers/expected_risk_minimization.py
def _prune_beam(states: List[State], beam_size: int, sort_states: bool = False) -> List[State]: """ This method can be used to prune the set of unfinished states on a beam or finished states at the end of search. In the former case, the states need not be ...
def _prune_beam(states: List[State], beam_size: int, sort_states: bool = False) -> List[State]: """ This method can be used to prune the set of unfinished states on a beam or finished states at the end of search. In the former case, the states need not be ...
[ "This", "method", "can", "be", "used", "to", "prune", "the", "set", "of", "unfinished", "states", "on", "a", "beam", "or", "finished", "states", "at", "the", "end", "of", "search", ".", "In", "the", "former", "case", "the", "states", "need", "not", "be...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/state_machines/trainers/expected_risk_minimization.py#L101-L125
[ "def", "_prune_beam", "(", "states", ":", "List", "[", "State", "]", ",", "beam_size", ":", "int", ",", "sort_states", ":", "bool", "=", "False", ")", "->", "List", "[", "State", "]", ":", "states_by_batch_index", ":", "Dict", "[", "int", ",", "List", ...
648a36f77db7e45784c047176074f98534c76636
train
ExpectedRiskMinimization._get_best_final_states
Returns the best finished states for each batch instance based on model scores. We return at most ``self._max_num_decoded_sequences`` number of sequences per instance.
allennlp/state_machines/trainers/expected_risk_minimization.py
def _get_best_final_states(self, finished_states: List[StateType]) -> Dict[int, List[StateType]]: """ Returns the best finished states for each batch instance based on model scores. We return at most ``self._max_num_decoded_sequences`` number of sequences per instance. """ batch_...
def _get_best_final_states(self, finished_states: List[StateType]) -> Dict[int, List[StateType]]: """ Returns the best finished states for each batch instance based on model scores. We return at most ``self._max_num_decoded_sequences`` number of sequences per instance. """ batch_...
[ "Returns", "the", "best", "finished", "states", "for", "each", "batch", "instance", "based", "on", "model", "scores", ".", "We", "return", "at", "most", "self", ".", "_max_num_decoded_sequences", "number", "of", "sequences", "per", "instance", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/state_machines/trainers/expected_risk_minimization.py#L151-L166
[ "def", "_get_best_final_states", "(", "self", ",", "finished_states", ":", "List", "[", "StateType", "]", ")", "->", "Dict", "[", "int", ",", "List", "[", "StateType", "]", "]", ":", "batch_states", ":", "Dict", "[", "int", ",", "List", "[", "StateType",...
648a36f77db7e45784c047176074f98534c76636
train
_read_pretrained_embeddings_file
Returns and embedding matrix for the given vocabulary using the pretrained embeddings contained in the given file. Embeddings for tokens not found in the pretrained embedding file are randomly initialized using a normal distribution with mean and standard deviation equal to those of the pretrained embedding...
allennlp/modules/token_embedders/embedding.py
def _read_pretrained_embeddings_file(file_uri: str, embedding_dim: int, vocab: Vocabulary, namespace: str = "tokens") -> torch.FloatTensor: """ Returns and embedding matrix for the given vocabulary usi...
def _read_pretrained_embeddings_file(file_uri: str, embedding_dim: int, vocab: Vocabulary, namespace: str = "tokens") -> torch.FloatTensor: """ Returns and embedding matrix for the given vocabulary usi...
[ "Returns", "and", "embedding", "matrix", "for", "the", "given", "vocabulary", "using", "the", "pretrained", "embeddings", "contained", "in", "the", "given", "file", ".", "Embeddings", "for", "tokens", "not", "found", "in", "the", "pretrained", "embedding", "file...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/modules/token_embedders/embedding.py#L317-L371
[ "def", "_read_pretrained_embeddings_file", "(", "file_uri", ":", "str", ",", "embedding_dim", ":", "int", ",", "vocab", ":", "Vocabulary", ",", "namespace", ":", "str", "=", "\"tokens\"", ")", "->", "torch", ".", "FloatTensor", ":", "file_ext", "=", "get_file_...
648a36f77db7e45784c047176074f98534c76636
train
_read_embeddings_from_text_file
Read pre-trained word vectors from an eventually compressed text file, possibly contained inside an archive with multiple files. The text file is assumed to be utf-8 encoded with space-separated fields: [word] [dim 1] [dim 2] ... Lines that contain more numerical tokens than ``embedding_dim`` raise a warni...
allennlp/modules/token_embedders/embedding.py
def _read_embeddings_from_text_file(file_uri: str, embedding_dim: int, vocab: Vocabulary, namespace: str = "tokens") -> torch.FloatTensor: """ Read pre-trained word vectors from an eventually compressed t...
def _read_embeddings_from_text_file(file_uri: str, embedding_dim: int, vocab: Vocabulary, namespace: str = "tokens") -> torch.FloatTensor: """ Read pre-trained word vectors from an eventually compressed t...
[ "Read", "pre", "-", "trained", "word", "vectors", "from", "an", "eventually", "compressed", "text", "file", "possibly", "contained", "inside", "an", "archive", "with", "multiple", "files", ".", "The", "text", "file", "is", "assumed", "to", "be", "utf", "-", ...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/modules/token_embedders/embedding.py#L374-L443
[ "def", "_read_embeddings_from_text_file", "(", "file_uri", ":", "str", ",", "embedding_dim", ":", "int", ",", "vocab", ":", "Vocabulary", ",", "namespace", ":", "str", "=", "\"tokens\"", ")", "->", "torch", ".", "FloatTensor", ":", "tokens_to_keep", "=", "set"...
648a36f77db7e45784c047176074f98534c76636
train
_read_embeddings_from_hdf5
Reads from a hdf5 formatted file. The embedding matrix is assumed to be keyed by 'embedding' and of size ``(num_tokens, embedding_dim)``.
allennlp/modules/token_embedders/embedding.py
def _read_embeddings_from_hdf5(embeddings_filename: str, embedding_dim: int, vocab: Vocabulary, namespace: str = "tokens") -> torch.FloatTensor: """ Reads from a hdf5 formatted file. The embedding matrix is assumed to ...
def _read_embeddings_from_hdf5(embeddings_filename: str, embedding_dim: int, vocab: Vocabulary, namespace: str = "tokens") -> torch.FloatTensor: """ Reads from a hdf5 formatted file. The embedding matrix is assumed to ...
[ "Reads", "from", "a", "hdf5", "formatted", "file", ".", "The", "embedding", "matrix", "is", "assumed", "to", "be", "keyed", "by", "embedding", "and", "of", "size", "(", "num_tokens", "embedding_dim", ")", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/modules/token_embedders/embedding.py#L446-L462
[ "def", "_read_embeddings_from_hdf5", "(", "embeddings_filename", ":", "str", ",", "embedding_dim", ":", "int", ",", "vocab", ":", "Vocabulary", ",", "namespace", ":", "str", "=", "\"tokens\"", ")", "->", "torch", ".", "FloatTensor", ":", "with", "h5py", ".", ...
648a36f77db7e45784c047176074f98534c76636
train
EmbeddingsTextFile._get_num_tokens_from_first_line
This function takes in input a string and if it contains 1 or 2 integers, it assumes the largest one it the number of tokens. Returns None if the line doesn't match that pattern.
allennlp/modules/token_embedders/embedding.py
def _get_num_tokens_from_first_line(line: str) -> Optional[int]: """ This function takes in input a string and if it contains 1 or 2 integers, it assumes the largest one it the number of tokens. Returns None if the line doesn't match that pattern. """ fields = line.split(' ') if 1 <= len...
def _get_num_tokens_from_first_line(line: str) -> Optional[int]: """ This function takes in input a string and if it contains 1 or 2 integers, it assumes the largest one it the number of tokens. Returns None if the line doesn't match that pattern. """ fields = line.split(' ') if 1 <= len...
[ "This", "function", "takes", "in", "input", "a", "string", "and", "if", "it", "contains", "1", "or", "2", "integers", "it", "assumes", "the", "largest", "one", "it", "the", "number", "of", "tokens", ".", "Returns", "None", "if", "the", "line", "doesn", ...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/modules/token_embedders/embedding.py#L632-L646
[ "def", "_get_num_tokens_from_first_line", "(", "line", ":", "str", ")", "->", "Optional", "[", "int", "]", ":", "fields", "=", "line", ".", "split", "(", "' '", ")", "if", "1", "<=", "len", "(", "fields", ")", "<=", "2", ":", "try", ":", "int_fields"...
648a36f77db7e45784c047176074f98534c76636
train
CoverageTransitionFunction._get_predicted_embedding_addition
Gets the embeddings of desired terminal actions yet to be produced by the decoder, and returns their sum for the decoder to add it to the predicted embedding to bias the prediction towards missing actions.
allennlp/state_machines/transition_functions/coverage_transition_function.py
def _get_predicted_embedding_addition(self, checklist_state: ChecklistStatelet, action_ids: List[int], action_embeddings: torch.Tensor) -> torch.Tensor: """ Gets the embeddings o...
def _get_predicted_embedding_addition(self, checklist_state: ChecklistStatelet, action_ids: List[int], action_embeddings: torch.Tensor) -> torch.Tensor: """ Gets the embeddings o...
[ "Gets", "the", "embeddings", "of", "desired", "terminal", "actions", "yet", "to", "be", "produced", "by", "the", "decoder", "and", "returns", "their", "sum", "for", "the", "decoder", "to", "add", "it", "to", "the", "predicted", "embedding", "to", "bias", "...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/state_machines/transition_functions/coverage_transition_function.py#L115-L160
[ "def", "_get_predicted_embedding_addition", "(", "self", ",", "checklist_state", ":", "ChecklistStatelet", ",", "action_ids", ":", "List", "[", "int", "]", ",", "action_embeddings", ":", "torch", ".", "Tensor", ")", "->", "torch", ".", "Tensor", ":", "# Our basi...
648a36f77db7e45784c047176074f98534c76636
train
_create_tensor_dicts
Pulls at most ``max_instances_in_memory`` from the input_queue, groups them into batches of size ``batch_size``, converts them to ``TensorDict`` s, and puts them on the ``output_queue``.
allennlp/data/iterators/multiprocess_iterator.py
def _create_tensor_dicts(input_queue: Queue, output_queue: Queue, iterator: DataIterator, shuffle: bool, index: int) -> None: """ Pulls at most ``max_instances_in_memory`` from the input_queue, groups them in...
def _create_tensor_dicts(input_queue: Queue, output_queue: Queue, iterator: DataIterator, shuffle: bool, index: int) -> None: """ Pulls at most ``max_instances_in_memory`` from the input_queue, groups them in...
[ "Pulls", "at", "most", "max_instances_in_memory", "from", "the", "input_queue", "groups", "them", "into", "batches", "of", "size", "batch_size", "converts", "them", "to", "TensorDict", "s", "and", "puts", "them", "on", "the", "output_queue", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/data/iterators/multiprocess_iterator.py#L15-L34
[ "def", "_create_tensor_dicts", "(", "input_queue", ":", "Queue", ",", "output_queue", ":", "Queue", ",", "iterator", ":", "DataIterator", ",", "shuffle", ":", "bool", ",", "index", ":", "int", ")", "->", "None", ":", "def", "instances", "(", ")", "->", "...
648a36f77db7e45784c047176074f98534c76636
train
_queuer
Reads Instances from the iterable and puts them in the input_queue.
allennlp/data/iterators/multiprocess_iterator.py
def _queuer(instances: Iterable[Instance], input_queue: Queue, num_workers: int, num_epochs: Optional[int]) -> None: """ Reads Instances from the iterable and puts them in the input_queue. """ epoch = 0 while num_epochs is None or epoch < num_epochs: epoc...
def _queuer(instances: Iterable[Instance], input_queue: Queue, num_workers: int, num_epochs: Optional[int]) -> None: """ Reads Instances from the iterable and puts them in the input_queue. """ epoch = 0 while num_epochs is None or epoch < num_epochs: epoc...
[ "Reads", "Instances", "from", "the", "iterable", "and", "puts", "them", "in", "the", "input_queue", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/data/iterators/multiprocess_iterator.py#L36-L53
[ "def", "_queuer", "(", "instances", ":", "Iterable", "[", "Instance", "]", ",", "input_queue", ":", "Queue", ",", "num_workers", ":", "int", ",", "num_epochs", ":", "Optional", "[", "int", "]", ")", "->", "None", ":", "epoch", "=", "0", "while", "num_e...
648a36f77db7e45784c047176074f98534c76636
train
GrammarBasedState.get_valid_actions
Returns a list of valid actions for each element of the group.
allennlp/state_machines/states/grammar_based_state.py
def get_valid_actions(self) -> List[Dict[str, Tuple[torch.Tensor, torch.Tensor, List[int]]]]: """ Returns a list of valid actions for each element of the group. """ return [state.get_valid_actions() for state in self.grammar_state]
def get_valid_actions(self) -> List[Dict[str, Tuple[torch.Tensor, torch.Tensor, List[int]]]]: """ Returns a list of valid actions for each element of the group. """ return [state.get_valid_actions() for state in self.grammar_state]
[ "Returns", "a", "list", "of", "valid", "actions", "for", "each", "element", "of", "the", "group", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/state_machines/states/grammar_based_state.py#L110-L114
[ "def", "get_valid_actions", "(", "self", ")", "->", "List", "[", "Dict", "[", "str", ",", "Tuple", "[", "torch", ".", "Tensor", ",", "torch", ".", "Tensor", ",", "List", "[", "int", "]", "]", "]", "]", ":", "return", "[", "state", ".", "get_valid_a...
648a36f77db7e45784c047176074f98534c76636
train
_worker
A worker that pulls filenames off the input queue, uses the dataset reader to read them, and places the generated instances on the output queue. When there are no filenames left on the input queue, it puts its ``index`` on the output queue and doesn't do anything else.
allennlp/data/dataset_readers/multiprocess_dataset_reader.py
def _worker(reader: DatasetReader, input_queue: Queue, output_queue: Queue, index: int) -> None: """ A worker that pulls filenames off the input queue, uses the dataset reader to read them, and places the generated instances on the output queue. When there are no file...
def _worker(reader: DatasetReader, input_queue: Queue, output_queue: Queue, index: int) -> None: """ A worker that pulls filenames off the input queue, uses the dataset reader to read them, and places the generated instances on the output queue. When there are no file...
[ "A", "worker", "that", "pulls", "filenames", "off", "the", "input", "queue", "uses", "the", "dataset", "reader", "to", "read", "them", "and", "places", "the", "generated", "instances", "on", "the", "output", "queue", ".", "When", "there", "are", "no", "fil...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/data/dataset_readers/multiprocess_dataset_reader.py#L30-L50
[ "def", "_worker", "(", "reader", ":", "DatasetReader", ",", "input_queue", ":", "Queue", ",", "output_queue", ":", "Queue", ",", "index", ":", "int", ")", "->", "None", ":", "# Keep going until you get a file_path that's None.", "while", "True", ":", "file_path", ...
648a36f77db7e45784c047176074f98534c76636
train
allowed_transitions
Given labels and a constraint type, returns the allowed transitions. It will additionally include transitions for the start and end states, which are used by the conditional random field. Parameters ---------- constraint_type : ``str``, required Indicates which constraint to apply. Current ...
allennlp/modules/conditional_random_field.py
def allowed_transitions(constraint_type: str, labels: Dict[int, str]) -> List[Tuple[int, int]]: """ Given labels and a constraint type, returns the allowed transitions. It will additionally include transitions for the start and end states, which are used by the conditional random field. Parameters ...
def allowed_transitions(constraint_type: str, labels: Dict[int, str]) -> List[Tuple[int, int]]: """ Given labels and a constraint type, returns the allowed transitions. It will additionally include transitions for the start and end states, which are used by the conditional random field. Parameters ...
[ "Given", "labels", "and", "a", "constraint", "type", "returns", "the", "allowed", "transitions", ".", "It", "will", "additionally", "include", "transitions", "for", "the", "start", "and", "end", "states", "which", "are", "used", "by", "the", "conditional", "ra...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/modules/conditional_random_field.py#L12-L55
[ "def", "allowed_transitions", "(", "constraint_type", ":", "str", ",", "labels", ":", "Dict", "[", "int", ",", "str", "]", ")", "->", "List", "[", "Tuple", "[", "int", ",", "int", "]", "]", ":", "num_labels", "=", "len", "(", "labels", ")", "start_ta...
648a36f77db7e45784c047176074f98534c76636
train
is_transition_allowed
Given a constraint type and strings ``from_tag`` and ``to_tag`` that represent the origin and destination of the transition, return whether the transition is allowed under the given constraint type. Parameters ---------- constraint_type : ``str``, required Indicates which constraint to appl...
allennlp/modules/conditional_random_field.py
def is_transition_allowed(constraint_type: str, from_tag: str, from_entity: str, to_tag: str, to_entity: str): """ Given a constraint type and strings ``from_tag`` and ``to_tag`` that represent the origin...
def is_transition_allowed(constraint_type: str, from_tag: str, from_entity: str, to_tag: str, to_entity: str): """ Given a constraint type and strings ``from_tag`` and ``to_tag`` that represent the origin...
[ "Given", "a", "constraint", "type", "and", "strings", "from_tag", "and", "to_tag", "that", "represent", "the", "origin", "and", "destination", "of", "the", "transition", "return", "whether", "the", "transition", "is", "allowed", "under", "the", "given", "constra...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/modules/conditional_random_field.py#L58-L149
[ "def", "is_transition_allowed", "(", "constraint_type", ":", "str", ",", "from_tag", ":", "str", ",", "from_entity", ":", "str", ",", "to_tag", ":", "str", ",", "to_entity", ":", "str", ")", ":", "# pylint: disable=too-many-return-statements", "if", "to_tag", "=...
648a36f77db7e45784c047176074f98534c76636
train
ConditionalRandomField._input_likelihood
Computes the (batch_size,) denominator term for the log-likelihood, which is the sum of the likelihoods across all possible state sequences.
allennlp/modules/conditional_random_field.py
def _input_likelihood(self, logits: torch.Tensor, mask: torch.Tensor) -> torch.Tensor: """ Computes the (batch_size,) denominator term for the log-likelihood, which is the sum of the likelihoods across all possible state sequences. """ batch_size, sequence_length, num_tags = logi...
def _input_likelihood(self, logits: torch.Tensor, mask: torch.Tensor) -> torch.Tensor: """ Computes the (batch_size,) denominator term for the log-likelihood, which is the sum of the likelihoods across all possible state sequences. """ batch_size, sequence_length, num_tags = logi...
[ "Computes", "the", "(", "batch_size", ")", "denominator", "term", "for", "the", "log", "-", "likelihood", "which", "is", "the", "sum", "of", "the", "likelihoods", "across", "all", "possible", "state", "sequences", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/modules/conditional_random_field.py#L207-L251
[ "def", "_input_likelihood", "(", "self", ",", "logits", ":", "torch", ".", "Tensor", ",", "mask", ":", "torch", ".", "Tensor", ")", "->", "torch", ".", "Tensor", ":", "batch_size", ",", "sequence_length", ",", "num_tags", "=", "logits", ".", "size", "(",...
648a36f77db7e45784c047176074f98534c76636
train
ConditionalRandomField._joint_likelihood
Computes the numerator term for the log-likelihood, which is just score(inputs, tags)
allennlp/modules/conditional_random_field.py
def _joint_likelihood(self, logits: torch.Tensor, tags: torch.Tensor, mask: torch.LongTensor) -> torch.Tensor: """ Computes the numerator term for the log-likelihood, which is just score(inputs, tags) """ batch...
def _joint_likelihood(self, logits: torch.Tensor, tags: torch.Tensor, mask: torch.LongTensor) -> torch.Tensor: """ Computes the numerator term for the log-likelihood, which is just score(inputs, tags) """ batch...
[ "Computes", "the", "numerator", "term", "for", "the", "log", "-", "likelihood", "which", "is", "just", "score", "(", "inputs", "tags", ")" ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/modules/conditional_random_field.py#L253-L306
[ "def", "_joint_likelihood", "(", "self", ",", "logits", ":", "torch", ".", "Tensor", ",", "tags", ":", "torch", ".", "Tensor", ",", "mask", ":", "torch", ".", "LongTensor", ")", "->", "torch", ".", "Tensor", ":", "batch_size", ",", "sequence_length", ","...
648a36f77db7e45784c047176074f98534c76636
train
ConditionalRandomField.forward
Computes the log likelihood.
allennlp/modules/conditional_random_field.py
def forward(self, inputs: torch.Tensor, tags: torch.Tensor, mask: torch.ByteTensor = None) -> torch.Tensor: """ Computes the log likelihood. """ # pylint: disable=arguments-differ if mask is None: mask = torch.ones(*tags...
def forward(self, inputs: torch.Tensor, tags: torch.Tensor, mask: torch.ByteTensor = None) -> torch.Tensor: """ Computes the log likelihood. """ # pylint: disable=arguments-differ if mask is None: mask = torch.ones(*tags...
[ "Computes", "the", "log", "likelihood", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/modules/conditional_random_field.py#L308-L322
[ "def", "forward", "(", "self", ",", "inputs", ":", "torch", ".", "Tensor", ",", "tags", ":", "torch", ".", "Tensor", ",", "mask", ":", "torch", ".", "ByteTensor", "=", "None", ")", "->", "torch", ".", "Tensor", ":", "# pylint: disable=arguments-differ", ...
648a36f77db7e45784c047176074f98534c76636
train
ConditionalRandomField.viterbi_tags
Uses viterbi algorithm to find most likely tags for the given inputs. If constraints are applied, disallows all other transitions.
allennlp/modules/conditional_random_field.py
def viterbi_tags(self, logits: torch.Tensor, mask: torch.Tensor) -> List[Tuple[List[int], float]]: """ Uses viterbi algorithm to find most likely tags for the given inputs. If constraints are applied, disallows all other transitions. """ ...
def viterbi_tags(self, logits: torch.Tensor, mask: torch.Tensor) -> List[Tuple[List[int], float]]: """ Uses viterbi algorithm to find most likely tags for the given inputs. If constraints are applied, disallows all other transitions. """ ...
[ "Uses", "viterbi", "algorithm", "to", "find", "most", "likely", "tags", "for", "the", "given", "inputs", ".", "If", "constraints", "are", "applied", "disallows", "all", "other", "transitions", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/modules/conditional_random_field.py#L324-L384
[ "def", "viterbi_tags", "(", "self", ",", "logits", ":", "torch", ".", "Tensor", ",", "mask", ":", "torch", ".", "Tensor", ")", "->", "List", "[", "Tuple", "[", "List", "[", "int", "]", ",", "float", "]", "]", ":", "_", ",", "max_seq_length", ",", ...
648a36f77db7e45784c047176074f98534c76636
train
BeamSearch.search
Given a starting state and a step function, apply beam search to find the most likely target sequences. Notes ----- If your step function returns ``-inf`` for some log probabilities (like if you're using a masked log-softmax) then some of the "best" sequences returned ma...
allennlp/nn/beam_search.py
def search(self, start_predictions: torch.Tensor, start_state: StateType, step: StepFunctionType) -> Tuple[torch.Tensor, torch.Tensor]: """ Given a starting state and a step function, apply beam search to find the most likely target sequences. ...
def search(self, start_predictions: torch.Tensor, start_state: StateType, step: StepFunctionType) -> Tuple[torch.Tensor, torch.Tensor]: """ Given a starting state and a step function, apply beam search to find the most likely target sequences. ...
[ "Given", "a", "starting", "state", "and", "a", "step", "function", "apply", "beam", "search", "to", "find", "the", "most", "likely", "target", "sequences", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/nn/beam_search.py#L44-L276
[ "def", "search", "(", "self", ",", "start_predictions", ":", "torch", ".", "Tensor", ",", "start_state", ":", "StateType", ",", "step", ":", "StepFunctionType", ")", "->", "Tuple", "[", "torch", ".", "Tensor", ",", "torch", ".", "Tensor", "]", ":", "batc...
648a36f77db7e45784c047176074f98534c76636
train
main
Parameters ---------- data_directory : str, required. The path to the data directory of https://github.com/jkkummerfeld/text2sql-data which has been preprocessed using scripts/reformat_text2sql_data.py. dataset : str, optional. The dataset to parse. By default all are parsed. fil...
scripts/examine_sql_coverage.py
def main(data_directory: int, dataset: str = None, filter_by: str = None, verbose: bool = False) -> None: """ Parameters ---------- data_directory : str, required. The path to the data directory of https://github.com/jkkummerfeld/text2sql-data which has been preprocessed using scripts/re...
def main(data_directory: int, dataset: str = None, filter_by: str = None, verbose: bool = False) -> None: """ Parameters ---------- data_directory : str, required. The path to the data directory of https://github.com/jkkummerfeld/text2sql-data which has been preprocessed using scripts/re...
[ "Parameters", "----------", "data_directory", ":", "str", "required", ".", "The", "path", "to", "the", "data", "directory", "of", "https", ":", "//", "github", ".", "com", "/", "jkkummerfeld", "/", "text2sql", "-", "data", "which", "has", "been", "preprocess...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/scripts/examine_sql_coverage.py#L91-L132
[ "def", "main", "(", "data_directory", ":", "int", ",", "dataset", ":", "str", "=", "None", ",", "filter_by", ":", "str", "=", "None", ",", "verbose", ":", "bool", "=", "False", ")", "->", "None", ":", "directory_dict", "=", "{", "path", ":", "files",...
648a36f77db7e45784c047176074f98534c76636
train
takes_arg
Checks whether the provided obj takes a certain arg. If it's a class, we're really checking whether its constructor does. If it's a function or method, we're checking the object itself. Otherwise, we raise an error.
allennlp/common/from_params.py
def takes_arg(obj, arg: str) -> bool: """ Checks whether the provided obj takes a certain arg. If it's a class, we're really checking whether its constructor does. If it's a function or method, we're checking the object itself. Otherwise, we raise an error. """ if inspect.isclass(obj): ...
def takes_arg(obj, arg: str) -> bool: """ Checks whether the provided obj takes a certain arg. If it's a class, we're really checking whether its constructor does. If it's a function or method, we're checking the object itself. Otherwise, we raise an error. """ if inspect.isclass(obj): ...
[ "Checks", "whether", "the", "provided", "obj", "takes", "a", "certain", "arg", ".", "If", "it", "s", "a", "class", "we", "re", "really", "checking", "whether", "its", "constructor", "does", ".", "If", "it", "s", "a", "function", "or", "method", "we", "...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/common/from_params.py#L59-L72
[ "def", "takes_arg", "(", "obj", ",", "arg", ":", "str", ")", "->", "bool", ":", "if", "inspect", ".", "isclass", "(", "obj", ")", ":", "signature", "=", "inspect", ".", "signature", "(", "obj", ".", "__init__", ")", "elif", "inspect", ".", "ismethod"...
648a36f77db7e45784c047176074f98534c76636
train
takes_kwargs
Checks whether a provided object takes in any positional arguments. Similar to takes_arg, we do this for both the __init__ function of the class or a function / method Otherwise, we raise an error
allennlp/common/from_params.py
def takes_kwargs(obj) -> bool: """ Checks whether a provided object takes in any positional arguments. Similar to takes_arg, we do this for both the __init__ function of the class or a function / method Otherwise, we raise an error """ if inspect.isclass(obj): signature = inspect.sig...
def takes_kwargs(obj) -> bool: """ Checks whether a provided object takes in any positional arguments. Similar to takes_arg, we do this for both the __init__ function of the class or a function / method Otherwise, we raise an error """ if inspect.isclass(obj): signature = inspect.sig...
[ "Checks", "whether", "a", "provided", "object", "takes", "in", "any", "positional", "arguments", ".", "Similar", "to", "takes_arg", "we", "do", "this", "for", "both", "the", "__init__", "function", "of", "the", "class", "or", "a", "function", "/", "method", ...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/common/from_params.py#L75-L89
[ "def", "takes_kwargs", "(", "obj", ")", "->", "bool", ":", "if", "inspect", ".", "isclass", "(", "obj", ")", ":", "signature", "=", "inspect", ".", "signature", "(", "obj", ".", "__init__", ")", "elif", "inspect", ".", "ismethod", "(", "obj", ")", "o...
648a36f77db7e45784c047176074f98534c76636
train
remove_optional
Optional[X] annotations are actually represented as Union[X, NoneType]. For our purposes, the "Optional" part is not interesting, so here we throw it away.
allennlp/common/from_params.py
def remove_optional(annotation: type): """ Optional[X] annotations are actually represented as Union[X, NoneType]. For our purposes, the "Optional" part is not interesting, so here we throw it away. """ origin = getattr(annotation, '__origin__', None) args = getattr(annotation, '__args__', (...
def remove_optional(annotation: type): """ Optional[X] annotations are actually represented as Union[X, NoneType]. For our purposes, the "Optional" part is not interesting, so here we throw it away. """ origin = getattr(annotation, '__origin__', None) args = getattr(annotation, '__args__', (...
[ "Optional", "[", "X", "]", "annotations", "are", "actually", "represented", "as", "Union", "[", "X", "NoneType", "]", ".", "For", "our", "purposes", "the", "Optional", "part", "is", "not", "interesting", "so", "here", "we", "throw", "it", "away", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/common/from_params.py#L92-L103
[ "def", "remove_optional", "(", "annotation", ":", "type", ")", ":", "origin", "=", "getattr", "(", "annotation", ",", "'__origin__'", ",", "None", ")", "args", "=", "getattr", "(", "annotation", ",", "'__args__'", ",", "(", ")", ")", "if", "origin", "=="...
648a36f77db7e45784c047176074f98534c76636
train
create_kwargs
Given some class, a `Params` object, and potentially other keyword arguments, create a dict of keyword args suitable for passing to the class's constructor. The function does this by finding the class's constructor, matching the constructor arguments to entries in the `params` object, and instantiating val...
allennlp/common/from_params.py
def create_kwargs(cls: Type[T], params: Params, **extras) -> Dict[str, Any]: """ Given some class, a `Params` object, and potentially other keyword arguments, create a dict of keyword args suitable for passing to the class's constructor. The function does this by finding the class's constructor, matchi...
def create_kwargs(cls: Type[T], params: Params, **extras) -> Dict[str, Any]: """ Given some class, a `Params` object, and potentially other keyword arguments, create a dict of keyword args suitable for passing to the class's constructor. The function does this by finding the class's constructor, matchi...
[ "Given", "some", "class", "a", "Params", "object", "and", "potentially", "other", "keyword", "arguments", "create", "a", "dict", "of", "keyword", "args", "suitable", "for", "passing", "to", "the", "class", "s", "constructor", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/common/from_params.py#L105-L136
[ "def", "create_kwargs", "(", "cls", ":", "Type", "[", "T", "]", ",", "params", ":", "Params", ",", "*", "*", "extras", ")", "->", "Dict", "[", "str", ",", "Any", "]", ":", "# Get the signature of the constructor.", "signature", "=", "inspect", ".", "sign...
648a36f77db7e45784c047176074f98534c76636
train
create_extras
Given a dictionary of extra arguments, returns a dictionary of kwargs that actually are a part of the signature of the cls.from_params (or cls) method.
allennlp/common/from_params.py
def create_extras(cls: Type[T], extras: Dict[str, Any]) -> Dict[str, Any]: """ Given a dictionary of extra arguments, returns a dictionary of kwargs that actually are a part of the signature of the cls.from_params (or cls) method. """ subextras: Dict[str, Any] = {} if hasat...
def create_extras(cls: Type[T], extras: Dict[str, Any]) -> Dict[str, Any]: """ Given a dictionary of extra arguments, returns a dictionary of kwargs that actually are a part of the signature of the cls.from_params (or cls) method. """ subextras: Dict[str, Any] = {} if hasat...
[ "Given", "a", "dictionary", "of", "extra", "arguments", "returns", "a", "dictionary", "of", "kwargs", "that", "actually", "are", "a", "part", "of", "the", "signature", "of", "the", "cls", ".", "from_params", "(", "or", "cls", ")", "method", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/common/from_params.py#L139-L166
[ "def", "create_extras", "(", "cls", ":", "Type", "[", "T", "]", ",", "extras", ":", "Dict", "[", "str", ",", "Any", "]", ")", "->", "Dict", "[", "str", ",", "Any", "]", ":", "subextras", ":", "Dict", "[", "str", ",", "Any", "]", "=", "{", "}"...
648a36f77db7e45784c047176074f98534c76636
train
construct_arg
Does the work of actually constructing an individual argument for :func:`create_kwargs`. Here we're in the inner loop of iterating over the parameters to a particular constructor, trying to construct just one of them. The information we get for that parameter is its name, its type annotation, and its defa...
allennlp/common/from_params.py
def construct_arg(cls: Type[T], # pylint: disable=inconsistent-return-statements,too-many-return-statements param_name: str, annotation: Type, default: Any, params: Params, **extras) -> Any: """ Does the work of actually c...
def construct_arg(cls: Type[T], # pylint: disable=inconsistent-return-statements,too-many-return-statements param_name: str, annotation: Type, default: Any, params: Params, **extras) -> Any: """ Does the work of actually c...
[ "Does", "the", "work", "of", "actually", "constructing", "an", "individual", "argument", "for", ":", "func", ":", "create_kwargs", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/common/from_params.py#L169-L318
[ "def", "construct_arg", "(", "cls", ":", "Type", "[", "T", "]", ",", "# pylint: disable=inconsistent-return-statements,too-many-return-statements", "param_name", ":", "str", ",", "annotation", ":", "Type", ",", "default", ":", "Any", ",", "params", ":", "Params", ...
648a36f77db7e45784c047176074f98534c76636
train
FromParams.from_params
This is the automatic implementation of `from_params`. Any class that subclasses `FromParams` (or `Registrable`, which itself subclasses `FromParams`) gets this implementation for free. If you want your class to be instantiated from params in the "obvious" way -- pop off parameters and hand them...
allennlp/common/from_params.py
def from_params(cls: Type[T], params: Params, **extras) -> T: """ This is the automatic implementation of `from_params`. Any class that subclasses `FromParams` (or `Registrable`, which itself subclasses `FromParams`) gets this implementation for free. If you want your class to be instant...
def from_params(cls: Type[T], params: Params, **extras) -> T: """ This is the automatic implementation of `from_params`. Any class that subclasses `FromParams` (or `Registrable`, which itself subclasses `FromParams`) gets this implementation for free. If you want your class to be instant...
[ "This", "is", "the", "automatic", "implementation", "of", "from_params", ".", "Any", "class", "that", "subclasses", "FromParams", "(", "or", "Registrable", "which", "itself", "subclasses", "FromParams", ")", "gets", "this", "implementation", "for", "free", ".", ...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/common/from_params.py#L327-L388
[ "def", "from_params", "(", "cls", ":", "Type", "[", "T", "]", ",", "params", ":", "Params", ",", "*", "*", "extras", ")", "->", "T", ":", "# pylint: disable=protected-access", "from", "allennlp", ".", "common", ".", "registrable", "import", "Registrable", ...
648a36f77db7e45784c047176074f98534c76636
train
TransitionFunction.take_step
The main method in the ``TransitionFunction`` API. This function defines the computation done at each step of decoding and returns a ranked list of next states. The input state is `grouped`, to allow for efficient computation, but the output states should all have a ``group_size`` of 1, to mak...
allennlp/state_machines/transition_functions/transition_function.py
def take_step(self, state: StateType, max_actions: int = None, allowed_actions: List[Set] = None) -> List[StateType]: """ The main method in the ``TransitionFunction`` API. This function defines the computation done at each step of decoding ...
def take_step(self, state: StateType, max_actions: int = None, allowed_actions: List[Set] = None) -> List[StateType]: """ The main method in the ``TransitionFunction`` API. This function defines the computation done at each step of decoding ...
[ "The", "main", "method", "in", "the", "TransitionFunction", "API", ".", "This", "function", "defines", "the", "computation", "done", "at", "each", "step", "of", "decoding", "and", "returns", "a", "ranked", "list", "of", "next", "states", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/state_machines/transition_functions/transition_function.py#L23-L82
[ "def", "take_step", "(", "self", ",", "state", ":", "StateType", ",", "max_actions", ":", "int", "=", "None", ",", "allowed_actions", ":", "List", "[", "Set", "]", "=", "None", ")", "->", "List", "[", "StateType", "]", ":", "raise", "NotImplementedError"...
648a36f77db7e45784c047176074f98534c76636
train
_safe_sparse_mask
In PyTorch 1.0, Tensor._sparse_mask was changed to Tensor.sparse_mask. This wrapper allows AllenNLP to (temporarily) work with both 1.0 and 0.4.1.
allennlp/training/optimizers.py
def _safe_sparse_mask(tensor: torch.Tensor, mask: torch.Tensor) -> torch.Tensor: """ In PyTorch 1.0, Tensor._sparse_mask was changed to Tensor.sparse_mask. This wrapper allows AllenNLP to (temporarily) work with both 1.0 and 0.4.1. """ # pylint: disable=protected-access try: return tenso...
def _safe_sparse_mask(tensor: torch.Tensor, mask: torch.Tensor) -> torch.Tensor: """ In PyTorch 1.0, Tensor._sparse_mask was changed to Tensor.sparse_mask. This wrapper allows AllenNLP to (temporarily) work with both 1.0 and 0.4.1. """ # pylint: disable=protected-access try: return tenso...
[ "In", "PyTorch", "1", ".", "0", "Tensor", ".", "_sparse_mask", "was", "changed", "to", "Tensor", ".", "sparse_mask", ".", "This", "wrapper", "allows", "AllenNLP", "to", "(", "temporarily", ")", "work", "with", "both", "1", ".", "0", "and", "0", ".", "4...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/training/optimizers.py#L147-L157
[ "def", "_safe_sparse_mask", "(", "tensor", ":", "torch", ".", "Tensor", ",", "mask", ":", "torch", ".", "Tensor", ")", "->", "torch", ".", "Tensor", ":", "# pylint: disable=protected-access", "try", ":", "return", "tensor", ".", "sparse_mask", "(", "mask", "...
648a36f77db7e45784c047176074f98534c76636
train
parse_sentence
Parses a chunk of text in the SemEval SDP format. Each word in the sentence is returned as a dictionary with the following format: 'id': '1', 'form': 'Pierre', 'lemma': 'Pierre', 'pos': 'NNP', 'head': '2', # Note that this is the `syntactic` head. 'deprel': 'nn', 'top': '-', '...
allennlp/data/dataset_readers/semantic_dependency_parsing.py
def parse_sentence(sentence_blob: str) -> Tuple[List[Dict[str, str]], List[Tuple[int, int]], List[str]]: """ Parses a chunk of text in the SemEval SDP format. Each word in the sentence is returned as a dictionary with the following format: 'id': '1', 'form': 'Pierre', 'lemma': 'Pierre', ...
def parse_sentence(sentence_blob: str) -> Tuple[List[Dict[str, str]], List[Tuple[int, int]], List[str]]: """ Parses a chunk of text in the SemEval SDP format. Each word in the sentence is returned as a dictionary with the following format: 'id': '1', 'form': 'Pierre', 'lemma': 'Pierre', ...
[ "Parses", "a", "chunk", "of", "text", "in", "the", "SemEval", "SDP", "format", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/data/dataset_readers/semantic_dependency_parsing.py#L17-L56
[ "def", "parse_sentence", "(", "sentence_blob", ":", "str", ")", "->", "Tuple", "[", "List", "[", "Dict", "[", "str", ",", "str", "]", "]", ",", "List", "[", "Tuple", "[", "int", ",", "int", "]", "]", ",", "List", "[", "str", "]", "]", ":", "ann...
648a36f77db7e45784c047176074f98534c76636
train
parse_cuda_device
Disambiguates single GPU and multiple GPU settings for cuda_device param.
allennlp/common/checks.py
def parse_cuda_device(cuda_device: Union[str, int, List[int]]) -> Union[int, List[int]]: """ Disambiguates single GPU and multiple GPU settings for cuda_device param. """ def from_list(strings): if len(strings) > 1: return [int(d) for d in strings] elif len(strings) == 1: ...
def parse_cuda_device(cuda_device: Union[str, int, List[int]]) -> Union[int, List[int]]: """ Disambiguates single GPU and multiple GPU settings for cuda_device param. """ def from_list(strings): if len(strings) > 1: return [int(d) for d in strings] elif len(strings) == 1: ...
[ "Disambiguates", "single", "GPU", "and", "multiple", "GPU", "settings", "for", "cuda_device", "param", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/common/checks.py#L51-L71
[ "def", "parse_cuda_device", "(", "cuda_device", ":", "Union", "[", "str", ",", "int", ",", "List", "[", "int", "]", "]", ")", "->", "Union", "[", "int", ",", "List", "[", "int", "]", "]", ":", "def", "from_list", "(", "strings", ")", ":", "if", "...
648a36f77db7e45784c047176074f98534c76636
train
fine_tune_model_from_args
Just converts from an ``argparse.Namespace`` object to string paths.
allennlp/commands/fine_tune.py
def fine_tune_model_from_args(args: argparse.Namespace): """ Just converts from an ``argparse.Namespace`` object to string paths. """ fine_tune_model_from_file_paths(model_archive_path=args.model_archive, config_file=args.config_file, ...
def fine_tune_model_from_args(args: argparse.Namespace): """ Just converts from an ``argparse.Namespace`` object to string paths. """ fine_tune_model_from_file_paths(model_archive_path=args.model_archive, config_file=args.config_file, ...
[ "Just", "converts", "from", "an", "argparse", ".", "Namespace", "object", "to", "string", "paths", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/commands/fine_tune.py#L89-L100
[ "def", "fine_tune_model_from_args", "(", "args", ":", "argparse", ".", "Namespace", ")", ":", "fine_tune_model_from_file_paths", "(", "model_archive_path", "=", "args", ".", "model_archive", ",", "config_file", "=", "args", ".", "config_file", ",", "serialization_dir"...
648a36f77db7e45784c047176074f98534c76636
train
fine_tune_model_from_file_paths
A wrapper around :func:`fine_tune_model` which loads the model archive from a file. Parameters ---------- model_archive_path : ``str`` Path to a saved model archive that is the result of running the ``train`` command. config_file : ``str`` A configuration file specifying how to continue...
allennlp/commands/fine_tune.py
def fine_tune_model_from_file_paths(model_archive_path: str, config_file: str, serialization_dir: str, overrides: str = "", extend_vocab: bool = False, ...
def fine_tune_model_from_file_paths(model_archive_path: str, config_file: str, serialization_dir: str, overrides: str = "", extend_vocab: bool = False, ...
[ "A", "wrapper", "around", ":", "func", ":", "fine_tune_model", "which", "loads", "the", "model", "archive", "from", "a", "file", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/commands/fine_tune.py#L103-L150
[ "def", "fine_tune_model_from_file_paths", "(", "model_archive_path", ":", "str", ",", "config_file", ":", "str", ",", "serialization_dir", ":", "str", ",", "overrides", ":", "str", "=", "\"\"", ",", "extend_vocab", ":", "bool", "=", "False", ",", "file_friendly_...
648a36f77db7e45784c047176074f98534c76636
train
fine_tune_model
Fine tunes the given model, using a set of parameters that is largely identical to those used for :func:`~allennlp.commands.train.train_model`, except that the ``model`` section is ignored, if it is present (as we are already given a ``Model`` here). The main difference between the logic done here and the ...
allennlp/commands/fine_tune.py
def fine_tune_model(model: Model, params: Params, serialization_dir: str, extend_vocab: bool = False, file_friendly_logging: bool = False, batch_weight_key: str = "", embedding_sources_mapping: Dict[s...
def fine_tune_model(model: Model, params: Params, serialization_dir: str, extend_vocab: bool = False, file_friendly_logging: bool = False, batch_weight_key: str = "", embedding_sources_mapping: Dict[s...
[ "Fine", "tunes", "the", "given", "model", "using", "a", "set", "of", "parameters", "that", "is", "largely", "identical", "to", "those", "used", "for", ":", "func", ":", "~allennlp", ".", "commands", ".", "train", ".", "train_model", "except", "that", "the"...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/commands/fine_tune.py#L152-L304
[ "def", "fine_tune_model", "(", "model", ":", "Model", ",", "params", ":", "Params", ",", "serialization_dir", ":", "str", ",", "extend_vocab", ":", "bool", "=", "False", ",", "file_friendly_logging", ":", "bool", "=", "False", ",", "batch_weight_key", ":", "...
648a36f77db7e45784c047176074f98534c76636