2020-09-13 15:05:05 +03:00
from typing import Optional
2018-11-30 22:16:14 +03:00
from pathlib import Path
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 23:24:35 +03:00
from wasabi import msg
2020-07-11 14:03:53 +03:00
import typer
2020-09-28 16:09:59 +03:00
import re
2018-11-16 00:17:16 +03:00
2020-07-11 14:03:53 +03:00
from . _util import app , Arg , Opt , parse_config_overrides , show_validation_error
2020-09-28 22:17:10 +03:00
from . _util import import_code , setup_gpu
2020-09-28 16:09:59 +03:00
from . . training . pretrain import pretrain
from . . util import load_config
2018-11-16 00:17:16 +03:00
2020-07-11 20:17:59 +03:00
@app.command (
" pretrain " ,
context_settings = { " allow_extra_args " : True , " ignore_unknown_options " : True } ,
)
2020-06-21 22:35:01 +03:00
def pretrain_cli (
2020-01-01 15:15:46 +03:00
# fmt: off
2020-07-11 14:03:53 +03:00
ctx : typer . Context , # This is only used to read additional arguments
2020-12-08 12:41:18 +03:00
config_path : Path = Arg ( . . . , help = " Path to config file " , exists = True , dir_okay = False , allow_dash = True ) ,
2020-09-13 15:05:05 +03:00
output_dir : Path = Arg ( . . . , help = " Directory to write weights to on each epoch " ) ,
2020-09-19 02:17:02 +03:00
code_path : Optional [ Path ] = Opt ( None , " --code " , " -c " , help = " Path to Python file with additional code (registered functions) to be imported " ) ,
2020-06-21 14:44:00 +03:00
resume_path : Optional [ Path ] = Opt ( None , " --resume-path " , " -r " , help = " Path to pretrained weights from which to resume pretraining " ) ,
2020-08-09 23:31:52 +03:00
epoch_resume : Optional [ int ] = Opt ( None , " --epoch-resume " , " -er " , help = " The epoch to resume counting from when using --resume-path. Prevents unintended overwriting of existing weight files. " ) ,
2020-07-22 17:53:41 +03:00
use_gpu : int = Opt ( - 1 , " --gpu-id " , " -g " , help = " GPU ID or -1 for CPU " ) ,
2023-04-03 16:24:03 +03:00
skip_last : bool = Opt ( False , " --skip-last " , " -L " , help = " Skip saving model-last.bin " ) ,
2020-06-04 17:09:55 +03:00
# fmt: on
2018-11-30 22:16:14 +03:00
) :
"""
Pre - train the ' token-to-vector ' ( tok2vec ) layer of pipeline components ,
2020-07-03 18:57:28 +03:00
using an approximate language - modelling objective . Two objective types
are available , vector - based and character - based .
2020-07-06 14:06:25 +03:00
2020-07-03 18:57:28 +03:00
In the vector - based objective , we load word vectors that have been trained
using a word2vec - style distributional similarity algorithm , 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 files to the
' spacy train ' command .
2018-11-30 22:16:14 +03:00
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-16 00:17:16 +03:00
2018-11-30 22:16:14 +03:00
To load the weights back in during ' spacy train ' , you need to ensure
2020-06-03 15:45:00 +03:00
all settings are the same between pretraining and training . Ideally ,
this is done by using the same config file for both commands .
2020-09-04 13:58:50 +03:00
2021-01-30 12:09:38 +03:00
DOCS : https : / / spacy . io / api / cli #pretrain
2018-11-30 22:16:14 +03:00
"""
2020-09-13 15:05:05 +03:00
config_overrides = parse_config_overrides ( ctx . args )
2020-07-11 14:03:53 +03:00
import_code ( code_path )
2020-09-13 15:05:05 +03:00
verify_cli_args ( config_path , output_dir , resume_path , epoch_resume )
2020-09-28 16:09:59 +03:00
setup_gpu ( use_gpu )
2020-07-22 14:42:59 +03:00
msg . info ( f " Loading config from: { config_path } " )
2020-09-13 15:05:05 +03:00
2020-08-02 16:18:30 +03:00
with show_validation_error ( config_path ) :
2020-09-28 16:09:59 +03:00
raw_config = load_config (
2020-09-27 23:21:31 +03:00
config_path , overrides = config_overrides , interpolate = False
2020-09-13 15:05:05 +03:00
)
2020-09-27 23:21:31 +03:00
config = raw_config . interpolate ( )
2020-09-13 15:05:05 +03:00
if not config . get ( " pretraining " ) :
2020-08-24 16:56:03 +03:00
# TODO: What's the solution here? How do we handle optional blocks?
msg . fail ( " The [pretraining] block in your config is empty " , exits = 1 )
2020-07-22 14:42:59 +03:00
if not output_dir . exists ( ) :
2022-07-26 15:35:18 +03:00
output_dir . mkdir ( parents = True )
2020-07-22 14:42:59 +03:00
msg . good ( f " Created output directory: { output_dir } " )
2020-09-27 23:21:31 +03:00
# Save non-interpolated config
raw_config . to_disk ( output_dir / " config.cfg " )
2020-06-03 15:45:00 +03:00
msg . good ( " Saved config file in the output directory " )
2020-09-17 12:48:04 +03:00
2020-09-13 15:05:05 +03:00
pretrain (
config ,
output_dir ,
resume_path = resume_path ,
epoch_resume = epoch_resume ,
use_gpu = use_gpu ,
2020-09-28 22:17:10 +03:00
silent = False ,
2023-04-03 16:24:03 +03:00
skip_last = skip_last ,
2020-09-13 15:05:05 +03:00
)
2019-06-16 14:22:57 +03:00
msg . good ( " Successfully finished pretrain " )
2018-11-16 01:44:07 +03:00
2018-11-28 20:04:58 +03:00
2020-09-13 15:05:05 +03:00
def verify_cli_args ( config_path , output_dir , resume_path , epoch_resume ) :
2020-12-08 12:41:18 +03:00
if not config_path or ( str ( config_path ) != " - " and not config_path . exists ( ) ) :
2020-07-03 18:57:28 +03:00
msg . fail ( " Config file not found " , config_path , exits = 1 )
if output_dir . exists ( ) and [ p for p in output_dir . iterdir ( ) ] :
if resume_path :
msg . warn (
2020-09-03 14:13:03 +03:00
" Output directory is not empty. " ,
" If you ' re resuming a run in this directory, the old weights "
" for the consecutive epochs will be overwritten with the new ones. " ,
2020-07-03 18:57:28 +03:00
)
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. " ,
)
if resume_path is not None :
2021-04-28 10:17:15 +03:00
if resume_path . is_dir ( ) :
# This is necessary because Windows gives a Permission Denied when we
# try to open the directory later, which is confusing. See #7878
msg . fail (
" --resume-path should be a weights file, but {resume_path} is a directory. " ,
exits = True ,
)
2020-07-03 18:57:28 +03:00
model_name = re . search ( r " model \ d+ \ .bin " , str ( resume_path ) )
if not model_name and not epoch_resume :
msg . fail (
" You have to use the --epoch-resume setting when using a renamed weight file for --resume-path " ,
exits = True ,
)
elif not model_name and epoch_resume < 0 :
msg . fail (
f " The argument --epoch-resume has to be greater or equal to 0. { epoch_resume } is invalid " ,
exits = True ,
)