Mentors4EDU commited on
Commit
ec3e3c1
·
verified ·
1 Parent(s): 9a031c4

Declare _no_split_modules so device_map='auto' can shard the model across GPUs

Browse files
modeling_riemann.py CHANGED
@@ -1,244 +1,245 @@
1
- from __future__ import annotations
2
- import math
3
- from typing import Optional
4
- import torch
5
- import torch.nn as nn
6
- import torch.nn.functional as F
7
- import torch.utils.checkpoint
8
- from transformers import GenerationMixin, PreTrainedModel
9
- from transformers.modeling_outputs import CausalLMOutputWithPast
10
- from .configuration_riemann import RiemannConfig
11
-
12
-
13
- class MultiHeadAttention(nn.Module):
14
-
15
- def __init__(self, config: RiemannConfig):
16
- super().__init__()
17
- self.num_heads = config.num_attention_heads
18
- self.hidden_size = config.hidden_size
19
- self.head_size = self.hidden_size // self.num_heads
20
- self.query = nn.Linear(config.hidden_size, config.hidden_size)
21
- self.key = nn.Linear(config.hidden_size, config.hidden_size)
22
- self.value = nn.Linear(config.hidden_size, config.hidden_size)
23
- self.out = nn.Linear(config.hidden_size, config.hidden_size)
24
- self.dropout = nn.Dropout(config.attention_dropout)
25
-
26
- def forward(
27
- self, hidden_states: torch.Tensor, attention_mask: Optional[torch.Tensor] = None
28
- ):
29
- batch_size, seq_length = hidden_states.shape[:2]
30
- query_states = self.query(hidden_states)
31
- key_states = self.key(hidden_states)
32
- value_states = self.value(hidden_states)
33
- query_states = query_states.view(
34
- batch_size, seq_length, self.num_heads, self.head_size
35
- ).transpose(1, 2)
36
- key_states = key_states.view(
37
- batch_size, seq_length, self.num_heads, self.head_size
38
- ).transpose(1, 2)
39
- value_states = value_states.view(
40
- batch_size, seq_length, self.num_heads, self.head_size
41
- ).transpose(1, 2)
42
- use_sdpa = hidden_states.device.type in ("cuda", "cpu")
43
- if use_sdpa:
44
- context_layer = F.scaled_dot_product_attention(
45
- query_states,
46
- key_states,
47
- value_states,
48
- attn_mask=attention_mask,
49
- dropout_p=self.dropout.p if self.training else 0.0,
50
- is_causal=attention_mask is None,
51
- )
52
- else:
53
- attention_scores = torch.matmul(query_states, key_states.transpose(-1, -2))
54
- attention_scores = attention_scores / math.sqrt(self.head_size)
55
- if attention_mask is None:
56
- attention_mask = torch.triu(
57
- torch.full(
58
- (seq_length, seq_length),
59
- torch.finfo(attention_scores.dtype).min,
60
- dtype=attention_scores.dtype,
61
- device=attention_scores.device,
62
- ),
63
- diagonal=1,
64
- )
65
- attention_scores = attention_scores + attention_mask
66
- attention_probs = F.softmax(attention_scores, dim=-1)
67
- attention_probs = self.dropout(attention_probs)
68
- context_layer = torch.matmul(attention_probs, value_states)
69
- context_layer = context_layer.transpose(1, 2).contiguous()
70
- context_layer = context_layer.view(batch_size, seq_length, self.hidden_size)
71
- context_layer = self.out(context_layer)
72
- return context_layer
73
-
74
-
75
- class MLP(nn.Module):
76
-
77
- def __init__(self, config: RiemannConfig):
78
- super().__init__()
79
- self.dense_h_to_4h = nn.Linear(config.hidden_size, config.intermediate_size)
80
- self.dense_4h_to_h = nn.Linear(config.intermediate_size, config.hidden_size)
81
- self.act = nn.GELU()
82
- self.dropout = nn.Dropout(config.hidden_dropout)
83
-
84
- def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
85
- hidden_states = self.dense_h_to_4h(hidden_states)
86
- hidden_states = self.act(hidden_states)
87
- hidden_states = self.dense_4h_to_h(hidden_states)
88
- hidden_states = self.dropout(hidden_states)
89
- return hidden_states
90
-
91
-
92
- class TransformerBlock(nn.Module):
93
-
94
- def __init__(self, config: RiemannConfig):
95
- super().__init__()
96
- self.attention = MultiHeadAttention(config)
97
- self.mlp = MLP(config)
98
- self.input_layernorm = nn.LayerNorm(
99
- config.hidden_size, eps=config.layer_norm_eps
100
- )
101
- self.post_attention_layernorm = nn.LayerNorm(
102
- config.hidden_size, eps=config.layer_norm_eps
103
- )
104
- self.dropout = nn.Dropout(config.hidden_dropout)
105
-
106
- def forward(
107
- self, hidden_states: torch.Tensor, attention_mask: Optional[torch.Tensor] = None
108
- ):
109
- attention_layernorm_out = self.input_layernorm(hidden_states)
110
- attention_output = self.attention(
111
- attention_layernorm_out, attention_mask=attention_mask
112
- )
113
- attention_output = self.dropout(attention_output)
114
- attention_output = attention_output + hidden_states
115
- mlp_layernorm_out = self.post_attention_layernorm(attention_output)
116
- mlp_output = self.mlp(mlp_layernorm_out)
117
- layer_output = mlp_output + attention_output
118
- return layer_output
119
-
120
-
121
- class RiemannPreTrainedModel(PreTrainedModel):
122
- config_class = RiemannConfig
123
- base_model_prefix = "riemann"
124
- supports_gradient_checkpointing = True
125
-
126
- def _init_weights(self, module):
127
- if isinstance(module, nn.Linear):
128
- module.weight.data.normal_(mean=0.0, std=0.02)
129
- if module.bias is not None:
130
- module.bias.data.zero_()
131
- elif isinstance(module, nn.Embedding):
132
- module.weight.data.normal_(mean=0.0, std=0.02)
133
- elif isinstance(module, nn.LayerNorm):
134
- module.bias.data.zero_()
135
- module.weight.data.fill_(1.0)
136
-
137
-
138
- class RiemannForCausalLM(RiemannPreTrainedModel, GenerationMixin):
139
-
140
- def __init__(self, config: RiemannConfig):
141
- super().__init__(config)
142
- self.config = config
143
- self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size)
144
- self.position_embeddings = nn.Embedding(
145
- config.max_position_embeddings, config.hidden_size
146
- )
147
- self.layers = nn.ModuleList(
148
- [TransformerBlock(config) for _ in range(config.num_hidden_layers)]
149
- )
150
- self.final_layernorm = nn.LayerNorm(
151
- config.hidden_size, eps=config.layer_norm_eps
152
- )
153
- self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
154
- self.gradient_checkpointing = False
155
- self.post_init()
156
-
157
- def get_input_embeddings(self):
158
- return self.word_embeddings
159
-
160
- def set_input_embeddings(self, value):
161
- self.word_embeddings = value
162
-
163
- def get_output_embeddings(self):
164
- return self.lm_head
165
-
166
- def set_output_embeddings(self, value):
167
- self.lm_head = value
168
-
169
- def _build_attention_mask(self, input_shape, attention_mask, dtype, device):
170
- batch_size, seq_length = input_shape
171
- causal = torch.triu(
172
- torch.full(
173
- (seq_length, seq_length),
174
- torch.finfo(dtype).min,
175
- dtype=dtype,
176
- device=device,
177
- ),
178
- diagonal=1,
179
- )
180
- causal = causal.unsqueeze(0).unsqueeze(0)
181
- if attention_mask is not None:
182
- padding = attention_mask[:, None, None, :].to(dtype=dtype)
183
- padding = (1.0 - padding) * torch.finfo(dtype).min
184
- return causal + padding
185
- return causal
186
-
187
- def forward(
188
- self,
189
- input_ids: Optional[torch.Tensor] = None,
190
- attention_mask: Optional[torch.Tensor] = None,
191
- inputs_embeds: Optional[torch.Tensor] = None,
192
- labels: Optional[torch.Tensor] = None,
193
- use_cache: Optional[bool] = None,
194
- **kwargs,
195
- ):
196
- if input_ids is not None and inputs_embeds is not None:
197
- raise ValueError("pass either input_ids or inputs_embeds, not both")
198
- if input_ids is not None:
199
- inputs_embeds = self.word_embeddings(input_ids)
200
- batch_size, seq_length = input_ids.shape
201
- elif inputs_embeds is not None:
202
- batch_size, seq_length = inputs_embeds.shape[:2]
203
- else:
204
- raise ValueError("need either input_ids or inputs_embeds")
205
- position_ids = torch.arange(
206
- seq_length, dtype=torch.long, device=inputs_embeds.device
207
- )
208
- position_ids = position_ids.unsqueeze(0).expand(batch_size, -1)
209
- position_embeds = self.position_embeddings(position_ids)
210
- hidden_states = inputs_embeds + position_embeds
211
- full_mask = (
212
- None
213
- if attention_mask is None
214
- else self._build_attention_mask(
215
- (batch_size, seq_length),
216
- attention_mask,
217
- hidden_states.dtype,
218
- hidden_states.device,
219
- )
220
- )
221
- for layer in self.layers:
222
- if self.gradient_checkpointing and self.training:
223
- hidden_states = torch.utils.checkpoint.checkpoint(
224
- layer, hidden_states, full_mask, use_reentrant=False
225
- )
226
- else:
227
- hidden_states = layer(hidden_states, full_mask)
228
- hidden_states = self.final_layernorm(hidden_states)
229
- logits = self.lm_head(hidden_states)
230
- loss = None
231
- if labels is not None:
232
- shift_logits = logits[..., :-1, :].contiguous()
233
- shift_labels = labels[..., 1:].contiguous()
234
- loss = F.cross_entropy(
235
- shift_logits.view(-1, self.config.vocab_size),
236
- shift_labels.view(-1),
237
- ignore_index=-100,
238
- )
239
- return CausalLMOutputWithPast(
240
- loss=loss, logits=logits, hidden_states=hidden_states
241
- )
242
-
243
- def prepare_inputs_for_generation(self, input_ids, **kwargs):
244
- return {"input_ids": input_ids}
 
 
1
+ from __future__ import annotations
2
+ import math
3
+ from typing import Optional
4
+ import torch
5
+ import torch.nn as nn
6
+ import torch.nn.functional as F
7
+ import torch.utils.checkpoint
8
+ from transformers import GenerationMixin, PreTrainedModel
9
+ from transformers.modeling_outputs import CausalLMOutputWithPast
10
+ from .configuration_riemann import RiemannConfig
11
+
12
+
13
+ class MultiHeadAttention(nn.Module):
14
+
15
+ def __init__(self, config: RiemannConfig):
16
+ super().__init__()
17
+ self.num_heads = config.num_attention_heads
18
+ self.hidden_size = config.hidden_size
19
+ self.head_size = self.hidden_size // self.num_heads
20
+ self.query = nn.Linear(config.hidden_size, config.hidden_size)
21
+ self.key = nn.Linear(config.hidden_size, config.hidden_size)
22
+ self.value = nn.Linear(config.hidden_size, config.hidden_size)
23
+ self.out = nn.Linear(config.hidden_size, config.hidden_size)
24
+ self.dropout = nn.Dropout(config.attention_dropout)
25
+
26
+ def forward(
27
+ self, hidden_states: torch.Tensor, attention_mask: Optional[torch.Tensor] = None
28
+ ):
29
+ batch_size, seq_length = hidden_states.shape[:2]
30
+ query_states = self.query(hidden_states)
31
+ key_states = self.key(hidden_states)
32
+ value_states = self.value(hidden_states)
33
+ query_states = query_states.view(
34
+ batch_size, seq_length, self.num_heads, self.head_size
35
+ ).transpose(1, 2)
36
+ key_states = key_states.view(
37
+ batch_size, seq_length, self.num_heads, self.head_size
38
+ ).transpose(1, 2)
39
+ value_states = value_states.view(
40
+ batch_size, seq_length, self.num_heads, self.head_size
41
+ ).transpose(1, 2)
42
+ use_sdpa = hidden_states.device.type in ("cuda", "cpu")
43
+ if use_sdpa:
44
+ context_layer = F.scaled_dot_product_attention(
45
+ query_states,
46
+ key_states,
47
+ value_states,
48
+ attn_mask=attention_mask,
49
+ dropout_p=self.dropout.p if self.training else 0.0,
50
+ is_causal=attention_mask is None,
51
+ )
52
+ else:
53
+ attention_scores = torch.matmul(query_states, key_states.transpose(-1, -2))
54
+ attention_scores = attention_scores / math.sqrt(self.head_size)
55
+ if attention_mask is None:
56
+ attention_mask = torch.triu(
57
+ torch.full(
58
+ (seq_length, seq_length),
59
+ torch.finfo(attention_scores.dtype).min,
60
+ dtype=attention_scores.dtype,
61
+ device=attention_scores.device,
62
+ ),
63
+ diagonal=1,
64
+ )
65
+ attention_scores = attention_scores + attention_mask
66
+ attention_probs = F.softmax(attention_scores, dim=-1)
67
+ attention_probs = self.dropout(attention_probs)
68
+ context_layer = torch.matmul(attention_probs, value_states)
69
+ context_layer = context_layer.transpose(1, 2).contiguous()
70
+ context_layer = context_layer.view(batch_size, seq_length, self.hidden_size)
71
+ context_layer = self.out(context_layer)
72
+ return context_layer
73
+
74
+
75
+ class MLP(nn.Module):
76
+
77
+ def __init__(self, config: RiemannConfig):
78
+ super().__init__()
79
+ self.dense_h_to_4h = nn.Linear(config.hidden_size, config.intermediate_size)
80
+ self.dense_4h_to_h = nn.Linear(config.intermediate_size, config.hidden_size)
81
+ self.act = nn.GELU()
82
+ self.dropout = nn.Dropout(config.hidden_dropout)
83
+
84
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
85
+ hidden_states = self.dense_h_to_4h(hidden_states)
86
+ hidden_states = self.act(hidden_states)
87
+ hidden_states = self.dense_4h_to_h(hidden_states)
88
+ hidden_states = self.dropout(hidden_states)
89
+ return hidden_states
90
+
91
+
92
+ class TransformerBlock(nn.Module):
93
+
94
+ def __init__(self, config: RiemannConfig):
95
+ super().__init__()
96
+ self.attention = MultiHeadAttention(config)
97
+ self.mlp = MLP(config)
98
+ self.input_layernorm = nn.LayerNorm(
99
+ config.hidden_size, eps=config.layer_norm_eps
100
+ )
101
+ self.post_attention_layernorm = nn.LayerNorm(
102
+ config.hidden_size, eps=config.layer_norm_eps
103
+ )
104
+ self.dropout = nn.Dropout(config.hidden_dropout)
105
+
106
+ def forward(
107
+ self, hidden_states: torch.Tensor, attention_mask: Optional[torch.Tensor] = None
108
+ ):
109
+ attention_layernorm_out = self.input_layernorm(hidden_states)
110
+ attention_output = self.attention(
111
+ attention_layernorm_out, attention_mask=attention_mask
112
+ )
113
+ attention_output = self.dropout(attention_output)
114
+ attention_output = attention_output + hidden_states
115
+ mlp_layernorm_out = self.post_attention_layernorm(attention_output)
116
+ mlp_output = self.mlp(mlp_layernorm_out)
117
+ layer_output = mlp_output + attention_output
118
+ return layer_output
119
+
120
+
121
+ class RiemannPreTrainedModel(PreTrainedModel):
122
+ config_class = RiemannConfig
123
+ base_model_prefix = "riemann"
124
+ supports_gradient_checkpointing = True
125
+ _no_split_modules = ["TransformerBlock"]
126
+
127
+ def _init_weights(self, module):
128
+ if isinstance(module, nn.Linear):
129
+ module.weight.data.normal_(mean=0.0, std=0.02)
130
+ if module.bias is not None:
131
+ module.bias.data.zero_()
132
+ elif isinstance(module, nn.Embedding):
133
+ module.weight.data.normal_(mean=0.0, std=0.02)
134
+ elif isinstance(module, nn.LayerNorm):
135
+ module.bias.data.zero_()
136
+ module.weight.data.fill_(1.0)
137
+
138
+
139
+ class RiemannForCausalLM(RiemannPreTrainedModel, GenerationMixin):
140
+
141
+ def __init__(self, config: RiemannConfig):
142
+ super().__init__(config)
143
+ self.config = config
144
+ self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size)
145
+ self.position_embeddings = nn.Embedding(
146
+ config.max_position_embeddings, config.hidden_size
147
+ )
148
+ self.layers = nn.ModuleList(
149
+ [TransformerBlock(config) for _ in range(config.num_hidden_layers)]
150
+ )
151
+ self.final_layernorm = nn.LayerNorm(
152
+ config.hidden_size, eps=config.layer_norm_eps
153
+ )
154
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
155
+ self.gradient_checkpointing = False
156
+ self.post_init()
157
+
158
+ def get_input_embeddings(self):
159
+ return self.word_embeddings
160
+
161
+ def set_input_embeddings(self, value):
162
+ self.word_embeddings = value
163
+
164
+ def get_output_embeddings(self):
165
+ return self.lm_head
166
+
167
+ def set_output_embeddings(self, value):
168
+ self.lm_head = value
169
+
170
+ def _build_attention_mask(self, input_shape, attention_mask, dtype, device):
171
+ batch_size, seq_length = input_shape
172
+ causal = torch.triu(
173
+ torch.full(
174
+ (seq_length, seq_length),
175
+ torch.finfo(dtype).min,
176
+ dtype=dtype,
177
+ device=device,
178
+ ),
179
+ diagonal=1,
180
+ )
181
+ causal = causal.unsqueeze(0).unsqueeze(0)
182
+ if attention_mask is not None:
183
+ padding = attention_mask[:, None, None, :].to(dtype=dtype)
184
+ padding = (1.0 - padding) * torch.finfo(dtype).min
185
+ return causal + padding
186
+ return causal
187
+
188
+ def forward(
189
+ self,
190
+ input_ids: Optional[torch.Tensor] = None,
191
+ attention_mask: Optional[torch.Tensor] = None,
192
+ inputs_embeds: Optional[torch.Tensor] = None,
193
+ labels: Optional[torch.Tensor] = None,
194
+ use_cache: Optional[bool] = None,
195
+ **kwargs,
196
+ ):
197
+ if input_ids is not None and inputs_embeds is not None:
198
+ raise ValueError("pass either input_ids or inputs_embeds, not both")
199
+ if input_ids is not None:
200
+ inputs_embeds = self.word_embeddings(input_ids)
201
+ batch_size, seq_length = input_ids.shape
202
+ elif inputs_embeds is not None:
203
+ batch_size, seq_length = inputs_embeds.shape[:2]
204
+ else:
205
+ raise ValueError("need either input_ids or inputs_embeds")
206
+ position_ids = torch.arange(
207
+ seq_length, dtype=torch.long, device=inputs_embeds.device
208
+ )
209
+ position_ids = position_ids.unsqueeze(0).expand(batch_size, -1)
210
+ position_embeds = self.position_embeddings(position_ids)
211
+ hidden_states = inputs_embeds + position_embeds
212
+ full_mask = (
213
+ None
214
+ if attention_mask is None
215
+ else self._build_attention_mask(
216
+ (batch_size, seq_length),
217
+ attention_mask,
218
+ hidden_states.dtype,
219
+ hidden_states.device,
220
+ )
221
+ )
222
+ for layer in self.layers:
223
+ if self.gradient_checkpointing and self.training:
224
+ hidden_states = torch.utils.checkpoint.checkpoint(
225
+ layer, hidden_states, full_mask, use_reentrant=False
226
+ )
227
+ else:
228
+ hidden_states = layer(hidden_states, full_mask)
229
+ hidden_states = self.final_layernorm(hidden_states)
230
+ logits = self.lm_head(hidden_states)
231
+ loss = None
232
+ if labels is not None:
233
+ shift_logits = logits[..., :-1, :].contiguous()
234
+ shift_labels = labels[..., 1:].contiguous()
235
+ loss = F.cross_entropy(
236
+ shift_logits.view(-1, self.config.vocab_size),
237
+ shift_labels.view(-1),
238
+ ignore_index=-100,
239
+ )
240
+ return CausalLMOutputWithPast(
241
+ loss=loss, logits=logits, hidden_states=hidden_states
242
+ )
243
+
244
+ def prepare_inputs_for_generation(self, input_ids, **kwargs):
245
+ return {"input_ids": input_ids}
training/riemann/modeling_riemann.py CHANGED
@@ -122,6 +122,7 @@ class RiemannPreTrainedModel(PreTrainedModel):
122
  config_class = RiemannConfig
123
  base_model_prefix = "riemann"
124
  supports_gradient_checkpointing = True
 
125
 
126
  def _init_weights(self, module):
127
  if isinstance(module, nn.Linear):
 
122
  config_class = RiemannConfig
123
  base_model_prefix = "riemann"
124
  supports_gradient_checkpointing = True
125
+ _no_split_modules = ["TransformerBlock"]
126
 
127
  def _init_weights(self, module):
128
  if isinstance(module, nn.Linear):