2021-12-04 22:34:48 +03:00
|
|
|
import random
|
|
|
|
|
2017-07-22 02:48:58 +03:00
|
|
|
import pytest
|
2020-10-13 22:07:13 +03:00
|
|
|
from numpy.testing import assert_equal
|
|
|
|
|
2021-12-04 22:34:48 +03:00
|
|
|
from spacy.attrs import ENT_IOB
|
🏷 Add Mypy check to CI and ignore all existing Mypy errors (#9167)
* 🚨 Ignore all existing Mypy errors
* 🏗 Add Mypy check to CI
* Add types-mock and types-requests as dev requirements
* Add additional type ignore directives
* Add types packages to dev-only list in reqs test
* Add types-dataclasses for python 3.6
* Add ignore to pretrain
* 🏷 Improve type annotation on `run_command` helper
The `run_command` helper previously declared that it returned an
`Optional[subprocess.CompletedProcess]`, but it isn't actually possible
for the function to return `None`. These changes modify the type
annotation of the `run_command` helper and remove all now-unnecessary
`# type: ignore` directives.
* 🔧 Allow variable type redefinition in limited contexts
These changes modify how Mypy is configured to allow variables to have
their type automatically redefined under certain conditions. The Mypy
documentation contains the following example:
```python
def process(items: List[str]) -> None:
# 'items' has type List[str]
items = [item.split() for item in items]
# 'items' now has type List[List[str]]
...
```
This configuration change is especially helpful in reducing the number
of `# type: ignore` directives needed to handle the common pattern of:
* Accepting a filepath as a string
* Overwriting the variable using `filepath = ensure_path(filepath)`
These changes enable redefinition and remove all `# type: ignore`
directives rendered redundant by this change.
* 🏷 Add type annotation to converters mapping
* 🚨 Fix Mypy error in convert CLI argument verification
* 🏷 Improve type annotation on `resolve_dot_names` helper
* 🏷 Add type annotations for `Vocab` attributes `strings` and `vectors`
* 🏷 Add type annotations for more `Vocab` attributes
* 🏷 Add loose type annotation for gold data compilation
* 🏷 Improve `_format_labels` type annotation
* 🏷 Fix `get_lang_class` type annotation
* 🏷 Loosen return type of `Language.evaluate`
* 🏷 Don't accept `Scorer` in `handle_scores_per_type`
* 🏷 Add `string_to_list` overloads
* 🏷 Fix non-Optional command-line options
* 🙈 Ignore redefinition of `wandb_logger` in `loggers.py`
* ➕ Install `typing_extensions` in Python 3.8+
The `typing_extensions` package states that it should be used when
"writing code that must be compatible with multiple Python versions".
Since SpaCy needs to support multiple Python versions, it should be used
when newer `typing` module members are required. One example of this is
`Literal`, which is available starting with Python 3.8.
Previously SpaCy tried to import `Literal` from `typing`, falling back
to `typing_extensions` if the import failed. However, Mypy doesn't seem
to be able to understand what `Literal` means when the initial import
means. Therefore, these changes modify how `compat` imports `Literal` by
always importing it from `typing_extensions`.
These changes also modify how `typing_extensions` is installed, so that
it is a requirement for all Python versions, including those greater
than or equal to 3.8.
* 🏷 Improve type annotation for `Language.pipe`
These changes add a missing overload variant to the type signature of
`Language.pipe`. Additionally, the type signature is enhanced to allow
type checkers to differentiate between the two overload variants based
on the `as_tuple` parameter.
Fixes #8772
* ➖ Don't install `typing-extensions` in Python 3.8+
After more detailed analysis of how to implement Python version-specific
type annotations using SpaCy, it has been determined that by branching
on a comparison against `sys.version_info` can be statically analyzed by
Mypy well enough to enable us to conditionally use
`typing_extensions.Literal`. This means that we no longer need to
install `typing_extensions` for Python versions greater than or equal to
3.8! 🎉
These changes revert previous changes installing `typing-extensions`
regardless of Python version and modify how we import the `Literal` type
to ensure that Mypy treats it properly.
* resolve mypy errors for Strict pydantic types
* refactor code to avoid missing return statement
* fix types of convert CLI command
* avoid list-set confustion in debug_data
* fix typo and formatting
* small fixes to avoid type ignores
* fix types in profile CLI command and make it more efficient
* type fixes in projects CLI
* put one ignore back
* type fixes for render
* fix render types - the sequel
* fix BaseDefault in language definitions
* fix type of noun_chunks iterator - yields tuple instead of span
* fix types in language-specific modules
* 🏷 Expand accepted inputs of `get_string_id`
`get_string_id` accepts either a string (in which case it returns its
ID) or an ID (in which case it immediately returns the ID). These
changes extend the type annotation of `get_string_id` to indicate that
it can accept either strings or IDs.
* 🏷 Handle override types in `combine_score_weights`
The `combine_score_weights` function allows users to pass an `overrides`
mapping to override data extracted from the `weights` argument. Since it
allows `Optional` dictionary values, the return value may also include
`Optional` dictionary values.
These changes update the type annotations for `combine_score_weights` to
reflect this fact.
* 🏷 Fix tokenizer serialization method signatures in `DummyTokenizer`
* 🏷 Fix redefinition of `wandb_logger`
These changes fix the redefinition of `wandb_logger` by giving a
separate name to each `WandbLogger` version. For
backwards-compatibility, `spacy.train` still exports `wandb_logger_v3`
as `wandb_logger` for now.
* more fixes for typing in language
* type fixes in model definitions
* 🏷 Annotate `_RandomWords.probs` as `NDArray`
* 🏷 Annotate `tok2vec` layers to help Mypy
* 🐛 Fix `_RandomWords.probs` type annotations for Python 3.6
Also remove an import that I forgot to move to the top of the module 😅
* more fixes for matchers and other pipeline components
* quick fix for entity linker
* fixing types for spancat, textcat, etc
* bugfix for tok2vec
* type annotations for scorer
* add runtime_checkable for Protocol
* type and import fixes in tests
* mypy fixes for training utilities
* few fixes in util
* fix import
* 🐵 Remove unused `# type: ignore` directives
* 🏷 Annotate `Language._components`
* 🏷 Annotate `spacy.pipeline.Pipe`
* add doc as property to span.pyi
* small fixes and cleanup
* explicit type annotations instead of via comment
Co-authored-by: Adriane Boyd <adrianeboyd@gmail.com>
Co-authored-by: svlandeg <sofie.vanlandeghem@gmail.com>
Co-authored-by: svlandeg <svlandeg@github.com>
2021-10-14 16:21:40 +03:00
|
|
|
from spacy import util, registry
|
2019-09-18 22:37:17 +03:00
|
|
|
from spacy.lang.en import English
|
2021-12-04 22:34:48 +03:00
|
|
|
from spacy.lang.it import Italian
|
2020-06-15 15:56:04 +03:00
|
|
|
from spacy.language import Language
|
|
|
|
from spacy.lookups import Lookups
|
2020-07-31 00:30:54 +03:00
|
|
|
from spacy.pipeline._parser_internals.ner import BiluoPushDown
|
2022-06-17 22:02:37 +03:00
|
|
|
from spacy.training import Example, iob_to_biluo, split_bilu_label
|
2021-05-06 11:49:55 +03:00
|
|
|
from spacy.tokens import Doc, Span
|
🏷 Add Mypy check to CI and ignore all existing Mypy errors (#9167)
* 🚨 Ignore all existing Mypy errors
* 🏗 Add Mypy check to CI
* Add types-mock and types-requests as dev requirements
* Add additional type ignore directives
* Add types packages to dev-only list in reqs test
* Add types-dataclasses for python 3.6
* Add ignore to pretrain
* 🏷 Improve type annotation on `run_command` helper
The `run_command` helper previously declared that it returned an
`Optional[subprocess.CompletedProcess]`, but it isn't actually possible
for the function to return `None`. These changes modify the type
annotation of the `run_command` helper and remove all now-unnecessary
`# type: ignore` directives.
* 🔧 Allow variable type redefinition in limited contexts
These changes modify how Mypy is configured to allow variables to have
their type automatically redefined under certain conditions. The Mypy
documentation contains the following example:
```python
def process(items: List[str]) -> None:
# 'items' has type List[str]
items = [item.split() for item in items]
# 'items' now has type List[List[str]]
...
```
This configuration change is especially helpful in reducing the number
of `# type: ignore` directives needed to handle the common pattern of:
* Accepting a filepath as a string
* Overwriting the variable using `filepath = ensure_path(filepath)`
These changes enable redefinition and remove all `# type: ignore`
directives rendered redundant by this change.
* 🏷 Add type annotation to converters mapping
* 🚨 Fix Mypy error in convert CLI argument verification
* 🏷 Improve type annotation on `resolve_dot_names` helper
* 🏷 Add type annotations for `Vocab` attributes `strings` and `vectors`
* 🏷 Add type annotations for more `Vocab` attributes
* 🏷 Add loose type annotation for gold data compilation
* 🏷 Improve `_format_labels` type annotation
* 🏷 Fix `get_lang_class` type annotation
* 🏷 Loosen return type of `Language.evaluate`
* 🏷 Don't accept `Scorer` in `handle_scores_per_type`
* 🏷 Add `string_to_list` overloads
* 🏷 Fix non-Optional command-line options
* 🙈 Ignore redefinition of `wandb_logger` in `loggers.py`
* ➕ Install `typing_extensions` in Python 3.8+
The `typing_extensions` package states that it should be used when
"writing code that must be compatible with multiple Python versions".
Since SpaCy needs to support multiple Python versions, it should be used
when newer `typing` module members are required. One example of this is
`Literal`, which is available starting with Python 3.8.
Previously SpaCy tried to import `Literal` from `typing`, falling back
to `typing_extensions` if the import failed. However, Mypy doesn't seem
to be able to understand what `Literal` means when the initial import
means. Therefore, these changes modify how `compat` imports `Literal` by
always importing it from `typing_extensions`.
These changes also modify how `typing_extensions` is installed, so that
it is a requirement for all Python versions, including those greater
than or equal to 3.8.
* 🏷 Improve type annotation for `Language.pipe`
These changes add a missing overload variant to the type signature of
`Language.pipe`. Additionally, the type signature is enhanced to allow
type checkers to differentiate between the two overload variants based
on the `as_tuple` parameter.
Fixes #8772
* ➖ Don't install `typing-extensions` in Python 3.8+
After more detailed analysis of how to implement Python version-specific
type annotations using SpaCy, it has been determined that by branching
on a comparison against `sys.version_info` can be statically analyzed by
Mypy well enough to enable us to conditionally use
`typing_extensions.Literal`. This means that we no longer need to
install `typing_extensions` for Python versions greater than or equal to
3.8! 🎉
These changes revert previous changes installing `typing-extensions`
regardless of Python version and modify how we import the `Literal` type
to ensure that Mypy treats it properly.
* resolve mypy errors for Strict pydantic types
* refactor code to avoid missing return statement
* fix types of convert CLI command
* avoid list-set confustion in debug_data
* fix typo and formatting
* small fixes to avoid type ignores
* fix types in profile CLI command and make it more efficient
* type fixes in projects CLI
* put one ignore back
* type fixes for render
* fix render types - the sequel
* fix BaseDefault in language definitions
* fix type of noun_chunks iterator - yields tuple instead of span
* fix types in language-specific modules
* 🏷 Expand accepted inputs of `get_string_id`
`get_string_id` accepts either a string (in which case it returns its
ID) or an ID (in which case it immediately returns the ID). These
changes extend the type annotation of `get_string_id` to indicate that
it can accept either strings or IDs.
* 🏷 Handle override types in `combine_score_weights`
The `combine_score_weights` function allows users to pass an `overrides`
mapping to override data extracted from the `weights` argument. Since it
allows `Optional` dictionary values, the return value may also include
`Optional` dictionary values.
These changes update the type annotations for `combine_score_weights` to
reflect this fact.
* 🏷 Fix tokenizer serialization method signatures in `DummyTokenizer`
* 🏷 Fix redefinition of `wandb_logger`
These changes fix the redefinition of `wandb_logger` by giving a
separate name to each `WandbLogger` version. For
backwards-compatibility, `spacy.train` still exports `wandb_logger_v3`
as `wandb_logger` for now.
* more fixes for typing in language
* type fixes in model definitions
* 🏷 Annotate `_RandomWords.probs` as `NDArray`
* 🏷 Annotate `tok2vec` layers to help Mypy
* 🐛 Fix `_RandomWords.probs` type annotations for Python 3.6
Also remove an import that I forgot to move to the top of the module 😅
* more fixes for matchers and other pipeline components
* quick fix for entity linker
* fixing types for spancat, textcat, etc
* bugfix for tok2vec
* type annotations for scorer
* add runtime_checkable for Protocol
* type and import fixes in tests
* mypy fixes for training utilities
* few fixes in util
* fix import
* 🐵 Remove unused `# type: ignore` directives
* 🏷 Annotate `Language._components`
* 🏷 Annotate `spacy.pipeline.Pipe`
* add doc as property to span.pyi
* small fixes and cleanup
* explicit type annotations instead of via comment
Co-authored-by: Adriane Boyd <adrianeboyd@gmail.com>
Co-authored-by: svlandeg <sofie.vanlandeghem@gmail.com>
Co-authored-by: svlandeg <svlandeg@github.com>
2021-10-14 16:21:40 +03:00
|
|
|
from spacy.vocab import Vocab
|
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
|
|
|
from thinc.api import fix_random_seed
|
2020-08-14 16:00:52 +03:00
|
|
|
import logging
|
2017-07-22 02:48:58 +03:00
|
|
|
|
2020-05-21 19:39:06 +03:00
|
|
|
from ..util import make_tempdir
|
2021-06-17 10:33:00 +03:00
|
|
|
from ...pipeline import EntityRecognizer
|
|
|
|
from ...pipeline.ner import DEFAULT_NER_MODEL
|
2020-08-14 16:00:52 +03:00
|
|
|
|
2020-01-29 19:06:46 +03:00
|
|
|
TRAIN_DATA = [
|
|
|
|
("Who is Shaka Khan?", {"entities": [(7, 17, "PERSON")]}),
|
|
|
|
("I like London and Berlin.", {"entities": [(7, 13, "LOC"), (18, 24, "LOC")]}),
|
2020-02-18 17:38:18 +03:00
|
|
|
]
|
2020-01-29 19:06:46 +03:00
|
|
|
|
2017-07-22 02:48:58 +03:00
|
|
|
|
2021-06-17 10:33:00 +03:00
|
|
|
@pytest.fixture
|
|
|
|
def neg_key():
|
|
|
|
return "non_entities"
|
|
|
|
|
|
|
|
|
2017-07-22 02:48:58 +03:00
|
|
|
@pytest.fixture
|
|
|
|
def vocab():
|
|
|
|
return Vocab()
|
|
|
|
|
|
|
|
|
|
|
|
@pytest.fixture
|
|
|
|
def doc(vocab):
|
2018-11-27 03:09:36 +03:00
|
|
|
return Doc(vocab, words=["Casey", "went", "to", "New", "York", "."])
|
2017-07-22 02:48:58 +03:00
|
|
|
|
|
|
|
|
|
|
|
@pytest.fixture
|
|
|
|
def entity_annots(doc):
|
|
|
|
casey = doc[0:1]
|
|
|
|
ny = doc[3:5]
|
2018-11-27 03:09:36 +03:00
|
|
|
return [
|
|
|
|
(casey.start_char, casey.end_char, "PERSON"),
|
|
|
|
(ny.start_char, ny.end_char, "GPE"),
|
|
|
|
]
|
2017-07-22 02:48:58 +03:00
|
|
|
|
|
|
|
|
|
|
|
@pytest.fixture
|
|
|
|
def entity_types(entity_annots):
|
|
|
|
return sorted(set([label for (s, e, label) in entity_annots]))
|
|
|
|
|
|
|
|
|
|
|
|
@pytest.fixture
|
|
|
|
def tsys(vocab, entity_types):
|
|
|
|
actions = BiluoPushDown.get_actions(entity_types=entity_types)
|
|
|
|
return BiluoPushDown(vocab.strings, actions)
|
|
|
|
|
|
|
|
|
2021-12-04 22:34:48 +03:00
|
|
|
@pytest.mark.parametrize("label", ["U-JOB-NAME"])
|
|
|
|
@pytest.mark.issue(1967)
|
|
|
|
def test_issue1967(label):
|
|
|
|
nlp = Language()
|
|
|
|
config = {}
|
|
|
|
ner = nlp.create_pipe("ner", config=config)
|
|
|
|
example = Example.from_dict(
|
|
|
|
Doc(ner.vocab, words=["word"]),
|
|
|
|
{
|
|
|
|
"ids": [0],
|
|
|
|
"words": ["word"],
|
|
|
|
"tags": ["tag"],
|
|
|
|
"heads": [0],
|
|
|
|
"deps": ["dep"],
|
|
|
|
"entities": [label],
|
|
|
|
},
|
|
|
|
)
|
|
|
|
assert "JOB-NAME" in ner.moves.get_actions(examples=[example])[1]
|
|
|
|
|
|
|
|
|
|
|
|
@pytest.mark.issue(2179)
|
|
|
|
def test_issue2179():
|
|
|
|
"""Test that spurious 'extra_labels' aren't created when initializing NER."""
|
|
|
|
nlp = Italian()
|
|
|
|
ner = nlp.add_pipe("ner")
|
|
|
|
ner.add_label("CITIZENSHIP")
|
|
|
|
nlp.initialize()
|
|
|
|
nlp2 = Italian()
|
|
|
|
nlp2.add_pipe("ner")
|
|
|
|
assert len(nlp2.get_pipe("ner").labels) == 0
|
|
|
|
model = nlp2.get_pipe("ner").model
|
|
|
|
model.attrs["resize_output"](model, nlp.get_pipe("ner").moves.n_moves)
|
|
|
|
nlp2.from_bytes(nlp.to_bytes())
|
|
|
|
assert "extra_labels" not in nlp2.get_pipe("ner").cfg
|
|
|
|
assert nlp2.get_pipe("ner").labels == ("CITIZENSHIP",)
|
|
|
|
|
|
|
|
|
|
|
|
@pytest.mark.issue(2385)
|
|
|
|
def test_issue2385():
|
|
|
|
"""Test that IOB tags are correctly converted to BILUO tags."""
|
|
|
|
# fix bug in labels with a 'b' character
|
|
|
|
tags1 = ("B-BRAWLER", "I-BRAWLER", "I-BRAWLER")
|
|
|
|
assert iob_to_biluo(tags1) == ["B-BRAWLER", "I-BRAWLER", "L-BRAWLER"]
|
|
|
|
# maintain support for iob1 format
|
|
|
|
tags2 = ("I-ORG", "I-ORG", "B-ORG")
|
|
|
|
assert iob_to_biluo(tags2) == ["B-ORG", "L-ORG", "U-ORG"]
|
|
|
|
# maintain support for iob2 format
|
|
|
|
tags3 = ("B-PERSON", "I-PERSON", "B-PERSON")
|
|
|
|
assert iob_to_biluo(tags3) == ["B-PERSON", "L-PERSON", "U-PERSON"]
|
2022-06-17 22:02:37 +03:00
|
|
|
# ensure it works with hyphens in the name
|
|
|
|
tags4 = ("B-MULTI-PERSON", "I-MULTI-PERSON", "B-MULTI-PERSON")
|
|
|
|
assert iob_to_biluo(tags4) == ["B-MULTI-PERSON", "L-MULTI-PERSON", "U-MULTI-PERSON"]
|
2021-12-04 22:34:48 +03:00
|
|
|
|
|
|
|
|
|
|
|
@pytest.mark.issue(2800)
|
|
|
|
def test_issue2800():
|
|
|
|
"""Test issue that arises when too many labels are added to NER model.
|
|
|
|
Used to cause segfault.
|
|
|
|
"""
|
|
|
|
nlp = English()
|
|
|
|
train_data = []
|
|
|
|
train_data.extend(
|
|
|
|
[Example.from_dict(nlp.make_doc("One sentence"), {"entities": []})]
|
|
|
|
)
|
|
|
|
entity_types = [str(i) for i in range(1000)]
|
|
|
|
ner = nlp.add_pipe("ner")
|
|
|
|
for entity_type in list(entity_types):
|
|
|
|
ner.add_label(entity_type)
|
|
|
|
optimizer = nlp.initialize()
|
|
|
|
for i in range(20):
|
|
|
|
losses = {}
|
|
|
|
random.shuffle(train_data)
|
|
|
|
for example in train_data:
|
|
|
|
nlp.update([example], sgd=optimizer, losses=losses, drop=0.5)
|
|
|
|
|
|
|
|
|
|
|
|
@pytest.mark.issue(3209)
|
|
|
|
def test_issue3209():
|
|
|
|
"""Test issue that occurred in spaCy nightly where NER labels were being
|
|
|
|
mapped to classes incorrectly after loading the model, when the labels
|
|
|
|
were added using ner.add_label().
|
|
|
|
"""
|
|
|
|
nlp = English()
|
|
|
|
ner = nlp.add_pipe("ner")
|
|
|
|
ner.add_label("ANIMAL")
|
|
|
|
nlp.initialize()
|
|
|
|
move_names = ["O", "B-ANIMAL", "I-ANIMAL", "L-ANIMAL", "U-ANIMAL"]
|
|
|
|
assert ner.move_names == move_names
|
|
|
|
nlp2 = English()
|
|
|
|
ner2 = nlp2.add_pipe("ner")
|
|
|
|
model = ner2.model
|
|
|
|
model.attrs["resize_output"](model, ner.moves.n_moves)
|
|
|
|
nlp2.from_bytes(nlp.to_bytes())
|
|
|
|
assert ner2.move_names == move_names
|
|
|
|
|
|
|
|
|
2022-06-17 22:02:37 +03:00
|
|
|
def test_labels_from_BILUO():
|
2022-06-27 10:35:35 +03:00
|
|
|
"""Test that labels are inferred correctly when there's a - in label."""
|
2022-06-17 22:02:37 +03:00
|
|
|
nlp = English()
|
|
|
|
ner = nlp.add_pipe("ner")
|
|
|
|
ner.add_label("LARGE-ANIMAL")
|
|
|
|
nlp.initialize()
|
2022-06-27 10:35:35 +03:00
|
|
|
move_names = [
|
|
|
|
"O",
|
|
|
|
"B-LARGE-ANIMAL",
|
|
|
|
"I-LARGE-ANIMAL",
|
|
|
|
"L-LARGE-ANIMAL",
|
|
|
|
"U-LARGE-ANIMAL",
|
|
|
|
]
|
2022-06-17 22:02:37 +03:00
|
|
|
labels = {"LARGE-ANIMAL"}
|
|
|
|
assert ner.move_names == move_names
|
|
|
|
assert set(ner.labels) == labels
|
|
|
|
|
|
|
|
|
2021-12-04 22:34:48 +03:00
|
|
|
@pytest.mark.issue(4267)
|
|
|
|
def test_issue4267():
|
|
|
|
"""Test that running an entity_ruler after ner gives consistent results"""
|
|
|
|
nlp = English()
|
|
|
|
ner = nlp.add_pipe("ner")
|
|
|
|
ner.add_label("PEOPLE")
|
|
|
|
nlp.initialize()
|
|
|
|
assert "ner" in nlp.pipe_names
|
|
|
|
# assert that we have correct IOB annotations
|
|
|
|
doc1 = nlp("hi")
|
|
|
|
assert doc1.has_annotation("ENT_IOB")
|
|
|
|
for token in doc1:
|
|
|
|
assert token.ent_iob == 2
|
|
|
|
# add entity ruler and run again
|
|
|
|
patterns = [{"label": "SOFTWARE", "pattern": "spacy"}]
|
|
|
|
ruler = nlp.add_pipe("entity_ruler")
|
|
|
|
ruler.add_patterns(patterns)
|
|
|
|
assert "entity_ruler" in nlp.pipe_names
|
|
|
|
assert "ner" in nlp.pipe_names
|
|
|
|
# assert that we still have correct IOB annotations
|
|
|
|
doc2 = nlp("hi")
|
|
|
|
assert doc2.has_annotation("ENT_IOB")
|
|
|
|
for token in doc2:
|
|
|
|
assert token.ent_iob == 2
|
|
|
|
|
|
|
|
|
|
|
|
@pytest.mark.issue(4313)
|
|
|
|
def test_issue4313():
|
|
|
|
"""This should not crash or exit with some strange error code"""
|
|
|
|
beam_width = 16
|
|
|
|
beam_density = 0.0001
|
|
|
|
nlp = English()
|
|
|
|
config = {
|
|
|
|
"beam_width": beam_width,
|
|
|
|
"beam_density": beam_density,
|
|
|
|
}
|
|
|
|
ner = nlp.add_pipe("beam_ner", config=config)
|
|
|
|
ner.add_label("SOME_LABEL")
|
|
|
|
nlp.initialize()
|
|
|
|
# add a new label to the doc
|
|
|
|
doc = nlp("What do you think about Apple ?")
|
|
|
|
assert len(ner.labels) == 1
|
|
|
|
assert "SOME_LABEL" in ner.labels
|
|
|
|
apple_ent = Span(doc, 5, 6, label="MY_ORG")
|
|
|
|
doc.ents = list(doc.ents) + [apple_ent]
|
|
|
|
|
|
|
|
# ensure the beam_parse still works with the new label
|
|
|
|
docs = [doc]
|
|
|
|
ner.beam_parse(docs, drop=0.0, beam_width=beam_width, beam_density=beam_density)
|
|
|
|
assert len(ner.labels) == 2
|
|
|
|
assert "MY_ORG" in ner.labels
|
|
|
|
|
|
|
|
|
2017-07-22 02:48:58 +03:00
|
|
|
def test_get_oracle_moves(tsys, doc, entity_annots):
|
2020-06-26 20:34:12 +03:00
|
|
|
example = Example.from_dict(doc, {"entities": entity_annots})
|
2020-12-13 04:08:32 +03:00
|
|
|
act_classes = tsys.get_oracle_sequence(example, _debug=False)
|
2017-07-22 02:48:58 +03:00
|
|
|
names = [tsys.get_class_name(act) for act in act_classes]
|
2018-11-27 03:09:36 +03:00
|
|
|
assert names == ["U-PERSON", "O", "O", "B-GPE", "L-GPE", "O"]
|
|
|
|
|
2017-07-22 02:48:58 +03:00
|
|
|
|
2021-06-17 10:33:00 +03:00
|
|
|
def test_negative_samples_two_word_input(tsys, vocab, neg_key):
|
|
|
|
"""Test that we don't get stuck in a two word input when we have a negative
|
|
|
|
span. This could happen if we don't have the right check on the B action.
|
|
|
|
"""
|
|
|
|
tsys.cfg["neg_key"] = neg_key
|
|
|
|
doc = Doc(vocab, words=["A", "B"])
|
|
|
|
entity_annots = [None, None]
|
2020-06-26 20:34:12 +03:00
|
|
|
example = Example.from_dict(doc, {"entities": entity_annots})
|
2021-06-17 10:33:00 +03:00
|
|
|
# These mean that the oracle sequence shouldn't have O for the first
|
|
|
|
# word, and it shouldn't analyse it as B-PERSON, L-PERSON
|
|
|
|
example.y.spans[neg_key] = [
|
|
|
|
Span(example.y, 0, 1, label="O"),
|
|
|
|
Span(example.y, 0, 2, label="PERSON"),
|
|
|
|
]
|
2020-06-26 20:34:12 +03:00
|
|
|
act_classes = tsys.get_oracle_sequence(example)
|
2017-07-22 02:48:58 +03:00
|
|
|
names = [tsys.get_class_name(act) for act in act_classes]
|
2018-11-30 19:43:08 +03:00
|
|
|
assert names
|
2021-06-17 10:33:00 +03:00
|
|
|
assert names[0] != "O"
|
|
|
|
assert names[0] != "B-PERSON"
|
|
|
|
assert names[1] != "L-PERSON"
|
2017-07-22 02:48:58 +03:00
|
|
|
|
|
|
|
|
2021-06-17 10:33:00 +03:00
|
|
|
def test_negative_samples_three_word_input(tsys, vocab, neg_key):
|
|
|
|
"""Test that we exclude a 2-word entity correctly using a negative example."""
|
|
|
|
tsys.cfg["neg_key"] = neg_key
|
|
|
|
doc = Doc(vocab, words=["A", "B", "C"])
|
|
|
|
entity_annots = [None, None, None]
|
2020-06-26 20:34:12 +03:00
|
|
|
example = Example.from_dict(doc, {"entities": entity_annots})
|
2021-06-17 10:33:00 +03:00
|
|
|
# These mean that the oracle sequence shouldn't have O for the first
|
|
|
|
# word, and it shouldn't analyse it as B-PERSON, L-PERSON
|
|
|
|
example.y.spans[neg_key] = [
|
|
|
|
Span(example.y, 0, 1, label="O"),
|
|
|
|
Span(example.y, 0, 2, label="PERSON"),
|
|
|
|
]
|
2020-06-26 20:34:12 +03:00
|
|
|
act_classes = tsys.get_oracle_sequence(example)
|
2017-07-22 02:48:58 +03:00
|
|
|
names = [tsys.get_class_name(act) for act in act_classes]
|
2018-11-30 19:43:08 +03:00
|
|
|
assert names
|
2021-06-17 10:33:00 +03:00
|
|
|
assert names[0] != "O"
|
|
|
|
assert names[1] != "B-PERSON"
|
2017-07-22 02:48:58 +03:00
|
|
|
|
|
|
|
|
2021-06-17 10:33:00 +03:00
|
|
|
def test_negative_samples_U_entity(tsys, vocab, neg_key):
|
|
|
|
"""Test that we exclude a 2-word entity correctly using a negative example."""
|
|
|
|
tsys.cfg["neg_key"] = neg_key
|
|
|
|
doc = Doc(vocab, words=["A"])
|
|
|
|
entity_annots = [None]
|
2020-06-26 20:34:12 +03:00
|
|
|
example = Example.from_dict(doc, {"entities": entity_annots})
|
2021-06-17 10:33:00 +03:00
|
|
|
# These mean that the oracle sequence shouldn't have O for the first
|
|
|
|
# word, and it shouldn't analyse it as B-PERSON, L-PERSON
|
|
|
|
example.y.spans[neg_key] = [
|
|
|
|
Span(example.y, 0, 1, label="O"),
|
|
|
|
Span(example.y, 0, 1, label="PERSON"),
|
|
|
|
]
|
2020-06-26 20:34:12 +03:00
|
|
|
act_classes = tsys.get_oracle_sequence(example)
|
2017-07-22 02:48:58 +03:00
|
|
|
names = [tsys.get_class_name(act) for act in act_classes]
|
2018-11-30 19:43:08 +03:00
|
|
|
assert names
|
2021-06-17 10:33:00 +03:00
|
|
|
assert names[0] != "O"
|
|
|
|
assert names[0] != "U-PERSON"
|
|
|
|
|
|
|
|
|
|
|
|
def test_negative_sample_key_is_in_config(vocab, entity_types):
|
|
|
|
actions = BiluoPushDown.get_actions(entity_types=entity_types)
|
|
|
|
tsys = BiluoPushDown(vocab.strings, actions, incorrect_spans_key="non_entities")
|
|
|
|
assert tsys.cfg["neg_key"] == "non_entities"
|
2018-07-25 00:38:44 +03:00
|
|
|
|
|
|
|
|
2020-06-26 20:34:12 +03:00
|
|
|
# We can't easily represent this on a Doc object. Not sure what the best solution
|
|
|
|
# would be, but I don't think it's an important use case?
|
2020-07-20 15:49:54 +03:00
|
|
|
@pytest.mark.skip(reason="No longer supported")
|
2019-08-29 15:33:39 +03:00
|
|
|
def test_oracle_moves_missing_B(en_vocab):
|
|
|
|
words = ["B", "52", "Bomber"]
|
|
|
|
biluo_tags = [None, None, "L-PRODUCT"]
|
|
|
|
|
|
|
|
doc = Doc(en_vocab, words=words)
|
2020-06-26 20:34:12 +03:00
|
|
|
example = Example.from_dict(doc, {"words": words, "entities": biluo_tags})
|
2019-08-29 15:33:39 +03:00
|
|
|
|
|
|
|
moves = BiluoPushDown(en_vocab.strings)
|
|
|
|
move_types = ("M", "B", "I", "L", "U", "O")
|
|
|
|
for tag in biluo_tags:
|
|
|
|
if tag is None:
|
|
|
|
continue
|
|
|
|
elif tag == "O":
|
|
|
|
moves.add_action(move_types.index("O"), "")
|
|
|
|
else:
|
2022-06-17 22:02:37 +03:00
|
|
|
action, label = split_bilu_label(tag)
|
2019-08-29 15:33:39 +03:00
|
|
|
moves.add_action(move_types.index("B"), label)
|
|
|
|
moves.add_action(move_types.index("I"), label)
|
|
|
|
moves.add_action(move_types.index("L"), label)
|
|
|
|
moves.add_action(move_types.index("U"), label)
|
2020-06-26 20:34:12 +03:00
|
|
|
moves.get_oracle_sequence(example)
|
2019-08-29 15:33:39 +03:00
|
|
|
|
2020-07-04 17:25:34 +03:00
|
|
|
|
2020-06-26 20:34:12 +03:00
|
|
|
# We can't easily represent this on a Doc object. Not sure what the best solution
|
|
|
|
# would be, but I don't think it's an important use case?
|
2020-07-20 15:49:54 +03:00
|
|
|
@pytest.mark.skip(reason="No longer supported")
|
2019-08-29 15:33:39 +03:00
|
|
|
def test_oracle_moves_whitespace(en_vocab):
|
2019-09-11 15:00:36 +03:00
|
|
|
words = ["production", "\n", "of", "Northrop", "\n", "Corp.", "\n", "'s", "radar"]
|
|
|
|
biluo_tags = ["O", "O", "O", "B-ORG", None, "I-ORG", "L-ORG", "O", "O"]
|
2019-08-29 15:33:39 +03:00
|
|
|
|
|
|
|
doc = Doc(en_vocab, words=words)
|
2020-06-26 20:34:12 +03:00
|
|
|
example = Example.from_dict(doc, {"entities": biluo_tags})
|
2019-08-29 15:33:39 +03:00
|
|
|
|
|
|
|
moves = BiluoPushDown(en_vocab.strings)
|
|
|
|
move_types = ("M", "B", "I", "L", "U", "O")
|
|
|
|
for tag in biluo_tags:
|
|
|
|
if tag is None:
|
|
|
|
continue
|
|
|
|
elif tag == "O":
|
|
|
|
moves.add_action(move_types.index("O"), "")
|
|
|
|
else:
|
2022-06-17 22:02:37 +03:00
|
|
|
action, label = split_bilu_label(tag)
|
2019-08-29 15:33:39 +03:00
|
|
|
moves.add_action(move_types.index(action), label)
|
2020-06-26 20:34:12 +03:00
|
|
|
moves.get_oracle_sequence(example)
|
2019-09-18 22:41:24 +03:00
|
|
|
|
|
|
|
|
2019-09-18 22:37:17 +03:00
|
|
|
def test_accept_blocked_token():
|
|
|
|
"""Test succesful blocking of tokens to be in an entity."""
|
|
|
|
# 1. test normal behaviour
|
|
|
|
nlp1 = English()
|
|
|
|
doc1 = nlp1("I live in New York")
|
2020-08-09 23:36:23 +03:00
|
|
|
config = {}
|
2020-07-22 14:42:59 +03:00
|
|
|
ner1 = nlp1.create_pipe("ner", config=config)
|
2019-09-18 22:37:17 +03:00
|
|
|
assert [token.ent_iob_ for token in doc1] == ["", "", "", "", ""]
|
|
|
|
assert [token.ent_type_ for token in doc1] == ["", "", "", "", ""]
|
|
|
|
|
|
|
|
# Add the OUT action
|
|
|
|
ner1.moves.add_action(5, "")
|
|
|
|
ner1.add_label("GPE")
|
|
|
|
# Get into the state just before "New"
|
|
|
|
state1 = ner1.moves.init_batch([doc1])[0]
|
|
|
|
ner1.moves.apply_transition(state1, "O")
|
|
|
|
ner1.moves.apply_transition(state1, "O")
|
|
|
|
ner1.moves.apply_transition(state1, "O")
|
|
|
|
# Check that B-GPE is valid.
|
|
|
|
assert ner1.moves.is_valid(state1, "B-GPE")
|
|
|
|
|
|
|
|
# 2. test blocking behaviour
|
|
|
|
nlp2 = English()
|
|
|
|
doc2 = nlp2("I live in New York")
|
2020-08-09 23:36:23 +03:00
|
|
|
config = {}
|
2020-07-22 14:42:59 +03:00
|
|
|
ner2 = nlp2.create_pipe("ner", config=config)
|
2019-09-18 22:37:17 +03:00
|
|
|
|
|
|
|
# set "New York" to a blocked entity
|
2020-09-21 16:54:05 +03:00
|
|
|
doc2.set_ents([], blocked=[doc2[3:5]], default="unmodified")
|
2019-09-18 22:37:17 +03:00
|
|
|
assert [token.ent_iob_ for token in doc2] == ["", "", "", "B", "B"]
|
|
|
|
assert [token.ent_type_ for token in doc2] == ["", "", "", "", ""]
|
|
|
|
|
|
|
|
# Check that B-GPE is now invalid.
|
|
|
|
ner2.moves.add_action(4, "")
|
|
|
|
ner2.moves.add_action(5, "")
|
|
|
|
ner2.add_label("GPE")
|
|
|
|
state2 = ner2.moves.init_batch([doc2])[0]
|
|
|
|
ner2.moves.apply_transition(state2, "O")
|
|
|
|
ner2.moves.apply_transition(state2, "O")
|
|
|
|
ner2.moves.apply_transition(state2, "O")
|
|
|
|
# we can only use U- for "New"
|
|
|
|
assert not ner2.moves.is_valid(state2, "B-GPE")
|
|
|
|
assert ner2.moves.is_valid(state2, "U-")
|
|
|
|
ner2.moves.apply_transition(state2, "U-")
|
|
|
|
# we can only use U- for "York"
|
|
|
|
assert not ner2.moves.is_valid(state2, "B-GPE")
|
|
|
|
assert ner2.moves.is_valid(state2, "U-")
|
|
|
|
|
|
|
|
|
2020-05-13 23:08:50 +03:00
|
|
|
def test_train_empty():
|
|
|
|
"""Test that training an empty text does not throw errors."""
|
|
|
|
train_data = [
|
|
|
|
("Who is Shaka Khan?", {"entities": [(7, 17, "PERSON")]}),
|
|
|
|
("", {"entities": []}),
|
|
|
|
]
|
|
|
|
|
|
|
|
nlp = English()
|
2020-07-06 14:02:36 +03:00
|
|
|
train_examples = []
|
|
|
|
for t in train_data:
|
|
|
|
train_examples.append(Example.from_dict(nlp.make_doc(t[0]), t[1]))
|
2020-07-22 14:42:59 +03:00
|
|
|
ner = nlp.add_pipe("ner", last=True)
|
2020-05-13 23:08:50 +03:00
|
|
|
ner.add_label("PERSON")
|
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
|
|
|
nlp.initialize(get_examples=lambda: train_examples)
|
2020-05-13 23:08:50 +03:00
|
|
|
for itn in range(2):
|
|
|
|
losses = {}
|
2020-08-04 16:09:37 +03:00
|
|
|
batches = util.minibatch(train_examples, size=8)
|
2020-05-13 23:08:50 +03:00
|
|
|
for batch in batches:
|
2020-07-06 14:02:36 +03:00
|
|
|
nlp.update(batch, losses=losses)
|
2020-05-13 23:08:50 +03:00
|
|
|
|
|
|
|
|
2021-06-17 10:33:00 +03:00
|
|
|
def test_train_negative_deprecated():
|
|
|
|
"""Test that the deprecated negative entity format raises a custom error."""
|
|
|
|
train_data = [
|
|
|
|
("Who is Shaka Khan?", {"entities": [(7, 17, "!PERSON")]}),
|
|
|
|
]
|
|
|
|
|
|
|
|
nlp = English()
|
|
|
|
train_examples = []
|
|
|
|
for t in train_data:
|
|
|
|
train_examples.append(Example.from_dict(nlp.make_doc(t[0]), t[1]))
|
|
|
|
ner = nlp.add_pipe("ner", last=True)
|
|
|
|
ner.add_label("PERSON")
|
|
|
|
nlp.initialize()
|
|
|
|
for itn in range(2):
|
|
|
|
losses = {}
|
|
|
|
batches = util.minibatch(train_examples, size=8)
|
|
|
|
for batch in batches:
|
|
|
|
with pytest.raises(ValueError):
|
|
|
|
nlp.update(batch, losses=losses)
|
|
|
|
|
|
|
|
|
2019-09-18 22:37:17 +03:00
|
|
|
def test_overwrite_token():
|
|
|
|
nlp = English()
|
2020-07-22 14:42:59 +03:00
|
|
|
nlp.add_pipe("ner")
|
2020-09-28 22:35:09 +03:00
|
|
|
nlp.initialize()
|
2019-09-18 22:37:17 +03:00
|
|
|
# The untrained NER will predict O for each token
|
|
|
|
doc = nlp("I live in New York")
|
|
|
|
assert [token.ent_iob_ for token in doc] == ["O", "O", "O", "O", "O"]
|
|
|
|
assert [token.ent_type_ for token in doc] == ["", "", "", "", ""]
|
|
|
|
# Check that a new ner can overwrite O
|
2020-08-09 23:36:23 +03:00
|
|
|
config = {}
|
2020-07-22 14:42:59 +03:00
|
|
|
ner2 = nlp.create_pipe("ner", config=config)
|
2019-09-18 22:37:17 +03:00
|
|
|
ner2.moves.add_action(5, "")
|
|
|
|
ner2.add_label("GPE")
|
|
|
|
state = ner2.moves.init_batch([doc])[0]
|
|
|
|
assert ner2.moves.is_valid(state, "B-GPE")
|
|
|
|
assert ner2.moves.is_valid(state, "U-GPE")
|
|
|
|
ner2.moves.apply_transition(state, "B-GPE")
|
|
|
|
assert ner2.moves.is_valid(state, "I-GPE")
|
|
|
|
assert ner2.moves.is_valid(state, "L-GPE")
|
|
|
|
|
|
|
|
|
2020-02-27 20:42:27 +03:00
|
|
|
def test_empty_ner():
|
|
|
|
nlp = English()
|
2020-07-22 14:42:59 +03:00
|
|
|
ner = nlp.add_pipe("ner")
|
2020-02-27 20:42:27 +03:00
|
|
|
ner.add_label("MY_LABEL")
|
2020-09-28 22:35:09 +03:00
|
|
|
nlp.initialize()
|
2020-02-27 20:42:27 +03:00
|
|
|
doc = nlp("John is watching the news about Croatia's elections")
|
|
|
|
# if this goes wrong, the initialization of the parser's upper layer is probably broken
|
2020-02-28 13:57:41 +03:00
|
|
|
result = ["O", "O", "O", "O", "O", "O", "O", "O", "O"]
|
|
|
|
assert [token.ent_iob_ for token in doc] == result
|
2020-02-27 20:42:27 +03:00
|
|
|
|
|
|
|
|
2019-09-18 22:37:17 +03:00
|
|
|
def test_ruler_before_ner():
|
2021-07-02 10:48:26 +03:00
|
|
|
"""Test that an NER works after an entity_ruler: the second can add annotations"""
|
2019-09-18 22:37:17 +03:00
|
|
|
nlp = English()
|
|
|
|
|
|
|
|
# 1 : Entity Ruler - should set "this" to B and everything else to empty
|
|
|
|
patterns = [{"label": "THING", "pattern": "This"}]
|
2020-07-22 14:42:59 +03:00
|
|
|
ruler = nlp.add_pipe("entity_ruler")
|
2019-09-18 22:37:17 +03:00
|
|
|
|
|
|
|
# 2: untrained NER - should set everything else to O
|
2020-07-22 14:42:59 +03:00
|
|
|
untrained_ner = nlp.add_pipe("ner")
|
2019-09-18 22:37:17 +03:00
|
|
|
untrained_ner.add_label("MY_LABEL")
|
2020-09-28 22:35:09 +03:00
|
|
|
nlp.initialize()
|
2021-06-03 10:05:26 +03:00
|
|
|
ruler.add_patterns(patterns)
|
2019-09-18 22:37:17 +03:00
|
|
|
doc = nlp("This is Antti Korhonen speaking in Finland")
|
|
|
|
expected_iobs = ["B", "O", "O", "O", "O", "O", "O"]
|
|
|
|
expected_types = ["THING", "", "", "", "", "", ""]
|
|
|
|
assert [token.ent_iob_ for token in doc] == expected_iobs
|
|
|
|
assert [token.ent_type_ for token in doc] == expected_types
|
|
|
|
|
|
|
|
|
2021-06-17 10:33:00 +03:00
|
|
|
def test_ner_constructor(en_vocab):
|
|
|
|
config = {
|
|
|
|
"update_with_oracle_cut_size": 100,
|
|
|
|
}
|
|
|
|
cfg = {"model": DEFAULT_NER_MODEL}
|
|
|
|
model = registry.resolve(cfg, validate=True)["model"]
|
2021-07-18 08:44:56 +03:00
|
|
|
EntityRecognizer(en_vocab, model, **config)
|
|
|
|
EntityRecognizer(en_vocab, model)
|
2021-06-17 10:33:00 +03:00
|
|
|
|
|
|
|
|
2019-09-18 22:37:17 +03:00
|
|
|
def test_ner_before_ruler():
|
2021-07-02 10:48:26 +03:00
|
|
|
"""Test that an entity_ruler works after an NER: the second can overwrite O annotations"""
|
2019-09-18 22:37:17 +03:00
|
|
|
nlp = English()
|
|
|
|
|
|
|
|
# 1: untrained NER - should set everything to O
|
2020-07-22 14:42:59 +03:00
|
|
|
untrained_ner = nlp.add_pipe("ner", name="uner")
|
2019-09-18 22:37:17 +03:00
|
|
|
untrained_ner.add_label("MY_LABEL")
|
2020-09-28 22:35:09 +03:00
|
|
|
nlp.initialize()
|
2019-09-18 22:37:17 +03:00
|
|
|
|
|
|
|
# 2 : Entity Ruler - should set "this" to B and keep everything else O
|
|
|
|
patterns = [{"label": "THING", "pattern": "This"}]
|
2020-07-22 14:42:59 +03:00
|
|
|
ruler = nlp.add_pipe("entity_ruler")
|
2019-09-18 22:37:17 +03:00
|
|
|
ruler.add_patterns(patterns)
|
|
|
|
|
|
|
|
doc = nlp("This is Antti Korhonen speaking in Finland")
|
|
|
|
expected_iobs = ["B", "O", "O", "O", "O", "O", "O"]
|
|
|
|
expected_types = ["THING", "", "", "", "", "", ""]
|
|
|
|
assert [token.ent_iob_ for token in doc] == expected_iobs
|
|
|
|
assert [token.ent_type_ for token in doc] == expected_types
|
|
|
|
|
|
|
|
|
|
|
|
def test_block_ner():
|
2021-07-02 10:48:26 +03:00
|
|
|
"""Test functionality for blocking tokens so they can't be in a named entity"""
|
2019-09-18 22:37:17 +03:00
|
|
|
# block "Antti L Korhonen" from being a named entity
|
|
|
|
nlp = English()
|
2020-07-22 14:42:59 +03:00
|
|
|
nlp.add_pipe("blocker", config={"start": 2, "end": 5})
|
|
|
|
untrained_ner = nlp.add_pipe("ner")
|
2019-09-18 22:37:17 +03:00
|
|
|
untrained_ner.add_label("MY_LABEL")
|
2020-09-28 22:35:09 +03:00
|
|
|
nlp.initialize()
|
2019-09-18 22:37:17 +03:00
|
|
|
doc = nlp("This is Antti L Korhonen speaking in Finland")
|
|
|
|
expected_iobs = ["O", "O", "B", "B", "B", "O", "O", "O"]
|
|
|
|
expected_types = ["", "", "", "", "", "", "", ""]
|
|
|
|
assert [token.ent_iob_ for token in doc] == expected_iobs
|
|
|
|
assert [token.ent_type_ for token in doc] == expected_types
|
|
|
|
|
|
|
|
|
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
|
|
|
def test_overfitting_IO():
|
|
|
|
fix_random_seed(1)
|
2021-01-07 08:28:27 +03:00
|
|
|
# Simple test to try and quickly overfit the NER component
|
2019-11-19 17:03:14 +03:00
|
|
|
nlp = English()
|
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
|
|
|
ner = nlp.add_pipe("ner", config={"model": {}})
|
2020-07-06 14:02:36 +03:00
|
|
|
train_examples = []
|
|
|
|
for text, annotations in TRAIN_DATA:
|
|
|
|
train_examples.append(Example.from_dict(nlp.make_doc(text), annotations))
|
2020-01-29 19:06:46 +03:00
|
|
|
for ent in annotations.get("entities"):
|
|
|
|
ner.add_label(ent[2])
|
2020-09-28 22:35:09 +03:00
|
|
|
optimizer = nlp.initialize()
|
2020-01-29 19:06:46 +03:00
|
|
|
|
|
|
|
for i in range(50):
|
|
|
|
losses = {}
|
2020-07-06 14:02:36 +03:00
|
|
|
nlp.update(train_examples, sgd=optimizer, losses=losses)
|
2020-01-29 19:06:46 +03:00
|
|
|
assert losses["ner"] < 0.00001
|
|
|
|
|
|
|
|
# test the trained model
|
|
|
|
test_text = "I like London."
|
|
|
|
doc = nlp(test_text)
|
|
|
|
ents = doc.ents
|
|
|
|
assert len(ents) == 1
|
|
|
|
assert ents[0].text == "London"
|
|
|
|
assert ents[0].label_ == "LOC"
|
|
|
|
|
2020-02-27 20:42:27 +03:00
|
|
|
# Also test the results are still the same after IO
|
|
|
|
with make_tempdir() as tmp_dir:
|
|
|
|
nlp.to_disk(tmp_dir)
|
|
|
|
nlp2 = util.load_model_from_path(tmp_dir)
|
|
|
|
doc2 = nlp2(test_text)
|
|
|
|
ents2 = doc2.ents
|
|
|
|
assert len(ents2) == 1
|
|
|
|
assert ents2[0].text == "London"
|
|
|
|
assert ents2[0].label_ == "LOC"
|
2020-12-18 13:56:57 +03:00
|
|
|
# Ensure that the predictions are still the same, even after adding a new label
|
|
|
|
ner2 = nlp2.get_pipe("ner")
|
|
|
|
ner2.add_label("RANDOM_NEW_LABEL")
|
|
|
|
doc3 = nlp2(test_text)
|
|
|
|
ents3 = doc3.ents
|
|
|
|
assert len(ents3) == 1
|
|
|
|
assert ents3[0].text == "London"
|
|
|
|
assert ents3[0].label_ == "LOC"
|
2019-11-19 17:03:14 +03:00
|
|
|
|
2020-10-13 22:07:13 +03:00
|
|
|
# Make sure that running pipe twice, or comparing to call, always amounts to the same predictions
|
|
|
|
texts = [
|
|
|
|
"Just a sentence.",
|
|
|
|
"Then one more sentence about London.",
|
|
|
|
"Here is another one.",
|
|
|
|
"I like London.",
|
|
|
|
]
|
|
|
|
batch_deps_1 = [doc.to_array([ENT_IOB]) for doc in nlp.pipe(texts)]
|
|
|
|
batch_deps_2 = [doc.to_array([ENT_IOB]) for doc in nlp.pipe(texts)]
|
|
|
|
no_batch_deps = [doc.to_array([ENT_IOB]) for doc in [nlp(text) for text in texts]]
|
|
|
|
assert_equal(batch_deps_1, batch_deps_2)
|
|
|
|
assert_equal(batch_deps_1, no_batch_deps)
|
|
|
|
|
2021-05-06 11:49:55 +03:00
|
|
|
# test that kb_id is preserved
|
|
|
|
test_text = "I like London and London."
|
|
|
|
doc = nlp.make_doc(test_text)
|
|
|
|
doc.ents = [Span(doc, 2, 3, label="LOC", kb_id=1234)]
|
|
|
|
ents = doc.ents
|
|
|
|
assert len(ents) == 1
|
|
|
|
assert ents[0].text == "London"
|
|
|
|
assert ents[0].label_ == "LOC"
|
|
|
|
assert ents[0].kb_id == 1234
|
|
|
|
doc = nlp.get_pipe("ner")(doc)
|
|
|
|
ents = doc.ents
|
|
|
|
assert len(ents) == 2
|
|
|
|
assert ents[0].text == "London"
|
|
|
|
assert ents[0].label_ == "LOC"
|
|
|
|
assert ents[0].kb_id == 1234
|
|
|
|
# ent added by ner has kb_id == 0
|
|
|
|
assert ents[1].text == "London"
|
|
|
|
assert ents[1].label_ == "LOC"
|
|
|
|
assert ents[1].kb_id == 0
|
|
|
|
|
2019-11-19 17:03:14 +03:00
|
|
|
|
2023-01-16 12:25:53 +03:00
|
|
|
def test_is_distillable():
|
|
|
|
nlp = English()
|
|
|
|
ner = nlp.add_pipe("ner")
|
|
|
|
assert ner.is_distillable
|
|
|
|
|
|
|
|
|
|
|
|
def test_distill():
|
|
|
|
teacher = English()
|
|
|
|
teacher_ner = teacher.add_pipe("ner")
|
|
|
|
train_examples = []
|
|
|
|
for text, annotations in TRAIN_DATA:
|
|
|
|
train_examples.append(Example.from_dict(teacher.make_doc(text), annotations))
|
|
|
|
for ent in annotations.get("entities"):
|
|
|
|
teacher_ner.add_label(ent[2])
|
|
|
|
|
|
|
|
optimizer = teacher.initialize(get_examples=lambda: train_examples)
|
|
|
|
|
|
|
|
for i in range(50):
|
|
|
|
losses = {}
|
|
|
|
teacher.update(train_examples, sgd=optimizer, losses=losses)
|
|
|
|
assert losses["ner"] < 0.00001
|
|
|
|
|
|
|
|
student = English()
|
|
|
|
student_ner = student.add_pipe("ner")
|
|
|
|
student_ner.initialize(
|
|
|
|
get_examples=lambda: train_examples, labels=teacher_ner.label_data
|
|
|
|
)
|
|
|
|
|
|
|
|
distill_examples = [
|
|
|
|
Example.from_dict(teacher.make_doc(t[0]), {}) for t in TRAIN_DATA
|
|
|
|
]
|
|
|
|
|
|
|
|
for i in range(100):
|
|
|
|
losses = {}
|
|
|
|
student_ner.distill(teacher_ner, distill_examples, sgd=optimizer, losses=losses)
|
|
|
|
assert losses["ner"] < 0.0001
|
|
|
|
|
|
|
|
# test the trained model
|
|
|
|
test_text = "I like London."
|
|
|
|
doc = student(test_text)
|
|
|
|
ents = doc.ents
|
|
|
|
assert len(ents) == 1
|
|
|
|
assert ents[0].text == "London"
|
|
|
|
assert ents[0].label_ == "LOC"
|
|
|
|
|
|
|
|
|
2021-01-06 14:02:32 +03:00
|
|
|
def test_beam_ner_scores():
|
|
|
|
# Test that we can get confidence values out of the beam_ner pipe
|
|
|
|
beam_width = 16
|
|
|
|
beam_density = 0.0001
|
|
|
|
nlp = English()
|
|
|
|
config = {
|
|
|
|
"beam_width": beam_width,
|
|
|
|
"beam_density": beam_density,
|
|
|
|
}
|
|
|
|
ner = nlp.add_pipe("beam_ner", config=config)
|
|
|
|
train_examples = []
|
|
|
|
for text, annotations in TRAIN_DATA:
|
|
|
|
train_examples.append(Example.from_dict(nlp.make_doc(text), annotations))
|
|
|
|
for ent in annotations.get("entities"):
|
|
|
|
ner.add_label(ent[2])
|
|
|
|
optimizer = nlp.initialize()
|
|
|
|
|
|
|
|
# update once
|
|
|
|
losses = {}
|
|
|
|
nlp.update(train_examples, sgd=optimizer, losses=losses)
|
|
|
|
|
|
|
|
# test the scores from the beam
|
|
|
|
test_text = "I like London."
|
|
|
|
doc = nlp.make_doc(test_text)
|
|
|
|
docs = [doc]
|
|
|
|
beams = ner.predict(docs)
|
|
|
|
entity_scores = ner.scored_ents(beams)[0]
|
|
|
|
|
|
|
|
for j in range(len(doc)):
|
|
|
|
for label in ner.labels:
|
2021-01-15 03:57:36 +03:00
|
|
|
score = entity_scores[(j, j + 1, label)]
|
2021-01-06 14:02:32 +03:00
|
|
|
eps = 0.00001
|
|
|
|
assert 0 - eps <= score <= 1 + eps
|
|
|
|
|
|
|
|
|
2021-06-17 10:33:00 +03:00
|
|
|
def test_beam_overfitting_IO(neg_key):
|
2021-01-06 14:02:32 +03:00
|
|
|
# Simple test to try and quickly overfit the Beam NER component
|
|
|
|
nlp = English()
|
|
|
|
beam_width = 16
|
|
|
|
beam_density = 0.0001
|
|
|
|
config = {
|
|
|
|
"beam_width": beam_width,
|
|
|
|
"beam_density": beam_density,
|
2021-06-17 10:33:00 +03:00
|
|
|
"incorrect_spans_key": neg_key,
|
2021-01-06 14:02:32 +03:00
|
|
|
}
|
|
|
|
ner = nlp.add_pipe("beam_ner", config=config)
|
|
|
|
train_examples = []
|
|
|
|
for text, annotations in TRAIN_DATA:
|
|
|
|
train_examples.append(Example.from_dict(nlp.make_doc(text), annotations))
|
|
|
|
for ent in annotations.get("entities"):
|
|
|
|
ner.add_label(ent[2])
|
|
|
|
optimizer = nlp.initialize()
|
|
|
|
|
|
|
|
# run overfitting
|
|
|
|
for i in range(50):
|
|
|
|
losses = {}
|
|
|
|
nlp.update(train_examples, sgd=optimizer, losses=losses)
|
|
|
|
assert losses["beam_ner"] < 0.0001
|
|
|
|
|
|
|
|
# test the scores from the beam
|
2021-06-17 10:33:00 +03:00
|
|
|
test_text = "I like London"
|
2021-01-06 14:02:32 +03:00
|
|
|
docs = [nlp.make_doc(test_text)]
|
|
|
|
beams = ner.predict(docs)
|
|
|
|
entity_scores = ner.scored_ents(beams)[0]
|
|
|
|
assert entity_scores[(2, 3, "LOC")] == 1.0
|
|
|
|
assert entity_scores[(2, 3, "PERSON")] == 0.0
|
2021-06-17 10:33:00 +03:00
|
|
|
assert len(nlp(test_text).ents) == 1
|
2021-01-06 14:02:32 +03:00
|
|
|
|
|
|
|
# Also test the results are still the same after IO
|
|
|
|
with make_tempdir() as tmp_dir:
|
|
|
|
nlp.to_disk(tmp_dir)
|
|
|
|
nlp2 = util.load_model_from_path(tmp_dir)
|
2021-01-07 08:28:27 +03:00
|
|
|
docs2 = [nlp2.make_doc(test_text)]
|
2021-01-06 14:02:32 +03:00
|
|
|
ner2 = nlp2.get_pipe("beam_ner")
|
|
|
|
beams2 = ner2.predict(docs2)
|
|
|
|
entity_scores2 = ner2.scored_ents(beams2)[0]
|
|
|
|
assert entity_scores2[(2, 3, "LOC")] == 1.0
|
|
|
|
assert entity_scores2[(2, 3, "PERSON")] == 0.0
|
|
|
|
|
2021-06-17 10:33:00 +03:00
|
|
|
# Try to unlearn the entity by using negative annotations
|
|
|
|
neg_doc = nlp.make_doc(test_text)
|
|
|
|
neg_ex = Example(neg_doc, neg_doc)
|
|
|
|
neg_ex.reference.spans[neg_key] = [Span(neg_doc, 2, 3, "LOC")]
|
|
|
|
neg_train_examples = [neg_ex]
|
|
|
|
|
|
|
|
for i in range(20):
|
|
|
|
losses = {}
|
|
|
|
nlp.update(neg_train_examples, sgd=optimizer, losses=losses)
|
|
|
|
|
|
|
|
# test the "untrained" model
|
|
|
|
assert len(nlp(test_text).ents) == 0
|
|
|
|
|
|
|
|
|
|
|
|
def test_neg_annotation(neg_key):
|
|
|
|
"""Check that the NER update works with a negative annotation that is a different label of the correct one,
|
|
|
|
or partly overlapping, etc"""
|
|
|
|
nlp = English()
|
|
|
|
beam_width = 16
|
|
|
|
beam_density = 0.0001
|
|
|
|
config = {
|
|
|
|
"beam_width": beam_width,
|
|
|
|
"beam_density": beam_density,
|
|
|
|
"incorrect_spans_key": neg_key,
|
|
|
|
}
|
|
|
|
ner = nlp.add_pipe("beam_ner", config=config)
|
|
|
|
train_text = "Who is Shaka Khan?"
|
|
|
|
neg_doc = nlp.make_doc(train_text)
|
|
|
|
ner.add_label("PERSON")
|
|
|
|
ner.add_label("ORG")
|
|
|
|
example = Example.from_dict(neg_doc, {"entities": [(7, 17, "PERSON")]})
|
2021-06-28 12:48:00 +03:00
|
|
|
example.reference.spans[neg_key] = [
|
|
|
|
Span(neg_doc, 2, 4, "ORG"),
|
|
|
|
Span(neg_doc, 2, 3, "PERSON"),
|
|
|
|
Span(neg_doc, 1, 4, "PERSON"),
|
|
|
|
]
|
2021-06-17 10:33:00 +03:00
|
|
|
|
|
|
|
optimizer = nlp.initialize()
|
|
|
|
for i in range(2):
|
|
|
|
losses = {}
|
|
|
|
nlp.update([example], sgd=optimizer, losses=losses)
|
|
|
|
|
|
|
|
|
|
|
|
def test_neg_annotation_conflict(neg_key):
|
|
|
|
# Check that NER raises for a negative annotation that is THE SAME as a correct one
|
|
|
|
nlp = English()
|
|
|
|
beam_width = 16
|
|
|
|
beam_density = 0.0001
|
|
|
|
config = {
|
|
|
|
"beam_width": beam_width,
|
|
|
|
"beam_density": beam_density,
|
|
|
|
"incorrect_spans_key": neg_key,
|
|
|
|
}
|
|
|
|
ner = nlp.add_pipe("beam_ner", config=config)
|
|
|
|
train_text = "Who is Shaka Khan?"
|
|
|
|
neg_doc = nlp.make_doc(train_text)
|
|
|
|
ner.add_label("PERSON")
|
|
|
|
ner.add_label("LOC")
|
|
|
|
example = Example.from_dict(neg_doc, {"entities": [(7, 17, "PERSON")]})
|
|
|
|
example.reference.spans[neg_key] = [Span(neg_doc, 2, 4, "PERSON")]
|
|
|
|
assert len(example.reference.ents) == 1
|
|
|
|
assert example.reference.ents[0].text == "Shaka Khan"
|
|
|
|
assert example.reference.ents[0].label_ == "PERSON"
|
|
|
|
assert len(example.reference.spans[neg_key]) == 1
|
|
|
|
assert example.reference.spans[neg_key][0].text == "Shaka Khan"
|
|
|
|
assert example.reference.spans[neg_key][0].label_ == "PERSON"
|
|
|
|
|
|
|
|
optimizer = nlp.initialize()
|
|
|
|
for i in range(2):
|
|
|
|
losses = {}
|
|
|
|
with pytest.raises(ValueError):
|
|
|
|
nlp.update([example], sgd=optimizer, losses=losses)
|
|
|
|
|
|
|
|
|
|
|
|
def test_beam_valid_parse(neg_key):
|
|
|
|
"""Regression test for previously flakey behaviour"""
|
|
|
|
nlp = English()
|
|
|
|
beam_width = 16
|
|
|
|
beam_density = 0.0001
|
|
|
|
config = {
|
|
|
|
"beam_width": beam_width,
|
|
|
|
"beam_density": beam_density,
|
|
|
|
"incorrect_spans_key": neg_key,
|
|
|
|
}
|
|
|
|
nlp.add_pipe("beam_ner", config=config)
|
|
|
|
# fmt: off
|
|
|
|
tokens = ['FEDERAL', 'NATIONAL', 'MORTGAGE', 'ASSOCIATION', '(', 'Fannie', 'Mae', '):', 'Posted', 'yields', 'on', '30', 'year', 'mortgage', 'commitments', 'for', 'delivery', 'within', '30', 'days', '(', 'priced', 'at', 'par', ')', '9.75', '%', ',', 'standard', 'conventional', 'fixed', '-', 'rate', 'mortgages', ';', '8.70', '%', ',', '6/2', 'rate', 'capped', 'one', '-', 'year', 'adjustable', 'rate', 'mortgages', '.', 'Source', ':', 'Telerate', 'Systems', 'Inc.']
|
|
|
|
iob = ['B-ORG', 'I-ORG', 'I-ORG', 'L-ORG', 'O', 'B-ORG', 'L-ORG', 'O', 'O', 'O', 'O', 'B-DATE', 'L-DATE', 'O', 'O', 'O', 'O', 'O', 'B-DATE', 'L-DATE', 'O', 'O', 'O', 'O', 'O', 'B-PERCENT', 'L-PERCENT', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'B-PERCENT', 'L-PERCENT', 'O', 'U-CARDINAL', 'O', 'O', 'B-DATE', 'I-DATE', 'L-DATE', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O']
|
|
|
|
# fmt: on
|
|
|
|
|
|
|
|
doc = Doc(nlp.vocab, words=tokens)
|
|
|
|
example = Example.from_dict(doc, {"ner": iob})
|
|
|
|
neg_span = Span(doc, 50, 53, "ORG")
|
|
|
|
example.reference.spans[neg_key] = [neg_span]
|
|
|
|
|
|
|
|
optimizer = nlp.initialize()
|
|
|
|
|
|
|
|
for i in range(5):
|
|
|
|
losses = {}
|
|
|
|
nlp.update([example], sgd=optimizer, losses=losses)
|
|
|
|
assert "beam_ner" in losses
|
|
|
|
|
2021-01-06 14:02:32 +03:00
|
|
|
|
2020-08-14 16:00:52 +03:00
|
|
|
def test_ner_warns_no_lookups(caplog):
|
2020-07-25 12:51:30 +03:00
|
|
|
nlp = English()
|
|
|
|
assert nlp.lang in util.LEXEME_NORM_LANGS
|
2020-06-15 15:56:04 +03:00
|
|
|
nlp.vocab.lookups = Lookups()
|
|
|
|
assert not len(nlp.vocab.lookups)
|
2020-07-22 14:42:59 +03:00
|
|
|
nlp.add_pipe("ner")
|
2020-08-14 16:00:52 +03:00
|
|
|
with caplog.at_level(logging.DEBUG):
|
2020-09-28 22:35:09 +03:00
|
|
|
nlp.initialize()
|
2020-08-14 16:00:52 +03:00
|
|
|
assert "W033" in caplog.text
|
|
|
|
caplog.clear()
|
2020-06-15 15:56:04 +03:00
|
|
|
nlp.vocab.lookups.add_table("lexeme_norm")
|
|
|
|
nlp.vocab.lookups.get_table("lexeme_norm")["a"] = "A"
|
2020-08-14 16:00:52 +03:00
|
|
|
with caplog.at_level(logging.DEBUG):
|
2020-09-28 22:35:09 +03:00
|
|
|
nlp.initialize()
|
2020-08-14 16:00:52 +03:00
|
|
|
assert "W033" not in caplog.text
|
2020-06-15 15:56:04 +03:00
|
|
|
|
|
|
|
|
2020-07-22 14:42:59 +03:00
|
|
|
@Language.factory("blocker")
|
2020-07-12 15:03:23 +03:00
|
|
|
class BlockerComponent1:
|
2020-07-22 14:42:59 +03:00
|
|
|
def __init__(self, nlp, start, end, name="my_blocker"):
|
2019-09-18 22:37:17 +03:00
|
|
|
self.start = start
|
|
|
|
self.end = end
|
2020-07-22 14:42:59 +03:00
|
|
|
self.name = name
|
2019-09-18 22:37:17 +03:00
|
|
|
|
|
|
|
def __call__(self, doc):
|
2020-09-28 22:35:09 +03:00
|
|
|
doc.set_ents([], blocked=[doc[self.start : self.end]], default="unmodified")
|
2019-09-18 22:37:17 +03:00
|
|
|
return doc
|