hongyuw commited on
Commit
abef245
·
verified ·
1 Parent(s): fea821b

Upload folder using huggingface_hub

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