repo stringlengths 7 55 | path stringlengths 4 223 | func_name stringlengths 1 134 | original_string stringlengths 75 104k | language stringclasses 1
value | code stringlengths 75 104k | code_tokens listlengths 19 28.4k | docstring stringlengths 1 46.9k | docstring_tokens listlengths 1 1.97k | sha stringlengths 40 40 | url stringlengths 87 315 | partition stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
allenai/allennlp | allennlp/data/dataset_readers/reading_comprehension/util.py | char_span_to_token_span | def char_span_to_token_span(token_offsets: List[Tuple[int, int]],
character_span: Tuple[int, int]) -> Tuple[Tuple[int, int], bool]:
"""
Converts a character span from a passage into the corresponding token span in the tokenized
version of the passage. If you pass in a character ... | python | def char_span_to_token_span(token_offsets: List[Tuple[int, int]],
character_span: Tuple[int, int]) -> Tuple[Tuple[int, int], bool]:
"""
Converts a character span from a passage into the corresponding token span in the tokenized
version of the passage. If you pass in a character ... | [
"def",
"char_span_to_token_span",
"(",
"token_offsets",
":",
"List",
"[",
"Tuple",
"[",
"int",
",",
"int",
"]",
"]",
",",
"character_span",
":",
"Tuple",
"[",
"int",
",",
"int",
"]",
")",
"->",
"Tuple",
"[",
"Tuple",
"[",
"int",
",",
"int",
"]",
",",... | Converts a character span from a passage into the corresponding token span in the tokenized
version of the passage. If you pass in a character span that does not correspond to complete
tokens in the tokenized version, we'll do our best, but the behavior is officially undefined.
We return an error flag in t... | [
"Converts",
"a",
"character",
"span",
"from",
"a",
"passage",
"into",
"the",
"corresponding",
"token",
"span",
"in",
"the",
"tokenized",
"version",
"of",
"the",
"passage",
".",
"If",
"you",
"pass",
"in",
"a",
"character",
"span",
"that",
"does",
"not",
"co... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/data/dataset_readers/reading_comprehension/util.py#L36-L94 | train |
allenai/allennlp | allennlp/data/dataset_readers/reading_comprehension/util.py | find_valid_answer_spans | def find_valid_answer_spans(passage_tokens: List[Token],
answer_texts: List[str]) -> List[Tuple[int, int]]:
"""
Finds a list of token spans in ``passage_tokens`` that match the given ``answer_texts``. This
tries to find all spans that would evaluate to correct given the SQuAD an... | python | def find_valid_answer_spans(passage_tokens: List[Token],
answer_texts: List[str]) -> List[Tuple[int, int]]:
"""
Finds a list of token spans in ``passage_tokens`` that match the given ``answer_texts``. This
tries to find all spans that would evaluate to correct given the SQuAD an... | [
"def",
"find_valid_answer_spans",
"(",
"passage_tokens",
":",
"List",
"[",
"Token",
"]",
",",
"answer_texts",
":",
"List",
"[",
"str",
"]",
")",
"->",
"List",
"[",
"Tuple",
"[",
"int",
",",
"int",
"]",
"]",
":",
"normalized_tokens",
"=",
"[",
"token",
... | Finds a list of token spans in ``passage_tokens`` that match the given ``answer_texts``. This
tries to find all spans that would evaluate to correct given the SQuAD and TriviaQA official
evaluation scripts, which do some normalization of the input text.
Note that this could return duplicate spans! The ca... | [
"Finds",
"a",
"list",
"of",
"token",
"spans",
"in",
"passage_tokens",
"that",
"match",
"the",
"given",
"answer_texts",
".",
"This",
"tries",
"to",
"find",
"all",
"spans",
"that",
"would",
"evaluate",
"to",
"correct",
"given",
"the",
"SQuAD",
"and",
"TriviaQA... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/data/dataset_readers/reading_comprehension/util.py#L97-L135 | train |
allenai/allennlp | allennlp/data/dataset_readers/reading_comprehension/util.py | make_reading_comprehension_instance | def make_reading_comprehension_instance(question_tokens: List[Token],
passage_tokens: List[Token],
token_indexers: Dict[str, TokenIndexer],
passage_text: str,
t... | python | def make_reading_comprehension_instance(question_tokens: List[Token],
passage_tokens: List[Token],
token_indexers: Dict[str, TokenIndexer],
passage_text: str,
t... | [
"def",
"make_reading_comprehension_instance",
"(",
"question_tokens",
":",
"List",
"[",
"Token",
"]",
",",
"passage_tokens",
":",
"List",
"[",
"Token",
"]",
",",
"token_indexers",
":",
"Dict",
"[",
"str",
",",
"TokenIndexer",
"]",
",",
"passage_text",
":",
"st... | Converts a question, a passage, and an optional answer (or answers) to an ``Instance`` for use
in a reading comprehension model.
Creates an ``Instance`` with at least these fields: ``question`` and ``passage``, both
``TextFields``; and ``metadata``, a ``MetadataField``. Additionally, if both ``answer_text... | [
"Converts",
"a",
"question",
"a",
"passage",
"and",
"an",
"optional",
"answer",
"(",
"or",
"answers",
")",
"to",
"an",
"Instance",
"for",
"use",
"in",
"a",
"reading",
"comprehension",
"model",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/data/dataset_readers/reading_comprehension/util.py#L138-L214 | train |
allenai/allennlp | allennlp/data/dataset_readers/reading_comprehension/util.py | make_reading_comprehension_instance_quac | def make_reading_comprehension_instance_quac(question_list_tokens: List[List[Token]],
passage_tokens: List[Token],
token_indexers: Dict[str, TokenIndexer],
passage_text: str,
... | python | def make_reading_comprehension_instance_quac(question_list_tokens: List[List[Token]],
passage_tokens: List[Token],
token_indexers: Dict[str, TokenIndexer],
passage_text: str,
... | [
"def",
"make_reading_comprehension_instance_quac",
"(",
"question_list_tokens",
":",
"List",
"[",
"List",
"[",
"Token",
"]",
"]",
",",
"passage_tokens",
":",
"List",
"[",
"Token",
"]",
",",
"token_indexers",
":",
"Dict",
"[",
"str",
",",
"TokenIndexer",
"]",
"... | Converts a question, a passage, and an optional answer (or answers) to an ``Instance`` for use
in a reading comprehension model.
Creates an ``Instance`` with at least these fields: ``question`` and ``passage``, both
``TextFields``; and ``metadata``, a ``MetadataField``. Additionally, if both ``answer_text... | [
"Converts",
"a",
"question",
"a",
"passage",
"and",
"an",
"optional",
"answer",
"(",
"or",
"answers",
")",
"to",
"an",
"Instance",
"for",
"use",
"in",
"a",
"reading",
"comprehension",
"model",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/data/dataset_readers/reading_comprehension/util.py#L217-L351 | train |
allenai/allennlp | allennlp/data/dataset_readers/reading_comprehension/util.py | handle_cannot | def handle_cannot(reference_answers: List[str]):
"""
Process a list of reference answers.
If equal or more than half of the reference answers are "CANNOTANSWER", take it as gold.
Otherwise, return answers that are not "CANNOTANSWER".
"""
num_cannot = 0
num_spans = 0
for ref in reference_... | python | def handle_cannot(reference_answers: List[str]):
"""
Process a list of reference answers.
If equal or more than half of the reference answers are "CANNOTANSWER", take it as gold.
Otherwise, return answers that are not "CANNOTANSWER".
"""
num_cannot = 0
num_spans = 0
for ref in reference_... | [
"def",
"handle_cannot",
"(",
"reference_answers",
":",
"List",
"[",
"str",
"]",
")",
":",
"num_cannot",
"=",
"0",
"num_spans",
"=",
"0",
"for",
"ref",
"in",
"reference_answers",
":",
"if",
"ref",
"==",
"'CANNOTANSWER'",
":",
"num_cannot",
"+=",
"1",
"else"... | Process a list of reference answers.
If equal or more than half of the reference answers are "CANNOTANSWER", take it as gold.
Otherwise, return answers that are not "CANNOTANSWER". | [
"Process",
"a",
"list",
"of",
"reference",
"answers",
".",
"If",
"equal",
"or",
"more",
"than",
"half",
"of",
"the",
"reference",
"answers",
"are",
"CANNOTANSWER",
"take",
"it",
"as",
"gold",
".",
"Otherwise",
"return",
"answers",
"that",
"are",
"not",
"CA... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/data/dataset_readers/reading_comprehension/util.py#L354-L371 | train |
allenai/allennlp | allennlp/models/reading_comprehension/util.py | get_best_span | def get_best_span(span_start_logits: torch.Tensor, span_end_logits: torch.Tensor) -> torch.Tensor:
"""
This acts the same as the static method ``BidirectionalAttentionFlow.get_best_span()``
in ``allennlp/models/reading_comprehension/bidaf.py``. We keep it here so that users can
directly import this func... | python | def get_best_span(span_start_logits: torch.Tensor, span_end_logits: torch.Tensor) -> torch.Tensor:
"""
This acts the same as the static method ``BidirectionalAttentionFlow.get_best_span()``
in ``allennlp/models/reading_comprehension/bidaf.py``. We keep it here so that users can
directly import this func... | [
"def",
"get_best_span",
"(",
"span_start_logits",
":",
"torch",
".",
"Tensor",
",",
"span_end_logits",
":",
"torch",
".",
"Tensor",
")",
"->",
"torch",
".",
"Tensor",
":",
"if",
"span_start_logits",
".",
"dim",
"(",
")",
"!=",
"2",
"or",
"span_end_logits",
... | This acts the same as the static method ``BidirectionalAttentionFlow.get_best_span()``
in ``allennlp/models/reading_comprehension/bidaf.py``. We keep it here so that users can
directly import this function without the class.
We call the inputs "logits" - they could either be unnormalized logits or normaliz... | [
"This",
"acts",
"the",
"same",
"as",
"the",
"static",
"method",
"BidirectionalAttentionFlow",
".",
"get_best_span",
"()",
"in",
"allennlp",
"/",
"models",
"/",
"reading_comprehension",
"/",
"bidaf",
".",
"py",
".",
"We",
"keep",
"it",
"here",
"so",
"that",
"... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/models/reading_comprehension/util.py#L4-L33 | train |
allenai/allennlp | allennlp/data/tokenizers/word_splitter.py | WordSplitter.batch_split_words | def batch_split_words(self, sentences: List[str]) -> List[List[Token]]:
"""
Spacy needs to do batch processing, or it can be really slow. This method lets you take
advantage of that if you want. Default implementation is to just iterate of the sentences
and call ``split_words``, but th... | python | def batch_split_words(self, sentences: List[str]) -> List[List[Token]]:
"""
Spacy needs to do batch processing, or it can be really slow. This method lets you take
advantage of that if you want. Default implementation is to just iterate of the sentences
and call ``split_words``, but th... | [
"def",
"batch_split_words",
"(",
"self",
",",
"sentences",
":",
"List",
"[",
"str",
"]",
")",
"->",
"List",
"[",
"List",
"[",
"Token",
"]",
"]",
":",
"return",
"[",
"self",
".",
"split_words",
"(",
"sentence",
")",
"for",
"sentence",
"in",
"sentences",... | Spacy needs to do batch processing, or it can be really slow. This method lets you take
advantage of that if you want. Default implementation is to just iterate of the sentences
and call ``split_words``, but the ``SpacyWordSplitter`` will actually do batched
processing. | [
"Spacy",
"needs",
"to",
"do",
"batch",
"processing",
"or",
"it",
"can",
"be",
"really",
"slow",
".",
"This",
"method",
"lets",
"you",
"take",
"advantage",
"of",
"that",
"if",
"you",
"want",
".",
"Default",
"implementation",
"is",
"to",
"just",
"iterate",
... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/data/tokenizers/word_splitter.py#L25-L32 | train |
allenai/allennlp | allennlp/state_machines/beam_search.py | BeamSearch.constrained_to | def constrained_to(self, initial_sequence: torch.Tensor, keep_beam_details: bool = True) -> 'BeamSearch':
"""
Return a new BeamSearch instance that's like this one but with the specified constraint.
"""
return BeamSearch(self._beam_size, self._per_node_beam_size, initial_sequence, keep_b... | python | def constrained_to(self, initial_sequence: torch.Tensor, keep_beam_details: bool = True) -> 'BeamSearch':
"""
Return a new BeamSearch instance that's like this one but with the specified constraint.
"""
return BeamSearch(self._beam_size, self._per_node_beam_size, initial_sequence, keep_b... | [
"def",
"constrained_to",
"(",
"self",
",",
"initial_sequence",
":",
"torch",
".",
"Tensor",
",",
"keep_beam_details",
":",
"bool",
"=",
"True",
")",
"->",
"'BeamSearch'",
":",
"return",
"BeamSearch",
"(",
"self",
".",
"_beam_size",
",",
"self",
".",
"_per_no... | Return a new BeamSearch instance that's like this one but with the specified constraint. | [
"Return",
"a",
"new",
"BeamSearch",
"instance",
"that",
"s",
"like",
"this",
"one",
"but",
"with",
"the",
"specified",
"constraint",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/state_machines/beam_search.py#L70-L74 | train |
allenai/allennlp | allennlp/state_machines/beam_search.py | BeamSearch.search | def search(self,
num_steps: int,
initial_state: StateType,
transition_function: TransitionFunction,
keep_final_unfinished_states: bool = True) -> Dict[int, List[StateType]]:
"""
Parameters
----------
num_steps : ``int``
... | python | def search(self,
num_steps: int,
initial_state: StateType,
transition_function: TransitionFunction,
keep_final_unfinished_states: bool = True) -> Dict[int, List[StateType]]:
"""
Parameters
----------
num_steps : ``int``
... | [
"def",
"search",
"(",
"self",
",",
"num_steps",
":",
"int",
",",
"initial_state",
":",
"StateType",
",",
"transition_function",
":",
"TransitionFunction",
",",
"keep_final_unfinished_states",
":",
"bool",
"=",
"True",
")",
"->",
"Dict",
"[",
"int",
",",
"List"... | Parameters
----------
num_steps : ``int``
How many steps should we take in our search? This is an upper bound, as it's possible
for the search to run out of valid actions before hitting this number, or for all
states on the beam to finish.
initial_state : ``S... | [
"Parameters",
"----------",
"num_steps",
":",
"int",
"How",
"many",
"steps",
"should",
"we",
"take",
"in",
"our",
"search?",
"This",
"is",
"an",
"upper",
"bound",
"as",
"it",
"s",
"possible",
"for",
"the",
"search",
"to",
"run",
"out",
"of",
"valid",
"ac... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/state_machines/beam_search.py#L76-L175 | train |
allenai/allennlp | allennlp/tools/drop_eval.py | _normalize_answer | def _normalize_answer(text: str) -> str:
"""Lower text and remove punctuation, articles and extra whitespace."""
parts = [_white_space_fix(_remove_articles(_normalize_number(_remove_punc(_lower(token)))))
for token in _tokenize(text)]
parts = [part for part in parts if part.strip()]
normal... | python | def _normalize_answer(text: str) -> str:
"""Lower text and remove punctuation, articles and extra whitespace."""
parts = [_white_space_fix(_remove_articles(_normalize_number(_remove_punc(_lower(token)))))
for token in _tokenize(text)]
parts = [part for part in parts if part.strip()]
normal... | [
"def",
"_normalize_answer",
"(",
"text",
":",
"str",
")",
"->",
"str",
":",
"parts",
"=",
"[",
"_white_space_fix",
"(",
"_remove_articles",
"(",
"_normalize_number",
"(",
"_remove_punc",
"(",
"_lower",
"(",
"token",
")",
")",
")",
")",
")",
"for",
"token",... | Lower text and remove punctuation, articles and extra whitespace. | [
"Lower",
"text",
"and",
"remove",
"punctuation",
"articles",
"and",
"extra",
"whitespace",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/tools/drop_eval.py#L36-L43 | train |
allenai/allennlp | allennlp/tools/drop_eval.py | _align_bags | def _align_bags(predicted: List[Set[str]], gold: List[Set[str]]) -> List[float]:
"""
Takes gold and predicted answer sets and first finds a greedy 1-1 alignment
between them and gets maximum metric values over all the answers
"""
f1_scores = []
for gold_index, gold_item in enumerate(gold):
... | python | def _align_bags(predicted: List[Set[str]], gold: List[Set[str]]) -> List[float]:
"""
Takes gold and predicted answer sets and first finds a greedy 1-1 alignment
between them and gets maximum metric values over all the answers
"""
f1_scores = []
for gold_index, gold_item in enumerate(gold):
... | [
"def",
"_align_bags",
"(",
"predicted",
":",
"List",
"[",
"Set",
"[",
"str",
"]",
"]",
",",
"gold",
":",
"List",
"[",
"Set",
"[",
"str",
"]",
"]",
")",
"->",
"List",
"[",
"float",
"]",
":",
"f1_scores",
"=",
"[",
"]",
"for",
"gold_index",
",",
... | Takes gold and predicted answer sets and first finds a greedy 1-1 alignment
between them and gets maximum metric values over all the answers | [
"Takes",
"gold",
"and",
"predicted",
"answer",
"sets",
"and",
"first",
"finds",
"a",
"greedy",
"1",
"-",
"1",
"alignment",
"between",
"them",
"and",
"gets",
"maximum",
"metric",
"values",
"over",
"all",
"the",
"answers"
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/tools/drop_eval.py#L73-L99 | train |
allenai/allennlp | allennlp/tools/drop_eval.py | get_metrics | def get_metrics(predicted: Union[str, List[str], Tuple[str, ...]],
gold: Union[str, List[str], Tuple[str, ...]]) -> Tuple[float, float]:
"""
Takes a predicted answer and a gold answer (that are both either a string or a list of
strings), and returns exact match and the DROP F1 metric for the... | python | def get_metrics(predicted: Union[str, List[str], Tuple[str, ...]],
gold: Union[str, List[str], Tuple[str, ...]]) -> Tuple[float, float]:
"""
Takes a predicted answer and a gold answer (that are both either a string or a list of
strings), and returns exact match and the DROP F1 metric for the... | [
"def",
"get_metrics",
"(",
"predicted",
":",
"Union",
"[",
"str",
",",
"List",
"[",
"str",
"]",
",",
"Tuple",
"[",
"str",
",",
"...",
"]",
"]",
",",
"gold",
":",
"Union",
"[",
"str",
",",
"List",
"[",
"str",
"]",
",",
"Tuple",
"[",
"str",
",",
... | Takes a predicted answer and a gold answer (that are both either a string or a list of
strings), and returns exact match and the DROP F1 metric for the prediction. If you are
writing a script for evaluating objects in memory (say, the output of predictions during
validation, or while training), this is the... | [
"Takes",
"a",
"predicted",
"answer",
"and",
"a",
"gold",
"answer",
"(",
"that",
"are",
"both",
"either",
"a",
"string",
"or",
"a",
"list",
"of",
"strings",
")",
"and",
"returns",
"exact",
"match",
"and",
"the",
"DROP",
"F1",
"metric",
"for",
"the",
"pr... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/tools/drop_eval.py#L130-L147 | train |
allenai/allennlp | allennlp/tools/drop_eval.py | answer_json_to_strings | def answer_json_to_strings(answer: Dict[str, Any]) -> Tuple[Tuple[str, ...], str]:
"""
Takes an answer JSON blob from the DROP data release and converts it into strings used for
evaluation.
"""
if "number" in answer and answer["number"]:
return tuple([str(answer["number"])]), "number"
el... | python | def answer_json_to_strings(answer: Dict[str, Any]) -> Tuple[Tuple[str, ...], str]:
"""
Takes an answer JSON blob from the DROP data release and converts it into strings used for
evaluation.
"""
if "number" in answer and answer["number"]:
return tuple([str(answer["number"])]), "number"
el... | [
"def",
"answer_json_to_strings",
"(",
"answer",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
")",
"->",
"Tuple",
"[",
"Tuple",
"[",
"str",
",",
"...",
"]",
",",
"str",
"]",
":",
"if",
"\"number\"",
"in",
"answer",
"and",
"answer",
"[",
"\"number\"",
"]"... | Takes an answer JSON blob from the DROP data release and converts it into strings used for
evaluation. | [
"Takes",
"an",
"answer",
"JSON",
"blob",
"from",
"the",
"DROP",
"data",
"release",
"and",
"converts",
"it",
"into",
"strings",
"used",
"for",
"evaluation",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/tools/drop_eval.py#L150-L164 | train |
allenai/allennlp | allennlp/tools/drop_eval.py | evaluate_json | def evaluate_json(annotations: Dict[str, Any], predicted_answers: Dict[str, Any]) -> Tuple[float, float]:
"""
Takes gold annotations and predicted answers and evaluates the predictions for each question
in the gold annotations. Both JSON dictionaries must have query_id keys, which are used to
match pr... | python | def evaluate_json(annotations: Dict[str, Any], predicted_answers: Dict[str, Any]) -> Tuple[float, float]:
"""
Takes gold annotations and predicted answers and evaluates the predictions for each question
in the gold annotations. Both JSON dictionaries must have query_id keys, which are used to
match pr... | [
"def",
"evaluate_json",
"(",
"annotations",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
",",
"predicted_answers",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
")",
"->",
"Tuple",
"[",
"float",
",",
"float",
"]",
":",
"instance_exact_match",
"=",
"[",
"]",
... | Takes gold annotations and predicted answers and evaluates the predictions for each question
in the gold annotations. Both JSON dictionaries must have query_id keys, which are used to
match predictions to gold annotations (note that these are somewhat deep in the JSON for the
gold annotations, but must be... | [
"Takes",
"gold",
"annotations",
"and",
"predicted",
"answers",
"and",
"evaluates",
"the",
"predictions",
"for",
"each",
"question",
"in",
"the",
"gold",
"annotations",
".",
"Both",
"JSON",
"dictionaries",
"must",
"have",
"query_id",
"keys",
"which",
"are",
"used... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/tools/drop_eval.py#L167-L226 | train |
allenai/allennlp | allennlp/tools/drop_eval.py | evaluate_prediction_file | def evaluate_prediction_file(prediction_path: str, gold_path: str) -> Tuple[float, float]:
"""
Takes a prediction file and a gold file and evaluates the predictions for each question in the
gold file. Both files must be json formatted and must have query_id keys, which are used to
match predictions to ... | python | def evaluate_prediction_file(prediction_path: str, gold_path: str) -> Tuple[float, float]:
"""
Takes a prediction file and a gold file and evaluates the predictions for each question in the
gold file. Both files must be json formatted and must have query_id keys, which are used to
match predictions to ... | [
"def",
"evaluate_prediction_file",
"(",
"prediction_path",
":",
"str",
",",
"gold_path",
":",
"str",
")",
"->",
"Tuple",
"[",
"float",
",",
"float",
"]",
":",
"predicted_answers",
"=",
"json",
".",
"load",
"(",
"open",
"(",
"prediction_path",
",",
"encoding"... | Takes a prediction file and a gold file and evaluates the predictions for each question in the
gold file. Both files must be json formatted and must have query_id keys, which are used to
match predictions to gold annotations. The gold file is assumed to have the format of the dev
set in the DROP data rele... | [
"Takes",
"a",
"prediction",
"file",
"and",
"a",
"gold",
"file",
"and",
"evaluates",
"the",
"predictions",
"for",
"each",
"question",
"in",
"the",
"gold",
"file",
".",
"Both",
"files",
"must",
"be",
"json",
"formatted",
"and",
"must",
"have",
"query_id",
"k... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/tools/drop_eval.py#L229-L240 | train |
allenai/allennlp | allennlp/data/dataset_readers/dataset_reader.py | DatasetReader.cache_data | def cache_data(self, cache_directory: str) -> None:
"""
When you call this method, we will use this directory to store a cache of already-processed
``Instances`` in every file passed to :func:`read`, serialized as one string-formatted
``Instance`` per line. If the cache file for a given... | python | def cache_data(self, cache_directory: str) -> None:
"""
When you call this method, we will use this directory to store a cache of already-processed
``Instances`` in every file passed to :func:`read`, serialized as one string-formatted
``Instance`` per line. If the cache file for a given... | [
"def",
"cache_data",
"(",
"self",
",",
"cache_directory",
":",
"str",
")",
"->",
"None",
":",
"self",
".",
"_cache_directory",
"=",
"pathlib",
".",
"Path",
"(",
"cache_directory",
")",
"os",
".",
"makedirs",
"(",
"self",
".",
"_cache_directory",
",",
"exis... | When you call this method, we will use this directory to store a cache of already-processed
``Instances`` in every file passed to :func:`read`, serialized as one string-formatted
``Instance`` per line. If the cache file for a given ``file_path`` exists, we read the
``Instances`` from the cache ... | [
"When",
"you",
"call",
"this",
"method",
"we",
"will",
"use",
"this",
"directory",
"to",
"store",
"a",
"cache",
"of",
"already",
"-",
"processed",
"Instances",
"in",
"every",
"file",
"passed",
"to",
":",
"func",
":",
"read",
"serialized",
"as",
"one",
"s... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/data/dataset_readers/dataset_reader.py#L72-L89 | train |
allenai/allennlp | allennlp/data/dataset_readers/dataset_reader.py | DatasetReader.read | def read(self, file_path: str) -> Iterable[Instance]:
"""
Returns an ``Iterable`` containing all the instances
in the specified dataset.
If ``self.lazy`` is False, this calls ``self._read()``,
ensures that the result is a list, then returns the resulting list.
If ``self... | python | def read(self, file_path: str) -> Iterable[Instance]:
"""
Returns an ``Iterable`` containing all the instances
in the specified dataset.
If ``self.lazy`` is False, this calls ``self._read()``,
ensures that the result is a list, then returns the resulting list.
If ``self... | [
"def",
"read",
"(",
"self",
",",
"file_path",
":",
"str",
")",
"->",
"Iterable",
"[",
"Instance",
"]",
":",
"lazy",
"=",
"getattr",
"(",
"self",
",",
"'lazy'",
",",
"None",
")",
"if",
"lazy",
"is",
"None",
":",
"logger",
".",
"warning",
"(",
"\"Dat... | Returns an ``Iterable`` containing all the instances
in the specified dataset.
If ``self.lazy`` is False, this calls ``self._read()``,
ensures that the result is a list, then returns the resulting list.
If ``self.lazy`` is True, this returns an object whose
``__iter__`` method ... | [
"Returns",
"an",
"Iterable",
"containing",
"all",
"the",
"instances",
"in",
"the",
"specified",
"dataset",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/data/dataset_readers/dataset_reader.py#L91-L145 | train |
allenai/allennlp | allennlp/training/checkpointer.py | Checkpointer.restore_checkpoint | def restore_checkpoint(self) -> Tuple[Dict[str, Any], Dict[str, Any]]:
"""
Restores a model from a serialization_dir to the last saved checkpoint.
This includes a training state (typically consisting of an epoch count and optimizer state),
which is serialized separately from model param... | python | def restore_checkpoint(self) -> Tuple[Dict[str, Any], Dict[str, Any]]:
"""
Restores a model from a serialization_dir to the last saved checkpoint.
This includes a training state (typically consisting of an epoch count and optimizer state),
which is serialized separately from model param... | [
"def",
"restore_checkpoint",
"(",
"self",
")",
"->",
"Tuple",
"[",
"Dict",
"[",
"str",
",",
"Any",
"]",
",",
"Dict",
"[",
"str",
",",
"Any",
"]",
"]",
":",
"latest_checkpoint",
"=",
"self",
".",
"find_latest_checkpoint",
"(",
")",
"if",
"latest_checkpoin... | Restores a model from a serialization_dir to the last saved checkpoint.
This includes a training state (typically consisting of an epoch count and optimizer state),
which is serialized separately from model parameters. This function should only be used to
continue training - if you wish to load... | [
"Restores",
"a",
"model",
"from",
"a",
"serialization_dir",
"to",
"the",
"last",
"saved",
"checkpoint",
".",
"This",
"includes",
"a",
"training",
"state",
"(",
"typically",
"consisting",
"of",
"an",
"epoch",
"count",
"and",
"optimizer",
"state",
")",
"which",
... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/training/checkpointer.py#L114-L145 | train |
allenai/allennlp | allennlp/models/semantic_role_labeler.py | write_to_conll_eval_file | def write_to_conll_eval_file(prediction_file: TextIO,
gold_file: TextIO,
verb_index: Optional[int],
sentence: List[str],
prediction: List[str],
gold_labels: List[str]):
""... | python | def write_to_conll_eval_file(prediction_file: TextIO,
gold_file: TextIO,
verb_index: Optional[int],
sentence: List[str],
prediction: List[str],
gold_labels: List[str]):
""... | [
"def",
"write_to_conll_eval_file",
"(",
"prediction_file",
":",
"TextIO",
",",
"gold_file",
":",
"TextIO",
",",
"verb_index",
":",
"Optional",
"[",
"int",
"]",
",",
"sentence",
":",
"List",
"[",
"str",
"]",
",",
"prediction",
":",
"List",
"[",
"str",
"]",
... | Prints predicate argument predictions and gold labels for a single verbal
predicate in a sentence to two provided file references.
Parameters
----------
prediction_file : TextIO, required.
A file reference to print predictions to.
gold_file : TextIO, required.
A file reference to pr... | [
"Prints",
"predicate",
"argument",
"predictions",
"and",
"gold",
"labels",
"for",
"a",
"single",
"verbal",
"predicate",
"in",
"a",
"sentence",
"to",
"two",
"provided",
"file",
"references",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/models/semantic_role_labeler.py#L226-L268 | train |
allenai/allennlp | allennlp/models/semantic_role_labeler.py | convert_bio_tags_to_conll_format | def convert_bio_tags_to_conll_format(labels: List[str]):
"""
Converts BIO formatted SRL tags to the format required for evaluation with the
official CONLL 2005 perl script. Spans are represented by bracketed labels,
with the labels of words inside spans being the same as those outside spans.
Beginni... | python | def convert_bio_tags_to_conll_format(labels: List[str]):
"""
Converts BIO formatted SRL tags to the format required for evaluation with the
official CONLL 2005 perl script. Spans are represented by bracketed labels,
with the labels of words inside spans being the same as those outside spans.
Beginni... | [
"def",
"convert_bio_tags_to_conll_format",
"(",
"labels",
":",
"List",
"[",
"str",
"]",
")",
":",
"sentence_length",
"=",
"len",
"(",
"labels",
")",
"conll_labels",
"=",
"[",
"]",
"for",
"i",
",",
"label",
"in",
"enumerate",
"(",
"labels",
")",
":",
"if"... | Converts BIO formatted SRL tags to the format required for evaluation with the
official CONLL 2005 perl script. Spans are represented by bracketed labels,
with the labels of words inside spans being the same as those outside spans.
Beginning spans always have a opening bracket and a closing asterisk (e.g. "... | [
"Converts",
"BIO",
"formatted",
"SRL",
"tags",
"to",
"the",
"format",
"required",
"for",
"evaluation",
"with",
"the",
"official",
"CONLL",
"2005",
"perl",
"script",
".",
"Spans",
"are",
"represented",
"by",
"bracketed",
"labels",
"with",
"the",
"labels",
"of",... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/models/semantic_role_labeler.py#L271-L310 | train |
allenai/allennlp | allennlp/semparse/domain_languages/nlvr_language.py | NlvrLanguage.get_agenda_for_sentence | def get_agenda_for_sentence(self, sentence: str) -> List[str]:
"""
Given a ``sentence``, returns a list of actions the sentence triggers as an ``agenda``. The
``agenda`` can be used while by a parser to guide the decoder. sequences as possible. This
is a simplistic mapping at this point... | python | def get_agenda_for_sentence(self, sentence: str) -> List[str]:
"""
Given a ``sentence``, returns a list of actions the sentence triggers as an ``agenda``. The
``agenda`` can be used while by a parser to guide the decoder. sequences as possible. This
is a simplistic mapping at this point... | [
"def",
"get_agenda_for_sentence",
"(",
"self",
",",
"sentence",
":",
"str",
")",
"->",
"List",
"[",
"str",
"]",
":",
"agenda",
"=",
"[",
"]",
"sentence",
"=",
"sentence",
".",
"lower",
"(",
")",
"if",
"sentence",
".",
"startswith",
"(",
"\"there is a box... | Given a ``sentence``, returns a list of actions the sentence triggers as an ``agenda``. The
``agenda`` can be used while by a parser to guide the decoder. sequences as possible. This
is a simplistic mapping at this point, and can be expanded.
Parameters
----------
sentence : ``... | [
"Given",
"a",
"sentence",
"returns",
"a",
"list",
"of",
"actions",
"the",
"sentence",
"triggers",
"as",
"an",
"agenda",
".",
"The",
"agenda",
"can",
"be",
"used",
"while",
"by",
"a",
"parser",
"to",
"guide",
"the",
"decoder",
".",
"sequences",
"as",
"pos... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/domain_languages/nlvr_language.py#L125-L199 | train |
allenai/allennlp | allennlp/semparse/domain_languages/nlvr_language.py | NlvrLanguage._get_number_productions | def _get_number_productions(sentence: str) -> List[str]:
"""
Gathers all the numbers in the sentence, and returns productions that lead to them.
"""
# The mapping here is very simple and limited, which also shouldn't be a problem
# because numbers seem to be represented fairly re... | python | def _get_number_productions(sentence: str) -> List[str]:
"""
Gathers all the numbers in the sentence, and returns productions that lead to them.
"""
# The mapping here is very simple and limited, which also shouldn't be a problem
# because numbers seem to be represented fairly re... | [
"def",
"_get_number_productions",
"(",
"sentence",
":",
"str",
")",
"->",
"List",
"[",
"str",
"]",
":",
"# The mapping here is very simple and limited, which also shouldn't be a problem",
"# because numbers seem to be represented fairly regularly.",
"number_strings",
"=",
"{",
"\... | Gathers all the numbers in the sentence, and returns productions that lead to them. | [
"Gathers",
"all",
"the",
"numbers",
"in",
"the",
"sentence",
"and",
"returns",
"productions",
"that",
"lead",
"to",
"them",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/domain_languages/nlvr_language.py#L202-L218 | train |
allenai/allennlp | allennlp/semparse/domain_languages/nlvr_language.py | NlvrLanguage.same_color | def same_color(self, objects: Set[Object]) -> Set[Object]:
"""
Filters the set of objects, and returns those objects whose color is the most frequent
color in the initial set of objects, if the highest frequency is greater than 1, or an
empty set otherwise.
This is an unusual na... | python | def same_color(self, objects: Set[Object]) -> Set[Object]:
"""
Filters the set of objects, and returns those objects whose color is the most frequent
color in the initial set of objects, if the highest frequency is greater than 1, or an
empty set otherwise.
This is an unusual na... | [
"def",
"same_color",
"(",
"self",
",",
"objects",
":",
"Set",
"[",
"Object",
"]",
")",
"->",
"Set",
"[",
"Object",
"]",
":",
"return",
"self",
".",
"_get_objects_with_same_attribute",
"(",
"objects",
",",
"lambda",
"x",
":",
"x",
".",
"color",
")"
] | Filters the set of objects, and returns those objects whose color is the most frequent
color in the initial set of objects, if the highest frequency is greater than 1, or an
empty set otherwise.
This is an unusual name for what the method does, but just as ``blue`` filters objects to
th... | [
"Filters",
"the",
"set",
"of",
"objects",
"and",
"returns",
"those",
"objects",
"whose",
"color",
"is",
"the",
"most",
"frequent",
"color",
"in",
"the",
"initial",
"set",
"of",
"objects",
"if",
"the",
"highest",
"frequency",
"is",
"greater",
"than",
"1",
"... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/domain_languages/nlvr_language.py#L275-L284 | train |
allenai/allennlp | allennlp/semparse/domain_languages/nlvr_language.py | NlvrLanguage.same_shape | def same_shape(self, objects: Set[Object]) -> Set[Object]:
"""
Filters the set of objects, and returns those objects whose color is the most frequent
color in the initial set of objects, if the highest frequency is greater than 1, or an
empty set otherwise.
This is an unusual na... | python | def same_shape(self, objects: Set[Object]) -> Set[Object]:
"""
Filters the set of objects, and returns those objects whose color is the most frequent
color in the initial set of objects, if the highest frequency is greater than 1, or an
empty set otherwise.
This is an unusual na... | [
"def",
"same_shape",
"(",
"self",
",",
"objects",
":",
"Set",
"[",
"Object",
"]",
")",
"->",
"Set",
"[",
"Object",
"]",
":",
"return",
"self",
".",
"_get_objects_with_same_attribute",
"(",
"objects",
",",
"lambda",
"x",
":",
"x",
".",
"shape",
")"
] | Filters the set of objects, and returns those objects whose color is the most frequent
color in the initial set of objects, if the highest frequency is greater than 1, or an
empty set otherwise.
This is an unusual name for what the method does, but just as ``triangle`` filters objects
t... | [
"Filters",
"the",
"set",
"of",
"objects",
"and",
"returns",
"those",
"objects",
"whose",
"color",
"is",
"the",
"most",
"frequent",
"color",
"in",
"the",
"initial",
"set",
"of",
"objects",
"if",
"the",
"highest",
"frequency",
"is",
"greater",
"than",
"1",
"... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/domain_languages/nlvr_language.py#L287-L296 | train |
allenai/allennlp | allennlp/semparse/domain_languages/nlvr_language.py | NlvrLanguage.touch_object | def touch_object(self, objects: Set[Object]) -> Set[Object]:
"""
Returns all objects that touch the given set of objects.
"""
objects_per_box = self._separate_objects_by_boxes(objects)
return_set = set()
for box, box_objects in objects_per_box.items():
candida... | python | def touch_object(self, objects: Set[Object]) -> Set[Object]:
"""
Returns all objects that touch the given set of objects.
"""
objects_per_box = self._separate_objects_by_boxes(objects)
return_set = set()
for box, box_objects in objects_per_box.items():
candida... | [
"def",
"touch_object",
"(",
"self",
",",
"objects",
":",
"Set",
"[",
"Object",
"]",
")",
"->",
"Set",
"[",
"Object",
"]",
":",
"objects_per_box",
"=",
"self",
".",
"_separate_objects_by_boxes",
"(",
"objects",
")",
"return_set",
"=",
"set",
"(",
")",
"fo... | Returns all objects that touch the given set of objects. | [
"Returns",
"all",
"objects",
"that",
"touch",
"the",
"given",
"set",
"of",
"objects",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/domain_languages/nlvr_language.py#L329-L341 | train |
allenai/allennlp | allennlp/semparse/domain_languages/nlvr_language.py | NlvrLanguage.top | def top(self, objects: Set[Object]) -> Set[Object]:
"""
Return the topmost objects (i.e. minimum y_loc). The comparison is done separately for each
box.
"""
objects_per_box = self._separate_objects_by_boxes(objects)
return_set: Set[Object] = set()
for _, box_objec... | python | def top(self, objects: Set[Object]) -> Set[Object]:
"""
Return the topmost objects (i.e. minimum y_loc). The comparison is done separately for each
box.
"""
objects_per_box = self._separate_objects_by_boxes(objects)
return_set: Set[Object] = set()
for _, box_objec... | [
"def",
"top",
"(",
"self",
",",
"objects",
":",
"Set",
"[",
"Object",
"]",
")",
"->",
"Set",
"[",
"Object",
"]",
":",
"objects_per_box",
"=",
"self",
".",
"_separate_objects_by_boxes",
"(",
"objects",
")",
"return_set",
":",
"Set",
"[",
"Object",
"]",
... | Return the topmost objects (i.e. minimum y_loc). The comparison is done separately for each
box. | [
"Return",
"the",
"topmost",
"objects",
"(",
"i",
".",
"e",
".",
"minimum",
"y_loc",
")",
".",
"The",
"comparison",
"is",
"done",
"separately",
"for",
"each",
"box",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/domain_languages/nlvr_language.py#L344-L354 | train |
allenai/allennlp | allennlp/semparse/domain_languages/nlvr_language.py | NlvrLanguage.bottom | def bottom(self, objects: Set[Object]) -> Set[Object]:
"""
Return the bottom most objects(i.e. maximum y_loc). The comparison is done separately for
each box.
"""
objects_per_box = self._separate_objects_by_boxes(objects)
return_set: Set[Object] = set()
for _, box... | python | def bottom(self, objects: Set[Object]) -> Set[Object]:
"""
Return the bottom most objects(i.e. maximum y_loc). The comparison is done separately for
each box.
"""
objects_per_box = self._separate_objects_by_boxes(objects)
return_set: Set[Object] = set()
for _, box... | [
"def",
"bottom",
"(",
"self",
",",
"objects",
":",
"Set",
"[",
"Object",
"]",
")",
"->",
"Set",
"[",
"Object",
"]",
":",
"objects_per_box",
"=",
"self",
".",
"_separate_objects_by_boxes",
"(",
"objects",
")",
"return_set",
":",
"Set",
"[",
"Object",
"]",... | Return the bottom most objects(i.e. maximum y_loc). The comparison is done separately for
each box. | [
"Return",
"the",
"bottom",
"most",
"objects",
"(",
"i",
".",
"e",
".",
"maximum",
"y_loc",
")",
".",
"The",
"comparison",
"is",
"done",
"separately",
"for",
"each",
"box",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/domain_languages/nlvr_language.py#L357-L367 | train |
allenai/allennlp | allennlp/semparse/domain_languages/nlvr_language.py | NlvrLanguage.above | def above(self, objects: Set[Object]) -> Set[Object]:
"""
Returns the set of objects in the same boxes that are above the given objects. That is, if
the input is a set of two objects, one in each box, we will return a union of the objects
above the first object in the first box, and thos... | python | def above(self, objects: Set[Object]) -> Set[Object]:
"""
Returns the set of objects in the same boxes that are above the given objects. That is, if
the input is a set of two objects, one in each box, we will return a union of the objects
above the first object in the first box, and thos... | [
"def",
"above",
"(",
"self",
",",
"objects",
":",
"Set",
"[",
"Object",
"]",
")",
"->",
"Set",
"[",
"Object",
"]",
":",
"objects_per_box",
"=",
"self",
".",
"_separate_objects_by_boxes",
"(",
"objects",
")",
"return_set",
"=",
"set",
"(",
")",
"for",
"... | Returns the set of objects in the same boxes that are above the given objects. That is, if
the input is a set of two objects, one in each box, we will return a union of the objects
above the first object in the first box, and those above the second object in the second box. | [
"Returns",
"the",
"set",
"of",
"objects",
"in",
"the",
"same",
"boxes",
"that",
"are",
"above",
"the",
"given",
"objects",
".",
"That",
"is",
"if",
"the",
"input",
"is",
"a",
"set",
"of",
"two",
"objects",
"one",
"in",
"each",
"box",
"we",
"will",
"r... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/domain_languages/nlvr_language.py#L370-L384 | train |
allenai/allennlp | allennlp/semparse/domain_languages/nlvr_language.py | NlvrLanguage.below | def below(self, objects: Set[Object]) -> Set[Object]:
"""
Returns the set of objects in the same boxes that are below the given objects. That is, if
the input is a set of two objects, one in each box, we will return a union of the objects
below the first object in the first box, and thos... | python | def below(self, objects: Set[Object]) -> Set[Object]:
"""
Returns the set of objects in the same boxes that are below the given objects. That is, if
the input is a set of two objects, one in each box, we will return a union of the objects
below the first object in the first box, and thos... | [
"def",
"below",
"(",
"self",
",",
"objects",
":",
"Set",
"[",
"Object",
"]",
")",
"->",
"Set",
"[",
"Object",
"]",
":",
"objects_per_box",
"=",
"self",
".",
"_separate_objects_by_boxes",
"(",
"objects",
")",
"return_set",
"=",
"set",
"(",
")",
"for",
"... | Returns the set of objects in the same boxes that are below the given objects. That is, if
the input is a set of two objects, one in each box, we will return a union of the objects
below the first object in the first box, and those below the second object in the second box. | [
"Returns",
"the",
"set",
"of",
"objects",
"in",
"the",
"same",
"boxes",
"that",
"are",
"below",
"the",
"given",
"objects",
".",
"That",
"is",
"if",
"the",
"input",
"is",
"a",
"set",
"of",
"two",
"objects",
"one",
"in",
"each",
"box",
"we",
"will",
"r... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/domain_languages/nlvr_language.py#L387-L401 | train |
allenai/allennlp | allennlp/semparse/domain_languages/nlvr_language.py | NlvrLanguage._objects_touch_each_other | def _objects_touch_each_other(self, object1: Object, object2: Object) -> bool:
"""
Returns true iff the objects touch each other.
"""
in_vertical_range = object1.y_loc <= object2.y_loc + object2.size and \
object1.y_loc + object1.size >= object2.y_loc
... | python | def _objects_touch_each_other(self, object1: Object, object2: Object) -> bool:
"""
Returns true iff the objects touch each other.
"""
in_vertical_range = object1.y_loc <= object2.y_loc + object2.size and \
object1.y_loc + object1.size >= object2.y_loc
... | [
"def",
"_objects_touch_each_other",
"(",
"self",
",",
"object1",
":",
"Object",
",",
"object2",
":",
"Object",
")",
"->",
"bool",
":",
"in_vertical_range",
"=",
"object1",
".",
"y_loc",
"<=",
"object2",
".",
"y_loc",
"+",
"object2",
".",
"size",
"and",
"ob... | Returns true iff the objects touch each other. | [
"Returns",
"true",
"iff",
"the",
"objects",
"touch",
"each",
"other",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/domain_languages/nlvr_language.py#L654-L666 | train |
allenai/allennlp | allennlp/semparse/domain_languages/nlvr_language.py | NlvrLanguage._separate_objects_by_boxes | def _separate_objects_by_boxes(self, objects: Set[Object]) -> Dict[Box, List[Object]]:
"""
Given a set of objects, separate them by the boxes they belong to and return a dict.
"""
objects_per_box: Dict[Box, List[Object]] = defaultdict(list)
for box in self.boxes:
for ... | python | def _separate_objects_by_boxes(self, objects: Set[Object]) -> Dict[Box, List[Object]]:
"""
Given a set of objects, separate them by the boxes they belong to and return a dict.
"""
objects_per_box: Dict[Box, List[Object]] = defaultdict(list)
for box in self.boxes:
for ... | [
"def",
"_separate_objects_by_boxes",
"(",
"self",
",",
"objects",
":",
"Set",
"[",
"Object",
"]",
")",
"->",
"Dict",
"[",
"Box",
",",
"List",
"[",
"Object",
"]",
"]",
":",
"objects_per_box",
":",
"Dict",
"[",
"Box",
",",
"List",
"[",
"Object",
"]",
"... | Given a set of objects, separate them by the boxes they belong to and return a dict. | [
"Given",
"a",
"set",
"of",
"objects",
"separate",
"them",
"by",
"the",
"boxes",
"they",
"belong",
"to",
"and",
"return",
"a",
"dict",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/domain_languages/nlvr_language.py#L668-L677 | train |
allenai/allennlp | allennlp/semparse/domain_languages/nlvr_language.py | NlvrLanguage._get_objects_with_same_attribute | def _get_objects_with_same_attribute(self,
objects: Set[Object],
attribute_function: Callable[[Object], str]) -> Set[Object]:
"""
Returns the set of objects for which the attribute function returns an attribute value that
... | python | def _get_objects_with_same_attribute(self,
objects: Set[Object],
attribute_function: Callable[[Object], str]) -> Set[Object]:
"""
Returns the set of objects for which the attribute function returns an attribute value that
... | [
"def",
"_get_objects_with_same_attribute",
"(",
"self",
",",
"objects",
":",
"Set",
"[",
"Object",
"]",
",",
"attribute_function",
":",
"Callable",
"[",
"[",
"Object",
"]",
",",
"str",
"]",
")",
"->",
"Set",
"[",
"Object",
"]",
":",
"objects_of_attribute",
... | Returns the set of objects for which the attribute function returns an attribute value that
is most frequent in the initial set, if the frequency is greater than 1. If not, all
objects have different attribute values, and this method returns an empty set. | [
"Returns",
"the",
"set",
"of",
"objects",
"for",
"which",
"the",
"attribute",
"function",
"returns",
"an",
"attribute",
"value",
"that",
"is",
"most",
"frequent",
"in",
"the",
"initial",
"set",
"if",
"the",
"frequency",
"is",
"greater",
"than",
"1",
".",
"... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/domain_languages/nlvr_language.py#L679-L695 | train |
allenai/allennlp | allennlp/nn/util.py | has_tensor | def has_tensor(obj) -> bool:
"""
Given a possibly complex data structure,
check if it has any torch.Tensors in it.
"""
if isinstance(obj, torch.Tensor):
return True
elif isinstance(obj, dict):
return any(has_tensor(value) for value in obj.values())
elif isinstance(obj, (list,... | python | def has_tensor(obj) -> bool:
"""
Given a possibly complex data structure,
check if it has any torch.Tensors in it.
"""
if isinstance(obj, torch.Tensor):
return True
elif isinstance(obj, dict):
return any(has_tensor(value) for value in obj.values())
elif isinstance(obj, (list,... | [
"def",
"has_tensor",
"(",
"obj",
")",
"->",
"bool",
":",
"if",
"isinstance",
"(",
"obj",
",",
"torch",
".",
"Tensor",
")",
":",
"return",
"True",
"elif",
"isinstance",
"(",
"obj",
",",
"dict",
")",
":",
"return",
"any",
"(",
"has_tensor",
"(",
"value... | Given a possibly complex data structure,
check if it has any torch.Tensors in it. | [
"Given",
"a",
"possibly",
"complex",
"data",
"structure",
"check",
"if",
"it",
"has",
"any",
"torch",
".",
"Tensors",
"in",
"it",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/nn/util.py#L20-L32 | train |
allenai/allennlp | allennlp/nn/util.py | move_to_device | def move_to_device(obj, cuda_device: int):
"""
Given a structure (possibly) containing Tensors on the CPU,
move all the Tensors to the specified GPU (or do nothing, if they should be on the CPU).
"""
if cuda_device < 0 or not has_tensor(obj):
return obj
elif isinstance(obj, torch.Tensor)... | python | def move_to_device(obj, cuda_device: int):
"""
Given a structure (possibly) containing Tensors on the CPU,
move all the Tensors to the specified GPU (or do nothing, if they should be on the CPU).
"""
if cuda_device < 0 or not has_tensor(obj):
return obj
elif isinstance(obj, torch.Tensor)... | [
"def",
"move_to_device",
"(",
"obj",
",",
"cuda_device",
":",
"int",
")",
":",
"if",
"cuda_device",
"<",
"0",
"or",
"not",
"has_tensor",
"(",
"obj",
")",
":",
"return",
"obj",
"elif",
"isinstance",
"(",
"obj",
",",
"torch",
".",
"Tensor",
")",
":",
"... | Given a structure (possibly) containing Tensors on the CPU,
move all the Tensors to the specified GPU (or do nothing, if they should be on the CPU). | [
"Given",
"a",
"structure",
"(",
"possibly",
")",
"containing",
"Tensors",
"on",
"the",
"CPU",
"move",
"all",
"the",
"Tensors",
"to",
"the",
"specified",
"GPU",
"(",
"or",
"do",
"nothing",
"if",
"they",
"should",
"be",
"on",
"the",
"CPU",
")",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/nn/util.py#L35-L51 | train |
allenai/allennlp | allennlp/nn/util.py | clamp_tensor | def clamp_tensor(tensor, minimum, maximum):
"""
Supports sparse and dense tensors.
Returns a tensor with values clamped between the provided minimum and maximum,
without modifying the original tensor.
"""
if tensor.is_sparse:
coalesced_tensor = tensor.coalesce()
# pylint: disable... | python | def clamp_tensor(tensor, minimum, maximum):
"""
Supports sparse and dense tensors.
Returns a tensor with values clamped between the provided minimum and maximum,
without modifying the original tensor.
"""
if tensor.is_sparse:
coalesced_tensor = tensor.coalesce()
# pylint: disable... | [
"def",
"clamp_tensor",
"(",
"tensor",
",",
"minimum",
",",
"maximum",
")",
":",
"if",
"tensor",
".",
"is_sparse",
":",
"coalesced_tensor",
"=",
"tensor",
".",
"coalesce",
"(",
")",
"# pylint: disable=protected-access",
"coalesced_tensor",
".",
"_values",
"(",
")... | Supports sparse and dense tensors.
Returns a tensor with values clamped between the provided minimum and maximum,
without modifying the original tensor. | [
"Supports",
"sparse",
"and",
"dense",
"tensors",
".",
"Returns",
"a",
"tensor",
"with",
"values",
"clamped",
"between",
"the",
"provided",
"minimum",
"and",
"maximum",
"without",
"modifying",
"the",
"original",
"tensor",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/nn/util.py#L54-L66 | train |
allenai/allennlp | allennlp/nn/util.py | batch_tensor_dicts | def batch_tensor_dicts(tensor_dicts: List[Dict[str, torch.Tensor]],
remove_trailing_dimension: bool = False) -> Dict[str, torch.Tensor]:
"""
Takes a list of tensor dictionaries, where each dictionary is assumed to have matching keys,
and returns a single dictionary with all tensors wi... | python | def batch_tensor_dicts(tensor_dicts: List[Dict[str, torch.Tensor]],
remove_trailing_dimension: bool = False) -> Dict[str, torch.Tensor]:
"""
Takes a list of tensor dictionaries, where each dictionary is assumed to have matching keys,
and returns a single dictionary with all tensors wi... | [
"def",
"batch_tensor_dicts",
"(",
"tensor_dicts",
":",
"List",
"[",
"Dict",
"[",
"str",
",",
"torch",
".",
"Tensor",
"]",
"]",
",",
"remove_trailing_dimension",
":",
"bool",
"=",
"False",
")",
"->",
"Dict",
"[",
"str",
",",
"torch",
".",
"Tensor",
"]",
... | Takes a list of tensor dictionaries, where each dictionary is assumed to have matching keys,
and returns a single dictionary with all tensors with the same key batched together.
Parameters
----------
tensor_dicts : ``List[Dict[str, torch.Tensor]]``
The list of tensor dictionaries to batch.
... | [
"Takes",
"a",
"list",
"of",
"tensor",
"dictionaries",
"where",
"each",
"dictionary",
"is",
"assumed",
"to",
"have",
"matching",
"keys",
"and",
"returns",
"a",
"single",
"dictionary",
"with",
"all",
"tensors",
"with",
"the",
"same",
"key",
"batched",
"together"... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/nn/util.py#L69-L93 | train |
allenai/allennlp | allennlp/nn/util.py | get_mask_from_sequence_lengths | def get_mask_from_sequence_lengths(sequence_lengths: torch.Tensor, max_length: int) -> torch.Tensor:
"""
Given a variable of shape ``(batch_size,)`` that represents the sequence lengths of each batch
element, this function returns a ``(batch_size, max_length)`` mask variable. For example, if
our input ... | python | def get_mask_from_sequence_lengths(sequence_lengths: torch.Tensor, max_length: int) -> torch.Tensor:
"""
Given a variable of shape ``(batch_size,)`` that represents the sequence lengths of each batch
element, this function returns a ``(batch_size, max_length)`` mask variable. For example, if
our input ... | [
"def",
"get_mask_from_sequence_lengths",
"(",
"sequence_lengths",
":",
"torch",
".",
"Tensor",
",",
"max_length",
":",
"int",
")",
"->",
"torch",
".",
"Tensor",
":",
"# (batch_size, max_length)",
"ones",
"=",
"sequence_lengths",
".",
"new_ones",
"(",
"sequence_lengt... | Given a variable of shape ``(batch_size,)`` that represents the sequence lengths of each batch
element, this function returns a ``(batch_size, max_length)`` mask variable. For example, if
our input was ``[2, 2, 3]``, with a ``max_length`` of 4, we'd return
``[[1, 1, 0, 0], [1, 1, 0, 0], [1, 1, 1, 0]]``.
... | [
"Given",
"a",
"variable",
"of",
"shape",
"(",
"batch_size",
")",
"that",
"represents",
"the",
"sequence",
"lengths",
"of",
"each",
"batch",
"element",
"this",
"function",
"returns",
"a",
"(",
"batch_size",
"max_length",
")",
"mask",
"variable",
".",
"For",
"... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/nn/util.py#L115-L129 | train |
allenai/allennlp | allennlp/nn/util.py | sort_batch_by_length | def sort_batch_by_length(tensor: torch.Tensor, sequence_lengths: torch.Tensor):
"""
Sort a batch first tensor by some specified lengths.
Parameters
----------
tensor : torch.FloatTensor, required.
A batch first Pytorch tensor.
sequence_lengths : torch.LongTensor, required.
A ten... | python | def sort_batch_by_length(tensor: torch.Tensor, sequence_lengths: torch.Tensor):
"""
Sort a batch first tensor by some specified lengths.
Parameters
----------
tensor : torch.FloatTensor, required.
A batch first Pytorch tensor.
sequence_lengths : torch.LongTensor, required.
A ten... | [
"def",
"sort_batch_by_length",
"(",
"tensor",
":",
"torch",
".",
"Tensor",
",",
"sequence_lengths",
":",
"torch",
".",
"Tensor",
")",
":",
"if",
"not",
"isinstance",
"(",
"tensor",
",",
"torch",
".",
"Tensor",
")",
"or",
"not",
"isinstance",
"(",
"sequence... | Sort a batch first tensor by some specified lengths.
Parameters
----------
tensor : torch.FloatTensor, required.
A batch first Pytorch tensor.
sequence_lengths : torch.LongTensor, required.
A tensor representing the lengths of some dimension of the tensor which
we want to sort b... | [
"Sort",
"a",
"batch",
"first",
"tensor",
"by",
"some",
"specified",
"lengths",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/nn/util.py#L132-L169 | train |
allenai/allennlp | allennlp/nn/util.py | get_final_encoder_states | def get_final_encoder_states(encoder_outputs: torch.Tensor,
mask: torch.Tensor,
bidirectional: bool = False) -> torch.Tensor:
"""
Given the output from a ``Seq2SeqEncoder``, with shape ``(batch_size, sequence_length,
encoding_dim)``, this method retu... | python | def get_final_encoder_states(encoder_outputs: torch.Tensor,
mask: torch.Tensor,
bidirectional: bool = False) -> torch.Tensor:
"""
Given the output from a ``Seq2SeqEncoder``, with shape ``(batch_size, sequence_length,
encoding_dim)``, this method retu... | [
"def",
"get_final_encoder_states",
"(",
"encoder_outputs",
":",
"torch",
".",
"Tensor",
",",
"mask",
":",
"torch",
".",
"Tensor",
",",
"bidirectional",
":",
"bool",
"=",
"False",
")",
"->",
"torch",
".",
"Tensor",
":",
"# These are the indices of the last words in... | Given the output from a ``Seq2SeqEncoder``, with shape ``(batch_size, sequence_length,
encoding_dim)``, this method returns the final hidden state for each element of the batch,
giving a tensor of shape ``(batch_size, encoding_dim)``. This is not as simple as
``encoder_outputs[:, -1]``, because the sequenc... | [
"Given",
"the",
"output",
"from",
"a",
"Seq2SeqEncoder",
"with",
"shape",
"(",
"batch_size",
"sequence_length",
"encoding_dim",
")",
"this",
"method",
"returns",
"the",
"final",
"hidden",
"state",
"for",
"each",
"element",
"of",
"the",
"batch",
"giving",
"a",
... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/nn/util.py#L172-L202 | train |
allenai/allennlp | allennlp/nn/util.py | get_dropout_mask | def get_dropout_mask(dropout_probability: float, tensor_for_masking: torch.Tensor):
"""
Computes and returns an element-wise dropout mask for a given tensor, where
each element in the mask is dropped out with probability dropout_probability.
Note that the mask is NOT applied to the tensor - the tensor i... | python | def get_dropout_mask(dropout_probability: float, tensor_for_masking: torch.Tensor):
"""
Computes and returns an element-wise dropout mask for a given tensor, where
each element in the mask is dropped out with probability dropout_probability.
Note that the mask is NOT applied to the tensor - the tensor i... | [
"def",
"get_dropout_mask",
"(",
"dropout_probability",
":",
"float",
",",
"tensor_for_masking",
":",
"torch",
".",
"Tensor",
")",
":",
"binary_mask",
"=",
"(",
"torch",
".",
"rand",
"(",
"tensor_for_masking",
".",
"size",
"(",
")",
")",
">",
"dropout_probabili... | Computes and returns an element-wise dropout mask for a given tensor, where
each element in the mask is dropped out with probability dropout_probability.
Note that the mask is NOT applied to the tensor - the tensor is passed to retain
the correct CUDA tensor type for the mask.
Parameters
----------... | [
"Computes",
"and",
"returns",
"an",
"element",
"-",
"wise",
"dropout",
"mask",
"for",
"a",
"given",
"tensor",
"where",
"each",
"element",
"in",
"the",
"mask",
"is",
"dropped",
"out",
"with",
"probability",
"dropout_probability",
".",
"Note",
"that",
"the",
"... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/nn/util.py#L205-L228 | train |
allenai/allennlp | allennlp/nn/util.py | masked_softmax | def masked_softmax(vector: torch.Tensor,
mask: torch.Tensor,
dim: int = -1,
memory_efficient: bool = False,
mask_fill_value: float = -1e32) -> torch.Tensor:
"""
``torch.nn.functional.softmax(vector)`` does not work if some elements of `... | python | def masked_softmax(vector: torch.Tensor,
mask: torch.Tensor,
dim: int = -1,
memory_efficient: bool = False,
mask_fill_value: float = -1e32) -> torch.Tensor:
"""
``torch.nn.functional.softmax(vector)`` does not work if some elements of `... | [
"def",
"masked_softmax",
"(",
"vector",
":",
"torch",
".",
"Tensor",
",",
"mask",
":",
"torch",
".",
"Tensor",
",",
"dim",
":",
"int",
"=",
"-",
"1",
",",
"memory_efficient",
":",
"bool",
"=",
"False",
",",
"mask_fill_value",
":",
"float",
"=",
"-",
... | ``torch.nn.functional.softmax(vector)`` does not work if some elements of ``vector`` should be
masked. This performs a softmax on just the non-masked portions of ``vector``. Passing
``None`` in for the mask is also acceptable; you'll just get a regular softmax.
``vector`` can have an arbitrary number of ... | [
"torch",
".",
"nn",
".",
"functional",
".",
"softmax",
"(",
"vector",
")",
"does",
"not",
"work",
"if",
"some",
"elements",
"of",
"vector",
"should",
"be",
"masked",
".",
"This",
"performs",
"a",
"softmax",
"on",
"just",
"the",
"non",
"-",
"masked",
"p... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/nn/util.py#L231-L269 | train |
allenai/allennlp | allennlp/nn/util.py | masked_log_softmax | def masked_log_softmax(vector: torch.Tensor, mask: torch.Tensor, dim: int = -1) -> torch.Tensor:
"""
``torch.nn.functional.log_softmax(vector)`` does not work if some elements of ``vector`` should be
masked. This performs a log_softmax on just the non-masked portions of ``vector``. Passing
``None`` in... | python | def masked_log_softmax(vector: torch.Tensor, mask: torch.Tensor, dim: int = -1) -> torch.Tensor:
"""
``torch.nn.functional.log_softmax(vector)`` does not work if some elements of ``vector`` should be
masked. This performs a log_softmax on just the non-masked portions of ``vector``. Passing
``None`` in... | [
"def",
"masked_log_softmax",
"(",
"vector",
":",
"torch",
".",
"Tensor",
",",
"mask",
":",
"torch",
".",
"Tensor",
",",
"dim",
":",
"int",
"=",
"-",
"1",
")",
"->",
"torch",
".",
"Tensor",
":",
"if",
"mask",
"is",
"not",
"None",
":",
"mask",
"=",
... | ``torch.nn.functional.log_softmax(vector)`` does not work if some elements of ``vector`` should be
masked. This performs a log_softmax on just the non-masked portions of ``vector``. Passing
``None`` in for the mask is also acceptable; you'll just get a regular log_softmax.
``vector`` can have an arbitrar... | [
"torch",
".",
"nn",
".",
"functional",
".",
"log_softmax",
"(",
"vector",
")",
"does",
"not",
"work",
"if",
"some",
"elements",
"of",
"vector",
"should",
"be",
"masked",
".",
"This",
"performs",
"a",
"log_softmax",
"on",
"just",
"the",
"non",
"-",
"maske... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/nn/util.py#L272-L303 | train |
allenai/allennlp | allennlp/nn/util.py | masked_max | def masked_max(vector: torch.Tensor,
mask: torch.Tensor,
dim: int,
keepdim: bool = False,
min_val: float = -1e7) -> torch.Tensor:
"""
To calculate max along certain dimensions on masked values
Parameters
----------
vector : ``torch.Tensor`... | python | def masked_max(vector: torch.Tensor,
mask: torch.Tensor,
dim: int,
keepdim: bool = False,
min_val: float = -1e7) -> torch.Tensor:
"""
To calculate max along certain dimensions on masked values
Parameters
----------
vector : ``torch.Tensor`... | [
"def",
"masked_max",
"(",
"vector",
":",
"torch",
".",
"Tensor",
",",
"mask",
":",
"torch",
".",
"Tensor",
",",
"dim",
":",
"int",
",",
"keepdim",
":",
"bool",
"=",
"False",
",",
"min_val",
":",
"float",
"=",
"-",
"1e7",
")",
"->",
"torch",
".",
... | To calculate max along certain dimensions on masked values
Parameters
----------
vector : ``torch.Tensor``
The vector to calculate max, assume unmasked parts are already zeros
mask : ``torch.Tensor``
The mask of the vector. It must be broadcastable with vector.
dim : ``int``
... | [
"To",
"calculate",
"max",
"along",
"certain",
"dimensions",
"on",
"masked",
"values"
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/nn/util.py#L306-L334 | train |
allenai/allennlp | allennlp/nn/util.py | masked_mean | def masked_mean(vector: torch.Tensor,
mask: torch.Tensor,
dim: int,
keepdim: bool = False,
eps: float = 1e-8) -> torch.Tensor:
"""
To calculate mean along certain dimensions on masked values
Parameters
----------
vector : ``torch.Tenso... | python | def masked_mean(vector: torch.Tensor,
mask: torch.Tensor,
dim: int,
keepdim: bool = False,
eps: float = 1e-8) -> torch.Tensor:
"""
To calculate mean along certain dimensions on masked values
Parameters
----------
vector : ``torch.Tenso... | [
"def",
"masked_mean",
"(",
"vector",
":",
"torch",
".",
"Tensor",
",",
"mask",
":",
"torch",
".",
"Tensor",
",",
"dim",
":",
"int",
",",
"keepdim",
":",
"bool",
"=",
"False",
",",
"eps",
":",
"float",
"=",
"1e-8",
")",
"->",
"torch",
".",
"Tensor",... | To calculate mean along certain dimensions on masked values
Parameters
----------
vector : ``torch.Tensor``
The vector to calculate mean.
mask : ``torch.Tensor``
The mask of the vector. It must be broadcastable with vector.
dim : ``int``
The dimension to calculate mean
k... | [
"To",
"calculate",
"mean",
"along",
"certain",
"dimensions",
"on",
"masked",
"values"
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/nn/util.py#L337-L367 | train |
allenai/allennlp | allennlp/nn/util.py | masked_flip | def masked_flip(padded_sequence: torch.Tensor,
sequence_lengths: List[int]) -> torch.Tensor:
"""
Flips a padded tensor along the time dimension without affecting masked entries.
Parameters
----------
padded_sequence : ``torch.Tensor``
The tensor to flip a... | python | def masked_flip(padded_sequence: torch.Tensor,
sequence_lengths: List[int]) -> torch.Tensor:
"""
Flips a padded tensor along the time dimension without affecting masked entries.
Parameters
----------
padded_sequence : ``torch.Tensor``
The tensor to flip a... | [
"def",
"masked_flip",
"(",
"padded_sequence",
":",
"torch",
".",
"Tensor",
",",
"sequence_lengths",
":",
"List",
"[",
"int",
"]",
")",
"->",
"torch",
".",
"Tensor",
":",
"assert",
"padded_sequence",
".",
"size",
"(",
"0",
")",
"==",
"len",
"(",
"sequence... | Flips a padded tensor along the time dimension without affecting masked entries.
Parameters
----------
padded_sequence : ``torch.Tensor``
The tensor to flip along the time dimension.
Assumed to be of dimensions (batch size, num timesteps, ...)
sequence_lengths : ... | [
"Flips",
"a",
"padded",
"tensor",
"along",
"the",
"time",
"dimension",
"without",
"affecting",
"masked",
"entries",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/nn/util.py#L370-L392 | train |
allenai/allennlp | allennlp/nn/util.py | viterbi_decode | def viterbi_decode(tag_sequence: torch.Tensor,
transition_matrix: torch.Tensor,
tag_observations: Optional[List[int]] = None):
"""
Perform Viterbi decoding in log space over a sequence given a transition matrix
specifying pairwise (transition) potentials between tags an... | python | def viterbi_decode(tag_sequence: torch.Tensor,
transition_matrix: torch.Tensor,
tag_observations: Optional[List[int]] = None):
"""
Perform Viterbi decoding in log space over a sequence given a transition matrix
specifying pairwise (transition) potentials between tags an... | [
"def",
"viterbi_decode",
"(",
"tag_sequence",
":",
"torch",
".",
"Tensor",
",",
"transition_matrix",
":",
"torch",
".",
"Tensor",
",",
"tag_observations",
":",
"Optional",
"[",
"List",
"[",
"int",
"]",
"]",
"=",
"None",
")",
":",
"sequence_length",
",",
"n... | Perform Viterbi decoding in log space over a sequence given a transition matrix
specifying pairwise (transition) potentials between tags and a matrix of shape
(sequence_length, num_tags) specifying unary potentials for possible tags per
timestep.
Parameters
----------
tag_sequence : torch.Tenso... | [
"Perform",
"Viterbi",
"decoding",
"in",
"log",
"space",
"over",
"a",
"sequence",
"given",
"a",
"transition",
"matrix",
"specifying",
"pairwise",
"(",
"transition",
")",
"potentials",
"between",
"tags",
"and",
"a",
"matrix",
"of",
"shape",
"(",
"sequence_length",... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/nn/util.py#L395-L478 | train |
allenai/allennlp | allennlp/nn/util.py | get_text_field_mask | def get_text_field_mask(text_field_tensors: Dict[str, torch.Tensor],
num_wrapping_dims: int = 0) -> torch.LongTensor:
"""
Takes the dictionary of tensors produced by a ``TextField`` and returns a mask
with 0 where the tokens are padding, and 1 otherwise. We also handle ``TextFields`... | python | def get_text_field_mask(text_field_tensors: Dict[str, torch.Tensor],
num_wrapping_dims: int = 0) -> torch.LongTensor:
"""
Takes the dictionary of tensors produced by a ``TextField`` and returns a mask
with 0 where the tokens are padding, and 1 otherwise. We also handle ``TextFields`... | [
"def",
"get_text_field_mask",
"(",
"text_field_tensors",
":",
"Dict",
"[",
"str",
",",
"torch",
".",
"Tensor",
"]",
",",
"num_wrapping_dims",
":",
"int",
"=",
"0",
")",
"->",
"torch",
".",
"LongTensor",
":",
"if",
"\"mask\"",
"in",
"text_field_tensors",
":",... | Takes the dictionary of tensors produced by a ``TextField`` and returns a mask
with 0 where the tokens are padding, and 1 otherwise. We also handle ``TextFields``
wrapped by an arbitrary number of ``ListFields``, where the number of wrapping ``ListFields``
is given by ``num_wrapping_dims``.
If ``num_w... | [
"Takes",
"the",
"dictionary",
"of",
"tensors",
"produced",
"by",
"a",
"TextField",
"and",
"returns",
"a",
"mask",
"with",
"0",
"where",
"the",
"tokens",
"are",
"padding",
"and",
"1",
"otherwise",
".",
"We",
"also",
"handle",
"TextFields",
"wrapped",
"by",
... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/nn/util.py#L481-L527 | train |
allenai/allennlp | allennlp/nn/util.py | weighted_sum | def weighted_sum(matrix: torch.Tensor, attention: torch.Tensor) -> torch.Tensor:
"""
Takes a matrix of vectors and a set of weights over the rows in the matrix (which we call an
"attention" vector), and returns a weighted sum of the rows in the matrix. This is the typical
computation performed after an... | python | def weighted_sum(matrix: torch.Tensor, attention: torch.Tensor) -> torch.Tensor:
"""
Takes a matrix of vectors and a set of weights over the rows in the matrix (which we call an
"attention" vector), and returns a weighted sum of the rows in the matrix. This is the typical
computation performed after an... | [
"def",
"weighted_sum",
"(",
"matrix",
":",
"torch",
".",
"Tensor",
",",
"attention",
":",
"torch",
".",
"Tensor",
")",
"->",
"torch",
".",
"Tensor",
":",
"# We'll special-case a few settings here, where there are efficient (but poorly-named)",
"# operations in pytorch that ... | Takes a matrix of vectors and a set of weights over the rows in the matrix (which we call an
"attention" vector), and returns a weighted sum of the rows in the matrix. This is the typical
computation performed after an attention mechanism.
Note that while we call this a "matrix" of vectors and an attentio... | [
"Takes",
"a",
"matrix",
"of",
"vectors",
"and",
"a",
"set",
"of",
"weights",
"over",
"the",
"rows",
"in",
"the",
"matrix",
"(",
"which",
"we",
"call",
"an",
"attention",
"vector",
")",
"and",
"returns",
"a",
"weighted",
"sum",
"of",
"the",
"rows",
"in"... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/nn/util.py#L530-L566 | train |
allenai/allennlp | allennlp/nn/util.py | sequence_cross_entropy_with_logits | def sequence_cross_entropy_with_logits(logits: torch.FloatTensor,
targets: torch.LongTensor,
weights: torch.FloatTensor,
average: str = "batch",
label_smoothing: fl... | python | def sequence_cross_entropy_with_logits(logits: torch.FloatTensor,
targets: torch.LongTensor,
weights: torch.FloatTensor,
average: str = "batch",
label_smoothing: fl... | [
"def",
"sequence_cross_entropy_with_logits",
"(",
"logits",
":",
"torch",
".",
"FloatTensor",
",",
"targets",
":",
"torch",
".",
"LongTensor",
",",
"weights",
":",
"torch",
".",
"FloatTensor",
",",
"average",
":",
"str",
"=",
"\"batch\"",
",",
"label_smoothing",... | Computes the cross entropy loss of a sequence, weighted with respect to
some user provided weights. Note that the weighting here is not the same as
in the :func:`torch.nn.CrossEntropyLoss()` criterion, which is weighting
classes; here we are weighting the loss contribution from particular elements
in th... | [
"Computes",
"the",
"cross",
"entropy",
"loss",
"of",
"a",
"sequence",
"weighted",
"with",
"respect",
"to",
"some",
"user",
"provided",
"weights",
".",
"Note",
"that",
"the",
"weighting",
"here",
"is",
"not",
"the",
"same",
"as",
"in",
"the",
":",
"func",
... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/nn/util.py#L569-L648 | train |
allenai/allennlp | allennlp/nn/util.py | replace_masked_values | def replace_masked_values(tensor: torch.Tensor, mask: torch.Tensor, replace_with: float) -> torch.Tensor:
"""
Replaces all masked values in ``tensor`` with ``replace_with``. ``mask`` must be broadcastable
to the same shape as ``tensor``. We require that ``tensor.dim() == mask.dim()``, as otherwise we
w... | python | def replace_masked_values(tensor: torch.Tensor, mask: torch.Tensor, replace_with: float) -> torch.Tensor:
"""
Replaces all masked values in ``tensor`` with ``replace_with``. ``mask`` must be broadcastable
to the same shape as ``tensor``. We require that ``tensor.dim() == mask.dim()``, as otherwise we
w... | [
"def",
"replace_masked_values",
"(",
"tensor",
":",
"torch",
".",
"Tensor",
",",
"mask",
":",
"torch",
".",
"Tensor",
",",
"replace_with",
":",
"float",
")",
"->",
"torch",
".",
"Tensor",
":",
"if",
"tensor",
".",
"dim",
"(",
")",
"!=",
"mask",
".",
... | Replaces all masked values in ``tensor`` with ``replace_with``. ``mask`` must be broadcastable
to the same shape as ``tensor``. We require that ``tensor.dim() == mask.dim()``, as otherwise we
won't know which dimensions of the mask to unsqueeze.
This just does ``tensor.masked_fill()``, except the pytorch ... | [
"Replaces",
"all",
"masked",
"values",
"in",
"tensor",
"with",
"replace_with",
".",
"mask",
"must",
"be",
"broadcastable",
"to",
"the",
"same",
"shape",
"as",
"tensor",
".",
"We",
"require",
"that",
"tensor",
".",
"dim",
"()",
"==",
"mask",
".",
"dim",
"... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/nn/util.py#L651-L663 | train |
allenai/allennlp | allennlp/nn/util.py | tensors_equal | def tensors_equal(tensor1: torch.Tensor, tensor2: torch.Tensor, tolerance: float = 1e-12) -> bool:
"""
A check for tensor equality (by value). We make sure that the tensors have the same shape,
then check all of the entries in the tensor for equality. We additionally allow the input
tensors to be list... | python | def tensors_equal(tensor1: torch.Tensor, tensor2: torch.Tensor, tolerance: float = 1e-12) -> bool:
"""
A check for tensor equality (by value). We make sure that the tensors have the same shape,
then check all of the entries in the tensor for equality. We additionally allow the input
tensors to be list... | [
"def",
"tensors_equal",
"(",
"tensor1",
":",
"torch",
".",
"Tensor",
",",
"tensor2",
":",
"torch",
".",
"Tensor",
",",
"tolerance",
":",
"float",
"=",
"1e-12",
")",
"->",
"bool",
":",
"# pylint: disable=too-many-return-statements",
"if",
"isinstance",
"(",
"te... | A check for tensor equality (by value). We make sure that the tensors have the same shape,
then check all of the entries in the tensor for equality. We additionally allow the input
tensors to be lists or dictionaries, where we then do the above check on every position in the
list / item in the dictionary.... | [
"A",
"check",
"for",
"tensor",
"equality",
"(",
"by",
"value",
")",
".",
"We",
"make",
"sure",
"that",
"the",
"tensors",
"have",
"the",
"same",
"shape",
"then",
"check",
"all",
"of",
"the",
"entries",
"in",
"the",
"tensor",
"for",
"equality",
".",
"We"... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/nn/util.py#L666-L699 | train |
allenai/allennlp | allennlp/nn/util.py | device_mapping | def device_mapping(cuda_device: int):
"""
In order to `torch.load()` a GPU-trained model onto a CPU (or specific GPU),
you have to supply a `map_location` function. Call this with
the desired `cuda_device` to get the function that `torch.load()` needs.
"""
def inner_device_mapping(storage: torc... | python | def device_mapping(cuda_device: int):
"""
In order to `torch.load()` a GPU-trained model onto a CPU (or specific GPU),
you have to supply a `map_location` function. Call this with
the desired `cuda_device` to get the function that `torch.load()` needs.
"""
def inner_device_mapping(storage: torc... | [
"def",
"device_mapping",
"(",
"cuda_device",
":",
"int",
")",
":",
"def",
"inner_device_mapping",
"(",
"storage",
":",
"torch",
".",
"Storage",
",",
"location",
")",
"->",
"torch",
".",
"Storage",
":",
"# pylint: disable=unused-argument",
"if",
"cuda_device",
">... | In order to `torch.load()` a GPU-trained model onto a CPU (or specific GPU),
you have to supply a `map_location` function. Call this with
the desired `cuda_device` to get the function that `torch.load()` needs. | [
"In",
"order",
"to",
"torch",
".",
"load",
"()",
"a",
"GPU",
"-",
"trained",
"model",
"onto",
"a",
"CPU",
"(",
"or",
"specific",
"GPU",
")",
"you",
"have",
"to",
"supply",
"a",
"map_location",
"function",
".",
"Call",
"this",
"with",
"the",
"desired",
... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/nn/util.py#L702-L715 | train |
allenai/allennlp | allennlp/nn/util.py | combine_tensors | def combine_tensors(combination: str, tensors: List[torch.Tensor]) -> torch.Tensor:
"""
Combines a list of tensors using element-wise operations and concatenation, specified by a
``combination`` string. The string refers to (1-indexed) positions in the input tensor list,
and looks like ``"1,2,1+2,3-1"`... | python | def combine_tensors(combination: str, tensors: List[torch.Tensor]) -> torch.Tensor:
"""
Combines a list of tensors using element-wise operations and concatenation, specified by a
``combination`` string. The string refers to (1-indexed) positions in the input tensor list,
and looks like ``"1,2,1+2,3-1"`... | [
"def",
"combine_tensors",
"(",
"combination",
":",
"str",
",",
"tensors",
":",
"List",
"[",
"torch",
".",
"Tensor",
"]",
")",
"->",
"torch",
".",
"Tensor",
":",
"if",
"len",
"(",
"tensors",
")",
">",
"9",
":",
"raise",
"ConfigurationError",
"(",
"\"Dou... | Combines a list of tensors using element-wise operations and concatenation, specified by a
``combination`` string. The string refers to (1-indexed) positions in the input tensor list,
and looks like ``"1,2,1+2,3-1"``.
We allow the following kinds of combinations: ``x``, ``x*y``, ``x+y``, ``x-y``, and ``x/... | [
"Combines",
"a",
"list",
"of",
"tensors",
"using",
"element",
"-",
"wise",
"operations",
"and",
"concatenation",
"specified",
"by",
"a",
"combination",
"string",
".",
"The",
"string",
"refers",
"to",
"(",
"1",
"-",
"indexed",
")",
"positions",
"in",
"the",
... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/nn/util.py#L718-L746 | train |
allenai/allennlp | allennlp/nn/util.py | _rindex | def _rindex(sequence: Sequence[T], obj: T) -> int:
"""
Return zero-based index in the sequence of the last item whose value is equal to obj. Raises a
ValueError if there is no such item.
Parameters
----------
sequence : ``Sequence[T]``
obj : ``T``
Returns
-------
zero-based in... | python | def _rindex(sequence: Sequence[T], obj: T) -> int:
"""
Return zero-based index in the sequence of the last item whose value is equal to obj. Raises a
ValueError if there is no such item.
Parameters
----------
sequence : ``Sequence[T]``
obj : ``T``
Returns
-------
zero-based in... | [
"def",
"_rindex",
"(",
"sequence",
":",
"Sequence",
"[",
"T",
"]",
",",
"obj",
":",
"T",
")",
"->",
"int",
":",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"sequence",
")",
"-",
"1",
",",
"-",
"1",
",",
"-",
"1",
")",
":",
"if",
"sequence",
... | Return zero-based index in the sequence of the last item whose value is equal to obj. Raises a
ValueError if there is no such item.
Parameters
----------
sequence : ``Sequence[T]``
obj : ``T``
Returns
-------
zero-based index associated to the position of the last item equal to obj | [
"Return",
"zero",
"-",
"based",
"index",
"in",
"the",
"sequence",
"of",
"the",
"last",
"item",
"whose",
"value",
"is",
"equal",
"to",
"obj",
".",
"Raises",
"a",
"ValueError",
"if",
"there",
"is",
"no",
"such",
"item",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/nn/util.py#L749-L767 | train |
allenai/allennlp | allennlp/nn/util.py | combine_tensors_and_multiply | def combine_tensors_and_multiply(combination: str,
tensors: List[torch.Tensor],
weights: torch.nn.Parameter) -> torch.Tensor:
"""
Like :func:`combine_tensors`, but does a weighted (linear) multiplication while combining.
This is a separate fu... | python | def combine_tensors_and_multiply(combination: str,
tensors: List[torch.Tensor],
weights: torch.nn.Parameter) -> torch.Tensor:
"""
Like :func:`combine_tensors`, but does a weighted (linear) multiplication while combining.
This is a separate fu... | [
"def",
"combine_tensors_and_multiply",
"(",
"combination",
":",
"str",
",",
"tensors",
":",
"List",
"[",
"torch",
".",
"Tensor",
"]",
",",
"weights",
":",
"torch",
".",
"nn",
".",
"Parameter",
")",
"->",
"torch",
".",
"Tensor",
":",
"if",
"len",
"(",
"... | Like :func:`combine_tensors`, but does a weighted (linear) multiplication while combining.
This is a separate function from ``combine_tensors`` because we try to avoid instantiating
large intermediate tensors during the combination, which is possible because we know that we're
going to be multiplying by a w... | [
"Like",
":",
"func",
":",
"combine_tensors",
"but",
"does",
"a",
"weighted",
"(",
"linear",
")",
"multiplication",
"while",
"combining",
".",
"This",
"is",
"a",
"separate",
"function",
"from",
"combine_tensors",
"because",
"we",
"try",
"to",
"avoid",
"instanti... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/nn/util.py#L792-L829 | train |
allenai/allennlp | allennlp/nn/util.py | get_combined_dim | def get_combined_dim(combination: str, tensor_dims: List[int]) -> int:
"""
For use with :func:`combine_tensors`. This function computes the resultant dimension when
calling ``combine_tensors(combination, tensors)``, when the tensor dimension is known. This is
necessary for knowing the sizes of weight ... | python | def get_combined_dim(combination: str, tensor_dims: List[int]) -> int:
"""
For use with :func:`combine_tensors`. This function computes the resultant dimension when
calling ``combine_tensors(combination, tensors)``, when the tensor dimension is known. This is
necessary for knowing the sizes of weight ... | [
"def",
"get_combined_dim",
"(",
"combination",
":",
"str",
",",
"tensor_dims",
":",
"List",
"[",
"int",
"]",
")",
"->",
"int",
":",
"if",
"len",
"(",
"tensor_dims",
")",
">",
"9",
":",
"raise",
"ConfigurationError",
"(",
"\"Double-digit tensor lists not curren... | For use with :func:`combine_tensors`. This function computes the resultant dimension when
calling ``combine_tensors(combination, tensors)``, when the tensor dimension is known. This is
necessary for knowing the sizes of weight matrices when building models that use
``combine_tensors``.
Parameters
... | [
"For",
"use",
"with",
":",
"func",
":",
"combine_tensors",
".",
"This",
"function",
"computes",
"the",
"resultant",
"dimension",
"when",
"calling",
"combine_tensors",
"(",
"combination",
"tensors",
")",
"when",
"the",
"tensor",
"dimension",
"is",
"known",
".",
... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/nn/util.py#L882-L901 | train |
allenai/allennlp | allennlp/nn/util.py | logsumexp | def logsumexp(tensor: torch.Tensor,
dim: int = -1,
keepdim: bool = False) -> torch.Tensor:
"""
A numerically stable computation of logsumexp. This is mathematically equivalent to
`tensor.exp().sum(dim, keep=keepdim).log()`. This function is typically used for summing log
pro... | python | def logsumexp(tensor: torch.Tensor,
dim: int = -1,
keepdim: bool = False) -> torch.Tensor:
"""
A numerically stable computation of logsumexp. This is mathematically equivalent to
`tensor.exp().sum(dim, keep=keepdim).log()`. This function is typically used for summing log
pro... | [
"def",
"logsumexp",
"(",
"tensor",
":",
"torch",
".",
"Tensor",
",",
"dim",
":",
"int",
"=",
"-",
"1",
",",
"keepdim",
":",
"bool",
"=",
"False",
")",
"->",
"torch",
".",
"Tensor",
":",
"max_score",
",",
"_",
"=",
"tensor",
".",
"max",
"(",
"dim"... | A numerically stable computation of logsumexp. This is mathematically equivalent to
`tensor.exp().sum(dim, keep=keepdim).log()`. This function is typically used for summing log
probabilities.
Parameters
----------
tensor : torch.FloatTensor, required.
A tensor of arbitrary size.
dim : ... | [
"A",
"numerically",
"stable",
"computation",
"of",
"logsumexp",
".",
"This",
"is",
"mathematically",
"equivalent",
"to",
"tensor",
".",
"exp",
"()",
".",
"sum",
"(",
"dim",
"keep",
"=",
"keepdim",
")",
".",
"log",
"()",
".",
"This",
"function",
"is",
"ty... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/nn/util.py#L919-L941 | train |
allenai/allennlp | allennlp/nn/util.py | flatten_and_batch_shift_indices | def flatten_and_batch_shift_indices(indices: torch.Tensor,
sequence_length: int) -> torch.Tensor:
"""
This is a subroutine for :func:`~batched_index_select`. The given ``indices`` of size
``(batch_size, d_1, ..., d_n)`` indexes into dimension 2 of a target tensor, which h... | python | def flatten_and_batch_shift_indices(indices: torch.Tensor,
sequence_length: int) -> torch.Tensor:
"""
This is a subroutine for :func:`~batched_index_select`. The given ``indices`` of size
``(batch_size, d_1, ..., d_n)`` indexes into dimension 2 of a target tensor, which h... | [
"def",
"flatten_and_batch_shift_indices",
"(",
"indices",
":",
"torch",
".",
"Tensor",
",",
"sequence_length",
":",
"int",
")",
"->",
"torch",
".",
"Tensor",
":",
"# Shape: (batch_size)",
"offsets",
"=",
"get_range_vector",
"(",
"indices",
".",
"size",
"(",
"0",... | This is a subroutine for :func:`~batched_index_select`. The given ``indices`` of size
``(batch_size, d_1, ..., d_n)`` indexes into dimension 2 of a target tensor, which has size
``(batch_size, sequence_length, embedding_size)``. This function returns a vector that
correctly indexes into the flattened target... | [
"This",
"is",
"a",
"subroutine",
"for",
":",
"func",
":",
"~batched_index_select",
".",
"The",
"given",
"indices",
"of",
"size",
"(",
"batch_size",
"d_1",
"...",
"d_n",
")",
"indexes",
"into",
"dimension",
"2",
"of",
"a",
"target",
"tensor",
"which",
"has"... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/nn/util.py#L954-L995 | train |
allenai/allennlp | allennlp/nn/util.py | batched_index_select | def batched_index_select(target: torch.Tensor,
indices: torch.LongTensor,
flattened_indices: Optional[torch.LongTensor] = None) -> torch.Tensor:
"""
The given ``indices`` of size ``(batch_size, d_1, ..., d_n)`` indexes into the sequence
dimension (dimension ... | python | def batched_index_select(target: torch.Tensor,
indices: torch.LongTensor,
flattened_indices: Optional[torch.LongTensor] = None) -> torch.Tensor:
"""
The given ``indices`` of size ``(batch_size, d_1, ..., d_n)`` indexes into the sequence
dimension (dimension ... | [
"def",
"batched_index_select",
"(",
"target",
":",
"torch",
".",
"Tensor",
",",
"indices",
":",
"torch",
".",
"LongTensor",
",",
"flattened_indices",
":",
"Optional",
"[",
"torch",
".",
"LongTensor",
"]",
"=",
"None",
")",
"->",
"torch",
".",
"Tensor",
":"... | The given ``indices`` of size ``(batch_size, d_1, ..., d_n)`` indexes into the sequence
dimension (dimension 2) of the target, which has size ``(batch_size, sequence_length,
embedding_size)``.
This function returns selected values in the target with respect to the provided indices, which
have size ``(b... | [
"The",
"given",
"indices",
"of",
"size",
"(",
"batch_size",
"d_1",
"...",
"d_n",
")",
"indexes",
"into",
"the",
"sequence",
"dimension",
"(",
"dimension",
"2",
")",
"of",
"the",
"target",
"which",
"has",
"size",
"(",
"batch_size",
"sequence_length",
"embeddi... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/nn/util.py#L998-L1049 | train |
allenai/allennlp | allennlp/nn/util.py | flattened_index_select | def flattened_index_select(target: torch.Tensor,
indices: torch.LongTensor) -> torch.Tensor:
"""
The given ``indices`` of size ``(set_size, subset_size)`` specifies subsets of the ``target``
that each of the set_size rows should select. The `target` has size
``(batch_size, seq... | python | def flattened_index_select(target: torch.Tensor,
indices: torch.LongTensor) -> torch.Tensor:
"""
The given ``indices`` of size ``(set_size, subset_size)`` specifies subsets of the ``target``
that each of the set_size rows should select. The `target` has size
``(batch_size, seq... | [
"def",
"flattened_index_select",
"(",
"target",
":",
"torch",
".",
"Tensor",
",",
"indices",
":",
"torch",
".",
"LongTensor",
")",
"->",
"torch",
".",
"Tensor",
":",
"if",
"indices",
".",
"dim",
"(",
")",
"!=",
"2",
":",
"raise",
"ConfigurationError",
"(... | The given ``indices`` of size ``(set_size, subset_size)`` specifies subsets of the ``target``
that each of the set_size rows should select. The `target` has size
``(batch_size, sequence_length, embedding_size)``, and the resulting selected tensor has size
``(batch_size, set_size, subset_size, embedding_size... | [
"The",
"given",
"indices",
"of",
"size",
"(",
"set_size",
"subset_size",
")",
"specifies",
"subsets",
"of",
"the",
"target",
"that",
"each",
"of",
"the",
"set_size",
"rows",
"should",
"select",
".",
"The",
"target",
"has",
"size",
"(",
"batch_size",
"sequenc... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/nn/util.py#L1052-L1081 | train |
allenai/allennlp | allennlp/nn/util.py | get_range_vector | def get_range_vector(size: int, device: int) -> torch.Tensor:
"""
Returns a range vector with the desired size, starting at 0. The CUDA implementation
is meant to avoid copy data from CPU to GPU.
"""
if device > -1:
return torch.cuda.LongTensor(size, device=device).fill_(1).cumsum(0) - 1
... | python | def get_range_vector(size: int, device: int) -> torch.Tensor:
"""
Returns a range vector with the desired size, starting at 0. The CUDA implementation
is meant to avoid copy data from CPU to GPU.
"""
if device > -1:
return torch.cuda.LongTensor(size, device=device).fill_(1).cumsum(0) - 1
... | [
"def",
"get_range_vector",
"(",
"size",
":",
"int",
",",
"device",
":",
"int",
")",
"->",
"torch",
".",
"Tensor",
":",
"if",
"device",
">",
"-",
"1",
":",
"return",
"torch",
".",
"cuda",
".",
"LongTensor",
"(",
"size",
",",
"device",
"=",
"device",
... | Returns a range vector with the desired size, starting at 0. The CUDA implementation
is meant to avoid copy data from CPU to GPU. | [
"Returns",
"a",
"range",
"vector",
"with",
"the",
"desired",
"size",
"starting",
"at",
"0",
".",
"The",
"CUDA",
"implementation",
"is",
"meant",
"to",
"avoid",
"copy",
"data",
"from",
"CPU",
"to",
"GPU",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/nn/util.py#L1084-L1092 | train |
allenai/allennlp | allennlp/nn/util.py | bucket_values | def bucket_values(distances: torch.Tensor,
num_identity_buckets: int = 4,
num_total_buckets: int = 10) -> torch.Tensor:
"""
Places the given values (designed for distances) into ``num_total_buckets``semi-logscale
buckets, with ``num_identity_buckets`` of these capturing s... | python | def bucket_values(distances: torch.Tensor,
num_identity_buckets: int = 4,
num_total_buckets: int = 10) -> torch.Tensor:
"""
Places the given values (designed for distances) into ``num_total_buckets``semi-logscale
buckets, with ``num_identity_buckets`` of these capturing s... | [
"def",
"bucket_values",
"(",
"distances",
":",
"torch",
".",
"Tensor",
",",
"num_identity_buckets",
":",
"int",
"=",
"4",
",",
"num_total_buckets",
":",
"int",
"=",
"10",
")",
"->",
"torch",
".",
"Tensor",
":",
"# Chunk the values into semi-logscale buckets using ... | Places the given values (designed for distances) into ``num_total_buckets``semi-logscale
buckets, with ``num_identity_buckets`` of these capturing single values.
The default settings will bucket values into the following buckets:
[0, 1, 2, 3, 4, 5-7, 8-15, 16-31, 32-63, 64+].
Parameters
----------... | [
"Places",
"the",
"given",
"values",
"(",
"designed",
"for",
"distances",
")",
"into",
"num_total_buckets",
"semi",
"-",
"logscale",
"buckets",
"with",
"num_identity_buckets",
"of",
"these",
"capturing",
"single",
"values",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/nn/util.py#L1095-L1132 | train |
allenai/allennlp | allennlp/nn/util.py | add_sentence_boundary_token_ids | def add_sentence_boundary_token_ids(tensor: torch.Tensor,
mask: torch.Tensor,
sentence_begin_token: Any,
sentence_end_token: Any) -> Tuple[torch.Tensor, torch.Tensor]:
"""
Add begin/end of sentence tokens... | python | def add_sentence_boundary_token_ids(tensor: torch.Tensor,
mask: torch.Tensor,
sentence_begin_token: Any,
sentence_end_token: Any) -> Tuple[torch.Tensor, torch.Tensor]:
"""
Add begin/end of sentence tokens... | [
"def",
"add_sentence_boundary_token_ids",
"(",
"tensor",
":",
"torch",
".",
"Tensor",
",",
"mask",
":",
"torch",
".",
"Tensor",
",",
"sentence_begin_token",
":",
"Any",
",",
"sentence_end_token",
":",
"Any",
")",
"->",
"Tuple",
"[",
"torch",
".",
"Tensor",
"... | Add begin/end of sentence tokens to the batch of sentences.
Given a batch of sentences with size ``(batch_size, timesteps)`` or
``(batch_size, timesteps, dim)`` this returns a tensor of shape
``(batch_size, timesteps + 2)`` or ``(batch_size, timesteps + 2, dim)`` respectively.
Returns both the new tens... | [
"Add",
"begin",
"/",
"end",
"of",
"sentence",
"tokens",
"to",
"the",
"batch",
"of",
"sentences",
".",
"Given",
"a",
"batch",
"of",
"sentences",
"with",
"size",
"(",
"batch_size",
"timesteps",
")",
"or",
"(",
"batch_size",
"timesteps",
"dim",
")",
"this",
... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/nn/util.py#L1135-L1189 | train |
allenai/allennlp | allennlp/nn/util.py | remove_sentence_boundaries | def remove_sentence_boundaries(tensor: torch.Tensor,
mask: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
"""
Remove begin/end of sentence embeddings from the batch of sentences.
Given a batch of sentences with size ``(batch_size, timesteps, dim)``
this returns a tens... | python | def remove_sentence_boundaries(tensor: torch.Tensor,
mask: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
"""
Remove begin/end of sentence embeddings from the batch of sentences.
Given a batch of sentences with size ``(batch_size, timesteps, dim)``
this returns a tens... | [
"def",
"remove_sentence_boundaries",
"(",
"tensor",
":",
"torch",
".",
"Tensor",
",",
"mask",
":",
"torch",
".",
"Tensor",
")",
"->",
"Tuple",
"[",
"torch",
".",
"Tensor",
",",
"torch",
".",
"Tensor",
"]",
":",
"# TODO: matthewp, profile this transfer",
"seque... | Remove begin/end of sentence embeddings from the batch of sentences.
Given a batch of sentences with size ``(batch_size, timesteps, dim)``
this returns a tensor of shape ``(batch_size, timesteps - 2, dim)`` after removing
the beginning and end sentence markers. The sentences are assumed to be padded on the... | [
"Remove",
"begin",
"/",
"end",
"of",
"sentence",
"embeddings",
"from",
"the",
"batch",
"of",
"sentences",
".",
"Given",
"a",
"batch",
"of",
"sentences",
"with",
"size",
"(",
"batch_size",
"timesteps",
"dim",
")",
"this",
"returns",
"a",
"tensor",
"of",
"sh... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/nn/util.py#L1192-L1232 | train |
allenai/allennlp | allennlp/nn/util.py | add_positional_features | def add_positional_features(tensor: torch.Tensor,
min_timescale: float = 1.0,
max_timescale: float = 1.0e4):
# pylint: disable=line-too-long
"""
Implements the frequency-based positional encoding described
in `Attention is all you Need
<https:/... | python | def add_positional_features(tensor: torch.Tensor,
min_timescale: float = 1.0,
max_timescale: float = 1.0e4):
# pylint: disable=line-too-long
"""
Implements the frequency-based positional encoding described
in `Attention is all you Need
<https:/... | [
"def",
"add_positional_features",
"(",
"tensor",
":",
"torch",
".",
"Tensor",
",",
"min_timescale",
":",
"float",
"=",
"1.0",
",",
"max_timescale",
":",
"float",
"=",
"1.0e4",
")",
":",
"# pylint: disable=line-too-long",
"_",
",",
"timesteps",
",",
"hidden_dim",... | Implements the frequency-based positional encoding described
in `Attention is all you Need
<https://www.semanticscholar.org/paper/Attention-Is-All-You-Need-Vaswani-Shazeer/0737da0767d77606169cbf4187b83e1ab62f6077>`_ .
Adds sinusoids of different frequencies to a ``Tensor``. A sinusoid of a
different fr... | [
"Implements",
"the",
"frequency",
"-",
"based",
"positional",
"encoding",
"described",
"in",
"Attention",
"is",
"all",
"you",
"Need",
"<https",
":",
"//",
"www",
".",
"semanticscholar",
".",
"org",
"/",
"paper",
"/",
"Attention",
"-",
"Is",
"-",
"All",
"-"... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/nn/util.py#L1235-L1286 | train |
allenai/allennlp | allennlp/nn/util.py | clone | def clone(module: torch.nn.Module, num_copies: int) -> torch.nn.ModuleList:
"""Produce N identical layers."""
return torch.nn.ModuleList([copy.deepcopy(module) for _ in range(num_copies)]) | python | def clone(module: torch.nn.Module, num_copies: int) -> torch.nn.ModuleList:
"""Produce N identical layers."""
return torch.nn.ModuleList([copy.deepcopy(module) for _ in range(num_copies)]) | [
"def",
"clone",
"(",
"module",
":",
"torch",
".",
"nn",
".",
"Module",
",",
"num_copies",
":",
"int",
")",
"->",
"torch",
".",
"nn",
".",
"ModuleList",
":",
"return",
"torch",
".",
"nn",
".",
"ModuleList",
"(",
"[",
"copy",
".",
"deepcopy",
"(",
"m... | Produce N identical layers. | [
"Produce",
"N",
"identical",
"layers",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/nn/util.py#L1289-L1291 | train |
allenai/allennlp | allennlp/nn/util.py | combine_initial_dims | def combine_initial_dims(tensor: torch.Tensor) -> torch.Tensor:
"""
Given a (possibly higher order) tensor of ids with shape
(d1, ..., dn, sequence_length)
Return a view that's (d1 * ... * dn, sequence_length).
If original tensor is 1-d or 2-d, return it as is.
"""
if tensor.dim() <= 2:
... | python | def combine_initial_dims(tensor: torch.Tensor) -> torch.Tensor:
"""
Given a (possibly higher order) tensor of ids with shape
(d1, ..., dn, sequence_length)
Return a view that's (d1 * ... * dn, sequence_length).
If original tensor is 1-d or 2-d, return it as is.
"""
if tensor.dim() <= 2:
... | [
"def",
"combine_initial_dims",
"(",
"tensor",
":",
"torch",
".",
"Tensor",
")",
"->",
"torch",
".",
"Tensor",
":",
"if",
"tensor",
".",
"dim",
"(",
")",
"<=",
"2",
":",
"return",
"tensor",
"else",
":",
"return",
"tensor",
".",
"view",
"(",
"-",
"1",
... | Given a (possibly higher order) tensor of ids with shape
(d1, ..., dn, sequence_length)
Return a view that's (d1 * ... * dn, sequence_length).
If original tensor is 1-d or 2-d, return it as is. | [
"Given",
"a",
"(",
"possibly",
"higher",
"order",
")",
"tensor",
"of",
"ids",
"with",
"shape",
"(",
"d1",
"...",
"dn",
"sequence_length",
")",
"Return",
"a",
"view",
"that",
"s",
"(",
"d1",
"*",
"...",
"*",
"dn",
"sequence_length",
")",
".",
"If",
"o... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/nn/util.py#L1294-L1304 | train |
allenai/allennlp | allennlp/nn/util.py | uncombine_initial_dims | def uncombine_initial_dims(tensor: torch.Tensor, original_size: torch.Size) -> torch.Tensor:
"""
Given a tensor of embeddings with shape
(d1 * ... * dn, sequence_length, embedding_dim)
and the original shape
(d1, ..., dn, sequence_length),
return the reshaped tensor of embeddings with shape
... | python | def uncombine_initial_dims(tensor: torch.Tensor, original_size: torch.Size) -> torch.Tensor:
"""
Given a tensor of embeddings with shape
(d1 * ... * dn, sequence_length, embedding_dim)
and the original shape
(d1, ..., dn, sequence_length),
return the reshaped tensor of embeddings with shape
... | [
"def",
"uncombine_initial_dims",
"(",
"tensor",
":",
"torch",
".",
"Tensor",
",",
"original_size",
":",
"torch",
".",
"Size",
")",
"->",
"torch",
".",
"Tensor",
":",
"if",
"len",
"(",
"original_size",
")",
"<=",
"2",
":",
"return",
"tensor",
"else",
":",... | Given a tensor of embeddings with shape
(d1 * ... * dn, sequence_length, embedding_dim)
and the original shape
(d1, ..., dn, sequence_length),
return the reshaped tensor of embeddings with shape
(d1, ..., dn, sequence_length, embedding_dim).
If original size is 1-d or 2-d, return it as is. | [
"Given",
"a",
"tensor",
"of",
"embeddings",
"with",
"shape",
"(",
"d1",
"*",
"...",
"*",
"dn",
"sequence_length",
"embedding_dim",
")",
"and",
"the",
"original",
"shape",
"(",
"d1",
"...",
"dn",
"sequence_length",
")",
"return",
"the",
"reshaped",
"tensor",
... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/nn/util.py#L1307-L1321 | train |
allenai/allennlp | allennlp/semparse/contexts/table_question_context.py | TableQuestionContext._string_in_table | def _string_in_table(self, candidate: str) -> List[str]:
"""
Checks if the string occurs in the table, and if it does, returns the names of the columns
under which it occurs. If it does not, returns an empty list.
"""
candidate_column_names: List[str] = []
# First check i... | python | def _string_in_table(self, candidate: str) -> List[str]:
"""
Checks if the string occurs in the table, and if it does, returns the names of the columns
under which it occurs. If it does not, returns an empty list.
"""
candidate_column_names: List[str] = []
# First check i... | [
"def",
"_string_in_table",
"(",
"self",
",",
"candidate",
":",
"str",
")",
"->",
"List",
"[",
"str",
"]",
":",
"candidate_column_names",
":",
"List",
"[",
"str",
"]",
"=",
"[",
"]",
"# First check if the entire candidate occurs as a cell.",
"if",
"candidate",
"i... | Checks if the string occurs in the table, and if it does, returns the names of the columns
under which it occurs. If it does not, returns an empty list. | [
"Checks",
"if",
"the",
"string",
"occurs",
"in",
"the",
"table",
"and",
"if",
"it",
"does",
"returns",
"the",
"names",
"of",
"the",
"columns",
"under",
"which",
"it",
"occurs",
".",
"If",
"it",
"does",
"not",
"returns",
"an",
"empty",
"list",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/contexts/table_question_context.py#L342-L357 | train |
allenai/allennlp | allennlp/semparse/contexts/table_question_context.py | TableQuestionContext.normalize_string | def normalize_string(string: str) -> str:
"""
These are the transformation rules used to normalize cell in column names in Sempre. See
``edu.stanford.nlp.sempre.tables.StringNormalizationUtils.characterNormalize`` and
``edu.stanford.nlp.sempre.tables.TableTypeSystem.canonicalizeName``. ... | python | def normalize_string(string: str) -> str:
"""
These are the transformation rules used to normalize cell in column names in Sempre. See
``edu.stanford.nlp.sempre.tables.StringNormalizationUtils.characterNormalize`` and
``edu.stanford.nlp.sempre.tables.TableTypeSystem.canonicalizeName``. ... | [
"def",
"normalize_string",
"(",
"string",
":",
"str",
")",
"->",
"str",
":",
"# Normalization rules from Sempre",
"# \\u201A -> ,",
"string",
"=",
"re",
".",
"sub",
"(",
"\"‚\", ",
"\"",
"\", ",
"s",
"ring)",
"",
"string",
"=",
"re",
".",
"sub",
"(",
"\"„\... | These are the transformation rules used to normalize cell in column names in Sempre. See
``edu.stanford.nlp.sempre.tables.StringNormalizationUtils.characterNormalize`` and
``edu.stanford.nlp.sempre.tables.TableTypeSystem.canonicalizeName``. We reproduce those
rules here to normalize and canoni... | [
"These",
"are",
"the",
"transformation",
"rules",
"used",
"to",
"normalize",
"cell",
"in",
"column",
"names",
"in",
"Sempre",
".",
"See",
"edu",
".",
"stanford",
".",
"nlp",
".",
"sempre",
".",
"tables",
".",
"StringNormalizationUtils",
".",
"characterNormaliz... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/contexts/table_question_context.py#L400-L437 | train |
allenai/allennlp | allennlp/semparse/util.py | lisp_to_nested_expression | def lisp_to_nested_expression(lisp_string: str) -> List:
"""
Takes a logical form as a lisp string and returns a nested list representation of the lisp.
For example, "(count (division first))" would get mapped to ['count', ['division', 'first']].
"""
stack: List = []
current_expression: List = [... | python | def lisp_to_nested_expression(lisp_string: str) -> List:
"""
Takes a logical form as a lisp string and returns a nested list representation of the lisp.
For example, "(count (division first))" would get mapped to ['count', ['division', 'first']].
"""
stack: List = []
current_expression: List = [... | [
"def",
"lisp_to_nested_expression",
"(",
"lisp_string",
":",
"str",
")",
"->",
"List",
":",
"stack",
":",
"List",
"=",
"[",
"]",
"current_expression",
":",
"List",
"=",
"[",
"]",
"tokens",
"=",
"lisp_string",
".",
"split",
"(",
")",
"for",
"token",
"in",... | Takes a logical form as a lisp string and returns a nested list representation of the lisp.
For example, "(count (division first))" would get mapped to ['count', ['division', 'first']]. | [
"Takes",
"a",
"logical",
"form",
"as",
"a",
"lisp",
"string",
"and",
"returns",
"a",
"nested",
"list",
"representation",
"of",
"the",
"lisp",
".",
"For",
"example",
"(",
"count",
"(",
"division",
"first",
"))",
"would",
"get",
"mapped",
"to",
"[",
"count... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/util.py#L4-L23 | train |
allenai/allennlp | allennlp/commands/elmo.py | ElmoEmbedder.batch_to_embeddings | def batch_to_embeddings(self, batch: List[List[str]]) -> Tuple[torch.Tensor, torch.Tensor]:
"""
Parameters
----------
batch : ``List[List[str]]``, required
A list of tokenized sentences.
Returns
-------
A tuple of tensors, the first representing a... | python | def batch_to_embeddings(self, batch: List[List[str]]) -> Tuple[torch.Tensor, torch.Tensor]:
"""
Parameters
----------
batch : ``List[List[str]]``, required
A list of tokenized sentences.
Returns
-------
A tuple of tensors, the first representing a... | [
"def",
"batch_to_embeddings",
"(",
"self",
",",
"batch",
":",
"List",
"[",
"List",
"[",
"str",
"]",
"]",
")",
"->",
"Tuple",
"[",
"torch",
".",
"Tensor",
",",
"torch",
".",
"Tensor",
"]",
":",
"character_ids",
"=",
"batch_to_ids",
"(",
"batch",
")",
... | Parameters
----------
batch : ``List[List[str]]``, required
A list of tokenized sentences.
Returns
-------
A tuple of tensors, the first representing activations (batch_size, 3, num_timesteps, 1024) and
the second a mask (batch_size, num_timesteps). | [
"Parameters",
"----------",
"batch",
":",
"List",
"[",
"List",
"[",
"str",
"]]",
"required",
"A",
"list",
"of",
"tokenized",
"sentences",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/commands/elmo.py#L171-L201 | train |
allenai/allennlp | allennlp/commands/elmo.py | ElmoEmbedder.embed_sentence | def embed_sentence(self, sentence: List[str]) -> numpy.ndarray:
"""
Computes the ELMo embeddings for a single tokenized sentence.
Please note that ELMo has internal state and will give different results for the same input.
See the comment under the class definition.
Parameters
... | python | def embed_sentence(self, sentence: List[str]) -> numpy.ndarray:
"""
Computes the ELMo embeddings for a single tokenized sentence.
Please note that ELMo has internal state and will give different results for the same input.
See the comment under the class definition.
Parameters
... | [
"def",
"embed_sentence",
"(",
"self",
",",
"sentence",
":",
"List",
"[",
"str",
"]",
")",
"->",
"numpy",
".",
"ndarray",
":",
"return",
"self",
".",
"embed_batch",
"(",
"[",
"sentence",
"]",
")",
"[",
"0",
"]"
] | Computes the ELMo embeddings for a single tokenized sentence.
Please note that ELMo has internal state and will give different results for the same input.
See the comment under the class definition.
Parameters
----------
sentence : ``List[str]``, required
A tokenize... | [
"Computes",
"the",
"ELMo",
"embeddings",
"for",
"a",
"single",
"tokenized",
"sentence",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/commands/elmo.py#L203-L220 | train |
allenai/allennlp | allennlp/commands/elmo.py | ElmoEmbedder.embed_batch | def embed_batch(self, batch: List[List[str]]) -> List[numpy.ndarray]:
"""
Computes the ELMo embeddings for a batch of tokenized sentences.
Please note that ELMo has internal state and will give different results for the same input.
See the comment under the class definition.
Pa... | python | def embed_batch(self, batch: List[List[str]]) -> List[numpy.ndarray]:
"""
Computes the ELMo embeddings for a batch of tokenized sentences.
Please note that ELMo has internal state and will give different results for the same input.
See the comment under the class definition.
Pa... | [
"def",
"embed_batch",
"(",
"self",
",",
"batch",
":",
"List",
"[",
"List",
"[",
"str",
"]",
"]",
")",
"->",
"List",
"[",
"numpy",
".",
"ndarray",
"]",
":",
"elmo_embeddings",
"=",
"[",
"]",
"# Batches with only an empty sentence will throw an exception inside Al... | Computes the ELMo embeddings for a batch of tokenized sentences.
Please note that ELMo has internal state and will give different results for the same input.
See the comment under the class definition.
Parameters
----------
batch : ``List[List[str]]``, required
A li... | [
"Computes",
"the",
"ELMo",
"embeddings",
"for",
"a",
"batch",
"of",
"tokenized",
"sentences",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/commands/elmo.py#L222-L254 | train |
allenai/allennlp | allennlp/commands/elmo.py | ElmoEmbedder.embed_sentences | def embed_sentences(self,
sentences: Iterable[List[str]],
batch_size: int = DEFAULT_BATCH_SIZE) -> Iterable[numpy.ndarray]:
"""
Computes the ELMo embeddings for a iterable of sentences.
Please note that ELMo has internal state and will give differ... | python | def embed_sentences(self,
sentences: Iterable[List[str]],
batch_size: int = DEFAULT_BATCH_SIZE) -> Iterable[numpy.ndarray]:
"""
Computes the ELMo embeddings for a iterable of sentences.
Please note that ELMo has internal state and will give differ... | [
"def",
"embed_sentences",
"(",
"self",
",",
"sentences",
":",
"Iterable",
"[",
"List",
"[",
"str",
"]",
"]",
",",
"batch_size",
":",
"int",
"=",
"DEFAULT_BATCH_SIZE",
")",
"->",
"Iterable",
"[",
"numpy",
".",
"ndarray",
"]",
":",
"for",
"batch",
"in",
... | Computes the ELMo embeddings for a iterable of sentences.
Please note that ELMo has internal state and will give different results for the same input.
See the comment under the class definition.
Parameters
----------
sentences : ``Iterable[List[str]]``, required
An ... | [
"Computes",
"the",
"ELMo",
"embeddings",
"for",
"a",
"iterable",
"of",
"sentences",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/commands/elmo.py#L256-L277 | train |
allenai/allennlp | allennlp/commands/elmo.py | ElmoEmbedder.embed_file | def embed_file(self,
input_file: IO,
output_file_path: str,
output_format: str = "all",
batch_size: int = DEFAULT_BATCH_SIZE,
forget_sentences: bool = False,
use_sentence_keys: bool = False) -> None:
... | python | def embed_file(self,
input_file: IO,
output_file_path: str,
output_format: str = "all",
batch_size: int = DEFAULT_BATCH_SIZE,
forget_sentences: bool = False,
use_sentence_keys: bool = False) -> None:
... | [
"def",
"embed_file",
"(",
"self",
",",
"input_file",
":",
"IO",
",",
"output_file_path",
":",
"str",
",",
"output_format",
":",
"str",
"=",
"\"all\"",
",",
"batch_size",
":",
"int",
"=",
"DEFAULT_BATCH_SIZE",
",",
"forget_sentences",
":",
"bool",
"=",
"False... | Computes ELMo embeddings from an input_file where each line contains a sentence tokenized by whitespace.
The ELMo embeddings are written out in HDF5 format, where each sentence embedding
is saved in a dataset with the line number in the original file as the key.
Parameters
----------
... | [
"Computes",
"ELMo",
"embeddings",
"from",
"an",
"input_file",
"where",
"each",
"line",
"contains",
"a",
"sentence",
"tokenized",
"by",
"whitespace",
".",
"The",
"ELMo",
"embeddings",
"are",
"written",
"out",
"in",
"HDF5",
"format",
"where",
"each",
"sentence",
... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/commands/elmo.py#L279-L365 | train |
allenai/allennlp | allennlp/data/instance.py | Instance.add_field | def add_field(self, field_name: str, field: Field, vocab: Vocabulary = None) -> None:
"""
Add the field to the existing fields mapping.
If we have already indexed the Instance, then we also index `field`, so
it is necessary to supply the vocab.
"""
self.fields[field_name]... | python | def add_field(self, field_name: str, field: Field, vocab: Vocabulary = None) -> None:
"""
Add the field to the existing fields mapping.
If we have already indexed the Instance, then we also index `field`, so
it is necessary to supply the vocab.
"""
self.fields[field_name]... | [
"def",
"add_field",
"(",
"self",
",",
"field_name",
":",
"str",
",",
"field",
":",
"Field",
",",
"vocab",
":",
"Vocabulary",
"=",
"None",
")",
"->",
"None",
":",
"self",
".",
"fields",
"[",
"field_name",
"]",
"=",
"field",
"if",
"self",
".",
"indexed... | Add the field to the existing fields mapping.
If we have already indexed the Instance, then we also index `field`, so
it is necessary to supply the vocab. | [
"Add",
"the",
"field",
"to",
"the",
"existing",
"fields",
"mapping",
".",
"If",
"we",
"have",
"already",
"indexed",
"the",
"Instance",
"then",
"we",
"also",
"index",
"field",
"so",
"it",
"is",
"necessary",
"to",
"supply",
"the",
"vocab",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/data/instance.py#L41-L49 | train |
allenai/allennlp | allennlp/data/instance.py | Instance.count_vocab_items | def count_vocab_items(self, counter: Dict[str, Dict[str, int]]):
"""
Increments counts in the given ``counter`` for all of the vocabulary items in all of the
``Fields`` in this ``Instance``.
"""
for field in self.fields.values():
field.count_vocab_items(counter) | python | def count_vocab_items(self, counter: Dict[str, Dict[str, int]]):
"""
Increments counts in the given ``counter`` for all of the vocabulary items in all of the
``Fields`` in this ``Instance``.
"""
for field in self.fields.values():
field.count_vocab_items(counter) | [
"def",
"count_vocab_items",
"(",
"self",
",",
"counter",
":",
"Dict",
"[",
"str",
",",
"Dict",
"[",
"str",
",",
"int",
"]",
"]",
")",
":",
"for",
"field",
"in",
"self",
".",
"fields",
".",
"values",
"(",
")",
":",
"field",
".",
"count_vocab_items",
... | Increments counts in the given ``counter`` for all of the vocabulary items in all of the
``Fields`` in this ``Instance``. | [
"Increments",
"counts",
"in",
"the",
"given",
"counter",
"for",
"all",
"of",
"the",
"vocabulary",
"items",
"in",
"all",
"of",
"the",
"Fields",
"in",
"this",
"Instance",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/data/instance.py#L51-L57 | train |
allenai/allennlp | allennlp/data/instance.py | Instance.index_fields | def index_fields(self, vocab: Vocabulary) -> None:
"""
Indexes all fields in this ``Instance`` using the provided ``Vocabulary``.
This `mutates` the current object, it does not return a new ``Instance``.
A ``DataIterator`` will call this on each pass through a dataset; we use the ``index... | python | def index_fields(self, vocab: Vocabulary) -> None:
"""
Indexes all fields in this ``Instance`` using the provided ``Vocabulary``.
This `mutates` the current object, it does not return a new ``Instance``.
A ``DataIterator`` will call this on each pass through a dataset; we use the ``index... | [
"def",
"index_fields",
"(",
"self",
",",
"vocab",
":",
"Vocabulary",
")",
"->",
"None",
":",
"if",
"not",
"self",
".",
"indexed",
":",
"self",
".",
"indexed",
"=",
"True",
"for",
"field",
"in",
"self",
".",
"fields",
".",
"values",
"(",
")",
":",
"... | Indexes all fields in this ``Instance`` using the provided ``Vocabulary``.
This `mutates` the current object, it does not return a new ``Instance``.
A ``DataIterator`` will call this on each pass through a dataset; we use the ``indexed``
flag to make sure that indexing only happens once.
... | [
"Indexes",
"all",
"fields",
"in",
"this",
"Instance",
"using",
"the",
"provided",
"Vocabulary",
".",
"This",
"mutates",
"the",
"current",
"object",
"it",
"does",
"not",
"return",
"a",
"new",
"Instance",
".",
"A",
"DataIterator",
"will",
"call",
"this",
"on",... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/data/instance.py#L59-L72 | train |
allenai/allennlp | allennlp/data/instance.py | Instance.get_padding_lengths | def get_padding_lengths(self) -> Dict[str, Dict[str, int]]:
"""
Returns a dictionary of padding lengths, keyed by field name. Each ``Field`` returns a
mapping from padding keys to actual lengths, and we just key that dictionary by field name.
"""
lengths = {}
for field_n... | python | def get_padding_lengths(self) -> Dict[str, Dict[str, int]]:
"""
Returns a dictionary of padding lengths, keyed by field name. Each ``Field`` returns a
mapping from padding keys to actual lengths, and we just key that dictionary by field name.
"""
lengths = {}
for field_n... | [
"def",
"get_padding_lengths",
"(",
"self",
")",
"->",
"Dict",
"[",
"str",
",",
"Dict",
"[",
"str",
",",
"int",
"]",
"]",
":",
"lengths",
"=",
"{",
"}",
"for",
"field_name",
",",
"field",
"in",
"self",
".",
"fields",
".",
"items",
"(",
")",
":",
"... | Returns a dictionary of padding lengths, keyed by field name. Each ``Field`` returns a
mapping from padding keys to actual lengths, and we just key that dictionary by field name. | [
"Returns",
"a",
"dictionary",
"of",
"padding",
"lengths",
"keyed",
"by",
"field",
"name",
".",
"Each",
"Field",
"returns",
"a",
"mapping",
"from",
"padding",
"keys",
"to",
"actual",
"lengths",
"and",
"we",
"just",
"key",
"that",
"dictionary",
"by",
"field",
... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/data/instance.py#L74-L82 | train |
allenai/allennlp | allennlp/data/instance.py | Instance.as_tensor_dict | def as_tensor_dict(self,
padding_lengths: Dict[str, Dict[str, int]] = None) -> Dict[str, DataArray]:
"""
Pads each ``Field`` in this instance to the lengths given in ``padding_lengths`` (which is
keyed by field name, then by padding key, the same as the return value in
... | python | def as_tensor_dict(self,
padding_lengths: Dict[str, Dict[str, int]] = None) -> Dict[str, DataArray]:
"""
Pads each ``Field`` in this instance to the lengths given in ``padding_lengths`` (which is
keyed by field name, then by padding key, the same as the return value in
... | [
"def",
"as_tensor_dict",
"(",
"self",
",",
"padding_lengths",
":",
"Dict",
"[",
"str",
",",
"Dict",
"[",
"str",
",",
"int",
"]",
"]",
"=",
"None",
")",
"->",
"Dict",
"[",
"str",
",",
"DataArray",
"]",
":",
"padding_lengths",
"=",
"padding_lengths",
"or... | Pads each ``Field`` in this instance to the lengths given in ``padding_lengths`` (which is
keyed by field name, then by padding key, the same as the return value in
:func:`get_padding_lengths`), returning a list of torch tensors for each field.
If ``padding_lengths`` is omitted, we will call ``... | [
"Pads",
"each",
"Field",
"in",
"this",
"instance",
"to",
"the",
"lengths",
"given",
"in",
"padding_lengths",
"(",
"which",
"is",
"keyed",
"by",
"field",
"name",
"then",
"by",
"padding",
"key",
"the",
"same",
"as",
"the",
"return",
"value",
"in",
":",
"fu... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/data/instance.py#L84-L98 | train |
allenai/allennlp | allennlp/common/configuration.py | full_name | def full_name(cla55: Optional[type]) -> str:
"""
Return the full name (including module) of the given class.
"""
# Special case to handle None:
if cla55 is None:
return "?"
if issubclass(cla55, Initializer) and cla55 not in [Initializer, PretrainedModelInitializer]:
init_fn = cl... | python | def full_name(cla55: Optional[type]) -> str:
"""
Return the full name (including module) of the given class.
"""
# Special case to handle None:
if cla55 is None:
return "?"
if issubclass(cla55, Initializer) and cla55 not in [Initializer, PretrainedModelInitializer]:
init_fn = cl... | [
"def",
"full_name",
"(",
"cla55",
":",
"Optional",
"[",
"type",
"]",
")",
"->",
"str",
":",
"# Special case to handle None:",
"if",
"cla55",
"is",
"None",
":",
"return",
"\"?\"",
"if",
"issubclass",
"(",
"cla55",
",",
"Initializer",
")",
"and",
"cla55",
"n... | Return the full name (including module) of the given class. | [
"Return",
"the",
"full",
"name",
"(",
"including",
"module",
")",
"of",
"the",
"given",
"class",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/common/configuration.py#L34-L62 | train |
allenai/allennlp | allennlp/common/configuration.py | _get_config_type | def _get_config_type(cla55: type) -> Optional[str]:
"""
Find the name (if any) that a subclass was registered under.
We do this simply by iterating through the registry until we
find it.
"""
# Special handling for pytorch RNN types:
if cla55 == torch.nn.RNN:
return "rnn"
elif cla... | python | def _get_config_type(cla55: type) -> Optional[str]:
"""
Find the name (if any) that a subclass was registered under.
We do this simply by iterating through the registry until we
find it.
"""
# Special handling for pytorch RNN types:
if cla55 == torch.nn.RNN:
return "rnn"
elif cla... | [
"def",
"_get_config_type",
"(",
"cla55",
":",
"type",
")",
"->",
"Optional",
"[",
"str",
"]",
":",
"# Special handling for pytorch RNN types:",
"if",
"cla55",
"==",
"torch",
".",
"nn",
".",
"RNN",
":",
"return",
"\"rnn\"",
"elif",
"cla55",
"==",
"torch",
"."... | Find the name (if any) that a subclass was registered under.
We do this simply by iterating through the registry until we
find it. | [
"Find",
"the",
"name",
"(",
"if",
"any",
")",
"that",
"a",
"subclass",
"was",
"registered",
"under",
".",
"We",
"do",
"this",
"simply",
"by",
"iterating",
"through",
"the",
"registry",
"until",
"we",
"find",
"it",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/common/configuration.py#L168-L193 | train |
allenai/allennlp | allennlp/common/configuration.py | _docspec_comments | def _docspec_comments(obj) -> Dict[str, str]:
"""
Inspect the docstring and get the comments for each parameter.
"""
# Sometimes our docstring is on the class, and sometimes it's on the initializer,
# so we've got to check both.
class_docstring = getattr(obj, '__doc__', None)
init_docstring ... | python | def _docspec_comments(obj) -> Dict[str, str]:
"""
Inspect the docstring and get the comments for each parameter.
"""
# Sometimes our docstring is on the class, and sometimes it's on the initializer,
# so we've got to check both.
class_docstring = getattr(obj, '__doc__', None)
init_docstring ... | [
"def",
"_docspec_comments",
"(",
"obj",
")",
"->",
"Dict",
"[",
"str",
",",
"str",
"]",
":",
"# Sometimes our docstring is on the class, and sometimes it's on the initializer,",
"# so we've got to check both.",
"class_docstring",
"=",
"getattr",
"(",
"obj",
",",
"'__doc__'"... | Inspect the docstring and get the comments for each parameter. | [
"Inspect",
"the",
"docstring",
"and",
"get",
"the",
"comments",
"for",
"each",
"parameter",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/common/configuration.py#L195-L221 | train |
allenai/allennlp | allennlp/common/configuration.py | _auto_config | def _auto_config(cla55: Type[T]) -> Config[T]:
"""
Create the ``Config`` for a class by reflecting on its ``__init__``
method and applying a few hacks.
"""
typ3 = _get_config_type(cla55)
# Don't include self, or vocab
names_to_ignore = {"self", "vocab"}
# Hack for RNNs
if cla55 in ... | python | def _auto_config(cla55: Type[T]) -> Config[T]:
"""
Create the ``Config`` for a class by reflecting on its ``__init__``
method and applying a few hacks.
"""
typ3 = _get_config_type(cla55)
# Don't include self, or vocab
names_to_ignore = {"self", "vocab"}
# Hack for RNNs
if cla55 in ... | [
"def",
"_auto_config",
"(",
"cla55",
":",
"Type",
"[",
"T",
"]",
")",
"->",
"Config",
"[",
"T",
"]",
":",
"typ3",
"=",
"_get_config_type",
"(",
"cla55",
")",
"# Don't include self, or vocab",
"names_to_ignore",
"=",
"{",
"\"self\"",
",",
"\"vocab\"",
"}",
... | Create the ``Config`` for a class by reflecting on its ``__init__``
method and applying a few hacks. | [
"Create",
"the",
"Config",
"for",
"a",
"class",
"by",
"reflecting",
"on",
"its",
"__init__",
"method",
"and",
"applying",
"a",
"few",
"hacks",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/common/configuration.py#L223-L295 | train |
allenai/allennlp | allennlp/common/configuration.py | render_config | def render_config(config: Config, indent: str = "") -> str:
"""
Pretty-print a config in sort-of-JSON+comments.
"""
# Add four spaces to the indent.
new_indent = indent + " "
return "".join([
# opening brace + newline
"{\n",
# "type": "...", (if present)
... | python | def render_config(config: Config, indent: str = "") -> str:
"""
Pretty-print a config in sort-of-JSON+comments.
"""
# Add four spaces to the indent.
new_indent = indent + " "
return "".join([
# opening brace + newline
"{\n",
# "type": "...", (if present)
... | [
"def",
"render_config",
"(",
"config",
":",
"Config",
",",
"indent",
":",
"str",
"=",
"\"\"",
")",
"->",
"str",
":",
"# Add four spaces to the indent.",
"new_indent",
"=",
"indent",
"+",
"\" \"",
"return",
"\"\"",
".",
"join",
"(",
"[",
"# opening brace + n... | Pretty-print a config in sort-of-JSON+comments. | [
"Pretty",
"-",
"print",
"a",
"config",
"in",
"sort",
"-",
"of",
"-",
"JSON",
"+",
"comments",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/common/configuration.py#L298-L315 | train |
allenai/allennlp | allennlp/common/configuration.py | _render | def _render(item: ConfigItem, indent: str = "") -> str:
"""
Render a single config item, with the provided indent
"""
optional = item.default_value != _NO_DEFAULT
if is_configurable(item.annotation):
rendered_annotation = f"{item.annotation} (configurable)"
else:
rendered_annota... | python | def _render(item: ConfigItem, indent: str = "") -> str:
"""
Render a single config item, with the provided indent
"""
optional = item.default_value != _NO_DEFAULT
if is_configurable(item.annotation):
rendered_annotation = f"{item.annotation} (configurable)"
else:
rendered_annota... | [
"def",
"_render",
"(",
"item",
":",
"ConfigItem",
",",
"indent",
":",
"str",
"=",
"\"\"",
")",
"->",
"str",
":",
"optional",
"=",
"item",
".",
"default_value",
"!=",
"_NO_DEFAULT",
"if",
"is_configurable",
"(",
"item",
".",
"annotation",
")",
":",
"rende... | Render a single config item, with the provided indent | [
"Render",
"a",
"single",
"config",
"item",
"with",
"the",
"provided",
"indent"
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/common/configuration.py#L355-L377 | train |
allenai/allennlp | allennlp/common/configuration.py | _valid_choices | def _valid_choices(cla55: type) -> Dict[str, str]:
"""
Return a mapping {registered_name -> subclass_name}
for the registered subclasses of `cla55`.
"""
valid_choices: Dict[str, str] = {}
if cla55 not in Registrable._registry:
raise ValueError(f"{cla55} is not a known Registrable class"... | python | def _valid_choices(cla55: type) -> Dict[str, str]:
"""
Return a mapping {registered_name -> subclass_name}
for the registered subclasses of `cla55`.
"""
valid_choices: Dict[str, str] = {}
if cla55 not in Registrable._registry:
raise ValueError(f"{cla55} is not a known Registrable class"... | [
"def",
"_valid_choices",
"(",
"cla55",
":",
"type",
")",
"->",
"Dict",
"[",
"str",
",",
"str",
"]",
":",
"valid_choices",
":",
"Dict",
"[",
"str",
",",
"str",
"]",
"=",
"{",
"}",
"if",
"cla55",
"not",
"in",
"Registrable",
".",
"_registry",
":",
"ra... | Return a mapping {registered_name -> subclass_name}
for the registered subclasses of `cla55`. | [
"Return",
"a",
"mapping",
"{",
"registered_name",
"-",
">",
"subclass_name",
"}",
"for",
"the",
"registered",
"subclasses",
"of",
"cla55",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/common/configuration.py#L427-L444 | train |
allenai/allennlp | allennlp/common/file_utils.py | url_to_filename | def url_to_filename(url: str, etag: str = None) -> str:
"""
Convert `url` into a hashed filename in a repeatable way.
If `etag` is specified, append its hash to the url's, delimited
by a period.
"""
url_bytes = url.encode('utf-8')
url_hash = sha256(url_bytes)
filename = url_hash.hexdiges... | python | def url_to_filename(url: str, etag: str = None) -> str:
"""
Convert `url` into a hashed filename in a repeatable way.
If `etag` is specified, append its hash to the url's, delimited
by a period.
"""
url_bytes = url.encode('utf-8')
url_hash = sha256(url_bytes)
filename = url_hash.hexdiges... | [
"def",
"url_to_filename",
"(",
"url",
":",
"str",
",",
"etag",
":",
"str",
"=",
"None",
")",
"->",
"str",
":",
"url_bytes",
"=",
"url",
".",
"encode",
"(",
"'utf-8'",
")",
"url_hash",
"=",
"sha256",
"(",
"url_bytes",
")",
"filename",
"=",
"url_hash",
... | Convert `url` into a hashed filename in a repeatable way.
If `etag` is specified, append its hash to the url's, delimited
by a period. | [
"Convert",
"url",
"into",
"a",
"hashed",
"filename",
"in",
"a",
"repeatable",
"way",
".",
"If",
"etag",
"is",
"specified",
"append",
"its",
"hash",
"to",
"the",
"url",
"s",
"delimited",
"by",
"a",
"period",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/common/file_utils.py#L39-L54 | train |
allenai/allennlp | allennlp/common/file_utils.py | filename_to_url | def filename_to_url(filename: str, cache_dir: str = None) -> Tuple[str, str]:
"""
Return the url and etag (which may be ``None``) stored for `filename`.
Raise ``FileNotFoundError`` if `filename` or its stored metadata do not exist.
"""
if cache_dir is None:
cache_dir = CACHE_DIRECTORY
c... | python | def filename_to_url(filename: str, cache_dir: str = None) -> Tuple[str, str]:
"""
Return the url and etag (which may be ``None``) stored for `filename`.
Raise ``FileNotFoundError`` if `filename` or its stored metadata do not exist.
"""
if cache_dir is None:
cache_dir = CACHE_DIRECTORY
c... | [
"def",
"filename_to_url",
"(",
"filename",
":",
"str",
",",
"cache_dir",
":",
"str",
"=",
"None",
")",
"->",
"Tuple",
"[",
"str",
",",
"str",
"]",
":",
"if",
"cache_dir",
"is",
"None",
":",
"cache_dir",
"=",
"CACHE_DIRECTORY",
"cache_path",
"=",
"os",
... | Return the url and etag (which may be ``None``) stored for `filename`.
Raise ``FileNotFoundError`` if `filename` or its stored metadata do not exist. | [
"Return",
"the",
"url",
"and",
"etag",
"(",
"which",
"may",
"be",
"None",
")",
"stored",
"for",
"filename",
".",
"Raise",
"FileNotFoundError",
"if",
"filename",
"or",
"its",
"stored",
"metadata",
"do",
"not",
"exist",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/common/file_utils.py#L57-L78 | train |
allenai/allennlp | allennlp/common/file_utils.py | cached_path | def cached_path(url_or_filename: Union[str, Path], cache_dir: str = None) -> str:
"""
Given something that might be a URL (or might be a local path),
determine which. If it's a URL, download the file and cache it, and
return the path to the cached file. If it's already a local path,
make sure the fi... | python | def cached_path(url_or_filename: Union[str, Path], cache_dir: str = None) -> str:
"""
Given something that might be a URL (or might be a local path),
determine which. If it's a URL, download the file and cache it, and
return the path to the cached file. If it's already a local path,
make sure the fi... | [
"def",
"cached_path",
"(",
"url_or_filename",
":",
"Union",
"[",
"str",
",",
"Path",
"]",
",",
"cache_dir",
":",
"str",
"=",
"None",
")",
"->",
"str",
":",
"if",
"cache_dir",
"is",
"None",
":",
"cache_dir",
"=",
"CACHE_DIRECTORY",
"if",
"isinstance",
"("... | Given something that might be a URL (or might be a local path),
determine which. If it's a URL, download the file and cache it, and
return the path to the cached file. If it's already a local path,
make sure the file exists and then return the path. | [
"Given",
"something",
"that",
"might",
"be",
"a",
"URL",
"(",
"or",
"might",
"be",
"a",
"local",
"path",
")",
"determine",
"which",
".",
"If",
"it",
"s",
"a",
"URL",
"download",
"the",
"file",
"and",
"cache",
"it",
"and",
"return",
"the",
"path",
"to... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/common/file_utils.py#L81-L107 | train |
allenai/allennlp | allennlp/common/file_utils.py | is_url_or_existing_file | def is_url_or_existing_file(url_or_filename: Union[str, Path, None]) -> bool:
"""
Given something that might be a URL (or might be a local path),
determine check if it's url or an existing file path.
"""
if url_or_filename is None:
return False
url_or_filename = os.path.expanduser(str(ur... | python | def is_url_or_existing_file(url_or_filename: Union[str, Path, None]) -> bool:
"""
Given something that might be a URL (or might be a local path),
determine check if it's url or an existing file path.
"""
if url_or_filename is None:
return False
url_or_filename = os.path.expanduser(str(ur... | [
"def",
"is_url_or_existing_file",
"(",
"url_or_filename",
":",
"Union",
"[",
"str",
",",
"Path",
",",
"None",
"]",
")",
"->",
"bool",
":",
"if",
"url_or_filename",
"is",
"None",
":",
"return",
"False",
"url_or_filename",
"=",
"os",
".",
"path",
".",
"expan... | Given something that might be a URL (or might be a local path),
determine check if it's url or an existing file path. | [
"Given",
"something",
"that",
"might",
"be",
"a",
"URL",
"(",
"or",
"might",
"be",
"a",
"local",
"path",
")",
"determine",
"check",
"if",
"it",
"s",
"url",
"or",
"an",
"existing",
"file",
"path",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/common/file_utils.py#L109-L118 | train |
allenai/allennlp | allennlp/common/file_utils.py | split_s3_path | def split_s3_path(url: str) -> Tuple[str, str]:
"""Split a full s3 path into the bucket name and path."""
parsed = urlparse(url)
if not parsed.netloc or not parsed.path:
raise ValueError("bad s3 path {}".format(url))
bucket_name = parsed.netloc
s3_path = parsed.path
# Remove '/' at begin... | python | def split_s3_path(url: str) -> Tuple[str, str]:
"""Split a full s3 path into the bucket name and path."""
parsed = urlparse(url)
if not parsed.netloc or not parsed.path:
raise ValueError("bad s3 path {}".format(url))
bucket_name = parsed.netloc
s3_path = parsed.path
# Remove '/' at begin... | [
"def",
"split_s3_path",
"(",
"url",
":",
"str",
")",
"->",
"Tuple",
"[",
"str",
",",
"str",
"]",
":",
"parsed",
"=",
"urlparse",
"(",
"url",
")",
"if",
"not",
"parsed",
".",
"netloc",
"or",
"not",
"parsed",
".",
"path",
":",
"raise",
"ValueError",
... | Split a full s3 path into the bucket name and path. | [
"Split",
"a",
"full",
"s3",
"path",
"into",
"the",
"bucket",
"name",
"and",
"path",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/common/file_utils.py#L120-L130 | train |
allenai/allennlp | allennlp/common/file_utils.py | s3_request | def s3_request(func: Callable):
"""
Wrapper function for s3 requests in order to create more helpful error
messages.
"""
@wraps(func)
def wrapper(url: str, *args, **kwargs):
try:
return func(url, *args, **kwargs)
except ClientError as exc:
if int(exc.resp... | python | def s3_request(func: Callable):
"""
Wrapper function for s3 requests in order to create more helpful error
messages.
"""
@wraps(func)
def wrapper(url: str, *args, **kwargs):
try:
return func(url, *args, **kwargs)
except ClientError as exc:
if int(exc.resp... | [
"def",
"s3_request",
"(",
"func",
":",
"Callable",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"url",
":",
"str",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"return",
"func",
"(",
"url",
",",
"*",
"arg... | Wrapper function for s3 requests in order to create more helpful error
messages. | [
"Wrapper",
"function",
"for",
"s3",
"requests",
"in",
"order",
"to",
"create",
"more",
"helpful",
"error",
"messages",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/common/file_utils.py#L133-L149 | train |
allenai/allennlp | allennlp/common/file_utils.py | s3_etag | def s3_etag(url: str) -> Optional[str]:
"""Check ETag on S3 object."""
s3_resource = boto3.resource("s3")
bucket_name, s3_path = split_s3_path(url)
s3_object = s3_resource.Object(bucket_name, s3_path)
return s3_object.e_tag | python | def s3_etag(url: str) -> Optional[str]:
"""Check ETag on S3 object."""
s3_resource = boto3.resource("s3")
bucket_name, s3_path = split_s3_path(url)
s3_object = s3_resource.Object(bucket_name, s3_path)
return s3_object.e_tag | [
"def",
"s3_etag",
"(",
"url",
":",
"str",
")",
"->",
"Optional",
"[",
"str",
"]",
":",
"s3_resource",
"=",
"boto3",
".",
"resource",
"(",
"\"s3\"",
")",
"bucket_name",
",",
"s3_path",
"=",
"split_s3_path",
"(",
"url",
")",
"s3_object",
"=",
"s3_resource"... | Check ETag on S3 object. | [
"Check",
"ETag",
"on",
"S3",
"object",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/common/file_utils.py#L153-L158 | train |
allenai/allennlp | allennlp/common/file_utils.py | s3_get | def s3_get(url: str, temp_file: IO) -> None:
"""Pull a file directly from S3."""
s3_resource = boto3.resource("s3")
bucket_name, s3_path = split_s3_path(url)
s3_resource.Bucket(bucket_name).download_fileobj(s3_path, temp_file) | python | def s3_get(url: str, temp_file: IO) -> None:
"""Pull a file directly from S3."""
s3_resource = boto3.resource("s3")
bucket_name, s3_path = split_s3_path(url)
s3_resource.Bucket(bucket_name).download_fileobj(s3_path, temp_file) | [
"def",
"s3_get",
"(",
"url",
":",
"str",
",",
"temp_file",
":",
"IO",
")",
"->",
"None",
":",
"s3_resource",
"=",
"boto3",
".",
"resource",
"(",
"\"s3\"",
")",
"bucket_name",
",",
"s3_path",
"=",
"split_s3_path",
"(",
"url",
")",
"s3_resource",
".",
"B... | Pull a file directly from S3. | [
"Pull",
"a",
"file",
"directly",
"from",
"S3",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/common/file_utils.py#L162-L166 | train |
allenai/allennlp | allennlp/common/file_utils.py | get_from_cache | def get_from_cache(url: str, cache_dir: str = None) -> str:
"""
Given a URL, look for the corresponding dataset in the local cache.
If it's not there, download it. Then return the path to the cached file.
"""
if cache_dir is None:
cache_dir = CACHE_DIRECTORY
os.makedirs(cache_dir, exist... | python | def get_from_cache(url: str, cache_dir: str = None) -> str:
"""
Given a URL, look for the corresponding dataset in the local cache.
If it's not there, download it. Then return the path to the cached file.
"""
if cache_dir is None:
cache_dir = CACHE_DIRECTORY
os.makedirs(cache_dir, exist... | [
"def",
"get_from_cache",
"(",
"url",
":",
"str",
",",
"cache_dir",
":",
"str",
"=",
"None",
")",
"->",
"str",
":",
"if",
"cache_dir",
"is",
"None",
":",
"cache_dir",
"=",
"CACHE_DIRECTORY",
"os",
".",
"makedirs",
"(",
"cache_dir",
",",
"exist_ok",
"=",
... | Given a URL, look for the corresponding dataset in the local cache.
If it's not there, download it. Then return the path to the cached file. | [
"Given",
"a",
"URL",
"look",
"for",
"the",
"corresponding",
"dataset",
"in",
"the",
"local",
"cache",
".",
"If",
"it",
"s",
"not",
"there",
"download",
"it",
".",
"Then",
"return",
"the",
"path",
"to",
"the",
"cached",
"file",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/common/file_utils.py#L182-L236 | train |
allenai/allennlp | allennlp/common/file_utils.py | read_set_from_file | def read_set_from_file(filename: str) -> Set[str]:
"""
Extract a de-duped collection (set) of text from a file.
Expected file format is one item per line.
"""
collection = set()
with open(filename, 'r') as file_:
for line in file_:
collection.add(line.rstrip())
return col... | python | def read_set_from_file(filename: str) -> Set[str]:
"""
Extract a de-duped collection (set) of text from a file.
Expected file format is one item per line.
"""
collection = set()
with open(filename, 'r') as file_:
for line in file_:
collection.add(line.rstrip())
return col... | [
"def",
"read_set_from_file",
"(",
"filename",
":",
"str",
")",
"->",
"Set",
"[",
"str",
"]",
":",
"collection",
"=",
"set",
"(",
")",
"with",
"open",
"(",
"filename",
",",
"'r'",
")",
"as",
"file_",
":",
"for",
"line",
"in",
"file_",
":",
"collection... | Extract a de-duped collection (set) of text from a file.
Expected file format is one item per line. | [
"Extract",
"a",
"de",
"-",
"duped",
"collection",
"(",
"set",
")",
"of",
"text",
"from",
"a",
"file",
".",
"Expected",
"file",
"format",
"is",
"one",
"item",
"per",
"line",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/common/file_utils.py#L239-L248 | train |
allenai/allennlp | scripts/reformat_text2sql_data.py | main | def main(output_directory: int, data: str) -> None:
"""
Processes the text2sql data into the following directory structure:
``dataset/{query_split, question_split}/{train,dev,test}.json``
for datasets which have train, dev and test splits, or:
``dataset/{query_split, question_split}/{split_{split... | python | def main(output_directory: int, data: str) -> None:
"""
Processes the text2sql data into the following directory structure:
``dataset/{query_split, question_split}/{train,dev,test}.json``
for datasets which have train, dev and test splits, or:
``dataset/{query_split, question_split}/{split_{split... | [
"def",
"main",
"(",
"output_directory",
":",
"int",
",",
"data",
":",
"str",
")",
"->",
"None",
":",
"json_files",
"=",
"glob",
".",
"glob",
"(",
"os",
".",
"path",
".",
"join",
"(",
"data",
",",
"\"*.json\"",
")",
")",
"for",
"dataset",
"in",
"jso... | Processes the text2sql data into the following directory structure:
``dataset/{query_split, question_split}/{train,dev,test}.json``
for datasets which have train, dev and test splits, or:
``dataset/{query_split, question_split}/{split_{split_id}}.json``
for datasets which use cross validation.
... | [
"Processes",
"the",
"text2sql",
"data",
"into",
"the",
"following",
"directory",
"structure",
":"
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/scripts/reformat_text2sql_data.py#L38-L91 | train |
allenai/allennlp | allennlp/modules/residual_with_layer_dropout.py | ResidualWithLayerDropout.forward | def forward(self,
layer_input: torch.Tensor,
layer_output: torch.Tensor,
layer_index: int = None,
total_layers: int = None) -> torch.Tensor:
# pylint: disable=arguments-differ
"""
Apply dropout to this layer, for this whole mini-bat... | python | def forward(self,
layer_input: torch.Tensor,
layer_output: torch.Tensor,
layer_index: int = None,
total_layers: int = None) -> torch.Tensor:
# pylint: disable=arguments-differ
"""
Apply dropout to this layer, for this whole mini-bat... | [
"def",
"forward",
"(",
"self",
",",
"layer_input",
":",
"torch",
".",
"Tensor",
",",
"layer_output",
":",
"torch",
".",
"Tensor",
",",
"layer_index",
":",
"int",
"=",
"None",
",",
"total_layers",
":",
"int",
"=",
"None",
")",
"->",
"torch",
".",
"Tenso... | Apply dropout to this layer, for this whole mini-batch.
dropout_prob = layer_index / total_layers * undecayed_dropout_prob if layer_idx and
total_layers is specified, else it will use the undecayed_dropout_prob directly.
Parameters
----------
layer_input ``torch.FloatTensor`` re... | [
"Apply",
"dropout",
"to",
"this",
"layer",
"for",
"this",
"whole",
"mini",
"-",
"batch",
".",
"dropout_prob",
"=",
"layer_index",
"/",
"total_layers",
"*",
"undecayed_dropout_prob",
"if",
"layer_idx",
"and",
"total_layers",
"is",
"specified",
"else",
"it",
"will... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/modules/residual_with_layer_dropout.py#L21-L59 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.