spaCy icon indicating copy to clipboard operation
spaCy copied to clipboard

Recognized entities disappear after running retokenizer

Open chrisdengso opened this issue 5 years ago • 4 comments

I've run into an odd bug where a previously recognized entity stops being recognized in the exact same sentence after retokenizer.merge has been called. I also tried to run Spacy from the latest master, but the issue perseveres.

The following example shows how it fails.

How to reproduce the behaviour

import spacy
from spacy import Language
from spacy.tokens import Doc, Token


Token.set_extension('is_merged', default=False)


@Language.component(
    "merge_single_characters",
    requires=["doc.ents", "token.ent_iob", "token.ent_type"],
    retokenizes=True,
)
def merge_single_characters(doc: Doc):
    """Merge single characters into a single token.
    doc (Doc): The Doc object.
    RETURNS (Doc): The Doc object with merged entities.
    """
    with doc.retokenize() as retokenizer:
        fromIdx = None
        toIdx = None

        l = len(doc)

        for idx, token in enumerate(doc):
            isMatch = len(token.text) == 1 or token.is_space or token.is_punct
            if isMatch:
                if fromIdx is None:
                    if token.is_alpha:
                        fromIdx = token.i
                else:
                    toIdx = token.i+1

            if (not isMatch or l == idx+1) and fromIdx is not None and toIdx is not None:
                if toIdx - fromIdx > 1:
                    span = doc[fromIdx:toIdx]
                    retokenizer.merge(span, attrs={"_": {"is_merged": True}})
            if not isMatch:
                fromIdx = None
                toIdx = None

    return doc


nlp = spacy.load('en_core_web_lg')

nlp.add_pipe("merge_single_characters")

sentence = "with Comcast.Patricia l.lastname is a person in this example."

# PASS
docA = nlp(sentence)
assert docA.ents[0].label_ == "PERSON"

# Run retokenizer
nlp("t e s t")

# FAIL
docB = nlp(sentence)
assert docB.ents[0].label_ == "PERSON"

I know it's a very specific example, and the text isn't correctly formatted but it seems like a bug nevertheless.

Your Environment

  • spaCy version: 3.0.5
  • Platform: macOS-11.2.3-x86_64-i386-64bit
  • Python version: 3.9.2
  • Pipelines: en_core_web_lg (3.0.0), en_core_web_sm (3.0.0), en_core_web_trf (3.0.0)

chrisdengso avatar Apr 06 '21 06:04 chrisdengso

Thanks for the report! This is definitely a bug. It's related to the vector table and not the retokenizer itself. The token l.lastname doesn't have a vector, and there's a bug in how unknown vectors are handled.

If you're interested in the gory details:

If a model has vectors, the retokenizer adds a new vector to the vector table for the merged token based on the vector for the span. The bug is that Vectors returns the index -1 for unknown tokens and StaticVectors treats that as an index and uses the last row in the vector table. In the unmodified en_core_web_lg, the last row is a vector for some rare token, but after the vector table is resized after adding new vectors, the last row is all zeroes, which changes the model predictions for l.lastname. Well, it doesn't really matter than it's all zeros, all that matters is that the last row is different.

StaticVectors should be modified to use an all-0 vector for -1 instead of the last row in the table.

adrianeboyd avatar Apr 06 '21 08:04 adrianeboyd

That's great, thanks for the fix already! Looking forward to v 3.1.

chrisdengso avatar Apr 07 '21 02:04 chrisdengso

If you're training your own models, this fix will be in the upcoming v3.0.6 if you use the new default config settings.

Unfortunately there's really no way to fix existing pretrained pipelines because they've learned that this random/rare vector was UNK rather than a 0-vector and there's not currently a way to specify a particular row as the UNK vector, either.

If you really need consistent predictions for a test suite or similar, you can get them by switching to spacy.MultiHashEmbed.v2 in your config for an existing pipeline (none of the config parameters have changed so editing this by hand won't break anything), but the predictions will probably be worse overall because of the different UNK behavior.

adrianeboyd avatar Apr 22 '21 09:04 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 23 '21 00:10 github-actions[bot]