Upload folder using huggingface_hub
Browse files- README.md +375 -3
- added_tokens.json +28 -0
- config.json +42 -0
- configuration_llama_enc.py +198 -0
- model.safetensors +3 -0
- modeling_llama_enc.py +1307 -0
- special_tokens_map.json +72 -0
- tokenization_utf8_like_byte.py +271 -0
- tokenizer_config.json +304 -0
README.md
CHANGED
|
@@ -1,3 +1,375 @@
|
|
| 1 |
-
---
|
| 2 |
-
license: apache-2.0
|
| 3 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
license: apache-2.0
|
| 3 |
+
language:
|
| 4 |
+
- ja
|
| 5 |
+
---
|
| 6 |
+
|
| 7 |
+
(English part follows Japanese one.)
|
| 8 |
+
|
| 9 |
+
# byBERT-JP 100M
|
| 10 |
+
|
| 11 |
+
バイト単位のtokenizerを採用して,日本語 [BERT](https://aclanthology.org/N19-1423/) モデルです。
|
| 12 |
+
|
| 13 |
+
## 利用方法
|
| 14 |
+
[transformers version 4.56.1](https://github.com/huggingface/transformers/releases/tag/v4.56.1) において、動作確認をしています。
|
| 15 |
+
|
| 16 |
+
```python
|
| 17 |
+
import argparse
|
| 18 |
+
|
| 19 |
+
import torch
|
| 20 |
+
from transformers import AutoModelForMaskedLM, AutoTokenizer
|
| 21 |
+
|
| 22 |
+
MASK_PLACEHOLDER = "<mask>"
|
| 23 |
+
SAMPLE_INPUT_TEXTS = [
|
| 24 |
+
f"東北大学は宮城県{MASK_PLACEHOLDER * 6}市にある大学です。", # 6 bytes mask
|
| 25 |
+
f"日本一高い山は{MASK_PLACEHOLDER * 9}です。", # 9 bytes mask
|
| 26 |
+
]
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def main(args):
|
| 30 |
+
torch.manual_seed(args.seed)
|
| 31 |
+
device = torch.device("cuda")
|
| 32 |
+
|
| 33 |
+
tokenizer = AutoTokenizer.from_pretrained(
|
| 34 |
+
args.model_name_or_path,
|
| 35 |
+
trust_remote_code=True,
|
| 36 |
+
)
|
| 37 |
+
model = AutoModelForMaskedLM.from_pretrained(
|
| 38 |
+
args.model_name_or_path,
|
| 39 |
+
dtype=torch.bfloat16,
|
| 40 |
+
trust_remote_code=True,
|
| 41 |
+
)
|
| 42 |
+
model.to(device)
|
| 43 |
+
model.eval()
|
| 44 |
+
|
| 45 |
+
input_texts = [
|
| 46 |
+
s.replace(MASK_PLACEHOLDER, tokenizer.mask_token)
|
| 47 |
+
for s in SAMPLE_INPUT_TEXTS
|
| 48 |
+
]
|
| 49 |
+
batch = tokenizer(input_texts, return_tensors="pt", padding="longest")
|
| 50 |
+
|
| 51 |
+
batch = batch.to(device)
|
| 52 |
+
outputs = model(**batch)
|
| 53 |
+
decoded_ids = torch.argmax(outputs.logits, dim=-1)
|
| 54 |
+
is_pad = batch.input_ids == tokenizer.pad_token_id
|
| 55 |
+
decoded_ids[is_pad] = tokenizer.pad_token_id
|
| 56 |
+
decoded_texts = tokenizer.batch_decode(decoded_ids, skip_special_tokens=False)
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
for input_ids, decoded_text in zip(batch.input_ids, decoded_texts):
|
| 60 |
+
input_text = tokenizer.decode(input_ids, skip_special_tokens=False)
|
| 61 |
+
print("===")
|
| 62 |
+
print(f"Input: {input_text}")
|
| 63 |
+
print(f"Decoded: {decoded_text}")
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
if __name__ == "__main__":
|
| 67 |
+
parser = argparse.ArgumentParser(allow_abbrev=False)
|
| 68 |
+
parser.add_argument(
|
| 69 |
+
"--model_name_or_path",
|
| 70 |
+
"-m",
|
| 71 |
+
type=str,
|
| 72 |
+
default="tohoku-nlp/bybert-jp-next-100m",
|
| 73 |
+
help="Path to the model or model identifier from huggingface.co/models."
|
| 74 |
+
)
|
| 75 |
+
parser.add_argument("--seed", "-s", type=int, help="Random seed", default=42)
|
| 76 |
+
args = parser.parse_args()
|
| 77 |
+
main(args)
|
| 78 |
+
```
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
## モデルアーキテクチャ
|
| 82 |
+
|
| 83 |
+
[Llama](https://arxiv.org/abs/2302.13971) アーキテクチャをベースとし、Causal Attention Mask を取り除くことで、Encoder 型言語モデルとして利用しています。
|
| 84 |
+
具体的には、以下のモジュールを採用しています。
|
| 85 |
+
|
| 86 |
+
- [SwiGLU](https://arxiv.org/abs/2002.05202)
|
| 87 |
+
- [Rotary Positional Embeddings (RoPE)](https://arxiv.org/abs/2104.09864)
|
| 88 |
+
- [Grouped Query Attention (GQA)](https://aclanthology.org/2023.emnlp-main.298/)
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
## 学習データ
|
| 92 |
+
|
| 93 |
+
[llm-jp-corpus-v3](https://gitlab.llm-jp.nii.ac.jp/datasets/llm-jp-corpus-v3) の日本語コーパスのサブセット (ja\_cc, ja\_warp\_html, ja\_warp\_pdf, ja\_wiki, kaken) を使用しました。
|
| 94 |
+
また、学習時には Whole Word Masking を実施しています。
|
| 95 |
+
Whole Word Masking 単語分割器には、[vibrato](https://github.com/daac-tools/vibrato) を利用しました。
|
| 96 |
+
辞書は [bccwj-suw+unidic-cwj-3_1_1](https://github.com/daac-tools/vibrato/releases#:~:text=Compact%2Ddual-,bccwj%2Dsuw%2Bunidic%2Dcwj%2D3_1_1,-618%20MB) を用いています。
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
## 学習時の設定
|
| 100 |
+
|
| 101 |
+
モデルの重みを初期化した Llama アーキテクチャベースの Encoder モデルを from scratch で学習させています。
|
| 102 |
+
各モデルの学習設定は以下の通りです。
|
| 103 |
+
|
| 104 |
+
| | Params. | Tokens | Steps | Batch Size (tokens) |
|
| 105 |
+
| --- | --- | --- | --- | --- |
|
| 106 |
+
| tohoku-nlp/bybert-jp-100m | 107 M | 623 B | 198,000 | 3,145,728 |
|
| 107 |
+
| tohoku-nlp/bybert-jp-200m | 205 M | 637 B | 270,000 | 2,359,296 |
|
| 108 |
+
| tohoku-nlp/bybert-jp-400m | 397 M | 1.23 T | 308,000 | 3,981,312 |
|
| 109 |
+
| tohoku-nlp/bybert-jp-next-100m | 114 M | 2.76 T | 330,000 | 8,388,608 |
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
学習には、Masked Language Modeling (MLM) のみ実施し、Next Sentence Prediction (NSP) は実施していません。
|
| 113 |
+
また,tohoku-nlp/bybert-jp-next-100mでは
|
| 114 |
+
|
| 115 |
+
- 学習データ量を2.85T tokensに増やす
|
| 116 |
+
- unicodeのencodingに独自形式を採用
|
| 117 |
+
- マスク率を50%で学習.その後30%に減少
|
| 118 |
+
- QKVの線形変換にバイアス項を追加
|
| 119 |
+
- batch sizeのwarmupを導入
|
| 120 |
+
|
| 121 |
+
により,小規模モデルながら比較的高い性能を達成しています.
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
### 学習設定の詳細
|
| 125 |
+
|
| 126 |
+
| | bybert-jp-100,200,400m | bybert-jp-next-100m |
|
| 127 |
+
| ---- | ---- | ---- |
|
| 128 |
+
| Max Learning Rate | 1.0E-3 | 1.0E-3 |
|
| 129 |
+
| Min Learning Rate | 1.0E-6 | 1.0E-6 |
|
| 130 |
+
| Learning Rate Warmup Steps | 2,000 | 2,000 |
|
| 131 |
+
| Scheduler | cosine | cosine |
|
| 132 |
+
| Optimizer | AdamW | AdamW |
|
| 133 |
+
| Optimizer Config | beta_1 = 0.9, beta_2 = 0.999, eps = 1.0E-8 | beta_1 = 0.9, beta_2 = 0.999, eps = 1.0E-8 |
|
| 134 |
+
| Weight Decay | 0.01 | 0.01 |
|
| 135 |
+
| Gradient Clipping | 1.0 | 1.0 |
|
| 136 |
+
| Sequence Length | 3,072 | 4,096 |
|
| 137 |
+
| MLM Probability | 0.3 | 0.5 -> 0.3 |
|
| 138 |
+
| Replace Masked-token Probability | 0.8 | 0.8 |
|
| 139 |
+
| Replace Random-token Probability | 0.1 | 0.1 |
|
| 140 |
+
|
| 141 |
+
学習には[Megatron-LM](https://arxiv.org/abs/1909.08053)をベースに,独自の変更を加えたコードベースを使用しています。
|
| 142 |
+
|
| 143 |
+
## 評価
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
評価指標として、単語のマスクされた単語の予測正解率を用いた。
|
| 147 |
+
実験設定の詳細は[工藤 et al. (2025)](https://www.anlp.jp/proceedings/annual_meeting/2025/pdf_dir/Q8-5.pdf) を参照してください。
|
| 148 |
+
評価結果は以下の通りです。
|
| 149 |
+
|
| 150 |
+
| | ichikara | wiki |
|
| 151 |
+
|--------------------------------|----------|------|
|
| 152 |
+
| tohoku-nlp/bybert-jp-100m | 58.0 | 26.3 |
|
| 153 |
+
| tohoku-nlp/bybert-jp-200m | 60.5 | 33.0 |
|
| 154 |
+
| tohoku-nlp/bybert-jp-400m | 67.4 | 38.5 |
|
| 155 |
+
| tohoku-nlp/bybert-jp-next-100m | 63.4 | 40.5 |
|
| 156 |
+
|
| 157 |
+
その他,
|
| 158 |
+
- モデルアーキテクチャ探索
|
| 159 |
+
- ハイパーパラメータ探索
|
| 160 |
+
- 内部機序等のパフォーマンス以外の側面からの分析
|
| 161 |
+
についても[工藤 et al. (2025)](https://www.anlp.jp/proceedings/annual_meeting/2025/pdf_dir/Q8-5.pdf) を参照してください。
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
## ライセンス
|
| 166 |
+
|
| 167 |
+
このモデルは Apache License 2.0 の下で配布しています。
|
| 168 |
+
|
| 169 |
+
# 免責事項
|
| 170 |
+
|
| 171 |
+
本モデルの作者は本モデルを作成するにあたって、その内容、機能等について細心の注意を払っておりますが、モデルの出力が正確であるかどうか、安全なものであるか等について保証をするものではなく、何らの責任を負うものではありません。
|
| 172 |
+
本モデルの利用により、万一、利用者に何らかの不都合や損害が発生したとしても、モデルやデータセットの作者や作者の所属組織は何らの責任を負うものではありません。
|
| 173 |
+
|
| 174 |
+
## 謝辞
|
| 175 |
+
|
| 176 |
+
このモデルの学習にあたり様々な面でご協力いただきました [Tohoku NLP Group](https://www.nlp.ecei.tohoku.ac.jp/) の皆様に感謝いたします。
|
| 177 |
+
|
| 178 |
+
## 作成者
|
| 179 |
+
- [Keito Kudo](https://x.com/k8kudo)
|
| 180 |
+
- [Go Kamoda](https://x.com/go2oo2)
|
| 181 |
+
- [Daiki Shiono](https://x.com/onely7_deep)
|
| 182 |
+
- [Jun Suzuki](https://x.com/drJunSuzuki)
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
<br>
|
| 186 |
+
<br>
|
| 187 |
+
<br>
|
| 188 |
+
<br>
|
| 189 |
+
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
---
|
| 193 |
+
license: apache-2.0
|
| 194 |
+
language:
|
| 195 |
+
- ja
|
| 196 |
+
---
|
| 197 |
+
|
| 198 |
+
(English part follows Japanese one.)
|
| 199 |
+
|
| 200 |
+
# byBERT-JP 100M
|
| 201 |
+
|
| 202 |
+
A Japanese [BERT](https://aclanthology.org/N19-1423/) model that adopts a byte-level tokenizer.
|
| 203 |
+
|
| 204 |
+
## Usage
|
| 205 |
+
|
| 206 |
+
```python
|
| 207 |
+
import argparse
|
| 208 |
+
|
| 209 |
+
import torch
|
| 210 |
+
from transformers import AutoModelForMaskedLM, AutoTokenizer
|
| 211 |
+
|
| 212 |
+
MASK_PLACEHOLDER = "<mask>"
|
| 213 |
+
SAMPLE_INPUT_TEXTS = [
|
| 214 |
+
f"東北大学は宮城県{MASK_PLACEHOLDER * 6}市にある大学です。", # 6 bytes mask
|
| 215 |
+
f"日本一高い山は{MASK_PLACEHOLDER * 9}です。", # 9 bytes mask
|
| 216 |
+
]
|
| 217 |
+
|
| 218 |
+
|
| 219 |
+
def main(args):
|
| 220 |
+
torch.manual_seed(args.seed)
|
| 221 |
+
device = torch.device("cuda")
|
| 222 |
+
|
| 223 |
+
tokenizer = AutoTokenizer.from_pretrained(
|
| 224 |
+
args.model_name_or_path,
|
| 225 |
+
trust_remote_code=True,
|
| 226 |
+
)
|
| 227 |
+
model = AutoModelForMaskedLM.from_pretrained(
|
| 228 |
+
args.model_name_or_path,
|
| 229 |
+
dtype=torch.bfloat16,
|
| 230 |
+
trust_remote_code=True,
|
| 231 |
+
)
|
| 232 |
+
model.to(device)
|
| 233 |
+
model.eval()
|
| 234 |
+
|
| 235 |
+
input_texts = [
|
| 236 |
+
s.replace(MASK_PLACEHOLDER, tokenizer.mask_token)
|
| 237 |
+
for s in SAMPLE_INPUT_TEXTS
|
| 238 |
+
]
|
| 239 |
+
batch = tokenizer(input_texts, return_tensors="pt", padding="longest")
|
| 240 |
+
|
| 241 |
+
batch = batch.to(device)
|
| 242 |
+
outputs = model(**batch)
|
| 243 |
+
decoded_ids = torch.argmax(outputs.logits, dim=-1)
|
| 244 |
+
is_pad = batch.input_ids == tokenizer.pad_token_id
|
| 245 |
+
decoded_ids[is_pad] = tokenizer.pad_token_id
|
| 246 |
+
decoded_texts = tokenizer.batch_decode(decoded_ids, skip_special_tokens=False)
|
| 247 |
+
|
| 248 |
+
|
| 249 |
+
for input_ids, decoded_text in zip(batch.input_ids, decoded_texts):
|
| 250 |
+
input_text = tokenizer.decode(input_ids, skip_special_tokens=False)
|
| 251 |
+
print("===")
|
| 252 |
+
print(f"Input: {input_text}")
|
| 253 |
+
print(f"Decoded: {decoded_text}")
|
| 254 |
+
|
| 255 |
+
|
| 256 |
+
if __name__ == "__main__":
|
| 257 |
+
parser = argparse.ArgumentParser(allow_abbrev=False)
|
| 258 |
+
parser.add_argument(
|
| 259 |
+
"--model_name_or_path",
|
| 260 |
+
"-m",
|
| 261 |
+
type=str,
|
| 262 |
+
default="tohoku-nlp/bybert-jp-next-100m",
|
| 263 |
+
help="Path to the model or model identifier from huggingface.co/models."
|
| 264 |
+
)
|
| 265 |
+
parser.add_argument("--seed", "-s", type=int, help="Random seed", default=42)
|
| 266 |
+
args = parser.parse_args()
|
| 267 |
+
main(args)
|
| 268 |
+
```
|
| 269 |
+
|
| 270 |
+
We have confirmed operation with [transformers version 4.56.1](https://github.com/huggingface/transformers/releases/tag/v4.56.1).
|
| 271 |
+
|
| 272 |
+
|
| 273 |
+
## Model Architecture
|
| 274 |
+
|
| 275 |
+
Based on the [Llama](https://arxiv.org/abs/2302.13971) architecture, we use it as an Encoder-type language model by removing the Causal Attention Mask.
|
| 276 |
+
Specifically, we adopt the following modules:
|
| 277 |
+
|
| 278 |
+
- [SwiGLU](https://arxiv.org/abs/2002.05202)
|
| 279 |
+
- [Rotary Positional Embeddings (RoPE)](https://arxiv.org/abs/2104.09864)
|
| 280 |
+
- [Grouped Query Attention (GQA)](https://aclanthology.org/2023.emnlp-main.298/)
|
| 281 |
+
|
| 282 |
+
|
| 283 |
+
## Training Data
|
| 284 |
+
|
| 285 |
+
We used a subset of Japanese corpora (ja_cc, ja_warp_html, ja_warp_pdf, ja_wiki, kaken) from [llm-jp-corpus-v3](https://gitlab.llm-jp.nii.ac.jp/datasets/llm-jp-corpus-v3).
|
| 286 |
+
Additionally, we implemented Whole Word Masking during training.
|
| 287 |
+
For the Whole Word Masking word segmenter, we used [vibrato](https://github.com/daac-tools/vibrato).
|
| 288 |
+
We used the [bccwj-suw+unidic-cwj-3_1_1](https://github.com/daac-tools/vibrato/releases#:~:text=Compact%2Ddual-,bccwj%2Dsuw%2Bunidic%2Dcwj%2D3_1_1,-618%20MB) dictionary.
|
| 289 |
+
|
| 290 |
+
|
| 291 |
+
## Training Configuration
|
| 292 |
+
|
| 293 |
+
We trained the Llama architecture-based Encoder model with initialized weights from scratch.
|
| 294 |
+
The training configuration for each model is as follows:
|
| 295 |
+
|
| 296 |
+
| | Params. | Tokens | Steps | Batch Size (tokens) |
|
| 297 |
+
| --- | --- | --- | --- | --- |
|
| 298 |
+
| tohoku-nlp/bybert-jp-100m | 107 M | 623 B | 198,000 | 3,145,728 |
|
| 299 |
+
| tohoku-nlp/bybert-jp-200m | 205 M | 637 B | 270,000 | 2,359,296 |
|
| 300 |
+
| tohoku-nlp/bybert-jp-400m | 397 M | 1.23 T | 308,000 | 3,981,312 |
|
| 301 |
+
| tohoku-nlp/bybert-jp-next-100m | 114 M | 2.76 T | 330,000 | 8,388,608 |
|
| 302 |
+
|
| 303 |
+
|
| 304 |
+
Training was performed using only Masked Language Modeling (MLM), without Next Sentence Prediction (NSP).
|
| 305 |
+
Additionally, for tohoku-nlp/bybert-jp-next-100m:
|
| 306 |
+
|
| 307 |
+
- Increased training data volume to 2.85T tokens
|
| 308 |
+
- Adopted proprietary format for unicode encoding
|
| 309 |
+
- Trained with 50% mask rate, then reduced to 30%
|
| 310 |
+
- Added bias term to QKV linear transformations
|
| 311 |
+
- Introduced batch size warmup
|
| 312 |
+
|
| 313 |
+
Through these improvements, we achieved relatively high performance despite being a small-scale model.
|
| 314 |
+
|
| 315 |
+
|
| 316 |
+
### Detailed Training Configuration
|
| 317 |
+
|
| 318 |
+
| | bybert-jp-100,200,400m | bybert-jp-next-100m |
|
| 319 |
+
| ---- | ---- | ---- |
|
| 320 |
+
| Max Learning Rate | 1.0E-3 | 1.0E-3 |
|
| 321 |
+
| Min Learning Rate | 1.0E-6 | 1.0E-6 |
|
| 322 |
+
| Learning Rate Warmup Steps | 2,000 | 2,000 |
|
| 323 |
+
| Scheduler | cosine | cosine |
|
| 324 |
+
| Optimizer | AdamW | AdamW |
|
| 325 |
+
| Optimizer Config | beta_1 = 0.9, beta_2 = 0.999, eps = 1.0E-8 | beta_1 = 0.9, beta_2 = 0.999, eps = 1.0E-8 |
|
| 326 |
+
| Weight Decay | 0.01 | 0.01 |
|
| 327 |
+
| Gradient Clipping | 1.0 | 1.0 |
|
| 328 |
+
| Sequence Length | 3,072 | 4,096 |
|
| 329 |
+
| MLM Probability | 0.3 | 0.5 -> 0.3 |
|
| 330 |
+
| Replace Masked-token Probability | 0.8 | 0.8 |
|
| 331 |
+
| Replace Random-token Probability | 0.1 | 0.1 |
|
| 332 |
+
|
| 333 |
+
For training, we use a codebase based on [Megatron-LM](https://arxiv.org/abs/1909.08053) with our own modifications.
|
| 334 |
+
|
| 335 |
+
## Evaluation
|
| 336 |
+
|
| 337 |
+
|
| 338 |
+
We used the prediction accuracy of masked words as the evaluation metric.
|
| 339 |
+
For details of the experimental setup, please refer to [Kudo et al. (2025)](https://www.anlp.jp/proceedings/annual_meeting/2025/pdf_dir/Q8-5.pdf).
|
| 340 |
+
The evaluation results are as follows:
|
| 341 |
+
|
| 342 |
+
| | ichikara | wiki |
|
| 343 |
+
|--------------------------------|----------|------|
|
| 344 |
+
| tohoku-nlp/bybert-jp-100m | 58.0 | 26.3 |
|
| 345 |
+
| tohoku-nlp/bybert-jp-200m | 60.5 | 33.0 |
|
| 346 |
+
| tohoku-nlp/bybert-jp-400m | 67.4 | 38.5 |
|
| 347 |
+
| tohoku-nlp/bybert-jp-next-100m | 63.4 | 40.5 |
|
| 348 |
+
|
| 349 |
+
For other aspects including:
|
| 350 |
+
- Model architecture exploration
|
| 351 |
+
- Hyperparameter exploration
|
| 352 |
+
- Analysis from non-performance perspectives such as internal mechanisms
|
| 353 |
+
|
| 354 |
+
Please refer to [Kudo et al. (2025)](https://www.anlp.jp/proceedings/annual_meeting/2025/pdf_dir/Q8-5.pdf).
|
| 355 |
+
|
| 356 |
+
|
| 357 |
+
|
| 358 |
+
## License
|
| 359 |
+
|
| 360 |
+
This model is distributed under the Apache License 2.0.
|
| 361 |
+
|
| 362 |
+
# Disclaimer
|
| 363 |
+
|
| 364 |
+
While the authors of this model have paid careful attention to its content and functionality in creating this model, they do not warrant that the model's output is accurate or safe, and assume no responsibility whatsoever.
|
| 365 |
+
The authors of the model and dataset and their affiliated organizations assume no responsibility for any inconvenience or damage that may occur to users through the use of this model.
|
| 366 |
+
|
| 367 |
+
## Acknowledgments
|
| 368 |
+
|
| 369 |
+
We would like to thank everyone at [Tohoku NLP Group](https://www.nlp.ecei.tohoku.ac.jp/) for their cooperation in various aspects of training this model.
|
| 370 |
+
|
| 371 |
+
## Creators
|
| 372 |
+
- [Keito Kudo](https://x.com/k8kudo)
|
| 373 |
+
- [Go Kamoda](https://x.com/go2oo2)
|
| 374 |
+
- [Daiki Shiono](https://x.com/onely7_deep)
|
| 375 |
+
- [Jun Suzuki](https://x.com/drJunSuzuki)
|
added_tokens.json
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"<extra_id_0>": 262,
|
| 3 |
+
"<extra_id_10>": 272,
|
| 4 |
+
"<extra_id_11>": 273,
|
| 5 |
+
"<extra_id_12>": 274,
|
| 6 |
+
"<extra_id_13>": 275,
|
| 7 |
+
"<extra_id_14>": 276,
|
| 8 |
+
"<extra_id_15>": 277,
|
| 9 |
+
"<extra_id_16>": 278,
|
| 10 |
+
"<extra_id_17>": 279,
|
| 11 |
+
"<extra_id_18>": 280,
|
| 12 |
+
"<extra_id_19>": 281,
|
| 13 |
+
"<extra_id_1>": 263,
|
| 14 |
+
"<extra_id_20>": 282,
|
| 15 |
+
"<extra_id_21>": 283,
|
| 16 |
+
"<extra_id_22>": 284,
|
| 17 |
+
"<extra_id_23>": 285,
|
| 18 |
+
"<extra_id_24>": 286,
|
| 19 |
+
"<extra_id_25>": 287,
|
| 20 |
+
"<extra_id_2>": 264,
|
| 21 |
+
"<extra_id_3>": 265,
|
| 22 |
+
"<extra_id_4>": 266,
|
| 23 |
+
"<extra_id_5>": 267,
|
| 24 |
+
"<extra_id_6>": 268,
|
| 25 |
+
"<extra_id_7>": 269,
|
| 26 |
+
"<extra_id_8>": 270,
|
| 27 |
+
"<extra_id_9>": 271
|
| 28 |
+
}
|
config.json
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"_name_or_path": "None",
|
| 3 |
+
"architectures": [
|
| 4 |
+
"LlamaEncForMaskedLM"
|
| 5 |
+
],
|
| 6 |
+
"attention_bias": true,
|
| 7 |
+
"attention_dropout": 0.0,
|
| 8 |
+
"auto_map": {
|
| 9 |
+
"AutoConfig": "configuration_llama_enc.LlamaEncConfig",
|
| 10 |
+
"AutoModel": "modeling_llama_enc.LlamaEncModel",
|
| 11 |
+
"AutoModelForMaskedLM": "modeling_llama_enc.LlamaEncForMaskedLM",
|
| 12 |
+
"AutoModelForQuestionAnswering": "modeling_llama_enc.LlamaEncForQuestionAnswering",
|
| 13 |
+
"AutoModelForSequenceClassification": "modeling_llama_enc.LlamaEncForSequenceClassification",
|
| 14 |
+
"AutoModelForTokenClassification": "modeling_llama_enc.LlamaEncForTokenClassification"
|
| 15 |
+
},
|
| 16 |
+
"bos_token_id": 2,
|
| 17 |
+
"eos_token_id": 1,
|
| 18 |
+
"force_disable_attetion_output_bias": true,
|
| 19 |
+
"hidden_act": "silu",
|
| 20 |
+
"hidden_size": 768,
|
| 21 |
+
"initializer_range": 0.02,
|
| 22 |
+
"intermediate_size": 3072,
|
| 23 |
+
"label_smoothing": 0.0,
|
| 24 |
+
"max_position_embeddings": 4096,
|
| 25 |
+
"mlp_bias": false,
|
| 26 |
+
"model_type": "llama_enc",
|
| 27 |
+
"num_attention_heads": 16,
|
| 28 |
+
"num_hidden_layers": 12,
|
| 29 |
+
"num_key_value_heads": 16,
|
| 30 |
+
"pretraining_tp": 1,
|
| 31 |
+
"rms_norm_eps": 1e-06,
|
| 32 |
+
"rope_scaling": null,
|
| 33 |
+
"rope_theta": 10000.0,
|
| 34 |
+
"tie_word_embeddings": false,
|
| 35 |
+
"torch_dtype": "float32",
|
| 36 |
+
"transformers_version": "4.41.2",
|
| 37 |
+
"trust_remote_code": true,
|
| 38 |
+
"use_cache": true,
|
| 39 |
+
"vocab_size": 288,
|
| 40 |
+
"window_size_left": -1,
|
| 41 |
+
"window_size_right": -1
|
| 42 |
+
}
|
configuration_llama_enc.py
ADDED
|
@@ -0,0 +1,198 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
|
| 5 |
+
# and OPT implementations in this library. It has been modified from its
|
| 6 |
+
# original forms to accommodate minor architectural differences compared
|
| 7 |
+
# to GPT-NeoX and OPT used by the Meta AI team that trained the model.
|
| 8 |
+
#
|
| 9 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 10 |
+
# you may not use this file except in compliance with the License.
|
| 11 |
+
# You may obtain a copy of the License at
|
| 12 |
+
#
|
| 13 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 14 |
+
#
|
| 15 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 16 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 17 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 18 |
+
# See the License for the specific language governing permissions and
|
| 19 |
+
# limitations under the License.
|
| 20 |
+
""" LLaMA model configuration"""
|
| 21 |
+
|
| 22 |
+
from transformers.configuration_utils import PretrainedConfig
|
| 23 |
+
from transformers.utils import logging
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
logger = logging.get_logger(__name__)
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
class LlamaEncConfig(PretrainedConfig):
|
| 30 |
+
r"""
|
| 31 |
+
This is the configuration class to store the configuration of a [`LlamaModel`]. It is used to instantiate an LLaMA
|
| 32 |
+
model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
|
| 33 |
+
defaults will yield a similar configuration to that of the LLaMA-7B.
|
| 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 32000):
|
| 41 |
+
Vocabulary size of the LLaMA model. Defines the number of different tokens that can be represented by the
|
| 42 |
+
`inputs_ids` passed when calling [`LlamaModel`]
|
| 43 |
+
hidden_size (`int`, *optional*, defaults to 4096):
|
| 44 |
+
Dimension of the hidden representations.
|
| 45 |
+
intermediate_size (`int`, *optional*, defaults to 11008):
|
| 46 |
+
Dimension of the MLP representations.
|
| 47 |
+
num_hidden_layers (`int`, *optional*, defaults to 32):
|
| 48 |
+
Number of hidden layers in the Transformer decoder.
|
| 49 |
+
num_attention_heads (`int`, *optional*, defaults to 32):
|
| 50 |
+
Number of attention heads for each attention layer in the Transformer decoder.
|
| 51 |
+
num_key_value_heads (`int`, *optional*):
|
| 52 |
+
This is the number of key_value heads that should be used to implement Grouped Query Attention. If
|
| 53 |
+
`num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
|
| 54 |
+
`num_key_value_heads=1 the model will use Multi Query Attention (MQA) otherwise GQA is used. When
|
| 55 |
+
converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
|
| 56 |
+
by meanpooling all the original heads within that group. For more details checkout [this
|
| 57 |
+
paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to
|
| 58 |
+
`num_attention_heads`.
|
| 59 |
+
hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
|
| 60 |
+
The non-linear activation function (function or string) in the decoder.
|
| 61 |
+
max_position_embeddings (`int`, *optional*, defaults to 2048):
|
| 62 |
+
The maximum sequence length that this model might ever be used with. Llama 1 supports up to 2048 tokens,
|
| 63 |
+
Llama 2 up to 4096, CodeLlama up to 16384.
|
| 64 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
| 65 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
| 66 |
+
rms_norm_eps (`float`, *optional*, defaults to 1e-06):
|
| 67 |
+
The epsilon used by the rms normalization layers.
|
| 68 |
+
use_cache (`bool`, *optional*, defaults to `True`):
|
| 69 |
+
Whether or not the model should return the last key/values attentions (not used by all models). Only
|
| 70 |
+
relevant if `config.is_decoder=True`.
|
| 71 |
+
pad_token_id (`int`, *optional*):
|
| 72 |
+
Padding token id.
|
| 73 |
+
bos_token_id (`int`, *optional*, defaults to 1):
|
| 74 |
+
Beginning of stream token id.
|
| 75 |
+
eos_token_id (`int`, *optional*, defaults to 2):
|
| 76 |
+
End of stream token id.
|
| 77 |
+
pretraining_tp (`int`, *optional*, defaults to 1):
|
| 78 |
+
Experimental feature. Tensor parallelism rank used during pretraining. Please refer to [this
|
| 79 |
+
document](https://huggingface.co/docs/transformers/main/perf_train_gpu_many#tensor-parallelism) to understand more about it. This value is
|
| 80 |
+
necessary to ensure exact reproducibility of the pretraining results. Please refer to [this
|
| 81 |
+
issue](https://github.com/pytorch/pytorch/issues/76232).
|
| 82 |
+
tie_word_embeddings (`bool`, *optional*, defaults to `False`):
|
| 83 |
+
Whether to tie weight embeddings
|
| 84 |
+
rope_theta (`float`, *optional*, defaults to 10000.0):
|
| 85 |
+
The base period of the RoPE embeddings.
|
| 86 |
+
rope_scaling (`Dict`, *optional*):
|
| 87 |
+
Dictionary containing the scaling configuration for the RoPE embeddings. Currently supports two scaling
|
| 88 |
+
strategies: linear and dynamic. Their scaling factor must be a float greater than 1. The expected format is
|
| 89 |
+
`{"type": strategy name, "factor": scaling factor}`. When using this flag, don't update
|
| 90 |
+
`max_position_embeddings` to the expected new maximum. See the following thread for more information on how
|
| 91 |
+
these scaling strategies behave:
|
| 92 |
+
https://www.reddit.com/r/LocalLLaMA/comments/14mrgpr/dynamically_scaled_rope_further_increases/. This is an
|
| 93 |
+
experimental feature, subject to breaking API changes in future versions.
|
| 94 |
+
attention_bias (`bool`, *optional*, defaults to `False`):
|
| 95 |
+
Whether to use a bias in the query, key, value and output projection layers during self-attention.
|
| 96 |
+
attention_dropout (`float`, *optional*, defaults to 0.0):
|
| 97 |
+
The dropout ratio for the attention probabilities.
|
| 98 |
+
mlp_bias (`bool`, *optional*, defaults to `False`):
|
| 99 |
+
Whether to use a bias in up_proj, down_proj and gate_proj layers in the MLP layers.
|
| 100 |
+
|
| 101 |
+
```python
|
| 102 |
+
>>> from transformers import LlamaModel, LlamaConfig
|
| 103 |
+
|
| 104 |
+
>>> # Initializing a LLaMA llama-7b style configuration
|
| 105 |
+
>>> configuration = LlamaConfig()
|
| 106 |
+
|
| 107 |
+
>>> # Initializing a model from the llama-7b style configuration
|
| 108 |
+
>>> model = LlamaModel(configuration)
|
| 109 |
+
|
| 110 |
+
>>> # Accessing the model configuration
|
| 111 |
+
>>> configuration = model.config
|
| 112 |
+
```"""
|
| 113 |
+
model_type = "llama_enc"
|
| 114 |
+
keys_to_ignore_at_inference = ["past_key_values"]
|
| 115 |
+
|
| 116 |
+
def __init__(
|
| 117 |
+
self,
|
| 118 |
+
vocab_size=32000,
|
| 119 |
+
hidden_size=4096,
|
| 120 |
+
intermediate_size=11008,
|
| 121 |
+
num_hidden_layers=32,
|
| 122 |
+
num_attention_heads=32,
|
| 123 |
+
num_key_value_heads=None,
|
| 124 |
+
hidden_act="silu",
|
| 125 |
+
max_position_embeddings=2048,
|
| 126 |
+
initializer_range=0.02,
|
| 127 |
+
rms_norm_eps=1e-6,
|
| 128 |
+
use_cache=True,
|
| 129 |
+
pad_token_id=None,
|
| 130 |
+
bos_token_id=1,
|
| 131 |
+
eos_token_id=2,
|
| 132 |
+
pretraining_tp=1,
|
| 133 |
+
tie_word_embeddings=False,
|
| 134 |
+
rope_theta=10000.0,
|
| 135 |
+
rope_scaling=None,
|
| 136 |
+
attention_bias=False,
|
| 137 |
+
attention_dropout=0.0,
|
| 138 |
+
mlp_bias=False,
|
| 139 |
+
label_smoothing=0.0,
|
| 140 |
+
window_size_left=-1,
|
| 141 |
+
window_size_right=-1,
|
| 142 |
+
force_disable_attetion_output_bias=False,
|
| 143 |
+
**kwargs,
|
| 144 |
+
):
|
| 145 |
+
self.vocab_size = vocab_size
|
| 146 |
+
self.max_position_embeddings = max_position_embeddings
|
| 147 |
+
self.hidden_size = hidden_size
|
| 148 |
+
self.intermediate_size = intermediate_size
|
| 149 |
+
self.num_hidden_layers = num_hidden_layers
|
| 150 |
+
self.num_attention_heads = num_attention_heads
|
| 151 |
+
|
| 152 |
+
# for backward compatibility
|
| 153 |
+
if num_key_value_heads is None:
|
| 154 |
+
num_key_value_heads = num_attention_heads
|
| 155 |
+
|
| 156 |
+
self.num_key_value_heads = num_key_value_heads
|
| 157 |
+
self.hidden_act = hidden_act
|
| 158 |
+
self.initializer_range = initializer_range
|
| 159 |
+
self.rms_norm_eps = rms_norm_eps
|
| 160 |
+
self.pretraining_tp = pretraining_tp
|
| 161 |
+
self.use_cache = use_cache
|
| 162 |
+
self.rope_theta = rope_theta
|
| 163 |
+
self.rope_scaling = rope_scaling
|
| 164 |
+
self._rope_scaling_validation()
|
| 165 |
+
self.attention_bias = attention_bias
|
| 166 |
+
self.attention_dropout = attention_dropout
|
| 167 |
+
self.mlp_bias = mlp_bias
|
| 168 |
+
self.label_smoothing = label_smoothing
|
| 169 |
+
self.window_size_left = window_size_left
|
| 170 |
+
self.window_size_right = window_size_right
|
| 171 |
+
self.force_disable_attetion_output_bias = force_disable_attetion_output_bias
|
| 172 |
+
super().__init__(
|
| 173 |
+
pad_token_id=pad_token_id,
|
| 174 |
+
bos_token_id=bos_token_id,
|
| 175 |
+
eos_token_id=eos_token_id,
|
| 176 |
+
tie_word_embeddings=tie_word_embeddings,
|
| 177 |
+
**kwargs,
|
| 178 |
+
)
|
| 179 |
+
|
| 180 |
+
def _rope_scaling_validation(self):
|
| 181 |
+
"""
|
| 182 |
+
Validate the `rope_scaling` configuration.
|
| 183 |
+
"""
|
| 184 |
+
if self.rope_scaling is None:
|
| 185 |
+
return
|
| 186 |
+
|
| 187 |
+
if not isinstance(self.rope_scaling, dict) or len(self.rope_scaling) != 2:
|
| 188 |
+
raise ValueError(
|
| 189 |
+
"`rope_scaling` must be a dictionary with two fields, `type` and `factor`, " f"got {self.rope_scaling}"
|
| 190 |
+
)
|
| 191 |
+
rope_scaling_type = self.rope_scaling.get("type", None)
|
| 192 |
+
rope_scaling_factor = self.rope_scaling.get("factor", None)
|
| 193 |
+
if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]:
|
| 194 |
+
raise ValueError(
|
| 195 |
+
f"`rope_scaling`'s type field must be one of ['linear', 'dynamic'], got {rope_scaling_type}"
|
| 196 |
+
)
|
| 197 |
+
if rope_scaling_factor is None or not isinstance(rope_scaling_factor, float) or rope_scaling_factor <= 1.0:
|
| 198 |
+
raise ValueError(f"`rope_scaling`'s factor field must be a float > 1, got {rope_scaling_factor}")
|
model.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:ea3b7ccfe404cba474a613a92efbc9293e2340ba93eeb38998d8f323c71acacf
|
| 3 |
+
size 454957768
|
modeling_llama_enc.py
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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
|
| 5 |
+
# and OPT implementations in this library. It has been modified from its
|
| 6 |
+
# original forms to accommodate minor architectural differences compared
|
| 7 |
+
# to GPT-NeoX and OPT used by the Meta AI team that trained the model.
|
| 8 |
+
#
|
| 9 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 10 |
+
# you may not use this file except in compliance with the License.
|
| 11 |
+
# You may obtain a copy of the License at
|
| 12 |
+
#
|
| 13 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 14 |
+
#
|
| 15 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 16 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 17 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 18 |
+
# See the License for the specific language governing permissions and
|
| 19 |
+
# limitations under the License.
|
| 20 |
+
"""PyTorch LLaMA Encodr model."""
|
| 21 |
+
|
| 22 |
+
import math
|
| 23 |
+
from typing import List, Optional, Tuple, Union
|
| 24 |
+
|
| 25 |
+
import torch
|
| 26 |
+
import torch.nn.functional as F
|
| 27 |
+
import torch.utils.checkpoint
|
| 28 |
+
from torch import nn
|
| 29 |
+
from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
|
| 30 |
+
|
| 31 |
+
from transformers.activations import ACT2FN
|
| 32 |
+
from transformers.modeling_outputs import (
|
| 33 |
+
BaseModelOutputWithPast,
|
| 34 |
+
CausalLMOutputWithPast,
|
| 35 |
+
QuestionAnsweringModelOutput,
|
| 36 |
+
SequenceClassifierOutputWithPast,
|
| 37 |
+
)
|
| 38 |
+
from transformers.modeling_attn_mask_utils import _prepare_4d_attention_mask_for_sdpa
|
| 39 |
+
from transformers.modeling_utils import PreTrainedModel
|
| 40 |
+
from transformers.pytorch_utils import ALL_LAYERNORM_LAYERS
|
| 41 |
+
from transformers.utils import (
|
| 42 |
+
add_start_docstrings,
|
| 43 |
+
add_start_docstrings_to_model_forward,
|
| 44 |
+
is_flash_attn_2_available,
|
| 45 |
+
is_flash_attn_greater_or_equal_2_10,
|
| 46 |
+
logging,
|
| 47 |
+
replace_return_docstrings,
|
| 48 |
+
)
|
| 49 |
+
from .configuration_llama_enc import LlamaEncConfig
|
| 50 |
+
|
| 51 |
+
if is_flash_attn_2_available():
|
| 52 |
+
from flash_attn import flash_attn_func, flash_attn_varlen_func
|
| 53 |
+
from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
logger = logging.get_logger(__name__)
|
| 57 |
+
|
| 58 |
+
_CONFIG_FOR_DOC = "LlamaEncConfig"
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def _get_unpad_data(attention_mask):
|
| 62 |
+
seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
|
| 63 |
+
indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
|
| 64 |
+
max_seqlen_in_batch = seqlens_in_batch.max().item()
|
| 65 |
+
cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.int32), (1, 0))
|
| 66 |
+
return (
|
| 67 |
+
indices,
|
| 68 |
+
cu_seqlens,
|
| 69 |
+
max_seqlen_in_batch,
|
| 70 |
+
)
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
class LlamaEncRMSNorm(nn.Module):
|
| 74 |
+
def __init__(self, hidden_size, eps=1e-6):
|
| 75 |
+
"""
|
| 76 |
+
LlamaEncRMSNorm is equivalent to T5LayerNorm
|
| 77 |
+
"""
|
| 78 |
+
super().__init__()
|
| 79 |
+
self.weight = nn.Parameter(torch.ones(hidden_size))
|
| 80 |
+
self.variance_epsilon = eps
|
| 81 |
+
|
| 82 |
+
def forward(self, hidden_states):
|
| 83 |
+
input_dtype = hidden_states.dtype
|
| 84 |
+
hidden_states = hidden_states.to(torch.float32)
|
| 85 |
+
variance = hidden_states.pow(2).mean(-1, keepdim=True)
|
| 86 |
+
hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
|
| 87 |
+
return self.weight * hidden_states.to(input_dtype)
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
ALL_LAYERNORM_LAYERS.append(LlamaEncRMSNorm)
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
class LlamaEncRotaryEmbedding(nn.Module):
|
| 94 |
+
def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):
|
| 95 |
+
super().__init__()
|
| 96 |
+
self.scaling_factor = scaling_factor
|
| 97 |
+
self.dim = dim
|
| 98 |
+
self.max_position_embeddings = max_position_embeddings
|
| 99 |
+
self.base = base
|
| 100 |
+
inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2, dtype=torch.int64).float().to(device) / self.dim))
|
| 101 |
+
self.register_buffer("inv_freq", inv_freq, persistent=False)
|
| 102 |
+
# For BC we register cos and sin cached
|
| 103 |
+
self.max_seq_len_cached = max_position_embeddings
|
| 104 |
+
|
| 105 |
+
@torch.no_grad()
|
| 106 |
+
def forward(self, x, position_ids):
|
| 107 |
+
# x: [bs, num_attention_heads, seq_len, head_size]
|
| 108 |
+
inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
|
| 109 |
+
position_ids_expanded = position_ids[:, None, :].float()
|
| 110 |
+
# Force float32 since bfloat16 loses precision on long contexts
|
| 111 |
+
# See https://github.com/huggingface/transformers/pull/29285
|
| 112 |
+
device_type = x.device.type
|
| 113 |
+
device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu"
|
| 114 |
+
with torch.autocast(device_type=device_type, enabled=False):
|
| 115 |
+
freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
|
| 116 |
+
emb = torch.cat((freqs, freqs), dim=-1)
|
| 117 |
+
cos = emb.cos()
|
| 118 |
+
sin = emb.sin()
|
| 119 |
+
return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
class LlamaEncLinearScalingRotaryEmbedding(LlamaEncRotaryEmbedding):
|
| 123 |
+
"""LlamaEncRotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendev"""
|
| 124 |
+
|
| 125 |
+
def forward(self, x, position_ids):
|
| 126 |
+
# difference to the original RoPE: a scaling factor is aplied to the position ids
|
| 127 |
+
position_ids = position_ids.float() / self.scaling_factor
|
| 128 |
+
cos, sin = super().forward(x, position_ids)
|
| 129 |
+
return cos, sin
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
class LlamaEncDynamicNTKScalingRotaryEmbedding(LlamaEncRotaryEmbedding):
|
| 133 |
+
"""LlamaEncRotaryEmbedding extended with Dynamic NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozilla"""
|
| 134 |
+
|
| 135 |
+
def forward(self, x, position_ids):
|
| 136 |
+
# difference to the original RoPE: inv_freq is recomputed when the sequence length > original length
|
| 137 |
+
seq_len = torch.max(position_ids) + 1
|
| 138 |
+
if seq_len > self.max_position_embeddings:
|
| 139 |
+
base = self.base * (
|
| 140 |
+
(self.scaling_factor * seq_len / self.max_position_embeddings) - (self.scaling_factor - 1)
|
| 141 |
+
) ** (self.dim / (self.dim - 2))
|
| 142 |
+
inv_freq = 1.0 / (
|
| 143 |
+
base ** (torch.arange(0, self.dim, 2, dtype=torch.int64).float().to(x.device) / self.dim)
|
| 144 |
+
)
|
| 145 |
+
self.register_buffer("inv_freq", inv_freq, persistent=False) # TODO joao: this may break with compilation
|
| 146 |
+
|
| 147 |
+
cos, sin = super().forward(x, position_ids)
|
| 148 |
+
return cos, sin
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
def rotate_half(x):
|
| 152 |
+
"""Rotates half the hidden dims of the input."""
|
| 153 |
+
x1 = x[..., : x.shape[-1] // 2]
|
| 154 |
+
x2 = x[..., x.shape[-1] // 2 :]
|
| 155 |
+
return torch.cat((-x2, x1), dim=-1)
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
|
| 159 |
+
"""Applies Rotary Position Embedding to the query and key tensors.
|
| 160 |
+
|
| 161 |
+
Args:
|
| 162 |
+
q (`torch.Tensor`): The query tensor.
|
| 163 |
+
k (`torch.Tensor`): The key tensor.
|
| 164 |
+
cos (`torch.Tensor`): The cosine part of the rotary embedding.
|
| 165 |
+
sin (`torch.Tensor`): The sine part of the rotary embedding.
|
| 166 |
+
position_ids (`torch.Tensor`, *optional*):
|
| 167 |
+
Deprecated and unused.
|
| 168 |
+
unsqueeze_dim (`int`, *optional*, defaults to 1):
|
| 169 |
+
The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
|
| 170 |
+
sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
|
| 171 |
+
that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
|
| 172 |
+
k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
|
| 173 |
+
cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
|
| 174 |
+
the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
|
| 175 |
+
Returns:
|
| 176 |
+
`tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
|
| 177 |
+
"""
|
| 178 |
+
cos = cos.unsqueeze(unsqueeze_dim)
|
| 179 |
+
sin = sin.unsqueeze(unsqueeze_dim)
|
| 180 |
+
q_embed = (q * cos) + (rotate_half(q) * sin)
|
| 181 |
+
k_embed = (k * cos) + (rotate_half(k) * sin)
|
| 182 |
+
return q_embed, k_embed
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
class LlamaEncMLP(nn.Module):
|
| 186 |
+
def __init__(self, config):
|
| 187 |
+
super().__init__()
|
| 188 |
+
self.config = config
|
| 189 |
+
self.hidden_size = config.hidden_size
|
| 190 |
+
self.intermediate_size = config.intermediate_size
|
| 191 |
+
self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)
|
| 192 |
+
self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)
|
| 193 |
+
self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=config.mlp_bias)
|
| 194 |
+
self.act_fn = ACT2FN[config.hidden_act]
|
| 195 |
+
|
| 196 |
+
def forward(self, x):
|
| 197 |
+
if self.config.pretraining_tp > 1:
|
| 198 |
+
slice = self.intermediate_size // self.config.pretraining_tp
|
| 199 |
+
gate_proj_slices = self.gate_proj.weight.split(slice, dim=0)
|
| 200 |
+
up_proj_slices = self.up_proj.weight.split(slice, dim=0)
|
| 201 |
+
down_proj_slices = self.down_proj.weight.split(slice, dim=1)
|
| 202 |
+
|
| 203 |
+
gate_proj = torch.cat(
|
| 204 |
+
[F.linear(x, gate_proj_slices[i]) for i in range(self.config.pretraining_tp)], dim=-1
|
| 205 |
+
)
|
| 206 |
+
up_proj = torch.cat([F.linear(x, up_proj_slices[i]) for i in range(self.config.pretraining_tp)], dim=-1)
|
| 207 |
+
|
| 208 |
+
intermediate_states = (self.act_fn(gate_proj) * up_proj).split(slice, dim=2)
|
| 209 |
+
down_proj = [
|
| 210 |
+
F.linear(intermediate_states[i], down_proj_slices[i]) for i in range(self.config.pretraining_tp)
|
| 211 |
+
]
|
| 212 |
+
down_proj = sum(down_proj)
|
| 213 |
+
else:
|
| 214 |
+
down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
|
| 215 |
+
|
| 216 |
+
return down_proj
|
| 217 |
+
|
| 218 |
+
|
| 219 |
+
def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
|
| 220 |
+
"""
|
| 221 |
+
This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
|
| 222 |
+
num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
|
| 223 |
+
"""
|
| 224 |
+
batch, num_key_value_heads, slen, head_dim = hidden_states.shape
|
| 225 |
+
if n_rep == 1:
|
| 226 |
+
return hidden_states
|
| 227 |
+
hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
|
| 228 |
+
return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
|
| 229 |
+
|
| 230 |
+
|
| 231 |
+
class LlamaEncAttention(nn.Module):
|
| 232 |
+
"""Multi-headed attention from 'Attention Is All You Need' paper"""
|
| 233 |
+
|
| 234 |
+
def __init__(self, config: LlamaEncConfig, layer_idx: Optional[int] = None):
|
| 235 |
+
super().__init__()
|
| 236 |
+
self.config = config
|
| 237 |
+
self.layer_idx = layer_idx
|
| 238 |
+
if layer_idx is None:
|
| 239 |
+
logger.warning_once(
|
| 240 |
+
f"Instantiating {self.__class__.__name__} without passing a `layer_idx` is not recommended and will "
|
| 241 |
+
"lead to errors during the forward call if caching is used. Please make sure to provide a `layer_idx` "
|
| 242 |
+
"when creating this class."
|
| 243 |
+
)
|
| 244 |
+
|
| 245 |
+
self.attention_dropout = config.attention_dropout
|
| 246 |
+
self.hidden_size = config.hidden_size
|
| 247 |
+
self.num_heads = config.num_attention_heads
|
| 248 |
+
self.head_dim = self.hidden_size // self.num_heads
|
| 249 |
+
self.num_key_value_heads = config.num_key_value_heads
|
| 250 |
+
self.num_key_value_groups = self.num_heads // self.num_key_value_heads
|
| 251 |
+
self.max_position_embeddings = config.max_position_embeddings
|
| 252 |
+
self.rope_theta = config.rope_theta
|
| 253 |
+
self.is_causal = False # Encoder model does not use causal attention
|
| 254 |
+
self.window_size = (config.window_size_left, config.window_size_right)
|
| 255 |
+
|
| 256 |
+
if (self.head_dim * self.num_heads) != self.hidden_size:
|
| 257 |
+
raise ValueError(
|
| 258 |
+
f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
|
| 259 |
+
f" and `num_heads`: {self.num_heads})."
|
| 260 |
+
)
|
| 261 |
+
|
| 262 |
+
self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=config.attention_bias)
|
| 263 |
+
self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
|
| 264 |
+
self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
|
| 265 |
+
self.o_proj = nn.Linear(
|
| 266 |
+
self.hidden_size,
|
| 267 |
+
self.hidden_size,
|
| 268 |
+
bias=config.attention_bias and (not config.force_disable_attetion_output_bias),
|
| 269 |
+
)
|
| 270 |
+
self._init_rope()
|
| 271 |
+
|
| 272 |
+
def _init_rope(self):
|
| 273 |
+
if self.config.rope_scaling is None:
|
| 274 |
+
self.rotary_emb = LlamaEncRotaryEmbedding(
|
| 275 |
+
self.head_dim,
|
| 276 |
+
max_position_embeddings=self.max_position_embeddings,
|
| 277 |
+
base=self.rope_theta,
|
| 278 |
+
)
|
| 279 |
+
else:
|
| 280 |
+
scaling_type = self.config.rope_scaling["type"]
|
| 281 |
+
scaling_factor = self.config.rope_scaling["factor"]
|
| 282 |
+
if scaling_type == "linear":
|
| 283 |
+
self.rotary_emb = LlamaEncLinearScalingRotaryEmbedding(
|
| 284 |
+
self.head_dim,
|
| 285 |
+
max_position_embeddings=self.max_position_embeddings,
|
| 286 |
+
scaling_factor=scaling_factor,
|
| 287 |
+
base=self.rope_theta,
|
| 288 |
+
)
|
| 289 |
+
elif scaling_type == "dynamic":
|
| 290 |
+
self.rotary_emb = LlamaEncDynamicNTKScalingRotaryEmbedding(
|
| 291 |
+
self.head_dim,
|
| 292 |
+
max_position_embeddings=self.max_position_embeddings,
|
| 293 |
+
scaling_factor=scaling_factor,
|
| 294 |
+
base=self.rope_theta,
|
| 295 |
+
)
|
| 296 |
+
else:
|
| 297 |
+
raise ValueError(f"Unknown RoPE scaling type {scaling_type}")
|
| 298 |
+
|
| 299 |
+
def forward(
|
| 300 |
+
self,
|
| 301 |
+
hidden_states: torch.Tensor,
|
| 302 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 303 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 304 |
+
output_attentions: bool = False,
|
| 305 |
+
**kwargs,
|
| 306 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
| 307 |
+
bsz, q_len, _ = hidden_states.size()
|
| 308 |
+
|
| 309 |
+
if self.config.pretraining_tp > 1:
|
| 310 |
+
key_value_slicing = (self.num_key_value_heads * self.head_dim) // self.config.pretraining_tp
|
| 311 |
+
query_slices = self.q_proj.weight.split(
|
| 312 |
+
(self.num_heads * self.head_dim) // self.config.pretraining_tp, dim=0
|
| 313 |
+
)
|
| 314 |
+
key_slices = self.k_proj.weight.split(key_value_slicing, dim=0)
|
| 315 |
+
value_slices = self.v_proj.weight.split(key_value_slicing, dim=0)
|
| 316 |
+
|
| 317 |
+
query_states = [F.linear(hidden_states, query_slices[i]) for i in range(self.config.pretraining_tp)]
|
| 318 |
+
query_states = torch.cat(query_states, dim=-1)
|
| 319 |
+
|
| 320 |
+
key_states = [F.linear(hidden_states, key_slices[i]) for i in range(self.config.pretraining_tp)]
|
| 321 |
+
key_states = torch.cat(key_states, dim=-1)
|
| 322 |
+
|
| 323 |
+
value_states = [F.linear(hidden_states, value_slices[i]) for i in range(self.config.pretraining_tp)]
|
| 324 |
+
value_states = torch.cat(value_states, dim=-1)
|
| 325 |
+
|
| 326 |
+
else:
|
| 327 |
+
query_states = self.q_proj(hidden_states)
|
| 328 |
+
key_states = self.k_proj(hidden_states)
|
| 329 |
+
value_states = self.v_proj(hidden_states)
|
| 330 |
+
|
| 331 |
+
query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
|
| 332 |
+
key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
| 333 |
+
value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
| 334 |
+
|
| 335 |
+
cos, sin = self.rotary_emb(value_states, position_ids)
|
| 336 |
+
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
|
| 337 |
+
|
| 338 |
+
key_states = repeat_kv(key_states, self.num_key_value_groups)
|
| 339 |
+
value_states = repeat_kv(value_states, self.num_key_value_groups)
|
| 340 |
+
|
| 341 |
+
attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
|
| 342 |
+
|
| 343 |
+
if attention_mask is not None: # no matter the length, we just slice it
|
| 344 |
+
causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
|
| 345 |
+
attn_weights = attn_weights + causal_mask
|
| 346 |
+
|
| 347 |
+
# upcast attention to fp32
|
| 348 |
+
attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
|
| 349 |
+
attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
|
| 350 |
+
attn_output = torch.matmul(attn_weights, value_states)
|
| 351 |
+
|
| 352 |
+
if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
|
| 353 |
+
raise ValueError(
|
| 354 |
+
f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
|
| 355 |
+
f" {attn_output.size()}"
|
| 356 |
+
)
|
| 357 |
+
|
| 358 |
+
attn_output = attn_output.transpose(1, 2).contiguous()
|
| 359 |
+
|
| 360 |
+
attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
|
| 361 |
+
|
| 362 |
+
if self.config.pretraining_tp > 1:
|
| 363 |
+
attn_output = attn_output.split(self.hidden_size // self.config.pretraining_tp, dim=2)
|
| 364 |
+
o_proj_slices = self.o_proj.weight.split(self.hidden_size // self.config.pretraining_tp, dim=1)
|
| 365 |
+
attn_output = sum([F.linear(attn_output[i], o_proj_slices[i]) for i in range(self.config.pretraining_tp)])
|
| 366 |
+
else:
|
| 367 |
+
attn_output = self.o_proj(attn_output)
|
| 368 |
+
|
| 369 |
+
if not output_attentions:
|
| 370 |
+
attn_weights = None
|
| 371 |
+
|
| 372 |
+
return attn_output, attn_weights
|
| 373 |
+
|
| 374 |
+
|
| 375 |
+
class LlamaEncFlashAttention2(LlamaEncAttention):
|
| 376 |
+
"""
|
| 377 |
+
LlamaEnc flash attention module. This module inherits from `LlamaEncAttention` as the weights of the module stays
|
| 378 |
+
untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
|
| 379 |
+
flash attention and deal with padding tokens in case the input contains any of them.
|
| 380 |
+
"""
|
| 381 |
+
|
| 382 |
+
def __init__(self, *args, **kwargs):
|
| 383 |
+
super().__init__(*args, **kwargs)
|
| 384 |
+
|
| 385 |
+
# TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
|
| 386 |
+
# 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.
|
| 387 |
+
# 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).
|
| 388 |
+
|
| 389 |
+
def forward(
|
| 390 |
+
self,
|
| 391 |
+
hidden_states: torch.Tensor,
|
| 392 |
+
attention_mask: Optional[torch.LongTensor] = None,
|
| 393 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 394 |
+
output_attentions: bool = False,
|
| 395 |
+
**kwargs,
|
| 396 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
| 397 |
+
output_attentions = False
|
| 398 |
+
|
| 399 |
+
bsz, q_len, _ = hidden_states.size()
|
| 400 |
+
|
| 401 |
+
query_states = self.q_proj(hidden_states)
|
| 402 |
+
key_states = self.k_proj(hidden_states)
|
| 403 |
+
value_states = self.v_proj(hidden_states)
|
| 404 |
+
|
| 405 |
+
# Flash attention requires the input to have the shape
|
| 406 |
+
# batch_size x seq_length x head_dim x hidden_dim
|
| 407 |
+
# therefore we just need to keep the original shape
|
| 408 |
+
query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
|
| 409 |
+
key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
| 410 |
+
value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
| 411 |
+
|
| 412 |
+
cos, sin = self.rotary_emb(value_states, position_ids)
|
| 413 |
+
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
|
| 414 |
+
|
| 415 |
+
|
| 416 |
+
# 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
|
| 417 |
+
# to be able to avoid many of these transpose/reshape/view.
|
| 418 |
+
query_states = query_states.transpose(1, 2)
|
| 419 |
+
key_states = key_states.transpose(1, 2)
|
| 420 |
+
value_states = value_states.transpose(1, 2)
|
| 421 |
+
|
| 422 |
+
dropout_rate = self.attention_dropout if self.training else 0.0
|
| 423 |
+
|
| 424 |
+
# In PEFT, usually we cast the layer norms in float32 for training stability reasons
|
| 425 |
+
# therefore the input hidden states gets silently casted in float32. Hence, we need
|
| 426 |
+
# cast them back in the correct dtype just to be sure everything works as expected.
|
| 427 |
+
# This might slowdown training & inference so it is recommended to not cast the LayerNorms
|
| 428 |
+
# in fp32. (LlamaEncRMSNorm handles it correctly)
|
| 429 |
+
|
| 430 |
+
input_dtype = query_states.dtype
|
| 431 |
+
if input_dtype == torch.float32:
|
| 432 |
+
if torch.is_autocast_enabled():
|
| 433 |
+
target_dtype = torch.get_autocast_gpu_dtype()
|
| 434 |
+
# Handle the case where the model is quantized
|
| 435 |
+
elif hasattr(self.config, "_pre_quantization_dtype"):
|
| 436 |
+
target_dtype = self.config._pre_quantization_dtype
|
| 437 |
+
else:
|
| 438 |
+
target_dtype = self.q_proj.weight.dtype
|
| 439 |
+
|
| 440 |
+
logger.warning_once(
|
| 441 |
+
f"The input hidden states seems to be silently casted in float32, this might be related to"
|
| 442 |
+
f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
|
| 443 |
+
f" {target_dtype}."
|
| 444 |
+
)
|
| 445 |
+
|
| 446 |
+
query_states = query_states.to(target_dtype)
|
| 447 |
+
key_states = key_states.to(target_dtype)
|
| 448 |
+
value_states = value_states.to(target_dtype)
|
| 449 |
+
|
| 450 |
+
attn_output = self._flash_attention_forward(
|
| 451 |
+
query_states, key_states, value_states, attention_mask, q_len, dropout=dropout_rate
|
| 452 |
+
)
|
| 453 |
+
|
| 454 |
+
attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
|
| 455 |
+
attn_output = self.o_proj(attn_output)
|
| 456 |
+
|
| 457 |
+
if not output_attentions:
|
| 458 |
+
attn_weights = None
|
| 459 |
+
|
| 460 |
+
return attn_output, attn_weights
|
| 461 |
+
|
| 462 |
+
def _flash_attention_forward(
|
| 463 |
+
self, query_states, key_states, value_states, attention_mask, query_length, dropout=0.0, softmax_scale=None
|
| 464 |
+
):
|
| 465 |
+
"""
|
| 466 |
+
Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
|
| 467 |
+
first unpad the input, then computes the attention scores and pad the final attention scores.
|
| 468 |
+
|
| 469 |
+
Args:
|
| 470 |
+
query_states (`torch.Tensor`):
|
| 471 |
+
Input query states to be passed to Flash Attention API
|
| 472 |
+
key_states (`torch.Tensor`):
|
| 473 |
+
Input key states to be passed to Flash Attention API
|
| 474 |
+
value_states (`torch.Tensor`):
|
| 475 |
+
Input value states to be passed to Flash Attention API
|
| 476 |
+
attention_mask (`torch.Tensor`):
|
| 477 |
+
The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
|
| 478 |
+
position of padding tokens and 1 for the position of non-padding tokens.
|
| 479 |
+
dropout (`float`):
|
| 480 |
+
Attention dropout
|
| 481 |
+
softmax_scale (`float`, *optional*):
|
| 482 |
+
The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
|
| 483 |
+
"""
|
| 484 |
+
causal = self.is_causal
|
| 485 |
+
|
| 486 |
+
# Contains at least one padding token in the sequence
|
| 487 |
+
if attention_mask is not None:
|
| 488 |
+
batch_size = query_states.shape[0]
|
| 489 |
+
query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._upad_input(
|
| 490 |
+
query_states, key_states, value_states, attention_mask, query_length
|
| 491 |
+
)
|
| 492 |
+
|
| 493 |
+
cu_seqlens_q, cu_seqlens_k = cu_seq_lens
|
| 494 |
+
max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
|
| 495 |
+
|
| 496 |
+
attn_output_unpad = flash_attn_varlen_func(
|
| 497 |
+
query_states,
|
| 498 |
+
key_states,
|
| 499 |
+
value_states,
|
| 500 |
+
cu_seqlens_q=cu_seqlens_q,
|
| 501 |
+
cu_seqlens_k=cu_seqlens_k,
|
| 502 |
+
max_seqlen_q=max_seqlen_in_batch_q,
|
| 503 |
+
max_seqlen_k=max_seqlen_in_batch_k,
|
| 504 |
+
dropout_p=dropout,
|
| 505 |
+
softmax_scale=softmax_scale,
|
| 506 |
+
window_size=self.window_size,
|
| 507 |
+
causal=causal,
|
| 508 |
+
)
|
| 509 |
+
|
| 510 |
+
attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length)
|
| 511 |
+
else:
|
| 512 |
+
attn_output = flash_attn_func(
|
| 513 |
+
query_states,
|
| 514 |
+
key_states,
|
| 515 |
+
value_states,
|
| 516 |
+
dropout,
|
| 517 |
+
softmax_scale=softmax_scale,
|
| 518 |
+
window_size=self.window_size,
|
| 519 |
+
causal=causal
|
| 520 |
+
)
|
| 521 |
+
|
| 522 |
+
return attn_output
|
| 523 |
+
|
| 524 |
+
def _upad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length):
|
| 525 |
+
indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
|
| 526 |
+
batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape
|
| 527 |
+
|
| 528 |
+
key_layer = index_first_axis(
|
| 529 |
+
key_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
|
| 530 |
+
)
|
| 531 |
+
value_layer = index_first_axis(
|
| 532 |
+
value_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
|
| 533 |
+
)
|
| 534 |
+
if query_length == kv_seq_len:
|
| 535 |
+
query_layer = index_first_axis(
|
| 536 |
+
query_layer.reshape(batch_size * kv_seq_len, self.num_heads, head_dim), indices_k
|
| 537 |
+
)
|
| 538 |
+
cu_seqlens_q = cu_seqlens_k
|
| 539 |
+
max_seqlen_in_batch_q = max_seqlen_in_batch_k
|
| 540 |
+
indices_q = indices_k
|
| 541 |
+
elif query_length == 1:
|
| 542 |
+
max_seqlen_in_batch_q = 1
|
| 543 |
+
cu_seqlens_q = torch.arange(
|
| 544 |
+
batch_size + 1, dtype=torch.int32, device=query_layer.device
|
| 545 |
+
) # There is a memcpy here, that is very bad.
|
| 546 |
+
indices_q = cu_seqlens_q[:-1]
|
| 547 |
+
query_layer = query_layer.squeeze(1)
|
| 548 |
+
else:
|
| 549 |
+
# The -q_len: slice assumes left padding.
|
| 550 |
+
attention_mask = attention_mask[:, -query_length:]
|
| 551 |
+
query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, attention_mask)
|
| 552 |
+
|
| 553 |
+
return (
|
| 554 |
+
query_layer,
|
| 555 |
+
key_layer,
|
| 556 |
+
value_layer,
|
| 557 |
+
indices_q,
|
| 558 |
+
(cu_seqlens_q, cu_seqlens_k),
|
| 559 |
+
(max_seqlen_in_batch_q, max_seqlen_in_batch_k),
|
| 560 |
+
)
|
| 561 |
+
|
| 562 |
+
class LlamaEncSdpaAttention(LlamaEncAttention):
|
| 563 |
+
"""
|
| 564 |
+
LlamaEnc attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
|
| 565 |
+
`LlamaEncAttention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
|
| 566 |
+
SDPA API.
|
| 567 |
+
"""
|
| 568 |
+
|
| 569 |
+
# Adapted from LlamaEncAttention.forward
|
| 570 |
+
def forward(
|
| 571 |
+
self,
|
| 572 |
+
hidden_states: torch.Tensor,
|
| 573 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 574 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 575 |
+
output_attentions: bool = False,
|
| 576 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
| 577 |
+
if output_attentions:
|
| 578 |
+
# TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented.
|
| 579 |
+
logger.warning_once(
|
| 580 |
+
"LlamaEncModel is using LlamaEncSdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to the manual attention implementation, "
|
| 581 |
+
'but specifying the manual implementation will be required from Transformers version v5.0.0 onwards. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.'
|
| 582 |
+
)
|
| 583 |
+
return super().forward(
|
| 584 |
+
hidden_states=hidden_states,
|
| 585 |
+
attention_mask=attention_mask,
|
| 586 |
+
position_ids=position_ids,
|
| 587 |
+
output_attentions=output_attentions,
|
| 588 |
+
)
|
| 589 |
+
|
| 590 |
+
bsz, q_len, _ = hidden_states.size()
|
| 591 |
+
|
| 592 |
+
query_states = self.q_proj(hidden_states)
|
| 593 |
+
key_states = self.k_proj(hidden_states)
|
| 594 |
+
value_states = self.v_proj(hidden_states)
|
| 595 |
+
|
| 596 |
+
query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
|
| 597 |
+
key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
| 598 |
+
value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
| 599 |
+
|
| 600 |
+
cos, sin = self.rotary_emb(value_states, position_ids)
|
| 601 |
+
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
|
| 602 |
+
|
| 603 |
+
key_states = repeat_kv(key_states, self.num_key_value_groups)
|
| 604 |
+
value_states = repeat_kv(value_states, self.num_key_value_groups)
|
| 605 |
+
|
| 606 |
+
causal_mask = attention_mask
|
| 607 |
+
if attention_mask is not None:
|
| 608 |
+
causal_mask = causal_mask[:, :, :, : key_states.shape[-2]]
|
| 609 |
+
|
| 610 |
+
# SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with custom attn_mask,
|
| 611 |
+
# Reference: https://github.com/pytorch/pytorch/issues/112577.
|
| 612 |
+
if query_states.device.type == "cuda" and causal_mask is not None:
|
| 613 |
+
query_states = query_states.contiguous()
|
| 614 |
+
key_states = key_states.contiguous()
|
| 615 |
+
value_states = value_states.contiguous()
|
| 616 |
+
|
| 617 |
+
# We dispatch to SDPA's Flash Attention or Efficient kernels via this if statement instead of an
|
| 618 |
+
# inline conditional assignment to support both torch.compile's `dynamic=True` and `fullgraph=True`
|
| 619 |
+
attn_output = torch.nn.functional.scaled_dot_product_attention(
|
| 620 |
+
query_states,
|
| 621 |
+
key_states,
|
| 622 |
+
value_states,
|
| 623 |
+
attn_mask=causal_mask,
|
| 624 |
+
dropout_p=self.attention_dropout if self.training else 0.0,
|
| 625 |
+
is_causal=False,
|
| 626 |
+
)
|
| 627 |
+
|
| 628 |
+
attn_output = attn_output.transpose(1, 2).contiguous()
|
| 629 |
+
attn_output = attn_output.view(bsz, q_len, self.hidden_size)
|
| 630 |
+
|
| 631 |
+
attn_output = self.o_proj(attn_output)
|
| 632 |
+
|
| 633 |
+
return attn_output, None
|
| 634 |
+
|
| 635 |
+
|
| 636 |
+
LLAMAENC_ATTENTION_CLASSES = {
|
| 637 |
+
"eager": LlamaEncAttention,
|
| 638 |
+
"flash_attention_2": LlamaEncFlashAttention2,
|
| 639 |
+
"sdpa": LlamaEncSdpaAttention,
|
| 640 |
+
}
|
| 641 |
+
|
| 642 |
+
|
| 643 |
+
class LlamaEncDecoderLayer(nn.Module):
|
| 644 |
+
def __init__(self, config: LlamaEncConfig, layer_idx: int):
|
| 645 |
+
super().__init__()
|
| 646 |
+
self.hidden_size = config.hidden_size
|
| 647 |
+
|
| 648 |
+
self.self_attn = LLAMAENC_ATTENTION_CLASSES[config._attn_implementation](config=config, layer_idx=layer_idx)
|
| 649 |
+
|
| 650 |
+
self.mlp = LlamaEncMLP(config)
|
| 651 |
+
self.input_layernorm = LlamaEncRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
| 652 |
+
self.post_attention_layernorm = LlamaEncRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
| 653 |
+
|
| 654 |
+
def forward(
|
| 655 |
+
self,
|
| 656 |
+
hidden_states: torch.Tensor,
|
| 657 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 658 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 659 |
+
output_attentions: Optional[bool] = False,
|
| 660 |
+
) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
|
| 661 |
+
"""
|
| 662 |
+
Args:
|
| 663 |
+
hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
|
| 664 |
+
attention_mask (`torch.FloatTensor`, *optional*):
|
| 665 |
+
attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
|
| 666 |
+
query_sequence_length, key_sequence_length)` if default attention is used.
|
| 667 |
+
output_attentions (`bool`, *optional*):
|
| 668 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
|
| 669 |
+
returned tensors for more detail.
|
| 670 |
+
use_cache (`bool`, *optional*):
|
| 671 |
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
|
| 672 |
+
(see `past_key_values`).
|
| 673 |
+
past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
|
| 674 |
+
"""
|
| 675 |
+
residual = hidden_states
|
| 676 |
+
|
| 677 |
+
hidden_states = self.input_layernorm(hidden_states)
|
| 678 |
+
|
| 679 |
+
# Self Attention
|
| 680 |
+
hidden_states, self_attn_weights = self.self_attn(
|
| 681 |
+
hidden_states=hidden_states,
|
| 682 |
+
attention_mask=attention_mask,
|
| 683 |
+
position_ids=position_ids,
|
| 684 |
+
output_attentions=output_attentions,
|
| 685 |
+
)
|
| 686 |
+
hidden_states = residual + hidden_states
|
| 687 |
+
|
| 688 |
+
# Fully Connected
|
| 689 |
+
residual = hidden_states
|
| 690 |
+
hidden_states = self.post_attention_layernorm(hidden_states)
|
| 691 |
+
hidden_states = self.mlp(hidden_states)
|
| 692 |
+
hidden_states = residual + hidden_states
|
| 693 |
+
|
| 694 |
+
outputs = (hidden_states,)
|
| 695 |
+
|
| 696 |
+
if output_attentions:
|
| 697 |
+
outputs += (self_attn_weights,)
|
| 698 |
+
|
| 699 |
+
return outputs
|
| 700 |
+
|
| 701 |
+
|
| 702 |
+
LLAMAENC_START_DOCSTRING = r"""
|
| 703 |
+
This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
|
| 704 |
+
library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
|
| 705 |
+
etc.)
|
| 706 |
+
|
| 707 |
+
This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
|
| 708 |
+
Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
|
| 709 |
+
and behavior.
|
| 710 |
+
|
| 711 |
+
Parameters:
|
| 712 |
+
config ([`LlamaEncConfig`]):
|
| 713 |
+
Model configuration class with all the parameters of the model. Initializing with a config file does not
|
| 714 |
+
load the weights associated with the model, only the configuration. Check out the
|
| 715 |
+
[`~PreTrainedModel.from_pretrained`] method to load the model weights.
|
| 716 |
+
"""
|
| 717 |
+
|
| 718 |
+
|
| 719 |
+
@add_start_docstrings(
|
| 720 |
+
"The bare LlamaEnc Model outputting raw hidden-states without any specific head on top.",
|
| 721 |
+
LLAMAENC_START_DOCSTRING,
|
| 722 |
+
)
|
| 723 |
+
class LlamaEncPreTrainedModel(PreTrainedModel):
|
| 724 |
+
config_class = LlamaEncConfig
|
| 725 |
+
base_model_prefix = "model"
|
| 726 |
+
supports_gradient_checkpointing = True
|
| 727 |
+
_no_split_modules = ["LlamaEncDecoderLayer"]
|
| 728 |
+
_skip_keys_device_placement = ["past_key_values"]
|
| 729 |
+
_supports_flash_attn_2 = True
|
| 730 |
+
_supports_sdpa = True
|
| 731 |
+
_supports_cache_class = True
|
| 732 |
+
_supports_static_cache = True
|
| 733 |
+
|
| 734 |
+
def _init_weights(self, module):
|
| 735 |
+
std = self.config.initializer_range
|
| 736 |
+
if isinstance(module, nn.Linear):
|
| 737 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
| 738 |
+
if module.bias is not None:
|
| 739 |
+
module.bias.data.zero_()
|
| 740 |
+
|
| 741 |
+
elif isinstance(module, nn.Embedding):
|
| 742 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
| 743 |
+
if module.padding_idx is not None:
|
| 744 |
+
module.weight.data[module.padding_idx].zero_()
|
| 745 |
+
|
| 746 |
+
|
| 747 |
+
LLAMAENC_INPUTS_DOCSTRING = r"""
|
| 748 |
+
Args:
|
| 749 |
+
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
|
| 750 |
+
Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
|
| 751 |
+
it.
|
| 752 |
+
|
| 753 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
| 754 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
| 755 |
+
|
| 756 |
+
[What are input IDs?](../glossary#input-ids)
|
| 757 |
+
attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 758 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
| 759 |
+
|
| 760 |
+
- 1 for tokens that are **not masked**,
|
| 761 |
+
- 0 for tokens that are **masked**.
|
| 762 |
+
|
| 763 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 764 |
+
|
| 765 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
| 766 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
| 767 |
+
|
| 768 |
+
If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
|
| 769 |
+
`past_key_values`).
|
| 770 |
+
|
| 771 |
+
If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
|
| 772 |
+
and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
|
| 773 |
+
information on the default strategy.
|
| 774 |
+
|
| 775 |
+
- 1 indicates the head is **not masked**,
|
| 776 |
+
- 0 indicates the head is **masked**.
|
| 777 |
+
position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 778 |
+
Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
|
| 779 |
+
config.n_positions - 1]`.
|
| 780 |
+
|
| 781 |
+
[What are position IDs?](../glossary#position-ids)
|
| 782 |
+
past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
|
| 783 |
+
Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
|
| 784 |
+
blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
|
| 785 |
+
returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
|
| 786 |
+
|
| 787 |
+
Two formats are allowed:
|
| 788 |
+
- a [`~cache_utils.Cache`] instance;
|
| 789 |
+
- Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
|
| 790 |
+
shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
|
| 791 |
+
cache format.
|
| 792 |
+
|
| 793 |
+
The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
|
| 794 |
+
legacy cache format will be returned.
|
| 795 |
+
|
| 796 |
+
If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
|
| 797 |
+
have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
|
| 798 |
+
of shape `(batch_size, sequence_length)`.
|
| 799 |
+
inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
|
| 800 |
+
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
|
| 801 |
+
is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
|
| 802 |
+
model's internal embedding lookup matrix.
|
| 803 |
+
use_cache (`bool`, *optional*):
|
| 804 |
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
|
| 805 |
+
`past_key_values`).
|
| 806 |
+
output_attentions (`bool`, *optional*):
|
| 807 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
| 808 |
+
tensors for more detail.
|
| 809 |
+
output_hidden_states (`bool`, *optional*):
|
| 810 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
| 811 |
+
more detail.
|
| 812 |
+
return_dict (`bool`, *optional*):
|
| 813 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
| 814 |
+
cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
|
| 815 |
+
Indices depicting the position of the input sequence tokens in the sequence. Contrarily to `position_ids`,
|
| 816 |
+
this tensor is not affected by padding. It is used to update the cache in the correct position and to infer
|
| 817 |
+
the complete sequence length.
|
| 818 |
+
"""
|
| 819 |
+
|
| 820 |
+
|
| 821 |
+
@add_start_docstrings(
|
| 822 |
+
"The bare LlamaEnc Model outputting raw hidden-states without any specific head on top.",
|
| 823 |
+
LLAMAENC_START_DOCSTRING,
|
| 824 |
+
)
|
| 825 |
+
class LlamaEncModel(LlamaEncPreTrainedModel):
|
| 826 |
+
"""
|
| 827 |
+
Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`LlamaEncDecoderLayer`]
|
| 828 |
+
|
| 829 |
+
Args:
|
| 830 |
+
config: LlamaEncConfig
|
| 831 |
+
"""
|
| 832 |
+
|
| 833 |
+
def __init__(self, config: LlamaEncConfig):
|
| 834 |
+
super().__init__(config)
|
| 835 |
+
self.padding_idx = config.pad_token_id
|
| 836 |
+
self.vocab_size = config.vocab_size
|
| 837 |
+
|
| 838 |
+
self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
|
| 839 |
+
self.layers = nn.ModuleList(
|
| 840 |
+
[LlamaEncDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
|
| 841 |
+
)
|
| 842 |
+
self.norm = LlamaEncRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
| 843 |
+
self.gradient_checkpointing = False
|
| 844 |
+
|
| 845 |
+
# Initialize weights and apply final processing
|
| 846 |
+
self.post_init()
|
| 847 |
+
|
| 848 |
+
def get_input_embeddings(self):
|
| 849 |
+
return self.embed_tokens
|
| 850 |
+
|
| 851 |
+
def set_input_embeddings(self, value):
|
| 852 |
+
self.embed_tokens = value
|
| 853 |
+
|
| 854 |
+
@add_start_docstrings_to_model_forward(LLAMAENC_INPUTS_DOCSTRING)
|
| 855 |
+
def forward(
|
| 856 |
+
self,
|
| 857 |
+
input_ids: torch.LongTensor = None,
|
| 858 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 859 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 860 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 861 |
+
output_attentions: Optional[bool] = None,
|
| 862 |
+
output_hidden_states: Optional[bool] = None,
|
| 863 |
+
return_dict: Optional[bool] = None,
|
| 864 |
+
) -> Union[Tuple, BaseModelOutputWithPast]:
|
| 865 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 866 |
+
output_hidden_states = (
|
| 867 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 868 |
+
)
|
| 869 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 870 |
+
|
| 871 |
+
if (input_ids is None) ^ (inputs_embeds is not None):
|
| 872 |
+
raise ValueError(
|
| 873 |
+
"You cannot specify both input_ids and inputs_embeds at the same time, and must specify either one"
|
| 874 |
+
)
|
| 875 |
+
|
| 876 |
+
if inputs_embeds is None:
|
| 877 |
+
inputs_embeds = self.embed_tokens(input_ids)
|
| 878 |
+
|
| 879 |
+
if position_ids is None:
|
| 880 |
+
position_ids = torch.arange(
|
| 881 |
+
0, inputs_embeds.shape[1], device=inputs_embeds.device
|
| 882 |
+
).unsqueeze(0)
|
| 883 |
+
|
| 884 |
+
causal_mask = self._update_causal_mask(
|
| 885 |
+
attention_mask, inputs_embeds, output_attentions
|
| 886 |
+
)
|
| 887 |
+
|
| 888 |
+
# embed positions
|
| 889 |
+
hidden_states = inputs_embeds
|
| 890 |
+
|
| 891 |
+
# decoder layers
|
| 892 |
+
all_hidden_states = () if output_hidden_states else None
|
| 893 |
+
all_self_attns = () if output_attentions else None
|
| 894 |
+
|
| 895 |
+
for decoder_layer in self.layers:
|
| 896 |
+
if output_hidden_states:
|
| 897 |
+
all_hidden_states += (hidden_states,)
|
| 898 |
+
|
| 899 |
+
if self.gradient_checkpointing and self.training:
|
| 900 |
+
layer_outputs = self._gradient_checkpointing_func(
|
| 901 |
+
decoder_layer.__call__,
|
| 902 |
+
hidden_states,
|
| 903 |
+
causal_mask,
|
| 904 |
+
position_ids,
|
| 905 |
+
output_attentions,
|
| 906 |
+
)
|
| 907 |
+
else:
|
| 908 |
+
layer_outputs = decoder_layer(
|
| 909 |
+
hidden_states,
|
| 910 |
+
attention_mask=causal_mask,
|
| 911 |
+
position_ids=position_ids,
|
| 912 |
+
output_attentions=output_attentions,
|
| 913 |
+
)
|
| 914 |
+
|
| 915 |
+
hidden_states = layer_outputs[0]
|
| 916 |
+
|
| 917 |
+
|
| 918 |
+
if output_attentions:
|
| 919 |
+
all_self_attns += (layer_outputs[1],)
|
| 920 |
+
|
| 921 |
+
if output_hidden_states:
|
| 922 |
+
all_hidden_states += (hidden_states,)
|
| 923 |
+
hidden_states = self.norm(hidden_states)
|
| 924 |
+
|
| 925 |
+
# add hidden states from the last decoder layer
|
| 926 |
+
if output_hidden_states:
|
| 927 |
+
all_hidden_states += (hidden_states,)
|
| 928 |
+
|
| 929 |
+
|
| 930 |
+
if not return_dict:
|
| 931 |
+
return tuple(v for v in [hidden_states, all_hidden_states, all_self_attns] if v is not None)
|
| 932 |
+
return BaseModelOutputWithPast(
|
| 933 |
+
last_hidden_state=hidden_states,
|
| 934 |
+
hidden_states=all_hidden_states,
|
| 935 |
+
attentions=all_self_attns,
|
| 936 |
+
)
|
| 937 |
+
|
| 938 |
+
def _update_causal_mask(
|
| 939 |
+
self,
|
| 940 |
+
attention_mask: torch.Tensor,
|
| 941 |
+
input_tensor: torch.Tensor,
|
| 942 |
+
output_attentions: bool,
|
| 943 |
+
):
|
| 944 |
+
# TODO: As of torch==2.2.0, the `attention_mask` passed to the model in `generate` is 2D and of dynamic length even when the static
|
| 945 |
+
# KV cache is used. This is an issue for torch.compile which then recaptures cudagraphs at each decode steps due to the dynamic shapes.
|
| 946 |
+
# (`recording cudagraph tree for symint key 13`, etc.), which is VERY slow. A workaround is `@torch.compiler.disable`, but this prevents using
|
| 947 |
+
# `fullgraph=True`. See more context in https://github.com/huggingface/transformers/pull/29114
|
| 948 |
+
if attention_mask is None:
|
| 949 |
+
return None
|
| 950 |
+
|
| 951 |
+
if self.config._attn_implementation == "flash_attention_2":
|
| 952 |
+
if 0.0 in attention_mask:
|
| 953 |
+
return attention_mask
|
| 954 |
+
return None
|
| 955 |
+
|
| 956 |
+
# For SDPA, when possible, we will rely on its `is_causal` argument instead of its `attn_mask` argument, in
|
| 957 |
+
# order to dispatch on Flash Attention 2. This feature is not compatible with static cache, as SDPA will fail
|
| 958 |
+
# to infer the attention mask.
|
| 959 |
+
# When output attentions is True, sdpa implementation's forward method calls the eager implementation's forward
|
| 960 |
+
|
| 961 |
+
if self.config._attn_implementation == "sdpa" and not output_attentions:
|
| 962 |
+
# No padding
|
| 963 |
+
if attention_mask.all():
|
| 964 |
+
return None
|
| 965 |
+
|
| 966 |
+
if attention_mask.dim() == 2:
|
| 967 |
+
return _prepare_4d_attention_mask_for_sdpa(
|
| 968 |
+
attention_mask, input_tensor.dtype, attention_mask.shape[-1]
|
| 969 |
+
)
|
| 970 |
+
if attention_mask is not None and attention_mask.dim() == 4:
|
| 971 |
+
# in this case we assume that the mask comes already in inverted form and requires no inversion or slicing
|
| 972 |
+
if attention_mask.max() != 0:
|
| 973 |
+
raise ValueError("Custom 4D attention mask should be passed in inverted form with max==0`")
|
| 974 |
+
return attention_mask
|
| 975 |
+
|
| 976 |
+
return self.get_extended_attention_mask(
|
| 977 |
+
attention_mask, input_tensor.shape,
|
| 978 |
+
)
|
| 979 |
+
|
| 980 |
+
|
| 981 |
+
class LlamaEncForMaskedLM(LlamaEncPreTrainedModel):
|
| 982 |
+
_tied_weights_keys = ["lm_head.weight"]
|
| 983 |
+
|
| 984 |
+
def __init__(self, config):
|
| 985 |
+
super().__init__(config)
|
| 986 |
+
self.model = LlamaEncModel(config)
|
| 987 |
+
self.vocab_size = config.vocab_size
|
| 988 |
+
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
| 989 |
+
|
| 990 |
+
# Initialize weights and apply final processing
|
| 991 |
+
self.post_init()
|
| 992 |
+
|
| 993 |
+
def get_input_embeddings(self):
|
| 994 |
+
return self.model.embed_tokens
|
| 995 |
+
|
| 996 |
+
def set_input_embeddings(self, value):
|
| 997 |
+
self.model.embed_tokens = value
|
| 998 |
+
|
| 999 |
+
def get_output_embeddings(self):
|
| 1000 |
+
return self.lm_head
|
| 1001 |
+
|
| 1002 |
+
def set_output_embeddings(self, new_embeddings):
|
| 1003 |
+
self.lm_head = new_embeddings
|
| 1004 |
+
|
| 1005 |
+
def set_decoder(self, decoder):
|
| 1006 |
+
self.model = decoder
|
| 1007 |
+
|
| 1008 |
+
def get_decoder(self):
|
| 1009 |
+
return self.model
|
| 1010 |
+
|
| 1011 |
+
@add_start_docstrings_to_model_forward(LLAMAENC_INPUTS_DOCSTRING)
|
| 1012 |
+
@replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
|
| 1013 |
+
def forward(
|
| 1014 |
+
self,
|
| 1015 |
+
input_ids: torch.LongTensor = None,
|
| 1016 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 1017 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 1018 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 1019 |
+
labels: Optional[torch.LongTensor] = None,
|
| 1020 |
+
output_attentions: Optional[bool] = None,
|
| 1021 |
+
output_hidden_states: Optional[bool] = None,
|
| 1022 |
+
return_dict: Optional[bool] = None,
|
| 1023 |
+
) -> Union[Tuple, CausalLMOutputWithPast]:
|
| 1024 |
+
r"""
|
| 1025 |
+
Args:
|
| 1026 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 1027 |
+
Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
|
| 1028 |
+
config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
|
| 1029 |
+
(masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
|
| 1030 |
+
|
| 1031 |
+
Returns:
|
| 1032 |
+
|
| 1033 |
+
Example:
|
| 1034 |
+
|
| 1035 |
+
```python
|
| 1036 |
+
>>> from transformers import AutoTokenizer, LlamaEncForCausalLM
|
| 1037 |
+
|
| 1038 |
+
>>> model = LlamaEncForCausalLM.from_pretrained("meta-llama/Llama-2-7b-hf")
|
| 1039 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-2-7b-hf")
|
| 1040 |
+
|
| 1041 |
+
>>> prompt = "Hey, are you conscious? Can you talk to me?"
|
| 1042 |
+
>>> inputs = tokenizer(prompt, return_tensors="pt")
|
| 1043 |
+
|
| 1044 |
+
>>> # Generate
|
| 1045 |
+
>>> generate_ids = model.generate(inputs.input_ids, max_length=30)
|
| 1046 |
+
>>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
|
| 1047 |
+
"Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
|
| 1048 |
+
```"""
|
| 1049 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 1050 |
+
output_hidden_states = (
|
| 1051 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 1052 |
+
)
|
| 1053 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1054 |
+
|
| 1055 |
+
# decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
|
| 1056 |
+
outputs = self.model(
|
| 1057 |
+
input_ids=input_ids,
|
| 1058 |
+
attention_mask=attention_mask,
|
| 1059 |
+
position_ids=position_ids,
|
| 1060 |
+
inputs_embeds=inputs_embeds,
|
| 1061 |
+
output_attentions=output_attentions,
|
| 1062 |
+
output_hidden_states=output_hidden_states,
|
| 1063 |
+
return_dict=return_dict,
|
| 1064 |
+
)
|
| 1065 |
+
|
| 1066 |
+
hidden_states = outputs[0]
|
| 1067 |
+
if self.config.pretraining_tp > 1:
|
| 1068 |
+
lm_head_slices = self.lm_head.weight.split(self.vocab_size // self.config.pretraining_tp, dim=0)
|
| 1069 |
+
logits = [F.linear(hidden_states, lm_head_slices[i]) for i in range(self.config.pretraining_tp)]
|
| 1070 |
+
logits = torch.cat(logits, dim=-1)
|
| 1071 |
+
else:
|
| 1072 |
+
logits = self.lm_head(hidden_states)
|
| 1073 |
+
logits = logits.float()
|
| 1074 |
+
|
| 1075 |
+
loss = None
|
| 1076 |
+
if labels is not None:
|
| 1077 |
+
loss_fct = CrossEntropyLoss(label_smoothing=self.config.label_smoothing)
|
| 1078 |
+
loss = loss_fct(
|
| 1079 |
+
logits.view(-1, self.config.vocab_size),
|
| 1080 |
+
labels.to(logits.device).view(-1)
|
| 1081 |
+
)
|
| 1082 |
+
|
| 1083 |
+
if not return_dict:
|
| 1084 |
+
output = (logits,) + outputs[1:]
|
| 1085 |
+
return (loss,) + output if loss is not None else output
|
| 1086 |
+
|
| 1087 |
+
return CausalLMOutputWithPast(
|
| 1088 |
+
loss=loss,
|
| 1089 |
+
logits=logits,
|
| 1090 |
+
hidden_states=outputs.hidden_states,
|
| 1091 |
+
attentions=outputs.attentions,
|
| 1092 |
+
)
|
| 1093 |
+
|
| 1094 |
+
@add_start_docstrings(
|
| 1095 |
+
"""
|
| 1096 |
+
The LLaMa Model transformer with a sequence classification head on top (linear layer).
|
| 1097 |
+
|
| 1098 |
+
[`LlamaEncForSequenceClassification`] uses the last token in order to do the classification, as other causal models
|
| 1099 |
+
(e.g. GPT-2) do.
|
| 1100 |
+
|
| 1101 |
+
Since it does classification on the last token, it requires to know the position of the last token. If a
|
| 1102 |
+
`pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
|
| 1103 |
+
no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
|
| 1104 |
+
padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
|
| 1105 |
+
each row of the batch).
|
| 1106 |
+
""",
|
| 1107 |
+
LLAMAENC_START_DOCSTRING,
|
| 1108 |
+
)
|
| 1109 |
+
class LlamaEncForSequenceClassification(LlamaEncPreTrainedModel):
|
| 1110 |
+
def __init__(self, config):
|
| 1111 |
+
super().__init__(config)
|
| 1112 |
+
self.num_labels = config.num_labels
|
| 1113 |
+
self.model = LlamaEncModel(config)
|
| 1114 |
+
self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
|
| 1115 |
+
|
| 1116 |
+
# Initialize weights and apply final processing
|
| 1117 |
+
self.post_init()
|
| 1118 |
+
|
| 1119 |
+
def get_input_embeddings(self):
|
| 1120 |
+
return self.model.embed_tokens
|
| 1121 |
+
|
| 1122 |
+
def set_input_embeddings(self, value):
|
| 1123 |
+
self.model.embed_tokens = value
|
| 1124 |
+
|
| 1125 |
+
@add_start_docstrings_to_model_forward(LLAMAENC_INPUTS_DOCSTRING)
|
| 1126 |
+
def forward(
|
| 1127 |
+
self,
|
| 1128 |
+
input_ids: torch.LongTensor = None,
|
| 1129 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 1130 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 1131 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 1132 |
+
labels: Optional[torch.LongTensor] = None,
|
| 1133 |
+
output_attentions: Optional[bool] = None,
|
| 1134 |
+
output_hidden_states: Optional[bool] = None,
|
| 1135 |
+
return_dict: Optional[bool] = None,
|
| 1136 |
+
) -> Union[Tuple, SequenceClassifierOutputWithPast]:
|
| 1137 |
+
r"""
|
| 1138 |
+
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
| 1139 |
+
Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
|
| 1140 |
+
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
|
| 1141 |
+
`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
|
| 1142 |
+
"""
|
| 1143 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1144 |
+
|
| 1145 |
+
transformer_outputs = self.model(
|
| 1146 |
+
input_ids,
|
| 1147 |
+
attention_mask=attention_mask,
|
| 1148 |
+
position_ids=position_ids,
|
| 1149 |
+
inputs_embeds=inputs_embeds,
|
| 1150 |
+
output_attentions=output_attentions,
|
| 1151 |
+
output_hidden_states=output_hidden_states,
|
| 1152 |
+
return_dict=return_dict,
|
| 1153 |
+
)
|
| 1154 |
+
hidden_states = transformer_outputs[0]
|
| 1155 |
+
logits = self.score(hidden_states)
|
| 1156 |
+
|
| 1157 |
+
if input_ids is not None:
|
| 1158 |
+
batch_size = input_ids.shape[0]
|
| 1159 |
+
else:
|
| 1160 |
+
batch_size = inputs_embeds.shape[0]
|
| 1161 |
+
|
| 1162 |
+
if self.config.pad_token_id is None and batch_size != 1:
|
| 1163 |
+
raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
|
| 1164 |
+
if self.config.pad_token_id is None:
|
| 1165 |
+
sequence_lengths = -1
|
| 1166 |
+
else:
|
| 1167 |
+
if input_ids is not None:
|
| 1168 |
+
# if no pad token found, use modulo instead of reverse indexing for ONNX compatibility
|
| 1169 |
+
sequence_lengths = torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
|
| 1170 |
+
sequence_lengths = sequence_lengths % input_ids.shape[-1]
|
| 1171 |
+
sequence_lengths = sequence_lengths.to(logits.device)
|
| 1172 |
+
else:
|
| 1173 |
+
sequence_lengths = -1
|
| 1174 |
+
|
| 1175 |
+
pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
|
| 1176 |
+
|
| 1177 |
+
loss = None
|
| 1178 |
+
if labels is not None:
|
| 1179 |
+
labels = labels.to(logits.device)
|
| 1180 |
+
if self.config.problem_type is None:
|
| 1181 |
+
if self.num_labels == 1:
|
| 1182 |
+
self.config.problem_type = "regression"
|
| 1183 |
+
elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
|
| 1184 |
+
self.config.problem_type = "single_label_classification"
|
| 1185 |
+
else:
|
| 1186 |
+
self.config.problem_type = "multi_label_classification"
|
| 1187 |
+
|
| 1188 |
+
if self.config.problem_type == "regression":
|
| 1189 |
+
loss_fct = MSELoss()
|
| 1190 |
+
if self.num_labels == 1:
|
| 1191 |
+
loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
|
| 1192 |
+
else:
|
| 1193 |
+
loss = loss_fct(pooled_logits, labels)
|
| 1194 |
+
elif self.config.problem_type == "single_label_classification":
|
| 1195 |
+
loss_fct = CrossEntropyLoss()
|
| 1196 |
+
loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
|
| 1197 |
+
elif self.config.problem_type == "multi_label_classification":
|
| 1198 |
+
loss_fct = BCEWithLogitsLoss()
|
| 1199 |
+
loss = loss_fct(pooled_logits, labels)
|
| 1200 |
+
if not return_dict:
|
| 1201 |
+
output = (pooled_logits,) + transformer_outputs[1:]
|
| 1202 |
+
return ((loss,) + output) if loss is not None else output
|
| 1203 |
+
|
| 1204 |
+
return SequenceClassifierOutputWithPast(
|
| 1205 |
+
loss=loss,
|
| 1206 |
+
logits=pooled_logits,
|
| 1207 |
+
past_key_values=transformer_outputs.past_key_values,
|
| 1208 |
+
hidden_states=transformer_outputs.hidden_states,
|
| 1209 |
+
attentions=transformer_outputs.attentions,
|
| 1210 |
+
)
|
| 1211 |
+
|
| 1212 |
+
|
| 1213 |
+
@add_start_docstrings(
|
| 1214 |
+
"""
|
| 1215 |
+
The LlamaEnc Model transformer with a span classification head on top for extractive question-answering tasks like
|
| 1216 |
+
SQuAD (a linear layer on top of the hidden-states output to compute `span start logits` and `span end logits`).
|
| 1217 |
+
""",
|
| 1218 |
+
LLAMAENC_START_DOCSTRING,
|
| 1219 |
+
)
|
| 1220 |
+
class LlamaEncForQuestionAnswering(LlamaEncPreTrainedModel):
|
| 1221 |
+
base_model_prefix = "transformer"
|
| 1222 |
+
|
| 1223 |
+
# Copied from transformers.models.bloom.modeling_bloom.BloomForQuestionAnswering.__init__ with Bloom->LlamaEnc
|
| 1224 |
+
def __init__(self, config):
|
| 1225 |
+
super().__init__(config)
|
| 1226 |
+
self.transformer = LlamaEncModel(config)
|
| 1227 |
+
self.qa_outputs = nn.Linear(config.hidden_size, 2)
|
| 1228 |
+
|
| 1229 |
+
# Initialize weights and apply final processing
|
| 1230 |
+
self.post_init()
|
| 1231 |
+
|
| 1232 |
+
def get_input_embeddings(self):
|
| 1233 |
+
return self.transformer.embed_tokens
|
| 1234 |
+
|
| 1235 |
+
def set_input_embeddings(self, value):
|
| 1236 |
+
self.transformer.embed_tokens = value
|
| 1237 |
+
|
| 1238 |
+
@add_start_docstrings_to_model_forward(LLAMAENC_INPUTS_DOCSTRING)
|
| 1239 |
+
def forward(
|
| 1240 |
+
self,
|
| 1241 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 1242 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
| 1243 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 1244 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 1245 |
+
start_positions: Optional[torch.LongTensor] = None,
|
| 1246 |
+
end_positions: Optional[torch.LongTensor] = None,
|
| 1247 |
+
output_attentions: Optional[bool] = None,
|
| 1248 |
+
output_hidden_states: Optional[bool] = None,
|
| 1249 |
+
return_dict: Optional[bool] = None,
|
| 1250 |
+
) -> Union[Tuple, QuestionAnsweringModelOutput]:
|
| 1251 |
+
r"""
|
| 1252 |
+
start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
| 1253 |
+
Labels for position (index) of the start of the labelled span for computing the token classification loss.
|
| 1254 |
+
Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
|
| 1255 |
+
are not taken into account for computing the loss.
|
| 1256 |
+
end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
| 1257 |
+
Labels for position (index) of the end of the labelled span for computing the token classification loss.
|
| 1258 |
+
Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
|
| 1259 |
+
are not taken into account for computing the loss.
|
| 1260 |
+
"""
|
| 1261 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1262 |
+
|
| 1263 |
+
outputs = self.transformer(
|
| 1264 |
+
input_ids,
|
| 1265 |
+
attention_mask=attention_mask,
|
| 1266 |
+
position_ids=position_ids,
|
| 1267 |
+
inputs_embeds=inputs_embeds,
|
| 1268 |
+
output_attentions=output_attentions,
|
| 1269 |
+
output_hidden_states=output_hidden_states,
|
| 1270 |
+
return_dict=return_dict,
|
| 1271 |
+
)
|
| 1272 |
+
|
| 1273 |
+
sequence_output = outputs[0]
|
| 1274 |
+
|
| 1275 |
+
logits = self.qa_outputs(sequence_output)
|
| 1276 |
+
start_logits, end_logits = logits.split(1, dim=-1)
|
| 1277 |
+
start_logits = start_logits.squeeze(-1).contiguous()
|
| 1278 |
+
end_logits = end_logits.squeeze(-1).contiguous()
|
| 1279 |
+
|
| 1280 |
+
total_loss = None
|
| 1281 |
+
if start_positions is not None and end_positions is not None:
|
| 1282 |
+
# If we are on multi-GPU, split add a dimension
|
| 1283 |
+
if len(start_positions.size()) > 1:
|
| 1284 |
+
start_positions = start_positions.squeeze(-1).to(start_logits.device)
|
| 1285 |
+
if len(end_positions.size()) > 1:
|
| 1286 |
+
end_positions = end_positions.squeeze(-1).to(end_logits.device)
|
| 1287 |
+
# sometimes the start/end positions are outside our model inputs, we ignore these terms
|
| 1288 |
+
ignored_index = start_logits.size(1)
|
| 1289 |
+
start_positions = start_positions.clamp(0, ignored_index)
|
| 1290 |
+
end_positions = end_positions.clamp(0, ignored_index)
|
| 1291 |
+
|
| 1292 |
+
loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
|
| 1293 |
+
start_loss = loss_fct(start_logits, start_positions)
|
| 1294 |
+
end_loss = loss_fct(end_logits, end_positions)
|
| 1295 |
+
total_loss = (start_loss + end_loss) / 2
|
| 1296 |
+
|
| 1297 |
+
if not return_dict:
|
| 1298 |
+
output = (start_logits, end_logits) + outputs[2:]
|
| 1299 |
+
return ((total_loss,) + output) if total_loss is not None else output
|
| 1300 |
+
|
| 1301 |
+
return QuestionAnsweringModelOutput(
|
| 1302 |
+
loss=total_loss,
|
| 1303 |
+
start_logits=start_logits,
|
| 1304 |
+
end_logits=end_logits,
|
| 1305 |
+
hidden_states=outputs.hidden_states,
|
| 1306 |
+
attentions=outputs.attentions,
|
| 1307 |
+
)
|
special_tokens_map.json
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"additional_special_tokens": [
|
| 3 |
+
"<extra_id_0>",
|
| 4 |
+
"<extra_id_1>",
|
| 5 |
+
"<extra_id_2>",
|
| 6 |
+
"<extra_id_3>",
|
| 7 |
+
"<extra_id_4>",
|
| 8 |
+
"<extra_id_5>",
|
| 9 |
+
"<extra_id_6>",
|
| 10 |
+
"<extra_id_7>",
|
| 11 |
+
"<extra_id_8>",
|
| 12 |
+
"<extra_id_9>",
|
| 13 |
+
"<extra_id_10>",
|
| 14 |
+
"<extra_id_11>",
|
| 15 |
+
"<extra_id_12>",
|
| 16 |
+
"<extra_id_13>",
|
| 17 |
+
"<extra_id_14>",
|
| 18 |
+
"<extra_id_15>",
|
| 19 |
+
"<extra_id_16>",
|
| 20 |
+
"<extra_id_17>",
|
| 21 |
+
"<extra_id_18>",
|
| 22 |
+
"<extra_id_19>",
|
| 23 |
+
"<extra_id_20>",
|
| 24 |
+
"<extra_id_21>",
|
| 25 |
+
"<extra_id_22>",
|
| 26 |
+
"<extra_id_23>",
|
| 27 |
+
"<extra_id_24>",
|
| 28 |
+
"<extra_id_25>"
|
| 29 |
+
],
|
| 30 |
+
"bos_token": {
|
| 31 |
+
"content": "<s>",
|
| 32 |
+
"lstrip": false,
|
| 33 |
+
"normalized": true,
|
| 34 |
+
"rstrip": false,
|
| 35 |
+
"single_word": false
|
| 36 |
+
},
|
| 37 |
+
"cls_token": {
|
| 38 |
+
"content": "<cls>",
|
| 39 |
+
"lstrip": false,
|
| 40 |
+
"normalized": true,
|
| 41 |
+
"rstrip": false,
|
| 42 |
+
"single_word": false
|
| 43 |
+
},
|
| 44 |
+
"eos_token": {
|
| 45 |
+
"content": "</s>",
|
| 46 |
+
"lstrip": false,
|
| 47 |
+
"normalized": true,
|
| 48 |
+
"rstrip": false,
|
| 49 |
+
"single_word": false
|
| 50 |
+
},
|
| 51 |
+
"mask_token": {
|
| 52 |
+
"content": "<mask>",
|
| 53 |
+
"lstrip": false,
|
| 54 |
+
"normalized": true,
|
| 55 |
+
"rstrip": false,
|
| 56 |
+
"single_word": false
|
| 57 |
+
},
|
| 58 |
+
"pad_token": {
|
| 59 |
+
"content": "<pad>",
|
| 60 |
+
"lstrip": false,
|
| 61 |
+
"normalized": true,
|
| 62 |
+
"rstrip": false,
|
| 63 |
+
"single_word": false
|
| 64 |
+
},
|
| 65 |
+
"sep_token": {
|
| 66 |
+
"content": "<sep>",
|
| 67 |
+
"lstrip": false,
|
| 68 |
+
"normalized": true,
|
| 69 |
+
"rstrip": false,
|
| 70 |
+
"single_word": false
|
| 71 |
+
}
|
| 72 |
+
}
|
tokenization_utf8_like_byte.py
ADDED
|
@@ -0,0 +1,271 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2021 T5 Authors and HuggingFace Inc. team.
|
| 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 |
+
"""Tokenization class for model ByT5."""
|
| 16 |
+
|
| 17 |
+
import warnings
|
| 18 |
+
from typing import List, Optional, Tuple
|
| 19 |
+
|
| 20 |
+
from transformers.tokenization_utils import AddedToken, PreTrainedTokenizer
|
| 21 |
+
from transformers.utils import logging
|
| 22 |
+
|
| 23 |
+
logger = logging.get_logger(__name__)
|
| 24 |
+
|
| 25 |
+
class UTF8LikeByteTokenizer(PreTrainedTokenizer):
|
| 26 |
+
"""
|
| 27 |
+
Construct a ByT5 tokenizer. ByT5 simply uses raw bytes utf-8 encoding.
|
| 28 |
+
|
| 29 |
+
This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
|
| 30 |
+
this superclass for more information regarding those methods.
|
| 31 |
+
|
| 32 |
+
Args:
|
| 33 |
+
eos_token (`str`, *optional*, defaults to `"</s>"`):
|
| 34 |
+
The end of sequence token.
|
| 35 |
+
|
| 36 |
+
<Tip>
|
| 37 |
+
|
| 38 |
+
When building a sequence using special tokens, this is not the token that is used for the end of sequence.
|
| 39 |
+
The token used is the `sep_token`.
|
| 40 |
+
|
| 41 |
+
</Tip>
|
| 42 |
+
|
| 43 |
+
unk_token (`str`, *optional*, defaults to `"<unk>"`):
|
| 44 |
+
The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
|
| 45 |
+
token instead.
|
| 46 |
+
pad_token (`str`, *optional*, defaults to `"<pad>"`):
|
| 47 |
+
The token used for padding, for example when batching sequences of different lengths.
|
| 48 |
+
extra_ids (`int`, *optional*, defaults to 125):
|
| 49 |
+
Add a number of extra ids added to the end of the vocabulary for use as sentinels. These tokens are
|
| 50 |
+
accessible as "<extra_id_{%d}>" where "{%d}" is a number between 0 and extra_ids-1. Extra tokens are
|
| 51 |
+
indexed from the end of the vocabulary up to beginning ("<extra_id_0>" is the last token in the vocabulary
|
| 52 |
+
like in ByT5 preprocessing see
|
| 53 |
+
[here](https://github.com/google-research/text-to-text-transfer-transformer/blob/9fd7b14a769417be33bc6c850f9598764913c833/t5/data/preprocessors.py#L2117)).
|
| 54 |
+
additional_special_tokens (`List[str]`, *optional*):
|
| 55 |
+
Additional special tokens used by the tokenizer.
|
| 56 |
+
"""
|
| 57 |
+
|
| 58 |
+
model_input_names = ["input_ids", "attention_mask"]
|
| 59 |
+
|
| 60 |
+
def __init__(
|
| 61 |
+
self,
|
| 62 |
+
bos_token="<s>",
|
| 63 |
+
eos_token="</s>",
|
| 64 |
+
pad_token="<pad>",
|
| 65 |
+
cls_token="<cls>",
|
| 66 |
+
sep_token="<sep>",
|
| 67 |
+
mask_token="<mask>",
|
| 68 |
+
extra_ids=26,
|
| 69 |
+
additional_special_tokens=None,
|
| 70 |
+
**kwargs,
|
| 71 |
+
) -> None:
|
| 72 |
+
# Add extra_ids to the special token list
|
| 73 |
+
if extra_ids > 0 and additional_special_tokens is None:
|
| 74 |
+
additional_special_tokens = [f"<extra_id_{i}>" for i in range(extra_ids)]
|
| 75 |
+
elif extra_ids > 0 and additional_special_tokens is not None and len(additional_special_tokens) > 0:
|
| 76 |
+
# Check that we have the right number of extra_id special tokens
|
| 77 |
+
extra_tokens = len(set(filter(lambda x: bool("extra_id" in str(x)), additional_special_tokens)))
|
| 78 |
+
if extra_tokens != extra_ids:
|
| 79 |
+
raise ValueError(
|
| 80 |
+
f"Both extra_ids ({extra_ids}) and additional_special_tokens ({additional_special_tokens}) are"
|
| 81 |
+
" provided to ByteTokenizer. In this case the additional_special_tokens must include the"
|
| 82 |
+
" extra_ids tokens"
|
| 83 |
+
)
|
| 84 |
+
|
| 85 |
+
bos_token = AddedToken(bos_token, lstrip=False, rstrip=False) if isinstance(bos_token, str) else bos_token
|
| 86 |
+
eos_token = AddedToken(eos_token, lstrip=False, rstrip=False) if isinstance(eos_token, str) else eos_token
|
| 87 |
+
pad_token = AddedToken(pad_token, lstrip=False, rstrip=False) if isinstance(pad_token, str) else pad_token
|
| 88 |
+
cls_token = AddedToken(cls_token, lstrip=False, rstrip=False) if isinstance(cls_token, str) else cls_token
|
| 89 |
+
sep_token = AddedToken(sep_token, lstrip=False, rstrip=False) if isinstance(sep_token, str) else sep_token
|
| 90 |
+
mask_token = AddedToken(mask_token, lstrip=False, rstrip=False) if isinstance(mask_token, str) else mask_token
|
| 91 |
+
|
| 92 |
+
# unk token needs to be in the vocab with correct index
|
| 93 |
+
self._added_tokens_decoder = {0: pad_token, 1: eos_token, 2: bos_token, 3: cls_token, 4: sep_token, 5: mask_token}
|
| 94 |
+
self.offset = len(self._added_tokens_decoder)
|
| 95 |
+
self._utf_vocab_size = 2**8 # utf is 8 bits
|
| 96 |
+
super().__init__(
|
| 97 |
+
bos_token=bos_token,
|
| 98 |
+
eos_token=eos_token,
|
| 99 |
+
pad_token=pad_token,
|
| 100 |
+
cls_token=cls_token,
|
| 101 |
+
sep_token=sep_token,
|
| 102 |
+
mask_token=mask_token,
|
| 103 |
+
extra_ids=0,
|
| 104 |
+
additional_special_tokens=additional_special_tokens, # TODO extra ids are not used :sweatywmile:
|
| 105 |
+
**kwargs,
|
| 106 |
+
)
|
| 107 |
+
|
| 108 |
+
@property
|
| 109 |
+
def vocab_size(self):
|
| 110 |
+
return self._utf_vocab_size
|
| 111 |
+
|
| 112 |
+
def get_vocab(self):
|
| 113 |
+
vocab = {
|
| 114 |
+
self.convert_ids_to_tokens(i): i for i in range(self.vocab_size + self.offset)
|
| 115 |
+
}
|
| 116 |
+
vocab.update(self.added_tokens_encoder)
|
| 117 |
+
return vocab
|
| 118 |
+
|
| 119 |
+
def _add_bos_if_not_present(self, token_ids: List[int]) -> List[int]:
|
| 120 |
+
"""Do not add bos again if user already added it."""
|
| 121 |
+
if len(token_ids) > 0 and token_ids[0] == self.bos_token_id:
|
| 122 |
+
warnings.warn(
|
| 123 |
+
f"This sequence already has {self.bos_token}. In future versions this behavior may lead to duplicated"
|
| 124 |
+
" bos tokens being added."
|
| 125 |
+
)
|
| 126 |
+
return token_ids
|
| 127 |
+
else:
|
| 128 |
+
return [self.bos_token_id] + token_ids
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
def _add_eos_if_not_present(self, token_ids: List[int]) -> List[int]:
|
| 133 |
+
"""Do not add eos again if user already added it."""
|
| 134 |
+
if len(token_ids) > 0 and token_ids[-1] == self.eos_token_id:
|
| 135 |
+
warnings.warn(
|
| 136 |
+
f"This sequence already has {self.eos_token}. In future versions this behavior may lead to duplicated"
|
| 137 |
+
" eos tokens being added."
|
| 138 |
+
)
|
| 139 |
+
return token_ids
|
| 140 |
+
else:
|
| 141 |
+
return token_ids + [self.eos_token_id]
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
def build_inputs_with_special_tokens(
|
| 145 |
+
self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
|
| 146 |
+
) -> List[int]:
|
| 147 |
+
"""
|
| 148 |
+
Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
|
| 149 |
+
adding special tokens. A sequence has the following format:
|
| 150 |
+
|
| 151 |
+
- single sequence: `X </s>`
|
| 152 |
+
- pair of sequences: `A </s> B </s>`
|
| 153 |
+
|
| 154 |
+
Args:
|
| 155 |
+
token_ids_0 (`List[int]`):
|
| 156 |
+
List of IDs to which the special tokens will be added.
|
| 157 |
+
token_ids_1 (`List[int]`, *optional*):
|
| 158 |
+
Optional second list of IDs for sequence pairs.
|
| 159 |
+
|
| 160 |
+
Returns:
|
| 161 |
+
`List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
|
| 162 |
+
"""
|
| 163 |
+
token_ids_0 = self._add_bos_if_not_present(token_ids_0)
|
| 164 |
+
token_ids_0 = self._add_eos_if_not_present(token_ids_0)
|
| 165 |
+
|
| 166 |
+
if token_ids_1 is None:
|
| 167 |
+
return token_ids_0
|
| 168 |
+
else:
|
| 169 |
+
token_ids_1 = self._add_bos_if_not_present(token_ids_1)
|
| 170 |
+
token_ids_1 = self._add_eos_if_not_present(token_ids_1)
|
| 171 |
+
return token_ids_0 + token_ids_1
|
| 172 |
+
|
| 173 |
+
def _tokenize(self, text: str) -> List[str]:
|
| 174 |
+
"""Take as input a string and return a list of strings (tokens) for words/sub-words"""
|
| 175 |
+
token_ids = []
|
| 176 |
+
for c in text:
|
| 177 |
+
token_ids.extend(self.unicode_to_bytes(ord(c)))
|
| 178 |
+
|
| 179 |
+
# Convert to string
|
| 180 |
+
token_ids = [str(i) for i in token_ids]
|
| 181 |
+
return token_ids
|
| 182 |
+
|
| 183 |
+
def _convert_token_to_id(self, token):
|
| 184 |
+
"""Converts a token (str) in an id using the vocab."""
|
| 185 |
+
token_id = int(token) + self.offset
|
| 186 |
+
return token_id
|
| 187 |
+
|
| 188 |
+
def _convert_id_to_token(self, index):
|
| 189 |
+
"""Converts an index (integer) in a token (str) using the vocab."""
|
| 190 |
+
return str(index - self.offset)
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
|
| 194 |
+
def convert_tokens_to_string(self, tokens):
|
| 195 |
+
token_id_with_special_tokens = []
|
| 196 |
+
for token in tokens:
|
| 197 |
+
try:
|
| 198 |
+
token_id = int(token)
|
| 199 |
+
token_id_with_special_tokens.append(token_id)
|
| 200 |
+
except ValueError:
|
| 201 |
+
token_id_with_special_tokens.append(token)
|
| 202 |
+
return self.decode_ids(token_id_with_special_tokens)
|
| 203 |
+
|
| 204 |
+
def decode_ids(self, tokens: List[int]) -> str:
|
| 205 |
+
decoded = ""
|
| 206 |
+
i = 0
|
| 207 |
+
try:
|
| 208 |
+
while i < len(tokens):
|
| 209 |
+
if type(tokens[i]) == str:
|
| 210 |
+
decoded += tokens[i]
|
| 211 |
+
i += 1
|
| 212 |
+
continue
|
| 213 |
+
|
| 214 |
+
if tokens[i] < 0b10000000:
|
| 215 |
+
decoded += chr(tokens[i])
|
| 216 |
+
i += 1
|
| 217 |
+
elif tokens[i] < 0b11000000:
|
| 218 |
+
decoded += chr(((tokens[i] & 0b00111111) << 7) + (tokens[i + 1] & 0b01111111))
|
| 219 |
+
i += 2
|
| 220 |
+
elif tokens[i] < 0b11100000:
|
| 221 |
+
decoded += chr(((tokens[i] & 0b00011111) << 13) + ((tokens[i + 1] & 0b00111111) << 7) + (tokens[i + 2] & 0b01111111))
|
| 222 |
+
i += 3
|
| 223 |
+
elif tokens[i] < 0b11110000:
|
| 224 |
+
decoded += chr(
|
| 225 |
+
((tokens[i] & 0b00001111) << 18) + ((tokens[i + 1] & 0b00111111) << 13) + ((tokens[i + 2] & 0b00111111) << 7) + (tokens[i + 3] & 0b01111111)
|
| 226 |
+
)
|
| 227 |
+
i += 4
|
| 228 |
+
else:
|
| 229 |
+
raise ValueError("invalid token")
|
| 230 |
+
except IndexError:
|
| 231 |
+
pass
|
| 232 |
+
return decoded
|
| 233 |
+
|
| 234 |
+
|
| 235 |
+
def unicode_to_bytes(self, codepoint: int) -> list[int]:
|
| 236 |
+
codepoint_bin = f"{codepoint:b}"
|
| 237 |
+
|
| 238 |
+
if len(codepoint_bin) <= 7: # 1byte char
|
| 239 |
+
codepoint_bin = f"{codepoint:07b}"
|
| 240 |
+
bytes_bin = [
|
| 241 |
+
"0" + codepoint_bin,
|
| 242 |
+
]
|
| 243 |
+
elif len(codepoint_bin) <= 13: # 2byte char
|
| 244 |
+
codepoint_bin = f"{codepoint:013b}"
|
| 245 |
+
bytes_bin = [
|
| 246 |
+
"10" + codepoint_bin[:6],
|
| 247 |
+
"0" + codepoint_bin[6:],
|
| 248 |
+
]
|
| 249 |
+
elif len(codepoint_bin) <= 18: # 3byte char
|
| 250 |
+
codepoint_bin = f"{codepoint:018b}"
|
| 251 |
+
bytes_bin = [
|
| 252 |
+
"110" + codepoint_bin[:5],
|
| 253 |
+
"10" + codepoint_bin[5:11],
|
| 254 |
+
"0" + codepoint_bin[11:],
|
| 255 |
+
]
|
| 256 |
+
elif len(codepoint_bin) <= 22: # 4byte char
|
| 257 |
+
codepoint_bin = f"{codepoint:022b}"
|
| 258 |
+
bytes_bin = [
|
| 259 |
+
"1110" + codepoint_bin[:4],
|
| 260 |
+
"110" + codepoint_bin[4:9],
|
| 261 |
+
"10" + codepoint_bin[9:15],
|
| 262 |
+
"0" + codepoint_bin[15:],
|
| 263 |
+
]
|
| 264 |
+
else:
|
| 265 |
+
raise ValueError("codepoint is too large")
|
| 266 |
+
|
| 267 |
+
return [int(byte, 2) for byte in bytes_bin]
|
| 268 |
+
|
| 269 |
+
# ByteTokenizer has no vocab file
|
| 270 |
+
def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
|
| 271 |
+
return ()
|
tokenizer_config.json
ADDED
|
@@ -0,0 +1,304 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"added_tokens_decoder": {
|
| 3 |
+
"0": {
|
| 4 |
+
"content": "<pad>",
|
| 5 |
+
"lstrip": false,
|
| 6 |
+
"normalized": true,
|
| 7 |
+
"rstrip": false,
|
| 8 |
+
"single_word": false,
|
| 9 |
+
"special": true
|
| 10 |
+
},
|
| 11 |
+
"1": {
|
| 12 |
+
"content": "</s>",
|
| 13 |
+
"lstrip": false,
|
| 14 |
+
"normalized": true,
|
| 15 |
+
"rstrip": false,
|
| 16 |
+
"single_word": false,
|
| 17 |
+
"special": true
|
| 18 |
+
},
|
| 19 |
+
"2": {
|
| 20 |
+
"content": "<s>",
|
| 21 |
+
"lstrip": false,
|
| 22 |
+
"normalized": true,
|
| 23 |
+
"rstrip": false,
|
| 24 |
+
"single_word": false,
|
| 25 |
+
"special": true
|
| 26 |
+
},
|
| 27 |
+
"3": {
|
| 28 |
+
"content": "<cls>",
|
| 29 |
+
"lstrip": false,
|
| 30 |
+
"normalized": true,
|
| 31 |
+
"rstrip": false,
|
| 32 |
+
"single_word": false,
|
| 33 |
+
"special": true
|
| 34 |
+
},
|
| 35 |
+
"4": {
|
| 36 |
+
"content": "<sep>",
|
| 37 |
+
"lstrip": false,
|
| 38 |
+
"normalized": true,
|
| 39 |
+
"rstrip": false,
|
| 40 |
+
"single_word": false,
|
| 41 |
+
"special": true
|
| 42 |
+
},
|
| 43 |
+
"5": {
|
| 44 |
+
"content": "<mask>",
|
| 45 |
+
"lstrip": false,
|
| 46 |
+
"normalized": true,
|
| 47 |
+
"rstrip": false,
|
| 48 |
+
"single_word": false,
|
| 49 |
+
"special": true
|
| 50 |
+
},
|
| 51 |
+
"262": {
|
| 52 |
+
"content": "<extra_id_0>",
|
| 53 |
+
"lstrip": false,
|
| 54 |
+
"normalized": false,
|
| 55 |
+
"rstrip": false,
|
| 56 |
+
"single_word": false,
|
| 57 |
+
"special": true
|
| 58 |
+
},
|
| 59 |
+
"263": {
|
| 60 |
+
"content": "<extra_id_1>",
|
| 61 |
+
"lstrip": false,
|
| 62 |
+
"normalized": false,
|
| 63 |
+
"rstrip": false,
|
| 64 |
+
"single_word": false,
|
| 65 |
+
"special": true
|
| 66 |
+
},
|
| 67 |
+
"264": {
|
| 68 |
+
"content": "<extra_id_2>",
|
| 69 |
+
"lstrip": false,
|
| 70 |
+
"normalized": false,
|
| 71 |
+
"rstrip": false,
|
| 72 |
+
"single_word": false,
|
| 73 |
+
"special": true
|
| 74 |
+
},
|
| 75 |
+
"265": {
|
| 76 |
+
"content": "<extra_id_3>",
|
| 77 |
+
"lstrip": false,
|
| 78 |
+
"normalized": false,
|
| 79 |
+
"rstrip": false,
|
| 80 |
+
"single_word": false,
|
| 81 |
+
"special": true
|
| 82 |
+
},
|
| 83 |
+
"266": {
|
| 84 |
+
"content": "<extra_id_4>",
|
| 85 |
+
"lstrip": false,
|
| 86 |
+
"normalized": false,
|
| 87 |
+
"rstrip": false,
|
| 88 |
+
"single_word": false,
|
| 89 |
+
"special": true
|
| 90 |
+
},
|
| 91 |
+
"267": {
|
| 92 |
+
"content": "<extra_id_5>",
|
| 93 |
+
"lstrip": false,
|
| 94 |
+
"normalized": false,
|
| 95 |
+
"rstrip": false,
|
| 96 |
+
"single_word": false,
|
| 97 |
+
"special": true
|
| 98 |
+
},
|
| 99 |
+
"268": {
|
| 100 |
+
"content": "<extra_id_6>",
|
| 101 |
+
"lstrip": false,
|
| 102 |
+
"normalized": false,
|
| 103 |
+
"rstrip": false,
|
| 104 |
+
"single_word": false,
|
| 105 |
+
"special": true
|
| 106 |
+
},
|
| 107 |
+
"269": {
|
| 108 |
+
"content": "<extra_id_7>",
|
| 109 |
+
"lstrip": false,
|
| 110 |
+
"normalized": false,
|
| 111 |
+
"rstrip": false,
|
| 112 |
+
"single_word": false,
|
| 113 |
+
"special": true
|
| 114 |
+
},
|
| 115 |
+
"270": {
|
| 116 |
+
"content": "<extra_id_8>",
|
| 117 |
+
"lstrip": false,
|
| 118 |
+
"normalized": false,
|
| 119 |
+
"rstrip": false,
|
| 120 |
+
"single_word": false,
|
| 121 |
+
"special": true
|
| 122 |
+
},
|
| 123 |
+
"271": {
|
| 124 |
+
"content": "<extra_id_9>",
|
| 125 |
+
"lstrip": false,
|
| 126 |
+
"normalized": false,
|
| 127 |
+
"rstrip": false,
|
| 128 |
+
"single_word": false,
|
| 129 |
+
"special": true
|
| 130 |
+
},
|
| 131 |
+
"272": {
|
| 132 |
+
"content": "<extra_id_10>",
|
| 133 |
+
"lstrip": false,
|
| 134 |
+
"normalized": false,
|
| 135 |
+
"rstrip": false,
|
| 136 |
+
"single_word": false,
|
| 137 |
+
"special": true
|
| 138 |
+
},
|
| 139 |
+
"273": {
|
| 140 |
+
"content": "<extra_id_11>",
|
| 141 |
+
"lstrip": false,
|
| 142 |
+
"normalized": false,
|
| 143 |
+
"rstrip": false,
|
| 144 |
+
"single_word": false,
|
| 145 |
+
"special": true
|
| 146 |
+
},
|
| 147 |
+
"274": {
|
| 148 |
+
"content": "<extra_id_12>",
|
| 149 |
+
"lstrip": false,
|
| 150 |
+
"normalized": false,
|
| 151 |
+
"rstrip": false,
|
| 152 |
+
"single_word": false,
|
| 153 |
+
"special": true
|
| 154 |
+
},
|
| 155 |
+
"275": {
|
| 156 |
+
"content": "<extra_id_13>",
|
| 157 |
+
"lstrip": false,
|
| 158 |
+
"normalized": false,
|
| 159 |
+
"rstrip": false,
|
| 160 |
+
"single_word": false,
|
| 161 |
+
"special": true
|
| 162 |
+
},
|
| 163 |
+
"276": {
|
| 164 |
+
"content": "<extra_id_14>",
|
| 165 |
+
"lstrip": false,
|
| 166 |
+
"normalized": false,
|
| 167 |
+
"rstrip": false,
|
| 168 |
+
"single_word": false,
|
| 169 |
+
"special": true
|
| 170 |
+
},
|
| 171 |
+
"277": {
|
| 172 |
+
"content": "<extra_id_15>",
|
| 173 |
+
"lstrip": false,
|
| 174 |
+
"normalized": false,
|
| 175 |
+
"rstrip": false,
|
| 176 |
+
"single_word": false,
|
| 177 |
+
"special": true
|
| 178 |
+
},
|
| 179 |
+
"278": {
|
| 180 |
+
"content": "<extra_id_16>",
|
| 181 |
+
"lstrip": false,
|
| 182 |
+
"normalized": false,
|
| 183 |
+
"rstrip": false,
|
| 184 |
+
"single_word": false,
|
| 185 |
+
"special": true
|
| 186 |
+
},
|
| 187 |
+
"279": {
|
| 188 |
+
"content": "<extra_id_17>",
|
| 189 |
+
"lstrip": false,
|
| 190 |
+
"normalized": false,
|
| 191 |
+
"rstrip": false,
|
| 192 |
+
"single_word": false,
|
| 193 |
+
"special": true
|
| 194 |
+
},
|
| 195 |
+
"280": {
|
| 196 |
+
"content": "<extra_id_18>",
|
| 197 |
+
"lstrip": false,
|
| 198 |
+
"normalized": false,
|
| 199 |
+
"rstrip": false,
|
| 200 |
+
"single_word": false,
|
| 201 |
+
"special": true
|
| 202 |
+
},
|
| 203 |
+
"281": {
|
| 204 |
+
"content": "<extra_id_19>",
|
| 205 |
+
"lstrip": false,
|
| 206 |
+
"normalized": false,
|
| 207 |
+
"rstrip": false,
|
| 208 |
+
"single_word": false,
|
| 209 |
+
"special": true
|
| 210 |
+
},
|
| 211 |
+
"282": {
|
| 212 |
+
"content": "<extra_id_20>",
|
| 213 |
+
"lstrip": false,
|
| 214 |
+
"normalized": false,
|
| 215 |
+
"rstrip": false,
|
| 216 |
+
"single_word": false,
|
| 217 |
+
"special": true
|
| 218 |
+
},
|
| 219 |
+
"283": {
|
| 220 |
+
"content": "<extra_id_21>",
|
| 221 |
+
"lstrip": false,
|
| 222 |
+
"normalized": false,
|
| 223 |
+
"rstrip": false,
|
| 224 |
+
"single_word": false,
|
| 225 |
+
"special": true
|
| 226 |
+
},
|
| 227 |
+
"284": {
|
| 228 |
+
"content": "<extra_id_22>",
|
| 229 |
+
"lstrip": false,
|
| 230 |
+
"normalized": false,
|
| 231 |
+
"rstrip": false,
|
| 232 |
+
"single_word": false,
|
| 233 |
+
"special": true
|
| 234 |
+
},
|
| 235 |
+
"285": {
|
| 236 |
+
"content": "<extra_id_23>",
|
| 237 |
+
"lstrip": false,
|
| 238 |
+
"normalized": false,
|
| 239 |
+
"rstrip": false,
|
| 240 |
+
"single_word": false,
|
| 241 |
+
"special": true
|
| 242 |
+
},
|
| 243 |
+
"286": {
|
| 244 |
+
"content": "<extra_id_24>",
|
| 245 |
+
"lstrip": false,
|
| 246 |
+
"normalized": false,
|
| 247 |
+
"rstrip": false,
|
| 248 |
+
"single_word": false,
|
| 249 |
+
"special": true
|
| 250 |
+
},
|
| 251 |
+
"287": {
|
| 252 |
+
"content": "<extra_id_25>",
|
| 253 |
+
"lstrip": false,
|
| 254 |
+
"normalized": false,
|
| 255 |
+
"rstrip": false,
|
| 256 |
+
"single_word": false,
|
| 257 |
+
"special": true
|
| 258 |
+
}
|
| 259 |
+
},
|
| 260 |
+
"additional_special_tokens": [
|
| 261 |
+
"<extra_id_0>",
|
| 262 |
+
"<extra_id_1>",
|
| 263 |
+
"<extra_id_2>",
|
| 264 |
+
"<extra_id_3>",
|
| 265 |
+
"<extra_id_4>",
|
| 266 |
+
"<extra_id_5>",
|
| 267 |
+
"<extra_id_6>",
|
| 268 |
+
"<extra_id_7>",
|
| 269 |
+
"<extra_id_8>",
|
| 270 |
+
"<extra_id_9>",
|
| 271 |
+
"<extra_id_10>",
|
| 272 |
+
"<extra_id_11>",
|
| 273 |
+
"<extra_id_12>",
|
| 274 |
+
"<extra_id_13>",
|
| 275 |
+
"<extra_id_14>",
|
| 276 |
+
"<extra_id_15>",
|
| 277 |
+
"<extra_id_16>",
|
| 278 |
+
"<extra_id_17>",
|
| 279 |
+
"<extra_id_18>",
|
| 280 |
+
"<extra_id_19>",
|
| 281 |
+
"<extra_id_20>",
|
| 282 |
+
"<extra_id_21>",
|
| 283 |
+
"<extra_id_22>",
|
| 284 |
+
"<extra_id_23>",
|
| 285 |
+
"<extra_id_24>",
|
| 286 |
+
"<extra_id_25>"
|
| 287 |
+
],
|
| 288 |
+
"auto_map": {
|
| 289 |
+
"AutoTokenizer": [
|
| 290 |
+
"tokenization_utf8_like_byte.UTF8LikeByteTokenizer",
|
| 291 |
+
null
|
| 292 |
+
]
|
| 293 |
+
},
|
| 294 |
+
"bos_token": "<s>",
|
| 295 |
+
"clean_up_tokenization_spaces": true,
|
| 296 |
+
"cls_token": "<cls>",
|
| 297 |
+
"eos_token": "</s>",
|
| 298 |
+
"extra_ids": 0,
|
| 299 |
+
"mask_token": "<mask>",
|
| 300 |
+
"model_max_length": 1000000000000000019884624838656,
|
| 301 |
+
"pad_token": "<pad>",
|
| 302 |
+
"sep_token": "<sep>",
|
| 303 |
+
"tokenizer_class": "UTF8LikeByteTokenizer"
|
| 304 |
+
}
|