Skill Tracer
Skills › Scientific Agent Skills › gtars › tokenizers.md

tokenizers.md

264 lines · skills/gtars/references/tokenizers.md at 5f2bc03

Open on GitHub

Most marks come from matching words in the file, so treat them as pointers.

1# Genomic tokenizers and fragment tokenization
2
3Local synthetic examples tested with Python `gtars==0.10.0`, wrapper crate `gtars==0.10.0`, and
4component `gtars-tokenizers==0.5.3` on **2026-10-01**.
5

Genomic tokenizers and fragment tokenization

Local synthetic examples tested with Python gtars==0.10.0, wrapper crate gtars==0.10.0, and component gtars-tokenizers==0.5.3 on 2026-10-01.

Raw lines 1 to 5
6## Current class and constructors
7
8The class is `Tokenizer`, not `TreeTokenizer`:
9
10```python
11from gtars.tokenizers import Tokenizer
13tokenizer = Tokenizer.from_bed("reviewed-universe.bed")
14```
16Verified Python signatures:
18```text
19Tokenizer(path)
20Tokenizer.from_config(path)
21Tokenizer.from_bed(path)
22Tokenizer.from_pretrained(path)
23Tokenizer.tokenize(regions)
24Tokenizer.encode(tokens)
25Tokenizer.decode(ids)
26Tokenizer.convert_ids_to_tokens(ids)
27Tokenizer.convert_tokens_to_ids(tokens)
28Tokenizer.get_vocab()
29```
31`Tokenizer(path)` auto-detects only `.toml`, `.bed`, and `.bed.gz`. The local
32constructors read local files and build an in-memory overlap index.

Current class and constructors

The class is Tokenizer, not TreeTokenizer:

from gtars.tokenizers import Tokenizer

tokenizer = Tokenizer.from_bed("reviewed-universe.bed")

Verified Python signatures:

Tokenizer(path)
Tokenizer.from_config(path)
Tokenizer.from_bed(path)
Tokenizer.from_pretrained(path)
Tokenizer.tokenize(regions)
Tokenizer.encode(tokens)
Tokenizer.decode(ids)
Tokenizer.convert_ids_to_tokens(ids)
Tokenizer.convert_tokens_to_ids(tokens)
Tokenizer.get_vocab()

Tokenizer(path) auto-detects only .toml, .bed, and .bed.gz. The local constructors read local files and build an in-memory overlap index.

Raw lines 6 to 33
34## Local config
36`from_config` expects TOML, not YAML:
38```toml
39universe = "universe.bed.gz"
40tokenizer_type = "bits"
41```
43The universe path is relative to the config file. `tokenizer_type` is optional
44and accepts `bits` or `ailist`; omitted means `bits`. A `special_tokens` array can
45override defaults, but its values must be valid region-token strings and all
46seven roles must remain compatible with the model. Prefer defaults unless a
47pinned model manifest explicitly defines every role.
49Default roles are:
51```text
52unk, pad, mask, cls, bos, eos, sep
53```
55For a unique N-row universe, the tested implementation has `N + 7` vocabulary
56entries. Do not hardcode IDs from another universe.

Local config

from_config expects TOML, not YAML:

universe = "universe.bed.gz"
tokenizer_type = "bits"

The universe path is relative to the config file. tokenizer_type is optional and accepts bits or ailist; omitted means bits. A special_tokens array can override defaults, but its values must be valid region-token strings and all seven roles must remain compatible with the model. Prefer defaults unless a pinned model manifest explicitly defines every role.

Default roles are:

unk, pad, mask, cls, bos, eos, sep

For a unique N-row universe, the tested implementation has N + 7 vocabulary entries. Do not hardcode IDs from another universe.

Raw lines 34 to 57
58## Tokenization semantics
60```python
61from gtars.models import Region, RegionSet
62from gtars.tokenizers import Tokenizer
64universe_path = "training-universe.bed"
65tokenizer = Tokenizer.from_bed(universe_path)
67query = RegionSet.from_regions(
68 [Region("chr1", 100, 200, None)],
70tokens = tokenizer.tokenize(query)
71batch = tokenizer(query)
72input_ids = batch["input_ids"]
73attention_mask = batch["attention_mask"]
74```
76The overlap index returns every universe region overlapping each query region.
77A query can therefore produce zero, one, or multiple region tokens; if the
78entire call yields no overlap, it returns the unknown token. Unknown contigs also
79fall through to unknown behavior. In a mixed call, unmatched regions disappear:
80there is no one-ID-per-input-row alignment and no unknown placeholder for each
81miss. The returned batch does not automatically add BOS/EOS/CLS tokens; record
82any model-specific insertion separately.
84The verified 0.10.0 wheel rejected a list of strings such as
85`["chr1:100-200"]` because the native extractor expected region objects.
86Older documentation showing string-list input is not reliable for this pin.
87Pass a `RegionSet` or `Region` objects.
89Conversion methods:
91```python
92ids = tokenizer.convert_tokens_to_ids(tokens)
93round_trip = tokenizer.convert_ids_to_tokens(ids)
94vocabulary = tokenizer.get_vocab()
95vocab_size = tokenizer.vocab_size
96specials = tokenizer.special_tokens_map
97special_ids = {role: getattr(tokenizer, f"{role}_token_id")
98 for role in ("unk", "pad", "mask", "cls", "bos", "eos", "sep")}
99```
101`encode()` maps token strings to IDs. Calling the tokenizer on regions performs
102region overlap tokenization plus encoding. These are different stages.

Tokenization semantics

from gtars.models import Region, RegionSet
from gtars.tokenizers import Tokenizer

universe_path = "training-universe.bed"
tokenizer = Tokenizer.from_bed(universe_path)

query = RegionSet.from_regions(
    [Region("chr1", 100, 200, None)],
)
tokens = tokenizer.tokenize(query)
batch = tokenizer(query)
input_ids = batch["input_ids"]
attention_mask = batch["attention_mask"]

The overlap index returns every universe region overlapping each query region. A query can therefore produce zero, one, or multiple region tokens; if the entire call yields no overlap, it returns the unknown token. Unknown contigs also fall through to unknown behavior. In a mixed call, unmatched regions disappear: there is no one-ID-per-input-row alignment and no unknown placeholder for each miss. The returned batch does not automatically add BOS/EOS/CLS tokens; record any model-specific insertion separately.

The verified 0.10.0 wheel rejected a list of strings such as ["chr1:100-200"] because the native extractor expected region objects. Older documentation showing string-list input is not reliable for this pin. Pass a RegionSet or Region objects.

Conversion methods:

ids = tokenizer.convert_tokens_to_ids(tokens)
round_trip = tokenizer.convert_ids_to_tokens(ids)
vocabulary = tokenizer.get_vocab()
vocab_size = tokenizer.vocab_size
specials = tokenizer.special_tokens_map
special_ids = {role: getattr(tokenizer, f"{role}_token_id")
               for role in ("unk", "pad", "mask", "cls", "bos", "eos", "sep")}

encode() maps token strings to IDs. Calling the tokenizer on regions performs region overlap tokenization plus encoding. These are different stages.

Raw lines 58 to 103
104## Universe compatibility is byte/order sensitive
106Token IDs depend on the exact universe rows, their order, duplicate policy,
107special-token assignment, and backend/config. Assembly labels alone are
108insufficient.
110Record this manifest before training or inference:
112```json
114 "schema_version": "1.0",
115 "assembly": "GRCh38.p14",
116 "coordinate_system": "0-based-half-open",
117 "gtars_python_version": "0.10.0",
118 "universe": {
119 "sha256": "<64 lowercase hex>",
120 "records": 100000,
121 "chrom_sizes_sha256": "<64 lowercase hex>"
122 },
123 "tokenizer": {
124 "backend": "bits",
125 "vocab_size": 100007,
126 "special_token_ids": {
127 "unk": 100000,
128 "pad": 100001,
129 "mask": 100002,
130 "cls": 100003,
131 "bos": 100004,
132 "eos": 100005,
133 "sep": 100006
134 }
135 }
137```
139The numbers above illustrate the schema, not guaranteed default ID order.
140Generate the values from the reviewed local tokenizer.
142Validate without importing gtars:
144```bash
145python3 -B scripts/tokenizer_manifest.py \
146 --manifest tokenizer-manifest.json \
147 --universe universe.bed \
148 --assembly GRCh38.p14 \
149 --chrom-sizes GRCh38.p14.chrom.sizes
150```
152The helper checks manifest structure and declared compatibility without importing
153Gtars; it does not prove that declared IDs equal the instantiated tokenizer.
154Compare `special_ids`, vocabulary, and a fixed query corpus at runtime.
155It requires exact SHA-256 and record count, seven distinct in-range
156special IDs, compatible assembly/coordinates/version, and a unique valid BED.

Universe compatibility is byte/order sensitive

Token IDs depend on the exact universe rows, their order, duplicate policy, special-token assignment, and backend/config. Assembly labels alone are insufficient.

Record this manifest before training or inference:

{
  "schema_version": "1.0",
  "assembly": "GRCh38.p14",
  "coordinate_system": "0-based-half-open",
  "gtars_python_version": "0.10.0",
  "universe": {
    "sha256": "<64 lowercase hex>",
    "records": 100000,
    "chrom_sizes_sha256": "<64 lowercase hex>"
  },
  "tokenizer": {
    "backend": "bits",
    "vocab_size": 100007,
    "special_token_ids": {
      "unk": 100000,
      "pad": 100001,
      "mask": 100002,
      "cls": 100003,
      "bos": 100004,
      "eos": 100005,
      "sep": 100006
    }
  }
}

The numbers above illustrate the schema, not guaranteed default ID order. Generate the values from the reviewed local tokenizer.

Validate without importing gtars:

python3 -B scripts/tokenizer_manifest.py \
  --manifest tokenizer-manifest.json \
  --universe universe.bed \
  --assembly GRCh38.p14 \
  --chrom-sizes GRCh38.p14.chrom.sizes

The helper checks manifest structure and declared compatibility without importing Gtars; it does not prove that declared IDs equal the instantiated tokenizer. Compare special_ids, vocabulary, and a fixed query corpus at runtime. It requires exact SHA-256 and record count, seven distinct in-range special IDs, compatible assembly/coordinates/version, and a unique valid BED.

Raw lines 104 to 157
Runs code scripts/tokenizer_manifest.py :145
158## `from_pretrained` is network-capable
160Tagged source implements:
1621. if `path` exists locally, append `universe.bed.gz`;
1632. otherwise construct a synchronous Hugging Face Hub client;
1643. fetch `universe.bed.gz` from the named model repository into the Hub cache.
166The Python signature exposes no `revision`, `cache_dir`, `local_files_only`, or
167expected checksum. Therefore:
169- do not call `Tokenizer.from_pretrained("owner/model")` by default;
170- obtain approval for `huggingface.co`, repository, exact commit/revision,
171 transfer size, cache path, and metadata disclosure;
172- fetch through a reviewed revision-pinning mechanism;
173- verify SHA-256 and manifest;
174- present an existing local directory containing the reviewed
175 `universe.bed.gz`.
177No remote model code is needed for a universe file; never enable remote code.

from_pretrained is network-capable

Tagged source implements:

  1. if path exists locally, append universe.bed.gz;
  2. otherwise construct a synchronous Hugging Face Hub client;
  3. fetch universe.bed.gz from the named model repository into the Hub cache.

The Python signature exposes no revision, cache_dir, local_files_only, or expected checksum. Therefore:

  • do not call Tokenizer.from_pretrained("owner/model") by default;
  • obtain approval for huggingface.co, repository, exact commit/revision, transfer size, cache path, and metadata disclosure;
  • fetch through a reviewed revision-pinning mechanism;
  • verify SHA-256 and manifest;
  • present an existing local directory containing the reviewed universe.bed.gz.

No remote model code is needed for a universe file; never enable remote code.

Raw lines 158 to 178
179## Fragment tokenization
181Current Python binding:
183```python
184from gtars.tokenizers import Tokenizer, tokenize_fragment_file
186tokenizer = Tokenizer.from_bed("training-universe.bed")
187by_barcode = tokenize_fragment_file("fragments.tsv.gz", tokenizer)
188# dict[str, list[int]]
189```
191Tagged implementation requires at least five whitespace-separated fields:
193```text
194chrom start end barcode count
195```
197It uses chromosome/start/end/barcode, but does **not** use the fifth count field.
198Each input row contributes its overlapping token IDs once, and duplicate IDs are
199retained in each barcode list. This can differ from expanding a fragment-support
200count. Validate that this is the intended weighting.
202The function accumulates all barcodes and token lists in memory. Set caps on
203compressed and expanded bytes, rows, distinct barcodes, tokens per row, total
204tokens, and process RSS before using it on single-cell data. Never print raw
205barcodes.
207For count matrices, the CLI's `fscoring --barcode` path uses a separate sparse
208count implementation and writes Matrix Market outputs; see `cli.md`.

Fragment tokenization

Current Python binding:

from gtars.tokenizers import Tokenizer, tokenize_fragment_file

tokenizer = Tokenizer.from_bed("training-universe.bed")
by_barcode = tokenize_fragment_file("fragments.tsv.gz", tokenizer)
# dict[str, list[int]]

Tagged implementation requires at least five whitespace-separated fields:

chrom  start  end  barcode  count

It uses chromosome/start/end/barcode, but does not use the fifth count field. Each input row contributes its overlapping token IDs once, and duplicate IDs are retained in each barcode list. This can differ from expanding a fragment-support count. Validate that this is the intended weighting.

The function accumulates all barcodes and token lists in memory. Set caps on compressed and expanded bytes, rows, distinct barcodes, tokens per row, total tokens, and process RSS before using it on single-cell data. Never print raw barcodes.

For count matrices, the CLI's fscoring --barcode path uses a separate sparse count implementation and writes Matrix Market outputs; see cli.md.

Raw lines 179 to 209
210## Split leakage
212Fit universes and tokenizers only from training patients/donors. All technical
213and biological replicates from one patient must stay in one split. A universe
214derived from all peaks leaks held-out locus support even if the model weights are
215trained later.
217Freeze and hash:
219- patient/replicate split manifest;
220- training-only BED inputs;
221- consensus/universe BED and chromosome sizes;
222- tokenizer manifest and special IDs;
223- tokenized corpus schema and checksum;
224- package/artifact versions.
226Do not tune unknown handling, universe support threshold, backend, or special
227tokens on validation/test outcomes more than the declared selection protocol
228allows.

Split leakage

Fit universes and tokenizers only from training patients/donors. All technical and biological replicates from one patient must stay in one split. A universe derived from all peaks leaks held-out locus support even if the model weights are trained later.

Freeze and hash:

  • patient/replicate split manifest;
  • training-only BED inputs;
  • consensus/universe BED and chromosome sizes;
  • tokenizer manifest and special IDs;
  • tokenized corpus schema and checksum;
  • package/artifact versions.

Do not tune unknown handling, universe support threshold, backend, or special tokens on validation/test outcomes more than the declared selection protocol allows.

Raw lines 210 to 229
230## Rust API
232```toml
233[dependencies]
234gtars = { version = "=0.10.0", default-features = false, features = ["tokenizers"] }
235```
237The wrapper exposes this source-reviewed, uncompiled Rust template:
239```rust
240use gtars::tokenizers::Tokenizer;
242let tokenizer = Tokenizer::from_bed("universe.bed")?;
243let tokens = tokenizer.tokenize(&regions)?;
244let ids = tokenizer.encode(&regions)?;
245```
247Rust also supports `from_config`, `from_auto`, and—because the wrapper enables
248the `huggingface` feature—`from_pretrained`. Apply the same local-first and
249revision/checksum gate.

Rust API

[dependencies]
gtars = { version = "=0.10.0", default-features = false, features = ["tokenizers"] }

The wrapper exposes this source-reviewed, uncompiled Rust template:

use gtars::tokenizers::Tokenizer;

let tokenizer = Tokenizer::from_bed("universe.bed")?;
let tokens = tokenizer.tokenize(&regions)?;
let ids = tokenizer.encode(&regions)?;

Rust also supports from_config, from_auto, and—because the wrapper enables the huggingface feature—from_pretrained. Apply the same local-first and revision/checksum gate.

Raw lines 230 to 250
251## Removed stale claims
253The current API does not provide `TreeTokenizer.from_bed_file`,
254`from_region_string`, YAML tokenizer config, token objects with `.metadata`, or
255the old CLI `tokenize` command in `gtars-cli 0.10.0`.

Removed stale claims

The current API does not provide TreeTokenizer.from_bed_file, from_region_string, YAML tokenizer config, token objects with .metadata, or the old CLI tokenize command in gtars-cli 0.10.0.

Raw lines 251 to 256
257## Official sources (accessed 2026-10-01)
259- [Gtars tokenizer guide](https://docs.bedbase.org/gtars/tokenizers/)
260- [Python 0.10.0 tokenizer stubs](https://github.com/databio/gtars/blob/gtars-python-v0.10.0/gtars-python/py_src/gtars/tokenizers/__init__.pyi)
261- [Python 0.10.0 tokenizer binding](https://github.com/databio/gtars/blob/gtars-python-v0.10.0/gtars-python/src/tokenizers/py_tokenizers/mod.rs)
262- [Tokenizer implementation at v0.10.0](https://github.com/databio/gtars/blob/gtars-v0.10.0/gtars-tokenizers/src/tokenizer.rs)
263- [Tokenizer TOML schema at v0.10.0](https://github.com/databio/gtars/blob/gtars-v0.10.0/gtars-tokenizers/src/config.rs)
264- [Fragment tokenizer source at v0.10.0](https://github.com/databio/gtars/blob/gtars-v0.10.0/gtars-tokenizers/src/utils/fragments.rs)