[Render][Speculator] Add return_loss_mask to render endpoint for training data generation (#46846)

Signed-off-by: Ranran Haoran Zhang <ranzhang@redhat.com>
Co-authored-by: Benjamin Chislett <chislett.ben@gmail.com>
This commit is contained in:
Ranran
2026-06-28 00:07:33 -07:00
committed by GitHub
co-authored by Benjamin Chislett
parent a2a92cbbaa
commit 09841ae705
7 changed files with 288 additions and 20 deletions
+106 -19
View File
@@ -7,7 +7,7 @@ import inspect
import itertools
import weakref
from collections import defaultdict, deque
from collections.abc import Sequence
from collections.abc import Mapping, Sequence
from functools import lru_cache
from typing import TYPE_CHECKING, Any, Final, Literal, cast, overload
@@ -678,6 +678,7 @@ def safe_apply_chat_template(
tools: list[dict[str, Any]] | None = ...,
chat_template: str | None = ...,
tokenize: Literal[True] = ...,
return_assistant_tokens_mask: Literal[False] = ...,
**kwargs,
) -> list[int]: ...
@overload
@@ -689,8 +690,20 @@ def safe_apply_chat_template(
tools: list[dict[str, Any]] | None = ...,
chat_template: str | None = ...,
tokenize: Literal[False] = ...,
return_assistant_tokens_mask: Literal[False] = ...,
**kwargs,
) -> str: ...
@overload
def safe_apply_chat_template(
model_config: ModelConfig,
tokenizer: HfTokenizer,
conversation: list[ConversationMessage],
*,
tools: list[dict[str, Any]] | None = ...,
chat_template: str | None = ...,
return_assistant_tokens_mask: Literal[True],
**kwargs,
) -> tuple[list[int], list[int] | None]: ...
def safe_apply_chat_template(
model_config: ModelConfig,
tokenizer: HfTokenizer,
@@ -699,8 +712,9 @@ def safe_apply_chat_template(
tools: list[dict[str, Any]] | None = None,
chat_template: str | None = None,
tokenize: bool = True,
return_assistant_tokens_mask: bool = False,
**kwargs,
) -> str | list[int]:
) -> str | list[int] | tuple[list[int], list[int] | None]:
chat_template = resolve_chat_template(
tokenizer,
chat_template=chat_template,
@@ -728,6 +742,38 @@ def safe_apply_chat_template(
chat_template_kwargs=kwargs,
)
# assistant_tokens_mask requires tokenized output — force tokenize=True.
if return_assistant_tokens_mask:
tokenize = True
# When return_assistant_tokens_mask is requested and the template supports it,
# request assistant_tokens_mask via return_dict.
# Check for the actual Jinja tag, not just the word "generation"
# (which also appears in add_generation_prompt).
if return_assistant_tokens_mask and "{% generation %}" in chat_template:
resolved_kwargs["return_assistant_tokens_mask"] = True
resolved_kwargs["return_dict"] = True
resolved_kwargs.pop("tokenize", None)
try:
result = tokenizer.apply_chat_template(
conversation=conversation, # type: ignore[arg-type]
tools=tools, # type: ignore[arg-type]
chat_template=chat_template,
tokenize=True,
**resolved_kwargs,
)
except (TypeError, ValueError) as exc:
logger.warning(
"apply_chat_template failed for assistant_tokens_mask: %s", exc
)
else:
if isinstance(result, Mapping):
token_ids = list(result.get("input_ids", []))
mask_raw = result.get("assistant_masks")
mask = list(mask_raw) if mask_raw is not None else None
return token_ids, mask
return list(result), None
# transformers v5 changed the default of `return_dict` to True, which
# makes `apply_chat_template(tokenize=True)` return a `BatchEncoding`
# instead of `list[int]`. Force `return_dict=False` so downstream code
@@ -737,23 +783,24 @@ def safe_apply_chat_template(
resolved_kwargs["return_dict"] = False
try:
return tokenizer.apply_chat_template(
plain = tokenizer.apply_chat_template(
conversation=conversation, # type: ignore[arg-type]
tools=tools, # type: ignore[arg-type]
chat_template=chat_template,
tokenize=tokenize,
**resolved_kwargs,
)
# External library exceptions can sometimes occur despite the framework's
# internal exception management capabilities.
except Exception as e:
# Log and report any library-related exceptions for further
# investigation.
logger.exception(
"An error occurred in `transformers` while applying chat template"
)
raise ValueError(str(e)) from e
if return_assistant_tokens_mask:
assert isinstance(plain, list), f"Expected list[int], got {type(plain)}"
return plain, None
return plain
def rebuild_mm_uuids_from_mm_data(
mm_uuids: MultiModalUUIDDict,
@@ -934,12 +981,22 @@ class HfRenderer(BaseRenderer[HfTokenizer]):
logger.warning_once(_TOKENIZE_OVERRIDE_WARNING)
chat_template_kwargs["tokenize"] = True
prompt_raw = safe_apply_chat_template(
model_config,
tokenizer,
conversation,
**chat_template_kwargs,
)
assistant_tokens_mask: list[int] | None = None
if params.return_assistant_tokens_mask:
prompt_raw, assistant_tokens_mask = safe_apply_chat_template(
model_config,
tokenizer,
conversation,
return_assistant_tokens_mask=True,
**chat_template_kwargs,
)
else:
prompt_raw = safe_apply_chat_template(
model_config,
tokenizer,
conversation,
**chat_template_kwargs,
)
# NOTE: use_unified_vision_chunk is currently specific to Kimi-K2.5
# model which uses unified vision chunks for both images and videos.
@@ -965,6 +1022,9 @@ class HfRenderer(BaseRenderer[HfTokenizer]):
prompt = parse_dec_only_prompt(prompt_raw)
if assistant_tokens_mask is not None:
cast(dict, prompt)["_assistant_tokens_mask"] = assistant_tokens_mask
# When `prompt_embeds` is mixed with other modality data,
# `_process_tokens` runs `_process_multimodal` first (expanding
# `<|AUDIO|>` / `<|IMAGE|>` placeholders) and then
@@ -1038,12 +1098,30 @@ class HfRenderer(BaseRenderer[HfTokenizer]):
logger.warning_once(_TOKENIZE_OVERRIDE_WARNING)
chat_template_kwargs["tokenize"] = True
prompt_raw = await self._apply_chat_template_async(
model_config,
tokenizer,
conversation,
**chat_template_kwargs,
)
assistant_tokens_mask: list[int] | None = None
if params.return_assistant_tokens_mask:
result_with_mask = cast(
tuple[list[int], list[int] | None],
await make_async(
safe_apply_chat_template,
executor=self._executor,
)(
model_config,
tokenizer,
conversation,
return_assistant_tokens_mask=True, # type: ignore[arg-type]
**chat_template_kwargs,
),
)
prompt_raw: str | list[int] = result_with_mask[0]
assistant_tokens_mask = result_with_mask[1]
else:
prompt_raw = await self._apply_chat_template_async(
model_config,
tokenizer,
conversation,
**chat_template_kwargs,
)
# NOTE: use_unified_vision_chunk is currently specific to Kimi-K2.5
# model which uses unified vision chunks for both images and videos.
@@ -1067,6 +1145,9 @@ class HfRenderer(BaseRenderer[HfTokenizer]):
prompt = parse_dec_only_prompt(prompt_raw)
if assistant_tokens_mask is not None:
cast(dict, prompt)["_assistant_tokens_mask"] = assistant_tokens_mask
# See `render_messages` for the rationale.
if prompt_embeds_tensors and mm_data:
assert prompt_embeds_placeholder_token_id is not None
@@ -1108,6 +1189,7 @@ class HfRenderer(BaseRenderer[HfTokenizer]):
processor records all placeholder offsets in the final (post-expansion)
coordinate space, no offset shifting needed afterwards.
"""
assistant_tokens_mask = cast(dict, prompt).pop("_assistant_tokens_mask", None)
prompt_embeds_info = cast(dict, prompt).pop("_prompt_embeds", None)
if prompt_embeds_info is not None:
tensors, placeholder_token_id = prompt_embeds_info
@@ -1123,6 +1205,8 @@ class HfRenderer(BaseRenderer[HfTokenizer]):
tensors,
mm_updates,
)
if assistant_tokens_mask is not None:
engine_input["assistant_tokens_mask"] = assistant_tokens_mask
return engine_input
@override
@@ -1133,6 +1217,7 @@ class HfRenderer(BaseRenderer[HfTokenizer]):
skip_mm_cache: bool = False,
) -> TokensInput | MultiModalInput:
"""Async equivalent of `_process_tokens`."""
assistant_tokens_mask = cast(dict, prompt).pop("_assistant_tokens_mask", None)
prompt_embeds_info = cast(dict, prompt).pop("_prompt_embeds", None)
if prompt_embeds_info is not None:
tensors, placeholder_token_id = prompt_embeds_info
@@ -1150,6 +1235,8 @@ class HfRenderer(BaseRenderer[HfTokenizer]):
tensors,
mm_updates,
)
if assistant_tokens_mask is not None:
engine_input["assistant_tokens_mask"] = assistant_tokens_mask
return engine_input
@staticmethod
+4
View File
@@ -87,6 +87,9 @@ class ChatParams:
mm_processor_kwargs: dict[str, Any] | None = None
"""The kwargs to pass to the multi-modal processor."""
return_assistant_tokens_mask: bool = False
"""Request a per-token assistant mask from apply_chat_template."""
def with_defaults(
self,
default_chat_template_kwargs: dict[str, Any] | None = None,
@@ -115,6 +118,7 @@ class ChatParams:
default_mm_processor_kwargs,
self.mm_processor_kwargs,
),
return_assistant_tokens_mask=self.return_assistant_tokens_mask,
)
def get_apply_chat_template_kwargs(self) -> dict[str, Any]: