Vance0124 commited on
Commit
4e15342
·
verified ·
1 Parent(s): aa47a6c

Upload folder using huggingface_hub

Browse files
.gitattributes CHANGED
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ tokenizer.json filter=lfs diff=lfs merge=lfs -text
added_tokens.json ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ {
2
+ "<|endoftext|>": 151643,
3
+ "<|im_end|>": 151645,
4
+ "<|im_start|>": 151644
5
+ }
config.json ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "/data/user/qxiao183/qxiao183test2/zyc/models/pretrain/PLM-1.8B-Instruct",
3
+ "architectures": [
4
+ "PLMForCausalLM"
5
+ ],
6
+ "attention_bias": false,
7
+ "attention_dropout": 0.0,
8
+ "auto_map": {
9
+ "AutoConfig": "configuration_plm.PLMConfig",
10
+ "AutoModel": "modeling_plm.PLMModel",
11
+ "AutoModelForCausalLM": "modeling_plm.PLMForCausalLM"
12
+ },
13
+ "bos_token_id": 151643,
14
+ "eos_token_id": 151643,
15
+ "hidden_act": "relu2",
16
+ "hidden_size": 2048,
17
+ "initializer_range": 0.02,
18
+ "intermediate_size": 8192,
19
+ "kv_lora_rank": 512,
20
+ "max_position_embeddings": 32768,
21
+ "model_type": "plm",
22
+ "n_routed_experts": null,
23
+ "num_attention_heads": 16,
24
+ "num_hidden_layers": 32,
25
+ "num_key_value_heads": 16,
26
+ "pretraining_tp": 1,
27
+ "q_lora_rank": null,
28
+ "qk_nope_head_dim": 128,
29
+ "qk_rope_head_dim": 64,
30
+ "rms_norm_eps": 1e-06,
31
+ "rope_scaling": null,
32
+ "rope_theta": 100000.0,
33
+ "routed_scaling_factor": null,
34
+ "torch_dtype": "bfloat16",
35
+ "transformers_version": "4.49.0",
36
+ "use_cache": false,
37
+ "v_head_dim": 128,
38
+ "vocab_size": 151646
39
+ }
configuration_plm.py ADDED
@@ -0,0 +1,155 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 The PLM team and The HuggingFace Inc. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """PLM model configuration"""
16
+ from transformers.configuration_utils import PretrainedConfig
17
+ from transformers.utils import logging
18
+
19
+
20
+ logger = logging.get_logger(__name__)
21
+
22
+
23
+ class PLMConfig(PretrainedConfig):
24
+ r"""
25
+ This is the configuration class to store the configuration of a [`PLMModel`]. It is used to instantiate a
26
+ PLM model according to the specified arguments, defining the model architecture.
27
+
28
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
29
+ documentation from [`PretrainedConfig`] for more information. Instantiating a configuration with the
30
+ defaults will yield a similar configuration to that of the PLM model.
31
+
32
+
33
+ Args:
34
+ vocab_size (`int`, *optional*, defaults to 151936):
35
+ Vocabulary size of the PLM model. Defines the number of different tokens that can be represented by the
36
+ `inputs_ids` passed when calling [`PLMModel`]
37
+ hidden_size (`int`, *optional*, defaults to 4096):
38
+ Dimension of the hidden representations.
39
+ intermediate_size (`int`, *optional*, defaults to 8192):
40
+ Dimension of the MLP representations.
41
+ num_hidden_layers (`int`, *optional*, defaults to 32):
42
+ Number of hidden layers in the Transformer encoder.
43
+ num_attention_heads (`int`, *optional*, defaults to 16):
44
+ Number of attention heads for each attention layer in the Transformer encoder.
45
+ num_key_value_heads (`int`, *optional*, defaults to 16):
46
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
47
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
48
+ `num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When
49
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
50
+ by meanpooling all the original heads within that group. For more details checkout [this
51
+ paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to `32`.
52
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
53
+ The non-linear activation function (function or string) in the decoder.
54
+ pretraining_tp (`int`, *optional*, defaults to 1):
55
+ Experimental feature. Tensor parallelism rank used during pretraining. Please refer to [this
56
+ document](https://huggingface.co/docs/transformers/parallelism) to understand more about it. This value is
57
+ necessary to ensure exact reproducibility of the pretraining results. Please refer to [this
58
+ issue](https://github.com/pytorch/pytorch/issues/76232).
59
+ max_position_embeddings (`int`, *optional*, defaults to 4096):
60
+ The maximum sequence length that this model might ever be used with.
61
+ initializer_range (`float`, *optional*, defaults to 0.02):
62
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
63
+ rms_norm_eps (`float`, *optional*, defaults to 1e-06):
64
+ The epsilon used by the rms normalization layers.
65
+ use_cache (`bool`, *optional*, defaults to `True`):
66
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
67
+ relevant if `config.is_decoder=True`.
68
+ tie_word_embeddings (`bool`, *optional*, defaults to `True`):
69
+ Whether the model's input and output word embeddings should be tied.
70
+ rope_scaling (`Dict`, *optional*):
71
+ Dictionary containing the scaling configuration for the RoPE embeddings. Currently supports normal rope.
72
+ rope_theta (`float`, *optional*, defaults to 100000.0):
73
+ The base period of the RoPE embeddings.
74
+ attention_bias (`bool`, defaults to `False`, *optional*, defaults to `False`):
75
+ Whether to use a bias in the query, key, value and output projection layers during self-attention.
76
+ attention_dropout (`float`, *optional*, defaults to 0.0):
77
+ The dropout ratio for the attention probabilities.
78
+
79
+ ```python
80
+ >>> from transformers import PLMModel, PLMConfig
81
+
82
+ >>> # Initializing a PLM style configuration
83
+ >>> configuration = PLMConfig()
84
+
85
+ >>> # Initializing a model from the PLM style configuration
86
+ >>> model = PLMModel(configuration)
87
+
88
+ >>> # Accessing the model configuration
89
+ >>> configuration = model.config
90
+ ```"""
91
+
92
+ model_type = "plm"
93
+ keys_to_ignore_at_inference = ["past_key_values"]
94
+
95
+ def __init__(
96
+ self,
97
+ vocab_size=151936,
98
+ hidden_size=2048,
99
+ intermediate_size=8192,
100
+ num_hidden_layers=32,
101
+ num_attention_heads=16,
102
+ num_key_value_heads=16,
103
+ kv_lora_rank = 512,
104
+ q_lora_rank = None,
105
+ qk_rope_head_dim = 64,
106
+ v_head_dim = 128,
107
+ qk_nope_head_dim = 128,
108
+ hidden_act="relu2",
109
+ max_position_embeddings=4096,
110
+ initializer_range=0.02,
111
+ rms_norm_eps=1e-6,
112
+ use_cache=True,
113
+ pretraining_tp=1,
114
+ tie_word_embeddings=True,
115
+ rope_theta=100000.0,
116
+ rope_scaling=None,
117
+ attention_bias=False,
118
+ attention_dropout=0.0,
119
+ n_routed_experts=None,
120
+ **kwargs,
121
+ ):
122
+ self.vocab_size = vocab_size
123
+ self.max_position_embeddings = max_position_embeddings
124
+ self.hidden_size = hidden_size
125
+ self.intermediate_size = intermediate_size
126
+ self.num_hidden_layers = num_hidden_layers
127
+ self.num_attention_heads = num_attention_heads
128
+ self.kv_lora_rank = kv_lora_rank
129
+ self.q_lora_rank = q_lora_rank
130
+ self.qk_rope_head_dim = qk_rope_head_dim
131
+ self.v_head_dim = v_head_dim
132
+ self.qk_nope_head_dim = qk_nope_head_dim
133
+ # for backward compatibility
134
+ if num_key_value_heads is None:
135
+ num_key_value_heads = num_attention_heads
136
+
137
+ self.num_key_value_heads = num_key_value_heads
138
+ self.hidden_act = hidden_act
139
+ self.initializer_range = initializer_range
140
+ self.rms_norm_eps = rms_norm_eps
141
+ self.pretraining_tp = pretraining_tp
142
+ self.use_cache = use_cache
143
+ self.rope_theta = rope_theta
144
+ self.rope_scaling = rope_scaling
145
+ self.attention_bias = attention_bias
146
+ self.attention_dropout = attention_dropout
147
+
148
+ # for vllm inference
149
+ self.n_routed_experts = n_routed_experts
150
+ self.routed_scaling_factor = None
151
+
152
+ super().__init__(
153
+ tie_word_embeddings=tie_word_embeddings,
154
+ **kwargs,
155
+ )
generation_config.json ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "bos_token_id": 151643,
4
+ "eos_token_id": 151643,
5
+ "transformers_version": "4.49.0"
6
+ }
merges.txt ADDED
The diff for this file is too large to render. See raw diff
 
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:31ceac4cedb24be03694ed7c94bda8a03ec8e6a5ba6346141081d8b892bcf9de
3
+ size 3649762688
modeling_plm.py ADDED
@@ -0,0 +1,1456 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 The PLM team and The HuggingFace Inc. All rights reserved.
3
+ #
4
+ # This code is based on Alibaba's Qwen2 library, DeepSeek-AI's deepseekv2
5
+ # library, EleutherAI's GPT-NeoX library and the GPT-NeoX and OPT implementations
6
+ # in this library. It has been modified from its original forms to accommodate
7
+ # minor architectural differences compared to GPT-NeoX and OPT used by the Meta
8
+ # AI team that trained the model.
9
+ #
10
+ # Licensed under the Apache License, Version 2.0 (the "License");
11
+ # you may not use this file except in compliance with the License.
12
+ # You may obtain a copy of the License at
13
+ #
14
+ # http://www.apache.org/licenses/LICENSE-2.0
15
+ #
16
+ # Unless required by applicable law or agreed to in writing, software
17
+ # distributed under the License is distributed on an "AS IS" BASIS,
18
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19
+ # See the License for the specific language governing permissions and
20
+ # limitations under the License.
21
+ """PyTorch PLM model."""
22
+
23
+ import inspect
24
+ import math
25
+ import warnings
26
+ from typing import List, Optional, Tuple, Union
27
+
28
+ import torch
29
+ import torch.nn.functional as F
30
+ import torch.utils.checkpoint
31
+ from torch import nn
32
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
33
+
34
+ from transformers.activations import ACT2FN
35
+ from transformers.cache_utils import Cache, DynamicCache, StaticCache
36
+ from transformers.modeling_attn_mask_utils import (
37
+ AttentionMaskConverter,
38
+ _prepare_4d_attention_mask,
39
+ _prepare_4d_causal_attention_mask
40
+ )
41
+ from transformers.modeling_outputs import (
42
+ BaseModelOutputWithPast,
43
+ CausalLMOutputWithPast,
44
+ SequenceClassifierOutputWithPast,
45
+ TokenClassifierOutput,
46
+ )
47
+ from transformers.modeling_utils import PreTrainedModel
48
+ from transformers.utils import (
49
+ add_start_docstrings,
50
+ add_start_docstrings_to_model_forward,
51
+ is_flash_attn_2_available,
52
+ is_flash_attn_greater_or_equal_2_10,
53
+ logging,
54
+ replace_return_docstrings,
55
+ )
56
+ from .configuration_plm import PLMConfig
57
+
58
+
59
+ if is_flash_attn_2_available():
60
+ from flash_attn import flash_attn_func, flash_attn_varlen_func
61
+ from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
62
+
63
+ _flash_supports_window_size = "window_size" in list(inspect.signature(flash_attn_func).parameters)
64
+
65
+
66
+ logger = logging.get_logger(__name__)
67
+
68
+
69
+ _CHECKPOINT_FOR_DOC = "PLM/PLM-1.8B-base"
70
+ _CONFIG_FOR_DOC = "PLMConfig"
71
+
72
+
73
+ # Copied from transformers.models.llama.modeling_llama._get_unpad_data
74
+ def _get_unpad_data(attention_mask):
75
+ seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
76
+ indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
77
+ max_seqlen_in_batch = seqlens_in_batch.max().item()
78
+ cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.int32), (1, 0))
79
+ return (
80
+ indices,
81
+ cu_seqlens,
82
+ max_seqlen_in_batch,
83
+ )
84
+
85
+
86
+ # Copied from transformers.models.llama.modeling_llama.LlamaRMSNorm with Llama->PLM
87
+ class PLMRMSNorm(nn.Module):
88
+ def __init__(self, hidden_size, eps=1e-6):
89
+ """
90
+ PLMRMSNorm is equivalent to T5LayerNorm
91
+ """
92
+ super().__init__()
93
+ self.weight = nn.Parameter(torch.ones(hidden_size))
94
+ self.variance_epsilon = eps
95
+ # We modify RMSNorm to align with TENorm, https://github.com/NVIDIA/TransformerEngine/issues/1132
96
+ def forward(self, hidden_states):
97
+ input_dtype = hidden_states.dtype
98
+ hidden_states = hidden_states.to(torch.float32)
99
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
100
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
101
+ # return self.weight * hidden_states.to(input_dtype)
102
+ return (self.weight.to(torch.float32) * hidden_states).to(input_dtype)
103
+
104
+
105
+ # Copied from transformers.models.mixtral.modeling_mixtral.MixtralRotaryEmbedding with Mixtral->PLM
106
+ class PLMRotaryEmbedding(nn.Module):
107
+ def __init__(self, dim, max_position_embeddings=4096, base=100000, device=None):
108
+ super().__init__()
109
+ self.dim = dim
110
+ self.max_position_embeddings = max_position_embeddings
111
+ self.base = base
112
+ inv_freq = 1.0 / (
113
+ self.base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim)
114
+ )
115
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
116
+
117
+ # Build here to make `torch.jit.trace` work.
118
+ self._set_cos_sin_cache(
119
+ seq_len=max_position_embeddings,
120
+ device=self.inv_freq.device,
121
+ dtype=torch.get_default_dtype(),
122
+ )
123
+ self.max_seq_len_cached = None
124
+
125
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
126
+ self.max_seq_len_cached = seq_len
127
+ t = torch.arange(
128
+ self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype
129
+ )
130
+
131
+ freqs = torch.outer(t, self.inv_freq.to(t.device))
132
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
133
+ emb = torch.cat((freqs, freqs), dim=-1)
134
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
135
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
136
+
137
+ def forward(self, x, seq_len=None):
138
+ # x: [bs, num_attention_heads, seq_len, head_size]
139
+ if self.max_seq_len_cached is None or seq_len > self.max_seq_len_cached:
140
+ self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)
141
+
142
+ return (
143
+ self.cos_cached[:seq_len].to(dtype=x.dtype),
144
+ self.sin_cached[:seq_len].to(dtype=x.dtype),
145
+ )
146
+
147
+
148
+ # Copied from transformers.models.llama.modeling_llama.rotate_half
149
+ def rotate_half(x):
150
+ """Rotates half the hidden dims of the input."""
151
+ x1 = x[..., : x.shape[-1] // 2]
152
+ x2 = x[..., x.shape[-1] // 2 :]
153
+ return torch.cat((-x2, x1), dim=-1)
154
+
155
+
156
+ # Copied from transformers.models.mixtral.modeling_mixtral.apply_rotary_pos_emb
157
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1):
158
+ """Applies Rotary Position Embedding to the query and key tensors.
159
+
160
+ Args:
161
+ q (`torch.Tensor`): The query tensor.
162
+ k (`torch.Tensor`): The key tensor.
163
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
164
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
165
+ position_ids (`torch.Tensor`):
166
+ The position indices of the tokens corresponding to the query and key tensors. For example, this can be
167
+ used to pass offsetted position ids when working with a KV-cache.
168
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
169
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
170
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
171
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
172
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
173
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
174
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
175
+ Returns:
176
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
177
+ """
178
+ cos = cos[position_ids].unsqueeze(unsqueeze_dim)
179
+ sin = sin[position_ids].unsqueeze(unsqueeze_dim)
180
+
181
+ b, h, s, d = q.shape
182
+ q = q.view(b, h, s, d // 2, 2).transpose(4, 3).reshape(b, h, s, d)
183
+
184
+ b, h, s, d = k.shape
185
+ k = k.view(b, h, s, d // 2, 2).transpose(4, 3).reshape(b, h, s, d)
186
+
187
+ q_embed = (q * cos) + (rotate_half(q) * sin)
188
+ k_embed = (k * cos) + (rotate_half(k) * sin)
189
+ return q_embed, k_embed
190
+
191
+
192
+ class PLMMLP(nn.Module):
193
+ def __init__(self, config):
194
+ super().__init__()
195
+ self.hidden_size = config.hidden_size
196
+ self.intermediate_size = config.intermediate_size
197
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
198
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
199
+ self.act_fn = ACT2FN[config.hidden_act]
200
+
201
+ def forward(self, hidden_state):
202
+ h = self.up_proj(hidden_state)
203
+ h = self.act_fn(h)
204
+ h = self.down_proj(h)
205
+ return h
206
+
207
+
208
+ # Copied from transformers.models.llama.modeling_llama.repeat_kv
209
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
210
+ """
211
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
212
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
213
+ """
214
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
215
+ if n_rep == 1:
216
+ return hidden_states
217
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
218
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
219
+
220
+
221
+ # Copied from https://huggingface.co/deepseek-ai/DeepSeek-V2-Lite/blob/main/modeling_deepseek.py
222
+ # DeepseekV2Attention with DeepseekV2->PLM
223
+
224
+ class PLMAttention(nn.Module):
225
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
226
+
227
+ def __init__(self, config, layer_idx: Optional[int] = None):
228
+ super().__init__()
229
+ self.config = config
230
+ self.layer_idx = layer_idx
231
+ if layer_idx is None:
232
+ logger.warning_once(
233
+ f"Instantiating {self.__class__.__name__} without passing `layer_idx` is not recommended and will "
234
+ "to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` "
235
+ "when creating this class."
236
+ )
237
+
238
+ self.attention_dropout = config.attention_dropout
239
+ self.hidden_size = config.hidden_size
240
+ self.num_heads = config.num_attention_heads
241
+
242
+ self.max_position_embeddings = config.max_position_embeddings
243
+ self.rope_theta = config.rope_theta
244
+ self.q_lora_rank = config.q_lora_rank
245
+ self.qk_rope_head_dim = config.qk_rope_head_dim
246
+ self.kv_lora_rank = config.kv_lora_rank
247
+ self.v_head_dim = config.v_head_dim
248
+ self.qk_nope_head_dim = config.qk_nope_head_dim
249
+ self.q_head_dim = config.qk_nope_head_dim + config.qk_rope_head_dim
250
+
251
+ self.is_causal = True
252
+
253
+ if self.q_lora_rank is None:
254
+ self.q_proj = nn.Linear(
255
+ self.hidden_size, self.num_heads * self.q_head_dim, bias=False
256
+ )
257
+ else:
258
+ self.q_a_proj = nn.Linear(
259
+ self.hidden_size, config.q_lora_rank, bias=config.attention_bias
260
+ )
261
+ self.q_a_layernorm = PLMRMSNorm(config.q_lora_rank)
262
+ self.q_b_proj = nn.Linear(
263
+ config.q_lora_rank, self.num_heads * self.q_head_dim, bias=False
264
+ )
265
+
266
+ self.kv_a_proj_with_mqa = nn.Linear(
267
+ self.hidden_size,
268
+ config.kv_lora_rank + config.qk_rope_head_dim,
269
+ bias=config.attention_bias,
270
+ )
271
+ self.kv_a_layernorm = PLMRMSNorm(config.kv_lora_rank)
272
+ self.kv_b_proj = nn.Linear(
273
+ config.kv_lora_rank,
274
+ self.num_heads
275
+ * (self.q_head_dim - self.qk_rope_head_dim + self.v_head_dim),
276
+ bias=False,
277
+ )
278
+ self.o_proj = nn.Linear(
279
+ self.num_heads * self.v_head_dim,
280
+ self.hidden_size,
281
+ bias=config.attention_bias,
282
+ )
283
+ self._init_rope()
284
+
285
+ self.softmax_scale = self.q_head_dim ** (-0.5)
286
+
287
+
288
+ def _init_rope(self):
289
+ if self.config.rope_scaling is None:
290
+ self.rotary_emb = PLMRotaryEmbedding(
291
+ self.qk_rope_head_dim,
292
+ max_position_embeddings=self.max_position_embeddings,
293
+ base=self.rope_theta,
294
+ )
295
+ else:
296
+ raise ValueError(f"Currently do not support other RoPE scaling type")
297
+
298
+
299
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
300
+ return (
301
+ tensor.view(bsz, seq_len, self.num_heads, self.v_head_dim)
302
+ .transpose(1, 2)
303
+ .contiguous()
304
+ )
305
+
306
+ def forward(
307
+ self,
308
+ hidden_states: torch.Tensor,
309
+ attention_mask: Optional[torch.Tensor] = None,
310
+ position_ids: Optional[torch.LongTensor] = None,
311
+ past_key_value: Optional[Cache] = None,
312
+ output_attentions: bool = False,
313
+ use_cache: bool = False,
314
+ **kwargs,
315
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
316
+ if "padding_mask" in kwargs:
317
+ warnings.warn(
318
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
319
+ )
320
+ bsz, q_len, _ = hidden_states.size()
321
+
322
+ if self.q_lora_rank is None:
323
+ q = self.q_proj(hidden_states)
324
+ else:
325
+ q = self.q_b_proj(self.q_a_layernorm(self.q_a_proj(hidden_states)))
326
+ q = q.view(bsz, q_len, self.num_heads, self.q_head_dim).transpose(1, 2)
327
+ q_nope, q_pe = torch.split(
328
+ q, [self.qk_nope_head_dim, self.qk_rope_head_dim], dim=-1
329
+ )
330
+
331
+ compressed_kv = self.kv_a_proj_with_mqa(hidden_states) # 1 9 576
332
+ compressed_kv, k_pe = torch.split(
333
+ compressed_kv, [self.kv_lora_rank, self.qk_rope_head_dim], dim=-1
334
+ )
335
+ k_pe = k_pe.view(bsz, q_len, 1, self.qk_rope_head_dim).transpose(1, 2)
336
+ kv = (
337
+ self.kv_b_proj(self.kv_a_layernorm(compressed_kv))
338
+ .view(bsz, q_len, self.num_heads, self.qk_nope_head_dim + self.v_head_dim)
339
+ .transpose(1, 2)
340
+ )
341
+ k_nope, value_states = torch.split(
342
+ kv, [self.qk_nope_head_dim, self.v_head_dim], dim=-1
343
+ )
344
+ kv_seq_len = value_states.shape[-2]
345
+ if past_key_value is not None:
346
+ if self.layer_idx is None:
347
+ raise ValueError(
348
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
349
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
350
+ "with a layer index."
351
+ )
352
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
353
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
354
+
355
+ q_pe, k_pe = apply_rotary_pos_emb(q_pe, k_pe, cos, sin, position_ids)
356
+
357
+ query_states = k_pe.new_empty(bsz, self.num_heads, q_len, self.q_head_dim)
358
+ query_states[:, :, :, : self.qk_nope_head_dim] = q_nope
359
+ query_states[:, :, :, self.qk_nope_head_dim :] = q_pe
360
+
361
+ key_states = k_pe.new_empty(bsz, self.num_heads, q_len, self.q_head_dim)
362
+ key_states[:, :, :, : self.qk_nope_head_dim] = k_nope
363
+ key_states[:, :, :, self.qk_nope_head_dim :] = k_pe
364
+ if past_key_value is not None:
365
+ cache_kwargs = {"sin": sin, "cos": cos}
366
+ key_states, value_states = past_key_value.update(
367
+ key_states, value_states, self.layer_idx, cache_kwargs
368
+ )
369
+
370
+ attn_weights = (
371
+ torch.matmul(query_states, key_states.transpose(2, 3)) * self.softmax_scale
372
+ )
373
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
374
+ raise ValueError(
375
+ f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
376
+ f" {attn_weights.size()}"
377
+ )
378
+ if attention_mask is not None:
379
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
380
+ raise ValueError(
381
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
382
+ )
383
+
384
+ attn_weights = attn_weights + attention_mask
385
+ attn_weights = nn.functional.softmax(
386
+ attn_weights, dim=-1, dtype=torch.float32
387
+ ).to(query_states.dtype)
388
+ attn_weights = nn.functional.dropout(
389
+ attn_weights, p=self.attention_dropout, training=self.training
390
+ )
391
+ attn_output = torch.matmul(attn_weights, value_states)
392
+
393
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.v_head_dim):
394
+ raise ValueError(
395
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.v_head_dim)}, but is"
396
+ f" {attn_output.size()}"
397
+ )
398
+ attn_output = attn_output.transpose(1, 2).contiguous()
399
+
400
+ attn_output = attn_output.reshape(bsz, q_len, self.num_heads * self.v_head_dim)
401
+
402
+ attn_output = self.o_proj(attn_output)
403
+
404
+ if not output_attentions:
405
+ attn_weights = None
406
+
407
+ return attn_output, attn_weights, past_key_value
408
+
409
+
410
+ class PLMFlashAttention2(PLMAttention):
411
+ """
412
+ PLM flash attention module. This module inherits from `PLMAttention` as the weights of the module stays
413
+ untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
414
+ flash attention and deal with padding tokens in case the input contains any of them.
415
+ """
416
+
417
+ def __init__(self, *args, **kwargs):
418
+ super().__init__(*args, **kwargs)
419
+
420
+ # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
421
+ # 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.
422
+ # 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).
423
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
424
+
425
+ def forward(
426
+ self,
427
+ hidden_states: torch.Tensor,
428
+ attention_mask: Optional[torch.LongTensor] = None,
429
+ position_ids: Optional[torch.LongTensor] = None,
430
+ past_key_value: Optional[Cache] = None,
431
+ output_attentions: bool = False,
432
+ use_cache: bool = False,
433
+ **kwargs,
434
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
435
+ # PLMFlashAttention2 attention does not support output_attentions
436
+
437
+ if "padding_mask" in kwargs:
438
+ warnings.warn(
439
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
440
+ )
441
+
442
+ # overwrite attention_mask with padding_mask
443
+ attention_mask = kwargs.pop("padding_mask")
444
+
445
+ output_attentions = False
446
+
447
+ bsz, q_len, _ = hidden_states.size()
448
+
449
+ if self.q_lora_rank is None:
450
+ q = self.q_proj(hidden_states)
451
+ else:
452
+ q = self.q_b_proj(self.q_a_layernorm(self.q_a_proj(hidden_states)))
453
+ q = q.view(bsz, q_len, self.num_heads, self.q_head_dim).transpose(1, 2)
454
+ q_nope, q_pe = torch.split(
455
+ q, [self.qk_nope_head_dim, self.qk_rope_head_dim], dim=-1
456
+ )
457
+
458
+ # Flash attention requires the input to have the shape
459
+ # batch_size x seq_length x head_dim x hidden_dim
460
+ # therefore we just need to keep the original shape
461
+ compressed_kv = self.kv_a_proj_with_mqa(hidden_states)
462
+ compressed_kv, k_pe = torch.split(
463
+ compressed_kv, [self.kv_lora_rank, self.qk_rope_head_dim], dim=-1
464
+ )
465
+ k_pe = k_pe.view(bsz, q_len, 1, self.qk_rope_head_dim).transpose(1, 2)
466
+ kv = (
467
+ self.kv_b_proj(self.kv_a_layernorm(compressed_kv))
468
+ .view(bsz, q_len, self.num_heads, self.qk_nope_head_dim + self.v_head_dim)
469
+ .transpose(1, 2)
470
+ )
471
+
472
+ k_nope, value_states = torch.split(
473
+ kv, [self.qk_nope_head_dim, self.v_head_dim], dim=-1
474
+ )
475
+ kv_seq_len = value_states.shape[-2]
476
+
477
+ kv_seq_len = value_states.shape[-2]
478
+ if past_key_value is not None:
479
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
480
+
481
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
482
+ q_pe, k_pe = apply_rotary_pos_emb(q_pe, k_pe, cos, sin, position_ids)
483
+
484
+ query_states = k_pe.new_empty(bsz, self.num_heads, q_len, self.q_head_dim)
485
+ query_states[:, :, :, : self.qk_nope_head_dim] = q_nope
486
+ query_states[:, :, :, self.qk_nope_head_dim :] = q_pe
487
+
488
+ key_states = k_pe.new_empty(bsz, self.num_heads, q_len, self.q_head_dim)
489
+ key_states[:, :, :, : self.qk_nope_head_dim] = k_nope
490
+ key_states[:, :, :, self.qk_nope_head_dim :] = k_pe
491
+
492
+ if self.q_head_dim != self.v_head_dim:
493
+ value_states = F.pad(value_states, [0, self.q_head_dim - self.v_head_dim])
494
+
495
+ if past_key_value is not None:
496
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
497
+ key_states, value_states = past_key_value.update(
498
+ key_states, value_states, self.layer_idx, cache_kwargs
499
+ )
500
+
501
+ # 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
502
+ # to be able to avoid many of these transpose/reshape/view.
503
+ query_states = query_states.transpose(1, 2)
504
+ key_states = key_states.transpose(1, 2)
505
+ value_states = value_states.transpose(1, 2)
506
+
507
+ dropout_rate = self.attention_dropout if self.training else 0.0
508
+
509
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
510
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
511
+ # cast them back in the correct dtype just to be sure everything works as expected.
512
+ # This might slowdown training & inference so it is recommended to not cast the LayerNorms
513
+ # in fp32. (PLMV2RMSNorm handles it correctly)
514
+
515
+ input_dtype = query_states.dtype
516
+ if input_dtype == torch.float32:
517
+ # Handle the case where the model is quantized
518
+ if hasattr(self.config, "_pre_quantization_dtype"):
519
+ target_dtype = self.config._pre_quantization_dtype
520
+ elif torch.is_autocast_enabled():
521
+ target_dtype = torch.get_autocast_gpu_dtype()
522
+ else:
523
+ target_dtype = self.q_proj.weight.dtype if self.q_lora_rank is None else self.q_a_proj.weight.dtype
524
+
525
+ logger.warning_once(
526
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
527
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
528
+ f" {target_dtype}."
529
+ )
530
+
531
+ query_states = query_states.to(target_dtype)
532
+ key_states = key_states.to(target_dtype)
533
+ value_states = value_states.to(target_dtype)
534
+
535
+ attn_output = self._flash_attention_forward(
536
+ query_states,
537
+ key_states,
538
+ value_states,
539
+ attention_mask,
540
+ q_len,
541
+ dropout=dropout_rate,
542
+ softmax_scale=self.softmax_scale,
543
+ )
544
+ if self.q_head_dim != self.v_head_dim:
545
+ attn_output = attn_output[:, :, :, : self.v_head_dim]
546
+
547
+ attn_output = attn_output.reshape(
548
+ bsz, q_len, self.num_heads * self.v_head_dim
549
+ ).contiguous()
550
+
551
+ attn_output = self.o_proj(attn_output)
552
+
553
+ if not output_attentions:
554
+ attn_weights = None
555
+
556
+ return attn_output, attn_weights, past_key_value
557
+
558
+ def _flash_attention_forward(
559
+ self,
560
+ query_states,
561
+ key_states,
562
+ value_states,
563
+ attention_mask,
564
+ query_length,
565
+ dropout=0.0,
566
+ softmax_scale=None,
567
+ ):
568
+ """
569
+ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
570
+ first unpad the input, then computes the attention scores and pad the final attention scores.
571
+
572
+ Args:
573
+ query_states (`torch.Tensor`):
574
+ Input query states to be passed to Flash Attention API
575
+ key_states (`torch.Tensor`):
576
+ Input key states to be passed to Flash Attention API
577
+ value_states (`torch.Tensor`):
578
+ Input value states to be passed to Flash Attention API
579
+ attention_mask (`torch.Tensor`):
580
+ The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
581
+ position of padding tokens and 1 for the position of non-padding tokens.
582
+ dropout (`int`, *optional*):
583
+ Attention dropout
584
+ softmax_scale (`float`, *optional*):
585
+ The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
586
+ """
587
+
588
+ if not self._flash_attn_uses_top_left_mask:
589
+ causal = self.is_causal
590
+ else:
591
+ # TODO: Remove the `query_length != 1` check once Flash Attention for RoCm is bumped to 2.1. For details, please see the comment in PLMFlashAttention2 __init__.
592
+ causal = self.is_causal and query_length != 1
593
+
594
+ # Contains at least one padding token in the sequence
595
+ if attention_mask is not None:
596
+ batch_size = query_states.shape[0]
597
+ (
598
+ query_states,
599
+ key_states,
600
+ value_states,
601
+ indices_q,
602
+ cu_seq_lens,
603
+ max_seq_lens,
604
+ ) = self._upad_input(
605
+ query_states, key_states, value_states, attention_mask, query_length
606
+ )
607
+
608
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
609
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
610
+
611
+ attn_output_unpad = flash_attn_varlen_func(
612
+ query_states,
613
+ key_states,
614
+ value_states,
615
+ cu_seqlens_q=cu_seqlens_q,
616
+ cu_seqlens_k=cu_seqlens_k,
617
+ max_seqlen_q=max_seqlen_in_batch_q,
618
+ max_seqlen_k=max_seqlen_in_batch_k,
619
+ dropout_p=dropout,
620
+ softmax_scale=softmax_scale,
621
+ causal=causal,
622
+ )
623
+
624
+ attn_output = pad_input(
625
+ attn_output_unpad, indices_q, batch_size, query_length
626
+ )
627
+ else:
628
+ attn_output = flash_attn_func(
629
+ query_states,
630
+ key_states,
631
+ value_states,
632
+ dropout,
633
+ softmax_scale=softmax_scale,
634
+ causal=causal,
635
+ )
636
+
637
+ return attn_output
638
+
639
+ def _upad_input(
640
+ self, query_layer, key_layer, value_layer, attention_mask, query_length
641
+ ):
642
+ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
643
+ batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape
644
+
645
+ key_layer = index_first_axis(
646
+ key_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim),
647
+ indices_k,
648
+ )
649
+ value_layer = index_first_axis(
650
+ value_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim),
651
+ indices_k,
652
+ )
653
+ if query_length == kv_seq_len:
654
+ query_layer = index_first_axis(
655
+ query_layer.reshape(batch_size * kv_seq_len, self.num_heads, head_dim),
656
+ indices_k,
657
+ )
658
+ cu_seqlens_q = cu_seqlens_k
659
+ max_seqlen_in_batch_q = max_seqlen_in_batch_k
660
+ indices_q = indices_k
661
+ elif query_length == 1:
662
+ max_seqlen_in_batch_q = 1
663
+ cu_seqlens_q = torch.arange(
664
+ batch_size + 1, dtype=torch.int32, device=query_layer.device
665
+ ) # There is a memcpy here, that is very bad.
666
+ indices_q = cu_seqlens_q[:-1]
667
+ query_layer = query_layer.squeeze(1)
668
+ else:
669
+ # The -q_len: slice assumes left padding.
670
+ attention_mask = attention_mask[:, -query_length:]
671
+ query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(
672
+ query_layer, attention_mask
673
+ )
674
+
675
+ return (
676
+ query_layer,
677
+ key_layer,
678
+ value_layer,
679
+ indices_q,
680
+ (cu_seqlens_q, cu_seqlens_k),
681
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
682
+ )
683
+ PLM_ATTENTION_CLASSES = {
684
+ "eager": PLMAttention,
685
+ "flash_attention_2": PLMFlashAttention2,
686
+ }
687
+
688
+
689
+ class PLMDecoderLayer(nn.Module):
690
+ def __init__(self, config: PLMConfig, layer_idx: int):
691
+ super().__init__()
692
+ self.hidden_size = config.hidden_size
693
+
694
+ self.self_attn = PLM_ATTENTION_CLASSES[config._attn_implementation](config, layer_idx)
695
+ self.mlp = PLMMLP(config)
696
+ self.input_layernorm = PLMRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
697
+ self.post_attention_layernorm = PLMRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
698
+
699
+ def forward(
700
+ self,
701
+ hidden_states: torch.Tensor,
702
+ attention_mask: Optional[torch.Tensor] = None,
703
+ position_ids: Optional[torch.LongTensor] = None,
704
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
705
+ output_attentions: Optional[bool] = False,
706
+ use_cache: Optional[bool] = False,
707
+ cache_position: Optional[torch.LongTensor] = None,
708
+ **kwargs,
709
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
710
+ """
711
+ Args:
712
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
713
+ attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
714
+ `(batch, sequence_length)` where padding elements are indicated by 0.
715
+ output_attentions (`bool`, *optional*):
716
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
717
+ returned tensors for more detail.
718
+ use_cache (`bool`, *optional*):
719
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
720
+ (see `past_key_values`).
721
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
722
+ cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
723
+ Indices depicting the position of the input sequence tokens in the sequence.
724
+ kwargs (`dict`, *optional*):
725
+ Arbitrary kwargs to be ignored, used for FSDP and other methods that injects code
726
+ into the model
727
+ """
728
+
729
+ residual = hidden_states
730
+
731
+ hidden_states = self.input_layernorm(hidden_states)
732
+
733
+ # Self Attention
734
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
735
+ hidden_states=hidden_states,
736
+ attention_mask=attention_mask,
737
+ position_ids=position_ids,
738
+ past_key_value=past_key_value,
739
+ output_attentions=output_attentions,
740
+ use_cache=use_cache,
741
+ cache_position=cache_position,
742
+ )
743
+ hidden_states = residual + hidden_states
744
+
745
+ # Fully Connected
746
+ residual = hidden_states
747
+ hidden_states = self.post_attention_layernorm(hidden_states)
748
+ hidden_states = self.mlp(hidden_states)
749
+ hidden_states = residual + hidden_states
750
+
751
+ outputs = (hidden_states,)
752
+
753
+ if output_attentions:
754
+ outputs += (self_attn_weights,)
755
+
756
+ if use_cache:
757
+ outputs += (present_key_value,)
758
+
759
+ return outputs
760
+
761
+
762
+ PLM_START_DOCSTRING = r"""
763
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
764
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
765
+ etc.)
766
+
767
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
768
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
769
+ and behavior.
770
+
771
+ Parameters:
772
+ config ([`PLMConfig`]):
773
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
774
+ load the weights associated with the model, only the configuration. Check out the
775
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
776
+ """
777
+
778
+
779
+ @add_start_docstrings(
780
+ "The bare PLM Model outputting raw hidden-states without any specific head on top.",
781
+ PLM_START_DOCSTRING,
782
+ )
783
+ class PLMPreTrainedModel(PreTrainedModel):
784
+ config_class = PLMConfig
785
+ base_model_prefix = "model"
786
+ supports_gradient_checkpointing = True
787
+ _no_split_modules = ["PLMDecoderLayer"]
788
+ _skip_keys_device_placement = "past_key_values"
789
+ _supports_flash_attn_2 = True
790
+ _supports_cache_class = True
791
+
792
+ def _init_weights(self, module):
793
+ std = self.config.initializer_range
794
+ if isinstance(module, nn.Linear):
795
+ module.weight.data.normal_(mean=0.0, std=std)
796
+ if module.bias is not None:
797
+ module.bias.data.zero_()
798
+ elif isinstance(module, nn.Embedding):
799
+ module.weight.data.normal_(mean=0.0, std=std)
800
+ if module.padding_idx is not None:
801
+ module.weight.data[module.padding_idx].zero_()
802
+
803
+
804
+ PLM_INPUTS_DOCSTRING = r"""
805
+ Args:
806
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
807
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
808
+ it.
809
+
810
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
811
+ [`PreTrainedTokenizer.__call__`] for details.
812
+
813
+ [What are input IDs?](../glossary#input-ids)
814
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
815
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
816
+
817
+ - 1 for tokens that are **not masked**,
818
+ - 0 for tokens that are **masked**.
819
+
820
+ [What are attention masks?](../glossary#attention-mask)
821
+
822
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
823
+ [`PreTrainedTokenizer.__call__`] for details.
824
+
825
+ If `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
826
+ `past_key_values`).
827
+
828
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
829
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
830
+ information on the default strategy.
831
+
832
+ - 1 indicates the head is **not masked**,
833
+ - 0 indicates the head is **masked**.
834
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
835
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
836
+ config.n_positions - 1]`.
837
+
838
+ [What are position IDs?](../glossary#position-ids)
839
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
840
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
841
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
842
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
843
+
844
+ Two formats are allowed:
845
+ - a [`~cache_utils.Cache`] instance;
846
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
847
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
848
+ cache format.
849
+
850
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
851
+ legacy cache format will be returned.
852
+
853
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
854
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
855
+ of shape `(batch_size, sequence_length)`.
856
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
857
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
858
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
859
+ model's internal embedding lookup matrix.
860
+ use_cache (`bool`, *optional*):
861
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
862
+ `past_key_values`).
863
+ output_attentions (`bool`, *optional*):
864
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
865
+ tensors for more detail.
866
+ output_hidden_states (`bool`, *optional*):
867
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
868
+ more detail.
869
+ return_dict (`bool`, *optional*):
870
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
871
+ cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
872
+ Indices depicting the position of the input sequence tokens in the sequence. Contrarily to `position_ids`,
873
+ this tensor is not affected by padding. It is used to update the cache in the correct position and to infer
874
+ the complete sequence length.
875
+ """
876
+
877
+
878
+ @add_start_docstrings(
879
+ "The bare PLM Model outputting raw hidden-states without any specific head on top.",
880
+ PLM_START_DOCSTRING,
881
+ )
882
+ class PLMModel(PLMPreTrainedModel):
883
+ """
884
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`PLMDecoderLayer`]
885
+
886
+ Args:
887
+ config: PLMConfig
888
+ """
889
+
890
+ def __init__(self, config: PLMConfig):
891
+ super().__init__(config)
892
+ self.padding_idx = config.pad_token_id
893
+ self.vocab_size = config.vocab_size
894
+
895
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
896
+ self.layers = nn.ModuleList(
897
+ [PLMDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
898
+ )
899
+ self._attn_implementation = config._attn_implementation
900
+ self.norm = PLMRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
901
+
902
+ self.gradient_checkpointing = False
903
+ # Initialize weights and apply final processing
904
+ self.post_init()
905
+
906
+ def get_input_embeddings(self):
907
+ return self.embed_tokens
908
+
909
+ def set_input_embeddings(self, value):
910
+ self.embed_tokens = value
911
+
912
+ @add_start_docstrings_to_model_forward(PLM_INPUTS_DOCSTRING)
913
+ def forward(
914
+ self,
915
+ input_ids: torch.LongTensor = None,
916
+ attention_mask: Optional[torch.Tensor] = None,
917
+ position_ids: Optional[torch.LongTensor] = None,
918
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
919
+ inputs_embeds: Optional[torch.FloatTensor] = None,
920
+ use_cache: Optional[bool] = None,
921
+ output_attentions: Optional[bool] = None,
922
+ output_hidden_states: Optional[bool] = None,
923
+ return_dict: Optional[bool] = None,
924
+ cache_position: Optional[torch.LongTensor] = None,
925
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
926
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
927
+ output_hidden_states = (
928
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
929
+ )
930
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
931
+
932
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
933
+
934
+ # retrieve input_ids and inputs_embeds
935
+ if (input_ids is None) ^ (inputs_embeds is not None):
936
+ raise ValueError(
937
+ "You cannot specify both input_ids and inputs_embeds at the same time, and must specify either one"
938
+ )
939
+ elif input_ids is not None:
940
+ batch_size, seq_length = input_ids.shape[:2]
941
+ elif inputs_embeds is not None:
942
+ batch_size, seq_length = inputs_embeds.shape[:2]
943
+ else:
944
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
945
+
946
+ if self.gradient_checkpointing and self.training:
947
+ if use_cache:
948
+ logger.warning_once(
949
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
950
+ )
951
+ use_cache = False
952
+
953
+ past_key_values_length = 0
954
+ if use_cache:
955
+ use_legacy_cache = not isinstance(past_key_values, Cache)
956
+ if use_legacy_cache:
957
+ past_key_values = DynamicCache.from_legacy_cache(past_key_values)
958
+ past_key_values_length = past_key_values.get_usable_length(seq_length)
959
+
960
+ if inputs_embeds is None:
961
+ inputs_embeds = self.embed_tokens(input_ids)
962
+
963
+ if cache_position is None:
964
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
965
+ cache_position = torch.arange(
966
+ past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
967
+ )
968
+ if position_ids is None:
969
+ position_ids = cache_position.unsqueeze(0)
970
+ if self.config._attn_implementation == "flash_attention_2":
971
+ # 2d mask is passed through the layers
972
+ attention_mask = (
973
+ attention_mask
974
+ if (attention_mask is not None and 0 in attention_mask)
975
+ else None
976
+ )
977
+ else:
978
+ # 4d mask is passed through the layers
979
+ attention_mask = _prepare_4d_causal_attention_mask(
980
+ attention_mask,
981
+ (batch_size, seq_length),
982
+ inputs_embeds,
983
+ past_key_values_length,
984
+ )
985
+
986
+ hidden_states = inputs_embeds
987
+
988
+ # decoder layers
989
+ all_hidden_states = () if output_hidden_states else None
990
+ all_self_attns = () if output_attentions else None
991
+ next_decoder_cache = None
992
+
993
+ for decoder_layer in self.layers:
994
+ if output_hidden_states:
995
+ all_hidden_states += (hidden_states,)
996
+
997
+ if self.gradient_checkpointing and self.training:
998
+ layer_outputs = self._gradient_checkpointing_func(
999
+ decoder_layer.__call__,
1000
+ hidden_states,
1001
+ attention_mask,
1002
+ position_ids,
1003
+ past_key_values,
1004
+ output_attentions,
1005
+ use_cache,
1006
+ cache_position,
1007
+ )
1008
+ else:
1009
+ layer_outputs = decoder_layer(
1010
+ hidden_states,
1011
+ attention_mask=attention_mask,
1012
+ position_ids=position_ids,
1013
+ past_key_value=past_key_values,
1014
+ output_attentions=output_attentions,
1015
+ use_cache=use_cache,
1016
+ cache_position=cache_position,
1017
+ )
1018
+
1019
+ hidden_states = layer_outputs[0]
1020
+
1021
+ if use_cache:
1022
+ next_decoder_cache = layer_outputs[2 if output_attentions else 1]
1023
+
1024
+ if output_attentions:
1025
+ all_self_attns += (layer_outputs[1],)
1026
+
1027
+ hidden_states = self.norm(hidden_states)
1028
+
1029
+ # add hidden states from the last decoder layer
1030
+ if output_hidden_states:
1031
+ all_hidden_states += (hidden_states,)
1032
+
1033
+ next_cache = None
1034
+ if use_cache:
1035
+ next_cache = next_decoder_cache.to_legacy_cache() if use_legacy_cache else next_decoder_cache
1036
+
1037
+ if not return_dict:
1038
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
1039
+ return BaseModelOutputWithPast(
1040
+ last_hidden_state=hidden_states,
1041
+ past_key_values=next_cache,
1042
+ hidden_states=all_hidden_states,
1043
+ attentions=all_self_attns,
1044
+ )
1045
+
1046
+
1047
+ class PLMForCausalLM(PLMPreTrainedModel):
1048
+ _tied_weights_keys = ["lm_head.weight"]
1049
+
1050
+ def __init__(self, config):
1051
+ super().__init__(config)
1052
+ self.model = PLMModel(config)
1053
+ self.vocab_size = config.vocab_size
1054
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1055
+
1056
+ # Initialize weights and apply final processing
1057
+ self.post_init()
1058
+
1059
+ def get_input_embeddings(self):
1060
+ return self.model.embed_tokens
1061
+
1062
+ def set_input_embeddings(self, value):
1063
+ self.model.embed_tokens = value
1064
+
1065
+ def get_output_embeddings(self):
1066
+ return self.lm_head
1067
+
1068
+ def set_output_embeddings(self, new_embeddings):
1069
+ self.lm_head = new_embeddings
1070
+
1071
+ def set_decoder(self, decoder):
1072
+ self.model = decoder
1073
+
1074
+ def get_decoder(self):
1075
+ return self.model
1076
+
1077
+ @add_start_docstrings_to_model_forward(PLM_INPUTS_DOCSTRING)
1078
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
1079
+ def forward(
1080
+ self,
1081
+ input_ids: torch.LongTensor = None,
1082
+ attention_mask: Optional[torch.Tensor] = None,
1083
+ position_ids: Optional[torch.LongTensor] = None,
1084
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1085
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1086
+ labels: Optional[torch.LongTensor] = None,
1087
+ use_cache: Optional[bool] = None,
1088
+ output_attentions: Optional[bool] = None,
1089
+ output_hidden_states: Optional[bool] = None,
1090
+ return_dict: Optional[bool] = None,
1091
+ cache_position: Optional[torch.LongTensor] = None,
1092
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
1093
+ r"""
1094
+ Args:
1095
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1096
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1097
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1098
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1099
+
1100
+ Returns:
1101
+
1102
+ Example:
1103
+
1104
+ ```python
1105
+ >>> from transformers import AutoTokenizer, PLMForCausalLM
1106
+
1107
+ >>> model = PLMForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
1108
+ >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
1109
+
1110
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
1111
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1112
+
1113
+ >>> # Generate
1114
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1115
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1116
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
1117
+ ```"""
1118
+
1119
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1120
+ output_hidden_states = (
1121
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1122
+ )
1123
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1124
+
1125
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1126
+ outputs = self.model(
1127
+ input_ids=input_ids,
1128
+ attention_mask=attention_mask,
1129
+ position_ids=position_ids,
1130
+ past_key_values=past_key_values,
1131
+ inputs_embeds=inputs_embeds,
1132
+ use_cache=use_cache,
1133
+ output_attentions=output_attentions,
1134
+ output_hidden_states=output_hidden_states,
1135
+ return_dict=return_dict,
1136
+ cache_position=cache_position,
1137
+ )
1138
+
1139
+ hidden_states = outputs[0]
1140
+ logits = self.lm_head(hidden_states)
1141
+ logits = logits.float()
1142
+
1143
+ loss = None
1144
+ if labels is not None:
1145
+ # Shift so that tokens < n predict n
1146
+ shift_logits = logits[..., :-1, :].contiguous()
1147
+ shift_labels = labels[..., 1:].contiguous()
1148
+ # Flatten the tokens
1149
+ loss_fct = CrossEntropyLoss()
1150
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1151
+ shift_labels = shift_labels.view(-1)
1152
+ # Enable model parallelism
1153
+ shift_labels = shift_labels.to(shift_logits.device)
1154
+ loss = loss_fct(shift_logits, shift_labels)
1155
+
1156
+ if not return_dict:
1157
+ output = (logits,) + outputs[1:]
1158
+ return (loss,) + output if loss is not None else output
1159
+
1160
+ return CausalLMOutputWithPast(
1161
+ loss=loss,
1162
+ logits=logits,
1163
+ past_key_values=outputs.past_key_values,
1164
+ hidden_states=outputs.hidden_states,
1165
+ attentions=outputs.attentions,
1166
+ )
1167
+
1168
+ def prepare_inputs_for_generation(
1169
+ self,
1170
+ input_ids,
1171
+ past_key_values=None,
1172
+ attention_mask=None,
1173
+ inputs_embeds=None,
1174
+ cache_position=None,
1175
+ use_cache=True,
1176
+ **kwargs,
1177
+ ):
1178
+ past_length = 0
1179
+ # Omit tokens covered by past_key_values
1180
+ if past_key_values is not None:
1181
+ # Past key values are always initialized with a `Cache` object -> no need for if-else anymore
1182
+ past_length = cache_position[0] if cache_position is not None else past_key_values.get_seq_length()
1183
+ max_cache_length = (
1184
+ torch.tensor(past_key_values.get_max_length(), device=input_ids.device)
1185
+ if past_key_values.get_max_length() is not None
1186
+ else None
1187
+ )
1188
+ cache_length = past_length if max_cache_length is None else torch.min(max_cache_length, past_length)
1189
+
1190
+ # Keep only the unprocessed tokens:
1191
+ # 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where
1192
+ # some of the inputs are exclusively passed as part of the cache (e.g. when passing input_embeds as
1193
+ # input)
1194
+ if attention_mask is not None and attention_mask.shape[1] > input_ids.shape[1]:
1195
+ input_ids = input_ids[:, -(attention_mask.shape[1] - past_length) :]
1196
+ # 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens. We can discard
1197
+ # input_ids based on the past_length.
1198
+ elif past_length < input_ids.shape[1]:
1199
+ input_ids = input_ids[:, past_length:]
1200
+ # 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens.
1201
+
1202
+ # If we are about to go beyond the maximum cache length, we need to crop the input attention mask.
1203
+ if (
1204
+ max_cache_length is not None
1205
+ and attention_mask is not None
1206
+ and cache_length + input_ids.shape[1] > max_cache_length
1207
+ ):
1208
+ attention_mask = attention_mask[:, -max_cache_length:]
1209
+
1210
+ position_ids = kwargs.get("position_ids", None)
1211
+ if attention_mask is not None and position_ids is None:
1212
+ # create position_ids on the fly for batch generation
1213
+ position_ids = attention_mask.long().cumsum(-1) - 1
1214
+ position_ids.masked_fill_(attention_mask == 0, 1)
1215
+ if past_key_values:
1216
+ position_ids = position_ids[:, -input_ids.shape[1] :]
1217
+
1218
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1219
+ if inputs_embeds is not None and past_length == 0:
1220
+ model_inputs = {"inputs_embeds": inputs_embeds}
1221
+ else:
1222
+ model_inputs = {"input_ids": input_ids}
1223
+
1224
+ input_length = position_ids.shape[-1] if position_ids is not None else input_ids.shape[-1]
1225
+ if cache_position is None:
1226
+ cache_position = torch.arange(past_length, past_length + input_length, device=input_ids.device)
1227
+ elif use_cache:
1228
+ cache_position = cache_position[-input_length:]
1229
+
1230
+ model_inputs.update(
1231
+ {
1232
+ "position_ids": position_ids,
1233
+ "past_key_values": past_key_values,
1234
+ "use_cache": use_cache,
1235
+ "attention_mask": attention_mask,
1236
+ "cache_position": cache_position,
1237
+ }
1238
+ )
1239
+ return model_inputs
1240
+
1241
+ @staticmethod
1242
+ def _reorder_cache(past_key_values, beam_idx):
1243
+ reordered_past = ()
1244
+ for layer_past in past_key_values:
1245
+ reordered_past += (
1246
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
1247
+ )
1248
+ return reordered_past
1249
+
1250
+
1251
+ @add_start_docstrings(
1252
+ """
1253
+ The PLM Model transformer with a sequence classification head on top (linear layer).
1254
+
1255
+ [`PLMForSequenceClassification`] uses the last token in order to do the classification, as other causal models
1256
+ (e.g. GPT-2) do.
1257
+
1258
+ Since it does classification on the last token, it requires to know the position of the last token. If a
1259
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
1260
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1261
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1262
+ each row of the batch).
1263
+ """,
1264
+ PLM_START_DOCSTRING,
1265
+ )
1266
+ class PLMForSequenceClassification(PLMPreTrainedModel):
1267
+ def __init__(self, config):
1268
+ super().__init__(config)
1269
+ self.num_labels = config.num_labels
1270
+ self.model = PLMModel(config)
1271
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
1272
+
1273
+ # Initialize weights and apply final processing
1274
+ self.post_init()
1275
+
1276
+ def get_input_embeddings(self):
1277
+ return self.model.embed_tokens
1278
+
1279
+ def set_input_embeddings(self, value):
1280
+ self.model.embed_tokens = value
1281
+
1282
+ @add_start_docstrings_to_model_forward(PLM_INPUTS_DOCSTRING)
1283
+ def forward(
1284
+ self,
1285
+ input_ids: torch.LongTensor = None,
1286
+ attention_mask: Optional[torch.Tensor] = None,
1287
+ position_ids: Optional[torch.LongTensor] = None,
1288
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1289
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1290
+ labels: Optional[torch.LongTensor] = None,
1291
+ use_cache: Optional[bool] = None,
1292
+ output_attentions: Optional[bool] = None,
1293
+ output_hidden_states: Optional[bool] = None,
1294
+ return_dict: Optional[bool] = None,
1295
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1296
+ r"""
1297
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1298
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1299
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1300
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1301
+ """
1302
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1303
+
1304
+ transformer_outputs = self.model(
1305
+ input_ids,
1306
+ attention_mask=attention_mask,
1307
+ position_ids=position_ids,
1308
+ past_key_values=past_key_values,
1309
+ inputs_embeds=inputs_embeds,
1310
+ use_cache=use_cache,
1311
+ output_attentions=output_attentions,
1312
+ output_hidden_states=output_hidden_states,
1313
+ return_dict=return_dict,
1314
+ )
1315
+ hidden_states = transformer_outputs[0]
1316
+ logits = self.score(hidden_states)
1317
+
1318
+ if input_ids is not None:
1319
+ batch_size = input_ids.shape[0]
1320
+ else:
1321
+ batch_size = inputs_embeds.shape[0]
1322
+
1323
+ if self.config.pad_token_id is None and batch_size != 1:
1324
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
1325
+ if self.config.pad_token_id is None:
1326
+ sequence_lengths = -1
1327
+ else:
1328
+ if input_ids is not None:
1329
+ # if no pad token found, use modulo instead of reverse indexing for ONNX compatibility
1330
+ sequence_lengths = torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
1331
+ sequence_lengths = sequence_lengths % input_ids.shape[-1]
1332
+ sequence_lengths = sequence_lengths.to(logits.device)
1333
+ else:
1334
+ sequence_lengths = -1
1335
+
1336
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
1337
+
1338
+ loss = None
1339
+ if labels is not None:
1340
+ labels = labels.to(logits.device)
1341
+ if self.config.problem_type is None:
1342
+ if self.num_labels == 1:
1343
+ self.config.problem_type = "regression"
1344
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1345
+ self.config.problem_type = "single_label_classification"
1346
+ else:
1347
+ self.config.problem_type = "multi_label_classification"
1348
+
1349
+ if self.config.problem_type == "regression":
1350
+ loss_fct = MSELoss()
1351
+ if self.num_labels == 1:
1352
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
1353
+ else:
1354
+ loss = loss_fct(pooled_logits, labels)
1355
+ elif self.config.problem_type == "single_label_classification":
1356
+ loss_fct = CrossEntropyLoss()
1357
+ loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
1358
+ elif self.config.problem_type == "multi_label_classification":
1359
+ loss_fct = BCEWithLogitsLoss()
1360
+ loss = loss_fct(pooled_logits, labels)
1361
+ if not return_dict:
1362
+ output = (pooled_logits,) + transformer_outputs[1:]
1363
+ return ((loss,) + output) if loss is not None else output
1364
+
1365
+ return SequenceClassifierOutputWithPast(
1366
+ loss=loss,
1367
+ logits=pooled_logits,
1368
+ past_key_values=transformer_outputs.past_key_values,
1369
+ hidden_states=transformer_outputs.hidden_states,
1370
+ attentions=transformer_outputs.attentions,
1371
+ )
1372
+
1373
+
1374
+ @add_start_docstrings(
1375
+ """
1376
+ The PLM Model transformer with a token classification head on top (a linear layer on top of the hidden-states
1377
+ output) e.g. for Named-Entity-Recognition (NER) tasks.
1378
+ """,
1379
+ PLM_START_DOCSTRING,
1380
+ )
1381
+ # Copied from transformers.models.llama.modeling_llama.LlamaForTokenClassification with Llama->PLM, LLAMA->PLM
1382
+ class PLMForTokenClassification(PLMPreTrainedModel):
1383
+ def __init__(self, config):
1384
+ super().__init__(config)
1385
+ self.num_labels = config.num_labels
1386
+ self.model = PLMModel(config)
1387
+ if getattr(config, "classifier_dropout", None) is not None:
1388
+ classifier_dropout = config.classifier_dropout
1389
+ elif getattr(config, "hidden_dropout", None) is not None:
1390
+ classifier_dropout = config.hidden_dropout
1391
+ else:
1392
+ classifier_dropout = 0.1
1393
+ self.dropout = nn.Dropout(classifier_dropout)
1394
+ self.score = nn.Linear(config.hidden_size, config.num_labels)
1395
+
1396
+ # Initialize weights and apply final processing
1397
+ self.post_init()
1398
+
1399
+ def get_input_embeddings(self):
1400
+ return self.model.embed_tokens
1401
+
1402
+ def set_input_embeddings(self, value):
1403
+ self.model.embed_tokens = value
1404
+
1405
+ @add_start_docstrings_to_model_forward(PLM_INPUTS_DOCSTRING)
1406
+ def forward(
1407
+ self,
1408
+ input_ids: Optional[torch.LongTensor] = None,
1409
+ attention_mask: Optional[torch.Tensor] = None,
1410
+ position_ids: Optional[torch.LongTensor] = None,
1411
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1412
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1413
+ labels: Optional[torch.LongTensor] = None,
1414
+ use_cache: Optional[bool] = None,
1415
+ output_attentions: Optional[bool] = None,
1416
+ output_hidden_states: Optional[bool] = None,
1417
+ return_dict: Optional[bool] = None,
1418
+ ) -> Union[Tuple, TokenClassifierOutput]:
1419
+ r"""
1420
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1421
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1422
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1423
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1424
+ """
1425
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1426
+
1427
+ outputs = self.model(
1428
+ input_ids,
1429
+ attention_mask=attention_mask,
1430
+ position_ids=position_ids,
1431
+ past_key_values=past_key_values,
1432
+ inputs_embeds=inputs_embeds,
1433
+ use_cache=use_cache,
1434
+ output_attentions=output_attentions,
1435
+ output_hidden_states=output_hidden_states,
1436
+ return_dict=return_dict,
1437
+ )
1438
+ sequence_output = outputs[0]
1439
+ sequence_output = self.dropout(sequence_output)
1440
+ logits = self.score(sequence_output)
1441
+
1442
+ loss = None
1443
+ if labels is not None:
1444
+ loss_fct = CrossEntropyLoss()
1445
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
1446
+
1447
+ if not return_dict:
1448
+ output = (logits,) + outputs[2:]
1449
+ return ((loss,) + output) if loss is not None else output
1450
+
1451
+ return TokenClassifierOutput(
1452
+ loss=loss,
1453
+ logits=logits,
1454
+ hidden_states=outputs.hidden_states,
1455
+ attentions=outputs.attentions,
1456
+ )
special_tokens_map.json ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "additional_special_tokens": [
3
+ "<|im_start|>",
4
+ "<|im_end|>"
5
+ ],
6
+ "eos_token": {
7
+ "content": "<|endoftext|>",
8
+ "lstrip": false,
9
+ "normalized": false,
10
+ "rstrip": false,
11
+ "single_word": false
12
+ },
13
+ "pad_token": {
14
+ "content": "<|endoftext|>",
15
+ "lstrip": false,
16
+ "normalized": false,
17
+ "rstrip": false,
18
+ "single_word": false
19
+ }
20
+ }
tokenizer.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9f01b30904856d7c99c70955425f25f60db471ed1a02e6abf2ff22a639e45206
3
+ size 11418366
tokenizer_config.json ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_prefix_space": false,
3
+ "added_tokens_decoder": {
4
+ "151643": {
5
+ "content": "<|endoftext|>",
6
+ "lstrip": false,
7
+ "normalized": false,
8
+ "rstrip": false,
9
+ "single_word": false,
10
+ "special": true
11
+ },
12
+ "151644": {
13
+ "content": "<|im_start|>",
14
+ "lstrip": false,
15
+ "normalized": false,
16
+ "rstrip": false,
17
+ "single_word": false,
18
+ "special": true
19
+ },
20
+ "151645": {
21
+ "content": "<|im_end|>",
22
+ "lstrip": false,
23
+ "normalized": false,
24
+ "rstrip": false,
25
+ "single_word": false,
26
+ "special": true
27
+ }
28
+ },
29
+ "additional_special_tokens": [
30
+ "<|im_start|>",
31
+ "<|im_end|>"
32
+ ],
33
+ "bos_token": null,
34
+ "chat_template": "{% for message in messages %}{% if loop.first and messages[0]['role'] != 'system' %}{{ '<|im_start|>system\nYou are a helpful assistant<|im_end|>\n' }}{% endif %}{{'<|im_start|>' + message['role'] + '\n' + message['content'] + '<|im_end|>' + '\n'}}{% endfor %}{% if add_generation_prompt %}{{ '<|im_start|>assistant\n' }}{% endif %}",
35
+ "clean_up_tokenization_spaces": false,
36
+ "eos_token": "<|endoftext|>",
37
+ "errors": "replace",
38
+ "extra_special_tokens": {},
39
+ "model_max_length": 4096,
40
+ "pad_token": "<|endoftext|>",
41
+ "padding_side": "right",
42
+ "split_special_tokens": false,
43
+ "tokenizer_class": "Qwen2Tokenizer",
44
+ "unk_token": null
45
+ }
vocab.json ADDED
The diff for this file is too large to render. See raw diff