Implement things¶
This page is for the people who add to Pie Extended: a model, the tokenizer of a language, a processor, an engine. It goes from
what needs no code to what does. Every block that is written with python below is run by the tests of the package
(tests/test_docs_extending.py), so it works as shown; the blocks written with py need a model, the network, or a change of
the package, and are not run.
The pieces¶
Piece |
What it is |
Where it is |
|---|---|---|
Model |
The Hugging Face model that is run, and how it is described |
a |
Process |
The code that goes with a model: how the text is cut, how the output is built |
a |
Tokenizer |
Cuts a text in sentences and words, and remembers what it replaced |
|
Excluder |
A kind of token that is not tagged (references, abbreviations…) and is given back |
|
Processor |
Changes the predictions of a token into the columns of the output; they are chained |
|
Disambiguator |
Changes the predictions of a sentence before the processors |
|
Engine |
Something that predicts: PaPie 1.0, Sôtêr, a spaCy pipeline |
|
text ─▶ tokenizer ─▶ data iterator ─▶ engine(s) ─▶ (disambiguator) ─▶ processors ─▶ columns ─▶ TSV
└ excluders: not tagged, given back ┘
Run a model that nobody wrapped¶
A model of Hugging Face runs with no code. Its name is organisation/repository#variant (add @commit to pin it):
pie-extended tag biblissima-textes/papie-greek#gold text.txt
Nothing wraps it, so it gets the generic process: the simple tokenizer, and the columns that the model gives (read from its
config.json). To give it the tokenizer and the columns of a model of the package, tell which one:
pie-extended tag someone/a-latin-model#v1 text.txt --wrap lasla
--wrap is for a model whose heads are the ones the process expects (lasla needs lemma, pos and the morphology). In
Python, pie_extended.wrappers.wrap_as("someone/a-latin-model#v1", "lasla") does the same before get_tagger. If the model is a
pack (#pack/*, one network for each task), its tasks cannot be known without loading it: give them with --model_path:
pie-extended tag lasla text.txt --model_path "<papie:someone/legacy#pack/*,lemma,pos>"
Add a model¶
A model is a line of the table of pie_extended.models. Call it foo.
The process. If the processes of the model already exist (the tokenizer of the family of languages, the processors of the tagset), name them. If not, write them (next sections) in a module of
pie_extended/processes/, and give them a name in itsPROCESSESdictionary with aProcess:pipeline(max_tokens=256)Required. Returns the data iterator and the processor.
chained()anditerator_for()build them.addons(model)Optional. What
pie-extended install-addonsruns (install a pipeline, learn a segmenter…). It receives theModel.disambiguator,disambiguation_tasksOptional. A
Disambiguator, or anObjectCreatorthat builds one (so that its state is renewed), and the tasks that have to be computed for it to run.
# pie_extended/processes/foo.py from pie_extended.pipeline.iterators.proto import DataIterator from pie_extended.pipeline.postprocessor.proto import ProcessorPrototype from pie_extended.pipeline.tokenizers.simple_tokenizer import SimpleTokenizer from pie_extended.processes import Process def foo_pipeline(max_tokens=256): return DataIterator(tokenizer=SimpleTokenizer(), max_tokens=max_tokens), ProcessorPrototype() PROCESSES = {"foo": Process(foo_pipeline)}
For a model that needs nothing of its own,
simple:genericis the process of any model of Hugging Face.The table. Add a
ModeltoMODELSinpie_extended/models.py. Without this, the command does not see the model.Model( name="foo", lang="foo", # a language: an ISO 639 code when there is one title="Foo", authors=["Author 1", "Author 2"], description="A readable description", link="A link to more information", models=papie_models("my-org/papie-foo", "default", ["lemma", "pos"]), process="foo:foo", # the module of pie_extended/processes, and the name in its PROCESSES ),
modelssays where the model is and which tasks you want from it:<papie:repository#variant,task,task>, written bypapie_models(). A variantpack/*is the networks of a language, one for each task.fileslists what has to be downloaded besides the model (lexicons…), asFile. The description feedspie-extended listand the table of Models; a model of Hugging Face that aModeldescribes is also known by its Hub name (pie-extended listshows it).Test it without the model, with the fake tagger: it gives
lemma0,pos0… to the tokens it receives.from pie_extended.cli.utils import get_model, get_imports from pie_extended.testing_utils import FakeAutoTag model = get_model("foo") tagger = FakeAutoTag.from_model_string(model.Models, batch_size=16) iterator, processor = get_imports(model).get_iterator_and_processor() print(tagger.tag_str("Un texte.", iterator=iterator, processor=processor))
Document it: add the model to the table of what each model needs and to the section on the models in Models, and add a line to
CHANGES.md.
For examples, read dum (nothing of its own, processes/simple.py), fro (a tokenizer, rules and glued columns,
processes/french.py) and lasla (enclitics and a disambiguator, processes/latin.py). Several models can share one
process: frm runs the one of fro.
Write a tokenizer¶
Most of the languages tokenize in the same way: sentences end at some characters, the punctuation is put apart, some tokens
(references, abbreviations, numbers) are put aside to be given back, and the tagger is shown a replaced version of the
others (v written u, the roman numbers turned into 2…). RuleTokenizer
does all that, and a language gives its data:
excluders(registry)The tokens that are not tagged. They are given back, in place, with the value of the model for what is excluded.
replace(token)What the tagger sees of a token that no excluder took. The original is kept in memory, and written in the column
treated. By default, the token itself.re_sentence_boundaries,re_add_space_around_punctWhere sentences end (by default
. ? ! …and the closing quotes and brackets), and which punctuation is put apart.strict_lower,new_char_registry()Details that some languages need:
loweronly if it isTrue, and a registry of characters shared between tokenizers.
from pie_extended.pipeline.tokenizers.rules import RuleTokenizer
from pie_extended.pipeline.tokenizers.utils.excluder import ReferenceExcluder
class FooTokenizer(RuleTokenizer):
""" What the tagger sees: `v` is written `u` """
def excluders(self, registry):
return (ReferenceExcluder(char_registry=registry),) # `[REF:1.2]` is not tagged, and given back
def replace(self, token: str) -> str:
return token.replace("v", "u").replace("V", "U")
tokenizer = FooTokenizer()
for sentence in tokenizer.sentence_tokenizer("Veni, vidi [REF:1.2] vici. Alia sententia!"):
print(sentence)
print(tokenizer.tokens[:3]) # (position, what was written, what the tagger sees)
print(tokenizer.exclude_patterns())
['Ueni', ',', 'uidi', '[REF:1.2]', 'uici', '.']
['Alia', 'sententia', '!']
[(0, 'Veni', 'Ueni'), (1, ',', ','), (2, 'vidi', 'uidi')]
[regex.Regex('(\\[REF:[^\\]]+\\])', flags=regex.V0)]
The excluders that exist are in pie_extended.pipeline.tokenizers.utils.excluder: ReferenceExcluder ([REF:...]),
RegexpExcluder (any pattern), ApostropheExcluder, DottedNumberExcluder, AbbreviationsRemoverExcluder and
CompoundAbbreviationsExcluder (a list of abbreviations)… A tokenizer that is not like the others (the Armenian one cuts
words, and writes where the pieces are) subclasses SimpleTokenizer or MemorizingTokenizer instead, and gives
surface_tokens() if it does not write the words as they are (see API usage).
Important
A change in a tokenizer changes the tokens that a model sees, and so its predictions. Before touching the tokenizer of a language, record what it gives (see Keep the output below).
Write the processors¶
A processor turns what the engine predicted (one value for each task) into the columns that are written. They are chained:
each one wraps the one that follows it, and changes its output. The columns that are asked for with --tasks and the heads
that are computed follow from the chain, so a processor has to say what it needs:
set_tasks(tasks)receives the tasks that were predicted and gives back the columns it produces;required_tasks(requested, available)gives the tasks to compute to produce the columns that are requested (a glued column needs all the columns it glues).
The ones that exist are in API usage. The usual two to write are a glue and rules.
GlueProcessorMerges columns into one:
OUTPUT_KEYSis what is written,GLUEwhat is merged in each,EMPTY_TAGthe values that count as empty,GLUE_EMPTYwhat to write when all are empty.RuleBasedProcessorrules(annotation)receives the dictionary of one token and returns it changed. Withapply_on_reinsert=True, it also sees the tokens that were put aside (punctuation that the model never saw).
A pipeline is a function that builds the data iterator and the chain. chained() takes the
links from the outermost to the innermost (the last one is an instance), and
iterator_for() an iterator that does not give the excluded tokens of the tokenizer:
from functools import partial
from typing import Dict
from pie_extended.pipeline.build import chained, iterator_for
from pie_extended.pipeline.postprocessor.glue import GlueProcessor
from pie_extended.pipeline.postprocessor.memory import MemoryzingProcessor
from pie_extended.pipeline.postprocessor.proto import ProcessorPrototype
from pie_extended.pipeline.postprocessor.rulebased import RuleBasedProcessor
from pie_extended.testing_utils import FakeAutoTag
class FooGlue(GlueProcessor):
""" Merges the columns `Case` and `Numb` into `morph` """
OUTPUT_KEYS = ["form", "lemma", "pos", "morph"]
GLUE = {"morph": ["Case", "Numb"]}
EMPTY_TAG = {"Case": "_", "Numb": "_"}
class Numbers(RuleBasedProcessor):
def rules(self, annotation: Dict[str, str]) -> Dict[str, str]:
if annotation["form"].isdigit():
annotation["pos"] = "NUM"
return annotation
def foo_pipeline(max_tokens=256):
tokenizer = FooTokenizer()
processor = chained(
Numbers, # the first to see a token
partial(MemoryzingProcessor, tokenizer_memory=tokenizer), # the column `treated`
FooGlue,
ProcessorPrototype(), # the predictions as they are
)
return iterator_for(tokenizer, max_tokens), processor
iterator, processor = foo_pipeline()
tagger = FakeAutoTag(["lemma", "pos", "Case", "Numb"])
for token in tagger.tag_str("Veni 12 [REF:1.2] vici.", iterator=iterator, processor=processor):
print(token)
{'form': 'Veni', 'lemma': 'lemma0', 'pos': 'pos0', 'morph': 'Case=Case0|Numb=Numb0', 'treated': 'Ueni'}
{'form': '12', 'lemma': 'lemma1', 'pos': 'NUM', 'morph': 'Case=Case1|Numb=Numb1', 'treated': '12'}
{'form': '[REF:1.2]', 'lemma': '_', 'pos': '_', 'morph': '_', 'treated': '--IGN.--'}
{'form': 'vici', 'lemma': 'lemma2', 'pos': 'pos2', 'morph': 'Case=Case2|Numb=Numb2', 'treated': 'uici'}
{'form': '.', 'lemma': 'lemma3', 'pos': 'pos3', 'morph': 'Case=Case3|Numb=Numb3', 'treated': '.'}
The reference was not tagged and was given back, in its place, with the values of the excluded tokens. Name the function in a
PROCESSES (see Add a model) and your model has it.
Make the output follow --tasks¶
--tasks and --disable-tasks need nothing from you if the processors say what they need (above): the columns are the ones of
set_tasks, and what has to be computed is worked out from them. Two things to know:
a column that another one needs (the lemma, for a disambiguator that uses it) has to be in
disambiguation_tasksof theProcess, so that it is computed even if it is not written;a task that the model does not give must not make the processors fail: ask for
lemmaonly, and see that your chain still works (GlueProcessorandSplitterPostProcessoralready skip what is missing).
iterator, processor = foo_pipeline()
tagger = FakeAutoTag(["lemma", "pos"]) # a model that gives no morphology
print(tagger.tag_str("Veni", iterator=iterator, processor=processor))
[{'form': 'Veni', 'lemma': 'lemma0', 'pos': 'pos0', 'treated': 'Ueni'}]
Learn the cuts of a treebank¶
Some treebanks cut written words (զմեղս is զ and մեղս), and the models that were trained on them expect the same
cuts. When no rule can say where (many words legitimately start with the letters of a proclitic), the cuts are learned:
LearnedSegmenter is an averaged perceptron that decides, for each position
in a word, from the letters around it and from the word itself (a lexicon for the words it has seen). A language gives its
data, nothing more: the letters of its words, its tokenizer (to know the tokens that are cut) and a treebank:
import regex as re
from pie_extended.pipeline.tokenizers.learned import LearnedSegmenter
class Toy(LearnedSegmenter):
WORD = re.compile(r"^[a-z]+$") # only words made of these letters are cut
class Words:
""" The tokenizer of the language, without the cuts (`segmenter` is given to see what it does with them) """
def __init__(self, segmenter=None):
self.segmenter = segmenter
def reset(self):
pass
def word_tokenizer(self, text, lower=False):
return [piece for word in text.split() for piece in (self.segmenter.split(word) if self.segmenter else [word])]
# The treebank cuts the prefix `un` of verbs: sentences as written, and their words
treebank = [("undo it", ["un", "do", "it"]), ("undress me", ["un", "dress", "me"]),
("uncle is here", ["uncle", "is", "here"]), ("untie it", ["un", "tie", "it"])] * 6
examples = Toy.training_examples(treebank, Words()) # where the treebank cuts each token
segmenter = Toy.train(examples, epochs=10)
print(segmenter.split("undo"), segmenter.split("uncle"))
print(segmenter.evaluate(treebank, lambda segmenter=None: Words(segmenter))["sentences_exact"])
['un', 'do'] ['uncle']
1.0
To make it a model’s step: segmenter.save(path) and Toy.load_or_warn(path, "learn it first") at the start of the pipeline, and
an addons(model) that calls learn() with the URLs of the treebank, so that
pie-extended install-addons foo learns it on the machine of the user. Classical Armenian (processes/armenian.py) does
exactly this, and does not distribute the weights because the license of its treebank (NC-SA) would apply to them.
Add an engine¶
An engine predicts. CompositeTagger takes each task from the engine that gives it, and an
engine only has to look like a tagger: tag(sentences, lengths=None) returns the tagged sentences and the tasks.
class MyEngine:
TASKS = ("lemma",)
def load(self):
... # imported lazily: the library is optional
return self
def tag(self, sents, lengths=None, **kwargs):
tagged = [[(token, (my_lemma(token),)) for token in sentence] for sentence in sents]
return tagged, ["lemma"] # for each token: (token, (a value for each task, in the order of the tasks))
Then give it a prefix in pie_extended/composite_tagger.py (engine_of tells which engine a name designates, add_model
builds it; look at papie: and soter:), and use it in a Model (models="<myengine:name,lemma><papie:...,pos>") or in
--model_path. Keep the library optional: import it in load() and say how to install it if it is missing (see
pie_extended/soter.py). A task must come from one engine only, and that is checked before anything is loaded.
Test it¶
Without the model, with
FakeAutoTag(above): it checks your tokenizer, your processors and the columns.With realistic values: the fake gives
pos0, which no rule of yours knows.tests/golden_processors.pyhas a fake tagger that gives values from short lists of real ones.The tests of a model that needs the network must be skipped without it (see
PIE_EXTENDED_HUB_TESTSintests/test_papie.py), and the ones that need another library (spaCy,transformers) without it.
Keep the output¶
Before changing a tokenizer or a processor that works, record what it gives, and see that it gives the same after:
tests/golden_tokenizers.py and tests/golden_processors.py write what every language gives for texts with their tricky cases
(tests/data/tokenizers.json, tests/data/processors.json), and the tests test_tokenizers_golden and
test_processors_golden compare. Add your language to their LANGUAGES, run python -m tests.golden_tokenizers and
python -m tests.golden_processors once, and review the files that are written: they are what you promise to keep.
Publish a model¶
The models are the ones of PaPie 1.0, see its documentation. Once a model is trained
(papie fit -c config.yaml), it is exported as a folder of plain files (no pickle) and pushed to Hugging Face:
papie export-model --ckpt best.ckpt --out my-model --license cc-by-4.0 --language grc --variant default --default
papie push-model my-model my-org/papie-foo # private by default; --public to publish
Then pin it in a Model (papie_models("my-org/papie-foo", "default", [...])), with the revision (@commit) if you want
the results to be reproducible. State the data and its license in the card: a model can inherit the terms of what it was
trained on.