# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨 # 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. from collections.abc import Callable from dataclasses import dataclass import torch import torch.nn as nn import torch.nn.functional as F from ... import initialization as init from ...activations import ACT2FN from ...cache_utils import Cache from ...generation import GenerationMixin from ...modeling_layers import GradientCheckpointingLayer from ...modeling_outputs import BaseModelOutputWithPast, BaseModelOutputWithPooling from ...modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel from ...processing_utils import Unpack from ...utils import ( ModelOutput, TransformersKwargs, auto_docstring, can_return_tuple, torch_compilable_check, ) from ...utils.deprecation import deprecate_kwarg from ...utils.generic import get_max_seqlen, is_flash_attention_requested, maybe_autocast from ...utils.output_capturing import capture_outputs from ...vision_utils import ( get_vision_attention_seqlens, get_vision_interpolation_indices_and_weights, get_vision_position_ids, ) from ..auto import AutoModel from .configuration_kimi_k25 import Kimi_K25Config, Kimi_K25VisionConfig @auto_docstring( custom_intro=""" Base class for Kimi_K25 outputs, with hidden states and attentions. """ ) @dataclass class Kimi_K25ModelOutputWithPast(BaseModelOutputWithPast): r""" past_key_values (`Cache`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`): It is a [`~cache_utils.Cache`] instance. For more details, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache). Contains pre-computed hidden-states (key and values in the self-attention blocks) that can be used (see `past_key_values` input) to speed up sequential decoding. image_hidden_states (`torch.FloatTensor`, *optional*): A `torch.FloatTensor` of size `(batch_size, num_images, sequence_length, hidden_size)`. image_hidden_states of the model produced by the vision encoder and after projecting the last hidden state. """ image_hidden_states: torch.FloatTensor | None = None @auto_docstring( custom_intro=""" Base class for Kimi_K25 causal language model (or autoregressive) outputs. """ ) @dataclass class Kimi_K25CausalLMOutputWithPast(ModelOutput): r""" loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided): Language modeling loss (for next-token prediction). logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`): Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax). past_key_values (`Cache`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`): It is a [`~cache_utils.Cache`] instance. For more details, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache). Contains pre-computed hidden-states (key and values in the self-attention blocks) that can be used (see `past_key_values` input) to speed up sequential decoding. image_hidden_states (`torch.FloatTensor`, *optional*): A `torch.FloatTensor` of size `(batch_size, num_images, sequence_length, hidden_size)`. image_hidden_states of the model produced by the vision encoder and after projecting the last hidden state. """ loss: torch.FloatTensor | None = None logits: torch.FloatTensor | None = None past_key_values: Cache | None = None hidden_states: tuple[torch.FloatTensor] | None = None attentions: tuple[torch.FloatTensor] | None = None image_hidden_states: torch.FloatTensor | None = None def get_vision_frame_index(grid_thw: torch.Tensor, kwargs: dict | None = None) -> torch.Tensor: """Per-patch index into a temporal embedding table whose row `0` is a zero pad, or pop `"frame_index"` from `kwargs`. Single-frame clips (`t == 1`, images) map every patch to `0` (no temporal term); frame `f` of a multi-frame clip maps to `f + 1`. Precomputable, so the encoder avoids a per-clip `if t > 1` loop. """ if kwargs is not None and (frame_index := kwargs.pop("frame_index", None)) is not None: return frame_index device = grid_thw.device parts = [] for t, h, w in grid_thw.tolist(): t, h, w = int(t), int(h), int(w) # t == 1 → [0] (padded row 0 = zero); t > 1 → [1..t] → time_emb[0..t-1] frames = torch.arange(t, device=device) + int(t > 1) parts.append(frames.repeat_interleave(h * w)) return torch.cat(parts) class Kimi_K25VisionPositionEmbeddings(nn.Module): def __init__(self, config): super().__init__() self.dim = config.hidden_size self.num_frames = config.pos_emb_time self.position_embeddings = nn.Parameter( torch.zeros(config.pos_emb_height, config.pos_emb_width, config.hidden_size) ) # How the (square) learned position grid is resampled to each image's grid. self.num_grid_per_side = config.pos_emb_height self.interpolation_align_corners = False self.interpolation_mode = "bicubic" # Time-axis pos_emb are an additive sinusoidal table, i.e. add pos to hiddens rather than rotating time_position_embeddings = self.compute_pos_embed() self.time_position_embeddings = nn.Buffer(time_position_embeddings, persistent=False) def compute_pos_embed(self): position_ids = torch.arange(self.num_frames, dtype=torch.float32) inv_freq = 1.0 / (10000 ** (torch.arange(0, self.dim, 2, dtype=torch.int64).to(dtype=torch.float) / self.dim)) freqs = torch.outer(position_ids, inv_freq) # (M, D/2) pos_embed = torch.cat([freqs.sin(), freqs.cos()], dim=1) # (M, D) # Prepend a zero row so frame index 0 (single-frame clips) adds no temporal offset. return torch.cat([pos_embed.new_zeros(1, self.dim), pos_embed]) # (M+1, D) def forward(self, hidden_states: torch.Tensor, grid_thw: torch.Tensor, **kwargs) -> torch.Tensor: # Spatial: bicubically resample the learned grid to each image's (h, w) as a fused weighted # gather (`embedding_bag`), equivalent to a per-image `F.interpolate(mode="bicubic")` but a # single traceable op over all patches — and faster. table = self.position_embeddings.flatten(0, 1) interp_indices, interp_weights = get_vision_interpolation_indices_and_weights( grid_thw, self.num_grid_per_side, mode=self.interpolation_mode, align_corners=self.interpolation_align_corners, kwargs=kwargs, ) pos = F.embedding_bag(interp_indices, table, per_sample_weights=interp_weights.to(table.dtype), mode="sum") # Temporal: add a per-frame sinusoid. Row 0 of the table is a zero pad, so single-frame clips # (frame index 0) get none. pos = pos + self.time_position_embeddings[get_vision_frame_index(grid_thw, kwargs=kwargs)] return hidden_states + pos.to(hidden_states.dtype) class Kimi_K25VisionPatchEmbed(nn.Module): def __init__(self, config): super().__init__() patch_size = ( config.patch_size if not isinstance(config.patch_size, int) else (config.patch_size, config.patch_size) ) self.proj = nn.Conv2d(3, config.hidden_size, kernel_size=patch_size, stride=patch_size) self.pos_emb = Kimi_K25VisionPositionEmbeddings(config) def forward(self, pixel_values: torch.Tensor, grid_thw: torch.Tensor, **kwargs) -> torch.Tensor: hidden_states = self.proj(pixel_values).view(pixel_values.size(0), -1) hidden_states = self.pos_emb(hidden_states, grid_thw, **kwargs) return hidden_states class Kimi_K25VisionRotaryEmbedding(nn.Module): @deprecate_kwarg("device", version="5.18") def __init__(self, config: Kimi_K25VisionConfig, device=None): super().__init__() self.max_seq_len_cached = config.max_position_embeddings self.original_max_seq_len = config.max_position_embeddings self.config = config self.rope_type = self.config.rope_parameters["rope_type"] rope_init_fn: Callable = self.compute_default_rope_parameters if self.rope_type != "default": rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type] inv_freq, self.attention_scaling = rope_init_fn(self.config, device) self.inv_freq = nn.Buffer(inv_freq, persistent=False) self.original_inv_freq = nn.Buffer(inv_freq.clone(), persistent=False) @staticmethod @deprecate_kwarg("device", version="5.18") def compute_default_rope_parameters( config: Kimi_K25VisionConfig, device=None, **kwargs ) -> tuple[torch.Tensor, float]: """ Computes the inverse frequencies according to the original RoPE implementation Args: config ([`~transformers.PreTrainedConfig`]): The model configuration. Returns: Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE). """ base = config.rope_parameters["rope_theta"] dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads # The reference implementation computes RoPE frequencies INDEPENDENTLY # for each spatial dimension using the partitioned head_dim (head_dim // ndim), # so both x and y dimensions get identical frequency ranges. # This is different from splitting the global inv_freq between dimensions. spatial_dim = dim // 2 attention_factor = 1.0 # Unused in this type of RoPE inv_freq = 1.0 / (base ** (torch.arange(0, spatial_dim, 2, dtype=torch.float) / spatial_dim)) return inv_freq.to(device), attention_factor @torch.no_grad() @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope) def forward(self, x, position_ids): position_ids_expanded = position_ids.transpose(0, 1)[..., None].float() # (positions, 2, 1) inv_freq_expanded = ( self.inv_freq[None, None, :].float().expand(position_ids_expanded.shape[0], 2, -1).to(x.device) ) # (positions, 2, freq_dim) device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu" with maybe_autocast(device_type=device_type, enabled=False): # Force float32 freqs = (inv_freq_expanded.float() * position_ids_expanded.float()).transpose(1, 2).flatten(1) emb = torch.cat([freqs, freqs], dim=-1) cos = emb.cos() * self.attention_scaling sin = emb.sin() * self.attention_scaling return cos, sin class Kimi_K25VisionMLP(nn.Module): def __init__(self, dim: int, hidden_dim: int, hidden_act: str) -> None: super().__init__() self.fc1 = nn.Linear(dim, hidden_dim) self.act = ACT2FN[hidden_act] self.fc2 = nn.Linear(hidden_dim, dim) def forward(self, x) -> torch.Tensor: return self.fc2(self.act(self.fc1(x))) def rotate_half(x): """Rotates half the hidden dims of the input.""" x1 = x[..., : x.shape[-1] // 2] x2 = x[..., x.shape[-1] // 2 :] return torch.cat((-x2, x1), dim=-1) def apply_rotary_pos_emb_vision( q: torch.Tensor, k: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor ) -> tuple[torch.Tensor, torch.Tensor]: orig_q_dtype = q.dtype orig_k_dtype = k.dtype q, k = q.float(), k.float() cos, sin = cos.unsqueeze(-2).float(), sin.unsqueeze(-2).float() q_embed = (q * cos) + (rotate_half(q) * sin) k_embed = (k * cos) + (rotate_half(k) * sin) q_embed = q_embed.to(orig_q_dtype) k_embed = k_embed.to(orig_k_dtype) return q_embed, k_embed def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor: """ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch, num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim) """ batch, num_key_value_heads, slen, head_dim = hidden_states.shape if n_rep == 1: return hidden_states hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim) return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim) def eager_attention_forward( module: nn.Module, query: torch.Tensor, key: torch.Tensor, value: torch.Tensor, attention_mask: torch.Tensor | None, scaling: float, dropout: float = 0.0, **kwargs, ): key_states = repeat_kv(key, module.num_key_value_groups) value_states = repeat_kv(value, module.num_key_value_groups) attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling if attention_mask is not None: attn_weights = attn_weights + attention_mask attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype) attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training) attn_output = torch.matmul(attn_weights, value_states) attn_output = attn_output.transpose(1, 2).contiguous() return attn_output, attn_weights class Kimi_K25VisionAttention(nn.Module): def __init__(self, config: Kimi_K25VisionConfig) -> None: super().__init__() self.dim = config.hidden_size self.num_heads = config.num_attention_heads self.head_dim = self.dim // self.num_heads self.num_key_value_groups = 1 # needed for eager attention self.proj = nn.Linear(self.dim, self.dim) self.scaling = self.head_dim**-0.5 self.config = config self.attention_dropout = 0.0 self.is_causal = False self.q_proj = nn.Linear(self.dim, self.dim, bias=True) self.k_proj = nn.Linear(self.dim, self.dim, bias=True) self.v_proj = nn.Linear(self.dim, self.dim, bias=True) def forward( self, hidden_states: torch.Tensor, cu_seqlens: torch.Tensor, position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None, max_seqlen: int | None = None, **kwargs, ) -> torch.Tensor: seq_length = hidden_states.shape[0] query_states = self.q_proj(hidden_states).reshape(1, seq_length, -1, self.head_dim) key_states = self.k_proj(hidden_states).reshape(1, seq_length, -1, self.head_dim) value_states = self.v_proj(hidden_states).reshape(1, seq_length, -1, self.head_dim) cos, sin = position_embeddings query_states, key_states = apply_rotary_pos_emb_vision(query_states, key_states, cos, sin) query_states = query_states.transpose(2, 1) key_states = key_states.transpose(2, 1) value_states = value_states.transpose(2, 1) attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface( self.config._attn_implementation, eager_attention_forward ) if is_flash_attention_requested(self.config): # Flash Attention: Use cu_seqlens for variable length attention max_seqlen = get_max_seqlen(cu_seqlens, self.config, kwargs={"max_seqlen": max_seqlen}) attn_output, _ = attention_interface( self, query_states, key_states, value_states, attention_mask=None, scaling=self.scaling, dropout=0.0 if not self.training else self.attention_dropout, cu_seq_lens_q=cu_seqlens, cu_seq_lens_k=cu_seqlens, max_length_q=max_seqlen, max_length_k=max_seqlen, is_causal=False, **kwargs, ) else: # Other implementations: Process each chunk separately lengths = cu_seqlens[1:] - cu_seqlens[:-1] splits = [ torch.split(tensor, lengths.tolist(), dim=2) for tensor in (query_states, key_states, value_states) ] attn_outputs = [ attention_interface( self, q, k, v, attention_mask=None, scaling=self.scaling, dropout=0.0 if not self.training else self.attention_dropout, is_causal=False, **kwargs, )[0] for q, k, v in zip(*splits) ] attn_output = torch.cat(attn_outputs, dim=1) attn_output = attn_output.reshape(seq_length, -1).contiguous() attn_output = self.proj(attn_output) return attn_output class Kimi_K25VisionEncoderLayer(GradientCheckpointingLayer): def __init__(self, config) -> None: super().__init__() self.norm1 = nn.LayerNorm(config.hidden_size, eps=1e-5) self.norm2 = nn.LayerNorm(config.hidden_size, eps=1e-5) self.attn = Kimi_K25VisionAttention(config=config) self.mlp = Kimi_K25VisionMLP(config.hidden_size, config.intermediate_size, config.hidden_act) def forward( self, hidden_states: torch.Tensor, cu_seqlens: torch.Tensor, position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None, **kwargs, ) -> torch.Tensor: hidden_states = hidden_states + self.attn( self.norm1(hidden_states), cu_seqlens=cu_seqlens, position_embeddings=position_embeddings, **kwargs, ) hidden_states = hidden_states + self.mlp(self.norm2(hidden_states)) return hidden_states @auto_docstring class Kimi_K25PreTrainedModel(PreTrainedModel): config: Kimi_K25Config base_model_prefix = "model" input_modalities = ("image", "video", "text") supports_gradient_checkpointing = True _no_split_modules = ["Kimi_K25VisionEncoderLayer"] _skip_keys_device_placement = ["past_key_values"] _supports_flash_attn = True _supports_sdpa = True _can_compile_fullgraph = True _supports_attention_backend = True def _init_weights(self, module): super()._init_weights(module) if isinstance(module, Kimi_K25VisionPositionEmbeddings): buffer_value = module.compute_pos_embed() init.copy_(module.time_position_embeddings, buffer_value) init.trunc_normal_(module.position_embeddings, mean=0.0) def get_vision_temporal_merge_index( grid_thw: torch.Tensor, kernel_height: int, kernel_width: int, kwargs: dict | None = None ) -> torch.Tensor: """Gather index regrouping a flat patch sequence into `(total_merged, t, kernel_height * kernel_width)` for the temporal-pooling merger, or pop `"temporal_merge_index"` from `kwargs`. Row `m` collects the `t` frames × `kernel_height*kernel_width` source patches that pool into merged token `m`; the caller means over the frame axis. Precomputable, so the encoder avoids a per-clip `grid_thw.tolist()` loop. """ if kwargs is not None and (index := kwargs.pop("temporal_merge_index", None)) is not None: return index device = grid_thw.device running, rows = 0, [] for t, h, w in grid_thw.tolist(): t, h, w = int(t), int(h), int(w) new_h, new_w = h // kernel_height, w // kernel_width base = torch.arange(running, running + t * h * w, device=device).view( t, new_h, kernel_height, new_w, kernel_width ) # (t, new_h, new_w, kh, kw) → (new_h*new_w, t, kh*kw): frame axis kept for the caller's mean. base = base.permute(1, 3, 0, 2, 4).reshape(new_h * new_w, t, kernel_height * kernel_width) rows.append(base) running += t * h * w return torch.cat(rows, dim=0) @auto_docstring class Kimi_K25VisionModel(Kimi_K25PreTrainedModel): config: Kimi_K25VisionConfig input_modalities = ("image", "video") _can_record_outputs = { "hidden_states": Kimi_K25VisionEncoderLayer, "attentions": Kimi_K25VisionAttention, } def __init__(self, config: Kimi_K25VisionConfig): super().__init__(config) self.merge_kernel_size = config.merge_kernel_size self.patch_embed = Kimi_K25VisionPatchEmbed(config) self.rotary_emb = Kimi_K25VisionRotaryEmbedding(config) self.layers = nn.ModuleList([Kimi_K25VisionEncoderLayer(config) for _ in range(config.num_hidden_layers)]) self.final_layernorm = nn.LayerNorm(config.hidden_size, eps=1e-05) self.post_init() def temporal_patch_merger( self, hidden_states: torch.Tensor, grid_thw: torch.Tensor, ) -> torch.Tensor: r""" Merges temporal frames by spatially pooling patch embeddings across time, returning `(total_merged_patches, kernel_height * kernel_width, hidden_dim)`. Kept for backward compatibility: `forward` now pools with the export-friendly `get_vision_temporal_merge_index` gather instead of this Python per-clip loop. """ hidden_dim = hidden_states.size(-1) kernel_height, kernel_width = self.merge_kernel_size outputs = [] running_length = 0 for t, h, w in grid_thw.tolist(): seq = hidden_states[running_length : running_length + t * h * w] new_height, new_width = h // kernel_height, w // kernel_width reshaped_seq = seq.view(t, new_height, kernel_height, new_width, kernel_width, hidden_dim) reshaped_seq = reshaped_seq.transpose(2, 3).mean(dim=0) # temporal pooling padded_seq = reshaped_seq.reshape(new_height * new_width, kernel_height * kernel_width, -1) outputs.append(padded_seq) running_length += t * h * w return torch.cat(outputs, dim=0) @capture_outputs @auto_docstring def forward( self, pixel_values: torch.Tensor, grid_thw: torch.Tensor, **kwargs: Unpack[TransformersKwargs], ) -> torch.Tensor: r""" grid_thw (`torch.LongTensor` of shape `(num_images, 3)`, *optional*): The temporal, height and width of feature shape of each image in LLM. """ hidden_states = self.patch_embed(pixel_values, grid_thw=grid_thw, **kwargs) position_ids = get_vision_position_ids(grid_thw, spatial_merge_size=1, kwargs=kwargs) position_ids = position_ids.transpose(0, 1).flip(0) # (2, positions) position_embeddings = self.rotary_emb(hidden_states, position_ids) cu_seqlens, max_seqlen = get_vision_attention_seqlens( grid_thw, self.config, merge_temporal=True, kwargs=kwargs ) for block in self.layers: hidden_states = block( hidden_states, cu_seqlens=cu_seqlens, max_seqlen=max_seqlen, position_embeddings=position_embeddings, **kwargs, ) hidden_states = self.final_layernorm(hidden_states) merge_index = get_vision_temporal_merge_index(grid_thw, *self.merge_kernel_size, kwargs=kwargs) pooled_hidden_states = hidden_states[merge_index].mean(dim=1) return BaseModelOutputWithPooling( last_hidden_state=hidden_states, pooler_output=pooled_hidden_states, ) class Kimi_K25MultimodalProjection(nn.Module): def __init__(self, config): super().__init__() self.hidden_size = config.vision_config.hidden_size * ( config.vision_config.merge_kernel_size[0] * config.vision_config.merge_kernel_size[1] ) self.pre_norm = nn.LayerNorm(config.projection_hidden_size, eps=config.projection_layer_norm_eps) self.in_proj = nn.Linear(self.hidden_size, self.hidden_size) self.act = nn.GELU() self.out_proj = nn.Linear(self.hidden_size, config.text_config.hidden_size) def forward(self, hidden_states: torch.Tensor): batch_size = hidden_states.shape[0] hidden_states = self.pre_norm(hidden_states).view(batch_size, -1, self.hidden_size) hidden_states = self.in_proj(hidden_states) hidden_states = self.act(hidden_states) hidden_states = self.out_proj(hidden_states) return hidden_states @auto_docstring class Kimi_K25Model(Kimi_K25PreTrainedModel): def __init__(self, config: Kimi_K25Config): super().__init__(config) self.vision_tower = Kimi_K25VisionModel._from_config(config.vision_config) self.language_model = AutoModel.from_config(config.text_config) self.mm_projector = Kimi_K25MultimodalProjection(config) self.post_init() def get_input_embeddings(self): return self.language_model.get_input_embeddings() def set_input_embeddings(self, value): self.language_model.set_input_embeddings(value) @can_return_tuple @auto_docstring def get_image_features( self, pixel_values: torch.FloatTensor, image_grid_thw: torch.LongTensor | None = None, **kwargs: Unpack[TransformersKwargs], ) -> tuple | BaseModelOutputWithPooling: vision_outputs = self.vision_tower(pixel_values, grid_thw=image_grid_thw, **kwargs) image_embeds = self.mm_projector(vision_outputs.pooler_output).squeeze(1) merge_kernel_size = self.vision_tower.merge_kernel_size[0] * self.vision_tower.merge_kernel_size[1] split_sizes = (image_grid_thw.prod(-1) // merge_kernel_size).tolist() vision_outputs.pooler_output = torch.split(image_embeds, split_sizes) return vision_outputs @auto_docstring def get_video_features( self, pixel_values_videos: torch.FloatTensor, video_grid_thw: torch.LongTensor | None = None, **kwargs: Unpack[TransformersKwargs], ) -> tuple | BaseModelOutputWithPooling: r""" pixel_values_videos (`torch.FloatTensor` of shape `(batch_size, num_channels, image_size, image_size)`): The tensors corresponding to the input videos. """ return self.get_image_features(pixel_values_videos, video_grid_thw, **kwargs) def get_placeholder_mask( self, input_ids: torch.LongTensor, inputs_embeds: torch.FloatTensor, image_features: torch.FloatTensor | None = None, video_features: torch.FloatTensor | None = None, ): """ Obtains multimodal placeholder mask from `input_ids` or `inputs_embeds`, and checks that the placeholder token count is equal to the length of multimodal features. If the lengths are different, an error is raised. """ if input_ids is None: special_image_mask = inputs_embeds == self.get_input_embeddings()( torch.full((), self.config.image_token_id, dtype=torch.long, device=inputs_embeds.device) ) special_image_mask = special_image_mask.all(-1) special_video_mask = inputs_embeds == self.get_input_embeddings()( torch.full((), self.config.video_token_id, dtype=torch.long, device=inputs_embeds.device) ) special_video_mask = special_video_mask.all(-1) else: special_image_mask = input_ids == self.config.image_token_id special_video_mask = input_ids == self.config.video_token_id n_image_tokens = special_image_mask.sum() special_image_mask = special_image_mask.unsqueeze(-1).to(inputs_embeds.device) if image_features is not None: torch_compilable_check( n_image_tokens * inputs_embeds.shape[-1] == image_features.numel(), f"Image features and image tokens do not match, tokens: {n_image_tokens}, features: {image_features.shape[0]}", ) n_video_tokens = special_video_mask.sum() special_video_mask = special_video_mask.unsqueeze(-1).to(inputs_embeds.device) if video_features is not None: torch_compilable_check( n_video_tokens * inputs_embeds.shape[-1] == video_features.numel(), f"Video features and video tokens do not match, tokens: {n_video_tokens}, features: {video_features.shape[0]}", ) return special_image_mask, special_video_mask @can_return_tuple @auto_docstring def forward( self, input_ids: torch.LongTensor | None = None, attention_mask: torch.Tensor | None = None, position_ids: torch.LongTensor | None = None, past_key_values: Cache | None = None, inputs_embeds: torch.FloatTensor | None = None, use_cache: bool | None = None, pixel_values: torch.Tensor | None = None, image_grid_thw: torch.LongTensor | None = None, pixel_values_videos: torch.Tensor | None = None, video_grid_thw: torch.LongTensor | None = None, **kwargs: Unpack[TransformersKwargs], ) -> tuple | Kimi_K25ModelOutputWithPast: if inputs_embeds is None: multimodal_mask = (input_ids == self.config.image_token_id) | (input_ids == self.config.video_token_id) llm_input_ids = input_ids.clone() llm_input_ids[multimodal_mask] = 0 inputs_embeds = self.get_input_embeddings()(llm_input_ids) if pixel_values is not None: image_embeds = self.get_image_features(pixel_values, image_grid_thw).pooler_output image_embeds = torch.cat(image_embeds, dim=0).to(device=inputs_embeds.device, dtype=inputs_embeds.dtype) image_mask, _ = self.get_placeholder_mask( input_ids, inputs_embeds=inputs_embeds, image_features=image_embeds ) inputs_embeds = inputs_embeds.masked_scatter(image_mask, image_embeds) if pixel_values_videos is not None: video_embeds = self.get_video_features(pixel_values_videos, video_grid_thw).pooler_output video_embeds = torch.cat(video_embeds, dim=0).to(device=inputs_embeds.device, dtype=inputs_embeds.dtype) _, video_mask = self.get_placeholder_mask( input_ids, inputs_embeds=inputs_embeds, video_features=video_embeds ) inputs_embeds = inputs_embeds.masked_scatter(video_mask, video_embeds) outputs = self.language_model( input_ids=None, position_ids=position_ids, attention_mask=attention_mask, past_key_values=past_key_values, inputs_embeds=inputs_embeds, use_cache=use_cache, **kwargs, ) return Kimi_K25ModelOutputWithPast( last_hidden_state=outputs.last_hidden_state, past_key_values=outputs.past_key_values, hidden_states=outputs.hidden_states, attentions=outputs.attentions, ) @auto_docstring class Kimi_K25ForConditionalGeneration(Kimi_K25PreTrainedModel, GenerationMixin): _tied_weights_keys = {"lm_head.weight": "model.language_model.embed_tokens.weight"} # Reference: fix gemma3 grad acc #37208 accepts_loss_kwargs = False def __init__(self, config): super().__init__(config) self.model = Kimi_K25Model(config) self.lm_head = nn.Linear(config.text_config.hidden_size, config.text_config.vocab_size, bias=False) self.post_init() @auto_docstring def get_video_features( self, pixel_values_videos: torch.FloatTensor, video_grid_thw: torch.LongTensor | None = None, **kwargs: Unpack[TransformersKwargs], ) -> tuple | BaseModelOutputWithPooling: r""" pixel_values_videos (`torch.FloatTensor` of shape `(batch_size, num_channels, image_size, image_size)`): The tensors corresponding to the input videos. """ return self.model.get_video_features(pixel_values_videos, video_grid_thw, **kwargs) @auto_docstring def get_image_features( self, pixel_values: torch.FloatTensor, image_grid_thw: torch.LongTensor | None = None, **kwargs: Unpack[TransformersKwargs], ) -> tuple | BaseModelOutputWithPooling: r""" pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, image_size, image_size)`): The tensors corresponding to the input images. """ return self.model.get_image_features(pixel_values, image_grid_thw, **kwargs) @can_return_tuple @auto_docstring def forward( self, input_ids: torch.LongTensor | None = None, attention_mask: torch.Tensor | None = None, position_ids: torch.LongTensor | None = None, past_key_values: Cache | None = None, inputs_embeds: torch.FloatTensor | None = None, labels: torch.LongTensor | None = None, use_cache: bool | None = None, pixel_values: torch.Tensor | None = None, image_grid_thw: torch.LongTensor | None = None, pixel_values_videos: torch.Tensor | None = None, video_grid_thw: torch.LongTensor | None = None, logits_to_keep: int | torch.Tensor = 0, **kwargs: Unpack[TransformersKwargs], ) -> tuple | Kimi_K25CausalLMOutputWithPast: r""" Example: ```python >>> from transformers import AutoProcessor, Kimi_K25ForConditionalGeneration >>> model = Kimi_K25ForConditionalGeneration.from_pretrained("moonshotai/Kimi-K2.6") >>> processor = AutoProcessor.from_pretrained("moonshotai/Kimi-K2.6") >>> messages = [ { "role": "user", "content": [ { "type": "image", "image": "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg", }, {"type": "text", "text": "Describe the image."}, ], } ] >>> inputs = processor.apply_chat_template( messages, tokenize=True, add_generation_prompt=True, return_dict=True, return_tensors="pt", ) >>> # Generate >>> generated_ids = model.generate(**inputs, max_new_tokens=1024) >>> generated_ids_trimmed = [out_ids[len(in_ids) :] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)] >>> output_text = processor.batch_decode(generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0] >>> print(output_text) ``` """ outputs: Kimi_K25ModelOutputWithPast = self.model( input_ids=input_ids, pixel_values=pixel_values, image_grid_thw=image_grid_thw, pixel_values_videos=pixel_values_videos, video_grid_thw=video_grid_thw, position_ids=position_ids, attention_mask=attention_mask, past_key_values=past_key_values, inputs_embeds=inputs_embeds, use_cache=use_cache, **kwargs, ) hidden_states = outputs.last_hidden_state # Only compute necessary logits, and do not upcast them to float if we are not computing the loss slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep logits = self.lm_head(hidden_states[:, slice_indices, :]) loss = None if labels is not None: loss = self.loss_function( logits=logits, labels=labels, vocab_size=self.config.text_config.vocab_size, **kwargs ) return Kimi_K25CausalLMOutputWithPast( loss=loss, logits=logits, past_key_values=outputs.past_key_values, hidden_states=outputs.hidden_states, attentions=outputs.attentions, ) __all__ = ["Kimi_K25ForConditionalGeneration", "Kimi_K25Model", "Kimi_K25PreTrainedModel", "Kimi_K25VisionModel"]