- Python 100%
| Filename | Latest commit message | Latest commit date |
|---|---|---|
| src/dantess_pretokenization | ||
| tests | ||
| .gitignore | ||
| .python-version | ||
| LICENSE | ||
| pyproject.toml | ||
| README.md | ||
| uv.lock | ||
dantess-pretokenization
Simple, extensible pretokenization for Hugging Face datasets with multiple chat formats.
This project turns raw chat or completion datasets into a single Parquet dataset containing:
input_idsattention_masklabels
It is designed for SFT-style preprocessing where some tokens should contribute to loss and others should be masked with -100.
What It Supports
- Chat datasets with configurable conversation and role field names
- Plain completion datasets
- Multiple prompt/chat wrappers:
ChatMLChatML with BOS FixGemma4GLM4Llama3Llama4Mistral V7 TekkenChatMLReasoningChatMLNonReasoningGLM4Reasoning
- Optional reasoning traces on chat data
- Optional system-prompt override
- Optional "train only on the last assistant response" mode
- Interactive tokenization preview before the main run
- Optional push of the final Parquet dataset to the Hugging Face Hub
Installation
Using uv:
uv sync
Then run:
uv run pretokenization --help
Or install with pip:
pip install -e .
Quick Start
Create a config file:
base_model: meta-llama/Llama-3.1-8B-Instruct
sequence_len: 8192
datasets:
- path: HuggingFaceH4/ultrachat_200k
type: dan-chat-advanced
conversation_field: messages
role_field: role
system_prompt: You are a concise assistant.
- path: openwebtext
type: completion
field: text
Run the tokenizer:
uv run pretokenization \
--config config.yaml \
--output output.parquet \
--format Llama3
If you omit --format and your config includes chat datasets, the CLI will open a TUI selector.
Config File
Top-level keys:
| Key | Required | Description |
|---|---|---|
base_model |
Yes | Tokenizer source passed to transformers.AutoTokenizer.from_pretrained(...). |
sequence_len |
No | Maximum sequence length. Defaults to 8192. |
datasets |
Yes | List of dataset entries to process. |
model_type |
No | Present in config parsing but not used by the current CLI. |
tokenizer_type |
No | Present in config parsing but not used by the current CLI. |
Dataset entries are split by type:
dan-chat-advanced: chat/conversation datacompletion: plain text completion data
Chat Dataset Fields
Supported chat dataset keys:
| Key | Required | Default | Description |
|---|---|---|---|
path |
Yes | - | Dataset identifier passed to datasets.load_dataset(...). |
type |
Yes | - | Must be dan-chat-advanced. |
conversation_field |
No | conversations |
Field containing the list of turns. |
role_field |
No | from |
Field inside each turn that contains the role. |
reasoning_field |
No | - | Field name to read reasoning content from. |
reasoning_prefix |
No | format-specific | Override reasoning prefix text. |
reasoning_suffix |
No | format-specific | Override reasoning suffix text. |
reasoning_loss |
No | format-specific | Whether reasoning tokens contribute to loss (jinja mode: default false, masked). |
system_prompt |
No | - | Replaces the existing system message or prepends one. |
train_last_response_only |
No | false |
Masks all assistant turns except the last one. |
template_kwargs |
No | - | Jinja mode only: kwargs passed to the chat template (e.g. enable_thinking: false). |
reasoning_mode |
No | reasoning_content |
Jinja mode only: reasoning_content, think_wrap, or none. |
Recognized role values are normalized to internal roles:
- system:
system,sys - user:
user,human - assistant:
assistant,model,gpt - tool:
tool,function,environment
Turn content is read from value when present, otherwise from content.
Completion Dataset Fields
| Key | Required | Default | Description |
|---|---|---|---|
path |
Yes | - | Dataset identifier passed to datasets.load_dataset(...). |
type |
Yes | - | Must be completion. |
field |
No | text |
Field containing the raw text to tokenize. |
Expected Input Shape
Chat example:
{
"messages": [
{"role": "system", "content": "You are helpful."},
{"role": "user", "content": "Explain gradient descent."},
{"role": "assistant", "content": "Gradient descent is..."}
]
}
Chat items may also include:
reasoningorreasoning_contenton assistant turnslosson individual turnstoolsorfunctionsfor tool-enabled ChatML reasoning data- assistant
tool_callsorfunction_calls
Completion example:
{
"text": "A plain training sample."
}
Output
The CLI writes a single Parquet file. Each row contains:
| Column | Meaning |
|---|---|
input_ids |
Token IDs for the formatted sample |
attention_mask |
All ones, matching sequence length |
labels |
Training labels, with masked positions set to -100 |
Behavior by dataset type:
- Chat datasets mask non-trainable tokens such as role wrappers, system text, and user text.
- Completion datasets train on every token.
- The final combined dataset is shuffled before being written.
CLI
pretokenization --config CONFIG [--output OUTPUT] [--format FORMAT] [--system-prompt TEXT] [--hf-push REPO] [--seed N] [--debug] [-y]
Flags:
| Flag | Description |
|---|---|
--config |
Path to the YAML config file. Required. |
--output |
Output Parquet path. Defaults to ./output.parquet. |
--format |
Chat format name. Built-in name or a Jinja entry (see below). Skips the interactive selector. |
--system-prompt |
Global override applied to all chat datasets. |
--chat-template |
Path to a chat_template.jinja file. Enables Jinja template mode. |
--template-kv |
Kwarg passed to the chat template, e.g. --template-kv enable_thinking=false. Repeatable; overrides per-dataset template_kwargs. |
--reasoning-mode |
Jinja mode only: reasoning_content (default), think_wrap, or none. |
--validate-format |
Dev tool: render a synthetic conversation with the jinja template (optionally compare against the --format built-in), then exit. |
--hf-push |
Pushes the final dataset to the Hugging Face Hub. |
--seed |
Seed for the final shuffle. |
--debug |
Enables debug logging. |
--yes, -y |
Skips the confirmation prompt after previews. |
Examples:
uv run pretokenization --config config.yaml --format ChatMLReasoning -y
uv run pretokenization \
--config config.yaml \
--output tokenized.parquet \
--format Llama4 \
--system-prompt "You are a careful coding assistant." \
--hf-push your-org/your-dataset \
-y
If you use --hf-push, set HF_TOKEN in the environment first.
Format Notes
- The hand-written formats above are frozen (maintenance only). For new formats,
use Jinja template mode with the model's
chat_template.jinja- no code changes required (see "Jinja Chat Template Mode"). - Templates containing
{% generation %}blocks automatically use a fast path: a single render returns per-token assistant masks, so the per-boundary diff renders are skipped entirely. The template author decides exactly what counts as assistant-generated (typically the message content and turn closure, not the role header). The fast path is used when every assistant message is trained and there is no reasoning to mask; otherwise the diff path handles the item. ChatMLReasoninghas special handling for reasoning traces, tool definitions, tool responses, and assistant tool calls.ChatMLNonReasoninginjects an empty<think>...</think>block into assistant turns.ChatML with BOS Fixuses the tokenizer's BOS token for the starting sequence.Gemma4includes an in-code warning that the first system message may need manual reasoning markup for Gemma 4 reasoning workflows.- For non-
ChatMLReasoningformats, reasoning content is injected only on the last assistant turn.
Jinja Chat Template Mode
Instead of the built-in per-format token skeletons, you can format datasets with any
standard chat_template.jinja file (the same templates shipped with tokenizers on
Hugging Face):
uv run pretokenization --config config.yaml --chat-template ./chat_template.jinja -y
or via --format "Jinja (custom .jinja file)" / --format "Jinja (tokenizer's chat_template.jinja)"
(the latter uses whatever template the tokenizer itself ships, e.g. Gemma's <|turn> markup).
How it works:
- Conversations are converted to OpenAI-style messages (
role/content, plustool_calls,reasoning_content, and item-leveltools) and rendered throughtokenizer.apply_chat_template(...). - Loss labels are derived by rendering the conversation with and without each
trained assistant message and marking the token difference as the trained
span. Each span is the union of a prefix-render diff and a content-erasure
diff against the final render, which keeps it correct even for stateful
templates whose rendering of a turn depends on the following conversation
(e.g. Gemma's thinking gate, Qwen's
last_query_index). Everything else stays masked. - Reasoning traces are masked by default (like the built-in reasoning formats);
set
reasoning_loss: trueon the dataset to train on them. Masking uses a dual render (message with vs. without its reasoning) and masks the token difference inside the trained span, including the whole<|channel>thoughtblock on Gemma. system_prompt,train_last_response_only, per-turnlossflags, tools, and tool calls all work as in the built-in formats.reasoning_prefix/reasoning_suffixare ignored - the template controls reasoning markup. Gemma'sdevelopersystem role is recognized.- Reasoning traces can be surfaced three ways (
--reasoning-mode):reasoning_content(default): put intomessage.reasoning_content, rendered by templates that support it (e.g.<think>.../<|channel>thoughtblocks),think_wrap: inlined as<think>...</think>in the message content,none: left untouched in the content.
- Template-specific variables (
enable_thinking,reasoning_effort,add_vision_id, ...) are forwarded via--template-kv key=value(CLI) or per-datasettemplate_kwargs(config).
Semantics (what gets trained vs masked, aligned with inference-time behavior):
- The assistant role header (e.g.
<|im_start|>assistant\n) and any template-emitted reasoning wrapper the model never generates are masked: an empty<think></think>block (non-thinking mode prefills it wholesale) and the<think>\nopener when reasoning is present (thinking mode prefills it). This matches the{% generation %}convention and the fast path below. - With reasoning present, the reasoning text is masked unless
reasoning_loss: true; the closing</think>(which the model does generate) stays trained. Note: for templates that omit the whole reasoning block when empty (e.g. Gemma's<|channel>thought), the opener can only be separated when reasoning is masked - withreasoning_loss: trueit is trained along with the reasoning. - The trailing turn separator after the last trained message stays trained in the diff path (the fast path drops it).
- Token-merge artifacts at span boundaries (where the renders tokenize differently at the junction) are detected and the first divergent token is masked, with a warning.
- Validated against the canonical Qwen and Gemma chat templates (see
tests/test_jinja_renderer.py).
Validating a template
A dev command renders a synthetic conversation through the jinja path and, when given a built-in format name, compares both outputs:
uv run pretokenization --config config.yaml --validate-format \
--chat-template ./chat_template_gemma.jinja --format Gemma4
It prints the rendered text, the trained region, the first token divergence and whether the trained regions are compatible, then exits without processing datasets (the config may list zero datasets).
Operational Notes
- Source datasets are loaded in streaming mode from the
trainsplit. - The tool previews one example from each dataset before processing unless
-yis used. - Intermediate tokenized shards are written to temporary Parquet files.
- The final combined dataset is materialized in memory for shuffling before the output file is written, so very large runs still need enough RAM.
Development
The project is packaged with Hatchling and includes Ruff configuration in pyproject.toml.