Safetensors
English
Chinese
plm
custom_code
jjw0126 commited on
Commit
c3d9e14
·
verified ·
1 Parent(s): 488d98a

Upload folder using huggingface_hub

Browse files
Files changed (10) hide show
  1. .gitattributes +36 -0
  2. README.md +3 -0
  3. config.json +37 -0
  4. configuration_plm.py +150 -0
  5. merges.txt +0 -0
  6. model.safetensors +3 -0
  7. modeling_plm.py +1461 -0
  8. tokenizer.json +3 -0
  9. tokenizer_config.json +44 -0
  10. vocab.json +0 -0
.gitattributes ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tar filter=lfs diff=lfs merge=lfs -text
29
+ *.tflite filter=lfs diff=lfs merge=lfs -text
30
+ *.tgz filter=lfs diff=lfs merge=lfs -text
31
+ *.wasm filter=lfs diff=lfs merge=lfs -text
32
+ *.xz 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
README.md ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ ---
2
+ license: mit
3
+ ---
config.json ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "PLMForCausalLM"
4
+ ],
5
+ "auto_map": {
6
+ "AutoConfig": "configuration_plm.PLMConfig",
7
+ "AutoModel": "modeling_plm.PLMModel",
8
+ "AutoModelForCausalLM": "modeling_plm.PLMForCausalLM"
9
+ },
10
+ "attention_bias": false,
11
+ "attention_dropout": 0.0,
12
+ "bos_token_id": 151643,
13
+ "eos_token_id": 151643,
14
+ "hidden_act": "relu2",
15
+ "hidden_size": 2048,
16
+ "initializer_range": 0.02,
17
+ "intermediate_size": 8192,
18
+ "kv_lora_rank": 512,
19
+ "max_position_embeddings": 4096,
20
+ "model_type": "plm",
21
+ "num_attention_heads": 16,
22
+ "num_key_value_heads": 16,
23
+ "num_hidden_layers": 32,
24
+ "q_lora_rank": null,
25
+ "qk_nope_head_dim": 128,
26
+ "qk_rope_head_dim": 64,
27
+ "rms_norm_eps": 1e-06,
28
+ "rope_scaling": null,
29
+ "pretraining_tp": 1,
30
+ "rope_theta": 100000.0,
31
+ "tie_word_embeddings": true,
32
+ "torch_dtype": "bfloat16",
33
+ "transformers_version": "4.40.1",
34
+ "use_cache": true,
35
+ "v_head_dim": 128,
36
+ "vocab_size": 151936
37
+ }
configuration_plm.py ADDED
@@ -0,0 +1,150 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ **kwargs,
120
+ ):
121
+ self.vocab_size = vocab_size
122
+ self.max_position_embeddings = max_position_embeddings
123
+ self.hidden_size = hidden_size
124
+ self.intermediate_size = intermediate_size
125
+ self.num_hidden_layers = num_hidden_layers
126
+ self.num_attention_heads = num_attention_heads
127
+ self.kv_lora_rank = kv_lora_rank
128
+ self.q_lora_rank = q_lora_rank
129
+ self.qk_rope_head_dim = qk_rope_head_dim
130
+ self.v_head_dim = v_head_dim
131
+ self.qk_nope_head_dim = qk_nope_head_dim
132
+ # for backward compatibility
133
+ if num_key_value_heads is None:
134
+ num_key_value_heads = num_attention_heads
135
+
136
+ self.num_key_value_heads = num_key_value_heads
137
+ self.hidden_act = hidden_act
138
+ self.initializer_range = initializer_range
139
+ self.rms_norm_eps = rms_norm_eps
140
+ self.pretraining_tp = pretraining_tp
141
+ self.use_cache = use_cache
142
+ self.rope_theta = rope_theta
143
+ self.rope_scaling = rope_scaling
144
+ self.attention_bias = attention_bias
145
+ self.attention_dropout = attention_dropout
146
+
147
+ super().__init__(
148
+ tie_word_embeddings=tie_word_embeddings,
149
+ **kwargs,
150
+ )
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:57e2148e5abfb7ac5a3c442895d73fbb8b234e0f0f088f0c84fb1c85ef31ff83
3
+ size 3650950536
modeling_plm.py ADDED
@@ -0,0 +1,1461 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ if config.use_sliding_window and config._attn_implementation != "flash_attention_2":
695
+ logger.warning_once(
696
+ f"Sliding Window Attention is enabled but not implemented for `{config._attn_implementation}`; "
697
+ "unexpected results may be encountered."
698
+ )
699
+ self.self_attn = PLM_ATTENTION_CLASSES[config._attn_implementation](config, layer_idx)
700
+ self.mlp = PLMMLP(config)
701
+ self.input_layernorm = PLMRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
702
+ self.post_attention_layernorm = PLMRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
703
+
704
+ def forward(
705
+ self,
706
+ hidden_states: torch.Tensor,
707
+ attention_mask: Optional[torch.Tensor] = None,
708
+ position_ids: Optional[torch.LongTensor] = None,
709
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
710
+ output_attentions: Optional[bool] = False,
711
+ use_cache: Optional[bool] = False,
712
+ cache_position: Optional[torch.LongTensor] = None,
713
+ **kwargs,
714
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
715
+ """
716
+ Args:
717
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
718
+ attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
719
+ `(batch, sequence_length)` where padding elements are indicated by 0.
720
+ output_attentions (`bool`, *optional*):
721
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
722
+ returned tensors for more detail.
723
+ use_cache (`bool`, *optional*):
724
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
725
+ (see `past_key_values`).
726
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
727
+ cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
728
+ Indices depicting the position of the input sequence tokens in the sequence.
729
+ kwargs (`dict`, *optional*):
730
+ Arbitrary kwargs to be ignored, used for FSDP and other methods that injects code
731
+ into the model
732
+ """
733
+
734
+ residual = hidden_states
735
+
736
+ hidden_states = self.input_layernorm(hidden_states)
737
+
738
+ # Self Attention
739
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
740
+ hidden_states=hidden_states,
741
+ attention_mask=attention_mask,
742
+ position_ids=position_ids,
743
+ past_key_value=past_key_value,
744
+ output_attentions=output_attentions,
745
+ use_cache=use_cache,
746
+ cache_position=cache_position,
747
+ )
748
+ hidden_states = residual + hidden_states
749
+
750
+ # Fully Connected
751
+ residual = hidden_states
752
+ hidden_states = self.post_attention_layernorm(hidden_states)
753
+ hidden_states = self.mlp(hidden_states)
754
+ hidden_states = residual + hidden_states
755
+
756
+ outputs = (hidden_states,)
757
+
758
+ if output_attentions:
759
+ outputs += (self_attn_weights,)
760
+
761
+ if use_cache:
762
+ outputs += (present_key_value,)
763
+
764
+ return outputs
765
+
766
+
767
+ PLM_START_DOCSTRING = r"""
768
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
769
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
770
+ etc.)
771
+
772
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
773
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
774
+ and behavior.
775
+
776
+ Parameters:
777
+ config ([`PLMConfig`]):
778
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
779
+ load the weights associated with the model, only the configuration. Check out the
780
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
781
+ """
782
+
783
+
784
+ @add_start_docstrings(
785
+ "The bare PLM Model outputting raw hidden-states without any specific head on top.",
786
+ PLM_START_DOCSTRING,
787
+ )
788
+ class PLMPreTrainedModel(PreTrainedModel):
789
+ config_class = PLMConfig
790
+ base_model_prefix = "model"
791
+ supports_gradient_checkpointing = True
792
+ _no_split_modules = ["PLMDecoderLayer"]
793
+ _skip_keys_device_placement = "past_key_values"
794
+ _supports_flash_attn_2 = True
795
+ _supports_cache_class = True
796
+
797
+ def _init_weights(self, module):
798
+ std = self.config.initializer_range
799
+ if isinstance(module, nn.Linear):
800
+ module.weight.data.normal_(mean=0.0, std=std)
801
+ if module.bias is not None:
802
+ module.bias.data.zero_()
803
+ elif isinstance(module, nn.Embedding):
804
+ module.weight.data.normal_(mean=0.0, std=std)
805
+ if module.padding_idx is not None:
806
+ module.weight.data[module.padding_idx].zero_()
807
+
808
+
809
+ PLM_INPUTS_DOCSTRING = r"""
810
+ Args:
811
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
812
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
813
+ it.
814
+
815
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
816
+ [`PreTrainedTokenizer.__call__`] for details.
817
+
818
+ [What are input IDs?](../glossary#input-ids)
819
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
820
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
821
+
822
+ - 1 for tokens that are **not masked**,
823
+ - 0 for tokens that are **masked**.
824
+
825
+ [What are attention masks?](../glossary#attention-mask)
826
+
827
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
828
+ [`PreTrainedTokenizer.__call__`] for details.
829
+
830
+ If `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
831
+ `past_key_values`).
832
+
833
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
834
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
835
+ information on the default strategy.
836
+
837
+ - 1 indicates the head is **not masked**,
838
+ - 0 indicates the head is **masked**.
839
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
840
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
841
+ config.n_positions - 1]`.
842
+
843
+ [What are position IDs?](../glossary#position-ids)
844
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
845
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
846
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
847
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
848
+
849
+ Two formats are allowed:
850
+ - a [`~cache_utils.Cache`] instance;
851
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
852
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
853
+ cache format.
854
+
855
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
856
+ legacy cache format will be returned.
857
+
858
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
859
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
860
+ of shape `(batch_size, sequence_length)`.
861
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
862
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
863
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
864
+ model's internal embedding lookup matrix.
865
+ use_cache (`bool`, *optional*):
866
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
867
+ `past_key_values`).
868
+ output_attentions (`bool`, *optional*):
869
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
870
+ tensors for more detail.
871
+ output_hidden_states (`bool`, *optional*):
872
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
873
+ more detail.
874
+ return_dict (`bool`, *optional*):
875
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
876
+ cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
877
+ Indices depicting the position of the input sequence tokens in the sequence. Contrarily to `position_ids`,
878
+ this tensor is not affected by padding. It is used to update the cache in the correct position and to infer
879
+ the complete sequence length.
880
+ """
881
+
882
+
883
+ @add_start_docstrings(
884
+ "The bare PLM Model outputting raw hidden-states without any specific head on top.",
885
+ PLM_START_DOCSTRING,
886
+ )
887
+ class PLMModel(PLMPreTrainedModel):
888
+ """
889
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`PLMDecoderLayer`]
890
+
891
+ Args:
892
+ config: PLMConfig
893
+ """
894
+
895
+ def __init__(self, config: PLMConfig):
896
+ super().__init__(config)
897
+ self.padding_idx = config.pad_token_id
898
+ self.vocab_size = config.vocab_size
899
+
900
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
901
+ self.layers = nn.ModuleList(
902
+ [PLMDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
903
+ )
904
+ self._attn_implementation = config._attn_implementation
905
+ self.norm = PLMRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
906
+
907
+ self.gradient_checkpointing = False
908
+ # Initialize weights and apply final processing
909
+ self.post_init()
910
+
911
+ def get_input_embeddings(self):
912
+ return self.embed_tokens
913
+
914
+ def set_input_embeddings(self, value):
915
+ self.embed_tokens = value
916
+
917
+ @add_start_docstrings_to_model_forward(PLM_INPUTS_DOCSTRING)
918
+ def forward(
919
+ self,
920
+ input_ids: torch.LongTensor = None,
921
+ attention_mask: Optional[torch.Tensor] = None,
922
+ position_ids: Optional[torch.LongTensor] = None,
923
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
924
+ inputs_embeds: Optional[torch.FloatTensor] = None,
925
+ use_cache: Optional[bool] = None,
926
+ output_attentions: Optional[bool] = None,
927
+ output_hidden_states: Optional[bool] = None,
928
+ return_dict: Optional[bool] = None,
929
+ cache_position: Optional[torch.LongTensor] = None,
930
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
931
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
932
+ output_hidden_states = (
933
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
934
+ )
935
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
936
+
937
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
938
+
939
+ # retrieve input_ids and inputs_embeds
940
+ if (input_ids is None) ^ (inputs_embeds is not None):
941
+ raise ValueError(
942
+ "You cannot specify both input_ids and inputs_embeds at the same time, and must specify either one"
943
+ )
944
+ elif input_ids is not None:
945
+ batch_size, seq_length = input_ids.shape[:2]
946
+ elif inputs_embeds is not None:
947
+ batch_size, seq_length = inputs_embeds.shape[:2]
948
+ else:
949
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
950
+
951
+ if self.gradient_checkpointing and self.training:
952
+ if use_cache:
953
+ logger.warning_once(
954
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
955
+ )
956
+ use_cache = False
957
+
958
+ past_key_values_length = 0
959
+ if use_cache:
960
+ use_legacy_cache = not isinstance(past_key_values, Cache)
961
+ if use_legacy_cache:
962
+ past_key_values = DynamicCache.from_legacy_cache(past_key_values)
963
+ past_key_values_length = past_key_values.get_usable_length(seq_length)
964
+
965
+ if inputs_embeds is None:
966
+ inputs_embeds = self.embed_tokens(input_ids)
967
+
968
+ if cache_position is None:
969
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
970
+ cache_position = torch.arange(
971
+ past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
972
+ )
973
+ if position_ids is None:
974
+ position_ids = cache_position.unsqueeze(0)
975
+ if self.config._attn_implementation == "flash_attention_2":
976
+ # 2d mask is passed through the layers
977
+ attention_mask = (
978
+ attention_mask
979
+ if (attention_mask is not None and 0 in attention_mask)
980
+ else None
981
+ )
982
+ else:
983
+ # 4d mask is passed through the layers
984
+ attention_mask = _prepare_4d_causal_attention_mask(
985
+ attention_mask,
986
+ (batch_size, seq_length),
987
+ inputs_embeds,
988
+ past_key_values_length,
989
+ )
990
+
991
+ hidden_states = inputs_embeds
992
+
993
+ # decoder layers
994
+ all_hidden_states = () if output_hidden_states else None
995
+ all_self_attns = () if output_attentions else None
996
+ next_decoder_cache = None
997
+
998
+ for decoder_layer in self.layers:
999
+ if output_hidden_states:
1000
+ all_hidden_states += (hidden_states,)
1001
+
1002
+ if self.gradient_checkpointing and self.training:
1003
+ layer_outputs = self._gradient_checkpointing_func(
1004
+ decoder_layer.__call__,
1005
+ hidden_states,
1006
+ attention_mask,
1007
+ position_ids,
1008
+ past_key_values,
1009
+ output_attentions,
1010
+ use_cache,
1011
+ cache_position,
1012
+ )
1013
+ else:
1014
+ layer_outputs = decoder_layer(
1015
+ hidden_states,
1016
+ attention_mask=attention_mask,
1017
+ position_ids=position_ids,
1018
+ past_key_value=past_key_values,
1019
+ output_attentions=output_attentions,
1020
+ use_cache=use_cache,
1021
+ cache_position=cache_position,
1022
+ )
1023
+
1024
+ hidden_states = layer_outputs[0]
1025
+
1026
+ if use_cache:
1027
+ next_decoder_cache = layer_outputs[2 if output_attentions else 1]
1028
+
1029
+ if output_attentions:
1030
+ all_self_attns += (layer_outputs[1],)
1031
+
1032
+ hidden_states = self.norm(hidden_states)
1033
+
1034
+ # add hidden states from the last decoder layer
1035
+ if output_hidden_states:
1036
+ all_hidden_states += (hidden_states,)
1037
+
1038
+ next_cache = None
1039
+ if use_cache:
1040
+ next_cache = next_decoder_cache.to_legacy_cache() if use_legacy_cache else next_decoder_cache
1041
+
1042
+ if not return_dict:
1043
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
1044
+ return BaseModelOutputWithPast(
1045
+ last_hidden_state=hidden_states,
1046
+ past_key_values=next_cache,
1047
+ hidden_states=all_hidden_states,
1048
+ attentions=all_self_attns,
1049
+ )
1050
+
1051
+
1052
+ class PLMForCausalLM(PLMPreTrainedModel):
1053
+ _tied_weights_keys = ["lm_head.weight"]
1054
+
1055
+ def __init__(self, config):
1056
+ super().__init__(config)
1057
+ self.model = PLMModel(config)
1058
+ self.vocab_size = config.vocab_size
1059
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1060
+
1061
+ # Initialize weights and apply final processing
1062
+ self.post_init()
1063
+
1064
+ def get_input_embeddings(self):
1065
+ return self.model.embed_tokens
1066
+
1067
+ def set_input_embeddings(self, value):
1068
+ self.model.embed_tokens = value
1069
+
1070
+ def get_output_embeddings(self):
1071
+ return self.lm_head
1072
+
1073
+ def set_output_embeddings(self, new_embeddings):
1074
+ self.lm_head = new_embeddings
1075
+
1076
+ def set_decoder(self, decoder):
1077
+ self.model = decoder
1078
+
1079
+ def get_decoder(self):
1080
+ return self.model
1081
+
1082
+ @add_start_docstrings_to_model_forward(PLM_INPUTS_DOCSTRING)
1083
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
1084
+ def forward(
1085
+ self,
1086
+ input_ids: torch.LongTensor = None,
1087
+ attention_mask: Optional[torch.Tensor] = None,
1088
+ position_ids: Optional[torch.LongTensor] = None,
1089
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1090
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1091
+ labels: Optional[torch.LongTensor] = None,
1092
+ use_cache: Optional[bool] = None,
1093
+ output_attentions: Optional[bool] = None,
1094
+ output_hidden_states: Optional[bool] = None,
1095
+ return_dict: Optional[bool] = None,
1096
+ cache_position: Optional[torch.LongTensor] = None,
1097
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
1098
+ r"""
1099
+ Args:
1100
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1101
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1102
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1103
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1104
+
1105
+ Returns:
1106
+
1107
+ Example:
1108
+
1109
+ ```python
1110
+ >>> from transformers import AutoTokenizer, PLMForCausalLM
1111
+
1112
+ >>> model = PLMForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
1113
+ >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
1114
+
1115
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
1116
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1117
+
1118
+ >>> # Generate
1119
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1120
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1121
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
1122
+ ```"""
1123
+
1124
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1125
+ output_hidden_states = (
1126
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1127
+ )
1128
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1129
+
1130
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1131
+ outputs = self.model(
1132
+ input_ids=input_ids,
1133
+ attention_mask=attention_mask,
1134
+ position_ids=position_ids,
1135
+ past_key_values=past_key_values,
1136
+ inputs_embeds=inputs_embeds,
1137
+ use_cache=use_cache,
1138
+ output_attentions=output_attentions,
1139
+ output_hidden_states=output_hidden_states,
1140
+ return_dict=return_dict,
1141
+ cache_position=cache_position,
1142
+ )
1143
+
1144
+ hidden_states = outputs[0]
1145
+ logits = self.lm_head(hidden_states)
1146
+ logits = logits.float()
1147
+
1148
+ loss = None
1149
+ if labels is not None:
1150
+ # Shift so that tokens < n predict n
1151
+ shift_logits = logits[..., :-1, :].contiguous()
1152
+ shift_labels = labels[..., 1:].contiguous()
1153
+ # Flatten the tokens
1154
+ loss_fct = CrossEntropyLoss()
1155
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1156
+ shift_labels = shift_labels.view(-1)
1157
+ # Enable model parallelism
1158
+ shift_labels = shift_labels.to(shift_logits.device)
1159
+ loss = loss_fct(shift_logits, shift_labels)
1160
+
1161
+ if not return_dict:
1162
+ output = (logits,) + outputs[1:]
1163
+ return (loss,) + output if loss is not None else output
1164
+
1165
+ return CausalLMOutputWithPast(
1166
+ loss=loss,
1167
+ logits=logits,
1168
+ past_key_values=outputs.past_key_values,
1169
+ hidden_states=outputs.hidden_states,
1170
+ attentions=outputs.attentions,
1171
+ )
1172
+
1173
+ def prepare_inputs_for_generation(
1174
+ self,
1175
+ input_ids,
1176
+ past_key_values=None,
1177
+ attention_mask=None,
1178
+ inputs_embeds=None,
1179
+ cache_position=None,
1180
+ use_cache=True,
1181
+ **kwargs,
1182
+ ):
1183
+ past_length = 0
1184
+ # Omit tokens covered by past_key_values
1185
+ if past_key_values is not None:
1186
+ # Past key values are always initialized with a `Cache` object -> no need for if-else anymore
1187
+ past_length = cache_position[0] if cache_position is not None else past_key_values.get_seq_length()
1188
+ max_cache_length = (
1189
+ torch.tensor(past_key_values.get_max_length(), device=input_ids.device)
1190
+ if past_key_values.get_max_length() is not None
1191
+ else None
1192
+ )
1193
+ cache_length = past_length if max_cache_length is None else torch.min(max_cache_length, past_length)
1194
+
1195
+ # Keep only the unprocessed tokens:
1196
+ # 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where
1197
+ # some of the inputs are exclusively passed as part of the cache (e.g. when passing input_embeds as
1198
+ # input)
1199
+ if attention_mask is not None and attention_mask.shape[1] > input_ids.shape[1]:
1200
+ input_ids = input_ids[:, -(attention_mask.shape[1] - past_length) :]
1201
+ # 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens. We can discard
1202
+ # input_ids based on the past_length.
1203
+ elif past_length < input_ids.shape[1]:
1204
+ input_ids = input_ids[:, past_length:]
1205
+ # 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens.
1206
+
1207
+ # If we are about to go beyond the maximum cache length, we need to crop the input attention mask.
1208
+ if (
1209
+ max_cache_length is not None
1210
+ and attention_mask is not None
1211
+ and cache_length + input_ids.shape[1] > max_cache_length
1212
+ ):
1213
+ attention_mask = attention_mask[:, -max_cache_length:]
1214
+
1215
+ position_ids = kwargs.get("position_ids", None)
1216
+ if attention_mask is not None and position_ids is None:
1217
+ # create position_ids on the fly for batch generation
1218
+ position_ids = attention_mask.long().cumsum(-1) - 1
1219
+ position_ids.masked_fill_(attention_mask == 0, 1)
1220
+ if past_key_values:
1221
+ position_ids = position_ids[:, -input_ids.shape[1] :]
1222
+
1223
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1224
+ if inputs_embeds is not None and past_length == 0:
1225
+ model_inputs = {"inputs_embeds": inputs_embeds}
1226
+ else:
1227
+ model_inputs = {"input_ids": input_ids}
1228
+
1229
+ input_length = position_ids.shape[-1] if position_ids is not None else input_ids.shape[-1]
1230
+ if cache_position is None:
1231
+ cache_position = torch.arange(past_length, past_length + input_length, device=input_ids.device)
1232
+ elif use_cache:
1233
+ cache_position = cache_position[-input_length:]
1234
+
1235
+ model_inputs.update(
1236
+ {
1237
+ "position_ids": position_ids,
1238
+ "past_key_values": past_key_values,
1239
+ "use_cache": use_cache,
1240
+ "attention_mask": attention_mask,
1241
+ "cache_position": cache_position,
1242
+ }
1243
+ )
1244
+ return model_inputs
1245
+
1246
+ @staticmethod
1247
+ def _reorder_cache(past_key_values, beam_idx):
1248
+ reordered_past = ()
1249
+ for layer_past in past_key_values:
1250
+ reordered_past += (
1251
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
1252
+ )
1253
+ return reordered_past
1254
+
1255
+
1256
+ @add_start_docstrings(
1257
+ """
1258
+ The PLM Model transformer with a sequence classification head on top (linear layer).
1259
+
1260
+ [`PLMForSequenceClassification`] uses the last token in order to do the classification, as other causal models
1261
+ (e.g. GPT-2) do.
1262
+
1263
+ Since it does classification on the last token, it requires to know the position of the last token. If a
1264
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
1265
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1266
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1267
+ each row of the batch).
1268
+ """,
1269
+ PLM_START_DOCSTRING,
1270
+ )
1271
+ class PLMForSequenceClassification(PLMPreTrainedModel):
1272
+ def __init__(self, config):
1273
+ super().__init__(config)
1274
+ self.num_labels = config.num_labels
1275
+ self.model = PLMModel(config)
1276
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
1277
+
1278
+ # Initialize weights and apply final processing
1279
+ self.post_init()
1280
+
1281
+ def get_input_embeddings(self):
1282
+ return self.model.embed_tokens
1283
+
1284
+ def set_input_embeddings(self, value):
1285
+ self.model.embed_tokens = value
1286
+
1287
+ @add_start_docstrings_to_model_forward(PLM_INPUTS_DOCSTRING)
1288
+ def forward(
1289
+ self,
1290
+ input_ids: torch.LongTensor = None,
1291
+ attention_mask: Optional[torch.Tensor] = None,
1292
+ position_ids: Optional[torch.LongTensor] = None,
1293
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1294
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1295
+ labels: Optional[torch.LongTensor] = None,
1296
+ use_cache: Optional[bool] = None,
1297
+ output_attentions: Optional[bool] = None,
1298
+ output_hidden_states: Optional[bool] = None,
1299
+ return_dict: Optional[bool] = None,
1300
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1301
+ r"""
1302
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1303
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1304
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1305
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1306
+ """
1307
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1308
+
1309
+ transformer_outputs = self.model(
1310
+ input_ids,
1311
+ attention_mask=attention_mask,
1312
+ position_ids=position_ids,
1313
+ past_key_values=past_key_values,
1314
+ inputs_embeds=inputs_embeds,
1315
+ use_cache=use_cache,
1316
+ output_attentions=output_attentions,
1317
+ output_hidden_states=output_hidden_states,
1318
+ return_dict=return_dict,
1319
+ )
1320
+ hidden_states = transformer_outputs[0]
1321
+ logits = self.score(hidden_states)
1322
+
1323
+ if input_ids is not None:
1324
+ batch_size = input_ids.shape[0]
1325
+ else:
1326
+ batch_size = inputs_embeds.shape[0]
1327
+
1328
+ if self.config.pad_token_id is None and batch_size != 1:
1329
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
1330
+ if self.config.pad_token_id is None:
1331
+ sequence_lengths = -1
1332
+ else:
1333
+ if input_ids is not None:
1334
+ # if no pad token found, use modulo instead of reverse indexing for ONNX compatibility
1335
+ sequence_lengths = torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
1336
+ sequence_lengths = sequence_lengths % input_ids.shape[-1]
1337
+ sequence_lengths = sequence_lengths.to(logits.device)
1338
+ else:
1339
+ sequence_lengths = -1
1340
+
1341
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
1342
+
1343
+ loss = None
1344
+ if labels is not None:
1345
+ labels = labels.to(logits.device)
1346
+ if self.config.problem_type is None:
1347
+ if self.num_labels == 1:
1348
+ self.config.problem_type = "regression"
1349
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1350
+ self.config.problem_type = "single_label_classification"
1351
+ else:
1352
+ self.config.problem_type = "multi_label_classification"
1353
+
1354
+ if self.config.problem_type == "regression":
1355
+ loss_fct = MSELoss()
1356
+ if self.num_labels == 1:
1357
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
1358
+ else:
1359
+ loss = loss_fct(pooled_logits, labels)
1360
+ elif self.config.problem_type == "single_label_classification":
1361
+ loss_fct = CrossEntropyLoss()
1362
+ loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
1363
+ elif self.config.problem_type == "multi_label_classification":
1364
+ loss_fct = BCEWithLogitsLoss()
1365
+ loss = loss_fct(pooled_logits, labels)
1366
+ if not return_dict:
1367
+ output = (pooled_logits,) + transformer_outputs[1:]
1368
+ return ((loss,) + output) if loss is not None else output
1369
+
1370
+ return SequenceClassifierOutputWithPast(
1371
+ loss=loss,
1372
+ logits=pooled_logits,
1373
+ past_key_values=transformer_outputs.past_key_values,
1374
+ hidden_states=transformer_outputs.hidden_states,
1375
+ attentions=transformer_outputs.attentions,
1376
+ )
1377
+
1378
+
1379
+ @add_start_docstrings(
1380
+ """
1381
+ The PLM Model transformer with a token classification head on top (a linear layer on top of the hidden-states
1382
+ output) e.g. for Named-Entity-Recognition (NER) tasks.
1383
+ """,
1384
+ PLM_START_DOCSTRING,
1385
+ )
1386
+ # Copied from transformers.models.llama.modeling_llama.LlamaForTokenClassification with Llama->PLM, LLAMA->PLM
1387
+ class PLMForTokenClassification(PLMPreTrainedModel):
1388
+ def __init__(self, config):
1389
+ super().__init__(config)
1390
+ self.num_labels = config.num_labels
1391
+ self.model = PLMModel(config)
1392
+ if getattr(config, "classifier_dropout", None) is not None:
1393
+ classifier_dropout = config.classifier_dropout
1394
+ elif getattr(config, "hidden_dropout", None) is not None:
1395
+ classifier_dropout = config.hidden_dropout
1396
+ else:
1397
+ classifier_dropout = 0.1
1398
+ self.dropout = nn.Dropout(classifier_dropout)
1399
+ self.score = nn.Linear(config.hidden_size, config.num_labels)
1400
+
1401
+ # Initialize weights and apply final processing
1402
+ self.post_init()
1403
+
1404
+ def get_input_embeddings(self):
1405
+ return self.model.embed_tokens
1406
+
1407
+ def set_input_embeddings(self, value):
1408
+ self.model.embed_tokens = value
1409
+
1410
+ @add_start_docstrings_to_model_forward(PLM_INPUTS_DOCSTRING)
1411
+ def forward(
1412
+ self,
1413
+ input_ids: Optional[torch.LongTensor] = None,
1414
+ attention_mask: Optional[torch.Tensor] = None,
1415
+ position_ids: Optional[torch.LongTensor] = None,
1416
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1417
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1418
+ labels: Optional[torch.LongTensor] = None,
1419
+ use_cache: Optional[bool] = None,
1420
+ output_attentions: Optional[bool] = None,
1421
+ output_hidden_states: Optional[bool] = None,
1422
+ return_dict: Optional[bool] = None,
1423
+ ) -> Union[Tuple, TokenClassifierOutput]:
1424
+ r"""
1425
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1426
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1427
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1428
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1429
+ """
1430
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1431
+
1432
+ outputs = self.model(
1433
+ input_ids,
1434
+ attention_mask=attention_mask,
1435
+ position_ids=position_ids,
1436
+ past_key_values=past_key_values,
1437
+ inputs_embeds=inputs_embeds,
1438
+ use_cache=use_cache,
1439
+ output_attentions=output_attentions,
1440
+ output_hidden_states=output_hidden_states,
1441
+ return_dict=return_dict,
1442
+ )
1443
+ sequence_output = outputs[0]
1444
+ sequence_output = self.dropout(sequence_output)
1445
+ logits = self.score(sequence_output)
1446
+
1447
+ loss = None
1448
+ if labels is not None:
1449
+ loss_fct = CrossEntropyLoss()
1450
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
1451
+
1452
+ if not return_dict:
1453
+ output = (logits,) + outputs[2:]
1454
+ return ((loss,) + output) if loss is not None else output
1455
+
1456
+ return TokenClassifierOutput(
1457
+ loss=loss,
1458
+ logits=logits,
1459
+ hidden_states=outputs.hidden_states,
1460
+ attentions=outputs.attentions,
1461
+ )
tokenizer.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:bcfe42da0a4497e8b2b172c1f9f4ec423a46dc12907f4349c55025f670422ba9
3
+ size 11418266
tokenizer_config.json ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ "model_max_length": 4096,
39
+ "pad_token": "<|endoftext|>",
40
+ "padding_side": "right",
41
+ "split_special_tokens": false,
42
+ "tokenizer_class": "Qwen2Tokenizer",
43
+ "unk_token": null
44
+ }
vocab.json ADDED
The diff for this file is too large to render. See raw diff