id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
23,000 | allenai/allennlp | allennlp/semparse/domain_languages/wikitables_language.py | WikiTablesLanguage.first | def first(self, rows: List[Row]) -> List[Row]:
"""
Takes an expression that evaluates to a list of rows, and returns the first one in that
list.
"""
if not rows:
logger.warning("Trying to get first row from an empty list")
return []
return [rows[0]... | python | def first(self, rows: List[Row]) -> List[Row]:
"""
Takes an expression that evaluates to a list of rows, and returns the first one in that
list.
"""
if not rows:
logger.warning("Trying to get first row from an empty list")
return []
return [rows[0]... | [
"def",
"first",
"(",
"self",
",",
"rows",
":",
"List",
"[",
"Row",
"]",
")",
"->",
"List",
"[",
"Row",
"]",
":",
"if",
"not",
"rows",
":",
"logger",
".",
"warning",
"(",
"\"Trying to get first row from an empty list\"",
")",
"return",
"[",
"]",
"return",... | Takes an expression that evaluates to a list of rows, and returns the first one in that
list. | [
"Takes",
"an",
"expression",
"that",
"evaluates",
"to",
"a",
"list",
"of",
"rows",
"and",
"returns",
"the",
"first",
"one",
"in",
"that",
"list",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/domain_languages/wikitables_language.py#L410-L418 |
23,001 | allenai/allennlp | allennlp/semparse/domain_languages/wikitables_language.py | WikiTablesLanguage.last | def last(self, rows: List[Row]) -> List[Row]:
"""
Takes an expression that evaluates to a list of rows, and returns the last one in that
list.
"""
if not rows:
logger.warning("Trying to get last row from an empty list")
return []
return [rows[-1]] | python | def last(self, rows: List[Row]) -> List[Row]:
"""
Takes an expression that evaluates to a list of rows, and returns the last one in that
list.
"""
if not rows:
logger.warning("Trying to get last row from an empty list")
return []
return [rows[-1]] | [
"def",
"last",
"(",
"self",
",",
"rows",
":",
"List",
"[",
"Row",
"]",
")",
"->",
"List",
"[",
"Row",
"]",
":",
"if",
"not",
"rows",
":",
"logger",
".",
"warning",
"(",
"\"Trying to get last row from an empty list\"",
")",
"return",
"[",
"]",
"return",
... | Takes an expression that evaluates to a list of rows, and returns the last one in that
list. | [
"Takes",
"an",
"expression",
"that",
"evaluates",
"to",
"a",
"list",
"of",
"rows",
"and",
"returns",
"the",
"last",
"one",
"in",
"that",
"list",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/domain_languages/wikitables_language.py#L421-L429 |
23,002 | allenai/allennlp | allennlp/semparse/domain_languages/wikitables_language.py | WikiTablesLanguage.previous | def previous(self, rows: List[Row]) -> List[Row]:
"""
Takes an expression that evaluates to a single row, and returns the row that occurs before
the input row in the original set of rows. If the input row happens to be the top row, we
will return an empty list.
"""
if not... | python | def previous(self, rows: List[Row]) -> List[Row]:
"""
Takes an expression that evaluates to a single row, and returns the row that occurs before
the input row in the original set of rows. If the input row happens to be the top row, we
will return an empty list.
"""
if not... | [
"def",
"previous",
"(",
"self",
",",
"rows",
":",
"List",
"[",
"Row",
"]",
")",
"->",
"List",
"[",
"Row",
"]",
":",
"if",
"not",
"rows",
":",
"return",
"[",
"]",
"input_row_index",
"=",
"self",
".",
"_get_row_index",
"(",
"rows",
"[",
"0",
"]",
"... | Takes an expression that evaluates to a single row, and returns the row that occurs before
the input row in the original set of rows. If the input row happens to be the top row, we
will return an empty list. | [
"Takes",
"an",
"expression",
"that",
"evaluates",
"to",
"a",
"single",
"row",
"and",
"returns",
"the",
"row",
"that",
"occurs",
"before",
"the",
"input",
"row",
"in",
"the",
"original",
"set",
"of",
"rows",
".",
"If",
"the",
"input",
"row",
"happens",
"t... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/domain_languages/wikitables_language.py#L432-L443 |
23,003 | allenai/allennlp | allennlp/semparse/domain_languages/wikitables_language.py | WikiTablesLanguage.next | def next(self, rows: List[Row]) -> List[Row]:
"""
Takes an expression that evaluates to a single row, and returns the row that occurs after
the input row in the original set of rows. If the input row happens to be the last row, we
will return an empty list.
"""
if not row... | python | def next(self, rows: List[Row]) -> List[Row]:
"""
Takes an expression that evaluates to a single row, and returns the row that occurs after
the input row in the original set of rows. If the input row happens to be the last row, we
will return an empty list.
"""
if not row... | [
"def",
"next",
"(",
"self",
",",
"rows",
":",
"List",
"[",
"Row",
"]",
")",
"->",
"List",
"[",
"Row",
"]",
":",
"if",
"not",
"rows",
":",
"return",
"[",
"]",
"input_row_index",
"=",
"self",
".",
"_get_row_index",
"(",
"rows",
"[",
"0",
"]",
")",
... | Takes an expression that evaluates to a single row, and returns the row that occurs after
the input row in the original set of rows. If the input row happens to be the last row, we
will return an empty list. | [
"Takes",
"an",
"expression",
"that",
"evaluates",
"to",
"a",
"single",
"row",
"and",
"returns",
"the",
"row",
"that",
"occurs",
"after",
"the",
"input",
"row",
"in",
"the",
"original",
"set",
"of",
"rows",
".",
"If",
"the",
"input",
"row",
"happens",
"to... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/domain_languages/wikitables_language.py#L446-L457 |
23,004 | allenai/allennlp | allennlp/semparse/domain_languages/wikitables_language.py | WikiTablesLanguage.average | def average(self, rows: List[Row], column: NumberColumn) -> Number:
"""
Takes a list of rows and a column and returns the mean of the values under that column in
those rows.
"""
cell_values = [row.values[column.name] for row in rows]
if not cell_values:
return... | python | def average(self, rows: List[Row], column: NumberColumn) -> Number:
"""
Takes a list of rows and a column and returns the mean of the values under that column in
those rows.
"""
cell_values = [row.values[column.name] for row in rows]
if not cell_values:
return... | [
"def",
"average",
"(",
"self",
",",
"rows",
":",
"List",
"[",
"Row",
"]",
",",
"column",
":",
"NumberColumn",
")",
"->",
"Number",
":",
"cell_values",
"=",
"[",
"row",
".",
"values",
"[",
"column",
".",
"name",
"]",
"for",
"row",
"in",
"rows",
"]",... | Takes a list of rows and a column and returns the mean of the values under that column in
those rows. | [
"Takes",
"a",
"list",
"of",
"rows",
"and",
"a",
"column",
"and",
"returns",
"the",
"mean",
"of",
"the",
"values",
"under",
"that",
"column",
"in",
"those",
"rows",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/domain_languages/wikitables_language.py#L737-L745 |
23,005 | allenai/allennlp | allennlp/semparse/domain_languages/wikitables_language.py | WikiTablesLanguage.diff | def diff(self, first_row: List[Row], second_row: List[Row], column: NumberColumn) -> Number:
"""
Takes a two rows and a number column and returns the difference between the values under
that column in those two rows.
"""
if not first_row or not second_row:
return 0.0 ... | python | def diff(self, first_row: List[Row], second_row: List[Row], column: NumberColumn) -> Number:
"""
Takes a two rows and a number column and returns the difference between the values under
that column in those two rows.
"""
if not first_row or not second_row:
return 0.0 ... | [
"def",
"diff",
"(",
"self",
",",
"first_row",
":",
"List",
"[",
"Row",
"]",
",",
"second_row",
":",
"List",
"[",
"Row",
"]",
",",
"column",
":",
"NumberColumn",
")",
"->",
"Number",
":",
"if",
"not",
"first_row",
"or",
"not",
"second_row",
":",
"retu... | Takes a two rows and a number column and returns the difference between the values under
that column in those two rows. | [
"Takes",
"a",
"two",
"rows",
"and",
"a",
"number",
"column",
"and",
"returns",
"the",
"difference",
"between",
"the",
"values",
"under",
"that",
"column",
"in",
"those",
"two",
"rows",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/domain_languages/wikitables_language.py#L747-L759 |
23,006 | allenai/allennlp | allennlp/semparse/worlds/world.py | World.is_terminal | def is_terminal(self, symbol: str) -> bool:
"""
This function will be called on nodes of a logical form tree, which are either non-terminal
symbols that can be expanded or terminal symbols that must be leaf nodes. Returns ``True``
if the given symbol is a terminal symbol.
"""
... | python | def is_terminal(self, symbol: str) -> bool:
"""
This function will be called on nodes of a logical form tree, which are either non-terminal
symbols that can be expanded or terminal symbols that must be leaf nodes. Returns ``True``
if the given symbol is a terminal symbol.
"""
... | [
"def",
"is_terminal",
"(",
"self",
",",
"symbol",
":",
"str",
")",
"->",
"bool",
":",
"# We special-case 'lambda' here because it behaves weirdly in action sequences.",
"return",
"(",
"symbol",
"in",
"self",
".",
"global_name_mapping",
"or",
"symbol",
"in",
"self",
".... | This function will be called on nodes of a logical form tree, which are either non-terminal
symbols that can be expanded or terminal symbols that must be leaf nodes. Returns ``True``
if the given symbol is a terminal symbol. | [
"This",
"function",
"will",
"be",
"called",
"on",
"nodes",
"of",
"a",
"logical",
"form",
"tree",
"which",
"are",
"either",
"non",
"-",
"terminal",
"symbols",
"that",
"can",
"be",
"expanded",
"or",
"terminal",
"symbols",
"that",
"must",
"be",
"leaf",
"nodes... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/worlds/world.py#L76-L85 |
23,007 | allenai/allennlp | allennlp/semparse/worlds/world.py | World.get_multi_match_mapping | def get_multi_match_mapping(self) -> Dict[Type, List[Type]]:
"""
Returns a mapping from each `MultiMatchNamedBasicType` to all the `NamedBasicTypes` that it
matches.
"""
if self._multi_match_mapping is None:
self._multi_match_mapping = {}
basic_types = sel... | python | def get_multi_match_mapping(self) -> Dict[Type, List[Type]]:
"""
Returns a mapping from each `MultiMatchNamedBasicType` to all the `NamedBasicTypes` that it
matches.
"""
if self._multi_match_mapping is None:
self._multi_match_mapping = {}
basic_types = sel... | [
"def",
"get_multi_match_mapping",
"(",
"self",
")",
"->",
"Dict",
"[",
"Type",
",",
"List",
"[",
"Type",
"]",
"]",
":",
"if",
"self",
".",
"_multi_match_mapping",
"is",
"None",
":",
"self",
".",
"_multi_match_mapping",
"=",
"{",
"}",
"basic_types",
"=",
... | Returns a mapping from each `MultiMatchNamedBasicType` to all the `NamedBasicTypes` that it
matches. | [
"Returns",
"a",
"mapping",
"from",
"each",
"MultiMatchNamedBasicType",
"to",
"all",
"the",
"NamedBasicTypes",
"that",
"it",
"matches",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/worlds/world.py#L184-L204 |
23,008 | allenai/allennlp | allennlp/semparse/worlds/world.py | World.parse_logical_form | def parse_logical_form(self,
logical_form: str,
remove_var_function: bool = True) -> Expression:
"""
Takes a logical form as a string, maps its tokens using the mapping and returns a parsed expression.
Parameters
----------
l... | python | def parse_logical_form(self,
logical_form: str,
remove_var_function: bool = True) -> Expression:
"""
Takes a logical form as a string, maps its tokens using the mapping and returns a parsed expression.
Parameters
----------
l... | [
"def",
"parse_logical_form",
"(",
"self",
",",
"logical_form",
":",
"str",
",",
"remove_var_function",
":",
"bool",
"=",
"True",
")",
"->",
"Expression",
":",
"if",
"not",
"logical_form",
".",
"startswith",
"(",
"\"(\"",
")",
":",
"logical_form",
"=",
"f\"({... | Takes a logical form as a string, maps its tokens using the mapping and returns a parsed expression.
Parameters
----------
logical_form : ``str``
Logical form to parse
remove_var_function : ``bool`` (optional)
``var`` is a special function that some languages use... | [
"Takes",
"a",
"logical",
"form",
"as",
"a",
"string",
"maps",
"its",
"tokens",
"using",
"the",
"mapping",
"and",
"returns",
"a",
"parsed",
"expression",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/worlds/world.py#L206-L235 |
23,009 | allenai/allennlp | allennlp/semparse/worlds/world.py | World.get_logical_form | def get_logical_form(self,
action_sequence: List[str],
add_var_function: bool = True) -> str:
"""
Takes an action sequence and constructs a logical form from it. This is useful if you want
to get a logical form from a decoded sequence of actions ... | python | def get_logical_form(self,
action_sequence: List[str],
add_var_function: bool = True) -> str:
"""
Takes an action sequence and constructs a logical form from it. This is useful if you want
to get a logical form from a decoded sequence of actions ... | [
"def",
"get_logical_form",
"(",
"self",
",",
"action_sequence",
":",
"List",
"[",
"str",
"]",
",",
"add_var_function",
":",
"bool",
"=",
"True",
")",
"->",
"str",
":",
"# Basic outline: we assume that the bracketing that we get in the RHS of each action is the",
"# correc... | Takes an action sequence and constructs a logical form from it. This is useful if you want
to get a logical form from a decoded sequence of actions generated by a transition based
semantic parser.
Parameters
----------
action_sequence : ``List[str]``
The sequence of ... | [
"Takes",
"an",
"action",
"sequence",
"and",
"constructs",
"a",
"logical",
"form",
"from",
"it",
".",
"This",
"is",
"useful",
"if",
"you",
"want",
"to",
"get",
"a",
"logical",
"form",
"from",
"a",
"decoded",
"sequence",
"of",
"actions",
"generated",
"by",
... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/worlds/world.py#L245-L285 |
23,010 | allenai/allennlp | allennlp/semparse/worlds/world.py | World._process_nested_expression | def _process_nested_expression(self, nested_expression) -> str:
"""
``nested_expression`` is the result of parsing a logical form in Lisp format.
We process it recursively and return a string in the format that NLTK's ``LogicParser``
would understand.
"""
expression_is_li... | python | def _process_nested_expression(self, nested_expression) -> str:
"""
``nested_expression`` is the result of parsing a logical form in Lisp format.
We process it recursively and return a string in the format that NLTK's ``LogicParser``
would understand.
"""
expression_is_li... | [
"def",
"_process_nested_expression",
"(",
"self",
",",
"nested_expression",
")",
"->",
"str",
":",
"expression_is_list",
"=",
"isinstance",
"(",
"nested_expression",
",",
"list",
")",
"expression_size",
"=",
"len",
"(",
"nested_expression",
")",
"if",
"expression_is... | ``nested_expression`` is the result of parsing a logical form in Lisp format.
We process it recursively and return a string in the format that NLTK's ``LogicParser``
would understand. | [
"nested_expression",
"is",
"the",
"result",
"of",
"parsing",
"a",
"logical",
"form",
"in",
"Lisp",
"format",
".",
"We",
"process",
"it",
"recursively",
"and",
"return",
"a",
"string",
"in",
"the",
"format",
"that",
"NLTK",
"s",
"LogicParser",
"would",
"under... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/worlds/world.py#L382-L408 |
23,011 | allenai/allennlp | allennlp/semparse/worlds/world.py | World._add_name_mapping | def _add_name_mapping(self, name: str, translated_name: str, name_type: Type = None):
"""
Utility method to add a name and its translation to the local name mapping, and the corresponding
signature, if available to the local type signatures. This method also updates the reverse name
mapp... | python | def _add_name_mapping(self, name: str, translated_name: str, name_type: Type = None):
"""
Utility method to add a name and its translation to the local name mapping, and the corresponding
signature, if available to the local type signatures. This method also updates the reverse name
mapp... | [
"def",
"_add_name_mapping",
"(",
"self",
",",
"name",
":",
"str",
",",
"translated_name",
":",
"str",
",",
"name_type",
":",
"Type",
"=",
"None",
")",
":",
"self",
".",
"local_name_mapping",
"[",
"name",
"]",
"=",
"translated_name",
"self",
".",
"reverse_n... | Utility method to add a name and its translation to the local name mapping, and the corresponding
signature, if available to the local type signatures. This method also updates the reverse name
mapping. | [
"Utility",
"method",
"to",
"add",
"a",
"name",
"and",
"its",
"translation",
"to",
"the",
"local",
"name",
"mapping",
"and",
"the",
"corresponding",
"signature",
"if",
"available",
"to",
"the",
"local",
"type",
"signatures",
".",
"This",
"method",
"also",
"up... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/worlds/world.py#L434-L443 |
23,012 | allenai/allennlp | allennlp/semparse/executors/wikitables_sempre_executor.py | WikiTablesSempreExecutor._create_sempre_executor | def _create_sempre_executor(self) -> None:
"""
Creates a server running SEMPRE that we can send logical forms to for evaluation. This
uses inter-process communication, because SEMPRE is java code. We also need to be careful
to clean up the process when our program exits.
"""
... | python | def _create_sempre_executor(self) -> None:
"""
Creates a server running SEMPRE that we can send logical forms to for evaluation. This
uses inter-process communication, because SEMPRE is java code. We also need to be careful
to clean up the process when our program exits.
"""
... | [
"def",
"_create_sempre_executor",
"(",
"self",
")",
"->",
"None",
":",
"if",
"self",
".",
"_executor_process",
":",
"return",
"# It'd be much nicer to just use `cached_path` for these files. However, the SEMPRE jar",
"# that we're using expects to find these files in a particular loca... | Creates a server running SEMPRE that we can send logical forms to for evaluation. This
uses inter-process communication, because SEMPRE is java code. We also need to be careful
to clean up the process when our program exits. | [
"Creates",
"a",
"server",
"running",
"SEMPRE",
"that",
"we",
"can",
"send",
"logical",
"forms",
"to",
"for",
"evaluation",
".",
"This",
"uses",
"inter",
"-",
"process",
"communication",
"because",
"SEMPRE",
"is",
"java",
"code",
".",
"We",
"also",
"need",
... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/executors/wikitables_sempre_executor.py#L63-L105 |
23,013 | allenai/allennlp | allennlp/training/metrics/conll_coref_scores.py | Scorer.phi4 | def phi4(gold_clustering, predicted_clustering):
"""
Subroutine for ceafe. Computes the mention F measure between gold and
predicted mentions in a cluster.
"""
return 2 * len([mention for mention in gold_clustering if mention in predicted_clustering]) \
/ float(len... | python | def phi4(gold_clustering, predicted_clustering):
"""
Subroutine for ceafe. Computes the mention F measure between gold and
predicted mentions in a cluster.
"""
return 2 * len([mention for mention in gold_clustering if mention in predicted_clustering]) \
/ float(len... | [
"def",
"phi4",
"(",
"gold_clustering",
",",
"predicted_clustering",
")",
":",
"return",
"2",
"*",
"len",
"(",
"[",
"mention",
"for",
"mention",
"in",
"gold_clustering",
"if",
"mention",
"in",
"predicted_clustering",
"]",
")",
"/",
"float",
"(",
"len",
"(",
... | Subroutine for ceafe. Computes the mention F measure between gold and
predicted mentions in a cluster. | [
"Subroutine",
"for",
"ceafe",
".",
"Computes",
"the",
"mention",
"F",
"measure",
"between",
"gold",
"and",
"predicted",
"mentions",
"in",
"a",
"cluster",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/training/metrics/conll_coref_scores.py#L208-L214 |
23,014 | allenai/allennlp | allennlp/training/util.py | sparse_clip_norm | def sparse_clip_norm(parameters, max_norm, norm_type=2) -> float:
"""Clips gradient norm of an iterable of parameters.
The norm is computed over all gradients together, as if they were
concatenated into a single vector. Gradients are modified in-place.
Supports sparse gradients.
Parameters
---... | python | def sparse_clip_norm(parameters, max_norm, norm_type=2) -> float:
"""Clips gradient norm of an iterable of parameters.
The norm is computed over all gradients together, as if they were
concatenated into a single vector. Gradients are modified in-place.
Supports sparse gradients.
Parameters
---... | [
"def",
"sparse_clip_norm",
"(",
"parameters",
",",
"max_norm",
",",
"norm_type",
"=",
"2",
")",
"->",
"float",
":",
"# pylint: disable=invalid-name,protected-access",
"parameters",
"=",
"list",
"(",
"filter",
"(",
"lambda",
"p",
":",
"p",
".",
"grad",
"is",
"n... | Clips gradient norm of an iterable of parameters.
The norm is computed over all gradients together, as if they were
concatenated into a single vector. Gradients are modified in-place.
Supports sparse gradients.
Parameters
----------
parameters : ``(Iterable[torch.Tensor])``
An iterable... | [
"Clips",
"gradient",
"norm",
"of",
"an",
"iterable",
"of",
"parameters",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/training/util.py#L34-L78 |
23,015 | allenai/allennlp | allennlp/training/util.py | move_optimizer_to_cuda | def move_optimizer_to_cuda(optimizer):
"""
Move the optimizer state to GPU, if necessary.
After calling, any parameter specific state in the optimizer
will be located on the same device as the parameter.
"""
for param_group in optimizer.param_groups:
for param in param_group['params']:
... | python | def move_optimizer_to_cuda(optimizer):
"""
Move the optimizer state to GPU, if necessary.
After calling, any parameter specific state in the optimizer
will be located on the same device as the parameter.
"""
for param_group in optimizer.param_groups:
for param in param_group['params']:
... | [
"def",
"move_optimizer_to_cuda",
"(",
"optimizer",
")",
":",
"for",
"param_group",
"in",
"optimizer",
".",
"param_groups",
":",
"for",
"param",
"in",
"param_group",
"[",
"'params'",
"]",
":",
"if",
"param",
".",
"is_cuda",
":",
"param_state",
"=",
"optimizer",... | Move the optimizer state to GPU, if necessary.
After calling, any parameter specific state in the optimizer
will be located on the same device as the parameter. | [
"Move",
"the",
"optimizer",
"state",
"to",
"GPU",
"if",
"necessary",
".",
"After",
"calling",
"any",
"parameter",
"specific",
"state",
"in",
"the",
"optimizer",
"will",
"be",
"located",
"on",
"the",
"same",
"device",
"as",
"the",
"parameter",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/training/util.py#L81-L93 |
23,016 | allenai/allennlp | allennlp/training/util.py | get_batch_size | def get_batch_size(batch: Union[Dict, torch.Tensor]) -> int:
"""
Returns the size of the batch dimension. Assumes a well-formed batch,
returns 0 otherwise.
"""
if isinstance(batch, torch.Tensor):
return batch.size(0) # type: ignore
elif isinstance(batch, Dict):
return get_batch_s... | python | def get_batch_size(batch: Union[Dict, torch.Tensor]) -> int:
"""
Returns the size of the batch dimension. Assumes a well-formed batch,
returns 0 otherwise.
"""
if isinstance(batch, torch.Tensor):
return batch.size(0) # type: ignore
elif isinstance(batch, Dict):
return get_batch_s... | [
"def",
"get_batch_size",
"(",
"batch",
":",
"Union",
"[",
"Dict",
",",
"torch",
".",
"Tensor",
"]",
")",
"->",
"int",
":",
"if",
"isinstance",
"(",
"batch",
",",
"torch",
".",
"Tensor",
")",
":",
"return",
"batch",
".",
"size",
"(",
"0",
")",
"# ty... | Returns the size of the batch dimension. Assumes a well-formed batch,
returns 0 otherwise. | [
"Returns",
"the",
"size",
"of",
"the",
"batch",
"dimension",
".",
"Assumes",
"a",
"well",
"-",
"formed",
"batch",
"returns",
"0",
"otherwise",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/training/util.py#L96-L106 |
23,017 | allenai/allennlp | allennlp/training/util.py | time_to_str | def time_to_str(timestamp: int) -> str:
"""
Convert seconds past Epoch to human readable string.
"""
datetimestamp = datetime.datetime.fromtimestamp(timestamp)
return '{:04d}-{:02d}-{:02d}-{:02d}-{:02d}-{:02d}'.format(
datetimestamp.year, datetimestamp.month, datetimestamp.day,
... | python | def time_to_str(timestamp: int) -> str:
"""
Convert seconds past Epoch to human readable string.
"""
datetimestamp = datetime.datetime.fromtimestamp(timestamp)
return '{:04d}-{:02d}-{:02d}-{:02d}-{:02d}-{:02d}'.format(
datetimestamp.year, datetimestamp.month, datetimestamp.day,
... | [
"def",
"time_to_str",
"(",
"timestamp",
":",
"int",
")",
"->",
"str",
":",
"datetimestamp",
"=",
"datetime",
".",
"datetime",
".",
"fromtimestamp",
"(",
"timestamp",
")",
"return",
"'{:04d}-{:02d}-{:02d}-{:02d}-{:02d}-{:02d}'",
".",
"format",
"(",
"datetimestamp",
... | Convert seconds past Epoch to human readable string. | [
"Convert",
"seconds",
"past",
"Epoch",
"to",
"human",
"readable",
"string",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/training/util.py#L109-L117 |
23,018 | allenai/allennlp | allennlp/training/util.py | str_to_time | def str_to_time(time_str: str) -> datetime.datetime:
"""
Convert human readable string to datetime.datetime.
"""
pieces: Any = [int(piece) for piece in time_str.split('-')]
return datetime.datetime(*pieces) | python | def str_to_time(time_str: str) -> datetime.datetime:
"""
Convert human readable string to datetime.datetime.
"""
pieces: Any = [int(piece) for piece in time_str.split('-')]
return datetime.datetime(*pieces) | [
"def",
"str_to_time",
"(",
"time_str",
":",
"str",
")",
"->",
"datetime",
".",
"datetime",
":",
"pieces",
":",
"Any",
"=",
"[",
"int",
"(",
"piece",
")",
"for",
"piece",
"in",
"time_str",
".",
"split",
"(",
"'-'",
")",
"]",
"return",
"datetime",
".",... | Convert human readable string to datetime.datetime. | [
"Convert",
"human",
"readable",
"string",
"to",
"datetime",
".",
"datetime",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/training/util.py#L120-L125 |
23,019 | allenai/allennlp | allennlp/training/util.py | datasets_from_params | def datasets_from_params(params: Params,
cache_directory: str = None,
cache_prefix: str = None) -> Dict[str, Iterable[Instance]]:
"""
Load all the datasets specified by the config.
Parameters
----------
params : ``Params``
cache_directory : ``st... | python | def datasets_from_params(params: Params,
cache_directory: str = None,
cache_prefix: str = None) -> Dict[str, Iterable[Instance]]:
"""
Load all the datasets specified by the config.
Parameters
----------
params : ``Params``
cache_directory : ``st... | [
"def",
"datasets_from_params",
"(",
"params",
":",
"Params",
",",
"cache_directory",
":",
"str",
"=",
"None",
",",
"cache_prefix",
":",
"str",
"=",
"None",
")",
"->",
"Dict",
"[",
"str",
",",
"Iterable",
"[",
"Instance",
"]",
"]",
":",
"dataset_reader_para... | Load all the datasets specified by the config.
Parameters
----------
params : ``Params``
cache_directory : ``str``, optional
If given, we will instruct the ``DatasetReaders`` that we construct to cache their
instances in this location (or read their instances from caches in this locatio... | [
"Load",
"all",
"the",
"datasets",
"specified",
"by",
"the",
"config",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/training/util.py#L128-L194 |
23,020 | allenai/allennlp | allennlp/training/util.py | create_serialization_dir | def create_serialization_dir(
params: Params,
serialization_dir: str,
recover: bool,
force: bool) -> None:
"""
This function creates the serialization directory if it doesn't exist. If it already exists
and is non-empty, then it verifies that we're recovering from a training... | python | def create_serialization_dir(
params: Params,
serialization_dir: str,
recover: bool,
force: bool) -> None:
"""
This function creates the serialization directory if it doesn't exist. If it already exists
and is non-empty, then it verifies that we're recovering from a training... | [
"def",
"create_serialization_dir",
"(",
"params",
":",
"Params",
",",
"serialization_dir",
":",
"str",
",",
"recover",
":",
"bool",
",",
"force",
":",
"bool",
")",
"->",
"None",
":",
"if",
"recover",
"and",
"force",
":",
"raise",
"ConfigurationError",
"(",
... | This function creates the serialization directory if it doesn't exist. If it already exists
and is non-empty, then it verifies that we're recovering from a training with an identical configuration.
Parameters
----------
params: ``Params``
A parameter object specifying an AllenNLP Experiment.
... | [
"This",
"function",
"creates",
"the",
"serialization",
"directory",
"if",
"it",
"doesn",
"t",
"exist",
".",
"If",
"it",
"already",
"exists",
"and",
"is",
"non",
"-",
"empty",
"then",
"it",
"verifies",
"that",
"we",
"re",
"recovering",
"from",
"a",
"trainin... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/training/util.py#L242-L309 |
23,021 | allenai/allennlp | allennlp/training/util.py | data_parallel | def data_parallel(batch_group: List[TensorDict],
model: Model,
cuda_devices: List) -> Dict[str, torch.Tensor]:
"""
Performs a forward pass using multiple GPUs. This is a simplification
of torch.nn.parallel.data_parallel to support the allennlp model
interface.
""... | python | def data_parallel(batch_group: List[TensorDict],
model: Model,
cuda_devices: List) -> Dict[str, torch.Tensor]:
"""
Performs a forward pass using multiple GPUs. This is a simplification
of torch.nn.parallel.data_parallel to support the allennlp model
interface.
""... | [
"def",
"data_parallel",
"(",
"batch_group",
":",
"List",
"[",
"TensorDict",
"]",
",",
"model",
":",
"Model",
",",
"cuda_devices",
":",
"List",
")",
"->",
"Dict",
"[",
"str",
",",
"torch",
".",
"Tensor",
"]",
":",
"assert",
"len",
"(",
"batch_group",
")... | Performs a forward pass using multiple GPUs. This is a simplification
of torch.nn.parallel.data_parallel to support the allennlp model
interface. | [
"Performs",
"a",
"forward",
"pass",
"using",
"multiple",
"GPUs",
".",
"This",
"is",
"a",
"simplification",
"of",
"torch",
".",
"nn",
".",
"parallel",
".",
"data_parallel",
"to",
"support",
"the",
"allennlp",
"model",
"interface",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/training/util.py#L311-L337 |
23,022 | allenai/allennlp | allennlp/training/util.py | rescale_gradients | def rescale_gradients(model: Model, grad_norm: Optional[float] = None) -> Optional[float]:
"""
Performs gradient rescaling. Is a no-op if gradient rescaling is not enabled.
"""
if grad_norm:
parameters_to_clip = [p for p in model.parameters()
if p.grad is not None]
... | python | def rescale_gradients(model: Model, grad_norm: Optional[float] = None) -> Optional[float]:
"""
Performs gradient rescaling. Is a no-op if gradient rescaling is not enabled.
"""
if grad_norm:
parameters_to_clip = [p for p in model.parameters()
if p.grad is not None]
... | [
"def",
"rescale_gradients",
"(",
"model",
":",
"Model",
",",
"grad_norm",
":",
"Optional",
"[",
"float",
"]",
"=",
"None",
")",
"->",
"Optional",
"[",
"float",
"]",
":",
"if",
"grad_norm",
":",
"parameters_to_clip",
"=",
"[",
"p",
"for",
"p",
"in",
"mo... | Performs gradient rescaling. Is a no-op if gradient rescaling is not enabled. | [
"Performs",
"gradient",
"rescaling",
".",
"Is",
"a",
"no",
"-",
"op",
"if",
"gradient",
"rescaling",
"is",
"not",
"enabled",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/training/util.py#L347-L355 |
23,023 | allenai/allennlp | allennlp/training/util.py | get_metrics | def get_metrics(model: Model, total_loss: float, num_batches: int, reset: bool = False) -> Dict[str, float]:
"""
Gets the metrics but sets ``"loss"`` to
the total loss divided by the ``num_batches`` so that
the ``"loss"`` metric is "average loss per batch".
"""
metrics = model.get_metrics(reset=... | python | def get_metrics(model: Model, total_loss: float, num_batches: int, reset: bool = False) -> Dict[str, float]:
"""
Gets the metrics but sets ``"loss"`` to
the total loss divided by the ``num_batches`` so that
the ``"loss"`` metric is "average loss per batch".
"""
metrics = model.get_metrics(reset=... | [
"def",
"get_metrics",
"(",
"model",
":",
"Model",
",",
"total_loss",
":",
"float",
",",
"num_batches",
":",
"int",
",",
"reset",
":",
"bool",
"=",
"False",
")",
"->",
"Dict",
"[",
"str",
",",
"float",
"]",
":",
"metrics",
"=",
"model",
".",
"get_metr... | Gets the metrics but sets ``"loss"`` to
the total loss divided by the ``num_batches`` so that
the ``"loss"`` metric is "average loss per batch". | [
"Gets",
"the",
"metrics",
"but",
"sets",
"loss",
"to",
"the",
"total",
"loss",
"divided",
"by",
"the",
"num_batches",
"so",
"that",
"the",
"loss",
"metric",
"is",
"average",
"loss",
"per",
"batch",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/training/util.py#L357-L365 |
23,024 | allenai/allennlp | scripts/check_requirements_and_setup.py | parse_requirements | def parse_requirements() -> Tuple[PackagesType, PackagesType, Set[str]]:
"""Parse all dependencies out of the requirements.txt file."""
essential_packages: PackagesType = {}
other_packages: PackagesType = {}
duplicates: Set[str] = set()
with open("requirements.txt", "r") as req_file:
section... | python | def parse_requirements() -> Tuple[PackagesType, PackagesType, Set[str]]:
"""Parse all dependencies out of the requirements.txt file."""
essential_packages: PackagesType = {}
other_packages: PackagesType = {}
duplicates: Set[str] = set()
with open("requirements.txt", "r") as req_file:
section... | [
"def",
"parse_requirements",
"(",
")",
"->",
"Tuple",
"[",
"PackagesType",
",",
"PackagesType",
",",
"Set",
"[",
"str",
"]",
"]",
":",
"essential_packages",
":",
"PackagesType",
"=",
"{",
"}",
"other_packages",
":",
"PackagesType",
"=",
"{",
"}",
"duplicates... | Parse all dependencies out of the requirements.txt file. | [
"Parse",
"all",
"dependencies",
"out",
"of",
"the",
"requirements",
".",
"txt",
"file",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/scripts/check_requirements_and_setup.py#L32-L60 |
23,025 | allenai/allennlp | scripts/check_requirements_and_setup.py | parse_setup | def parse_setup() -> Tuple[PackagesType, PackagesType, Set[str], Set[str]]:
"""Parse all dependencies out of the setup.py script."""
essential_packages: PackagesType = {}
test_packages: PackagesType = {}
essential_duplicates: Set[str] = set()
test_duplicates: Set[str] = set()
with open('setup.p... | python | def parse_setup() -> Tuple[PackagesType, PackagesType, Set[str], Set[str]]:
"""Parse all dependencies out of the setup.py script."""
essential_packages: PackagesType = {}
test_packages: PackagesType = {}
essential_duplicates: Set[str] = set()
test_duplicates: Set[str] = set()
with open('setup.p... | [
"def",
"parse_setup",
"(",
")",
"->",
"Tuple",
"[",
"PackagesType",
",",
"PackagesType",
",",
"Set",
"[",
"str",
"]",
",",
"Set",
"[",
"str",
"]",
"]",
":",
"essential_packages",
":",
"PackagesType",
"=",
"{",
"}",
"test_packages",
":",
"PackagesType",
"... | Parse all dependencies out of the setup.py script. | [
"Parse",
"all",
"dependencies",
"out",
"of",
"the",
"setup",
".",
"py",
"script",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/scripts/check_requirements_and_setup.py#L63-L93 |
23,026 | allenai/allennlp | allennlp/data/dataset_readers/dataset_utils/span_utils.py | enumerate_spans | def enumerate_spans(sentence: List[T],
offset: int = 0,
max_span_width: int = None,
min_span_width: int = 1,
filter_function: Callable[[List[T]], bool] = None) -> List[Tuple[int, int]]:
"""
Given a sentence, return all token spans w... | python | def enumerate_spans(sentence: List[T],
offset: int = 0,
max_span_width: int = None,
min_span_width: int = 1,
filter_function: Callable[[List[T]], bool] = None) -> List[Tuple[int, int]]:
"""
Given a sentence, return all token spans w... | [
"def",
"enumerate_spans",
"(",
"sentence",
":",
"List",
"[",
"T",
"]",
",",
"offset",
":",
"int",
"=",
"0",
",",
"max_span_width",
":",
"int",
"=",
"None",
",",
"min_span_width",
":",
"int",
"=",
"1",
",",
"filter_function",
":",
"Callable",
"[",
"[",
... | Given a sentence, return all token spans within the sentence. Spans are `inclusive`.
Additionally, you can provide a maximum and minimum span width, which will be used
to exclude spans outside of this range.
Finally, you can provide a function mapping ``List[T] -> bool``, which will
be applied to every... | [
"Given",
"a",
"sentence",
"return",
"all",
"token",
"spans",
"within",
"the",
"sentence",
".",
"Spans",
"are",
"inclusive",
".",
"Additionally",
"you",
"can",
"provide",
"a",
"maximum",
"and",
"minimum",
"span",
"width",
"which",
"will",
"be",
"used",
"to",
... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/data/dataset_readers/dataset_utils/span_utils.py#L20-L66 |
23,027 | allenai/allennlp | allennlp/data/dataset_readers/dataset_utils/span_utils.py | to_bioul | def to_bioul(tag_sequence: List[str], encoding: str = "IOB1") -> List[str]:
"""
Given a tag sequence encoded with IOB1 labels, recode to BIOUL.
In the IOB1 scheme, I is a token inside a span, O is a token outside
a span and B is the beginning of span immediately following another
span of the same t... | python | def to_bioul(tag_sequence: List[str], encoding: str = "IOB1") -> List[str]:
"""
Given a tag sequence encoded with IOB1 labels, recode to BIOUL.
In the IOB1 scheme, I is a token inside a span, O is a token outside
a span and B is the beginning of span immediately following another
span of the same t... | [
"def",
"to_bioul",
"(",
"tag_sequence",
":",
"List",
"[",
"str",
"]",
",",
"encoding",
":",
"str",
"=",
"\"IOB1\"",
")",
"->",
"List",
"[",
"str",
"]",
":",
"if",
"not",
"encoding",
"in",
"{",
"\"IOB1\"",
",",
"\"BIO\"",
"}",
":",
"raise",
"Configura... | Given a tag sequence encoded with IOB1 labels, recode to BIOUL.
In the IOB1 scheme, I is a token inside a span, O is a token outside
a span and B is the beginning of span immediately following another
span of the same type.
In the BIO scheme, I is a token inside a span, O is a token outside
a span... | [
"Given",
"a",
"tag",
"sequence",
"encoded",
"with",
"IOB1",
"labels",
"recode",
"to",
"BIOUL",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/data/dataset_readers/dataset_utils/span_utils.py#L267-L373 |
23,028 | allenai/allennlp | scripts/check_links.py | url_ok | def url_ok(match_tuple: MatchTuple) -> bool:
"""Check if a URL is reachable."""
try:
result = requests.get(match_tuple.link, timeout=5)
return result.ok
except (requests.ConnectionError, requests.Timeout):
return False | python | def url_ok(match_tuple: MatchTuple) -> bool:
"""Check if a URL is reachable."""
try:
result = requests.get(match_tuple.link, timeout=5)
return result.ok
except (requests.ConnectionError, requests.Timeout):
return False | [
"def",
"url_ok",
"(",
"match_tuple",
":",
"MatchTuple",
")",
"->",
"bool",
":",
"try",
":",
"result",
"=",
"requests",
".",
"get",
"(",
"match_tuple",
".",
"link",
",",
"timeout",
"=",
"5",
")",
"return",
"result",
".",
"ok",
"except",
"(",
"requests",... | Check if a URL is reachable. | [
"Check",
"if",
"a",
"URL",
"is",
"reachable",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/scripts/check_links.py#L24-L30 |
23,029 | allenai/allennlp | scripts/check_links.py | path_ok | def path_ok(match_tuple: MatchTuple) -> bool:
"""Check if a file in this repository exists."""
relative_path = match_tuple.link.split("#")[0]
full_path = os.path.join(os.path.dirname(str(match_tuple.source)), relative_path)
return os.path.exists(full_path) | python | def path_ok(match_tuple: MatchTuple) -> bool:
"""Check if a file in this repository exists."""
relative_path = match_tuple.link.split("#")[0]
full_path = os.path.join(os.path.dirname(str(match_tuple.source)), relative_path)
return os.path.exists(full_path) | [
"def",
"path_ok",
"(",
"match_tuple",
":",
"MatchTuple",
")",
"->",
"bool",
":",
"relative_path",
"=",
"match_tuple",
".",
"link",
".",
"split",
"(",
"\"#\"",
")",
"[",
"0",
"]",
"full_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path... | Check if a file in this repository exists. | [
"Check",
"if",
"a",
"file",
"in",
"this",
"repository",
"exists",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/scripts/check_links.py#L33-L37 |
23,030 | allenai/allennlp | allennlp/common/params.py | _environment_variables | def _environment_variables() -> Dict[str, str]:
"""
Wraps `os.environ` to filter out non-encodable values.
"""
return {key: value
for key, value in os.environ.items()
if _is_encodable(value)} | python | def _environment_variables() -> Dict[str, str]:
"""
Wraps `os.environ` to filter out non-encodable values.
"""
return {key: value
for key, value in os.environ.items()
if _is_encodable(value)} | [
"def",
"_environment_variables",
"(",
")",
"->",
"Dict",
"[",
"str",
",",
"str",
"]",
":",
"return",
"{",
"key",
":",
"value",
"for",
"key",
",",
"value",
"in",
"os",
".",
"environ",
".",
"items",
"(",
")",
"if",
"_is_encodable",
"(",
"value",
")",
... | Wraps `os.environ` to filter out non-encodable values. | [
"Wraps",
"os",
".",
"environ",
"to",
"filter",
"out",
"non",
"-",
"encodable",
"values",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/common/params.py#L85-L91 |
23,031 | allenai/allennlp | allennlp/common/params.py | with_fallback | def with_fallback(preferred: Dict[str, Any], fallback: Dict[str, Any]) -> Dict[str, Any]:
"""
Deep merge two dicts, preferring values from `preferred`.
"""
def merge(preferred_value: Any, fallback_value: Any) -> Any:
if isinstance(preferred_value, dict) and isinstance(fallback_value, dict):
... | python | def with_fallback(preferred: Dict[str, Any], fallback: Dict[str, Any]) -> Dict[str, Any]:
"""
Deep merge two dicts, preferring values from `preferred`.
"""
def merge(preferred_value: Any, fallback_value: Any) -> Any:
if isinstance(preferred_value, dict) and isinstance(fallback_value, dict):
... | [
"def",
"with_fallback",
"(",
"preferred",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
",",
"fallback",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
")",
"->",
"Dict",
"[",
"str",
",",
"Any",
"]",
":",
"def",
"merge",
"(",
"preferred_value",
":",
"Any",
... | Deep merge two dicts, preferring values from `preferred`. | [
"Deep",
"merge",
"two",
"dicts",
"preferring",
"values",
"from",
"preferred",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/common/params.py#L121-L161 |
23,032 | allenai/allennlp | allennlp/common/params.py | Params.add_file_to_archive | def add_file_to_archive(self, name: str) -> None:
"""
Any class in its ``from_params`` method can request that some of its
input files be added to the archive by calling this method.
For example, if some class ``A`` had an ``input_file`` parameter, it could call
```
par... | python | def add_file_to_archive(self, name: str) -> None:
"""
Any class in its ``from_params`` method can request that some of its
input files be added to the archive by calling this method.
For example, if some class ``A`` had an ``input_file`` parameter, it could call
```
par... | [
"def",
"add_file_to_archive",
"(",
"self",
",",
"name",
":",
"str",
")",
"->",
"None",
":",
"if",
"not",
"self",
".",
"loading_from_archive",
":",
"self",
".",
"files_to_archive",
"[",
"f\"{self.history}{name}\"",
"]",
"=",
"cached_path",
"(",
"self",
".",
"... | Any class in its ``from_params`` method can request that some of its
input files be added to the archive by calling this method.
For example, if some class ``A`` had an ``input_file`` parameter, it could call
```
params.add_file_to_archive("input_file")
```
which would... | [
"Any",
"class",
"in",
"its",
"from_params",
"method",
"can",
"request",
"that",
"some",
"of",
"its",
"input",
"files",
"be",
"added",
"to",
"the",
"archive",
"by",
"calling",
"this",
"method",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/common/params.py#L209-L232 |
23,033 | allenai/allennlp | allennlp/common/params.py | Params.pop_int | def pop_int(self, key: str, default: Any = DEFAULT) -> int:
"""
Performs a pop and coerces to an int.
"""
value = self.pop(key, default)
if value is None:
return None
else:
return int(value) | python | def pop_int(self, key: str, default: Any = DEFAULT) -> int:
"""
Performs a pop and coerces to an int.
"""
value = self.pop(key, default)
if value is None:
return None
else:
return int(value) | [
"def",
"pop_int",
"(",
"self",
",",
"key",
":",
"str",
",",
"default",
":",
"Any",
"=",
"DEFAULT",
")",
"->",
"int",
":",
"value",
"=",
"self",
".",
"pop",
"(",
"key",
",",
"default",
")",
"if",
"value",
"is",
"None",
":",
"return",
"None",
"else... | Performs a pop and coerces to an int. | [
"Performs",
"a",
"pop",
"and",
"coerces",
"to",
"an",
"int",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/common/params.py#L254-L262 |
23,034 | allenai/allennlp | allennlp/common/params.py | Params.pop_float | def pop_float(self, key: str, default: Any = DEFAULT) -> float:
"""
Performs a pop and coerces to a float.
"""
value = self.pop(key, default)
if value is None:
return None
else:
return float(value) | python | def pop_float(self, key: str, default: Any = DEFAULT) -> float:
"""
Performs a pop and coerces to a float.
"""
value = self.pop(key, default)
if value is None:
return None
else:
return float(value) | [
"def",
"pop_float",
"(",
"self",
",",
"key",
":",
"str",
",",
"default",
":",
"Any",
"=",
"DEFAULT",
")",
"->",
"float",
":",
"value",
"=",
"self",
".",
"pop",
"(",
"key",
",",
"default",
")",
"if",
"value",
"is",
"None",
":",
"return",
"None",
"... | Performs a pop and coerces to a float. | [
"Performs",
"a",
"pop",
"and",
"coerces",
"to",
"a",
"float",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/common/params.py#L264-L272 |
23,035 | allenai/allennlp | allennlp/common/params.py | Params.pop_bool | def pop_bool(self, key: str, default: Any = DEFAULT) -> bool:
"""
Performs a pop and coerces to a bool.
"""
value = self.pop(key, default)
if value is None:
return None
elif isinstance(value, bool):
return value
elif value == "true":
... | python | def pop_bool(self, key: str, default: Any = DEFAULT) -> bool:
"""
Performs a pop and coerces to a bool.
"""
value = self.pop(key, default)
if value is None:
return None
elif isinstance(value, bool):
return value
elif value == "true":
... | [
"def",
"pop_bool",
"(",
"self",
",",
"key",
":",
"str",
",",
"default",
":",
"Any",
"=",
"DEFAULT",
")",
"->",
"bool",
":",
"value",
"=",
"self",
".",
"pop",
"(",
"key",
",",
"default",
")",
"if",
"value",
"is",
"None",
":",
"return",
"None",
"el... | Performs a pop and coerces to a bool. | [
"Performs",
"a",
"pop",
"and",
"coerces",
"to",
"a",
"bool",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/common/params.py#L274-L288 |
23,036 | allenai/allennlp | allennlp/common/params.py | Params.pop_choice | def pop_choice(self, key: str, choices: List[Any], default_to_first_choice: bool = False) -> Any:
"""
Gets the value of ``key`` in the ``params`` dictionary, ensuring that the value is one of
the given choices. Note that this `pops` the key from params, modifying the dictionary,
consiste... | python | def pop_choice(self, key: str, choices: List[Any], default_to_first_choice: bool = False) -> Any:
"""
Gets the value of ``key`` in the ``params`` dictionary, ensuring that the value is one of
the given choices. Note that this `pops` the key from params, modifying the dictionary,
consiste... | [
"def",
"pop_choice",
"(",
"self",
",",
"key",
":",
"str",
",",
"choices",
":",
"List",
"[",
"Any",
"]",
",",
"default_to_first_choice",
":",
"bool",
"=",
"False",
")",
"->",
"Any",
":",
"default",
"=",
"choices",
"[",
"0",
"]",
"if",
"default_to_first_... | Gets the value of ``key`` in the ``params`` dictionary, ensuring that the value is one of
the given choices. Note that this `pops` the key from params, modifying the dictionary,
consistent with how parameters are processed in this codebase.
Parameters
----------
key: str
... | [
"Gets",
"the",
"value",
"of",
"key",
"in",
"the",
"params",
"dictionary",
"ensuring",
"that",
"the",
"value",
"is",
"one",
"of",
"the",
"given",
"choices",
".",
"Note",
"that",
"this",
"pops",
"the",
"key",
"from",
"params",
"modifying",
"the",
"dictionary... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/common/params.py#L305-L335 |
23,037 | allenai/allennlp | allennlp/common/params.py | Params.as_dict | def as_dict(self, quiet: bool = False, infer_type_and_cast: bool = False):
"""
Sometimes we need to just represent the parameters as a dict, for instance when we pass
them to PyTorch code.
Parameters
----------
quiet: bool, optional (default = False)
Whether ... | python | def as_dict(self, quiet: bool = False, infer_type_and_cast: bool = False):
"""
Sometimes we need to just represent the parameters as a dict, for instance when we pass
them to PyTorch code.
Parameters
----------
quiet: bool, optional (default = False)
Whether ... | [
"def",
"as_dict",
"(",
"self",
",",
"quiet",
":",
"bool",
"=",
"False",
",",
"infer_type_and_cast",
":",
"bool",
"=",
"False",
")",
":",
"if",
"infer_type_and_cast",
":",
"params_as_dict",
"=",
"infer_and_cast",
"(",
"self",
".",
"params",
")",
"else",
":"... | Sometimes we need to just represent the parameters as a dict, for instance when we pass
them to PyTorch code.
Parameters
----------
quiet: bool, optional (default = False)
Whether to log the parameters before returning them as a dict.
infer_type_and_cast : bool, opti... | [
"Sometimes",
"we",
"need",
"to",
"just",
"represent",
"the",
"parameters",
"as",
"a",
"dict",
"for",
"instance",
"when",
"we",
"pass",
"them",
"to",
"PyTorch",
"code",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/common/params.py#L337-L370 |
23,038 | allenai/allennlp | allennlp/common/params.py | Params.as_flat_dict | def as_flat_dict(self):
"""
Returns the parameters of a flat dictionary from keys to values.
Nested structure is collapsed with periods.
"""
flat_params = {}
def recurse(parameters, path):
for key, value in parameters.items():
newpath = path + ... | python | def as_flat_dict(self):
"""
Returns the parameters of a flat dictionary from keys to values.
Nested structure is collapsed with periods.
"""
flat_params = {}
def recurse(parameters, path):
for key, value in parameters.items():
newpath = path + ... | [
"def",
"as_flat_dict",
"(",
"self",
")",
":",
"flat_params",
"=",
"{",
"}",
"def",
"recurse",
"(",
"parameters",
",",
"path",
")",
":",
"for",
"key",
",",
"value",
"in",
"parameters",
".",
"items",
"(",
")",
":",
"newpath",
"=",
"path",
"+",
"[",
"... | Returns the parameters of a flat dictionary from keys to values.
Nested structure is collapsed with periods. | [
"Returns",
"the",
"parameters",
"of",
"a",
"flat",
"dictionary",
"from",
"keys",
"to",
"values",
".",
"Nested",
"structure",
"is",
"collapsed",
"with",
"periods",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/common/params.py#L372-L387 |
23,039 | allenai/allennlp | allennlp/common/params.py | Params.from_file | def from_file(params_file: str, params_overrides: str = "", ext_vars: dict = None) -> 'Params':
"""
Load a `Params` object from a configuration file.
Parameters
----------
params_file : ``str``
The path to the configuration file to load.
params_overrides : ``... | python | def from_file(params_file: str, params_overrides: str = "", ext_vars: dict = None) -> 'Params':
"""
Load a `Params` object from a configuration file.
Parameters
----------
params_file : ``str``
The path to the configuration file to load.
params_overrides : ``... | [
"def",
"from_file",
"(",
"params_file",
":",
"str",
",",
"params_overrides",
":",
"str",
"=",
"\"\"",
",",
"ext_vars",
":",
"dict",
"=",
"None",
")",
"->",
"'Params'",
":",
"if",
"ext_vars",
"is",
"None",
":",
"ext_vars",
"=",
"{",
"}",
"# redirect to ca... | Load a `Params` object from a configuration file.
Parameters
----------
params_file : ``str``
The path to the configuration file to load.
params_overrides : ``str``, optional
A dict of overrides that can be applied to final object.
e.g. {"model.embedd... | [
"Load",
"a",
"Params",
"object",
"from",
"a",
"configuration",
"file",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/common/params.py#L436-L466 |
23,040 | allenai/allennlp | allennlp/common/params.py | Params.as_ordered_dict | def as_ordered_dict(self, preference_orders: List[List[str]] = None) -> OrderedDict:
"""
Returns Ordered Dict of Params from list of partial order preferences.
Parameters
----------
preference_orders: List[List[str]], optional
``preference_orders`` is list of partial... | python | def as_ordered_dict(self, preference_orders: List[List[str]] = None) -> OrderedDict:
"""
Returns Ordered Dict of Params from list of partial order preferences.
Parameters
----------
preference_orders: List[List[str]], optional
``preference_orders`` is list of partial... | [
"def",
"as_ordered_dict",
"(",
"self",
",",
"preference_orders",
":",
"List",
"[",
"List",
"[",
"str",
"]",
"]",
"=",
"None",
")",
"->",
"OrderedDict",
":",
"params_dict",
"=",
"self",
".",
"as_dict",
"(",
"quiet",
"=",
"True",
")",
"if",
"not",
"prefe... | Returns Ordered Dict of Params from list of partial order preferences.
Parameters
----------
preference_orders: List[List[str]], optional
``preference_orders`` is list of partial preference orders. ["A", "B", "C"] means
"A" > "B" > "C". For multiple preference_orders fir... | [
"Returns",
"Ordered",
"Dict",
"of",
"Params",
"from",
"list",
"of",
"partial",
"order",
"preferences",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/common/params.py#L472-L507 |
23,041 | allenai/allennlp | allennlp/training/metric_tracker.py | MetricTracker.clear | def clear(self) -> None:
"""
Clears out the tracked metrics, but keeps the patience and should_decrease settings.
"""
self._best_so_far = None
self._epochs_with_no_improvement = 0
self._is_best_so_far = True
self._epoch_number = 0
self.best_epoch = None | python | def clear(self) -> None:
"""
Clears out the tracked metrics, but keeps the patience and should_decrease settings.
"""
self._best_so_far = None
self._epochs_with_no_improvement = 0
self._is_best_so_far = True
self._epoch_number = 0
self.best_epoch = None | [
"def",
"clear",
"(",
"self",
")",
"->",
"None",
":",
"self",
".",
"_best_so_far",
"=",
"None",
"self",
".",
"_epochs_with_no_improvement",
"=",
"0",
"self",
".",
"_is_best_so_far",
"=",
"True",
"self",
".",
"_epoch_number",
"=",
"0",
"self",
".",
"best_epo... | Clears out the tracked metrics, but keeps the patience and should_decrease settings. | [
"Clears",
"out",
"the",
"tracked",
"metrics",
"but",
"keeps",
"the",
"patience",
"and",
"should_decrease",
"settings",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/training/metric_tracker.py#L59-L67 |
23,042 | allenai/allennlp | allennlp/training/metric_tracker.py | MetricTracker.state_dict | def state_dict(self) -> Dict[str, Any]:
"""
A ``Trainer`` can use this to serialize the state of the metric tracker.
"""
return {
"best_so_far": self._best_so_far,
"patience": self._patience,
"epochs_with_no_improvement": self._epochs_with_... | python | def state_dict(self) -> Dict[str, Any]:
"""
A ``Trainer`` can use this to serialize the state of the metric tracker.
"""
return {
"best_so_far": self._best_so_far,
"patience": self._patience,
"epochs_with_no_improvement": self._epochs_with_... | [
"def",
"state_dict",
"(",
"self",
")",
"->",
"Dict",
"[",
"str",
",",
"Any",
"]",
":",
"return",
"{",
"\"best_so_far\"",
":",
"self",
".",
"_best_so_far",
",",
"\"patience\"",
":",
"self",
".",
"_patience",
",",
"\"epochs_with_no_improvement\"",
":",
"self",... | A ``Trainer`` can use this to serialize the state of the metric tracker. | [
"A",
"Trainer",
"can",
"use",
"this",
"to",
"serialize",
"the",
"state",
"of",
"the",
"metric",
"tracker",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/training/metric_tracker.py#L69-L82 |
23,043 | allenai/allennlp | allennlp/training/metric_tracker.py | MetricTracker.add_metric | def add_metric(self, metric: float) -> None:
"""
Record a new value of the metric and update the various things that depend on it.
"""
new_best = ((self._best_so_far is None) or
(self._should_decrease and metric < self._best_so_far) or
(not self._s... | python | def add_metric(self, metric: float) -> None:
"""
Record a new value of the metric and update the various things that depend on it.
"""
new_best = ((self._best_so_far is None) or
(self._should_decrease and metric < self._best_so_far) or
(not self._s... | [
"def",
"add_metric",
"(",
"self",
",",
"metric",
":",
"float",
")",
"->",
"None",
":",
"new_best",
"=",
"(",
"(",
"self",
".",
"_best_so_far",
"is",
"None",
")",
"or",
"(",
"self",
".",
"_should_decrease",
"and",
"metric",
"<",
"self",
".",
"_best_so_f... | Record a new value of the metric and update the various things that depend on it. | [
"Record",
"a",
"new",
"value",
"of",
"the",
"metric",
"and",
"update",
"the",
"various",
"things",
"that",
"depend",
"on",
"it",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/training/metric_tracker.py#L97-L113 |
23,044 | allenai/allennlp | allennlp/training/metric_tracker.py | MetricTracker.add_metrics | def add_metrics(self, metrics: Iterable[float]) -> None:
"""
Helper to add multiple metrics at once.
"""
for metric in metrics:
self.add_metric(metric) | python | def add_metrics(self, metrics: Iterable[float]) -> None:
"""
Helper to add multiple metrics at once.
"""
for metric in metrics:
self.add_metric(metric) | [
"def",
"add_metrics",
"(",
"self",
",",
"metrics",
":",
"Iterable",
"[",
"float",
"]",
")",
"->",
"None",
":",
"for",
"metric",
"in",
"metrics",
":",
"self",
".",
"add_metric",
"(",
"metric",
")"
] | Helper to add multiple metrics at once. | [
"Helper",
"to",
"add",
"multiple",
"metrics",
"at",
"once",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/training/metric_tracker.py#L115-L120 |
23,045 | allenai/allennlp | allennlp/training/metric_tracker.py | MetricTracker.should_stop_early | def should_stop_early(self) -> bool:
"""
Returns true if improvement has stopped for long enough.
"""
if self._patience is None:
return False
else:
return self._epochs_with_no_improvement >= self._patience | python | def should_stop_early(self) -> bool:
"""
Returns true if improvement has stopped for long enough.
"""
if self._patience is None:
return False
else:
return self._epochs_with_no_improvement >= self._patience | [
"def",
"should_stop_early",
"(",
"self",
")",
"->",
"bool",
":",
"if",
"self",
".",
"_patience",
"is",
"None",
":",
"return",
"False",
"else",
":",
"return",
"self",
".",
"_epochs_with_no_improvement",
">=",
"self",
".",
"_patience"
] | Returns true if improvement has stopped for long enough. | [
"Returns",
"true",
"if",
"improvement",
"has",
"stopped",
"for",
"long",
"enough",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/training/metric_tracker.py#L128-L135 |
23,046 | allenai/allennlp | allennlp/models/archival.py | archive_model | def archive_model(serialization_dir: str,
weights: str = _DEFAULT_WEIGHTS,
files_to_archive: Dict[str, str] = None,
archive_path: str = None) -> None:
"""
Archive the model weights, its training configuration, and its
vocabulary to `model.tar.gz`. Includ... | python | def archive_model(serialization_dir: str,
weights: str = _DEFAULT_WEIGHTS,
files_to_archive: Dict[str, str] = None,
archive_path: str = None) -> None:
"""
Archive the model weights, its training configuration, and its
vocabulary to `model.tar.gz`. Includ... | [
"def",
"archive_model",
"(",
"serialization_dir",
":",
"str",
",",
"weights",
":",
"str",
"=",
"_DEFAULT_WEIGHTS",
",",
"files_to_archive",
":",
"Dict",
"[",
"str",
",",
"str",
"]",
"=",
"None",
",",
"archive_path",
":",
"str",
"=",
"None",
")",
"->",
"N... | Archive the model weights, its training configuration, and its
vocabulary to `model.tar.gz`. Include the additional ``files_to_archive``
if provided.
Parameters
----------
serialization_dir: ``str``
The directory where the weights and vocabulary are written out.
weights: ``str``, option... | [
"Archive",
"the",
"model",
"weights",
"its",
"training",
"configuration",
"and",
"its",
"vocabulary",
"to",
"model",
".",
"tar",
".",
"gz",
".",
"Include",
"the",
"additional",
"files_to_archive",
"if",
"provided",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/models/archival.py#L89-L148 |
23,047 | allenai/allennlp | allennlp/models/archival.py | load_archive | def load_archive(archive_file: str,
cuda_device: int = -1,
overrides: str = "",
weights_file: str = None) -> Archive:
"""
Instantiates an Archive from an archived `tar.gz` file.
Parameters
----------
archive_file: ``str``
The archive file t... | python | def load_archive(archive_file: str,
cuda_device: int = -1,
overrides: str = "",
weights_file: str = None) -> Archive:
"""
Instantiates an Archive from an archived `tar.gz` file.
Parameters
----------
archive_file: ``str``
The archive file t... | [
"def",
"load_archive",
"(",
"archive_file",
":",
"str",
",",
"cuda_device",
":",
"int",
"=",
"-",
"1",
",",
"overrides",
":",
"str",
"=",
"\"\"",
",",
"weights_file",
":",
"str",
"=",
"None",
")",
"->",
"Archive",
":",
"# redirect to the cache, if necessary"... | Instantiates an Archive from an archived `tar.gz` file.
Parameters
----------
archive_file: ``str``
The archive file to load the model from.
weights_file: ``str``, optional (default = None)
The weights file to use. If unspecified, weights.th in the archive_file will be used.
cuda_d... | [
"Instantiates",
"an",
"Archive",
"from",
"an",
"archived",
"tar",
".",
"gz",
"file",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/models/archival.py#L150-L232 |
23,048 | allenai/allennlp | allennlp/models/archival.py | Archive.extract_module | def extract_module(self, path: str, freeze: bool = True) -> Module:
"""
This method can be used to load a module from the pretrained model archive.
It is also used implicitly in FromParams based construction. So instead of using standard
params to construct a module, you can instead loa... | python | def extract_module(self, path: str, freeze: bool = True) -> Module:
"""
This method can be used to load a module from the pretrained model archive.
It is also used implicitly in FromParams based construction. So instead of using standard
params to construct a module, you can instead loa... | [
"def",
"extract_module",
"(",
"self",
",",
"path",
":",
"str",
",",
"freeze",
":",
"bool",
"=",
"True",
")",
"->",
"Module",
":",
"modules_dict",
"=",
"{",
"path",
":",
"module",
"for",
"path",
",",
"module",
"in",
"self",
".",
"model",
".",
"named_m... | This method can be used to load a module from the pretrained model archive.
It is also used implicitly in FromParams based construction. So instead of using standard
params to construct a module, you can instead load a pretrained module from the model
archive directly. For eg, instead of using ... | [
"This",
"method",
"can",
"be",
"used",
"to",
"load",
"a",
"module",
"from",
"the",
"pretrained",
"model",
"archive",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/models/archival.py#L28-L76 |
23,049 | allenai/allennlp | allennlp/models/semantic_parsing/nlvr/nlvr_semantic_parser.py | NlvrSemanticParser._get_action_strings | def _get_action_strings(cls,
possible_actions: List[List[ProductionRule]],
action_indices: Dict[int, List[List[int]]]) -> List[List[List[str]]]:
"""
Takes a list of possible actions and indices of decoded actions into those possible actions
... | python | def _get_action_strings(cls,
possible_actions: List[List[ProductionRule]],
action_indices: Dict[int, List[List[int]]]) -> List[List[List[str]]]:
"""
Takes a list of possible actions and indices of decoded actions into those possible actions
... | [
"def",
"_get_action_strings",
"(",
"cls",
",",
"possible_actions",
":",
"List",
"[",
"List",
"[",
"ProductionRule",
"]",
"]",
",",
"action_indices",
":",
"Dict",
"[",
"int",
",",
"List",
"[",
"List",
"[",
"int",
"]",
"]",
"]",
")",
"->",
"List",
"[",
... | Takes a list of possible actions and indices of decoded actions into those possible actions
for a batch and returns sequences of action strings. We assume ``action_indices`` is a dict
mapping batch indices to k-best decoded sequence lists. | [
"Takes",
"a",
"list",
"of",
"possible",
"actions",
"and",
"indices",
"of",
"decoded",
"actions",
"into",
"those",
"possible",
"actions",
"for",
"a",
"batch",
"and",
"returns",
"sequences",
"of",
"action",
"strings",
".",
"We",
"assume",
"action_indices",
"is",... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/models/semantic_parsing/nlvr/nlvr_semantic_parser.py#L122-L140 |
23,050 | allenai/allennlp | allennlp/models/semantic_parsing/nlvr/nlvr_semantic_parser.py | NlvrSemanticParser.decode | def decode(self, output_dict: Dict[str, torch.Tensor]) -> Dict[str, torch.Tensor]:
"""
This method overrides ``Model.decode``, which gets called after ``Model.forward``, at test
time, to finalize predictions. We only transform the action string sequences into logical
forms here.
... | python | def decode(self, output_dict: Dict[str, torch.Tensor]) -> Dict[str, torch.Tensor]:
"""
This method overrides ``Model.decode``, which gets called after ``Model.forward``, at test
time, to finalize predictions. We only transform the action string sequences into logical
forms here.
... | [
"def",
"decode",
"(",
"self",
",",
"output_dict",
":",
"Dict",
"[",
"str",
",",
"torch",
".",
"Tensor",
"]",
")",
"->",
"Dict",
"[",
"str",
",",
"torch",
".",
"Tensor",
"]",
":",
"best_action_strings",
"=",
"output_dict",
"[",
"\"best_action_strings\"",
... | This method overrides ``Model.decode``, which gets called after ``Model.forward``, at test
time, to finalize predictions. We only transform the action string sequences into logical
forms here. | [
"This",
"method",
"overrides",
"Model",
".",
"decode",
"which",
"gets",
"called",
"after",
"Model",
".",
"forward",
"at",
"test",
"time",
"to",
"finalize",
"predictions",
".",
"We",
"only",
"transform",
"the",
"action",
"string",
"sequences",
"into",
"logical"... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/models/semantic_parsing/nlvr/nlvr_semantic_parser.py#L201-L244 |
23,051 | allenai/allennlp | allennlp/models/semantic_parsing/nlvr/nlvr_semantic_parser.py | NlvrSemanticParser._check_state_denotations | def _check_state_denotations(self, state: GrammarBasedState, worlds: List[NlvrLanguage]) -> List[bool]:
"""
Returns whether action history in the state evaluates to the correct denotations over all
worlds. Only defined when the state is finished.
"""
assert state.is_finished(), "... | python | def _check_state_denotations(self, state: GrammarBasedState, worlds: List[NlvrLanguage]) -> List[bool]:
"""
Returns whether action history in the state evaluates to the correct denotations over all
worlds. Only defined when the state is finished.
"""
assert state.is_finished(), "... | [
"def",
"_check_state_denotations",
"(",
"self",
",",
"state",
":",
"GrammarBasedState",
",",
"worlds",
":",
"List",
"[",
"NlvrLanguage",
"]",
")",
"->",
"List",
"[",
"bool",
"]",
":",
"assert",
"state",
".",
"is_finished",
"(",
")",
",",
"\"Cannot compute de... | Returns whether action history in the state evaluates to the correct denotations over all
worlds. Only defined when the state is finished. | [
"Returns",
"whether",
"action",
"history",
"in",
"the",
"state",
"evaluates",
"to",
"the",
"correct",
"denotations",
"over",
"all",
"worlds",
".",
"Only",
"defined",
"when",
"the",
"state",
"is",
"finished",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/models/semantic_parsing/nlvr/nlvr_semantic_parser.py#L246-L258 |
23,052 | allenai/allennlp | allennlp/commands/find_learning_rate.py | find_learning_rate_from_args | def find_learning_rate_from_args(args: argparse.Namespace) -> None:
"""
Start learning rate finder for given args
"""
params = Params.from_file(args.param_path, args.overrides)
find_learning_rate_model(params, args.serialization_dir,
start_lr=args.start_lr,
... | python | def find_learning_rate_from_args(args: argparse.Namespace) -> None:
"""
Start learning rate finder for given args
"""
params = Params.from_file(args.param_path, args.overrides)
find_learning_rate_model(params, args.serialization_dir,
start_lr=args.start_lr,
... | [
"def",
"find_learning_rate_from_args",
"(",
"args",
":",
"argparse",
".",
"Namespace",
")",
"->",
"None",
":",
"params",
"=",
"Params",
".",
"from_file",
"(",
"args",
".",
"param_path",
",",
"args",
".",
"overrides",
")",
"find_learning_rate_model",
"(",
"para... | Start learning rate finder for given args | [
"Start",
"learning",
"rate",
"finder",
"for",
"given",
"args"
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/commands/find_learning_rate.py#L121-L132 |
23,053 | allenai/allennlp | allennlp/commands/find_learning_rate.py | find_learning_rate_model | def find_learning_rate_model(params: Params, serialization_dir: str,
start_lr: float = 1e-5,
end_lr: float = 10,
num_batches: int = 100,
linear_steps: bool = False,
stopping_f... | python | def find_learning_rate_model(params: Params, serialization_dir: str,
start_lr: float = 1e-5,
end_lr: float = 10,
num_batches: int = 100,
linear_steps: bool = False,
stopping_f... | [
"def",
"find_learning_rate_model",
"(",
"params",
":",
"Params",
",",
"serialization_dir",
":",
"str",
",",
"start_lr",
":",
"float",
"=",
"1e-5",
",",
"end_lr",
":",
"float",
"=",
"10",
",",
"num_batches",
":",
"int",
"=",
"100",
",",
"linear_steps",
":",... | Runs learning rate search for given `num_batches` and saves the results in ``serialization_dir``
Parameters
----------
params : ``Params``
A parameter object specifying an AllenNLP Experiment.
serialization_dir : ``str``
The directory in which to save results.
start_lr: ``float``
... | [
"Runs",
"learning",
"rate",
"search",
"for",
"given",
"num_batches",
"and",
"saves",
"the",
"results",
"in",
"serialization_dir"
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/commands/find_learning_rate.py#L134-L229 |
23,054 | allenai/allennlp | allennlp/commands/find_learning_rate.py | _smooth | def _smooth(values: List[float], beta: float) -> List[float]:
""" Exponential smoothing of values """
avg_value = 0.
smoothed = []
for i, value in enumerate(values):
avg_value = beta * avg_value + (1 - beta) * value
smoothed.append(avg_value / (1 - beta ** (i + 1)))
return smoothed | python | def _smooth(values: List[float], beta: float) -> List[float]:
""" Exponential smoothing of values """
avg_value = 0.
smoothed = []
for i, value in enumerate(values):
avg_value = beta * avg_value + (1 - beta) * value
smoothed.append(avg_value / (1 - beta ** (i + 1)))
return smoothed | [
"def",
"_smooth",
"(",
"values",
":",
"List",
"[",
"float",
"]",
",",
"beta",
":",
"float",
")",
"->",
"List",
"[",
"float",
"]",
":",
"avg_value",
"=",
"0.",
"smoothed",
"=",
"[",
"]",
"for",
"i",
",",
"value",
"in",
"enumerate",
"(",
"values",
... | Exponential smoothing of values | [
"Exponential",
"smoothing",
"of",
"values"
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/commands/find_learning_rate.py#L315-L322 |
23,055 | allenai/allennlp | allennlp/modules/scalar_mix.py | ScalarMix.forward | def forward(self, tensors: List[torch.Tensor], # pylint: disable=arguments-differ
mask: torch.Tensor = None) -> torch.Tensor:
"""
Compute a weighted average of the ``tensors``. The input tensors an be any shape
with at least two dimensions, but must all be the same shape.
... | python | def forward(self, tensors: List[torch.Tensor], # pylint: disable=arguments-differ
mask: torch.Tensor = None) -> torch.Tensor:
"""
Compute a weighted average of the ``tensors``. The input tensors an be any shape
with at least two dimensions, but must all be the same shape.
... | [
"def",
"forward",
"(",
"self",
",",
"tensors",
":",
"List",
"[",
"torch",
".",
"Tensor",
"]",
",",
"# pylint: disable=arguments-differ",
"mask",
":",
"torch",
".",
"Tensor",
"=",
"None",
")",
"->",
"torch",
".",
"Tensor",
":",
"if",
"len",
"(",
"tensors"... | Compute a weighted average of the ``tensors``. The input tensors an be any shape
with at least two dimensions, but must all be the same shape.
When ``do_layer_norm=True``, the ``mask`` is required input. If the ``tensors`` are
dimensioned ``(dim_0, ..., dim_{n-1}, dim_n)``, then the ``mask``... | [
"Compute",
"a",
"weighted",
"average",
"of",
"the",
"tensors",
".",
"The",
"input",
"tensors",
"an",
"be",
"any",
"shape",
"with",
"at",
"least",
"two",
"dimensions",
"but",
"must",
"all",
"be",
"the",
"same",
"shape",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/modules/scalar_mix.py#L38-L81 |
23,056 | allenai/allennlp | allennlp/semparse/domain_languages/domain_language.py | DomainLanguage.execute | def execute(self, logical_form: str):
"""Executes a logical form, using whatever predicates you have defined."""
if not hasattr(self, '_functions'):
raise RuntimeError("You must call super().__init__() in your Language constructor")
logical_form = logical_form.replace(",", " ")
... | python | def execute(self, logical_form: str):
"""Executes a logical form, using whatever predicates you have defined."""
if not hasattr(self, '_functions'):
raise RuntimeError("You must call super().__init__() in your Language constructor")
logical_form = logical_form.replace(",", " ")
... | [
"def",
"execute",
"(",
"self",
",",
"logical_form",
":",
"str",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'_functions'",
")",
":",
"raise",
"RuntimeError",
"(",
"\"You must call super().__init__() in your Language constructor\"",
")",
"logical_form",
"=",... | Executes a logical form, using whatever predicates you have defined. | [
"Executes",
"a",
"logical",
"form",
"using",
"whatever",
"predicates",
"you",
"have",
"defined",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/domain_languages/domain_language.py#L307-L313 |
23,057 | allenai/allennlp | allennlp/semparse/domain_languages/domain_language.py | DomainLanguage.get_nonterminal_productions | def get_nonterminal_productions(self) -> Dict[str, List[str]]:
"""
Induces a grammar from the defined collection of predicates in this language and returns
all productions in that grammar, keyed by the non-terminal they are expanding.
This includes terminal productions implied by each p... | python | def get_nonterminal_productions(self) -> Dict[str, List[str]]:
"""
Induces a grammar from the defined collection of predicates in this language and returns
all productions in that grammar, keyed by the non-terminal they are expanding.
This includes terminal productions implied by each p... | [
"def",
"get_nonterminal_productions",
"(",
"self",
")",
"->",
"Dict",
"[",
"str",
",",
"List",
"[",
"str",
"]",
"]",
":",
"if",
"not",
"self",
".",
"_nonterminal_productions",
":",
"actions",
":",
"Dict",
"[",
"str",
",",
"Set",
"[",
"str",
"]",
"]",
... | Induces a grammar from the defined collection of predicates in this language and returns
all productions in that grammar, keyed by the non-terminal they are expanding.
This includes terminal productions implied by each predicate as well as productions for the
`return type` of each defined predi... | [
"Induces",
"a",
"grammar",
"from",
"the",
"defined",
"collection",
"of",
"predicates",
"in",
"this",
"language",
"and",
"returns",
"all",
"productions",
"in",
"that",
"grammar",
"keyed",
"by",
"the",
"non",
"-",
"terminal",
"they",
"are",
"expanding",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/domain_languages/domain_language.py#L335-L367 |
23,058 | allenai/allennlp | allennlp/semparse/domain_languages/domain_language.py | DomainLanguage.logical_form_to_action_sequence | def logical_form_to_action_sequence(self, logical_form: str) -> List[str]:
"""
Converts a logical form into a linearization of the production rules from its abstract
syntax tree. The linearization is top-down, depth-first.
Each production rule is formatted as "LHS -> RHS", where "LHS" ... | python | def logical_form_to_action_sequence(self, logical_form: str) -> List[str]:
"""
Converts a logical form into a linearization of the production rules from its abstract
syntax tree. The linearization is top-down, depth-first.
Each production rule is formatted as "LHS -> RHS", where "LHS" ... | [
"def",
"logical_form_to_action_sequence",
"(",
"self",
",",
"logical_form",
":",
"str",
")",
"->",
"List",
"[",
"str",
"]",
":",
"expression",
"=",
"util",
".",
"lisp_to_nested_expression",
"(",
"logical_form",
")",
"try",
":",
"transitions",
",",
"start_type",
... | Converts a logical form into a linearization of the production rules from its abstract
syntax tree. The linearization is top-down, depth-first.
Each production rule is formatted as "LHS -> RHS", where "LHS" is a single non-terminal
type, and RHS is either a terminal or a list of non-terminals ... | [
"Converts",
"a",
"logical",
"form",
"into",
"a",
"linearization",
"of",
"the",
"production",
"rules",
"from",
"its",
"abstract",
"syntax",
"tree",
".",
"The",
"linearization",
"is",
"top",
"-",
"down",
"depth",
"-",
"first",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/domain_languages/domain_language.py#L379-L409 |
23,059 | allenai/allennlp | allennlp/semparse/domain_languages/domain_language.py | DomainLanguage.is_nonterminal | def is_nonterminal(self, symbol: str) -> bool:
"""
Determines whether an input symbol is a valid non-terminal in the grammar.
"""
nonterminal_productions = self.get_nonterminal_productions()
return symbol in nonterminal_productions | python | def is_nonterminal(self, symbol: str) -> bool:
"""
Determines whether an input symbol is a valid non-terminal in the grammar.
"""
nonterminal_productions = self.get_nonterminal_productions()
return symbol in nonterminal_productions | [
"def",
"is_nonterminal",
"(",
"self",
",",
"symbol",
":",
"str",
")",
"->",
"bool",
":",
"nonterminal_productions",
"=",
"self",
".",
"get_nonterminal_productions",
"(",
")",
"return",
"symbol",
"in",
"nonterminal_productions"
] | Determines whether an input symbol is a valid non-terminal in the grammar. | [
"Determines",
"whether",
"an",
"input",
"symbol",
"is",
"a",
"valid",
"non",
"-",
"terminal",
"in",
"the",
"grammar",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/domain_languages/domain_language.py#L488-L493 |
23,060 | allenai/allennlp | allennlp/data/token_indexers/token_indexer.py | TokenIndexer.pad_token_sequence | def pad_token_sequence(self,
tokens: Dict[str, List[TokenType]],
desired_num_tokens: Dict[str, int],
padding_lengths: Dict[str, int]) -> Dict[str, List[TokenType]]:
"""
This method pads a list of tokens to ``desired_num_tok... | python | def pad_token_sequence(self,
tokens: Dict[str, List[TokenType]],
desired_num_tokens: Dict[str, int],
padding_lengths: Dict[str, int]) -> Dict[str, List[TokenType]]:
"""
This method pads a list of tokens to ``desired_num_tok... | [
"def",
"pad_token_sequence",
"(",
"self",
",",
"tokens",
":",
"Dict",
"[",
"str",
",",
"List",
"[",
"TokenType",
"]",
"]",
",",
"desired_num_tokens",
":",
"Dict",
"[",
"str",
",",
"int",
"]",
",",
"padding_lengths",
":",
"Dict",
"[",
"str",
",",
"int",... | This method pads a list of tokens to ``desired_num_tokens`` and returns a padded copy of the
input tokens. If the input token list is longer than ``desired_num_tokens`` then it will be
truncated.
``padding_lengths`` is used to provide supplemental padding parameters which are needed
in... | [
"This",
"method",
"pads",
"a",
"list",
"of",
"tokens",
"to",
"desired_num_tokens",
"and",
"returns",
"a",
"padded",
"copy",
"of",
"the",
"input",
"tokens",
".",
"If",
"the",
"input",
"token",
"list",
"is",
"longer",
"than",
"desired_num_tokens",
"then",
"it"... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/data/token_indexers/token_indexer.py#L62-L75 |
23,061 | allenai/allennlp | allennlp/data/dataset_readers/coreference_resolution/conll.py | canonicalize_clusters | def canonicalize_clusters(clusters: DefaultDict[int, List[Tuple[int, int]]]) -> List[List[Tuple[int, int]]]:
"""
The CONLL 2012 data includes 2 annotated spans which are identical,
but have different ids. This checks all clusters for spans which are
identical, and if it finds any, merges the clusters co... | python | def canonicalize_clusters(clusters: DefaultDict[int, List[Tuple[int, int]]]) -> List[List[Tuple[int, int]]]:
"""
The CONLL 2012 data includes 2 annotated spans which are identical,
but have different ids. This checks all clusters for spans which are
identical, and if it finds any, merges the clusters co... | [
"def",
"canonicalize_clusters",
"(",
"clusters",
":",
"DefaultDict",
"[",
"int",
",",
"List",
"[",
"Tuple",
"[",
"int",
",",
"int",
"]",
"]",
"]",
")",
"->",
"List",
"[",
"List",
"[",
"Tuple",
"[",
"int",
",",
"int",
"]",
"]",
"]",
":",
"merged_clu... | The CONLL 2012 data includes 2 annotated spans which are identical,
but have different ids. This checks all clusters for spans which are
identical, and if it finds any, merges the clusters containing the
identical spans. | [
"The",
"CONLL",
"2012",
"data",
"includes",
"2",
"annotated",
"spans",
"which",
"are",
"identical",
"but",
"have",
"different",
"ids",
".",
"This",
"checks",
"all",
"clusters",
"for",
"spans",
"which",
"are",
"identical",
"and",
"if",
"it",
"finds",
"any",
... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/data/dataset_readers/coreference_resolution/conll.py#L18-L47 |
23,062 | allenai/allennlp | allennlp/predictors/open_information_extraction.py | get_predicate_indices | def get_predicate_indices(tags: List[str]) -> List[int]:
"""
Return the word indices of a predicate in BIO tags.
"""
return [ind for ind, tag in enumerate(tags) if 'V' in tag] | python | def get_predicate_indices(tags: List[str]) -> List[int]:
"""
Return the word indices of a predicate in BIO tags.
"""
return [ind for ind, tag in enumerate(tags) if 'V' in tag] | [
"def",
"get_predicate_indices",
"(",
"tags",
":",
"List",
"[",
"str",
"]",
")",
"->",
"List",
"[",
"int",
"]",
":",
"return",
"[",
"ind",
"for",
"ind",
",",
"tag",
"in",
"enumerate",
"(",
"tags",
")",
"if",
"'V'",
"in",
"tag",
"]"
] | Return the word indices of a predicate in BIO tags. | [
"Return",
"the",
"word",
"indices",
"of",
"a",
"predicate",
"in",
"BIO",
"tags",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/predictors/open_information_extraction.py#L63-L67 |
23,063 | allenai/allennlp | allennlp/predictors/open_information_extraction.py | get_predicate_text | def get_predicate_text(sent_tokens: List[Token], tags: List[str]) -> str:
"""
Get the predicate in this prediction.
"""
return " ".join([sent_tokens[pred_id].text
for pred_id in get_predicate_indices(tags)]) | python | def get_predicate_text(sent_tokens: List[Token], tags: List[str]) -> str:
"""
Get the predicate in this prediction.
"""
return " ".join([sent_tokens[pred_id].text
for pred_id in get_predicate_indices(tags)]) | [
"def",
"get_predicate_text",
"(",
"sent_tokens",
":",
"List",
"[",
"Token",
"]",
",",
"tags",
":",
"List",
"[",
"str",
"]",
")",
"->",
"str",
":",
"return",
"\" \"",
".",
"join",
"(",
"[",
"sent_tokens",
"[",
"pred_id",
"]",
".",
"text",
"for",
"pred... | Get the predicate in this prediction. | [
"Get",
"the",
"predicate",
"in",
"this",
"prediction",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/predictors/open_information_extraction.py#L69-L74 |
23,064 | allenai/allennlp | allennlp/predictors/open_information_extraction.py | predicates_overlap | def predicates_overlap(tags1: List[str], tags2: List[str]) -> bool:
"""
Tests whether the predicate in BIO tags1 overlap
with those of tags2.
"""
# Get predicate word indices from both predictions
pred_ind1 = get_predicate_indices(tags1)
pred_ind2 = get_predicate_indices(tags2)
# Return... | python | def predicates_overlap(tags1: List[str], tags2: List[str]) -> bool:
"""
Tests whether the predicate in BIO tags1 overlap
with those of tags2.
"""
# Get predicate word indices from both predictions
pred_ind1 = get_predicate_indices(tags1)
pred_ind2 = get_predicate_indices(tags2)
# Return... | [
"def",
"predicates_overlap",
"(",
"tags1",
":",
"List",
"[",
"str",
"]",
",",
"tags2",
":",
"List",
"[",
"str",
"]",
")",
"->",
"bool",
":",
"# Get predicate word indices from both predictions",
"pred_ind1",
"=",
"get_predicate_indices",
"(",
"tags1",
")",
"pred... | Tests whether the predicate in BIO tags1 overlap
with those of tags2. | [
"Tests",
"whether",
"the",
"predicate",
"in",
"BIO",
"tags1",
"overlap",
"with",
"those",
"of",
"tags2",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/predictors/open_information_extraction.py#L76-L86 |
23,065 | allenai/allennlp | allennlp/predictors/open_information_extraction.py | get_coherent_next_tag | def get_coherent_next_tag(prev_label: str, cur_label: str) -> str:
"""
Generate a coherent tag, given previous tag and current label.
"""
if cur_label == "O":
# Don't need to add prefix to an "O" label
return "O"
if prev_label == cur_label:
return f"I-{cur_label}"
else:
... | python | def get_coherent_next_tag(prev_label: str, cur_label: str) -> str:
"""
Generate a coherent tag, given previous tag and current label.
"""
if cur_label == "O":
# Don't need to add prefix to an "O" label
return "O"
if prev_label == cur_label:
return f"I-{cur_label}"
else:
... | [
"def",
"get_coherent_next_tag",
"(",
"prev_label",
":",
"str",
",",
"cur_label",
":",
"str",
")",
"->",
"str",
":",
"if",
"cur_label",
"==",
"\"O\"",
":",
"# Don't need to add prefix to an \"O\" label",
"return",
"\"O\"",
"if",
"prev_label",
"==",
"cur_label",
":"... | Generate a coherent tag, given previous tag and current label. | [
"Generate",
"a",
"coherent",
"tag",
"given",
"previous",
"tag",
"and",
"current",
"label",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/predictors/open_information_extraction.py#L88-L99 |
23,066 | allenai/allennlp | allennlp/predictors/open_information_extraction.py | merge_overlapping_predictions | def merge_overlapping_predictions(tags1: List[str], tags2: List[str]) -> List[str]:
"""
Merge two predictions into one. Assumes the predicate in tags1 overlap with
the predicate of tags2.
"""
ret_sequence = []
prev_label = "O"
# Build a coherent sequence out of two
# spans which predica... | python | def merge_overlapping_predictions(tags1: List[str], tags2: List[str]) -> List[str]:
"""
Merge two predictions into one. Assumes the predicate in tags1 overlap with
the predicate of tags2.
"""
ret_sequence = []
prev_label = "O"
# Build a coherent sequence out of two
# spans which predica... | [
"def",
"merge_overlapping_predictions",
"(",
"tags1",
":",
"List",
"[",
"str",
"]",
",",
"tags2",
":",
"List",
"[",
"str",
"]",
")",
"->",
"List",
"[",
"str",
"]",
":",
"ret_sequence",
"=",
"[",
"]",
"prev_label",
"=",
"\"O\"",
"# Build a coherent sequence... | Merge two predictions into one. Assumes the predicate in tags1 overlap with
the predicate of tags2. | [
"Merge",
"two",
"predictions",
"into",
"one",
".",
"Assumes",
"the",
"predicate",
"in",
"tags1",
"overlap",
"with",
"the",
"predicate",
"of",
"tags2",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/predictors/open_information_extraction.py#L101-L130 |
23,067 | allenai/allennlp | allennlp/predictors/open_information_extraction.py | sanitize_label | def sanitize_label(label: str) -> str:
"""
Sanitize a BIO label - this deals with OIE
labels sometimes having some noise, as parentheses.
"""
if "-" in label:
prefix, suffix = label.split("-")
suffix = suffix.split("(")[-1]
return f"{prefix}-{suffix}"
else:
return... | python | def sanitize_label(label: str) -> str:
"""
Sanitize a BIO label - this deals with OIE
labels sometimes having some noise, as parentheses.
"""
if "-" in label:
prefix, suffix = label.split("-")
suffix = suffix.split("(")[-1]
return f"{prefix}-{suffix}"
else:
return... | [
"def",
"sanitize_label",
"(",
"label",
":",
"str",
")",
"->",
"str",
":",
"if",
"\"-\"",
"in",
"label",
":",
"prefix",
",",
"suffix",
"=",
"label",
".",
"split",
"(",
"\"-\"",
")",
"suffix",
"=",
"suffix",
".",
"split",
"(",
"\"(\"",
")",
"[",
"-",... | Sanitize a BIO label - this deals with OIE
labels sometimes having some noise, as parentheses. | [
"Sanitize",
"a",
"BIO",
"label",
"-",
"this",
"deals",
"with",
"OIE",
"labels",
"sometimes",
"having",
"some",
"noise",
"as",
"parentheses",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/predictors/open_information_extraction.py#L161-L171 |
23,068 | allenai/allennlp | allennlp/modules/elmo.py | _ElmoBiLm.create_cached_cnn_embeddings | def create_cached_cnn_embeddings(self, tokens: List[str]) -> None:
"""
Given a list of tokens, this method precomputes word representations
by running just the character convolutions and highway layers of elmo,
essentially creating uncontextual word vectors. On subsequent forward passes,... | python | def create_cached_cnn_embeddings(self, tokens: List[str]) -> None:
"""
Given a list of tokens, this method precomputes word representations
by running just the character convolutions and highway layers of elmo,
essentially creating uncontextual word vectors. On subsequent forward passes,... | [
"def",
"create_cached_cnn_embeddings",
"(",
"self",
",",
"tokens",
":",
"List",
"[",
"str",
"]",
")",
"->",
"None",
":",
"tokens",
"=",
"[",
"ELMoCharacterMapper",
".",
"bos_token",
",",
"ELMoCharacterMapper",
".",
"eos_token",
"]",
"+",
"tokens",
"timesteps",... | Given a list of tokens, this method precomputes word representations
by running just the character convolutions and highway layers of elmo,
essentially creating uncontextual word vectors. On subsequent forward passes,
the word ids are looked up from an embedding, rather than being computed on
... | [
"Given",
"a",
"list",
"of",
"tokens",
"this",
"method",
"precomputes",
"word",
"representations",
"by",
"running",
"just",
"the",
"character",
"convolutions",
"and",
"highway",
"layers",
"of",
"elmo",
"essentially",
"creating",
"uncontextual",
"word",
"vectors",
"... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/modules/elmo.py#L627-L685 |
23,069 | allenai/allennlp | allennlp/data/dataset_readers/reading_comprehension/util.py | normalize_text | def normalize_text(text: str) -> str:
"""
Performs a normalization that is very similar to that done by the normalization functions in
SQuAD and TriviaQA.
This involves splitting and rejoining the text, and could be a somewhat expensive operation.
"""
return ' '.join([token
... | python | def normalize_text(text: str) -> str:
"""
Performs a normalization that is very similar to that done by the normalization functions in
SQuAD and TriviaQA.
This involves splitting and rejoining the text, and could be a somewhat expensive operation.
"""
return ' '.join([token
... | [
"def",
"normalize_text",
"(",
"text",
":",
"str",
")",
"->",
"str",
":",
"return",
"' '",
".",
"join",
"(",
"[",
"token",
"for",
"token",
"in",
"text",
".",
"lower",
"(",
")",
".",
"strip",
"(",
"STRIPPED_CHARACTERS",
")",
".",
"split",
"(",
")",
"... | Performs a normalization that is very similar to that done by the normalization functions in
SQuAD and TriviaQA.
This involves splitting and rejoining the text, and could be a somewhat expensive operation. | [
"Performs",
"a",
"normalization",
"that",
"is",
"very",
"similar",
"to",
"that",
"done",
"by",
"the",
"normalization",
"functions",
"in",
"SQuAD",
"and",
"TriviaQA",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/data/dataset_readers/reading_comprehension/util.py#L24-L33 |
23,070 | 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 |
23,071 | 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 |
23,072 | 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 |
23,073 | 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 |
23,074 | 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 |
23,075 | 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 |
23,076 | 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 |
23,077 | 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 |
23,078 | 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 |
23,079 | 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 |
23,080 | 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 |
23,081 | 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 |
23,082 | 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 |
23,083 | 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 |
23,084 | 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 |
23,085 | 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 |
23,086 | 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 |
23,087 | 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 |
23,088 | 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 |
23,089 | 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 |
23,090 | 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 |
23,091 | 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 |
23,092 | 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 |
23,093 | 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 |
23,094 | 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 |
23,095 | 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 |
23,096 | 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 |
23,097 | 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 |
23,098 | 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 |
23,099 | 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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.