feat(CRITICAL): 从 GitHub 扫描搬运 ixformer SDK + xllm 完整 GDN/MoE 代码
来源:
1. Chranos/ixformer (GitHub) → ixformer_sdk/ (230 files, 70K lines)
- inference/functions/vllm.py: vllm_moe_topk_softmax 完整实现 (2033 lines)
- inference/functions/moe.py: MoE ops 完整实现 (1380 lines)
- contrib/vllm_flash_attn/: FA2 Python 接口 (1018 lines)
- contrib/tgi/fused_moe.py: TGI fused MoE (429 lines)
- csrc/include/ixformer/: C++ kernel headers + cmake
2. Deep-Spark/xllm (GitHub) → upstream_ref/xllm_latest/ (+15 files)
- npu_torch/qwen3_5_decoder_layer_impl.cpp/.h
- npu_torch/qwen3_5_gated_delta_net.cpp/.h
- npu_torch/qwen3_next_*.cpp/.h (6 files)
- npu_torch/attention.cpp/.h + fused_moe.cpp/.h + CMakeLists.txt
- models/llm/qwen3_5.h + qwen3_5_mtp.h + qwen3_next.h
- models/vlm/qwen3_5.h
调用链完整性:
ixformer_sdk/inference/functions/vllm.py
→ ops.infer.moe_topk_softmax() (C++ 层)
→ 这就是 base 镜像 libixformer.so 里的实现
upstream_ref/xllm_latest/core/layers/ilu/fused_moe.cpp
→ ixformer::infer::topk_softmax() (直接 C++ 调用)
→ ixformer::infer::group_gemm() → 完整 7-step MoE pipeline
This commit is contained in:
1
ixformer_sdk/train/speedformer/__init__.py
Normal file
1
ixformer_sdk/train/speedformer/__init__.py
Normal file
@@ -0,0 +1 @@
|
||||
from .speedformer import SpeedFormer
|
||||
0
ixformer_sdk/train/speedformer/layers/__init__.py
Normal file
0
ixformer_sdk/train/speedformer/layers/__init__.py
Normal file
162
ixformer_sdk/train/speedformer/layers/baichuan/attention.py
Normal file
162
ixformer_sdk/train/speedformer/layers/baichuan/attention.py
Normal file
@@ -0,0 +1,162 @@
|
||||
import math
|
||||
import warnings
|
||||
from typing import List, Optional, Tuple, Union
|
||||
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
import torch.nn.functional as F
|
||||
|
||||
from flash_attn import flash_attn_func, flash_attn_varlen_func
|
||||
from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input
|
||||
from ixformer.train.speedformer.models.baichuan.configuration_baichuan import BaichuanConfig
|
||||
from ixformer.train.speedformer.models.baichuan.modeling_baichuan import Attention
|
||||
|
||||
from ixformer.train.functions.fused_rope import fused_apply_rotary_pos_emb
|
||||
from ixformer.train.speedformer.layers.rotary_pos_embedding import RotaryEmbedding
|
||||
|
||||
from ixformer.train.speedformer.layers.lazy import LazyInitContext
|
||||
|
||||
|
||||
class FlashAttention(Attention):
|
||||
# 这个类主要的改进包含:1. apply_rotary_pos_emb;2. flash-attn 代替 native attention
|
||||
def __init__(self, config: BaichuanConfig):
|
||||
super().__init__(config)
|
||||
self.rotary_emb = RotaryEmbedding(self.head_dim)
|
||||
|
||||
|
||||
def forward(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
attention_mask: Optional[torch.Tensor] = None,
|
||||
position_ids: Optional[torch.LongTensor] = None,
|
||||
past_key_value: Optional[Tuple[torch.Tensor]] = None,
|
||||
output_attentions: bool = False,
|
||||
use_cache: bool = False,
|
||||
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
||||
bsz, q_len, _ = hidden_states.size()
|
||||
|
||||
proj = self.W_pack(hidden_states)
|
||||
proj = proj.unflatten(-1, (3, self.hidden_size)).unsqueeze(0).transpose(0, -2).squeeze(-2)
|
||||
|
||||
# fused_apply_rotary_pos_emb need qk to be in "sbhd", v stay in "bshd"
|
||||
query_states = proj[0].view(bsz, q_len, self.num_heads, self.head_dim).transpose(0, 1).contiguous()
|
||||
key_states = proj[1].view(bsz, q_len, self.num_heads, self.head_dim).transpose(0, 1).contiguous()
|
||||
value_states = proj[2].view(bsz, q_len, self.num_heads, self.head_dim)
|
||||
|
||||
kv_seq_len = key_states.shape[0]
|
||||
if past_key_value is not None:
|
||||
kv_seq_len += past_key_value[0].shape[0]
|
||||
|
||||
# fused_apply_rotary_pos_emb need emb in float32
|
||||
emb = self.rotary_emb(kv_seq_len).to(dtype=torch.float32)
|
||||
query_states = fused_apply_rotary_pos_emb(query_states, emb)
|
||||
key_states = fused_apply_rotary_pos_emb(key_states, emb)
|
||||
|
||||
if past_key_value is not None:
|
||||
# reuse k, v, self_attention
|
||||
key_states = torch.cat([past_key_value[0], key_states], dim=0)
|
||||
value_states = torch.cat([past_key_value[1], value_states], dim=0)
|
||||
|
||||
past_key_value = (key_states, value_states) if use_cache else None
|
||||
|
||||
# after fused_apply_rotary_pos_emb, qk change to "bshd" for flashattn or "bhsd" for sdpa
|
||||
if attention_mask is None: # flash-attn
|
||||
query_states = query_states.transpose(0, 1).contiguous()
|
||||
key_states = key_states.transpose(0, 1).contiguous()
|
||||
else: # sdpa
|
||||
query_states = query_states.permute(1, 2, 0, 3).contiguous()
|
||||
key_states = key_states.permute(1, 2, 0, 3).contiguous()
|
||||
value_states = value_states.transpose(1, 2).contiguous()
|
||||
|
||||
'''
|
||||
if attention_mask is not None:
|
||||
batch_size = query_states.shape[0] # bsz, q_len, self.num_heads, self.head_dim
|
||||
query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._upad_input(
|
||||
query_states, key_states, value_states, attention_mask, q_len
|
||||
)
|
||||
|
||||
cu_seqlens_q, cu_seqlens_k = cu_seq_lens
|
||||
max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
|
||||
attn_output_unpad = flash_attn_varlen_func(
|
||||
query_states,
|
||||
key_states,
|
||||
value_states,
|
||||
cu_seqlens_q=cu_seqlens_q,
|
||||
cu_seqlens_k=cu_seqlens_k,
|
||||
max_seqlen_q=max_seqlen_in_batch_q,
|
||||
max_seqlen_k=max_seqlen_in_batch_k,
|
||||
dropout_p=0.0,
|
||||
softmax_scale=None,
|
||||
causal=True,
|
||||
)
|
||||
|
||||
attn_output = pad_input(attn_output_unpad, indices_q, batch_size, q_len)
|
||||
else:
|
||||
attn_output = flash_attn_func(
|
||||
query_states, key_states, value_states, 0.0, softmax_scale=None, causal=True
|
||||
)
|
||||
'''
|
||||
attn_output = self._flash_attention_forward(
|
||||
query_states, key_states, value_states, q_len, attention_mask, dropout=0.0
|
||||
)
|
||||
|
||||
attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
|
||||
attn_output = self.o_proj(attn_output)
|
||||
|
||||
if not output_attentions:
|
||||
attn_weights = None
|
||||
|
||||
return attn_output, attn_weights, past_key_value
|
||||
|
||||
def _flash_attention_forward(
|
||||
self,
|
||||
query_states: torch.Tensor,
|
||||
key_states: torch.Tensor,
|
||||
value_states: torch.Tensor,
|
||||
query_length: int,
|
||||
attention_mask: Optional[torch.Tensor] = None,
|
||||
dropout=0.0,
|
||||
softmax_scale=None
|
||||
):
|
||||
if attention_mask is not None:
|
||||
attn_output = torch.nn.functional.scaled_dot_product_attention(
|
||||
query_states,
|
||||
key_states,
|
||||
value_states,
|
||||
attn_mask=attention_mask,
|
||||
dropout_p=0.0,
|
||||
# The q_len > 1 is necessary to match with AttentionMaskConverter.to_causal_4d that does not create a causal mask in case q_len == 1.
|
||||
is_causal=query_length > 1,
|
||||
)
|
||||
attn_output = attn_output.transpose(1, 2).contiguous()
|
||||
|
||||
else:
|
||||
attn_output = flash_attn_func(
|
||||
query_states, key_states, value_states, dropout, softmax_scale=softmax_scale, causal=self.is_causal
|
||||
)
|
||||
|
||||
return attn_output
|
||||
|
||||
class BaichuanAttention(FlashAttention):
|
||||
def __init__(self) -> None:
|
||||
raise NotImplementedError(
|
||||
"BaichuanAttention is not implemented as a physical class. "
|
||||
"It is meant to be used only with the from_native_module interface to Convert a native BaichuanAttention module to LlamaAttention module provided above."
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def from_native_module(module: nn.Module, *args, **kwargs) -> nn.Module:
|
||||
|
||||
LazyInitContext.materialize(module)
|
||||
|
||||
# try to get normalized_shape, eps, elementwise_affine from the module
|
||||
config = getattr(module, "config")
|
||||
|
||||
attention = FlashAttention(
|
||||
config=config,
|
||||
)
|
||||
|
||||
attention.W_pack.weight = module.W_pack.weight
|
||||
attention.o_proj.weight = module.o_proj.weight
|
||||
|
||||
return attention
|
||||
141
ixformer_sdk/train/speedformer/layers/baichuan/baichuan_model.py
Normal file
141
ixformer_sdk/train/speedformer/layers/baichuan/baichuan_model.py
Normal file
@@ -0,0 +1,141 @@
|
||||
import math
|
||||
import warnings
|
||||
from typing import List, Optional, Tuple, Union
|
||||
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
import torch.nn.functional as F
|
||||
|
||||
from ixformer.train.speedformer.models.baichuan.configuration_baichuan import BaichuanConfig
|
||||
from ixformer.train.speedformer.models.baichuan.modeling_baichuan import BaichuanModel
|
||||
from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
|
||||
from transformers.utils import logging, ContextManagers
|
||||
|
||||
|
||||
from ixformer.train.speedformer.layers.lazy import LazyInitContext
|
||||
|
||||
logger = logging.get_logger(__name__)
|
||||
|
||||
|
||||
class IXFBaichuanModel(BaichuanModel):
|
||||
def forward(
|
||||
self,
|
||||
input_ids: torch.LongTensor = None,
|
||||
attention_mask: Optional[torch.Tensor] = None,
|
||||
position_ids: Optional[torch.LongTensor] = None,
|
||||
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
||||
inputs_embeds: Optional[torch.FloatTensor] = None,
|
||||
use_cache: Optional[bool] = None,
|
||||
output_attentions: Optional[bool] = None,
|
||||
output_hidden_states: Optional[bool] = None,
|
||||
return_dict: Optional[bool] = None,
|
||||
) -> Union[Tuple, BaseModelOutputWithPast]:
|
||||
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
||||
output_hidden_states = (
|
||||
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
||||
)
|
||||
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
||||
|
||||
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
||||
|
||||
# retrieve input_ids and inputs_embeds
|
||||
if input_ids is not None and inputs_embeds is not None:
|
||||
raise ValueError(
|
||||
"You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time")
|
||||
elif input_ids is not None:
|
||||
batch_size, seq_length = input_ids.shape
|
||||
elif inputs_embeds is not None:
|
||||
batch_size, seq_length, _ = inputs_embeds.shape
|
||||
else:
|
||||
raise ValueError(
|
||||
"You have to specify either decoder_input_ids or decoder_inputs_embeds")
|
||||
|
||||
seq_length_with_past = seq_length
|
||||
past_key_values_length = 0
|
||||
|
||||
if past_key_values is not None:
|
||||
past_key_values_length = past_key_values[0][0].shape[2]
|
||||
seq_length_with_past = seq_length_with_past + past_key_values_length
|
||||
|
||||
if position_ids is None:
|
||||
device = input_ids.device if input_ids is not None else inputs_embeds.device
|
||||
position_ids = torch.arange(
|
||||
past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
|
||||
)
|
||||
position_ids = position_ids.unsqueeze(0).view(-1, seq_length)
|
||||
else:
|
||||
position_ids = position_ids.view(-1, seq_length).long()
|
||||
|
||||
if inputs_embeds is None:
|
||||
inputs_embeds = self.embed_tokens(input_ids)
|
||||
|
||||
hidden_states = inputs_embeds
|
||||
|
||||
if self.gradient_checkpointing and self.training:
|
||||
if use_cache:
|
||||
logger.warning_once(
|
||||
"`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
|
||||
)
|
||||
use_cache = False
|
||||
|
||||
# decoder layers
|
||||
all_hidden_states = () if output_hidden_states else None
|
||||
all_self_attns = () if output_attentions else None
|
||||
next_decoder_cache = () if use_cache else None
|
||||
|
||||
for idx, decoder_layer in enumerate(self.layers):
|
||||
if output_hidden_states:
|
||||
all_hidden_states += (hidden_states,)
|
||||
|
||||
past_key_value = past_key_values[idx] if past_key_values is not None else None
|
||||
|
||||
if self.gradient_checkpointing and self.training:
|
||||
|
||||
def create_custom_forward(module):
|
||||
def custom_forward(*inputs):
|
||||
# None for past_key_value
|
||||
return module(*inputs, output_attentions, None)
|
||||
|
||||
return custom_forward
|
||||
|
||||
layer_outputs = torch.utils.checkpoint.checkpoint(
|
||||
create_custom_forward(decoder_layer),
|
||||
hidden_states,
|
||||
attention_mask,
|
||||
position_ids,
|
||||
None,
|
||||
)
|
||||
else:
|
||||
layer_outputs = decoder_layer(
|
||||
hidden_states,
|
||||
attention_mask=attention_mask,
|
||||
position_ids=position_ids,
|
||||
past_key_value=past_key_value,
|
||||
output_attentions=output_attentions,
|
||||
use_cache=use_cache,
|
||||
)
|
||||
|
||||
hidden_states = layer_outputs[0]
|
||||
|
||||
if use_cache:
|
||||
next_decoder_cache += (
|
||||
layer_outputs[2 if output_attentions else 1],)
|
||||
|
||||
if output_attentions:
|
||||
all_self_attns += (layer_outputs[1],)
|
||||
|
||||
hidden_states = self.norm(hidden_states)
|
||||
|
||||
# add hidden states from the last decoder layer
|
||||
if output_hidden_states:
|
||||
all_hidden_states += (hidden_states,)
|
||||
|
||||
next_cache = next_decoder_cache if use_cache else None
|
||||
if not return_dict:
|
||||
return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
|
||||
return BaseModelOutputWithPast(
|
||||
last_hidden_state=hidden_states,
|
||||
past_key_values=next_cache,
|
||||
hidden_states=all_hidden_states,
|
||||
attentions=all_self_attns,
|
||||
)
|
||||
53
ixformer_sdk/train/speedformer/layers/baichuan/mlp.py
Normal file
53
ixformer_sdk/train/speedformer/layers/baichuan/mlp.py
Normal file
@@ -0,0 +1,53 @@
|
||||
import math
|
||||
import warnings
|
||||
from typing import List, Optional, Tuple, Union
|
||||
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
|
||||
import ixformer.train.functions as F
|
||||
from ixformer.train.speedformer.models.baichuan.configuration_baichuan import BaichuanConfig
|
||||
from ixformer.train.speedformer.models.baichuan.modeling_baichuan import MLP
|
||||
from transformers.utils import logging
|
||||
|
||||
from ixformer.train.speedformer.layers.lazy import LazyInitContext
|
||||
|
||||
|
||||
class BaseMLP(MLP):
|
||||
"""
|
||||
这个层主要的优化点是:将linear1(act(cat(linear2(x), linear3(x))))的结构变成 linear1(act(linear23(x)))
|
||||
"""
|
||||
|
||||
def __init__(self, hidden_size, intermediate_size, hidden_act):
|
||||
super().__init__(hidden_size, intermediate_size, hidden_act)
|
||||
self.gate_up = nn.Linear(
|
||||
hidden_size, intermediate_size * 2, bias=False)
|
||||
del self.gate_proj, self.up_proj
|
||||
del self.act_fn
|
||||
|
||||
def forward(self, x):
|
||||
res = self.gate_up(x)
|
||||
down_proj = self.down_proj(F.swiglu(res))
|
||||
return down_proj
|
||||
|
||||
|
||||
class IXFBaichuanMLP(BaseMLP):
|
||||
def __init__(self) -> None:
|
||||
raise NotImplementedError(
|
||||
"IXFLlamaMLP is not implemented as a physical class. "
|
||||
"It is meant to be used only with the from_native_module interface to Convert a native LlamaAttention module to IXFLlamaMLP module provided above."
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def from_native_module(module: nn.Module, *args, **kwargs) -> nn.Module:
|
||||
hidden_size, intermediate_size = module.gate_proj.in_features, module.gate_proj.out_features
|
||||
hidden_act = "silu"
|
||||
|
||||
mlp = BaseMLP(hidden_size=hidden_size,
|
||||
intermediate_size=intermediate_size, hidden_act=hidden_act)
|
||||
|
||||
mlp.gate_up.weight.data = torch.concat(
|
||||
(module.gate_proj.weight.data, module.up_proj.weight.data), dim=0)
|
||||
mlp.down_proj.weight.data = module.down_proj.weight.data
|
||||
|
||||
return mlp
|
||||
160
ixformer_sdk/train/speedformer/layers/bloom/attention.py
Normal file
160
ixformer_sdk/train/speedformer/layers/bloom/attention.py
Normal file
@@ -0,0 +1,160 @@
|
||||
import math
|
||||
import warnings
|
||||
from typing import List, Optional, Tuple, Union
|
||||
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
import torch.nn.functional as F
|
||||
|
||||
from flash_attn import flash_attn_func, flash_attn_varlen_func
|
||||
from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input
|
||||
from ixformer.train.speedformer.models.bloom.modeling_bloom import BloomAttention, dropout_add
|
||||
from ixformer.train.speedformer.models.bloom.configuration_bloom import BloomConfig
|
||||
|
||||
from apex.transformer.functional.fused_rope import fused_apply_rotary_pos_emb_cached
|
||||
from apex.transformer.functional.fused_rope import FusedRoPEFunc
|
||||
|
||||
|
||||
class FlashAttention(BloomAttention):
|
||||
|
||||
def forward(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
residual: torch.Tensor,
|
||||
alibi: torch.Tensor,
|
||||
attention_mask: torch.Tensor,
|
||||
layer_past: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
|
||||
head_mask: Optional[torch.Tensor] = None,
|
||||
use_cache: bool = False,
|
||||
output_attentions: bool = False,
|
||||
):
|
||||
fused_qkv = self.query_key_value(hidden_states)
|
||||
(query_layer, key_layer, value_layer) = self._split_heads(fused_qkv) # 3 x [batch_size, seq_length, num_heads, head_dim]
|
||||
batch_size, q_length, _, _ = query_layer.shape
|
||||
|
||||
if layer_past is not None:
|
||||
past_key, past_value = layer_past
|
||||
key_layer = torch.cat((past_key, key_layer), dim=1)
|
||||
value_layer = torch.cat((past_value, value_layer), dim=1)
|
||||
|
||||
present = (key_layer, value_layer) if use_cache else None
|
||||
# if attention_mask is not None:
|
||||
if False:
|
||||
query_layer, key_layer, value_layer, indices_q, cu_seq_lens, max_seq_lens = self._upad_input(
|
||||
query_layer, key_layer, value_layer, attention_mask, q_length
|
||||
)
|
||||
|
||||
cu_seqlens_q, cu_seqlens_k = cu_seq_lens
|
||||
max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
|
||||
attn_output_unpad = flash_attn_varlen_func(
|
||||
query_layer,
|
||||
key_layer,
|
||||
value_layer,
|
||||
cu_seqlens_q=cu_seqlens_q,
|
||||
cu_seqlens_k=cu_seqlens_k,
|
||||
max_seqlen_q=max_seqlen_in_batch_q,
|
||||
max_seqlen_k=max_seqlen_in_batch_k,
|
||||
dropout_p=0.0,
|
||||
softmax_scale=None,
|
||||
causal=True,
|
||||
use_alibi=True,
|
||||
)
|
||||
attn_output = pad_input(attn_output_unpad, indices_q, batch_size, q_length)
|
||||
else:
|
||||
attn_output = flash_attn_func(
|
||||
query_layer, key_layer, value_layer, 0.0, softmax_scale=None, causal=True, use_alibi=True,
|
||||
)
|
||||
|
||||
attn_output = attn_output.reshape(batch_size, q_length, attn_output.shape[2]*attn_output.shape[3]).contiguous()
|
||||
output_tensor = self.dense(attn_output)
|
||||
|
||||
output_tensor = dropout_add(output_tensor, residual, self.hidden_dropout, self.training)
|
||||
|
||||
outputs = (output_tensor, present, None)
|
||||
|
||||
return outputs
|
||||
|
||||
|
||||
def _upad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length):
|
||||
|
||||
def _get_unpad_data(attention_mask):
|
||||
seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
|
||||
indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
|
||||
max_seqlen_in_batch = seqlens_in_batch.max().item()
|
||||
cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.torch.int32), (1, 0))
|
||||
return (
|
||||
indices,
|
||||
cu_seqlens,
|
||||
max_seqlen_in_batch,
|
||||
)
|
||||
|
||||
indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
|
||||
batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape
|
||||
|
||||
key_layer = index_first_axis(
|
||||
key_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
|
||||
)
|
||||
value_layer = index_first_axis(
|
||||
value_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
|
||||
)
|
||||
if query_length == kv_seq_len:
|
||||
query_layer = index_first_axis(
|
||||
query_layer.reshape(batch_size * kv_seq_len, self.num_heads, head_dim), indices_k
|
||||
)
|
||||
cu_seqlens_q = cu_seqlens_k
|
||||
max_seqlen_in_batch_q = max_seqlen_in_batch_k
|
||||
indices_q = indices_k
|
||||
elif query_length == 1:
|
||||
max_seqlen_in_batch_q = 1
|
||||
cu_seqlens_q = torch.arange(
|
||||
batch_size + 1, dtype=torch.int32, device=query_layer.device
|
||||
) # There is a memcpy here, that is very bad.
|
||||
indices_q = cu_seqlens_q[:-1]
|
||||
query_layer = query_layer.squeeze(1)
|
||||
else:
|
||||
# The -q_len: slice assumes left padding.
|
||||
attention_mask = attention_mask[:, -query_length:]
|
||||
query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, attention_mask)
|
||||
|
||||
return (
|
||||
query_layer,
|
||||
key_layer,
|
||||
value_layer,
|
||||
indices_q,
|
||||
(cu_seqlens_q, cu_seqlens_k),
|
||||
(max_seqlen_in_batch_q, max_seqlen_in_batch_k),
|
||||
)
|
||||
|
||||
|
||||
class BloomFlashAttention(FlashAttention):
|
||||
|
||||
def __init__(self) -> None:
|
||||
raise NotImplementedError(
|
||||
"BloomAttention is not implemented as a physical class. "
|
||||
"It is meant to be used only with the from_native_module interface to Convert a native BloomAttention module to FlashAttention module provided above."
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def from_native_module(module: nn.Module, *args, **kwargs) -> nn.Module:
|
||||
|
||||
# try to get normalized_shape, eps, elementwise_affine from the module
|
||||
new_config = BloomConfig()
|
||||
new_config.pretraining_tp = module.pretraining_tp
|
||||
new_config.slow_but_exact = module.slow_but_exact
|
||||
new_config.hidden_size = module.hidden_size
|
||||
new_config.n_head = module.num_heads
|
||||
new_config.hidden_size = module.split_size
|
||||
new_config.hidden_dropout = module.hidden_dropout
|
||||
new_config.attention_dropout = module.attention_dropout.p
|
||||
|
||||
attention = FlashAttention(
|
||||
config=new_config,
|
||||
)
|
||||
|
||||
attention.query_key_value.weight = module.query_key_value.weight
|
||||
attention.query_key_value.bias = module.query_key_value.bias
|
||||
|
||||
attention.dense.weight = module.dense.weight
|
||||
attention.dense.bias = module.dense.bias
|
||||
|
||||
return attention
|
||||
199
ixformer_sdk/train/speedformer/layers/chatglm/attention.py
Normal file
199
ixformer_sdk/train/speedformer/layers/chatglm/attention.py
Normal file
@@ -0,0 +1,199 @@
|
||||
import math
|
||||
import os
|
||||
import warnings
|
||||
from typing import List, Optional, Tuple, Union
|
||||
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
import torch.nn.functional as F
|
||||
|
||||
from ixformer.train.speedformer.models.chatglm.modeling_chatglm import (
|
||||
CoreAttention,
|
||||
SelfAttention,
|
||||
split_tensor_along_last_dim,
|
||||
apply_rotary_pos_emb
|
||||
)
|
||||
from ixformer.train.speedformer.models.chatglm.configuration_chatglm import ChatGLMConfig
|
||||
|
||||
from transformers.utils import is_flash_attn_2_available
|
||||
|
||||
if is_flash_attn_2_available():
|
||||
from flash_attn import flash_attn_func, flash_attn_varlen_func
|
||||
from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
|
||||
|
||||
|
||||
class FlashCoreAttention(CoreAttention):
|
||||
|
||||
def forward(self, query_layer, key_layer, value_layer, attention_mask):
|
||||
if int(os.environ.get("USE_FLASH_ATTN", 0)):
|
||||
query_layer, key_layer, value_layer = [
|
||||
k.permute(1, 0, 2, 3) for k in [query_layer, key_layer, value_layer]]
|
||||
batch_size, query_length, _, _ = query_layer.shape
|
||||
|
||||
if attention_mask is not None:
|
||||
batch_size = query_layer.shape[0]
|
||||
query_layer, key_layer, value_layer, indices_q, cu_seq_lens, max_seq_lens = self._upad_input(
|
||||
query_layer, key_layer, value_layer, attention_mask, query_length
|
||||
)
|
||||
|
||||
cu_seqlens_q, cu_seqlens_k = cu_seq_lens
|
||||
max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
|
||||
|
||||
attn_output_unpad = flash_attn_varlen_func(
|
||||
query_layer,
|
||||
key_layer,
|
||||
value_layer,
|
||||
cu_seqlens_q=cu_seqlens_q,
|
||||
cu_seqlens_k=cu_seqlens_k,
|
||||
max_seqlen_q=max_seqlen_in_batch_q,
|
||||
max_seqlen_k=max_seqlen_in_batch_k,
|
||||
dropout_p=0.0,
|
||||
softmax_scale=None,
|
||||
causal=True,
|
||||
)
|
||||
attn_output = pad_input(
|
||||
attn_output_unpad, indices_q, batch_size, query_length)
|
||||
context_layer = attn_output.permute(1, 0, 2, 3)
|
||||
else:
|
||||
attn_output = flash_attn_func(
|
||||
query_layer, key_layer, value_layer, 0.0, softmax_scale=None, causal=True
|
||||
)
|
||||
context_layer = attn_output.permute(1, 0, 2, 3)
|
||||
|
||||
if attention_mask is not None:
|
||||
if query_layer.shape[2] != key_layer.shape[2]:
|
||||
num_group = query_layer.shape[2] // key_layer.shape[2]
|
||||
final_shape = (*key_layer.shape[:2], *query_layer.shape[2:])
|
||||
key_layer = key_layer.unsqueeze(-2)
|
||||
key_layer = key_layer.expand(
|
||||
-1, -1, -1, num_group, -1
|
||||
)
|
||||
key_layer = key_layer.contiguous().view(
|
||||
final_shape
|
||||
)
|
||||
value_layer = value_layer.unsqueeze(-2)
|
||||
value_layer = value_layer.expand(
|
||||
-1, -1, -1, num_group, -1
|
||||
)
|
||||
value_layer = value_layer.contiguous().view(
|
||||
final_shape
|
||||
)
|
||||
|
||||
query_layer, key_layer, value_layer = [
|
||||
k.permute(1, 2, 0, 3) for k in [query_layer, key_layer, value_layer]] # bhsd
|
||||
attention_mask = ~attention_mask
|
||||
context_layer = torch.nn.functional.scaled_dot_product_attention(query_layer, key_layer, value_layer,
|
||||
attention_mask)
|
||||
context_layer = context_layer.permute(2, 0, 1, 3)
|
||||
|
||||
else:
|
||||
query_layer, key_layer, value_layer = [
|
||||
k.permute(1, 0, 2, 3) for k in [query_layer, key_layer, value_layer]] # bshd
|
||||
context_layer = flash_attn_func(
|
||||
query_layer, key_layer, value_layer, 0, softmax_scale=None, causal=True
|
||||
) # bshd
|
||||
context_layer = context_layer.permute(1, 0, 2, 3)
|
||||
|
||||
context_layer = context_layer.reshape(
|
||||
context_layer.size(0), context_layer.size(1), -1)
|
||||
|
||||
return context_layer
|
||||
|
||||
|
||||
class FlashSelfAttention(SelfAttention):
|
||||
|
||||
def __init__(self, config: ChatGLMConfig, layer_number, device=None):
|
||||
super().__init__(config, layer_number, device=device)
|
||||
self.core_attention = FlashCoreAttention(config, self.layer_number)
|
||||
|
||||
def forward(self, hidden_states, attention_mask, rotary_pos_emb, kv_cache=None, use_cache=True):
|
||||
mixed_x_layer = self.query_key_value(hidden_states)
|
||||
if self.multi_query_attention:
|
||||
(query_layer, key_layer, value_layer) = mixed_x_layer.split(
|
||||
[
|
||||
self.num_attention_heads_per_partition * self.hidden_size_per_attention_head,
|
||||
self.num_multi_query_groups_per_partition * self.hidden_size_per_attention_head,
|
||||
self.num_multi_query_groups_per_partition * self.hidden_size_per_attention_head,
|
||||
],
|
||||
dim=-1,
|
||||
)
|
||||
query_layer = query_layer.view(
|
||||
query_layer.size()[
|
||||
:-1] + (self.num_attention_heads_per_partition, self.hidden_size_per_attention_head)
|
||||
)
|
||||
key_layer = key_layer.view(
|
||||
key_layer.size()[
|
||||
:-1] + (self.num_multi_query_groups_per_partition, self.hidden_size_per_attention_head)
|
||||
)
|
||||
value_layer = value_layer.view(
|
||||
value_layer.size()[:-1]
|
||||
+ (self.num_multi_query_groups_per_partition,
|
||||
self.hidden_size_per_attention_head)
|
||||
)
|
||||
else:
|
||||
new_tensor_shape = mixed_x_layer.size()[:-1] + \
|
||||
(self.num_attention_heads_per_partition,
|
||||
3 * self.hidden_size_per_attention_head)
|
||||
mixed_x_layer = mixed_x_layer.view(*new_tensor_shape)
|
||||
|
||||
# [sq, b, np, 3 * hn] --> 3 [sq, b, np, hn]
|
||||
(query_layer, key_layer, value_layer) = split_tensor_along_last_dim(
|
||||
mixed_x_layer, 3)
|
||||
|
||||
if rotary_pos_emb is not None:
|
||||
query_layer = apply_rotary_pos_emb(query_layer, rotary_pos_emb)
|
||||
key_layer = apply_rotary_pos_emb(key_layer, rotary_pos_emb)
|
||||
|
||||
# adjust key and value for inference
|
||||
if kv_cache is not None:
|
||||
cache_k, cache_v = kv_cache
|
||||
key_layer = torch.cat((cache_k, key_layer), dim=0)
|
||||
value_layer = torch.cat((cache_v, value_layer), dim=0)
|
||||
if use_cache:
|
||||
kv_cache = (key_layer, value_layer)
|
||||
else:
|
||||
kv_cache = None
|
||||
|
||||
# 这里省略了 kv "sbhd" -> "sb(h*num_multi-group)d" 的过程,因为flash-attn支持 MGA
|
||||
# ==================================
|
||||
# core attention computation
|
||||
# ==================================
|
||||
|
||||
context_layer = self.core_attention(
|
||||
query_layer, key_layer, value_layer, attention_mask)
|
||||
|
||||
# =================
|
||||
# Output. [sq, b, h]
|
||||
# =================
|
||||
|
||||
output = self.dense(context_layer)
|
||||
|
||||
return output, kv_cache
|
||||
|
||||
|
||||
class ChatglmFlashAttention(FlashSelfAttention):
|
||||
|
||||
def __init__(self) -> None:
|
||||
raise NotImplementedError(
|
||||
"BloomAttention is not implemented as a physical class. "
|
||||
"It is meant to be used only with the from_native_module interface to Convert a native BloomAttention module to FlashAttention module provided above."
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def from_native_module(module: nn.Module, *args, **kwargs) -> nn.Module:
|
||||
# 这个原实现没有在类中保存config,所以需要初始化一个config
|
||||
layer_number = getattr(module, "layer_number")
|
||||
config = getattr(module, "config")
|
||||
attention = FlashSelfAttention(
|
||||
config=config,
|
||||
layer_number=layer_number,
|
||||
)
|
||||
|
||||
attention.query_key_value.weight.data = module.query_key_value.weight.data
|
||||
attention.dense.weight.data = module.dense.weight.data
|
||||
if getattr(attention.query_key_value, "bias") is not None:
|
||||
attention.query_key_value.bias.data = module.query_key_value.bias.data
|
||||
if getattr(attention.dense, "bias") is not None:
|
||||
attention.dense.bias.data = module.dense.bias.data
|
||||
|
||||
return attention
|
||||
@@ -0,0 +1,9 @@
|
||||
from ixformer.train.speedformer.models.chatglm.modeling_chatglm import RotaryEmbedding
|
||||
from ixformer.train.speedformer.layers.rotary_pos_embedding import RotaryEmbedding
|
||||
|
||||
|
||||
class ChatglmRotaryEmbedding(RotaryEmbedding):
|
||||
def from_native_attr(attr_class, *args, **kwargs):
|
||||
dim = attr_class.dim
|
||||
rote = RotaryEmbedding(dim=dim)
|
||||
return rote
|
||||
127
ixformer_sdk/train/speedformer/layers/chatglm/methods.py
Normal file
127
ixformer_sdk/train/speedformer/layers/chatglm/methods.py
Normal file
@@ -0,0 +1,127 @@
|
||||
import math
|
||||
import warnings
|
||||
from typing import List, Optional, Tuple, Union
|
||||
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
import torch.nn.functional as F
|
||||
|
||||
from ixformer.train.speedformer.models.chatglm.modeling_chatglm import ChatGLMModel
|
||||
|
||||
|
||||
def ChatGLMModel_forward():
|
||||
from transformers.modeling_outputs import BaseModelOutputWithPast
|
||||
from transformers.utils import logging, is_flash_attn_2_available
|
||||
|
||||
def forward(
|
||||
self,
|
||||
input_ids,
|
||||
position_ids: Optional[torch.Tensor] = None,
|
||||
attention_mask: Optional[torch.BoolTensor] = None,
|
||||
full_attention_mask: Optional[torch.BoolTensor] = None,
|
||||
past_key_values: Optional[Tuple[Tuple[torch.Tensor, torch.Tensor], ...]] = None,
|
||||
inputs_embeds: Optional[torch.Tensor] = None,
|
||||
use_cache: Optional[bool] = None,
|
||||
output_hidden_states: Optional[bool] = None,
|
||||
return_dict: Optional[bool] = None,
|
||||
):
|
||||
def is_lower_triangular(mask):
|
||||
"""
|
||||
ixdnn 虽然支持2种causal mask, 如下图:
|
||||
mode0:
|
||||
if seqlen_q < seqlen_k
|
||||
1 0 0 0 0
|
||||
1 1 0 0 0
|
||||
if seqlen_k < seqlen_q
|
||||
1 0
|
||||
1 1
|
||||
1 1
|
||||
1 1
|
||||
1 1
|
||||
mode1:
|
||||
if seqlen_q < seqlen_k
|
||||
1 1 1 1 0
|
||||
1 1 1 1 1
|
||||
if seqlen_k < seqlen_q
|
||||
0 0
|
||||
0 0
|
||||
0 0
|
||||
1 0
|
||||
1 1
|
||||
|
||||
但 flash-attn 目前只支持 mode1, 所以下面需要判断一下传入的mask是不是mode1这种模式
|
||||
"""
|
||||
batch_size, _, rows, cols = mask.shape
|
||||
|
||||
# 创建一个mode1的下三角矩阵
|
||||
if rows <= cols:
|
||||
part = torch.ones(rows, cols - rows,
|
||||
dtype=torch.bool, device=mask.device)
|
||||
gt = ~torch.triu(torch.ones(
|
||||
rows, rows, dtype=torch.bool, device=mask.device), diagonal=1)
|
||||
gt = torch.cat((part, gt), dim=1)
|
||||
else:
|
||||
part = torch.zeros(
|
||||
rows-cols, cols, dtype=torch.bool, device=mask.device)
|
||||
gt = ~torch.triu(torch.ones(
|
||||
cols, cols, dtype=torch.bool, device=mask.device), diagonal=1)
|
||||
gt = torch.cat((part, gt), dim=0)
|
||||
gt = gt[None, None, :, :].expand(batch_size, -1, -1, -1)
|
||||
|
||||
# 检查所有的元素是不是都一样
|
||||
check = (gt == mask).all()
|
||||
|
||||
return check
|
||||
|
||||
output_hidden_states = (
|
||||
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
||||
)
|
||||
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
||||
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
||||
|
||||
batch_size, seq_length = input_ids.shape
|
||||
|
||||
if inputs_embeds is None:
|
||||
inputs_embeds = self.embedding(input_ids)
|
||||
|
||||
if self.pre_seq_len is not None:
|
||||
if past_key_values is None:
|
||||
past_key_values = self.get_prompt(batch_size=batch_size, device=input_ids.device,
|
||||
dtype=inputs_embeds.dtype)
|
||||
if attention_mask is not None:
|
||||
attention_mask = torch.cat([attention_mask.new_ones((batch_size, self.pre_seq_len)),
|
||||
attention_mask], dim=-1)
|
||||
|
||||
if full_attention_mask is None:
|
||||
if (attention_mask is not None and not attention_mask.all()) or (past_key_values and seq_length != 1):
|
||||
full_attention_mask = self.get_masks(
|
||||
input_ids, past_key_values, padding_mask=attention_mask)
|
||||
|
||||
# Rotary positional embeddings
|
||||
rotary_pos_emb = self.rotary_pos_emb(self.seq_length)
|
||||
if position_ids is not None:
|
||||
rotary_pos_emb = rotary_pos_emb[position_ids]
|
||||
else:
|
||||
rotary_pos_emb = rotary_pos_emb[None, :seq_length]
|
||||
rotary_pos_emb = rotary_pos_emb.transpose(0, 1).contiguous()
|
||||
|
||||
# Run encoder.
|
||||
attn_mask = None
|
||||
if full_attention_mask is not None:
|
||||
if not is_lower_triangular(full_attention_mask):
|
||||
attn_mask = full_attention_mask
|
||||
hidden_states, presents, all_hidden_states, all_self_attentions = self.encoder(
|
||||
inputs_embeds, attn_mask, rotary_pos_emb=rotary_pos_emb,
|
||||
kv_caches=past_key_values, use_cache=use_cache, output_hidden_states=output_hidden_states
|
||||
)
|
||||
|
||||
if not return_dict:
|
||||
return tuple(v for v in [hidden_states, presents, all_hidden_states, all_self_attentions] if v is not None)
|
||||
|
||||
return BaseModelOutputWithPast(
|
||||
last_hidden_state=hidden_states,
|
||||
past_key_values=presents,
|
||||
hidden_states=all_hidden_states,
|
||||
attentions=all_self_attentions,
|
||||
)
|
||||
return forward
|
||||
370
ixformer_sdk/train/speedformer/layers/cross_entropy_loss.py
Normal file
370
ixformer_sdk/train/speedformer/layers/cross_entropy_loss.py
Normal file
@@ -0,0 +1,370 @@
|
||||
import time
|
||||
import numpy as np
|
||||
import torch
|
||||
import triton
|
||||
import triton.language as tl
|
||||
from packaging.version import Version
|
||||
if Version(triton.__version__) >= Version("3.0.0"):
|
||||
from triton.language.extra import libdevice
|
||||
triton_tanh = libdevice.tanh
|
||||
else:
|
||||
import triton.language as tl
|
||||
triton_tanh = tl.math.tanh
|
||||
|
||||
|
||||
def calculate_settings(n):
|
||||
BLOCK_SIZE = triton.next_power_of_2(n)
|
||||
if BLOCK_SIZE > MAX_FUSED_SIZE:
|
||||
raise RuntimeError(f"Cannot launch Triton kernel since n = {n} exceeds "
|
||||
f"the maximum CUDA blocksize = {MAX_FUSED_SIZE}.")
|
||||
num_warps = 4
|
||||
if BLOCK_SIZE >= 32768:
|
||||
num_warps = 32
|
||||
elif BLOCK_SIZE >= 8192:
|
||||
num_warps = 16
|
||||
elif BLOCK_SIZE >= 2048:
|
||||
num_warps = 8
|
||||
return BLOCK_SIZE, num_warps
|
||||
|
||||
|
||||
@triton.heuristics({"DO_SOFTCAPPING": lambda args: args["DO_SOFTCAPPING"], })
|
||||
@triton.jit
|
||||
def _cross_entropy_forward(
|
||||
logits_ptr, logits_row_stride,
|
||||
loss_ptr,
|
||||
logsumexp_ptr,
|
||||
labels_ptr,
|
||||
VOCAB_SIZE: tl.constexpr,
|
||||
BLOCK_SIZE: tl.constexpr,
|
||||
DO_SOFTCAPPING: tl.constexpr,
|
||||
SOFTCAP: tl.constexpr,
|
||||
):
|
||||
"""
|
||||
Cross Entropy Loss = 1/n sum [ -yi log(Pi) ]
|
||||
Pi = exp(xi) / sum(exp(xi))
|
||||
CE_i = -y log(p) = -y log[ exp(x) / sum(exp(x)) ]
|
||||
= -y [ x - log[sum(exp(x))] ]
|
||||
= y * (log[sum(exp(x))] - x)
|
||||
If y == 0: CE_i = 0
|
||||
If y == 1: CE_i = logsumexp - x
|
||||
|
||||
logsumexp is also stable
|
||||
Take y = log[sum(exp(x))]
|
||||
exp(y) = sum(exp(x))
|
||||
exp(y) = sum(exp(x - c)*exp(c)) Since e^(x-c)*e^c = e^x
|
||||
exp(y) = exp(c)*sum(exp(x - c))
|
||||
y = log(exp(c)*sum(exp(x - c)))
|
||||
y = c + log[sum(exp(x - c))]
|
||||
This means we can set c = max(x) to make sure
|
||||
exp(x - c) always is exp(x - max(x)).
|
||||
This ensures exp(x - max(x))'s maximum is 1 as exp(0) = 1.
|
||||
"""
|
||||
row_idx = tl.program_id(0)
|
||||
logits_ptr += row_idx * logits_row_stride.to(tl.int64)
|
||||
loss_ptr += row_idx
|
||||
logsumexp_ptr += row_idx
|
||||
labels_ptr += row_idx
|
||||
|
||||
col_offsets = tl.arange(0, BLOCK_SIZE)
|
||||
mask = col_offsets < VOCAB_SIZE
|
||||
|
||||
label_idx = tl.load(labels_ptr).to(tl.int32)
|
||||
logits = tl.load(logits_ptr + col_offsets, mask=mask, other=-float("inf"))
|
||||
# Do logit softcapping for Gemma 2: t * tanh(1/t * x)
|
||||
if DO_SOFTCAPPING:
|
||||
logits = SOFTCAP * triton_tanh(logits / SOFTCAP)
|
||||
|
||||
logits = logits.to(tl.float32)
|
||||
c = tl.max(logits, 0)
|
||||
logsumexp = c + tl.log(tl.sum(tl.exp(logits - c), 0))
|
||||
|
||||
if label_idx != -100:
|
||||
x = tl.load(logits_ptr + label_idx)
|
||||
# Do logit softcapping for Gemma 2: t * tanh(1/t * x)
|
||||
if DO_SOFTCAPPING:
|
||||
x = SOFTCAP * triton_tanh(x / SOFTCAP)
|
||||
loss = logsumexp - x.to(tl.float32)
|
||||
else:
|
||||
loss = 0.0
|
||||
tl.store(logsumexp_ptr, logsumexp)
|
||||
tl.store(loss_ptr, loss)
|
||||
|
||||
|
||||
@triton.heuristics({"DO_SOFTCAPPING": lambda args: args["DO_SOFTCAPPING"], })
|
||||
@triton.jit
|
||||
def _chunked_cross_entropy_forward(
|
||||
logits_ptr, logits_row_stride,
|
||||
loss_ptr,
|
||||
logsumexp_ptr,
|
||||
labels_ptr,
|
||||
VOCAB_SIZE: tl.constexpr,
|
||||
N_CHUNKS: tl.constexpr,
|
||||
BLOCK_SIZE: tl.constexpr,
|
||||
DO_SOFTCAPPING: tl.constexpr,
|
||||
SOFTCAP: tl.constexpr,
|
||||
):
|
||||
"""
|
||||
256K vocab divided in 4 chunks
|
||||
|
||||
|-65536-| |-65536-| |-65536-| |-65536-|
|
||||
|-------| |-------| |-------| |-------|
|
||||
|-------| |-------| |-------| |-------|
|
||||
|
||||
If y == 0: CE_i = 0
|
||||
If y == 1: CE_i = logsumexp - x
|
||||
|
||||
Notice we can do logsumexp for each chunk and then
|
||||
logsumexp[chunk_sum(logsumexp)] == logsumexp
|
||||
|
||||
chunk_sum = log[chunk_sum(logsumexp)]
|
||||
= log[exp(logsumexp(a)) + ... + exp(logsumexp(z))]
|
||||
= log[exp(log[sum(exp(a))]) + ... + exp(log[sum(exp(z))])]
|
||||
= log[sum(exp(a)) + ... + sum(exp(z))]
|
||||
= logsumexp(x)
|
||||
|
||||
This means we can perform a logsumexp for each chunk, then do a
|
||||
final logsumexp reduction!
|
||||
|
||||
Ie do: logsumexp(chunked_logsumexp) - x
|
||||
"""
|
||||
row_idx = tl.program_id(0)
|
||||
chunk_idx = tl.program_id(1)
|
||||
logits_ptr += row_idx * logits_row_stride.to(tl.int64)
|
||||
loss_ptr += row_idx
|
||||
logsumexp_ptr += row_idx * N_CHUNKS + chunk_idx
|
||||
labels_ptr += row_idx
|
||||
|
||||
col_offsets = chunk_idx*BLOCK_SIZE + tl.arange(0, BLOCK_SIZE)
|
||||
mask = col_offsets < VOCAB_SIZE
|
||||
|
||||
label_idx = tl.load(labels_ptr).to(tl.int32)
|
||||
logits = tl.load(logits_ptr + col_offsets, mask=mask, other=-float("inf"))
|
||||
# Do logit softcapping for Gemma 2: t * tanh(1/t * x)
|
||||
if DO_SOFTCAPPING:
|
||||
logits = SOFTCAP * triton_tanh(logits / SOFTCAP)
|
||||
|
||||
logits = logits.to(tl.float32)
|
||||
c = tl.max(logits, 0)
|
||||
logsumexp = c + tl.log(tl.sum(tl.exp(logits - c), 0))
|
||||
|
||||
if chunk_idx == 0:
|
||||
# logsumexp(chunked_logsumexp) - x
|
||||
# Do the -x separately
|
||||
if label_idx != -100:
|
||||
x = tl.load(logits_ptr + label_idx).to(tl.float32)
|
||||
# Do logit softcapping for Gemma 2: t * tanh(1/t * x)
|
||||
if DO_SOFTCAPPING:
|
||||
x = SOFTCAP * triton_tanh(x / SOFTCAP)
|
||||
loss = -1.0 * x.to(tl.float32)
|
||||
else:
|
||||
loss = 0.0
|
||||
tl.store(loss_ptr, loss)
|
||||
|
||||
tl.store(logsumexp_ptr, logsumexp)
|
||||
|
||||
|
||||
@triton.heuristics({"DO_SOFTCAPPING": lambda args: args["DO_SOFTCAPPING"], })
|
||||
@triton.jit
|
||||
def _cross_entropy_backward(
|
||||
logits_ptr, logits_row_stride,
|
||||
dloss_ptr, dloss_row_stride,
|
||||
logsumexp_ptr,
|
||||
labels_ptr,
|
||||
VOCAB_SIZE: tl.constexpr,
|
||||
BLOCK_SIZE: tl.constexpr,
|
||||
DO_SOFTCAPPING: tl.constexpr,
|
||||
SOFTCAP: tl.constexpr,
|
||||
):
|
||||
"""
|
||||
CE_i = -y log(P) = y * (log[sum(exp(x))] - x)
|
||||
dC/dx = d/dx (y * log[sum(exp(x))] - x * y)
|
||||
|
||||
From https://en.wikipedia.org/wiki/LogSumExp
|
||||
d/dx logsumexp = exp(x) / sum(exp(x)) = softmax(x)
|
||||
|
||||
dC/dx = y * exp(x) / sum(exp(x)) - d/dx (x * y)
|
||||
dC/dx = y * exp[ log[exp(x) / sum(exp(x))] ] using x = exp(log(x)) trick
|
||||
dC/dx = y * exp[x - logsumexp] - d/dx (x * y)
|
||||
|
||||
If y == 0: dC/dx = 0
|
||||
If y == 1 and x == label: dC/dlabel = exp[x - logsumexp] - 1
|
||||
If y == 1 and x != label: dC/dx = exp[x - logsumexp]
|
||||
"""
|
||||
row_idx = tl.program_id(0)
|
||||
block_idx = tl.program_id(1)
|
||||
|
||||
logits_ptr += row_idx * logits_row_stride.to(tl.int64)
|
||||
dloss_ptr += row_idx * dloss_row_stride
|
||||
col_offsets = block_idx*BLOCK_SIZE + tl.arange(0, BLOCK_SIZE)
|
||||
mask = col_offsets < VOCAB_SIZE
|
||||
label_idx = tl.load(labels_ptr + row_idx).to(tl.int32)
|
||||
|
||||
if label_idx != -100:
|
||||
dloss = tl.load(dloss_ptr)
|
||||
else:
|
||||
dloss = 0.0
|
||||
|
||||
x = tl.load(logits_ptr + col_offsets, mask=mask, other=-float("inf"))
|
||||
# Do logit softcapping for Gemma 2: t * tanh(1/t * x)
|
||||
if DO_SOFTCAPPING:
|
||||
# d/dx [t * tanh(1/t * x)] = 1 - tanh^2(1/t * x)
|
||||
partial = triton_tanh(x / SOFTCAP)
|
||||
x = SOFTCAP * partial
|
||||
|
||||
logsumexp = tl.load(logsumexp_ptr + row_idx)
|
||||
y = tl.exp(x.to(tl.float32) - logsumexp)
|
||||
y = tl.where(
|
||||
col_offsets == label_idx,
|
||||
y - 1.0, # exp(x - logsumexp) - 1
|
||||
y, # exp(x - logsumexp)
|
||||
)
|
||||
|
||||
if DO_SOFTCAPPING:
|
||||
# d/dx [t * tanh(1/t * x)] = 1 - tanh^2(1/t * x)
|
||||
y = y * (1.0 - partial*partial)
|
||||
|
||||
# If y == 0: dC/dx = 0 ==> we already masked it to be = 0, so dloss = 0.
|
||||
tl.store(logits_ptr + col_offsets, dloss * y, mask=mask)
|
||||
|
||||
|
||||
MAX_FUSED_SIZE = 65536 # 2**16
|
||||
|
||||
|
||||
class Fast_CrossEntropyLoss(torch.autograd.Function):
|
||||
@staticmethod
|
||||
def forward(ctx, logits, labels, logit_softcapping=0):
|
||||
n_rows, vocab_size = logits.shape
|
||||
|
||||
div, mod = divmod(vocab_size, MAX_FUSED_SIZE)
|
||||
n_chunks = div + (mod != 0)
|
||||
losses = torch.empty(n_rows, dtype=torch.float32, device=logits.device)
|
||||
|
||||
DO_SOFTCAPPING = (logit_softcapping != 0)
|
||||
|
||||
if n_chunks == 1:
|
||||
# For small vocabs <= 65336 like Llama, Mistral
|
||||
BLOCK_SIZE, num_warps = calculate_settings(vocab_size)
|
||||
logsumexp = torch.empty(
|
||||
n_rows, dtype=torch.float32, device=logits.device)
|
||||
|
||||
_cross_entropy_forward[(n_rows,)](
|
||||
logits, logits.stride(0),
|
||||
losses,
|
||||
logsumexp,
|
||||
labels,
|
||||
VOCAB_SIZE=vocab_size,
|
||||
BLOCK_SIZE=BLOCK_SIZE,
|
||||
DO_SOFTCAPPING=DO_SOFTCAPPING,
|
||||
SOFTCAP=logit_softcapping,
|
||||
num_warps=num_warps,
|
||||
)
|
||||
else:
|
||||
# For large vocabs > 65336 like Gemma 256K
|
||||
logsumexp = torch.empty(
|
||||
(n_rows, n_chunks,), dtype=torch.float32, device=logits.device)
|
||||
|
||||
_chunked_cross_entropy_forward[(n_rows, n_chunks,)](
|
||||
logits, logits.stride(0),
|
||||
losses,
|
||||
logsumexp,
|
||||
labels,
|
||||
VOCAB_SIZE=vocab_size,
|
||||
N_CHUNKS=n_chunks,
|
||||
BLOCK_SIZE=MAX_FUSED_SIZE,
|
||||
DO_SOFTCAPPING=DO_SOFTCAPPING,
|
||||
SOFTCAP=logit_softcapping,
|
||||
num_warps=32,
|
||||
)
|
||||
# logsumexp(chunked_logsumexp) - x
|
||||
# Do the -x separately
|
||||
logsumexp = torch.logsumexp(logsumexp, dim=1) # Row sum
|
||||
losses += logsumexp
|
||||
# Don't forget to mask padding out!
|
||||
losses.masked_fill_(labels == -100, 0)
|
||||
|
||||
ctx.save_for_backward(logits, logsumexp, labels)
|
||||
ctx.DO_SOFTCAPPING = DO_SOFTCAPPING
|
||||
ctx.logit_softcapping = logit_softcapping
|
||||
return losses
|
||||
|
||||
@staticmethod
|
||||
def backward(ctx, dlosses):
|
||||
logits, logsumexp, labels = ctx.saved_tensors
|
||||
n_rows, vocab_size = logits.shape
|
||||
|
||||
BLOCK_SIZE = 4096
|
||||
div, mod = divmod(vocab_size, BLOCK_SIZE)
|
||||
n_blocks = div + (mod != 0)
|
||||
|
||||
_cross_entropy_backward[(n_rows, n_blocks,)](
|
||||
logits, logits.stride(0),
|
||||
dlosses, dlosses.stride(0),
|
||||
logsumexp,
|
||||
labels,
|
||||
VOCAB_SIZE=vocab_size,
|
||||
BLOCK_SIZE=BLOCK_SIZE,
|
||||
DO_SOFTCAPPING=ctx.DO_SOFTCAPPING,
|
||||
SOFTCAP=ctx.logit_softcapping,
|
||||
num_warps=8,
|
||||
)
|
||||
return logits, None, None,
|
||||
|
||||
|
||||
@torch._disable_dynamo
|
||||
def fast_cross_entropy_loss(logits, labels, logit_softcapping=0):
|
||||
"""
|
||||
Arguments:
|
||||
logits: (batch, seq_len, vocab_size)
|
||||
labels: (batch, seq_len,)
|
||||
Returns:
|
||||
losses: float
|
||||
"""
|
||||
assert len(logits.size()) == 2 or len(logits.size()) == 3
|
||||
if len(logits.size()) == 3:
|
||||
batch, seq_len, d = logits.shape
|
||||
assert (labels.shape == (batch, seq_len))
|
||||
logits = logits.view(batch*seq_len, d)
|
||||
labels = labels.view(-1)
|
||||
|
||||
loss = Fast_CrossEntropyLoss.apply(
|
||||
logits,
|
||||
labels,
|
||||
logit_softcapping,
|
||||
)
|
||||
n_items = torch.count_nonzero(labels != -100)
|
||||
return loss.sum() / n_items
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
shift_logits_numpy = np.random.randn(4096, 32000).astype(np.float32)
|
||||
shift_labels_numpy = np.random.randint(0, 32000, (4096, )).astype(np.int64)
|
||||
|
||||
shift_logits = torch.from_numpy(shift_logits_numpy).cuda()
|
||||
shift_labels = torch.from_numpy(shift_labels_numpy).cuda()
|
||||
|
||||
shift_logits_ref = torch.from_numpy(shift_logits_numpy).cuda()
|
||||
shift_labels_ref = torch.from_numpy(shift_labels_numpy).cuda()
|
||||
|
||||
shift_logits.requires_grad = True
|
||||
shift_logits_ref.requires_grad = True
|
||||
|
||||
# test accuracy
|
||||
loss = fast_cross_entropy_loss(shift_logits, shift_labels)
|
||||
loss_ref = torch.nn.CrossEntropyLoss()(shift_logits_ref, shift_labels_ref)
|
||||
loss.backward()
|
||||
loss_ref.backward()
|
||||
|
||||
torch.testing.assert_close(loss, loss_ref)
|
||||
torch.testing.assert_close(shift_logits.grad, shift_logits_ref.grad)
|
||||
|
||||
start = time.time()
|
||||
for i in range(1000):
|
||||
loss = fast_cross_entropy_loss(shift_logits, shift_labels)
|
||||
loss.backward()
|
||||
print("triton:", time.time() - start)
|
||||
|
||||
start = time.time()
|
||||
for i in range(1000):
|
||||
loss_ref = torch.nn.CrossEntropyLoss()(shift_logits, shift_labels)
|
||||
loss_ref.backward()
|
||||
print("torch:", time.time() - start)
|
||||
305
ixformer_sdk/train/speedformer/layers/fast_lora/fast_lora.py
Normal file
305
ixformer_sdk/train/speedformer/layers/fast_lora/fast_lora.py
Normal file
@@ -0,0 +1,305 @@
|
||||
# Copyright 2023-present Daniel Han-Chen & the Unsloth team. All rights reserved.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
from ixformer.train.speedformer.layers.fast_lora.swiglu import swiglu_fg_kernel, swiglu_DWf_DW_dfg_kernel
|
||||
import torch
|
||||
from ixformer.train.speedformer.layers.fast_lora.utils import (
|
||||
fast_dequantize,
|
||||
QUANT_STATE,
|
||||
get_lora_parameters,
|
||||
matmul_lora,
|
||||
torch_amp_custom_fwd,
|
||||
torch_amp_custom_bwd,
|
||||
)
|
||||
|
||||
|
||||
class LoRA_MLP(torch.autograd.Function):
|
||||
"""
|
||||
### LoRA weights
|
||||
G = G + Ag @ Bg
|
||||
U = U + Au @ Bu
|
||||
W = W + Aw @ Bw
|
||||
|
||||
### SwiGLU(X)
|
||||
e = X @ G
|
||||
f = e * sigmoid(e)
|
||||
g = X @ U
|
||||
h = f * g
|
||||
i = h @ W
|
||||
|
||||
### Backpropagation chain rule
|
||||
See our blog post for more details
|
||||
|
||||
df = sigmoid(e) * (1 - f) + f
|
||||
dC/dW = h.T @ dY
|
||||
dC/dU = X.T @ (D @ W.T * f)
|
||||
dC/dG = X.T @ (D @ W.T * df * g)
|
||||
|
||||
### Down projection LoRA weights
|
||||
dC/dAw = dC/dW @ B.T
|
||||
dC/dBw = A.T @ dC/dW
|
||||
dC/dAw = h.T @ dY @ B.T
|
||||
dC/dBw = A.T @ h.T @ dY
|
||||
|
||||
### Up projection LoRA weights
|
||||
dC/dAu = X.T @ (D @ W.T * f) @ B.T
|
||||
dC/dBu = A.T @ X.T @ (D @ W.T * f)
|
||||
|
||||
### Gate projection LoRA weights
|
||||
dC/dAg = X.T @ (D @ W.T * df * g) @ B.T
|
||||
dC/dBg = A.T @ X.T @ (D @ W.T * df * g)
|
||||
|
||||
Don't forget to see our blog post for more details!
|
||||
"""
|
||||
@staticmethod
|
||||
@torch_amp_custom_fwd
|
||||
def forward(ctx, X: torch.Tensor,
|
||||
gateW, gateW_quant, gateA, gateB, gateS,
|
||||
upW, upW_quant, upA, upB, upS,
|
||||
downW, downW_quant, downA, downB, downS,
|
||||
_forward_function, _backward_function,):
|
||||
dtype = X.dtype
|
||||
|
||||
e = matmul_lora(X, gateW, gateW_quant, gateA, gateB, gateS)
|
||||
g = matmul_lora(X, upW, upW_quant, upA, upB, upS)
|
||||
h = _forward_function(e, g)
|
||||
i = matmul_lora(h, downW, downW_quant, downA, downB, downS)
|
||||
|
||||
ctx.custom_saved_tensors = (
|
||||
gateW, gateW_quant, gateS,
|
||||
upW, upW_quant, upS,
|
||||
downW, downW_quant, downS,
|
||||
_backward_function,
|
||||
)
|
||||
ctx.save_for_backward(gateA, gateB, upA, upB, downA, downB,
|
||||
X, e, g)
|
||||
return i
|
||||
pass
|
||||
|
||||
@staticmethod
|
||||
@torch_amp_custom_bwd
|
||||
def backward(ctx, dY: torch.Tensor):
|
||||
gateW, gateW_quant, gateS, upW, upW_quant, upS, downW, downW_quant, downS, \
|
||||
_backward_function = ctx.custom_saved_tensors
|
||||
gateA, gateB, upA, upB, downA, downB, \
|
||||
X, e, g = ctx.saved_tensors
|
||||
|
||||
gateA, gateB, upA, upB, downA, downB = \
|
||||
gateA.t(), gateB.t(), upA.t(), upB.t(), downA.t(), downB.t()
|
||||
|
||||
batch, seq_len, hd = X.shape
|
||||
dY = dY.view(-1, dY.shape[-1])
|
||||
X = X .view(-1, X .shape[-1])
|
||||
e = e .view(-1, e .shape[-1])
|
||||
g = g .view(-1, g .shape[-1])
|
||||
dtype = X.dtype
|
||||
|
||||
DW = matmul_lora(dY, downW.t(), downW_quant, downB, downA, downS)
|
||||
DW, e, g = _backward_function(DW, e, g)
|
||||
h, df, de = DW, e, g
|
||||
|
||||
# Down projection LoRA weights
|
||||
d_downA = h.t() @ (dY @ downB.t())
|
||||
d_downB = (downA.t() @ h.t()) @ dY
|
||||
d_downA *= downS
|
||||
d_downB *= downS
|
||||
|
||||
# Up projection LoRA weights
|
||||
d_upA = X.t() @ (df @ upB.t())
|
||||
d_upB = (upA.t() @ X.t()) @ df
|
||||
d_upA *= upS
|
||||
d_upB *= upS
|
||||
|
||||
# Gate projection LoRA weights
|
||||
d_gateA = X.t() @ (de @ gateB.t())
|
||||
d_gateB = (gateA.t() @ X.t()) @ de
|
||||
d_gateA *= gateS
|
||||
d_gateB *= gateS
|
||||
|
||||
# dX = matmul_lora(df, upW.t(), upW_quant, upB, upA, upS)
|
||||
# dX += matmul_lora(de, gateW.t(), gateW_quant, gateB, gateA, gateS)
|
||||
upW = fast_dequantize(upW.t(), upW_quant)
|
||||
dX = torch.matmul(df, upW.t(), out=X)
|
||||
del upW
|
||||
dX += df @ upB.to(dtype).t() @ (upS * upA.to(dtype).t())
|
||||
|
||||
gateW = fast_dequantize(gateW.t(), gateW_quant)
|
||||
dX += de @ gateW.t()
|
||||
del gateW
|
||||
dX += de @ gateB.to(dtype).t() @ (gateS * gateA.to(dtype).t())
|
||||
|
||||
# gateW, gateW_quant, gateA, gateB, gateS,
|
||||
# upW, upW_quant, upA, upB, upS,
|
||||
# downW, downW_quant, downA, downB, downS,
|
||||
return dX.view(batch, seq_len, hd), \
|
||||
None, None, d_gateA.t(), d_gateB.t(), None, \
|
||||
None, None, d_upA.t(), d_upB.t(), None, \
|
||||
None, None, d_downA.t(), d_downB.t(), None, \
|
||||
None, None, # _backward and _forward
|
||||
pass
|
||||
|
||||
|
||||
pass
|
||||
|
||||
|
||||
def apply_lora_mlp_swiglu(self, X):
|
||||
gateW, gateW_quant, gateA, gateB, gateS = get_lora_parameters(
|
||||
self.gate_proj)
|
||||
upW, upW_quant, upA, upB, upS = get_lora_parameters(
|
||||
self. up_proj)
|
||||
downW, downW_quant, downA, downB, downS = get_lora_parameters(
|
||||
self.down_proj)
|
||||
|
||||
out = LoRA_MLP.apply(X,
|
||||
gateW, gateW_quant, gateA, gateB, gateS,
|
||||
upW, upW_quant, upA, upB, upS,
|
||||
downW, downW_quant, downA, downB, downS,
|
||||
swiglu_fg_kernel, swiglu_DWf_DW_dfg_kernel,)
|
||||
return out
|
||||
|
||||
|
||||
pass
|
||||
|
||||
|
||||
class LoRA_FUSEMLP(torch.autograd.Function):
|
||||
"""
|
||||
### LoRA weights
|
||||
G = G + Ag @ Bg
|
||||
U = U + Au @ Bu
|
||||
W = W + Aw @ Bw
|
||||
|
||||
### SwiGLU(X)
|
||||
e = X @ G
|
||||
f = e * sigmoid(e)
|
||||
g = X @ U
|
||||
h = f * g
|
||||
i = h @ W
|
||||
|
||||
### Backpropagation chain rule
|
||||
See our blog post for more details
|
||||
|
||||
df = sigmoid(e) * (1 - f) + f
|
||||
dC/dW = h.T @ dY
|
||||
dC/dU = X.T @ (D @ W.T * f)
|
||||
dC/dG = X.T @ (D @ W.T * df * g)
|
||||
|
||||
### Down projection LoRA weights
|
||||
dC/dAw = dC/dW @ B.T
|
||||
dC/dBw = A.T @ dC/dW
|
||||
dC/dAw = h.T @ dY @ B.T
|
||||
dC/dBw = A.T @ h.T @ dY
|
||||
|
||||
### Up projection LoRA weights
|
||||
dC/dAu = X.T @ (D @ W.T * f) @ B.T
|
||||
dC/dBu = A.T @ X.T @ (D @ W.T * f)
|
||||
|
||||
### Gate projection LoRA weights
|
||||
dC/dAg = X.T @ (D @ W.T * df * g) @ B.T
|
||||
dC/dBg = A.T @ X.T @ (D @ W.T * df * g)
|
||||
|
||||
Don't forget to see our blog post for more details!
|
||||
"""
|
||||
@staticmethod
|
||||
@torch_amp_custom_fwd
|
||||
def forward(ctx, X: torch.Tensor,
|
||||
gateupW, gateupW_quant, gateupA, gateupB, gateupS,
|
||||
downW, downW_quant, downA, downB, downS,
|
||||
_forward_function, _backward_function,):
|
||||
dtype = X.dtype
|
||||
|
||||
res_gateup_proj = matmul_lora(
|
||||
X, gateupW, gateupW_quant, gateupA, gateupB, gateupS)
|
||||
# e, g = torch.chunk(res_gateup_proj, 2, dim=-1)
|
||||
e, g = torch.split(
|
||||
res_gateup_proj, res_gateup_proj.size(-1)//2, dim=-1)
|
||||
h = _forward_function(e, g)
|
||||
i = matmul_lora(h, downW, downW_quant, downA, downB, downS)
|
||||
|
||||
ctx.custom_saved_tensors = (
|
||||
gateupW, gateupW_quant, gateupS,
|
||||
downW, downW_quant, downS,
|
||||
_backward_function,
|
||||
)
|
||||
ctx.save_for_backward(gateupA, gateupB, downA, downB, X, e, g)
|
||||
return i
|
||||
pass
|
||||
|
||||
@staticmethod
|
||||
@torch_amp_custom_bwd
|
||||
def backward(ctx, dY: torch.Tensor):
|
||||
gateupW, gateupW_quant, gateupS, downW, downW_quant, downS, \
|
||||
_backward_function = ctx.custom_saved_tensors
|
||||
gateupA, gateupB, downA, downB, \
|
||||
X, e, g = ctx.saved_tensors
|
||||
|
||||
gateupA, gateupB, downA, downB = \
|
||||
gateupA.t(), gateupB.t(), downA.t(), downB.t()
|
||||
|
||||
batch, seq_len, hd = X.shape
|
||||
dY = dY.view(-1, dY.shape[-1])
|
||||
X = X .view(-1, X .shape[-1])
|
||||
e = e .view(-1, e .shape[-1])
|
||||
g = g .view(-1, g .shape[-1])
|
||||
dtype = X.dtype
|
||||
|
||||
DW = matmul_lora(dY, downW.t(), downW_quant, downB, downA, downS)
|
||||
DW, e, g = _backward_function(DW, e, g)
|
||||
h, df, de = DW, e, g
|
||||
|
||||
# Down projection LoRA weights
|
||||
d_downA = h.t() @ (dY @ downB.t())
|
||||
d_downB = (downA.t() @ h.t()) @ dY
|
||||
d_downA *= downS
|
||||
d_downB *= downS
|
||||
|
||||
# Gate_up projection LoRA weights
|
||||
d_gateupA = X.t() @ (de @ gateupB.t())
|
||||
d_gateupB = (gateupA.t() @ X.t()) @ de
|
||||
d_gateupA *= gateupS
|
||||
d_gateupB *= gateupS
|
||||
|
||||
# dX = matmul_lora(df, upW.t(), upW_quant, upB, upA, upS)
|
||||
# dX += matmul_lora(de, gateW.t(), gateW_quant, gateB, gateA, gateS)
|
||||
gateupW = fast_dequantize(gateupW.t(), gateupW_quant)
|
||||
dX = de @ gateupW.t()
|
||||
del gateupW
|
||||
dX += de @ gateupB.to(dtype).t() @ (gateupS * gateupA.to(dtype).t())
|
||||
|
||||
# gateW, gateW_quant, gateA, gateB, gateS,
|
||||
# upW, upW_quant, upA, upB, upS,
|
||||
# downW, downW_quant, downA, downB, downS,
|
||||
return dX.view(batch, seq_len, hd), \
|
||||
None, None, d_gateupA.t(), d_gateupB.t(), None, \
|
||||
None, None, d_downA.t(), d_downB.t(), None, \
|
||||
None, None, # _backward and _forward
|
||||
pass
|
||||
|
||||
|
||||
pass
|
||||
|
||||
|
||||
def apply_lora_fuse_mlp_swiglu(self, X):
|
||||
gateupW, gateupW_quant, gateupA, gateupB, gateupS = get_lora_parameters(
|
||||
self.gate_up)
|
||||
downW, downW_quant, downA, downB, downS = get_lora_parameters(
|
||||
self.down_proj)
|
||||
|
||||
out = LoRA_FUSEMLP.apply(X,
|
||||
gateupW, gateupW_quant, gateupA, gateupB, gateupS,
|
||||
downW, downW_quant, downA, downB, downS,
|
||||
swiglu_fg_kernel, swiglu_DWf_DW_dfg_kernel,)
|
||||
return out
|
||||
|
||||
|
||||
pass
|
||||
148
ixformer_sdk/train/speedformer/layers/fast_lora/fast_lora_.py
Normal file
148
ixformer_sdk/train/speedformer/layers/fast_lora/fast_lora_.py
Normal file
@@ -0,0 +1,148 @@
|
||||
# Copyright 2023-present Daniel Han-Chen & the Unsloth team. All rights reserved.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
import torch
|
||||
from .utils import (
|
||||
fast_dequantize,
|
||||
QUANT_STATE,
|
||||
get_lora_parameters,
|
||||
matmul_lora,
|
||||
torch_amp_custom_fwd,
|
||||
torch_amp_custom_bwd,
|
||||
)
|
||||
|
||||
|
||||
class LoRA_MLP(torch.autograd.Function):
|
||||
"""
|
||||
### LoRA weights
|
||||
G = G + Ag @ Bg
|
||||
U = U + Au @ Bu
|
||||
W = W + Aw @ Bw
|
||||
|
||||
### SwiGLU(X)
|
||||
e = X @ G
|
||||
f = e * sigmoid(e)
|
||||
g = X @ U
|
||||
h = f * g
|
||||
i = h @ W
|
||||
|
||||
### Backpropagation chain rule
|
||||
See our blog post for more details
|
||||
|
||||
df = sigmoid(e) * (1 - f) + f
|
||||
dC/dW = h.T @ dY
|
||||
dC/dU = X.T @ (D @ W.T * f)
|
||||
dC/dG = X.T @ (D @ W.T * df * g)
|
||||
|
||||
### Down projection LoRA weights
|
||||
dC/dAw = dC/dW @ B.T
|
||||
dC/dBw = A.T @ dC/dW
|
||||
dC/dAw = h.T @ dY @ B.T
|
||||
dC/dBw = A.T @ h.T @ dY
|
||||
|
||||
### Up projection LoRA weights
|
||||
dC/dAu = X.T @ (D @ W.T * f) @ B.T
|
||||
dC/dBu = A.T @ X.T @ (D @ W.T * f)
|
||||
|
||||
### Gate projection LoRA weights
|
||||
dC/dAg = X.T @ (D @ W.T * df * g) @ B.T
|
||||
dC/dBg = A.T @ X.T @ (D @ W.T * df * g)
|
||||
|
||||
Don't forget to see our blog post for more details!
|
||||
"""
|
||||
@staticmethod
|
||||
@torch_amp_custom_fwd
|
||||
def forward(ctx, X : torch.Tensor,
|
||||
gateupW, gateupW_quant, gateupA, gateupB, gateupS,
|
||||
downW, downW_quant, downA, downB, downS,
|
||||
_forward_function, _backward_function,):
|
||||
dtype = X.dtype
|
||||
|
||||
res_gateup_proj = matmul_lora(X, gateupW, gateupW_quant, gateupA, gateupB, gateupS)
|
||||
res_swiglu = _forward_function(res_gateup_proj)
|
||||
res_mlp = matmul_lora(res_swiglu, downW, downW_quant, downA, downB, downS)
|
||||
|
||||
ctx.custom_saved_tensors = (
|
||||
gateupW, gateupW_quant, gateupS,
|
||||
downW, downW_quant, downS,
|
||||
_backward_function,
|
||||
)
|
||||
ctx.save_for_backward(gateupA, gateupB, downA, downB, X, res_gateup_proj, res_mlp)
|
||||
return res_mlp
|
||||
pass
|
||||
|
||||
|
||||
@staticmethod
|
||||
@torch_amp_custom_bwd
|
||||
def backward(ctx, dY : torch.Tensor):
|
||||
gateupW, gateupW_quant, gateupS, downW, downW_quant, downS, \
|
||||
_backward_function = ctx.custom_saved_tensors
|
||||
gateupA, gateupB, downA, downB, \
|
||||
X, res_gateup_proj, res_mlp = ctx.saved_tensors
|
||||
|
||||
gateupA, gateupB, downA, downB = \
|
||||
gateupA.t(), gateupB.t(), downA.t(), downB.t()
|
||||
|
||||
batch, seq_len, hd = X.shape
|
||||
dY = dY.view(-1, dY.shape[-1])
|
||||
X = X .view(-1, X .shape[-1])
|
||||
res_gateup_proj = res_gateup_proj.view(-1, res_gateup_proj.shape[-1])
|
||||
dtype = X.dtype
|
||||
|
||||
D_swiglu = matmul_lora(dY, downW.t(), downW_quant, downB, downA, downS)
|
||||
DW, e, g = _backward_function(D_swiglu, res_gateup_proj)
|
||||
h, df, de = DW, e, g
|
||||
|
||||
# Down projection LoRA weights
|
||||
d_downA = h.t() @ (dY @ downB.t())
|
||||
d_downB = (downA.t() @ h.t()) @ dY
|
||||
d_downA *= downS
|
||||
d_downB *= downS
|
||||
|
||||
# Gate_up projection LoRA weights
|
||||
d_gateupA = X.t() @ (de @ gateupB.t())
|
||||
d_gateupB = (gateupA.t() @ X.t()) @ de
|
||||
d_gateupA *= gateupS
|
||||
d_gateupB *= gateupS
|
||||
|
||||
# dX = matmul_lora(df, upW.t(), upW_quant, upB, upA, upS)
|
||||
# dX += matmul_lora(de, gateW.t(), gateW_quant, gateB, gateA, gateS)
|
||||
|
||||
gateupW = fast_dequantize(gateupW.t(), gateupW_quant)
|
||||
dX = de @ gateupW.t()
|
||||
del gateupW
|
||||
dX += de @ gateupB.to(dtype).t() @ (gateupS * gateupA.to(dtype).t())
|
||||
|
||||
# gateW, gateW_quant, gateA, gateB, gateS,
|
||||
# upW, upW_quant, upA, upB, upS,
|
||||
# downW, downW_quant, downA, downB, downS,
|
||||
return dX.view(batch, seq_len, hd), \
|
||||
None, None, d_gateupA.t(), d_gateupB.t(), None, \
|
||||
None, None, d_downA.t(), d_downB.t(), None, \
|
||||
None, None, # _backward and _forward
|
||||
pass
|
||||
pass
|
||||
|
||||
|
||||
from .swiglu_ import swiglu_fg_kernel, swiglu_DWf_DW_dfg_kernel
|
||||
def apply_lora_mlp_swiglu(self, X):
|
||||
gateupW, gateupW_quant, gateupA, gateupB, gateupS = get_lora_parameters(self.gate_up)
|
||||
downW, downW_quant, downA, downB, downS = get_lora_parameters(self.down_proj)
|
||||
|
||||
out = LoRA_MLP.apply(X,
|
||||
gateupW, gateupW_quant, gateupA, gateupB, gateupS,
|
||||
downW, downW_quant, downA, downB, downS,
|
||||
swiglu_fg_kernel, swiglu_DWf_DW_dfg_kernel,)
|
||||
return out
|
||||
pass
|
||||
106
ixformer_sdk/train/speedformer/layers/fast_lora/swiglu.py
Normal file
106
ixformer_sdk/train/speedformer/layers/fast_lora/swiglu.py
Normal file
@@ -0,0 +1,106 @@
|
||||
# Copyright 2023-present Daniel Han-Chen & the Unsloth team. All rights reserved.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
import triton
|
||||
import triton.language as tl
|
||||
import torch
|
||||
|
||||
|
||||
@triton.jit
|
||||
def _fg_kernel(e, g, h, n_elements, BLOCK_SIZE: tl.constexpr,):
|
||||
block_idx = tl.program_id(0)
|
||||
offsets = block_idx*BLOCK_SIZE + tl.arange(0, BLOCK_SIZE)
|
||||
mask = offsets < n_elements
|
||||
|
||||
e_row = tl.load(e + offsets, mask=mask, other=0).to(tl.float32)
|
||||
g_row = tl.load(g + offsets, mask=mask, other=0) # .to(tl.float32)
|
||||
|
||||
# f = e * sigmoid(e)
|
||||
f_row = e_row * tl.sigmoid(e_row) # e_row / (1 + tl.exp(-e_row))
|
||||
f_row = f_row.to(g_row.dtype) # Exact copy from HF
|
||||
# h = f * g
|
||||
h_row = f_row * g_row
|
||||
|
||||
# Store h
|
||||
tl.store(h + offsets, h_row, mask=mask)
|
||||
|
||||
|
||||
pass
|
||||
|
||||
|
||||
def swiglu_fg_kernel(e, g):
|
||||
batch, seq_len, hd = e.shape
|
||||
n_elements = e.numel()
|
||||
h = torch.empty((batch, seq_len, hd), dtype=e.dtype, device="cuda:0")
|
||||
def grid(meta): return (triton.cdiv(n_elements, meta['BLOCK_SIZE']),)
|
||||
_fg_kernel[grid](e, g, h, n_elements, BLOCK_SIZE=1024,)
|
||||
return h
|
||||
|
||||
|
||||
pass
|
||||
|
||||
|
||||
@triton.jit
|
||||
def _DWf_DW_dfg_kernel(DW, e, g, n_elements, BLOCK_SIZE: tl.constexpr,):
|
||||
"""
|
||||
e = e.float()
|
||||
se = 1.0 / (1.0 + torch.exp(-e))
|
||||
f = (se * e).to(dtype)
|
||||
h = f * g
|
||||
df = DW * f
|
||||
dg = DW * g
|
||||
de = (dg.float() * se * (1.0 + e * (1.0 - se))).to(dtype)
|
||||
"""
|
||||
block_idx = tl.program_id(0)
|
||||
offsets = block_idx*BLOCK_SIZE + tl.arange(0, BLOCK_SIZE)
|
||||
mask = offsets < n_elements
|
||||
|
||||
DW_row = tl.load(DW + offsets, mask=mask, other=0) # .to(tl.float32)
|
||||
e_row = tl.load(e + offsets, mask=mask, other=0).to(tl.float32)
|
||||
g_row = tl.load(g + offsets, mask=mask, other=0) # .to(tl.float32)
|
||||
|
||||
# e = e.float()
|
||||
# se = 1.0 / (1.0 + torch.exp(-e))
|
||||
se_row = tl.sigmoid(e_row) # 1.0 / (1.0 + tl.exp(-e_row))
|
||||
# f = (se * e).to(dtype)
|
||||
f_row = se_row * e_row
|
||||
f_row = f_row.to(DW_row.dtype)
|
||||
# h = f * g
|
||||
h_row = f_row * g_row
|
||||
# df = DW * f
|
||||
df_row = DW_row * f_row
|
||||
# dg = DW * g
|
||||
dg_row = DW_row * g_row
|
||||
# de = (dg.float() * se * (1.0 + e * (1.0 - se))).to(dtype)
|
||||
de_row = dg_row.to(tl.float32) * se_row * (1.0 + e_row * (1.0 - se_row))
|
||||
de_row = de_row.to(DW_row.dtype)
|
||||
|
||||
# Store derivatives in buffers
|
||||
tl.store(DW + offsets, h_row, mask=mask) # h = f * g
|
||||
tl.store(e + offsets, df_row, mask=mask) # df = DW * f
|
||||
tl.store(g + offsets, de_row, mask=mask) # de
|
||||
|
||||
|
||||
pass
|
||||
|
||||
|
||||
def swiglu_DWf_DW_dfg_kernel(DW, e, g):
|
||||
batch_seq_len, hd = e.shape
|
||||
n_elements = e.numel()
|
||||
def grid(meta): return (triton.cdiv(n_elements, meta['BLOCK_SIZE']),)
|
||||
_DWf_DW_dfg_kernel[grid](DW, e, g, n_elements, BLOCK_SIZE=1024,)
|
||||
return DW, e, g
|
||||
|
||||
|
||||
pass
|
||||
102
ixformer_sdk/train/speedformer/layers/fast_lora/swiglu_.py
Normal file
102
ixformer_sdk/train/speedformer/layers/fast_lora/swiglu_.py
Normal file
@@ -0,0 +1,102 @@
|
||||
# Copyright 2023-present Daniel Han-Chen & the Unsloth team. All rights reserved.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
import triton
|
||||
import triton.language as tl
|
||||
import torch
|
||||
|
||||
|
||||
@triton.jit
|
||||
def _fg_kernel(x, h, hd, BLOCK_SIZE : tl.constexpr,):
|
||||
block_idx = tl.program_id(0)
|
||||
offsets0 = block_idx*2*hd + tl.arange(0, BLOCK_SIZE)
|
||||
offsets1 = block_idx*2*hd + hd + tl.arange(0, BLOCK_SIZE)
|
||||
mask = offsets0 < hd
|
||||
|
||||
e_row = tl.load(x + offsets0, mask = mask, other = 0).to(tl.float32)
|
||||
g_row = tl.load(x + offsets1, mask = mask, other = 0)#.to(tl.float32)
|
||||
|
||||
# f = e * sigmoid(e)
|
||||
f_row = e_row * tl.sigmoid(e_row) # e_row / (1 + tl.exp(-e_row))
|
||||
f_row = f_row.to(g_row.dtype) # Exact copy from HF
|
||||
# h = f * g
|
||||
h_row = f_row * g_row
|
||||
|
||||
# Store h
|
||||
tl.store(h + offsets0, h_row, mask = mask)
|
||||
pass
|
||||
|
||||
|
||||
def swiglu_fg_kernel(x):
|
||||
batch, seq_len, hdx2 = x.shape
|
||||
hd = hdx2 // 2
|
||||
n_rows = batch * seq_len
|
||||
BLOCK_SIZE = triton.next_power_of_2(hd)
|
||||
h = torch.empty((batch, seq_len, hd), dtype = x.dtype, device = "cuda:0")
|
||||
|
||||
_fg_kernel[n_rows,](x, h, hd, BLOCK_SIZE=BLOCK_SIZE)
|
||||
return h
|
||||
pass
|
||||
|
||||
|
||||
@triton.jit
|
||||
def _DWf_DW_dfg_kernel(DW, x, hd, BLOCK_SIZE : tl.constexpr,):
|
||||
"""
|
||||
e = e.float()
|
||||
se = 1.0 / (1.0 + torch.exp(-e))
|
||||
f = (se * e).to(dtype)
|
||||
h = f * g
|
||||
df = DW * f
|
||||
dg = DW * g
|
||||
de = (dg.float() * se * (1.0 + e * (1.0 - se))).to(dtype)
|
||||
"""
|
||||
block_idx = tl.program_id(0)
|
||||
offsets0 = block_idx*hd*2 + tl.arange(0, BLOCK_SIZE)
|
||||
offsets1 = block_idx*hd*2 + hd + tl.arange(0, BLOCK_SIZE)
|
||||
mask = BLOCK_SIZE < hd
|
||||
|
||||
DW_row = tl.load(DW + offsets0, mask = mask, other = 0)#.to(tl.float32)
|
||||
e_row = tl.load(x + offsets0, mask = mask, other = 0).to(tl.float32)
|
||||
g_row = tl.load(x + offsets1, mask = mask, other = 0)#.to(tl.float32)
|
||||
|
||||
# e = e.float()
|
||||
# se = 1.0 / (1.0 + torch.exp(-e))
|
||||
se_row = tl.sigmoid(e_row) # 1.0 / (1.0 + tl.exp(-e_row))
|
||||
# f = (se * e).to(dtype)
|
||||
f_row = se_row * e_row
|
||||
f_row = f_row.to(DW_row.dtype)
|
||||
# h = f * g
|
||||
h_row = f_row * g_row
|
||||
# df = DW * f
|
||||
df_row = DW_row * f_row
|
||||
# dg = DW * g
|
||||
dg_row = DW_row * g_row
|
||||
# de = (dg.float() * se * (1.0 + e * (1.0 - se))).to(dtype)
|
||||
de_row = dg_row.to(tl.float32) * se_row * (1.0 + e_row * (1.0 - se_row))
|
||||
de_row = de_row.to(DW_row.dtype)
|
||||
|
||||
# Store derivatives in buffers
|
||||
tl.store(DW + offsets0, h_row, mask = mask) # h = f * g
|
||||
tl.store(x + offsets0, df_row, mask = mask) # df = DW * f
|
||||
tl.store(x + offsets1, de_row, mask = mask) # de
|
||||
pass
|
||||
|
||||
|
||||
def swiglu_DWf_DW_dfg_kernel(DW, x):
|
||||
batch_seq_len, hdx2 = x.shape
|
||||
hd = hdx2 // 2
|
||||
BLOCK_SIZE = triton.next_power_of_2(hd)
|
||||
_DWf_DW_dfg_kernel[batch_seq_len, ](DW, x, hd, BLOCK_SIZE=BLOCK_SIZE,)
|
||||
return DW, x
|
||||
pass
|
||||
195
ixformer_sdk/train/speedformer/layers/fast_lora/utils.py
Normal file
195
ixformer_sdk/train/speedformer/layers/fast_lora/utils.py
Normal file
@@ -0,0 +1,195 @@
|
||||
# Copyright 2023-present Daniel Han-Chen & the Unsloth team. All rights reserved.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
import ctypes
|
||||
import bitsandbytes as bnb
|
||||
from packaging.version import Version
|
||||
import torch
|
||||
import triton
|
||||
MAX_FUSED_SIZE = 65536
|
||||
next_power_of_2 = triton.next_power_of_2
|
||||
|
||||
# torch.cuda.amp.custom_fwd is deprecated >= 2.4
|
||||
if Version(torch.__version__) < Version("2.4.0"):
|
||||
torch_amp_custom_fwd = torch.cuda.amp.custom_fwd
|
||||
torch_amp_custom_bwd = torch.cuda.amp.custom_bwd
|
||||
else:
|
||||
torch_amp_custom_fwd = torch.amp.custom_fwd(device_type="cuda")
|
||||
torch_amp_custom_bwd = torch.amp.custom_bwd(device_type="cuda")
|
||||
pass
|
||||
|
||||
|
||||
# tl.math.tanh now is libdevice.tanh
|
||||
if Version(triton.__version__) >= Version("3.0.0"):
|
||||
from triton.language.extra import libdevice
|
||||
triton_tanh = libdevice.tanh
|
||||
else:
|
||||
import triton.language as tl
|
||||
triton_tanh = tl.math.tanh
|
||||
pass
|
||||
|
||||
|
||||
def calculate_settings(n):
|
||||
BLOCK_SIZE = next_power_of_2(n)
|
||||
if BLOCK_SIZE > MAX_FUSED_SIZE:
|
||||
raise RuntimeError(f"Cannot launch Triton kernel since n = {n} exceeds "
|
||||
f"the maximum CUDA blocksize = {MAX_FUSED_SIZE}.")
|
||||
num_warps = 4
|
||||
if BLOCK_SIZE >= 32768:
|
||||
num_warps = 32
|
||||
elif BLOCK_SIZE >= 8192:
|
||||
num_warps = 16
|
||||
elif BLOCK_SIZE >= 2048:
|
||||
num_warps = 8
|
||||
return BLOCK_SIZE, num_warps
|
||||
|
||||
|
||||
pass
|
||||
|
||||
|
||||
get_ptr = bnb.functional.get_ptr
|
||||
cdequantize_blockwise_fp32 = bnb.functional.lib.cdequantize_blockwise_fp32
|
||||
cdequantize_blockwise_fp16_nf4 = bnb.functional.lib.cdequantize_blockwise_fp16_nf4
|
||||
cdequantize_blockwise_bf16_nf4 = bnb.functional.lib.cdequantize_blockwise_bf16_nf4
|
||||
|
||||
|
||||
def QUANT_STATE(W):
|
||||
return getattr(W, "quant_state", None)
|
||||
|
||||
|
||||
pass
|
||||
|
||||
|
||||
def get_lora_parameters(proj):
|
||||
# For DPO or disabled adapters
|
||||
base_layer = (proj.base_layer if hasattr(proj, "base_layer") else proj)
|
||||
W = base_layer.weight
|
||||
|
||||
if not hasattr(proj, "disable_adapters") or proj.disable_adapters or proj.merged:
|
||||
return W, QUANT_STATE(W), None, None, None
|
||||
pass
|
||||
|
||||
active_adapter = proj.active_adapters[0] if \
|
||||
hasattr(proj, "active_adapters") else proj.active_adapter
|
||||
A = proj.lora_A[active_adapter].weight
|
||||
B = proj.lora_B[active_adapter].weight
|
||||
s = proj.scaling[active_adapter]
|
||||
return W, QUANT_STATE(W), A, B, s
|
||||
|
||||
|
||||
pass
|
||||
|
||||
|
||||
def get_lora_parameters_bias(proj):
|
||||
# For DPO or disabled adapters
|
||||
base_layer = (proj.base_layer if hasattr(proj, "base_layer") else proj)
|
||||
W = base_layer.weight
|
||||
bias = base_layer.bias
|
||||
|
||||
if not hasattr(proj, "disable_adapters") or proj.disable_adapters or proj.merged:
|
||||
return W, QUANT_STATE(W), None, None, None, bias
|
||||
pass
|
||||
|
||||
active_adapter = proj.active_adapters[0] if \
|
||||
hasattr(proj, "active_adapters") else proj.active_adapter
|
||||
A = proj.lora_A[active_adapter].weight
|
||||
B = proj.lora_B[active_adapter].weight
|
||||
s = proj.scaling[active_adapter]
|
||||
return W, QUANT_STATE(W), A, B, s, bias
|
||||
|
||||
|
||||
pass
|
||||
|
||||
|
||||
def fast_dequantize(W, quant_state=None, out=None):
|
||||
if quant_state is None:
|
||||
return W
|
||||
if type(quant_state) is not list:
|
||||
# New quant_state as a class
|
||||
# https://github.com/TimDettmers/bitsandbytes/pull/763/files
|
||||
absmax = quant_state.absmax
|
||||
shape = quant_state.shape
|
||||
dtype = quant_state.dtype
|
||||
blocksize = quant_state.blocksize
|
||||
offset = quant_state.offset
|
||||
state2 = quant_state.state2
|
||||
absmax2 = state2.absmax
|
||||
code2 = state2.code
|
||||
blocksize2 = state2.blocksize
|
||||
else:
|
||||
# Old quant_state as a list of lists
|
||||
absmax, shape, dtype, blocksize, compressed_stats, _, _ = quant_state
|
||||
offset, state2 = compressed_stats
|
||||
absmax2, code2, blocksize2, _, _, _, _ = state2
|
||||
pass
|
||||
|
||||
# Create weight matrix
|
||||
if out is None:
|
||||
out = torch.empty(shape, dtype=dtype, device="cuda:0")
|
||||
else:
|
||||
assert (out.shape == shape)
|
||||
assert (out.dtype == dtype)
|
||||
|
||||
# NF4 dequantization of statistics
|
||||
n_elements_absmax = absmax.numel()
|
||||
out_absmax = torch.empty(
|
||||
n_elements_absmax, dtype=torch.float32, device="cuda:0")
|
||||
|
||||
# Do dequantization
|
||||
ptr_out_absmax = get_ptr(out_absmax)
|
||||
cdequantize_blockwise_fp32(
|
||||
get_ptr(code2), get_ptr(absmax), get_ptr(absmax2), ptr_out_absmax,
|
||||
ctypes.c_int(blocksize2), ctypes.c_int(n_elements_absmax)
|
||||
)
|
||||
out_absmax += offset
|
||||
|
||||
fx = cdequantize_blockwise_fp16_nf4 if dtype == torch.float16 else \
|
||||
cdequantize_blockwise_bf16_nf4
|
||||
fx(get_ptr(None), get_ptr(W), ptr_out_absmax, get_ptr(out),
|
||||
ctypes.c_int(blocksize), ctypes.c_int(out.numel()))
|
||||
|
||||
# Careful returning transposed data
|
||||
is_transposed = (True if W.shape[0] == 1 else False)
|
||||
return out.t() if is_transposed else out
|
||||
|
||||
|
||||
pass
|
||||
|
||||
|
||||
def matmul_lora(X, W, W_quant, A, B, s, out=None):
|
||||
dtype = X.dtype
|
||||
W = fast_dequantize(W.t(), W_quant)
|
||||
|
||||
if X.dim() == 3:
|
||||
batch, seq_len, d = X.shape
|
||||
X = X.view(-1, X.shape[-1])
|
||||
reshape = True
|
||||
else:
|
||||
reshape = False
|
||||
pass
|
||||
|
||||
out = torch.matmul(X, W, out=out)
|
||||
if W_quant is not None:
|
||||
del W
|
||||
|
||||
if A is not None:
|
||||
# LoRA is enabled
|
||||
A, B = A.t(), B.t()
|
||||
out += (X @ A.to(dtype)) @ (s * B.to(dtype))
|
||||
pass
|
||||
|
||||
return out.view(batch, seq_len, -1) if reshape else out
|
||||
|
||||
|
||||
pass
|
||||
45
ixformer_sdk/train/speedformer/layers/gpt2/attention.py
Normal file
45
ixformer_sdk/train/speedformer/layers/gpt2/attention.py
Normal file
@@ -0,0 +1,45 @@
|
||||
import torch
|
||||
import os
|
||||
from einops import rearrange
|
||||
from flash_attn import flash_attn_varlen_func
|
||||
|
||||
|
||||
@staticmethod
|
||||
def replace_flash_attn_forward(self, q, k, v, attention_mask, query_length, dropout=0.0, softmax_scale=None):
|
||||
|
||||
# flash-attn(ixdnn)存在gpt2(118M,338M,738M) shape没适配,只能采用普通版本
|
||||
assert os.getenv('ENABLE_FLASH_ATTENTION_WITH_IXDNN', "1") == '0', "flash-attn should not be use ixdnn version, please set variables" \
|
||||
" in shell \"export ENABLE_FLASH_ATTENTION_WITH_IXDNN=0 \" "
|
||||
assert all((i.dtype in [torch.float16, torch.bfloat16] for i in (q, k, v)))
|
||||
assert all((i.is_cuda for i in (q, k, v)))
|
||||
|
||||
batch_size, seqlen_q = q.shape[0], q.shape[1]
|
||||
seqlen_k = k.shape[1]
|
||||
|
||||
q, k, v = [rearrange(x, 'b s ... -> (b s) ...') for x in [q, k, v]]
|
||||
cu_seqlens_q = torch.arange(0, (batch_size + 1) * seqlen_q, step=seqlen_q, dtype=torch.int32,
|
||||
device=q.device)
|
||||
|
||||
if query_length != 1:
|
||||
# during training q,k,v always have same seqlen
|
||||
assert seqlen_k == seqlen_q
|
||||
|
||||
is_causal = self.is_causal
|
||||
cu_seqlens_k = cu_seqlens_q
|
||||
dropout_p = dropout
|
||||
else:
|
||||
# turn off FA causal mask after first inference autoregressive iteration
|
||||
# only on first autoregressive step q,k,v have same seqlen
|
||||
is_causal = seqlen_q == seqlen_k
|
||||
cu_seqlens_k = torch.arange(0, (batch_size + 1) * seqlen_k, step=seqlen_k, dtype=torch.int32,
|
||||
device=q.device)
|
||||
dropout_p = 0
|
||||
|
||||
output = flash_attn_varlen_func(
|
||||
q, k, v, cu_seqlens_q, cu_seqlens_k, seqlen_q, seqlen_k,
|
||||
dropout_p,
|
||||
softmax_scale=softmax_scale, causal=is_causal
|
||||
)
|
||||
# print(f"{output}")
|
||||
output = rearrange(output, '(b s) ... -> b s ...', b=batch_size)
|
||||
return output
|
||||
6
ixformer_sdk/train/speedformer/layers/lazy/__init__.py
Normal file
6
ixformer_sdk/train/speedformer/layers/lazy/__init__.py
Normal file
@@ -0,0 +1,6 @@
|
||||
from .lazy_init import LazyInitContext, LazyTensor
|
||||
|
||||
__all__ = [
|
||||
"LazyInitContext",
|
||||
"LazyTensor",
|
||||
]
|
||||
87
ixformer_sdk/train/speedformer/layers/lazy/construction.py
Normal file
87
ixformer_sdk/train/speedformer/layers/lazy/construction.py
Normal file
@@ -0,0 +1,87 @@
|
||||
from contextlib import contextmanager
|
||||
from typing import Callable, Dict, Tuple
|
||||
|
||||
import torch
|
||||
|
||||
__all__ = [
|
||||
"_LEGACY_TENSOR_CONSTRUCTOR",
|
||||
"_NO_META_FACTORY",
|
||||
"_NORMAL_FACTORY",
|
||||
"ConstructorManager",
|
||||
]
|
||||
|
||||
# reference: https://pytorch.org/cppdocs/notes/tensor_creation.html
|
||||
_NORMAL_FACTORY = [
|
||||
"arange",
|
||||
"full",
|
||||
"empty",
|
||||
"linspace",
|
||||
"logspace",
|
||||
"ones",
|
||||
"rand",
|
||||
"randn",
|
||||
"randint",
|
||||
"randperm",
|
||||
"zeros",
|
||||
"tensor",
|
||||
]
|
||||
|
||||
# factory function that does not support meta tensor backend
|
||||
_NO_META_FACTORY = [
|
||||
"eye",
|
||||
]
|
||||
|
||||
_LEGACY_TENSOR_CONSTRUCTOR = {
|
||||
"FloatTensor": torch.float,
|
||||
"DoubleTensor": torch.double,
|
||||
"HalfTensor": torch.half,
|
||||
"BFloat16Tensor": torch.bfloat16,
|
||||
"ByteTensor": torch.uint8,
|
||||
"CharTensor": torch.int8,
|
||||
"ShortTensor": torch.short,
|
||||
"IntTensor": torch.int,
|
||||
"LongTensor": torch.long,
|
||||
"BoolTensor": torch.bool,
|
||||
}
|
||||
|
||||
|
||||
class ConstructorManager:
|
||||
# function name: (new, old)
|
||||
overwrites: Dict[str, Tuple[Callable, Callable]] = {}
|
||||
changed: bool = False
|
||||
|
||||
@staticmethod
|
||||
def apply(overwrites: Dict[Callable, Callable]):
|
||||
ConstructorManager.overwrites.clear()
|
||||
ConstructorManager.overwrites.update(overwrites)
|
||||
ConstructorManager.redo()
|
||||
|
||||
@staticmethod
|
||||
def undo():
|
||||
assert ConstructorManager.changed, "No constructor change to undo"
|
||||
for name, (new, old) in ConstructorManager.overwrites.items():
|
||||
setattr(torch, name, old)
|
||||
ConstructorManager.changed = False
|
||||
|
||||
@staticmethod
|
||||
def redo():
|
||||
assert not ConstructorManager.changed, "Constructor already changed"
|
||||
for name, (new, old) in ConstructorManager.overwrites.items():
|
||||
setattr(torch, name, new)
|
||||
ConstructorManager.changed = True
|
||||
|
||||
@staticmethod
|
||||
@contextmanager
|
||||
def disable():
|
||||
enabled = ConstructorManager.changed
|
||||
if enabled:
|
||||
ConstructorManager.undo()
|
||||
yield
|
||||
if enabled:
|
||||
ConstructorManager.redo()
|
||||
|
||||
@staticmethod
|
||||
def clear():
|
||||
if ConstructorManager.changed:
|
||||
ConstructorManager.undo()
|
||||
ConstructorManager.overwrites.clear()
|
||||
669
ixformer_sdk/train/speedformer/layers/lazy/lazy_init.py
Normal file
669
ixformer_sdk/train/speedformer/layers/lazy/lazy_init.py
Normal file
@@ -0,0 +1,669 @@
|
||||
from types import MethodType
|
||||
from typing import Callable, Optional, Union
|
||||
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
from packaging import version
|
||||
from torch import Tensor
|
||||
from torch.nn import Parameter
|
||||
from torch.utils._pytree import tree_map
|
||||
|
||||
from ixformer.train.speedformer.layers.lazy.construction import ConstructorManager
|
||||
from ixformer.train.speedformer.layers.lazy.pretrained import PretrainedManager
|
||||
|
||||
# reference: https://pytorch.org/cppdocs/notes/tensor_creation.html
|
||||
_NORMAL_FACTORY = [
|
||||
"arange",
|
||||
"full",
|
||||
"empty",
|
||||
"linspace",
|
||||
"logspace",
|
||||
"ones",
|
||||
"rand",
|
||||
"randn",
|
||||
"randint",
|
||||
"randperm",
|
||||
"zeros",
|
||||
"tensor",
|
||||
]
|
||||
|
||||
# factory function that does not support meta tensor backend
|
||||
_NO_META_FACTORY = [
|
||||
"eye",
|
||||
]
|
||||
|
||||
_EARLY_MATERIALIZED_OPS = ["__getitem__", "split"]
|
||||
|
||||
# If your intent is to change the metadata of a Tensor (such as sizes / strides / storage / storage_offset)
|
||||
# without autograd tracking the change, remove the .data / .detach() call and wrap the change in a `with torch.no_grad():` block.
|
||||
# These ops cannot be unwrapped using .data
|
||||
_CHANGE_META_OPS = ["_cudnn_rnn_flatten_weight",
|
||||
"requires_grad_", "__get__", "__set__", "numel", "size", "dim"]
|
||||
|
||||
# These ops is not related to tensor value and should not be rerun
|
||||
_NO_RERUN_OPS = ["__get__", "numel", "size", "dim"]
|
||||
|
||||
_LEGACY_TENSOR_CONSTRUCTOR = {
|
||||
"FloatTensor": torch.float,
|
||||
"DoubleTensor": torch.double,
|
||||
"HalfTensor": torch.half,
|
||||
"BFloat16Tensor": torch.bfloat16,
|
||||
"ByteTensor": torch.uint8,
|
||||
"CharTensor": torch.int8,
|
||||
"ShortTensor": torch.short,
|
||||
"IntTensor": torch.int,
|
||||
"LongTensor": torch.long,
|
||||
"BoolTensor": torch.bool,
|
||||
}
|
||||
|
||||
# These ops have at least one lazy tensor argument and maybe a scalar argument
|
||||
# scalar value should be converted to meta tensor
|
||||
# this is a hack for torch 2.0
|
||||
_EXPAND_SCALAR_OPS = [
|
||||
"where",
|
||||
"clamp",
|
||||
"clamp_min",
|
||||
"clamp_max",
|
||||
"clamp_",
|
||||
"clamp_min_",
|
||||
"clamp_max_",
|
||||
]
|
||||
_old_tensor_factory = torch.tensor
|
||||
|
||||
_EMPTY_DATA = torch.empty(0)
|
||||
|
||||
|
||||
class _MyTensor(Tensor):
|
||||
"""This class is only for correctness verification."""
|
||||
|
||||
_pre_op_fn: Callable[["LazyTensor"], None] = lambda *args: None
|
||||
|
||||
default_device: Optional[torch.device] = None
|
||||
|
||||
def __new__(cls, func, *args, concrete_data=None, **kwargs) -> "_MyTensor":
|
||||
cls._pre_op_fn()
|
||||
if concrete_data is not None:
|
||||
# uniform api as LazyTensor
|
||||
data = concrete_data
|
||||
else:
|
||||
kwargs["device"] = cls.default_device
|
||||
data = func(*args, **kwargs)
|
||||
return Tensor._make_subclass(cls, data, require_grad=data.requires_grad)
|
||||
|
||||
@classmethod
|
||||
def __torch_function__(cls, func, types, args=(), kwargs=None):
|
||||
cls._pre_op_fn()
|
||||
return super().__torch_function__(func, types, args, kwargs)
|
||||
|
||||
|
||||
def _data_tolist(tensor: torch.Tensor) -> list:
|
||||
"""tolist() method is not allowed for a subclass of tensor. Tensor.data returns a Tensor."""
|
||||
return tensor.data.tolist()
|
||||
|
||||
|
||||
def _convert_cls(tensor: "LazyTensor", target: torch.Tensor) -> torch.Tensor:
|
||||
"""Convert a lazy tensor's class to target's class, with target's data.
|
||||
|
||||
The reason why we change the class of a lazy tensor in-place is that this can easily handle shared modules/parameters, which is common in huggingface models.
|
||||
If we create a new tensor and update the module by ``setattr(module, name, param)``, the shared parameters will not be updated. And we have to track all shared parameters and update them manually.
|
||||
|
||||
Args:
|
||||
tensor (LazyTensor): the LazyTensor to be converted
|
||||
target (torch.Tensor): target tensor
|
||||
|
||||
Returns:
|
||||
torch.Tensor: the converted tensor
|
||||
"""
|
||||
cls_to_become = Parameter if isinstance(
|
||||
tensor, Parameter) else torch.Tensor
|
||||
tensor.__class__ = cls_to_become
|
||||
if cls_to_become is Parameter:
|
||||
# to fit UninitializedParameter
|
||||
delattr(tensor, "_is_param")
|
||||
tensor.data = target
|
||||
tensor.requires_grad = target.requires_grad
|
||||
# subclass of torch.Tensor does not have tolist() method
|
||||
# overwrite this method after materialization or distribution
|
||||
tensor.tolist = MethodType(_data_tolist, tensor)
|
||||
return tensor
|
||||
|
||||
|
||||
class LazyTensor(torch.Tensor):
|
||||
"""A naive implementation of LazyTensor (https://arxiv.org/pdf/2102.13267.pdf).
|
||||
|
||||
Usage:
|
||||
1. Use ``LazyTensor`` instead of ``torch.Tensor``.
|
||||
>>> x = LazyTensor(torch.zeros, 2, 3)
|
||||
>>> x += 1
|
||||
>>> y = x * x
|
||||
>>> y = y.cuda().half()
|
||||
>>> y[0, 0] = 0
|
||||
>>> y = y.materialize() # materialize the tensor
|
||||
>>> print(y)
|
||||
tensor([[0., 1., 1.],
|
||||
[1., 1., 1.]], device='cuda:0', dtype=torch.float16)
|
||||
|
||||
Warnings:
|
||||
1. Cases that ``LazyTensor`` can't deal with.
|
||||
>>> x = LazyTensor(torch.ones, 2, 3)
|
||||
>>> x[0, 0] = -x[0, 0] # this will cause infinite recursion
|
||||
>>> y = x.clone()
|
||||
>>> x.add_(1) # modifying origin tensor after cloning leads to wrong materialization
|
||||
>>> z = x.tolist()
|
||||
>>> x.zeros_() # modifying origin tensor after cloning tolist is not allowed
|
||||
>>> nn.utils.weight_norm(self.conv, name="weight", dim=2) # applying weight norm on a lazy tensor is not allowed
|
||||
|
||||
|
||||
2. Cases that ``LazyTensor`` becomes eager (early materialization).
|
||||
>>> b = a[:, 2:] # get a slice of a lazy tensor triggers early materialization
|
||||
>>> chunks = a.split(3) # this also triggers early materialization
|
||||
>>> x.data = torch.rand(2, 3) # directly setting data of a lazy tensor triggers early materialization
|
||||
|
||||
"""
|
||||
|
||||
_repr = True
|
||||
_meta_data: Optional[torch.Tensor] = None # shape, dtype, device
|
||||
_pre_op_fn: Callable[["LazyTensor"], None] = lambda *args: None
|
||||
|
||||
default_device: Optional[torch.device] = None
|
||||
_device: torch.device # fake device of mate tensor
|
||||
|
||||
@staticmethod
|
||||
def __new__(cls, func, *args, meta_data=None, concrete_data=None, **kwargs):
|
||||
# tips for torch 2.0:
|
||||
# torch 2.0 disables torch dispatch for subclass of tensor
|
||||
# MetaTensor is cannot be used
|
||||
# Now lazy tensor contains device injection and meta tensor
|
||||
if concrete_data is not None:
|
||||
# some ops don't support meta backend and should have concrete data
|
||||
elem = concrete_data
|
||||
else:
|
||||
if meta_data is None:
|
||||
with ConstructorManager.disable():
|
||||
# to disable create lazy tensor in inner ops, this is a hack for torch 2.0
|
||||
meta_data = func(*args, **{**kwargs, "device": "meta"})
|
||||
elem = meta_data
|
||||
# As a meta tensor cannot be modified __class__ to torch.Tensor, we should use an empty real tensor here
|
||||
r = torch.Tensor._make_subclass(
|
||||
cls, _EMPTY_DATA, require_grad=elem.requires_grad)
|
||||
r._meta_data = meta_data
|
||||
|
||||
return r
|
||||
|
||||
def __init__(self, func, *args, meta_data=None, concrete_data=None, **kwargs):
|
||||
self._device = torch.device(kwargs.get("device", None) or "cpu")
|
||||
if func.__name__ in _NORMAL_FACTORY:
|
||||
kwargs = {**kwargs, "device": LazyTensor.default_device}
|
||||
self._factory_method = (func, args, kwargs) # (func, args, kwargs)
|
||||
self._op_buffer = [] # (func, args, kwargs, replace)
|
||||
# materialized data
|
||||
self._materialized_data: Optional[torch.Tensor] = concrete_data
|
||||
|
||||
@property
|
||||
def device(self) -> torch.device:
|
||||
return self._materialized_data.device if self._materialized_data is not None else self._device
|
||||
|
||||
def __repr__(self):
|
||||
return f"LazyTensor(..., size={tuple(self.shape)}, device='{self.device}', dtype={self.dtype})"
|
||||
|
||||
def materialize(self) -> torch.Tensor:
|
||||
"""Materialize the ``LazyTensor`` to ``torch.Tensor`` by modifying __class__ (inplace).
|
||||
|
||||
Returns:
|
||||
torch.Tensor: The materialized tensor (self).
|
||||
"""
|
||||
target = self._materialize_data()
|
||||
self.clean()
|
||||
return _convert_cls(self, target)
|
||||
|
||||
def clean(self) -> None:
|
||||
"""Clean all stored operations, meta data and materialized data, which prevents memory leaking. This should be called after all tensors are materialized."""
|
||||
delattr(self, "_factory_method")
|
||||
delattr(self, "_op_buffer")
|
||||
delattr(self, "_materialized_data")
|
||||
delattr(self, "_meta_data")
|
||||
|
||||
@staticmethod
|
||||
def _replace_with_materialized(x):
|
||||
if isinstance(x, LazyTensor):
|
||||
return x._materialize_data()
|
||||
return x
|
||||
|
||||
def _materialize_data(self) -> torch.Tensor:
|
||||
# self._materialized_data should be generated after the first call of this function
|
||||
if self._materialized_data is None:
|
||||
# apply factory method
|
||||
func, args, kwargs = self._factory_method
|
||||
# apply cached sequence
|
||||
self._pre_op_fn()
|
||||
|
||||
init_val = func(
|
||||
*tree_map(self._replace_with_materialized, args), **tree_map(self._replace_with_materialized, kwargs)
|
||||
)
|
||||
|
||||
self._materialized_data = self._rerun_ops(init_val)
|
||||
return self._materialized_data
|
||||
|
||||
def _rerun_ops(self, target=None) -> torch.Tensor:
|
||||
"""Do lazy execution by rerunning all (stored) related operations.
|
||||
|
||||
Args:
|
||||
target (torc.Tensor, optional): Intial value of the target tensor (self). Defaults to None.
|
||||
"""
|
||||
|
||||
def replace(x):
|
||||
if x is self:
|
||||
return target
|
||||
elif isinstance(x, LazyTensor):
|
||||
return x._materialize_data()
|
||||
return x
|
||||
|
||||
packed = None
|
||||
|
||||
for func, args, kwargs in self._op_buffer:
|
||||
if func == torch.Tensor.requires_grad_:
|
||||
packed = func, args, kwargs # requires grad should be set at last
|
||||
else:
|
||||
self._pre_op_fn()
|
||||
o = func(*tree_map(replace, args), **tree_map(replace, kwargs))
|
||||
# if func returns non-Tensor, discard the value
|
||||
target = o if isinstance(o, torch.Tensor) else target
|
||||
|
||||
# super-dainiu: set requires_grad after all inplace-ops are done
|
||||
if packed is not None:
|
||||
func, args, kwargs = packed
|
||||
func(*tree_map(replace, args), **tree_map(replace, kwargs))
|
||||
|
||||
return target
|
||||
|
||||
# cache everything with __torch_function__
|
||||
|
||||
@classmethod
|
||||
def __torch_function__(cls, func, types, args=(), kwargs=None):
|
||||
if kwargs is None:
|
||||
kwargs = {}
|
||||
if func.__name__ in _EARLY_MATERIALIZED_OPS:
|
||||
# These OPs cannot be lazy and related tensors should be early materialized
|
||||
tree_map(cls._replace_with_materialized, args)
|
||||
tree_map(cls._replace_with_materialized, kwargs)
|
||||
is_inplace: bool = (
|
||||
func.__name__.endswith("_")
|
||||
and not (func.__name__.endswith("__"))
|
||||
or func.__name__ in ("__setitem__", "__set__")
|
||||
)
|
||||
|
||||
is_change_meta_op: bool = func.__name__ in _CHANGE_META_OPS
|
||||
|
||||
if isinstance(func, torch._C.ScriptMethod):
|
||||
# FIXME(ver217): torch script functions are not verified
|
||||
|
||||
target = None
|
||||
|
||||
def unwrap(x):
|
||||
if isinstance(x, LazyTensor):
|
||||
return x._meta_data
|
||||
return x
|
||||
|
||||
target: LazyTensor = args[0].clone()
|
||||
target._op_buffer.append((func, args, kwargs))
|
||||
target._meta_data = getattr(target._meta_data, func.name)(
|
||||
*tree_map(unwrap, args[1:]), **tree_map(unwrap, kwargs)
|
||||
)
|
||||
return target
|
||||
else:
|
||||
meta_to_lazy = {}
|
||||
|
||||
def unwrap(x):
|
||||
if isinstance(x, LazyTensor):
|
||||
if x._materialized_data is not None:
|
||||
# for early materialized tensor, use its materialized data directly
|
||||
return x._materialized_data if is_change_meta_op else x._materialized_data.data
|
||||
t = x if is_inplace else x.clone()
|
||||
if func.__name__ not in _NO_RERUN_OPS:
|
||||
t._op_buffer.append((func, args, kwargs))
|
||||
meta = x._meta_data if is_change_meta_op else x._meta_data.data
|
||||
meta_to_lazy[meta] = t
|
||||
return meta
|
||||
elif (
|
||||
version.parse(torch.__version__) >= version.parse("2.0.0")
|
||||
and func.__name__ in _EXPAND_SCALAR_OPS
|
||||
and not isinstance(x, torch.Tensor)
|
||||
):
|
||||
return _old_tensor_factory(x, device="meta")
|
||||
return x
|
||||
|
||||
def wrap(y, i=None):
|
||||
if isinstance(y, torch.Tensor):
|
||||
if y.is_meta:
|
||||
if y in meta_to_lazy:
|
||||
# inplace op, just return origin lazy tensor
|
||||
return meta_to_lazy[y]
|
||||
else:
|
||||
# out of place op, create new lazy tensor
|
||||
fn = lambda *a, **kw: func(*a, **
|
||||
kw) if i is None else func(*a, **kw)[i]
|
||||
fn.__name__ = func.__name__
|
||||
lazy_y = LazyTensor(
|
||||
fn, *args, meta_data=y, **kwargs)
|
||||
return lazy_y
|
||||
else:
|
||||
# for early materialized tensor
|
||||
return LazyTensor(lambda: None, concrete_data=y)
|
||||
return y
|
||||
|
||||
cls._pre_op_fn()
|
||||
with ConstructorManager.disable():
|
||||
# to disable create lazy tensor in inner ops, this is a hack for torch 2.0
|
||||
o = func(*tree_map(unwrap, args), **tree_map(unwrap, kwargs))
|
||||
if isinstance(o, (tuple, list)):
|
||||
return type(o)(wrap(y, i=i) for i, y in enumerate(o))
|
||||
return wrap(o)
|
||||
|
||||
def to(self, *args, **kwargs) -> torch.Tensor:
|
||||
if self._materialized_data is not None:
|
||||
return LazyTensor(lambda: None, concrete_data=self._materialized_data.to(*args, **kwargs))
|
||||
|
||||
device = None
|
||||
|
||||
def replace(x):
|
||||
nonlocal device
|
||||
if isinstance(x, (str, int, torch.device)) and not isinstance(x, bool):
|
||||
device = x
|
||||
return torch.device("meta")
|
||||
return x
|
||||
|
||||
meta_data = self._meta_data.to(
|
||||
*tree_map(replace, args), **tree_map(replace, kwargs))
|
||||
|
||||
if meta_data is self._meta_data and device == self.device:
|
||||
return self
|
||||
|
||||
def factory_fn(t: torch.Tensor, **kw):
|
||||
return t.to(*args, **kwargs)
|
||||
|
||||
return LazyTensor(factory_fn, self, meta_data=meta_data, device=device)
|
||||
|
||||
def cpu(self, memory_format: torch.memory_format = torch.preserve_format):
|
||||
return self.to(device=torch.device("cpu"), memory_format=memory_format)
|
||||
|
||||
def cuda(self, device=None, non_blocking=False, memory_format: torch.memory_format = torch.preserve_format):
|
||||
device = torch.device(device or "cuda")
|
||||
return self.to(device=device, non_blocking=non_blocking, memory_format=memory_format)
|
||||
|
||||
def clone(self) -> "LazyTensor":
|
||||
def factory_fn(t: torch.Tensor, **kw):
|
||||
# if self is materialized, return self
|
||||
return t.clone()
|
||||
|
||||
target = LazyTensor(factory_fn, self, meta_data=self._meta_data)
|
||||
|
||||
return target
|
||||
|
||||
def detach(self) -> Tensor:
|
||||
return self
|
||||
|
||||
def __deepcopy__(self, memo):
|
||||
if not self.is_leaf:
|
||||
raise RuntimeError(
|
||||
"Only Tensors created explicitly by the user "
|
||||
"(graph leaves) support the deepcopy protocol at the moment"
|
||||
)
|
||||
if id(self) in memo:
|
||||
return memo[id(self)]
|
||||
|
||||
def factory_fn(t: torch.Tensor, **kw):
|
||||
# if self is materialized, return self
|
||||
return _copy_tensor(t, t.requires_grad)
|
||||
|
||||
if self._materialized_data is not None:
|
||||
# self is early materialized
|
||||
copied = _copy_tensor(self._materialized_data, self.requires_grad)
|
||||
target = LazyTensor(lambda: None, concrete_data=copied)
|
||||
else:
|
||||
target = LazyTensor(factory_fn, self, meta_data=self._meta_data)
|
||||
|
||||
if isinstance(self, Parameter):
|
||||
# hack isinstance check of parameter
|
||||
target._is_param = True
|
||||
|
||||
memo[id(self)] = target
|
||||
return target
|
||||
|
||||
@property
|
||||
def data(self):
|
||||
return self
|
||||
|
||||
@data.setter
|
||||
def data(self, other: "LazyTensor"):
|
||||
"""This is sightly different from oringinal `data` setter.
|
||||
|
||||
E.g.:
|
||||
>>> a = torch.randn(3, 3) # a is a Tensor
|
||||
>>> b = torch.rand(2, 2)
|
||||
>>> a.data = b
|
||||
>>> b.add_(1) # this will affect a
|
||||
>>> x = torch.randn(3, 3) # x is a LazyTensor
|
||||
>>> y = torch.rand(2, 2) # y is a LazyTensor
|
||||
>>> x.data = y
|
||||
>>> y.add_(1) # this will not affect x
|
||||
|
||||
"""
|
||||
if other is self:
|
||||
return
|
||||
|
||||
def replace(x):
|
||||
if x is other:
|
||||
return self
|
||||
return x
|
||||
|
||||
for func, args, kwargs in [other._factory_method, *other._op_buffer]:
|
||||
self._op_buffer.append(
|
||||
(func, tree_map(replace, args), tree_map(replace, kwargs)))
|
||||
|
||||
def tolist(self) -> list:
|
||||
# Though self.__class__ is modified to torch.Tensor, in C++ side, it is still a subclass of torch.Tensor
|
||||
# And subclass of torch.Tensor does not have tolist() method
|
||||
t = self._materialize_data()
|
||||
return t.tolist()
|
||||
|
||||
def __hash__(self):
|
||||
return id(self)
|
||||
|
||||
def __rpow__(self, other):
|
||||
dtype = torch.result_type(self, other)
|
||||
return torch.tensor(other, dtype=dtype, device=self.device) ** self
|
||||
|
||||
|
||||
class LazyInitContext:
|
||||
"""Context manager for lazy initialization. Enables initializing the model without allocating real memory.
|
||||
|
||||
Args:
|
||||
tensor_cls (Union[_MyTensor, LazyTensor], optional): This is only for test. Defaults to LazyTensor.
|
||||
default_device (Optional[Union[torch.device, str, int]], optional): Defalt device for initialization.
|
||||
If it's cuda, initilization will be accelerated, but cuda memory will be allocated. By default, it's cpu.
|
||||
Defaults to None.
|
||||
"""
|
||||
|
||||
_replaced: bool = False
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
tensor_cls: Union[_MyTensor, LazyTensor] = LazyTensor,
|
||||
default_device: Optional[Union[torch.device, str, int]] = None,
|
||||
):
|
||||
assert tensor_cls is LazyTensor or tensor_cls is _MyTensor
|
||||
self.tensor_cls = tensor_cls
|
||||
self.old_default_device = LazyTensor.default_device
|
||||
self.default_device = default_device
|
||||
|
||||
def __enter__(self):
|
||||
if LazyInitContext._replaced:
|
||||
raise RuntimeError(f"LazyInitContext is not reentrant")
|
||||
LazyInitContext._replaced = True
|
||||
self.old_default_device = self.tensor_cls.default_device
|
||||
self.tensor_cls.default_device = self.default_device
|
||||
|
||||
def wrap_factory_method(target):
|
||||
# factory functions (eg. torch.empty())
|
||||
def wrapper(*args, **kwargs):
|
||||
return self.tensor_cls(target, *args, **kwargs)
|
||||
|
||||
return wrapper, target
|
||||
|
||||
def wrap_factory_like_method(orig_target, target):
|
||||
# factory_like functions (eg. torch.empty_like())
|
||||
def wrapper(*args, **kwargs):
|
||||
orig_t = args[0]
|
||||
return self.tensor_cls(
|
||||
orig_target, *orig_t.shape, *args[1:], device=orig_t.device, dtype=orig_t.dtype, **kwargs
|
||||
)
|
||||
|
||||
return wrapper, target
|
||||
|
||||
def wrap_legacy_constructor(target, dtype):
|
||||
# legacy constructor (e.g. torch.LongTensor())
|
||||
def wrapper(*args, **kwargs):
|
||||
if len(args) == 1 and isinstance(args[0], torch.Tensor):
|
||||
# (Tensor other)
|
||||
return args[0]
|
||||
elif len(args) == 1:
|
||||
# (object data, *, torch.device device)
|
||||
kwargs = {**kwargs, "dtype": dtype}
|
||||
replaced, orig = self.overrides["tensor"]
|
||||
return replaced(*args, **kwargs)
|
||||
elif _is_int_tuple(args):
|
||||
# (tuple of ints size, *, torch.device device)
|
||||
kwargs = {**kwargs, "dtype": dtype}
|
||||
replaced, orig = self.overrides["empty"]
|
||||
return replaced(*args, **kwargs)
|
||||
else:
|
||||
raise TypeError(
|
||||
f"new() received an invalid combination of arguments - got {tuple(type(x) for x in args)}, but expected one of:\n * (Tensor other)\n * (tuple of ints size, *, torch.device device)\n * (object data, *, torch.device device)"
|
||||
)
|
||||
|
||||
return wrapper, target
|
||||
|
||||
def wrap_no_meta_factory(target):
|
||||
# factory functions which don't support meta tensor backend
|
||||
def wrapper(*args, **kwargs):
|
||||
tensor = target(*args, **kwargs)
|
||||
return self.tensor_cls(lambda: None, concrete_data=tensor)
|
||||
|
||||
return wrapper, target
|
||||
|
||||
overrides = {
|
||||
target: wrap_factory_method(getattr(torch, target))
|
||||
for target in _NORMAL_FACTORY
|
||||
if callable(getattr(torch, target, None))
|
||||
}
|
||||
|
||||
overrides.update(
|
||||
{
|
||||
target + "_like": wrap_factory_like_method(getattr(torch, target), getattr(torch, target + "_like"))
|
||||
for target in _NORMAL_FACTORY
|
||||
if callable(getattr(torch, target + "_like", None))
|
||||
}
|
||||
)
|
||||
|
||||
overrides.update(
|
||||
{
|
||||
target: wrap_legacy_constructor(getattr(torch, target), dtype)
|
||||
for target, dtype in _LEGACY_TENSOR_CONSTRUCTOR.items()
|
||||
if callable(getattr(torch, target, None))
|
||||
}
|
||||
)
|
||||
|
||||
overrides.update(
|
||||
{
|
||||
target: wrap_no_meta_factory(getattr(torch, target))
|
||||
for target in _NO_META_FACTORY
|
||||
if callable(getattr(torch, target, None))
|
||||
}
|
||||
)
|
||||
|
||||
ConstructorManager.apply(overrides)
|
||||
PretrainedManager.inject()
|
||||
|
||||
def __exit__(self, exc_type, exc_val, exc_tb):
|
||||
self.tensor_cls.default_device = self.old_default_device
|
||||
LazyInitContext._replaced = False
|
||||
ConstructorManager.clear()
|
||||
PretrainedManager.recover()
|
||||
|
||||
@staticmethod
|
||||
def materialize(module: nn.Module, verbose: bool = False) -> nn.Module:
|
||||
"""Initialize all ``Parameter`` from ``LazyTensor``. This function will modify the module in-place.
|
||||
|
||||
Args:
|
||||
module (nn.Module): Target ``nn.Module``
|
||||
verbose (bool): Whether to print lazy initialization rate. Defaults to False.
|
||||
"""
|
||||
|
||||
def apply_fn(name: str, p: LazyTensor):
|
||||
p.materialize()
|
||||
|
||||
return _apply_to_lazy_module(module, apply_fn, verbose)
|
||||
|
||||
|
||||
def _apply_to_lazy_module(
|
||||
module: nn.Module, apply_fn: Callable[[str, torch.Tensor], None], verbose: bool = False
|
||||
) -> nn.Module:
|
||||
if verbose:
|
||||
# verbose info
|
||||
param_cnt = 0
|
||||
param_lazy_cnt = 0
|
||||
buf_cnt = 0
|
||||
buf_lazy_cnt = 0
|
||||
total_numel = 0
|
||||
non_lazy_numel = 0
|
||||
|
||||
for name, p in module.named_parameters():
|
||||
if verbose:
|
||||
param_cnt += 1
|
||||
total_numel += p.numel()
|
||||
if getattr(p, "_materialized_data", False) is None:
|
||||
# if no _materialized_data attr, the tensor is not lazy
|
||||
param_lazy_cnt += 1
|
||||
else:
|
||||
non_lazy_numel += p.numel()
|
||||
if isinstance(p, LazyTensor):
|
||||
apply_fn(name, p)
|
||||
|
||||
for name, buf in module.named_buffers():
|
||||
if verbose:
|
||||
buf_cnt += 1
|
||||
total_numel += buf.numel()
|
||||
if getattr(buf, "_materialized_data", False) is None:
|
||||
# if no _materialized_data attr, the tensor is not lazy
|
||||
buf_lazy_cnt += 1
|
||||
else:
|
||||
non_lazy_numel += buf.numel()
|
||||
if isinstance(buf, LazyTensor):
|
||||
apply_fn(name, buf)
|
||||
|
||||
# if verbose:
|
||||
# non_lazy_numel_ratio = non_lazy_numel / total_numel * 100 if non_lazy_numel != 0 else 0
|
||||
# logger = get_dist_logger()
|
||||
# logger.info(f"Param lazy rate: {param_lazy_cnt}/{param_cnt}", ranks=[0])
|
||||
# logger.info(f"Buffer lazy rate: {buf_lazy_cnt}/{buf_cnt}", ranks=[0])
|
||||
# logger.info(
|
||||
# f"Non lazy numel: {non_lazy_numel} ({non_lazy_numel/1024**2:.3f} M), ratio: {non_lazy_numel_ratio}%",
|
||||
# ranks=[0],
|
||||
# )
|
||||
|
||||
return module
|
||||
|
||||
|
||||
def _is_int_tuple(args) -> bool:
|
||||
if not isinstance(args, tuple):
|
||||
return False
|
||||
for x in args:
|
||||
if not isinstance(x, int):
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def _copy_tensor(tensor: Tensor, requires_grad: bool) -> Tensor:
|
||||
copied = tensor.data.clone()
|
||||
copied.requires_grad = requires_grad
|
||||
return copied
|
||||
318
ixformer_sdk/train/speedformer/layers/lazy/pretrained.py
Normal file
318
ixformer_sdk/train/speedformer/layers/lazy/pretrained.py
Normal file
@@ -0,0 +1,318 @@
|
||||
import os
|
||||
from typing import Callable, Optional, Union
|
||||
|
||||
import torch
|
||||
from torch.nn import Module
|
||||
|
||||
|
||||
class PretrainedManager:
|
||||
old_from_pretrained: Optional[Callable] = None
|
||||
|
||||
@staticmethod
|
||||
def inject() -> None:
|
||||
try:
|
||||
from transformers.modeling_utils import PreTrainedModel
|
||||
except ImportError:
|
||||
return
|
||||
# recover bound method to plain function
|
||||
PretrainedManager.old_from_pretrained = PreTrainedModel.from_pretrained.__func__
|
||||
PreTrainedModel.from_pretrained = new_from_pretrained
|
||||
|
||||
@staticmethod
|
||||
def recover() -> None:
|
||||
try:
|
||||
from transformers.modeling_utils import PreTrainedModel
|
||||
except ImportError:
|
||||
return
|
||||
# convert plain function to class method
|
||||
PreTrainedModel.from_pretrained = classmethod(
|
||||
PretrainedManager.old_from_pretrained)
|
||||
PretrainedManager.old_from_pretrained = None
|
||||
|
||||
|
||||
@classmethod
|
||||
def new_from_pretrained(
|
||||
cls, pretrained_model_name_or_path: Optional[Union[str, os.PathLike]], *model_args, **kwargs
|
||||
) -> Module:
|
||||
from transformers import GenerationConfig
|
||||
from transformers.configuration_utils import PretrainedConfig
|
||||
from transformers.modeling_utils import (
|
||||
ContextManagers,
|
||||
_add_variant,
|
||||
cached_file,
|
||||
download_url,
|
||||
has_file,
|
||||
is_offline_mode,
|
||||
is_remote_url,
|
||||
no_init_weights,
|
||||
)
|
||||
from transformers.utils import (
|
||||
SAFE_WEIGHTS_INDEX_NAME,
|
||||
SAFE_WEIGHTS_NAME,
|
||||
WEIGHTS_INDEX_NAME,
|
||||
WEIGHTS_NAME,
|
||||
is_safetensors_available,
|
||||
logging,
|
||||
)
|
||||
|
||||
logger = logging.get_logger(__name__)
|
||||
|
||||
config = kwargs.pop("config", None)
|
||||
cache_dir = kwargs.pop("cache_dir", None)
|
||||
force_download = kwargs.pop("force_download", False)
|
||||
resume_download = kwargs.pop("resume_download", False)
|
||||
proxies = kwargs.pop("proxies", None)
|
||||
local_files_only = kwargs.pop("local_files_only", False)
|
||||
use_auth_token = kwargs.pop("use_auth_token", None)
|
||||
revision = kwargs.pop("revision", None)
|
||||
_ = kwargs.pop("mirror", None)
|
||||
from_pipeline = kwargs.pop("_from_pipeline", None)
|
||||
from_auto_class = kwargs.pop("_from_auto", False)
|
||||
_fast_init = kwargs.pop("_fast_init", True)
|
||||
torch_dtype = kwargs.pop("torch_dtype", None)
|
||||
subfolder = kwargs.pop("subfolder", "")
|
||||
commit_hash = kwargs.pop("_commit_hash", None)
|
||||
variant = kwargs.pop("variant", None)
|
||||
use_safetensors = kwargs.pop(
|
||||
"use_safetensors", None if is_safetensors_available() else False)
|
||||
|
||||
if len(kwargs) > 0:
|
||||
logger.warning(f"Below kwargs may be ignored: {list(kwargs.keys())}")
|
||||
|
||||
from_pt = True
|
||||
|
||||
user_agent = {"file_type": "model", "framework": "pytorch",
|
||||
"from_auto_class": from_auto_class}
|
||||
if from_pipeline is not None:
|
||||
user_agent["using_pipeline"] = from_pipeline
|
||||
|
||||
if is_offline_mode() and not local_files_only:
|
||||
logger.info("Offline mode: forcing local_files_only=True")
|
||||
local_files_only = True
|
||||
|
||||
# Load config if we don't provide a configuration
|
||||
if not isinstance(config, PretrainedConfig):
|
||||
config_path = config if config is not None else pretrained_model_name_or_path
|
||||
config, model_kwargs = cls.config_class.from_pretrained(
|
||||
config_path,
|
||||
cache_dir=cache_dir,
|
||||
return_unused_kwargs=True,
|
||||
force_download=force_download,
|
||||
resume_download=resume_download,
|
||||
proxies=proxies,
|
||||
local_files_only=local_files_only,
|
||||
use_auth_token=use_auth_token,
|
||||
revision=revision,
|
||||
subfolder=subfolder,
|
||||
_from_auto=from_auto_class,
|
||||
_from_pipeline=from_pipeline,
|
||||
**kwargs,
|
||||
)
|
||||
else:
|
||||
model_kwargs = kwargs
|
||||
|
||||
if commit_hash is None:
|
||||
commit_hash = getattr(config, "_commit_hash", None)
|
||||
|
||||
# This variable will flag if we're loading a sharded checkpoint. In this case the archive file is just the
|
||||
# index of the files.
|
||||
|
||||
if pretrained_model_name_or_path is not None:
|
||||
pretrained_model_name_or_path = str(pretrained_model_name_or_path)
|
||||
is_local = os.path.isdir(pretrained_model_name_or_path)
|
||||
if is_local:
|
||||
if use_safetensors is not False and os.path.isfile(
|
||||
os.path.join(pretrained_model_name_or_path, subfolder,
|
||||
_add_variant(SAFE_WEIGHTS_NAME, variant))
|
||||
):
|
||||
# Load from a safetensors checkpoint
|
||||
archive_file = os.path.join(
|
||||
pretrained_model_name_or_path, subfolder, _add_variant(
|
||||
SAFE_WEIGHTS_NAME, variant)
|
||||
)
|
||||
elif use_safetensors is not False and os.path.isfile(
|
||||
os.path.join(pretrained_model_name_or_path, subfolder,
|
||||
_add_variant(SAFE_WEIGHTS_INDEX_NAME, variant))
|
||||
):
|
||||
# Load from a sharded safetensors checkpoint
|
||||
archive_file = os.path.join(
|
||||
pretrained_model_name_or_path, subfolder, _add_variant(
|
||||
SAFE_WEIGHTS_INDEX_NAME, variant)
|
||||
)
|
||||
elif os.path.isfile(
|
||||
os.path.join(pretrained_model_name_or_path,
|
||||
subfolder, _add_variant(WEIGHTS_NAME, variant))
|
||||
):
|
||||
# Load from a PyTorch checkpoint
|
||||
archive_file = os.path.join(
|
||||
pretrained_model_name_or_path, subfolder, _add_variant(
|
||||
WEIGHTS_NAME, variant)
|
||||
)
|
||||
elif os.path.isfile(
|
||||
os.path.join(pretrained_model_name_or_path, subfolder,
|
||||
_add_variant(WEIGHTS_INDEX_NAME, variant))
|
||||
):
|
||||
# Load from a sharded PyTorch checkpoint
|
||||
archive_file = os.path.join(
|
||||
pretrained_model_name_or_path, subfolder, _add_variant(
|
||||
WEIGHTS_INDEX_NAME, variant)
|
||||
)
|
||||
else:
|
||||
raise EnvironmentError(
|
||||
f"Error no file named {_add_variant(WEIGHTS_NAME, variant)} found in directory"
|
||||
f" {pretrained_model_name_or_path}."
|
||||
)
|
||||
elif os.path.isfile(os.path.join(subfolder, pretrained_model_name_or_path)):
|
||||
archive_file = pretrained_model_name_or_path
|
||||
is_local = True
|
||||
elif is_remote_url(pretrained_model_name_or_path):
|
||||
filename = pretrained_model_name_or_path
|
||||
resolved_archive_file = download_url(pretrained_model_name_or_path)
|
||||
else:
|
||||
# set correct filename
|
||||
if use_safetensors is not False:
|
||||
filename = _add_variant(SAFE_WEIGHTS_NAME, variant)
|
||||
else:
|
||||
filename = _add_variant(WEIGHTS_NAME, variant)
|
||||
|
||||
try:
|
||||
# Load from URL or cache if already cached
|
||||
cached_file_kwargs = {
|
||||
"cache_dir": cache_dir,
|
||||
"force_download": force_download,
|
||||
"proxies": proxies,
|
||||
"resume_download": resume_download,
|
||||
"local_files_only": local_files_only,
|
||||
"use_auth_token": use_auth_token,
|
||||
"user_agent": user_agent,
|
||||
"revision": revision,
|
||||
"subfolder": subfolder,
|
||||
"_raise_exceptions_for_missing_entries": False,
|
||||
"_commit_hash": commit_hash,
|
||||
}
|
||||
resolved_archive_file = cached_file(
|
||||
pretrained_model_name_or_path, filename, **cached_file_kwargs)
|
||||
|
||||
# Since we set _raise_exceptions_for_missing_entries=False, we don't get an exception but a None
|
||||
# result when internet is up, the repo and revision exist, but the file does not.
|
||||
if resolved_archive_file is None and filename == _add_variant(SAFE_WEIGHTS_NAME, variant):
|
||||
# Maybe the checkpoint is sharded, we try to grab the index name in this case.
|
||||
resolved_archive_file = cached_file(
|
||||
pretrained_model_name_or_path,
|
||||
_add_variant(SAFE_WEIGHTS_INDEX_NAME, variant),
|
||||
**cached_file_kwargs,
|
||||
)
|
||||
if resolved_archive_file is not None:
|
||||
pass
|
||||
elif use_safetensors:
|
||||
raise EnvironmentError(
|
||||
f" {_add_variant(SAFE_WEIGHTS_NAME, variant)} or {_add_variant(SAFE_WEIGHTS_INDEX_NAME, variant)} and thus cannot be loaded with `safetensors`. Please make sure that the model has been saved with `safe_serialization=True` or do not set `use_safetensors=True`."
|
||||
)
|
||||
else:
|
||||
# This repo has no safetensors file of any kind, we switch to PyTorch.
|
||||
filename = _add_variant(WEIGHTS_NAME, variant)
|
||||
resolved_archive_file = cached_file(
|
||||
pretrained_model_name_or_path, filename, **cached_file_kwargs
|
||||
)
|
||||
if resolved_archive_file is None and filename == _add_variant(WEIGHTS_NAME, variant):
|
||||
# Maybe the checkpoint is sharded, we try to grab the index name in this case.
|
||||
resolved_archive_file = cached_file(
|
||||
pretrained_model_name_or_path,
|
||||
_add_variant(WEIGHTS_INDEX_NAME, variant),
|
||||
**cached_file_kwargs,
|
||||
)
|
||||
if resolved_archive_file is not None:
|
||||
pass
|
||||
if resolved_archive_file is None:
|
||||
# Otherwise, maybe there is a TF or Flax model file. We try those to give a helpful error
|
||||
# message.
|
||||
has_file_kwargs = {
|
||||
"revision": revision,
|
||||
"proxies": proxies,
|
||||
"use_auth_token": use_auth_token,
|
||||
}
|
||||
if variant is not None and has_file(pretrained_model_name_or_path, WEIGHTS_NAME, **has_file_kwargs):
|
||||
raise EnvironmentError(
|
||||
f"{pretrained_model_name_or_path} does not appear to have a file named"
|
||||
f" {_add_variant(WEIGHTS_NAME, variant)} but there is a file without the variant"
|
||||
f" {variant}. Use `variant=None` to load this model from those weights."
|
||||
)
|
||||
else:
|
||||
raise EnvironmentError(
|
||||
f"{pretrained_model_name_or_path} does not appear to have a file named"
|
||||
f" {_add_variant(WEIGHTS_NAME, variant)}"
|
||||
)
|
||||
except EnvironmentError:
|
||||
# Raise any environment error raise by `cached_file`. It will have a helpful error message adapted
|
||||
# to the original exception.
|
||||
raise
|
||||
except Exception:
|
||||
# For any other exception, we throw a generic error.
|
||||
raise EnvironmentError(
|
||||
f"Can't load the model for '{pretrained_model_name_or_path}'. If you were trying to load it"
|
||||
" from 'https://huggingface.co/models', make sure you don't have a local directory with the"
|
||||
f" same name. Otherwise, make sure '{pretrained_model_name_or_path}' is the correct path to a"
|
||||
f" directory containing a file named {_add_variant(WEIGHTS_NAME, variant)}."
|
||||
)
|
||||
|
||||
if is_local:
|
||||
logger.info(f"loading weights file {archive_file}")
|
||||
resolved_archive_file = archive_file
|
||||
else:
|
||||
logger.info(
|
||||
f"loading weights file {filename} from cache at {resolved_archive_file}")
|
||||
else:
|
||||
resolved_archive_file = None
|
||||
|
||||
if from_pt:
|
||||
# set dtype to instantiate the model under:
|
||||
# 1. If torch_dtype is not None, we use that dtype
|
||||
dtype_orig = None
|
||||
|
||||
if torch_dtype is not None:
|
||||
if not isinstance(torch_dtype, torch.dtype):
|
||||
raise ValueError(
|
||||
f"`torch_dtype` can be either `torch.dtype` or `None`, but received {torch_dtype}")
|
||||
dtype_orig = cls._set_default_torch_dtype(torch_dtype)
|
||||
|
||||
config.name_or_path = pretrained_model_name_or_path
|
||||
|
||||
# Instantiate model.
|
||||
init_contexts = [no_init_weights(_enable=_fast_init)]
|
||||
|
||||
with ContextManagers(init_contexts):
|
||||
model = cls(config, *model_args, **model_kwargs)
|
||||
|
||||
if from_pt:
|
||||
# restore default dtype
|
||||
if dtype_orig is not None:
|
||||
torch.set_default_dtype(dtype_orig)
|
||||
|
||||
# make sure token embedding weights are still tied if needed
|
||||
model.tie_weights()
|
||||
|
||||
# Set model in evaluation mode to deactivate DropOut modules by default
|
||||
model.eval()
|
||||
|
||||
# If it is a model with generation capabilities, attempt to load the generation config
|
||||
if model.can_generate():
|
||||
try:
|
||||
model.generation_config = GenerationConfig.from_pretrained(
|
||||
pretrained_model_name_or_path,
|
||||
cache_dir=cache_dir,
|
||||
force_download=force_download,
|
||||
resume_download=resume_download,
|
||||
proxies=proxies,
|
||||
local_files_only=local_files_only,
|
||||
use_auth_token=use_auth_token,
|
||||
revision=revision,
|
||||
subfolder=subfolder,
|
||||
_from_auto=from_auto_class,
|
||||
_from_pipeline=from_pipeline,
|
||||
**kwargs,
|
||||
)
|
||||
except (OSError, TypeError):
|
||||
logger.info(
|
||||
"Generation config file not found, using a generation config created from the model config.")
|
||||
|
||||
return model
|
||||
186
ixformer_sdk/train/speedformer/layers/llama/attention.py
Normal file
186
ixformer_sdk/train/speedformer/layers/llama/attention.py
Normal file
@@ -0,0 +1,186 @@
|
||||
import math
|
||||
import warnings
|
||||
from typing import List, Optional, Tuple, Union
|
||||
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
|
||||
from ixformer.train.speedformer.models.llama.configuration_llama import LlamaConfig
|
||||
from ixformer.train.speedformer.models.llama.modeling_llama import LlamaFlashAttention2
|
||||
from transformers import Cache
|
||||
from transformers.utils import logging
|
||||
|
||||
from flash_attn import flash_attn_func, flash_attn_varlen_func
|
||||
from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input
|
||||
|
||||
from ixformer.train.functions.fused_rope import fused_apply_rotary_pos_emb
|
||||
from ixformer.train.speedformer.layers.rotary_pos_embedding import RotaryEmbedding
|
||||
|
||||
|
||||
class BaseLlamaAttention(LlamaFlashAttention2):
|
||||
"""
|
||||
加这个层的原因:1.当原模型中使用的是torch nvtive的attention,强制替换成flash_attn; 2.优化rope
|
||||
"""
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
if self.config.rope_scaling is None:
|
||||
self.rotary_emb = RotaryEmbedding(self.head_dim)
|
||||
|
||||
def forward(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
attention_mask: Optional[torch.LongTensor] = None,
|
||||
position_ids: Optional[torch.LongTensor] = None,
|
||||
past_key_value: Optional[Cache] = None,
|
||||
output_attentions: bool = False,
|
||||
use_cache: bool = False,
|
||||
**kwargs,
|
||||
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
||||
output_attentions = False
|
||||
bsz, q_len, _ = hidden_states.size()
|
||||
query_states = self.q_proj(hidden_states)
|
||||
key_states = self.k_proj(hidden_states)
|
||||
value_states = self.v_proj(hidden_states)
|
||||
|
||||
# fused_apply_rotary_pos_emb need qk to be in "sbhd"
|
||||
query_states = query_states.view(
|
||||
bsz, q_len, self.num_heads, self.head_dim).transpose(1, 0).contiguous()
|
||||
key_states = key_states.view(
|
||||
bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 0).contiguous()
|
||||
value_states = value_states.view(
|
||||
bsz, q_len, self.num_heads, self.head_dim)
|
||||
|
||||
kv_seq_len = key_states.shape[0]
|
||||
if past_key_value is not None:
|
||||
kv_seq_len += past_key_value[0].shape[0]
|
||||
|
||||
emb = self.rotary_emb(kv_seq_len).to(dtype=torch.float32)
|
||||
query_states = fused_apply_rotary_pos_emb(query_states, emb)
|
||||
key_states = fused_apply_rotary_pos_emb(key_states, emb)
|
||||
|
||||
# kv cache staff
|
||||
if past_key_value is not None:
|
||||
# reuse k, v, self_attention
|
||||
key_states = torch.cat([past_key_value[0], key_states], dim=0)
|
||||
value_states = torch.cat([past_key_value[1], value_states], dim=0)
|
||||
past_key_value = (key_states, value_states) if use_cache else None
|
||||
|
||||
dropout_rate = self.attention_dropout if self.training else 0.0
|
||||
|
||||
# after fused_apply_rotary_pos_emb, qk change to "bshd" for flashattn or "bhsd" for sdpa
|
||||
if attention_mask is None: # flash-attn
|
||||
query_states = query_states.transpose(0, 1).contiguous()
|
||||
key_states = key_states.transpose(0, 1).contiguous()
|
||||
else: # sdpa
|
||||
query_states = query_states.permute(1, 2, 0, 3).contiguous()
|
||||
key_states = key_states.permute(1, 2, 0, 3).contiguous()
|
||||
value_states = value_states.transpose(1, 2).contiguous()
|
||||
# In PEFT, usually we cast the layer norms in float32 for training stability reasons
|
||||
# therefore the input hidden states gets silently casted in float32. Hence, we need
|
||||
# cast them back in the correct dtype just to be sure everything works as expected.
|
||||
# This might slowdown training & inference so it is recommended to not cast the LayerNorms
|
||||
# in fp32. (LlamaRMSNorm handles it correctly)
|
||||
|
||||
input_dtype = query_states.dtype
|
||||
if input_dtype == torch.float32:
|
||||
# Handle the case where the model is quantized
|
||||
if hasattr(self.config, "_pre_quantization_dtype"):
|
||||
target_dtype = self.config._pre_quantization_dtype
|
||||
else:
|
||||
target_dtype = self.q_proj.weight.dtype
|
||||
|
||||
query_states = query_states.to(target_dtype)
|
||||
key_states = key_states.to(target_dtype)
|
||||
value_states = value_states.to(target_dtype)
|
||||
|
||||
attn_output = self._flash_attention_forward(
|
||||
query_states, key_states, value_states, attention_mask, q_len, dropout=dropout_rate
|
||||
)
|
||||
|
||||
attn_output = attn_output.reshape(
|
||||
bsz, q_len, self.hidden_size).contiguous()
|
||||
attn_output = self.o_proj(attn_output)
|
||||
|
||||
if not output_attentions:
|
||||
attn_weights = None
|
||||
|
||||
return attn_output, attn_weights, past_key_value
|
||||
|
||||
def _flash_attention_forward(
|
||||
self, query_states, key_states, value_states, attention_mask, query_length, dropout=0.0, softmax_scale=None
|
||||
):
|
||||
"""
|
||||
for now, if attention_mask is none, flash-attn has better performance than torch.nn.functional.scaled_dot_product_attention;
|
||||
if attention_mask is not none, torch.nn.functional.scaled_dot_product_attention works better
|
||||
so sdpa and flash-attn is perfered according to attention_mask
|
||||
|
||||
Args:
|
||||
query_states (`torch.Tensor`):
|
||||
Input query states to be passed to Flash Attention API
|
||||
key_states (`torch.Tensor`):
|
||||
Input key states to be passed to Flash Attention API
|
||||
value_states (`torch.Tensor`):
|
||||
Input value states to be passed to Flash Attention API
|
||||
attention_mask (`torch.Tensor`):
|
||||
The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
|
||||
position of padding tokens and 1 for the position of non-padding tokens.
|
||||
dropout (`int`, *optional*):
|
||||
Attention dropout
|
||||
softmax_scale (`float`, *optional*):
|
||||
The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
|
||||
"""
|
||||
# Contains at least one padding token in the sequence
|
||||
# if attention_mask is not None:
|
||||
if attention_mask is not None:
|
||||
attn_output = torch.nn.functional.scaled_dot_product_attention(
|
||||
query_states,
|
||||
key_states,
|
||||
value_states,
|
||||
attn_mask=attention_mask,
|
||||
dropout_p=self.attention_dropout if self.training else 0.0,
|
||||
# The q_len > 1 is necessary to match with AttentionMaskConverter.to_causal_4d that does not create a causal mask in case q_len == 1.
|
||||
is_causal=self.is_causal and attention_mask is None and query_length > 1,
|
||||
)
|
||||
attn_output = attn_output.transpose(1, 2).contiguous()
|
||||
|
||||
else:
|
||||
attn_output = flash_attn_func(
|
||||
query_states, key_states, value_states, dropout, softmax_scale=softmax_scale, causal=self.is_causal
|
||||
)
|
||||
|
||||
return attn_output
|
||||
|
||||
|
||||
class LlamaAttention(BaseLlamaAttention):
|
||||
def __init__(self) -> None:
|
||||
raise NotImplementedError(
|
||||
"LlamaAttention is not implemented as a physical class. "
|
||||
"It is meant to be used only with the from_native_module interface to Convert a native LlamaAttention module to LlamaAttention module provided above."
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def from_native_module(module: nn.Module, *args, **kwargs) -> nn.Module:
|
||||
|
||||
# LazyInitContext.materialize(module)
|
||||
|
||||
# try to get normalized_shape, eps, elementwise_affine from the module
|
||||
config = getattr(module, "config")
|
||||
layer_idx = getattr(module, "layer_idx", None)
|
||||
|
||||
attention = BaseLlamaAttention(
|
||||
config=config,
|
||||
layer_idx=layer_idx,
|
||||
)
|
||||
|
||||
attention.q_proj.weight = module.q_proj.weight
|
||||
attention.k_proj.weight = module.k_proj.weight
|
||||
attention.v_proj.weight = module.v_proj.weight
|
||||
attention.o_proj.weight = module.o_proj.weight
|
||||
|
||||
if config.attention_bias:
|
||||
attention.q_proj.bias = module.q_proj.bias
|
||||
attention.k_proj.bias = module.k_proj.bias
|
||||
attention.v_proj.bias = module.v_proj.bias
|
||||
attention.o_proj.bias = module.o_proj.bias
|
||||
return attention
|
||||
224
ixformer_sdk/train/speedformer/layers/llama/llama_method.py
Normal file
224
ixformer_sdk/train/speedformer/layers/llama/llama_method.py
Normal file
@@ -0,0 +1,224 @@
|
||||
import math
|
||||
import warnings
|
||||
from typing import List, Optional, Tuple, Union
|
||||
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
import torch.nn.functional as F
|
||||
|
||||
from ixformer.train.speedformer.models.llama.modeling_llama import LlamaModel
|
||||
from ixformer.train.speedformer.models.llama.modeling_attn_mask_utils import _prepare_4d_causal_attention_mask_for_sdpa
|
||||
from ixformer.train.speedformer.layers.cross_entropy_loss import fast_cross_entropy_loss as CrossEntropyLoss
|
||||
from transformers.utils import logging
|
||||
from transformers.cache_utils import Cache, DynamicCache
|
||||
|
||||
logger = logging.get_logger(__name__)
|
||||
|
||||
|
||||
def LlamaModel_forward():
|
||||
from transformers.modeling_outputs import BaseModelOutputWithPast
|
||||
|
||||
def forward(
|
||||
self,
|
||||
input_ids: torch.LongTensor = None,
|
||||
attention_mask: Optional[torch.Tensor] = None,
|
||||
position_ids: Optional[torch.LongTensor] = None,
|
||||
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
||||
inputs_embeds: Optional[torch.FloatTensor] = None,
|
||||
use_cache: Optional[bool] = None,
|
||||
output_attentions: Optional[bool] = None,
|
||||
output_hidden_states: Optional[bool] = None,
|
||||
return_dict: Optional[bool] = None,
|
||||
) -> Union[Tuple, BaseModelOutputWithPast]:
|
||||
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
||||
output_hidden_states = (
|
||||
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
||||
)
|
||||
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
||||
|
||||
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
||||
|
||||
# retrieve input_ids and inputs_embeds
|
||||
if input_ids is not None and inputs_embeds is not None:
|
||||
raise ValueError(
|
||||
"You cannot specify both input_ids and inputs_embeds at the same time")
|
||||
elif input_ids is not None:
|
||||
batch_size, seq_length = input_ids.shape[:2]
|
||||
elif inputs_embeds is not None:
|
||||
batch_size, seq_length = inputs_embeds.shape[:2]
|
||||
else:
|
||||
raise ValueError(
|
||||
"You have to specify either input_ids or inputs_embeds")
|
||||
|
||||
if self.gradient_checkpointing and self.training:
|
||||
if use_cache:
|
||||
logger.warning_once(
|
||||
"`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
|
||||
)
|
||||
use_cache = False
|
||||
|
||||
past_key_values_length = 0
|
||||
if use_cache:
|
||||
use_legacy_cache = not isinstance(past_key_values, Cache)
|
||||
if use_legacy_cache:
|
||||
past_key_values = DynamicCache.from_legacy_cache(
|
||||
past_key_values)
|
||||
past_key_values_length = past_key_values.get_usable_length(
|
||||
seq_length)
|
||||
|
||||
if position_ids is None:
|
||||
device = input_ids.device if input_ids is not None else inputs_embeds.device
|
||||
position_ids = torch.arange(
|
||||
past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
|
||||
)
|
||||
position_ids = position_ids.unsqueeze(0)
|
||||
|
||||
if inputs_embeds is None:
|
||||
inputs_embeds = self.embed_tokens(input_ids)
|
||||
|
||||
if attention_mask is not None:
|
||||
# output_attentions=True can not be supported when using SDPA, and we fall back on
|
||||
# the manual implementation that requires a 4D causal mask in all cases.
|
||||
attention_mask = _prepare_4d_causal_attention_mask_for_sdpa(
|
||||
attention_mask,
|
||||
(batch_size, seq_length),
|
||||
inputs_embeds,
|
||||
past_key_values_length,
|
||||
)
|
||||
|
||||
# embed positions
|
||||
hidden_states = inputs_embeds
|
||||
|
||||
# decoder layers
|
||||
all_hidden_states = () if output_hidden_states else None
|
||||
all_self_attns = () if output_attentions else None
|
||||
next_decoder_cache = None
|
||||
|
||||
for decoder_layer in self.layers:
|
||||
if output_hidden_states:
|
||||
all_hidden_states += (hidden_states,)
|
||||
|
||||
if self.gradient_checkpointing and self.training:
|
||||
layer_outputs = self._gradient_checkpointing_func(
|
||||
decoder_layer.__call__,
|
||||
hidden_states,
|
||||
attention_mask,
|
||||
position_ids,
|
||||
past_key_values,
|
||||
output_attentions,
|
||||
use_cache,
|
||||
)
|
||||
else:
|
||||
layer_outputs = decoder_layer(
|
||||
hidden_states,
|
||||
attention_mask=attention_mask,
|
||||
position_ids=position_ids,
|
||||
past_key_value=past_key_values,
|
||||
output_attentions=output_attentions,
|
||||
use_cache=use_cache,
|
||||
)
|
||||
|
||||
hidden_states = layer_outputs[0]
|
||||
|
||||
if use_cache:
|
||||
next_decoder_cache = layer_outputs[2 if output_attentions else 1]
|
||||
|
||||
if output_attentions:
|
||||
all_self_attns += (layer_outputs[1],)
|
||||
|
||||
hidden_states = self.norm(hidden_states)
|
||||
|
||||
# add hidden states from the last decoder layer
|
||||
if output_hidden_states:
|
||||
all_hidden_states += (hidden_states,)
|
||||
|
||||
next_cache = None
|
||||
if use_cache:
|
||||
next_cache = next_decoder_cache.to_legacy_cache(
|
||||
) if use_legacy_cache else next_decoder_cache
|
||||
if not return_dict:
|
||||
return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
|
||||
return BaseModelOutputWithPast(
|
||||
last_hidden_state=hidden_states,
|
||||
past_key_values=next_cache,
|
||||
hidden_states=all_hidden_states,
|
||||
attentions=all_self_attns,
|
||||
)
|
||||
|
||||
return forward
|
||||
|
||||
|
||||
def LlamaForCausalLM_forward():
|
||||
from transformers.utils import add_start_docstrings_to_model_forward, replace_return_docstrings
|
||||
from transformers.models.llama.modeling_llama import LLAMA_INPUTS_DOCSTRING, CausalLMOutputWithPast, _CONFIG_FOR_DOC
|
||||
|
||||
def forward(
|
||||
self,
|
||||
input_ids: torch.LongTensor = None,
|
||||
attention_mask: Optional[torch.Tensor] = None,
|
||||
position_ids: Optional[torch.LongTensor] = None,
|
||||
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
||||
inputs_embeds: Optional[torch.FloatTensor] = None,
|
||||
labels: Optional[torch.LongTensor] = None,
|
||||
use_cache: Optional[bool] = None,
|
||||
output_attentions: Optional[bool] = None,
|
||||
output_hidden_states: Optional[bool] = None,
|
||||
return_dict: Optional[bool] = None,
|
||||
) -> Union[Tuple, CausalLMOutputWithPast]:
|
||||
|
||||
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
||||
output_hidden_states = (
|
||||
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
||||
)
|
||||
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
||||
|
||||
# decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
|
||||
outputs = self.model(
|
||||
input_ids=input_ids,
|
||||
attention_mask=attention_mask,
|
||||
position_ids=position_ids,
|
||||
past_key_values=past_key_values,
|
||||
inputs_embeds=inputs_embeds,
|
||||
use_cache=use_cache,
|
||||
output_attentions=output_attentions,
|
||||
output_hidden_states=output_hidden_states,
|
||||
return_dict=return_dict,
|
||||
)
|
||||
|
||||
hidden_states = outputs[0]
|
||||
if self.config.pretraining_tp > 1:
|
||||
lm_head_slices = self.lm_head.weight.split(
|
||||
self.vocab_size // self.config.pretraining_tp, dim=0)
|
||||
logits = [F.linear(hidden_states, lm_head_slices[i])
|
||||
for i in range(self.config.pretraining_tp)]
|
||||
logits = torch.cat(logits, dim=-1)
|
||||
else:
|
||||
logits = self.lm_head(hidden_states)
|
||||
logits = logits.float()
|
||||
|
||||
loss = None
|
||||
if labels is not None:
|
||||
# Shift so that tokens < n predict n
|
||||
shift_logits = logits[..., :-1, :].contiguous()
|
||||
shift_labels = labels[..., 1:].contiguous()
|
||||
# Flatten the tokens
|
||||
loss_fct = CrossEntropyLoss
|
||||
shift_logits = shift_logits.view(-1, self.config.vocab_size)
|
||||
shift_labels = shift_labels.view(-1)
|
||||
# Enable model parallelism
|
||||
shift_labels = shift_labels.to(shift_logits.device)
|
||||
loss = loss_fct(shift_logits, shift_labels)
|
||||
|
||||
if not return_dict:
|
||||
output = (logits,) + outputs[1:]
|
||||
return (loss,) + output if loss is not None else output
|
||||
|
||||
return CausalLMOutputWithPast(
|
||||
loss=loss,
|
||||
logits=logits,
|
||||
past_key_values=outputs.past_key_values,
|
||||
hidden_states=outputs.hidden_states,
|
||||
attentions=outputs.attentions,
|
||||
)
|
||||
|
||||
return forward
|
||||
55
ixformer_sdk/train/speedformer/layers/llama/mlp.py
Normal file
55
ixformer_sdk/train/speedformer/layers/llama/mlp.py
Normal file
@@ -0,0 +1,55 @@
|
||||
import math
|
||||
import warnings
|
||||
from typing import List, Optional, Tuple, Union
|
||||
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
|
||||
import ixformer.train.functions as F
|
||||
from ixformer.train.speedformer.models.llama.configuration_llama import LlamaConfig
|
||||
from ixformer.train.speedformer.models.llama.modeling_llama import LlamaMLP
|
||||
from transformers import Cache
|
||||
from transformers.utils import logging
|
||||
|
||||
from ixformer.train.speedformer.layers.lazy import LazyInitContext
|
||||
|
||||
|
||||
class BaseLlamaMLP(LlamaMLP):
|
||||
"""
|
||||
这个层主要的优化点是:将linear1(act(cat(linear2(x), linear3(x))))的结构变成 linear1(act(linear23(x)))
|
||||
"""
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
self.gate_up = nn.Linear(
|
||||
self.hidden_size, self.intermediate_size * 2, bias=False)
|
||||
del self.gate_proj, self.up_proj
|
||||
del self.act_fn
|
||||
|
||||
def forward(self, x):
|
||||
res = self.gate_up(x)
|
||||
down_proj = self.down_proj(F.swiglu(res))
|
||||
return down_proj
|
||||
|
||||
|
||||
class IXFLlamaMLP(BaseLlamaMLP):
|
||||
def __init__(self) -> None:
|
||||
raise NotImplementedError(
|
||||
"IXFLlamaMLP is not implemented as a physical class. "
|
||||
"It is meant to be used only with the from_native_module interface to Convert a native LlamaAttention module to IXFLlamaMLP module provided above."
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def from_native_module(module: nn.Module, *args, **kwargs) -> nn.Module:
|
||||
|
||||
LazyInitContext.materialize(module)
|
||||
|
||||
config = getattr(module, "config")
|
||||
|
||||
mlp = BaseLlamaMLP(config=config)
|
||||
|
||||
mlp.gate_up.weight.data = torch.concat(
|
||||
(module.gate_proj.weight.data, module.up_proj.weight.data), dim=0)
|
||||
mlp.down_proj.weight.data = module.down_proj.weight.data
|
||||
|
||||
return mlp
|
||||
129
ixformer_sdk/train/speedformer/layers/normalization.py
Normal file
129
ixformer_sdk/train/speedformer/layers/normalization.py
Normal file
@@ -0,0 +1,129 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- encoding: utf-8 -*-
|
||||
import warnings
|
||||
from abc import ABC, abstractmethod
|
||||
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
import ixformer.functions as ixff
|
||||
from ixformer.train.functions import FusedRMSNorm as ixf_FusedRMSNorm
|
||||
from apex.normalization.fused_layer_norm import FusedRMSNorm as apex_FusedRMSNorm
|
||||
from ixformer.train.speedformer.layers.lazy import LazyInitContext
|
||||
|
||||
|
||||
class BaseLayerNorm(ABC):
|
||||
@abstractmethod
|
||||
def from_native_module(module: nn.Module, sp_partial_derived: bool = False):
|
||||
"""
|
||||
Convert a native PyTorch layer normalization module to a specific layer normalization module,
|
||||
and optionally mark parameters for gradient aggregation.
|
||||
|
||||
Args:
|
||||
module (nn.Module): The native PyTorch layer normalization module to be converted.
|
||||
sp_partial_derived (bool): Whether this module's gradients are partially derived in sequence parallelism.
|
||||
|
||||
Returns:
|
||||
nn.Module: The specific layer normalization module.
|
||||
|
||||
Raises:
|
||||
AssertionError: If the provided module is not an instance of the supported layer normalization type.
|
||||
"""
|
||||
|
||||
|
||||
class IXFFusedRMSNorm(BaseLayerNorm):
|
||||
"""
|
||||
This is a wrapper around the apex fused rms norm implementation. It is meant to be used only with the from_native_module interface.
|
||||
"""
|
||||
|
||||
def __init__(self) -> None:
|
||||
raise NotImplementedError(
|
||||
"FusedRMSNorm is not implemented as a physical class. "
|
||||
"It is meant to be used only with the from_native_module interface to Convert a native RMSNorm module to FusedRMSNorm module provided by apex."
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def from_native_module(module: nn.Module, *args, **kwargs) -> nn.Module:
|
||||
r"""
|
||||
Convert a native RMSNorm module module to FusedRMSNorm module provided by ixformer,
|
||||
and optionally marking parameters for gradient aggregation.
|
||||
|
||||
Args:
|
||||
module (nn.LayerNorm): The native PyTorch LayerNorm module to be converted.
|
||||
sp_partial_derived (bool): Whether this module's gradients are partially derived in sequence parallelism.
|
||||
|
||||
Returns:
|
||||
nn.Module: FusedRMSNorm module.
|
||||
"""
|
||||
|
||||
LazyInitContext.materialize(module)
|
||||
|
||||
# try to get normalized_shape, eps, elementwise_affine from the module
|
||||
normalized_shape = getattr(
|
||||
module, "normalized_shape", module.weight.shape[0])
|
||||
eps = module.variance_epsilon if hasattr(
|
||||
module, "variance_epsilon") else module.eps
|
||||
elementwise_affine = getattr(module, "elementwise_affine", True)
|
||||
|
||||
rmsnorm = ixf_FusedRMSNorm(
|
||||
normalized_shape=normalized_shape,
|
||||
eps=eps,
|
||||
elementwise_affine=elementwise_affine,
|
||||
)
|
||||
|
||||
rmsnorm.weight = module.weight
|
||||
|
||||
return rmsnorm
|
||||
|
||||
|
||||
class APEXFusedRMSNorm(BaseLayerNorm):
|
||||
"""
|
||||
This is a wrapper around the apex fused rms norm implementation. It is meant to be used only with the from_native_module interface.
|
||||
"""
|
||||
|
||||
def __init__(self) -> None:
|
||||
raise NotImplementedError(
|
||||
"FusedRMSNorm is not implemented as a physical class. "
|
||||
"It is meant to be used only with the from_native_module interface to Convert a native RMSNorm module to FusedRMSNorm module provided by apex."
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def from_native_module(module: nn.Module, *args, **kwargs) -> nn.Module:
|
||||
r"""
|
||||
Convert a native RMSNorm module module to FusedRMSNorm module provided by ixformer,
|
||||
and optionally marking parameters for gradient aggregation.
|
||||
|
||||
Args:
|
||||
module (nn.LayerNorm): The native PyTorch LayerNorm module to be converted.
|
||||
sp_partial_derived (bool): Whether this module's gradients are partially derived in sequence parallelism.
|
||||
|
||||
Returns:
|
||||
nn.Module: FusedRMSNorm module.
|
||||
"""
|
||||
|
||||
LazyInitContext.materialize(module)
|
||||
|
||||
# try to get normalized_shape, eps, elementwise_affine from the module
|
||||
normalized_shape = getattr(
|
||||
module, "normalized_shape", module.weight.shape[0])
|
||||
eps = module.variance_epsilon if hasattr(
|
||||
module, "variance_epsilon") else module.eps
|
||||
elementwise_affine = getattr(module, "elementwise_affine", True)
|
||||
|
||||
rmsnorm = apex_FusedRMSNorm(
|
||||
normalized_shape=normalized_shape,
|
||||
eps=eps,
|
||||
elementwise_affine=elementwise_affine,
|
||||
)
|
||||
|
||||
rmsnorm.weight = module.weight
|
||||
|
||||
return rmsnorm
|
||||
|
||||
|
||||
# 替换torch LayerNorm 的forward
|
||||
@staticmethod
|
||||
def replace_layernorm_forward(self, input: torch.Tensor) -> torch.Tensor:
|
||||
|
||||
output = torch.empty_like(input)
|
||||
|
||||
return ixff.layernorm_train(input, self.weight, self.bias, self.normalized_shape, output, True)
|
||||
263
ixformer_sdk/train/speedformer/layers/qwen2/attention.py
Normal file
263
ixformer_sdk/train/speedformer/layers/qwen2/attention.py
Normal file
@@ -0,0 +1,263 @@
|
||||
import math
|
||||
import warnings
|
||||
import inspect
|
||||
from typing import List, Optional, Tuple, Union
|
||||
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
|
||||
from ixformer.train.speedformer.models.qwen2.configuration_qwen2 import Qwen2Config
|
||||
from ixformer.train.speedformer.models.qwen2.modeling_qwen2 import Qwen2FlashAttention2
|
||||
from transformers import Cache
|
||||
from transformers.utils import logging
|
||||
|
||||
from flash_attn import flash_attn_func, flash_attn_varlen_func
|
||||
|
||||
from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input
|
||||
|
||||
from ixformer.train.functions.fused_rope import fused_apply_rotary_pos_emb
|
||||
from ixformer.train.speedformer.layers.rotary_pos_embedding import RotaryEmbedding
|
||||
|
||||
from ixformer.train.speedformer.layers.lazy import LazyInitContext
|
||||
|
||||
_flash_supports_window_size = "window_size" in list(
|
||||
inspect.signature(flash_attn_func).parameters)
|
||||
logger = logging.get_logger(__name__)
|
||||
|
||||
|
||||
# Copied from transformers.models.llama.modeling_llama.repeat_kv
|
||||
def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
|
||||
"""
|
||||
This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
|
||||
num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
|
||||
"""
|
||||
batch, num_key_value_heads, slen, head_dim = hidden_states.shape
|
||||
if n_rep == 1:
|
||||
return hidden_states
|
||||
hidden_states = hidden_states[:, :, None, :, :].expand(
|
||||
batch, num_key_value_heads, n_rep, slen, head_dim)
|
||||
return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
|
||||
|
||||
|
||||
class BaseQwenAttention(Qwen2FlashAttention2):
|
||||
"""
|
||||
加这个层的原因:1.当原模型中使用的是torch nvtive的attention,强制替换成flash_attn; 2.优化rope
|
||||
"""
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
out_dim = self.num_heads * self.head_dim + \
|
||||
self.num_key_value_heads * self.head_dim * 2
|
||||
self.qkv_proj = nn.Linear(self.hidden_size, out_dim, bias=True)
|
||||
del self.q_proj, self.k_proj, self.v_proj
|
||||
self.rotary_emb = RotaryEmbedding(self.head_dim, self.rope_theta)
|
||||
|
||||
def forward(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
attention_mask: Optional[torch.Tensor] = None,
|
||||
position_ids: Optional[torch.LongTensor] = None,
|
||||
past_key_value: Optional[Cache] = None,
|
||||
output_attentions: bool = False,
|
||||
use_cache: bool = False,
|
||||
):
|
||||
bsz, q_len, _ = hidden_states.size()
|
||||
qkv = self.qkv_proj(hidden_states)
|
||||
q_dim = self.num_heads * self.head_dim
|
||||
kv_dim = self.num_key_value_heads * self.head_dim
|
||||
query_states, key_states, value_states = torch.split(
|
||||
qkv, (q_dim, kv_dim, kv_dim), dim=-1)
|
||||
# fused_apply_rotary_pos_emb need qk to be in "sbhd", v stay "bshd"
|
||||
query_states = query_states.view(
|
||||
bsz, q_len, self.num_heads, self.head_dim).transpose(0, 1).contiguous()
|
||||
key_states = key_states.view(
|
||||
bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(0, 1).contiguous()
|
||||
value_states = value_states.view(
|
||||
bsz, q_len, self.num_key_value_heads, self.head_dim)
|
||||
|
||||
kv_seq_len = key_states.shape[0]
|
||||
if past_key_value is not None:
|
||||
if self.layer_idx is None:
|
||||
raise ValueError(
|
||||
f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
|
||||
"for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
|
||||
"with a layer index."
|
||||
)
|
||||
kv_seq_len += past_key_value[0].shape[0]
|
||||
|
||||
emb = self.rotary_emb(kv_seq_len).to(dtype=torch.float32)
|
||||
query_states = fused_apply_rotary_pos_emb(query_states, emb)
|
||||
key_states = fused_apply_rotary_pos_emb(key_states, emb)
|
||||
use_sliding_windows = (
|
||||
_flash_supports_window_size
|
||||
and getattr(self.config, "sliding_window", None) is not None
|
||||
and kv_seq_len > self.config.sliding_window
|
||||
and self.config.use_sliding_window
|
||||
)
|
||||
|
||||
if not _flash_supports_window_size:
|
||||
logger.warning_once(
|
||||
"The current flash attention version does not support sliding window attention, for a more memory efficient implementation"
|
||||
" make sure to upgrade flash-attn library."
|
||||
)
|
||||
|
||||
# for now, attention with sliding_windows have not test, so if use_sliding_windows throw error
|
||||
if use_sliding_windows:
|
||||
raise KeyError("use_sliding_windows not support for now")
|
||||
|
||||
# kv cache staff
|
||||
if past_key_value is not None:
|
||||
# reuse k, v, self_attention
|
||||
key_states = torch.cat([past_key_value[0], key_states], dim=0)
|
||||
value_states = torch.cat([past_key_value[1], value_states], dim=0)
|
||||
past_key_value = (key_states, value_states) if use_cache else None
|
||||
|
||||
# if attention mask is None, use flashattn which support GQA
|
||||
if attention_mask is not None:
|
||||
key_states = repeat_kv(key_states, self.num_key_value_groups)
|
||||
value_states = repeat_kv(value_states, self.num_key_value_groups)
|
||||
|
||||
dropout_rate = 0.0 if not self.training else self.attention_dropout
|
||||
# In PEFT, usually we cast the layer norms in float32 for training stability reasons
|
||||
# therefore the input hidden states gets silently casted in float32. Hence, we need
|
||||
# cast them back in float16 just to be sure everything works as expected.
|
||||
input_dtype = query_states.dtype
|
||||
if input_dtype == torch.float32:
|
||||
if torch.is_autocast_enabled():
|
||||
target_dtype = torch.get_autocast_gpu_dtype()
|
||||
# Handle the case where the model is quantized
|
||||
elif hasattr(self.config, "_pre_quantization_dtype"):
|
||||
target_dtype = self.config._pre_quantization_dtype
|
||||
else:
|
||||
target_dtype = self.q_proj.weight.dtype
|
||||
|
||||
logger.warning_once(
|
||||
f"The input hidden states seems to be silently casted in float32, this might be related to"
|
||||
f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
|
||||
f" {target_dtype}."
|
||||
)
|
||||
|
||||
query_states = query_states.to(target_dtype)
|
||||
key_states = key_states.to(target_dtype)
|
||||
value_states = value_states.to(target_dtype)
|
||||
|
||||
# after fused_apply_rotary_pos_emb, qk change to "bshd" for flashattn or "bhsd" for sdpa
|
||||
if attention_mask is None: # flash-attn
|
||||
query_states = query_states.transpose(0, 1).contiguous()
|
||||
key_states = key_states.transpose(0, 1).contiguous()
|
||||
else: # sdpa
|
||||
query_states = query_states.permute(1, 2, 0, 3).contiguous()
|
||||
key_states = key_states.permute(1, 2, 0, 3).contiguous()
|
||||
value_states = value_states.transpose(1, 2).contiguous()
|
||||
|
||||
attn_output = self._attention_forward(
|
||||
query_states,
|
||||
key_states,
|
||||
value_states,
|
||||
attention_mask,
|
||||
q_len,
|
||||
dropout=dropout_rate,
|
||||
use_sliding_windows=use_sliding_windows,
|
||||
)
|
||||
|
||||
attn_output = attn_output.reshape(
|
||||
bsz, q_len, self.hidden_size).contiguous()
|
||||
attn_output = self.o_proj(attn_output)
|
||||
|
||||
if not output_attentions:
|
||||
attn_weights = None
|
||||
|
||||
return attn_output, attn_weights, past_key_value
|
||||
|
||||
def _attention_forward(
|
||||
self,
|
||||
query_states,
|
||||
key_states,
|
||||
value_states,
|
||||
attention_mask,
|
||||
query_length,
|
||||
dropout=0.0,
|
||||
softmax_scale=None,
|
||||
use_sliding_windows=False,
|
||||
):
|
||||
"""
|
||||
Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
|
||||
first unpad the input, then computes the attention scores and pad the final attention scores.
|
||||
|
||||
Args:
|
||||
query_states (`torch.Tensor`):
|
||||
Input query states to be passed to Flash Attention API
|
||||
key_states (`torch.Tensor`):
|
||||
Input key states to be passed to Flash Attention API
|
||||
value_states (`torch.Tensor`):
|
||||
Input value states to be passed to Flash Attention API
|
||||
attention_mask (`torch.Tensor`):
|
||||
The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
|
||||
position of padding tokens and 1 for the position of non-padding tokens.
|
||||
dropout (`float`):
|
||||
Attention dropout
|
||||
softmax_scale (`float`, *optional*):
|
||||
The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
|
||||
use_sliding_windows (`bool`, *optional*):
|
||||
Whether to activate sliding window attention.
|
||||
"""
|
||||
if not self._flash_attn_uses_top_left_mask:
|
||||
causal = self.is_causal
|
||||
else:
|
||||
# TODO: Remove the `query_length != 1` check once Flash Attention for RoCm is bumped to 2.1. For details, please see the comment in LlamaFlashAttention2 __init__.
|
||||
causal = self.is_causal and query_length != 1
|
||||
|
||||
if attention_mask is not None:
|
||||
batch_size = query_states.shape[0]
|
||||
attn_output = torch.nn.functional.scaled_dot_product_attention(
|
||||
query_states,
|
||||
key_states,
|
||||
value_states,
|
||||
attn_mask=attention_mask,
|
||||
dropout_p=self.attention_dropout if self.training else 0.0,
|
||||
# The q_len > 1 is necessary to match with AttentionMaskConverter.to_causal_4d that does not create a causal mask in case q_len == 1.
|
||||
is_causal=causal,
|
||||
)
|
||||
attn_output = attn_output.transpose(1, 2).contiguous()
|
||||
else:
|
||||
attn_output = flash_attn_func(
|
||||
query_states,
|
||||
key_states,
|
||||
value_states,
|
||||
dropout,
|
||||
softmax_scale=softmax_scale,
|
||||
causal=causal,
|
||||
)
|
||||
|
||||
return attn_output
|
||||
|
||||
|
||||
class QwenAttention(BaseQwenAttention):
|
||||
def __init__(self) -> None:
|
||||
raise NotImplementedError(
|
||||
"LlamaAttention is not implemented as a physical class. "
|
||||
"It is meant to be used only with the from_native_module interface to Convert a native LlamaAttention module to LlamaAttention module provided above."
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def from_native_module(module: nn.Module, *args, **kwargs) -> nn.Module:
|
||||
|
||||
LazyInitContext.materialize(module)
|
||||
|
||||
# try to get normalized_shape, eps, elementwise_affine from the module
|
||||
config = getattr(module, "config")
|
||||
layer_idx = getattr(module, "layer_idx", None)
|
||||
|
||||
attention = BaseQwenAttention(
|
||||
config=config,
|
||||
layer_idx=layer_idx,
|
||||
)
|
||||
|
||||
attention.qkv_proj.weight.data = torch.cat(
|
||||
(module.q_proj.weight.data, module.k_proj.weight.data, module.v_proj.weight.data), dim=0)
|
||||
attention.qkv_proj.bias.data = torch.cat(
|
||||
(module.q_proj.bias.data, module.k_proj.bias.data, module.v_proj.bias.data), dim=0)
|
||||
|
||||
attention.o_proj.weight.data = module.o_proj.weight.data
|
||||
|
||||
return attention
|
||||
55
ixformer_sdk/train/speedformer/layers/qwen2/mlp.py
Normal file
55
ixformer_sdk/train/speedformer/layers/qwen2/mlp.py
Normal file
@@ -0,0 +1,55 @@
|
||||
import math
|
||||
import warnings
|
||||
from typing import List, Optional, Tuple, Union
|
||||
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
|
||||
import ixformer.train.functions as F
|
||||
from ixformer.train.speedformer.models.qwen2.configuration_qwen2 import Qwen2Config
|
||||
from ixformer.train.speedformer.models.qwen2.modeling_qwen2 import Qwen2MLP
|
||||
from transformers import Cache
|
||||
from transformers.utils import logging
|
||||
|
||||
from ixformer.train.speedformer.layers.lazy import LazyInitContext
|
||||
|
||||
|
||||
class BaseQwen2MLP(Qwen2MLP):
|
||||
"""
|
||||
这个层主要的优化点是:将linear1(act(cat(linear2(x), linear3(x))))的结构变成 linear1(act(linear23(x)))
|
||||
"""
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
self.gate_up = nn.Linear(
|
||||
self.hidden_size, self.intermediate_size * 2, bias=False)
|
||||
del self.gate_proj, self.up_proj
|
||||
del self.act_fn
|
||||
|
||||
def forward(self, x):
|
||||
res = self.gate_up(x)
|
||||
down_proj = self.down_proj(F.swiglu(res))
|
||||
return down_proj
|
||||
|
||||
|
||||
class IXFQwen2MLP(BaseQwen2MLP):
|
||||
def __init__(self) -> None:
|
||||
raise NotImplementedError(
|
||||
"IXFQwen2MLP is not implemented as a physical class. "
|
||||
"It is meant to be used only with the from_native_module interface to Convert a native Qwen2MLP module to BaseQwen2MLP module provided above."
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def from_native_module(module: nn.Module, *args, **kwargs) -> nn.Module:
|
||||
|
||||
LazyInitContext.materialize(module)
|
||||
|
||||
config = getattr(module, "config")
|
||||
|
||||
mlp = BaseQwen2MLP(config=config)
|
||||
|
||||
mlp.gate_up.weight.data = torch.concat(
|
||||
(module.gate_proj.weight.data, module.up_proj.weight.data), dim=0)
|
||||
mlp.down_proj.weight.data = module.down_proj.weight.data
|
||||
|
||||
return mlp
|
||||
@@ -0,0 +1,55 @@
|
||||
import importlib.util
|
||||
import torch
|
||||
|
||||
from torch import einsum, nn
|
||||
|
||||
__all__ = ['RotaryEmbedding']
|
||||
|
||||
|
||||
# RotaryEmbedding and apply_rotary_pos_emb are copy from http://bitbucket.iluvatar.ai:7990/projects/PSR/repos/megatron-deepspeed/browse/megatron/model/rotary_pos_embedding.py
|
||||
# for now RotaryEmbedding is used, apply_rotary_pos_emb can be replaced by fused_apply_rotary_pos_emb from ixformer for better performance
|
||||
|
||||
class RotaryEmbedding(nn.Module):
|
||||
def __init__(self, dim, base=10000):
|
||||
super().__init__()
|
||||
inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2).float() / dim))
|
||||
self.register_buffer('inv_freq', inv_freq)
|
||||
if importlib.util.find_spec('einops') is None:
|
||||
raise RuntimeError("einops is required for Rotary Embedding")
|
||||
|
||||
def forward(self, max_seq_len, offset=0):
|
||||
seq = torch.arange(max_seq_len, device=self.inv_freq.device) + offset
|
||||
freqs = einsum(
|
||||
'i , j -> i j', seq.type_as(self.inv_freq), self.inv_freq)
|
||||
# first part even vector components, second part odd vector components,
|
||||
# 2 * dim in dimension size
|
||||
emb = torch.cat((freqs, freqs), dim=-1)
|
||||
# emb [seq_length, .., dim]
|
||||
from einops import rearrange
|
||||
return rearrange(emb, 'n d -> n 1 1 d')
|
||||
|
||||
|
||||
def _rotate_half(x):
|
||||
"""
|
||||
change sign so the last dimension becomes [-odd, +even]
|
||||
"""
|
||||
from einops import rearrange
|
||||
x = rearrange(x, '... (j d) -> ... j d', j=2)
|
||||
x1, x2 = x.unbind(dim=-2)
|
||||
return torch.cat((-x2, x1), dim=-1)
|
||||
|
||||
|
||||
def apply_rotary_pos_emb(t, freqs):
|
||||
"""
|
||||
input tensor t is of shape [seq_length, ..., dim]
|
||||
rotary positional embeding tensor freqs is of shape [seq_length, ..., dim]
|
||||
check https://kexue.fm/archives/8265 for detailed formulas
|
||||
"""
|
||||
rot_dim = freqs.shape[-1]
|
||||
# ideally t_pass is empty so rotary pos embedding is applied to all tensor t
|
||||
t, t_pass = t[..., :rot_dim], t[..., rot_dim:]
|
||||
|
||||
# first part is cosine component
|
||||
# second part is sine component, need to change signs with _rotate_half method
|
||||
t = (t * freqs.cos()) + (_rotate_half(t) * freqs.sin())
|
||||
return torch.cat((t, t_pass), dim=-1)
|
||||
18
ixformer_sdk/train/speedformer/model_replacer_mapping.py
Normal file
18
ixformer_sdk/train/speedformer/model_replacer_mapping.py
Normal file
@@ -0,0 +1,18 @@
|
||||
import torch
|
||||
|
||||
from ixformer.train.speedformer.policy.gpt2 import GPT2Replacer
|
||||
from ixformer.train.speedformer.policy.qwen2 import Qwen2Replacer
|
||||
from ixformer.train.speedformer.policy.llama import LlamaReplacer
|
||||
from ixformer.train.speedformer.policy.baichuan import BaichuanReplacer
|
||||
from ixformer.train.speedformer.policy.bloom import BloomReplacer
|
||||
from ixformer.train.speedformer.policy.chatglm import ChatglmReplacer
|
||||
|
||||
|
||||
ModelMapping = {
|
||||
"gpt2": GPT2Replacer,
|
||||
"qwen2": Qwen2Replacer,
|
||||
"llama": LlamaReplacer,
|
||||
"baichuan": BaichuanReplacer,
|
||||
"bloom": BloomReplacer,
|
||||
"chatglm": ChatglmReplacer
|
||||
}
|
||||
0
ixformer_sdk/train/speedformer/models/__init__.py
Normal file
0
ixformer_sdk/train/speedformer/models/__init__.py
Normal file
@@ -0,0 +1,68 @@
|
||||
# Copyright 2023 Baichuan Inc. All Rights Reserved.
|
||||
|
||||
# Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.
|
||||
#
|
||||
# This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
|
||||
# and OPT implementations in this library. It has been modified from its
|
||||
# original forms to accommodate minor architectural differences compared
|
||||
# to GPT-NeoX and OPT used by the Meta AI team that trained the model.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
from transformers.configuration_utils import PretrainedConfig
|
||||
from transformers.utils import logging
|
||||
|
||||
|
||||
logger = logging.get_logger(__name__)
|
||||
|
||||
|
||||
class BaichuanConfig(PretrainedConfig):
|
||||
model_type = "baichuan"
|
||||
keys_to_ignore_at_inference = ["past_key_values"]
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
vocab_size=125696,
|
||||
hidden_size=4096,
|
||||
intermediate_size=11008,
|
||||
num_hidden_layers=32,
|
||||
num_attention_heads=32,
|
||||
hidden_act="silu",
|
||||
max_position_embeddings=4096,
|
||||
initializer_range=0.02,
|
||||
rms_norm_eps=1e-6,
|
||||
use_cache=True,
|
||||
pad_token_id=0,
|
||||
bos_token_id=1,
|
||||
eos_token_id=2,
|
||||
tie_word_embeddings=False,
|
||||
**kwargs,
|
||||
):
|
||||
self.vocab_size = vocab_size
|
||||
self.max_position_embeddings = max_position_embeddings
|
||||
self.hidden_size = hidden_size
|
||||
self.intermediate_size = intermediate_size
|
||||
self.num_hidden_layers = num_hidden_layers
|
||||
self.num_attention_heads = num_attention_heads
|
||||
self.hidden_act = hidden_act
|
||||
self.initializer_range = initializer_range
|
||||
self.rms_norm_eps = rms_norm_eps
|
||||
self.use_cache = use_cache
|
||||
self.z_loss_weight = 0
|
||||
super().__init__(
|
||||
pad_token_id=pad_token_id,
|
||||
bos_token_id=bos_token_id,
|
||||
eos_token_id=eos_token_id,
|
||||
tie_word_embeddings=tie_word_embeddings,
|
||||
**kwargs,
|
||||
)
|
||||
@@ -0,0 +1,83 @@
|
||||
from typing import List
|
||||
from queue import Queue
|
||||
|
||||
import torch
|
||||
|
||||
|
||||
def build_chat_input(model, tokenizer, messages: List[dict], max_new_tokens: int=0):
|
||||
def _parse_messages(messages, split_role="user"):
|
||||
system, rounds = "", []
|
||||
round = []
|
||||
for i, message in enumerate(messages):
|
||||
if message["role"] == "system":
|
||||
assert i == 0
|
||||
system = message["content"]
|
||||
continue
|
||||
if message["role"] == split_role and round:
|
||||
rounds.append(round)
|
||||
round = []
|
||||
round.append(message)
|
||||
if round:
|
||||
rounds.append(round)
|
||||
return system, rounds
|
||||
|
||||
max_new_tokens = max_new_tokens or model.generation_config.max_new_tokens
|
||||
max_input_tokens = model.config.model_max_length - max_new_tokens
|
||||
system, rounds = _parse_messages(messages, split_role="user")
|
||||
system_tokens = tokenizer.encode(system)
|
||||
max_history_tokens = max_input_tokens - len(system_tokens)
|
||||
|
||||
history_tokens = []
|
||||
for round in rounds[::-1]:
|
||||
round_tokens = []
|
||||
for message in round:
|
||||
if message["role"] == "user":
|
||||
round_tokens.append(model.generation_config.user_token_id)
|
||||
else:
|
||||
round_tokens.append(model.generation_config.assistant_token_id)
|
||||
round_tokens.extend(tokenizer.encode(message["content"]))
|
||||
if len(history_tokens) == 0 or len(history_tokens) + len(round_tokens) <= max_history_tokens:
|
||||
history_tokens = round_tokens + history_tokens # concat left
|
||||
if len(history_tokens) < max_history_tokens:
|
||||
continue
|
||||
break
|
||||
|
||||
input_tokens = system_tokens + history_tokens
|
||||
if messages[-1]["role"] != "assistant":
|
||||
input_tokens.append(model.generation_config.assistant_token_id)
|
||||
input_tokens = input_tokens[-max_input_tokens:] # truncate left
|
||||
return torch.LongTensor([input_tokens]).to(model.device)
|
||||
|
||||
|
||||
class TextIterStreamer:
|
||||
def __init__(self, tokenizer, skip_prompt=False, skip_special_tokens=False):
|
||||
self.tokenizer = tokenizer
|
||||
self.skip_prompt = skip_prompt
|
||||
self.skip_special_tokens = skip_special_tokens
|
||||
self.tokens = []
|
||||
self.text_queue = Queue()
|
||||
self.next_tokens_are_prompt = True
|
||||
|
||||
def put(self, value):
|
||||
if self.skip_prompt and self.next_tokens_are_prompt:
|
||||
self.next_tokens_are_prompt = False
|
||||
else:
|
||||
if len(value.shape) > 1:
|
||||
value = value[0]
|
||||
self.tokens.extend(value.tolist())
|
||||
self.text_queue.put(
|
||||
self.tokenizer.decode(self.tokens, skip_special_tokens=self.skip_special_tokens))
|
||||
|
||||
def end(self):
|
||||
self.text_queue.put(None)
|
||||
|
||||
def __iter__(self):
|
||||
return self
|
||||
|
||||
def __next__(self):
|
||||
value = self.text_queue.get()
|
||||
if value is None:
|
||||
raise StopIteration()
|
||||
else:
|
||||
return value
|
||||
|
||||
@@ -0,0 +1,783 @@
|
||||
# Copyright 2023 Baichuan Inc. All Rights Reserved.
|
||||
|
||||
# Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.
|
||||
#
|
||||
# This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
|
||||
# and OPT implementations in this library. It has been modified from its
|
||||
# original forms to accommodate minor architectural differences compared
|
||||
# to GPT-NeoX and OPT used by the Meta AI team that trained the model.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
|
||||
from .configuration_baichuan import BaichuanConfig
|
||||
from .generation_utils import build_chat_input, TextIterStreamer
|
||||
|
||||
import math
|
||||
from typing import List, Optional, Tuple, Union
|
||||
from threading import Thread
|
||||
|
||||
import torch
|
||||
import torch.utils.checkpoint
|
||||
from torch import nn
|
||||
from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
|
||||
from torch.nn import functional as F
|
||||
from transformers import PreTrainedModel, PretrainedConfig
|
||||
from transformers.activations import ACT2FN
|
||||
from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
|
||||
from transformers.generation.utils import GenerationConfig
|
||||
from transformers.utils import logging, ContextManagers
|
||||
|
||||
import os
|
||||
from contextlib import contextmanager
|
||||
logger = logging.get_logger(__name__)
|
||||
|
||||
try:
|
||||
from xformers import ops as xops
|
||||
except ImportError:
|
||||
xops = None
|
||||
logger.warning(
|
||||
"Xformers is not installed correctly. If you want to use memory_efficient_attention to accelerate training use the following command to install Xformers\npip install xformers."
|
||||
)
|
||||
|
||||
|
||||
# Copied from transformers.models.bart.modeling_bart._make_causal_mask
|
||||
def _make_causal_mask(
|
||||
input_ids_shape: torch.Size, dtype: torch.dtype, device: torch.device, past_key_values_length: int = 0
|
||||
):
|
||||
"""
|
||||
Make causal mask used for bi-directional self-attention.
|
||||
"""
|
||||
bsz, tgt_len = input_ids_shape
|
||||
mask = torch.full((tgt_len, tgt_len), torch.tensor(torch.finfo(dtype).min, device=device), device=device)
|
||||
mask_cond = torch.arange(mask.size(-1), device=device)
|
||||
mask.masked_fill_(mask_cond < (mask_cond + 1).view(mask.size(-1), 1), 0)
|
||||
mask = mask.to(dtype)
|
||||
|
||||
if past_key_values_length > 0:
|
||||
mask = torch.cat([torch.zeros(tgt_len, past_key_values_length, dtype=dtype, device=device), mask], dim=-1)
|
||||
return mask[None, None, :, :].expand(bsz, 1, tgt_len, tgt_len + past_key_values_length)
|
||||
|
||||
def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None):
|
||||
"""
|
||||
Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.
|
||||
"""
|
||||
if len(mask.size()) == 3:
|
||||
bsz, src_len, _ = mask.size()
|
||||
tgt_len = tgt_len if tgt_len is not None else src_len
|
||||
expanded_mask = mask[:,None,:,:].expand(bsz, 1, tgt_len, src_len).to(dtype)
|
||||
else:
|
||||
bsz, src_len = mask.size()
|
||||
tgt_len = tgt_len if tgt_len is not None else src_len
|
||||
expanded_mask = mask[:, None, None, :].expand(bsz, 1, tgt_len, src_len).to(dtype)
|
||||
|
||||
inverted_mask = 1.0 - expanded_mask
|
||||
|
||||
return inverted_mask.masked_fill(inverted_mask.to(torch.bool), torch.finfo(dtype).min)
|
||||
|
||||
|
||||
class RMSNorm(nn.Module):
|
||||
def __init__(self, hidden_size, eps=1e-6):
|
||||
"""
|
||||
RMSNorm is equivalent to T5LayerNorm
|
||||
"""
|
||||
super().__init__()
|
||||
self.weight = nn.Parameter(torch.ones(hidden_size))
|
||||
self.variance_epsilon = eps
|
||||
|
||||
def forward(self, hidden_states):
|
||||
variance = hidden_states.to(torch.float32).pow(2).mean(-1, keepdim=True)
|
||||
hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
|
||||
|
||||
# convert into half-precision if necessary
|
||||
if self.weight.dtype in [torch.float16, torch.bfloat16]:
|
||||
hidden_states = hidden_states.to(self.weight.dtype)
|
||||
|
||||
return self.weight * hidden_states
|
||||
|
||||
|
||||
class RotaryEmbedding(torch.nn.Module):
|
||||
def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
|
||||
super().__init__()
|
||||
self.inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2).float().to(device) / dim))
|
||||
self.max_seq_len_cached = max_position_embeddings
|
||||
t = torch.arange(self.max_seq_len_cached, device=self.inv_freq.device, dtype=torch.float32)
|
||||
freqs = torch.outer(t, self.inv_freq)
|
||||
emb = torch.cat((freqs, freqs), dim=-1)
|
||||
self.cos_cached = emb.cos()[None, None, :, :].to(torch.float32)
|
||||
self.sin_cached = emb.sin()[None, None, :, :].to(torch.float32)
|
||||
def forward(self, x, seq_len=None):
|
||||
# x: [bs, num_attention_heads, seq_len, head_size]
|
||||
# This `if` block is unlikely to be run after we build sin/cos in `__init__`. Keep the logic here just in case.
|
||||
if seq_len > self.max_seq_len_cached:
|
||||
self.max_seq_len_cached = seq_len
|
||||
t = torch.arange(self.max_seq_len_cached, device=self.inv_freq.device, dtype=torch.float32)
|
||||
freqs = torch.outer(t, self.inv_freq)
|
||||
emb = torch.cat((freqs, freqs), dim=-1)
|
||||
self.cos_cached = emb.cos()[None, None, :, :].to(torch.float32).to(x.device)
|
||||
self.sin_cached = emb.sin()[None, None, :, :].to(torch.float32).to(x.device)
|
||||
elif self.cos_cached.device != x.device:
|
||||
self.cos_cached = self.cos_cached.to(x.device)
|
||||
self.sin_cached = self.sin_cached.to(x.device)
|
||||
return (
|
||||
self.cos_cached[:, :, :seq_len, ...],
|
||||
self.sin_cached[:, :, :seq_len, ...],
|
||||
)
|
||||
|
||||
|
||||
def rotate_half(x):
|
||||
"""Rotates half the hidden dims of the input."""
|
||||
x1 = x[..., : x.shape[-1] // 2]
|
||||
x2 = x[..., x.shape[-1] // 2:]
|
||||
return torch.cat((-x2, x1), dim=-1)
|
||||
|
||||
|
||||
def apply_rotary_pos_emb(q, k, cos_, sin_, position_ids):
|
||||
cos = cos_.squeeze(1).squeeze(0) # [seq_len, dim]
|
||||
sin = sin_.squeeze(1).squeeze(0) # [seq_len, dim]
|
||||
cos = cos[position_ids].unsqueeze(1) # [bs, 1, seq_len, dim]
|
||||
sin = sin[position_ids].unsqueeze(1) # [bs, 1, seq_len, dim]
|
||||
q_embed = (q.float() * cos) + (rotate_half(q.float()) * sin)
|
||||
k_embed = (k.float() * cos) + (rotate_half(k.float()) * sin)
|
||||
return q_embed.to(q.dtype), k_embed.to(k.dtype)
|
||||
|
||||
|
||||
class MLP(nn.Module):
|
||||
def __init__(
|
||||
self,
|
||||
hidden_size: int,
|
||||
intermediate_size: int,
|
||||
hidden_act: str,
|
||||
):
|
||||
super().__init__()
|
||||
self.gate_proj = nn.Linear(hidden_size, intermediate_size, bias=False)
|
||||
self.down_proj = nn.Linear(intermediate_size, hidden_size, bias=False)
|
||||
self.up_proj = nn.Linear(hidden_size, intermediate_size, bias=False)
|
||||
self.act_fn = ACT2FN[hidden_act]
|
||||
|
||||
def forward(self, x):
|
||||
return self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
|
||||
|
||||
|
||||
class Attention(nn.Module):
|
||||
"""Multi-headed attention from 'Attention Is All You Need' paper"""
|
||||
def __init__(self, config: BaichuanConfig):
|
||||
super().__init__()
|
||||
self.config = config
|
||||
self.hidden_size = config.hidden_size
|
||||
self.num_heads = config.num_attention_heads
|
||||
self.head_dim = self.hidden_size // self.num_heads
|
||||
self.max_position_embeddings = config.max_position_embeddings
|
||||
|
||||
if (self.head_dim * self.num_heads) != self.hidden_size:
|
||||
raise ValueError(
|
||||
f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
|
||||
f" and `num_heads`: {self.num_heads})."
|
||||
)
|
||||
self.W_pack = nn.Linear(self.hidden_size, 3 * self.hidden_size, bias=False)
|
||||
self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False)
|
||||
self.rotary_emb = RotaryEmbedding(self.head_dim, max_position_embeddings=self.max_position_embeddings)
|
||||
|
||||
def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
|
||||
return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
|
||||
|
||||
def forward(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
attention_mask: Optional[torch.Tensor] = None,
|
||||
position_ids: Optional[torch.LongTensor] = None,
|
||||
past_key_value: Optional[Tuple[torch.Tensor]] = None,
|
||||
output_attentions: bool = False,
|
||||
use_cache: bool = False,
|
||||
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
||||
bsz, q_len, _ = hidden_states.size()
|
||||
|
||||
proj = self.W_pack(hidden_states)
|
||||
proj = proj.unflatten(-1, (3, self.hidden_size)).unsqueeze(0).transpose(0, -2).squeeze(-2)
|
||||
query_states = proj[0].view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
|
||||
key_states = proj[1].view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
|
||||
value_states = proj[2].view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
|
||||
|
||||
kv_seq_len = key_states.shape[-2]
|
||||
if past_key_value is not None:
|
||||
kv_seq_len += past_key_value[0].shape[-2]
|
||||
cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
|
||||
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
|
||||
# [bsz, nh, t, hd]
|
||||
|
||||
if past_key_value is not None:
|
||||
# reuse k, v, self_attention
|
||||
key_states = torch.cat([past_key_value[0], key_states], dim=2)
|
||||
value_states = torch.cat([past_key_value[1], value_states], dim=2)
|
||||
|
||||
past_key_value = (key_states, value_states) if use_cache else None
|
||||
if xops is not None and self.training:
|
||||
attn_weights = None
|
||||
query_states = query_states.transpose(1, 2)
|
||||
key_states = key_states.transpose(1, 2)
|
||||
value_states = value_states.transpose(1, 2)
|
||||
attn_output = xops.memory_efficient_attention(
|
||||
query_states, key_states, value_states, attn_bias=xops.LowerTriangularMask()
|
||||
)
|
||||
else:
|
||||
with torch.backends.cuda.sdp_kernel(enable_flash=True, enable_math=True, enable_mem_efficient=True):
|
||||
attn_output = F.scaled_dot_product_attention(query_states, key_states, value_states, attn_mask = attention_mask)
|
||||
attn_output = attn_output.transpose(1, 2)
|
||||
attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
|
||||
attn_output = self.o_proj(attn_output)
|
||||
|
||||
if not output_attentions:
|
||||
attn_weights = None
|
||||
|
||||
return attn_output, attn_weights, past_key_value
|
||||
|
||||
|
||||
class DecoderLayer(nn.Module):
|
||||
def __init__(self, config: BaichuanConfig):
|
||||
super().__init__()
|
||||
self.hidden_size = config.hidden_size
|
||||
self.self_attn = Attention(config=config)
|
||||
self.mlp = MLP(
|
||||
hidden_size=self.hidden_size,
|
||||
intermediate_size=config.intermediate_size,
|
||||
hidden_act=config.hidden_act,
|
||||
)
|
||||
self.input_layernorm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
||||
self.post_attention_layernorm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
||||
|
||||
def forward(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
attention_mask: Optional[torch.Tensor] = None,
|
||||
position_ids: Optional[torch.LongTensor] = None,
|
||||
past_key_value: Optional[Tuple[torch.Tensor]] = None,
|
||||
output_attentions: Optional[bool] = False,
|
||||
use_cache: Optional[bool] = False,
|
||||
) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
|
||||
|
||||
residual = hidden_states
|
||||
|
||||
hidden_states = self.input_layernorm(hidden_states)
|
||||
|
||||
# Self Attention
|
||||
hidden_states, self_attn_weights, present_key_value = self.self_attn(
|
||||
hidden_states=hidden_states,
|
||||
attention_mask=attention_mask,
|
||||
position_ids=position_ids,
|
||||
past_key_value=past_key_value,
|
||||
output_attentions=output_attentions,
|
||||
use_cache=use_cache,
|
||||
)
|
||||
hidden_states = residual + hidden_states
|
||||
|
||||
# Fully Connected
|
||||
residual = hidden_states
|
||||
hidden_states = self.post_attention_layernorm(hidden_states)
|
||||
hidden_states = self.mlp(hidden_states)
|
||||
hidden_states = residual + hidden_states
|
||||
|
||||
outputs = (hidden_states,)
|
||||
|
||||
if output_attentions:
|
||||
outputs += (self_attn_weights,)
|
||||
|
||||
if use_cache:
|
||||
outputs += (present_key_value,)
|
||||
|
||||
return outputs
|
||||
|
||||
|
||||
class BaichuanPreTrainedModel(PreTrainedModel):
|
||||
config_class = BaichuanConfig
|
||||
base_model_prefix = "model"
|
||||
supports_gradient_checkpointing = True
|
||||
_no_split_modules = ["DecoderLayer"]
|
||||
_keys_to_ignore_on_load_unexpected = [r"decoder\.version"]
|
||||
|
||||
def _init_weights(self, module):
|
||||
std = self.config.initializer_range
|
||||
if isinstance(module, nn.Linear):
|
||||
module.weight.data.normal_(mean=0.0, std=std)
|
||||
if module.bias is not None:
|
||||
module.bias.data.zero_()
|
||||
elif isinstance(module, nn.Embedding):
|
||||
module.weight.data.normal_(mean=0.0, std=std)
|
||||
if module.padding_idx is not None:
|
||||
module.weight.data[module.padding_idx].zero_()
|
||||
|
||||
def _set_gradient_checkpointing(self, module, value=False):
|
||||
if isinstance(module, BaichuanModel):
|
||||
module.gradient_checkpointing = value
|
||||
|
||||
|
||||
class BaichuanModel(BaichuanPreTrainedModel):
|
||||
def __init__(self, config: BaichuanConfig):
|
||||
super().__init__(config)
|
||||
self.padding_idx = config.pad_token_id
|
||||
self.vocab_size = config.vocab_size
|
||||
|
||||
self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
|
||||
self.layers = nn.ModuleList([DecoderLayer(config) for _ in range(config.num_hidden_layers)])
|
||||
self.norm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
||||
|
||||
self.gradient_checkpointing = False
|
||||
# Initialize weights and apply final processing
|
||||
self.post_init()
|
||||
|
||||
def get_input_embeddings(self):
|
||||
return self.embed_tokens
|
||||
|
||||
def set_input_embeddings(self, value):
|
||||
self.embed_tokens = value
|
||||
|
||||
# Copied from transformers.models.bart.modeling_bart.BartDecoder._prepare_decoder_attention_mask
|
||||
def _prepare_decoder_attention_mask(self, attention_mask, input_shape, inputs_embeds, past_key_values_length):
|
||||
# create causal mask
|
||||
# [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
|
||||
combined_attention_mask = None
|
||||
if input_shape[-1] > 1:
|
||||
combined_attention_mask = _make_causal_mask(
|
||||
input_shape,
|
||||
inputs_embeds.dtype,
|
||||
device=inputs_embeds.device,
|
||||
past_key_values_length=past_key_values_length,
|
||||
)
|
||||
|
||||
if attention_mask is not None:
|
||||
# [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
|
||||
expanded_attn_mask = _expand_mask(attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1]).to(
|
||||
inputs_embeds.device
|
||||
)
|
||||
combined_attention_mask = (
|
||||
expanded_attn_mask if combined_attention_mask is None else expanded_attn_mask + combined_attention_mask
|
||||
)
|
||||
|
||||
return combined_attention_mask
|
||||
|
||||
def forward(
|
||||
self,
|
||||
input_ids: torch.LongTensor = None,
|
||||
attention_mask: Optional[torch.Tensor] = None,
|
||||
position_ids: Optional[torch.LongTensor] = None,
|
||||
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
||||
inputs_embeds: Optional[torch.FloatTensor] = None,
|
||||
use_cache: Optional[bool] = None,
|
||||
output_attentions: Optional[bool] = None,
|
||||
output_hidden_states: Optional[bool] = None,
|
||||
return_dict: Optional[bool] = None,
|
||||
) -> Union[Tuple, BaseModelOutputWithPast]:
|
||||
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
||||
output_hidden_states = (
|
||||
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
||||
)
|
||||
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
||||
|
||||
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
||||
|
||||
# retrieve input_ids and inputs_embeds
|
||||
if input_ids is not None and inputs_embeds is not None:
|
||||
raise ValueError("You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time")
|
||||
elif input_ids is not None:
|
||||
batch_size, seq_length = input_ids.shape
|
||||
elif inputs_embeds is not None:
|
||||
batch_size, seq_length, _ = inputs_embeds.shape
|
||||
else:
|
||||
raise ValueError("You have to specify either decoder_input_ids or decoder_inputs_embeds")
|
||||
|
||||
seq_length_with_past = seq_length
|
||||
past_key_values_length = 0
|
||||
|
||||
if past_key_values is not None:
|
||||
past_key_values_length = past_key_values[0][0].shape[2]
|
||||
seq_length_with_past = seq_length_with_past + past_key_values_length
|
||||
|
||||
if position_ids is None:
|
||||
device = input_ids.device if input_ids is not None else inputs_embeds.device
|
||||
position_ids = torch.arange(
|
||||
past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
|
||||
)
|
||||
position_ids = position_ids.unsqueeze(0).view(-1, seq_length)
|
||||
else:
|
||||
position_ids = position_ids.view(-1, seq_length).long()
|
||||
|
||||
if inputs_embeds is None:
|
||||
inputs_embeds = self.embed_tokens(input_ids)
|
||||
# embed positions
|
||||
if attention_mask is None:
|
||||
attention_mask = torch.ones(
|
||||
(batch_size, seq_length_with_past), dtype=torch.bool, device=inputs_embeds.device
|
||||
)
|
||||
attention_mask = self._prepare_decoder_attention_mask(
|
||||
attention_mask, (batch_size, seq_length), inputs_embeds, past_key_values_length
|
||||
)
|
||||
|
||||
hidden_states = inputs_embeds
|
||||
|
||||
if self.gradient_checkpointing and self.training:
|
||||
if use_cache:
|
||||
logger.warning_once(
|
||||
"`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
|
||||
)
|
||||
use_cache = False
|
||||
|
||||
# decoder layers
|
||||
all_hidden_states = () if output_hidden_states else None
|
||||
all_self_attns = () if output_attentions else None
|
||||
next_decoder_cache = () if use_cache else None
|
||||
|
||||
for idx, decoder_layer in enumerate(self.layers):
|
||||
if output_hidden_states:
|
||||
all_hidden_states += (hidden_states,)
|
||||
|
||||
past_key_value = past_key_values[idx] if past_key_values is not None else None
|
||||
|
||||
if self.gradient_checkpointing and self.training:
|
||||
|
||||
def create_custom_forward(module):
|
||||
def custom_forward(*inputs):
|
||||
# None for past_key_value
|
||||
return module(*inputs, output_attentions, None)
|
||||
|
||||
return custom_forward
|
||||
|
||||
layer_outputs = torch.utils.checkpoint.checkpoint(
|
||||
create_custom_forward(decoder_layer),
|
||||
hidden_states,
|
||||
attention_mask,
|
||||
position_ids,
|
||||
None,
|
||||
)
|
||||
else:
|
||||
layer_outputs = decoder_layer(
|
||||
hidden_states,
|
||||
attention_mask=attention_mask,
|
||||
position_ids=position_ids,
|
||||
past_key_value=past_key_value,
|
||||
output_attentions=output_attentions,
|
||||
use_cache=use_cache,
|
||||
)
|
||||
|
||||
hidden_states = layer_outputs[0]
|
||||
|
||||
if use_cache:
|
||||
next_decoder_cache += (layer_outputs[2 if output_attentions else 1],)
|
||||
|
||||
if output_attentions:
|
||||
all_self_attns += (layer_outputs[1],)
|
||||
|
||||
hidden_states = self.norm(hidden_states)
|
||||
|
||||
# add hidden states from the last decoder layer
|
||||
if output_hidden_states:
|
||||
all_hidden_states += (hidden_states,)
|
||||
|
||||
next_cache = next_decoder_cache if use_cache else None
|
||||
if not return_dict:
|
||||
return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
|
||||
return BaseModelOutputWithPast(
|
||||
last_hidden_state=hidden_states,
|
||||
past_key_values=next_cache,
|
||||
hidden_states=all_hidden_states,
|
||||
attentions=all_self_attns,
|
||||
)
|
||||
|
||||
|
||||
class NormHead(nn.Module):
|
||||
def __init__(self, hidden_size, vocab_size, bias=False):
|
||||
super().__init__()
|
||||
self.weight = nn.Parameter(torch.empty((vocab_size, hidden_size)))
|
||||
nn.init.kaiming_uniform_(self.weight, a=math.sqrt(5))
|
||||
self.first_flag = True
|
||||
|
||||
def forward(self, hidden_states):
|
||||
if self.training:
|
||||
norm_weight = nn.functional.normalize(self.weight)
|
||||
elif self.first_flag:
|
||||
self.first_flag = False
|
||||
self.weight = nn.Parameter(nn.functional.normalize(self.weight))
|
||||
norm_weight = self.weight
|
||||
else:
|
||||
norm_weight = self.weight
|
||||
return nn.functional.linear(hidden_states, norm_weight)
|
||||
|
||||
_init_weights = True
|
||||
@contextmanager
|
||||
def no_init_weights(_enable=True):
|
||||
global _init_weights
|
||||
old_init_weights = _init_weights
|
||||
if _enable:
|
||||
_init_weights = False
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
_init_weights = old_init_weights
|
||||
|
||||
class BaichuanForCausalLM(BaichuanPreTrainedModel):
|
||||
def __init__(self, config, *model_args, **model_kwargs):
|
||||
super().__init__(config, *model_args, **model_kwargs)
|
||||
self.model = BaichuanModel(config)
|
||||
|
||||
self.lm_head = NormHead(config.hidden_size, config.vocab_size, bias=False)
|
||||
if hasattr(config, "quantization_config") and config.quantization_config['load_in_4bit']:
|
||||
try:
|
||||
from .quantizer import quantize_offline, init_model_weight_int4
|
||||
except ImportError:
|
||||
raise ImportError(f"Needs QLinear to run quantize.")
|
||||
quantize_offline(self, 4)
|
||||
# Initialize weights and apply final processing
|
||||
self.post_init()
|
||||
|
||||
def get_input_embeddings(self):
|
||||
return self.model.embed_tokens
|
||||
|
||||
def set_input_embeddings(self, value):
|
||||
self.model.embed_tokens = value
|
||||
|
||||
def get_output_embeddings(self):
|
||||
return self.lm_head
|
||||
|
||||
def set_output_embeddings(self, new_embeddings):
|
||||
self.lm_head = new_embeddings
|
||||
|
||||
def set_decoder(self, decoder):
|
||||
self.model = decoder
|
||||
|
||||
def get_decoder(self):
|
||||
return self.model
|
||||
|
||||
@classmethod
|
||||
def from_pretrained(
|
||||
cls,
|
||||
pretrained_model_name_or_path: Optional[Union[str, os.PathLike]],
|
||||
*model_args,
|
||||
config: Optional[Union[PretrainedConfig, str, os.PathLike]] = None,
|
||||
cache_dir: Optional[Union[str, os.PathLike]] = None,
|
||||
ignore_mismatched_sizes: bool = False,
|
||||
force_download: bool = False,
|
||||
local_files_only: bool = False,
|
||||
token: Optional[Union[str, bool]] = None,
|
||||
revision: str = "main",
|
||||
use_safetensors: bool = None,
|
||||
**kwargs,
|
||||
):
|
||||
# Load config if we don't provide a configuration
|
||||
if not isinstance(config, PretrainedConfig):
|
||||
config_path = config if config is not None else pretrained_model_name_or_path
|
||||
config, model_kwargs = cls.config_class.from_pretrained(
|
||||
config_path,
|
||||
cache_dir=cache_dir,
|
||||
return_unused_kwargs=True,
|
||||
force_download=force_download,
|
||||
resume_download=False,
|
||||
proxies=None,
|
||||
local_files_only=local_files_only,
|
||||
token=token,
|
||||
revision=revision,
|
||||
subfolder="",
|
||||
_from_auto=False,
|
||||
_from_pipeline=None,
|
||||
**kwargs,
|
||||
)
|
||||
else:
|
||||
model_kwargs = kwargs
|
||||
|
||||
if hasattr(config, "quantization_config") and config.quantization_config['load_in_4bit']:
|
||||
try:
|
||||
from .quantizer import init_model_weight_int4
|
||||
from accelerate import init_empty_weights, dispatch_model, infer_auto_device_map
|
||||
from accelerate.utils import CustomDtype
|
||||
from accelerate.utils import get_balanced_memory
|
||||
except ImportError:
|
||||
raise ImportError(f"Needs import model weight init func to run quantize.")
|
||||
# Instantiate model.
|
||||
init_contexts = [no_init_weights(_enable=True)]
|
||||
init_contexts.append(init_empty_weights())
|
||||
with ContextManagers(init_contexts):
|
||||
model = cls(config)
|
||||
|
||||
model_file = os.path.join(pretrained_model_name_or_path, 'pytorch_model.bin')
|
||||
state_dict = torch.load(model_file, map_location="cpu")
|
||||
model.is_quantized = True
|
||||
|
||||
device_map = kwargs.pop("device_map", None)
|
||||
torch_dtype = kwargs.pop("torch_dtype", None)
|
||||
|
||||
kwargs = {"no_split_module_classes": model._no_split_modules}
|
||||
target_dtype = CustomDtype.INT4
|
||||
max_memory = get_balanced_memory(
|
||||
model,
|
||||
dtype=target_dtype,
|
||||
low_zero=(device_map == "balanced_low_0"),
|
||||
max_memory=None,
|
||||
**kwargs,
|
||||
)
|
||||
kwargs["max_memory"] = max_memory
|
||||
|
||||
device_map = infer_auto_device_map(model, dtype=target_dtype, **kwargs)
|
||||
model = init_model_weight_int4(config, model, state_dict)
|
||||
|
||||
# Set model in evaluation mode to deactivate DropOut modules by default
|
||||
model.eval()
|
||||
# If it is a model with generation capabilities, attempt to load the generation config
|
||||
if model.can_generate():
|
||||
try:
|
||||
model.generation_config = GenerationConfig.from_pretrained(
|
||||
pretrained_model_name_or_path,
|
||||
cache_dir=cache_dir,
|
||||
force_download=force_download,
|
||||
resume_download=False,
|
||||
proxies=None,
|
||||
local_files_only=local_files_only,
|
||||
token=token,
|
||||
revision=revision,
|
||||
subfolder="",
|
||||
_from_auto=False,
|
||||
_from_pipeline=None,
|
||||
**kwargs,
|
||||
)
|
||||
except (OSError, TypeError):
|
||||
logger.info(
|
||||
"Generation config file not found, using a generation config created from the model config."
|
||||
)
|
||||
pass
|
||||
|
||||
if device_map is not None:
|
||||
dispatch_model(model, device_map=device_map)
|
||||
|
||||
return model
|
||||
return super(BaichuanForCausalLM, cls).from_pretrained(pretrained_model_name_or_path, *model_args,
|
||||
config=config, cache_dir=cache_dir, ignore_mismatched_sizes=ignore_mismatched_sizes,
|
||||
force_download=force_download, local_files_only=local_files_only, token=token, revision=revision,
|
||||
use_safetensors=use_safetensors, **kwargs)
|
||||
|
||||
def forward(
|
||||
self,
|
||||
input_ids: torch.LongTensor = None,
|
||||
attention_mask: Optional[torch.Tensor] = None,
|
||||
position_ids: Optional[torch.LongTensor] = None,
|
||||
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
||||
inputs_embeds: Optional[torch.FloatTensor] = None,
|
||||
labels: Optional[torch.LongTensor] = None,
|
||||
use_cache: Optional[bool] = None,
|
||||
output_attentions: Optional[bool] = None,
|
||||
output_hidden_states: Optional[bool] = None,
|
||||
return_dict: Optional[bool] = None,
|
||||
) -> Union[Tuple, CausalLMOutputWithPast]:
|
||||
|
||||
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
||||
output_hidden_states = (
|
||||
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
||||
)
|
||||
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
||||
|
||||
# decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
|
||||
outputs = self.model(
|
||||
input_ids=input_ids,
|
||||
attention_mask=attention_mask,
|
||||
position_ids=position_ids,
|
||||
past_key_values=past_key_values,
|
||||
inputs_embeds=inputs_embeds,
|
||||
use_cache=use_cache,
|
||||
output_attentions=output_attentions,
|
||||
output_hidden_states=output_hidden_states,
|
||||
return_dict=return_dict,
|
||||
)
|
||||
|
||||
hidden_states = outputs[0]
|
||||
logits = self.lm_head(hidden_states)
|
||||
loss = None
|
||||
if labels is not None:
|
||||
# Shift so that tokens < n predict n
|
||||
shift_logits = logits[..., :-1, :].contiguous()
|
||||
shift_labels = labels[..., 1:].contiguous()
|
||||
# Flatten the tokens
|
||||
loss_fct = CrossEntropyLoss()
|
||||
shift_logits = shift_logits.view(-1, self.config.vocab_size)
|
||||
shift_labels = shift_labels.view(-1)
|
||||
softmax_normalizer = shift_logits.max(-1).values ** 2
|
||||
z_loss = self.config.z_loss_weight * softmax_normalizer.mean()
|
||||
# Enable model parallelism
|
||||
shift_labels = shift_labels.to(shift_logits.device)
|
||||
loss = loss_fct(shift_logits, shift_labels) + z_loss
|
||||
|
||||
if not return_dict:
|
||||
output = (logits,) + outputs[1:]
|
||||
return (loss,) + output if loss is not None else output
|
||||
|
||||
return CausalLMOutputWithPast(
|
||||
loss=loss,
|
||||
logits=logits,
|
||||
past_key_values=outputs.past_key_values,
|
||||
hidden_states=outputs.hidden_states,
|
||||
attentions=outputs.attentions,
|
||||
)
|
||||
|
||||
def prepare_inputs_for_generation(
|
||||
self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs
|
||||
):
|
||||
if past_key_values:
|
||||
input_ids = input_ids[:, -1:]
|
||||
|
||||
position_ids = kwargs.get("position_ids", None)
|
||||
if attention_mask is not None and position_ids is None:
|
||||
# create position_ids on the fly for batch generation
|
||||
position_ids = attention_mask.long().cumsum(-1) - 1
|
||||
position_ids.masked_fill_(attention_mask == 0, 1)
|
||||
if past_key_values:
|
||||
position_ids = position_ids[:, -1].unsqueeze(-1)
|
||||
|
||||
# if `inputs_embeds` are passed, we only want to use them in the 1st generation step
|
||||
if inputs_embeds is not None and past_key_values is None:
|
||||
model_inputs = {"inputs_embeds": inputs_embeds}
|
||||
else:
|
||||
model_inputs = {"input_ids": input_ids}
|
||||
|
||||
model_inputs.update(
|
||||
{
|
||||
"position_ids": position_ids,
|
||||
"past_key_values": past_key_values,
|
||||
"use_cache": kwargs.get("use_cache"),
|
||||
"attention_mask": attention_mask,
|
||||
}
|
||||
)
|
||||
return model_inputs
|
||||
|
||||
@staticmethod
|
||||
def _reorder_cache(past_key_values, beam_idx):
|
||||
reordered_past = ()
|
||||
for layer_past in past_key_values:
|
||||
reordered_past += (tuple(past_state.index_select(0, beam_idx) for past_state in layer_past),)
|
||||
return reordered_past
|
||||
|
||||
def quantize(self, bits: int):
|
||||
try:
|
||||
from .quantizer import quantize_online
|
||||
except ImportError:
|
||||
raise ImportError(f"Needs QLinear to run quantize.")
|
||||
return quantize_online(self, bits)
|
||||
|
||||
def chat(self, tokenizer, messages: List[dict], stream=False,
|
||||
generation_config: Optional[GenerationConfig]=None):
|
||||
generation_config = generation_config or self.generation_config
|
||||
input_ids = build_chat_input(self, tokenizer, messages, generation_config.max_new_tokens)
|
||||
if stream:
|
||||
streamer = TextIterStreamer(tokenizer, skip_prompt=True, skip_special_tokens=True)
|
||||
Thread(target=self.generate, kwargs=dict(
|
||||
inputs=input_ids, streamer=streamer,
|
||||
generation_config=generation_config,
|
||||
)).start()
|
||||
return streamer
|
||||
else:
|
||||
outputs = self.generate(input_ids, generation_config=generation_config)
|
||||
response = tokenizer.decode(outputs[0][len(input_ids[0]):], skip_special_tokens=True)
|
||||
return response
|
||||
210
ixformer_sdk/train/speedformer/models/baichuan/quantizer.py
Normal file
210
ixformer_sdk/train/speedformer/models/baichuan/quantizer.py
Normal file
@@ -0,0 +1,210 @@
|
||||
import bitsandbytes as bnb
|
||||
from bitsandbytes.nn.modules import Params4bit, Int8Params
|
||||
import torch
|
||||
|
||||
def Params4bitCuda(self, device):
|
||||
self.data = self.data.cuda(device)
|
||||
self.quant_state[0] = self.quant_state[0].cuda(device)
|
||||
self.quant_state[4][0] = self.quant_state[4][0].cuda(device)
|
||||
self.quant_state[4][1][0] = self.quant_state[4][1][0].cuda(device)
|
||||
self.quant_state[4][1][1] = self.quant_state[4][1][1].cuda(device)
|
||||
|
||||
self.quant_state[6] = self.quant_state[6].cuda(device)
|
||||
return self
|
||||
|
||||
class Linear4bitOnline(torch.nn.Module):
|
||||
def __init__(self, weight, bias, quant_type):
|
||||
super().__init__()
|
||||
self.weight = Params4bit(
|
||||
weight.data, requires_grad=False, compress_statistics=True, quant_type=quant_type
|
||||
)
|
||||
self.compute_dtype = None
|
||||
#self.weight.cuda(weight.device)
|
||||
self.bias = bias
|
||||
|
||||
def forward(self, x: torch.Tensor):
|
||||
# weights are cast automatically as Int8Params, but the bias has to be cast manually
|
||||
if self.bias is not None and self.bias.dtype != x.dtype:
|
||||
self.bias.data = self.bias.data.to(x.dtype)
|
||||
|
||||
if getattr(self.weight, "quant_state", None) is None:
|
||||
print(
|
||||
"FP4 quantization state not initialized. Please call .cuda() or .to(device) on the LinearFP4 layer first."
|
||||
)
|
||||
inp_dtype = x.dtype
|
||||
if self.compute_dtype is not None:
|
||||
x = x.to(self.compute_dtype)
|
||||
|
||||
bias = None if self.bias is None else self.bias.to(self.compute_dtype)
|
||||
out = bnb.matmul_4bit(
|
||||
x, self.weight.t(), bias=bias, quant_state=self.weight.quant_state
|
||||
)
|
||||
|
||||
out = out.to(inp_dtype)
|
||||
|
||||
return out
|
||||
|
||||
class Linear8bitLtOnline(torch.nn.Module):
|
||||
def __init__(
|
||||
self,
|
||||
weight,
|
||||
bias,
|
||||
has_fp16_weights=True,
|
||||
memory_efficient_backward=False,
|
||||
threshold=0.0,
|
||||
index=None,
|
||||
):
|
||||
super().__init__()
|
||||
assert (
|
||||
not memory_efficient_backward
|
||||
), "memory_efficient_backward is no longer required and the argument is deprecated in 0.37.0 and will be removed in 0.39.0"
|
||||
self.state = bnb.MatmulLtState()
|
||||
self.index = index
|
||||
|
||||
# Necessary for stacked layers
|
||||
self.state.threshold = threshold
|
||||
self.state.has_fp16_weights = has_fp16_weights
|
||||
self.state.memory_efficient_backward = memory_efficient_backward
|
||||
if threshold > 0.0 and not has_fp16_weights:
|
||||
self.state.use_pool = True
|
||||
|
||||
self.weight = Int8Params(
|
||||
weight.data,
|
||||
has_fp16_weights=has_fp16_weights,
|
||||
requires_grad=has_fp16_weights,
|
||||
)
|
||||
self.bias = bias
|
||||
|
||||
def init_8bit_state(self):
|
||||
self.state.CB = self.weight.CB
|
||||
self.state.SCB = self.weight.SCB
|
||||
self.weight.CB = None
|
||||
self.weight.SCB = None
|
||||
|
||||
def forward(self, x: torch.Tensor):
|
||||
self.state.is_training = self.training
|
||||
if self.weight.CB is not None:
|
||||
self.init_8bit_state()
|
||||
|
||||
# weights are cast automatically as Int8Params, but the bias has to be cast manually
|
||||
if self.bias is not None and self.bias.dtype != x.dtype:
|
||||
self.bias.data = self.bias.data.to(x.dtype)
|
||||
|
||||
out = bnb.matmul(x, self.weight, bias=self.bias, state=self.state)
|
||||
|
||||
if not self.state.has_fp16_weights:
|
||||
if self.state.CB is not None and self.state.CxB is not None:
|
||||
# we converted 8-bit row major to turing/ampere format in the first inference pass
|
||||
# we no longer need the row-major weight
|
||||
del self.state.CB
|
||||
self.weight.data = self.state.CxB
|
||||
return out
|
||||
|
||||
def quantize_offline(model, bits: int):
|
||||
assert (bits == 4), f'bits: {bits} is not supported'
|
||||
|
||||
for i, layer in enumerate(model.model.layers):
|
||||
layer.self_attn.W_pack = bnb.nn.Linear4bit(
|
||||
layer.self_attn.W_pack.weight.shape[1],
|
||||
layer.self_attn.W_pack.weight.shape[0],
|
||||
False,
|
||||
torch.float16,
|
||||
compress_statistics=True,
|
||||
quant_type="nf4",
|
||||
)
|
||||
layer.self_attn.o_proj = bnb.nn.Linear4bit(
|
||||
layer.self_attn.o_proj.weight.shape[1],
|
||||
layer.self_attn.o_proj.weight.shape[0],
|
||||
False,
|
||||
torch.float16,
|
||||
compress_statistics=True,
|
||||
quant_type="nf4",
|
||||
)
|
||||
|
||||
layer.mlp.gate_proj = bnb.nn.Linear4bit(
|
||||
layer.mlp.gate_proj.weight.shape[1],
|
||||
layer.mlp.gate_proj.weight.shape[0],
|
||||
False,
|
||||
torch.float16,
|
||||
compress_statistics=True,
|
||||
quant_type="nf4",
|
||||
)
|
||||
layer.mlp.down_proj = bnb.nn.Linear4bit(
|
||||
layer.mlp.down_proj.weight.shape[1],
|
||||
layer.mlp.down_proj.weight.shape[0],
|
||||
False,
|
||||
torch.float16,
|
||||
compress_statistics=True,
|
||||
quant_type="nf4",
|
||||
)
|
||||
layer.mlp.up_proj = bnb.nn.Linear4bit(
|
||||
layer.mlp.up_proj.weight.shape[1],
|
||||
layer.mlp.up_proj.weight.shape[0],
|
||||
False,
|
||||
torch.float16,
|
||||
compress_statistics=True,
|
||||
quant_type="nf4",
|
||||
)
|
||||
return model
|
||||
|
||||
def quantize_online(model, bits: int):
|
||||
def quant(weight, bias=None):
|
||||
if bits == 8:
|
||||
linear = Linear8bitLtOnline(
|
||||
weight,
|
||||
bias,
|
||||
has_fp16_weights=False,
|
||||
threshold=6.0,
|
||||
)
|
||||
if bias is not None:
|
||||
linear.bias = torch.nn.Parameter(bias)
|
||||
elif bits == 4:
|
||||
linear = Linear4bitOnline(
|
||||
weight,
|
||||
bias,
|
||||
quant_type="nf4", #fp4/nf4
|
||||
)
|
||||
else:
|
||||
raise ValueError("quantize only support 4/8 bit")
|
||||
return linear
|
||||
|
||||
for i, layer in enumerate(model.model.layers):
|
||||
layer.self_attn.W_pack = quant(layer.self_attn.W_pack.weight)
|
||||
layer.self_attn.o_proj = quant(layer.self_attn.o_proj.weight)
|
||||
layer.mlp.gate_proj = quant(layer.mlp.gate_proj.weight)
|
||||
layer.mlp.down_proj = quant(layer.mlp.down_proj.weight)
|
||||
layer.mlp.up_proj = quant(layer.mlp.up_proj.weight)
|
||||
return model
|
||||
|
||||
def init_model_weight_int4(config, model, state_dict):
|
||||
#replace Params4bit.cuda with Params4bitCuda
|
||||
Params4bit.cuda = Params4bitCuda
|
||||
|
||||
for i in range(config.num_hidden_layers):
|
||||
weight_data = state_dict[f'model.layers.{i}.self_attn.W_pack.weight.data']
|
||||
weight_quant_state = state_dict[f'model.layers.{i}.self_attn.W_pack.weight.quant_state']
|
||||
model.model.layers[i].self_attn.W_pack.weight = Params4bit(weight_data, requires_grad=False, quant_state=weight_quant_state)
|
||||
|
||||
weight_data = state_dict[f'model.layers.{i}.self_attn.o_proj.weight.data']
|
||||
weight_quant_state = state_dict[f'model.layers.{i}.self_attn.o_proj.weight.quant_state']
|
||||
model.model.layers[i].self_attn.o_proj.weight = Params4bit(weight_data, requires_grad=False, quant_state=weight_quant_state)
|
||||
|
||||
weight_data = state_dict[f'model.layers.{i}.mlp.gate_proj.weight.data']
|
||||
weight_quant_state = state_dict[f'model.layers.{i}.mlp.gate_proj.weight.quant_state']
|
||||
model.model.layers[i].mlp.gate_proj.weight = Params4bit(weight_data, requires_grad=False, quant_state=weight_quant_state)
|
||||
|
||||
weight_data = state_dict[f'model.layers.{i}.mlp.up_proj.weight.data']
|
||||
weight_quant_state = state_dict[f'model.layers.{i}.mlp.up_proj.weight.quant_state']
|
||||
model.model.layers[i].mlp.up_proj.weight = Params4bit(weight_data, requires_grad=False, quant_state=weight_quant_state)
|
||||
|
||||
weight_data = state_dict[f'model.layers.{i}.mlp.down_proj.weight.data']
|
||||
weight_quant_state = state_dict[f'model.layers.{i}.mlp.down_proj.weight.quant_state']
|
||||
model.model.layers[i].mlp.down_proj.weight = Params4bit(weight_data, requires_grad=False, quant_state=weight_quant_state)
|
||||
|
||||
model.model.layers[i].input_layernorm.weight = state_dict[f'model.layers.{i}.input_layernorm.weight']
|
||||
model.model.layers[i].post_attention_layernorm.weight = state_dict[f'model.layers.{i}.post_attention_layernorm.weight']
|
||||
|
||||
model.model.embed_tokens.weight = state_dict['model.embed_tokens.weight']
|
||||
model.model.norm.weight = state_dict['model.norm.weight']
|
||||
model.lm_head.weight = state_dict['lm_head.weight']
|
||||
return model
|
||||
@@ -0,0 +1,242 @@
|
||||
# coding=utf-8
|
||||
# Copyright 2022 the Big Science Workshop and HuggingFace Inc. team. All rights reserved.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
""" Bloom configuration"""
|
||||
from collections import OrderedDict
|
||||
from typing import TYPE_CHECKING, Any, List, Mapping, Optional
|
||||
|
||||
from packaging import version
|
||||
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from ... import PreTrainedTokenizer, TensorType
|
||||
|
||||
from transformers.configuration_utils import PretrainedConfig
|
||||
from transformers.onnx import OnnxConfigWithPast, PatchingSpec
|
||||
from transformers.utils import is_torch_available, logging
|
||||
|
||||
|
||||
logger = logging.get_logger(__name__)
|
||||
|
||||
BLOOM_PRETRAINED_CONFIG_ARCHIVE_MAP = {
|
||||
"bigscience/bloom": "https://huggingface.co/bigscience/bloom/resolve/main/config.json",
|
||||
"bigscience/bloom-560m": "https://huggingface.co/bigscience/bloom-560m/blob/main/config.json",
|
||||
"bigscience/bloom-1b1": "https://huggingface.co/bigscience/bloom-1b1/blob/main/config.json",
|
||||
"bigscience/bloom-1b7": "https://huggingface.co/bigscience/bloom-1b7/blob/main/config.json",
|
||||
"bigscience/bloom-3b": "https://huggingface.co/bigscience/bloom-3b/blob/main/config.json",
|
||||
"bigscience/bloom-7b1": "https://huggingface.co/bigscience/bloom-7b1/blob/main/config.json",
|
||||
}
|
||||
|
||||
|
||||
class BloomConfig(PretrainedConfig):
|
||||
"""
|
||||
This is the configuration class to store the configuration of a [`BloomModel`]. It is used to instantiate a Bloom
|
||||
model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
|
||||
defaults will yield a similar configuration to the Bloom architecture
|
||||
[bigscience/bloom](https://huggingface.co/bigscience/bloom).
|
||||
|
||||
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
||||
documentation from [`PretrainedConfig`] for more information.
|
||||
|
||||
|
||||
Args:
|
||||
vocab_size (`int`, *optional*, defaults to 250880):
|
||||
Vocabulary size of the Bloom model. Defines the maximum number of different tokens that can be represented
|
||||
by the `inputs_ids` passed when calling [`BloomModel`]. Check [this
|
||||
discussion](https://huggingface.co/bigscience/bloom/discussions/120#633d28389addb8530b406c2a) on how the
|
||||
`vocab_size` has been defined.
|
||||
hidden_size (`int`, *optional*, defaults to 64):
|
||||
Dimensionality of the embeddings and hidden states.
|
||||
n_layer (`int`, *optional*, defaults to 2):
|
||||
Number of hidden layers in the Transformer encoder.
|
||||
n_head (`int`, *optional*, defaults to 8):
|
||||
Number of attention heads for each attention layer in the Transformer encoder.
|
||||
layer_norm_epsilon (`float`, *optional*, defaults to 1e-5):
|
||||
The epsilon to use in the layer normalization layers.
|
||||
initializer_range (`float`, *optional*, defaults to 0.02):
|
||||
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
||||
apply_residual_connection_post_layernorm (`bool`, *optional*, defaults to `False`):
|
||||
If enabled, use the layer norm of the hidden states as the residual in the transformer blocks
|
||||
hidden_dropout (`float`, *optional*, defaults to 0.1):
|
||||
Dropout rate of the dropout function on the bias dropout.
|
||||
attention_dropout (`float`, *optional*, defaults to 0.1):
|
||||
Dropout rate applied to the attention probs
|
||||
use_cache (`bool`, *optional*, defaults to `True`):
|
||||
Whether or not the model should return the last key/values attentions (not used by all models).
|
||||
pretraining_tp (`int`, *optional*, defaults to `1`):
|
||||
Experimental feature. Tensor parallelism rank used during pretraining with Megatron. Please refer to [this
|
||||
document](https://huggingface.co/docs/transformers/parallelism) to understand more about it. This value is
|
||||
necessary to ensure exact reproducibility of the pretraining results. Please refer to [this
|
||||
issue](https://github.com/pytorch/pytorch/issues/76232). Note also that this is enabled only when
|
||||
`slow_but_exact=True`.
|
||||
slow_but_exact (`bool`, *optional*, defaults to `False`):
|
||||
Experimental feature. Whether to use slow but exact implementation of the attention mechanism. While
|
||||
merging the TP rank tensors, due to slicing operations the results may be slightly different between the
|
||||
model trained on Megatron and our model. Please refer to [this
|
||||
issue](https://github.com/pytorch/pytorch/issues/76232). A solution to obtain more accurate results is to
|
||||
enable this feature. Enabling this will hurt the computational time of the inference. Will be probably
|
||||
resolved in the future once the main model has been fine-tuned with TP_rank=1.
|
||||
|
||||
Example:
|
||||
|
||||
```python
|
||||
>>> from transformers import BloomConfig, BloomModel
|
||||
|
||||
>>> # Initializing a Bloom configuration
|
||||
>>> configuration = BloomConfig()
|
||||
|
||||
>>> # Initializing a model (with random weights) from the configuration
|
||||
>>> model = BloomModel(configuration)
|
||||
|
||||
>>> # Accessing the model configuration
|
||||
>>> configuration = model.config
|
||||
```"""
|
||||
|
||||
model_type = "bloom"
|
||||
keys_to_ignore_at_inference = ["past_key_values"]
|
||||
attribute_map = {
|
||||
"num_hidden_layers": "n_layer",
|
||||
"num_attention_heads": "n_head",
|
||||
}
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
vocab_size=250880,
|
||||
hidden_size=64,
|
||||
n_layer=2,
|
||||
n_head=8,
|
||||
layer_norm_epsilon=1e-5,
|
||||
initializer_range=0.02,
|
||||
use_cache=True,
|
||||
bos_token_id=1,
|
||||
eos_token_id=2,
|
||||
apply_residual_connection_post_layernorm=False,
|
||||
hidden_dropout=0.0,
|
||||
attention_dropout=0.0,
|
||||
pretraining_tp=1, # TP rank used when training with megatron
|
||||
slow_but_exact=False,
|
||||
**kwargs,
|
||||
):
|
||||
self.vocab_size = vocab_size
|
||||
# Backward compatibility with n_embed kwarg
|
||||
n_embed = kwargs.pop("n_embed", None)
|
||||
self.hidden_size = hidden_size if n_embed is None else n_embed
|
||||
self.n_layer = n_layer
|
||||
self.n_head = n_head
|
||||
self.layer_norm_epsilon = layer_norm_epsilon
|
||||
self.initializer_range = initializer_range
|
||||
self.use_cache = use_cache
|
||||
self.pretraining_tp = pretraining_tp
|
||||
self.apply_residual_connection_post_layernorm = apply_residual_connection_post_layernorm
|
||||
self.hidden_dropout = hidden_dropout
|
||||
self.attention_dropout = attention_dropout
|
||||
|
||||
self.bos_token_id = bos_token_id
|
||||
self.eos_token_id = eos_token_id
|
||||
self.slow_but_exact = slow_but_exact
|
||||
|
||||
super().__init__(bos_token_id=bos_token_id, eos_token_id=eos_token_id, **kwargs)
|
||||
|
||||
|
||||
class BloomOnnxConfig(OnnxConfigWithPast):
|
||||
torch_onnx_minimum_version = version.parse("1.12")
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
config: PretrainedConfig,
|
||||
task: str = "default",
|
||||
patching_specs: List[PatchingSpec] = None,
|
||||
use_past: bool = False,
|
||||
):
|
||||
super().__init__(config, task=task, patching_specs=patching_specs, use_past=use_past)
|
||||
if not getattr(self._config, "pad_token_id", None):
|
||||
# TODO: how to do that better?
|
||||
self._config.pad_token_id = 0
|
||||
|
||||
@property
|
||||
def inputs(self) -> Mapping[str, Mapping[int, str]]:
|
||||
common_inputs = OrderedDict({"input_ids": {0: "batch", 1: "sequence"}})
|
||||
if self.use_past:
|
||||
# BLOOM stores values on dynamic axis 2. For more details see: https://github.com/huggingface/transformers/pull/18344
|
||||
self.fill_with_past_key_values_(common_inputs, direction="inputs", inverted_values_shape=True)
|
||||
common_inputs["attention_mask"] = {0: "batch", 1: "past_sequence + sequence"}
|
||||
else:
|
||||
common_inputs["attention_mask"] = {0: "batch", 1: "sequence"}
|
||||
|
||||
return common_inputs
|
||||
|
||||
@property
|
||||
def num_layers(self) -> int:
|
||||
return self._config.n_layer
|
||||
|
||||
@property
|
||||
def num_attention_heads(self) -> int:
|
||||
return self._config.n_head
|
||||
|
||||
@property
|
||||
def atol_for_validation(self) -> float:
|
||||
return 1e-3
|
||||
|
||||
def generate_dummy_inputs(
|
||||
self,
|
||||
tokenizer: "PreTrainedTokenizer",
|
||||
batch_size: int = -1,
|
||||
seq_length: int = -1,
|
||||
is_pair: bool = False,
|
||||
framework: Optional["TensorType"] = None,
|
||||
) -> Mapping[str, Any]:
|
||||
common_inputs = super(OnnxConfigWithPast, self).generate_dummy_inputs(
|
||||
tokenizer, batch_size=batch_size, seq_length=seq_length, is_pair=is_pair, framework=framework
|
||||
)
|
||||
|
||||
# We need to order the input in the way they appears in the forward()
|
||||
ordered_inputs = OrderedDict({"input_ids": common_inputs["input_ids"]})
|
||||
|
||||
# Need to add the past_keys
|
||||
if self.use_past:
|
||||
if not is_torch_available():
|
||||
raise ValueError("Cannot generate dummy past_keys inputs without PyTorch installed.")
|
||||
else:
|
||||
import torch
|
||||
|
||||
batch, seqlen = common_inputs["input_ids"].shape
|
||||
# Not using the same length for past_key_values
|
||||
past_key_values_length = seqlen + 2
|
||||
head_dim = self._config.hidden_size // self.num_attention_heads
|
||||
past_key_shape = (
|
||||
batch * self.num_attention_heads,
|
||||
head_dim,
|
||||
past_key_values_length,
|
||||
)
|
||||
past_value_shape = (
|
||||
batch * self.num_attention_heads,
|
||||
past_key_values_length,
|
||||
head_dim,
|
||||
)
|
||||
ordered_inputs["past_key_values"] = [
|
||||
(torch.zeros(past_key_shape), torch.zeros(past_value_shape)) for _ in range(self.num_layers)
|
||||
]
|
||||
|
||||
ordered_inputs["attention_mask"] = common_inputs["attention_mask"]
|
||||
if self.use_past:
|
||||
mask_dtype = ordered_inputs["attention_mask"].dtype
|
||||
ordered_inputs["attention_mask"] = torch.cat(
|
||||
[ordered_inputs["attention_mask"], torch.ones(batch, past_key_values_length, dtype=mask_dtype)], dim=1
|
||||
)
|
||||
|
||||
return ordered_inputs
|
||||
|
||||
@property
|
||||
def default_onnx_opset(self) -> int:
|
||||
return 13
|
||||
@@ -0,0 +1,500 @@
|
||||
# Copyright 2023 The HuggingFace Team. All rights reserved.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
from dataclasses import dataclass
|
||||
from typing import List, Optional, Tuple, Union
|
||||
|
||||
import torch
|
||||
|
||||
|
||||
@dataclass
|
||||
class AttentionMaskConverter:
|
||||
"""
|
||||
A utility attention mask class that allows one to:
|
||||
- Create a causal 4d mask
|
||||
- Create a causal 4d mask with slided window
|
||||
- Convert a 2d attention mask (batch_size, query_length) to a 4d attention mask (batch_size, 1, query_length,
|
||||
key_value_length) that can be multiplied with attention scores
|
||||
|
||||
Examples:
|
||||
|
||||
```python
|
||||
>>> import torch
|
||||
>>> from transformers.modeling_attn_mask_utils import AttentionMaskConverter
|
||||
|
||||
>>> converter = AttentionMaskConverter(True)
|
||||
>>> converter.to_4d(torch.tensor([[0, 0, 0, 1, 1]]), 5, key_value_length=5, dtype=torch.float32)
|
||||
tensor([[[[-3.4028e+38, -3.4028e+38, -3.4028e+38, -3.4028e+38, -3.4028e+38],
|
||||
[-3.4028e+38, -3.4028e+38, -3.4028e+38, -3.4028e+38, -3.4028e+38],
|
||||
[-3.4028e+38, -3.4028e+38, -3.4028e+38, -3.4028e+38, -3.4028e+38],
|
||||
[-3.4028e+38, -3.4028e+38, -3.4028e+38, 0.0000e+00, -3.4028e+38],
|
||||
[-3.4028e+38, -3.4028e+38, -3.4028e+38, 0.0000e+00, 0.0000e+00]]]])
|
||||
```
|
||||
|
||||
Parameters:
|
||||
is_causal (`bool`):
|
||||
Whether the attention mask should be a uni-directional (causal) or bi-directional mask.
|
||||
|
||||
sliding_window (`int`, *optional*):
|
||||
Optionally, the sliding window masks can be created if `sliding_window` is defined to a positive integer.
|
||||
"""
|
||||
|
||||
is_causal: bool
|
||||
sliding_window: int
|
||||
|
||||
def __init__(self, is_causal: bool, sliding_window: Optional[int] = None):
|
||||
self.is_causal = is_causal
|
||||
self.sliding_window = sliding_window
|
||||
|
||||
if self.sliding_window is not None and self.sliding_window <= 0:
|
||||
raise ValueError(
|
||||
f"Make sure that when passing `sliding_window` that its value is a strictly positive integer, not `{self.sliding_window}`"
|
||||
)
|
||||
|
||||
def to_causal_4d(
|
||||
self,
|
||||
batch_size: int,
|
||||
query_length: int,
|
||||
key_value_length: int,
|
||||
dtype: torch.dtype,
|
||||
device: Union[torch.device, "str"] = "cpu",
|
||||
) -> Optional[torch.Tensor]:
|
||||
"""
|
||||
Creates a causal 4D mask of (bsz, head_dim=1, query_length, key_value_length) shape and adds large negative
|
||||
bias to upper right hand triangular matrix (causal mask).
|
||||
"""
|
||||
if not self.is_causal:
|
||||
raise ValueError(f"Please use `to_causal_4d` only if {self.__class__} has `is_causal` set to True.")
|
||||
|
||||
# If shape is not cached, create a new causal mask and cache it
|
||||
input_shape = (batch_size, query_length)
|
||||
past_key_values_length = key_value_length - query_length
|
||||
|
||||
# create causal mask
|
||||
# [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
|
||||
causal_4d_mask = None
|
||||
if input_shape[-1] > 1 or self.sliding_window is not None:
|
||||
causal_4d_mask = self._make_causal_mask(
|
||||
input_shape,
|
||||
dtype,
|
||||
device=device,
|
||||
past_key_values_length=past_key_values_length,
|
||||
sliding_window=self.sliding_window,
|
||||
)
|
||||
|
||||
return causal_4d_mask
|
||||
|
||||
def to_4d(
|
||||
self,
|
||||
attention_mask_2d: torch.Tensor,
|
||||
query_length: int,
|
||||
dtype: torch.dtype,
|
||||
key_value_length: Optional[int] = None,
|
||||
) -> torch.Tensor:
|
||||
"""
|
||||
Converts 2D attention mask to 4D attention mask by expanding mask to (bsz, head_dim=1, query_length,
|
||||
key_value_length) shape and by adding a large negative bias to not-attended positions. If attention_mask is
|
||||
causal, a causal mask will be added.
|
||||
"""
|
||||
input_shape = (attention_mask_2d.shape[0], query_length)
|
||||
|
||||
# create causal mask
|
||||
# [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
|
||||
causal_4d_mask = None
|
||||
if (input_shape[-1] > 1 or self.sliding_window is not None) and self.is_causal:
|
||||
if key_value_length is None:
|
||||
raise ValueError(
|
||||
"This attention mask converter is causal. Make sure to pass `key_value_length` to correctly create a causal mask."
|
||||
)
|
||||
|
||||
past_key_values_length = key_value_length - query_length
|
||||
causal_4d_mask = self._make_causal_mask(
|
||||
input_shape,
|
||||
dtype,
|
||||
device=attention_mask_2d.device,
|
||||
past_key_values_length=past_key_values_length,
|
||||
sliding_window=self.sliding_window,
|
||||
)
|
||||
elif self.sliding_window is not None:
|
||||
raise NotImplementedError("Sliding window is currently only implemented for causal masking")
|
||||
|
||||
# [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
|
||||
expanded_attn_mask = self._expand_mask(attention_mask_2d, dtype, tgt_len=input_shape[-1]).to(
|
||||
attention_mask_2d.device
|
||||
)
|
||||
|
||||
if causal_4d_mask is not None:
|
||||
expanded_attn_mask = causal_4d_mask.masked_fill(expanded_attn_mask.bool(), torch.finfo(dtype).min)
|
||||
|
||||
# expanded_attn_mask + causal_4d_mask can cause some overflow
|
||||
expanded_4d_mask = expanded_attn_mask
|
||||
|
||||
return expanded_4d_mask
|
||||
|
||||
@staticmethod
|
||||
def _make_causal_mask(
|
||||
input_ids_shape: torch.Size,
|
||||
dtype: torch.dtype,
|
||||
device: torch.device,
|
||||
past_key_values_length: int = 0,
|
||||
sliding_window: Optional[int] = None,
|
||||
):
|
||||
"""
|
||||
Make causal mask used for bi-directional self-attention.
|
||||
"""
|
||||
bsz, tgt_len = input_ids_shape
|
||||
mask = torch.full((tgt_len, tgt_len), torch.finfo(dtype).min, device=device)
|
||||
mask_cond = torch.arange(mask.size(-1), device=device)
|
||||
mask.masked_fill_(mask_cond < (mask_cond + 1).view(mask.size(-1), 1), 0)
|
||||
|
||||
mask = mask.to(dtype)
|
||||
|
||||
if past_key_values_length > 0:
|
||||
mask = torch.cat([torch.zeros(tgt_len, past_key_values_length, dtype=dtype, device=device), mask], dim=-1)
|
||||
|
||||
# add lower triangular sliding window mask if necessary
|
||||
if sliding_window is not None:
|
||||
diagonal = past_key_values_length - sliding_window + 1
|
||||
|
||||
context_mask = 1 - torch.triu(torch.ones_like(mask, dtype=torch.int), diagonal=diagonal)
|
||||
mask.masked_fill_(context_mask.bool(), torch.finfo(dtype).min)
|
||||
|
||||
return mask[None, None, :, :].expand(bsz, 1, tgt_len, tgt_len + past_key_values_length)
|
||||
|
||||
@staticmethod
|
||||
def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None):
|
||||
"""
|
||||
Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.
|
||||
"""
|
||||
bsz, src_len = mask.size()
|
||||
tgt_len = tgt_len if tgt_len is not None else src_len
|
||||
|
||||
expanded_mask = mask[:, None, None, :].expand(bsz, 1, tgt_len, src_len).to(dtype)
|
||||
|
||||
inverted_mask = 1.0 - expanded_mask
|
||||
|
||||
return inverted_mask.masked_fill(inverted_mask.to(torch.bool), torch.finfo(dtype).min)
|
||||
|
||||
@staticmethod
|
||||
def _unmask_unattended(
|
||||
expanded_mask: torch.Tensor, attention_mask: torch.Tensor, unmasked_value: Union[bool, float]
|
||||
):
|
||||
# fmt: off
|
||||
"""
|
||||
Attend to all tokens in masked rows from the expanded attention mask, for example the relevant first rows when
|
||||
using left padding. This is required by F.scaled_dot_product_attention memory-efficient attention path.
|
||||
Details: https://github.com/pytorch/pytorch/issues/110213
|
||||
|
||||
`expanded_mask` is [bsz, num_masks, tgt_seq_len, src_seq_len] or [bsz, tgt_seq_len, src_seq_len].
|
||||
`attention_mask` is [bsz, src_seq_len].
|
||||
|
||||
The dimension num_masks of `expanded_mask` is most often 1, but it can also be the number of heads in the case of alibi attention bias.
|
||||
|
||||
For example, if `attention_mask` is
|
||||
```
|
||||
[[0, 0, 1],
|
||||
[1, 1, 1],
|
||||
[0, 1, 1]]
|
||||
```
|
||||
and `expanded_mask` is (e.g. here left-padding case)
|
||||
```
|
||||
[[[[0, 0, 0],
|
||||
[0, 0, 0],
|
||||
[0, 0, 1]]],
|
||||
[[[1, 0, 0],
|
||||
[1, 1, 0],
|
||||
[1, 1, 1]]],
|
||||
[[[0, 0, 0],
|
||||
[0, 1, 0],
|
||||
[0, 1, 1]]]]
|
||||
```
|
||||
then the modified `expanded_mask` will be
|
||||
```
|
||||
[[[[1, 1, 1], <-- modified
|
||||
[1, 1, 1], <-- modified
|
||||
[0, 0, 1]]],
|
||||
[[[1, 0, 0],
|
||||
[1, 1, 0],
|
||||
[1, 1, 1]]],
|
||||
[[[1, 1, 1], <-- modified
|
||||
[0, 1, 0],
|
||||
[0, 1, 1]]]]
|
||||
```
|
||||
"""
|
||||
# fmt: on
|
||||
|
||||
# Get the index of the first non-zero value for every sample in the batch.
|
||||
# In the above example, indices = [[2], [0], [1]]]
|
||||
tmp = torch.arange(attention_mask.shape[1], 0, -1)
|
||||
indices = torch.argmax(attention_mask.cpu() * tmp, 1, keepdim=True)
|
||||
|
||||
# Find the batch indexes that have unattended tokens on the leftmost side (e.g. [0, 0, 1, 1, 1]), for which the first rows of the
|
||||
# expanded mask will be completely unattended.
|
||||
left_masked_rows = torch.where(indices > 0)[0]
|
||||
|
||||
if left_masked_rows.shape[0] == 0:
|
||||
return expanded_mask
|
||||
indices = indices[left_masked_rows]
|
||||
|
||||
max_len = torch.max(indices)
|
||||
range_tensor = torch.arange(max_len).unsqueeze(0)
|
||||
range_tensor = range_tensor.repeat(indices.size(0), 1)
|
||||
|
||||
# Avoid unmasking tokens at relevant target positions (on the row axis), by rather unmasking possibly several times the first row that should always be unmasked as we filtered out the batch above.
|
||||
range_tensor[range_tensor >= indices] = 0
|
||||
|
||||
# TODO: we may drop support for 3D attention mask as the refactor from Patrick maybe dropped this case
|
||||
if expanded_mask.dim() == 4:
|
||||
num_masks = expanded_mask.shape[1]
|
||||
if num_masks == 1:
|
||||
# Broadcast [left_masked_rows, 1], [left_masked_rows, max_len]
|
||||
mask_slice = (left_masked_rows[:, None], 0, range_tensor)
|
||||
else:
|
||||
# Broadcast [left_masked_rows, 1, 1], [1, num_masks, 1], [left_masked_rows, 1, max_len]
|
||||
mask_slice = (
|
||||
left_masked_rows[:, None, None],
|
||||
torch.arange(num_masks)[None, :, None],
|
||||
range_tensor[:, None, :],
|
||||
)
|
||||
else:
|
||||
# Broadcast [left_masked_rows, 1], [left_masked_rows, max_len]
|
||||
mask_slice = (left_masked_rows[:, None], range_tensor)
|
||||
|
||||
expanded_mask[mask_slice] = unmasked_value
|
||||
|
||||
return expanded_mask
|
||||
|
||||
|
||||
def _prepare_4d_causal_attention_mask(
|
||||
attention_mask: Optional[torch.Tensor],
|
||||
input_shape: Union[torch.Size, Tuple, List],
|
||||
inputs_embeds: torch.Tensor,
|
||||
past_key_values_length: int,
|
||||
sliding_window: Optional[int] = None,
|
||||
):
|
||||
"""
|
||||
Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
|
||||
`(batch_size, key_value_length)`
|
||||
|
||||
Args:
|
||||
attention_mask (`torch.Tensor` or `None`):
|
||||
A 2D attention mask of shape `(batch_size, key_value_length)`
|
||||
input_shape (`tuple(int)` or `list(int)` or `torch.Size`):
|
||||
The input shape should be a tuple that defines `(batch_size, query_length)`.
|
||||
inputs_embeds (`torch.Tensor`):
|
||||
The embedded inputs as a torch Tensor.
|
||||
past_key_values_length (`int`):
|
||||
The length of the key value cache.
|
||||
sliding_window (`int`, *optional*):
|
||||
If the model uses windowed attention, a sliding window should be passed.
|
||||
"""
|
||||
attn_mask_converter = AttentionMaskConverter(is_causal=True, sliding_window=sliding_window)
|
||||
|
||||
key_value_length = input_shape[-1] + past_key_values_length
|
||||
|
||||
# 4d mask is passed through the layers
|
||||
if attention_mask is not None and len(attention_mask.shape) == 2:
|
||||
attention_mask = attn_mask_converter.to_4d(
|
||||
attention_mask, input_shape[-1], key_value_length=key_value_length, dtype=inputs_embeds.dtype
|
||||
)
|
||||
elif attention_mask is not None and len(attention_mask.shape) == 4:
|
||||
expected_shape = (input_shape[0], 1, input_shape[1], key_value_length)
|
||||
if tuple(attention_mask.shape) != expected_shape:
|
||||
raise ValueError(
|
||||
f"Incorrect 4D attention_mask shape: {tuple(attention_mask.shape)}; expected: {expected_shape}."
|
||||
)
|
||||
else:
|
||||
# if the 4D mask has correct shape - invert it and fill with negative infinity
|
||||
inverted_mask = 1.0 - attention_mask
|
||||
attention_mask = inverted_mask.masked_fill(
|
||||
inverted_mask.to(torch.bool), torch.finfo(inputs_embeds.dtype).min
|
||||
)
|
||||
else:
|
||||
attention_mask = attn_mask_converter.to_causal_4d(
|
||||
input_shape[0], input_shape[-1], key_value_length, dtype=inputs_embeds.dtype, device=inputs_embeds.device
|
||||
)
|
||||
|
||||
return attention_mask
|
||||
|
||||
|
||||
# Adapted from _prepare_4d_causal_attention_mask
|
||||
def _prepare_4d_causal_attention_mask_for_sdpa(
|
||||
attention_mask: Optional[torch.Tensor],
|
||||
input_shape: Union[torch.Size, Tuple, List],
|
||||
inputs_embeds: torch.Tensor,
|
||||
past_key_values_length: int,
|
||||
sliding_window: Optional[int] = None,
|
||||
):
|
||||
"""
|
||||
Prepares the correct `attn_mask` argument to be used by `torch.nn.functional.scaled_dot_product_attention`.
|
||||
|
||||
In case no token is masked in the `attention_mask` argument, we simply set it to `None` for the cases `query_length == 1` and
|
||||
`key_value_length == query_length`, and rely instead on SDPA `is_causal` argument to use causal/non-causal masks,
|
||||
allowing to dispatch to the flash attention kernel (that can otherwise not be used if a custom `attn_mask` is passed).
|
||||
"""
|
||||
attn_mask_converter = AttentionMaskConverter(is_causal=True, sliding_window=sliding_window)
|
||||
|
||||
key_value_length = input_shape[-1] + past_key_values_length
|
||||
batch_size, query_length = input_shape
|
||||
|
||||
# torch.jit.trace, symbolic_trace and torchdynamo with fullgraph=True are unable to capture the controlflow `is_causal=attention_mask is None and q_len > 1`
|
||||
# used as an SDPA argument. We keep compatibility with these tracing tools by always using SDPA's `attn_mask` argument in case we are tracing.
|
||||
# TODO: Fix this as well when using torchdynamo with fullgraph=True.
|
||||
is_tracing = torch.jit.is_tracing() or isinstance(inputs_embeds, torch.fx.Proxy)
|
||||
|
||||
if attention_mask is not None:
|
||||
# 4d mask is passed through
|
||||
if len(attention_mask.shape) == 4:
|
||||
expected_shape = (input_shape[0], 1, input_shape[1], key_value_length)
|
||||
if tuple(attention_mask.shape) != expected_shape:
|
||||
raise ValueError(
|
||||
f"Incorrect 4D attention_mask shape: {tuple(attention_mask.shape)}; expected: {expected_shape}."
|
||||
)
|
||||
else:
|
||||
# if the 4D mask has correct shape - invert it and fill with negative infinity
|
||||
inverted_mask = 1.0 - attention_mask.to(inputs_embeds.dtype)
|
||||
attention_mask = inverted_mask.masked_fill(
|
||||
inverted_mask.to(torch.bool), torch.finfo(inputs_embeds.dtype).min
|
||||
)
|
||||
return attention_mask
|
||||
|
||||
elif not is_tracing and torch.all(attention_mask == 1):
|
||||
if query_length == 1:
|
||||
# For query_length == 1, causal attention and bi-directional attention are the same.
|
||||
attention_mask = None
|
||||
elif key_value_length == query_length:
|
||||
attention_mask = None
|
||||
else:
|
||||
# Unfortunately, for query_length > 1 and key_value_length != query_length, we cannot generally ignore the attention mask, as SDPA causal mask generation
|
||||
# may be wrong. We will set `is_causal=False` in SDPA and rely on Transformers attention_mask instead, hence not setting it to None here.
|
||||
# Reference: https://github.com/pytorch/pytorch/issues/108108
|
||||
pass
|
||||
elif query_length > 1 and key_value_length != query_length:
|
||||
# See the comment above (https://github.com/pytorch/pytorch/issues/108108).
|
||||
# Ugly: we set it to True here to dispatch in the following controlflow to `to_causal_4d`.
|
||||
attention_mask = True
|
||||
elif is_tracing:
|
||||
raise ValueError(
|
||||
'Attention using SDPA can not be traced with torch.jit.trace when no attention_mask is provided. To solve this issue, please either load your model with the argument `attn_implementation="eager"` or pass an attention_mask input when tracing the model.'
|
||||
)
|
||||
|
||||
if attention_mask is None:
|
||||
expanded_4d_mask = None
|
||||
elif attention_mask is True:
|
||||
expanded_4d_mask = attn_mask_converter.to_causal_4d(
|
||||
input_shape[0], input_shape[-1], key_value_length, dtype=inputs_embeds.dtype, device=inputs_embeds.device
|
||||
)
|
||||
else:
|
||||
expanded_4d_mask = attn_mask_converter.to_4d(
|
||||
attention_mask,
|
||||
input_shape[-1],
|
||||
dtype=inputs_embeds.dtype,
|
||||
key_value_length=key_value_length,
|
||||
)
|
||||
|
||||
# From PyTorch 2.1 onwards, F.scaled_dot_product_attention with the memory-efficient attention backend
|
||||
# produces nans if sequences are completely unattended in the attention mask. Details: https://github.com/pytorch/pytorch/issues/110213
|
||||
#
|
||||
# This fix is not applied in case we are tracing with torch.jit.trace or symbolic_trace, as _unmask_unattended has a data-dependent
|
||||
# controlflow that can not be captured properly.
|
||||
# TODO: _unmask_unattended does not work either with torch.compile when using fullgraph=True. We should find a way to detect this case.
|
||||
if query_length > 1 and not is_tracing:
|
||||
expanded_4d_mask = AttentionMaskConverter._unmask_unattended(
|
||||
expanded_4d_mask, attention_mask, unmasked_value=0.0
|
||||
)
|
||||
|
||||
return expanded_4d_mask
|
||||
|
||||
|
||||
def _prepare_4d_attention_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None):
|
||||
"""
|
||||
Creates a non-causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
|
||||
`(batch_size, key_value_length)`
|
||||
|
||||
Args:
|
||||
mask (`torch.Tensor` or `None`):
|
||||
A 2D attention mask of shape `(batch_size, key_value_length)`
|
||||
dtype (`torch.dtype`):
|
||||
The torch dtype the created mask shall have.
|
||||
tgt_len (`int`):
|
||||
The target length or query length the created mask shall have.
|
||||
"""
|
||||
return AttentionMaskConverter._expand_mask(mask=mask, dtype=dtype, tgt_len=tgt_len)
|
||||
|
||||
|
||||
def _prepare_4d_attention_mask_for_sdpa(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None):
|
||||
"""
|
||||
Creates a non-causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
|
||||
`(batch_size, key_value_length)`
|
||||
|
||||
Args:
|
||||
mask (`torch.Tensor` or `None`):
|
||||
A 2D attention mask of shape `(batch_size, key_value_length)`
|
||||
dtype (`torch.dtype`):
|
||||
The torch dtype the created mask shall have.
|
||||
tgt_len (`int`):
|
||||
The target length or query length the created mask shall have.
|
||||
"""
|
||||
batch_size, key_value_length = mask.shape
|
||||
tgt_len = tgt_len if tgt_len is not None else key_value_length
|
||||
|
||||
# torch.jit.trace and torchdynamo with fullgraph=True are unable to capture the controlflow `is_causal=attention_mask is None and q_len > 1`
|
||||
# used as an SDPA argument. We keep compatibility with these tracing tools by always using SDPA's `attn_mask` argument in case we are tracing.
|
||||
# TODO: Fix this as well when using torchdynamo with fullgraph=True.
|
||||
is_tracing = torch.jit.is_tracing()
|
||||
|
||||
if torch.all(mask == 1):
|
||||
if is_tracing:
|
||||
pass
|
||||
elif tgt_len == 1:
|
||||
# For query_length == 1, causal attention and bi-directional attention are the same.
|
||||
return None
|
||||
elif key_value_length == tgt_len:
|
||||
return None
|
||||
else:
|
||||
# Unfortunately, for query_length > 1 and key_value_length != query_length, we can not generally ignore the attention mask, as SDPA causal mask generation
|
||||
# may be wrong. We will set is_causal=False in SDPA and rely on Transformers attention_mask instead, hence not setting it to None here.
|
||||
# Reference: https://github.com/pytorch/pytorch/issues/108108
|
||||
return AttentionMaskConverter._expand_mask(mask=mask, dtype=dtype, tgt_len=tgt_len)
|
||||
else:
|
||||
return AttentionMaskConverter._expand_mask(mask=mask, dtype=dtype, tgt_len=tgt_len)
|
||||
|
||||
|
||||
def _create_4d_causal_attention_mask(
|
||||
input_shape: Union[torch.Size, Tuple, List],
|
||||
dtype: torch.dtype,
|
||||
device: torch.device,
|
||||
past_key_values_length: int = 0,
|
||||
sliding_window: Optional[int] = None,
|
||||
) -> Optional[torch.Tensor]:
|
||||
"""
|
||||
Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)`
|
||||
|
||||
Args:
|
||||
input_shape (`tuple(int)` or `list(int)` or `torch.Size`):
|
||||
The input shape should be a tuple that defines `(batch_size, query_length)`.
|
||||
dtype (`torch.dtype`):
|
||||
The torch dtype the created mask shall have.
|
||||
device (`int`):
|
||||
The torch device the created mask shall have.
|
||||
sliding_window (`int`, *optional*):
|
||||
If the model uses windowed attention, a sliding window should be passed.
|
||||
"""
|
||||
attn_mask_converter = AttentionMaskConverter(is_causal=True, sliding_window=sliding_window)
|
||||
|
||||
key_value_length = past_key_values_length + input_shape[-1]
|
||||
attention_mask = attn_mask_converter.to_causal_4d(
|
||||
input_shape[0], input_shape[-1], key_value_length, dtype=dtype, device=device
|
||||
)
|
||||
|
||||
return attention_mask
|
||||
1250
ixformer_sdk/train/speedformer/models/bloom/modeling_bloom.py
Normal file
1250
ixformer_sdk/train/speedformer/models/bloom/modeling_bloom.py
Normal file
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,61 @@
|
||||
from transformers import PretrainedConfig
|
||||
|
||||
|
||||
class ChatGLMConfig(PretrainedConfig):
|
||||
model_type = "chatglm"
|
||||
def __init__(
|
||||
self,
|
||||
num_layers=28,
|
||||
padded_vocab_size=65024,
|
||||
hidden_size=4096,
|
||||
ffn_hidden_size=13696,
|
||||
kv_channels=128,
|
||||
num_attention_heads=32,
|
||||
seq_length=2048,
|
||||
hidden_dropout=0.0,
|
||||
classifier_dropout=None,
|
||||
attention_dropout=0.0,
|
||||
layernorm_epsilon=1e-5,
|
||||
rmsnorm=True,
|
||||
apply_residual_connection_post_layernorm=False,
|
||||
post_layer_norm=True,
|
||||
add_bias_linear=False,
|
||||
add_qkv_bias=False,
|
||||
bias_dropout_fusion=True,
|
||||
multi_query_attention=False,
|
||||
multi_query_group_num=1,
|
||||
apply_query_key_layer_scaling=True,
|
||||
attention_softmax_in_fp32=True,
|
||||
fp32_residual_connection=False,
|
||||
quantization_bit=0,
|
||||
pre_seq_len=None,
|
||||
prefix_projection=False,
|
||||
**kwargs
|
||||
):
|
||||
self.num_layers = num_layers
|
||||
self.vocab_size = padded_vocab_size
|
||||
self.padded_vocab_size = padded_vocab_size
|
||||
self.hidden_size = hidden_size
|
||||
self.ffn_hidden_size = ffn_hidden_size
|
||||
self.kv_channels = kv_channels
|
||||
self.num_attention_heads = num_attention_heads
|
||||
self.seq_length = seq_length
|
||||
self.hidden_dropout = hidden_dropout
|
||||
self.classifier_dropout = classifier_dropout
|
||||
self.attention_dropout = attention_dropout
|
||||
self.layernorm_epsilon = layernorm_epsilon
|
||||
self.rmsnorm = rmsnorm
|
||||
self.apply_residual_connection_post_layernorm = apply_residual_connection_post_layernorm
|
||||
self.post_layer_norm = post_layer_norm
|
||||
self.add_bias_linear = add_bias_linear
|
||||
self.add_qkv_bias = add_qkv_bias
|
||||
self.bias_dropout_fusion = bias_dropout_fusion
|
||||
self.multi_query_attention = multi_query_attention
|
||||
self.multi_query_group_num = multi_query_group_num
|
||||
self.apply_query_key_layer_scaling = apply_query_key_layer_scaling
|
||||
self.attention_softmax_in_fp32 = attention_softmax_in_fp32
|
||||
self.fp32_residual_connection = fp32_residual_connection
|
||||
self.quantization_bit = quantization_bit
|
||||
self.pre_seq_len = pre_seq_len
|
||||
self.prefix_projection = prefix_projection
|
||||
super().__init__(**kwargs)
|
||||
1300
ixformer_sdk/train/speedformer/models/chatglm/modeling_chatglm.py
Normal file
1300
ixformer_sdk/train/speedformer/models/chatglm/modeling_chatglm.py
Normal file
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
269
ixformer_sdk/train/speedformer/models/gpt2/configuration_gpt2.py
Normal file
269
ixformer_sdk/train/speedformer/models/gpt2/configuration_gpt2.py
Normal file
@@ -0,0 +1,269 @@
|
||||
# coding=utf-8
|
||||
# Copyright 2018 The OpenAI Team Authors and HuggingFace Inc. team.
|
||||
# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
""" OpenAI GPT-2 configuration"""
|
||||
from collections import OrderedDict
|
||||
from typing import Any, List, Mapping, Optional
|
||||
|
||||
from transformers import PreTrainedTokenizer, TensorType, is_torch_available
|
||||
from transformers.configuration_utils import PretrainedConfig
|
||||
from transformers.onnx import OnnxConfigWithPast, PatchingSpec
|
||||
from transformers.utils import logging
|
||||
|
||||
|
||||
logger = logging.get_logger(__name__)
|
||||
|
||||
|
||||
class GPT2Config(PretrainedConfig):
|
||||
"""
|
||||
This is the configuration class to store the configuration of a [`GPT2Model`] or a [`TFGPT2Model`]. It is used to
|
||||
instantiate a GPT-2 model according to the specified arguments, defining the model architecture. Instantiating a
|
||||
configuration with the defaults will yield a similar configuration to that of the GPT-2
|
||||
[openai-community/gpt2](https://huggingface.co/openai-community/gpt2) architecture.
|
||||
|
||||
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
||||
documentation from [`PretrainedConfig`] for more information.
|
||||
|
||||
|
||||
Args:
|
||||
vocab_size (`int`, *optional*, defaults to 50257):
|
||||
Vocabulary size of the GPT-2 model. Defines the number of different tokens that can be represented by the
|
||||
`inputs_ids` passed when calling [`GPT2Model`] or [`TFGPT2Model`].
|
||||
n_positions (`int`, *optional*, defaults to 1024):
|
||||
The maximum sequence length that this model might ever be used with. Typically set this to something large
|
||||
just in case (e.g., 512 or 1024 or 2048).
|
||||
n_embd (`int`, *optional*, defaults to 768):
|
||||
Dimensionality of the embeddings and hidden states.
|
||||
n_layer (`int`, *optional*, defaults to 12):
|
||||
Number of hidden layers in the Transformer encoder.
|
||||
n_head (`int`, *optional*, defaults to 12):
|
||||
Number of attention heads for each attention layer in the Transformer encoder.
|
||||
n_inner (`int`, *optional*):
|
||||
Dimensionality of the inner feed-forward layers. `None` will set it to 4 times n_embd
|
||||
activation_function (`str`, *optional*, defaults to `"gelu_new"`):
|
||||
Activation function, to be selected in the list `["relu", "silu", "gelu", "tanh", "gelu_new"]`.
|
||||
resid_pdrop (`float`, *optional*, defaults to 0.1):
|
||||
The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
|
||||
embd_pdrop (`float`, *optional*, defaults to 0.1):
|
||||
The dropout ratio for the embeddings.
|
||||
attn_pdrop (`float`, *optional*, defaults to 0.1):
|
||||
The dropout ratio for the attention.
|
||||
layer_norm_epsilon (`float`, *optional*, defaults to 1e-05):
|
||||
The epsilon to use in the layer normalization layers.
|
||||
initializer_range (`float`, *optional*, defaults to 0.02):
|
||||
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
||||
summary_type (`string`, *optional*, defaults to `"cls_index"`):
|
||||
Argument used when doing sequence summary, used in the models [`GPT2DoubleHeadsModel`] and
|
||||
[`TFGPT2DoubleHeadsModel`].
|
||||
|
||||
Has to be one of the following options:
|
||||
|
||||
- `"last"`: Take the last token hidden state (like XLNet).
|
||||
- `"first"`: Take the first token hidden state (like BERT).
|
||||
- `"mean"`: Take the mean of all tokens hidden states.
|
||||
- `"cls_index"`: Supply a Tensor of classification token position (like GPT/GPT-2).
|
||||
- `"attn"`: Not implemented now, use multi-head attention.
|
||||
summary_use_proj (`bool`, *optional*, defaults to `True`):
|
||||
Argument used when doing sequence summary, used in the models [`GPT2DoubleHeadsModel`] and
|
||||
[`TFGPT2DoubleHeadsModel`].
|
||||
|
||||
Whether or not to add a projection after the vector extraction.
|
||||
summary_activation (`str`, *optional*):
|
||||
Argument used when doing sequence summary. Used in for the multiple choice head in
|
||||
[`GPT2DoubleHeadsModel`].
|
||||
|
||||
Pass `"tanh"` for a tanh activation to the output, any other value will result in no activation.
|
||||
summary_proj_to_labels (`bool`, *optional*, defaults to `True`):
|
||||
Argument used when doing sequence summary, used in the models [`GPT2DoubleHeadsModel`] and
|
||||
[`TFGPT2DoubleHeadsModel`].
|
||||
|
||||
Whether the projection outputs should have `config.num_labels` or `config.hidden_size` classes.
|
||||
summary_first_dropout (`float`, *optional*, defaults to 0.1):
|
||||
Argument used when doing sequence summary, used in the models [`GPT2DoubleHeadsModel`] and
|
||||
[`TFGPT2DoubleHeadsModel`].
|
||||
|
||||
The dropout ratio to be used after the projection and activation.
|
||||
scale_attn_weights (`bool`, *optional*, defaults to `True`):
|
||||
Scale attention weights by dividing by sqrt(hidden_size)..
|
||||
use_cache (`bool`, *optional*, defaults to `True`):
|
||||
Whether or not the model should return the last key/values attentions (not used by all models).
|
||||
bos_token_id (`int`, *optional*, defaults to 50256):
|
||||
Id of the beginning of sentence token in the vocabulary.
|
||||
eos_token_id (`int`, *optional*, defaults to 50256):
|
||||
Id of the end of sentence token in the vocabulary.
|
||||
scale_attn_by_inverse_layer_idx (`bool`, *optional*, defaults to `False`):
|
||||
Whether to additionally scale attention weights by `1 / layer_idx + 1`.
|
||||
reorder_and_upcast_attn (`bool`, *optional*, defaults to `False`):
|
||||
Whether to scale keys (K) prior to computing attention (dot-product) and upcast attention
|
||||
dot-product/softmax to float() when training with mixed precision.
|
||||
|
||||
Example:
|
||||
|
||||
```python
|
||||
>>> from transformers import GPT2Config, GPT2Model
|
||||
|
||||
>>> # Initializing a GPT2 configuration
|
||||
>>> configuration = GPT2Config()
|
||||
|
||||
>>> # Initializing a model (with random weights) from the configuration
|
||||
>>> model = GPT2Model(configuration)
|
||||
|
||||
>>> # Accessing the model configuration
|
||||
>>> configuration = model.config
|
||||
```"""
|
||||
|
||||
model_type = "gpt2"
|
||||
keys_to_ignore_at_inference = ["past_key_values"]
|
||||
attribute_map = {
|
||||
"hidden_size": "n_embd",
|
||||
"max_position_embeddings": "n_positions",
|
||||
"num_attention_heads": "n_head",
|
||||
"num_hidden_layers": "n_layer",
|
||||
}
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
vocab_size=50257,
|
||||
n_positions=1024,
|
||||
n_embd=768,
|
||||
n_layer=12,
|
||||
n_head=12,
|
||||
n_inner=None,
|
||||
activation_function="gelu_new",
|
||||
resid_pdrop=0.1,
|
||||
embd_pdrop=0.1,
|
||||
attn_pdrop=0.1,
|
||||
layer_norm_epsilon=1e-5,
|
||||
initializer_range=0.02,
|
||||
summary_type="cls_index",
|
||||
summary_use_proj=True,
|
||||
summary_activation=None,
|
||||
summary_proj_to_labels=True,
|
||||
summary_first_dropout=0.1,
|
||||
scale_attn_weights=True,
|
||||
use_cache=True,
|
||||
bos_token_id=50256,
|
||||
eos_token_id=50256,
|
||||
scale_attn_by_inverse_layer_idx=False,
|
||||
reorder_and_upcast_attn=False,
|
||||
**kwargs,
|
||||
):
|
||||
self.vocab_size = vocab_size
|
||||
self.n_positions = n_positions
|
||||
self.n_embd = n_embd
|
||||
self.n_layer = n_layer
|
||||
self.n_head = n_head
|
||||
self.n_inner = n_inner
|
||||
self.activation_function = activation_function
|
||||
self.resid_pdrop = resid_pdrop
|
||||
self.embd_pdrop = embd_pdrop
|
||||
self.attn_pdrop = attn_pdrop
|
||||
self.layer_norm_epsilon = layer_norm_epsilon
|
||||
self.initializer_range = initializer_range
|
||||
self.summary_type = summary_type
|
||||
self.summary_use_proj = summary_use_proj
|
||||
self.summary_activation = summary_activation
|
||||
self.summary_first_dropout = summary_first_dropout
|
||||
self.summary_proj_to_labels = summary_proj_to_labels
|
||||
self.scale_attn_weights = scale_attn_weights
|
||||
self.use_cache = use_cache
|
||||
self.scale_attn_by_inverse_layer_idx = scale_attn_by_inverse_layer_idx
|
||||
self.reorder_and_upcast_attn = reorder_and_upcast_attn
|
||||
|
||||
self.bos_token_id = bos_token_id
|
||||
self.eos_token_id = eos_token_id
|
||||
|
||||
super().__init__(bos_token_id=bos_token_id, eos_token_id=eos_token_id, **kwargs)
|
||||
|
||||
|
||||
class GPT2OnnxConfig(OnnxConfigWithPast):
|
||||
def __init__(
|
||||
self,
|
||||
config: PretrainedConfig,
|
||||
task: str = "default",
|
||||
patching_specs: List[PatchingSpec] = None,
|
||||
use_past: bool = False,
|
||||
):
|
||||
super().__init__(config, task=task, patching_specs=patching_specs, use_past=use_past)
|
||||
if not getattr(self._config, "pad_token_id", None):
|
||||
# TODO: how to do that better?
|
||||
self._config.pad_token_id = 0
|
||||
|
||||
@property
|
||||
def inputs(self) -> Mapping[str, Mapping[int, str]]:
|
||||
common_inputs = OrderedDict({"input_ids": {0: "batch", 1: "sequence"}})
|
||||
if self.use_past:
|
||||
self.fill_with_past_key_values_(common_inputs, direction="inputs")
|
||||
common_inputs["attention_mask"] = {0: "batch", 1: "past_sequence + sequence"}
|
||||
else:
|
||||
common_inputs["attention_mask"] = {0: "batch", 1: "sequence"}
|
||||
|
||||
return common_inputs
|
||||
|
||||
@property
|
||||
def num_layers(self) -> int:
|
||||
return self._config.n_layer
|
||||
|
||||
@property
|
||||
def num_attention_heads(self) -> int:
|
||||
return self._config.n_head
|
||||
|
||||
def generate_dummy_inputs(
|
||||
self,
|
||||
tokenizer: PreTrainedTokenizer,
|
||||
batch_size: int = -1,
|
||||
seq_length: int = -1,
|
||||
is_pair: bool = False,
|
||||
framework: Optional[TensorType] = None,
|
||||
) -> Mapping[str, Any]:
|
||||
common_inputs = super(OnnxConfigWithPast, self).generate_dummy_inputs(
|
||||
tokenizer, batch_size=batch_size, seq_length=seq_length, is_pair=is_pair, framework=framework
|
||||
)
|
||||
|
||||
# We need to order the input in the way they appears in the forward()
|
||||
ordered_inputs = OrderedDict({"input_ids": common_inputs["input_ids"]})
|
||||
|
||||
# Need to add the past_keys
|
||||
if self.use_past:
|
||||
if not is_torch_available():
|
||||
raise ValueError("Cannot generate dummy past_keys inputs without PyTorch installed.")
|
||||
else:
|
||||
import torch
|
||||
|
||||
batch, seqlen = common_inputs["input_ids"].shape
|
||||
# Not using the same length for past_key_values
|
||||
past_key_values_length = seqlen + 2
|
||||
past_shape = (
|
||||
batch,
|
||||
self.num_attention_heads,
|
||||
past_key_values_length,
|
||||
self._config.hidden_size // self.num_attention_heads,
|
||||
)
|
||||
ordered_inputs["past_key_values"] = [
|
||||
(torch.zeros(past_shape), torch.zeros(past_shape)) for _ in range(self.num_layers)
|
||||
]
|
||||
|
||||
ordered_inputs["attention_mask"] = common_inputs["attention_mask"]
|
||||
if self.use_past:
|
||||
mask_dtype = ordered_inputs["attention_mask"].dtype
|
||||
ordered_inputs["attention_mask"] = torch.cat(
|
||||
[ordered_inputs["attention_mask"], torch.ones(batch, past_key_values_length, dtype=mask_dtype)], dim=1
|
||||
)
|
||||
|
||||
return ordered_inputs
|
||||
|
||||
@property
|
||||
def default_onnx_opset(self) -> int:
|
||||
return 13
|
||||
@@ -0,0 +1,500 @@
|
||||
# Copyright 2023 The HuggingFace Team. All rights reserved.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
from dataclasses import dataclass
|
||||
from typing import List, Optional, Tuple, Union
|
||||
|
||||
import torch
|
||||
|
||||
|
||||
@dataclass
|
||||
class AttentionMaskConverter:
|
||||
"""
|
||||
A utility attention mask class that allows one to:
|
||||
- Create a causal 4d mask
|
||||
- Create a causal 4d mask with slided window
|
||||
- Convert a 2d attention mask (batch_size, query_length) to a 4d attention mask (batch_size, 1, query_length,
|
||||
key_value_length) that can be multiplied with attention scores
|
||||
|
||||
Examples:
|
||||
|
||||
```python
|
||||
>>> import torch
|
||||
>>> from transformers.modeling_attn_mask_utils import AttentionMaskConverter
|
||||
|
||||
>>> converter = AttentionMaskConverter(True)
|
||||
>>> converter.to_4d(torch.tensor([[0, 0, 0, 1, 1]]), 5, key_value_length=5, dtype=torch.float32)
|
||||
tensor([[[[-3.4028e+38, -3.4028e+38, -3.4028e+38, -3.4028e+38, -3.4028e+38],
|
||||
[-3.4028e+38, -3.4028e+38, -3.4028e+38, -3.4028e+38, -3.4028e+38],
|
||||
[-3.4028e+38, -3.4028e+38, -3.4028e+38, -3.4028e+38, -3.4028e+38],
|
||||
[-3.4028e+38, -3.4028e+38, -3.4028e+38, 0.0000e+00, -3.4028e+38],
|
||||
[-3.4028e+38, -3.4028e+38, -3.4028e+38, 0.0000e+00, 0.0000e+00]]]])
|
||||
```
|
||||
|
||||
Parameters:
|
||||
is_causal (`bool`):
|
||||
Whether the attention mask should be a uni-directional (causal) or bi-directional mask.
|
||||
|
||||
sliding_window (`int`, *optional*):
|
||||
Optionally, the sliding window masks can be created if `sliding_window` is defined to a positive integer.
|
||||
"""
|
||||
|
||||
is_causal: bool
|
||||
sliding_window: int
|
||||
|
||||
def __init__(self, is_causal: bool, sliding_window: Optional[int] = None):
|
||||
self.is_causal = is_causal
|
||||
self.sliding_window = sliding_window
|
||||
|
||||
if self.sliding_window is not None and self.sliding_window <= 0:
|
||||
raise ValueError(
|
||||
f"Make sure that when passing `sliding_window` that its value is a strictly positive integer, not `{self.sliding_window}`"
|
||||
)
|
||||
|
||||
def to_causal_4d(
|
||||
self,
|
||||
batch_size: int,
|
||||
query_length: int,
|
||||
key_value_length: int,
|
||||
dtype: torch.dtype,
|
||||
device: Union[torch.device, "str"] = "cpu",
|
||||
) -> Optional[torch.Tensor]:
|
||||
"""
|
||||
Creates a causal 4D mask of (bsz, head_dim=1, query_length, key_value_length) shape and adds large negative
|
||||
bias to upper right hand triangular matrix (causal mask).
|
||||
"""
|
||||
if not self.is_causal:
|
||||
raise ValueError(f"Please use `to_causal_4d` only if {self.__class__} has `is_causal` set to True.")
|
||||
|
||||
# If shape is not cached, create a new causal mask and cache it
|
||||
input_shape = (batch_size, query_length)
|
||||
past_key_values_length = key_value_length - query_length
|
||||
|
||||
# create causal mask
|
||||
# [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
|
||||
causal_4d_mask = None
|
||||
if input_shape[-1] > 1 or self.sliding_window is not None:
|
||||
causal_4d_mask = self._make_causal_mask(
|
||||
input_shape,
|
||||
dtype,
|
||||
device=device,
|
||||
past_key_values_length=past_key_values_length,
|
||||
sliding_window=self.sliding_window,
|
||||
)
|
||||
|
||||
return causal_4d_mask
|
||||
|
||||
def to_4d(
|
||||
self,
|
||||
attention_mask_2d: torch.Tensor,
|
||||
query_length: int,
|
||||
dtype: torch.dtype,
|
||||
key_value_length: Optional[int] = None,
|
||||
) -> torch.Tensor:
|
||||
"""
|
||||
Converts 2D attention mask to 4D attention mask by expanding mask to (bsz, head_dim=1, query_length,
|
||||
key_value_length) shape and by adding a large negative bias to not-attended positions. If attention_mask is
|
||||
causal, a causal mask will be added.
|
||||
"""
|
||||
input_shape = (attention_mask_2d.shape[0], query_length)
|
||||
|
||||
# create causal mask
|
||||
# [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
|
||||
causal_4d_mask = None
|
||||
if (input_shape[-1] > 1 or self.sliding_window is not None) and self.is_causal:
|
||||
if key_value_length is None:
|
||||
raise ValueError(
|
||||
"This attention mask converter is causal. Make sure to pass `key_value_length` to correctly create a causal mask."
|
||||
)
|
||||
|
||||
past_key_values_length = key_value_length - query_length
|
||||
causal_4d_mask = self._make_causal_mask(
|
||||
input_shape,
|
||||
dtype,
|
||||
device=attention_mask_2d.device,
|
||||
past_key_values_length=past_key_values_length,
|
||||
sliding_window=self.sliding_window,
|
||||
)
|
||||
elif self.sliding_window is not None:
|
||||
raise NotImplementedError("Sliding window is currently only implemented for causal masking")
|
||||
|
||||
# [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
|
||||
expanded_attn_mask = self._expand_mask(attention_mask_2d, dtype, tgt_len=input_shape[-1]).to(
|
||||
attention_mask_2d.device
|
||||
)
|
||||
|
||||
if causal_4d_mask is not None:
|
||||
expanded_attn_mask = causal_4d_mask.masked_fill(expanded_attn_mask.bool(), torch.finfo(dtype).min)
|
||||
|
||||
# expanded_attn_mask + causal_4d_mask can cause some overflow
|
||||
expanded_4d_mask = expanded_attn_mask
|
||||
|
||||
return expanded_4d_mask
|
||||
|
||||
@staticmethod
|
||||
def _make_causal_mask(
|
||||
input_ids_shape: torch.Size,
|
||||
dtype: torch.dtype,
|
||||
device: torch.device,
|
||||
past_key_values_length: int = 0,
|
||||
sliding_window: Optional[int] = None,
|
||||
):
|
||||
"""
|
||||
Make causal mask used for bi-directional self-attention.
|
||||
"""
|
||||
bsz, tgt_len = input_ids_shape
|
||||
mask = torch.full((tgt_len, tgt_len), torch.finfo(dtype).min, device=device)
|
||||
mask_cond = torch.arange(mask.size(-1), device=device)
|
||||
mask.masked_fill_(mask_cond < (mask_cond + 1).view(mask.size(-1), 1), 0)
|
||||
|
||||
mask = mask.to(dtype)
|
||||
|
||||
if past_key_values_length > 0:
|
||||
mask = torch.cat([torch.zeros(tgt_len, past_key_values_length, dtype=dtype, device=device), mask], dim=-1)
|
||||
|
||||
# add lower triangular sliding window mask if necessary
|
||||
if sliding_window is not None:
|
||||
diagonal = past_key_values_length - sliding_window + 1
|
||||
|
||||
context_mask = 1 - torch.triu(torch.ones_like(mask, dtype=torch.int), diagonal=diagonal)
|
||||
mask.masked_fill_(context_mask.bool(), torch.finfo(dtype).min)
|
||||
|
||||
return mask[None, None, :, :].expand(bsz, 1, tgt_len, tgt_len + past_key_values_length)
|
||||
|
||||
@staticmethod
|
||||
def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None):
|
||||
"""
|
||||
Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.
|
||||
"""
|
||||
bsz, src_len = mask.size()
|
||||
tgt_len = tgt_len if tgt_len is not None else src_len
|
||||
|
||||
expanded_mask = mask[:, None, None, :].expand(bsz, 1, tgt_len, src_len).to(dtype)
|
||||
|
||||
inverted_mask = 1.0 - expanded_mask
|
||||
|
||||
return inverted_mask.masked_fill(inverted_mask.to(torch.bool), torch.finfo(dtype).min)
|
||||
|
||||
@staticmethod
|
||||
def _unmask_unattended(
|
||||
expanded_mask: torch.Tensor, attention_mask: torch.Tensor, unmasked_value: Union[bool, float]
|
||||
):
|
||||
# fmt: off
|
||||
"""
|
||||
Attend to all tokens in masked rows from the expanded attention mask, for example the relevant first rows when
|
||||
using left padding. This is required by F.scaled_dot_product_attention memory-efficient attention path.
|
||||
Details: https://github.com/pytorch/pytorch/issues/110213
|
||||
|
||||
`expanded_mask` is [bsz, num_masks, tgt_seq_len, src_seq_len] or [bsz, tgt_seq_len, src_seq_len].
|
||||
`attention_mask` is [bsz, src_seq_len].
|
||||
|
||||
The dimension num_masks of `expanded_mask` is most often 1, but it can also be the number of heads in the case of alibi attention bias.
|
||||
|
||||
For example, if `attention_mask` is
|
||||
```
|
||||
[[0, 0, 1],
|
||||
[1, 1, 1],
|
||||
[0, 1, 1]]
|
||||
```
|
||||
and `expanded_mask` is (e.g. here left-padding case)
|
||||
```
|
||||
[[[[0, 0, 0],
|
||||
[0, 0, 0],
|
||||
[0, 0, 1]]],
|
||||
[[[1, 0, 0],
|
||||
[1, 1, 0],
|
||||
[1, 1, 1]]],
|
||||
[[[0, 0, 0],
|
||||
[0, 1, 0],
|
||||
[0, 1, 1]]]]
|
||||
```
|
||||
then the modified `expanded_mask` will be
|
||||
```
|
||||
[[[[1, 1, 1], <-- modified
|
||||
[1, 1, 1], <-- modified
|
||||
[0, 0, 1]]],
|
||||
[[[1, 0, 0],
|
||||
[1, 1, 0],
|
||||
[1, 1, 1]]],
|
||||
[[[1, 1, 1], <-- modified
|
||||
[0, 1, 0],
|
||||
[0, 1, 1]]]]
|
||||
```
|
||||
"""
|
||||
# fmt: on
|
||||
|
||||
# Get the index of the first non-zero value for every sample in the batch.
|
||||
# In the above example, indices = [[2], [0], [1]]]
|
||||
tmp = torch.arange(attention_mask.shape[1], 0, -1)
|
||||
indices = torch.argmax(attention_mask.cpu() * tmp, 1, keepdim=True)
|
||||
|
||||
# Find the batch indexes that have unattended tokens on the leftmost side (e.g. [0, 0, 1, 1, 1]), for which the first rows of the
|
||||
# expanded mask will be completely unattended.
|
||||
left_masked_rows = torch.where(indices > 0)[0]
|
||||
|
||||
if left_masked_rows.shape[0] == 0:
|
||||
return expanded_mask
|
||||
indices = indices[left_masked_rows]
|
||||
|
||||
max_len = torch.max(indices)
|
||||
range_tensor = torch.arange(max_len).unsqueeze(0)
|
||||
range_tensor = range_tensor.repeat(indices.size(0), 1)
|
||||
|
||||
# Avoid unmasking tokens at relevant target positions (on the row axis), by rather unmasking possibly several times the first row that should always be unmasked as we filtered out the batch above.
|
||||
range_tensor[range_tensor >= indices] = 0
|
||||
|
||||
# TODO: we may drop support for 3D attention mask as the refactor from Patrick maybe dropped this case
|
||||
if expanded_mask.dim() == 4:
|
||||
num_masks = expanded_mask.shape[1]
|
||||
if num_masks == 1:
|
||||
# Broadcast [left_masked_rows, 1], [left_masked_rows, max_len]
|
||||
mask_slice = (left_masked_rows[:, None], 0, range_tensor)
|
||||
else:
|
||||
# Broadcast [left_masked_rows, 1, 1], [1, num_masks, 1], [left_masked_rows, 1, max_len]
|
||||
mask_slice = (
|
||||
left_masked_rows[:, None, None],
|
||||
torch.arange(num_masks)[None, :, None],
|
||||
range_tensor[:, None, :],
|
||||
)
|
||||
else:
|
||||
# Broadcast [left_masked_rows, 1], [left_masked_rows, max_len]
|
||||
mask_slice = (left_masked_rows[:, None], range_tensor)
|
||||
|
||||
expanded_mask[mask_slice] = unmasked_value
|
||||
|
||||
return expanded_mask
|
||||
|
||||
|
||||
def _prepare_4d_causal_attention_mask(
|
||||
attention_mask: Optional[torch.Tensor],
|
||||
input_shape: Union[torch.Size, Tuple, List],
|
||||
inputs_embeds: torch.Tensor,
|
||||
past_key_values_length: int,
|
||||
sliding_window: Optional[int] = None,
|
||||
):
|
||||
"""
|
||||
Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
|
||||
`(batch_size, key_value_length)`
|
||||
|
||||
Args:
|
||||
attention_mask (`torch.Tensor` or `None`):
|
||||
A 2D attention mask of shape `(batch_size, key_value_length)`
|
||||
input_shape (`tuple(int)` or `list(int)` or `torch.Size`):
|
||||
The input shape should be a tuple that defines `(batch_size, query_length)`.
|
||||
inputs_embeds (`torch.Tensor`):
|
||||
The embedded inputs as a torch Tensor.
|
||||
past_key_values_length (`int`):
|
||||
The length of the key value cache.
|
||||
sliding_window (`int`, *optional*):
|
||||
If the model uses windowed attention, a sliding window should be passed.
|
||||
"""
|
||||
attn_mask_converter = AttentionMaskConverter(is_causal=True, sliding_window=sliding_window)
|
||||
|
||||
key_value_length = input_shape[-1] + past_key_values_length
|
||||
|
||||
# 4d mask is passed through the layers
|
||||
if attention_mask is not None and len(attention_mask.shape) == 2:
|
||||
attention_mask = attn_mask_converter.to_4d(
|
||||
attention_mask, input_shape[-1], key_value_length=key_value_length, dtype=inputs_embeds.dtype
|
||||
)
|
||||
elif attention_mask is not None and len(attention_mask.shape) == 4:
|
||||
expected_shape = (input_shape[0], 1, input_shape[1], key_value_length)
|
||||
if tuple(attention_mask.shape) != expected_shape:
|
||||
raise ValueError(
|
||||
f"Incorrect 4D attention_mask shape: {tuple(attention_mask.shape)}; expected: {expected_shape}."
|
||||
)
|
||||
else:
|
||||
# if the 4D mask has correct shape - invert it and fill with negative infinity
|
||||
inverted_mask = 1.0 - attention_mask
|
||||
attention_mask = inverted_mask.masked_fill(
|
||||
inverted_mask.to(torch.bool), torch.finfo(inputs_embeds.dtype).min
|
||||
)
|
||||
else:
|
||||
attention_mask = attn_mask_converter.to_causal_4d(
|
||||
input_shape[0], input_shape[-1], key_value_length, dtype=inputs_embeds.dtype, device=inputs_embeds.device
|
||||
)
|
||||
|
||||
return attention_mask
|
||||
|
||||
|
||||
# Adapted from _prepare_4d_causal_attention_mask
|
||||
def _prepare_4d_causal_attention_mask_for_sdpa(
|
||||
attention_mask: Optional[torch.Tensor],
|
||||
input_shape: Union[torch.Size, Tuple, List],
|
||||
inputs_embeds: torch.Tensor,
|
||||
past_key_values_length: int,
|
||||
sliding_window: Optional[int] = None,
|
||||
):
|
||||
"""
|
||||
Prepares the correct `attn_mask` argument to be used by `torch.nn.functional.scaled_dot_product_attention`.
|
||||
|
||||
In case no token is masked in the `attention_mask` argument, we simply set it to `None` for the cases `query_length == 1` and
|
||||
`key_value_length == query_length`, and rely instead on SDPA `is_causal` argument to use causal/non-causal masks,
|
||||
allowing to dispatch to the flash attention kernel (that can otherwise not be used if a custom `attn_mask` is passed).
|
||||
"""
|
||||
attn_mask_converter = AttentionMaskConverter(is_causal=True, sliding_window=sliding_window)
|
||||
|
||||
key_value_length = input_shape[-1] + past_key_values_length
|
||||
batch_size, query_length = input_shape
|
||||
|
||||
# torch.jit.trace, symbolic_trace and torchdynamo with fullgraph=True are unable to capture the controlflow `is_causal=attention_mask is None and q_len > 1`
|
||||
# used as an SDPA argument. We keep compatibility with these tracing tools by always using SDPA's `attn_mask` argument in case we are tracing.
|
||||
# TODO: Fix this as well when using torchdynamo with fullgraph=True.
|
||||
is_tracing = torch.jit.is_tracing() or isinstance(inputs_embeds, torch.fx.Proxy)
|
||||
|
||||
if attention_mask is not None:
|
||||
# 4d mask is passed through
|
||||
if len(attention_mask.shape) == 4:
|
||||
expected_shape = (input_shape[0], 1, input_shape[1], key_value_length)
|
||||
if tuple(attention_mask.shape) != expected_shape:
|
||||
raise ValueError(
|
||||
f"Incorrect 4D attention_mask shape: {tuple(attention_mask.shape)}; expected: {expected_shape}."
|
||||
)
|
||||
else:
|
||||
# if the 4D mask has correct shape - invert it and fill with negative infinity
|
||||
inverted_mask = 1.0 - attention_mask.to(inputs_embeds.dtype)
|
||||
attention_mask = inverted_mask.masked_fill(
|
||||
inverted_mask.to(torch.bool), torch.finfo(inputs_embeds.dtype).min
|
||||
)
|
||||
return attention_mask
|
||||
|
||||
elif not is_tracing and torch.all(attention_mask == 1):
|
||||
if query_length == 1:
|
||||
# For query_length == 1, causal attention and bi-directional attention are the same.
|
||||
attention_mask = None
|
||||
elif key_value_length == query_length:
|
||||
attention_mask = None
|
||||
else:
|
||||
# Unfortunately, for query_length > 1 and key_value_length != query_length, we cannot generally ignore the attention mask, as SDPA causal mask generation
|
||||
# may be wrong. We will set `is_causal=False` in SDPA and rely on Transformers attention_mask instead, hence not setting it to None here.
|
||||
# Reference: https://github.com/pytorch/pytorch/issues/108108
|
||||
pass
|
||||
elif query_length > 1 and key_value_length != query_length:
|
||||
# See the comment above (https://github.com/pytorch/pytorch/issues/108108).
|
||||
# Ugly: we set it to True here to dispatch in the following controlflow to `to_causal_4d`.
|
||||
attention_mask = True
|
||||
elif is_tracing:
|
||||
raise ValueError(
|
||||
'Attention using SDPA can not be traced with torch.jit.trace when no attention_mask is provided. To solve this issue, please either load your model with the argument `attn_implementation="eager"` or pass an attention_mask input when tracing the model.'
|
||||
)
|
||||
|
||||
if attention_mask is None:
|
||||
expanded_4d_mask = None
|
||||
elif attention_mask is True:
|
||||
expanded_4d_mask = attn_mask_converter.to_causal_4d(
|
||||
input_shape[0], input_shape[-1], key_value_length, dtype=inputs_embeds.dtype, device=inputs_embeds.device
|
||||
)
|
||||
else:
|
||||
expanded_4d_mask = attn_mask_converter.to_4d(
|
||||
attention_mask,
|
||||
input_shape[-1],
|
||||
dtype=inputs_embeds.dtype,
|
||||
key_value_length=key_value_length,
|
||||
)
|
||||
|
||||
# From PyTorch 2.1 onwards, F.scaled_dot_product_attention with the memory-efficient attention backend
|
||||
# produces nans if sequences are completely unattended in the attention mask. Details: https://github.com/pytorch/pytorch/issues/110213
|
||||
#
|
||||
# This fix is not applied in case we are tracing with torch.jit.trace or symbolic_trace, as _unmask_unattended has a data-dependent
|
||||
# controlflow that can not be captured properly.
|
||||
# TODO: _unmask_unattended does not work either with torch.compile when using fullgraph=True. We should find a way to detect this case.
|
||||
if query_length > 1 and not is_tracing:
|
||||
expanded_4d_mask = AttentionMaskConverter._unmask_unattended(
|
||||
expanded_4d_mask, attention_mask, unmasked_value=0.0
|
||||
)
|
||||
|
||||
return expanded_4d_mask
|
||||
|
||||
|
||||
def _prepare_4d_attention_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None):
|
||||
"""
|
||||
Creates a non-causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
|
||||
`(batch_size, key_value_length)`
|
||||
|
||||
Args:
|
||||
mask (`torch.Tensor` or `None`):
|
||||
A 2D attention mask of shape `(batch_size, key_value_length)`
|
||||
dtype (`torch.dtype`):
|
||||
The torch dtype the created mask shall have.
|
||||
tgt_len (`int`):
|
||||
The target length or query length the created mask shall have.
|
||||
"""
|
||||
return AttentionMaskConverter._expand_mask(mask=mask, dtype=dtype, tgt_len=tgt_len)
|
||||
|
||||
|
||||
def _prepare_4d_attention_mask_for_sdpa(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None):
|
||||
"""
|
||||
Creates a non-causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
|
||||
`(batch_size, key_value_length)`
|
||||
|
||||
Args:
|
||||
mask (`torch.Tensor` or `None`):
|
||||
A 2D attention mask of shape `(batch_size, key_value_length)`
|
||||
dtype (`torch.dtype`):
|
||||
The torch dtype the created mask shall have.
|
||||
tgt_len (`int`):
|
||||
The target length or query length the created mask shall have.
|
||||
"""
|
||||
batch_size, key_value_length = mask.shape
|
||||
tgt_len = tgt_len if tgt_len is not None else key_value_length
|
||||
|
||||
# torch.jit.trace and torchdynamo with fullgraph=True are unable to capture the controlflow `is_causal=attention_mask is None and q_len > 1`
|
||||
# used as an SDPA argument. We keep compatibility with these tracing tools by always using SDPA's `attn_mask` argument in case we are tracing.
|
||||
# TODO: Fix this as well when using torchdynamo with fullgraph=True.
|
||||
is_tracing = torch.jit.is_tracing()
|
||||
|
||||
if torch.all(mask == 1):
|
||||
if is_tracing:
|
||||
pass
|
||||
elif tgt_len == 1:
|
||||
# For query_length == 1, causal attention and bi-directional attention are the same.
|
||||
return None
|
||||
elif key_value_length == tgt_len:
|
||||
return None
|
||||
else:
|
||||
# Unfortunately, for query_length > 1 and key_value_length != query_length, we can not generally ignore the attention mask, as SDPA causal mask generation
|
||||
# may be wrong. We will set is_causal=False in SDPA and rely on Transformers attention_mask instead, hence not setting it to None here.
|
||||
# Reference: https://github.com/pytorch/pytorch/issues/108108
|
||||
return AttentionMaskConverter._expand_mask(mask=mask, dtype=dtype, tgt_len=tgt_len)
|
||||
else:
|
||||
return AttentionMaskConverter._expand_mask(mask=mask, dtype=dtype, tgt_len=tgt_len)
|
||||
|
||||
|
||||
def _create_4d_causal_attention_mask(
|
||||
input_shape: Union[torch.Size, Tuple, List],
|
||||
dtype: torch.dtype,
|
||||
device: torch.device,
|
||||
past_key_values_length: int = 0,
|
||||
sliding_window: Optional[int] = None,
|
||||
) -> Optional[torch.Tensor]:
|
||||
"""
|
||||
Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)`
|
||||
|
||||
Args:
|
||||
input_shape (`tuple(int)` or `list(int)` or `torch.Size`):
|
||||
The input shape should be a tuple that defines `(batch_size, query_length)`.
|
||||
dtype (`torch.dtype`):
|
||||
The torch dtype the created mask shall have.
|
||||
device (`int`):
|
||||
The torch device the created mask shall have.
|
||||
sliding_window (`int`, *optional*):
|
||||
If the model uses windowed attention, a sliding window should be passed.
|
||||
"""
|
||||
attn_mask_converter = AttentionMaskConverter(is_causal=True, sliding_window=sliding_window)
|
||||
|
||||
key_value_length = past_key_values_length + input_shape[-1]
|
||||
attention_mask = attn_mask_converter.to_causal_4d(
|
||||
input_shape[0], input_shape[-1], key_value_length, dtype=dtype, device=device
|
||||
)
|
||||
|
||||
return attention_mask
|
||||
1949
ixformer_sdk/train/speedformer/models/gpt2/modeling_gpt2.py
Normal file
1949
ixformer_sdk/train/speedformer/models/gpt2/modeling_gpt2.py
Normal file
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,191 @@
|
||||
# coding=utf-8
|
||||
# Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.
|
||||
#
|
||||
# This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
|
||||
# and OPT implementations in this library. It has been modified from its
|
||||
# original forms to accommodate minor architectural differences compared
|
||||
# to GPT-NeoX and OPT used by the Meta AI team that trained the model.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
""" LLaMA model configuration"""
|
||||
|
||||
from transformers.configuration_utils import PretrainedConfig
|
||||
from transformers.utils import logging
|
||||
|
||||
|
||||
logger = logging.get_logger(__name__)
|
||||
|
||||
LLAMA_PRETRAINED_CONFIG_ARCHIVE_MAP = {}
|
||||
|
||||
|
||||
class LlamaConfig(PretrainedConfig):
|
||||
r"""
|
||||
This is the configuration class to store the configuration of a [`LlamaModel`]. It is used to instantiate an LLaMA
|
||||
model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
|
||||
defaults will yield a similar configuration to that of the LLaMA-7B.
|
||||
|
||||
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
||||
documentation from [`PretrainedConfig`] for more information.
|
||||
|
||||
|
||||
Args:
|
||||
vocab_size (`int`, *optional*, defaults to 32000):
|
||||
Vocabulary size of the LLaMA model. Defines the number of different tokens that can be represented by the
|
||||
`inputs_ids` passed when calling [`LlamaModel`]
|
||||
hidden_size (`int`, *optional*, defaults to 4096):
|
||||
Dimension of the hidden representations.
|
||||
intermediate_size (`int`, *optional*, defaults to 11008):
|
||||
Dimension of the MLP representations.
|
||||
num_hidden_layers (`int`, *optional*, defaults to 32):
|
||||
Number of hidden layers in the Transformer decoder.
|
||||
num_attention_heads (`int`, *optional*, defaults to 32):
|
||||
Number of attention heads for each attention layer in the Transformer decoder.
|
||||
num_key_value_heads (`int`, *optional*):
|
||||
This is the number of key_value heads that should be used to implement Grouped Query Attention. If
|
||||
`num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
|
||||
`num_key_value_heads=1 the model will use Multi Query Attention (MQA) otherwise GQA is used. When
|
||||
converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
|
||||
by meanpooling all the original heads within that group. For more details checkout [this
|
||||
paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to
|
||||
`num_attention_heads`.
|
||||
hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
|
||||
The non-linear activation function (function or string) in the decoder.
|
||||
max_position_embeddings (`int`, *optional*, defaults to 2048):
|
||||
The maximum sequence length that this model might ever be used with. Llama 1 supports up to 2048 tokens,
|
||||
Llama 2 up to 4096, CodeLlama up to 16384.
|
||||
initializer_range (`float`, *optional*, defaults to 0.02):
|
||||
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
||||
rms_norm_eps (`float`, *optional*, defaults to 1e-06):
|
||||
The epsilon used by the rms normalization layers.
|
||||
use_cache (`bool`, *optional*, defaults to `True`):
|
||||
Whether or not the model should return the last key/values attentions (not used by all models). Only
|
||||
relevant if `config.is_decoder=True`.
|
||||
pad_token_id (`int`, *optional*):
|
||||
Padding token id.
|
||||
bos_token_id (`int`, *optional*, defaults to 1):
|
||||
Beginning of stream token id.
|
||||
eos_token_id (`int`, *optional*, defaults to 2):
|
||||
End of stream token id.
|
||||
pretraining_tp (`int`, *optional*, defaults to 1):
|
||||
Experimental feature. Tensor parallelism rank used during pretraining. Please refer to [this
|
||||
document](https://huggingface.co/docs/transformers/parallelism) to understand more about it. This value is
|
||||
necessary to ensure exact reproducibility of the pretraining results. Please refer to [this
|
||||
issue](https://github.com/pytorch/pytorch/issues/76232).
|
||||
tie_word_embeddings (`bool`, *optional*, defaults to `False`):
|
||||
Whether to tie weight embeddings
|
||||
rope_theta (`float`, *optional*, defaults to 10000.0):
|
||||
The base period of the RoPE embeddings.
|
||||
rope_scaling (`Dict`, *optional*):
|
||||
Dictionary containing the scaling configuration for the RoPE embeddings. Currently supports two scaling
|
||||
strategies: linear and dynamic. Their scaling factor must be a float greater than 1. The expected format is
|
||||
`{"type": strategy name, "factor": scaling factor}`. When using this flag, don't update
|
||||
`max_position_embeddings` to the expected new maximum. See the following thread for more information on how
|
||||
these scaling strategies behave:
|
||||
https://www.reddit.com/r/LocalLLaMA/comments/14mrgpr/dynamically_scaled_rope_further_increases/. This is an
|
||||
experimental feature, subject to breaking API changes in future versions.
|
||||
attention_bias (`bool`, defaults to `False`, *optional*, defaults to `False`):
|
||||
Whether to use a bias in the query, key, value and output projection layers during self-attention.
|
||||
attention_dropout (`float`, *optional*, defaults to 0.0):
|
||||
The dropout ratio for the attention probabilities.
|
||||
|
||||
```python
|
||||
>>> from transformers import LlamaModel, LlamaConfig
|
||||
|
||||
>>> # Initializing a LLaMA llama-7b style configuration
|
||||
>>> configuration = LlamaConfig()
|
||||
|
||||
>>> # Initializing a model from the llama-7b style configuration
|
||||
>>> model = LlamaModel(configuration)
|
||||
|
||||
>>> # Accessing the model configuration
|
||||
>>> configuration = model.config
|
||||
```"""
|
||||
|
||||
model_type = "llama"
|
||||
keys_to_ignore_at_inference = ["past_key_values"]
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
vocab_size=32000,
|
||||
hidden_size=4096,
|
||||
intermediate_size=11008,
|
||||
num_hidden_layers=32,
|
||||
num_attention_heads=32,
|
||||
num_key_value_heads=None,
|
||||
hidden_act="silu",
|
||||
max_position_embeddings=2048,
|
||||
initializer_range=0.02,
|
||||
rms_norm_eps=1e-6,
|
||||
use_cache=True,
|
||||
pad_token_id=None,
|
||||
bos_token_id=1,
|
||||
eos_token_id=2,
|
||||
pretraining_tp=1,
|
||||
tie_word_embeddings=False,
|
||||
rope_theta=10000.0,
|
||||
rope_scaling=None,
|
||||
attention_bias=False,
|
||||
attention_dropout=0.0,
|
||||
**kwargs,
|
||||
):
|
||||
self.vocab_size = vocab_size
|
||||
self.max_position_embeddings = max_position_embeddings
|
||||
self.hidden_size = hidden_size
|
||||
self.intermediate_size = intermediate_size
|
||||
self.num_hidden_layers = num_hidden_layers
|
||||
self.num_attention_heads = num_attention_heads
|
||||
|
||||
# for backward compatibility
|
||||
if num_key_value_heads is None:
|
||||
num_key_value_heads = num_attention_heads
|
||||
|
||||
self.num_key_value_heads = num_key_value_heads
|
||||
self.hidden_act = hidden_act
|
||||
self.initializer_range = initializer_range
|
||||
self.rms_norm_eps = rms_norm_eps
|
||||
self.pretraining_tp = pretraining_tp
|
||||
self.use_cache = use_cache
|
||||
self.rope_theta = rope_theta
|
||||
self.rope_scaling = rope_scaling
|
||||
self._rope_scaling_validation()
|
||||
self.attention_bias = attention_bias
|
||||
self.attention_dropout = attention_dropout
|
||||
|
||||
super().__init__(
|
||||
pad_token_id=pad_token_id,
|
||||
bos_token_id=bos_token_id,
|
||||
eos_token_id=eos_token_id,
|
||||
tie_word_embeddings=tie_word_embeddings,
|
||||
**kwargs,
|
||||
)
|
||||
|
||||
def _rope_scaling_validation(self):
|
||||
"""
|
||||
Validate the `rope_scaling` configuration.
|
||||
"""
|
||||
if self.rope_scaling is None:
|
||||
return
|
||||
|
||||
if not isinstance(self.rope_scaling, dict) or len(self.rope_scaling) != 2:
|
||||
raise ValueError(
|
||||
"`rope_scaling` must be a dictionary with with two fields, `type` and `factor`, "
|
||||
f"got {self.rope_scaling}"
|
||||
)
|
||||
rope_scaling_type = self.rope_scaling.get("type", None)
|
||||
rope_scaling_factor = self.rope_scaling.get("factor", None)
|
||||
if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]:
|
||||
raise ValueError(
|
||||
f"`rope_scaling`'s type field must be one of ['linear', 'dynamic'], got {rope_scaling_type}"
|
||||
)
|
||||
if rope_scaling_factor is None or not isinstance(rope_scaling_factor, float) or rope_scaling_factor <= 1.0:
|
||||
raise ValueError(f"`rope_scaling`'s factor field must be a float > 1, got {rope_scaling_factor}")
|
||||
@@ -0,0 +1,500 @@
|
||||
# Copyright 2023 The HuggingFace Team. All rights reserved.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
from dataclasses import dataclass
|
||||
from typing import List, Optional, Tuple, Union
|
||||
|
||||
import torch
|
||||
|
||||
|
||||
@dataclass
|
||||
class AttentionMaskConverter:
|
||||
"""
|
||||
A utility attention mask class that allows one to:
|
||||
- Create a causal 4d mask
|
||||
- Create a causal 4d mask with slided window
|
||||
- Convert a 2d attention mask (batch_size, query_length) to a 4d attention mask (batch_size, 1, query_length,
|
||||
key_value_length) that can be multiplied with attention scores
|
||||
|
||||
Examples:
|
||||
|
||||
```python
|
||||
>>> import torch
|
||||
>>> from transformers.modeling_attn_mask_utils import AttentionMaskConverter
|
||||
|
||||
>>> converter = AttentionMaskConverter(True)
|
||||
>>> converter.to_4d(torch.tensor([[0, 0, 0, 1, 1]]), 5, key_value_length=5, dtype=torch.float32)
|
||||
tensor([[[[-3.4028e+38, -3.4028e+38, -3.4028e+38, -3.4028e+38, -3.4028e+38],
|
||||
[-3.4028e+38, -3.4028e+38, -3.4028e+38, -3.4028e+38, -3.4028e+38],
|
||||
[-3.4028e+38, -3.4028e+38, -3.4028e+38, -3.4028e+38, -3.4028e+38],
|
||||
[-3.4028e+38, -3.4028e+38, -3.4028e+38, 0.0000e+00, -3.4028e+38],
|
||||
[-3.4028e+38, -3.4028e+38, -3.4028e+38, 0.0000e+00, 0.0000e+00]]]])
|
||||
```
|
||||
|
||||
Parameters:
|
||||
is_causal (`bool`):
|
||||
Whether the attention mask should be a uni-directional (causal) or bi-directional mask.
|
||||
|
||||
sliding_window (`int`, *optional*):
|
||||
Optionally, the sliding window masks can be created if `sliding_window` is defined to a positive integer.
|
||||
"""
|
||||
|
||||
is_causal: bool
|
||||
sliding_window: int
|
||||
|
||||
def __init__(self, is_causal: bool, sliding_window: Optional[int] = None):
|
||||
self.is_causal = is_causal
|
||||
self.sliding_window = sliding_window
|
||||
|
||||
if self.sliding_window is not None and self.sliding_window <= 0:
|
||||
raise ValueError(
|
||||
f"Make sure that when passing `sliding_window` that its value is a strictly positive integer, not `{self.sliding_window}`"
|
||||
)
|
||||
|
||||
def to_causal_4d(
|
||||
self,
|
||||
batch_size: int,
|
||||
query_length: int,
|
||||
key_value_length: int,
|
||||
dtype: torch.dtype,
|
||||
device: Union[torch.device, "str"] = "cpu",
|
||||
) -> Optional[torch.Tensor]:
|
||||
"""
|
||||
Creates a causal 4D mask of (bsz, head_dim=1, query_length, key_value_length) shape and adds large negative
|
||||
bias to upper right hand triangular matrix (causal mask).
|
||||
"""
|
||||
if not self.is_causal:
|
||||
raise ValueError(f"Please use `to_causal_4d` only if {self.__class__} has `is_causal` set to True.")
|
||||
|
||||
# If shape is not cached, create a new causal mask and cache it
|
||||
input_shape = (batch_size, query_length)
|
||||
past_key_values_length = key_value_length - query_length
|
||||
|
||||
# create causal mask
|
||||
# [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
|
||||
causal_4d_mask = None
|
||||
if input_shape[-1] > 1 or self.sliding_window is not None:
|
||||
causal_4d_mask = self._make_causal_mask(
|
||||
input_shape,
|
||||
dtype,
|
||||
device=device,
|
||||
past_key_values_length=past_key_values_length,
|
||||
sliding_window=self.sliding_window,
|
||||
)
|
||||
|
||||
return causal_4d_mask
|
||||
|
||||
def to_4d(
|
||||
self,
|
||||
attention_mask_2d: torch.Tensor,
|
||||
query_length: int,
|
||||
dtype: torch.dtype,
|
||||
key_value_length: Optional[int] = None,
|
||||
) -> torch.Tensor:
|
||||
"""
|
||||
Converts 2D attention mask to 4D attention mask by expanding mask to (bsz, head_dim=1, query_length,
|
||||
key_value_length) shape and by adding a large negative bias to not-attended positions. If attention_mask is
|
||||
causal, a causal mask will be added.
|
||||
"""
|
||||
input_shape = (attention_mask_2d.shape[0], query_length)
|
||||
|
||||
# create causal mask
|
||||
# [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
|
||||
causal_4d_mask = None
|
||||
if (input_shape[-1] > 1 or self.sliding_window is not None) and self.is_causal:
|
||||
if key_value_length is None:
|
||||
raise ValueError(
|
||||
"This attention mask converter is causal. Make sure to pass `key_value_length` to correctly create a causal mask."
|
||||
)
|
||||
|
||||
past_key_values_length = key_value_length - query_length
|
||||
causal_4d_mask = self._make_causal_mask(
|
||||
input_shape,
|
||||
dtype,
|
||||
device=attention_mask_2d.device,
|
||||
past_key_values_length=past_key_values_length,
|
||||
sliding_window=self.sliding_window,
|
||||
)
|
||||
elif self.sliding_window is not None:
|
||||
raise NotImplementedError("Sliding window is currently only implemented for causal masking")
|
||||
|
||||
# [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
|
||||
expanded_attn_mask = self._expand_mask(attention_mask_2d, dtype, tgt_len=input_shape[-1]).to(
|
||||
attention_mask_2d.device
|
||||
)
|
||||
|
||||
if causal_4d_mask is not None:
|
||||
expanded_attn_mask = causal_4d_mask.masked_fill(expanded_attn_mask.bool(), torch.finfo(dtype).min)
|
||||
|
||||
# expanded_attn_mask + causal_4d_mask can cause some overflow
|
||||
expanded_4d_mask = expanded_attn_mask
|
||||
|
||||
return expanded_4d_mask
|
||||
|
||||
@staticmethod
|
||||
def _make_causal_mask(
|
||||
input_ids_shape: torch.Size,
|
||||
dtype: torch.dtype,
|
||||
device: torch.device,
|
||||
past_key_values_length: int = 0,
|
||||
sliding_window: Optional[int] = None,
|
||||
):
|
||||
"""
|
||||
Make causal mask used for bi-directional self-attention.
|
||||
"""
|
||||
bsz, tgt_len = input_ids_shape
|
||||
mask = torch.full((tgt_len, tgt_len), torch.finfo(dtype).min, device=device)
|
||||
mask_cond = torch.arange(mask.size(-1), device=device)
|
||||
mask.masked_fill_(mask_cond < (mask_cond + 1).view(mask.size(-1), 1), 0)
|
||||
|
||||
mask = mask.to(dtype)
|
||||
|
||||
if past_key_values_length > 0:
|
||||
mask = torch.cat([torch.zeros(tgt_len, past_key_values_length, dtype=dtype, device=device), mask], dim=-1)
|
||||
|
||||
# add lower triangular sliding window mask if necessary
|
||||
if sliding_window is not None:
|
||||
diagonal = past_key_values_length - sliding_window + 1
|
||||
|
||||
context_mask = 1 - torch.triu(torch.ones_like(mask, dtype=torch.int), diagonal=diagonal)
|
||||
mask.masked_fill_(context_mask.bool(), torch.finfo(dtype).min)
|
||||
|
||||
return mask[None, None, :, :].expand(bsz, 1, tgt_len, tgt_len + past_key_values_length)
|
||||
|
||||
@staticmethod
|
||||
def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None):
|
||||
"""
|
||||
Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.
|
||||
"""
|
||||
bsz, src_len = mask.size()
|
||||
tgt_len = tgt_len if tgt_len is not None else src_len
|
||||
|
||||
expanded_mask = mask[:, None, None, :].expand(bsz, 1, tgt_len, src_len).to(dtype)
|
||||
|
||||
inverted_mask = 1.0 - expanded_mask
|
||||
|
||||
return inverted_mask.masked_fill(inverted_mask.to(torch.bool), torch.finfo(dtype).min)
|
||||
|
||||
@staticmethod
|
||||
def _unmask_unattended(
|
||||
expanded_mask: torch.Tensor, attention_mask: torch.Tensor, unmasked_value: Union[bool, float]
|
||||
):
|
||||
# fmt: off
|
||||
"""
|
||||
Attend to all tokens in masked rows from the expanded attention mask, for example the relevant first rows when
|
||||
using left padding. This is required by F.scaled_dot_product_attention memory-efficient attention path.
|
||||
Details: https://github.com/pytorch/pytorch/issues/110213
|
||||
|
||||
`expanded_mask` is [bsz, num_masks, tgt_seq_len, src_seq_len] or [bsz, tgt_seq_len, src_seq_len].
|
||||
`attention_mask` is [bsz, src_seq_len].
|
||||
|
||||
The dimension num_masks of `expanded_mask` is most often 1, but it can also be the number of heads in the case of alibi attention bias.
|
||||
|
||||
For example, if `attention_mask` is
|
||||
```
|
||||
[[0, 0, 1],
|
||||
[1, 1, 1],
|
||||
[0, 1, 1]]
|
||||
```
|
||||
and `expanded_mask` is (e.g. here left-padding case)
|
||||
```
|
||||
[[[[0, 0, 0],
|
||||
[0, 0, 0],
|
||||
[0, 0, 1]]],
|
||||
[[[1, 0, 0],
|
||||
[1, 1, 0],
|
||||
[1, 1, 1]]],
|
||||
[[[0, 0, 0],
|
||||
[0, 1, 0],
|
||||
[0, 1, 1]]]]
|
||||
```
|
||||
then the modified `expanded_mask` will be
|
||||
```
|
||||
[[[[1, 1, 1], <-- modified
|
||||
[1, 1, 1], <-- modified
|
||||
[0, 0, 1]]],
|
||||
[[[1, 0, 0],
|
||||
[1, 1, 0],
|
||||
[1, 1, 1]]],
|
||||
[[[1, 1, 1], <-- modified
|
||||
[0, 1, 0],
|
||||
[0, 1, 1]]]]
|
||||
```
|
||||
"""
|
||||
# fmt: on
|
||||
|
||||
# Get the index of the first non-zero value for every sample in the batch.
|
||||
# In the above example, indices = [[2], [0], [1]]]
|
||||
tmp = torch.arange(attention_mask.shape[1], 0, -1)
|
||||
indices = torch.argmax(attention_mask.cpu() * tmp, 1, keepdim=True)
|
||||
|
||||
# Find the batch indexes that have unattended tokens on the leftmost side (e.g. [0, 0, 1, 1, 1]), for which the first rows of the
|
||||
# expanded mask will be completely unattended.
|
||||
left_masked_rows = torch.where(indices > 0)[0]
|
||||
|
||||
if left_masked_rows.shape[0] == 0:
|
||||
return expanded_mask
|
||||
indices = indices[left_masked_rows]
|
||||
|
||||
max_len = torch.max(indices)
|
||||
range_tensor = torch.arange(max_len).unsqueeze(0)
|
||||
range_tensor = range_tensor.repeat(indices.size(0), 1)
|
||||
|
||||
# Avoid unmasking tokens at relevant target positions (on the row axis), by rather unmasking possibly several times the first row that should always be unmasked as we filtered out the batch above.
|
||||
range_tensor[range_tensor >= indices] = 0
|
||||
|
||||
# TODO: we may drop support for 3D attention mask as the refactor from Patrick maybe dropped this case
|
||||
if expanded_mask.dim() == 4:
|
||||
num_masks = expanded_mask.shape[1]
|
||||
if num_masks == 1:
|
||||
# Broadcast [left_masked_rows, 1], [left_masked_rows, max_len]
|
||||
mask_slice = (left_masked_rows[:, None], 0, range_tensor)
|
||||
else:
|
||||
# Broadcast [left_masked_rows, 1, 1], [1, num_masks, 1], [left_masked_rows, 1, max_len]
|
||||
mask_slice = (
|
||||
left_masked_rows[:, None, None],
|
||||
torch.arange(num_masks)[None, :, None],
|
||||
range_tensor[:, None, :],
|
||||
)
|
||||
else:
|
||||
# Broadcast [left_masked_rows, 1], [left_masked_rows, max_len]
|
||||
mask_slice = (left_masked_rows[:, None], range_tensor)
|
||||
|
||||
expanded_mask[mask_slice] = unmasked_value
|
||||
|
||||
return expanded_mask
|
||||
|
||||
|
||||
def _prepare_4d_causal_attention_mask(
|
||||
attention_mask: Optional[torch.Tensor],
|
||||
input_shape: Union[torch.Size, Tuple, List],
|
||||
inputs_embeds: torch.Tensor,
|
||||
past_key_values_length: int,
|
||||
sliding_window: Optional[int] = None,
|
||||
):
|
||||
"""
|
||||
Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
|
||||
`(batch_size, key_value_length)`
|
||||
|
||||
Args:
|
||||
attention_mask (`torch.Tensor` or `None`):
|
||||
A 2D attention mask of shape `(batch_size, key_value_length)`
|
||||
input_shape (`tuple(int)` or `list(int)` or `torch.Size`):
|
||||
The input shape should be a tuple that defines `(batch_size, query_length)`.
|
||||
inputs_embeds (`torch.Tensor`):
|
||||
The embedded inputs as a torch Tensor.
|
||||
past_key_values_length (`int`):
|
||||
The length of the key value cache.
|
||||
sliding_window (`int`, *optional*):
|
||||
If the model uses windowed attention, a sliding window should be passed.
|
||||
"""
|
||||
attn_mask_converter = AttentionMaskConverter(is_causal=True, sliding_window=sliding_window)
|
||||
|
||||
key_value_length = input_shape[-1] + past_key_values_length
|
||||
|
||||
# 4d mask is passed through the layers
|
||||
if attention_mask is not None and len(attention_mask.shape) == 2:
|
||||
attention_mask = attn_mask_converter.to_4d(
|
||||
attention_mask, input_shape[-1], key_value_length=key_value_length, dtype=inputs_embeds.dtype
|
||||
)
|
||||
elif attention_mask is not None and len(attention_mask.shape) == 4:
|
||||
expected_shape = (input_shape[0], 1, input_shape[1], key_value_length)
|
||||
if tuple(attention_mask.shape) != expected_shape:
|
||||
raise ValueError(
|
||||
f"Incorrect 4D attention_mask shape: {tuple(attention_mask.shape)}; expected: {expected_shape}."
|
||||
)
|
||||
else:
|
||||
# if the 4D mask has correct shape - invert it and fill with negative infinity
|
||||
inverted_mask = 1.0 - attention_mask
|
||||
attention_mask = inverted_mask.masked_fill(
|
||||
inverted_mask.to(torch.bool), torch.finfo(inputs_embeds.dtype).min
|
||||
)
|
||||
else:
|
||||
attention_mask = attn_mask_converter.to_causal_4d(
|
||||
input_shape[0], input_shape[-1], key_value_length, dtype=inputs_embeds.dtype, device=inputs_embeds.device
|
||||
)
|
||||
|
||||
return attention_mask
|
||||
|
||||
|
||||
# Adapted from _prepare_4d_causal_attention_mask
|
||||
def _prepare_4d_causal_attention_mask_for_sdpa(
|
||||
attention_mask: Optional[torch.Tensor],
|
||||
input_shape: Union[torch.Size, Tuple, List],
|
||||
inputs_embeds: torch.Tensor,
|
||||
past_key_values_length: int,
|
||||
sliding_window: Optional[int] = None,
|
||||
):
|
||||
"""
|
||||
Prepares the correct `attn_mask` argument to be used by `torch.nn.functional.scaled_dot_product_attention`.
|
||||
|
||||
In case no token is masked in the `attention_mask` argument, we simply set it to `None` for the cases `query_length == 1` and
|
||||
`key_value_length == query_length`, and rely instead on SDPA `is_causal` argument to use causal/non-causal masks,
|
||||
allowing to dispatch to the flash attention kernel (that can otherwise not be used if a custom `attn_mask` is passed).
|
||||
"""
|
||||
attn_mask_converter = AttentionMaskConverter(is_causal=True, sliding_window=sliding_window)
|
||||
|
||||
key_value_length = input_shape[-1] + past_key_values_length
|
||||
batch_size, query_length = input_shape
|
||||
|
||||
# torch.jit.trace, symbolic_trace and torchdynamo with fullgraph=True are unable to capture the controlflow `is_causal=attention_mask is None and q_len > 1`
|
||||
# used as an SDPA argument. We keep compatibility with these tracing tools by always using SDPA's `attn_mask` argument in case we are tracing.
|
||||
# TODO: Fix this as well when using torchdynamo with fullgraph=True.
|
||||
is_tracing = torch.jit.is_tracing() or isinstance(inputs_embeds, torch.fx.Proxy)
|
||||
|
||||
if attention_mask is not None:
|
||||
# 4d mask is passed through
|
||||
if len(attention_mask.shape) == 4:
|
||||
expected_shape = (input_shape[0], 1, input_shape[1], key_value_length)
|
||||
if tuple(attention_mask.shape) != expected_shape:
|
||||
raise ValueError(
|
||||
f"Incorrect 4D attention_mask shape: {tuple(attention_mask.shape)}; expected: {expected_shape}."
|
||||
)
|
||||
else:
|
||||
# if the 4D mask has correct shape - invert it and fill with negative infinity
|
||||
inverted_mask = 1.0 - attention_mask.to(inputs_embeds.dtype)
|
||||
attention_mask = inverted_mask.masked_fill(
|
||||
inverted_mask.to(torch.bool), torch.finfo(inputs_embeds.dtype).min
|
||||
)
|
||||
return attention_mask
|
||||
|
||||
elif not is_tracing and torch.all(attention_mask == 1):
|
||||
if query_length == 1:
|
||||
# For query_length == 1, causal attention and bi-directional attention are the same.
|
||||
attention_mask = None
|
||||
elif key_value_length == query_length:
|
||||
attention_mask = None
|
||||
else:
|
||||
# Unfortunately, for query_length > 1 and key_value_length != query_length, we cannot generally ignore the attention mask, as SDPA causal mask generation
|
||||
# may be wrong. We will set `is_causal=False` in SDPA and rely on Transformers attention_mask instead, hence not setting it to None here.
|
||||
# Reference: https://github.com/pytorch/pytorch/issues/108108
|
||||
pass
|
||||
elif query_length > 1 and key_value_length != query_length:
|
||||
# See the comment above (https://github.com/pytorch/pytorch/issues/108108).
|
||||
# Ugly: we set it to True here to dispatch in the following controlflow to `to_causal_4d`.
|
||||
attention_mask = True
|
||||
elif is_tracing:
|
||||
raise ValueError(
|
||||
'Attention using SDPA can not be traced with torch.jit.trace when no attention_mask is provided. To solve this issue, please either load your model with the argument `attn_implementation="eager"` or pass an attention_mask input when tracing the model.'
|
||||
)
|
||||
|
||||
if attention_mask is None:
|
||||
expanded_4d_mask = None
|
||||
elif attention_mask is True:
|
||||
expanded_4d_mask = attn_mask_converter.to_causal_4d(
|
||||
input_shape[0], input_shape[-1], key_value_length, dtype=inputs_embeds.dtype, device=inputs_embeds.device
|
||||
)
|
||||
else:
|
||||
expanded_4d_mask = attn_mask_converter.to_4d(
|
||||
attention_mask,
|
||||
input_shape[-1],
|
||||
dtype=inputs_embeds.dtype,
|
||||
key_value_length=key_value_length,
|
||||
)
|
||||
|
||||
# From PyTorch 2.1 onwards, F.scaled_dot_product_attention with the memory-efficient attention backend
|
||||
# produces nans if sequences are completely unattended in the attention mask. Details: https://github.com/pytorch/pytorch/issues/110213
|
||||
#
|
||||
# This fix is not applied in case we are tracing with torch.jit.trace or symbolic_trace, as _unmask_unattended has a data-dependent
|
||||
# controlflow that can not be captured properly.
|
||||
# TODO: _unmask_unattended does not work either with torch.compile when using fullgraph=True. We should find a way to detect this case.
|
||||
if query_length > 1 and not is_tracing:
|
||||
expanded_4d_mask = AttentionMaskConverter._unmask_unattended(
|
||||
expanded_4d_mask, attention_mask, unmasked_value=0.0
|
||||
)
|
||||
|
||||
return expanded_4d_mask
|
||||
|
||||
|
||||
def _prepare_4d_attention_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None):
|
||||
"""
|
||||
Creates a non-causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
|
||||
`(batch_size, key_value_length)`
|
||||
|
||||
Args:
|
||||
mask (`torch.Tensor` or `None`):
|
||||
A 2D attention mask of shape `(batch_size, key_value_length)`
|
||||
dtype (`torch.dtype`):
|
||||
The torch dtype the created mask shall have.
|
||||
tgt_len (`int`):
|
||||
The target length or query length the created mask shall have.
|
||||
"""
|
||||
return AttentionMaskConverter._expand_mask(mask=mask, dtype=dtype, tgt_len=tgt_len)
|
||||
|
||||
|
||||
def _prepare_4d_attention_mask_for_sdpa(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None):
|
||||
"""
|
||||
Creates a non-causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
|
||||
`(batch_size, key_value_length)`
|
||||
|
||||
Args:
|
||||
mask (`torch.Tensor` or `None`):
|
||||
A 2D attention mask of shape `(batch_size, key_value_length)`
|
||||
dtype (`torch.dtype`):
|
||||
The torch dtype the created mask shall have.
|
||||
tgt_len (`int`):
|
||||
The target length or query length the created mask shall have.
|
||||
"""
|
||||
batch_size, key_value_length = mask.shape
|
||||
tgt_len = tgt_len if tgt_len is not None else key_value_length
|
||||
|
||||
# torch.jit.trace and torchdynamo with fullgraph=True are unable to capture the controlflow `is_causal=attention_mask is None and q_len > 1`
|
||||
# used as an SDPA argument. We keep compatibility with these tracing tools by always using SDPA's `attn_mask` argument in case we are tracing.
|
||||
# TODO: Fix this as well when using torchdynamo with fullgraph=True.
|
||||
is_tracing = torch.jit.is_tracing()
|
||||
|
||||
if torch.all(mask == 1):
|
||||
if is_tracing:
|
||||
pass
|
||||
elif tgt_len == 1:
|
||||
# For query_length == 1, causal attention and bi-directional attention are the same.
|
||||
return None
|
||||
elif key_value_length == tgt_len:
|
||||
return None
|
||||
else:
|
||||
# Unfortunately, for query_length > 1 and key_value_length != query_length, we can not generally ignore the attention mask, as SDPA causal mask generation
|
||||
# may be wrong. We will set is_causal=False in SDPA and rely on Transformers attention_mask instead, hence not setting it to None here.
|
||||
# Reference: https://github.com/pytorch/pytorch/issues/108108
|
||||
return AttentionMaskConverter._expand_mask(mask=mask, dtype=dtype, tgt_len=tgt_len)
|
||||
else:
|
||||
return AttentionMaskConverter._expand_mask(mask=mask, dtype=dtype, tgt_len=tgt_len)
|
||||
|
||||
|
||||
def _create_4d_causal_attention_mask(
|
||||
input_shape: Union[torch.Size, Tuple, List],
|
||||
dtype: torch.dtype,
|
||||
device: torch.device,
|
||||
past_key_values_length: int = 0,
|
||||
sliding_window: Optional[int] = None,
|
||||
) -> Optional[torch.Tensor]:
|
||||
"""
|
||||
Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)`
|
||||
|
||||
Args:
|
||||
input_shape (`tuple(int)` or `list(int)` or `torch.Size`):
|
||||
The input shape should be a tuple that defines `(batch_size, query_length)`.
|
||||
dtype (`torch.dtype`):
|
||||
The torch dtype the created mask shall have.
|
||||
device (`int`):
|
||||
The torch device the created mask shall have.
|
||||
sliding_window (`int`, *optional*):
|
||||
If the model uses windowed attention, a sliding window should be passed.
|
||||
"""
|
||||
attn_mask_converter = AttentionMaskConverter(is_causal=True, sliding_window=sliding_window)
|
||||
|
||||
key_value_length = past_key_values_length + input_shape[-1]
|
||||
attention_mask = attn_mask_converter.to_causal_4d(
|
||||
input_shape[0], input_shape[-1], key_value_length, dtype=dtype, device=device
|
||||
)
|
||||
|
||||
return attention_mask
|
||||
1415
ixformer_sdk/train/speedformer/models/llama/modeling_llama.py
Normal file
1415
ixformer_sdk/train/speedformer/models/llama/modeling_llama.py
Normal file
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,144 @@
|
||||
# coding=utf-8
|
||||
# Copyright 2024 The Qwen team, Alibaba Group and the HuggingFace Inc. team. All rights reserved.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
""" Qwen2 model configuration"""
|
||||
|
||||
from transformers.configuration_utils import PretrainedConfig
|
||||
from transformers.utils import logging
|
||||
|
||||
|
||||
logger = logging.get_logger(__name__)
|
||||
|
||||
QWEN2_PRETRAINED_CONFIG_ARCHIVE_MAP = {
|
||||
"Qwen/Qwen2-7B-beta": "https://huggingface.co/Qwen/Qwen2-7B-beta/resolve/main/config.json",
|
||||
}
|
||||
|
||||
|
||||
class Qwen2Config(PretrainedConfig):
|
||||
r"""
|
||||
This is the configuration class to store the configuration of a [`Qwen2Model`]. It is used to instantiate a
|
||||
Qwen2 model according to the specified arguments, defining the model architecture. Instantiating a configuration
|
||||
with the defaults will yield a similar configuration to that of
|
||||
Qwen2-7B-beta [Qwen/Qwen2-7B-beta](https://huggingface.co/Qwen/Qwen2-7B-beta).
|
||||
|
||||
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
||||
documentation from [`PretrainedConfig`] for more information.
|
||||
|
||||
|
||||
Args:
|
||||
vocab_size (`int`, *optional*, defaults to 151936):
|
||||
Vocabulary size of the Qwen2 model. Defines the number of different tokens that can be represented by the
|
||||
`inputs_ids` passed when calling [`Qwen2Model`]
|
||||
hidden_size (`int`, *optional*, defaults to 4096):
|
||||
Dimension of the hidden representations.
|
||||
intermediate_size (`int`, *optional*, defaults to 22016):
|
||||
Dimension of the MLP representations.
|
||||
num_hidden_layers (`int`, *optional*, defaults to 32):
|
||||
Number of hidden layers in the Transformer encoder.
|
||||
num_attention_heads (`int`, *optional*, defaults to 32):
|
||||
Number of attention heads for each attention layer in the Transformer encoder.
|
||||
num_key_value_heads (`int`, *optional*, defaults to 32):
|
||||
This is the number of key_value heads that should be used to implement Grouped Query Attention. If
|
||||
`num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
|
||||
`num_key_value_heads=1 the model will use Multi Query Attention (MQA) otherwise GQA is used. When
|
||||
converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
|
||||
by meanpooling all the original heads within that group. For more details checkout [this
|
||||
paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to `32`.
|
||||
hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
|
||||
The non-linear activation function (function or string) in the decoder.
|
||||
max_position_embeddings (`int`, *optional*, defaults to 32768):
|
||||
The maximum sequence length that this model might ever be used with.
|
||||
initializer_range (`float`, *optional*, defaults to 0.02):
|
||||
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
||||
rms_norm_eps (`float`, *optional*, defaults to 1e-06):
|
||||
The epsilon used by the rms normalization layers.
|
||||
use_cache (`bool`, *optional*, defaults to `True`):
|
||||
Whether or not the model should return the last key/values attentions (not used by all models). Only
|
||||
relevant if `config.is_decoder=True`.
|
||||
tie_word_embeddings (`bool`, *optional*, defaults to `False`):
|
||||
Whether the model's input and output word embeddings should be tied.
|
||||
rope_theta (`float`, *optional*, defaults to 10000.0):
|
||||
The base period of the RoPE embeddings.
|
||||
use_sliding_window (`bool`, *optional*, defaults to `False`):
|
||||
Whether to use sliding window attention.
|
||||
sliding_window (`int`, *optional*, defaults to 4096):
|
||||
Sliding window attention (SWA) window size. If not specified, will default to `4096`.
|
||||
max_window_layers (`int`, *optional*, defaults to 28):
|
||||
The number of layers that use SWA (Sliding Window Attention). The bottom layers use SWA while the top use full attention.
|
||||
attention_dropout (`float`, *optional*, defaults to 0.0):
|
||||
The dropout ratio for the attention probabilities.
|
||||
|
||||
```python
|
||||
>>> from transformers import Qwen2Model, Qwen2Config
|
||||
|
||||
>>> # Initializing a Qwen2 style configuration
|
||||
>>> configuration = Qwen2Config()
|
||||
|
||||
>>> # Initializing a model from the Qwen2-7B style configuration
|
||||
>>> model = Qwen2Model(configuration)
|
||||
|
||||
>>> # Accessing the model configuration
|
||||
>>> configuration = model.config
|
||||
```"""
|
||||
|
||||
model_type = "qwen2"
|
||||
keys_to_ignore_at_inference = ["past_key_values"]
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
vocab_size=151936,
|
||||
hidden_size=4096,
|
||||
intermediate_size=22016,
|
||||
num_hidden_layers=32,
|
||||
num_attention_heads=32,
|
||||
num_key_value_heads=32,
|
||||
hidden_act="silu",
|
||||
max_position_embeddings=32768,
|
||||
initializer_range=0.02,
|
||||
rms_norm_eps=1e-6,
|
||||
use_cache=True,
|
||||
tie_word_embeddings=False,
|
||||
rope_theta=10000.0,
|
||||
use_sliding_window=False,
|
||||
sliding_window=4096,
|
||||
max_window_layers=28,
|
||||
attention_dropout=0.0,
|
||||
**kwargs,
|
||||
):
|
||||
self.vocab_size = vocab_size
|
||||
self.max_position_embeddings = max_position_embeddings
|
||||
self.hidden_size = hidden_size
|
||||
self.intermediate_size = intermediate_size
|
||||
self.num_hidden_layers = num_hidden_layers
|
||||
self.num_attention_heads = num_attention_heads
|
||||
self.use_sliding_window = use_sliding_window
|
||||
self.sliding_window = sliding_window
|
||||
self.max_window_layers = max_window_layers
|
||||
|
||||
# for backward compatibility
|
||||
if num_key_value_heads is None:
|
||||
num_key_value_heads = num_attention_heads
|
||||
|
||||
self.num_key_value_heads = num_key_value_heads
|
||||
self.hidden_act = hidden_act
|
||||
self.initializer_range = initializer_range
|
||||
self.rms_norm_eps = rms_norm_eps
|
||||
self.use_cache = use_cache
|
||||
self.rope_theta = rope_theta
|
||||
self.attention_dropout = attention_dropout
|
||||
|
||||
super().__init__(
|
||||
tie_word_embeddings=tie_word_embeddings,
|
||||
**kwargs,
|
||||
)
|
||||
@@ -0,0 +1,500 @@
|
||||
# Copyright 2023 The HuggingFace Team. All rights reserved.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
from dataclasses import dataclass
|
||||
from typing import List, Optional, Tuple, Union
|
||||
|
||||
import torch
|
||||
|
||||
|
||||
@dataclass
|
||||
class AttentionMaskConverter:
|
||||
"""
|
||||
A utility attention mask class that allows one to:
|
||||
- Create a causal 4d mask
|
||||
- Create a causal 4d mask with slided window
|
||||
- Convert a 2d attention mask (batch_size, query_length) to a 4d attention mask (batch_size, 1, query_length,
|
||||
key_value_length) that can be multiplied with attention scores
|
||||
|
||||
Examples:
|
||||
|
||||
```python
|
||||
>>> import torch
|
||||
>>> from transformers.modeling_attn_mask_utils import AttentionMaskConverter
|
||||
|
||||
>>> converter = AttentionMaskConverter(True)
|
||||
>>> converter.to_4d(torch.tensor([[0, 0, 0, 1, 1]]), 5, key_value_length=5, dtype=torch.float32)
|
||||
tensor([[[[-3.4028e+38, -3.4028e+38, -3.4028e+38, -3.4028e+38, -3.4028e+38],
|
||||
[-3.4028e+38, -3.4028e+38, -3.4028e+38, -3.4028e+38, -3.4028e+38],
|
||||
[-3.4028e+38, -3.4028e+38, -3.4028e+38, -3.4028e+38, -3.4028e+38],
|
||||
[-3.4028e+38, -3.4028e+38, -3.4028e+38, 0.0000e+00, -3.4028e+38],
|
||||
[-3.4028e+38, -3.4028e+38, -3.4028e+38, 0.0000e+00, 0.0000e+00]]]])
|
||||
```
|
||||
|
||||
Parameters:
|
||||
is_causal (`bool`):
|
||||
Whether the attention mask should be a uni-directional (causal) or bi-directional mask.
|
||||
|
||||
sliding_window (`int`, *optional*):
|
||||
Optionally, the sliding window masks can be created if `sliding_window` is defined to a positive integer.
|
||||
"""
|
||||
|
||||
is_causal: bool
|
||||
sliding_window: int
|
||||
|
||||
def __init__(self, is_causal: bool, sliding_window: Optional[int] = None):
|
||||
self.is_causal = is_causal
|
||||
self.sliding_window = sliding_window
|
||||
|
||||
if self.sliding_window is not None and self.sliding_window <= 0:
|
||||
raise ValueError(
|
||||
f"Make sure that when passing `sliding_window` that its value is a strictly positive integer, not `{self.sliding_window}`"
|
||||
)
|
||||
|
||||
def to_causal_4d(
|
||||
self,
|
||||
batch_size: int,
|
||||
query_length: int,
|
||||
key_value_length: int,
|
||||
dtype: torch.dtype,
|
||||
device: Union[torch.device, "str"] = "cpu",
|
||||
) -> Optional[torch.Tensor]:
|
||||
"""
|
||||
Creates a causal 4D mask of (bsz, head_dim=1, query_length, key_value_length) shape and adds large negative
|
||||
bias to upper right hand triangular matrix (causal mask).
|
||||
"""
|
||||
if not self.is_causal:
|
||||
raise ValueError(f"Please use `to_causal_4d` only if {self.__class__} has `is_causal` set to True.")
|
||||
|
||||
# If shape is not cached, create a new causal mask and cache it
|
||||
input_shape = (batch_size, query_length)
|
||||
past_key_values_length = key_value_length - query_length
|
||||
|
||||
# create causal mask
|
||||
# [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
|
||||
causal_4d_mask = None
|
||||
if input_shape[-1] > 1 or self.sliding_window is not None:
|
||||
causal_4d_mask = self._make_causal_mask(
|
||||
input_shape,
|
||||
dtype,
|
||||
device=device,
|
||||
past_key_values_length=past_key_values_length,
|
||||
sliding_window=self.sliding_window,
|
||||
)
|
||||
|
||||
return causal_4d_mask
|
||||
|
||||
def to_4d(
|
||||
self,
|
||||
attention_mask_2d: torch.Tensor,
|
||||
query_length: int,
|
||||
dtype: torch.dtype,
|
||||
key_value_length: Optional[int] = None,
|
||||
) -> torch.Tensor:
|
||||
"""
|
||||
Converts 2D attention mask to 4D attention mask by expanding mask to (bsz, head_dim=1, query_length,
|
||||
key_value_length) shape and by adding a large negative bias to not-attended positions. If attention_mask is
|
||||
causal, a causal mask will be added.
|
||||
"""
|
||||
input_shape = (attention_mask_2d.shape[0], query_length)
|
||||
|
||||
# create causal mask
|
||||
# [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
|
||||
causal_4d_mask = None
|
||||
if (input_shape[-1] > 1 or self.sliding_window is not None) and self.is_causal:
|
||||
if key_value_length is None:
|
||||
raise ValueError(
|
||||
"This attention mask converter is causal. Make sure to pass `key_value_length` to correctly create a causal mask."
|
||||
)
|
||||
|
||||
past_key_values_length = key_value_length - query_length
|
||||
causal_4d_mask = self._make_causal_mask(
|
||||
input_shape,
|
||||
dtype,
|
||||
device=attention_mask_2d.device,
|
||||
past_key_values_length=past_key_values_length,
|
||||
sliding_window=self.sliding_window,
|
||||
)
|
||||
elif self.sliding_window is not None:
|
||||
raise NotImplementedError("Sliding window is currently only implemented for causal masking")
|
||||
|
||||
# [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
|
||||
expanded_attn_mask = self._expand_mask(attention_mask_2d, dtype, tgt_len=input_shape[-1]).to(
|
||||
attention_mask_2d.device
|
||||
)
|
||||
|
||||
if causal_4d_mask is not None:
|
||||
expanded_attn_mask = causal_4d_mask.masked_fill(expanded_attn_mask.bool(), torch.finfo(dtype).min)
|
||||
|
||||
# expanded_attn_mask + causal_4d_mask can cause some overflow
|
||||
expanded_4d_mask = expanded_attn_mask
|
||||
|
||||
return expanded_4d_mask
|
||||
|
||||
@staticmethod
|
||||
def _make_causal_mask(
|
||||
input_ids_shape: torch.Size,
|
||||
dtype: torch.dtype,
|
||||
device: torch.device,
|
||||
past_key_values_length: int = 0,
|
||||
sliding_window: Optional[int] = None,
|
||||
):
|
||||
"""
|
||||
Make causal mask used for bi-directional self-attention.
|
||||
"""
|
||||
bsz, tgt_len = input_ids_shape
|
||||
mask = torch.full((tgt_len, tgt_len), torch.finfo(dtype).min, device=device)
|
||||
mask_cond = torch.arange(mask.size(-1), device=device)
|
||||
mask.masked_fill_(mask_cond < (mask_cond + 1).view(mask.size(-1), 1), 0)
|
||||
|
||||
mask = mask.to(dtype)
|
||||
|
||||
if past_key_values_length > 0:
|
||||
mask = torch.cat([torch.zeros(tgt_len, past_key_values_length, dtype=dtype, device=device), mask], dim=-1)
|
||||
|
||||
# add lower triangular sliding window mask if necessary
|
||||
if sliding_window is not None:
|
||||
diagonal = past_key_values_length - sliding_window + 1
|
||||
|
||||
context_mask = 1 - torch.triu(torch.ones_like(mask, dtype=torch.int), diagonal=diagonal)
|
||||
mask.masked_fill_(context_mask.bool(), torch.finfo(dtype).min)
|
||||
|
||||
return mask[None, None, :, :].expand(bsz, 1, tgt_len, tgt_len + past_key_values_length)
|
||||
|
||||
@staticmethod
|
||||
def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None):
|
||||
"""
|
||||
Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.
|
||||
"""
|
||||
bsz, src_len = mask.size()
|
||||
tgt_len = tgt_len if tgt_len is not None else src_len
|
||||
|
||||
expanded_mask = mask[:, None, None, :].expand(bsz, 1, tgt_len, src_len).to(dtype)
|
||||
|
||||
inverted_mask = 1.0 - expanded_mask
|
||||
|
||||
return inverted_mask.masked_fill(inverted_mask.to(torch.bool), torch.finfo(dtype).min)
|
||||
|
||||
@staticmethod
|
||||
def _unmask_unattended(
|
||||
expanded_mask: torch.Tensor, attention_mask: torch.Tensor, unmasked_value: Union[bool, float]
|
||||
):
|
||||
# fmt: off
|
||||
"""
|
||||
Attend to all tokens in masked rows from the expanded attention mask, for example the relevant first rows when
|
||||
using left padding. This is required by F.scaled_dot_product_attention memory-efficient attention path.
|
||||
Details: https://github.com/pytorch/pytorch/issues/110213
|
||||
|
||||
`expanded_mask` is [bsz, num_masks, tgt_seq_len, src_seq_len] or [bsz, tgt_seq_len, src_seq_len].
|
||||
`attention_mask` is [bsz, src_seq_len].
|
||||
|
||||
The dimension num_masks of `expanded_mask` is most often 1, but it can also be the number of heads in the case of alibi attention bias.
|
||||
|
||||
For example, if `attention_mask` is
|
||||
```
|
||||
[[0, 0, 1],
|
||||
[1, 1, 1],
|
||||
[0, 1, 1]]
|
||||
```
|
||||
and `expanded_mask` is (e.g. here left-padding case)
|
||||
```
|
||||
[[[[0, 0, 0],
|
||||
[0, 0, 0],
|
||||
[0, 0, 1]]],
|
||||
[[[1, 0, 0],
|
||||
[1, 1, 0],
|
||||
[1, 1, 1]]],
|
||||
[[[0, 0, 0],
|
||||
[0, 1, 0],
|
||||
[0, 1, 1]]]]
|
||||
```
|
||||
then the modified `expanded_mask` will be
|
||||
```
|
||||
[[[[1, 1, 1], <-- modified
|
||||
[1, 1, 1], <-- modified
|
||||
[0, 0, 1]]],
|
||||
[[[1, 0, 0],
|
||||
[1, 1, 0],
|
||||
[1, 1, 1]]],
|
||||
[[[1, 1, 1], <-- modified
|
||||
[0, 1, 0],
|
||||
[0, 1, 1]]]]
|
||||
```
|
||||
"""
|
||||
# fmt: on
|
||||
|
||||
# Get the index of the first non-zero value for every sample in the batch.
|
||||
# In the above example, indices = [[2], [0], [1]]]
|
||||
tmp = torch.arange(attention_mask.shape[1], 0, -1)
|
||||
indices = torch.argmax(attention_mask.cpu() * tmp, 1, keepdim=True)
|
||||
|
||||
# Find the batch indexes that have unattended tokens on the leftmost side (e.g. [0, 0, 1, 1, 1]), for which the first rows of the
|
||||
# expanded mask will be completely unattended.
|
||||
left_masked_rows = torch.where(indices > 0)[0]
|
||||
|
||||
if left_masked_rows.shape[0] == 0:
|
||||
return expanded_mask
|
||||
indices = indices[left_masked_rows]
|
||||
|
||||
max_len = torch.max(indices)
|
||||
range_tensor = torch.arange(max_len).unsqueeze(0)
|
||||
range_tensor = range_tensor.repeat(indices.size(0), 1)
|
||||
|
||||
# Avoid unmasking tokens at relevant target positions (on the row axis), by rather unmasking possibly several times the first row that should always be unmasked as we filtered out the batch above.
|
||||
range_tensor[range_tensor >= indices] = 0
|
||||
|
||||
# TODO: we may drop support for 3D attention mask as the refactor from Patrick maybe dropped this case
|
||||
if expanded_mask.dim() == 4:
|
||||
num_masks = expanded_mask.shape[1]
|
||||
if num_masks == 1:
|
||||
# Broadcast [left_masked_rows, 1], [left_masked_rows, max_len]
|
||||
mask_slice = (left_masked_rows[:, None], 0, range_tensor)
|
||||
else:
|
||||
# Broadcast [left_masked_rows, 1, 1], [1, num_masks, 1], [left_masked_rows, 1, max_len]
|
||||
mask_slice = (
|
||||
left_masked_rows[:, None, None],
|
||||
torch.arange(num_masks)[None, :, None],
|
||||
range_tensor[:, None, :],
|
||||
)
|
||||
else:
|
||||
# Broadcast [left_masked_rows, 1], [left_masked_rows, max_len]
|
||||
mask_slice = (left_masked_rows[:, None], range_tensor)
|
||||
|
||||
expanded_mask[mask_slice] = unmasked_value
|
||||
|
||||
return expanded_mask
|
||||
|
||||
|
||||
def _prepare_4d_causal_attention_mask(
|
||||
attention_mask: Optional[torch.Tensor],
|
||||
input_shape: Union[torch.Size, Tuple, List],
|
||||
inputs_embeds: torch.Tensor,
|
||||
past_key_values_length: int,
|
||||
sliding_window: Optional[int] = None,
|
||||
):
|
||||
"""
|
||||
Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
|
||||
`(batch_size, key_value_length)`
|
||||
|
||||
Args:
|
||||
attention_mask (`torch.Tensor` or `None`):
|
||||
A 2D attention mask of shape `(batch_size, key_value_length)`
|
||||
input_shape (`tuple(int)` or `list(int)` or `torch.Size`):
|
||||
The input shape should be a tuple that defines `(batch_size, query_length)`.
|
||||
inputs_embeds (`torch.Tensor`):
|
||||
The embedded inputs as a torch Tensor.
|
||||
past_key_values_length (`int`):
|
||||
The length of the key value cache.
|
||||
sliding_window (`int`, *optional*):
|
||||
If the model uses windowed attention, a sliding window should be passed.
|
||||
"""
|
||||
attn_mask_converter = AttentionMaskConverter(is_causal=True, sliding_window=sliding_window)
|
||||
|
||||
key_value_length = input_shape[-1] + past_key_values_length
|
||||
|
||||
# 4d mask is passed through the layers
|
||||
if attention_mask is not None and len(attention_mask.shape) == 2:
|
||||
attention_mask = attn_mask_converter.to_4d(
|
||||
attention_mask, input_shape[-1], key_value_length=key_value_length, dtype=inputs_embeds.dtype
|
||||
)
|
||||
elif attention_mask is not None and len(attention_mask.shape) == 4:
|
||||
expected_shape = (input_shape[0], 1, input_shape[1], key_value_length)
|
||||
if tuple(attention_mask.shape) != expected_shape:
|
||||
raise ValueError(
|
||||
f"Incorrect 4D attention_mask shape: {tuple(attention_mask.shape)}; expected: {expected_shape}."
|
||||
)
|
||||
else:
|
||||
# if the 4D mask has correct shape - invert it and fill with negative infinity
|
||||
inverted_mask = 1.0 - attention_mask
|
||||
attention_mask = inverted_mask.masked_fill(
|
||||
inverted_mask.to(torch.bool), torch.finfo(inputs_embeds.dtype).min
|
||||
)
|
||||
else:
|
||||
attention_mask = attn_mask_converter.to_causal_4d(
|
||||
input_shape[0], input_shape[-1], key_value_length, dtype=inputs_embeds.dtype, device=inputs_embeds.device
|
||||
)
|
||||
|
||||
return attention_mask
|
||||
|
||||
|
||||
# Adapted from _prepare_4d_causal_attention_mask
|
||||
def _prepare_4d_causal_attention_mask_for_sdpa(
|
||||
attention_mask: Optional[torch.Tensor],
|
||||
input_shape: Union[torch.Size, Tuple, List],
|
||||
inputs_embeds: torch.Tensor,
|
||||
past_key_values_length: int,
|
||||
sliding_window: Optional[int] = None,
|
||||
):
|
||||
"""
|
||||
Prepares the correct `attn_mask` argument to be used by `torch.nn.functional.scaled_dot_product_attention`.
|
||||
|
||||
In case no token is masked in the `attention_mask` argument, we simply set it to `None` for the cases `query_length == 1` and
|
||||
`key_value_length == query_length`, and rely instead on SDPA `is_causal` argument to use causal/non-causal masks,
|
||||
allowing to dispatch to the flash attention kernel (that can otherwise not be used if a custom `attn_mask` is passed).
|
||||
"""
|
||||
attn_mask_converter = AttentionMaskConverter(is_causal=True, sliding_window=sliding_window)
|
||||
|
||||
key_value_length = input_shape[-1] + past_key_values_length
|
||||
batch_size, query_length = input_shape
|
||||
|
||||
# torch.jit.trace, symbolic_trace and torchdynamo with fullgraph=True are unable to capture the controlflow `is_causal=attention_mask is None and q_len > 1`
|
||||
# used as an SDPA argument. We keep compatibility with these tracing tools by always using SDPA's `attn_mask` argument in case we are tracing.
|
||||
# TODO: Fix this as well when using torchdynamo with fullgraph=True.
|
||||
is_tracing = torch.jit.is_tracing() or isinstance(inputs_embeds, torch.fx.Proxy)
|
||||
|
||||
if attention_mask is not None:
|
||||
# 4d mask is passed through
|
||||
if len(attention_mask.shape) == 4:
|
||||
expected_shape = (input_shape[0], 1, input_shape[1], key_value_length)
|
||||
if tuple(attention_mask.shape) != expected_shape:
|
||||
raise ValueError(
|
||||
f"Incorrect 4D attention_mask shape: {tuple(attention_mask.shape)}; expected: {expected_shape}."
|
||||
)
|
||||
else:
|
||||
# if the 4D mask has correct shape - invert it and fill with negative infinity
|
||||
inverted_mask = 1.0 - attention_mask.to(inputs_embeds.dtype)
|
||||
attention_mask = inverted_mask.masked_fill(
|
||||
inverted_mask.to(torch.bool), torch.finfo(inputs_embeds.dtype).min
|
||||
)
|
||||
return attention_mask
|
||||
|
||||
elif not is_tracing and torch.all(attention_mask == 1):
|
||||
if query_length == 1:
|
||||
# For query_length == 1, causal attention and bi-directional attention are the same.
|
||||
attention_mask = None
|
||||
elif key_value_length == query_length:
|
||||
attention_mask = None
|
||||
else:
|
||||
# Unfortunately, for query_length > 1 and key_value_length != query_length, we cannot generally ignore the attention mask, as SDPA causal mask generation
|
||||
# may be wrong. We will set `is_causal=False` in SDPA and rely on Transformers attention_mask instead, hence not setting it to None here.
|
||||
# Reference: https://github.com/pytorch/pytorch/issues/108108
|
||||
pass
|
||||
elif query_length > 1 and key_value_length != query_length:
|
||||
# See the comment above (https://github.com/pytorch/pytorch/issues/108108).
|
||||
# Ugly: we set it to True here to dispatch in the following controlflow to `to_causal_4d`.
|
||||
attention_mask = True
|
||||
elif is_tracing:
|
||||
raise ValueError(
|
||||
'Attention using SDPA can not be traced with torch.jit.trace when no attention_mask is provided. To solve this issue, please either load your model with the argument `attn_implementation="eager"` or pass an attention_mask input when tracing the model.'
|
||||
)
|
||||
|
||||
if attention_mask is None:
|
||||
expanded_4d_mask = None
|
||||
elif attention_mask is True:
|
||||
expanded_4d_mask = attn_mask_converter.to_causal_4d(
|
||||
input_shape[0], input_shape[-1], key_value_length, dtype=inputs_embeds.dtype, device=inputs_embeds.device
|
||||
)
|
||||
else:
|
||||
expanded_4d_mask = attn_mask_converter.to_4d(
|
||||
attention_mask,
|
||||
input_shape[-1],
|
||||
dtype=inputs_embeds.dtype,
|
||||
key_value_length=key_value_length,
|
||||
)
|
||||
|
||||
# From PyTorch 2.1 onwards, F.scaled_dot_product_attention with the memory-efficient attention backend
|
||||
# produces nans if sequences are completely unattended in the attention mask. Details: https://github.com/pytorch/pytorch/issues/110213
|
||||
#
|
||||
# This fix is not applied in case we are tracing with torch.jit.trace or symbolic_trace, as _unmask_unattended has a data-dependent
|
||||
# controlflow that can not be captured properly.
|
||||
# TODO: _unmask_unattended does not work either with torch.compile when using fullgraph=True. We should find a way to detect this case.
|
||||
if query_length > 1 and not is_tracing:
|
||||
expanded_4d_mask = AttentionMaskConverter._unmask_unattended(
|
||||
expanded_4d_mask, attention_mask, unmasked_value=0.0
|
||||
)
|
||||
|
||||
return expanded_4d_mask
|
||||
|
||||
|
||||
def _prepare_4d_attention_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None):
|
||||
"""
|
||||
Creates a non-causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
|
||||
`(batch_size, key_value_length)`
|
||||
|
||||
Args:
|
||||
mask (`torch.Tensor` or `None`):
|
||||
A 2D attention mask of shape `(batch_size, key_value_length)`
|
||||
dtype (`torch.dtype`):
|
||||
The torch dtype the created mask shall have.
|
||||
tgt_len (`int`):
|
||||
The target length or query length the created mask shall have.
|
||||
"""
|
||||
return AttentionMaskConverter._expand_mask(mask=mask, dtype=dtype, tgt_len=tgt_len)
|
||||
|
||||
|
||||
def _prepare_4d_attention_mask_for_sdpa(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None):
|
||||
"""
|
||||
Creates a non-causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
|
||||
`(batch_size, key_value_length)`
|
||||
|
||||
Args:
|
||||
mask (`torch.Tensor` or `None`):
|
||||
A 2D attention mask of shape `(batch_size, key_value_length)`
|
||||
dtype (`torch.dtype`):
|
||||
The torch dtype the created mask shall have.
|
||||
tgt_len (`int`):
|
||||
The target length or query length the created mask shall have.
|
||||
"""
|
||||
batch_size, key_value_length = mask.shape
|
||||
tgt_len = tgt_len if tgt_len is not None else key_value_length
|
||||
|
||||
# torch.jit.trace and torchdynamo with fullgraph=True are unable to capture the controlflow `is_causal=attention_mask is None and q_len > 1`
|
||||
# used as an SDPA argument. We keep compatibility with these tracing tools by always using SDPA's `attn_mask` argument in case we are tracing.
|
||||
# TODO: Fix this as well when using torchdynamo with fullgraph=True.
|
||||
is_tracing = torch.jit.is_tracing()
|
||||
|
||||
if torch.all(mask == 1):
|
||||
if is_tracing:
|
||||
pass
|
||||
elif tgt_len == 1:
|
||||
# For query_length == 1, causal attention and bi-directional attention are the same.
|
||||
return None
|
||||
elif key_value_length == tgt_len:
|
||||
return None
|
||||
else:
|
||||
# Unfortunately, for query_length > 1 and key_value_length != query_length, we can not generally ignore the attention mask, as SDPA causal mask generation
|
||||
# may be wrong. We will set is_causal=False in SDPA and rely on Transformers attention_mask instead, hence not setting it to None here.
|
||||
# Reference: https://github.com/pytorch/pytorch/issues/108108
|
||||
return AttentionMaskConverter._expand_mask(mask=mask, dtype=dtype, tgt_len=tgt_len)
|
||||
else:
|
||||
return AttentionMaskConverter._expand_mask(mask=mask, dtype=dtype, tgt_len=tgt_len)
|
||||
|
||||
|
||||
def _create_4d_causal_attention_mask(
|
||||
input_shape: Union[torch.Size, Tuple, List],
|
||||
dtype: torch.dtype,
|
||||
device: torch.device,
|
||||
past_key_values_length: int = 0,
|
||||
sliding_window: Optional[int] = None,
|
||||
) -> Optional[torch.Tensor]:
|
||||
"""
|
||||
Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)`
|
||||
|
||||
Args:
|
||||
input_shape (`tuple(int)` or `list(int)` or `torch.Size`):
|
||||
The input shape should be a tuple that defines `(batch_size, query_length)`.
|
||||
dtype (`torch.dtype`):
|
||||
The torch dtype the created mask shall have.
|
||||
device (`int`):
|
||||
The torch device the created mask shall have.
|
||||
sliding_window (`int`, *optional*):
|
||||
If the model uses windowed attention, a sliding window should be passed.
|
||||
"""
|
||||
attn_mask_converter = AttentionMaskConverter(is_causal=True, sliding_window=sliding_window)
|
||||
|
||||
key_value_length = past_key_values_length + input_shape[-1]
|
||||
attention_mask = attn_mask_converter.to_causal_4d(
|
||||
input_shape[0], input_shape[-1], key_value_length, dtype=dtype, device=device
|
||||
)
|
||||
|
||||
return attention_mask
|
||||
1401
ixformer_sdk/train/speedformer/models/qwen2/modeling_qwen2.py
Normal file
1401
ixformer_sdk/train/speedformer/models/qwen2/modeling_qwen2.py
Normal file
File diff suppressed because it is too large
Load Diff
0
ixformer_sdk/train/speedformer/policy/__init__.py
Normal file
0
ixformer_sdk/train/speedformer/policy/__init__.py
Normal file
59
ixformer_sdk/train/speedformer/policy/baichuan.py
Normal file
59
ixformer_sdk/train/speedformer/policy/baichuan.py
Normal file
@@ -0,0 +1,59 @@
|
||||
import warnings
|
||||
from abc import ABC, abstractmethod
|
||||
from functools import partial
|
||||
from typing import Callable, Dict, List, Union
|
||||
|
||||
import torch.nn as nn
|
||||
from torch import Tensor
|
||||
from torch.nn import Module
|
||||
|
||||
from ixformer.train.speedformer.policy.utils import SubModuleReplacementDescription
|
||||
from ixformer.train.speedformer.policy.replacer import Replacer
|
||||
|
||||
from ixformer.train.speedformer.models.baichuan.modeling_baichuan import BaichuanModel, DecoderLayer
|
||||
from ixformer.train.speedformer.layers.normalization import APEXFusedRMSNorm, IXFFusedRMSNorm
|
||||
from ixformer.train.speedformer.layers.baichuan.attention import BaichuanAttention
|
||||
from ixformer.train.speedformer.layers.baichuan.mlp import IXFBaichuanMLP
|
||||
|
||||
|
||||
class BaichuanReplacer(Replacer):
|
||||
def __init__(self):
|
||||
self.policy = {}
|
||||
|
||||
def module_policy(self) -> Dict[Union[str, nn.Module], List[SubModuleReplacementDescription]]:
|
||||
self.append_or_create_submodule_replacement(
|
||||
description=[
|
||||
SubModuleReplacementDescription(
|
||||
suffix="input_layernorm",
|
||||
target_module=APEXFusedRMSNorm,
|
||||
kwargs={}
|
||||
),
|
||||
SubModuleReplacementDescription(
|
||||
suffix="post_attention_layernorm",
|
||||
target_module=APEXFusedRMSNorm,
|
||||
kwargs={},
|
||||
),
|
||||
SubModuleReplacementDescription(
|
||||
suffix="self_attn",
|
||||
target_module=BaichuanAttention,
|
||||
kwargs={}
|
||||
),
|
||||
SubModuleReplacementDescription(
|
||||
suffix="mlp",
|
||||
target_module=IXFBaichuanMLP,
|
||||
kwargs={}
|
||||
),
|
||||
],
|
||||
target_key="DecoderLayer"
|
||||
)
|
||||
|
||||
self.append_or_create_submodule_replacement(
|
||||
description=[
|
||||
SubModuleReplacementDescription(
|
||||
suffix="norm",
|
||||
target_module=APEXFusedRMSNorm,
|
||||
kwargs={}
|
||||
),
|
||||
],
|
||||
target_key=BaichuanModel
|
||||
)
|
||||
53
ixformer_sdk/train/speedformer/policy/bloom.py
Normal file
53
ixformer_sdk/train/speedformer/policy/bloom.py
Normal file
@@ -0,0 +1,53 @@
|
||||
import warnings
|
||||
from abc import ABC, abstractmethod
|
||||
from functools import partial
|
||||
from typing import Callable, Dict, List, Union
|
||||
|
||||
import torch.nn as nn
|
||||
from torch import Tensor
|
||||
from torch.nn import Module
|
||||
|
||||
from ixformer.train.speedformer.policy.utils import SubModuleReplacementDescription
|
||||
from ixformer.train.speedformer.policy.replacer import Replacer
|
||||
|
||||
from ixformer.train.speedformer.models.bloom.modeling_bloom import BloomModel, BloomBlock
|
||||
from ixformer.train.speedformer.layers.normalization import APEXFusedRMSNorm, IXFFusedRMSNorm
|
||||
from ixformer.train.speedformer.layers.bloom.attention import BloomFlashAttention
|
||||
|
||||
|
||||
class BloomReplacer(Replacer):
|
||||
def __init__(self):
|
||||
self.policy = {}
|
||||
|
||||
def module_policy(self) -> Dict[Union[str, nn.Module], List[SubModuleReplacementDescription]]:
|
||||
self.append_or_create_submodule_replacement(
|
||||
description=[
|
||||
SubModuleReplacementDescription(
|
||||
suffix="input_layernorm",
|
||||
target_module=APEXFusedRMSNorm,
|
||||
kwargs={}
|
||||
),
|
||||
SubModuleReplacementDescription(
|
||||
suffix="post_attention_layernorm",
|
||||
target_module=APEXFusedRMSNorm,
|
||||
kwargs={},
|
||||
),
|
||||
SubModuleReplacementDescription(
|
||||
suffix="self_attention",
|
||||
target_module=BloomFlashAttention,
|
||||
kwargs={}
|
||||
),
|
||||
],
|
||||
target_key="BloomBlock"
|
||||
)
|
||||
|
||||
self.append_or_create_submodule_replacement(
|
||||
description=[
|
||||
SubModuleReplacementDescription(
|
||||
suffix="ln_f",
|
||||
target_module=APEXFusedRMSNorm,
|
||||
kwargs={}
|
||||
),
|
||||
],
|
||||
target_key=BloomModel
|
||||
)
|
||||
57
ixformer_sdk/train/speedformer/policy/chatglm.py
Normal file
57
ixformer_sdk/train/speedformer/policy/chatglm.py
Normal file
@@ -0,0 +1,57 @@
|
||||
from typing import Callable, Dict, List, Union
|
||||
from torch.nn import Module
|
||||
|
||||
from ixformer.train.speedformer.policy.utils import SubModuleReplacementDescription
|
||||
from ixformer.train.speedformer.policy.replacer import Replacer
|
||||
|
||||
from ixformer.train.speedformer.layers.normalization import APEXFusedRMSNorm, IXFFusedRMSNorm
|
||||
from ixformer.train.speedformer.layers.chatglm.attention import ChatglmFlashAttention
|
||||
from ixformer.train.speedformer.layers.chatglm.methods import ChatGLMModel_forward
|
||||
|
||||
|
||||
class ChatglmReplacer(Replacer):
|
||||
def __init__(self):
|
||||
self.policy = {}
|
||||
|
||||
def module_policy(self) -> Dict[str | Module, List[SubModuleReplacementDescription]]:
|
||||
self.append_or_create_submodule_replacement(
|
||||
description=[
|
||||
SubModuleReplacementDescription(
|
||||
suffix="final_layernorm",
|
||||
target_module=APEXFusedRMSNorm,
|
||||
kwargs={}
|
||||
),
|
||||
],
|
||||
target_key="GLMTransformer"
|
||||
)
|
||||
self.append_or_create_submodule_replacement(
|
||||
description=[
|
||||
SubModuleReplacementDescription(
|
||||
suffix="input_layernorm",
|
||||
target_module=APEXFusedRMSNorm,
|
||||
kwargs={}
|
||||
),
|
||||
SubModuleReplacementDescription(
|
||||
suffix="post_attention_layernorm",
|
||||
target_module=APEXFusedRMSNorm,
|
||||
kwargs={}
|
||||
),
|
||||
],
|
||||
target_key="GLMBlock"
|
||||
)
|
||||
self.append_or_create_submodule_replacement(
|
||||
description=[
|
||||
SubModuleReplacementDescription(
|
||||
suffix="self_attention",
|
||||
target_module=ChatglmFlashAttention,
|
||||
kwargs={}
|
||||
),
|
||||
],
|
||||
target_key="GLMBlock"
|
||||
)
|
||||
self.append_or_create_method_replacement(
|
||||
description=[
|
||||
{"forward": ChatGLMModel_forward()}
|
||||
],
|
||||
target_key="ChatGLMModel"
|
||||
)
|
||||
27
ixformer_sdk/train/speedformer/policy/gpt2.py
Normal file
27
ixformer_sdk/train/speedformer/policy/gpt2.py
Normal file
@@ -0,0 +1,27 @@
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
from torch.nn import LayerNorm
|
||||
from types import ModuleType, MethodType
|
||||
from abc import ABC
|
||||
|
||||
from ixformer.train.speedformer.models.gpt2.modeling_gpt2 import GPT2FlashAttention2
|
||||
|
||||
from ixformer.train.speedformer.layers.normalization import replace_layernorm_forward
|
||||
from ixformer.train.speedformer.layers.gpt2.attention import replace_flash_attn_forward
|
||||
|
||||
|
||||
class GPT2Replacer(ABC):
|
||||
def __init__(self) -> None:
|
||||
super().__init__()
|
||||
|
||||
@staticmethod
|
||||
def accelerate(model):
|
||||
# layer/kernel replace
|
||||
for name, module in model.named_modules():
|
||||
if isinstance(module, LayerNorm):
|
||||
module.forward = MethodType(replace_layernorm_forward, module)
|
||||
if isinstance(module, GPT2FlashAttention2):
|
||||
module._flash_attention_forward = MethodType(
|
||||
replace_flash_attn_forward, module)
|
||||
|
||||
return model
|
||||
104
ixformer_sdk/train/speedformer/policy/llama.py
Normal file
104
ixformer_sdk/train/speedformer/policy/llama.py
Normal file
@@ -0,0 +1,104 @@
|
||||
import warnings
|
||||
import types
|
||||
from abc import ABC, abstractmethod
|
||||
from functools import partial
|
||||
from typing import Callable, Dict, List, Union
|
||||
|
||||
import torch.nn as nn
|
||||
from torch import Tensor
|
||||
from torch.nn import Module
|
||||
|
||||
from ixformer.train.speedformer.policy.utils import SubModuleReplacementDescription
|
||||
from ixformer.train.speedformer.policy.replacer import Replacer
|
||||
|
||||
from ixformer.train.speedformer.layers.normalization import APEXFusedRMSNorm, IXFFusedRMSNorm
|
||||
from ixformer.train.speedformer.layers.llama.attention import LlamaAttention as IXF_LlamaAttention
|
||||
from ixformer.train.speedformer.layers.llama.mlp import IXFLlamaMLP
|
||||
from ixformer.train.speedformer.layers.llama.llama_method import LlamaModel_forward, LlamaForCausalLM_forward
|
||||
from ixformer.train.speedformer.layers.fast_lora.fast_lora import apply_lora_mlp_swiglu
|
||||
|
||||
from peft import PeftType
|
||||
|
||||
|
||||
class LlamaReplacer(Replacer):
|
||||
def __init__(self):
|
||||
self.policy = {}
|
||||
|
||||
def module_policy(self) -> Dict[Union[str, nn.Module], List[SubModuleReplacementDescription]]:
|
||||
self.append_or_create_submodule_replacement(
|
||||
description=[
|
||||
SubModuleReplacementDescription(
|
||||
suffix="input_layernorm",
|
||||
target_module=APEXFusedRMSNorm,
|
||||
kwargs={}
|
||||
),
|
||||
SubModuleReplacementDescription(
|
||||
suffix="post_attention_layernorm",
|
||||
target_module=APEXFusedRMSNorm,
|
||||
kwargs={},
|
||||
),
|
||||
SubModuleReplacementDescription(
|
||||
suffix="self_attn",
|
||||
target_module=IXF_LlamaAttention,
|
||||
kwargs={}
|
||||
),
|
||||
# SubModuleReplacementDescription(
|
||||
# suffix="mlp",
|
||||
# target_module=IXFLlamaMLP,
|
||||
# kwargs={}
|
||||
# ),
|
||||
],
|
||||
target_key="LlamaDecoderLayer"
|
||||
)
|
||||
|
||||
self.append_or_create_submodule_replacement(
|
||||
description=[
|
||||
SubModuleReplacementDescription(
|
||||
suffix="norm",
|
||||
target_module=APEXFusedRMSNorm,
|
||||
kwargs={}
|
||||
),
|
||||
],
|
||||
target_key="LlamaModel"
|
||||
)
|
||||
|
||||
self.append_or_create_method_replacement(
|
||||
description=[
|
||||
{"forward": LlamaModel_forward()}
|
||||
],
|
||||
target_key="LlamaModel"
|
||||
)
|
||||
self.append_or_create_method_replacement(
|
||||
description=[
|
||||
{"forward": LlamaForCausalLM_forward()}
|
||||
],
|
||||
target_key="LlamaForCausalLM"
|
||||
)
|
||||
|
||||
def post_process(self, model: nn.Module):
|
||||
if model.peft_type != PeftType.LORA:
|
||||
return
|
||||
peft_config = model.peft_config
|
||||
active_adapter = model.active_adapters[0] if \
|
||||
hasattr(model, "active_adapters") else model.active_adapter
|
||||
target_modules = peft_config[active_adapter].target_modules
|
||||
|
||||
# for now, fast_lora only support lora_dropout=0 and bias=None
|
||||
lora_dropout = model.peft_config[active_adapter].lora_dropout
|
||||
bias = model.peft_config[active_adapter].bias
|
||||
|
||||
# 首先判断是否可以使用fast_lora
|
||||
check = lora_dropout == 0 and bias == "none"
|
||||
|
||||
# 其次确定mlp的3个线性层是否在target_modules
|
||||
mlp_use_fastlora = "gate_proj" in target_modules and "up_proj" in target_modules and "up_proj" in target_modules
|
||||
|
||||
n_mlp = 0
|
||||
if check:
|
||||
if mlp_use_fastlora:
|
||||
for layer in model.model.model.layers:
|
||||
layer.mlp.forward = types.MethodType(
|
||||
apply_lora_mlp_swiglu, layer.mlp)
|
||||
n_mlp += 1
|
||||
|
||||
print(f"{len(model.model.model.layers)} layers replace mlp with fast_lora mlp")
|
||||
57
ixformer_sdk/train/speedformer/policy/qwen2.py
Normal file
57
ixformer_sdk/train/speedformer/policy/qwen2.py
Normal file
@@ -0,0 +1,57 @@
|
||||
import warnings
|
||||
from abc import ABC, abstractmethod
|
||||
from functools import partial
|
||||
from typing import Callable, Dict, List, Union
|
||||
|
||||
import torch.nn as nn
|
||||
from torch import Tensor
|
||||
from torch.nn import Module
|
||||
|
||||
from ixformer.train.speedformer.policy.utils import SubModuleReplacementDescription
|
||||
from ixformer.train.speedformer.policy.replacer import Replacer
|
||||
import os
|
||||
import sys
|
||||
from ixformer.train.speedformer.layers.normalization import APEXFusedRMSNorm, IXFFusedRMSNorm
|
||||
from ixformer.train.speedformer.layers.qwen2.attention import QwenAttention as IXF_QwenAttention
|
||||
|
||||
|
||||
class Qwen2Replacer(Replacer):
|
||||
def __init__(self):
|
||||
self.policy = {}
|
||||
|
||||
def module_policy(self) -> Dict[Union[str, nn.Module], List[SubModuleReplacementDescription]]:
|
||||
self.append_or_create_submodule_replacement(
|
||||
description=[
|
||||
SubModuleReplacementDescription(
|
||||
suffix="input_layernorm",
|
||||
target_module=APEXFusedRMSNorm,
|
||||
kwargs={}
|
||||
),
|
||||
SubModuleReplacementDescription(
|
||||
suffix="post_attention_layernorm",
|
||||
target_module=APEXFusedRMSNorm,
|
||||
kwargs={},
|
||||
),
|
||||
SubModuleReplacementDescription(
|
||||
suffix="self_attn",
|
||||
target_module=IXF_QwenAttention,
|
||||
kwargs={}
|
||||
),
|
||||
],
|
||||
target_key="Qwen2DecoderLayer"
|
||||
)
|
||||
|
||||
self.append_or_create_submodule_replacement(
|
||||
description=[
|
||||
SubModuleReplacementDescription(
|
||||
suffix="norm",
|
||||
target_module=APEXFusedRMSNorm,
|
||||
kwargs={}
|
||||
),
|
||||
],
|
||||
target_key="Qwen2Model"
|
||||
)
|
||||
|
||||
|
||||
|
||||
|
||||
224
ixformer_sdk/train/speedformer/policy/replacer.py
Normal file
224
ixformer_sdk/train/speedformer/policy/replacer.py
Normal file
@@ -0,0 +1,224 @@
|
||||
import warnings
|
||||
from types import MethodType
|
||||
from abc import ABC, abstractmethod
|
||||
from functools import partial
|
||||
from typing import Any, Callable, Dict, List, Optional, Set, Union
|
||||
import tabulate
|
||||
|
||||
import torch.nn as nn
|
||||
|
||||
from ixformer.train.speedformer.policy.utils import SubModuleReplacementDescription, ModulePolicyDescription, getattr_, setattr_, print_rank_0
|
||||
|
||||
|
||||
class Replacer(ABC):
|
||||
def __init__(self):
|
||||
self.policy = {}
|
||||
|
||||
def module_policy(self) -> Dict[Union[str, nn.Module], List[SubModuleReplacementDescription]]:
|
||||
r"""
|
||||
This method returns the module policy, which is a dictionary. The key is the module name or the module object,
|
||||
and the value is the ModulePolicyDescription object. The ModulePolicyDescription object describes how the module
|
||||
will be transformed.
|
||||
"""
|
||||
|
||||
def append_or_create_submodule_replacement(
|
||||
self,
|
||||
description: Union[SubModuleReplacementDescription, List[SubModuleReplacementDescription]],
|
||||
target_key: Union[str, nn.Module],
|
||||
) -> Dict[Union[str, nn.Module], List]:
|
||||
r"""
|
||||
Append or create a new submodule replacement description to the policy for the given key.
|
||||
|
||||
Args:
|
||||
submodule_replace_desc (Union[SubModuleReplacementDescription, List[SubModuleReplacementDescription]]): the submodule replacement description to be appended
|
||||
policy (Dict[Union[str, nn.Module], ModulePolicyDescription]): the policy to be updated
|
||||
target_key (Union[str, nn.Module]): the key of the policy to be updated
|
||||
"""
|
||||
# convert to list
|
||||
if isinstance(description, SubModuleReplacementDescription):
|
||||
description = [description]
|
||||
|
||||
# append or create a new description
|
||||
if target_key in self.policy:
|
||||
if self.policy[target_key].sub_module_replacement is None:
|
||||
self.policy[target_key].sub_module_replacement = description
|
||||
else:
|
||||
self.policy[target_key].sub_module_replacement.extend(
|
||||
description)
|
||||
else:
|
||||
self.policy[target_key] = ModulePolicyDescription(
|
||||
sub_module_replacement=description)
|
||||
|
||||
def append_or_create_method_replacement(
|
||||
self,
|
||||
description: Dict[str, Callable],
|
||||
target_key: Union[str, nn.Module],
|
||||
) -> Dict[Union[str, nn.Module], ModulePolicyDescription]:
|
||||
r"""
|
||||
Append or create a new method replacement description to the policy for the given key.
|
||||
|
||||
Args:
|
||||
description (Union[SubModuleReplacementDescription, List[SubModuleReplacementDescription]]): the submodule replacement description to be appended
|
||||
policy (Dict[Union[str, nn.Module], ModulePolicyDescription]): the policy to be updated
|
||||
target_key (Union[str, nn.Module]): the key of the policy to be updated
|
||||
"""
|
||||
if target_key in self.policy:
|
||||
if self.policy[target_key].method_replacement is None:
|
||||
self.policy[target_key].method_replacement = description
|
||||
else:
|
||||
self.policy[target_key].method_replacement.extend(description)
|
||||
else:
|
||||
self.policy[target_key] = ModulePolicyDescription(
|
||||
method_replacement=description)
|
||||
|
||||
def append_or_create_attribute_replacement(
|
||||
self,
|
||||
description: Dict[str, Callable],
|
||||
target_key: Union[str, nn.Module],
|
||||
) -> Dict[Union[str, nn.Module], ModulePolicyDescription]:
|
||||
r"""
|
||||
Append or create a new method replacement description to the policy for the given key.
|
||||
|
||||
Args:
|
||||
description (Union[SubModuleReplacementDescription, List[SubModuleReplacementDescription]]): the submodule replacement description to be appended
|
||||
policy (Dict[Union[str, nn.Module], ModulePolicyDescription]): the policy to be updated
|
||||
target_key (Union[str, nn.Module]): the key of the policy to be updated
|
||||
"""
|
||||
if target_key in self.policy:
|
||||
if self.policy[target_key].attribute_replacement is None:
|
||||
self.policy[target_key].attribute_replacement = description
|
||||
else:
|
||||
self.policy[target_key].attribute_replacement.extend(
|
||||
description)
|
||||
else:
|
||||
self.policy[target_key] = ModulePolicyDescription(
|
||||
attribute_replacement=description)
|
||||
|
||||
def accelerate(self, model) -> None:
|
||||
r"""
|
||||
Replace the module according to the policy, and replace the module one by one
|
||||
|
||||
Args:
|
||||
model (:class:`torch.nn.Module`): The model to shard
|
||||
"""
|
||||
self.module_policy()
|
||||
self.module_replace = []
|
||||
for layer_cls, module_description in self.policy.items():
|
||||
self.replace_sub_module(
|
||||
model, layer_cls, module_description.sub_module_replacement)
|
||||
self._replace_method(
|
||||
model, layer_cls, module_description.method_replacement)
|
||||
print_rank_0(tabulate.tabulate(self.module_replace, headers=[
|
||||
"old_layer", "new_layer"], tablefmt="psql"))
|
||||
return model
|
||||
|
||||
def replace_sub_module(
|
||||
self,
|
||||
module: nn.Module,
|
||||
origin_cls: Union[str, nn.Module],
|
||||
sub_module_replacement: List[SubModuleReplacementDescription],
|
||||
) -> None:
|
||||
r"""
|
||||
Reverse the replace layer operation
|
||||
"""
|
||||
if not sub_module_replacement:
|
||||
return
|
||||
|
||||
if (isinstance(origin_cls, str) and origin_cls == module.__class__.__name__) or (
|
||||
module.__class__ == origin_cls
|
||||
):
|
||||
for description in sub_module_replacement:
|
||||
suffix = description.suffix
|
||||
target_module = description.target_module
|
||||
kwargs = {} if description.kwargs is None else description.kwargs
|
||||
|
||||
assert target_module is not None, "target_module should not be None"
|
||||
|
||||
native_sub_module = getattr_(module, suffix, ignore=True)
|
||||
|
||||
assert not isinstance(
|
||||
native_sub_module, target_module
|
||||
), f"The module with suffix {suffix} has been replaced, please check the policy"
|
||||
|
||||
# if it is None and we are allowed to ignore this module
|
||||
# just skip
|
||||
if description.ignore_if_not_exist and native_sub_module is None:
|
||||
continue
|
||||
try:
|
||||
replace_layer = target_module.from_native_module(
|
||||
native_sub_module, **kwargs)
|
||||
except Exception as e:
|
||||
raise RuntimeError(
|
||||
f"Failed to replace {suffix} of type {native_sub_module.__class__.__qualname__}"
|
||||
f" with {target_module.__qualname__} with the exception: {e}. "
|
||||
"Please check your model configuration or sharding policy, you can set up an issue for us to help you as well."
|
||||
)
|
||||
|
||||
setattr_(module, suffix, replace_layer)
|
||||
self.module_replace.append(
|
||||
[native_sub_module.__class__.__qualname__, target_module.__qualname__])
|
||||
|
||||
for name, child in module.named_children():
|
||||
self.replace_sub_module(
|
||||
child,
|
||||
origin_cls,
|
||||
sub_module_replacement,
|
||||
)
|
||||
|
||||
def _replace_method(self, module: nn.Module, origin_cls: Union[str, nn.Module], method_replacement: List[Dict[str, Callable]]):
|
||||
if not method_replacement:
|
||||
return
|
||||
|
||||
if (isinstance(origin_cls, str) and origin_cls == module.__class__.__name__) or (
|
||||
module.__class__ == origin_cls
|
||||
):
|
||||
for method in method_replacement:
|
||||
for method_name, new_method in method.items():
|
||||
# bind the new method to the module
|
||||
bound_method = MethodType(new_method, module)
|
||||
setattr(module, method_name, bound_method)
|
||||
|
||||
for name, child in module.named_children():
|
||||
self._replace_method(
|
||||
child,
|
||||
origin_cls,
|
||||
method_replacement,
|
||||
)
|
||||
|
||||
def _replace_attr(
|
||||
self,
|
||||
module: nn.Module,
|
||||
origin_cls: Union[str, nn.Module],
|
||||
attr_replacement: List[Dict[str, Any]],
|
||||
) -> None:
|
||||
r"""
|
||||
Replace the attribute of the layer
|
||||
|
||||
Args:
|
||||
module (:class:`torch.nn.Module`): The object of layer to shard
|
||||
attr_replacement (Dict): The attribute dict to modify
|
||||
"""
|
||||
if not attr_replacement:
|
||||
return
|
||||
|
||||
if (isinstance(origin_cls, str) and origin_cls == module.__class__.__name__) or (
|
||||
module.__class__ == origin_cls
|
||||
):
|
||||
for attr in attr_replacement:
|
||||
for module_attr, target_attr in attr.items():
|
||||
native_attr = getattr_(module, module_attr, ignore=False)
|
||||
if isinstance(native_attr, type):
|
||||
replace_attr = target_attr.from_native_attr(
|
||||
native_attr)
|
||||
setattr_(module, module_attr,
|
||||
replace_attr, ignore=False)
|
||||
else:
|
||||
setattr_(module, module_attr,
|
||||
target_attr, ignore=False)
|
||||
|
||||
for name, child in module.named_children():
|
||||
self._replace_attr(
|
||||
child,
|
||||
origin_cls,
|
||||
attr_replacement,
|
||||
)
|
||||
156
ixformer_sdk/train/speedformer/policy/utils.py
Normal file
156
ixformer_sdk/train/speedformer/policy/utils.py
Normal file
@@ -0,0 +1,156 @@
|
||||
from abc import ABC, abstractmethod
|
||||
from dataclasses import dataclass
|
||||
from typing import Any, Callable, Dict, List, Optional, Union
|
||||
import re
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
|
||||
|
||||
@dataclass
|
||||
class SubModuleReplacementDescription:
|
||||
r"""
|
||||
Describe how a submodule will be replaced
|
||||
|
||||
Args:
|
||||
suffix (str): used to get the submodule object
|
||||
target_module (ParallelModule): specifies the module class used to replace to submodule
|
||||
kwargs (Dict[str, Any]): the dictionary used to pass extra arguments to the `ParallelModule.from_native_module` method.
|
||||
ignore_if_not_exist (bool): if the submodule does not exist, ignore it or raise an exception
|
||||
"""
|
||||
|
||||
suffix: str
|
||||
target_module: nn.Module
|
||||
kwargs: Dict[str, Any] = None
|
||||
ignore_if_not_exist: bool = False
|
||||
|
||||
|
||||
@dataclass
|
||||
class ModulePolicyDescription:
|
||||
"copy from colossalai, for now sub_module_replacement and method_replacement is used"
|
||||
r"""
|
||||
Describe how the attributes and parameters will be transformed in a policy.
|
||||
|
||||
Args:
|
||||
attribute_replacement (Dict[str, Any]): key is the attribute name, value is the attribute value after sharding
|
||||
param_replacement (List[Callable]): a list of functions to perform in-place param replacement. The function
|
||||
must receive only one arguments: module. One example is
|
||||
|
||||
```python
|
||||
def example_replace_weight(module: torch.nn.Module):
|
||||
weight = module.weight
|
||||
new_weight = shard_rowwise(weight, process_group)
|
||||
module.weight = torch.nn.Parameter(new_weight)
|
||||
```
|
||||
sub_module_replacement (List[SubModuleReplacementDescription]): each element in the list is a SubModuleReplacementDescription
|
||||
object which specifies the module to be replaced and the target module used to replacement.
|
||||
method_replace (Dict[str, Callable]): key is the method name, value is the method for replacement
|
||||
"""
|
||||
|
||||
attribute_replacement: List[Dict[str, Any]] = None
|
||||
param_replacement: List[Callable] = None
|
||||
sub_module_replacement: List[SubModuleReplacementDescription] = None
|
||||
method_replacement: List[Dict[str, Callable]] = None
|
||||
|
||||
|
||||
def getattr_(obj, attr: str, ignore: bool = False):
|
||||
r"""
|
||||
Get the object's multi sublevel attr
|
||||
|
||||
Args:
|
||||
obj (object): The object to set
|
||||
attr (str): The multi level attr to set
|
||||
ignore (bool): Whether to ignore when the attr doesn't exist
|
||||
"""
|
||||
|
||||
attrs = attr.split(".")
|
||||
for a in attrs:
|
||||
try:
|
||||
obj = get_obj_list_element(obj, a)
|
||||
except AttributeError:
|
||||
if ignore:
|
||||
return None
|
||||
raise AttributeError(
|
||||
f"Object {obj.__class__.__name__} has no attribute {attr}")
|
||||
return obj
|
||||
|
||||
|
||||
def get_obj_list_element(obj, attr: str):
|
||||
r"""
|
||||
Get the element of the list in the object
|
||||
|
||||
If the attr is a normal attribute, return the attribute of the object.
|
||||
If the attr is a index type, return the element of the index in the list, like `layers[0]`.
|
||||
|
||||
Args:
|
||||
obj (Object): The object to get
|
||||
attr (str): The suffix of the attribute to get
|
||||
|
||||
"""
|
||||
re_pattern = r"\[\d+\]"
|
||||
prog = re.compile(re_pattern)
|
||||
result = prog.search(attr)
|
||||
if result:
|
||||
matched_brackets = result.group()
|
||||
matched_index = matched_brackets.replace("[", "")
|
||||
matched_index = matched_index.replace("]", "")
|
||||
attr_ = attr.replace(matched_brackets, "")
|
||||
container_obj = getattr(obj, attr_)
|
||||
obj = container_obj[int(matched_index)]
|
||||
else:
|
||||
obj = getattr(obj, attr)
|
||||
return obj
|
||||
|
||||
|
||||
def setattr_(obj, attr: str, value, ignore: bool = False):
|
||||
r"""
|
||||
Set the object's multi sublevel attr to value, if ignore, ignore when it doesn't exist
|
||||
|
||||
Args:
|
||||
obj (object): The object to set
|
||||
attr (str): The multi level attr to set
|
||||
value (Any): The value to set
|
||||
ignore (bool): Whether to ignore when the attr doesn't exist
|
||||
"""
|
||||
|
||||
attrs = attr.split(".")
|
||||
for a in attrs[:-1]:
|
||||
try:
|
||||
obj = get_obj_list_element(obj, a)
|
||||
except AttributeError:
|
||||
if ignore:
|
||||
return
|
||||
raise AttributeError(
|
||||
f"Object {obj.__class__.__name__} has no attribute {attr}")
|
||||
set_obj_list_element(obj, attrs[-1], value)
|
||||
|
||||
|
||||
def set_obj_list_element(obj, attr: str, value):
|
||||
r"""
|
||||
Set the element to value of a list object
|
||||
|
||||
It used like set_obj_list_element(obj, 'layers[0]', new_layer), it will set obj.layers[0] to value
|
||||
|
||||
Args:
|
||||
obj (object): The object to set
|
||||
attr (str): the string including a list index like `layers[0]`
|
||||
"""
|
||||
re_pattern = r"\[\d+\]"
|
||||
prog = re.compile(re_pattern)
|
||||
result = prog.search(attr)
|
||||
if result:
|
||||
matched_brackets = result.group()
|
||||
matched_index = matched_brackets.replace("[", "")
|
||||
matched_index = matched_index.replace("]", "")
|
||||
attr_ = attr.replace(matched_brackets, "")
|
||||
container_obj = getattr(obj, attr_)
|
||||
container_obj[int(matched_index)] = value
|
||||
else:
|
||||
setattr(obj, attr, value)
|
||||
|
||||
|
||||
def print_rank_0(message):
|
||||
if torch.distributed.is_initialized():
|
||||
if torch.distributed.get_rank() == 0:
|
||||
print(message, flush=True)
|
||||
else:
|
||||
print(message, flush=True)
|
||||
25
ixformer_sdk/train/speedformer/speedformer.py
Normal file
25
ixformer_sdk/train/speedformer/speedformer.py
Normal file
@@ -0,0 +1,25 @@
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
from abc import ABC
|
||||
from ixformer.train.speedformer.model_replacer_mapping import ModelMapping
|
||||
|
||||
# 外部接口
|
||||
class SpeedFormer(ABC):
|
||||
def __init__(self) -> None:
|
||||
super().__init__()
|
||||
self.replacer = None
|
||||
|
||||
|
||||
def accelerate(self, model):
|
||||
if model.config.model_type in ModelMapping:
|
||||
self.replacer = ModelMapping[model.config.model_type]()
|
||||
accelerate_model = self.replacer.accelerate(model)
|
||||
else:
|
||||
Warning(f"Warning: model '{model.config.model_type}' is not supported now.")
|
||||
accelerate_model = model
|
||||
|
||||
return accelerate_model
|
||||
|
||||
|
||||
def post_process(self, model):
|
||||
self.replacer.post_process(model)
|
||||
Reference in New Issue
Block a user