# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨 # This file was automatically generated from src/transformers/models/kimi_k25/modular_kimi_k25.py. # Do NOT edit this file manually as any edits will be overwritten by the generation of # the file from the modular. If any change should be done, please apply the change to the # modular_kimi_k25.py file directly. One of our CI enforces this. # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨 # Copyright 2026 the HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import time import numpy as np from ...processing_utils import MultiModalData, ProcessingKwargs, ProcessorMixin from ...utils import auto_docstring, logging logger = logging.get_logger(__name__) class Kimi_K25ProcessorKwargs(ProcessingKwargs, total=False): _defaults = { "text_kwargs": { "padding": False, "return_mm_token_type_ids": False, }, "videos_kwargs": {"return_metadata": True}, } @auto_docstring class Kimi_K25Processor(ProcessorMixin): valid_processor_kwargs = Kimi_K25ProcessorKwargs def __init__( self, image_processor=None, tokenizer=None, video_processor=None, chat_template=None, **kwargs, ): super().__init__(image_processor, tokenizer, video_processor, chat_template=chat_template) self.image_token = "<|media_pad|>" if not hasattr(tokenizer, "image_token") else tokenizer.image_token self.video_token = ( "<|kimi_k25_video_placeholder|>" if not hasattr(tokenizer, "video_token") else tokenizer.video_token ) self.image_token_id = ( tokenizer.image_token_id if getattr(tokenizer, "image_token_id", None) else tokenizer.convert_tokens_to_ids(self.image_token) ) self.video_token_id = ( tokenizer.video_token_id if getattr(tokenizer, "video_token_id", None) else tokenizer.convert_tokens_to_ids(self.video_token) ) def replace_image_token(self, image_inputs: dict, image_idx: int, **kwargs) -> str: merge_length = self.image_processor.merge_size**2 num_image_tokens = image_inputs["image_grid_thw"][image_idx].prod() // merge_length return self.image_token * num_image_tokens def replace_video_token(self, video_inputs: dict, video_idx: int, **kwargs) -> str: merge_length = self.video_processor.merge_size**2 temporal_patch_size = self.video_processor.temporal_patch_size num_chunks = video_inputs["num_chunks_per_video"][video_idx] start = 0 if video_idx == 0 else np.cumsum(video_inputs["num_chunks_per_video"])[video_idx - 1] video_grid_thw = video_inputs["video_grid_thw"][start : start + num_chunks] video_structure = "" metadata = video_inputs["video_metadata"][video_idx] if metadata.fps is None: logger.warning_once( "SmolVLM requires frame timestamps to construct prompts, but the `fps` of the input video could not be inferred. " "Probably `video_metadata` was missing from inputs and you passed pre-sampled frames. " "Defaulting to `fps=24`. Please provide `video_metadata` for more accurate results." ) metadata.fps = 24 for chunk_id in range(num_chunks): current_chunk = metadata.timestamps[ (chunk_id * temporal_patch_size) : (chunk_id + 1) * temporal_patch_size ] timestamp = float(current_chunk[0]) current_chunk = metadata.timestamps[chunk_id : chunk_id + temporal_patch_size] timestamp_str = time.strftime("%H:%M:%S", time.gmtime(timestamp)) + f".{int(timestamp % 1 * 1000):03d}" num_frame_tokens = video_grid_thw[chunk_id][1:].prod() // merge_length video_tokens = num_frame_tokens * self.video_token video_structure += f"{timestamp_str}<|media_begin|>video<|media_content|>{video_tokens}<|media_end|>" return video_structure def _get_num_multimodal_tokens(self, image_sizes=None, video_sizes=None, **kwargs): """ Computes the number of placeholder tokens needed for multimodal inputs with the given sizes. Args: image_sizes (`list[list[int]]`, *optional*): The input sizes formatted as (height, width) per each image. video_sizes (`list[list[int]]`, *optional*): The input sizes formatted as (num_frames, height, width) per each video. Returns: `MultiModalData`: A `MultiModalData` object holding number of tokens per each of the provided input modalities, along with other useful data. """ vision_data = {} if image_sizes is not None: images_kwargs = Kimi_K25ProcessorKwargs._defaults.get("images_kwargs", {}) images_kwargs.update(kwargs) merge_size = images_kwargs.get("merge_size", None) or self.image_processor.merge_size num_image_patches = [ self.image_processor.get_number_of_image_patches(*image_size, images_kwargs) for image_size in image_sizes ] num_image_tokens = [(num_patches // merge_size**2) for num_patches in num_image_patches] vision_data.update({"num_image_tokens": num_image_tokens, "num_image_patches": num_image_patches}) if video_sizes is not None: videos_kwargs = Kimi_K25ProcessorKwargs._defaults.get("videos_kwargs", {}) videos_kwargs.update(kwargs) num_video_patches = [ self.video_processor.get_number_of_video_patches(*video_size, videos_kwargs) for video_size in video_sizes ] num_video_tokens = [(num_patches // merge_size**2) for num_patches in num_video_patches] vision_data["num_video_tokens"] = num_video_tokens return MultiModalData(**vision_data) def post_process_image_text_to_text( self, generated_outputs, skip_special_tokens=True, clean_up_tokenization_spaces=False, **kwargs ): """ Post-process the output of the model to decode the text. Args: generated_outputs (`torch.Tensor` or `np.ndarray`): The output of the model `generate` function. The output is expected to be a tensor of shape `(batch_size, sequence_length)` or `(sequence_length,)`. skip_special_tokens (`bool`, *optional*, defaults to `True`): Whether or not to remove special tokens in the output. Argument passed to the tokenizer's `batch_decode` method. clean_up_tokenization_spaces (`bool`, *optional*, defaults to `False`): Whether or not to clean up the tokenization spaces. Argument passed to the tokenizer's `batch_decode` method. **kwargs: Additional arguments to be passed to the tokenizer's `batch_decode method`. Returns: `list[str]`: The decoded text. """ return self.tokenizer.batch_decode( generated_outputs, skip_special_tokens=skip_special_tokens, clean_up_tokenization_spaces=clean_up_tokenization_spaces, **kwargs, ) @property def model_input_names(self) -> list[str]: model_input_names = [] for attribute_name in self.get_attributes(): attribute = getattr(self, attribute_name, None) if attribute is not None: attr_input_names = getattr(attribute, "model_input_names") model_input_names.extend(attr_input_names) return [name for name in model_input_names if name not in self.unused_input_names] @property def unused_input_names(self): return ["num_chunks_per_video"] __all__ = ["Kimi_K25Processor"]