wenge-research commited on
Commit
782e264
1 Parent(s): 77c6fd2

Upload 6 files

Browse files
latest ADDED
@@ -0,0 +1 @@
 
 
1
+ global_step4000
modeling_YAYIUIE.py ADDED
@@ -0,0 +1,824 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .configuration_YAYIUIE import YAYIUIEConfig
2
+ from .generation_utils import build_chat_input, TextIterStreamer
3
+
4
+ import math
5
+ from threading import Thread
6
+ from typing import List, Optional, Tuple, Union
7
+
8
+ import torch
9
+ from torch import nn
10
+ from torch.nn import CrossEntropyLoss
11
+ from torch.nn import functional as F
12
+ from transformers import PreTrainedModel, PretrainedConfig
13
+ from transformers.activations import ACT2FN
14
+ from transformers.generation.utils import GenerationConfig
15
+ from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
16
+ from transformers.utils import logging, ContextManagers
17
+
18
+ import os
19
+ from contextlib import contextmanager
20
+ from accelerate import init_empty_weights
21
+
22
+ logger = logging.get_logger(__name__)
23
+
24
+ try:
25
+ from xformers import ops as xops
26
+ except ImportError:
27
+ xops = None
28
+ logger.warning(
29
+ "Xformers is not installed correctly. If you want to use memory_efficient_attention to accelerate training use the following command to install Xformers\npip install xformers."
30
+ )
31
+
32
+
33
+ def _get_interleave(n):
34
+ def _get_interleave_power_of_2(n):
35
+ start = 2 ** (-(2 ** -(math.log2(n) - 3)))
36
+ ratio = start
37
+ return [start * ratio**i for i in range(n)]
38
+
39
+ if math.log2(n).is_integer():
40
+ return _get_interleave_power_of_2(n)
41
+ else:
42
+ closest_power_of_2 = 2 ** math.floor(math.log2(n))
43
+ return (
44
+ _get_interleave_power_of_2(closest_power_of_2)
45
+ + _get_interleave(2 * closest_power_of_2)[0::2][: n - closest_power_of_2]
46
+ )
47
+
48
+
49
+ def _fill_with_neg_inf(t):
50
+ """FP16-compatible function that fills a tensor with -inf."""
51
+ return t.float().fill_(float("-inf")).type_as(t)
52
+
53
+
54
+ def _buffered_future_mask(tensor, maxpos, alibi, attn_heads):
55
+ _future_mask = torch.triu(_fill_with_neg_inf(torch.zeros([maxpos, maxpos])), 1)
56
+ _future_mask = _future_mask.unsqueeze(0) + alibi
57
+ new_future_mask = _future_mask.to(tensor)
58
+ return new_future_mask[: tensor.shape[0] * attn_heads, :maxpos, :maxpos]
59
+
60
+
61
+ def _gen_alibi_mask(tensor, n_head, max_pos):
62
+ slopes = torch.Tensor(_get_interleave(n_head))
63
+ position_point = torch.arange(max_pos) - max_pos + 1
64
+ position_point = position_point.unsqueeze(0).unsqueeze(0).expand(n_head, -1, -1)
65
+ diag = torch.diag(position_point[0])
66
+ position_point = position_point - diag.unsqueeze(0).unsqueeze(0).transpose(-1, -2)
67
+ alibi = slopes.unsqueeze(1).unsqueeze(1) * position_point
68
+ alibi = alibi.view(n_head, 1, max_pos)
69
+ alibi_mask = torch.triu(_fill_with_neg_inf(torch.zeros([max_pos, max_pos])), 1)
70
+ alibi_mask = alibi_mask.unsqueeze(0) + alibi
71
+ return alibi_mask
72
+
73
+
74
+ class RMSNorm(torch.nn.Module):
75
+ def __init__(self, hidden_size, epsilon=1e-6):
76
+ super().__init__()
77
+ self.weight = torch.nn.Parameter(torch.empty(hidden_size))
78
+ self.epsilon = epsilon
79
+
80
+ def forward(self, hidden_states):
81
+ variance = hidden_states.to(torch.float32).pow(2).mean(-1, keepdim=True)
82
+ hidden_states = hidden_states * torch.rsqrt(variance + self.epsilon)
83
+
84
+ # convert into half-precision
85
+ if self.weight.dtype in [torch.float16, torch.bfloat16]:
86
+ hidden_states = hidden_states.to(self.weight.dtype)
87
+
88
+ return self.weight * hidden_states
89
+
90
+
91
+ class MLP(torch.nn.Module):
92
+ def __init__(
93
+ self,
94
+ hidden_size: int,
95
+ intermediate_size: int,
96
+ hidden_act: str,
97
+ ):
98
+ super().__init__()
99
+ self.gate_proj = torch.nn.Linear(hidden_size, intermediate_size, bias=False)
100
+ self.down_proj = torch.nn.Linear(intermediate_size, hidden_size, bias=False)
101
+ self.up_proj = torch.nn.Linear(hidden_size, intermediate_size, bias=False)
102
+ self.act_fn = ACT2FN[hidden_act]
103
+
104
+ def forward(self, x):
105
+ return self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
106
+
107
+
108
+ class YAYIUIEAttention(torch.nn.Module):
109
+ def __init__(self, config: YAYIUIEConfig):
110
+ super().__init__()
111
+ self.config = config
112
+ self.hidden_size = config.hidden_size
113
+ self.num_heads = config.num_attention_heads
114
+ self.head_dim = self.hidden_size // self.num_heads
115
+ self.max_position_embeddings = config.model_max_length
116
+
117
+ if (self.head_dim * self.num_heads) != self.hidden_size:
118
+ raise ValueError(
119
+ f"hidden_size {self.hidden_size} is not divisible by num_heads {self.num_heads}"
120
+ )
121
+ self.W_pack = torch.nn.Linear(
122
+ self.hidden_size, 3 * self.hidden_size, bias=False
123
+ )
124
+ self.o_proj = torch.nn.Linear(
125
+ self.num_heads * self.head_dim, self.hidden_size, bias=False
126
+ )
127
+
128
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
129
+ return (
130
+ tensor.view(bsz, seq_len, self.num_heads, self.head_dim)
131
+ .transpose(1, 2)
132
+ .contiguous()
133
+ )
134
+
135
+ def forward(
136
+ self,
137
+ hidden_states: torch.Tensor,
138
+ attention_mask: Optional[torch.Tensor] = None,
139
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
140
+ output_attentions: bool = False,
141
+ use_cache: bool = False,
142
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
143
+ bsz, q_len, _ = hidden_states.size()
144
+
145
+ proj = self.W_pack(hidden_states)
146
+ proj = (
147
+ proj.unflatten(-1, (3, self.hidden_size))
148
+ .unsqueeze(0)
149
+ .transpose(0, -2)
150
+ .squeeze(-2)
151
+ )
152
+ query_states = (
153
+ proj[0].view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
154
+ )
155
+ key_states = (
156
+ proj[1].view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
157
+ )
158
+ value_states = (
159
+ proj[2].view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
160
+ )
161
+
162
+ kv_seq_len = key_states.shape[-2]
163
+ if past_key_value is not None:
164
+ kv_seq_len += past_key_value[0].shape[-2]
165
+
166
+ if past_key_value is not None:
167
+ # reuse k, v, self_attention
168
+ key_states = torch.cat([past_key_value[0], key_states], dim=2)
169
+ value_states = torch.cat([past_key_value[1], value_states], dim=2)
170
+
171
+ past_key_value = (key_states, value_states) if use_cache else None
172
+ if xops is not None and self.training:
173
+ attn_weights = None
174
+ # query_states = query_states.transpose(1, 2)
175
+ # key_states = key_states.transpose(1, 2)
176
+ # value_states = value_states.transpose(1, 2)
177
+ # attn_output = xops.memory_efficient_attention(
178
+ # query_states, key_states, value_states, attn_bias=attention_mask
179
+ # )
180
+ with torch.backends.cuda.sdp_kernel(enable_flash=True, enable_math=True, enable_mem_efficient=True):
181
+ attn_output = F.scaled_dot_product_attention(query_states, key_states, value_states, attn_mask = attention_mask)
182
+ attn_output = attn_output.transpose(1, 2)
183
+ else:
184
+ attn_weights = torch.matmul(
185
+ query_states, key_states.transpose(2, 3)
186
+ ) / math.sqrt(self.head_dim)
187
+
188
+ if attention_mask is not None:
189
+ if q_len == 1: # inference with cache
190
+ if len(attention_mask.size()) == 4:
191
+ attention_mask = attention_mask[:, :, -1:, :]
192
+ else:
193
+ attention_mask = attention_mask[:, -1:, :]
194
+ attn_weights = attn_weights + attention_mask
195
+ attn_weights = torch.max(
196
+ attn_weights, torch.tensor(torch.finfo(attn_weights.dtype).min)
197
+ )
198
+
199
+ attn_weights = torch.nn.functional.softmax(attn_weights, dim=-1)
200
+ attn_output = torch.matmul(attn_weights, value_states)
201
+
202
+ attn_output = attn_output.transpose(1, 2)
203
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
204
+ attn_output = self.o_proj(attn_output)
205
+
206
+ if not output_attentions:
207
+ attn_weights = None
208
+
209
+ return attn_output, attn_weights, past_key_value
210
+
211
+
212
+ class YAYIUIELayer(torch.nn.Module):
213
+ def __init__(self, config: YAYIUIEConfig):
214
+ super().__init__()
215
+ self.hidden_size = config.hidden_size
216
+ self.self_attn = YAYIUIEAttention(config=config)
217
+ self.mlp = MLP(
218
+ hidden_size=self.hidden_size,
219
+ intermediate_size=config.intermediate_size,
220
+ hidden_act=config.hidden_act,
221
+ )
222
+ self.input_layernorm = RMSNorm(config.hidden_size, epsilon=config.rms_norm_eps)
223
+ self.post_attention_layernorm = RMSNorm(
224
+ config.hidden_size, epsilon=config.rms_norm_eps
225
+ )
226
+
227
+ def forward(
228
+ self,
229
+ hidden_states: torch.Tensor,
230
+ attention_mask: Optional[torch.Tensor] = None,
231
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
232
+ output_attentions: Optional[bool] = False,
233
+ use_cache: Optional[bool] = False,
234
+ ) -> Tuple[
235
+ torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]
236
+ ]:
237
+ residual = hidden_states
238
+
239
+ hidden_states = self.input_layernorm(hidden_states)
240
+
241
+ # Self Attention
242
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
243
+ hidden_states=hidden_states,
244
+ attention_mask=attention_mask,
245
+ past_key_value=past_key_value,
246
+ output_attentions=output_attentions,
247
+ use_cache=use_cache,
248
+ )
249
+ hidden_states = residual + hidden_states
250
+
251
+ # Fully Connected
252
+ residual = hidden_states
253
+ hidden_states = self.post_attention_layernorm(hidden_states)
254
+ hidden_states = self.mlp(hidden_states)
255
+ hidden_states = residual + hidden_states
256
+
257
+ outputs = (hidden_states,)
258
+
259
+ if use_cache:
260
+ outputs += (present_key_value,)
261
+
262
+ return outputs
263
+
264
+
265
+ class YAYIUIEPreTrainedModel(PreTrainedModel):
266
+ config_class = YAYIUIEConfig
267
+ base_model_prefix = "model"
268
+ supports_gradient_checkpointing = True
269
+ _no_split_modules = ["YAYIUIELayer"]
270
+ _keys_to_ignore_on_load_unexpected = [r"decoder\.version"]
271
+
272
+ def _init_weights(self, module):
273
+ std = self.config.initializer_range
274
+ if isinstance(module, torch.nn.Linear):
275
+ module.weight.data.normal_(mean=0.0, std=std)
276
+ if module.bias is not None:
277
+ module.bias.data.zero_()
278
+ elif isinstance(module, torch.nn.Embedding):
279
+ module.weight.data.normal_(mean=0.0, std=std)
280
+ if module.padding_idx is not None:
281
+ module.weight.data[module.padding_idx].zero_()
282
+
283
+ def _set_gradient_checkpointing(self, module, value=False):
284
+ if isinstance(module, YAYIUIEModel):
285
+ module.gradient_checkpointing = value
286
+
287
+
288
+ class YAYIUIEModel(YAYIUIEPreTrainedModel):
289
+ def __init__(self, config: YAYIUIEConfig):
290
+ super().__init__(config)
291
+ self.padding_idx = config.pad_token_id
292
+ self.vocab_size = config.vocab_size
293
+ self.n_head = config.num_attention_heads
294
+ self.embed_tokens = torch.nn.Embedding(
295
+ config.vocab_size, config.hidden_size, self.padding_idx
296
+ )
297
+ self.layers = torch.nn.ModuleList(
298
+ [YAYIUIELayer(config) for _ in range(config.num_hidden_layers)]
299
+ )
300
+ self.norm = RMSNorm(config.hidden_size, epsilon=config.rms_norm_eps)
301
+
302
+ self.gradient_checkpointing = config.gradient_checkpointing
303
+ self.post_init()
304
+ self.max_cache_pos = config.model_max_length
305
+ self.first_run = True
306
+ self.alibi_mask = None
307
+
308
+ def get_input_embeddings(self):
309
+ return self.embed_tokens
310
+
311
+ def set_input_embeddings(self, value):
312
+ self.embed_tokens = value
313
+
314
+ def get_alibi_mask(self, tensor, seq_length_with_past):
315
+ if self.training:
316
+ slopes = torch.Tensor(_get_interleave(self.n_head))
317
+ position_point = (
318
+ torch.arange(seq_length_with_past) - seq_length_with_past + 1
319
+ )
320
+ position_point = (
321
+ position_point.unsqueeze(0)
322
+ .unsqueeze(0)
323
+ .expand(self.n_head, seq_length_with_past, -1)
324
+ )
325
+ diag = torch.diag(position_point[0])
326
+ position_point = position_point - diag.unsqueeze(0).unsqueeze(0).transpose(
327
+ -1, -2
328
+ )
329
+ alibi = slopes.unsqueeze(1).unsqueeze(1) * position_point
330
+ mask = _buffered_future_mask(
331
+ tensor, seq_length_with_past, alibi, self.n_head
332
+ )
333
+ else:
334
+ if self.first_run:
335
+ self.first_run = False
336
+ self.register_buffer(
337
+ "future_mask",
338
+ _gen_alibi_mask(tensor, self.n_head, self.max_cache_pos).to(
339
+ tensor
340
+ ),
341
+ persistent=False,
342
+ )
343
+ if seq_length_with_past > self.max_cache_pos:
344
+ self.max_cache_pos = seq_length_with_past
345
+ self.register_buffer(
346
+ "future_mask",
347
+ _gen_alibi_mask(tensor, self.n_head, self.max_cache_pos).to(
348
+ tensor
349
+ ),
350
+ persistent=False,
351
+ )
352
+ mask = self.future_mask[
353
+ : self.n_head, :seq_length_with_past, :seq_length_with_past
354
+ ]
355
+ return mask
356
+
357
+ def forward(
358
+ self,
359
+ input_ids: torch.LongTensor = None,
360
+ attention_mask: Optional[torch.Tensor] = None,
361
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
362
+ inputs_embeds: Optional[torch.FloatTensor] = None,
363
+ use_cache: Optional[bool] = False,
364
+ output_attentions: Optional[bool] = False,
365
+ output_hidden_states: Optional[bool] = False,
366
+ return_dict: Optional[bool] = True,
367
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
368
+ if input_ids is not None and inputs_embeds is not None:
369
+ raise ValueError(
370
+ "You cannot provide both input_ids and inputs_embeds simultaneously"
371
+ )
372
+ elif input_ids is not None:
373
+ batch_size, seq_length = input_ids.shape
374
+ elif inputs_embeds is not None:
375
+ batch_size, seq_length, _ = inputs_embeds.shape
376
+ else:
377
+ raise ValueError("You need to provide input_ids or inputs_embeds")
378
+
379
+ return_dict = (
380
+ return_dict if return_dict is not None else self.config.use_return_dict
381
+ )
382
+
383
+ seq_length_with_past = seq_length
384
+
385
+ if past_key_values is not None:
386
+ past_key_values_length = past_key_values[0][0].shape[2]
387
+ seq_length_with_past = seq_length_with_past + past_key_values_length
388
+
389
+ if inputs_embeds is None:
390
+ inputs_embeds = self.embed_tokens(input_ids)
391
+
392
+ if self.training:
393
+ if (
394
+ self.alibi_mask is None
395
+ or self.alibi_mask.shape[-1] != seq_length_with_past
396
+ ):
397
+ self.alibi_mask = self.get_alibi_mask(
398
+ inputs_embeds, seq_length_with_past
399
+ )
400
+ alibi_mask = self.alibi_mask
401
+ else:
402
+ alibi_mask = self.get_alibi_mask(inputs_embeds, seq_length_with_past)
403
+
404
+ if attention_mask is not None:
405
+ if len(attention_mask.shape) == 2:
406
+ expanded_mask = attention_mask.to(alibi_mask.dtype)
407
+ expanded_mask = torch.tril(
408
+ torch.gt(expanded_mask[:, :, None] * expanded_mask[:, None, :], 0)
409
+ ) * torch.eq(expanded_mask[:, :, None] - expanded_mask[:, None, :], 0)
410
+ else:
411
+ expanded_mask = attention_mask
412
+ bsz = inputs_embeds.size(0)
413
+ src_len, tgt_len = alibi_mask.size()[-2:]
414
+ expanded_mask = (
415
+ expanded_mask.unsqueeze(1)
416
+ .expand(bsz, 1, src_len, tgt_len)
417
+ .to(alibi_mask.dtype)
418
+ )
419
+ inverted_mask = 1.0 - expanded_mask
420
+ inverted_mask = inverted_mask.masked_fill(
421
+ inverted_mask.to(torch.bool), torch.finfo(alibi_mask.dtype).min
422
+ )
423
+ attention_mask = inverted_mask + alibi_mask.unsqueeze(0)
424
+ else:
425
+ attention_mask = alibi_mask
426
+
427
+ hidden_states = inputs_embeds
428
+
429
+ if self.gradient_checkpointing and self.training:
430
+ if use_cache:
431
+ logger.warning_once(
432
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
433
+ )
434
+ use_cache = False
435
+
436
+ # decoder layers
437
+ all_hidden_states = () if output_hidden_states else None
438
+ all_self_attns = () if output_attentions else None
439
+ next_decoder_cache = () if use_cache else None
440
+
441
+ for idx, decoder_layer in enumerate(self.layers):
442
+ if output_hidden_states:
443
+ all_hidden_states += (hidden_states,)
444
+
445
+ past_key_value = (
446
+ past_key_values[idx] if past_key_values is not None else None
447
+ )
448
+
449
+ if self.gradient_checkpointing and self.training:
450
+
451
+ def create_custom_forward(module):
452
+ def custom_forward(*inputs):
453
+ # None for past_key_value
454
+ return module(*inputs, output_attentions, None)
455
+
456
+ return custom_forward
457
+
458
+ layer_outputs = torch.utils.checkpoint.checkpoint(
459
+ create_custom_forward(decoder_layer),
460
+ hidden_states,
461
+ attention_mask,
462
+ None,
463
+ )
464
+ else:
465
+ layer_outputs = decoder_layer(
466
+ hidden_states,
467
+ attention_mask=attention_mask,
468
+ past_key_value=past_key_value,
469
+ output_attentions=output_attentions,
470
+ use_cache=use_cache,
471
+ )
472
+
473
+ hidden_states = layer_outputs[0]
474
+
475
+ if use_cache:
476
+ next_decoder_cache += (layer_outputs[2 if output_attentions else 1],)
477
+
478
+ if output_attentions:
479
+ all_self_attns += (layer_outputs[1],)
480
+
481
+ hidden_states = self.norm(hidden_states)
482
+
483
+ # add hidden states from the last decoder layer
484
+ if output_hidden_states:
485
+ all_hidden_states += (hidden_states,)
486
+
487
+ next_cache = next_decoder_cache if use_cache else None
488
+ if not return_dict:
489
+ return tuple(
490
+ v
491
+ for v in [hidden_states, next_cache, all_hidden_states, all_self_attns]
492
+ if v is not None
493
+ )
494
+ return BaseModelOutputWithPast(
495
+ last_hidden_state=hidden_states,
496
+ past_key_values=next_cache,
497
+ hidden_states=all_hidden_states,
498
+ attentions=all_self_attns,
499
+ )
500
+
501
+
502
+ class NormHead(nn.Module):
503
+ def __init__(self, hidden_size, vocab_size, bias=False):
504
+ super().__init__()
505
+ self.weight = nn.Parameter(torch.empty((vocab_size, hidden_size)))
506
+ nn.init.kaiming_uniform_(self.weight, a=math.sqrt(5))
507
+ self.first_flag = True
508
+
509
+ def forward(self, hidden_states):
510
+ if self.training:
511
+ norm_weight = nn.functional.normalize(self.weight)
512
+ elif self.first_flag:
513
+ self.first_flag = False
514
+ self.weight = nn.Parameter(nn.functional.normalize(self.weight))
515
+ norm_weight = self.weight
516
+ else:
517
+ norm_weight = self.weight
518
+ return nn.functional.linear(hidden_states, norm_weight)
519
+
520
+ _init_weights = True
521
+ @contextmanager
522
+ def no_init_weights(_enable=True):
523
+ global _init_weights
524
+ old_init_weights = _init_weights
525
+ if _enable:
526
+ _init_weights = False
527
+ try:
528
+ yield
529
+ finally:
530
+ _init_weights = old_init_weights
531
+
532
+
533
+ class YAYIUIEForCausalLM(YAYIUIEPreTrainedModel):
534
+ def __init__(self, config, *model_args, **model_kwargs):
535
+ super().__init__(config, *model_args, **model_kwargs)
536
+ self.model = YAYIUIEModel(config)
537
+ self.lm_head = NormHead(config.hidden_size, config.vocab_size, bias=False)
538
+ #if hasattr(config, "quantization_config") and config.quantization_config['load_in_4bit']:
539
+ if hasattr(config, "quantization_config") and isinstance(config.quantization_config, dict) and config.quantization_config.get('load_in_4bit', False):
540
+ try:
541
+ from .quantizer import quantize_offline, init_model_weight_int4
542
+ except ImportError:
543
+ raise ImportError(f"Needs quantize_offline to run quantize.")
544
+ quantize_offline(self, 4)
545
+ # Initialize weights and apply final processing
546
+ self.post_init()
547
+
548
+ def get_input_embeddings(self):
549
+ return self.model.embed_tokens
550
+
551
+ def set_input_embeddings(self, value):
552
+ self.model.embed_tokens = value
553
+
554
+ def get_output_embeddings(self):
555
+ return self.lm_head
556
+
557
+ def set_output_embeddings(self, new_embeddings):
558
+ self.lm_head = new_embeddings
559
+
560
+ def set_decoder(self, decoder):
561
+ self.model = decoder
562
+
563
+ def get_decoder(self):
564
+ return self.model
565
+
566
+ @classmethod
567
+ def from_pretrained(
568
+ cls,
569
+ pretrained_model_name_or_path: Optional[Union[str, os.PathLike]],
570
+ *model_args,
571
+ config: Optional[Union[PretrainedConfig, str, os.PathLike]] = None,
572
+ cache_dir: Optional[Union[str, os.PathLike]] = None,
573
+ ignore_mismatched_sizes: bool = False,
574
+ force_download: bool = False,
575
+ local_files_only: bool = False,
576
+ token: Optional[Union[str, bool]] = None,
577
+ revision: str = "main",
578
+ use_safetensors: bool = None,
579
+ **kwargs,
580
+ ):
581
+
582
+ # Load config if we don't provide a configuration
583
+ if not isinstance(config, PretrainedConfig):
584
+ config_path = config if config is not None else pretrained_model_name_or_path
585
+ config, model_kwargs = cls.config_class.from_pretrained(
586
+ config_path,
587
+ cache_dir=cache_dir,
588
+ return_unused_kwargs=True,
589
+ force_download=force_download,
590
+ resume_download=False,
591
+ proxies=None,
592
+ local_files_only=local_files_only,
593
+ token=token,
594
+ revision=revision,
595
+ subfolder="",
596
+ _from_auto=False,
597
+ _from_pipeline=None,
598
+ **kwargs,
599
+ )
600
+ else:
601
+ model_kwargs = kwargs
602
+
603
+ if hasattr(config, "quantization_config") and config.quantization_config['load_in_4bit']:
604
+ try:
605
+ from .quantizer import init_model_weight_int4
606
+ from accelerate import init_empty_weights, dispatch_model, infer_auto_device_map
607
+ from accelerate.utils import CustomDtype
608
+ from accelerate.utils import get_balanced_memory
609
+ except ImportError:
610
+ raise ImportError(f"Needs import model weight init func to run quantize.")
611
+ # Instantiate model.
612
+ init_contexts = [no_init_weights(_enable=True)]
613
+ init_contexts.append(init_empty_weights())
614
+ with ContextManagers(init_contexts):
615
+ model = cls(config)
616
+
617
+ model_file = os.path.join(pretrained_model_name_or_path, 'pytorch_model.bin')
618
+ state_dict = torch.load(model_file, map_location="cpu")
619
+ model.is_quantized = True
620
+
621
+ device_map = kwargs.pop("device_map", None)
622
+ torch_dtype = kwargs.pop("torch_dtype", None)
623
+ if device_map is not None:
624
+ kwargs = {"no_split_module_classes": model._no_split_modules}
625
+ target_dtype = CustomDtype.INT4
626
+ max_memory = get_balanced_memory(
627
+ model,
628
+ dtype=target_dtype,
629
+ low_zero=(device_map == "balanced_low_0"),
630
+ max_memory=None,
631
+ **kwargs,
632
+ )
633
+ kwargs["max_memory"] = max_memory
634
+ device_map = infer_auto_device_map(model, dtype=target_dtype, **kwargs)
635
+ model = init_model_weight_int4(config, model, state_dict)
636
+
637
+ # Set model in evaluation mode to deactivate DropOut modules by default
638
+ model.eval()
639
+ # If it is a model with generation capabilities, attempt to load the generation config
640
+ if model.can_generate():
641
+ try:
642
+ model.generation_config = GenerationConfig.from_pretrained(
643
+ pretrained_model_name_or_path,
644
+ cache_dir=cache_dir,
645
+ force_download=force_download,
646
+ resume_download=False,
647
+ proxies=None,
648
+ local_files_only=local_files_only,
649
+ token=token,
650
+ revision=revision,
651
+ subfolder="",
652
+ _from_auto=False,
653
+ _from_pipeline=None,
654
+ **kwargs,
655
+ )
656
+ except (OSError, TypeError):
657
+ logger.info(
658
+ "Generation config file not found, using a generation config created from the model config."
659
+ )
660
+ pass
661
+
662
+ if device_map is not None:
663
+ dispatch_model(model, device_map=device_map)
664
+
665
+ return model
666
+
667
+ return super(YAYIUIEForCausalLM, cls).from_pretrained(pretrained_model_name_or_path, *model_args,
668
+ config=config, cache_dir=cache_dir, ignore_mismatched_sizes=ignore_mismatched_sizes,
669
+ force_download=force_download, local_files_only=local_files_only, token=token, revision=revision,
670
+ use_safetensors=use_safetensors, **kwargs)
671
+
672
+ def forward(
673
+ self,
674
+ input_ids: torch.LongTensor = None,
675
+ attention_mask: Optional[torch.Tensor] = None,
676
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
677
+ inputs_embeds: Optional[torch.FloatTensor] = None,
678
+ labels: Optional[torch.LongTensor] = None,
679
+ use_cache: Optional[bool] = None,
680
+ output_attentions: Optional[bool] = False,
681
+ output_hidden_states: Optional[bool] = False,
682
+ return_dict: Optional[bool] = True,
683
+ **kwargs,
684
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
685
+ return_dict = (
686
+ return_dict if return_dict is not None else self.config.use_return_dict
687
+ )
688
+
689
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
690
+ outputs = self.model(
691
+ input_ids=input_ids,
692
+ attention_mask=attention_mask,
693
+ past_key_values=past_key_values,
694
+ inputs_embeds=inputs_embeds,
695
+ use_cache=use_cache,
696
+ output_attentions=output_attentions,
697
+ output_hidden_states=output_hidden_states,
698
+ return_dict=return_dict,
699
+ )
700
+
701
+ hidden_states = outputs[0]
702
+ logits = self.lm_head(hidden_states)
703
+ loss = None
704
+ if labels is not None:
705
+ # Shift so that tokens < n predict n
706
+ shift_logits = logits[..., :-1, :].contiguous()
707
+ shift_labels = labels[..., 1:].contiguous()
708
+ # Flatten the tokens
709
+ loss_fct = CrossEntropyLoss()
710
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
711
+ shift_labels = shift_labels.view(-1)
712
+ softmax_normalizer = shift_logits.max(-1).values ** 2
713
+ z_loss = self.config.z_loss_weight * softmax_normalizer.mean()
714
+ # Enable model parallelism
715
+ shift_labels = shift_labels.to(shift_logits.device)
716
+ loss = loss_fct(shift_logits, shift_labels) + z_loss
717
+
718
+ if not return_dict:
719
+ output = (logits,) + outputs[1:]
720
+ return (loss,) + output if loss is not None else output
721
+
722
+ return CausalLMOutputWithPast(
723
+ loss=loss,
724
+ logits=logits,
725
+ past_key_values=outputs.past_key_values,
726
+ hidden_states=outputs.hidden_states,
727
+ attentions=outputs.attentions,
728
+ )
729
+
730
+ def quantize(self, bits: int):
731
+ try:
732
+ from .quantizer import quantize_online
733
+ except ImportError:
734
+ raise ImportError(f"Needs QLinear to run quantize.")
735
+ return quantize_online(self, bits)
736
+
737
+ def prepare_inputs_for_generation(
738
+ self,
739
+ input_ids: torch.LongTensor,
740
+ past_key_values: Optional[torch.Tensor] = None,
741
+ attention_mask: Optional[torch.Tensor] = None,
742
+ inputs_embeds: Optional[torch.Tensor] = None,
743
+ **kwargs,
744
+ ):
745
+ if past_key_values:
746
+ input_ids = input_ids[:, -1:]
747
+
748
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
749
+ if inputs_embeds is not None and past_key_values is None:
750
+ model_inputs = {"inputs_embeds": inputs_embeds}
751
+ else:
752
+ model_inputs = {"input_ids": input_ids}
753
+
754
+ model_inputs.update(
755
+ {
756
+ "past_key_values": past_key_values,
757
+ "use_cache": kwargs.get("use_cache"),
758
+ "attention_mask": attention_mask,
759
+ }
760
+ )
761
+ return model_inputs
762
+
763
+ @staticmethod
764
+ def _reorder_cache(past_key_values, beam_idx):
765
+ return tuple(
766
+ tuple(past_state.index_select(0, beam_idx) for past_state in layer_past)
767
+ for layer_past in past_key_values
768
+ )
769
+
770
+ def _build_chat_input(
771
+ self, tokenizer, messages: List[dict], max_new_tokens: int = 0
772
+ ):
773
+ max_new_tokens = max_new_tokens or self.generation_config.max_new_tokens
774
+ max_input_tokens = self.config.model_max_length - max_new_tokens
775
+ max_input_tokens = max(self.config.model_max_length // 2, max_input_tokens)
776
+ total_input, round_input = [], []
777
+ for i, message in enumerate(messages[::-1]):
778
+ content_tokens = tokenizer.encode(message["content"])
779
+ if message["role"] == "user":
780
+ round_input = (
781
+ [self.generation_config.user_token_id]
782
+ + content_tokens
783
+ + round_input
784
+ )
785
+ if (
786
+ total_input
787
+ and len(total_input) + len(round_input) > max_input_tokens
788
+ ):
789
+ break
790
+ else:
791
+ total_input = round_input + total_input
792
+ if len(total_input) >= max_input_tokens:
793
+ break
794
+ else:
795
+ round_input = []
796
+ elif message["role"] == "assistant":
797
+ round_input = (
798
+ [self.generation_config.assistant_token_id]
799
+ + content_tokens
800
+ + [self.generation_config.eos_token_id]
801
+ + round_input
802
+ )
803
+ else:
804
+ raise ValueError(f"message role not supported yet: {message['role']}")
805
+ total_input = total_input[-max_input_tokens:] # truncate left
806
+ total_input.append(self.generation_config.assistant_token_id)
807
+ total_input = torch.LongTensor([total_input]).to(self.device)
808
+ return total_input
809
+
810
+ def chat(self, tokenizer, messages: List[dict], stream=False,
811
+ generation_config: Optional[GenerationConfig]=None):
812
+ generation_config = generation_config or self.generation_config
813
+ input_ids = build_chat_input(self, tokenizer, messages, generation_config.max_new_tokens)
814
+ if stream:
815
+ streamer = TextIterStreamer(tokenizer, skip_prompt=True, skip_special_tokens=True)
816
+ Thread(target=self.generate, kwargs=dict(
817
+ inputs=input_ids, streamer=streamer,
818
+ generation_config=generation_config,
819
+ )).start()
820
+ return streamer
821
+ else:
822
+ outputs = self.generate(input_ids, generation_config=generation_config)
823
+ response = tokenizer.decode(outputs[0][len(input_ids[0]):], skip_special_tokens=True)
824
+ return response
special_tokens_map.json ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token": {
3
+ "content": "<s>",
4
+ "lstrip": false,
5
+ "normalized": true,
6
+ "rstrip": false,
7
+ "single_word": true
8
+ },
9
+ "eos_token": {
10
+ "content": "</s>",
11
+ "lstrip": false,
12
+ "normalized": true,
13
+ "rstrip": false,
14
+ "single_word": true
15
+ },
16
+ "pad_token": {
17
+ "content": "<unk>",
18
+ "lstrip": false,
19
+ "normalized": true,
20
+ "rstrip": false,
21
+ "single_word": true
22
+ },
23
+ "unk_token": {
24
+ "content": "<unk>",
25
+ "lstrip": false,
26
+ "normalized": true,
27
+ "rstrip": false,
28
+ "single_word": true
29
+ }
30
+ }
tokenization_YAYIUIE.py ADDED
@@ -0,0 +1,257 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import os
3
+ from shutil import copyfile
4
+ from typing import Any, Dict, List, Optional, Tuple
5
+
6
+ import sentencepiece as spm
7
+ from transformers.tokenization_utils import AddedToken, PreTrainedTokenizer
8
+ from transformers.utils import logging
9
+
10
+
11
+ logger = logging.get_logger(__name__)
12
+
13
+ VOCAB_FILES_NAMES = {"vocab_file": "tokenizer.model"}
14
+
15
+ PRETRAINED_VOCAB_FILES_MAP = {
16
+ "vocab_file": {},
17
+ "tokenizer_file": {},
18
+ }
19
+ PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES = {}
20
+
21
+
22
+ class YAYIUIETokenizer(PreTrainedTokenizer):
23
+ """
24
+ Construct a YAYIUIE tokenizer. Based on byte-level Byte-Pair-Encoding.
25
+
26
+ Args:
27
+ vocab_file (`str`):
28
+ Path to the vocabulary file.
29
+ """
30
+
31
+ vocab_files_names = VOCAB_FILES_NAMES
32
+ pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
33
+ max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
34
+ model_input_names = ["input_ids", "attention_mask"]
35
+
36
+ def __init__(
37
+ self,
38
+ vocab_file,
39
+ unk_token="<unk>",
40
+ bos_token="<s>",
41
+ eos_token="</s>",
42
+ pad_token=None,
43
+ sp_model_kwargs: Optional[Dict[str, Any]] = None,
44
+ add_bos_token=True,
45
+ add_eos_token=False,
46
+ clean_up_tokenization_spaces=False,
47
+ **kwargs,
48
+ ):
49
+ self.sp_model_kwargs = {} if sp_model_kwargs is None else sp_model_kwargs
50
+ bos_token = (
51
+ AddedToken(bos_token, lstrip=False, rstrip=False)
52
+ if isinstance(bos_token, str)
53
+ else bos_token
54
+ )
55
+ eos_token = (
56
+ AddedToken(eos_token, lstrip=False, rstrip=False)
57
+ if isinstance(eos_token, str)
58
+ else eos_token
59
+ )
60
+ unk_token = (
61
+ AddedToken(unk_token, lstrip=False, rstrip=False)
62
+ if isinstance(unk_token, str)
63
+ else unk_token
64
+ )
65
+ pad_token = (
66
+ AddedToken(pad_token, lstrip=False, rstrip=False)
67
+ if isinstance(pad_token, str)
68
+ else pad_token
69
+ )
70
+ super().__init__(
71
+ bos_token=bos_token,
72
+ eos_token=eos_token,
73
+ unk_token=unk_token,
74
+ pad_token=pad_token,
75
+ add_bos_token=add_bos_token,
76
+ add_eos_token=add_eos_token,
77
+ sp_model_kwargs=self.sp_model_kwargs,
78
+ clean_up_tokenization_spaces=clean_up_tokenization_spaces,
79
+ **kwargs,
80
+ )
81
+ self.vocab_file = vocab_file
82
+ self.add_bos_token = add_bos_token
83
+ self.add_eos_token = add_eos_token
84
+ self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
85
+ self.sp_model.Load(vocab_file)
86
+
87
+ def __getstate__(self):
88
+ state = self.__dict__.copy()
89
+ state["sp_model"] = None
90
+ return state
91
+
92
+ def __setstate__(self, d):
93
+ self.__dict__ = d
94
+ self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
95
+ self.sp_model.Load(self.vocab_file)
96
+
97
+ @property
98
+ def vocab_size(self):
99
+ """Returns vocab size"""
100
+ return self.sp_model.get_piece_size()
101
+
102
+ def get_vocab(self):
103
+ """Returns vocab as a dict"""
104
+ vocab = {self.convert_ids_to_tokens(i): i for i in range(self.vocab_size)}
105
+ vocab.update(self.added_tokens_encoder)
106
+ return vocab
107
+
108
+ def _tokenize(self, text):
109
+ """Returns a tokenized string."""
110
+ return self.sp_model.encode(text, out_type=str)
111
+
112
+ def _convert_token_to_id(self, token):
113
+ """Converts a token (str) in an id using the vocab."""
114
+ return self.sp_model.piece_to_id(token)
115
+
116
+ def _convert_id_to_token(self, index):
117
+ """Converts an index (integer) in a token (str) using the vocab."""
118
+ token = self.sp_model.IdToPiece(index)
119
+ return token
120
+
121
+ def convert_tokens_to_string(self, tokens):
122
+ """Converts a sequence of tokens (string) in a single string."""
123
+ current_sub_tokens = []
124
+ out_string = ""
125
+ prev_is_special = False
126
+ for i, token in enumerate(tokens):
127
+ # make sure that special tokens are not decoded using sentencepiece model
128
+ if token in self.all_special_tokens:
129
+ if not prev_is_special and i != 0:
130
+ out_string += " "
131
+ out_string += self.sp_model.decode(current_sub_tokens) + token
132
+ prev_is_special = True
133
+ current_sub_tokens = []
134
+ else:
135
+ current_sub_tokens.append(token)
136
+ prev_is_special = False
137
+ out_string += self.sp_model.decode(current_sub_tokens)
138
+ return out_string
139
+
140
+ def save_vocabulary(
141
+ self, save_directory, filename_prefix: Optional[str] = None
142
+ ) -> Tuple[str]:
143
+ """
144
+ Save the vocabulary and special tokens file to a directory.
145
+
146
+ Args:
147
+ save_directory (`str`):
148
+ The directory in which to save the vocabulary.
149
+
150
+ Returns:
151
+ `Tuple(str)`: Paths to the files saved.
152
+ """
153
+ if not os.path.isdir(save_directory):
154
+ logger.error(f"Vocabulary path ({save_directory}) should be a directory")
155
+ return
156
+ out_vocab_file = os.path.join(
157
+ save_directory,
158
+ (filename_prefix + "-" if filename_prefix else "")
159
+ + VOCAB_FILES_NAMES["vocab_file"],
160
+ )
161
+
162
+ if os.path.abspath(self.vocab_file) != os.path.abspath(
163
+ out_vocab_file
164
+ ) and os.path.isfile(self.vocab_file):
165
+ copyfile(self.vocab_file, out_vocab_file)
166
+ elif not os.path.isfile(self.vocab_file):
167
+ with open(out_vocab_file, "wb") as fi:
168
+ content_spiece_model = self.sp_model.serialized_model_proto()
169
+ fi.write(content_spiece_model)
170
+
171
+ return (out_vocab_file,)
172
+
173
+ def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None):
174
+ bos_token_id = [self.bos_token_id] if self.add_bos_token else []
175
+ eos_token_id = [self.eos_token_id] if self.add_eos_token else []
176
+
177
+ output = bos_token_id + token_ids_0 + eos_token_id
178
+
179
+ if token_ids_1 is not None:
180
+ output = output + bos_token_id + token_ids_1 + eos_token_id
181
+
182
+ return output
183
+
184
+ def get_special_tokens_mask(
185
+ self,
186
+ token_ids_0: List[int],
187
+ token_ids_1: Optional[List[int]] = None,
188
+ already_has_special_tokens: bool = False,
189
+ ) -> List[int]:
190
+ """
191
+ Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
192
+ special tokens using the tokenizer `prepare_for_model` method.
193
+
194
+ Args:
195
+ token_ids_0 (`List[int]`):
196
+ List of IDs.
197
+ token_ids_1 (`List[int]`, *optional*):
198
+ Optional second list of IDs for sequence pairs.
199
+ already_has_special_tokens (`bool`, *optional*, defaults to `False`):
200
+ Whether or not the token list is already formatted with special tokens for the model.
201
+
202
+ Returns:
203
+ `List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
204
+ """
205
+ if already_has_special_tokens:
206
+ return super().get_special_tokens_mask(
207
+ token_ids_0=token_ids_0,
208
+ token_ids_1=token_ids_1,
209
+ already_has_special_tokens=True,
210
+ )
211
+
212
+ bos_token_id = [1] if self.add_bos_token else []
213
+ eos_token_id = [1] if self.add_eos_token else []
214
+
215
+ if token_ids_1 is None:
216
+ return bos_token_id + ([0] * len(token_ids_0)) + eos_token_id
217
+ return (
218
+ bos_token_id
219
+ + ([0] * len(token_ids_0))
220
+ + eos_token_id
221
+ + bos_token_id
222
+ + ([0] * len(token_ids_1))
223
+ + eos_token_id
224
+ )
225
+
226
+ def create_token_type_ids_from_sequences(
227
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
228
+ ) -> List[int]:
229
+ """
230
+ Creates a mask from the two sequences passed to be used in a sequence-pair classification task. An ALBERT
231
+ sequence pair mask has the following format:
232
+
233
+ ```
234
+ 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1
235
+ | first sequence | second sequence |
236
+ ```
237
+
238
+ if token_ids_1 is None, only returns the first portion of the mask (0s).
239
+
240
+ Args:
241
+ token_ids_0 (`List[int]`):
242
+ List of ids.
243
+ token_ids_1 (`List[int]`, *optional*):
244
+ Optional second list of IDs for sequence pairs.
245
+
246
+ Returns:
247
+ `List[int]`: List of [token type IDs](../glossary#token-type-ids) according to the given sequence(s).
248
+ """
249
+ bos_token_id = [self.bos_token_id] if self.add_bos_token else []
250
+ eos_token_id = [self.eos_token_id] if self.add_eos_token else []
251
+
252
+ output = [0] * len(bos_token_id + token_ids_0 + eos_token_id)
253
+
254
+ if token_ids_1 is not None:
255
+ output += [1] * len(bos_token_id + token_ids_1 + eos_token_id)
256
+
257
+ return output
tokenizer_config.json ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_bos_token": false,
3
+ "add_eos_token": false,
4
+ "auto_map": {
5
+ "AutoTokenizer": [
6
+ "tokenization_YAYIUIE.YAYIUIETokenizer",
7
+ null
8
+ ]
9
+ },
10
+ "bos_token": {
11
+ "__type": "AddedToken",
12
+ "content": "<s>",
13
+ "lstrip": false,
14
+ "normalized": true,
15
+ "rstrip": false,
16
+ "single_word": true
17
+ },
18
+ "clean_up_tokenization_spaces": false,
19
+ "eos_token": {
20
+ "__type": "AddedToken",
21
+ "content": "</s>",
22
+ "lstrip": false,
23
+ "normalized": true,
24
+ "rstrip": false,
25
+ "single_word": true
26
+ },
27
+ "model_max_length": 2048,
28
+ "pad_token": {
29
+ "__type": "AddedToken",
30
+ "content": "<unk>",
31
+ "lstrip": false,
32
+ "normalized": true,
33
+ "rstrip": false,
34
+ "single_word": true
35
+ },
36
+ "sp_model_kwargs": {},
37
+ "tokenizer_class": "YAYIUIETokenizer",
38
+ "unk_token": {
39
+ "__type": "AddedToken",
40
+ "content": "<unk>",
41
+ "lstrip": false,
42
+ "normalized": true,
43
+ "rstrip": false,
44
+ "single_word": true
45
+ }
46
+ }
zero_to_fp32.py ADDED
@@ -0,0 +1,578 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+
3
+ # Copyright (c) Microsoft Corporation.
4
+ # SPDX-License-Identifier: Apache-2.0
5
+
6
+ # DeepSpeed Team
7
+
8
+ # This script extracts fp32 consolidated weights from a zero 1, 2 and 3 DeepSpeed checkpoints. It gets
9
+ # copied into the top level checkpoint dir, so the user can easily do the conversion at any point in
10
+ # the future. Once extracted, the weights don't require DeepSpeed and can be used in any
11
+ # application.
12
+ #
13
+ # example: python zero_to_fp32.py . pytorch_model.bin
14
+
15
+ import argparse
16
+ import torch
17
+ import glob
18
+ import math
19
+ import os
20
+ import re
21
+ from collections import OrderedDict
22
+ from dataclasses import dataclass
23
+
24
+ # while this script doesn't use deepspeed to recover data, since the checkpoints are pickled with
25
+ # DeepSpeed data structures it has to be available in the current python environment.
26
+ from deepspeed.utils import logger
27
+ from deepspeed.checkpoint.constants import (DS_VERSION, OPTIMIZER_STATE_DICT, SINGLE_PARTITION_OF_FP32_GROUPS,
28
+ FP32_FLAT_GROUPS, ZERO_STAGE, PARTITION_COUNT, PARAM_SHAPES, BUFFER_NAMES,
29
+ FROZEN_PARAM_SHAPES, FROZEN_PARAM_FRAGMENTS)
30
+
31
+
32
+ @dataclass
33
+ class zero_model_state:
34
+ buffers: dict()
35
+ param_shapes: dict()
36
+ shared_params: list
37
+ ds_version: int
38
+ frozen_param_shapes: dict()
39
+ frozen_param_fragments: dict()
40
+
41
+
42
+ debug = 0
43
+
44
+ # load to cpu
45
+ device = torch.device('cpu')
46
+
47
+
48
+ def atoi(text):
49
+ return int(text) if text.isdigit() else text
50
+
51
+
52
+ def natural_keys(text):
53
+ '''
54
+ alist.sort(key=natural_keys) sorts in human order
55
+ http://nedbatchelder.com/blog/200712/human_sorting.html
56
+ (See Toothy's implementation in the comments)
57
+ '''
58
+ return [atoi(c) for c in re.split(r'(\d+)', text)]
59
+
60
+
61
+ def get_model_state_file(checkpoint_dir, zero_stage):
62
+ if not os.path.isdir(checkpoint_dir):
63
+ raise FileNotFoundError(f"Directory '{checkpoint_dir}' doesn't exist")
64
+
65
+ # there should be only one file
66
+ if zero_stage <= 2:
67
+ file = os.path.join(checkpoint_dir, "mp_rank_00_model_states.pt")
68
+ elif zero_stage == 3:
69
+ file = os.path.join(checkpoint_dir, "zero_pp_rank_0_mp_rank_00_model_states.pt")
70
+
71
+ if not os.path.exists(file):
72
+ raise FileNotFoundError(f"can't find model states file at '{file}'")
73
+
74
+ return file
75
+
76
+
77
+ def get_checkpoint_files(checkpoint_dir, glob_pattern):
78
+ # XXX: need to test that this simple glob rule works for multi-node setup too
79
+ ckpt_files = sorted(glob.glob(os.path.join(checkpoint_dir, glob_pattern)), key=natural_keys)
80
+
81
+ if len(ckpt_files) == 0:
82
+ raise FileNotFoundError(f"can't find {glob_pattern} files in directory '{checkpoint_dir}'")
83
+
84
+ return ckpt_files
85
+
86
+
87
+ def get_optim_files(checkpoint_dir):
88
+ return get_checkpoint_files(checkpoint_dir, "*_optim_states.pt")
89
+
90
+
91
+ def get_model_state_files(checkpoint_dir):
92
+ return get_checkpoint_files(checkpoint_dir, "*_model_states.pt")
93
+
94
+
95
+ def parse_model_states(files):
96
+ zero_model_states = []
97
+ for file in files:
98
+ state_dict = torch.load(file, map_location=device)
99
+
100
+ if BUFFER_NAMES not in state_dict:
101
+ raise ValueError(f"{file} is not a model state checkpoint")
102
+ buffer_names = state_dict[BUFFER_NAMES]
103
+ if debug:
104
+ print("Found buffers:", buffer_names)
105
+
106
+ # recover just the buffers while restoring them to fp32 if they were saved in fp16
107
+ buffers = {k: v.float() for k, v in state_dict["module"].items() if k in buffer_names}
108
+ param_shapes = state_dict[PARAM_SHAPES]
109
+
110
+ # collect parameters that are included in param_shapes
111
+ param_names = []
112
+ for s in param_shapes:
113
+ for name in s.keys():
114
+ param_names.append(name)
115
+
116
+ # update with frozen parameters
117
+ frozen_param_shapes = state_dict.get(FROZEN_PARAM_SHAPES, None)
118
+ if frozen_param_shapes is not None:
119
+ if debug:
120
+ print(f"Found frozen_param_shapes: {frozen_param_shapes}")
121
+ param_names += list(frozen_param_shapes.keys())
122
+
123
+ # handle shared params
124
+ shared_params = [[k, v] for k, v in state_dict["shared_params"].items()]
125
+
126
+ ds_version = state_dict.get(DS_VERSION, None)
127
+
128
+ frozen_param_fragments = state_dict.get(FROZEN_PARAM_FRAGMENTS, None)
129
+
130
+ z_model_state = zero_model_state(buffers=buffers,
131
+ param_shapes=param_shapes,
132
+ shared_params=shared_params,
133
+ ds_version=ds_version,
134
+ frozen_param_shapes=frozen_param_shapes,
135
+ frozen_param_fragments=frozen_param_fragments)
136
+ zero_model_states.append(z_model_state)
137
+
138
+ return zero_model_states
139
+
140
+
141
+ def parse_optim_states(files, ds_checkpoint_dir):
142
+
143
+ total_files = len(files)
144
+ state_dicts = []
145
+ for f in files:
146
+ state_dicts.append(torch.load(f, map_location=device))
147
+
148
+ if not ZERO_STAGE in state_dicts[0][OPTIMIZER_STATE_DICT]:
149
+ raise ValueError(f"{files[0]} is not a zero checkpoint")
150
+ zero_stage = state_dicts[0][OPTIMIZER_STATE_DICT][ZERO_STAGE]
151
+ world_size = state_dicts[0][OPTIMIZER_STATE_DICT][PARTITION_COUNT]
152
+
153
+ # For ZeRO-2 each param group can have different partition_count as data parallelism for expert
154
+ # parameters can be different from data parallelism for non-expert parameters. So we can just
155
+ # use the max of the partition_count to get the dp world_size.
156
+
157
+ if type(world_size) is list:
158
+ world_size = max(world_size)
159
+
160
+ if world_size != total_files:
161
+ raise ValueError(
162
+ f"Expected {world_size} of '*_optim_states.pt' under '{ds_checkpoint_dir}' but found {total_files} files. "
163
+ "Possibly due to an overwrite of an old checkpoint, or a checkpoint didn't get saved by one or more processes."
164
+ )
165
+
166
+ # the groups are named differently in each stage
167
+ if zero_stage <= 2:
168
+ fp32_groups_key = SINGLE_PARTITION_OF_FP32_GROUPS
169
+ elif zero_stage == 3:
170
+ fp32_groups_key = FP32_FLAT_GROUPS
171
+ else:
172
+ raise ValueError(f"unknown zero stage {zero_stage}")
173
+
174
+ if zero_stage <= 2:
175
+ fp32_flat_groups = [state_dicts[i][OPTIMIZER_STATE_DICT][fp32_groups_key] for i in range(len(state_dicts))]
176
+ elif zero_stage == 3:
177
+ # if there is more than one param group, there will be multiple flattened tensors - one
178
+ # flattened tensor per group - for simplicity merge them into a single tensor
179
+ #
180
+ # XXX: could make the script more memory efficient for when there are multiple groups - it
181
+ # will require matching the sub-lists of param_shapes for each param group flattened tensor
182
+
183
+ fp32_flat_groups = [
184
+ torch.cat(state_dicts[i][OPTIMIZER_STATE_DICT][fp32_groups_key], 0) for i in range(len(state_dicts))
185
+ ]
186
+
187
+ return zero_stage, world_size, fp32_flat_groups
188
+
189
+
190
+ def _get_fp32_state_dict_from_zero_checkpoint(ds_checkpoint_dir):
191
+ """
192
+ Returns fp32 state_dict reconstructed from ds checkpoint
193
+
194
+ Args:
195
+ - ``ds_checkpoint_dir``: path to the deepspeed checkpoint folder (where the optimizer files are)
196
+
197
+ """
198
+ print(f"Processing zero checkpoint '{ds_checkpoint_dir}'")
199
+
200
+ optim_files = get_optim_files(ds_checkpoint_dir)
201
+ zero_stage, world_size, fp32_flat_groups = parse_optim_states(optim_files, ds_checkpoint_dir)
202
+ print(f"Detected checkpoint of type zero stage {zero_stage}, world_size: {world_size}")
203
+
204
+ model_files = get_model_state_files(ds_checkpoint_dir)
205
+
206
+ zero_model_states = parse_model_states(model_files)
207
+ print(f'Parsing checkpoint created by deepspeed=={zero_model_states[0].ds_version}')
208
+
209
+ if zero_stage <= 2:
210
+ return _get_fp32_state_dict_from_zero2_checkpoint(world_size, fp32_flat_groups, zero_model_states)
211
+ elif zero_stage == 3:
212
+ return _get_fp32_state_dict_from_zero3_checkpoint(world_size, fp32_flat_groups, zero_model_states)
213
+
214
+
215
+ def _zero2_merge_frozen_params(state_dict, zero_model_states):
216
+ if zero_model_states[0].frozen_param_shapes is None or len(zero_model_states[0].frozen_param_shapes) == 0:
217
+ return
218
+
219
+ frozen_param_shapes = zero_model_states[0].frozen_param_shapes
220
+ frozen_param_fragments = zero_model_states[0].frozen_param_fragments
221
+
222
+ if debug:
223
+ num_elem = sum(s.numel() for s in frozen_param_shapes.values())
224
+ print(f'rank 0: {FROZEN_PARAM_SHAPES}.numel = {num_elem}')
225
+
226
+ wanted_params = len(frozen_param_shapes)
227
+ wanted_numel = sum(s.numel() for s in frozen_param_shapes.values())
228
+ avail_numel = sum([p.numel() for p in frozen_param_fragments.values()])
229
+ print(f'Frozen params: Have {avail_numel} numels to process.')
230
+ print(f'Frozen params: Need {wanted_numel} numels in {wanted_params} params')
231
+
232
+ total_params = 0
233
+ total_numel = 0
234
+ for name, shape in frozen_param_shapes.items():
235
+ total_params += 1
236
+ unpartitioned_numel = shape.numel()
237
+ total_numel += unpartitioned_numel
238
+
239
+ state_dict[name] = frozen_param_fragments[name]
240
+
241
+ if debug:
242
+ print(f"{name} full shape: {shape} unpartitioned numel {unpartitioned_numel} ")
243
+
244
+ print(f"Reconstructed Frozen fp32 state dict with {total_params} params {total_numel} elements")
245
+
246
+
247
+ def _zero2_merge_trainable_params(state_dict, world_size, fp32_flat_groups, zero_model_states):
248
+ param_shapes = zero_model_states[0].param_shapes
249
+
250
+ # Reconstruction protocol:
251
+ #
252
+ # XXX: document this
253
+
254
+ if debug:
255
+ for i in range(world_size):
256
+ for j in range(len(fp32_flat_groups[0])):
257
+ print(f"{FP32_FLAT_GROUPS}[{i}][{j}].shape={fp32_flat_groups[i][j].shape}")
258
+
259
+ # XXX: memory usage doubles here (zero2)
260
+ num_param_groups = len(fp32_flat_groups[0])
261
+ merged_single_partition_of_fp32_groups = []
262
+ for i in range(num_param_groups):
263
+ merged_partitions = [sd[i] for sd in fp32_flat_groups]
264
+ full_single_fp32_vector = torch.cat(merged_partitions, 0)
265
+ merged_single_partition_of_fp32_groups.append(full_single_fp32_vector)
266
+ avail_numel = sum(
267
+ [full_single_fp32_vector.numel() for full_single_fp32_vector in merged_single_partition_of_fp32_groups])
268
+
269
+ if debug:
270
+ wanted_params = sum([len(shapes) for shapes in param_shapes])
271
+ wanted_numel = sum([sum(shape.numel() for shape in shapes.values()) for shapes in param_shapes])
272
+ # not asserting if there is a mismatch due to possible padding
273
+ print(f"Have {avail_numel} numels to process.")
274
+ print(f"Need {wanted_numel} numels in {wanted_params} params.")
275
+
276
+ # params
277
+ # XXX: for huge models that can't fit into the host's RAM we will have to recode this to support
278
+ # out-of-core computing solution
279
+ total_numel = 0
280
+ total_params = 0
281
+ for shapes, full_single_fp32_vector in zip(param_shapes, merged_single_partition_of_fp32_groups):
282
+ offset = 0
283
+ avail_numel = full_single_fp32_vector.numel()
284
+ for name, shape in shapes.items():
285
+
286
+ unpartitioned_numel = shape.numel()
287
+ total_numel += unpartitioned_numel
288
+ total_params += 1
289
+
290
+ if debug:
291
+ print(f"{name} full shape: {shape} unpartitioned numel {unpartitioned_numel} ")
292
+ state_dict[name] = full_single_fp32_vector.narrow(0, offset, unpartitioned_numel).view(shape)
293
+ offset += unpartitioned_numel
294
+
295
+ # Z2 started to align to 2*world_size to improve nccl performance. Therefore both offset and
296
+ # avail_numel can differ by anywhere between 0..2*world_size. Due to two unrelated complex
297
+ # paddings performed in the code it's almost impossible to predict the exact numbers w/o the
298
+ # live optimizer object, so we are checking that the numbers are within the right range
299
+ align_to = 2 * world_size
300
+
301
+ def zero2_align(x):
302
+ return align_to * math.ceil(x / align_to)
303
+
304
+ if debug:
305
+ print(f"original offset={offset}, avail_numel={avail_numel}")
306
+
307
+ offset = zero2_align(offset)
308
+ avail_numel = zero2_align(avail_numel)
309
+
310
+ if debug:
311
+ print(f"aligned offset={offset}, avail_numel={avail_numel}")
312
+
313
+ # Sanity check
314
+ if offset != avail_numel:
315
+ raise ValueError(f"consumed {offset} numels out of {avail_numel} - something is wrong")
316
+
317
+ print(f"Reconstructed fp32 state dict with {total_params} params {total_numel} elements")
318
+
319
+
320
+ def _get_fp32_state_dict_from_zero2_checkpoint(world_size, fp32_flat_groups, zero_model_states):
321
+ state_dict = OrderedDict()
322
+
323
+ # buffers
324
+ buffers = zero_model_states[0].buffers
325
+ state_dict.update(buffers)
326
+ if debug:
327
+ print(f"added {len(buffers)} buffers")
328
+
329
+ _zero2_merge_frozen_params(state_dict, zero_model_states)
330
+
331
+ _zero2_merge_trainable_params(state_dict, world_size, fp32_flat_groups, zero_model_states)
332
+
333
+ # recover shared parameters
334
+ for pair in zero_model_states[0].shared_params:
335
+ if pair[1] in state_dict:
336
+ state_dict[pair[0]] = state_dict[pair[1]]
337
+
338
+ return state_dict
339
+
340
+
341
+ def zero3_partitioned_param_info(unpartitioned_numel, world_size):
342
+ remainder = unpartitioned_numel % world_size
343
+ padding_numel = (world_size - remainder) if remainder else 0
344
+ partitioned_numel = math.ceil(unpartitioned_numel / world_size)
345
+ return partitioned_numel, padding_numel
346
+
347
+
348
+ def _zero3_merge_frozen_params(state_dict, world_size, zero_model_states):
349
+ if zero_model_states[0].frozen_param_shapes is None or len(zero_model_states[0].frozen_param_shapes) == 0:
350
+ return
351
+
352
+ if debug:
353
+ for i in range(world_size):
354
+ num_elem = sum(s.numel() for s in zero_model_states[i].frozen_param_fragments.values())
355
+ print(f'rank {i}: {FROZEN_PARAM_SHAPES}.numel = {num_elem}')
356
+
357
+ frozen_param_shapes = zero_model_states[0].frozen_param_shapes
358
+ wanted_params = len(frozen_param_shapes)
359
+ wanted_numel = sum(s.numel() for s in frozen_param_shapes.values())
360
+ avail_numel = sum([p.numel() for p in zero_model_states[0].frozen_param_fragments.values()]) * world_size
361
+ print(f'Frozen params: Have {avail_numel} numels to process.')
362
+ print(f'Frozen params: Need {wanted_numel} numels in {wanted_params} params')
363
+
364
+ total_params = 0
365
+ total_numel = 0
366
+ for name, shape in zero_model_states[0].frozen_param_shapes.items():
367
+ total_params += 1
368
+ unpartitioned_numel = shape.numel()
369
+ total_numel += unpartitioned_numel
370
+
371
+ param_frags = tuple(model_state.frozen_param_fragments[name] for model_state in zero_model_states)
372
+ state_dict[name] = torch.cat(param_frags, 0).narrow(0, 0, unpartitioned_numel).view(shape)
373
+
374
+ partitioned_numel, partitioned_padding_numel = zero3_partitioned_param_info(unpartitioned_numel, world_size)
375
+
376
+ if debug:
377
+ print(
378
+ f"Frozen params: {total_params} {name} full shape: {shape} partition0 numel={partitioned_numel} partitioned_padding_numel={partitioned_padding_numel}"
379
+ )
380
+
381
+ print(f"Reconstructed Frozen fp32 state dict with {total_params} params {total_numel} elements")
382
+
383
+
384
+ def _zero3_merge_trainable_params(state_dict, world_size, fp32_flat_groups, zero_model_states):
385
+ param_shapes = zero_model_states[0].param_shapes
386
+ avail_numel = fp32_flat_groups[0].numel() * world_size
387
+ # Reconstruction protocol: For zero3 we need to zip the partitions together at boundary of each
388
+ # param, re-consolidating each param, while dealing with padding if any
389
+
390
+ # merge list of dicts, preserving order
391
+ param_shapes = {k: v for d in param_shapes for k, v in d.items()}
392
+
393
+ if debug:
394
+ for i in range(world_size):
395
+ print(f"{FP32_FLAT_GROUPS}[{i}].shape={fp32_flat_groups[i].shape}")
396
+
397
+ wanted_params = len(param_shapes)
398
+ wanted_numel = sum(shape.numel() for shape in param_shapes.values())
399
+ # not asserting if there is a mismatch due to possible padding
400
+ avail_numel = fp32_flat_groups[0].numel() * world_size
401
+ print(f"Trainable params: Have {avail_numel} numels to process.")
402
+ print(f"Trainable params: Need {wanted_numel} numels in {wanted_params} params.")
403
+
404
+ # params
405
+ # XXX: for huge models that can't fit into the host's RAM we will have to recode this to support
406
+ # out-of-core computing solution
407
+ offset = 0
408
+ total_numel = 0
409
+ total_params = 0
410
+ for name, shape in param_shapes.items():
411
+
412
+ unpartitioned_numel = shape.numel()
413
+ total_numel += unpartitioned_numel
414
+ total_params += 1
415
+
416
+ partitioned_numel, partitioned_padding_numel = zero3_partitioned_param_info(unpartitioned_numel, world_size)
417
+
418
+ if debug:
419
+ print(
420
+ f"Trainable params: {total_params} {name} full shape: {shape} partition0 numel={partitioned_numel} partitioned_padding_numel={partitioned_padding_numel}"
421
+ )
422
+
423
+ # XXX: memory usage doubles here
424
+ state_dict[name] = torch.cat(
425
+ tuple(fp32_flat_groups[i].narrow(0, offset, partitioned_numel) for i in range(world_size)),
426
+ 0).narrow(0, 0, unpartitioned_numel).view(shape)
427
+ offset += partitioned_numel
428
+
429
+ offset *= world_size
430
+
431
+ # Sanity check
432
+ if offset != avail_numel:
433
+ raise ValueError(f"consumed {offset} numels out of {avail_numel} - something is wrong")
434
+
435
+ print(f"Reconstructed Trainable fp32 state dict with {total_params} params {total_numel} elements")
436
+
437
+
438
+ def _get_fp32_state_dict_from_zero3_checkpoint(world_size, fp32_flat_groups, zero_model_states):
439
+ state_dict = OrderedDict()
440
+
441
+ # buffers
442
+ buffers = zero_model_states[0].buffers
443
+ state_dict.update(buffers)
444
+ if debug:
445
+ print(f"added {len(buffers)} buffers")
446
+
447
+ _zero3_merge_frozen_params(state_dict, world_size, zero_model_states)
448
+
449
+ _zero3_merge_trainable_params(state_dict, world_size, fp32_flat_groups, zero_model_states)
450
+
451
+ # recover shared parameters
452
+ for pair in zero_model_states[0].shared_params:
453
+ if pair[1] in state_dict:
454
+ state_dict[pair[0]] = state_dict[pair[1]]
455
+
456
+ return state_dict
457
+
458
+
459
+ def get_fp32_state_dict_from_zero_checkpoint(checkpoint_dir, tag=None):
460
+ """
461
+ Convert ZeRO 2 or 3 checkpoint into a single fp32 consolidated state_dict that can be loaded with
462
+ ``load_state_dict()`` and used for training without DeepSpeed or shared with others, for example
463
+ via a model hub.
464
+
465
+ Args:
466
+ - ``checkpoint_dir``: path to the desired checkpoint folder
467
+ - ``tag``: checkpoint tag used as a unique identifier for checkpoint. If not provided will attempt to load tag in 'latest' file. e.g., ``global_step14``
468
+
469
+ Returns:
470
+ - pytorch ``state_dict``
471
+
472
+ Note: this approach may not work if your application doesn't have sufficient free CPU memory and
473
+ you may need to use the offline approach using the ``zero_to_fp32.py`` script that is saved with
474
+ the checkpoint.
475
+
476
+ A typical usage might be ::
477
+
478
+ from deepspeed.utils.zero_to_fp32 import get_fp32_state_dict_from_zero_checkpoint
479
+ # do the training and checkpoint saving
480
+ state_dict = get_fp32_state_dict_from_zero_checkpoint(checkpoint_dir) # already on cpu
481
+ model = model.cpu() # move to cpu
482
+ model.load_state_dict(state_dict)
483
+ # submit to model hub or save the model to share with others
484
+
485
+ In this example the ``model`` will no longer be usable in the deepspeed context of the same
486
+ application. i.e. you will need to re-initialize the deepspeed engine, since
487
+ ``model.load_state_dict(state_dict)`` will remove all the deepspeed magic from it.
488
+
489
+ If you want it all done for you, use ``load_state_dict_from_zero_checkpoint`` instead.
490
+
491
+ """
492
+ if tag is None:
493
+ latest_path = os.path.join(checkpoint_dir, 'latest')
494
+ if os.path.isfile(latest_path):
495
+ with open(latest_path, 'r') as fd:
496
+ tag = fd.read().strip()
497
+ else:
498
+ raise ValueError(f"Unable to find 'latest' file at {latest_path}")
499
+
500
+ ds_checkpoint_dir = os.path.join(checkpoint_dir, tag)
501
+
502
+ if not os.path.isdir(ds_checkpoint_dir):
503
+ raise FileNotFoundError(f"Directory '{ds_checkpoint_dir}' doesn't exist")
504
+
505
+ return _get_fp32_state_dict_from_zero_checkpoint(ds_checkpoint_dir)
506
+
507
+
508
+ def convert_zero_checkpoint_to_fp32_state_dict(checkpoint_dir, output_file, tag=None):
509
+ """
510
+ Convert ZeRO 2 or 3 checkpoint into a single fp32 consolidated ``state_dict`` file that can be
511
+ loaded with ``torch.load(file)`` + ``load_state_dict()`` and used for training without DeepSpeed.
512
+
513
+ Args:
514
+ - ``checkpoint_dir``: path to the desired checkpoint folder. (one that contains the tag-folder, like ``global_step14``)
515
+ - ``output_file``: path to the pytorch fp32 state_dict output file (e.g. path/pytorch_model.bin)
516
+ - ``tag``: checkpoint tag used as a unique identifier for checkpoint. If not provided will attempt to load tag in the file named ``latest`` in the checkpoint folder, e.g., ``global_step14``
517
+ """
518
+
519
+ state_dict = get_fp32_state_dict_from_zero_checkpoint(checkpoint_dir, tag)
520
+ print(f"Saving fp32 state dict to {output_file}")
521
+ torch.save(state_dict, output_file)
522
+
523
+
524
+ def load_state_dict_from_zero_checkpoint(model, checkpoint_dir, tag=None):
525
+ """
526
+ 1. Put the provided model to cpu
527
+ 2. Convert ZeRO 2 or 3 checkpoint into a single fp32 consolidated ``state_dict``
528
+ 3. Load it into the provided model
529
+
530
+ Args:
531
+ - ``model``: the model object to update
532
+ - ``checkpoint_dir``: path to the desired checkpoint folder. (one that contains the tag-folder, like ``global_step14``)
533
+ - ``tag``: checkpoint tag used as a unique identifier for checkpoint. If not provided will attempt to load tag in the file named ``latest`` in the checkpoint folder, e.g., ``global_step14``
534
+
535
+ Returns:
536
+ - ``model`: modified model
537
+
538
+ Make sure you have plenty of CPU memory available before you call this function. If you don't
539
+ have enough use the ``zero_to_fp32.py`` utility to do the conversion. You will find it
540
+ conveniently placed for you in the checkpoint folder.
541
+
542
+ A typical usage might be ::
543
+
544
+ from deepspeed.utils.zero_to_fp32 import load_state_dict_from_zero_checkpoint
545
+ model = load_state_dict_from_zero_checkpoint(trainer.model, checkpoint_dir)
546
+ # submit to model hub or save the model to share with others
547
+
548
+ Note, that once this was run, the ``model`` will no longer be usable in the deepspeed context
549
+ of the same application. i.e. you will need to re-initialize the deepspeed engine, since
550
+ ``model.load_state_dict(state_dict)`` will remove all the deepspeed magic from it.
551
+
552
+ """
553
+ logger.info(f"Extracting fp32 weights")
554
+ state_dict = get_fp32_state_dict_from_zero_checkpoint(checkpoint_dir, tag)
555
+
556
+ logger.info(f"Overwriting model with fp32 weights")
557
+ model = model.cpu()
558
+ model.load_state_dict(state_dict, strict=False)
559
+
560
+ return model
561
+
562
+
563
+ if __name__ == "__main__":
564
+
565
+ parser = argparse.ArgumentParser()
566
+ parser.add_argument("checkpoint_dir",
567
+ type=str,
568
+ help="path to the desired checkpoint folder, e.g., path/checkpoint-12")
569
+ parser.add_argument(
570
+ "output_file",
571
+ type=str,
572
+ help="path to the pytorch fp32 state_dict output file (e.g. path/checkpoint-12/pytorch_model.bin)")
573
+ parser.add_argument("-d", "--debug", action='store_true', help="enable debug")
574
+ args = parser.parse_args()
575
+
576
+ debug = args.debug
577
+
578
+ convert_zero_checkpoint_to_fp32_state_dict(args.checkpoint_dir, args.output_file)