2021-06-16 09:45:00 +00:00
|
|
|
from functools import partial
|
2023-11-29 08:11:54 +00:00
|
|
|
from typing import List, Optional, Tuple, cast
|
2020-10-18 12:50:41 +00:00
|
|
|
|
2023-06-14 15:48:41 +00:00
|
|
|
from thinc.api import (
|
|
|
|
Dropout,
|
|
|
|
LayerNorm,
|
|
|
|
Linear,
|
|
|
|
Logistic,
|
|
|
|
Maxout,
|
|
|
|
Model,
|
|
|
|
ParametricAttention,
|
|
|
|
Relu,
|
|
|
|
Softmax,
|
|
|
|
SparseLinear,
|
2023-11-29 08:11:54 +00:00
|
|
|
SparseLinear_v2,
|
2023-06-14 15:48:41 +00:00
|
|
|
chain,
|
|
|
|
clone,
|
|
|
|
concatenate,
|
|
|
|
list2ragged,
|
2023-12-21 10:00:06 +00:00
|
|
|
reduce_first,
|
|
|
|
reduce_last,
|
|
|
|
reduce_max,
|
2023-06-14 15:48:41 +00:00
|
|
|
reduce_mean,
|
|
|
|
reduce_sum,
|
|
|
|
residual,
|
|
|
|
resizable,
|
|
|
|
softmax_activation,
|
|
|
|
with_cpu,
|
|
|
|
)
|
2021-01-06 11:44:04 +00:00
|
|
|
from thinc.layers.chain import init as init_chain
|
2023-06-14 15:48:41 +00:00
|
|
|
from thinc.layers.resizable import resize_linear_weighted, resize_model
|
2023-11-29 08:11:54 +00:00
|
|
|
from thinc.types import ArrayXd, Floats2d
|
2020-02-27 17:42:27 +00:00
|
|
|
|
2021-01-15 10:42:40 +00:00
|
|
|
from ...attrs import ORTH
|
2023-11-29 08:11:54 +00:00
|
|
|
from ...errors import Errors
|
2023-06-14 15:48:41 +00:00
|
|
|
from ...tokens import Doc
|
2020-02-28 10:57:41 +00:00
|
|
|
from ...util import registry
|
|
|
|
from ..extract_ngrams import extract_ngrams
|
2020-07-29 12:35:36 +00:00
|
|
|
from ..staticvectors import StaticVectors
|
2021-01-06 11:44:04 +00:00
|
|
|
from .tok2vec import get_tok2vec_width
|
2020-02-27 17:42:27 +00:00
|
|
|
|
2021-06-16 09:45:00 +00:00
|
|
|
NEG_VALUE = -5000
|
|
|
|
|
|
|
|
|
|
|
|
@registry.architectures("spacy.TextCatCNN.v2")
|
2020-07-22 11:42:59 +00:00
|
|
|
def build_simple_cnn_text_classifier(
|
|
|
|
tok2vec: Model, exclusive_classes: bool, nO: Optional[int] = None
|
2020-10-18 12:50:41 +00:00
|
|
|
) -> Model[List[Doc], Floats2d]:
|
2020-02-27 17:42:27 +00:00
|
|
|
"""
|
|
|
|
Build a simple CNN text classifier, given a token-to-vector model as inputs.
|
|
|
|
If exclusive_classes=True, a softmax non-linearity is applied, so that the
|
|
|
|
outputs sum to 1. If exclusive_classes=False, a logistic non-linearity
|
|
|
|
is applied instead, so that outputs are in the range [0, 1].
|
|
|
|
"""
|
2023-12-21 10:00:06 +00:00
|
|
|
return build_reduce_text_classifier(
|
|
|
|
tok2vec=tok2vec,
|
|
|
|
exclusive_classes=exclusive_classes,
|
|
|
|
use_reduce_first=False,
|
|
|
|
use_reduce_last=False,
|
|
|
|
use_reduce_max=False,
|
|
|
|
use_reduce_mean=True,
|
|
|
|
nO=nO,
|
|
|
|
)
|
2020-02-27 17:42:27 +00:00
|
|
|
|
|
|
|
|
2021-06-16 09:45:00 +00:00
|
|
|
def resize_and_set_ref(model, new_nO, resizable_layer):
|
|
|
|
resizable_layer = resize_model(resizable_layer, new_nO)
|
|
|
|
model.set_ref("output_layer", resizable_layer.layers[0])
|
|
|
|
model.set_dim("nO", new_nO, force=True)
|
|
|
|
return model
|
|
|
|
|
|
|
|
|
|
|
|
@registry.architectures("spacy.TextCatBOW.v2")
|
2020-07-31 15:02:54 +00:00
|
|
|
def build_bow_text_classifier(
|
|
|
|
exclusive_classes: bool,
|
|
|
|
ngram_size: int,
|
|
|
|
no_output_layer: bool,
|
|
|
|
nO: Optional[int] = None,
|
2023-11-29 08:11:54 +00:00
|
|
|
) -> Model[List[Doc], Floats2d]:
|
|
|
|
return _build_bow_text_classifier(
|
|
|
|
exclusive_classes=exclusive_classes,
|
|
|
|
ngram_size=ngram_size,
|
|
|
|
no_output_layer=no_output_layer,
|
|
|
|
nO=nO,
|
|
|
|
sparse_linear=SparseLinear(nO=nO),
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
@registry.architectures("spacy.TextCatBOW.v3")
|
|
|
|
def build_bow_text_classifier_v3(
|
|
|
|
exclusive_classes: bool,
|
|
|
|
ngram_size: int,
|
|
|
|
no_output_layer: bool,
|
|
|
|
length: int = 262144,
|
|
|
|
nO: Optional[int] = None,
|
|
|
|
) -> Model[List[Doc], Floats2d]:
|
|
|
|
if length < 1:
|
|
|
|
raise ValueError(Errors.E1056.format(length=length))
|
|
|
|
|
|
|
|
# Find k such that 2**(k-1) < length <= 2**k.
|
|
|
|
length = 2 ** (length - 1).bit_length()
|
|
|
|
|
|
|
|
return _build_bow_text_classifier(
|
|
|
|
exclusive_classes=exclusive_classes,
|
|
|
|
ngram_size=ngram_size,
|
|
|
|
no_output_layer=no_output_layer,
|
|
|
|
nO=nO,
|
|
|
|
sparse_linear=SparseLinear_v2(nO=nO, length=length),
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
def _build_bow_text_classifier(
|
|
|
|
exclusive_classes: bool,
|
|
|
|
ngram_size: int,
|
|
|
|
no_output_layer: bool,
|
|
|
|
sparse_linear: Model[Tuple[ArrayXd, ArrayXd, ArrayXd], ArrayXd],
|
|
|
|
nO: Optional[int] = None,
|
2020-10-18 12:50:41 +00:00
|
|
|
) -> Model[List[Doc], Floats2d]:
|
2021-06-16 09:45:00 +00:00
|
|
|
fill_defaults = {"b": 0, "W": 0}
|
2020-02-27 17:42:27 +00:00
|
|
|
with Model.define_operators({">>": chain}):
|
2021-06-16 09:45:00 +00:00
|
|
|
output_layer = None
|
2020-02-27 17:42:27 +00:00
|
|
|
if not no_output_layer:
|
2021-06-16 09:45:00 +00:00
|
|
|
fill_defaults["b"] = NEG_VALUE
|
2020-03-29 17:40:36 +00:00
|
|
|
output_layer = softmax_activation() if exclusive_classes else Logistic()
|
2022-05-25 07:33:54 +00:00
|
|
|
resizable_layer: Model[Floats2d, Floats2d] = resizable(
|
2021-06-16 09:45:00 +00:00
|
|
|
sparse_linear,
|
|
|
|
resize_layer=partial(resize_linear_weighted, fill_defaults=fill_defaults),
|
|
|
|
)
|
|
|
|
model = extract_ngrams(ngram_size, attr=ORTH) >> resizable_layer
|
|
|
|
model = with_cpu(model, model.ops)
|
|
|
|
if output_layer:
|
2020-03-29 17:40:36 +00:00
|
|
|
model = model >> with_cpu(output_layer, output_layer.ops)
|
2022-05-25 07:33:54 +00:00
|
|
|
if nO is not None:
|
|
|
|
model.set_dim("nO", cast(int, nO))
|
2020-03-29 17:40:36 +00:00
|
|
|
model.set_ref("output_layer", sparse_linear)
|
2020-06-12 00:02:07 +00:00
|
|
|
model.attrs["multi_label"] = not exclusive_classes
|
2021-06-16 09:45:00 +00:00
|
|
|
model.attrs["resize_output"] = partial(
|
|
|
|
resize_and_set_ref, resizable_layer=resizable_layer
|
|
|
|
)
|
2020-03-29 17:40:36 +00:00
|
|
|
return model
|
|
|
|
|
|
|
|
|
2021-03-02 16:56:28 +00:00
|
|
|
@registry.architectures("spacy.TextCatEnsemble.v2")
|
2020-11-10 12:14:47 +00:00
|
|
|
def build_text_classifier_v2(
|
2020-10-18 12:50:41 +00:00
|
|
|
tok2vec: Model[List[Doc], List[Floats2d]],
|
|
|
|
linear_model: Model[List[Doc], Floats2d],
|
|
|
|
nO: Optional[int] = None,
|
|
|
|
) -> Model[List[Doc], Floats2d]:
|
|
|
|
exclusive_classes = not linear_model.attrs["multi_label"]
|
|
|
|
with Model.define_operators({">>": chain, "|": concatenate}):
|
2020-11-10 12:14:47 +00:00
|
|
|
width = tok2vec.maybe_get_dim("nO")
|
2021-06-16 09:45:00 +00:00
|
|
|
attention_layer = ParametricAttention(width)
|
2021-01-18 23:37:17 +00:00
|
|
|
maxout_layer = Maxout(nO=width, nI=width)
|
|
|
|
norm_layer = LayerNorm(nI=width)
|
2020-10-18 12:50:41 +00:00
|
|
|
cnn_model = (
|
2021-01-15 00:57:36 +00:00
|
|
|
tok2vec
|
|
|
|
>> list2ragged()
|
|
|
|
>> attention_layer
|
|
|
|
>> reduce_sum()
|
2021-01-18 23:37:17 +00:00
|
|
|
>> residual(maxout_layer >> norm_layer >> Dropout(0.0))
|
2020-10-18 12:50:41 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
nO_double = nO * 2 if nO else None
|
|
|
|
if exclusive_classes:
|
|
|
|
output_layer = Softmax(nO=nO, nI=nO_double)
|
|
|
|
else:
|
2021-01-18 15:53:02 +00:00
|
|
|
output_layer = Linear(nO=nO, nI=nO_double) >> Logistic()
|
2020-10-18 12:50:41 +00:00
|
|
|
model = (linear_model | cnn_model) >> output_layer
|
|
|
|
model.set_ref("tok2vec", tok2vec)
|
2022-05-25 07:33:54 +00:00
|
|
|
if model.has_dim("nO") is not False and nO is not None:
|
|
|
|
model.set_dim("nO", cast(int, nO))
|
2020-10-18 12:50:41 +00:00
|
|
|
model.set_ref("output_layer", linear_model.get_ref("output_layer"))
|
2021-01-06 11:44:04 +00:00
|
|
|
model.set_ref("attention_layer", attention_layer)
|
|
|
|
model.set_ref("maxout_layer", maxout_layer)
|
2021-01-18 23:37:17 +00:00
|
|
|
model.set_ref("norm_layer", norm_layer)
|
2020-10-18 12:50:41 +00:00
|
|
|
model.attrs["multi_label"] = not exclusive_classes
|
2021-01-06 11:44:04 +00:00
|
|
|
|
🏷 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 13:21:40 +00:00
|
|
|
model.init = init_ensemble_textcat # type: ignore[assignment]
|
2021-01-06 11:44:04 +00:00
|
|
|
return model
|
|
|
|
|
|
|
|
|
|
|
|
def init_ensemble_textcat(model, X, Y) -> Model:
|
|
|
|
tok2vec_width = get_tok2vec_width(model)
|
|
|
|
model.get_ref("attention_layer").set_dim("nO", tok2vec_width)
|
|
|
|
model.get_ref("maxout_layer").set_dim("nO", tok2vec_width)
|
|
|
|
model.get_ref("maxout_layer").set_dim("nI", tok2vec_width)
|
2021-01-18 23:37:17 +00:00
|
|
|
model.get_ref("norm_layer").set_dim("nI", tok2vec_width)
|
2021-02-06 12:44:51 +00:00
|
|
|
model.get_ref("norm_layer").set_dim("nO", tok2vec_width)
|
2021-01-06 11:44:04 +00:00
|
|
|
init_chain(model, X, Y)
|
2020-10-18 12:50:41 +00:00
|
|
|
return model
|
|
|
|
|
2021-01-05 02:41:53 +00:00
|
|
|
|
2021-03-02 16:56:28 +00:00
|
|
|
@registry.architectures("spacy.TextCatLowData.v1")
|
2020-07-31 15:02:54 +00:00
|
|
|
def build_text_classifier_lowdata(
|
2020-10-18 12:50:41 +00:00
|
|
|
width: int, dropout: Optional[float], nO: Optional[int] = None
|
|
|
|
) -> Model[List[Doc], Floats2d]:
|
2020-08-07 14:17:34 +00:00
|
|
|
# Don't document this yet, I'm not sure it's right.
|
2020-03-29 17:40:36 +00:00
|
|
|
# Note, before v.3, this was the default if setting "low_data" and "pretrained_dims"
|
|
|
|
with Model.define_operators({">>": chain, "**": clone}):
|
|
|
|
model = (
|
2020-07-29 12:35:36 +00:00
|
|
|
StaticVectors(width)
|
2020-03-29 17:40:36 +00:00
|
|
|
>> list2ragged()
|
|
|
|
>> ParametricAttention(width)
|
|
|
|
>> reduce_sum()
|
2022-05-25 07:33:54 +00:00
|
|
|
>> residual(Relu(width, width)) ** 2
|
2020-03-29 17:40:36 +00:00
|
|
|
>> Linear(nO, width)
|
|
|
|
)
|
2020-06-03 09:50:16 +00:00
|
|
|
if dropout:
|
|
|
|
model = model >> Dropout(dropout)
|
|
|
|
model = model >> Logistic()
|
2020-02-27 17:42:27 +00:00
|
|
|
return model
|
2023-12-21 10:00:06 +00:00
|
|
|
|
|
|
|
|
|
|
|
@registry.architectures("spacy.TextCatReduce.v1")
|
|
|
|
def build_reduce_text_classifier(
|
|
|
|
tok2vec: Model,
|
|
|
|
exclusive_classes: bool,
|
|
|
|
use_reduce_first: bool,
|
|
|
|
use_reduce_last: bool,
|
|
|
|
use_reduce_max: bool,
|
|
|
|
use_reduce_mean: bool,
|
|
|
|
nO: Optional[int] = None,
|
|
|
|
) -> Model[List[Doc], Floats2d]:
|
|
|
|
"""Build a model that classifies pooled `Doc` representations.
|
|
|
|
|
|
|
|
Pooling is performed using reductions. Reductions are concatenated when
|
|
|
|
multiple reductions are used.
|
|
|
|
|
|
|
|
tok2vec (Model): the tok2vec layer to pool over.
|
|
|
|
exclusive_classes (bool): Whether or not classes are mutually exclusive.
|
|
|
|
use_reduce_first (bool): Pool by using the hidden representation of the
|
|
|
|
first token of a `Doc`.
|
|
|
|
use_reduce_last (bool): Pool by using the hidden representation of the
|
|
|
|
last token of a `Doc`.
|
|
|
|
use_reduce_max (bool): Pool by taking the maximum values of the hidden
|
|
|
|
representations of a `Doc`.
|
|
|
|
use_reduce_mean (bool): Pool by taking the mean of all hidden
|
|
|
|
representations of a `Doc`.
|
|
|
|
nO (Optional[int]): Number of classes.
|
|
|
|
"""
|
|
|
|
|
|
|
|
fill_defaults = {"b": 0, "W": 0}
|
|
|
|
reductions = []
|
|
|
|
if use_reduce_first:
|
|
|
|
reductions.append(reduce_first())
|
|
|
|
if use_reduce_last:
|
|
|
|
reductions.append(reduce_last())
|
|
|
|
if use_reduce_max:
|
|
|
|
reductions.append(reduce_max())
|
|
|
|
if use_reduce_mean:
|
|
|
|
reductions.append(reduce_mean())
|
|
|
|
|
|
|
|
if not len(reductions):
|
|
|
|
raise ValueError(Errors.E1057)
|
|
|
|
|
|
|
|
with Model.define_operators({">>": chain}):
|
|
|
|
cnn = tok2vec >> list2ragged() >> concatenate(*reductions)
|
|
|
|
nO_tok2vec = tok2vec.maybe_get_dim("nO")
|
|
|
|
nI = nO_tok2vec * len(reductions) if nO_tok2vec is not None else None
|
|
|
|
if exclusive_classes:
|
|
|
|
output_layer = Softmax(nO=nO, nI=nI)
|
|
|
|
fill_defaults["b"] = NEG_VALUE
|
|
|
|
resizable_layer: Model = resizable(
|
|
|
|
output_layer,
|
|
|
|
resize_layer=partial(
|
|
|
|
resize_linear_weighted, fill_defaults=fill_defaults
|
|
|
|
),
|
|
|
|
)
|
|
|
|
model = cnn >> resizable_layer
|
|
|
|
else:
|
|
|
|
output_layer = Linear(nO=nO, nI=nI)
|
|
|
|
resizable_layer = resizable(
|
|
|
|
output_layer,
|
|
|
|
resize_layer=partial(
|
|
|
|
resize_linear_weighted, fill_defaults=fill_defaults
|
|
|
|
),
|
|
|
|
)
|
|
|
|
model = cnn >> resizable_layer >> Logistic()
|
|
|
|
model.set_ref("output_layer", output_layer)
|
|
|
|
model.attrs["resize_output"] = partial(
|
|
|
|
resize_and_set_ref,
|
|
|
|
resizable_layer=resizable_layer,
|
|
|
|
)
|
|
|
|
model.set_ref("tok2vec", tok2vec)
|
|
|
|
if nO is not None:
|
|
|
|
model.set_dim("nO", cast(int, nO))
|
|
|
|
model.attrs["multi_label"] = not exclusive_classes
|
|
|
|
return model
|