marksverdhei Claude commited on
Commit
e7bd90e
·
1 Parent(s): 7742637

Add custom modeling and configuration files for trust_remote_code support

Browse files

- Add modeling_gpt_oss_dense.py with GptOssDense model implementation
- Add configuration_gpt_oss_dense.py with GptOssDenseConfig
- Add config.json with auto_map for remote code loading
- Add README.md with model documentation

This allows the model to be loaded with trust_remote_code=True from the Hub.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>

README.md ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # GptOssDense
2
+
3
+ GptOssDense is a dense variant of the GptOss model architecture. While GptOss uses a Mixture-of-Experts (MoE) approach with routing, GptOssDense replaces the MoE layer with a standard dense feedforward network (FFN).
4
+
5
+ ## Model Architecture
6
+
7
+ - **Attention**: Same as GptOss with sliding window attention and sink tokens
8
+ - **MLP**: Dense FFN with GLU activation (instead of MoE with router)
9
+ - **Activation**: Same GLU activation as GptOss experts: `(up + 1) * gate * sigmoid(gate * alpha)` where `alpha=1.702`
10
+ - **Normalization**: RMSNorm
11
+ - **RoPE**: YaRN (Yet another RoPE extensioN)
12
+
13
+ ## Key Differences from GptOss
14
+
15
+ | Feature | GptOss | GptOssDense |
16
+ |---------|--------|-------------|
17
+ | MLP Type | Mixture-of-Experts | Dense FFN |
18
+ | Router | Yes | No |
19
+ | Experts | Multiple (128) | Single |
20
+ | Parameters | More (due to multiple experts) | Fewer |
21
+ | Inference | Routes tokens to top-k experts | Single FFN for all tokens |
22
+
23
+ ## Usage
24
+
25
+ ### With `trust_remote_code=True`
26
+
27
+ ```python
28
+ from transformers import AutoModelForCausalLM, AutoTokenizer
29
+
30
+ model = AutoModelForCausalLM.from_pretrained(
31
+ "marksverdhei/gpt-oss-dense",
32
+ trust_remote_code=True
33
+ )
34
+ tokenizer = AutoTokenizer.from_pretrained("marksverdhei/gpt-oss-dense")
35
+
36
+ # Generate text
37
+ inputs = tokenizer("Hello, how are you?", return_tensors="pt")
38
+ outputs = model.generate(**inputs, max_length=50)
39
+ print(tokenizer.decode(outputs[0]))
40
+ ```
41
+
42
+ ### With transformers installation (if model is registered)
43
+
44
+ ```python
45
+ from transformers import GptOssDenseForCausalLM, GptOssDenseConfig
46
+
47
+ config = GptOssDenseConfig()
48
+ model = GptOssDenseForCausalLM(config)
49
+ ```
50
+
51
+ ## Model Configuration
52
+
53
+ - **Hidden size**: 2880
54
+ - **Intermediate size**: 2880
55
+ - **Number of layers**: 36
56
+ - **Number of attention heads**: 64
57
+ - **Number of key-value heads**: 8
58
+ - **Head dimension**: 64
59
+ - **Vocabulary size**: 201,088
60
+ - **Max position embeddings**: 131,072
61
+ - **Sliding window**: 128
62
+ - **RoPE type**: YaRN with factor 32.0
63
+
64
+ ## License
65
+
66
+ Apache 2.0
67
+
68
+ ## Citation
69
+
70
+ If you use this model, please cite the original GptOss work and acknowledge this dense variant.
config.json ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "GptOssDenseForCausalLM"
4
+ ],
5
+ "attention_bias": true,
6
+ "attention_dropout": 0.0,
7
+ "auto_map": {
8
+ "AutoConfig": "configuration_gpt_oss_dense.GptOssDenseConfig",
9
+ "AutoModel": "modeling_gpt_oss_dense.GptOssDenseModel",
10
+ "AutoModelForCausalLM": "modeling_gpt_oss_dense.GptOssDenseForCausalLM"
11
+ },
12
+ "head_dim": 64,
13
+ "hidden_act": "silu",
14
+ "hidden_size": 2880,
15
+ "initializer_range": 0.02,
16
+ "intermediate_size": 2880,
17
+ "layer_types": null,
18
+ "max_position_embeddings": 131072,
19
+ "model_type": "gpt_oss_dense",
20
+ "num_attention_heads": 64,
21
+ "num_hidden_layers": 36,
22
+ "num_key_value_heads": 8,
23
+ "rms_norm_eps": 1e-05,
24
+ "rope_parameters": {
25
+ "rope_type": "yarn",
26
+ "factor": 32.0,
27
+ "beta_fast": 32.0,
28
+ "beta_slow": 1.0,
29
+ "original_max_position_embeddings": 4096
30
+ },
31
+ "rope_theta": 150000.0,
32
+ "sliding_window": 128,
33
+ "tie_word_embeddings": false,
34
+ "torch_dtype": "float32",
35
+ "transformers_version": "4.48.0.dev0",
36
+ "use_cache": true,
37
+ "vocab_size": 201088
38
+ }
configuration_gpt_oss_dense.py ADDED
@@ -0,0 +1,153 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2025 The HuggingFace Team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """GptOssDense model configuration"""
16
+
17
+ from typing import Optional
18
+
19
+ from ...configuration_utils import PreTrainedConfig, layer_type_validation
20
+ from ...modeling_rope_utils import RopeParameters, rope_config_validation, standardize_rope_params
21
+
22
+
23
+ class GptOssDenseConfig(PreTrainedConfig):
24
+ r"""
25
+ This is the configuration class to store the configuration of a [`GptOssDenseModel`]. It is used to instantiate a
26
+ GptOssDense model according to the specified arguments, defining the model architecture.
27
+
28
+ Configuration objects inherit from [`PreTrainedConfig`] and can be used to control the model outputs. Read the
29
+ documentation from [`PreTrainedConfig`] for more information.
30
+
31
+ Args:
32
+ num_hidden_layers (`int`, *optional*, defaults to 36):
33
+ Number of hidden layers in the Transformer decoder.
34
+ vocab_size (`int`, *optional*, defaults to 201088):
35
+ Vocabulary size of the GptOssDense model.
36
+ hidden_size (`int`, *optional*, defaults to 2880):
37
+ Dimension of the hidden representations.
38
+ intermediate_size (`int`, *optional*, defaults to 2880):
39
+ Dimension of the MLP representations.
40
+ head_dim (`int`, *optional*, defaults to 64):
41
+ The attention head dimension.
42
+ num_attention_heads (`int`, *optional*, defaults to 64):
43
+ Number of attention heads for each attention layer in the Transformer decoder.
44
+ num_key_value_heads (`int`, *optional*, defaults to 8):
45
+ Number of key-value heads for each attention layer. If None, defaults to num_attention_heads.
46
+ sliding_window (`int`, *optional*, defaults to 128):
47
+ Sliding window attention window size. If None, no sliding window is applied.
48
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
49
+ Whether to tie the weights of the input embeddings and the output embeddings.
50
+ hidden_act (`str`, *optional*, defaults to `"silu"`):
51
+ The non-linear activation function in the MLP.
52
+ initializer_range (`float`, *optional*, defaults to 0.02):
53
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
54
+ max_position_embeddings (`int`, *optional*, defaults to 131072):
55
+ The maximum sequence length that this model might ever be used with.
56
+ rms_norm_eps (`float`, *optional*, defaults to 1e-5):
57
+ The epsilon used by the rms normalization layers.
58
+ rope_parameters (`dict`, *optional*):
59
+ The RoPE parameters for the model. Defaults to yarn RoPE with specific parameters.
60
+ attention_dropout (`float`, *optional*, defaults to 0.0):
61
+ The dropout ratio for the attention probabilities.
62
+ use_cache (`bool`, *optional*, defaults to `True`):
63
+ Whether or not the model should return the last key/values attentions.
64
+ layer_types (`list[str]`, *optional*):
65
+ List of layer types (e.g., "sliding_attention", "full_attention"). If None, defaults to alternating pattern.
66
+ """
67
+
68
+ model_type = "gpt_oss_dense"
69
+ base_model_pp_plan = {
70
+ "embed_tokens": (["input_ids"], ["inputs_embeds"]),
71
+ "layers": (["hidden_states", "attention_mask"], ["hidden_states"]),
72
+ "norm": (["hidden_states"], ["hidden_states"]),
73
+ }
74
+ base_model_tp_plan = {
75
+ "layers.*.self_attn.q_proj": "colwise",
76
+ "layers.*.self_attn.k_proj": "colwise",
77
+ "layers.*.self_attn.v_proj": "colwise",
78
+ "layers.*.self_attn.o_proj": "rowwise",
79
+ "layers.*.self_attn.sinks": "local_rowwise",
80
+ "layers.*.mlp.gate_up_proj": "colwise",
81
+ "layers.*.mlp.down_proj": "rowwise",
82
+ }
83
+
84
+ def __init__(
85
+ self,
86
+ num_hidden_layers: Optional[int] = 36,
87
+ vocab_size: Optional[int] = 201088,
88
+ hidden_size: Optional[int] = 2880,
89
+ intermediate_size: Optional[int] = 2880,
90
+ head_dim: Optional[int] = 64,
91
+ num_attention_heads: Optional[int] = 64,
92
+ num_key_value_heads: Optional[int] = 8,
93
+ sliding_window: Optional[int] = 128,
94
+ tie_word_embeddings: Optional[bool] = False,
95
+ hidden_act: Optional[str] = "silu",
96
+ initializer_range: Optional[float] = 0.02,
97
+ max_position_embeddings: Optional[int] = 131072,
98
+ rms_norm_eps: Optional[float] = 1e-5,
99
+ rope_parameters: Optional[RopeParameters] = {
100
+ "rope_type": "yarn",
101
+ "factor": 32.0,
102
+ "beta_fast": 32.0,
103
+ "beta_slow": 1.0,
104
+ "truncate": False,
105
+ "original_max_position_embeddings": 4096,
106
+ },
107
+ attention_dropout: Optional[float] = 0.0,
108
+ use_cache: Optional[bool] = True,
109
+ layer_types: Optional[list[str]] = None,
110
+ **kwargs,
111
+ ):
112
+ self.vocab_size = vocab_size
113
+ self.hidden_size = hidden_size
114
+ self.intermediate_size = intermediate_size
115
+ self.num_hidden_layers = num_hidden_layers
116
+ self.num_attention_heads = num_attention_heads
117
+ self.sliding_window = sliding_window
118
+ # for backward compatibility
119
+ if num_key_value_heads is None:
120
+ num_key_value_heads = num_attention_heads
121
+
122
+ self.num_key_value_heads = num_key_value_heads
123
+ self.hidden_act = hidden_act
124
+ self.initializer_range = initializer_range
125
+ self.rms_norm_eps = rms_norm_eps
126
+ self.attention_dropout = attention_dropout
127
+ self.head_dim = head_dim if head_dim is not None else self.hidden_size // self.num_attention_heads
128
+ self.layer_types = layer_types
129
+ if self.layer_types is None:
130
+ self.layer_types = [
131
+ "sliding_attention" if bool((i + 1) % 2) else "full_attention" for i in range(self.num_hidden_layers)
132
+ ]
133
+ layer_type_validation(self.layer_types, self.num_hidden_layers)
134
+
135
+ self.attention_bias = True
136
+ self.max_position_embeddings = max_position_embeddings
137
+ self.use_cache = use_cache
138
+ # Try to set `rope_scaling` if available, otherwise use `rope_parameters`
139
+ rope_scaling = kwargs.pop("rope_scaling", None)
140
+ self.rope_parameters = rope_scaling or rope_parameters
141
+
142
+ # Validate the correctness of rotary position embeddings parameters
143
+ rope_theta = kwargs.get("rope_theta", 150000.0)
144
+ standardize_rope_params(self, rope_theta=rope_theta)
145
+ rope_config_validation(self)
146
+
147
+ super().__init__(
148
+ tie_word_embeddings=tie_word_embeddings,
149
+ **kwargs,
150
+ )
151
+
152
+
153
+ __all__ = ["GptOssDenseConfig"]
modeling_gpt_oss_dense.py ADDED
@@ -0,0 +1,570 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
2
+ # This file was automatically generated from src/transformers/models/gpt_oss_dense/modular_gpt_oss_dense.py.
3
+ # Do NOT edit this file manually as any edits will be overwritten by the generation of
4
+ # the file from the modular. If any change should be done, please apply the change to the
5
+ # modular_gpt_oss_dense.py file directly. One of our CI enforces this.
6
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
7
+ # coding=utf-8
8
+ # Copyright 2025 The HuggingFace Team. All rights reserved.
9
+ #
10
+ # Licensed under the Apache License, Version 2.0 (the "License");
11
+ # you may not use this file except in compliance with the License.
12
+ # You may obtain a copy of the License at
13
+ #
14
+ # http://www.apache.org/licenses/LICENSE-2.0
15
+ #
16
+ # Unless required by applicable law or agreed to in writing, software
17
+ # distributed under the License is distributed on an "AS IS" BASIS,
18
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19
+ # See the License for the specific language governing permissions and
20
+ # limitations under the License.
21
+ from collections.abc import Callable
22
+ from typing import Optional
23
+
24
+ import torch
25
+ from torch import nn
26
+ from torch.nn import functional as F
27
+
28
+ from ...cache_utils import Cache, DynamicCache
29
+ from ...integrations.hub_kernels import use_kernel_forward_from_hub
30
+ from ...masking_utils import create_causal_mask, create_sliding_window_causal_mask
31
+ from ...modeling_layers import GradientCheckpointingLayer
32
+ from ...modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
33
+ from ...modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
34
+ from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
35
+ from ...processing_utils import Unpack
36
+ from ...utils import TransformersKwargs, auto_docstring
37
+ from ...utils.generic import check_model_inputs
38
+ from .configuration_gpt_oss_dense import GptOssDenseConfig
39
+
40
+
41
+ @use_kernel_forward_from_hub("RMSNorm")
42
+ class GptOssDenseRMSNorm(nn.Module):
43
+ def __init__(self, hidden_size, eps=1e-6):
44
+ """
45
+ GptOssDenseRMSNorm is equivalent to T5LayerNorm
46
+ """
47
+ super().__init__()
48
+ self.weight = nn.Parameter(torch.ones(hidden_size))
49
+ self.variance_epsilon = eps
50
+
51
+ def forward(self, hidden_states):
52
+ input_dtype = hidden_states.dtype
53
+ hidden_states = hidden_states.to(torch.float32)
54
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
55
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
56
+ return (self.weight * hidden_states).to(input_dtype) # main diff with Llama
57
+
58
+ def extra_repr(self):
59
+ return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
60
+
61
+
62
+ class GptOssDenseMLP(nn.Module):
63
+ """Dense MLP layer for GptOssDense. Uses the same activation as GptOss experts but without routing."""
64
+
65
+ def __init__(self, config):
66
+ super().__init__()
67
+ self.intermediate_size = config.intermediate_size
68
+ self.hidden_size = config.hidden_size
69
+ # Combined gate and up projection
70
+ self.gate_up_proj = nn.Linear(self.hidden_size, 2 * self.intermediate_size, bias=True)
71
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=True)
72
+ self.alpha = 1.702
73
+ self.limit = 7.0
74
+
75
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
76
+ """
77
+ Args:
78
+ hidden_states (torch.Tensor): (batch_size, seq_len, hidden_size)
79
+ Returns:
80
+ torch.Tensor: (batch_size, seq_len, hidden_size)
81
+ """
82
+ # Apply combined gate and up projection
83
+ gate_up = self.gate_up_proj(hidden_states)
84
+ # Split into gate and up components
85
+ gate, up = gate_up[..., ::2], gate_up[..., 1::2]
86
+ # Apply clamping
87
+ gate = gate.clamp(min=None, max=self.limit)
88
+ up = up.clamp(min=-self.limit, max=self.limit)
89
+ # Apply GLU activation
90
+ glu = gate * torch.sigmoid(gate * self.alpha)
91
+ gated_output = (up + 1) * glu
92
+ # Project back to hidden size
93
+ output = self.down_proj(gated_output)
94
+ return output
95
+
96
+
97
+ class GptOssDenseRotaryEmbedding(nn.Module):
98
+ inv_freq: torch.Tensor # fix linting for `register_buffer`
99
+
100
+ def __init__(self, config: GptOssDenseConfig, device=None):
101
+ super().__init__()
102
+ self.max_seq_len_cached = config.max_position_embeddings
103
+ self.original_max_seq_len = config.max_position_embeddings
104
+
105
+ self.config = config
106
+
107
+ self.rope_type = self.config.rope_parameters["rope_type"]
108
+ rope_init_fn: Callable = self.compute_default_rope_parameters
109
+ if self.rope_type != "default":
110
+ rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
111
+ inv_freq, self.attention_scaling = rope_init_fn(self.config, device)
112
+
113
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
114
+ self.original_inv_freq = inv_freq
115
+
116
+ @staticmethod
117
+ def compute_default_rope_parameters(
118
+ config: Optional[GptOssDenseConfig] = None,
119
+ device: Optional["torch.device"] = None,
120
+ seq_len: Optional[int] = None,
121
+ ) -> tuple["torch.Tensor", float]:
122
+ """
123
+ Computes the inverse frequencies according to the original RoPE implementation
124
+ Args:
125
+ config ([`~transformers.PreTrainedConfig`]):
126
+ The model configuration.
127
+ device (`torch.device`):
128
+ The device to use for initialization of the inverse frequencies.
129
+ seq_len (`int`, *optional*):
130
+ The current sequence length. Unused for this type of RoPE.
131
+ Returns:
132
+ Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the
133
+ post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE).
134
+ """
135
+ base = config.rope_parameters["rope_theta"]
136
+ dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads
137
+
138
+ attention_factor = 1.0 # Unused in this type of RoPE
139
+
140
+ # Compute the inverse frequencies
141
+ inv_freq = 1.0 / (
142
+ base ** (torch.arange(0, dim, 2, dtype=torch.int64).to(device=device, dtype=torch.float) / dim)
143
+ )
144
+ return inv_freq, attention_factor
145
+
146
+ @torch.no_grad()
147
+ @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
148
+ def forward(self, x, position_ids):
149
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
150
+ position_ids_expanded = position_ids[:, None, :].float()
151
+
152
+ device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
153
+ with torch.autocast(device_type=device_type, enabled=False): # Force float32
154
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
155
+ emb = freqs
156
+ cos = emb.cos() * self.attention_scaling
157
+ sin = emb.sin() * self.attention_scaling
158
+
159
+ return cos.to(x.dtype), sin.to(x.dtype)
160
+
161
+
162
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
163
+ """
164
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
165
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
166
+ """
167
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
168
+ if n_rep == 1:
169
+ return hidden_states
170
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
171
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
172
+
173
+
174
+ def _apply_rotary_emb(
175
+ x: torch.Tensor,
176
+ cos: torch.Tensor,
177
+ sin: torch.Tensor,
178
+ ) -> torch.Tensor:
179
+ first_half, second_half = torch.chunk(x, 2, dim=-1)
180
+ first_ = first_half * cos - second_half * sin
181
+ second_ = second_half * cos + first_half * sin
182
+ return torch.cat((first_, second_), dim=-1)
183
+
184
+
185
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
186
+ cos = cos.unsqueeze(unsqueeze_dim)
187
+ sin = sin.unsqueeze(unsqueeze_dim)
188
+ q_embed = _apply_rotary_emb(q, cos, sin)
189
+ k_embed = _apply_rotary_emb(k, cos, sin)
190
+ return q_embed, k_embed
191
+
192
+
193
+ def eager_attention_forward(
194
+ module: nn.Module,
195
+ query: torch.Tensor,
196
+ key: torch.Tensor,
197
+ value: torch.Tensor,
198
+ attention_mask: Optional[torch.Tensor],
199
+ scaling: float,
200
+ dropout: float = 0.0,
201
+ **kwargs,
202
+ ):
203
+ key_states = repeat_kv(key, module.num_key_value_groups)
204
+ value_states = repeat_kv(value, module.num_key_value_groups)
205
+ attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
206
+ if attention_mask is not None:
207
+ causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
208
+ attn_weights = attn_weights + causal_mask
209
+
210
+ sinks = module.sinks.reshape(1, -1, 1, 1).expand(query.shape[0], -1, query.shape[-2], -1)
211
+ combined_logits = torch.cat([attn_weights, sinks], dim=-1)
212
+
213
+ # This was not in the original implementation and slightly affect results; it prevents overflow in BF16/FP16
214
+ # when training with bsz>1 we clamp max values.
215
+
216
+ combined_logits = combined_logits - combined_logits.max(dim=-1, keepdim=True).values
217
+ probs = F.softmax(combined_logits, dim=-1, dtype=combined_logits.dtype)
218
+ scores = probs[..., :-1] # we drop the sink here
219
+ attn_weights = nn.functional.dropout(scores, p=dropout, training=module.training)
220
+ attn_output = torch.matmul(attn_weights, value_states)
221
+ attn_output = attn_output.transpose(1, 2).contiguous()
222
+ return attn_output, attn_weights
223
+
224
+
225
+ class GptOssDenseAttention(nn.Module):
226
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
227
+
228
+ def __init__(self, config: GptOssDenseConfig, layer_idx: int):
229
+ super().__init__()
230
+ self.layer_type = config.layer_types[layer_idx] if hasattr(config, "layer_types") else None
231
+ self.config = config
232
+ self.layer_idx = layer_idx
233
+ self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
234
+ self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
235
+ self.scaling = self.head_dim**-0.5
236
+ self.attention_dropout = config.attention_dropout
237
+ self.is_causal = True
238
+ self.q_proj = nn.Linear(
239
+ config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias
240
+ )
241
+ self.k_proj = nn.Linear(
242
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
243
+ )
244
+ self.v_proj = nn.Linear(
245
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
246
+ )
247
+ self.o_proj = nn.Linear(
248
+ config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.attention_bias
249
+ )
250
+ self.sliding_window = config.sliding_window if self.layer_type == "sliding_attention" else None
251
+ self.sinks = nn.Parameter(torch.empty(config.num_attention_heads))
252
+
253
+ def forward(
254
+ self,
255
+ hidden_states: torch.Tensor,
256
+ position_embeddings: tuple[torch.Tensor, torch.Tensor],
257
+ attention_mask: Optional[torch.Tensor],
258
+ past_key_values: Optional[Cache] = None,
259
+ cache_position: Optional[torch.LongTensor] = None,
260
+ position_ids: Optional[torch.LongTensor] = None,
261
+ **kwargs: Unpack[TransformersKwargs],
262
+ ) -> tuple[torch.Tensor, torch.Tensor]:
263
+ input_shape = hidden_states.shape[:-1]
264
+ hidden_shape = (*input_shape, -1, self.head_dim)
265
+
266
+ query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
267
+ key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
268
+ value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
269
+
270
+ cos, sin = position_embeddings
271
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
272
+
273
+ if past_key_values is not None:
274
+ cache_kwargs = {"cache_position": cache_position}
275
+ key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx, cache_kwargs)
276
+
277
+ attention_interface: Callable = eager_attention_forward
278
+ if self.config._attn_implementation != "eager":
279
+ attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
280
+
281
+ attn_output, attn_weights = attention_interface(
282
+ self,
283
+ query_states,
284
+ key_states,
285
+ value_states,
286
+ attention_mask,
287
+ dropout=0.0 if not self.training else self.attention_dropout,
288
+ scaling=self.scaling,
289
+ sliding_window=self.sliding_window,
290
+ position_ids=position_ids,
291
+ s_aux=self.sinks, # diff with Llama
292
+ **kwargs,
293
+ )
294
+
295
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
296
+ attn_output = self.o_proj(attn_output)
297
+ return attn_output, attn_weights
298
+
299
+
300
+ class GptOssDenseDecoderLayer(GradientCheckpointingLayer):
301
+ def __init__(self, config: GptOssDenseConfig, layer_idx: int):
302
+ super().__init__()
303
+ self.hidden_size = config.hidden_size
304
+ self.self_attn = GptOssDenseAttention(config=config, layer_idx=layer_idx)
305
+ self.mlp = GptOssDenseMLP(config)
306
+ self.input_layernorm = GptOssDenseRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
307
+ self.post_attention_layernorm = GptOssDenseRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
308
+ self.attention_type = config.layer_types[layer_idx]
309
+
310
+ def forward(
311
+ self,
312
+ hidden_states: torch.Tensor,
313
+ attention_mask: Optional[torch.Tensor] = None,
314
+ position_ids: Optional[torch.LongTensor] = None,
315
+ past_key_values: Optional[Cache] = None,
316
+ use_cache: Optional[bool] = False,
317
+ cache_position: Optional[torch.LongTensor] = None,
318
+ position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None,
319
+ **kwargs: Unpack[TransformersKwargs],
320
+ ) -> torch.Tensor:
321
+ residual = hidden_states
322
+ hidden_states = self.input_layernorm(hidden_states)
323
+ # Self Attention
324
+ hidden_states, _ = self.self_attn(
325
+ hidden_states=hidden_states,
326
+ attention_mask=attention_mask,
327
+ position_ids=position_ids,
328
+ past_key_values=past_key_values,
329
+ use_cache=use_cache,
330
+ cache_position=cache_position,
331
+ position_embeddings=position_embeddings,
332
+ **kwargs,
333
+ )
334
+ hidden_states = residual + hidden_states
335
+
336
+ # Fully Connected
337
+ residual = hidden_states
338
+ hidden_states = self.post_attention_layernorm(hidden_states)
339
+ hidden_states = self.mlp(hidden_states)
340
+ hidden_states = residual + hidden_states
341
+ return hidden_states
342
+
343
+
344
+ @auto_docstring
345
+ class GptOssDensePreTrainedModel(PreTrainedModel):
346
+ config: GptOssDenseConfig
347
+ base_model_prefix = "model"
348
+ supports_gradient_checkpointing = True
349
+ _no_split_modules = ["GptOssDenseDecoderLayer"]
350
+ _skip_keys_device_placement = ["past_key_values"]
351
+ _supports_flash_attn = True
352
+ _supports_sdpa = False
353
+ _supports_flex_attn = True
354
+
355
+ _can_compile_fullgraph = True
356
+ _supports_attention_backend = True
357
+ _can_record_outputs = {
358
+ "hidden_states": GptOssDenseDecoderLayer,
359
+ "attentions": GptOssDenseAttention,
360
+ }
361
+ _keep_in_fp32_modules = ["post_attention_layernorm", "input_layernorm", "norm"]
362
+ _supports_flash_attention = False
363
+ _supports_flex_attention = False
364
+
365
+ def _init_weights(self, module):
366
+ std = self.config.initializer_range
367
+ if isinstance(module, nn.Linear):
368
+ module.weight.data.normal_(mean=0.0, std=std)
369
+ if module.bias is not None:
370
+ module.bias.data.zero_()
371
+ elif isinstance(module, nn.Parameter):
372
+ module.data.normal_(mean=0.0, std=std)
373
+ elif isinstance(module, nn.Embedding):
374
+ module.weight.data.normal_(mean=0.0, std=std)
375
+ if module.padding_idx is not None:
376
+ module.weight.data[module.padding_idx].zero_()
377
+ elif isinstance(module, GptOssDenseRMSNorm):
378
+ module.weight.data.fill_(1.0)
379
+ elif isinstance(module, GptOssDenseMLP):
380
+ module.gate_up_proj.weight.data.normal_(mean=0.0, std=std)
381
+ module.gate_up_proj.bias.data.zero_()
382
+ module.down_proj.weight.data.normal_(mean=0.0, std=std)
383
+ module.down_proj.bias.data.zero_()
384
+ elif isinstance(module, GptOssDenseAttention):
385
+ module.sinks.data.normal_(mean=0.0, std=std)
386
+
387
+
388
+ @auto_docstring
389
+ class GptOssDenseModel(GptOssDensePreTrainedModel):
390
+ """
391
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`GptOssDenseDecoderLayer`]
392
+
393
+ Args:
394
+ config: GptOssDenseConfig
395
+ """
396
+
397
+ _no_split_modules = ["GptOssDenseDecoderLayer"]
398
+
399
+ def __init__(self, config: GptOssDenseConfig):
400
+ super().__init__(config)
401
+ self.padding_idx = config.pad_token_id
402
+ self.vocab_size = config.vocab_size
403
+
404
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
405
+ self.layers = nn.ModuleList(
406
+ [GptOssDenseDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
407
+ )
408
+ self.norm = GptOssDenseRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
409
+ self.rotary_emb = GptOssDenseRotaryEmbedding(config=config)
410
+ self.gradient_checkpointing = False
411
+
412
+ # Initialize weights and apply final processing
413
+ self.post_init()
414
+
415
+ @check_model_inputs()
416
+ @auto_docstring
417
+ def forward(
418
+ self,
419
+ input_ids: Optional[torch.LongTensor] = None,
420
+ attention_mask: Optional[torch.Tensor] = None,
421
+ position_ids: Optional[torch.LongTensor] = None,
422
+ past_key_values: Optional[Cache] = None,
423
+ inputs_embeds: Optional[torch.FloatTensor] = None,
424
+ use_cache: Optional[bool] = None,
425
+ cache_position: Optional[torch.LongTensor] = None,
426
+ **kwargs: Unpack[TransformersKwargs],
427
+ ) -> BaseModelOutputWithPast:
428
+ if (input_ids is None) ^ (inputs_embeds is not None):
429
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
430
+
431
+ if use_cache and past_key_values is None:
432
+ past_key_values = DynamicCache(config=self.config)
433
+
434
+ if inputs_embeds is None:
435
+ inputs_embeds = self.embed_tokens(input_ids)
436
+
437
+ if cache_position is None:
438
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
439
+ cache_position = torch.arange(
440
+ past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
441
+ )
442
+ if position_ids is None:
443
+ position_ids = cache_position.unsqueeze(0)
444
+
445
+ # It may already have been prepared by e.g. `generate`
446
+ if not isinstance(causal_mask_mapping := attention_mask, dict):
447
+ mask_kwargs = {
448
+ "config": self.config,
449
+ "input_embeds": inputs_embeds,
450
+ "attention_mask": attention_mask,
451
+ "cache_position": cache_position,
452
+ "past_key_values": past_key_values,
453
+ }
454
+ causal_mask_mapping = {
455
+ "full_attention": create_causal_mask(**mask_kwargs),
456
+ "sliding_attention": create_sliding_window_causal_mask(**mask_kwargs),
457
+ }
458
+
459
+ hidden_states = inputs_embeds
460
+ position_embeddings = self.rotary_emb(hidden_states, position_ids)
461
+
462
+ for decoder_layer in self.layers:
463
+ hidden_states = decoder_layer(
464
+ hidden_states,
465
+ attention_mask=causal_mask_mapping[decoder_layer.attention_type],
466
+ position_embeddings=position_embeddings,
467
+ position_ids=position_ids,
468
+ past_key_values=past_key_values,
469
+ use_cache=use_cache,
470
+ cache_position=cache_position,
471
+ **kwargs,
472
+ )
473
+ hidden_states = self.norm(hidden_states)
474
+ return BaseModelOutputWithPast(
475
+ last_hidden_state=hidden_states,
476
+ past_key_values=past_key_values,
477
+ )
478
+
479
+
480
+ @auto_docstring
481
+ class GptOssDenseForCausalLM(GptOssDensePreTrainedModel):
482
+ _tied_weights_keys = ["lm_head.weight"]
483
+ _tp_plan = {"lm_head": "colwise_rep"}
484
+ _pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
485
+
486
+ def __init__(self, config):
487
+ super().__init__(config)
488
+ self.model = GptOssDenseModel(config)
489
+ self.vocab_size = config.vocab_size
490
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
491
+
492
+ # Initialize weights and apply final processing
493
+ self.post_init()
494
+
495
+ def forward(
496
+ self,
497
+ input_ids: Optional[torch.LongTensor] = None,
498
+ attention_mask: Optional[torch.Tensor] = None,
499
+ position_ids: Optional[torch.LongTensor] = None,
500
+ past_key_values: Optional[Cache] = None,
501
+ inputs_embeds: Optional[torch.FloatTensor] = None,
502
+ labels: Optional[torch.LongTensor] = None,
503
+ use_cache: Optional[bool] = None,
504
+ cache_position: Optional[torch.LongTensor] = None,
505
+ **kwargs: Unpack[TransformersKwargs],
506
+ ) -> CausalLMOutputWithPast:
507
+ r"""
508
+ Args:
509
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
510
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
511
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
512
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
513
+
514
+ Returns:
515
+
516
+ Example:
517
+
518
+ ```python
519
+ >>> from transformers import AutoTokenizer, GptOssDenseForCausalLM
520
+
521
+ >>> model = GptOssDenseForCausalLM.from_pretrained("USERNAME/MODEL_NAME")
522
+ >>> tokenizer = AutoTokenizer.from_pretrained("USERNAME/MODEL_NAME")
523
+
524
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
525
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
526
+
527
+ >>> # Generate
528
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
529
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
530
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
531
+ ```"""
532
+
533
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
534
+ outputs: BaseModelOutputWithPast = self.model(
535
+ input_ids=input_ids,
536
+ attention_mask=attention_mask,
537
+ position_ids=position_ids,
538
+ past_key_values=past_key_values,
539
+ inputs_embeds=inputs_embeds,
540
+ use_cache=use_cache,
541
+ cache_position=cache_position,
542
+ **kwargs,
543
+ )
544
+
545
+ hidden_states = outputs.last_hidden_state
546
+ logits = self.lm_head(hidden_states)
547
+
548
+ loss = None
549
+ if labels is not None:
550
+ # Shift so that tokens < n predict n
551
+ shift_logits = logits[..., :-1, :].contiguous()
552
+ shift_labels = labels[..., 1:].contiguous()
553
+ # Flatten the tokens
554
+ loss_fct = nn.CrossEntropyLoss()
555
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
556
+ shift_labels = shift_labels.view(-1)
557
+ # Enable model parallelism
558
+ shift_labels = shift_labels.to(shift_logits.device)
559
+ loss = loss_fct(shift_logits, shift_labels)
560
+
561
+ return CausalLMOutputWithPast(
562
+ loss=loss,
563
+ logits=logits,
564
+ past_key_values=outputs.past_key_values,
565
+ hidden_states=outputs.hidden_states,
566
+ attentions=outputs.attentions,
567
+ )
568
+
569
+
570
+ __all__ = ["GptOssDenseForCausalLM", "GptOssDenseModel", "GptOssDensePreTrainedModel"]