Spaces:
Sleeping
Sleeping
Commit
·
429f1a9
1
Parent(s):
f7d2f16
Adds pharia model.
Browse files- app.py +5 -3
- source/models/pharia.py +696 -0
app.py
CHANGED
|
@@ -18,7 +18,9 @@ midi_instruments = {
|
|
| 18 |
# Load the model once and cache it.
|
| 19 |
@st.cache_resource
|
| 20 |
def load_model():
|
| 21 |
-
|
|
|
|
|
|
|
| 22 |
return model
|
| 23 |
model = load_model()
|
| 24 |
|
|
@@ -50,8 +52,8 @@ def main():
|
|
| 50 |
|
| 51 |
# Add a title.
|
| 52 |
st.title("Garland Composer")
|
| 53 |
-
linkedin_url = "https://
|
| 54 |
-
x_url = "https://
|
| 55 |
st.write(f"By Dr. Tristan Behrens. Find me on [LinkedIn]({linkedin_url}) and [X]({x_url}).")
|
| 56 |
hf_url = "https://huggingface.co/TristanBehrens/bach-garland-mambaplus/"
|
| 57 |
st.write(f"Model available on [Hugging Face]({hf_url}).")
|
|
|
|
| 18 |
# Load the model once and cache it.
|
| 19 |
@st.cache_resource
|
| 20 |
def load_model():
|
| 21 |
+
#model_id = "TristanBehrens/bach-garland-mambaplus"
|
| 22 |
+
model_id = "TristanBehrens/bach-garland-pharia"
|
| 23 |
+
model = LanguageModel(model_id)
|
| 24 |
return model
|
| 25 |
model = load_model()
|
| 26 |
|
|
|
|
| 52 |
|
| 53 |
# Add a title.
|
| 54 |
st.title("Garland Composer")
|
| 55 |
+
linkedin_url = "https://www.linkedin.com/dr-tristan-behrens-734967a2/"
|
| 56 |
+
x_url = "https://x.com/DrTBehrens"
|
| 57 |
st.write(f"By Dr. Tristan Behrens. Find me on [LinkedIn]({linkedin_url}) and [X]({x_url}).")
|
| 58 |
hf_url = "https://huggingface.co/TristanBehrens/bach-garland-mambaplus/"
|
| 59 |
st.write(f"Model available on [Hugging Face]({hf_url}).")
|
source/models/pharia.py
ADDED
|
@@ -0,0 +1,696 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from dataclasses import dataclass, field
|
| 2 |
+
from typing import Optional, Any
|
| 3 |
+
import math
|
| 4 |
+
from typing import List, Optional, Tuple, Union
|
| 5 |
+
import torch
|
| 6 |
+
from torch import nn
|
| 7 |
+
from transformers.activations import ACT2FN
|
| 8 |
+
from transformers.cache_utils import Cache, DynamicCache, StaticCache
|
| 9 |
+
from transformers.modeling_attn_mask_utils import AttentionMaskConverter
|
| 10 |
+
from transformers.modeling_outputs import (
|
| 11 |
+
BaseModelOutputWithPast,
|
| 12 |
+
CausalLMOutputWithPast,
|
| 13 |
+
)
|
| 14 |
+
from transformers.modeling_utils import PreTrainedModel
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
@dataclass
|
| 18 |
+
class PhariaConfig:
|
| 19 |
+
pad_token_id: Optional[int] = None
|
| 20 |
+
bos_token_id: int = 1
|
| 21 |
+
eos_token_id: int = 2
|
| 22 |
+
hidden_act: str = "gelu"
|
| 23 |
+
hidden_size: int = 512
|
| 24 |
+
initializer_range: float = 0.02
|
| 25 |
+
intermediate_size: int = 2048
|
| 26 |
+
max_position_embeddings: int = 8192
|
| 27 |
+
num_attention_heads: int = 4
|
| 28 |
+
num_hidden_layers: int = 4
|
| 29 |
+
num_key_value_heads: int = 2
|
| 30 |
+
torch_dtype: str = "bfloat16"
|
| 31 |
+
transformers_version: str = "4.31.0.dev0"
|
| 32 |
+
use_cache: bool = True
|
| 33 |
+
vocab_size: int = -1
|
| 34 |
+
mlp_bias: bool = True
|
| 35 |
+
attention_bias: bool = True
|
| 36 |
+
tie_word_embeddings: bool = False
|
| 37 |
+
attention_dropout: float = 0.0
|
| 38 |
+
rope_theta: int = 1000000
|
| 39 |
+
rope_scaling: Optional[Any] = None
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
class PhariaRotaryEmbedding(nn.Module):
|
| 44 |
+
def __init__(
|
| 45 |
+
self,
|
| 46 |
+
dim,
|
| 47 |
+
max_position_embeddings=2048,
|
| 48 |
+
base=10000,
|
| 49 |
+
device=None,
|
| 50 |
+
scaling_factor=1.0,
|
| 51 |
+
):
|
| 52 |
+
super().__init__()
|
| 53 |
+
self.scaling_factor = scaling_factor
|
| 54 |
+
self.dim = dim
|
| 55 |
+
self.max_position_embeddings = max_position_embeddings
|
| 56 |
+
self.base = base
|
| 57 |
+
inv_freq = 1.0 / (
|
| 58 |
+
self.base
|
| 59 |
+
** (
|
| 60 |
+
torch.arange(0, self.dim, 2, dtype=torch.int64).float().to(device)
|
| 61 |
+
/ self.dim
|
| 62 |
+
)
|
| 63 |
+
)
|
| 64 |
+
self.register_buffer("inv_freq", inv_freq, persistent=False)
|
| 65 |
+
# For BC we register cos and sin cached
|
| 66 |
+
self.max_seq_len_cached = max_position_embeddings
|
| 67 |
+
|
| 68 |
+
@torch.no_grad()
|
| 69 |
+
def forward(self, x, position_ids):
|
| 70 |
+
# x: [bs, num_attention_heads, seq_len, head_size]
|
| 71 |
+
inv_freq_expanded = (
|
| 72 |
+
self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
|
| 73 |
+
)
|
| 74 |
+
position_ids_expanded = position_ids[:, None, :].float()
|
| 75 |
+
# Force float32 since bfloat16 loses precision on long contexts
|
| 76 |
+
# See https://github.com/huggingface/transformers/pull/29285
|
| 77 |
+
device_type = x.device.type
|
| 78 |
+
device_type = (
|
| 79 |
+
device_type
|
| 80 |
+
if isinstance(device_type, str) and device_type != "mps"
|
| 81 |
+
else "cpu"
|
| 82 |
+
)
|
| 83 |
+
with torch.autocast(device_type=device_type, enabled=False):
|
| 84 |
+
freqs = (
|
| 85 |
+
inv_freq_expanded.float() @ position_ids_expanded.float()
|
| 86 |
+
).transpose(1, 2)
|
| 87 |
+
emb = freqs.repeat_interleave(2, dim=-1, output_size=self.dim)
|
| 88 |
+
cos = emb.cos()
|
| 89 |
+
sin = emb.sin()
|
| 90 |
+
|
| 91 |
+
return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
class PhariaLinearScalingRotaryEmbedding(PhariaRotaryEmbedding):
|
| 95 |
+
"""PhariaRotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendev"""
|
| 96 |
+
|
| 97 |
+
def forward(self, x, position_ids):
|
| 98 |
+
# difference to the original RoPE: a scaling factor is aplied to the position ids
|
| 99 |
+
position_ids = position_ids.float() / self.scaling_factor
|
| 100 |
+
cos, sin = super().forward(x, position_ids)
|
| 101 |
+
return cos, sin
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
class PhariaDynamicNTKScalingRotaryEmbedding(PhariaRotaryEmbedding):
|
| 105 |
+
"""PhariaRotaryEmbedding extended with Dynamic NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozilla"""
|
| 106 |
+
|
| 107 |
+
def forward(self, x, position_ids):
|
| 108 |
+
# difference to the original RoPE: inv_freq is recomputed when the sequence length > original length
|
| 109 |
+
seq_len = torch.max(position_ids) + 1
|
| 110 |
+
if seq_len > self.max_position_embeddings:
|
| 111 |
+
base = self.base * (
|
| 112 |
+
(self.scaling_factor * seq_len / self.max_position_embeddings)
|
| 113 |
+
- (self.scaling_factor - 1)
|
| 114 |
+
) ** (self.dim / (self.dim - 2))
|
| 115 |
+
inv_freq = 1.0 / (
|
| 116 |
+
base
|
| 117 |
+
** (
|
| 118 |
+
torch.arange(0, self.dim, 2, dtype=torch.int64).float().to(x.device)
|
| 119 |
+
/ self.dim
|
| 120 |
+
)
|
| 121 |
+
)
|
| 122 |
+
self.register_buffer(
|
| 123 |
+
"inv_freq", inv_freq, persistent=False
|
| 124 |
+
) # TODO joao: this may break with compilation
|
| 125 |
+
|
| 126 |
+
cos, sin = super().forward(x, position_ids)
|
| 127 |
+
return cos, sin
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
def rotate_half(x):
|
| 131 |
+
"""Rotates half the hidden dims of the input (interleaved)."""
|
| 132 |
+
y = torch.empty_like(x)
|
| 133 |
+
y[..., ::2] = -x[..., 1::2]
|
| 134 |
+
y[..., 1::2] = x[..., ::2]
|
| 135 |
+
return y
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
|
| 139 |
+
"""Applies Rotary Position Embedding to the query and key tensors.
|
| 140 |
+
|
| 141 |
+
Args:
|
| 142 |
+
q (`torch.Tensor`): The query tensor.
|
| 143 |
+
k (`torch.Tensor`): The key tensor.
|
| 144 |
+
cos (`torch.Tensor`): The cosine part of the rotary embedding.
|
| 145 |
+
sin (`torch.Tensor`): The sine part of the rotary embedding.
|
| 146 |
+
position_ids (`torch.Tensor`, *optional*):
|
| 147 |
+
Deprecated and unused.
|
| 148 |
+
unsqueeze_dim (`int`, *optional*, defaults to 1):
|
| 149 |
+
The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
|
| 150 |
+
sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
|
| 151 |
+
that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
|
| 152 |
+
k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
|
| 153 |
+
cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
|
| 154 |
+
the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
|
| 155 |
+
Returns:
|
| 156 |
+
`tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
|
| 157 |
+
"""
|
| 158 |
+
cos = cos.unsqueeze(unsqueeze_dim)
|
| 159 |
+
sin = sin.unsqueeze(unsqueeze_dim)
|
| 160 |
+
q_embed = (q * cos) + (rotate_half(q) * sin)
|
| 161 |
+
k_embed = (k * cos) + (rotate_half(k) * sin)
|
| 162 |
+
|
| 163 |
+
return q_embed, k_embed
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
|
| 167 |
+
"""
|
| 168 |
+
This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
|
| 169 |
+
num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
|
| 170 |
+
"""
|
| 171 |
+
batch, num_key_value_heads, slen, head_dim = hidden_states.shape
|
| 172 |
+
if n_rep == 1:
|
| 173 |
+
return hidden_states
|
| 174 |
+
hidden_states = hidden_states[:, :, None, :, :].expand(
|
| 175 |
+
batch, num_key_value_heads, n_rep, slen, head_dim
|
| 176 |
+
)
|
| 177 |
+
return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
class LlamaAttention(nn.Module):
|
| 181 |
+
"""Multi-headed attention from 'Attention Is All You Need' paper"""
|
| 182 |
+
|
| 183 |
+
def __init__(self, config: PhariaConfig, layer_idx: Optional[int] = None):
|
| 184 |
+
super().__init__()
|
| 185 |
+
self.config = config
|
| 186 |
+
self.layer_idx = layer_idx
|
| 187 |
+
# if layer_idx is None:
|
| 188 |
+
# logger.warning_once(
|
| 189 |
+
# f"Instantiating {self.__class__.__name__} without passing a `layer_idx` is not recommended and will "
|
| 190 |
+
# "lead to errors during the forward call if caching is used. Please make sure to provide a `layer_idx` "
|
| 191 |
+
# "when creating this class."
|
| 192 |
+
# )
|
| 193 |
+
|
| 194 |
+
self.attention_dropout = config.attention_dropout
|
| 195 |
+
self.hidden_size = config.hidden_size
|
| 196 |
+
self.num_heads = config.num_attention_heads
|
| 197 |
+
self.head_dim = self.hidden_size // self.num_heads
|
| 198 |
+
self.num_key_value_heads = config.num_key_value_heads
|
| 199 |
+
self.num_key_value_groups = self.num_heads // self.num_key_value_heads
|
| 200 |
+
self.max_position_embeddings = config.max_position_embeddings
|
| 201 |
+
self.rope_theta = config.rope_theta
|
| 202 |
+
self.is_causal = True
|
| 203 |
+
|
| 204 |
+
if (self.head_dim * self.num_heads) != self.hidden_size:
|
| 205 |
+
raise ValueError(
|
| 206 |
+
f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
|
| 207 |
+
f" and `num_heads`: {self.num_heads})."
|
| 208 |
+
)
|
| 209 |
+
|
| 210 |
+
self.q_proj = nn.Linear(
|
| 211 |
+
self.hidden_size, self.num_heads * self.head_dim, bias=config.attention_bias
|
| 212 |
+
)
|
| 213 |
+
self.k_proj = nn.Linear(
|
| 214 |
+
self.hidden_size,
|
| 215 |
+
self.num_key_value_heads * self.head_dim,
|
| 216 |
+
bias=config.attention_bias,
|
| 217 |
+
)
|
| 218 |
+
self.v_proj = nn.Linear(
|
| 219 |
+
self.hidden_size,
|
| 220 |
+
self.num_key_value_heads * self.head_dim,
|
| 221 |
+
bias=config.attention_bias,
|
| 222 |
+
)
|
| 223 |
+
self.o_proj = nn.Linear(
|
| 224 |
+
self.hidden_size, self.hidden_size, bias=config.attention_bias
|
| 225 |
+
)
|
| 226 |
+
self._init_rope()
|
| 227 |
+
|
| 228 |
+
def _init_rope(self):
|
| 229 |
+
if self.config.rope_scaling is None:
|
| 230 |
+
self.rotary_emb = PhariaRotaryEmbedding(
|
| 231 |
+
self.head_dim,
|
| 232 |
+
max_position_embeddings=self.max_position_embeddings,
|
| 233 |
+
base=self.rope_theta,
|
| 234 |
+
)
|
| 235 |
+
else:
|
| 236 |
+
scaling_type = self.config.rope_scaling["type"]
|
| 237 |
+
scaling_factor = self.config.rope_scaling["factor"]
|
| 238 |
+
if scaling_type == "linear":
|
| 239 |
+
self.rotary_emb = PhariaLinearScalingRotaryEmbedding(
|
| 240 |
+
self.head_dim,
|
| 241 |
+
max_position_embeddings=self.max_position_embeddings,
|
| 242 |
+
scaling_factor=scaling_factor,
|
| 243 |
+
base=self.rope_theta,
|
| 244 |
+
)
|
| 245 |
+
elif scaling_type == "dynamic":
|
| 246 |
+
self.rotary_emb = PhariaDynamicNTKScalingRotaryEmbedding(
|
| 247 |
+
self.head_dim,
|
| 248 |
+
max_position_embeddings=self.max_position_embeddings,
|
| 249 |
+
scaling_factor=scaling_factor,
|
| 250 |
+
base=self.rope_theta,
|
| 251 |
+
)
|
| 252 |
+
else:
|
| 253 |
+
raise ValueError(f"Unknown RoPE scaling type {scaling_type}")
|
| 254 |
+
|
| 255 |
+
def forward(
|
| 256 |
+
self,
|
| 257 |
+
hidden_states: torch.Tensor,
|
| 258 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 259 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 260 |
+
past_key_value: Optional[Cache] = None,
|
| 261 |
+
output_attentions: bool = False,
|
| 262 |
+
use_cache: bool = False,
|
| 263 |
+
cache_position: Optional[torch.LongTensor] = None,
|
| 264 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
| 265 |
+
bsz, q_len, _ = hidden_states.size()
|
| 266 |
+
|
| 267 |
+
query_states = self.q_proj(hidden_states)
|
| 268 |
+
key_states = self.k_proj(hidden_states)
|
| 269 |
+
value_states = self.v_proj(hidden_states)
|
| 270 |
+
|
| 271 |
+
query_states = query_states.view(
|
| 272 |
+
bsz, q_len, self.num_heads, self.head_dim
|
| 273 |
+
).transpose(1, 2)
|
| 274 |
+
key_states = key_states.view(
|
| 275 |
+
bsz, q_len, self.num_key_value_heads, self.head_dim
|
| 276 |
+
).transpose(1, 2)
|
| 277 |
+
value_states = value_states.view(
|
| 278 |
+
bsz, q_len, self.num_key_value_heads, self.head_dim
|
| 279 |
+
).transpose(1, 2)
|
| 280 |
+
|
| 281 |
+
cos, sin = self.rotary_emb(value_states, position_ids)
|
| 282 |
+
query_states, key_states = apply_rotary_pos_emb(
|
| 283 |
+
query_states, key_states, cos, sin
|
| 284 |
+
)
|
| 285 |
+
|
| 286 |
+
if past_key_value is not None:
|
| 287 |
+
# cache_position needed for the static cache
|
| 288 |
+
cache_kwargs = {"cache_position": cache_position}
|
| 289 |
+
key_states, value_states = past_key_value.update(
|
| 290 |
+
key_states, value_states, self.layer_idx, cache_kwargs
|
| 291 |
+
)
|
| 292 |
+
|
| 293 |
+
key_states = repeat_kv(key_states, self.num_key_value_groups)
|
| 294 |
+
value_states = repeat_kv(value_states, self.num_key_value_groups)
|
| 295 |
+
|
| 296 |
+
attn_weights = torch.matmul(
|
| 297 |
+
query_states, key_states.transpose(2, 3)
|
| 298 |
+
) / math.sqrt(self.head_dim)
|
| 299 |
+
|
| 300 |
+
if attention_mask is not None: # no matter the length, we just slice it
|
| 301 |
+
causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
|
| 302 |
+
attn_weights = attn_weights + causal_mask
|
| 303 |
+
|
| 304 |
+
# upcast attention to fp32
|
| 305 |
+
attn_weights = nn.functional.softmax(
|
| 306 |
+
attn_weights, dim=-1, dtype=torch.float32
|
| 307 |
+
).to(query_states.dtype)
|
| 308 |
+
attn_weights = nn.functional.dropout(
|
| 309 |
+
attn_weights, p=self.attention_dropout, training=self.training
|
| 310 |
+
)
|
| 311 |
+
attn_output = torch.matmul(attn_weights, value_states)
|
| 312 |
+
|
| 313 |
+
if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
|
| 314 |
+
raise ValueError(
|
| 315 |
+
f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
|
| 316 |
+
f" {attn_output.size()}"
|
| 317 |
+
)
|
| 318 |
+
|
| 319 |
+
attn_output: Optional[torch.Tensor] = attn_output.transpose(1, 2).contiguous()
|
| 320 |
+
|
| 321 |
+
attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
|
| 322 |
+
|
| 323 |
+
attn_output = self.o_proj(attn_output)
|
| 324 |
+
|
| 325 |
+
if not output_attentions:
|
| 326 |
+
attn_weights = None
|
| 327 |
+
|
| 328 |
+
return attn_output, attn_weights, past_key_value
|
| 329 |
+
|
| 330 |
+
|
| 331 |
+
class PhariaMLP(nn.Module):
|
| 332 |
+
def __init__(self, config, layer_idx: int):
|
| 333 |
+
super().__init__()
|
| 334 |
+
self.layer_idx = layer_idx
|
| 335 |
+
self.config = config
|
| 336 |
+
self.hidden_size = config.hidden_size
|
| 337 |
+
self.intermediate_size = config.intermediate_size
|
| 338 |
+
self.up_proj = nn.Linear(
|
| 339 |
+
self.hidden_size, self.intermediate_size, bias=config.mlp_bias
|
| 340 |
+
)
|
| 341 |
+
self.down_proj = nn.Linear(
|
| 342 |
+
self.intermediate_size, self.hidden_size, bias=config.mlp_bias
|
| 343 |
+
)
|
| 344 |
+
self.act_fn = ACT2FN[config.hidden_act]
|
| 345 |
+
|
| 346 |
+
def forward(self, x):
|
| 347 |
+
o = self.down_proj(self.act_fn(self.up_proj(x)))
|
| 348 |
+
return o
|
| 349 |
+
|
| 350 |
+
|
| 351 |
+
class PhariaDecoderLayer(nn.Module):
|
| 352 |
+
def __init__(self, config: PhariaConfig, layer_idx: int):
|
| 353 |
+
super().__init__()
|
| 354 |
+
self.hidden_size = config.hidden_size
|
| 355 |
+
self.self_attn = LlamaAttention(config=config, layer_idx=layer_idx)
|
| 356 |
+
self.mlp = PhariaMLP(config, layer_idx=layer_idx)
|
| 357 |
+
self.input_layernorm = nn.LayerNorm(config.hidden_size)
|
| 358 |
+
self.post_attention_layernorm = nn.LayerNorm(config.hidden_size)
|
| 359 |
+
self.layer_idx = layer_idx
|
| 360 |
+
|
| 361 |
+
def forward(
|
| 362 |
+
self,
|
| 363 |
+
hidden_states: torch.Tensor,
|
| 364 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 365 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 366 |
+
past_key_value: Optional[Cache] = None,
|
| 367 |
+
output_attentions: Optional[bool] = False,
|
| 368 |
+
use_cache: Optional[bool] = False,
|
| 369 |
+
cache_position: Optional[torch.LongTensor] = None,
|
| 370 |
+
) -> Tuple[
|
| 371 |
+
torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]
|
| 372 |
+
]:
|
| 373 |
+
residual = hidden_states
|
| 374 |
+
|
| 375 |
+
hidden_states = self.input_layernorm(hidden_states)
|
| 376 |
+
|
| 377 |
+
hidden_states, self_attn_weights, present_key_value = self.self_attn(
|
| 378 |
+
hidden_states=hidden_states,
|
| 379 |
+
attention_mask=attention_mask,
|
| 380 |
+
position_ids=position_ids,
|
| 381 |
+
past_key_value=past_key_value,
|
| 382 |
+
output_attentions=output_attentions,
|
| 383 |
+
use_cache=use_cache,
|
| 384 |
+
cache_position=cache_position,
|
| 385 |
+
)
|
| 386 |
+
hidden_states = residual + hidden_states
|
| 387 |
+
|
| 388 |
+
residual = hidden_states
|
| 389 |
+
hidden_states = self.post_attention_layernorm(hidden_states)
|
| 390 |
+
|
| 391 |
+
if self.layer_idx == -1:
|
| 392 |
+
print("Layer 0 huggingface")
|
| 393 |
+
print(hidden_states)
|
| 394 |
+
print(hidden_states.shape)
|
| 395 |
+
|
| 396 |
+
hidden_states = self.mlp(hidden_states)
|
| 397 |
+
hidden_states = residual + hidden_states
|
| 398 |
+
|
| 399 |
+
outputs = (hidden_states,)
|
| 400 |
+
|
| 401 |
+
if output_attentions:
|
| 402 |
+
outputs += (self_attn_weights,)
|
| 403 |
+
|
| 404 |
+
if use_cache:
|
| 405 |
+
outputs += (present_key_value,)
|
| 406 |
+
|
| 407 |
+
return outputs
|
| 408 |
+
|
| 409 |
+
|
| 410 |
+
class PhariaPreTrainedModel(nn.Module):
|
| 411 |
+
config_class = PhariaConfig
|
| 412 |
+
base_model_prefix = "model"
|
| 413 |
+
supports_gradient_checkpointing = True
|
| 414 |
+
_no_split_modules = ["PhariaDecoderLayer"]
|
| 415 |
+
_skip_keys_device_placement = ["past_key_values"]
|
| 416 |
+
_supports_flash_attn_2 = False
|
| 417 |
+
_supports_sdpa = False
|
| 418 |
+
_supports_cache_class = True
|
| 419 |
+
_supports_static_cache = True
|
| 420 |
+
|
| 421 |
+
def _init_weights(self, module):
|
| 422 |
+
std = self.config.initializer_range
|
| 423 |
+
if isinstance(module, nn.Linear):
|
| 424 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
| 425 |
+
if module.bias is not None:
|
| 426 |
+
module.bias.data.zero_()
|
| 427 |
+
elif isinstance(module, nn.Embedding):
|
| 428 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
| 429 |
+
if module.padding_idx is not None:
|
| 430 |
+
module.weight.data[module.padding_idx].zero_()
|
| 431 |
+
|
| 432 |
+
|
| 433 |
+
class PhariaModel(nn.Module):
|
| 434 |
+
config_class = PhariaConfig
|
| 435 |
+
|
| 436 |
+
def __init__(self, config: PhariaConfig):
|
| 437 |
+
#super().__init__(config)
|
| 438 |
+
super(PhariaModel, self).__init__()
|
| 439 |
+
self.config = config
|
| 440 |
+
self.padding_idx = config.pad_token_id
|
| 441 |
+
self.vocab_size = config.vocab_size
|
| 442 |
+
|
| 443 |
+
print(config.vocab_size, config.hidden_size, self.padding_idx)
|
| 444 |
+
|
| 445 |
+
self.embed_tokens = nn.Embedding(
|
| 446 |
+
config.vocab_size, config.hidden_size, self.padding_idx
|
| 447 |
+
)
|
| 448 |
+
|
| 449 |
+
self.layers = nn.ModuleList(
|
| 450 |
+
[
|
| 451 |
+
PhariaDecoderLayer(config, layer_idx)
|
| 452 |
+
for layer_idx in range(config.num_hidden_layers)
|
| 453 |
+
]
|
| 454 |
+
)
|
| 455 |
+
self.norm = nn.LayerNorm(config.hidden_size)
|
| 456 |
+
self.head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
| 457 |
+
|
| 458 |
+
def forward(
|
| 459 |
+
self,
|
| 460 |
+
input_ids: torch.LongTensor = None,
|
| 461 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 462 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 463 |
+
past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
|
| 464 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 465 |
+
use_cache: Optional[bool] = None,
|
| 466 |
+
output_attentions: Optional[bool] = False,
|
| 467 |
+
output_hidden_states: Optional[bool] = False,
|
| 468 |
+
return_dict: Optional[bool] = False,
|
| 469 |
+
cache_position: Optional[torch.LongTensor] = None,
|
| 470 |
+
) -> Union[Tuple, BaseModelOutputWithPast]:
|
| 471 |
+
output_attentions = (
|
| 472 |
+
output_attentions
|
| 473 |
+
if output_attentions is not None
|
| 474 |
+
else self.config.output_attentions
|
| 475 |
+
)
|
| 476 |
+
output_hidden_states = (
|
| 477 |
+
output_hidden_states
|
| 478 |
+
if output_hidden_states is not None
|
| 479 |
+
else self.config.output_hidden_states
|
| 480 |
+
)
|
| 481 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
| 482 |
+
return_dict = (
|
| 483 |
+
return_dict if return_dict is not None else self.config.use_return_dict
|
| 484 |
+
)
|
| 485 |
+
|
| 486 |
+
if (input_ids is None) ^ (inputs_embeds is not None):
|
| 487 |
+
raise ValueError(
|
| 488 |
+
"You cannot specify both input_ids and inputs_embeds at the same time, and must specify either one"
|
| 489 |
+
)
|
| 490 |
+
|
| 491 |
+
# if self.gradient_checkpointing and self.training and use_cache:
|
| 492 |
+
# # logger.warning_once(
|
| 493 |
+
# # "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`."
|
| 494 |
+
# # )
|
| 495 |
+
# use_cache = False
|
| 496 |
+
|
| 497 |
+
if inputs_embeds is None:
|
| 498 |
+
inputs_embeds = self.embed_tokens(input_ids)
|
| 499 |
+
|
| 500 |
+
return_legacy_cache = False
|
| 501 |
+
if use_cache and not isinstance(
|
| 502 |
+
past_key_values, Cache
|
| 503 |
+
): # kept for BC (non `Cache` `past_key_values` inputs)
|
| 504 |
+
return_legacy_cache = True
|
| 505 |
+
past_key_values = DynamicCache.from_legacy_cache(past_key_values)
|
| 506 |
+
|
| 507 |
+
if cache_position is None:
|
| 508 |
+
past_seen_tokens = (
|
| 509 |
+
past_key_values.get_seq_length() if past_key_values is not None else 0
|
| 510 |
+
)
|
| 511 |
+
cache_position = torch.arange(
|
| 512 |
+
past_seen_tokens,
|
| 513 |
+
past_seen_tokens + inputs_embeds.shape[1],
|
| 514 |
+
device=inputs_embeds.device,
|
| 515 |
+
)
|
| 516 |
+
if position_ids is None:
|
| 517 |
+
position_ids = cache_position.unsqueeze(0)
|
| 518 |
+
|
| 519 |
+
causal_mask = self._update_causal_mask(
|
| 520 |
+
attention_mask,
|
| 521 |
+
inputs_embeds,
|
| 522 |
+
cache_position,
|
| 523 |
+
past_key_values,
|
| 524 |
+
output_attentions,
|
| 525 |
+
)
|
| 526 |
+
|
| 527 |
+
# embed positions
|
| 528 |
+
hidden_states = inputs_embeds
|
| 529 |
+
|
| 530 |
+
# decoder layers
|
| 531 |
+
all_hidden_states = () if output_hidden_states else None
|
| 532 |
+
all_self_attns = () if output_attentions else None
|
| 533 |
+
next_decoder_cache = None
|
| 534 |
+
|
| 535 |
+
for decoder_layer in self.layers:
|
| 536 |
+
if output_hidden_states:
|
| 537 |
+
all_hidden_states += (hidden_states,)
|
| 538 |
+
|
| 539 |
+
# if self.gradient_checkpointing and self.training:
|
| 540 |
+
# layer_outputs = self._gradient_checkpointing_func(
|
| 541 |
+
# decoder_layer.__call__,
|
| 542 |
+
# hidden_states,
|
| 543 |
+
# causal_mask,
|
| 544 |
+
# position_ids,
|
| 545 |
+
# past_key_values,
|
| 546 |
+
# output_attentions,
|
| 547 |
+
# use_cache,
|
| 548 |
+
# cache_position,
|
| 549 |
+
# )
|
| 550 |
+
# else:
|
| 551 |
+
layer_outputs = decoder_layer(
|
| 552 |
+
hidden_states,
|
| 553 |
+
attention_mask=causal_mask,
|
| 554 |
+
position_ids=position_ids,
|
| 555 |
+
past_key_value=past_key_values,
|
| 556 |
+
output_attentions=output_attentions,
|
| 557 |
+
use_cache=use_cache,
|
| 558 |
+
cache_position=cache_position,
|
| 559 |
+
)
|
| 560 |
+
|
| 561 |
+
hidden_states = layer_outputs[0]
|
| 562 |
+
|
| 563 |
+
if use_cache:
|
| 564 |
+
next_decoder_cache = layer_outputs[2 if output_attentions else 1]
|
| 565 |
+
|
| 566 |
+
if output_attentions:
|
| 567 |
+
all_self_attns += (layer_outputs[1],)
|
| 568 |
+
|
| 569 |
+
hidden_states = self.norm(hidden_states)
|
| 570 |
+
|
| 571 |
+
# add hidden states from the last decoder layer
|
| 572 |
+
if output_hidden_states:
|
| 573 |
+
all_hidden_states += (hidden_states,)
|
| 574 |
+
|
| 575 |
+
next_cache = next_decoder_cache if use_cache else None
|
| 576 |
+
if return_legacy_cache:
|
| 577 |
+
next_cache = next_cache.to_legacy_cache()
|
| 578 |
+
|
| 579 |
+
hidden_states = self.head(hidden_states)
|
| 580 |
+
return hidden_states
|
| 581 |
+
|
| 582 |
+
if not return_dict:
|
| 583 |
+
return tuple(
|
| 584 |
+
v
|
| 585 |
+
for v in [hidden_states, next_cache, all_hidden_states, all_self_attns]
|
| 586 |
+
if v is not None
|
| 587 |
+
)
|
| 588 |
+
#return BaseModelOutputWithPast(
|
| 589 |
+
# last_hidden_state=hidden_states,
|
| 590 |
+
# past_key_values=next_cache,
|
| 591 |
+
# hidden_states=all_hidden_states,
|
| 592 |
+
# attentions=all_self_attns,
|
| 593 |
+
#)
|
| 594 |
+
|
| 595 |
+
def _update_causal_mask(
|
| 596 |
+
self,
|
| 597 |
+
attention_mask: torch.Tensor,
|
| 598 |
+
input_tensor: torch.Tensor,
|
| 599 |
+
cache_position: torch.Tensor,
|
| 600 |
+
past_key_values: Cache,
|
| 601 |
+
output_attentions: bool,
|
| 602 |
+
):
|
| 603 |
+
# TODO: As of torch==2.2.0, the `attention_mask` passed to the model in `generate` is 2D and of dynamic length even when the static
|
| 604 |
+
# KV cache is used. This is an issue for torch.compile which then recaptures cudagraphs at each decode steps due to the dynamic shapes.
|
| 605 |
+
# (`recording cudagraph tree for symint key 13`, etc.), which is VERY slow. A workaround is `@torch.compiler.disable`, but this prevents using
|
| 606 |
+
# `fullgraph=True`. See more context in https://github.com/huggingface/transformers/pull/29114
|
| 607 |
+
|
| 608 |
+
# Removed by Tristan.
|
| 609 |
+
#if self.config._attn_implementation == "flash_attention_2":
|
| 610 |
+
# if attention_mask is not None and 0.0 in attention_mask:
|
| 611 |
+
# return attention_mask
|
| 612 |
+
# return None
|
| 613 |
+
|
| 614 |
+
# For SDPA, when possible, we will rely on its `is_causal` argument instead of its `attn_mask` argument, in
|
| 615 |
+
# order to dispatch on Flash Attention 2. This feature is not compatible with static cache, as SDPA will fail
|
| 616 |
+
# to infer the attention mask.
|
| 617 |
+
past_seen_tokens = (
|
| 618 |
+
past_key_values.get_seq_length() if past_key_values is not None else 0
|
| 619 |
+
)
|
| 620 |
+
using_static_cache = isinstance(past_key_values, StaticCache)
|
| 621 |
+
|
| 622 |
+
# When output attentions is True, sdpa implementation's forward method calls the eager implementation's forward
|
| 623 |
+
#if (
|
| 624 |
+
# self.config._attn_implementation == "sdpa"
|
| 625 |
+
# and not using_static_cache
|
| 626 |
+
# and not output_attentions
|
| 627 |
+
#):
|
| 628 |
+
# if AttentionMaskConverter._ignore_causal_mask_sdpa(
|
| 629 |
+
# attention_mask,
|
| 630 |
+
# inputs_embeds=input_tensor,
|
| 631 |
+
# past_key_values_length=past_seen_tokens,
|
| 632 |
+
# is_training=self.training,
|
| 633 |
+
# ):
|
| 634 |
+
# return None
|
| 635 |
+
|
| 636 |
+
dtype, device = input_tensor.dtype, input_tensor.device
|
| 637 |
+
min_dtype = torch.finfo(dtype).min
|
| 638 |
+
sequence_length = input_tensor.shape[1]
|
| 639 |
+
if using_static_cache:
|
| 640 |
+
target_length = past_key_values.get_max_length()
|
| 641 |
+
else:
|
| 642 |
+
target_length = (
|
| 643 |
+
attention_mask.shape[-1]
|
| 644 |
+
if isinstance(attention_mask, torch.Tensor)
|
| 645 |
+
else past_seen_tokens + sequence_length + 1
|
| 646 |
+
)
|
| 647 |
+
|
| 648 |
+
if attention_mask is not None and attention_mask.dim() == 4:
|
| 649 |
+
# in this case we assume that the mask comes already in inverted form and requires no inversion or slicing
|
| 650 |
+
if attention_mask.max() != 0:
|
| 651 |
+
raise ValueError(
|
| 652 |
+
"Custom 4D attention mask should be passed in inverted form with max==0`"
|
| 653 |
+
)
|
| 654 |
+
causal_mask = attention_mask
|
| 655 |
+
else:
|
| 656 |
+
causal_mask = torch.full(
|
| 657 |
+
(sequence_length, target_length),
|
| 658 |
+
fill_value=min_dtype,
|
| 659 |
+
dtype=dtype,
|
| 660 |
+
device=device,
|
| 661 |
+
)
|
| 662 |
+
if sequence_length != 1:
|
| 663 |
+
causal_mask = torch.triu(causal_mask, diagonal=1)
|
| 664 |
+
causal_mask *= torch.arange(
|
| 665 |
+
target_length, device=device
|
| 666 |
+
) > cache_position.reshape(-1, 1)
|
| 667 |
+
causal_mask = causal_mask[None, None, :, :].expand(
|
| 668 |
+
input_tensor.shape[0], 1, -1, -1
|
| 669 |
+
)
|
| 670 |
+
if attention_mask is not None:
|
| 671 |
+
causal_mask = (
|
| 672 |
+
causal_mask.clone()
|
| 673 |
+
) # copy to contiguous memory for in-place edit
|
| 674 |
+
mask_length = attention_mask.shape[-1]
|
| 675 |
+
padding_mask = (
|
| 676 |
+
causal_mask[:, :, :, :mask_length]
|
| 677 |
+
+ attention_mask[:, None, None, :]
|
| 678 |
+
)
|
| 679 |
+
padding_mask = padding_mask == 0
|
| 680 |
+
causal_mask[:, :, :, :mask_length] = causal_mask[
|
| 681 |
+
:, :, :, :mask_length
|
| 682 |
+
].masked_fill(padding_mask, min_dtype)
|
| 683 |
+
#if (
|
| 684 |
+
# self.config._attn_implementation == "sdpa"
|
| 685 |
+
# and attention_mask is not None
|
| 686 |
+
# and attention_mask.device.type == "cuda"
|
| 687 |
+
# and not output_attentions
|
| 688 |
+
#):
|
| 689 |
+
# Attend to all tokens in fully masked rows in the causal_mask, for example the relevant first rows when
|
| 690 |
+
# using left padding. This is required by F.scaled_dot_product_attention memory-efficient attention path.
|
| 691 |
+
# Details: https://github.com/pytorch/pytorch/issues/110213
|
| 692 |
+
# causal_mask = AttentionMaskConverter._unmask_unattended(
|
| 693 |
+
# causal_mask, min_dtype
|
| 694 |
+
# )
|
| 695 |
+
|
| 696 |
+
return causal_mask
|