2020-09-29 11:58:50 +03:00
|
|
|
import gzip
|
2023-06-26 12:41:03 +03:00
|
|
|
import tarfile
|
|
|
|
import warnings
|
2020-09-29 11:58:50 +03:00
|
|
|
import zipfile
|
2021-04-08 11:08:04 +03:00
|
|
|
from itertools import islice
|
2023-06-26 12:41:03 +03:00
|
|
|
from pathlib import Path
|
|
|
|
from typing import IO, TYPE_CHECKING, Any, Dict, Optional, Union
|
|
|
|
|
|
|
|
import numpy
|
|
|
|
import srsly
|
|
|
|
import tqdm
|
|
|
|
from thinc.api import Config, ConfigValidationError
|
2020-09-28 16:09:59 +03:00
|
|
|
|
2021-01-26 06:51:52 +03:00
|
|
|
from ..errors import Errors, Warnings
|
2023-06-26 12:41:03 +03:00
|
|
|
from ..lookups import Lookups
|
2023-04-21 14:49:40 +03:00
|
|
|
from ..schemas import ConfigSchemaDistill, ConfigSchemaTraining
|
2023-06-26 12:41:03 +03:00
|
|
|
from ..util import (
|
|
|
|
DEFAULT_OOV_PROB,
|
|
|
|
OOV_RANK,
|
|
|
|
ensure_path,
|
|
|
|
get_sourced_components,
|
|
|
|
load_model,
|
|
|
|
load_model_from_config,
|
|
|
|
logger,
|
|
|
|
registry,
|
|
|
|
resolve_dot_names,
|
|
|
|
set_gpu_allocator_from_config,
|
|
|
|
set_seed_from_config,
|
|
|
|
)
|
|
|
|
from ..vectors import Mode as VectorsMode
|
|
|
|
from ..vectors import Vectors
|
|
|
|
from .pretrain import get_tok2vec_ref
|
2020-09-28 16:09:59 +03:00
|
|
|
|
2020-09-29 17:05:48 +03:00
|
|
|
if TYPE_CHECKING:
|
|
|
|
from ..language import Language # noqa: F401
|
2020-09-28 16:09:59 +03:00
|
|
|
|
2020-09-29 17:05:48 +03:00
|
|
|
|
2020-09-29 17:08:39 +03:00
|
|
|
def init_nlp(config: Config, *, use_gpu: int = -1) -> "Language":
|
2020-09-28 16:09:59 +03:00
|
|
|
raw_config = config
|
|
|
|
config = raw_config.interpolate()
|
2023-04-21 14:49:40 +03:00
|
|
|
set_seed_from_config(config)
|
|
|
|
set_gpu_allocator_from_config(config, use_gpu)
|
2020-09-28 16:09:59 +03:00
|
|
|
# Use original config here before it's resolved to functions
|
2021-01-29 07:57:04 +03:00
|
|
|
sourced = get_sourced_components(config)
|
2020-09-28 16:09:59 +03:00
|
|
|
nlp = load_model_from_config(raw_config, auto_fill=True)
|
2020-09-29 17:08:39 +03:00
|
|
|
logger.info("Set up nlp object from config")
|
2020-09-28 16:09:59 +03:00
|
|
|
config = nlp.config.interpolate()
|
|
|
|
# Resolve all training-relevant sections using the filled nlp config
|
|
|
|
T = registry.resolve(config["training"], schema=ConfigSchemaTraining)
|
|
|
|
dot_names = [T["train_corpus"], T["dev_corpus"]]
|
2020-10-18 15:50:41 +03:00
|
|
|
if not isinstance(T["train_corpus"], str):
|
2021-01-05 05:41:53 +03:00
|
|
|
raise ConfigValidationError(
|
|
|
|
desc=Errors.E897.format(
|
|
|
|
field="training.train_corpus", type=type(T["train_corpus"])
|
|
|
|
)
|
|
|
|
)
|
2020-10-18 15:50:41 +03:00
|
|
|
if not isinstance(T["dev_corpus"], str):
|
2021-01-05 05:41:53 +03:00
|
|
|
raise ConfigValidationError(
|
|
|
|
desc=Errors.E897.format(
|
|
|
|
field="training.dev_corpus", type=type(T["dev_corpus"])
|
|
|
|
)
|
|
|
|
)
|
2020-09-28 16:09:59 +03:00
|
|
|
train_corpus, dev_corpus = resolve_dot_names(config, dot_names)
|
|
|
|
optimizer = T["optimizer"]
|
|
|
|
# Components that shouldn't be updated during training
|
|
|
|
frozen_components = T["frozen_components"]
|
|
|
|
# Sourced components that require resume_training
|
2021-01-29 07:57:04 +03:00
|
|
|
resume_components = [p for p in sourced if p not in frozen_components]
|
2023-02-02 13:15:22 +03:00
|
|
|
logger.info("Pipeline: %s", nlp.pipe_names)
|
2020-09-28 16:09:59 +03:00
|
|
|
if resume_components:
|
|
|
|
with nlp.select_pipes(enable=resume_components):
|
2023-02-02 13:15:22 +03:00
|
|
|
logger.info("Resuming training for: %s", resume_components)
|
2020-09-28 16:09:59 +03:00
|
|
|
nlp.resume_training(sgd=optimizer)
|
2023-06-27 11:47:07 +03:00
|
|
|
# Make sure that internal component names are synced and listeners are
|
|
|
|
# defined before initializing further
|
2021-02-01 14:19:58 +03:00
|
|
|
nlp._link_components()
|
2020-09-28 16:09:59 +03:00
|
|
|
with nlp.select_pipes(disable=[*frozen_components, *resume_components]):
|
2021-04-08 11:08:04 +03:00
|
|
|
if T["max_epochs"] == -1:
|
2021-07-17 06:43:15 +03:00
|
|
|
sample_size = 100
|
2021-06-28 12:48:00 +03:00
|
|
|
logger.debug(
|
2023-02-02 13:15:22 +03:00
|
|
|
"Due to streamed train corpus, using only first %s examples for initialization. "
|
|
|
|
"If necessary, provide all labels in [initialize]. "
|
|
|
|
"More info: https://spacy.io/api/cli#init_labels",
|
|
|
|
sample_size,
|
2021-06-28 12:48:00 +03:00
|
|
|
)
|
2021-07-23 11:04:09 +03:00
|
|
|
nlp.initialize(
|
|
|
|
lambda: islice(train_corpus(nlp), sample_size), sgd=optimizer
|
|
|
|
)
|
2021-04-08 11:08:04 +03:00
|
|
|
else:
|
|
|
|
nlp.initialize(lambda: train_corpus(nlp), sgd=optimizer)
|
2023-02-02 13:15:22 +03:00
|
|
|
logger.info("Initialized pipeline components: %s", nlp.pipe_names)
|
2021-01-20 03:12:35 +03:00
|
|
|
# Detect components with listeners that are not frozen consistently
|
2023-04-21 14:49:40 +03:00
|
|
|
for name, proc in nlp.pipeline:
|
|
|
|
for listener in getattr(
|
|
|
|
proc, "listening_components", []
|
|
|
|
): # e.g. tok2vec/transformer
|
|
|
|
# Don't warn about components not in the pipeline
|
|
|
|
if listener not in nlp.pipe_names:
|
|
|
|
continue
|
|
|
|
if listener in frozen_components and name not in frozen_components:
|
|
|
|
logger.warning(Warnings.W087.format(name=name, listener=listener))
|
|
|
|
# We always check this regardless, in case user freezes tok2vec
|
|
|
|
if listener not in frozen_components and name in frozen_components:
|
|
|
|
if name not in T["annotating_components"]:
|
|
|
|
logger.warning(Warnings.W086.format(name=name, listener=listener))
|
|
|
|
return nlp
|
|
|
|
|
|
|
|
|
|
|
|
def init_nlp_student(
|
|
|
|
config: Config, teacher: "Language", *, use_gpu: int = -1
|
|
|
|
) -> "Language":
|
|
|
|
"""Initialize student pipeline for distillation.
|
|
|
|
|
|
|
|
config (Config): Student model configuration.
|
|
|
|
teacher (Language): The teacher pipeline to distill from.
|
|
|
|
use_gpu (int): Whether to train on GPU. Make sure to call require_gpu
|
|
|
|
before calling this function.
|
|
|
|
"""
|
|
|
|
raw_config = config
|
|
|
|
config = raw_config.interpolate()
|
|
|
|
set_seed_from_config(config)
|
|
|
|
set_gpu_allocator_from_config(config, use_gpu)
|
|
|
|
|
|
|
|
# Use original config here before it's resolved to functions
|
|
|
|
sourced = get_sourced_components(config)
|
|
|
|
nlp = load_model_from_config(raw_config, auto_fill=True)
|
|
|
|
logger.info("Set up nlp object from config")
|
|
|
|
config = nlp.config.interpolate()
|
|
|
|
# Resolve all training-relevant sections using the filled nlp config
|
|
|
|
T = registry.resolve(config["training"], schema=ConfigSchemaTraining)
|
|
|
|
D = registry.resolve(config["distillation"], schema=ConfigSchemaDistill)
|
|
|
|
dot_names = [T["dev_corpus"]]
|
|
|
|
if not isinstance(D["corpus"], str):
|
|
|
|
raise ConfigValidationError(
|
|
|
|
desc=Errors.E897.format(field="distillation.corpus", type=type(D["corpus"]))
|
|
|
|
)
|
|
|
|
if not isinstance(T["dev_corpus"], str):
|
|
|
|
raise ConfigValidationError(
|
|
|
|
desc=Errors.E897.format(
|
|
|
|
field="training.dev_corpus", type=type(T["dev_corpus"])
|
|
|
|
)
|
|
|
|
)
|
|
|
|
(dev_corpus,) = resolve_dot_names(config, dot_names)
|
|
|
|
optimizer = T["optimizer"]
|
|
|
|
# Components that shouldn't be updated during training
|
|
|
|
frozen_components = T["frozen_components"]
|
|
|
|
# Sourced components that require resume_training
|
|
|
|
resume_components = [p for p in sourced if p not in frozen_components]
|
|
|
|
logger.info(f"Pipeline: {nlp.pipe_names}")
|
|
|
|
if resume_components:
|
|
|
|
with nlp.select_pipes(enable=resume_components):
|
|
|
|
logger.info(f"Resuming training for: {resume_components}")
|
|
|
|
nlp.resume_training(sgd=optimizer)
|
|
|
|
# Make sure that listeners are defined before initializing further
|
|
|
|
nlp._link_components()
|
|
|
|
|
|
|
|
# Get teacher labels to initialize student with.
|
|
|
|
student_to_teacher = D["student_to_teacher"]
|
|
|
|
teacher_pipes = dict(teacher.pipeline)
|
|
|
|
labels = {}
|
|
|
|
for name, pipe in nlp.pipeline:
|
|
|
|
# Copy teacher labels.
|
|
|
|
teacher_pipe_name = (
|
|
|
|
student_to_teacher[name] if name in student_to_teacher else name
|
|
|
|
)
|
|
|
|
teacher_pipe = teacher_pipes.get(teacher_pipe_name, None)
|
|
|
|
if (
|
|
|
|
teacher_pipe is not None
|
|
|
|
and getattr(teacher_pipe, "label_data", None) is not None
|
|
|
|
):
|
|
|
|
labels[name] = teacher_pipe.label_data # type: ignore[attr-defined]
|
|
|
|
|
|
|
|
with nlp.select_pipes(disable=[*frozen_components, *resume_components]):
|
|
|
|
# Initialize on the dev corpus, since the distillation corpus does
|
|
|
|
# usually not have labels. Since we copy the labels from the teacher
|
|
|
|
# pipe, the dev data does not have to be exhaustive.
|
|
|
|
if T["max_epochs"] == -1:
|
|
|
|
sample_size = 100
|
|
|
|
logger.debug(
|
|
|
|
f"Due to streamed train corpus, using only first {sample_size} "
|
|
|
|
f"examples for initialization. If necessary, provide all labels "
|
|
|
|
f"in [initialize]. More info: https://spacy.io/api/cli#init_labels"
|
|
|
|
)
|
|
|
|
nlp.initialize(lambda: islice(dev_corpus(nlp), sample_size), sgd=optimizer)
|
|
|
|
else:
|
|
|
|
nlp.initialize(lambda: dev_corpus(nlp), sgd=optimizer, labels=labels)
|
|
|
|
logger.info(f"Initialized pipeline components: {nlp.pipe_names}")
|
|
|
|
# Detect components with listeners that are not frozen consistently
|
2021-01-20 03:12:35 +03:00
|
|
|
for name, proc in nlp.pipeline:
|
2021-06-28 12:48:00 +03:00
|
|
|
for listener in getattr(
|
|
|
|
proc, "listening_components", []
|
|
|
|
): # e.g. tok2vec/transformer
|
2021-03-17 16:41:41 +03:00
|
|
|
# Don't warn about components not in the pipeline
|
|
|
|
if listener not in nlp.pipe_names:
|
|
|
|
continue
|
|
|
|
if listener in frozen_components and name not in frozen_components:
|
|
|
|
logger.warning(Warnings.W087.format(name=name, listener=listener))
|
|
|
|
# We always check this regardless, in case user freezes tok2vec
|
|
|
|
if listener not in frozen_components and name in frozen_components:
|
2021-08-26 10:50:35 +03:00
|
|
|
if name not in T["annotating_components"]:
|
|
|
|
logger.warning(Warnings.W086.format(name=name, listener=listener))
|
2020-09-28 16:09:59 +03:00
|
|
|
return nlp
|
|
|
|
|
|
|
|
|
|
|
|
def init_vocab(
|
2020-09-29 17:05:48 +03:00
|
|
|
nlp: "Language",
|
2020-09-28 16:09:59 +03:00
|
|
|
*,
|
|
|
|
data: Optional[Path] = None,
|
|
|
|
lookups: Optional[Lookups] = None,
|
|
|
|
vectors: Optional[str] = None,
|
🏷 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
|
|
|
) -> None:
|
2020-09-28 16:09:59 +03:00
|
|
|
if lookups:
|
|
|
|
nlp.vocab.lookups = lookups
|
2023-02-02 13:15:22 +03:00
|
|
|
logger.info("Added vocab lookups: %s", ", ".join(lookups.tables))
|
2020-09-28 16:09:59 +03:00
|
|
|
data_path = ensure_path(data)
|
|
|
|
if data_path is not None:
|
|
|
|
lex_attrs = srsly.read_jsonl(data_path)
|
|
|
|
for lexeme in nlp.vocab:
|
|
|
|
lexeme.rank = OOV_RANK
|
|
|
|
for attrs in lex_attrs:
|
|
|
|
if "settings" in attrs:
|
|
|
|
continue
|
|
|
|
lexeme = nlp.vocab[attrs["orth"]]
|
|
|
|
lexeme.set_attrs(**attrs)
|
|
|
|
if len(nlp.vocab):
|
|
|
|
oov_prob = min(lex.prob for lex in nlp.vocab) - 1
|
|
|
|
else:
|
|
|
|
oov_prob = DEFAULT_OOV_PROB
|
|
|
|
nlp.vocab.cfg.update({"oov_prob": oov_prob})
|
2023-02-02 13:15:22 +03:00
|
|
|
logger.info("Added %d lexical entries to the vocab", len(nlp.vocab))
|
2020-09-29 17:22:41 +03:00
|
|
|
logger.info("Created vocabulary")
|
2020-09-28 16:09:59 +03:00
|
|
|
if vectors is not None:
|
|
|
|
load_vectors_into_model(nlp, vectors)
|
2023-02-02 13:15:22 +03:00
|
|
|
logger.info("Added vectors: %s", vectors)
|
2021-07-06 13:43:17 +03:00
|
|
|
# warn if source model vectors are not identical
|
|
|
|
sourced_vectors_hashes = nlp.meta.pop("_sourced_vectors_hashes", {})
|
2023-05-08 17:51:58 +03:00
|
|
|
if len(sourced_vectors_hashes) > 0:
|
|
|
|
vectors_hash = hash(nlp.vocab.vectors.to_bytes(exclude=["strings"]))
|
|
|
|
for sourced_component, sourced_vectors_hash in sourced_vectors_hashes.items():
|
|
|
|
if vectors_hash != sourced_vectors_hash:
|
|
|
|
warnings.warn(Warnings.W113.format(name=sourced_component))
|
2020-09-29 23:53:14 +03:00
|
|
|
logger.info("Finished initializing nlp object")
|
2020-09-28 16:09:59 +03:00
|
|
|
|
|
|
|
|
|
|
|
def load_vectors_into_model(
|
2020-09-29 17:05:48 +03:00
|
|
|
nlp: "Language", name: Union[str, Path], *, add_strings: bool = True
|
2020-09-28 16:09:59 +03:00
|
|
|
) -> None:
|
|
|
|
"""Load word vectors from an installed model or path into a model instance."""
|
|
|
|
try:
|
2021-10-04 13:19:02 +03:00
|
|
|
# Load with the same vocab, which automatically adds the vectors to
|
|
|
|
# the current nlp object. Exclude lookups so they are not modified.
|
|
|
|
exclude = ["lookups"]
|
|
|
|
if not add_strings:
|
|
|
|
exclude.append("strings")
|
|
|
|
vectors_nlp = load_model(name, vocab=nlp.vocab, exclude=exclude)
|
2020-09-28 16:09:59 +03:00
|
|
|
except ConfigValidationError as e:
|
|
|
|
title = f"Config validation error for vectors {name}"
|
|
|
|
desc = (
|
|
|
|
"This typically means that there's a problem in the config.cfg included "
|
|
|
|
"with the packaged vectors. Make sure that the vectors package you're "
|
|
|
|
"loading is compatible with the current version of spaCy."
|
|
|
|
)
|
2020-12-09 01:16:07 +03:00
|
|
|
err = ConfigValidationError.from_error(e, title=title, desc=desc)
|
2020-09-28 16:09:59 +03:00
|
|
|
raise err from None
|
2021-04-04 21:20:24 +03:00
|
|
|
|
2021-10-27 15:08:31 +03:00
|
|
|
if (
|
|
|
|
len(vectors_nlp.vocab.vectors.keys()) == 0
|
|
|
|
and vectors_nlp.vocab.vectors.mode != VectorsMode.floret
|
|
|
|
) or (
|
2022-01-18 19:14:35 +03:00
|
|
|
vectors_nlp.vocab.vectors.shape[0] == 0
|
2021-10-27 15:08:31 +03:00
|
|
|
and vectors_nlp.vocab.vectors.mode == VectorsMode.floret
|
|
|
|
):
|
2021-04-04 21:20:24 +03:00
|
|
|
logger.warning(Warnings.W112.format(name=name))
|
|
|
|
|
2021-07-19 11:25:54 +03:00
|
|
|
for lex in nlp.vocab:
|
🏷 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
|
|
|
lex.rank = nlp.vocab.vectors.key2row.get(lex.orth, OOV_RANK) # type: ignore[attr-defined]
|
2020-09-28 16:09:59 +03:00
|
|
|
|
|
|
|
|
2020-09-29 17:05:48 +03:00
|
|
|
def init_tok2vec(
|
2020-09-29 17:47:55 +03:00
|
|
|
nlp: "Language", pretrain_config: Dict[str, Any], init_config: Dict[str, Any]
|
2020-09-28 16:09:59 +03:00
|
|
|
) -> bool:
|
|
|
|
# Load pretrained tok2vec weights - cf. CLI command 'pretrain'
|
|
|
|
P = pretrain_config
|
2020-09-29 17:47:55 +03:00
|
|
|
I = init_config
|
2020-09-28 16:09:59 +03:00
|
|
|
weights_data = None
|
2020-09-29 17:47:55 +03:00
|
|
|
init_tok2vec = ensure_path(I["init_tok2vec"])
|
2020-09-28 16:09:59 +03:00
|
|
|
if init_tok2vec is not None:
|
|
|
|
if not init_tok2vec.exists():
|
|
|
|
err = f"can't find pretrained tok2vec: {init_tok2vec}"
|
2020-09-29 21:38:35 +03:00
|
|
|
errors = [{"loc": ["initialize", "init_tok2vec"], "msg": err}]
|
2020-09-28 16:09:59 +03:00
|
|
|
raise ConfigValidationError(config=nlp.config, errors=errors)
|
|
|
|
with init_tok2vec.open("rb") as file_:
|
|
|
|
weights_data = file_.read()
|
|
|
|
if weights_data is not None:
|
2021-03-09 06:01:13 +03:00
|
|
|
layer = get_tok2vec_ref(nlp, P)
|
2020-09-28 16:09:59 +03:00
|
|
|
layer.from_bytes(weights_data)
|
2023-02-02 13:15:22 +03:00
|
|
|
logger.info("Loaded pretrained weights from %s", init_tok2vec)
|
2020-09-28 16:09:59 +03:00
|
|
|
return True
|
|
|
|
return False
|
|
|
|
|
|
|
|
|
2020-09-29 11:58:50 +03:00
|
|
|
def convert_vectors(
|
2020-09-29 17:05:48 +03:00
|
|
|
nlp: "Language",
|
2020-09-29 11:58:50 +03:00
|
|
|
vectors_loc: Optional[Path],
|
|
|
|
*,
|
|
|
|
truncate: int,
|
|
|
|
prune: int,
|
2021-10-27 15:08:31 +03:00
|
|
|
mode: str = VectorsMode.default,
|
2023-06-28 10:43:14 +03:00
|
|
|
attr: str = "ORTH",
|
2020-09-29 11:58:50 +03:00
|
|
|
) -> None:
|
|
|
|
vectors_loc = ensure_path(vectors_loc)
|
|
|
|
if vectors_loc and vectors_loc.parts[-1].endswith(".npz"):
|
2023-06-28 10:43:14 +03:00
|
|
|
if attr != "ORTH":
|
|
|
|
raise ValueError(
|
|
|
|
"ORTH is the only attribute supported for vectors in .npz format."
|
|
|
|
)
|
2021-10-27 15:08:31 +03:00
|
|
|
nlp.vocab.vectors = Vectors(
|
|
|
|
strings=nlp.vocab.strings, data=numpy.load(vectors_loc.open("rb"))
|
|
|
|
)
|
2020-09-29 11:58:50 +03:00
|
|
|
for lex in nlp.vocab:
|
|
|
|
if lex.rank and lex.rank != OOV_RANK:
|
🏷 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
|
|
|
nlp.vocab.vectors.add(lex.orth, row=lex.rank) # type: ignore[attr-defined]
|
2022-03-30 09:54:23 +03:00
|
|
|
nlp.vocab.deduplicate_vectors()
|
2020-09-29 11:58:50 +03:00
|
|
|
else:
|
|
|
|
if vectors_loc:
|
2023-02-02 13:15:22 +03:00
|
|
|
logger.info("Reading vectors from %s", vectors_loc)
|
2021-10-27 15:08:31 +03:00
|
|
|
vectors_data, vector_keys, floret_settings = read_vectors(
|
|
|
|
vectors_loc,
|
|
|
|
truncate,
|
|
|
|
mode=mode,
|
|
|
|
)
|
2023-02-02 13:15:22 +03:00
|
|
|
logger.info("Loaded vectors from %s", vectors_loc)
|
2020-09-29 11:58:50 +03:00
|
|
|
else:
|
|
|
|
vectors_data, vector_keys = (None, None)
|
2021-10-27 15:08:31 +03:00
|
|
|
if vector_keys is not None and mode != VectorsMode.floret:
|
2020-09-29 11:58:50 +03:00
|
|
|
for word in vector_keys:
|
|
|
|
if word not in nlp.vocab:
|
|
|
|
nlp.vocab[word]
|
|
|
|
if vectors_data is not None:
|
2021-10-27 15:08:31 +03:00
|
|
|
if mode == VectorsMode.floret:
|
|
|
|
nlp.vocab.vectors = Vectors(
|
|
|
|
strings=nlp.vocab.strings,
|
|
|
|
data=vectors_data,
|
2023-06-28 10:43:14 +03:00
|
|
|
attr=attr,
|
2021-10-27 15:08:31 +03:00
|
|
|
**floret_settings,
|
|
|
|
)
|
|
|
|
else:
|
|
|
|
nlp.vocab.vectors = Vectors(
|
2023-06-28 10:43:14 +03:00
|
|
|
strings=nlp.vocab.strings,
|
|
|
|
data=vectors_data,
|
|
|
|
keys=vector_keys,
|
|
|
|
attr=attr,
|
2021-10-27 15:08:31 +03:00
|
|
|
)
|
2022-03-30 09:54:23 +03:00
|
|
|
nlp.vocab.deduplicate_vectors()
|
2021-10-27 15:08:31 +03:00
|
|
|
if prune >= 1 and mode != VectorsMode.floret:
|
2020-09-29 11:58:50 +03:00
|
|
|
nlp.vocab.prune_vectors(prune)
|
|
|
|
|
|
|
|
|
2021-10-27 15:08:31 +03:00
|
|
|
def read_vectors(
|
|
|
|
vectors_loc: Path, truncate_vectors: int, *, mode: str = VectorsMode.default
|
|
|
|
):
|
2021-02-07 03:05:43 +03:00
|
|
|
f = ensure_shape(vectors_loc)
|
2021-10-27 15:08:31 +03:00
|
|
|
header_parts = next(f).split()
|
|
|
|
shape = tuple(int(size) for size in header_parts[:2])
|
|
|
|
floret_settings = {}
|
|
|
|
if mode == VectorsMode.floret:
|
|
|
|
if len(header_parts) != 8:
|
|
|
|
raise ValueError(
|
|
|
|
"Invalid header for floret vectors. "
|
|
|
|
"Expected: bucket dim minn maxn hash_count hash_seed BOW EOW"
|
|
|
|
)
|
|
|
|
floret_settings = {
|
|
|
|
"mode": "floret",
|
|
|
|
"minn": int(header_parts[2]),
|
|
|
|
"maxn": int(header_parts[3]),
|
|
|
|
"hash_count": int(header_parts[4]),
|
|
|
|
"hash_seed": int(header_parts[5]),
|
|
|
|
"bow": header_parts[6],
|
|
|
|
"eow": header_parts[7],
|
|
|
|
}
|
|
|
|
if truncate_vectors >= 1:
|
|
|
|
raise ValueError(Errors.E860)
|
|
|
|
else:
|
|
|
|
assert len(header_parts) == 2
|
|
|
|
if truncate_vectors >= 1:
|
|
|
|
shape = (truncate_vectors, shape[1])
|
2020-09-29 11:58:50 +03:00
|
|
|
vectors_data = numpy.zeros(shape=shape, dtype="f")
|
|
|
|
vectors_keys = []
|
2023-09-22 19:20:22 +03:00
|
|
|
for i, line in enumerate(tqdm.tqdm(f, disable=None)):
|
2020-09-29 11:58:50 +03:00
|
|
|
line = line.rstrip()
|
|
|
|
pieces = line.rsplit(" ", vectors_data.shape[1])
|
|
|
|
word = pieces.pop(0)
|
|
|
|
if len(pieces) != vectors_data.shape[1]:
|
|
|
|
raise ValueError(Errors.E094.format(line_num=i, loc=vectors_loc))
|
|
|
|
vectors_data[i] = numpy.asarray(pieces, dtype="f")
|
|
|
|
vectors_keys.append(word)
|
|
|
|
if i == truncate_vectors - 1:
|
|
|
|
break
|
2021-10-27 15:08:31 +03:00
|
|
|
return vectors_data, vectors_keys, floret_settings
|
2020-09-29 11:58:50 +03:00
|
|
|
|
|
|
|
|
|
|
|
def open_file(loc: Union[str, Path]) -> IO:
|
|
|
|
"""Handle .gz, .tar.gz or unzipped files"""
|
|
|
|
loc = ensure_path(loc)
|
|
|
|
if tarfile.is_tarfile(str(loc)):
|
🏷 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
|
|
|
return tarfile.open(str(loc), "r:gz") # type: ignore[return-value]
|
2020-09-29 11:58:50 +03:00
|
|
|
elif loc.parts[-1].endswith("gz"):
|
🏷 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
|
|
|
return (line.decode("utf8") for line in gzip.open(str(loc), "r")) # type: ignore[return-value]
|
2020-09-29 11:58:50 +03:00
|
|
|
elif loc.parts[-1].endswith("zip"):
|
|
|
|
zip_file = zipfile.ZipFile(str(loc))
|
|
|
|
names = zip_file.namelist()
|
|
|
|
file_ = zip_file.open(names[0])
|
🏷 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
|
|
|
return (line.decode("utf8") for line in file_) # type: ignore[return-value]
|
2020-09-29 11:58:50 +03:00
|
|
|
else:
|
|
|
|
return loc.open("r", encoding="utf8")
|
|
|
|
|
|
|
|
|
2021-02-07 03:05:43 +03:00
|
|
|
def ensure_shape(vectors_loc):
|
2020-09-29 11:58:50 +03:00
|
|
|
"""Ensure that the first line of the data is the vectors shape.
|
|
|
|
If it's not, we read in the data and output the shape as the first result,
|
|
|
|
so that the reader doesn't have to deal with the problem.
|
|
|
|
"""
|
2021-02-07 03:05:43 +03:00
|
|
|
lines = open_file(vectors_loc)
|
2020-09-29 11:58:50 +03:00
|
|
|
first_line = next(lines)
|
|
|
|
try:
|
2021-10-27 15:08:31 +03:00
|
|
|
shape = tuple(int(size) for size in first_line.split()[:2])
|
2020-09-29 11:58:50 +03:00
|
|
|
except ValueError:
|
|
|
|
shape = None
|
|
|
|
if shape is not None:
|
|
|
|
# All good, give the data
|
|
|
|
yield first_line
|
|
|
|
yield from lines
|
|
|
|
else:
|
|
|
|
# Figure out the shape, make it the first value, and then give the
|
|
|
|
# rest of the data.
|
|
|
|
width = len(first_line.split()) - 1
|
2021-02-07 03:05:43 +03:00
|
|
|
length = 1
|
|
|
|
for _ in lines:
|
|
|
|
length += 1
|
2020-09-29 11:58:50 +03:00
|
|
|
yield f"{length} {width}"
|
2021-02-07 03:05:43 +03:00
|
|
|
# Reading the lines in again from file. This to avoid having to
|
|
|
|
# store all the results in a list in memory
|
|
|
|
lines2 = open_file(vectors_loc)
|
|
|
|
yield from lines2
|
2022-08-22 13:04:30 +03:00
|
|
|
lines2.close()
|
|
|
|
lines.close()
|