repo stringlengths 7 55 | path stringlengths 4 223 | func_name stringlengths 1 134 | original_string stringlengths 75 104k | language stringclasses 1
value | code stringlengths 75 104k | code_tokens listlengths 19 28.4k | docstring stringlengths 1 46.9k | docstring_tokens listlengths 1 1.97k | sha stringlengths 40 40 | url stringlengths 87 315 | partition stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
allenai/allennlp | allennlp/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 | train |
allenai/allennlp | allennlp/modules/augmented_lstm.py | AugmentedLstm.forward | def forward(self, # pylint: disable=arguments-differ
inputs: PackedSequence,
initial_state: Optional[Tuple[torch.Tensor, torch.Tensor]] = None):
"""
Parameters
----------
inputs : PackedSequence, required.
A tensor of shape (batch_size, num_ti... | python | def forward(self, # pylint: disable=arguments-differ
inputs: PackedSequence,
initial_state: Optional[Tuple[torch.Tensor, torch.Tensor]] = None):
"""
Parameters
----------
inputs : PackedSequence, required.
A tensor of shape (batch_size, num_ti... | [
"def",
"forward",
"(",
"self",
",",
"# pylint: disable=arguments-differ",
"inputs",
":",
"PackedSequence",
",",
"initial_state",
":",
"Optional",
"[",
"Tuple",
"[",
"torch",
".",
"Tensor",
",",
"torch",
".",
"Tensor",
"]",
"]",
"=",
"None",
")",
":",
"if",
... | Parameters
----------
inputs : PackedSequence, required.
A tensor of shape (batch_size, num_timesteps, input_size)
to apply the LSTM over.
initial_state : Tuple[torch.Tensor, torch.Tensor], optional, (default = None)
A tuple (state, memory) representing the i... | [
"Parameters",
"----------",
"inputs",
":",
"PackedSequence",
"required",
".",
"A",
"tensor",
"of",
"shape",
"(",
"batch_size",
"num_timesteps",
"input_size",
")",
"to",
"apply",
"the",
"LSTM",
"over",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/modules/augmented_lstm.py#L96-L212 | train |
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 | train |
allenai/allennlp | allennlp/training/metrics/conll_coref_scores.py | Scorer.b_cubed | def b_cubed(clusters, mention_to_gold):
"""
Averaged per-mention precision and recall.
<https://pdfs.semanticscholar.org/cfe3/c24695f1c14b78a5b8e95bcbd1c666140fd1.pdf>
"""
numerator, denominator = 0, 0
for cluster in clusters:
if len(cluster) == 1:
... | python | def b_cubed(clusters, mention_to_gold):
"""
Averaged per-mention precision and recall.
<https://pdfs.semanticscholar.org/cfe3/c24695f1c14b78a5b8e95bcbd1c666140fd1.pdf>
"""
numerator, denominator = 0, 0
for cluster in clusters:
if len(cluster) == 1:
... | [
"def",
"b_cubed",
"(",
"clusters",
",",
"mention_to_gold",
")",
":",
"numerator",
",",
"denominator",
"=",
"0",
",",
"0",
"for",
"cluster",
"in",
"clusters",
":",
"if",
"len",
"(",
"cluster",
")",
"==",
"1",
":",
"continue",
"gold_counts",
"=",
"Counter"... | Averaged per-mention precision and recall.
<https://pdfs.semanticscholar.org/cfe3/c24695f1c14b78a5b8e95bcbd1c666140fd1.pdf> | [
"Averaged",
"per",
"-",
"mention",
"precision",
"and",
"recall",
".",
"<https",
":",
"//",
"pdfs",
".",
"semanticscholar",
".",
"org",
"/",
"cfe3",
"/",
"c24695f1c14b78a5b8e95bcbd1c666140fd1",
".",
"pdf",
">"
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/training/metrics/conll_coref_scores.py#L166-L185 | train |
allenai/allennlp | allennlp/training/metrics/conll_coref_scores.py | Scorer.muc | def muc(clusters, mention_to_gold):
"""
Counts the mentions in each predicted cluster which need to be re-allocated in
order for each predicted cluster to be contained by the respective gold cluster.
<http://aclweb.org/anthology/M/M95/M95-1005.pdf>
"""
true_p, all_p = 0, ... | python | def muc(clusters, mention_to_gold):
"""
Counts the mentions in each predicted cluster which need to be re-allocated in
order for each predicted cluster to be contained by the respective gold cluster.
<http://aclweb.org/anthology/M/M95/M95-1005.pdf>
"""
true_p, all_p = 0, ... | [
"def",
"muc",
"(",
"clusters",
",",
"mention_to_gold",
")",
":",
"true_p",
",",
"all_p",
"=",
"0",
",",
"0",
"for",
"cluster",
"in",
"clusters",
":",
"all_p",
"+=",
"len",
"(",
"cluster",
")",
"-",
"1",
"true_p",
"+=",
"len",
"(",
"cluster",
")",
"... | Counts the mentions in each predicted cluster which need to be re-allocated in
order for each predicted cluster to be contained by the respective gold cluster.
<http://aclweb.org/anthology/M/M95/M95-1005.pdf> | [
"Counts",
"the",
"mentions",
"in",
"each",
"predicted",
"cluster",
"which",
"need",
"to",
"be",
"re",
"-",
"allocated",
"in",
"order",
"for",
"each",
"predicted",
"cluster",
"to",
"be",
"contained",
"by",
"the",
"respective",
"gold",
"cluster",
".",
"<http",... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/training/metrics/conll_coref_scores.py#L188-L205 | train |
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 | train |
allenai/allennlp | allennlp/training/metrics/conll_coref_scores.py | Scorer.ceafe | def ceafe(clusters, gold_clusters):
"""
Computes the Constrained EntityAlignment F-Measure (CEAF) for evaluating coreference.
Gold and predicted mentions are aligned into clusterings which maximise a metric - in
this case, the F measure between gold and predicted clusters.
<htt... | python | def ceafe(clusters, gold_clusters):
"""
Computes the Constrained EntityAlignment F-Measure (CEAF) for evaluating coreference.
Gold and predicted mentions are aligned into clusterings which maximise a metric - in
this case, the F measure between gold and predicted clusters.
<htt... | [
"def",
"ceafe",
"(",
"clusters",
",",
"gold_clusters",
")",
":",
"clusters",
"=",
"[",
"cluster",
"for",
"cluster",
"in",
"clusters",
"if",
"len",
"(",
"cluster",
")",
"!=",
"1",
"]",
"scores",
"=",
"np",
".",
"zeros",
"(",
"(",
"len",
"(",
"gold_clu... | Computes the Constrained EntityAlignment F-Measure (CEAF) for evaluating coreference.
Gold and predicted mentions are aligned into clusterings which maximise a metric - in
this case, the F measure between gold and predicted clusters.
<https://www.semanticscholar.org/paper/On-Coreference-Resolu... | [
"Computes",
"the",
"Constrained",
"EntityAlignment",
"F",
"-",
"Measure",
"(",
"CEAF",
")",
"for",
"evaluating",
"coreference",
".",
"Gold",
"and",
"predicted",
"mentions",
"are",
"aligned",
"into",
"clusterings",
"which",
"maximise",
"a",
"metric",
"-",
"in",
... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/training/metrics/conll_coref_scores.py#L217-L232 | train |
allenai/allennlp | allennlp/state_machines/states/grammar_statelet.py | GrammarStatelet.take_action | def take_action(self, production_rule: str) -> 'GrammarStatelet':
"""
Takes an action in the current grammar state, returning a new grammar state with whatever
updates are necessary. The production rule is assumed to be formatted as "LHS -> RHS".
This will update the non-terminal stack... | python | def take_action(self, production_rule: str) -> 'GrammarStatelet':
"""
Takes an action in the current grammar state, returning a new grammar state with whatever
updates are necessary. The production rule is assumed to be formatted as "LHS -> RHS".
This will update the non-terminal stack... | [
"def",
"take_action",
"(",
"self",
",",
"production_rule",
":",
"str",
")",
"->",
"'GrammarStatelet'",
":",
"left_side",
",",
"right_side",
"=",
"production_rule",
".",
"split",
"(",
"' -> '",
")",
"assert",
"self",
".",
"_nonterminal_stack",
"[",
"-",
"1",
... | Takes an action in the current grammar state, returning a new grammar state with whatever
updates are necessary. The production rule is assumed to be formatted as "LHS -> RHS".
This will update the non-terminal stack. Updating the non-terminal stack involves popping
the non-terminal that was ... | [
"Takes",
"an",
"action",
"in",
"the",
"current",
"grammar",
"state",
"returning",
"a",
"new",
"grammar",
"state",
"with",
"whatever",
"updates",
"are",
"necessary",
".",
"The",
"production",
"rule",
"is",
"assumed",
"to",
"be",
"formatted",
"as",
"LHS",
"-",... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/state_machines/states/grammar_statelet.py#L70-L104 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
allenai/allennlp | allennlp/data/dataset_readers/dataset_utils/span_utils.py | bio_tags_to_spans | def bio_tags_to_spans(tag_sequence: List[str],
classes_to_ignore: List[str] = None) -> List[TypedStringSpan]:
"""
Given a sequence corresponding to BIO tags, extracts spans.
Spans are inclusive and can be of zero length, representing a single word span.
Ill-formed spans are also in... | python | def bio_tags_to_spans(tag_sequence: List[str],
classes_to_ignore: List[str] = None) -> List[TypedStringSpan]:
"""
Given a sequence corresponding to BIO tags, extracts spans.
Spans are inclusive and can be of zero length, representing a single word span.
Ill-formed spans are also in... | [
"def",
"bio_tags_to_spans",
"(",
"tag_sequence",
":",
"List",
"[",
"str",
"]",
",",
"classes_to_ignore",
":",
"List",
"[",
"str",
"]",
"=",
"None",
")",
"->",
"List",
"[",
"TypedStringSpan",
"]",
":",
"classes_to_ignore",
"=",
"classes_to_ignore",
"or",
"[",... | Given a sequence corresponding to BIO tags, extracts spans.
Spans are inclusive and can be of zero length, representing a single word span.
Ill-formed spans are also included (i.e those which do not start with a "B-LABEL"),
as otherwise it is possible to get a perfect precision score whilst still predicting... | [
"Given",
"a",
"sequence",
"corresponding",
"to",
"BIO",
"tags",
"extracts",
"spans",
".",
"Spans",
"are",
"inclusive",
"and",
"can",
"be",
"of",
"zero",
"length",
"representing",
"a",
"single",
"word",
"span",
".",
"Ill",
"-",
"formed",
"spans",
"are",
"al... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/data/dataset_readers/dataset_utils/span_utils.py#L69-L139 | train |
allenai/allennlp | allennlp/data/dataset_readers/dataset_utils/span_utils.py | iob1_tags_to_spans | def iob1_tags_to_spans(tag_sequence: List[str],
classes_to_ignore: List[str] = None) -> List[TypedStringSpan]:
"""
Given a sequence corresponding to IOB1 tags, extracts spans.
Spans are inclusive and can be of zero length, representing a single word span.
Ill-formed spans are also... | python | def iob1_tags_to_spans(tag_sequence: List[str],
classes_to_ignore: List[str] = None) -> List[TypedStringSpan]:
"""
Given a sequence corresponding to IOB1 tags, extracts spans.
Spans are inclusive and can be of zero length, representing a single word span.
Ill-formed spans are also... | [
"def",
"iob1_tags_to_spans",
"(",
"tag_sequence",
":",
"List",
"[",
"str",
"]",
",",
"classes_to_ignore",
":",
"List",
"[",
"str",
"]",
"=",
"None",
")",
"->",
"List",
"[",
"TypedStringSpan",
"]",
":",
"classes_to_ignore",
"=",
"classes_to_ignore",
"or",
"["... | Given a sequence corresponding to IOB1 tags, extracts spans.
Spans are inclusive and can be of zero length, representing a single word span.
Ill-formed spans are also included (i.e., those where "B-LABEL" is not preceded
by "I-LABEL" or "B-LABEL").
Parameters
----------
tag_sequence : List[str]... | [
"Given",
"a",
"sequence",
"corresponding",
"to",
"IOB1",
"tags",
"extracts",
"spans",
".",
"Spans",
"are",
"inclusive",
"and",
"can",
"be",
"of",
"zero",
"length",
"representing",
"a",
"single",
"word",
"span",
".",
"Ill",
"-",
"formed",
"spans",
"are",
"a... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/data/dataset_readers/dataset_utils/span_utils.py#L142-L201 | train |
allenai/allennlp | allennlp/data/dataset_readers/dataset_utils/span_utils.py | bioul_tags_to_spans | def bioul_tags_to_spans(tag_sequence: List[str],
classes_to_ignore: List[str] = None) -> List[TypedStringSpan]:
"""
Given a sequence corresponding to BIOUL tags, extracts spans.
Spans are inclusive and can be of zero length, representing a single word span.
Ill-formed spans are n... | python | def bioul_tags_to_spans(tag_sequence: List[str],
classes_to_ignore: List[str] = None) -> List[TypedStringSpan]:
"""
Given a sequence corresponding to BIOUL tags, extracts spans.
Spans are inclusive and can be of zero length, representing a single word span.
Ill-formed spans are n... | [
"def",
"bioul_tags_to_spans",
"(",
"tag_sequence",
":",
"List",
"[",
"str",
"]",
",",
"classes_to_ignore",
":",
"List",
"[",
"str",
"]",
"=",
"None",
")",
"->",
"List",
"[",
"TypedStringSpan",
"]",
":",
"spans",
"=",
"[",
"]",
"classes_to_ignore",
"=",
"... | Given a sequence corresponding to BIOUL tags, extracts spans.
Spans are inclusive and can be of zero length, representing a single word span.
Ill-formed spans are not allowed and will raise ``InvalidTagSequence``.
This function works properly when the spans are unlabeled (i.e., your labels are
simply "B... | [
"Given",
"a",
"sequence",
"corresponding",
"to",
"BIOUL",
"tags",
"extracts",
"spans",
".",
"Spans",
"are",
"inclusive",
"and",
"can",
"be",
"of",
"zero",
"length",
"representing",
"a",
"single",
"word",
"span",
".",
"Ill",
"-",
"formed",
"spans",
"are",
"... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/data/dataset_readers/dataset_utils/span_utils.py#L217-L260 | train |
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 | train |
allenai/allennlp | allennlp/data/dataset_readers/dataset_utils/span_utils.py | bmes_tags_to_spans | def bmes_tags_to_spans(tag_sequence: List[str],
classes_to_ignore: List[str] = None) -> List[TypedStringSpan]:
"""
Given a sequence corresponding to BMES tags, extracts spans.
Spans are inclusive and can be of zero length, representing a single word span.
Ill-formed spans are also... | python | def bmes_tags_to_spans(tag_sequence: List[str],
classes_to_ignore: List[str] = None) -> List[TypedStringSpan]:
"""
Given a sequence corresponding to BMES tags, extracts spans.
Spans are inclusive and can be of zero length, representing a single word span.
Ill-formed spans are also... | [
"def",
"bmes_tags_to_spans",
"(",
"tag_sequence",
":",
"List",
"[",
"str",
"]",
",",
"classes_to_ignore",
":",
"List",
"[",
"str",
"]",
"=",
"None",
")",
"->",
"List",
"[",
"TypedStringSpan",
"]",
":",
"def",
"extract_bmes_tag_label",
"(",
"text",
")",
":"... | Given a sequence corresponding to BMES tags, extracts spans.
Spans are inclusive and can be of zero length, representing a single word span.
Ill-formed spans are also included (i.e those which do not start with a "B-LABEL"),
as otherwise it is possible to get a perfect precision score whilst still predictin... | [
"Given",
"a",
"sequence",
"corresponding",
"to",
"BMES",
"tags",
"extracts",
"spans",
".",
"Spans",
"are",
"inclusive",
"and",
"can",
"be",
"of",
"zero",
"length",
"representing",
"a",
"single",
"word",
"span",
".",
"Ill",
"-",
"formed",
"spans",
"are",
"a... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/data/dataset_readers/dataset_utils/span_utils.py#L376-L435 | train |
allenai/allennlp | allennlp/commands/dry_run.py | dry_run_from_args | def dry_run_from_args(args: argparse.Namespace):
"""
Just converts from an ``argparse.Namespace`` object to params.
"""
parameter_path = args.param_path
serialization_dir = args.serialization_dir
overrides = args.overrides
params = Params.from_file(parameter_path, overrides)
dry_run_fr... | python | def dry_run_from_args(args: argparse.Namespace):
"""
Just converts from an ``argparse.Namespace`` object to params.
"""
parameter_path = args.param_path
serialization_dir = args.serialization_dir
overrides = args.overrides
params = Params.from_file(parameter_path, overrides)
dry_run_fr... | [
"def",
"dry_run_from_args",
"(",
"args",
":",
"argparse",
".",
"Namespace",
")",
":",
"parameter_path",
"=",
"args",
".",
"param_path",
"serialization_dir",
"=",
"args",
".",
"serialization_dir",
"overrides",
"=",
"args",
".",
"overrides",
"params",
"=",
"Params... | Just converts from an ``argparse.Namespace`` object to params. | [
"Just",
"converts",
"from",
"an",
"argparse",
".",
"Namespace",
"object",
"to",
"params",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/commands/dry_run.py#L72-L82 | train |
allenai/allennlp | allennlp/state_machines/constrained_beam_search.py | ConstrainedBeamSearch.search | def search(self,
initial_state: State,
transition_function: TransitionFunction) -> Dict[int, List[State]]:
"""
Parameters
----------
initial_state : ``State``
The starting state of our search. This is assumed to be `batched`, and our beam search... | python | def search(self,
initial_state: State,
transition_function: TransitionFunction) -> Dict[int, List[State]]:
"""
Parameters
----------
initial_state : ``State``
The starting state of our search. This is assumed to be `batched`, and our beam search... | [
"def",
"search",
"(",
"self",
",",
"initial_state",
":",
"State",
",",
"transition_function",
":",
"TransitionFunction",
")",
"->",
"Dict",
"[",
"int",
",",
"List",
"[",
"State",
"]",
"]",
":",
"finished_states",
":",
"Dict",
"[",
"int",
",",
"List",
"["... | Parameters
----------
initial_state : ``State``
The starting state of our search. This is assumed to be `batched`, and our beam search
is batch-aware - we'll keep ``beam_size`` states around for each instance in the batch.
transition_function : ``TransitionFunction``
... | [
"Parameters",
"----------",
"initial_state",
":",
"State",
"The",
"starting",
"state",
"of",
"our",
"search",
".",
"This",
"is",
"assumed",
"to",
"be",
"batched",
"and",
"our",
"beam",
"search",
"is",
"batch",
"-",
"aware",
"-",
"we",
"ll",
"keep",
"beam_s... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/state_machines/constrained_beam_search.py#L60-L114 | train |
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 | train |
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 | train |
allenai/allennlp | allennlp/common/params.py | infer_and_cast | def infer_and_cast(value: Any):
"""
In some cases we'll be feeding params dicts to functions we don't own;
for example, PyTorch optimizers. In that case we can't use ``pop_int``
or similar to force casts (which means you can't specify ``int`` parameters
using environment variables). This function ta... | python | def infer_and_cast(value: Any):
"""
In some cases we'll be feeding params dicts to functions we don't own;
for example, PyTorch optimizers. In that case we can't use ``pop_int``
or similar to force casts (which means you can't specify ``int`` parameters
using environment variables). This function ta... | [
"def",
"infer_and_cast",
"(",
"value",
":",
"Any",
")",
":",
"# pylint: disable=too-many-return-statements",
"if",
"isinstance",
"(",
"value",
",",
"(",
"int",
",",
"float",
",",
"bool",
")",
")",
":",
"# Already one of our desired types, so leave as is.",
"return",
... | In some cases we'll be feeding params dicts to functions we don't own;
for example, PyTorch optimizers. In that case we can't use ``pop_int``
or similar to force casts (which means you can't specify ``int`` parameters
using environment variables). This function takes something that looks JSON-like
and r... | [
"In",
"some",
"cases",
"we",
"ll",
"be",
"feeding",
"params",
"dicts",
"to",
"functions",
"we",
"don",
"t",
"own",
";",
"for",
"example",
"PyTorch",
"optimizers",
".",
"In",
"that",
"case",
"we",
"can",
"t",
"use",
"pop_int",
"or",
"similar",
"to",
"fo... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/common/params.py#L35-L72 | train |
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 | train |
allenai/allennlp | allennlp/common/params.py | unflatten | def unflatten(flat_dict: Dict[str, Any]) -> Dict[str, Any]:
"""
Given a "flattened" dict with compound keys, e.g.
{"a.b": 0}
unflatten it:
{"a": {"b": 0}}
"""
unflat: Dict[str, Any] = {}
for compound_key, value in flat_dict.items():
curr_dict = unflat
parts = com... | python | def unflatten(flat_dict: Dict[str, Any]) -> Dict[str, Any]:
"""
Given a "flattened" dict with compound keys, e.g.
{"a.b": 0}
unflatten it:
{"a": {"b": 0}}
"""
unflat: Dict[str, Any] = {}
for compound_key, value in flat_dict.items():
curr_dict = unflat
parts = com... | [
"def",
"unflatten",
"(",
"flat_dict",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
")",
"->",
"Dict",
"[",
"str",
",",
"Any",
"]",
":",
"unflat",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
"=",
"{",
"}",
"for",
"compound_key",
",",
"value",
"in",
"... | Given a "flattened" dict with compound keys, e.g.
{"a.b": 0}
unflatten it:
{"a": {"b": 0}} | [
"Given",
"a",
"flattened",
"dict",
"with",
"compound",
"keys",
"e",
".",
"g",
".",
"{",
"a",
".",
"b",
":",
"0",
"}",
"unflatten",
"it",
":",
"{",
"a",
":",
"{",
"b",
":",
"0",
"}}"
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/common/params.py#L93-L119 | train |
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 | train |
allenai/allennlp | allennlp/common/params.py | pop_choice | def pop_choice(params: Dict[str, Any],
key: str,
choices: List[Any],
default_to_first_choice: bool = False,
history: str = "?.") -> Any:
"""
Performs the same function as :func:`Params.pop_choice`, but is required in order to deal with
places that ... | python | def pop_choice(params: Dict[str, Any],
key: str,
choices: List[Any],
default_to_first_choice: bool = False,
history: str = "?.") -> Any:
"""
Performs the same function as :func:`Params.pop_choice`, but is required in order to deal with
places that ... | [
"def",
"pop_choice",
"(",
"params",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
",",
"key",
":",
"str",
",",
"choices",
":",
"List",
"[",
"Any",
"]",
",",
"default_to_first_choice",
":",
"bool",
"=",
"False",
",",
"history",
":",
"str",
"=",
"\"?.\"",
... | Performs the same function as :func:`Params.pop_choice`, but is required in order to deal with
places that the Params object is not welcome, such as inside Keras layers. See the docstring
of that method for more detail on how this function works.
This method adds a ``history`` parameter, in the off-chance... | [
"Performs",
"the",
"same",
"function",
"as",
":",
"func",
":",
"Params",
".",
"pop_choice",
"but",
"is",
"required",
"in",
"order",
"to",
"deal",
"with",
"places",
"that",
"the",
"Params",
"object",
"is",
"not",
"welcome",
"such",
"as",
"inside",
"Keras",
... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/common/params.py#L518-L534 | train |
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 | train |
allenai/allennlp | allennlp/common/params.py | Params.pop | def pop(self, key: str, default: Any = DEFAULT) -> Any:
"""
Performs the functionality associated with dict.pop(key), along with checking for
returned dictionaries, replacing them with Param objects with an updated history.
If ``key`` is not present in the dictionary, and no default was... | python | def pop(self, key: str, default: Any = DEFAULT) -> Any:
"""
Performs the functionality associated with dict.pop(key), along with checking for
returned dictionaries, replacing them with Param objects with an updated history.
If ``key`` is not present in the dictionary, and no default was... | [
"def",
"pop",
"(",
"self",
",",
"key",
":",
"str",
",",
"default",
":",
"Any",
"=",
"DEFAULT",
")",
"->",
"Any",
":",
"if",
"default",
"is",
"self",
".",
"DEFAULT",
":",
"try",
":",
"value",
"=",
"self",
".",
"params",
".",
"pop",
"(",
"key",
"... | Performs the functionality associated with dict.pop(key), along with checking for
returned dictionaries, replacing them with Param objects with an updated history.
If ``key`` is not present in the dictionary, and no default was specified, we raise a
``ConfigurationError``, instead of the typica... | [
"Performs",
"the",
"functionality",
"associated",
"with",
"dict",
".",
"pop",
"(",
"key",
")",
"along",
"with",
"checking",
"for",
"returned",
"dictionaries",
"replacing",
"them",
"with",
"Param",
"objects",
"with",
"an",
"updated",
"history",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/common/params.py#L235-L252 | train |
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 | train |
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 | train |
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 | train |
allenai/allennlp | allennlp/common/params.py | Params.get | def get(self, key: str, default: Any = DEFAULT):
"""
Performs the functionality associated with dict.get(key) but also checks for returned
dicts and returns a Params object in their place with an updated history.
"""
if default is self.DEFAULT:
try:
va... | python | def get(self, key: str, default: Any = DEFAULT):
"""
Performs the functionality associated with dict.get(key) but also checks for returned
dicts and returns a Params object in their place with an updated history.
"""
if default is self.DEFAULT:
try:
va... | [
"def",
"get",
"(",
"self",
",",
"key",
":",
"str",
",",
"default",
":",
"Any",
"=",
"DEFAULT",
")",
":",
"if",
"default",
"is",
"self",
".",
"DEFAULT",
":",
"try",
":",
"value",
"=",
"self",
".",
"params",
".",
"get",
"(",
"key",
")",
"except",
... | Performs the functionality associated with dict.get(key) but also checks for returned
dicts and returns a Params object in their place with an updated history. | [
"Performs",
"the",
"functionality",
"associated",
"with",
"dict",
".",
"get",
"(",
"key",
")",
"but",
"also",
"checks",
"for",
"returned",
"dicts",
"and",
"returns",
"a",
"Params",
"object",
"in",
"their",
"place",
"with",
"an",
"updated",
"history",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/common/params.py#L291-L303 | train |
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 | train |
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 | train |
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 | train |
allenai/allennlp | allennlp/common/params.py | Params.assert_empty | def assert_empty(self, class_name: str):
"""
Raises a ``ConfigurationError`` if ``self.params`` is not empty. We take ``class_name`` as
an argument so that the error message gives some idea of where an error happened, if there
was one. ``class_name`` should be the name of the `calling`... | python | def assert_empty(self, class_name: str):
"""
Raises a ``ConfigurationError`` if ``self.params`` is not empty. We take ``class_name`` as
an argument so that the error message gives some idea of where an error happened, if there
was one. ``class_name`` should be the name of the `calling`... | [
"def",
"assert_empty",
"(",
"self",
",",
"class_name",
":",
"str",
")",
":",
"if",
"self",
".",
"params",
":",
"raise",
"ConfigurationError",
"(",
"\"Extra parameters passed to {}: {}\"",
".",
"format",
"(",
"class_name",
",",
"self",
".",
"params",
")",
")"
] | Raises a ``ConfigurationError`` if ``self.params`` is not empty. We take ``class_name`` as
an argument so that the error message gives some idea of where an error happened, if there
was one. ``class_name`` should be the name of the `calling` class, the one that got extra
parameters (if there a... | [
"Raises",
"a",
"ConfigurationError",
"if",
"self",
".",
"params",
"is",
"not",
"empty",
".",
"We",
"take",
"class_name",
"as",
"an",
"argument",
"so",
"that",
"the",
"error",
"message",
"gives",
"some",
"idea",
"of",
"where",
"an",
"error",
"happened",
"if... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/common/params.py#L396-L404 | train |
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 | train |
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 | train |
allenai/allennlp | allennlp/common/params.py | Params.get_hash | def get_hash(self) -> str:
"""
Returns a hash code representing the current state of this ``Params`` object. We don't
want to implement ``__hash__`` because that has deeper python implications (and this is a
mutable object), but this will give you a representation of the current state.
... | python | def get_hash(self) -> str:
"""
Returns a hash code representing the current state of this ``Params`` object. We don't
want to implement ``__hash__`` because that has deeper python implications (and this is a
mutable object), but this will give you a representation of the current state.
... | [
"def",
"get_hash",
"(",
"self",
")",
"->",
"str",
":",
"return",
"str",
"(",
"hash",
"(",
"json",
".",
"dumps",
"(",
"self",
".",
"params",
",",
"sort_keys",
"=",
"True",
")",
")",
")"
] | Returns a hash code representing the current state of this ``Params`` object. We don't
want to implement ``__hash__`` because that has deeper python implications (and this is a
mutable object), but this will give you a representation of the current state. | [
"Returns",
"a",
"hash",
"code",
"representing",
"the",
"current",
"state",
"of",
"this",
"Params",
"object",
".",
"We",
"don",
"t",
"want",
"to",
"implement",
"__hash__",
"because",
"that",
"has",
"deeper",
"python",
"implications",
"(",
"and",
"this",
"is",... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/common/params.py#L509-L515 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
allenai/allennlp | allennlp/commands/find_learning_rate.py | search_learning_rate | def search_learning_rate(trainer: Trainer,
start_lr: float = 1e-5,
end_lr: float = 10,
num_batches: int = 100,
linear_steps: bool = False,
stopping_factor: float = None) -> Tuple[List[float], Lis... | python | def search_learning_rate(trainer: Trainer,
start_lr: float = 1e-5,
end_lr: float = 10,
num_batches: int = 100,
linear_steps: bool = False,
stopping_factor: float = None) -> Tuple[List[float], Lis... | [
"def",
"search_learning_rate",
"(",
"trainer",
":",
"Trainer",
",",
"start_lr",
":",
"float",
"=",
"1e-5",
",",
"end_lr",
":",
"float",
"=",
"10",
",",
"num_batches",
":",
"int",
"=",
"100",
",",
"linear_steps",
":",
"bool",
"=",
"False",
",",
"stopping_... | Runs training loop on the model using :class:`~allennlp.training.trainer.Trainer`
increasing learning rate from ``start_lr`` to ``end_lr`` recording the losses.
Parameters
----------
trainer: :class:`~allennlp.training.trainer.Trainer`
start_lr: ``float``
The learning rate to start the searc... | [
"Runs",
"training",
"loop",
"on",
"the",
"model",
"using",
":",
"class",
":",
"~allennlp",
".",
"training",
".",
"trainer",
".",
"Trainer",
"increasing",
"learning",
"rate",
"from",
"start_lr",
"to",
"end_lr",
"recording",
"the",
"losses",
".",
"Parameters",
... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/commands/find_learning_rate.py#L231-L312 | train |
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 | train |
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 | train |
allenai/allennlp | allennlp/semparse/domain_languages/domain_language.py | predicate_with_side_args | def predicate_with_side_args(side_arguments: List[str]) -> Callable: # pylint: disable=invalid-name
"""
Like :func:`predicate`, but used when some of the arguments to the function are meant to be
provided by the decoder or other state, instead of from the language. For example, you might
want to have ... | python | def predicate_with_side_args(side_arguments: List[str]) -> Callable: # pylint: disable=invalid-name
"""
Like :func:`predicate`, but used when some of the arguments to the function are meant to be
provided by the decoder or other state, instead of from the language. For example, you might
want to have ... | [
"def",
"predicate_with_side_args",
"(",
"side_arguments",
":",
"List",
"[",
"str",
"]",
")",
"->",
"Callable",
":",
"# pylint: disable=invalid-name",
"def",
"decorator",
"(",
"function",
":",
"Callable",
")",
"->",
"Callable",
":",
"setattr",
"(",
"function",
",... | Like :func:`predicate`, but used when some of the arguments to the function are meant to be
provided by the decoder or other state, instead of from the language. For example, you might
want to have a function use the decoder's attention over some input text when a terminal was
predicted. That attention wo... | [
"Like",
":",
"func",
":",
"predicate",
"but",
"used",
"when",
"some",
"of",
"the",
"arguments",
"to",
"the",
"function",
"are",
"meant",
"to",
"be",
"provided",
"by",
"the",
"decoder",
"or",
"other",
"state",
"instead",
"of",
"from",
"the",
"language",
"... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/domain_languages/domain_language.py#L182-L198 | train |
allenai/allennlp | allennlp/semparse/domain_languages/domain_language.py | nltk_tree_to_logical_form | def nltk_tree_to_logical_form(tree: Tree) -> str:
"""
Given an ``nltk.Tree`` representing the syntax tree that generates a logical form, this method
produces the actual (lisp-like) logical form, with all of the non-terminal symbols converted
into the correct number of parentheses.
This is used in t... | python | def nltk_tree_to_logical_form(tree: Tree) -> str:
"""
Given an ``nltk.Tree`` representing the syntax tree that generates a logical form, this method
produces the actual (lisp-like) logical form, with all of the non-terminal symbols converted
into the correct number of parentheses.
This is used in t... | [
"def",
"nltk_tree_to_logical_form",
"(",
"tree",
":",
"Tree",
")",
"->",
"str",
":",
"# nltk.Tree actually inherits from `list`, so you use `len()` to get the number of children.",
"# We're going to be explicit about checking length, instead of using `if tree:`, just to avoid",
"# any funny ... | Given an ``nltk.Tree`` representing the syntax tree that generates a logical form, this method
produces the actual (lisp-like) logical form, with all of the non-terminal symbols converted
into the correct number of parentheses.
This is used in the logic that converts action sequences back into logical form... | [
"Given",
"an",
"nltk",
".",
"Tree",
"representing",
"the",
"syntax",
"tree",
"that",
"generates",
"a",
"logical",
"form",
"this",
"method",
"produces",
"the",
"actual",
"(",
"lisp",
"-",
"like",
")",
"logical",
"form",
"with",
"all",
"of",
"the",
"non",
... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/domain_languages/domain_language.py#L201-L218 | train |
allenai/allennlp | allennlp/semparse/domain_languages/domain_language.py | PredicateType.get_type | def get_type(type_: Type) -> 'PredicateType':
"""
Converts a python ``Type`` (as you might get from a type annotation) into a
``PredicateType``. If the ``Type`` is callable, this will return a ``FunctionType``;
otherwise, it will return a ``BasicType``.
``BasicTypes`` have a si... | python | def get_type(type_: Type) -> 'PredicateType':
"""
Converts a python ``Type`` (as you might get from a type annotation) into a
``PredicateType``. If the ``Type`` is callable, this will return a ``FunctionType``;
otherwise, it will return a ``BasicType``.
``BasicTypes`` have a si... | [
"def",
"get_type",
"(",
"type_",
":",
"Type",
")",
"->",
"'PredicateType'",
":",
"if",
"is_callable",
"(",
"type_",
")",
":",
"callable_args",
"=",
"type_",
".",
"__args__",
"argument_types",
"=",
"[",
"PredicateType",
".",
"get_type",
"(",
"t",
")",
"for"... | Converts a python ``Type`` (as you might get from a type annotation) into a
``PredicateType``. If the ``Type`` is callable, this will return a ``FunctionType``;
otherwise, it will return a ``BasicType``.
``BasicTypes`` have a single ``name`` parameter - we typically get this from
``typ... | [
"Converts",
"a",
"python",
"Type",
"(",
"as",
"you",
"might",
"get",
"from",
"a",
"type",
"annotation",
")",
"into",
"a",
"PredicateType",
".",
"If",
"the",
"Type",
"is",
"callable",
"this",
"will",
"return",
"a",
"FunctionType",
";",
"otherwise",
"it",
... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/domain_languages/domain_language.py#L60-L82 | train |
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 | train |
allenai/allennlp | allennlp/semparse/domain_languages/domain_language.py | DomainLanguage.execute_action_sequence | def execute_action_sequence(self, action_sequence: List[str], side_arguments: List[Dict] = None):
"""
Executes the program defined by an action sequence directly, without needing the overhead
of translating to a logical form first. For any given program, :func:`execute` and this
functio... | python | def execute_action_sequence(self, action_sequence: List[str], side_arguments: List[Dict] = None):
"""
Executes the program defined by an action sequence directly, without needing the overhead
of translating to a logical form first. For any given program, :func:`execute` and this
functio... | [
"def",
"execute_action_sequence",
"(",
"self",
",",
"action_sequence",
":",
"List",
"[",
"str",
"]",
",",
"side_arguments",
":",
"List",
"[",
"Dict",
"]",
"=",
"None",
")",
":",
"# We'll strip off the first action, because it doesn't matter for execution.",
"first_actio... | Executes the program defined by an action sequence directly, without needing the overhead
of translating to a logical form first. For any given program, :func:`execute` and this
function are equivalent, they just take different representations of the program, so you
can use whichever is more ef... | [
"Executes",
"the",
"program",
"defined",
"by",
"an",
"action",
"sequence",
"directly",
"without",
"needing",
"the",
"overhead",
"of",
"translating",
"to",
"a",
"logical",
"form",
"first",
".",
"For",
"any",
"given",
"program",
":",
"func",
":",
"execute",
"a... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/domain_languages/domain_language.py#L315-L333 | train |
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 | train |
allenai/allennlp | allennlp/semparse/domain_languages/domain_language.py | DomainLanguage.all_possible_productions | def all_possible_productions(self) -> List[str]:
"""
Returns a sorted list of all production rules in the grammar induced by
:func:`get_nonterminal_productions`.
"""
all_actions = set()
for action_set in self.get_nonterminal_productions().values():
all_actions... | python | def all_possible_productions(self) -> List[str]:
"""
Returns a sorted list of all production rules in the grammar induced by
:func:`get_nonterminal_productions`.
"""
all_actions = set()
for action_set in self.get_nonterminal_productions().values():
all_actions... | [
"def",
"all_possible_productions",
"(",
"self",
")",
"->",
"List",
"[",
"str",
"]",
":",
"all_actions",
"=",
"set",
"(",
")",
"for",
"action_set",
"in",
"self",
".",
"get_nonterminal_productions",
"(",
")",
".",
"values",
"(",
")",
":",
"all_actions",
".",... | Returns a sorted list of all production rules in the grammar induced by
:func:`get_nonterminal_productions`. | [
"Returns",
"a",
"sorted",
"list",
"of",
"all",
"production",
"rules",
"in",
"the",
"grammar",
"induced",
"by",
":",
"func",
":",
"get_nonterminal_productions",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/domain_languages/domain_language.py#L369-L377 | train |
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 | train |
allenai/allennlp | allennlp/semparse/domain_languages/domain_language.py | DomainLanguage.action_sequence_to_logical_form | def action_sequence_to_logical_form(self, action_sequence: List[str]) -> str:
"""
Takes an action sequence as produced by :func:`logical_form_to_action_sequence`, which is a
linearization of an abstract syntax tree, and reconstructs the logical form defined by that
abstract syntax tree.
... | python | def action_sequence_to_logical_form(self, action_sequence: List[str]) -> str:
"""
Takes an action sequence as produced by :func:`logical_form_to_action_sequence`, which is a
linearization of an abstract syntax tree, and reconstructs the logical form defined by that
abstract syntax tree.
... | [
"def",
"action_sequence_to_logical_form",
"(",
"self",
",",
"action_sequence",
":",
"List",
"[",
"str",
"]",
")",
"->",
"str",
":",
"# Basic outline: we assume that the bracketing that we get in the RHS of each action is the",
"# correct bracketing for reconstructing the logical form... | Takes an action sequence as produced by :func:`logical_form_to_action_sequence`, which is a
linearization of an abstract syntax tree, and reconstructs the logical form defined by that
abstract syntax tree. | [
"Takes",
"an",
"action",
"sequence",
"as",
"produced",
"by",
":",
"func",
":",
"logical_form_to_action_sequence",
"which",
"is",
"a",
"linearization",
"of",
"an",
"abstract",
"syntax",
"tree",
"and",
"reconstructs",
"the",
"logical",
"form",
"defined",
"by",
"th... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/domain_languages/domain_language.py#L411-L436 | train |
allenai/allennlp | allennlp/semparse/domain_languages/domain_language.py | DomainLanguage.add_predicate | def add_predicate(self, name: str, function: Callable, side_arguments: List[str] = None):
"""
Adds a predicate to this domain language. Typically you do this with the ``@predicate``
decorator on the methods in your class. But, if you need to for whatever reason, you can
also call this ... | python | def add_predicate(self, name: str, function: Callable, side_arguments: List[str] = None):
"""
Adds a predicate to this domain language. Typically you do this with the ``@predicate``
decorator on the methods in your class. But, if you need to for whatever reason, you can
also call this ... | [
"def",
"add_predicate",
"(",
"self",
",",
"name",
":",
"str",
",",
"function",
":",
"Callable",
",",
"side_arguments",
":",
"List",
"[",
"str",
"]",
"=",
"None",
")",
":",
"side_arguments",
"=",
"side_arguments",
"or",
"[",
"]",
"signature",
"=",
"inspec... | Adds a predicate to this domain language. Typically you do this with the ``@predicate``
decorator on the methods in your class. But, if you need to for whatever reason, you can
also call this function yourself with a (type-annotated) function to add it to your
language.
Parameters
... | [
"Adds",
"a",
"predicate",
"to",
"this",
"domain",
"language",
".",
"Typically",
"you",
"do",
"this",
"with",
"the",
"@predicate",
"decorator",
"on",
"the",
"methods",
"in",
"your",
"class",
".",
"But",
"if",
"you",
"need",
"to",
"for",
"whatever",
"reason"... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/domain_languages/domain_language.py#L438-L470 | train |
allenai/allennlp | allennlp/semparse/domain_languages/domain_language.py | DomainLanguage.add_constant | def add_constant(self, name: str, value: Any, type_: Type = None):
"""
Adds a constant to this domain language. You would typically just pass in a list of
constants to the ``super().__init__()`` call in your constructor, but you can also call
this method to add constants if it is more c... | python | def add_constant(self, name: str, value: Any, type_: Type = None):
"""
Adds a constant to this domain language. You would typically just pass in a list of
constants to the ``super().__init__()`` call in your constructor, but you can also call
this method to add constants if it is more c... | [
"def",
"add_constant",
"(",
"self",
",",
"name",
":",
"str",
",",
"value",
":",
"Any",
",",
"type_",
":",
"Type",
"=",
"None",
")",
":",
"value_type",
"=",
"type_",
"if",
"type_",
"else",
"type",
"(",
"value",
")",
"constant_type",
"=",
"PredicateType"... | Adds a constant to this domain language. You would typically just pass in a list of
constants to the ``super().__init__()`` call in your constructor, but you can also call
this method to add constants if it is more convenient.
Because we construct a grammar over this language for you, in order... | [
"Adds",
"a",
"constant",
"to",
"this",
"domain",
"language",
".",
"You",
"would",
"typically",
"just",
"pass",
"in",
"a",
"list",
"of",
"constants",
"to",
"the",
"super",
"()",
".",
"__init__",
"()",
"call",
"in",
"your",
"constructor",
"but",
"you",
"ca... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/domain_languages/domain_language.py#L472-L486 | train |
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 | train |
allenai/allennlp | allennlp/semparse/domain_languages/domain_language.py | DomainLanguage._execute_expression | def _execute_expression(self, expression: Any):
"""
This does the bulk of the work of executing a logical form, recursively executing a single
expression. Basically, if the expression is a function we know about, we evaluate its
arguments then call the function. If it's a list, we eval... | python | def _execute_expression(self, expression: Any):
"""
This does the bulk of the work of executing a logical form, recursively executing a single
expression. Basically, if the expression is a function we know about, we evaluate its
arguments then call the function. If it's a list, we eval... | [
"def",
"_execute_expression",
"(",
"self",
",",
"expression",
":",
"Any",
")",
":",
"# pylint: disable=too-many-return-statements",
"if",
"isinstance",
"(",
"expression",
",",
"list",
")",
":",
"if",
"isinstance",
"(",
"expression",
"[",
"0",
"]",
",",
"list",
... | This does the bulk of the work of executing a logical form, recursively executing a single
expression. Basically, if the expression is a function we know about, we evaluate its
arguments then call the function. If it's a list, we evaluate all elements of the list.
If it's a constant (or a zero... | [
"This",
"does",
"the",
"bulk",
"of",
"the",
"work",
"of",
"executing",
"a",
"logical",
"form",
"recursively",
"executing",
"a",
"single",
"expression",
".",
"Basically",
"if",
"the",
"expression",
"is",
"a",
"function",
"we",
"know",
"about",
"we",
"evaluate... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/domain_languages/domain_language.py#L496-L539 | train |
allenai/allennlp | allennlp/semparse/domain_languages/domain_language.py | DomainLanguage._execute_sequence | def _execute_sequence(self,
action_sequence: List[str],
side_arguments: List[Dict]) -> Tuple[Any, List[str], List[Dict]]:
"""
This does the bulk of the work of :func:`execute_action_sequence`, recursively executing
the functions it finds and tr... | python | def _execute_sequence(self,
action_sequence: List[str],
side_arguments: List[Dict]) -> Tuple[Any, List[str], List[Dict]]:
"""
This does the bulk of the work of :func:`execute_action_sequence`, recursively executing
the functions it finds and tr... | [
"def",
"_execute_sequence",
"(",
"self",
",",
"action_sequence",
":",
"List",
"[",
"str",
"]",
",",
"side_arguments",
":",
"List",
"[",
"Dict",
"]",
")",
"->",
"Tuple",
"[",
"Any",
",",
"List",
"[",
"str",
"]",
",",
"List",
"[",
"Dict",
"]",
"]",
"... | This does the bulk of the work of :func:`execute_action_sequence`, recursively executing
the functions it finds and trimming actions off of the action sequence. The return value
is a tuple of (execution, remaining_actions), where the second value is necessary to handle
the recursion. | [
"This",
"does",
"the",
"bulk",
"of",
"the",
"work",
"of",
":",
"func",
":",
"execute_action_sequence",
"recursively",
"executing",
"the",
"functions",
"it",
"finds",
"and",
"trimming",
"actions",
"off",
"of",
"the",
"action",
"sequence",
".",
"The",
"return",
... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/domain_languages/domain_language.py#L541-L607 | train |
allenai/allennlp | allennlp/semparse/domain_languages/domain_language.py | DomainLanguage._get_transitions | def _get_transitions(self, expression: Any, expected_type: PredicateType) -> Tuple[List[str], PredicateType]:
"""
This is used when converting a logical form into an action sequence. This piece
recursively translates a lisp expression into an action sequence, making sure we match the
ex... | python | def _get_transitions(self, expression: Any, expected_type: PredicateType) -> Tuple[List[str], PredicateType]:
"""
This is used when converting a logical form into an action sequence. This piece
recursively translates a lisp expression into an action sequence, making sure we match the
ex... | [
"def",
"_get_transitions",
"(",
"self",
",",
"expression",
":",
"Any",
",",
"expected_type",
":",
"PredicateType",
")",
"->",
"Tuple",
"[",
"List",
"[",
"str",
"]",
",",
"PredicateType",
"]",
":",
"if",
"isinstance",
"(",
"expression",
",",
"(",
"list",
... | This is used when converting a logical form into an action sequence. This piece
recursively translates a lisp expression into an action sequence, making sure we match the
expected type (or using the expected type to get the right type for constant expressions). | [
"This",
"is",
"used",
"when",
"converting",
"a",
"logical",
"form",
"into",
"an",
"action",
"sequence",
".",
"This",
"piece",
"recursively",
"translates",
"a",
"lisp",
"expression",
"into",
"an",
"action",
"sequence",
"making",
"sure",
"we",
"match",
"the",
... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/domain_languages/domain_language.py#L609-L645 | train |
allenai/allennlp | allennlp/semparse/domain_languages/domain_language.py | DomainLanguage._get_function_transitions | def _get_function_transitions(self,
expression: Union[str, List],
expected_type: PredicateType) -> Tuple[List[str],
PredicateType,
... | python | def _get_function_transitions(self,
expression: Union[str, List],
expected_type: PredicateType) -> Tuple[List[str],
PredicateType,
... | [
"def",
"_get_function_transitions",
"(",
"self",
",",
"expression",
":",
"Union",
"[",
"str",
",",
"List",
"]",
",",
"expected_type",
":",
"PredicateType",
")",
"->",
"Tuple",
"[",
"List",
"[",
"str",
"]",
",",
"PredicateType",
",",
"List",
"[",
"Predicate... | A helper method for ``_get_transitions``. This gets the transitions for the predicate
itself in a function call. If we only had simple functions (e.g., "(add 2 3)"), this would
be pretty straightforward and we wouldn't need a separate method to handle it. We split it
out into its own method b... | [
"A",
"helper",
"method",
"for",
"_get_transitions",
".",
"This",
"gets",
"the",
"transitions",
"for",
"the",
"predicate",
"itself",
"in",
"a",
"function",
"call",
".",
"If",
"we",
"only",
"had",
"simple",
"functions",
"(",
"e",
".",
"g",
".",
"(",
"add",... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/domain_languages/domain_language.py#L647-L691 | train |
allenai/allennlp | allennlp/semparse/domain_languages/domain_language.py | DomainLanguage._construct_node_from_actions | def _construct_node_from_actions(self,
current_node: Tree,
remaining_actions: List[List[str]]) -> List[List[str]]:
"""
Given a current node in the logical form tree, and a list of actions in an action sequence,
this method... | python | def _construct_node_from_actions(self,
current_node: Tree,
remaining_actions: List[List[str]]) -> List[List[str]]:
"""
Given a current node in the logical form tree, and a list of actions in an action sequence,
this method... | [
"def",
"_construct_node_from_actions",
"(",
"self",
",",
"current_node",
":",
"Tree",
",",
"remaining_actions",
":",
"List",
"[",
"List",
"[",
"str",
"]",
"]",
")",
"->",
"List",
"[",
"List",
"[",
"str",
"]",
"]",
":",
"if",
"not",
"remaining_actions",
"... | Given a current node in the logical form tree, and a list of actions in an action sequence,
this method fills in the children of the current node from the action sequence, then
returns whatever actions are left.
For example, we could get a node with type ``c``, and an action sequence that begin... | [
"Given",
"a",
"current",
"node",
"in",
"the",
"logical",
"form",
"tree",
"and",
"a",
"list",
"of",
"actions",
"in",
"an",
"action",
"sequence",
"this",
"method",
"fills",
"in",
"the",
"children",
"of",
"the",
"current",
"node",
"from",
"the",
"action",
"... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/domain_languages/domain_language.py#L693-L733 | train |
allenai/allennlp | allennlp/modules/sampled_softmax_loss.py | _choice | def _choice(num_words: int, num_samples: int) -> Tuple[np.ndarray, int]:
"""
Chooses ``num_samples`` samples without replacement from [0, ..., num_words).
Returns a tuple (samples, num_tries).
"""
num_tries = 0
num_chosen = 0
def get_buffer() -> np.ndarray:
log_samples = np.random.r... | python | def _choice(num_words: int, num_samples: int) -> Tuple[np.ndarray, int]:
"""
Chooses ``num_samples`` samples without replacement from [0, ..., num_words).
Returns a tuple (samples, num_tries).
"""
num_tries = 0
num_chosen = 0
def get_buffer() -> np.ndarray:
log_samples = np.random.r... | [
"def",
"_choice",
"(",
"num_words",
":",
"int",
",",
"num_samples",
":",
"int",
")",
"->",
"Tuple",
"[",
"np",
".",
"ndarray",
",",
"int",
"]",
":",
"num_tries",
"=",
"0",
"num_chosen",
"=",
"0",
"def",
"get_buffer",
"(",
")",
"->",
"np",
".",
"nda... | Chooses ``num_samples`` samples without replacement from [0, ..., num_words).
Returns a tuple (samples, num_tries). | [
"Chooses",
"num_samples",
"samples",
"without",
"replacement",
"from",
"[",
"0",
"...",
"num_words",
")",
".",
"Returns",
"a",
"tuple",
"(",
"samples",
"num_tries",
")",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/modules/sampled_softmax_loss.py#L11-L42 | train |
allenai/allennlp | allennlp/data/token_indexers/token_indexer.py | TokenIndexer.tokens_to_indices | def tokens_to_indices(self,
tokens: List[Token],
vocabulary: Vocabulary,
index_name: str) -> Dict[str, List[TokenType]]:
"""
Takes a list of tokens and converts them to one or more sets of indices.
This could be just a... | python | def tokens_to_indices(self,
tokens: List[Token],
vocabulary: Vocabulary,
index_name: str) -> Dict[str, List[TokenType]]:
"""
Takes a list of tokens and converts them to one or more sets of indices.
This could be just a... | [
"def",
"tokens_to_indices",
"(",
"self",
",",
"tokens",
":",
"List",
"[",
"Token",
"]",
",",
"vocabulary",
":",
"Vocabulary",
",",
"index_name",
":",
"str",
")",
"->",
"Dict",
"[",
"str",
",",
"List",
"[",
"TokenType",
"]",
"]",
":",
"raise",
"NotImple... | Takes a list of tokens and converts them to one or more sets of indices.
This could be just an ID for each token from the vocabulary.
Or it could split each token into characters and return one ID per character.
Or (for instance, in the case of byte-pair encoding) there might not be a clean
... | [
"Takes",
"a",
"list",
"of",
"tokens",
"and",
"converts",
"them",
"to",
"one",
"or",
"more",
"sets",
"of",
"indices",
".",
"This",
"could",
"be",
"just",
"an",
"ID",
"for",
"each",
"token",
"from",
"the",
"vocabulary",
".",
"Or",
"it",
"could",
"split",... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/data/token_indexers/token_indexer.py#L33-L44 | train |
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 | train |
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 | train |
allenai/allennlp | allennlp/predictors/open_information_extraction.py | join_mwp | def join_mwp(tags: List[str]) -> List[str]:
"""
Join multi-word predicates to a single
predicate ('V') token.
"""
ret = []
verb_flag = False
for tag in tags:
if "V" in tag:
# Create a continuous 'V' BIO span
prefix, _ = tag.split("-")
if verb_flag:... | python | def join_mwp(tags: List[str]) -> List[str]:
"""
Join multi-word predicates to a single
predicate ('V') token.
"""
ret = []
verb_flag = False
for tag in tags:
if "V" in tag:
# Create a continuous 'V' BIO span
prefix, _ = tag.split("-")
if verb_flag:... | [
"def",
"join_mwp",
"(",
"tags",
":",
"List",
"[",
"str",
"]",
")",
"->",
"List",
"[",
"str",
"]",
":",
"ret",
"=",
"[",
"]",
"verb_flag",
"=",
"False",
"for",
"tag",
"in",
"tags",
":",
"if",
"\"V\"",
"in",
"tag",
":",
"# Create a continuous 'V' BIO s... | Join multi-word predicates to a single
predicate ('V') token. | [
"Join",
"multi",
"-",
"word",
"predicates",
"to",
"a",
"single",
"predicate",
"(",
"V",
")",
"token",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/predictors/open_information_extraction.py#L13-L33 | train |
allenai/allennlp | allennlp/predictors/open_information_extraction.py | make_oie_string | def make_oie_string(tokens: List[Token], tags: List[str]) -> str:
"""
Converts a list of model outputs (i.e., a list of lists of bio tags, each
pertaining to a single word), returns an inline bracket representation of
the prediction.
"""
frame = []
chunk = []
words = [token.text for toke... | python | def make_oie_string(tokens: List[Token], tags: List[str]) -> str:
"""
Converts a list of model outputs (i.e., a list of lists of bio tags, each
pertaining to a single word), returns an inline bracket representation of
the prediction.
"""
frame = []
chunk = []
words = [token.text for toke... | [
"def",
"make_oie_string",
"(",
"tokens",
":",
"List",
"[",
"Token",
"]",
",",
"tags",
":",
"List",
"[",
"str",
"]",
")",
"->",
"str",
":",
"frame",
"=",
"[",
"]",
"chunk",
"=",
"[",
"]",
"words",
"=",
"[",
"token",
".",
"text",
"for",
"token",
... | Converts a list of model outputs (i.e., a list of lists of bio tags, each
pertaining to a single word), returns an inline bracket representation of
the prediction. | [
"Converts",
"a",
"list",
"of",
"model",
"outputs",
"(",
"i",
".",
"e",
".",
"a",
"list",
"of",
"lists",
"of",
"bio",
"tags",
"each",
"pertaining",
"to",
"a",
"single",
"word",
")",
"returns",
"an",
"inline",
"bracket",
"representation",
"of",
"the",
"p... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/predictors/open_information_extraction.py#L35-L61 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
allenai/allennlp | allennlp/predictors/open_information_extraction.py | consolidate_predictions | def consolidate_predictions(outputs: List[List[str]], sent_tokens: List[Token]) -> Dict[str, List[str]]:
"""
Identify that certain predicates are part of a multiword predicate
(e.g., "decided to run") in which case, we don't need to return
the embedded predicate ("run").
"""
pred_dict: Dict[str,... | python | def consolidate_predictions(outputs: List[List[str]], sent_tokens: List[Token]) -> Dict[str, List[str]]:
"""
Identify that certain predicates are part of a multiword predicate
(e.g., "decided to run") in which case, we don't need to return
the embedded predicate ("run").
"""
pred_dict: Dict[str,... | [
"def",
"consolidate_predictions",
"(",
"outputs",
":",
"List",
"[",
"List",
"[",
"str",
"]",
"]",
",",
"sent_tokens",
":",
"List",
"[",
"Token",
"]",
")",
"->",
"Dict",
"[",
"str",
",",
"List",
"[",
"str",
"]",
"]",
":",
"pred_dict",
":",
"Dict",
"... | Identify that certain predicates are part of a multiword predicate
(e.g., "decided to run") in which case, we don't need to return
the embedded predicate ("run"). | [
"Identify",
"that",
"certain",
"predicates",
"are",
"part",
"of",
"a",
"multiword",
"predicate",
"(",
"e",
".",
"g",
".",
"decided",
"to",
"run",
")",
"in",
"which",
"case",
"we",
"don",
"t",
"need",
"to",
"return",
"the",
"embedded",
"predicate",
"(",
... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/predictors/open_information_extraction.py#L132-L158 | train |
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 | train |
allenai/allennlp | allennlp/modules/elmo.py | batch_to_ids | def batch_to_ids(batch: List[List[str]]) -> torch.Tensor:
"""
Converts a batch of tokenized sentences to a tensor representing the sentences with encoded characters
(len(batch), max sentence length, max word length).
Parameters
----------
batch : ``List[List[str]]``, required
A list of ... | python | def batch_to_ids(batch: List[List[str]]) -> torch.Tensor:
"""
Converts a batch of tokenized sentences to a tensor representing the sentences with encoded characters
(len(batch), max sentence length, max word length).
Parameters
----------
batch : ``List[List[str]]``, required
A list of ... | [
"def",
"batch_to_ids",
"(",
"batch",
":",
"List",
"[",
"List",
"[",
"str",
"]",
"]",
")",
"->",
"torch",
".",
"Tensor",
":",
"instances",
"=",
"[",
"]",
"indexer",
"=",
"ELMoTokenCharactersIndexer",
"(",
")",
"for",
"sentence",
"in",
"batch",
":",
"tok... | Converts a batch of tokenized sentences to a tensor representing the sentences with encoded characters
(len(batch), max sentence length, max word length).
Parameters
----------
batch : ``List[List[str]]``, required
A list of tokenized sentences.
Returns
-------
A tensor of padd... | [
"Converts",
"a",
"batch",
"of",
"tokenized",
"sentences",
"to",
"a",
"tensor",
"representing",
"the",
"sentences",
"with",
"encoded",
"characters",
"(",
"len",
"(",
"batch",
")",
"max",
"sentence",
"length",
"max",
"word",
"length",
")",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/modules/elmo.py#L230-L256 | train |
allenai/allennlp | allennlp/modules/elmo.py | Elmo.forward | def forward(self, # pylint: disable=arguments-differ
inputs: torch.Tensor,
word_inputs: torch.Tensor = None) -> Dict[str, Union[torch.Tensor, List[torch.Tensor]]]:
"""
Parameters
----------
inputs: ``torch.Tensor``, required.
Shape ``(batch_size... | python | def forward(self, # pylint: disable=arguments-differ
inputs: torch.Tensor,
word_inputs: torch.Tensor = None) -> Dict[str, Union[torch.Tensor, List[torch.Tensor]]]:
"""
Parameters
----------
inputs: ``torch.Tensor``, required.
Shape ``(batch_size... | [
"def",
"forward",
"(",
"self",
",",
"# pylint: disable=arguments-differ",
"inputs",
":",
"torch",
".",
"Tensor",
",",
"word_inputs",
":",
"torch",
".",
"Tensor",
"=",
"None",
")",
"->",
"Dict",
"[",
"str",
",",
"Union",
"[",
"torch",
".",
"Tensor",
",",
... | Parameters
----------
inputs: ``torch.Tensor``, required.
Shape ``(batch_size, timesteps, 50)`` of character ids representing the current batch.
word_inputs : ``torch.Tensor``, required.
If you passed a cached vocab, you can in addition pass a tensor of shape
``(b... | [
"Parameters",
"----------",
"inputs",
":",
"torch",
".",
"Tensor",
"required",
".",
"Shape",
"(",
"batch_size",
"timesteps",
"50",
")",
"of",
"character",
"ids",
"representing",
"the",
"current",
"batch",
".",
"word_inputs",
":",
"torch",
".",
"Tensor",
"requi... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/modules/elmo.py#L127-L201 | train |
allenai/allennlp | allennlp/modules/elmo.py | _ElmoCharacterEncoder.forward | def forward(self, inputs: torch.Tensor) -> Dict[str, torch.Tensor]: # pylint: disable=arguments-differ
"""
Compute context insensitive token embeddings for ELMo representations.
Parameters
----------
inputs: ``torch.Tensor``
Shape ``(batch_size, sequence_length, 50)... | python | def forward(self, inputs: torch.Tensor) -> Dict[str, torch.Tensor]: # pylint: disable=arguments-differ
"""
Compute context insensitive token embeddings for ELMo representations.
Parameters
----------
inputs: ``torch.Tensor``
Shape ``(batch_size, sequence_length, 50)... | [
"def",
"forward",
"(",
"self",
",",
"inputs",
":",
"torch",
".",
"Tensor",
")",
"->",
"Dict",
"[",
"str",
",",
"torch",
".",
"Tensor",
"]",
":",
"# pylint: disable=arguments-differ",
"# Add BOS/EOS",
"mask",
"=",
"(",
"(",
"inputs",
">",
"0",
")",
".",
... | Compute context insensitive token embeddings for ELMo representations.
Parameters
----------
inputs: ``torch.Tensor``
Shape ``(batch_size, sequence_length, 50)`` of character ids representing the
current batch.
Returns
-------
Dict with keys:
... | [
"Compute",
"context",
"insensitive",
"token",
"embeddings",
"for",
"ELMo",
"representations",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/modules/elmo.py#L324-L395 | train |
allenai/allennlp | allennlp/modules/elmo.py | _ElmoBiLm.forward | def forward(self, # pylint: disable=arguments-differ
inputs: torch.Tensor,
word_inputs: torch.Tensor = None) -> Dict[str, Union[torch.Tensor, List[torch.Tensor]]]:
"""
Parameters
----------
inputs: ``torch.Tensor``, required.
Shape ``(batch_si... | python | def forward(self, # pylint: disable=arguments-differ
inputs: torch.Tensor,
word_inputs: torch.Tensor = None) -> Dict[str, Union[torch.Tensor, List[torch.Tensor]]]:
"""
Parameters
----------
inputs: ``torch.Tensor``, required.
Shape ``(batch_si... | [
"def",
"forward",
"(",
"self",
",",
"# pylint: disable=arguments-differ",
"inputs",
":",
"torch",
".",
"Tensor",
",",
"word_inputs",
":",
"torch",
".",
"Tensor",
"=",
"None",
")",
"->",
"Dict",
"[",
"str",
",",
"Union",
"[",
"torch",
".",
"Tensor",
",",
... | Parameters
----------
inputs: ``torch.Tensor``, required.
Shape ``(batch_size, timesteps, 50)`` of character ids representing the current batch.
word_inputs : ``torch.Tensor``, required.
If you passed a cached vocab, you can in addition pass a tensor of shape ``(batch_siz... | [
"Parameters",
"----------",
"inputs",
":",
"torch",
".",
"Tensor",
"required",
".",
"Shape",
"(",
"batch_size",
"timesteps",
"50",
")",
"of",
"character",
"ids",
"representing",
"the",
"current",
"batch",
".",
"word_inputs",
":",
"torch",
".",
"Tensor",
"requi... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/modules/elmo.py#L561-L625 | train |
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 | train |
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 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.