repo
stringlengths
7
55
path
stringlengths
4
223
func_name
stringlengths
1
134
original_string
stringlengths
75
104k
language
stringclasses
1 value
code
stringlengths
75
104k
code_tokens
listlengths
19
28.4k
docstring
stringlengths
1
46.9k
docstring_tokens
listlengths
1
1.97k
sha
stringlengths
40
40
url
stringlengths
87
315
partition
stringclasses
1 value
allenai/allennlp
allennlp/semparse/type_declarations/wikitables_lambda_dcs.py
ArgExtremeType.resolve
def resolve(self, other: Type) -> Optional[Type]: """See ``PlaceholderType.resolve``""" if not isinstance(other, NltkComplexType): return None expected_second = ComplexType(NUMBER_TYPE, ComplexType(ANY_TYPE, ComplexType(ComplexType(ANY_TYPE, ANY_...
python
def resolve(self, other: Type) -> Optional[Type]: """See ``PlaceholderType.resolve``""" if not isinstance(other, NltkComplexType): return None expected_second = ComplexType(NUMBER_TYPE, ComplexType(ANY_TYPE, ComplexType(ComplexType(ANY_TYPE, ANY_...
[ "def", "resolve", "(", "self", ",", "other", ":", "Type", ")", "->", "Optional", "[", "Type", "]", ":", "if", "not", "isinstance", "(", "other", ",", "NltkComplexType", ")", ":", "return", "None", "expected_second", "=", "ComplexType", "(", "NUMBER_TYPE", ...
See ``PlaceholderType.resolve``
[ "See", "PlaceholderType", ".", "resolve" ]
648a36f77db7e45784c047176074f98534c76636
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/type_declarations/wikitables_lambda_dcs.py#L83-L123
train
allenai/allennlp
allennlp/semparse/type_declarations/wikitables_lambda_dcs.py
CountType.resolve
def resolve(self, other: Type) -> Type: """See ``PlaceholderType.resolve``""" if not isinstance(other, NltkComplexType): return None resolved_second = NUMBER_TYPE.resolve(other.second) if not resolved_second: return None return CountType(other.first)
python
def resolve(self, other: Type) -> Type: """See ``PlaceholderType.resolve``""" if not isinstance(other, NltkComplexType): return None resolved_second = NUMBER_TYPE.resolve(other.second) if not resolved_second: return None return CountType(other.first)
[ "def", "resolve", "(", "self", ",", "other", ":", "Type", ")", "->", "Type", ":", "if", "not", "isinstance", "(", "other", ",", "NltkComplexType", ")", ":", "return", "None", "resolved_second", "=", "NUMBER_TYPE", ".", "resolve", "(", "other", ".", "seco...
See ``PlaceholderType.resolve``
[ "See", "PlaceholderType", ".", "resolve" ]
648a36f77db7e45784c047176074f98534c76636
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/type_declarations/wikitables_lambda_dcs.py#L149-L156
train
allenai/allennlp
scripts/nlvr/get_nlvr_logical_forms.py
process_data
def process_data(input_file: str, output_file: str, max_path_length: int, max_num_logical_forms: int, ignore_agenda: bool, write_sequences: bool) -> None: """ Reads an NLVR dataset and returns a JSON representation containing s...
python
def process_data(input_file: str, output_file: str, max_path_length: int, max_num_logical_forms: int, ignore_agenda: bool, write_sequences: bool) -> None: """ Reads an NLVR dataset and returns a JSON representation containing s...
[ "def", "process_data", "(", "input_file", ":", "str", ",", "output_file", ":", "str", ",", "max_path_length", ":", "int", ",", "max_num_logical_forms", ":", "int", ",", "ignore_agenda", ":", "bool", ",", "write_sequences", ":", "bool", ")", "->", "None", ":"...
Reads an NLVR dataset and returns a JSON representation containing sentences, labels, correct and incorrect logical forms. The output will contain at most `max_num_logical_forms` logical forms each in both correct and incorrect lists. The output format is: ``[{"id": str, "label": str, "sentence": str, "...
[ "Reads", "an", "NLVR", "dataset", "and", "returns", "a", "JSON", "representation", "containing", "sentences", "labels", "correct", "and", "incorrect", "logical", "forms", ".", "The", "output", "will", "contain", "at", "most", "max_num_logical_forms", "logical", "f...
648a36f77db7e45784c047176074f98534c76636
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/scripts/nlvr/get_nlvr_logical_forms.py#L32-L104
train
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
train
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
train
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
train
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
train
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
train
allenai/allennlp
allennlp/data/dataset_readers/dataset_utils/ontonotes.py
Ontonotes._process_coref_span_annotations_for_word
def _process_coref_span_annotations_for_word(label: str, word_index: int, clusters: DefaultDict[int, List[Tuple[int, int]]], coref_stacks: DefaultDict[int, List[int]]) -> No...
python
def _process_coref_span_annotations_for_word(label: str, word_index: int, clusters: DefaultDict[int, List[Tuple[int, int]]], coref_stacks: DefaultDict[int, List[int]]) -> No...
[ "def", "_process_coref_span_annotations_for_word", "(", "label", ":", "str", ",", "word_index", ":", "int", ",", "clusters", ":", "DefaultDict", "[", "int", ",", "List", "[", "Tuple", "[", "int", ",", "int", "]", "]", "]", ",", "coref_stacks", ":", "Defaul...
For a given coref label, add it to a currently open span(s), complete a span(s) or ignore it, if it is outside of all spans. This method mutates the clusters and coref_stacks dictionaries. Parameters ---------- label : ``str`` The coref label for this word. w...
[ "For", "a", "given", "coref", "label", "add", "it", "to", "a", "currently", "open", "span", "(", "s", ")", "complete", "a", "span", "(", "s", ")", "or", "ignore", "it", "if", "it", "is", "outside", "of", "all", "spans", ".", "This", "method", "muta...
648a36f77db7e45784c047176074f98534c76636
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/data/dataset_readers/dataset_utils/ontonotes.py#L362-L408
train
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
train
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
train
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
train
allenai/allennlp
allennlp/training/metrics/metric.py
Metric.get_metric
def get_metric(self, reset: bool) -> Union[float, Tuple[float, ...], Dict[str, float], Dict[str, List[float]]]: """ Compute and return the metric. Optionally also call :func:`self.reset`. """ raise NotImplementedError
python
def get_metric(self, reset: bool) -> Union[float, Tuple[float, ...], Dict[str, float], Dict[str, List[float]]]: """ Compute and return the metric. Optionally also call :func:`self.reset`. """ raise NotImplementedError
[ "def", "get_metric", "(", "self", ",", "reset", ":", "bool", ")", "->", "Union", "[", "float", ",", "Tuple", "[", "float", ",", "...", "]", ",", "Dict", "[", "str", ",", "float", "]", ",", "Dict", "[", "str", ",", "List", "[", "float", "]", "]"...
Compute and return the metric. Optionally also call :func:`self.reset`.
[ "Compute", "and", "return", "the", "metric", ".", "Optionally", "also", "call", ":", "func", ":", "self", ".", "reset", "." ]
648a36f77db7e45784c047176074f98534c76636
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/training/metrics/metric.py#L29-L33
train
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
train
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
train
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
train
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
train
allenai/allennlp
allennlp/data/dataset_readers/dataset_utils/text2sql_utils.py
read_dataset_schema
def read_dataset_schema(schema_path: str) -> Dict[str, List[TableColumn]]: """ Reads a schema from the text2sql data, returning a dictionary mapping table names to their columns and respective types. This handles columns in an arbitrary order and also allows either ``{Table, Field}`` or ``{Table, Fi...
python
def read_dataset_schema(schema_path: str) -> Dict[str, List[TableColumn]]: """ Reads a schema from the text2sql data, returning a dictionary mapping table names to their columns and respective types. This handles columns in an arbitrary order and also allows either ``{Table, Field}`` or ``{Table, Fi...
[ "def", "read_dataset_schema", "(", "schema_path", ":", "str", ")", "->", "Dict", "[", "str", ",", "List", "[", "TableColumn", "]", "]", ":", "schema", ":", "Dict", "[", "str", ",", "List", "[", "TableColumn", "]", "]", "=", "defaultdict", "(", "list", ...
Reads a schema from the text2sql data, returning a dictionary mapping table names to their columns and respective types. This handles columns in an arbitrary order and also allows either ``{Table, Field}`` or ``{Table, Field} Name`` as headers, because both appear in the data. It also uppercases table a...
[ "Reads", "a", "schema", "from", "the", "text2sql", "data", "returning", "a", "dictionary", "mapping", "table", "names", "to", "their", "columns", "and", "respective", "types", ".", "This", "handles", "columns", "in", "an", "arbitrary", "order", "and", "also", ...
648a36f77db7e45784c047176074f98534c76636
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/data/dataset_readers/dataset_utils/text2sql_utils.py#L152-L184
train
allenai/allennlp
allennlp/data/dataset_readers/dataset_utils/text2sql_utils.py
process_sql_data
def process_sql_data(data: List[JsonDict], use_all_sql: bool = False, use_all_queries: bool = False, remove_unneeded_aliases: bool = False, schema: Dict[str, List[TableColumn]] = None) -> Iterable[SqlData]: """ A utility functio...
python
def process_sql_data(data: List[JsonDict], use_all_sql: bool = False, use_all_queries: bool = False, remove_unneeded_aliases: bool = False, schema: Dict[str, List[TableColumn]] = None) -> Iterable[SqlData]: """ A utility functio...
[ "def", "process_sql_data", "(", "data", ":", "List", "[", "JsonDict", "]", ",", "use_all_sql", ":", "bool", "=", "False", ",", "use_all_queries", ":", "bool", "=", "False", ",", "remove_unneeded_aliases", ":", "bool", "=", "False", ",", "schema", ":", "Dic...
A utility function for reading in text2sql data. The blob is the result of loading the json from a file produced by the script ``scripts/reformat_text2sql_data.py``. Parameters ---------- data : ``JsonDict`` use_all_sql : ``bool``, optional (default = False) Whether to use all of the sq...
[ "A", "utility", "function", "for", "reading", "in", "text2sql", "data", ".", "The", "blob", "is", "the", "result", "of", "loading", "the", "json", "from", "a", "file", "produced", "by", "the", "script", "scripts", "/", "reformat_text2sql_data", ".", "py", ...
648a36f77db7e45784c047176074f98534c76636
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/data/dataset_readers/dataset_utils/text2sql_utils.py#L187-L258
train
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
train
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
train
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
train
allenai/allennlp
allennlp/state_machines/util.py
construct_prefix_tree
def construct_prefix_tree(targets: Union[torch.Tensor, List[List[List[int]]]], target_mask: Optional[torch.Tensor] = None) -> List[Dict[Tuple[int, ...], Set[int]]]: """ Takes a list of valid target action sequences and creates a mapping from all possible (valid) action prefixes to ...
python
def construct_prefix_tree(targets: Union[torch.Tensor, List[List[List[int]]]], target_mask: Optional[torch.Tensor] = None) -> List[Dict[Tuple[int, ...], Set[int]]]: """ Takes a list of valid target action sequences and creates a mapping from all possible (valid) action prefixes to ...
[ "def", "construct_prefix_tree", "(", "targets", ":", "Union", "[", "torch", ".", "Tensor", ",", "List", "[", "List", "[", "List", "[", "int", "]", "]", "]", "]", ",", "target_mask", ":", "Optional", "[", "torch", ".", "Tensor", "]", "=", "None", ")",...
Takes a list of valid target action sequences and creates a mapping from all possible (valid) action prefixes to allowed actions given that prefix. While the method is called ``construct_prefix_tree``, we're actually returning a map that has as keys the paths to `all internal nodes of the trie`, and as val...
[ "Takes", "a", "list", "of", "valid", "target", "action", "sequences", "and", "creates", "a", "mapping", "from", "all", "possible", "(", "valid", ")", "action", "prefixes", "to", "allowed", "actions", "given", "that", "prefix", ".", "While", "the", "method", ...
648a36f77db7e45784c047176074f98534c76636
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/state_machines/util.py#L7-L47
train
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
train
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
train
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
train
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
train
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
train
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
train
allenai/allennlp
scripts/write_srl_predictions_to_conll_format.py
main
def main(serialization_directory: int, device: int, data: str, prefix: str, domain: str = None): """ serialization_directory : str, required. The directory containing the serialized weights. device: int, default = -1 The device to run the evaluation on. ...
python
def main(serialization_directory: int, device: int, data: str, prefix: str, domain: str = None): """ serialization_directory : str, required. The directory containing the serialized weights. device: int, default = -1 The device to run the evaluation on. ...
[ "def", "main", "(", "serialization_directory", ":", "int", ",", "device", ":", "int", ",", "data", ":", "str", ",", "prefix", ":", "str", ",", "domain", ":", "str", "=", "None", ")", ":", "config", "=", "Params", ".", "from_file", "(", "os", ".", "...
serialization_directory : str, required. The directory containing the serialized weights. device: int, default = -1 The device to run the evaluation on. data: str, default = None The data to evaluate on. By default, we use the validation data from the original experiment. pre...
[ "serialization_directory", ":", "str", "required", ".", "The", "directory", "containing", "the", "serialized", "weights", ".", "device", ":", "int", "default", "=", "-", "1", "The", "device", "to", "run", "the", "evaluation", "on", ".", "data", ":", "str", ...
648a36f77db7e45784c047176074f98534c76636
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/scripts/write_srl_predictions_to_conll_format.py#L18-L90
train
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
train
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
train
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
train
allenai/allennlp
allennlp/modules/text_field_embedders/text_field_embedder.py
TextFieldEmbedder.forward
def forward(self, # pylint: disable=arguments-differ text_field_input: Dict[str, torch.Tensor], num_wrapping_dims: int = 0) -> torch.Tensor: """ Parameters ---------- text_field_input : ``Dict[str, torch.Tensor]`` A dictionary that was the out...
python
def forward(self, # pylint: disable=arguments-differ text_field_input: Dict[str, torch.Tensor], num_wrapping_dims: int = 0) -> torch.Tensor: """ Parameters ---------- text_field_input : ``Dict[str, torch.Tensor]`` A dictionary that was the out...
[ "def", "forward", "(", "self", ",", "# pylint: disable=arguments-differ", "text_field_input", ":", "Dict", "[", "str", ",", "torch", ".", "Tensor", "]", ",", "num_wrapping_dims", ":", "int", "=", "0", ")", "->", "torch", ".", "Tensor", ":", "raise", "NotImpl...
Parameters ---------- text_field_input : ``Dict[str, torch.Tensor]`` A dictionary that was the output of a call to ``TextField.as_tensor``. Each tensor in here is assumed to have a shape roughly similar to ``(batch_size, sequence_length)`` (perhaps with an extra trai...
[ "Parameters", "----------", "text_field_input", ":", "Dict", "[", "str", "torch", ".", "Tensor", "]", "A", "dictionary", "that", "was", "the", "output", "of", "a", "call", "to", "TextField", ".", "as_tensor", ".", "Each", "tensor", "in", "here", "is", "ass...
648a36f77db7e45784c047176074f98534c76636
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/modules/text_field_embedders/text_field_embedder.py#L26-L42
train
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
train
allenai/allennlp
allennlp/modules/elmo_lstm.py
ElmoLstm.forward
def forward(self, # pylint: disable=arguments-differ inputs: torch.Tensor, mask: torch.LongTensor) -> torch.Tensor: """ Parameters ---------- inputs : ``torch.Tensor``, required. A Tensor of shape ``(batch_size, sequence_length, hidden_size)``...
python
def forward(self, # pylint: disable=arguments-differ inputs: torch.Tensor, mask: torch.LongTensor) -> torch.Tensor: """ Parameters ---------- inputs : ``torch.Tensor``, required. A Tensor of shape ``(batch_size, sequence_length, hidden_size)``...
[ "def", "forward", "(", "self", ",", "# pylint: disable=arguments-differ", "inputs", ":", "torch", ".", "Tensor", ",", "mask", ":", "torch", ".", "LongTensor", ")", "->", "torch", ".", "Tensor", ":", "batch_size", ",", "total_sequence_length", "=", "mask", ".",...
Parameters ---------- inputs : ``torch.Tensor``, required. A Tensor of shape ``(batch_size, sequence_length, hidden_size)``. mask : ``torch.LongTensor``, required. A binary mask of shape ``(batch_size, sequence_length)`` representing the non-padded elements in...
[ "Parameters", "----------", "inputs", ":", "torch", ".", "Tensor", "required", ".", "A", "Tensor", "of", "shape", "(", "batch_size", "sequence_length", "hidden_size", ")", ".", "mask", ":", "torch", ".", "LongTensor", "required", ".", "A", "binary", "mask", ...
648a36f77db7e45784c047176074f98534c76636
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/modules/elmo_lstm.py#L104-L158
train
allenai/allennlp
allennlp/modules/elmo_lstm.py
ElmoLstm._lstm_forward
def _lstm_forward(self, inputs: PackedSequence, initial_state: Optional[Tuple[torch.Tensor, torch.Tensor]] = None) -> \ Tuple[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]: """ Parameters ---------- inputs : ``PackedSequence``, r...
python
def _lstm_forward(self, inputs: PackedSequence, initial_state: Optional[Tuple[torch.Tensor, torch.Tensor]] = None) -> \ Tuple[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]: """ Parameters ---------- inputs : ``PackedSequence``, r...
[ "def", "_lstm_forward", "(", "self", ",", "inputs", ":", "PackedSequence", ",", "initial_state", ":", "Optional", "[", "Tuple", "[", "torch", ".", "Tensor", ",", "torch", ".", "Tensor", "]", "]", "=", "None", ")", "->", "Tuple", "[", "torch", ".", "Ten...
Parameters ---------- inputs : ``PackedSequence``, required. A batch first ``PackedSequence`` to run the stacked LSTM over. initial_state : ``Tuple[torch.Tensor, torch.Tensor]``, optional, (default = None) A tuple (state, memory) representing the initial hidden state and ...
[ "Parameters", "----------", "inputs", ":", "PackedSequence", "required", ".", "A", "batch", "first", "PackedSequence", "to", "run", "the", "stacked", "LSTM", "over", ".", "initial_state", ":", "Tuple", "[", "torch", ".", "Tensor", "torch", ".", "Tensor", "]", ...
648a36f77db7e45784c047176074f98534c76636
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/modules/elmo_lstm.py#L160-L241
train
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
train
allenai/allennlp
allennlp/modules/stacked_alternating_lstm.py
StackedAlternatingLstm.forward
def forward(self, # pylint: disable=arguments-differ inputs: PackedSequence, initial_state: Optional[Tuple[torch.Tensor, torch.Tensor]] = None) -> \ Tuple[Union[torch.Tensor, PackedSequence], Tuple[torch.Tensor, torch.Tensor]]: """ Parameters --------...
python
def forward(self, # pylint: disable=arguments-differ inputs: PackedSequence, initial_state: Optional[Tuple[torch.Tensor, torch.Tensor]] = None) -> \ Tuple[Union[torch.Tensor, PackedSequence], Tuple[torch.Tensor, torch.Tensor]]: """ Parameters --------...
[ "def", "forward", "(", "self", ",", "# pylint: disable=arguments-differ", "inputs", ":", "PackedSequence", ",", "initial_state", ":", "Optional", "[", "Tuple", "[", "torch", ".", "Tensor", ",", "torch", ".", "Tensor", "]", "]", "=", "None", ")", "->", "Tuple...
Parameters ---------- inputs : ``PackedSequence``, required. A batch first ``PackedSequence`` to run the stacked LSTM over. initial_state : Tuple[torch.Tensor, torch.Tensor], optional, (default = None) A tuple (state, memory) representing the initial hidden state and memo...
[ "Parameters", "----------", "inputs", ":", "PackedSequence", "required", ".", "A", "batch", "first", "PackedSequence", "to", "run", "the", "stacked", "LSTM", "over", ".", "initial_state", ":", "Tuple", "[", "torch", ".", "Tensor", "torch", ".", "Tensor", "]", ...
648a36f77db7e45784c047176074f98534c76636
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/modules/stacked_alternating_lstm.py#L72-L111
train
allenai/allennlp
allennlp/semparse/type_declarations/type_declaration.py
substitute_any_type
def substitute_any_type(type_: Type, basic_types: Set[BasicType]) -> List[Type]: """ Takes a type and a set of basic types, and substitutes all instances of ANY_TYPE with all possible basic types and returns a list with all possible combinations. Note that this substitution is unconstrained. That is, ...
python
def substitute_any_type(type_: Type, basic_types: Set[BasicType]) -> List[Type]: """ Takes a type and a set of basic types, and substitutes all instances of ANY_TYPE with all possible basic types and returns a list with all possible combinations. Note that this substitution is unconstrained. That is, ...
[ "def", "substitute_any_type", "(", "type_", ":", "Type", ",", "basic_types", ":", "Set", "[", "BasicType", "]", ")", "->", "List", "[", "Type", "]", ":", "if", "type_", "==", "ANY_TYPE", ":", "return", "list", "(", "basic_types", ")", "if", "isinstance",...
Takes a type and a set of basic types, and substitutes all instances of ANY_TYPE with all possible basic types and returns a list with all possible combinations. Note that this substitution is unconstrained. That is, If you have a type with placeholders, <#1,#1> for example, this may substitute the placeh...
[ "Takes", "a", "type", "and", "a", "set", "of", "basic", "types", "and", "substitutes", "all", "instances", "of", "ANY_TYPE", "with", "all", "possible", "basic", "types", "and", "returns", "a", "list", "with", "all", "possible", "combinations", ".", "Note", ...
648a36f77db7e45784c047176074f98534c76636
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/type_declarations/type_declaration.py#L540-L554
train
allenai/allennlp
allennlp/semparse/type_declarations/type_declaration.py
_get_complex_type_production
def _get_complex_type_production(complex_type: ComplexType, multi_match_mapping: Dict[Type, List[Type]]) -> List[Tuple[Type, str]]: """ Takes a complex type (without any placeholders), gets its return values, and returns productions (perhaps each with multiple arguments) tha...
python
def _get_complex_type_production(complex_type: ComplexType, multi_match_mapping: Dict[Type, List[Type]]) -> List[Tuple[Type, str]]: """ Takes a complex type (without any placeholders), gets its return values, and returns productions (perhaps each with multiple arguments) tha...
[ "def", "_get_complex_type_production", "(", "complex_type", ":", "ComplexType", ",", "multi_match_mapping", ":", "Dict", "[", "Type", ",", "List", "[", "Type", "]", "]", ")", "->", "List", "[", "Tuple", "[", "Type", ",", "str", "]", "]", ":", "return_type"...
Takes a complex type (without any placeholders), gets its return values, and returns productions (perhaps each with multiple arguments) that produce the return values. This method also takes care of ``MultiMatchNamedBasicTypes``. If one of the arguments or the return types is a multi match type, it gets al...
[ "Takes", "a", "complex", "type", "(", "without", "any", "placeholders", ")", "gets", "its", "return", "values", "and", "returns", "productions", "(", "perhaps", "each", "with", "multiple", "arguments", ")", "that", "produce", "the", "return", "values", ".", ...
648a36f77db7e45784c047176074f98534c76636
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/type_declarations/type_declaration.py#L561-L597
train
allenai/allennlp
allennlp/semparse/type_declarations/type_declaration.py
get_valid_actions
def get_valid_actions(name_mapping: Dict[str, str], type_signatures: Dict[str, Type], basic_types: Set[Type], multi_match_mapping: Dict[Type, List[Type]] = None, valid_starting_types: Set[Type] = None, num_nest...
python
def get_valid_actions(name_mapping: Dict[str, str], type_signatures: Dict[str, Type], basic_types: Set[Type], multi_match_mapping: Dict[Type, List[Type]] = None, valid_starting_types: Set[Type] = None, num_nest...
[ "def", "get_valid_actions", "(", "name_mapping", ":", "Dict", "[", "str", ",", "str", "]", ",", "type_signatures", ":", "Dict", "[", "str", ",", "Type", "]", ",", "basic_types", ":", "Set", "[", "Type", "]", ",", "multi_match_mapping", ":", "Dict", "[", ...
Generates all the valid actions starting from each non-terminal. For terminals of a specific type, we simply add a production from the type to the terminal. For all terminal `functions`, we additionally add a rule that allows their return type to be generated from an application of the function. For exampl...
[ "Generates", "all", "the", "valid", "actions", "starting", "from", "each", "non", "-", "terminal", ".", "For", "terminals", "of", "a", "specific", "type", "we", "simply", "add", "a", "production", "from", "the", "type", "to", "the", "terminal", ".", "For",...
648a36f77db7e45784c047176074f98534c76636
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/type_declarations/type_declaration.py#L600-L692
train
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
train
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
train
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
train
allenai/allennlp
allennlp/semparse/type_declarations/type_declaration.py
UnaryOpType.resolve
def resolve(self, other) -> Optional[Type]: """See ``PlaceholderType.resolve``""" if not isinstance(other, NltkComplexType): return None other_first = other.first.resolve(other.second) if not other_first: return None other_second = other.second.resolve(oth...
python
def resolve(self, other) -> Optional[Type]: """See ``PlaceholderType.resolve``""" if not isinstance(other, NltkComplexType): return None other_first = other.first.resolve(other.second) if not other_first: return None other_second = other.second.resolve(oth...
[ "def", "resolve", "(", "self", ",", "other", ")", "->", "Optional", "[", "Type", "]", ":", "if", "not", "isinstance", "(", "other", ",", "NltkComplexType", ")", ":", "return", "None", "other_first", "=", "other", ".", "first", ".", "resolve", "(", "oth...
See ``PlaceholderType.resolve``
[ "See", "PlaceholderType", ".", "resolve" ]
648a36f77db7e45784c047176074f98534c76636
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/type_declarations/type_declaration.py#L279-L289
train
allenai/allennlp
allennlp/semparse/type_declarations/type_declaration.py
BinaryOpType.resolve
def resolve(self, other: Type) -> Optional[Type]: """See ``PlaceholderType.resolve``""" if not isinstance(other, NltkComplexType): return None if not isinstance(other.second, NltkComplexType): return None other_first = other.first.resolve(other.second.first) ...
python
def resolve(self, other: Type) -> Optional[Type]: """See ``PlaceholderType.resolve``""" if not isinstance(other, NltkComplexType): return None if not isinstance(other.second, NltkComplexType): return None other_first = other.first.resolve(other.second.first) ...
[ "def", "resolve", "(", "self", ",", "other", ":", "Type", ")", "->", "Optional", "[", "Type", "]", ":", "if", "not", "isinstance", "(", "other", ",", "NltkComplexType", ")", ":", "return", "None", "if", "not", "isinstance", "(", "other", ".", "second",...
See ``PlaceholderType.resolve``
[ "See", "PlaceholderType", ".", "resolve" ]
648a36f77db7e45784c047176074f98534c76636
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/type_declarations/type_declaration.py#L332-L347
train
allenai/allennlp
allennlp/semparse/type_declarations/type_declaration.py
DynamicTypeApplicationExpression._set_type
def _set_type(self, other_type: Type = ANY_TYPE, signature=None) -> None: """ We override this method to do just one thing on top of ``ApplicationExpression._set_type``. In lambda expressions of the form /x F(x), where the function is F and the argument is x, we can use the type of F to ...
python
def _set_type(self, other_type: Type = ANY_TYPE, signature=None) -> None: """ We override this method to do just one thing on top of ``ApplicationExpression._set_type``. In lambda expressions of the form /x F(x), where the function is F and the argument is x, we can use the type of F to ...
[ "def", "_set_type", "(", "self", ",", "other_type", ":", "Type", "=", "ANY_TYPE", ",", "signature", "=", "None", ")", "->", "None", ":", "super", "(", "DynamicTypeApplicationExpression", ",", "self", ")", ".", "_set_type", "(", "other_type", ",", "signature"...
We override this method to do just one thing on top of ``ApplicationExpression._set_type``. In lambda expressions of the form /x F(x), where the function is F and the argument is x, we can use the type of F to infer the type of x. That is, if F is of type <a, b>, we can resolve the type of x aga...
[ "We", "override", "this", "method", "to", "do", "just", "one", "thing", "on", "top", "of", "ApplicationExpression", ".", "_set_type", ".", "In", "lambda", "expressions", "of", "the", "form", "/", "x", "F", "(", "x", ")", "where", "the", "function", "is",...
648a36f77db7e45784c047176074f98534c76636
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/type_declarations/type_declaration.py#L412-L437
train
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
train
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
train
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
train
allenai/allennlp
allennlp/training/tensorboard_writer.py
TensorboardWriter.log_metrics
def log_metrics(self, train_metrics: dict, val_metrics: dict = None, epoch: int = None, log_to_console: bool = False) -> None: """ Sends all of the train metrics (and validation metrics, if provided) to tensorboard. ...
python
def log_metrics(self, train_metrics: dict, val_metrics: dict = None, epoch: int = None, log_to_console: bool = False) -> None: """ Sends all of the train metrics (and validation metrics, if provided) to tensorboard. ...
[ "def", "log_metrics", "(", "self", ",", "train_metrics", ":", "dict", ",", "val_metrics", ":", "dict", "=", "None", ",", "epoch", ":", "int", "=", "None", ",", "log_to_console", ":", "bool", "=", "False", ")", "->", "None", ":", "metric_names", "=", "s...
Sends all of the train metrics (and validation metrics, if provided) to tensorboard.
[ "Sends", "all", "of", "the", "train", "metrics", "(", "and", "validation", "metrics", "if", "provided", ")", "to", "tensorboard", "." ]
648a36f77db7e45784c047176074f98534c76636
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/training/tensorboard_writer.py#L141-L178
train
allenai/allennlp
allennlp/semparse/contexts/quarel_utils.py
get_explanation
def get_explanation(logical_form: str, world_extractions: JsonDict, answer_index: int, world: QuarelWorld) -> List[JsonDict]: """ Create explanation (as a list of header/content entries) for an answer """ output = [] nl_world = {} if wo...
python
def get_explanation(logical_form: str, world_extractions: JsonDict, answer_index: int, world: QuarelWorld) -> List[JsonDict]: """ Create explanation (as a list of header/content entries) for an answer """ output = [] nl_world = {} if wo...
[ "def", "get_explanation", "(", "logical_form", ":", "str", ",", "world_extractions", ":", "JsonDict", ",", "answer_index", ":", "int", ",", "world", ":", "QuarelWorld", ")", "->", "List", "[", "JsonDict", "]", ":", "output", "=", "[", "]", "nl_world", "=",...
Create explanation (as a list of header/content entries) for an answer
[ "Create", "explanation", "(", "as", "a", "list", "of", "header", "/", "content", "entries", ")", "for", "an", "answer" ]
648a36f77db7e45784c047176074f98534c76636
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/contexts/quarel_utils.py#L126-L182
train
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
train
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
train
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
train
allenai/allennlp
allennlp/modules/bimpm_matching.py
BiMpmMatching.forward
def forward(self, context_1: torch.Tensor, mask_1: torch.Tensor, context_2: torch.Tensor, mask_2: torch.Tensor) -> Tuple[List[torch.Tensor], List[torch.Tensor]]: # pylint: disable=arguments-differ """ Given the forward (or backward)...
python
def forward(self, context_1: torch.Tensor, mask_1: torch.Tensor, context_2: torch.Tensor, mask_2: torch.Tensor) -> Tuple[List[torch.Tensor], List[torch.Tensor]]: # pylint: disable=arguments-differ """ Given the forward (or backward)...
[ "def", "forward", "(", "self", ",", "context_1", ":", "torch", ".", "Tensor", ",", "mask_1", ":", "torch", ".", "Tensor", ",", "context_2", ":", "torch", ".", "Tensor", ",", "mask_2", ":", "torch", ".", "Tensor", ")", "->", "Tuple", "[", "List", "[",...
Given the forward (or backward) representations of sentence1 and sentence2, apply four bilateral matching functions between them in one direction. Parameters ---------- context_1 : ``torch.Tensor`` Tensor of shape (batch_size, seq_len1, hidden_dim) representing the encoding ...
[ "Given", "the", "forward", "(", "or", "backward", ")", "representations", "of", "sentence1", "and", "sentence2", "apply", "four", "bilateral", "matching", "functions", "between", "them", "in", "one", "direction", "." ]
648a36f77db7e45784c047176074f98534c76636
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/modules/bimpm_matching.py#L188-L361
train
allenai/allennlp
allennlp/data/dataset_readers/semantic_parsing/wikitables/util.py
parse_example_line
def parse_example_line(lisp_string: str) -> Dict: """ Training data in WikitableQuestions comes with examples in the form of lisp strings in the format: (example (id <example-id>) (utterance <question>) (context (graph tables.TableKnowledgeGraph <table-filename>)) ...
python
def parse_example_line(lisp_string: str) -> Dict: """ Training data in WikitableQuestions comes with examples in the form of lisp strings in the format: (example (id <example-id>) (utterance <question>) (context (graph tables.TableKnowledgeGraph <table-filename>)) ...
[ "def", "parse_example_line", "(", "lisp_string", ":", "str", ")", "->", "Dict", ":", "id_piece", ",", "rest", "=", "lisp_string", ".", "split", "(", "') (utterance \"'", ")", "example_id", "=", "id_piece", ".", "split", "(", "'(id '", ")", "[", "1", "]", ...
Training data in WikitableQuestions comes with examples in the form of lisp strings in the format: (example (id <example-id>) (utterance <question>) (context (graph tables.TableKnowledgeGraph <table-filename>)) (targetValue (list (description <answer1>) (descri...
[ "Training", "data", "in", "WikitableQuestions", "comes", "with", "examples", "in", "the", "form", "of", "lisp", "strings", "in", "the", "format", ":", "(", "example", "(", "id", "<example", "-", "id", ">", ")", "(", "utterance", "<question", ">", ")", "(...
648a36f77db7e45784c047176074f98534c76636
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/data/dataset_readers/semantic_parsing/wikitables/util.py#L3-L26
train
allenai/allennlp
allennlp/commands/make_vocab.py
make_vocab_from_args
def make_vocab_from_args(args: argparse.Namespace): """ Just converts from an ``argparse.Namespace`` object to params. """ parameter_path = args.param_path overrides = args.overrides serialization_dir = args.serialization_dir params = Params.from_file(parameter_path, overrides) make_vo...
python
def make_vocab_from_args(args: argparse.Namespace): """ Just converts from an ``argparse.Namespace`` object to params. """ parameter_path = args.param_path overrides = args.overrides serialization_dir = args.serialization_dir params = Params.from_file(parameter_path, overrides) make_vo...
[ "def", "make_vocab_from_args", "(", "args", ":", "argparse", ".", "Namespace", ")", ":", "parameter_path", "=", "args", ".", "param_path", "overrides", "=", "args", ".", "overrides", "serialization_dir", "=", "args", ".", "serialization_dir", "params", "=", "Par...
Just converts from an ``argparse.Namespace`` object to params.
[ "Just", "converts", "from", "an", "argparse", ".", "Namespace", "object", "to", "params", "." ]
648a36f77db7e45784c047176074f98534c76636
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/commands/make_vocab.py#L67-L77
train
allenai/allennlp
allennlp/semparse/worlds/quarel_world.py
QuarelWorld.execute
def execute(self, lf_raw: str) -> int: """ Very basic model for executing friction logical forms. For now returns answer index (or -1 if no answer can be concluded) """ # Remove "a:" prefixes from attributes (hack) logical_form = re.sub(r"\(a:", r"(", lf_raw) pars...
python
def execute(self, lf_raw: str) -> int: """ Very basic model for executing friction logical forms. For now returns answer index (or -1 if no answer can be concluded) """ # Remove "a:" prefixes from attributes (hack) logical_form = re.sub(r"\(a:", r"(", lf_raw) pars...
[ "def", "execute", "(", "self", ",", "lf_raw", ":", "str", ")", "->", "int", ":", "# Remove \"a:\" prefixes from attributes (hack)", "logical_form", "=", "re", ".", "sub", "(", "r\"\\(a:\"", ",", "r\"(\"", ",", "lf_raw", ")", "parse", "=", "semparse_util", ".",...
Very basic model for executing friction logical forms. For now returns answer index (or -1 if no answer can be concluded)
[ "Very", "basic", "model", "for", "executing", "friction", "logical", "forms", ".", "For", "now", "returns", "answer", "index", "(", "or", "-", "1", "if", "no", "answer", "can", "be", "concluded", ")" ]
648a36f77db7e45784c047176074f98534c76636
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/worlds/quarel_world.py#L167-L182
train
allenai/allennlp
allennlp/semparse/contexts/atis_tables.py
get_times_from_utterance
def get_times_from_utterance(utterance: str, char_offset_to_token_index: Dict[int, int], indices_of_approximate_words: Set[int]) -> Dict[str, List[int]]: """ Given an utterance, we get the numbers that correspond to times and convert them to values t...
python
def get_times_from_utterance(utterance: str, char_offset_to_token_index: Dict[int, int], indices_of_approximate_words: Set[int]) -> Dict[str, List[int]]: """ Given an utterance, we get the numbers that correspond to times and convert them to values t...
[ "def", "get_times_from_utterance", "(", "utterance", ":", "str", ",", "char_offset_to_token_index", ":", "Dict", "[", "int", ",", "int", "]", ",", "indices_of_approximate_words", ":", "Set", "[", "int", "]", ")", "->", "Dict", "[", "str", ",", "List", "[", ...
Given an utterance, we get the numbers that correspond to times and convert them to values that may appear in the query. For example: convert ``7pm`` to ``1900``.
[ "Given", "an", "utterance", "we", "get", "the", "numbers", "that", "correspond", "to", "times", "and", "convert", "them", "to", "values", "that", "may", "appear", "in", "the", "query", ".", "For", "example", ":", "convert", "7pm", "to", "1900", "." ]
648a36f77db7e45784c047176074f98534c76636
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/contexts/atis_tables.py#L37-L77
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
allenai/allennlp
allennlp/modules/token_embedders/bert_token_embedder.py
BertEmbedder.forward
def forward(self, input_ids: torch.LongTensor, offsets: torch.LongTensor = None, token_type_ids: torch.LongTensor = None) -> torch.Tensor: """ Parameters ---------- input_ids : ``torch.LongTensor`` The (batch_size, ..., max_sequ...
python
def forward(self, input_ids: torch.LongTensor, offsets: torch.LongTensor = None, token_type_ids: torch.LongTensor = None) -> torch.Tensor: """ Parameters ---------- input_ids : ``torch.LongTensor`` The (batch_size, ..., max_sequ...
[ "def", "forward", "(", "self", ",", "input_ids", ":", "torch", ".", "LongTensor", ",", "offsets", ":", "torch", ".", "LongTensor", "=", "None", ",", "token_type_ids", ":", "torch", ".", "LongTensor", "=", "None", ")", "->", "torch", ".", "Tensor", ":", ...
Parameters ---------- input_ids : ``torch.LongTensor`` The (batch_size, ..., max_sequence_length) tensor of wordpiece ids. offsets : ``torch.LongTensor``, optional The BERT embeddings are one per wordpiece. However it's possible/likely you might want one per o...
[ "Parameters", "----------", "input_ids", ":", "torch", ".", "LongTensor", "The", "(", "batch_size", "...", "max_sequence_length", ")", "tensor", "of", "wordpiece", "ids", ".", "offsets", ":", "torch", ".", "LongTensor", "optional", "The", "BERT", "embeddings", "...
648a36f77db7e45784c047176074f98534c76636
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/modules/token_embedders/bert_token_embedder.py#L51-L111
train
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
train
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
train
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
train
allenai/allennlp
allennlp/data/token_indexers/openai_transformer_byte_pair_indexer.py
text_standardize
def text_standardize(text): """ Apply text standardization following original implementation. """ text = text.replace('—', '-') text = text.replace('–', '-') text = text.replace('―', '-') text = text.replace('…', '...') text = text.replace('´', "'") text = re.sub(r'''(-+|~+|!+|"+|;+|...
python
def text_standardize(text): """ Apply text standardization following original implementation. """ text = text.replace('—', '-') text = text.replace('–', '-') text = text.replace('―', '-') text = text.replace('…', '...') text = text.replace('´', "'") text = re.sub(r'''(-+|~+|!+|"+|;+|...
[ "def", "text_standardize", "(", "text", ")", ":", "text", "=", "text", ".", "replace", "(", "'—', ", "'", "')", "", "text", "=", "text", ".", "replace", "(", "'–', ", "'", "')", "", "text", "=", "text", ".", "replace", "(", "'―', ", "'", "')", ""...
Apply text standardization following original implementation.
[ "Apply", "text", "standardization", "following", "original", "implementation", "." ]
648a36f77db7e45784c047176074f98534c76636
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/data/token_indexers/openai_transformer_byte_pair_indexer.py#L15-L27
train
allenai/allennlp
allennlp/commands/__init__.py
main
def main(prog: str = None, subcommand_overrides: Dict[str, Subcommand] = {}) -> None: """ The :mod:`~allennlp.run` command only knows about the registered classes in the ``allennlp`` codebase. In particular, once you start creating your own ``Model`` s and so forth, it won't work for them, unle...
python
def main(prog: str = None, subcommand_overrides: Dict[str, Subcommand] = {}) -> None: """ The :mod:`~allennlp.run` command only knows about the registered classes in the ``allennlp`` codebase. In particular, once you start creating your own ``Model`` s and so forth, it won't work for them, unle...
[ "def", "main", "(", "prog", ":", "str", "=", "None", ",", "subcommand_overrides", ":", "Dict", "[", "str", ",", "Subcommand", "]", "=", "{", "}", ")", "->", "None", ":", "# pylint: disable=dangerous-default-value", "parser", "=", "ArgumentParserWithDefaults", ...
The :mod:`~allennlp.run` command only knows about the registered classes in the ``allennlp`` codebase. In particular, once you start creating your own ``Model`` s and so forth, it won't work for them, unless you use the ``--include-package`` flag.
[ "The", ":", "mod", ":", "~allennlp", ".", "run", "command", "only", "knows", "about", "the", "registered", "classes", "in", "the", "allennlp", "codebase", ".", "In", "particular", "once", "you", "start", "creating", "your", "own", "Model", "s", "and", "so"...
648a36f77db7e45784c047176074f98534c76636
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/commands/__init__.py#L52-L104
train
allenai/allennlp
allennlp/data/fields/text_field.py
TextField.get_padding_lengths
def get_padding_lengths(self) -> Dict[str, int]: """ The ``TextField`` has a list of ``Tokens``, and each ``Token`` gets converted into arrays by (potentially) several ``TokenIndexers``. This method gets the max length (over tokens) associated with each of these arrays. """ ...
python
def get_padding_lengths(self) -> Dict[str, int]: """ The ``TextField`` has a list of ``Tokens``, and each ``Token`` gets converted into arrays by (potentially) several ``TokenIndexers``. This method gets the max length (over tokens) associated with each of these arrays. """ ...
[ "def", "get_padding_lengths", "(", "self", ")", "->", "Dict", "[", "str", ",", "int", "]", ":", "# Our basic outline: we will iterate over `TokenIndexers`, and aggregate lengths over tokens", "# for each indexer separately. Then we will combine the results for each indexer into a single...
The ``TextField`` has a list of ``Tokens``, and each ``Token`` gets converted into arrays by (potentially) several ``TokenIndexers``. This method gets the max length (over tokens) associated with each of these arrays.
[ "The", "TextField", "has", "a", "list", "of", "Tokens", "and", "each", "Token", "gets", "converted", "into", "arrays", "by", "(", "potentially", ")", "several", "TokenIndexers", ".", "This", "method", "gets", "the", "max", "length", "(", "over", "tokens", ...
648a36f77db7e45784c047176074f98534c76636
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/data/fields/text_field.py#L75-L125
train
allenai/allennlp
allennlp/tools/create_elmo_embeddings_from_vocab.py
main
def main(vocab_path: str, elmo_config_path: str, elmo_weights_path: str, output_dir: str, batch_size: int, device: int, use_custom_oov_token: bool = False): """ Creates ELMo word representations from a vocabulary file. These word representations are _ind...
python
def main(vocab_path: str, elmo_config_path: str, elmo_weights_path: str, output_dir: str, batch_size: int, device: int, use_custom_oov_token: bool = False): """ Creates ELMo word representations from a vocabulary file. These word representations are _ind...
[ "def", "main", "(", "vocab_path", ":", "str", ",", "elmo_config_path", ":", "str", ",", "elmo_weights_path", ":", "str", ",", "output_dir", ":", "str", ",", "batch_size", ":", "int", ",", "device", ":", "int", ",", "use_custom_oov_token", ":", "bool", "=",...
Creates ELMo word representations from a vocabulary file. These word representations are _independent_ - they are the result of running the CNN and Highway layers of the ELMo model, but not the Bidirectional LSTM. ELMo requires 2 additional tokens: <S> and </S>. The first token in this file is assumed t...
[ "Creates", "ELMo", "word", "representations", "from", "a", "vocabulary", "file", ".", "These", "word", "representations", "are", "_independent_", "-", "they", "are", "the", "result", "of", "running", "the", "CNN", "and", "Highway", "layers", "of", "the", "ELMo...
648a36f77db7e45784c047176074f98534c76636
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/tools/create_elmo_embeddings_from_vocab.py#L16-L94
train
allenai/allennlp
allennlp/data/iterators/bucket_iterator.py
sort_by_padding
def sort_by_padding(instances: List[Instance], sorting_keys: List[Tuple[str, str]], # pylint: disable=invalid-sequence-index vocab: Vocabulary, padding_noise: float = 0.0) -> List[Instance]: """ Sorts the instances by their padding lengths, using the ...
python
def sort_by_padding(instances: List[Instance], sorting_keys: List[Tuple[str, str]], # pylint: disable=invalid-sequence-index vocab: Vocabulary, padding_noise: float = 0.0) -> List[Instance]: """ Sorts the instances by their padding lengths, using the ...
[ "def", "sort_by_padding", "(", "instances", ":", "List", "[", "Instance", "]", ",", "sorting_keys", ":", "List", "[", "Tuple", "[", "str", ",", "str", "]", "]", ",", "# pylint: disable=invalid-sequence-index", "vocab", ":", "Vocabulary", ",", "padding_noise", ...
Sorts the instances by their padding lengths, using the keys in ``sorting_keys`` (in the order in which they are provided). ``sorting_keys`` is a list of ``(field_name, padding_key)`` tuples.
[ "Sorts", "the", "instances", "by", "their", "padding", "lengths", "using", "the", "keys", "in", "sorting_keys", "(", "in", "the", "order", "in", "which", "they", "are", "provided", ")", ".", "sorting_keys", "is", "a", "list", "of", "(", "field_name", "padd...
648a36f77db7e45784c047176074f98534c76636
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/data/iterators/bucket_iterator.py#L17-L41
train
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
train
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
train
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
train
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
train
allenai/allennlp
allennlp/state_machines/states/lambda_grammar_statelet.py
LambdaGrammarStatelet.take_action
def take_action(self, production_rule: str) -> 'LambdaGrammarStatelet': """ Takes an action in the current grammar state, returning a new grammar state with whatever updates are necessary. The production rule is assumed to be formatted as "LHS -> RHS". This will update the non-terminal...
python
def take_action(self, production_rule: str) -> 'LambdaGrammarStatelet': """ Takes an action in the current grammar state, returning a new grammar state with whatever updates are necessary. The production rule is assumed to be formatted as "LHS -> RHS". This will update the non-terminal...
[ "def", "take_action", "(", "self", ",", "production_rule", ":", "str", ")", "->", "'LambdaGrammarStatelet'", ":", "left_side", ",", "right_side", "=", "production_rule", ".", "split", "(", "' -> '", ")", "assert", "self", ".", "_nonterminal_stack", "[", "-", "...
Takes an action in the current grammar state, returning a new grammar state with whatever updates are necessary. The production rule is assumed to be formatted as "LHS -> RHS". This will update the non-terminal stack and the context-dependent actions. Updating the non-terminal stack involves ...
[ "Takes", "an", "action", "in", "the", "current", "grammar", "state", "returning", "a", "new", "grammar", "state", "with", "whatever", "updates", "are", "necessary", ".", "The", "production", "rule", "is", "assumed", "to", "be", "formatted", "as", "LHS", "-",...
648a36f77db7e45784c047176074f98534c76636
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/state_machines/states/lambda_grammar_statelet.py#L102-L158
train
allenai/allennlp
allennlp/nn/chu_liu_edmonds.py
decode_mst
def decode_mst(energy: numpy.ndarray, length: int, has_labels: bool = True) -> Tuple[numpy.ndarray, numpy.ndarray]: """ Note: Counter to typical intuition, this function decodes the _maximum_ spanning tree. Decode the optimal MST tree with the Chu-Liu-Edmonds algorithm for...
python
def decode_mst(energy: numpy.ndarray, length: int, has_labels: bool = True) -> Tuple[numpy.ndarray, numpy.ndarray]: """ Note: Counter to typical intuition, this function decodes the _maximum_ spanning tree. Decode the optimal MST tree with the Chu-Liu-Edmonds algorithm for...
[ "def", "decode_mst", "(", "energy", ":", "numpy", ".", "ndarray", ",", "length", ":", "int", ",", "has_labels", ":", "bool", "=", "True", ")", "->", "Tuple", "[", "numpy", ".", "ndarray", ",", "numpy", ".", "ndarray", "]", ":", "if", "has_labels", "a...
Note: Counter to typical intuition, this function decodes the _maximum_ spanning tree. Decode the optimal MST tree with the Chu-Liu-Edmonds algorithm for maximum spanning arborescences on graphs. Parameters ---------- energy : ``numpy.ndarray``, required. A tensor with shape (num_label...
[ "Note", ":", "Counter", "to", "typical", "intuition", "this", "function", "decodes", "the", "_maximum_", "spanning", "tree", "." ]
648a36f77db7e45784c047176074f98534c76636
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/nn/chu_liu_edmonds.py#L7-L85
train
allenai/allennlp
allennlp/nn/chu_liu_edmonds.py
chu_liu_edmonds
def chu_liu_edmonds(length: int, score_matrix: numpy.ndarray, current_nodes: List[bool], final_edges: Dict[int, int], old_input: numpy.ndarray, old_output: numpy.ndarray, representatives: List[Set[int...
python
def chu_liu_edmonds(length: int, score_matrix: numpy.ndarray, current_nodes: List[bool], final_edges: Dict[int, int], old_input: numpy.ndarray, old_output: numpy.ndarray, representatives: List[Set[int...
[ "def", "chu_liu_edmonds", "(", "length", ":", "int", ",", "score_matrix", ":", "numpy", ".", "ndarray", ",", "current_nodes", ":", "List", "[", "bool", "]", ",", "final_edges", ":", "Dict", "[", "int", ",", "int", "]", ",", "old_input", ":", "numpy", "...
Applies the chu-liu-edmonds algorithm recursively to a graph with edge weights defined by score_matrix. Note that this function operates in place, so variables will be modified. Parameters ---------- length : ``int``, required. The number of nodes. score_matrix : ``numpy.ndarray``,...
[ "Applies", "the", "chu", "-", "liu", "-", "edmonds", "algorithm", "recursively", "to", "a", "graph", "with", "edge", "weights", "defined", "by", "score_matrix", "." ]
648a36f77db7e45784c047176074f98534c76636
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/nn/chu_liu_edmonds.py#L87-L241
train
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
train
allenai/allennlp
allennlp/training/moving_average.py
MovingAverage.restore
def restore(self) -> None: """ Restore the backed-up (non-average) parameter values. """ for name, parameter in self._parameters: parameter.data.copy_(self._backups[name])
python
def restore(self) -> None: """ Restore the backed-up (non-average) parameter values. """ for name, parameter in self._parameters: parameter.data.copy_(self._backups[name])
[ "def", "restore", "(", "self", ")", "->", "None", ":", "for", "name", ",", "parameter", "in", "self", ".", "_parameters", ":", "parameter", ".", "data", ".", "copy_", "(", "self", ".", "_backups", "[", "name", "]", ")" ]
Restore the backed-up (non-average) parameter values.
[ "Restore", "the", "backed", "-", "up", "(", "non", "-", "average", ")", "parameter", "values", "." ]
648a36f77db7e45784c047176074f98534c76636
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/training/moving_average.py#L36-L41
train
allenai/allennlp
allennlp/modules/similarity_functions/similarity_function.py
SimilarityFunction.forward
def forward(self, tensor_1: torch.Tensor, tensor_2: torch.Tensor) -> torch.Tensor: # pylint: disable=arguments-differ """ Takes two tensors of the same shape, such as ``(batch_size, length_1, length_2, embedding_dim)``. Computes a (possibly parameterized) similarity on the final dimensi...
python
def forward(self, tensor_1: torch.Tensor, tensor_2: torch.Tensor) -> torch.Tensor: # pylint: disable=arguments-differ """ Takes two tensors of the same shape, such as ``(batch_size, length_1, length_2, embedding_dim)``. Computes a (possibly parameterized) similarity on the final dimensi...
[ "def", "forward", "(", "self", ",", "tensor_1", ":", "torch", ".", "Tensor", ",", "tensor_2", ":", "torch", ".", "Tensor", ")", "->", "torch", ".", "Tensor", ":", "# pylint: disable=arguments-differ", "raise", "NotImplementedError" ]
Takes two tensors of the same shape, such as ``(batch_size, length_1, length_2, embedding_dim)``. Computes a (possibly parameterized) similarity on the final dimension and returns a tensor with one less dimension, such as ``(batch_size, length_1, length_2)``.
[ "Takes", "two", "tensors", "of", "the", "same", "shape", "such", "as", "(", "batch_size", "length_1", "length_2", "embedding_dim", ")", ".", "Computes", "a", "(", "possibly", "parameterized", ")", "similarity", "on", "the", "final", "dimension", "and", "return...
648a36f77db7e45784c047176074f98534c76636
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/modules/similarity_functions/similarity_function.py#L23-L30
train
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
train
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
train
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
train
allenai/allennlp
allennlp/modules/token_embedders/embedding.py
_read_embeddings_from_text_file
def _read_embeddings_from_text_file(file_uri: str, embedding_dim: int, vocab: Vocabulary, namespace: str = "tokens") -> torch.FloatTensor: """ Read pre-trained word vectors from an eventually compressed t...
python
def _read_embeddings_from_text_file(file_uri: str, embedding_dim: int, vocab: Vocabulary, namespace: str = "tokens") -> torch.FloatTensor: """ Read pre-trained word vectors from an eventually compressed t...
[ "def", "_read_embeddings_from_text_file", "(", "file_uri", ":", "str", ",", "embedding_dim", ":", "int", ",", "vocab", ":", "Vocabulary", ",", "namespace", ":", "str", "=", "\"tokens\"", ")", "->", "torch", ".", "FloatTensor", ":", "tokens_to_keep", "=", "set"...
Read pre-trained word vectors from an eventually compressed text file, possibly contained inside an archive with multiple files. The text file is assumed to be utf-8 encoded with space-separated fields: [word] [dim 1] [dim 2] ... Lines that contain more numerical tokens than ``embedding_dim`` raise a warni...
[ "Read", "pre", "-", "trained", "word", "vectors", "from", "an", "eventually", "compressed", "text", "file", "possibly", "contained", "inside", "an", "archive", "with", "multiple", "files", ".", "The", "text", "file", "is", "assumed", "to", "be", "utf", "-", ...
648a36f77db7e45784c047176074f98534c76636
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/modules/token_embedders/embedding.py#L374-L443
train
allenai/allennlp
allennlp/modules/token_embedders/embedding.py
_read_embeddings_from_hdf5
def _read_embeddings_from_hdf5(embeddings_filename: str, embedding_dim: int, vocab: Vocabulary, namespace: str = "tokens") -> torch.FloatTensor: """ Reads from a hdf5 formatted file. The embedding matrix is assumed to ...
python
def _read_embeddings_from_hdf5(embeddings_filename: str, embedding_dim: int, vocab: Vocabulary, namespace: str = "tokens") -> torch.FloatTensor: """ Reads from a hdf5 formatted file. The embedding matrix is assumed to ...
[ "def", "_read_embeddings_from_hdf5", "(", "embeddings_filename", ":", "str", ",", "embedding_dim", ":", "int", ",", "vocab", ":", "Vocabulary", ",", "namespace", ":", "str", "=", "\"tokens\"", ")", "->", "torch", ".", "FloatTensor", ":", "with", "h5py", ".", ...
Reads from a hdf5 formatted file. The embedding matrix is assumed to be keyed by 'embedding' and of size ``(num_tokens, embedding_dim)``.
[ "Reads", "from", "a", "hdf5", "formatted", "file", ".", "The", "embedding", "matrix", "is", "assumed", "to", "be", "keyed", "by", "embedding", "and", "of", "size", "(", "num_tokens", "embedding_dim", ")", "." ]
648a36f77db7e45784c047176074f98534c76636
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/modules/token_embedders/embedding.py#L446-L462
train
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
train
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
train
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
train
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
train