diff --git a/docs/source/en/_toctree.yml b/docs/source/en/_toctree.yml index 208df65d787c..2d0a899a1864 100644 --- a/docs/source/en/_toctree.yml +++ b/docs/source/en/_toctree.yml @@ -1451,6 +1451,8 @@ title: Inkling - local: model_doc/inkling2 title: Inkling2 + - local: model_doc/inkling2_loop + title: Inkling2Loop - local: model_doc/instructblip title: InstructBLIP - local: model_doc/instructblipvideo diff --git a/docs/source/en/model_doc/inkling2.md b/docs/source/en/model_doc/inkling2.md index e35d2d71f282..b1e39838840a 100644 --- a/docs/source/en/model_doc/inkling2.md +++ b/docs/source/en/model_doc/inkling2.md @@ -114,6 +114,9 @@ print(processor.decode(outputs[0][input_len:], skip_special_tokens=False)) ## Notes - Attention runs in eager mode only, because every layer adds a relative position bias and a sink. +- The short convolutions use fast GPU kernels when available: Hub kernels when loading with `use_kernels=True`, + otherwise the [causal-conv1d](https://github.com/Dao-AILab/causal-conv1d) package if installed + (`pip install causal-conv1d`). Without them, they fall back to a slower PyTorch implementation. ## Inkling2Config diff --git a/docs/source/en/model_doc/inkling2_loop.md b/docs/source/en/model_doc/inkling2_loop.md new file mode 100644 index 000000000000..2ab95ebe8f4a --- /dev/null +++ b/docs/source/en/model_doc/inkling2_loop.md @@ -0,0 +1,216 @@ + +*This model was contributed to Hugging Face Transformers on 2026-11-21.* + +# Inkling 2 Mini + +[Inkling 2 Mini](https://huggingface.co/collections/thinkingmachines/inkling-2) is a multimodal model from [Thinking Machines Lab](https://huggingface.co/thinkingmachines) that accepts text and image inputs and generates text outputs. It is based on [Inkling 2 Small](./inkling2) but has only 24 decoder layers instead of 48. The lower layer count is compensated for by a looping mechanism in which layers 6 to 17 run three times. Information is shared between loop passes through a learned message-passing mechanism that mixes the residuals of the previous pass into the attention and mixture-of-experts inputs of each loop layer. The decoder has a hidden size of 2304 and routes each token to 8 of 128 experts. The image encoder, tokenizer and processor are identical to those of Inkling 2 Small. + +Inkling 2 Mini comes with an additional [research checkpoint](https://huggingface.co/thinkingmachines/TML-d24-varloop-research) that supports a variable number of loop passes. The architecture is identical to the main Inkling 2 Mini model. The number of loop passes can be adjusted to trade off speed against quality. Fewer passes are faster, while more passes improve quality. + +Both checkpoints contain NVFP4 and MXFP8 quantized layers that Transformers dequantizes when loading the model. + +**Checkpoints** + +- [Inkling 2 Mini](https://huggingface.co/thinkingmachines/Inkling-2-Mini) +- [Inkling 2 Mini varloop research](https://huggingface.co/thinkingmachines/TML-d24-varloop-research) + +## Resources + +- [Thinking Machines Blog](https://thinkingmachines.ai/news/inkling-2-mini/) +- [Hugging Face Blog](https://huggingface.co/blog/inkling2mini) + + + + +```python +import torch + +from transformers import pipeline + +pipe = pipeline( + "image-text-to-text", model="thinkingmachines/Inkling-2-Mini", 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?"}, + ], + }, +] + +output = pipe(messages, max_new_tokens=1024, return_full_text=False, skip_special_tokens=False) +print(output[0]["generated_text"]) +# <|message_model|><|content_thinking|>The user is asking about an animal in an image. Let me +# analyze what I see: a small wild feline with thick, fluffy fur dusted with snow, short legs, a +# broad face, and black stripes/spots. +# ... +# <|end_message|><|message_model|><|content_text|>The animal appears to be a Pallas’s cat (manul) — +# a small, bear-like wild cat with thick speckled/striped fur. It’s standing on snow inside what +# looks like a zoo or wildlife enclosure, with snow-covered birch/log branches and a chain-link +# fence in the background.<|end_message|><|content_model_end_sampling|> +``` + + + + +```python +import torch + +from transformers import AutoModelForMultimodalLM, AutoProcessor + +model_id = "thinkingmachines/Inkling-2-Mini" +processor = AutoProcessor.from_pretrained(model_id) +model = AutoModelForMultimodalLM.from_pretrained(model_id, 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)) +# <|message_model|><|content_thinking|>The user is asking what animal is in the image and where it +# is. Let me analyze the image. +# ... +# <|end_message|><|message_model|><|content_text|>The animal appears to be a Pallas’s cat (manul), a +# stocky small wild cat with thick, snow-dusted fur. It is standing on snow, likely inside a zoo or +# wildlife enclosure — you can see birch/aspen-like posts and chain-link fencing in the +# background.<|end_message|><|content_model_end_sampling|> +``` + + + + + +```python +import torch + +from transformers import AutoModelForMultimodalLM, AutoProcessor + +model_id = "thinkingmachines/TML-d24-varloop-research" +processor = AutoProcessor.from_pretrained(model_id) +model = AutoModelForMultimodalLM.from_pretrained( + model_id, + dtype=torch.bfloat16, + device_map="auto", + text_config={"loop_num_passes": 3}, # number of loop passes, must be at least 1 +) + +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)) +# <|message_model|><|content_thinking|>We need answer image question. Need identify animal and where +# is it. +# ... +# <|end_message|><|message_model|><|content_text|>The animal is a Pallas’s cat (a.k.a. Manul), a +# stocky, densely furred small wild cat. It’s in the snow outdoors in a cold setting—likely a winter +# enclosure/habitat—standing/walking on snow at the center of the +# image.<|end_message|><|content_model_end_sampling|> +``` + + + + + +## Notes + +- Attention runs in eager mode only because every layer adds a relative position bias and a sink. +- The short convolutions use fast GPU kernels when available: Hub kernels when loading with `use_kernels=True`, + otherwise the [causal-conv1d](https://github.com/Dao-AILab/causal-conv1d) package if installed + (`pip install causal-conv1d`). Without them, they fall back to a slower PyTorch implementation. +- Every pass through the loop layers keeps its own keys, values and convolution states, so the cache has one layer per layer visit (48 for the released checkpoint). +- `output_hidden_states` and `output_attentions` return one entry per layer visit. + +## Inkling2LoopConfig + +[[autodoc]] Inkling2LoopConfig + +## Inkling2LoopTextConfig + +[[autodoc]] Inkling2LoopTextConfig + +## Inkling2LoopPreTrainedModel + +[[autodoc]] Inkling2LoopPreTrainedModel + - forward + +## Inkling2LoopTextModel + +[[autodoc]] Inkling2LoopTextModel + - forward + +## Inkling2LoopForCausalLM + +[[autodoc]] Inkling2LoopForCausalLM + - forward + +## Inkling2LoopModel + +[[autodoc]] Inkling2LoopModel + - forward + +## Inkling2LoopForConditionalGeneration + +[[autodoc]] Inkling2LoopForConditionalGeneration + - forward diff --git a/src/transformers/conversion_mapping.py b/src/transformers/conversion_mapping.py index 2a518bdb0307..77060d1add88 100755 --- a/src/transformers/conversion_mapping.py +++ b/src/transformers/conversion_mapping.py @@ -24,6 +24,9 @@ ErnieFuseAndSplitTextVisionExperts, GroupWeightRename, Inkling2IndexOffsetWeightRename, + Inkling2LoopDequantizeExperts, + Inkling2LoopMergeMessageQueries, + Inkling2UnpadVocab, Interleave, LayerPairCollapse, MergeModulelist, @@ -297,6 +300,11 @@ def _build_checkpoint_conversion_mapping(): ], "inkling2": [ WeightRenaming(source_patterns=r"model\.llm\.unembed\.", target_patterns=r"lm_head."), + WeightConverter( + source_patterns=r"lm_head\.weight", + target_patterns=r"lm_head.weight", + operations=[Inkling2UnpadVocab()], + ), WeightRenaming(source_patterns=r"model\.llm\.", target_patterns=r"model.language_model."), WeightRenaming(source_patterns=r"model\.visual\.", target_patterns=r"model.vision_tower."), WeightRenaming( @@ -344,6 +352,11 @@ def _build_checkpoint_conversion_mapping(): ], "inkling2_text": [ WeightRenaming(source_patterns=r"model\.llm\.unembed\.", target_patterns=r"lm_head."), + WeightConverter( + source_patterns=r"lm_head\.weight", + target_patterns=r"lm_head.weight", + operations=[Inkling2UnpadVocab()], + ), WeightRenaming(source_patterns=r"model\.llm\.", target_patterns=r"model."), WeightRenaming(source_patterns=r"embed\.weight", target_patterns=r"embed_tokens.weight"), WeightRenaming(source_patterns=r"embed_norm\.", target_patterns=r"embed_tokens.embed_norm."), @@ -363,12 +376,23 @@ def _build_checkpoint_conversion_mapping(): ), WeightRenaming(source_patterns=r"mlp.gate.bias", target_patterns=r"mlp.gate.e_score_correction_bias"), WeightRenaming(source_patterns=r"\.attn\.", target_patterns=r".self_attn."), - WeightRenaming(source_patterns=r"self_attn\.wq_du", target_patterns=r"self_attn.q_proj"), - WeightRenaming(source_patterns=r"self_attn\.wk_dv", target_patterns=r"self_attn.k_proj"), - WeightRenaming(source_patterns=r"self_attn\.wv_dv", target_patterns=r"self_attn.v_proj"), - WeightRenaming(source_patterns=r"self_attn\.wr_du", target_patterns=r"self_attn.r_proj"), - WeightRenaming(source_patterns=r"self_attn\.wo_ud", target_patterns=r"self_attn.o_proj"), - WeightRenaming(source_patterns=r"self_attn\.gate_attn", target_patterns=r"self_attn.gate_proj"), + WeightRenaming(source_patterns=r"self_attn\.wq_du", target_patterns=r"self_attn.q_proj.linear"), + WeightRenaming(source_patterns=r"self_attn\.wk_dv", target_patterns=r"self_attn.k_proj.linear"), + WeightRenaming(source_patterns=r"self_attn\.wv_dv", target_patterns=r"self_attn.v_proj.linear"), + WeightRenaming(source_patterns=r"self_attn\.k_sconv\.", target_patterns=r"self_attn.k_proj.sconv."), + WeightRenaming(source_patterns=r"self_attn\.v_sconv\.", target_patterns=r"self_attn.v_proj.sconv."), + WeightRenaming( + source_patterns=r"self_attn\.rel_logits_proj\.", target_patterns=r"self_attn.relative_position_bias." + ), + WeightRenaming( + source_patterns=r"self_attn\.wr_du", target_patterns=r"self_attn.relative_position_bias.linear" + ), + WeightRenaming(source_patterns=r"self_attn\.q_l2_clip\.", target_patterns=r"self_attn.q_proj.norm."), + WeightRenaming( + source_patterns=r"self_attn\.rel_l2_clip\.", target_patterns=r"self_attn.relative_position_bias.norm." + ), + WeightRenaming(source_patterns=r"self_attn\.wo_ud", target_patterns=r"self_attn.o_proj.linear"), + WeightRenaming(source_patterns=r"self_attn\.gate_attn", target_patterns=r"self_attn.o_proj.gate_proj"), WeightRenaming(source_patterns=r"self_attn\.attn_sink_proj", target_patterns=r"self_attn.sink_proj"), WeightRenaming(source_patterns=r"attn_sconv\.", target_patterns=r"post_attention_convolution."), WeightRenaming(source_patterns=r"mlp_sconv\.", target_patterns=r"post_mlp_convolution."), @@ -2627,6 +2651,62 @@ def _build_checkpoint_conversion_mapping(): ), ] + mapping["inkling2_loop"] = mapping["inkling2"].copy() + # Temporary: the original Inkling2Loop checkpoints store NVFP4 and MXFP8 experts. They are dequantized on load and + # replace the Inkling2 expert transforms, which keep MXFP8 experts quantized. + inkling2_loop_experts = [ + WeightConverter( + source_patterns=[ + r"mlp\.experts\.w13_weight", + r"mlp\.experts\.w13_weight_scale", + r"mlp\.experts\.w13_weight_amax", + r"mlp\.experts\.w13_weight_outer_scale_denominator", + ], + target_patterns=r"mlp.experts.gate_up_proj", + operations=[Inkling2LoopDequantizeExperts(), Interleave(dim=1)], + ), + WeightConverter( + source_patterns=[ + r"mlp\.experts\.w2_weight", + r"mlp\.experts\.w2_weight_scale", + r"mlp\.experts\.w2_weight_amax", + r"mlp\.experts\.w2_weight_outer_scale_denominator", + ], + target_patterns=r"mlp.experts.down_proj", + operations=[Inkling2LoopDequantizeExperts()], + ), + ] + inkling2_text = [ + transform + for transform in mapping["inkling2_text"] + if not transform._original_source_patterns[0].startswith(r"mlp\.experts\.w") + ] + mapping["inkling2_loop_text"] = [ + WeightRenaming(source_patterns=r"controllers\.attn\.", target_patterns=r"q_message_gate."), + WeightRenaming(source_patterns=r"controllers\.k\.", target_patterns=r"k_message_gate."), + WeightRenaming(source_patterns=r"controllers\.v\.", target_patterns=r"v_message_gate."), + WeightRenaming(source_patterns=r"controllers\.mlp\.", target_patterns=r"mlp_message_gate."), + WeightRenaming( + source_patterns=r"_message_gate\.down_weight", target_patterns=r"_message_gate.down_proj.weight" + ), + WeightRenaming( + source_patterns=r"_message_gate\.gain_weight", target_patterns=r"_message_gate.message_gate_proj.weight" + ), + WeightRenaming( + source_patterns=r"_message_gate\.forget_weight", target_patterns=r"_message_gate.forget_gate_proj.weight" + ), + # The original checkpoint stores two (2 * num_loop_layers, hidden_size) query parameters: + # - middle_cycle_cross_pass_queries: the query and mlp queries of each loop layer + # - middle_cycle_cross_pass_kv_queries: the key and value queries of each loop layer + # We merge them into a single (num_loop_layers, 4, hidden_size) query param. + WeightConverter( + source_patterns=[r"middle_cycle_cross_pass_queries", r"middle_cycle_cross_pass_kv_queries"], + target_patterns=r"message_input.query", + operations=[Inkling2LoopMergeMessageQueries()], + ), + *inkling2_loop_experts, + ] + inkling2_text + for model_type, base_pattern in _MODEL_TO_CONVERSION_PATTERN.items(): if model_type in mapping: continue diff --git a/src/transformers/core_model_loading.py b/src/transformers/core_model_loading.py index f2d6405ae2bb..4794ea34d211 100644 --- a/src/transformers/core_model_loading.py +++ b/src/transformers/core_model_loading.py @@ -769,6 +769,119 @@ def reverse_op(self) -> ConversionOps: return ErnieFuseAndSplitTextVisionExperts(stack_dim=self.stack_dim, concat_dim=self.concat_dim) +class Inkling2LoopDequantizeExperts(ConversionOps): + r""" + Temporary op that dequantizes the NVFP4 and MXFP8 expert weights of the original Inkling2Loop checkpoints to the + dtype of the model param, until these formats can be loaded quantized. + + - NVFP4 (`amax` present): two E2M1 codes per byte (even element in the low nibble), one float8 scale per 16 values + and a per-expert factor `amax / outer_scale_denominator`. + - MXFP8: float8 values with one power-of-two scale `2 ** (scale - 127)` per 32 values. + """ + + E2M1_VALUES = (0.0, 0.5, 1.0, 1.5, 2.0, 3.0, 4.0, 6.0, -0.0, -0.5, -1.0, -1.5, -2.0, -3.0, -4.0, -6.0) + EXPERTS_PER_CHUNK = 8 + + @torch.no_grad() + def convert(self, input_dict, source_patterns, target_patterns, model=None, full_layer_name=None, **kwargs): + tensors = {key: value[0] if isinstance(value, list) else value for key, value in input_dict.items()} + if len(tensors) == 1: + return {target_patterns[0]: next(iter(tensors.values()))} + weight, scale, amax, denominator = (tensors.get(pattern) for pattern in source_patterns) + + # Without a quantizer, the loader casts all sources to the param dtype, but don't rely on it + try: + dtype = model.get_parameter(full_layer_name).dtype + except (AttributeError, TypeError): + dtype = torch.bfloat16 + num_experts, rows = weight.shape[:2] + columns = weight.shape[2] * 2 if amax is not None else weight.shape[2] + output = torch.empty(num_experts, rows, columns, dtype=dtype, device=weight.device) + if amax is not None: + e2m1_values = torch.tensor(self.E2M1_VALUES, device=weight.device) + byte = torch.arange(256, device=weight.device) + byte_to_values = torch.stack((e2m1_values[byte & 0xF], e2m1_values[byte >> 4]), dim=-1) + expert_factor = amax.float() / denominator.float() + for start in range(0, num_experts, self.EXPERTS_PER_CHUNK): + experts = slice(start, start + self.EXPERTS_PER_CHUNK) + block_scale = scale[experts].float() + if amax is None: + values = weight[experts].float().view(*block_scale.shape, 32) + values = values * torch.exp2(block_scale - 127)[..., None] + else: + codes = weight[experts].to(torch.uint8).long() + values = byte_to_values[codes].view(*block_scale.shape, 16) * block_scale[..., None] + values = values * expert_factor[experts, None, None, None] + output[experts] = values.reshape(-1, rows, columns).to(dtype) + return {target_patterns[0]: output} + + @property + def reverse_op(self) -> ConversionOps: + return self + + +class Inkling2LoopMergeMessageQueries(ConversionOps): + r""" + Merges the message queries of the original Inkling2Loop checkpoints into one `(num_loop_layers, 4, hidden_size)` + tensor, or splits them back with `inverse=True`. The checkpoints store them as two + `(2 * num_loop_layers, hidden_size)` tensors: the query and MLP queries of each loop layer, then its key and value + queries. The merged tensor holds the query, key, value and MLP queries of each loop layer, in that order. + """ + + def __init__(self, inverse: bool = False): + self.inverse = inverse + + @torch.no_grad + def convert(self, input_dict, source_patterns, target_patterns, **kwargs): + if self.inverse: + tensor = next(iter(input_dict.values())) + tensor = tensor[0] if isinstance(tensor, list) else tensor + queries = tensor[:, [0, 3]].flatten(0, 1) + kv_queries = tensor[:, 1:3].flatten(0, 1) + return {target_patterns[0]: queries.contiguous(), target_patterns[1]: kv_queries.contiguous()} + + queries, kv_queries = (input_dict[pattern] for pattern in source_patterns) + queries = queries[0] if isinstance(queries, list) else queries + kv_queries = kv_queries[0] if isinstance(kv_queries, list) else kv_queries + # (num_loop_layers, 2, hidden_size): [query, mlp] and [key, value] of each loop layer + queries = queries.unflatten(0, (-1, 2)) + kv_queries = kv_queries.unflatten(0, (-1, 2)) + return {target_patterns[0]: torch.cat([queries[:, :1], kv_queries, queries[:, 1:]], dim=1)} + + @property + def reverse_op(self) -> ConversionOps: + return Inkling2LoopMergeMessageQueries(inverse=not self.inverse) + + +class Inkling2UnpadVocab(ConversionOps): + r""" + Drops the padded rows of the Inkling2 unembedding, which checkpoints store padded to `vocab_size`, keeping the first + `unpadded_vocab_size` rows. With `inverse=True`, appends zero rows to pad it back to `vocab_size`. + """ + + def __init__(self, inverse: bool = False): + self.inverse = inverse + + @torch.no_grad + def convert( + self, input_dict, source_patterns, target_patterns, config=None, model=None, full_layer_name=None, **kwargs + ): + tensor = next(iter(input_dict.values())) + tensor = tensor[0] if isinstance(tensor, list) else tensor + text_config = config.get_text_config() + if self.inverse: + padding = tensor.new_zeros(text_config.vocab_size - tensor.shape[0], *tensor.shape[1:]) + tensor = torch.cat([tensor, padding], dim=0) + else: + dtype = model.get_parameter(full_layer_name).dtype + tensor = tensor[: text_config.unpadded_vocab_size].to(dtype).contiguous() + return {target_patterns[0]: tensor} + + @property + def reverse_op(self) -> ConversionOps: + return Inkling2UnpadVocab(inverse=not self.inverse) + + def process_target_pattern(pattern: str) -> tuple[str, str | None]: """ Process a target pattern for reverse mapping (when targets become sources). diff --git a/src/transformers/models/__init__.py b/src/transformers/models/__init__.py index 1c35a5e99ec7..69be04f9d81f 100644 --- a/src/transformers/models/__init__.py +++ b/src/transformers/models/__init__.py @@ -248,6 +248,7 @@ from .informer import * from .inkling import * from .inkling2 import * + from .inkling2_loop import * from .instructblip import * from .instructblipvideo import * from .internlm3 import * diff --git a/src/transformers/models/auto/auto_mappings.py b/src/transformers/models/auto/auto_mappings.py index 9f0792b865ee..d15bd78b34f4 100644 --- a/src/transformers/models/auto/auto_mappings.py +++ b/src/transformers/models/auto/auto_mappings.py @@ -345,6 +345,8 @@ ("imagegpt", "ImageGPTConfig"), ("informer", "InformerConfig"), ("inkling2", "Inkling2Config"), + ("inkling2_loop", "Inkling2LoopConfig"), + ("inkling2_loop_text", "Inkling2LoopTextConfig"), ("inkling2_text", "Inkling2TextConfig"), ("inkling2_vision", "Inkling2VisionConfig"), ("inkling_audio", "InklingAudioConfig"), @@ -957,6 +959,7 @@ ("idefics3_vision", "idefics3"), ("idefics_perciever", "idefics"), ("idefics_vision", "idefics"), + ("inkling2_loop_text", "inkling2_loop"), ("inkling2_text", "inkling2"), ("inkling2_vision", "inkling2"), ("inkling_audio", "inkling"), diff --git a/src/transformers/models/auto/image_processing_auto.py b/src/transformers/models/auto/image_processing_auto.py index 0821f5e039c1..58b07c7d6d92 100644 --- a/src/transformers/models/auto/image_processing_auto.py +++ b/src/transformers/models/auto/image_processing_auto.py @@ -106,6 +106,7 @@ {"torchvision": "Qwen2VLImageProcessor", "pil": "Qwen2VLImageProcessorPil"}, ), ("ijepa", {"torchvision": "ViTImageProcessor", "pil": "ViTImageProcessorPil"}), + ("inkling2_loop", {"torchvision": "Inkling2ImageProcessor"}), ("inkling_mm_model", {"torchvision": "InklingImageProcessor"}), ("instructblip", {"torchvision": "BlipImageProcessor", "pil": "BlipImageProcessorPil"}), ("internvl", {"torchvision": "GotOcr2ImageProcessor", "pil": "GotOcr2ImageProcessorPil"}), diff --git a/src/transformers/models/auto/modeling_auto.py b/src/transformers/models/auto/modeling_auto.py index c3c0fb111334..ca55fea40b90 100644 --- a/src/transformers/models/auto/modeling_auto.py +++ b/src/transformers/models/auto/modeling_auto.py @@ -292,6 +292,8 @@ class _BaseModelWithGenerate(PreTrainedModel, GenerationMixin): ("imagegpt", "ImageGPTModel"), ("informer", "InformerModel"), ("inkling2", "Inkling2Model"), + ("inkling2_loop", "Inkling2LoopModel"), + ("inkling2_loop_text", "Inkling2LoopTextModel"), ("inkling2_text", "Inkling2TextModel"), ("inkling2_vision", "Inkling2VisionModel"), ("inkling_mm_model", "InklingModel"), @@ -709,6 +711,7 @@ class _BaseModelWithGenerate(PreTrainedModel, GenerationMixin): ("idefics2", "Idefics2ForConditionalGeneration"), ("idefics3", "Idefics3ForConditionalGeneration"), ("inkling2", "Inkling2ForConditionalGeneration"), + ("inkling2_loop", "Inkling2LoopForConditionalGeneration"), ("inkling_mm_model", "InklingForConditionalGeneration"), ("janus", "JanusForConditionalGeneration"), ("layoutlm", "LayoutLMForMaskedLM"), @@ -872,6 +875,7 @@ class _BaseModelWithGenerate(PreTrainedModel, GenerationMixin): ("hy_v3", "HYV3ForCausalLM"), ("hy_v4", "HYV4ForCausalLM"), ("hyperclovax", "HyperCLOVAXForCausalLM"), + ("inkling2_loop_text", "Inkling2LoopForCausalLM"), ("inkling2_text", "Inkling2ForCausalLM"), ("inkling_text", "InklingForCausalLM"), ("internlm3", "LlamaForCausalLM"), @@ -1225,6 +1229,7 @@ class _BaseModelWithGenerate(PreTrainedModel, GenerationMixin): ("idefics2", "Idefics2ForConditionalGeneration"), ("idefics3", "Idefics3ForConditionalGeneration"), ("inkling2", "Inkling2ForConditionalGeneration"), + ("inkling2_loop", "Inkling2LoopForConditionalGeneration"), ("inkling_mm_model", "InklingForConditionalGeneration"), ("instructblip", "InstructBlipForConditionalGeneration"), ("instructblipvideo", "InstructBlipVideoForConditionalGeneration"), diff --git a/src/transformers/models/auto/processing_auto.py b/src/transformers/models/auto/processing_auto.py index 4d639b4e6fe7..142b508e273f 100644 --- a/src/transformers/models/auto/processing_auto.py +++ b/src/transformers/models/auto/processing_auto.py @@ -65,6 +65,7 @@ ("granite_speech_plus", "GraniteSpeechProcessor"), ("groupvit", "CLIPProcessor"), ("hubert", "Wav2Vec2Processor"), + ("inkling2_loop", "Inkling2Processor"), ("inkling_mm_model", "InklingProcessor"), ("lasr_ctc", "LasrProcessor"), ("lasr_encoder", "LasrProcessor"), diff --git a/src/transformers/models/inkling2/configuration_inkling2.py b/src/transformers/models/inkling2/configuration_inkling2.py index cec7b73f0695..ffb750f5baea 100644 --- a/src/transformers/models/inkling2/configuration_inkling2.py +++ b/src/transformers/models/inkling2/configuration_inkling2.py @@ -29,7 +29,8 @@ class Inkling2TextConfig(PreTrainedConfig): r""" unpadded_vocab_size (`int`, *optional*, defaults to 200058): - Number of rows of the unembedding matrix that hold real tokens. Logits beyond it are dropped. + Output size of the language modeling head. The checkpoint unembedding is padded to `vocab_size`, the padded + rows are dropped on load and restored as zeros on save. swa_num_attention_heads (`int`, *optional*, defaults to 48): Number of attention heads in the sliding-window layers. swa_num_key_value_heads (`int`, *optional*, defaults to 8): diff --git a/src/transformers/models/inkling2/modeling_inkling2.py b/src/transformers/models/inkling2/modeling_inkling2.py index 83e2f839a72a..b18924484bba 100644 --- a/src/transformers/models/inkling2/modeling_inkling2.py +++ b/src/transformers/models/inkling2/modeling_inkling2.py @@ -37,7 +37,12 @@ use_kernelized_func, ) from ...integrations.accelerate import force_accelerate_hooks -from ...masking_utils import create_causal_mask, create_recurrent_attention_mask, create_sliding_window_causal_mask +from ...masking_utils import ( + create_causal_mask, + create_recurrent_attention_mask, + create_sliding_window_causal_mask, + find_first_full_attention_index, +) from ...modeling_layers import GradientCheckpointingLayer from ...modeling_outputs import ( BaseModelOutputWithPooling, @@ -118,8 +123,11 @@ def __init__(self, eps: float = 1.0e-6): super().__init__() self.eps = eps - def forward(self, x: torch.Tensor) -> torch.Tensor: - return x * torch.rsqrt(x.float().square().mean(-1, keepdim=True) + self.eps).to(x.dtype) + 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 Inkling2L2Clip(nn.Module): @@ -144,37 +152,79 @@ def __init__(self, num_heads: int, head_dim: int, threshold: float): self.threshold = threshold self.scale = nn.Parameter(torch.ones(num_heads, head_dim)) - def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: + 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 Inkling2RelativeLogits(nn.Module): - """hidden states conditioned relative position bias. `proj` is a trained bank of bias-vs-distance profiles; each token's - `relative_states` mixes them into one bias value per backward distance - (`sglang RelLogitsProj` + the FA4 `score_mod`, materialized densely). The bias is zero - outside `0 <= distance < rel_extent`; causality and padding stay in the attention mask. +class Inkling2LogScale(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: Inkling2TextConfig): + 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 Inkling2LogScaledL2Clip(nn.Module): + """`Inkling2ScaledL2Clip` followed by `Inkling2LogScale`.""" + + # trf-ignore: TRF029 (num_heads and head_dim depend on the attention layer type) + def __init__(self, config: Inkling2TextConfig, num_heads: int, head_dim: int, threshold: float): + super().__init__() + self.scale = nn.Parameter(torch.ones(num_heads, head_dim)) + self.l2_clip = Inkling2L2Clip(threshold) + self.log_scale = Inkling2LogScale(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 Inkling2RelativePositionBias(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 + `Inkling2LogScale`. """ - def __init__(self, d_rel: int, rel_extent: int): + # trf-ignore: TRF029 (num_heads depends on the attention layer type) + def __init__(self, config: Inkling2TextConfig, num_heads: int, rel_extent: int, log_scaling: bool): super().__init__() + self.num_heads = num_heads self.rel_extent = rel_extent - self.proj = nn.Parameter(torch.empty(d_rel, rel_extent)) + self.linear = nn.Linear(config.hidden_size, num_heads * config.d_rel, bias=False) + self.norm = ( + Inkling2LogScaledL2Clip(config, num_heads, config.d_rel, config.rel_l2_clip_threshold) + if log_scaling + else Inkling2ScaledL2Clip(num_heads, config.d_rel, config.rel_l2_clip_threshold) + ) + self.proj = nn.Parameter(torch.empty(config.d_rel, rel_extent)) def forward( - self, - relative_states: torch.Tensor, - query_positions: torch.Tensor, - key_positions: torch.Tensor, + 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) - distance = (query_positions[:, None] - key_positions[None, :])[None, None, :, :] - gather_index = distance.clamp(0, self.rel_extent - 1).expand(*rel_logits.shape[:2], -1, -1) + 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((distance < 0) | (distance >= self.rel_extent), 0.0) + 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): @@ -254,10 +304,19 @@ def __init__(self, hidden_size: int, conv_kernel_size: int, layer_idx: int, conv 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 `Inkling2DynamicShortConvolution`. + 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() @@ -266,16 +325,16 @@ def forward( 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(self.layer_idx, state_idx=self.conv_idx) + 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(self.layer_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, self.layer_idx, state_idx=self.conv_idx, conv_kernel_size=self.conv_kernel_size + hidden_states, cache_layer_idx, state_idx=self.conv_idx, conv_kernel_size=self.conv_kernel_size ) hidden_states = causal_conv1d_fn( @@ -316,8 +375,13 @@ def forward( 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() @@ -329,17 +393,113 @@ def forward( 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, state_idx=self.conv_idx, conv_kernel_size=self.conv_kernel_size + 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 Inkling2QueryProjection(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: Inkling2TextConfig, 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 = ( + Inkling2LogScaledL2Clip(config, num_heads, head_dim, config.qk_l2_clip_threshold) + if log_scaling + else Inkling2ScaledL2Clip(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 Inkling2KeyValueProjection(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: Inkling2TextConfig, + 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 = ( + Inkling2DynamicShortConvolution( + num_heads * head_dim, + config.hidden_size, + num_heads, + config.sconv_kernel_size, + layer_idx, + conv_idx=conv_idx, + ) + if dynamic + else Inkling2ShortConvolution( + num_heads * head_dim, config.sconv_kernel_size, layer_idx, conv_idx=conv_idx + ).to(dtype=torch.float32) + ) + self.norm = ( + Inkling2L2Clip(config.qk_l2_clip_threshold) + if is_key + else Inkling2UnweightedRMSNorm(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 Inkling2GatedOutputProjection(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: Inkling2TextConfig, 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) + + 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, @@ -401,71 +561,65 @@ def __init__(self, config: Inkling2TextConfig, layer_idx: int): self.scaling = self.head_dim**-0.5 self.attention_dropout = config.attention_dropout self.is_causal = True - - self.q_proj = nn.Linear(config.hidden_size, self.num_heads * self.head_dim, bias=False) - self.k_proj = nn.Linear(config.hidden_size, self.num_key_value_heads * self.head_dim, bias=False) - self.v_proj = nn.Linear(config.hidden_size, self.num_key_value_heads * self.head_dim, bias=False) - self.r_proj = nn.Linear(config.hidden_size, self.num_heads * config.d_rel, bias=False) - self.o_proj = nn.Linear(self.num_heads * self.head_dim, config.hidden_size, bias=False) - self.k_sconv = Inkling2ShortConvolution( - self.num_key_value_heads * self.head_dim, config.sconv_kernel_size, layer_idx, conv_idx=0 - ).to(dtype=torch.float32) - self.v_sconv = Inkling2ShortConvolution( - self.num_key_value_heads * self.head_dim, config.sconv_kernel_size, layer_idx, conv_idx=1 - ).to(dtype=torch.float32) - self.rel_logits_proj = Inkling2RelativeLogits(config.d_rel, self.rel_extent) - self.gate_proj = nn.Linear(config.hidden_size, self.num_heads * self.head_dim, bias=False) + self.q_proj = Inkling2QueryProjection(config, self.num_heads, self.head_dim, log_scaling=False) + self.k_proj = Inkling2KeyValueProjection( + config, self.num_key_value_heads, self.head_dim, layer_idx, conv_idx=0, is_key=True + ) + self.v_proj = Inkling2KeyValueProjection( + config, self.num_key_value_heads, self.head_dim, layer_idx, conv_idx=1, is_key=False + ) + self.o_proj = Inkling2GatedOutputProjection(config, self.num_heads, self.head_dim) self.sink_proj = nn.Linear(config.hidden_size, self.num_heads, bias=False) - self.q_l2_clip = Inkling2ScaledL2Clip(self.num_heads, self.head_dim, config.qk_l2_clip_threshold) - self.k_l2_clip = Inkling2L2Clip(config.qk_l2_clip_threshold) - self.rel_l2_clip = Inkling2ScaledL2Clip(self.num_heads, config.d_rel, config.rel_l2_clip_threshold) - self.v_norm = Inkling2UnweightedRMSNorm(eps=config.rms_norm_eps) + self.relative_position_bias = Inkling2RelativePositionBias( + 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] - hidden_shape = (*input_shape, -1, self.head_dim) - query_states = self.q_proj(hidden_states) - key_states = self.k_sconv(self.k_proj(hidden_states), cache=cache, conv_mask=conv_mask) - value_states = self.v_sconv(self.v_proj(hidden_states), cache=cache, conv_mask=conv_mask) - relative_states = self.r_proj(hidden_states) - gate = self.gate_proj(hidden_states) - sinks = self.sink_proj(hidden_states) - - q_length = query_states.shape[1] - if cache is not None: - kv_length, kv_offset = cache.get_mask_sizes(q_length, self.layer_idx) - q_offset = cache.get_query_offset(self.layer_idx) - else: - kv_length = q_length - q_offset, kv_offset = 0, 0 - kv_positions = torch.arange(kv_length, device=hidden_states.device) + kv_offset - q_positions = torch.arange(q_length, device=hidden_states.device) + q_offset - - query_states = self.q_l2_clip(query_states.view(hidden_shape)).transpose(1, 2) - key_states = self.k_l2_clip(key_states.view(hidden_shape)).transpose(1, 2) - value_states = value_states.view(hidden_shape) - value_states = self.v_norm(value_states.float()).to(value_states.dtype) - value_states = value_states.transpose(1, 2) - relative_states = self.rel_l2_clip(relative_states.view(*input_shape, self.num_heads, -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, self.layer_idx, kwargs=kwargs) - - position_bias = self.rel_logits_proj(relative_states, q_positions, kv_positions) + 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, @@ -476,13 +630,12 @@ def forward( scaling=self.scaling, sliding_window=self.sliding_window, position_bias=position_bias, - sinks=sinks.transpose(1, 2).unsqueeze(-1), + sinks=sinks, **kwargs, ) attn_output = attn_output.reshape(*input_shape, -1).contiguous() - attn_output = (attn_output.float() * torch.sigmoid(gate.float())).to(attn_output.dtype) - attn_output = self.o_proj(attn_output) + attn_output = self.o_proj(attn_output, hidden_states) return attn_output, attn_weights @@ -501,35 +654,18 @@ def __init__(self, config: Inkling2TextConfig, layer_idx: int): self.scaling = self.head_dim**-0.5 self.attention_dropout = config.attention_dropout self.is_causal = True - - self.q_proj = nn.Linear(config.hidden_size, self.num_heads * self.head_dim, bias=False) - self.k_proj = nn.Linear(config.hidden_size, self.num_key_value_heads * self.head_dim, bias=False) - self.v_proj = nn.Linear(config.hidden_size, self.num_key_value_heads * self.head_dim, bias=False) - self.r_proj = nn.Linear(config.hidden_size, self.num_heads * config.d_rel, bias=False) - self.o_proj = nn.Linear(self.num_heads * self.head_dim, config.hidden_size, bias=False) - self.k_sconv = Inkling2DynamicShortConvolution( - self.num_key_value_heads * self.head_dim, - config.hidden_size, - self.num_key_value_heads, - config.sconv_kernel_size, - layer_idx, - conv_idx=0, + self.q_proj = Inkling2QueryProjection(config, self.num_heads, self.head_dim, log_scaling=True) + self.k_proj = Inkling2KeyValueProjection( + config, self.num_key_value_heads, self.head_dim, layer_idx, conv_idx=0, is_key=True, dynamic=True ) - self.v_sconv = Inkling2DynamicShortConvolution( - self.num_key_value_heads * self.head_dim, - config.hidden_size, - self.num_key_value_heads, - config.sconv_kernel_size, - layer_idx, - conv_idx=1, + self.v_proj = Inkling2KeyValueProjection( + config, self.num_key_value_heads, self.head_dim, layer_idx, conv_idx=1, is_key=False, dynamic=True ) - self.rel_logits_proj = Inkling2RelativeLogits(config.d_rel, self.rel_extent) - self.gate_proj = nn.Linear(config.hidden_size, self.num_heads * self.head_dim, bias=False) + self.o_proj = Inkling2GatedOutputProjection(config, self.num_heads, self.head_dim) self.sink_proj = nn.Linear(config.hidden_size, self.num_heads, bias=False) - self.q_l2_clip = Inkling2ScaledL2Clip(self.num_heads, self.head_dim, config.qk_l2_clip_threshold) - self.k_l2_clip = Inkling2L2Clip(config.qk_l2_clip_threshold) - self.rel_l2_clip = Inkling2ScaledL2Clip(self.num_heads, config.d_rel, config.rel_l2_clip_threshold) - self.v_norm = Inkling2UnweightedRMSNorm(eps=config.rms_norm_eps) + self.relative_position_bias = Inkling2RelativePositionBias( + config, self.num_heads, self.rel_extent, log_scaling=True + ) @deprecate_kwarg("past_key_values", "5.40.0", new_name="cache") def forward( @@ -538,65 +674,43 @@ def forward( 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] - hidden_shape = (*input_shape, -1, self.head_dim) - query_states = self.q_proj(hidden_states) - key_states = self.k_sconv(self.k_proj(key_hidden_states), key_hidden_states, cache=cache, conv_mask=conv_mask) - value_states = self.v_sconv( - self.v_proj(value_hidden_states), - value_hidden_states, - cache=cache, - conv_mask=conv_mask, + 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 ) - relative_states = self.r_proj(hidden_states) - gate = self.gate_proj(hidden_states) - sinks = self.sink_proj(hidden_states) - - q_length = query_states.shape[1] - if cache is not None: - kv_length, kv_offset = cache.get_mask_sizes(q_length, self.layer_idx) - q_offset = cache.get_query_offset(self.layer_idx) - else: - kv_length = q_length - q_offset, kv_offset = 0, 0 - kv_positions = torch.arange(kv_length, device=hidden_states.device) + kv_offset - q_positions = torch.arange(q_length, device=hidden_states.device) + q_offset - - # log scaling of the queries and relative states, in fp32 as in the original - tau = 1.0 + self.config.log_scaling_alpha * torch.log( - ((kwargs["position_ids"] + 1).float() / self.config.log_scaling_n_floor).clamp(min=1.0) + value_states = self.v_proj( + value_hidden_states, cache=cache, conv_mask=conv_mask, cache_offset=cache_offset, **kwargs ) - tau = tau[..., None, None] - - query_states = self.q_l2_clip(query_states.view(hidden_shape)) - query_states = (query_states.float() * tau).to(query_states.dtype).transpose(1, 2) - key_states = self.k_l2_clip(key_states.view(hidden_shape)).transpose(1, 2) - value_states = value_states.view(hidden_shape) - value_states = self.v_norm(value_states.float()).to(value_states.dtype) - value_states = value_states.transpose(1, 2) - relative_states = self.rel_l2_clip(relative_states.view(*input_shape, self.num_heads, -1)) - relative_states = (relative_states.float() * tau).to(relative_states.dtype) if cache is not None: - key_states, value_states = cache.update(key_states, value_states, self.layer_idx, kwargs=kwargs) - - position_bias = self.rel_logits_proj(relative_states, q_positions, kv_positions) + 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, @@ -607,13 +721,12 @@ def forward( scaling=self.scaling, sliding_window=self.sliding_window, position_bias=position_bias, - sinks=sinks.transpose(1, 2).unsqueeze(-1), + sinks=sinks, **kwargs, ) attn_output = attn_output.reshape(*input_shape, -1).contiguous() - attn_output = (attn_output.float() * torch.sigmoid(gate.float())).to(attn_output.dtype) - attn_output = self.o_proj(attn_output) + attn_output = self.o_proj(attn_output, hidden_states) return attn_output, attn_weights @@ -723,6 +836,9 @@ def __init__(self, config: Inkling2TextConfig, num_queries: int = 1): 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 = Inkling2UnweightedRMSNorm() + 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() @@ -731,10 +847,15 @@ def forward(self, block_states: torch.Tensor, partial_block_states: torch.Tensor 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) - attn_output = F.scaled_dot_product_attention( - query_states, stacked_states, stacked_states, scale=hidden_size**-0.5 + + attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface( + self.config._attn_implementation, eager_attention_forward ) - return attn_output.unbind(-2) + + 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 Inkling2SlidingDecoderLayer(GradientCheckpointingLayer): @@ -762,6 +883,7 @@ def forward( 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], @@ -774,11 +896,12 @@ def forward( 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) + 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: @@ -788,7 +911,7 @@ def forward( 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) + hidden_states = self.post_mlp_convolution(hidden_states, cache=cache, conv_mask=conv_mask, **kwargs) return (residual + hidden_states).to(dtype) @@ -819,6 +942,7 @@ def forward( 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], @@ -837,11 +961,12 @@ def forward( 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) + 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: @@ -851,7 +976,7 @@ def forward( 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) + hidden_states = self.post_mlp_convolution(hidden_states, cache=cache, conv_mask=conv_mask, **kwargs) return (residual + hidden_states).to(dtype) @@ -1147,8 +1272,7 @@ class Inkling2PreTrainedModel(PreTrainedModel): base_model_prefix = "model" supports_gradient_checkpointing = True _no_split_modules = ["Inkling2SlidingDecoderLayer", "Inkling2FullDecoderLayer", "Inkling2VisionEncoderLayer"] - # The relative position bias flows through the attention interface as a `position_bias` (duh) - # kwarg that only the eager path consumes; other backends need a score_mod/kernel + # Disabled because of the per-token attention sinks _supports_flash_attn = False _supports_sdpa = False _supports_flex_attn = False @@ -1159,8 +1283,7 @@ class Inkling2PreTrainedModel(PreTrainedModel): "mlp.gate.weight", "post_attention_convolution", "post_mlp_convolution", - "k_sconv.conv1d", - "v_sconv.conv1d", + "sconv.conv1d", "attention_input", "mlp_input", "final_input", @@ -1174,7 +1297,7 @@ class Inkling2PreTrainedModel(PreTrainedModel): def _init_weights(self, module): super()._init_weights(module) std = self.config.get_text_config().initializer_range - if isinstance(module, Inkling2RelativeLogits): + if isinstance(module, Inkling2RelativePositionBias): init.normal_(module.proj, mean=0.0, std=std) elif isinstance(module, Inkling2Experts): init.normal_(module.gate_up_proj, mean=0.0, std=std) @@ -1182,18 +1305,12 @@ def _init_weights(self, module): elif isinstance(module, Inkling2TopKRouter): init.normal_(module.weight, mean=0.0, std=std) init.zeros_(module.e_score_correction_bias) - elif isinstance(module, Inkling2ScaledL2Clip): + elif isinstance(module, (Inkling2ScaledL2Clip, Inkling2LogScaledL2Clip)): init.ones_(module.scale) elif isinstance(module, Inkling2DynamicShortConvolution): init.zeros_(module.static_weight) elif isinstance(module, Inkling2BlockAttentionResidual): init.zeros_(module.query) - elif isinstance(module, Inkling2VisionEmbeddings): - init.normal_(module.class_embedding, mean=0.0, std=std) - init.normal_(module.cls_position_embedding, mean=0.0, std=std) - elif isinstance(module, Inkling2VisionEncoderLayer): - init.constant_(module.lambda_1, module.config.layer_scale_init_value) - init.constant_(module.lambda_2, module.config.layer_scale_init_value) class Inkling2NormedEmbedding(nn.Embedding): @@ -1205,6 +1322,28 @@ 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 Inkling2TextModel(Inkling2PreTrainedModel): config: Inkling2TextConfig @@ -1273,6 +1412,10 @@ def forward( "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]) @@ -1281,6 +1424,7 @@ def forward( 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, @@ -1311,7 +1455,7 @@ def __init__(self, config: Inkling2TextConfig): super().__init__(config) self.model = Inkling2TextModel(config) self.vocab_size = config.vocab_size - self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False) + self.lm_head = nn.Linear(config.hidden_size, config.unpadded_vocab_size, bias=False) self.logit_softcap = Inkling2Softcap(config.final_logit_softcapping) # Initialize weights and apply final processing @@ -1370,7 +1514,6 @@ def forward( 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) - logits = logits[..., : self.config.unpadded_vocab_size] loss = None if labels is not None: @@ -1407,6 +1550,16 @@ def __init__(self, config: Inkling2VisionConfig): self.merger = Inkling2VisionMerger(config) self.post_init() + def _init_weights(self, module): + super()._init_weights(module) + std = self.config.initializer_range + if isinstance(module, Inkling2VisionEmbeddings): + init.normal_(module.class_embedding, mean=0.0, std=std) + init.normal_(module.cls_position_embedding, mean=0.0, std=std) + elif isinstance(module, Inkling2VisionEncoderLayer): + init.constant_(module.lambda_1, module.config.layer_scale_init_value) + init.constant_(module.lambda_2, module.config.layer_scale_init_value) + @capture_outputs @auto_docstring def forward( @@ -1617,9 +1770,7 @@ class Inkling2ForConditionalGeneration(Inkling2PreTrainedModel, GenerationMixin) def __init__(self, config: Inkling2Config): super().__init__(config) self.model = Inkling2Model(config) - # checkpoints store `unembed` padded to vocab_size; logits are sliced to - # unpadded_vocab_size in forward, like sglang - self.lm_head = nn.Linear(config.text_config.hidden_size, config.text_config.vocab_size, bias=False) + self.lm_head = nn.Linear(config.text_config.hidden_size, config.text_config.unpadded_vocab_size, bias=False) self.logit_softcap = Inkling2Softcap(config.text_config.final_logit_softcapping) self.post_init() @@ -1701,11 +1852,9 @@ def forward( **kwargs, ) - text_config = self.config.text_config 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) - logits = logits[..., : text_config.unpadded_vocab_size] loss = None if labels is not None: diff --git a/src/transformers/models/inkling2/modular_inkling2.py b/src/transformers/models/inkling2/modular_inkling2.py index b2f933398d78..d83829718c47 100644 --- a/src/transformers/models/inkling2/modular_inkling2.py +++ b/src/transformers/models/inkling2/modular_inkling2.py @@ -30,7 +30,12 @@ from ...image_utils import ChannelDimension, ImageInput, ImageType, SizeDict, get_image_type from ...integrations import use_experts_implementation, use_kernelized_func from ...integrations.accelerate import force_accelerate_hooks -from ...masking_utils import create_causal_mask, create_recurrent_attention_mask, create_sliding_window_causal_mask +from ...masking_utils import ( + create_causal_mask, + create_recurrent_attention_mask, + create_sliding_window_causal_mask, + find_first_full_attention_index, +) from ...modeling_layers import GradientCheckpointingLayer from ...modeling_outputs import BaseModelOutputWithPooling, MoeModelOutputWithPast from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel, slice_logits_to_keep @@ -52,7 +57,6 @@ InklingModel, InklingModelOutputWithPast, InklingPreTrainedModel, - InklingRelativeLogits, InklingShortConvolution, InklingTextModel, ) @@ -72,7 +76,8 @@ class Inkling2TextConfig(InklingTextConfig): r""" unpadded_vocab_size (`int`, *optional*, defaults to 200058): - Number of rows of the unembedding matrix that hold real tokens. Logits beyond it are dropped. + Output size of the language modeling head. The checkpoint unembedding is padded to `vocab_size`, the padded + rows are dropped on load and restored as zeros on save. swa_num_attention_heads (`int`, *optional*, defaults to 48): Number of attention heads in the sliding-window layers. swa_num_key_value_heads (`int`, *optional*, defaults to 8): @@ -259,7 +264,11 @@ class Inkling2RMSNorm(Olmo2RMSNorm): class Inkling2UnweightedRMSNorm(DeepseekV4UnweightedRMSNorm): - pass + 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 Inkling2L2Clip(nn.Module): @@ -284,15 +293,101 @@ def __init__(self, num_heads: int, head_dim: int, threshold: float): self.threshold = threshold self.scale = nn.Parameter(torch.ones(num_heads, head_dim)) - def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: + 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 Inkling2RelativeLogits(InklingRelativeLogits): - pass +class Inkling2LogScale(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: Inkling2TextConfig): + 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 Inkling2LogScaledL2Clip(nn.Module): + """`Inkling2ScaledL2Clip` followed by `Inkling2LogScale`.""" + + # trf-ignore: TRF029 (num_heads and head_dim depend on the attention layer type) + def __init__(self, config: Inkling2TextConfig, num_heads: int, head_dim: int, threshold: float): + super().__init__() + self.scale = nn.Parameter(torch.ones(num_heads, head_dim)) + self.l2_clip = Inkling2L2Clip(threshold) + self.log_scale = Inkling2LogScale(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) + + +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, :] + + +class Inkling2RelativePositionBias(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 + `Inkling2LogScale`. + """ + + # trf-ignore: TRF029 (num_heads depends on the attention layer type) + def __init__(self, config: Inkling2TextConfig, 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 = ( + Inkling2LogScaledL2Clip(config, num_heads, config.d_rel, config.rel_l2_clip_threshold) + if log_scaling + else Inkling2ScaledL2Clip(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) @use_kernelized_func([causal_conv1d_update, causal_conv1d_fn]) @@ -302,10 +397,19 @@ class Inkling2ShortConvolution(InklingShortConvolution): 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 `Inkling2DynamicShortConvolution`. + 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() @@ -314,16 +418,16 @@ def forward( 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(self.layer_idx, state_idx=self.conv_idx) + 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(self.layer_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, self.layer_idx, state_idx=self.conv_idx, conv_kernel_size=self.conv_kernel_size + hidden_states, cache_layer_idx, state_idx=self.conv_idx, conv_kernel_size=self.conv_kernel_size ) hidden_states = causal_conv1d_fn( @@ -364,8 +468,13 @@ def forward( 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() @@ -377,17 +486,98 @@ def forward( 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, state_idx=self.conv_idx, conv_kernel_size=self.conv_kernel_size + 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 Inkling2QueryProjection(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: Inkling2TextConfig, 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 = ( + Inkling2LogScaledL2Clip(config, num_heads, head_dim, config.qk_l2_clip_threshold) + if log_scaling + else Inkling2ScaledL2Clip(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 Inkling2KeyValueProjection(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: Inkling2TextConfig, + 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 = ( + Inkling2DynamicShortConvolution( + num_heads * head_dim, + config.hidden_size, + num_heads, + config.sconv_kernel_size, + layer_idx, + conv_idx=conv_idx, + ) + if dynamic + else Inkling2ShortConvolution( + num_heads * head_dim, config.sconv_kernel_size, layer_idx, conv_idx=conv_idx + ).to(dtype=torch.float32) + ) + self.norm = ( + Inkling2L2Clip(config.qk_l2_clip_threshold) + if is_key + else Inkling2UnweightedRMSNorm(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) + + def eager_attention_forward( module: nn.Module, query: torch.Tensor, @@ -422,64 +612,90 @@ def eager_attention_forward( return attn_output, attn_weights +class Inkling2GatedOutputProjection(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: Inkling2TextConfig, 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 Inkling2SlidingAttention(InklingAttention): def __init__(self, config: Inkling2TextConfig, layer_idx: int): super().__init__(config, layer_idx) self.scaling = self.head_dim**-0.5 - self.gate_proj = nn.Linear(config.hidden_size, self.num_heads * self.head_dim, bias=False) + self.o_proj = Inkling2GatedOutputProjection(config, self.num_heads, self.head_dim) self.sink_proj = nn.Linear(config.hidden_size, self.num_heads, bias=False) - self.q_l2_clip = Inkling2ScaledL2Clip(self.num_heads, self.head_dim, config.qk_l2_clip_threshold) - self.k_l2_clip = Inkling2L2Clip(config.qk_l2_clip_threshold) - self.rel_l2_clip = Inkling2ScaledL2Clip(self.num_heads, config.d_rel, config.rel_l2_clip_threshold) - self.v_norm = Inkling2UnweightedRMSNorm(eps=config.rms_norm_eps) + self.q_proj = Inkling2QueryProjection(config, self.num_heads, self.head_dim, log_scaling=False) + self.k_proj = Inkling2KeyValueProjection( + config, self.num_key_value_heads, self.head_dim, layer_idx, conv_idx=0, is_key=True + ) + self.v_proj = Inkling2KeyValueProjection( + config, self.num_key_value_heads, self.head_dim, layer_idx, conv_idx=1, is_key=False + ) + self.relative_position_bias = Inkling2RelativePositionBias( + config, self.num_heads, self.rel_extent, log_scaling=False + ) del self.q_norm del self.k_norm + del self.r_proj + del self.rel_logits_proj + del self.k_sconv + del self.v_sconv @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] - hidden_shape = (*input_shape, -1, self.head_dim) - query_states = self.q_proj(hidden_states) - key_states = self.k_sconv(self.k_proj(hidden_states), cache=cache, conv_mask=conv_mask) - value_states = self.v_sconv(self.v_proj(hidden_states), cache=cache, conv_mask=conv_mask) - relative_states = self.r_proj(hidden_states) - gate = self.gate_proj(hidden_states) - sinks = self.sink_proj(hidden_states) - - q_length = query_states.shape[1] - if cache is not None: - kv_length, kv_offset = cache.get_mask_sizes(q_length, self.layer_idx) - q_offset = cache.get_query_offset(self.layer_idx) - else: - kv_length = q_length - q_offset, kv_offset = 0, 0 - kv_positions = torch.arange(kv_length, device=hidden_states.device) + kv_offset - q_positions = torch.arange(q_length, device=hidden_states.device) + q_offset - - query_states = self.q_l2_clip(query_states.view(hidden_shape)).transpose(1, 2) - key_states = self.k_l2_clip(key_states.view(hidden_shape)).transpose(1, 2) - value_states = value_states.view(hidden_shape) - value_states = self.v_norm(value_states.float()).to(value_states.dtype) - value_states = value_states.transpose(1, 2) - relative_states = self.rel_l2_clip(relative_states.view(*input_shape, self.num_heads, -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, self.layer_idx, kwargs=kwargs) - - position_bias = self.rel_logits_proj(relative_states, q_positions, kv_positions) + 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, @@ -490,13 +706,12 @@ def forward( scaling=self.scaling, sliding_window=self.sliding_window, position_bias=position_bias, - sinks=sinks.transpose(1, 2).unsqueeze(-1), + sinks=sinks, **kwargs, ) attn_output = attn_output.reshape(*input_shape, -1).contiguous() - attn_output = (attn_output.float() * torch.sigmoid(gate.float())).to(attn_output.dtype) - attn_output = self.o_proj(attn_output) + attn_output = self.o_proj(attn_output, hidden_states) return attn_output, attn_weights @@ -504,30 +719,24 @@ class Inkling2FullAttention(InklingAttention): def __init__(self, config: Inkling2TextConfig, layer_idx: int): super().__init__(config, layer_idx) self.scaling = self.head_dim**-0.5 - self.k_sconv = Inkling2DynamicShortConvolution( - self.num_key_value_heads * self.head_dim, - config.hidden_size, - self.num_key_value_heads, - config.sconv_kernel_size, - layer_idx, - conv_idx=0, + self.o_proj = Inkling2GatedOutputProjection(config, self.num_heads, self.head_dim) + self.sink_proj = nn.Linear(config.hidden_size, self.num_heads, bias=False) + self.q_proj = Inkling2QueryProjection(config, self.num_heads, self.head_dim, log_scaling=True) + self.k_proj = Inkling2KeyValueProjection( + config, self.num_key_value_heads, self.head_dim, layer_idx, conv_idx=0, is_key=True, dynamic=True ) - self.v_sconv = Inkling2DynamicShortConvolution( - self.num_key_value_heads * self.head_dim, - config.hidden_size, - self.num_key_value_heads, - config.sconv_kernel_size, - layer_idx, - conv_idx=1, + self.v_proj = Inkling2KeyValueProjection( + config, self.num_key_value_heads, self.head_dim, layer_idx, conv_idx=1, is_key=False, dynamic=True + ) + self.relative_position_bias = Inkling2RelativePositionBias( + config, self.num_heads, self.rel_extent, log_scaling=True ) - self.gate_proj = nn.Linear(config.hidden_size, self.num_heads * self.head_dim, bias=False) - self.sink_proj = nn.Linear(config.hidden_size, self.num_heads, bias=False) - self.q_l2_clip = Inkling2ScaledL2Clip(self.num_heads, self.head_dim, config.qk_l2_clip_threshold) - self.k_l2_clip = Inkling2L2Clip(config.qk_l2_clip_threshold) - self.rel_l2_clip = Inkling2ScaledL2Clip(self.num_heads, config.d_rel, config.rel_l2_clip_threshold) - self.v_norm = Inkling2UnweightedRMSNorm(eps=config.rms_norm_eps) del self.q_norm del self.k_norm + del self.r_proj + del self.rel_logits_proj + del self.k_sconv + del self.v_sconv @deprecate_kwarg("past_key_values", "5.40.0", new_name="cache") def forward( @@ -536,65 +745,43 @@ def forward( 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] - hidden_shape = (*input_shape, -1, self.head_dim) - query_states = self.q_proj(hidden_states) - key_states = self.k_sconv(self.k_proj(key_hidden_states), key_hidden_states, cache=cache, conv_mask=conv_mask) - value_states = self.v_sconv( - self.v_proj(value_hidden_states), - value_hidden_states, - cache=cache, - conv_mask=conv_mask, + 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 ) - relative_states = self.r_proj(hidden_states) - gate = self.gate_proj(hidden_states) - sinks = self.sink_proj(hidden_states) - - q_length = query_states.shape[1] - if cache is not None: - kv_length, kv_offset = cache.get_mask_sizes(q_length, self.layer_idx) - q_offset = cache.get_query_offset(self.layer_idx) - else: - kv_length = q_length - q_offset, kv_offset = 0, 0 - kv_positions = torch.arange(kv_length, device=hidden_states.device) + kv_offset - q_positions = torch.arange(q_length, device=hidden_states.device) + q_offset - - # log scaling of the queries and relative states, in fp32 as in the original - tau = 1.0 + self.config.log_scaling_alpha * torch.log( - ((kwargs["position_ids"] + 1).float() / self.config.log_scaling_n_floor).clamp(min=1.0) + value_states = self.v_proj( + value_hidden_states, cache=cache, conv_mask=conv_mask, cache_offset=cache_offset, **kwargs ) - tau = tau[..., None, None] - - query_states = self.q_l2_clip(query_states.view(hidden_shape)) - query_states = (query_states.float() * tau).to(query_states.dtype).transpose(1, 2) - key_states = self.k_l2_clip(key_states.view(hidden_shape)).transpose(1, 2) - value_states = value_states.view(hidden_shape) - value_states = self.v_norm(value_states.float()).to(value_states.dtype) - value_states = value_states.transpose(1, 2) - relative_states = self.rel_l2_clip(relative_states.view(*input_shape, self.num_heads, -1)) - relative_states = (relative_states.float() * tau).to(relative_states.dtype) if cache is not None: - key_states, value_states = cache.update(key_states, value_states, self.layer_idx, kwargs=kwargs) - - position_bias = self.rel_logits_proj(relative_states, q_positions, kv_positions) + 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, @@ -605,13 +792,12 @@ def forward( scaling=self.scaling, sliding_window=self.sliding_window, position_bias=position_bias, - sinks=sinks.transpose(1, 2).unsqueeze(-1), + sinks=sinks, **kwargs, ) attn_output = attn_output.reshape(*input_shape, -1).contiguous() - attn_output = (attn_output.float() * torch.sigmoid(gate.float())).to(attn_output.dtype) - attn_output = self.o_proj(attn_output) + attn_output = self.o_proj(attn_output, hidden_states) return attn_output, attn_weights @@ -692,6 +878,9 @@ def __init__(self, config: Inkling2TextConfig, num_queries: int = 1): 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 = Inkling2UnweightedRMSNorm() + 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() @@ -700,10 +889,15 @@ def forward(self, block_states: torch.Tensor, partial_block_states: torch.Tensor 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) - attn_output = F.scaled_dot_product_attention( - query_states, stacked_states, stacked_states, scale=hidden_size**-0.5 + + attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface( + self.config._attn_implementation, eager_attention_forward ) - return attn_output.unbind(-2) + + 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 Inkling2SlidingDecoderLayer(GradientCheckpointingLayer): @@ -731,6 +925,7 @@ def forward( 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], @@ -743,11 +938,12 @@ def forward( 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) + 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: @@ -757,7 +953,7 @@ def forward( 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) + hidden_states = self.post_mlp_convolution(hidden_states, cache=cache, conv_mask=conv_mask, **kwargs) return (residual + hidden_states).to(dtype) @@ -788,6 +984,7 @@ def forward( 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], @@ -806,11 +1003,12 @@ def forward( 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) + 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: @@ -820,7 +1018,7 @@ def forward( 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) + hidden_states = self.post_mlp_convolution(hidden_states, cache=cache, conv_mask=conv_mask, **kwargs) return (residual + hidden_states).to(dtype) @@ -943,6 +1141,8 @@ def __init__(self, config: Inkling2VisionConfig): class Inkling2PreTrainedModel(InklingPreTrainedModel): config: Inkling2Config _no_split_modules = ["Inkling2SlidingDecoderLayer", "Inkling2FullDecoderLayer", "Inkling2VisionEncoderLayer"] + # Disabled because of the per-token attention sinks + _supports_flash_attn = False _supports_sdpa = False _supports_flex_attn = False _can_record_outputs = { @@ -955,8 +1155,7 @@ class Inkling2PreTrainedModel(InklingPreTrainedModel): "mlp.gate.weight", "post_attention_convolution", "post_mlp_convolution", - "k_sconv.conv1d", - "v_sconv.conv1d", + "sconv.conv1d", "attention_input", "mlp_input", "final_input", @@ -966,7 +1165,7 @@ class Inkling2PreTrainedModel(InklingPreTrainedModel): def _init_weights(self, module): PreTrainedModel._init_weights(self, module) std = self.config.get_text_config().initializer_range - if isinstance(module, Inkling2RelativeLogits): + if isinstance(module, Inkling2RelativePositionBias): init.normal_(module.proj, mean=0.0, std=std) elif isinstance(module, Inkling2Experts): init.normal_(module.gate_up_proj, mean=0.0, std=std) @@ -974,18 +1173,12 @@ def _init_weights(self, module): elif isinstance(module, Inkling2TopKRouter): init.normal_(module.weight, mean=0.0, std=std) init.zeros_(module.e_score_correction_bias) - elif isinstance(module, Inkling2ScaledL2Clip): + elif isinstance(module, (Inkling2ScaledL2Clip, Inkling2LogScaledL2Clip)): init.ones_(module.scale) elif isinstance(module, Inkling2DynamicShortConvolution): init.zeros_(module.static_weight) elif isinstance(module, Inkling2BlockAttentionResidual): init.zeros_(module.query) - elif isinstance(module, Inkling2VisionEmbeddings): - init.normal_(module.class_embedding, mean=0.0, std=std) - init.normal_(module.cls_position_embedding, mean=0.0, std=std) - elif isinstance(module, Inkling2VisionEncoderLayer): - init.constant_(module.lambda_1, module.config.layer_scale_init_value) - init.constant_(module.lambda_2, module.config.layer_scale_init_value) @auto_docstring @@ -1043,6 +1236,10 @@ def forward( "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]) @@ -1051,6 +1248,7 @@ def forward( 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, @@ -1071,6 +1269,7 @@ def forward( class Inkling2ForCausalLM(InklingForCausalLM): def __init__(self, config: Inkling2TextConfig): super().__init__(config) + self.lm_head = nn.Linear(config.hidden_size, config.unpadded_vocab_size, bias=False) self.logit_softcap = Inkling2Softcap(config.final_logit_softcapping) @can_return_tuple @@ -1126,7 +1325,6 @@ def forward( 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) - logits = logits[..., : self.config.unpadded_vocab_size] loss = None if labels is not None: @@ -1163,6 +1361,16 @@ def __init__(self, config: Inkling2VisionConfig): self.merger = Inkling2VisionMerger(config) self.post_init() + def _init_weights(self, module): + super()._init_weights(module) + std = self.config.initializer_range + if isinstance(module, Inkling2VisionEmbeddings): + init.normal_(module.class_embedding, mean=0.0, std=std) + init.normal_(module.cls_position_embedding, mean=0.0, std=std) + elif isinstance(module, Inkling2VisionEncoderLayer): + init.constant_(module.lambda_1, module.config.layer_scale_init_value) + init.constant_(module.lambda_2, module.config.layer_scale_init_value) + @capture_outputs @auto_docstring def forward( @@ -1329,6 +1537,7 @@ class Inkling2ForConditionalGeneration(InklingForConditionalGeneration): def __init__(self, config: Inkling2Config): super().__init__(config) + self.lm_head = nn.Linear(config.text_config.hidden_size, config.text_config.unpadded_vocab_size, bias=False) self.logit_softcap = Inkling2Softcap(config.text_config.final_logit_softcapping) @auto_docstring @@ -1409,11 +1618,9 @@ def forward( **kwargs, ) - text_config = self.config.text_config 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) - logits = logits[..., : text_config.unpadded_vocab_size] loss = None if labels is not None: diff --git a/src/transformers/models/inkling2_loop/__init__.py b/src/transformers/models/inkling2_loop/__init__.py new file mode 100644 index 000000000000..7a9cb23fd008 --- /dev/null +++ b/src/transformers/models/inkling2_loop/__init__.py @@ -0,0 +1,33 @@ +# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨 +# This file was automatically generated from the modules in `src/transformers/models/inkling2_loop`. +# Do NOT edit this file manually as any edits will be overwritten by auto-generation of the file. +# A module is picked up once it exports a name through `__all__`. +# Regenerate the file with: `python utils/check_inits.py --fix_and_overwrite` +# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨 +# 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 typing import TYPE_CHECKING + +from ...utils import _LazyModule +from ...utils.import_utils import define_import_structure + + +if TYPE_CHECKING: + from .configuration_inkling2_loop import * + from .modeling_inkling2_loop import * +else: + import sys + + _file = globals()["__file__"] + sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__) diff --git a/src/transformers/models/inkling2_loop/configuration_inkling2_loop.py b/src/transformers/models/inkling2_loop/configuration_inkling2_loop.py new file mode 100644 index 000000000000..8553b3c99b99 --- /dev/null +++ b/src/transformers/models/inkling2_loop/configuration_inkling2_loop.py @@ -0,0 +1,210 @@ +# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨 +# This file was automatically generated from src/transformers/models/inkling2_loop/modular_inkling2_loop.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_inkling2_loop.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 huggingface_hub.dataclasses import strict + +from ...configuration_utils import PreTrainedConfig, SubConfigSpec +from ...utils import auto_docstring +from ..auto import AutoConfig + + +@auto_docstring(checkpoint="thinkingmachines/Inkling-2-Mini") +@strict +class Inkling2LoopTextConfig(PreTrainedConfig): + r""" + unpadded_vocab_size (`int`, *optional*, defaults to 200058): + Output size of the language modeling head. The checkpoint unembedding is padded to `vocab_size`, the padded + rows are dropped on load and restored as zeros on save. + swa_num_attention_heads (`int`, *optional*, defaults to 24): + Number of attention heads in the sliding-window layers. + swa_num_key_value_heads (`int`, *optional*, defaults to 8): + Number of key/value heads in the sliding-window layers. + swa_head_dim (`int`, *optional*, defaults to 128): + Dimension of query and key heads in the sliding-window layers. + sliding_window_size (`int`, *optional*, defaults to 1024): + Size of the sliding attention window used by layers whose `layer_types` entry is `"hybrid_sliding"`. + d_rel (`int`, *optional*, defaults to 16): + Per-head dimension of the relative states that are mixed into the relative position bias. + rel_extent (`int`, *optional*, defaults to 1024): + Backward distance, in tokens, over which the relative position bias is applied in the full-attention layers. + log_scaling_n_floor (`int`, *optional*, defaults to 8192): + Position from which queries and relative states are scaled up logarithmically in the full-attention layers. + log_scaling_alpha (`float`, *optional*, defaults to 0.1): + Strength of the logarithmic scaling controlled by `log_scaling_n_floor`. + qk_l2_clip_threshold (`float`, *optional*, defaults to 22.627416997969522): + Maximum L2 norm of each query and key head vector. Longer vectors are scaled down to this norm. + rel_l2_clip_threshold (`float`, *optional*, defaults to 8.0): + Maximum L2 norm of each relative-state head vector. + n_layers_per_attn_res_block (`int`, *optional*, defaults to 6): + Number of decoder layers summed into one block before the block becomes a source of the attention residuals. + mlp_gate_softcap (`float`, *optional*, defaults to 4.0): + Softcap applied to the linear part of the experts' gate projection. + mlp_up_softcap (`float`, *optional*, defaults to 25.0): + Softcap applied to the experts' up projection. + final_logit_softcapping (`float`, *optional*, defaults to 30.0): + Softcap applied to the output logits. + scoring_func (`str`, *optional*, defaults to `"sigmoid"`): + Activation turning the router logits into expert scores. + loop_layer_index_start (`int`, *optional*, defaults to 6): + Index of the first looped decoder layer. Must be a multiple of `n_layers_per_attn_res_block`. + loop_layer_index_end (`int`, *optional*, defaults to 18): + Index after the last looped decoder layer. Layers `loop_layer_index_start` to + `loop_layer_index_end - 1` are looped. Must be a multiple of `n_layers_per_attn_res_block`. + loop_num_passes (`int`, *optional*, defaults to 3): + Number of loops. + loop_gate_rank (`int`, *optional*, defaults to 64): + Rank of the message gate projections that mix the residual blocks of the previous pass into the current + one. + """ + + model_type = "inkling2_loop_text" + base_config_key = "text_config" + base_model_tp_plan = { + "embed_tokens": "replicate", + "layers.*.mlp.experts.gate_up_proj": "colwise", + "layers.*.mlp.experts.down_proj": "rowwise", + "layers.*.mlp.experts": "moe_tp_experts", + } + base_model_ep_plan = { + "layers.*.mlp.experts.gate_up_proj": "grouped_gemm", + "layers.*.mlp.experts.down_proj": "grouped_gemm", + "layers.*.mlp.experts": "ep_dispatch_experts", + } + attribute_map = { + "sliding_window": "sliding_window_size", + "num_local_experts": "n_routed_experts", + "sconv_kernel_size": "conv_kernel_size", + "model_max_length": "max_position_embeddings", + "intermediate_size": "moe_intermediate_size", + "routed_scaling_factor": "route_scale", + } + + vocab_size: int = 201024 + + unpadded_vocab_size: int = 200058 + + hidden_size: int = 2304 + num_hidden_layers: int = 24 + num_attention_heads: int = 24 + num_key_value_heads: int = 8 + head_dim: int = 128 + swa_num_attention_heads: int = 24 + swa_num_key_value_heads: int = 8 + swa_head_dim: int = 128 + sliding_window_size: int = 1024 + d_rel: int = 16 + rel_extent: int = 1024 + log_scaling_n_floor: int = 8192 + log_scaling_alpha: float = 0.1 + layer_types: list[str] | None = None + max_position_embeddings: int = 1048576 + rms_norm_eps: float = 1e-6 + conv_kernel_size: int = 4 + hidden_act: str = "silu" + moe_intermediate_size: int = 1152 + n_routed_experts: int = 128 + num_experts_per_tok: int = 8 + route_scale: float = 8.0 + attention_dropout: float = 0.0 + initializer_range: float = 0.02 + pad_token_id: int | None = None + bos_token_id: int | None = None + eos_token_id: int | None = 200006 + qk_l2_clip_threshold: float = 22.627416997969522 + rel_l2_clip_threshold: float = 8.0 + n_layers_per_attn_res_block: int = 6 + mlp_gate_softcap: float = 4.0 + mlp_up_softcap: float = 25.0 + final_logit_softcapping: float = 30.0 + scoring_func: str = "sigmoid" + use_cache: bool = True + number_of_conv_states = 4 + loop_layer_index_start: int = 6 + loop_layer_index_end: int = 18 + loop_num_passes: int = 3 + loop_gate_rank: int = 64 + + def __post_init__(self, **kwargs): + if (loop_config := kwargs.get("loop_config")) is not None: + self.loop_layer_index_start = loop_config.get("core_start", self.loop_layer_index_start) + self.loop_layer_index_end = loop_config.get("core_end", self.loop_layer_index_end) + self.loop_num_passes = loop_config.get("num_passes", self.loop_num_passes) + self.loop_gate_rank = loop_config.get("gate_rank", self.loop_gate_rank) + if self.layer_types is None: + self.layer_types = [ + "hybrid" if (i + 1) % 6 == 0 else "hybrid_sliding" for i in range(self.num_hidden_layers) + ] + super().__post_init__(**kwargs) + + def validate_architecture(self): + if self.loop_num_passes < 1: + raise ValueError(f"`loop_num_passes` ({self.loop_num_passes}) must be at least 1.") + if self.loop_layer_index_start <= 0: + raise ValueError(f"`loop_layer_index_start` ({self.loop_layer_index_start}) must be greater than 0.") + if self.loop_layer_index_start % self.n_layers_per_attn_res_block != 0: + raise ValueError( + f"`loop_layer_index_start` ({self.loop_layer_index_start}) must be a multiple of " + f"`n_layers_per_attn_res_block` ({self.n_layers_per_attn_res_block})." + ) + if self.loop_layer_index_end % self.n_layers_per_attn_res_block != 0: + raise ValueError( + f"`loop_layer_index_end` ({self.loop_layer_index_end}) must be a multiple of " + f"`n_layers_per_attn_res_block` ({self.n_layers_per_attn_res_block})." + ) + + @property + def total_num_hidden_layers(self) -> int: + """Total number of decoder layers visited in each forward pass. This takes looped layers into account.""" + num_loop_layers = self.loop_layer_index_end - self.loop_layer_index_start + return self.num_hidden_layers + (self.loop_num_passes - 1) * num_loop_layers + + +@auto_docstring(checkpoint="thinkingmachines/Inkling-2-Mini") +@strict +class Inkling2LoopConfig(PreTrainedConfig): + r""" + image_token_id (`int`, *optional*, defaults to 200054): + Token index of the image placeholders, each replaced by one image feature. + """ + + model_type = "inkling2_loop" + sub_configs_defaults = { + "text_config": Inkling2LoopTextConfig, + "vision_config": SubConfigSpec( + config_class=AutoConfig, + model_type="inkling2_vision", + init_kwargs={"text_hidden_size": 2304}, + ), + } + + text_config: Inkling2LoopTextConfig | dict | None = None + + vision_config: dict | PreTrainedConfig | None = None + image_token_id: int = 200054 + + def validate_architecture(self): + if self.vision_config.text_hidden_size != self.text_config.hidden_size: + raise ValueError( + f"`vision_config.text_hidden_size` ({self.vision_config.text_hidden_size}) must match " + f"`text_config.hidden_size` ({self.text_config.hidden_size})." + ) + + +__all__ = ["Inkling2LoopConfig", "Inkling2LoopTextConfig"] diff --git a/src/transformers/models/inkling2_loop/modeling_inkling2_loop.py b/src/transformers/models/inkling2_loop/modeling_inkling2_loop.py new file mode 100644 index 000000000000..78498834e280 --- /dev/null +++ b/src/transformers/models/inkling2_loop/modeling_inkling2_loop.py @@ -0,0 +1,1840 @@ +# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨 +# This file was automatically generated from src/transformers/models/inkling2_loop/modular_inkling2_loop.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_inkling2_loop.py file directly. One of our CI enforces this. +# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨 +# Copyright 2026 the HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import 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 ... import initialization as init +from ...activations import ACT2FN +from ...cache_utils import Cache, DynamicCache +from ...generation import GenerationMixin +from ...integrations import ( + use_experts_implementation, + use_kernel_forward_from_hub, + use_kernel_func_from_hub_with_fallback, + use_kernelized_func, +) +from ...integrations.accelerate import force_accelerate_hooks +from ...masking_utils import ( + create_causal_mask, + create_recurrent_attention_mask, + create_sliding_window_causal_mask, + find_first_full_attention_index, +) +from ...modeling_layers import GradientCheckpointingLayer +from ...modeling_outputs import ( + BaseModelOutputWithPooling, + MoeModelOutputWithPast, + MultimodalBaseModelOutputWithPast, + MultimodalCausalLMOutputWithPast, +) +from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel, slice_logits_to_keep +from ...processing_utils import Unpack +from ...utils import TransformersKwargs, auto_docstring, can_return_tuple, logging, torch_compilable_check +from ...utils.deprecation import deprecate_kwarg +from ...utils.generic import merge_with_config_defaults +from ...utils.output_capturing import OutputRecorder, capture_outputs +from ..auto import AutoModel +from .configuration_inkling2_loop import Inkling2LoopConfig, Inkling2LoopTextConfig + + +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, + **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) + 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, + **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) + 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 + + +@auto_docstring +class Inkling2LoopPreTrainedModel(PreTrainedModel): + config: Inkling2LoopConfig + base_model_prefix = "model" + supports_gradient_checkpointing = True + _no_split_modules = [ + "Inkling2LoopSlidingDecoderLayer", + "Inkling2LoopFullDecoderLayer", + "Inkling2LoopSlidingLoopDecoderLayer", + "Inkling2LoopFullLoopDecoderLayer", + ] + # 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) + + +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) + + # 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, + **kwargs: Unpack[TransformersKwargs], + ) -> MoeModelOutputWithPast: + 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 use_cache and cache is None: + cache = DynamicCache(config=self.config) + + 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) + + 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), + } + + loop_start = self.config.loop_layer_index_start + loop_end = self.config.loop_layer_index_end + num_loop_layers = loop_end - loop_start + + if cache is not None and len(cache.layers) == self.config.num_hidden_layers: + # Append extra caches for loop layers + loop_cache_layers = cache.layers[loop_start:loop_end] + cache.layers += [copy.deepcopy(layer) for layer in loop_cache_layers * (self.config.loop_num_passes - 1)] + + 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] + + # First pass over loop layers + for decoder_layer in 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, + 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, self.config.loop_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 + 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, + 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, + **kwargs: Unpack[TransformersKwargs], + ) -> Inkling2LoopCausalLMOutputWithPast: + r""" + Example: + + ```python + >>> import torch + >>> from transformers import AutoTokenizer, Inkling2LoopForCausalLM + + >>> tokenizer = AutoTokenizer.from_pretrained("thinkingmachines/Inkling-2-Mini") + >>> model = Inkling2LoopForCausalLM.from_pretrained( + ... "thinkingmachines/Inkling-2-Mini", 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, + **kwargs, + ) + + 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, + **kwargs: Unpack[TransformersKwargs], + ) -> tuple | Inkling2LoopModelOutputWithPast: + r""" + 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, Inkling2LoopModel + + >>> processor = AutoProcessor.from_pretrained("thinkingmachines/Inkling-2-Mini") + >>> model = Inkling2LoopModel.from_pretrained( + ... "thinkingmachines/Inkling-2-Mini", 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 (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) + + 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 __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, + **kwargs: Unpack[TransformersKwargs], + ) -> tuple | Inkling2LoopCausalLMOutputWithPast: + r""" + 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, Inkling2LoopForConditionalGeneration + + >>> processor = AutoProcessor.from_pretrained("thinkingmachines/Inkling-2-Mini") + >>> model = Inkling2LoopForConditionalGeneration.from_pretrained( + ... "thinkingmachines/Inkling-2-Mini", 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, + **kwargs, + ) + + 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", +] diff --git a/src/transformers/models/inkling2_loop/modular_inkling2_loop.py b/src/transformers/models/inkling2_loop/modular_inkling2_loop.py new file mode 100644 index 000000000000..98ec3180a3e5 --- /dev/null +++ b/src/transformers/models/inkling2_loop/modular_inkling2_loop.py @@ -0,0 +1,720 @@ +# 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 +from collections.abc import Callable + +import torch +import torch.nn as nn +from huggingface_hub.dataclasses import strict + +from ... import initialization as init +from ...cache_utils import Cache, DynamicCache +from ...configuration_utils import PreTrainedConfig, SubConfigSpec +from ...masking_utils import create_causal_mask, create_recurrent_attention_mask, create_sliding_window_causal_mask +from ...modeling_outputs import MoeModelOutputWithPast +from ...modeling_utils import ALL_ATTENTION_FUNCTIONS +from ...processing_utils import Unpack +from ...utils import TransformersKwargs, auto_docstring +from ...utils.deprecation import deprecate_kwarg +from ...utils.generic import merge_with_config_defaults +from ...utils.output_capturing import OutputRecorder, capture_outputs +from ..auto import AutoConfig, AutoModel +from ..inkling2.configuration_inkling2 import Inkling2Config, Inkling2TextConfig +from ..inkling2.modeling_inkling2 import ( + Inkling2BlockAttentionResidual, + Inkling2ForCausalLM, + Inkling2ForConditionalGeneration, + Inkling2FullAttention, + Inkling2FullDecoderLayer, + Inkling2Model, + Inkling2PreTrainedModel, + Inkling2SlidingAttention, + Inkling2SlidingDecoderLayer, + Inkling2TextModel, + Inkling2TopKRouter, + Inkling2UnweightedRMSNorm, + eager_attention_forward, + get_relative_distance, +) + + +@auto_docstring(checkpoint="thinkingmachines/Inkling-2-Mini") +@strict +class Inkling2LoopTextConfig(Inkling2TextConfig): + r""" + unpadded_vocab_size (`int`, *optional*, defaults to 200058): + Output size of the language modeling head. The checkpoint unembedding is padded to `vocab_size`, the padded + rows are dropped on load and restored as zeros on save. + swa_num_attention_heads (`int`, *optional*, defaults to 24): + Number of attention heads in the sliding-window layers. + swa_num_key_value_heads (`int`, *optional*, defaults to 8): + Number of key/value heads in the sliding-window layers. + swa_head_dim (`int`, *optional*, defaults to 128): + Dimension of query and key heads in the sliding-window layers. + sliding_window_size (`int`, *optional*, defaults to 1024): + Size of the sliding attention window used by layers whose `layer_types` entry is `"hybrid_sliding"`. + d_rel (`int`, *optional*, defaults to 16): + Per-head dimension of the relative states that are mixed into the relative position bias. + rel_extent (`int`, *optional*, defaults to 1024): + Backward distance, in tokens, over which the relative position bias is applied in the full-attention layers. + log_scaling_n_floor (`int`, *optional*, defaults to 8192): + Position from which queries and relative states are scaled up logarithmically in the full-attention layers. + log_scaling_alpha (`float`, *optional*, defaults to 0.1): + Strength of the logarithmic scaling controlled by `log_scaling_n_floor`. + qk_l2_clip_threshold (`float`, *optional*, defaults to 22.627416997969522): + Maximum L2 norm of each query and key head vector. Longer vectors are scaled down to this norm. + rel_l2_clip_threshold (`float`, *optional*, defaults to 8.0): + Maximum L2 norm of each relative-state head vector. + n_layers_per_attn_res_block (`int`, *optional*, defaults to 6): + Number of decoder layers summed into one block before the block becomes a source of the attention residuals. + mlp_gate_softcap (`float`, *optional*, defaults to 4.0): + Softcap applied to the linear part of the experts' gate projection. + mlp_up_softcap (`float`, *optional*, defaults to 25.0): + Softcap applied to the experts' up projection. + final_logit_softcapping (`float`, *optional*, defaults to 30.0): + Softcap applied to the output logits. + scoring_func (`str`, *optional*, defaults to `"sigmoid"`): + Activation turning the router logits into expert scores. + loop_layer_index_start (`int`, *optional*, defaults to 6): + Index of the first looped decoder layer. Must be a multiple of `n_layers_per_attn_res_block`. + loop_layer_index_end (`int`, *optional*, defaults to 18): + Index after the last looped decoder layer. Layers `loop_layer_index_start` to + `loop_layer_index_end - 1` are looped. Must be a multiple of `n_layers_per_attn_res_block`. + loop_num_passes (`int`, *optional*, defaults to 3): + Number of loops. + loop_gate_rank (`int`, *optional*, defaults to 64): + Rank of the message gate projections that mix the residual blocks of the previous pass into the current + one. + """ + + model_type = "inkling2_loop_text" + + hidden_size: int = 2304 + num_hidden_layers: int = 24 + num_attention_heads: int = 24 + swa_num_attention_heads: int = 24 + log_scaling_n_floor: int = 8192 + moe_intermediate_size: int = 1152 + n_routed_experts: int = 128 + loop_layer_index_start: int = 6 + loop_layer_index_end: int = 18 + loop_num_passes: int = 3 + loop_gate_rank: int = 64 + + def __post_init__(self, **kwargs): + if (loop_config := kwargs.get("loop_config")) is not None: + self.loop_layer_index_start = loop_config.get("core_start", self.loop_layer_index_start) + self.loop_layer_index_end = loop_config.get("core_end", self.loop_layer_index_end) + self.loop_num_passes = loop_config.get("num_passes", self.loop_num_passes) + self.loop_gate_rank = loop_config.get("gate_rank", self.loop_gate_rank) + super().__post_init__(**kwargs) + + def validate_architecture(self): + if self.loop_num_passes < 1: + raise ValueError(f"`loop_num_passes` ({self.loop_num_passes}) must be at least 1.") + if self.loop_layer_index_start <= 0: + raise ValueError(f"`loop_layer_index_start` ({self.loop_layer_index_start}) must be greater than 0.") + if self.loop_layer_index_start % self.n_layers_per_attn_res_block != 0: + raise ValueError( + f"`loop_layer_index_start` ({self.loop_layer_index_start}) must be a multiple of " + f"`n_layers_per_attn_res_block` ({self.n_layers_per_attn_res_block})." + ) + if self.loop_layer_index_end % self.n_layers_per_attn_res_block != 0: + raise ValueError( + f"`loop_layer_index_end` ({self.loop_layer_index_end}) must be a multiple of " + f"`n_layers_per_attn_res_block` ({self.n_layers_per_attn_res_block})." + ) + + @property + def total_num_hidden_layers(self) -> int: + """Total number of decoder layers visited in each forward pass. This takes looped layers into account.""" + num_loop_layers = self.loop_layer_index_end - self.loop_layer_index_start + return self.num_hidden_layers + (self.loop_num_passes - 1) * num_loop_layers + + +@auto_docstring(checkpoint="thinkingmachines/Inkling-2-Mini") +@strict +class Inkling2LoopConfig(Inkling2Config): + r""" + image_token_id (`int`, *optional*, defaults to 200054): + Token index of the image placeholders, each replaced by one image feature. + """ + + model_type = "inkling2_loop" + sub_configs_defaults = { + "text_config": Inkling2LoopTextConfig, + "vision_config": SubConfigSpec( + config_class=AutoConfig, + model_type="inkling2_vision", + init_kwargs={"text_hidden_size": 2304}, + ), + } + + vision_config: dict | PreTrainedConfig | None = None + + +class Inkling2LoopUnweightedRMSNorm(Inkling2UnweightedRMSNorm): + pass + + +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 + + +class Inkling2LoopMessageAttentionResidual(Inkling2BlockAttentionResidual): + """Retrieves messages from the block states of the previous block using learned queries.""" + + def __init__(self, config: Inkling2LoopTextConfig): + super().__init__(config) + # 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)) + + 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 Inkling2LoopSlidingAttention(Inkling2SlidingAttention): + pass + + +class Inkling2LoopFullAttention(Inkling2FullAttention): + pass + + +class Inkling2LoopSlidingDecoderLayer(Inkling2SlidingDecoderLayer): + pass + + +class Inkling2LoopSlidingLoopDecoderLayer(Inkling2SlidingDecoderLayer): + def __init__(self, config: Inkling2LoopTextConfig, layer_idx: int): + super().__init__(config, layer_idx) + 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, + **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) + 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(Inkling2FullDecoderLayer): + pass + + +class Inkling2LoopFullLoopDecoderLayer(Inkling2FullDecoderLayer): + def __init__(self, config: Inkling2LoopTextConfig, layer_idx: int): + super().__init__(config, layer_idx) + 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, + **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) + 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(Inkling2TopKRouter): + pass + + +@auto_docstring +class Inkling2LoopPreTrainedModel(Inkling2PreTrainedModel): + _no_split_modules = [ + "Inkling2LoopSlidingDecoderLayer", + "Inkling2LoopFullDecoderLayer", + "Inkling2LoopSlidingLoopDecoderLayer", + "Inkling2LoopFullLoopDecoderLayer", + ] + _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) + if isinstance(module, Inkling2LoopMessageAttentionResidual): + init.zeros_(module.query) + + +@auto_docstring +class Inkling2LoopTextModel(Inkling2TextModel): + def __init__(self, config: Inkling2LoopTextConfig): + super().__init__(config) + self.layers = nn.ModuleList() + 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) + + @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, + **kwargs: Unpack[TransformersKwargs], + ) -> MoeModelOutputWithPast: + 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 use_cache and cache is None: + cache = DynamicCache(config=self.config) + + 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) + + 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), + } + + loop_start = self.config.loop_layer_index_start + loop_end = self.config.loop_layer_index_end + num_loop_layers = loop_end - loop_start + + if cache is not None and len(cache.layers) == self.config.num_hidden_layers: + # Append extra caches for loop layers + loop_cache_layers = cache.layers[loop_start:loop_end] + cache.layers += [copy.deepcopy(layer) for layer in loop_cache_layers * (self.config.loop_num_passes - 1)] + + 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] + + # First pass over loop layers + for decoder_layer in 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, + 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, self.config.loop_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 + 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, + 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, + ) + + +class Inkling2LoopForCausalLM(Inkling2ForCausalLM): + def forward(self, **super_kwargs): + r""" + Example: + + ```python + >>> import torch + >>> from transformers import AutoTokenizer, Inkling2LoopForCausalLM + + >>> tokenizer = AutoTokenizer.from_pretrained("thinkingmachines/Inkling-2-Mini") + >>> model = Inkling2LoopForCausalLM.from_pretrained( + ... "thinkingmachines/Inkling-2-Mini", 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)) + ```""" + return super().forward(**super_kwargs) + + +class Inkling2LoopModel(Inkling2Model): + def __init__(self, config: Inkling2LoopConfig): + super().__init__(config) + self.vision_tower = AutoModel.from_config(config.vision_config) + + def forward(self, **super_kwargs): + r""" + 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, Inkling2LoopModel + + >>> processor = AutoProcessor.from_pretrained("thinkingmachines/Inkling-2-Mini") + >>> model = Inkling2LoopModel.from_pretrained( + ... "thinkingmachines/Inkling-2-Mini", 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 + ``` + """ + return super().forward(**super_kwargs) + + +class Inkling2LoopForConditionalGeneration(Inkling2ForConditionalGeneration): + def forward(self, **super_kwargs): + r""" + 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, Inkling2LoopForConditionalGeneration + + >>> processor = AutoProcessor.from_pretrained("thinkingmachines/Inkling-2-Mini") + >>> model = Inkling2LoopForConditionalGeneration.from_pretrained( + ... "thinkingmachines/Inkling-2-Mini", 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)) + ``` + """ + return super().forward(**super_kwargs) + + +__all__ = [ + "Inkling2LoopConfig", + "Inkling2LoopTextConfig", + "Inkling2LoopPreTrainedModel", + "Inkling2LoopTextModel", + "Inkling2LoopForCausalLM", + "Inkling2LoopModel", + "Inkling2LoopForConditionalGeneration", +] diff --git a/src/transformers/quantizers/quantizer_finegrained_fp8.py b/src/transformers/quantizers/quantizer_finegrained_fp8.py index dd6ed00ce1f4..08566cabb7c7 100644 --- a/src/transformers/quantizers/quantizer_finegrained_fp8.py +++ b/src/transformers/quantizers/quantizer_finegrained_fp8.py @@ -188,7 +188,7 @@ def update_weight_conversions(self, weight_conversions, model): WeightRenaming(source_patterns=r"^(.+)\.scale", target_patterns=r"\1.weight_scale_inv"), WeightRenaming(source_patterns=r"\.qscale_weight", target_patterns=".weight_scale_inv"), ] - # Inkling2 has params ending with `.scale` which should not be renamed (e.g. `q_l2_clip.scale`) - if any(name.endswith("_l2_clip.scale") for name, _ in model.named_parameters()): + # Inkling2 has params ending with `.scale` which should not be renamed (e.g. `q_norm.scale`) + if model.config.model_type.startswith("inkling2"): scale_renames = scale_renames[1:] return scale_renames + super().update_weight_conversions(weight_conversions, model) diff --git a/src/transformers/utils/auto_docstring.py b/src/transformers/utils/auto_docstring.py index 4fa312cdf816..c095174b27dc 100644 --- a/src/transformers/utils/auto_docstring.py +++ b/src/transformers/utils/auto_docstring.py @@ -76,7 +76,6 @@ "kosmos2": "Kosmos2Config", "kosmos2-5": "Kosmos2_5Config", "inkling": "InklingConfig", - "inkling2": "Inkling2Config", "donut": "DonutSwinConfig", "esmfold": "EsmConfig", "parakeet": "ParakeetCTCConfig", diff --git a/tests/models/inkling2/test_modeling_inkling2.py b/tests/models/inkling2/test_modeling_inkling2.py index 6c0c3f2ad549..1b718f902e0a 100644 --- a/tests/models/inkling2/test_modeling_inkling2.py +++ b/tests/models/inkling2/test_modeling_inkling2.py @@ -19,6 +19,7 @@ from transformers import ( AutoProcessor, + DataCollatorWithFlattening, Inkling2Config, Inkling2TextConfig, Inkling2VisionConfig, @@ -26,6 +27,7 @@ ) from transformers.testing_utils import ( Expectations, + require_causal_conv1d, require_deterministic_for_xpu, require_torch, require_torch_accelerator, @@ -74,6 +76,7 @@ def get_small_config_defaults(cls, **kwargs): values["swa_num_attention_heads"] = values["num_attention_heads"] values["swa_num_key_value_heads"] = values["num_key_value_heads"] values["swa_head_dim"] = values["head_dim"] + values["unpadded_vocab_size"] = values["vocab_size"] return values @@ -99,6 +102,28 @@ def test_eager_matches_batched_and_grouped_inference(self, name, dtype): self.skipTest("Low-precision rounding differences across expert kernels exceed the 1e-4 tolerance") _test_eager_matches_batched_and_grouped_inference(self, name, dtype) + @require_causal_conv1d + @require_torch_accelerator + def test_padding_free_matches_separate_sequences(self): + """Tests that packed sequences do not leak through the causal_conv1 layers.""" + config = self.model_tester.get_config() + model = Inkling2ForCausalLM(config).to(torch_device).eval() + features = [{"input_ids": [1, 2, 3, 4, 5, 6, 7, 8, 9]}, {"input_ids": [10, 11, 12, 13, 14, 15, 16]}] + batch = DataCollatorWithFlattening(return_tensors="pt", return_seq_idx=True)(features) + batch.pop("labels") + batch = {key: value.to(torch_device) for key, value in batch.items()} + + with torch.no_grad(): + separate_logits = torch.cat( + [ + model(input_ids=torch.tensor([feature["input_ids"]], device=torch_device)).logits[0] + for feature in features + ] + ) + packed_logits = model(**batch, use_cache=False).logits[0] + + torch.testing.assert_close(packed_logits, separate_logits, atol=1e-5, rtol=1e-5) + class Inkling2VisionText2TextModelTester(VLMModelTester): base_model_class = Inkling2Model @@ -126,6 +151,7 @@ class Inkling2VisionText2TextModelTester(VLMModelTester): def get_small_config_defaults(cls, **kwargs): values = super().get_small_config_defaults(**kwargs) values["text_hidden_size"] = values["hidden_size"] + values["unpadded_vocab_size"] = values["vocab_size"] return values def create_pixel_values(self, batch_size: int | None = None): @@ -141,7 +167,8 @@ def get_additional_inputs(self, config, input_ids, pixel_values, batch_size: int @require_torch class Inkling2VisionText2TextModelTest(VLMModelTest, unittest.TestCase): model_tester_class = Inkling2VisionText2TextModelTester - # each image adds a class token and `spatial_merge_size**2` vision tokens per `pixel_values` row + # `last_hidden_state` holds `spatial_merge_size**2` patch states per `pixel_values` row plus a class token per image, + # but the common test expects one state per `pixel_values` row skip_test_image_features_output_shape = True def _get_conv_state_shape(self, batch_size: int, config): diff --git a/tests/models/inkling2_loop/__init__.py b/tests/models/inkling2_loop/__init__.py new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/tests/models/inkling2_loop/test_modeling_inkling2_loop.py b/tests/models/inkling2_loop/test_modeling_inkling2_loop.py new file mode 100644 index 000000000000..de1ea3e3a81e --- /dev/null +++ b/tests/models/inkling2_loop/test_modeling_inkling2_loop.py @@ -0,0 +1,449 @@ +# 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. +"""Testing suite for the PyTorch Inkling2Loop model.""" + +import copy +import unittest + +from parameterized import parameterized + +from transformers import ( + AutoProcessor, + Inkling2LoopConfig, + Inkling2LoopTextConfig, + Inkling2VisionConfig, + is_torch_available, +) +from transformers.testing_utils import ( + Expectations, + require_deterministic_for_xpu, + require_torch, + require_torch_accelerator, + require_torch_accelerator_memory, + require_vision, + slow, + torch_device, +) + +from ...causal_lm_tester import CausalLMModelTest, CausalLMModelTester +from ...test_memory_cleanup_mixin import MemoryCleanupMixin +from ...test_modeling_common import ( + TEST_EAGER_MATCHES_BATCHED_AND_GROUPED_INFERENCE_PARAMETERIZATION, + _test_eager_matches_batched_and_grouped_inference, + floats_tensor, +) +from ...test_processing_common import url_to_local_path +from ...vlm_tester import VLMModelTest, VLMModelTester + + +if is_torch_available(): + import torch + + from transformers import ( + Inkling2LoopForCausalLM, + Inkling2LoopForConditionalGeneration, + Inkling2LoopModel, + Inkling2LoopTextModel, + ) + + +def check_loop_cache(test, batch_size, cache, seq_length, config, check_cache): + """The cache has the layers of the physical decoder layers, then one per layer of every extra pass through the loop + layers, shaped like the cache layer of the same loop layer.""" + text_config = config.get_text_config(decoder=True) + loop_layers = range(text_config.loop_layer_index_start, text_config.loop_layer_index_end) + pass_layers = [layer_idx for _ in range(text_config.loop_num_passes - 1) for layer_idx in loop_layers] + test.assertEqual(len(cache), text_config.num_hidden_layers + len(pass_layers)) + + physical_cache = copy.copy(cache) + physical_cache.layers = cache.layers[: text_config.num_hidden_layers] + check_cache(batch_size, physical_cache, seq_length, config) + for pass_layer, layer_idx in zip(cache.layers[text_config.num_hidden_layers :], pass_layers): + test.assertIs(type(pass_layer), type(cache.layers[layer_idx])) + test.assertEqual(pass_layer.keys.shape, cache.layers[layer_idx].keys.shape) + test.assertEqual( + [state.shape for state in pass_layer.conv_states.values()], + [state.shape for state in cache.layers[layer_idx].conv_states.values()], + ) + + +class Inkling2LoopTextModelTester(CausalLMModelTester): + if is_torch_available(): + config_class = Inkling2LoopTextConfig + base_model_class = Inkling2LoopTextModel + causal_lm_class = Inkling2LoopForCausalLM + + small_config_overrides = { + "num_hidden_layers": 4, + "layer_types": ["hybrid_sliding", "hybrid_sliding", "hybrid", "hybrid_sliding"], + "n_layers_per_attn_res_block": 1, + "loop_layer_index_start": 1, + "loop_layer_index_end": 3, + "loop_num_passes": 3, + "loop_gate_rank": 8, + "n_routed_experts": 8, + # hidden states are recorded at every layer visit (4 layers + 2 more passes through the 2 loop layers) and + # for the embeddings + "expected_num_hidden_layers": 4 + 2 * 2 + 1, + } + + @classmethod + def get_small_config_defaults(cls, **kwargs): + values = super().get_small_config_defaults(**kwargs) + values["swa_num_attention_heads"] = values["num_attention_heads"] + values["swa_num_key_value_heads"] = values["num_key_value_heads"] + values["swa_head_dim"] = values["head_dim"] + values["unpadded_vocab_size"] = values["vocab_size"] + return values + + +@require_torch +class Inkling2LoopTextModelTest(CausalLMModelTest, unittest.TestCase): + model_tester_class = Inkling2LoopTextModelTester + # `copy.deepcopy` of the cache layers appended for the loop layers in `forward` fails on export's fake tensors + test_torch_exportable = False + + @unittest.skip("Attentions are returned per layer visit: the loop layers run several times per forward") + def test_attention_outputs(self): + pass + + @unittest.skip("Chained renames leave no intermediate key after the reverse mapping") + def test_reverse_loading_mapping(self): + pass + + def _check_cache_for_generate(self, batch_size, cache, seq_length, config): + check_loop_cache(self, batch_size, cache, seq_length, config, super()._check_cache_for_generate) + + def _get_conv_state_shape(self, batch_size: int, config): + # key and value convolutions, then the attention output and MLP output convolutions + kv_size = config.num_key_value_heads * config.head_dim + return [(batch_size, kv_size, config.conv_kernel_size)] * 2 + [ + (batch_size, config.hidden_size, config.conv_kernel_size) + ] * 2 + + @parameterized.expand(TEST_EAGER_MATCHES_BATCHED_AND_GROUPED_INFERENCE_PARAMETERIZATION) + def test_eager_matches_batched_and_grouped_inference(self, name, dtype): + # batched_mm runs one matrix-vector product per token, whose float32 sums round differently in low precision + if dtype in ("fp16", "bf16"): + self.skipTest("Low-precision rounding differences across expert kernels exceed the 1e-4 tolerance") + _test_eager_matches_batched_and_grouped_inference(self, name, dtype) + + +class Inkling2LoopVisionText2TextModelTester(VLMModelTester): + base_model_class = Inkling2LoopModel + config_class = Inkling2LoopConfig + text_config_class = Inkling2LoopTextConfig + vision_config_class = Inkling2VisionConfig + conditional_generation_class = Inkling2LoopForConditionalGeneration + + small_config_overrides = { + "image_token_id": 4, + "patch_size": 2, + "spatial_merge_size": 2, + "num_image_tokens": 4, + "posemb_grid_size": 4, + "projection_hidden_dim": 32, + "text_num_hidden_layers": 4, + "layer_types": ["hybrid_sliding", "hybrid_sliding", "hybrid", "hybrid_sliding"], + "n_layers_per_attn_res_block": 1, + "loop_layer_index_start": 1, + "loop_layer_index_end": 3, + "loop_num_passes": 3, + "loop_gate_rank": 8, + "expected_num_hidden_layers": 4 + 2 * 2 + 1, + "moe_intermediate_size": 16, + "n_routed_experts": 8, + "swa_num_attention_heads": 2, + "swa_num_key_value_heads": 2, + "swa_head_dim": 16, + } + + @classmethod + def get_small_config_defaults(cls, **kwargs): + values = super().get_small_config_defaults(**kwargs) + values["text_hidden_size"] = values["hidden_size"] + values["unpadded_vocab_size"] = values["vocab_size"] + return values + + def create_pixel_values(self, batch_size: int | None = None): + batch_size = batch_size if batch_size is not None else self.batch_size + side = self.patch_size * self.spatial_merge_size + return floats_tensor([batch_size * self.num_image_tokens, side, side, self.num_channels]) + + def get_additional_inputs(self, config, input_ids, pixel_values, batch_size: int | None = None): + batch_size = batch_size if batch_size is not None else self.batch_size + return {"image_grid_thw": torch.tensor([[1, 2, 2]] * batch_size, device=torch_device)} + + +@require_torch +class Inkling2LoopVisionText2TextModelTest(VLMModelTest, unittest.TestCase): + model_tester_class = Inkling2LoopVisionText2TextModelTester + # `copy.deepcopy` of the cache layers appended for the loop layers in `forward` fails on export's fake tensors + test_torch_exportable = False + + # `last_hidden_state` holds `spatial_merge_size**2` patch states per `pixel_values` row plus a class token per image, + # but the common test expects one state per `pixel_values` row + skip_test_image_features_output_shape = True + + @unittest.skip("Attentions are returned per layer visit: the loop layers run several times per forward") + def test_attention_outputs(self): + pass + + @unittest.skip("Chained renames leave no intermediate key after the reverse mapping") + def test_reverse_loading_mapping(self): + pass + + def _check_cache_for_generate(self, batch_size, cache, seq_length, config): + check_loop_cache(self, batch_size, cache, seq_length, config, super()._check_cache_for_generate) + + def _image_features_get_expected_num_attentions(self, model_tester=None): + return self.model_tester.num_hidden_layers + + def _get_conv_state_shape(self, batch_size: int, config): + # key and value convolutions, then the attention output and MLP output convolutions + kv_size = config.num_key_value_heads * config.head_dim + return [(batch_size, kv_size, config.conv_kernel_size)] * 2 + [ + (batch_size, config.hidden_size, config.conv_kernel_size) + ] * 2 + + @parameterized.expand(TEST_EAGER_MATCHES_BATCHED_AND_GROUPED_INFERENCE_PARAMETERIZATION) + def test_eager_matches_batched_and_grouped_inference(self, name, dtype): + # batched_mm runs one matrix-vector product per token, whose float32 sums round differently in low precision + if dtype in ("fp16", "bf16"): + self.skipTest("Low-precision rounding differences across expert kernels exceed the 1e-4 tolerance") + _test_eager_matches_batched_and_grouped_inference(self, name, dtype) + + @unittest.skip( + "Inkling2LoopModel does not support SDPA: text attention adds a relative position bias and a per-token sink" + ) + def test_can_set_attention_dynamically_composite_model(self): + pass + + +@slow +@require_torch_accelerator +class Inkling2LoopSmallModelIntegrationTest(MemoryCleanupMixin, unittest.TestCase): + r"""Greedy completions and first-step logits of a tiny checkpoint sliced from the original one. + Differences to the original checkpoint: + + - decoder layers: 18 instead of 24 (original layers 0-11 and 18-23), with a single attn-res block of loop layers + (6-11) instead of two (6-17); NVFP4 experts on layers 0-13 and MXFP8 experts on layers 14-17 + - text: hidden size 256 instead of 2304, 16 experts (top-4) instead of 128 + - vision: hidden size 128, 2 layers instead of 23 + + Expectations are gibberish as the model is not trained. + """ + + model_id = "hf-internal-testing/tiny-inkling2-mini" + + MAX_NEW_TOKENS = 20 + + image_url = ( + "https://huggingface.co/datasets/hf-internal-testing/fixtures_image_utils/resolve/main/pipeline-cat-chonk.jpeg" + ) + + @classmethod + def setUpClass(cls): + cls.model = None + + @classmethod + def get_model(cls): + if cls.model is None: + cls.model = Inkling2LoopForConditionalGeneration.from_pretrained( + cls.model_id, dtype=torch.bfloat16, device_map=torch_device + ) + return cls.model + + def setUp(self): + super().setUp() + self.processor = AutoProcessor.from_pretrained(self.model_id) + + def _generate(self, messages, **kwargs): + model = self.get_model() + inputs = self.processor.apply_chat_template( + messages, add_generation_prompt=True, tokenize=True, return_dict=True, return_tensors="pt", **kwargs + ) + inputs = inputs.to(model.device).to(model.dtype) + output = model.generate( + **inputs, + max_new_tokens=self.MAX_NEW_TOKENS, + do_sample=False, + return_dict_in_generate=True, + output_logits=True, + ) + completion = self.processor.decode( + output.sequences[0, inputs["input_ids"].shape[1] :], skip_special_tokens=False + ) + return output, completion + + @require_deterministic_for_xpu + def test_small_model_integration_test_text(self): + messages = [ + { + "role": "user", + "content": [{"type": "text", "text": "Explain in one sentence why the sky is usually blue."}], + } + ] + output, completion = self._generate(messages, reasoning_effort="none") + + EXPECTED_LOGITS = Expectations( + { + ("cuda", 8): [1.9270305633544922, 0.287100613117218, 3.4533743858337402, 2.711331605911255, 0.878654956817627], + ("cuda", 10): [1.9970425367355347, 0.26171210408210754, 3.4687917232513428, 2.6803338527679443, 0.9059745073318481], + } + ) # fmt: skip + expected_logits = torch.tensor(EXPECTED_LOGITS.get_expectation(), device=torch_device) + torch.testing.assert_close(output.logits[0][0, :5].float(), expected_logits, atol=1e-4, rtol=1e-4) + + EXPECTED_COMPLETION = Expectations( + { + ("cuda", 8): "floursigne턽 перек перек перек перек перек перек перек перек перек перек перек перек перек перек перек перек перек", + ("cuda", 10): "floursigne턽 перек перек перек перек перек перек перек перек перек перек перек перек перек перек перек перек перек", + } + ) # fmt: skip + self.assertEqual(completion, EXPECTED_COMPLETION.get_expectation()) + + @require_vision + @require_deterministic_for_xpu + def test_small_model_integration_test_image(self): + messages = [ + { + "role": "user", + "content": [ + {"type": "image", "url": url_to_local_path(self.image_url)}, + {"type": "text", "text": "What animal is in this image, and where is it?"}, + ], + } + ] + output, completion = self._generate(messages) + + EXPECTED_LOGITS = Expectations( + { + ("cuda", 8): [0.4433271288871765, -1.3506488800048828, 3.853593111038208, 0.593672513961792, 1.5766711235046387], + ("cuda", 10): [0.4452798366546631, -1.3506488800048828, 3.8689591884613037, 0.6053866147994995, 1.5688800811767578], + } + ) # fmt: skip + expected_logits = torch.tensor(EXPECTED_LOGITS.get_expectation(), device=torch_device) + torch.testing.assert_close(output.logits[0][0, :5].float(), expected_logits, atol=1e-4, rtol=1e-4) + + EXPECTED_COMPLETION = Expectations( + { + ("cuda", 8): " Studyпсихијатventovécudostępучитель�SenStudieпсихијатventoperdere● Studyпсихијатventoperdere", + ("cuda", 10): " Studyпсихијатventovécudostępучитель�SenStudieпсихијатventoperdere● Studyпсихијатventoperdere", + } + ) # fmt: skip + self.assertEqual(completion, EXPECTED_COMPLETION.get_expectation()) + + +@slow +@require_torch_accelerator +@require_torch_accelerator_memory(memory=80) # ~50 GiB of weights with the experts dequantized to bfloat16 +class Inkling2LoopIntegrationTest(MemoryCleanupMixin, unittest.TestCase): + r"""Greedy completions and first-step logits of the reference implementation (sglang, one B200, experts + dequantized to bfloat16) on the prompts of the Inkling2 integration tests. + + Run from the repository root on a GPU with at least 80 GiB:: + + RUN_SLOW=1 pytest tests/models/inkling2_loop/test_modeling_inkling2_loop.py::Inkling2LoopIntegrationTest -s + """ + + model_id = "thinkingmachines/Inkling-2-Mini" + + MAX_NEW_TOKENS = 30 + + image_url = ( + "https://huggingface.co/datasets/hf-internal-testing/fixtures_image_utils/resolve/main/pipeline-cat-chonk.jpeg" + ) + + @classmethod + def setUpClass(cls): + cls.model = Inkling2LoopForConditionalGeneration.from_pretrained( + cls.model_id, dtype=torch.bfloat16, device_map="auto" + ).eval() + cls.processor = AutoProcessor.from_pretrained(cls.model_id) + + def _generate(self, messages, **kwargs): + inputs = self.processor.apply_chat_template( + messages, add_generation_prompt=True, tokenize=True, return_dict=True, return_tensors="pt", **kwargs + ) + inputs = inputs.to(self.model.device).to(self.model.dtype) + output = self.model.generate( + **inputs, + max_new_tokens=self.MAX_NEW_TOKENS, + do_sample=False, + return_dict_in_generate=True, + output_logits=True, + ) + completion = self.processor.decode( + output.sequences[0, inputs["input_ids"].shape[1] :], skip_special_tokens=False + ) + return output, completion + + def test_integration_text(self): + messages = [ + { + "role": "user", + "content": [{"type": "text", "text": "Explain in one sentence why the sky is usually blue."}], + } + ] + output, completion = self._generate(messages, reasoning_effort="none") + + EXPECTED_LOGITS = Expectations( + { + ("cuda", 10): [-12.755270957946777, -11.535194396972656, -16.171504974365234, -17.790428161621094, -19.750545501708984], + } + ) # fmt: skip + expected_logits = torch.tensor(EXPECTED_LOGITS.get_expectation(), device=torch_device) + torch.testing.assert_close(output.logits[0][0, :5].float(), expected_logits, atol=1.5, rtol=0) + + EXPECTED_COMPLETION = Expectations( + { + ("cuda", 10): ( + "<|message_model|><|content_thinking|>The user asks for one sentence explanation why sky is " + "usually blue. Need answer concise. Need ensure accuracy: Rayleigh scattering: shorter blue" + ), + } + ) # fmt: skip + self.assertEqual(completion, EXPECTED_COMPLETION.get_expectation()) + + @require_vision + def test_integration_image(self): + messages = [ + { + "role": "user", + "content": [ + {"type": "image", "url": url_to_local_path(self.image_url)}, + {"type": "text", "text": "What animal is in this image, and where is it?"}, + ], + } + ] + output, completion = self._generate(messages) + + EXPECTED_LOGITS = Expectations( + { + ("cuda", 10): [-3.7679390907287598, -3.2080488204956055, -4.347489356994629, -9.261019706726074, -11.941338539123535], + } + ) # fmt: skip + expected_logits = torch.tensor(EXPECTED_LOGITS.get_expectation(), device=torch_device) + torch.testing.assert_close(output.logits[0][0, :5].float(), expected_logits, atol=1.5, rtol=0) + + EXPECTED_COMPLETION = Expectations( + { + ("cuda", 10): ( + "<|message_model|><|content_thinking|>The user is asking what animal is in the image and where it " + "is. Let me analyze the image.\n\nThe image shows a stocky" + ), + } + ) # fmt: skip + self.assertEqual(completion, EXPECTED_COMPLETION.get_expectation()) diff --git a/tests/test_modeling_common.py b/tests/test_modeling_common.py index 59ac0c874716..bfdfbd03ed43 100644 --- a/tests/test_modeling_common.py +++ b/tests/test_modeling_common.py @@ -876,6 +876,7 @@ def test_num_layers_is_small(self): "ZambaModelTest": 5, # The minimum number to test beyond the initial ["mamba", "mamba", "hybrid"] in `ZambaConfig._layers_block_type` "Wav2Vec2BertModelTest": 4, "Lfm3ModelTest": 3, # One layer per operator type: ["full_attention", "sliding_attention", "conv"] + "Inkling2LoopTextModelTest": 4, # need to test all layer types (before loop, loop, after loop). 2 layers for loop because of sliding and full attention layers. "LaraMiniModelTest": 3, # One layer per token mixer: ["linear_attention", "sliding_attention", "full_attention"] } target_num_hidden_layers = exceptional_num_hidden_layers.get(type(self).__name__, 2) diff --git a/utils/check_config_attributes.py b/utils/check_config_attributes.py index 658a2a11ec5f..a91a6124630b 100644 --- a/utils/check_config_attributes.py +++ b/utils/check_config_attributes.py @@ -156,6 +156,7 @@ ], # Consumed by config logic: `mlp_ratio` sets `intermediate_size`. "Inkling2VisionConfig": ["mlp_ratio"], + "Inkling2LoopTextConfig": ["hidden_act"], "FalconMambaConfig": ["expand"], "FSMTConfig": ["langs", "common_kwargs", "early_stopping", "length_penalty", "max_length", "num_beams"], "GPTNeoConfig": ["attention_types"], diff --git a/utils/check_repo.py b/utils/check_repo.py index ef31033403c4..6338bbac4be6 100644 --- a/utils/check_repo.py +++ b/utils/check_repo.py @@ -493,6 +493,7 @@ ("inkling_mm_model", "inkling"), ("inkling2_text", "inkling2"), ("inkling2_vision", "inkling2"), + ("inkling2_loop_text", "inkling2_loop"), ("nemo_speechlm", "nemotron3_5_transcribe"), ] )