Skip to content

Latest commit

 

History

History
234 lines (185 loc) · 9.73 KB

PUNCTUATION.md

File metadata and controls

234 lines (185 loc) · 9.73 KB

Sentence markers and optional punctuation

This guide describes library version 2.2.0. CTLS2 and CTWM binary format versions are unchanged. These rules apply to word, syllable and character training.

Structural sentence markers

The defaults, defined in tokenization.py, are:

START_TOKEN = "<START>"
END_TOKEN = "<END>"

These English defaults apply to newly trained models. Loading an existing model preserves its exact stored labels and IDs; see MIGRATION.md.

These labels each occupy one vocabulary entry and have one integer token ID. The angle brackets have no special interpretation in the binary format. A marker is an artificial token inserted by the trainer, independent of any literal period or question mark in the corpus. The names can be changed:

from languagestatisticslibpy import NGramTrainer

trainer = NGramTrainer(
    orders=(2, 3), unit="word", sentence_boundaries=True,
    start_token="<SENTENCE_START>", end_token="<SENTENCE_END>",
)

Labels retain their exact spelling even when the corpus is lowercased or case-folded. They must be nonempty valid Unicode strings, distinct after the configured normalization, and must not collide with vocabulary entries or an active <UNK> marker. Reserved token input to add_tokens is rejected rather than silently counted twice. Do not put structural labels into corpus text; ordinary word tokenization would process their characters as ordinary text.

With boundaries enabled and default single-start padding:

trainer.add_tokens(["I", "am", "a", "human"])
# Effective sequence:
# ["<SENTENCE_START>", "I", "am", "a", "human", "<SENTENCE_END>"]

Every nonempty sequence receives one end marker, including a last sentence without written punctuation. Empty token sequences produce no artificial sentences. No n-grams cross independent sequences, files or unknown-token breaks. pad_start=True uses n-1 start markers for the model of order n; there is still only one end marker. For unigrams this padding option means zero start markers. Without pad_start, unigrams include one start marker.

The Python API defaults sentence_boundaries=False; enable it explicitly. The CLI enables markers by default for --unit word, and disables them by default for character and syllable units. Use --sentence-boundaries or --no-sentence-boundaries to choose explicitly.

IDs depend on the ordered vocabulary and must not be hard-coded:

start_id = model.token_to_id[model.metadata["start_token"]]
end_id = model.token_to_id[model.metadata["end_token"]]
assert start_id == model.metadata["start_token_id"]
assert end_id == model.metadata["end_token_id"]

When boundaries are disabled, their labels and IDs are stored as null and the trainer does not add them to the vocabulary.

Select the punctuation to retain

punctuation is independent of the lexical vocabulary and the sentence-ending rule. A selected punctuation token is automatically added to the vocabulary, even when a fixed word or syllable inventory was supplied. An already present selected token is not added twice. Selection order is retained for newly added symbols, followed by the active structural markers; dynamically seen lexical tokens then receive their IDs in first-seen order.

Setting Meaning
None or False (default) Keep the previous tokenizer behavior
True Retain the common punctuation preset as separate tokens
[".", ",", "!", "?"] Retain exactly these punctuation tokens
[] Enable selection but discard punctuation; retain its role as a separator

The common preset is:

[".", ",", ";", ":", "!", "?", "…", "(", ")", "[", "]", "{", "}",
 '"', "'", "„", "“", "”", "‘", "’", "«", "»", "–", "—", "-", "/"]

Explicit entries must consist of Unicode punctuation or symbol characters, with no whitespace or letters. Multi-character entries such as "..." are allowed and use longest matching. Unicode and case normalization is applied to the selection and corpus consistently; duplicates after normalization are rejected. None preserves existing behavior: word tokenization drops ordinary punctuation, character tokenization retains non-whitespace characters, and separated-syllable tokenization splits only at whitespace.

In explicit selection mode, unselected punctuation separates words/syllables and is discarded. For example, if only ! is selected, Hello,world! gives ["Hello", "world", "!"], not a combined "Helloworld" token. N-gram windows still connect the resulting tokens within the same sentence. This differs from an unknown-token break, which invalidates crossing windows.

Word-internal apostrophes (', ’) and hyphens (-) are retained inside can't and well-known by default. To split a joiner into its own token, both select it and set split_word_joiners=True. External quotation marks can already be emitted as selected punctuation. Syllable punctuation selection delimits lexical spans, so choose the selection to match the inventory.

Keep symbols and detect sentences independently

from languagestatisticslibpy import NGramTrainer, save_model

trainer = NGramTrainer(
    orders=(1, 2, 3), unit="word", sentence_boundaries=True,
    punctuation=[".", ",", ";", ":", "!", "?"],
    sentence_endings=[".", "!", "?"],
)
trainer.add_text("Hello, world!")
model = trainer.build(storage="sparse")[2]
save_model(model, "english-punctuation.ctwm", format="ctwm")

The effective sequence is:

["<START>", "Hello", ",", "world", "!", "<END>"]

Its five bigrams, each with raw count 1, are:

("<START>", "Hello")
("Hello", ",")
(",", "world")
("world", "!")
("!", "<END>")

The comma stays inside the sentence; the exclamation mark stays before the end marker.

sentence_endings defaults to [".", "!", "?"]. These signs need not be selected as retained tokens. Conversely a selected sign need not terminate a sentence. For example, select "." but set sentence_endings=["!", "?"] to retain periods without splitting on them. An explicit empty ending list disables punctuation-based splitting; blank lines and file boundaries still separate sequences. Consecutive terminators such as ?! belong to one end, and adjacent closing quotes/brackets remain with the preceding sentence. Selected closing quotes appear before the structural end marker.

The splitter is a simple literal punctuation rule. It does not recognize abbreviations or decimal points. For reliable externally segmented input use sentence_per_line=True (CLI: --sentence-per-line) or add_tokens with one sentence per call. Those paths bypass punctuation-based sentence splitting. When sentence boundaries are disabled, add_text also skips that splitting; selected literal punctuation can still be retained.

add_tokens accepts already segmented tokens: it does not drop punctuation or split a sequence when an input token equals a sentence-ending sign. Use add_text/add_file to apply the configured raw-text tokenizer and splitter.

Syllable example

trainer = NGramTrainer(
    orders=(2, 7), unit="syllable",
    vocabulary=["La", "Le", "Li", "Lo", "Lu"],
    punctuation=[",", "!"],
    sentence_boundaries=True,
)
trainer.add_text("La,Le!")
model = trainer.build(storage="sparse")[2]
assert model.count_tokens(["La", ","]) == 1
assert model.count_tokens([",", "Le"]) == 1

The inventory automatically gains ,, ! and the two boundary markers. Attached punctuation works in both separated and greedy syllable modes. Greedy mode also splits unseparated lexical spans using the supplied inventory; separated mode requires whitespace between adjacent lexical syllable tokens.

Command line

From the project directory, use the common preset:

python -m languagestatisticslibpy train --input examples/words_en.txt --output-dir punctuation_models --unit word --orders 2 3 --include-punctuation --storage sparse

Or choose exactly the retained symbols and label spelling:

python -m languagestatisticslibpy train --input examples/words_en.txt --output-dir punctuation_models --unit word --orders 2 3 --punctuation "." "," "!" "?" --sentence-endings "." "!" "?" --start-token "<SENTENCE_START>" --end-token "<SENTENCE_END>" --storage sparse

For shell-sensitive symbols use --punctuation-file punctuation.json, with a UTF-8 JSON array such as [".", ",", "!", "?", "\""]. The independent --sentence-endings-file accepts the same kind of array; [] disables punctuation-based segmentation. Keep boundary labels quoted on the command line because shells interpret angle brackets.

Scoring and compatibility

Markers and punctuation use the same numeric lookup as other tokens. The scorer does not tokenize text or insert markers: prepare each candidate with the same boundary, punctuation and padding rules as training. For this example:

ids = model.encode_tokens(["<START>", "La", ",", "Le", "!", "<END>"])
score = model.calculate_cost(ids)
key = model.encode_key(ids[:2])
lookup = model.lookup_key
score_for_first_bigram = lookup(key)

The direct lookup and scoring code are unchanged from version 2.0. Punctuation processing happens during preparation, outside cryptanalysis search loops. More tokens enlarge the vocabulary and alter the scores: dense storage grows as 4 * V**n bytes, and larger working sets can affect cache performance. Sparse storage avoids allocating all possible windows. No identical-latency claim can cover every enlarged alphabet or arbitrary order.

The expanded vocabulary, exact marker labels/IDs and all relevant policies are saved in CTLS2/CTWM metadata. Already encoded IDs and keys from an older vocabulary cannot be reused. Multi-character marker names and syllables cannot be represented through the old character-only CTLS1 format. This extension does not change that compatibility limit.