papie lemmatization · tagging · any language

Pretraining and benchmarking

Embedding distillation, silver-data pretraining and the CPU benchmark.

Generated from the source by tools/make_api.py; do not edit by hand.

papie.pretrain.distill

Feature distillation of a tiny soter-style student encoder from a frozen T5 teacher.

Both models see the same NFD byte sequence of each word; the loss is applied on the
aligned per-byte states of every word's target form. Run with::

    python -m papie.cli distill-embeddings -c distill.yaml [--set key=value ...]

The student checkpoint (student.pt = encoder state_dict; student.json =
its settings) loads into SoterEmbedding(soter_init='checkpoint', checkpoint=...).

feature_loss

feature_loss(pred, target, kind)

relational_loss

relational_loss(s, t, word_ids)
MSE between within-word cosine Gram matrices (dimension-agnostic).

class Distiller (nn.Module)

Distiller(self, cfg)

Distiller.infill_loss

infill_loss(self, sentences, rng)

Distiller.fill_exact

fill_exact(self, sentences, rng)
Greedy exact-match of the refilled word (the real infilling metric).

Distiller.forward

forward(self, sentences, rng=None)

sentence_stream

sentence_stream(cfg, split, epoch=0)
Sentences for split ('train' | 'val').

evaluate

evaluate(model, cfg)
Returns (val_loss, val_cos, extras); extras has fill_exact with infilling.

save_student

save_student(model, cfg, path_dir, tag='student')
<tag>.pt = encoder state_dict (loads into SoterEmbedding(soter_init='checkpoint'));
<tag>_head.pt = its Linear+LayerNorm head (head_checkpoint); <tag>_decoder.pt =
the infilling-pretrained T5 decoder (t5_checkpoint of a decoder: t5 task).

train

train(cfg)

load_config

load_config(argv)

main

main(argv=None)

papie.pretrain.teacher

Frozen T5 teacher: per-word byte-span states from plain (un-prompted) sentences.

span_index

span_index(sent_or_row, starts, ends)
Flat gather indices for many [start, end) spans at once.

sent_or_row/starts/ends are 1-D tensors (one entry per span). Returns
(span_id, row, pos) with one entry per covered position, in span order, so
hidden[row, pos] concatenates every span's states with a single gather instead
of a Python loop of tiny slices.

class TeacherEncoder

TeacherEncoder(self, model_name, device='cuda', dtype=torch.bfloat16)
Wraps a frozen T5EncoderModel (decoder discarded).

word_states(sentences, layers) encodes each sentence as
" ".join(words) bytes (+ </s>) and returns, per requested hidden-state
layer, the flat concatenation of every word's byte-span states in
sentence-major word order -- the same order/length as the student's target
spans, which makes the two byte-aligned 1:1.

layers index hidden_states (0 = embeddings, num_layers = final).

TeacherEncoder.word_states

word_states(self, sentences, layers)

papie.pretrain.data

Raw-text reader for embedding distillation.

Streams parquet files (e.g. comma-project/pen-alignment-pairs), takes one text
field, optionally filters on a lang column, normalises it and chops each row
into pseudo-sentences of at most max_words whitespace-separated words.

split_sentences

split_sentences(text: str, normalization: str, max_words: int, min_words: int=1) -> List[List[str]]

iter_parquet_sentences

iter_parquet_sentences(pattern: str, field: str='target', normalization: str='NFD', max_words: int=24, lang: Optional[List[str]]=None, lang_field: str='lang', shuffle_files: bool=False, seed: int=0, skip_rows: int=0) -> Iterator[List[str]]

batched

batched(it: Iterator, size: int, shuffle_buffer: int=0, seed: int=0) -> Iterator[list]
Group an iterator into lists of size, with an optional shuffle buffer.

class PlainTextMixture

PlainTextMixture(self, sources, normalization='NFD', max_words=24, min_words=3, val_fraction=0.02, seed=0)
i.i.d. sampler of pseudo-sentences from weighted plain-text corpora.

sources: list of {glob: str | [str], weight: float, exclude: [substr]}.
Each draw picks a source (by weight), a file **uniformly** within it (so a huge
file does not swamp small ones), a random byte offset in that file, reads the
next full line, picks one sentence (random max_words window if longer).

The last val_fraction of every file is held out: split='train' only
starts lines in [0, 1-val_fraction) of a file, split='val' in the tail.

PlainTextMixture.stream

stream(self, split='train', n=None)
Infinite (n=None) or n-long stream of sentences (lists of words).

papie.silver

Silver-data pretraining followed by gold fine-tuning, and silver-data creation.

fit-silver — train for a *manual number of epochs on silver data* (automatically annotated,
noisier, usually much larger), then fine-tune on the gold data with the usual early stopping::

    python -m papie.cli fit-silver -c config.yaml --silver silver.tsv --silver-epochs 5

annotate — produce a silver TSV by running a trained model over raw text::

    python -m papie.cli annotate -c config.yaml --ckpt teacher.ckpt --input raw.txt --output silver.tsv

Both stages run through the ordinary fit command, so every config option applies unchanged.

deep_merge

deep_merge(a, b)

load_config

load_config(paths)

plan_silver

plan_silver(cfg, silver_path, silver_epochs, workdir, vocab_path=None)
Build the two stage configs. Pure function (no I/O) so it can be inspected and tested.

Stage A trains on silver_path for exactly silver_epochs epochs: early stopping is dropped
and the only checkpoint kept is last.ckpt in <workdir>/silver_ckpt. Stage B is the original
config on the gold data, warm-started from that checkpoint (model.init_from). Both stages use one
label encoder, built from gold + silver so that neither vocabulary is truncated.

fit_silver

fit_silver(argv=None)

read_raw

read_raw(path, header=False)
Raw input -> list of token lists. A TSV (tabs in the first line, tokens in column 0, blank line
between sentences) or plain text (one sentence per line, whitespace-separated tokens).

format_silver

format_silver(sents, preds, tasks_columns, header=True)
TSV text with every task at its configured column (other columns _). preds[task] is a
flat list of labels, sentence-major.

annotate

annotate(argv=None)

papie.benchmark

papie cpu-benchmark: CPU inference speed and accuracy of a trained checkpoint,
with and without dynamic INT8 quantization, at one or several thread counts.

    python -m papie.cli cpu-benchmark -c config.yaml --ckpt best.ckpt         [--test test.tsv] [--tokens 20000] [--threads 1,8] [--variants fp32,int8]

The same random sample of the test file (sentences chunked to --max-sent-len words) is run
through every (variant, threads) pair after a warm-up batch; tokens per second covers
model.predict (free-running decoding) only. Accuracy is exact match per task against the
gold columns named in the config. Compare ratios, not absolute values, on a busy machine.

sample_test_file

sample_test_file(test_path, out_path, tokens=20000, max_sent_len=35, seed=0, header=True)
Write a random sample (about tokens tokens) of test_path to out_path; returns
the sentences as lists of TSV fields.

run_variant

run_variant(load, batches, tasks, variant, threads)

format_table

format_table(rows, tasks)

main

main(argv=None)