Metadata-Version: 2.4
Name: textslinger
Version: 0.4.0
Summary: TextSlinger: Fast and accurate text predictions in Python
Author-email: Keith Vertanen <vertanen@mtu.edu>, Dylan Gaines <dgaine20@kennesaw.edu>, Soufia Bahmani <sbahmani@mtu.edu>
License-Expression: MIT
Project-URL: Homepage, https://github.com/kdv123/textslinger
Project-URL: Source, https://github.com/kdv123/textslinger
Platform: Linux
Platform: Windows
Platform: Mac OS-X
Classifier: Development Status :: 3 - Alpha
Classifier: Topic :: Scientific/Engineering :: Human Machine Interfaces
Classifier: Natural Language :: English
Classifier: Intended Audience :: Science/Research
Classifier: Intended Audience :: End Users/Desktop
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Python
Classifier: Programming Language :: Python :: 3.10
Requires-Python: <3.11,>=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: torch>=2.6.0
Requires-Dist: torchvision>=0.21.0
Requires-Dist: torchaudio>=2.6.0
Requires-Dist: datasets==2.18.0
Requires-Dist: bitsandbytes>=0.50.2
Requires-Dist: requests<3,>=2.34.2
Requires-Dist: kenlm==0.2.0
Requires-Dist: nlpaug==1.1.11
Requires-Dist: psutil==5.7.2
Requires-Dist: ipywidgets==8.1.3
Requires-Dist: sentencepiece==0.2.0
Requires-Dist: protobuf==4.25.3
Requires-Dist: evaluate==0.4.0
Requires-Dist: scikit-learn==1.2.2
Requires-Dist: accelerate>=1.1.0
Requires-Dist: transformers>=5.2.0
Requires-Dist: lm-eval==0.4.13
Requires-Dist: numpy~=1.26.3
Requires-Dist: regex
Requires-Dist: tqdm==4.62.2
Requires-Dist: peft~=0.14.0
Provides-Extra: dev
Requires-Dist: coverage>=7.0; extra == "dev"
Requires-Dist: pytest; extra == "dev"
Requires-Dist: black; extra == "dev"
Provides-Extra: release
Requires-Dist: twine==5.0.0; extra == "release"
Requires-Dist: build>=1.4.0; extra == "release"
Requires-Dist: wheel==0.43.0; extra == "release"
Dynamic: license-file

<table border="0" cellpadding="0" cellspacing="0">
  <tr>
    <td width="120">
      <a href="images/textslinger.png"><img src="images/textslinger_small.jpg" width="236" alt="Cowboy drawing his two cell phone six shooters"></a>
    </td>
    <td align="center">
      <h2>TextSlinger: Fast and Accurate Text Predictions in Python</h2>
    </td>
  </tr>
</table>

This is a Python library for making text predictions using different types of
language models.
Current features: 

* Predict the distribution over the next character given the previous text.
* Predict the most likely next words given accepted text, a current-word prefix,
  and optional noisy input observations.
* Score supplied strings and report search uncertainty for bounded predictions.
* Supports:
  - N-gram language models via [KenLM](https://github.com/kpu/kenlm).
  - Prediction by Partial Matching (PPM) character language models.
  - Subword tokenized large language models (LLMs) via
    [Hugging Face](https://huggingface.co/docs/hub/en/index), including multilingual
    Apertus.
  - Byte tokenized LLMs via Hugging Face and
    [Byte Latent Transformer](https://arxiv.org/abs/2412.09871).

Start with the examples below for the public API. The
[mathematical overview](textslinger/MATH.tex) explains the inference model with a
worked touchscreen example; [implementation notes](textslinger/MATH_IMPLEMENTATION.tex)
and the [subword engine guide](textslinger/subword/README.md) describe the code.
See the [script guide](scripts/README.md) for evaluation commands and the
[test guide](tests/README.md) for backend validation and regression references.

The examples below assume a loaded `model`; model construction is described
under [Transformer quantization](#transformer-quantization) and
[N-gram and PPM construction](#n-gram-and-ppm-construction).

## Prediction character sets

Language-model constructors describe the model itself, while prediction calls
describe the outcomes needed by one client request. Every `predict_characters()`
call therefore requires `output_characters`. Word prediction optionally accepts
`word_spelling_characters` to limit returned spellings and
`word_ending_characters` to choose accepted delimiters. Model-specific ending
defaults are used when `word_ending_characters` is omitted. These immutable
defaults are exported at the package root, so clients can inspect, reuse, or
extend the exact policy without constructing a model:

| Model family | Public default |
| --- | --- |
| N-gram | `DEFAULT_NGRAM_WORD_ENDING_CHARACTERS` |
| PPM | `DEFAULT_PPM_WORD_ENDING_CHARACTERS` |
| Byte | `DEFAULT_BYTE_WORD_ENDING_CHARACTERS` |
| Subword | `DEFAULT_SUBWORD_WORD_ENDING_CHARACTERS` |

```python
characters = tuple("abcdefghijklmnopqrstuvwxyz '")

character_result = model.predict_characters(
    left_context="the ca",
    output_characters=characters,
)
word_result = model.predict_words(
    left_context="the ca",
    word_spelling_characters=characters,
    word_ending_characters=(" ", ",", "."),
    nbest=5,
)
```

`predict_words()` also accepts an immutable `WordList` to restrict which
semantic words are returned. The file is strict UTF-8 with one word per line;
words may use any Unicode script. Filtering happens after search but before
`nbest`, so hidden words remain in probability evidence and the returned
scores are not renormalized:

```python
from textslinger import WordList

word_list = WordList.from_file("words.txt")
word_result = model.predict_words(
    left_context="the ca",
    word_list=word_list,
    nbest=5,
)
```

The loader NFC-normalizes and deduplicates entries. It rejects a byte-order
mark, blank lines, leading or trailing whitespace, and whitespace inside a
word. Matching follows `predict_lower`: lowercase requests compare lowercase
NFC keys, while exact-case requests preserve case distinctions. Search limits
can still produce fewer than the requested number of allowed words.

The repository includes small English and multilingual examples in
`assets/word_lists/`. They demonstrate the file format and support integration
tests; they are not intended as evaluation or production vocabularies.

N-gram, PPM, byte, and subword word prediction use the normalized input channel
described in `textslinger/MATH.tex`. Callers may supply
`InputChannelConfig` to control channel insertions, channel deletions, outlier
mixing, and the balance between
autocomplete and complete-input hypotheses. Omitting it uses the public default
configuration; these models do not expose a separate penalty-based decoder.
All four model families' word results include retained evidence, omitted mass,
and conservative posterior intervals when search limits leave paths unexplored.

The n-gram, PPM, and byte visible-ending defaults contain a space. The subword
default also contains common whitespace and punctuation. Passing an explicit
sequence replaces the visible-ending default for that request. For models with
an EOS outcome, EOS is always retained as an additional zero-width sentence
ending and is independent of the client's visible-ending selection.
For character prediction, the same EOS outcome is exposed separately through
`PredictCharactersResult.termination_probability`; PPM leaves it unset because
PPM has no distinct EOS outcome.

### Reading results

Both prediction methods return structured results. Use `result.get(label)` for
one returned outcome, `result.top(5)` for a ranked view, or `result.predictions`
for the stored records. Character records retain the effective requested alphabet order;
word records are ranked and contain the full semantic word, accepted ending
contributions, and a `replacement` operation for selecting it.

```python
import math

for prediction in character_result.top(5):
    bounds = prediction.probability
    if bounds.log_lower_bound is None or bounds.log_upper_bound is None:
        continue  # This result does not expose a posterior interval.
    print(prediction.character,
          math.exp(bounds.log_lower_bound),
          math.exp(bounds.log_upper_bound))
```

Probability fields use natural logs: `-math.inf` represents zero. Each
`probability.log_retained_joint_mass` is an unnormalized retained contribution;
`log_lower_bound` and `log_upper_bound` describe its posterior interval. A
`None` bound means unavailable, not zero. Do not
normalize just the displayed list. Hidden outcomes and unresolved search mass
remain in `result.evidence`. `exact` means no search mass was omitted, subject to
the conditioning and numerical limitations below. Word-ending contributions are
joint word-and-ending probabilities, not probabilities conditional on the word.

### Noisy observations after accepted text

`left_context` is already accepted text. `input_sequence` describes only the
observations that follow it, even when the context ends inside the current word.
For example, after accepting `"the ca"`, two events can describe the remaining
`"ts"` in `"cats"`:

```python
import math
from textslinger import InputChannelConfig, InputEvent

word_result = model.predict_words(
    left_context="the ca",
    input_sequence=(
        InputEvent((("t", math.log(0.6)), ("r", math.log(0.4))),
                   channel_insertion_log_density=0.0),
        InputEvent((("s", 0.0),), channel_insertion_log_density=0.0),
    ),
    input_channel=InputChannelConfig(
        channel_insertion_probability=0.0,
        channel_deletion_probability=0.0,
        complete_endpoint_probability=1.0,
    ),
    word_ending_characters=(" ",),
    nbest=5,
)
```

These illustrative likelihoods can support both `cats` and `cars`; the model
prior and search also affect which predictions are returned. Complete-input
mode requires the remaining spelling to explain both events. Set
`complete_endpoint_probability=0.0` for autocomplete or a value between zero
and one to mix the interpretations. Insertions and deletions are disabled in
this example; their public defaults are both `0.01`. A one-hot observation is
not fixed accepted text when edits are allowed.

Event values are `log f(observation | intended character)`, supplied by the
application's input model. They need not sum to one across characters, and
continuous densities can exceed one. The insertion density describes an extra
observation unrelated to an intended character. Accepted `ca` receives no input
likelihood and is not consumed by those two events. Results still report the
whole word; `replacement` and optional `alignment_for(word, mode=...)` use
positions in that full word. Subword alignments are computed on demand for a
specific
`WordInputMode.AUTOCOMPLETE` or `WordInputMode.COMPLETE` interpretation;
results without an alignment provider raise `ValueError` for this method.

### Unicode scope

Character prediction completes UTF-8 across token boundaries for supported
reversible byte tokenizers and across ordinary BLT byte emissions. Word search
currently uses static token text: subword tokens that need cross-token UTF-8
reconstruction do not have the same support, and BLT word expansion is limited
to independently visible single-byte characters. A Unicode word list does not
extend that search space. Unsupported ordinary continuations retain conservative
mass accounting; character support is not a claim of complete Unicode word
prediction. Exact-case character requests (`predict_lower=False`) are needed
for requested labels whose lowercase mapping expands to multiple code points.

### Scope of probability bounds

Subword prediction fixes one canonical tokenization of the context before its
last ASCII space, then marginalizes compatible paths after that anchor. Its
character and word intervals bound search uncertainty conditional on those
fixed token IDs. Alternative tokenizations of the anchored text are not searched
or included in omitted mass, so the intervals do not bound the error relative to
full visible-history marginalization. Larger search limits or an `exact=True`
result do not remove this limitation. With no ASCII space, the entire context is
reconstructed after the prescribed starting tokens by default.

Both character and word prediction optionally accept `open_context_token_budget`
in their subword configurations:

```python
from textslinger import ConfigPredictCharactersSubword, ConfigPredictWordsSubword

result = model.predict_characters(
    left_context="the internationaliz",
    output_characters=characters,
    config=ConfigPredictCharactersSubword(open_context_token_budget=4),
)
word_result = model.predict_words(
    left_context="the internationaliz",
    config=ConfigPredictWordsSubword(open_context_token_budget=4),
    nbest=5,
)
```

The default `None` preserves the existing last-space policy. With a positive
integer, a suffix that fits the budget still uses the last space. Longer
suffixes fix a prefix of the current canonical tokenization, targeting that
many tokens of open history. A cut never moves earlier than the last ASCII
space and never splits a Unicode grapheme. Alignment can leave more tokens
open than the budget; a tokenizer that cannot round-trip the text falls back
to the space anchor. Character results expose `result.evidence.context_boundary`
with the actual cut, suffix token count, and reason when the option is enabled.
Word results do not currently expose this diagnostic field.

All historical text remains in the model context. This option limits the
tokenization search suffix, rather than truncating model context or guaranteeing
constant latency. It adds a canonical-history approximation for the newly fixed
text; probability bounds remain conditional on that history. A fresh cut is
determined from the current text on every request, including edits. Character
and word budgets are configured independently. Word search preserves the full
lexical prefix, selection replacement, and alignment offsets even when its
computational anchor moves inside that prefix. Only accepted `left_context`
can be fixed; all noisy observations remain in the search. A changed anchor may
also reduce cache reuse, so immediate-repeat timings do not predict typing latency.
Both defaults are `None`; no particular positive budget is recommended universally.

The character perplexity evaluator and both subword character profilers expose
`--open-context-token-budget N` (`none` disables it). For example, the multilingual
COMM2 evaluator runs all 34 corrected language sets with their own inventories:

```sh
python scripts/profile_apertus_multilingual_perplexity.py --gpus 0 \
    --open-context-token-budget 4 --warmup-character-query \
    --no-lm-eval --output profiles/comm2-budget4.json
```

Independent canonical-token sentence scores from `lm-eval` do not depend on this
character-search budget; the example omits that repeated work. Character
perplexity endpoints reflect search uncertainty and still exclude anchoring
error. A zero target lower bound makes the conservative perplexity infinite;
JSON reports represent unavailable or infinite endpoints as `null` alongside
explicit error/support counts.

To run only the independent `lm-eval` baseline on all 34 languages, skipping
character search and warmup:

```sh
python scripts/profile_apertus_multilingual_perplexity.py --gpus 1,2,4,6 \
    --precision bf16 --lm-eval-only --output profiles/comm2-lm-eval-only.json
```

This mode retains the same normalization, context template, model-directory
options, and `--language-at-a-time` scheduling. Per-language and per-sentence
`lm_eval` records contain canonical-token and character-normalized perplexity;
skipped character-search metrics are not reported as measured results.
The harness computes canonical likelihoods separately from character search,
but shares the production restricted generation policy and FP32 normalizer.
It is not an independent check of that normalizer.

For the BLT baseline, add `--model-type blt` (only supported with
`--lm-eval-only`). Its default checkpoint is `itazap/blt-1b-hf`:

```sh
python scripts/profile_apertus_multilingual_perplexity.py --gpus 0 \
    --precision bf16 --lm-eval-only --model-type blt \
    --output profiles/blt-comm2-lm-eval-only.json
```

BLT scores retain its fixed two-token starting context and use the restricted
generation law with transformer caching disabled. Its token perplexity counts
scored byte tokens; character perplexity counts normalized Unicode characters.
Both exclude the fixed starting context and do not append EOS. The existing
`--model-dir`, `--model-dir-prefix`, and `--left-context-template` options also
apply to BLT.

The multilingual profiler also accepts `--posterior-diagnostics` to retain
every target's posterior interval and omitted-mass reasons after its request
timer, together with per-shard peak device memory. This is independent of
internal `--character-search-stats` instrumentation. Use
`--language-at-a-time` to share each language across all selected GPUs.

Historical boundary and UTF-8 experiments, temporary diagnostic scripts and
their validation artifacts are preserved in the
[pre-cleanup tag](https://github.com/kdv123/textslinger/tree/boundary-before-cleanup-20261021).

N-gram and PPM character histories determine a unique state under their model
policies; finite-order context is not a tokenization approximation. The byte
adapter likewise has one ordinary token history per valid UTF-8 string. Byte
results condition on that history and prescribed starting tokens. The declared
generation law forbids additional non-EOS special controls; unresolved allowed
output still remains in omitted-mass accounting. See
[MATH.tex](textslinger/MATH.tex) for the conditioning distinction and
[MATH_IMPLEMENTATION.tex](textslinger/MATH_IMPLEMENTATION.tex) for each model.

### Special-token generation policy

The byte/subword generation policy is specified in
[MATH.tex](textslinger/MATH.tex), under “Declared special-token generation
policy.”
The API, metadata, numerical and evaluation requirements are recorded in
[MATH_IMPLEMENTATION.tex](textslinger/MATH_IMPLEMENTATION.tex), under “Shared
special-token generation policy.”
At every generated token, tokenizer-declared non-EOS special outputs are
masked before normalization over the remaining semantic token IDs. EOS retains
its termination role, including when it shares an ID with another special.
Fixed starting tokens and attention-masked batch padding remain unchanged.

Character prediction, noisy/noiseless word prediction, and `score_items()`
share this law. Forbidden outputs have zero probability under the new law;
search uncertainty among allowed outputs is still accounted for. This is
a change to the generation distribution. It does not add Unicode word
generation or establish that hidden special-token paths were impossible under
the original distribution. The implementation also corrects missing EOS
evidence in noiseless subword word prediction. Comparisons with the frozen
pre-policy source include both changes; attributing results to the token
restriction alone requires an EOS-corrected baseline or an explicit ablation.

## Word-search budget

Subword word prediction defaults to `max_active_hypotheses=80` and `beam_best=2.0`
for noisy and noiseless input, including the evaluation and interface scripts.
Explicit `ConfigPredictWordsSubword` or CLI settings override either limit.
Character prediction and other model families retain their separate defaults.
This changes the search tradeoff, so rankings, probability bounds and typing
savings can change. See the [accepted COMM2 comparison](textslinger/OPTIMIZATIONS.md#common-word-search-budget-accepted).

For long-running clients, [`prepare_compilation()`](textslinger/subword/README.md#one-call-optional-compilation)
optionally prepares character inference and/or word matching before serving. The guide owns
API usage and failure semantics; [optimization history](textslinger/OPTIMIZATIONS.md#accepted-optional-character-compilation)
owns measured benefits and precision-specific limitations.

## Preparing compiled alignment

Word-matching compilation is opt-in. It prepares matching with extra/missed taps
and one-observation-per-character matching; both allow uncertain letters. Each
request uses the appropriate implementation. See the [preparation guide](textslinger/subword/README.md#startup-alignment-compilation)
for guards, eager fallback, disk reuse, limits and numerical scope.

Subword word search also automatically caches static token-bucket metadata and
reuses eligible identical-observation preview-to-final alignment work. The
[cache guide](textslinger/subword/README.md#1-model-wide-metadata-caches) describes its
storage limits; the [endpoint guide](textslinger/subword/README.md#alignment-endpoint-reuse)
explains why this differs from caching predictions or extending growing inputs.

## Cancelling predictions

Use `cancellation_scope()` when a prediction becomes obsolete before it finishes.
The scope accepts a cheap, nonblocking predicate, such as a `threading.Event`'s
`is_set` method. Another thread can call `stop.set()` while the prediction runs:

```python
from threading import Event
from textslinger import PredictionCancelled, cancellation_scope

stop = Event()
try:
    with cancellation_scope(stop.is_set):
        result = model.predict_words(left_context="the ca", nbest=5)
except PredictionCancelled:
    result = None  # Discard this request; the model can serve another prediction.
```

This applies to `predict_words()` and `predict_characters()` across n-gram,
PPM, subword and byte backends without changing their request parameters.
Search checks run between frontier expansions, alignment steps and transformer
batches, and before returning a result. Prepared alignment checks between chunks
of up to six generated characters; the zero-event formula is checked before and
after its batched update. Cancellation raises `PredictionCancelled`
instead of returning partial predictions. A native operation already executing
or GPU work already submitted cannot be preempted by these checks, so there is
no fixed cancellation-time guarantee.

Scopes are local to the calling thread or async context, nest without masking
an outer cancellation, and restore their state on exit. Install the scope in the
thread that actually calls the model. They do not make one model instance safe
for concurrent prediction calls. Completed graph nodes remain reusable after
cancellation, and subword cache memory accounting is refreshed on exceptional
exits. Clear or replace a set event before using it for another request. Callback
exceptions propagate unchanged if an application needs a distinct deadline error.

## Scoring supplied strings

`model.score_items(["The cat sat.", "The car stopped."])` returns one natural-log
likelihood per supplied string, in input order. For subword models this scores
one canonical tokenization after the model's fixed starting context; BLT scores
its ordinary byte sequence. Starting tokens are unscored and EOS is not appended.
The restricted generation law above applies to every scored target: a forbidden
control or a target after EOS makes that continuation impossible. Empty strings
have log likelihood zero.

Canonical sentence likelihood and a product of character-marginal predictions
are different evaluation targets. A narrow character perplexity interval does
not guarantee agreement with canonical scoring. The item scorer's
`ConfigScoreItemsSubword.max_batch_tokens` (or byte equivalent) controls padded
inference-batch size; it is unrelated to `open_context_token_budget` and does not
change the intended likelihood.

## Transformer quantization

Byte and subword transformer constructors accept `quantization` with
`ModelQuantization.NONE`, `INT8`, `NF4`, or `NF4_DOUBLE`. Quantized loading uses
bitsandbytes and is intended for CUDA devices. The general evaluation CLIs and
multilingual profiler expose the same choice as
`--quantization=none|int8|nf4|nf4-double`; repository tests use the identical
pytest switch. The frozen English COMM2 benchmark is unquantized and has no
quantization switch.

For example, load a subword model in unquantized CPU FP32:

```python
from textslinger import CausalSubwordLanguageModel, Device, Precision

model = CausalSubwordLanguageModel(
    lang_model_name="swiss-ai/Apertus-v1.1-0.5B",
    device=Device.CPU,
    precision=Precision.FP32,
)
```

## N-gram and PPM construction

An ARPA-format n-gram model derives its structural `model_alphabet` from the
unigram vocabulary. A KenLM binary does not expose that vocabulary and therefore
requires `model_alphabet` in the `NGramLanguageModel` constructor. PPM models can
be created either with `PPM.from_alphabet()` or with
`PPM.from_training_texts()`, which pools the training characters before fitting
the model. Successive exclusion is disabled by default; callers can enable it
with `use_exclusion=True` for experimental comparisons.

## Developer setup
Our code style is whatever the Black formatter says it should be. 
You should [configure your IDE to format using Black when you save][black-editors].

[black-editors]: https://black.readthedocs.io/en/stable/integrations/editors.html

### Windows
Windows is not supported by the library dependencies of textslinger.
To use our library on Windows, you will need to use
[Windows Subsystem for Linux (WSL)](https://learn.microsoft.com/en-gb/windows/wsl/).
Please follow the
[installation directions](https://learn.microsoft.com/en-gb/windows/wsl/install)
and use the Linux commands below.
The Miniforge environment below includes pip.

## Setting up a Python environment
TextSlinger requires **Python 3.10** (`>=3.10,<3.11`), even if Miniforge's base
environment uses a newer Python. Run the commands below in a terminal, using
the same activated environment throughout. The dependency versions are declared
in [pyproject.toml](pyproject.toml).

### macOS prerequisites and Miniforge

These Mac instructions target native Apple Silicon (`arm64`) on macOS 14 or
newer. The declared bitsandbytes dependency provides an
[Apple Silicon wheel for macOS 14+](https://pypi.org/project/bitsandbytes/0.50.2/).
Use a native terminal rather than a terminal running under Rosetta. Check the
architecture and Apple's Command Line Tools:

```bash
uname -m
xcode-select -p
```

The architecture should be `arm64`. If the Command Line Tools are missing,
install them with `xcode-select --install` and finish the installer before
continuing; they provide the C++ compiler needed for KenLM.

If Miniforge is not already installed, use its
[official installer](https://github.com/conda-forge/miniforge):

```bash
curl -LO https://github.com/conda-forge/miniforge/releases/latest/download/Miniforge3-MacOSX-arm64.sh
bash Miniforge3-MacOSX-arm64.sh
```

Assuming the default installation directory, initialize zsh and enable conda
in the current terminal:

```bash
"$HOME/miniforge3/bin/conda" init zsh
source "$HOME/miniforge3/etc/profile.d/conda.sh"
```

Use your installation path if it differs. New terminals will load the shell
initialization automatically. If replacing an older Anaconda installation,
check `conda info --base` points to the intended Miniforge installation.

### Linux and Windows Subsystem for Linux

For Linux or WSL on x86-64, install Miniforge if needed:

```bash
curl -LO https://github.com/conda-forge/miniforge/releases/latest/download/Miniforge3-Linux-x86_64.sh
bash Miniforge3-Linux-x86_64.sh
source "$HOME/miniforge3/etc/profile.d/conda.sh"
```

Accept shell initialization in the installer, then reopen the terminal for
future sessions. On Ubuntu/WSL, also install the C++ build tools:

```bash
sudo apt-get update
sudo apt-get install build-essential
```

### Create the project environment

On either platform, create and activate the environment. CMake 3 is selected
for compatibility with the pinned KenLM source package. These channel options
apply to this command without replacing your global conda channel settings.

```bash
conda create -n textslinger --override-channels -c conda-forge \
  python=3.10 pip "cmake>=3.22,<4" make -y
conda activate textslinger
python --version
python -m pip --version
python -m pip install --upgrade pip "setuptools>=77.0.3" wheel
```

Python should report `3.10.x`, and pip's path should be inside the `textslinger`
environment. Activate it again in each new terminal before running TextSlinger.

### Install PyTorch and TextSlinger

On **Apple Silicon**, install the native PyTorch packages from the default
Python package index. Apple graphics processing unit (GPU) acceleration uses
[Metal Performance Shaders (MPS)](https://docs.pytorch.org/docs/stable/notes/mps.html)
and is included in this build:

```bash
python -m pip install "torch>=2.6.0" "torchvision>=0.21.0" "torchaudio>=2.6.0"
```

On **Linux/WSL**, choose the matching PyTorch build instead. For a central
processing unit (CPU) installation:

```bash
python -m pip install "torch>=2.6.0" "torchvision>=0.21.0" "torchaudio>=2.6.0" \
  --index-url https://download.pytorch.org/whl/cpu
```

For an NVIDIA GPU, use the
[official PyTorch installation commands](https://pytorch.org/get-started/previous-versions/)
for your GPU and driver, selecting PyTorch 2.6 or newer and matching torchvision
and torchaudio versions. For example, a CUDA 12.6 build can be installed with:

```bash
python -m pip install "torch>=2.6.0" "torchvision>=0.21.0" "torchaudio>=2.6.0" \
  --index-url https://download.pytorch.org/whl/cu126
```

CUDA is NVIDIA's GPU computing platform; it is not used on the Mac. Check
`nvidia-smi` on Linux/WSL before choosing a CUDA build. Newer GPU architectures
may require a newer build than the example above.

From the repository root (the directory containing `pyproject.toml`), build
**KenLM with 12-gram support**, then install this checkout and its development
tools:

```bash
MAX_ORDER=12 python -m pip install --force-reinstall --no-cache-dir \
  --no-binary=kenlm --no-build-isolation "kenlm==0.2.0"
python -m pip install -e ".[dev]"
python -m pip check
```

[KenLM](https://github.com/kpu/kenlm) otherwise defaults to six-gram support,
which cannot load the repository's 12-gram test models. The source build avoids
reusing a wheel compiled with that lower limit; disabling build isolation makes
it use the environment's CMake and build tools. If you later reinstall KenLM,
repeat this source-build command.

The editable install reads the complete dependency list from `pyproject.toml`,
including Transformers 5.2 or newer, bitsandbytes 0.50.2 or newer, `regex`, and
the evaluation/profiling dependencies. It also installs pytest, coverage, and
Black through the `dev` extra. Byte Latent Transformer (BLT) and Apertus support
come from Transformers; a separate BLT checkout is not needed.

If an older dependency fails because it imports `pkg_resources`, use this
temporary compatibility workaround. Setuptools 82 removed that module; see the
[setuptools release notes](https://github.com/pypa/setuptools/blob/v82.0.0/NEWS.rst).
Apply it only if needed, then rerun the failed command:

```bash
python -m pip install "setuptools>=77.0.3,<82"
```

### Verify the environment

This check imports TextSlinger and BLT support and allocates a tensor on the
available accelerator. It does not download model weights:

```bash
python - <<'PY'
import platform
import sys
import torch
import transformers
import textslinger
from transformers import BltForCausalLM

print("Python:", sys.version.split()[0], sys.executable)
print("Architecture:", platform.machine())
print("TextSlinger:", textslinger.__version__, textslinger.__file__)
print("PyTorch:", torch.__version__)
print("Transformers:", transformers.__version__)
print("MPS built / available:", torch.backends.mps.is_built(), torch.backends.mps.is_available())
print("CUDA available:", torch.cuda.is_available())

device = "mps" if torch.backends.mps.is_available() else "cuda" if torch.cuda.is_available() else "cpu"
x = torch.ones(2, device=device)
print("Tensor:", x.device, "sum:", x.sum().item())
PY
```

On an Apple Silicon Mac, expect `arm64` and MPS availability to be `True`.
The TextSlinger path should point to this checkout. A CPU-only result still
permits CPU use, but does not verify Mac GPU acceleration.

Run these small tests before downloading assets; they use synthetic tokenizers
and do not load pretrained model weights:

```bash
python -m pytest tests/subword/test_metadata.py tests/subword/test_public_validation.py -q
```

### Download test assets and run model tests

Public Hugging Face models can be downloaded without signing in. For gated or
private models, first obtain access and log in using the installed command-line
interface and a [Hugging Face access token](https://huggingface.co/docs/huggingface_hub/en/quick-start#authentication):

```bash
hf auth login
```

From the repository root, download the assets without `sudo`:

```bash
python assets/download.py
```

The default download includes all six Hugging Face model snapshots used by the
tests, including BLT and `swiss-ai/Apertus-v1.1-0.5B`, and can require substantial
disk space and download time. Existing files in `assets/` and the Hugging Face
cache are reused; they can be retained when recreating the conda environment.
Use `python assets/download.py --skip-hugging-face` to download repository assets
without caching those six snapshots; tests that load a model by repository name
may still download it later. Use `--force` only to redownload assets/snapshots
and regenerate derived word lists.

Repository assets include character and unigram word language models, COMM2
phrases, the local subword model, and per-language character inventories under
`assets/inventory/` for all four source datasets in the multilingual Open Science
Framework project. Derived lowercase and mixed-case English word lists under
`assets/word_lists/` contain 1,000, 10,000, 100,000, and 500,000 words.

After downloading assets, check that KenLM can load a 12-gram model:

```bash
python - <<'PY'
import kenlm
model = kenlm.Model("assets/lm_dec19_char_tiny_12gram.arpa")
assert model.order == 12, model.order
print("KenLM 12-gram load passed")
PY
```

The default suite runs on the CPU, selects the OPT subword model, and uses
32-bit floating point (FP32) precision without quantization:

```bash
python -m pytest -v -rs
```

For Mac GPU validation, run the subword tests explicitly on MPS with Apertus:

```bash
python scripts/test.py tests/subword -v -rs --device mps --precision fp32 \
  --quantization none --subword-llm apertus
```

The `--subword-llm` option selects model-dependent subword tests; use `all` to
exercise every supported subword model. Long tests require `--run-long`.
For initial Mac validation, use the unquantized FP32 configuration above. The
runner isolates MPS test cases into fresh processes to release backend resources;
see the [MPS instructions](tests/README.md#mps-process-isolation) for details.
Triton is optional for the fused CUDA
character reducer and is not required for CPU or MPS use.

---
This material is based upon work supported by the NSF under Grant No.
IIS-1909089 and IIS-2402876.
