spaCy icon indicating copy to clipboard operation
spaCy copied to clipboard

Documentation/specification of vocabulary file for spacy init-model

Open emiguevara opened this issue 6 years ago • 10 comments

I am trying to make a custom model for spacy 2.2. This involves using the latest init-model, which requires a JSONL vocabulary file. I have done this in the past, using v. 2.0, and then all that was needed was a frequency list, clusters and embeddings model (deprecated options --freqs-loc and --clusters-loc).

  • How can I make my own vocabulary file? Is it possible to extract it from older models? Is there a dedicated script for this?
  • Are the vocabulary files for the official models available?
  • How are the "oov_prob" and "prob" values defined?
  • Are there any extensive specifications for the lexicon format? I am thinking about obligatory and optional fields, default values, etc.

Which page or section is this issue related to?

  • https://spacy.io/api/cli#init-model
  • https://spacy.io/api/annotation#vocab-jsonl
  • https://spacy.io/usage/adding-languages#vocab-file

emiguevara avatar Jan 16 '20 09:01 emiguevara

This isn't documented very well, sorry!

I haven't tried it, but from the code it looks like you can still provide --freqs-loc and --clusters-loc instead of -json-loc if you'd like. However, in v2 the models don't rely on as much of this information as in v1. In particular, the probability and the cluster attributes aren't used by any of the v2 models. The vocab file is optional, so you can run spacy init-model just with vectors if you want.

Spacy's small models are trained without a vocab file and you can see how most of the other attributes can be computed dynamically for a particular token. In the md and lg files the attributes like .prob and .cluster are still there if you'd like to use them, but they're not really necessary.

I think you could reverse engineer everything out of a md or lg model by finding all strings nlp.vocab.strings, lookup up the lexemes in nlp.vocab to find the cases where is_oov is False, and then looking up all the attributes for those tokens, but I don't really think it's necessary. (I don't know of any obvious reason why the vocab files couldn't be distributed, since the exact same information is all available in the models.)

adrianeboyd avatar Jan 16 '20 10:01 adrianeboyd

We could distribute those vocab jsonl files, that's a good idea. I actually did exactly the vocab-to-jsonl process @adrianeboyd mentioned when I implemented the jsonl system. This was a one-off script though; I don't have it handy. Currently downloading the vocab (it's zipped with the vectors) to paste you a snippet.

The probability values are log probabilities. I estimated them using Simple Good-Turing smoothing, using the implementation here: https://github.com/explosion/preshed/blob/master/preshed/counter.pyx . After creating the table, call counter.inc over your samples, and then call counter.prob with the key. If you try this on an unrealistic toy example you might get a (poorly worded) error. The smoothing assumes you'll have more items occurring with a count of 1 than a count of 2, which will be true of any non-trivial sample of language.

The history of the clusters.txt and freqs.txt files is that I simply didn't know about jsonl when I was designing those things, and I really struggled to come up with a format that could handle arbitrary characters. I ended up using Python repr(), which is obviously pretty bad.

honnibal avatar Jan 16 '20 11:01 honnibal

Thanks a lot for all the help! I will then reverse engineer my previous vocabulary more or less like this [lex for lex in nlp.vocab if lex.is_oov == False] and then formatting/saving to JSONL.

Out of curiosity, though, will training quality be affected if the lexicon file is available for init-model?

emiguevara avatar Jan 16 '20 12:01 emiguevara

Since prob and cluster aren't really used, I was wondering if there is any real speed advantage to preloading all the easily-derivable lexeme stuff? Is it worth extra loading time to create all the lexemes?

adrianeboyd avatar Jan 16 '20 12:01 adrianeboyd

@adrianeboyd Currently it isn't worth it, no. This is one of the things I want to talk about in the sprint: your PhraseMatcher changes took away one of the last real "load bearing" things the Vocab was doing, so we can now transition it to just be a dumb cache.

We would need to change the class to keep the probability and cluster separate, so that you can have those stored without having a LexemeC object.

honnibal avatar Jan 20 '20 11:01 honnibal

Hi I just wanted to follow on from this issue, because I believe I am running into the same thing. I have created a Word2Vec embedding with Gensim for a specific domain. I have packaged the word embeddings into a spaCy model with:

spacy init-model en my_spacy_model --vector-loc path/to/w2v.txt

I have not included any vocabulary data with the --jsonl-loc option.

I was testing that things and came across this issue - a word in lower case had a word vector, but if it was in upper case it didn't:

import spacy 

nlp = spacy.load("my_spacy_model")
doc = nlp("copd COPD")
for token in doc:
    print(token, token.vector[0:3], token.is_oov, token.lower)

# > copd [1.2579243  -0.43484268 -2.6918478] True 5901122368271152623
# > COPD [0. 0. 0.] False 5901122368271152623

We lowercase everything in the preprocessing before Word2Vec training, so I understand that there is not an entry to COPD in the Word2Vec file, but I want spaCy to match the uppercase COPD with the lowercase copd when fetching its word embedding vector. Both have a matching token.lower attribute hash.

I tested this with the en_core_web_md model, with the word dog and it came back as expected:

import spacy 

nlp = spacy.load("en_core_web_md")
doc = nlp("dog DOG")
for token in doc:
    print(token, token.vector[0:5], token.is_oov, token.lower)

#> dog [-0.40176   0.37057   0.021281] True 7562983679033046312
#> DOG [-0.40176   0.37057   0.021281] True 7562983679033046312 

Is the solution here to provide vocabulary data when packaging the the model with spacy init-model? If it is I guess I have the same questions that the original author of this issue raised:

  • How can I make my own vocabulary file? Is it possible to extract it from older models? Is there a dedicated script for this?
  • Are the vocabulary files for the official models available?
  • Are there any extensive specifications for the lexicon format? I am thinking about obligatory and optional fields, default values, etc.

Essentially I'm confused about which parts of the model are out of the box, and which are the parts I have to provide myself.

Thanks, Dan

1danjordan avatar Dec 10 '20 17:12 1danjordan

There's no out-of-the-box support for lowercase-only vectors, so if you want to have variants, you'll have to add them yourself. (It turns out that I'm actually not sure what the source is for some of the variants in the English models? I'm not sure if it's from the original glove vectors or if it's a spacy-specific enhancement that happened before my time. It also looks like the vector table is wasting a lot of space by storing duplicate vectors separately, and I'm not sure when the unintended duplication happened in the history of the models. If you look at en_vectors_web_lg, you can see that dog and DOG have different vectors and in en_core_web_lg both look the same as DOG but are separate entries underneath. This is a bit weird and I had never noticed...)

In any case, what you want to do is add the variants that you want by pointing them to the right row in the vectors table with vectors.add:

row = nlp.vocab.vectors.find(key="copd")
nlp.vocab.vectors.add("COPD", row=row)

After doing this for all the tokens you want to modify, save and reload the model with nlp.to_disk("/path/to/model") and spacy.load("/path/to/model") and then the vectors will be ready for use with all the statistical components. The similarity functions will work without reloading, but saving and reloading is the most foolproof way to get the vectors reloaded correctly for the statistical models.

To avoid headaches with how the vectors are loaded in the background, it's also a good idea to give the modified vectors a new unique name before saving the model. You can set the name by setting nlp.vocab.vectors.name. Set the name before adding any statistical components that use the vectors so that their configs get initialized with the right vectors name. (The idea is that you can use the same name in multiple models and if the models are loaded in the same script, the vectors should only be stored in memory once. The idea is nice, but it turns out to be a bit of a headache because init-model doesn't force you to set a name and people end up unintentionally using the same default name for different sets of vectors, which breaks their models if they're loaded at the same time.)

The only other interesting parts of the vocab files are norm, prob, and cluster, which have been moved to lookups tables within the vocab in v2.3. You can either load custom tables into nlp.vocab.lookups or set values through the vocab (Lexeme) entries, e.g., nlp.vocab["the"].prob = 0.012345 and those values will be saved with the model with nlp.to_disk(). The rest isn't really necessary because things like prefix and lower can just be calculated from the word form when the token is added to the vocab.

adrianeboyd avatar Dec 11 '20 07:12 adrianeboyd

Hi Adriane,

Thanks for the detailed response. So I've just retrained the Word2Vec model without an lowercasing which has worked out perfectly. I have a follow up question about the vocab file. If prefix and lower and so the other properties are computed on the fly when entries are added to the vocab and norm, prob and cluster have moved to lookup tables, then is there any need for providing a vocabulary JSONL file when running init-model?

1danjordan avatar Dec 15 '20 09:12 1danjordan

No, you don't really need it.

adrianeboyd avatar Dec 15 '20 09:12 adrianeboyd

This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.

github-actions[bot] avatar Oct 28 '21 00:10 github-actions[bot]