MengLinMaker commited on
Commit
f0cf42d
·
1 Parent(s): 1403f74

feat: use local model

Browse files
Files changed (2) hide show
  1. modelling_maincoder.py +31 -20
  2. run.py +9 -5
modelling_maincoder.py CHANGED
@@ -81,13 +81,29 @@ class MaincoderRotaryEmbedding(nn.Module):
81
 
82
  def __init__(self, config: MaincoderConfig, device=None):
83
  super().__init__()
84
- self.rope_type = "llama3" if config.rope_scaling is not None else "default"
 
 
 
 
85
  self.config = config
86
- self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
87
-
88
- inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device)
 
 
89
  self.register_buffer("inv_freq", inv_freq, persistent=False)
90
 
 
 
 
 
 
 
 
 
 
 
91
  @torch.no_grad()
92
  @dynamic_rope_update
93
  def forward(self, x: torch.Tensor, position_ids: torch.Tensor) -> torch.Tensor:
@@ -188,7 +204,7 @@ class MaincoderAttention(nn.Module):
188
  position_embeddings: torch.Tensor,
189
  attention_mask: Optional[torch.Tensor] = None,
190
  past_key_values: Optional[Cache] = None,
191
- cache_position: Optional[torch.LongTensor] = None,
192
  **kwargs: Unpack[FlashAttentionKwargs],
193
  ) -> tuple[torch.Tensor, Optional[torch.Tensor]]:
194
  batch_size, seq_len, _ = hidden_states.shape
@@ -212,7 +228,7 @@ class MaincoderAttention(nn.Module):
212
 
213
  # Update KV cache
214
  if past_key_values is not None:
215
- cache_kwargs = {"cache_position": cache_position}
216
  key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx, cache_kwargs)
217
 
218
  # Attention
@@ -253,7 +269,7 @@ class MaincoderDecoderLayer(GradientCheckpointingLayer):
253
  attention_mask: Optional[torch.Tensor] = None,
254
  position_embeddings: Optional[torch.Tensor] = None,
255
  past_key_values: Optional[Cache] = None,
256
- cache_position: Optional[torch.LongTensor] = None,
257
  **kwargs: Unpack[FlashAttentionKwargs],
258
  ) -> torch.Tensor:
259
  # Self Attention
@@ -264,7 +280,7 @@ class MaincoderDecoderLayer(GradientCheckpointingLayer):
264
  position_embeddings=position_embeddings,
265
  attention_mask=attention_mask,
266
  past_key_values=past_key_values,
267
- cache_position=cache_position,
268
  **kwargs,
269
  )
270
  hidden_states = residual + hidden_states
@@ -332,7 +348,6 @@ class MaincoderModel(MaincoderPreTrainedModel):
332
  past_key_values: Optional[Cache] = None,
333
  inputs_embeds: Optional[torch.FloatTensor] = None,
334
  use_cache: Optional[bool] = None,
335
- cache_position: Optional[torch.LongTensor] = None,
336
  **kwargs: Unpack[TransformersKwargs],
337
  ) -> Union[tuple, BaseModelOutputWithPast]:
338
  if (input_ids is None) ^ (inputs_embeds is not None):
@@ -344,24 +359,22 @@ class MaincoderModel(MaincoderPreTrainedModel):
344
  if use_cache and past_key_values is None:
345
  past_key_values = DynamicCache()
346
 
347
- if cache_position is None:
348
  past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
349
- cache_position = torch.arange(
350
  past_seen_tokens,
351
  past_seen_tokens + inputs_embeds.shape[1],
352
  device=inputs_embeds.device,
353
  )
354
-
355
- if position_ids is None:
356
- position_ids = cache_position.unsqueeze(0)
357
 
358
  # Create causal mask
359
  causal_mask = create_causal_mask(
360
  config=self.config,
361
- input_embeds=inputs_embeds,
362
  attention_mask=attention_mask,
363
- cache_position=cache_position,
364
  past_key_values=past_key_values,
 
365
  )
366
 
367
  # Position embeddings
@@ -374,7 +387,7 @@ class MaincoderModel(MaincoderPreTrainedModel):
374
  attention_mask=causal_mask,
375
  position_embeddings=position_embeddings,
376
  past_key_values=past_key_values,
377
- cache_position=cache_position,
378
  **kwargs,
379
  )
380
 
@@ -389,7 +402,7 @@ class MaincoderModel(MaincoderPreTrainedModel):
389
  class MaincoderForCausalLM(MaincoderPreTrainedModel, GenerationMixin):
390
  """Maincoder model with a causal language modeling head."""
391
 
392
- _tied_weights_keys = ["lm_head.weight"]
393
 
394
  def __init__(self, config: MaincoderConfig):
395
  super().__init__(config)
@@ -422,7 +435,6 @@ class MaincoderForCausalLM(MaincoderPreTrainedModel, GenerationMixin):
422
  inputs_embeds: Optional[torch.FloatTensor] = None,
423
  labels: Optional[torch.LongTensor] = None,
424
  use_cache: Optional[bool] = None,
425
- cache_position: Optional[torch.LongTensor] = None,
426
  logits_to_keep: Union[int, torch.Tensor] = 0,
427
  **kwargs: Unpack[TransformersKwargs],
428
  ) -> Union[tuple, CausalLMOutputWithPast]:
@@ -454,7 +466,6 @@ class MaincoderForCausalLM(MaincoderPreTrainedModel, GenerationMixin):
454
  past_key_values=past_key_values,
455
  inputs_embeds=inputs_embeds,
456
  use_cache=use_cache,
457
- cache_position=cache_position,
458
  **kwargs,
459
  )
460
 
 
81
 
82
  def __init__(self, config: MaincoderConfig, device=None):
83
  super().__init__()
84
+ self.rope_type = (
85
+ config.rope_scaling.get("rope_type", "default")
86
+ if isinstance(config.rope_scaling, dict)
87
+ else "default"
88
+ )
89
  self.config = config
90
+ if self.rope_type == "default":
91
+ inv_freq, self.attention_scaling = self._compute_default_rope_parameters(device)
92
+ else:
93
+ self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
94
+ inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device)
95
  self.register_buffer("inv_freq", inv_freq, persistent=False)
96
 
97
+ def _compute_default_rope_parameters(self, device=None) -> tuple[torch.Tensor, float]:
98
+ inv_freq = 1.0 / (
99
+ self.config.rope_theta
100
+ ** (
101
+ torch.arange(0, self.config.head_dim, 2, dtype=torch.int64, device=device).float()
102
+ / self.config.head_dim
103
+ )
104
+ )
105
+ return inv_freq, 1.0
106
+
107
  @torch.no_grad()
108
  @dynamic_rope_update
109
  def forward(self, x: torch.Tensor, position_ids: torch.Tensor) -> torch.Tensor:
 
204
  position_embeddings: torch.Tensor,
205
  attention_mask: Optional[torch.Tensor] = None,
206
  past_key_values: Optional[Cache] = None,
207
+ position_ids: Optional[torch.LongTensor] = None,
208
  **kwargs: Unpack[FlashAttentionKwargs],
209
  ) -> tuple[torch.Tensor, Optional[torch.Tensor]]:
210
  batch_size, seq_len, _ = hidden_states.shape
 
228
 
229
  # Update KV cache
230
  if past_key_values is not None:
231
+ cache_kwargs = {"cache_position": position_ids}
232
  key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx, cache_kwargs)
233
 
234
  # Attention
 
269
  attention_mask: Optional[torch.Tensor] = None,
270
  position_embeddings: Optional[torch.Tensor] = None,
271
  past_key_values: Optional[Cache] = None,
272
+ position_ids: Optional[torch.LongTensor] = None,
273
  **kwargs: Unpack[FlashAttentionKwargs],
274
  ) -> torch.Tensor:
275
  # Self Attention
 
280
  position_embeddings=position_embeddings,
281
  attention_mask=attention_mask,
282
  past_key_values=past_key_values,
283
+ position_ids=position_ids,
284
  **kwargs,
285
  )
286
  hidden_states = residual + hidden_states
 
348
  past_key_values: Optional[Cache] = None,
349
  inputs_embeds: Optional[torch.FloatTensor] = None,
350
  use_cache: Optional[bool] = None,
 
351
  **kwargs: Unpack[TransformersKwargs],
352
  ) -> Union[tuple, BaseModelOutputWithPast]:
353
  if (input_ids is None) ^ (inputs_embeds is not None):
 
359
  if use_cache and past_key_values is None:
360
  past_key_values = DynamicCache()
361
 
362
+ if position_ids is None:
363
  past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
364
+ token_positions = torch.arange(
365
  past_seen_tokens,
366
  past_seen_tokens + inputs_embeds.shape[1],
367
  device=inputs_embeds.device,
368
  )
369
+ position_ids = token_positions.unsqueeze(0)
 
 
370
 
371
  # Create causal mask
372
  causal_mask = create_causal_mask(
373
  config=self.config,
374
+ inputs_embeds=inputs_embeds,
375
  attention_mask=attention_mask,
 
376
  past_key_values=past_key_values,
377
+ position_ids=position_ids,
378
  )
379
 
380
  # Position embeddings
 
387
  attention_mask=causal_mask,
388
  position_embeddings=position_embeddings,
389
  past_key_values=past_key_values,
390
+ position_ids=position_ids,
391
  **kwargs,
392
  )
393
 
 
402
  class MaincoderForCausalLM(MaincoderPreTrainedModel, GenerationMixin):
403
  """Maincoder model with a causal language modeling head."""
404
 
405
+ _tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"}
406
 
407
  def __init__(self, config: MaincoderConfig):
408
  super().__init__(config)
 
435
  inputs_embeds: Optional[torch.FloatTensor] = None,
436
  labels: Optional[torch.LongTensor] = None,
437
  use_cache: Optional[bool] = None,
 
438
  logits_to_keep: Union[int, torch.Tensor] = 0,
439
  **kwargs: Unpack[TransformersKwargs],
440
  ) -> Union[tuple, CausalLMOutputWithPast]:
 
466
  past_key_values=past_key_values,
467
  inputs_embeds=inputs_embeds,
468
  use_cache=use_cache,
 
469
  **kwargs,
470
  )
471
 
run.py CHANGED
@@ -1,26 +1,30 @@
 
 
1
  from transformers import AutoModelForCausalLM, AutoTokenizer
2
 
 
 
3
  model = AutoModelForCausalLM.from_pretrained(
4
- "MengLinMaker/Maincoder-1B",
5
  torch_dtype="auto",
6
  device_map="auto",
7
  trust_remote_code=True,
8
  )
9
  tokenizer = AutoTokenizer.from_pretrained(
10
- "MengLinMaker/Maincoder-1B",
11
  trust_remote_code=True,
12
  )
13
 
14
  # Code completion example
15
- prompt = '''def fibonacci(n: int) -> int:
16
- """Return the n-th Fibonacci number."""
17
  '''
18
 
19
  inputs = tokenizer(prompt, return_tensors="pt").to(model.device)
20
  outputs = model.generate(
21
  **inputs,
22
  max_new_tokens=256,
23
- temperature=0.2,
24
  do_sample=True,
25
  )
26
  print(tokenizer.decode(outputs[0], skip_special_tokens=True))
 
1
+ from pathlib import Path
2
+
3
  from transformers import AutoModelForCausalLM, AutoTokenizer
4
 
5
+ MODEL_DIR = Path(__file__).resolve().parent
6
+
7
  model = AutoModelForCausalLM.from_pretrained(
8
+ MODEL_DIR,
9
  torch_dtype="auto",
10
  device_map="auto",
11
  trust_remote_code=True,
12
  )
13
  tokenizer = AutoTokenizer.from_pretrained(
14
+ MODEL_DIR,
15
  trust_remote_code=True,
16
  )
17
 
18
  # Code completion example
19
+ prompt = '''"""Complete the fibonacci function in Python."""
20
+ def fibonacci(n: int) -> int:
21
  '''
22
 
23
  inputs = tokenizer(prompt, return_tensors="pt").to(model.device)
24
  outputs = model.generate(
25
  **inputs,
26
  max_new_tokens=256,
27
+ temperature=0.5,
28
  do_sample=True,
29
  )
30
  print(tokenizer.decode(outputs[0], skip_special_tokens=True))