nemo_automodel.components.datasets.llm.formatting_utils
nemo_automodel.components.datasets.llm.formatting_utils
Module Contents
Functions
Data
API
Add pad token to tokenizer if not present.
Return how many leading tokens of turn a generation prompt render supplies, or 0.
base_ids is the conversation prefix rendered plain, generation_ids
the same prefix rendered with add_generation_prompt=True and turn
the tokens the full render has after base_ids. The prompt counts only
when the prompt render is the plain render plus an appended block and the
turn opens with that whole block: the block is then exactly what the
template emits at inference with no assistant message present, so it holds
no token of the message. A prompt render that rewrites the prefix, or a
turn that reproduces the block only partly, proves nothing and gives 0
(see :func:_build_generation_prompt_mask for why).
Mark the tokens of each assistant turn that the generation prompt supplies.
At inference the chat template, not the model, emits the assistant role
header plus whatever it inserts ahead of the first generated token. For a
turn without reasoning that is typically an empty reasoning block such as
<think></think> (Nemotron), <think>\n\n</think>\n\n (Qwen3) or
</think> (DeepSeek V3.1); for a thinking turn it may be an opening
<think>\n. The model never produces these tokens, so supervising them
only teaches template boilerplate, and an empty reasoning block also
teaches an immediate <think> -> </think> transition.
The span is located without knowing any tag string, from what a generation
prompt is by definition: the tokens add_generation_prompt=True appends
to the rendered conversation prefix. For every assistant turn,
messages[:idx] is rendered plain and with the generation prompt; when
the template reads enable_thinking, the prompt is rendered in both
modes (True and False), because the data alone cannot tell them apart: a
thinking turn may carry its reasoning in reasoning_content or inline
in content. A template that never reads the variable renders one
prompt, without the keyword (a backend without Jinja templates may reject
it). A mode counts only when its prompt render appends a block to the
unchanged plain render and the turn in the full render opens with that
whole block (see :func:_appended_generation_prompt_length); the longest
such block is marked. No token of the message is compared or inferred, so
assistant content is never reached, and everything else fails closed:
- a plain prefix render that is not an exact prefix of the full render (the template rewrites history as the conversation grows, or replaces its terminator) leaves the turn supervised, warned once per process;
- a prompt render that rewrites the prefix instead of appending to it
(Gemma 4 prepends a thinking system block, GLM 4.5 appends
/nothinkto the user turn) is ignored, since its added tokens cannot be told from rendered history; - a turn that reproduces the appended block only partly (SmolLM3, or
Qwen3-Thinking without reasoning text, render fewer tokens than the
prompt emits) is left supervised. A partial match says nothing about
where the template stops and the message starts, because a message
token can equal the prompt token at the same position: Gemma 4’s
<|channel>thought\nis generated in thinking mode but appended by the non-thinking prompt.
Truncation is handled like :func:_build_reasoning_mask: spans are located
in the untruncated render and mapped back through the retained window,
which must be a contiguous prefix or suffix of it. A leading assistant turn
whose template cannot render an empty conversation is left untouched
(warned once per process); any other render error propagates. Positions
are computed from unpadded (left-aligned) ids, like
:func:_build_multiturn_assistant_mask, whose prefix renders are read
from prefix_cache (nothing is written back). One or two extra
apply_chat_template renders per assistant turn are the price, which is
why this is opt-in.
Build a fallback loss mask that supervises every assistant turn.
Each assistant span is located by tokenizing the conversation prefixes
before and after the turn, which is O(turns) apply_chat_template calls.
Two reductions keep that from re-doing work:
unpadded_full_idsis the caller’s already-known unpadded tokenization of the whole conversation. When the dialogue ends on an assistant turn its closing boundary is the full conversation, so passing it skips re-tokenizing the entire prefix (the single most expensive call in the loop). When omitted, the full conversation is tokenized once here.- Each prefix length is memoized so a boundary shared by adjacent turns (a
turn’s end and the next turn’s start) is tokenized at most once. When the
caller passes a
prefix_cachedict (k-> ids offormatted_text[:k]) the rendered ids are kept in it as well, so :func:_build_generation_prompt_maskcan reuse these renders instead of repeating them; without one only the lengths are retained, since holding every prefix render would cost O(turns x sequence length) per sample.
Every tokenized prefix is validated against unpadded_full_ids (see
:func:_is_consistent_render_prefix). A known trailing EOS may differ when
the prefix is rendered alone. Any other mismatch raises :class:ValueError
because prefix arithmetic cannot place the spans safely.
Build a token mask for reasoning_content spans inside assistant turns.
Each span is isolated by comparing the full conversation render with a
second full render where only that message’s reasoning_content is
cleared. This remains correct when the template rewrites earlier turns
based on later messages. If clearing the field does not change the render,
that turn’s reasoning is not present and no tokens need to be masked.
Return the number of leading elements left and right share.
Locate the contiguous token span attributable to reasoning content.
Boolean mask identifying right-trailing padding positions.
When pad_token_id != eos_token_id, it is simply sequence == pad_token_id.
When the two IDs collide, a plain equality check would also match real EOS tokens inside the content. In that case the function locates the trailing contiguous run of the shared token and treats all positions after the first one in that run as padding. The first token in the trailing run is the real EOS and is kept unmasked so the model still learns to predict end-of-sequence.
Parameters:
1-D token id tensor.
The token id used for padding.
The token id used for end-of-sequence. When equal to pad_token_id the positional trailing-run logic is used.
Returns: torch.Tensor
Boolean tensor (same shape as sequence) where True = padding.
Check if the tokenizer supports a chat template.
Parameters:
The tokenizer to check.
Returns: bool
True if the tokenizer supports a chat template, False otherwise.
Check that a prefix render matches the start of the full-conversation render.
Locating spans by prefix lengths is only correct when
render(messages[:k]) reproduces the first tokens of render(messages).
The comparison is exact unless a multi-token prefix ends with a known
standalone terminator that is replaced when the next message is appended.
Restrict supervision to the final assistant turn (mask_history).
Operates on any per-token sequence where ignore_index marks
unsupervised positions: a label list (ignore_index=-100) or a 0/1
assistant mask (ignore_index=0). Each assistant turn renders as a
single contiguous supervised span, so this keeps only the last such run
and rewrites every earlier supervised position to ignore_index.
Apply this to the assistant mask before any reasoning_content holes are punched into it; running it on already-holed labels would treat the reasoning gap as a turn boundary and drop in-turn content before the hole.
Parameters:
per-token labels or 0/1 mask (ignore_index marks unsupervised).
the value marking unsupervised positions.
Returns: List[int]
The same list, mutated so only the final supervised run is kept.
Return a copy of a message with reasoning_content removed.
Shift a token-level mask right when the tokenizer uses left padding.
_build_multiturn_assistant_mask and _build_reasoning_mask compute
span indices from unpadded (left-aligned) tokenizations. When the
tokenizer pads on the left, actual content is right-aligned in
input_ids, so the mask must be shifted right by the padding offset to
keep positions aligned.
For right-padding tokenizers (the majority) this is a no-op.
Package a tokenized example with proper masking and padding.
Returns:
A dictionary with input_ids, labels, and attention_mask.
When unshifted is True, labels is replaced by loss_mask.
Parameters:
The tokenizer to use.
The tokenized input ids.
Boolean mask indicating which tokens are assistant/answer tokens (1) vs prompt tokens (0).
The end-of-sequence token id.
The padding token id.
Optional sequence length for padding.
Optional truncation strategy.
Optional padding strategy.
If True, return unshifted format for dLLM training
(input_ids at full length with loss_mask instead of
shifted input_ids/labels).
Pad a sample to a specific sequence length.
Resolve a chat template string that may be a file path.
If chat_template points to an existing file, its contents are returned.
If opening it as a file fails and the string contains Jinja-like characters
({, }, or newlines) it is treated as a literal template. Otherwise
a :class:ValueError is raised so the caller knows the path was invalid.
Parameters:
A Jinja template string or path to a template file.
Returns: str | None
The resolved template string, or None when the input is None.
Zero every position of mask that removed marks.
Tokenize chat messages without padding and return input ids.
template_kwargs (for example add_generation_prompt or
enable_thinking) are forwarded to apply_chat_template as given, so the
default path calls the tokenizer exactly as before.
Return the tokenized chat length for a message prefix without padding.
Return where the retained (truncated) tokens start inside the untruncated render.
The retained window must be a contiguous prefix (right truncation) or suffix
(left truncation) of reference_full_ids. A short window can match both
ends of a render that starts and ends with the same tokens, so the side the
tokenizer actually truncates on (tokenizer.truncation_side) is tried first.
Format a chat template style example.
Parameters:
The tokenizer to use.
The formatted text, with role tags embedded in the content.
The end-of-sequence token id.
The padding token id.
Optional sequence length for padding.
Optional list of tool definitions for function calling.
Whether to compute the loss mask only on the answer tokens.
Whether to exclude rendered reasoning_content tokens from loss.
Whether to supervise only the final assistant turn,
masking every earlier assistant turn (mask_history). Applied to the
assistant mask before reasoning_content is masked out.
Whether to exclude from the loss the tokens of each
assistant turn that the chat template’s generation prompt supplies at
inference: the role header and any template-inserted empty reasoning
block (for example <think></think>). See
:func:_build_generation_prompt_mask.
Returns: Dict[str, List[int]]
A dictionary with the formatted example.
Format a prompt-completion style example (without chat template).
Parameters:
The tokenizer to use.
The prompt string (e.g. context + question).
The answer string.
The end-of-sequence token id.
The padding token id.
Optional sequence length for padding.
Returns: Dict[str, List[int]]
A dictionary with the formatted example.