huggingface/transformers · #50099
Add Dory model support
docs/source/en/_toctree.yml2 + / 0 −
@@ -621,6 +621,8 @@ title: DistilBERT - local: model_doc/doge title: Doge+ - local: model_doc/dory+ title: Dory - local: model_doc/dots1 title: dots1 - local: model_doc/dprdocs/source/en/model_doc/dory.mdadded94 + / 0 −
@@ -0,0 +1,94 @@+<!--Copyright 2026 The HuggingFace Team. All rights reserved.+Copyright (c) 2026, NVIDIA CORPORATION. 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.+-->+*This model was contributed to Hugging Face Transformers on 2026-11-19.*++# Dory++Dory is a looped (latent-recurrent) language model from NVIDIA. It uses a [normalized-GPT](https://huggingface.co/papers/2410.01131) architecture with interleaved sliding-window and full attention layers. By applying a shared block of layers repeatedly, Dory can scale its intelligence by spending more compute per token. This compute can be adjusted by changing the loop count during inference with the same checkpoint.++Find all official checkpoints in the [Dory collection](https://huggingface.co/collections/nvidia/nemotron-labs-dory).++## Quickstart++Generate text with [`Pipeline`] or [`AutoModelForCausalLM`]. Both examples use the chat template, which enables thinking by default, and the recommended sampling settings.++<hfoptions id="usage">+<hfoption id="Pipeline">++```python+from transformers import pipeline++pipe = pipeline(+ task="text-generation",+ model="nvidia/NVIDIA-Nemotron-Labs-Dory1.0-4B-BF16",+)+pipe([{"role": "user", "content": "Name the largest planet in our solar system."}], max_new_tokens=512)+```++</hfoption>+<hfoption id="AutoModelForCausalLM">++```python+from transformers import AutoModelForCausalLM, AutoTokenizer++checkpoint = "nvidia/NVIDIA-Nemotron-Labs-Dory1.0-4B-BF16"+tokenizer = AutoTokenizer.from_pretrained(checkpoint)+model = AutoModelForCausalLM.from_pretrained(checkpoint, device_map="auto")++inputs = tokenizer.apply_chat_template(+ [{"role": "user", "content": "Name the largest planet in our solar system."}],+ add_generation_prompt=True,+ return_dict=True,+ return_tensors="pt",+).to(model.device)++outputs = model.generate(**inputs, max_new_tokens=512)+print(tokenizer.decode(outputs[0, inputs["input_ids"].shape[1] :], skip_special_tokens=True))+```++</hfoption>+</hfoptions>++## Notes++- Set `n_recurrent_loops` to balance compute and accuracy. The released checkpoints default to 2. Try 1 for lower compute per token or 4 for higher accuracy. More loops can shorten responses, so measure end-to-end latency.+- Set `recurrent_kv_cache_mode="last_loop"` to share KV history across loops instead of keeping separate histories with the default `per_loop`. Cache memory then stays independent of loop count. Every loop still computes its own Q, K and V, but only the last loop writes them to the cache. Earlier loops read the cached past and attend over it plus their own new keys, without writing. The diagram below shows one recurrent layer `L` with 3 loops.++ ```text+ prefill "a b c": cache[L] empty+ loop0: attend [k0(abc)]+ loop1: attend [k1(abc)]+ loop2: attend [k2(abc)] → cache[L] = k2(abc) (write)++ decode "d": cache[L] = k2(abc) (read)+ loop0: attend [k2(abc) | k0(d)]+ loop1: attend [k2(abc) | k1(d)]+ loop2: attend [k2(abc) | k2(d)] → cache[L] = k2(abcd)+ ```++## DoryConfig++[[autodoc]] DoryConfig++## DoryModel++[[autodoc]] DoryModel+ - forward++## DoryForCausalLM++[[autodoc]] DoryForCausalLM+ - forwardsrc/transformers/conversion_mapping.py8 + / 0 −
@@ -25,6 +25,7 @@ GroupWeightRename, Inkling2IndexOffsetWeightRename, Interleave,+ LayerPairCollapse, MergeModulelist, PermuteForRope, PrefixChange,@@ -157,6 +158,13 @@ def _build_checkpoint_conversion_mapping(): mapping = {+ # Dory checkpoints store each decoder layer as an attention block followed by an mlp block+ "dory": [+ LayerPairCollapse(),+ WeightRenaming(r"\.self_attn\.g_proj\.", ".self_attn.gate_proj."),+ WeightRenaming(r"^backbone\.", "model."),+ WeightRenaming(r"\.embeddings\.", ".embed_tokens."),+ ], "hy_v4": [ # General HC prefix which is dropped WeightRenaming(r"\.hc_pre\.hc_", ".hc_"),src/transformers/core_model_loading.py29 + / 0 −
@@ -1228,6 +1228,35 @@ def reverse_transform(self) -> WeightTransform: return result +class LayerPairCollapse(WeightRenaming):+ """+ Loads checkpoints storing each decoder layer as an attention block `layers.{2i}` and an mlp block `layers.{2i+1}`:++ layers.0.mixer.q_proj.weight -> layers.0.self_attn.q_proj.weight+ layers.1.mixer.up_proj.weight -> layers.0.mlp.up_proj.weight+ layers.1.mlp_alpha -> layers.0.lambda_2+ """++ __slots__ = ()+ pattern = re.compile(r"layers\.(\d+)\.(mixer|attn_alpha|mlp_alpha)(?=\.|$)")++ def __init__(self):+ super().__init__(source_patterns=r"layers\.(\d+)", target_patterns=r"layers.\1")++ def rename_source_key(self, source_key: str) -> tuple[str, str | None]:+ if (match := self.pattern.search(source_key)) is None:+ return source_key, None+ self._was_used = True+ index, name = int(match[1]), match[2]+ name = {"attn_alpha": "lambda_1", "mlp_alpha": "lambda_2"}.get(name, ("self_attn", "mlp")[index % 2])+ renamed = f"layers.{index // 2}.{name}"+ return source_key[: match.start()] + renamed + source_key[match.end() :], self.source_patterns[0]++ def reverse_transform(self) -> WeightTransform:+ # TODO: save back to the two-block layout. Our names never match `pattern`, so saving keeps our layout+ return self++ class WeightConverter(WeightTransform): __slots__ = ("operations", "force_cpu") src/transformers/models/__init__.py1 + / 0 −
@@ -131,6 +131,7 @@ from .distilbert import * from .doge import * from .donut import *+ from .dory import * from .dots1 import * from .dots3_note import * from .dpr import *src/transformers/models/auto/auto_mappings.py1 + / 0 −
@@ -168,6 +168,7 @@ ("distilbert", "DistilBertConfig"), ("doge", "DogeConfig"), ("donut-swin", "DonutSwinConfig"),+ ("dory", "DoryConfig"), ("dots1", "Dots1Config"), ("dots3_note", "Dots3NoteConfig"), ("dots3_note_audio_encoder", "Dots3NoteAudioConfig"),src/transformers/models/auto/modeling_auto.py2 + / 0 −
@@ -149,6 +149,7 @@ class _BaseModelWithGenerate(PreTrainedModel, GenerationMixin): ("distilbert", "DistilBertModel"), ("doge", "DogeModel"), ("donut-swin", "DonutSwinModel"),+ ("dory", "DoryModel"), ("dots1", "Dots1Model"), ("dots3_note", "Dots3NoteModel"), ("dots3_note_text", "Dots3NoteTextModel"),@@ -811,6 +812,7 @@ class _BaseModelWithGenerate(PreTrainedModel, GenerationMixin): ("deepseek_v4", "DeepseekV4ForCausalLM"), ("diffllama", "DiffLlamaForCausalLM"), ("doge", "DogeForCausalLM"),+ ("dory", "DoryForCausalLM"), ("dots1", "Dots1ForCausalLM"), ("dots3_note", "Dots3NoteForCausalLM"), ("dots3_note_text", "Dots3NoteForCausalLM"),src/transformers/models/dory/__init__.pyadded33 + / 0 −
@@ -0,0 +1,33 @@+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨+# This file was automatically generated from the modules in `src/transformers/models/dory`.+# 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 (c) 2026, NVIDIA CORPORATION. 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_dory import *+ from .modeling_dory import *+else:+ import sys++ _file = globals()["__file__"]+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)src/transformers/models/dory/configuration_dory.pyadded123 + / 0 −
@@ -0,0 +1,123 @@+# Copyright (c) 2026, NVIDIA CORPORATION. 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.+"""Dory model configuration"""++from typing import Literal++from huggingface_hub.dataclasses import strict++from ...configuration_utils import PreTrainedConfig+from ...utils import auto_docstring+++@auto_docstring(checkpoint="nvidia/NVIDIA-Nemotron-Labs-Dory1.0-4B-BF16")+@strict+class DoryConfig(PreTrainedConfig):+ r"""+ ngpt_alpha_init (`float`, *optional*, defaults to 0.05):+ Initial value of the nGPT residual interpolation rates `lambda_1`/`lambda_2`.+ n_input_layers (`int`, *optional*, defaults to 8):+ Number of decoder layers run once before the recurrent section.+ n_recurrent_layers (`int`, *optional*):+ Number of decoder layers in the recurrent section. Defaults to the remaining layers.+ n_output_layers (`int`, *optional*, defaults to 8):+ Number of decoder layers run once after the recurrent section.+ n_recurrent_loops (`int`, *optional*, defaults to 2):+ Number of passes through the recurrent section. More loops trade compute for accuracy.+ recurrent_kv_cache_mode (`str`, *optional*, defaults to `"per_loop"`):+ `"per_loop"` keeps one KV cache per recurrent loop. `"last_loop"` keeps a single KV cache per recurrent layer,+ written only by the last loop (earlier loops read it), so cache memory does not grow with the loop count.++ ```python+ >>> from transformers import DoryConfig, DoryForCausalLM++ >>> configuration = DoryConfig()+ >>> model = DoryForCausalLM(configuration)+ >>> configuration = model.config+ ```+ """++ model_type = "dory"+ base_model_tp_plan = {"embed_tokens": "embedding_rowwise"}+ keys_to_ignore_at_inference = ["cache"]++ vocab_size: int = 131072+ hidden_size: int = 2560+ intermediate_size: int = 7168+ num_hidden_layers: int = 36+ num_attention_heads: int = 16+ num_key_value_heads: int = 4+ head_dim: int = 256+ hidden_act: str = "silu"+ max_position_embeddings: int = 8192+ # nGPT scaled parameters (paper §2.6) are stored as `s` and used as `s * s_init / initializer_range`+ initializer_range: float = 0.0177+ use_cache: bool = True+ pad_token_id: int | None = None+ bos_token_id: int | None = None+ eos_token_id: int | list[int] | None = None+ tie_word_embeddings: bool = False+ rope_parameters: dict | None = None+ attention_bias: bool = False+ attention_dropout: float = 0.0+ mlp_bias: bool = False+ sliding_window: int = 1024+ layer_types: list[str] | None = None+ ngpt_alpha_init: float = 0.05+ n_input_layers: int = 8+ n_recurrent_layers: int | None = None+ n_output_layers: int = 8+ n_recurrent_loops: int = 2+ recurrent_kv_cache_mode: Literal["per_loop", "last_loop"] = "per_loop"++ def __post_init__(self, **kwargs):+ if self.layer_types is not None and "mlp" in self.layer_types:+ # Released `config.json`s list attention and mlp as separate blocks: each (attention, mlp) pair is one layer+ self.layer_types = self.layer_types[::2]+ self.num_hidden_layers //= 2+ self.n_input_layers //= 2+ self.n_output_layers //= 2+ if self.n_recurrent_layers is not None:+ self.n_recurrent_layers //= 2+ if self.layer_types is None:+ self.layer_types = [+ "full_attention" if (i + 1) % 4 == 0 else "sliding_attention" for i in range(self.num_hidden_layers)+ ]+ if self.n_recurrent_layers is None:+ self.n_recurrent_layers = self.num_hidden_layers - self.n_input_layers - self.n_output_layers+ if self.rope_parameters is None:+ rope_thetas = {"sliding_attention": 10_000.0, "full_attention": 10_000_000.0}+ self.rope_parameters = {+ layer_type: {"rope_type": "default", "rope_theta": rope_thetas[layer_type]}+ for layer_type in set(self.layer_types)+ }+ super().__post_init__(**kwargs)++ def to_dict(self):+ output = super().to_dict()+ # Serialize the layout `__post_init__` converted from, as released checkpoints (and vLLM / llama.cpp) store it:+ # each decoder layer is an attention block followed by an mlp block+ output["layer_types"] = [block for layer_type in self.layer_types for block in (layer_type, "mlp")]+ for key in ("num_hidden_layers", "n_input_layers", "n_recurrent_layers", "n_output_layers"):+ output[key] = 2 * getattr(self, key)+ return output++ def validate_architecture(self):+ if self.n_input_layers + self.n_recurrent_layers + self.n_output_layers != self.num_hidden_layers:+ raise ValueError("n_input_layers + n_recurrent_layers + n_output_layers must equal num_hidden_layers")+ if self.n_recurrent_loops < 1:+ raise ValueError(f"n_recurrent_loops must be at least 1, got {self.n_recurrent_loops}")+++__all__ = ["DoryConfig"]src/transformers/models/dory/modeling_dory.pyadded609 + / 0 −
@@ -0,0 +1,609 @@+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨+# This file was automatically generated from src/transformers/models/dory/modular_dory.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_dory.py file directly. One of our CI enforces this.+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨+# Copyright (c) 2026, NVIDIA CORPORATION. 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+from torch import nn++from ... import initialization as init+from ...activations import ACT2FN+from ...cache_utils import Cache, DynamicCache+from ...generation import GenerationMixin+from ...integrations import use_kernel_forward_from_hub, use_kernelized_func+from ...masking_utils import create_causal_mask, create_sliding_window_causal_mask+from ...modeling_layers import GradientCheckpointingLayer+from ...modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast+from ...modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update+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+from ...utils.generic import merge_with_config_defaults+from ...utils.output_capturing import capture_outputs+from .configuration_dory import DoryConfig+++class DoryL2Norm(torch.nn.Module):+ """Projects onto the unit sphere: nGPT keeps every hidden state at norm 1, not RMS 1."""++ def __init__(self, eps: float = 1e-6):+ super().__init__()+ self.eps = eps++ def _norm(self, x):+ return x * torch.rsqrt(x.pow(2).sum(-1, keepdim=True) + self.eps)++ def forward(self, x):+ return self._norm(x.float()).type_as(x)++ def extra_repr(self):+ return f"eps={self.eps}"+++class DoryRotaryEmbedding(nn.Module):+ def __init__(self, config: DoryConfig, device=None):+ super().__init__()+ self.max_seq_len_cached = config.max_position_embeddings+ self.original_max_seq_len = config.max_position_embeddings+ self.config = config+ self.layer_types = sorted(set(config.layer_types))+ self.rope_type = {}+ for layer_type in self.layer_types:+ rope_params = self.config.rope_parameters[layer_type]+ if rope_params is None:+ continue++ self.rope_type[layer_type] = rope_params["rope_type"]+ rope_init_fn: Callable = self.compute_default_rope_parameters+ if self.rope_type[layer_type] != "default":+ rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type[layer_type]]+ curr_inv_freq, curr_attention_scaling = rope_init_fn(self.config, device, layer_type=layer_type)+ setattr(self, f"{layer_type}_inv_freq", nn.Buffer(curr_inv_freq, persistent=False))+ setattr(self, f"{layer_type}_original_inv_freq", nn.Buffer(curr_inv_freq.clone(), persistent=False))+ setattr(self, f"{layer_type}_attention_scaling", curr_attention_scaling)++ @staticmethod+ def compute_default_rope_parameters(+ config: DoryConfig, device=None, layer_type: str | None = None, **kwargs+ ) -> tuple[torch.Tensor, float]:+ """+ Computes the inverse frequencies according to the original RoPE implementation+ Args:+ config ([`~transformers.PreTrainedConfig`]):+ The model configuration.+ layer_type (`str`):+ The current layer type if the model has different RoPE parameters per type.+ Should not be used unless `config.layer_types is not None`++ Returns:+ Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the+ post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE).+ """+ # For backward compatibility standardize the `rope_parameters_dict` if it uses old format+ base = config.rope_parameters[layer_type]["rope_theta"]+ dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads++ attention_factor = 1.0 # Unused in this type of RoPE+ # Compute the inverse frequencies+ inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2, dtype=torch.float) / dim))+ return inv_freq.to(device), attention_factor++ @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)+ def forward(self, x, position_ids, layer_type):+ inv_freq = getattr(self, f"{layer_type}_inv_freq")+ attention_scaling = getattr(self, f"{layer_type}_attention_scaling")++ freqs = position_ids[..., None].float() * inv_freq.to(device=x.device, dtype=torch.float)+ emb = torch.cat((freqs, freqs), dim=-1)+ cos = emb.cos() * attention_scaling+ sin = emb.sin() * attention_scaling++ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)+++def rotate_half(x):+ """Rotates half the hidden dims of the input."""+ x1 = x[..., : x.shape[-1] // 2]+ x2 = x[..., x.shape[-1] // 2 :]+ return torch.cat((-x2, x1), dim=-1)+++@use_kernel_forward_from_hub("rotary_pos_emb")+def apply_rotary_pos_emb(q, k, cos, sin, unsqueeze_dim=1):+ """Applies Rotary Position Embedding to the query and key tensors.++ Args:+ q (`torch.Tensor`): The query tensor.+ k (`torch.Tensor`): The key tensor.+ cos (`torch.Tensor`): The cosine part of the rotary embedding.+ sin (`torch.Tensor`): The sine part of the rotary embedding.+ unsqueeze_dim (`int`, *optional*, defaults to 1):+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.+ Returns:+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.+ """+ cos = cos.unsqueeze(unsqueeze_dim)+ sin = sin.unsqueeze(unsqueeze_dim)+ q_embed = (q * cos) + (rotate_half(q) * sin)+ k_embed = (k * cos) + (rotate_half(k) * sin)+ return q_embed, k_embed+++def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:+ """+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)+ """+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape+ if n_rep == 1:+ return hidden_states+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)+++def eager_attention_forward(+ module: nn.Module,+ query: torch.Tensor,+ key: torch.Tensor,+ value: torch.Tensor,+ attention_mask: torch.Tensor | None,+ scaling: float,+ dropout: float = 0.0,+ **kwargs: Unpack[TransformersKwargs],+):+ key_states = repeat_kv(key, module.num_key_value_groups)+ value_states = repeat_kv(value, module.num_key_value_groups)++ attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling+ if attention_mask is not None:+ attn_weights = attn_weights + attention_mask++ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)+ attn_output = torch.matmul(attn_weights, value_states)+ attn_output = attn_output.transpose(1, 2).contiguous()++ return attn_output, attn_weights+++@use_kernelized_func(apply_rotary_pos_emb)+class DoryAttention(nn.Module):+ """+ Afmoe attention with nGPT details: unit-norm queries and keys, queries rescaled per channel by `sqk` after rope,+ and a learned scale `s_gate` inside the output gate.+ """++ def __init__(self, config: DoryConfig, layer_idx: int):+ super().__init__()+ self.config = config+ self.layer_idx = layer_idx+ self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)+ self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads+ 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, config.num_attention_heads * self.head_dim, bias=config.attention_bias+ )+ self.k_proj = nn.Linear(+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias+ )+ self.v_proj = nn.Linear(+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias+ )+ self.o_proj = nn.Linear(+ config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.attention_bias+ )+ self.is_local_attention = config.layer_types[layer_idx] == "sliding_attention"+ self.sliding_window = config.sliding_window if self.is_local_attention else None+ self.q_norm = DoryL2Norm()+ self.k_norm = DoryL2Norm()+ self.gate_proj = nn.Linear(config.hidden_size, config.num_attention_heads * self.head_dim, bias=False)+ self.attn_sub_norm = DoryL2Norm()+ self.sqk = nn.Parameter(torch.full((config.num_attention_heads * self.head_dim,), config.initializer_range))+ self.s_gate = nn.Parameter(torch.full((config.num_attention_heads * self.head_dim,), config.initializer_range))+ self.sqk_scale = self.head_dim**0.5 / config.initializer_range+ self.s_gate_scale = config.hidden_size**0.25 / config.initializer_range++ def forward(+ self,+ hidden_states: torch.Tensor,+ position_embeddings: tuple[torch.Tensor, torch.Tensor],+ attention_mask: torch.Tensor | None,+ cache: Cache | None = None,+ cache_offset: int = 0,+ shared_kv_states: dict[int, tuple[torch.Tensor, torch.Tensor]] | None = None,+ **kwargs: Unpack[TransformersKwargs],+ ) -> tuple[torch.Tensor, torch.Tensor]:+ input_shape = hidden_states.shape[:-1]+ hidden_shape = (*input_shape, -1, self.head_dim)++ query_states = self.q_proj(hidden_states).view(hidden_shape)+ key_states = self.k_proj(hidden_states).view(hidden_shape)+ value_states = self.v_proj(hidden_states).view(hidden_shape)+ gate_states = self.gate_proj(hidden_states)++ query_states = self.q_norm(query_states).transpose(1, 2)+ key_states = self.k_norm(key_states).transpose(1, 2)+ value_states = value_states.transpose(1, 2)++ cos, sin = position_embeddings+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)+ query_scale = (self.sqk * self.sqk_scale).view(-1, 1, self.head_dim)+ query_states = query_states * query_scale.square()++ if shared_kv_states is not None:+ # `last_loop`: earlier loops attend over the last loop's cached past and their own tokens, without writing+ if (past := shared_kv_states.get(self.layer_idx)) is not None:+ key_states = torch.cat([past[0], key_states], dim=-2)+ value_states = torch.cat([past[1], value_states], dim=-2)+ if self.sliding_window is not None:+ # The cache may hold more than the window if past recording is on+ num_visible = self.sliding_window - 1 + query_states.shape[-2]+ key_states, value_states = key_states[..., -num_visible:, :], value_states[..., -num_visible:, :]+ elif cache is not None:+ # `per_loop` loops past the first write to their own copy of this layer's cache, see `DoryModel.forward`+ key_states, value_states = cache.update(key_states, value_states, self.layer_idx + cache_offset)++ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(+ self.config._attn_implementation, eager_attention_forward+ )+ output, attn_weights = attention_interface(+ self,+ query_states,+ key_states,+ value_states,+ attention_mask=attention_mask,+ dropout=0.0 if not self.training else self.attention_dropout,+ scaling=self.scaling,+ sliding_window=self.sliding_window,+ **kwargs,+ )++ output = output.view(*input_shape, -1).contiguous()+ output = output * torch.sigmoid(gate_states * (self.s_gate * self.s_gate_scale).square())+ attn_output = self.o_proj(self.attn_sub_norm(output))+ return attn_output, attn_weights+++class DoryMLP(nn.Module):+ def __init__(self, config: DoryConfig):+ super().__init__()+ self.config = config+ self.hidden_size = config.hidden_size+ self.intermediate_size = config.intermediate_size+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=config.mlp_bias)+ self.act_fn = ACT2FN[config.hidden_act]+ self.suv_gate = nn.Parameter(torch.ones(config.intermediate_size))+ self.suv_up = nn.Parameter(torch.ones(config.intermediate_size))+ self.suv_scale = config.hidden_size**0.5+ self.ffn_sub_norm = DoryL2Norm()++ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:+ gate = self.gate_proj(hidden_states) * (self.suv_gate * self.suv_scale)+ up = self.up_proj(hidden_states) * (self.suv_up * self.suv_scale)+ return self.down_proj(self.ffn_sub_norm(self.act_fn(gate) * up))+++class DoryDecoderLayer(GradientCheckpointingLayer):+ """+ Gemma2 sandwich layer on the unit sphere: the residual is an interpolation towards the normalized update, at a+ learned per-channel rate (`lambda_1`, `lambda_2`), instead of an addition.+ """++ def __init__(self, config: DoryConfig, layer_idx: int):+ super().__init__()+ self.hidden_size = config.hidden_size+ self.config = config+ self.self_attn = DoryAttention(config=config, layer_idx=layer_idx)+ self.mlp = DoryMLP(config)+ self.input_layernorm = DoryL2Norm()+ self.post_attention_layernorm = DoryL2Norm()+ self.pre_feedforward_layernorm = DoryL2Norm()+ self.post_feedforward_layernorm = DoryL2Norm()+ self.attention_type = config.layer_types[layer_idx]+ self.lambda_1 = nn.Parameter(torch.full((config.hidden_size,), config.initializer_range))+ self.lambda_2 = nn.Parameter(torch.full((config.hidden_size,), config.initializer_range))+ self.lambda_scale = config.ngpt_alpha_init / config.initializer_range++ def forward(+ self,+ hidden_states: torch.Tensor,+ attention_mask: torch.Tensor | None = None,+ position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,+ cache: Cache | None = None,+ **kwargs: Unpack[TransformersKwargs],+ ) -> torch.Tensor:+ hidden_states = self.input_layernorm(hidden_states)+ attn_output, _ = self.self_attn(+ hidden_states,+ attention_mask=attention_mask,+ position_embeddings=position_embeddings,+ cache=cache,+ **kwargs,+ )+ attn_output = self.post_attention_layernorm(attn_output)+ attention_rate = (self.lambda_1 * self.lambda_scale).abs()+ hidden_states = hidden_states + attention_rate * (attn_output - hidden_states)++ hidden_states = self.pre_feedforward_layernorm(hidden_states)+ mlp_output = self.post_feedforward_layernorm(self.mlp(hidden_states))+ mlp_rate = (self.lambda_2 * self.lambda_scale).abs()+ hidden_states = hidden_states + mlp_rate * (mlp_output - hidden_states)+ return hidden_states+++class DoryLMHead(nn.Linear):+ """`lm_head` with a learned per-token logit scale."""++ def __init__(self, config: DoryConfig):+ super().__init__(config.hidden_size, config.vocab_size, bias=False)+ self.logit_scale = nn.Parameter(torch.full((config.vocab_size,), config.initializer_range))+ self.logit_scale_factor = 1 / config.initializer_range++ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:+ logits = super().forward(hidden_states).float()+ return logits * (self.logit_scale.float() * self.logit_scale_factor)+++@auto_docstring+class DoryPreTrainedModel(PreTrainedModel):+ config: DoryConfig+ base_model_prefix = "model"+ supports_gradient_checkpointing = True+ _no_split_modules = ["DoryDecoderLayer"]+ _supports_flash_attn = True+ _supports_sdpa = True+ _supports_flex_attn = True++ _can_compile_fullgraph = True+ _supports_attention_backend = True+ _can_record_outputs = {+ "hidden_states": DoryDecoderLayer,+ "attentions": DoryAttention,+ }++ @torch.no_grad()+ def _init_weights(self, module):+ super()._init_weights(module)+ if isinstance(module, DoryRotaryEmbedding):+ for layer_type in module.layer_types:+ rope_init_fn = module.compute_default_rope_parameters+ if module.rope_type[layer_type] != "default":+ rope_init_fn = ROPE_INIT_FUNCTIONS[module.rope_type[layer_type]]+ inv_freq, _ = rope_init_fn(module.config, layer_type=layer_type)+ init.copy_(getattr(module, f"{layer_type}_inv_freq"), inv_freq)+ init.copy_(getattr(module, f"{layer_type}_original_inv_freq"), inv_freq)+ elif isinstance(module, DoryAttention):+ init.constant_(module.sqk, self.config.initializer_range)+ init.constant_(module.s_gate, self.config.initializer_range)+ elif isinstance(module, DoryMLP):+ init.ones_(module.suv_gate)+ init.ones_(module.suv_up)+ elif isinstance(module, DoryDecoderLayer):+ init.constant_(module.lambda_1, self.config.initializer_range)+ init.constant_(module.lambda_2, self.config.initializer_range)+ elif isinstance(module, DoryLMHead):+ init.constant_(module.logit_scale, self.config.initializer_range)+++@auto_docstring+class DoryModel(DoryPreTrainedModel):+ def __init__(self, config: DoryConfig):+ super().__init__(config)+ self.padding_idx = config.pad_token_id+ self.vocab_size = config.vocab_size++ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)+ self.layers = nn.ModuleList(+ [DoryDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]+ )+ self.norm = DoryL2Norm()+ self.rotary_emb = DoryRotaryEmbedding(config)+ self.gradient_checkpointing = False++ # Initialize weights and apply final processing+ self.post_init()++ @merge_with_config_defaults+ @capture_outputs+ @auto_docstring+ 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.FloatTensor | None = None,+ use_cache: bool | None = None,+ **kwargs: Unpack[TransformersKwargs],+ ) -> BaseModelOutputWithPast:+ 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),+ }++ position_embeddings = {+ attention_type: self.rotary_emb(inputs_embeds, position_ids, attention_type)+ for attention_type in {layer.attention_type for layer in self.layers}+ }++ n_loops = self.config.n_recurrent_loops+ recurrent_start = self.config.n_input_layers+ n_recurrent = self.config.n_recurrent_layers+ recurrent_end = recurrent_start + n_recurrent+ last_loop_only = self.config.recurrent_kv_cache_mode == "last_loop"++ shared_kv_states = None+ if cache is not None and last_loop_only:+ # Only the last loop writes, the earlier ones read the past+ shared_kv_states = {i: (c.keys, c.values) for i, c in enumerate(cache.layers) if c.is_initialized}+ elif cache is not None and len(cache.layers) == self.config.num_hidden_layers:+ # Loops 1, 2, ... write to copies of the recurrent cache layers, appended at the end+ cache.layers += [copy.deepcopy(c) for c in cache.layers[recurrent_start:recurrent_end] * (n_loops - 1)]++ hidden_states = inputs_embeds+ for decoder_layer in self.layers[:recurrent_start]:+ hidden_states = decoder_layer(+ hidden_states,+ attention_mask=causal_mask_mapping[decoder_layer.attention_type],+ position_embeddings=position_embeddings[decoder_layer.attention_type],+ cache=cache,+ **kwargs,+ )++ # Loop i > 0 writes to its copies of the recurrent cache layers, appended after the model's layers+ offset = len(self.layers) - recurrent_start - n_recurrent+ # Each loop restarts from the input section's output+ input_hidden_states = self.norm(hidden_states)+ for loop_idx in range(n_loops):+ hidden_states = self.norm(hidden_states) + input_hidden_states+ cache_offset = 0 if loop_idx == 0 or last_loop_only else offset + loop_idx * n_recurrent+ for decoder_layer in self.layers[recurrent_start:recurrent_end]:+ hidden_states = decoder_layer(+ hidden_states,+ attention_mask=causal_mask_mapping[decoder_layer.attention_type],+ position_embeddings=position_embeddings[decoder_layer.attention_type],+ cache=cache,+ cache_offset=cache_offset,+ shared_kv_states=shared_kv_states if loop_idx < n_loops - 1 else None,+ **kwargs,+ )++ output_start = self.config.num_hidden_layers - self.config.n_output_layers+ for decoder_layer in self.layers[output_start:]:+ hidden_states = decoder_layer(+ hidden_states,+ attention_mask=causal_mask_mapping[decoder_layer.attention_type],+ position_embeddings=position_embeddings[decoder_layer.attention_type],+ cache=cache,+ **kwargs,+ )++ hidden_states = self.norm(hidden_states)+ return BaseModelOutputWithPast(last_hidden_state=hidden_states, cache=cache)+++@auto_docstring+class DoryForCausalLM(DoryPreTrainedModel, GenerationMixin):+ _tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"}+ _tp_plan = {"lm_head": "colwise_gather_output"}+ _pp_plan = {"lm_head": (["hidden_states"], ["logits"])}+ _fsdp_plan = {"lm_head": "keep_full_weight"}++ def __init__(self, config: DoryConfig):+ super().__init__(config)+ self.model = DoryModel(config)+ self.vocab_size = config.vocab_size+ self.lm_head = DoryLMHead(config)++ # Initialize weights and apply final processing+ self.post_init()++ @can_return_tuple+ @auto_docstring+ def forward(+ self,+ input_ids: torch.LongTensor | None = None,+ attention_mask: torch.Tensor | None = None,+ position_ids: torch.LongTensor | None = None,+ 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],+ ) -> CausalLMOutputWithPast:+ r"""+ Example:++ ```python+ >>> from transformers import AutoTokenizer, DoryForCausalLM++ >>> model = DoryForCausalLM.from_pretrained("meta-dory/Dory-2-7b-hf")+ >>> tokenizer = AutoTokenizer.from_pretrained("meta-dory/Dory-2-7b-hf")++ >>> prompt = "Hey, are you conscious? Can you talk to me?"+ >>> inputs = tokenizer(prompt, return_tensors="pt")++ >>> # Generate+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."+ ```"""+ outputs: BaseModelOutputWithPast = 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 = outputs.last_hidden_state+ hidden_states = slice_logits_to_keep(hidden_states, logits_to_keep)+ logits = self.lm_head(hidden_states)++ loss = None+ if labels is not None:+ loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)++ return CausalLMOutputWithPast(+ loss=loss,+ logits=logits,+ cache=outputs.cache,+ hidden_states=outputs.hidden_states,+ attentions=outputs.attentions,+ )+++__all__ = ["DoryPreTrainedModel", "DoryModel", "DoryForCausalLM"]src/transformers/models/dory/modular_dory.pyadded359 + / 0 −
@@ -0,0 +1,359 @@+# Copyright (c) 2026, NVIDIA CORPORATION. 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.+"""Dory: a looped normalized transformer (nGPT, https://huggingface.co/papers/2410.01131)."""++import copy+from collections.abc import Callable++import torch+from torch import nn++from ... import initialization as init+from ...cache_utils import Cache, DynamicCache+from ...masking_utils import create_causal_mask, create_sliding_window_causal_mask+from ...modeling_outputs import BaseModelOutputWithPast+from ...modeling_rope_utils import ROPE_INIT_FUNCTIONS+from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel+from ...processing_utils import Unpack+from ...utils import TransformersKwargs, auto_docstring, can_return_tuple+from ...utils.generic import merge_with_config_defaults, no_inherit_decorator+from ...utils.output_capturing import capture_outputs+from ..afmoe.modeling_afmoe import AfmoeAttention+from ..gemma2.modeling_gemma2 import Gemma2DecoderLayer+from ..gemma3.modeling_gemma3 import Gemma3RotaryEmbedding+from ..llama.modeling_llama import (+ LlamaForCausalLM,+ LlamaMLP,+ LlamaModel,+ LlamaPreTrainedModel,+ apply_rotary_pos_emb,+ eager_attention_forward,+)+from ..llama4.modeling_llama4 import Llama4TextL2Norm+from .configuration_dory import DoryConfig+++class DoryL2Norm(Llama4TextL2Norm):+ """Projects onto the unit sphere: nGPT keeps every hidden state at norm 1, not RMS 1."""++ def _norm(self, x):+ return x * torch.rsqrt(x.pow(2).sum(-1, keepdim=True) + self.eps)+++class DoryRotaryEmbedding(Gemma3RotaryEmbedding):+ def __init__(self, config: DoryConfig, device=None):+ super().__init__(config)++ def compute_default_rope_parameters(+ config: DoryConfig, device=None, layer_type: str | None = None, **kwargs+ ) -> tuple[torch.Tensor, float]:+ return super().compute_default_rope_parameters(config, layer_type)+++class DoryAttention(AfmoeAttention):+ """+ Afmoe attention with nGPT details: unit-norm queries and keys, queries rescaled per channel by `sqk` after rope,+ and a learned scale `s_gate` inside the output gate.+ """++ def __init__(self, config: DoryConfig, layer_idx: int):+ super().__init__(config, layer_idx)+ self.q_norm = DoryL2Norm()+ self.k_norm = DoryL2Norm()+ self.attn_sub_norm = DoryL2Norm()+ self.sqk = nn.Parameter(torch.full((config.num_attention_heads * self.head_dim,), config.initializer_range))+ self.s_gate = nn.Parameter(torch.full((config.num_attention_heads * self.head_dim,), config.initializer_range))+ self.sqk_scale = self.head_dim**0.5 / config.initializer_range+ self.s_gate_scale = config.hidden_size**0.25 / config.initializer_range+ self.is_local_attention = config.layer_types[layer_idx] == "sliding_attention"+ self.sliding_window = config.sliding_window if self.is_local_attention else None++ @no_inherit_decorator+ def forward(+ self,+ hidden_states: torch.Tensor,+ position_embeddings: tuple[torch.Tensor, torch.Tensor],+ attention_mask: torch.Tensor | None,+ cache: Cache | None = None,+ cache_offset: int = 0,+ shared_kv_states: dict[int, tuple[torch.Tensor, torch.Tensor]] | None = None,+ **kwargs: Unpack[TransformersKwargs],+ ) -> tuple[torch.Tensor, torch.Tensor]:+ input_shape = hidden_states.shape[:-1]+ hidden_shape = (*input_shape, -1, self.head_dim)++ query_states = self.q_proj(hidden_states).view(hidden_shape)+ key_states = self.k_proj(hidden_states).view(hidden_shape)+ value_states = self.v_proj(hidden_states).view(hidden_shape)+ gate_states = self.gate_proj(hidden_states)++ query_states = self.q_norm(query_states).transpose(1, 2)+ key_states = self.k_norm(key_states).transpose(1, 2)+ value_states = value_states.transpose(1, 2)++ cos, sin = position_embeddings+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)+ query_scale = (self.sqk * self.sqk_scale).view(-1, 1, self.head_dim)+ query_states = query_states * query_scale.square()++ if shared_kv_states is not None:+ # `last_loop`: earlier loops attend over the last loop's cached past and their own tokens, without writing+ if (past := shared_kv_states.get(self.layer_idx)) is not None:+ key_states = torch.cat([past[0], key_states], dim=-2)+ value_states = torch.cat([past[1], value_states], dim=-2)+ if self.sliding_window is not None:+ # The cache may hold more than the window if past recording is on+ num_visible = self.sliding_window - 1 + query_states.shape[-2]+ key_states, value_states = key_states[..., -num_visible:, :], value_states[..., -num_visible:, :]+ elif cache is not None:+ # `per_loop` loops past the first write to their own copy of this layer's cache, see `DoryModel.forward`+ key_states, value_states = cache.update(key_states, value_states, self.layer_idx + cache_offset)++ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(+ self.config._attn_implementation, eager_attention_forward+ )+ output, attn_weights = attention_interface(+ self,+ query_states,+ key_states,+ value_states,+ attention_mask=attention_mask,+ dropout=0.0 if not self.training else self.attention_dropout,+ scaling=self.scaling,+ sliding_window=self.sliding_window,+ **kwargs,+ )++ output = output.view(*input_shape, -1).contiguous()+ output = output * torch.sigmoid(gate_states * (self.s_gate * self.s_gate_scale).square())+ attn_output = self.o_proj(self.attn_sub_norm(output))+ return attn_output, attn_weights+++class DoryMLP(LlamaMLP):+ def __init__(self, config: DoryConfig):+ super().__init__(config)+ self.suv_gate = nn.Parameter(torch.ones(config.intermediate_size))+ self.suv_up = nn.Parameter(torch.ones(config.intermediate_size))+ self.suv_scale = config.hidden_size**0.5+ self.ffn_sub_norm = DoryL2Norm()++ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:+ gate = self.gate_proj(hidden_states) * (self.suv_gate * self.suv_scale)+ up = self.up_proj(hidden_states) * (self.suv_up * self.suv_scale)+ return self.down_proj(self.ffn_sub_norm(self.act_fn(gate) * up))+++class DoryDecoderLayer(Gemma2DecoderLayer):+ """+ Gemma2 sandwich layer on the unit sphere: the residual is an interpolation towards the normalized update, at a+ learned per-channel rate (`lambda_1`, `lambda_2`), instead of an addition.+ """++ def __init__(self, config: DoryConfig, layer_idx: int):+ super().__init__(config, layer_idx)+ self.attention_type = config.layer_types[layer_idx]+ self.input_layernorm = DoryL2Norm()+ self.post_attention_layernorm = DoryL2Norm()+ self.pre_feedforward_layernorm = DoryL2Norm()+ self.post_feedforward_layernorm = DoryL2Norm()+ self.lambda_1 = nn.Parameter(torch.full((config.hidden_size,), config.initializer_range))+ self.lambda_2 = nn.Parameter(torch.full((config.hidden_size,), config.initializer_range))+ self.lambda_scale = config.ngpt_alpha_init / config.initializer_range++ @no_inherit_decorator+ def forward(+ self,+ hidden_states: torch.Tensor,+ attention_mask: torch.Tensor | None = None,+ position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,+ cache: Cache | None = None,+ **kwargs: Unpack[TransformersKwargs],+ ) -> torch.Tensor:+ hidden_states = self.input_layernorm(hidden_states)+ attn_output, _ = self.self_attn(+ hidden_states,+ attention_mask=attention_mask,+ position_embeddings=position_embeddings,+ cache=cache,+ **kwargs,+ )+ attn_output = self.post_attention_layernorm(attn_output)+ attention_rate = (self.lambda_1 * self.lambda_scale).abs()+ hidden_states = hidden_states + attention_rate * (attn_output - hidden_states)++ hidden_states = self.pre_feedforward_layernorm(hidden_states)+ mlp_output = self.post_feedforward_layernorm(self.mlp(hidden_states))+ mlp_rate = (self.lambda_2 * self.lambda_scale).abs()+ hidden_states = hidden_states + mlp_rate * (mlp_output - hidden_states)+ return hidden_states+++class DoryLMHead(nn.Linear):+ """`lm_head` with a learned per-token logit scale."""++ def __init__(self, config: DoryConfig):+ super().__init__(config.hidden_size, config.vocab_size, bias=False)+ self.logit_scale = nn.Parameter(torch.full((config.vocab_size,), config.initializer_range))+ self.logit_scale_factor = 1 / config.initializer_range++ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:+ logits = super().forward(hidden_states).float()+ return logits * (self.logit_scale.float() * self.logit_scale_factor)+++class DoryPreTrainedModel(LlamaPreTrainedModel):+ @torch.no_grad()+ def _init_weights(self, module):+ PreTrainedModel._init_weights(self, module)+ if isinstance(module, DoryRotaryEmbedding):+ for layer_type in module.layer_types:+ rope_init_fn = module.compute_default_rope_parameters+ if module.rope_type[layer_type] != "default":+ rope_init_fn = ROPE_INIT_FUNCTIONS[module.rope_type[layer_type]]+ inv_freq, _ = rope_init_fn(module.config, layer_type=layer_type)+ init.copy_(getattr(module, f"{layer_type}_inv_freq"), inv_freq)+ init.copy_(getattr(module, f"{layer_type}_original_inv_freq"), inv_freq)+ elif isinstance(module, DoryAttention):+ init.constant_(module.sqk, self.config.initializer_range)+ init.constant_(module.s_gate, self.config.initializer_range)+ elif isinstance(module, DoryMLP):+ init.ones_(module.suv_gate)+ init.ones_(module.suv_up)+ elif isinstance(module, DoryDecoderLayer):+ init.constant_(module.lambda_1, self.config.initializer_range)+ init.constant_(module.lambda_2, self.config.initializer_range)+ elif isinstance(module, DoryLMHead):+ init.constant_(module.logit_scale, self.config.initializer_range)+++class DoryModel(LlamaModel):+ def __init__(self, config: DoryConfig):+ super().__init__(config)+ self.rotary_emb = DoryRotaryEmbedding(config)+ self.norm = DoryL2Norm()++ @merge_with_config_defaults+ @capture_outputs+ @auto_docstring+ 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.FloatTensor | None = None,+ use_cache: bool | None = None,+ **kwargs: Unpack[TransformersKwargs],+ ) -> BaseModelOutputWithPast:+ 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),+ }++ position_embeddings = {+ attention_type: self.rotary_emb(inputs_embeds, position_ids, attention_type)+ for attention_type in {layer.attention_type for layer in self.layers}+ }++ n_loops = self.config.n_recurrent_loops+ recurrent_start = self.config.n_input_layers+ n_recurrent = self.config.n_recurrent_layers+ recurrent_end = recurrent_start + n_recurrent+ last_loop_only = self.config.recurrent_kv_cache_mode == "last_loop"++ shared_kv_states = None+ if cache is not None and last_loop_only:+ # Only the last loop writes, the earlier ones read the past+ shared_kv_states = {i: (c.keys, c.values) for i, c in enumerate(cache.layers) if c.is_initialized}+ elif cache is not None and len(cache.layers) == self.config.num_hidden_layers:+ # Loops 1, 2, ... write to copies of the recurrent cache layers, appended at the end+ cache.layers += [copy.deepcopy(c) for c in cache.layers[recurrent_start:recurrent_end] * (n_loops - 1)]++ hidden_states = inputs_embeds+ for decoder_layer in self.layers[:recurrent_start]:+ hidden_states = decoder_layer(+ hidden_states,+ attention_mask=causal_mask_mapping[decoder_layer.attention_type],+ position_embeddings=position_embeddings[decoder_layer.attention_type],+ cache=cache,+ **kwargs,+ )++ # Loop i > 0 writes to its copies of the recurrent cache layers, appended after the model's layers+ offset = len(self.layers) - recurrent_start - n_recurrent+ # Each loop restarts from the input section's output+ input_hidden_states = self.norm(hidden_states)+ for loop_idx in range(n_loops):+ hidden_states = self.norm(hidden_states) + input_hidden_states+ cache_offset = 0 if loop_idx == 0 or last_loop_only else offset + loop_idx * n_recurrent+ for decoder_layer in self.layers[recurrent_start:recurrent_end]:+ hidden_states = decoder_layer(+ hidden_states,+ attention_mask=causal_mask_mapping[decoder_layer.attention_type],+ position_embeddings=position_embeddings[decoder_layer.attention_type],+ cache=cache,+ cache_offset=cache_offset,+ shared_kv_states=shared_kv_states if loop_idx < n_loops - 1 else None,+ **kwargs,+ )++ output_start = self.config.num_hidden_layers - self.config.n_output_layers+ for decoder_layer in self.layers[output_start:]:+ hidden_states = decoder_layer(+ hidden_states,+ attention_mask=causal_mask_mapping[decoder_layer.attention_type],+ position_embeddings=position_embeddings[decoder_layer.attention_type],+ cache=cache,+ **kwargs,+ )++ hidden_states = self.norm(hidden_states)+ return BaseModelOutputWithPast(last_hidden_state=hidden_states, cache=cache)+++class DoryForCausalLM(LlamaForCausalLM):+ def __init__(self, config: DoryConfig):+ super().__init__(config)+ self.lm_head = DoryLMHead(config)++ @can_return_tuple+ @auto_docstring+ def forward(self, **super_kwargs):+ return super().forward(**super_kwargs)+++__all__ = ["DoryPreTrainedModel", "DoryModel", "DoryForCausalLM"]tests/models/dory/__init__.pyadded1 + / 0 −
@@ -0,0 +1 @@+# Copyright (c) 2026, NVIDIA CORPORATION. All rights reserved.tests/models/dory/test_modeling_dory.pyadded125 + / 0 −
@@ -0,0 +1,125 @@+# 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 Dory model."""++import unittest++from huggingface_hub.errors import StrictDataclassClassValidationError++from transformers import AutoTokenizer, DoryConfig, is_torch_available+from transformers.testing_utils import require_torch, require_torch_accelerator, slow, torch_device++from ...causal_lm_tester import CausalLMModelTest, CausalLMModelTester+++if is_torch_available():+ import torch++ from transformers import DoryForCausalLM, DoryModel+++class DoryModelTester(CausalLMModelTester):+ if is_torch_available():+ base_model_class = DoryModel++ # One loop keeps the common tests' one-cache-slot-per-layer assumption; loops are tested below+ small_config_overrides = {"n_input_layers": 1, "n_output_layers": 0, "n_recurrent_loops": 1}+++@require_torch+class DoryModelTest(CausalLMModelTest, unittest.TestCase):+ model_tester_class = DoryModelTester+ # The nGPT normalized updates start small (`ngpt_alpha_init`), so overfitting takes a few more steps+ training_overfit_steps = 400++ @unittest.skip("New model: `cache` only, no `past_key_values` BC")+ def test_bc_cache_name_forward(self):+ pass++ def test_reverse_loading_mapping(self):+ # Checkpoints are saved with the `backbone.` prefix, which only exists on the head model+ super().test_reverse_loading_mapping(skip_base_model=True)++ def test_chunked_prefill_and_decode_match_full_forward(self):+ config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()+ config.num_hidden_layers, config.layer_types, config.rope_parameters = 4, None, None+ config.n_input_layers, config.n_recurrent_layers, config.n_output_layers, config.n_recurrent_loops = 1, 2, 1, 3+ config.__post_init__()+ model = DoryForCausalLM(config).to(torch_device).eval()+ input_ids = inputs_dict["input_ids"]+ with torch.no_grad():+ full_logits = model(input_ids).logits+ outputs = model(input_ids[:, :4], use_cache=True)+ logits = [outputs.logits]+ for position in range(4, input_ids.shape[1]):+ outputs = model(input_ids[:, position : position + 1], cache=outputs.cache)+ logits.append(outputs.logits)+ torch.testing.assert_close(torch.cat(logits, dim=1), full_logits, rtol=1e-4, atol=1e-4)++ def test_prompt_lookup_past_sliding_window_with_loops(self):+ # Assisted decoding rolls the cache back: the later loops' sliding layers must record their past too+ config, _ = self.model_tester.prepare_config_and_inputs_for_common()+ config.num_hidden_layers, config.layer_types, config.rope_parameters = 4, None, None+ config.n_input_layers, config.n_recurrent_layers, config.n_output_layers, config.n_recurrent_loops = 1, 2, 1, 3+ config.sliding_window = 8+ config.__post_init__()+ model = DoryForCausalLM(config).to(torch_device).eval()+ input_ids = torch.tensor([[1, 2, 3, 4, 5] * 3], device=torch_device)+ greedy = model.generate(input_ids, max_new_tokens=24, do_sample=False)+ prompt_lookup = model.generate(input_ids, max_new_tokens=24, do_sample=False, prompt_lookup_num_tokens=4)+ self.assertTrue(torch.equal(greedy, prompt_lookup))++ def test_at_least_one_recurrent_loop(self):+ with self.assertRaises(StrictDataclassClassValidationError):+ DoryConfig(n_recurrent_loops=0)++ def test_recurrent_cache_layout(self):+ # Plain cache layers: `per_loop` appends one copy of the recurrent layers per extra loop, `last_loop` adds none+ config = DoryConfig(num_hidden_layers=4, n_input_layers=1, n_output_layers=1, n_recurrent_loops=3)+ input_ids = torch.tensor([[1, 2, 3]])+ for mode, expected in [+ ("per_loop", ["DynamicSlidingWindowLayer"] * 3 + ["DynamicLayer"] + ["DynamicSlidingWindowLayer"] * 4),+ ("last_loop", ["DynamicSlidingWindowLayer"] * 3 + ["DynamicLayer"]),+ ]:+ config.recurrent_kv_cache_mode = mode+ cache = DoryModel(config).eval()(input_ids, use_cache=True).cache+ self.assertEqual([type(layer).__name__ for layer in cache.layers], expected)+ self.assertTrue(all(layer.get_seq_length() == 3 for layer in cache.layers))++ def test_recurrent_layers_use_the_mask_and_rope_of_their_attention_type(self):+ config = DoryConfig(num_hidden_layers=4, n_input_layers=1, n_output_layers=1, n_recurrent_loops=2)+ model = DoryModel(config)+ self.assertEqual(+ [layer.attention_type for layer in model.layers],+ ["sliding_attention", "sliding_attention", "sliding_attention", "full_attention"],+ )+ self.assertTrue(model.layers[1].self_attn.is_local_attention)+ self.assertEqual(model.layers[1].self_attn.sliding_window, config.sliding_window)+++@slow+@require_torch_accelerator+class DoryIntegrationTest(unittest.TestCase):+ checkpoint = "nvidia/NVIDIA-Nemotron-Labs-Dory1.0-4B-BF16"++ def test_bf16_generation(self):+ tokenizer = AutoTokenizer.from_pretrained(self.checkpoint)+ model = DoryForCausalLM.from_pretrained(self.checkpoint, dtype=torch.bfloat16, device_map=torch_device)+ inputs = tokenizer("The capital of France is", return_tensors="pt").to(torch_device)+ output = model.generate(**inputs, max_new_tokens=24, do_sample=False)+ self.assertEqual(+ tokenizer.decode(output[0], skip_special_tokens=True),+ "The capital of France is Paris. The capital of Germany is Berlin. "+ "The capital of Italy is Rome. The capital of Spain is Madrid. The",+ )