Create modeling_llama_encoder.py
Browse files- modeling_llama_encoder.py +198 -0
modeling_llama_encoder.py
ADDED
@@ -0,0 +1,198 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
|
3 |
+
from packaging import version
|
4 |
+
import importlib.metadata
|
5 |
+
|
6 |
+
from transformers import LlamaModel, LlamaForCausalLM, LlamaPreTrainedModel, LlamaConfig
|
7 |
+
from transformers.models.llama.modeling_llama import (
|
8 |
+
LlamaDecoderLayer,
|
9 |
+
LlamaAttention,
|
10 |
+
LlamaFlashAttention2,
|
11 |
+
LlamaSdpaAttention,
|
12 |
+
LlamaMLP,
|
13 |
+
LlamaRMSNorm,
|
14 |
+
LlamaRotaryEmbedding,
|
15 |
+
)
|
16 |
+
|
17 |
+
from torch import nn
|
18 |
+
from transformers.utils import logging
|
19 |
+
from transformers.cache_utils import Cache, StaticCache
|
20 |
+
|
21 |
+
from transformers.modeling_attn_mask_utils import AttentionMaskConverter
|
22 |
+
from transformers.utils.import_utils import _is_package_available
|
23 |
+
|
24 |
+
from peft import PeftModel
|
25 |
+
|
26 |
+
logger = logging.get_logger(__name__)
|
27 |
+
|
28 |
+
|
29 |
+
def is_transformers_attn_greater_or_equal_4_43_1():
|
30 |
+
if not _is_package_available("transformers"):
|
31 |
+
return False
|
32 |
+
|
33 |
+
return version.parse(importlib.metadata.version("transformers")) >= version.parse(
|
34 |
+
"4.43.1"
|
35 |
+
)
|
36 |
+
|
37 |
+
|
38 |
+
class ModifiedLlamaAttention(LlamaAttention):
|
39 |
+
def __init__(self, *args, **kwargs):
|
40 |
+
super().__init__(*args, **kwargs)
|
41 |
+
self.is_causal = False
|
42 |
+
|
43 |
+
|
44 |
+
class ModifiedLlamaFlashAttention2(LlamaFlashAttention2):
|
45 |
+
def __init__(self, *args, **kwargs):
|
46 |
+
super().__init__(*args, **kwargs)
|
47 |
+
self.is_causal = False
|
48 |
+
|
49 |
+
|
50 |
+
class ModifiedLlamaSdpaAttention(LlamaSdpaAttention):
|
51 |
+
def __init__(self, *args, **kwargs):
|
52 |
+
super().__init__(*args, **kwargs)
|
53 |
+
self.is_causal = False
|
54 |
+
|
55 |
+
|
56 |
+
LLAMA_ATTENTION_CLASSES = {
|
57 |
+
"eager": ModifiedLlamaAttention,
|
58 |
+
"flash_attention_2": ModifiedLlamaFlashAttention2,
|
59 |
+
"sdpa": ModifiedLlamaSdpaAttention,
|
60 |
+
}
|
61 |
+
|
62 |
+
|
63 |
+
class ModifiedLlamaDecoderLayer(LlamaDecoderLayer):
|
64 |
+
def __init__(self, config: LlamaConfig, layer_idx: int):
|
65 |
+
nn.Module.__init__(self)
|
66 |
+
self.hidden_size = config.hidden_size
|
67 |
+
|
68 |
+
self.self_attn = LLAMA_ATTENTION_CLASSES[config._attn_implementation](
|
69 |
+
config=config, layer_idx=layer_idx
|
70 |
+
)
|
71 |
+
|
72 |
+
self.mlp = LlamaMLP(config)
|
73 |
+
self.input_layernorm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
74 |
+
self.post_attention_layernorm = LlamaRMSNorm(
|
75 |
+
config.hidden_size, eps=config.rms_norm_eps
|
76 |
+
)
|
77 |
+
|
78 |
+
|
79 |
+
class LlamaEncoderModel(LlamaModel):
|
80 |
+
_no_split_modules = ["ModifiedLlamaDecoderLayer"]
|
81 |
+
|
82 |
+
def __init__(self, config: LlamaConfig):
|
83 |
+
if not is_transformers_attn_greater_or_equal_4_43_1():
|
84 |
+
raise ValueError(
|
85 |
+
"The current implementation of LlamaEncoderModel follows modeling_llama.py of transformers version >= 4.43.1"
|
86 |
+
)
|
87 |
+
LlamaPreTrainedModel.__init__(self, config)
|
88 |
+
self.padding_idx = config.pad_token_id
|
89 |
+
self.vocab_size = config.vocab_size
|
90 |
+
|
91 |
+
self.embed_tokens = nn.Embedding(
|
92 |
+
config.vocab_size, config.hidden_size, self.padding_idx
|
93 |
+
)
|
94 |
+
self.layers = nn.ModuleList(
|
95 |
+
[
|
96 |
+
ModifiedLlamaDecoderLayer(config, layer_idx)
|
97 |
+
for layer_idx in range(config.num_hidden_layers)
|
98 |
+
]
|
99 |
+
)
|
100 |
+
self.norm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
101 |
+
self.rotary_emb = LlamaRotaryEmbedding(config=config)
|
102 |
+
self.gradient_checkpointing = False
|
103 |
+
|
104 |
+
# Initialize weights and apply final processing
|
105 |
+
self.post_init()
|
106 |
+
|
107 |
+
def _update_causal_mask(
|
108 |
+
self,
|
109 |
+
attention_mask,
|
110 |
+
input_tensor,
|
111 |
+
cache_position,
|
112 |
+
past_key_values: Cache,
|
113 |
+
output_attentions: bool,
|
114 |
+
):
|
115 |
+
if self.config._attn_implementation == "flash_attention_2":
|
116 |
+
if attention_mask is not None and 0.0 in attention_mask:
|
117 |
+
return attention_mask
|
118 |
+
return None
|
119 |
+
|
120 |
+
# For SDPA, when possible, we will rely on its `is_causal` argument instead of its `attn_mask` argument, in
|
121 |
+
# order to dispatch on Flash Attention 2. This feature is not compatible with static cache, as SDPA will fail
|
122 |
+
# to infer the attention mask.
|
123 |
+
past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
|
124 |
+
using_static_cache = isinstance(past_key_values, StaticCache)
|
125 |
+
|
126 |
+
# When output attentions is True, sdpa implementation's forward method calls the eager implementation's forward
|
127 |
+
# if self.config._attn_implementation == "sdpa" and not using_static_cache and not output_attentions:
|
128 |
+
# if AttentionMaskConverter._ignore_causal_mask_sdpa(
|
129 |
+
# attention_mask,
|
130 |
+
# inputs_embeds=input_tensor,
|
131 |
+
# past_key_values_length=past_seen_tokens,
|
132 |
+
# is_training=self.training,
|
133 |
+
# ):
|
134 |
+
# return None
|
135 |
+
|
136 |
+
dtype, device = input_tensor.dtype, input_tensor.device
|
137 |
+
min_dtype = torch.finfo(dtype).min
|
138 |
+
sequence_length = input_tensor.shape[1]
|
139 |
+
if using_static_cache:
|
140 |
+
target_length = past_key_values.get_max_length()
|
141 |
+
else:
|
142 |
+
target_length = (
|
143 |
+
attention_mask.shape[-1]
|
144 |
+
if isinstance(attention_mask, torch.Tensor)
|
145 |
+
else past_seen_tokens + sequence_length + 1
|
146 |
+
)
|
147 |
+
|
148 |
+
causal_mask = torch.zeros(
|
149 |
+
(sequence_length, target_length), dtype=dtype, device=device
|
150 |
+
) # in original implementation - torch.full((sequence_length, target_length), fill_value=min_dtype, dtype=dtype, device=device)
|
151 |
+
# Commenting out next 2 lines to disable causal masking
|
152 |
+
# if sequence_length != 1:
|
153 |
+
# causal_mask = torch.triu(causal_mask, diagonal=1)
|
154 |
+
causal_mask *= torch.arange(
|
155 |
+
target_length, device=device
|
156 |
+
) > cache_position.reshape(-1, 1)
|
157 |
+
causal_mask = causal_mask[None, None, :, :].expand(
|
158 |
+
input_tensor.shape[0], 1, -1, -1
|
159 |
+
)
|
160 |
+
if attention_mask is not None:
|
161 |
+
causal_mask = (
|
162 |
+
causal_mask.clone()
|
163 |
+
) # copy to contiguous memory for in-place edit
|
164 |
+
if attention_mask.dim() == 2:
|
165 |
+
mask_length = attention_mask.shape[-1]
|
166 |
+
padding_mask = causal_mask[..., :mask_length].eq(0.0) * attention_mask[
|
167 |
+
:, None, None, :
|
168 |
+
].eq(0.0)
|
169 |
+
causal_mask[..., :mask_length] = causal_mask[
|
170 |
+
..., :mask_length
|
171 |
+
].masked_fill(padding_mask, min_dtype)
|
172 |
+
elif attention_mask.dim() == 4:
|
173 |
+
# backwards compatibility: we allow passing a 4D attention mask shorter than the input length with
|
174 |
+
# cache. In that case, the 4D attention mask attends to the newest tokens only.
|
175 |
+
if attention_mask.shape[-2] < cache_position[0] + sequence_length:
|
176 |
+
offset = cache_position[0]
|
177 |
+
else:
|
178 |
+
offset = 0
|
179 |
+
mask_shape = attention_mask.shape
|
180 |
+
mask_slice = (attention_mask.eq(0.0)).to(dtype=dtype) * min_dtype
|
181 |
+
causal_mask[
|
182 |
+
: mask_shape[0],
|
183 |
+
: mask_shape[1],
|
184 |
+
offset : mask_shape[2] + offset,
|
185 |
+
: mask_shape[3],
|
186 |
+
] = mask_slice
|
187 |
+
|
188 |
+
if (
|
189 |
+
self.config._attn_implementation == "sdpa"
|
190 |
+
and attention_mask is not None
|
191 |
+
and attention_mask.device.type == "cuda"
|
192 |
+
and not output_attentions
|
193 |
+
):
|
194 |
+
causal_mask = AttentionMaskConverter._unmask_unattended(
|
195 |
+
causal_mask, min_dtype
|
196 |
+
)
|
197 |
+
|
198 |
+
return causal_mask
|