2017-03-23 13:08:41 +03:00
|
|
|
# coding: utf8
|
|
|
|
from __future__ import unicode_literals, division, print_function
|
|
|
|
|
2017-05-22 13:28:58 +03:00
|
|
|
import plac
|
2018-12-10 11:46:53 +03:00
|
|
|
import os
|
2017-05-17 13:04:50 +03:00
|
|
|
from pathlib import Path
|
2017-09-21 03:17:10 +03:00
|
|
|
from thinc.neural._classes.model import Model
|
2017-05-23 11:06:53 +03:00
|
|
|
from timeit import default_timer as timer
|
2018-06-25 14:40:17 +03:00
|
|
|
import shutil
|
💫 Replace ujson, msgpack and dill/pickle/cloudpickle with srsly (#3003)
Remove hacks and wrappers, keep code in sync across our libraries and move spaCy a few steps closer to only depending on packages with binary wheels 🎉
See here: https://github.com/explosion/srsly
Serialization is hard, especially across Python versions and multiple platforms. After dealing with many subtle bugs over the years (encodings, locales, large files) our libraries like spaCy and Prodigy have steadily grown a number of utility functions to wrap the multiple serialization formats we need to support (especially json, msgpack and pickle). These wrapping functions ended up duplicated across our codebases, so we wanted to put them in one place.
At the same time, we noticed that having a lot of small dependencies was making maintainence harder, and making installation slower. To solve this, we've made srsly standalone, by including the component packages directly within it. This way we can provide all the serialization utilities we need in a single binary wheel.
srsly currently includes forks of the following packages:
ujson
msgpack
msgpack-numpy
cloudpickle
* WIP: replace json/ujson with srsly
* Replace ujson in examples
Use regular json instead of srsly to make code easier to read and follow
* Update requirements
* Fix imports
* Fix typos
* Replace msgpack with srsly
* Fix warning
2018-12-03 03:28:22 +03:00
|
|
|
import srsly
|
2018-11-30 22:16:14 +03:00
|
|
|
from wasabi import Printer
|
2018-12-10 11:46:53 +03:00
|
|
|
import contextlib
|
|
|
|
import random
|
2017-03-23 13:08:41 +03:00
|
|
|
|
2018-11-30 22:16:14 +03:00
|
|
|
from .._ml import create_default_optimizer
|
2018-02-17 20:11:11 +03:00
|
|
|
from ..attrs import PROB, IS_OOV, CLUSTER, LANG
|
2018-03-27 20:23:02 +03:00
|
|
|
from ..gold import GoldCorpus
|
2019-05-11 16:48:35 +03:00
|
|
|
from ..compat import path2str
|
2017-03-23 13:08:41 +03:00
|
|
|
from .. import util
|
2017-09-25 20:00:47 +03:00
|
|
|
from .. import about
|
2018-11-30 22:16:14 +03:00
|
|
|
|
|
|
|
|
2017-05-22 13:28:58 +03:00
|
|
|
@plac.annotations(
|
2018-11-30 22:16:14 +03:00
|
|
|
lang=("Model language", "positional", None, str),
|
|
|
|
output_path=("Output directory to store model in", "positional", None, Path),
|
|
|
|
train_path=("Location of JSON-formatted training data", "positional", None, Path),
|
|
|
|
dev_path=("Location of JSON-formatted development data", "positional", None, Path),
|
💫 Better support for semi-supervised learning (#3035)
The new spacy pretrain command implemented BERT/ULMFit/etc-like transfer learning, using our Language Modelling with Approximate Outputs version of BERT's cloze task. Pretraining is convenient, but in some ways it's a bit of a strange solution. All we're doing is initialising the weights. At the same time, we're putting a lot of work into our optimisation so that it's less sensitive to initial conditions, and more likely to find good optima. I discuss this a bit in the pseudo-rehearsal blog post: https://explosion.ai/blog/pseudo-rehearsal-catastrophic-forgetting
Support semi-supervised learning in spacy train
One obvious way to improve these pretraining methods is to do multi-task learning, instead of just transfer learning. This has been shown to work very well: https://arxiv.org/pdf/1809.08370.pdf . This patch makes it easy to do this sort of thing.
Add a new argument to spacy train, --raw-text. This takes a jsonl file with unlabelled data that can be used in arbitrary ways to do semi-supervised learning.
Add a new method to the Language class and to pipeline components, .rehearse(). This is like .update(), but doesn't expect GoldParse objects. It takes a batch of Doc objects, and performs an update on some semi-supervised objective.
Move the BERT-LMAO objective out from spacy/cli/pretrain.py into spacy/_ml.py, so we can create a new pipeline component, ClozeMultitask. This can be specified as a parser or NER multitask in the spacy train command. Example usage:
python -m spacy train en ./tmp ~/data/en-core-web/train/nw.json ~/data/en-core-web/dev/nw.json --pipeline parser --raw-textt ~/data/unlabelled/reddit-100k.jsonl --vectors en_vectors_web_lg --parser-multitasks cloze
Implement rehearsal methods for pipeline components
The new --raw-text argument and nlp.rehearse() method also gives us a good place to implement the the idea in the pseudo-rehearsal blog post in the parser. This works as follows:
Add a new nlp.resume_training() method. This allocates copies of pre-trained models in the pipeline, setting things up for the rehearsal updates. It also returns an optimizer object. This also greatly reduces confusion around the nlp.begin_training() method, which randomises the weights, making it not suitable for adding new labels or otherwise fine-tuning a pre-trained model.
Implement rehearsal updates on the Parser class, making it available for the dependency parser and NER. During rehearsal, the initial model is used to supervise the model being trained. The current model is asked to match the predictions of the initial model on some data. This minimises catastrophic forgetting, by keeping the model's predictions close to the original. See the blog post for details.
Implement rehearsal updates for tagger
Implement rehearsal updates for text categoriz
2018-12-10 18:25:33 +03:00
|
|
|
raw_text=(
|
|
|
|
"Path to jsonl file with unlabelled text documents.",
|
|
|
|
"option",
|
|
|
|
"rt",
|
|
|
|
Path,
|
|
|
|
),
|
2018-11-30 22:16:14 +03:00
|
|
|
base_model=("Name of model to update (optional)", "option", "b", str),
|
|
|
|
pipeline=("Comma-separated names of pipeline components", "option", "p", str),
|
|
|
|
vectors=("Model to load vectors from", "option", "v", str),
|
|
|
|
n_iter=("Number of iterations", "option", "n", int),
|
2019-04-22 15:31:25 +03:00
|
|
|
n_early_stopping=(
|
|
|
|
"Maximum number of training epochs without dev accuracy improvement",
|
|
|
|
"option",
|
|
|
|
"ne",
|
|
|
|
int,
|
|
|
|
),
|
2018-11-30 22:16:14 +03:00
|
|
|
n_examples=("Number of examples", "option", "ns", int),
|
2017-06-04 00:10:23 +03:00
|
|
|
use_gpu=("Use GPU", "option", "g", int),
|
2017-09-26 18:59:34 +03:00
|
|
|
version=("Model version", "option", "V", str),
|
2018-11-30 22:16:14 +03:00
|
|
|
meta_path=("Optional path to meta.json to use as base.", "option", "m", Path),
|
|
|
|
init_tok2vec=(
|
|
|
|
"Path to pretrained weights for the token-to-vector parts of the models. See 'spacy pretrain'. Experimental.",
|
|
|
|
"option",
|
|
|
|
"t2v",
|
|
|
|
Path,
|
|
|
|
),
|
|
|
|
parser_multitasks=(
|
|
|
|
"Side objectives for parser CNN, e.g. 'dep' or 'dep,tag'",
|
|
|
|
"option",
|
|
|
|
"pt",
|
|
|
|
str,
|
|
|
|
),
|
|
|
|
entity_multitasks=(
|
|
|
|
"Side objectives for NER CNN, e.g. 'dep' or 'dep,tag'",
|
|
|
|
"option",
|
|
|
|
"et",
|
|
|
|
str,
|
|
|
|
),
|
|
|
|
noise_level=("Amount of corruption for data augmentation", "option", "nl", float),
|
2019-03-16 17:02:39 +03:00
|
|
|
eval_beam_widths=("Beam widths to evaluate, e.g. 4,8", "option", "bw", str),
|
2018-11-30 22:16:14 +03:00
|
|
|
gold_preproc=("Use gold preprocessing", "flag", "G", bool),
|
|
|
|
learn_tokens=("Make parser learn gold-standard tokenization", "flag", "T", bool),
|
|
|
|
verbose=("Display more information for debug", "flag", "VV", bool),
|
|
|
|
debug=("Run data diagnostics before training", "flag", "D", bool),
|
|
|
|
)
|
|
|
|
def train(
|
|
|
|
lang,
|
|
|
|
output_path,
|
|
|
|
train_path,
|
|
|
|
dev_path,
|
💫 Better support for semi-supervised learning (#3035)
The new spacy pretrain command implemented BERT/ULMFit/etc-like transfer learning, using our Language Modelling with Approximate Outputs version of BERT's cloze task. Pretraining is convenient, but in some ways it's a bit of a strange solution. All we're doing is initialising the weights. At the same time, we're putting a lot of work into our optimisation so that it's less sensitive to initial conditions, and more likely to find good optima. I discuss this a bit in the pseudo-rehearsal blog post: https://explosion.ai/blog/pseudo-rehearsal-catastrophic-forgetting
Support semi-supervised learning in spacy train
One obvious way to improve these pretraining methods is to do multi-task learning, instead of just transfer learning. This has been shown to work very well: https://arxiv.org/pdf/1809.08370.pdf . This patch makes it easy to do this sort of thing.
Add a new argument to spacy train, --raw-text. This takes a jsonl file with unlabelled data that can be used in arbitrary ways to do semi-supervised learning.
Add a new method to the Language class and to pipeline components, .rehearse(). This is like .update(), but doesn't expect GoldParse objects. It takes a batch of Doc objects, and performs an update on some semi-supervised objective.
Move the BERT-LMAO objective out from spacy/cli/pretrain.py into spacy/_ml.py, so we can create a new pipeline component, ClozeMultitask. This can be specified as a parser or NER multitask in the spacy train command. Example usage:
python -m spacy train en ./tmp ~/data/en-core-web/train/nw.json ~/data/en-core-web/dev/nw.json --pipeline parser --raw-textt ~/data/unlabelled/reddit-100k.jsonl --vectors en_vectors_web_lg --parser-multitasks cloze
Implement rehearsal methods for pipeline components
The new --raw-text argument and nlp.rehearse() method also gives us a good place to implement the the idea in the pseudo-rehearsal blog post in the parser. This works as follows:
Add a new nlp.resume_training() method. This allocates copies of pre-trained models in the pipeline, setting things up for the rehearsal updates. It also returns an optimizer object. This also greatly reduces confusion around the nlp.begin_training() method, which randomises the weights, making it not suitable for adding new labels or otherwise fine-tuning a pre-trained model.
Implement rehearsal updates on the Parser class, making it available for the dependency parser and NER. During rehearsal, the initial model is used to supervise the model being trained. The current model is asked to match the predictions of the initial model on some data. This minimises catastrophic forgetting, by keeping the model's predictions close to the original. See the blog post for details.
Implement rehearsal updates for tagger
Implement rehearsal updates for text categoriz
2018-12-10 18:25:33 +03:00
|
|
|
raw_text=None,
|
2018-11-30 22:16:14 +03:00
|
|
|
base_model=None,
|
|
|
|
pipeline="tagger,parser,ner",
|
|
|
|
vectors=None,
|
|
|
|
n_iter=30,
|
2019-04-22 15:31:25 +03:00
|
|
|
n_early_stopping=None,
|
2018-11-30 22:16:14 +03:00
|
|
|
n_examples=0,
|
|
|
|
use_gpu=-1,
|
|
|
|
version="0.0.0",
|
|
|
|
meta_path=None,
|
|
|
|
init_tok2vec=None,
|
|
|
|
parser_multitasks="",
|
|
|
|
entity_multitasks="",
|
|
|
|
noise_level=0.0,
|
2019-03-16 17:02:39 +03:00
|
|
|
eval_beam_widths="",
|
2018-11-30 22:16:14 +03:00
|
|
|
gold_preproc=False,
|
|
|
|
learn_tokens=False,
|
|
|
|
verbose=False,
|
|
|
|
debug=False,
|
|
|
|
):
|
2017-05-27 21:01:46 +03:00
|
|
|
"""
|
2018-11-30 22:16:14 +03:00
|
|
|
Train or update a spaCy model. Requires data to be formatted in spaCy's
|
|
|
|
JSON format. To convert data from other formats, use the `spacy convert`
|
|
|
|
command.
|
2017-05-27 21:01:46 +03:00
|
|
|
"""
|
2019-09-09 17:32:11 +03:00
|
|
|
|
|
|
|
# temp fix to avoid import issues cf https://github.com/explosion/spaCy/issues/4200
|
|
|
|
import tqdm
|
|
|
|
|
2018-11-30 22:16:14 +03:00
|
|
|
msg = Printer()
|
2018-02-13 14:42:23 +03:00
|
|
|
util.fix_random_seed()
|
2018-11-30 22:16:14 +03:00
|
|
|
util.set_env_log(verbose)
|
|
|
|
|
|
|
|
# Make sure all files and paths exists if they are needed
|
|
|
|
train_path = util.ensure_path(train_path)
|
|
|
|
dev_path = util.ensure_path(dev_path)
|
2017-09-25 20:00:47 +03:00
|
|
|
meta_path = util.ensure_path(meta_path)
|
2019-04-15 13:04:36 +03:00
|
|
|
output_path = util.ensure_path(output_path)
|
💫 Better support for semi-supervised learning (#3035)
The new spacy pretrain command implemented BERT/ULMFit/etc-like transfer learning, using our Language Modelling with Approximate Outputs version of BERT's cloze task. Pretraining is convenient, but in some ways it's a bit of a strange solution. All we're doing is initialising the weights. At the same time, we're putting a lot of work into our optimisation so that it's less sensitive to initial conditions, and more likely to find good optima. I discuss this a bit in the pseudo-rehearsal blog post: https://explosion.ai/blog/pseudo-rehearsal-catastrophic-forgetting
Support semi-supervised learning in spacy train
One obvious way to improve these pretraining methods is to do multi-task learning, instead of just transfer learning. This has been shown to work very well: https://arxiv.org/pdf/1809.08370.pdf . This patch makes it easy to do this sort of thing.
Add a new argument to spacy train, --raw-text. This takes a jsonl file with unlabelled data that can be used in arbitrary ways to do semi-supervised learning.
Add a new method to the Language class and to pipeline components, .rehearse(). This is like .update(), but doesn't expect GoldParse objects. It takes a batch of Doc objects, and performs an update on some semi-supervised objective.
Move the BERT-LMAO objective out from spacy/cli/pretrain.py into spacy/_ml.py, so we can create a new pipeline component, ClozeMultitask. This can be specified as a parser or NER multitask in the spacy train command. Example usage:
python -m spacy train en ./tmp ~/data/en-core-web/train/nw.json ~/data/en-core-web/dev/nw.json --pipeline parser --raw-textt ~/data/unlabelled/reddit-100k.jsonl --vectors en_vectors_web_lg --parser-multitasks cloze
Implement rehearsal methods for pipeline components
The new --raw-text argument and nlp.rehearse() method also gives us a good place to implement the the idea in the pseudo-rehearsal blog post in the parser. This works as follows:
Add a new nlp.resume_training() method. This allocates copies of pre-trained models in the pipeline, setting things up for the rehearsal updates. It also returns an optimizer object. This also greatly reduces confusion around the nlp.begin_training() method, which randomises the weights, making it not suitable for adding new labels or otherwise fine-tuning a pre-trained model.
Implement rehearsal updates on the Parser class, making it available for the dependency parser and NER. During rehearsal, the initial model is used to supervise the model being trained. The current model is asked to match the predictions of the initial model on some data. This minimises catastrophic forgetting, by keeping the model's predictions close to the original. See the blog post for details.
Implement rehearsal updates for tagger
Implement rehearsal updates for text categoriz
2018-12-10 18:25:33 +03:00
|
|
|
if raw_text is not None:
|
|
|
|
raw_text = list(srsly.read_jsonl(raw_text))
|
2018-11-30 22:16:14 +03:00
|
|
|
if not train_path or not train_path.exists():
|
2018-12-08 13:49:43 +03:00
|
|
|
msg.fail("Training data not found", train_path, exits=1)
|
2018-11-30 22:16:14 +03:00
|
|
|
if not dev_path or not dev_path.exists():
|
2018-12-08 13:49:43 +03:00
|
|
|
msg.fail("Development data not found", dev_path, exits=1)
|
2017-09-25 20:00:47 +03:00
|
|
|
if meta_path is not None and not meta_path.exists():
|
2018-12-08 13:49:43 +03:00
|
|
|
msg.fail("Can't find model meta.json", meta_path, exits=1)
|
💫 Replace ujson, msgpack and dill/pickle/cloudpickle with srsly (#3003)
Remove hacks and wrappers, keep code in sync across our libraries and move spaCy a few steps closer to only depending on packages with binary wheels 🎉
See here: https://github.com/explosion/srsly
Serialization is hard, especially across Python versions and multiple platforms. After dealing with many subtle bugs over the years (encodings, locales, large files) our libraries like spaCy and Prodigy have steadily grown a number of utility functions to wrap the multiple serialization formats we need to support (especially json, msgpack and pickle). These wrapping functions ended up duplicated across our codebases, so we wanted to put them in one place.
At the same time, we noticed that having a lot of small dependencies was making maintainence harder, and making installation slower. To solve this, we've made srsly standalone, by including the component packages directly within it. This way we can provide all the serialization utilities we need in a single binary wheel.
srsly currently includes forks of the following packages:
ujson
msgpack
msgpack-numpy
cloudpickle
* WIP: replace json/ujson with srsly
* Replace ujson in examples
Use regular json instead of srsly to make code easier to read and follow
* Update requirements
* Fix imports
* Fix typos
* Replace msgpack with srsly
* Fix warning
2018-12-03 03:28:22 +03:00
|
|
|
meta = srsly.read_json(meta_path) if meta_path else {}
|
2018-11-30 22:16:14 +03:00
|
|
|
if output_path.exists() and [p for p in output_path.iterdir() if p.is_dir()]:
|
2018-12-08 13:49:43 +03:00
|
|
|
msg.warn(
|
|
|
|
"Output directory is not empty",
|
|
|
|
"This can lead to unintended side effects when saving the model. "
|
|
|
|
"Please use an empty directory or a different path instead. If "
|
|
|
|
"the specified output path doesn't exist, the directory will be "
|
|
|
|
"created for you.",
|
|
|
|
)
|
2018-03-27 20:23:02 +03:00
|
|
|
if not output_path.exists():
|
|
|
|
output_path.mkdir()
|
2017-03-23 13:08:41 +03:00
|
|
|
|
2018-12-07 22:54:35 +03:00
|
|
|
# Take dropout and batch size as generators of values -- dropout
|
|
|
|
# starts high and decays sharply, to force the optimizer to explore.
|
|
|
|
# Batch size starts at 1 and grows, so that we make updates quickly
|
|
|
|
# at the beginning of training.
|
|
|
|
dropout_rates = util.decaying(
|
2018-12-08 21:59:11 +03:00
|
|
|
util.env_opt("dropout_from", 0.2),
|
|
|
|
util.env_opt("dropout_to", 0.2),
|
2018-12-07 22:54:35 +03:00
|
|
|
util.env_opt("dropout_decay", 0.0),
|
|
|
|
)
|
|
|
|
batch_sizes = util.compounding(
|
|
|
|
util.env_opt("batch_from", 100.0),
|
2018-12-18 02:15:39 +03:00
|
|
|
util.env_opt("batch_to", 1000.0),
|
2018-12-07 22:54:35 +03:00
|
|
|
util.env_opt("batch_compound", 1.001),
|
|
|
|
)
|
|
|
|
|
2019-03-16 17:02:39 +03:00
|
|
|
if not eval_beam_widths:
|
|
|
|
eval_beam_widths = [1]
|
|
|
|
else:
|
|
|
|
eval_beam_widths = [int(bw) for bw in eval_beam_widths.split(",")]
|
|
|
|
if 1 not in eval_beam_widths:
|
|
|
|
eval_beam_widths.append(1)
|
|
|
|
eval_beam_widths.sort()
|
2019-03-16 17:55:31 +03:00
|
|
|
has_beam_widths = eval_beam_widths != [1]
|
2019-03-16 17:02:39 +03:00
|
|
|
|
2018-11-30 22:16:14 +03:00
|
|
|
# Set up the base model and pipeline. If a base model is specified, load
|
|
|
|
# the model and make sure the pipeline matches the pipeline setting. If
|
|
|
|
# training starts from a blank model, intitalize the language class.
|
|
|
|
pipeline = [p.strip() for p in pipeline.split(",")]
|
2018-12-08 13:49:43 +03:00
|
|
|
msg.text("Training pipeline: {}".format(pipeline))
|
2018-11-30 22:16:14 +03:00
|
|
|
if base_model:
|
2018-12-08 13:49:43 +03:00
|
|
|
msg.text("Starting with base model '{}'".format(base_model))
|
2018-11-30 22:16:14 +03:00
|
|
|
nlp = util.load_model(base_model)
|
|
|
|
if nlp.lang != lang:
|
2018-12-08 13:49:43 +03:00
|
|
|
msg.fail(
|
|
|
|
"Model language ('{}') doesn't match language specified as "
|
|
|
|
"`lang` argument ('{}') ".format(nlp.lang, lang),
|
|
|
|
exits=1,
|
|
|
|
)
|
2018-11-30 22:16:14 +03:00
|
|
|
other_pipes = [pipe for pipe in nlp.pipe_names if pipe not in pipeline]
|
|
|
|
nlp.disable_pipes(*other_pipes)
|
|
|
|
for pipe in pipeline:
|
|
|
|
if pipe not in nlp.pipe_names:
|
2019-08-23 18:54:00 +03:00
|
|
|
if pipe == "parser":
|
|
|
|
pipe_cfg = {"learn_tokens": learn_tokens}
|
|
|
|
else:
|
|
|
|
pipe_cfg = {}
|
|
|
|
nlp.add_pipe(nlp.create_pipe(pipe, config=pipe_cfg))
|
2018-11-30 22:16:14 +03:00
|
|
|
else:
|
2018-12-08 13:49:43 +03:00
|
|
|
msg.text("Starting with blank model '{}'".format(lang))
|
2018-11-30 22:16:14 +03:00
|
|
|
lang_cls = util.get_lang_class(lang)
|
|
|
|
nlp = lang_cls()
|
|
|
|
for pipe in pipeline:
|
2019-08-23 18:54:00 +03:00
|
|
|
if pipe == "parser":
|
|
|
|
pipe_cfg = {"learn_tokens": learn_tokens}
|
|
|
|
else:
|
|
|
|
pipe_cfg = {}
|
|
|
|
nlp.add_pipe(nlp.create_pipe(pipe, config=pipe_cfg))
|
2017-03-23 13:08:41 +03:00
|
|
|
|
2017-09-23 04:00:40 +03:00
|
|
|
if vectors:
|
2018-12-08 13:49:43 +03:00
|
|
|
msg.text("Loading vector from model '{}'".format(vectors))
|
2018-11-30 22:16:14 +03:00
|
|
|
_load_vectors(nlp, vectors)
|
|
|
|
|
|
|
|
# Multitask objectives
|
|
|
|
multitask_options = [("parser", parser_multitasks), ("ner", entity_multitasks)]
|
|
|
|
for pipe_name, multitasks in multitask_options:
|
|
|
|
if multitasks:
|
|
|
|
if pipe_name not in pipeline:
|
2018-12-08 13:49:43 +03:00
|
|
|
msg.fail(
|
|
|
|
"Can't use multitask objective without '{}' in the "
|
|
|
|
"pipeline".format(pipe_name)
|
|
|
|
)
|
2018-11-30 22:16:14 +03:00
|
|
|
pipe = nlp.get_pipe(pipe_name)
|
|
|
|
for objective in multitasks.split(","):
|
|
|
|
pipe.add_multitask_objective(objective)
|
|
|
|
|
|
|
|
# Prepare training corpus
|
2018-12-08 13:49:43 +03:00
|
|
|
msg.text("Counting training words (limit={})".format(n_examples))
|
2018-11-30 22:16:14 +03:00
|
|
|
corpus = GoldCorpus(train_path, dev_path, limit=n_examples)
|
|
|
|
n_train_words = corpus.count_train()
|
|
|
|
|
|
|
|
if base_model:
|
|
|
|
# Start with an existing model, use default optimizer
|
|
|
|
optimizer = create_default_optimizer(Model.ops)
|
|
|
|
else:
|
|
|
|
# Start with a blank model, call begin_training
|
|
|
|
optimizer = nlp.begin_training(lambda: corpus.train_tuples, device=use_gpu)
|
2018-12-01 16:42:35 +03:00
|
|
|
|
2017-09-02 20:46:01 +03:00
|
|
|
nlp._optimizer = None
|
2017-05-26 00:16:30 +03:00
|
|
|
|
2018-11-30 22:16:14 +03:00
|
|
|
# Load in pre-trained weights
|
|
|
|
if init_tok2vec is not None:
|
|
|
|
components = _load_pretrained_tok2vec(nlp, init_tok2vec)
|
2018-12-08 13:49:43 +03:00
|
|
|
msg.text("Loaded pretrained tok2vec for: {}".format(components))
|
2018-11-30 22:16:14 +03:00
|
|
|
|
2018-12-08 13:49:43 +03:00
|
|
|
# fmt: off
|
2019-03-16 18:04:15 +03:00
|
|
|
row_head = ["Itn", "Dep Loss", "NER Loss", "UAS", "NER P", "NER R", "NER F", "Tag %", "Token %", "CPU WPS", "GPU WPS"]
|
|
|
|
row_widths = [3, 10, 10, 7, 7, 7, 7, 7, 7, 7, 7]
|
2019-03-16 17:55:31 +03:00
|
|
|
if has_beam_widths:
|
|
|
|
row_head.insert(1, "Beam W.")
|
|
|
|
row_widths.insert(1, 7)
|
|
|
|
row_settings = {"widths": row_widths, "aligns": tuple(["r" for i in row_head]), "spacing": 2}
|
2018-12-08 13:49:43 +03:00
|
|
|
# fmt: on
|
|
|
|
print("")
|
|
|
|
msg.row(row_head, **row_settings)
|
|
|
|
msg.row(["-" * width for width in row_settings["widths"]], **row_settings)
|
2017-05-26 13:52:09 +03:00
|
|
|
try:
|
2019-04-15 13:04:36 +03:00
|
|
|
iter_since_best = 0
|
2019-04-22 15:31:11 +03:00
|
|
|
best_score = 0.0
|
2017-05-26 13:52:09 +03:00
|
|
|
for i in range(n_iter):
|
2018-11-30 22:16:14 +03:00
|
|
|
train_docs = corpus.train_docs(
|
|
|
|
nlp, noise_level=noise_level, gold_preproc=gold_preproc, max_length=0
|
|
|
|
)
|
💫 Better support for semi-supervised learning (#3035)
The new spacy pretrain command implemented BERT/ULMFit/etc-like transfer learning, using our Language Modelling with Approximate Outputs version of BERT's cloze task. Pretraining is convenient, but in some ways it's a bit of a strange solution. All we're doing is initialising the weights. At the same time, we're putting a lot of work into our optimisation so that it's less sensitive to initial conditions, and more likely to find good optima. I discuss this a bit in the pseudo-rehearsal blog post: https://explosion.ai/blog/pseudo-rehearsal-catastrophic-forgetting
Support semi-supervised learning in spacy train
One obvious way to improve these pretraining methods is to do multi-task learning, instead of just transfer learning. This has been shown to work very well: https://arxiv.org/pdf/1809.08370.pdf . This patch makes it easy to do this sort of thing.
Add a new argument to spacy train, --raw-text. This takes a jsonl file with unlabelled data that can be used in arbitrary ways to do semi-supervised learning.
Add a new method to the Language class and to pipeline components, .rehearse(). This is like .update(), but doesn't expect GoldParse objects. It takes a batch of Doc objects, and performs an update on some semi-supervised objective.
Move the BERT-LMAO objective out from spacy/cli/pretrain.py into spacy/_ml.py, so we can create a new pipeline component, ClozeMultitask. This can be specified as a parser or NER multitask in the spacy train command. Example usage:
python -m spacy train en ./tmp ~/data/en-core-web/train/nw.json ~/data/en-core-web/dev/nw.json --pipeline parser --raw-textt ~/data/unlabelled/reddit-100k.jsonl --vectors en_vectors_web_lg --parser-multitasks cloze
Implement rehearsal methods for pipeline components
The new --raw-text argument and nlp.rehearse() method also gives us a good place to implement the the idea in the pseudo-rehearsal blog post in the parser. This works as follows:
Add a new nlp.resume_training() method. This allocates copies of pre-trained models in the pipeline, setting things up for the rehearsal updates. It also returns an optimizer object. This also greatly reduces confusion around the nlp.begin_training() method, which randomises the weights, making it not suitable for adding new labels or otherwise fine-tuning a pre-trained model.
Implement rehearsal updates on the Parser class, making it available for the dependency parser and NER. During rehearsal, the initial model is used to supervise the model being trained. The current model is asked to match the predictions of the initial model on some data. This minimises catastrophic forgetting, by keeping the model's predictions close to the original. See the blog post for details.
Implement rehearsal updates for tagger
Implement rehearsal updates for text categoriz
2018-12-10 18:25:33 +03:00
|
|
|
if raw_text:
|
|
|
|
random.shuffle(raw_text)
|
|
|
|
raw_batches = util.minibatch(
|
|
|
|
(nlp.make_doc(rt["text"]) for rt in raw_text), size=8
|
|
|
|
)
|
2018-03-27 20:23:02 +03:00
|
|
|
words_seen = 0
|
2018-12-20 15:57:00 +03:00
|
|
|
with tqdm.tqdm(total=n_train_words, leave=False) as pbar:
|
2017-05-26 13:52:09 +03:00
|
|
|
losses = {}
|
2018-11-30 22:16:14 +03:00
|
|
|
for batch in util.minibatch_by_words(train_docs, size=batch_sizes):
|
2017-11-03 03:54:54 +03:00
|
|
|
if not batch:
|
|
|
|
continue
|
2017-05-26 13:52:09 +03:00
|
|
|
docs, golds = zip(*batch)
|
2018-11-30 22:16:14 +03:00
|
|
|
nlp.update(
|
|
|
|
docs,
|
|
|
|
golds,
|
|
|
|
sgd=optimizer,
|
|
|
|
drop=next(dropout_rates),
|
|
|
|
losses=losses,
|
|
|
|
)
|
💫 Better support for semi-supervised learning (#3035)
The new spacy pretrain command implemented BERT/ULMFit/etc-like transfer learning, using our Language Modelling with Approximate Outputs version of BERT's cloze task. Pretraining is convenient, but in some ways it's a bit of a strange solution. All we're doing is initialising the weights. At the same time, we're putting a lot of work into our optimisation so that it's less sensitive to initial conditions, and more likely to find good optima. I discuss this a bit in the pseudo-rehearsal blog post: https://explosion.ai/blog/pseudo-rehearsal-catastrophic-forgetting
Support semi-supervised learning in spacy train
One obvious way to improve these pretraining methods is to do multi-task learning, instead of just transfer learning. This has been shown to work very well: https://arxiv.org/pdf/1809.08370.pdf . This patch makes it easy to do this sort of thing.
Add a new argument to spacy train, --raw-text. This takes a jsonl file with unlabelled data that can be used in arbitrary ways to do semi-supervised learning.
Add a new method to the Language class and to pipeline components, .rehearse(). This is like .update(), but doesn't expect GoldParse objects. It takes a batch of Doc objects, and performs an update on some semi-supervised objective.
Move the BERT-LMAO objective out from spacy/cli/pretrain.py into spacy/_ml.py, so we can create a new pipeline component, ClozeMultitask. This can be specified as a parser or NER multitask in the spacy train command. Example usage:
python -m spacy train en ./tmp ~/data/en-core-web/train/nw.json ~/data/en-core-web/dev/nw.json --pipeline parser --raw-textt ~/data/unlabelled/reddit-100k.jsonl --vectors en_vectors_web_lg --parser-multitasks cloze
Implement rehearsal methods for pipeline components
The new --raw-text argument and nlp.rehearse() method also gives us a good place to implement the the idea in the pseudo-rehearsal blog post in the parser. This works as follows:
Add a new nlp.resume_training() method. This allocates copies of pre-trained models in the pipeline, setting things up for the rehearsal updates. It also returns an optimizer object. This also greatly reduces confusion around the nlp.begin_training() method, which randomises the weights, making it not suitable for adding new labels or otherwise fine-tuning a pre-trained model.
Implement rehearsal updates on the Parser class, making it available for the dependency parser and NER. During rehearsal, the initial model is used to supervise the model being trained. The current model is asked to match the predictions of the initial model on some data. This minimises catastrophic forgetting, by keeping the model's predictions close to the original. See the blog post for details.
Implement rehearsal updates for tagger
Implement rehearsal updates for text categoriz
2018-12-10 18:25:33 +03:00
|
|
|
if raw_text:
|
|
|
|
# If raw text is available, perform 'rehearsal' updates,
|
|
|
|
# which use unlabelled data to reduce overfitting.
|
|
|
|
raw_batch = list(next(raw_batches))
|
|
|
|
nlp.rehearse(raw_batch, sgd=optimizer, losses=losses)
|
|
|
|
if not int(os.environ.get("LOG_FRIENDLY", 0)):
|
2018-12-10 11:46:53 +03:00
|
|
|
pbar.update(sum(len(doc) for doc in docs))
|
2018-03-27 20:23:02 +03:00
|
|
|
words_seen += sum(len(doc) for doc in docs)
|
2017-05-26 13:52:09 +03:00
|
|
|
with nlp.use_params(optimizer.averages):
|
2017-06-03 21:28:20 +03:00
|
|
|
util.set_env_log(False)
|
2018-11-30 22:16:14 +03:00
|
|
|
epoch_model_path = output_path / ("model%d" % i)
|
2017-06-03 21:28:20 +03:00
|
|
|
nlp.to_disk(epoch_model_path)
|
2017-10-10 20:51:20 +03:00
|
|
|
nlp_loaded = util.load_model_from_path(epoch_model_path)
|
2019-03-16 17:02:39 +03:00
|
|
|
for beam_width in eval_beam_widths:
|
2019-03-15 17:18:28 +03:00
|
|
|
for name, component in nlp_loaded.pipeline:
|
|
|
|
if hasattr(component, "cfg"):
|
|
|
|
component.cfg["beam_width"] = beam_width
|
2019-03-16 17:55:13 +03:00
|
|
|
dev_docs = list(
|
|
|
|
corpus.dev_docs(nlp_loaded, gold_preproc=gold_preproc)
|
|
|
|
)
|
2019-03-15 17:18:28 +03:00
|
|
|
nwords = sum(len(doc_gold[0]) for doc_gold in dev_docs)
|
|
|
|
start_time = timer()
|
|
|
|
scorer = nlp_loaded.evaluate(dev_docs, debug)
|
|
|
|
end_time = timer()
|
|
|
|
if use_gpu < 0:
|
|
|
|
gpu_wps = None
|
2018-11-30 22:16:14 +03:00
|
|
|
cpu_wps = nwords / (end_time - start_time)
|
2019-03-15 17:18:28 +03:00
|
|
|
else:
|
|
|
|
gpu_wps = nwords / (end_time - start_time)
|
|
|
|
with Model.use_device("cpu"):
|
|
|
|
nlp_loaded = util.load_model_from_path(epoch_model_path)
|
2019-04-15 13:04:36 +03:00
|
|
|
for name, component in nlp_loaded.pipeline:
|
|
|
|
if hasattr(component, "cfg"):
|
|
|
|
component.cfg["beam_width"] = beam_width
|
2019-03-15 17:18:28 +03:00
|
|
|
dev_docs = list(
|
|
|
|
corpus.dev_docs(nlp_loaded, gold_preproc=gold_preproc)
|
|
|
|
)
|
|
|
|
start_time = timer()
|
|
|
|
scorer = nlp_loaded.evaluate(dev_docs)
|
|
|
|
end_time = timer()
|
|
|
|
cpu_wps = nwords / (end_time - start_time)
|
|
|
|
acc_loc = output_path / ("model%d" % i) / "accuracy.json"
|
|
|
|
srsly.write_json(acc_loc, scorer.scores)
|
|
|
|
|
|
|
|
# Update model meta.json
|
|
|
|
meta["lang"] = nlp.lang
|
|
|
|
meta["pipeline"] = nlp.pipe_names
|
|
|
|
meta["spacy_version"] = ">=%s" % about.__version__
|
|
|
|
if beam_width == 1:
|
2019-03-16 17:55:13 +03:00
|
|
|
meta["speed"] = {
|
|
|
|
"nwords": nwords,
|
|
|
|
"cpu": cpu_wps,
|
|
|
|
"gpu": gpu_wps,
|
|
|
|
}
|
2019-03-15 17:18:28 +03:00
|
|
|
meta["accuracy"] = scorer.scores
|
|
|
|
else:
|
|
|
|
meta.setdefault("beam_accuracy", {})
|
|
|
|
meta.setdefault("beam_speed", {})
|
|
|
|
meta["beam_accuracy"][beam_width] = scorer.scores
|
2019-03-16 17:55:13 +03:00
|
|
|
meta["beam_speed"][beam_width] = {
|
|
|
|
"nwords": nwords,
|
|
|
|
"cpu": cpu_wps,
|
|
|
|
"gpu": gpu_wps,
|
|
|
|
}
|
2019-03-15 17:18:28 +03:00
|
|
|
meta["vectors"] = {
|
|
|
|
"width": nlp.vocab.vectors_length,
|
|
|
|
"vectors": len(nlp.vocab.vectors),
|
|
|
|
"keys": nlp.vocab.vectors.n_keys,
|
2019-03-16 17:55:13 +03:00
|
|
|
"name": nlp.vocab.vectors.name,
|
|
|
|
}
|
2019-03-15 17:18:28 +03:00
|
|
|
meta.setdefault("name", "model%d" % i)
|
|
|
|
meta.setdefault("version", version)
|
|
|
|
meta_loc = output_path / ("model%d" % i) / "meta.json"
|
|
|
|
srsly.write_json(meta_loc, meta)
|
|
|
|
util.set_env_log(verbose)
|
|
|
|
|
|
|
|
progress = _get_progress(
|
2019-03-16 18:02:47 +03:00
|
|
|
i,
|
|
|
|
losses,
|
|
|
|
scorer.scores,
|
|
|
|
beam_width=beam_width if has_beam_widths else None,
|
|
|
|
cpu_wps=cpu_wps,
|
|
|
|
gpu_wps=gpu_wps,
|
2019-03-15 17:18:28 +03:00
|
|
|
)
|
|
|
|
msg.row(progress, **row_settings)
|
2019-04-22 15:31:11 +03:00
|
|
|
# Early stopping
|
2019-04-22 15:31:25 +03:00
|
|
|
if n_early_stopping is not None:
|
2019-04-15 13:04:36 +03:00
|
|
|
current_score = _score_for_model(meta)
|
|
|
|
if current_score < best_score:
|
|
|
|
iter_since_best += 1
|
|
|
|
else:
|
|
|
|
iter_since_best = 0
|
|
|
|
best_score = current_score
|
2019-04-22 15:31:25 +03:00
|
|
|
if iter_since_best >= n_early_stopping:
|
2019-04-22 15:31:11 +03:00
|
|
|
msg.text(
|
|
|
|
"Early stopping, best iteration "
|
|
|
|
"is: {}".format(i - iter_since_best)
|
|
|
|
)
|
|
|
|
msg.text(
|
|
|
|
"Best score = {}; Final iteration "
|
|
|
|
"score = {}".format(best_score, current_score)
|
|
|
|
)
|
2019-04-15 13:04:36 +03:00
|
|
|
break
|
2017-05-26 13:52:09 +03:00
|
|
|
finally:
|
2018-12-08 13:49:43 +03:00
|
|
|
with nlp.use_params(optimizer.averages):
|
|
|
|
final_model_path = output_path / "model-final"
|
|
|
|
nlp.to_disk(final_model_path)
|
|
|
|
msg.good("Saved model to output directory", final_model_path)
|
|
|
|
with msg.loading("Creating best model..."):
|
|
|
|
best_model_path = _collate_best_model(meta, output_path, nlp.pipe_names)
|
|
|
|
msg.good("Created best model", best_model_path)
|
2018-11-30 22:16:14 +03:00
|
|
|
|
2019-04-22 15:31:11 +03:00
|
|
|
|
2019-04-15 13:04:36 +03:00
|
|
|
def _score_for_model(meta):
|
|
|
|
""" Returns mean score between tasks in pipeline that can be used for early stopping. """
|
|
|
|
mean_acc = list()
|
2019-04-22 15:31:11 +03:00
|
|
|
pipes = meta["pipeline"]
|
|
|
|
acc = meta["accuracy"]
|
|
|
|
if "tagger" in pipes:
|
|
|
|
mean_acc.append(acc["tags_acc"])
|
|
|
|
if "parser" in pipes:
|
|
|
|
mean_acc.append((acc["uas"] + acc["las"]) / 2)
|
|
|
|
if "ner" in pipes:
|
|
|
|
mean_acc.append((acc["ents_p"] + acc["ents_r"] + acc["ents_f"]) / 3)
|
2019-04-15 13:04:36 +03:00
|
|
|
return sum(mean_acc) / len(mean_acc)
|
2018-11-30 22:16:14 +03:00
|
|
|
|
2019-04-22 15:31:11 +03:00
|
|
|
|
2018-12-10 11:46:53 +03:00
|
|
|
@contextlib.contextmanager
|
|
|
|
def _create_progress_bar(total):
|
2019-09-09 17:32:11 +03:00
|
|
|
# temp fix to avoid import issues cf https://github.com/explosion/spaCy/issues/4200
|
|
|
|
import tqdm
|
|
|
|
|
💫 Better support for semi-supervised learning (#3035)
The new spacy pretrain command implemented BERT/ULMFit/etc-like transfer learning, using our Language Modelling with Approximate Outputs version of BERT's cloze task. Pretraining is convenient, but in some ways it's a bit of a strange solution. All we're doing is initialising the weights. At the same time, we're putting a lot of work into our optimisation so that it's less sensitive to initial conditions, and more likely to find good optima. I discuss this a bit in the pseudo-rehearsal blog post: https://explosion.ai/blog/pseudo-rehearsal-catastrophic-forgetting
Support semi-supervised learning in spacy train
One obvious way to improve these pretraining methods is to do multi-task learning, instead of just transfer learning. This has been shown to work very well: https://arxiv.org/pdf/1809.08370.pdf . This patch makes it easy to do this sort of thing.
Add a new argument to spacy train, --raw-text. This takes a jsonl file with unlabelled data that can be used in arbitrary ways to do semi-supervised learning.
Add a new method to the Language class and to pipeline components, .rehearse(). This is like .update(), but doesn't expect GoldParse objects. It takes a batch of Doc objects, and performs an update on some semi-supervised objective.
Move the BERT-LMAO objective out from spacy/cli/pretrain.py into spacy/_ml.py, so we can create a new pipeline component, ClozeMultitask. This can be specified as a parser or NER multitask in the spacy train command. Example usage:
python -m spacy train en ./tmp ~/data/en-core-web/train/nw.json ~/data/en-core-web/dev/nw.json --pipeline parser --raw-textt ~/data/unlabelled/reddit-100k.jsonl --vectors en_vectors_web_lg --parser-multitasks cloze
Implement rehearsal methods for pipeline components
The new --raw-text argument and nlp.rehearse() method also gives us a good place to implement the the idea in the pseudo-rehearsal blog post in the parser. This works as follows:
Add a new nlp.resume_training() method. This allocates copies of pre-trained models in the pipeline, setting things up for the rehearsal updates. It also returns an optimizer object. This also greatly reduces confusion around the nlp.begin_training() method, which randomises the weights, making it not suitable for adding new labels or otherwise fine-tuning a pre-trained model.
Implement rehearsal updates on the Parser class, making it available for the dependency parser and NER. During rehearsal, the initial model is used to supervise the model being trained. The current model is asked to match the predictions of the initial model on some data. This minimises catastrophic forgetting, by keeping the model's predictions close to the original. See the blog post for details.
Implement rehearsal updates for tagger
Implement rehearsal updates for text categoriz
2018-12-10 18:25:33 +03:00
|
|
|
if int(os.environ.get("LOG_FRIENDLY", 0)):
|
2018-12-10 11:46:53 +03:00
|
|
|
yield
|
|
|
|
else:
|
|
|
|
pbar = tqdm.tqdm(total=total, leave=False)
|
|
|
|
yield pbar
|
|
|
|
|
|
|
|
|
2018-11-30 22:16:14 +03:00
|
|
|
def _load_vectors(nlp, vectors):
|
|
|
|
util.load_model(vectors, vocab=nlp.vocab)
|
|
|
|
for lex in nlp.vocab:
|
|
|
|
values = {}
|
|
|
|
for attr, func in nlp.vocab.lex_attr_getters.items():
|
|
|
|
# These attrs are expected to be set by data. Others should
|
|
|
|
# be set by calling the language functions.
|
|
|
|
if attr not in (CLUSTER, PROB, IS_OOV, LANG):
|
|
|
|
values[lex.vocab.strings[attr]] = func(lex.orth_)
|
|
|
|
lex.set_attrs(**values)
|
|
|
|
lex.is_oov = False
|
2018-06-25 17:36:42 +03:00
|
|
|
|
2018-06-25 00:39:52 +03:00
|
|
|
|
2018-11-16 00:17:16 +03:00
|
|
|
def _load_pretrained_tok2vec(nlp, loc):
|
|
|
|
"""Load pre-trained weights for the 'token-to-vector' part of the component
|
|
|
|
models, which is typically a CNN. See 'spacy pretrain'. Experimental.
|
|
|
|
"""
|
2018-11-30 22:16:14 +03:00
|
|
|
with loc.open("rb") as file_:
|
2018-11-16 00:17:16 +03:00
|
|
|
weights_data = file_.read()
|
|
|
|
loaded = []
|
|
|
|
for name, component in nlp.pipeline:
|
2018-11-30 22:16:14 +03:00
|
|
|
if hasattr(component, "model") and hasattr(component.model, "tok2vec"):
|
2018-11-16 02:34:54 +03:00
|
|
|
component.tok2vec.from_bytes(weights_data)
|
2018-11-16 00:17:16 +03:00
|
|
|
loaded.append(name)
|
|
|
|
return loaded
|
|
|
|
|
|
|
|
|
2018-06-25 00:39:52 +03:00
|
|
|
def _collate_best_model(meta, output_path, components):
|
|
|
|
bests = {}
|
|
|
|
for component in components:
|
|
|
|
bests[component] = _find_best(output_path, component)
|
2018-11-30 22:16:14 +03:00
|
|
|
best_dest = output_path / "model-best"
|
2019-05-11 16:48:35 +03:00
|
|
|
shutil.copytree(path2str(output_path / "model-final"), path2str(best_dest))
|
2018-06-25 00:39:52 +03:00
|
|
|
for component, best_component_src in bests.items():
|
2019-05-11 16:48:35 +03:00
|
|
|
shutil.rmtree(path2str(best_dest / component))
|
|
|
|
shutil.copytree(
|
|
|
|
path2str(best_component_src / component), path2str(best_dest / component)
|
|
|
|
)
|
💫 Replace ujson, msgpack and dill/pickle/cloudpickle with srsly (#3003)
Remove hacks and wrappers, keep code in sync across our libraries and move spaCy a few steps closer to only depending on packages with binary wheels 🎉
See here: https://github.com/explosion/srsly
Serialization is hard, especially across Python versions and multiple platforms. After dealing with many subtle bugs over the years (encodings, locales, large files) our libraries like spaCy and Prodigy have steadily grown a number of utility functions to wrap the multiple serialization formats we need to support (especially json, msgpack and pickle). These wrapping functions ended up duplicated across our codebases, so we wanted to put them in one place.
At the same time, we noticed that having a lot of small dependencies was making maintainence harder, and making installation slower. To solve this, we've made srsly standalone, by including the component packages directly within it. This way we can provide all the serialization utilities we need in a single binary wheel.
srsly currently includes forks of the following packages:
ujson
msgpack
msgpack-numpy
cloudpickle
* WIP: replace json/ujson with srsly
* Replace ujson in examples
Use regular json instead of srsly to make code easier to read and follow
* Update requirements
* Fix imports
* Fix typos
* Replace msgpack with srsly
* Fix warning
2018-12-03 03:28:22 +03:00
|
|
|
accs = srsly.read_json(best_component_src / "accuracy.json")
|
2018-06-25 00:39:52 +03:00
|
|
|
for metric in _get_metrics(component):
|
2018-11-30 22:16:14 +03:00
|
|
|
meta["accuracy"][metric] = accs[metric]
|
💫 Replace ujson, msgpack and dill/pickle/cloudpickle with srsly (#3003)
Remove hacks and wrappers, keep code in sync across our libraries and move spaCy a few steps closer to only depending on packages with binary wheels 🎉
See here: https://github.com/explosion/srsly
Serialization is hard, especially across Python versions and multiple platforms. After dealing with many subtle bugs over the years (encodings, locales, large files) our libraries like spaCy and Prodigy have steadily grown a number of utility functions to wrap the multiple serialization formats we need to support (especially json, msgpack and pickle). These wrapping functions ended up duplicated across our codebases, so we wanted to put them in one place.
At the same time, we noticed that having a lot of small dependencies was making maintainence harder, and making installation slower. To solve this, we've made srsly standalone, by including the component packages directly within it. This way we can provide all the serialization utilities we need in a single binary wheel.
srsly currently includes forks of the following packages:
ujson
msgpack
msgpack-numpy
cloudpickle
* WIP: replace json/ujson with srsly
* Replace ujson in examples
Use regular json instead of srsly to make code easier to read and follow
* Update requirements
* Fix imports
* Fix typos
* Replace msgpack with srsly
* Fix warning
2018-12-03 03:28:22 +03:00
|
|
|
srsly.write_json(best_dest / "meta.json", meta)
|
2018-12-08 13:49:43 +03:00
|
|
|
return best_dest
|
2018-06-25 00:39:52 +03:00
|
|
|
|
|
|
|
|
|
|
|
def _find_best(experiment_dir, component):
|
|
|
|
accuracies = []
|
|
|
|
for epoch_model in experiment_dir.iterdir():
|
|
|
|
if epoch_model.is_dir() and epoch_model.parts[-1] != "model-final":
|
💫 Replace ujson, msgpack and dill/pickle/cloudpickle with srsly (#3003)
Remove hacks and wrappers, keep code in sync across our libraries and move spaCy a few steps closer to only depending on packages with binary wheels 🎉
See here: https://github.com/explosion/srsly
Serialization is hard, especially across Python versions and multiple platforms. After dealing with many subtle bugs over the years (encodings, locales, large files) our libraries like spaCy and Prodigy have steadily grown a number of utility functions to wrap the multiple serialization formats we need to support (especially json, msgpack and pickle). These wrapping functions ended up duplicated across our codebases, so we wanted to put them in one place.
At the same time, we noticed that having a lot of small dependencies was making maintainence harder, and making installation slower. To solve this, we've made srsly standalone, by including the component packages directly within it. This way we can provide all the serialization utilities we need in a single binary wheel.
srsly currently includes forks of the following packages:
ujson
msgpack
msgpack-numpy
cloudpickle
* WIP: replace json/ujson with srsly
* Replace ujson in examples
Use regular json instead of srsly to make code easier to read and follow
* Update requirements
* Fix imports
* Fix typos
* Replace msgpack with srsly
* Fix warning
2018-12-03 03:28:22 +03:00
|
|
|
accs = srsly.read_json(epoch_model / "accuracy.json")
|
2018-06-25 00:39:52 +03:00
|
|
|
scores = [accs.get(metric, 0.0) for metric in _get_metrics(component)]
|
|
|
|
accuracies.append((scores, epoch_model))
|
|
|
|
if accuracies:
|
|
|
|
return max(accuracies)[1]
|
|
|
|
else:
|
|
|
|
return None
|
|
|
|
|
2018-11-30 22:16:14 +03:00
|
|
|
|
2018-06-25 00:39:52 +03:00
|
|
|
def _get_metrics(component):
|
|
|
|
if component == "parser":
|
|
|
|
return ("las", "uas", "token_acc")
|
|
|
|
elif component == "tagger":
|
|
|
|
return ("tags_acc",)
|
|
|
|
elif component == "ner":
|
|
|
|
return ("ents_f", "ents_p", "ents_r")
|
|
|
|
return ("token_acc",)
|
2017-05-20 02:15:50 +03:00
|
|
|
|
|
|
|
|
2019-03-16 18:02:47 +03:00
|
|
|
def _get_progress(itn, losses, dev_scores, beam_width=None, cpu_wps=0.0, gpu_wps=0.0):
|
2017-05-16 17:17:30 +03:00
|
|
|
scores = {}
|
2018-11-30 22:16:14 +03:00
|
|
|
for col in [
|
|
|
|
"dep_loss",
|
|
|
|
"tag_loss",
|
|
|
|
"uas",
|
|
|
|
"tags_acc",
|
|
|
|
"token_acc",
|
|
|
|
"ents_p",
|
|
|
|
"ents_r",
|
|
|
|
"ents_f",
|
|
|
|
"cpu_wps",
|
|
|
|
"gpu_wps",
|
|
|
|
]:
|
2017-05-16 17:17:30 +03:00
|
|
|
scores[col] = 0.0
|
2018-11-30 22:16:14 +03:00
|
|
|
scores["dep_loss"] = losses.get("parser", 0.0)
|
|
|
|
scores["ner_loss"] = losses.get("ner", 0.0)
|
|
|
|
scores["tag_loss"] = losses.get("tagger", 0.0)
|
2017-05-16 17:17:30 +03:00
|
|
|
scores.update(dev_scores)
|
2018-11-30 22:16:14 +03:00
|
|
|
scores["cpu_wps"] = cpu_wps
|
|
|
|
scores["gpu_wps"] = gpu_wps or 0.0
|
2019-03-16 18:02:47 +03:00
|
|
|
result = [
|
2018-12-08 13:49:43 +03:00
|
|
|
itn,
|
|
|
|
"{:.3f}".format(scores["dep_loss"]),
|
|
|
|
"{:.3f}".format(scores["ner_loss"]),
|
|
|
|
"{:.3f}".format(scores["uas"]),
|
|
|
|
"{:.3f}".format(scores["ents_p"]),
|
|
|
|
"{:.3f}".format(scores["ents_r"]),
|
|
|
|
"{:.3f}".format(scores["ents_f"]),
|
|
|
|
"{:.3f}".format(scores["tags_acc"]),
|
|
|
|
"{:.3f}".format(scores["token_acc"]),
|
|
|
|
"{:.0f}".format(scores["cpu_wps"]),
|
|
|
|
"{:.0f}".format(scores["gpu_wps"]),
|
|
|
|
]
|
2019-03-16 18:02:47 +03:00
|
|
|
if beam_width is not None:
|
|
|
|
result.insert(1, beam_width)
|
|
|
|
return result
|