id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
23,100 | allenai/allennlp | allennlp/commands/elmo.py | ElmoEmbedder.embed_sentence | def embed_sentence(self, sentence: List[str]) -> numpy.ndarray:
"""
Computes the ELMo embeddings for a single tokenized sentence.
Please note that ELMo has internal state and will give different results for the same input.
See the comment under the class definition.
Parameters
... | python | def embed_sentence(self, sentence: List[str]) -> numpy.ndarray:
"""
Computes the ELMo embeddings for a single tokenized sentence.
Please note that ELMo has internal state and will give different results for the same input.
See the comment under the class definition.
Parameters
... | [
"def",
"embed_sentence",
"(",
"self",
",",
"sentence",
":",
"List",
"[",
"str",
"]",
")",
"->",
"numpy",
".",
"ndarray",
":",
"return",
"self",
".",
"embed_batch",
"(",
"[",
"sentence",
"]",
")",
"[",
"0",
"]"
] | Computes the ELMo embeddings for a single tokenized sentence.
Please note that ELMo has internal state and will give different results for the same input.
See the comment under the class definition.
Parameters
----------
sentence : ``List[str]``, required
A tokenize... | [
"Computes",
"the",
"ELMo",
"embeddings",
"for",
"a",
"single",
"tokenized",
"sentence",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/commands/elmo.py#L203-L220 |
23,101 | allenai/allennlp | allennlp/commands/elmo.py | ElmoEmbedder.embed_batch | def embed_batch(self, batch: List[List[str]]) -> List[numpy.ndarray]:
"""
Computes the ELMo embeddings for a batch of tokenized sentences.
Please note that ELMo has internal state and will give different results for the same input.
See the comment under the class definition.
Pa... | python | def embed_batch(self, batch: List[List[str]]) -> List[numpy.ndarray]:
"""
Computes the ELMo embeddings for a batch of tokenized sentences.
Please note that ELMo has internal state and will give different results for the same input.
See the comment under the class definition.
Pa... | [
"def",
"embed_batch",
"(",
"self",
",",
"batch",
":",
"List",
"[",
"List",
"[",
"str",
"]",
"]",
")",
"->",
"List",
"[",
"numpy",
".",
"ndarray",
"]",
":",
"elmo_embeddings",
"=",
"[",
"]",
"# Batches with only an empty sentence will throw an exception inside Al... | Computes the ELMo embeddings for a batch of tokenized sentences.
Please note that ELMo has internal state and will give different results for the same input.
See the comment under the class definition.
Parameters
----------
batch : ``List[List[str]]``, required
A li... | [
"Computes",
"the",
"ELMo",
"embeddings",
"for",
"a",
"batch",
"of",
"tokenized",
"sentences",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/commands/elmo.py#L222-L254 |
23,102 | allenai/allennlp | allennlp/commands/elmo.py | ElmoEmbedder.embed_sentences | def embed_sentences(self,
sentences: Iterable[List[str]],
batch_size: int = DEFAULT_BATCH_SIZE) -> Iterable[numpy.ndarray]:
"""
Computes the ELMo embeddings for a iterable of sentences.
Please note that ELMo has internal state and will give differ... | python | def embed_sentences(self,
sentences: Iterable[List[str]],
batch_size: int = DEFAULT_BATCH_SIZE) -> Iterable[numpy.ndarray]:
"""
Computes the ELMo embeddings for a iterable of sentences.
Please note that ELMo has internal state and will give differ... | [
"def",
"embed_sentences",
"(",
"self",
",",
"sentences",
":",
"Iterable",
"[",
"List",
"[",
"str",
"]",
"]",
",",
"batch_size",
":",
"int",
"=",
"DEFAULT_BATCH_SIZE",
")",
"->",
"Iterable",
"[",
"numpy",
".",
"ndarray",
"]",
":",
"for",
"batch",
"in",
... | Computes the ELMo embeddings for a iterable of sentences.
Please note that ELMo has internal state and will give different results for the same input.
See the comment under the class definition.
Parameters
----------
sentences : ``Iterable[List[str]]``, required
An ... | [
"Computes",
"the",
"ELMo",
"embeddings",
"for",
"a",
"iterable",
"of",
"sentences",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/commands/elmo.py#L256-L277 |
23,103 | allenai/allennlp | allennlp/commands/elmo.py | ElmoEmbedder.embed_file | def embed_file(self,
input_file: IO,
output_file_path: str,
output_format: str = "all",
batch_size: int = DEFAULT_BATCH_SIZE,
forget_sentences: bool = False,
use_sentence_keys: bool = False) -> None:
... | python | def embed_file(self,
input_file: IO,
output_file_path: str,
output_format: str = "all",
batch_size: int = DEFAULT_BATCH_SIZE,
forget_sentences: bool = False,
use_sentence_keys: bool = False) -> None:
... | [
"def",
"embed_file",
"(",
"self",
",",
"input_file",
":",
"IO",
",",
"output_file_path",
":",
"str",
",",
"output_format",
":",
"str",
"=",
"\"all\"",
",",
"batch_size",
":",
"int",
"=",
"DEFAULT_BATCH_SIZE",
",",
"forget_sentences",
":",
"bool",
"=",
"False... | Computes ELMo embeddings from an input_file where each line contains a sentence tokenized by whitespace.
The ELMo embeddings are written out in HDF5 format, where each sentence embedding
is saved in a dataset with the line number in the original file as the key.
Parameters
----------
... | [
"Computes",
"ELMo",
"embeddings",
"from",
"an",
"input_file",
"where",
"each",
"line",
"contains",
"a",
"sentence",
"tokenized",
"by",
"whitespace",
".",
"The",
"ELMo",
"embeddings",
"are",
"written",
"out",
"in",
"HDF5",
"format",
"where",
"each",
"sentence",
... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/commands/elmo.py#L279-L365 |
23,104 | allenai/allennlp | allennlp/data/instance.py | Instance.add_field | def add_field(self, field_name: str, field: Field, vocab: Vocabulary = None) -> None:
"""
Add the field to the existing fields mapping.
If we have already indexed the Instance, then we also index `field`, so
it is necessary to supply the vocab.
"""
self.fields[field_name]... | python | def add_field(self, field_name: str, field: Field, vocab: Vocabulary = None) -> None:
"""
Add the field to the existing fields mapping.
If we have already indexed the Instance, then we also index `field`, so
it is necessary to supply the vocab.
"""
self.fields[field_name]... | [
"def",
"add_field",
"(",
"self",
",",
"field_name",
":",
"str",
",",
"field",
":",
"Field",
",",
"vocab",
":",
"Vocabulary",
"=",
"None",
")",
"->",
"None",
":",
"self",
".",
"fields",
"[",
"field_name",
"]",
"=",
"field",
"if",
"self",
".",
"indexed... | Add the field to the existing fields mapping.
If we have already indexed the Instance, then we also index `field`, so
it is necessary to supply the vocab. | [
"Add",
"the",
"field",
"to",
"the",
"existing",
"fields",
"mapping",
".",
"If",
"we",
"have",
"already",
"indexed",
"the",
"Instance",
"then",
"we",
"also",
"index",
"field",
"so",
"it",
"is",
"necessary",
"to",
"supply",
"the",
"vocab",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/data/instance.py#L41-L49 |
23,105 | allenai/allennlp | allennlp/data/instance.py | Instance.count_vocab_items | def count_vocab_items(self, counter: Dict[str, Dict[str, int]]):
"""
Increments counts in the given ``counter`` for all of the vocabulary items in all of the
``Fields`` in this ``Instance``.
"""
for field in self.fields.values():
field.count_vocab_items(counter) | python | def count_vocab_items(self, counter: Dict[str, Dict[str, int]]):
"""
Increments counts in the given ``counter`` for all of the vocabulary items in all of the
``Fields`` in this ``Instance``.
"""
for field in self.fields.values():
field.count_vocab_items(counter) | [
"def",
"count_vocab_items",
"(",
"self",
",",
"counter",
":",
"Dict",
"[",
"str",
",",
"Dict",
"[",
"str",
",",
"int",
"]",
"]",
")",
":",
"for",
"field",
"in",
"self",
".",
"fields",
".",
"values",
"(",
")",
":",
"field",
".",
"count_vocab_items",
... | Increments counts in the given ``counter`` for all of the vocabulary items in all of the
``Fields`` in this ``Instance``. | [
"Increments",
"counts",
"in",
"the",
"given",
"counter",
"for",
"all",
"of",
"the",
"vocabulary",
"items",
"in",
"all",
"of",
"the",
"Fields",
"in",
"this",
"Instance",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/data/instance.py#L51-L57 |
23,106 | allenai/allennlp | allennlp/data/instance.py | Instance.index_fields | def index_fields(self, vocab: Vocabulary) -> None:
"""
Indexes all fields in this ``Instance`` using the provided ``Vocabulary``.
This `mutates` the current object, it does not return a new ``Instance``.
A ``DataIterator`` will call this on each pass through a dataset; we use the ``index... | python | def index_fields(self, vocab: Vocabulary) -> None:
"""
Indexes all fields in this ``Instance`` using the provided ``Vocabulary``.
This `mutates` the current object, it does not return a new ``Instance``.
A ``DataIterator`` will call this on each pass through a dataset; we use the ``index... | [
"def",
"index_fields",
"(",
"self",
",",
"vocab",
":",
"Vocabulary",
")",
"->",
"None",
":",
"if",
"not",
"self",
".",
"indexed",
":",
"self",
".",
"indexed",
"=",
"True",
"for",
"field",
"in",
"self",
".",
"fields",
".",
"values",
"(",
")",
":",
"... | Indexes all fields in this ``Instance`` using the provided ``Vocabulary``.
This `mutates` the current object, it does not return a new ``Instance``.
A ``DataIterator`` will call this on each pass through a dataset; we use the ``indexed``
flag to make sure that indexing only happens once.
... | [
"Indexes",
"all",
"fields",
"in",
"this",
"Instance",
"using",
"the",
"provided",
"Vocabulary",
".",
"This",
"mutates",
"the",
"current",
"object",
"it",
"does",
"not",
"return",
"a",
"new",
"Instance",
".",
"A",
"DataIterator",
"will",
"call",
"this",
"on",... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/data/instance.py#L59-L72 |
23,107 | allenai/allennlp | allennlp/data/instance.py | Instance.get_padding_lengths | def get_padding_lengths(self) -> Dict[str, Dict[str, int]]:
"""
Returns a dictionary of padding lengths, keyed by field name. Each ``Field`` returns a
mapping from padding keys to actual lengths, and we just key that dictionary by field name.
"""
lengths = {}
for field_n... | python | def get_padding_lengths(self) -> Dict[str, Dict[str, int]]:
"""
Returns a dictionary of padding lengths, keyed by field name. Each ``Field`` returns a
mapping from padding keys to actual lengths, and we just key that dictionary by field name.
"""
lengths = {}
for field_n... | [
"def",
"get_padding_lengths",
"(",
"self",
")",
"->",
"Dict",
"[",
"str",
",",
"Dict",
"[",
"str",
",",
"int",
"]",
"]",
":",
"lengths",
"=",
"{",
"}",
"for",
"field_name",
",",
"field",
"in",
"self",
".",
"fields",
".",
"items",
"(",
")",
":",
"... | Returns a dictionary of padding lengths, keyed by field name. Each ``Field`` returns a
mapping from padding keys to actual lengths, and we just key that dictionary by field name. | [
"Returns",
"a",
"dictionary",
"of",
"padding",
"lengths",
"keyed",
"by",
"field",
"name",
".",
"Each",
"Field",
"returns",
"a",
"mapping",
"from",
"padding",
"keys",
"to",
"actual",
"lengths",
"and",
"we",
"just",
"key",
"that",
"dictionary",
"by",
"field",
... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/data/instance.py#L74-L82 |
23,108 | allenai/allennlp | allennlp/common/configuration.py | _docspec_comments | def _docspec_comments(obj) -> Dict[str, str]:
"""
Inspect the docstring and get the comments for each parameter.
"""
# Sometimes our docstring is on the class, and sometimes it's on the initializer,
# so we've got to check both.
class_docstring = getattr(obj, '__doc__', None)
init_docstring ... | python | def _docspec_comments(obj) -> Dict[str, str]:
"""
Inspect the docstring and get the comments for each parameter.
"""
# Sometimes our docstring is on the class, and sometimes it's on the initializer,
# so we've got to check both.
class_docstring = getattr(obj, '__doc__', None)
init_docstring ... | [
"def",
"_docspec_comments",
"(",
"obj",
")",
"->",
"Dict",
"[",
"str",
",",
"str",
"]",
":",
"# Sometimes our docstring is on the class, and sometimes it's on the initializer,",
"# so we've got to check both.",
"class_docstring",
"=",
"getattr",
"(",
"obj",
",",
"'__doc__'"... | Inspect the docstring and get the comments for each parameter. | [
"Inspect",
"the",
"docstring",
"and",
"get",
"the",
"comments",
"for",
"each",
"parameter",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/common/configuration.py#L195-L221 |
23,109 | allenai/allennlp | allennlp/common/configuration.py | render_config | def render_config(config: Config, indent: str = "") -> str:
"""
Pretty-print a config in sort-of-JSON+comments.
"""
# Add four spaces to the indent.
new_indent = indent + " "
return "".join([
# opening brace + newline
"{\n",
# "type": "...", (if present)
... | python | def render_config(config: Config, indent: str = "") -> str:
"""
Pretty-print a config in sort-of-JSON+comments.
"""
# Add four spaces to the indent.
new_indent = indent + " "
return "".join([
# opening brace + newline
"{\n",
# "type": "...", (if present)
... | [
"def",
"render_config",
"(",
"config",
":",
"Config",
",",
"indent",
":",
"str",
"=",
"\"\"",
")",
"->",
"str",
":",
"# Add four spaces to the indent.",
"new_indent",
"=",
"indent",
"+",
"\" \"",
"return",
"\"\"",
".",
"join",
"(",
"[",
"# opening brace + n... | Pretty-print a config in sort-of-JSON+comments. | [
"Pretty",
"-",
"print",
"a",
"config",
"in",
"sort",
"-",
"of",
"-",
"JSON",
"+",
"comments",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/common/configuration.py#L298-L315 |
23,110 | allenai/allennlp | allennlp/common/configuration.py | _render | def _render(item: ConfigItem, indent: str = "") -> str:
"""
Render a single config item, with the provided indent
"""
optional = item.default_value != _NO_DEFAULT
if is_configurable(item.annotation):
rendered_annotation = f"{item.annotation} (configurable)"
else:
rendered_annota... | python | def _render(item: ConfigItem, indent: str = "") -> str:
"""
Render a single config item, with the provided indent
"""
optional = item.default_value != _NO_DEFAULT
if is_configurable(item.annotation):
rendered_annotation = f"{item.annotation} (configurable)"
else:
rendered_annota... | [
"def",
"_render",
"(",
"item",
":",
"ConfigItem",
",",
"indent",
":",
"str",
"=",
"\"\"",
")",
"->",
"str",
":",
"optional",
"=",
"item",
".",
"default_value",
"!=",
"_NO_DEFAULT",
"if",
"is_configurable",
"(",
"item",
".",
"annotation",
")",
":",
"rende... | Render a single config item, with the provided indent | [
"Render",
"a",
"single",
"config",
"item",
"with",
"the",
"provided",
"indent"
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/common/configuration.py#L355-L377 |
23,111 | allenai/allennlp | allennlp/common/file_utils.py | url_to_filename | def url_to_filename(url: str, etag: str = None) -> str:
"""
Convert `url` into a hashed filename in a repeatable way.
If `etag` is specified, append its hash to the url's, delimited
by a period.
"""
url_bytes = url.encode('utf-8')
url_hash = sha256(url_bytes)
filename = url_hash.hexdiges... | python | def url_to_filename(url: str, etag: str = None) -> str:
"""
Convert `url` into a hashed filename in a repeatable way.
If `etag` is specified, append its hash to the url's, delimited
by a period.
"""
url_bytes = url.encode('utf-8')
url_hash = sha256(url_bytes)
filename = url_hash.hexdiges... | [
"def",
"url_to_filename",
"(",
"url",
":",
"str",
",",
"etag",
":",
"str",
"=",
"None",
")",
"->",
"str",
":",
"url_bytes",
"=",
"url",
".",
"encode",
"(",
"'utf-8'",
")",
"url_hash",
"=",
"sha256",
"(",
"url_bytes",
")",
"filename",
"=",
"url_hash",
... | Convert `url` into a hashed filename in a repeatable way.
If `etag` is specified, append its hash to the url's, delimited
by a period. | [
"Convert",
"url",
"into",
"a",
"hashed",
"filename",
"in",
"a",
"repeatable",
"way",
".",
"If",
"etag",
"is",
"specified",
"append",
"its",
"hash",
"to",
"the",
"url",
"s",
"delimited",
"by",
"a",
"period",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/common/file_utils.py#L39-L54 |
23,112 | allenai/allennlp | allennlp/common/file_utils.py | split_s3_path | def split_s3_path(url: str) -> Tuple[str, str]:
"""Split a full s3 path into the bucket name and path."""
parsed = urlparse(url)
if not parsed.netloc or not parsed.path:
raise ValueError("bad s3 path {}".format(url))
bucket_name = parsed.netloc
s3_path = parsed.path
# Remove '/' at begin... | python | def split_s3_path(url: str) -> Tuple[str, str]:
"""Split a full s3 path into the bucket name and path."""
parsed = urlparse(url)
if not parsed.netloc or not parsed.path:
raise ValueError("bad s3 path {}".format(url))
bucket_name = parsed.netloc
s3_path = parsed.path
# Remove '/' at begin... | [
"def",
"split_s3_path",
"(",
"url",
":",
"str",
")",
"->",
"Tuple",
"[",
"str",
",",
"str",
"]",
":",
"parsed",
"=",
"urlparse",
"(",
"url",
")",
"if",
"not",
"parsed",
".",
"netloc",
"or",
"not",
"parsed",
".",
"path",
":",
"raise",
"ValueError",
... | Split a full s3 path into the bucket name and path. | [
"Split",
"a",
"full",
"s3",
"path",
"into",
"the",
"bucket",
"name",
"and",
"path",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/common/file_utils.py#L120-L130 |
23,113 | allenai/allennlp | allennlp/common/file_utils.py | s3_request | def s3_request(func: Callable):
"""
Wrapper function for s3 requests in order to create more helpful error
messages.
"""
@wraps(func)
def wrapper(url: str, *args, **kwargs):
try:
return func(url, *args, **kwargs)
except ClientError as exc:
if int(exc.resp... | python | def s3_request(func: Callable):
"""
Wrapper function for s3 requests in order to create more helpful error
messages.
"""
@wraps(func)
def wrapper(url: str, *args, **kwargs):
try:
return func(url, *args, **kwargs)
except ClientError as exc:
if int(exc.resp... | [
"def",
"s3_request",
"(",
"func",
":",
"Callable",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"url",
":",
"str",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"return",
"func",
"(",
"url",
",",
"*",
"arg... | Wrapper function for s3 requests in order to create more helpful error
messages. | [
"Wrapper",
"function",
"for",
"s3",
"requests",
"in",
"order",
"to",
"create",
"more",
"helpful",
"error",
"messages",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/common/file_utils.py#L133-L149 |
23,114 | allenai/allennlp | allennlp/common/file_utils.py | s3_etag | def s3_etag(url: str) -> Optional[str]:
"""Check ETag on S3 object."""
s3_resource = boto3.resource("s3")
bucket_name, s3_path = split_s3_path(url)
s3_object = s3_resource.Object(bucket_name, s3_path)
return s3_object.e_tag | python | def s3_etag(url: str) -> Optional[str]:
"""Check ETag on S3 object."""
s3_resource = boto3.resource("s3")
bucket_name, s3_path = split_s3_path(url)
s3_object = s3_resource.Object(bucket_name, s3_path)
return s3_object.e_tag | [
"def",
"s3_etag",
"(",
"url",
":",
"str",
")",
"->",
"Optional",
"[",
"str",
"]",
":",
"s3_resource",
"=",
"boto3",
".",
"resource",
"(",
"\"s3\"",
")",
"bucket_name",
",",
"s3_path",
"=",
"split_s3_path",
"(",
"url",
")",
"s3_object",
"=",
"s3_resource"... | Check ETag on S3 object. | [
"Check",
"ETag",
"on",
"S3",
"object",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/common/file_utils.py#L153-L158 |
23,115 | allenai/allennlp | allennlp/common/file_utils.py | s3_get | def s3_get(url: str, temp_file: IO) -> None:
"""Pull a file directly from S3."""
s3_resource = boto3.resource("s3")
bucket_name, s3_path = split_s3_path(url)
s3_resource.Bucket(bucket_name).download_fileobj(s3_path, temp_file) | python | def s3_get(url: str, temp_file: IO) -> None:
"""Pull a file directly from S3."""
s3_resource = boto3.resource("s3")
bucket_name, s3_path = split_s3_path(url)
s3_resource.Bucket(bucket_name).download_fileobj(s3_path, temp_file) | [
"def",
"s3_get",
"(",
"url",
":",
"str",
",",
"temp_file",
":",
"IO",
")",
"->",
"None",
":",
"s3_resource",
"=",
"boto3",
".",
"resource",
"(",
"\"s3\"",
")",
"bucket_name",
",",
"s3_path",
"=",
"split_s3_path",
"(",
"url",
")",
"s3_resource",
".",
"B... | Pull a file directly from S3. | [
"Pull",
"a",
"file",
"directly",
"from",
"S3",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/common/file_utils.py#L162-L166 |
23,116 | allenai/allennlp | allennlp/common/file_utils.py | get_from_cache | def get_from_cache(url: str, cache_dir: str = None) -> str:
"""
Given a URL, look for the corresponding dataset in the local cache.
If it's not there, download it. Then return the path to the cached file.
"""
if cache_dir is None:
cache_dir = CACHE_DIRECTORY
os.makedirs(cache_dir, exist... | python | def get_from_cache(url: str, cache_dir: str = None) -> str:
"""
Given a URL, look for the corresponding dataset in the local cache.
If it's not there, download it. Then return the path to the cached file.
"""
if cache_dir is None:
cache_dir = CACHE_DIRECTORY
os.makedirs(cache_dir, exist... | [
"def",
"get_from_cache",
"(",
"url",
":",
"str",
",",
"cache_dir",
":",
"str",
"=",
"None",
")",
"->",
"str",
":",
"if",
"cache_dir",
"is",
"None",
":",
"cache_dir",
"=",
"CACHE_DIRECTORY",
"os",
".",
"makedirs",
"(",
"cache_dir",
",",
"exist_ok",
"=",
... | Given a URL, look for the corresponding dataset in the local cache.
If it's not there, download it. Then return the path to the cached file. | [
"Given",
"a",
"URL",
"look",
"for",
"the",
"corresponding",
"dataset",
"in",
"the",
"local",
"cache",
".",
"If",
"it",
"s",
"not",
"there",
"download",
"it",
".",
"Then",
"return",
"the",
"path",
"to",
"the",
"cached",
"file",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/common/file_utils.py#L182-L236 |
23,117 | allenai/allennlp | allennlp/data/tokenizers/sentence_splitter.py | SentenceSplitter.batch_split_sentences | def batch_split_sentences(self, texts: List[str]) -> List[List[str]]:
"""
This method lets you take advantage of spacy's batch processing.
Default implementation is to just iterate over the texts and call ``split_sentences``.
"""
return [self.split_sentences(text) for text in tex... | python | def batch_split_sentences(self, texts: List[str]) -> List[List[str]]:
"""
This method lets you take advantage of spacy's batch processing.
Default implementation is to just iterate over the texts and call ``split_sentences``.
"""
return [self.split_sentences(text) for text in tex... | [
"def",
"batch_split_sentences",
"(",
"self",
",",
"texts",
":",
"List",
"[",
"str",
"]",
")",
"->",
"List",
"[",
"List",
"[",
"str",
"]",
"]",
":",
"return",
"[",
"self",
".",
"split_sentences",
"(",
"text",
")",
"for",
"text",
"in",
"texts",
"]"
] | This method lets you take advantage of spacy's batch processing.
Default implementation is to just iterate over the texts and call ``split_sentences``. | [
"This",
"method",
"lets",
"you",
"take",
"advantage",
"of",
"spacy",
"s",
"batch",
"processing",
".",
"Default",
"implementation",
"is",
"to",
"just",
"iterate",
"over",
"the",
"texts",
"and",
"call",
"split_sentences",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/data/tokenizers/sentence_splitter.py#L22-L27 |
23,118 | allenai/allennlp | allennlp/data/dataset_readers/dataset_utils/ontonotes.py | Ontonotes.dataset_iterator | def dataset_iterator(self, file_path: str) -> Iterator[OntonotesSentence]:
"""
An iterator over the entire dataset, yielding all sentences processed.
"""
for conll_file in self.dataset_path_iterator(file_path):
yield from self.sentence_iterator(conll_file) | python | def dataset_iterator(self, file_path: str) -> Iterator[OntonotesSentence]:
"""
An iterator over the entire dataset, yielding all sentences processed.
"""
for conll_file in self.dataset_path_iterator(file_path):
yield from self.sentence_iterator(conll_file) | [
"def",
"dataset_iterator",
"(",
"self",
",",
"file_path",
":",
"str",
")",
"->",
"Iterator",
"[",
"OntonotesSentence",
"]",
":",
"for",
"conll_file",
"in",
"self",
".",
"dataset_path_iterator",
"(",
"file_path",
")",
":",
"yield",
"from",
"self",
".",
"sente... | An iterator over the entire dataset, yielding all sentences processed. | [
"An",
"iterator",
"over",
"the",
"entire",
"dataset",
"yielding",
"all",
"sentences",
"processed",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/data/dataset_readers/dataset_utils/ontonotes.py#L176-L181 |
23,119 | allenai/allennlp | allennlp/data/dataset_readers/dataset_utils/ontonotes.py | Ontonotes.dataset_path_iterator | def dataset_path_iterator(file_path: str) -> Iterator[str]:
"""
An iterator returning file_paths in a directory
containing CONLL-formatted files.
"""
logger.info("Reading CONLL sentences from dataset files at: %s", file_path)
for root, _, files in list(os.walk(file_path))... | python | def dataset_path_iterator(file_path: str) -> Iterator[str]:
"""
An iterator returning file_paths in a directory
containing CONLL-formatted files.
"""
logger.info("Reading CONLL sentences from dataset files at: %s", file_path)
for root, _, files in list(os.walk(file_path))... | [
"def",
"dataset_path_iterator",
"(",
"file_path",
":",
"str",
")",
"->",
"Iterator",
"[",
"str",
"]",
":",
"logger",
".",
"info",
"(",
"\"Reading CONLL sentences from dataset files at: %s\"",
",",
"file_path",
")",
"for",
"root",
",",
"_",
",",
"files",
"in",
... | An iterator returning file_paths in a directory
containing CONLL-formatted files. | [
"An",
"iterator",
"returning",
"file_paths",
"in",
"a",
"directory",
"containing",
"CONLL",
"-",
"formatted",
"files",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/data/dataset_readers/dataset_utils/ontonotes.py#L184-L198 |
23,120 | allenai/allennlp | allennlp/data/dataset_readers/dataset_utils/ontonotes.py | Ontonotes.dataset_document_iterator | def dataset_document_iterator(self, file_path: str) -> Iterator[List[OntonotesSentence]]:
"""
An iterator over CONLL formatted files which yields documents, regardless
of the number of document annotations in a particular file. This is useful
for conll data which has been preprocessed, s... | python | def dataset_document_iterator(self, file_path: str) -> Iterator[List[OntonotesSentence]]:
"""
An iterator over CONLL formatted files which yields documents, regardless
of the number of document annotations in a particular file. This is useful
for conll data which has been preprocessed, s... | [
"def",
"dataset_document_iterator",
"(",
"self",
",",
"file_path",
":",
"str",
")",
"->",
"Iterator",
"[",
"List",
"[",
"OntonotesSentence",
"]",
"]",
":",
"with",
"codecs",
".",
"open",
"(",
"file_path",
",",
"'r'",
",",
"encoding",
"=",
"'utf8'",
")",
... | An iterator over CONLL formatted files which yields documents, regardless
of the number of document annotations in a particular file. This is useful
for conll data which has been preprocessed, such as the preprocessing which
takes place for the 2012 CONLL Coreference Resolution task. | [
"An",
"iterator",
"over",
"CONLL",
"formatted",
"files",
"which",
"yields",
"documents",
"regardless",
"of",
"the",
"number",
"of",
"document",
"annotations",
"in",
"a",
"particular",
"file",
".",
"This",
"is",
"useful",
"for",
"conll",
"data",
"which",
"has",... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/data/dataset_readers/dataset_utils/ontonotes.py#L200-L225 |
23,121 | allenai/allennlp | allennlp/data/dataset_readers/dataset_utils/ontonotes.py | Ontonotes.sentence_iterator | def sentence_iterator(self, file_path: str) -> Iterator[OntonotesSentence]:
"""
An iterator over the sentences in an individual CONLL formatted file.
"""
for document in self.dataset_document_iterator(file_path):
for sentence in document:
yield sentence | python | def sentence_iterator(self, file_path: str) -> Iterator[OntonotesSentence]:
"""
An iterator over the sentences in an individual CONLL formatted file.
"""
for document in self.dataset_document_iterator(file_path):
for sentence in document:
yield sentence | [
"def",
"sentence_iterator",
"(",
"self",
",",
"file_path",
":",
"str",
")",
"->",
"Iterator",
"[",
"OntonotesSentence",
"]",
":",
"for",
"document",
"in",
"self",
".",
"dataset_document_iterator",
"(",
"file_path",
")",
":",
"for",
"sentence",
"in",
"document"... | An iterator over the sentences in an individual CONLL formatted file. | [
"An",
"iterator",
"over",
"the",
"sentences",
"in",
"an",
"individual",
"CONLL",
"formatted",
"file",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/data/dataset_readers/dataset_utils/ontonotes.py#L227-L233 |
23,122 | allenai/allennlp | allennlp/data/dataset_readers/dataset_utils/ontonotes.py | Ontonotes._process_span_annotations_for_word | def _process_span_annotations_for_word(annotations: List[str],
span_labels: List[List[str]],
current_span_labels: List[Optional[str]]) -> None:
"""
Given a sequence of different label types for a single word and the cu... | python | def _process_span_annotations_for_word(annotations: List[str],
span_labels: List[List[str]],
current_span_labels: List[Optional[str]]) -> None:
"""
Given a sequence of different label types for a single word and the cu... | [
"def",
"_process_span_annotations_for_word",
"(",
"annotations",
":",
"List",
"[",
"str",
"]",
",",
"span_labels",
":",
"List",
"[",
"List",
"[",
"str",
"]",
"]",
",",
"current_span_labels",
":",
"List",
"[",
"Optional",
"[",
"str",
"]",
"]",
")",
"->",
... | Given a sequence of different label types for a single word and the current
span label we are inside, compute the BIO tag for each label and append to a list.
Parameters
----------
annotations: ``List[str]``
A list of labels to compute BIO tags for.
span_labels : ``L... | [
"Given",
"a",
"sequence",
"of",
"different",
"label",
"types",
"for",
"a",
"single",
"word",
"and",
"the",
"current",
"span",
"label",
"we",
"are",
"inside",
"compute",
"the",
"BIO",
"tag",
"for",
"each",
"label",
"and",
"append",
"to",
"a",
"list",
"."
... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/data/dataset_readers/dataset_utils/ontonotes.py#L411-L449 |
23,123 | allenai/allennlp | allennlp/commands/print_results.py | print_results_from_args | def print_results_from_args(args: argparse.Namespace):
"""
Prints results from an ``argparse.Namespace`` object.
"""
path = args.path
metrics_name = args.metrics_filename
keys = args.keys
results_dict = {}
for root, _, files in os.walk(path):
if metrics_name in files:
... | python | def print_results_from_args(args: argparse.Namespace):
"""
Prints results from an ``argparse.Namespace`` object.
"""
path = args.path
metrics_name = args.metrics_filename
keys = args.keys
results_dict = {}
for root, _, files in os.walk(path):
if metrics_name in files:
... | [
"def",
"print_results_from_args",
"(",
"args",
":",
"argparse",
".",
"Namespace",
")",
":",
"path",
"=",
"args",
".",
"path",
"metrics_name",
"=",
"args",
".",
"metrics_filename",
"keys",
"=",
"args",
".",
"keys",
"results_dict",
"=",
"{",
"}",
"for",
"roo... | Prints results from an ``argparse.Namespace`` object. | [
"Prints",
"results",
"from",
"an",
"argparse",
".",
"Namespace",
"object",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/commands/print_results.py#L66-L88 |
23,124 | allenai/allennlp | allennlp/modules/input_variational_dropout.py | InputVariationalDropout.forward | def forward(self, input_tensor):
# pylint: disable=arguments-differ
"""
Apply dropout to input tensor.
Parameters
----------
input_tensor: ``torch.FloatTensor``
A tensor of shape ``(batch_size, num_timesteps, embedding_dim)``
Returns
-------
... | python | def forward(self, input_tensor):
# pylint: disable=arguments-differ
"""
Apply dropout to input tensor.
Parameters
----------
input_tensor: ``torch.FloatTensor``
A tensor of shape ``(batch_size, num_timesteps, embedding_dim)``
Returns
-------
... | [
"def",
"forward",
"(",
"self",
",",
"input_tensor",
")",
":",
"# pylint: disable=arguments-differ",
"ones",
"=",
"input_tensor",
".",
"data",
".",
"new_ones",
"(",
"input_tensor",
".",
"shape",
"[",
"0",
"]",
",",
"input_tensor",
".",
"shape",
"[",
"-",
"1",... | Apply dropout to input tensor.
Parameters
----------
input_tensor: ``torch.FloatTensor``
A tensor of shape ``(batch_size, num_timesteps, embedding_dim)``
Returns
-------
output: ``torch.FloatTensor``
A tensor of shape ``(batch_size, num_timesteps... | [
"Apply",
"dropout",
"to",
"input",
"tensor",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/modules/input_variational_dropout.py#L13-L34 |
23,125 | allenai/allennlp | allennlp/training/metrics/metric.py | Metric.unwrap_to_tensors | def unwrap_to_tensors(*tensors: torch.Tensor):
"""
If you actually passed gradient-tracking Tensors to a Metric, there will be
a huge memory leak, because it will prevent garbage collection for the computation
graph. This method ensures that you're using tensors directly and that they ar... | python | def unwrap_to_tensors(*tensors: torch.Tensor):
"""
If you actually passed gradient-tracking Tensors to a Metric, there will be
a huge memory leak, because it will prevent garbage collection for the computation
graph. This method ensures that you're using tensors directly and that they ar... | [
"def",
"unwrap_to_tensors",
"(",
"*",
"tensors",
":",
"torch",
".",
"Tensor",
")",
":",
"return",
"(",
"x",
".",
"detach",
"(",
")",
".",
"cpu",
"(",
")",
"if",
"isinstance",
"(",
"x",
",",
"torch",
".",
"Tensor",
")",
"else",
"x",
"for",
"x",
"i... | If you actually passed gradient-tracking Tensors to a Metric, there will be
a huge memory leak, because it will prevent garbage collection for the computation
graph. This method ensures that you're using tensors directly and that they are on
the CPU. | [
"If",
"you",
"actually",
"passed",
"gradient",
"-",
"tracking",
"Tensors",
"to",
"a",
"Metric",
"there",
"will",
"be",
"a",
"huge",
"memory",
"leak",
"because",
"it",
"will",
"prevent",
"garbage",
"collection",
"for",
"the",
"computation",
"graph",
".",
"Thi... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/training/metrics/metric.py#L42-L49 |
23,126 | allenai/allennlp | allennlp/data/dataset_readers/dataset_utils/text2sql_utils.py | replace_variables | def replace_variables(sentence: List[str],
sentence_variables: Dict[str, str]) -> Tuple[List[str], List[str]]:
"""
Replaces abstract variables in text with their concrete counterparts.
"""
tokens = []
tags = []
for token in sentence:
if token not in sentence_variabl... | python | def replace_variables(sentence: List[str],
sentence_variables: Dict[str, str]) -> Tuple[List[str], List[str]]:
"""
Replaces abstract variables in text with their concrete counterparts.
"""
tokens = []
tags = []
for token in sentence:
if token not in sentence_variabl... | [
"def",
"replace_variables",
"(",
"sentence",
":",
"List",
"[",
"str",
"]",
",",
"sentence_variables",
":",
"Dict",
"[",
"str",
",",
"str",
"]",
")",
"->",
"Tuple",
"[",
"List",
"[",
"str",
"]",
",",
"List",
"[",
"str",
"]",
"]",
":",
"tokens",
"=",... | Replaces abstract variables in text with their concrete counterparts. | [
"Replaces",
"abstract",
"variables",
"in",
"text",
"with",
"their",
"concrete",
"counterparts",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/data/dataset_readers/dataset_utils/text2sql_utils.py#L65-L80 |
23,127 | allenai/allennlp | allennlp/data/dataset_readers/dataset_utils/text2sql_utils.py | clean_and_split_sql | def clean_and_split_sql(sql: str) -> List[str]:
"""
Cleans up and unifies a SQL query. This involves unifying quoted strings
and splitting brackets which aren't formatted consistently in the data.
"""
sql_tokens: List[str] = []
for token in sql.strip().split():
token = token.replace('"',... | python | def clean_and_split_sql(sql: str) -> List[str]:
"""
Cleans up and unifies a SQL query. This involves unifying quoted strings
and splitting brackets which aren't formatted consistently in the data.
"""
sql_tokens: List[str] = []
for token in sql.strip().split():
token = token.replace('"',... | [
"def",
"clean_and_split_sql",
"(",
"sql",
":",
"str",
")",
"->",
"List",
"[",
"str",
"]",
":",
"sql_tokens",
":",
"List",
"[",
"str",
"]",
"=",
"[",
"]",
"for",
"token",
"in",
"sql",
".",
"strip",
"(",
")",
".",
"split",
"(",
")",
":",
"token",
... | Cleans up and unifies a SQL query. This involves unifying quoted strings
and splitting brackets which aren't formatted consistently in the data. | [
"Cleans",
"up",
"and",
"unifies",
"a",
"SQL",
"query",
".",
"This",
"involves",
"unifying",
"quoted",
"strings",
"and",
"splitting",
"brackets",
"which",
"aren",
"t",
"formatted",
"consistently",
"in",
"the",
"data",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/data/dataset_readers/dataset_utils/text2sql_utils.py#L89-L102 |
23,128 | allenai/allennlp | allennlp/data/dataset_readers/dataset_utils/text2sql_utils.py | resolve_primary_keys_in_schema | def resolve_primary_keys_in_schema(sql_tokens: List[str],
schema: Dict[str, List[TableColumn]]) -> List[str]:
"""
Some examples in the text2sql datasets use ID as a column reference to the
column of a table which has a primary key. This causes problems if you are trying
... | python | def resolve_primary_keys_in_schema(sql_tokens: List[str],
schema: Dict[str, List[TableColumn]]) -> List[str]:
"""
Some examples in the text2sql datasets use ID as a column reference to the
column of a table which has a primary key. This causes problems if you are trying
... | [
"def",
"resolve_primary_keys_in_schema",
"(",
"sql_tokens",
":",
"List",
"[",
"str",
"]",
",",
"schema",
":",
"Dict",
"[",
"str",
",",
"List",
"[",
"TableColumn",
"]",
"]",
")",
"->",
"List",
"[",
"str",
"]",
":",
"primary_keys_for_tables",
"=",
"{",
"na... | Some examples in the text2sql datasets use ID as a column reference to the
column of a table which has a primary key. This causes problems if you are trying
to constrain a grammar to only produce the column names directly, because you don't
know what ID refers to. So instead of dealing with that, we just re... | [
"Some",
"examples",
"in",
"the",
"text2sql",
"datasets",
"use",
"ID",
"as",
"a",
"column",
"reference",
"to",
"the",
"column",
"of",
"a",
"table",
"which",
"has",
"a",
"primary",
"key",
".",
"This",
"causes",
"problems",
"if",
"you",
"are",
"trying",
"to... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/data/dataset_readers/dataset_utils/text2sql_utils.py#L104-L121 |
23,129 | allenai/allennlp | allennlp/modules/encoder_base.py | _EncoderBase.sort_and_run_forward | def sort_and_run_forward(self,
module: Callable[[PackedSequence, Optional[RnnState]],
Tuple[Union[PackedSequence, torch.Tensor], RnnState]],
inputs: torch.Tensor,
mask: torch.Tensor,
... | python | def sort_and_run_forward(self,
module: Callable[[PackedSequence, Optional[RnnState]],
Tuple[Union[PackedSequence, torch.Tensor], RnnState]],
inputs: torch.Tensor,
mask: torch.Tensor,
... | [
"def",
"sort_and_run_forward",
"(",
"self",
",",
"module",
":",
"Callable",
"[",
"[",
"PackedSequence",
",",
"Optional",
"[",
"RnnState",
"]",
"]",
",",
"Tuple",
"[",
"Union",
"[",
"PackedSequence",
",",
"torch",
".",
"Tensor",
"]",
",",
"RnnState",
"]",
... | This function exists because Pytorch RNNs require that their inputs be sorted
before being passed as input. As all of our Seq2xxxEncoders use this functionality,
it is provided in a base class. This method can be called on any module which
takes as input a ``PackedSequence`` and some ``hidden_st... | [
"This",
"function",
"exists",
"because",
"Pytorch",
"RNNs",
"require",
"that",
"their",
"inputs",
"be",
"sorted",
"before",
"being",
"passed",
"as",
"input",
".",
"As",
"all",
"of",
"our",
"Seq2xxxEncoders",
"use",
"this",
"functionality",
"it",
"is",
"provide... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/modules/encoder_base.py#L32-L118 |
23,130 | allenai/allennlp | allennlp/modules/encoder_base.py | _EncoderBase._get_initial_states | def _get_initial_states(self,
batch_size: int,
num_valid: int,
sorting_indices: torch.LongTensor) -> Optional[RnnState]:
"""
Returns an initial state for use in an RNN. Additionally, this method handles
the batch... | python | def _get_initial_states(self,
batch_size: int,
num_valid: int,
sorting_indices: torch.LongTensor) -> Optional[RnnState]:
"""
Returns an initial state for use in an RNN. Additionally, this method handles
the batch... | [
"def",
"_get_initial_states",
"(",
"self",
",",
"batch_size",
":",
"int",
",",
"num_valid",
":",
"int",
",",
"sorting_indices",
":",
"torch",
".",
"LongTensor",
")",
"->",
"Optional",
"[",
"RnnState",
"]",
":",
"# We don't know the state sizes the first time calling... | Returns an initial state for use in an RNN. Additionally, this method handles
the batch size changing across calls by mutating the state to append initial states
for new elements in the batch. Finally, it also handles sorting the states
with respect to the sequence lengths of elements in the bat... | [
"Returns",
"an",
"initial",
"state",
"for",
"use",
"in",
"an",
"RNN",
".",
"Additionally",
"this",
"method",
"handles",
"the",
"batch",
"size",
"changing",
"across",
"calls",
"by",
"mutating",
"the",
"state",
"to",
"append",
"initial",
"states",
"for",
"new"... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/modules/encoder_base.py#L120-L205 |
23,131 | allenai/allennlp | allennlp/modules/encoder_base.py | _EncoderBase._update_states | def _update_states(self,
final_states: RnnStateStorage,
restoration_indices: torch.LongTensor) -> None:
"""
After the RNN has run forward, the states need to be updated.
This method just sets the state to the updated new state, performing
sev... | python | def _update_states(self,
final_states: RnnStateStorage,
restoration_indices: torch.LongTensor) -> None:
"""
After the RNN has run forward, the states need to be updated.
This method just sets the state to the updated new state, performing
sev... | [
"def",
"_update_states",
"(",
"self",
",",
"final_states",
":",
"RnnStateStorage",
",",
"restoration_indices",
":",
"torch",
".",
"LongTensor",
")",
"->",
"None",
":",
"# TODO(Mark): seems weird to sort here, but append zeros in the subclasses.",
"# which way around is best?",
... | After the RNN has run forward, the states need to be updated.
This method just sets the state to the updated new state, performing
several pieces of book-keeping along the way - namely, unsorting the
states and ensuring that the states of completely padded sequences are
not updated. Fina... | [
"After",
"the",
"RNN",
"has",
"run",
"forward",
"the",
"states",
"need",
"to",
"be",
"updated",
".",
"This",
"method",
"just",
"sets",
"the",
"state",
"to",
"the",
"updated",
"new",
"state",
"performing",
"several",
"pieces",
"of",
"book",
"-",
"keeping",
... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/modules/encoder_base.py#L207-L282 |
23,132 | allenai/allennlp | allennlp/tools/wikitables_evaluator.py | to_value | def to_value(original_string, corenlp_value=None):
"""Convert the string to Value object.
Args:
original_string (basestring): Original string
corenlp_value (basestring): Optional value returned from CoreNLP
Returns:
Value
"""
if isinstance(original_string, Value):
# ... | python | def to_value(original_string, corenlp_value=None):
"""Convert the string to Value object.
Args:
original_string (basestring): Original string
corenlp_value (basestring): Optional value returned from CoreNLP
Returns:
Value
"""
if isinstance(original_string, Value):
# ... | [
"def",
"to_value",
"(",
"original_string",
",",
"corenlp_value",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"original_string",
",",
"Value",
")",
":",
"# Already a Value",
"return",
"original_string",
"if",
"not",
"corenlp_value",
":",
"corenlp_value",
"=",
... | Convert the string to Value object.
Args:
original_string (basestring): Original string
corenlp_value (basestring): Optional value returned from CoreNLP
Returns:
Value | [
"Convert",
"the",
"string",
"to",
"Value",
"object",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/tools/wikitables_evaluator.py#L252-L278 |
23,133 | allenai/allennlp | allennlp/tools/wikitables_evaluator.py | to_value_list | def to_value_list(original_strings, corenlp_values=None):
"""Convert a list of strings to a list of Values
Args:
original_strings (list[basestring])
corenlp_values (list[basestring or None])
Returns:
list[Value]
"""
assert isinstance(original_strings, (list, tuple, set))
... | python | def to_value_list(original_strings, corenlp_values=None):
"""Convert a list of strings to a list of Values
Args:
original_strings (list[basestring])
corenlp_values (list[basestring or None])
Returns:
list[Value]
"""
assert isinstance(original_strings, (list, tuple, set))
... | [
"def",
"to_value_list",
"(",
"original_strings",
",",
"corenlp_values",
"=",
"None",
")",
":",
"assert",
"isinstance",
"(",
"original_strings",
",",
"(",
"list",
",",
"tuple",
",",
"set",
")",
")",
"if",
"corenlp_values",
"is",
"not",
"None",
":",
"assert",
... | Convert a list of strings to a list of Values
Args:
original_strings (list[basestring])
corenlp_values (list[basestring or None])
Returns:
list[Value] | [
"Convert",
"a",
"list",
"of",
"strings",
"to",
"a",
"list",
"of",
"Values"
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/tools/wikitables_evaluator.py#L280-L296 |
23,134 | allenai/allennlp | allennlp/tools/wikitables_evaluator.py | check_denotation | def check_denotation(target_values, predicted_values):
"""Return True if the predicted denotation is correct.
Args:
target_values (list[Value])
predicted_values (list[Value])
Returns:
bool
"""
# Check size
if len(target_values) != len(predicted_values):
return Fa... | python | def check_denotation(target_values, predicted_values):
"""Return True if the predicted denotation is correct.
Args:
target_values (list[Value])
predicted_values (list[Value])
Returns:
bool
"""
# Check size
if len(target_values) != len(predicted_values):
return Fa... | [
"def",
"check_denotation",
"(",
"target_values",
",",
"predicted_values",
")",
":",
"# Check size",
"if",
"len",
"(",
"target_values",
")",
"!=",
"len",
"(",
"predicted_values",
")",
":",
"return",
"False",
"# Check items",
"for",
"target",
"in",
"target_values",
... | Return True if the predicted denotation is correct.
Args:
target_values (list[Value])
predicted_values (list[Value])
Returns:
bool | [
"Return",
"True",
"if",
"the",
"predicted",
"denotation",
"is",
"correct",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/tools/wikitables_evaluator.py#L301-L317 |
23,135 | allenai/allennlp | allennlp/tools/wikitables_evaluator.py | NumberValue.parse | def parse(text):
"""Try to parse into a number.
Return:
the number (int or float) if successful; otherwise None.
"""
try:
return int(text)
except ValueError:
try:
amount = float(text)
assert not isnan(amount) an... | python | def parse(text):
"""Try to parse into a number.
Return:
the number (int or float) if successful; otherwise None.
"""
try:
return int(text)
except ValueError:
try:
amount = float(text)
assert not isnan(amount) an... | [
"def",
"parse",
"(",
"text",
")",
":",
"try",
":",
"return",
"int",
"(",
"text",
")",
"except",
"ValueError",
":",
"try",
":",
"amount",
"=",
"float",
"(",
"text",
")",
"assert",
"not",
"isnan",
"(",
"amount",
")",
"and",
"not",
"isinf",
"(",
"amou... | Try to parse into a number.
Return:
the number (int or float) if successful; otherwise None. | [
"Try",
"to",
"parse",
"into",
"a",
"number",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/tools/wikitables_evaluator.py#L169-L183 |
23,136 | allenai/allennlp | allennlp/tools/wikitables_evaluator.py | DateValue.parse | def parse(text):
"""Try to parse into a date.
Return:
tuple (year, month, date) if successful; otherwise None.
"""
try:
ymd = text.lower().split('-')
assert len(ymd) == 3
year = -1 if ymd[0] in ('xx', 'xxxx') else int(ymd[0])
m... | python | def parse(text):
"""Try to parse into a date.
Return:
tuple (year, month, date) if successful; otherwise None.
"""
try:
ymd = text.lower().split('-')
assert len(ymd) == 3
year = -1 if ymd[0] in ('xx', 'xxxx') else int(ymd[0])
m... | [
"def",
"parse",
"(",
"text",
")",
":",
"try",
":",
"ymd",
"=",
"text",
".",
"lower",
"(",
")",
".",
"split",
"(",
"'-'",
")",
"assert",
"len",
"(",
"ymd",
")",
"==",
"3",
"year",
"=",
"-",
"1",
"if",
"ymd",
"[",
"0",
"]",
"in",
"(",
"'xx'",... | Try to parse into a date.
Return:
tuple (year, month, date) if successful; otherwise None. | [
"Try",
"to",
"parse",
"into",
"a",
"date",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/tools/wikitables_evaluator.py#L230-L247 |
23,137 | allenai/allennlp | allennlp/modules/span_extractors/span_extractor.py | SpanExtractor.forward | def forward(self, # pylint: disable=arguments-differ
sequence_tensor: torch.FloatTensor,
span_indices: torch.LongTensor,
sequence_mask: torch.LongTensor = None,
span_indices_mask: torch.LongTensor = None):
"""
Given a sequence tensor, extra... | python | def forward(self, # pylint: disable=arguments-differ
sequence_tensor: torch.FloatTensor,
span_indices: torch.LongTensor,
sequence_mask: torch.LongTensor = None,
span_indices_mask: torch.LongTensor = None):
"""
Given a sequence tensor, extra... | [
"def",
"forward",
"(",
"self",
",",
"# pylint: disable=arguments-differ",
"sequence_tensor",
":",
"torch",
".",
"FloatTensor",
",",
"span_indices",
":",
"torch",
".",
"LongTensor",
",",
"sequence_mask",
":",
"torch",
".",
"LongTensor",
"=",
"None",
",",
"span_indi... | Given a sequence tensor, extract spans and return representations of
them. Span representation can be computed in many different ways,
such as concatenation of the start and end spans, attention over the
vectors contained inside the span, etc.
Parameters
----------
seque... | [
"Given",
"a",
"sequence",
"tensor",
"extract",
"spans",
"and",
"return",
"representations",
"of",
"them",
".",
"Span",
"representation",
"can",
"be",
"computed",
"in",
"many",
"different",
"ways",
"such",
"as",
"concatenation",
"of",
"the",
"start",
"and",
"en... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/modules/span_extractors/span_extractor.py#L19-L53 |
23,138 | allenai/allennlp | allennlp/state_machines/trainers/decoder_trainer.py | DecoderTrainer.decode | def decode(self,
initial_state: State,
transition_function: TransitionFunction,
supervision: SupervisionType) -> Dict[str, torch.Tensor]:
"""
Takes an initial state object, a means of transitioning from state to state, and a
supervision signal, and us... | python | def decode(self,
initial_state: State,
transition_function: TransitionFunction,
supervision: SupervisionType) -> Dict[str, torch.Tensor]:
"""
Takes an initial state object, a means of transitioning from state to state, and a
supervision signal, and us... | [
"def",
"decode",
"(",
"self",
",",
"initial_state",
":",
"State",
",",
"transition_function",
":",
"TransitionFunction",
",",
"supervision",
":",
"SupervisionType",
")",
"->",
"Dict",
"[",
"str",
",",
"torch",
".",
"Tensor",
"]",
":",
"raise",
"NotImplementedE... | Takes an initial state object, a means of transitioning from state to state, and a
supervision signal, and uses the supervision to train the transition function to pick
"good" states.
This function should typically return a ``loss`` key during training, which the ``Model``
will use as i... | [
"Takes",
"an",
"initial",
"state",
"object",
"a",
"means",
"of",
"transitioning",
"from",
"state",
"to",
"state",
"and",
"a",
"supervision",
"signal",
"and",
"uses",
"the",
"supervision",
"to",
"train",
"the",
"transition",
"function",
"to",
"pick",
"good",
... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/state_machines/trainers/decoder_trainer.py#L24-L52 |
23,139 | allenai/allennlp | allennlp/training/scheduler.py | Scheduler.state_dict | def state_dict(self) -> Dict[str, Any]:
"""
Returns the state of the scheduler as a ``dict``.
"""
return {key: value for key, value in self.__dict__.items() if key != 'optimizer'} | python | def state_dict(self) -> Dict[str, Any]:
"""
Returns the state of the scheduler as a ``dict``.
"""
return {key: value for key, value in self.__dict__.items() if key != 'optimizer'} | [
"def",
"state_dict",
"(",
"self",
")",
"->",
"Dict",
"[",
"str",
",",
"Any",
"]",
":",
"return",
"{",
"key",
":",
"value",
"for",
"key",
",",
"value",
"in",
"self",
".",
"__dict__",
".",
"items",
"(",
")",
"if",
"key",
"!=",
"'optimizer'",
"}"
] | Returns the state of the scheduler as a ``dict``. | [
"Returns",
"the",
"state",
"of",
"the",
"scheduler",
"as",
"a",
"dict",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/training/scheduler.py#L49-L53 |
23,140 | allenai/allennlp | allennlp/training/scheduler.py | Scheduler.load_state_dict | def load_state_dict(self, state_dict: Dict[str, Any]) -> None:
"""
Load the schedulers state.
Parameters
----------
state_dict : ``Dict[str, Any]``
Scheduler state. Should be an object returned from a call to ``state_dict``.
"""
self.__dict__.update(s... | python | def load_state_dict(self, state_dict: Dict[str, Any]) -> None:
"""
Load the schedulers state.
Parameters
----------
state_dict : ``Dict[str, Any]``
Scheduler state. Should be an object returned from a call to ``state_dict``.
"""
self.__dict__.update(s... | [
"def",
"load_state_dict",
"(",
"self",
",",
"state_dict",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
")",
"->",
"None",
":",
"self",
".",
"__dict__",
".",
"update",
"(",
"state_dict",
")"
] | Load the schedulers state.
Parameters
----------
state_dict : ``Dict[str, Any]``
Scheduler state. Should be an object returned from a call to ``state_dict``. | [
"Load",
"the",
"schedulers",
"state",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/training/scheduler.py#L55-L64 |
23,141 | allenai/allennlp | allennlp/models/reading_comprehension/bidaf_ensemble.py | ensemble | def ensemble(subresults: List[Dict[str, torch.Tensor]]) -> torch.Tensor:
"""
Identifies the best prediction given the results from the submodels.
Parameters
----------
subresults : List[Dict[str, torch.Tensor]]
Results of each submodel.
Returns
-------
The index of the best sub... | python | def ensemble(subresults: List[Dict[str, torch.Tensor]]) -> torch.Tensor:
"""
Identifies the best prediction given the results from the submodels.
Parameters
----------
subresults : List[Dict[str, torch.Tensor]]
Results of each submodel.
Returns
-------
The index of the best sub... | [
"def",
"ensemble",
"(",
"subresults",
":",
"List",
"[",
"Dict",
"[",
"str",
",",
"torch",
".",
"Tensor",
"]",
"]",
")",
"->",
"torch",
".",
"Tensor",
":",
"# Choose the highest average confidence span.",
"span_start_probs",
"=",
"sum",
"(",
"subresult",
"[",
... | Identifies the best prediction given the results from the submodels.
Parameters
----------
subresults : List[Dict[str, torch.Tensor]]
Results of each submodel.
Returns
-------
The index of the best submodel. | [
"Identifies",
"the",
"best",
"prediction",
"given",
"the",
"results",
"from",
"the",
"submodels",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/models/reading_comprehension/bidaf_ensemble.py#L124-L142 |
23,142 | allenai/allennlp | allennlp/modules/elmo_lstm.py | ElmoLstm.load_weights | def load_weights(self, weight_file: str) -> None:
"""
Load the pre-trained weights from the file.
"""
requires_grad = self.requires_grad
with h5py.File(cached_path(weight_file), 'r') as fin:
for i_layer, lstms in enumerate(
zip(self.forward_layers... | python | def load_weights(self, weight_file: str) -> None:
"""
Load the pre-trained weights from the file.
"""
requires_grad = self.requires_grad
with h5py.File(cached_path(weight_file), 'r') as fin:
for i_layer, lstms in enumerate(
zip(self.forward_layers... | [
"def",
"load_weights",
"(",
"self",
",",
"weight_file",
":",
"str",
")",
"->",
"None",
":",
"requires_grad",
"=",
"self",
".",
"requires_grad",
"with",
"h5py",
".",
"File",
"(",
"cached_path",
"(",
"weight_file",
")",
",",
"'r'",
")",
"as",
"fin",
":",
... | Load the pre-trained weights from the file. | [
"Load",
"the",
"pre",
"-",
"trained",
"weights",
"from",
"the",
"file",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/modules/elmo_lstm.py#L243-L301 |
23,143 | allenai/allennlp | allennlp/semparse/type_declarations/type_declaration.py | ComplexType.return_type | def return_type(self) -> Type:
"""
Gives the final return type for this function. If the function takes a single argument,
this is just ``self.second``. If the function takes multiple arguments and returns a basic
type, this should be the final ``.second`` after following all complex t... | python | def return_type(self) -> Type:
"""
Gives the final return type for this function. If the function takes a single argument,
this is just ``self.second``. If the function takes multiple arguments and returns a basic
type, this should be the final ``.second`` after following all complex t... | [
"def",
"return_type",
"(",
"self",
")",
"->",
"Type",
":",
"return_type",
"=",
"self",
".",
"second",
"while",
"isinstance",
"(",
"return_type",
",",
"ComplexType",
")",
":",
"return_type",
"=",
"return_type",
".",
"second",
"return",
"return_type"
] | Gives the final return type for this function. If the function takes a single argument,
this is just ``self.second``. If the function takes multiple arguments and returns a basic
type, this should be the final ``.second`` after following all complex types. That is the
implementation here in t... | [
"Gives",
"the",
"final",
"return",
"type",
"for",
"this",
"function",
".",
"If",
"the",
"function",
"takes",
"a",
"single",
"argument",
"this",
"is",
"just",
"self",
".",
"second",
".",
"If",
"the",
"function",
"takes",
"multiple",
"arguments",
"and",
"ret... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/type_declarations/type_declaration.py#L29-L40 |
23,144 | allenai/allennlp | allennlp/semparse/type_declarations/type_declaration.py | ComplexType.argument_types | def argument_types(self) -> List[Type]:
"""
Gives the types of all arguments to this function. For functions returning a basic type,
we grab all ``.first`` types until ``.second`` is no longer a ``ComplexType``. That logic
is implemented here in the base class. If you have a higher-or... | python | def argument_types(self) -> List[Type]:
"""
Gives the types of all arguments to this function. For functions returning a basic type,
we grab all ``.first`` types until ``.second`` is no longer a ``ComplexType``. That logic
is implemented here in the base class. If you have a higher-or... | [
"def",
"argument_types",
"(",
"self",
")",
"->",
"List",
"[",
"Type",
"]",
":",
"arguments",
"=",
"[",
"self",
".",
"first",
"]",
"remaining_type",
"=",
"self",
".",
"second",
"while",
"isinstance",
"(",
"remaining_type",
",",
"ComplexType",
")",
":",
"a... | Gives the types of all arguments to this function. For functions returning a basic type,
we grab all ``.first`` types until ``.second`` is no longer a ``ComplexType``. That logic
is implemented here in the base class. If you have a higher-order function that returns a
function itself, you nee... | [
"Gives",
"the",
"types",
"of",
"all",
"arguments",
"to",
"this",
"function",
".",
"For",
"functions",
"returning",
"a",
"basic",
"type",
"we",
"grab",
"all",
".",
"first",
"types",
"until",
".",
"second",
"is",
"no",
"longer",
"a",
"ComplexType",
".",
"T... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/type_declarations/type_declaration.py#L42-L54 |
23,145 | allenai/allennlp | allennlp/semparse/type_declarations/type_declaration.py | ComplexType.substitute_any_type | def substitute_any_type(self, basic_types: Set[BasicType]) -> List[Type]:
"""
Takes a set of ``BasicTypes`` and replaces any instances of ``ANY_TYPE`` inside this
complex type with each of those basic types.
"""
substitutions = []
for first_type in substitute_any_type(sel... | python | def substitute_any_type(self, basic_types: Set[BasicType]) -> List[Type]:
"""
Takes a set of ``BasicTypes`` and replaces any instances of ``ANY_TYPE`` inside this
complex type with each of those basic types.
"""
substitutions = []
for first_type in substitute_any_type(sel... | [
"def",
"substitute_any_type",
"(",
"self",
",",
"basic_types",
":",
"Set",
"[",
"BasicType",
"]",
")",
"->",
"List",
"[",
"Type",
"]",
":",
"substitutions",
"=",
"[",
"]",
"for",
"first_type",
"in",
"substitute_any_type",
"(",
"self",
".",
"first",
",",
... | Takes a set of ``BasicTypes`` and replaces any instances of ``ANY_TYPE`` inside this
complex type with each of those basic types. | [
"Takes",
"a",
"set",
"of",
"BasicTypes",
"and",
"replaces",
"any",
"instances",
"of",
"ANY_TYPE",
"inside",
"this",
"complex",
"type",
"with",
"each",
"of",
"those",
"basic",
"types",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/type_declarations/type_declaration.py#L56-L65 |
23,146 | allenai/allennlp | allennlp/training/tensorboard_writer.py | TensorboardWriter.log_parameter_and_gradient_statistics | def log_parameter_and_gradient_statistics(self, # pylint: disable=invalid-name
model: Model,
batch_grad_norm: float) -> None:
"""
Send the mean and std of all parameters and gradients to tensorboard, as well
... | python | def log_parameter_and_gradient_statistics(self, # pylint: disable=invalid-name
model: Model,
batch_grad_norm: float) -> None:
"""
Send the mean and std of all parameters and gradients to tensorboard, as well
... | [
"def",
"log_parameter_and_gradient_statistics",
"(",
"self",
",",
"# pylint: disable=invalid-name",
"model",
":",
"Model",
",",
"batch_grad_norm",
":",
"float",
")",
"->",
"None",
":",
"if",
"self",
".",
"_should_log_parameter_statistics",
":",
"# Log parameter values to ... | Send the mean and std of all parameters and gradients to tensorboard, as well
as logging the average gradient norm. | [
"Send",
"the",
"mean",
"and",
"std",
"of",
"all",
"parameters",
"and",
"gradients",
"to",
"tensorboard",
"as",
"well",
"as",
"logging",
"the",
"average",
"gradient",
"norm",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/training/tensorboard_writer.py#L84-L112 |
23,147 | allenai/allennlp | allennlp/training/tensorboard_writer.py | TensorboardWriter.log_learning_rates | def log_learning_rates(self,
model: Model,
optimizer: torch.optim.Optimizer):
"""
Send current parameter specific learning rates to tensorboard
"""
if self._should_log_learning_rate:
# optimizer stores lr info keyed by par... | python | def log_learning_rates(self,
model: Model,
optimizer: torch.optim.Optimizer):
"""
Send current parameter specific learning rates to tensorboard
"""
if self._should_log_learning_rate:
# optimizer stores lr info keyed by par... | [
"def",
"log_learning_rates",
"(",
"self",
",",
"model",
":",
"Model",
",",
"optimizer",
":",
"torch",
".",
"optim",
".",
"Optimizer",
")",
":",
"if",
"self",
".",
"_should_log_learning_rate",
":",
"# optimizer stores lr info keyed by parameter tensor",
"# we want to l... | Send current parameter specific learning rates to tensorboard | [
"Send",
"current",
"parameter",
"specific",
"learning",
"rates",
"to",
"tensorboard"
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/training/tensorboard_writer.py#L114-L131 |
23,148 | allenai/allennlp | allennlp/training/tensorboard_writer.py | TensorboardWriter.log_histograms | def log_histograms(self, model: Model, histogram_parameters: Set[str]) -> None:
"""
Send histograms of parameters to tensorboard.
"""
for name, param in model.named_parameters():
if name in histogram_parameters:
self.add_train_histogram("parameter_histogram/" ... | python | def log_histograms(self, model: Model, histogram_parameters: Set[str]) -> None:
"""
Send histograms of parameters to tensorboard.
"""
for name, param in model.named_parameters():
if name in histogram_parameters:
self.add_train_histogram("parameter_histogram/" ... | [
"def",
"log_histograms",
"(",
"self",
",",
"model",
":",
"Model",
",",
"histogram_parameters",
":",
"Set",
"[",
"str",
"]",
")",
"->",
"None",
":",
"for",
"name",
",",
"param",
"in",
"model",
".",
"named_parameters",
"(",
")",
":",
"if",
"name",
"in",
... | Send histograms of parameters to tensorboard. | [
"Send",
"histograms",
"of",
"parameters",
"to",
"tensorboard",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/training/tensorboard_writer.py#L133-L139 |
23,149 | allenai/allennlp | allennlp/semparse/contexts/quarel_utils.py | align_entities | def align_entities(extracted: List[str],
literals: JsonDict,
stemmer: NltkPorterStemmer) -> List[str]:
"""
Use stemming to attempt alignment between extracted world and given world literals.
If more words align to one world vs the other, it's considered aligned.
"""... | python | def align_entities(extracted: List[str],
literals: JsonDict,
stemmer: NltkPorterStemmer) -> List[str]:
"""
Use stemming to attempt alignment between extracted world and given world literals.
If more words align to one world vs the other, it's considered aligned.
"""... | [
"def",
"align_entities",
"(",
"extracted",
":",
"List",
"[",
"str",
"]",
",",
"literals",
":",
"JsonDict",
",",
"stemmer",
":",
"NltkPorterStemmer",
")",
"->",
"List",
"[",
"str",
"]",
":",
"literal_keys",
"=",
"list",
"(",
"literals",
".",
"keys",
"(",
... | Use stemming to attempt alignment between extracted world and given world literals.
If more words align to one world vs the other, it's considered aligned. | [
"Use",
"stemming",
"to",
"attempt",
"alignment",
"between",
"extracted",
"world",
"and",
"given",
"world",
"literals",
".",
"If",
"more",
"words",
"align",
"to",
"one",
"world",
"vs",
"the",
"other",
"it",
"s",
"considered",
"aligned",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/contexts/quarel_utils.py#L360-L378 |
23,150 | allenai/allennlp | allennlp/modules/bimpm_matching.py | multi_perspective_match | def multi_perspective_match(vector1: torch.Tensor,
vector2: torch.Tensor,
weight: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
"""
Calculate multi-perspective cosine matching between time-steps of vectors
of the same length.
Parameters
... | python | def multi_perspective_match(vector1: torch.Tensor,
vector2: torch.Tensor,
weight: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
"""
Calculate multi-perspective cosine matching between time-steps of vectors
of the same length.
Parameters
... | [
"def",
"multi_perspective_match",
"(",
"vector1",
":",
"torch",
".",
"Tensor",
",",
"vector2",
":",
"torch",
".",
"Tensor",
",",
"weight",
":",
"torch",
".",
"Tensor",
")",
"->",
"Tuple",
"[",
"torch",
".",
"Tensor",
",",
"torch",
".",
"Tensor",
"]",
"... | Calculate multi-perspective cosine matching between time-steps of vectors
of the same length.
Parameters
----------
vector1 : ``torch.Tensor``
A tensor of shape ``(batch, seq_len, hidden_size)``
vector2 : ``torch.Tensor``
A tensor of shape ``(batch, seq_len or 1, hidden_size)``
... | [
"Calculate",
"multi",
"-",
"perspective",
"cosine",
"matching",
"between",
"time",
"-",
"steps",
"of",
"vectors",
"of",
"the",
"same",
"length",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/modules/bimpm_matching.py#L16-L53 |
23,151 | allenai/allennlp | allennlp/modules/bimpm_matching.py | multi_perspective_match_pairwise | def multi_perspective_match_pairwise(vector1: torch.Tensor,
vector2: torch.Tensor,
weight: torch.Tensor,
eps: float = 1e-8) -> torch.Tensor:
"""
Calculate multi-perspective cosine matching between each... | python | def multi_perspective_match_pairwise(vector1: torch.Tensor,
vector2: torch.Tensor,
weight: torch.Tensor,
eps: float = 1e-8) -> torch.Tensor:
"""
Calculate multi-perspective cosine matching between each... | [
"def",
"multi_perspective_match_pairwise",
"(",
"vector1",
":",
"torch",
".",
"Tensor",
",",
"vector2",
":",
"torch",
".",
"Tensor",
",",
"weight",
":",
"torch",
".",
"Tensor",
",",
"eps",
":",
"float",
"=",
"1e-8",
")",
"->",
"torch",
".",
"Tensor",
":"... | Calculate multi-perspective cosine matching between each time step of
one vector and each time step of another vector.
Parameters
----------
vector1 : ``torch.Tensor``
A tensor of shape ``(batch, seq_len1, hidden_size)``
vector2 : ``torch.Tensor``
A tensor of shape ``(batch, seq_len... | [
"Calculate",
"multi",
"-",
"perspective",
"cosine",
"matching",
"between",
"each",
"time",
"step",
"of",
"one",
"vector",
"and",
"each",
"time",
"step",
"of",
"another",
"vector",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/modules/bimpm_matching.py#L56-L98 |
23,152 | allenai/allennlp | allennlp/semparse/contexts/atis_tables.py | get_date_from_utterance | def get_date_from_utterance(tokenized_utterance: List[Token],
year: int = 1993) -> List[datetime]:
"""
When the year is not explicitly mentioned in the utterance, the query assumes that
it is 1993 so we do the same here. If there is no mention of the month or day then
we do n... | python | def get_date_from_utterance(tokenized_utterance: List[Token],
year: int = 1993) -> List[datetime]:
"""
When the year is not explicitly mentioned in the utterance, the query assumes that
it is 1993 so we do the same here. If there is no mention of the month or day then
we do n... | [
"def",
"get_date_from_utterance",
"(",
"tokenized_utterance",
":",
"List",
"[",
"Token",
"]",
",",
"year",
":",
"int",
"=",
"1993",
")",
"->",
"List",
"[",
"datetime",
"]",
":",
"dates",
"=",
"[",
"]",
"utterance",
"=",
"' '",
".",
"join",
"(",
"[",
... | When the year is not explicitly mentioned in the utterance, the query assumes that
it is 1993 so we do the same here. If there is no mention of the month or day then
we do not return any dates from the utterance. | [
"When",
"the",
"year",
"is",
"not",
"explicitly",
"mentioned",
"in",
"the",
"utterance",
"the",
"query",
"assumes",
"that",
"it",
"is",
"1993",
"so",
"we",
"do",
"the",
"same",
"here",
".",
"If",
"there",
"is",
"no",
"mention",
"of",
"the",
"month",
"o... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/contexts/atis_tables.py#L79-L126 |
23,153 | allenai/allennlp | allennlp/semparse/contexts/atis_tables.py | get_numbers_from_utterance | def get_numbers_from_utterance(utterance: str, tokenized_utterance: List[Token]) -> Dict[str, List[int]]:
"""
Given an utterance, this function finds all the numbers that are in the action space. Since we need to
keep track of linking scores, we represent the numbers as a dictionary, where the keys are the ... | python | def get_numbers_from_utterance(utterance: str, tokenized_utterance: List[Token]) -> Dict[str, List[int]]:
"""
Given an utterance, this function finds all the numbers that are in the action space. Since we need to
keep track of linking scores, we represent the numbers as a dictionary, where the keys are the ... | [
"def",
"get_numbers_from_utterance",
"(",
"utterance",
":",
"str",
",",
"tokenized_utterance",
":",
"List",
"[",
"Token",
"]",
")",
"->",
"Dict",
"[",
"str",
",",
"List",
"[",
"int",
"]",
"]",
":",
"# When we use a regex to find numbers or strings, we need a mapping... | Given an utterance, this function finds all the numbers that are in the action space. Since we need to
keep track of linking scores, we represent the numbers as a dictionary, where the keys are the string
representation of the number and the values are lists of the token indices that triggers that number. | [
"Given",
"an",
"utterance",
"this",
"function",
"finds",
"all",
"the",
"numbers",
"that",
"are",
"in",
"the",
"action",
"space",
".",
"Since",
"we",
"need",
"to",
"keep",
"track",
"of",
"linking",
"scores",
"we",
"represent",
"the",
"numbers",
"as",
"a",
... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/contexts/atis_tables.py#L128-L170 |
23,154 | allenai/allennlp | allennlp/semparse/contexts/atis_tables.py | digit_to_query_time | def digit_to_query_time(digit: str) -> List[int]:
"""
Given a digit in the utterance, return a list of the times that it corresponds to.
"""
if len(digit) > 2:
return [int(digit), int(digit) + TWELVE_TO_TWENTY_FOUR]
elif int(digit) % 12 == 0:
return [0, 1200, 2400]
return [int(di... | python | def digit_to_query_time(digit: str) -> List[int]:
"""
Given a digit in the utterance, return a list of the times that it corresponds to.
"""
if len(digit) > 2:
return [int(digit), int(digit) + TWELVE_TO_TWENTY_FOUR]
elif int(digit) % 12 == 0:
return [0, 1200, 2400]
return [int(di... | [
"def",
"digit_to_query_time",
"(",
"digit",
":",
"str",
")",
"->",
"List",
"[",
"int",
"]",
":",
"if",
"len",
"(",
"digit",
")",
">",
"2",
":",
"return",
"[",
"int",
"(",
"digit",
")",
",",
"int",
"(",
"digit",
")",
"+",
"TWELVE_TO_TWENTY_FOUR",
"]... | Given a digit in the utterance, return a list of the times that it corresponds to. | [
"Given",
"a",
"digit",
"in",
"the",
"utterance",
"return",
"a",
"list",
"of",
"the",
"times",
"that",
"it",
"corresponds",
"to",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/contexts/atis_tables.py#L238-L247 |
23,155 | allenai/allennlp | allennlp/semparse/contexts/atis_tables.py | get_approximate_times | def get_approximate_times(times: List[int]) -> List[int]:
"""
Given a list of times that follow a word such as ``about``,
we return a list of times that could appear in the query as a result
of this. For example if ``about 7pm`` appears in the utterance, then
we also want to add ``1830`` and ``1930`... | python | def get_approximate_times(times: List[int]) -> List[int]:
"""
Given a list of times that follow a word such as ``about``,
we return a list of times that could appear in the query as a result
of this. For example if ``about 7pm`` appears in the utterance, then
we also want to add ``1830`` and ``1930`... | [
"def",
"get_approximate_times",
"(",
"times",
":",
"List",
"[",
"int",
"]",
")",
"->",
"List",
"[",
"int",
"]",
":",
"approximate_times",
"=",
"[",
"]",
"for",
"time",
"in",
"times",
":",
"hour",
"=",
"int",
"(",
"time",
"/",
"HOUR_TO_TWENTY_FOUR",
")"... | Given a list of times that follow a word such as ``about``,
we return a list of times that could appear in the query as a result
of this. For example if ``about 7pm`` appears in the utterance, then
we also want to add ``1830`` and ``1930``. | [
"Given",
"a",
"list",
"of",
"times",
"that",
"follow",
"a",
"word",
"such",
"as",
"about",
"we",
"return",
"a",
"list",
"of",
"times",
"that",
"could",
"appear",
"in",
"the",
"query",
"as",
"a",
"result",
"of",
"this",
".",
"For",
"example",
"if",
"a... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/contexts/atis_tables.py#L249-L268 |
23,156 | allenai/allennlp | allennlp/semparse/contexts/atis_tables.py | _time_regex_match | def _time_regex_match(regex: str,
utterance: str,
char_offset_to_token_index: Dict[int, int],
map_match_to_query_value: Callable[[str], List[int]],
indices_of_approximate_words: Set[int]) -> Dict[str, List[int]]:
r"""
Given ... | python | def _time_regex_match(regex: str,
utterance: str,
char_offset_to_token_index: Dict[int, int],
map_match_to_query_value: Callable[[str], List[int]],
indices_of_approximate_words: Set[int]) -> Dict[str, List[int]]:
r"""
Given ... | [
"def",
"_time_regex_match",
"(",
"regex",
":",
"str",
",",
"utterance",
":",
"str",
",",
"char_offset_to_token_index",
":",
"Dict",
"[",
"int",
",",
"int",
"]",
",",
"map_match_to_query_value",
":",
"Callable",
"[",
"[",
"str",
"]",
",",
"List",
"[",
"int"... | r"""
Given a regex for matching times in the utterance, we want to convert the matches
to the values that appear in the query and token indices they correspond to.
``char_offset_to_token_index`` is a dictionary that maps from the character offset to
the token index, we use this to look up what token a ... | [
"r",
"Given",
"a",
"regex",
"for",
"matching",
"times",
"in",
"the",
"utterance",
"we",
"want",
"to",
"convert",
"the",
"matches",
"to",
"the",
"values",
"that",
"appear",
"in",
"the",
"query",
"and",
"token",
"indices",
"they",
"correspond",
"to",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/contexts/atis_tables.py#L270-L304 |
23,157 | allenai/allennlp | allennlp/semparse/executors/sql_executor.py | SqlExecutor._evaluate_sql_query_subprocess | def _evaluate_sql_query_subprocess(self, predicted_query: str, sql_query_labels: List[str]) -> int:
"""
We evaluate here whether the predicted query and the query label evaluate to the
exact same table. This method is only called by the subprocess, so we just exit with
1 if it is correct... | python | def _evaluate_sql_query_subprocess(self, predicted_query: str, sql_query_labels: List[str]) -> int:
"""
We evaluate here whether the predicted query and the query label evaluate to the
exact same table. This method is only called by the subprocess, so we just exit with
1 if it is correct... | [
"def",
"_evaluate_sql_query_subprocess",
"(",
"self",
",",
"predicted_query",
":",
"str",
",",
"sql_query_labels",
":",
"List",
"[",
"str",
"]",
")",
"->",
"int",
":",
"postprocessed_predicted_query",
"=",
"self",
".",
"postprocess_query_sqlite",
"(",
"predicted_que... | We evaluate here whether the predicted query and the query label evaluate to the
exact same table. This method is only called by the subprocess, so we just exit with
1 if it is correct and 0 otherwise. | [
"We",
"evaluate",
"here",
"whether",
"the",
"predicted",
"query",
"and",
"the",
"query",
"label",
"evaluate",
"to",
"the",
"exact",
"same",
"table",
".",
"This",
"method",
"is",
"only",
"called",
"by",
"the",
"subprocess",
"so",
"we",
"just",
"exit",
"with... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/executors/sql_executor.py#L52-L79 |
23,158 | allenai/allennlp | allennlp/semparse/contexts/sql_context_utils.py | format_grammar_string | def format_grammar_string(grammar_dictionary: Dict[str, List[str]]) -> str:
"""
Formats a dictionary of production rules into the string format expected
by the Parsimonious Grammar class.
"""
grammar_string = '\n'.join([f"{nonterminal} = {' / '.join(right_hand_side)}"
... | python | def format_grammar_string(grammar_dictionary: Dict[str, List[str]]) -> str:
"""
Formats a dictionary of production rules into the string format expected
by the Parsimonious Grammar class.
"""
grammar_string = '\n'.join([f"{nonterminal} = {' / '.join(right_hand_side)}"
... | [
"def",
"format_grammar_string",
"(",
"grammar_dictionary",
":",
"Dict",
"[",
"str",
",",
"List",
"[",
"str",
"]",
"]",
")",
"->",
"str",
":",
"grammar_string",
"=",
"'\\n'",
".",
"join",
"(",
"[",
"f\"{nonterminal} = {' / '.join(right_hand_side)}\"",
"for",
"non... | Formats a dictionary of production rules into the string format expected
by the Parsimonious Grammar class. | [
"Formats",
"a",
"dictionary",
"of",
"production",
"rules",
"into",
"the",
"string",
"format",
"expected",
"by",
"the",
"Parsimonious",
"Grammar",
"class",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/contexts/sql_context_utils.py#L16-L23 |
23,159 | allenai/allennlp | allennlp/semparse/contexts/sql_context_utils.py | initialize_valid_actions | def initialize_valid_actions(grammar: Grammar,
keywords_to_uppercase: List[str] = None) -> Dict[str, List[str]]:
"""
We initialize the valid actions with the global actions. These include the
valid actions that result from the grammar and also those that result from
the tabl... | python | def initialize_valid_actions(grammar: Grammar,
keywords_to_uppercase: List[str] = None) -> Dict[str, List[str]]:
"""
We initialize the valid actions with the global actions. These include the
valid actions that result from the grammar and also those that result from
the tabl... | [
"def",
"initialize_valid_actions",
"(",
"grammar",
":",
"Grammar",
",",
"keywords_to_uppercase",
":",
"List",
"[",
"str",
"]",
"=",
"None",
")",
"->",
"Dict",
"[",
"str",
",",
"List",
"[",
"str",
"]",
"]",
":",
"valid_actions",
":",
"Dict",
"[",
"str",
... | We initialize the valid actions with the global actions. These include the
valid actions that result from the grammar and also those that result from
the tables provided. The keys represent the nonterminals in the grammar
and the values are lists of the valid actions of that nonterminal. | [
"We",
"initialize",
"the",
"valid",
"actions",
"with",
"the",
"global",
"actions",
".",
"These",
"include",
"the",
"valid",
"actions",
"that",
"result",
"from",
"the",
"grammar",
"and",
"also",
"those",
"that",
"result",
"from",
"the",
"tables",
"provided",
... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/contexts/sql_context_utils.py#L26-L61 |
23,160 | allenai/allennlp | allennlp/semparse/contexts/sql_context_utils.py | format_action | def format_action(nonterminal: str,
right_hand_side: str,
is_string: bool = False,
is_number: bool = False,
keywords_to_uppercase: List[str] = None) -> str:
"""
This function formats an action as it appears in models. It
splits producti... | python | def format_action(nonterminal: str,
right_hand_side: str,
is_string: bool = False,
is_number: bool = False,
keywords_to_uppercase: List[str] = None) -> str:
"""
This function formats an action as it appears in models. It
splits producti... | [
"def",
"format_action",
"(",
"nonterminal",
":",
"str",
",",
"right_hand_side",
":",
"str",
",",
"is_string",
":",
"bool",
"=",
"False",
",",
"is_number",
":",
"bool",
"=",
"False",
",",
"keywords_to_uppercase",
":",
"List",
"[",
"str",
"]",
"=",
"None",
... | This function formats an action as it appears in models. It
splits productions based on the special `ws` and `wsp` rules,
which are used in grammars to denote whitespace, and then
rejoins these tokens a formatted, comma separated list.
Importantly, note that it `does not` split on spaces in
the gram... | [
"This",
"function",
"formats",
"an",
"action",
"as",
"it",
"appears",
"in",
"models",
".",
"It",
"splits",
"productions",
"based",
"on",
"the",
"special",
"ws",
"and",
"wsp",
"rules",
"which",
"are",
"used",
"in",
"grammars",
"to",
"denote",
"whitespace",
... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/contexts/sql_context_utils.py#L64-L109 |
23,161 | allenai/allennlp | allennlp/semparse/contexts/sql_context_utils.py | SqlVisitor.add_action | def add_action(self, node: Node) -> None:
"""
For each node, we accumulate the rules that generated its children in a list.
"""
if node.expr.name and node.expr.name not in ['ws', 'wsp']:
nonterminal = f'{node.expr.name} -> '
if isinstance(node.expr, Literal):
... | python | def add_action(self, node: Node) -> None:
"""
For each node, we accumulate the rules that generated its children in a list.
"""
if node.expr.name and node.expr.name not in ['ws', 'wsp']:
nonterminal = f'{node.expr.name} -> '
if isinstance(node.expr, Literal):
... | [
"def",
"add_action",
"(",
"self",
",",
"node",
":",
"Node",
")",
"->",
"None",
":",
"if",
"node",
".",
"expr",
".",
"name",
"and",
"node",
".",
"expr",
".",
"name",
"not",
"in",
"[",
"'ws'",
",",
"'wsp'",
"]",
":",
"nonterminal",
"=",
"f'{node.expr... | For each node, we accumulate the rules that generated its children in a list. | [
"For",
"each",
"node",
"we",
"accumulate",
"the",
"rules",
"that",
"generated",
"its",
"children",
"in",
"a",
"list",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/contexts/sql_context_utils.py#L164-L191 |
23,162 | allenai/allennlp | allennlp/semparse/contexts/sql_context_utils.py | SqlVisitor.visit | def visit(self, node):
"""
See the ``NodeVisitor`` visit method. This just changes the order in which
we visit nonterminals from right to left to left to right.
"""
method = getattr(self, 'visit_' + node.expr_name, self.generic_visit)
# Call that method, and show where i... | python | def visit(self, node):
"""
See the ``NodeVisitor`` visit method. This just changes the order in which
we visit nonterminals from right to left to left to right.
"""
method = getattr(self, 'visit_' + node.expr_name, self.generic_visit)
# Call that method, and show where i... | [
"def",
"visit",
"(",
"self",
",",
"node",
")",
":",
"method",
"=",
"getattr",
"(",
"self",
",",
"'visit_'",
"+",
"node",
".",
"expr_name",
",",
"self",
".",
"generic_visit",
")",
"# Call that method, and show where in the tree it failed if it blows",
"# up.",
"try... | See the ``NodeVisitor`` visit method. This just changes the order in which
we visit nonterminals from right to left to left to right. | [
"See",
"the",
"NodeVisitor",
"visit",
"method",
".",
"This",
"just",
"changes",
"the",
"order",
"in",
"which",
"we",
"visit",
"nonterminals",
"from",
"right",
"to",
"left",
"to",
"left",
"to",
"right",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/contexts/sql_context_utils.py#L194-L215 |
23,163 | allenai/allennlp | allennlp/semparse/contexts/text2sql_table_context.py | update_grammar_to_be_variable_free | def update_grammar_to_be_variable_free(grammar_dictionary: Dict[str, List[str]]):
"""
SQL is a predominately variable free language in terms of simple usage, in the
sense that most queries do not create references to variables which are not
already static tables in a dataset. However, it is possible to ... | python | def update_grammar_to_be_variable_free(grammar_dictionary: Dict[str, List[str]]):
"""
SQL is a predominately variable free language in terms of simple usage, in the
sense that most queries do not create references to variables which are not
already static tables in a dataset. However, it is possible to ... | [
"def",
"update_grammar_to_be_variable_free",
"(",
"grammar_dictionary",
":",
"Dict",
"[",
"str",
",",
"List",
"[",
"str",
"]",
"]",
")",
":",
"# Tables in variable free grammars cannot be aliased, so we",
"# remove this functionality from the grammar.",
"grammar_dictionary",
"[... | SQL is a predominately variable free language in terms of simple usage, in the
sense that most queries do not create references to variables which are not
already static tables in a dataset. However, it is possible to do this via
derived tables. If we don't require this functionality, we can tighten the
... | [
"SQL",
"is",
"a",
"predominately",
"variable",
"free",
"language",
"in",
"terms",
"of",
"simple",
"usage",
"in",
"the",
"sense",
"that",
"most",
"queries",
"do",
"not",
"create",
"references",
"to",
"variables",
"which",
"are",
"not",
"already",
"static",
"t... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/contexts/text2sql_table_context.py#L145-L179 |
23,164 | allenai/allennlp | allennlp/semparse/contexts/text2sql_table_context.py | update_grammar_with_untyped_entities | def update_grammar_with_untyped_entities(grammar_dictionary: Dict[str, List[str]]) -> None:
"""
Variables can be treated as numbers or strings if their type can be inferred -
however, that can be difficult, so instead, we can just treat them all as values
and be a bit looser on the typing we allow in ou... | python | def update_grammar_with_untyped_entities(grammar_dictionary: Dict[str, List[str]]) -> None:
"""
Variables can be treated as numbers or strings if their type can be inferred -
however, that can be difficult, so instead, we can just treat them all as values
and be a bit looser on the typing we allow in ou... | [
"def",
"update_grammar_with_untyped_entities",
"(",
"grammar_dictionary",
":",
"Dict",
"[",
"str",
",",
"List",
"[",
"str",
"]",
"]",
")",
"->",
"None",
":",
"grammar_dictionary",
"[",
"\"string_set_vals\"",
"]",
"=",
"[",
"'(value ws \",\" ws string_set_vals)'",
",... | Variables can be treated as numbers or strings if their type can be inferred -
however, that can be difficult, so instead, we can just treat them all as values
and be a bit looser on the typing we allow in our grammar. Here we just remove
all references to number and string from the grammar, replacing them ... | [
"Variables",
"can",
"be",
"treated",
"as",
"numbers",
"or",
"strings",
"if",
"their",
"type",
"can",
"be",
"inferred",
"-",
"however",
"that",
"can",
"be",
"difficult",
"so",
"instead",
"we",
"can",
"just",
"treat",
"them",
"all",
"as",
"values",
"and",
... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/contexts/text2sql_table_context.py#L181-L194 |
23,165 | allenai/allennlp | allennlp/models/ensemble.py | Ensemble._load | def _load(cls,
config: Params,
serialization_dir: str,
weights_file: str = None,
cuda_device: int = -1) -> 'Model':
"""
Ensembles don't have vocabularies or weights of their own, so they override _load.
"""
model_params = config.get... | python | def _load(cls,
config: Params,
serialization_dir: str,
weights_file: str = None,
cuda_device: int = -1) -> 'Model':
"""
Ensembles don't have vocabularies or weights of their own, so they override _load.
"""
model_params = config.get... | [
"def",
"_load",
"(",
"cls",
",",
"config",
":",
"Params",
",",
"serialization_dir",
":",
"str",
",",
"weights_file",
":",
"str",
"=",
"None",
",",
"cuda_device",
":",
"int",
"=",
"-",
"1",
")",
"->",
"'Model'",
":",
"model_params",
"=",
"config",
".",
... | Ensembles don't have vocabularies or weights of their own, so they override _load. | [
"Ensembles",
"don",
"t",
"have",
"vocabularies",
"or",
"weights",
"of",
"their",
"own",
"so",
"they",
"override",
"_load",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/models/ensemble.py#L34-L58 |
23,166 | allenai/allennlp | allennlp/semparse/domain_languages/quarel_language.py | QuaRelLanguage.infer | def infer(self, setup: QuaRelType, answer_0: QuaRelType, answer_1: QuaRelType) -> int:
"""
Take the question and check if it is compatible with either of the answer choices.
"""
if self._check_quarels_compatible(setup, answer_0):
if self._check_quarels_compatible(setup, answe... | python | def infer(self, setup: QuaRelType, answer_0: QuaRelType, answer_1: QuaRelType) -> int:
"""
Take the question and check if it is compatible with either of the answer choices.
"""
if self._check_quarels_compatible(setup, answer_0):
if self._check_quarels_compatible(setup, answe... | [
"def",
"infer",
"(",
"self",
",",
"setup",
":",
"QuaRelType",
",",
"answer_0",
":",
"QuaRelType",
",",
"answer_1",
":",
"QuaRelType",
")",
"->",
"int",
":",
"if",
"self",
".",
"_check_quarels_compatible",
"(",
"setup",
",",
"answer_0",
")",
":",
"if",
"s... | Take the question and check if it is compatible with either of the answer choices. | [
"Take",
"the",
"question",
"and",
"check",
"if",
"it",
"is",
"compatible",
"with",
"either",
"of",
"the",
"answer",
"choices",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/domain_languages/quarel_language.py#L97-L110 |
23,167 | allenai/allennlp | allennlp/service/server_simple.py | make_app | def make_app(predictor: Predictor,
field_names: List[str] = None,
static_dir: str = None,
sanitizer: Callable[[JsonDict], JsonDict] = None,
title: str = "AllenNLP Demo") -> Flask:
"""
Creates a Flask app that serves up the provided ``Predictor``
along with... | python | def make_app(predictor: Predictor,
field_names: List[str] = None,
static_dir: str = None,
sanitizer: Callable[[JsonDict], JsonDict] = None,
title: str = "AllenNLP Demo") -> Flask:
"""
Creates a Flask app that serves up the provided ``Predictor``
along with... | [
"def",
"make_app",
"(",
"predictor",
":",
"Predictor",
",",
"field_names",
":",
"List",
"[",
"str",
"]",
"=",
"None",
",",
"static_dir",
":",
"str",
"=",
"None",
",",
"sanitizer",
":",
"Callable",
"[",
"[",
"JsonDict",
"]",
",",
"JsonDict",
"]",
"=",
... | Creates a Flask app that serves up the provided ``Predictor``
along with a front-end for interacting with it.
If you want to use the built-in bare-bones HTML, you must provide the
field names for the inputs (which will be used both as labels
and as the keys in the JSON that gets sent to the predictor).... | [
"Creates",
"a",
"Flask",
"app",
"that",
"serves",
"up",
"the",
"provided",
"Predictor",
"along",
"with",
"a",
"front",
"-",
"end",
"for",
"interacting",
"with",
"it",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/service/server_simple.py#L53-L139 |
23,168 | allenai/allennlp | allennlp/service/server_simple.py | _html | def _html(title: str, field_names: List[str]) -> str:
"""
Returns bare bones HTML for serving up an input form with the
specified fields that can render predictions from the configured model.
"""
inputs = ''.join(_SINGLE_INPUT_TEMPLATE.substitute(field_name=field_name)
for field... | python | def _html(title: str, field_names: List[str]) -> str:
"""
Returns bare bones HTML for serving up an input form with the
specified fields that can render predictions from the configured model.
"""
inputs = ''.join(_SINGLE_INPUT_TEMPLATE.substitute(field_name=field_name)
for field... | [
"def",
"_html",
"(",
"title",
":",
"str",
",",
"field_names",
":",
"List",
"[",
"str",
"]",
")",
"->",
"str",
":",
"inputs",
"=",
"''",
".",
"join",
"(",
"_SINGLE_INPUT_TEMPLATE",
".",
"substitute",
"(",
"field_name",
"=",
"field_name",
")",
"for",
"fi... | Returns bare bones HTML for serving up an input form with the
specified fields that can render predictions from the configured model. | [
"Returns",
"bare",
"bones",
"HTML",
"for",
"serving",
"up",
"an",
"input",
"form",
"with",
"the",
"specified",
"fields",
"that",
"can",
"render",
"predictions",
"from",
"the",
"configured",
"model",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/service/server_simple.py#L741-L755 |
23,169 | allenai/allennlp | allennlp/state_machines/states/lambda_grammar_statelet.py | LambdaGrammarStatelet.get_valid_actions | def get_valid_actions(self) -> Dict[str, Tuple[torch.Tensor, torch.Tensor, List[int]]]:
"""
Returns the valid actions in the current grammar state. See the class docstring for a
description of what we're returning here.
"""
actions = self._valid_actions[self._nonterminal_stack[-... | python | def get_valid_actions(self) -> Dict[str, Tuple[torch.Tensor, torch.Tensor, List[int]]]:
"""
Returns the valid actions in the current grammar state. See the class docstring for a
description of what we're returning here.
"""
actions = self._valid_actions[self._nonterminal_stack[-... | [
"def",
"get_valid_actions",
"(",
"self",
")",
"->",
"Dict",
"[",
"str",
",",
"Tuple",
"[",
"torch",
".",
"Tensor",
",",
"torch",
".",
"Tensor",
",",
"List",
"[",
"int",
"]",
"]",
"]",
":",
"actions",
"=",
"self",
".",
"_valid_actions",
"[",
"self",
... | Returns the valid actions in the current grammar state. See the class docstring for a
description of what we're returning here. | [
"Returns",
"the",
"valid",
"actions",
"in",
"the",
"current",
"grammar",
"state",
".",
"See",
"the",
"class",
"docstring",
"for",
"a",
"description",
"of",
"what",
"we",
"re",
"returning",
"here",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/state_machines/states/lambda_grammar_statelet.py#L77-L100 |
23,170 | allenai/allennlp | allennlp/training/moving_average.py | MovingAverage.assign_average_value | def assign_average_value(self) -> None:
"""
Replace all the parameter values with the averages.
Save the current parameter values to restore later.
"""
for name, parameter in self._parameters:
self._backups[name].copy_(parameter.data)
parameter.data.copy_(... | python | def assign_average_value(self) -> None:
"""
Replace all the parameter values with the averages.
Save the current parameter values to restore later.
"""
for name, parameter in self._parameters:
self._backups[name].copy_(parameter.data)
parameter.data.copy_(... | [
"def",
"assign_average_value",
"(",
"self",
")",
"->",
"None",
":",
"for",
"name",
",",
"parameter",
"in",
"self",
".",
"_parameters",
":",
"self",
".",
"_backups",
"[",
"name",
"]",
".",
"copy_",
"(",
"parameter",
".",
"data",
")",
"parameter",
".",
"... | Replace all the parameter values with the averages.
Save the current parameter values to restore later. | [
"Replace",
"all",
"the",
"parameter",
"values",
"with",
"the",
"averages",
".",
"Save",
"the",
"current",
"parameter",
"values",
"to",
"restore",
"later",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/training/moving_average.py#L27-L34 |
23,171 | allenai/allennlp | allennlp/state_machines/trainers/expected_risk_minimization.py | ExpectedRiskMinimization._prune_beam | def _prune_beam(states: List[State],
beam_size: int,
sort_states: bool = False) -> List[State]:
"""
This method can be used to prune the set of unfinished states on a beam or finished states
at the end of search. In the former case, the states need not be ... | python | def _prune_beam(states: List[State],
beam_size: int,
sort_states: bool = False) -> List[State]:
"""
This method can be used to prune the set of unfinished states on a beam or finished states
at the end of search. In the former case, the states need not be ... | [
"def",
"_prune_beam",
"(",
"states",
":",
"List",
"[",
"State",
"]",
",",
"beam_size",
":",
"int",
",",
"sort_states",
":",
"bool",
"=",
"False",
")",
"->",
"List",
"[",
"State",
"]",
":",
"states_by_batch_index",
":",
"Dict",
"[",
"int",
",",
"List",
... | This method can be used to prune the set of unfinished states on a beam or finished states
at the end of search. In the former case, the states need not be sorted because the all come
from the same decoding step, which does the sorting. However, if the states are finished and
this method is call... | [
"This",
"method",
"can",
"be",
"used",
"to",
"prune",
"the",
"set",
"of",
"unfinished",
"states",
"on",
"a",
"beam",
"or",
"finished",
"states",
"at",
"the",
"end",
"of",
"search",
".",
"In",
"the",
"former",
"case",
"the",
"states",
"need",
"not",
"be... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/state_machines/trainers/expected_risk_minimization.py#L101-L125 |
23,172 | allenai/allennlp | allennlp/state_machines/trainers/expected_risk_minimization.py | ExpectedRiskMinimization._get_best_final_states | def _get_best_final_states(self, finished_states: List[StateType]) -> Dict[int, List[StateType]]:
"""
Returns the best finished states for each batch instance based on model scores. We return
at most ``self._max_num_decoded_sequences`` number of sequences per instance.
"""
batch_... | python | def _get_best_final_states(self, finished_states: List[StateType]) -> Dict[int, List[StateType]]:
"""
Returns the best finished states for each batch instance based on model scores. We return
at most ``self._max_num_decoded_sequences`` number of sequences per instance.
"""
batch_... | [
"def",
"_get_best_final_states",
"(",
"self",
",",
"finished_states",
":",
"List",
"[",
"StateType",
"]",
")",
"->",
"Dict",
"[",
"int",
",",
"List",
"[",
"StateType",
"]",
"]",
":",
"batch_states",
":",
"Dict",
"[",
"int",
",",
"List",
"[",
"StateType",... | Returns the best finished states for each batch instance based on model scores. We return
at most ``self._max_num_decoded_sequences`` number of sequences per instance. | [
"Returns",
"the",
"best",
"finished",
"states",
"for",
"each",
"batch",
"instance",
"based",
"on",
"model",
"scores",
".",
"We",
"return",
"at",
"most",
"self",
".",
"_max_num_decoded_sequences",
"number",
"of",
"sequences",
"per",
"instance",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/state_machines/trainers/expected_risk_minimization.py#L151-L166 |
23,173 | allenai/allennlp | allennlp/modules/token_embedders/embedding.py | _read_pretrained_embeddings_file | def _read_pretrained_embeddings_file(file_uri: str,
embedding_dim: int,
vocab: Vocabulary,
namespace: str = "tokens") -> torch.FloatTensor:
"""
Returns and embedding matrix for the given vocabulary usi... | python | def _read_pretrained_embeddings_file(file_uri: str,
embedding_dim: int,
vocab: Vocabulary,
namespace: str = "tokens") -> torch.FloatTensor:
"""
Returns and embedding matrix for the given vocabulary usi... | [
"def",
"_read_pretrained_embeddings_file",
"(",
"file_uri",
":",
"str",
",",
"embedding_dim",
":",
"int",
",",
"vocab",
":",
"Vocabulary",
",",
"namespace",
":",
"str",
"=",
"\"tokens\"",
")",
"->",
"torch",
".",
"FloatTensor",
":",
"file_ext",
"=",
"get_file_... | Returns and embedding matrix for the given vocabulary using the pretrained embeddings
contained in the given file. Embeddings for tokens not found in the pretrained embedding file
are randomly initialized using a normal distribution with mean and standard deviation equal to
those of the pretrained embedding... | [
"Returns",
"and",
"embedding",
"matrix",
"for",
"the",
"given",
"vocabulary",
"using",
"the",
"pretrained",
"embeddings",
"contained",
"in",
"the",
"given",
"file",
".",
"Embeddings",
"for",
"tokens",
"not",
"found",
"in",
"the",
"pretrained",
"embedding",
"file... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/modules/token_embedders/embedding.py#L317-L371 |
23,174 | allenai/allennlp | allennlp/modules/token_embedders/embedding.py | EmbeddingsTextFile._get_num_tokens_from_first_line | def _get_num_tokens_from_first_line(line: str) -> Optional[int]:
""" This function takes in input a string and if it contains 1 or 2 integers, it assumes the
largest one it the number of tokens. Returns None if the line doesn't match that pattern. """
fields = line.split(' ')
if 1 <= len... | python | def _get_num_tokens_from_first_line(line: str) -> Optional[int]:
""" This function takes in input a string and if it contains 1 or 2 integers, it assumes the
largest one it the number of tokens. Returns None if the line doesn't match that pattern. """
fields = line.split(' ')
if 1 <= len... | [
"def",
"_get_num_tokens_from_first_line",
"(",
"line",
":",
"str",
")",
"->",
"Optional",
"[",
"int",
"]",
":",
"fields",
"=",
"line",
".",
"split",
"(",
"' '",
")",
"if",
"1",
"<=",
"len",
"(",
"fields",
")",
"<=",
"2",
":",
"try",
":",
"int_fields"... | This function takes in input a string and if it contains 1 or 2 integers, it assumes the
largest one it the number of tokens. Returns None if the line doesn't match that pattern. | [
"This",
"function",
"takes",
"in",
"input",
"a",
"string",
"and",
"if",
"it",
"contains",
"1",
"or",
"2",
"integers",
"it",
"assumes",
"the",
"largest",
"one",
"it",
"the",
"number",
"of",
"tokens",
".",
"Returns",
"None",
"if",
"the",
"line",
"doesn",
... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/modules/token_embedders/embedding.py#L632-L646 |
23,175 | allenai/allennlp | allennlp/state_machines/transition_functions/coverage_transition_function.py | CoverageTransitionFunction._get_predicted_embedding_addition | def _get_predicted_embedding_addition(self,
checklist_state: ChecklistStatelet,
action_ids: List[int],
action_embeddings: torch.Tensor) -> torch.Tensor:
"""
Gets the embeddings o... | python | def _get_predicted_embedding_addition(self,
checklist_state: ChecklistStatelet,
action_ids: List[int],
action_embeddings: torch.Tensor) -> torch.Tensor:
"""
Gets the embeddings o... | [
"def",
"_get_predicted_embedding_addition",
"(",
"self",
",",
"checklist_state",
":",
"ChecklistStatelet",
",",
"action_ids",
":",
"List",
"[",
"int",
"]",
",",
"action_embeddings",
":",
"torch",
".",
"Tensor",
")",
"->",
"torch",
".",
"Tensor",
":",
"# Our basi... | Gets the embeddings of desired terminal actions yet to be produced by the decoder, and
returns their sum for the decoder to add it to the predicted embedding to bias the
prediction towards missing actions. | [
"Gets",
"the",
"embeddings",
"of",
"desired",
"terminal",
"actions",
"yet",
"to",
"be",
"produced",
"by",
"the",
"decoder",
"and",
"returns",
"their",
"sum",
"for",
"the",
"decoder",
"to",
"add",
"it",
"to",
"the",
"predicted",
"embedding",
"to",
"bias",
"... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/state_machines/transition_functions/coverage_transition_function.py#L115-L160 |
23,176 | allenai/allennlp | allennlp/data/iterators/multiprocess_iterator.py | _create_tensor_dicts | def _create_tensor_dicts(input_queue: Queue,
output_queue: Queue,
iterator: DataIterator,
shuffle: bool,
index: int) -> None:
"""
Pulls at most ``max_instances_in_memory`` from the input_queue,
groups them in... | python | def _create_tensor_dicts(input_queue: Queue,
output_queue: Queue,
iterator: DataIterator,
shuffle: bool,
index: int) -> None:
"""
Pulls at most ``max_instances_in_memory`` from the input_queue,
groups them in... | [
"def",
"_create_tensor_dicts",
"(",
"input_queue",
":",
"Queue",
",",
"output_queue",
":",
"Queue",
",",
"iterator",
":",
"DataIterator",
",",
"shuffle",
":",
"bool",
",",
"index",
":",
"int",
")",
"->",
"None",
":",
"def",
"instances",
"(",
")",
"->",
"... | Pulls at most ``max_instances_in_memory`` from the input_queue,
groups them into batches of size ``batch_size``, converts them
to ``TensorDict`` s, and puts them on the ``output_queue``. | [
"Pulls",
"at",
"most",
"max_instances_in_memory",
"from",
"the",
"input_queue",
"groups",
"them",
"into",
"batches",
"of",
"size",
"batch_size",
"converts",
"them",
"to",
"TensorDict",
"s",
"and",
"puts",
"them",
"on",
"the",
"output_queue",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/data/iterators/multiprocess_iterator.py#L15-L34 |
23,177 | allenai/allennlp | allennlp/data/iterators/multiprocess_iterator.py | _queuer | def _queuer(instances: Iterable[Instance],
input_queue: Queue,
num_workers: int,
num_epochs: Optional[int]) -> None:
"""
Reads Instances from the iterable and puts them in the input_queue.
"""
epoch = 0
while num_epochs is None or epoch < num_epochs:
epoc... | python | def _queuer(instances: Iterable[Instance],
input_queue: Queue,
num_workers: int,
num_epochs: Optional[int]) -> None:
"""
Reads Instances from the iterable and puts them in the input_queue.
"""
epoch = 0
while num_epochs is None or epoch < num_epochs:
epoc... | [
"def",
"_queuer",
"(",
"instances",
":",
"Iterable",
"[",
"Instance",
"]",
",",
"input_queue",
":",
"Queue",
",",
"num_workers",
":",
"int",
",",
"num_epochs",
":",
"Optional",
"[",
"int",
"]",
")",
"->",
"None",
":",
"epoch",
"=",
"0",
"while",
"num_e... | Reads Instances from the iterable and puts them in the input_queue. | [
"Reads",
"Instances",
"from",
"the",
"iterable",
"and",
"puts",
"them",
"in",
"the",
"input_queue",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/data/iterators/multiprocess_iterator.py#L36-L53 |
23,178 | allenai/allennlp | allennlp/state_machines/states/grammar_based_state.py | GrammarBasedState.get_valid_actions | def get_valid_actions(self) -> List[Dict[str, Tuple[torch.Tensor, torch.Tensor, List[int]]]]:
"""
Returns a list of valid actions for each element of the group.
"""
return [state.get_valid_actions() for state in self.grammar_state] | python | def get_valid_actions(self) -> List[Dict[str, Tuple[torch.Tensor, torch.Tensor, List[int]]]]:
"""
Returns a list of valid actions for each element of the group.
"""
return [state.get_valid_actions() for state in self.grammar_state] | [
"def",
"get_valid_actions",
"(",
"self",
")",
"->",
"List",
"[",
"Dict",
"[",
"str",
",",
"Tuple",
"[",
"torch",
".",
"Tensor",
",",
"torch",
".",
"Tensor",
",",
"List",
"[",
"int",
"]",
"]",
"]",
"]",
":",
"return",
"[",
"state",
".",
"get_valid_a... | Returns a list of valid actions for each element of the group. | [
"Returns",
"a",
"list",
"of",
"valid",
"actions",
"for",
"each",
"element",
"of",
"the",
"group",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/state_machines/states/grammar_based_state.py#L110-L114 |
23,179 | allenai/allennlp | allennlp/data/dataset_readers/multiprocess_dataset_reader.py | _worker | def _worker(reader: DatasetReader,
input_queue: Queue,
output_queue: Queue,
index: int) -> None:
"""
A worker that pulls filenames off the input queue, uses the dataset reader
to read them, and places the generated instances on the output queue.
When there are no file... | python | def _worker(reader: DatasetReader,
input_queue: Queue,
output_queue: Queue,
index: int) -> None:
"""
A worker that pulls filenames off the input queue, uses the dataset reader
to read them, and places the generated instances on the output queue.
When there are no file... | [
"def",
"_worker",
"(",
"reader",
":",
"DatasetReader",
",",
"input_queue",
":",
"Queue",
",",
"output_queue",
":",
"Queue",
",",
"index",
":",
"int",
")",
"->",
"None",
":",
"# Keep going until you get a file_path that's None.",
"while",
"True",
":",
"file_path",
... | A worker that pulls filenames off the input queue, uses the dataset reader
to read them, and places the generated instances on the output queue.
When there are no filenames left on the input queue, it puts its ``index``
on the output queue and doesn't do anything else. | [
"A",
"worker",
"that",
"pulls",
"filenames",
"off",
"the",
"input",
"queue",
"uses",
"the",
"dataset",
"reader",
"to",
"read",
"them",
"and",
"places",
"the",
"generated",
"instances",
"on",
"the",
"output",
"queue",
".",
"When",
"there",
"are",
"no",
"fil... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/data/dataset_readers/multiprocess_dataset_reader.py#L30-L50 |
23,180 | allenai/allennlp | allennlp/modules/conditional_random_field.py | allowed_transitions | def allowed_transitions(constraint_type: str, labels: Dict[int, str]) -> List[Tuple[int, int]]:
"""
Given labels and a constraint type, returns the allowed transitions. It will
additionally include transitions for the start and end states, which are used
by the conditional random field.
Parameters
... | python | def allowed_transitions(constraint_type: str, labels: Dict[int, str]) -> List[Tuple[int, int]]:
"""
Given labels and a constraint type, returns the allowed transitions. It will
additionally include transitions for the start and end states, which are used
by the conditional random field.
Parameters
... | [
"def",
"allowed_transitions",
"(",
"constraint_type",
":",
"str",
",",
"labels",
":",
"Dict",
"[",
"int",
",",
"str",
"]",
")",
"->",
"List",
"[",
"Tuple",
"[",
"int",
",",
"int",
"]",
"]",
":",
"num_labels",
"=",
"len",
"(",
"labels",
")",
"start_ta... | Given labels and a constraint type, returns the allowed transitions. It will
additionally include transitions for the start and end states, which are used
by the conditional random field.
Parameters
----------
constraint_type : ``str``, required
Indicates which constraint to apply. Current ... | [
"Given",
"labels",
"and",
"a",
"constraint",
"type",
"returns",
"the",
"allowed",
"transitions",
".",
"It",
"will",
"additionally",
"include",
"transitions",
"for",
"the",
"start",
"and",
"end",
"states",
"which",
"are",
"used",
"by",
"the",
"conditional",
"ra... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/modules/conditional_random_field.py#L12-L55 |
23,181 | allenai/allennlp | allennlp/modules/conditional_random_field.py | is_transition_allowed | def is_transition_allowed(constraint_type: str,
from_tag: str,
from_entity: str,
to_tag: str,
to_entity: str):
"""
Given a constraint type and strings ``from_tag`` and ``to_tag`` that
represent the origin... | python | def is_transition_allowed(constraint_type: str,
from_tag: str,
from_entity: str,
to_tag: str,
to_entity: str):
"""
Given a constraint type and strings ``from_tag`` and ``to_tag`` that
represent the origin... | [
"def",
"is_transition_allowed",
"(",
"constraint_type",
":",
"str",
",",
"from_tag",
":",
"str",
",",
"from_entity",
":",
"str",
",",
"to_tag",
":",
"str",
",",
"to_entity",
":",
"str",
")",
":",
"# pylint: disable=too-many-return-statements",
"if",
"to_tag",
"=... | Given a constraint type and strings ``from_tag`` and ``to_tag`` that
represent the origin and destination of the transition, return whether
the transition is allowed under the given constraint type.
Parameters
----------
constraint_type : ``str``, required
Indicates which constraint to appl... | [
"Given",
"a",
"constraint",
"type",
"and",
"strings",
"from_tag",
"and",
"to_tag",
"that",
"represent",
"the",
"origin",
"and",
"destination",
"of",
"the",
"transition",
"return",
"whether",
"the",
"transition",
"is",
"allowed",
"under",
"the",
"given",
"constra... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/modules/conditional_random_field.py#L58-L149 |
23,182 | allenai/allennlp | allennlp/modules/conditional_random_field.py | ConditionalRandomField.viterbi_tags | def viterbi_tags(self,
logits: torch.Tensor,
mask: torch.Tensor) -> List[Tuple[List[int], float]]:
"""
Uses viterbi algorithm to find most likely tags for the given inputs.
If constraints are applied, disallows all other transitions.
"""
... | python | def viterbi_tags(self,
logits: torch.Tensor,
mask: torch.Tensor) -> List[Tuple[List[int], float]]:
"""
Uses viterbi algorithm to find most likely tags for the given inputs.
If constraints are applied, disallows all other transitions.
"""
... | [
"def",
"viterbi_tags",
"(",
"self",
",",
"logits",
":",
"torch",
".",
"Tensor",
",",
"mask",
":",
"torch",
".",
"Tensor",
")",
"->",
"List",
"[",
"Tuple",
"[",
"List",
"[",
"int",
"]",
",",
"float",
"]",
"]",
":",
"_",
",",
"max_seq_length",
",",
... | Uses viterbi algorithm to find most likely tags for the given inputs.
If constraints are applied, disallows all other transitions. | [
"Uses",
"viterbi",
"algorithm",
"to",
"find",
"most",
"likely",
"tags",
"for",
"the",
"given",
"inputs",
".",
"If",
"constraints",
"are",
"applied",
"disallows",
"all",
"other",
"transitions",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/modules/conditional_random_field.py#L324-L384 |
23,183 | allenai/allennlp | allennlp/common/from_params.py | takes_arg | def takes_arg(obj, arg: str) -> bool:
"""
Checks whether the provided obj takes a certain arg.
If it's a class, we're really checking whether its constructor does.
If it's a function or method, we're checking the object itself.
Otherwise, we raise an error.
"""
if inspect.isclass(obj):
... | python | def takes_arg(obj, arg: str) -> bool:
"""
Checks whether the provided obj takes a certain arg.
If it's a class, we're really checking whether its constructor does.
If it's a function or method, we're checking the object itself.
Otherwise, we raise an error.
"""
if inspect.isclass(obj):
... | [
"def",
"takes_arg",
"(",
"obj",
",",
"arg",
":",
"str",
")",
"->",
"bool",
":",
"if",
"inspect",
".",
"isclass",
"(",
"obj",
")",
":",
"signature",
"=",
"inspect",
".",
"signature",
"(",
"obj",
".",
"__init__",
")",
"elif",
"inspect",
".",
"ismethod"... | Checks whether the provided obj takes a certain arg.
If it's a class, we're really checking whether its constructor does.
If it's a function or method, we're checking the object itself.
Otherwise, we raise an error. | [
"Checks",
"whether",
"the",
"provided",
"obj",
"takes",
"a",
"certain",
"arg",
".",
"If",
"it",
"s",
"a",
"class",
"we",
"re",
"really",
"checking",
"whether",
"its",
"constructor",
"does",
".",
"If",
"it",
"s",
"a",
"function",
"or",
"method",
"we",
"... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/common/from_params.py#L59-L72 |
23,184 | allenai/allennlp | allennlp/common/from_params.py | create_kwargs | def create_kwargs(cls: Type[T], params: Params, **extras) -> Dict[str, Any]:
"""
Given some class, a `Params` object, and potentially other keyword arguments,
create a dict of keyword args suitable for passing to the class's constructor.
The function does this by finding the class's constructor, matchi... | python | def create_kwargs(cls: Type[T], params: Params, **extras) -> Dict[str, Any]:
"""
Given some class, a `Params` object, and potentially other keyword arguments,
create a dict of keyword args suitable for passing to the class's constructor.
The function does this by finding the class's constructor, matchi... | [
"def",
"create_kwargs",
"(",
"cls",
":",
"Type",
"[",
"T",
"]",
",",
"params",
":",
"Params",
",",
"*",
"*",
"extras",
")",
"->",
"Dict",
"[",
"str",
",",
"Any",
"]",
":",
"# Get the signature of the constructor.",
"signature",
"=",
"inspect",
".",
"sign... | Given some class, a `Params` object, and potentially other keyword arguments,
create a dict of keyword args suitable for passing to the class's constructor.
The function does this by finding the class's constructor, matching the constructor
arguments to entries in the `params` object, and instantiating val... | [
"Given",
"some",
"class",
"a",
"Params",
"object",
"and",
"potentially",
"other",
"keyword",
"arguments",
"create",
"a",
"dict",
"of",
"keyword",
"args",
"suitable",
"for",
"passing",
"to",
"the",
"class",
"s",
"constructor",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/common/from_params.py#L105-L136 |
23,185 | allenai/allennlp | allennlp/state_machines/transition_functions/transition_function.py | TransitionFunction.take_step | def take_step(self,
state: StateType,
max_actions: int = None,
allowed_actions: List[Set] = None) -> List[StateType]:
"""
The main method in the ``TransitionFunction`` API. This function defines the computation
done at each step of decoding ... | python | def take_step(self,
state: StateType,
max_actions: int = None,
allowed_actions: List[Set] = None) -> List[StateType]:
"""
The main method in the ``TransitionFunction`` API. This function defines the computation
done at each step of decoding ... | [
"def",
"take_step",
"(",
"self",
",",
"state",
":",
"StateType",
",",
"max_actions",
":",
"int",
"=",
"None",
",",
"allowed_actions",
":",
"List",
"[",
"Set",
"]",
"=",
"None",
")",
"->",
"List",
"[",
"StateType",
"]",
":",
"raise",
"NotImplementedError"... | The main method in the ``TransitionFunction`` API. This function defines the computation
done at each step of decoding and returns a ranked list of next states.
The input state is `grouped`, to allow for efficient computation, but the output states
should all have a ``group_size`` of 1, to mak... | [
"The",
"main",
"method",
"in",
"the",
"TransitionFunction",
"API",
".",
"This",
"function",
"defines",
"the",
"computation",
"done",
"at",
"each",
"step",
"of",
"decoding",
"and",
"returns",
"a",
"ranked",
"list",
"of",
"next",
"states",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/state_machines/transition_functions/transition_function.py#L23-L82 |
23,186 | allenai/allennlp | allennlp/data/dataset_readers/semantic_dependency_parsing.py | parse_sentence | def parse_sentence(sentence_blob: str) -> Tuple[List[Dict[str, str]], List[Tuple[int, int]], List[str]]:
"""
Parses a chunk of text in the SemEval SDP format.
Each word in the sentence is returned as a dictionary with the following
format:
'id': '1',
'form': 'Pierre',
'lemma': 'Pierre',
... | python | def parse_sentence(sentence_blob: str) -> Tuple[List[Dict[str, str]], List[Tuple[int, int]], List[str]]:
"""
Parses a chunk of text in the SemEval SDP format.
Each word in the sentence is returned as a dictionary with the following
format:
'id': '1',
'form': 'Pierre',
'lemma': 'Pierre',
... | [
"def",
"parse_sentence",
"(",
"sentence_blob",
":",
"str",
")",
"->",
"Tuple",
"[",
"List",
"[",
"Dict",
"[",
"str",
",",
"str",
"]",
"]",
",",
"List",
"[",
"Tuple",
"[",
"int",
",",
"int",
"]",
"]",
",",
"List",
"[",
"str",
"]",
"]",
":",
"ann... | Parses a chunk of text in the SemEval SDP format.
Each word in the sentence is returned as a dictionary with the following
format:
'id': '1',
'form': 'Pierre',
'lemma': 'Pierre',
'pos': 'NNP',
'head': '2', # Note that this is the `syntactic` head.
'deprel': 'nn',
'top': '-',
'... | [
"Parses",
"a",
"chunk",
"of",
"text",
"in",
"the",
"SemEval",
"SDP",
"format",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/data/dataset_readers/semantic_dependency_parsing.py#L17-L56 |
23,187 | allenai/allennlp | allennlp/common/checks.py | parse_cuda_device | def parse_cuda_device(cuda_device: Union[str, int, List[int]]) -> Union[int, List[int]]:
"""
Disambiguates single GPU and multiple GPU settings for cuda_device param.
"""
def from_list(strings):
if len(strings) > 1:
return [int(d) for d in strings]
elif len(strings) == 1:
... | python | def parse_cuda_device(cuda_device: Union[str, int, List[int]]) -> Union[int, List[int]]:
"""
Disambiguates single GPU and multiple GPU settings for cuda_device param.
"""
def from_list(strings):
if len(strings) > 1:
return [int(d) for d in strings]
elif len(strings) == 1:
... | [
"def",
"parse_cuda_device",
"(",
"cuda_device",
":",
"Union",
"[",
"str",
",",
"int",
",",
"List",
"[",
"int",
"]",
"]",
")",
"->",
"Union",
"[",
"int",
",",
"List",
"[",
"int",
"]",
"]",
":",
"def",
"from_list",
"(",
"strings",
")",
":",
"if",
"... | Disambiguates single GPU and multiple GPU settings for cuda_device param. | [
"Disambiguates",
"single",
"GPU",
"and",
"multiple",
"GPU",
"settings",
"for",
"cuda_device",
"param",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/common/checks.py#L51-L71 |
23,188 | allenai/allennlp | allennlp/data/iterators/data_iterator.py | add_epoch_number | def add_epoch_number(batch: Batch, epoch: int) -> Batch:
"""
Add the epoch number to the batch instances as a MetadataField.
"""
for instance in batch.instances:
instance.fields['epoch_num'] = MetadataField(epoch)
return batch | python | def add_epoch_number(batch: Batch, epoch: int) -> Batch:
"""
Add the epoch number to the batch instances as a MetadataField.
"""
for instance in batch.instances:
instance.fields['epoch_num'] = MetadataField(epoch)
return batch | [
"def",
"add_epoch_number",
"(",
"batch",
":",
"Batch",
",",
"epoch",
":",
"int",
")",
"->",
"Batch",
":",
"for",
"instance",
"in",
"batch",
".",
"instances",
":",
"instance",
".",
"fields",
"[",
"'epoch_num'",
"]",
"=",
"MetadataField",
"(",
"epoch",
")"... | Add the epoch number to the batch instances as a MetadataField. | [
"Add",
"the",
"epoch",
"number",
"to",
"the",
"batch",
"instances",
"as",
"a",
"MetadataField",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/data/iterators/data_iterator.py#L22-L28 |
23,189 | allenai/allennlp | allennlp/data/iterators/data_iterator.py | DataIterator._take_instances | def _take_instances(self,
instances: Iterable[Instance],
max_instances: Optional[int] = None) -> Iterator[Instance]:
"""
Take the next `max_instances` instances from the given dataset.
If `max_instances` is `None`, then just take all instances from... | python | def _take_instances(self,
instances: Iterable[Instance],
max_instances: Optional[int] = None) -> Iterator[Instance]:
"""
Take the next `max_instances` instances from the given dataset.
If `max_instances` is `None`, then just take all instances from... | [
"def",
"_take_instances",
"(",
"self",
",",
"instances",
":",
"Iterable",
"[",
"Instance",
"]",
",",
"max_instances",
":",
"Optional",
"[",
"int",
"]",
"=",
"None",
")",
"->",
"Iterator",
"[",
"Instance",
"]",
":",
"# If max_instances isn't specified, just itera... | Take the next `max_instances` instances from the given dataset.
If `max_instances` is `None`, then just take all instances from the dataset.
If `max_instances` is not `None`, each call resumes where the previous one
left off, and when you get to the end of the dataset you start again from the be... | [
"Take",
"the",
"next",
"max_instances",
"instances",
"from",
"the",
"given",
"dataset",
".",
"If",
"max_instances",
"is",
"None",
"then",
"just",
"take",
"all",
"instances",
"from",
"the",
"dataset",
".",
"If",
"max_instances",
"is",
"not",
"None",
"each",
"... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/data/iterators/data_iterator.py#L163-L192 |
23,190 | allenai/allennlp | allennlp/data/iterators/data_iterator.py | DataIterator._memory_sized_lists | def _memory_sized_lists(self,
instances: Iterable[Instance]) -> Iterable[List[Instance]]:
"""
Breaks the dataset into "memory-sized" lists of instances,
which it yields up one at a time until it gets through a full epoch.
For example, if the dataset is alread... | python | def _memory_sized_lists(self,
instances: Iterable[Instance]) -> Iterable[List[Instance]]:
"""
Breaks the dataset into "memory-sized" lists of instances,
which it yields up one at a time until it gets through a full epoch.
For example, if the dataset is alread... | [
"def",
"_memory_sized_lists",
"(",
"self",
",",
"instances",
":",
"Iterable",
"[",
"Instance",
"]",
")",
"->",
"Iterable",
"[",
"List",
"[",
"Instance",
"]",
"]",
":",
"lazy",
"=",
"is_lazy",
"(",
"instances",
")",
"# Get an iterator over the next epoch worth of... | Breaks the dataset into "memory-sized" lists of instances,
which it yields up one at a time until it gets through a full epoch.
For example, if the dataset is already an in-memory list, and each epoch
represents one pass through the dataset, it just yields back the dataset.
Whereas if t... | [
"Breaks",
"the",
"dataset",
"into",
"memory",
"-",
"sized",
"lists",
"of",
"instances",
"which",
"it",
"yields",
"up",
"one",
"at",
"a",
"time",
"until",
"it",
"gets",
"through",
"a",
"full",
"epoch",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/data/iterators/data_iterator.py#L194-L228 |
23,191 | allenai/allennlp | allennlp/data/iterators/data_iterator.py | DataIterator._ensure_batch_is_sufficiently_small | def _ensure_batch_is_sufficiently_small(
self,
batch_instances: Iterable[Instance],
excess: Deque[Instance]) -> List[List[Instance]]:
"""
If self._maximum_samples_per_batch is specified, then split the batch
into smaller sub-batches if it exceeds the maximum s... | python | def _ensure_batch_is_sufficiently_small(
self,
batch_instances: Iterable[Instance],
excess: Deque[Instance]) -> List[List[Instance]]:
"""
If self._maximum_samples_per_batch is specified, then split the batch
into smaller sub-batches if it exceeds the maximum s... | [
"def",
"_ensure_batch_is_sufficiently_small",
"(",
"self",
",",
"batch_instances",
":",
"Iterable",
"[",
"Instance",
"]",
",",
"excess",
":",
"Deque",
"[",
"Instance",
"]",
")",
"->",
"List",
"[",
"List",
"[",
"Instance",
"]",
"]",
":",
"if",
"self",
".",
... | If self._maximum_samples_per_batch is specified, then split the batch
into smaller sub-batches if it exceeds the maximum size.
Parameters
----------
batch_instances : ``Iterable[Instance]``
A candidate batch.
excess : ``Deque[Instance]``
Instances that we... | [
"If",
"self",
".",
"_maximum_samples_per_batch",
"is",
"specified",
"then",
"split",
"the",
"batch",
"into",
"smaller",
"sub",
"-",
"batches",
"if",
"it",
"exceeds",
"the",
"maximum",
"size",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/data/iterators/data_iterator.py#L230-L297 |
23,192 | allenai/allennlp | allennlp/data/iterators/data_iterator.py | DataIterator._create_batches | def _create_batches(self, instances: Iterable[Instance], shuffle: bool) -> Iterable[Batch]:
"""
This method should return one epoch worth of batches.
"""
raise NotImplementedError | python | def _create_batches(self, instances: Iterable[Instance], shuffle: bool) -> Iterable[Batch]:
"""
This method should return one epoch worth of batches.
"""
raise NotImplementedError | [
"def",
"_create_batches",
"(",
"self",
",",
"instances",
":",
"Iterable",
"[",
"Instance",
"]",
",",
"shuffle",
":",
"bool",
")",
"->",
"Iterable",
"[",
"Batch",
"]",
":",
"raise",
"NotImplementedError"
] | This method should return one epoch worth of batches. | [
"This",
"method",
"should",
"return",
"one",
"epoch",
"worth",
"of",
"batches",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/data/iterators/data_iterator.py#L314-L318 |
23,193 | allenai/allennlp | allennlp/modules/seq2seq_encoders/bidirectional_language_model_transformer.py | attention | def attention(query: torch.Tensor,
key: torch.Tensor,
value: torch.Tensor,
mask: torch.Tensor = None,
dropout: Callable = None) -> Tuple[torch.Tensor, torch.Tensor]:
"""Compute 'Scaled Dot Product Attention'"""
d_k = query.size(-1)
scores = torch.matmu... | python | def attention(query: torch.Tensor,
key: torch.Tensor,
value: torch.Tensor,
mask: torch.Tensor = None,
dropout: Callable = None) -> Tuple[torch.Tensor, torch.Tensor]:
"""Compute 'Scaled Dot Product Attention'"""
d_k = query.size(-1)
scores = torch.matmu... | [
"def",
"attention",
"(",
"query",
":",
"torch",
".",
"Tensor",
",",
"key",
":",
"torch",
".",
"Tensor",
",",
"value",
":",
"torch",
".",
"Tensor",
",",
"mask",
":",
"torch",
".",
"Tensor",
"=",
"None",
",",
"dropout",
":",
"Callable",
"=",
"None",
... | Compute 'Scaled Dot Product Attention | [
"Compute",
"Scaled",
"Dot",
"Product",
"Attention"
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/modules/seq2seq_encoders/bidirectional_language_model_transformer.py#L24-L37 |
23,194 | allenai/allennlp | allennlp/modules/seq2seq_encoders/bidirectional_language_model_transformer.py | subsequent_mask | def subsequent_mask(size: int, device: str = 'cpu') -> torch.Tensor:
"""Mask out subsequent positions."""
mask = torch.tril(torch.ones(size, size, device=device, dtype=torch.int32)).unsqueeze(0)
return mask | python | def subsequent_mask(size: int, device: str = 'cpu') -> torch.Tensor:
"""Mask out subsequent positions."""
mask = torch.tril(torch.ones(size, size, device=device, dtype=torch.int32)).unsqueeze(0)
return mask | [
"def",
"subsequent_mask",
"(",
"size",
":",
"int",
",",
"device",
":",
"str",
"=",
"'cpu'",
")",
"->",
"torch",
".",
"Tensor",
":",
"mask",
"=",
"torch",
".",
"tril",
"(",
"torch",
".",
"ones",
"(",
"size",
",",
"size",
",",
"device",
"=",
"device"... | Mask out subsequent positions. | [
"Mask",
"out",
"subsequent",
"positions",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/modules/seq2seq_encoders/bidirectional_language_model_transformer.py#L40-L43 |
23,195 | allenai/allennlp | allennlp/modules/seq2seq_encoders/bidirectional_language_model_transformer.py | SublayerConnection.forward | def forward(self, x: torch.Tensor, sublayer: Callable[[torch.Tensor], torch.Tensor]) -> torch.Tensor:
"""Apply residual connection to any sublayer with the same size."""
return x + self.dropout(sublayer(self.norm(x))) | python | def forward(self, x: torch.Tensor, sublayer: Callable[[torch.Tensor], torch.Tensor]) -> torch.Tensor:
"""Apply residual connection to any sublayer with the same size."""
return x + self.dropout(sublayer(self.norm(x))) | [
"def",
"forward",
"(",
"self",
",",
"x",
":",
"torch",
".",
"Tensor",
",",
"sublayer",
":",
"Callable",
"[",
"[",
"torch",
".",
"Tensor",
"]",
",",
"torch",
".",
"Tensor",
"]",
")",
"->",
"torch",
".",
"Tensor",
":",
"return",
"x",
"+",
"self",
"... | Apply residual connection to any sublayer with the same size. | [
"Apply",
"residual",
"connection",
"to",
"any",
"sublayer",
"with",
"the",
"same",
"size",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/modules/seq2seq_encoders/bidirectional_language_model_transformer.py#L114-L116 |
23,196 | allenai/allennlp | allennlp/nn/initializers.py | block_orthogonal | def block_orthogonal(tensor: torch.Tensor,
split_sizes: List[int],
gain: float = 1.0) -> None:
"""
An initializer which allows initializing model parameters in "blocks". This is helpful
in the case of recurrent models which use multiple gates applied to linear proje... | python | def block_orthogonal(tensor: torch.Tensor,
split_sizes: List[int],
gain: float = 1.0) -> None:
"""
An initializer which allows initializing model parameters in "blocks". This is helpful
in the case of recurrent models which use multiple gates applied to linear proje... | [
"def",
"block_orthogonal",
"(",
"tensor",
":",
"torch",
".",
"Tensor",
",",
"split_sizes",
":",
"List",
"[",
"int",
"]",
",",
"gain",
":",
"float",
"=",
"1.0",
")",
"->",
"None",
":",
"data",
"=",
"tensor",
".",
"data",
"sizes",
"=",
"list",
"(",
"... | An initializer which allows initializing model parameters in "blocks". This is helpful
in the case of recurrent models which use multiple gates applied to linear projections,
which can be computed efficiently if they are concatenated together. However, they are
separate parameters which should be initialize... | [
"An",
"initializer",
"which",
"allows",
"initializing",
"model",
"parameters",
"in",
"blocks",
".",
"This",
"is",
"helpful",
"in",
"the",
"case",
"of",
"recurrent",
"models",
"which",
"use",
"multiple",
"gates",
"applied",
"to",
"linear",
"projections",
"which",... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/nn/initializers.py#L98-L138 |
23,197 | allenai/allennlp | allennlp/nn/initializers.py | lstm_hidden_bias | def lstm_hidden_bias(tensor: torch.Tensor) -> None:
"""
Initialize the biases of the forget gate to 1, and all other gates to 0,
following Jozefowicz et al., An Empirical Exploration of Recurrent Network Architectures
"""
# gates are (b_hi|b_hf|b_hg|b_ho) of shape (4*hidden_size)
tensor.data.zer... | python | def lstm_hidden_bias(tensor: torch.Tensor) -> None:
"""
Initialize the biases of the forget gate to 1, and all other gates to 0,
following Jozefowicz et al., An Empirical Exploration of Recurrent Network Architectures
"""
# gates are (b_hi|b_hf|b_hg|b_ho) of shape (4*hidden_size)
tensor.data.zer... | [
"def",
"lstm_hidden_bias",
"(",
"tensor",
":",
"torch",
".",
"Tensor",
")",
"->",
"None",
":",
"# gates are (b_hi|b_hf|b_hg|b_ho) of shape (4*hidden_size)",
"tensor",
".",
"data",
".",
"zero_",
"(",
")",
"hidden_size",
"=",
"tensor",
".",
"shape",
"[",
"0",
"]",... | Initialize the biases of the forget gate to 1, and all other gates to 0,
following Jozefowicz et al., An Empirical Exploration of Recurrent Network Architectures | [
"Initialize",
"the",
"biases",
"of",
"the",
"forget",
"gate",
"to",
"1",
"and",
"all",
"other",
"gates",
"to",
"0",
"following",
"Jozefowicz",
"et",
"al",
".",
"An",
"Empirical",
"Exploration",
"of",
"Recurrent",
"Network",
"Architectures"
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/nn/initializers.py#L144-L152 |
23,198 | allenai/allennlp | allennlp/semparse/contexts/table_question_knowledge_graph.py | TableQuestionKnowledgeGraph._should_split_column_cells | def _should_split_column_cells(cls, column_cells: List[str]) -> bool:
"""
Returns true if there is any cell in this column that can be split.
"""
return any(cls._should_split_cell(cell_text) for cell_text in column_cells) | python | def _should_split_column_cells(cls, column_cells: List[str]) -> bool:
"""
Returns true if there is any cell in this column that can be split.
"""
return any(cls._should_split_cell(cell_text) for cell_text in column_cells) | [
"def",
"_should_split_column_cells",
"(",
"cls",
",",
"column_cells",
":",
"List",
"[",
"str",
"]",
")",
"->",
"bool",
":",
"return",
"any",
"(",
"cls",
".",
"_should_split_cell",
"(",
"cell_text",
")",
"for",
"cell_text",
"in",
"column_cells",
")"
] | Returns true if there is any cell in this column that can be split. | [
"Returns",
"true",
"if",
"there",
"is",
"any",
"cell",
"in",
"this",
"column",
"that",
"can",
"be",
"split",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/contexts/table_question_knowledge_graph.py#L329-L333 |
23,199 | allenai/allennlp | allennlp/semparse/contexts/table_question_knowledge_graph.py | TableQuestionKnowledgeGraph._should_split_cell | def _should_split_cell(cls, cell_text: str) -> bool:
"""
Checks whether the cell should be split. We're just doing the same thing that SEMPRE did
here.
"""
if ', ' in cell_text or '\n' in cell_text or '/' in cell_text:
return True
return False | python | def _should_split_cell(cls, cell_text: str) -> bool:
"""
Checks whether the cell should be split. We're just doing the same thing that SEMPRE did
here.
"""
if ', ' in cell_text or '\n' in cell_text or '/' in cell_text:
return True
return False | [
"def",
"_should_split_cell",
"(",
"cls",
",",
"cell_text",
":",
"str",
")",
"->",
"bool",
":",
"if",
"', '",
"in",
"cell_text",
"or",
"'\\n'",
"in",
"cell_text",
"or",
"'/'",
"in",
"cell_text",
":",
"return",
"True",
"return",
"False"
] | Checks whether the cell should be split. We're just doing the same thing that SEMPRE did
here. | [
"Checks",
"whether",
"the",
"cell",
"should",
"be",
"split",
".",
"We",
"re",
"just",
"doing",
"the",
"same",
"thing",
"that",
"SEMPRE",
"did",
"here",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/contexts/table_question_knowledge_graph.py#L336-L343 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.