NeuraCraft commited on
Commit
6f6d725
·
1 Parent(s): 123a250

Upload folder using huggingface_hub

Browse files
Files changed (2) hide show
  1. generation_config.json +1 -1
  2. lance_ai_model.py +158 -106
generation_config.json CHANGED
@@ -1,6 +1,6 @@
1
  {
2
- "_from_model_config": true,
3
  "bos_token_id": 151643,
4
  "eos_token_id": 151643,
 
5
  "transformers_version": "4.57.3"
6
  }
 
1
  {
 
2
  "bos_token_id": 151643,
3
  "eos_token_id": 151643,
4
+ "max_new_tokens": 2048,
5
  "transformers_version": "4.57.3"
6
  }
lance_ai_model.py CHANGED
@@ -1,11 +1,19 @@
1
  import math
 
2
  import torch
3
  import torch.nn as nn
4
  from torch.nn import functional as F
5
  from transformers import PreTrainedModel, PretrainedConfig, GenerationMixin
6
- from transformers.modeling_outputs import CausalLMOutputWithPast
7
  from transformers.models.auto.configuration_auto import CONFIG_MAPPING
8
  from transformers.models.auto.modeling_auto import MODEL_FOR_CAUSAL_LM_MAPPING
 
 
 
 
 
 
 
9
 
10
  class LanceAIConfig(PretrainedConfig):
11
  model_type = "lance_ai"
@@ -52,6 +60,7 @@ class LanceAIConfig(PretrainedConfig):
52
  self.bos_token_id = bos_token_id
53
  self.eos_token_id = eos_token_id
54
 
 
55
  class LanceAIRMSNorm(nn.Module):
56
  def __init__(self, hidden_size, eps=1e-6):
57
  super().__init__()
@@ -65,6 +74,7 @@ class LanceAIRMSNorm(nn.Module):
65
  hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
66
  return self.weight * hidden_states.to(input_dtype)
67
 
 
68
  class LanceAIRotaryEmbedding(nn.Module):
69
  def __init__(self, config):
70
  super().__init__()
@@ -84,11 +94,13 @@ class LanceAIRotaryEmbedding(nn.Module):
84
  sin = emb.sin()
85
  return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
86
 
 
87
  def rotate_half(x):
88
  x1 = x[..., :x.shape[-1] // 2]
89
  x2 = x[..., x.shape[-1] // 2:]
90
  return torch.cat((-x2, x1), dim=-1)
91
 
 
92
  def apply_rotary_pos_emb(q, k, cos, sin):
93
  cos = cos.unsqueeze(1)
94
  sin = sin.unsqueeze(1)
@@ -96,6 +108,7 @@ def apply_rotary_pos_emb(q, k, cos, sin):
96
  k_embed = (k * cos) + (rotate_half(k) * sin)
97
  return q_embed, k_embed
98
 
 
99
  def repeat_kv(hidden_states, n_rep):
100
  batch, num_key_value_heads, slen, head_dim = hidden_states.shape
101
  if n_rep == 1:
@@ -103,6 +116,33 @@ def repeat_kv(hidden_states, n_rep):
103
  hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
104
  return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
105
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
106
  class LanceAIAttention(nn.Module):
107
  def __init__(self, config, layer_idx):
108
  super().__init__()
@@ -121,39 +161,50 @@ class LanceAIAttention(nn.Module):
121
  self.v_proj = nn.Linear(config.hidden_size, config.num_key_value_heads * self.head_dim, bias=True)
122
  self.o_proj = nn.Linear(config.num_attention_heads * self.head_dim, config.hidden_size, bias=False)
123
 
124
- def forward(self, hidden_states, attention_mask=None, position_embeddings=None, past_key_values=None, use_cache=False):
125
- batch_size, seq_len, _ = hidden_states.shape
126
- query_states = self.q_proj(hidden_states).view(batch_size, seq_len, self.num_heads, self.head_dim).transpose(1, 2)
127
- key_states = self.k_proj(hidden_states).view(batch_size, seq_len, self.num_kv_heads, self.head_dim).transpose(1, 2)
128
- value_states = self.v_proj(hidden_states).view(batch_size, seq_len, self.num_kv_heads, self.head_dim).transpose(1, 2)
 
 
 
 
 
 
 
 
 
 
129
 
130
  cos, sin = position_embeddings
131
  query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
132
 
133
  if past_key_values is not None:
134
- if past_key_values[0] is not None:
135
- key_states = torch.cat([past_key_values[0], key_states], dim=2)
136
- if past_key_values[1] is not None:
137
- value_states = torch.cat([past_key_values[1], value_states], dim=2)
138
-
139
- past = (key_states, value_states) if use_cache else None
140
-
141
- key_states = repeat_kv(key_states, self.num_key_value_groups)
142
- value_states = repeat_kv(value_states, self.num_key_value_groups)
143
-
144
- attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) * self.scaling
145
-
146
- if attention_mask is not None:
147
- attn_weights = attn_weights + attention_mask
 
 
 
 
 
148
 
149
- attn_weights = F.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
150
- attn_weights = F.dropout(attn_weights, p=self.attention_dropout, training=self.training)
151
- attn_output = torch.matmul(attn_weights, value_states)
152
- attn_output = attn_output.transpose(1, 2).contiguous()
153
- attn_output = attn_output.reshape(batch_size, seq_len, -1)
154
  attn_output = self.o_proj(attn_output)
 
155
 
156
- return attn_output, past
157
 
158
  class LanceAIMLP(nn.Module):
159
  def __init__(self, config):
@@ -167,7 +218,8 @@ class LanceAIMLP(nn.Module):
167
  def forward(self, x):
168
  return self.down_proj(F.silu(self.gate_proj(x)) * self.up_proj(x))
169
 
170
- class LanceAIDecoderLayer(nn.Module):
 
171
  def __init__(self, config, layer_idx):
172
  super().__init__()
173
  self.hidden_size = config.hidden_size
@@ -176,15 +228,24 @@ class LanceAIDecoderLayer(nn.Module):
176
  self.input_layernorm = LanceAIRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
177
  self.post_attention_layernorm = LanceAIRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
178
 
179
- def forward(self, hidden_states, attention_mask=None, position_embeddings=None, past_key_values=None, use_cache=False):
 
 
 
 
 
 
 
 
180
  residual = hidden_states
181
  hidden_states = self.input_layernorm(hidden_states)
182
- hidden_states, past_kv = self.self_attn(
183
- hidden_states,
184
  attention_mask=attention_mask,
185
  position_embeddings=position_embeddings,
186
  past_key_values=past_key_values,
187
- use_cache=use_cache,
 
188
  )
189
  hidden_states = residual + hidden_states
190
 
@@ -193,7 +254,8 @@ class LanceAIDecoderLayer(nn.Module):
193
  hidden_states = self.mlp(hidden_states)
194
  hidden_states = residual + hidden_states
195
 
196
- return hidden_states, past_kv
 
197
 
198
  class LanceAIPreTrainedModel(PreTrainedModel):
199
  config_class = LanceAIConfig
@@ -203,6 +265,9 @@ class LanceAIPreTrainedModel(PreTrainedModel):
203
  _skip_keys_device_placement = ["past_key_values"]
204
  _supports_flash_attn = True
205
  _supports_sdpa = True
 
 
 
206
 
207
  class LanceAIModel(LanceAIPreTrainedModel):
208
  def __init__(self, config):
@@ -220,49 +285,30 @@ class LanceAIModel(LanceAIPreTrainedModel):
220
  self.gradient_checkpointing = False
221
  self.post_init()
222
 
223
- def _past_seq_length(self, past_key_values):
224
- """Get sequence length from past cache (tuple or DynamicCache)"""
225
- if past_key_values is None:
226
- return 0
227
- if hasattr(past_key_values, 'get_seq_length'):
228
- return past_key_values.get_seq_length()
229
- if len(past_key_values) > 0 and past_key_values[0] is not None:
230
- if past_key_values[0][0] is not None:
231
- return past_key_values[0][0].shape[2]
232
- return 0
233
-
234
- def _convert_past(self, past_key_values, use_cache):
235
- """Convert DynamicCache to our tuple format if needed"""
236
- if past_key_values is None or not use_cache:
237
- return past_key_values, use_cache
238
- if isinstance(past_key_values, list):
239
- return past_key_values, use_cache
240
- # DynamicCache -> list of (k, v) tuples
241
- if hasattr(past_key_values, 'get_seq_length'):
242
- converted = []
243
- for i in range(len(self.layers)):
244
- if i < len(past_key_values):
245
- kv = past_key_values[i]
246
- converted.append((kv[0], kv[1]))
247
- else:
248
- converted.append((None, None))
249
- return converted, use_cache
250
- return past_key_values, use_cache
251
-
252
- def forward(self, input_ids=None, attention_mask=None, position_ids=None, past_key_values=None, inputs_embeds=None, use_cache=None):
253
  if (input_ids is None) ^ (inputs_embeds is not None):
254
  raise ValueError("Specify exactly one of input_ids or inputs_embeds")
255
  if inputs_embeds is None:
256
  inputs_embeds = self.embed_tokens(input_ids)
257
- batch_size, seq_len = inputs_embeds.shape[:2]
258
 
259
- past_key_values, use_cache = self._convert_past(past_key_values, use_cache)
 
260
 
261
  if position_ids is None:
262
- past_seen_tokens = self._past_seq_length(past_key_values)
263
- position_ids = torch.arange(seq_len, device=inputs_embeds.device) + past_seen_tokens
264
- position_ids = position_ids.unsqueeze(0).expand(batch_size, -1)
265
 
 
266
  position_embeddings = self.rotary_emb(inputs_embeds, position_ids)
267
 
268
  if attention_mask is not None:
@@ -274,31 +320,31 @@ class LanceAIModel(LanceAIPreTrainedModel):
274
  attention_mask = self._make_causal_mask(inputs_embeds, past_key_values)
275
 
276
  hidden_states = inputs_embeds
277
- new_past = [] if use_cache else None
278
-
279
  for i, layer in enumerate(self.layers):
280
- layer_past = past_key_values[i] if past_key_values is not None else None
281
- hidden_states, layer_past = layer(
282
  hidden_states,
283
  attention_mask=attention_mask,
284
  position_embeddings=position_embeddings,
285
- past_key_values=layer_past,
286
- use_cache=use_cache,
 
287
  )
288
- if use_cache:
289
- new_past.append(layer_past)
290
 
291
  hidden_states = self.norm(hidden_states)
292
- return hidden_states, new_past
 
 
 
293
 
294
- def _make_causal_mask(self, inputs_embeds, past_key_values=None):
295
- batch_size, seq_len, _ = inputs_embeds.shape
296
- past_len = self._past_seq_length(past_key_values)
297
  total_len = past_len + seq_len
298
- mask = torch.full((seq_len, total_len), float('-inf'), device=inputs_embeds.device)
299
  mask = torch.triu(mask, diagonal=1 + past_len)
300
  return mask[None, None, :, :]
301
 
 
302
  class LanceAI(LanceAIPreTrainedModel, GenerationMixin):
303
  _tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"}
304
 
@@ -310,45 +356,47 @@ class LanceAI(LanceAIPreTrainedModel, GenerationMixin):
310
 
311
  self.post_init()
312
 
313
- def forward(self, input_ids=None, attention_mask=None, position_ids=None, past_key_values=None, inputs_embeds=None, labels=None, use_cache=None, **kwargs):
314
- hidden_states, past = self.model(
 
 
 
 
 
 
 
 
 
 
 
315
  input_ids=input_ids,
316
  attention_mask=attention_mask,
317
  position_ids=position_ids,
318
  past_key_values=past_key_values,
319
  inputs_embeds=inputs_embeds,
320
  use_cache=use_cache,
 
321
  )
322
 
323
- logits = self.lm_head(hidden_states)
 
 
324
 
325
  loss = None
326
  if labels is not None:
327
- shift_logits = logits[..., :-1, :].contiguous()
328
- shift_labels = labels[..., 1:].contiguous()
329
- loss = F.cross_entropy(
330
- shift_logits.view(-1, shift_logits.size(-1)),
331
- shift_labels.view(-1),
332
- ignore_index=-100,
333
- )
334
-
335
- return CausalLMOutputWithPast(loss=loss, logits=logits, past_key_values=past)
336
 
337
- def _past_seq_len(self, past_key_values):
338
- if past_key_values is None:
339
- return 0
340
- if hasattr(past_key_values, 'get_seq_length'):
341
- return past_key_values.get_seq_length()
342
- if isinstance(past_key_values, list) and len(past_key_values) > 0:
343
- if past_key_values[0] is not None:
344
- k, v = past_key_values[0]
345
- if k is not None:
346
- return k.shape[2]
347
- return 0
348
 
349
  def prepare_inputs_for_generation(self, input_ids, past_key_values=None, attention_mask=None, **kwargs):
350
- if self._past_seq_len(past_key_values) > 0:
351
- input_ids = input_ids[:, -1:]
 
 
352
  return {
353
  "input_ids": input_ids,
354
  "attention_mask": attention_mask,
@@ -357,13 +405,17 @@ class LanceAI(LanceAIPreTrainedModel, GenerationMixin):
357
  }
358
 
359
  def _reorder_cache(self, past_key_values, beam_idx):
 
 
 
360
  reordered = []
361
  for layer_past in past_key_values:
362
  layer_k, layer_v = layer_past
363
  reordered.append((layer_k.index_select(0, beam_idx), layer_v.index_select(0, beam_idx)))
364
  return reordered
365
 
 
366
  CONFIG_MAPPING.register("lance_ai", LanceAIConfig)
367
  MODEL_FOR_CAUSAL_LM_MAPPING.register(LanceAIConfig, LanceAI)
368
  LanceAIConfig.register_for_auto_class("AutoConfig")
369
- LanceAI.register_for_auto_class("AutoModelForCausalLM")
 
1
  import math
2
+ from functools import partial
3
  import torch
4
  import torch.nn as nn
5
  from torch.nn import functional as F
6
  from transformers import PreTrainedModel, PretrainedConfig, GenerationMixin
7
+ from transformers.modeling_outputs import CausalLMOutputWithPast, BaseModelOutputWithPast
8
  from transformers.models.auto.configuration_auto import CONFIG_MAPPING
9
  from transformers.models.auto.modeling_auto import MODEL_FOR_CAUSAL_LM_MAPPING
10
+ from transformers.cache_utils import Cache, DynamicCache
11
+
12
+ from transformers.modeling_flash_attention_utils import FlashAttentionKwargs
13
+ from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS
14
+ from transformers.processing_utils import Unpack
15
+ from transformers.utils import TransformersKwargs, logging
16
+ from transformers.modeling_layers import GradientCheckpointingLayer
17
 
18
  class LanceAIConfig(PretrainedConfig):
19
  model_type = "lance_ai"
 
60
  self.bos_token_id = bos_token_id
61
  self.eos_token_id = eos_token_id
62
 
63
+
64
  class LanceAIRMSNorm(nn.Module):
65
  def __init__(self, hidden_size, eps=1e-6):
66
  super().__init__()
 
74
  hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
75
  return self.weight * hidden_states.to(input_dtype)
76
 
77
+
78
  class LanceAIRotaryEmbedding(nn.Module):
79
  def __init__(self, config):
80
  super().__init__()
 
94
  sin = emb.sin()
95
  return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
96
 
97
+
98
  def rotate_half(x):
99
  x1 = x[..., :x.shape[-1] // 2]
100
  x2 = x[..., x.shape[-1] // 2:]
101
  return torch.cat((-x2, x1), dim=-1)
102
 
103
+
104
  def apply_rotary_pos_emb(q, k, cos, sin):
105
  cos = cos.unsqueeze(1)
106
  sin = sin.unsqueeze(1)
 
108
  k_embed = (k * cos) + (rotate_half(k) * sin)
109
  return q_embed, k_embed
110
 
111
+
112
  def repeat_kv(hidden_states, n_rep):
113
  batch, num_key_value_heads, slen, head_dim = hidden_states.shape
114
  if n_rep == 1:
 
116
  hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
117
  return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
118
 
119
+
120
+ def eager_attention_forward(
121
+ module: nn.Module,
122
+ query: torch.Tensor,
123
+ key: torch.Tensor,
124
+ value: torch.Tensor,
125
+ attention_mask: torch.Tensor | None,
126
+ scaling: float,
127
+ dropout: float = 0.0,
128
+ **kwargs: Unpack[TransformersKwargs],
129
+ ):
130
+ key_states = repeat_kv(key, module.num_key_value_groups)
131
+ value_states = repeat_kv(value, module.num_key_value_groups)
132
+
133
+ attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
134
+ if attention_mask is not None:
135
+ causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
136
+ attn_weights = attn_weights + causal_mask
137
+
138
+ attn_weights = F.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
139
+ attn_weights = F.dropout(attn_weights, p=dropout, training=module.training)
140
+ attn_output = torch.matmul(attn_weights, value_states)
141
+ attn_output = attn_output.transpose(1, 2).contiguous()
142
+
143
+ return attn_output, attn_weights
144
+
145
+
146
  class LanceAIAttention(nn.Module):
147
  def __init__(self, config, layer_idx):
148
  super().__init__()
 
161
  self.v_proj = nn.Linear(config.hidden_size, config.num_key_value_heads * self.head_dim, bias=True)
162
  self.o_proj = nn.Linear(config.num_attention_heads * self.head_dim, config.hidden_size, bias=False)
163
 
164
+ def forward(
165
+ self,
166
+ hidden_states: torch.Tensor,
167
+ position_embeddings: tuple[torch.Tensor, torch.Tensor],
168
+ attention_mask: torch.Tensor | None = None,
169
+ past_key_values: Cache | None = None,
170
+ cache_position: torch.LongTensor | None = None,
171
+ **kwargs: Unpack[FlashAttentionKwargs],
172
+ ):
173
+ input_shape = hidden_states.shape[:-1]
174
+ hidden_shape = (*input_shape, -1, self.head_dim)
175
+
176
+ query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
177
+ key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
178
+ value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
179
 
180
  cos, sin = position_embeddings
181
  query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
182
 
183
  if past_key_values is not None:
184
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
185
+ key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx, cache_kwargs)
186
+
187
+ attention_interface = eager_attention_forward
188
+ if self.config._attn_implementation != "eager":
189
+ if self.config._attn_implementation in ALL_ATTENTION_FUNCTIONS:
190
+ attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
191
+
192
+ attn_output, attn_weights = attention_interface(
193
+ self,
194
+ query_states,
195
+ key_states,
196
+ value_states,
197
+ attention_mask,
198
+ dropout=0.0 if not self.training else self.attention_dropout,
199
+ scaling=self.scaling,
200
+ sliding_window=getattr(self, 'sliding_window', None),
201
+ **kwargs,
202
+ )
203
 
204
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
 
 
 
 
205
  attn_output = self.o_proj(attn_output)
206
+ return attn_output, attn_weights
207
 
 
208
 
209
  class LanceAIMLP(nn.Module):
210
  def __init__(self, config):
 
218
  def forward(self, x):
219
  return self.down_proj(F.silu(self.gate_proj(x)) * self.up_proj(x))
220
 
221
+
222
+ class LanceAIDecoderLayer(GradientCheckpointingLayer):
223
  def __init__(self, config, layer_idx):
224
  super().__init__()
225
  self.hidden_size = config.hidden_size
 
228
  self.input_layernorm = LanceAIRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
229
  self.post_attention_layernorm = LanceAIRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
230
 
231
+ def forward(
232
+ self,
233
+ hidden_states,
234
+ attention_mask=None,
235
+ position_embeddings=None,
236
+ past_key_values=None,
237
+ cache_position=None,
238
+ **kwargs,
239
+ ):
240
  residual = hidden_states
241
  hidden_states = self.input_layernorm(hidden_states)
242
+ hidden_states, _ = self.self_attn(
243
+ hidden_states=hidden_states,
244
  attention_mask=attention_mask,
245
  position_embeddings=position_embeddings,
246
  past_key_values=past_key_values,
247
+ cache_position=cache_position,
248
+ **kwargs,
249
  )
250
  hidden_states = residual + hidden_states
251
 
 
254
  hidden_states = self.mlp(hidden_states)
255
  hidden_states = residual + hidden_states
256
 
257
+ return hidden_states
258
+
259
 
260
  class LanceAIPreTrainedModel(PreTrainedModel):
261
  config_class = LanceAIConfig
 
265
  _skip_keys_device_placement = ["past_key_values"]
266
  _supports_flash_attn = True
267
  _supports_sdpa = True
268
+ _supports_flex_attn = True
269
+ _can_compile_fullgraph = True
270
+
271
 
272
  class LanceAIModel(LanceAIPreTrainedModel):
273
  def __init__(self, config):
 
285
  self.gradient_checkpointing = False
286
  self.post_init()
287
 
288
+ def forward(
289
+ self,
290
+ input_ids=None,
291
+ attention_mask=None,
292
+ position_ids=None,
293
+ past_key_values=None,
294
+ inputs_embeds=None,
295
+ use_cache=None,
296
+ **kwargs,
297
+ ):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
298
  if (input_ids is None) ^ (inputs_embeds is not None):
299
  raise ValueError("Specify exactly one of input_ids or inputs_embeds")
300
  if inputs_embeds is None:
301
  inputs_embeds = self.embed_tokens(input_ids)
 
302
 
303
+ if use_cache and past_key_values is None:
304
+ past_key_values = DynamicCache()
305
 
306
  if position_ids is None:
307
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
308
+ position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device) + past_seen_tokens
309
+ position_ids = position_ids.unsqueeze(0)
310
 
311
+ cache_position = position_ids[0]
312
  position_embeddings = self.rotary_emb(inputs_embeds, position_ids)
313
 
314
  if attention_mask is not None:
 
320
  attention_mask = self._make_causal_mask(inputs_embeds, past_key_values)
321
 
322
  hidden_states = inputs_embeds
 
 
323
  for i, layer in enumerate(self.layers):
324
+ hidden_states = layer(
 
325
  hidden_states,
326
  attention_mask=attention_mask,
327
  position_embeddings=position_embeddings,
328
+ past_key_values=past_key_values,
329
+ cache_position=cache_position,
330
+ **kwargs,
331
  )
 
 
332
 
333
  hidden_states = self.norm(hidden_states)
334
+ return BaseModelOutputWithPast(
335
+ last_hidden_state=hidden_states,
336
+ past_key_values=past_key_values if use_cache else None,
337
+ )
338
 
339
+ def _make_causal_mask(self, input_embeds, past_key_values=None):
340
+ batch_size, seq_len, _ = input_embeds.shape
341
+ past_len = past_key_values.get_seq_length() if past_key_values is not None else 0
342
  total_len = past_len + seq_len
343
+ mask = torch.full((seq_len, total_len), float('-inf'), device=input_embeds.device)
344
  mask = torch.triu(mask, diagonal=1 + past_len)
345
  return mask[None, None, :, :]
346
 
347
+
348
  class LanceAI(LanceAIPreTrainedModel, GenerationMixin):
349
  _tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"}
350
 
 
356
 
357
  self.post_init()
358
 
359
+ def forward(
360
+ self,
361
+ input_ids=None,
362
+ attention_mask=None,
363
+ position_ids=None,
364
+ past_key_values=None,
365
+ inputs_embeds=None,
366
+ labels=None,
367
+ use_cache=None,
368
+ logits_to_keep=0,
369
+ **kwargs,
370
+ ):
371
+ outputs = self.model(
372
  input_ids=input_ids,
373
  attention_mask=attention_mask,
374
  position_ids=position_ids,
375
  past_key_values=past_key_values,
376
  inputs_embeds=inputs_embeds,
377
  use_cache=use_cache,
378
+ **kwargs,
379
  )
380
 
381
+ hidden_states = outputs.last_hidden_state
382
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
383
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
384
 
385
  loss = None
386
  if labels is not None:
387
+ loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)
 
 
 
 
 
 
 
 
388
 
389
+ return CausalLMOutputWithPast(
390
+ loss=loss,
391
+ logits=logits,
392
+ past_key_values=outputs.past_key_values,
393
+ )
 
 
 
 
 
 
394
 
395
  def prepare_inputs_for_generation(self, input_ids, past_key_values=None, attention_mask=None, **kwargs):
396
+ if past_key_values is not None:
397
+ past_length = past_key_values.get_seq_length() if hasattr(past_key_values, 'get_seq_length') else 0
398
+ if past_length > 0:
399
+ input_ids = input_ids[:, -1:]
400
  return {
401
  "input_ids": input_ids,
402
  "attention_mask": attention_mask,
 
405
  }
406
 
407
  def _reorder_cache(self, past_key_values, beam_idx):
408
+ if hasattr(past_key_values, 'reorder_cache'):
409
+ past_key_values.reorder_cache(beam_idx)
410
+ return past_key_values
411
  reordered = []
412
  for layer_past in past_key_values:
413
  layer_k, layer_v = layer_past
414
  reordered.append((layer_k.index_select(0, beam_idx), layer_v.index_select(0, beam_idx)))
415
  return reordered
416
 
417
+
418
  CONFIG_MAPPING.register("lance_ai", LanceAIConfig)
419
  MODEL_FOR_CAUSAL_LM_MAPPING.register(LanceAIConfig, LanceAI)
420
  LanceAIConfig.register_for_auto_class("AutoConfig")
421
+ LanceAI.register_for_auto_class("AutoModelForCausalLM")