minlik commited on
Commit
816589e
1 Parent(s): 493f6f1

Upload modeling_llama.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. modeling_llama.py +1074 -0
modeling_llama.py ADDED
@@ -0,0 +1,1074 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
5
+ # and OPT implementations in this library. It has been modified from its
6
+ # original forms to accommodate minor architectural differences compared
7
+ # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
8
+ #
9
+ # Licensed under the Apache License, Version 2.0 (the "License");
10
+ # you may not use this file except in compliance with the License.
11
+ # You may obtain a copy of the License at
12
+ #
13
+ # http://www.apache.org/licenses/LICENSE-2.0
14
+ #
15
+ # Unless required by applicable law or agreed to in writing, software
16
+ # distributed under the License is distributed on an "AS IS" BASIS,
17
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
+ # See the License for the specific language governing permissions and
19
+ # limitations under the License.
20
+ """ PyTorch LLaMA model."""
21
+ import math
22
+ import warnings
23
+ from typing import List, Optional, Tuple, Union
24
+
25
+ import torch
26
+ import torch.nn.functional as F
27
+ import torch.utils.checkpoint
28
+ from torch import nn
29
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
30
+
31
+ from transformers.activations import ACT2FN
32
+ from transformers.cache_utils import Cache, DynamicCache
33
+ from transformers.modeling_attn_mask_utils import (
34
+ AttentionMaskConverter,
35
+ _prepare_4d_attention_mask,
36
+ _prepare_4d_causal_attention_mask,
37
+ _prepare_4d_causal_attention_mask_for_sdpa,
38
+ )
39
+ from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast, \
40
+ SequenceClassifierOutputWithPast
41
+ from transformers.modeling_utils import PreTrainedModel
42
+ from transformers.pytorch_utils import ALL_LAYERNORM_LAYERS, is_torch_greater_or_equal_than_1_13
43
+ from transformers.utils import (
44
+ add_start_docstrings,
45
+ add_start_docstrings_to_model_forward,
46
+ logging,
47
+ replace_return_docstrings,
48
+ )
49
+ from transformers.utils.import_utils import is_torch_fx_available
50
+ from .configuration_llama import LlamaConfig
51
+
52
+
53
+ # This makes `_prepare_4d_causal_attention_mask` a leaf function in the FX graph.
54
+ # It means that the function will not be traced through and simply appear as a node in the graph.
55
+ if is_torch_fx_available():
56
+ if not is_torch_greater_or_equal_than_1_13:
57
+ import torch.fx
58
+
59
+ _prepare_4d_causal_attention_mask = torch.fx.wrap(_prepare_4d_causal_attention_mask)
60
+
61
+ logger = logging.get_logger(__name__)
62
+
63
+ _CONFIG_FOR_DOC = "LlamaConfig"
64
+
65
+
66
+ def _get_unpad_data(attention_mask):
67
+ seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
68
+ indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
69
+ max_seqlen_in_batch = seqlens_in_batch.max().item()
70
+ cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.torch.int32), (1, 0))
71
+ return (
72
+ indices,
73
+ cu_seqlens,
74
+ max_seqlen_in_batch,
75
+ )
76
+
77
+
78
+ def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None):
79
+ warnings.warn(
80
+ "Calling `transformers.models.llama.modeling_llama._prepare_4d_attention_mask` is deprecated and will be removed in v4.37. Use `transformers.modeling_attn_mask_utils._prepare_4d_attention_mask"
81
+ )
82
+ return _prepare_4d_attention_mask(mask=mask, dtype=dtype, tgt_len=tgt_len)
83
+
84
+
85
+ def _make_causal_mask(
86
+ input_ids_shape: torch.Size, dtype: torch.dtype, device: torch.device, past_key_values_length: int = 0
87
+ ):
88
+ warnings.warn(
89
+ "Calling `transformers.models.llama.modeling_llama._make_causal_mask` is deprecated and will be removed in v4.37. Use `transformers.models.llama.modeling_llama.AttentionMaskConverter._make_causal_mask"
90
+ )
91
+ return AttentionMaskConverter._make_causal_mask(
92
+ input_ids_shape=input_ids_shape, dtype=dtype, device=device, past_key_values_length=past_key_values_length
93
+ )
94
+
95
+
96
+ class LlamaRMSNorm(nn.Module):
97
+ def __init__(self, hidden_size, eps=1e-6):
98
+ """
99
+ LlamaRMSNorm is equivalent to T5LayerNorm
100
+ """
101
+ super().__init__()
102
+ self.weight = nn.Parameter(torch.ones(hidden_size))
103
+ self.variance_epsilon = eps
104
+
105
+ def forward(self, hidden_states):
106
+ input_dtype = hidden_states.dtype
107
+ hidden_states = hidden_states.to(torch.float32)
108
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
109
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
110
+ return self.weight * hidden_states.to(input_dtype)
111
+
112
+
113
+ ALL_LAYERNORM_LAYERS.append(LlamaRMSNorm)
114
+
115
+
116
+ class LlamaRotaryEmbedding(nn.Module):
117
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
118
+ super().__init__()
119
+
120
+ self.dim = dim
121
+ self.max_position_embeddings = max_position_embeddings
122
+ self.base = base
123
+ inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim))
124
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
125
+
126
+ # Build here to make `torch.jit.trace` work.
127
+ self._set_cos_sin_cache(
128
+ seq_len=max_position_embeddings, device=self.inv_freq.device, dtype=torch.get_default_dtype()
129
+ )
130
+
131
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
132
+ self.max_seq_len_cached = seq_len
133
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
134
+
135
+ freqs = torch.outer(t, self.inv_freq)
136
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
137
+ emb = torch.cat((freqs, freqs), dim=-1)
138
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
139
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
140
+
141
+ def forward(self, x, seq_len=None):
142
+ # x: [bs, num_attention_heads, seq_len, head_size]
143
+ if seq_len > self.max_seq_len_cached:
144
+ self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)
145
+
146
+ return (
147
+ self.cos_cached[:seq_len].to(dtype=x.dtype),
148
+ self.sin_cached[:seq_len].to(dtype=x.dtype),
149
+ )
150
+
151
+
152
+ class LlamaLinearScalingRotaryEmbedding(LlamaRotaryEmbedding):
153
+ """LlamaRotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendev"""
154
+
155
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):
156
+ self.scaling_factor = scaling_factor
157
+ super().__init__(dim, max_position_embeddings, base, device)
158
+
159
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
160
+ self.max_seq_len_cached = seq_len
161
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
162
+ t = t / self.scaling_factor
163
+
164
+ freqs = torch.outer(t, self.inv_freq)
165
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
166
+ emb = torch.cat((freqs, freqs), dim=-1)
167
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
168
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
169
+
170
+
171
+ class LlamaDynamicNTKScalingRotaryEmbedding(LlamaRotaryEmbedding):
172
+ """LlamaRotaryEmbedding extended with Dynamic NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozilla"""
173
+
174
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):
175
+ self.scaling_factor = scaling_factor
176
+ super().__init__(dim, max_position_embeddings, base, device)
177
+
178
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
179
+ self.max_seq_len_cached = seq_len
180
+
181
+ if seq_len > self.max_position_embeddings:
182
+ base = self.base * (
183
+ (self.scaling_factor * seq_len / self.max_position_embeddings) - (self.scaling_factor - 1)
184
+ ) ** (self.dim / (self.dim - 2))
185
+ inv_freq = 1.0 / (base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim))
186
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
187
+
188
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
189
+
190
+ freqs = torch.outer(t, self.inv_freq)
191
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
192
+ emb = torch.cat((freqs, freqs), dim=-1)
193
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
194
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
195
+
196
+
197
+ def rotate_half(x):
198
+ """Rotates half the hidden dims of the input."""
199
+ x1 = x[..., : x.shape[-1] // 2]
200
+ x2 = x[..., x.shape[-1] // 2:]
201
+ return torch.cat((-x2, x1), dim=-1)
202
+
203
+
204
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1):
205
+ """Applies Rotary Position Embedding to the query and key tensors.
206
+
207
+ Args:
208
+ q (`torch.Tensor`): The query tensor.
209
+ k (`torch.Tensor`): The key tensor.
210
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
211
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
212
+ position_ids (`torch.Tensor`):
213
+ The position indices of the tokens corresponding to the query and key tensors. For example, this can be
214
+ used to pass offsetted position ids when working with a KV-cache.
215
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
216
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
217
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
218
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
219
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
220
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
221
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
222
+ Returns:
223
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
224
+ """
225
+ cos = cos[position_ids].unsqueeze(unsqueeze_dim)
226
+ sin = sin[position_ids].unsqueeze(unsqueeze_dim)
227
+ q_embed = (q * cos) + (rotate_half(q) * sin)
228
+ k_embed = (k * cos) + (rotate_half(k) * sin)
229
+ return q_embed, k_embed
230
+
231
+
232
+ class LlamaMLP(nn.Module):
233
+ def __init__(self, config):
234
+ super().__init__()
235
+ self.config = config
236
+ self.hidden_size = config.hidden_size
237
+ self.intermediate_size = config.intermediate_size
238
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
239
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
240
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
241
+ self.act_fn = ACT2FN[config.hidden_act]
242
+
243
+ def forward(self, x):
244
+ if self.config.pretraining_tp > 1:
245
+ slice = self.intermediate_size // self.config.pretraining_tp
246
+ gate_proj_slices = self.gate_proj.weight.split(slice, dim=0)
247
+ up_proj_slices = self.up_proj.weight.split(slice, dim=0)
248
+ down_proj_slices = self.down_proj.weight.split(slice, dim=1)
249
+
250
+ gate_proj = torch.cat(
251
+ [F.linear(x, gate_proj_slices[i]) for i in range(self.config.pretraining_tp)], dim=-1
252
+ )
253
+ up_proj = torch.cat([F.linear(x, up_proj_slices[i]) for i in range(self.config.pretraining_tp)], dim=-1)
254
+
255
+ intermediate_states = (self.act_fn(gate_proj) * up_proj).split(slice, dim=2)
256
+ down_proj = [
257
+ F.linear(intermediate_states[i], down_proj_slices[i]) for i in range(self.config.pretraining_tp)
258
+ ]
259
+ down_proj = sum(down_proj)
260
+ else:
261
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
262
+
263
+ return down_proj
264
+
265
+
266
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
267
+ """
268
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
269
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
270
+ """
271
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
272
+ if n_rep == 1:
273
+ return hidden_states
274
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
275
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
276
+
277
+
278
+ class LlamaAttention(nn.Module):
279
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
280
+
281
+ def __init__(self, config: LlamaConfig, layer_idx: Optional[int] = None):
282
+ super().__init__()
283
+ self.config = config
284
+ self.layer_idx = layer_idx
285
+ if layer_idx is None:
286
+ logger.warning_once(
287
+ f"Instantiating {self.__class__.__name__} without passing `layer_idx` is not recommended and will "
288
+ "to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` "
289
+ "when creating this class."
290
+ )
291
+
292
+ self.attention_dropout = config.attention_dropout
293
+ self.hidden_size = config.hidden_size
294
+ self.num_heads = config.num_attention_heads
295
+ self.head_dim = self.hidden_size // self.num_heads
296
+ self.num_key_value_heads = config.num_key_value_heads
297
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
298
+ self.max_position_embeddings = config.max_position_embeddings
299
+ self.rope_theta = config.rope_theta
300
+ self.is_causal = True
301
+
302
+ # fixme: config needs to be updated to include these parameters
303
+ self._lambda_ts = 1
304
+ self._lambda_st = 1
305
+ self._lambda_ss = 1
306
+
307
+ if (self.head_dim * self.num_heads) != self.hidden_size:
308
+ raise ValueError(
309
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
310
+ f" and `num_heads`: {self.num_heads})."
311
+ )
312
+
313
+ self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=config.attention_bias)
314
+ self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
315
+ self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
316
+ self.spatial_q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=config.attention_bias)
317
+ self.spatial_k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
318
+ self.spatial_v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
319
+ self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=config.attention_bias)
320
+ self._init_rope()
321
+
322
+ def _init_rope(self):
323
+ if self.config.rope_scaling is None:
324
+ self.rotary_emb = LlamaRotaryEmbedding(
325
+ self.head_dim,
326
+ max_position_embeddings=self.max_position_embeddings,
327
+ base=self.rope_theta,
328
+ )
329
+ else:
330
+ scaling_type = self.config.rope_scaling["type"]
331
+ scaling_factor = self.config.rope_scaling["factor"]
332
+ if scaling_type == "linear":
333
+ self.rotary_emb = LlamaLinearScalingRotaryEmbedding(
334
+ self.head_dim,
335
+ max_position_embeddings=self.max_position_embeddings,
336
+ scaling_factor=scaling_factor,
337
+ base=self.rope_theta,
338
+ )
339
+ elif scaling_type == "dynamic":
340
+ self.rotary_emb = LlamaDynamicNTKScalingRotaryEmbedding(
341
+ self.head_dim,
342
+ max_position_embeddings=self.max_position_embeddings,
343
+ scaling_factor=scaling_factor,
344
+ base=self.rope_theta,
345
+ )
346
+ else:
347
+ raise ValueError(f"Unknown RoPE scaling type {scaling_type}")
348
+
349
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
350
+ return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
351
+
352
+ def forward(
353
+ self,
354
+ hidden_states: torch.Tensor,
355
+ bounding_box_embeddings: torch.Tensor,
356
+ attention_mask: Optional[torch.Tensor] = None,
357
+ position_ids: Optional[torch.LongTensor] = None,
358
+ past_key_value: Optional[Cache] = None,
359
+ spatial_past_key_value: Optional[Cache] = None,
360
+ output_attentions: bool = False,
361
+ use_cache: bool = False,
362
+ **kwargs,
363
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
364
+ if "padding_mask" in kwargs:
365
+ warnings.warn(
366
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
367
+ )
368
+
369
+ bsz, q_len, _ = hidden_states.size()
370
+
371
+ if self.config.pretraining_tp > 1:
372
+ key_value_slicing = (self.num_key_value_heads * self.head_dim) // self.config.pretraining_tp
373
+ query_slices = self.q_proj.weight.split(
374
+ (self.num_heads * self.head_dim) // self.config.pretraining_tp, dim=0
375
+ )
376
+ key_slices = self.k_proj.weight.split(key_value_slicing, dim=0)
377
+ value_slices = self.v_proj.weight.split(key_value_slicing, dim=0)
378
+
379
+ spatial_query_slices = self.spatial_q_proj.weight.split(
380
+ (self.num_heads * self.head_dim) // self.config.pretraining_tp, dim=0
381
+ )
382
+ spatial_key_slices = self.spatial_k_proj.weight.split(key_value_slicing, dim=0)
383
+ spatial_value_slices = self.spatial_v_proj.weight.split(key_value_slicing, dim=0)
384
+
385
+ query_states = [F.linear(hidden_states, query_slices[i]) for i in range(self.config.pretraining_tp)]
386
+ query_states = torch.cat(query_states, dim=-1)
387
+ spatial_query_states = [F.linear(bounding_box_embeddings, spatial_query_slices[i]) for i in range(self.config.pretraining_tp)]
388
+ spatial_query_states = torch.cat(spatial_query_states, dim=-1)
389
+
390
+ key_states = [F.linear(hidden_states, key_slices[i]) for i in range(self.config.pretraining_tp)]
391
+ key_states = torch.cat(key_states, dim=-1)
392
+ spatial_key_states = [F.linear(bounding_box_embeddings, spatial_key_slices[i]) for i in range(self.config.pretraining_tp)]
393
+ spatial_key_states = torch.cat(spatial_key_states, dim=-1)
394
+
395
+ value_states = [F.linear(hidden_states, value_slices[i]) for i in range(self.config.pretraining_tp)]
396
+ value_states = torch.cat(value_states, dim=-1)
397
+ spatial_value_states = [F.linear(bounding_box_embeddings, spatial_value_slices[i]) for i in range(self.config.pretraining_tp)]
398
+ spatial_value_states = torch.cat(spatial_value_states, dim=-1)
399
+ else:
400
+ query_states = self.q_proj(hidden_states)
401
+ key_states = self.k_proj(hidden_states)
402
+ value_states = self.v_proj(hidden_states)
403
+
404
+ spatial_query_states = self.spatial_q_proj(bounding_box_embeddings)
405
+ spatial_key_states = self.spatial_k_proj(bounding_box_embeddings)
406
+ spatial_value_states = self.spatial_v_proj(bounding_box_embeddings)
407
+
408
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
409
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
410
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
411
+ spatial_query_states = spatial_query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
412
+ spatial_key_states = spatial_key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
413
+ spatial_value_states = spatial_value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
414
+
415
+ kv_seq_len = key_states.shape[-2]
416
+ if past_key_value is not None:
417
+ if self.layer_idx is None:
418
+ raise ValueError(
419
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
420
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
421
+ "with a layer index."
422
+ )
423
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
424
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
425
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
426
+
427
+ # fixme: do we need to apply rotary pos emb to spatial query and key states?
428
+ spatial_query_states, spatial_key_states = apply_rotary_pos_emb(spatial_query_states, spatial_key_states, cos, sin, position_ids)
429
+
430
+ if past_key_value is not None:
431
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
432
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
433
+ if spatial_past_key_value is not None:
434
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
435
+ spatial_key_states, spatial_value_states = spatial_past_key_value.update(spatial_key_states, spatial_value_states, self.layer_idx, cache_kwargs)
436
+
437
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
438
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
439
+ spatial_key_states = repeat_kv(spatial_key_states, self.num_key_value_groups)
440
+
441
+ attn_weight_tt = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
442
+ attn_weight_ts = torch.matmul(query_states, spatial_key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
443
+ attn_weight_st = torch.matmul(spatial_query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
444
+ attn_weight_ss = torch.matmul(spatial_query_states, spatial_key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
445
+
446
+ attn_weights = attn_weight_tt + self._lambda_ts * attn_weight_ts + self._lambda_st * attn_weight_st + self._lambda_ss * attn_weight_ss
447
+
448
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
449
+ raise ValueError(
450
+ f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
451
+ f" {attn_weights.size()}"
452
+ )
453
+
454
+ if attention_mask is not None:
455
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
456
+ raise ValueError(
457
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
458
+ )
459
+ attn_weights = attn_weights + attention_mask
460
+
461
+ # upcast attention to fp32
462
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
463
+ attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
464
+ attn_output = torch.matmul(attn_weights, value_states)
465
+
466
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
467
+ raise ValueError(
468
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
469
+ f" {attn_output.size()}"
470
+ )
471
+
472
+ attn_output = attn_output.transpose(1, 2).contiguous()
473
+
474
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
475
+
476
+ if self.config.pretraining_tp > 1:
477
+ attn_output = attn_output.split(self.hidden_size // self.config.pretraining_tp, dim=2)
478
+ o_proj_slices = self.o_proj.weight.split(self.hidden_size // self.config.pretraining_tp, dim=1)
479
+ attn_output = sum([F.linear(attn_output[i], o_proj_slices[i]) for i in range(self.config.pretraining_tp)])
480
+ else:
481
+ attn_output = self.o_proj(attn_output)
482
+
483
+ if not output_attentions:
484
+ attn_weights = None
485
+
486
+ return attn_output, attn_weights, past_key_value, spatial_past_key_value
487
+
488
+
489
+ class LlamaDecoderLayer(nn.Module):
490
+ def __init__(self, config: LlamaConfig, layer_idx: int):
491
+ super().__init__()
492
+ self.hidden_size = config.hidden_size
493
+
494
+ # flash attention is not supported for Docllm model yet
495
+ # self.self_attn = LLAMA_ATTENTION_CLASSES[config._attn_implementation](config=config, layer_idx=layer_idx)
496
+ self.self_attn = LlamaAttention(config=config, layer_idx=layer_idx)
497
+ self.mlp = LlamaMLP(config)
498
+ self.input_layernorm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
499
+ self.post_attention_layernorm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
500
+
501
+ def forward(
502
+ self,
503
+ hidden_states: torch.Tensor,
504
+ bounding_box_embeddings: Optional[torch.Tensor] = None,
505
+ attention_mask: Optional[torch.Tensor] = None,
506
+ position_ids: Optional[torch.LongTensor] = None,
507
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
508
+ spatial_past_key_value: Optional[Tuple[torch.Tensor]] = None,
509
+ output_attentions: Optional[bool] = False,
510
+ use_cache: Optional[bool] = False,
511
+ **kwargs,
512
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
513
+ """
514
+ Args:
515
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
516
+ attention_mask (`torch.FloatTensor`, *optional*):
517
+ attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
518
+ query_sequence_length, key_sequence_length)` if default attention is used.
519
+ output_attentions (`bool`, *optional*):
520
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
521
+ returned tensors for more detail.
522
+ use_cache (`bool`, *optional*):
523
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
524
+ (see `past_key_values`).
525
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
526
+ """
527
+ if "padding_mask" in kwargs:
528
+ warnings.warn(
529
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
530
+ )
531
+
532
+ residual = hidden_states
533
+
534
+ hidden_states = self.input_layernorm(hidden_states)
535
+
536
+ # Self Attention
537
+ hidden_states, self_attn_weights, present_key_value, spatial_present_key_value = self.self_attn(
538
+ hidden_states=hidden_states,
539
+ bounding_box_embeddings=bounding_box_embeddings,
540
+ attention_mask=attention_mask,
541
+ position_ids=position_ids,
542
+ past_key_value=past_key_value,
543
+ spatial_past_key_value=spatial_past_key_value,
544
+ output_attentions=output_attentions,
545
+ use_cache=use_cache,
546
+ **kwargs,
547
+ )
548
+ hidden_states = residual + hidden_states
549
+
550
+ # Fully Connected
551
+ residual = hidden_states
552
+ hidden_states = self.post_attention_layernorm(hidden_states)
553
+ hidden_states = self.mlp(hidden_states)
554
+ hidden_states = residual + hidden_states
555
+
556
+ outputs = (hidden_states,)
557
+
558
+ if output_attentions:
559
+ outputs += (self_attn_weights,)
560
+
561
+ if use_cache:
562
+ outputs += (present_key_value,)
563
+ outputs += (spatial_present_key_value,)
564
+
565
+ return outputs
566
+
567
+
568
+ LLAMA_START_DOCSTRING = r"""
569
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
570
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
571
+ etc.)
572
+
573
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
574
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
575
+ and behavior.
576
+
577
+ Parameters:
578
+ config ([`LlamaConfig`]):
579
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
580
+ load the weights associated with the model, only the configuration. Check out the
581
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
582
+ """
583
+
584
+
585
+ @add_start_docstrings(
586
+ "The bare LLaMA Model outputting raw hidden-states without any specific head on top.",
587
+ LLAMA_START_DOCSTRING,
588
+ )
589
+ class LlamaPreTrainedModel(PreTrainedModel):
590
+ config_class = LlamaConfig
591
+ base_model_prefix = "model"
592
+ supports_gradient_checkpointing = True
593
+ _no_split_modules = ["LlamaDecoderLayer"]
594
+ _skip_keys_device_placement = "past_key_values"
595
+ _supports_cache_class = True
596
+
597
+ def _init_weights(self, module):
598
+ std = self.config.initializer_range
599
+ if isinstance(module, nn.Linear):
600
+ module.weight.data.normal_(mean=0.0, std=std)
601
+ if module.bias is not None:
602
+ module.bias.data.zero_()
603
+ elif isinstance(module, nn.Embedding):
604
+ module.weight.data.normal_(mean=0.0, std=std)
605
+ if module.padding_idx is not None:
606
+ module.weight.data[module.padding_idx].zero_()
607
+
608
+
609
+ LLAMA_INPUTS_DOCSTRING = r"""
610
+ Args:
611
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
612
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
613
+ it.
614
+
615
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
616
+ [`PreTrainedTokenizer.__call__`] for details.
617
+
618
+ [What are input IDs?](../glossary#input-ids)
619
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
620
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
621
+
622
+ - 1 for tokens that are **not masked**,
623
+ - 0 for tokens that are **masked**.
624
+
625
+ [What are attention masks?](../glossary#attention-mask)
626
+
627
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
628
+ [`PreTrainedTokenizer.__call__`] for details.
629
+
630
+ If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
631
+ `past_key_values`).
632
+
633
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
634
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
635
+ information on the default strategy.
636
+
637
+ - 1 indicates the head is **not masked**,
638
+ - 0 indicates the head is **masked**.
639
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
640
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
641
+ config.n_positions - 1]`.
642
+
643
+ [What are position IDs?](../glossary#position-ids)
644
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
645
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
646
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
647
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
648
+
649
+ Two formats are allowed:
650
+ - a [`~cache_utils.Cache`] instance;
651
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
652
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
653
+ cache format.
654
+
655
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
656
+ legacy cache format will be returned.
657
+
658
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
659
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
660
+ of shape `(batch_size, sequence_length)`.
661
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
662
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
663
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
664
+ model's internal embedding lookup matrix.
665
+ use_cache (`bool`, *optional*):
666
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
667
+ `past_key_values`).
668
+ output_attentions (`bool`, *optional*):
669
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
670
+ tensors for more detail.
671
+ output_hidden_states (`bool`, *optional*):
672
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
673
+ more detail.
674
+ return_dict (`bool`, *optional*):
675
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
676
+ """
677
+
678
+
679
+ @add_start_docstrings(
680
+ "The bare LLaMA Model outputting raw hidden-states without any specific head on top.",
681
+ LLAMA_START_DOCSTRING,
682
+ )
683
+ class DocLLMBaseModelOutputWithPast(BaseModelOutputWithPast):
684
+ def __init__(self, *args, spatial_past_key_values=None, **kwargs):
685
+ super().__init__(*args, **kwargs)
686
+ self.spatial_past_key_values = spatial_past_key_values
687
+
688
+
689
+ class DocLLMCausalLMOutputWithPast(CausalLMOutputWithPast):
690
+ def __init__(self, *args, spatial_past_key_values=None, **kwargs):
691
+ super().__init__(*args, **kwargs)
692
+ self.spatial_past_key_values = spatial_past_key_values
693
+
694
+
695
+ class LlamaModel(LlamaPreTrainedModel):
696
+ """
697
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`LlamaDecoderLayer`]
698
+
699
+ Args:
700
+ config: LlamaConfig
701
+ """
702
+
703
+ def __init__(self, config: LlamaConfig):
704
+ super().__init__(config)
705
+ self.padding_idx = config.pad_token_id
706
+ self.vocab_size = config.vocab_size
707
+
708
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
709
+ self.embed_spatial = nn.Linear(4, config.hidden_size, bias=False)
710
+ self.layers = nn.ModuleList(
711
+ [LlamaDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
712
+ )
713
+ self._use_sdpa = config._attn_implementation == "sdpa"
714
+ # self._use_flash_attention_2 = config._attn_implementation == "flash_attention_2"
715
+ self.norm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
716
+
717
+ self.gradient_checkpointing = False
718
+ # Initialize weights and apply final processing
719
+ self.post_init()
720
+
721
+ def get_input_embeddings(self):
722
+ return self.embed_tokens
723
+
724
+ def set_input_embeddings(self, value):
725
+ self.embed_tokens = value
726
+
727
+ @add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
728
+ def forward(
729
+ self,
730
+ input_ids: torch.LongTensor = None,
731
+ input_coordinates: torch.FloatTensor = None,
732
+ attention_mask: Optional[torch.Tensor] = None,
733
+ position_ids: Optional[torch.LongTensor] = None,
734
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
735
+ spatial_past_key_values: Optional[torch.FloatTensor] = None,
736
+ inputs_embeds: Optional[torch.FloatTensor] = None,
737
+ use_cache: Optional[bool] = None,
738
+ output_attentions: Optional[bool] = None,
739
+ output_hidden_states: Optional[bool] = None,
740
+ return_dict: Optional[bool] = None,
741
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
742
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
743
+ output_hidden_states = (
744
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
745
+ )
746
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
747
+
748
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
749
+
750
+ # retrieve input_ids and inputs_embeds
751
+ if input_ids is not None and inputs_embeds is not None:
752
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
753
+ elif input_ids is not None:
754
+ batch_size, seq_length = input_ids.shape[:2]
755
+ elif inputs_embeds is not None:
756
+ batch_size, seq_length = inputs_embeds.shape[:2]
757
+ else:
758
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
759
+ assert input_ids.device == input_coordinates.device
760
+
761
+ if self.gradient_checkpointing and self.training:
762
+ if use_cache:
763
+ logger.warning_once(
764
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
765
+ )
766
+ use_cache = False
767
+
768
+ past_key_values_length = 0
769
+ if use_cache:
770
+ use_legacy_cache = not isinstance(past_key_values, Cache)
771
+ if use_legacy_cache:
772
+ past_key_values = DynamicCache.from_legacy_cache(past_key_values)
773
+ past_key_values_length = past_key_values.get_usable_length(seq_length)
774
+
775
+ spatial_use_legacy_cache = not isinstance(spatial_past_key_values, Cache)
776
+ if spatial_use_legacy_cache:
777
+ spatial_past_key_values = DynamicCache.from_legacy_cache(spatial_past_key_values)
778
+
779
+ if position_ids is None:
780
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
781
+ position_ids = torch.arange(
782
+ past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
783
+ )
784
+ position_ids = position_ids.unsqueeze(0)
785
+
786
+ if inputs_embeds is None:
787
+ inputs_embeds = self.embed_tokens(input_ids)
788
+
789
+ coordinate_embeds = self.embed_spatial(input_coordinates)
790
+
791
+ # if self._use_flash_attention_2:
792
+ # # 2d mask is passed through the layers
793
+ # attention_mask = attention_mask if (attention_mask is not None and 0 in attention_mask) else None
794
+ if self._use_sdpa and not output_attentions:
795
+ # output_attentions=True can not be supported when using SDPA, and we fall back on
796
+ # the manual implementation that requires a 4D causal mask in all cases.
797
+ attention_mask = _prepare_4d_causal_attention_mask_for_sdpa(
798
+ attention_mask,
799
+ (batch_size, seq_length),
800
+ inputs_embeds,
801
+ past_key_values_length,
802
+ )
803
+ else:
804
+ # 4d mask is passed through the layers
805
+ attention_mask = _prepare_4d_causal_attention_mask(
806
+ attention_mask, (batch_size, seq_length), inputs_embeds, past_key_values_length
807
+ )
808
+
809
+ # embed positions
810
+ hidden_states = inputs_embeds
811
+
812
+ # decoder layers
813
+ all_hidden_states = () if output_hidden_states else None
814
+ all_self_attns = () if output_attentions else None
815
+ next_decoder_cache = None
816
+ spatial_next_decoder_cache = None
817
+
818
+ for decoder_layer in self.layers:
819
+ if output_hidden_states:
820
+ all_hidden_states += (hidden_states,)
821
+
822
+ if self.gradient_checkpointing and self.training:
823
+ layer_outputs = self._gradient_checkpointing_func(
824
+ decoder_layer.__call__,
825
+ hidden_states,
826
+ coordinate_embeds,
827
+ attention_mask,
828
+ position_ids,
829
+ past_key_values,
830
+ output_attentions,
831
+ use_cache,
832
+ )
833
+ else:
834
+ layer_outputs = decoder_layer(
835
+ hidden_states,
836
+ coordinate_embeds,
837
+ attention_mask=attention_mask,
838
+ position_ids=position_ids,
839
+ past_key_value=past_key_values,
840
+ spatial_past_key_value=spatial_past_key_values,
841
+ output_attentions=output_attentions,
842
+ use_cache=use_cache,
843
+ )
844
+
845
+ hidden_states = layer_outputs[0]
846
+
847
+ if use_cache:
848
+ next_decoder_cache = layer_outputs[2 if output_attentions else 1]
849
+ spatial_next_decoder_cache = layer_outputs[3 if output_attentions else 2]
850
+
851
+ if output_attentions:
852
+ all_self_attns += (layer_outputs[1],)
853
+
854
+ hidden_states = self.norm(hidden_states)
855
+
856
+ # add hidden states from the last decoder layer
857
+ if output_hidden_states:
858
+ all_hidden_states += (hidden_states,)
859
+
860
+ next_cache = None
861
+ spatial_next_cache = None
862
+ if use_cache:
863
+ next_cache = next_decoder_cache.to_legacy_cache() if use_legacy_cache else next_decoder_cache
864
+ spatial_next_cache = spatial_next_decoder_cache.to_legacy_cache() if spatial_use_legacy_cache \
865
+ else spatial_next_decoder_cache
866
+ if not return_dict:
867
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
868
+ return DocLLMBaseModelOutputWithPast(
869
+ last_hidden_state=hidden_states,
870
+ past_key_values=next_cache,
871
+ spatial_past_key_values=spatial_next_cache,
872
+ hidden_states=all_hidden_states,
873
+ attentions=all_self_attns,
874
+ )
875
+
876
+
877
+ class LlamaForCausalLM(LlamaPreTrainedModel):
878
+ _tied_weights_keys = ["lm_head.weight"]
879
+
880
+ def __init__(self, config):
881
+ super().__init__(config)
882
+ self.model = LlamaModel(config)
883
+ self.vocab_size = config.vocab_size
884
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
885
+
886
+ # Initialize weights and apply final processing
887
+ self.post_init()
888
+
889
+ def get_input_embeddings(self):
890
+ return self.model.embed_tokens
891
+
892
+ def set_input_embeddings(self, value):
893
+ self.model.embed_tokens = value
894
+
895
+ def get_output_embeddings(self):
896
+ return self.lm_head
897
+
898
+ def set_output_embeddings(self, new_embeddings):
899
+ self.lm_head = new_embeddings
900
+
901
+ def set_decoder(self, decoder):
902
+ self.model = decoder
903
+
904
+ def get_decoder(self):
905
+ return self.model
906
+
907
+ @add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
908
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
909
+ def forward(
910
+ self,
911
+ input_ids: torch.LongTensor = None,
912
+ input_coordinates: torch.FloatTensor = None,
913
+ attention_mask: Optional[torch.Tensor] = None,
914
+ position_ids: Optional[torch.LongTensor] = None,
915
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
916
+ spatial_past_key_values: Optional[List[torch.FloatTensor]] = None,
917
+ inputs_embeds: Optional[torch.FloatTensor] = None,
918
+ labels: Optional[torch.LongTensor] = None,
919
+ use_cache: Optional[bool] = None,
920
+ output_attentions: Optional[bool] = None,
921
+ output_hidden_states: Optional[bool] = None,
922
+ return_dict: Optional[bool] = None,
923
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
924
+ r"""
925
+ Args:
926
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
927
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
928
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
929
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
930
+
931
+ Returns:
932
+
933
+ Example:
934
+
935
+ ```python
936
+ >>> from transformers import AutoTokenizer, LlamaForCausalLM
937
+
938
+ >>> model = LlamaForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
939
+ >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
940
+
941
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
942
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
943
+
944
+ >>> # Generate
945
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
946
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
947
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
948
+ ```"""
949
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
950
+ output_hidden_states = (
951
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
952
+ )
953
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
954
+
955
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
956
+ outputs = self.model(
957
+ input_ids=input_ids,
958
+ input_coordinates=input_coordinates,
959
+ attention_mask=attention_mask,
960
+ position_ids=position_ids,
961
+ past_key_values=past_key_values,
962
+ spatial_past_key_values=spatial_past_key_values,
963
+ inputs_embeds=inputs_embeds,
964
+ use_cache=use_cache,
965
+ output_attentions=output_attentions,
966
+ output_hidden_states=output_hidden_states,
967
+ return_dict=return_dict,
968
+ )
969
+
970
+ hidden_states = outputs[0]
971
+ if self.config.pretraining_tp > 1:
972
+ lm_head_slices = self.lm_head.weight.split(self.vocab_size // self.config.pretraining_tp, dim=0)
973
+ logits = [F.linear(hidden_states, lm_head_slices[i]) for i in range(self.config.pretraining_tp)]
974
+ logits = torch.cat(logits, dim=-1)
975
+ else:
976
+ logits = self.lm_head(hidden_states)
977
+ logits = logits.float()
978
+
979
+ loss = None
980
+ if labels is not None:
981
+ # Shift so that tokens < n predict n
982
+ shift_logits = logits[..., :-1, :].contiguous()
983
+ shift_labels = labels[..., 1:].contiguous()
984
+ # Flatten the tokens
985
+ loss_fct = CrossEntropyLoss()
986
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
987
+ shift_labels = shift_labels.view(-1)
988
+ # Enable model parallelism
989
+ shift_labels = shift_labels.to(shift_logits.device)
990
+ loss = loss_fct(shift_logits, shift_labels)
991
+
992
+ if not return_dict:
993
+ output = (logits,) + outputs[1:]
994
+ return (loss,) + output if loss is not None else output
995
+
996
+ return DocLLMCausalLMOutputWithPast(
997
+ loss=loss,
998
+ logits=logits,
999
+ past_key_values=outputs.past_key_values,
1000
+ spatial_past_key_values=outputs.spatial_past_key_values,
1001
+ hidden_states=outputs.hidden_states,
1002
+ attentions=outputs.attentions,
1003
+ )
1004
+
1005
+ def prepare_inputs_for_generation(
1006
+ self, input_ids, input_coordinates, past_key_values=None, spatial_pst_key_values=None,
1007
+ attention_mask=None, inputs_embeds=None, coordinates_embeds=None, **kwargs
1008
+ ):
1009
+ if past_key_values is not None:
1010
+ if isinstance(past_key_values, Cache):
1011
+ cache_length = past_key_values.get_seq_length()
1012
+ past_length = past_key_values.seen_tokens
1013
+ max_cache_length = past_key_values.get_max_length()
1014
+ else:
1015
+ cache_length = past_length = past_key_values[0][0].shape[2]
1016
+ max_cache_length = None
1017
+
1018
+ # Keep only the unprocessed tokens:
1019
+ # 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where
1020
+ # some of the inputs are exclusivelly passed as part of the cache (e.g. when passing input_embeds as
1021
+ # input)
1022
+ if attention_mask is not None and attention_mask.shape[1] > input_ids.shape[1]:
1023
+ input_ids = input_ids[:, -(attention_mask.shape[1] - past_length):]
1024
+ input_coordinates = input_coordinates[:, -(attention_mask.shape[1] - past_length):]
1025
+ # 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens. We can discard
1026
+ # input_ids based on the past_length.
1027
+ elif past_length < input_ids.shape[1]:
1028
+ input_ids = input_ids[:, past_length:]
1029
+ input_coordinates = input_coordinates[:, past_length:]
1030
+ # 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens.
1031
+
1032
+ # If we are about to go beyond the maximum cache length, we need to crop the input attention mask.
1033
+ if (
1034
+ max_cache_length is not None
1035
+ and attention_mask is not None
1036
+ and cache_length + input_ids.shape[1] > max_cache_length
1037
+ ):
1038
+ attention_mask = attention_mask[:, -max_cache_length:]
1039
+
1040
+ position_ids = kwargs.get("position_ids", None)
1041
+ if attention_mask is not None and position_ids is None:
1042
+ # create position_ids on the fly for batch generation
1043
+ position_ids = attention_mask.long().cumsum(-1) - 1
1044
+ position_ids.masked_fill_(attention_mask == 0, 1)
1045
+ if past_key_values:
1046
+ position_ids = position_ids[:, -input_ids.shape[1]:]
1047
+
1048
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1049
+ if inputs_embeds is not None and past_key_values is None:
1050
+ model_inputs = {"inputs_embeds": inputs_embeds,
1051
+ "coordinates_embeds": coordinates_embeds}
1052
+ else:
1053
+ model_inputs = {"input_ids": input_ids,
1054
+ "input_coordinates": input_coordinates}
1055
+
1056
+ model_inputs.update(
1057
+ {
1058
+ "position_ids": position_ids,
1059
+ "past_key_values": past_key_values,
1060
+ "spatial_past_key_values": spatial_pst_key_values,
1061
+ "use_cache": kwargs.get("use_cache"),
1062
+ "attention_mask": attention_mask,
1063
+ }
1064
+ )
1065
+ return model_inputs
1066
+
1067
+ @staticmethod
1068
+ def _reorder_cache(past_key_values, beam_idx):
1069
+ reordered_past = ()
1070
+ for layer_past in past_key_values:
1071
+ reordered_past += (
1072
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
1073
+ )
1074
+ return reordered_past