Candidate features
A language-independent, opt-in input that tells the model the possible (lemma, POS) readings of each form, from a dictionary or an external analyzer. Off unless model.candidates is configured.
Sources: dictionary (TSV; works for any language), collatinus (Latin only; pycollatinus [pycollatinus; Collatinus]
, needs a regex tag_map onto the dataset tagset), ikelos (Ancient Greek, built in), callable (module:function: any analyzer in a few lines, see the Ikelos example), or any class_path. Each is cached per form (cache_path persists it).
Features per word and source: POS multi-hot · counts (lemmas, POS, unknown, ambiguous) · optional hashed bag of lemma strings. dropout hides a word’s candidates during training, so the model copes with missing or wrong analyses.
Where it plugs into the network
The features are added inside the embedding module, right after the character encoder and before the sentence encoder. A linear layer maps them to each target’s size, and the result is added to two tensors:
emb, the word vector (inject: emb). It then goes through the sentence encoder, so the information reaches (a) the POS/morphology heads, which read the sentence encoder’s output, and (b) the lemma decoder’s context, the per-word vector it receives at every decoding step. Without a sentence encoder (use_sentence_encoder: false) it feeds the heads and decoders directly.outs, the per-character (or per-byte) states of the word (inject: outs, masked to the word’s real length). These are what the lemma decoder attends over while it writes the lemma; with the T5 decoder they are the prompt states it cross-attends to.
Both linear layers start at zero, so at step 0 the network is exactly the baseline and the candidates only matter once training finds them useful. They are cached per form, computed on the CPU, and add no parameters beyond those two layers.
What it cannot do (yet). Candidates are encoded as features, not as strings the decoder can emit. The copy mechanism still points at the word’s own characters, so a candidate lemma cannot be copied in; the hashed lemma bag is only a fuzzy hint of which lemmas are plausible. Stronger designs — candidate strings as an extra copy source, or appended to the T5 prompt — are not implemented.
python -m papie.cli fit -c config.yaml -c candidates.yaml # candidates.yaml: the `model.candidates` block below
python -m papie.lexicon.precompute -c … -c … --split dev # caches + oracle
model.candidates is top-level so that layering yaml files does not overwrite model_config. A dictionary built from the training set leaks the gold reading (mitigations: min_count, dropout, another corpus).
Example: Collatinus for Latin (LASLA data)
Oracle on the dev set (how often the gold is among the candidates, before any model):
| Unknown forms | 0.6 % |
| Ambiguous forms | 60 % (3.6 candidates on average) |
| Gold lemma among candidates | 88.7 % |
| Gold POS among candidates | 93.0 % |
The model already reaches 97 % lemma and 97 % POS without help, so Collatinus covers less than the model predicts; any gain has to come from the forms the model gets wrong (unknown or ambiguous). The LASLA tags are derived from Collatinus’ coarse codes by hand (the mapping is given below); lemma conventions agree (u/v, capitalised proper nouns). pycollatinus predates Python 3.10, so the source applies a small collections compatibility shim when it imports it.
Collatinus tag mapping for the LASLA tagset
model:
candidates:
inject: [emb, outs]
pos_task: pos
lemma_hash_dim: 64
dropout: 0.2
sources:
- name: collatinus
tag_map: # first match wins; matched text is "<pos> <morph>[ UPPER]"
- ["^n\\s.*UPPER", NOMpro]
- ["^n\\b", NOMcom]
- ["^a\\s.*UPPER", ADJqua]
- ["^am\\b", [ADJcar, ADJord, ADJdis, ADJmul]]
- ["^a\\b", ADJqua]
- ["^v\\b", VER]
- ["^ap\\b", [PROdem, PROind, PROpos, PROrel, PROint, ADJqua]]
- ["^p\\b", [PROdem, PROrel, PROind, PROper, PROpos, PROint, PROref, PROpos.ref]]
- ["^d\\b", [ADV, ADVneg, ADVrel, ADVint]]
- ["^cd\\b", CONcoo]
- ["^cr\\b", [CONsub, CONcoo]]
- ["^c\\b", [CONsub, CONcoo]]
- ["^rd\\b", [PRE, CONsub, ADV]]
- ["^r\\b", PRE]
- ["^(i|e|id)\\b", [INJ, ADV]]
- ["^m\\b", [ADJcar, ADJord]]
The Collatinus codes are n noun, a adjective, v verb, p pronoun, ap determiner, d adverb, c subordinating and cd coordinating conjunction, r preposition, rd preposition/adverb/conjunction, i interjection, am numeral adjective, m letter or numeral.
Trained on the LASLA data with the best benchmark architecture, the candidate features gave a small gain on the test set:
| Run | Lemma acc. | POS acc. | Note |
|---|---|---|---|
| Best benchmark architecture (baseline) | 0.9718 | 0.9666 | test, best epoch 33 |
| + Collatinus candidate features | 0.9730 | 0.9683 | test; +0.12 lemma, +0.17 POS (one run) |
This is a single run (no seeds, no significance test), so treat it as suggestive.
Example: an analyzer as a function (Ikelos for Ancient Greek)
Any analyzer can be plugged in with a function that takes a form and returns its possible readings, with no change to the library. Ikelos is a Python port of the Morpheus analyzer: it lists the readings of a Greek form and does not choose one. This is the function (put it in a module on your Python path, here greek_ikelos.py):
import unicodedata
import ikelos
def candidates(form):
"""Readings of a Greek form as (lemma, label) pairs; the label is Ikelos' own class."""
try:
analyses = ikelos.analyze(unicodedata.normalize("NFC", form))
except Exception: # a form Ikelos cannot analyse has no candidates
return []
readings = []
for a in analyses or []:
lemma = unicodedata.normalize("NFC", a.lemma).rstrip("0123456789") # ἐράω1 -> ἐράω
label = a.pos if a.pos != "indeclinable" else f"indeclinable {a.stemtype}"
if (lemma, label) not in readings:
readings.append((lemma, label))
return readings
What the function may return for a form: a list of lemma strings, of (lemma, pos) pairs, or of {"lemma": ..., "pos": ...} dicts; an empty list for an unknown form. It is called once per distinct form (the results are cached), so it can be slow, and it runs on the CPU only.
No tag mapping. The labels are Ikelos’ own: noun, verb, participle, and, for indeclinable words, indeclinable plus the stem class (indeclinable article, indeclinable prep, indeclinable conj, …). The Collatinus example above needs a regex table onto the dataset’s tags; here there is none. The features go through a learned linear layer, so they only have to be consistent, not to match the model’s tagset, and mapping Ikelos’ classes onto UD tags would only add approximation.
Config (model.candidates, layered on a normal Greek config):
model:
candidates:
inject: [emb, outs] # the word vector and the byte states the decoder attends over
lemma_hash_dim: 64 # a hashed bag of the candidate lemmas
dropout: 0.2 # hide a word's candidates in 20 % of the training cases
pos_vocab: # the feature vocabulary = the labels the function returns (50 here)
- noun
- verb
- participle
- indeclinable article
- indeclinable prep
- indeclinable conj
# … every label that occurs in the cache, see step 3
sources:
- name: callable
function: greek_ikelos:candidates
cache_path: runs/candidates/ikelos_greek.json
Steps
pip install ikelos, and makegreek_ikelos.pyimportable (for example run from its folder, orPYTHONPATH=.).- Build the cache: the function runs once on every distinct form of the train, dev and test files (123 286 forms; about 15 to 20 minutes on one thread, because Ikelos handles about 129 forms per second). Training then reads the cache and never calls Ikelos.
python -m papie.lexicon.precompute -c config.yaml -c candidates.yaml --split dev - Get the vocabulary from the cache. The label is the second item of each candidate:Paste the list under
import json cache = json.load(open("runs/candidates/ikelos_greek.json", encoding="utf8")) print(sorted({c[1] for cands in cache.values() for c in cands if c[1]}))pos_vocab. It is written into the config explicitly so that an exported model carries it and needs no cache at inference. - Train as usual:
python -m papie.cli fit -c config.yaml -c candidates.yaml.
On the dev set, the gold lemma is among Ikelos’ candidates for 87.3 % of the tokens (96.6 % of the forms it knows), with about 1.3 candidates per form.
A built-in shortcut. The library ships this same function as a source: replace the callable entry with - name: ikelos (plus the same cache_path) and nothing else. It gives the same readings (checked on a set of forms) and is what the Greek models below were trained with.
Result. On the gold Greek test file the model with Ikelos features gains about 0.4 point of lemma and 0.4 of POS over the same model without them, and every period improves (details on the Greek benchmark page). These are single runs, so treat the size of the gain as approximate.
Publishing. A model trained with a function source can be exported, and the config keeps the function’s name (not the cache path). Whoever loads the model needs the module importable, so ship it as a package; with the built-in ikelos source the model card lists ikelos as the dependency instead. The Greek models on the Hub are the plain ones, without candidate features.