53687b5bca
* [wip] Update * [wip] Update * Add initial port * [wip] Update * Fix all imports * Add spancat_exclusive to pipeline * [WIP] Update * [ci skip] Add breakpoint for debugging * Use spacy.SpanCategorizer.v1 as default archi * Update spacy/pipeline/spancat_exclusive.py Co-authored-by: kadarakos <kadar.akos@gmail.com> * [ci skip] Small updates * Use Softmax v2 directly from thinc * Cache the label map * Fix mypy errors However, I ignored line 370 because it opened up a bunch of type errors that might be trickier to solve and might lead to a more complicated codebase. * avoid multiplication with 1.0 Co-authored-by: kadarakos <kadar.akos@gmail.com> * Update spacy/pipeline/spancat_exclusive.py Co-authored-by: Sofie Van Landeghem <svlandeg@users.noreply.github.com> * Update component versions to v2 * Add scorer to docstring * Add _n_labels property to SpanCategorizer Instead of using len(self.labels) in initialize() I am using a private property self._n_labels. This achieves implementation parity and allows me to delete the whole initialize() method for spancat_exclusive (since it's now the same with spancat). * Inherit from SpanCat instead of TrainablePipe This commit changes the inheritance structure of Exclusive_Spancat, now it's inheriting from SpanCategorizer than TrainablePipe. This allows me to remove duplicate methods that are already present in the parent function. * Revert documentation link to spancat * Fix init call for exclusive spancat * Update spacy/pipeline/spancat_exclusive.py Co-authored-by: Adriane Boyd <adrianeboyd@gmail.com> * Import Suggester from spancat * Include zero_init.v1 for spancat * Implement _allow_extra_label to use _n_labels To ensure that spancat / spancat_exclusive cannot be resized after initialization, I inherited the _allow_extra_label() method from spacy/pipeline/trainable_pipe.pyx and used self._n_labels instead of len(self.labels) for checking. I think that changing it locally is a better solution rather than forcing each class that inherits TrainablePipe to use the self._n_labels attribute. Also note that I turned-off black formatting in this block of code because it reads better without the overhang. * Extend existing tests to spancat_exclusive In this commit, I extended the existing tests for spancat to include spancat_exclusive. I parametrized the test functions with 'name' (similar var name with textcat and textcat_multilabel) for each applicable test. TODO: Add overfitting tests for spancat_exclusive * Update documentation for spancat * Turn on formatting for allow_extra_label * Remove initializers in default config * Use DEFAULT_EXCL_SPANCAT_MODEL I also renamed spancat_exclusive_default_config into spancat_excl_default_config because black does some not pretty formatting changes. * Update documentation Update grammar and usage Co-authored-by: Adriane Boyd <adrianeboyd@gmail.com> * Clarify docstring for Exclusive_SpanCategorizer * Remove mypy ignore and typecast labels to list * Fix documentation API * Use a single variable for tests * Update defaults for number of rows Co-authored-by: Adriane Boyd <adrianeboyd@gmail.com> * Put back initializers in spancat config Whenever I remove model.scorer.init_w and model.scorer.init_b, I encounter an error in the test: SystemError: <method '__getitem__' of 'dict' objects> returned a result with an error set. My Thinc version is 8.1.5, but I can't seem to check what's causing the error. * Update spancat_exclusive docstring * Remove init_W and init_B parameters This commit is expected to fail until the new Thinc release. * Require thinc>=8.1.6 for serializable Softmax defaults * Handle zero suggestions to make tests pass I'm not sure if this is the most elegant solution. But what should happen is that the _make_span_group function MUST return an empty SpanGroup if there are no suggestions. The error happens when the 'scores' variable is empty. We cannot get the 'predicted' and other downstream vars. * Better approach for handling zero suggestions * Update website/docs/api/spancategorizer.md Co-authored-by: Adriane Boyd <adrianeboyd@gmail.com> * Update spancategorizer headers * Apply suggestions from code review Co-authored-by: Sofie Van Landeghem <svlandeg@users.noreply.github.com> * Add default value in negative_weight in docs * Add default value in allow_overlap in docs * Update how spancat_exclusive is constructed In this commit, I added the following: - Put the default values of negative_weight and allow_overlap in the default_config dictionary. - Rename make_spancat -> make_exclusive_spancat * Run prettier on spancategorizer.mdx * Change exactly one -> at most one * Add suggester documentation in Exclusive_SpanCategorizer * Add suggester to spancat docstrings * merge multilabel and singlelabel spancat * rename spancat_exclusive to singlelable * wire up different make_spangroups for single and multilabel * black * black * add docstrings * more docstring and fix negative_label * don't rely on default arguments * black * remove spancat exclusive * replace single_label with add_negative_label and adjust inference * mypy * logical bug in configuration check * add spans.attrs[scores] * single label make_spangroup test * bugfix * black * tests for make_span_group with negative labels * refactor make_span_group * black * Update spacy/tests/pipeline/test_spancat.py Co-authored-by: Adriane Boyd <adrianeboyd@gmail.com> * remove duplicate declaration * Update spacy/pipeline/spancat.py Co-authored-by: Adriane Boyd <adrianeboyd@gmail.com> * raise error instead of just print * make label mapper private * update docs * run prettier * Update website/docs/api/spancategorizer.mdx Co-authored-by: Adriane Boyd <adrianeboyd@gmail.com> * Update website/docs/api/spancategorizer.mdx Co-authored-by: Adriane Boyd <adrianeboyd@gmail.com> * Update spacy/pipeline/spancat.py Co-authored-by: Adriane Boyd <adrianeboyd@gmail.com> * Update spacy/pipeline/spancat.py Co-authored-by: Adriane Boyd <adrianeboyd@gmail.com> * Update spacy/pipeline/spancat.py Co-authored-by: Adriane Boyd <adrianeboyd@gmail.com> * Update spacy/pipeline/spancat.py Co-authored-by: Adriane Boyd <adrianeboyd@gmail.com> * don't keep recomputing self._label_map for each span * typo in docs * Intervals to private and document 'name' param * Update spacy/pipeline/spancat.py Co-authored-by: Adriane Boyd <adrianeboyd@gmail.com> * Update spacy/pipeline/spancat.py Co-authored-by: Adriane Boyd <adrianeboyd@gmail.com> * add Tag to new features * replace tags * revert * revert * revert * revert * Update website/docs/api/spancategorizer.mdx Co-authored-by: Adriane Boyd <adrianeboyd@gmail.com> * Update website/docs/api/spancategorizer.mdx Co-authored-by: Adriane Boyd <adrianeboyd@gmail.com> * prettier * Fix merge * Update website/docs/api/spancategorizer.mdx * remove references to 'single_label' * remove old paragraph * Add spancat_singlelabel to config template * Format * Extend init config tests --------- Co-authored-by: kadarakos <kadar.akos@gmail.com> Co-authored-by: Sofie Van Landeghem <svlandeg@users.noreply.github.com> Co-authored-by: Adriane Boyd <adrianeboyd@gmail.com> |
||
---|---|---|
.. | ||
doc | ||
lang | ||
matcher | ||
morphology | ||
package | ||
parser | ||
pipeline | ||
serialize | ||
tokenizer | ||
training | ||
vocab_vectors | ||
__init__.py | ||
conftest.py | ||
enable_gpu.py | ||
README.md | ||
test_architectures.py | ||
test_cli_app.py | ||
test_cli.py | ||
test_displacy.py | ||
test_errors.py | ||
test_language.py | ||
test_misc.py | ||
test_models.py | ||
test_pickles.py | ||
test_scorer.py | ||
test_ty.py | ||
util.py |
spaCy tests
spaCy uses the pytest framework for testing. For more info on this, see the pytest documentation.
Tests for spaCy modules and classes live in their own directories of the same name. For example, tests for the Tokenizer
can be found in /tests/tokenizer
. All test modules (i.e. directories) also need to be listed in spaCy's setup.py
. To be interpreted and run, all test files and test functions need to be prefixed with test_
.
⚠️ Important note: As part of our new model training infrastructure, we've moved all model tests to the
spacy-models
repository. This allows us to test the models separately from the core library functionality.
Table of contents
- Running the tests
- Dos and don'ts
- Parameters
- Fixtures
- Helpers and utilities
- Contributing to the tests
Running the tests
To show print statements, run the tests with py.test -s
. To abort after the
first failure, run them with py.test -x
.
py.test spacy # run basic tests
py.test spacy --slow # run basic and slow tests
You can also run tests in a specific file or directory, or even only one specific test:
py.test spacy/tests/tokenizer # run all tests in directory
py.test spacy/tests/tokenizer/test_exceptions.py # run all tests in file
py.test spacy/tests/tokenizer/test_exceptions.py::test_tokenizer_handles_emoji # run specific test
Dos and don'ts
To keep the behavior of the tests consistent and predictable, we try to follow a few basic conventions:
- Test names should follow a pattern of
test_[module]_[tested behaviour]
. For example:test_tokenizer_keeps_email
ortest_spans_override_sentiment
. - If you're testing for a bug reported in a specific issue, always create a regression test. Regression tests should be named
test_issue[ISSUE NUMBER]
and live in theregression
directory. - Only use
@pytest.mark.xfail
for tests that should pass, but currently fail. To test for desired negative behavior, useassert not
in your test. - Very extensive tests that take a long time to run should be marked with
@pytest.mark.slow
. If your slow test is testing important behavior, consider adding an additional simpler version. - If tests require loading the models, they should be added to the
spacy-models
tests. - Before requiring the models, always make sure there is no other way to test the particular behavior. In a lot of cases, it's sufficient to simply create a
Doc
object manually. See the section on helpers and utility functions for more info on this. - Avoid unnecessary imports. There should never be a need to explicitly import spaCy at the top of a file, and many components are available as fixtures. You should also avoid wildcard imports (
from module import *
). - If you're importing from spaCy, always use absolute imports. For example:
from spacy.language import Language
. - Try to keep the tests readable and concise. Use clear and descriptive variable names (
doc
,tokens
andtext
are great), keep it short and only test for one behavior at a time.
Parameters
If the test cases can be extracted from the test, always parametrize
them instead of hard-coding them into the test:
@pytest.mark.parametrize('text', ["google.com", "spacy.io"])
def test_tokenizer_keep_urls(tokenizer, text):
tokens = tokenizer(text)
assert len(tokens) == 1
This will run the test once for each text
value. Even if you're only testing one example, it's usually best to specify it as a parameter. This will later make it easier for others to quickly add additional test cases without having to modify the test.
You can also specify parameters as tuples to test with multiple values per test:
@pytest.mark.parametrize('text,length', [("U.S.", 1), ("us.", 2), ("(U.S.", 2)])
To test for combinations of parameters, you can add several parametrize
markers:
@pytest.mark.parametrize('text', ["A test sentence", "Another sentence"])
@pytest.mark.parametrize('punct', ['.', '!', '?'])
This will run the test with all combinations of the two parameters text
and punct
. Use this feature sparingly, though, as it can easily cause unnecessary or undesired test bloat.
Fixtures
Fixtures to create instances of spaCy objects and other components should only be defined once in the global conftest.py
. We avoid having per-directory conftest files, as this can easily lead to confusion.
These are the main fixtures that are currently available:
Fixture | Description |
---|---|
tokenizer |
Basic, language-independent tokenizer. Identical to the xx language class. |
en_tokenizer , de_tokenizer , ... |
Creates an English, German etc. tokenizer. |
en_vocab |
Creates an instance of the English Vocab . |
The fixtures can be used in all tests by simply setting them as an argument, like this:
def test_module_do_something(en_tokenizer):
tokens = en_tokenizer("Some text here")
If all tests in a file require a specific configuration, or use the same complex example, it can be helpful to create a separate fixture. This fixture should be added at the top of each file. Make sure to use descriptive names for these fixtures and don't override any of the global fixtures listed above. From looking at a test, it should immediately be clear which fixtures are used, and where they are coming from.
Helpers and utilities
Our new test setup comes with a few handy utility functions that can be imported from util.py
.
Constructing a Doc
object manually
Loading the models is expensive and not necessary if you're not actually testing the model performance. If all you need is a Doc
object with annotations like heads, POS tags or the dependency parse, you can construct it manually.
def test_doc_token_api_strings(en_vocab):
words = ["Give", "it", "back", "!", "He", "pleaded", "."]
pos = ['VERB', 'PRON', 'PART', 'PUNCT', 'PRON', 'VERB', 'PUNCT']
heads = [0, 0, 0, 0, 5, 5, 5]
deps = ['ROOT', 'dobj', 'prt', 'punct', 'nsubj', 'ROOT', 'punct']
doc = Doc(en_vocab, words=words, pos=pos, heads=heads, deps=deps)
assert doc[0].text == 'Give'
assert doc[0].lower_ == 'give'
assert doc[0].pos_ == 'VERB'
assert doc[0].dep_ == 'ROOT'
Other utilities
Name | Description |
---|---|
apply_transition_sequence(parser, doc, sequence) |
Perform a series of pre-specified transitions, to put the parser in a desired state. |
add_vecs_to_vocab(vocab, vectors) |
Add list of vector tuples ([("text", [1, 2, 3])] ) to given vocab. All vectors need to have the same length. |
get_cosine(vec1, vec2) |
Get cosine for two given vectors. |
assert_docs_equal(doc1, doc2) |
Compare two Doc objects and assert that they're equal. Tests for tokens, tags, dependencies and entities. |
Contributing to the tests
There's still a long way to go to finally reach 100% test coverage – and we'd appreciate your help! 🙌 You can open an issue on our issue tracker and label it tests
, or make a pull request to this repository.
📖 For more information on contributing to spaCy in general, check out our contribution guidelines.