mattmengli commited on
Commit
2510df9
·
1 Parent(s): 43af8e0

init model

Browse files
config.json ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "BailingMoeLinearForCausalLM"
4
+ ],
5
+ "attention_dropout": 0.0,
6
+ "auto_map": {
7
+ "AutoConfig": "configuration_bailing_moe_linear.BailingMoeLinearConfig",
8
+ "AutoModel": "modeling_bailing_moe_linear.BailingMoeLinearModel",
9
+ "AutoModelForCausalLM": "modeling_bailing_moe_linear.BailingMoeLinearForCausalLM"
10
+ },
11
+ "eos_token_id": 126081,
12
+ "pad_token_id": 126081,
13
+ "first_k_dense_replace": 0,
14
+ "hidden_act": "silu",
15
+ "hidden_size": 2048,
16
+ "initializer_range": 0.006,
17
+ "intermediate_size": 5632,
18
+ "max_position_embeddings": 16384,
19
+ "model_type": "bailing_moe_linear",
20
+ "moe_intermediate_size": 1408,
21
+ "num_experts": 64,
22
+ "num_shared_experts": 2,
23
+ "norm_topk_prob": true,
24
+ "num_attention_heads": 16,
25
+ "num_experts_per_tok": 6,
26
+ "num_hidden_layers": 28,
27
+ "num_key_value_heads": 4,
28
+ "pretraining_tp": 1,
29
+ "rms_norm_eps": 1e-05,
30
+ "rope_scaling": null,
31
+ "rope_theta": 600000,
32
+ "tie_word_embeddings": false,
33
+ "torch_dtype": "bfloat16",
34
+ "transformers_version": "4.36.0",
35
+ "use_cache": true,
36
+ "use_bias": false,
37
+ "use_qkv_bias": false,
38
+ "vocab_size": 126464,
39
+ "embedding_dropout": 0.0,
40
+ "norm_head": true,
41
+ "norm_softmax": false,
42
+ "output_dropout": 0.0,
43
+ "output_router_logits": false,
44
+ "layer_group_size": 7,
45
+ "use_linear_silu": false,
46
+ "linear_rope": true,
47
+ "use_linear_gpa": false,
48
+ "use_low_rank": false,
49
+ "linear_mode": "chunk"
50
+ }
configuration_bailing_moe_linear.py ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ Bailing MoE model configuration """
2
+
3
+ from transformers.configuration_utils import PretrainedConfig
4
+
5
+
6
+ class BailingMoeLinearConfig(PretrainedConfig):
7
+ model_type = "bailing_moe_linear"
8
+
9
+ def __init__(
10
+ self,
11
+ vocab_size=30592,
12
+ hidden_size=1024,
13
+ intermediate_size=None,
14
+ num_hidden_layers=24,
15
+ num_attention_heads=16,
16
+ num_key_value_heads=0,
17
+ hidden_act="silu",
18
+ use_qkv_bias=False, # bailing only
19
+ use_bias=True, # bailing only
20
+ rms_norm_eps=1e-05,
21
+ norm_head=False, # bailing only
22
+ tie_word_embeddings=False, # PretrainedConfig key, here change default value.
23
+ embedding_dropout=0.1,
24
+ attention_dropout=0.1,
25
+ output_dropout=0.1,
26
+ initializer_range=0.02,
27
+ max_position_embeddings=16384,
28
+ rope_theta=10000.0,
29
+ use_cache=True,
30
+ use_sliding_window=False,
31
+ sliding_window=4096,
32
+ max_window_layers=28,
33
+ rope_scaling=None,
34
+ pad_token_id=126081,
35
+ num_experts=16,
36
+ num_shared_experts=0,
37
+ num_experts_per_tok=2,
38
+ norm_topk_prob=True,
39
+ moe_intermediate_size=None,
40
+ first_k_dense_replace=0,
41
+ head_dim=None,
42
+ output_router_logits=False,
43
+ layer_group_size=1,
44
+ use_linear_silu=False,
45
+ linear_rope=True,
46
+ use_linear_gqa=False,
47
+ use_low_rank=False,
48
+ rotary_type='full-1d',
49
+ linear_mode='chunk',
50
+ **kwargs,
51
+ ):
52
+ self.num_hidden_layers = num_hidden_layers
53
+ self.vocab_size = vocab_size
54
+ self.hidden_size = hidden_size
55
+ self.intermediate_size = intermediate_size
56
+ self.num_attention_heads = num_attention_heads
57
+ self.num_key_value_heads = num_key_value_heads
58
+ self.hidden_act = hidden_act
59
+ self.use_qkv_bias = use_qkv_bias
60
+ self.use_bias = use_bias
61
+ self.norm_head = norm_head
62
+ self.rms_norm_eps = rms_norm_eps
63
+ self.embedding_dropout = embedding_dropout
64
+ self.attention_dropout = attention_dropout
65
+ self.output_dropout = output_dropout
66
+ self.initializer_range = initializer_range
67
+ self.max_position_embeddings = max_position_embeddings
68
+ self.rope_theta = rope_theta
69
+ self.use_cache = use_cache
70
+ self.use_sliding_window = use_sliding_window
71
+ self.sliding_window = sliding_window
72
+ self.max_window_layers = max_window_layers
73
+ self.head_dim = head_dim or self.hidden_size // self.num_attention_heads
74
+ self.rope_scaling = rope_scaling
75
+
76
+ # MoE configs
77
+ self.num_experts = num_experts
78
+ self.num_shared_experts = num_shared_experts
79
+ self.num_experts_per_tok = num_experts_per_tok
80
+ self.norm_topk_prob = norm_topk_prob
81
+ self.moe_intermediate_size = moe_intermediate_size
82
+ self.first_k_dense_replace = first_k_dense_replace
83
+ self.output_router_logits = output_router_logits
84
+
85
+ # hybrid linear configs
86
+ self.layer_group_size = layer_group_size
87
+ self.use_linear_silu = use_linear_silu
88
+ self.linear_rope = linear_rope
89
+ self.use_linear_gqa = use_linear_gqa
90
+ self.use_low_rank = use_low_rank
91
+ self.rotary_type = rotary_type
92
+ self.linear_mode = linear_mode
93
+
94
+ super().__init__(pad_token_id=pad_token_id, tie_word_embeddings=tie_word_embeddings, **kwargs)
model-00001-of-00004.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2b17f713e7a8004fe6cd54d579c43c75a8b7ea38894f86fac6cd60d53b96e384
3
+ size 8268016216
model-00002-of-00004.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4d15b10ce9630cf1ffa4f74ef1a493a91b958d9d3c56a1c661b3661818fd7e7f
3
+ size 8268017024
model-00003-of-00004.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2cfcc75a197c543f64e1c7d2dd3db3a4f99393d63b4fcc610541961fa03d6f87
3
+ size 8268017632
model-00004-of-00004.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:fe8d770f22b1b2de30acafdef3f6d4860143e5fb5822b3cb95ac9c4af9b26d4f
3
+ size 9304015544
model.safetensors.index.json ADDED
The diff for this file is too large to render. See raw diff
 
modeling_bailing_moe_linear.py ADDED
@@ -0,0 +1,1867 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 Antgroup and The HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
5
+ # and OPT implementations in this library. It has been modified from its
6
+ # original forms to accommodate minor architectural differences compared
7
+ # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
8
+ #
9
+ # Licensed under the Apache License, Version 2.0 (the "License");
10
+ # you may not use this file except in compliance with the License.
11
+ # You may obtain a copy of the License at
12
+ #
13
+ # http://www.apache.org/licenses/LICENSE-2.0
14
+ #
15
+ # Unless required by applicable law or agreed to in writing, software
16
+ # distributed under the License is distributed on an "AS IS" BASIS,
17
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
+ # See the License for the specific language governing permissions and
19
+ # limitations under the License.
20
+ """ PyTorch BailingMoeLinear Model."""
21
+ import math
22
+ import warnings
23
+ from typing import List, Optional, Tuple, Union
24
+ from einops import rearrange, repeat
25
+
26
+ import torch
27
+ import torch.nn.functional as F
28
+ import torch.utils.checkpoint
29
+ from torch import nn
30
+ from torch.nn import CrossEntropyLoss
31
+ from transformers.activations import ACT2FN
32
+ from transformers.cache_utils import Cache, DynamicCache
33
+ from transformers.modeling_attn_mask_utils import (
34
+ AttentionMaskConverter, _prepare_4d_attention_mask,
35
+ _prepare_4d_causal_attention_mask,
36
+ _prepare_4d_causal_attention_mask_for_sdpa)
37
+ from transformers.modeling_outputs import (MoeCausalLMOutputWithPast,
38
+ MoeModelOutputWithPast)
39
+ from transformers.modeling_utils import PreTrainedModel
40
+ from transformers.pytorch_utils import (ALL_LAYERNORM_LAYERS,
41
+ is_torch_greater_or_equal_than_1_13)
42
+ from transformers.utils import (add_start_docstrings,
43
+ add_start_docstrings_to_model_forward,
44
+ is_flash_attn_2_available,
45
+ is_flash_attn_greater_or_equal_2_10, logging,
46
+ replace_return_docstrings)
47
+ from transformers.utils.import_utils import is_torch_fx_available
48
+ from .configuration_bailing_moe_linear import BailingMoeLinearConfig
49
+
50
+ if is_flash_attn_2_available():
51
+ from flash_attn import flash_attn_func, flash_attn_varlen_func
52
+ from flash_attn.bert_padding import (index_first_axis, pad_input, # noqa
53
+ unpad_input)
54
+ from fla.ops.simple_gla.fused_recurrent import fused_recurrent_simple_gla
55
+ from fla.ops.simple_gla.chunk import chunk_simple_gla
56
+
57
+ # This makes `_prepare_4d_causal_attention_mask` a leaf function in the FX graph.
58
+ # It means that the function will not be traced through and simply appear as a node in the graph.
59
+ if is_torch_fx_available():
60
+ if not is_torch_greater_or_equal_than_1_13:
61
+ import torch.fx
62
+
63
+ _prepare_4d_causal_attention_mask = torch.fx.wrap(_prepare_4d_causal_attention_mask)
64
+
65
+
66
+ logger = logging.get_logger(__name__)
67
+
68
+ _CONFIG_FOR_DOC = "BailingMoeLinearConfig"
69
+
70
+
71
+ def _get_unpad_data(attention_mask):
72
+ seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
73
+ indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
74
+ max_seqlen_in_batch = seqlens_in_batch.max().item()
75
+ cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.torch.int32), (1, 0))
76
+ return (
77
+ indices,
78
+ cu_seqlens,
79
+ max_seqlen_in_batch,
80
+ )
81
+
82
+
83
+ def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None):
84
+ warnings.warn(
85
+ "Calling `transformers.models.BailingMoe.modeling_BailingMoe._prepare_4d_attention_mask` is deprecated and will be removed in v4.37. Use `transformers.modeling_attn_mask_utils._prepare_4d_attention_mask"
86
+ )
87
+ return _prepare_4d_attention_mask(mask=mask, dtype=dtype, tgt_len=tgt_len)
88
+
89
+
90
+ def _make_causal_mask(
91
+ input_ids_shape: torch.Size, dtype: torch.dtype, device: torch.device, past_key_values_length: int = 0
92
+ ):
93
+ warnings.warn(
94
+ "Calling `transformers.models.BailingMoe.modeling_BailingMoe._make_causal_mask` is deprecated and will be removed in v4.37. Use `transformers.models.BailingMoe.modeling_BailingMoe.AttentionMaskConverter._make_causal_mask"
95
+ )
96
+ return AttentionMaskConverter._make_causal_mask(
97
+ input_ids_shape=input_ids_shape, dtype=dtype, device=device, past_key_values_length=past_key_values_length
98
+ )
99
+
100
+
101
+ class BailingMoeRMSNorm(nn.Module):
102
+ def __init__(self, hidden_size, eps=1e-6):
103
+ """
104
+ BailingMoeRMSNorm is equivalent to T5LayerNorm
105
+ """
106
+ super().__init__()
107
+ self.weight = nn.Parameter(torch.ones(hidden_size))
108
+ self.variance_epsilon = eps
109
+
110
+ def forward(self, hidden_states):
111
+ input_dtype = hidden_states.dtype
112
+ hidden_states = hidden_states.to(torch.float32)
113
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
114
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
115
+ return self.weight * hidden_states.to(input_dtype)
116
+
117
+ ALL_LAYERNORM_LAYERS.append(BailingMoeRMSNorm)
118
+
119
+
120
+ class BailingMoeRotaryEmbedding(nn.Module):
121
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
122
+ super().__init__()
123
+
124
+ self.dim = dim
125
+ self.max_position_embeddings = max_position_embeddings
126
+ self.base = base
127
+ inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim))
128
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
129
+
130
+ # Build here to make `torch.jit.trace` work.
131
+ self._set_cos_sin_cache(
132
+ seq_len=max_position_embeddings, device=self.inv_freq.device, dtype=torch.get_default_dtype()
133
+ )
134
+ self.max_seq_len_cached = None
135
+
136
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
137
+ self.max_seq_len_cached = seq_len
138
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
139
+
140
+ freqs = torch.outer(t, self.inv_freq.to(t.device))
141
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
142
+ emb = torch.cat((freqs, freqs), dim=-1)
143
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
144
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
145
+
146
+ def forward(self, x, seq_len=None):
147
+ # x: [bs, num_attention_heads, seq_len, head_size]
148
+ if self.max_seq_len_cached is None or seq_len > self.max_seq_len_cached:
149
+ self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)
150
+
151
+ return (
152
+ self.cos_cached[:seq_len].to(dtype=x.dtype),
153
+ self.sin_cached[:seq_len].to(dtype=x.dtype),
154
+ )
155
+
156
+
157
+ # Copied from transformers.models.llama.modeling_llama.LlamaLinearScalingRotaryEmbedding with Llama->BailingMoe
158
+ class BailingMoeLinearScalingRotaryEmbedding(BailingMoeRotaryEmbedding):
159
+ """BailingMoeRotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendev"""
160
+
161
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):
162
+ self.scaling_factor = scaling_factor
163
+ super().__init__(dim, max_position_embeddings, base, device)
164
+
165
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
166
+ self.max_seq_len_cached = seq_len
167
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
168
+ t = t / self.scaling_factor
169
+
170
+ freqs = torch.outer(t, self.inv_freq)
171
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
172
+ emb = torch.cat((freqs, freqs), dim=-1)
173
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
174
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
175
+
176
+
177
+ # Copied from transformers.models.llama.modeling_llama.LlamaDynamicNTKScalingRotaryEmbedding with Llama->BailingMoe
178
+ class BailingMoeDynamicNTKScalingRotaryEmbedding(BailingMoeRotaryEmbedding):
179
+ """BailingMoeRotaryEmbedding extended with Dynamic NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozilla"""
180
+
181
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):
182
+ self.scaling_factor = scaling_factor
183
+ super().__init__(dim, max_position_embeddings, base, device)
184
+
185
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
186
+ self.max_seq_len_cached = seq_len
187
+
188
+ if seq_len > self.max_position_embeddings:
189
+ base = self.base * (
190
+ (self.scaling_factor * seq_len / self.max_position_embeddings) - (self.scaling_factor - 1)
191
+ ) ** (self.dim / (self.dim - 2))
192
+ inv_freq = 1.0 / (base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim))
193
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
194
+
195
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
196
+
197
+ freqs = torch.outer(t, self.inv_freq)
198
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
199
+ emb = torch.cat((freqs, freqs), dim=-1)
200
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
201
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
202
+
203
+
204
+ # Inverse dim formula to find dim based on number of rotations
205
+ def yarn_find_correction_dim(num_rotations, dim, base=10000, max_position_embeddings=2048):
206
+ return (dim * math.log(max_position_embeddings / (num_rotations * 2 * math.pi))) / (2 * math.log(base))
207
+
208
+
209
+ # Find dim range bounds based on rotations
210
+ def yarn_find_correction_range(low_rot, high_rot, dim, base=10000, max_position_embeddings=2048):
211
+ low = math.floor(yarn_find_correction_dim(low_rot, dim, base, max_position_embeddings))
212
+ high = math.ceil(yarn_find_correction_dim(high_rot, dim, base, max_position_embeddings))
213
+ return max(low, 0), min(high, dim - 1) # Clamp values just in case
214
+
215
+
216
+ def yarn_get_mscale(scale=1, mscale=1):
217
+ if scale <= 1:
218
+ return 1.0
219
+ return 0.1 * mscale * math.log(scale) + 1.0
220
+
221
+
222
+ def yarn_linear_ramp_mask(min, max, dim):
223
+ if min == max:
224
+ max += 0.001 # Prevent singularity
225
+
226
+ linear_func = (torch.arange(dim, dtype=torch.float32) - min) / (max - min)
227
+ ramp_func = torch.clamp(linear_func, 0, 1)
228
+ return ramp_func
229
+
230
+
231
+ class BailingMoeYarnRotaryEmbedding(BailingMoeRotaryEmbedding):
232
+
233
+ def __init__(
234
+ self,
235
+ dim,
236
+ max_position_embeddings=2048,
237
+ base=10000,
238
+ device=None,
239
+ scaling_factor=1.0,
240
+ original_max_position_embeddings=4096,
241
+ beta_fast=32,
242
+ beta_slow=1,
243
+ mscale=1,
244
+ mscale_all_dim=0,
245
+ ):
246
+ self.scaling_factor = scaling_factor
247
+ self.original_max_position_embeddings = original_max_position_embeddings
248
+ self.beta_fast = beta_fast
249
+ self.beta_slow = beta_slow
250
+ self.mscale = mscale
251
+ self.mscale_all_dim = mscale_all_dim
252
+ super().__init__(dim, max_position_embeddings, base, device)
253
+
254
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
255
+ self.max_seq_len_cached = seq_len
256
+ dim = self.dim
257
+
258
+ freq_extra = 1.0 / (self.base ** (torch.arange(0, dim, 2, dtype=torch.float32, device=device) / dim))
259
+ freq_inter = 1.0 / (
260
+ self.scaling_factor * self.base ** (torch.arange(0, dim, 2, dtype=torch.float32, device=device) / dim)
261
+ )
262
+
263
+ low, high = yarn_find_correction_range(
264
+ self.beta_fast,
265
+ self.beta_slow,
266
+ dim,
267
+ self.base,
268
+ self.original_max_position_embeddings,
269
+ )
270
+ inv_freq_mask = 1.0 - yarn_linear_ramp_mask(low, high, dim // 2).to(device=device, dtype=torch.float32)
271
+ inv_freq = freq_inter * (1 - inv_freq_mask) + freq_extra * inv_freq_mask
272
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
273
+
274
+ t = torch.arange(seq_len, device=device, dtype=torch.float32)
275
+
276
+ freqs = torch.outer(t, inv_freq)
277
+
278
+ _mscale = float(
279
+ yarn_get_mscale(self.scaling_factor, self.mscale)
280
+ / yarn_get_mscale(self.scaling_factor, self.mscale_all_dim)
281
+ )
282
+
283
+ emb = torch.cat((freqs, freqs), dim=-1)
284
+ self.register_buffer("cos_cached", (emb.cos() * _mscale).to(dtype), persistent=False)
285
+ self.register_buffer("sin_cached", (emb.sin() * _mscale).to(dtype), persistent=False)
286
+
287
+
288
+ # Copied from transformers.models.llama.modeling_llama.rotate_half
289
+ def rotate_half(x):
290
+ """Rotates half the hidden dims of the input."""
291
+ x1 = x[..., : x.shape[-1] // 2]
292
+ x2 = x[..., x.shape[-1] // 2 :]
293
+ return torch.cat((-x2, x1), dim=-1)
294
+
295
+
296
+ # Copied from transformers.models.llama.modeling_llama.apply_rotary_pos_emb
297
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1):
298
+ """Applies Rotary Position Embedding to the query and key tensors.
299
+
300
+ Args:
301
+ q (`torch.Tensor`): The query tensor.
302
+ k (`torch.Tensor`): The key tensor.
303
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
304
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
305
+ position_ids (`torch.Tensor`):
306
+ The position indices of the tokens corresponding to the query and key tensors. For example, this can be
307
+ used to pass offsetted position ids when working with a KV-cache.
308
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
309
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
310
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
311
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
312
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
313
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
314
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
315
+ Returns:
316
+ `tuple(torch.Tensor)` comprising the query and key tensors rotated using the Rotary Position Embedding.
317
+ """
318
+ cos = cos[position_ids].unsqueeze(unsqueeze_dim)
319
+ sin = sin[position_ids].unsqueeze(unsqueeze_dim)
320
+ q_embed = (q * cos) + (rotate_half(q) * sin)
321
+ k_embed = (k * cos) + (rotate_half(k) * sin)
322
+ return q_embed, k_embed
323
+
324
+ class BailingMoeMLP(nn.Module):
325
+ def __init__(self, config: BailingMoeLinearConfig, intermediate_size: int):
326
+ super().__init__()
327
+ self.config = config
328
+ self.hidden_size = config.hidden_size
329
+ self.intermediate_size = intermediate_size
330
+
331
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
332
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
333
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
334
+ self.act_fn = ACT2FN[config.hidden_act]
335
+
336
+ def forward(self, x):
337
+ return self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
338
+
339
+
340
+ class BailingMoeGate(nn.Module):
341
+ def __init__(self, config):
342
+ super().__init__()
343
+ self.config = config
344
+ self.top_k = config.num_experts_per_tok
345
+ self.num_experts = config.num_experts
346
+
347
+ # topk selection algorithm
348
+ self.norm_topk_prob = config.norm_topk_prob
349
+ self.gating_dim = config.hidden_size
350
+ self.weight = nn.Parameter(torch.empty((self.num_experts, self.gating_dim)))
351
+ self.reset_parameters()
352
+
353
+ def reset_parameters(self) -> None:
354
+ import torch.nn.init as init
355
+ init.kaiming_uniform_(self.weight, a=math.sqrt(5))
356
+
357
+ def forward(self, hidden_states, sort=False):
358
+ bsz, seq_len, h = hidden_states.shape
359
+ # compute gating score
360
+ hidden_states = hidden_states.view(-1, h)
361
+ logits = F.linear(hidden_states, self.weight, None)
362
+ scores = logits.softmax(dim=-1, dtype=torch.float32)
363
+
364
+ # select top-k experts
365
+ topk_weight, topk_idx = torch.topk(scores, k=self.top_k, dim=-1, sorted=sort)
366
+
367
+ # norm gate to sum 1
368
+ if self.top_k > 1 and self.norm_topk_prob:
369
+ denominator = topk_weight.sum(dim=-1, keepdim=True)
370
+ topk_weight = topk_weight / denominator
371
+
372
+ return topk_idx, topk_weight, logits
373
+
374
+
375
+ class BailingMoeSparseMoeBlock(nn.Module):
376
+ """
377
+ A mixed expert module containing shared experts.
378
+ """
379
+
380
+ def __init__(self, config: BailingMoeLinearConfig):
381
+ super().__init__()
382
+ self.config = config
383
+ self.num_experts_per_tok = config.num_experts_per_tok
384
+ self._setup_experts()
385
+ self.gate = BailingMoeGate(config)
386
+ if config.num_shared_experts is not None:
387
+ self.shared_experts = BailingMoeMLP(
388
+ config=config, intermediate_size=config.moe_intermediate_size * config.num_shared_experts
389
+ )
390
+
391
+ def _setup_experts(self):
392
+ self.experts = nn.ModuleList(
393
+ [
394
+ BailingMoeMLP(config=self.config, intermediate_size=self.config.moe_intermediate_size)
395
+ for _ in range(self.config.num_experts)
396
+ ]
397
+ )
398
+
399
+ def forward(self, hidden_states):
400
+ identity = hidden_states
401
+ bsz, seq_len, h = hidden_states.shape
402
+ topk_idx, topk_weight, router_logits = self.gate(hidden_states)
403
+ hidden_states = hidden_states.view(-1, hidden_states.shape[-1])
404
+ flat_topk_idx = topk_idx.view(-1)
405
+ if self.training:
406
+ hidden_states = hidden_states.repeat_interleave(self.num_experts_per_tok, dim=0)
407
+ y = torch.empty_like(hidden_states)
408
+ for i, expert in enumerate(self.experts):
409
+ y[flat_topk_idx == i] = expert(hidden_states[flat_topk_idx == i])
410
+ y = (y.view(*topk_weight.shape, -1) * topk_weight.unsqueeze(-1)).sum(dim=1)
411
+ y = y.to(hidden_states.dtype).view(bsz, seq_len, h)
412
+ else:
413
+ y = self.moe_infer(hidden_states, topk_idx, topk_weight).view(bsz, seq_len, h)
414
+ if self.config.num_shared_experts is not None:
415
+ y = y + self.shared_experts(identity)
416
+ return y, (router_logits.view(bsz, seq_len, -1), topk_idx.view(bsz, seq_len, -1))
417
+
418
+ @torch.no_grad()
419
+ def moe_infer(self, x, topk_ids, topk_weight):
420
+ cnts = topk_ids.new_zeros((topk_ids.shape[0], len(self.experts)))
421
+ cnts.scatter_(1, topk_ids, 1)
422
+ tokens_per_expert = cnts.sum(dim=0)
423
+ idxs = topk_ids.view(-1).argsort()
424
+ sorted_tokens = x[idxs // topk_ids.shape[1]]
425
+ sorted_tokens_shape = sorted_tokens.shape
426
+ tokens_per_expert = tokens_per_expert.cpu().numpy()
427
+ outputs = []
428
+ start_idx = 0
429
+ for i, num_tokens in enumerate(tokens_per_expert):
430
+ end_idx = start_idx + num_tokens
431
+ if num_tokens == 0:
432
+ continue
433
+ expert = self.experts[i]
434
+ tokens_for_this_expert = sorted_tokens[start_idx:end_idx]
435
+ expert_out = expert(tokens_for_this_expert)
436
+ outputs.append(expert_out)
437
+ start_idx = end_idx
438
+
439
+ outs = torch.cat(outputs, dim=0) if len(outputs) else sorted_tokens.new_empty(0)
440
+ new_x = torch.empty_like(outs)
441
+ new_x[idxs] = outs
442
+ final_out = (
443
+ new_x.view(*topk_ids.shape, -1)
444
+ .type(topk_weight.dtype)
445
+ .mul_(topk_weight.unsqueeze(dim=-1))
446
+ .sum(dim=1)
447
+ .type(new_x.dtype)
448
+ )
449
+ return final_out
450
+
451
+
452
+ # Copied from transformers.models.llama.modeling_llama.repeat_kv
453
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
454
+ """
455
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
456
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
457
+ """
458
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
459
+ if n_rep == 1:
460
+ return hidden_states
461
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
462
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
463
+
464
+
465
+ def init_rotary_embeddings(config, head_dim, max_position_embeddings, rope_theta):
466
+ """Shared function to initialize rotary embeddings"""
467
+ if config.rope_scaling is None:
468
+ return BailingMoeRotaryEmbedding(
469
+ head_dim,
470
+ max_position_embeddings=max_position_embeddings,
471
+ base=rope_theta,
472
+ )
473
+ else:
474
+ scaling_type = config.rope_scaling["type"]
475
+ scaling_factor = config.rope_scaling["factor"]
476
+ if scaling_type == "linear":
477
+ return BailingMoeLinearScalingRotaryEmbedding(
478
+ head_dim,
479
+ max_position_embeddings=max_position_embeddings,
480
+ scaling_factor=scaling_factor,
481
+ base=rope_theta,
482
+ )
483
+ elif scaling_type == "dynamic":
484
+ return BailingMoeDynamicNTKScalingRotaryEmbedding(
485
+ head_dim,
486
+ max_position_embeddings=max_position_embeddings,
487
+ scaling_factor=scaling_factor,
488
+ base=rope_theta,
489
+ )
490
+ elif scaling_type == "yarn":
491
+ kwargs = {
492
+ key: config.rope_scaling[key]
493
+ for key in [
494
+ "original_max_position_embeddings",
495
+ "beta_fast",
496
+ "beta_slow",
497
+ "mscale",
498
+ "mscale_all_dim",
499
+ ]
500
+ if key in config.rope_scaling
501
+ }
502
+ return BailingMoeYarnRotaryEmbedding(
503
+ head_dim,
504
+ max_position_embeddings=max_position_embeddings,
505
+ scaling_factor=scaling_factor,
506
+ base=rope_theta,
507
+ **kwargs,
508
+ )
509
+ else:
510
+ raise ValueError(f"Unknown RoPE scaling type {scaling_type}")
511
+
512
+
513
+ def build_slope_tensor(n_attention_heads: int):
514
+ """
515
+ Build a tensor of slopes for Lightning Attention-2 as described in the paper:
516
+ "Lightning Attention-2: A Free Lunch for Handling Unlimited Sequence Lengths in Large Language Models"
517
+ (https://arxiv.org/abs/2401.04658)
518
+
519
+ This function computes the slope values that control the decay rate of attention scores
520
+ based on the number of attention heads. The slopes are designed to have specific
521
+ mathematical properties that work optimally when the number of heads is a power of 2.
522
+
523
+ For non-power-of-2 head counts, a workaround is implemented to maintain similar properties.
524
+
525
+ Args:
526
+ n_attention_heads (int): Number of attention heads in the model
527
+
528
+ Returns:
529
+ torch.Tensor: A tensor of shape [n_attention_heads] containing the computed slopes
530
+
531
+ Note:
532
+ Code copied from: https://github.com/OpenNLPLab/lightning-attention/blob/d15c38529bbd5c2c82b44ddda3cac885825aa873/lightning_attn/utils/utils.py#L6
533
+ """
534
+ def get_slopes(n):
535
+ def get_slopes_power_of_2(n):
536
+ start = 2 ** (-(2 ** -(math.log2(n) - 3)))
537
+ ratio = start
538
+ return [start * ratio ** i for i in range(n)]
539
+
540
+ if math.log2(n).is_integer():
541
+ return get_slopes_power_of_2(
542
+ n) # In the paper, we only train models that have 2^a heads for some a. This function has
543
+ else: # some good properties that only occur when the input is a power of 2. To maintain that even
544
+ closest_power_of_2 = 2 ** math.floor(
545
+ math.log2(n)) # when the number of heads is not a power of 2, we use this workaround.
546
+ return (get_slopes_power_of_2(closest_power_of_2)
547
+ + get_slopes(2 * closest_power_of_2)[0::2][:n - closest_power_of_2])
548
+
549
+ slopes = torch.tensor(get_slopes(n_attention_heads), dtype=torch.float)
550
+ return slopes
551
+
552
+
553
+ class BailingMoeLinearAttention(nn.Module):
554
+ """
555
+ BailingMoeLinearAttention implements a linear attention mechanism based on Lightning Attention-2
556
+ (https://arxiv.org/abs/2401.04658) with efficient computation using flash-linear-attention operators.
557
+
558
+ The implementation leverages optimized kernels from the flash-linear-attention library
559
+ (https://github.com/fla-org/flash-linear-attention) for maximum performance.
560
+ """
561
+ def __init__(
562
+ self,
563
+ config: BailingMoeLinearConfig,
564
+ mode: str = 'chunk',
565
+ hidden_size: int = 1024,
566
+ expand_k: float = 1.0,
567
+ expand_v: float = 1.0,
568
+ head_dim: int = 128,
569
+ num_heads: int = 8,
570
+ num_kv_heads: Optional[int] = None,
571
+ feature_map: Optional[str] = None,
572
+ use_output_gate: bool = True,
573
+ gate_fn: str = 'swish',
574
+ norm_eps: float = 1e-5,
575
+ layer_idx: int = None,
576
+ num_layers: int = None,
577
+ use_low_rank: bool = False,
578
+ rotary_type: str = 'none'
579
+ ):
580
+ super().__init__()
581
+ self.mode = mode
582
+ self.hidden_size = hidden_size
583
+ self.expand_k = expand_k
584
+ self.expand_v = expand_v
585
+ self.head_dim = head_dim
586
+ self.num_heads = num_heads
587
+ self.num_kv_heads = num_kv_heads if num_kv_heads is not None else num_heads
588
+ self.num_kv_groups = self.num_heads // self.num_kv_heads
589
+ self.feature_map_fn = ACT2FN[feature_map] if feature_map is not None else None
590
+ self.use_output_gate = use_output_gate
591
+
592
+ self.key_dim = int(hidden_size * expand_k)
593
+ self.value_dim = int(hidden_size * expand_v)
594
+ self.layer_idx = layer_idx
595
+ self.num_layers = num_layers
596
+ self.max_position_embeddings = config.max_position_embeddings
597
+ self.rope_theta = config.rope_theta
598
+
599
+ assert mode in ['chunk', 'fused_chunk', 'parallel', 'fused_recurrent'], f"Not suppoerted mode `{mode}`."
600
+ assert self.key_dim % num_heads == 0, f"key dim must be divisible by num_heads of {num_heads}"
601
+ assert self.value_dim % num_heads == 0, f"value dim must be divisible by num_heads of {num_heads}"
602
+
603
+ if self.head_dim is not None:
604
+ self.head_qk_dim = self.head_dim
605
+ self.head_v_dim = self.head_dim
606
+ else:
607
+ self.head_qk_dim = self.key_dim // num_heads
608
+ self.head_v_dim = self.value_dim // num_heads
609
+
610
+ self.query_key_value = nn.Linear(
611
+ hidden_size,
612
+ self.num_heads * self.head_qk_dim + self.num_kv_heads * self.head_qk_dim + self.num_kv_heads * self.head_v_dim,
613
+ bias=False
614
+ )
615
+ if self.use_output_gate:
616
+ if use_low_rank:
617
+ self.g_proj = nn.Sequential(
618
+ nn.Linear(hidden_size, self.head_qk_dim, bias=False),
619
+ nn.Linear(self.head_qk_dim, self.num_heads * self.head_v_dim, bias=False),
620
+ )
621
+ else:
622
+ self.g_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_v_dim, bias=False)
623
+ self.rotary_emb = init_rotary_embeddings(config, self.head_qk_dim, self.max_position_embeddings, self.rope_theta)
624
+
625
+ self.linear_rope = config.linear_rope
626
+ self.use_linear_silu = config.use_linear_silu
627
+ self.rotary_type = rotary_type
628
+ self.dense = nn.Linear(self.num_heads * self.head_v_dim, hidden_size, bias=False)
629
+
630
+ self.g_norm = BailingMoeRMSNorm(hidden_size=self.num_heads * self.head_v_dim, eps=norm_eps)
631
+ self.gate_fn = ACT2FN[gate_fn]
632
+ self.linear_scale = None
633
+ self.lightning_attn_ops = {
634
+ 'fused_recurrent': fused_recurrent_simple_gla,
635
+ 'chunk': chunk_simple_gla
636
+ }
637
+
638
+ def forward(
639
+ self,
640
+ hidden_states: torch.Tensor, # [b, s, h]
641
+ attention_mask: Optional[torch.Tensor] = None, # [b, s]
642
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
643
+ position_ids=None,
644
+ use_cache: Optional[bool] = False,
645
+ output_attentions: Optional[bool] = False,
646
+ **kwargs
647
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Cache]]:
648
+ if attention_mask is not None:
649
+ assert len(attention_mask.shape) == 2, (
650
+ "Expected attention_mask as a 0-1 matrix with shape [batch_size, seq_len] "
651
+ "for padding purposes (0 indicating padding). "
652
+ "Arbitrary attention masks of shape [batch_size, seq_len, seq_len] are not allowed."
653
+ )
654
+
655
+ # launching the triton kernel for just one token will actually be slower
656
+ mode = 'fused_recurrent' if hidden_states.shape[1] <= 64 else self.mode
657
+
658
+ # Currently output_attentions can only be False, returning attention weights is not supported
659
+ assert not output_attentions, "output_attentions can only be False, returning attention weights is not supported"
660
+
661
+ qkv = self.query_key_value(hidden_states)
662
+ if self.use_linear_silu:
663
+ qkv = F.silu(qkv)
664
+ q, k, v = torch.split(qkv, [
665
+ self.num_heads * self.head_qk_dim,
666
+ self.num_kv_heads * self.head_qk_dim,
667
+ self.num_kv_heads * self.head_v_dim
668
+ ], dim=-1)
669
+ device = hidden_states.device
670
+
671
+ recurrent_state = None
672
+ if past_key_value is not None and isinstance(past_key_value, Cache):
673
+ # ensure the cache list is long enough
674
+ while len(past_key_value.key_cache) <= self.layer_idx:
675
+ past_key_value.key_cache.append(None)
676
+ past_key_value.value_cache.append(None)
677
+
678
+ # check if there is a state for this layer
679
+ if past_key_value.key_cache[self.layer_idx] is not None:
680
+ recurrent_state = past_key_value.key_cache[self.layer_idx]
681
+ # ensure recurrent_state is on the same device as hidden_states
682
+ if recurrent_state.device != hidden_states.device:
683
+ recurrent_state = recurrent_state.to(device).contiguous()
684
+
685
+ if recurrent_state is None:
686
+ # dealing with left-padding
687
+ if attention_mask is not None and use_cache:
688
+ v = v.mul_(attention_mask[:, -v.shape[-2]:, None])
689
+
690
+ q = rearrange(q, '... (h d) -> ... h d', h=self.num_heads)
691
+ k = rearrange(k, '... (h d) -> ... h d', h=self.num_kv_heads)
692
+
693
+ rotary_cos, rotary_sin = self.rotary_emb(hidden_states, seq_len=position_ids.max() + 1)
694
+ rotary_emb = (rotary_cos, rotary_sin)
695
+
696
+ if self.linear_rope:
697
+ if self.rotary_type in ['full-1d']:
698
+ (cos, sin) = rotary_emb
699
+ # Support fot multi GPU inference
700
+ if cos.device != hidden_states.device:
701
+ cos = cos.to(hidden_states.device)
702
+ sin = sin.to(hidden_states.device)
703
+
704
+ q, k = apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=2)
705
+ q = q.to(v.dtype)
706
+ k = k.to(v.dtype)
707
+ else:
708
+ raise ValueError(f"Unsupported rotary type: {self.rotary_type}")
709
+
710
+ if self.num_kv_groups > 1:
711
+ k = repeat(k, 'b t h d -> b t (h g) d', h=self.num_kv_heads, g=self.num_kv_groups)
712
+ v = repeat(v, 'b t (h d) -> b t (h g) d', h=self.num_kv_heads, g=self.num_kv_groups)
713
+ else:
714
+ v = rearrange(v, 'b t (h d) -> b t h d', h=self.num_kv_heads)
715
+
716
+ H = q.shape[2]
717
+ s = -build_slope_tensor(H) * (1 - self.layer_idx / (self.num_layers - 1) + 1e-5)
718
+ g = s[None, None, :].expand(q.shape[0], q.shape[1], q.shape[2]).contiguous()
719
+
720
+ q = q.to(device)
721
+ k = k.to(device)
722
+ v = v.to(device)
723
+ g = g.to(device)
724
+
725
+ if mode in self.lightning_attn_ops:
726
+ o, recurrent_state = self.lightning_attn_ops[mode](
727
+ q=q,
728
+ k=k,
729
+ v=v,
730
+ g=g,
731
+ scale=self.linear_scale,
732
+ initial_state=recurrent_state,
733
+ output_final_state=use_cache,
734
+ head_first=False
735
+ )
736
+ else:
737
+ raise NotImplementedError(f"Not supported mode `{mode}`.")
738
+ o = o.to(hidden_states.dtype)
739
+ o = rearrange(o, 'b t h d -> b t (h d)')
740
+ o = self.g_norm(o)
741
+ g = self.g_proj(hidden_states)
742
+ o = o * F.sigmoid(g)
743
+ o = self.dense(o)
744
+
745
+ # update DynamicCache
746
+ if use_cache and past_key_value is not None and isinstance(past_key_value, Cache):
747
+ target_device = None
748
+ for cache in past_key_value.key_cache:
749
+ if cache is not None:
750
+ target_device = cache.device
751
+ break
752
+ if target_device is None:
753
+ target_device = recurrent_state.device
754
+
755
+ # move to target device
756
+ if recurrent_state.device != target_device:
757
+ recurrent_state = recurrent_state.to(target_device)
758
+
759
+ past_key_value.key_cache[self.layer_idx] = recurrent_state
760
+ past_key_value.value_cache[self.layer_idx] = None
761
+
762
+ if self.layer_idx == 0:
763
+ # update seen_tokens
764
+ past_key_value._seen_tokens += hidden_states.shape[1]
765
+
766
+ if not output_attentions:
767
+ attn_weights = None
768
+ return o, attn_weights, past_key_value
769
+
770
+
771
+ # Copied from transformers.models.llama.modeling_llama.LlamaAttention with Llama->BailingMoe
772
+ class BailingMoeAttention(nn.Module):
773
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
774
+
775
+ def __init__(self, config: BailingMoeLinearConfig, layer_idx: Optional[int] = None):
776
+ super().__init__()
777
+ self.config = config
778
+ self.layer_idx = layer_idx
779
+ if layer_idx is None:
780
+ logger.warning_once(
781
+ f"Instantiating {self.__class__.__name__} without passing `layer_idx` is not recommended and will "
782
+ "to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` "
783
+ "when creating this class."
784
+ )
785
+
786
+ self.attention_dropout = config.attention_dropout
787
+ self.hidden_size = config.hidden_size
788
+ self.num_heads = config.num_attention_heads
789
+ self.head_dim = config.head_dim or self.hidden_size // self.num_heads
790
+ self.num_key_value_heads = config.num_key_value_heads
791
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
792
+ self.max_position_embeddings = config.max_position_embeddings
793
+ self.rope_theta = config.rope_theta
794
+ self.is_causal = True
795
+
796
+ self.query_key_value = nn.Linear(
797
+ self.hidden_size,
798
+ (self.num_heads + 2 * self.num_key_value_heads) * self.head_dim,
799
+ bias=config.use_qkv_bias,
800
+ )
801
+ self.dense = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=config.use_bias)
802
+ self.rotary_emb = init_rotary_embeddings(config, self.head_dim, self.max_position_embeddings, self.rope_theta)
803
+
804
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
805
+ return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
806
+
807
+ def forward(
808
+ self,
809
+ hidden_states: torch.Tensor,
810
+ attention_mask: Optional[torch.Tensor] = None,
811
+ position_ids: Optional[torch.LongTensor] = None,
812
+ past_key_value: Optional[Cache] = None,
813
+ output_attentions: bool = False,
814
+ use_cache: bool = False,
815
+ **kwargs,
816
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
817
+ if "padding_mask" in kwargs:
818
+ warnings.warn(
819
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
820
+ )
821
+
822
+ bsz, q_len, _ = hidden_states.size()
823
+
824
+ qkv = self.query_key_value(hidden_states)
825
+ qkv = qkv.view(bsz, q_len, self.num_heads + 2 * self.num_key_value_heads, self.head_dim)
826
+
827
+ query_states, key_states, value_states = qkv.split(
828
+ [self.num_heads, self.num_key_value_heads, self.num_key_value_heads], dim=-2
829
+ )
830
+ query_states = query_states.transpose(1, 2)
831
+ key_states = key_states.transpose(1, 2)
832
+ value_states = value_states.transpose(1, 2)
833
+
834
+ kv_seq_len = key_states.shape[-2]
835
+ if past_key_value is not None:
836
+ if self.layer_idx is None:
837
+ raise ValueError(
838
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
839
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
840
+ "with a layer index."
841
+ )
842
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
843
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
844
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
845
+
846
+ if past_key_value is not None:
847
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
848
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
849
+
850
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
851
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
852
+
853
+ attn_weights = torch.matmul(query_states / math.sqrt(self.head_dim), key_states.transpose(2, 3))
854
+
855
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
856
+ raise ValueError(
857
+ f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
858
+ f" {attn_weights.size()}"
859
+ )
860
+
861
+ if attention_mask is not None:
862
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
863
+ raise ValueError(
864
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
865
+ )
866
+ attn_weights = attn_weights + attention_mask
867
+
868
+ # upcast attention to fp32
869
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
870
+ attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
871
+ attn_output = torch.matmul(attn_weights, value_states)
872
+
873
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
874
+ raise ValueError(
875
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
876
+ f" {attn_output.size()}"
877
+ )
878
+
879
+ attn_output = attn_output.transpose(1, 2).contiguous()
880
+
881
+ attn_output = attn_output.reshape(bsz, q_len, -1)
882
+
883
+ attn_output = self.dense(attn_output)
884
+
885
+ if not output_attentions:
886
+ attn_weights = None
887
+
888
+ return attn_output, attn_weights, past_key_value
889
+
890
+
891
+ # Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2 with Llama->BailingMoe
892
+ class BailingMoeFlashAttention2(BailingMoeAttention):
893
+ """
894
+ BailingMoe flash attention module. This module inherits from `BailingMoeAttention` as the weights of the module stays
895
+ untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
896
+ flash attention and deal with padding tokens in case the input contains any of them.
897
+ """
898
+
899
+ def __init__(self, *args, **kwargs):
900
+ super().__init__(*args, **kwargs)
901
+
902
+ # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
903
+ # flash_attn<2.1 generates top-left aligned causal mask, while what is needed here is bottom-right alignement, that was made default for flash_attn>=2.1. This attribute is used to handle this difference. Reference: https://github.com/Dao-AILab/flash-attention/releases/tag/v2.1.0.
904
+ # Beware that with flash_attn<2.1, using q_seqlen != k_seqlen (except for the case q_seqlen == 1) produces a wrong mask (top-left).
905
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
906
+
907
+ def forward(
908
+ self,
909
+ hidden_states: torch.Tensor,
910
+ attention_mask: Optional[torch.LongTensor] = None,
911
+ position_ids: Optional[torch.LongTensor] = None,
912
+ past_key_value: Optional[Cache] = None,
913
+ output_attentions: bool = False,
914
+ use_cache: bool = False,
915
+ **kwargs,
916
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
917
+ # BailingMoeFlashAttention2 attention does not support output_attentions
918
+ if "padding_mask" in kwargs:
919
+ warnings.warn(
920
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
921
+ )
922
+
923
+ # overwrite attention_mask with padding_mask
924
+ attention_mask = kwargs.pop("padding_mask")
925
+
926
+ output_attentions = False
927
+
928
+ bsz, q_len, _ = hidden_states.size()
929
+
930
+ # Flash attention requires the input to have the shape
931
+ # batch_size x seq_length x head_dim x hidden_dim
932
+ # therefore we just need to keep the original shape
933
+
934
+ qkv = self.query_key_value(hidden_states)
935
+ qkv = qkv.view(bsz, q_len, self.num_heads + 2 * self.num_key_value_heads, self.head_dim)
936
+
937
+ query_states, key_states, value_states = qkv.split(
938
+ [self.num_heads, self.num_key_value_heads, self.num_key_value_heads], dim=-2
939
+ )
940
+ query_states = query_states.transpose(1, 2)
941
+ key_states = key_states.transpose(1, 2)
942
+ value_states = value_states.transpose(1, 2)
943
+
944
+ kv_seq_len = key_states.shape[-2]
945
+ if past_key_value is not None:
946
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
947
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
948
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
949
+
950
+ if past_key_value is not None:
951
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
952
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
953
+
954
+ # TODO: These transpose are quite inefficient but Flash Attention requires the layout [batch_size, sequence_length, num_heads, head_dim]. We would need to refactor the KV cache
955
+ # to be able to avoid many of these transpose/reshape/view.
956
+ query_states = query_states.transpose(1, 2)
957
+ key_states = key_states.transpose(1, 2)
958
+ value_states = value_states.transpose(1, 2)
959
+
960
+ dropout_rate = self.attention_dropout if self.training else 0.0
961
+
962
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
963
+ # therefore the input hidden states gets silently cast in float32. Hence, we need
964
+ # cast them back in the correct dtype just to be sure everything works as expected.
965
+ # This might slow down training & inference so it is recommended to not cast the LayerNorms
966
+ # in fp32. (BailingMoeRMSNorm handles it correctly)
967
+
968
+ input_dtype = query_states.dtype
969
+ if input_dtype == torch.float32:
970
+ # Handle the case where the model is quantized
971
+ if hasattr(self.config, "_pre_quantization_dtype"):
972
+ target_dtype = self.config._pre_quantization_dtype
973
+ elif torch.is_autocast_enabled():
974
+ target_dtype = torch.get_autocast_gpu_dtype()
975
+ else:
976
+ target_dtype = self.q_proj.weight.dtype
977
+
978
+ logger.warning_once(
979
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
980
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
981
+ f" {target_dtype}."
982
+ )
983
+
984
+ query_states = query_states.to(target_dtype)
985
+ key_states = key_states.to(target_dtype)
986
+ value_states = value_states.to(target_dtype)
987
+
988
+ attn_output = self._flash_attention_forward(
989
+ query_states, key_states, value_states, attention_mask, q_len, dropout=dropout_rate
990
+ )
991
+
992
+ attn_output = attn_output.reshape(bsz, q_len, -1).contiguous()
993
+ attn_output = self.dense(attn_output)
994
+
995
+ if not output_attentions:
996
+ attn_weights = None
997
+
998
+ return attn_output, attn_weights, past_key_value
999
+
1000
+ def _flash_attention_forward(
1001
+ self, query_states, key_states, value_states, attention_mask, query_length, dropout=0.0, softmax_scale=None
1002
+ ):
1003
+ """
1004
+ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
1005
+ first unpad the input, then computes the attention scores and pad the final attention scores.
1006
+
1007
+ Args:
1008
+ query_states (`torch.Tensor`):
1009
+ Input query states to be passed to Flash Attention API
1010
+ key_states (`torch.Tensor`):
1011
+ Input key states to be passed to Flash Attention API
1012
+ value_states (`torch.Tensor`):
1013
+ Input value states to be passed to Flash Attention API
1014
+ attention_mask (`torch.Tensor`):
1015
+ The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
1016
+ position of padding tokens and 1 for the position of non-padding tokens.
1017
+ dropout (`int`, *optional*):
1018
+ Attention dropout
1019
+ softmax_scale (`float`, *optional*):
1020
+ The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
1021
+ query_length (`int`):
1022
+ The length of the query sequence in terms of tokens. This represents the number of tokens in the
1023
+ `query_states` tensor along the sequence dimension. It is used to determine the effective sequence
1024
+ length for attention computations.
1025
+ """
1026
+ if not self._flash_attn_uses_top_left_mask:
1027
+ causal = self.is_causal
1028
+ else:
1029
+ # TODO: Remove the `query_length != 1` check once Flash Attention for RoCm is bumped to 2.1. For details, please see the comment in BailingMoeFlashAttention2 __init__.
1030
+ causal = self.is_causal and query_length != 1
1031
+
1032
+ # Contains at least one padding token in the sequence
1033
+ if attention_mask is not None:
1034
+ batch_size = query_states.shape[0]
1035
+ query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._upad_input(
1036
+ query_states, key_states, value_states, attention_mask, query_length
1037
+ )
1038
+
1039
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
1040
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
1041
+
1042
+ attn_output_unpad = flash_attn_varlen_func(
1043
+ query_states,
1044
+ key_states,
1045
+ value_states,
1046
+ cu_seqlens_q=cu_seqlens_q,
1047
+ cu_seqlens_k=cu_seqlens_k,
1048
+ max_seqlen_q=max_seqlen_in_batch_q,
1049
+ max_seqlen_k=max_seqlen_in_batch_k,
1050
+ dropout_p=dropout,
1051
+ softmax_scale=softmax_scale,
1052
+ causal=causal,
1053
+ )
1054
+
1055
+ attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length)
1056
+ else:
1057
+ attn_output = flash_attn_func(
1058
+ query_states, key_states, value_states, dropout, softmax_scale=softmax_scale, causal=causal
1059
+ )
1060
+
1061
+ return attn_output
1062
+
1063
+ def _upad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length):
1064
+ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
1065
+ batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape
1066
+
1067
+ key_layer = index_first_axis(
1068
+ key_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
1069
+ )
1070
+ value_layer = index_first_axis(
1071
+ value_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
1072
+ )
1073
+ if query_length == kv_seq_len:
1074
+ query_layer = index_first_axis(
1075
+ query_layer.reshape(batch_size * kv_seq_len, self.num_heads, head_dim), indices_k
1076
+ )
1077
+ cu_seqlens_q = cu_seqlens_k
1078
+ max_seqlen_in_batch_q = max_seqlen_in_batch_k
1079
+ indices_q = indices_k
1080
+ elif query_length == 1:
1081
+ max_seqlen_in_batch_q = 1
1082
+ cu_seqlens_q = torch.arange(
1083
+ batch_size + 1, dtype=torch.int32, device=query_layer.device
1084
+ ) # There is a memcpy here, that is very bad.
1085
+ indices_q = cu_seqlens_q[:-1]
1086
+ query_layer = query_layer.squeeze(1)
1087
+ else:
1088
+ # The -q_len: slice assumes left padding.
1089
+ attention_mask = attention_mask[:, -query_length:]
1090
+ query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, attention_mask)
1091
+
1092
+ return (
1093
+ query_layer,
1094
+ key_layer,
1095
+ value_layer,
1096
+ indices_q,
1097
+ (cu_seqlens_q, cu_seqlens_k),
1098
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
1099
+ )
1100
+
1101
+
1102
+ # Copied from transformers.models.llama.modeling_llama.LlamaSdpaAttention with Llama->BailingMoe
1103
+ class BailingMoeSdpaAttention(BailingMoeAttention):
1104
+ """
1105
+ BailingMoe attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
1106
+ `BailingMoeAttention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
1107
+ SDPA API.
1108
+ """
1109
+
1110
+ # Adapted from BailingMoeAttention.forward
1111
+ def forward(
1112
+ self,
1113
+ hidden_states: torch.Tensor,
1114
+ attention_mask: Optional[torch.Tensor] = None,
1115
+ position_ids: Optional[torch.LongTensor] = None,
1116
+ past_key_value: Optional[Cache] = None,
1117
+ output_attentions: bool = False,
1118
+ use_cache: bool = False,
1119
+ **kwargs,
1120
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
1121
+ if output_attentions:
1122
+ # TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented.
1123
+ logger.warning_once(
1124
+ "BailingMoeLinearModel is using BailingMoeSdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to the manual attention implementation, "
1125
+ 'but specifying the manual implementation will be required from Transformers version v5.0.0 onwards. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.'
1126
+ )
1127
+ return super().forward(
1128
+ hidden_states=hidden_states,
1129
+ attention_mask=attention_mask,
1130
+ position_ids=position_ids,
1131
+ past_key_value=past_key_value,
1132
+ output_attentions=output_attentions,
1133
+ use_cache=use_cache,
1134
+ )
1135
+
1136
+ bsz, q_len, _ = hidden_states.size()
1137
+
1138
+ qkv = self.query_key_value(hidden_states)
1139
+ qkv = qkv.view(bsz, q_len, self.num_heads + 2 * self.num_key_value_heads, self.head_dim)
1140
+
1141
+ query_states, key_states, value_states = qkv.split(
1142
+ [self.num_heads, self.num_key_value_heads, self.num_key_value_heads], dim=-2
1143
+ )
1144
+ query_states = query_states.transpose(1, 2)
1145
+ key_states = key_states.transpose(1, 2)
1146
+ value_states = value_states.transpose(1, 2)
1147
+
1148
+ kv_seq_len = key_states.shape[-2]
1149
+ if past_key_value is not None:
1150
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
1151
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
1152
+
1153
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
1154
+
1155
+ if past_key_value is not None:
1156
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
1157
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
1158
+
1159
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
1160
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
1161
+
1162
+ if attention_mask is not None:
1163
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
1164
+ raise ValueError(
1165
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
1166
+ )
1167
+
1168
+ # SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with custom attn_mask,
1169
+ # Reference: https://github.com/pytorch/pytorch/issues/112577.
1170
+ if query_states.device.type == "cuda" and attention_mask is not None:
1171
+ query_states = query_states.contiguous()
1172
+ key_states = key_states.contiguous()
1173
+ value_states = value_states.contiguous()
1174
+
1175
+ attn_output = torch.nn.functional.scaled_dot_product_attention(
1176
+ query_states,
1177
+ key_states,
1178
+ value_states,
1179
+ attn_mask=attention_mask,
1180
+ dropout_p=self.attention_dropout if self.training else 0.0,
1181
+ # 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.
1182
+ is_causal=self.is_causal and attention_mask is None and q_len > 1,
1183
+ )
1184
+
1185
+ attn_output = attn_output.transpose(1, 2).contiguous()
1186
+ attn_output = attn_output.reshape(bsz, q_len, -1)
1187
+
1188
+ attn_output = self.dense(attn_output)
1189
+
1190
+ return attn_output, None, past_key_value
1191
+
1192
+
1193
+ BAILING_MOE_ATTENTION_CLASSES = {
1194
+ "eager": BailingMoeAttention,
1195
+ "flash_attention_2": BailingMoeFlashAttention2,
1196
+ "sdpa": BailingMoeSdpaAttention,
1197
+ }
1198
+
1199
+
1200
+ class BailingMoeLinearDecoderLayer(nn.Module):
1201
+ def __init__(self, config: BailingMoeLinearConfig, layer_idx: int):
1202
+ super().__init__()
1203
+ self.hidden_size = config.hidden_size
1204
+ self.layer_group_size = config.layer_group_size
1205
+
1206
+ # Use standard Attention if layer_idx+1 is divisible by layer_group_size or if layer_idx exceeds
1207
+ # the threshold (num_hidden_layers // layer_group_size * layer_group_size), otherwise use linear attention
1208
+ self.attention_layer_type = "attention" if (layer_idx + 1) % config.layer_group_size == 0 or \
1209
+ layer_idx >= config.num_hidden_layers // config.layer_group_size * config.layer_group_size else "linear_attention"
1210
+
1211
+ if self.attention_layer_type == "attention":
1212
+ self.attention = BAILING_MOE_ATTENTION_CLASSES[config._attn_implementation](config=config, layer_idx=layer_idx)
1213
+ else:
1214
+ self.head_dim = config.head_dim or config.hidden_size // config.num_attention_heads
1215
+ self.use_linear_gqa = config.use_linear_gqa
1216
+ self.linear_mode = config.linear_mode
1217
+ self.attention = BailingMoeLinearAttention(
1218
+ config=config,
1219
+ mode=self.linear_mode,
1220
+ hidden_size=self.hidden_size,
1221
+ expand_k=1,
1222
+ expand_v=1,
1223
+ head_dim=self.head_dim,
1224
+ num_heads=config.num_attention_heads,
1225
+ num_kv_heads=config.num_key_value_heads if self.use_linear_gqa else None,
1226
+ feature_map=None,
1227
+ use_output_gate=True,
1228
+ gate_fn="swish",
1229
+ norm_eps=config.rms_norm_eps,
1230
+ layer_idx=layer_idx,
1231
+ num_layers=config.num_hidden_layers,
1232
+ use_low_rank=config.use_low_rank,
1233
+ rotary_type=config.rotary_type,
1234
+ )
1235
+ self.mlp = (
1236
+ BailingMoeSparseMoeBlock(config)
1237
+ if (config.num_experts is not None and layer_idx >= config.first_k_dense_replace)
1238
+ else BailingMoeMLP(config=config, intermediate_size=config.intermediate_size)
1239
+ )
1240
+ self.layer_idx = layer_idx
1241
+ self.input_layernorm = BailingMoeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
1242
+ self.post_attention_layernorm = BailingMoeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
1243
+
1244
+ def forward(
1245
+ self,
1246
+ hidden_states: torch.Tensor,
1247
+ attention_mask: Optional[torch.Tensor] = None,
1248
+ position_ids: Optional[torch.LongTensor] = None,
1249
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
1250
+ output_attentions: Optional[bool] = False,
1251
+ output_router_logits: Optional[bool] = False,
1252
+ use_cache: Optional[bool] = False,
1253
+ **kwargs,
1254
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
1255
+ """
1256
+ Args:
1257
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
1258
+ attention_mask (`torch.FloatTensor`, *optional*):
1259
+ attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
1260
+ query_sequence_length, key_sequence_length)` if default attention is used.
1261
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1262
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
1263
+ config.n_positions - 1]`.
1264
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*):
1265
+ cached past key and value projection states
1266
+ output_attentions (`bool`, *optional*):
1267
+ Whether to return the attentions tensors of all attention layers. See `attentions` under
1268
+ returned tensors for more detail.
1269
+ output_router_logits (`bool`, *optional*):
1270
+ Whether or not to return the logits of all the routers. They are useful for computing the router loss,
1271
+ and should not be returned during inference.
1272
+ use_cache (`bool`, *optional*):
1273
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
1274
+ (see `past_key_values`).
1275
+ """
1276
+ if "padding_mask" in kwargs:
1277
+ warnings.warn(
1278
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
1279
+ )
1280
+ residual = hidden_states
1281
+ hidden_states = self.input_layernorm(hidden_states)
1282
+
1283
+ if self.attention_layer_type == "attention":
1284
+ # Self Attention
1285
+ hidden_states, self_attn_weights, present_key_value = self.attention(
1286
+ hidden_states=hidden_states,
1287
+ attention_mask=attention_mask,
1288
+ position_ids=position_ids,
1289
+ past_key_value=past_key_value,
1290
+ output_attentions=output_attentions,
1291
+ use_cache=use_cache,
1292
+ )
1293
+ else:
1294
+ # Linear Attention
1295
+ batch_size, seq_len = hidden_states.shape[0], hidden_states.shape[1]
1296
+ device = hidden_states.device
1297
+ if attention_mask is None:
1298
+ # if attention_mask is None, create a full mask
1299
+ attention_mask = torch.ones((batch_size, seq_len), dtype=torch.int32, device=device)
1300
+ elif attention_mask.dim() == 0:
1301
+ mask_value = attention_mask.item()
1302
+ attention_mask = torch.full((batch_size, seq_len), mask_value, dtype=torch.int32, device=device)
1303
+ elif attention_mask.dim() == 4 and attention_mask.shape[1] == 1:
1304
+ attention_mask = attention_mask[:, 0, -1, :].to(torch.int32)
1305
+ # the attention mask is additive mask, which means the masked position is a large negative number, and the unmasked position is 0
1306
+ attention_mask = (attention_mask > -1e4).to(torch.int32)
1307
+ else:
1308
+ raise ValueError(f"Unsupported mask dimension: {attention_mask.shape}")
1309
+
1310
+ hidden_states, self_attn_weights, present_key_value = self.attention(
1311
+ hidden_states=hidden_states,
1312
+ attention_mask=attention_mask,
1313
+ past_key_value=past_key_value,
1314
+ position_ids=position_ids,
1315
+ use_cache=use_cache,
1316
+ output_attentions=output_attentions,
1317
+ )
1318
+
1319
+ hidden_states = residual + hidden_states
1320
+
1321
+ # Fully Connected
1322
+ residual = hidden_states
1323
+ hidden_states = self.post_attention_layernorm(hidden_states)
1324
+ hidden_states = self.mlp(hidden_states)
1325
+
1326
+ if isinstance(hidden_states, tuple):
1327
+ hidden_states, router_logits = hidden_states
1328
+ else:
1329
+ router_logits = None
1330
+ hidden_states = residual + hidden_states
1331
+
1332
+ outputs = (hidden_states,)
1333
+
1334
+ if output_attentions:
1335
+ outputs += (self_attn_weights,)
1336
+
1337
+ if use_cache:
1338
+ outputs += (present_key_value,)
1339
+
1340
+ if output_router_logits:
1341
+ outputs += (router_logits,)
1342
+
1343
+ return outputs
1344
+
1345
+
1346
+ BAILINGMOELINEAR_START_DOCSTRING = r"""
1347
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
1348
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
1349
+ etc.)
1350
+
1351
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
1352
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
1353
+ and behavior.
1354
+
1355
+ Parameters:
1356
+ config ([`BailingMoeLinearConfig`]):
1357
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
1358
+ load the weights associated with the model, only the configuration. Check out the
1359
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
1360
+ """
1361
+
1362
+
1363
+ @add_start_docstrings(
1364
+ "The bare BailingMoeLinear Model outputting raw hidden-states without any specific head on top.",
1365
+ BAILINGMOELINEAR_START_DOCSTRING,
1366
+ )
1367
+ class BailingMoeLinearPreTrainedModel(PreTrainedModel):
1368
+ config_class = BailingMoeLinearConfig
1369
+ base_model_prefix = "model"
1370
+ supports_gradient_checkpointing = True
1371
+ _no_split_modules = ["BailingMoeLinearDecoderLayer"]
1372
+ _skip_keys_device_placement = "past_key_values"
1373
+ _supports_flash_attn_2 = True
1374
+ _supports_sdpa = True
1375
+ _supports_cache_class = True
1376
+
1377
+ def _init_weights(self, module):
1378
+ std = self.config.initializer_range
1379
+ if isinstance(module, nn.Linear):
1380
+ module.weight.data.normal_(mean=0.0, std=std)
1381
+ if module.bias is not None:
1382
+ module.bias.data.zero_()
1383
+ elif isinstance(module, nn.Embedding):
1384
+ module.weight.data.normal_(mean=0.0, std=std)
1385
+ if module.padding_idx is not None:
1386
+ module.weight.data[module.padding_idx].zero_()
1387
+
1388
+
1389
+ BAILINGMOE_INPUTS_DOCSTRING = r"""
1390
+ Args:
1391
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
1392
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
1393
+ it.
1394
+
1395
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1396
+ [`PreTrainedTokenizer.__call__`] for details.
1397
+
1398
+ [What are input IDs?](../glossary#input-ids)
1399
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
1400
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
1401
+
1402
+ - 1 for tokens that are **not masked**,
1403
+ - 0 for tokens that are **masked**.
1404
+
1405
+ [What are attention masks?](../glossary#attention-mask)
1406
+
1407
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1408
+ [`PreTrainedTokenizer.__call__`] for details.
1409
+
1410
+ If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
1411
+ `past_key_values`).
1412
+
1413
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
1414
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
1415
+ information on the default strategy.
1416
+
1417
+ - 1 indicates the head is **not masked**,
1418
+ - 0 indicates the head is **masked**.
1419
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1420
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
1421
+ config.n_positions - 1]`.
1422
+
1423
+ [What are position IDs?](../glossary#position-ids)
1424
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
1425
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
1426
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
1427
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
1428
+
1429
+ Two formats are allowed:
1430
+ - a [`~cache_utils.Cache`] instance;
1431
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
1432
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
1433
+ cache format.
1434
+
1435
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
1436
+ legacy cache format will be returned.
1437
+
1438
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
1439
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
1440
+ of shape `(batch_size, sequence_length)`.
1441
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
1442
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
1443
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
1444
+ model's internal embedding lookup matrix.
1445
+ use_cache (`bool`, *optional*):
1446
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
1447
+ `past_key_values`).
1448
+ output_attentions (`bool`, *optional*):
1449
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
1450
+ tensors for more detail.
1451
+ output_hidden_states (`bool`, *optional*):
1452
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
1453
+ more detail.
1454
+ return_dict (`bool`, *optional*):
1455
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
1456
+ """
1457
+
1458
+
1459
+ @add_start_docstrings(
1460
+ "The bare BailingMoeLinear Model outputting raw hidden-states without any specific head on top.",
1461
+ BAILINGMOELINEAR_START_DOCSTRING,
1462
+ )
1463
+ class BailingMoeLinearModel(BailingMoeLinearPreTrainedModel):
1464
+ """
1465
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`BailingMoeLinearDecoderLayer`]
1466
+
1467
+ Args:
1468
+ config: BailingMoeLinearConfig
1469
+ """
1470
+
1471
+ def __init__(self, config: BailingMoeLinearConfig):
1472
+ super().__init__(config)
1473
+ self.padding_idx = config.pad_token_id
1474
+ self.vocab_size = config.vocab_size
1475
+
1476
+ self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
1477
+ self.layers = nn.ModuleList(
1478
+ [BailingMoeLinearDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
1479
+ )
1480
+
1481
+ # find a standard Attention layer_idx for later sequence length calculation
1482
+ self.standard_attn_layer_idx = 0
1483
+ for layer_idx, layer in enumerate(self.layers):
1484
+ if hasattr(layer, 'attention_layer_type') and layer.attention_layer_type == "attention":
1485
+ self.standard_attn_layer_idx = layer_idx
1486
+ break
1487
+
1488
+ self._use_sdpa = config._attn_implementation == "sdpa"
1489
+ self._use_flash_attention_2 = config._attn_implementation == "flash_attention_2"
1490
+ self.norm = BailingMoeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
1491
+
1492
+ self.gradient_checkpointing = False
1493
+ # Initialize weights and apply final processing
1494
+ self.post_init()
1495
+
1496
+ def get_input_embeddings(self):
1497
+ return self.word_embeddings
1498
+
1499
+ def set_input_embeddings(self, value):
1500
+ self.word_embeddings = value
1501
+
1502
+ @add_start_docstrings_to_model_forward(BAILINGMOE_INPUTS_DOCSTRING)
1503
+ def forward(
1504
+ self,
1505
+ input_ids: torch.LongTensor = None,
1506
+ attention_mask: Optional[torch.Tensor] = None,
1507
+ position_ids: Optional[torch.LongTensor] = None,
1508
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1509
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1510
+ use_cache: Optional[bool] = None,
1511
+ output_attentions: Optional[bool] = None,
1512
+ output_hidden_states: Optional[bool] = None,
1513
+ output_router_logits: Optional[bool] = None,
1514
+ return_dict: Optional[bool] = None,
1515
+ **kwargs,
1516
+ ) -> Union[Tuple, MoeModelOutputWithPast]:
1517
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1518
+ output_hidden_states = (
1519
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1520
+ )
1521
+ output_router_logits = (
1522
+ output_router_logits if output_router_logits is not None else self.config.output_router_logits
1523
+ )
1524
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1525
+
1526
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1527
+
1528
+ # retrieve input_ids and inputs_embeds
1529
+ if input_ids is not None and inputs_embeds is not None:
1530
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
1531
+ elif input_ids is not None:
1532
+ batch_size, seq_length = input_ids.shape[:2]
1533
+ elif inputs_embeds is not None:
1534
+ batch_size, seq_length = inputs_embeds.shape[:2]
1535
+ else:
1536
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
1537
+
1538
+ if self.gradient_checkpointing and self.training:
1539
+ if use_cache:
1540
+ logger.warning_once(
1541
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`transformers."
1542
+ )
1543
+ use_cache = False
1544
+
1545
+ past_key_values_length = 0
1546
+
1547
+ if use_cache:
1548
+ use_legacy_cache = not isinstance(past_key_values, Cache)
1549
+ if use_legacy_cache:
1550
+ past_key_values = DynamicCache.from_legacy_cache(past_key_values)
1551
+ past_key_values_length = past_key_values.get_usable_length(seq_length, layer_idx=self.standard_attn_layer_idx)
1552
+
1553
+ if position_ids is None:
1554
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
1555
+ position_ids = torch.arange(
1556
+ past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
1557
+ )
1558
+ position_ids = position_ids.unsqueeze(0)
1559
+
1560
+ if inputs_embeds is None:
1561
+ inputs_embeds = self.word_embeddings(input_ids)
1562
+
1563
+ if self._use_flash_attention_2:
1564
+ # 2d mask is passed through the layers
1565
+ attention_mask = attention_mask if (attention_mask is not None and 0 in attention_mask) else None
1566
+ elif self._use_sdpa and not output_attentions:
1567
+ # output_attentions=True can not be supported when using SDPA, and we fall back on
1568
+ # the manual implementation that requires a 4D causal mask in all cases.
1569
+ attention_mask = _prepare_4d_causal_attention_mask_for_sdpa(
1570
+ attention_mask,
1571
+ (batch_size, seq_length),
1572
+ inputs_embeds,
1573
+ past_key_values_length,
1574
+ )
1575
+ else:
1576
+ # 4d mask is passed through the layers
1577
+ attention_mask = _prepare_4d_causal_attention_mask(
1578
+ attention_mask, (batch_size, seq_length), inputs_embeds, past_key_values_length
1579
+ )
1580
+
1581
+ # embed positions
1582
+ hidden_states = inputs_embeds
1583
+
1584
+ # decoder layers
1585
+ all_hidden_states = () if output_hidden_states else None
1586
+ all_self_attns = () if output_attentions else None
1587
+ all_router_logits = () if output_router_logits else None
1588
+ next_decoder_cache = None
1589
+
1590
+ for decoder_layer in self.layers:
1591
+ if output_hidden_states:
1592
+ all_hidden_states += (hidden_states,)
1593
+
1594
+ if self.gradient_checkpointing and self.training:
1595
+ layer_outputs = self._gradient_checkpointing_func(
1596
+ decoder_layer.__call__,
1597
+ hidden_states,
1598
+ attention_mask,
1599
+ position_ids,
1600
+ past_key_values,
1601
+ output_attentions,
1602
+ output_router_logits,
1603
+ use_cache,
1604
+ )
1605
+ else:
1606
+ layer_outputs = decoder_layer(
1607
+ hidden_states,
1608
+ attention_mask=attention_mask,
1609
+ position_ids=position_ids,
1610
+ past_key_value=past_key_values,
1611
+ output_attentions=output_attentions,
1612
+ output_router_logits=output_router_logits,
1613
+ use_cache=use_cache,
1614
+ )
1615
+ hidden_states = layer_outputs[0]
1616
+
1617
+ if use_cache:
1618
+ next_decoder_cache = layer_outputs[2 if output_attentions else 1]
1619
+
1620
+ if output_attentions:
1621
+ all_self_attns += (layer_outputs[1],)
1622
+
1623
+ if output_router_logits and layer_outputs[-1] is not None:
1624
+ all_router_logits += (layer_outputs[-1],)
1625
+
1626
+ hidden_states = self.norm(hidden_states)
1627
+
1628
+ # add hidden states from the last decoder layer
1629
+ if output_hidden_states:
1630
+ all_hidden_states += (hidden_states,)
1631
+
1632
+ next_cache = None
1633
+ if use_cache:
1634
+ next_cache = next_decoder_cache.to_legacy_cache() if use_legacy_cache else next_decoder_cache
1635
+ if not return_dict:
1636
+ return tuple(
1637
+ v
1638
+ for v in [hidden_states, next_cache, all_hidden_states, all_self_attns, all_router_logits]
1639
+ if v is not None
1640
+ )
1641
+ return MoeModelOutputWithPast(
1642
+ last_hidden_state=hidden_states,
1643
+ past_key_values=next_cache,
1644
+ hidden_states=all_hidden_states,
1645
+ attentions=all_self_attns,
1646
+ router_logits=all_router_logits,
1647
+ )
1648
+
1649
+
1650
+ class BailingMoeLinearForCausalLM(BailingMoeLinearPreTrainedModel):
1651
+ _tied_weights_keys = ["lm_head.weight"]
1652
+
1653
+ def __init__(self, config: BailingMoeLinearConfig):
1654
+ super().__init__(config)
1655
+ self.model = BailingMoeLinearModel(config)
1656
+ self.vocab_size = config.vocab_size
1657
+ self.norm_head = config.norm_head
1658
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1659
+ self.standard_attn_layer_idx = self.model.standard_attn_layer_idx
1660
+
1661
+ # Initialize weights and apply final processing
1662
+ self.post_init()
1663
+
1664
+ def get_input_embeddings(self):
1665
+ return self.model.word_embeddings
1666
+
1667
+ def set_input_embeddings(self, value):
1668
+ self.model.word_embeddings = value
1669
+
1670
+ def get_output_embeddings(self):
1671
+ return self.lm_head
1672
+
1673
+ def set_output_embeddings(self, new_embeddings):
1674
+ self.lm_head = new_embeddings
1675
+
1676
+ def set_decoder(self, decoder):
1677
+ self.model = decoder
1678
+
1679
+ def get_decoder(self):
1680
+ return self.model
1681
+
1682
+ def compute_logit(self, hidden_states):
1683
+ if self.norm_head:
1684
+ if self.training:
1685
+ norm_weight = (
1686
+ self.lm_head.weight / (torch.norm(self.lm_head.weight, p=2, dim=0, keepdim=True) + 1e-7).detach()
1687
+ )
1688
+ logits = F.linear(hidden_states, norm_weight, None)
1689
+ else:
1690
+ self.lm_head.weight.data = (
1691
+ self.lm_head.weight.data.float()
1692
+ / (torch.norm(self.lm_head.weight.data.float(), p=2, dim=0, keepdim=True) + 1e-7)
1693
+ ).to(hidden_states.dtype)
1694
+ logits = F.linear(hidden_states, self.lm_head.weight.data, None)
1695
+ self.norm_head = False
1696
+ else:
1697
+ logits = self.lm_head(hidden_states)
1698
+ return logits
1699
+
1700
+ @add_start_docstrings_to_model_forward(BAILINGMOE_INPUTS_DOCSTRING)
1701
+ @replace_return_docstrings(output_type=MoeCausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
1702
+ def forward(
1703
+ self,
1704
+ input_ids: torch.LongTensor = None,
1705
+ attention_mask: Optional[torch.Tensor] = None,
1706
+ position_ids: Optional[torch.LongTensor] = None,
1707
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1708
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1709
+ labels: Optional[torch.LongTensor] = None,
1710
+ use_cache: Optional[bool] = None,
1711
+ output_attentions: Optional[bool] = None,
1712
+ output_hidden_states: Optional[bool] = None,
1713
+ output_router_logits: Optional[bool] = None,
1714
+ return_dict: Optional[bool] = None,
1715
+ **kwargs,
1716
+ ) -> Union[Tuple, MoeCausalLMOutputWithPast]:
1717
+ r"""
1718
+ Args:
1719
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1720
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1721
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1722
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1723
+
1724
+ Returns:
1725
+
1726
+ Example:
1727
+
1728
+ ```python
1729
+ >>> from transformers import AutoTokenizer
1730
+
1731
+ >>> model = BailingMoeForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
1732
+ >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
1733
+
1734
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
1735
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1736
+
1737
+ >>> # Generate
1738
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1739
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1740
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
1741
+ ```"""
1742
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1743
+ output_hidden_states = (
1744
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1745
+ )
1746
+ output_router_logits = (
1747
+ output_router_logits if output_router_logits is not None else self.config.output_router_logits
1748
+ )
1749
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1750
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1751
+ outputs = self.model(
1752
+ input_ids=input_ids,
1753
+ attention_mask=attention_mask,
1754
+ position_ids=position_ids,
1755
+ past_key_values=past_key_values,
1756
+ inputs_embeds=inputs_embeds,
1757
+ use_cache=use_cache,
1758
+ output_attentions=output_attentions,
1759
+ output_hidden_states=output_hidden_states,
1760
+ output_router_logits=output_router_logits,
1761
+ return_dict=return_dict,
1762
+ **kwargs,
1763
+ )
1764
+
1765
+ hidden_states = outputs[0]
1766
+
1767
+ logits = self.compute_logit(hidden_states=hidden_states)
1768
+ logits = logits.float()
1769
+
1770
+ loss = None
1771
+ aux_loss = None
1772
+
1773
+ if labels is not None:
1774
+ # Shift so that tokens < n predict n
1775
+ shift_logits = logits[..., :-1, :].contiguous()
1776
+ shift_labels = labels[..., 1:].contiguous()
1777
+ # Flatten the tokens
1778
+ loss_fct = CrossEntropyLoss()
1779
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1780
+ shift_labels = shift_labels.view(-1)
1781
+ # Enable model parallelism
1782
+ shift_labels = shift_labels.to(shift_logits.device)
1783
+ loss = loss_fct(shift_logits, shift_labels)
1784
+
1785
+ if not return_dict:
1786
+ output = (logits,) + outputs[1:]
1787
+ if output_router_logits:
1788
+ output = (aux_loss,) + output
1789
+ return (loss,) + output if loss is not None else output
1790
+
1791
+ return MoeCausalLMOutputWithPast(
1792
+ loss=loss,
1793
+ aux_loss=aux_loss,
1794
+ logits=logits,
1795
+ past_key_values=outputs.past_key_values,
1796
+ hidden_states=outputs.hidden_states,
1797
+ attentions=outputs.attentions,
1798
+ router_logits=outputs.router_logits,
1799
+ )
1800
+
1801
+ def prepare_inputs_for_generation(
1802
+ self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, token_type_ids=None, **kwargs
1803
+ ):
1804
+ if past_key_values is not None:
1805
+ if isinstance(past_key_values, Cache):
1806
+ cache_length = past_key_values.get_seq_length(self.standard_attn_layer_idx)
1807
+ past_length = past_key_values.seen_tokens
1808
+ max_cache_length = (
1809
+ past_key_values.get_max_length()
1810
+ if hasattr(past_key_values, "get_max_length")
1811
+ else past_key_values.get_max_cache_shape()
1812
+ )
1813
+ else:
1814
+ cache_length = past_length = past_key_values[self.standard_attn_layer_idx][0].shape[2]
1815
+ max_cache_length = None
1816
+
1817
+ # Keep only the unprocessed tokens:
1818
+ # 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where
1819
+ # some of the inputs are exclusivelly passed as part of the cache (e.g. when passing input_embeds as input)
1820
+ if attention_mask is not None and attention_mask.shape[1] > input_ids.shape[1]:
1821
+ input_ids = input_ids[:, -(attention_mask.shape[1] - past_length) :]
1822
+ # 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens. We can discard
1823
+ # input_ids based on the past_length.
1824
+ elif past_length < input_ids.shape[1]:
1825
+ input_ids = input_ids[:, past_length:]
1826
+ # 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens.
1827
+
1828
+ # If we are about to go beyond the maximum cache length, we need to crop the input attention mask.
1829
+ if (
1830
+ max_cache_length is not None
1831
+ and attention_mask is not None
1832
+ and cache_length + input_ids.shape[1] > max_cache_length
1833
+ ):
1834
+ attention_mask = attention_mask[:, -max_cache_length:]
1835
+
1836
+ position_ids = kwargs.get("position_ids", None)
1837
+ if attention_mask is not None and position_ids is None:
1838
+ # create position_ids on the fly for batch generation
1839
+ position_ids = attention_mask.long().cumsum(-1) - 1
1840
+ position_ids.masked_fill_(attention_mask == 0, 1)
1841
+ if past_key_values:
1842
+ position_ids = position_ids[:, -input_ids.shape[1] :]
1843
+
1844
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1845
+ if inputs_embeds is not None and past_key_values is None:
1846
+ model_inputs = {"inputs_embeds": inputs_embeds}
1847
+ else:
1848
+ model_inputs = {"input_ids": input_ids}
1849
+
1850
+ model_inputs.update(
1851
+ {
1852
+ "position_ids": position_ids,
1853
+ "past_key_values": past_key_values,
1854
+ "use_cache": kwargs.get("use_cache"),
1855
+ "attention_mask": attention_mask,
1856
+ }
1857
+ )
1858
+ return model_inputs
1859
+
1860
+ @staticmethod
1861
+ def _reorder_cache(past_key_values, beam_idx):
1862
+ reordered_past = ()
1863
+ for layer_past in past_key_values:
1864
+ reordered_past += (
1865
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
1866
+ )
1867
+ return reordered_past
special_tokens_map.json ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "additional_special_tokens": [
3
+ "<|arithmetic_start|>",
4
+ "<|arithmetic_end|>",
5
+ "<role>",
6
+ "</role>",
7
+ "<|number_end|>",
8
+ "<|number_start|>"
9
+ ],
10
+ "bos_token": "<|startoftext|>",
11
+ "cls_token": "[CLS]",
12
+ "eos_token": "<|endoftext|>",
13
+ "gmask_token": "[gMASK]",
14
+ "pad_token": "<|endoftext|>"
15
+ }
tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
tokenizer_config.json ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_bos_token": false,
3
+ "add_eos_token": false,
4
+ "additional_special_tokens": [
5
+ "<role>",
6
+ "</role>",
7
+ "<|arithmetic_start|>",
8
+ "<|arithmetic_end|>",
9
+ "<|number_start|>",
10
+ "<|number_end|>"
11
+ ],
12
+ "bos_token": "<|startoftext|>",
13
+ "chat_template": "{% for message in messages %}{% set role = message['role'] | lower %}{% if role == 'user' %}{% set role = 'HUMAN' %}{% endif %}{% set role = role | upper %}{{ '<role>' + role + '</role>' + message['content'].split('</think>')[-1].lstrip('\\n') }}{% endfor %}{% if add_generation_prompt %}{{ '<role>ASSISTANT</role>' }}{% endif %}",
14
+ "clean_up_tokenization_spaces": false,
15
+ "cls_token": "[CLS]",
16
+ "eos_token": "<|endoftext|>",
17
+ "gmask_token": "[gMASK]",
18
+ "merges_file": null,
19
+ "model_max_length": 1000000000000000019884624838656,
20
+ "pad_token": "<|endoftext|>",
21
+ "tokenizer_class": "PreTrainedTokenizerFast",
22
+ "trust_remote_code": true,
23
+ "vocab_file": null,
24
+ "fast_tokenizer": true
25
+ }