fredzzp commited on
Commit
78f3e43
·
verified ·
1 Parent(s): bc4e288

Initial model upload with self-contained custom code

Browse files
Files changed (1) hide show
  1. modeling_qwen2.py +118 -505
modeling_qwen2.py CHANGED
@@ -1,517 +1,130 @@
1
- # Copyright 2024 The Qwen team, Alibaba Group and The HuggingFace Inc. team. All rights reserved.
2
- #
3
- # Licensed under the Apache License, Version 2.0 (the "License");
4
- # you may not use this file except in compliance with the License.
5
- # You may obtain a copy of the License at
6
- #
7
- # http://www.apache.org/licenses/LICENSE-2.0
8
- #
9
- # Unless required by applicable law or agreed to in writing, software
10
- # distributed under the License is distributed on an "AS IS" BASIS,
11
- # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
- # See the License for the specific language governing permissions and
13
- # limitations under the License.
14
-
15
- # This is a cleaned version of the model script for public release.
16
- # It imports the MDMGenerationMixin from the accompanying generation_utils.py file.
17
-
18
- import logging
19
- from typing import Any, Callable, Dict, List, Optional, Tuple, Union
20
-
21
- import torch
22
- from torch import nn
23
- from transformers.activations import ACT2FN
24
- from transformers.cache_utils import Cache, DynamicCache, SlidingWindowCache, StaticCache
25
- from transformers.modeling_attn_mask_utils import AttentionMaskConverter
26
- from transformers.modeling_flash_attention_utils import FlashAttentionKwargs
27
- from transformers.modeling_outputs import (
28
- BaseModelOutputWithPast,
29
- CausalLMOutputWithPast,
30
- )
31
- from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS
32
- from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
33
- from transformers.models.qwen2.configuration_qwen2 import Qwen2Config
34
- from transformers.processing_utils import Unpack
35
- from transformers.utils import (
36
- add_start_docstrings,
37
- add_start_docstrings_to_model_forward,
38
- replace_return_docstrings,
39
- )
40
-
41
- # Import the custom generation mixin from the local file in the repo
42
- from .generation_utils import MDMGenerationMixin
43
-
44
- logger = logging.getLogger(__name__)
45
-
46
- _CHECKPOINT_FOR_DOC = "meta-qwen2/Qwen2-2-7b-hf"
47
- _CONFIG_FOR_DOC = "Qwen2Config"
48
-
49
-
50
- class Qwen2MLP(nn.Module):
51
- def __init__(self, config):
52
- super().__init__()
53
- self.config = config
54
- self.hidden_size = config.hidden_size
55
- self.intermediate_size = config.intermediate_size
56
- self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
57
- self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
58
- self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
59
- self.act_fn = ACT2FN[config.hidden_act]
60
-
61
- def forward(self, x):
62
- down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
63
- return down_proj
64
-
65
-
66
- def rotate_half(x):
67
- """Rotates half the hidden dims of the input."""
68
- x1 = x[..., : x.shape[-1] // 2]
69
- x2 = x[..., x.shape[-1] // 2 :]
70
- return torch.cat((-x2, x1), dim=-1)
71
-
72
-
73
- def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
74
- cos = cos.unsqueeze(unsqueeze_dim)
75
- sin = sin.unsqueeze(unsqueeze_dim)
76
- q_embed = (q * cos) + (rotate_half(q) * sin)
77
- k_embed = (k * cos) + (rotate_half(k) * sin)
78
- return q_embed, k_embed
79
-
80
-
81
- def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
82
- """
83
- This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
84
- num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
85
- """
86
- batch, num_key_value_heads, slen, head_dim = hidden_states.shape
87
- if n_rep == 1:
88
- return hidden_states
89
- hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
90
- return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
91
-
92
-
93
- class Qwen2Attention(nn.Module):
94
- # ... (rest of the class is unchanged)
95
- def __init__(self, config: Qwen2Config, layer_idx: int):
96
- super().__init__()
97
- self.config = config
98
- self.layer_idx = layer_idx
99
- self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
100
- self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
101
- self.scaling = self.head_dim**-0.5
102
- self.attention_dropout = config.attention_dropout
103
- self.q_proj = nn.Linear(config.hidden_size, config.num_attention_heads * self.head_dim, bias=True)
104
- self.k_proj = nn.Linear(config.hidden_size, config.num_key_value_heads * self.head_dim, bias=True)
105
- self.v_proj = nn.Linear(config.hidden_size, config.num_key_value_heads * self.head_dim, bias=True)
106
- self.o_proj = nn.Linear(config.num_attention_heads * self.head_dim, config.hidden_size, bias=False)
107
-
108
- def forward(
109
- self,
110
- hidden_states: torch.Tensor,
111
- position_embeddings: Tuple[torch.Tensor, torch.Tensor],
112
- attention_mask: Optional[torch.Tensor],
113
- past_key_value: Optional[Cache] = None,
114
- output_attentions: Optional[bool] = False,
115
- cache_position: Optional[torch.LongTensor] = None,
116
- is_causal: bool = True,
117
- **kwargs: Unpack[FlashAttentionKwargs],
118
- ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
119
- bsz, q_len, _ = hidden_states.size()
120
- hidden_shape = (bsz, q_len, -1, self.head_dim)
121
-
122
- query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
123
- key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
124
- value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
125
-
126
- full_q_len = query_states.size(2)
127
- cos, sin = position_embeddings
128
- query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
129
-
130
- if past_key_value is not None:
131
- cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
132
- key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
133
-
134
- attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get(self.config._attn_implementation, None)
135
- if attention_interface is None:
136
- raise ValueError(f"Attention implementation {self.config._attn_implementation} not found.")
137
-
138
- if self.config._attn_implementation == "sdpa" and output_attentions:
139
- logger.warning_once("Using SDPA with `output_attentions=True` requires eager attention.")
140
- attention_interface = ALL_ATTENTION_FUNCTIONS["eager"]
141
-
142
-
143
- attn_output, attn_weights = attention_interface(
144
- query_states,
145
- key_states,
146
- value_states,
147
- attention_mask=attention_mask,
148
- dropout=self.attention_dropout if self.training else 0.0,
149
- is_causal=is_causal,
150
- **kwargs,
151
- )
152
- attn_output = attn_output.transpose(1, 2).contiguous()
153
- attn_output = attn_output.reshape(bsz, q_len, self.config.hidden_size)
154
- attn_output = self.o_proj(attn_output)
155
-
156
- if not output_attentions:
157
- attn_weights = None
158
-
159
- return attn_output, attn_weights, past_key_value
160
-
161
- # ... (Qwen2RMSNorm, Qwen2DecoderLayer, Qwen2RotaryEmbedding, Qwen2PreTrainedModel, Qwen2Model are unchanged)
162
- class Qwen2RMSNorm(nn.Module):
163
- def __init__(self, hidden_size, eps=1e-6):
164
- super().__init__()
165
- self.weight = nn.Parameter(torch.ones(hidden_size))
166
- self.variance_epsilon = eps
167
-
168
- def forward(self, hidden_states):
169
- input_dtype = hidden_states.dtype
170
- hidden_states = hidden_states.to(torch.float32)
171
- variance = hidden_states.pow(2).mean(-1, keepdim=True)
172
- hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
173
- return self.weight * hidden_states.to(input_dtype)
174
-
175
- class Qwen2DecoderLayer(nn.Module):
176
- def __init__(self, config: Qwen2Config, layer_idx: int):
177
- super().__init__()
178
- self.hidden_size = config.hidden_size
179
- self.self_attn = Qwen2Attention(config=config, layer_idx=layer_idx)
180
- self.mlp = Qwen2MLP(config)
181
- self.input_layernorm = Qwen2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
182
- self.post_attention_layernorm = Qwen2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
183
-
184
- def forward(
185
- self,
186
- hidden_states: torch.Tensor,
187
- attention_mask: Optional[torch.Tensor] = None,
188
- position_ids: Optional[torch.LongTensor] = None,
189
- past_key_value: Optional[Cache] = None,
190
- output_attentions: Optional[bool] = False,
191
- use_cache: Optional[bool] = False,
192
- cache_position: Optional[torch.LongTensor] = None,
193
- position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
194
- is_causal: bool = True,
195
- **kwargs: Unpack[FlashAttentionKwargs],
196
- ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
197
- residual = hidden_states
198
- hidden_states = self.input_layernorm(hidden_states)
199
-
200
- hidden_states, self_attn_weights, present_key_value = self.self_attn(
201
- hidden_states=hidden_states,
202
- attention_mask=attention_mask,
203
- past_key_value=past_key_value,
204
- output_attentions=output_attentions,
205
- cache_position=cache_position,
206
- position_embeddings=position_embeddings,
207
- is_causal=is_causal,
208
- **kwargs,
209
- )
210
- hidden_states = residual + hidden_states
211
-
212
- residual = hidden_states
213
- hidden_states = self.post_attention_layernorm(hidden_states)
214
- hidden_states = self.mlp(hidden_states)
215
- hidden_states = residual + hidden_states
216
-
217
- outputs = (hidden_states,)
218
- if output_attentions:
219
- outputs += (self_attn_weights,)
220
- if use_cache:
221
- outputs += (present_key_value,)
222
-
223
- return outputs
224
-
225
- class Qwen2RotaryEmbedding(nn.Module):
226
- def __init__(self, config: Qwen2Config, device=None):
227
- super().__init__()
228
- if hasattr(config, "rope_scaling") and config.rope_scaling is not None:
229
- self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))
230
- else:
231
- self.rope_type = "default"
232
- self.max_seq_len_cached = config.max_position_embeddings
233
- self.original_max_seq_len = config.max_position_embeddings
234
- self.config = config
235
- self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
236
- inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device)
237
- self.register_buffer("inv_freq", inv_freq, persistent=False)
238
- self.original_inv_freq = self.inv_freq
239
-
240
- def _dynamic_frequency_update(self, position_ids, device):
241
- seq_len = torch.max(position_ids) + 1
242
- if seq_len > self.max_seq_len_cached:
243
- inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device, seq_len=seq_len)
244
- self.register_buffer("inv_freq", inv_freq, persistent=False)
245
- self.max_seq_len_cached = seq_len
246
- if seq_len < self.original_max_seq_len and self.max_seq_len_cached > self.original_max_seq_len:
247
- self.original_inv_freq = self.original_inv_freq.to(device)
248
- self.register_buffer("inv_freq", self.original_inv_freq, persistent=False)
249
- self.max_seq_len_cached = self.original_max_seq_len
250
-
251
- @torch.no_grad()
252
- def forward(self, x, position_ids):
253
- if "dynamic" in self.rope_type:
254
- self._dynamic_frequency_update(position_ids, device=x.device)
255
- inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
256
- position_ids_expanded = position_ids[:, None, :].float()
257
- device_type = x.device.type
258
- device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu"
259
- with torch.autocast(device_type=device_type, enabled=False):
260
- freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
261
- emb = torch.cat((freqs, freqs), dim=-1)
262
- cos = emb.cos()
263
- sin = emb.sin()
264
- cos = cos * self.attention_scaling
265
- sin = sin * self.attention_scaling
266
- return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
267
-
268
- @add_start_docstrings(
269
- "The bare Qwen2 Model outputting raw hidden-states without any specific head on top.",
270
- QWEN2_START_DOCSTRING,
271
- )
272
- class Qwen2PreTrainedModel(PreTrainedModel):
273
- config_class = Qwen2Config
274
- base_model_prefix = "model"
275
- supports_gradient_checkpointing = True
276
- _no_split_modules = ["Qwen2DecoderLayer"]
277
- _skip_keys_device_placement = ["past_key_values"]
278
- _supports_flash_attn_2 = True
279
- _supports_sdpa = True
280
- _supports_cache_class = True
281
-
282
- def _init_weights(self, module):
283
- std = self.config.initializer_range
284
- if isinstance(module, nn.Linear):
285
- module.weight.data.normal_(mean=0.0, std=std)
286
- if module.bias is not None:
287
- module.bias.data.zero_()
288
- elif isinstance(module, nn.Embedding):
289
- module.weight.data.normal_(mean=0.0, std=std)
290
- if module.padding_idx is not None:
291
- module.weight.data[module.padding_idx].zero_()
292
-
293
- class Qwen2Model(Qwen2PreTrainedModel):
294
- def __init__(self, config: Qwen2Config):
295
- super().__init__(config)
296
- self.padding_idx = config.pad_token_id
297
- self.vocab_size = config.vocab_size
298
- self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
299
- self.layers = nn.ModuleList(
300
- [Qwen2DecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
301
- )
302
- self.norm = Qwen2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
303
- self.rotary_emb = Qwen2RotaryEmbedding(config=config)
304
- self.gradient_checkpointing = False
305
- self.post_init()
306
-
307
- def get_input_embeddings(self):
308
- return self.embed_tokens
309
-
310
- def set_input_embeddings(self, value):
311
- self.embed_tokens = value
312
-
313
- def forward(
314
- self,
315
- input_ids: torch.LongTensor = None,
316
- attention_mask: Optional[torch.Tensor] = None,
317
- position_ids: Optional[torch.LongTensor] = None,
318
- past_key_values: Optional[Cache] = None,
319
- inputs_embeds: Optional[torch.FloatTensor] = None,
320
- use_cache: Optional[bool] = None,
321
- output_attentions: Optional[bool] = None,
322
- output_hidden_states: Optional[bool] = None,
323
- return_dict: Optional[bool] = None,
324
- cache_position: Optional[torch.LongTensor] = None,
325
- is_causal: bool = True,
326
- **flash_attn_kwargs: Unpack[FlashAttentionKwargs],
327
- ) -> Union[Tuple, BaseModelOutputWithPast]:
328
- output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
329
- output_hidden_states = (
330
- output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
331
- )
332
- use_cache = use_cache if use_cache is not None else self.config.use_cache
333
- return_dict = return_dict if return_dict is not None else self.config.use_return_dict
334
-
335
- if (input_ids is None) ^ (inputs_embeds is not None):
336
- raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
337
- if self.gradient_checkpointing and self.training and use_cache:
338
- logger.warning_once("`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`.")
339
- use_cache = False
340
- if inputs_embeds is None:
341
- inputs_embeds = self.embed_tokens(input_ids)
342
-
343
- past_key_values_length = 0
344
- if use_cache:
345
- if past_key_values is None:
346
- past_key_values = DynamicCache()
347
- past_key_values_length = past_key_values.get_seq_length()
348
-
349
- if cache_position is None:
350
- cache_position = torch.arange(
351
- past_key_values_length, past_key_values_length + inputs_embeds.shape[1], device=inputs_embeds.device
352
- )
353
- if position_ids is None:
354
- position_ids = cache_position.unsqueeze(0)
355
-
356
- causal_mask = self._update_causal_mask(attention_mask, inputs_embeds, cache_position, is_causal)
357
- hidden_states = inputs_embeds
358
- position_embeddings = self.rotary_emb(hidden_states, position_ids)
359
- all_hidden_states = () if output_hidden_states else None
360
- all_self_attns = () if output_attentions else None
361
- next_decoder_cache = () if use_cache else None
362
-
363
- for decoder_layer in self.layers:
364
- if output_hidden_states:
365
- all_hidden_states += (hidden_states,)
366
-
367
- layer_outputs = decoder_layer(
368
- hidden_states,
369
- attention_mask=causal_mask,
370
- position_ids=position_ids,
371
- past_key_value=past_key_values,
372
- output_attentions=output_attentions,
373
- use_cache=use_cache,
374
- cache_position=cache_position,
375
- position_embeddings=position_embeddings,
376
- is_causal=is_causal,
377
- **flash_attn_kwargs,
378
- )
379
- hidden_states = layer_outputs[0]
380
- if use_cache:
381
- next_decoder_cache += (layer_outputs[2 if output_attentions else 1],)
382
- if output_attentions:
383
- all_self_attns += (layer_outputs[1],)
384
-
385
- hidden_states = self.norm(hidden_states)
386
- if output_hidden_states:
387
- all_hidden_states += (hidden_states,)
388
 
389
- next_cache = next_decoder_cache if use_cache else None
 
 
390
 
391
- if not return_dict:
392
- return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
393
- return BaseModelOutputWithPast(
394
- last_hidden_state=hidden_states,
395
- past_key_values=next_cache,
396
- hidden_states=all_hidden_states,
397
- attentions=all_self_attns,
398
- )
399
-
400
- def _update_causal_mask(self, attention_mask, input_tensor, cache_position, is_causal):
401
- if not is_causal:
402
- return attention_mask
403
 
404
- seq_len = input_tensor.shape[1]
405
- if self.config._attn_implementation == "flash_attention_2":
406
- if attention_mask is not None and 0.0 in attention_mask:
407
- return attention_mask
408
- return None
409
 
410
- dtype = input_tensor.dtype
411
- device = input_tensor.device
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
412
 
413
- causal_mask = torch.triu(torch.full((seq_len, seq_len), torch.finfo(dtype).min, device=device), 1)
414
- causal_mask = causal_mask[None, None, :, :].expand(input_tensor.shape[0], 1, -1, -1)
415
 
416
- if attention_mask is not None:
417
- causal_mask = causal_mask.clone()
418
- causal_mask = causal_mask + attention_mask[:, None, None, :]
419
-
420
- return causal_mask
421
-
422
- class Qwen2ForCausalLM(Qwen2PreTrainedModel, MDMGenerationMixin):
423
- _tied_weights_keys = ["lm_head.weight"]
424
-
425
- def __init__(self, config):
426
- super().__init__(config)
427
- self.model = Qwen2Model(config)
428
- self.vocab_size = config.vocab_size
429
- self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
430
- self.post_init()
431
-
432
- def get_input_embeddings(self):
433
- return self.model.embed_tokens
434
-
435
- def set_input_embeddings(self, value):
436
- self.model.embed_tokens = value
437
-
438
- def get_output_embeddings(self):
439
- return self.lm_head
440
 
441
- def set_output_embeddings(self, new_embeddings):
442
- self.lm_head = new_embeddings
443
-
444
- def set_decoder(self, decoder):
445
- self.model = decoder
446
-
447
- def get_decoder(self):
448
- return self.model
449
-
450
- @add_start_docstrings_to_model_forward(QWEN2_INPUTS_DOCSTRING)
451
- @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
452
- def forward(
453
- self,
454
- input_ids: torch.LongTensor = None,
455
- attention_mask: Optional[torch.Tensor] = None,
456
- position_ids: Optional[torch.LongTensor] = None,
457
- past_key_values: Optional[Cache] = None,
458
- inputs_embeds: Optional[torch.FloatTensor] = None,
459
- labels: Optional[torch.LongTensor] = None,
460
- use_cache: Optional[bool] = None,
461
- output_attentions: Optional[bool] = None,
462
- output_hidden_states: Optional[bool] = None,
463
- return_dict: Optional[bool] = None,
464
- cache_position: Optional[torch.LongTensor] = None,
465
- is_causal: bool = True,
466
- **kwargs: Unpack[FlashAttentionKwargs],
467
- ) -> Union[Tuple, CausalLMOutputWithPast]:
468
- output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
469
- output_hidden_states = (
470
- output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
471
- )
472
- return_dict = return_dict if return_dict is not None else self.config.use_return_dict
473
-
474
- outputs = self.model(
475
- input_ids=input_ids,
476
- attention_mask=attention_mask,
477
- position_ids=position_ids,
478
- past_key_values=past_key_values,
479
- inputs_embeds=inputs_embeds,
480
- use_cache=use_cache,
481
- output_attentions=output_attentions,
482
- output_hidden_states=output_hidden_states,
483
- return_dict=return_dict,
484
- cache_position=cache_position,
485
- is_causal=is_causal,
486
- **kwargs,
487
- )
488
-
489
- hidden_states = outputs[0]
490
- logits = self.lm_head(hidden_states)
491
- logits = logits.float()
492
- loss = None
493
-
494
- if labels is not None:
495
- shift_logits = logits[..., :-1, :].contiguous()
496
- shift_labels = labels[..., 1:].contiguous()
497
- loss_fct = torch.nn.CrossEntropyLoss()
498
- shift_logits = shift_logits.view(-1, self.config.vocab_size)
499
- shift_labels = shift_labels.view(-1)
500
- shift_labels = shift_labels.to(shift_logits.device)
501
- loss = loss_fct(shift_logits, shift_labels)
502
 
503
- if not return_dict:
504
- output = (logits,) + outputs[1:]
505
- return (loss,) + output if loss is not None else output
506
 
507
- return CausalLMOutputWithPast(
508
- loss=loss,
509
- logits=logits,
510
- past_key_values=outputs.past_key_values,
511
- hidden_states=outputs.hidden_states,
512
- attentions=outputs.attentions,
513
  )
 
 
514
 
515
- ModelClass = Qwen2ForCausalLM
 
 
 
 
516
 
517
- __all__ = ["Qwen2ForCausalLM", "Qwen2Model", "Qwen2PreTrainedModel"]
 
 
1
+ import argparse
2
+ import json
3
+ import os
4
+ import shutil
5
+ import sys
6
+ from pathlib import Path
7
+
8
+ from huggingface_hub import create_repo, upload_folder
9
+
10
+ def main():
11
+ """Main function to handle model preparation and upload."""
12
+ parser = argparse.ArgumentParser(
13
+ description="Upload a custom Hugging Face model with its self-contained code."
14
+ )
15
+ parser.add_argument(
16
+ "--model_code_path",
17
+ type=str,
18
+ required=True,
19
+ help="Path to the self-contained, single Python model file.",
20
+ )
21
+ parser.add_argument(
22
+ "--ckpt_dir",
23
+ type=str,
24
+ required=True,
25
+ help="Directory containing the model weights and tokenizer files (hf_ckpt).",
26
+ )
27
+ parser.add_argument(
28
+ "--repo",
29
+ type=str,
30
+ required=True,
31
+ help="Name of the repository on Hugging Face Hub (e.g., 'username/repo-name').",
32
+ )
33
+ parser.add_argument(
34
+ "--readme_path",
35
+ type=str,
36
+ required=True,
37
+ help="Path to the README.md file to be included in the repository.",
38
+ )
39
+ parser.add_argument(
40
+ "--private",
41
+ action="store_true",
42
+ help="If set, creates a private repository.",
43
+ )
44
+
45
+ args = parser.parse_args()
46
+
47
+ staging_dir = Path("./temp_upload_staging")
48
+ if staging_dir.exists():
49
+ shutil.rmtree(staging_dir)
50
+ staging_dir.mkdir()
51
+ print(f"Created temporary staging directory: {staging_dir}")
52
+
53
+ try:
54
+ # --- 2. Copy All Necessary Files ---
55
+ print("\nCopying files to staging directory...")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
56
 
57
+ # Copy checkpoint files
58
+ for f in os.listdir(args.ckpt_dir):
59
+ shutil.copy(os.path.join(args.ckpt_dir, f), staging_dir)
60
 
61
+ # Copy the single, self-contained model code file
62
+ model_code_source = Path(args.model_code_path)
63
+ if not model_code_source.exists():
64
+ print(f"Error: Model code file not found at {model_code_source}")
65
+ sys.exit(1)
 
 
 
 
 
 
 
66
 
67
+ # The destination file MUST be named correctly for auto_map to work.
68
+ model_code_dest = staging_dir / "modeling_qwen2.py"
69
+ print(f"Copying model code from {model_code_source} to {model_code_dest}")
70
+ shutil.copy(model_code_source, model_code_dest)
 
71
 
72
+ print("File copying complete.")
73
+
74
+ # --- 3. Configure `config.json` for Auto-Loading ---
75
+ print("\nConfiguring config.json for auto-loading...")
76
+ config_path = staging_dir / "config.json"
77
+ if not config_path.exists():
78
+ print(f"Error: config.json not found in {args.ckpt_dir}")
79
+ sys.exit(1)
80
+
81
+ with open(config_path, "r", encoding="utf-8") as f:
82
+ config_data = json.load(f)
83
+
84
+ config_data["auto_map"] = {
85
+ "AutoModelForCausalLM": "modeling_qwen2.Qwen2ForCausalLM"
86
+ }
87
+ config_data["architectures"] = ["Qwen2ForCausalLM"]
88
+ config_data["trust_remote_code"] = True
89
+
90
+ with open(config_path, "w", encoding="utf-8") as f:
91
+ json.dump(config_data, f, indent=2)
92
+ print("config.json updated successfully.")
93
+
94
+ # --- 4. Copy `README.md` ---
95
+ print("\nCopying README.md...")
96
+ readme_source = Path(args.readme_path)
97
+ if not readme_source.exists():
98
+ print(f"Error: README file not found at {readme_source}")
99
+ sys.exit(1)
100
 
101
+ with open(readme_source, "r", encoding="utf-8") as f:
102
+ readme_content = f.read()
103
 
104
+ readme_content = readme_content.replace("{repo_id}", args.repo)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
105
 
106
+ with open(staging_dir / "README.md", "w", encoding="utf-8") as f:
107
+ f.write(readme_content)
108
+ print("README.md copied and processed.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
109
 
110
+ # --- 5. Upload to the Hub ---
111
+ print(f"\nPreparing to upload to repository: {args.repo}")
112
+ repo_url = create_repo(args.repo, repo_type="model", exist_ok=True, private=args.private)
113
 
114
+ upload_folder(
115
+ folder_path=staging_dir,
116
+ repo_id=args.repo,
117
+ repo_type="model",
118
+ commit_message="Initial model upload with self-contained custom code",
 
119
  )
120
+ print("\n🚀 Upload complete! 🚀")
121
+ print(f"Check out your model at: {repo_url}")
122
 
123
+ finally:
124
+ # --- 6. Clean Up ---
125
+ print("\nCleaning up temporary staging directory...")
126
+ shutil.rmtree(staging_dir)
127
+ print("Cleanup complete.")
128
 
129
+ if __name__ == "__main__":
130
+ main()