Add fixed Raven package for Quasar hybrid generation

#3
by NiroQ - opened
raven/__init__.py ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+
3
+ from raven.models.raven import RavenConfig, RavenForCausalLM, RavenModel
4
+
5
+ __all__ = [
6
+ 'RavenConfig', 'RavenForCausalLM', 'RavenModel',
7
+ ]
raven/layers/__init__.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+
3
+ from raven.layers.raven import RavenAttention
4
+
5
+ __all__ = ['RavenAttention']
raven/layers/raven.py ADDED
@@ -0,0 +1,331 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+
3
+ from __future__ import annotations
4
+
5
+ import warnings
6
+ from typing import TYPE_CHECKING, Dict, Optional, Tuple
7
+
8
+ import torch
9
+ import torch.nn as nn
10
+ import math
11
+ import torch.nn.functional as F
12
+ from einops import rearrange, repeat
13
+
14
+ from fla.layers.utils import get_unpad_data, index_first_axis, pad_input
15
+ from fla.modules.feature_map import ReLUFeatureMap, SwishFeatureMap, T2RFeatureMap
16
+ from fla.modules.layernorm import rms_norm_linear
17
+ from fla.ops.gsa import chunk_gsa as chunk_raven, fused_recurrent_gsa as fused_recurrent_raven
18
+
19
+
20
+ from fla.ops.utils.index import prepare_lens_from_mask
21
+
22
+
23
+ from fla.modules import FusedRMSNormGated , RMSNorm, RotaryEmbedding #Added for RoPE
24
+
25
+ if TYPE_CHECKING:
26
+ from transformers.processing_utils import Unpack
27
+
28
+ from fla.models.utils import Cache
29
+
30
+ def _max_offset(seqlen_offset):
31
+ if seqlen_offset is None:
32
+ return 0
33
+ if isinstance(seqlen_offset, int):
34
+ # scalar offset, nothing fancy
35
+ return seqlen_offset
36
+ if isinstance(seqlen_offset, torch.Tensor):
37
+ # tensor of offsets -> take max
38
+ return int(seqlen_offset.max().item())
39
+ # list/tuple/other iterables
40
+ return max(seqlen_offset)
41
+
42
+
43
+ class RavenAttention(nn.Module):
44
+
45
+ def __init__(
46
+ self,
47
+ mode: str = 'chunk',
48
+ hidden_size: int = 1024,
49
+ expand_k: float = 1.,
50
+ expand_v: float = 1.,
51
+ num_heads: int = 4,
52
+ num_kv_heads: Optional[int] = None,
53
+ num_slots: Optional[int] = None,
54
+ elementwise_affine: Optional[bool] = True,
55
+ norm_eps: float = 1e-5,
56
+ gate_logit_normalizer: int = 8,
57
+ feature_map: str = 'swish',
58
+ use_output_gate: bool = False,
59
+ use_norm: bool = True,
60
+ layer_idx: Optional[int] = None,
61
+ scale: Optional[float] = 1.,
62
+ decay_type: str = 'Mamba2',
63
+ topk: int = 32,
64
+ bias_rmm: bool = False,
65
+ add_gumbel_noise: bool = True,
66
+ router_score: str = 'sigmoid',
67
+ router_type: str = 'lin',
68
+ use_rope: bool = False,
69
+ **kwargs
70
+ ) -> RavenAttention:
71
+ super().__init__()
72
+
73
+ self.mode = mode
74
+ self.decay_type = decay_type
75
+ self.hidden_size = hidden_size
76
+ self.expand_k = expand_k
77
+ self.expand_v = expand_v
78
+ self.num_heads = num_heads
79
+ self.num_kv_heads = num_heads if num_kv_heads is None else num_kv_heads
80
+ self.num_kv_groups = self.num_heads // self.num_kv_heads
81
+ self.key_dim = int(hidden_size * expand_k)
82
+ self.value_dim = int(hidden_size * expand_v)
83
+ self.key_dim_per_group = self.key_dim // self.num_kv_groups
84
+ self.value_dim_per_group = self.value_dim // self.num_kv_groups
85
+ self.head_k_dim = self.key_dim // self.num_heads
86
+ self.head_v_dim = self.value_dim // self.num_heads
87
+ self.topk = topk
88
+ self.use_output_gate = use_output_gate
89
+ self.use_rope = use_rope
90
+ self.gate_logit_normalizer = gate_logit_normalizer
91
+ self.use_norm = use_norm
92
+ self.scale = scale
93
+ self.rope_theta = 10000.
94
+
95
+ ## For Router Design
96
+ self.bias_rmm = bias_rmm # For no gumbel router with bias
97
+ self.add_gumbel_noise = add_gumbel_noise # For no gumbel router with bias
98
+ self.router_score = router_score
99
+ self.router_type = router_type
100
+
101
+ if num_slots is None:
102
+ num_slots = self.head_k_dim
103
+ self.num_slots = num_slots
104
+
105
+ self.layer_idx = layer_idx
106
+
107
+ if layer_idx is None:
108
+ warnings.warn(
109
+ f"Instantiating {self.__class__.__name__} without passing `layer_idx` is not recommended and will "
110
+ "to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` "
111
+ "when creating this class."
112
+ )
113
+
114
+ self.register_module('feature_map', None)
115
+ if feature_map == 'swish':
116
+ self.feature_map = SwishFeatureMap()
117
+ elif feature_map == 'relu':
118
+ self.feature_map = ReLUFeatureMap()
119
+ elif feature_map == 't2r':
120
+ self.feature_map = T2RFeatureMap(self.head_k_dim, self.head_k_dim)
121
+ else:
122
+ raise NotImplementedError(f"Feature map `{feature_map}` is not supported now.")
123
+
124
+ ## ===== QKV Proj =====
125
+ self.q_proj = nn.Linear(self.hidden_size, self.key_dim, bias=False)
126
+ self.k_proj = nn.Linear(self.hidden_size, self.key_dim_per_group, bias=False)
127
+ self.v_proj = nn.Linear(self.hidden_size, self.value_dim_per_group, bias=False)
128
+
129
+ ## ===== Forget Gate/ Decay =====
130
+ if self.decay_type == 'Mamba2':
131
+ # Decay of Mamba2
132
+ self.a_proj = nn.Linear(self.hidden_size, self.num_heads, bias=False)
133
+ A = torch.empty(self.num_heads, dtype=torch.float32).uniform_(0, 16)
134
+ self.A_log = nn.Parameter(torch.log(A))
135
+ self.A_log._no_weight_decay = True
136
+ # hard coded for now
137
+ dt_min = 0.001
138
+ dt_max = 0.1
139
+ dt_init_floor = 1e-4
140
+ dt = torch.exp(
141
+ torch.rand(self.num_heads) * (math.log(dt_max) - math.log(dt_min))
142
+ + math.log(dt_min)
143
+ )
144
+ dt = torch.clamp(dt, min=dt_init_floor)
145
+ # Inverse of softplus: https://github.com/pytorch/pytorch/issues/72759
146
+ inv_dt = dt + torch.log(-torch.expm1(-dt))
147
+ self.dt_bias = nn.Parameter(inv_dt)
148
+ # Just to be explicit. Without this we already don't put wd on dt_bias because of the check
149
+ # name.endswith("bias") in param_grouping.py
150
+ self.dt_bias._no_weight_decay = True
151
+
152
+ elif self.decay_type == 'GLA':
153
+ self.f_proj = nn.Linear(self.hidden_size, self.num_kv_heads * self.num_slots, bias=False)
154
+
155
+ ## ===== Router =====
156
+ if self.bias_rmm:
157
+ self.r_bias = nn.Parameter(torch.empty( ( self.num_heads , self.num_slots) , dtype=torch.float32))
158
+
159
+ if self.router_type == 'lin':
160
+ self.r_proj = nn.Linear(self.hidden_size, self.num_heads * self.num_slots , bias=False)
161
+
162
+ elif self.router_type == 'mlp':
163
+ self.r_proj = nn.Sequential(
164
+ nn.Linear(self.hidden_size, self.hidden_size, bias=True),
165
+ nn.GELU(),
166
+ nn.Linear(self.hidden_size, self.num_heads * self.num_slots, bias=False) )
167
+
168
+ self.score_fn = (
169
+ (lambda x: torch.sigmoid(x))
170
+ if self.router_score == "sigmoid"
171
+ else (lambda x: torch.softmax(x, dim=-1))
172
+ )
173
+
174
+
175
+ ## ===== RoPE =====
176
+ if self.use_rope:
177
+ self.rotary = RotaryEmbedding(dim=self.head_k_dim, base=self.rope_theta) # Added for RoPE
178
+
179
+ ## ===== QK Norm =====
180
+ self.q_norm = RMSNorm(self.head_k_dim, elementwise_affine, eps=norm_eps)
181
+ self.k_norm = RMSNorm(self.head_k_dim, elementwise_affine, eps=norm_eps)
182
+
183
+ ## ===== Output Layer =====
184
+ if self.use_output_gate:
185
+ self.o_gate_proj = nn.Linear(hidden_size, self.value_dim, bias=False)
186
+ self.o_norm = FusedRMSNormGated(self.head_v_dim, eps=norm_eps)
187
+ else:
188
+ self.g_norm = RMSNorm(self.hidden_size, elementwise_affine, eps=norm_eps)
189
+
190
+ self.o_proj = nn.Linear(self.value_dim, self.hidden_size, bias=False)
191
+
192
+ def forward(
193
+ self,
194
+ hidden_states: torch.Tensor,
195
+ attention_mask: Optional[torch.Tensor] = None,
196
+ past_key_values: Optional[Cache] = None,
197
+ use_cache: Optional[bool] = False,
198
+ output_attentions: Optional[bool] = False,
199
+ **kwargs: Unpack[Dict]
200
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Cache]]:
201
+ if attention_mask is not None:
202
+ assert len(attention_mask.shape) == 2, (
203
+ "Expected attention_mask as a 0-1 matrix with shape [batch_size, seq_len] "
204
+ "for padding purposes (0 indicating padding). "
205
+ "Arbitrary attention masks of shape [batch_size, seq_len, seq_len] are not allowed."
206
+ )
207
+
208
+ batch_size, q_len, _ = hidden_states.shape
209
+ mode = 'fused_recurrent' if hidden_states.shape[1] <= 64 else self.mode
210
+ seqlen_offset, max_seqlen = 0, q_len # Added for RoPE
211
+
212
+ last_state = None
213
+ if past_key_values is not None and len(past_key_values) > self.layer_idx:
214
+ seqlen_offset = past_key_values.get_seq_length(self.layer_idx) # Added for RoPE
215
+ last_state = past_key_values[self.layer_idx]
216
+ max_seqlen = q_len + seqlen_offset # Added for RoPE
217
+
218
+ cu_seqlens = kwargs.get('cu_seqlens', None)
219
+ if attention_mask is not None:
220
+ indices, cu_seqlens, _ = get_unpad_data(attention_mask[:, -q_len:])
221
+ hidden_states = index_first_axis(rearrange(hidden_states, "b s ... -> (b s) ..."), indices).unsqueeze(0) # to deliminate the offsets of padding tokens
222
+ seqlen_offset = seqlen_offset + prepare_lens_from_mask(attention_mask) - attention_mask.shape[-1] # Added for RoPE
223
+ max_seqlen = max(q_len, q_len + _max_offset(seqlen_offset)) # Added for RoPE
224
+
225
+ q = rearrange(self.q_proj(hidden_states), '... (h d) -> ... h d', d=self.head_k_dim)
226
+ k = rearrange(self.k_proj(hidden_states), '... (h d) -> ... h d', d=self.head_k_dim)
227
+ v = rearrange(self.v_proj(hidden_states), '... (h d) -> ... h d', d=self.head_v_dim)
228
+ router = rearrange(self.r_proj(hidden_states) , '... (h m) -> ... h m', m=self.num_slots)
229
+
230
+ if self.decay_type == 'Mamba2':
231
+ # Build Mamba2 Decay
232
+ f = (- self.A_log.float().exp() * F.softplus(self.a_proj(hidden_states).float() + self.dt_bias)).unsqueeze(-1)
233
+ elif self.decay_type == 'GLA':
234
+ f = rearrange(self.f_proj(hidden_states) , '... (h m) -> ... h m', m=self.num_slots)
235
+ f = F.logsigmoid(f) / self.gate_logit_normalizer
236
+ if self.num_kv_groups > 1:
237
+ f = repeat(f, '... h d -> ... (h g) d', g=self.num_kv_groups)
238
+
239
+ if self.feature_map is not None:
240
+ q, k = map(lambda x: self.feature_map(x), (q, k))
241
+
242
+ # QK Norm
243
+ q, k = self.q_norm(q), self.k_norm(k)
244
+
245
+ if self.use_rope:
246
+ assert batch_size == 1, "RoPE is not supported for batch size > 1"
247
+ max_seqlen = max(max_seqlen, 8192) # Added for RoPE
248
+ q, k = self.rotary(q, k, seqlen_offset=seqlen_offset, max_seqlen=max_seqlen, cu_seqlens=cu_seqlens) #Added for RoPE
249
+
250
+ # V Feature map
251
+ v = F.silu(v)
252
+
253
+ # Build RMM Router
254
+ if self.add_gumbel_noise:
255
+ if self.training:
256
+ router = router - torch.empty_like(router).exponential_().log()
257
+
258
+ orig_scores = self.score_fn(router)
259
+ if self.bias_rmm:
260
+ scores = orig_scores + self.r_bias.float()
261
+ else:
262
+ scores = orig_scores
263
+
264
+ route_idx = scores.topk(self.topk, dim=-1).indices
265
+ topk_weights = torch.gather(orig_scores, dim=-1, index=route_idx)
266
+
267
+ if self.router_score == 'sigmoid':
268
+ topk_weights /= (topk_weights.sum(dim=-1, keepdim=True) + 1e-9)
269
+
270
+ s_multihot = torch.zeros_like(router).scatter_(-1, route_idx, topk_weights.to(router.dtype))
271
+
272
+ f = (f*s_multihot).to(q.dtype)
273
+ s = (1-f.exp()).to(q.dtype)
274
+
275
+ recurrent_state = last_state['recurrent_state'] if last_state is not None else None
276
+ if self.num_kv_groups > 1:
277
+ k, v = map(lambda x: repeat(x, '... h d -> ... (h g) d', g=self.num_kv_groups), (k, v))
278
+
279
+ assert q.shape[-2] == k.shape[-2] == v.shape[-2] == f.shape[-2] == s.shape[-2], (
280
+ f"Raven head mismatch: q={q.shape}, k={k.shape}, v={v.shape}, f={f.shape}, s={s.shape}"
281
+ )
282
+
283
+ if mode == 'fused_recurrent':
284
+ o, recurrent_state = fused_recurrent_raven(
285
+ q=q,
286
+ k=k,
287
+ v=v,
288
+ s=s,
289
+ g=f,
290
+ initial_state=recurrent_state,
291
+ output_final_state=use_cache,
292
+ scale=self.scale,
293
+ cu_seqlens=cu_seqlens,
294
+ )
295
+ elif mode == 'chunk':
296
+ o, recurrent_state = chunk_raven(
297
+ q=q,
298
+ k=k,
299
+ v=v,
300
+ s=s,
301
+ g=f,
302
+ initial_state=recurrent_state,
303
+ output_final_state=use_cache,
304
+ scale=self.scale,
305
+ cu_seqlens=cu_seqlens,
306
+ )
307
+ else:
308
+ raise NotImplementedError(f"Not supported mode `{mode}`.")
309
+
310
+ if past_key_values is not None:
311
+ past_key_values.update(
312
+ recurrent_state=recurrent_state,
313
+ conv_state=None,
314
+ layer_idx=self.layer_idx,
315
+ offset=q_len
316
+ )
317
+
318
+
319
+ if self.use_output_gate:
320
+ gate_out = rearrange(self.o_gate_proj(hidden_states), '... (h d) -> ... h d', d=self.head_v_dim)
321
+ o = self.o_norm(F.silu(o), gate_out)
322
+ o = rearrange(o, '... h d -> ... (h d)')
323
+ o = self.o_proj(o)
324
+ else:
325
+ o = rearrange(o, '... h d -> ... (h d)')
326
+ o = rms_norm_linear(F.silu(o), self.g_norm.weight, self.g_norm.bias, self.o_proj.weight, self.o_proj.bias)
327
+
328
+ if attention_mask is not None:
329
+ o = pad_input(o.squeeze(0), indices, batch_size, q_len)
330
+
331
+ return o, None, past_key_values
raven/models/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ # -*- coding: utf-8 -*-
raven/models/raven/__init__.py ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+
3
+ from transformers import AutoConfig, AutoModel, AutoModelForCausalLM
4
+
5
+ from raven.models.raven.configuration_raven import RavenConfig
6
+ from raven.models.raven.modeling_raven import RavenForCausalLM, RavenModel
7
+
8
+ AutoConfig.register(RavenConfig.model_type, RavenConfig, exist_ok=True)
9
+ AutoModel.register(RavenConfig, RavenModel, exist_ok=True)
10
+ AutoModelForCausalLM.register(RavenConfig, RavenForCausalLM, exist_ok=True)
11
+
12
+ __all__ = ['RavenConfig', 'RavenForCausalLM', 'RavenModel']
raven/models/raven/configuration_raven.py ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+
3
+ from typing import Dict, Optional
4
+
5
+ from transformers.configuration_utils import PretrainedConfig
6
+
7
+
8
+ class RavenConfig(PretrainedConfig):
9
+
10
+ model_type = 'raven'
11
+ keys_to_ignore_at_inference = ['past_key_values']
12
+
13
+ def __init__(
14
+ self,
15
+ hidden_size: int = 2048,
16
+ gate_logit_normalizer: Optional[int] = 8,
17
+ clamp_min: Optional[float] = None,
18
+ clamp_max: Optional[float] = None,
19
+ hidden_ratio: Optional[int] = 4,
20
+ intermediate_size: Optional[int] = None,
21
+ num_hidden_layers: int = 24,
22
+ num_heads: int = 4,
23
+ num_kv_heads: Optional[int] = None,
24
+ num_slots: Optional[int] = 64,
25
+ use_short_conv: bool = False,
26
+ conv_size: int = 4,
27
+ exapnd_k: float = 1,
28
+ exapnd_v: float = 1,
29
+ feature_map: str = 'swish',
30
+ use_output_gate: bool = False,
31
+ use_norm: bool = True,
32
+ max_position_embeddings: int = 2048,
33
+ hidden_act: str = "swish",
34
+ decay_type: str = 'Mamba2',
35
+ bias_rmm: bool = False,
36
+ add_gumbel_noise: bool = True,
37
+ router_score: str = 'sigmoid',
38
+ router_type: str = 'lin',
39
+ topk = 32,
40
+ elementwise_affine: Optional[bool] = True,
41
+ norm_eps: float = 1e-6,
42
+ attn: Optional[Dict] = None,
43
+ use_cache: bool = True,
44
+ pad_token_id: Optional[int] = None,
45
+ bos_token_id: int = 1,
46
+ eos_token_id: int = 2,
47
+ initializer_range: float = 0.02,
48
+ tie_word_embeddings: bool = False,
49
+ fuse_norm: bool = True,
50
+ fuse_swiglu: bool = True,
51
+ fuse_cross_entropy: bool = True,
52
+ use_l2warp: bool = False,
53
+ vocab_size: int = 32000,
54
+ **kwargs
55
+ ):
56
+ self.hidden_size = hidden_size
57
+ self.gate_logit_normalizer = gate_logit_normalizer
58
+ self.clamp_min = clamp_min
59
+ self.clamp_max = clamp_max
60
+ self.hidden_ratio = hidden_ratio
61
+ self.intermediate_size = intermediate_size
62
+ self.num_hidden_layers = num_hidden_layers
63
+ self.num_heads = num_heads
64
+ self.num_kv_heads = num_kv_heads
65
+ self.num_slots = num_slots
66
+ self.use_short_conv = use_short_conv
67
+ self.conv_size = conv_size
68
+ self.expand_k = exapnd_k
69
+ self.expand_v = exapnd_v
70
+ self.feature_map = feature_map
71
+ self.use_output_gate = use_output_gate
72
+ self.use_norm = use_norm
73
+ self.max_position_embeddings = max_position_embeddings
74
+ self.hidden_act = hidden_act
75
+ self.elementwise_affine = elementwise_affine
76
+ self.norm_eps = norm_eps
77
+ self.attn = attn
78
+ self.use_cache = use_cache
79
+ self.initializer_range = initializer_range
80
+ self.decay_type = decay_type
81
+ self.topk = topk
82
+ self.bias_rmm = bias_rmm
83
+ self.add_gumbel_noise = add_gumbel_noise
84
+ self.router_score = router_score
85
+ self.router_type = router_type
86
+ self.fuse_norm = fuse_norm
87
+ self.fuse_swiglu = fuse_swiglu
88
+ self.fuse_cross_entropy = fuse_cross_entropy
89
+ self.use_l2warp = use_l2warp
90
+ self.vocab_size = vocab_size
91
+
92
+ if attn is not None:
93
+ if not isinstance(attn, Dict):
94
+ raise ValueError("attn must be a dictionary")
95
+ if 'layers' not in attn:
96
+ raise ValueError("Layer indices must be provided to initialize hybrid attention layers")
97
+ if 'num_heads' not in attn:
98
+ raise ValueError("Number of heads must be provided to initialize hybrid attention layers")
99
+ attn['num_kv_heads'] = attn.get('num_kv_heads', attn['num_heads'])
100
+ attn['qkv_bias'] = attn.get('qkv_bias', False)
101
+ attn['window_size'] = attn.get('window_size', None)
102
+ attn['rope_theta'] = attn.get('rope_theta', 10000.)
103
+ attn['use_rope'] = attn.get('use_rope', True)
104
+
105
+ super().__init__(
106
+ pad_token_id=pad_token_id,
107
+ bos_token_id=bos_token_id,
108
+ eos_token_id=eos_token_id,
109
+ tie_word_embeddings=tie_word_embeddings,
110
+ **kwargs,
111
+ )
raven/models/raven/modeling_raven.py ADDED
@@ -0,0 +1,429 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+
3
+ from __future__ import annotations
4
+
5
+ import math
6
+ import warnings
7
+ from typing import TYPE_CHECKING, Dict, List, Optional, Tuple, Union
8
+
9
+ import torch
10
+ import torch.nn as nn
11
+ import torch.utils.checkpoint
12
+ from transformers.generation import GenerationMixin
13
+ from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
14
+ from transformers.modeling_utils import PreTrainedModel
15
+ from transformers.utils import logging
16
+ from transformers.utils.deprecation import deprecate_kwarg
17
+
18
+ from fla.layers.attn import Attention
19
+ from raven.layers.raven import RavenAttention
20
+ from raven.models.raven.configuration_raven import RavenConfig
21
+ from fla.models.utils import Cache
22
+ from fla.modules import FusedCrossEntropyLoss, FusedLinearCrossEntropyLoss
23
+ from fla.modules import GatedMLP as GSAMLP
24
+ from fla.modules import RMSNorm
25
+ from fla.modules.l2warp import l2_warp
26
+
27
+ if TYPE_CHECKING:
28
+ from transformers.processing_utils import Unpack
29
+
30
+ logger = logging.get_logger(__name__)
31
+
32
+
33
+ class RavenBlock(nn.Module):
34
+ def __init__(self, config: RavenConfig, layer_idx: int):
35
+ super().__init__()
36
+
37
+ self.config = config
38
+ self.layer_idx = layer_idx
39
+
40
+ self.attn_norm = (RMSNorm if config.fuse_norm else nn.RMSNorm)(config.hidden_size, eps=config.norm_eps)
41
+ if config.attn is not None and layer_idx in config.attn['layers']:
42
+ self.attn = Attention(
43
+ hidden_size=config.hidden_size,
44
+ num_heads=config.attn['num_heads'],
45
+ num_kv_heads=config.attn['num_kv_heads'],
46
+ qkv_bias=config.attn['qkv_bias'],
47
+ window_size=config.attn['window_size'],
48
+ use_rope=config.attn['use_rope'],
49
+ rope_theta=config.attn['rope_theta'],
50
+ max_position_embeddings=config.max_position_embeddings,
51
+ layer_idx=layer_idx
52
+ )
53
+ else:
54
+ self.attn = RavenAttention(
55
+ hidden_size=config.hidden_size,
56
+ expand_k=config.expand_k,
57
+ expand_v=config.expand_v,
58
+ num_heads=config.num_heads,
59
+ num_kv_heads=config.num_kv_heads,
60
+ num_slots=config.num_slots,
61
+ use_short_conv=config.use_short_conv,
62
+ conv_size=config.conv_size,
63
+ feature_map=config.feature_map,
64
+ use_output_gate=config.use_output_gate,
65
+ use_norm=config.use_norm,
66
+ gate_fn=config.hidden_act,
67
+ topk=config.topk,
68
+ bias_rmm=config.bias_rmm,
69
+ add_gumbel_noise=config.add_gumbel_noise,
70
+ router_score=config.router_score,
71
+ router_type=config.router_type,
72
+ decay_type = config.decay_type,
73
+ gate_logit_normalizer=config.gate_logit_normalizer,
74
+ elementwise_affine=config.elementwise_affine,
75
+ norm_eps=config.norm_eps,
76
+ fuse_norm=config.fuse_norm,
77
+ layer_idx=layer_idx
78
+ )
79
+ self.mlp_norm = (RMSNorm if config.fuse_norm else nn.RMSNorm)(config.hidden_size, eps=config.norm_eps)
80
+ self.mlp = GSAMLP(
81
+ hidden_size=config.hidden_size,
82
+ hidden_ratio=config.hidden_ratio,
83
+ intermediate_size=config.intermediate_size,
84
+ hidden_act=config.hidden_act,
85
+ fuse_swiglu=config.fuse_swiglu
86
+ )
87
+
88
+ def forward(
89
+ self,
90
+ hidden_states: torch.Tensor,
91
+ attention_mask: Optional[torch.Tensor] = None,
92
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
93
+ use_cache: Optional[bool] = False,
94
+ output_attentions: Optional[bool] = False,
95
+ **kwargs: Unpack[Dict]
96
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
97
+ residual = hidden_states
98
+ hidden_states = self.attn_norm(hidden_states)
99
+ hidden_states, attentions, past_key_values = self.attn(
100
+ hidden_states=hidden_states,
101
+ attention_mask=attention_mask,
102
+ past_key_values=past_key_values,
103
+ use_cache=use_cache,
104
+ output_attentions=output_attentions,
105
+ **kwargs
106
+ )
107
+ if self.config.fuse_norm:
108
+ hidden_states, residual = self.mlp_norm(hidden_states, residual, True)
109
+ else:
110
+ hidden_states = residual + hidden_states
111
+ residual = hidden_states
112
+ hidden_states = self.mlp_norm(hidden_states)
113
+ hidden_states = self.mlp(hidden_states, **kwargs)
114
+ hidden_states = residual + hidden_states
115
+
116
+ outputs = (hidden_states, attentions, past_key_values)
117
+
118
+ return outputs
119
+
120
+
121
+ class RavenPreTrainedModel(PreTrainedModel):
122
+
123
+ config_class = RavenConfig
124
+ base_model_prefix = 'model'
125
+ supports_gradient_checkpointing = True
126
+ _no_split_modules = ['RavenBlock']
127
+ _supports_cache_class = True
128
+
129
+ def __init__(self, *inputs, **kwargs):
130
+ super().__init__(*inputs, **kwargs)
131
+
132
+ def _init_weights(
133
+ self,
134
+ module: nn.Module,
135
+ prenorm_residual_strategy: Optional[str] = None,
136
+ num_residuals_per_layer: int = 2,
137
+ ):
138
+ if isinstance(module, (nn.Linear, nn.Conv1d)):
139
+ # Slightly different from the TF version which uses truncated_normal for initialization
140
+ # cf https://github.com/pytorch/pytorch/pull/5617
141
+ nn.init.normal_(module.weight, mean=0.0, std=self.config.initializer_range)
142
+ if module.bias is not None:
143
+ nn.init.zeros_(module.bias)
144
+ elif isinstance(module, nn.Embedding):
145
+ nn.init.normal_(module.weight, mean=0.0, std=self.config.initializer_range)
146
+ elif hasattr(module, 'reset_parameters'):
147
+ module.reset_parameters()
148
+
149
+ if prenorm_residual_strategy is not None:
150
+ # Reinitialize selected weights subject to the OpenAI GPT-2 Paper Scheme:
151
+ # > A modified initialization which accounts for the accumulation on the residual path with model depth. Scale
152
+ # > the weights of residual layers at initialization by a factor of 1/√N where N is the # of residual layers.
153
+ # > -- GPT-2 :: https://openai.com/blog/better-language-models/
154
+ #
155
+ # Reference (Megatron-LM): https://github.com/NVIDIA/Megatron-LM/blob/main/megatron/model/gpt_model.py
156
+ p = None
157
+ if hasattr(module, 'o_proj'):
158
+ p = module.o_proj.weight
159
+ elif hasattr(module, 'down_proj'):
160
+ p = module.down_proj.weight
161
+ if p is not None:
162
+ # Special Scaled Initialization --> There are 2 Layer Norms per Transformer Block
163
+ # Following Pytorch init, except scale by 1/sqrt(2 * n_layer)
164
+ # We need to reinit p since this code could be called multiple times
165
+ # Having just p *= scale would repeatedly scale it down
166
+ if prenorm_residual_strategy == 'rescale':
167
+ nn.init.kaiming_uniform_(p, a=math.sqrt(5))
168
+ with torch.no_grad():
169
+ p /= math.sqrt(num_residuals_per_layer * self.config.num_hidden_layers)
170
+ elif prenorm_residual_strategy == 'zero':
171
+ nn.init.zeros_(p)
172
+ else:
173
+ raise ValueError(f"Invalid prenorm_residual_strategy: {prenorm_residual_strategy}")
174
+
175
+
176
+ class RavenModel(RavenPreTrainedModel):
177
+
178
+ def __init__(self, config: RavenConfig):
179
+ super().__init__(config)
180
+ self.padding_idx = config.pad_token_id
181
+ self.vocab_size = config.vocab_size
182
+
183
+ self.embeddings = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
184
+ self.layers = nn.ModuleList([RavenBlock(config, layer_idx) for layer_idx in range(config.num_hidden_layers)])
185
+ self.norm = (RMSNorm if config.fuse_norm else nn.RMSNorm)(config.hidden_size, eps=config.norm_eps)
186
+
187
+ self.gradient_checkpointing = False
188
+
189
+ self.post_init()
190
+
191
+ def get_input_embeddings(self):
192
+ return self.embeddings
193
+
194
+ def set_input_embeddings(self, value):
195
+ self.embeddings = value
196
+
197
+ def forward(
198
+ self,
199
+ input_ids: Optional[torch.LongTensor] = None,
200
+ attention_mask: Optional[torch.Tensor] = None, # noqa
201
+ inputs_embeds: Optional[torch.FloatTensor] = None,
202
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
203
+ use_cache: Optional[bool] = None,
204
+ output_attentions: Optional[bool] = None,
205
+ output_hidden_states: Optional[bool] = None,
206
+ return_dict: Optional[bool] = None,
207
+ **kwargs: Unpack[Dict]
208
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
209
+ if output_attentions:
210
+ warnings.warn("`RavenModel` does not `output_attentions` now, setting it to `False`.")
211
+ output_attentions = False
212
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
213
+ output_hidden_states = output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
214
+ use_cache = use_cache if use_cache is not None else (self.config.use_cache if not self.training else False)
215
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
216
+
217
+ # retrieve input_ids and inputs_embeds
218
+ if input_ids is not None and inputs_embeds is not None:
219
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
220
+ if input_ids is None and inputs_embeds is None:
221
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
222
+
223
+ if inputs_embeds is None:
224
+ inputs_embeds = self.embeddings(input_ids)
225
+ hidden_states = inputs_embeds
226
+
227
+ if use_cache and not isinstance(past_key_values, Cache):
228
+ past_key_values = Cache.from_legacy_cache(past_key_values)
229
+
230
+ if self.gradient_checkpointing and self.training and use_cache:
231
+ logger.warning_once("`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`...")
232
+ use_cache = False
233
+
234
+ all_hidden_states = () if output_hidden_states else None
235
+ all_attns = () if output_attentions else None
236
+ for layer in self.layers:
237
+ if output_hidden_states:
238
+ all_hidden_states += (hidden_states,)
239
+
240
+ if self.gradient_checkpointing and self.training:
241
+ hidden_states, attentions, past_key_values = self._gradient_checkpointing_func(
242
+ layer.__call__,
243
+ hidden_states,
244
+ attention_mask,
245
+ past_key_values,
246
+ use_cache,
247
+ output_attentions,
248
+ **kwargs
249
+ )
250
+ else:
251
+ hidden_states, attentions, past_key_values = layer(
252
+ hidden_states,
253
+ attention_mask=attention_mask,
254
+ past_key_values=past_key_values,
255
+ use_cache=use_cache,
256
+ output_attentions=output_attentions,
257
+ **kwargs
258
+ )
259
+
260
+ if output_attentions:
261
+ all_attns += (attentions,)
262
+
263
+ hidden_states = self.norm(hidden_states)
264
+
265
+ # add hidden states from the last decoder layer
266
+ if output_hidden_states:
267
+ all_hidden_states += (hidden_states,)
268
+
269
+ if not return_dict:
270
+ return tuple(i for i in [hidden_states, past_key_values, all_hidden_states, all_attns] if i is not None)
271
+ return BaseModelOutputWithPast(
272
+ last_hidden_state=hidden_states,
273
+ past_key_values=past_key_values,
274
+ hidden_states=all_hidden_states,
275
+ attentions=all_attns
276
+ )
277
+
278
+
279
+ class RavenForCausalLM(RavenPreTrainedModel, GenerationMixin):
280
+
281
+ _tied_weights_keys = ["lm_head.weight"]
282
+
283
+ def __init__(self, config):
284
+
285
+ super().__init__(config)
286
+ self.model = RavenModel(config)
287
+ self.vocab_size = config.vocab_size
288
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
289
+ self.criterion = None
290
+
291
+ # Initialize weights and apply final processing
292
+ self.post_init()
293
+
294
+ def get_input_embeddings(self):
295
+ return self.model.embeddings
296
+
297
+ def set_input_embeddings(self, value):
298
+ self.model.embeddings = value
299
+
300
+ def get_output_embeddings(self):
301
+ return self.lm_head
302
+
303
+ def set_output_embeddings(self, new_embeddings):
304
+ self.lm_head = new_embeddings
305
+
306
+ def set_decoder(self, decoder):
307
+ self.model = decoder
308
+
309
+ def get_decoder(self):
310
+ return self.model
311
+
312
+ def generate(self, *args, **kwargs):
313
+ try:
314
+ return super().generate(*args, **kwargs)
315
+ except AttributeError as exception:
316
+ if 'past_key_values' in str(exception):
317
+ raise AttributeError(
318
+ f"You tried to call `generate` with a decoding strategy that manipulates `past_key_values`, "
319
+ f"which is not supported for {self.__class__.__name__}. "
320
+ f"Try another generation strategy instead. "
321
+ f"For the available generation strategies, check this doc: "
322
+ f"https://huggingface.co/docs/transformers/en/generation_strategies#decoding-strategies"
323
+ )
324
+ else:
325
+ raise exception
326
+
327
+ @deprecate_kwarg("num_logits_to_keep", version="4.50", new_name="logits_to_keep")
328
+ def prepare_inputs_for_generation(
329
+ self,
330
+ input_ids: torch.LongTensor = None,
331
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
332
+ attention_mask: Optional[torch.Tensor] = None,
333
+ inputs_embeds: Optional[torch.Tensor] = None,
334
+ use_cache: bool = True,
335
+ logits_to_keep: Optional[int] = None,
336
+ **kwargs
337
+ ):
338
+ # only last token for `inputs_ids` if the `past_key_values` is not empty.
339
+ if past_key_values is not None and len(past_key_values) > 0:
340
+ input_ids = input_ids[:, -1:]
341
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
342
+ if inputs_embeds is not None and len(past_key_values) == 0:
343
+ model_inputs = {'inputs_embeds': inputs_embeds}
344
+ else:
345
+ # The `contiguous()` here is necessary to have a static stride during decoding. torchdynamo otherwise
346
+ # recompiles graphs as the stride of the inputs is a guard.
347
+ # Ref: https://github.com/huggingface/transformers/pull/29114
348
+ # TODO: use `next_tokens` directly instead.
349
+ model_inputs = {'input_ids': input_ids.contiguous()}
350
+
351
+ if logits_to_keep is not None:
352
+ model_inputs['logits_to_keep'] = logits_to_keep
353
+
354
+ model_inputs.update({
355
+ 'past_key_values': past_key_values,
356
+ 'use_cache': use_cache,
357
+ 'attention_mask': attention_mask,
358
+ })
359
+ return model_inputs
360
+
361
+ @deprecate_kwarg("num_logits_to_keep", version="4.50", new_name="logits_to_keep")
362
+ def forward(
363
+ self,
364
+ input_ids: torch.LongTensor = None,
365
+ attention_mask: Optional[torch.Tensor] = None,
366
+ inputs_embeds: Optional[torch.Tensor] = None,
367
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
368
+ labels: Optional[torch.LongTensor] = None,
369
+ use_cache: Optional[bool] = None,
370
+ output_attentions: Optional[bool] = None,
371
+ output_hidden_states: Optional[bool] = None,
372
+ return_dict: Optional[bool] = None,
373
+ logits_to_keep: Optional[int] = 0,
374
+ **kwargs: Unpack[Dict]
375
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
376
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
377
+ output_hidden_states = (
378
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
379
+ )
380
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
381
+
382
+ outputs = self.model(
383
+ input_ids=input_ids,
384
+ attention_mask=attention_mask,
385
+ inputs_embeds=inputs_embeds,
386
+ past_key_values=past_key_values,
387
+ use_cache=use_cache,
388
+ output_attentions=output_attentions,
389
+ output_hidden_states=output_hidden_states,
390
+ return_dict=return_dict,
391
+ **kwargs
392
+ )
393
+
394
+ hidden_states = outputs[0]
395
+ fuse_linear_and_cross_entropy = self.config.fuse_cross_entropy and self.training and labels is not None
396
+
397
+ loss, logits = None, None
398
+ if not fuse_linear_and_cross_entropy or labels is None:
399
+ logits = self.lm_head(hidden_states if logits_to_keep is None else hidden_states[:, -logits_to_keep:])
400
+ if labels is not None:
401
+ if getattr(self, 'criterion', None) is None:
402
+ if fuse_linear_and_cross_entropy:
403
+ criterion = FusedLinearCrossEntropyLoss(use_l2warp=self.config.use_l2warp)
404
+ elif self.config.fuse_cross_entropy:
405
+ criterion = FusedCrossEntropyLoss(inplace_backward=True)
406
+ else:
407
+ criterion = nn.CrossEntropyLoss()
408
+ else:
409
+ criterion = self.criterion
410
+ # Enable model parallelism
411
+ labels = labels.to(hidden_states.device)
412
+ labels = torch.cat((labels[..., 1:], torch.full_like(labels[:, :1], criterion.ignore_index)), 1)
413
+ if fuse_linear_and_cross_entropy:
414
+ loss = criterion(hidden_states, labels, self.lm_head.weight, self.lm_head.bias)
415
+ else:
416
+ loss = criterion(logits.view(labels.numel(), -1), labels.view(-1))
417
+ loss = l2_warp(loss, logits) if self.config.use_l2warp else loss
418
+
419
+ if not return_dict:
420
+ output = (logits,) + outputs[1:]
421
+ return (loss,) + output if loss is not None else output
422
+
423
+ return CausalLMOutputWithPast(
424
+ loss=loss,
425
+ logits=logits,
426
+ past_key_values=outputs.past_key_values,
427
+ hidden_states=outputs.hidden_states,
428
+ attentions=outputs.attentions,
429
+ )