> ## Documentation Index
> Fetch the complete documentation index at: https://ladygraph.io.vn/llms.txt
> Use this file to discover all available pages before exploring further.

# Local models

> Run an LLM and a span tagger on your own machine.

Two interfaces cover work that should run on this machine. Both follow the embedder's pattern: a small engine protocol so tests need no model file, a lazy import of the heavy library, one lock because the engines are not thread-safe, and a fake for tests.

## A local LLM client

`LiteRtLlmClient` is an `LlmClient` over a LiteRT-LM model, such as Gemma 4 E2B as a `.litertlm` file. It takes the same `complete` and `acomplete` calls as the ADK client, so the `Translator`, and anything else that depends on `LlmClient`, runs on it unchanged.

```python theme={null}
from ladygraph.llm import LiteRtLlmClient, LlmConfig, Translator
from ladygraph.llm.adk import create_client

llm = LiteRtLlmClient("model/gemma-4-E2B-it-gpu.litertlm", device="gpu")      # or: create_client(LlmConfig(backend="litert", model=..., device="gpu"))
print(Translator(llm).translate("Chi vượt 10% định mức cần Tổng Giám đốc phê duyệt.").text)
```

* **Structured output is constrained decoding.** The pydantic schema goes to the engine, which can only emit JSON that matches it. Without that, the model answered in a fence with its own key names, which no repair step fixes. If an engine refuses a schema, the client falls back to an instruction plus the same validate-and-repair step the other backends use, and logs it once. Either way the answer is validated against the pydantic class.
* **Reproducible.** Greedy sampling (top-k 1, temperature 0, a fixed seed) gave the same answer on repeated calls.
* **Stateless and serialized.** Each call is a fresh conversation, so a prompt carries its own context. One lock serializes calls.
* **Plain text.** `complete_text(system, prompt)` returns text with no JSON wrapper. The aligned translator and the back-quote step use it.

Configuration: `LlmConfig(backend="litert", model=<path to the .litertlm>, device="cpu"|"gpu"|"npu", max_output_tokens, thinking, repair_attempts)`.

### Choose the device

`LITERT_LLM_DEVICE` (or `device=`) picks the backend: `cpu` (the default), `gpu` or `npu`. A `.litertlm` file is built for one backend, so a file built for the GPU on `cpu` can fail with:

```text theme={null}
tf_lite_prefill_decode not found in the model
```

Set the device to the one the file was built for, or use a model built for the CPU. In the repository's `model/` folder, `gemma-4-E2B-it-gpu.litertlm` is a GPU build and `gemma3-1b-it-int4.litertlm` is a smaller model.

### Speed

Measured on a Mac with Gemma 4 E2B on the GPU: loading plus the first call took about 12 s. Three Vietnamese-to-English sentences then took 5.7, 7.7 and 11 s through the `Translator` with the packaged glossary, all passing the gate on the first attempt. Extracting concepts from one short passage took 12 to 16 s. It is a local and private path, not a fast one.

> [!WARNING]
>
> Only this one model on the GPU was tried. `npu` and the `thinking` setting are untested. Token counts are not reported in `LlmUsage`. The packaged translator prompt carries the whole glossary, which is part of why a sentence takes seconds.

## A span tagger

An LLM extractor asks a model for concepts and quotes. A tagger finds spans of text and labels them, with a score, in one small model run. `SpanTagger` is the interface for building extractors on that.

```python theme={null}
tagger.recognize(texts, labels, threshold=0.5, flat=True)
# one list of Span(start, end, text, label, score) per text, or None for a text it cannot take
```

| Piece | What it does |
| - | - |
| `SpanTagger`, `Span` | The protocol and the result. Offsets are into the text as passed. Pass `faithful(passage.text)` to get positions in the coordinates evidence uses. |
| `recognize_all` | A tagger carries `labels_per_call` labels at most. This splits any number of labels into calls and merges the spans. |
| `recognize_windowed` | For text longer than the tagger can take: overlapping word windows, and a window that does not fit is halved. Spans come back in the full text's offsets. |
| `merge_spans` | Spans without clashes from several lists: the best score wins, with the same rules as the model's decoder. |
| `spans_to_candidates` | Spans to candidate dicts (word, type, description, quote) through a label-to-type map. |
| `FakeSpanTagger` | For tests. |
| `ner.litert_gliner.LiteRtGliner` | GLiNER (zero-shot: any labels you name) as a LiteRT `.tflite`, on the CPU or GPU. |
| `ner.tokenizers_encoder.TokenizersEncoder` | GLiNER's tokenization and collation without PyTorch. `LiteRtGliner` uses it by default. |

```python theme={null}
from ladygraph.core.normalize import faithful
from ladygraph.ner import recognize_windowed, spans_to_candidates
from ladygraph.ner.litert_gliner import LiteRtGliner

tagger = LiteRtGliner("model/tflite/gliner_gpu.tflite", tokenizer="gliner-community/gliner_small-v2.5", device="gpu")
text = faithful(passage.text)
spans = recognize_windowed(tagger, text, ["organization", "date", "percentage"], size=8)
candidates = spans_to_candidates(spans, {"organization": "Body", "percentage": "Rule"}, min_score=0.5)
# ground each candidate's quote in the passage with locate_quote, then assemble and validate the Contribution
```

To use a tagger in a project, set `extractor.kind: ner` as described on [Extractors](https://ladygraph.io.vn/guides/extractors.md).

### What the converted model does

These facts are from `gliner_small-v2.5` on the GPU.

* **Fixed shapes.** The `.tflite` takes a batch of 2 texts, 28 subwords, 15 words and 5 label slots. A 13-word sentence with numbers already did not fit, so real text needs `recognize_windowed`. The adapter returns `None` for a text that does not fit, and answers an empty text with `[]`.
* **Fast.** Six short texts against seven labels (two calls) took 134 ms. Two long sentences took 24 and 41 ms, windowed. The PyTorch model took about 1.7 s per chunk in the experiment.
* **Matches the reference.** On six sentences its entities were identical to `GLiNER.inference`, and the offsets were exact.
* **Float32 on the GPU.** The DeBERTa encoder overflows in float16, so the adapter forces float32.
* **Loads in about 8 s, with no PyTorch.** Importing the `gliner` package would add torch (about 14 s) and weights the `.tflite` makes unnecessary (about 8 s). `TokenizersEncoder` does the same preparation with the `tokenizers` library. What remains is compiling the `.tflite` for the GPU, about 8 s, which is not cached between processes. `encoder_kind="gliner"` forces the package, and `"auto"` falls back to it if the checkpoint lacks `tokenizer.json` or `gliner_config.json`.
* **The same inputs as GLiNER.** On 95 texts and 4 label sets, including Vietnamese, CJK and Arabic, all 1,152 arrays matched: token ids, attention and word masks, spans, and the character maps. One difference between files: the checkpoint's `tokenizer.json` normalizes with NFKC, while GLiNER's own tokenizer uses NFC, so the encoder sets GLiNER's normalizer. Only the whitespace splitter and the span model are supported. Anything else raises, and `auto` falls back.
* **Generic labels give a weak signal.** Percentages were reliable ("200%" at 0.94). "Ceiling" came out as a rating level (0.43) and "KHUT" as money (0.57). The labels you choose matter more than the runtime.
* **English only.** `gliner_small-v2.5` is an English checkpoint. Vietnamese text needs a multilingual checkpoint, or translation first. See [Translation and verification](https://ladygraph.io.vn/guides/translation.md).

One bug from the original experiment is fixed here. GLiNER's `prepare_batch` silently drops empty texts, so an empty string in a batch shifted every later result onto the wrong text. The adapter answers empty texts itself and checks the map GLiNER returns.

Converting a checkpoint to `.tflite` is outside this package. The conversion scripts are in `demoGraphIndex/prep/prepare_gliner/convert`.

## Tests that use real files

The tests that need the real files skip themselves unless you name them. Set `LITERT_LLM_MODEL` and `LITERT_LLM_DEVICE` for `tests/test_litert_llm.py`, and `GLINER_TFLITE`, `GLINER_TOKENIZER` and `GLINER_DEVICE` for `tests/test_ner.py`. See [Environment variables](https://ladygraph.io.vn/reference/environment-variables.md).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.