code stringlengths 66 870k | docstring stringlengths 19 26.7k | func_name stringlengths 1 138 | language stringclasses 1
value | repo stringlengths 7 68 | path stringlengths 5 324 | url stringlengths 46 389 | license stringclasses 7
values |
|---|---|---|---|---|---|---|---|
def _get_productions_from_string(production_string ) :
u"""
Takes a string like '[<d,d>, d]' and parses it into a list like ['<d,d>', 'd']. For
production strings that are not lists, like '<e,d>', we return a single-element list:
['<e,d>'].
"""
if product... |
Takes a string like '[<d,d>, d]' and parses it into a list like ['<d,d>', 'd']. For
production strings that are not lists, like '<e,d>', we return a single-element list:
['<e,d>'].
| _get_productions_from_string | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/nn/decoding/grammar_state.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/nn/decoding/grammar_state.py | MIT |
def construct_prefix_tree(targets ,
target_mask = None) :
u"""
Takes a list of valid target action sequences and creates a mapping from all possible
(valid) action prefixes to... |
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 a... | construct_prefix_tree | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/nn/decoding/util.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/nn/decoding/util.py | MIT |
def decode(self,
initial_state ,
decode_step ,
supervision ) :
u"""
Takes an initial state object, a means of transitioning from state to state, and a
supervision signal, and uses the ... |
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... | decode | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/nn/decoding/decoder_trainers/decoder_trainer.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/nn/decoding/decoder_trainers/decoder_trainer.py | MIT |
def _prune_beam(states ,
beam_size ,
sort_states = False) :
u"""
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 stat... |
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 metho... | _prune_beam | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/nn/decoding/decoder_trainers/expected_risk_minimization.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/nn/decoding/decoder_trainers/expected_risk_minimization.py | MIT |
def _get_best_action_sequences(self,
finished_states ) :
u"""
Returns the best action sequences for each item based on model scores. We return at most
``self._max_num_decoded_sequences`` number of sequences per insta... |
Returns the best action sequences for each item based on model scores. We return at most
``self._max_num_decoded_sequences`` number of sequences per instance.
| _get_best_action_sequences | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/nn/decoding/decoder_trainers/expected_risk_minimization.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/nn/decoding/decoder_trainers/expected_risk_minimization.py | MIT |
def __call__(self, module ) :
u"""
Parameters
----------
module : torch.nn.Module, required
The module to regularize.
"""
accumulator = 0.0
# For each parameter find the first matching regex.
for name, parameter i... |
Parameters
----------
module : torch.nn.Module, required
The module to regularize.
| __call__ | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/nn/regularizers/regularizer_applicator.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/nn/regularizers/regularizer_applicator.py | MIT |
def from_params(cls, params = ()) :
u"""
Converts a List of pairs (regex, params) into an RegularizerApplicator.
This list should look like
[["regex1": {"type": "l2", "alpha": 0.01}], ["regex2": "l1"]]
where each... |
Converts a List of pairs (regex, params) into an RegularizerApplicator.
This list should look like
[["regex1": {"type": "l2", "alpha": 0.01}], ["regex2": "l1"]]
where each parameter receives the penalty corresponding to the first regex
that matches its name (which may be no re... | from_params | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/nn/regularizers/regularizer_applicator.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/nn/regularizers/regularizer_applicator.py | MIT |
def _json_to_instance(self, json_dict ) :
u"""
Expects JSON that looks like ``{"sentence": "..."}``.
"""
spacy_tokens = self._tokenizer.split_words(json_dict[u"sentence"])
sentence_text = [token.text for token in spacy_tokens]
pos_tags = [token.tag_ fo... |
Expects JSON that looks like ``{"sentence": "..."}``.
| _json_to_instance | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/predictors/biaffine_dependency_parser.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/predictors/biaffine_dependency_parser.py | MIT |
def _build_hierplane_tree(words ,
heads ,
tags ,
pos ) :
u"""
Returns
-------
A JSON dictionary render-able by Hierplane for the given tree.
... |
Returns
-------
A JSON dictionary render-able by Hierplane for the given tree.
| _build_hierplane_tree | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/predictors/biaffine_dependency_parser.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/predictors/biaffine_dependency_parser.py | MIT |
def _json_to_instance(self, json_dict ) :
u"""
Expects JSON that looks like ``{"question": "...", "passage": "..."}``.
"""
question_text = json_dict[u"question"]
passage_text = json_dict[u"passage"]
return self._dataset_reader.text_to_instance(question... |
Expects JSON that looks like ``{"question": "...", "passage": "..."}``.
| _json_to_instance | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/predictors/bidaf.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/predictors/bidaf.py | MIT |
def _build_hierplane_tree(self, tree , index , is_root ) :
u"""
Recursively builds a JSON dictionary from an NLTK ``Tree`` suitable for
rendering trees using the `Hierplane library<https://allenai.github.io/hierplane/>`.
Parameters
----------
tre... |
Recursively builds a JSON dictionary from an NLTK ``Tree`` suitable for
rendering trees using the `Hierplane library<https://allenai.github.io/hierplane/>`.
Parameters
----------
tree : ``Tree``, required.
The tree to convert into Hierplane JSON.
index : int... | _build_hierplane_tree | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/predictors/constituency_parser.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/predictors/constituency_parser.py | MIT |
def _json_to_instance(self, json_dict ) :
u"""
Expects JSON that looks like ``{"document": "string of document text"}``
"""
document = json_dict[u"document"]
spacy_document = self._spacy(document)
sentences = [[token.text for token in sentence] for sen... |
Expects JSON that looks like ``{"document": "string of document text"}``
| _json_to_instance | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/predictors/coref.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/predictors/coref.py | MIT |
def _json_to_instance(self, json_dict ) :
u"""
Expects JSON that looks like ``{"premise": "...", "hypothesis": "..."}``.
"""
premise_text = json_dict[u"premise"]
hypothesis_text = json_dict[u"hypothesis"]
return self._dataset_reader.text_to_instance(pr... |
Expects JSON that looks like ``{"premise": "...", "hypothesis": "..."}``.
| _json_to_instance | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/predictors/decomposable_attention.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/predictors/decomposable_attention.py | MIT |
def _batch_json_to_instances(self, json_dicts ) :
u"""
Converts a list of JSON objects into a list of :class:`~allennlp.data.instance.Instance`s.
By default, this expects that a "batch" consists of a list of JSON blobs which would
individually be predicted... |
Converts a list of JSON objects into a list of :class:`~allennlp.data.instance.Instance`s.
By default, this expects that a "batch" consists of a list of JSON blobs which would
individually be predicted by :func:`predict_json`. In order to use this method for
batch prediction, :func:`_js... | _batch_json_to_instances | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/predictors/predictor.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/predictors/predictor.py | MIT |
def from_archive(cls, archive , predictor_name = None) :
u"""
Instantiate a :class:`Predictor` from an :class:`~allennlp.models.archival.Archive`;
that is, from the result of training a model. Optionally specify which `Predictor`
subclass; otherwise, the defaul... |
Instantiate a :class:`Predictor` from an :class:`~allennlp.models.archival.Archive`;
that is, from the result of training a model. Optionally specify which `Predictor`
subclass; otherwise, the default one for the model will be used.
| from_archive | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/predictors/predictor.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/predictors/predictor.py | MIT |
def _sentence_to_srl_instances(self, json_dict ) :
u"""
The SRL model has a slightly different API from other models, as the model is run
forward for every verb in the sentence. This means that for a single sentence, we need
to generate a ``List[Instance]``, whe... |
The SRL model has a slightly different API from other models, as the model is run
forward for every verb in the sentence. This means that for a single sentence, we need
to generate a ``List[Instance]``, where the length of this list corresponds to the number
of verbs in the sentence. Ad... | _sentence_to_srl_instances | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/predictors/semantic_role_labeler.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/predictors/semantic_role_labeler.py | MIT |
def predict_batch_json(self, inputs ) :
u"""
Expects JSON that looks like ``[{"sentence": "..."}, {"sentence": "..."}, ...]``
and returns JSON that looks like
.. code-block:: js
[
{"words": [...],
"verbs": [
... |
Expects JSON that looks like ``[{"sentence": "..."}, {"sentence": "..."}, ...]``
and returns JSON that looks like
.. code-block:: js
[
{"words": [...],
"verbs": [
{"verb": "...", "description": "...", "tags": [...]},
... | predict_batch_json | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/predictors/semantic_role_labeler.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/predictors/semantic_role_labeler.py | MIT |
def predict_json(self, inputs ) :
u"""
Expects JSON that looks like ``{"sentence": "..."}``
and returns JSON that looks like
.. code-block:: js
{"words": [...],
"verbs": [
{"verb": "...", "description": "...", "tags": [...]},... |
Expects JSON that looks like ``{"sentence": "..."}``
and returns JSON that looks like
.. code-block:: js
{"words": [...],
"verbs": [
{"verb": "...", "description": "...", "tags": [...]},
...
{"verb": "...", "description"... | predict_json | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/predictors/semantic_role_labeler.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/predictors/semantic_role_labeler.py | MIT |
def _json_to_instance(self, json_dict ) :
u"""
Expects JSON that looks like ``{"sentence": "..."}``.
Runs the underlying model, and adds the ``"words"`` to the output.
"""
sentence = json_dict[u"sentence"]
tokens = self._tokenizer.split_words(sentence)... |
Expects JSON that looks like ``{"sentence": "..."}``.
Runs the underlying model, and adds the ``"words"`` to the output.
| _json_to_instance | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/predictors/sentence_tagger.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/predictors/sentence_tagger.py | MIT |
def _json_to_instance(self, json_dict ) :
u"""
Expects JSON that looks like ``{"question": "...", "table": "..."}``.
"""
question_text = json_dict[u"question"]
table_rows = json_dict[u"table"].split(u'\n')
# pylint: disable=protected-access
to... |
Expects JSON that looks like ``{"question": "...", "table": "..."}``.
| _json_to_instance | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/predictors/wikitables_parser.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/predictors/wikitables_parser.py | MIT |
def _execute_logical_form_on_table(logical_form , table ):
u"""
The parameters are written out to files which the jar file reads and then executes the
logical form.
"""
logical_form_filename = os.path.join(SEMPRE_DIR, u'logical_forms.txt')
with open(logical_form_f... |
The parameters are written out to files which the jar file reads and then executes the
logical form.
| _execute_logical_form_on_table | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/predictors/wikitables_parser.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/predictors/wikitables_parser.py | MIT |
def _walk(self) :
u"""
Walk over action space to collect completed paths of at most ``self._max_path_length`` steps.
"""
# Buffer of NTs to expand, previous actions
incomplete_paths = [([unicode(type_)], ["{START_SYMBOL} -> {type_}"]) for type_ in
... |
Walk over action space to collect completed paths of at most ``self._max_path_length`` steps.
| _walk | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/semparse/action_space_walker.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/semparse/action_space_walker.py | MIT |
def lisp_to_nested_expression(lisp_string ) :
u"""
Takes a logical form as a lisp string and returns a nested list representation of the lisp.
For example, "(count (division first))" would get mapped to ['count', ['division', 'first']].
"""
stack = []
current_expression = ... |
Takes a logical form as a lisp string and returns a nested list representation of the lisp.
For example, "(count (division first))" would get mapped to ['count', ['division', 'first']].
| lisp_to_nested_expression | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/semparse/util.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/semparse/util.py | MIT |
def get_times_from_utterance(utterance ,
char_offset_to_token_index ,
indices_of_approximate_words ) :
u"""
Given an utterance, we get the numbers that correspond to times and convert them to
values ... |
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``.
| get_times_from_utterance | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/semparse/contexts/atis_tables.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/semparse/contexts/atis_tables.py | MIT |
def get_date_from_utterance(tokenized_utterance ,
year = 1993,
month = None,
day = None) :
u"""
When the year is not explicitly mentioned in the utterance, the query assumes that
it is 1... |
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.
| get_date_from_utterance | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/semparse/contexts/atis_tables.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/semparse/contexts/atis_tables.py | MIT |
def get_numbers_from_utterance(utterance , tokenized_utterance ) :
u"""
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... |
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.
... | get_numbers_from_utterance | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/semparse/contexts/atis_tables.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/semparse/contexts/atis_tables.py | MIT |
def digit_to_query_time(digit ) :
u"""
Given a digit in the utterance, return a list of the times that it corresponds to.
"""
if int(digit) % 12 == 0:
return [0, 1200, 2400]
return [int(digit) * HOUR_TO_TWENTY_FOUR,
(int(digit) * HOUR_TO_TWENTY_FOUR + TWELVE_TO_TW... |
Given a digit in the utterance, return a list of the times that it corresponds to.
| digit_to_query_time | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/semparse/contexts/atis_tables.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/semparse/contexts/atis_tables.py | MIT |
def get_approximate_times(times ) :
u"""
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 ``about 7pm`` appears in the utterance, then
we also want to add ``1830`` and ``1930``.
| get_approximate_times | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/semparse/contexts/atis_tables.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/semparse/contexts/atis_tables.py | MIT |
def _time_regex_match(regex ,
utterance ,
char_offset_to_token_index ,
map_match_to_query_value ,
indices_of_approximate_words ) :
ur"""
Given... |
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 rege... | _time_regex_match | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/semparse/contexts/atis_tables.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/semparse/contexts/atis_tables.py | MIT |
def initialize_valid_actions(self) :
u"""
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
... |
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... | initialize_valid_actions | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/semparse/contexts/sql_table_context.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/semparse/contexts/sql_table_context.py | MIT |
def add_action(self, node ) :
u"""
For each node, we accumulate the rules that generated its children in a list.
"""
if node.expr.name and node.expr.name != u'ws':
nonterminal = '{node.expr.name} -> '
if isinstance(node.expr, Literal):
... |
For each node, we accumulate the rules that generated its children in a list.
| add_action | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/semparse/contexts/sql_table_context.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/semparse/contexts/sql_table_context.py | MIT |
def read_from_json(cls, json_object ) :
u"""
We read tables formatted as JSON objects (dicts) here. This is useful when you are reading
data from a demo. The expected format is::
{"question": [token1, token2, ...],
"columns... |
We read tables formatted as JSON objects (dicts) here. This is useful when you are reading
data from a demo. The expected format is::
{"question": [token1, token2, ...],
"columns": [column1, column2, ...],
"cells": [[row1_cell1, row1_cell2, ...],
... | read_from_json | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/semparse/contexts/table_question_knowledge_graph.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/semparse/contexts/table_question_knowledge_graph.py | MIT |
def _normalize_string(string ) :
u"""
These are the transformation rules used to normalize cell in column names in Sempre. See
``edu.stanford.nlp.sempre.tables.StringNormalizationUtils.characterNormalize`` and
``edu.stanford.nlp.sempre.tables.TableTypeSystem.canonicalizeName``... |
These are the transformation rules used to normalize cell in column names in Sempre. See
``edu.stanford.nlp.sempre.tables.StringNormalizationUtils.characterNormalize`` and
``edu.stanford.nlp.sempre.tables.TableTypeSystem.canonicalizeName``. We reproduce those
rules here to normalize a... | _normalize_string | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/semparse/contexts/table_question_knowledge_graph.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/semparse/contexts/table_question_knowledge_graph.py | MIT |
def _get_numbers_from_tokens(tokens ) :
u"""
Finds numbers in the input tokens and returns them as strings. We do some simple heuristic
number recognition, finding ordinals and cardinals expressed as text ("one", "first",
etc.), as well as numerals ("... |
Finds numbers in the input tokens and returns them as strings. We do some simple heuristic
number recognition, finding ordinals and cardinals expressed as text ("one", "first",
etc.), as well as numerals ("7th", "3rd"), months (mapping "july" to 7), and units
("1ghz").
We also... | _get_numbers_from_tokens | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/semparse/contexts/table_question_knowledge_graph.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/semparse/contexts/table_question_knowledge_graph.py | MIT |
def _get_cell_parts(cls, cell_text ) :
u"""
Splits a cell into parts and returns the parts of the cell. We return a list of
``(entity_name, entity_text)``, where ``entity_name`` is ``fb:part.[something]``, and
``entity_text`` is the text of the cell correspon... |
Splits a cell into parts and returns the parts of the cell. We return a list of
``(entity_name, entity_text)``, where ``entity_name`` is ``fb:part.[something]``, and
``entity_text`` is the text of the cell corresponding to that part. For many cells, there
is only one "part", and we re... | _get_cell_parts | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/semparse/contexts/table_question_knowledge_graph.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/semparse/contexts/table_question_knowledge_graph.py | MIT |
def _should_split_cell(cls, cell_text ) :
u"""
Checks whether the cell should be split. We're just doing the same thing that SEMPRE did
here.
"""
if u', ' in cell_text or u'\n' in cell_text or u'/' in cell_text:
return True
return False |
Checks whether the cell should be split. We're just doing the same thing that SEMPRE did
here.
| _should_split_cell | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/semparse/contexts/table_question_knowledge_graph.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/semparse/contexts/table_question_knowledge_graph.py | MIT |
def get_linked_agenda_items(self) :
u"""
Returns entities that can be linked to spans in the question, that should be in the agenda,
for training a coverage based semantic parser. This method essentially does a heuristic
entity linking, to provide weak supervision for a learn... |
Returns entities that can be linked to spans in the question, that should be in the agenda,
for training a coverage based semantic parser. This method essentially does a heuristic
entity linking, to provide weak supervision for a learning to search parser.
| get_linked_agenda_items | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/semparse/contexts/table_question_knowledge_graph.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/semparse/contexts/table_question_knowledge_graph.py | MIT |
def return_type(self) :
u"""
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 ... |
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 ... | return_type | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/semparse/type_declarations/type_declaration.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/semparse/type_declarations/type_declaration.py | MIT |
def argument_types(self) :
u"""
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-o... |
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... | argument_types | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/semparse/type_declarations/type_declaration.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/semparse/type_declarations/type_declaration.py | MIT |
def substitute_any_type(self, basic_types ) :
u"""
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(se... |
Takes a set of ``BasicTypes`` and replaces any instances of ``ANY_TYPE`` inside this
complex type with each of those basic types.
| substitute_any_type | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/semparse/type_declarations/type_declaration.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/semparse/type_declarations/type_declaration.py | MIT |
def _set_type(self, other_type = ANY_TYPE, signature=None) :
u"""
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... |
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... | _set_type | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/semparse/type_declarations/type_declaration.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/semparse/type_declarations/type_declaration.py | MIT |
def substitute_any_type(type_ , basic_types ) :
u"""
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,... |
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 p... | substitute_any_type | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/semparse/type_declarations/type_declaration.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/semparse/type_declarations/type_declaration.py | MIT |
def _get_complex_type_production(complex_type ) :
u"""
Takes a complex type (without any placeholders), gets its return value, and returns a single
production (perhaps with multiple arguments) that produces the return value. For example, if
the complex is ``<a,<<b,c>,d>>`... |
Takes a complex type (without any placeholders), gets its return value, and returns a single
production (perhaps with multiple arguments) that produces the return value. For example, if
the complex is ``<a,<<b,c>,d>>``, this gives the following tuple:
``('d', 'd -> [<a,<<b,c>,d>, a, <b,c>])``
| _get_complex_type_production | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/semparse/type_declarations/type_declaration.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/semparse/type_declarations/type_declaration.py | MIT |
def get_strings_from_utterance(tokenized_utterance ) :
u"""
Based on the current utterance, return a dictionary where the keys are the strings in the utterance
that map to lists of the token indices that they are linked to.
"""
string_linking_scores ... |
Based on the current utterance, return a dictionary where the keys are the strings in the utterance
that map to lists of the token indices that they are linked to.
| get_strings_from_utterance | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/semparse/worlds/atis_world.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/semparse/worlds/atis_world.py | MIT |
def init_all_valid_actions(self) :
u"""
We initialize the valid actions with the global actions. We then iterate through the
utterances up to and including the current utterance and add the valid strings.
"""
valid_actions = deepcopy(... |
We initialize the valid actions with the global actions. We then iterate through the
utterances up to and including the current utterance and add the valid strings.
| init_all_valid_actions | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/semparse/worlds/atis_world.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/semparse/worlds/atis_world.py | MIT |
def get_grammar_str(self) :
u"""
Generate a string that can be used to instantiate a ``Grammar`` object. The string is a sequence of
rules that define the grammar.
"""
grammar_str_with_context = self.sql_table_context.grammar_str
numbers = [number.split(u" -> ")[1].... |
Generate a string that can be used to instantiate a ``Grammar`` object. The string is a sequence of
rules that define the grammar.
| get_grammar_str | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/semparse/worlds/atis_world.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/semparse/worlds/atis_world.py | MIT |
def all_possible_actions(self) :
u"""
Return a sorted list of strings representing all possible actions
of the form: nonterminal -> [right_hand_side]
"""
all_actions = set()
for _, action_list in list(self.valid_actions.items()):
for action in acti... |
Return a sorted list of strings representing all possible actions
of the form: nonterminal -> [right_hand_side]
| all_possible_actions | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/semparse/worlds/atis_world.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/semparse/worlds/atis_world.py | MIT |
def get_agenda_for_sentence(self,
sentence ,
add_paths_to_agenda = False) :
u"""
Given a ``sentence``, returns a list of actions the sentence triggers as an ``agenda``. The
``agenda`` can be used while by a par... |
Given a ``sentence``, returns a list of actions the sentence triggers as an ``agenda``. The
``agenda`` can be used while by a parser to guide the decoder. sequences as possible. This
is a simplistic mapping at this point, and can be expanded.
Parameters
----------
sent... | get_agenda_for_sentence | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/semparse/worlds/nlvr_world.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/semparse/worlds/nlvr_world.py | MIT |
def _get_number_productions(sentence ) :
u"""
Gathers all the numbers in the sentence, and returns productions that lead to them.
"""
# The mapping here is very simple and limited, which also shouldn't be a problem
# because numbers seem to be represented fairly r... |
Gathers all the numbers in the sentence, and returns productions that lead to them.
| _get_number_productions | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/semparse/worlds/nlvr_world.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/semparse/worlds/nlvr_world.py | MIT |
def _add_nonterminal_productions(self, agenda ) :
u"""
Given a partially populated agenda with (mostly) terminal productions, this method adds the
nonterminal productions that lead from the root to the terminal productions.
"""
nonterminal_productions = set(... |
Given a partially populated agenda with (mostly) terminal productions, this method adds the
nonterminal productions that lead from the root to the terminal productions.
| _add_nonterminal_productions | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/semparse/worlds/nlvr_world.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/semparse/worlds/nlvr_world.py | MIT |
def execute(self, logical_form ) :
u"""
Execute the logical form. The top level function is an assertion function (see below). We
just parse the string into a list and pass the whole thing to ``_execute_assertion`` and let
the method deal with it. This is because the dataset c... |
Execute the logical form. The top level function is an assertion function (see below). We
just parse the string into a list and pass the whole thing to ``_execute_assertion`` and let
the method deal with it. This is because the dataset contains sentences (instead of
questions), and they... | execute | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/semparse/worlds/nlvr_world.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/semparse/worlds/nlvr_world.py | MIT |
def _execute_assertion(self, sub_expression ) :
u"""
Assertion functions are boolean functions. They are of two types:
1) Exists functions: They take one argument, a set and check whether it is not empty.
Syntax: ``(exists_function function_returning_entities)``
Examp... |
Assertion functions are boolean functions. They are of two types:
1) Exists functions: They take one argument, a set and check whether it is not empty.
Syntax: ``(exists_function function_returning_entities)``
Example: ``(object_exists (black (top all_objects)))`` ("There is a black obj... | _execute_assertion | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/semparse/worlds/nlvr_world.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/semparse/worlds/nlvr_world.py | MIT |
def _execute_box_filter(self, sub_expression ) :
u"""
Box filtering functions either apply a filter on a set of boxes and return the filtered set,
or return all the boxes.
The elements should evaluate to one of the following:
``(box_filtering_function ... |
Box filtering functions either apply a filter on a set of boxes and return the filtered set,
or return all the boxes.
The elements should evaluate to one of the following:
``(box_filtering_function set_to_filter constant)`` or
``all_boxes``
In the first kind of forms, t... | _execute_box_filter | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/semparse/worlds/nlvr_world.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/semparse/worlds/nlvr_world.py | MIT |
def _execute_object_filter(self, sub_expression ) :
u"""
Object filtering functions should either be a string referring to all objects, or list which
executes to a filtering operation.
The elements should evaluate to one of the following:
(objec... |
Object filtering functions should either be a string referring to all objects, or list which
executes to a filtering operation.
The elements should evaluate to one of the following:
(object_filtering_function object_set)
((negate_filter object_filtering_function) object_... | _execute_object_filter | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/semparse/worlds/nlvr_world.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/semparse/worlds/nlvr_world.py | MIT |
def _execute_constant(sub_expression ):
u"""
Acceptable constants are numbers or strings starting with `shape_` or `color_`
"""
if not isinstance(sub_expression, unicode):
logger.error(u"Invalid constant: %s", sub_expression)
raise ExecutionError(u"Invalid con... |
Acceptable constants are numbers or strings starting with `shape_` or `color_`
| _execute_constant | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/semparse/worlds/nlvr_world.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/semparse/worlds/nlvr_world.py | MIT |
def _get_objects_with_same_attribute(objects ,
attribute_function ) :
u"""
Returns the set of objects for which the attribute function returns an attribute value that
is most frequent in the initial set, i... |
Returns the set of objects for which the attribute function returns an attribute value that
is most frequent in the initial set, if the frequency is greater than 1. If not, all
objects have different attribute values, and this method returns an empty set.
| _get_objects_with_same_attribute | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/semparse/worlds/nlvr_world.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/semparse/worlds/nlvr_world.py | MIT |
def touch_object(self, objects ) :
u"""
Returns all objects that touch the given set of objects.
"""
objects_per_box = self._separate_objects_by_boxes(objects)
return_set = set()
for box, box_objects in list(objects_per_box.items()):
... |
Returns all objects that touch the given set of objects.
| touch_object | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/semparse/worlds/nlvr_world.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/semparse/worlds/nlvr_world.py | MIT |
def _objects_touch_each_other(cls, object1 , object2 ) :
u"""
Returns true iff the objects touch each other.
"""
in_vertical_range = object1.y_loc <= object2.y_loc + object2.size and\
object1.y_loc + object1.size >= object2.y_loc
i... |
Returns true iff the objects touch each other.
| _objects_touch_each_other | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/semparse/worlds/nlvr_world.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/semparse/worlds/nlvr_world.py | MIT |
def top(self, objects ) :
u"""
Return the topmost objects (i.e. minimum y_loc). The comparison is done separately for each
box.
"""
objects_per_box = self._separate_objects_by_boxes(objects)
return_set = set()
for _, box_obje... |
Return the topmost objects (i.e. minimum y_loc). The comparison is done separately for each
box.
| top | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/semparse/worlds/nlvr_world.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/semparse/worlds/nlvr_world.py | MIT |
def bottom(self, objects ) :
u"""
Return the bottom most objects(i.e. maximum y_loc). The comparison is done separately for
each box.
"""
objects_per_box = self._separate_objects_by_boxes(objects)
return_set = set()
for _, bo... |
Return the bottom most objects(i.e. maximum y_loc). The comparison is done separately for
each box.
| bottom | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/semparse/worlds/nlvr_world.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/semparse/worlds/nlvr_world.py | MIT |
def above(self, objects ) :
u"""
Returns the set of objects in the same boxes that are above the given objects. That is, if
the input is a set of two objects, one in each box, we will return a union of the objects
above the first object in the first box, and tho... |
Returns the set of objects in the same boxes that are above the given objects. That is, if
the input is a set of two objects, one in each box, we will return a union of the objects
above the first object in the first box, and those above the second object in the second box.
| above | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/semparse/worlds/nlvr_world.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/semparse/worlds/nlvr_world.py | MIT |
def below(self, objects ) :
u"""
Returns the set of objects in the same boxes that are below the given objects. That is, if
the input is a set of two objects, one in each box, we will return a union of the objects
below the first object in the first box, and tho... |
Returns the set of objects in the same boxes that are below the given objects. That is, if
the input is a set of two objects, one in each box, we will return a union of the objects
below the first object in the first box, and those below the second object in the second box.
| below | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/semparse/worlds/nlvr_world.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/semparse/worlds/nlvr_world.py | MIT |
def _separate_objects_by_boxes(self, objects ) :
u"""
Given a set of objects, separate them by the boxes they belong to and return a dict.
"""
objects_per_box = defaultdict(list)
for box in self._boxes:
fo... |
Given a set of objects, separate them by the boxes they belong to and return a dict.
| _separate_objects_by_boxes | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/semparse/worlds/nlvr_world.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/semparse/worlds/nlvr_world.py | MIT |
def _remove_action_from_type(valid_actions ,
type_ ,
filter_function ) :
u"""
Finds the production rule matching the filter function in the given type's valid action
list, and ... |
Finds the production rule matching the filter function in the given type's valid action
list, and removes it. If there is more than one matching function, we crash.
| _remove_action_from_type | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/semparse/worlds/wikitables_world.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/semparse/worlds/wikitables_world.py | MIT |
def nltk_tree_to_logical_form(tree ) :
u"""
Given an ``nltk.Tree`` representing the syntax tree that generates a logical form, this method
produces the actual (lisp-like) logical form, with all of the non-terminal symbols converted
into the correct number of parentheses.
"""
# nltk.Tr... |
Given an ``nltk.Tree`` representing the syntax tree that generates a logical form, this method
produces the actual (lisp-like) logical form, with all of the non-terminal symbols converted
into the correct number of parentheses.
| nltk_tree_to_logical_form | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/semparse/worlds/world.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/semparse/worlds/world.py | MIT |
def is_terminal(self, symbol ) :
u"""
This function will be called on nodes of a logical form tree, which are either non-terminal
symbols that can be expanded or terminal symbols that must be leaf nodes. Returns ``True``
if the given symbol is a terminal symbol.
"""
... |
This function will be called on nodes of a logical form tree, which are either non-terminal
symbols that can be expanded or terminal symbols that must be leaf nodes. Returns ``True``
if the given symbol is a terminal symbol.
| is_terminal | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/semparse/worlds/world.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/semparse/worlds/world.py | MIT |
def get_paths_to_root(self,
action ,
max_path_length = 20,
beam_size = 30,
max_num_paths = 10) :
u"""
For a given action, returns at most ``max_num_paths`` paths t... |
For a given action, returns at most ``max_num_paths`` paths to the root (production with
``START_SYMBOL``) that are not longer than ``max_path_length``.
| get_paths_to_root | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/semparse/worlds/world.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/semparse/worlds/world.py | MIT |
def parse_logical_form(self,
logical_form ,
remove_var_function = True) :
u"""
Takes a logical form as a string, maps its tokens using the mapping and returns a parsed expression.
Parameters
----------
... |
Takes a logical form as a string, maps its tokens using the mapping and returns a parsed expression.
Parameters
----------
logical_form : ``str``
Logical form to parse
remove_var_function : ``bool`` (optional)
``var`` is a special function that some lang... | parse_logical_form | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/semparse/worlds/world.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/semparse/worlds/world.py | MIT |
def get_action_sequence(self, expression ) :
u"""
Returns the sequence of actions (as strings) that resulted in the given expression.
"""
# Starting with the type of the whole expression
return self._get_transitions(expression,
... |
Returns the sequence of actions (as strings) that resulted in the given expression.
| get_action_sequence | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/semparse/worlds/world.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/semparse/worlds/world.py | MIT |
def get_logical_form(self,
action_sequence ,
add_var_function = True) :
u"""
Takes an action sequence and constructs a logical form from it. This is useful if you want
to get a logical form from a decoded sequence of actions... |
Takes an action sequence and constructs a logical form from it. This is useful if you want
to get a logical form from a decoded sequence of actions generated by a transition based
semantic parser.
Parameters
----------
action_sequence : ``List[str]``
The seq... | get_logical_form | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/semparse/worlds/world.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/semparse/worlds/world.py | MIT |
def _construct_node_from_actions(self,
current_node ,
remaining_actions ,
add_var_function ) :
u"""
Given a current node in the logical form tree, an... |
Given a current node in the logical form tree, and a list of actions in an action sequence,
this method fills in the children of the current node from the action sequence, then
returns whatever actions are left.
For example, we could get a node with type ``c``, and an action sequence t... | _construct_node_from_actions | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/semparse/worlds/world.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/semparse/worlds/world.py | MIT |
def _infer_num_arguments(cls, type_signature ) :
u"""
Takes a type signature and infers the number of arguments the corresponding function takes.
Examples:
e -> 0
<r,e> -> 1
<e,<e,t>> -> 2
<b,<<b,#1>,<#1,b>>> -> 3
"""
if n... |
Takes a type signature and infers the number of arguments the corresponding function takes.
Examples:
e -> 0
<r,e> -> 1
<e,<e,t>> -> 2
<b,<<b,#1>,<#1,b>>> -> 3
| _infer_num_arguments | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/semparse/worlds/world.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/semparse/worlds/world.py | MIT |
def _process_nested_expression(self, nested_expression) :
u"""
``nested_expression`` is the result of parsing a logical form in Lisp format.
We process it recursively and return a string in the format that NLTK's ``LogicParser``
would understand.
"""
expression_is_l... |
``nested_expression`` is the result of parsing a logical form in Lisp format.
We process it recursively and return a string in the format that NLTK's ``LogicParser``
would understand.
| _process_nested_expression | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/semparse/worlds/world.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/semparse/worlds/world.py | MIT |
def _add_name_mapping(self, name , translated_name , name_type = None):
u"""
Utility method to add a name and its translation to the local name mapping, and the corresponding
signature, if available to the local type signatures. This method also updates the reverse name
map... |
Utility method to add a name and its translation to the local name mapping, and the corresponding
signature, if available to the local type signatures. This method also updates the reverse name
mapping.
| _add_name_mapping | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/semparse/worlds/world.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/semparse/worlds/world.py | MIT |
def make_app(include_packages = ()) :
u"""
Creates a Flask app that serves up a simple configuration wizard.
"""
# Load modules
for package_name in include_packages:
import_submodules(package_name)
app = Flask(__name__) # pylint: disable=invalid-name
@app.er... |
Creates a Flask app that serves up a simple configuration wizard.
| make_app | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/service/config_explorer.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/service/config_explorer.py | MIT |
def make_app(predictor ,
field_names = None,
static_dir = None,
sanitizer = None,
title = u"AllenNLP Demo") :
u"""
Creates a Flask app that serves up the provided ``Predictor``
along wi... |
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 predic... | make_app | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/service/server_simple.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/service/server_simple.py | MIT |
def predict() : # pylint: disable=unused-variable
u"""make a prediction using the specified model and return the results"""
if request.method == u"OPTIONS":
return Response(response=u"", status=200)
data = request.get_json()
prediction = predictor.predict_json(d... | make a prediction using the specified model and return the results | predict | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/service/server_simple.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/service/server_simple.py | MIT |
def _html(title , field_names ) :
u"""
Returns bare bones HTML for serving up an input form with the
specified fields that can render predictions from the configured model.
"""
inputs = u''.join(_SINGLE_INPUT_TEMPLATE.substitute(field_name=field_name)
for fie... |
Returns bare bones HTML for serving up an input form with the
specified fields that can render predictions from the configured model.
| _html | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/service/server_simple.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/service/server_simple.py | MIT |
def test_get_module_root(self):
u"""
When a user runs ``allennlp test-install``, we have no idea where
they're running it from, so we do an ``os.chdir`` to the _module_
root in order to get all the paths in the fixtures to resolve properly.
The logic within ``allennlp test-insta... |
When a user runs ``allennlp test-install``, we have no idea where
they're running it from, so we do an ``os.chdir`` to the _module_
root in order to get all the paths in the fixtures to resolve properly.
The logic within ``allennlp test-install`` is pretty hard to test in
its e... | test_get_module_root | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/tests/commands/test_install_test.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/tests/commands/test_install_test.py | MIT |
def head_callback(_):
u"""
Writing this as a callback allows different responses to different HEAD requests.
In our case, we're going to change the ETag header every `change_etag_every`
requests, which will allow us to simulate having a new version of the file.
"""
nonloc... |
Writing this as a callback allows different responses to different HEAD requests.
In our case, we're going to change the ETag header every `change_etag_every`
requests, which will allow us to simulate having a new version of the file.
| head_callback | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/tests/common/file_utils_test.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/tests/common/file_utils_test.py | MIT |
def set_up_s3_bucket(bucket_name = u"my-bucket", s3_objects = None):
u"""Creates a mock s3 bucket optionally with objects uploaded from local files."""
s3_client = boto3.client(u"s3")
s3_client.create_bucket(Bucket=bucket_name)
for filename, key in s3_objects or []:
s... | Creates a mock s3 bucket optionally with objects uploaded from local files. | set_up_s3_bucket | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/tests/common/file_utils_test.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/tests/common/file_utils_test.py | MIT |
def test_s3_bucket(self):
u"""This just ensures the bucket gets set up correctly."""
set_up_s3_bucket()
s3_client = boto3.client(u"s3")
buckets = s3_client.list_buckets()[u"Buckets"]
assert len(buckets) == 1
assert buckets[0][u"Name"] == u"my-bucket" | This just ensures the bucket gets set up correctly. | test_s3_bucket | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/tests/common/file_utils_test.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/tests/common/file_utils_test.py | MIT |
def test_from_params_valid_vocab_extension_thoroughly(self):
u'''
Tests for Valid Vocab Extension thoroughly: Vocab extension is valid
when overlapping namespaces have same padding behaviour (padded/non-padded)
Summary of namespace paddings in this test:
original_vocab namespaces... |
Tests for Valid Vocab Extension thoroughly: Vocab extension is valid
when overlapping namespaces have same padding behaviour (padded/non-padded)
Summary of namespace paddings in this test:
original_vocab namespaces
tokens0 padded
tokens1 non-padded
... | test_from_params_valid_vocab_extension_thoroughly | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/tests/data/vocabulary_test.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/tests/data/vocabulary_test.py | MIT |
def test_from_instances_exclusive_embeddings_file_inside_archive(self):
u""" Just for ensuring there are no problems when reading pretrained tokens from an archive """
# Read embeddings file from archive
archive_path = unicode(self.TEST_DIR / u"embeddings-archive.zip")
with zipfile.ZipF... | Just for ensuring there are no problems when reading pretrained tokens from an archive | test_from_instances_exclusive_embeddings_file_inside_archive | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/tests/data/vocabulary_test.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/tests/data/vocabulary_test.py | MIT |
def test_forward_pass_runs_correctly(self):
u"""
Check to make sure a forward pass on an ensemble of two identical copies of a model yields the same
results as the model itself.
"""
bidaf_ensemble = BidafEnsemble([self.model, self.model])
batch = Batch(self.instances)
... |
Check to make sure a forward pass on an ensemble of two identical copies of a model yields the same
results as the model itself.
| test_forward_pass_runs_correctly | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/tests/models/reading_comprehension/bidaf_ensemble_test.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/tests/models/reading_comprehension/bidaf_ensemble_test.py | MIT |
def score(self, logits, tags):
u"""
Computes the likelihood score for the given sequence of tags,
given the provided logits (and the transition weights in the CRF model)
"""
# Start with transitions from START and to END
total = self.transitions_from_start[tags[0]] + self... |
Computes the likelihood score for the given sequence of tags,
given the provided logits (and the transition weights in the CRF model)
| score | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/tests/modules/conditional_random_field_test.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/tests/modules/conditional_random_field_test.py | MIT |
def _load_sentences_embeddings(self):
u"""
Load the test sentences and the expected LM embeddings.
These files loaded in this method were created with a batch-size of 3.
Due to idiosyncrasies with TensorFlow, the 30 sentences in sentences.json are split into 3 files in which
the... |
Load the test sentences and the expected LM embeddings.
These files loaded in this method were created with a batch-size of 3.
Due to idiosyncrasies with TensorFlow, the 30 sentences in sentences.json are split into 3 files in which
the k-th sentence in each is from batch k.
T... | _load_sentences_embeddings | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/tests/modules/elmo_test.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/tests/modules/elmo_test.py | MIT |
def create_small_test_fixture(output_dir = u'/tmp') :
u"""
This is how I created the transformer_model.tar.gz.
After running this, go to the specified output dir and run
tar -czvf transformer_model.tar.gz model/
In case you need to regenerate the fixture for some reason.
"""
... |
This is how I created the transformer_model.tar.gz.
After running this, go to the specified output dir and run
tar -czvf transformer_model.tar.gz model/
In case you need to regenerate the fixture for some reason.
| create_small_test_fixture | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/tests/modules/token_embedders/openai_transformer_embedder_test.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/tests/modules/token_embedders/openai_transformer_embedder_test.py | MIT |
def test_html(self):
u"""
The pip-installed version of allennlp (currently) requires the config explorer HTML
to be hardcoded into the server file. But when iterating on it, it's easier to use the
/debug/ endpoint, which points at `config_explorer.html`, so that you don't have to
... |
The pip-installed version of allennlp (currently) requires the config explorer HTML
to be hardcoded into the server file. But when iterating on it, it's easier to use the
/debug/ endpoint, which points at `config_explorer.html`, so that you don't have to
restart the server every time yo... | test_html | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/tests/service/config_explorer_test.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/tests/service/config_explorer_test.py | MIT |
def test_rnn_hack(self):
u"""
Behind the scenes, when you try to create a torch RNN,
it just calls torch.RNNBase with an extra parameter.
This test is to make sure that works correctly.
"""
response = self.client.get(u'/api/config/?class=torch.nn.modules.rnn.LSTM')
... |
Behind the scenes, when you try to create a torch RNN,
it just calls torch.RNNBase with an extra parameter.
This test is to make sure that works correctly.
| test_rnn_hack | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/tests/service/config_explorer_test.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/tests/service/config_explorer_test.py | MIT |
def step(self, closure=None):
u"""
Performs a single optimization step.
Parameters
----------
closure : ``callable``, optional.
A closure that reevaluates the model and returns the loss.
"""
loss = None
if closure is not None:
loss... |
Performs a single optimization step.
Parameters
----------
closure : ``callable``, optional.
A closure that reevaluates the model and returns the loss.
| step | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/training/optimizers.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/training/optimizers.py | MIT |
def sparse_clip_norm(parameters, max_norm, norm_type=2) :
u"""Clips gradient norm of an iterable of parameters.
The norm is computed over all gradients together, as if they were
concatenated into a single vector. Gradients are modified in-place.
Supports sparse gradients.
Parameters
--... | Clips gradient norm of an iterable of parameters.
The norm is computed over all gradients together, as if they were
concatenated into a single vector. Gradients are modified in-place.
Supports sparse gradients.
Parameters
----------
parameters : ``(Iterable[torch.Tensor])``
An iterable... | sparse_clip_norm | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/training/trainer.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/training/trainer.py | MIT |
def move_optimizer_to_cuda(optimizer):
u"""
Move the optimizer state to GPU, if necessary.
After calling, any parameter specific state in the optimizer
will be located on the same device as the parameter.
"""
for param_group in optimizer.param_groups:
for param in param_group[u'params']:... |
Move the optimizer state to GPU, if necessary.
After calling, any parameter specific state in the optimizer
will be located on the same device as the parameter.
| move_optimizer_to_cuda | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/training/trainer.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/training/trainer.py | MIT |
def time_to_str(timestamp ) :
u"""
Convert seconds past Epoch to human readable string.
"""
datetimestamp = datetime.datetime.fromtimestamp(timestamp)
return u'{:04d}-{:02d}-{:02d}-{:02d}-{:02d}-{:02d}'.format(
datetimestamp.year, datetimestamp.month, datetimestamp.day,
... |
Convert seconds past Epoch to human readable string.
| time_to_str | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/training/trainer.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/training/trainer.py | MIT |
def __init__(self,
model ,
optimizer ,
iterator ,
train_dataset ,
validation_dataset = None,
patience = None,
... |
Parameters
----------
model : ``Model``, required.
An AllenNLP model to be optimized. Pytorch Modules can also be optimized if
their ``forward`` method returns a dictionary with a "loss" key, containing a
scalar tensor representing the loss function to be opt... | __init__ | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/training/trainer.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/training/trainer.py | MIT |
def _rescale_gradients(self) :
u"""
Performs gradient rescaling. Is a no-op if gradient rescaling is not enabled.
"""
if self._grad_norm:
parameters_to_clip = [p for p in self._model.parameters()
if p.grad is not None]
... |
Performs gradient rescaling. Is a no-op if gradient rescaling is not enabled.
| _rescale_gradients | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/training/trainer.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/training/trainer.py | MIT |
def _data_parallel(self, batch):
u"""
Do the forward pass using multiple GPUs. This is a simplification
of torch.nn.parallel.data_parallel to support the allennlp model
interface.
"""
inputs, module_kwargs = scatter_kwargs((), batch, self._cuda_devices, 0)
used_d... |
Do the forward pass using multiple GPUs. This is a simplification
of torch.nn.parallel.data_parallel to support the allennlp model
interface.
| _data_parallel | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/training/trainer.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/training/trainer.py | MIT |
def _batch_loss(self, batch , for_training ) :
u"""
Does a forward pass on the given batch and returns the ``loss`` value in the result.
If ``for_training`` is `True` also applies regularization penalty.
"""
if self._multiple_gpu:
outp... |
Does a forward pass on the given batch and returns the ``loss`` value in the result.
If ``for_training`` is `True` also applies regularization penalty.
| _batch_loss | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/training/trainer.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/training/trainer.py | MIT |
def _get_metrics(self, total_loss , num_batches , reset = False) :
u"""
Gets the metrics but sets ``"loss"`` to
the total loss divided by the ``num_batches`` so that
the ``"loss"`` metric is "average loss per batch".
"""
metrics = self._... |
Gets the metrics but sets ``"loss"`` to
the total loss divided by the ``num_batches`` so that
the ``"loss"`` metric is "average loss per batch".
| _get_metrics | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/training/trainer.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/training/trainer.py | MIT |
def _train_epoch(self, epoch ) :
u"""
Trains one epoch and returns metrics.
"""
logger.info(u"Epoch %d/%d", epoch, self._num_epochs - 1)
logger.info("Peak CPU memory usage MB: {peak_memory_mb()}")
for gpu, memory in list(gpu_memory_mb().items()):
... |
Trains one epoch and returns metrics.
| _train_epoch | python | plasticityai/magnitude | pymagnitude/third_party/allennlp/training/trainer.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/allennlp/training/trainer.py | MIT |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.