sthui/SimpleSeg
010
1# coding=utf-82# Copyright 2025 The Moonshot Team and HuggingFace Inc. team. All rights reserved.3#4# The code is based on the Qwen2VL processor (qwen2_vl/processing_qwen2_vl.py), but modified for KimiVL.5#6# Licensed under the Apache License, Version 2.0 (the "License");7# you may not use this file except in compliance with the License.8# You may obtain a copy of the License at9#10# http://www.apache.org/licenses/LICENSE-2.011#12# Unless required by applicable law or agreed to in writing, software13# distributed under the License is distributed on an "AS IS" BASIS,14# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.15# See the License for the specific language governing permissions and16# limitations under the License.17"""18Processor class for KimiVL.19"""20 21from typing import List, Union22 23from transformers.feature_extraction_utils import BatchFeature24from transformers.image_utils import ImageInput25from transformers.processing_utils import ProcessingKwargs, ProcessorMixin, Unpack26from transformers.tokenization_utils_base import PreTokenizedInput, TextInput27from transformers.utils import logging28 29 30logger = logging.get_logger(__name__)31 32 33class KimiVLProcessorKwargs(ProcessingKwargs, total=False):34 _defaults = {35 "text_kwargs": {36 "padding": False,37 },38 "images_kwargs": {},39 }40 41 42class KimiVLProcessor(ProcessorMixin):43 r"""44 Constructs a KimiVL processor which wraps a KimiVL image processor and a tokenizer into a single processor.45 46 [`KimiVLProcessor`] offers all the functionalities of [`KimiVLImageProcessor`] and [`TikTokenTokenizer`]. See the47 [`~KimiVLProcessor.__call__`] and [`~KimiVLProcessor.decode`] for more information.48 49 Args:50 image_processor ([`KimiVLImageProcessor`], *optional*):51 The image processor is a required input.52 tokenizer ([`TikTokenTokenizer`], *optional*):53 The tokenizer is a required input.54 chat_template (`str`, *optional*): A Jinja template which will be used to convert lists of messages55 in a chat into a tokenizable string.56 """57 58 attributes = ["image_processor", "tokenizer"]59 valid_kwargs = [ "chat_template"]60 image_processor_class = "AutoImageProcessor"61 tokenizer_class = "AutoTokenizer"62 63 def __init__(64 self,65 image_processor=None,66 tokenizer=None,67 chat_template=None,68 **kwargs,69 ):70 self.image_token = "<|media_pad|>"71 super().__init__(image_processor, tokenizer, chat_template=chat_template)72 73 def __call__(74 self,75 images: ImageInput = None,76 text: Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None,77 **kwargs: Unpack[KimiVLProcessorKwargs],78 ) -> BatchFeature:79 """80 Main method to prepare for the model one or several sequences(s) and image(s). This method forwards the `text`81 and `kwargs` arguments to TikTokenTokenizer's [`~TikTokenTokenizer.__call__`] if `text` is not `None` to encode82 the text. To prepare the image(s), this method forwards the `images` and `kwrags` arguments to83 CLIPImageProcessor's [`~CLIPImageProcessor.__call__`] if `images` is not `None`. Please refer to the docstring84 of the above two methods for more information.85 86 Args:87 images (`PIL.Image.Image`, `np.ndarray`, `torch.Tensor`, `List[PIL.Image.Image]`, `List[np.ndarray]`, `List[torch.Tensor]`):88 The image or batch of images to be prepared. Each image can be a PIL image, NumPy array or PyTorch89 tensor. Both channels-first and channels-last formats are supported.90 text (`str`, `List[str]`, `List[List[str]]`):91 The sequence or batch of sequences to be encoded. Each sequence can be a string or a list of strings92 (pretokenized string). If the sequences are provided as list of strings (pretokenized), you must set93 `is_split_into_words=True` (to lift the ambiguity with a batch of sequences).94 return_tensors (`str` or [`~utils.TensorType`], *optional*):95 If set, will return tensors of a particular framework. Acceptable values are:96 - `'tf'`: Return TensorFlow `tf.constant` objects.97 - `'pt'`: Return PyTorch `torch.Tensor` objects.98 - `'np'`: Return NumPy `np.ndarray` objects.99 - `'jax'`: Return JAX `jnp.ndarray` objects.100 101 Returns:102 [`BatchFeature`]: A [`BatchFeature`] with the following fields:103 104 - **input_ids** -- List of token ids to be fed to a model. Returned when `text` is not `None`.105 - **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when106 `return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names` and if `text` is not107 `None`).108 - **pixel_values** -- Pixel values to be fed to a model. Returned when `images` is not `None`.109 """110 if images is None and text is None:111 raise ValueError("You have to specify at least one of `images` or `text`.")112 113 output_kwargs = self._merge_kwargs(114 KimiVLProcessorKwargs,115 tokenizer_init_kwargs=self.tokenizer.init_kwargs,116 **kwargs,117 )118 if images is not None:119 image_inputs = self.image_processor(images, **output_kwargs["images_kwargs"])120 image_grid_hws = image_inputs["image_grid_hws"]121 else:122 image_inputs = {}123 image_grid_hws = None124 125 if isinstance(text, str):126 text = [text]127 elif not isinstance(text, list) and not isinstance(text[0], str):128 raise ValueError("Invalid input text. Please provide a string, or a list of strings")129 130 if image_grid_hws is not None:131 merge_length = self.image_processor.merge_kernel_size[0] * self.image_processor.merge_kernel_size[1]132 index = 0133 for i in range(len(text)):134 while self.image_token in text[i]:135 text[i] = text[i].replace(136 self.image_token,137 "<|placeholder|>" * (image_grid_hws[index].prod() // merge_length),138 1,139 )140 index += 1141 text[i] = text[i].replace("<|placeholder|>", self.image_token)142 143 text_inputs = self.tokenizer(text, **output_kwargs["text_kwargs"])144 return BatchFeature(data={**text_inputs, **image_inputs})145 146 def batch_decode(self, *args, **kwargs):147 """148 This method forwards all its arguments to LlamaTokenizerFast's [`~PreTrainedTokenizer.batch_decode`]. Please149 refer to the docstring of this method for more information.150 """151 return self.tokenizer.batch_decode(*args, **kwargs)152 153 def decode(self, *args, **kwargs):154 """155 This method forwards all its arguments to LlamaTokenizerFast's [`~PreTrainedTokenizer.decode`]. Please refer to156 the docstring of this method for more information.157 """158 return self.tokenizer.decode(*args, **kwargs)159 160 @property161 def model_input_names(self):162 tokenizer_input_names = self.tokenizer.model_input_names163 image_processor_input_names = self.image_processor.model_input_names164 return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names))165 166 167__all__ = ["KimiVLProcessorKwargs"]