Inkling-2-Mini-Uncensored-V18 / modeling_inkling2_loop_v18.py
win10's picture
Release four-epoch V18 grounded memory checkpoint and model card
cc31783 verified
Raw History Blame Contribute Delete
92.6 kB
# 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 copy import math from collections.abc import Callable from dataclasses import dataclass import torch import torch.nn as nn import torch.nn.functional as F from transformers import initialization as init from transformers.activations import ACT2FN from transformers.conversion_mapping import ( USER_REGISTERED_MAPPINGS, get_checkpoint_conversion_mapping, register_checkpoint_conversion_mapping, ) from transformers.cache_utils import Cache, DynamicCache from transformers.generation import GenerationMixin from transformers.integrations import ( use_experts_implementation, use_kernel_forward_from_hub, use_kernel_func_from_hub_with_fallback, use_kernelized_func, ) from transformers.integrations.accelerate import force_accelerate_hooks from transformers.masking_utils import ( create_causal_mask, create_recurrent_attention_mask, create_sliding_window_causal_mask, find_first_full_attention_index, ) from transformers.modeling_layers import GradientCheckpointingLayer from transformers.modeling_outputs import ( BaseModelOutputWithPooling, MoeModelOutputWithPast, MultimodalBaseModelOutputWithPast, MultimodalCausalLMOutputWithPast, ) from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel, slice_logits_to_keep from transformers.processing_utils import Unpack from transformers.utils import TransformersKwargs, auto_docstring, can_return_tuple, logging, torch_compilable_check from transformers.utils.deprecation import deprecate_kwarg from transformers.utils.generic import merge_with_config_defaults from transformers.utils.output_capturing import ( OutputRecorder, _active_collector, capture_outputs, resolve_hidden_states_indices, selected_hidden_states, ) from transformers.models.auto import AutoModel from .configuration_inkling2_loop_v18 import Inkling2LoopConfig, Inkling2LoopTextConfig from .memory_v18 import Inkling2V18MemoryComponents from .runtime_v18 import open_checkpoint_memory # Custom models opt in to loading the original packed Inkling weight layout. # Separate identifiers preserve upstream conversion behavior for native Inkling models. for _v18, _native in ( (Inkling2LoopConfig.model_type, "inkling2_loop"), (Inkling2LoopTextConfig.model_type, "inkling2_loop_text"), ): if _v18 not in USER_REGISTERED_MAPPINGS: _conversions = get_checkpoint_conversion_mapping(_native) if not _conversions: raise ImportError("V18 needs a Transformers release with native Inkling 2 Loop checkpoint converters") register_checkpoint_conversion_mapping(_v18, _conversions) logger = logging.get_logger(__name__) class Inkling2LoopUnweightedRMSNorm(nn.Module): def __init__(self, eps: float = 1.0e-6): super().__init__() self.eps = eps def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: input_dtype = hidden_states.dtype hidden_states = hidden_states.float() hidden_states = hidden_states * torch.rsqrt(hidden_states.square().mean(-1, keepdim=True) + self.eps) return hidden_states.to(input_dtype) class Inkling2LoopMessageGate(nn.Module): """Mixes hidden states and message as `(1 - forget_gate) * hidden_states + message_gate * message`""" def __init__(self, config: Inkling2LoopTextConfig): super().__init__() self.norm = Inkling2LoopUnweightedRMSNorm(eps=config.rms_norm_eps) self.down_proj = nn.Linear(2 * config.hidden_size, config.loop_gate_rank, bias=False) self.forget_gate_proj = nn.Linear(config.loop_gate_rank, config.hidden_size, bias=False, dtype=torch.float32) self.message_gate_proj = nn.Linear(config.loop_gate_rank, config.hidden_size, bias=False, dtype=torch.float32) def forward(self, hidden_states: torch.Tensor, message: torch.Tensor) -> torch.Tensor: hidden_states, message = hidden_states.float(), message.float() gate_hidden_states = torch.cat([self.norm(hidden_states), self.norm(message)], dim=-1) gate_hidden_states = self.down_proj(gate_hidden_states.to(self.down_proj.weight.dtype)).float() forget_gate = torch.tanh(self.forget_gate_proj(gate_hidden_states)) message_gate = torch.tanh(self.message_gate_proj(gate_hidden_states)) return (1 - forget_gate) * hidden_states + message_gate * message 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, position_bias: torch.Tensor | None = None, sinks: torch.Tensor | None = None, **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 position_bias is not None: attn_weights = attn_weights + position_bias if attention_mask is not None: attn_weights = attn_weights + attention_mask if sinks is not None: # The sink is one extra logit per query with a zero value: it only absorbs probability mass combined_logits = torch.cat([attn_weights, sinks], dim=-1).float() attn_weights = F.softmax(combined_logits, dim=-1)[..., :-1].to(query.dtype) else: attn_weights = F.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 Inkling2LoopMessageAttentionResidual(nn.Module): """Retrieves messages from the block states of the previous block using learned queries.""" def __init__(self, config: Inkling2LoopTextConfig): super().__init__() # one query per message (query, key, value and mlp) for each loop layer shape = (config.loop_layer_index_end - config.loop_layer_index_start, 4, config.hidden_size) self.query = nn.Parameter(torch.zeros(*shape, dtype=torch.float32)) self.norm = Inkling2LoopUnweightedRMSNorm() self.config = config self.num_key_value_groups = 1 self.is_causal = False def forward( self, block_states: torch.Tensor, partial_block_states: torch.Tensor, loop_layer_idx: int ) -> torch.Tensor: stacked_states = torch.cat([block_states, partial_block_states.unsqueeze(-2)], dim=-2).float() stacked_states = self.norm(stacked_states) hidden_size = stacked_states.shape[-1] query_states = self.query[loop_layer_idx].float() query_states = query_states.expand(*stacked_states.shape[:-2], -1, -1) attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface( self.config._attn_implementation, eager_attention_forward ) attn_output, _ = attention_interface( self, query_states, stacked_states, stacked_states, None, scaling=hidden_size**-0.5 ) return attn_output.transpose(1, 2) class Inkling2LoopL2Clip(nn.Module): """Scales each head vector down to `threshold` when its L2 norm is larger; shorter vectors are unchanged.""" def __init__(self, threshold: float): super().__init__() self.threshold = threshold def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: input_dtype = hidden_states.dtype hidden_states = hidden_states.float() norm = torch.linalg.vector_norm(hidden_states, dim=-1, keepdim=True) return (hidden_states * (self.threshold / (norm + 1e-6)).clamp(max=1.0)).to(input_dtype) class Inkling2LoopScaledL2Clip(nn.Module): """`Inkling2LoopL2Clip` applied after a learned scale.""" def __init__(self, num_heads: int, head_dim: int, threshold: float): super().__init__() self.threshold = threshold self.scale = nn.Parameter(torch.ones(num_heads, head_dim)) def forward(self, hidden_states: torch.Tensor, position_ids: torch.Tensor | None = None) -> torch.Tensor: input_dtype = hidden_states.dtype hidden_states = hidden_states.float() * self.scale.float() norm = torch.linalg.vector_norm(hidden_states, dim=-1, keepdim=True) return (hidden_states * (self.threshold / (norm + 1e-6)).clamp(max=1.0)).to(input_dtype) class Inkling2LoopLogScale(nn.Module): """ Scales the per-head states by `tau = 1 + log_scaling_alpha * log(max((position + 1) / log_scaling_n_floor, 1))`. """ def __init__(self, config: Inkling2LoopTextConfig): super().__init__() self.log_scaling_alpha = config.log_scaling_alpha self.log_scaling_n_floor = config.log_scaling_n_floor def forward(self, hidden_states: torch.Tensor, position_ids: torch.Tensor) -> torch.Tensor: input_dtype = hidden_states.dtype scale = 1.0 + self.log_scaling_alpha * torch.log( ((position_ids + 1).float() / self.log_scaling_n_floor).clamp(min=1.0) ) return (hidden_states.float() * scale[..., None, None]).to(input_dtype) class Inkling2LoopLogScaledL2Clip(nn.Module): """`Inkling2LoopScaledL2Clip` followed by `Inkling2LoopLogScale`.""" # trf-ignore: TRF029 (num_heads and head_dim depend on the attention layer type) def __init__(self, config: Inkling2LoopTextConfig, num_heads: int, head_dim: int, threshold: float): super().__init__() self.scale = nn.Parameter(torch.ones(num_heads, head_dim)) self.l2_clip = Inkling2LoopL2Clip(threshold) self.log_scale = Inkling2LoopLogScale(config) def forward(self, hidden_states: torch.Tensor, position_ids: torch.Tensor) -> torch.Tensor: input_dtype = hidden_states.dtype hidden_states = self.l2_clip(hidden_states.float() * self.scale.float()).to(input_dtype) return self.log_scale(hidden_states, position_ids) class Inkling2LoopRelativePositionBias(nn.Module): """ Hidden-states conditioned relative position bias. `linear` and `norm` give each token per-head `relative_states` that mix the trained bank of bias-vs-distance profiles in `proj` into one bias value per backward distance. The bias is zero outside `0 <= distance < rel_extent`. With `log_scaling`, the relative states are also scaled by `Inkling2LoopLogScale`. """ # trf-ignore: TRF029 (num_heads depends on the attention layer type) def __init__(self, config: Inkling2LoopTextConfig, num_heads: int, rel_extent: int, log_scaling: bool): super().__init__() self.num_heads = num_heads self.rel_extent = rel_extent self.linear = nn.Linear(config.hidden_size, num_heads * config.d_rel, bias=False) self.norm = ( Inkling2LoopLogScaledL2Clip(config, num_heads, config.d_rel, config.rel_l2_clip_threshold) if log_scaling else Inkling2LoopScaledL2Clip(num_heads, config.d_rel, config.rel_l2_clip_threshold) ) self.proj = nn.Parameter(torch.empty(config.d_rel, rel_extent)) def forward( self, hidden_states: torch.Tensor, relative_distance: torch.Tensor, position_ids: torch.Tensor ) -> torch.Tensor: relative_states = self.linear(hidden_states).view(*hidden_states.shape[:-1], self.num_heads, -1) relative_states = self.norm(relative_states, position_ids) # relative_states: [batch, q_len, num_heads, d_rel] -> bias: [batch, num_heads, q_len, kv_len] rel_logits = (relative_states @ self.proj).transpose(1, 2) gather_index = relative_distance.clamp(0, self.rel_extent - 1).expand(*rel_logits.shape[:2], -1, -1) position_bias = rel_logits.gather(-1, gather_index) return position_bias.masked_fill((relative_distance < 0) | (relative_distance >= self.rel_extent), 0.0) def apply_mask_to_padding_states(hidden_states, attention_mask): """ Tunes out the hidden states for padding tokens, see https://github.com/state-spaces/mamba/issues/66 """ # NOTE: attention mask is a 2D boolean tensor if attention_mask is not None: dtype = hidden_states.dtype hidden_states = (hidden_states * attention_mask[:, :, None]).to(dtype) return hidden_states @use_kernel_func_from_hub_with_fallback("causal_conv1d_update", "causal_conv1d") def causal_conv1d_update( hidden_states: torch.Tensor, conv_state: torch.Tensor, weight: nn.Parameter, bias: nn.Parameter | None = None, activation: str | None = None, ): _, hidden_size, seq_len = hidden_states.shape state_len = conv_state.shape[-1] hidden_states_new = torch.cat([conv_state, hidden_states], dim=-1).to(weight.dtype) conv_state.copy_(hidden_states_new[:, :, -state_len:]) out = F.conv1d(hidden_states_new, weight.unsqueeze(1), bias, padding=0, groups=hidden_size) out = out[:, :, -seq_len:] if activation is not None: out = ACT2FN[activation](out) return out.to(hidden_states.dtype) @use_kernel_func_from_hub_with_fallback("causal_conv1d_fn", "causal_conv1d") def causal_conv1d_fn( hidden_states: torch.Tensor, weight: nn.Parameter, bias: nn.Parameter | None = None, activation: str | None = None, **kwargs, ): _, hidden_size, seq_len = hidden_states.shape padding = weight.shape[-1] - 1 out = F.conv1d( hidden_states.to(weight.dtype), weight=weight.unsqueeze(1), bias=bias, padding=padding, groups=hidden_size, )[:, :, :seq_len] if activation is not None: out = ACT2FN[activation](out) return out.to(hidden_states.dtype) @use_kernelized_func([causal_conv1d_update, causal_conv1d_fn]) class Inkling2LoopShortConvolution(nn.Module): def __init__(self, hidden_size: int, conv_kernel_size: int, layer_idx: int, conv_idx: int): super().__init__() self.layer_idx = layer_idx self.conv_idx = conv_idx self.conv_kernel_size = conv_kernel_size self.conv1d = nn.Conv1d( in_channels=hidden_size, out_channels=hidden_size, kernel_size=conv_kernel_size, groups=hidden_size, padding=conv_kernel_size - 1, bias=False, ) @force_accelerate_hooks("conv1d") @deprecate_kwarg("past_key_values", "5.40.0", new_name="cache") def forward( self, hidden_states: torch.Tensor, dynamic_input: torch.Tensor | None = None, cache: Cache | None = None, conv_mask: torch.Tensor | None = None, cache_offset: int = 0, **kwargs: Unpack[TransformersKwargs], ): r""" dynamic_input (`torch.Tensor`, *optional*): Ignored, accepted for interface compatibility with `Inkling2LoopDynamicShortConvolution`. cache_offset (`int`, *optional*, defaults to 0): Offset added to `layer_idx` to get the cache layer holding the state of this call. """ cache_layer_idx = self.layer_idx + cache_offset input_dtype = hidden_states.dtype hidden_states = hidden_states.float() residual = hidden_states hidden_states = apply_mask_to_padding_states(hidden_states, conv_mask) seq_len = hidden_states.shape[1] hidden_states = hidden_states.transpose(1, 2) conv_state = None if cache is None else cache.get_conv_state(cache_layer_idx, state_idx=self.conv_idx) if conv_state is not None and seq_len == 1 and not cache.is_recording_past(cache_layer_idx): hidden_states = causal_conv1d_update( hidden_states, conv_state, self.conv1d.weight.squeeze(1), self.conv1d.bias ) else: if cache is not None: hidden_states = cache.update_conv_state( hidden_states, cache_layer_idx, state_idx=self.conv_idx, conv_kernel_size=self.conv_kernel_size ) hidden_states = causal_conv1d_fn( hidden_states, self.conv1d.weight.squeeze(1), self.conv1d.bias, seq_idx=kwargs.get("seq_idx") ) if cache is not None: hidden_states = hidden_states[:, :, -seq_len:] hidden_states = hidden_states.transpose(1, 2) # Different from Inkling which has no output scale hidden_states = (hidden_states + residual) / math.sqrt(self.conv_kernel_size + 1) return hidden_states.to(dtype=input_dtype) class Inkling2LoopDynamicShortConvolution(nn.Module): """ Short causal convolution whose taps are the sum of static per-channel weights and per-token weights projected from `dynamic_input`, shared within each key/value head. Used for keys and values in the full-attention layers. """ def __init__( self, hidden_size: int, input_size: int, num_heads: int, conv_kernel_size: int, layer_idx: int, conv_idx: int ): super().__init__() self.layer_idx = layer_idx self.conv_idx = conv_idx self.conv_kernel_size = conv_kernel_size self.num_heads = num_heads # tap index is the backward distance: `static_weight[0]` weights the current token self.static_weight = nn.Parameter(torch.zeros(conv_kernel_size, hidden_size)) self.weight_proj = nn.Linear(input_size, num_heads * conv_kernel_size, bias=False) @deprecate_kwarg("past_key_values", "5.40.0", new_name="cache") def forward( self, hidden_states: torch.Tensor, dynamic_input: torch.Tensor, cache: Cache | None = None, conv_mask: torch.Tensor | None = None, cache_offset: int = 0, **kwargs: Unpack[TransformersKwargs], ): r""" cache_offset (`int`, *optional*, defaults to 0): Offset added to `layer_idx` to get the cache layer holding the state of this call. """ input_dtype = hidden_states.dtype batch_size, seq_len, hidden_size = hidden_states.shape dynamic_weights = self.weight_proj(dynamic_input).float() dynamic_weights = dynamic_weights.view(batch_size, seq_len, self.num_heads, 1, self.conv_kernel_size) weights = self.static_weight.float().T.view(self.num_heads, -1, self.conv_kernel_size) + dynamic_weights hidden_states = hidden_states.float() residual = hidden_states context = apply_mask_to_padding_states(hidden_states, conv_mask).transpose(1, 2) if cache is not None: context = cache.update_conv_state( context, self.layer_idx + cache_offset, state_idx=self.conv_idx, conv_kernel_size=self.conv_kernel_size, ) context = F.pad(context, (self.conv_kernel_size - 1, 0))[..., -(seq_len + self.conv_kernel_size - 1) :] # windows[..., lag] is the token `lag` steps back windows = context.unfold(-1, self.conv_kernel_size, 1).flip(-1).transpose(1, 2) windows = windows.reshape(batch_size, seq_len, self.num_heads, -1, self.conv_kernel_size) if (seq_idx := kwargs.get("seq_idx")) is not None: seq_idx = seq_idx.to(windows.device) context_seq_idx = torch.cat([seq_idx[:, :1].expand(-1, self.conv_kernel_size - 1), seq_idx], dim=1) window_seq_idx = context_seq_idx.unfold(-1, self.conv_kernel_size, 1).flip(-1) windows = windows * (window_seq_idx == seq_idx[..., None])[:, :, None, None, :] hidden_states = (windows * weights).sum(-1).reshape(batch_size, seq_len, hidden_size) hidden_states = (hidden_states + residual) / math.sqrt(2 * self.conv_kernel_size + 1) return hidden_states.to(input_dtype) class Inkling2LoopQueryProjection(nn.Module): """Returns query states of the attention layers.""" # trf-ignore: TRF029 (num_heads and head_dim depend on the attention layer type) def __init__(self, config: Inkling2LoopTextConfig, num_heads: int, head_dim: int, log_scaling: bool): super().__init__() self.head_dim = head_dim self.linear = nn.Linear(config.hidden_size, num_heads * head_dim, bias=False) self.norm = ( Inkling2LoopLogScaledL2Clip(config, num_heads, head_dim, config.qk_l2_clip_threshold) if log_scaling else Inkling2LoopScaledL2Clip(num_heads, head_dim, config.qk_l2_clip_threshold) ) def forward(self, hidden_states: torch.Tensor, position_ids: torch.Tensor) -> torch.Tensor: states = self.linear(hidden_states) states = states.view(*states.shape[:-1], -1, self.head_dim) return self.norm(states, position_ids).transpose(1, 2) class Inkling2LoopKeyValueProjection(nn.Module): """Returns key or value states of the attention layers.""" # trf-ignore: TRF029 (num_heads and head_dim depend on the attention layer type) def __init__( self, config: Inkling2LoopTextConfig, num_heads: int, head_dim: int, layer_idx: int, conv_idx: int, is_key: bool, dynamic: bool = False, ): super().__init__() self.head_dim = head_dim self.linear = nn.Linear(config.hidden_size, num_heads * head_dim, bias=False) self.sconv = ( Inkling2LoopDynamicShortConvolution( num_heads * head_dim, config.hidden_size, num_heads, config.sconv_kernel_size, layer_idx, conv_idx=conv_idx, ) if dynamic else Inkling2LoopShortConvolution( num_heads * head_dim, config.sconv_kernel_size, layer_idx, conv_idx=conv_idx ).to(dtype=torch.float32) ) self.norm = ( Inkling2LoopL2Clip(config.qk_l2_clip_threshold) if is_key else Inkling2LoopUnweightedRMSNorm(eps=config.rms_norm_eps) ) def forward( self, hidden_states: torch.Tensor, cache: Cache | None = None, conv_mask: torch.Tensor | None = None, cache_offset: int = 0, **kwargs: Unpack[TransformersKwargs], ) -> torch.Tensor: states = self.linear(hidden_states) states = self.sconv( states, hidden_states, cache=cache, conv_mask=conv_mask, cache_offset=cache_offset, **kwargs ) states = states.view(*states.shape[:-1], -1, self.head_dim) return self.norm(states).transpose(1, 2) class Inkling2LoopGatedOutputProjection(nn.Module): """Output projection of the attention layers, applied after gating the attention output with a sigmoid of the layer input.""" # trf-ignore: TRF029 (num_heads and head_dim depend on the attention layer type) def __init__(self, config: Inkling2LoopTextConfig, num_heads: int, head_dim: int): super().__init__() self.gate_proj = nn.Linear(config.hidden_size, num_heads * head_dim, bias=False) self.linear = nn.Linear(num_heads * head_dim, config.hidden_size, bias=False) def forward(self, attn_output: torch.Tensor, hidden_states: torch.Tensor) -> torch.Tensor: gate = torch.sigmoid(self.gate_proj(hidden_states).float()) attn_output = (attn_output.float() * gate).to(attn_output.dtype) return self.linear(attn_output) class Inkling2LoopSlidingAttention(nn.Module): def __init__(self, config: Inkling2LoopTextConfig, layer_idx: int): super().__init__() self.config = config self.layer_idx = layer_idx self.is_sliding = config.layer_types[self.layer_idx] == "hybrid_sliding" self.head_dim = config.swa_head_dim if self.is_sliding else config.head_dim self.num_heads = config.swa_num_attention_heads if self.is_sliding else config.num_attention_heads self.num_key_value_heads = config.swa_num_key_value_heads if self.is_sliding else config.num_key_value_heads self.num_key_value_groups = self.num_heads // self.num_key_value_heads self.sliding_window = config.sliding_window_size if self.is_sliding else None self.rel_extent = config.sliding_window_size if self.is_sliding else config.rel_extent self.scaling = self.head_dim**-0.5 self.attention_dropout = config.attention_dropout self.is_causal = True self.q_proj = Inkling2LoopQueryProjection(config, self.num_heads, self.head_dim, log_scaling=False) self.k_proj = Inkling2LoopKeyValueProjection( config, self.num_key_value_heads, self.head_dim, layer_idx, conv_idx=0, is_key=True ) self.v_proj = Inkling2LoopKeyValueProjection( config, self.num_key_value_heads, self.head_dim, layer_idx, conv_idx=1, is_key=False ) self.o_proj = Inkling2LoopGatedOutputProjection(config, self.num_heads, self.head_dim) self.sink_proj = nn.Linear(config.hidden_size, self.num_heads, bias=False) self.relative_position_bias = Inkling2LoopRelativePositionBias( config, self.num_heads, self.rel_extent, log_scaling=False ) @deprecate_kwarg("past_key_values", "5.40.0", new_name="cache") def forward( self, hidden_states: torch.Tensor, attention_mask: torch.Tensor | None, relative_distance: torch.Tensor, conv_mask: torch.Tensor | None = None, cache: Cache | None = None, key_hidden_states: torch.Tensor | None = None, value_hidden_states: torch.Tensor | None = None, cache_offset: int = 0, **kwargs: Unpack[TransformersKwargs], ) -> tuple[torch.Tensor, torch.Tensor | None]: r""" relative_distance (`torch.Tensor` of shape `(query_length, key_length)`): Distance from each query position to each key position, see `get_relative_distance`. key_hidden_states (`torch.Tensor`, *optional*): Input of the key projection, `hidden_states` by default. value_hidden_states (`torch.Tensor`, *optional*): Input of the value projection, `hidden_states` by default. cache_offset (`int`, *optional*, defaults to 0): Offset added to `layer_idx` to get the cache layer holding the keys, values and convolution states of this call. """ cache_layer_idx = self.layer_idx + cache_offset key_hidden_states = hidden_states if key_hidden_states is None else key_hidden_states value_hidden_states = hidden_states if value_hidden_states is None else value_hidden_states input_shape = hidden_states.shape[:-1] query_states = self.q_proj(hidden_states, kwargs["position_ids"]) key_states = self.k_proj( key_hidden_states, cache=cache, conv_mask=conv_mask, cache_offset=cache_offset, **kwargs ) value_states = self.v_proj( value_hidden_states, cache=cache, conv_mask=conv_mask, cache_offset=cache_offset, **kwargs ) if cache is not None: key_states, value_states = cache.update(key_states, value_states, cache_layer_idx, kwargs=kwargs) attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface( self.config._attn_implementation, eager_attention_forward ) position_bias = self.relative_position_bias(hidden_states, relative_distance, kwargs["position_ids"]) sinks = self.sink_proj(hidden_states).transpose(1, 2).unsqueeze(-1) attn_output, attn_weights = attention_interface( self, query_states, key_states, value_states, attention_mask, dropout=0.0 if not self.training else self.attention_dropout, scaling=self.scaling, sliding_window=self.sliding_window, position_bias=position_bias, sinks=sinks, **kwargs, ) attn_output = attn_output.reshape(*input_shape, -1).contiguous() attn_output = self.o_proj(attn_output, hidden_states) return attn_output, attn_weights class Inkling2LoopFullAttention(nn.Module): def __init__(self, config: Inkling2LoopTextConfig, layer_idx: int): super().__init__() self.config = config self.layer_idx = layer_idx self.is_sliding = config.layer_types[self.layer_idx] == "hybrid_sliding" self.head_dim = config.swa_head_dim if self.is_sliding else config.head_dim self.num_heads = config.swa_num_attention_heads if self.is_sliding else config.num_attention_heads self.num_key_value_heads = config.swa_num_key_value_heads if self.is_sliding else config.num_key_value_heads self.num_key_value_groups = self.num_heads // self.num_key_value_heads self.sliding_window = config.sliding_window_size if self.is_sliding else None self.rel_extent = config.sliding_window_size if self.is_sliding else config.rel_extent self.scaling = self.head_dim**-0.5 self.attention_dropout = config.attention_dropout self.is_causal = True self.q_proj = Inkling2LoopQueryProjection(config, self.num_heads, self.head_dim, log_scaling=True) self.k_proj = Inkling2LoopKeyValueProjection( config, self.num_key_value_heads, self.head_dim, layer_idx, conv_idx=0, is_key=True, dynamic=True ) self.v_proj = Inkling2LoopKeyValueProjection( config, self.num_key_value_heads, self.head_dim, layer_idx, conv_idx=1, is_key=False, dynamic=True ) self.o_proj = Inkling2LoopGatedOutputProjection(config, self.num_heads, self.head_dim) self.sink_proj = nn.Linear(config.hidden_size, self.num_heads, bias=False) self.relative_position_bias = Inkling2LoopRelativePositionBias( config, self.num_heads, self.rel_extent, log_scaling=True ) @deprecate_kwarg("past_key_values", "5.40.0", new_name="cache") def forward( self, hidden_states: torch.Tensor, key_hidden_states: torch.Tensor, value_hidden_states: torch.Tensor, attention_mask: torch.Tensor | None, relative_distance: torch.Tensor, conv_mask: torch.Tensor | None = None, cache: Cache | None = None, cache_offset: int = 0, **kwargs: Unpack[TransformersKwargs], ) -> tuple[torch.Tensor, torch.Tensor | None]: r""" relative_distance (`torch.Tensor` of shape `(query_length, key_length)`): Distance from each query position to each key position, see `get_relative_distance`. key_hidden_states (`torch.Tensor`): Input of the key projection and of the key convolution weights. value_hidden_states (`torch.Tensor`): Input of the value projection and of the value convolution weights. cache_offset (`int`, *optional*, defaults to 0): Offset added to `layer_idx` to get the cache layer holding the keys, values and convolution states of this call. """ cache_layer_idx = self.layer_idx + cache_offset input_shape = hidden_states.shape[:-1] query_states = self.q_proj(hidden_states, kwargs["position_ids"]) key_states = self.k_proj( key_hidden_states, cache=cache, conv_mask=conv_mask, cache_offset=cache_offset, **kwargs ) value_states = self.v_proj( value_hidden_states, cache=cache, conv_mask=conv_mask, cache_offset=cache_offset, **kwargs ) if cache is not None: key_states, value_states = cache.update(key_states, value_states, cache_layer_idx, kwargs=kwargs) attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface( self.config._attn_implementation, eager_attention_forward ) position_bias = self.relative_position_bias(hidden_states, relative_distance, kwargs["position_ids"]) sinks = self.sink_proj(hidden_states).transpose(1, 2).unsqueeze(-1) attn_output, attn_weights = attention_interface( self, query_states, key_states, value_states, attention_mask, dropout=0.0 if not self.training else self.attention_dropout, scaling=self.scaling, sliding_window=self.sliding_window, position_bias=position_bias, sinks=sinks, **kwargs, ) attn_output = attn_output.reshape(*input_shape, -1).contiguous() attn_output = self.o_proj(attn_output, hidden_states) return attn_output, attn_weights @use_kernel_forward_from_hub("RMSNorm") class Inkling2LoopRMSNorm(nn.Module): def __init__(self, hidden_size, eps: float = 1e-6) -> None: """ Inkling2LoopRMSNorm is equivalent to T5LayerNorm """ super().__init__() self.weight = nn.Parameter(torch.ones(hidden_size)) self.variance_epsilon = eps def forward(self, hidden_states) -> torch.Tensor: input_dtype = hidden_states.dtype hidden_states = hidden_states.to(torch.float32) variance = hidden_states.pow(2).mean(-1, keepdim=True) hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon) return (self.weight * hidden_states).to(input_dtype) def extra_repr(self): return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}" class Inkling2LoopSoftcap(nn.Module): def __init__(self, softcap: float): super().__init__() self.softcap = softcap def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: return torch.tanh(hidden_states / self.softcap) * self.softcap class Inkling2LoopSoftcappedSwiGLU(nn.Module): """SwiGLU where the sigmoid sees the raw gate and the softcaps only bound the linear gate factor and `up`.""" def __init__(self, config: Inkling2LoopTextConfig): super().__init__() self.gate_softcap = Inkling2LoopSoftcap(config.mlp_gate_softcap) self.up_softcap = Inkling2LoopSoftcap(config.mlp_up_softcap) def forward(self, gate: torch.Tensor, up: torch.Tensor) -> torch.Tensor: input_dtype = gate.dtype gate, up = gate.float(), up.float() return (self.gate_softcap(gate) * torch.sigmoid(gate) * self.up_softcap(up)).to(input_dtype) @use_experts_implementation class Inkling2LoopExperts(nn.Module): """Collection of expert weights stored as 3D tensors.""" def __init__(self, config: Inkling2LoopTextConfig): super().__init__() self.num_experts = config.n_routed_experts self.hidden_dim = config.hidden_size self.intermediate_dim = config.moe_intermediate_size self.gate_up_proj = nn.Parameter(torch.empty(self.num_experts, 2 * self.intermediate_dim, self.hidden_dim)) self.down_proj = nn.Parameter(torch.empty(self.num_experts, self.hidden_dim, self.intermediate_dim)) self.act_fn = Inkling2LoopSoftcappedSwiGLU(config) def forward( self, hidden_states: torch.Tensor, top_k_index: torch.Tensor, top_k_weights: torch.Tensor ) -> torch.Tensor: # accumulate the top-k expert outputs in fp32, as in the original final_hidden_states = torch.zeros_like(hidden_states, dtype=torch.float32) with torch.no_grad(): expert_mask = F.one_hot(top_k_index, num_classes=self.num_experts + 1).permute(2, 1, 0) expert_hit = torch.greater(expert_mask.sum(dim=(-1, -2)), 0).nonzero() for expert_idx in expert_hit: expert_idx = expert_idx[0] if expert_idx == self.num_experts: continue top_k_pos, token_idx = torch.where(expert_mask[expert_idx]) current_state = hidden_states[token_idx] current_hidden_states = self._apply_gate(F.linear(current_state, self.gate_up_proj[expert_idx])) current_hidden_states = F.linear(current_hidden_states, self.down_proj[expert_idx]) current_hidden_states = current_hidden_states * top_k_weights[token_idx, top_k_pos, None] final_hidden_states.index_add_(0, token_idx, current_hidden_states.to(final_hidden_states.dtype)) return final_hidden_states.to(hidden_states.dtype) def _apply_gate(self, gate_up: torch.Tensor) -> torch.Tensor: gate, up = gate_up.chunk(2, dim=-1) return self.act_fn(gate, up) class Inkling2LoopSparseMoeBlock(nn.Module): def __init__(self, config: Inkling2LoopConfig): super().__init__() self.experts = Inkling2LoopExperts(config) self.gate = Inkling2LoopTopKRouter(config) def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: batch_size, sequence_length, hidden_dim = hidden_states.shape hidden_states_reshaped = hidden_states.view(-1, hidden_dim) _, routing_weights, selected_experts = self.gate(hidden_states_reshaped) final_hidden_states = self.experts(hidden_states_reshaped, selected_experts, routing_weights) return final_hidden_states.reshape(batch_size, sequence_length, hidden_dim) class Inkling2LoopBlockAttentionResidual(nn.Module): def __init__(self, config: Inkling2LoopTextConfig, num_queries: int = 1): super().__init__() shape = (config.hidden_size,) if num_queries == 1 else (num_queries, config.hidden_size) self.query = nn.Parameter(torch.zeros(*shape, dtype=torch.float32)) self.norm = Inkling2LoopUnweightedRMSNorm() self.config = config self.num_key_value_groups = 1 self.is_causal = False def forward(self, block_states: torch.Tensor, partial_block_states: torch.Tensor) -> tuple[torch.Tensor, ...]: stacked_states = torch.cat([block_states, partial_block_states.unsqueeze(-2)], dim=-2).float() stacked_states = self.norm(stacked_states) hidden_size = stacked_states.shape[-1] # (batch, seq_len, num_queries, hidden_size), the same queries at every position query_states = self.query.float().view(-1, hidden_size).expand(*stacked_states.shape[:-2], -1, -1) attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface( self.config._attn_implementation, eager_attention_forward ) attn_output, _ = attention_interface( self, query_states, stacked_states, stacked_states, None, scaling=hidden_size**-0.5 ) return attn_output.transpose(1, 2).unbind(-2) class Inkling2LoopSlidingDecoderLayer(GradientCheckpointingLayer): attention_type = "sliding_attention" def __init__(self, config: Inkling2LoopTextConfig, layer_idx: int): super().__init__() self.is_block_boundary = layer_idx % config.n_layers_per_attn_res_block == 0 self.attention_input = Inkling2LoopBlockAttentionResidual(config) if layer_idx > 0 else None self.mlp_input = Inkling2LoopBlockAttentionResidual(config) self.self_attn = Inkling2LoopSlidingAttention(config, layer_idx) self.mlp = Inkling2LoopSparseMoeBlock(config) self.input_layernorm = Inkling2LoopRMSNorm(config.hidden_size, config.rms_norm_eps) self.post_attention_layernorm = Inkling2LoopRMSNorm(config.hidden_size, config.rms_norm_eps) self.post_attention_convolution = Inkling2LoopShortConvolution( config.hidden_size, config.conv_kernel_size, layer_idx=layer_idx, conv_idx=2 ).to(dtype=torch.float32) self.post_mlp_convolution = Inkling2LoopShortConvolution( config.hidden_size, config.conv_kernel_size, layer_idx=layer_idx, conv_idx=3 ).to(dtype=torch.float32) @deprecate_kwarg("past_key_values", "5.40.0", new_name="cache") def forward( self, hidden_states: torch.Tensor, block_states: torch.Tensor, attention_mask: torch.Tensor | None = None, relative_distance: torch.Tensor | None = None, conv_mask: torch.Tensor | None = None, cache: Cache | None = None, **kwargs: Unpack[TransformersKwargs], ) -> torch.Tensor: dtype = hidden_states.dtype block_residual = hidden_states if self.attention_input is not None: hidden_states = self.attention_input(block_states, hidden_states)[0] hidden_states, _ = self.self_attn( hidden_states=self.input_layernorm(hidden_states).to(dtype), attention_mask=attention_mask, relative_distance=relative_distance, conv_mask=conv_mask, cache=cache, **kwargs, ) hidden_states = self.post_attention_convolution(hidden_states, cache=cache, conv_mask=conv_mask, **kwargs) residual = hidden_states = hidden_states.float() if self.is_block_boundary: block_states = torch.cat([block_states, block_residual.unsqueeze(-2)], dim=-2) else: residual = hidden_states = block_residual.float() + hidden_states hidden_states = self.mlp_input(block_states, hidden_states)[0] hidden_states = self.mlp(self.post_attention_layernorm(hidden_states).to(dtype)) hidden_states = self.post_mlp_convolution(hidden_states, cache=cache, conv_mask=conv_mask, **kwargs) return (residual + hidden_states).to(dtype) class Inkling2LoopSlidingLoopDecoderLayer(GradientCheckpointingLayer): attention_type = "sliding_attention" def __init__(self, config: Inkling2LoopTextConfig, layer_idx: int): super().__init__() self.is_block_boundary = layer_idx % config.n_layers_per_attn_res_block == 0 self.attention_input = Inkling2LoopBlockAttentionResidual(config) if layer_idx > 0 else None self.mlp_input = Inkling2LoopBlockAttentionResidual(config) self.self_attn = Inkling2LoopSlidingAttention(config, layer_idx) self.mlp = Inkling2LoopSparseMoeBlock(config) self.input_layernorm = Inkling2LoopRMSNorm(config.hidden_size, config.rms_norm_eps) self.post_attention_layernorm = Inkling2LoopRMSNorm(config.hidden_size, config.rms_norm_eps) self.post_attention_convolution = Inkling2LoopShortConvolution( config.hidden_size, config.conv_kernel_size, layer_idx=layer_idx, conv_idx=2 ).to(dtype=torch.float32) self.post_mlp_convolution = Inkling2LoopShortConvolution( config.hidden_size, config.conv_kernel_size, layer_idx=layer_idx, conv_idx=3 ).to(dtype=torch.float32) self.q_message_gate = Inkling2LoopMessageGate(config) self.k_message_gate = Inkling2LoopMessageGate(config) self.v_message_gate = Inkling2LoopMessageGate(config) self.mlp_message_gate = Inkling2LoopMessageGate(config) @deprecate_kwarg("past_key_values", "5.40.0", new_name="cache") def forward( self, hidden_states: torch.Tensor, block_states: torch.Tensor, messages: torch.Tensor | None = None, attention_mask: torch.Tensor | None = None, relative_distance: torch.Tensor | None = None, conv_mask: torch.Tensor | None = None, cache: Cache | None = None, cache_offset: int = 0, memory_context=None, memory_components=None, memory_hop: int = 1, **kwargs: Unpack[TransformersKwargs], ) -> torch.Tensor: r""" messages (`torch.Tensor` of shape `(batch_size, sequence_length, 4, hidden_size)`, *optional*): Messages of the previous pass through the loop layers for the query, key, value and MLP inputs, in the passes after the first. cache_offset (`int`, *optional*, defaults to 0): Offset added to `layer_idx` to get the cache layer holding the keys, values and convolution states of this call. """ dtype = hidden_states.dtype block_residual = hidden_states hidden_states = self.attention_input(block_states, hidden_states)[0] if messages is None: query_hidden_states = key_hidden_states = value_hidden_states = self.input_layernorm(hidden_states) else: query_message, key_message, value_message, mlp_message = messages.unbind(-2) query_hidden_states = self.input_layernorm(self.q_message_gate(hidden_states, query_message)) key_hidden_states = self.input_layernorm(self.k_message_gate(hidden_states, key_message)) value_hidden_states = self.input_layernorm(self.v_message_gate(hidden_states, value_message)) hidden_states, _ = self.self_attn( hidden_states=query_hidden_states.to(dtype), key_hidden_states=key_hidden_states.to(dtype), value_hidden_states=value_hidden_states.to(dtype), attention_mask=attention_mask, relative_distance=relative_distance, conv_mask=conv_mask, cache=cache, cache_offset=cache_offset, **kwargs, ) hidden_states = self.post_attention_convolution( hidden_states, cache=cache, conv_mask=conv_mask, cache_offset=cache_offset, **kwargs ) residual = hidden_states = hidden_states.float() if self.is_block_boundary: block_states = torch.cat([block_states, block_residual.unsqueeze(-2)], dim=-2) else: residual = hidden_states = block_residual.float() + hidden_states hidden_states = self.mlp_input(block_states, hidden_states)[0] if messages is not None: hidden_states = self.mlp_message_gate(hidden_states, mlp_message) if memory_context is not None: hidden_states = memory_context.inject(memory_components, hidden_states, memory_hop) hidden_states = self.mlp(self.post_attention_layernorm(hidden_states).to(dtype)) hidden_states = self.post_mlp_convolution( hidden_states, cache=cache, conv_mask=conv_mask, cache_offset=cache_offset, **kwargs ) return (residual + hidden_states).to(dtype) class Inkling2LoopFullDecoderLayer(GradientCheckpointingLayer): attention_type = "full_attention" def __init__(self, config: Inkling2LoopTextConfig, layer_idx: int): super().__init__() self.is_block_boundary = layer_idx % config.n_layers_per_attn_res_block == 0 self.attention_input = Inkling2LoopBlockAttentionResidual(config, num_queries=3) if layer_idx > 0 else None self.mlp_input = Inkling2LoopBlockAttentionResidual(config) self.self_attn = Inkling2LoopFullAttention(config, layer_idx) self.mlp = Inkling2LoopSparseMoeBlock(config) self.q_input_layernorm = Inkling2LoopRMSNorm(config.hidden_size, config.rms_norm_eps) self.k_input_layernorm = Inkling2LoopRMSNorm(config.hidden_size, config.rms_norm_eps) self.v_input_layernorm = Inkling2LoopRMSNorm(config.hidden_size, config.rms_norm_eps) self.post_attention_layernorm = Inkling2LoopRMSNorm(config.hidden_size, config.rms_norm_eps) self.post_attention_convolution = Inkling2LoopShortConvolution( config.hidden_size, config.conv_kernel_size, layer_idx=layer_idx, conv_idx=2 ).to(dtype=torch.float32) self.post_mlp_convolution = Inkling2LoopShortConvolution( config.hidden_size, config.conv_kernel_size, layer_idx=layer_idx, conv_idx=3 ).to(dtype=torch.float32) @deprecate_kwarg("past_key_values", "5.40.0", new_name="cache") def forward( self, hidden_states: torch.Tensor, block_states: torch.Tensor, attention_mask: torch.Tensor | None = None, relative_distance: torch.Tensor | None = None, conv_mask: torch.Tensor | None = None, cache: Cache | None = None, **kwargs: Unpack[TransformersKwargs], ) -> torch.Tensor: dtype = hidden_states.dtype block_residual = hidden_states if self.attention_input is None: query_hidden_states = key_hidden_states = value_hidden_states = hidden_states else: query_hidden_states, key_hidden_states, value_hidden_states = self.attention_input( block_states, hidden_states ) hidden_states, _ = self.self_attn( hidden_states=self.q_input_layernorm(query_hidden_states).to(dtype), key_hidden_states=self.k_input_layernorm(key_hidden_states).to(dtype), value_hidden_states=self.v_input_layernorm(value_hidden_states).to(dtype), attention_mask=attention_mask, relative_distance=relative_distance, conv_mask=conv_mask, cache=cache, **kwargs, ) hidden_states = self.post_attention_convolution(hidden_states, cache=cache, conv_mask=conv_mask, **kwargs) residual = hidden_states = hidden_states.float() if self.is_block_boundary: block_states = torch.cat([block_states, block_residual.unsqueeze(-2)], dim=-2) else: residual = hidden_states = block_residual.float() + hidden_states hidden_states = self.mlp_input(block_states, hidden_states)[0] hidden_states = self.mlp(self.post_attention_layernorm(hidden_states).to(dtype)) hidden_states = self.post_mlp_convolution(hidden_states, cache=cache, conv_mask=conv_mask, **kwargs) return (residual + hidden_states).to(dtype) class Inkling2LoopFullLoopDecoderLayer(GradientCheckpointingLayer): attention_type = "full_attention" def __init__(self, config: Inkling2LoopTextConfig, layer_idx: int): super().__init__() self.is_block_boundary = layer_idx % config.n_layers_per_attn_res_block == 0 self.attention_input = Inkling2LoopBlockAttentionResidual(config, num_queries=3) if layer_idx > 0 else None self.mlp_input = Inkling2LoopBlockAttentionResidual(config) self.self_attn = Inkling2LoopFullAttention(config, layer_idx) self.mlp = Inkling2LoopSparseMoeBlock(config) self.q_input_layernorm = Inkling2LoopRMSNorm(config.hidden_size, config.rms_norm_eps) self.k_input_layernorm = Inkling2LoopRMSNorm(config.hidden_size, config.rms_norm_eps) self.v_input_layernorm = Inkling2LoopRMSNorm(config.hidden_size, config.rms_norm_eps) self.post_attention_layernorm = Inkling2LoopRMSNorm(config.hidden_size, config.rms_norm_eps) self.post_attention_convolution = Inkling2LoopShortConvolution( config.hidden_size, config.conv_kernel_size, layer_idx=layer_idx, conv_idx=2 ).to(dtype=torch.float32) self.post_mlp_convolution = Inkling2LoopShortConvolution( config.hidden_size, config.conv_kernel_size, layer_idx=layer_idx, conv_idx=3 ).to(dtype=torch.float32) self.q_message_gate = Inkling2LoopMessageGate(config) self.k_message_gate = Inkling2LoopMessageGate(config) self.v_message_gate = Inkling2LoopMessageGate(config) self.mlp_message_gate = Inkling2LoopMessageGate(config) @deprecate_kwarg("past_key_values", "5.40.0", new_name="cache") def forward( self, hidden_states: torch.Tensor, block_states: torch.Tensor, messages: torch.Tensor | None = None, attention_mask: torch.Tensor | None = None, relative_distance: torch.Tensor | None = None, conv_mask: torch.Tensor | None = None, cache: Cache | None = None, cache_offset: int = 0, memory_context=None, memory_components=None, memory_hop: int = 1, **kwargs: Unpack[TransformersKwargs], ) -> torch.Tensor: r""" messages (`torch.Tensor` of shape `(batch_size, sequence_length, 4, hidden_size)`, *optional*): Messages of the previous pass through the loop layers for the query, key, value and MLP inputs, in the passes after the first. cache_offset (`int`, *optional*, defaults to 0): Offset added to `layer_idx` to get the cache layer holding the keys, values and convolution states of this call. """ dtype = hidden_states.dtype block_residual = hidden_states query_hidden_states, key_hidden_states, value_hidden_states = self.attention_input(block_states, hidden_states) if messages is not None: query_message, key_message, value_message, mlp_message = messages.unbind(-2) query_hidden_states = self.q_message_gate(query_hidden_states, query_message) key_hidden_states = self.k_message_gate(key_hidden_states, key_message) value_hidden_states = self.v_message_gate(value_hidden_states, value_message) hidden_states, _ = self.self_attn( hidden_states=self.q_input_layernorm(query_hidden_states).to(dtype), key_hidden_states=self.k_input_layernorm(key_hidden_states).to(dtype), value_hidden_states=self.v_input_layernorm(value_hidden_states).to(dtype), attention_mask=attention_mask, relative_distance=relative_distance, conv_mask=conv_mask, cache=cache, cache_offset=cache_offset, **kwargs, ) hidden_states = self.post_attention_convolution( hidden_states, cache=cache, conv_mask=conv_mask, cache_offset=cache_offset, **kwargs ) residual = hidden_states = hidden_states.float() if self.is_block_boundary: block_states = torch.cat([block_states, block_residual.unsqueeze(-2)], dim=-2) else: residual = hidden_states = block_residual.float() + hidden_states hidden_states = self.mlp_input(block_states, hidden_states)[0] if messages is not None: hidden_states = self.mlp_message_gate(hidden_states, mlp_message) if memory_context is not None: hidden_states = memory_context.inject(memory_components, hidden_states, memory_hop) hidden_states = self.mlp(self.post_attention_layernorm(hidden_states).to(dtype)) hidden_states = self.post_mlp_convolution( hidden_states, cache=cache, conv_mask=conv_mask, cache_offset=cache_offset, **kwargs ) return (residual + hidden_states).to(dtype) class Inkling2LoopTopKRouter(nn.Module): def __init__(self, config: Inkling2LoopTextConfig): super().__init__() self.top_k = config.num_experts_per_tok self.num_experts = config.num_local_experts self.hidden_dim = config.hidden_size self.weight = nn.Parameter(torch.empty(self.num_experts, self.hidden_dim, dtype=torch.float32)) self.score_fn = ACT2FN[config.scoring_func] self.routed_scaling_factor = config.routed_scaling_factor self.e_score_correction_bias = nn.Buffer(torch.zeros(self.num_experts, dtype=torch.float32)) def forward(self, hidden_states: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: # routing runs in fp32, as in the original hidden_states = hidden_states.float() flat = hidden_states.reshape(-1, self.hidden_dim) logits = F.linear(flat, self.weight) scores = self.score_fn(logits) indices = torch.topk(scores + self.e_score_correction_bias, self.top_k, dim=-1, sorted=False).indices weights = scores.gather(1, indices) weights = weights / (weights.sum(dim=-1, keepdim=True) + 1e-20) return logits, weights * self.routed_scaling_factor, indices class _SourceValidationProcessor: """Validate the final read before HF selects or streams a token, also for partial/cached prompts.""" def __init__(self, validate): self.validate = validate def __call__(self, input_ids, scores): self.validate(allow_pending=False) return scores @auto_docstring class Inkling2LoopPreTrainedModel(PreTrainedModel): config: Inkling2LoopConfig base_model_prefix = "model" supports_gradient_checkpointing = True def _get_logits_processor(self, *args, **kwargs): processors = super()._get_logits_processor(*args, **kwargs) context = (kwargs.get("model_kwargs") or {}).get("memory_context") validate = getattr(context, "validate_source_for_answer", None) if validate is not None and getattr(context, "requires_source_validation", True): processors.insert(0, _SourceValidationProcessor(validate)) return processors _no_split_modules = [ "Inkling2LoopSlidingDecoderLayer", "Inkling2LoopFullDecoderLayer", "Inkling2LoopSlidingLoopDecoderLayer", "Inkling2LoopFullLoopDecoderLayer", "Inkling2V18MemoryComponents", ] # Disabled because of the per-token attention sinks _supports_flash_attn = False _supports_sdpa = False _supports_flex_attn = False _can_compile_fullgraph = False _supports_attention_backend = False _keep_in_fp32_modules_strict = [ "e_score_correction_bias", "mlp.gate.weight", "post_attention_convolution", "post_mlp_convolution", "sconv.conv1d", "attention_input", "mlp_input", "final_input", "message_input", "message_gate_proj", "forget_gate_proj", ] _can_record_outputs = { "hidden_states": OutputRecorder( ( Inkling2LoopSlidingDecoderLayer, Inkling2LoopFullDecoderLayer, Inkling2LoopSlidingLoopDecoderLayer, Inkling2LoopFullLoopDecoderLayer, ), num_hidden_layers_key="total_num_hidden_layers", ), "attentions": [Inkling2LoopSlidingAttention, Inkling2LoopFullAttention], "router_logits": OutputRecorder(Inkling2LoopTopKRouter, index=0), } def _init_weights(self, module): super()._init_weights(module) std = self.config.get_text_config().initializer_range if isinstance(module, Inkling2LoopRelativePositionBias): init.normal_(module.proj, mean=0.0, std=std) elif isinstance(module, Inkling2LoopExperts): init.normal_(module.gate_up_proj, mean=0.0, std=std) init.normal_(module.down_proj, mean=0.0, std=std) elif isinstance(module, Inkling2LoopTopKRouter): init.normal_(module.weight, mean=0.0, std=std) init.zeros_(module.e_score_correction_bias) elif isinstance(module, (Inkling2LoopScaledL2Clip, Inkling2LoopLogScaledL2Clip)): init.ones_(module.scale) elif isinstance(module, Inkling2LoopDynamicShortConvolution): init.zeros_(module.static_weight) elif isinstance(module, Inkling2LoopBlockAttentionResidual): init.zeros_(module.query) if isinstance(module, Inkling2LoopMessageAttentionResidual): init.zeros_(module.query) if isinstance(module, Inkling2V18MemoryComponents): module.reset_memory_parameters() class Inkling2LoopNormedEmbedding(nn.Embedding): def __init__(self, num_embeddings: int, embedding_dim: int, padding_idx: int, norm_eps: float): super().__init__(num_embeddings, embedding_dim, padding_idx) self.embed_norm = Inkling2LoopRMSNorm(embedding_dim, eps=norm_eps) def forward(self, input_ids: torch.Tensor): return self.embed_norm(super().forward(input_ids)) def get_relative_distance(inputs_embeds: torch.Tensor, cache: Cache | None, is_sliding: bool) -> torch.Tensor: """ Distance from each query position to each key position, of shape `(query_length, key_length)`, for the full or sliding attention layers. The sizes and offsets come from the same cache layer as for the attention masks. """ q_length = inputs_embeds.shape[1] if cache is None: kv_length, kv_offset, q_offset = q_length, 0, 0 else: if not is_sliding: layer_idx = find_first_full_attention_index(cache) elif True in cache.is_sliding: layer_idx = cache.is_sliding.index(True) else: layer_idx = 0 kv_length, kv_offset = cache.get_mask_sizes(q_length, layer_idx) q_offset = cache.get_query_offset(layer_idx) q_positions = torch.arange(q_length, device=inputs_embeds.device) + q_offset kv_positions = torch.arange(kv_length, device=inputs_embeds.device) + kv_offset return q_positions[:, None] - kv_positions[None, :] @auto_docstring class Inkling2LoopTextModel(Inkling2LoopPreTrainedModel): config: Inkling2LoopTextConfig def __init__(self, config: Inkling2LoopTextConfig): super().__init__(config) self.padding_idx = config.pad_token_id self.vocab_size = config.vocab_size self.embed_tokens = Inkling2LoopNormedEmbedding( config.vocab_size, config.hidden_size, self.padding_idx, config.rms_norm_eps ) self.layers = nn.ModuleList() self.norm = Inkling2LoopRMSNorm(config.hidden_size, eps=config.rms_norm_eps) self.gradient_checkpointing = False self.final_input = Inkling2LoopBlockAttentionResidual(config) layer_classes = { # (is_sliding, is_loop_layer) (False, False): Inkling2LoopFullDecoderLayer, (True, False): Inkling2LoopSlidingDecoderLayer, (False, True): Inkling2LoopFullLoopDecoderLayer, (True, True): Inkling2LoopSlidingLoopDecoderLayer, } for layer_idx in range(config.num_hidden_layers): is_sliding = config.layer_types[layer_idx] == "hybrid_sliding" is_loop_layer = config.loop_layer_index_start <= layer_idx < config.loop_layer_index_end layer_class = layer_classes[(is_sliding, is_loop_layer)] self.layers.append(layer_class(config, layer_idx)) self.message_input = Inkling2LoopMessageAttentionResidual(config) self.memory_v18 = Inkling2V18MemoryComponents(config.hidden_size) if config.v18_memory_enabled else None # Initialize weights and apply final processing self.post_init() @merge_with_config_defaults @capture_outputs @auto_docstring @deprecate_kwarg("past_key_values", "5.40.0", new_name="cache") def forward( self, input_ids: torch.LongTensor | None = None, attention_mask: torch.Tensor | None = None, position_ids: torch.LongTensor | None = None, cache: Cache | None = None, inputs_embeds: torch.Tensor | None = None, use_cache: bool | None = None, memory_context=None, loop_num_passes: int | None = None, **kwargs: Unpack[TransformersKwargs], ) -> MoeModelOutputWithPast: r""" memory_context (`object`, `optional`): Request-local V18 evidence session. The session binds causal token positions for each forward. loop_num_passes (`int`, `optional`): Override the core traversal count for this request (1 to 10). A cache and its continuations must use the same depth. Omit to use the checkpoint's configured depth. """ if (input_ids is None) ^ (inputs_embeds is not None): raise ValueError("You must specify exactly one of input_ids or inputs_embeds") if inputs_embeds is None: inputs_embeds = self.embed_tokens(input_ids) if loop_num_passes is not None and (type(loop_num_passes) is not int or not 1 <= loop_num_passes <= 10): raise ValueError("loop_num_passes must be an integer between 1 and 10.") num_passes = self.config.loop_num_passes if loop_num_passes is None else loop_num_passes loop_start = self.config.loop_layer_index_start loop_end = self.config.loop_layer_index_end num_loop_layers = loop_end - loop_start physical_layers = self.config.num_hidden_layers expected_slots = physical_layers + (num_passes - 1) * num_loop_layers # Select captured hidden states relative to the requested execution depth. if num_passes != self.config.loop_num_passes: selected = selected_hidden_states(kwargs.get("output_hidden_states", self.config.output_hidden_states)) if selected is not None: _active_collector.get()["_hidden_states_layers"] = resolve_hidden_states_indices( self, selected, num_hidden_states=expected_slots + 1 ) if use_cache and cache is None: cache = DynamicCache(config=self.config) if cache is not None: depth = getattr(cache, "_inkling2_loop_num_passes", None) if depth is not None and depth != num_passes: raise ValueError(f"Cache was created with {depth} loop passes; start a fresh cache for {num_passes}.") if len(cache.layers) != expected_slots: # Only expand a fresh physical-layer cache. A one-pass prefix has exactly as # many slots, but already contains token-dependent KV and convolution states. if len(cache.layers) != physical_layers or cache.get_seq_length() != 0: raise ValueError(f"Expected {expected_slots} cache slots for {num_passes} loop passes.") templates = cache.layers[loop_start:loop_end] cache.layers.extend(copy.deepcopy(layer) for _ in range(num_passes - 1) for layer in templates) cache._inkling2_loop_num_passes = num_passes if position_ids is None: past_seen_tokens = cache.get_seq_length() if cache is not None else 0 position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device) + past_seen_tokens position_ids = position_ids.unsqueeze(0) memory_view = None if memory_context is not None: if self.memory_v18 is None: raise ValueError("A memory_context requires v18_memory_enabled=True in the text config.") if hasattr(memory_context, "bind_loop_num_passes"): memory_context.bind_loop_num_passes(num_passes) memory_view = memory_context.begin_forward(position_ids, attention_mask) if not isinstance(causal_mask_mapping := attention_mask, dict): mask_kwargs = { "config": self.config, "inputs_embeds": inputs_embeds, "attention_mask": attention_mask, "cache": cache, "position_ids": position_ids, } causal_mask_mapping = { "full_attention": create_causal_mask(**mask_kwargs), "sliding_attention": create_sliding_window_causal_mask(**mask_kwargs), "linear_attention": create_recurrent_attention_mask(**mask_kwargs), } relative_distance_mapping = { "full_attention": get_relative_distance(inputs_embeds, cache, is_sliding=False), "sliding_attention": get_relative_distance(inputs_embeds, cache, is_sliding=True), } hidden_states = inputs_embeds block_states = inputs_embeds.new_zeros(*inputs_embeds.shape[:-1], 0, inputs_embeds.shape[-1]) # Pre loop layers for decoder_layer in self.layers[:loop_start]: new_hidden_states = decoder_layer( hidden_states, block_states, attention_mask=causal_mask_mapping[decoder_layer.attention_type], relative_distance=relative_distance_mapping[decoder_layer.attention_type], conv_mask=causal_mask_mapping["linear_attention"], cache=cache, position_ids=position_ids, **kwargs, ) if decoder_layer.is_block_boundary: block_states = torch.cat([block_states.to(hidden_states.device), hidden_states.unsqueeze(-2)], dim=-2) hidden_states = new_hidden_states pre_loop_hidden_states, pre_loop_block_states = hidden_states, block_states num_pre_loop_blocks = pre_loop_block_states.shape[-2] # A single-pass core reads the evidence in this pass, using only pre-core features for retrieval. one_pass_read = memory_view is not None and num_passes == 1 if one_pass_read: memory_view.prepare(self.memory_v18, hidden_states, 1) # First pass over loop layers for loop_layer_idx, decoder_layer in enumerate(self.layers[loop_start:loop_end]): new_hidden_states = decoder_layer( hidden_states, block_states, attention_mask=causal_mask_mapping[decoder_layer.attention_type], relative_distance=relative_distance_mapping[decoder_layer.attention_type], conv_mask=causal_mask_mapping["linear_attention"], cache=cache, memory_context=memory_view if one_pass_read and loop_layer_idx == num_loop_layers - 1 else None, memory_components=self.memory_v18, position_ids=position_ids, **kwargs, ) if decoder_layer.is_block_boundary: block_states = torch.cat([block_states.to(hidden_states.device), hidden_states.unsqueeze(-2)], dim=-2) hidden_states = new_hidden_states # Remaining passes restart from the pre loop states and receive messages from the previous pass for loop_idx in range(1, num_passes): # +1 to skip the states appended by the first loop pass previous_block_states = block_states[..., num_pre_loop_blocks + 1 :, :] previous_hidden_states = hidden_states # The first two pass boundaries can retrieve. Further passes reuse the second hop. memory_hop = min(loop_idx, 2) if memory_view is not None and loop_idx <= 2: memory_view.prepare(self.memory_v18, previous_hidden_states, memory_hop) hidden_states, block_states = pre_loop_hidden_states, pre_loop_block_states # Each pass uses its own copies of the loop cache layers, appended after the model's layers cache_offset = self.config.num_hidden_layers + (loop_idx - 1) * num_loop_layers - loop_start for loop_layer_idx, decoder_layer in enumerate(self.layers[loop_start:loop_end]): messages = self.message_input(previous_block_states, previous_hidden_states, loop_layer_idx) new_hidden_states = decoder_layer( hidden_states, block_states, messages, attention_mask=causal_mask_mapping[decoder_layer.attention_type], relative_distance=relative_distance_mapping[decoder_layer.attention_type], conv_mask=causal_mask_mapping["linear_attention"], cache=cache, cache_offset=cache_offset, memory_context=memory_view if loop_layer_idx == num_loop_layers - 1 else None, memory_components=self.memory_v18, memory_hop=memory_hop, position_ids=position_ids, **kwargs, ) if decoder_layer.is_block_boundary: block_states = torch.cat( [block_states.to(hidden_states.device), hidden_states.unsqueeze(-2)], dim=-2 ) hidden_states = new_hidden_states # Post loop layers for decoder_layer in self.layers[loop_end:]: new_hidden_states = decoder_layer( hidden_states, block_states, attention_mask=causal_mask_mapping[decoder_layer.attention_type], relative_distance=relative_distance_mapping[decoder_layer.attention_type], conv_mask=causal_mask_mapping["linear_attention"], cache=cache, position_ids=position_ids, **kwargs, ) if decoder_layer.is_block_boundary: block_states = torch.cat([block_states.to(hidden_states.device), hidden_states.unsqueeze(-2)], dim=-2) hidden_states = new_hidden_states hidden_states = self.final_input(block_states, hidden_states)[0] hidden_states = self.norm(hidden_states).to(inputs_embeds.dtype) return MoeModelOutputWithPast( last_hidden_state=hidden_states, cache=cache, ) @auto_docstring @dataclass class Inkling2LoopCausalLMOutputWithPast(MultimodalCausalLMOutputWithPast): router_logits: tuple[torch.Tensor] | None = None @property def image_hidden_states(self): logger.warning_once( "`image_hidden_states` is deprecated and will return a list of all hidden " "states per layer from v5.30; Use `out.image_outputs.pooler_output` to obtain pooled features." ) return self.image_outputs.pooler_output @auto_docstring class Inkling2LoopForCausalLM(Inkling2LoopPreTrainedModel, GenerationMixin): # `embed` and `unembed` are separate tensors in the checkpoints, never tied _tied_weights_keys = {} _tp_plan = {"lm_head": "rowwise_split_input"} _pp_plan = {"lm_head": (["hidden_states"], ["logits"])} _fsdp_plan = {"lm_head": "keep_full_weight"} config: Inkling2LoopTextConfig def __init__(self, config: Inkling2LoopTextConfig): super().__init__(config) self.model = Inkling2LoopTextModel(config) self.vocab_size = config.vocab_size self.lm_head = nn.Linear(config.hidden_size, config.unpadded_vocab_size, bias=False) self.logit_softcap = Inkling2LoopSoftcap(config.final_logit_softcapping) # Initialize weights and apply final processing self.post_init() @can_return_tuple @auto_docstring @deprecate_kwarg("past_key_values", "5.40.0", new_name="cache") def forward( self, input_ids: torch.LongTensor | None = None, attention_mask: torch.Tensor | None = None, position_ids: torch.LongTensor | None = None, cache: Cache | None = None, inputs_embeds: torch.Tensor | None = None, labels: torch.LongTensor | None = None, use_cache: bool | None = None, logits_to_keep: int | torch.Tensor = 0, memory_context=None, loop_num_passes: int | None = None, **kwargs: Unpack[TransformersKwargs], ) -> Inkling2LoopCausalLMOutputWithPast: r""" memory_context (`object`, `optional`): Request-local V18 evidence session. The session binds causal token positions for each forward. loop_num_passes (`int`, `optional`): Override the core traversal count for this request (1 to 10). A cache and its continuations must use the same depth. Omit to use the checkpoint's configured depth. Example: ```python >>> import torch >>> from transformers import AutoTokenizer, AutoModelForImageTextToText >>> tokenizer = AutoTokenizer.from_pretrained("/path/to/inkling-v18", trust_remote_code=True) >>> model = AutoModelForImageTextToText.from_pretrained( ... "/path/to/inkling-v18", trust_remote_code=True, dtype=torch.bfloat16, device_map="auto" ... ) >>> messages = [{"role": "user", "content": "Explain in one sentence why the sky is usually blue."}] >>> inputs = tokenizer.apply_chat_template( ... messages, ... tokenize=True, ... add_generation_prompt=True, ... return_dict=True, ... return_tensors="pt", ... ).to(model.device) >>> input_len = inputs["input_ids"].shape[-1] >>> outputs = model.generate(**inputs, max_new_tokens=1024) >>> print(tokenizer.decode(outputs[0][input_len:], skip_special_tokens=False)) ```""" outputs = self.model( input_ids=input_ids, attention_mask=attention_mask, position_ids=position_ids, cache=cache, inputs_embeds=inputs_embeds, use_cache=use_cache, memory_context=memory_context, loop_num_passes=loop_num_passes, **kwargs, ) # Manual decode also consumes these logits. A prefix before the anchor may still be cached. validate = getattr(memory_context, "validate_source_for_answer", None) if labels is None and validate is not None and getattr(memory_context, "requires_source_validation", True): validate() hidden_states = slice_logits_to_keep(outputs.last_hidden_state, logits_to_keep) logits = self.lm_head(hidden_states).float() logits = self.logit_softcap(logits) loss = None if labels is not None: loss = self.loss_function(logits=logits, labels=labels, vocab_size=logits.shape[-1], **kwargs) return Inkling2LoopCausalLMOutputWithPast( loss=loss, logits=logits, cache=outputs.cache, hidden_states=outputs.hidden_states, attentions=outputs.attentions, router_logits=outputs.router_logits, ) @auto_docstring @dataclass class Inkling2LoopModelOutputWithPast(MultimodalBaseModelOutputWithPast): router_logits: tuple[torch.Tensor] | None = None @property def image_hidden_states(self): logger.warning_once( "`image_hidden_states` is deprecated and will return a list of all hidden " "states per layer from v5.30; Use `out.image_outputs.pooler_output` to obtain pooled features." ) return self.image_outputs.pooler_output @auto_docstring( custom_intro=""" The Base Inkling2Loop model which consists of a vision backbone and a language model without language modeling head., """ ) class Inkling2LoopModel(Inkling2LoopPreTrainedModel): # we are filtering the logits/labels so we shouldn't divide the loss based on num_items_in_batch accepts_loss_kwargs = False input_modalities = ("image", "text") def __init__(self, config: Inkling2LoopConfig): super().__init__(config) self.language_model = Inkling2LoopTextModel(config.text_config) self.vision_tower = AutoModel.from_config(config.vision_config) self.post_init() @can_return_tuple @auto_docstring(custom_intro="Encodes images into language model embeddings, one per image token.") def get_image_features( self, pixel_values: torch.Tensor, image_grid_thw: torch.LongTensor, **kwargs: Unpack[TransformersKwargs] ) -> tuple | BaseModelOutputWithPooling: image_grid_thw = image_grid_thw.cpu() image_outputs = self.vision_tower(pixel_values=pixel_values, image_grid_thw=image_grid_thw, **kwargs) image_outputs.pooler_output = image_outputs.pooler_output.split(image_grid_thw.prod(-1).tolist()) return image_outputs def get_placeholder_mask( self, input_ids: torch.LongTensor, inputs_embeds: torch.Tensor, features: torch.Tensor, token_id: int, ): """ Obtains a multimodal placeholder mask from `input_ids` or `inputs_embeds` for the given `token_id`, and checks that the placeholder token count matches the length of `features`. If the lengths differ, an error is raised. """ if input_ids is None: special_mask = inputs_embeds == self.get_input_embeddings()( torch.tensor(token_id, dtype=torch.long, device=inputs_embeds.device) ) special_mask = special_mask.all(-1) else: special_mask = input_ids == token_id n_tokens = special_mask.sum() special_mask = special_mask.unsqueeze(-1).expand_as(inputs_embeds).to(inputs_embeds.device) torch_compilable_check( inputs_embeds[special_mask].numel() == features.numel(), f"Multimodal features and placeholder tokens do not match, tokens: {n_tokens}, features: {features.shape[0]}", ) return special_mask @can_return_tuple @auto_docstring @deprecate_kwarg("past_key_values", "5.40.0", new_name="cache") def forward( self, input_ids: torch.LongTensor | None = None, pixel_values: torch.Tensor | None = None, image_grid_thw: torch.LongTensor | None = None, attention_mask: torch.Tensor | None = None, position_ids: torch.LongTensor | None = None, cache: Cache | None = None, inputs_embeds: torch.Tensor | None = None, use_cache: bool | None = None, mm_encoder_outputs: dict[str, BaseModelOutputWithPooling] | None = None, memory_context=None, loop_num_passes: int | None = None, **kwargs: Unpack[TransformersKwargs], ) -> tuple | Inkling2LoopModelOutputWithPast: r""" memory_context (`object`, `optional`): Request-local V18 evidence session. The session binds causal token positions for each forward. loop_num_passes (`int`, `optional`): Override the core traversal count for this request (1 to 10). A cache and its continuations must use the same depth. Omit to use the checkpoint's configured depth. image_grid_thw (`torch.LongTensor` of shape `(num_images, 3)`, *optional*): Temporal, height and width of each image, counted in language model image tokens. Example: ```python >>> import torch >>> from transformers import AutoProcessor, AutoModel >>> processor = AutoProcessor.from_pretrained("/path/to/inkling-v18", trust_remote_code=True) >>> model = AutoModel.from_pretrained( ... "/path/to/inkling-v18", trust_remote_code=True, dtype=torch.bfloat16, device_map="auto" ... ) >>> messages = [ ... { ... "role": "user", ... "content": [ ... { ... "type": "image", ... "image": "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg", ... }, ... {"type": "text", "text": "What animal is in this image, and where is it?"}, ... ], ... }, ... ] >>> inputs = processor.apply_chat_template( ... messages, ... tokenize=True, ... add_generation_prompt=True, ... return_dict=True, ... return_tensors="pt", ... ).to(model.device) >>> outputs = model(**inputs) >>> last_hidden_state = outputs.last_hidden_state ``` """ if memory_context is not None: kwargs["memory_context"] = memory_context if loop_num_passes is not None: kwargs["loop_num_passes"] = loop_num_passes if (input_ids is None) ^ (inputs_embeds is not None): raise ValueError("You must specify exactly one of input_ids or inputs_embeds") if pixel_values is not None and mm_encoder_outputs is not None: raise ValueError("You cannot specify both pixel_values and mm_encoder_outputs at the same time") if inputs_embeds is None: inputs_embeds = self.get_input_embeddings()(input_ids) mm_encoder_outputs = mm_encoder_outputs if mm_encoder_outputs is not None else {} if mm_encoder_outputs.get("image") is None and pixel_values is not None: mm_encoder_outputs["image"] = self.get_image_features(pixel_values, image_grid_thw, return_dict=True) image_embeds = None if mm_encoder_outputs.get("image") is not None: image_embeds = torch.cat(mm_encoder_outputs["image"].pooler_output) image_embeds = image_embeds.to(inputs_embeds.device, inputs_embeds.dtype) special_image_mask = self.get_placeholder_mask( input_ids, inputs_embeds, image_embeds, self.config.image_token_id ) inputs_embeds = inputs_embeds.masked_scatter(special_image_mask, image_embeds) native_binding = getattr(memory_context, "_native_binding", None) if native_binding is not None: native_binding.observe(inputs_embeds, special_image_mask if image_embeds is not None else None, position_ids, cache) outputs = self.language_model( attention_mask=attention_mask, position_ids=position_ids, cache=cache, inputs_embeds=inputs_embeds, use_cache=use_cache, **kwargs, ) return Inkling2LoopModelOutputWithPast( last_hidden_state=outputs.last_hidden_state, cache=outputs.cache, hidden_states=outputs.hidden_states, attentions=outputs.attentions, image_outputs=mm_encoder_outputs.get("image"), video_outputs=mm_encoder_outputs.get("video"), router_logits=outputs.router_logits, ) @auto_docstring( custom_intro=""" The Base Inkling2Loop model which consists of a vision backbone and a language model without language modeling head., """ ) class Inkling2LoopForConditionalGeneration(Inkling2LoopPreTrainedModel, GenerationMixin): # `embed` and `unembed` are separate tensors in the checkpoints, never tied _tied_weights_keys = {} _tp_plan = {"lm_head": "rowwise_split_input"} # we are filtering the logits/labels so we shouldn't divide the loss based on num_items_in_batch # Fix: https://github.com/huggingface/transformers/issues/40564 accepts_loss_kwargs = False input_modalities = ("image", "text") def open_memory(self, processor, path, *, bank_id, checkpoint_dir=None): """Open the checkpoint's event bank. A source-bound context may raise a LookupError carrying status="insufficient_evidence" and a grounding record before an answer token is issued. """ return open_checkpoint_memory(self, processor, path, bank_id=bank_id, checkpoint_dir=checkpoint_dir) def __init__(self, config: Inkling2LoopConfig): super().__init__(config) self.model = Inkling2LoopModel(config) self.lm_head = nn.Linear(config.text_config.hidden_size, config.text_config.unpadded_vocab_size, bias=False) self.logit_softcap = Inkling2LoopSoftcap(config.text_config.final_logit_softcapping) self.post_init() @auto_docstring def get_image_features( self, pixel_values: torch.Tensor, image_grid_thw: torch.LongTensor, **kwargs: Unpack[TransformersKwargs] ): return self.model.get_image_features(pixel_values, image_grid_thw, **kwargs) @can_return_tuple @auto_docstring @deprecate_kwarg("past_key_values", "5.40.0", new_name="cache") def forward( self, input_ids: torch.LongTensor | None = None, pixel_values: torch.Tensor | None = None, image_grid_thw: torch.LongTensor | None = None, attention_mask: torch.Tensor | None = None, position_ids: torch.LongTensor | None = None, cache: Cache | None = None, inputs_embeds: torch.Tensor | None = None, labels: torch.LongTensor | None = None, use_cache: bool | None = None, logits_to_keep: int | torch.Tensor = 0, mm_encoder_outputs: dict[str, BaseModelOutputWithPooling] | None = None, memory_context=None, loop_num_passes: int | None = None, **kwargs: Unpack[TransformersKwargs], ) -> tuple | Inkling2LoopCausalLMOutputWithPast: r""" memory_context (`object`, `optional`): Request-local V18 evidence session. The session binds causal token positions for each forward. loop_num_passes (`int`, `optional`): Override the core traversal count for this request (1 to 10). A cache and its continuations must use the same depth. Omit to use the checkpoint's configured depth. image_grid_thw (`torch.LongTensor` of shape `(num_images, 3)`, *optional*): Temporal, height and width of each image, counted in language model image tokens. Example: ```python >>> import torch >>> from transformers import AutoProcessor, AutoModelForImageTextToText >>> processor = AutoProcessor.from_pretrained("/path/to/inkling-v18", trust_remote_code=True) >>> model = AutoModelForImageTextToText.from_pretrained( ... "/path/to/inkling-v18", trust_remote_code=True, dtype=torch.bfloat16, device_map="auto" ... ) >>> messages = [ ... { ... "role": "user", ... "content": [ ... { ... "type": "image", ... "image": "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg", ... }, ... {"type": "text", "text": "What animal is in this image, and where is it?"}, ... ], ... }, ... ] >>> inputs = processor.apply_chat_template( ... messages, ... tokenize=True, ... add_generation_prompt=True, ... return_dict=True, ... return_tensors="pt", ... ).to(model.device) >>> input_len = inputs["input_ids"].shape[-1] >>> outputs = model.generate(**inputs, max_new_tokens=1024) >>> print(processor.decode(outputs[0][input_len:], skip_special_tokens=False)) ``` """ outputs = self.model( input_ids=input_ids, pixel_values=pixel_values, image_grid_thw=image_grid_thw, attention_mask=attention_mask, position_ids=position_ids, cache=cache, inputs_embeds=inputs_embeds, use_cache=use_cache, mm_encoder_outputs=mm_encoder_outputs, memory_context=memory_context, loop_num_passes=loop_num_passes, **kwargs, ) # Manual decode also consumes these logits. A prefix before the anchor may still be cached. validate = getattr(memory_context, "validate_source_for_answer", None) if labels is None and validate is not None and getattr(memory_context, "requires_source_validation", True): validate() hidden_states = slice_logits_to_keep(outputs.last_hidden_state, logits_to_keep) logits = self.lm_head(hidden_states).float() logits = self.logit_softcap(logits) loss = None if labels is not None: loss = self.loss_function(logits=logits, labels=labels, vocab_size=logits.shape[-1], **kwargs) return Inkling2LoopCausalLMOutputWithPast( loss=loss, logits=logits, cache=outputs.cache, hidden_states=outputs.hidden_states, attentions=outputs.attentions, image_outputs=outputs.image_outputs, video_outputs=outputs.video_outputs, router_logits=outputs.router_logits, ) __all__ = [ "Inkling2LoopPreTrainedModel", "Inkling2LoopTextModel", "Inkling2LoopForCausalLM", "Inkling2LoopModel", "Inkling2LoopForConditionalGeneration", ]
# 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 copy
import math
from collections.abc import Callable
from dataclasses import dataclass
import torch
import torch.nn as nn
import torch.nn.functional as F
from transformers import initialization as init
from transformers.activations import ACT2FN
from transformers.conversion_mapping import (
USER_REGISTERED_MAPPINGS,
get_checkpoint_conversion_mapping,
register_checkpoint_conversion_mapping,
)
from transformers.cache_utils import Cache, DynamicCache
from transformers.generation import GenerationMixin
from transformers.integrations import (
use_experts_implementation,
use_kernel_forward_from_hub,
use_kernel_func_from_hub_with_fallback,
use_kernelized_func,
)
from transformers.integrations.accelerate import force_accelerate_hooks
from transformers.masking_utils import (
create_causal_mask,
create_recurrent_attention_mask,
create_sliding_window_causal_mask,
find_first_full_attention_index,
)
from transformers.modeling_layers import GradientCheckpointingLayer
from transformers.modeling_outputs import (
BaseModelOutputWithPooling,
MoeModelOutputWithPast,
MultimodalBaseModelOutputWithPast,
MultimodalCausalLMOutputWithPast,
)
from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel, slice_logits_to_keep
from transformers.processing_utils import Unpack
from transformers.utils import TransformersKwargs, auto_docstring, can_return_tuple, logging, torch_compilable_check
from transformers.utils.deprecation import deprecate_kwarg
from transformers.utils.generic import merge_with_config_defaults
from transformers.utils.output_capturing import (
OutputRecorder,
_active_collector,
capture_outputs,
resolve_hidden_states_indices,
selected_hidden_states,
)
from transformers.models.auto import AutoModel
from .configuration_inkling2_loop_v18 import Inkling2LoopConfig, Inkling2LoopTextConfig
from .memory_v18 import Inkling2V18MemoryComponents
from .runtime_v18 import open_checkpoint_memory
# Custom models opt in to loading the original packed Inkling weight layout.
# Separate identifiers preserve upstream conversion behavior for native Inkling models.
for _v18, _native in (
(Inkling2LoopConfig.model_type, "inkling2_loop"),
(Inkling2LoopTextConfig.model_type, "inkling2_loop_text"),
):
if _v18 not in USER_REGISTERED_MAPPINGS:
_conversions = get_checkpoint_conversion_mapping(_native)
if not _conversions:
raise ImportError("V18 needs a Transformers release with native Inkling 2 Loop checkpoint converters")
register_checkpoint_conversion_mapping(_v18, _conversions)
logger = logging.get_logger(__name__)
class Inkling2LoopUnweightedRMSNorm(nn.Module):
def __init__(self, eps: float = 1.0e-6):
super().__init__()
self.eps = eps
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
input_dtype = hidden_states.dtype
hidden_states = hidden_states.float()
hidden_states = hidden_states * torch.rsqrt(hidden_states.square().mean(-1, keepdim=True) + self.eps)
return hidden_states.to(input_dtype)
class Inkling2LoopMessageGate(nn.Module):
"""Mixes hidden states and message as `(1 - forget_gate) * hidden_states + message_gate * message`"""