2018-11-15 21:17:16 +00:00
import random
import numpy
import time
2019-07-09 19:48:30 +00:00
import re
2018-11-15 22:45:36 +00:00
from collections import Counter
2020-06-03 12:45:00 +00:00
import plac
2018-11-30 19:16:14 +00:00
from pathlib import Path
2020-06-03 20:17:02 +00:00
from thinc . api import Linear , Maxout , chain , list2array , use_pytorch_for_gpu_memory
Generalize handling of tokenizer special cases (#4259)
* Generalize handling of tokenizer special cases
Handle tokenizer special cases more generally by using the Matcher
internally to match special cases after the affix/token_match
tokenization is complete.
Instead of only matching special cases while processing balanced or
nearly balanced prefixes and suffixes, this recognizes special cases in
a wider range of contexts:
* Allows arbitrary numbers of prefixes/affixes around special cases
* Allows special cases separated by infixes
Existing tests/settings that couldn't be preserved as before:
* The emoticon '")' is no longer a supported special case
* The emoticon ':)' in "example:)" is a false positive again
When merged with #4258 (or the relevant cache bugfix), the affix and
token_match properties should be modified to flush and reload all
special cases to use the updated internal tokenization with the Matcher.
* Remove accidentally added test case
* Really remove accidentally added test
* Reload special cases when necessary
Reload special cases when affixes or token_match are modified. Skip
reloading during initialization.
* Update error code number
* Fix offset and whitespace in Matcher special cases
* Fix offset bugs when merging and splitting tokens
* Set final whitespace on final token in inserted special case
* Improve cache flushing in tokenizer
* Separate cache and specials memory (temporarily)
* Flush cache when adding special cases
* Repeated `self._cache = PreshMap()` and `self._specials = PreshMap()`
are necessary due to this bug:
https://github.com/explosion/preshed/issues/21
* Remove reinitialized PreshMaps on cache flush
* Update UD bin scripts
* Update imports for `bin/`
* Add all currently supported languages
* Update subtok merger for new Matcher validation
* Modify blinded check to look at tokens instead of lemmas (for corpora
with tokens but not lemmas like Telugu)
* Use special Matcher only for cases with affixes
* Reinsert specials cache checks during normal tokenization for special
cases as much as possible
* Additionally include specials cache checks while splitting on infixes
* Since the special Matcher needs consistent affix-only tokenization
for the special cases themselves, introduce the argument
`with_special_cases` in order to do tokenization with or without
specials cache checks
* After normal tokenization, postprocess with special cases Matcher for
special cases containing affixes
* Replace PhraseMatcher with Aho-Corasick
Replace PhraseMatcher with the Aho-Corasick algorithm over numpy arrays
of the hash values for the relevant attribute. The implementation is
based on FlashText.
The speed should be similar to the previous PhraseMatcher. It is now
possible to easily remove match IDs and matches don't go missing with
large keyword lists / vocabularies.
Fixes #4308.
* Restore support for pickling
* Fix internal keyword add/remove for numpy arrays
* Add test for #4248, clean up test
* Improve efficiency of special cases handling
* Use PhraseMatcher instead of Matcher
* Improve efficiency of merging/splitting special cases in document
* Process merge/splits in one pass without repeated token shifting
* Merge in place if no splits
* Update error message number
* Remove UD script modifications
Only used for timing/testing, should be a separate PR
* Remove final traces of UD script modifications
* Update UD bin scripts
* Update imports for `bin/`
* Add all currently supported languages
* Update subtok merger for new Matcher validation
* Modify blinded check to look at tokens instead of lemmas (for corpora
with tokens but not lemmas like Telugu)
* Add missing loop for match ID set in search loop
* Remove cruft in matching loop for partial matches
There was a bit of unnecessary code left over from FlashText in the
matching loop to handle partial token matches, which we don't have with
PhraseMatcher.
* Replace dict trie with MapStruct trie
* Fix how match ID hash is stored/added
* Update fix for match ID vocab
* Switch from map_get_unless_missing to map_get
* Switch from numpy array to Token.get_struct_attr
Access token attributes directly in Doc instead of making a copy of the
relevant values in a numpy array.
Add unsatisfactory warning for hash collision with reserved terminal
hash key. (Ideally it would change the reserved terminal hash and redo
the whole trie, but for now, I'm hoping there won't be collisions.)
* Restructure imports to export find_matches
* Implement full remove()
Remove unnecessary trie paths and free unused maps.
Parallel to Matcher, raise KeyError when attempting to remove a match ID
that has not been added.
* Switch to PhraseMatcher.find_matches
* Switch to local cdef functions for span filtering
* Switch special case reload threshold to variable
Refer to variable instead of hard-coded threshold
* Move more of special case retokenize to cdef nogil
Move as much of the special case retokenization to nogil as possible.
* Rewrap sort as stdsort for OS X
* Rewrap stdsort with specific types
* Switch to qsort
* Fix merge
* Improve cmp functions
* Fix realloc
* Fix realloc again
* Initialize span struct while retokenizing
* Temporarily skip retokenizing
* Revert "Move more of special case retokenize to cdef nogil"
This reverts commit 0b7e52c797cd8ff1548f214bd4186ebb3a7ce8b1.
* Revert "Switch to qsort"
This reverts commit a98d71a942fc9bca531cf5eb05cf89fa88153b60.
* Fix specials check while caching
* Modify URL test with emoticons
The multiple suffix tests result in the emoticon `:>`, which is now
retokenized into one token as a special case after the suffixes are
split off.
* Refactor _apply_special_cases()
* Use cdef ints for span info used in multiple spots
* Modify _filter_special_spans() to prefer earlier
Parallel to #4414, modify _filter_special_spans() so that the earlier
span is preferred for overlapping spans of the same length.
* Replace MatchStruct with Entity
Replace MatchStruct with Entity since the existing Entity struct is
nearly identical.
* Replace Entity with more general SpanC
* Replace MatchStruct with SpanC
* Add error in debug-data if no dev docs are available (see #4575)
* Update azure-pipelines.yml
* Revert "Update azure-pipelines.yml"
This reverts commit ed1060cf59e5895b5fe92ad5b894fd1078ec4c49.
* Use latest wasabi
* Reorganise install_requires
* add dframcy to universe.json (#4580)
* Update universe.json [ci skip]
* Fix multiprocessing for as_tuples=True (#4582)
* Fix conllu script (#4579)
* force extensions to avoid clash between example scripts
* fix arg order and default file encoding
* add example config for conllu script
* newline
* move extension definitions to main function
* few more encodings fixes
* Add load_from_docbin example [ci skip]
TODO: upload the file somewhere
* Update README.md
* Add warnings about 3.8 (resolves #4593) [ci skip]
* Fixed typo: Added space between "recognize" and "various" (#4600)
* Fix DocBin.merge() example (#4599)
* Replace function registries with catalogue (#4584)
* Replace functions registries with catalogue
* Update __init__.py
* Fix test
* Revert unrelated flag [ci skip]
* Bugfix/dep matcher issue 4590 (#4601)
* add contributor agreement for prilopes
* add test for issue #4590
* fix on_match params for DependencyMacther (#4590)
* Minor updates to language example sentences (#4608)
* Add punctuation to Spanish example sentences
* Combine multilanguage examples for lang xx
* Add punctuation to nb examples
* Always realloc to a larger size
Avoid potential (unlikely) edge case and cymem error seen in #4604.
* Add error in debug-data if no dev docs are available (see #4575)
* Update debug-data for GoldCorpus / Example
* Ignore None label in misaligned NER data
2019-11-13 20:24:35 +00:00
from wasabi import msg
💫 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 00:28:22 +00:00
import srsly
2018-11-15 21:17:16 +00:00
2019-06-16 11:22:57 +00:00
from . . errors import Errors
2020-02-27 17:42:27 +00:00
from . . ml . models . multi_task import build_masked_language_model
2018-11-30 19:16:14 +00:00
from . . tokens import Doc
from . . attrs import ID , HEAD
from . . import util
2020-06-03 12:45:00 +00:00
from . . gold import Example
2018-11-15 21:17:16 +00:00
2020-06-03 12:45:00 +00:00
@plac.annotations (
2020-01-01 12:15:46 +00:00
# fmt: off
2020-06-03 12:45:00 +00:00
texts_loc = ( " Path to JSONL file with raw texts to learn from, with text provided as the key ' text ' or tokens as the key ' tokens ' " , " positional " , None , str ) ,
vectors_model = ( " Name or path to spaCy model with vectors to learn from " , " positional " , None , str ) ,
output_dir = ( " Directory to write models to on each epoch " , " positional " , None , Path ) ,
2020-06-03 17:32:40 +00:00
config_path = ( " Path to config file " , " positional " , None , Path ) ,
2020-06-03 12:45:00 +00:00
use_gpu = ( " Use GPU " , " option " , " g " , int ) ,
2020-06-20 12:15:04 +00:00
resume_path = ( " Path to pretrained weights from which to resume pretraining " , " option " , " r " , Path ) ,
epoch_resume = ( " The epoch to resume counting from when using ' --resume_path ' . Prevents unintended overwriting of existing weight files. " , " option " , " er " , int ) ,
2020-06-04 14:09:55 +00:00
# fmt: on
2020-06-03 12:45:00 +00:00
)
def pretrain (
texts_loc ,
vectors_model ,
config_path ,
output_dir ,
use_gpu = - 1 ,
2020-06-03 20:00:25 +00:00
resume_path = None ,
epoch_resume = None ,
2018-11-30 19:16:14 +00:00
) :
"""
Pre - train the ' token-to-vector ' ( tok2vec ) layer of pipeline components ,
using an approximate language - modelling objective . Specifically , we load
2019-10-02 08:37:39 +00:00
pretrained vectors , and train a component like a CNN , BiLSTM , etc to predict
vectors which match the pretrained ones . The weights are saved to a directory
after each epoch . You can then pass a path to one of these pretrained weights
2018-11-30 19:16:14 +00:00
files to the ' spacy train ' command .
This technique may be especially helpful if you have little labelled data .
However , it ' s still quite experimental, so your mileage may vary.
2018-11-15 21:17:16 +00:00
2018-11-30 19:16:14 +00:00
To load the weights back in during ' spacy train ' , you need to ensure
2020-06-03 12:45:00 +00:00
all settings are the same between pretraining and training . Ideally ,
this is done by using the same config file for both commands .
2018-11-30 19:16:14 +00:00
"""
2020-06-03 12:45:00 +00:00
if not config_path or not config_path . exists ( ) :
msg . fail ( " Config file not found " , config_path , exits = 1 )
2018-11-30 19:16:14 +00:00
2020-06-03 12:45:00 +00:00
if use_gpu > = 0 :
msg . info ( " Using GPU " )
util . use_gpu ( use_gpu )
else :
msg . info ( " Using CPU " )
2019-10-07 21:34:58 +00:00
2020-06-03 12:45:00 +00:00
msg . info ( f " Loading config from: { config_path } " )
config = util . load_config ( config_path , create_objects = False )
2020-06-03 17:32:40 +00:00
util . fix_random_seed ( config [ " pretraining " ] [ " seed " ] )
if config [ " pretraining " ] [ " use_pytorch_for_gpu_memory " ] :
2020-06-03 12:45:00 +00:00
use_pytorch_for_gpu_memory ( )
2018-11-30 19:16:14 +00:00
2020-02-16 16:16:41 +00:00
if output_dir . exists ( ) and [ p for p in output_dir . iterdir ( ) ] :
2020-06-03 20:00:25 +00:00
if resume_path :
msg . warn (
" Output directory is not empty. " ,
2020-06-03 20:17:02 +00:00
" If you ' re resuming a run from a previous model in this directory, "
" the old models for the consecutive epochs will be overwritten "
2020-06-03 20:00:25 +00:00
" with the new ones. " ,
)
else :
msg . warn (
" Output directory is not empty. " ,
" It is better to use an empty directory or refer to a new output path, "
" then the new directory will be created for you. " ,
)
2018-11-30 19:16:14 +00:00
if not output_dir . exists ( ) :
output_dir . mkdir ( )
2020-02-18 14:38:18 +00:00
msg . good ( f " Created output directory: { output_dir } " )
💫 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 00:28:22 +00:00
srsly . write_json ( output_dir / " config.json " , config )
2020-06-03 12:45:00 +00:00
msg . good ( " Saved config file in the output directory " )
config = util . load_config ( config_path , create_objects = True )
pretrain_config = config [ " pretraining " ]
2018-11-30 19:16:14 +00:00
# Load texts from file or stdin
if texts_loc != " - " : # reading from a file
texts_loc = Path ( texts_loc )
if not texts_loc . exists ( ) :
msg . fail ( " Input text file doesn ' t exist " , texts_loc , exits = 1 )
with msg . loading ( " Loading input texts... " ) :
💫 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 00:28:22 +00:00
texts = list ( srsly . read_jsonl ( texts_loc ) )
2019-06-16 11:22:57 +00:00
if not texts :
msg . fail ( " Input file is empty " , texts_loc , exits = 1 )
2018-11-30 19:16:14 +00:00
msg . good ( " Loaded input texts " )
random . shuffle ( texts )
else : # reading from stdin
2020-06-03 20:00:25 +00:00
msg . info ( " Reading input text from stdin... " )
💫 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 00:28:22 +00:00
texts = srsly . read_jsonl ( " - " )
2018-11-30 19:16:14 +00:00
2019-12-22 00:53:56 +00:00
with msg . loading ( f " Loading model ' { vectors_model } ' ... " ) :
2018-11-30 19:16:14 +00:00
nlp = util . load_model ( vectors_model )
2019-12-22 00:53:56 +00:00
msg . good ( f " Loaded model ' { vectors_model } ' " )
2020-06-04 13:49:23 +00:00
tok2vec_path = pretrain_config [ " tok2vec_model " ]
tok2vec = config
for subpath in tok2vec_path . split ( " . " ) :
tok2vec = tok2vec . get ( subpath )
2020-06-03 12:45:00 +00:00
model = create_pretraining_model ( nlp , tok2vec )
optimizer = pretrain_config [ " optimizer " ]
2020-06-03 17:32:40 +00:00
2020-06-03 20:00:25 +00:00
# Load in pretrained weights to resume from
if resume_path is not None :
msg . info ( f " Resume training tok2vec from: { resume_path } " )
with resume_path . open ( " rb " ) as file_ :
weights_data = file_ . read ( )
model . get_ref ( " tok2vec " ) . from_bytes ( weights_data )
2020-06-03 17:32:40 +00:00
# Parse the epoch number from the given weight file
2020-06-03 20:00:25 +00:00
model_name = re . search ( r " model \ d+ \ .bin " , str ( resume_path ) )
2020-06-03 17:32:40 +00:00
if model_name :
# Default weight file name so read epoch_start from it by cutting off 'model' and '.bin'
2020-06-03 20:00:25 +00:00
epoch_resume = int ( model_name . group ( 0 ) [ 5 : ] [ : - 4 ] ) + 1
msg . info ( f " Resuming from epoch: { epoch_resume } " )
2020-06-03 17:32:40 +00:00
else :
2020-06-03 20:00:25 +00:00
if not epoch_resume :
2020-06-03 17:32:40 +00:00
msg . fail (
2020-06-03 20:17:02 +00:00
" You have to use the --epoch-resume setting when using a renamed weight file for --resume-path " ,
2020-06-03 17:32:40 +00:00
exits = True ,
)
2020-06-03 20:00:25 +00:00
elif epoch_resume < 0 :
2020-06-03 17:32:40 +00:00
msg . fail (
2020-06-03 20:17:02 +00:00
f " The argument --epoch-resume has to be greater or equal to 0. { epoch_resume } is invalid " ,
2020-06-03 17:32:40 +00:00
exits = True ,
)
2020-06-03 20:17:02 +00:00
else :
msg . info ( f " Resuming from epoch: { epoch_resume } " )
2020-06-03 17:32:40 +00:00
else :
2020-06-03 20:17:02 +00:00
# Without '--resume-path' the '--epoch-resume' argument is ignored
2020-06-03 20:00:25 +00:00
epoch_resume = 0
2019-07-09 19:48:30 +00:00
2018-12-18 18:19:26 +00:00
tracker = ProgressTracker ( frequency = 10000 )
2020-06-03 20:00:25 +00:00
msg . divider ( f " Pre-training tok2vec layer - starting at epoch { epoch_resume } " )
2018-11-30 19:16:14 +00:00
row_settings = { " widths " : ( 3 , 10 , 10 , 6 , 4 ) , " aligns " : ( " r " , " r " , " r " , " r " , " r " ) }
msg . row ( ( " # " , " # Words " , " Total Loss " , " Loss " , " w/s " ) , * * row_settings )
Add save after `--save-every` batches for `spacy pretrain` (#3510)
<!--- Provide a general summary of your changes in the title. -->
When using `spacy pretrain`, the model is saved only after every epoch. But each epoch can be very big since `pretrain` is used for language modeling tasks. So I added a `--save-every` option in the CLI to save after every `--save-every` batches.
## Description
<!--- Use this section to describe your changes. If your changes required
testing, include information about the testing environment and the tests you
ran. If your test fixes a bug reported in an issue, don't forget to include the
issue number. If your PR is still a work in progress, that's totally fine – just
include a note to let us know. -->
To test...
Save this file to `sample_sents.jsonl`
```
{"text": "hello there."}
{"text": "hello there."}
{"text": "hello there."}
{"text": "hello there."}
{"text": "hello there."}
{"text": "hello there."}
{"text": "hello there."}
{"text": "hello there."}
{"text": "hello there."}
{"text": "hello there."}
{"text": "hello there."}
{"text": "hello there."}
{"text": "hello there."}
{"text": "hello there."}
{"text": "hello there."}
{"text": "hello there."}
```
Then run `--save-every 2` when pretraining.
```bash
spacy pretrain sample_sents.jsonl en_core_web_md here -nw 1 -bs 1 -i 10 --save-every 2
```
And it should save the model to the `here/` folder after every 2 batches. The models that are saved during an epoch will have a `.temp` appended to the save name.
At the end the training, you should see these files (`ls here/`):
```bash
config.json model2.bin model5.bin model8.bin
log.jsonl model2.temp.bin model5.temp.bin model8.temp.bin
model0.bin model3.bin model6.bin model9.bin
model0.temp.bin model3.temp.bin model6.temp.bin model9.temp.bin
model1.bin model4.bin model7.bin
model1.temp.bin model4.temp.bin model7.temp.bin
```
### Types of change
<!-- What type of change does your PR cover? Is it a bug fix, an enhancement
or new feature, or a change to the documentation? -->
This is a new feature to `spacy pretrain`.
🌵 **Unfortunately, I haven't been able to test this because compiling from source is not working (cythonize error).**
```
Processing matcher.pyx
[Errno 2] No such file or directory: '/Users/mwu/github/spaCy/spacy/matcher.pyx'
Traceback (most recent call last):
File "/Users/mwu/github/spaCy/bin/cythonize.py", line 169, in <module>
run(args.root)
File "/Users/mwu/github/spaCy/bin/cythonize.py", line 158, in run
process(base, filename, db)
File "/Users/mwu/github/spaCy/bin/cythonize.py", line 124, in process
preserve_cwd(base, process_pyx, root + ".pyx", root + ".cpp")
File "/Users/mwu/github/spaCy/bin/cythonize.py", line 87, in preserve_cwd
func(*args)
File "/Users/mwu/github/spaCy/bin/cythonize.py", line 63, in process_pyx
raise Exception("Cython failed")
Exception: Cython failed
Traceback (most recent call last):
File "setup.py", line 276, in <module>
setup_package()
File "setup.py", line 209, in setup_package
generate_cython(root, "spacy")
File "setup.py", line 132, in generate_cython
raise RuntimeError("Running cythonize failed")
RuntimeError: Running cythonize failed
```
Edit: Fixed! after deleting all `.cpp` files: `find spacy -name "*.cpp" | xargs rm`
## Checklist
<!--- Before you submit the PR, go over this checklist and make sure you can
tick off all the boxes. [] -> [x] -->
- [x] I have submitted the spaCy Contributor Agreement.
- [x] I ran the tests, and all new and existing tests passed.
- [x] My changes don't require a change to the documentation, or if they do, I've added all required information.
2019-04-22 12:10:16 +00:00
def _save_model ( epoch , is_temp = False ) :
is_temp_str = " .temp " if is_temp else " "
with model . use_params ( optimizer . averages ) :
2019-12-25 16:59:52 +00:00
with ( output_dir / f " model { epoch } { is_temp_str } .bin " ) . open ( " wb " ) as file_ :
2020-02-27 17:42:27 +00:00
file_ . write ( model . get_ref ( " tok2vec " ) . to_bytes ( ) )
Add save after `--save-every` batches for `spacy pretrain` (#3510)
<!--- Provide a general summary of your changes in the title. -->
When using `spacy pretrain`, the model is saved only after every epoch. But each epoch can be very big since `pretrain` is used for language modeling tasks. So I added a `--save-every` option in the CLI to save after every `--save-every` batches.
## Description
<!--- Use this section to describe your changes. If your changes required
testing, include information about the testing environment and the tests you
ran. If your test fixes a bug reported in an issue, don't forget to include the
issue number. If your PR is still a work in progress, that's totally fine – just
include a note to let us know. -->
To test...
Save this file to `sample_sents.jsonl`
```
{"text": "hello there."}
{"text": "hello there."}
{"text": "hello there."}
{"text": "hello there."}
{"text": "hello there."}
{"text": "hello there."}
{"text": "hello there."}
{"text": "hello there."}
{"text": "hello there."}
{"text": "hello there."}
{"text": "hello there."}
{"text": "hello there."}
{"text": "hello there."}
{"text": "hello there."}
{"text": "hello there."}
{"text": "hello there."}
```
Then run `--save-every 2` when pretraining.
```bash
spacy pretrain sample_sents.jsonl en_core_web_md here -nw 1 -bs 1 -i 10 --save-every 2
```
And it should save the model to the `here/` folder after every 2 batches. The models that are saved during an epoch will have a `.temp` appended to the save name.
At the end the training, you should see these files (`ls here/`):
```bash
config.json model2.bin model5.bin model8.bin
log.jsonl model2.temp.bin model5.temp.bin model8.temp.bin
model0.bin model3.bin model6.bin model9.bin
model0.temp.bin model3.temp.bin model6.temp.bin model9.temp.bin
model1.bin model4.bin model7.bin
model1.temp.bin model4.temp.bin model7.temp.bin
```
### Types of change
<!-- What type of change does your PR cover? Is it a bug fix, an enhancement
or new feature, or a change to the documentation? -->
This is a new feature to `spacy pretrain`.
🌵 **Unfortunately, I haven't been able to test this because compiling from source is not working (cythonize error).**
```
Processing matcher.pyx
[Errno 2] No such file or directory: '/Users/mwu/github/spaCy/spacy/matcher.pyx'
Traceback (most recent call last):
File "/Users/mwu/github/spaCy/bin/cythonize.py", line 169, in <module>
run(args.root)
File "/Users/mwu/github/spaCy/bin/cythonize.py", line 158, in run
process(base, filename, db)
File "/Users/mwu/github/spaCy/bin/cythonize.py", line 124, in process
preserve_cwd(base, process_pyx, root + ".pyx", root + ".cpp")
File "/Users/mwu/github/spaCy/bin/cythonize.py", line 87, in preserve_cwd
func(*args)
File "/Users/mwu/github/spaCy/bin/cythonize.py", line 63, in process_pyx
raise Exception("Cython failed")
Exception: Cython failed
Traceback (most recent call last):
File "setup.py", line 276, in <module>
setup_package()
File "setup.py", line 209, in setup_package
generate_cython(root, "spacy")
File "setup.py", line 132, in generate_cython
raise RuntimeError("Running cythonize failed")
RuntimeError: Running cythonize failed
```
Edit: Fixed! after deleting all `.cpp` files: `find spacy -name "*.cpp" | xargs rm`
## Checklist
<!--- Before you submit the PR, go over this checklist and make sure you can
tick off all the boxes. [] -> [x] -->
- [x] I have submitted the spaCy Contributor Agreement.
- [x] I ran the tests, and all new and existing tests passed.
- [x] My changes don't require a change to the documentation, or if they do, I've added all required information.
2019-04-22 12:10:16 +00:00
log = {
" nr_word " : tracker . nr_word ,
" loss " : tracker . loss ,
" epoch_loss " : tracker . epoch_loss ,
" epoch " : epoch ,
}
with ( output_dir / " log.jsonl " ) . open ( " a " ) as file_ :
file_ . write ( srsly . json_dumps ( log ) + " \n " )
2019-06-16 11:22:57 +00:00
skip_counter = 0
2020-06-03 12:45:00 +00:00
loss_func = pretrain_config [ " loss_func " ]
2020-06-03 20:00:25 +00:00
for epoch in range ( epoch_resume , pretrain_config [ " max_epochs " ] ) :
2020-06-03 12:45:00 +00:00
examples = [ Example ( doc = text ) for text in texts ]
batches = util . minibatch_by_words ( examples , size = pretrain_config [ " batch_size " ] )
for batch_id , batch in enumerate ( batches ) :
2019-06-16 11:22:57 +00:00
docs , count = make_docs (
2019-03-16 20:38:45 +00:00
nlp ,
2020-06-03 12:45:00 +00:00
[ ex . doc for ex in batch ] ,
max_length = pretrain_config [ " max_length " ] ,
min_length = pretrain_config [ " min_length " ] ,
2019-03-16 20:38:45 +00:00
)
2019-06-16 11:22:57 +00:00
skip_counter + = count
2020-06-03 12:45:00 +00:00
loss = make_update ( model , docs , optimizer , distance = loss_func )
2018-11-30 19:16:14 +00:00
progress = tracker . update ( epoch , loss , docs )
if progress :
msg . row ( progress , * * row_settings )
if texts_loc == " - " and tracker . words_per_epoch [ epoch ] > = 10 * * 7 :
break
2020-06-04 14:09:55 +00:00
if pretrain_config [ " n_save_every " ] and (
batch_id % pretrain_config [ " n_save_every " ] == 0
) :
Add save after `--save-every` batches for `spacy pretrain` (#3510)
<!--- Provide a general summary of your changes in the title. -->
When using `spacy pretrain`, the model is saved only after every epoch. But each epoch can be very big since `pretrain` is used for language modeling tasks. So I added a `--save-every` option in the CLI to save after every `--save-every` batches.
## Description
<!--- Use this section to describe your changes. If your changes required
testing, include information about the testing environment and the tests you
ran. If your test fixes a bug reported in an issue, don't forget to include the
issue number. If your PR is still a work in progress, that's totally fine – just
include a note to let us know. -->
To test...
Save this file to `sample_sents.jsonl`
```
{"text": "hello there."}
{"text": "hello there."}
{"text": "hello there."}
{"text": "hello there."}
{"text": "hello there."}
{"text": "hello there."}
{"text": "hello there."}
{"text": "hello there."}
{"text": "hello there."}
{"text": "hello there."}
{"text": "hello there."}
{"text": "hello there."}
{"text": "hello there."}
{"text": "hello there."}
{"text": "hello there."}
{"text": "hello there."}
```
Then run `--save-every 2` when pretraining.
```bash
spacy pretrain sample_sents.jsonl en_core_web_md here -nw 1 -bs 1 -i 10 --save-every 2
```
And it should save the model to the `here/` folder after every 2 batches. The models that are saved during an epoch will have a `.temp` appended to the save name.
At the end the training, you should see these files (`ls here/`):
```bash
config.json model2.bin model5.bin model8.bin
log.jsonl model2.temp.bin model5.temp.bin model8.temp.bin
model0.bin model3.bin model6.bin model9.bin
model0.temp.bin model3.temp.bin model6.temp.bin model9.temp.bin
model1.bin model4.bin model7.bin
model1.temp.bin model4.temp.bin model7.temp.bin
```
### Types of change
<!-- What type of change does your PR cover? Is it a bug fix, an enhancement
or new feature, or a change to the documentation? -->
This is a new feature to `spacy pretrain`.
🌵 **Unfortunately, I haven't been able to test this because compiling from source is not working (cythonize error).**
```
Processing matcher.pyx
[Errno 2] No such file or directory: '/Users/mwu/github/spaCy/spacy/matcher.pyx'
Traceback (most recent call last):
File "/Users/mwu/github/spaCy/bin/cythonize.py", line 169, in <module>
run(args.root)
File "/Users/mwu/github/spaCy/bin/cythonize.py", line 158, in run
process(base, filename, db)
File "/Users/mwu/github/spaCy/bin/cythonize.py", line 124, in process
preserve_cwd(base, process_pyx, root + ".pyx", root + ".cpp")
File "/Users/mwu/github/spaCy/bin/cythonize.py", line 87, in preserve_cwd
func(*args)
File "/Users/mwu/github/spaCy/bin/cythonize.py", line 63, in process_pyx
raise Exception("Cython failed")
Exception: Cython failed
Traceback (most recent call last):
File "setup.py", line 276, in <module>
setup_package()
File "setup.py", line 209, in setup_package
generate_cython(root, "spacy")
File "setup.py", line 132, in generate_cython
raise RuntimeError("Running cythonize failed")
RuntimeError: Running cythonize failed
```
Edit: Fixed! after deleting all `.cpp` files: `find spacy -name "*.cpp" | xargs rm`
## Checklist
<!--- Before you submit the PR, go over this checklist and make sure you can
tick off all the boxes. [] -> [x] -->
- [x] I have submitted the spaCy Contributor Agreement.
- [x] I ran the tests, and all new and existing tests passed.
- [x] My changes don't require a change to the documentation, or if they do, I've added all required information.
2019-04-22 12:10:16 +00:00
_save_model ( epoch , is_temp = True )
_save_model ( epoch )
2018-11-30 19:16:14 +00:00
tracker . epoch_loss = 0.0
if texts_loc != " - " :
# Reshuffle the texts if texts were loaded from a file
random . shuffle ( texts )
2019-06-16 11:22:57 +00:00
if skip_counter > 0 :
2019-12-22 00:53:56 +00:00
msg . warn ( f " Skipped { skip_counter } empty values " )
2019-06-16 11:22:57 +00:00
msg . good ( " Successfully finished pretrain " )
2018-11-15 22:44:07 +00:00
2018-11-28 17:04:58 +00:00
2020-06-03 12:45:00 +00:00
def make_update ( model , docs , optimizer , distance ) :
2018-11-15 21:17:16 +00:00
""" Perform an update over a single batch of documents.
docs ( iterable ) : A batch of ` Doc ` objects .
optimizer ( callable ) : An optimizer .
RETURNS loss : A float for the loss .
"""
2020-06-03 12:45:00 +00:00
predictions , backprop = model . begin_update ( docs )
loss , gradients = get_vectors_loss ( model . ops , docs , predictions , distance )
backprop ( gradients )
model . finish_update ( optimizer )
2018-11-28 17:04:58 +00:00
# Don't want to return a cupy object here
# The gradients are modified in-place by the BERT MLM,
# so we get an accurate loss
2018-12-18 18:19:26 +00:00
return float ( loss )
2018-11-15 21:17:16 +00:00
2019-03-16 20:38:45 +00:00
def make_docs ( nlp , batch , min_length , max_length ) :
2018-11-28 17:04:58 +00:00
docs = [ ]
2019-06-16 11:22:57 +00:00
skip_count = 0
2018-11-28 17:04:58 +00:00
for record in batch :
2019-06-16 11:22:57 +00:00
if not isinstance ( record , dict ) :
raise TypeError ( Errors . E137 . format ( type = type ( record ) , line = record ) )
2018-11-28 17:04:58 +00:00
if " tokens " in record :
2019-06-16 11:22:57 +00:00
words = record [ " tokens " ]
if not words :
skip_count + = 1
continue
doc = Doc ( nlp . vocab , words = words )
elif " text " in record :
2019-05-11 13:41:29 +00:00
text = record [ " text " ]
2019-06-16 11:22:57 +00:00
if not text :
skip_count + = 1
continue
2018-11-28 17:04:58 +00:00
doc = nlp . make_doc ( text )
2019-06-16 11:22:57 +00:00
else :
raise ValueError ( Errors . E138 . format ( text = record ) )
2018-11-28 17:04:58 +00:00
if " heads " in record :
heads = record [ " heads " ]
heads = numpy . asarray ( heads , dtype = " uint64 " )
heads = heads . reshape ( ( len ( doc ) , 1 ) )
doc = doc . from_array ( [ HEAD ] , heads )
2020-06-03 12:45:00 +00:00
if min_length < = len ( doc ) < max_length :
2018-11-28 17:04:58 +00:00
docs . append ( doc )
2019-06-16 11:22:57 +00:00
return docs , skip_count
2018-11-28 17:04:58 +00:00
2020-06-03 12:45:00 +00:00
def get_vectors_loss ( ops , docs , prediction , distance ) :
2018-11-15 21:17:16 +00:00
""" Compute a mean-squared error loss between the documents ' vectors and
2018-11-30 19:16:14 +00:00
the prediction .
2018-11-15 21:17:16 +00:00
Note that this is ripe for customization ! We could compute the vectors
in some other word , e . g . with an LSTM language model , or use some other
type of objective .
"""
# The simplest way to implement this would be to vstack the
# token.vector values, but that's a bit inefficient, especially on GPU.
# Instead we fetch the index into the vectors table for each of our tokens,
# and look them up all at once. This prevents data copying.
ids = ops . flatten ( [ doc . to_array ( ID ) . ravel ( ) for doc in docs ] )
target = docs [ 0 ] . vocab . vectors . data [ ids ]
2020-01-29 16:06:46 +00:00
d_target , loss = distance ( prediction , target )
2019-03-20 11:06:35 +00:00
return loss , d_target
2018-12-18 18:19:26 +00:00
def create_pretraining_model ( nlp , tok2vec ) :
2018-11-30 19:16:14 +00:00
""" Define a network for the pretraining. We simply add an output layer onto
2018-11-15 21:17:16 +00:00
the tok2vec input model . The tok2vec input model needs to be a model that
takes a batch of Doc objects ( as a list ) , and returns a list of arrays .
Each array in the output needs to have one row per token in the doc .
2020-06-12 00:02:07 +00:00
The actual tok2vec layer is stored as a reference , and only this bit will be
serialized to file and read back in when calling the ' train ' command .
2018-11-30 19:16:14 +00:00
"""
2018-11-15 21:17:16 +00:00
output_size = nlp . vocab . vectors . data . shape [ 1 ]
2018-11-29 12:36:43 +00:00
output_layer = chain (
2020-06-03 12:45:00 +00:00
Maxout ( nO = 300 , nP = 3 , normalize = True , dropout = 0.0 ) , Linear ( output_size )
2018-11-29 12:36:43 +00:00
)
2020-06-12 00:02:07 +00:00
model = chain ( tok2vec , list2array ( ) )
model = chain ( model , output_layer )
2020-01-29 16:06:46 +00:00
model . initialize ( X = [ nlp . make_doc ( " Give it a doc to infer shapes " ) ] )
2020-06-03 12:45:00 +00:00
mlm_model = build_masked_language_model ( nlp . vocab , model )
mlm_model . set_ref ( " tok2vec " , tok2vec )
mlm_model . set_ref ( " output_layer " , output_layer )
mlm_model . initialize ( X = [ nlp . make_doc ( " Give it a doc to infer shapes " ) ] )
return mlm_model
2018-11-15 21:17:16 +00:00
class ProgressTracker ( object ) :
2018-11-29 12:36:43 +00:00
def __init__ ( self , frequency = 1000000 ) :
2018-11-28 17:04:58 +00:00
self . loss = 0.0
self . prev_loss = 0.0
2018-11-15 21:17:16 +00:00
self . nr_word = 0
2018-11-15 22:44:07 +00:00
self . words_per_epoch = Counter ( )
2018-11-15 21:17:16 +00:00
self . frequency = frequency
self . last_time = time . time ( )
self . last_update = 0
2018-11-29 12:36:43 +00:00
self . epoch_loss = 0.0
2018-11-15 21:17:16 +00:00
def update ( self , epoch , loss , docs ) :
self . loss + = loss
2018-11-29 12:36:43 +00:00
self . epoch_loss + = loss
2018-11-15 22:44:07 +00:00
words_in_batch = sum ( len ( doc ) for doc in docs )
self . words_per_epoch [ epoch ] + = words_in_batch
self . nr_word + = words_in_batch
2018-11-15 21:17:16 +00:00
words_since_update = self . nr_word - self . last_update
if words_since_update > = self . frequency :
wps = words_since_update / ( time . time ( ) - self . last_time )
self . last_update = self . nr_word
self . last_time = time . time ( )
2018-11-28 17:04:58 +00:00
loss_per_word = self . loss - self . prev_loss
status = (
epoch ,
self . nr_word ,
2019-03-16 20:38:45 +00:00
_smart_round ( self . loss , width = 10 ) ,
_smart_round ( loss_per_word , width = 6 ) ,
2018-11-28 17:04:58 +00:00
int ( wps ) ,
)
self . prev_loss = float ( self . loss )
2018-11-15 21:17:16 +00:00
return status
else :
return None
2019-03-16 20:38:45 +00:00
def _smart_round ( figure , width = 10 , max_decimal = 4 ) :
""" Round large numbers as integers, smaller numbers as decimals. """
n_digits = len ( str ( int ( figure ) ) )
n_decimal = width - ( n_digits + 1 )
if n_decimal < = 1 :
return str ( int ( figure ) )
else :
n_decimal = min ( n_decimal , max_decimal )
format_str = " % . " + str ( n_decimal ) + " f "
return format_str % figure