niallturbitt commited on
Commit
3984235
·
1 Parent(s): 6d8a7d1

LLM-foundry update January 08, 2024 10:30:15

Browse files
Files changed (6) hide show
  1. attention.py +122 -37
  2. blocks.py +21 -7
  3. configuration_mpt.py +56 -16
  4. ffn.py +72 -14
  5. hf_prefixlm_converter.py +2 -242
  6. modeling_mpt.py +206 -51
attention.py CHANGED
@@ -1,15 +1,41 @@
1
  """Attention layers."""
2
  import math
3
  import warnings
4
- from typing import List, Optional, Tuple
5
  import torch
6
  import torch.nn as nn
 
7
  from einops import rearrange
8
  from packaging import version
9
  from torch import nn
10
  from .fc import FC_CLASS_REGISTRY
11
  from .norm import NORM_CLASS_REGISTRY
12
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13
  def _reset_is_causal(num_query_tokens: int, num_key_tokens: int, original_is_causal: bool) -> bool:
14
  if original_is_causal and num_query_tokens != num_key_tokens:
15
  if num_query_tokens != 1:
@@ -18,7 +44,20 @@ def _reset_is_causal(num_query_tokens: int, num_key_tokens: int, original_is_cau
18
  return False
19
  return original_is_causal
20
 
21
- def scaled_multihead_dot_product_attention(query: torch.Tensor, key: torch.Tensor, value: torch.Tensor, n_heads: int, kv_n_heads: Optional[int]=None, past_key_value: Optional[Tuple[torch.Tensor, torch.Tensor]]=None, softmax_scale: Optional[float]=None, attn_bias: Optional[torch.Tensor]=None, key_padding_mask: Optional[torch.Tensor]=None, is_causal: bool=False, dropout_p: float=0.0, training: bool=False, needs_weights: bool=False, multiquery: bool=False) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor, torch.Tensor]]]:
 
 
 
 
 
 
 
 
 
 
 
 
 
22
  if multiquery:
23
  warnings.warn(DeprecationWarning('The direct use of the multiquery arg is deprecated. Setting kv_n_heads=1 automatically. Please set kv_n_heads=1 explicitly to remove this warning.'))
24
  kv_n_heads = 1
@@ -36,8 +75,8 @@ def scaled_multihead_dot_product_attention(query: torch.Tensor, key: torch.Tenso
36
  (b, _, s_q, d) = q.shape
37
  s_k = k.size(-1)
38
  if kv_n_heads > 1 and kv_n_heads < n_heads:
39
- k = k.repeat_interleave(n_heads // kv_n_heads, dim=1)
40
- v = v.repeat_interleave(n_heads // kv_n_heads, dim=1)
41
  if softmax_scale is None:
42
  softmax_scale = 1 / math.sqrt(d)
43
  attn_weight = q.matmul(k) * softmax_scale
@@ -70,7 +109,7 @@ def scaled_multihead_dot_product_attention(query: torch.Tensor, key: torch.Tenso
70
  return (out, attn_weight, past_key_value)
71
  return (out, None, past_key_value)
72
 
73
- def check_valid_inputs(*tensors: torch.Tensor, valid_dtypes: Optional[List[torch.dtype]]=None):
74
  if valid_dtypes is None:
75
  valid_dtypes = [torch.float16, torch.bfloat16]
76
  for tensor in tensors:
@@ -79,11 +118,11 @@ def check_valid_inputs(*tensors: torch.Tensor, valid_dtypes: Optional[List[torch
79
  if not tensor.is_cuda:
80
  raise TypeError(f'Inputs must be cuda tensors (tensor.is_cuda={tensor.is_cuda!r}).')
81
 
82
- def flash_attn_fn(query: torch.Tensor, key: torch.Tensor, value: torch.Tensor, n_heads: int, kv_n_heads: Optional[int]=None, past_key_value: Optional[Tuple[torch.Tensor, torch.Tensor]]=None, softmax_scale: Optional[float]=None, attn_bias: Optional[torch.Tensor]=None, key_padding_mask: Optional[torch.Tensor]=None, is_causal: bool=False, dropout_p: float=0.0, training: bool=False, needs_weights: bool=False, multiquery: bool=False) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor, torch.Tensor]]]:
83
  try:
84
  from flash_attn import bert_padding, flash_attn_interface
85
  except:
86
- raise RuntimeError('Please install flash-attn==1.0.3.post0')
87
  check_valid_inputs(query, key, value)
88
  if multiquery:
89
  warnings.warn(DeprecationWarning('The direct use of the multiquery arg is deprecated. Setting kv_n_heads=1 automatically. Please set kv_n_heads=1 explicitly to remove this warning.'))
@@ -96,35 +135,50 @@ def flash_attn_fn(query: torch.Tensor, key: torch.Tensor, value: torch.Tensor, n
96
  key = torch.cat([past_key_value[0], key], dim=1)
97
  value = torch.cat([past_key_value[1], value], dim=1)
98
  past_key_value = (key, value)
99
- if attn_bias is not None:
100
- _s_q = max(0, attn_bias.size(2) - query.size(1))
101
- _s_k = max(0, attn_bias.size(3) - key.size(1))
102
- attn_bias = attn_bias[:, :, _s_q:, _s_k:]
103
  if attn_bias is not None:
104
  raise NotImplementedError(f'attn_bias not implemented for flash attn.')
105
  (batch_size, seqlen) = query.shape[:2]
106
- if key_padding_mask is None:
107
- key_padding_mask = torch.ones_like(key[:, :, 0], dtype=torch.bool)
108
- query_padding_mask = key_padding_mask[:, -query.size(1):]
109
- (query_unpad, indices_q, cu_seqlens_q, max_seqlen_q) = bert_padding.unpad_input(query, query_padding_mask)
 
 
 
 
 
 
110
  query_unpad = rearrange(query_unpad, 'nnz (h d) -> nnz h d', h=n_heads)
111
- (key_unpad, _, cu_seqlens_k, max_seqlen_k) = bert_padding.unpad_input(key, key_padding_mask)
112
  key_unpad = rearrange(key_unpad, 'nnz (h d) -> nnz h d', h=kv_n_heads)
113
- (value_unpad, _, _, _) = bert_padding.unpad_input(value, key_padding_mask)
114
  value_unpad = rearrange(value_unpad, 'nnz (h d) -> nnz h d', h=kv_n_heads)
115
- if kv_n_heads == 1:
116
- key_unpad = key_unpad.expand(key_unpad.size(0), n_heads, key_unpad.size(-1))
117
- value_unpad = value_unpad.expand(value_unpad.size(0), n_heads, value_unpad.size(-1))
118
- elif kv_n_heads < n_heads:
119
- key_unpad = key_unpad.repeat_interleave(n_heads // kv_n_heads, dim=1)
120
- value_unpad = value_unpad.repeat_interleave(n_heads // kv_n_heads, dim=1)
 
 
 
121
  dropout_p = dropout_p if training else 0.0
122
  reset_is_causal = _reset_is_causal(query.size(1), key.size(1), is_causal)
123
- output_unpad = flash_attn_interface.flash_attn_unpadded_func(query_unpad, key_unpad, value_unpad, cu_seqlens_q, cu_seqlens_k, max_seqlen_q, max_seqlen_k, dropout_p, softmax_scale=softmax_scale, causal=reset_is_causal, return_attn_probs=needs_weights)
 
 
 
 
 
 
 
 
 
 
124
  output = bert_padding.pad_input(rearrange(output_unpad, 'nnz h d -> nnz (h d)'), indices_q, batch_size, seqlen)
125
  return (output, None, past_key_value)
126
 
127
- def triton_flash_attn_fn(query: torch.Tensor, key: torch.Tensor, value: torch.Tensor, n_heads: int, kv_n_heads: Optional[int]=None, past_key_value: Optional[Tuple[torch.Tensor, torch.Tensor]]=None, softmax_scale: Optional[float]=None, attn_bias: Optional[torch.Tensor]=None, key_padding_mask: Optional[torch.Tensor]=None, is_causal: bool=False, dropout_p: float=0.0, training: bool=False, needs_weights: bool=False, multiquery: bool=False) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor, torch.Tensor]]]:
128
  try:
129
  from .flash_attn_triton import flash_attn_func
130
  except:
@@ -171,8 +225,8 @@ def triton_flash_attn_fn(query: torch.Tensor, key: torch.Tensor, value: torch.Te
171
  key = key.repeat(1, 1, n_heads, 1)
172
  value = value.repeat(1, 1, n_heads, 1)
173
  elif kv_n_heads < n_heads:
174
- key = key.repeat_interleave(n_heads // kv_n_heads, dim=2)
175
- value = value.repeat_interleave(n_heads // kv_n_heads, dim=2)
176
  reset_is_causal = _reset_is_causal(query.size(1), key.size(1), is_causal)
177
  attn_output = flash_attn_func(query, key, value, attn_bias, reset_is_causal, softmax_scale)
178
  output = attn_output.view(*attn_output.shape[:2], -1)
@@ -188,7 +242,7 @@ class GroupedQueryAttention(nn.Module):
188
  implementation enables user to also use additive bias.
189
  """
190
 
191
- def __init__(self, d_model: int, n_heads: int, kv_n_heads: int, attn_impl: str='triton', clip_qkv: Optional[float]=None, qk_ln: bool=False, softmax_scale: Optional[float]=None, attn_pdrop: float=0.0, norm_type: str='low_precision_layernorm', fc_type: str='torch', device: Optional[str]=None):
192
  super().__init__()
193
  self.attn_impl = attn_impl
194
  self.clip_qkv = clip_qkv
@@ -196,6 +250,7 @@ class GroupedQueryAttention(nn.Module):
196
  self.d_model = d_model
197
  self.n_heads = n_heads
198
  self.kv_n_heads = kv_n_heads
 
199
  self.head_dim = d_model // n_heads
200
  if self.kv_n_heads <= 0:
201
  raise ValueError('kv_n_heads should be greater than zero.')
@@ -207,7 +262,7 @@ class GroupedQueryAttention(nn.Module):
207
  if self.softmax_scale is None:
208
  self.softmax_scale = 1 / math.sqrt(self.d_model / self.n_heads)
209
  self.attn_dropout_p = attn_pdrop
210
- fc_kwargs = {}
211
  if fc_type != 'te':
212
  fc_kwargs['device'] = device
213
  self.Wqkv = FC_CLASS_REGISTRY[fc_type](self.d_model, self.d_model + 2 * self.kv_n_heads * self.head_dim, **fc_kwargs)
@@ -228,7 +283,7 @@ class GroupedQueryAttention(nn.Module):
228
  self.out_proj = FC_CLASS_REGISTRY[fc_type](self.d_model, self.d_model, **fc_kwargs)
229
  self.out_proj._is_residual = True
230
 
231
- def forward(self, x: torch.Tensor, past_key_value: Optional[Tuple[torch.Tensor, torch.Tensor]]=None, attn_bias: Optional[torch.Tensor]=None, attention_mask: Optional[torch.Tensor]=None, is_causal: bool=True, needs_weights: bool=False) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor, torch.Tensor]]]:
232
  qkv = self.Wqkv(x)
233
  if self.clip_qkv:
234
  qkv = qkv.clamp(min=-self.clip_qkv, max=self.clip_qkv)
@@ -238,7 +293,35 @@ class GroupedQueryAttention(nn.Module):
238
  dtype = query.dtype
239
  query = self.q_ln(query).to(dtype)
240
  key = self.k_ln(key).to(dtype)
241
- (context, attn_weights, past_key_value) = self.attn_fn(query, key, value, self.n_heads, self.kv_n_heads, past_key_value=past_key_value, softmax_scale=self.softmax_scale, attn_bias=attn_bias, key_padding_mask=key_padding_mask, is_causal=is_causal, dropout_p=self.attn_dropout_p, training=self.training, needs_weights=needs_weights)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
242
  return (self.out_proj(context), attn_weights, past_key_value)
243
 
244
  class MultiheadAttention(GroupedQueryAttention):
@@ -248,8 +331,8 @@ class MultiheadAttention(GroupedQueryAttention):
248
  additive bias.
249
  """
250
 
251
- def __init__(self, d_model: int, n_heads: int, attn_impl: str='triton', clip_qkv: Optional[float]=None, qk_ln: bool=False, softmax_scale: Optional[float]=None, attn_pdrop: float=0.0, norm_type: str='low_precision_layernorm', fc_type: str='torch', device: Optional[str]=None):
252
- super().__init__(d_model=d_model, n_heads=n_heads, kv_n_heads=n_heads, attn_impl=attn_impl, clip_qkv=clip_qkv, qk_ln=qk_ln, softmax_scale=softmax_scale, attn_pdrop=attn_pdrop, norm_type=norm_type, fc_type=fc_type, device=device)
253
 
254
  class MultiQueryAttention(GroupedQueryAttention):
255
  """Multi-Query self attention.
@@ -258,10 +341,10 @@ class MultiQueryAttention(GroupedQueryAttention):
258
  additive bias.
259
  """
260
 
261
- def __init__(self, d_model: int, n_heads: int, attn_impl: str='triton', clip_qkv: Optional[float]=None, qk_ln: bool=False, softmax_scale: Optional[float]=None, attn_pdrop: float=0.0, norm_type: str='low_precision_layernorm', fc_type: str='torch', device: Optional[str]=None):
262
- super().__init__(d_model=d_model, n_heads=n_heads, kv_n_heads=1, attn_impl=attn_impl, clip_qkv=clip_qkv, qk_ln=qk_ln, softmax_scale=softmax_scale, attn_pdrop=attn_pdrop, norm_type=norm_type, fc_type=fc_type, device=device)
263
 
264
- def attn_bias_shape(attn_impl: str, n_heads: int, seq_len: int, alibi: bool, prefix_lm: bool, causal: bool, use_sequence_id: bool) -> Optional[Tuple[int, int, int, int]]:
265
  if attn_impl == 'flash':
266
  return None
267
  elif attn_impl in ['torch', 'triton']:
@@ -286,13 +369,15 @@ def build_attn_bias(attn_impl: str, attn_bias: torch.Tensor, n_heads: int, seq_l
286
  else:
287
  raise ValueError(f'attn_impl={attn_impl!r} is an invalid setting.')
288
 
289
- def gen_slopes(n_heads: int, alibi_bias_max: int=8, device: Optional[torch.device]=None) -> torch.Tensor:
290
  _n_heads = 2 ** math.ceil(math.log2(n_heads))
291
  m = torch.arange(1, _n_heads + 1, dtype=torch.float32, device=device)
292
  m = m.mul(alibi_bias_max / _n_heads)
293
  slopes = 1.0 / torch.pow(2, m)
294
  if _n_heads != n_heads:
295
  slopes = torch.concat([slopes[1::2], slopes[::2]])[:n_heads]
 
 
296
  return slopes.view(1, n_heads, 1, 1)
297
 
298
  def build_alibi_bias(n_heads: int, seq_len: int, full: bool=False, alibi_bias_max: int=8, device: Optional[torch.device]=None, dtype: Optional[torch.dtype]=None) -> torch.Tensor:
 
1
  """Attention layers."""
2
  import math
3
  import warnings
4
+ from typing import Any, Optional
5
  import torch
6
  import torch.nn as nn
7
+ import transformers
8
  from einops import rearrange
9
  from packaging import version
10
  from torch import nn
11
  from .fc import FC_CLASS_REGISTRY
12
  from .norm import NORM_CLASS_REGISTRY
13
 
14
+ def is_flash_v2_installed(v2_version: str='2.0.0'):
15
+ assert version.parse(v2_version) >= version.parse('2.0.0')
16
+ try:
17
+ import flash_attn as flash_attn
18
+ except:
19
+ return False
20
+ return version.parse(flash_attn.__version__) >= version.parse(v2_version)
21
+
22
+ def is_flash_v1_installed():
23
+ try:
24
+ import flash_attn as flash_attn
25
+ except:
26
+ return False
27
+ return version.parse(flash_attn.__version__) < version.parse('2.0.0')
28
+
29
+ def is_transformers_version_gte(hf_version: str) -> bool:
30
+ return version.parse(transformers.__version__) >= version.parse(hf_version)
31
+
32
+ def check_alibi_support(attention_impl: str) -> bool:
33
+ return attention_impl != 'flash' or is_flash_v2_installed(v2_version='v2.4.2')
34
+ if is_flash_v1_installed():
35
+ import transformers
36
+ transformers.utils.is_flash_attn_available = lambda : False
37
+ from transformers.models.llama.modeling_llama import apply_rotary_pos_emb
38
+
39
  def _reset_is_causal(num_query_tokens: int, num_key_tokens: int, original_is_causal: bool) -> bool:
40
  if original_is_causal and num_query_tokens != num_key_tokens:
41
  if num_query_tokens != 1:
 
44
  return False
45
  return original_is_causal
46
 
47
+ def repeat_kv_for_gqa(hidden: torch.Tensor, n_rep: int) -> torch.Tensor:
48
+ """Perform repeat of kv heads along a particular dimension.
49
+
50
+ hidden.shape expected to be: (batch size, seq len, kv_n_heads, head_dim)
51
+ n_rep: amount of repetitions of kv_n_heads
52
+ Unlike torch.repeat_interleave, this function avoids allocating new memory.
53
+ """
54
+ if n_rep == 1:
55
+ return hidden
56
+ (b, s, kv_n_heads, d) = hidden.shape
57
+ hidden = hidden[:, :, :, None, :].expand(b, s, kv_n_heads, n_rep, d)
58
+ return hidden.reshape(b, s, kv_n_heads * n_rep, d)
59
+
60
+ def scaled_multihead_dot_product_attention(query: torch.Tensor, key: torch.Tensor, value: torch.Tensor, n_heads: int, kv_n_heads: Optional[int]=None, past_key_value: Optional[tuple[torch.Tensor, torch.Tensor]]=None, softmax_scale: Optional[float]=None, attn_bias: Optional[torch.Tensor]=None, key_padding_mask: Optional[torch.Tensor]=None, is_causal: bool=False, dropout_p: float=0.0, training: bool=False, needs_weights: bool=False, multiquery: bool=False) -> tuple[torch.Tensor, Optional[torch.Tensor], Optional[tuple[torch.Tensor, torch.Tensor]]]:
61
  if multiquery:
62
  warnings.warn(DeprecationWarning('The direct use of the multiquery arg is deprecated. Setting kv_n_heads=1 automatically. Please set kv_n_heads=1 explicitly to remove this warning.'))
63
  kv_n_heads = 1
 
75
  (b, _, s_q, d) = q.shape
76
  s_k = k.size(-1)
77
  if kv_n_heads > 1 and kv_n_heads < n_heads:
78
+ k = repeat_kv_for_gqa(k.transpose(1, 2), n_heads // kv_n_heads).transpose(1, 2)
79
+ v = repeat_kv_for_gqa(v.transpose(1, 2), n_heads // kv_n_heads).transpose(1, 2)
80
  if softmax_scale is None:
81
  softmax_scale = 1 / math.sqrt(d)
82
  attn_weight = q.matmul(k) * softmax_scale
 
109
  return (out, attn_weight, past_key_value)
110
  return (out, None, past_key_value)
111
 
112
+ def check_valid_inputs(*tensors: torch.Tensor, valid_dtypes: Optional[list[torch.dtype]]=None):
113
  if valid_dtypes is None:
114
  valid_dtypes = [torch.float16, torch.bfloat16]
115
  for tensor in tensors:
 
118
  if not tensor.is_cuda:
119
  raise TypeError(f'Inputs must be cuda tensors (tensor.is_cuda={tensor.is_cuda!r}).')
120
 
121
+ def flash_attn_fn(query: torch.Tensor, key: torch.Tensor, value: torch.Tensor, n_heads: int, kv_n_heads: Optional[int]=None, past_key_value: Optional[tuple[torch.Tensor, torch.Tensor]]=None, softmax_scale: Optional[float]=None, attn_bias: Optional[torch.Tensor]=None, key_padding_mask: Optional[torch.Tensor]=None, is_causal: bool=False, dropout_p: float=0.0, training: bool=False, needs_weights: bool=False, multiquery: bool=False, attention_mask_in_length: Optional[torch.Tensor]=None, should_repeat_kv_for_gqa: Optional[bool]=True, sliding_window_size: int=-1, alibi_slopes: Optional[torch.Tensor]=None) -> tuple[torch.Tensor, Optional[torch.Tensor], Optional[tuple[torch.Tensor, torch.Tensor]]]:
122
  try:
123
  from flash_attn import bert_padding, flash_attn_interface
124
  except:
125
+ raise RuntimeError('Please install flash-attn==1.0.9 or flash-attn==2.3.6')
126
  check_valid_inputs(query, key, value)
127
  if multiquery:
128
  warnings.warn(DeprecationWarning('The direct use of the multiquery arg is deprecated. Setting kv_n_heads=1 automatically. Please set kv_n_heads=1 explicitly to remove this warning.'))
 
135
  key = torch.cat([past_key_value[0], key], dim=1)
136
  value = torch.cat([past_key_value[1], value], dim=1)
137
  past_key_value = (key, value)
 
 
 
 
138
  if attn_bias is not None:
139
  raise NotImplementedError(f'attn_bias not implemented for flash attn.')
140
  (batch_size, seqlen) = query.shape[:2]
141
+ if attention_mask_in_length is None:
142
+ if key_padding_mask is None:
143
+ key_padding_mask = torch.ones_like(key[:, :, 0], dtype=torch.bool)
144
+ query_padding_mask = key_padding_mask[:, -query.size(1):]
145
+ unpadding_function = bert_padding.unpad_input
146
+ else:
147
+ key_padding_mask = attention_mask_in_length
148
+ query_padding_mask = attention_mask_in_length
149
+ unpadding_function = bert_padding.unpad_input_for_concatenated_sequences
150
+ (query_unpad, indices_q, cu_seqlens_q, max_seqlen_q) = unpadding_function(query, query_padding_mask)
151
  query_unpad = rearrange(query_unpad, 'nnz (h d) -> nnz h d', h=n_heads)
152
+ (key_unpad, _, cu_seqlens_k, max_seqlen_k) = unpadding_function(key, key_padding_mask)
153
  key_unpad = rearrange(key_unpad, 'nnz (h d) -> nnz h d', h=kv_n_heads)
154
+ (value_unpad, _, _, _) = unpadding_function(value, key_padding_mask)
155
  value_unpad = rearrange(value_unpad, 'nnz (h d) -> nnz h d', h=kv_n_heads)
156
+ if kv_n_heads < n_heads and (not is_flash_v2_installed()) and (not should_repeat_kv_for_gqa):
157
+ raise ValueError('For Grouped Query Attention or Multi Query Attention, should_repeat_kv_for_gqa should be set to True if not using Flash Attention v2.')
158
+ if should_repeat_kv_for_gqa:
159
+ if kv_n_heads == 1:
160
+ key_unpad = key_unpad.expand(key_unpad.size(0), n_heads, key_unpad.size(-1))
161
+ value_unpad = value_unpad.expand(value_unpad.size(0), n_heads, value_unpad.size(-1))
162
+ elif kv_n_heads < n_heads:
163
+ key_unpad = repeat_kv_for_gqa(key_unpad.view(1, key_unpad.size(0), kv_n_heads, -1), n_heads // kv_n_heads).view(key_unpad.size(0), n_heads, -1)
164
+ value_unpad = repeat_kv_for_gqa(value_unpad.view(1, value_unpad.size(0), kv_n_heads, -1), n_heads // kv_n_heads).view(value_unpad.size(0), n_heads, -1)
165
  dropout_p = dropout_p if training else 0.0
166
  reset_is_causal = _reset_is_causal(query.size(1), key.size(1), is_causal)
167
+ if is_flash_v1_installed():
168
+ output_unpad = flash_attn_interface.flash_attn_unpadded_func(q=query_unpad, k=key_unpad, v=value_unpad, cu_seqlens_q=cu_seqlens_q, cu_seqlens_k=cu_seqlens_k, max_seqlen_q=max_seqlen_q, max_seqlen_k=max_seqlen_k, dropout_p=dropout_p, softmax_scale=softmax_scale, causal=reset_is_causal, return_attn_probs=needs_weights)
169
+ elif is_flash_v2_installed():
170
+ alibi_kwargs = {}
171
+ if check_alibi_support('flash'):
172
+ alibi_kwargs = {'alibi_slopes': alibi_slopes}
173
+ elif alibi_slopes is not None:
174
+ raise ValueError('alibi_slopes is only supported for flash-attn>=2.4.2')
175
+ output_unpad = flash_attn_interface.flash_attn_varlen_func(q=query_unpad, k=key_unpad, v=value_unpad, cu_seqlens_q=cu_seqlens_q, cu_seqlens_k=cu_seqlens_k, max_seqlen_q=max_seqlen_q, max_seqlen_k=max_seqlen_k, dropout_p=dropout_p, softmax_scale=softmax_scale, causal=reset_is_causal, return_attn_probs=needs_weights, window_size=(sliding_window_size, sliding_window_size), **alibi_kwargs)
176
+ else:
177
+ raise RuntimeError('flash-attn==1.0.9 or flash-attn==2.4.2 is required.')
178
  output = bert_padding.pad_input(rearrange(output_unpad, 'nnz h d -> nnz (h d)'), indices_q, batch_size, seqlen)
179
  return (output, None, past_key_value)
180
 
181
+ def triton_flash_attn_fn(query: torch.Tensor, key: torch.Tensor, value: torch.Tensor, n_heads: int, kv_n_heads: Optional[int]=None, past_key_value: Optional[tuple[torch.Tensor, torch.Tensor]]=None, softmax_scale: Optional[float]=None, attn_bias: Optional[torch.Tensor]=None, key_padding_mask: Optional[torch.Tensor]=None, is_causal: bool=False, dropout_p: float=0.0, training: bool=False, needs_weights: bool=False, multiquery: bool=False) -> tuple[torch.Tensor, Optional[torch.Tensor], Optional[tuple[torch.Tensor, torch.Tensor]]]:
182
  try:
183
  from .flash_attn_triton import flash_attn_func
184
  except:
 
225
  key = key.repeat(1, 1, n_heads, 1)
226
  value = value.repeat(1, 1, n_heads, 1)
227
  elif kv_n_heads < n_heads:
228
+ key = repeat_kv_for_gqa(key, n_heads // kv_n_heads)
229
+ value = repeat_kv_for_gqa(value, n_heads // kv_n_heads)
230
  reset_is_causal = _reset_is_causal(query.size(1), key.size(1), is_causal)
231
  attn_output = flash_attn_func(query, key, value, attn_bias, reset_is_causal, softmax_scale)
232
  output = attn_output.view(*attn_output.shape[:2], -1)
 
242
  implementation enables user to also use additive bias.
243
  """
244
 
245
+ def __init__(self, d_model: int, n_heads: int, kv_n_heads: int, attn_impl: str='triton', clip_qkv: Optional[float]=None, qk_ln: bool=False, softmax_scale: Optional[float]=None, attn_pdrop: float=0.0, norm_type: str='low_precision_layernorm', fc_type: str='torch', device: Optional[str]=None, bias: bool=True, sliding_window_size: int=-1):
246
  super().__init__()
247
  self.attn_impl = attn_impl
248
  self.clip_qkv = clip_qkv
 
250
  self.d_model = d_model
251
  self.n_heads = n_heads
252
  self.kv_n_heads = kv_n_heads
253
+ self.sliding_window_size = sliding_window_size
254
  self.head_dim = d_model // n_heads
255
  if self.kv_n_heads <= 0:
256
  raise ValueError('kv_n_heads should be greater than zero.')
 
262
  if self.softmax_scale is None:
263
  self.softmax_scale = 1 / math.sqrt(self.d_model / self.n_heads)
264
  self.attn_dropout_p = attn_pdrop
265
+ fc_kwargs: dict[str, Any] = {'bias': bias}
266
  if fc_type != 'te':
267
  fc_kwargs['device'] = device
268
  self.Wqkv = FC_CLASS_REGISTRY[fc_type](self.d_model, self.d_model + 2 * self.kv_n_heads * self.head_dim, **fc_kwargs)
 
283
  self.out_proj = FC_CLASS_REGISTRY[fc_type](self.d_model, self.d_model, **fc_kwargs)
284
  self.out_proj._is_residual = True
285
 
286
+ def forward(self, x: torch.Tensor, past_key_value: Optional[tuple[torch.Tensor, torch.Tensor]]=None, attn_bias: Optional[torch.Tensor]=None, attention_mask: Optional[torch.Tensor]=None, rotary_emb_w_meta_info: Optional[dict]=None, is_causal: bool=True, needs_weights: bool=False, attention_mask_in_length: Optional[torch.Tensor]=None, alibi_slopes: Optional[torch.Tensor]=None) -> tuple[torch.Tensor, Optional[torch.Tensor], Optional[tuple[torch.Tensor, torch.Tensor]]]:
287
  qkv = self.Wqkv(x)
288
  if self.clip_qkv:
289
  qkv = qkv.clamp(min=-self.clip_qkv, max=self.clip_qkv)
 
293
  dtype = query.dtype
294
  query = self.q_ln(query).to(dtype)
295
  key = self.k_ln(key).to(dtype)
296
+ if rotary_emb_w_meta_info is not None:
297
+ rotary_emb = rotary_emb_w_meta_info['rotary_emb']
298
+ seq_len = rotary_emb_w_meta_info['seq_len']
299
+ offset_info = rotary_emb_w_meta_info['offset_info']
300
+ (bsz, seqlen) = query.shape[:2]
301
+ query = query.view(bsz, seqlen, -1, self.head_dim)
302
+ key = key.view(bsz, seqlen, -1, self.head_dim)
303
+ if rotary_emb_w_meta_info['impl'] == 'dail':
304
+ value = value.view(bsz, seqlen, -1, self.head_dim)
305
+ kv = torch.stack([key, value], dim=2)
306
+ (query, kv) = rotary_emb(query, kv, seqlen_offset=offset_info, max_seqlen=seq_len)
307
+ [key, value] = torch.unbind(kv, dim=2)
308
+ value = value.view(bsz, seqlen, self.kv_n_heads * self.head_dim)
309
+ elif rotary_emb_w_meta_info['impl'] == 'hf':
310
+ (cos, sin) = rotary_emb(value, seq_len)
311
+ if is_transformers_version_gte('4.36'):
312
+ (query, key) = apply_rotary_pos_emb(query, key, cos, sin, offset_info, unsqueeze_dim=2)
313
+ else:
314
+ query = query.transpose(1, 2)
315
+ key = key.transpose(1, 2)
316
+ (query, key) = apply_rotary_pos_emb(query, key, cos, sin, offset_info)
317
+ query = query.transpose(1, 2)
318
+ key = key.transpose(1, 2)
319
+ query = query.view(bsz, seqlen, self.d_model)
320
+ key = key.view(bsz, seqlen, self.kv_n_heads * self.head_dim)
321
+ extra_attn_kwargs = {}
322
+ if self.attn_impl == 'flash':
323
+ extra_attn_kwargs = {'attention_mask_in_length': attention_mask_in_length, 'should_repeat_kv_for_gqa': not is_flash_v2_installed(), 'sliding_window_size': self.sliding_window_size, 'alibi_slopes': alibi_slopes}
324
+ (context, attn_weights, past_key_value) = self.attn_fn(query, key, value, self.n_heads, self.kv_n_heads, past_key_value=past_key_value, softmax_scale=self.softmax_scale, attn_bias=attn_bias, key_padding_mask=key_padding_mask, is_causal=is_causal, dropout_p=self.attn_dropout_p, training=self.training, needs_weights=needs_weights, **extra_attn_kwargs)
325
  return (self.out_proj(context), attn_weights, past_key_value)
326
 
327
  class MultiheadAttention(GroupedQueryAttention):
 
331
  additive bias.
332
  """
333
 
334
+ def __init__(self, d_model: int, n_heads: int, attn_impl: str='triton', clip_qkv: Optional[float]=None, qk_ln: bool=False, softmax_scale: Optional[float]=None, attn_pdrop: float=0.0, norm_type: str='low_precision_layernorm', fc_type: str='torch', device: Optional[str]=None, bias: bool=True, sliding_window_size: int=-1):
335
+ super().__init__(d_model=d_model, n_heads=n_heads, kv_n_heads=n_heads, attn_impl=attn_impl, clip_qkv=clip_qkv, qk_ln=qk_ln, softmax_scale=softmax_scale, attn_pdrop=attn_pdrop, norm_type=norm_type, fc_type=fc_type, device=device, bias=bias, sliding_window_size=sliding_window_size)
336
 
337
  class MultiQueryAttention(GroupedQueryAttention):
338
  """Multi-Query self attention.
 
341
  additive bias.
342
  """
343
 
344
+ def __init__(self, d_model: int, n_heads: int, attn_impl: str='triton', clip_qkv: Optional[float]=None, qk_ln: bool=False, softmax_scale: Optional[float]=None, attn_pdrop: float=0.0, norm_type: str='low_precision_layernorm', fc_type: str='torch', device: Optional[str]=None, bias: bool=True, sliding_window_size: int=-1):
345
+ super().__init__(d_model=d_model, n_heads=n_heads, kv_n_heads=1, attn_impl=attn_impl, clip_qkv=clip_qkv, qk_ln=qk_ln, softmax_scale=softmax_scale, attn_pdrop=attn_pdrop, norm_type=norm_type, fc_type=fc_type, device=device, bias=bias, sliding_window_size=sliding_window_size)
346
 
347
+ def attn_bias_shape(attn_impl: str, n_heads: int, seq_len: int, alibi: bool, prefix_lm: bool, causal: bool, use_sequence_id: bool) -> Optional[tuple[int, int, int, int]]:
348
  if attn_impl == 'flash':
349
  return None
350
  elif attn_impl in ['torch', 'triton']:
 
369
  else:
370
  raise ValueError(f'attn_impl={attn_impl!r} is an invalid setting.')
371
 
372
+ def gen_slopes(n_heads: int, alibi_bias_max: int=8, device: Optional[torch.device]=None, return_1d: bool=False) -> torch.Tensor:
373
  _n_heads = 2 ** math.ceil(math.log2(n_heads))
374
  m = torch.arange(1, _n_heads + 1, dtype=torch.float32, device=device)
375
  m = m.mul(alibi_bias_max / _n_heads)
376
  slopes = 1.0 / torch.pow(2, m)
377
  if _n_heads != n_heads:
378
  slopes = torch.concat([slopes[1::2], slopes[::2]])[:n_heads]
379
+ if return_1d:
380
+ return slopes
381
  return slopes.view(1, n_heads, 1, 1)
382
 
383
  def build_alibi_bias(n_heads: int, seq_len: int, full: bool=False, alibi_bias_max: int=8, device: Optional[torch.device]=None, dtype: Optional[torch.dtype]=None) -> torch.Tensor:
blocks.py CHANGED
@@ -5,12 +5,17 @@ import torch.nn as nn
5
  from .attention import ATTN_CLASS_REGISTRY
6
  from .ffn import FFN_CLASS_REGISTRY, build_ffn
7
  from .norm import NORM_CLASS_REGISTRY
 
 
 
 
 
8
 
9
  class MPTBlock(nn.Module):
10
 
11
- def __init__(self, d_model: int, n_heads: int, expansion_ratio: int, attn_config: Optional[Dict]=None, ffn_config: Optional[Dict]=None, resid_pdrop: float=0.0, norm_type: str='low_precision_layernorm', fc_type: str='torch', device: Optional[str]=None, **kwargs: Any):
12
  if attn_config is None:
13
- attn_config = {'attn_type': 'multihead_attention', 'attn_pdrop': 0.0, 'attn_impl': 'triton', 'qk_ln': False, 'clip_qkv': None, 'softmax_scale': None, 'prefix_lm': False, 'attn_uses_sequence_id': False, 'alibi': False, 'alibi_bias_max': 8}
14
  if ffn_config is None:
15
  ffn_config = {'ffn_type': 'mptmlp'}
16
  del kwargs
@@ -18,24 +23,33 @@ class MPTBlock(nn.Module):
18
  norm_class = NORM_CLASS_REGISTRY[norm_type.lower()]
19
  assert isinstance(attn_config['attn_type'], str)
20
  attn_class = ATTN_CLASS_REGISTRY[attn_config['attn_type']]
21
- args_to_exclude_in_attn_class = {'attn_type', 'prefix_lm', 'alibi', 'attn_uses_sequence_id', 'alibi_bias_max'}
22
  attn_config_subset_for_attn_class = {k: v for (k, v) in attn_config.items() if k not in args_to_exclude_in_attn_class}
23
  self.norm_1 = norm_class(d_model, device=device)
24
- self.attn = attn_class(d_model=d_model, n_heads=n_heads, fc_type=fc_type, device=device, **attn_config_subset_for_attn_class)
25
  self.norm_2 = None
26
  if not getattr(FFN_CLASS_REGISTRY[ffn_config['ffn_type']], '_has_norm', False):
27
  self.norm_2 = norm_class(d_model, device=device)
28
- self.ffn = build_ffn(d_model=d_model, expansion_ratio=expansion_ratio, device=device, **ffn_config)
29
  self.resid_attn_dropout = nn.Dropout(resid_pdrop)
30
  self.resid_ffn_dropout = nn.Dropout(resid_pdrop)
 
31
 
32
- def forward(self, x: torch.Tensor, past_key_value: Optional[Tuple[torch.Tensor, torch.Tensor]]=None, attn_bias: Optional[torch.Tensor]=None, attention_mask: Optional[torch.ByteTensor]=None, is_causal: bool=True) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor, torch.Tensor]]]:
33
  a = self.norm_1(x)
34
- (b, attn_weights, past_key_value) = self.attn(a, past_key_value=past_key_value, attn_bias=attn_bias, attention_mask=attention_mask, is_causal=is_causal)
35
  x = x + self.resid_attn_dropout(b)
36
  m = x
37
  if self.norm_2 is not None:
38
  m = self.norm_2(x)
 
 
 
 
 
39
  n = self.ffn(m)
 
 
 
40
  x = x + self.resid_ffn_dropout(n)
41
  return (x, attn_weights, past_key_value)
 
5
  from .attention import ATTN_CLASS_REGISTRY
6
  from .ffn import FFN_CLASS_REGISTRY, build_ffn
7
  from .norm import NORM_CLASS_REGISTRY
8
+ try:
9
+ from flash_attn.bert_padding import unpad_input, pad_input
10
+ except:
11
+ (unpad_input, pad_input) = (None, None)
12
+ attn_config_defaults: Dict = {'attn_type': 'multihead_attention', 'attn_pdrop': 0.0, 'attn_impl': 'triton', 'qk_ln': False, 'clip_qkv': None, 'softmax_scale': None, 'prefix_lm': False, 'attn_uses_sequence_id': False, 'sliding_window_size': -1, 'alibi': False, 'alibi_bias_max': 8, 'rope': False, 'rope_theta': 10000, 'rope_impl': 'dail', 'rope_dail_config': {'type': 'original', 'pos_idx_in_fp32': True, 'xpos_scale_base': 512}, 'rope_hf_config': {'type': 'no_scaling', 'factor': 1.0}}
13
 
14
  class MPTBlock(nn.Module):
15
 
16
+ def __init__(self, d_model: int, n_heads: int, expansion_ratio: int, attn_config: Optional[Dict]=None, ffn_config: Optional[Dict]=None, resid_pdrop: float=0.0, norm_type: str='low_precision_layernorm', fc_type: str='torch', device: Optional[str]=None, no_bias: bool=False, use_pad_tok_in_ffn: bool=True, **kwargs: Any):
17
  if attn_config is None:
18
+ attn_config = attn_config_defaults
19
  if ffn_config is None:
20
  ffn_config = {'ffn_type': 'mptmlp'}
21
  del kwargs
 
23
  norm_class = NORM_CLASS_REGISTRY[norm_type.lower()]
24
  assert isinstance(attn_config['attn_type'], str)
25
  attn_class = ATTN_CLASS_REGISTRY[attn_config['attn_type']]
26
+ args_to_exclude_in_attn_class = {'attn_type', 'prefix_lm', 'alibi', 'attn_uses_sequence_id', 'alibi_bias_max', 'rope', 'rope_theta', 'rope_impl', 'rope_dail_config', 'rope_hf_config'}
27
  attn_config_subset_for_attn_class = {k: v for (k, v) in attn_config.items() if k not in args_to_exclude_in_attn_class}
28
  self.norm_1 = norm_class(d_model, device=device)
29
+ self.attn = attn_class(d_model=d_model, n_heads=n_heads, fc_type=fc_type, device=device, **attn_config_subset_for_attn_class, bias=not no_bias)
30
  self.norm_2 = None
31
  if not getattr(FFN_CLASS_REGISTRY[ffn_config['ffn_type']], '_has_norm', False):
32
  self.norm_2 = norm_class(d_model, device=device)
33
+ self.ffn = build_ffn(d_model=d_model, expansion_ratio=expansion_ratio, device=device, bias=not no_bias, **ffn_config)
34
  self.resid_attn_dropout = nn.Dropout(resid_pdrop)
35
  self.resid_ffn_dropout = nn.Dropout(resid_pdrop)
36
+ self.use_pad_tok_in_ffn = use_pad_tok_in_ffn
37
 
38
+ def forward(self, x: torch.Tensor, past_key_value: Optional[Tuple[torch.Tensor, torch.Tensor]]=None, attn_bias: Optional[torch.Tensor]=None, rotary_emb_w_meta_info: Optional[Dict]=None, attention_mask: Optional[torch.ByteTensor]=None, is_causal: bool=True, output_attentions: bool=False, attention_mask_in_length: Optional[torch.Tensor]=None, alibi_slopes: Optional[torch.Tensor]=None) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor, torch.Tensor]]]:
39
  a = self.norm_1(x)
40
+ (b, attn_weights, past_key_value) = self.attn(a, past_key_value=past_key_value, attn_bias=attn_bias, rotary_emb_w_meta_info=rotary_emb_w_meta_info, attention_mask=attention_mask, is_causal=is_causal, needs_weights=output_attentions, attention_mask_in_length=attention_mask_in_length, alibi_slopes=alibi_slopes)
41
  x = x + self.resid_attn_dropout(b)
42
  m = x
43
  if self.norm_2 is not None:
44
  m = self.norm_2(x)
45
+ (batch_size, seq_len) = m.size()[:2]
46
+ indices = None
47
+ if not self.use_pad_tok_in_ffn:
48
+ assert unpad_input is not None
49
+ (m, indices, _, _) = unpad_input(m, attention_mask)
50
  n = self.ffn(m)
51
+ if not self.use_pad_tok_in_ffn:
52
+ assert pad_input is not None
53
+ n = pad_input(n, indices, batch_size, seq_len)
54
  x = x + self.resid_ffn_dropout(n)
55
  return (x, attn_weights, past_key_value)
configuration_mpt.py CHANGED
@@ -2,21 +2,25 @@
2
  import warnings
3
  from typing import Any, Dict, Optional, Union
4
  from transformers import PretrainedConfig
5
- attn_config_defaults: Dict = {'attn_type': 'multihead_attention', 'attn_pdrop': 0.0, 'attn_impl': 'triton', 'qk_ln': False, 'clip_qkv': None, 'softmax_scale': None, 'prefix_lm': False, 'attn_uses_sequence_id': False, 'alibi': False, 'alibi_bias_max': 8}
 
 
 
 
6
  ffn_config_defaults: Dict = {'ffn_type': 'mptmlp'}
7
  init_config_defaults: Dict = {'name': 'kaiming_normal_', 'fan_mode': 'fan_in', 'init_nonlinearity': 'relu', 'init_div_is_residual': True, 'emb_init_std': None, 'emb_init_uniform_lim': None, 'init_std': None, 'init_gain': 0.0}
8
 
9
  class MPTConfig(PretrainedConfig):
10
  model_type = 'mpt'
11
 
12
- def __init__(self, d_model: int=2048, n_heads: int=16, n_layers: int=24, expansion_ratio: int=4, max_seq_len: int=2048, vocab_size: int=50368, resid_pdrop: float=0.0, emb_pdrop: float=0.0, learned_pos_emb: bool=True, attn_config: Dict=attn_config_defaults, ffn_config: Dict=ffn_config_defaults, init_device: str='cpu', logit_scale: Optional[Union[float, str]]=None, no_bias: bool=False, embedding_fraction: float=1.0, norm_type: str='low_precision_layernorm', use_cache: bool=False, init_config: Dict=init_config_defaults, fc_type: str='torch', verbose: Optional[int]=None, **kwargs: Any):
13
  """The MPT configuration class.
14
 
15
  Args:
16
  d_model (int): The size of the embedding dimension of the model.
17
  n_heads (int): The number of attention heads.
18
  n_layers (int): The number of layers in the model.
19
- expansion_ratio (int): The ratio of the up/down scale in the ffn.
20
  max_seq_len (int): The maximum sequence length of the model.
21
  vocab_size (int): The size of the vocabulary.
22
  resid_pdrop (float): The dropout probability applied to the attention output before combining with residual.
@@ -38,15 +42,26 @@ class MPTConfig(PretrainedConfig):
38
  When the model is in `train` mode, this requires passing an extra `sequence_id` argument which indicates
39
  which sub-sequence each token belongs to.
40
  Defaults to ``False`` meaning any provided `sequence_id` will be ignored.
 
41
  alibi (bool): Whether to use the alibi bias instead of position embeddings.
42
  alibi_bias_max (int): The maximum value of the alibi bias.
 
 
 
 
 
 
 
 
 
 
43
  kv_n_heads (Optional[int]): For grouped_query_attention only, allow user to specify number of kv heads.
44
  ffn_config (Dict): A dictionary used to configure the model's ffn module:
45
- ffn_type (str): type of ffn to use. Options: mptmlp, te_ln_mlp
46
  init_device (str): The device to use for parameter initialization.
47
  logit_scale (Optional[Union[float, str]]): If not None, scale the logits by this value.
48
  no_bias (bool): Whether to use bias in all layers.
49
- verbose (int): The verbosity level. 0 is silent.
50
  embedding_fraction (float): The fraction to scale the gradients of the embedding layer by.
51
  norm_type (str): choose type of norm to use
52
  use_cache (bool): Whether or not the model should return the last key/values attentions
@@ -66,6 +81,8 @@ class MPTConfig(PretrainedConfig):
66
  ---
67
  See llmfoundry.models.utils.param_init_fns.py for info on other param init config options
68
  fc_type (str): choose fc layer implementation. Options: torch and te. te layers support fp8 when using H100 GPUs.
 
 
69
  """
70
  self.d_model = d_model
71
  self.n_heads = n_heads
@@ -86,22 +103,25 @@ class MPTConfig(PretrainedConfig):
86
  self.use_cache = use_cache
87
  self.init_config = init_config
88
  self.fc_type = fc_type
 
89
  if verbose is not None:
90
  warnings.warn(DeprecationWarning('verbose argument for MPTConfig is now ignored and will be removed. Use python_log_level instead.'))
91
  if 'name' in kwargs:
92
  del kwargs['name']
93
  if 'loss_fn' in kwargs:
94
  del kwargs['loss_fn']
95
- if self.attn_config.get('alibi', False):
96
  self.learned_pos_emb = False
97
- warnings.warn(f'alibi is turned on, setting `learned_pos_emb` to `False.`')
98
- super().__init__(**kwargs)
99
  self._validate_config()
100
 
101
  def _set_config_defaults(self, config: Dict[str, Any], config_defaults: Dict[str, Any]) -> Dict[str, Any]:
102
  for (k, v) in config_defaults.items():
103
  if k not in config:
104
  config[k] = v
 
 
105
  return config
106
 
107
  def _validate_config(self) -> None:
@@ -116,25 +136,45 @@ class MPTConfig(PretrainedConfig):
116
  raise ValueError(f"Unknown attn_impl={self.attn_config['attn_impl']}")
117
  if self.attn_config['prefix_lm'] and self.attn_config['attn_impl'] not in ['torch', 'triton']:
118
  raise NotImplementedError('prefix_lm only implemented with torch and triton attention.')
119
- if self.attn_config['alibi'] and self.attn_config['attn_impl'] not in ['torch', 'triton']:
120
- raise NotImplementedError('alibi only implemented with torch and triton attention.')
121
- if self.attn_config['attn_uses_sequence_id'] and self.attn_config['attn_impl'] not in ['torch', 'triton']:
122
- raise NotImplementedError('attn_uses_sequence_id only implemented with torch and triton attention.')
 
 
 
 
 
 
 
 
 
 
 
123
  if self.embedding_fraction > 1 or self.embedding_fraction <= 0:
124
  raise ValueError('model.embedding_fraction must be between 0 (exclusive) and 1 (inclusive)!')
125
  if isinstance(self.logit_scale, str) and self.logit_scale != 'inv_sqrt_d_model':
126
  raise ValueError(f"self.logit_scale={self.logit_scale!r} is not recognized as an option; use numeric value or 'inv_sqrt_d_model'.")
127
  if self.init_config.get('name', None) is None:
128
  raise ValueError(f"self.init_config={self.init_config!r} 'name' needs to be set.")
129
- if not self.learned_pos_emb and (not self.attn_config['alibi']):
130
- warnings.warn(f'Positional information not being provided to the model using either learned_pos_emb or alibi.')
131
  if self.fc_type == 'te' or self.ffn_config['ffn_type'] == 'te_ln_mlp':
132
  try:
133
  import transformer_engine.pytorch as te
134
  del te
135
  except:
136
  raise ImportError('TransformerEngine import fail. `fc_type: te` requires TransformerEngine be installed. ' + 'The required version of transformer_engine also requires FlashAttention v1.0.6 is installed:\n' + 'pip install flash-attn==1.0.6 --no-build-isolation \n' + 'pip install git+https://github.com/NVIDIA/TransformerEngine.git@144e4888b2cdd60bd52e706d5b7a79cb9c1a7156')
137
- if self.ffn_config['ffn_type'] == 'mptmlp':
 
 
138
  self.ffn_config['fc_type'] = self.fc_type
139
  elif self.ffn_config['ffn_type'] == 'te_ln_mlp':
140
- self.ffn_config['bias'] = not self.no_bias
 
 
 
 
 
 
 
 
2
  import warnings
3
  from typing import Any, Dict, Optional, Union
4
  from transformers import PretrainedConfig
5
+ from .attention import check_alibi_support, is_flash_v2_installed
6
+ from .blocks import attn_config_defaults
7
+ from .fc import FC_CLASS_REGISTRY
8
+ from .norm import LPLayerNorm
9
+ from .ffn import FFN_CLASS_REGISTRY
10
  ffn_config_defaults: Dict = {'ffn_type': 'mptmlp'}
11
  init_config_defaults: Dict = {'name': 'kaiming_normal_', 'fan_mode': 'fan_in', 'init_nonlinearity': 'relu', 'init_div_is_residual': True, 'emb_init_std': None, 'emb_init_uniform_lim': None, 'init_std': None, 'init_gain': 0.0}
12
 
13
  class MPTConfig(PretrainedConfig):
14
  model_type = 'mpt'
15
 
16
+ def __init__(self, d_model: int=2048, n_heads: int=16, n_layers: int=24, expansion_ratio: Union[int, float]=4, max_seq_len: int=2048, vocab_size: int=50368, resid_pdrop: float=0.0, emb_pdrop: float=0.0, learned_pos_emb: bool=True, attn_config: Dict=attn_config_defaults, ffn_config: Dict=ffn_config_defaults, init_device: str='cpu', logit_scale: Optional[Union[float, str]]=None, no_bias: bool=False, embedding_fraction: float=1.0, norm_type: str='low_precision_layernorm', use_cache: bool=False, init_config: Dict=init_config_defaults, fc_type: str='torch', tie_word_embeddings: bool=True, use_pad_tok_in_ffn: bool=True, verbose: Optional[int]=None, **kwargs: Any):
17
  """The MPT configuration class.
18
 
19
  Args:
20
  d_model (int): The size of the embedding dimension of the model.
21
  n_heads (int): The number of attention heads.
22
  n_layers (int): The number of layers in the model.
23
+ expansion_ratio (Union[int, float]): The ratio of the up/down scale in the ffn.
24
  max_seq_len (int): The maximum sequence length of the model.
25
  vocab_size (int): The size of the vocabulary.
26
  resid_pdrop (float): The dropout probability applied to the attention output before combining with residual.
 
42
  When the model is in `train` mode, this requires passing an extra `sequence_id` argument which indicates
43
  which sub-sequence each token belongs to.
44
  Defaults to ``False`` meaning any provided `sequence_id` will be ignored.
45
+ sliding_window_size (int): Window size for sliding window local attention. Defaults to -1, which means no sliding window. Query at position i will only attend to keys between [i + seqlen_k - seqlen_q - window_size, i + seqlen_k - seqlen_q + window_size] inclusive. Only works for flash attention v2.3.0 or higher.
46
  alibi (bool): Whether to use the alibi bias instead of position embeddings.
47
  alibi_bias_max (int): The maximum value of the alibi bias.
48
+ rope (bool): Whether to use rotary positional embeddings.
49
+ rope_theta (int): The base frequency for rope.
50
+ rope_impl (str): The implementation of rope to use. One of 'hf' (to use the implementation from https://github.com/huggingface/transformers/blob/main/src/transformers/models/llama/modeling_llama.py) or 'dail' (to use the implementation from https://github.com/Dao-AILab/flash-attention/blob/main/flash_attn/layers/rotary.py).
51
+ rope_dail_config (Dict): The configuration for the dail implementation of rope.
52
+ type (str): The type of rotary position embedding to use. Options: 'original' (for https://arxiv.org/pdf/2104.09864.pdf), 'xpos' (for https://arxiv.org/pdf/2212.10554.pdf).
53
+ pos_idx_in_fp32 (bool): If True, the position indices [0, ..., seqlen - 1] are in fp32, otherwise they might be in lower precision. A consequence could be, for example, that bf16 rounds position 1995 to 2000, which leads to them having the same positional embedding.
54
+ xpos_scale_base (float): The scale base for XPos (if using XPos).
55
+ rope_hf_config (Dict): A dictionary used to configure rope's scaling behavior (when scaling beyond the training length).
56
+ type (str): Can be one of 'no_scaling', 'linear', or 'dynamic'. 'no_scaling' uses the default implementation for rotary embeddings, 'linear' uses linear scaling as proposed by the Reddit user /u/kaiokendev, and 'dynamic' uses Dynamic NTK scaling as proposed by the Reddit users /u/bloc97 and /u/emozilla.
57
+ factor (float): Scaling factor to use if using 'linear' or 'dynamic' as rope_scaling.type.
58
  kv_n_heads (Optional[int]): For grouped_query_attention only, allow user to specify number of kv heads.
59
  ffn_config (Dict): A dictionary used to configure the model's ffn module:
60
+ ffn_type (str): type of ffn to use. Options: mptmlp, mptglu, te_ln_mlp
61
  init_device (str): The device to use for parameter initialization.
62
  logit_scale (Optional[Union[float, str]]): If not None, scale the logits by this value.
63
  no_bias (bool): Whether to use bias in all layers.
64
+ verbose (int): Deprecated.
65
  embedding_fraction (float): The fraction to scale the gradients of the embedding layer by.
66
  norm_type (str): choose type of norm to use
67
  use_cache (bool): Whether or not the model should return the last key/values attentions
 
81
  ---
82
  See llmfoundry.models.utils.param_init_fns.py for info on other param init config options
83
  fc_type (str): choose fc layer implementation. Options: torch and te. te layers support fp8 when using H100 GPUs.
84
+ tie_word_embeddings (bool): Whether to tie the input embedding and output layers.
85
+ use_pad_tok_in_ffn (bool): Whether to forward the pad token in the feedforward networks.
86
  """
87
  self.d_model = d_model
88
  self.n_heads = n_heads
 
103
  self.use_cache = use_cache
104
  self.init_config = init_config
105
  self.fc_type = fc_type
106
+ self.use_pad_tok_in_ffn = use_pad_tok_in_ffn
107
  if verbose is not None:
108
  warnings.warn(DeprecationWarning('verbose argument for MPTConfig is now ignored and will be removed. Use python_log_level instead.'))
109
  if 'name' in kwargs:
110
  del kwargs['name']
111
  if 'loss_fn' in kwargs:
112
  del kwargs['loss_fn']
113
+ if self.attn_config.get('alibi', False) or self.attn_config.get('rope', False):
114
  self.learned_pos_emb = False
115
+ warnings.warn(f'alibi or rope is turned on, setting `learned_pos_emb` to `False.`')
116
+ super().__init__(tie_word_embeddings=tie_word_embeddings, **kwargs)
117
  self._validate_config()
118
 
119
  def _set_config_defaults(self, config: Dict[str, Any], config_defaults: Dict[str, Any]) -> Dict[str, Any]:
120
  for (k, v) in config_defaults.items():
121
  if k not in config:
122
  config[k] = v
123
+ elif isinstance(v, dict):
124
+ config[k] = self._set_config_defaults(config[k] if config[k] is not None else {}, v)
125
  return config
126
 
127
  def _validate_config(self) -> None:
 
136
  raise ValueError(f"Unknown attn_impl={self.attn_config['attn_impl']}")
137
  if self.attn_config['prefix_lm'] and self.attn_config['attn_impl'] not in ['torch', 'triton']:
138
  raise NotImplementedError('prefix_lm only implemented with torch and triton attention.')
139
+ if self.attn_config['alibi'] and (not check_alibi_support(self.attn_config['attn_impl'])):
140
+ raise NotImplementedError('alibi only implemented with torch, triton, and flash (v2.4.2 or higher) attention.')
141
+ if self.attn_config['attn_uses_sequence_id'] and (not (self.attn_config['attn_impl'] in ['torch', 'triton'] or (self.attn_config['attn_impl'] == 'flash' and is_flash_v2_installed(v2_version='v2.1.2')))):
142
+ raise NotImplementedError('attn_uses_sequence_id only implemented with torch, triton, and flash (v2.1.2 or higher) attention.')
143
+ if self.attn_config['rope'] and self.attn_config['rope_impl'] not in ['dail', 'hf']:
144
+ raise ValueError('If rope is being used then rope_impl should be either "dail", or "hf".')
145
+ if self.attn_config['rope'] and self.attn_config['rope_impl'] == 'hf' and (self.attn_config['rope_hf_config']['type'] not in ['no_scaling', 'linear', 'dynamic']):
146
+ raise ValueError('If using hf implementation of rope, the type should be one of "no_scaling", "linear" or "dynamic".')
147
+ if self.attn_config['rope'] and self.attn_config['rope_impl'] == 'dail':
148
+ if self.attn_config['rope_dail_config']['type'] not in ['original', 'xpos']:
149
+ raise ValueError('If using the dail implementation of rope, the type should be one of "original" or "xpos".')
150
+ if not is_flash_v2_installed(v2_version='2.0.1'):
151
+ raise ImportError('If using the dail implementation of rope, the flash_attn library v2.0.1 or higher must be installed. Please check the instructions at https://github.com/mosaicml/llm-foundry/blob/main/TUTORIAL.md#what-kinds-of-positional-embeddings-does-llm-foundry-support')
152
+ if self.attn_config['sliding_window_size'] != -1 and (not (self.attn_config['attn_impl'] == 'flash' and is_flash_v2_installed(v2_version='v2.3.0'))):
153
+ raise NotImplementedError('sliding window only implemented with flash attention v2.3.0 or higher.')
154
  if self.embedding_fraction > 1 or self.embedding_fraction <= 0:
155
  raise ValueError('model.embedding_fraction must be between 0 (exclusive) and 1 (inclusive)!')
156
  if isinstance(self.logit_scale, str) and self.logit_scale != 'inv_sqrt_d_model':
157
  raise ValueError(f"self.logit_scale={self.logit_scale!r} is not recognized as an option; use numeric value or 'inv_sqrt_d_model'.")
158
  if self.init_config.get('name', None) is None:
159
  raise ValueError(f"self.init_config={self.init_config!r} 'name' needs to be set.")
160
+ if not (self.learned_pos_emb or self.attn_config['alibi'] or self.attn_config['rope']):
161
+ warnings.warn(f'Positional information not being provided to the model using either learned_pos_emb or alibi or rope.')
162
  if self.fc_type == 'te' or self.ffn_config['ffn_type'] == 'te_ln_mlp':
163
  try:
164
  import transformer_engine.pytorch as te
165
  del te
166
  except:
167
  raise ImportError('TransformerEngine import fail. `fc_type: te` requires TransformerEngine be installed. ' + 'The required version of transformer_engine also requires FlashAttention v1.0.6 is installed:\n' + 'pip install flash-attn==1.0.6 --no-build-isolation \n' + 'pip install git+https://github.com/NVIDIA/TransformerEngine.git@144e4888b2cdd60bd52e706d5b7a79cb9c1a7156')
168
+ if self.ffn_config['ffn_type'] == 'mptgeglu':
169
+ raise ValueError('API CHANGE: `ffn_type=="mptgeglu"` changed to `ffn_type=="mptglu"`. ' + 'See [#829](https://github.com/mosaicml/llm-foundry/pull/829) for details.')
170
+ elif self.ffn_config['ffn_type'] in ['mptmlp', 'mptglu']:
171
  self.ffn_config['fc_type'] = self.fc_type
172
  elif self.ffn_config['ffn_type'] == 'te_ln_mlp':
173
+ self.ffn_config['bias'] = not self.no_bias
174
+ if 'ffn_act_fn' in self.ffn_config.keys():
175
+ raise ValueError(f'Transformer Engine block does not support custom activation functions.')
176
+ if not self.use_pad_tok_in_ffn:
177
+ try:
178
+ from flash_attn.bert_padding import unpad_input, pad_input
179
+ except:
180
+ raise ImportError('In order to set `use_pad_tok_in_ffn=False`, please install flash-attn==1.0.9 or flash-attn==2.3.6')
ffn.py CHANGED
@@ -1,5 +1,8 @@
1
- """GPT Blocks used for the GPT Model."""
2
- from typing import Any, Optional
 
 
 
3
  import torch
4
  import torch.nn as nn
5
  from .fc import FC_CLASS_REGISTRY
@@ -7,33 +10,88 @@ try:
7
  import transformer_engine.pytorch as te
8
  except:
9
  te = None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10
 
11
  class MPTMLP(nn.Module):
12
 
13
- def __init__(self, d_model: int, expansion_ratio: int, fc_type: str='torch', device: Optional[str]=None):
14
  super().__init__()
15
- fc_kwargs = {}
 
16
  if fc_type != 'te':
17
- fc_kwargs['device'] = device
18
- self.up_proj = FC_CLASS_REGISTRY[fc_type](d_model, expansion_ratio * d_model, **fc_kwargs)
19
- self.act = nn.GELU(approximate='none')
20
- self.down_proj = FC_CLASS_REGISTRY[fc_type](expansion_ratio * d_model, d_model, **fc_kwargs)
21
  self.down_proj._is_residual = True
22
 
23
  def forward(self, x: torch.Tensor) -> torch.Tensor:
24
  return self.down_proj(self.act(self.up_proj(x)))
25
- FFN_CLASS_REGISTRY = {'mptmlp': MPTMLP}
 
 
 
 
 
 
 
 
 
26
  if te is not None:
27
  te.LayerNormMLP._has_norm = True
28
  FFN_CLASS_REGISTRY['te_ln_mlp'] = te.LayerNormMLP
29
 
30
- def build_ffn(d_model: int, expansion_ratio: int, fc_type: str='torch', device: Optional[str]=None, **kwargs: Any) -> nn.Module:
31
  ffn_type = kwargs.pop('ffn_type')
32
- if ffn_type == 'mptmlp':
33
  if len(kwargs) > 0:
34
- raise ValueError(f'MPTMLP got an unexpected keyword argument: {kwargs}')
35
- return MPTMLP(d_model=d_model, expansion_ratio=expansion_ratio, fc_type=fc_type, device=device)
36
  elif ffn_type == 'te_ln_mlp':
37
  assert te is not None
38
- return te.LayerNormMLP(hidden_size=d_model, ffn_hidden_size=d_model * expansion_ratio, **kwargs)
 
 
 
39
  raise ValueError(f'ffn_type={ffn_type!r} not recognized.')
 
1
+ """MPT Blocks used for the MPT Model."""
2
+ import logging
3
+ from copy import deepcopy
4
+ from functools import partial
5
+ from typing import Any, Callable, Optional, Union
6
  import torch
7
  import torch.nn as nn
8
  from .fc import FC_CLASS_REGISTRY
 
10
  import transformer_engine.pytorch as te
11
  except:
12
  te = None
13
+ log = logging.getLogger(__name__)
14
+ _FFN_ACT_FN_DEFAULT = {'name': 'gelu', 'approximate': 'none'}
15
+
16
+ def resolve_ffn_act_fn(config: Optional[dict]=None) -> Callable[[torch.Tensor], torch.Tensor]:
17
+ """Resolve the activation function for the feed-forward network.
18
+
19
+ Args:
20
+ config (Optional[dict]): The configuration dictionary for the activation function.
21
+ The dict config must specify the 'name' of a torch.nn.functional activation
22
+ function. All of other key values pairs are bound to the function as a partial.
23
+
24
+ Returns:
25
+ Callable[[torch.Tensor], torch.Tensor]: The activation function.
26
+ """
27
+ if config is None:
28
+ config = _FFN_ACT_FN_DEFAULT
29
+ config = deepcopy(config)
30
+ name = config.pop('name')
31
+ if not hasattr(torch.nn.functional, name):
32
+ raise ValueError(f'Unrecognised activation function name ({name}).')
33
+ act = getattr(torch.nn.functional, name)
34
+ return partial(act, **config)
35
+ _DEFAULT_ACT_FN = resolve_ffn_act_fn(_FFN_ACT_FN_DEFAULT)
36
+
37
+ def resolve_ffn_hidden_size(d_model: int, expansion_ratio: Union[int, float], ffn_hidden_size: Optional[int]=None) -> int:
38
+ """Resolve the hidden size of the feed-forward network.
39
+
40
+ Args:
41
+ d_model (int): The dimension of the input and output of the feed-forward network.
42
+ expansion_ratio (Union[int, float]): The expansion ratio of the feed-forward network.
43
+ ffn_hidden_size (Optional[int]): The hidden size of the feed-forward network.
44
+
45
+ Returns:
46
+ int: The hidden size of the feed-forward network.
47
+ """
48
+ if ffn_hidden_size is not None:
49
+ log.info(f'`expansion_ratio` (={expansion_ratio}) ignored when `ffn_hidden_size` (={ffn_hidden_size}) is specified.')
50
+ else:
51
+ ffn_hidden_size = int(d_model * expansion_ratio)
52
+ if ffn_hidden_size != d_model * expansion_ratio:
53
+ raise ValueError(f'`d_model * expansion_ratio` must be an integer (d_model={d_model!r}; expansion_ratio={expansion_ratio!r}; d_model * expansion_ratio={d_model * expansion_ratio!r}).')
54
+ return ffn_hidden_size
55
 
56
  class MPTMLP(nn.Module):
57
 
58
+ def __init__(self, d_model: int, expansion_ratio: Union[int, float], fc_type: str='torch', ffn_hidden_size: Optional[int]=None, act_fn: Callable[[torch.Tensor], torch.Tensor]=_DEFAULT_ACT_FN, device: Optional[str]=None, bias: bool=True):
59
  super().__init__()
60
+ ffn_hidden_size = resolve_ffn_hidden_size(d_model, expansion_ratio, ffn_hidden_size)
61
+ self.fc_kwargs: dict[str, Any] = {'bias': bias}
62
  if fc_type != 'te':
63
+ self.fc_kwargs['device'] = device
64
+ self.up_proj = FC_CLASS_REGISTRY[fc_type](d_model, ffn_hidden_size, **self.fc_kwargs)
65
+ self.act = act_fn
66
+ self.down_proj = FC_CLASS_REGISTRY[fc_type](ffn_hidden_size, d_model, **self.fc_kwargs)
67
  self.down_proj._is_residual = True
68
 
69
  def forward(self, x: torch.Tensor) -> torch.Tensor:
70
  return self.down_proj(self.act(self.up_proj(x)))
71
+
72
+ class MPTGLU(MPTMLP):
73
+
74
+ def __init__(self, d_model: int, expansion_ratio: Union[int, float], fc_type: str='torch', ffn_hidden_size: Optional[int]=None, act_fn: Callable[[torch.Tensor], torch.Tensor]=_DEFAULT_ACT_FN, device: Optional[str]=None, bias: bool=True):
75
+ super().__init__(d_model=d_model, expansion_ratio=expansion_ratio, fc_type=fc_type, ffn_hidden_size=ffn_hidden_size, act_fn=act_fn, device=device, bias=bias)
76
+ self.gate_proj = FC_CLASS_REGISTRY[fc_type](d_model, self.up_proj.out_features, **self.fc_kwargs)
77
+
78
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
79
+ return self.down_proj(self.act(self.gate_proj(x)) * self.up_proj(x))
80
+ FFN_CLASS_REGISTRY = {'mptmlp': MPTMLP, 'mptglu': MPTGLU}
81
  if te is not None:
82
  te.LayerNormMLP._has_norm = True
83
  FFN_CLASS_REGISTRY['te_ln_mlp'] = te.LayerNormMLP
84
 
85
+ def build_ffn(d_model: int, expansion_ratio: Union[int, float], fc_type: str='torch', ffn_hidden_size: Optional[int]=None, ffn_act_fn: Optional[dict]=None, device: Optional[str]=None, bias: bool=True, **kwargs: Any) -> nn.Module:
86
  ffn_type = kwargs.pop('ffn_type')
87
+ if ffn_type in ['mptmlp', 'mptglu']:
88
  if len(kwargs) > 0:
89
+ raise ValueError(f'MPTMLP (or MPTGLU) got an unexpected keyword argument: {kwargs}')
90
+ return FFN_CLASS_REGISTRY[ffn_type](d_model=d_model, expansion_ratio=expansion_ratio, fc_type=fc_type, act_fn=resolve_ffn_act_fn(ffn_act_fn), ffn_hidden_size=ffn_hidden_size, device=device, bias=bias)
91
  elif ffn_type == 'te_ln_mlp':
92
  assert te is not None
93
+ ffn_hidden_size = resolve_ffn_hidden_size(d_model, expansion_ratio, ffn_hidden_size)
94
+ if ffn_act_fn is not None:
95
+ raise ValueError(f'Transformer Engine block does not support custom activation functions.')
96
+ return te.LayerNormMLP(hidden_size=d_model, ffn_hidden_size=ffn_hidden_size, bias=bias, **kwargs)
97
  raise ValueError(f'ffn_type={ffn_type!r} not recognized.')
hf_prefixlm_converter.py CHANGED
@@ -6,23 +6,13 @@ Causal LM to convert it to a Prefix LM.
6
  Prefix LMs accepts a `bidirectional_mask` input in `forward`
7
  and treat the input prompt as the prefix in `generate`.
8
  """
9
- import math
10
- import warnings
11
  from types import MethodType
12
  from typing import Any, List, MutableMapping, Optional, Tuple, Union
13
  import torch
14
- from transformers.models.bloom.modeling_bloom import BaseModelOutputWithPastAndCrossAttentions, BloomForCausalLM, BloomModel, CausalLMOutputWithCrossAttentions, CrossEntropyLoss
15
- from transformers.models.bloom.modeling_bloom import _expand_mask as _expand_mask_bloom
16
- from transformers.models.bloom.modeling_bloom import _make_causal_mask as _make_causal_mask_bloom
17
- from transformers.models.bloom.modeling_bloom import logging
18
  from transformers.models.gpt2.modeling_gpt2 import GPT2LMHeadModel
19
  from transformers.models.gpt_neo.modeling_gpt_neo import GPTNeoForCausalLM
20
  from transformers.models.gpt_neox.modeling_gpt_neox import GPTNeoXForCausalLM
21
  from transformers.models.gptj.modeling_gptj import GPTJForCausalLM
22
- from transformers.models.opt.modeling_opt import OPTForCausalLM
23
- from transformers.models.opt.modeling_opt import _expand_mask as _expand_mask_opt
24
- from transformers.models.opt.modeling_opt import _make_causal_mask as _make_causal_mask_opt
25
- logger = logging.get_logger(__name__)
26
  _SUPPORTED_GPT_MODELS = (GPT2LMHeadModel, GPTJForCausalLM, GPTNeoForCausalLM, GPTNeoXForCausalLM)
27
  CAUSAL_GPT_TYPES = Union[GPT2LMHeadModel, GPTJForCausalLM, GPTNeoForCausalLM, GPTNeoXForCausalLM]
28
 
@@ -110,232 +100,8 @@ def _convert_gpt_causal_lm_to_prefix_lm(model: CAUSAL_GPT_TYPES) -> CAUSAL_GPT_T
110
  setattr(model, 'generate', MethodType(generate, model))
111
  setattr(model, '_prefix_lm_converted', True)
112
  return model
113
-
114
- def _convert_bloom_causal_lm_to_prefix_lm(model: BloomForCausalLM) -> BloomForCausalLM:
115
- """Converts a BLOOM Causal LM to a Prefix LM.
116
-
117
- Supported HuggingFace model classes:
118
- - `BloomForCausalLM`
119
-
120
- See `convert_hf_causal_lm_to_prefix_lm` for more details.
121
- """
122
- if hasattr(model, '_prefix_lm_converted'):
123
- return model
124
- assert isinstance(model, BloomForCausalLM)
125
- assert model.config.add_cross_attention == False, 'Only supports BLOOM decoder-only models'
126
-
127
- def _prepare_attn_mask(self: BloomModel, attention_mask: torch.Tensor, bidirectional_mask: Optional[torch.Tensor], input_shape: Tuple[int, int], past_key_values_length: int) -> torch.BoolTensor:
128
- combined_attention_mask = None
129
- device = attention_mask.device
130
- (_, src_length) = input_shape
131
- if src_length > 1:
132
- combined_attention_mask = _make_causal_mask_bloom(input_shape, device=device, past_key_values_length=past_key_values_length)
133
- if bidirectional_mask is not None:
134
- assert attention_mask.shape == bidirectional_mask.shape
135
- expanded_bidirectional_mask = _expand_mask_bloom(bidirectional_mask, tgt_length=src_length)
136
- combined_attention_mask = torch.logical_and(combined_attention_mask, expanded_bidirectional_mask)
137
- expanded_attn_mask = _expand_mask_bloom(attention_mask, tgt_length=src_length)
138
- combined_attention_mask = expanded_attn_mask if combined_attention_mask is None else expanded_attn_mask | combined_attention_mask
139
- return combined_attention_mask
140
-
141
- def _build_alibi_tensor(self: BloomModel, batch_size: int, query_length: int, key_length: int, dtype: torch.dtype, device: torch.device) -> torch.Tensor:
142
- num_heads = self.config.n_head
143
- closest_power_of_2 = 2 ** math.floor(math.log2(num_heads))
144
- base = torch.tensor(2 ** (-2 ** (-(math.log2(closest_power_of_2) - 3))), device=device, dtype=torch.float32)
145
- powers = torch.arange(1, 1 + closest_power_of_2, device=device, dtype=torch.int32)
146
- slopes = torch.pow(base, powers)
147
- if closest_power_of_2 != num_heads:
148
- extra_base = torch.tensor(2 ** (-2 ** (-(math.log2(2 * closest_power_of_2) - 3))), device=device, dtype=torch.float32)
149
- num_remaining_heads = min(closest_power_of_2, num_heads - closest_power_of_2)
150
- extra_powers = torch.arange(1, 1 + 2 * num_remaining_heads, 2, device=device, dtype=torch.int32)
151
- slopes = torch.cat([slopes, torch.pow(extra_base, extra_powers)], dim=0)
152
- qa = torch.arange(query_length, device=device, dtype=torch.int32).view(-1, 1)
153
- ka = torch.arange(key_length, device=device, dtype=torch.int32).view(1, -1)
154
- diffs = qa - ka + key_length - query_length
155
- diffs = -diffs.abs()
156
- alibi = slopes.view(1, num_heads, 1, 1) * diffs.view(1, 1, query_length, key_length)
157
- alibi = alibi.expand(batch_size, -1, -1, -1).reshape(-1, query_length, key_length)
158
- return alibi.to(dtype)
159
- KeyValueT = Tuple[torch.Tensor, torch.Tensor]
160
-
161
- def transformer_forward(self: BloomModel, input_ids: Optional[torch.LongTensor]=None, past_key_values: Optional[Tuple[KeyValueT, ...]]=None, attention_mask: Optional[torch.Tensor]=None, bidirectional_mask: Optional[torch.Tensor]=None, head_mask: Optional[torch.LongTensor]=None, inputs_embeds: Optional[torch.LongTensor]=None, use_cache: Optional[bool]=None, output_attentions: Optional[bool]=None, output_hidden_states: Optional[bool]=None, return_dict: Optional[bool]=None, **deprecated_arguments: Any) -> Union[Tuple[torch.Tensor, ...], BaseModelOutputWithPastAndCrossAttentions]:
162
- if deprecated_arguments.pop('position_ids', False) is not False:
163
- warnings.warn('`position_ids` have no functionality in BLOOM and will be removed in v5.0.0. ' + 'You can safely ignore passing `position_ids`.', FutureWarning)
164
- if len(deprecated_arguments) > 0:
165
- raise ValueError(f'Got unexpected arguments: {deprecated_arguments}')
166
- output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
167
- output_hidden_states = output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
168
- use_cache = use_cache if use_cache is not None else self.config.use_cache
169
- return_dict = return_dict if return_dict is not None else self.config.use_return_dict
170
- if input_ids is not None and inputs_embeds is not None:
171
- raise ValueError('You cannot specify both input_ids and inputs_embeds at the same time')
172
- elif input_ids is not None:
173
- (batch_size, seq_length) = input_ids.shape
174
- elif inputs_embeds is not None:
175
- (batch_size, seq_length, _) = inputs_embeds.shape
176
- else:
177
- raise ValueError('You have to specify either input_ids or inputs_embeds')
178
- if past_key_values is None:
179
- past_key_values = tuple([None] * len(self.h))
180
- head_mask = self.get_head_mask(head_mask, self.config.n_layer)
181
- if inputs_embeds is None:
182
- inputs_embeds = self.word_embeddings(input_ids)
183
- hidden_states = self.word_embeddings_layernorm(inputs_embeds)
184
- presents = () if use_cache else None
185
- all_self_attentions = () if output_attentions else None
186
- all_hidden_states = () if output_hidden_states else None
187
- seq_length_with_past = seq_length
188
- past_key_values_length = 0
189
- if past_key_values[0] is not None:
190
- tmp = past_key_values[0][0]
191
- past_key_values_length = tmp.shape[2]
192
- seq_length_with_past = seq_length_with_past + past_key_values_length
193
- if attention_mask is None:
194
- attention_mask = torch.ones((batch_size, seq_length_with_past), device=hidden_states.device)
195
- else:
196
- attention_mask = attention_mask.to(hidden_states.device)
197
- alibi = self._build_alibi_tensor(batch_size=batch_size, query_length=seq_length, key_length=seq_length_with_past, dtype=hidden_states.dtype, device=hidden_states.device)
198
- causal_mask = self._prepare_attn_mask(attention_mask, bidirectional_mask, input_shape=(batch_size, seq_length), past_key_values_length=past_key_values_length)
199
- for (i, (block, layer_past)) in enumerate(zip(self.h, past_key_values)):
200
- if output_hidden_states:
201
- hst = (hidden_states,)
202
- all_hidden_states = all_hidden_states + hst
203
- if self.gradient_checkpointing and self.training:
204
- if use_cache:
205
- logger.warning('`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`...')
206
- use_cache = False
207
-
208
- def create_custom_forward(module: torch.nn.Module):
209
-
210
- def custom_forward(*inputs: Any):
211
- return module(*inputs, use_cache=use_cache, output_attentions=output_attentions)
212
- return custom_forward
213
- outputs = torch.utils.checkpoint.checkpoint(create_custom_forward(block), hidden_states, alibi, causal_mask, head_mask[i])
214
- else:
215
- outputs = block(hidden_states, layer_past=layer_past, attention_mask=causal_mask, head_mask=head_mask[i], use_cache=use_cache, output_attentions=output_attentions, alibi=alibi)
216
- hidden_states = outputs[0]
217
- if use_cache is True:
218
- presents = presents + (outputs[1],)
219
- if output_attentions:
220
- oa = (outputs[2 if use_cache else 1],)
221
- all_self_attentions = all_self_attentions + oa
222
- hidden_states = self.ln_f(hidden_states)
223
- if output_hidden_states:
224
- hst = (hidden_states,)
225
- all_hidden_states = all_hidden_states + hst
226
- if not return_dict:
227
- return tuple((v for v in [hidden_states, presents, all_hidden_states, all_self_attentions] if v is not None))
228
- return BaseModelOutputWithPastAndCrossAttentions(last_hidden_state=hidden_states, past_key_values=presents, hidden_states=all_hidden_states, attentions=all_self_attentions)
229
- setattr(model.transformer, '_prepare_attn_mask', MethodType(_prepare_attn_mask, model.transformer))
230
- setattr(model.transformer, '_build_alibi_tensor', MethodType(_build_alibi_tensor, model.transformer))
231
- setattr(model.transformer, 'forward', MethodType(transformer_forward, model.transformer))
232
- KeyValueT = Tuple[torch.Tensor, torch.Tensor]
233
-
234
- def forward(self: BloomForCausalLM, input_ids: Optional[torch.LongTensor]=None, past_key_values: Optional[Tuple[KeyValueT, ...]]=None, attention_mask: Optional[torch.Tensor]=None, bidirectional_mask: Optional[torch.Tensor]=None, head_mask: Optional[torch.Tensor]=None, inputs_embeds: Optional[torch.Tensor]=None, labels: Optional[torch.Tensor]=None, use_cache: Optional[bool]=None, output_attentions: Optional[bool]=None, output_hidden_states: Optional[bool]=None, return_dict: Optional[bool]=None, **deprecated_arguments: Any) -> Union[Tuple[torch.Tensor], CausalLMOutputWithCrossAttentions]:
235
- """Replacement forward method for BloomCausalLM."""
236
- if deprecated_arguments.pop('position_ids', False) is not False:
237
- warnings.warn('`position_ids` have no functionality in BLOOM and will be removed ' + 'in v5.0.0. You can safely ignore passing `position_ids`.', FutureWarning)
238
- if len(deprecated_arguments) > 0:
239
- raise ValueError(f'Got unexpected arguments: {deprecated_arguments}')
240
- return_dict = return_dict if return_dict is not None else self.config.use_return_dict
241
- transformer_outputs = self.transformer(input_ids, past_key_values=past_key_values, attention_mask=attention_mask, bidirectional_mask=bidirectional_mask, head_mask=head_mask, inputs_embeds=inputs_embeds, use_cache=use_cache, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict)
242
- hidden_states = transformer_outputs[0]
243
- lm_logits = self.lm_head(hidden_states)
244
- loss = None
245
- if labels is not None:
246
- shift_logits = lm_logits[..., :-1, :].contiguous()
247
- shift_labels = labels[..., 1:].contiguous()
248
- (batch_size, seq_length, vocab_size) = shift_logits.shape
249
- loss_fct = CrossEntropyLoss()
250
- loss = loss_fct(shift_logits.view(batch_size * seq_length, vocab_size), shift_labels.view(batch_size * seq_length))
251
- if not return_dict:
252
- output = (lm_logits,) + transformer_outputs[1:]
253
- return (loss,) + output if loss is not None else output
254
- return CausalLMOutputWithCrossAttentions(loss=loss, logits=lm_logits, past_key_values=transformer_outputs.past_key_values, hidden_states=transformer_outputs.hidden_states, attentions=transformer_outputs.attentions)
255
-
256
- def prepare_inputs_for_generation(self: BloomForCausalLM, input_ids: torch.LongTensor, past: Optional[torch.Tensor]=None, attention_mask: Optional[torch.Tensor]=None, **kwargs: Any) -> dict:
257
- del kwargs
258
- if past:
259
- input_ids = input_ids[:, -1].unsqueeze(-1)
260
- bidirectional_mask = None
261
- if past[0][0].shape[0] == input_ids.shape[0]:
262
- past = self._convert_to_bloom_cache(past)
263
- else:
264
- bidirectional_mask = torch.ones_like(input_ids)
265
- return {'input_ids': input_ids, 'past_key_values': past, 'use_cache': True, 'attention_mask': attention_mask, 'bidirectional_mask': bidirectional_mask}
266
- setattr(model, 'forward', MethodType(forward, model))
267
- setattr(model, 'prepare_inputs_for_generation', MethodType(prepare_inputs_for_generation, model))
268
- setattr(model, '_prefix_lm_converted', True)
269
- return model
270
-
271
- def _convert_opt_causal_lm_to_prefix_lm(model: OPTForCausalLM) -> OPTForCausalLM:
272
- """Converts an OPT Causal LM to a Prefix LM.
273
-
274
- Supported HuggingFace model classes:
275
- - `OPTForCausalLM`
276
-
277
- See `convert_hf_causal_lm_to_prefix_lm` for more details.
278
- """
279
- if hasattr(model, '_prefix_lm_converted'):
280
- return model
281
- assert isinstance(model, OPTForCausalLM)
282
- assert model.config.add_cross_attention == False, 'Only supports OPT decoder-only models'
283
- setattr(model, '_original_forward', getattr(model, 'forward'))
284
- setattr(model, '_original_generate', getattr(model, 'generate'))
285
- model.model.decoder.bidirectional_mask = None
286
-
287
- def _prepare_decoder_attention_mask(self: torch.nn.Module, attention_mask: Optional[torch.Tensor], input_shape: Tuple[int, int], inputs_embeds: Optional[torch.Tensor], past_key_values_length: int):
288
- combined_attention_mask = None
289
- if input_shape[-1] > 1:
290
- assert inputs_embeds is not None
291
- if self.bidirectional_mask == 'g':
292
- (bsz, src_length) = input_shape
293
- combined_attention_mask = torch.zeros((bsz, 1, src_length, src_length + past_key_values_length), dtype=inputs_embeds.dtype, device=inputs_embeds.device)
294
- else:
295
- combined_attention_mask = _make_causal_mask_opt(input_shape, inputs_embeds.dtype, past_key_values_length=past_key_values_length).to(inputs_embeds.device)
296
- if self.bidirectional_mask is not None:
297
- assert attention_mask is not None
298
- assert attention_mask.shape == self.bidirectional_mask.shape
299
- expanded_bidirectional_mask = _expand_mask_opt(self.bidirectional_mask, inputs_embeds.dtype, tgt_len=input_shape[-1]).to(inputs_embeds.device)
300
- combined_attention_mask = torch.maximum(expanded_bidirectional_mask, combined_attention_mask)
301
- if attention_mask is not None:
302
- assert inputs_embeds is not None
303
- expanded_attn_mask = _expand_mask_opt(attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1]).to(inputs_embeds.device)
304
- combined_attention_mask = expanded_attn_mask if combined_attention_mask is None else expanded_attn_mask + combined_attention_mask
305
- return combined_attention_mask
306
- setattr(model.model.decoder, '_prepare_decoder_attention_mask', MethodType(_prepare_decoder_attention_mask, model.model.decoder))
307
-
308
- def forward(self: OPTForCausalLM, input_ids: Optional[torch.LongTensor]=None, attention_mask: Optional[torch.Tensor]=None, bidirectional_mask: Optional[torch.ByteTensor]=None, head_mask: Optional[torch.Tensor]=None, past_key_values: Optional[List[torch.FloatTensor]]=None, inputs_embeds: Optional[torch.FloatTensor]=None, labels: Optional[torch.LongTensor]=None, use_cache: Optional[bool]=None, output_attentions: Optional[bool]=None, output_hidden_states: Optional[bool]=None, return_dict: Optional[bool]=None):
309
-
310
- def call_og_forward():
311
- return self._original_forward(input_ids=input_ids, attention_mask=attention_mask, head_mask=head_mask, past_key_values=past_key_values, inputs_embeds=inputs_embeds, labels=labels, use_cache=use_cache, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict)
312
- if bidirectional_mask is None:
313
- return call_og_forward()
314
- self.model.decoder.bidirectional_mask = bidirectional_mask
315
- try:
316
- outputs = call_og_forward()
317
- except:
318
- self.model.decoder.bidirectional_mask = None
319
- raise
320
- self.model.decoder.bidirectional_mask = None
321
- return outputs
322
-
323
- def generate(self: OPTForCausalLM, *args: tuple, **kwargs: Any):
324
- """Wraps original generate to enable PrefixLM-style attention."""
325
- self.model.decoder.bidirectional_mask = 'g'
326
- try:
327
- output = self._original_generate(*args, **kwargs)
328
- except:
329
- self.model.decoder.bidirectional_mask = None
330
- raise
331
- self.model.decoder.bidirectional_mask = None
332
- return output
333
- setattr(model, 'forward', MethodType(forward, model))
334
- setattr(model, 'generate', MethodType(generate, model))
335
- setattr(model, '_prefix_lm_converted', True)
336
- return model
337
- _SUPPORTED_HF_MODELS = _SUPPORTED_GPT_MODELS + (BloomForCausalLM, OPTForCausalLM)
338
- CAUSAL_LM_TYPES = Union[GPT2LMHeadModel, GPTJForCausalLM, GPTNeoForCausalLM, GPTNeoXForCausalLM, BloomForCausalLM, OPTForCausalLM]
339
 
340
  def convert_hf_causal_lm_to_prefix_lm(model: CAUSAL_LM_TYPES) -> CAUSAL_LM_TYPES:
341
  """Converts a HuggingFace Causal LM to a Prefix LM.
@@ -345,8 +111,6 @@ def convert_hf_causal_lm_to_prefix_lm(model: CAUSAL_LM_TYPES) -> CAUSAL_LM_TYPES
345
  - `GPTNeoForCausalLM`
346
  - `GPTNeoXForCausalLM`
347
  - `GPTJForCausalLM`
348
- - `BloomForCausalLM`
349
- - `OPTForCausalLM`
350
 
351
  Conversion to a Prefix LM is done by modifying the `forward` method, and possibly also the
352
  `generate` method and/or select underlying methods depending on the model class.
@@ -396,10 +160,6 @@ def convert_hf_causal_lm_to_prefix_lm(model: CAUSAL_LM_TYPES) -> CAUSAL_LM_TYPES
396
  """
397
  if isinstance(model, _SUPPORTED_GPT_MODELS):
398
  return _convert_gpt_causal_lm_to_prefix_lm(model)
399
- elif isinstance(model, BloomForCausalLM):
400
- return _convert_bloom_causal_lm_to_prefix_lm(model)
401
- elif isinstance(model, OPTForCausalLM):
402
- return _convert_opt_causal_lm_to_prefix_lm(model)
403
  else:
404
  raise TypeError(f'Cannot convert model to Prefix LM. ' + f'Model does not belong to set of supported HF models:' + f'\n{_SUPPORTED_HF_MODELS}')
405
 
 
6
  Prefix LMs accepts a `bidirectional_mask` input in `forward`
7
  and treat the input prompt as the prefix in `generate`.
8
  """
 
 
9
  from types import MethodType
10
  from typing import Any, List, MutableMapping, Optional, Tuple, Union
11
  import torch
 
 
 
 
12
  from transformers.models.gpt2.modeling_gpt2 import GPT2LMHeadModel
13
  from transformers.models.gpt_neo.modeling_gpt_neo import GPTNeoForCausalLM
14
  from transformers.models.gpt_neox.modeling_gpt_neox import GPTNeoXForCausalLM
15
  from transformers.models.gptj.modeling_gptj import GPTJForCausalLM
 
 
 
 
16
  _SUPPORTED_GPT_MODELS = (GPT2LMHeadModel, GPTJForCausalLM, GPTNeoForCausalLM, GPTNeoXForCausalLM)
17
  CAUSAL_GPT_TYPES = Union[GPT2LMHeadModel, GPTJForCausalLM, GPTNeoForCausalLM, GPTNeoXForCausalLM]
18
 
 
100
  setattr(model, 'generate', MethodType(generate, model))
101
  setattr(model, '_prefix_lm_converted', True)
102
  return model
103
+ _SUPPORTED_HF_MODELS = _SUPPORTED_GPT_MODELS
104
+ CAUSAL_LM_TYPES = Union[GPT2LMHeadModel, GPTJForCausalLM, GPTNeoForCausalLM, GPTNeoXForCausalLM]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
105
 
106
  def convert_hf_causal_lm_to_prefix_lm(model: CAUSAL_LM_TYPES) -> CAUSAL_LM_TYPES:
107
  """Converts a HuggingFace Causal LM to a Prefix LM.
 
111
  - `GPTNeoForCausalLM`
112
  - `GPTNeoXForCausalLM`
113
  - `GPTJForCausalLM`
 
 
114
 
115
  Conversion to a Prefix LM is done by modifying the `forward` method, and possibly also the
116
  `generate` method and/or select underlying methods depending on the model class.
 
160
  """
161
  if isinstance(model, _SUPPORTED_GPT_MODELS):
162
  return _convert_gpt_causal_lm_to_prefix_lm(model)
 
 
 
 
163
  else:
164
  raise TypeError(f'Cannot convert model to Prefix LM. ' + f'Model does not belong to set of supported HF models:' + f'\n{_SUPPORTED_HF_MODELS}')
165
 
modeling_mpt.py CHANGED
@@ -8,9 +8,18 @@ from typing import Any, Dict, List, Mapping, MutableMapping, Optional, Tuple, Un
8
  import torch
9
  import torch.nn as nn
10
  import torch.nn.functional as F
 
 
 
 
 
 
11
  from transformers import PreTrainedModel, PreTrainedTokenizerBase
12
  from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
13
- from .attention import attn_bias_shape, build_attn_bias
 
 
 
14
  from .blocks import MPTBlock
15
  from .custom_embedding import SharedEmbedding
16
  from .fc import FC_CLASS_REGISTRY as FC_CLASS_REGISTRY
@@ -30,6 +39,96 @@ except:
30
  import logging
31
  log = logging.getLogger(__name__)
32
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33
  class MPTPreTrainedModel(PreTrainedModel):
34
  config_class = MPTConfig
35
  base_model_prefix = 'model'
@@ -62,6 +161,11 @@ class MPTModel(MPTPreTrainedModel):
62
  self.emb_drop = nn.Dropout(config.emb_pdrop)
63
  self.blocks = nn.ModuleList([MPTBlock(device=config.init_device, **config.to_dict()) for _ in range(config.n_layers)])
64
  self.norm_f = norm_class(config.d_model, device=config.init_device)
 
 
 
 
 
65
  if config.init_device != 'meta':
66
  log.info(f'We recommend using config.init_device="meta" with Composer + FSDP for faster initialization.')
67
  self.apply(self.param_init_fn)
@@ -74,13 +178,16 @@ class MPTModel(MPTPreTrainedModel):
74
  if hasattr(module, 'bias') and isinstance(module.bias, nn.Parameter):
75
  log.info(f'Removing bias ({module.bias}) from {module}.')
76
  module.register_parameter('bias', None)
 
 
 
77
  log.debug(self)
78
  log.debug(f"Using {self.config.init_config['name']} initialization.")
79
 
80
- def get_input_embeddings(self) -> nn.Embedding:
81
  return self.wte
82
 
83
- def set_input_embeddings(self, value: nn.Embedding) -> None:
84
  self.wte = value
85
 
86
  @torch.no_grad()
@@ -101,7 +208,7 @@ class MPTModel(MPTPreTrainedModel):
101
  attn_bias = self._apply_prefix_mask(attn_bias, prefix_mask)
102
  if self.attn_uses_sequence_id and sequence_id is not None:
103
  assert isinstance(attn_bias, torch.Tensor)
104
- attn_bias = self._apply_sequence_id(attn_bias, sequence_id)
105
  if attention_mask is not None:
106
  s_k = attention_mask.shape[-1]
107
  if attn_bias is None:
@@ -113,7 +220,7 @@ class MPTModel(MPTPreTrainedModel):
113
  raise ValueError(f'attention_mask shape={attention_mask.shape} ' + f'and prefix_mask shape={prefix_mask.shape} are not equal.')
114
  min_val = torch.finfo(attn_bias.dtype).min
115
  attn_bias = attn_bias.masked_fill(~attention_mask.view(-1, 1, 1, s_k), min_val)
116
- return (attn_bias, None)
117
 
118
  def _apply_prefix_mask(self, attn_bias: torch.Tensor, prefix_mask: torch.Tensor) -> torch.Tensor:
119
  (s_k, s_q) = attn_bias.shape[-2:]
@@ -130,17 +237,7 @@ class MPTModel(MPTPreTrainedModel):
130
  attn_bias = attn_bias.masked_fill(cannot_attend, min_val)
131
  return attn_bias
132
 
133
- def _apply_sequence_id(self, attn_bias: torch.Tensor, sequence_id: torch.LongTensor) -> torch.Tensor:
134
- seq_len = sequence_id.shape[-1]
135
- if seq_len > self.config.max_seq_len:
136
- raise ValueError(f'sequence_id sequence length cannot exceed max_seq_len={self.config.max_seq_len}')
137
- attn_bias = attn_bias[..., :seq_len, :seq_len]
138
- cannot_attend = torch.logical_not(torch.eq(sequence_id.view(-1, seq_len, 1), sequence_id.view(-1, 1, seq_len))).unsqueeze(1)
139
- min_val = torch.finfo(attn_bias.dtype).min
140
- attn_bias = attn_bias.masked_fill(cannot_attend, min_val)
141
- return attn_bias
142
-
143
- def forward(self, input_ids: torch.LongTensor, past_key_values: Optional[List[Tuple[torch.FloatTensor]]]=None, attention_mask: Optional[torch.ByteTensor]=None, prefix_mask: Optional[torch.ByteTensor]=None, sequence_id: Optional[torch.LongTensor]=None, return_dict: Optional[bool]=None, output_attentions: Optional[bool]=None, output_hidden_states: Optional[bool]=None, use_cache: Optional[bool]=None, inputs_embeds: Optional[torch.Tensor]=None) -> BaseModelOutputWithPast:
144
  return_dict = return_dict if return_dict is not None else self.config.return_dict
145
  use_cache = use_cache if use_cache is not None else self.config.use_cache
146
  if attention_mask is not None:
@@ -156,17 +253,26 @@ class MPTModel(MPTPreTrainedModel):
156
  raise NotImplementedError('MPT does not support training with left padding.')
157
  if self.prefix_lm and prefix_mask is None:
158
  raise ValueError('prefix_mask is a required argument when MPT is configured with prefix_lm=True.')
159
- if inputs_embeds is not None:
160
- raise NotImplementedError('inputs_embeds is not implemented for MPT.')
161
  if self.training:
162
  if self.attn_uses_sequence_id and sequence_id is None:
163
  raise ValueError('sequence_id is a required argument when MPT is configured with attn_uses_sequence_id=True ' + 'and the model is in train mode.')
164
  elif self.attn_uses_sequence_id is False and sequence_id is not None:
165
  warnings.warn('MPT received non-None input for `sequence_id` but is configured with attn_uses_sequence_id=False. ' + 'This input will be ignored. If you want the model to use `sequence_id`, set attn_uses_sequence_id to True.')
166
- S = input_ids.size(1)
 
 
 
 
 
 
 
 
 
 
 
167
  assert S <= self.config.max_seq_len, f'Cannot forward input with seq_len={S}, this model only supports seq_len<={self.config.max_seq_len}'
168
- tok_emb = self.wte(input_ids)
169
- if self.learned_pos_emb:
170
  past_position = 0
171
  if past_key_values is not None:
172
  if len(past_key_values) != self.config.n_layers:
@@ -174,15 +280,18 @@ class MPTModel(MPTPreTrainedModel):
174
  past_position = past_key_values[0][0].size(1)
175
  if self.attn_impl == 'torch':
176
  past_position = past_key_values[0][0].size(3)
177
- if S + past_position > self.config.max_seq_len:
178
  raise ValueError(f'Cannot forward input with past sequence length {past_position} and current sequence length ' + f'{S + 1}, this model only supports total sequence length <= {self.config.max_seq_len}.')
179
- pos = torch.arange(past_position, S + past_position, dtype=torch.long, device=input_ids.device).unsqueeze(0)
180
- if attention_mask is not None:
181
- pos = torch.clamp(pos - torch.cumsum((~attention_mask).to(torch.int32), dim=1)[:, past_position:], min=0)
182
- pos_emb = self.wpe(pos)
183
- x = tok_emb + pos_emb
184
- else:
185
- x = tok_emb
 
 
 
186
  if self.embedding_fraction == 1:
187
  x = self.emb_drop(x)
188
  else:
@@ -190,6 +299,11 @@ class MPTModel(MPTPreTrainedModel):
190
  assert isinstance(self.emb_drop, nn.Module)
191
  x = self.emb_drop(x_shrunk)
192
  (attn_bias, attention_mask) = self._attn_bias(device=x.device, dtype=torch.float32, attention_mask=attention_mask, prefix_mask=prefix_mask, sequence_id=sequence_id)
 
 
 
 
 
193
  if use_cache and past_key_values is None:
194
  past_key_values = [() for _ in range(self.config.n_layers)]
195
  all_hidden_states = () if output_hidden_states else None
@@ -199,9 +313,9 @@ class MPTModel(MPTPreTrainedModel):
199
  assert all_hidden_states is not None
200
  all_hidden_states = all_hidden_states + (x,)
201
  past_key_value = past_key_values[b_idx] if past_key_values is not None else None
202
- (x, attn_weights, past_key_value) = block(x, past_key_value=past_key_value, attn_bias=attn_bias, attention_mask=attention_mask, is_causal=self.is_causal)
203
- if past_key_values is not None:
204
- past_key_values[b_idx] = past_key_value
205
  if output_attentions:
206
  assert all_self_attns is not None
207
  all_self_attns = all_self_attns + (attn_weights,)
@@ -209,7 +323,7 @@ class MPTModel(MPTPreTrainedModel):
209
  if output_hidden_states:
210
  assert all_hidden_states is not None
211
  all_hidden_states = all_hidden_states + (x,)
212
- return BaseModelOutputWithPast(last_hidden_state=x, past_key_values=past_key_values, hidden_states=all_hidden_states, attentions=all_self_attns)
213
 
214
  def param_init_fn(self, module: nn.Module) -> None:
215
  init_fn_name = self.config.init_config['name']
@@ -225,10 +339,12 @@ class MPTForCausalLM(MPTPreTrainedModel):
225
 
226
  def __init__(self, config: MPTConfig):
227
  super().__init__(config)
228
- if not config.tie_word_embeddings:
229
- raise ValueError('MPTForCausalLM only supports tied word embeddings')
230
  log.info(f'Instantiating an MPTForCausalLM model from {__file__}')
231
  self.transformer: MPTModel = MPTModel(config)
 
 
 
 
232
  for child in self.transformer.children():
233
  if isinstance(child, torch.nn.ModuleList):
234
  continue
@@ -244,17 +360,28 @@ class MPTForCausalLM(MPTPreTrainedModel):
244
  raise ValueError(f"logit_scale={logit_scale!r} is not recognized as an option; use numeric value or 'inv_sqrt_d_model'.")
245
  self.logit_scale = logit_scale
246
 
247
- def get_input_embeddings(self) -> nn.Embedding:
248
- return self.transformer.wte
249
 
250
  def set_input_embeddings(self, value: Union[SharedEmbedding, nn.Embedding]) -> None:
251
- self.transformer.wte = value
252
 
253
- def get_output_embeddings(self) -> nn.Embedding:
254
- return self.transformer.wte
 
 
255
 
256
- def set_output_embeddings(self, new_embeddings: Union[SharedEmbedding, nn.Embedding]) -> None:
257
- self.transformer.wte = new_embeddings
 
 
 
 
 
 
 
 
 
258
 
259
  def set_decoder(self, decoder: MPTModel) -> None:
260
  self.transformer = decoder
@@ -262,13 +389,16 @@ class MPTForCausalLM(MPTPreTrainedModel):
262
  def get_decoder(self) -> MPTModel:
263
  return self.transformer
264
 
265
- def forward(self, input_ids: torch.LongTensor, past_key_values: Optional[List[Tuple[torch.FloatTensor]]]=None, attention_mask: Optional[torch.ByteTensor]=None, prefix_mask: Optional[torch.ByteTensor]=None, sequence_id: Optional[torch.LongTensor]=None, labels: Optional[torch.LongTensor]=None, return_dict: Optional[bool]=None, output_attentions: Optional[bool]=None, output_hidden_states: Optional[bool]=None, use_cache: Optional[bool]=None, inputs_embeds: Optional[torch.FloatTensor]=None) -> CausalLMOutputWithPast:
266
  return_dict = return_dict if return_dict is not None else self.config.return_dict
267
  use_cache = use_cache if use_cache is not None else self.config.use_cache
268
- if inputs_embeds is not None:
269
- raise NotImplementedError('inputs_embeds has to be None (for hf/peft support).')
270
- outputs = self.transformer(input_ids=input_ids, past_key_values=past_key_values, attention_mask=attention_mask, prefix_mask=prefix_mask, sequence_id=sequence_id, return_dict=return_dict, output_attentions=output_attentions, output_hidden_states=output_hidden_states, use_cache=use_cache)
271
- logits = self.transformer.wte(outputs.last_hidden_state.to(self.transformer.wte.weight.device), True)
 
 
 
272
  if self.logit_scale is not None:
273
  if self.logit_scale == 0:
274
  warnings.warn(f'Multiplying logits by self.logit_scale={self.logit_scale!r}. This will produce uniform (uninformative) outputs.')
@@ -288,11 +418,31 @@ class MPTForCausalLM(MPTPreTrainedModel):
288
  return isinstance(module, MPTBlock)
289
 
290
  def activation_checkpointing_fn(self, module: nn.Module) -> bool:
291
- return isinstance(module, MPTBlock)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
292
 
293
  def prepare_inputs_for_generation(self, input_ids: torch.Tensor, past_key_values: Optional[List[Tuple[torch.Tensor, torch.Tensor]]]=None, inputs_embeds: Optional[torch.Tensor]=None, **kwargs: Any) -> Dict[str, Any]:
294
- if inputs_embeds is not None:
295
- raise NotImplementedError('inputs_embeds is not implemented for MPT yet')
296
  attention_mask = kwargs['attention_mask'].bool()
297
  if attention_mask[:, -1].sum() != attention_mask.shape[0]:
298
  raise NotImplementedError('MPT does not support generation with right padding.')
@@ -308,7 +458,12 @@ class MPTForCausalLM(MPTPreTrainedModel):
308
  raise NotImplementedError('MPT with prefix_lm=True does not support use_cache=False.')
309
  else:
310
  prefix_mask = None
311
- return {'input_ids': input_ids, 'attention_mask': attention_mask, 'prefix_mask': prefix_mask, 'sequence_id': sequence_id, 'past_key_values': past_key_values, 'use_cache': kwargs.get('use_cache', True)}
 
 
 
 
 
312
 
313
  @staticmethod
314
  def _reorder_cache(past_key_values: List[Tuple[torch.Tensor, torch.Tensor]], beam_idx: torch.LongTensor) -> List[Tuple[torch.Tensor, ...]]:
 
8
  import torch
9
  import torch.nn as nn
10
  import torch.nn.functional as F
11
+ from .attention import is_flash_v2_installed
12
+ if is_flash_v2_installed():
13
+ try:
14
+ from flash_attn.layers.rotary import RotaryEmbedding as DAILRotaryEmbedding
15
+ except Exception as e:
16
+ raise e
17
  from transformers import PreTrainedModel, PreTrainedTokenizerBase
18
  from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
19
+ from transformers.models.llama.modeling_llama import LlamaDynamicNTKScalingRotaryEmbedding as HFDynamicNTKScalingRotaryEmbedding
20
+ from transformers.models.llama.modeling_llama import LlamaLinearScalingRotaryEmbedding as HFLinearScalingRotaryEmbedding
21
+ from transformers.models.llama.modeling_llama import LlamaRotaryEmbedding as HFRotaryEmbedding
22
+ from .attention import ATTN_CLASS_REGISTRY, attn_bias_shape, build_attn_bias, gen_slopes
23
  from .blocks import MPTBlock
24
  from .custom_embedding import SharedEmbedding
25
  from .fc import FC_CLASS_REGISTRY as FC_CLASS_REGISTRY
 
39
  import logging
40
  log = logging.getLogger(__name__)
41
 
42
+ def gen_rotary_embedding(rope_head_dim: int, rope_impl: str, rope_theta: int, rope_dail_config: dict, rope_hf_config: dict, max_seq_len: int):
43
+ if rope_impl == 'dail':
44
+ return DAILRotaryEmbedding(dim=rope_head_dim, base=rope_theta, interleaved=False, scale_base=rope_dail_config['xpos_scale_base'] if rope_dail_config['type'] == 'xpos' else None, pos_idx_in_fp32=rope_dail_config['pos_idx_in_fp32'], device='cpu')
45
+ elif rope_impl == 'hf':
46
+ if rope_hf_config['type'] == 'no_scaling':
47
+ return HFRotaryEmbedding(rope_head_dim, max_position_embeddings=max_seq_len, base=rope_theta, device='cpu')
48
+ elif rope_hf_config['type'] == 'linear':
49
+ return HFLinearScalingRotaryEmbedding(rope_head_dim, max_position_embeddings=max_seq_len, base=rope_theta, scaling_factor=rope_hf_config['factor'], device='cpu')
50
+ elif rope_hf_config['type'] == 'dynamic':
51
+ return HFDynamicNTKScalingRotaryEmbedding(rope_head_dim, max_position_embeddings=max_seq_len, base=rope_theta, scaling_factor=rope_hf_config['factor'], device='cpu')
52
+ raise ValueError('rope_impl needs to be either dail or hf')
53
+
54
+ def gen_attention_mask_in_length(sequence_id: Union[None, torch.Tensor], S: int, attn_uses_sequence_id: bool, attn_impl: str, attention_mask: Union[torch.Tensor, None]):
55
+ """Generates the attention mask used for sequence masking in FA v2.
56
+
57
+ Only supports sequence id based sparse attention for no attention masking or attention masking with right padding.
58
+ In case of left padding:
59
+ 1. Training with left padding is not supported in MPT (see https://github.com/mosaicml/llm-foundry/blob/1eecd4cb8e734499f77f6a35f657b8b20c0adfcb/llmfoundry/models/mpt/modeling_mpt.py#L407).
60
+ 2. For generation with left padding, we only have a single sequence id per sample, so we don't need sequence id based sparse attention.
61
+
62
+ Args:
63
+ sequence_id (Union[None, torch.Tensor]): Tensor containing the sequence id for each token. Shape (batch_size, seq_len).
64
+ S (int): Sequence length
65
+ attn_uses_sequence_id (bool): Whether the attention uses sequence id based masking.
66
+ attn_impl (str): Attention implementation. This function is only creates attention_mask_in_length for flash attention.
67
+ attention_mask (Union[torch.Tensor, None]): Attention mask tensor of shape (batch_size, seq_len)
68
+
69
+ Returns:
70
+ attention_mask_in_length: (batch, seqlen), int, a nonzero number (e.g., 1, 2, 3, etc.) means length of concatenated sequence in b-th batch, and 0 means none. For example, if batch = 3 and seqlen = 6, the attention_mask_in_length is:
71
+ ```
72
+ [
73
+ [2, 3, 0, 0, 0, 0],
74
+ [3, 2, 0, 0, 0, 0],
75
+ [6, 0, 0, 0, 0, 0]
76
+ ]
77
+ ```
78
+ , which refers to the 3D-attention mask:
79
+ ```
80
+ [
81
+ [
82
+ [1, 0, 0, 0, 0, 0],
83
+ [1, 1, 0, 0, 0, 0],
84
+ [0, 0, 1, 0, 0, 0],
85
+ [0, 0, 1, 1, 0, 0],
86
+ [0, 0, 1, 1, 1, 0],
87
+ [0, 0, 0, 0, 0, 1]
88
+ ],
89
+ [
90
+ [1, 0, 0, 0, 0, 0],
91
+ [1, 1, 0, 0, 0, 0],
92
+ [1, 1, 1, 0, 0, 0],
93
+ [0, 0, 0, 1, 0, 0],
94
+ [0, 0, 0, 1, 1, 0],
95
+ [0, 0, 0, 0, 0, 1]
96
+ ],
97
+ [
98
+ [1, 0, 0, 0, 0, 0],
99
+ [1, 1, 0, 0, 0, 0],
100
+ [1, 1, 1, 0, 0, 0],
101
+ [1, 1, 1, 1, 0, 0],
102
+ [1, 1, 1, 1, 1, 0],
103
+ [1, 1, 1, 1, 1, 1]
104
+ ]
105
+ ]
106
+ ```.
107
+ (The description above is taken verbatim from https://github.com/Dao-AILab/flash-attention/blob/9356a1c0389660d7e231ff3163c1ac17d9e3824a/flash_attn/bert_padding.py#L125 .)
108
+ """
109
+ attention_mask_in_length = None
110
+ if sequence_id is not None and attn_uses_sequence_id and (attn_impl == 'flash'):
111
+ if attention_mask is not None and attention_mask[:, 0].sum() != attention_mask.shape[0]:
112
+ raise NotImplementedError('Left padding is not supported with flash attention when attn_uses_sequence_id is set to True.')
113
+ if S != sequence_id.shape[-1]:
114
+ raise ValueError(f'Sequence length ({S}) does not match length of sequences in sequence_id ({sequence_id.shape[-1]}).')
115
+ attention_mask_in_length = torch.nn.functional.one_hot(sequence_id)
116
+ if attention_mask is not None:
117
+ attention_mask_in_length = attention_mask_in_length.masked_fill(~attention_mask.unsqueeze(-1), 0)
118
+ attention_mask_in_length = attention_mask_in_length.sum(dim=1)
119
+ attention_mask_in_length = torch.nn.functional.pad(attention_mask_in_length, (0, S - attention_mask_in_length.shape[-1]), mode='constant', value=0)
120
+ return attention_mask_in_length
121
+
122
+ def apply_sequence_id(attn_bias: torch.Tensor, sequence_id: torch.LongTensor, max_seq_len: int) -> torch.Tensor:
123
+ seq_len = sequence_id.shape[-1]
124
+ if seq_len > max_seq_len:
125
+ raise ValueError(f'sequence_id sequence length cannot exceed max_seq_len={max_seq_len}')
126
+ attn_bias = attn_bias[..., :seq_len, :seq_len]
127
+ cannot_attend = torch.logical_not(torch.eq(sequence_id.view(-1, seq_len, 1), sequence_id.view(-1, 1, seq_len))).unsqueeze(1)
128
+ min_val = torch.finfo(attn_bias.dtype).min
129
+ attn_bias = attn_bias.masked_fill(cannot_attend, min_val)
130
+ return attn_bias
131
+
132
  class MPTPreTrainedModel(PreTrainedModel):
133
  config_class = MPTConfig
134
  base_model_prefix = 'model'
 
161
  self.emb_drop = nn.Dropout(config.emb_pdrop)
162
  self.blocks = nn.ModuleList([MPTBlock(device=config.init_device, **config.to_dict()) for _ in range(config.n_layers)])
163
  self.norm_f = norm_class(config.d_model, device=config.init_device)
164
+ self.rope = config.attn_config['rope']
165
+ self.rope_impl = None
166
+ if self.rope:
167
+ self.rope_impl = config.attn_config['rope_impl']
168
+ self.rotary_embedding = gen_rotary_embedding(rope_head_dim=config.d_model // config.n_heads, rope_impl=self.rope_impl, rope_theta=config.attn_config['rope_theta'], rope_dail_config=config.attn_config['rope_dail_config'], rope_hf_config=config.attn_config['rope_hf_config'], max_seq_len=self.config.max_seq_len)
169
  if config.init_device != 'meta':
170
  log.info(f'We recommend using config.init_device="meta" with Composer + FSDP for faster initialization.')
171
  self.apply(self.param_init_fn)
 
178
  if hasattr(module, 'bias') and isinstance(module.bias, nn.Parameter):
179
  log.info(f'Removing bias ({module.bias}) from {module}.')
180
  module.register_parameter('bias', None)
181
+ if hasattr(module, 'use_bias'):
182
+ log.info(f'Setting use_bias=False for {module}.')
183
+ module.use_bias = False
184
  log.debug(self)
185
  log.debug(f"Using {self.config.init_config['name']} initialization.")
186
 
187
+ def get_input_embeddings(self) -> Union[SharedEmbedding, nn.Embedding]:
188
  return self.wte
189
 
190
+ def set_input_embeddings(self, value: Union[SharedEmbedding, nn.Embedding]) -> None:
191
  self.wte = value
192
 
193
  @torch.no_grad()
 
208
  attn_bias = self._apply_prefix_mask(attn_bias, prefix_mask)
209
  if self.attn_uses_sequence_id and sequence_id is not None:
210
  assert isinstance(attn_bias, torch.Tensor)
211
+ attn_bias = apply_sequence_id(attn_bias, sequence_id, self.config.max_seq_len)
212
  if attention_mask is not None:
213
  s_k = attention_mask.shape[-1]
214
  if attn_bias is None:
 
220
  raise ValueError(f'attention_mask shape={attention_mask.shape} ' + f'and prefix_mask shape={prefix_mask.shape} are not equal.')
221
  min_val = torch.finfo(attn_bias.dtype).min
222
  attn_bias = attn_bias.masked_fill(~attention_mask.view(-1, 1, 1, s_k), min_val)
223
+ return (attn_bias, attention_mask)
224
 
225
  def _apply_prefix_mask(self, attn_bias: torch.Tensor, prefix_mask: torch.Tensor) -> torch.Tensor:
226
  (s_k, s_q) = attn_bias.shape[-2:]
 
237
  attn_bias = attn_bias.masked_fill(cannot_attend, min_val)
238
  return attn_bias
239
 
240
+ def forward(self, input_ids: Optional[torch.LongTensor]=None, past_key_values: Optional[List[Tuple[torch.FloatTensor]]]=None, attention_mask: Optional[torch.ByteTensor]=None, prefix_mask: Optional[torch.ByteTensor]=None, sequence_id: Optional[torch.LongTensor]=None, return_dict: Optional[bool]=None, output_attentions: Optional[bool]=None, output_hidden_states: Optional[bool]=None, use_cache: Optional[bool]=None, inputs_embeds: Optional[torch.Tensor]=None) -> BaseModelOutputWithPast:
 
 
 
 
 
 
 
 
 
 
241
  return_dict = return_dict if return_dict is not None else self.config.return_dict
242
  use_cache = use_cache if use_cache is not None else self.config.use_cache
243
  if attention_mask is not None:
 
253
  raise NotImplementedError('MPT does not support training with left padding.')
254
  if self.prefix_lm and prefix_mask is None:
255
  raise ValueError('prefix_mask is a required argument when MPT is configured with prefix_lm=True.')
 
 
256
  if self.training:
257
  if self.attn_uses_sequence_id and sequence_id is None:
258
  raise ValueError('sequence_id is a required argument when MPT is configured with attn_uses_sequence_id=True ' + 'and the model is in train mode.')
259
  elif self.attn_uses_sequence_id is False and sequence_id is not None:
260
  warnings.warn('MPT received non-None input for `sequence_id` but is configured with attn_uses_sequence_id=False. ' + 'This input will be ignored. If you want the model to use `sequence_id`, set attn_uses_sequence_id to True.')
261
+ if input_ids is not None and inputs_embeds is not None:
262
+ raise ValueError('You cannot specify both input_ids and inputs_embeds.')
263
+ elif input_ids is not None:
264
+ S = input_ids.size(1)
265
+ x = self.wte(input_ids)
266
+ input_device = input_ids.device
267
+ elif inputs_embeds is not None:
268
+ S = inputs_embeds.size(1)
269
+ x = inputs_embeds
270
+ input_device = inputs_embeds.device
271
+ else:
272
+ raise ValueError('You must specify input_ids or inputs_embeds')
273
  assert S <= self.config.max_seq_len, f'Cannot forward input with seq_len={S}, this model only supports seq_len<={self.config.max_seq_len}'
274
+ rotary_emb_w_meta_info = None
275
+ if self.learned_pos_emb or self.rope:
276
  past_position = 0
277
  if past_key_values is not None:
278
  if len(past_key_values) != self.config.n_layers:
 
280
  past_position = past_key_values[0][0].size(1)
281
  if self.attn_impl == 'torch':
282
  past_position = past_key_values[0][0].size(3)
283
+ if self.learned_pos_emb and S + past_position > self.config.max_seq_len:
284
  raise ValueError(f'Cannot forward input with past sequence length {past_position} and current sequence length ' + f'{S + 1}, this model only supports total sequence length <= {self.config.max_seq_len}.')
285
+ if self.learned_pos_emb or (self.rope and self.rope_impl == 'hf'):
286
+ pos = torch.arange(past_position, S + past_position, dtype=torch.long, device=input_device).unsqueeze(0)
287
+ if attention_mask is not None:
288
+ pos = torch.clamp(pos - torch.cumsum((~attention_mask).to(torch.int32), dim=1)[:, past_position:], min=0)
289
+ if self.learned_pos_emb:
290
+ x = x + self.wpe(pos)
291
+ elif self.rope and self.rope_impl == 'hf':
292
+ rotary_emb_w_meta_info = {'impl': self.rope_impl, 'rotary_emb': self.rotary_embedding, 'offset_info': pos, 'seq_len': S + past_position}
293
+ elif self.rope and self.rope_impl == 'dail':
294
+ rotary_emb_w_meta_info = {'impl': self.rope_impl, 'rotary_emb': self.rotary_embedding, 'offset_info': past_position, 'seq_len': S + past_position}
295
  if self.embedding_fraction == 1:
296
  x = self.emb_drop(x)
297
  else:
 
299
  assert isinstance(self.emb_drop, nn.Module)
300
  x = self.emb_drop(x_shrunk)
301
  (attn_bias, attention_mask) = self._attn_bias(device=x.device, dtype=torch.float32, attention_mask=attention_mask, prefix_mask=prefix_mask, sequence_id=sequence_id)
302
+ attention_mask_in_length = gen_attention_mask_in_length(sequence_id=sequence_id, S=S, attn_uses_sequence_id=self.attn_uses_sequence_id, attn_impl=self.attn_impl, attention_mask=attention_mask)
303
+ alibi_slopes = None
304
+ if self.alibi and self.attn_impl == 'flash':
305
+ alibi_slopes = gen_slopes(n_heads=self.config.n_heads, alibi_bias_max=self.alibi_bias_max, device=x.device, return_1d=True)
306
+ presents = () if use_cache else None
307
  if use_cache and past_key_values is None:
308
  past_key_values = [() for _ in range(self.config.n_layers)]
309
  all_hidden_states = () if output_hidden_states else None
 
313
  assert all_hidden_states is not None
314
  all_hidden_states = all_hidden_states + (x,)
315
  past_key_value = past_key_values[b_idx] if past_key_values is not None else None
316
+ (x, attn_weights, present) = block(x, past_key_value=past_key_value, attn_bias=attn_bias, rotary_emb_w_meta_info=rotary_emb_w_meta_info, attention_mask=attention_mask, is_causal=self.is_causal, output_attentions=bool(output_attentions), attention_mask_in_length=attention_mask_in_length, alibi_slopes=alibi_slopes)
317
+ if presents is not None:
318
+ presents += (present,)
319
  if output_attentions:
320
  assert all_self_attns is not None
321
  all_self_attns = all_self_attns + (attn_weights,)
 
323
  if output_hidden_states:
324
  assert all_hidden_states is not None
325
  all_hidden_states = all_hidden_states + (x,)
326
+ return BaseModelOutputWithPast(last_hidden_state=x, past_key_values=presents, hidden_states=all_hidden_states, attentions=all_self_attns)
327
 
328
  def param_init_fn(self, module: nn.Module) -> None:
329
  init_fn_name = self.config.init_config['name']
 
339
 
340
  def __init__(self, config: MPTConfig):
341
  super().__init__(config)
 
 
342
  log.info(f'Instantiating an MPTForCausalLM model from {__file__}')
343
  self.transformer: MPTModel = MPTModel(config)
344
+ self.lm_head = None
345
+ if not config.tie_word_embeddings:
346
+ self.lm_head = nn.Linear(config.d_model, config.vocab_size, bias=False, device=config.init_device)
347
+ self.lm_head._fsdp_wrap = True
348
  for child in self.transformer.children():
349
  if isinstance(child, torch.nn.ModuleList):
350
  continue
 
360
  raise ValueError(f"logit_scale={logit_scale!r} is not recognized as an option; use numeric value or 'inv_sqrt_d_model'.")
361
  self.logit_scale = logit_scale
362
 
363
+ def get_input_embeddings(self) -> Union[SharedEmbedding, nn.Embedding]:
364
+ return self.transformer.get_input_embeddings()
365
 
366
  def set_input_embeddings(self, value: Union[SharedEmbedding, nn.Embedding]) -> None:
367
+ self.transformer.set_input_embeddings(value)
368
 
369
+ def get_output_embeddings(self) -> Union[SharedEmbedding, nn.Embedding, nn.Linear]:
370
+ if self.lm_head is not None:
371
+ return self.lm_head
372
+ return self.transformer.get_input_embeddings()
373
 
374
+ def set_output_embeddings(self, new_embeddings: Union[SharedEmbedding, nn.Embedding, nn.Linear]) -> None:
375
+ if self.lm_head is not None:
376
+ self.lm_head = new_embeddings
377
+ else:
378
+ if not isinstance(new_embeddings, (SharedEmbedding, nn.Embedding)):
379
+ raise ValueError('new_embeddings must be an instance of SharedEmbedding ' + f'or nn.Embedding, but got {type(new_embeddings)}.')
380
+ warnings.warn('Using `set_output_embeddings` to set the embedding layer of ' + 'MPTForCausalLM with tied weights. Given weights are tied, ' + 'using `set_input_embeddings` is recommended over using ' + '`set_output_embeddings`.')
381
+ self.transformer.set_input_embeddings(new_embeddings)
382
+
383
+ def tie_weights(self) -> None:
384
+ self.lm_head = None
385
 
386
  def set_decoder(self, decoder: MPTModel) -> None:
387
  self.transformer = decoder
 
389
  def get_decoder(self) -> MPTModel:
390
  return self.transformer
391
 
392
+ def forward(self, input_ids: Optional[torch.LongTensor]=None, past_key_values: Optional[List[Tuple[torch.FloatTensor]]]=None, attention_mask: Optional[torch.ByteTensor]=None, prefix_mask: Optional[torch.ByteTensor]=None, sequence_id: Optional[torch.LongTensor]=None, labels: Optional[torch.LongTensor]=None, return_dict: Optional[bool]=None, output_attentions: Optional[bool]=None, output_hidden_states: Optional[bool]=None, use_cache: Optional[bool]=None, inputs_embeds: Optional[torch.FloatTensor]=None) -> CausalLMOutputWithPast:
393
  return_dict = return_dict if return_dict is not None else self.config.return_dict
394
  use_cache = use_cache if use_cache is not None else self.config.use_cache
395
+ outputs = self.transformer(input_ids=input_ids, past_key_values=past_key_values, attention_mask=attention_mask, prefix_mask=prefix_mask, sequence_id=sequence_id, return_dict=return_dict, output_attentions=output_attentions, output_hidden_states=output_hidden_states, use_cache=use_cache, inputs_embeds=inputs_embeds)
396
+ if self.lm_head is not None:
397
+ logits = self.lm_head(outputs.last_hidden_state)
398
+ else:
399
+ out = outputs.last_hidden_state
400
+ out = out.to(self.transformer.wte.weight.device)
401
+ logits = self.transformer.wte(out, True)
402
  if self.logit_scale is not None:
403
  if self.logit_scale == 0:
404
  warnings.warn(f'Multiplying logits by self.logit_scale={self.logit_scale!r}. This will produce uniform (uninformative) outputs.')
 
418
  return isinstance(module, MPTBlock)
419
 
420
  def activation_checkpointing_fn(self, module: nn.Module) -> bool:
421
+ act_ckpt_list = getattr(self.config, 'activation_checkpointing_target', None) or ['MPTBlock']
422
+ if isinstance(act_ckpt_list, str):
423
+ act_ckpt_list = [act_ckpt_list]
424
+ elif not isinstance(act_ckpt_list, list):
425
+ raise ValueError(f'activation_checkpointing_target must be either a single string or a list, but got {type(act_ckpt_list)}')
426
+ if 'MPTBlock' in act_ckpt_list or 'mptblock' in act_ckpt_list:
427
+ if len(act_ckpt_list) > 1:
428
+ log.info('Activation checkpointing MPTBlock only (ignoring other sub-block modules specified in activation_checkpointing_target).')
429
+ return isinstance(module, MPTBlock)
430
+ mod_types = ()
431
+ for mod_name in act_ckpt_list:
432
+ if mod_name.lower() == 'mptblock':
433
+ mod_types += (MPTBlock,)
434
+ elif mod_name in ATTN_CLASS_REGISTRY:
435
+ mod_types += (ATTN_CLASS_REGISTRY[mod_name],)
436
+ elif mod_name in FFN_CLASS_REGISTRY:
437
+ mod_types += (FFN_CLASS_REGISTRY[mod_name],)
438
+ elif mod_name in NORM_CLASS_REGISTRY:
439
+ mod_types += (NORM_CLASS_REGISTRY[mod_name],)
440
+ else:
441
+ msg = ', '.join(list(ATTN_CLASS_REGISTRY.keys()) + list(FFN_CLASS_REGISTRY.keys()) + list(NORM_CLASS_REGISTRY.keys()) + ['MPTBlock'])
442
+ raise ValueError(f'{mod_name} (specified in activation_checkpointing_target) is not a recognized option out of available options {msg}.')
443
+ return isinstance(module, mod_types)
444
 
445
  def prepare_inputs_for_generation(self, input_ids: torch.Tensor, past_key_values: Optional[List[Tuple[torch.Tensor, torch.Tensor]]]=None, inputs_embeds: Optional[torch.Tensor]=None, **kwargs: Any) -> Dict[str, Any]:
 
 
446
  attention_mask = kwargs['attention_mask'].bool()
447
  if attention_mask[:, -1].sum() != attention_mask.shape[0]:
448
  raise NotImplementedError('MPT does not support generation with right padding.')
 
458
  raise NotImplementedError('MPT with prefix_lm=True does not support use_cache=False.')
459
  else:
460
  prefix_mask = None
461
+ if inputs_embeds is not None and past_key_values is None:
462
+ model_inputs = {'inputs_embeds': inputs_embeds}
463
+ else:
464
+ model_inputs = {'input_ids': input_ids}
465
+ model_inputs.update({'attention_mask': attention_mask, 'prefix_mask': prefix_mask, 'sequence_id': sequence_id, 'past_key_values': past_key_values, 'use_cache': kwargs.get('use_cache', True)})
466
+ return model_inputs
467
 
468
  @staticmethod
469
  def _reorder_cache(past_key_values: List[Tuple[torch.Tensor, torch.Tensor]], beam_idx: torch.LongTensor) -> List[Tuple[torch.Tensor, ...]]: