2020-07-22 14:42:59 +03:00
|
|
|
import pytest
|
2021-12-04 22:34:48 +03:00
|
|
|
from catalogue import RegistryError
|
2020-09-26 14:13:57 +03:00
|
|
|
from thinc.api import Config, ConfigValidationError
|
2021-12-04 22:34:48 +03:00
|
|
|
|
2020-02-27 20:42:27 +03:00
|
|
|
import spacy
|
2020-08-06 00:35:09 +03:00
|
|
|
from spacy.lang.de import German
|
2021-12-04 22:34:48 +03:00
|
|
|
from spacy.lang.en import English
|
|
|
|
from spacy.language import DEFAULT_CONFIG, DEFAULT_CONFIG_PRETRAIN_PATH
|
|
|
|
from spacy.language import Language
|
|
|
|
from spacy.ml.models import MaxoutWindowEncoder, MultiHashEmbed
|
|
|
|
from spacy.ml.models import build_tb_parser_model, build_Tok2Vec_model
|
2020-12-08 09:41:03 +03:00
|
|
|
from spacy.schemas import ConfigSchema, ConfigSchemaPretrain
|
2021-12-04 22:34:48 +03:00
|
|
|
from spacy.util import load_config, load_config_from_str
|
|
|
|
from spacy.util import load_model_from_config, registry
|
2020-07-22 14:42:59 +03:00
|
|
|
|
2020-12-08 09:41:03 +03:00
|
|
|
from ..util import make_tempdir
|
2020-02-27 20:42:27 +03:00
|
|
|
|
|
|
|
nlp_config_string = """
|
2020-08-04 16:09:37 +03:00
|
|
|
[paths]
|
2020-09-29 23:33:46 +03:00
|
|
|
train = null
|
|
|
|
dev = null
|
2020-08-04 16:09:37 +03:00
|
|
|
|
2020-09-17 12:38:59 +03:00
|
|
|
[corpora]
|
2020-09-15 22:58:04 +03:00
|
|
|
|
2020-09-17 12:38:59 +03:00
|
|
|
[corpora.train]
|
2020-08-04 16:09:37 +03:00
|
|
|
@readers = "spacy.Corpus.v1"
|
2020-08-20 12:20:58 +03:00
|
|
|
path = ${paths.train}
|
2020-08-04 16:09:37 +03:00
|
|
|
|
2020-09-17 12:38:59 +03:00
|
|
|
[corpora.dev]
|
2020-08-04 16:09:37 +03:00
|
|
|
@readers = "spacy.Corpus.v1"
|
2020-08-20 12:20:58 +03:00
|
|
|
path = ${paths.dev}
|
2020-08-04 16:09:37 +03:00
|
|
|
|
2020-09-17 12:38:59 +03:00
|
|
|
[training]
|
|
|
|
|
2020-08-04 16:09:37 +03:00
|
|
|
[training.batcher]
|
2020-09-03 18:30:41 +03:00
|
|
|
@batchers = "spacy.batch_by_words.v1"
|
2020-08-04 16:09:37 +03:00
|
|
|
size = 666
|
2020-07-22 14:42:59 +03:00
|
|
|
|
2020-02-27 20:42:27 +03:00
|
|
|
[nlp]
|
|
|
|
lang = "en"
|
2020-07-22 14:42:59 +03:00
|
|
|
pipeline = ["tok2vec", "tagger"]
|
2020-02-27 20:42:27 +03:00
|
|
|
|
2020-07-22 14:42:59 +03:00
|
|
|
[components]
|
2020-07-12 15:28:34 +03:00
|
|
|
|
2020-07-22 14:42:59 +03:00
|
|
|
[components.tok2vec]
|
2020-07-22 18:29:31 +03:00
|
|
|
factory = "tok2vec"
|
2020-02-27 20:42:27 +03:00
|
|
|
|
2020-07-22 14:42:59 +03:00
|
|
|
[components.tok2vec.model]
|
2020-02-27 20:42:27 +03:00
|
|
|
@architectures = "spacy.HashEmbedCNN.v1"
|
|
|
|
pretrained_vectors = null
|
|
|
|
width = 342
|
|
|
|
depth = 4
|
|
|
|
window_size = 1
|
|
|
|
embed_size = 2000
|
|
|
|
maxout_pieces = 3
|
|
|
|
subword_features = true
|
|
|
|
|
2020-07-22 14:42:59 +03:00
|
|
|
[components.tagger]
|
2020-07-22 18:29:31 +03:00
|
|
|
factory = "tagger"
|
2020-02-27 20:42:27 +03:00
|
|
|
|
2020-07-22 14:42:59 +03:00
|
|
|
[components.tagger.model]
|
2022-03-15 16:15:31 +03:00
|
|
|
@architectures = "spacy.Tagger.v2"
|
2020-02-27 20:42:27 +03:00
|
|
|
|
2020-07-22 14:42:59 +03:00
|
|
|
[components.tagger.model.tok2vec]
|
2020-07-29 14:47:37 +03:00
|
|
|
@architectures = "spacy.Tok2VecListener.v1"
|
2020-08-20 12:20:58 +03:00
|
|
|
width = ${components.tok2vec.model.width}
|
2020-02-27 20:42:27 +03:00
|
|
|
"""
|
|
|
|
|
2020-12-08 09:41:03 +03:00
|
|
|
pretrain_config_string = """
|
|
|
|
[paths]
|
|
|
|
train = null
|
|
|
|
dev = null
|
|
|
|
|
|
|
|
[corpora]
|
|
|
|
|
|
|
|
[corpora.train]
|
|
|
|
@readers = "spacy.Corpus.v1"
|
|
|
|
path = ${paths.train}
|
|
|
|
|
|
|
|
[corpora.dev]
|
|
|
|
@readers = "spacy.Corpus.v1"
|
|
|
|
path = ${paths.dev}
|
|
|
|
|
|
|
|
[training]
|
|
|
|
|
|
|
|
[training.batcher]
|
|
|
|
@batchers = "spacy.batch_by_words.v1"
|
|
|
|
size = 666
|
|
|
|
|
|
|
|
[nlp]
|
|
|
|
lang = "en"
|
|
|
|
pipeline = ["tok2vec", "tagger"]
|
|
|
|
|
|
|
|
[components]
|
|
|
|
|
|
|
|
[components.tok2vec]
|
|
|
|
factory = "tok2vec"
|
|
|
|
|
|
|
|
[components.tok2vec.model]
|
|
|
|
@architectures = "spacy.HashEmbedCNN.v1"
|
|
|
|
pretrained_vectors = null
|
|
|
|
width = 342
|
|
|
|
depth = 4
|
|
|
|
window_size = 1
|
|
|
|
embed_size = 2000
|
|
|
|
maxout_pieces = 3
|
|
|
|
subword_features = true
|
|
|
|
|
|
|
|
[components.tagger]
|
|
|
|
factory = "tagger"
|
|
|
|
|
|
|
|
[components.tagger.model]
|
2022-03-15 16:15:31 +03:00
|
|
|
@architectures = "spacy.Tagger.v2"
|
2020-12-08 09:41:03 +03:00
|
|
|
|
|
|
|
[components.tagger.model.tok2vec]
|
|
|
|
@architectures = "spacy.Tok2VecListener.v1"
|
|
|
|
width = ${components.tok2vec.model.width}
|
|
|
|
|
|
|
|
[pretraining]
|
|
|
|
"""
|
|
|
|
|
2020-02-27 20:42:27 +03:00
|
|
|
|
2020-12-18 13:56:57 +03:00
|
|
|
parser_config_string_upper = """
|
2020-02-27 20:42:27 +03:00
|
|
|
[model]
|
Merge the parser refactor into `v4` (#10940)
* Try to fix doc.copy
* Set dev version
* Make vocab always own lexemes
* Change version
* Add SpanGroups.copy method
* Fix set_annotations during Parser.update
* Fix dict proxy copy
* Upd version
* Fix copying SpanGroups
* Fix set_annotations in parser.update
* Fix parser set_annotations during update
* Revert "Fix parser set_annotations during update"
This reverts commit eb138c89edb306608826dca50619ea8a60de2b14.
* Revert "Fix set_annotations in parser.update"
This reverts commit c6df0eafd0046179c1c9fb7840074edf04e4721d.
* Fix set_annotations during parser update
* Inc version
* Handle final states in get_oracle_sequence
* Inc version
* Try to fix parser training
* Inc version
* Fix
* Inc version
* Fix parser oracle
* Inc version
* Inc version
* Fix transition has_gold
* Inc version
* Try to use real histories, not oracle
* Inc version
* Upd parser
* Inc version
* WIP on rewrite parser
* WIP refactor parser
* New progress on parser model refactor
* Prepare to remove parser_model.pyx
* Convert parser from cdef class
* Delete spacy.ml.parser_model
* Delete _precomputable_affine module
* Wire up tb_framework to new parser model
* Wire up parser model
* Uncython ner.pyx and dep_parser.pyx
* Uncython
* Work on parser model
* Support unseen_classes in parser model
* Support unseen classes in parser
* Cleaner handling of unseen classes
* Work through tests
* Keep working through errors
* Keep working through errors
* Work on parser. 15 tests failing
* Xfail beam stuff. 9 failures
* More xfail. 7 failures
* Xfail. 6 failures
* cleanup
* formatting
* fixes
* pass nO through
* Fix empty doc in update
* Hackishly fix resizing. 3 failures
* Fix redundant test. 2 failures
* Add reference version
* black formatting
* Get tests passing with reference implementation
* Fix missing prints
* Add missing file
* Improve indexing on reference implementation
* Get non-reference forward func working
* Start rigging beam back up
* removing redundant tests, cf #8106
* black formatting
* temporarily xfailing issue 4314
* make flake8 happy again
* mypy fixes
* ensure labels are added upon predict
* cleanup remnants from merge conflicts
* Improve unseen label masking
Two changes to speed up masking by ~10%:
- Use a bool array rather than an array of float32.
- Let the mask indicate whether a label was seen, rather than
unseen. The mask is most frequently used to index scores for
seen labels. However, since the mask marked unseen labels,
this required computing an intermittent flipped mask.
* Write moves costs directly into numpy array (#10163)
This avoids elementwise indexing and the allocation of an additional
array.
Gives a ~15% speed improvement when using batch_by_sequence with size
32.
* Temporarily disable ner and rehearse tests
Until rehearse is implemented again in the refactored parser.
* Fix loss serialization issue (#10600)
* Fix loss serialization issue
Serialization of a model fails with:
TypeError: array(738.3855, dtype=float32) is not JSON serializable
Fix this using float conversion.
* Disable CI steps that require spacy.TransitionBasedParser.v2
After finishing the refactor, TransitionBasedParser.v2 should be
provided for backwards compat.
* Add back support for beam parsing to the refactored parser (#10633)
* Add back support for beam parsing
Beam parsing was already implemented as part of the `BeamBatch` class.
This change makes its counterpart `GreedyBatch`. Both classes are hooked
up in `TransitionModel`, selecting `GreedyBatch` when the beam size is
one, or `BeamBatch` otherwise.
* Use kwarg for beam width
Co-authored-by: Sofie Van Landeghem <svlandeg@users.noreply.github.com>
* Avoid implicit default for beam_width and beam_density
* Parser.{beam,greedy}_parse: ensure labels are added
* Remove 'deprecated' comments
Co-authored-by: Sofie Van Landeghem <svlandeg@users.noreply.github.com>
Co-authored-by: Sofie Van Landeghem <svlandeg@users.noreply.github.com>
* Parser `StateC` optimizations (#10746)
* `StateC`: Optimizations
Avoid GIL acquisition in `__init__`
Increase default buffer capacities on init
Reduce C++ exception overhead
* Fix typo
* Replace `set::count` with `set::find`
* Add exception attribute to c'tor
* Remove unused import
* Use a power-of-two value for initial capacity
Use default-insert to init `_heads` and `_unshiftable`
* Merge `cdef` variable declarations and assignments
* Vectorize `example.get_aligned_parses` (#10789)
* `example`: Vectorize `get_aligned_parse`
Rename `numpy` import
* Convert aligned array to lists before returning
* Revert import renaming
* Elide slice arguments when selecting the entire range
* Tagger/morphologizer alignment performance optimizations (#10798)
* `example`: Unwrap `numpy` scalar arrays before passing them to `StringStore.__getitem__`
* `AlignmentArray`: Use native list as staging buffer for offset calculation
* `example`: Vectorize `get_aligned`
* Hoist inner functions out of `get_aligned`
* Replace inline `if..else` clause in assignment statement
* `AlignmentArray`: Use raw indexing into offset and data `numpy` arrays
* `example`: Replace array unique value check with `groupby`
* `example`: Correctly exclude tokens with no alignment in `_get_aligned_vectorized`
Simplify `_get_aligned_non_vectorized`
* `util`: Update `all_equal` docstring
* Explicitly use `int32_t*`
* Restore C CPU inference in the refactored parser (#10747)
* Bring back the C parsing model
The C parsing model is used for CPU inference and is still faster for
CPU inference than the forward pass of the Thinc model.
* Use C sgemm provided by the Ops implementation
* Make tb_framework module Cython, merge in C forward implementation
* TransitionModel: raise in backprop returned from forward_cpu
* Re-enable greedy parse test
* Return transition scores when forward_cpu is used
* Apply suggestions from code review
Import `Model` from `thinc.api`
Co-authored-by: Sofie Van Landeghem <svlandeg@users.noreply.github.com>
* Use relative imports in tb_framework
* Don't assume a default for beam_width
* We don't have a direct dependency on BLIS anymore
* Rename forwards to _forward_{fallback,greedy_cpu}
* Require thinc >=8.1.0,<8.2.0
* tb_framework: clean up imports
* Fix return type of _get_seen_mask
* Move up _forward_greedy_cpu
* Style fixes.
* Lower thinc lowerbound to 8.1.0.dev0
* Formatting fix
Co-authored-by: Adriane Boyd <adrianeboyd@gmail.com>
Co-authored-by: Sofie Van Landeghem <svlandeg@users.noreply.github.com>
Co-authored-by: Adriane Boyd <adrianeboyd@gmail.com>
* Reimplement parser rehearsal function (#10878)
* Reimplement parser rehearsal function
Before the parser refactor, rehearsal was driven by a loop in the
`rehearse` method itself. For each parsing step, the loops would:
1. Get the predictions of the teacher.
2. Get the predictions and backprop function of the student.
3. Compute the loss and backprop into the student.
4. Move the teacher and student forward with the predictions of
the student.
In the refactored parser, we cannot perform search stepwise rehearsal
anymore, since the model now predicts all parsing steps at once.
Therefore, rehearsal is performed in the following steps:
1. Get the predictions of all parsing steps from the student, along
with its backprop function.
2. Get the predictions from the teacher, but use the predictions of
the student to advance the parser while doing so.
3. Compute the loss and backprop into the student.
To support the second step a new method, `advance_with_actions` is
added to `GreedyBatch`, which performs the provided parsing steps.
* tb_framework: wrap upper_W and upper_b in Linear
Thinc's Optimizer cannot handle resizing of existing parameters. Until
it does, we work around this by wrapping the weights/biases of the upper
layer of the parser model in Linear. When the upper layer is resized, we
copy over the existing parameters into a new Linear instance. This does
not trigger an error in Optimizer, because it sees the resized layer as
a new set of parameters.
* Add test for TransitionSystem.apply_actions
* Better FIXME marker
Co-authored-by: Madeesh Kannan <shadeMe@users.noreply.github.com>
* Fixes from Madeesh
* Apply suggestions from Sofie
Co-authored-by: Sofie Van Landeghem <svlandeg@users.noreply.github.com>
* Remove useless assignment
Co-authored-by: Madeesh Kannan <shadeMe@users.noreply.github.com>
Co-authored-by: Sofie Van Landeghem <svlandeg@users.noreply.github.com>
* Rename some identifiers in the parser refactor (#10935)
* Rename _parseC to _parse_batch
* tb_framework: prefix many auxiliary functions with underscore
To clearly state the intent that they are private.
* Rename `lower` to `hidden`, `upper` to `output`
* Parser slow test fixup
We don't have TransitionBasedParser.{v1,v2} until we bring it back as a
legacy option.
* Remove last vestiges of PrecomputableAffine
This does not exist anymore as a separate layer.
* ner: re-enable sentence boundary checks
* Re-enable test that works now.
* test_ner: make loss test more strict again
* Remove commented line
* Re-enable some more beam parser tests
* Remove unused _forward_reference function
* Update for CBlas changes in Thinc 8.1.0.dev2
Bump thinc dependency to 8.1.0.dev3.
* Remove references to spacy.TransitionBasedParser.{v1,v2}
Since they will not be offered starting with spaCy v4.
* `tb_framework`: Replace references to `thinc.backends.linalg` with `CBlas`
* dont use get_array_module (#11056) (#11293)
Co-authored-by: kadarakos <kadar.akos@gmail.com>
* Move `thinc.extra.search` to `spacy.pipeline._parser_internals` (#11317)
* `search`: Move from `thinc.extra.search`
Fix NPE in `Beam.__dealloc__`
* `pytest`: Add support for executing Cython tests
Move `search` tests from thinc and patch them to run with `pytest`
* `mypy` fix
* Update comment
* `conftest`: Expose `register_cython_tests`
* Remove unused import
* Move `argmax` impls to new `_parser_utils` Cython module (#11410)
* Parser does not have to be a cdef class anymore
This also fixes validation of the initialization schema.
* Add back spacy.TransitionBasedParser.v2
* Fix a rename that was missed in #10878.
So that rehearsal tests pass.
* Remove module from setup.py that got added during the merge
* Bring back support for `update_with_oracle_cut_size` (#12086)
* Bring back support for `update_with_oracle_cut_size`
This option was available in the pre-refactor parser, but was never
implemented in the refactored parser. This option cuts transition
sequences that are longer than `update_with_oracle_cut` size into
separate sequences that have at most `update_with_oracle_cut`
transitions. The oracle (gold standard) transition sequence is used to
determine the cuts and the initial states for the additional sequences.
Applying this cut makes the batches more homogeneous in the transition
sequence lengths, making forward passes (and as a consequence training)
much faster.
Training time 1000 steps on de_core_news_lg:
- Before this change: 149s
- After this change: 68s
- Pre-refactor parser: 81s
* Fix a rename that was missed in #10878.
So that rehearsal tests pass.
* Apply suggestions from @shadeMe
* Use chained conditional
* Test with update_with_oracle_cut_size={0, 1, 5, 100}
And fix a git that occurs with a cut size of 1.
* Fix up some merge fall out
* Update parser distillation for the refactor
In the old parser, we'd iterate over the transitions in the distill
function and compute the loss/gradients on the go. In the refactored
parser, we first let the student model parse the inputs. Then we'll let
the teacher compute the transition probabilities of the states in the
student's transition sequence. We can then compute the gradients of the
student given the teacher.
* Add back spacy.TransitionBasedParser.v1 references
- Accordion in the architecture docs.
- Test in test_parse, but disabled until we have a spacy-legacy release.
Co-authored-by: Matthew Honnibal <honnibal+gh@gmail.com>
Co-authored-by: svlandeg <svlandeg@github.com>
Co-authored-by: Sofie Van Landeghem <svlandeg@users.noreply.github.com>
Co-authored-by: Madeesh Kannan <shadeMe@users.noreply.github.com>
Co-authored-by: Adriane Boyd <adrianeboyd@gmail.com>
Co-authored-by: kadarakos <kadar.akos@gmail.com>
2023-01-18 13:27:45 +03:00
|
|
|
@architectures = "spacy.TransitionBasedParser.v3"
|
2020-09-23 17:53:49 +03:00
|
|
|
state_type = "parser"
|
2020-09-23 14:35:09 +03:00
|
|
|
extra_state_tokens = false
|
2020-02-27 20:42:27 +03:00
|
|
|
hidden_width = 66
|
|
|
|
maxout_pieces = 2
|
|
|
|
|
|
|
|
[model.tok2vec]
|
|
|
|
@architectures = "spacy.HashEmbedCNN.v1"
|
|
|
|
pretrained_vectors = null
|
|
|
|
width = 333
|
|
|
|
depth = 4
|
|
|
|
embed_size = 5555
|
|
|
|
window_size = 1
|
|
|
|
maxout_pieces = 7
|
|
|
|
subword_features = false
|
|
|
|
"""
|
|
|
|
|
|
|
|
|
2021-03-02 19:56:28 +03:00
|
|
|
@registry.architectures("my_test_parser")
|
2020-02-27 20:42:27 +03:00
|
|
|
def my_parser():
|
2020-02-28 13:57:41 +03:00
|
|
|
tok2vec = build_Tok2Vec_model(
|
2020-07-28 23:43:19 +03:00
|
|
|
MultiHashEmbed(
|
|
|
|
width=321,
|
2020-10-05 22:13:53 +03:00
|
|
|
attrs=["LOWER", "SHAPE"],
|
|
|
|
rows=[5432, 5432],
|
|
|
|
include_static_vectors=False,
|
2020-07-28 23:43:19 +03:00
|
|
|
),
|
2020-08-05 17:00:59 +03:00
|
|
|
MaxoutWindowEncoder(width=321, window_size=3, maxout_pieces=4, depth=2),
|
2020-02-28 13:57:41 +03:00
|
|
|
)
|
|
|
|
parser = build_tb_parser_model(
|
2020-09-23 14:35:09 +03:00
|
|
|
tok2vec=tok2vec,
|
2020-09-23 17:53:49 +03:00
|
|
|
state_type="parser",
|
2020-09-23 14:35:09 +03:00
|
|
|
extra_state_tokens=True,
|
|
|
|
hidden_width=65,
|
|
|
|
maxout_pieces=5,
|
2020-02-28 13:57:41 +03:00
|
|
|
)
|
2020-02-27 20:42:27 +03:00
|
|
|
return parser
|
|
|
|
|
|
|
|
|
2021-12-04 22:34:48 +03:00
|
|
|
@pytest.mark.issue(8190)
|
|
|
|
def test_issue8190():
|
|
|
|
"""Test that config overrides are not lost after load is complete."""
|
|
|
|
source_cfg = {
|
|
|
|
"nlp": {
|
|
|
|
"lang": "en",
|
|
|
|
},
|
|
|
|
"custom": {"key": "value"},
|
|
|
|
}
|
|
|
|
source_nlp = English.from_config(source_cfg)
|
|
|
|
with make_tempdir() as dir_path:
|
|
|
|
# We need to create a loadable source pipeline
|
|
|
|
source_path = dir_path / "test_model"
|
|
|
|
source_nlp.to_disk(source_path)
|
|
|
|
nlp = spacy.load(source_path, config={"custom": {"key": "updated_value"}})
|
|
|
|
|
|
|
|
assert nlp.config["custom"]["key"] == "updated_value"
|
|
|
|
|
|
|
|
|
2020-07-22 14:42:59 +03:00
|
|
|
def test_create_nlp_from_config():
|
|
|
|
config = Config().from_str(nlp_config_string)
|
|
|
|
with pytest.raises(ConfigValidationError):
|
2020-09-27 23:21:31 +03:00
|
|
|
load_model_from_config(config, auto_fill=False)
|
|
|
|
nlp = load_model_from_config(config, auto_fill=True)
|
2020-08-04 16:09:37 +03:00
|
|
|
assert nlp.config["training"]["batcher"]["size"] == 666
|
2020-07-22 14:42:59 +03:00
|
|
|
assert len(nlp.config["training"]) > 1
|
|
|
|
assert nlp.pipe_names == ["tok2vec", "tagger"]
|
|
|
|
assert len(nlp.config["components"]) == 2
|
|
|
|
assert len(nlp.config["nlp"]["pipeline"]) == 2
|
|
|
|
nlp.remove_pipe("tagger")
|
|
|
|
assert len(nlp.config["components"]) == 1
|
|
|
|
assert len(nlp.config["nlp"]["pipeline"]) == 1
|
|
|
|
with pytest.raises(ValueError):
|
|
|
|
bad_cfg = {"yolo": {}}
|
|
|
|
load_model_from_config(Config(bad_cfg), auto_fill=True)
|
|
|
|
with pytest.raises(ValueError):
|
|
|
|
bad_cfg = {"pipeline": {"foo": "bar"}}
|
|
|
|
load_model_from_config(Config(bad_cfg), auto_fill=True)
|
|
|
|
|
|
|
|
|
2020-12-08 09:41:03 +03:00
|
|
|
def test_create_nlp_from_pretraining_config():
|
|
|
|
"""Test that the default pretraining config validates properly"""
|
|
|
|
config = Config().from_str(pretrain_config_string)
|
|
|
|
pretrain_config = load_config(DEFAULT_CONFIG_PRETRAIN_PATH)
|
|
|
|
filled = config.merge(pretrain_config)
|
2021-01-05 05:41:53 +03:00
|
|
|
registry.resolve(filled["pretraining"], schema=ConfigSchemaPretrain)
|
2020-12-08 09:41:03 +03:00
|
|
|
|
|
|
|
|
2020-07-22 14:42:59 +03:00
|
|
|
def test_create_nlp_from_config_multiple_instances():
|
|
|
|
"""Test that the nlp object is created correctly for a config with multiple
|
|
|
|
instances of the same component."""
|
|
|
|
config = Config().from_str(nlp_config_string)
|
|
|
|
config["components"] = {
|
|
|
|
"t2v": config["components"]["tok2vec"],
|
|
|
|
"tagger1": config["components"]["tagger"],
|
|
|
|
"tagger2": config["components"]["tagger"],
|
|
|
|
}
|
|
|
|
config["nlp"]["pipeline"] = list(config["components"].keys())
|
2020-09-27 23:21:31 +03:00
|
|
|
nlp = load_model_from_config(config, auto_fill=True)
|
2020-07-22 14:42:59 +03:00
|
|
|
assert nlp.pipe_names == ["t2v", "tagger1", "tagger2"]
|
|
|
|
assert nlp.get_pipe_meta("t2v").factory == "tok2vec"
|
|
|
|
assert nlp.get_pipe_meta("tagger1").factory == "tagger"
|
|
|
|
assert nlp.get_pipe_meta("tagger2").factory == "tagger"
|
|
|
|
pipeline_config = nlp.config["components"]
|
|
|
|
assert len(pipeline_config) == 3
|
|
|
|
assert list(pipeline_config.keys()) == ["t2v", "tagger1", "tagger2"]
|
|
|
|
assert nlp.config["nlp"]["pipeline"] == ["t2v", "tagger1", "tagger2"]
|
|
|
|
|
|
|
|
|
2020-02-27 20:42:27 +03:00
|
|
|
def test_serialize_nlp():
|
2021-07-02 10:48:26 +03:00
|
|
|
"""Create a custom nlp pipeline from config and ensure it serializes it correctly"""
|
2020-02-27 20:42:27 +03:00
|
|
|
nlp_config = Config().from_str(nlp_config_string)
|
2020-09-27 23:21:31 +03:00
|
|
|
nlp = load_model_from_config(nlp_config, auto_fill=True)
|
2020-08-31 22:24:33 +03:00
|
|
|
nlp.get_pipe("tagger").add_label("A")
|
2020-09-28 22:35:09 +03:00
|
|
|
nlp.initialize()
|
2020-02-27 20:42:27 +03:00
|
|
|
assert "tok2vec" in nlp.pipe_names
|
|
|
|
assert "tagger" in nlp.pipe_names
|
|
|
|
assert "parser" not in nlp.pipe_names
|
|
|
|
assert nlp.get_pipe("tagger").model.get_ref("tok2vec").get_dim("nO") == 342
|
|
|
|
|
|
|
|
with make_tempdir() as d:
|
|
|
|
nlp.to_disk(d)
|
|
|
|
nlp2 = spacy.load(d)
|
|
|
|
assert "tok2vec" in nlp2.pipe_names
|
|
|
|
assert "tagger" in nlp2.pipe_names
|
|
|
|
assert "parser" not in nlp2.pipe_names
|
|
|
|
assert nlp2.get_pipe("tagger").model.get_ref("tok2vec").get_dim("nO") == 342
|
|
|
|
|
|
|
|
|
|
|
|
def test_serialize_custom_nlp():
|
2021-07-02 10:48:26 +03:00
|
|
|
"""Create a custom nlp pipeline and ensure it serializes it correctly"""
|
2020-02-27 20:42:27 +03:00
|
|
|
nlp = English()
|
|
|
|
parser_cfg = dict()
|
2020-02-28 13:57:41 +03:00
|
|
|
parser_cfg["model"] = {"@architectures": "my_test_parser"}
|
2020-07-22 14:42:59 +03:00
|
|
|
nlp.add_pipe("parser", config=parser_cfg)
|
2020-09-28 22:35:09 +03:00
|
|
|
nlp.initialize()
|
2020-02-27 20:42:27 +03:00
|
|
|
|
|
|
|
with make_tempdir() as d:
|
|
|
|
nlp.to_disk(d)
|
|
|
|
nlp2 = spacy.load(d)
|
|
|
|
model = nlp2.get_pipe("parser").model
|
Merge the parser refactor into `v4` (#10940)
* Try to fix doc.copy
* Set dev version
* Make vocab always own lexemes
* Change version
* Add SpanGroups.copy method
* Fix set_annotations during Parser.update
* Fix dict proxy copy
* Upd version
* Fix copying SpanGroups
* Fix set_annotations in parser.update
* Fix parser set_annotations during update
* Revert "Fix parser set_annotations during update"
This reverts commit eb138c89edb306608826dca50619ea8a60de2b14.
* Revert "Fix set_annotations in parser.update"
This reverts commit c6df0eafd0046179c1c9fb7840074edf04e4721d.
* Fix set_annotations during parser update
* Inc version
* Handle final states in get_oracle_sequence
* Inc version
* Try to fix parser training
* Inc version
* Fix
* Inc version
* Fix parser oracle
* Inc version
* Inc version
* Fix transition has_gold
* Inc version
* Try to use real histories, not oracle
* Inc version
* Upd parser
* Inc version
* WIP on rewrite parser
* WIP refactor parser
* New progress on parser model refactor
* Prepare to remove parser_model.pyx
* Convert parser from cdef class
* Delete spacy.ml.parser_model
* Delete _precomputable_affine module
* Wire up tb_framework to new parser model
* Wire up parser model
* Uncython ner.pyx and dep_parser.pyx
* Uncython
* Work on parser model
* Support unseen_classes in parser model
* Support unseen classes in parser
* Cleaner handling of unseen classes
* Work through tests
* Keep working through errors
* Keep working through errors
* Work on parser. 15 tests failing
* Xfail beam stuff. 9 failures
* More xfail. 7 failures
* Xfail. 6 failures
* cleanup
* formatting
* fixes
* pass nO through
* Fix empty doc in update
* Hackishly fix resizing. 3 failures
* Fix redundant test. 2 failures
* Add reference version
* black formatting
* Get tests passing with reference implementation
* Fix missing prints
* Add missing file
* Improve indexing on reference implementation
* Get non-reference forward func working
* Start rigging beam back up
* removing redundant tests, cf #8106
* black formatting
* temporarily xfailing issue 4314
* make flake8 happy again
* mypy fixes
* ensure labels are added upon predict
* cleanup remnants from merge conflicts
* Improve unseen label masking
Two changes to speed up masking by ~10%:
- Use a bool array rather than an array of float32.
- Let the mask indicate whether a label was seen, rather than
unseen. The mask is most frequently used to index scores for
seen labels. However, since the mask marked unseen labels,
this required computing an intermittent flipped mask.
* Write moves costs directly into numpy array (#10163)
This avoids elementwise indexing and the allocation of an additional
array.
Gives a ~15% speed improvement when using batch_by_sequence with size
32.
* Temporarily disable ner and rehearse tests
Until rehearse is implemented again in the refactored parser.
* Fix loss serialization issue (#10600)
* Fix loss serialization issue
Serialization of a model fails with:
TypeError: array(738.3855, dtype=float32) is not JSON serializable
Fix this using float conversion.
* Disable CI steps that require spacy.TransitionBasedParser.v2
After finishing the refactor, TransitionBasedParser.v2 should be
provided for backwards compat.
* Add back support for beam parsing to the refactored parser (#10633)
* Add back support for beam parsing
Beam parsing was already implemented as part of the `BeamBatch` class.
This change makes its counterpart `GreedyBatch`. Both classes are hooked
up in `TransitionModel`, selecting `GreedyBatch` when the beam size is
one, or `BeamBatch` otherwise.
* Use kwarg for beam width
Co-authored-by: Sofie Van Landeghem <svlandeg@users.noreply.github.com>
* Avoid implicit default for beam_width and beam_density
* Parser.{beam,greedy}_parse: ensure labels are added
* Remove 'deprecated' comments
Co-authored-by: Sofie Van Landeghem <svlandeg@users.noreply.github.com>
Co-authored-by: Sofie Van Landeghem <svlandeg@users.noreply.github.com>
* Parser `StateC` optimizations (#10746)
* `StateC`: Optimizations
Avoid GIL acquisition in `__init__`
Increase default buffer capacities on init
Reduce C++ exception overhead
* Fix typo
* Replace `set::count` with `set::find`
* Add exception attribute to c'tor
* Remove unused import
* Use a power-of-two value for initial capacity
Use default-insert to init `_heads` and `_unshiftable`
* Merge `cdef` variable declarations and assignments
* Vectorize `example.get_aligned_parses` (#10789)
* `example`: Vectorize `get_aligned_parse`
Rename `numpy` import
* Convert aligned array to lists before returning
* Revert import renaming
* Elide slice arguments when selecting the entire range
* Tagger/morphologizer alignment performance optimizations (#10798)
* `example`: Unwrap `numpy` scalar arrays before passing them to `StringStore.__getitem__`
* `AlignmentArray`: Use native list as staging buffer for offset calculation
* `example`: Vectorize `get_aligned`
* Hoist inner functions out of `get_aligned`
* Replace inline `if..else` clause in assignment statement
* `AlignmentArray`: Use raw indexing into offset and data `numpy` arrays
* `example`: Replace array unique value check with `groupby`
* `example`: Correctly exclude tokens with no alignment in `_get_aligned_vectorized`
Simplify `_get_aligned_non_vectorized`
* `util`: Update `all_equal` docstring
* Explicitly use `int32_t*`
* Restore C CPU inference in the refactored parser (#10747)
* Bring back the C parsing model
The C parsing model is used for CPU inference and is still faster for
CPU inference than the forward pass of the Thinc model.
* Use C sgemm provided by the Ops implementation
* Make tb_framework module Cython, merge in C forward implementation
* TransitionModel: raise in backprop returned from forward_cpu
* Re-enable greedy parse test
* Return transition scores when forward_cpu is used
* Apply suggestions from code review
Import `Model` from `thinc.api`
Co-authored-by: Sofie Van Landeghem <svlandeg@users.noreply.github.com>
* Use relative imports in tb_framework
* Don't assume a default for beam_width
* We don't have a direct dependency on BLIS anymore
* Rename forwards to _forward_{fallback,greedy_cpu}
* Require thinc >=8.1.0,<8.2.0
* tb_framework: clean up imports
* Fix return type of _get_seen_mask
* Move up _forward_greedy_cpu
* Style fixes.
* Lower thinc lowerbound to 8.1.0.dev0
* Formatting fix
Co-authored-by: Adriane Boyd <adrianeboyd@gmail.com>
Co-authored-by: Sofie Van Landeghem <svlandeg@users.noreply.github.com>
Co-authored-by: Adriane Boyd <adrianeboyd@gmail.com>
* Reimplement parser rehearsal function (#10878)
* Reimplement parser rehearsal function
Before the parser refactor, rehearsal was driven by a loop in the
`rehearse` method itself. For each parsing step, the loops would:
1. Get the predictions of the teacher.
2. Get the predictions and backprop function of the student.
3. Compute the loss and backprop into the student.
4. Move the teacher and student forward with the predictions of
the student.
In the refactored parser, we cannot perform search stepwise rehearsal
anymore, since the model now predicts all parsing steps at once.
Therefore, rehearsal is performed in the following steps:
1. Get the predictions of all parsing steps from the student, along
with its backprop function.
2. Get the predictions from the teacher, but use the predictions of
the student to advance the parser while doing so.
3. Compute the loss and backprop into the student.
To support the second step a new method, `advance_with_actions` is
added to `GreedyBatch`, which performs the provided parsing steps.
* tb_framework: wrap upper_W and upper_b in Linear
Thinc's Optimizer cannot handle resizing of existing parameters. Until
it does, we work around this by wrapping the weights/biases of the upper
layer of the parser model in Linear. When the upper layer is resized, we
copy over the existing parameters into a new Linear instance. This does
not trigger an error in Optimizer, because it sees the resized layer as
a new set of parameters.
* Add test for TransitionSystem.apply_actions
* Better FIXME marker
Co-authored-by: Madeesh Kannan <shadeMe@users.noreply.github.com>
* Fixes from Madeesh
* Apply suggestions from Sofie
Co-authored-by: Sofie Van Landeghem <svlandeg@users.noreply.github.com>
* Remove useless assignment
Co-authored-by: Madeesh Kannan <shadeMe@users.noreply.github.com>
Co-authored-by: Sofie Van Landeghem <svlandeg@users.noreply.github.com>
* Rename some identifiers in the parser refactor (#10935)
* Rename _parseC to _parse_batch
* tb_framework: prefix many auxiliary functions with underscore
To clearly state the intent that they are private.
* Rename `lower` to `hidden`, `upper` to `output`
* Parser slow test fixup
We don't have TransitionBasedParser.{v1,v2} until we bring it back as a
legacy option.
* Remove last vestiges of PrecomputableAffine
This does not exist anymore as a separate layer.
* ner: re-enable sentence boundary checks
* Re-enable test that works now.
* test_ner: make loss test more strict again
* Remove commented line
* Re-enable some more beam parser tests
* Remove unused _forward_reference function
* Update for CBlas changes in Thinc 8.1.0.dev2
Bump thinc dependency to 8.1.0.dev3.
* Remove references to spacy.TransitionBasedParser.{v1,v2}
Since they will not be offered starting with spaCy v4.
* `tb_framework`: Replace references to `thinc.backends.linalg` with `CBlas`
* dont use get_array_module (#11056) (#11293)
Co-authored-by: kadarakos <kadar.akos@gmail.com>
* Move `thinc.extra.search` to `spacy.pipeline._parser_internals` (#11317)
* `search`: Move from `thinc.extra.search`
Fix NPE in `Beam.__dealloc__`
* `pytest`: Add support for executing Cython tests
Move `search` tests from thinc and patch them to run with `pytest`
* `mypy` fix
* Update comment
* `conftest`: Expose `register_cython_tests`
* Remove unused import
* Move `argmax` impls to new `_parser_utils` Cython module (#11410)
* Parser does not have to be a cdef class anymore
This also fixes validation of the initialization schema.
* Add back spacy.TransitionBasedParser.v2
* Fix a rename that was missed in #10878.
So that rehearsal tests pass.
* Remove module from setup.py that got added during the merge
* Bring back support for `update_with_oracle_cut_size` (#12086)
* Bring back support for `update_with_oracle_cut_size`
This option was available in the pre-refactor parser, but was never
implemented in the refactored parser. This option cuts transition
sequences that are longer than `update_with_oracle_cut` size into
separate sequences that have at most `update_with_oracle_cut`
transitions. The oracle (gold standard) transition sequence is used to
determine the cuts and the initial states for the additional sequences.
Applying this cut makes the batches more homogeneous in the transition
sequence lengths, making forward passes (and as a consequence training)
much faster.
Training time 1000 steps on de_core_news_lg:
- Before this change: 149s
- After this change: 68s
- Pre-refactor parser: 81s
* Fix a rename that was missed in #10878.
So that rehearsal tests pass.
* Apply suggestions from @shadeMe
* Use chained conditional
* Test with update_with_oracle_cut_size={0, 1, 5, 100}
And fix a git that occurs with a cut size of 1.
* Fix up some merge fall out
* Update parser distillation for the refactor
In the old parser, we'd iterate over the transitions in the distill
function and compute the loss/gradients on the go. In the refactored
parser, we first let the student model parse the inputs. Then we'll let
the teacher compute the transition probabilities of the states in the
student's transition sequence. We can then compute the gradients of the
student given the teacher.
* Add back spacy.TransitionBasedParser.v1 references
- Accordion in the architecture docs.
- Test in test_parse, but disabled until we have a spacy-legacy release.
Co-authored-by: Matthew Honnibal <honnibal+gh@gmail.com>
Co-authored-by: svlandeg <svlandeg@github.com>
Co-authored-by: Sofie Van Landeghem <svlandeg@users.noreply.github.com>
Co-authored-by: Madeesh Kannan <shadeMe@users.noreply.github.com>
Co-authored-by: Adriane Boyd <adrianeboyd@gmail.com>
Co-authored-by: kadarakos <kadar.akos@gmail.com>
2023-01-18 13:27:45 +03:00
|
|
|
assert model.get_ref("tok2vec") is not None
|
|
|
|
assert model.has_param("hidden_W")
|
|
|
|
assert model.has_param("hidden_b")
|
|
|
|
output = model.get_ref("output")
|
|
|
|
assert output is not None
|
|
|
|
assert output.has_param("W")
|
|
|
|
assert output.has_param("b")
|
2020-02-27 20:42:27 +03:00
|
|
|
|
|
|
|
|
Merge the parser refactor into `v4` (#10940)
* Try to fix doc.copy
* Set dev version
* Make vocab always own lexemes
* Change version
* Add SpanGroups.copy method
* Fix set_annotations during Parser.update
* Fix dict proxy copy
* Upd version
* Fix copying SpanGroups
* Fix set_annotations in parser.update
* Fix parser set_annotations during update
* Revert "Fix parser set_annotations during update"
This reverts commit eb138c89edb306608826dca50619ea8a60de2b14.
* Revert "Fix set_annotations in parser.update"
This reverts commit c6df0eafd0046179c1c9fb7840074edf04e4721d.
* Fix set_annotations during parser update
* Inc version
* Handle final states in get_oracle_sequence
* Inc version
* Try to fix parser training
* Inc version
* Fix
* Inc version
* Fix parser oracle
* Inc version
* Inc version
* Fix transition has_gold
* Inc version
* Try to use real histories, not oracle
* Inc version
* Upd parser
* Inc version
* WIP on rewrite parser
* WIP refactor parser
* New progress on parser model refactor
* Prepare to remove parser_model.pyx
* Convert parser from cdef class
* Delete spacy.ml.parser_model
* Delete _precomputable_affine module
* Wire up tb_framework to new parser model
* Wire up parser model
* Uncython ner.pyx and dep_parser.pyx
* Uncython
* Work on parser model
* Support unseen_classes in parser model
* Support unseen classes in parser
* Cleaner handling of unseen classes
* Work through tests
* Keep working through errors
* Keep working through errors
* Work on parser. 15 tests failing
* Xfail beam stuff. 9 failures
* More xfail. 7 failures
* Xfail. 6 failures
* cleanup
* formatting
* fixes
* pass nO through
* Fix empty doc in update
* Hackishly fix resizing. 3 failures
* Fix redundant test. 2 failures
* Add reference version
* black formatting
* Get tests passing with reference implementation
* Fix missing prints
* Add missing file
* Improve indexing on reference implementation
* Get non-reference forward func working
* Start rigging beam back up
* removing redundant tests, cf #8106
* black formatting
* temporarily xfailing issue 4314
* make flake8 happy again
* mypy fixes
* ensure labels are added upon predict
* cleanup remnants from merge conflicts
* Improve unseen label masking
Two changes to speed up masking by ~10%:
- Use a bool array rather than an array of float32.
- Let the mask indicate whether a label was seen, rather than
unseen. The mask is most frequently used to index scores for
seen labels. However, since the mask marked unseen labels,
this required computing an intermittent flipped mask.
* Write moves costs directly into numpy array (#10163)
This avoids elementwise indexing and the allocation of an additional
array.
Gives a ~15% speed improvement when using batch_by_sequence with size
32.
* Temporarily disable ner and rehearse tests
Until rehearse is implemented again in the refactored parser.
* Fix loss serialization issue (#10600)
* Fix loss serialization issue
Serialization of a model fails with:
TypeError: array(738.3855, dtype=float32) is not JSON serializable
Fix this using float conversion.
* Disable CI steps that require spacy.TransitionBasedParser.v2
After finishing the refactor, TransitionBasedParser.v2 should be
provided for backwards compat.
* Add back support for beam parsing to the refactored parser (#10633)
* Add back support for beam parsing
Beam parsing was already implemented as part of the `BeamBatch` class.
This change makes its counterpart `GreedyBatch`. Both classes are hooked
up in `TransitionModel`, selecting `GreedyBatch` when the beam size is
one, or `BeamBatch` otherwise.
* Use kwarg for beam width
Co-authored-by: Sofie Van Landeghem <svlandeg@users.noreply.github.com>
* Avoid implicit default for beam_width and beam_density
* Parser.{beam,greedy}_parse: ensure labels are added
* Remove 'deprecated' comments
Co-authored-by: Sofie Van Landeghem <svlandeg@users.noreply.github.com>
Co-authored-by: Sofie Van Landeghem <svlandeg@users.noreply.github.com>
* Parser `StateC` optimizations (#10746)
* `StateC`: Optimizations
Avoid GIL acquisition in `__init__`
Increase default buffer capacities on init
Reduce C++ exception overhead
* Fix typo
* Replace `set::count` with `set::find`
* Add exception attribute to c'tor
* Remove unused import
* Use a power-of-two value for initial capacity
Use default-insert to init `_heads` and `_unshiftable`
* Merge `cdef` variable declarations and assignments
* Vectorize `example.get_aligned_parses` (#10789)
* `example`: Vectorize `get_aligned_parse`
Rename `numpy` import
* Convert aligned array to lists before returning
* Revert import renaming
* Elide slice arguments when selecting the entire range
* Tagger/morphologizer alignment performance optimizations (#10798)
* `example`: Unwrap `numpy` scalar arrays before passing them to `StringStore.__getitem__`
* `AlignmentArray`: Use native list as staging buffer for offset calculation
* `example`: Vectorize `get_aligned`
* Hoist inner functions out of `get_aligned`
* Replace inline `if..else` clause in assignment statement
* `AlignmentArray`: Use raw indexing into offset and data `numpy` arrays
* `example`: Replace array unique value check with `groupby`
* `example`: Correctly exclude tokens with no alignment in `_get_aligned_vectorized`
Simplify `_get_aligned_non_vectorized`
* `util`: Update `all_equal` docstring
* Explicitly use `int32_t*`
* Restore C CPU inference in the refactored parser (#10747)
* Bring back the C parsing model
The C parsing model is used for CPU inference and is still faster for
CPU inference than the forward pass of the Thinc model.
* Use C sgemm provided by the Ops implementation
* Make tb_framework module Cython, merge in C forward implementation
* TransitionModel: raise in backprop returned from forward_cpu
* Re-enable greedy parse test
* Return transition scores when forward_cpu is used
* Apply suggestions from code review
Import `Model` from `thinc.api`
Co-authored-by: Sofie Van Landeghem <svlandeg@users.noreply.github.com>
* Use relative imports in tb_framework
* Don't assume a default for beam_width
* We don't have a direct dependency on BLIS anymore
* Rename forwards to _forward_{fallback,greedy_cpu}
* Require thinc >=8.1.0,<8.2.0
* tb_framework: clean up imports
* Fix return type of _get_seen_mask
* Move up _forward_greedy_cpu
* Style fixes.
* Lower thinc lowerbound to 8.1.0.dev0
* Formatting fix
Co-authored-by: Adriane Boyd <adrianeboyd@gmail.com>
Co-authored-by: Sofie Van Landeghem <svlandeg@users.noreply.github.com>
Co-authored-by: Adriane Boyd <adrianeboyd@gmail.com>
* Reimplement parser rehearsal function (#10878)
* Reimplement parser rehearsal function
Before the parser refactor, rehearsal was driven by a loop in the
`rehearse` method itself. For each parsing step, the loops would:
1. Get the predictions of the teacher.
2. Get the predictions and backprop function of the student.
3. Compute the loss and backprop into the student.
4. Move the teacher and student forward with the predictions of
the student.
In the refactored parser, we cannot perform search stepwise rehearsal
anymore, since the model now predicts all parsing steps at once.
Therefore, rehearsal is performed in the following steps:
1. Get the predictions of all parsing steps from the student, along
with its backprop function.
2. Get the predictions from the teacher, but use the predictions of
the student to advance the parser while doing so.
3. Compute the loss and backprop into the student.
To support the second step a new method, `advance_with_actions` is
added to `GreedyBatch`, which performs the provided parsing steps.
* tb_framework: wrap upper_W and upper_b in Linear
Thinc's Optimizer cannot handle resizing of existing parameters. Until
it does, we work around this by wrapping the weights/biases of the upper
layer of the parser model in Linear. When the upper layer is resized, we
copy over the existing parameters into a new Linear instance. This does
not trigger an error in Optimizer, because it sees the resized layer as
a new set of parameters.
* Add test for TransitionSystem.apply_actions
* Better FIXME marker
Co-authored-by: Madeesh Kannan <shadeMe@users.noreply.github.com>
* Fixes from Madeesh
* Apply suggestions from Sofie
Co-authored-by: Sofie Van Landeghem <svlandeg@users.noreply.github.com>
* Remove useless assignment
Co-authored-by: Madeesh Kannan <shadeMe@users.noreply.github.com>
Co-authored-by: Sofie Van Landeghem <svlandeg@users.noreply.github.com>
* Rename some identifiers in the parser refactor (#10935)
* Rename _parseC to _parse_batch
* tb_framework: prefix many auxiliary functions with underscore
To clearly state the intent that they are private.
* Rename `lower` to `hidden`, `upper` to `output`
* Parser slow test fixup
We don't have TransitionBasedParser.{v1,v2} until we bring it back as a
legacy option.
* Remove last vestiges of PrecomputableAffine
This does not exist anymore as a separate layer.
* ner: re-enable sentence boundary checks
* Re-enable test that works now.
* test_ner: make loss test more strict again
* Remove commented line
* Re-enable some more beam parser tests
* Remove unused _forward_reference function
* Update for CBlas changes in Thinc 8.1.0.dev2
Bump thinc dependency to 8.1.0.dev3.
* Remove references to spacy.TransitionBasedParser.{v1,v2}
Since they will not be offered starting with spaCy v4.
* `tb_framework`: Replace references to `thinc.backends.linalg` with `CBlas`
* dont use get_array_module (#11056) (#11293)
Co-authored-by: kadarakos <kadar.akos@gmail.com>
* Move `thinc.extra.search` to `spacy.pipeline._parser_internals` (#11317)
* `search`: Move from `thinc.extra.search`
Fix NPE in `Beam.__dealloc__`
* `pytest`: Add support for executing Cython tests
Move `search` tests from thinc and patch them to run with `pytest`
* `mypy` fix
* Update comment
* `conftest`: Expose `register_cython_tests`
* Remove unused import
* Move `argmax` impls to new `_parser_utils` Cython module (#11410)
* Parser does not have to be a cdef class anymore
This also fixes validation of the initialization schema.
* Add back spacy.TransitionBasedParser.v2
* Fix a rename that was missed in #10878.
So that rehearsal tests pass.
* Remove module from setup.py that got added during the merge
* Bring back support for `update_with_oracle_cut_size` (#12086)
* Bring back support for `update_with_oracle_cut_size`
This option was available in the pre-refactor parser, but was never
implemented in the refactored parser. This option cuts transition
sequences that are longer than `update_with_oracle_cut` size into
separate sequences that have at most `update_with_oracle_cut`
transitions. The oracle (gold standard) transition sequence is used to
determine the cuts and the initial states for the additional sequences.
Applying this cut makes the batches more homogeneous in the transition
sequence lengths, making forward passes (and as a consequence training)
much faster.
Training time 1000 steps on de_core_news_lg:
- Before this change: 149s
- After this change: 68s
- Pre-refactor parser: 81s
* Fix a rename that was missed in #10878.
So that rehearsal tests pass.
* Apply suggestions from @shadeMe
* Use chained conditional
* Test with update_with_oracle_cut_size={0, 1, 5, 100}
And fix a git that occurs with a cut size of 1.
* Fix up some merge fall out
* Update parser distillation for the refactor
In the old parser, we'd iterate over the transitions in the distill
function and compute the loss/gradients on the go. In the refactored
parser, we first let the student model parse the inputs. Then we'll let
the teacher compute the transition probabilities of the states in the
student's transition sequence. We can then compute the gradients of the
student given the teacher.
* Add back spacy.TransitionBasedParser.v1 references
- Accordion in the architecture docs.
- Test in test_parse, but disabled until we have a spacy-legacy release.
Co-authored-by: Matthew Honnibal <honnibal+gh@gmail.com>
Co-authored-by: svlandeg <svlandeg@github.com>
Co-authored-by: Sofie Van Landeghem <svlandeg@users.noreply.github.com>
Co-authored-by: Madeesh Kannan <shadeMe@users.noreply.github.com>
Co-authored-by: Adriane Boyd <adrianeboyd@gmail.com>
Co-authored-by: kadarakos <kadar.akos@gmail.com>
2023-01-18 13:27:45 +03:00
|
|
|
@pytest.mark.parametrize("parser_config_string", [parser_config_string_upper])
|
2020-12-18 13:56:57 +03:00
|
|
|
def test_serialize_parser(parser_config_string):
|
2021-07-02 10:48:26 +03:00
|
|
|
"""Create a non-default parser config to check nlp serializes it correctly"""
|
2020-02-27 20:42:27 +03:00
|
|
|
nlp = English()
|
|
|
|
model_config = Config().from_str(parser_config_string)
|
2020-07-22 14:42:59 +03:00
|
|
|
parser = nlp.add_pipe("parser", config=model_config)
|
2020-02-27 20:42:27 +03:00
|
|
|
parser.add_label("nsubj")
|
2020-09-28 22:35:09 +03:00
|
|
|
nlp.initialize()
|
2020-02-27 20:42:27 +03:00
|
|
|
|
|
|
|
with make_tempdir() as d:
|
|
|
|
nlp.to_disk(d)
|
|
|
|
nlp2 = spacy.load(d)
|
|
|
|
model = nlp2.get_pipe("parser").model
|
Merge the parser refactor into `v4` (#10940)
* Try to fix doc.copy
* Set dev version
* Make vocab always own lexemes
* Change version
* Add SpanGroups.copy method
* Fix set_annotations during Parser.update
* Fix dict proxy copy
* Upd version
* Fix copying SpanGroups
* Fix set_annotations in parser.update
* Fix parser set_annotations during update
* Revert "Fix parser set_annotations during update"
This reverts commit eb138c89edb306608826dca50619ea8a60de2b14.
* Revert "Fix set_annotations in parser.update"
This reverts commit c6df0eafd0046179c1c9fb7840074edf04e4721d.
* Fix set_annotations during parser update
* Inc version
* Handle final states in get_oracle_sequence
* Inc version
* Try to fix parser training
* Inc version
* Fix
* Inc version
* Fix parser oracle
* Inc version
* Inc version
* Fix transition has_gold
* Inc version
* Try to use real histories, not oracle
* Inc version
* Upd parser
* Inc version
* WIP on rewrite parser
* WIP refactor parser
* New progress on parser model refactor
* Prepare to remove parser_model.pyx
* Convert parser from cdef class
* Delete spacy.ml.parser_model
* Delete _precomputable_affine module
* Wire up tb_framework to new parser model
* Wire up parser model
* Uncython ner.pyx and dep_parser.pyx
* Uncython
* Work on parser model
* Support unseen_classes in parser model
* Support unseen classes in parser
* Cleaner handling of unseen classes
* Work through tests
* Keep working through errors
* Keep working through errors
* Work on parser. 15 tests failing
* Xfail beam stuff. 9 failures
* More xfail. 7 failures
* Xfail. 6 failures
* cleanup
* formatting
* fixes
* pass nO through
* Fix empty doc in update
* Hackishly fix resizing. 3 failures
* Fix redundant test. 2 failures
* Add reference version
* black formatting
* Get tests passing with reference implementation
* Fix missing prints
* Add missing file
* Improve indexing on reference implementation
* Get non-reference forward func working
* Start rigging beam back up
* removing redundant tests, cf #8106
* black formatting
* temporarily xfailing issue 4314
* make flake8 happy again
* mypy fixes
* ensure labels are added upon predict
* cleanup remnants from merge conflicts
* Improve unseen label masking
Two changes to speed up masking by ~10%:
- Use a bool array rather than an array of float32.
- Let the mask indicate whether a label was seen, rather than
unseen. The mask is most frequently used to index scores for
seen labels. However, since the mask marked unseen labels,
this required computing an intermittent flipped mask.
* Write moves costs directly into numpy array (#10163)
This avoids elementwise indexing and the allocation of an additional
array.
Gives a ~15% speed improvement when using batch_by_sequence with size
32.
* Temporarily disable ner and rehearse tests
Until rehearse is implemented again in the refactored parser.
* Fix loss serialization issue (#10600)
* Fix loss serialization issue
Serialization of a model fails with:
TypeError: array(738.3855, dtype=float32) is not JSON serializable
Fix this using float conversion.
* Disable CI steps that require spacy.TransitionBasedParser.v2
After finishing the refactor, TransitionBasedParser.v2 should be
provided for backwards compat.
* Add back support for beam parsing to the refactored parser (#10633)
* Add back support for beam parsing
Beam parsing was already implemented as part of the `BeamBatch` class.
This change makes its counterpart `GreedyBatch`. Both classes are hooked
up in `TransitionModel`, selecting `GreedyBatch` when the beam size is
one, or `BeamBatch` otherwise.
* Use kwarg for beam width
Co-authored-by: Sofie Van Landeghem <svlandeg@users.noreply.github.com>
* Avoid implicit default for beam_width and beam_density
* Parser.{beam,greedy}_parse: ensure labels are added
* Remove 'deprecated' comments
Co-authored-by: Sofie Van Landeghem <svlandeg@users.noreply.github.com>
Co-authored-by: Sofie Van Landeghem <svlandeg@users.noreply.github.com>
* Parser `StateC` optimizations (#10746)
* `StateC`: Optimizations
Avoid GIL acquisition in `__init__`
Increase default buffer capacities on init
Reduce C++ exception overhead
* Fix typo
* Replace `set::count` with `set::find`
* Add exception attribute to c'tor
* Remove unused import
* Use a power-of-two value for initial capacity
Use default-insert to init `_heads` and `_unshiftable`
* Merge `cdef` variable declarations and assignments
* Vectorize `example.get_aligned_parses` (#10789)
* `example`: Vectorize `get_aligned_parse`
Rename `numpy` import
* Convert aligned array to lists before returning
* Revert import renaming
* Elide slice arguments when selecting the entire range
* Tagger/morphologizer alignment performance optimizations (#10798)
* `example`: Unwrap `numpy` scalar arrays before passing them to `StringStore.__getitem__`
* `AlignmentArray`: Use native list as staging buffer for offset calculation
* `example`: Vectorize `get_aligned`
* Hoist inner functions out of `get_aligned`
* Replace inline `if..else` clause in assignment statement
* `AlignmentArray`: Use raw indexing into offset and data `numpy` arrays
* `example`: Replace array unique value check with `groupby`
* `example`: Correctly exclude tokens with no alignment in `_get_aligned_vectorized`
Simplify `_get_aligned_non_vectorized`
* `util`: Update `all_equal` docstring
* Explicitly use `int32_t*`
* Restore C CPU inference in the refactored parser (#10747)
* Bring back the C parsing model
The C parsing model is used for CPU inference and is still faster for
CPU inference than the forward pass of the Thinc model.
* Use C sgemm provided by the Ops implementation
* Make tb_framework module Cython, merge in C forward implementation
* TransitionModel: raise in backprop returned from forward_cpu
* Re-enable greedy parse test
* Return transition scores when forward_cpu is used
* Apply suggestions from code review
Import `Model` from `thinc.api`
Co-authored-by: Sofie Van Landeghem <svlandeg@users.noreply.github.com>
* Use relative imports in tb_framework
* Don't assume a default for beam_width
* We don't have a direct dependency on BLIS anymore
* Rename forwards to _forward_{fallback,greedy_cpu}
* Require thinc >=8.1.0,<8.2.0
* tb_framework: clean up imports
* Fix return type of _get_seen_mask
* Move up _forward_greedy_cpu
* Style fixes.
* Lower thinc lowerbound to 8.1.0.dev0
* Formatting fix
Co-authored-by: Adriane Boyd <adrianeboyd@gmail.com>
Co-authored-by: Sofie Van Landeghem <svlandeg@users.noreply.github.com>
Co-authored-by: Adriane Boyd <adrianeboyd@gmail.com>
* Reimplement parser rehearsal function (#10878)
* Reimplement parser rehearsal function
Before the parser refactor, rehearsal was driven by a loop in the
`rehearse` method itself. For each parsing step, the loops would:
1. Get the predictions of the teacher.
2. Get the predictions and backprop function of the student.
3. Compute the loss and backprop into the student.
4. Move the teacher and student forward with the predictions of
the student.
In the refactored parser, we cannot perform search stepwise rehearsal
anymore, since the model now predicts all parsing steps at once.
Therefore, rehearsal is performed in the following steps:
1. Get the predictions of all parsing steps from the student, along
with its backprop function.
2. Get the predictions from the teacher, but use the predictions of
the student to advance the parser while doing so.
3. Compute the loss and backprop into the student.
To support the second step a new method, `advance_with_actions` is
added to `GreedyBatch`, which performs the provided parsing steps.
* tb_framework: wrap upper_W and upper_b in Linear
Thinc's Optimizer cannot handle resizing of existing parameters. Until
it does, we work around this by wrapping the weights/biases of the upper
layer of the parser model in Linear. When the upper layer is resized, we
copy over the existing parameters into a new Linear instance. This does
not trigger an error in Optimizer, because it sees the resized layer as
a new set of parameters.
* Add test for TransitionSystem.apply_actions
* Better FIXME marker
Co-authored-by: Madeesh Kannan <shadeMe@users.noreply.github.com>
* Fixes from Madeesh
* Apply suggestions from Sofie
Co-authored-by: Sofie Van Landeghem <svlandeg@users.noreply.github.com>
* Remove useless assignment
Co-authored-by: Madeesh Kannan <shadeMe@users.noreply.github.com>
Co-authored-by: Sofie Van Landeghem <svlandeg@users.noreply.github.com>
* Rename some identifiers in the parser refactor (#10935)
* Rename _parseC to _parse_batch
* tb_framework: prefix many auxiliary functions with underscore
To clearly state the intent that they are private.
* Rename `lower` to `hidden`, `upper` to `output`
* Parser slow test fixup
We don't have TransitionBasedParser.{v1,v2} until we bring it back as a
legacy option.
* Remove last vestiges of PrecomputableAffine
This does not exist anymore as a separate layer.
* ner: re-enable sentence boundary checks
* Re-enable test that works now.
* test_ner: make loss test more strict again
* Remove commented line
* Re-enable some more beam parser tests
* Remove unused _forward_reference function
* Update for CBlas changes in Thinc 8.1.0.dev2
Bump thinc dependency to 8.1.0.dev3.
* Remove references to spacy.TransitionBasedParser.{v1,v2}
Since they will not be offered starting with spaCy v4.
* `tb_framework`: Replace references to `thinc.backends.linalg` with `CBlas`
* dont use get_array_module (#11056) (#11293)
Co-authored-by: kadarakos <kadar.akos@gmail.com>
* Move `thinc.extra.search` to `spacy.pipeline._parser_internals` (#11317)
* `search`: Move from `thinc.extra.search`
Fix NPE in `Beam.__dealloc__`
* `pytest`: Add support for executing Cython tests
Move `search` tests from thinc and patch them to run with `pytest`
* `mypy` fix
* Update comment
* `conftest`: Expose `register_cython_tests`
* Remove unused import
* Move `argmax` impls to new `_parser_utils` Cython module (#11410)
* Parser does not have to be a cdef class anymore
This also fixes validation of the initialization schema.
* Add back spacy.TransitionBasedParser.v2
* Fix a rename that was missed in #10878.
So that rehearsal tests pass.
* Remove module from setup.py that got added during the merge
* Bring back support for `update_with_oracle_cut_size` (#12086)
* Bring back support for `update_with_oracle_cut_size`
This option was available in the pre-refactor parser, but was never
implemented in the refactored parser. This option cuts transition
sequences that are longer than `update_with_oracle_cut` size into
separate sequences that have at most `update_with_oracle_cut`
transitions. The oracle (gold standard) transition sequence is used to
determine the cuts and the initial states for the additional sequences.
Applying this cut makes the batches more homogeneous in the transition
sequence lengths, making forward passes (and as a consequence training)
much faster.
Training time 1000 steps on de_core_news_lg:
- Before this change: 149s
- After this change: 68s
- Pre-refactor parser: 81s
* Fix a rename that was missed in #10878.
So that rehearsal tests pass.
* Apply suggestions from @shadeMe
* Use chained conditional
* Test with update_with_oracle_cut_size={0, 1, 5, 100}
And fix a git that occurs with a cut size of 1.
* Fix up some merge fall out
* Update parser distillation for the refactor
In the old parser, we'd iterate over the transitions in the distill
function and compute the loss/gradients on the go. In the refactored
parser, we first let the student model parse the inputs. Then we'll let
the teacher compute the transition probabilities of the states in the
student's transition sequence. We can then compute the gradients of the
student given the teacher.
* Add back spacy.TransitionBasedParser.v1 references
- Accordion in the architecture docs.
- Test in test_parse, but disabled until we have a spacy-legacy release.
Co-authored-by: Matthew Honnibal <honnibal+gh@gmail.com>
Co-authored-by: svlandeg <svlandeg@github.com>
Co-authored-by: Sofie Van Landeghem <svlandeg@users.noreply.github.com>
Co-authored-by: Madeesh Kannan <shadeMe@users.noreply.github.com>
Co-authored-by: Adriane Boyd <adrianeboyd@gmail.com>
Co-authored-by: kadarakos <kadar.akos@gmail.com>
2023-01-18 13:27:45 +03:00
|
|
|
assert model.get_ref("tok2vec") is not None
|
|
|
|
assert model.has_param("hidden_W")
|
|
|
|
assert model.has_param("hidden_b")
|
|
|
|
output = model.get_ref("output")
|
|
|
|
assert output is not None
|
|
|
|
assert output.has_param("b")
|
|
|
|
assert output.has_param("W")
|
2020-12-18 13:56:57 +03:00
|
|
|
|
2020-07-22 14:42:59 +03:00
|
|
|
|
|
|
|
def test_config_nlp_roundtrip():
|
2021-03-09 06:01:13 +03:00
|
|
|
"""Test that a config produced by the nlp object passes training config
|
2020-07-22 14:42:59 +03:00
|
|
|
validation."""
|
|
|
|
nlp = English()
|
|
|
|
nlp.add_pipe("entity_ruler")
|
|
|
|
nlp.add_pipe("ner")
|
2020-09-27 23:21:31 +03:00
|
|
|
new_nlp = load_model_from_config(nlp.config, auto_fill=False)
|
2020-07-22 14:42:59 +03:00
|
|
|
assert new_nlp.config == nlp.config
|
|
|
|
assert new_nlp.pipe_names == nlp.pipe_names
|
|
|
|
assert new_nlp._pipe_configs == nlp._pipe_configs
|
|
|
|
assert new_nlp._pipe_meta == nlp._pipe_meta
|
|
|
|
assert new_nlp._factory_meta == nlp._factory_meta
|
|
|
|
|
|
|
|
|
2020-08-27 17:44:36 +03:00
|
|
|
def test_config_nlp_roundtrip_bytes_disk():
|
|
|
|
"""Test that the config is serialized correctly and not interpolated
|
|
|
|
by mistake."""
|
|
|
|
nlp = English()
|
|
|
|
nlp_bytes = nlp.to_bytes()
|
|
|
|
new_nlp = English().from_bytes(nlp_bytes)
|
|
|
|
assert new_nlp.config == nlp.config
|
|
|
|
nlp = English()
|
|
|
|
with make_tempdir() as d:
|
|
|
|
nlp.to_disk(d)
|
|
|
|
new_nlp = spacy.load(d)
|
|
|
|
assert new_nlp.config == nlp.config
|
|
|
|
|
|
|
|
|
2020-07-22 14:42:59 +03:00
|
|
|
def test_serialize_config_language_specific():
|
|
|
|
"""Test that config serialization works as expected with language-specific
|
|
|
|
factories."""
|
|
|
|
name = "test_serialize_config_language_specific"
|
|
|
|
|
|
|
|
@English.factory(name, default_config={"foo": 20})
|
|
|
|
def custom_factory(nlp: Language, name: str, foo: int):
|
|
|
|
return lambda doc: doc
|
|
|
|
|
|
|
|
nlp = Language()
|
|
|
|
assert not nlp.has_factory(name)
|
|
|
|
nlp = English()
|
|
|
|
assert nlp.has_factory(name)
|
|
|
|
nlp.add_pipe(name, config={"foo": 100}, name="bar")
|
|
|
|
pipe_config = nlp.config["components"]["bar"]
|
|
|
|
assert pipe_config["foo"] == 100
|
2020-07-22 18:29:31 +03:00
|
|
|
assert pipe_config["factory"] == name
|
2020-07-22 14:42:59 +03:00
|
|
|
|
|
|
|
with make_tempdir() as d:
|
|
|
|
nlp.to_disk(d)
|
|
|
|
nlp2 = spacy.load(d)
|
|
|
|
assert nlp2.has_factory(name)
|
|
|
|
assert nlp2.pipe_names == ["bar"]
|
|
|
|
assert nlp2.get_pipe_meta("bar").factory == name
|
|
|
|
pipe_config = nlp2.config["components"]["bar"]
|
|
|
|
assert pipe_config["foo"] == 100
|
2020-07-22 18:29:31 +03:00
|
|
|
assert pipe_config["factory"] == name
|
2020-07-22 14:42:59 +03:00
|
|
|
|
|
|
|
config = Config().from_str(nlp2.config.to_str())
|
|
|
|
config["nlp"]["lang"] = "de"
|
|
|
|
with pytest.raises(ValueError):
|
|
|
|
# German doesn't have a factory, only English does
|
|
|
|
load_model_from_config(config)
|
|
|
|
|
|
|
|
|
|
|
|
def test_serialize_config_missing_pipes():
|
|
|
|
config = Config().from_str(nlp_config_string)
|
|
|
|
config["components"].pop("tok2vec")
|
|
|
|
assert "tok2vec" in config["nlp"]["pipeline"]
|
|
|
|
assert "tok2vec" not in config["components"]
|
|
|
|
with pytest.raises(ValueError):
|
|
|
|
load_model_from_config(config, auto_fill=True)
|
2020-08-06 00:35:09 +03:00
|
|
|
|
|
|
|
|
|
|
|
def test_config_overrides():
|
|
|
|
overrides_nested = {"nlp": {"lang": "de", "pipeline": ["tagger"]}}
|
|
|
|
overrides_dot = {"nlp.lang": "de", "nlp.pipeline": ["tagger"]}
|
|
|
|
# load_model from config with overrides passed directly to Config
|
|
|
|
config = Config().from_str(nlp_config_string, overrides=overrides_dot)
|
2020-09-27 23:21:31 +03:00
|
|
|
nlp = load_model_from_config(config, auto_fill=True)
|
2020-08-06 00:35:09 +03:00
|
|
|
assert isinstance(nlp, German)
|
|
|
|
assert nlp.pipe_names == ["tagger"]
|
|
|
|
# Serialized roundtrip with config passed in
|
|
|
|
base_config = Config().from_str(nlp_config_string)
|
2020-09-27 23:21:31 +03:00
|
|
|
base_nlp = load_model_from_config(base_config, auto_fill=True)
|
2020-08-06 00:35:09 +03:00
|
|
|
assert isinstance(base_nlp, English)
|
|
|
|
assert base_nlp.pipe_names == ["tok2vec", "tagger"]
|
|
|
|
with make_tempdir() as d:
|
|
|
|
base_nlp.to_disk(d)
|
|
|
|
nlp = spacy.load(d, config=overrides_nested)
|
|
|
|
assert isinstance(nlp, German)
|
|
|
|
assert nlp.pipe_names == ["tagger"]
|
|
|
|
with make_tempdir() as d:
|
|
|
|
base_nlp.to_disk(d)
|
|
|
|
nlp = spacy.load(d, config=overrides_dot)
|
|
|
|
assert isinstance(nlp, German)
|
|
|
|
assert nlp.pipe_names == ["tagger"]
|
|
|
|
with make_tempdir() as d:
|
|
|
|
base_nlp.to_disk(d)
|
|
|
|
nlp = spacy.load(d)
|
|
|
|
assert isinstance(nlp, English)
|
|
|
|
assert nlp.pipe_names == ["tok2vec", "tagger"]
|
2020-08-13 18:38:30 +03:00
|
|
|
|
|
|
|
|
|
|
|
def test_config_interpolation():
|
|
|
|
config = Config().from_str(nlp_config_string, interpolate=False)
|
2020-09-17 12:38:59 +03:00
|
|
|
assert config["corpora"]["train"]["path"] == "${paths.train}"
|
2020-08-13 18:38:30 +03:00
|
|
|
interpolated = config.interpolate()
|
2020-09-29 23:33:46 +03:00
|
|
|
assert interpolated["corpora"]["train"]["path"] is None
|
2020-08-13 18:38:30 +03:00
|
|
|
nlp = English.from_config(config)
|
2020-09-17 12:38:59 +03:00
|
|
|
assert nlp.config["corpora"]["train"]["path"] == "${paths.train}"
|
2020-08-13 18:38:30 +03:00
|
|
|
# Ensure that variables are preserved in nlp config
|
2020-08-20 12:20:58 +03:00
|
|
|
width = "${components.tok2vec.model.width}"
|
2020-08-13 18:38:30 +03:00
|
|
|
assert config["components"]["tagger"]["model"]["tok2vec"]["width"] == width
|
|
|
|
assert nlp.config["components"]["tagger"]["model"]["tok2vec"]["width"] == width
|
|
|
|
interpolated2 = nlp.config.interpolate()
|
2020-09-29 23:33:46 +03:00
|
|
|
assert interpolated2["corpora"]["train"]["path"] is None
|
2020-08-13 18:38:30 +03:00
|
|
|
assert interpolated2["components"]["tagger"]["model"]["tok2vec"]["width"] == 342
|
|
|
|
nlp2 = English.from_config(interpolated)
|
2020-09-29 23:33:46 +03:00
|
|
|
assert nlp2.config["corpora"]["train"]["path"] is None
|
2020-08-13 18:38:30 +03:00
|
|
|
assert nlp2.config["components"]["tagger"]["model"]["tok2vec"]["width"] == 342
|
2020-08-24 16:56:03 +03:00
|
|
|
|
|
|
|
|
|
|
|
def test_config_optional_sections():
|
|
|
|
config = Config().from_str(nlp_config_string)
|
|
|
|
config = DEFAULT_CONFIG.merge(config)
|
|
|
|
assert "pretraining" not in config
|
2020-09-27 23:21:31 +03:00
|
|
|
filled = registry.fill(config, schema=ConfigSchema, validate=False)
|
2020-08-24 16:56:03 +03:00
|
|
|
# Make sure that optional "pretraining" block doesn't default to None,
|
|
|
|
# which would (rightly) cause error because it'd result in a top-level
|
|
|
|
# key that's not a section (dict). Note that the following roundtrip is
|
|
|
|
# also how Config.interpolate works under the hood.
|
|
|
|
new_config = Config().from_str(filled.to_str())
|
|
|
|
assert new_config["pretraining"] == {}
|
2020-08-24 23:53:47 +03:00
|
|
|
|
|
|
|
|
|
|
|
def test_config_auto_fill_extra_fields():
|
|
|
|
config = Config({"nlp": {"lang": "en"}, "training": {}})
|
|
|
|
assert load_model_from_config(config, auto_fill=True)
|
|
|
|
config = Config({"nlp": {"lang": "en"}, "training": {"extra": "hello"}})
|
2020-09-27 23:21:31 +03:00
|
|
|
nlp = load_model_from_config(config, auto_fill=True, validate=False)
|
2020-08-24 23:53:47 +03:00
|
|
|
assert "extra" not in nlp.config["training"]
|
|
|
|
# Make sure the config generated is valid
|
|
|
|
load_model_from_config(nlp.config)
|
2020-09-23 18:32:14 +03:00
|
|
|
|
|
|
|
|
Merge the parser refactor into `v4` (#10940)
* Try to fix doc.copy
* Set dev version
* Make vocab always own lexemes
* Change version
* Add SpanGroups.copy method
* Fix set_annotations during Parser.update
* Fix dict proxy copy
* Upd version
* Fix copying SpanGroups
* Fix set_annotations in parser.update
* Fix parser set_annotations during update
* Revert "Fix parser set_annotations during update"
This reverts commit eb138c89edb306608826dca50619ea8a60de2b14.
* Revert "Fix set_annotations in parser.update"
This reverts commit c6df0eafd0046179c1c9fb7840074edf04e4721d.
* Fix set_annotations during parser update
* Inc version
* Handle final states in get_oracle_sequence
* Inc version
* Try to fix parser training
* Inc version
* Fix
* Inc version
* Fix parser oracle
* Inc version
* Inc version
* Fix transition has_gold
* Inc version
* Try to use real histories, not oracle
* Inc version
* Upd parser
* Inc version
* WIP on rewrite parser
* WIP refactor parser
* New progress on parser model refactor
* Prepare to remove parser_model.pyx
* Convert parser from cdef class
* Delete spacy.ml.parser_model
* Delete _precomputable_affine module
* Wire up tb_framework to new parser model
* Wire up parser model
* Uncython ner.pyx and dep_parser.pyx
* Uncython
* Work on parser model
* Support unseen_classes in parser model
* Support unseen classes in parser
* Cleaner handling of unseen classes
* Work through tests
* Keep working through errors
* Keep working through errors
* Work on parser. 15 tests failing
* Xfail beam stuff. 9 failures
* More xfail. 7 failures
* Xfail. 6 failures
* cleanup
* formatting
* fixes
* pass nO through
* Fix empty doc in update
* Hackishly fix resizing. 3 failures
* Fix redundant test. 2 failures
* Add reference version
* black formatting
* Get tests passing with reference implementation
* Fix missing prints
* Add missing file
* Improve indexing on reference implementation
* Get non-reference forward func working
* Start rigging beam back up
* removing redundant tests, cf #8106
* black formatting
* temporarily xfailing issue 4314
* make flake8 happy again
* mypy fixes
* ensure labels are added upon predict
* cleanup remnants from merge conflicts
* Improve unseen label masking
Two changes to speed up masking by ~10%:
- Use a bool array rather than an array of float32.
- Let the mask indicate whether a label was seen, rather than
unseen. The mask is most frequently used to index scores for
seen labels. However, since the mask marked unseen labels,
this required computing an intermittent flipped mask.
* Write moves costs directly into numpy array (#10163)
This avoids elementwise indexing and the allocation of an additional
array.
Gives a ~15% speed improvement when using batch_by_sequence with size
32.
* Temporarily disable ner and rehearse tests
Until rehearse is implemented again in the refactored parser.
* Fix loss serialization issue (#10600)
* Fix loss serialization issue
Serialization of a model fails with:
TypeError: array(738.3855, dtype=float32) is not JSON serializable
Fix this using float conversion.
* Disable CI steps that require spacy.TransitionBasedParser.v2
After finishing the refactor, TransitionBasedParser.v2 should be
provided for backwards compat.
* Add back support for beam parsing to the refactored parser (#10633)
* Add back support for beam parsing
Beam parsing was already implemented as part of the `BeamBatch` class.
This change makes its counterpart `GreedyBatch`. Both classes are hooked
up in `TransitionModel`, selecting `GreedyBatch` when the beam size is
one, or `BeamBatch` otherwise.
* Use kwarg for beam width
Co-authored-by: Sofie Van Landeghem <svlandeg@users.noreply.github.com>
* Avoid implicit default for beam_width and beam_density
* Parser.{beam,greedy}_parse: ensure labels are added
* Remove 'deprecated' comments
Co-authored-by: Sofie Van Landeghem <svlandeg@users.noreply.github.com>
Co-authored-by: Sofie Van Landeghem <svlandeg@users.noreply.github.com>
* Parser `StateC` optimizations (#10746)
* `StateC`: Optimizations
Avoid GIL acquisition in `__init__`
Increase default buffer capacities on init
Reduce C++ exception overhead
* Fix typo
* Replace `set::count` with `set::find`
* Add exception attribute to c'tor
* Remove unused import
* Use a power-of-two value for initial capacity
Use default-insert to init `_heads` and `_unshiftable`
* Merge `cdef` variable declarations and assignments
* Vectorize `example.get_aligned_parses` (#10789)
* `example`: Vectorize `get_aligned_parse`
Rename `numpy` import
* Convert aligned array to lists before returning
* Revert import renaming
* Elide slice arguments when selecting the entire range
* Tagger/morphologizer alignment performance optimizations (#10798)
* `example`: Unwrap `numpy` scalar arrays before passing them to `StringStore.__getitem__`
* `AlignmentArray`: Use native list as staging buffer for offset calculation
* `example`: Vectorize `get_aligned`
* Hoist inner functions out of `get_aligned`
* Replace inline `if..else` clause in assignment statement
* `AlignmentArray`: Use raw indexing into offset and data `numpy` arrays
* `example`: Replace array unique value check with `groupby`
* `example`: Correctly exclude tokens with no alignment in `_get_aligned_vectorized`
Simplify `_get_aligned_non_vectorized`
* `util`: Update `all_equal` docstring
* Explicitly use `int32_t*`
* Restore C CPU inference in the refactored parser (#10747)
* Bring back the C parsing model
The C parsing model is used for CPU inference and is still faster for
CPU inference than the forward pass of the Thinc model.
* Use C sgemm provided by the Ops implementation
* Make tb_framework module Cython, merge in C forward implementation
* TransitionModel: raise in backprop returned from forward_cpu
* Re-enable greedy parse test
* Return transition scores when forward_cpu is used
* Apply suggestions from code review
Import `Model` from `thinc.api`
Co-authored-by: Sofie Van Landeghem <svlandeg@users.noreply.github.com>
* Use relative imports in tb_framework
* Don't assume a default for beam_width
* We don't have a direct dependency on BLIS anymore
* Rename forwards to _forward_{fallback,greedy_cpu}
* Require thinc >=8.1.0,<8.2.0
* tb_framework: clean up imports
* Fix return type of _get_seen_mask
* Move up _forward_greedy_cpu
* Style fixes.
* Lower thinc lowerbound to 8.1.0.dev0
* Formatting fix
Co-authored-by: Adriane Boyd <adrianeboyd@gmail.com>
Co-authored-by: Sofie Van Landeghem <svlandeg@users.noreply.github.com>
Co-authored-by: Adriane Boyd <adrianeboyd@gmail.com>
* Reimplement parser rehearsal function (#10878)
* Reimplement parser rehearsal function
Before the parser refactor, rehearsal was driven by a loop in the
`rehearse` method itself. For each parsing step, the loops would:
1. Get the predictions of the teacher.
2. Get the predictions and backprop function of the student.
3. Compute the loss and backprop into the student.
4. Move the teacher and student forward with the predictions of
the student.
In the refactored parser, we cannot perform search stepwise rehearsal
anymore, since the model now predicts all parsing steps at once.
Therefore, rehearsal is performed in the following steps:
1. Get the predictions of all parsing steps from the student, along
with its backprop function.
2. Get the predictions from the teacher, but use the predictions of
the student to advance the parser while doing so.
3. Compute the loss and backprop into the student.
To support the second step a new method, `advance_with_actions` is
added to `GreedyBatch`, which performs the provided parsing steps.
* tb_framework: wrap upper_W and upper_b in Linear
Thinc's Optimizer cannot handle resizing of existing parameters. Until
it does, we work around this by wrapping the weights/biases of the upper
layer of the parser model in Linear. When the upper layer is resized, we
copy over the existing parameters into a new Linear instance. This does
not trigger an error in Optimizer, because it sees the resized layer as
a new set of parameters.
* Add test for TransitionSystem.apply_actions
* Better FIXME marker
Co-authored-by: Madeesh Kannan <shadeMe@users.noreply.github.com>
* Fixes from Madeesh
* Apply suggestions from Sofie
Co-authored-by: Sofie Van Landeghem <svlandeg@users.noreply.github.com>
* Remove useless assignment
Co-authored-by: Madeesh Kannan <shadeMe@users.noreply.github.com>
Co-authored-by: Sofie Van Landeghem <svlandeg@users.noreply.github.com>
* Rename some identifiers in the parser refactor (#10935)
* Rename _parseC to _parse_batch
* tb_framework: prefix many auxiliary functions with underscore
To clearly state the intent that they are private.
* Rename `lower` to `hidden`, `upper` to `output`
* Parser slow test fixup
We don't have TransitionBasedParser.{v1,v2} until we bring it back as a
legacy option.
* Remove last vestiges of PrecomputableAffine
This does not exist anymore as a separate layer.
* ner: re-enable sentence boundary checks
* Re-enable test that works now.
* test_ner: make loss test more strict again
* Remove commented line
* Re-enable some more beam parser tests
* Remove unused _forward_reference function
* Update for CBlas changes in Thinc 8.1.0.dev2
Bump thinc dependency to 8.1.0.dev3.
* Remove references to spacy.TransitionBasedParser.{v1,v2}
Since they will not be offered starting with spaCy v4.
* `tb_framework`: Replace references to `thinc.backends.linalg` with `CBlas`
* dont use get_array_module (#11056) (#11293)
Co-authored-by: kadarakos <kadar.akos@gmail.com>
* Move `thinc.extra.search` to `spacy.pipeline._parser_internals` (#11317)
* `search`: Move from `thinc.extra.search`
Fix NPE in `Beam.__dealloc__`
* `pytest`: Add support for executing Cython tests
Move `search` tests from thinc and patch them to run with `pytest`
* `mypy` fix
* Update comment
* `conftest`: Expose `register_cython_tests`
* Remove unused import
* Move `argmax` impls to new `_parser_utils` Cython module (#11410)
* Parser does not have to be a cdef class anymore
This also fixes validation of the initialization schema.
* Add back spacy.TransitionBasedParser.v2
* Fix a rename that was missed in #10878.
So that rehearsal tests pass.
* Remove module from setup.py that got added during the merge
* Bring back support for `update_with_oracle_cut_size` (#12086)
* Bring back support for `update_with_oracle_cut_size`
This option was available in the pre-refactor parser, but was never
implemented in the refactored parser. This option cuts transition
sequences that are longer than `update_with_oracle_cut` size into
separate sequences that have at most `update_with_oracle_cut`
transitions. The oracle (gold standard) transition sequence is used to
determine the cuts and the initial states for the additional sequences.
Applying this cut makes the batches more homogeneous in the transition
sequence lengths, making forward passes (and as a consequence training)
much faster.
Training time 1000 steps on de_core_news_lg:
- Before this change: 149s
- After this change: 68s
- Pre-refactor parser: 81s
* Fix a rename that was missed in #10878.
So that rehearsal tests pass.
* Apply suggestions from @shadeMe
* Use chained conditional
* Test with update_with_oracle_cut_size={0, 1, 5, 100}
And fix a git that occurs with a cut size of 1.
* Fix up some merge fall out
* Update parser distillation for the refactor
In the old parser, we'd iterate over the transitions in the distill
function and compute the loss/gradients on the go. In the refactored
parser, we first let the student model parse the inputs. Then we'll let
the teacher compute the transition probabilities of the states in the
student's transition sequence. We can then compute the gradients of the
student given the teacher.
* Add back spacy.TransitionBasedParser.v1 references
- Accordion in the architecture docs.
- Test in test_parse, but disabled until we have a spacy-legacy release.
Co-authored-by: Matthew Honnibal <honnibal+gh@gmail.com>
Co-authored-by: svlandeg <svlandeg@github.com>
Co-authored-by: Sofie Van Landeghem <svlandeg@users.noreply.github.com>
Co-authored-by: Madeesh Kannan <shadeMe@users.noreply.github.com>
Co-authored-by: Adriane Boyd <adrianeboyd@gmail.com>
Co-authored-by: kadarakos <kadar.akos@gmail.com>
2023-01-18 13:27:45 +03:00
|
|
|
@pytest.mark.parametrize("parser_config_string", [parser_config_string_upper])
|
2020-12-18 13:56:57 +03:00
|
|
|
def test_config_validate_literal(parser_config_string):
|
2020-09-23 18:32:14 +03:00
|
|
|
nlp = English()
|
|
|
|
config = Config().from_str(parser_config_string)
|
|
|
|
config["model"]["state_type"] = "nonsense"
|
|
|
|
with pytest.raises(ConfigValidationError):
|
|
|
|
nlp.add_pipe("parser", config=config)
|
|
|
|
config["model"]["state_type"] = "ner"
|
2020-09-23 18:33:13 +03:00
|
|
|
nlp.add_pipe("parser", config=config)
|
2021-01-13 04:02:59 +03:00
|
|
|
|
|
|
|
|
|
|
|
def test_config_only_resolve_relevant_blocks():
|
|
|
|
"""Test that only the relevant blocks are resolved in the different methods
|
|
|
|
and that invalid blocks are ignored if needed. For instance, the [initialize]
|
|
|
|
shouldn't be resolved at runtime.
|
|
|
|
"""
|
|
|
|
nlp = English()
|
|
|
|
config = nlp.config
|
|
|
|
config["training"]["before_to_disk"] = {"@misc": "nonexistent"}
|
|
|
|
config["initialize"]["lookups"] = {"@misc": "nonexistent"}
|
|
|
|
# This shouldn't resolve [training] or [initialize]
|
|
|
|
nlp = load_model_from_config(config, auto_fill=True)
|
|
|
|
# This will raise for nonexistent value
|
|
|
|
with pytest.raises(RegistryError):
|
|
|
|
nlp.initialize()
|
|
|
|
nlp.config["initialize"]["lookups"] = None
|
|
|
|
nlp.initialize()
|
2021-04-12 15:35:57 +03:00
|
|
|
|
|
|
|
|
|
|
|
def test_hyphen_in_config():
|
|
|
|
hyphen_config_str = """
|
|
|
|
[nlp]
|
|
|
|
lang = "en"
|
|
|
|
pipeline = ["my_punctual_component"]
|
|
|
|
|
|
|
|
[components]
|
|
|
|
|
|
|
|
[components.my_punctual_component]
|
|
|
|
factory = "my_punctual_component"
|
|
|
|
punctuation = ["?","-"]
|
|
|
|
"""
|
|
|
|
|
|
|
|
@spacy.Language.factory("my_punctual_component")
|
|
|
|
class MyPunctualComponent(object):
|
|
|
|
name = "my_punctual_component"
|
|
|
|
|
|
|
|
def __init__(
|
|
|
|
self,
|
|
|
|
nlp,
|
|
|
|
name,
|
|
|
|
punctuation,
|
|
|
|
):
|
|
|
|
self.punctuation = punctuation
|
|
|
|
|
|
|
|
nlp = English.from_config(load_config_from_str(hyphen_config_str))
|
2021-06-28 12:48:00 +03:00
|
|
|
assert nlp.get_pipe("my_punctual_component").punctuation == ["?", "-"]
|