nilabhra commited on
Commit
bcf87a6
1 Parent(s): aac04bc

Upload folder using huggingface_hub

Browse files
.ipynb_checkpoints/README-checkpoint.md ADDED
@@ -0,0 +1,156 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ library_name: transformers
3
+ tags: []
4
+ ---
5
+
6
+ # Falcon-11B-Base-V1.1
7
+ The Falcon-11B-Base-V1 Large Language Model (LLM) is a pretrained generative text model with 11.1 billion parameters.
8
+
9
+ ## Model Specifications
10
+ - Base Model (not instruct tuned)
11
+ - Flash Attention 2
12
+ - Untied LM-Head and Word Embeddings (This adds 300M parameters over the 10.8B)
13
+ - 11.1B Parameters
14
+ - Rope Theta 500,042
15
+
16
+
17
+
18
+ ### Inference Model
19
+ Inference the model with `trust_remote_code=True` to use our modeling code. We show an example below with the most basic hyperparameters.
20
+
21
+ ```python
22
+ import os
23
+ import sys
24
+ import torch
25
+ from transformers import AutoTokenizer, AutoModelForCausalLM
26
+
27
+ #Load Model and Tokenizer
28
+ base_model_id = "ruliadai/falcon-base-v1.1"
29
+
30
+ model = AutoModelForCausalLM.from_pretrained(
31
+ base_model_id,
32
+ device_map="auto",
33
+ torch_dtype=torch.bfloat16,
34
+ trust_remote_code=True,
35
+ attn_implementation="flash_attention_2",
36
+ )
37
+
38
+ tokenizer = AutoTokenizer.from_pretrained(
39
+ base_model_id,
40
+ padding_side="left",
41
+ device_map="auto",
42
+ )
43
+ tokenizer.pad_token = tokenizer.eos_token
44
+
45
+ #Run Inference
46
+ while True:
47
+ prompt = input("Instruction: ")
48
+ model_input = tokenizer(prompt, return_tensors="pt", return_token_type_ids=False)
49
+ model.eval()
50
+ print(model.generation_config)
51
+ with torch.no_grad():
52
+ print(tokenizer.decode(
53
+ model.generate(**model_input,max_new_tokens=800, temperature=0.0, do_sample=False, repetition_penalty=1.15)[0], use_cache=True)
54
+ )
55
+ ```
56
+
57
+ ### How to run inference
58
+
59
+ Setup and activate your venv/or conda env
60
+
61
+ ```bash
62
+ python3 -m venv env \
63
+ && source env/bin/activate
64
+ ```
65
+
66
+ Install torch:
67
+ ```bash
68
+ pip3 install torch torchvision torchaudio
69
+ ```
70
+ Note that you may need to install torch according to your system req/drivers (https://pytorch.org/get-started/locally/)
71
+
72
+
73
+ Install requirements:
74
+ ```bash
75
+ pip3 install --upgrade --force-reinstall transformers accelerate flash-attn hf_transfer
76
+ ```
77
+
78
+ Run script:
79
+
80
+ ```bash
81
+
82
+ HF_HUB_ENABLE_HF_TRANSFER=1 HF_TOKEN=<YOUR_HF_TOKEN> python3 inference.py
83
+ ```
84
+
85
+
86
+ If flash-attn is broken:
87
+ ```bash
88
+ pip3 uninstall flash-attn
89
+ pip3 cache purge
90
+ pip3 install flash-attn
91
+ ```
92
+
93
+
94
+ ## Model Evaluation
95
+
96
+ ### Measured Benchmarks (by Ruliad)
97
+
98
+ | MODEL | AVERAGE | MMLU (5-s) | TQA (0-s) | ARC (25-s) | GSM8K (5-s)| HS (10-s) | WG (5-s) |
99
+ | --------------- | ---------- | ---------- | ---------- | ---------- | ---------- | ---------- | ---------- |
100
+ | Falcon-Base-v1.1 | 0.6440 | 0.5683 | 0.5263 | 0.6041 | 0.5542 | 0.8280 | 0.7806 |
101
+ | Llama-3-8B | 0.6300 | 0.6513 | 0.4385 | 0.5904 | 0.5034 | 0.8223 | 0.7751 |
102
+ | Mistral-7B-v0.1 | 0.6130 | 0.6233 | 0.4258 | 0.6220 | 0.3859 | 0.8332 | 0.7861 |
103
+
104
+ ### Evaluation Replication
105
+
106
+ **Install Eval Harness**
107
+
108
+ To install the `lm-eval` package from the github repository, run:
109
+ ```bash
110
+ git clone https://github.com/EleutherAI/lm-evaluation-harness
111
+ cd lm-evaluation-harness
112
+ pip install -e .
113
+ pip install hf_transfer accelerate transformers flash_attn
114
+ ```
115
+ **Benchmarking**
116
+
117
+ To evaluate our model:
118
+
119
+ Evaluating MMLU, GSM8K and WG on 5-Shot
120
+ ```bash
121
+ HF_HUB_ENABLE_HF_TRANSFER=1 HF_TOKEN=<YOUR_HF_TOKEN> accelerate launch -m lm_eval --model hf-auto \
122
+ --model_args pretrained=ruliadai/falcon-base-v1.1,trust_remote_code=True \
123
+ --tasks mmlu,gsm8k,winogrande \
124
+ --device cuda:0 \
125
+ --num_fewshot 5 \
126
+ --batch_size 1
127
+ ```
128
+
129
+ Evaluating TQA on 0-Shot
130
+ ```bash
131
+ HF_HUB_ENABLE_HF_TRANSFER=1 HF_TOKEN=<YOUR_HF_TOKEN> accelerate launch -m lm_eval --model hf-auto \
132
+ --model_args pretrained=ruliadai/falcon-base-v1.1,trust_remote_code=True \
133
+ --tasks truthfulqa_mc2 \
134
+ --device cuda:0 \
135
+ --batch_size 1
136
+ ```
137
+
138
+ Evaluating HS on 10-Shot
139
+ ```bash
140
+ HF_HUB_ENABLE_HF_TRANSFER=1 HF_TOKEN=<YOUR_HF_TOKEN> accelerate launch -m lm_eval --model hf-auto \
141
+ --model_args pretrained=ruliadai/falcon-base-v1.1,trust_remote_code=True \
142
+ --tasks hellaswag \
143
+ --device cuda:0 \
144
+ --num_fewshot 10 \
145
+ --batch_size 1
146
+ ```
147
+
148
+ Evaluating ARC on 25-Shot
149
+ ```bash
150
+ HF_HUB_ENABLE_HF_TRANSFER=1 HF_TOKEN=<YOUR_HF_TOKEN> accelerate launch -m lm_eval --model hf-auto \
151
+ --model_args pretrained=ruliadai/falcon-base-v1.1,trust_remote_code=True \
152
+ --tasks arc_challenge \
153
+ --device cuda:0 \
154
+ --num_fewshot 25 \
155
+ --batch_size 1
156
+ ```
.ipynb_checkpoints/config-checkpoint.json ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "tiiuae/falcon-11B",
3
+ "activation": "gelu",
4
+ "alibi": false,
5
+ "architectures": [
6
+ "FalconForCausalLM"
7
+ ],
8
+ "attention_dropout": 0.0,
9
+ "auto_map": {
10
+ "AutoConfig": "tiiuae/falcon-11B--configuration_falcon.FalconConfig",
11
+ "AutoModel": "tiiuae/falcon-11B--modeling_falcon.FalconModel",
12
+ "AutoModelForCausalLM": "tiiuae/falcon-11B--modeling_falcon.FalconForCausalLM",
13
+ "AutoModelForQuestionAnswering": "tiiuae/falcon-11B--modeling_falcon.FalconForQuestionAnswering",
14
+ "AutoModelForSequenceClassification": "tiiuae/falcon-11B--modeling_falcon.FalconForSequenceClassification",
15
+ "AutoModelForTokenClassification": "tiiuae/falcon-11B--modeling_falcon.FalconForTokenClassification"
16
+ },
17
+ "bias": false,
18
+ "bos_token_id": 11,
19
+ "eos_token_id": 11,
20
+ "ff_factor": 4,
21
+ "ffn_hidden_size": 16384,
22
+ "hidden_dropout": 0.0,
23
+ "hidden_size": 4096,
24
+ "initializer_range": 0.02,
25
+ "layer_norm_epsilon": 1e-05,
26
+ "max_position_embeddings": 8192,
27
+ "model_type": "falcon",
28
+ "multi_query": true,
29
+ "new_decoder_architecture": true,
30
+ "num_attention_heads": 32,
31
+ "num_hidden_layers": 60,
32
+ "num_kv_heads": 8,
33
+ "num_ln_in_parallel_attn": 1,
34
+ "parallel_attn": true,
35
+ "rope_scaling": null,
36
+ "rope_theta": 500042.0,
37
+ "rotary_base": 5000042,
38
+ "tie_word_embeddings": false,
39
+ "torch_dtype": "bfloat16",
40
+ "transformers_version": "4.39.2",
41
+ "use_cache": true,
42
+ "vocab_size": 65024
43
+ }
.ipynb_checkpoints/generation_config-checkpoint.json ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "bos_token_id": 11,
4
+ "eos_token_id": 11,
5
+ "transformers_version": "4.40.1"
6
+ }
.ipynb_checkpoints/model.safetensors.index-checkpoint.json ADDED
@@ -0,0 +1,371 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "metadata": {
3
+ "total_size": 22205644800
4
+ },
5
+ "weight_map": {
6
+ "lm_head.weight": "model-00005-of-00005.safetensors",
7
+ "transformer.h.0.input_layernorm.bias": "model-00001-of-00005.safetensors",
8
+ "transformer.h.0.input_layernorm.weight": "model-00001-of-00005.safetensors",
9
+ "transformer.h.0.mlp.downscale.weight": "model-00001-of-00005.safetensors",
10
+ "transformer.h.0.mlp.upscale.weight": "model-00001-of-00005.safetensors",
11
+ "transformer.h.0.self_attention.dense.weight": "model-00001-of-00005.safetensors",
12
+ "transformer.h.0.self_attention.query_key_value.weight": "model-00001-of-00005.safetensors",
13
+ "transformer.h.1.input_layernorm.bias": "model-00001-of-00005.safetensors",
14
+ "transformer.h.1.input_layernorm.weight": "model-00001-of-00005.safetensors",
15
+ "transformer.h.1.mlp.downscale.weight": "model-00001-of-00005.safetensors",
16
+ "transformer.h.1.mlp.upscale.weight": "model-00001-of-00005.safetensors",
17
+ "transformer.h.1.self_attention.dense.weight": "model-00001-of-00005.safetensors",
18
+ "transformer.h.1.self_attention.query_key_value.weight": "model-00001-of-00005.safetensors",
19
+ "transformer.h.10.input_layernorm.bias": "model-00001-of-00005.safetensors",
20
+ "transformer.h.10.input_layernorm.weight": "model-00001-of-00005.safetensors",
21
+ "transformer.h.10.mlp.downscale.weight": "model-00001-of-00005.safetensors",
22
+ "transformer.h.10.mlp.upscale.weight": "model-00001-of-00005.safetensors",
23
+ "transformer.h.10.self_attention.dense.weight": "model-00001-of-00005.safetensors",
24
+ "transformer.h.10.self_attention.query_key_value.weight": "model-00001-of-00005.safetensors",
25
+ "transformer.h.11.input_layernorm.bias": "model-00001-of-00005.safetensors",
26
+ "transformer.h.11.input_layernorm.weight": "model-00001-of-00005.safetensors",
27
+ "transformer.h.11.mlp.downscale.weight": "model-00001-of-00005.safetensors",
28
+ "transformer.h.11.mlp.upscale.weight": "model-00001-of-00005.safetensors",
29
+ "transformer.h.11.self_attention.dense.weight": "model-00001-of-00005.safetensors",
30
+ "transformer.h.11.self_attention.query_key_value.weight": "model-00001-of-00005.safetensors",
31
+ "transformer.h.12.input_layernorm.bias": "model-00002-of-00005.safetensors",
32
+ "transformer.h.12.input_layernorm.weight": "model-00002-of-00005.safetensors",
33
+ "transformer.h.12.mlp.downscale.weight": "model-00002-of-00005.safetensors",
34
+ "transformer.h.12.mlp.upscale.weight": "model-00001-of-00005.safetensors",
35
+ "transformer.h.12.self_attention.dense.weight": "model-00001-of-00005.safetensors",
36
+ "transformer.h.12.self_attention.query_key_value.weight": "model-00001-of-00005.safetensors",
37
+ "transformer.h.13.input_layernorm.bias": "model-00002-of-00005.safetensors",
38
+ "transformer.h.13.input_layernorm.weight": "model-00002-of-00005.safetensors",
39
+ "transformer.h.13.mlp.downscale.weight": "model-00002-of-00005.safetensors",
40
+ "transformer.h.13.mlp.upscale.weight": "model-00002-of-00005.safetensors",
41
+ "transformer.h.13.self_attention.dense.weight": "model-00002-of-00005.safetensors",
42
+ "transformer.h.13.self_attention.query_key_value.weight": "model-00002-of-00005.safetensors",
43
+ "transformer.h.14.input_layernorm.bias": "model-00002-of-00005.safetensors",
44
+ "transformer.h.14.input_layernorm.weight": "model-00002-of-00005.safetensors",
45
+ "transformer.h.14.mlp.downscale.weight": "model-00002-of-00005.safetensors",
46
+ "transformer.h.14.mlp.upscale.weight": "model-00002-of-00005.safetensors",
47
+ "transformer.h.14.self_attention.dense.weight": "model-00002-of-00005.safetensors",
48
+ "transformer.h.14.self_attention.query_key_value.weight": "model-00002-of-00005.safetensors",
49
+ "transformer.h.15.input_layernorm.bias": "model-00002-of-00005.safetensors",
50
+ "transformer.h.15.input_layernorm.weight": "model-00002-of-00005.safetensors",
51
+ "transformer.h.15.mlp.downscale.weight": "model-00002-of-00005.safetensors",
52
+ "transformer.h.15.mlp.upscale.weight": "model-00002-of-00005.safetensors",
53
+ "transformer.h.15.self_attention.dense.weight": "model-00002-of-00005.safetensors",
54
+ "transformer.h.15.self_attention.query_key_value.weight": "model-00002-of-00005.safetensors",
55
+ "transformer.h.16.input_layernorm.bias": "model-00002-of-00005.safetensors",
56
+ "transformer.h.16.input_layernorm.weight": "model-00002-of-00005.safetensors",
57
+ "transformer.h.16.mlp.downscale.weight": "model-00002-of-00005.safetensors",
58
+ "transformer.h.16.mlp.upscale.weight": "model-00002-of-00005.safetensors",
59
+ "transformer.h.16.self_attention.dense.weight": "model-00002-of-00005.safetensors",
60
+ "transformer.h.16.self_attention.query_key_value.weight": "model-00002-of-00005.safetensors",
61
+ "transformer.h.17.input_layernorm.bias": "model-00002-of-00005.safetensors",
62
+ "transformer.h.17.input_layernorm.weight": "model-00002-of-00005.safetensors",
63
+ "transformer.h.17.mlp.downscale.weight": "model-00002-of-00005.safetensors",
64
+ "transformer.h.17.mlp.upscale.weight": "model-00002-of-00005.safetensors",
65
+ "transformer.h.17.self_attention.dense.weight": "model-00002-of-00005.safetensors",
66
+ "transformer.h.17.self_attention.query_key_value.weight": "model-00002-of-00005.safetensors",
67
+ "transformer.h.18.input_layernorm.bias": "model-00002-of-00005.safetensors",
68
+ "transformer.h.18.input_layernorm.weight": "model-00002-of-00005.safetensors",
69
+ "transformer.h.18.mlp.downscale.weight": "model-00002-of-00005.safetensors",
70
+ "transformer.h.18.mlp.upscale.weight": "model-00002-of-00005.safetensors",
71
+ "transformer.h.18.self_attention.dense.weight": "model-00002-of-00005.safetensors",
72
+ "transformer.h.18.self_attention.query_key_value.weight": "model-00002-of-00005.safetensors",
73
+ "transformer.h.19.input_layernorm.bias": "model-00002-of-00005.safetensors",
74
+ "transformer.h.19.input_layernorm.weight": "model-00002-of-00005.safetensors",
75
+ "transformer.h.19.mlp.downscale.weight": "model-00002-of-00005.safetensors",
76
+ "transformer.h.19.mlp.upscale.weight": "model-00002-of-00005.safetensors",
77
+ "transformer.h.19.self_attention.dense.weight": "model-00002-of-00005.safetensors",
78
+ "transformer.h.19.self_attention.query_key_value.weight": "model-00002-of-00005.safetensors",
79
+ "transformer.h.2.input_layernorm.bias": "model-00001-of-00005.safetensors",
80
+ "transformer.h.2.input_layernorm.weight": "model-00001-of-00005.safetensors",
81
+ "transformer.h.2.mlp.downscale.weight": "model-00001-of-00005.safetensors",
82
+ "transformer.h.2.mlp.upscale.weight": "model-00001-of-00005.safetensors",
83
+ "transformer.h.2.self_attention.dense.weight": "model-00001-of-00005.safetensors",
84
+ "transformer.h.2.self_attention.query_key_value.weight": "model-00001-of-00005.safetensors",
85
+ "transformer.h.20.input_layernorm.bias": "model-00002-of-00005.safetensors",
86
+ "transformer.h.20.input_layernorm.weight": "model-00002-of-00005.safetensors",
87
+ "transformer.h.20.mlp.downscale.weight": "model-00002-of-00005.safetensors",
88
+ "transformer.h.20.mlp.upscale.weight": "model-00002-of-00005.safetensors",
89
+ "transformer.h.20.self_attention.dense.weight": "model-00002-of-00005.safetensors",
90
+ "transformer.h.20.self_attention.query_key_value.weight": "model-00002-of-00005.safetensors",
91
+ "transformer.h.21.input_layernorm.bias": "model-00002-of-00005.safetensors",
92
+ "transformer.h.21.input_layernorm.weight": "model-00002-of-00005.safetensors",
93
+ "transformer.h.21.mlp.downscale.weight": "model-00002-of-00005.safetensors",
94
+ "transformer.h.21.mlp.upscale.weight": "model-00002-of-00005.safetensors",
95
+ "transformer.h.21.self_attention.dense.weight": "model-00002-of-00005.safetensors",
96
+ "transformer.h.21.self_attention.query_key_value.weight": "model-00002-of-00005.safetensors",
97
+ "transformer.h.22.input_layernorm.bias": "model-00002-of-00005.safetensors",
98
+ "transformer.h.22.input_layernorm.weight": "model-00002-of-00005.safetensors",
99
+ "transformer.h.22.mlp.downscale.weight": "model-00002-of-00005.safetensors",
100
+ "transformer.h.22.mlp.upscale.weight": "model-00002-of-00005.safetensors",
101
+ "transformer.h.22.self_attention.dense.weight": "model-00002-of-00005.safetensors",
102
+ "transformer.h.22.self_attention.query_key_value.weight": "model-00002-of-00005.safetensors",
103
+ "transformer.h.23.input_layernorm.bias": "model-00002-of-00005.safetensors",
104
+ "transformer.h.23.input_layernorm.weight": "model-00002-of-00005.safetensors",
105
+ "transformer.h.23.mlp.downscale.weight": "model-00002-of-00005.safetensors",
106
+ "transformer.h.23.mlp.upscale.weight": "model-00002-of-00005.safetensors",
107
+ "transformer.h.23.self_attention.dense.weight": "model-00002-of-00005.safetensors",
108
+ "transformer.h.23.self_attention.query_key_value.weight": "model-00002-of-00005.safetensors",
109
+ "transformer.h.24.input_layernorm.bias": "model-00002-of-00005.safetensors",
110
+ "transformer.h.24.input_layernorm.weight": "model-00002-of-00005.safetensors",
111
+ "transformer.h.24.mlp.downscale.weight": "model-00002-of-00005.safetensors",
112
+ "transformer.h.24.mlp.upscale.weight": "model-00002-of-00005.safetensors",
113
+ "transformer.h.24.self_attention.dense.weight": "model-00002-of-00005.safetensors",
114
+ "transformer.h.24.self_attention.query_key_value.weight": "model-00002-of-00005.safetensors",
115
+ "transformer.h.25.input_layernorm.bias": "model-00002-of-00005.safetensors",
116
+ "transformer.h.25.input_layernorm.weight": "model-00002-of-00005.safetensors",
117
+ "transformer.h.25.mlp.downscale.weight": "model-00002-of-00005.safetensors",
118
+ "transformer.h.25.mlp.upscale.weight": "model-00002-of-00005.safetensors",
119
+ "transformer.h.25.self_attention.dense.weight": "model-00002-of-00005.safetensors",
120
+ "transformer.h.25.self_attention.query_key_value.weight": "model-00002-of-00005.safetensors",
121
+ "transformer.h.26.input_layernorm.bias": "model-00003-of-00005.safetensors",
122
+ "transformer.h.26.input_layernorm.weight": "model-00003-of-00005.safetensors",
123
+ "transformer.h.26.mlp.downscale.weight": "model-00003-of-00005.safetensors",
124
+ "transformer.h.26.mlp.upscale.weight": "model-00002-of-00005.safetensors",
125
+ "transformer.h.26.self_attention.dense.weight": "model-00002-of-00005.safetensors",
126
+ "transformer.h.26.self_attention.query_key_value.weight": "model-00002-of-00005.safetensors",
127
+ "transformer.h.27.input_layernorm.bias": "model-00003-of-00005.safetensors",
128
+ "transformer.h.27.input_layernorm.weight": "model-00003-of-00005.safetensors",
129
+ "transformer.h.27.mlp.downscale.weight": "model-00003-of-00005.safetensors",
130
+ "transformer.h.27.mlp.upscale.weight": "model-00003-of-00005.safetensors",
131
+ "transformer.h.27.self_attention.dense.weight": "model-00003-of-00005.safetensors",
132
+ "transformer.h.27.self_attention.query_key_value.weight": "model-00003-of-00005.safetensors",
133
+ "transformer.h.28.input_layernorm.bias": "model-00003-of-00005.safetensors",
134
+ "transformer.h.28.input_layernorm.weight": "model-00003-of-00005.safetensors",
135
+ "transformer.h.28.mlp.downscale.weight": "model-00003-of-00005.safetensors",
136
+ "transformer.h.28.mlp.upscale.weight": "model-00003-of-00005.safetensors",
137
+ "transformer.h.28.self_attention.dense.weight": "model-00003-of-00005.safetensors",
138
+ "transformer.h.28.self_attention.query_key_value.weight": "model-00003-of-00005.safetensors",
139
+ "transformer.h.29.input_layernorm.bias": "model-00003-of-00005.safetensors",
140
+ "transformer.h.29.input_layernorm.weight": "model-00003-of-00005.safetensors",
141
+ "transformer.h.29.mlp.downscale.weight": "model-00003-of-00005.safetensors",
142
+ "transformer.h.29.mlp.upscale.weight": "model-00003-of-00005.safetensors",
143
+ "transformer.h.29.self_attention.dense.weight": "model-00003-of-00005.safetensors",
144
+ "transformer.h.29.self_attention.query_key_value.weight": "model-00003-of-00005.safetensors",
145
+ "transformer.h.3.input_layernorm.bias": "model-00001-of-00005.safetensors",
146
+ "transformer.h.3.input_layernorm.weight": "model-00001-of-00005.safetensors",
147
+ "transformer.h.3.mlp.downscale.weight": "model-00001-of-00005.safetensors",
148
+ "transformer.h.3.mlp.upscale.weight": "model-00001-of-00005.safetensors",
149
+ "transformer.h.3.self_attention.dense.weight": "model-00001-of-00005.safetensors",
150
+ "transformer.h.3.self_attention.query_key_value.weight": "model-00001-of-00005.safetensors",
151
+ "transformer.h.30.input_layernorm.bias": "model-00003-of-00005.safetensors",
152
+ "transformer.h.30.input_layernorm.weight": "model-00003-of-00005.safetensors",
153
+ "transformer.h.30.mlp.downscale.weight": "model-00003-of-00005.safetensors",
154
+ "transformer.h.30.mlp.upscale.weight": "model-00003-of-00005.safetensors",
155
+ "transformer.h.30.self_attention.dense.weight": "model-00003-of-00005.safetensors",
156
+ "transformer.h.30.self_attention.query_key_value.weight": "model-00003-of-00005.safetensors",
157
+ "transformer.h.31.input_layernorm.bias": "model-00003-of-00005.safetensors",
158
+ "transformer.h.31.input_layernorm.weight": "model-00003-of-00005.safetensors",
159
+ "transformer.h.31.mlp.downscale.weight": "model-00003-of-00005.safetensors",
160
+ "transformer.h.31.mlp.upscale.weight": "model-00003-of-00005.safetensors",
161
+ "transformer.h.31.self_attention.dense.weight": "model-00003-of-00005.safetensors",
162
+ "transformer.h.31.self_attention.query_key_value.weight": "model-00003-of-00005.safetensors",
163
+ "transformer.h.32.input_layernorm.bias": "model-00003-of-00005.safetensors",
164
+ "transformer.h.32.input_layernorm.weight": "model-00003-of-00005.safetensors",
165
+ "transformer.h.32.mlp.downscale.weight": "model-00003-of-00005.safetensors",
166
+ "transformer.h.32.mlp.upscale.weight": "model-00003-of-00005.safetensors",
167
+ "transformer.h.32.self_attention.dense.weight": "model-00003-of-00005.safetensors",
168
+ "transformer.h.32.self_attention.query_key_value.weight": "model-00003-of-00005.safetensors",
169
+ "transformer.h.33.input_layernorm.bias": "model-00003-of-00005.safetensors",
170
+ "transformer.h.33.input_layernorm.weight": "model-00003-of-00005.safetensors",
171
+ "transformer.h.33.mlp.downscale.weight": "model-00003-of-00005.safetensors",
172
+ "transformer.h.33.mlp.upscale.weight": "model-00003-of-00005.safetensors",
173
+ "transformer.h.33.self_attention.dense.weight": "model-00003-of-00005.safetensors",
174
+ "transformer.h.33.self_attention.query_key_value.weight": "model-00003-of-00005.safetensors",
175
+ "transformer.h.34.input_layernorm.bias": "model-00003-of-00005.safetensors",
176
+ "transformer.h.34.input_layernorm.weight": "model-00003-of-00005.safetensors",
177
+ "transformer.h.34.mlp.downscale.weight": "model-00003-of-00005.safetensors",
178
+ "transformer.h.34.mlp.upscale.weight": "model-00003-of-00005.safetensors",
179
+ "transformer.h.34.self_attention.dense.weight": "model-00003-of-00005.safetensors",
180
+ "transformer.h.34.self_attention.query_key_value.weight": "model-00003-of-00005.safetensors",
181
+ "transformer.h.35.input_layernorm.bias": "model-00003-of-00005.safetensors",
182
+ "transformer.h.35.input_layernorm.weight": "model-00003-of-00005.safetensors",
183
+ "transformer.h.35.mlp.downscale.weight": "model-00003-of-00005.safetensors",
184
+ "transformer.h.35.mlp.upscale.weight": "model-00003-of-00005.safetensors",
185
+ "transformer.h.35.self_attention.dense.weight": "model-00003-of-00005.safetensors",
186
+ "transformer.h.35.self_attention.query_key_value.weight": "model-00003-of-00005.safetensors",
187
+ "transformer.h.36.input_layernorm.bias": "model-00003-of-00005.safetensors",
188
+ "transformer.h.36.input_layernorm.weight": "model-00003-of-00005.safetensors",
189
+ "transformer.h.36.mlp.downscale.weight": "model-00003-of-00005.safetensors",
190
+ "transformer.h.36.mlp.upscale.weight": "model-00003-of-00005.safetensors",
191
+ "transformer.h.36.self_attention.dense.weight": "model-00003-of-00005.safetensors",
192
+ "transformer.h.36.self_attention.query_key_value.weight": "model-00003-of-00005.safetensors",
193
+ "transformer.h.37.input_layernorm.bias": "model-00003-of-00005.safetensors",
194
+ "transformer.h.37.input_layernorm.weight": "model-00003-of-00005.safetensors",
195
+ "transformer.h.37.mlp.downscale.weight": "model-00003-of-00005.safetensors",
196
+ "transformer.h.37.mlp.upscale.weight": "model-00003-of-00005.safetensors",
197
+ "transformer.h.37.self_attention.dense.weight": "model-00003-of-00005.safetensors",
198
+ "transformer.h.37.self_attention.query_key_value.weight": "model-00003-of-00005.safetensors",
199
+ "transformer.h.38.input_layernorm.bias": "model-00003-of-00005.safetensors",
200
+ "transformer.h.38.input_layernorm.weight": "model-00003-of-00005.safetensors",
201
+ "transformer.h.38.mlp.downscale.weight": "model-00003-of-00005.safetensors",
202
+ "transformer.h.38.mlp.upscale.weight": "model-00003-of-00005.safetensors",
203
+ "transformer.h.38.self_attention.dense.weight": "model-00003-of-00005.safetensors",
204
+ "transformer.h.38.self_attention.query_key_value.weight": "model-00003-of-00005.safetensors",
205
+ "transformer.h.39.input_layernorm.bias": "model-00003-of-00005.safetensors",
206
+ "transformer.h.39.input_layernorm.weight": "model-00003-of-00005.safetensors",
207
+ "transformer.h.39.mlp.downscale.weight": "model-00003-of-00005.safetensors",
208
+ "transformer.h.39.mlp.upscale.weight": "model-00003-of-00005.safetensors",
209
+ "transformer.h.39.self_attention.dense.weight": "model-00003-of-00005.safetensors",
210
+ "transformer.h.39.self_attention.query_key_value.weight": "model-00003-of-00005.safetensors",
211
+ "transformer.h.4.input_layernorm.bias": "model-00001-of-00005.safetensors",
212
+ "transformer.h.4.input_layernorm.weight": "model-00001-of-00005.safetensors",
213
+ "transformer.h.4.mlp.downscale.weight": "model-00001-of-00005.safetensors",
214
+ "transformer.h.4.mlp.upscale.weight": "model-00001-of-00005.safetensors",
215
+ "transformer.h.4.self_attention.dense.weight": "model-00001-of-00005.safetensors",
216
+ "transformer.h.4.self_attention.query_key_value.weight": "model-00001-of-00005.safetensors",
217
+ "transformer.h.40.input_layernorm.bias": "model-00004-of-00005.safetensors",
218
+ "transformer.h.40.input_layernorm.weight": "model-00004-of-00005.safetensors",
219
+ "transformer.h.40.mlp.downscale.weight": "model-00004-of-00005.safetensors",
220
+ "transformer.h.40.mlp.upscale.weight": "model-00003-of-00005.safetensors",
221
+ "transformer.h.40.self_attention.dense.weight": "model-00003-of-00005.safetensors",
222
+ "transformer.h.40.self_attention.query_key_value.weight": "model-00003-of-00005.safetensors",
223
+ "transformer.h.41.input_layernorm.bias": "model-00004-of-00005.safetensors",
224
+ "transformer.h.41.input_layernorm.weight": "model-00004-of-00005.safetensors",
225
+ "transformer.h.41.mlp.downscale.weight": "model-00004-of-00005.safetensors",
226
+ "transformer.h.41.mlp.upscale.weight": "model-00004-of-00005.safetensors",
227
+ "transformer.h.41.self_attention.dense.weight": "model-00004-of-00005.safetensors",
228
+ "transformer.h.41.self_attention.query_key_value.weight": "model-00004-of-00005.safetensors",
229
+ "transformer.h.42.input_layernorm.bias": "model-00004-of-00005.safetensors",
230
+ "transformer.h.42.input_layernorm.weight": "model-00004-of-00005.safetensors",
231
+ "transformer.h.42.mlp.downscale.weight": "model-00004-of-00005.safetensors",
232
+ "transformer.h.42.mlp.upscale.weight": "model-00004-of-00005.safetensors",
233
+ "transformer.h.42.self_attention.dense.weight": "model-00004-of-00005.safetensors",
234
+ "transformer.h.42.self_attention.query_key_value.weight": "model-00004-of-00005.safetensors",
235
+ "transformer.h.43.input_layernorm.bias": "model-00004-of-00005.safetensors",
236
+ "transformer.h.43.input_layernorm.weight": "model-00004-of-00005.safetensors",
237
+ "transformer.h.43.mlp.downscale.weight": "model-00004-of-00005.safetensors",
238
+ "transformer.h.43.mlp.upscale.weight": "model-00004-of-00005.safetensors",
239
+ "transformer.h.43.self_attention.dense.weight": "model-00004-of-00005.safetensors",
240
+ "transformer.h.43.self_attention.query_key_value.weight": "model-00004-of-00005.safetensors",
241
+ "transformer.h.44.input_layernorm.bias": "model-00004-of-00005.safetensors",
242
+ "transformer.h.44.input_layernorm.weight": "model-00004-of-00005.safetensors",
243
+ "transformer.h.44.mlp.downscale.weight": "model-00004-of-00005.safetensors",
244
+ "transformer.h.44.mlp.upscale.weight": "model-00004-of-00005.safetensors",
245
+ "transformer.h.44.self_attention.dense.weight": "model-00004-of-00005.safetensors",
246
+ "transformer.h.44.self_attention.query_key_value.weight": "model-00004-of-00005.safetensors",
247
+ "transformer.h.45.input_layernorm.bias": "model-00004-of-00005.safetensors",
248
+ "transformer.h.45.input_layernorm.weight": "model-00004-of-00005.safetensors",
249
+ "transformer.h.45.mlp.downscale.weight": "model-00004-of-00005.safetensors",
250
+ "transformer.h.45.mlp.upscale.weight": "model-00004-of-00005.safetensors",
251
+ "transformer.h.45.self_attention.dense.weight": "model-00004-of-00005.safetensors",
252
+ "transformer.h.45.self_attention.query_key_value.weight": "model-00004-of-00005.safetensors",
253
+ "transformer.h.46.input_layernorm.bias": "model-00004-of-00005.safetensors",
254
+ "transformer.h.46.input_layernorm.weight": "model-00004-of-00005.safetensors",
255
+ "transformer.h.46.mlp.downscale.weight": "model-00004-of-00005.safetensors",
256
+ "transformer.h.46.mlp.upscale.weight": "model-00004-of-00005.safetensors",
257
+ "transformer.h.46.self_attention.dense.weight": "model-00004-of-00005.safetensors",
258
+ "transformer.h.46.self_attention.query_key_value.weight": "model-00004-of-00005.safetensors",
259
+ "transformer.h.47.input_layernorm.bias": "model-00004-of-00005.safetensors",
260
+ "transformer.h.47.input_layernorm.weight": "model-00004-of-00005.safetensors",
261
+ "transformer.h.47.mlp.downscale.weight": "model-00004-of-00005.safetensors",
262
+ "transformer.h.47.mlp.upscale.weight": "model-00004-of-00005.safetensors",
263
+ "transformer.h.47.self_attention.dense.weight": "model-00004-of-00005.safetensors",
264
+ "transformer.h.47.self_attention.query_key_value.weight": "model-00004-of-00005.safetensors",
265
+ "transformer.h.48.input_layernorm.bias": "model-00004-of-00005.safetensors",
266
+ "transformer.h.48.input_layernorm.weight": "model-00004-of-00005.safetensors",
267
+ "transformer.h.48.mlp.downscale.weight": "model-00004-of-00005.safetensors",
268
+ "transformer.h.48.mlp.upscale.weight": "model-00004-of-00005.safetensors",
269
+ "transformer.h.48.self_attention.dense.weight": "model-00004-of-00005.safetensors",
270
+ "transformer.h.48.self_attention.query_key_value.weight": "model-00004-of-00005.safetensors",
271
+ "transformer.h.49.input_layernorm.bias": "model-00004-of-00005.safetensors",
272
+ "transformer.h.49.input_layernorm.weight": "model-00004-of-00005.safetensors",
273
+ "transformer.h.49.mlp.downscale.weight": "model-00004-of-00005.safetensors",
274
+ "transformer.h.49.mlp.upscale.weight": "model-00004-of-00005.safetensors",
275
+ "transformer.h.49.self_attention.dense.weight": "model-00004-of-00005.safetensors",
276
+ "transformer.h.49.self_attention.query_key_value.weight": "model-00004-of-00005.safetensors",
277
+ "transformer.h.5.input_layernorm.bias": "model-00001-of-00005.safetensors",
278
+ "transformer.h.5.input_layernorm.weight": "model-00001-of-00005.safetensors",
279
+ "transformer.h.5.mlp.downscale.weight": "model-00001-of-00005.safetensors",
280
+ "transformer.h.5.mlp.upscale.weight": "model-00001-of-00005.safetensors",
281
+ "transformer.h.5.self_attention.dense.weight": "model-00001-of-00005.safetensors",
282
+ "transformer.h.5.self_attention.query_key_value.weight": "model-00001-of-00005.safetensors",
283
+ "transformer.h.50.input_layernorm.bias": "model-00004-of-00005.safetensors",
284
+ "transformer.h.50.input_layernorm.weight": "model-00004-of-00005.safetensors",
285
+ "transformer.h.50.mlp.downscale.weight": "model-00004-of-00005.safetensors",
286
+ "transformer.h.50.mlp.upscale.weight": "model-00004-of-00005.safetensors",
287
+ "transformer.h.50.self_attention.dense.weight": "model-00004-of-00005.safetensors",
288
+ "transformer.h.50.self_attention.query_key_value.weight": "model-00004-of-00005.safetensors",
289
+ "transformer.h.51.input_layernorm.bias": "model-00004-of-00005.safetensors",
290
+ "transformer.h.51.input_layernorm.weight": "model-00004-of-00005.safetensors",
291
+ "transformer.h.51.mlp.downscale.weight": "model-00004-of-00005.safetensors",
292
+ "transformer.h.51.mlp.upscale.weight": "model-00004-of-00005.safetensors",
293
+ "transformer.h.51.self_attention.dense.weight": "model-00004-of-00005.safetensors",
294
+ "transformer.h.51.self_attention.query_key_value.weight": "model-00004-of-00005.safetensors",
295
+ "transformer.h.52.input_layernorm.bias": "model-00004-of-00005.safetensors",
296
+ "transformer.h.52.input_layernorm.weight": "model-00004-of-00005.safetensors",
297
+ "transformer.h.52.mlp.downscale.weight": "model-00004-of-00005.safetensors",
298
+ "transformer.h.52.mlp.upscale.weight": "model-00004-of-00005.safetensors",
299
+ "transformer.h.52.self_attention.dense.weight": "model-00004-of-00005.safetensors",
300
+ "transformer.h.52.self_attention.query_key_value.weight": "model-00004-of-00005.safetensors",
301
+ "transformer.h.53.input_layernorm.bias": "model-00004-of-00005.safetensors",
302
+ "transformer.h.53.input_layernorm.weight": "model-00004-of-00005.safetensors",
303
+ "transformer.h.53.mlp.downscale.weight": "model-00004-of-00005.safetensors",
304
+ "transformer.h.53.mlp.upscale.weight": "model-00004-of-00005.safetensors",
305
+ "transformer.h.53.self_attention.dense.weight": "model-00004-of-00005.safetensors",
306
+ "transformer.h.53.self_attention.query_key_value.weight": "model-00004-of-00005.safetensors",
307
+ "transformer.h.54.input_layernorm.bias": "model-00005-of-00005.safetensors",
308
+ "transformer.h.54.input_layernorm.weight": "model-00005-of-00005.safetensors",
309
+ "transformer.h.54.mlp.downscale.weight": "model-00005-of-00005.safetensors",
310
+ "transformer.h.54.mlp.upscale.weight": "model-00004-of-00005.safetensors",
311
+ "transformer.h.54.self_attention.dense.weight": "model-00004-of-00005.safetensors",
312
+ "transformer.h.54.self_attention.query_key_value.weight": "model-00004-of-00005.safetensors",
313
+ "transformer.h.55.input_layernorm.bias": "model-00005-of-00005.safetensors",
314
+ "transformer.h.55.input_layernorm.weight": "model-00005-of-00005.safetensors",
315
+ "transformer.h.55.mlp.downscale.weight": "model-00005-of-00005.safetensors",
316
+ "transformer.h.55.mlp.upscale.weight": "model-00005-of-00005.safetensors",
317
+ "transformer.h.55.self_attention.dense.weight": "model-00005-of-00005.safetensors",
318
+ "transformer.h.55.self_attention.query_key_value.weight": "model-00005-of-00005.safetensors",
319
+ "transformer.h.56.input_layernorm.bias": "model-00005-of-00005.safetensors",
320
+ "transformer.h.56.input_layernorm.weight": "model-00005-of-00005.safetensors",
321
+ "transformer.h.56.mlp.downscale.weight": "model-00005-of-00005.safetensors",
322
+ "transformer.h.56.mlp.upscale.weight": "model-00005-of-00005.safetensors",
323
+ "transformer.h.56.self_attention.dense.weight": "model-00005-of-00005.safetensors",
324
+ "transformer.h.56.self_attention.query_key_value.weight": "model-00005-of-00005.safetensors",
325
+ "transformer.h.57.input_layernorm.bias": "model-00005-of-00005.safetensors",
326
+ "transformer.h.57.input_layernorm.weight": "model-00005-of-00005.safetensors",
327
+ "transformer.h.57.mlp.downscale.weight": "model-00005-of-00005.safetensors",
328
+ "transformer.h.57.mlp.upscale.weight": "model-00005-of-00005.safetensors",
329
+ "transformer.h.57.self_attention.dense.weight": "model-00005-of-00005.safetensors",
330
+ "transformer.h.57.self_attention.query_key_value.weight": "model-00005-of-00005.safetensors",
331
+ "transformer.h.58.input_layernorm.bias": "model-00005-of-00005.safetensors",
332
+ "transformer.h.58.input_layernorm.weight": "model-00005-of-00005.safetensors",
333
+ "transformer.h.58.mlp.downscale.weight": "model-00005-of-00005.safetensors",
334
+ "transformer.h.58.mlp.upscale.weight": "model-00005-of-00005.safetensors",
335
+ "transformer.h.58.self_attention.dense.weight": "model-00005-of-00005.safetensors",
336
+ "transformer.h.58.self_attention.query_key_value.weight": "model-00005-of-00005.safetensors",
337
+ "transformer.h.59.input_layernorm.bias": "model-00005-of-00005.safetensors",
338
+ "transformer.h.59.input_layernorm.weight": "model-00005-of-00005.safetensors",
339
+ "transformer.h.59.mlp.downscale.weight": "model-00005-of-00005.safetensors",
340
+ "transformer.h.59.mlp.upscale.weight": "model-00005-of-00005.safetensors",
341
+ "transformer.h.59.self_attention.dense.weight": "model-00005-of-00005.safetensors",
342
+ "transformer.h.59.self_attention.query_key_value.weight": "model-00005-of-00005.safetensors",
343
+ "transformer.h.6.input_layernorm.bias": "model-00001-of-00005.safetensors",
344
+ "transformer.h.6.input_layernorm.weight": "model-00001-of-00005.safetensors",
345
+ "transformer.h.6.mlp.downscale.weight": "model-00001-of-00005.safetensors",
346
+ "transformer.h.6.mlp.upscale.weight": "model-00001-of-00005.safetensors",
347
+ "transformer.h.6.self_attention.dense.weight": "model-00001-of-00005.safetensors",
348
+ "transformer.h.6.self_attention.query_key_value.weight": "model-00001-of-00005.safetensors",
349
+ "transformer.h.7.input_layernorm.bias": "model-00001-of-00005.safetensors",
350
+ "transformer.h.7.input_layernorm.weight": "model-00001-of-00005.safetensors",
351
+ "transformer.h.7.mlp.downscale.weight": "model-00001-of-00005.safetensors",
352
+ "transformer.h.7.mlp.upscale.weight": "model-00001-of-00005.safetensors",
353
+ "transformer.h.7.self_attention.dense.weight": "model-00001-of-00005.safetensors",
354
+ "transformer.h.7.self_attention.query_key_value.weight": "model-00001-of-00005.safetensors",
355
+ "transformer.h.8.input_layernorm.bias": "model-00001-of-00005.safetensors",
356
+ "transformer.h.8.input_layernorm.weight": "model-00001-of-00005.safetensors",
357
+ "transformer.h.8.mlp.downscale.weight": "model-00001-of-00005.safetensors",
358
+ "transformer.h.8.mlp.upscale.weight": "model-00001-of-00005.safetensors",
359
+ "transformer.h.8.self_attention.dense.weight": "model-00001-of-00005.safetensors",
360
+ "transformer.h.8.self_attention.query_key_value.weight": "model-00001-of-00005.safetensors",
361
+ "transformer.h.9.input_layernorm.bias": "model-00001-of-00005.safetensors",
362
+ "transformer.h.9.input_layernorm.weight": "model-00001-of-00005.safetensors",
363
+ "transformer.h.9.mlp.downscale.weight": "model-00001-of-00005.safetensors",
364
+ "transformer.h.9.mlp.upscale.weight": "model-00001-of-00005.safetensors",
365
+ "transformer.h.9.self_attention.dense.weight": "model-00001-of-00005.safetensors",
366
+ "transformer.h.9.self_attention.query_key_value.weight": "model-00001-of-00005.safetensors",
367
+ "transformer.ln_f.bias": "model-00005-of-00005.safetensors",
368
+ "transformer.ln_f.weight": "model-00005-of-00005.safetensors",
369
+ "transformer.word_embeddings.weight": "model-00001-of-00005.safetensors"
370
+ }
371
+ }
.ipynb_checkpoints/modeling_falcon-checkpoint.py ADDED
@@ -0,0 +1,1670 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 the Falcon authors and HuggingFace Inc. team. 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
+ """PyTorch Falcon model."""
16
+
17
+ import math
18
+ import warnings
19
+ from typing import TYPE_CHECKING, Optional, Tuple, Union
20
+
21
+ import torch
22
+ import torch.utils.checkpoint
23
+ from torch import nn
24
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, LayerNorm, MSELoss
25
+ from torch.nn import functional as F
26
+
27
+ from transformers.modeling_attn_mask_utils import (
28
+ AttentionMaskConverter,
29
+ _prepare_4d_causal_attention_mask,
30
+ _prepare_4d_causal_attention_mask_for_sdpa,
31
+ )
32
+ from transformers.modeling_outputs import (
33
+ BaseModelOutputWithPastAndCrossAttentions,
34
+ CausalLMOutputWithCrossAttentions,
35
+ QuestionAnsweringModelOutput,
36
+ SequenceClassifierOutputWithPast,
37
+ TokenClassifierOutput,
38
+ )
39
+ from transformers.modeling_utils import PreTrainedModel
40
+ from transformers.pytorch_utils import is_torch_greater_or_equal_than_2_0
41
+ from transformers.utils import (
42
+ add_code_sample_docstrings,
43
+ add_start_docstrings,
44
+ add_start_docstrings_to_model_forward,
45
+ is_flash_attn_2_available,
46
+ is_flash_attn_greater_or_equal_2_10,
47
+ logging,
48
+ )
49
+ from .configuration_falcon import FalconConfig
50
+
51
+
52
+ if TYPE_CHECKING:
53
+ from transformers.configuration_utils import PretrainedConfig
54
+
55
+ if is_flash_attn_2_available():
56
+ from flash_attn import flash_attn_func, flash_attn_varlen_func
57
+ from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
58
+
59
+ logger = logging.get_logger(__name__)
60
+
61
+ FALCON_PRETRAINED_MODEL_ARCHIVE_LIST = [
62
+ "tiiuae/falcon-40b",
63
+ "tiiuae/falcon-40b-instruct",
64
+ "tiiuae/falcon-7b",
65
+ "tiiuae/falcon-7b-instruct",
66
+ "tiiuae/falcon-rw-7b",
67
+ "tiiuae/falcon-rw-1b",
68
+ ]
69
+ _CHECKPOINT_FOR_DOC = "Rocketknight1/falcon-rw-1b"
70
+ _CONFIG_FOR_DOC = "FalconConfig"
71
+
72
+
73
+ # NOTE(Hesslow): Unfortunately we did not fuse matmul and bias during training, this means that there's one additional quantization to bfloat16 between the operations.
74
+ # In order not to degrade the quality of our HF-port, we keep these characteristics in the final model.
75
+ class FalconLinear(nn.Linear):
76
+ def forward(self, input: torch.Tensor) -> torch.Tensor:
77
+ hidden_states = input @ self.weight.T
78
+ if self.bias is None:
79
+ return hidden_states
80
+ return hidden_states + self.bias
81
+
82
+
83
+ # Copied from transformers.models.llama.modeling_llama.rotate_half
84
+ def rotate_half(x):
85
+ """Rotates half the hidden dims of the input."""
86
+ x1 = x[..., : x.shape[-1] // 2]
87
+ x2 = x[..., x.shape[-1] // 2 :]
88
+ return torch.cat((-x2, x1), dim=-1)
89
+
90
+
91
+ # Copied from transformers.models.mistral.modeling_mistral.apply_rotary_pos_emb
92
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1):
93
+ """Applies Rotary Position Embedding to the query and key tensors.
94
+
95
+ Args:
96
+ q (`torch.Tensor`): The query tensor.
97
+ k (`torch.Tensor`): The key tensor.
98
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
99
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
100
+ position_ids (`torch.Tensor`):
101
+ The position indices of the tokens corresponding to the query and key tensors. For example, this can be
102
+ used to pass offsetted position ids when working with a KV-cache.
103
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
104
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
105
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
106
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
107
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
108
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
109
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
110
+ Returns:
111
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
112
+ """
113
+ cos = cos[position_ids].unsqueeze(unsqueeze_dim)
114
+ sin = sin[position_ids].unsqueeze(unsqueeze_dim)
115
+ q_embed = (q * cos) + (rotate_half(q) * sin)
116
+ k_embed = (k * cos) + (rotate_half(k) * sin)
117
+ return q_embed, k_embed
118
+
119
+
120
+ @torch.jit.script
121
+ def get_max_seqlen_in_batch(attention_mask: torch.Tensor) -> torch.Tensor:
122
+ max_num = int(torch.max(attention_mask).item())
123
+ batch_size, _ = attention_mask.shape
124
+ counts = torch.zeros((batch_size, max_num), dtype=torch.int32)
125
+
126
+ for i in range(1, max_num + 1):
127
+ mask = attention_mask == i
128
+ counts[:, i - 1] = torch.sum(mask, dim=-1).to(dtype=torch.int32)
129
+
130
+ result = counts.flatten()
131
+ nonzero_indices = torch.nonzero(result).squeeze(-1)
132
+ return result[nonzero_indices]
133
+
134
+
135
+ @torch.jit.script
136
+ def _get_unpad_data(attention_mask: torch.Tensor):
137
+ device = attention_mask.device
138
+ seqlens_in_batch = get_max_seqlen_in_batch(attention_mask)
139
+ indices = torch.nonzero(attention_mask.flatten()).flatten()
140
+ max_seqlen_in_batch = seqlens_in_batch.max().item()
141
+ cu_seqlens = (
142
+ F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.int32), (1, 0))
143
+ .to(device=device)
144
+ .detach()
145
+ )
146
+ return (
147
+ indices,
148
+ cu_seqlens,
149
+ max_seqlen_in_batch,
150
+ )
151
+
152
+ # Copied from transformers.models.mistral.modeling_mistral.MistralRotaryEmbedding with Mistral->Falcon
153
+ class FalconRotaryEmbedding(nn.Module):
154
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
155
+ super().__init__()
156
+
157
+ self.dim = dim
158
+ self.max_position_embeddings = max_position_embeddings
159
+ self.base = base
160
+ inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2, dtype=torch.int64).float().to(device) / self.dim))
161
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
162
+
163
+ # Build here to make `torch.jit.trace` work.
164
+ self._set_cos_sin_cache(
165
+ seq_len=max_position_embeddings, device=self.inv_freq.device, dtype=torch.get_default_dtype()
166
+ )
167
+
168
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
169
+ self.max_seq_len_cached = seq_len
170
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=torch.int64).type_as(self.inv_freq)
171
+
172
+ freqs = torch.outer(t, self.inv_freq)
173
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
174
+ emb = torch.cat((freqs, freqs), dim=-1)
175
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
176
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
177
+
178
+ def forward(self, x, seq_len=None):
179
+ # x: [bs, num_attention_heads, seq_len, head_size]
180
+ if seq_len > self.max_seq_len_cached:
181
+ self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)
182
+
183
+ return (
184
+ self.cos_cached[:seq_len].to(dtype=x.dtype),
185
+ self.sin_cached[:seq_len].to(dtype=x.dtype),
186
+ )
187
+
188
+
189
+ # copied from transformers.models.llama.modeling_llama.LlamaLinearScalingRotaryEmbedding with Llama->Falcon
190
+ # TODO @joao no longer copied from LLama after static cache, fix me (copied -> Copied)
191
+ class FalconLinearScalingRotaryEmbedding(FalconRotaryEmbedding):
192
+ """FalconRotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendev"""
193
+
194
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):
195
+ self.scaling_factor = scaling_factor
196
+ super().__init__(dim, max_position_embeddings, base, device)
197
+
198
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
199
+ self.max_seq_len_cached = seq_len
200
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=torch.int64).type_as(self.inv_freq)
201
+ t = t / self.scaling_factor
202
+
203
+ freqs = torch.outer(t, self.inv_freq)
204
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
205
+ emb = torch.cat((freqs, freqs), dim=-1)
206
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
207
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
208
+
209
+
210
+ # copied from transformers.models.llama.modeling_llama.LlamaDynamicNTKScalingRotaryEmbedding with Llama->Falcon
211
+ # TODO @joao no longer copied from LLama after static cache, fix me (copied -> Copied)
212
+ class FalconDynamicNTKScalingRotaryEmbedding(FalconRotaryEmbedding):
213
+ """FalconRotaryEmbedding extended with Dynamic NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozilla"""
214
+
215
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):
216
+ self.scaling_factor = scaling_factor
217
+ super().__init__(dim, max_position_embeddings, base, device)
218
+
219
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
220
+ self.max_seq_len_cached = seq_len
221
+
222
+ if seq_len > self.max_position_embeddings:
223
+ base = self.base * (
224
+ (self.scaling_factor * seq_len / self.max_position_embeddings) - (self.scaling_factor - 1)
225
+ ) ** (self.dim / (self.dim - 2))
226
+ inv_freq = 1.0 / (base ** (torch.arange(0, self.dim, 2, dtype=torch.int64).float().to(device) / self.dim))
227
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
228
+
229
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=torch.int64).type_as(self.inv_freq)
230
+
231
+ freqs = torch.outer(t, self.inv_freq)
232
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
233
+ emb = torch.cat((freqs, freqs), dim=-1)
234
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
235
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
236
+
237
+
238
+ def build_alibi_tensor(attention_mask: torch.Tensor, num_heads: int, dtype: torch.dtype) -> torch.Tensor:
239
+ batch_size, seq_length = attention_mask.shape
240
+ closest_power_of_2 = 2 ** math.floor(math.log2(num_heads))
241
+ base = torch.tensor(
242
+ 2 ** (-(2 ** -(math.log2(closest_power_of_2) - 3))), device=attention_mask.device, dtype=torch.float32
243
+ )
244
+ powers = torch.arange(1, 1 + closest_power_of_2, device=attention_mask.device, dtype=torch.int32)
245
+ slopes = torch.pow(base, powers)
246
+
247
+ if closest_power_of_2 != num_heads:
248
+ extra_base = torch.tensor(
249
+ 2 ** (-(2 ** -(math.log2(2 * closest_power_of_2) - 3))), device=attention_mask.device, dtype=torch.float32
250
+ )
251
+ num_remaining_heads = min(closest_power_of_2, num_heads - closest_power_of_2)
252
+ extra_powers = torch.arange(1, 1 + 2 * num_remaining_heads, 2, device=attention_mask.device, dtype=torch.int32)
253
+ slopes = torch.cat([slopes, torch.pow(extra_base, extra_powers)], dim=0)
254
+
255
+ # Note: alibi will added to the attention bias that will be applied to the query, key product of attention
256
+ # => therefore alibi will have to be of shape (batch_size, num_heads, query_length, key_length)
257
+ # => here we set (batch_size=1, num_heads=num_heads, query_length=1, key_length=max_length)
258
+ # => the query_length dimension will then be broadcasted correctly
259
+ # This is more or less identical to T5's relative position bias:
260
+ # https://github.com/huggingface/transformers/blob/f681437203baa7671de3174b0fa583c349d9d5e1/src/transformers/models/t5/modeling_t5.py#L527
261
+ arange_tensor = ((attention_mask.cumsum(dim=-1) - 1) * attention_mask)[:, None, :]
262
+ alibi = slopes[..., None].bfloat16() * arange_tensor
263
+ return alibi.reshape(batch_size * num_heads, 1, seq_length).to(dtype)
264
+
265
+
266
+ # Copied from transformers.models.bloom.modeling_bloom.dropout_add
267
+ def dropout_add(x: torch.Tensor, residual: torch.Tensor, prob: float, training: bool) -> torch.Tensor:
268
+ """
269
+ Dropout add function
270
+
271
+ Args:
272
+ x (`torch.tensor`, *required*):
273
+ input tensor
274
+ residual (`torch.tensor`, *required*):
275
+ residual tensor
276
+ prob (`float`, *required*):
277
+ dropout probability
278
+ training (`bool`, *required*):
279
+ training mode
280
+ """
281
+ out = F.dropout(x, p=prob, training=training)
282
+ out = residual + out
283
+ return out
284
+
285
+
286
+ class FalconAttention(nn.Module):
287
+ def __init__(self, config: FalconConfig):
288
+ super().__init__()
289
+
290
+ self.config = config
291
+ self.hidden_size = config.hidden_size
292
+ self.num_heads = config.num_attention_heads
293
+ self.head_dim = self.hidden_size // self.num_heads
294
+ self.split_size = self.hidden_size
295
+ self.hidden_dropout = config.hidden_dropout
296
+ self.max_position_embeddings = config.max_position_embeddings
297
+ self.rope_theta = config.rope_theta
298
+ self.is_causal = True
299
+ self._use_sdpa = config._attn_implementation == "sdpa"
300
+
301
+ if self.head_dim * self.num_heads != self.hidden_size:
302
+ raise ValueError(
303
+ f"`hidden_size` must be divisible by num_heads (got `hidden_size`: {self.hidden_size} and `num_heads`:"
304
+ f" {self.num_heads})."
305
+ )
306
+
307
+ if config.rotary:
308
+ self._init_rope()
309
+
310
+ # Layer-wise attention scaling
311
+ self.inv_norm_factor = 1.0 / math.sqrt(self.head_dim)
312
+ self.beta = self.inv_norm_factor
313
+ if config.new_decoder_architecture:
314
+ qkv_out_dim = (config.num_kv_heads * 2 + config.num_attention_heads) * self.head_dim
315
+ elif config.multi_query:
316
+ qkv_out_dim = self.hidden_size + 2 * self.head_dim
317
+ else:
318
+ qkv_out_dim = 3 * self.hidden_size
319
+ self.query_key_value = FalconLinear(self.hidden_size, qkv_out_dim, bias=config.bias)
320
+ self.new_decoder_architecture = config.new_decoder_architecture
321
+ self.multi_query = config.multi_query
322
+ self.dense = FalconLinear(self.hidden_size, self.hidden_size, bias=config.bias)
323
+ self.attention_dropout = nn.Dropout(config.attention_dropout)
324
+ self.num_kv_heads = config.num_kv_heads if (self.new_decoder_architecture or not self.multi_query) else 1
325
+
326
+ # Copied from transformers.models.llama.modeling_llama.LlamaAttention._init_rope with Llama->Falcon
327
+ def _init_rope(self):
328
+ if self.config.rope_scaling is None:
329
+ self.rotary_emb = FalconRotaryEmbedding(
330
+ self.head_dim,
331
+ max_position_embeddings=self.max_position_embeddings,
332
+ base=self.rope_theta,
333
+ )
334
+ else:
335
+ scaling_type = self.config.rope_scaling["type"]
336
+ scaling_factor = self.config.rope_scaling["factor"]
337
+ if scaling_type == "linear":
338
+ self.rotary_emb = FalconLinearScalingRotaryEmbedding(
339
+ self.head_dim,
340
+ max_position_embeddings=self.max_position_embeddings,
341
+ scaling_factor=scaling_factor,
342
+ base=self.rope_theta,
343
+ )
344
+ elif scaling_type == "dynamic":
345
+ self.rotary_emb = FalconDynamicNTKScalingRotaryEmbedding(
346
+ self.head_dim,
347
+ max_position_embeddings=self.max_position_embeddings,
348
+ scaling_factor=scaling_factor,
349
+ base=self.rope_theta,
350
+ )
351
+ else:
352
+ raise ValueError(f"Unknown RoPE scaling type {scaling_type}")
353
+
354
+ def _split_heads(self, fused_qkv: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
355
+ """
356
+ Split the last dimension into (num_heads, head_dim), results share same memory storage as `fused_qkv`
357
+
358
+ Args:
359
+ fused_qkv (`torch.tensor`, *required*): [batch_size, seq_length, num_heads * 3 * head_dim]
360
+
361
+ Returns:
362
+ query: [batch_size, seq_length, num_heads, head_dim] key: [batch_size, seq_length, num_heads, head_dim]
363
+ value: [batch_size, seq_length, num_heads, head_dim]
364
+ """
365
+ if self.new_decoder_architecture:
366
+ batch, seq_len, _ = fused_qkv.shape
367
+ qkv = fused_qkv.view(batch, seq_len, -1, self.num_heads // self.num_kv_heads + 2, self.head_dim)
368
+ query = qkv[:, :, :, :-2]
369
+ key = qkv[:, :, :, [-2]]
370
+ value = qkv[:, :, :, [-1]]
371
+ key = torch.broadcast_to(key, query.shape)
372
+ value = torch.broadcast_to(value, query.shape)
373
+
374
+ query, key, value = [x.flatten(2, 3) for x in (query, key, value)]
375
+ return query, key, value
376
+ elif not self.multi_query:
377
+ batch_size, seq_length, three_times_hidden_size = fused_qkv.shape
378
+ fused_qkv = fused_qkv.view(batch_size, seq_length, self.num_heads, 3, self.head_dim)
379
+ return fused_qkv[..., 0, :], fused_qkv[..., 1, :], fused_qkv[..., 2, :]
380
+ else:
381
+ batch_size, seq_length, three_times_hidden_size = fused_qkv.shape
382
+ fused_qkv = fused_qkv.view(batch_size, seq_length, self.num_heads + 2, self.head_dim)
383
+ return fused_qkv[..., :-2, :], fused_qkv[..., [-2], :], fused_qkv[..., [-1], :]
384
+
385
+ # Copied from transformers.models.bloom.modeling_bloom.BloomAttention._merge_heads
386
+ def _merge_heads(self, x: torch.Tensor) -> torch.Tensor:
387
+ """
388
+ Merge heads together over the last dimension
389
+
390
+ Args:
391
+ x (`torch.tensor`, *required*): [batch_size * num_heads, seq_length, head_dim]
392
+
393
+ Returns:
394
+ torch.tensor: [batch_size, seq_length, num_heads * head_dim]
395
+ """
396
+ # What we want to achieve is:
397
+ # batch_size * num_heads, seq_length, head_dim -> batch_size, seq_length, num_heads * head_dim
398
+ batch_size_and_num_heads, seq_length, _ = x.shape
399
+ batch_size = batch_size_and_num_heads // self.num_heads
400
+
401
+ # First view to decompose the batch size
402
+ # batch_size * num_heads, seq_length, head_dim -> batch_size, num_heads, seq_length, head_dim
403
+ x = x.view(batch_size, self.num_heads, seq_length, self.head_dim)
404
+
405
+ # batch_size, num_heads, seq_length, head_dim -> batch_size, seq_length, num_heads, head_dim
406
+ x = x.permute(0, 2, 1, 3)
407
+
408
+ # batch_size, seq_length, num_heads, head_dim -> batch_size, seq_length, num_heads * head_dim
409
+ return x.reshape(batch_size, seq_length, self.num_heads * self.head_dim)
410
+
411
+ def forward(
412
+ self,
413
+ hidden_states: torch.Tensor,
414
+ alibi: Optional[torch.Tensor],
415
+ attention_mask: torch.Tensor,
416
+ position_ids: Optional[torch.LongTensor] = None,
417
+ layer_past: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
418
+ head_mask: Optional[torch.Tensor] = None,
419
+ use_cache: bool = False,
420
+ output_attentions: bool = False,
421
+ **kwargs,
422
+ ):
423
+ if "padding_mask" in kwargs:
424
+ warnings.warn(
425
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
426
+ )
427
+
428
+ fused_qkv = self.query_key_value(hidden_states) # [batch_size, seq_length, 3 x hidden_size]
429
+ num_kv_heads = self.num_heads if self.new_decoder_architecture else self.num_kv_heads
430
+ # 3 x [batch_size, seq_length, num_heads, head_dim]
431
+ (query_layer, key_layer, value_layer) = self._split_heads(fused_qkv)
432
+
433
+ batch_size, query_length, _, _ = query_layer.shape
434
+
435
+ query_layer = query_layer.transpose(1, 2).reshape(batch_size, self.num_heads, query_length, self.head_dim)
436
+ key_layer = key_layer.transpose(1, 2).reshape(batch_size, num_kv_heads, query_length, self.head_dim)
437
+ value_layer = value_layer.transpose(1, 2).reshape(batch_size, num_kv_heads, query_length, self.head_dim)
438
+
439
+ kv_seq_len = key_layer.shape[-2]
440
+ if layer_past is not None:
441
+ kv_seq_len += layer_past[0].shape[-2]
442
+ if alibi is None:
443
+ cos, sin = self.rotary_emb(value_layer, seq_len=kv_seq_len)
444
+ query_layer, key_layer = apply_rotary_pos_emb(query_layer, key_layer, cos, sin, position_ids)
445
+
446
+ if layer_past is not None:
447
+ past_key, past_value = layer_past
448
+ # concatenate along seq_length dimension:
449
+ # - key: [batch_size, self.num_heads, kv_length, head_dim]
450
+ # - value: [batch_size, self.num_heads, kv_length, head_dim]
451
+ key_layer = torch.cat((past_key, key_layer), dim=-2)
452
+ value_layer = torch.cat((past_value, value_layer), dim=-2)
453
+
454
+ kv_length = key_layer.shape[-2]
455
+ if use_cache:
456
+ present = (key_layer, value_layer)
457
+ else:
458
+ present = None
459
+
460
+ if self._use_sdpa and query_layer.device.type == "cuda" and attention_mask is not None:
461
+ # For torch<=2.1.2, SDPA with memory-efficient backend is bugged with non-contiguous inputs with custom attn_mask,
462
+ # Reference: https://github.com/pytorch/pytorch/issues/112577.
463
+ query_layer = query_layer.contiguous()
464
+ key_layer = key_layer.contiguous()
465
+ value_layer = value_layer.contiguous()
466
+
467
+ if alibi is None:
468
+ if self._use_sdpa and not output_attentions:
469
+ attn_output = F.scaled_dot_product_attention(
470
+ query_layer,
471
+ key_layer,
472
+ value_layer,
473
+ attention_mask,
474
+ 0.0,
475
+ # The query_length > 1 is necessary to match with AttentionMaskConverter.to_causal_4d that does not create a causal mask in case query_length == 1.
476
+ is_causal=self.is_causal and attention_mask is None and query_length > 1,
477
+ )
478
+
479
+ attention_scores = None
480
+ else:
481
+ attention_scores = query_layer @ key_layer.transpose(-1, -2)
482
+ attention_scores /= math.sqrt(self.head_dim)
483
+
484
+ attention_scores = F.softmax(attention_scores + attention_mask, dim=-1, dtype=hidden_states.dtype)
485
+ # It is unclear why neither dropout nor head_mask is applied here (while it is with alibi).
486
+ attn_output = attention_scores @ value_layer
487
+
488
+ attn_output = attn_output.view(batch_size, self.num_heads, query_length, self.head_dim)
489
+ attn_output = attn_output.permute(0, 2, 1, 3)
490
+ attn_output = attn_output.reshape(batch_size, query_length, self.num_heads * self.head_dim)
491
+
492
+ attn_output = self.dense(attn_output)
493
+
494
+ if output_attentions:
495
+ return attn_output, present, attention_scores
496
+ else:
497
+ return attn_output, present
498
+
499
+ else:
500
+ if self._use_sdpa and not output_attentions and head_mask is None:
501
+ attn_output = F.scaled_dot_product_attention(
502
+ query_layer,
503
+ key_layer,
504
+ value_layer,
505
+ attn_mask=attention_mask,
506
+ dropout_p=self.attention_dropout.p if self.training else 0.0,
507
+ is_causal=self.is_causal and attention_mask is None and query_length > 1,
508
+ )
509
+ attn_output = attn_output.transpose(1, 2)
510
+ attn_output = attn_output.reshape(batch_size, query_length, self.num_heads * self.head_dim)
511
+
512
+ attn_output = self.dense(attn_output)
513
+ else:
514
+ matmul_result = query_layer @ key_layer.transpose(-1, -2)
515
+
516
+ # change view to [batch_size, num_heads, q_length, kv_length]
517
+ attention_scores = matmul_result.view(batch_size, self.num_heads, query_length, kv_length)
518
+
519
+ # cast attention scores to fp32, compute scaled softmax and cast back to initial dtype - [batch_size, num_heads, q_length, kv_length]
520
+ input_dtype = attention_scores.dtype
521
+ # `float16` has a minimum value of -65504.0, whereas `bfloat16` and `float32` have a minimum value of `-3.4e+38`
522
+ if input_dtype == torch.float16 or input_dtype == torch.bfloat16:
523
+ attention_scores = attention_scores.to(torch.float32)
524
+
525
+ attention_logits = attention_scores + alibi.view(batch_size, self.num_heads, 1, -1)
526
+ attention_logits *= self.inv_norm_factor
527
+ attention_probs = F.softmax(attention_logits + attention_mask, dim=-1, dtype=hidden_states.dtype)
528
+ # [batch_size, num_heads, q_length, kv_length]
529
+ attention_probs = self.attention_dropout(attention_probs)
530
+
531
+ if head_mask is not None:
532
+ attention_probs = attention_probs * head_mask
533
+
534
+ # change view [batch_size, num_heads, q_length, kv_length]
535
+ attention_probs_reshaped = attention_probs.view(batch_size, self.num_heads, query_length, kv_length)
536
+
537
+ # matmul: [batch_size * num_heads, q_length, head_dim]
538
+ attn_output = (attention_probs_reshaped @ value_layer).flatten(0, 1)
539
+
540
+ # change view [batch_size, q_length, num_heads * head_dim]
541
+ attn_output = self._merge_heads(attn_output)
542
+
543
+ attn_output = self.dense(attn_output)
544
+
545
+ if output_attentions:
546
+ return attn_output, present, attention_probs
547
+ else:
548
+ return attn_output, present
549
+
550
+
551
+ class FalconFlashAttention2(FalconAttention):
552
+ """
553
+ Falcon flash attention module. This module inherits from `FalconAttention` as the weights of the module stays
554
+ untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
555
+ flash attention and deal with padding tokens in case the input contains any of them.
556
+ """
557
+
558
+ # Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2.__init__
559
+ def __init__(self, *args, **kwargs):
560
+ super().__init__(*args, **kwargs)
561
+
562
+ # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
563
+ # 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.
564
+ # 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).
565
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
566
+
567
+ def forward(
568
+ self,
569
+ hidden_states: torch.Tensor,
570
+ alibi: Optional[torch.Tensor],
571
+ attention_mask: torch.Tensor,
572
+ position_ids: Optional[torch.LongTensor] = None,
573
+ layer_past: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
574
+ head_mask: Optional[torch.Tensor] = None,
575
+ use_cache: bool = False,
576
+ output_attentions: bool = False,
577
+ **kwargs,
578
+ ):
579
+ if "padding_mask" in kwargs:
580
+ warnings.warn(
581
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
582
+ )
583
+
584
+ # overwrite attention_mask with padding_mask
585
+ attention_mask = kwargs.pop("padding_mask")
586
+
587
+ fused_qkv = self.query_key_value(hidden_states) # [batch_size, seq_length, 3 x hidden_size]
588
+ num_kv_heads = self.num_heads if self.new_decoder_architecture else self.num_kv_heads
589
+ # 3 x [batch_size, seq_length, num_heads, head_dim]
590
+ (query_layer, key_layer, value_layer) = self._split_heads(fused_qkv)
591
+
592
+ batch_size, query_length, _, _ = query_layer.shape
593
+
594
+ query_layer = query_layer.transpose(1, 2).reshape(batch_size, self.num_heads, query_length, self.head_dim)
595
+ key_layer = key_layer.transpose(1, 2).reshape(batch_size, num_kv_heads, query_length, self.head_dim)
596
+ value_layer = value_layer.transpose(1, 2).reshape(batch_size, num_kv_heads, query_length, self.head_dim)
597
+
598
+ kv_seq_len = key_layer.shape[-2]
599
+ if layer_past is not None:
600
+ kv_seq_len += layer_past[0].shape[-2]
601
+ if alibi is None:
602
+ cos, sin = self.rotary_emb(value_layer, seq_len=kv_seq_len)
603
+ query_layer, key_layer = apply_rotary_pos_emb(query_layer, key_layer, cos, sin, position_ids)
604
+
605
+ if layer_past is not None and use_cache:
606
+ past_key, past_value = layer_past
607
+ # concatenate along seq_length dimension:
608
+ # - key: [batch_size, self.num_heads, kv_length, head_dim]
609
+ # - value: [batch_size, self.num_heads, kv_length, head_dim]
610
+ key_layer = torch.cat((past_key, key_layer), dim=-2)
611
+ value_layer = torch.cat((past_value, value_layer), dim=-2)
612
+
613
+ past_key_value = (key_layer, value_layer) if use_cache else None
614
+
615
+ # 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
616
+ # to be able to avoid many of these transpose/reshape/view.
617
+ query_layer = query_layer.transpose(1, 2)
618
+ key_layer = key_layer.transpose(1, 2)
619
+ value_layer = value_layer.transpose(1, 2)
620
+
621
+ if alibi is not None:
622
+ raise ValueError("`alibi` is not supported when `use_flash_attn` is True")
623
+
624
+ attn_dropout = self.config.attention_dropout if self.training else 0.0
625
+
626
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
627
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
628
+ # cast them back in float16 just to be sure everything works as expected.
629
+ input_dtype = query_layer.dtype
630
+ if input_dtype == torch.float32:
631
+ if torch.is_autocast_enabled():
632
+ target_dtype = torch.get_autocast_gpu_dtype()
633
+ # Handle the case where the model is quantized
634
+ elif hasattr(self.config, "_pre_quantization_dtype"):
635
+ target_dtype = self.config._pre_quantization_dtype
636
+ else:
637
+ target_dtype = self.query_key_value.weight.dtype
638
+
639
+ logger.warning_once(
640
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
641
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
642
+ f" {target_dtype}."
643
+ )
644
+
645
+ query_layer = query_layer.to(target_dtype)
646
+ key_layer = key_layer.to(target_dtype)
647
+ value_layer = value_layer.to(target_dtype)
648
+
649
+ attn_output = self._flash_attention_forward(
650
+ query_layer, key_layer, value_layer, attention_mask, query_length, dropout=attn_dropout
651
+ )
652
+
653
+ attn_weights = attn_output.reshape(batch_size, query_length, self.num_heads * self.head_dim)
654
+ attn_output = self.dense(attn_weights)
655
+
656
+ if not output_attentions:
657
+ attn_weights = None
658
+
659
+ return attn_output, past_key_value, attn_weights
660
+
661
+ # Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2._flash_attention_forward
662
+ def _flash_attention_forward(
663
+ self, query_states, key_states, value_states, attention_mask, query_length, dropout=0.0, softmax_scale=None
664
+ ):
665
+ """
666
+ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
667
+ first unpad the input, then computes the attention scores and pad the final attention scores.
668
+
669
+ Args:
670
+ query_states (`torch.Tensor`):
671
+ Input query states to be passed to Flash Attention API
672
+ key_states (`torch.Tensor`):
673
+ Input key states to be passed to Flash Attention API
674
+ value_states (`torch.Tensor`):
675
+ Input value states to be passed to Flash Attention API
676
+ attention_mask (`torch.Tensor`):
677
+ The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
678
+ position of padding tokens and 1 for the position of non-padding tokens.
679
+ dropout (`float`):
680
+ Attention dropout
681
+ softmax_scale (`float`, *optional*):
682
+ The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
683
+ """
684
+ if not self._flash_attn_uses_top_left_mask:
685
+ causal = self.is_causal
686
+ else:
687
+ # TODO: Remove the `query_length != 1` check once Flash Attention for RoCm is bumped to 2.1. For details, please see the comment in LlamaFlashAttention2 __init__.
688
+ causal = self.is_causal and query_length != 1
689
+
690
+ # Contains at least one padding token in the sequence
691
+ if attention_mask is not None:
692
+ batch_size = query_states.shape[0]
693
+ query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._upad_input(
694
+ query_states, key_states, value_states, attention_mask, query_length
695
+ )
696
+
697
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
698
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
699
+
700
+ attn_output_unpad = flash_attn_varlen_func(
701
+ query_states,
702
+ key_states,
703
+ value_states,
704
+ cu_seqlens_q=cu_seqlens_q,
705
+ cu_seqlens_k=cu_seqlens_k,
706
+ max_seqlen_q=max_seqlen_in_batch_q,
707
+ max_seqlen_k=max_seqlen_in_batch_k,
708
+ dropout_p=dropout,
709
+ softmax_scale=softmax_scale,
710
+ causal=causal,
711
+ )
712
+
713
+ attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length)
714
+ else:
715
+ attn_output = flash_attn_func(
716
+ query_states, key_states, value_states, dropout, softmax_scale=softmax_scale, causal=causal
717
+ )
718
+
719
+ return attn_output
720
+
721
+ # Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2._upad_input
722
+ def _upad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length):
723
+ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
724
+ batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape
725
+
726
+ key_layer = index_first_axis(
727
+ key_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
728
+ )
729
+ value_layer = index_first_axis(
730
+ value_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
731
+ )
732
+ if query_length == kv_seq_len:
733
+ query_layer = index_first_axis(
734
+ query_layer.reshape(batch_size * kv_seq_len, self.num_heads, head_dim), indices_k
735
+ )
736
+ cu_seqlens_q = cu_seqlens_k
737
+ max_seqlen_in_batch_q = max_seqlen_in_batch_k
738
+ indices_q = indices_k
739
+ elif query_length == 1:
740
+ max_seqlen_in_batch_q = 1
741
+ cu_seqlens_q = torch.arange(
742
+ batch_size + 1, dtype=torch.int32, device=query_layer.device
743
+ ) # There is a memcpy here, that is very bad.
744
+ indices_q = cu_seqlens_q[:-1]
745
+ query_layer = query_layer.squeeze(1)
746
+ else:
747
+ # The -q_len: slice assumes left padding.
748
+ attention_mask = attention_mask[:, -query_length:]
749
+ query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, attention_mask)
750
+
751
+ return (
752
+ query_layer,
753
+ key_layer,
754
+ value_layer,
755
+ indices_q,
756
+ (cu_seqlens_q, cu_seqlens_k),
757
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
758
+ )
759
+
760
+
761
+ class FalconMLP(nn.Module):
762
+ def __init__(self, config: FalconConfig):
763
+ super().__init__()
764
+ hidden_size = config.hidden_size
765
+
766
+ self.upscale = FalconLinear(
767
+ hidden_size, config.ff_factor * hidden_size, bias=config.bias
768
+ )
769
+ self.act = nn.GELU()
770
+ self.downscale = FalconLinear(
771
+ config.ff_factor * hidden_size, hidden_size, bias=config.bias
772
+ )
773
+ self.hidden_dropout = config.hidden_dropout
774
+
775
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
776
+ x = self.act(self.upscale(x))
777
+ x = self.downscale(x)
778
+ return x
779
+
780
+ FALCON_ATTENTION_CLASSES = {
781
+ "eager": FalconAttention,
782
+ "sdpa": FalconAttention, # FalconAttention originally implemented both a forward with & without SDPA
783
+ "flash_attention_2": FalconFlashAttention2,
784
+ }
785
+
786
+
787
+ class FalconDecoderLayer(nn.Module):
788
+ def __init__(self, config: FalconConfig):
789
+ super().__init__()
790
+ hidden_size = config.hidden_size
791
+ self.num_heads = config.num_attention_heads
792
+
793
+ self.self_attention = FALCON_ATTENTION_CLASSES[config._attn_implementation](config)
794
+ self.mlp = FalconMLP(config)
795
+ self.hidden_dropout = config.hidden_dropout
796
+ self.config = config
797
+
798
+ if config.new_decoder_architecture and config.num_ln_in_parallel_attn == 2:
799
+ # The layer norm before self-attention
800
+ self.ln_attn = LayerNorm(hidden_size, eps=config.layer_norm_epsilon)
801
+ # The layer norm before the MLP
802
+ self.ln_mlp = LayerNorm(hidden_size, eps=config.layer_norm_epsilon)
803
+ else:
804
+ self.input_layernorm = LayerNorm(hidden_size, eps=config.layer_norm_epsilon)
805
+ if not config.parallel_attn:
806
+ self.post_attention_layernorm = LayerNorm(hidden_size, eps=config.layer_norm_epsilon)
807
+
808
+ def forward(
809
+ self,
810
+ hidden_states: torch.Tensor,
811
+ alibi: Optional[torch.Tensor],
812
+ attention_mask: torch.Tensor,
813
+ position_ids: Optional[torch.LongTensor] = None,
814
+ layer_past: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
815
+ head_mask: Optional[torch.Tensor] = None,
816
+ use_cache: bool = False,
817
+ output_attentions: bool = False,
818
+ **kwargs,
819
+ ):
820
+ if "padding_mask" in kwargs:
821
+ warnings.warn(
822
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
823
+ )
824
+
825
+ residual = hidden_states
826
+
827
+ if self.config.num_ln_in_parallel_attn == 2:
828
+ attention_layernorm_out = self.ln_attn(hidden_states)
829
+ mlp_layernorm_out = self.ln_mlp(hidden_states)
830
+ else:
831
+ attention_layernorm_out = self.input_layernorm(hidden_states)
832
+
833
+ # Self attention.
834
+ attn_outputs = self.self_attention(
835
+ attention_layernorm_out,
836
+ layer_past=layer_past,
837
+ attention_mask=attention_mask,
838
+ position_ids=position_ids,
839
+ alibi=alibi,
840
+ head_mask=head_mask,
841
+ use_cache=use_cache,
842
+ output_attentions=output_attentions,
843
+ **kwargs,
844
+ )
845
+
846
+ attention_output = attn_outputs[0]
847
+
848
+ if self.config.num_ln_in_parallel_attn == 1:
849
+ if self.config.parallel_attn:
850
+ mlp_layernorm_out = attention_layernorm_out
851
+ else:
852
+ residual = dropout_add(
853
+ attention_output, residual, self.config.attention_dropout, training=self.training
854
+ )
855
+ mlp_layernorm_out = self.post_attention_layernorm(residual)
856
+
857
+ outputs = attn_outputs[1:]
858
+
859
+ # MLP.
860
+ mlp_output = self.mlp(mlp_layernorm_out)
861
+
862
+ if self.config.new_decoder_architecture or self.config.parallel_attn:
863
+ mlp_output += attention_output
864
+
865
+ output = dropout_add(mlp_output, residual, self.config.hidden_dropout, training=self.training)
866
+
867
+ if use_cache:
868
+ outputs = (output,) + outputs
869
+ else:
870
+ outputs = (output,) + outputs[1:]
871
+
872
+ return outputs # hidden_states, present, attentions
873
+
874
+
875
+ FALCON_START_DOCSTRING = r"""
876
+
877
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
878
+ library implements for all its model (such as downloading or saving, resizing the input embeddings etc.)
879
+
880
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
881
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
882
+ and behavior.
883
+
884
+ Parameters:
885
+ config ([`FalconConfig`]): Model configuration class with all the parameters of the model.
886
+ Initializing with a config file does not load the weights associated with the model, only the
887
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
888
+ """
889
+
890
+ FALCON_INPUTS_DOCSTRING = r"""
891
+ Args:
892
+ input_ids (`torch.LongTensor` of shape `(batch_size, input_ids_length)`):
893
+ `input_ids_length` = `sequence_length` if `past_key_values` is `None` else `past_key_values[0][0].shape[2]`
894
+ (`sequence_length` of input past key value states). Indices of input sequence tokens in the vocabulary.
895
+
896
+ If `past_key_values` is used, only `input_ids` that do not have their past calculated should be passed as
897
+ `input_ids`.
898
+
899
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
900
+ [`PreTrainedTokenizer.__call__`] for details.
901
+
902
+ [What are input IDs?](../glossary#input-ids)
903
+ past_key_values (`Tuple[Tuple[torch.Tensor]]` of length `config.num_hidden_layers`):
904
+ Contains precomputed hidden-states (key and values in the attention blocks) as computed by the model (see
905
+ `past_key_values` output below). Can be used to speed up sequential decoding. The `input_ids` which have
906
+ their past given to this model should not be passed as `input_ids` as they have already been computed.
907
+
908
+ Each element of `past_key_values` is a tuple (past_key, past_value):
909
+ - past_key: [batch_size * num_heads, head_dim, kv_length]
910
+ - past_value: [batch_size * num_heads, kv_length, head_dim]
911
+ attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
912
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
913
+
914
+ - 1 for tokens that are **not masked**,
915
+ - 0 for tokens that are **masked**.
916
+
917
+ [What are attention masks?](../glossary#attention-mask)
918
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
919
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
920
+ config.n_positions - 1]`.
921
+
922
+ [What are position IDs?](../glossary#position-ids)
923
+ head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
924
+ Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
925
+
926
+ - 1 indicates the head is **not masked**,
927
+ - 0 indicates the head is **masked**.
928
+
929
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
930
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
931
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
932
+ model's internal embedding lookup matrix.
933
+
934
+ If `past_key_values` is used, optionally only the last `inputs_embeds` have to be input (see
935
+ `past_key_values`).
936
+ use_cache (`bool`, *optional*):
937
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
938
+ `past_key_values`).
939
+ output_attentions (`bool`, *optional*):
940
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
941
+ tensors for more detail.
942
+ output_hidden_states (`bool`, *optional*):
943
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
944
+ more detail.
945
+ return_dict (`bool`, *optional*):
946
+ Whether or not to return a [`~file_utils.ModelOutput`] instead of a plain tuple.
947
+ """
948
+
949
+
950
+ class FalconPreTrainedModel(PreTrainedModel):
951
+ """
952
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
953
+ models.
954
+ """
955
+
956
+ config_class = FalconConfig
957
+ base_model_prefix = "transformer"
958
+ supports_gradient_checkpointing = True
959
+ _no_split_modules = ["FalconDecoderLayer"]
960
+ _supports_flash_attn_2 = True
961
+ _supports_sdpa = True
962
+
963
+ def __init__(self, *inputs, **kwargs):
964
+ super().__init__(*inputs, **kwargs)
965
+
966
+ def _init_weights(self, module: nn.Module):
967
+ """Initialize the weights."""
968
+ if isinstance(module, nn.Linear) or isinstance(module, FalconLinear):
969
+ # Slightly different from the TF version which uses truncated_normal for initialization
970
+ # cf https://github.com/pytorch/pytorch/pull/5617
971
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
972
+ if module.bias is not None:
973
+ module.bias.data.zero_()
974
+ elif isinstance(module, nn.Embedding):
975
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
976
+ if module.padding_idx is not None:
977
+ module.weight.data[module.padding_idx].zero_()
978
+ elif isinstance(module, LayerNorm):
979
+ module.bias.data.zero_()
980
+ module.weight.data.fill_(1.0)
981
+
982
+ # Adapted from transformers.modeling_utils.PreTrainedModel._check_and_enable_sdpa
983
+ @classmethod
984
+ def _check_and_enable_sdpa(cls, config, hard_check_only: bool = False) -> "PretrainedConfig":
985
+ # NOTE: Falcon supported SDPA from PyTorch 2.0. We keep it like that for backward compatibility (automatically use SDPA for torch>=2.0).
986
+ if hard_check_only:
987
+ if not is_torch_greater_or_equal_than_2_0:
988
+ raise ImportError("PyTorch SDPA requirements in Transformers are not met. Please install torch>=2.0.")
989
+
990
+ if not is_torch_greater_or_equal_than_2_0:
991
+ return config
992
+
993
+ _is_bettertransformer = getattr(cls, "use_bettertransformer", False)
994
+ if _is_bettertransformer:
995
+ return config
996
+
997
+ if not hard_check_only:
998
+ config._attn_implementation = "sdpa"
999
+ return config
1000
+
1001
+
1002
+ @add_start_docstrings(
1003
+ "The bare Falcon Model transformer outputting raw hidden-states without any specific head on top.",
1004
+ FALCON_START_DOCSTRING,
1005
+ )
1006
+ class FalconModel(FalconPreTrainedModel):
1007
+ def __init__(self, config: FalconConfig):
1008
+ super().__init__(config)
1009
+
1010
+ self.embed_dim = config.hidden_size
1011
+ self.num_heads = config.num_attention_heads
1012
+ self.use_alibi = config.alibi
1013
+
1014
+ # Embedding + LN Embedding
1015
+ self.word_embeddings = nn.Embedding(config.vocab_size, self.embed_dim)
1016
+
1017
+ # Transformer blocks
1018
+ self.h = nn.ModuleList([FalconDecoderLayer(config) for _ in range(config.num_hidden_layers)])
1019
+ self._use_flash_attention_2 = config._attn_implementation == "flash_attention_2"
1020
+ self._use_sdpa = config._attn_implementation == "sdpa"
1021
+
1022
+ # Final Layer Norm
1023
+ self.ln_f = LayerNorm(self.embed_dim, eps=config.layer_norm_epsilon)
1024
+
1025
+ self.gradient_checkpointing = False
1026
+
1027
+ # Initialize weights and apply final processing
1028
+ self.post_init()
1029
+
1030
+ def get_input_embeddings(self):
1031
+ return self.word_embeddings
1032
+
1033
+ def set_input_embeddings(self, new_embeddings: torch.Tensor):
1034
+ self.word_embeddings = new_embeddings
1035
+
1036
+ @add_start_docstrings_to_model_forward(FALCON_INPUTS_DOCSTRING)
1037
+ @add_code_sample_docstrings(
1038
+ checkpoint=_CHECKPOINT_FOR_DOC,
1039
+ output_type=BaseModelOutputWithPastAndCrossAttentions,
1040
+ config_class=_CONFIG_FOR_DOC,
1041
+ )
1042
+ def forward(
1043
+ self,
1044
+ input_ids: Optional[torch.LongTensor] = None,
1045
+ past_key_values: Optional[Tuple[Tuple[torch.Tensor, torch.Tensor], ...]] = None,
1046
+ attention_mask: Optional[torch.Tensor] = None,
1047
+ position_ids: Optional[torch.LongTensor] = None,
1048
+ head_mask: Optional[torch.LongTensor] = None,
1049
+ inputs_embeds: Optional[torch.LongTensor] = None,
1050
+ use_cache: Optional[bool] = None,
1051
+ output_attentions: Optional[bool] = None,
1052
+ output_hidden_states: Optional[bool] = None,
1053
+ return_dict: Optional[bool] = None,
1054
+ ) -> Union[Tuple[torch.Tensor, ...], BaseModelOutputWithPastAndCrossAttentions]:
1055
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1056
+ output_hidden_states = (
1057
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1058
+ )
1059
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1060
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1061
+
1062
+ if input_ids is not None and inputs_embeds is not None:
1063
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
1064
+ elif input_ids is not None:
1065
+ batch_size, seq_length = input_ids.shape
1066
+ elif inputs_embeds is not None:
1067
+ batch_size, seq_length, _ = inputs_embeds.shape
1068
+ else:
1069
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
1070
+
1071
+ if past_key_values is None:
1072
+ past_key_values = tuple([None] * len(self.h))
1073
+
1074
+ if inputs_embeds is None:
1075
+ inputs_embeds = self.word_embeddings(input_ids)
1076
+
1077
+ hidden_states = inputs_embeds
1078
+
1079
+ if self.gradient_checkpointing and self.training:
1080
+ if use_cache:
1081
+ logger.warning(
1082
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
1083
+ )
1084
+ use_cache = False
1085
+ presents = () if use_cache else None
1086
+ all_self_attentions = () if output_attentions else None
1087
+ all_hidden_states = () if output_hidden_states else None
1088
+
1089
+ # Compute alibi tensor: check build_alibi_tensor documentation
1090
+ past_key_values_length = 0
1091
+ if past_key_values[0] is not None:
1092
+ past_key_values_length = past_key_values[0][0].shape[-2]
1093
+
1094
+ if self.use_alibi:
1095
+ mask = (
1096
+ torch.ones(
1097
+ (batch_size, seq_length + past_key_values_length), device=inputs_embeds.device, dtype=torch.long
1098
+ )
1099
+ if attention_mask is None
1100
+ else attention_mask
1101
+ )
1102
+ alibi = build_alibi_tensor(mask, self.num_heads, dtype=hidden_states.dtype)
1103
+ else:
1104
+ alibi = None
1105
+ if position_ids is None:
1106
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
1107
+ position_ids = torch.arange(
1108
+ past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
1109
+ )
1110
+ position_ids = position_ids.unsqueeze(0)
1111
+
1112
+ if self._use_flash_attention_2:
1113
+ # 2d mask is passed through the layers
1114
+ attention_mask = attention_mask if (attention_mask is not None and 0 in attention_mask) else None
1115
+ elif self._use_sdpa and not output_attentions:
1116
+ # output_attentions=True can not be supported when using SDPA, and we fall back on
1117
+ # the manual implementation that requires a 4D causal mask in all cases.
1118
+ if alibi is None:
1119
+ attention_mask = _prepare_4d_causal_attention_mask_for_sdpa(
1120
+ attention_mask,
1121
+ (batch_size, seq_length),
1122
+ inputs_embeds,
1123
+ past_key_values_length,
1124
+ )
1125
+ elif head_mask is None:
1126
+ alibi = alibi.reshape(batch_size, -1, *alibi.shape[1:])
1127
+
1128
+ attention_mask_2d = attention_mask
1129
+ # We don't call _prepare_4d_causal_attention_mask_for_sdpa as we need to mask alibi using the 4D attention_mask untouched.
1130
+ attention_mask = _prepare_4d_causal_attention_mask(
1131
+ attention_mask, (batch_size, seq_length), inputs_embeds, past_key_values_length
1132
+ )
1133
+
1134
+ # We take care to integrate alibi bias in the attention_mask here.
1135
+ if attention_mask_2d is None:
1136
+ attention_mask = alibi / math.sqrt(self.config.hidden_size // self.num_heads)
1137
+ else:
1138
+ min_dtype = torch.finfo(alibi.dtype).min
1139
+ attention_mask = torch.masked_fill(
1140
+ alibi / math.sqrt(self.config.hidden_size // self.num_heads),
1141
+ attention_mask < -1,
1142
+ min_dtype,
1143
+ )
1144
+
1145
+ # From PyTorch 2.1 onwards, F.scaled_dot_product_attention with the memory-efficient attention backend
1146
+ # produces nans if sequences are completely unattended in the attention mask. Details: https://github.com/pytorch/pytorch/issues/110213
1147
+ if seq_length > 1 and attention_mask.device.type == "cuda":
1148
+ attention_mask = AttentionMaskConverter._unmask_unattended(attention_mask, min_dtype=min_dtype)
1149
+ else:
1150
+ # PyTorch SDPA does not support head_mask, we fall back on the eager implementation in this case.
1151
+ attention_mask = _prepare_4d_causal_attention_mask(
1152
+ attention_mask, (batch_size, seq_length), inputs_embeds, past_key_values_length
1153
+ )
1154
+ else:
1155
+ # 4d mask is passed through the layers
1156
+ attention_mask = _prepare_4d_causal_attention_mask(
1157
+ attention_mask, (batch_size, seq_length), inputs_embeds, past_key_values_length
1158
+ )
1159
+
1160
+ # Prepare head mask if needed
1161
+ # 1.0 in head_mask indicate we keep the head
1162
+ # attention_probs has shape batch_size x num_heads x N x N
1163
+ # head_mask has shape n_layer x batch x num_heads x N x N
1164
+ head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
1165
+
1166
+ for i, (block, layer_past) in enumerate(zip(self.h, past_key_values)):
1167
+ if output_hidden_states:
1168
+ all_hidden_states = all_hidden_states + (hidden_states,)
1169
+
1170
+ if self.gradient_checkpointing and self.training:
1171
+ outputs = self._gradient_checkpointing_func(
1172
+ block.__call__,
1173
+ hidden_states,
1174
+ alibi,
1175
+ attention_mask,
1176
+ position_ids,
1177
+ head_mask[i],
1178
+ layer_past,
1179
+ use_cache,
1180
+ output_attentions,
1181
+ )
1182
+ else:
1183
+ outputs = block(
1184
+ hidden_states,
1185
+ layer_past=layer_past,
1186
+ attention_mask=attention_mask,
1187
+ position_ids=position_ids,
1188
+ head_mask=head_mask[i],
1189
+ use_cache=use_cache,
1190
+ output_attentions=output_attentions,
1191
+ alibi=alibi,
1192
+ )
1193
+
1194
+ hidden_states = outputs[0]
1195
+ if use_cache is True:
1196
+ presents = presents + (outputs[1],)
1197
+
1198
+ if output_attentions:
1199
+ all_self_attentions = all_self_attentions + (outputs[2 if use_cache else 1],)
1200
+
1201
+ # Add last hidden state
1202
+ hidden_states = self.ln_f(hidden_states)
1203
+
1204
+ if output_hidden_states:
1205
+ all_hidden_states = all_hidden_states + (hidden_states,)
1206
+
1207
+ if not return_dict:
1208
+ return tuple(v for v in [hidden_states, presents, all_hidden_states, all_self_attentions] if v is not None)
1209
+
1210
+ return BaseModelOutputWithPastAndCrossAttentions(
1211
+ last_hidden_state=hidden_states,
1212
+ past_key_values=presents,
1213
+ hidden_states=all_hidden_states,
1214
+ attentions=all_self_attentions,
1215
+ )
1216
+
1217
+
1218
+ @add_start_docstrings(
1219
+ "The Falcon Model transformer with a language modeling head on top (linear layer with weights tied to the input embeddings).",
1220
+ FALCON_START_DOCSTRING,
1221
+ )
1222
+ class FalconForCausalLM(FalconPreTrainedModel):
1223
+ _tied_weights_keys = None # ["lm_head.weight"]
1224
+
1225
+ def __init__(self, config: FalconConfig):
1226
+ super().__init__(config)
1227
+ self.transformer = FalconModel(config)
1228
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1229
+
1230
+ # Initialize weights and apply final processing
1231
+ self.post_init()
1232
+
1233
+ def get_output_embeddings(self):
1234
+ return self.lm_head
1235
+
1236
+ def set_output_embeddings(self, new_embeddings: torch.Tensor):
1237
+ self.lm_head = new_embeddings
1238
+
1239
+ def prepare_inputs_for_generation(
1240
+ self,
1241
+ input_ids: torch.LongTensor,
1242
+ past_key_values: Optional[torch.Tensor] = None,
1243
+ attention_mask: Optional[torch.Tensor] = None,
1244
+ position_ids: Optional[torch.Tensor] = None,
1245
+ **kwargs,
1246
+ ) -> dict:
1247
+ if past_key_values is not None:
1248
+ past_length = past_key_values[0][0].shape[2]
1249
+
1250
+ # Some generation methods already pass only the last input ID
1251
+ if input_ids.shape[1] > past_length:
1252
+ remove_prefix_length = past_length
1253
+ else:
1254
+ # Default to old behavior: keep only final ID
1255
+ remove_prefix_length = input_ids.shape[1] - 1
1256
+
1257
+ input_ids = input_ids[:, remove_prefix_length:]
1258
+
1259
+ # Note: versions of Falcon with alibi do not use position_ids. It is used with RoPE.
1260
+ if not self.transformer.use_alibi and attention_mask is not None and position_ids is None:
1261
+ # create position_ids on the fly for batch generation
1262
+ position_ids = attention_mask.long().cumsum(-1) - 1
1263
+ position_ids.masked_fill_(attention_mask == 0, 1)
1264
+ if past_key_values:
1265
+ position_ids = position_ids[:, -input_ids.shape[1] :]
1266
+
1267
+ return {
1268
+ "input_ids": input_ids,
1269
+ "position_ids": position_ids,
1270
+ "past_key_values": past_key_values,
1271
+ "use_cache": kwargs.get("use_cache"),
1272
+ "attention_mask": attention_mask,
1273
+ }
1274
+
1275
+ @add_start_docstrings_to_model_forward(FALCON_INPUTS_DOCSTRING)
1276
+ @add_code_sample_docstrings(
1277
+ checkpoint=_CHECKPOINT_FOR_DOC,
1278
+ output_type=CausalLMOutputWithCrossAttentions,
1279
+ config_class=_CONFIG_FOR_DOC,
1280
+ )
1281
+ def forward(
1282
+ self,
1283
+ input_ids: Optional[torch.LongTensor] = None,
1284
+ past_key_values: Optional[Tuple[Tuple[torch.Tensor, torch.Tensor], ...]] = None,
1285
+ attention_mask: Optional[torch.Tensor] = None,
1286
+ position_ids: Optional[torch.LongTensor] = None,
1287
+ head_mask: Optional[torch.Tensor] = None,
1288
+ inputs_embeds: Optional[torch.Tensor] = None,
1289
+ labels: Optional[torch.Tensor] = None,
1290
+ use_cache: Optional[bool] = None,
1291
+ output_attentions: Optional[bool] = None,
1292
+ output_hidden_states: Optional[bool] = None,
1293
+ return_dict: Optional[bool] = None,
1294
+ ) -> Union[Tuple[torch.Tensor], CausalLMOutputWithCrossAttentions]:
1295
+ r"""
1296
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1297
+ Labels for language modeling. Note that the labels **are shifted** inside the model, i.e. you can set
1298
+ `labels = input_ids` Indices are selected in `[-100, 0, ..., config.vocab_size]` All labels set to `-100`
1299
+ are ignored (masked), the loss is only computed for labels in `[0, ..., config.vocab_size]`
1300
+ """
1301
+
1302
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1303
+
1304
+ transformer_outputs = self.transformer(
1305
+ input_ids,
1306
+ past_key_values=past_key_values,
1307
+ attention_mask=attention_mask,
1308
+ position_ids=position_ids,
1309
+ head_mask=head_mask,
1310
+ inputs_embeds=inputs_embeds,
1311
+ use_cache=use_cache,
1312
+ output_attentions=output_attentions,
1313
+ output_hidden_states=output_hidden_states,
1314
+ return_dict=return_dict,
1315
+ )
1316
+ hidden_states = transformer_outputs[0]
1317
+
1318
+ lm_logits = self.lm_head(hidden_states)
1319
+
1320
+ loss = None
1321
+ if labels is not None:
1322
+ # Shift so that tokens < n predict n
1323
+ shift_logits = lm_logits[..., :-1, :].contiguous()
1324
+ shift_labels = labels[..., 1:].contiguous()
1325
+ batch_size, seq_length, vocab_size = shift_logits.shape
1326
+ # Flatten the tokens
1327
+ loss_fct = CrossEntropyLoss()
1328
+ loss = loss_fct(
1329
+ shift_logits.view(batch_size * seq_length, vocab_size), shift_labels.view(batch_size * seq_length)
1330
+ )
1331
+
1332
+ if not return_dict:
1333
+ output = (lm_logits,) + transformer_outputs[1:]
1334
+ return ((loss,) + output) if loss is not None else output
1335
+
1336
+ return CausalLMOutputWithCrossAttentions(
1337
+ loss=loss,
1338
+ logits=lm_logits,
1339
+ past_key_values=transformer_outputs.past_key_values,
1340
+ hidden_states=transformer_outputs.hidden_states,
1341
+ attentions=transformer_outputs.attentions,
1342
+ )
1343
+
1344
+ def _reorder_cache(
1345
+ self, past: Tuple[Tuple[torch.Tensor, torch.Tensor], ...], beam_idx: torch.LongTensor
1346
+ ) -> Tuple[Tuple[torch.Tensor, torch.Tensor], ...]:
1347
+ """
1348
+ This function is used to re-order the `past_key_values` cache if [`~PreTrainedModel.beam_search`] or
1349
+ [`~PreTrainedModel.beam_sample`] is called. This is required to match `past_key_values` with the correct
1350
+ beam_idx at every generation step.
1351
+
1352
+ Output shares the same memory storage as `past`.
1353
+ """
1354
+
1355
+ # Get a copy of `beam_idx` on all the devices where we need those indices.
1356
+ device_to_beam_idx = {
1357
+ past_state.device: beam_idx.to(past_state.device) for layer_past in past for past_state in layer_past
1358
+ }
1359
+ reordered_past = tuple(
1360
+ (
1361
+ layer_past[0].index_select(0, device_to_beam_idx[layer_past[0].device]),
1362
+ layer_past[1].index_select(0, device_to_beam_idx[layer_past[0].device]),
1363
+ )
1364
+ for layer_past in past
1365
+ )
1366
+ return reordered_past
1367
+
1368
+
1369
+ @add_start_docstrings(
1370
+ """
1371
+ The Falcon Model transformer with a sequence classification head on top (linear layer).
1372
+
1373
+ [`FalconForSequenceClassification`] uses the last token in order to do the classification, as other causal models
1374
+ (e.g. GPT-1) do.
1375
+
1376
+ Since it does classification on the last token, it requires to know the position of the last token. If a
1377
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
1378
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1379
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1380
+ each row of the batch).
1381
+ """,
1382
+ FALCON_START_DOCSTRING,
1383
+ )
1384
+ class FalconForSequenceClassification(FalconPreTrainedModel):
1385
+ def __init__(self, config: FalconConfig):
1386
+ super().__init__(config)
1387
+ self.num_labels = config.num_labels
1388
+ self.transformer = FalconModel(config)
1389
+ self.score = nn.Linear(config.hidden_size, config.num_labels, bias=False)
1390
+
1391
+ # Initialize weights and apply final processing
1392
+ self.post_init()
1393
+
1394
+ @add_start_docstrings_to_model_forward(FALCON_INPUTS_DOCSTRING)
1395
+ @add_code_sample_docstrings(
1396
+ checkpoint=_CHECKPOINT_FOR_DOC,
1397
+ output_type=SequenceClassifierOutputWithPast,
1398
+ config_class=_CONFIG_FOR_DOC,
1399
+ )
1400
+ def forward(
1401
+ self,
1402
+ input_ids: Optional[torch.LongTensor] = None,
1403
+ past_key_values: Optional[Tuple[Tuple[torch.Tensor, torch.Tensor], ...]] = None,
1404
+ attention_mask: Optional[torch.Tensor] = None,
1405
+ head_mask: Optional[torch.Tensor] = None,
1406
+ inputs_embeds: Optional[torch.Tensor] = None,
1407
+ labels: Optional[torch.Tensor] = None,
1408
+ use_cache: Optional[bool] = None,
1409
+ output_attentions: Optional[bool] = None,
1410
+ output_hidden_states: Optional[bool] = None,
1411
+ return_dict: Optional[bool] = None,
1412
+ ) -> Union[Tuple[torch.Tensor], SequenceClassifierOutputWithPast]:
1413
+ r"""
1414
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1415
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1416
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1417
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1418
+ """
1419
+
1420
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1421
+
1422
+ transformer_outputs = self.transformer(
1423
+ input_ids,
1424
+ past_key_values=past_key_values,
1425
+ attention_mask=attention_mask,
1426
+ head_mask=head_mask,
1427
+ inputs_embeds=inputs_embeds,
1428
+ use_cache=use_cache,
1429
+ output_attentions=output_attentions,
1430
+ output_hidden_states=output_hidden_states,
1431
+ return_dict=return_dict,
1432
+ )
1433
+
1434
+ hidden_states = transformer_outputs[0]
1435
+ logits = self.score(hidden_states)
1436
+
1437
+ if input_ids is not None:
1438
+ batch_size = input_ids.shape[0]
1439
+ else:
1440
+ batch_size = inputs_embeds.shape[0]
1441
+
1442
+ if self.config.pad_token_id is None and batch_size != 1:
1443
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
1444
+ if self.config.pad_token_id is None:
1445
+ sequence_lengths = -1
1446
+ else:
1447
+ if input_ids is not None:
1448
+ # if no pad token found, use modulo instead of reverse indexing for ONNX compatibility
1449
+ sequence_lengths = torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
1450
+ sequence_lengths = sequence_lengths % input_ids.shape[-1]
1451
+ sequence_lengths = sequence_lengths.to(logits.device)
1452
+ else:
1453
+ sequence_lengths = -1
1454
+ logger.warning(
1455
+ f"{self.__class__.__name__} will not detect padding tokens in `inputs_embeds`. Results may be "
1456
+ "unexpected if using padding tokens in conjunction with `inputs_embeds.`"
1457
+ )
1458
+
1459
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
1460
+
1461
+ loss = None
1462
+ if labels is not None:
1463
+ if self.config.problem_type is None:
1464
+ if self.num_labels == 1:
1465
+ self.config.problem_type = "regression"
1466
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1467
+ self.config.problem_type = "single_label_classification"
1468
+ else:
1469
+ self.config.problem_type = "multi_label_classification"
1470
+
1471
+ if self.config.problem_type == "regression":
1472
+ loss_fct = MSELoss()
1473
+ if self.num_labels == 1:
1474
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
1475
+ else:
1476
+ loss = loss_fct(pooled_logits, labels)
1477
+ elif self.config.problem_type == "single_label_classification":
1478
+ loss_fct = CrossEntropyLoss()
1479
+ loss = loss_fct(pooled_logits, labels)
1480
+ elif self.config.problem_type == "multi_label_classification":
1481
+ loss_fct = BCEWithLogitsLoss()
1482
+ loss = loss_fct(pooled_logits, labels)
1483
+ if not return_dict:
1484
+ output = (pooled_logits,) + transformer_outputs[1:]
1485
+ return ((loss,) + output) if loss is not None else output
1486
+
1487
+ return SequenceClassifierOutputWithPast(
1488
+ loss=loss,
1489
+ logits=pooled_logits,
1490
+ past_key_values=transformer_outputs.past_key_values,
1491
+ hidden_states=transformer_outputs.hidden_states,
1492
+ attentions=transformer_outputs.attentions,
1493
+ )
1494
+
1495
+
1496
+ @add_start_docstrings(
1497
+ """
1498
+ Falcon Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for
1499
+ Named-Entity-Recognition (NER) tasks.
1500
+ """,
1501
+ FALCON_START_DOCSTRING,
1502
+ )
1503
+ class FalconForTokenClassification(FalconPreTrainedModel):
1504
+ def __init__(self, config: FalconConfig):
1505
+ super().__init__(config)
1506
+ self.num_labels = config.num_labels
1507
+
1508
+ self.transformer = FalconModel(config)
1509
+ if getattr(config, "classifier_dropout", None) is not None:
1510
+ classifier_dropout = config.classifier_dropout
1511
+ elif getattr(config, "hidden_dropout", None) is not None:
1512
+ classifier_dropout = config.hidden_dropout
1513
+ else:
1514
+ classifier_dropout = 0.1
1515
+ self.dropout = nn.Dropout(classifier_dropout)
1516
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
1517
+
1518
+ # Initialize weights and apply final processing
1519
+ self.post_init()
1520
+
1521
+ @add_start_docstrings_to_model_forward(FALCON_INPUTS_DOCSTRING)
1522
+ @add_code_sample_docstrings(
1523
+ checkpoint=_CHECKPOINT_FOR_DOC,
1524
+ output_type=TokenClassifierOutput,
1525
+ config_class=_CONFIG_FOR_DOC,
1526
+ )
1527
+ def forward(
1528
+ self,
1529
+ input_ids: Optional[torch.LongTensor] = None,
1530
+ past_key_values: Optional[Tuple[Tuple[torch.Tensor, torch.Tensor], ...]] = None,
1531
+ attention_mask: Optional[torch.Tensor] = None,
1532
+ head_mask: Optional[torch.Tensor] = None,
1533
+ inputs_embeds: Optional[torch.Tensor] = None,
1534
+ labels: Optional[torch.Tensor] = None,
1535
+ use_cache: Optional[bool] = None,
1536
+ output_attentions: Optional[bool] = None,
1537
+ output_hidden_states: Optional[bool] = None,
1538
+ return_dict: Optional[bool] = None,
1539
+ ) -> Union[Tuple[torch.Tensor], TokenClassifierOutput]:
1540
+ r"""
1541
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1542
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1543
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1544
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1545
+ """
1546
+
1547
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1548
+
1549
+ transformer_outputs = self.transformer(
1550
+ input_ids,
1551
+ past_key_values=past_key_values,
1552
+ attention_mask=attention_mask,
1553
+ head_mask=head_mask,
1554
+ inputs_embeds=inputs_embeds,
1555
+ use_cache=use_cache,
1556
+ output_attentions=output_attentions,
1557
+ output_hidden_states=output_hidden_states,
1558
+ return_dict=return_dict,
1559
+ )
1560
+
1561
+ hidden_states = transformer_outputs[0]
1562
+ hidden_states = self.dropout(hidden_states)
1563
+ logits = self.classifier(hidden_states)
1564
+
1565
+ loss = None
1566
+ if labels is not None:
1567
+ batch_size, seq_length = labels.shape
1568
+ loss_fct = CrossEntropyLoss()
1569
+ loss = loss_fct(
1570
+ logits.view(batch_size * seq_length, self.num_labels), labels.view(batch_size * seq_length)
1571
+ )
1572
+
1573
+ if not return_dict:
1574
+ output = (logits,) + transformer_outputs[2:]
1575
+ return ((loss,) + output) if loss is not None else output
1576
+
1577
+ return TokenClassifierOutput(
1578
+ loss=loss,
1579
+ logits=logits,
1580
+ hidden_states=transformer_outputs.hidden_states,
1581
+ attentions=transformer_outputs.attentions,
1582
+ )
1583
+
1584
+
1585
+ @add_start_docstrings(
1586
+ """
1587
+ The Falcon Model transformer with a span classification head on top for extractive question-answering tasks like
1588
+ SQuAD (a linear layers on top of the hidden-states output to compute `span start logits` and `span end logits`).
1589
+ """,
1590
+ FALCON_START_DOCSTRING,
1591
+ )
1592
+ class FalconForQuestionAnswering(FalconPreTrainedModel):
1593
+ def __init__(self, config):
1594
+ super().__init__(config)
1595
+ self.transformer = FalconModel(config)
1596
+ self.qa_outputs = nn.Linear(config.hidden_size, 2)
1597
+
1598
+ # Initialize weights and apply final processing
1599
+ self.post_init()
1600
+
1601
+ @add_start_docstrings_to_model_forward(FALCON_INPUTS_DOCSTRING)
1602
+ def forward(
1603
+ self,
1604
+ input_ids: Optional[torch.LongTensor] = None,
1605
+ attention_mask: Optional[torch.FloatTensor] = None,
1606
+ head_mask: Optional[torch.FloatTensor] = None,
1607
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1608
+ start_positions: Optional[torch.LongTensor] = None,
1609
+ end_positions: Optional[torch.LongTensor] = None,
1610
+ output_attentions: Optional[bool] = None,
1611
+ output_hidden_states: Optional[bool] = None,
1612
+ return_dict: Optional[bool] = None,
1613
+ ) -> Union[Tuple, QuestionAnsweringModelOutput]:
1614
+ r"""
1615
+ start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1616
+ Labels for position (index) of the start of the labelled span for computing the token classification loss.
1617
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
1618
+ are not taken into account for computing the loss.
1619
+ end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1620
+ Labels for position (index) of the end of the labelled span for computing the token classification loss.
1621
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
1622
+ are not taken into account for computing the loss.
1623
+ """
1624
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1625
+
1626
+ outputs = self.transformer(
1627
+ input_ids,
1628
+ attention_mask=attention_mask,
1629
+ head_mask=head_mask,
1630
+ inputs_embeds=inputs_embeds,
1631
+ output_attentions=output_attentions,
1632
+ output_hidden_states=output_hidden_states,
1633
+ return_dict=return_dict,
1634
+ )
1635
+
1636
+ sequence_output = outputs[0]
1637
+
1638
+ logits = self.qa_outputs(sequence_output)
1639
+ start_logits, end_logits = logits.split(1, dim=-1)
1640
+ start_logits = start_logits.squeeze(-1).contiguous()
1641
+ end_logits = end_logits.squeeze(-1).contiguous()
1642
+
1643
+ total_loss = None
1644
+ if start_positions is not None and end_positions is not None:
1645
+ # If we are on multi-GPU, split add a dimension
1646
+ if len(start_positions.size()) > 1:
1647
+ start_positions = start_positions.squeeze(-1)
1648
+ if len(end_positions.size()) > 1:
1649
+ end_positions = end_positions.squeeze(-1)
1650
+ # sometimes the start/end positions are outside our model inputs, we ignore these terms
1651
+ ignored_index = start_logits.size(1)
1652
+ start_positions = start_positions.clamp(0, ignored_index)
1653
+ end_positions = end_positions.clamp(0, ignored_index)
1654
+
1655
+ loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
1656
+ start_loss = loss_fct(start_logits, start_positions)
1657
+ end_loss = loss_fct(end_logits, end_positions)
1658
+ total_loss = (start_loss + end_loss) / 2
1659
+
1660
+ if not return_dict:
1661
+ output = (start_logits, end_logits) + outputs[2:]
1662
+ return ((total_loss,) + output) if total_loss is not None else output
1663
+
1664
+ return QuestionAnsweringModelOutput(
1665
+ loss=total_loss,
1666
+ start_logits=start_logits,
1667
+ end_logits=end_logits,
1668
+ hidden_states=outputs.hidden_states,
1669
+ attentions=outputs.attentions,
1670
+ )
.ipynb_checkpoints/special_tokens_map-checkpoint.json ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "additional_special_tokens": [
3
+ ">>TITLE<<",
4
+ ">>ABSTRACT<<",
5
+ ">>INTRODUCTION<<",
6
+ ">>SUMMARY<<",
7
+ ">>COMMENT<<",
8
+ ">>ANSWER<<",
9
+ ">>QUESTION<<",
10
+ ">>DOMAIN<<",
11
+ ">>PREFIX<<",
12
+ ">>SUFFIX<<",
13
+ ">>MIDDLE<<"
14
+ ],
15
+ "bos_token": ">>",
16
+ "eos_token": {
17
+ "content": "<|endoftext|>",
18
+ "lstrip": false,
19
+ "normalized": false,
20
+ "rstrip": false,
21
+ "single_word": false
22
+ },
23
+ "pad_token": "<|endoftext|>"
24
+ }
.ipynb_checkpoints/tokenizer-checkpoint.json ADDED
The diff for this file is too large to render. See raw diff
 
.ipynb_checkpoints/tokenizer_config-checkpoint.json ADDED
@@ -0,0 +1,135 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_prefix_space": false,
3
+ "added_tokens_decoder": {
4
+ "0": {
5
+ "content": ">>TITLE<<",
6
+ "lstrip": false,
7
+ "normalized": false,
8
+ "rstrip": false,
9
+ "single_word": false,
10
+ "special": true
11
+ },
12
+ "1": {
13
+ "content": ">>ABSTRACT<<",
14
+ "lstrip": false,
15
+ "normalized": false,
16
+ "rstrip": false,
17
+ "single_word": false,
18
+ "special": true
19
+ },
20
+ "2": {
21
+ "content": ">>INTRODUCTION<<",
22
+ "lstrip": false,
23
+ "normalized": false,
24
+ "rstrip": false,
25
+ "single_word": false,
26
+ "special": true
27
+ },
28
+ "3": {
29
+ "content": ">>SUMMARY<<",
30
+ "lstrip": false,
31
+ "normalized": false,
32
+ "rstrip": false,
33
+ "single_word": false,
34
+ "special": true
35
+ },
36
+ "4": {
37
+ "content": ">>COMMENT<<",
38
+ "lstrip": false,
39
+ "normalized": false,
40
+ "rstrip": false,
41
+ "single_word": false,
42
+ "special": true
43
+ },
44
+ "5": {
45
+ "content": ">>ANSWER<<",
46
+ "lstrip": false,
47
+ "normalized": false,
48
+ "rstrip": false,
49
+ "single_word": false,
50
+ "special": true
51
+ },
52
+ "6": {
53
+ "content": ">>QUESTION<<",
54
+ "lstrip": false,
55
+ "normalized": false,
56
+ "rstrip": false,
57
+ "single_word": false,
58
+ "special": true
59
+ },
60
+ "7": {
61
+ "content": ">>DOMAIN<<",
62
+ "lstrip": false,
63
+ "normalized": false,
64
+ "rstrip": false,
65
+ "single_word": false,
66
+ "special": true
67
+ },
68
+ "8": {
69
+ "content": ">>PREFIX<<",
70
+ "lstrip": false,
71
+ "normalized": false,
72
+ "rstrip": false,
73
+ "single_word": false,
74
+ "special": true
75
+ },
76
+ "9": {
77
+ "content": ">>SUFFIX<<",
78
+ "lstrip": false,
79
+ "normalized": false,
80
+ "rstrip": false,
81
+ "single_word": false,
82
+ "special": true
83
+ },
84
+ "10": {
85
+ "content": ">>MIDDLE<<",
86
+ "lstrip": false,
87
+ "normalized": false,
88
+ "rstrip": false,
89
+ "single_word": false,
90
+ "special": true
91
+ },
92
+ "11": {
93
+ "content": "<|endoftext|>",
94
+ "lstrip": false,
95
+ "normalized": false,
96
+ "rstrip": false,
97
+ "single_word": false,
98
+ "special": true
99
+ },
100
+ "500": {
101
+ "content": ">>",
102
+ "lstrip": false,
103
+ "normalized": false,
104
+ "rstrip": false,
105
+ "single_word": false,
106
+ "special": true
107
+ }
108
+ },
109
+ "additional_special_tokens": [
110
+ ">>TITLE<<",
111
+ ">>ABSTRACT<<",
112
+ ">>INTRODUCTION<<",
113
+ ">>SUMMARY<<",
114
+ ">>COMMENT<<",
115
+ ">>ANSWER<<",
116
+ ">>QUESTION<<",
117
+ ">>DOMAIN<<",
118
+ ">>PREFIX<<",
119
+ ">>SUFFIX<<",
120
+ ">>MIDDLE<<"
121
+ ],
122
+ "bos_token": ">>",
123
+ "chat_template": "{% for message in messages %}\n{% if message['role'] == 'user' %}\n{{ 'User: \n' + message['content'] }}\n{% elif message['role'] == 'system' %}\n{{ 'System: ' + message['content'] }}\n{% elif message['role'] == 'assistant' %}\n{{ 'Falcon:\n' + message['content']}}\n{% endif %}\n{% if loop.last and add_generation_prompt %}\n{{ 'Falcon:' }}\n{% endif %}\n{% endfor %}",
124
+ "clean_up_tokenization_spaces": true,
125
+ "device_map": "cuda:2",
126
+ "eos_token": "<|endoftext|>",
127
+ "model_input_names": [
128
+ "input_ids",
129
+ "attention_mask"
130
+ ],
131
+ "model_max_length": 1000000000000000019884624838656,
132
+ "pad_token": "<|endoftext|>",
133
+ "padding_side": "left",
134
+ "tokenizer_class": "PreTrainedTokenizerFast"
135
+ }
config.json ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "tiiuae/falcon-11B",
3
+ "activation": "gelu",
4
+ "alibi": false,
5
+ "architectures": [
6
+ "FalconForCausalLM"
7
+ ],
8
+ "attention_dropout": 0.0,
9
+ "auto_map": {
10
+ "AutoConfig": "tiiuae/falcon-11B--configuration_falcon.FalconConfig",
11
+ "AutoModel": "tiiuae/falcon-11B--modeling_falcon.FalconModel",
12
+ "AutoModelForCausalLM": "tiiuae/falcon-11B--modeling_falcon.FalconForCausalLM",
13
+ "AutoModelForQuestionAnswering": "tiiuae/falcon-11B--modeling_falcon.FalconForQuestionAnswering",
14
+ "AutoModelForSequenceClassification": "tiiuae/falcon-11B--modeling_falcon.FalconForSequenceClassification",
15
+ "AutoModelForTokenClassification": "tiiuae/falcon-11B--modeling_falcon.FalconForTokenClassification"
16
+ },
17
+ "bias": false,
18
+ "bos_token_id": 11,
19
+ "eos_token_id": 11,
20
+ "ff_factor": 4,
21
+ "ffn_hidden_size": 16384,
22
+ "hidden_dropout": 0.0,
23
+ "hidden_size": 4096,
24
+ "initializer_range": 0.02,
25
+ "layer_norm_epsilon": 1e-05,
26
+ "max_position_embeddings": 8192,
27
+ "model_type": "falcon",
28
+ "multi_query": true,
29
+ "new_decoder_architecture": true,
30
+ "num_attention_heads": 32,
31
+ "num_hidden_layers": 60,
32
+ "num_kv_heads": 8,
33
+ "num_ln_in_parallel_attn": 1,
34
+ "parallel_attn": true,
35
+ "rope_scaling": null,
36
+ "rope_theta": 500042.0,
37
+ "rotary_base": 5000042,
38
+ "tie_word_embeddings": false,
39
+ "torch_dtype": "bfloat16",
40
+ "transformers_version": "4.39.2",
41
+ "use_cache": true,
42
+ "vocab_size": 65024
43
+ }
configuration_falcon.py ADDED
@@ -0,0 +1,192 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 the Falcon authors and HuggingFace Inc. team. 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
+ """ Falcon configuration"""
16
+ from transformers.configuration_utils import PretrainedConfig
17
+ from transformers.utils import logging
18
+
19
+
20
+ logger = logging.get_logger(__name__)
21
+
22
+ FALCON_PRETRAINED_CONFIG_ARCHIVE_MAP = {
23
+ "tiiuae/falcon-40b": "https://huggingface.co/tiiuae/falcon-40b/resolve/main/config.json",
24
+ "tiiuae/falcon-7b": "https://huggingface.co/tiiuae/falcon-7b/resolve/main/config.json",
25
+ }
26
+
27
+
28
+ class FalconConfig(PretrainedConfig):
29
+ r"""
30
+ This is the configuration class to store the configuration of a [`FalconModel`]. It is used to instantiate a Falcon
31
+ model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
32
+ defaults will yield a similar configuration to that of the
33
+ [tiiuae/falcon-7b](https://huggingface.co/tiiuae/falcon-7b) architecture.
34
+
35
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
36
+ documentation from [`PretrainedConfig`] for more information.
37
+
38
+
39
+ Args:
40
+ vocab_size (`int`, *optional*, defaults to 65024):
41
+ Vocabulary size of the Falcon model. Defines the number of different tokens that can be represented by the
42
+ `inputs_ids` passed when calling [`FalconModel`]
43
+ hidden_size (`int`, *optional*, defaults to 4544):
44
+ Dimension of the hidden representations.
45
+ num_hidden_layers (`int`, *optional*, defaults to 32):
46
+ Number of hidden layers in the Transformer decoder.
47
+ num_attention_heads (`int`, *optional*, defaults to 71):
48
+ Number of attention heads for each attention layer in the Transformer encoder.
49
+ layer_norm_epsilon (`float`, *optional*, defaults to 1e-05):
50
+ The epsilon used by the layer normalization layers.
51
+ initializer_range (`float`, *optional*, defaults to 0.02):
52
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
53
+ use_cache (`bool`, *optional*, defaults to `True`):
54
+ Whether the model should return the last key/values attentions (not used by all models). Only relevant if
55
+ `config.is_decoder=True`.
56
+ hidden_dropout (`float`, *optional*, defaults to 0.0):
57
+ The dropout probability for MLP layers.
58
+ attention_dropout (`float`, *optional*, defaults to 0.0):
59
+ The dropout probability for attention layers.
60
+ num_kv_heads (`int`, *optional*):
61
+ Number of key-value heads to use per attention layer. If unset, defaults to the same value as
62
+ `num_attention_heads`.
63
+ alibi (`bool`, *optional*, defaults to `False`):
64
+ Whether to use ALiBi positional biases during self-attention.
65
+ new_decoder_architecture (`bool`, *optional*, defaults to `False`):
66
+ Whether to use the new (Falcon-40B) decoder architecture. If `True`, the `multi_query` and `parallel_attn`
67
+ arguments are ignored, as the new decoder always uses parallel attention.
68
+ multi_query (`bool`, *optional*, defaults to `True`):
69
+ Whether to use multi-query attention in the decoder. Ignored when `new_decoder_architecture` is `True`.
70
+ parallel_attn (`bool`, *optional*, defaults to `True`):
71
+ Whether to compute attention in parallel with the feedforward layer. If False, they are consecutive
72
+ instead, as in the original Transformer architecture. Ignored when `new_decoder_architecture` is `True`.
73
+ bias (`bool`, *optional*, defaults to `False`):
74
+ Whether to use bias on Linear layers.
75
+ max_position_embeddings (`int`, *optional*, defaults to 2048):
76
+ The maximum sequence length that this model might ever be used with, when `alibi` is `False`. Pretrained
77
+ Falcon models with RoPE support up to 2048 tokens.
78
+ rope_theta (`float`, *optional*, defaults to 10000.0):
79
+ The base period of the RoPE embeddings.
80
+ rope_scaling (`Dict`, *optional*):
81
+ Dictionary containing the scaling configuration for the RoPE embeddings. Currently supports two scaling
82
+ strategies: linear and dynamic. Their scaling factor must be a float greater than 1. The expected format is
83
+ `{"type": strategy name, "factor": scaling factor}`. When using this flag, don't update
84
+ `max_position_embeddings` to the expected new maximum. See the following thread for more information on how
85
+ these scaling strategies behave:
86
+ https://www.reddit.com/r/LocalLLaMA/comments/14mrgpr/dynamically_scaled_rope_further_increases/. This is an
87
+ experimental feature, subject to breaking API changes in future versions.
88
+ bos_token_id (`int`, *optional*, defaults to 11):
89
+ The id of the "beginning-of-sequence" token.
90
+ eos_token_id (`int`, *optional*, defaults to 11):
91
+ The id of the "end-of-sequence" token.
92
+
93
+ Example:
94
+
95
+ ```python
96
+ >>> from transformers import FalconModel, FalconConfig
97
+
98
+ >>> # Initializing a small (2-layer) Falcon configuration
99
+ >>> configuration = FalconConfig(num_hidden_layers=2)
100
+
101
+ >>> # Initializing a model from the small configuration
102
+ >>> model = FalconModel(configuration)
103
+
104
+ >>> # Accessing the model configuration
105
+ >>> configuration = model.config
106
+ ```"""
107
+
108
+ model_type = "falcon"
109
+ keys_to_ignore_at_inference = ["past_key_values"]
110
+
111
+ def __init__(
112
+ self,
113
+ vocab_size=65024,
114
+ hidden_size=4544,
115
+ num_hidden_layers=32,
116
+ num_attention_heads=71,
117
+ layer_norm_epsilon=1e-5,
118
+ initializer_range=0.02,
119
+ use_cache=True,
120
+ hidden_dropout=0.0,
121
+ attention_dropout=0.0,
122
+ num_kv_heads=None,
123
+ alibi=False,
124
+ new_decoder_architecture=False,
125
+ multi_query=True,
126
+ parallel_attn=True,
127
+ bias=False,
128
+ max_position_embeddings=8192,
129
+ rope_theta=10000.0,
130
+ rope_scaling=None,
131
+ bos_token_id=11,
132
+ eos_token_id=11,
133
+ **kwargs,
134
+ ):
135
+ self.vocab_size = vocab_size
136
+ # Backward compatibility with n_embed kwarg
137
+ n_embed = kwargs.pop("n_embed", None)
138
+ self.hidden_size = hidden_size if n_embed is None else n_embed
139
+ self.num_hidden_layers = num_hidden_layers
140
+ self.num_attention_heads = num_attention_heads
141
+ self.layer_norm_epsilon = layer_norm_epsilon
142
+ self.initializer_range = initializer_range
143
+ self.use_cache = use_cache
144
+ self.hidden_dropout = hidden_dropout
145
+ self.attention_dropout = attention_dropout
146
+
147
+ self.bos_token_id = bos_token_id
148
+ self.eos_token_id = eos_token_id
149
+ self.num_kv_heads = num_attention_heads if num_kv_heads is None else num_kv_heads
150
+ self.alibi = alibi
151
+ self.new_decoder_architecture = new_decoder_architecture
152
+ self.multi_query = multi_query # Ignored when new_decoder_architecture is True
153
+ self.parallel_attn = parallel_attn
154
+ self.bias = bias
155
+ self.max_position_embeddings = max_position_embeddings
156
+ self.rope_theta = rope_theta
157
+ self.rope_scaling = rope_scaling
158
+ self._rope_scaling_validation()
159
+
160
+ super().__init__(bos_token_id=bos_token_id, eos_token_id=eos_token_id, **kwargs)
161
+
162
+ @property
163
+ def head_dim(self):
164
+ return self.hidden_size // self.num_attention_heads
165
+
166
+ @property
167
+ def rotary(self):
168
+ return not self.alibi
169
+
170
+ def _rope_scaling_validation(self):
171
+ """
172
+ Validate the `rope_scaling` configuration.
173
+ """
174
+ if self.rope_scaling is None:
175
+ return
176
+
177
+ if self.alibi:
178
+ raise ValueError("`rope_scaling` is not supported when `alibi` is `True`.")
179
+
180
+ if not isinstance(self.rope_scaling, dict) or len(self.rope_scaling) != 2:
181
+ raise ValueError(
182
+ "`rope_scaling` must be a dictionary with with two fields, `type` and `factor`, "
183
+ f"got {self.rope_scaling}"
184
+ )
185
+ rope_scaling_type = self.rope_scaling.get("type", None)
186
+ rope_scaling_factor = self.rope_scaling.get("factor", None)
187
+ if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]:
188
+ raise ValueError(
189
+ f"`rope_scaling`'s type field must be one of ['linear', 'dynamic'], got {rope_scaling_type}"
190
+ )
191
+ if rope_scaling_factor is None or not isinstance(rope_scaling_factor, float) or rope_scaling_factor <= 1.0:
192
+ raise ValueError(f"`rope_scaling`'s factor field must be a float > 1, got {rope_scaling_factor}")
generation_config.json ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "bos_token_id": 11,
4
+ "eos_token_id": 11,
5
+ "transformers_version": "4.40.1"
6
+ }
model-00001-of-00005.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a7f12d1629a8a47b89f57b80c7fc4781347970f47df4c2c35d7908948ee285bd
3
+ size 4978844408
model-00002-of-00005.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:01ca0693ff809a32700e4255c2d85aaf5ba4934edbea289a9055b5661abb5fcf
3
+ size 4932740832
model-00003-of-00005.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a31b75705b43abca86920c0bc8cc12bb0ec62ca99e9e8ce928946d878936ae2b
3
+ size 4932740832
model-00004-of-00005.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1880ff98c2c5227b8436514be14f1261a48e2bbf426974b2143d6e41de6280f6
3
+ size 4932740832
model-00005-of-00005.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ec0c1b5f09be4f2019194d03767fa53226bdbe33f560c15893f968581064f8a1
3
+ size 2428620904
model.safetensors.index.json ADDED
@@ -0,0 +1,371 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "metadata": {
3
+ "total_size": 22205644800
4
+ },
5
+ "weight_map": {
6
+ "lm_head.weight": "model-00005-of-00005.safetensors",
7
+ "transformer.h.0.input_layernorm.bias": "model-00001-of-00005.safetensors",
8
+ "transformer.h.0.input_layernorm.weight": "model-00001-of-00005.safetensors",
9
+ "transformer.h.0.mlp.downscale.weight": "model-00001-of-00005.safetensors",
10
+ "transformer.h.0.mlp.upscale.weight": "model-00001-of-00005.safetensors",
11
+ "transformer.h.0.self_attention.dense.weight": "model-00001-of-00005.safetensors",
12
+ "transformer.h.0.self_attention.query_key_value.weight": "model-00001-of-00005.safetensors",
13
+ "transformer.h.1.input_layernorm.bias": "model-00001-of-00005.safetensors",
14
+ "transformer.h.1.input_layernorm.weight": "model-00001-of-00005.safetensors",
15
+ "transformer.h.1.mlp.downscale.weight": "model-00001-of-00005.safetensors",
16
+ "transformer.h.1.mlp.upscale.weight": "model-00001-of-00005.safetensors",
17
+ "transformer.h.1.self_attention.dense.weight": "model-00001-of-00005.safetensors",
18
+ "transformer.h.1.self_attention.query_key_value.weight": "model-00001-of-00005.safetensors",
19
+ "transformer.h.10.input_layernorm.bias": "model-00001-of-00005.safetensors",
20
+ "transformer.h.10.input_layernorm.weight": "model-00001-of-00005.safetensors",
21
+ "transformer.h.10.mlp.downscale.weight": "model-00001-of-00005.safetensors",
22
+ "transformer.h.10.mlp.upscale.weight": "model-00001-of-00005.safetensors",
23
+ "transformer.h.10.self_attention.dense.weight": "model-00001-of-00005.safetensors",
24
+ "transformer.h.10.self_attention.query_key_value.weight": "model-00001-of-00005.safetensors",
25
+ "transformer.h.11.input_layernorm.bias": "model-00001-of-00005.safetensors",
26
+ "transformer.h.11.input_layernorm.weight": "model-00001-of-00005.safetensors",
27
+ "transformer.h.11.mlp.downscale.weight": "model-00001-of-00005.safetensors",
28
+ "transformer.h.11.mlp.upscale.weight": "model-00001-of-00005.safetensors",
29
+ "transformer.h.11.self_attention.dense.weight": "model-00001-of-00005.safetensors",
30
+ "transformer.h.11.self_attention.query_key_value.weight": "model-00001-of-00005.safetensors",
31
+ "transformer.h.12.input_layernorm.bias": "model-00002-of-00005.safetensors",
32
+ "transformer.h.12.input_layernorm.weight": "model-00002-of-00005.safetensors",
33
+ "transformer.h.12.mlp.downscale.weight": "model-00002-of-00005.safetensors",
34
+ "transformer.h.12.mlp.upscale.weight": "model-00001-of-00005.safetensors",
35
+ "transformer.h.12.self_attention.dense.weight": "model-00001-of-00005.safetensors",
36
+ "transformer.h.12.self_attention.query_key_value.weight": "model-00001-of-00005.safetensors",
37
+ "transformer.h.13.input_layernorm.bias": "model-00002-of-00005.safetensors",
38
+ "transformer.h.13.input_layernorm.weight": "model-00002-of-00005.safetensors",
39
+ "transformer.h.13.mlp.downscale.weight": "model-00002-of-00005.safetensors",
40
+ "transformer.h.13.mlp.upscale.weight": "model-00002-of-00005.safetensors",
41
+ "transformer.h.13.self_attention.dense.weight": "model-00002-of-00005.safetensors",
42
+ "transformer.h.13.self_attention.query_key_value.weight": "model-00002-of-00005.safetensors",
43
+ "transformer.h.14.input_layernorm.bias": "model-00002-of-00005.safetensors",
44
+ "transformer.h.14.input_layernorm.weight": "model-00002-of-00005.safetensors",
45
+ "transformer.h.14.mlp.downscale.weight": "model-00002-of-00005.safetensors",
46
+ "transformer.h.14.mlp.upscale.weight": "model-00002-of-00005.safetensors",
47
+ "transformer.h.14.self_attention.dense.weight": "model-00002-of-00005.safetensors",
48
+ "transformer.h.14.self_attention.query_key_value.weight": "model-00002-of-00005.safetensors",
49
+ "transformer.h.15.input_layernorm.bias": "model-00002-of-00005.safetensors",
50
+ "transformer.h.15.input_layernorm.weight": "model-00002-of-00005.safetensors",
51
+ "transformer.h.15.mlp.downscale.weight": "model-00002-of-00005.safetensors",
52
+ "transformer.h.15.mlp.upscale.weight": "model-00002-of-00005.safetensors",
53
+ "transformer.h.15.self_attention.dense.weight": "model-00002-of-00005.safetensors",
54
+ "transformer.h.15.self_attention.query_key_value.weight": "model-00002-of-00005.safetensors",
55
+ "transformer.h.16.input_layernorm.bias": "model-00002-of-00005.safetensors",
56
+ "transformer.h.16.input_layernorm.weight": "model-00002-of-00005.safetensors",
57
+ "transformer.h.16.mlp.downscale.weight": "model-00002-of-00005.safetensors",
58
+ "transformer.h.16.mlp.upscale.weight": "model-00002-of-00005.safetensors",
59
+ "transformer.h.16.self_attention.dense.weight": "model-00002-of-00005.safetensors",
60
+ "transformer.h.16.self_attention.query_key_value.weight": "model-00002-of-00005.safetensors",
61
+ "transformer.h.17.input_layernorm.bias": "model-00002-of-00005.safetensors",
62
+ "transformer.h.17.input_layernorm.weight": "model-00002-of-00005.safetensors",
63
+ "transformer.h.17.mlp.downscale.weight": "model-00002-of-00005.safetensors",
64
+ "transformer.h.17.mlp.upscale.weight": "model-00002-of-00005.safetensors",
65
+ "transformer.h.17.self_attention.dense.weight": "model-00002-of-00005.safetensors",
66
+ "transformer.h.17.self_attention.query_key_value.weight": "model-00002-of-00005.safetensors",
67
+ "transformer.h.18.input_layernorm.bias": "model-00002-of-00005.safetensors",
68
+ "transformer.h.18.input_layernorm.weight": "model-00002-of-00005.safetensors",
69
+ "transformer.h.18.mlp.downscale.weight": "model-00002-of-00005.safetensors",
70
+ "transformer.h.18.mlp.upscale.weight": "model-00002-of-00005.safetensors",
71
+ "transformer.h.18.self_attention.dense.weight": "model-00002-of-00005.safetensors",
72
+ "transformer.h.18.self_attention.query_key_value.weight": "model-00002-of-00005.safetensors",
73
+ "transformer.h.19.input_layernorm.bias": "model-00002-of-00005.safetensors",
74
+ "transformer.h.19.input_layernorm.weight": "model-00002-of-00005.safetensors",
75
+ "transformer.h.19.mlp.downscale.weight": "model-00002-of-00005.safetensors",
76
+ "transformer.h.19.mlp.upscale.weight": "model-00002-of-00005.safetensors",
77
+ "transformer.h.19.self_attention.dense.weight": "model-00002-of-00005.safetensors",
78
+ "transformer.h.19.self_attention.query_key_value.weight": "model-00002-of-00005.safetensors",
79
+ "transformer.h.2.input_layernorm.bias": "model-00001-of-00005.safetensors",
80
+ "transformer.h.2.input_layernorm.weight": "model-00001-of-00005.safetensors",
81
+ "transformer.h.2.mlp.downscale.weight": "model-00001-of-00005.safetensors",
82
+ "transformer.h.2.mlp.upscale.weight": "model-00001-of-00005.safetensors",
83
+ "transformer.h.2.self_attention.dense.weight": "model-00001-of-00005.safetensors",
84
+ "transformer.h.2.self_attention.query_key_value.weight": "model-00001-of-00005.safetensors",
85
+ "transformer.h.20.input_layernorm.bias": "model-00002-of-00005.safetensors",
86
+ "transformer.h.20.input_layernorm.weight": "model-00002-of-00005.safetensors",
87
+ "transformer.h.20.mlp.downscale.weight": "model-00002-of-00005.safetensors",
88
+ "transformer.h.20.mlp.upscale.weight": "model-00002-of-00005.safetensors",
89
+ "transformer.h.20.self_attention.dense.weight": "model-00002-of-00005.safetensors",
90
+ "transformer.h.20.self_attention.query_key_value.weight": "model-00002-of-00005.safetensors",
91
+ "transformer.h.21.input_layernorm.bias": "model-00002-of-00005.safetensors",
92
+ "transformer.h.21.input_layernorm.weight": "model-00002-of-00005.safetensors",
93
+ "transformer.h.21.mlp.downscale.weight": "model-00002-of-00005.safetensors",
94
+ "transformer.h.21.mlp.upscale.weight": "model-00002-of-00005.safetensors",
95
+ "transformer.h.21.self_attention.dense.weight": "model-00002-of-00005.safetensors",
96
+ "transformer.h.21.self_attention.query_key_value.weight": "model-00002-of-00005.safetensors",
97
+ "transformer.h.22.input_layernorm.bias": "model-00002-of-00005.safetensors",
98
+ "transformer.h.22.input_layernorm.weight": "model-00002-of-00005.safetensors",
99
+ "transformer.h.22.mlp.downscale.weight": "model-00002-of-00005.safetensors",
100
+ "transformer.h.22.mlp.upscale.weight": "model-00002-of-00005.safetensors",
101
+ "transformer.h.22.self_attention.dense.weight": "model-00002-of-00005.safetensors",
102
+ "transformer.h.22.self_attention.query_key_value.weight": "model-00002-of-00005.safetensors",
103
+ "transformer.h.23.input_layernorm.bias": "model-00002-of-00005.safetensors",
104
+ "transformer.h.23.input_layernorm.weight": "model-00002-of-00005.safetensors",
105
+ "transformer.h.23.mlp.downscale.weight": "model-00002-of-00005.safetensors",
106
+ "transformer.h.23.mlp.upscale.weight": "model-00002-of-00005.safetensors",
107
+ "transformer.h.23.self_attention.dense.weight": "model-00002-of-00005.safetensors",
108
+ "transformer.h.23.self_attention.query_key_value.weight": "model-00002-of-00005.safetensors",
109
+ "transformer.h.24.input_layernorm.bias": "model-00002-of-00005.safetensors",
110
+ "transformer.h.24.input_layernorm.weight": "model-00002-of-00005.safetensors",
111
+ "transformer.h.24.mlp.downscale.weight": "model-00002-of-00005.safetensors",
112
+ "transformer.h.24.mlp.upscale.weight": "model-00002-of-00005.safetensors",
113
+ "transformer.h.24.self_attention.dense.weight": "model-00002-of-00005.safetensors",
114
+ "transformer.h.24.self_attention.query_key_value.weight": "model-00002-of-00005.safetensors",
115
+ "transformer.h.25.input_layernorm.bias": "model-00002-of-00005.safetensors",
116
+ "transformer.h.25.input_layernorm.weight": "model-00002-of-00005.safetensors",
117
+ "transformer.h.25.mlp.downscale.weight": "model-00002-of-00005.safetensors",
118
+ "transformer.h.25.mlp.upscale.weight": "model-00002-of-00005.safetensors",
119
+ "transformer.h.25.self_attention.dense.weight": "model-00002-of-00005.safetensors",
120
+ "transformer.h.25.self_attention.query_key_value.weight": "model-00002-of-00005.safetensors",
121
+ "transformer.h.26.input_layernorm.bias": "model-00003-of-00005.safetensors",
122
+ "transformer.h.26.input_layernorm.weight": "model-00003-of-00005.safetensors",
123
+ "transformer.h.26.mlp.downscale.weight": "model-00003-of-00005.safetensors",
124
+ "transformer.h.26.mlp.upscale.weight": "model-00002-of-00005.safetensors",
125
+ "transformer.h.26.self_attention.dense.weight": "model-00002-of-00005.safetensors",
126
+ "transformer.h.26.self_attention.query_key_value.weight": "model-00002-of-00005.safetensors",
127
+ "transformer.h.27.input_layernorm.bias": "model-00003-of-00005.safetensors",
128
+ "transformer.h.27.input_layernorm.weight": "model-00003-of-00005.safetensors",
129
+ "transformer.h.27.mlp.downscale.weight": "model-00003-of-00005.safetensors",
130
+ "transformer.h.27.mlp.upscale.weight": "model-00003-of-00005.safetensors",
131
+ "transformer.h.27.self_attention.dense.weight": "model-00003-of-00005.safetensors",
132
+ "transformer.h.27.self_attention.query_key_value.weight": "model-00003-of-00005.safetensors",
133
+ "transformer.h.28.input_layernorm.bias": "model-00003-of-00005.safetensors",
134
+ "transformer.h.28.input_layernorm.weight": "model-00003-of-00005.safetensors",
135
+ "transformer.h.28.mlp.downscale.weight": "model-00003-of-00005.safetensors",
136
+ "transformer.h.28.mlp.upscale.weight": "model-00003-of-00005.safetensors",
137
+ "transformer.h.28.self_attention.dense.weight": "model-00003-of-00005.safetensors",
138
+ "transformer.h.28.self_attention.query_key_value.weight": "model-00003-of-00005.safetensors",
139
+ "transformer.h.29.input_layernorm.bias": "model-00003-of-00005.safetensors",
140
+ "transformer.h.29.input_layernorm.weight": "model-00003-of-00005.safetensors",
141
+ "transformer.h.29.mlp.downscale.weight": "model-00003-of-00005.safetensors",
142
+ "transformer.h.29.mlp.upscale.weight": "model-00003-of-00005.safetensors",
143
+ "transformer.h.29.self_attention.dense.weight": "model-00003-of-00005.safetensors",
144
+ "transformer.h.29.self_attention.query_key_value.weight": "model-00003-of-00005.safetensors",
145
+ "transformer.h.3.input_layernorm.bias": "model-00001-of-00005.safetensors",
146
+ "transformer.h.3.input_layernorm.weight": "model-00001-of-00005.safetensors",
147
+ "transformer.h.3.mlp.downscale.weight": "model-00001-of-00005.safetensors",
148
+ "transformer.h.3.mlp.upscale.weight": "model-00001-of-00005.safetensors",
149
+ "transformer.h.3.self_attention.dense.weight": "model-00001-of-00005.safetensors",
150
+ "transformer.h.3.self_attention.query_key_value.weight": "model-00001-of-00005.safetensors",
151
+ "transformer.h.30.input_layernorm.bias": "model-00003-of-00005.safetensors",
152
+ "transformer.h.30.input_layernorm.weight": "model-00003-of-00005.safetensors",
153
+ "transformer.h.30.mlp.downscale.weight": "model-00003-of-00005.safetensors",
154
+ "transformer.h.30.mlp.upscale.weight": "model-00003-of-00005.safetensors",
155
+ "transformer.h.30.self_attention.dense.weight": "model-00003-of-00005.safetensors",
156
+ "transformer.h.30.self_attention.query_key_value.weight": "model-00003-of-00005.safetensors",
157
+ "transformer.h.31.input_layernorm.bias": "model-00003-of-00005.safetensors",
158
+ "transformer.h.31.input_layernorm.weight": "model-00003-of-00005.safetensors",
159
+ "transformer.h.31.mlp.downscale.weight": "model-00003-of-00005.safetensors",
160
+ "transformer.h.31.mlp.upscale.weight": "model-00003-of-00005.safetensors",
161
+ "transformer.h.31.self_attention.dense.weight": "model-00003-of-00005.safetensors",
162
+ "transformer.h.31.self_attention.query_key_value.weight": "model-00003-of-00005.safetensors",
163
+ "transformer.h.32.input_layernorm.bias": "model-00003-of-00005.safetensors",
164
+ "transformer.h.32.input_layernorm.weight": "model-00003-of-00005.safetensors",
165
+ "transformer.h.32.mlp.downscale.weight": "model-00003-of-00005.safetensors",
166
+ "transformer.h.32.mlp.upscale.weight": "model-00003-of-00005.safetensors",
167
+ "transformer.h.32.self_attention.dense.weight": "model-00003-of-00005.safetensors",
168
+ "transformer.h.32.self_attention.query_key_value.weight": "model-00003-of-00005.safetensors",
169
+ "transformer.h.33.input_layernorm.bias": "model-00003-of-00005.safetensors",
170
+ "transformer.h.33.input_layernorm.weight": "model-00003-of-00005.safetensors",
171
+ "transformer.h.33.mlp.downscale.weight": "model-00003-of-00005.safetensors",
172
+ "transformer.h.33.mlp.upscale.weight": "model-00003-of-00005.safetensors",
173
+ "transformer.h.33.self_attention.dense.weight": "model-00003-of-00005.safetensors",
174
+ "transformer.h.33.self_attention.query_key_value.weight": "model-00003-of-00005.safetensors",
175
+ "transformer.h.34.input_layernorm.bias": "model-00003-of-00005.safetensors",
176
+ "transformer.h.34.input_layernorm.weight": "model-00003-of-00005.safetensors",
177
+ "transformer.h.34.mlp.downscale.weight": "model-00003-of-00005.safetensors",
178
+ "transformer.h.34.mlp.upscale.weight": "model-00003-of-00005.safetensors",
179
+ "transformer.h.34.self_attention.dense.weight": "model-00003-of-00005.safetensors",
180
+ "transformer.h.34.self_attention.query_key_value.weight": "model-00003-of-00005.safetensors",
181
+ "transformer.h.35.input_layernorm.bias": "model-00003-of-00005.safetensors",
182
+ "transformer.h.35.input_layernorm.weight": "model-00003-of-00005.safetensors",
183
+ "transformer.h.35.mlp.downscale.weight": "model-00003-of-00005.safetensors",
184
+ "transformer.h.35.mlp.upscale.weight": "model-00003-of-00005.safetensors",
185
+ "transformer.h.35.self_attention.dense.weight": "model-00003-of-00005.safetensors",
186
+ "transformer.h.35.self_attention.query_key_value.weight": "model-00003-of-00005.safetensors",
187
+ "transformer.h.36.input_layernorm.bias": "model-00003-of-00005.safetensors",
188
+ "transformer.h.36.input_layernorm.weight": "model-00003-of-00005.safetensors",
189
+ "transformer.h.36.mlp.downscale.weight": "model-00003-of-00005.safetensors",
190
+ "transformer.h.36.mlp.upscale.weight": "model-00003-of-00005.safetensors",
191
+ "transformer.h.36.self_attention.dense.weight": "model-00003-of-00005.safetensors",
192
+ "transformer.h.36.self_attention.query_key_value.weight": "model-00003-of-00005.safetensors",
193
+ "transformer.h.37.input_layernorm.bias": "model-00003-of-00005.safetensors",
194
+ "transformer.h.37.input_layernorm.weight": "model-00003-of-00005.safetensors",
195
+ "transformer.h.37.mlp.downscale.weight": "model-00003-of-00005.safetensors",
196
+ "transformer.h.37.mlp.upscale.weight": "model-00003-of-00005.safetensors",
197
+ "transformer.h.37.self_attention.dense.weight": "model-00003-of-00005.safetensors",
198
+ "transformer.h.37.self_attention.query_key_value.weight": "model-00003-of-00005.safetensors",
199
+ "transformer.h.38.input_layernorm.bias": "model-00003-of-00005.safetensors",
200
+ "transformer.h.38.input_layernorm.weight": "model-00003-of-00005.safetensors",
201
+ "transformer.h.38.mlp.downscale.weight": "model-00003-of-00005.safetensors",
202
+ "transformer.h.38.mlp.upscale.weight": "model-00003-of-00005.safetensors",
203
+ "transformer.h.38.self_attention.dense.weight": "model-00003-of-00005.safetensors",
204
+ "transformer.h.38.self_attention.query_key_value.weight": "model-00003-of-00005.safetensors",
205
+ "transformer.h.39.input_layernorm.bias": "model-00003-of-00005.safetensors",
206
+ "transformer.h.39.input_layernorm.weight": "model-00003-of-00005.safetensors",
207
+ "transformer.h.39.mlp.downscale.weight": "model-00003-of-00005.safetensors",
208
+ "transformer.h.39.mlp.upscale.weight": "model-00003-of-00005.safetensors",
209
+ "transformer.h.39.self_attention.dense.weight": "model-00003-of-00005.safetensors",
210
+ "transformer.h.39.self_attention.query_key_value.weight": "model-00003-of-00005.safetensors",
211
+ "transformer.h.4.input_layernorm.bias": "model-00001-of-00005.safetensors",
212
+ "transformer.h.4.input_layernorm.weight": "model-00001-of-00005.safetensors",
213
+ "transformer.h.4.mlp.downscale.weight": "model-00001-of-00005.safetensors",
214
+ "transformer.h.4.mlp.upscale.weight": "model-00001-of-00005.safetensors",
215
+ "transformer.h.4.self_attention.dense.weight": "model-00001-of-00005.safetensors",
216
+ "transformer.h.4.self_attention.query_key_value.weight": "model-00001-of-00005.safetensors",
217
+ "transformer.h.40.input_layernorm.bias": "model-00004-of-00005.safetensors",
218
+ "transformer.h.40.input_layernorm.weight": "model-00004-of-00005.safetensors",
219
+ "transformer.h.40.mlp.downscale.weight": "model-00004-of-00005.safetensors",
220
+ "transformer.h.40.mlp.upscale.weight": "model-00003-of-00005.safetensors",
221
+ "transformer.h.40.self_attention.dense.weight": "model-00003-of-00005.safetensors",
222
+ "transformer.h.40.self_attention.query_key_value.weight": "model-00003-of-00005.safetensors",
223
+ "transformer.h.41.input_layernorm.bias": "model-00004-of-00005.safetensors",
224
+ "transformer.h.41.input_layernorm.weight": "model-00004-of-00005.safetensors",
225
+ "transformer.h.41.mlp.downscale.weight": "model-00004-of-00005.safetensors",
226
+ "transformer.h.41.mlp.upscale.weight": "model-00004-of-00005.safetensors",
227
+ "transformer.h.41.self_attention.dense.weight": "model-00004-of-00005.safetensors",
228
+ "transformer.h.41.self_attention.query_key_value.weight": "model-00004-of-00005.safetensors",
229
+ "transformer.h.42.input_layernorm.bias": "model-00004-of-00005.safetensors",
230
+ "transformer.h.42.input_layernorm.weight": "model-00004-of-00005.safetensors",
231
+ "transformer.h.42.mlp.downscale.weight": "model-00004-of-00005.safetensors",
232
+ "transformer.h.42.mlp.upscale.weight": "model-00004-of-00005.safetensors",
233
+ "transformer.h.42.self_attention.dense.weight": "model-00004-of-00005.safetensors",
234
+ "transformer.h.42.self_attention.query_key_value.weight": "model-00004-of-00005.safetensors",
235
+ "transformer.h.43.input_layernorm.bias": "model-00004-of-00005.safetensors",
236
+ "transformer.h.43.input_layernorm.weight": "model-00004-of-00005.safetensors",
237
+ "transformer.h.43.mlp.downscale.weight": "model-00004-of-00005.safetensors",
238
+ "transformer.h.43.mlp.upscale.weight": "model-00004-of-00005.safetensors",
239
+ "transformer.h.43.self_attention.dense.weight": "model-00004-of-00005.safetensors",
240
+ "transformer.h.43.self_attention.query_key_value.weight": "model-00004-of-00005.safetensors",
241
+ "transformer.h.44.input_layernorm.bias": "model-00004-of-00005.safetensors",
242
+ "transformer.h.44.input_layernorm.weight": "model-00004-of-00005.safetensors",
243
+ "transformer.h.44.mlp.downscale.weight": "model-00004-of-00005.safetensors",
244
+ "transformer.h.44.mlp.upscale.weight": "model-00004-of-00005.safetensors",
245
+ "transformer.h.44.self_attention.dense.weight": "model-00004-of-00005.safetensors",
246
+ "transformer.h.44.self_attention.query_key_value.weight": "model-00004-of-00005.safetensors",
247
+ "transformer.h.45.input_layernorm.bias": "model-00004-of-00005.safetensors",
248
+ "transformer.h.45.input_layernorm.weight": "model-00004-of-00005.safetensors",
249
+ "transformer.h.45.mlp.downscale.weight": "model-00004-of-00005.safetensors",
250
+ "transformer.h.45.mlp.upscale.weight": "model-00004-of-00005.safetensors",
251
+ "transformer.h.45.self_attention.dense.weight": "model-00004-of-00005.safetensors",
252
+ "transformer.h.45.self_attention.query_key_value.weight": "model-00004-of-00005.safetensors",
253
+ "transformer.h.46.input_layernorm.bias": "model-00004-of-00005.safetensors",
254
+ "transformer.h.46.input_layernorm.weight": "model-00004-of-00005.safetensors",
255
+ "transformer.h.46.mlp.downscale.weight": "model-00004-of-00005.safetensors",
256
+ "transformer.h.46.mlp.upscale.weight": "model-00004-of-00005.safetensors",
257
+ "transformer.h.46.self_attention.dense.weight": "model-00004-of-00005.safetensors",
258
+ "transformer.h.46.self_attention.query_key_value.weight": "model-00004-of-00005.safetensors",
259
+ "transformer.h.47.input_layernorm.bias": "model-00004-of-00005.safetensors",
260
+ "transformer.h.47.input_layernorm.weight": "model-00004-of-00005.safetensors",
261
+ "transformer.h.47.mlp.downscale.weight": "model-00004-of-00005.safetensors",
262
+ "transformer.h.47.mlp.upscale.weight": "model-00004-of-00005.safetensors",
263
+ "transformer.h.47.self_attention.dense.weight": "model-00004-of-00005.safetensors",
264
+ "transformer.h.47.self_attention.query_key_value.weight": "model-00004-of-00005.safetensors",
265
+ "transformer.h.48.input_layernorm.bias": "model-00004-of-00005.safetensors",
266
+ "transformer.h.48.input_layernorm.weight": "model-00004-of-00005.safetensors",
267
+ "transformer.h.48.mlp.downscale.weight": "model-00004-of-00005.safetensors",
268
+ "transformer.h.48.mlp.upscale.weight": "model-00004-of-00005.safetensors",
269
+ "transformer.h.48.self_attention.dense.weight": "model-00004-of-00005.safetensors",
270
+ "transformer.h.48.self_attention.query_key_value.weight": "model-00004-of-00005.safetensors",
271
+ "transformer.h.49.input_layernorm.bias": "model-00004-of-00005.safetensors",
272
+ "transformer.h.49.input_layernorm.weight": "model-00004-of-00005.safetensors",
273
+ "transformer.h.49.mlp.downscale.weight": "model-00004-of-00005.safetensors",
274
+ "transformer.h.49.mlp.upscale.weight": "model-00004-of-00005.safetensors",
275
+ "transformer.h.49.self_attention.dense.weight": "model-00004-of-00005.safetensors",
276
+ "transformer.h.49.self_attention.query_key_value.weight": "model-00004-of-00005.safetensors",
277
+ "transformer.h.5.input_layernorm.bias": "model-00001-of-00005.safetensors",
278
+ "transformer.h.5.input_layernorm.weight": "model-00001-of-00005.safetensors",
279
+ "transformer.h.5.mlp.downscale.weight": "model-00001-of-00005.safetensors",
280
+ "transformer.h.5.mlp.upscale.weight": "model-00001-of-00005.safetensors",
281
+ "transformer.h.5.self_attention.dense.weight": "model-00001-of-00005.safetensors",
282
+ "transformer.h.5.self_attention.query_key_value.weight": "model-00001-of-00005.safetensors",
283
+ "transformer.h.50.input_layernorm.bias": "model-00004-of-00005.safetensors",
284
+ "transformer.h.50.input_layernorm.weight": "model-00004-of-00005.safetensors",
285
+ "transformer.h.50.mlp.downscale.weight": "model-00004-of-00005.safetensors",
286
+ "transformer.h.50.mlp.upscale.weight": "model-00004-of-00005.safetensors",
287
+ "transformer.h.50.self_attention.dense.weight": "model-00004-of-00005.safetensors",
288
+ "transformer.h.50.self_attention.query_key_value.weight": "model-00004-of-00005.safetensors",
289
+ "transformer.h.51.input_layernorm.bias": "model-00004-of-00005.safetensors",
290
+ "transformer.h.51.input_layernorm.weight": "model-00004-of-00005.safetensors",
291
+ "transformer.h.51.mlp.downscale.weight": "model-00004-of-00005.safetensors",
292
+ "transformer.h.51.mlp.upscale.weight": "model-00004-of-00005.safetensors",
293
+ "transformer.h.51.self_attention.dense.weight": "model-00004-of-00005.safetensors",
294
+ "transformer.h.51.self_attention.query_key_value.weight": "model-00004-of-00005.safetensors",
295
+ "transformer.h.52.input_layernorm.bias": "model-00004-of-00005.safetensors",
296
+ "transformer.h.52.input_layernorm.weight": "model-00004-of-00005.safetensors",
297
+ "transformer.h.52.mlp.downscale.weight": "model-00004-of-00005.safetensors",
298
+ "transformer.h.52.mlp.upscale.weight": "model-00004-of-00005.safetensors",
299
+ "transformer.h.52.self_attention.dense.weight": "model-00004-of-00005.safetensors",
300
+ "transformer.h.52.self_attention.query_key_value.weight": "model-00004-of-00005.safetensors",
301
+ "transformer.h.53.input_layernorm.bias": "model-00004-of-00005.safetensors",
302
+ "transformer.h.53.input_layernorm.weight": "model-00004-of-00005.safetensors",
303
+ "transformer.h.53.mlp.downscale.weight": "model-00004-of-00005.safetensors",
304
+ "transformer.h.53.mlp.upscale.weight": "model-00004-of-00005.safetensors",
305
+ "transformer.h.53.self_attention.dense.weight": "model-00004-of-00005.safetensors",
306
+ "transformer.h.53.self_attention.query_key_value.weight": "model-00004-of-00005.safetensors",
307
+ "transformer.h.54.input_layernorm.bias": "model-00005-of-00005.safetensors",
308
+ "transformer.h.54.input_layernorm.weight": "model-00005-of-00005.safetensors",
309
+ "transformer.h.54.mlp.downscale.weight": "model-00005-of-00005.safetensors",
310
+ "transformer.h.54.mlp.upscale.weight": "model-00004-of-00005.safetensors",
311
+ "transformer.h.54.self_attention.dense.weight": "model-00004-of-00005.safetensors",
312
+ "transformer.h.54.self_attention.query_key_value.weight": "model-00004-of-00005.safetensors",
313
+ "transformer.h.55.input_layernorm.bias": "model-00005-of-00005.safetensors",
314
+ "transformer.h.55.input_layernorm.weight": "model-00005-of-00005.safetensors",
315
+ "transformer.h.55.mlp.downscale.weight": "model-00005-of-00005.safetensors",
316
+ "transformer.h.55.mlp.upscale.weight": "model-00005-of-00005.safetensors",
317
+ "transformer.h.55.self_attention.dense.weight": "model-00005-of-00005.safetensors",
318
+ "transformer.h.55.self_attention.query_key_value.weight": "model-00005-of-00005.safetensors",
319
+ "transformer.h.56.input_layernorm.bias": "model-00005-of-00005.safetensors",
320
+ "transformer.h.56.input_layernorm.weight": "model-00005-of-00005.safetensors",
321
+ "transformer.h.56.mlp.downscale.weight": "model-00005-of-00005.safetensors",
322
+ "transformer.h.56.mlp.upscale.weight": "model-00005-of-00005.safetensors",
323
+ "transformer.h.56.self_attention.dense.weight": "model-00005-of-00005.safetensors",
324
+ "transformer.h.56.self_attention.query_key_value.weight": "model-00005-of-00005.safetensors",
325
+ "transformer.h.57.input_layernorm.bias": "model-00005-of-00005.safetensors",
326
+ "transformer.h.57.input_layernorm.weight": "model-00005-of-00005.safetensors",
327
+ "transformer.h.57.mlp.downscale.weight": "model-00005-of-00005.safetensors",
328
+ "transformer.h.57.mlp.upscale.weight": "model-00005-of-00005.safetensors",
329
+ "transformer.h.57.self_attention.dense.weight": "model-00005-of-00005.safetensors",
330
+ "transformer.h.57.self_attention.query_key_value.weight": "model-00005-of-00005.safetensors",
331
+ "transformer.h.58.input_layernorm.bias": "model-00005-of-00005.safetensors",
332
+ "transformer.h.58.input_layernorm.weight": "model-00005-of-00005.safetensors",
333
+ "transformer.h.58.mlp.downscale.weight": "model-00005-of-00005.safetensors",
334
+ "transformer.h.58.mlp.upscale.weight": "model-00005-of-00005.safetensors",
335
+ "transformer.h.58.self_attention.dense.weight": "model-00005-of-00005.safetensors",
336
+ "transformer.h.58.self_attention.query_key_value.weight": "model-00005-of-00005.safetensors",
337
+ "transformer.h.59.input_layernorm.bias": "model-00005-of-00005.safetensors",
338
+ "transformer.h.59.input_layernorm.weight": "model-00005-of-00005.safetensors",
339
+ "transformer.h.59.mlp.downscale.weight": "model-00005-of-00005.safetensors",
340
+ "transformer.h.59.mlp.upscale.weight": "model-00005-of-00005.safetensors",
341
+ "transformer.h.59.self_attention.dense.weight": "model-00005-of-00005.safetensors",
342
+ "transformer.h.59.self_attention.query_key_value.weight": "model-00005-of-00005.safetensors",
343
+ "transformer.h.6.input_layernorm.bias": "model-00001-of-00005.safetensors",
344
+ "transformer.h.6.input_layernorm.weight": "model-00001-of-00005.safetensors",
345
+ "transformer.h.6.mlp.downscale.weight": "model-00001-of-00005.safetensors",
346
+ "transformer.h.6.mlp.upscale.weight": "model-00001-of-00005.safetensors",
347
+ "transformer.h.6.self_attention.dense.weight": "model-00001-of-00005.safetensors",
348
+ "transformer.h.6.self_attention.query_key_value.weight": "model-00001-of-00005.safetensors",
349
+ "transformer.h.7.input_layernorm.bias": "model-00001-of-00005.safetensors",
350
+ "transformer.h.7.input_layernorm.weight": "model-00001-of-00005.safetensors",
351
+ "transformer.h.7.mlp.downscale.weight": "model-00001-of-00005.safetensors",
352
+ "transformer.h.7.mlp.upscale.weight": "model-00001-of-00005.safetensors",
353
+ "transformer.h.7.self_attention.dense.weight": "model-00001-of-00005.safetensors",
354
+ "transformer.h.7.self_attention.query_key_value.weight": "model-00001-of-00005.safetensors",
355
+ "transformer.h.8.input_layernorm.bias": "model-00001-of-00005.safetensors",
356
+ "transformer.h.8.input_layernorm.weight": "model-00001-of-00005.safetensors",
357
+ "transformer.h.8.mlp.downscale.weight": "model-00001-of-00005.safetensors",
358
+ "transformer.h.8.mlp.upscale.weight": "model-00001-of-00005.safetensors",
359
+ "transformer.h.8.self_attention.dense.weight": "model-00001-of-00005.safetensors",
360
+ "transformer.h.8.self_attention.query_key_value.weight": "model-00001-of-00005.safetensors",
361
+ "transformer.h.9.input_layernorm.bias": "model-00001-of-00005.safetensors",
362
+ "transformer.h.9.input_layernorm.weight": "model-00001-of-00005.safetensors",
363
+ "transformer.h.9.mlp.downscale.weight": "model-00001-of-00005.safetensors",
364
+ "transformer.h.9.mlp.upscale.weight": "model-00001-of-00005.safetensors",
365
+ "transformer.h.9.self_attention.dense.weight": "model-00001-of-00005.safetensors",
366
+ "transformer.h.9.self_attention.query_key_value.weight": "model-00001-of-00005.safetensors",
367
+ "transformer.ln_f.bias": "model-00005-of-00005.safetensors",
368
+ "transformer.ln_f.weight": "model-00005-of-00005.safetensors",
369
+ "transformer.word_embeddings.weight": "model-00001-of-00005.safetensors"
370
+ }
371
+ }
modeling_falcon.py ADDED
@@ -0,0 +1,1670 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 the Falcon authors and HuggingFace Inc. team. 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
+ """PyTorch Falcon model."""
16
+
17
+ import math
18
+ import warnings
19
+ from typing import TYPE_CHECKING, Optional, Tuple, Union
20
+
21
+ import torch
22
+ import torch.utils.checkpoint
23
+ from torch import nn
24
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, LayerNorm, MSELoss
25
+ from torch.nn import functional as F
26
+
27
+ from transformers.modeling_attn_mask_utils import (
28
+ AttentionMaskConverter,
29
+ _prepare_4d_causal_attention_mask,
30
+ _prepare_4d_causal_attention_mask_for_sdpa,
31
+ )
32
+ from transformers.modeling_outputs import (
33
+ BaseModelOutputWithPastAndCrossAttentions,
34
+ CausalLMOutputWithCrossAttentions,
35
+ QuestionAnsweringModelOutput,
36
+ SequenceClassifierOutputWithPast,
37
+ TokenClassifierOutput,
38
+ )
39
+ from transformers.modeling_utils import PreTrainedModel
40
+ from transformers.pytorch_utils import is_torch_greater_or_equal_than_2_0
41
+ from transformers.utils import (
42
+ add_code_sample_docstrings,
43
+ add_start_docstrings,
44
+ add_start_docstrings_to_model_forward,
45
+ is_flash_attn_2_available,
46
+ is_flash_attn_greater_or_equal_2_10,
47
+ logging,
48
+ )
49
+ from .configuration_falcon import FalconConfig
50
+
51
+
52
+ if TYPE_CHECKING:
53
+ from transformers.configuration_utils import PretrainedConfig
54
+
55
+ if is_flash_attn_2_available():
56
+ from flash_attn import flash_attn_func, flash_attn_varlen_func
57
+ from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
58
+
59
+ logger = logging.get_logger(__name__)
60
+
61
+ FALCON_PRETRAINED_MODEL_ARCHIVE_LIST = [
62
+ "tiiuae/falcon-40b",
63
+ "tiiuae/falcon-40b-instruct",
64
+ "tiiuae/falcon-7b",
65
+ "tiiuae/falcon-7b-instruct",
66
+ "tiiuae/falcon-rw-7b",
67
+ "tiiuae/falcon-rw-1b",
68
+ ]
69
+ _CHECKPOINT_FOR_DOC = "Rocketknight1/falcon-rw-1b"
70
+ _CONFIG_FOR_DOC = "FalconConfig"
71
+
72
+
73
+ # NOTE(Hesslow): Unfortunately we did not fuse matmul and bias during training, this means that there's one additional quantization to bfloat16 between the operations.
74
+ # In order not to degrade the quality of our HF-port, we keep these characteristics in the final model.
75
+ class FalconLinear(nn.Linear):
76
+ def forward(self, input: torch.Tensor) -> torch.Tensor:
77
+ hidden_states = input @ self.weight.T
78
+ if self.bias is None:
79
+ return hidden_states
80
+ return hidden_states + self.bias
81
+
82
+
83
+ # Copied from transformers.models.llama.modeling_llama.rotate_half
84
+ def rotate_half(x):
85
+ """Rotates half the hidden dims of the input."""
86
+ x1 = x[..., : x.shape[-1] // 2]
87
+ x2 = x[..., x.shape[-1] // 2 :]
88
+ return torch.cat((-x2, x1), dim=-1)
89
+
90
+
91
+ # Copied from transformers.models.mistral.modeling_mistral.apply_rotary_pos_emb
92
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1):
93
+ """Applies Rotary Position Embedding to the query and key tensors.
94
+
95
+ Args:
96
+ q (`torch.Tensor`): The query tensor.
97
+ k (`torch.Tensor`): The key tensor.
98
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
99
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
100
+ position_ids (`torch.Tensor`):
101
+ The position indices of the tokens corresponding to the query and key tensors. For example, this can be
102
+ used to pass offsetted position ids when working with a KV-cache.
103
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
104
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
105
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
106
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
107
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
108
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
109
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
110
+ Returns:
111
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
112
+ """
113
+ cos = cos[position_ids].unsqueeze(unsqueeze_dim)
114
+ sin = sin[position_ids].unsqueeze(unsqueeze_dim)
115
+ q_embed = (q * cos) + (rotate_half(q) * sin)
116
+ k_embed = (k * cos) + (rotate_half(k) * sin)
117
+ return q_embed, k_embed
118
+
119
+
120
+ @torch.jit.script
121
+ def get_max_seqlen_in_batch(attention_mask: torch.Tensor) -> torch.Tensor:
122
+ max_num = int(torch.max(attention_mask).item())
123
+ batch_size, _ = attention_mask.shape
124
+ counts = torch.zeros((batch_size, max_num), dtype=torch.int32)
125
+
126
+ for i in range(1, max_num + 1):
127
+ mask = attention_mask == i
128
+ counts[:, i - 1] = torch.sum(mask, dim=-1).to(dtype=torch.int32)
129
+
130
+ result = counts.flatten()
131
+ nonzero_indices = torch.nonzero(result).squeeze(-1)
132
+ return result[nonzero_indices]
133
+
134
+
135
+ @torch.jit.script
136
+ def _get_unpad_data(attention_mask: torch.Tensor):
137
+ device = attention_mask.device
138
+ seqlens_in_batch = get_max_seqlen_in_batch(attention_mask)
139
+ indices = torch.nonzero(attention_mask.flatten()).flatten()
140
+ max_seqlen_in_batch = seqlens_in_batch.max().item()
141
+ cu_seqlens = (
142
+ F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.int32), (1, 0))
143
+ .to(device=device)
144
+ .detach()
145
+ )
146
+ return (
147
+ indices,
148
+ cu_seqlens,
149
+ max_seqlen_in_batch,
150
+ )
151
+
152
+ # Copied from transformers.models.mistral.modeling_mistral.MistralRotaryEmbedding with Mistral->Falcon
153
+ class FalconRotaryEmbedding(nn.Module):
154
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
155
+ super().__init__()
156
+
157
+ self.dim = dim
158
+ self.max_position_embeddings = max_position_embeddings
159
+ self.base = base
160
+ inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2, dtype=torch.int64).float().to(device) / self.dim))
161
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
162
+
163
+ # Build here to make `torch.jit.trace` work.
164
+ self._set_cos_sin_cache(
165
+ seq_len=max_position_embeddings, device=self.inv_freq.device, dtype=torch.get_default_dtype()
166
+ )
167
+
168
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
169
+ self.max_seq_len_cached = seq_len
170
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=torch.int64).type_as(self.inv_freq)
171
+
172
+ freqs = torch.outer(t, self.inv_freq)
173
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
174
+ emb = torch.cat((freqs, freqs), dim=-1)
175
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
176
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
177
+
178
+ def forward(self, x, seq_len=None):
179
+ # x: [bs, num_attention_heads, seq_len, head_size]
180
+ if seq_len > self.max_seq_len_cached:
181
+ self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)
182
+
183
+ return (
184
+ self.cos_cached[:seq_len].to(dtype=x.dtype),
185
+ self.sin_cached[:seq_len].to(dtype=x.dtype),
186
+ )
187
+
188
+
189
+ # copied from transformers.models.llama.modeling_llama.LlamaLinearScalingRotaryEmbedding with Llama->Falcon
190
+ # TODO @joao no longer copied from LLama after static cache, fix me (copied -> Copied)
191
+ class FalconLinearScalingRotaryEmbedding(FalconRotaryEmbedding):
192
+ """FalconRotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendev"""
193
+
194
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):
195
+ self.scaling_factor = scaling_factor
196
+ super().__init__(dim, max_position_embeddings, base, device)
197
+
198
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
199
+ self.max_seq_len_cached = seq_len
200
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=torch.int64).type_as(self.inv_freq)
201
+ t = t / self.scaling_factor
202
+
203
+ freqs = torch.outer(t, self.inv_freq)
204
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
205
+ emb = torch.cat((freqs, freqs), dim=-1)
206
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
207
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
208
+
209
+
210
+ # copied from transformers.models.llama.modeling_llama.LlamaDynamicNTKScalingRotaryEmbedding with Llama->Falcon
211
+ # TODO @joao no longer copied from LLama after static cache, fix me (copied -> Copied)
212
+ class FalconDynamicNTKScalingRotaryEmbedding(FalconRotaryEmbedding):
213
+ """FalconRotaryEmbedding extended with Dynamic NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozilla"""
214
+
215
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):
216
+ self.scaling_factor = scaling_factor
217
+ super().__init__(dim, max_position_embeddings, base, device)
218
+
219
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
220
+ self.max_seq_len_cached = seq_len
221
+
222
+ if seq_len > self.max_position_embeddings:
223
+ base = self.base * (
224
+ (self.scaling_factor * seq_len / self.max_position_embeddings) - (self.scaling_factor - 1)
225
+ ) ** (self.dim / (self.dim - 2))
226
+ inv_freq = 1.0 / (base ** (torch.arange(0, self.dim, 2, dtype=torch.int64).float().to(device) / self.dim))
227
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
228
+
229
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=torch.int64).type_as(self.inv_freq)
230
+
231
+ freqs = torch.outer(t, self.inv_freq)
232
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
233
+ emb = torch.cat((freqs, freqs), dim=-1)
234
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
235
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
236
+
237
+
238
+ def build_alibi_tensor(attention_mask: torch.Tensor, num_heads: int, dtype: torch.dtype) -> torch.Tensor:
239
+ batch_size, seq_length = attention_mask.shape
240
+ closest_power_of_2 = 2 ** math.floor(math.log2(num_heads))
241
+ base = torch.tensor(
242
+ 2 ** (-(2 ** -(math.log2(closest_power_of_2) - 3))), device=attention_mask.device, dtype=torch.float32
243
+ )
244
+ powers = torch.arange(1, 1 + closest_power_of_2, device=attention_mask.device, dtype=torch.int32)
245
+ slopes = torch.pow(base, powers)
246
+
247
+ if closest_power_of_2 != num_heads:
248
+ extra_base = torch.tensor(
249
+ 2 ** (-(2 ** -(math.log2(2 * closest_power_of_2) - 3))), device=attention_mask.device, dtype=torch.float32
250
+ )
251
+ num_remaining_heads = min(closest_power_of_2, num_heads - closest_power_of_2)
252
+ extra_powers = torch.arange(1, 1 + 2 * num_remaining_heads, 2, device=attention_mask.device, dtype=torch.int32)
253
+ slopes = torch.cat([slopes, torch.pow(extra_base, extra_powers)], dim=0)
254
+
255
+ # Note: alibi will added to the attention bias that will be applied to the query, key product of attention
256
+ # => therefore alibi will have to be of shape (batch_size, num_heads, query_length, key_length)
257
+ # => here we set (batch_size=1, num_heads=num_heads, query_length=1, key_length=max_length)
258
+ # => the query_length dimension will then be broadcasted correctly
259
+ # This is more or less identical to T5's relative position bias:
260
+ # https://github.com/huggingface/transformers/blob/f681437203baa7671de3174b0fa583c349d9d5e1/src/transformers/models/t5/modeling_t5.py#L527
261
+ arange_tensor = ((attention_mask.cumsum(dim=-1) - 1) * attention_mask)[:, None, :]
262
+ alibi = slopes[..., None].bfloat16() * arange_tensor
263
+ return alibi.reshape(batch_size * num_heads, 1, seq_length).to(dtype)
264
+
265
+
266
+ # Copied from transformers.models.bloom.modeling_bloom.dropout_add
267
+ def dropout_add(x: torch.Tensor, residual: torch.Tensor, prob: float, training: bool) -> torch.Tensor:
268
+ """
269
+ Dropout add function
270
+
271
+ Args:
272
+ x (`torch.tensor`, *required*):
273
+ input tensor
274
+ residual (`torch.tensor`, *required*):
275
+ residual tensor
276
+ prob (`float`, *required*):
277
+ dropout probability
278
+ training (`bool`, *required*):
279
+ training mode
280
+ """
281
+ out = F.dropout(x, p=prob, training=training)
282
+ out = residual + out
283
+ return out
284
+
285
+
286
+ class FalconAttention(nn.Module):
287
+ def __init__(self, config: FalconConfig):
288
+ super().__init__()
289
+
290
+ self.config = config
291
+ self.hidden_size = config.hidden_size
292
+ self.num_heads = config.num_attention_heads
293
+ self.head_dim = self.hidden_size // self.num_heads
294
+ self.split_size = self.hidden_size
295
+ self.hidden_dropout = config.hidden_dropout
296
+ self.max_position_embeddings = config.max_position_embeddings
297
+ self.rope_theta = config.rope_theta
298
+ self.is_causal = True
299
+ self._use_sdpa = config._attn_implementation == "sdpa"
300
+
301
+ if self.head_dim * self.num_heads != self.hidden_size:
302
+ raise ValueError(
303
+ f"`hidden_size` must be divisible by num_heads (got `hidden_size`: {self.hidden_size} and `num_heads`:"
304
+ f" {self.num_heads})."
305
+ )
306
+
307
+ if config.rotary:
308
+ self._init_rope()
309
+
310
+ # Layer-wise attention scaling
311
+ self.inv_norm_factor = 1.0 / math.sqrt(self.head_dim)
312
+ self.beta = self.inv_norm_factor
313
+ if config.new_decoder_architecture:
314
+ qkv_out_dim = (config.num_kv_heads * 2 + config.num_attention_heads) * self.head_dim
315
+ elif config.multi_query:
316
+ qkv_out_dim = self.hidden_size + 2 * self.head_dim
317
+ else:
318
+ qkv_out_dim = 3 * self.hidden_size
319
+ self.query_key_value = FalconLinear(self.hidden_size, qkv_out_dim, bias=config.bias)
320
+ self.new_decoder_architecture = config.new_decoder_architecture
321
+ self.multi_query = config.multi_query
322
+ self.dense = FalconLinear(self.hidden_size, self.hidden_size, bias=config.bias)
323
+ self.attention_dropout = nn.Dropout(config.attention_dropout)
324
+ self.num_kv_heads = config.num_kv_heads if (self.new_decoder_architecture or not self.multi_query) else 1
325
+
326
+ # Copied from transformers.models.llama.modeling_llama.LlamaAttention._init_rope with Llama->Falcon
327
+ def _init_rope(self):
328
+ if self.config.rope_scaling is None:
329
+ self.rotary_emb = FalconRotaryEmbedding(
330
+ self.head_dim,
331
+ max_position_embeddings=self.max_position_embeddings,
332
+ base=self.rope_theta,
333
+ )
334
+ else:
335
+ scaling_type = self.config.rope_scaling["type"]
336
+ scaling_factor = self.config.rope_scaling["factor"]
337
+ if scaling_type == "linear":
338
+ self.rotary_emb = FalconLinearScalingRotaryEmbedding(
339
+ self.head_dim,
340
+ max_position_embeddings=self.max_position_embeddings,
341
+ scaling_factor=scaling_factor,
342
+ base=self.rope_theta,
343
+ )
344
+ elif scaling_type == "dynamic":
345
+ self.rotary_emb = FalconDynamicNTKScalingRotaryEmbedding(
346
+ self.head_dim,
347
+ max_position_embeddings=self.max_position_embeddings,
348
+ scaling_factor=scaling_factor,
349
+ base=self.rope_theta,
350
+ )
351
+ else:
352
+ raise ValueError(f"Unknown RoPE scaling type {scaling_type}")
353
+
354
+ def _split_heads(self, fused_qkv: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
355
+ """
356
+ Split the last dimension into (num_heads, head_dim), results share same memory storage as `fused_qkv`
357
+
358
+ Args:
359
+ fused_qkv (`torch.tensor`, *required*): [batch_size, seq_length, num_heads * 3 * head_dim]
360
+
361
+ Returns:
362
+ query: [batch_size, seq_length, num_heads, head_dim] key: [batch_size, seq_length, num_heads, head_dim]
363
+ value: [batch_size, seq_length, num_heads, head_dim]
364
+ """
365
+ if self.new_decoder_architecture:
366
+ batch, seq_len, _ = fused_qkv.shape
367
+ qkv = fused_qkv.view(batch, seq_len, -1, self.num_heads // self.num_kv_heads + 2, self.head_dim)
368
+ query = qkv[:, :, :, :-2]
369
+ key = qkv[:, :, :, [-2]]
370
+ value = qkv[:, :, :, [-1]]
371
+ key = torch.broadcast_to(key, query.shape)
372
+ value = torch.broadcast_to(value, query.shape)
373
+
374
+ query, key, value = [x.flatten(2, 3) for x in (query, key, value)]
375
+ return query, key, value
376
+ elif not self.multi_query:
377
+ batch_size, seq_length, three_times_hidden_size = fused_qkv.shape
378
+ fused_qkv = fused_qkv.view(batch_size, seq_length, self.num_heads, 3, self.head_dim)
379
+ return fused_qkv[..., 0, :], fused_qkv[..., 1, :], fused_qkv[..., 2, :]
380
+ else:
381
+ batch_size, seq_length, three_times_hidden_size = fused_qkv.shape
382
+ fused_qkv = fused_qkv.view(batch_size, seq_length, self.num_heads + 2, self.head_dim)
383
+ return fused_qkv[..., :-2, :], fused_qkv[..., [-2], :], fused_qkv[..., [-1], :]
384
+
385
+ # Copied from transformers.models.bloom.modeling_bloom.BloomAttention._merge_heads
386
+ def _merge_heads(self, x: torch.Tensor) -> torch.Tensor:
387
+ """
388
+ Merge heads together over the last dimension
389
+
390
+ Args:
391
+ x (`torch.tensor`, *required*): [batch_size * num_heads, seq_length, head_dim]
392
+
393
+ Returns:
394
+ torch.tensor: [batch_size, seq_length, num_heads * head_dim]
395
+ """
396
+ # What we want to achieve is:
397
+ # batch_size * num_heads, seq_length, head_dim -> batch_size, seq_length, num_heads * head_dim
398
+ batch_size_and_num_heads, seq_length, _ = x.shape
399
+ batch_size = batch_size_and_num_heads // self.num_heads
400
+
401
+ # First view to decompose the batch size
402
+ # batch_size * num_heads, seq_length, head_dim -> batch_size, num_heads, seq_length, head_dim
403
+ x = x.view(batch_size, self.num_heads, seq_length, self.head_dim)
404
+
405
+ # batch_size, num_heads, seq_length, head_dim -> batch_size, seq_length, num_heads, head_dim
406
+ x = x.permute(0, 2, 1, 3)
407
+
408
+ # batch_size, seq_length, num_heads, head_dim -> batch_size, seq_length, num_heads * head_dim
409
+ return x.reshape(batch_size, seq_length, self.num_heads * self.head_dim)
410
+
411
+ def forward(
412
+ self,
413
+ hidden_states: torch.Tensor,
414
+ alibi: Optional[torch.Tensor],
415
+ attention_mask: torch.Tensor,
416
+ position_ids: Optional[torch.LongTensor] = None,
417
+ layer_past: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
418
+ head_mask: Optional[torch.Tensor] = None,
419
+ use_cache: bool = False,
420
+ output_attentions: bool = False,
421
+ **kwargs,
422
+ ):
423
+ if "padding_mask" in kwargs:
424
+ warnings.warn(
425
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
426
+ )
427
+
428
+ fused_qkv = self.query_key_value(hidden_states) # [batch_size, seq_length, 3 x hidden_size]
429
+ num_kv_heads = self.num_heads if self.new_decoder_architecture else self.num_kv_heads
430
+ # 3 x [batch_size, seq_length, num_heads, head_dim]
431
+ (query_layer, key_layer, value_layer) = self._split_heads(fused_qkv)
432
+
433
+ batch_size, query_length, _, _ = query_layer.shape
434
+
435
+ query_layer = query_layer.transpose(1, 2).reshape(batch_size, self.num_heads, query_length, self.head_dim)
436
+ key_layer = key_layer.transpose(1, 2).reshape(batch_size, num_kv_heads, query_length, self.head_dim)
437
+ value_layer = value_layer.transpose(1, 2).reshape(batch_size, num_kv_heads, query_length, self.head_dim)
438
+
439
+ kv_seq_len = key_layer.shape[-2]
440
+ if layer_past is not None:
441
+ kv_seq_len += layer_past[0].shape[-2]
442
+ if alibi is None:
443
+ cos, sin = self.rotary_emb(value_layer, seq_len=kv_seq_len)
444
+ query_layer, key_layer = apply_rotary_pos_emb(query_layer, key_layer, cos, sin, position_ids)
445
+
446
+ if layer_past is not None:
447
+ past_key, past_value = layer_past
448
+ # concatenate along seq_length dimension:
449
+ # - key: [batch_size, self.num_heads, kv_length, head_dim]
450
+ # - value: [batch_size, self.num_heads, kv_length, head_dim]
451
+ key_layer = torch.cat((past_key, key_layer), dim=-2)
452
+ value_layer = torch.cat((past_value, value_layer), dim=-2)
453
+
454
+ kv_length = key_layer.shape[-2]
455
+ if use_cache:
456
+ present = (key_layer, value_layer)
457
+ else:
458
+ present = None
459
+
460
+ if self._use_sdpa and query_layer.device.type == "cuda" and attention_mask is not None:
461
+ # For torch<=2.1.2, SDPA with memory-efficient backend is bugged with non-contiguous inputs with custom attn_mask,
462
+ # Reference: https://github.com/pytorch/pytorch/issues/112577.
463
+ query_layer = query_layer.contiguous()
464
+ key_layer = key_layer.contiguous()
465
+ value_layer = value_layer.contiguous()
466
+
467
+ if alibi is None:
468
+ if self._use_sdpa and not output_attentions:
469
+ attn_output = F.scaled_dot_product_attention(
470
+ query_layer,
471
+ key_layer,
472
+ value_layer,
473
+ attention_mask,
474
+ 0.0,
475
+ # The query_length > 1 is necessary to match with AttentionMaskConverter.to_causal_4d that does not create a causal mask in case query_length == 1.
476
+ is_causal=self.is_causal and attention_mask is None and query_length > 1,
477
+ )
478
+
479
+ attention_scores = None
480
+ else:
481
+ attention_scores = query_layer @ key_layer.transpose(-1, -2)
482
+ attention_scores /= math.sqrt(self.head_dim)
483
+
484
+ attention_scores = F.softmax(attention_scores + attention_mask, dim=-1, dtype=hidden_states.dtype)
485
+ # It is unclear why neither dropout nor head_mask is applied here (while it is with alibi).
486
+ attn_output = attention_scores @ value_layer
487
+
488
+ attn_output = attn_output.view(batch_size, self.num_heads, query_length, self.head_dim)
489
+ attn_output = attn_output.permute(0, 2, 1, 3)
490
+ attn_output = attn_output.reshape(batch_size, query_length, self.num_heads * self.head_dim)
491
+
492
+ attn_output = self.dense(attn_output)
493
+
494
+ if output_attentions:
495
+ return attn_output, present, attention_scores
496
+ else:
497
+ return attn_output, present
498
+
499
+ else:
500
+ if self._use_sdpa and not output_attentions and head_mask is None:
501
+ attn_output = F.scaled_dot_product_attention(
502
+ query_layer,
503
+ key_layer,
504
+ value_layer,
505
+ attn_mask=attention_mask,
506
+ dropout_p=self.attention_dropout.p if self.training else 0.0,
507
+ is_causal=self.is_causal and attention_mask is None and query_length > 1,
508
+ )
509
+ attn_output = attn_output.transpose(1, 2)
510
+ attn_output = attn_output.reshape(batch_size, query_length, self.num_heads * self.head_dim)
511
+
512
+ attn_output = self.dense(attn_output)
513
+ else:
514
+ matmul_result = query_layer @ key_layer.transpose(-1, -2)
515
+
516
+ # change view to [batch_size, num_heads, q_length, kv_length]
517
+ attention_scores = matmul_result.view(batch_size, self.num_heads, query_length, kv_length)
518
+
519
+ # cast attention scores to fp32, compute scaled softmax and cast back to initial dtype - [batch_size, num_heads, q_length, kv_length]
520
+ input_dtype = attention_scores.dtype
521
+ # `float16` has a minimum value of -65504.0, whereas `bfloat16` and `float32` have a minimum value of `-3.4e+38`
522
+ if input_dtype == torch.float16 or input_dtype == torch.bfloat16:
523
+ attention_scores = attention_scores.to(torch.float32)
524
+
525
+ attention_logits = attention_scores + alibi.view(batch_size, self.num_heads, 1, -1)
526
+ attention_logits *= self.inv_norm_factor
527
+ attention_probs = F.softmax(attention_logits + attention_mask, dim=-1, dtype=hidden_states.dtype)
528
+ # [batch_size, num_heads, q_length, kv_length]
529
+ attention_probs = self.attention_dropout(attention_probs)
530
+
531
+ if head_mask is not None:
532
+ attention_probs = attention_probs * head_mask
533
+
534
+ # change view [batch_size, num_heads, q_length, kv_length]
535
+ attention_probs_reshaped = attention_probs.view(batch_size, self.num_heads, query_length, kv_length)
536
+
537
+ # matmul: [batch_size * num_heads, q_length, head_dim]
538
+ attn_output = (attention_probs_reshaped @ value_layer).flatten(0, 1)
539
+
540
+ # change view [batch_size, q_length, num_heads * head_dim]
541
+ attn_output = self._merge_heads(attn_output)
542
+
543
+ attn_output = self.dense(attn_output)
544
+
545
+ if output_attentions:
546
+ return attn_output, present, attention_probs
547
+ else:
548
+ return attn_output, present
549
+
550
+
551
+ class FalconFlashAttention2(FalconAttention):
552
+ """
553
+ Falcon flash attention module. This module inherits from `FalconAttention` as the weights of the module stays
554
+ untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
555
+ flash attention and deal with padding tokens in case the input contains any of them.
556
+ """
557
+
558
+ # Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2.__init__
559
+ def __init__(self, *args, **kwargs):
560
+ super().__init__(*args, **kwargs)
561
+
562
+ # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
563
+ # 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.
564
+ # 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).
565
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
566
+
567
+ def forward(
568
+ self,
569
+ hidden_states: torch.Tensor,
570
+ alibi: Optional[torch.Tensor],
571
+ attention_mask: torch.Tensor,
572
+ position_ids: Optional[torch.LongTensor] = None,
573
+ layer_past: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
574
+ head_mask: Optional[torch.Tensor] = None,
575
+ use_cache: bool = False,
576
+ output_attentions: bool = False,
577
+ **kwargs,
578
+ ):
579
+ if "padding_mask" in kwargs:
580
+ warnings.warn(
581
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
582
+ )
583
+
584
+ # overwrite attention_mask with padding_mask
585
+ attention_mask = kwargs.pop("padding_mask")
586
+
587
+ fused_qkv = self.query_key_value(hidden_states) # [batch_size, seq_length, 3 x hidden_size]
588
+ num_kv_heads = self.num_heads if self.new_decoder_architecture else self.num_kv_heads
589
+ # 3 x [batch_size, seq_length, num_heads, head_dim]
590
+ (query_layer, key_layer, value_layer) = self._split_heads(fused_qkv)
591
+
592
+ batch_size, query_length, _, _ = query_layer.shape
593
+
594
+ query_layer = query_layer.transpose(1, 2).reshape(batch_size, self.num_heads, query_length, self.head_dim)
595
+ key_layer = key_layer.transpose(1, 2).reshape(batch_size, num_kv_heads, query_length, self.head_dim)
596
+ value_layer = value_layer.transpose(1, 2).reshape(batch_size, num_kv_heads, query_length, self.head_dim)
597
+
598
+ kv_seq_len = key_layer.shape[-2]
599
+ if layer_past is not None:
600
+ kv_seq_len += layer_past[0].shape[-2]
601
+ if alibi is None:
602
+ cos, sin = self.rotary_emb(value_layer, seq_len=kv_seq_len)
603
+ query_layer, key_layer = apply_rotary_pos_emb(query_layer, key_layer, cos, sin, position_ids)
604
+
605
+ if layer_past is not None and use_cache:
606
+ past_key, past_value = layer_past
607
+ # concatenate along seq_length dimension:
608
+ # - key: [batch_size, self.num_heads, kv_length, head_dim]
609
+ # - value: [batch_size, self.num_heads, kv_length, head_dim]
610
+ key_layer = torch.cat((past_key, key_layer), dim=-2)
611
+ value_layer = torch.cat((past_value, value_layer), dim=-2)
612
+
613
+ past_key_value = (key_layer, value_layer) if use_cache else None
614
+
615
+ # 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
616
+ # to be able to avoid many of these transpose/reshape/view.
617
+ query_layer = query_layer.transpose(1, 2)
618
+ key_layer = key_layer.transpose(1, 2)
619
+ value_layer = value_layer.transpose(1, 2)
620
+
621
+ if alibi is not None:
622
+ raise ValueError("`alibi` is not supported when `use_flash_attn` is True")
623
+
624
+ attn_dropout = self.config.attention_dropout if self.training else 0.0
625
+
626
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
627
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
628
+ # cast them back in float16 just to be sure everything works as expected.
629
+ input_dtype = query_layer.dtype
630
+ if input_dtype == torch.float32:
631
+ if torch.is_autocast_enabled():
632
+ target_dtype = torch.get_autocast_gpu_dtype()
633
+ # Handle the case where the model is quantized
634
+ elif hasattr(self.config, "_pre_quantization_dtype"):
635
+ target_dtype = self.config._pre_quantization_dtype
636
+ else:
637
+ target_dtype = self.query_key_value.weight.dtype
638
+
639
+ logger.warning_once(
640
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
641
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
642
+ f" {target_dtype}."
643
+ )
644
+
645
+ query_layer = query_layer.to(target_dtype)
646
+ key_layer = key_layer.to(target_dtype)
647
+ value_layer = value_layer.to(target_dtype)
648
+
649
+ attn_output = self._flash_attention_forward(
650
+ query_layer, key_layer, value_layer, attention_mask, query_length, dropout=attn_dropout
651
+ )
652
+
653
+ attn_weights = attn_output.reshape(batch_size, query_length, self.num_heads * self.head_dim)
654
+ attn_output = self.dense(attn_weights)
655
+
656
+ if not output_attentions:
657
+ attn_weights = None
658
+
659
+ return attn_output, past_key_value, attn_weights
660
+
661
+ # Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2._flash_attention_forward
662
+ def _flash_attention_forward(
663
+ self, query_states, key_states, value_states, attention_mask, query_length, dropout=0.0, softmax_scale=None
664
+ ):
665
+ """
666
+ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
667
+ first unpad the input, then computes the attention scores and pad the final attention scores.
668
+
669
+ Args:
670
+ query_states (`torch.Tensor`):
671
+ Input query states to be passed to Flash Attention API
672
+ key_states (`torch.Tensor`):
673
+ Input key states to be passed to Flash Attention API
674
+ value_states (`torch.Tensor`):
675
+ Input value states to be passed to Flash Attention API
676
+ attention_mask (`torch.Tensor`):
677
+ The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
678
+ position of padding tokens and 1 for the position of non-padding tokens.
679
+ dropout (`float`):
680
+ Attention dropout
681
+ softmax_scale (`float`, *optional*):
682
+ The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
683
+ """
684
+ if not self._flash_attn_uses_top_left_mask:
685
+ causal = self.is_causal
686
+ else:
687
+ # TODO: Remove the `query_length != 1` check once Flash Attention for RoCm is bumped to 2.1. For details, please see the comment in LlamaFlashAttention2 __init__.
688
+ causal = self.is_causal and query_length != 1
689
+
690
+ # Contains at least one padding token in the sequence
691
+ if attention_mask is not None:
692
+ batch_size = query_states.shape[0]
693
+ query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._upad_input(
694
+ query_states, key_states, value_states, attention_mask, query_length
695
+ )
696
+
697
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
698
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
699
+
700
+ attn_output_unpad = flash_attn_varlen_func(
701
+ query_states,
702
+ key_states,
703
+ value_states,
704
+ cu_seqlens_q=cu_seqlens_q,
705
+ cu_seqlens_k=cu_seqlens_k,
706
+ max_seqlen_q=max_seqlen_in_batch_q,
707
+ max_seqlen_k=max_seqlen_in_batch_k,
708
+ dropout_p=dropout,
709
+ softmax_scale=softmax_scale,
710
+ causal=causal,
711
+ )
712
+
713
+ attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length)
714
+ else:
715
+ attn_output = flash_attn_func(
716
+ query_states, key_states, value_states, dropout, softmax_scale=softmax_scale, causal=causal
717
+ )
718
+
719
+ return attn_output
720
+
721
+ # Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2._upad_input
722
+ def _upad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length):
723
+ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
724
+ batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape
725
+
726
+ key_layer = index_first_axis(
727
+ key_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
728
+ )
729
+ value_layer = index_first_axis(
730
+ value_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
731
+ )
732
+ if query_length == kv_seq_len:
733
+ query_layer = index_first_axis(
734
+ query_layer.reshape(batch_size * kv_seq_len, self.num_heads, head_dim), indices_k
735
+ )
736
+ cu_seqlens_q = cu_seqlens_k
737
+ max_seqlen_in_batch_q = max_seqlen_in_batch_k
738
+ indices_q = indices_k
739
+ elif query_length == 1:
740
+ max_seqlen_in_batch_q = 1
741
+ cu_seqlens_q = torch.arange(
742
+ batch_size + 1, dtype=torch.int32, device=query_layer.device
743
+ ) # There is a memcpy here, that is very bad.
744
+ indices_q = cu_seqlens_q[:-1]
745
+ query_layer = query_layer.squeeze(1)
746
+ else:
747
+ # The -q_len: slice assumes left padding.
748
+ attention_mask = attention_mask[:, -query_length:]
749
+ query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, attention_mask)
750
+
751
+ return (
752
+ query_layer,
753
+ key_layer,
754
+ value_layer,
755
+ indices_q,
756
+ (cu_seqlens_q, cu_seqlens_k),
757
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
758
+ )
759
+
760
+
761
+ class FalconMLP(nn.Module):
762
+ def __init__(self, config: FalconConfig):
763
+ super().__init__()
764
+ hidden_size = config.hidden_size
765
+
766
+ self.upscale = FalconLinear(
767
+ hidden_size, config.ff_factor * hidden_size, bias=config.bias
768
+ )
769
+ self.act = nn.GELU()
770
+ self.downscale = FalconLinear(
771
+ config.ff_factor * hidden_size, hidden_size, bias=config.bias
772
+ )
773
+ self.hidden_dropout = config.hidden_dropout
774
+
775
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
776
+ x = self.act(self.upscale(x))
777
+ x = self.downscale(x)
778
+ return x
779
+
780
+ FALCON_ATTENTION_CLASSES = {
781
+ "eager": FalconAttention,
782
+ "sdpa": FalconAttention, # FalconAttention originally implemented both a forward with & without SDPA
783
+ "flash_attention_2": FalconFlashAttention2,
784
+ }
785
+
786
+
787
+ class FalconDecoderLayer(nn.Module):
788
+ def __init__(self, config: FalconConfig):
789
+ super().__init__()
790
+ hidden_size = config.hidden_size
791
+ self.num_heads = config.num_attention_heads
792
+
793
+ self.self_attention = FALCON_ATTENTION_CLASSES[config._attn_implementation](config)
794
+ self.mlp = FalconMLP(config)
795
+ self.hidden_dropout = config.hidden_dropout
796
+ self.config = config
797
+
798
+ if config.new_decoder_architecture and config.num_ln_in_parallel_attn == 2:
799
+ # The layer norm before self-attention
800
+ self.ln_attn = LayerNorm(hidden_size, eps=config.layer_norm_epsilon)
801
+ # The layer norm before the MLP
802
+ self.ln_mlp = LayerNorm(hidden_size, eps=config.layer_norm_epsilon)
803
+ else:
804
+ self.input_layernorm = LayerNorm(hidden_size, eps=config.layer_norm_epsilon)
805
+ if not config.parallel_attn:
806
+ self.post_attention_layernorm = LayerNorm(hidden_size, eps=config.layer_norm_epsilon)
807
+
808
+ def forward(
809
+ self,
810
+ hidden_states: torch.Tensor,
811
+ alibi: Optional[torch.Tensor],
812
+ attention_mask: torch.Tensor,
813
+ position_ids: Optional[torch.LongTensor] = None,
814
+ layer_past: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
815
+ head_mask: Optional[torch.Tensor] = None,
816
+ use_cache: bool = False,
817
+ output_attentions: bool = False,
818
+ **kwargs,
819
+ ):
820
+ if "padding_mask" in kwargs:
821
+ warnings.warn(
822
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
823
+ )
824
+
825
+ residual = hidden_states
826
+
827
+ if self.config.num_ln_in_parallel_attn == 2:
828
+ attention_layernorm_out = self.ln_attn(hidden_states)
829
+ mlp_layernorm_out = self.ln_mlp(hidden_states)
830
+ else:
831
+ attention_layernorm_out = self.input_layernorm(hidden_states)
832
+
833
+ # Self attention.
834
+ attn_outputs = self.self_attention(
835
+ attention_layernorm_out,
836
+ layer_past=layer_past,
837
+ attention_mask=attention_mask,
838
+ position_ids=position_ids,
839
+ alibi=alibi,
840
+ head_mask=head_mask,
841
+ use_cache=use_cache,
842
+ output_attentions=output_attentions,
843
+ **kwargs,
844
+ )
845
+
846
+ attention_output = attn_outputs[0]
847
+
848
+ if self.config.num_ln_in_parallel_attn == 1:
849
+ if self.config.parallel_attn:
850
+ mlp_layernorm_out = attention_layernorm_out
851
+ else:
852
+ residual = dropout_add(
853
+ attention_output, residual, self.config.attention_dropout, training=self.training
854
+ )
855
+ mlp_layernorm_out = self.post_attention_layernorm(residual)
856
+
857
+ outputs = attn_outputs[1:]
858
+
859
+ # MLP.
860
+ mlp_output = self.mlp(mlp_layernorm_out)
861
+
862
+ if self.config.new_decoder_architecture or self.config.parallel_attn:
863
+ mlp_output += attention_output
864
+
865
+ output = dropout_add(mlp_output, residual, self.config.hidden_dropout, training=self.training)
866
+
867
+ if use_cache:
868
+ outputs = (output,) + outputs
869
+ else:
870
+ outputs = (output,) + outputs[1:]
871
+
872
+ return outputs # hidden_states, present, attentions
873
+
874
+
875
+ FALCON_START_DOCSTRING = r"""
876
+
877
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
878
+ library implements for all its model (such as downloading or saving, resizing the input embeddings etc.)
879
+
880
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
881
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
882
+ and behavior.
883
+
884
+ Parameters:
885
+ config ([`FalconConfig`]): Model configuration class with all the parameters of the model.
886
+ Initializing with a config file does not load the weights associated with the model, only the
887
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
888
+ """
889
+
890
+ FALCON_INPUTS_DOCSTRING = r"""
891
+ Args:
892
+ input_ids (`torch.LongTensor` of shape `(batch_size, input_ids_length)`):
893
+ `input_ids_length` = `sequence_length` if `past_key_values` is `None` else `past_key_values[0][0].shape[2]`
894
+ (`sequence_length` of input past key value states). Indices of input sequence tokens in the vocabulary.
895
+
896
+ If `past_key_values` is used, only `input_ids` that do not have their past calculated should be passed as
897
+ `input_ids`.
898
+
899
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
900
+ [`PreTrainedTokenizer.__call__`] for details.
901
+
902
+ [What are input IDs?](../glossary#input-ids)
903
+ past_key_values (`Tuple[Tuple[torch.Tensor]]` of length `config.num_hidden_layers`):
904
+ Contains precomputed hidden-states (key and values in the attention blocks) as computed by the model (see
905
+ `past_key_values` output below). Can be used to speed up sequential decoding. The `input_ids` which have
906
+ their past given to this model should not be passed as `input_ids` as they have already been computed.
907
+
908
+ Each element of `past_key_values` is a tuple (past_key, past_value):
909
+ - past_key: [batch_size * num_heads, head_dim, kv_length]
910
+ - past_value: [batch_size * num_heads, kv_length, head_dim]
911
+ attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
912
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
913
+
914
+ - 1 for tokens that are **not masked**,
915
+ - 0 for tokens that are **masked**.
916
+
917
+ [What are attention masks?](../glossary#attention-mask)
918
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
919
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
920
+ config.n_positions - 1]`.
921
+
922
+ [What are position IDs?](../glossary#position-ids)
923
+ head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
924
+ Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
925
+
926
+ - 1 indicates the head is **not masked**,
927
+ - 0 indicates the head is **masked**.
928
+
929
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
930
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
931
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
932
+ model's internal embedding lookup matrix.
933
+
934
+ If `past_key_values` is used, optionally only the last `inputs_embeds` have to be input (see
935
+ `past_key_values`).
936
+ use_cache (`bool`, *optional*):
937
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
938
+ `past_key_values`).
939
+ output_attentions (`bool`, *optional*):
940
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
941
+ tensors for more detail.
942
+ output_hidden_states (`bool`, *optional*):
943
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
944
+ more detail.
945
+ return_dict (`bool`, *optional*):
946
+ Whether or not to return a [`~file_utils.ModelOutput`] instead of a plain tuple.
947
+ """
948
+
949
+
950
+ class FalconPreTrainedModel(PreTrainedModel):
951
+ """
952
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
953
+ models.
954
+ """
955
+
956
+ config_class = FalconConfig
957
+ base_model_prefix = "transformer"
958
+ supports_gradient_checkpointing = True
959
+ _no_split_modules = ["FalconDecoderLayer"]
960
+ _supports_flash_attn_2 = True
961
+ _supports_sdpa = True
962
+
963
+ def __init__(self, *inputs, **kwargs):
964
+ super().__init__(*inputs, **kwargs)
965
+
966
+ def _init_weights(self, module: nn.Module):
967
+ """Initialize the weights."""
968
+ if isinstance(module, nn.Linear) or isinstance(module, FalconLinear):
969
+ # Slightly different from the TF version which uses truncated_normal for initialization
970
+ # cf https://github.com/pytorch/pytorch/pull/5617
971
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
972
+ if module.bias is not None:
973
+ module.bias.data.zero_()
974
+ elif isinstance(module, nn.Embedding):
975
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
976
+ if module.padding_idx is not None:
977
+ module.weight.data[module.padding_idx].zero_()
978
+ elif isinstance(module, LayerNorm):
979
+ module.bias.data.zero_()
980
+ module.weight.data.fill_(1.0)
981
+
982
+ # Adapted from transformers.modeling_utils.PreTrainedModel._check_and_enable_sdpa
983
+ @classmethod
984
+ def _check_and_enable_sdpa(cls, config, hard_check_only: bool = False) -> "PretrainedConfig":
985
+ # NOTE: Falcon supported SDPA from PyTorch 2.0. We keep it like that for backward compatibility (automatically use SDPA for torch>=2.0).
986
+ if hard_check_only:
987
+ if not is_torch_greater_or_equal_than_2_0:
988
+ raise ImportError("PyTorch SDPA requirements in Transformers are not met. Please install torch>=2.0.")
989
+
990
+ if not is_torch_greater_or_equal_than_2_0:
991
+ return config
992
+
993
+ _is_bettertransformer = getattr(cls, "use_bettertransformer", False)
994
+ if _is_bettertransformer:
995
+ return config
996
+
997
+ if not hard_check_only:
998
+ config._attn_implementation = "sdpa"
999
+ return config
1000
+
1001
+
1002
+ @add_start_docstrings(
1003
+ "The bare Falcon Model transformer outputting raw hidden-states without any specific head on top.",
1004
+ FALCON_START_DOCSTRING,
1005
+ )
1006
+ class FalconModel(FalconPreTrainedModel):
1007
+ def __init__(self, config: FalconConfig):
1008
+ super().__init__(config)
1009
+
1010
+ self.embed_dim = config.hidden_size
1011
+ self.num_heads = config.num_attention_heads
1012
+ self.use_alibi = config.alibi
1013
+
1014
+ # Embedding + LN Embedding
1015
+ self.word_embeddings = nn.Embedding(config.vocab_size, self.embed_dim)
1016
+
1017
+ # Transformer blocks
1018
+ self.h = nn.ModuleList([FalconDecoderLayer(config) for _ in range(config.num_hidden_layers)])
1019
+ self._use_flash_attention_2 = config._attn_implementation == "flash_attention_2"
1020
+ self._use_sdpa = config._attn_implementation == "sdpa"
1021
+
1022
+ # Final Layer Norm
1023
+ self.ln_f = LayerNorm(self.embed_dim, eps=config.layer_norm_epsilon)
1024
+
1025
+ self.gradient_checkpointing = False
1026
+
1027
+ # Initialize weights and apply final processing
1028
+ self.post_init()
1029
+
1030
+ def get_input_embeddings(self):
1031
+ return self.word_embeddings
1032
+
1033
+ def set_input_embeddings(self, new_embeddings: torch.Tensor):
1034
+ self.word_embeddings = new_embeddings
1035
+
1036
+ @add_start_docstrings_to_model_forward(FALCON_INPUTS_DOCSTRING)
1037
+ @add_code_sample_docstrings(
1038
+ checkpoint=_CHECKPOINT_FOR_DOC,
1039
+ output_type=BaseModelOutputWithPastAndCrossAttentions,
1040
+ config_class=_CONFIG_FOR_DOC,
1041
+ )
1042
+ def forward(
1043
+ self,
1044
+ input_ids: Optional[torch.LongTensor] = None,
1045
+ past_key_values: Optional[Tuple[Tuple[torch.Tensor, torch.Tensor], ...]] = None,
1046
+ attention_mask: Optional[torch.Tensor] = None,
1047
+ position_ids: Optional[torch.LongTensor] = None,
1048
+ head_mask: Optional[torch.LongTensor] = None,
1049
+ inputs_embeds: Optional[torch.LongTensor] = None,
1050
+ use_cache: Optional[bool] = None,
1051
+ output_attentions: Optional[bool] = None,
1052
+ output_hidden_states: Optional[bool] = None,
1053
+ return_dict: Optional[bool] = None,
1054
+ ) -> Union[Tuple[torch.Tensor, ...], BaseModelOutputWithPastAndCrossAttentions]:
1055
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1056
+ output_hidden_states = (
1057
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1058
+ )
1059
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1060
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1061
+
1062
+ if input_ids is not None and inputs_embeds is not None:
1063
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
1064
+ elif input_ids is not None:
1065
+ batch_size, seq_length = input_ids.shape
1066
+ elif inputs_embeds is not None:
1067
+ batch_size, seq_length, _ = inputs_embeds.shape
1068
+ else:
1069
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
1070
+
1071
+ if past_key_values is None:
1072
+ past_key_values = tuple([None] * len(self.h))
1073
+
1074
+ if inputs_embeds is None:
1075
+ inputs_embeds = self.word_embeddings(input_ids)
1076
+
1077
+ hidden_states = inputs_embeds
1078
+
1079
+ if self.gradient_checkpointing and self.training:
1080
+ if use_cache:
1081
+ logger.warning(
1082
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
1083
+ )
1084
+ use_cache = False
1085
+ presents = () if use_cache else None
1086
+ all_self_attentions = () if output_attentions else None
1087
+ all_hidden_states = () if output_hidden_states else None
1088
+
1089
+ # Compute alibi tensor: check build_alibi_tensor documentation
1090
+ past_key_values_length = 0
1091
+ if past_key_values[0] is not None:
1092
+ past_key_values_length = past_key_values[0][0].shape[-2]
1093
+
1094
+ if self.use_alibi:
1095
+ mask = (
1096
+ torch.ones(
1097
+ (batch_size, seq_length + past_key_values_length), device=inputs_embeds.device, dtype=torch.long
1098
+ )
1099
+ if attention_mask is None
1100
+ else attention_mask
1101
+ )
1102
+ alibi = build_alibi_tensor(mask, self.num_heads, dtype=hidden_states.dtype)
1103
+ else:
1104
+ alibi = None
1105
+ if position_ids is None:
1106
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
1107
+ position_ids = torch.arange(
1108
+ past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
1109
+ )
1110
+ position_ids = position_ids.unsqueeze(0)
1111
+
1112
+ if self._use_flash_attention_2:
1113
+ # 2d mask is passed through the layers
1114
+ attention_mask = attention_mask if (attention_mask is not None and 0 in attention_mask) else None
1115
+ elif self._use_sdpa and not output_attentions:
1116
+ # output_attentions=True can not be supported when using SDPA, and we fall back on
1117
+ # the manual implementation that requires a 4D causal mask in all cases.
1118
+ if alibi is None:
1119
+ attention_mask = _prepare_4d_causal_attention_mask_for_sdpa(
1120
+ attention_mask,
1121
+ (batch_size, seq_length),
1122
+ inputs_embeds,
1123
+ past_key_values_length,
1124
+ )
1125
+ elif head_mask is None:
1126
+ alibi = alibi.reshape(batch_size, -1, *alibi.shape[1:])
1127
+
1128
+ attention_mask_2d = attention_mask
1129
+ # We don't call _prepare_4d_causal_attention_mask_for_sdpa as we need to mask alibi using the 4D attention_mask untouched.
1130
+ attention_mask = _prepare_4d_causal_attention_mask(
1131
+ attention_mask, (batch_size, seq_length), inputs_embeds, past_key_values_length
1132
+ )
1133
+
1134
+ # We take care to integrate alibi bias in the attention_mask here.
1135
+ if attention_mask_2d is None:
1136
+ attention_mask = alibi / math.sqrt(self.config.hidden_size // self.num_heads)
1137
+ else:
1138
+ min_dtype = torch.finfo(alibi.dtype).min
1139
+ attention_mask = torch.masked_fill(
1140
+ alibi / math.sqrt(self.config.hidden_size // self.num_heads),
1141
+ attention_mask < -1,
1142
+ min_dtype,
1143
+ )
1144
+
1145
+ # From PyTorch 2.1 onwards, F.scaled_dot_product_attention with the memory-efficient attention backend
1146
+ # produces nans if sequences are completely unattended in the attention mask. Details: https://github.com/pytorch/pytorch/issues/110213
1147
+ if seq_length > 1 and attention_mask.device.type == "cuda":
1148
+ attention_mask = AttentionMaskConverter._unmask_unattended(attention_mask, min_dtype=min_dtype)
1149
+ else:
1150
+ # PyTorch SDPA does not support head_mask, we fall back on the eager implementation in this case.
1151
+ attention_mask = _prepare_4d_causal_attention_mask(
1152
+ attention_mask, (batch_size, seq_length), inputs_embeds, past_key_values_length
1153
+ )
1154
+ else:
1155
+ # 4d mask is passed through the layers
1156
+ attention_mask = _prepare_4d_causal_attention_mask(
1157
+ attention_mask, (batch_size, seq_length), inputs_embeds, past_key_values_length
1158
+ )
1159
+
1160
+ # Prepare head mask if needed
1161
+ # 1.0 in head_mask indicate we keep the head
1162
+ # attention_probs has shape batch_size x num_heads x N x N
1163
+ # head_mask has shape n_layer x batch x num_heads x N x N
1164
+ head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
1165
+
1166
+ for i, (block, layer_past) in enumerate(zip(self.h, past_key_values)):
1167
+ if output_hidden_states:
1168
+ all_hidden_states = all_hidden_states + (hidden_states,)
1169
+
1170
+ if self.gradient_checkpointing and self.training:
1171
+ outputs = self._gradient_checkpointing_func(
1172
+ block.__call__,
1173
+ hidden_states,
1174
+ alibi,
1175
+ attention_mask,
1176
+ position_ids,
1177
+ head_mask[i],
1178
+ layer_past,
1179
+ use_cache,
1180
+ output_attentions,
1181
+ )
1182
+ else:
1183
+ outputs = block(
1184
+ hidden_states,
1185
+ layer_past=layer_past,
1186
+ attention_mask=attention_mask,
1187
+ position_ids=position_ids,
1188
+ head_mask=head_mask[i],
1189
+ use_cache=use_cache,
1190
+ output_attentions=output_attentions,
1191
+ alibi=alibi,
1192
+ )
1193
+
1194
+ hidden_states = outputs[0]
1195
+ if use_cache is True:
1196
+ presents = presents + (outputs[1],)
1197
+
1198
+ if output_attentions:
1199
+ all_self_attentions = all_self_attentions + (outputs[2 if use_cache else 1],)
1200
+
1201
+ # Add last hidden state
1202
+ hidden_states = self.ln_f(hidden_states)
1203
+
1204
+ if output_hidden_states:
1205
+ all_hidden_states = all_hidden_states + (hidden_states,)
1206
+
1207
+ if not return_dict:
1208
+ return tuple(v for v in [hidden_states, presents, all_hidden_states, all_self_attentions] if v is not None)
1209
+
1210
+ return BaseModelOutputWithPastAndCrossAttentions(
1211
+ last_hidden_state=hidden_states,
1212
+ past_key_values=presents,
1213
+ hidden_states=all_hidden_states,
1214
+ attentions=all_self_attentions,
1215
+ )
1216
+
1217
+
1218
+ @add_start_docstrings(
1219
+ "The Falcon Model transformer with a language modeling head on top (linear layer with weights tied to the input embeddings).",
1220
+ FALCON_START_DOCSTRING,
1221
+ )
1222
+ class FalconForCausalLM(FalconPreTrainedModel):
1223
+ _tied_weights_keys = None # ["lm_head.weight"]
1224
+
1225
+ def __init__(self, config: FalconConfig):
1226
+ super().__init__(config)
1227
+ self.transformer = FalconModel(config)
1228
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1229
+
1230
+ # Initialize weights and apply final processing
1231
+ self.post_init()
1232
+
1233
+ def get_output_embeddings(self):
1234
+ return self.lm_head
1235
+
1236
+ def set_output_embeddings(self, new_embeddings: torch.Tensor):
1237
+ self.lm_head = new_embeddings
1238
+
1239
+ def prepare_inputs_for_generation(
1240
+ self,
1241
+ input_ids: torch.LongTensor,
1242
+ past_key_values: Optional[torch.Tensor] = None,
1243
+ attention_mask: Optional[torch.Tensor] = None,
1244
+ position_ids: Optional[torch.Tensor] = None,
1245
+ **kwargs,
1246
+ ) -> dict:
1247
+ if past_key_values is not None:
1248
+ past_length = past_key_values[0][0].shape[2]
1249
+
1250
+ # Some generation methods already pass only the last input ID
1251
+ if input_ids.shape[1] > past_length:
1252
+ remove_prefix_length = past_length
1253
+ else:
1254
+ # Default to old behavior: keep only final ID
1255
+ remove_prefix_length = input_ids.shape[1] - 1
1256
+
1257
+ input_ids = input_ids[:, remove_prefix_length:]
1258
+
1259
+ # Note: versions of Falcon with alibi do not use position_ids. It is used with RoPE.
1260
+ if not self.transformer.use_alibi and attention_mask is not None and position_ids is None:
1261
+ # create position_ids on the fly for batch generation
1262
+ position_ids = attention_mask.long().cumsum(-1) - 1
1263
+ position_ids.masked_fill_(attention_mask == 0, 1)
1264
+ if past_key_values:
1265
+ position_ids = position_ids[:, -input_ids.shape[1] :]
1266
+
1267
+ return {
1268
+ "input_ids": input_ids,
1269
+ "position_ids": position_ids,
1270
+ "past_key_values": past_key_values,
1271
+ "use_cache": kwargs.get("use_cache"),
1272
+ "attention_mask": attention_mask,
1273
+ }
1274
+
1275
+ @add_start_docstrings_to_model_forward(FALCON_INPUTS_DOCSTRING)
1276
+ @add_code_sample_docstrings(
1277
+ checkpoint=_CHECKPOINT_FOR_DOC,
1278
+ output_type=CausalLMOutputWithCrossAttentions,
1279
+ config_class=_CONFIG_FOR_DOC,
1280
+ )
1281
+ def forward(
1282
+ self,
1283
+ input_ids: Optional[torch.LongTensor] = None,
1284
+ past_key_values: Optional[Tuple[Tuple[torch.Tensor, torch.Tensor], ...]] = None,
1285
+ attention_mask: Optional[torch.Tensor] = None,
1286
+ position_ids: Optional[torch.LongTensor] = None,
1287
+ head_mask: Optional[torch.Tensor] = None,
1288
+ inputs_embeds: Optional[torch.Tensor] = None,
1289
+ labels: Optional[torch.Tensor] = None,
1290
+ use_cache: Optional[bool] = None,
1291
+ output_attentions: Optional[bool] = None,
1292
+ output_hidden_states: Optional[bool] = None,
1293
+ return_dict: Optional[bool] = None,
1294
+ ) -> Union[Tuple[torch.Tensor], CausalLMOutputWithCrossAttentions]:
1295
+ r"""
1296
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1297
+ Labels for language modeling. Note that the labels **are shifted** inside the model, i.e. you can set
1298
+ `labels = input_ids` Indices are selected in `[-100, 0, ..., config.vocab_size]` All labels set to `-100`
1299
+ are ignored (masked), the loss is only computed for labels in `[0, ..., config.vocab_size]`
1300
+ """
1301
+
1302
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1303
+
1304
+ transformer_outputs = self.transformer(
1305
+ input_ids,
1306
+ past_key_values=past_key_values,
1307
+ attention_mask=attention_mask,
1308
+ position_ids=position_ids,
1309
+ head_mask=head_mask,
1310
+ inputs_embeds=inputs_embeds,
1311
+ use_cache=use_cache,
1312
+ output_attentions=output_attentions,
1313
+ output_hidden_states=output_hidden_states,
1314
+ return_dict=return_dict,
1315
+ )
1316
+ hidden_states = transformer_outputs[0]
1317
+
1318
+ lm_logits = self.lm_head(hidden_states)
1319
+
1320
+ loss = None
1321
+ if labels is not None:
1322
+ # Shift so that tokens < n predict n
1323
+ shift_logits = lm_logits[..., :-1, :].contiguous()
1324
+ shift_labels = labels[..., 1:].contiguous()
1325
+ batch_size, seq_length, vocab_size = shift_logits.shape
1326
+ # Flatten the tokens
1327
+ loss_fct = CrossEntropyLoss()
1328
+ loss = loss_fct(
1329
+ shift_logits.view(batch_size * seq_length, vocab_size), shift_labels.view(batch_size * seq_length)
1330
+ )
1331
+
1332
+ if not return_dict:
1333
+ output = (lm_logits,) + transformer_outputs[1:]
1334
+ return ((loss,) + output) if loss is not None else output
1335
+
1336
+ return CausalLMOutputWithCrossAttentions(
1337
+ loss=loss,
1338
+ logits=lm_logits,
1339
+ past_key_values=transformer_outputs.past_key_values,
1340
+ hidden_states=transformer_outputs.hidden_states,
1341
+ attentions=transformer_outputs.attentions,
1342
+ )
1343
+
1344
+ def _reorder_cache(
1345
+ self, past: Tuple[Tuple[torch.Tensor, torch.Tensor], ...], beam_idx: torch.LongTensor
1346
+ ) -> Tuple[Tuple[torch.Tensor, torch.Tensor], ...]:
1347
+ """
1348
+ This function is used to re-order the `past_key_values` cache if [`~PreTrainedModel.beam_search`] or
1349
+ [`~PreTrainedModel.beam_sample`] is called. This is required to match `past_key_values` with the correct
1350
+ beam_idx at every generation step.
1351
+
1352
+ Output shares the same memory storage as `past`.
1353
+ """
1354
+
1355
+ # Get a copy of `beam_idx` on all the devices where we need those indices.
1356
+ device_to_beam_idx = {
1357
+ past_state.device: beam_idx.to(past_state.device) for layer_past in past for past_state in layer_past
1358
+ }
1359
+ reordered_past = tuple(
1360
+ (
1361
+ layer_past[0].index_select(0, device_to_beam_idx[layer_past[0].device]),
1362
+ layer_past[1].index_select(0, device_to_beam_idx[layer_past[0].device]),
1363
+ )
1364
+ for layer_past in past
1365
+ )
1366
+ return reordered_past
1367
+
1368
+
1369
+ @add_start_docstrings(
1370
+ """
1371
+ The Falcon Model transformer with a sequence classification head on top (linear layer).
1372
+
1373
+ [`FalconForSequenceClassification`] uses the last token in order to do the classification, as other causal models
1374
+ (e.g. GPT-1) do.
1375
+
1376
+ Since it does classification on the last token, it requires to know the position of the last token. If a
1377
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
1378
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1379
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1380
+ each row of the batch).
1381
+ """,
1382
+ FALCON_START_DOCSTRING,
1383
+ )
1384
+ class FalconForSequenceClassification(FalconPreTrainedModel):
1385
+ def __init__(self, config: FalconConfig):
1386
+ super().__init__(config)
1387
+ self.num_labels = config.num_labels
1388
+ self.transformer = FalconModel(config)
1389
+ self.score = nn.Linear(config.hidden_size, config.num_labels, bias=False)
1390
+
1391
+ # Initialize weights and apply final processing
1392
+ self.post_init()
1393
+
1394
+ @add_start_docstrings_to_model_forward(FALCON_INPUTS_DOCSTRING)
1395
+ @add_code_sample_docstrings(
1396
+ checkpoint=_CHECKPOINT_FOR_DOC,
1397
+ output_type=SequenceClassifierOutputWithPast,
1398
+ config_class=_CONFIG_FOR_DOC,
1399
+ )
1400
+ def forward(
1401
+ self,
1402
+ input_ids: Optional[torch.LongTensor] = None,
1403
+ past_key_values: Optional[Tuple[Tuple[torch.Tensor, torch.Tensor], ...]] = None,
1404
+ attention_mask: Optional[torch.Tensor] = None,
1405
+ head_mask: Optional[torch.Tensor] = None,
1406
+ inputs_embeds: Optional[torch.Tensor] = None,
1407
+ labels: Optional[torch.Tensor] = None,
1408
+ use_cache: Optional[bool] = None,
1409
+ output_attentions: Optional[bool] = None,
1410
+ output_hidden_states: Optional[bool] = None,
1411
+ return_dict: Optional[bool] = None,
1412
+ ) -> Union[Tuple[torch.Tensor], SequenceClassifierOutputWithPast]:
1413
+ r"""
1414
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1415
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1416
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1417
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1418
+ """
1419
+
1420
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1421
+
1422
+ transformer_outputs = self.transformer(
1423
+ input_ids,
1424
+ past_key_values=past_key_values,
1425
+ attention_mask=attention_mask,
1426
+ head_mask=head_mask,
1427
+ inputs_embeds=inputs_embeds,
1428
+ use_cache=use_cache,
1429
+ output_attentions=output_attentions,
1430
+ output_hidden_states=output_hidden_states,
1431
+ return_dict=return_dict,
1432
+ )
1433
+
1434
+ hidden_states = transformer_outputs[0]
1435
+ logits = self.score(hidden_states)
1436
+
1437
+ if input_ids is not None:
1438
+ batch_size = input_ids.shape[0]
1439
+ else:
1440
+ batch_size = inputs_embeds.shape[0]
1441
+
1442
+ if self.config.pad_token_id is None and batch_size != 1:
1443
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
1444
+ if self.config.pad_token_id is None:
1445
+ sequence_lengths = -1
1446
+ else:
1447
+ if input_ids is not None:
1448
+ # if no pad token found, use modulo instead of reverse indexing for ONNX compatibility
1449
+ sequence_lengths = torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
1450
+ sequence_lengths = sequence_lengths % input_ids.shape[-1]
1451
+ sequence_lengths = sequence_lengths.to(logits.device)
1452
+ else:
1453
+ sequence_lengths = -1
1454
+ logger.warning(
1455
+ f"{self.__class__.__name__} will not detect padding tokens in `inputs_embeds`. Results may be "
1456
+ "unexpected if using padding tokens in conjunction with `inputs_embeds.`"
1457
+ )
1458
+
1459
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
1460
+
1461
+ loss = None
1462
+ if labels is not None:
1463
+ if self.config.problem_type is None:
1464
+ if self.num_labels == 1:
1465
+ self.config.problem_type = "regression"
1466
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1467
+ self.config.problem_type = "single_label_classification"
1468
+ else:
1469
+ self.config.problem_type = "multi_label_classification"
1470
+
1471
+ if self.config.problem_type == "regression":
1472
+ loss_fct = MSELoss()
1473
+ if self.num_labels == 1:
1474
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
1475
+ else:
1476
+ loss = loss_fct(pooled_logits, labels)
1477
+ elif self.config.problem_type == "single_label_classification":
1478
+ loss_fct = CrossEntropyLoss()
1479
+ loss = loss_fct(pooled_logits, labels)
1480
+ elif self.config.problem_type == "multi_label_classification":
1481
+ loss_fct = BCEWithLogitsLoss()
1482
+ loss = loss_fct(pooled_logits, labels)
1483
+ if not return_dict:
1484
+ output = (pooled_logits,) + transformer_outputs[1:]
1485
+ return ((loss,) + output) if loss is not None else output
1486
+
1487
+ return SequenceClassifierOutputWithPast(
1488
+ loss=loss,
1489
+ logits=pooled_logits,
1490
+ past_key_values=transformer_outputs.past_key_values,
1491
+ hidden_states=transformer_outputs.hidden_states,
1492
+ attentions=transformer_outputs.attentions,
1493
+ )
1494
+
1495
+
1496
+ @add_start_docstrings(
1497
+ """
1498
+ Falcon Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for
1499
+ Named-Entity-Recognition (NER) tasks.
1500
+ """,
1501
+ FALCON_START_DOCSTRING,
1502
+ )
1503
+ class FalconForTokenClassification(FalconPreTrainedModel):
1504
+ def __init__(self, config: FalconConfig):
1505
+ super().__init__(config)
1506
+ self.num_labels = config.num_labels
1507
+
1508
+ self.transformer = FalconModel(config)
1509
+ if getattr(config, "classifier_dropout", None) is not None:
1510
+ classifier_dropout = config.classifier_dropout
1511
+ elif getattr(config, "hidden_dropout", None) is not None:
1512
+ classifier_dropout = config.hidden_dropout
1513
+ else:
1514
+ classifier_dropout = 0.1
1515
+ self.dropout = nn.Dropout(classifier_dropout)
1516
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
1517
+
1518
+ # Initialize weights and apply final processing
1519
+ self.post_init()
1520
+
1521
+ @add_start_docstrings_to_model_forward(FALCON_INPUTS_DOCSTRING)
1522
+ @add_code_sample_docstrings(
1523
+ checkpoint=_CHECKPOINT_FOR_DOC,
1524
+ output_type=TokenClassifierOutput,
1525
+ config_class=_CONFIG_FOR_DOC,
1526
+ )
1527
+ def forward(
1528
+ self,
1529
+ input_ids: Optional[torch.LongTensor] = None,
1530
+ past_key_values: Optional[Tuple[Tuple[torch.Tensor, torch.Tensor], ...]] = None,
1531
+ attention_mask: Optional[torch.Tensor] = None,
1532
+ head_mask: Optional[torch.Tensor] = None,
1533
+ inputs_embeds: Optional[torch.Tensor] = None,
1534
+ labels: Optional[torch.Tensor] = None,
1535
+ use_cache: Optional[bool] = None,
1536
+ output_attentions: Optional[bool] = None,
1537
+ output_hidden_states: Optional[bool] = None,
1538
+ return_dict: Optional[bool] = None,
1539
+ ) -> Union[Tuple[torch.Tensor], TokenClassifierOutput]:
1540
+ r"""
1541
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1542
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1543
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1544
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1545
+ """
1546
+
1547
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1548
+
1549
+ transformer_outputs = self.transformer(
1550
+ input_ids,
1551
+ past_key_values=past_key_values,
1552
+ attention_mask=attention_mask,
1553
+ head_mask=head_mask,
1554
+ inputs_embeds=inputs_embeds,
1555
+ use_cache=use_cache,
1556
+ output_attentions=output_attentions,
1557
+ output_hidden_states=output_hidden_states,
1558
+ return_dict=return_dict,
1559
+ )
1560
+
1561
+ hidden_states = transformer_outputs[0]
1562
+ hidden_states = self.dropout(hidden_states)
1563
+ logits = self.classifier(hidden_states)
1564
+
1565
+ loss = None
1566
+ if labels is not None:
1567
+ batch_size, seq_length = labels.shape
1568
+ loss_fct = CrossEntropyLoss()
1569
+ loss = loss_fct(
1570
+ logits.view(batch_size * seq_length, self.num_labels), labels.view(batch_size * seq_length)
1571
+ )
1572
+
1573
+ if not return_dict:
1574
+ output = (logits,) + transformer_outputs[2:]
1575
+ return ((loss,) + output) if loss is not None else output
1576
+
1577
+ return TokenClassifierOutput(
1578
+ loss=loss,
1579
+ logits=logits,
1580
+ hidden_states=transformer_outputs.hidden_states,
1581
+ attentions=transformer_outputs.attentions,
1582
+ )
1583
+
1584
+
1585
+ @add_start_docstrings(
1586
+ """
1587
+ The Falcon Model transformer with a span classification head on top for extractive question-answering tasks like
1588
+ SQuAD (a linear layers on top of the hidden-states output to compute `span start logits` and `span end logits`).
1589
+ """,
1590
+ FALCON_START_DOCSTRING,
1591
+ )
1592
+ class FalconForQuestionAnswering(FalconPreTrainedModel):
1593
+ def __init__(self, config):
1594
+ super().__init__(config)
1595
+ self.transformer = FalconModel(config)
1596
+ self.qa_outputs = nn.Linear(config.hidden_size, 2)
1597
+
1598
+ # Initialize weights and apply final processing
1599
+ self.post_init()
1600
+
1601
+ @add_start_docstrings_to_model_forward(FALCON_INPUTS_DOCSTRING)
1602
+ def forward(
1603
+ self,
1604
+ input_ids: Optional[torch.LongTensor] = None,
1605
+ attention_mask: Optional[torch.FloatTensor] = None,
1606
+ head_mask: Optional[torch.FloatTensor] = None,
1607
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1608
+ start_positions: Optional[torch.LongTensor] = None,
1609
+ end_positions: Optional[torch.LongTensor] = None,
1610
+ output_attentions: Optional[bool] = None,
1611
+ output_hidden_states: Optional[bool] = None,
1612
+ return_dict: Optional[bool] = None,
1613
+ ) -> Union[Tuple, QuestionAnsweringModelOutput]:
1614
+ r"""
1615
+ start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1616
+ Labels for position (index) of the start of the labelled span for computing the token classification loss.
1617
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
1618
+ are not taken into account for computing the loss.
1619
+ end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1620
+ Labels for position (index) of the end of the labelled span for computing the token classification loss.
1621
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
1622
+ are not taken into account for computing the loss.
1623
+ """
1624
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1625
+
1626
+ outputs = self.transformer(
1627
+ input_ids,
1628
+ attention_mask=attention_mask,
1629
+ head_mask=head_mask,
1630
+ inputs_embeds=inputs_embeds,
1631
+ output_attentions=output_attentions,
1632
+ output_hidden_states=output_hidden_states,
1633
+ return_dict=return_dict,
1634
+ )
1635
+
1636
+ sequence_output = outputs[0]
1637
+
1638
+ logits = self.qa_outputs(sequence_output)
1639
+ start_logits, end_logits = logits.split(1, dim=-1)
1640
+ start_logits = start_logits.squeeze(-1).contiguous()
1641
+ end_logits = end_logits.squeeze(-1).contiguous()
1642
+
1643
+ total_loss = None
1644
+ if start_positions is not None and end_positions is not None:
1645
+ # If we are on multi-GPU, split add a dimension
1646
+ if len(start_positions.size()) > 1:
1647
+ start_positions = start_positions.squeeze(-1)
1648
+ if len(end_positions.size()) > 1:
1649
+ end_positions = end_positions.squeeze(-1)
1650
+ # sometimes the start/end positions are outside our model inputs, we ignore these terms
1651
+ ignored_index = start_logits.size(1)
1652
+ start_positions = start_positions.clamp(0, ignored_index)
1653
+ end_positions = end_positions.clamp(0, ignored_index)
1654
+
1655
+ loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
1656
+ start_loss = loss_fct(start_logits, start_positions)
1657
+ end_loss = loss_fct(end_logits, end_positions)
1658
+ total_loss = (start_loss + end_loss) / 2
1659
+
1660
+ if not return_dict:
1661
+ output = (start_logits, end_logits) + outputs[2:]
1662
+ return ((total_loss,) + output) if total_loss is not None else output
1663
+
1664
+ return QuestionAnsweringModelOutput(
1665
+ loss=total_loss,
1666
+ start_logits=start_logits,
1667
+ end_logits=end_logits,
1668
+ hidden_states=outputs.hidden_states,
1669
+ attentions=outputs.attentions,
1670
+ )
special_tokens_map.json ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "additional_special_tokens": [
3
+ ">>TITLE<<",
4
+ ">>ABSTRACT<<",
5
+ ">>INTRODUCTION<<",
6
+ ">>SUMMARY<<",
7
+ ">>COMMENT<<",
8
+ ">>ANSWER<<",
9
+ ">>QUESTION<<",
10
+ ">>DOMAIN<<",
11
+ ">>PREFIX<<",
12
+ ">>SUFFIX<<",
13
+ ">>MIDDLE<<"
14
+ ],
15
+ "bos_token": ">>",
16
+ "eos_token": {
17
+ "content": "<|endoftext|>",
18
+ "lstrip": false,
19
+ "normalized": false,
20
+ "rstrip": false,
21
+ "single_word": false
22
+ },
23
+ "pad_token": "<|endoftext|>"
24
+ }
tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
tokenizer_config.json ADDED
@@ -0,0 +1,135 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_prefix_space": false,
3
+ "added_tokens_decoder": {
4
+ "0": {
5
+ "content": ">>TITLE<<",
6
+ "lstrip": false,
7
+ "normalized": false,
8
+ "rstrip": false,
9
+ "single_word": false,
10
+ "special": true
11
+ },
12
+ "1": {
13
+ "content": ">>ABSTRACT<<",
14
+ "lstrip": false,
15
+ "normalized": false,
16
+ "rstrip": false,
17
+ "single_word": false,
18
+ "special": true
19
+ },
20
+ "2": {
21
+ "content": ">>INTRODUCTION<<",
22
+ "lstrip": false,
23
+ "normalized": false,
24
+ "rstrip": false,
25
+ "single_word": false,
26
+ "special": true
27
+ },
28
+ "3": {
29
+ "content": ">>SUMMARY<<",
30
+ "lstrip": false,
31
+ "normalized": false,
32
+ "rstrip": false,
33
+ "single_word": false,
34
+ "special": true
35
+ },
36
+ "4": {
37
+ "content": ">>COMMENT<<",
38
+ "lstrip": false,
39
+ "normalized": false,
40
+ "rstrip": false,
41
+ "single_word": false,
42
+ "special": true
43
+ },
44
+ "5": {
45
+ "content": ">>ANSWER<<",
46
+ "lstrip": false,
47
+ "normalized": false,
48
+ "rstrip": false,
49
+ "single_word": false,
50
+ "special": true
51
+ },
52
+ "6": {
53
+ "content": ">>QUESTION<<",
54
+ "lstrip": false,
55
+ "normalized": false,
56
+ "rstrip": false,
57
+ "single_word": false,
58
+ "special": true
59
+ },
60
+ "7": {
61
+ "content": ">>DOMAIN<<",
62
+ "lstrip": false,
63
+ "normalized": false,
64
+ "rstrip": false,
65
+ "single_word": false,
66
+ "special": true
67
+ },
68
+ "8": {
69
+ "content": ">>PREFIX<<",
70
+ "lstrip": false,
71
+ "normalized": false,
72
+ "rstrip": false,
73
+ "single_word": false,
74
+ "special": true
75
+ },
76
+ "9": {
77
+ "content": ">>SUFFIX<<",
78
+ "lstrip": false,
79
+ "normalized": false,
80
+ "rstrip": false,
81
+ "single_word": false,
82
+ "special": true
83
+ },
84
+ "10": {
85
+ "content": ">>MIDDLE<<",
86
+ "lstrip": false,
87
+ "normalized": false,
88
+ "rstrip": false,
89
+ "single_word": false,
90
+ "special": true
91
+ },
92
+ "11": {
93
+ "content": "<|endoftext|>",
94
+ "lstrip": false,
95
+ "normalized": false,
96
+ "rstrip": false,
97
+ "single_word": false,
98
+ "special": true
99
+ },
100
+ "500": {
101
+ "content": ">>",
102
+ "lstrip": false,
103
+ "normalized": false,
104
+ "rstrip": false,
105
+ "single_word": false,
106
+ "special": true
107
+ }
108
+ },
109
+ "additional_special_tokens": [
110
+ ">>TITLE<<",
111
+ ">>ABSTRACT<<",
112
+ ">>INTRODUCTION<<",
113
+ ">>SUMMARY<<",
114
+ ">>COMMENT<<",
115
+ ">>ANSWER<<",
116
+ ">>QUESTION<<",
117
+ ">>DOMAIN<<",
118
+ ">>PREFIX<<",
119
+ ">>SUFFIX<<",
120
+ ">>MIDDLE<<"
121
+ ],
122
+ "bos_token": ">>",
123
+ "chat_template": "{% for message in messages %}\n{% if message['role'] == 'user' %}\n{{ 'User: \n' + message['content'] }}\n{% elif message['role'] == 'system' %}\n{{ 'System: ' + message['content'] }}\n{% elif message['role'] == 'assistant' %}\n{{ 'Falcon:\n' + message['content']}}\n{% endif %}\n{% if loop.last and add_generation_prompt %}\n{{ 'Falcon:' }}\n{% endif %}\n{% endfor %}",
124
+ "clean_up_tokenization_spaces": true,
125
+ "device_map": "cuda:2",
126
+ "eos_token": "<|endoftext|>",
127
+ "model_input_names": [
128
+ "input_ids",
129
+ "attention_mask"
130
+ ],
131
+ "model_max_length": 1000000000000000019884624838656,
132
+ "pad_token": "<|endoftext|>",
133
+ "padding_side": "left",
134
+ "tokenizer_class": "PreTrainedTokenizerFast"
135
+ }