mirror of
https://github.com/explosion/spaCy.git
synced 2025-11-11 13:25:43 +03:00
In order to support Python 3.13, we had to migrate to Cython 3.0. This caused some tricky interaction with our Pydantic usage, because Cython 3 uses the from __future__ import annotations semantics, which causes type annotations to be saved as strings. The end result is that we can't have Language.factory decorated functions in Cython modules anymore, as the Language.factory decorator expects to inspect the signature of the functions and build a Pydantic model. If the function is implemented in Cython, an error is raised because the type is not resolved. To address this I've moved the factory functions into a new module, spacy.pipeline.factories. I've added __getattr__ importlib hooks to the previous locations, in case anyone was importing these functions directly. The change should have no backwards compatibility implications. Along the way I've also refactored the registration of functions for the config. Previously these ran as import-time side-effects, using the registry decorator. I've created instead a new module spacy.registrations. When the registry is accessed it calls a function ensure_populated(), which cases the registrations to occur. I've made a similar change to the Language.factory registrations in the new spacy.pipeline.factories module. I want to remove these import-time side-effects so that we can speed up the loading time of the library, which can be especially painful on the CLI. I also find that I'm often working to track down the implementations of functions referenced by strings in the config. Having the registrations all happen in one place will make this easier. With these changes I've fortunately avoided the need to migrate to Pydantic v2 properly --- we're still using the v1 compatibility shim. We might not be able to hold out forever though: Pydantic (reasonably) aren't actively supporting the v1 shims. I put a lot of work into v2 migration when investigating the 3.13 support, and it's definitely challenging. In any case, it's a relief that we don't have to do the v2 migration at the same time as the Cython 3.0/Python 3.13 support.
127 lines
4.0 KiB
Python
127 lines
4.0 KiB
Python
from typing import Callable, Dict, Iterable
|
|
|
|
import pytest
|
|
from thinc.api import Config, fix_random_seed
|
|
|
|
from spacy import Language
|
|
from spacy.schemas import ConfigSchemaTraining
|
|
from spacy.training import Example
|
|
from spacy.util import load_model_from_config, registry, resolve_dot_names
|
|
|
|
|
|
def test_readers():
|
|
config_string = """
|
|
[training]
|
|
|
|
[corpora]
|
|
@readers = "myreader.v1"
|
|
|
|
[nlp]
|
|
lang = "en"
|
|
pipeline = ["tok2vec", "textcat"]
|
|
|
|
[components]
|
|
|
|
[components.tok2vec]
|
|
factory = "tok2vec"
|
|
|
|
[components.textcat]
|
|
factory = "textcat"
|
|
"""
|
|
|
|
@registry.readers("myreader.v1")
|
|
def myreader() -> Dict[str, Callable[[Language], Iterable[Example]]]:
|
|
annots = {"cats": {"POS": 1.0, "NEG": 0.0}}
|
|
|
|
def reader(nlp: Language):
|
|
doc = nlp.make_doc(f"This is an example")
|
|
return [Example.from_dict(doc, annots)]
|
|
|
|
return {"train": reader, "dev": reader, "extra": reader, "something": reader}
|
|
|
|
config = Config().from_str(config_string)
|
|
nlp = load_model_from_config(config, auto_fill=True)
|
|
T = registry.resolve(
|
|
nlp.config.interpolate()["training"], schema=ConfigSchemaTraining
|
|
)
|
|
dot_names = [T["train_corpus"], T["dev_corpus"]]
|
|
train_corpus, dev_corpus = resolve_dot_names(nlp.config, dot_names)
|
|
assert isinstance(train_corpus, Callable)
|
|
optimizer = T["optimizer"]
|
|
# simulate a training loop
|
|
nlp.initialize(lambda: train_corpus(nlp), sgd=optimizer)
|
|
for example in train_corpus(nlp):
|
|
nlp.update([example], sgd=optimizer)
|
|
scores = nlp.evaluate(list(dev_corpus(nlp)))
|
|
assert scores["cats_macro_auc"] == 0.0
|
|
# ensure the pipeline runs
|
|
doc = nlp("Quick test")
|
|
assert doc.cats
|
|
corpora = {"corpora": nlp.config.interpolate()["corpora"]}
|
|
extra_corpus = registry.resolve(corpora)["corpora"]["extra"]
|
|
assert isinstance(extra_corpus, Callable)
|
|
|
|
|
|
@pytest.mark.slow
|
|
@pytest.mark.parametrize(
|
|
"reader,additional_config",
|
|
[
|
|
("ml_datasets.imdb_sentiment.v1", {"train_limit": 10, "dev_limit": 10}),
|
|
("ml_datasets.dbpedia.v1", {"train_limit": 10, "dev_limit": 10}),
|
|
("ml_datasets.cmu_movies.v1", {"limit": 10, "freq_cutoff": 200, "split": 0.8}),
|
|
],
|
|
)
|
|
def test_cat_readers(reader, additional_config):
|
|
nlp_config_string = """
|
|
[training]
|
|
seed = 0
|
|
|
|
[training.score_weights]
|
|
cats_macro_auc = 1.0
|
|
|
|
[corpora]
|
|
@readers = "PLACEHOLDER"
|
|
|
|
[nlp]
|
|
lang = "en"
|
|
pipeline = ["tok2vec", "textcat_multilabel"]
|
|
|
|
[components]
|
|
|
|
[components.tok2vec]
|
|
factory = "tok2vec"
|
|
|
|
[components.textcat_multilabel]
|
|
factory = "textcat_multilabel"
|
|
"""
|
|
config = Config().from_str(nlp_config_string)
|
|
fix_random_seed(config["training"]["seed"])
|
|
config["corpora"]["@readers"] = reader
|
|
config["corpora"].update(additional_config)
|
|
nlp = load_model_from_config(config, auto_fill=True)
|
|
T = registry.resolve(nlp.config["training"], schema=ConfigSchemaTraining)
|
|
dot_names = [T["train_corpus"], T["dev_corpus"]]
|
|
print("T", T)
|
|
print("dot names", dot_names)
|
|
train_corpus, dev_corpus = resolve_dot_names(nlp.config, dot_names)
|
|
data = list(train_corpus(nlp))
|
|
print(len(data))
|
|
optimizer = T["optimizer"]
|
|
# simulate a training loop
|
|
nlp.initialize(lambda: train_corpus(nlp), sgd=optimizer)
|
|
for example in train_corpus(nlp):
|
|
assert example.y.cats
|
|
# this shouldn't fail if each training example has at least one positive label
|
|
assert sorted(list(set(example.y.cats.values()))) == [0.0, 1.0]
|
|
nlp.update([example], sgd=optimizer)
|
|
# simulate performance benchmark on dev corpus
|
|
dev_examples = list(dev_corpus(nlp))
|
|
for example in dev_examples:
|
|
# this shouldn't fail if each dev example has at least one positive label
|
|
assert sorted(list(set(example.y.cats.values()))) == [0.0, 1.0]
|
|
scores = nlp.evaluate(dev_examples)
|
|
assert scores["cats_score"]
|
|
# ensure the pipeline runs
|
|
doc = nlp("Quick test")
|
|
assert doc.cats
|