Upload folder using huggingface_hub
Browse files- README.md +134 -0
- bert_layers.py +1075 -0
- bert_padding.py +159 -0
- config.json +30 -0
- configuration_bert.py +25 -0
- flash_attn_triton.py +1114 -0
- pytorch_model.bin +3 -0
- special_tokens_map.json +7 -0
- tokenization_SEA_BPE.py +292 -0
- tokenizer.model +3 -0
- tokenizer_config.json +17 -0
README.md
ADDED
@@ -0,0 +1,134 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
---
|
2 |
+
license: mit
|
3 |
+
language:
|
4 |
+
- en
|
5 |
+
- zh
|
6 |
+
- id
|
7 |
+
- ms
|
8 |
+
- th
|
9 |
+
- vi
|
10 |
+
- tl
|
11 |
+
- ta
|
12 |
+
- my
|
13 |
+
- km
|
14 |
+
- lo
|
15 |
+
inference: false
|
16 |
+
---
|
17 |
+
# SEA-LION-BERT
|
18 |
+
|
19 |
+
SEA-LION stands for <i>Southeast Asian Languages In One Network</i>.
|
20 |
+
|
21 |
+
This is the card for the SEA-LION-BERT base model.
|
22 |
+
|
23 |
+
## How To Use
|
24 |
+
|
25 |
+
```python
|
26 |
+
from transformers import AutoModelForMaskedLM, AutoTokenizer
|
27 |
+
|
28 |
+
tokenizer = AutoTokenizer.from_pretrained('aisingapore/sealion-bert-base', trust_remote_code=True)
|
29 |
+
model = AutoModelForMaskedLM.from_pretrained('aisingapore/sealion-bert-base', trust_remote_code=True)
|
30 |
+
|
31 |
+
# prepare input
|
32 |
+
text = "Give me a <|mask|>!!!"
|
33 |
+
encoded_input = tokenizer(text, return_tensors='pt')
|
34 |
+
|
35 |
+
```
|
36 |
+
|
37 |
+
## Model Details
|
38 |
+
|
39 |
+
### Model Description
|
40 |
+
|
41 |
+
The SEA-LION-BERT model is built on the MosaicBERT architecture and has a vocabulary size of 256K.
|
42 |
+
|
43 |
+
For tokenization, the model employs our custom SEABPETokenizer, which is specially tailored for SEA languages, ensuring optimal model performance.
|
44 |
+
|
45 |
+
The training data for SEA-LION-BERT encompasses 980B tokens.
|
46 |
+
|
47 |
+
- **Developed by:** Products Pillar, AI Singapore
|
48 |
+
- **Funded by:** Singapore NRF
|
49 |
+
- **Model type:** Encoder
|
50 |
+
- **Languages:** English, Chinese, Indonesian, Malay, Thai, Vietnamese, Filipino, Tamil, Burmese, Khmer, Lao
|
51 |
+
- **License:** MIT License
|
52 |
+
|
53 |
+
## Training Details
|
54 |
+
|
55 |
+
### Data
|
56 |
+
|
57 |
+
SEA-LION was trained on 790B tokens of the following data:
|
58 |
+
|
59 |
+
| Data Source | Tokens | Percentage |
|
60 |
+
|---------------------------|-------:|:----------:|
|
61 |
+
| RefinedWeb - English | 571.3B | 72.26% |
|
62 |
+
| mC4 - Chinese | 91.2B | 11.54% |
|
63 |
+
| mC4 - Indonesian | 14.7B | 1.86% |
|
64 |
+
| mC4 - Malay | 2.9B | 0.36% |
|
65 |
+
| mC4 - Filipino | 5.3B | 0.67% |
|
66 |
+
| mC4 - Burmese | 4.9B | 0.61% |
|
67 |
+
| mC4 - Vietnamese | 63.4B | 8.02% |
|
68 |
+
| mC4 - Thai | 21.6B | 2.74% |
|
69 |
+
| mC4 - Lao | 1.1B | 0.14% |
|
70 |
+
| mC4 - Khmer | 3.9B | 0.50% |
|
71 |
+
| mC4 - Tamil | 10.2B | 1.29% |
|
72 |
+
|
73 |
+
### Infrastructure
|
74 |
+
|
75 |
+
SEA-LION was trained using [MosaicML Composer](https://github.com/mosaicml/composer)
|
76 |
+
on the following hardware:
|
77 |
+
|
78 |
+
| Training Details | SEA-LION-BERT |
|
79 |
+
|----------------------|:-------------:|
|
80 |
+
| Nvidia A100 40GB GPU | 4 |
|
81 |
+
| Training Duration | 14 days |
|
82 |
+
|
83 |
+
|
84 |
+
### Configuration
|
85 |
+
|
86 |
+
| HyperParameter | SEA-LION-BERT |
|
87 |
+
|-------------------|:-----------------------:|
|
88 |
+
| Precision | bfloat16 |
|
89 |
+
| Optimizer | decoupled_adamw |
|
90 |
+
| Scheduler | linear_decay_with_warmup|
|
91 |
+
| Learning Rate | 5e-4 |
|
92 |
+
| Global Batch Size | 448 |
|
93 |
+
| Micro Batch Size | 56 |
|
94 |
+
|
95 |
+
|
96 |
+
## Technical Specifications
|
97 |
+
|
98 |
+
### Model Architecture and Objective
|
99 |
+
|
100 |
+
SEA-LION-BERT is an encoder model using the MosaicBERT architecture.
|
101 |
+
|
102 |
+
| Parameter | SEA-LION-BERT |
|
103 |
+
|-----------------|:-------------:|
|
104 |
+
| Layers | 12 |
|
105 |
+
| d_model | 768 |
|
106 |
+
| head_dim | 12 |
|
107 |
+
| Vocabulary | 256000 |
|
108 |
+
| Sequence Length | 128 |
|
109 |
+
|
110 |
+
|
111 |
+
### Tokenizer Details
|
112 |
+
|
113 |
+
We sample 20M lines from the training data to train the tokenizer.<br>
|
114 |
+
The framework for training is [SentencePiece](https://github.com/google/sentencepiece).<br>
|
115 |
+
The tokenizer type is Byte-Pair Encoding (BPE).
|
116 |
+
|
117 |
+
|
118 |
+
## The Team
|
119 |
+
|
120 |
+
Montalan Jann Railey<br>
|
121 |
+
Nguyen Thanh Ngan<br>
|
122 |
+
Rengarajan Hamsawardhini<br>
|
123 |
+
Teo Leslie<br>
|
124 |
+
Tjhi William<br>
|
125 |
+
|
126 |
+
|
127 |
+
## Acknowledgements
|
128 |
+
|
129 |
+
AI Singapore is a national programme supported by the National Research Foundation, Singapore and hosted by the National University of Singapore.
|
130 |
+
Any opinions, findings and conclusions or recommendations expressed in this material are those of the author(s) and do not reflect the views of National Research Foundation, Singapore.
|
131 |
+
|
132 |
+
## Contact
|
133 |
+
|
134 |
+
For more info, please contact us at sealion@aisingapore.org
|
bert_layers.py
ADDED
@@ -0,0 +1,1075 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright 2022 MosaicML Examples authors
|
2 |
+
# SPDX-License-Identifier: Apache-2.0
|
3 |
+
|
4 |
+
# Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
|
5 |
+
# Copyright (c) 2018-2021, NVIDIA CORPORATION. All rights reserved.
|
6 |
+
# Copyright (c) 2022, Tri Dao.
|
7 |
+
|
8 |
+
"""Implements Mosaic BERT, with an eye towards the Hugging Face API.
|
9 |
+
|
10 |
+
Mosaic BERT improves performance over Hugging Face BERT through the following:
|
11 |
+
|
12 |
+
1. ALiBi. This architectural change removes positional embeddings and instead encodes positional
|
13 |
+
information through attention biases based on query-key position distance. It improves the effectiveness
|
14 |
+
of training with shorter sequence lengths by enabling extrapolation to longer sequences.
|
15 |
+
|
16 |
+
2. Gated Linear Units (GLU). This architectural change replaces the FFN component of the BERT layer
|
17 |
+
to improve overall expressiveness, providing better convergence properties.
|
18 |
+
|
19 |
+
3. Flash Attention. The Mosaic BERT's self-attention layer makes use of Flash Attention, which dramatically
|
20 |
+
improves the speed of self-attention. Our implementation utilizes a bleeding edge implementation that
|
21 |
+
supports attention biases, which allows us to use Flash Attention with ALiBi.
|
22 |
+
|
23 |
+
4. Unpadding. Padding is often used to simplify batching across sequences of different lengths. Standard BERT
|
24 |
+
implementations waste computation on padded tokens. Mosaic BERT internally unpads to reduce unnecessary computation
|
25 |
+
and improve speed. It does this without changing how the user interfaces with the model, thereby
|
26 |
+
preserving the simple API of standard implementations.
|
27 |
+
|
28 |
+
|
29 |
+
Currently, Mosaic BERT is available for masked language modeling :class:`BertForMaskedLM` and sequence
|
30 |
+
classification :class:`BertForSequenceClassification`. We aim to expand this catalogue in future releases.
|
31 |
+
|
32 |
+
See :file:`./mosaic_bert.py` for utilities to simplify working with Mosaic BERT in Composer, and for example usage
|
33 |
+
of the core Mosaic BERT classes.
|
34 |
+
"""
|
35 |
+
|
36 |
+
import copy
|
37 |
+
import logging
|
38 |
+
import math
|
39 |
+
import warnings
|
40 |
+
from typing import List, Optional, Tuple, Union
|
41 |
+
|
42 |
+
import torch
|
43 |
+
import torch.nn as nn
|
44 |
+
from einops import rearrange
|
45 |
+
from torch.nn.modules.utils import consume_prefix_in_state_dict_if_present
|
46 |
+
from transformers.activations import ACT2FN
|
47 |
+
from transformers.modeling_outputs import (MaskedLMOutput,
|
48 |
+
SequenceClassifierOutput)
|
49 |
+
from transformers.models.bert.modeling_bert import BertPreTrainedModel
|
50 |
+
|
51 |
+
from .bert_padding import (index_first_axis,
|
52 |
+
index_put_first_axis, pad_input,
|
53 |
+
unpad_input, unpad_input_only)
|
54 |
+
from .configuration_bert import BertConfig
|
55 |
+
|
56 |
+
try:
|
57 |
+
from .flash_attn_triton import flash_attn_qkvpacked_func
|
58 |
+
except ImportError as e:
|
59 |
+
flash_attn_qkvpacked_func = None
|
60 |
+
|
61 |
+
logger = logging.getLogger(__name__)
|
62 |
+
|
63 |
+
|
64 |
+
class BertEmbeddings(nn.Module):
|
65 |
+
"""Construct the embeddings for words, ignoring position.
|
66 |
+
|
67 |
+
There are no positional embeddings since we use ALiBi and token_type
|
68 |
+
embeddings.
|
69 |
+
|
70 |
+
This module is modeled after the Hugging Face BERT's
|
71 |
+
:class:`~transformers.model.bert.modeling_bert.BertEmbeddings`, but is
|
72 |
+
modified as part of Mosaic BERT's ALiBi implementation. The key change is
|
73 |
+
that position embeddings are removed. Position information instead comes
|
74 |
+
from attention biases that scale linearly with the position distance
|
75 |
+
between query and key tokens.
|
76 |
+
|
77 |
+
This module ignores the `position_ids` input to the `forward` method.
|
78 |
+
"""
|
79 |
+
|
80 |
+
def __init__(self, config):
|
81 |
+
super().__init__()
|
82 |
+
self.word_embeddings = nn.Embedding(config.vocab_size,
|
83 |
+
config.hidden_size,
|
84 |
+
padding_idx=config.pad_token_id)
|
85 |
+
# ALiBi doesn't use position embeddings
|
86 |
+
self.token_type_embeddings = nn.Embedding(config.type_vocab_size,
|
87 |
+
config.hidden_size)
|
88 |
+
|
89 |
+
# self.LayerNorm is not snake-cased to stick with TensorFlow model
|
90 |
+
# variable name and be able to load any TensorFlow checkpoint file
|
91 |
+
self.LayerNorm = nn.LayerNorm(config.hidden_size,
|
92 |
+
eps=config.layer_norm_eps)
|
93 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
94 |
+
self.register_buffer('token_type_ids',
|
95 |
+
torch.zeros(config.max_position_embeddings,
|
96 |
+
dtype=torch.long),
|
97 |
+
persistent=False)
|
98 |
+
|
99 |
+
def forward(
|
100 |
+
self,
|
101 |
+
input_ids: Optional[torch.LongTensor] = None,
|
102 |
+
token_type_ids: Optional[torch.LongTensor] = None,
|
103 |
+
position_ids: Optional[torch.LongTensor] = None,
|
104 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
105 |
+
past_key_values_length: int = 0,
|
106 |
+
) -> torch.Tensor:
|
107 |
+
if (input_ids is not None) == (inputs_embeds is not None):
|
108 |
+
raise ValueError('Must specify either input_ids or input_embeds!')
|
109 |
+
if input_ids is not None:
|
110 |
+
input_shape = input_ids.size()
|
111 |
+
else:
|
112 |
+
assert inputs_embeds is not None # just for type checking
|
113 |
+
input_shape = inputs_embeds.size()[:-1]
|
114 |
+
|
115 |
+
seq_length = input_shape[1]
|
116 |
+
|
117 |
+
if position_ids is None:
|
118 |
+
# great! ALiBi
|
119 |
+
pass
|
120 |
+
|
121 |
+
# Setting the token_type_ids to the registered buffer in constructor
|
122 |
+
# where it is all zeros, which usually occurs when it's auto-generated;
|
123 |
+
# registered buffer helps users when tracing the model without passing
|
124 |
+
# token_type_ids, solves issue #5664
|
125 |
+
if token_type_ids is None:
|
126 |
+
if hasattr(self, 'token_type_ids'):
|
127 |
+
assert isinstance(self.token_type_ids, torch.LongTensor)
|
128 |
+
buffered_token_type_ids = self.token_type_ids[:, :seq_length]
|
129 |
+
buffered_token_type_ids_expanded = buffered_token_type_ids.expand(
|
130 |
+
input_shape[0], seq_length)
|
131 |
+
token_type_ids = buffered_token_type_ids_expanded # type: ignore
|
132 |
+
else:
|
133 |
+
token_type_ids = torch.zeros(input_shape, # type: ignore
|
134 |
+
dtype=torch.long,
|
135 |
+
device=self.word_embeddings.device) # type: ignore # yapf: disable
|
136 |
+
|
137 |
+
if inputs_embeds is None:
|
138 |
+
inputs_embeds = self.word_embeddings(input_ids)
|
139 |
+
token_type_embeddings = self.token_type_embeddings(token_type_ids)
|
140 |
+
|
141 |
+
embeddings = inputs_embeds + token_type_embeddings
|
142 |
+
# no position embeddings! ALiBi
|
143 |
+
embeddings = self.LayerNorm(embeddings)
|
144 |
+
embeddings = self.dropout(embeddings)
|
145 |
+
return embeddings
|
146 |
+
|
147 |
+
|
148 |
+
class BertUnpadSelfAttention(nn.Module):
|
149 |
+
"""Performs multi-headed self attention on a batch of unpadded sequences.
|
150 |
+
|
151 |
+
If Triton is installed, this module uses Flash Attention to greatly improve throughput.
|
152 |
+
The Flash Attention implementation used in Mosaic BERT supports arbitrary attention biases (which
|
153 |
+
we use to implement ALiBi), but does not support attention dropout. If either Triton is not installed
|
154 |
+
or `config.attention_probs_dropout_prob > 0`, the implementation will default to a
|
155 |
+
math-equivalent pytorch version, which is much slower.
|
156 |
+
|
157 |
+
See `forward` method for additional detail.
|
158 |
+
"""
|
159 |
+
|
160 |
+
def __init__(self, config):
|
161 |
+
super().__init__()
|
162 |
+
if config.hidden_size % config.num_attention_heads != 0 and not hasattr(
|
163 |
+
config, 'embedding_size'):
|
164 |
+
raise ValueError(
|
165 |
+
f'The hidden size ({config.hidden_size}) is not a multiple of the number of attention '
|
166 |
+
f'heads ({config.num_attention_heads})')
|
167 |
+
|
168 |
+
self.num_attention_heads = config.num_attention_heads
|
169 |
+
self.attention_head_size = int(config.hidden_size /
|
170 |
+
config.num_attention_heads)
|
171 |
+
self.all_head_size = self.num_attention_heads * self.attention_head_size
|
172 |
+
self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
|
173 |
+
self.p_dropout = config.attention_probs_dropout_prob
|
174 |
+
self.Wqkv = nn.Linear(self.all_head_size, 3 * config.hidden_size)
|
175 |
+
|
176 |
+
# Warn if defaulting to pytorch because of import issues
|
177 |
+
if flash_attn_qkvpacked_func is None:
|
178 |
+
warnings.warn(
|
179 |
+
'Unable to import Triton; defaulting MosaicBERT attention implementation to pytorch (this will reduce throughput when using this model).'
|
180 |
+
)
|
181 |
+
|
182 |
+
def forward(self, hidden_states: torch.Tensor, cu_seqlens: torch.Tensor,
|
183 |
+
max_seqlen_in_batch: int, indices: torch.Tensor,
|
184 |
+
attn_mask: torch.Tensor, bias: torch.Tensor) -> torch.Tensor:
|
185 |
+
"""Perform self-attention.
|
186 |
+
|
187 |
+
If dropout is zero, then we can use the Triton kernel, so we do that. However, if not, we send through a standard PyTorch
|
188 |
+
implementation of self-attention.
|
189 |
+
|
190 |
+
The arguments are unpadded, and our implementations of attention require padded arguments,
|
191 |
+
so we first call `pad_input`. Once we compute attention, we re-unpad our outputs for the other layers.
|
192 |
+
The pad/unpad operations add overhead, but not sending pad tokens through ffs saves compute.
|
193 |
+
It is possible to write an unpadded implementation of attention (in Triton and PyTorch), which we will eventually do.
|
194 |
+
|
195 |
+
Args:
|
196 |
+
hidden_states: (total_nnz, dim)
|
197 |
+
cu_seqlens: (batch + 1,)
|
198 |
+
max_seqlen_in_batch: int
|
199 |
+
indices: (total_nnz,)
|
200 |
+
attn_mask: (batch, max_seqlen_in_batch)
|
201 |
+
bias: (batch, heads, max_seqlen_in_batch, max_seqlen_in_batch)
|
202 |
+
|
203 |
+
Returns:
|
204 |
+
attention: (total_nnz, dim)
|
205 |
+
"""
|
206 |
+
qkv = self.Wqkv(hidden_states)
|
207 |
+
qkv = pad_input(qkv, indices, cu_seqlens.shape[0] - 1,
|
208 |
+
max_seqlen_in_batch) # batch, max_seqlen_in_batch, thd
|
209 |
+
qkv = rearrange(qkv,
|
210 |
+
'b s (t h d) -> b s t h d',
|
211 |
+
t=3,
|
212 |
+
h=self.num_attention_heads)
|
213 |
+
if self.p_dropout or flash_attn_qkvpacked_func is None:
|
214 |
+
# if we have nonzero attention dropout (e.g. during fine-tuning) or no Triton, compute attention in PyTorch
|
215 |
+
q = qkv[:, :, 0, :, :].permute(0, 2, 1, 3) # b h s d
|
216 |
+
k = qkv[:, :, 1, :, :].permute(0, 2, 3, 1) # b h d s
|
217 |
+
v = qkv[:, :, 2, :, :].permute(0, 2, 1, 3) # b h s d
|
218 |
+
attention_scores = torch.matmul(q, k) / math.sqrt(
|
219 |
+
self.attention_head_size)
|
220 |
+
attention_scores = attention_scores + bias
|
221 |
+
attention_probs = nn.functional.softmax(attention_scores, dim=-1)
|
222 |
+
attention_probs = self.dropout(attention_probs)
|
223 |
+
attention = torch.matmul(attention_probs, v).permute(0, 2, 1,
|
224 |
+
3) # b s h d
|
225 |
+
else:
|
226 |
+
# Triton implementation only supports 0 attention dropout
|
227 |
+
convert_dtype = qkv.dtype not in [torch.float16, torch.bfloat16]
|
228 |
+
if convert_dtype:
|
229 |
+
# Triton implementation only supports fp16 and bf16
|
230 |
+
orig_dtype = qkv.dtype
|
231 |
+
qkv = qkv.to(torch.float16)
|
232 |
+
bias_dtype = bias.dtype
|
233 |
+
bias = bias.to(torch.float16)
|
234 |
+
attention = flash_attn_qkvpacked_func(qkv, bias)
|
235 |
+
attention = attention.to(orig_dtype)
|
236 |
+
bias = bias.to(bias_dtype)
|
237 |
+
else:
|
238 |
+
attention = flash_attn_qkvpacked_func(qkv, bias)
|
239 |
+
|
240 |
+
# attn_mask is 1 for attend and 0 for don't
|
241 |
+
attention = unpad_input_only(attention, torch.squeeze(attn_mask) == 1)
|
242 |
+
return rearrange(attention, 'nnz h d -> nnz (h d)')
|
243 |
+
|
244 |
+
|
245 |
+
# Copy of transformer's library BertSelfOutput that will not be caught by surgery methods looking for HF BERT modules.
|
246 |
+
class BertSelfOutput(nn.Module):
|
247 |
+
"""Computes the output of the attention layer.
|
248 |
+
|
249 |
+
This module is modeled after the Hugging Face BERT's
|
250 |
+
:class:`~transformers.model.bert.modeling_bert.BertSelfOutput`.
|
251 |
+
The implementation is identical. Rather than use the original module
|
252 |
+
directly, we re-implement it here so that Mosaic BERT's modules will not
|
253 |
+
be affected by any Composer surgery algorithm that modifies Hugging Face
|
254 |
+
BERT modules.
|
255 |
+
"""
|
256 |
+
|
257 |
+
def __init__(self, config):
|
258 |
+
super().__init__()
|
259 |
+
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
|
260 |
+
self.LayerNorm = nn.LayerNorm(config.hidden_size,
|
261 |
+
eps=config.layer_norm_eps)
|
262 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
263 |
+
|
264 |
+
def forward(self, hidden_states: torch.Tensor,
|
265 |
+
input_tensor: torch.Tensor) -> torch.Tensor:
|
266 |
+
hidden_states = self.dense(hidden_states)
|
267 |
+
hidden_states = self.dropout(hidden_states)
|
268 |
+
hidden_states = self.LayerNorm(hidden_states + input_tensor)
|
269 |
+
return hidden_states
|
270 |
+
|
271 |
+
|
272 |
+
class BertUnpadAttention(nn.Module):
|
273 |
+
"""Chains attention, Dropout, and LayerNorm for Mosaic BERT."""
|
274 |
+
|
275 |
+
def __init__(self, config):
|
276 |
+
super().__init__()
|
277 |
+
self.self = BertUnpadSelfAttention(config)
|
278 |
+
self.output = BertSelfOutput(config)
|
279 |
+
|
280 |
+
def forward(
|
281 |
+
self,
|
282 |
+
input_tensor: torch.Tensor,
|
283 |
+
cu_seqlens: torch.Tensor,
|
284 |
+
max_s: int,
|
285 |
+
subset_idx: Optional[torch.Tensor] = None,
|
286 |
+
indices: Optional[torch.Tensor] = None,
|
287 |
+
attn_mask: Optional[torch.Tensor] = None,
|
288 |
+
bias: Optional[torch.Tensor] = None,
|
289 |
+
) -> torch.Tensor:
|
290 |
+
"""Forward pass for scaled self-attention without padding.
|
291 |
+
|
292 |
+
Arguments:
|
293 |
+
input_tensor: (total_nnz, dim)
|
294 |
+
cu_seqlens: (batch + 1,)
|
295 |
+
max_s: int
|
296 |
+
subset_idx: () set of indices whose values we care about at the end of the layer
|
297 |
+
(e.g., the masked tokens, if this is the final layer).
|
298 |
+
indices: None or (total_nnz,)
|
299 |
+
attn_mask: None or (batch, max_seqlen_in_batch)
|
300 |
+
bias: None or (batch, heads, max_seqlen_in_batch, max_seqlen_in_batch)
|
301 |
+
"""
|
302 |
+
self_output = self.self(input_tensor, cu_seqlens, max_s, indices,
|
303 |
+
attn_mask, bias)
|
304 |
+
if subset_idx is not None:
|
305 |
+
return self.output(index_first_axis(self_output, subset_idx),
|
306 |
+
index_first_axis(input_tensor, subset_idx))
|
307 |
+
else:
|
308 |
+
return self.output(self_output, input_tensor)
|
309 |
+
|
310 |
+
|
311 |
+
class BertGatedLinearUnitMLP(nn.Module):
|
312 |
+
"""Applies the FFN at the end of each Mosaic BERT layer.
|
313 |
+
|
314 |
+
Compared to the default BERT architecture, this block replaces :class:`~transformers.model.bert.modeling_bert.BertIntermediate`
|
315 |
+
and :class:`~transformers.model.bert.modeling_bert.SelfOutput` with a single module that has similar functionality, but
|
316 |
+
introduces Gated Linear Units.
|
317 |
+
|
318 |
+
Note: Mosaic BERT adds parameters in order to implement Gated Linear Units. To keep parameter count consistent with that of a
|
319 |
+
standard Hugging Face BERT, scale down `config.intermediate_size` by 2/3. For example, a Mosaic BERT constructed with
|
320 |
+
`config.intermediate_size=2048` will have the same parameter footprint as its Hugging Face BERT counterpart constructed
|
321 |
+
with the `config.intermediate_size=3072`.
|
322 |
+
However, in most cases it will not be necessary to adjust `config.intermediate_size` since, despite the increased
|
323 |
+
parameter size, Mosaic BERT typically offers a net higher throughput than a Hugging Face BERT built from the same `config`.
|
324 |
+
"""
|
325 |
+
|
326 |
+
def __init__(self, config):
|
327 |
+
super().__init__()
|
328 |
+
self.config = config
|
329 |
+
self.gated_layers = nn.Linear(config.hidden_size,
|
330 |
+
config.intermediate_size * 2,
|
331 |
+
bias=False)
|
332 |
+
self.act = nn.GELU(approximate='none')
|
333 |
+
self.wo = nn.Linear(config.intermediate_size, config.hidden_size)
|
334 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
335 |
+
self.layernorm = nn.LayerNorm(config.hidden_size,
|
336 |
+
eps=config.layer_norm_eps)
|
337 |
+
|
338 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
339 |
+
"""Compute new hidden states from current hidden states.
|
340 |
+
|
341 |
+
Args:
|
342 |
+
hidden_states (torch.Tensor): The (unpadded) hidden states from
|
343 |
+
the attention layer [nnz, dim].
|
344 |
+
"""
|
345 |
+
residual_connection = hidden_states
|
346 |
+
# compute the activation
|
347 |
+
hidden_states = self.gated_layers(hidden_states)
|
348 |
+
gated = hidden_states[:, :self.config.intermediate_size]
|
349 |
+
non_gated = hidden_states[:, self.config.intermediate_size:]
|
350 |
+
hidden_states = self.act(gated) * non_gated
|
351 |
+
hidden_states = self.dropout(hidden_states)
|
352 |
+
# multiply by the second matrix
|
353 |
+
hidden_states = self.wo(hidden_states)
|
354 |
+
# add the residual connection and post-LN
|
355 |
+
hidden_states = self.layernorm(hidden_states + residual_connection)
|
356 |
+
return hidden_states
|
357 |
+
|
358 |
+
|
359 |
+
class BertLayer(nn.Module):
|
360 |
+
"""Composes the Mosaic BERT attention and FFN blocks into a single layer."""
|
361 |
+
|
362 |
+
def __init__(self, config):
|
363 |
+
super(BertLayer, self).__init__()
|
364 |
+
self.attention = BertUnpadAttention(config)
|
365 |
+
self.mlp = BertGatedLinearUnitMLP(config)
|
366 |
+
|
367 |
+
def forward(
|
368 |
+
self,
|
369 |
+
hidden_states: torch.Tensor,
|
370 |
+
cu_seqlens: torch.Tensor,
|
371 |
+
seqlen: int,
|
372 |
+
subset_idx: Optional[torch.Tensor] = None,
|
373 |
+
indices: Optional[torch.Tensor] = None,
|
374 |
+
attn_mask: Optional[torch.Tensor] = None,
|
375 |
+
bias: Optional[torch.Tensor] = None,
|
376 |
+
) -> torch.Tensor:
|
377 |
+
"""Forward pass for a BERT layer, including both attention and MLP.
|
378 |
+
|
379 |
+
Args:
|
380 |
+
hidden_states: (total_nnz, dim)
|
381 |
+
cu_seqlens: (batch + 1,)
|
382 |
+
seqlen: int
|
383 |
+
subset_idx: () set of indices whose values we care about at the end of the layer
|
384 |
+
(e.g., the masked tokens, if this is the final layer).
|
385 |
+
indices: None or (total_nnz,)
|
386 |
+
attn_mask: None or (batch, max_seqlen_in_batch)
|
387 |
+
bias: None or (batch, heads, max_seqlen_in_batch, max_seqlen_in_batch)
|
388 |
+
"""
|
389 |
+
attention_output = self.attention(hidden_states, cu_seqlens, seqlen,
|
390 |
+
subset_idx, indices, attn_mask, bias)
|
391 |
+
layer_output = self.mlp(attention_output)
|
392 |
+
return layer_output
|
393 |
+
|
394 |
+
|
395 |
+
class BertEncoder(nn.Module):
|
396 |
+
"""A stack of BERT layers providing the backbone of Mosaic BERT.
|
397 |
+
|
398 |
+
This module is modeled after the Hugging Face BERT's :class:`~transformers.model.bert.modeling_bert.BertEncoder`,
|
399 |
+
but with substantial modifications to implement unpadding and ALiBi.
|
400 |
+
|
401 |
+
Compared to the analogous Hugging Face BERT module, this module handles unpadding to reduce unnecessary computation
|
402 |
+
at padded tokens, and pre-computes attention biases to implement ALiBi.
|
403 |
+
"""
|
404 |
+
|
405 |
+
def __init__(self, config):
|
406 |
+
super().__init__()
|
407 |
+
layer = BertLayer(config)
|
408 |
+
self.layer = nn.ModuleList(
|
409 |
+
[copy.deepcopy(layer) for _ in range(config.num_hidden_layers)])
|
410 |
+
|
411 |
+
self.num_attention_heads = config.num_attention_heads
|
412 |
+
|
413 |
+
# The alibi mask will be dynamically expanded if it is too small for
|
414 |
+
# the input the model receives. But it generally helps to initialize it
|
415 |
+
# to a reasonably large size to help pre-allocate CUDA memory.
|
416 |
+
# The default `alibi_starting_size` is 512.
|
417 |
+
self._current_alibi_size = int(config.alibi_starting_size)
|
418 |
+
self.alibi = torch.zeros(
|
419 |
+
(1, self.num_attention_heads, self._current_alibi_size,
|
420 |
+
self._current_alibi_size))
|
421 |
+
self.rebuild_alibi_tensor(size=config.alibi_starting_size)
|
422 |
+
|
423 |
+
def rebuild_alibi_tensor(self,
|
424 |
+
size: int,
|
425 |
+
device: Optional[Union[torch.device, str]] = None):
|
426 |
+
# Alibi
|
427 |
+
# Following https://github.com/ofirpress/attention_with_linear_biases/issues/5 (Implementation 1)
|
428 |
+
# In the causal case, you can exploit the fact that softmax is invariant to a uniform translation
|
429 |
+
# of the logits, which makes the math work out *after* applying causal masking. If no causal masking
|
430 |
+
# will be applied, it is necessary to construct the diagonal mask.
|
431 |
+
n_heads = self.num_attention_heads
|
432 |
+
|
433 |
+
def _get_alibi_head_slopes(n_heads: int) -> List[float]:
|
434 |
+
|
435 |
+
def get_slopes_power_of_2(n_heads: int) -> List[float]:
|
436 |
+
start = (2**(-2**-(math.log2(n_heads) - 3)))
|
437 |
+
ratio = start
|
438 |
+
return [start * ratio**i for i in range(n_heads)]
|
439 |
+
|
440 |
+
# In the paper, they only train models that have 2^a heads for some a. This function
|
441 |
+
# has some good properties that only occur when the input is a power of 2. To
|
442 |
+
# maintain that even when the number of heads is not a power of 2, we use a
|
443 |
+
# workaround.
|
444 |
+
if math.log2(n_heads).is_integer():
|
445 |
+
return get_slopes_power_of_2(n_heads)
|
446 |
+
|
447 |
+
closest_power_of_2 = 2**math.floor(math.log2(n_heads))
|
448 |
+
slopes_a = get_slopes_power_of_2(closest_power_of_2)
|
449 |
+
slopes_b = _get_alibi_head_slopes(2 * closest_power_of_2)
|
450 |
+
slopes_b = slopes_b[0::2][:n_heads - closest_power_of_2]
|
451 |
+
return slopes_a + slopes_b
|
452 |
+
|
453 |
+
context_position = torch.arange(size, device=device)[:, None]
|
454 |
+
memory_position = torch.arange(size, device=device)[None, :]
|
455 |
+
relative_position = torch.abs(memory_position - context_position)
|
456 |
+
# [n_heads, max_token_length, max_token_length]
|
457 |
+
relative_position = relative_position.unsqueeze(0).expand(
|
458 |
+
n_heads, -1, -1)
|
459 |
+
slopes = torch.Tensor(_get_alibi_head_slopes(n_heads)).to(device)
|
460 |
+
alibi = slopes.unsqueeze(1).unsqueeze(1) * -relative_position
|
461 |
+
# [1, n_heads, max_token_length, max_token_length]
|
462 |
+
alibi = alibi.unsqueeze(0)
|
463 |
+
assert alibi.shape == torch.Size([1, n_heads, size, size])
|
464 |
+
|
465 |
+
self._current_alibi_size = size
|
466 |
+
self.alibi = alibi
|
467 |
+
|
468 |
+
def forward(
|
469 |
+
self,
|
470 |
+
hidden_states: torch.Tensor,
|
471 |
+
attention_mask: torch.Tensor,
|
472 |
+
output_all_encoded_layers: Optional[bool] = True,
|
473 |
+
subset_mask: Optional[torch.Tensor] = None,
|
474 |
+
) -> List[torch.Tensor]:
|
475 |
+
|
476 |
+
extended_attention_mask = attention_mask.unsqueeze(1).unsqueeze(2)
|
477 |
+
extended_attention_mask = extended_attention_mask.to(
|
478 |
+
dtype=next(self.parameters()).dtype) # fp16 compatibility
|
479 |
+
extended_attention_mask = (1.0 - extended_attention_mask) * -10000.0
|
480 |
+
|
481 |
+
attention_mask_bool = attention_mask.bool()
|
482 |
+
batch, seqlen = hidden_states.shape[:2]
|
483 |
+
# Unpad inputs and mask. It will remove tokens that are padded.
|
484 |
+
# Assume ntokens is total number of tokens (padded and non-padded)
|
485 |
+
# and ntokens_unpad is total number of non-padded tokens.
|
486 |
+
# Then unpadding performs the following compression of the inputs:
|
487 |
+
# hidden_states[ntokens,hidden] -> hidden_states[ntokens_unpad,hidden]
|
488 |
+
hidden_states, indices, cu_seqlens, _ = unpad_input(
|
489 |
+
hidden_states, attention_mask_bool)
|
490 |
+
|
491 |
+
# Add alibi matrix to extended_attention_mask
|
492 |
+
if self._current_alibi_size < seqlen:
|
493 |
+
# Rebuild the alibi tensor when needed
|
494 |
+
warnings.warn(
|
495 |
+
f'Increasing alibi size from {self._current_alibi_size} to {seqlen}'
|
496 |
+
)
|
497 |
+
self.rebuild_alibi_tensor(size=seqlen, device=hidden_states.device)
|
498 |
+
elif self.alibi.device != hidden_states.device:
|
499 |
+
# Device catch-up
|
500 |
+
self.alibi = self.alibi.to(hidden_states.device)
|
501 |
+
alibi_bias = self.alibi[:, :, :seqlen, :seqlen]
|
502 |
+
attn_bias = extended_attention_mask[:, :, :seqlen, :seqlen]
|
503 |
+
alibi_attn_mask = attn_bias + alibi_bias
|
504 |
+
|
505 |
+
all_encoder_layers = []
|
506 |
+
if subset_mask is None:
|
507 |
+
for layer_module in self.layer:
|
508 |
+
hidden_states = layer_module(hidden_states,
|
509 |
+
cu_seqlens,
|
510 |
+
seqlen,
|
511 |
+
None,
|
512 |
+
indices,
|
513 |
+
attn_mask=attention_mask,
|
514 |
+
bias=alibi_attn_mask)
|
515 |
+
if output_all_encoded_layers:
|
516 |
+
all_encoder_layers.append(hidden_states)
|
517 |
+
# Pad inputs and mask. It will insert back zero-padded tokens.
|
518 |
+
# Assume ntokens is total number of tokens (padded and non-padded)
|
519 |
+
# and ntokens_unpad is total number of non-padded tokens.
|
520 |
+
# Then padding performs the following de-compression:
|
521 |
+
# hidden_states[ntokens_unpad,hidden] -> hidden_states[ntokens,hidden]
|
522 |
+
hidden_states = pad_input(hidden_states, indices, batch, seqlen)
|
523 |
+
else:
|
524 |
+
for i in range(len(self.layer) - 1):
|
525 |
+
layer_module = self.layer[i]
|
526 |
+
hidden_states = layer_module(hidden_states,
|
527 |
+
cu_seqlens,
|
528 |
+
seqlen,
|
529 |
+
None,
|
530 |
+
indices,
|
531 |
+
attn_mask=attention_mask,
|
532 |
+
bias=alibi_attn_mask)
|
533 |
+
if output_all_encoded_layers:
|
534 |
+
all_encoder_layers.append(hidden_states)
|
535 |
+
subset_idx = torch.nonzero(subset_mask[attention_mask_bool],
|
536 |
+
as_tuple=False).flatten()
|
537 |
+
hidden_states = self.layer[-1](hidden_states,
|
538 |
+
cu_seqlens,
|
539 |
+
seqlen,
|
540 |
+
subset_idx=subset_idx,
|
541 |
+
indices=indices,
|
542 |
+
attn_mask=attention_mask,
|
543 |
+
bias=alibi_attn_mask)
|
544 |
+
|
545 |
+
if not output_all_encoded_layers:
|
546 |
+
all_encoder_layers.append(hidden_states)
|
547 |
+
return all_encoder_layers
|
548 |
+
|
549 |
+
|
550 |
+
class BertPooler(nn.Module):
|
551 |
+
|
552 |
+
def __init__(self, config):
|
553 |
+
super(BertPooler, self).__init__()
|
554 |
+
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
|
555 |
+
self.activation = nn.Tanh()
|
556 |
+
|
557 |
+
def forward(self,
|
558 |
+
hidden_states: torch.Tensor,
|
559 |
+
pool: Optional[bool] = True) -> torch.Tensor:
|
560 |
+
# We "pool" the model by simply taking the hidden state corresponding
|
561 |
+
# to the first token.
|
562 |
+
first_token_tensor = hidden_states[:, 0] if pool else hidden_states
|
563 |
+
pooled_output = self.dense(first_token_tensor)
|
564 |
+
pooled_output = self.activation(pooled_output)
|
565 |
+
return pooled_output
|
566 |
+
|
567 |
+
|
568 |
+
class BertPredictionHeadTransform(nn.Module):
|
569 |
+
|
570 |
+
def __init__(self, config):
|
571 |
+
super().__init__()
|
572 |
+
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
|
573 |
+
if isinstance(config.hidden_act, str):
|
574 |
+
self.transform_act_fn = ACT2FN[config.hidden_act]
|
575 |
+
else:
|
576 |
+
self.transform_act_fn = config.hidden_act
|
577 |
+
self.LayerNorm = torch.nn.LayerNorm(config.hidden_size, eps=1e-12)
|
578 |
+
|
579 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
580 |
+
hidden_states = self.dense(hidden_states)
|
581 |
+
hidden_states = self.transform_act_fn(hidden_states)
|
582 |
+
hidden_states = self.LayerNorm(hidden_states)
|
583 |
+
return hidden_states
|
584 |
+
|
585 |
+
|
586 |
+
class BertModel(BertPreTrainedModel):
|
587 |
+
"""Overall BERT model.
|
588 |
+
|
589 |
+
Args:
|
590 |
+
config: a BertConfig class instance with the configuration to build a new model
|
591 |
+
|
592 |
+
Inputs:
|
593 |
+
`input_ids`: a torch.LongTensor of shape [batch_size, sequence_length]
|
594 |
+
with the word token indices in the vocabulary(see the tokens preprocessing logic in the scripts
|
595 |
+
`extract_features.py`, `run_classifier.py` and `run_squad.py`)
|
596 |
+
`token_type_ids`: an optional torch.LongTensor of shape [batch_size, sequence_length] with the token
|
597 |
+
types indices selected in [0, 1]. Type 0 corresponds to a `sentence A` and type 1 corresponds to
|
598 |
+
a `sentence B` token (see BERT paper for more details).
|
599 |
+
`attention_mask`: an optional torch.LongTensor of shape [batch_size, sequence_length] with indices
|
600 |
+
selected in [0, 1]. It's a mask to be used if the input sequence length is smaller than the max
|
601 |
+
input sequence length in the current batch. It's the mask that we typically use for attention when
|
602 |
+
a batch has varying length sentences.
|
603 |
+
`output_all_encoded_layers`: boolean which controls the content of the `encoded_layers` output as described below. Default: `True`.
|
604 |
+
|
605 |
+
Outputs: Tuple of (encoded_layers, pooled_output)
|
606 |
+
`encoded_layers`: controlled by `output_all_encoded_layers` argument:
|
607 |
+
- `output_all_encoded_layers=True`: outputs a list of the full sequences of encoded-hidden-states at the end
|
608 |
+
of each attention block (i.e. 12 full sequences for BERT-base, 24 for BERT-large), each
|
609 |
+
encoded-hidden-state is a torch.FloatTensor of size [batch_size, sequence_length, hidden_size],
|
610 |
+
- `output_all_encoded_layers=False`: outputs only the full sequence of hidden-states corresponding
|
611 |
+
to the last attention block of shape [batch_size, sequence_length, hidden_size],
|
612 |
+
`pooled_output`: a torch.FloatTensor of size [batch_size, hidden_size] which is the output of a
|
613 |
+
classifier pretrained on top of the hidden state associated to the first character of the
|
614 |
+
input (`CLS`) to train on the Next-Sentence task (see BERT's paper).
|
615 |
+
|
616 |
+
Example usage:
|
617 |
+
```python
|
618 |
+
# Already been converted into WordPiece token ids
|
619 |
+
input_ids = torch.LongTensor([[31, 51, 99], [15, 5, 0]])
|
620 |
+
input_mask = torch.LongTensor([[1, 1, 1], [1, 1, 0]])
|
621 |
+
token_type_ids = torch.LongTensor([[0, 0, 1], [0, 1, 0]])
|
622 |
+
config = modeling.BertConfig(vocab_size_or_config_json_file=32000, hidden_size=768,
|
623 |
+
num_hidden_layers=12, num_attention_heads=12, intermediate_size=3072)
|
624 |
+
model = BertModel(config=config)
|
625 |
+
all_encoder_layers, pooled_output = model(input_ids, token_type_ids, input_mask)
|
626 |
+
```
|
627 |
+
"""
|
628 |
+
|
629 |
+
def __init__(self, config, add_pooling_layer=True):
|
630 |
+
super(BertModel, self).__init__(config)
|
631 |
+
self.embeddings = BertEmbeddings(config)
|
632 |
+
self.encoder = BertEncoder(config)
|
633 |
+
self.pooler = BertPooler(config) if add_pooling_layer else None
|
634 |
+
self.post_init()
|
635 |
+
|
636 |
+
def get_input_embeddings(self):
|
637 |
+
return self.embeddings.word_embeddings
|
638 |
+
|
639 |
+
def set_input_embeddings(self, value):
|
640 |
+
self.embeddings.word_embeddings = value
|
641 |
+
|
642 |
+
def forward(
|
643 |
+
self,
|
644 |
+
input_ids: torch.Tensor,
|
645 |
+
token_type_ids: Optional[torch.Tensor] = None,
|
646 |
+
attention_mask: Optional[torch.Tensor] = None,
|
647 |
+
position_ids: Optional[torch.Tensor] = None,
|
648 |
+
output_all_encoded_layers: Optional[bool] = False,
|
649 |
+
masked_tokens_mask: Optional[torch.Tensor] = None,
|
650 |
+
**kwargs
|
651 |
+
) -> Tuple[Union[List[torch.Tensor], torch.Tensor], Optional[torch.Tensor]]:
|
652 |
+
if attention_mask is None:
|
653 |
+
attention_mask = torch.ones_like(input_ids)
|
654 |
+
if token_type_ids is None:
|
655 |
+
token_type_ids = torch.zeros_like(input_ids)
|
656 |
+
|
657 |
+
embedding_output = self.embeddings(input_ids, token_type_ids,
|
658 |
+
position_ids)
|
659 |
+
|
660 |
+
subset_mask = []
|
661 |
+
first_col_mask = []
|
662 |
+
|
663 |
+
if masked_tokens_mask is None:
|
664 |
+
subset_mask = None
|
665 |
+
else:
|
666 |
+
first_col_mask = torch.zeros_like(masked_tokens_mask)
|
667 |
+
first_col_mask[:, 0] = True
|
668 |
+
subset_mask = masked_tokens_mask | first_col_mask
|
669 |
+
|
670 |
+
encoder_outputs = self.encoder(
|
671 |
+
embedding_output,
|
672 |
+
attention_mask,
|
673 |
+
output_all_encoded_layers=output_all_encoded_layers,
|
674 |
+
subset_mask=subset_mask)
|
675 |
+
|
676 |
+
if masked_tokens_mask is None:
|
677 |
+
sequence_output = encoder_outputs[-1]
|
678 |
+
pooled_output = self.pooler(
|
679 |
+
sequence_output) if self.pooler is not None else None
|
680 |
+
else:
|
681 |
+
# TD [2022-03-01]: the indexing here is very tricky.
|
682 |
+
attention_mask_bool = attention_mask.bool()
|
683 |
+
subset_idx = subset_mask[attention_mask_bool] # type: ignore
|
684 |
+
sequence_output = encoder_outputs[-1][
|
685 |
+
masked_tokens_mask[attention_mask_bool][subset_idx]]
|
686 |
+
if self.pooler is not None:
|
687 |
+
pool_input = encoder_outputs[-1][
|
688 |
+
first_col_mask[attention_mask_bool][subset_idx]]
|
689 |
+
pooled_output = self.pooler(pool_input, pool=False)
|
690 |
+
else:
|
691 |
+
pooled_output = None
|
692 |
+
|
693 |
+
if not output_all_encoded_layers:
|
694 |
+
encoder_outputs = sequence_output
|
695 |
+
|
696 |
+
if self.pooler is not None:
|
697 |
+
return encoder_outputs, pooled_output
|
698 |
+
|
699 |
+
return encoder_outputs, None
|
700 |
+
|
701 |
+
|
702 |
+
###################
|
703 |
+
# Bert Heads
|
704 |
+
###################
|
705 |
+
class BertLMPredictionHead(nn.Module):
|
706 |
+
|
707 |
+
def __init__(self, config, bert_model_embedding_weights):
|
708 |
+
super().__init__()
|
709 |
+
self.transform = BertPredictionHeadTransform(config)
|
710 |
+
# The output weights are the same as the input embeddings, but there is
|
711 |
+
# an output-only bias for each token.
|
712 |
+
self.decoder = nn.Linear(bert_model_embedding_weights.size(1),
|
713 |
+
bert_model_embedding_weights.size(0))
|
714 |
+
self.decoder.weight = bert_model_embedding_weights
|
715 |
+
|
716 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
717 |
+
hidden_states = self.transform(hidden_states)
|
718 |
+
hidden_states = self.decoder(hidden_states)
|
719 |
+
return hidden_states
|
720 |
+
|
721 |
+
|
722 |
+
class BertOnlyMLMHead(nn.Module):
|
723 |
+
|
724 |
+
def __init__(self, config, bert_model_embedding_weights):
|
725 |
+
super().__init__()
|
726 |
+
self.predictions = BertLMPredictionHead(config,
|
727 |
+
bert_model_embedding_weights)
|
728 |
+
|
729 |
+
def forward(self, sequence_output: torch.Tensor) -> torch.Tensor:
|
730 |
+
prediction_scores = self.predictions(sequence_output)
|
731 |
+
return prediction_scores
|
732 |
+
|
733 |
+
|
734 |
+
class BertOnlyNSPHead(nn.Module):
|
735 |
+
|
736 |
+
def __init__(self, config):
|
737 |
+
super().__init__()
|
738 |
+
self.seq_relationship = nn.Linear(config.hidden_size, 2)
|
739 |
+
|
740 |
+
def forward(self, pooled_output: torch.Tensor) -> torch.Tensor:
|
741 |
+
seq_relationship_score = self.seq_relationship(pooled_output)
|
742 |
+
return seq_relationship_score
|
743 |
+
|
744 |
+
|
745 |
+
#####################
|
746 |
+
# Various Bert models
|
747 |
+
#####################
|
748 |
+
|
749 |
+
|
750 |
+
class BertForPreTraining(BertPreTrainedModel):
|
751 |
+
#TBD: Coming in Future Commit
|
752 |
+
pass
|
753 |
+
|
754 |
+
|
755 |
+
class BertLMHeadModel(BertPreTrainedModel):
|
756 |
+
#TBD: Coming in Future Commit
|
757 |
+
pass
|
758 |
+
|
759 |
+
|
760 |
+
class BertForMaskedLM(BertPreTrainedModel):
|
761 |
+
|
762 |
+
config_class = BertConfig
|
763 |
+
|
764 |
+
def __init__(self, config):
|
765 |
+
super().__init__(config)
|
766 |
+
|
767 |
+
if config.is_decoder:
|
768 |
+
warnings.warn(
|
769 |
+
'If you want to use `BertForMaskedLM` make sure `config.is_decoder=False` for '
|
770 |
+
'bi-directional self-attention.')
|
771 |
+
|
772 |
+
self.bert = BertModel(config, add_pooling_layer=False)
|
773 |
+
self.cls = BertOnlyMLMHead(config,
|
774 |
+
self.bert.embeddings.word_embeddings.weight)
|
775 |
+
|
776 |
+
# Initialize weights and apply final processing
|
777 |
+
self.post_init()
|
778 |
+
|
779 |
+
@classmethod
|
780 |
+
def from_composer(cls,
|
781 |
+
pretrained_checkpoint,
|
782 |
+
state_dict=None,
|
783 |
+
cache_dir=None,
|
784 |
+
from_tf=False,
|
785 |
+
config=None,
|
786 |
+
*inputs,
|
787 |
+
**kwargs):
|
788 |
+
"""Load from pre-trained."""
|
789 |
+
model = cls(config, *inputs, **kwargs)
|
790 |
+
if from_tf:
|
791 |
+
raise ValueError(
|
792 |
+
'Mosaic BERT does not support loading TensorFlow weights.')
|
793 |
+
|
794 |
+
state_dict = torch.load(pretrained_checkpoint)
|
795 |
+
# If the state_dict was saved after wrapping with `composer.HuggingFaceModel`, it takes on the `model` prefix
|
796 |
+
consume_prefix_in_state_dict_if_present(state_dict, prefix='model.')
|
797 |
+
missing_keys, unexpected_keys = model.load_state_dict(state_dict,
|
798 |
+
strict=False)
|
799 |
+
|
800 |
+
if len(missing_keys) > 0:
|
801 |
+
logger.warning(
|
802 |
+
f"Found these missing keys in the checkpoint: {', '.join(missing_keys)}"
|
803 |
+
)
|
804 |
+
if len(unexpected_keys) > 0:
|
805 |
+
logger.warning(
|
806 |
+
f"Found these unexpected keys in the checkpoint: {', '.join(unexpected_keys)}"
|
807 |
+
)
|
808 |
+
|
809 |
+
return model
|
810 |
+
|
811 |
+
def get_output_embeddings(self):
|
812 |
+
return self.cls.predictions.decoder
|
813 |
+
|
814 |
+
def set_output_embeddings(self, new_embeddings):
|
815 |
+
self.cls.predictions.decoder = new_embeddings
|
816 |
+
|
817 |
+
def forward(
|
818 |
+
self,
|
819 |
+
input_ids: Optional[torch.Tensor] = None,
|
820 |
+
attention_mask: Optional[torch.Tensor] = None,
|
821 |
+
token_type_ids: Optional[torch.Tensor] = None,
|
822 |
+
position_ids: Optional[torch.Tensor] = None,
|
823 |
+
head_mask: Optional[torch.Tensor] = None,
|
824 |
+
inputs_embeds: Optional[torch.Tensor] = None,
|
825 |
+
encoder_hidden_states: Optional[torch.Tensor] = None,
|
826 |
+
encoder_attention_mask: Optional[torch.Tensor] = None,
|
827 |
+
labels: Optional[torch.Tensor] = None,
|
828 |
+
output_attentions: Optional[bool] = None,
|
829 |
+
output_hidden_states: Optional[bool] = None,
|
830 |
+
return_dict: Optional[bool] = None,
|
831 |
+
) -> Union[Tuple[torch.Tensor], MaskedLMOutput]:
|
832 |
+
# labels should be a `torch.LongTensor` of shape
|
833 |
+
# `(batch_size, sequence_length)`. These are used for computing the
|
834 |
+
# masked language modeling loss.
|
835 |
+
#
|
836 |
+
# Indices should be in `[-100, 0, ..., config.vocab_size]` (see
|
837 |
+
# `input_ids` docstring) Tokens with indices set to `-100` are ignored
|
838 |
+
# (masked), the loss is only computed for the tokens with labels in `[0,
|
839 |
+
# ..., config.vocab_size]`
|
840 |
+
#
|
841 |
+
# Prediction scores are only computed for masked tokens and the (bs,
|
842 |
+
# seqlen) dimensions are flattened
|
843 |
+
if (input_ids is not None) == (inputs_embeds is not None):
|
844 |
+
raise ValueError('Must specify either input_ids or input_embeds!')
|
845 |
+
|
846 |
+
if labels is None:
|
847 |
+
masked_tokens_mask = None
|
848 |
+
else:
|
849 |
+
masked_tokens_mask = labels > 0
|
850 |
+
|
851 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
852 |
+
|
853 |
+
outputs = self.bert(
|
854 |
+
input_ids,
|
855 |
+
attention_mask=attention_mask,
|
856 |
+
token_type_ids=token_type_ids,
|
857 |
+
position_ids=position_ids,
|
858 |
+
head_mask=head_mask,
|
859 |
+
inputs_embeds=inputs_embeds,
|
860 |
+
encoder_hidden_states=encoder_hidden_states,
|
861 |
+
encoder_attention_mask=encoder_attention_mask,
|
862 |
+
output_attentions=output_attentions,
|
863 |
+
output_hidden_states=output_hidden_states,
|
864 |
+
return_dict=return_dict,
|
865 |
+
masked_tokens_mask=masked_tokens_mask,
|
866 |
+
)
|
867 |
+
|
868 |
+
sequence_output = outputs[0]
|
869 |
+
prediction_scores = self.cls(sequence_output)
|
870 |
+
|
871 |
+
loss = None
|
872 |
+
if labels is not None:
|
873 |
+
# Compute loss
|
874 |
+
loss_fct = nn.CrossEntropyLoss()
|
875 |
+
masked_token_idx = torch.nonzero(labels.flatten() > 0,
|
876 |
+
as_tuple=False).flatten()
|
877 |
+
loss = loss_fct(prediction_scores,
|
878 |
+
labels.flatten()[masked_token_idx])
|
879 |
+
|
880 |
+
assert input_ids is not None, 'Coding error; please open an issue'
|
881 |
+
batch, seqlen = input_ids.shape[:2]
|
882 |
+
prediction_scores = rearrange(index_put_first_axis(
|
883 |
+
prediction_scores, masked_token_idx, batch * seqlen),
|
884 |
+
'(b s) d -> b s d',
|
885 |
+
b=batch)
|
886 |
+
|
887 |
+
if not return_dict:
|
888 |
+
output = (prediction_scores,) + outputs[2:]
|
889 |
+
return ((loss,) + output) if loss is not None else output
|
890 |
+
|
891 |
+
return MaskedLMOutput(
|
892 |
+
loss=loss,
|
893 |
+
logits=prediction_scores,
|
894 |
+
hidden_states=None,
|
895 |
+
attentions=None,
|
896 |
+
)
|
897 |
+
|
898 |
+
def prepare_inputs_for_generation(self, input_ids: torch.Tensor,
|
899 |
+
attention_mask: torch.Tensor,
|
900 |
+
**model_kwargs):
|
901 |
+
input_shape = input_ids.shape
|
902 |
+
effective_batch_size = input_shape[0]
|
903 |
+
|
904 |
+
# add a dummy token
|
905 |
+
if self.config.pad_token_id is None:
|
906 |
+
raise ValueError('The PAD token should be defined for generation')
|
907 |
+
|
908 |
+
attention_mask = torch.cat([
|
909 |
+
attention_mask,
|
910 |
+
attention_mask.new_zeros((attention_mask.shape[0], 1))
|
911 |
+
],
|
912 |
+
dim=-1)
|
913 |
+
dummy_token = torch.full((effective_batch_size, 1),
|
914 |
+
self.config.pad_token_id,
|
915 |
+
dtype=torch.long,
|
916 |
+
device=input_ids.device)
|
917 |
+
input_ids = torch.cat([input_ids, dummy_token], dim=1)
|
918 |
+
|
919 |
+
return {'input_ids': input_ids, 'attention_mask': attention_mask}
|
920 |
+
|
921 |
+
|
922 |
+
class BertForNextSentencePrediction(BertPreTrainedModel):
|
923 |
+
#TBD: Push in future commit
|
924 |
+
pass
|
925 |
+
|
926 |
+
|
927 |
+
class BertForSequenceClassification(BertPreTrainedModel):
|
928 |
+
"""Bert Model transformer with a sequence classification/regression head.
|
929 |
+
|
930 |
+
This head is just a linear layer on top of the pooled output. Used for,
|
931 |
+
e.g., GLUE tasks.
|
932 |
+
"""
|
933 |
+
|
934 |
+
def __init__(self, config):
|
935 |
+
super().__init__(config)
|
936 |
+
self.num_labels = config.num_labels
|
937 |
+
self.config = config
|
938 |
+
|
939 |
+
self.bert = BertModel(config)
|
940 |
+
classifier_dropout = (config.classifier_dropout
|
941 |
+
if config.classifier_dropout is not None else
|
942 |
+
config.hidden_dropout_prob)
|
943 |
+
self.dropout = nn.Dropout(classifier_dropout)
|
944 |
+
self.classifier = nn.Linear(config.hidden_size, config.num_labels)
|
945 |
+
|
946 |
+
# Initialize weights and apply final processing
|
947 |
+
self.post_init()
|
948 |
+
|
949 |
+
@classmethod
|
950 |
+
def from_composer(cls,
|
951 |
+
pretrained_checkpoint,
|
952 |
+
state_dict=None,
|
953 |
+
cache_dir=None,
|
954 |
+
from_tf=False,
|
955 |
+
config=None,
|
956 |
+
*inputs,
|
957 |
+
**kwargs):
|
958 |
+
"""Load from pre-trained."""
|
959 |
+
model = cls(config, *inputs, **kwargs)
|
960 |
+
if from_tf:
|
961 |
+
raise ValueError(
|
962 |
+
'Mosaic BERT does not support loading TensorFlow weights.')
|
963 |
+
|
964 |
+
state_dict = torch.load(pretrained_checkpoint)
|
965 |
+
# If the state_dict was saved after wrapping with `composer.HuggingFaceModel`, it takes on the `model` prefix
|
966 |
+
consume_prefix_in_state_dict_if_present(state_dict, prefix='model.')
|
967 |
+
missing_keys, unexpected_keys = model.load_state_dict(state_dict,
|
968 |
+
strict=False)
|
969 |
+
|
970 |
+
if len(missing_keys) > 0:
|
971 |
+
logger.warning(
|
972 |
+
f"Found these missing keys in the checkpoint: {', '.join(missing_keys)}"
|
973 |
+
)
|
974 |
+
if len(unexpected_keys) > 0:
|
975 |
+
logger.warning(
|
976 |
+
f"Found these unexpected keys in the checkpoint: {', '.join(unexpected_keys)}"
|
977 |
+
)
|
978 |
+
|
979 |
+
return model
|
980 |
+
|
981 |
+
def forward(
|
982 |
+
self,
|
983 |
+
input_ids: Optional[torch.Tensor] = None,
|
984 |
+
attention_mask: Optional[torch.Tensor] = None,
|
985 |
+
token_type_ids: Optional[torch.Tensor] = None,
|
986 |
+
position_ids: Optional[torch.Tensor] = None,
|
987 |
+
head_mask: Optional[torch.Tensor] = None,
|
988 |
+
inputs_embeds: Optional[torch.Tensor] = None,
|
989 |
+
labels: Optional[torch.Tensor] = None,
|
990 |
+
output_attentions: Optional[bool] = None,
|
991 |
+
output_hidden_states: Optional[bool] = None,
|
992 |
+
return_dict: Optional[bool] = None,
|
993 |
+
) -> Union[Tuple[torch.Tensor], SequenceClassifierOutput]:
|
994 |
+
# labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
995 |
+
# Labels for computing the sequence classification/regression loss.
|
996 |
+
# Indices should be in `[0, ..., config.num_labels - 1]`.
|
997 |
+
# If `config.num_labels == 1` a regression loss is computed
|
998 |
+
# (mean-square loss). If `config.num_labels > 1` a classification loss
|
999 |
+
# is computed (cross-entropy).
|
1000 |
+
|
1001 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
1002 |
+
|
1003 |
+
outputs = self.bert(
|
1004 |
+
input_ids,
|
1005 |
+
attention_mask=attention_mask,
|
1006 |
+
token_type_ids=token_type_ids,
|
1007 |
+
position_ids=position_ids,
|
1008 |
+
head_mask=head_mask,
|
1009 |
+
inputs_embeds=inputs_embeds,
|
1010 |
+
output_attentions=output_attentions,
|
1011 |
+
output_hidden_states=output_hidden_states,
|
1012 |
+
return_dict=return_dict,
|
1013 |
+
)
|
1014 |
+
|
1015 |
+
pooled_output = outputs[1]
|
1016 |
+
|
1017 |
+
pooled_output = self.dropout(pooled_output)
|
1018 |
+
logits = self.classifier(pooled_output)
|
1019 |
+
|
1020 |
+
loss = None
|
1021 |
+
if labels is not None:
|
1022 |
+
# Compute loss
|
1023 |
+
if self.config.problem_type is None:
|
1024 |
+
if self.num_labels == 1:
|
1025 |
+
self.config.problem_type = 'regression'
|
1026 |
+
elif self.num_labels > 1 and (labels.dtype == torch.long or
|
1027 |
+
labels.dtype == torch.int):
|
1028 |
+
self.config.problem_type = 'single_label_classification'
|
1029 |
+
else:
|
1030 |
+
self.config.problem_type = 'multi_label_classification'
|
1031 |
+
|
1032 |
+
if self.config.problem_type == 'regression':
|
1033 |
+
loss_fct = nn.MSELoss()
|
1034 |
+
if self.num_labels == 1:
|
1035 |
+
loss = loss_fct(logits.squeeze(), labels.squeeze())
|
1036 |
+
else:
|
1037 |
+
loss = loss_fct(logits, labels)
|
1038 |
+
elif self.config.problem_type == 'single_label_classification':
|
1039 |
+
loss_fct = nn.CrossEntropyLoss()
|
1040 |
+
loss = loss_fct(logits.view(-1, self.num_labels),
|
1041 |
+
labels.view(-1))
|
1042 |
+
elif self.config.problem_type == 'multi_label_classification':
|
1043 |
+
loss_fct = nn.BCEWithLogitsLoss()
|
1044 |
+
loss = loss_fct(logits, labels)
|
1045 |
+
|
1046 |
+
if not return_dict:
|
1047 |
+
output = (logits,) + outputs[2:]
|
1048 |
+
return ((loss,) + output) if loss is not None else output
|
1049 |
+
|
1050 |
+
return SequenceClassifierOutput(
|
1051 |
+
loss=loss,
|
1052 |
+
logits=logits,
|
1053 |
+
hidden_states=None,
|
1054 |
+
attentions=None,
|
1055 |
+
)
|
1056 |
+
|
1057 |
+
|
1058 |
+
class BertForMultipleChoice(BertPreTrainedModel):
|
1059 |
+
#TBD: Push in future commit
|
1060 |
+
pass
|
1061 |
+
|
1062 |
+
|
1063 |
+
class BertForTokenClassification(BertPreTrainedModel):
|
1064 |
+
#TBD: Push in future commit
|
1065 |
+
pass
|
1066 |
+
|
1067 |
+
|
1068 |
+
class BertForQuestionAnswering(BertPreTrainedModel):
|
1069 |
+
"""Bert Model with a span classification head.
|
1070 |
+
|
1071 |
+
This is used for extractive question-answering tasks like SQuAD (a linear
|
1072 |
+
layers on top of the hidden states' output to compute `span start logits`
|
1073 |
+
and `span end logits`).
|
1074 |
+
"""
|
1075 |
+
#TBD: Push in future commit
|
bert_padding.py
ADDED
@@ -0,0 +1,159 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright 2022 MosaicML Examples authors
|
2 |
+
# SPDX-License-Identifier: Apache-2.0
|
3 |
+
|
4 |
+
# Adapted from https://github.com/HazyResearch/flash-attention/blob/main/flash_attn/bert_padding.py
|
5 |
+
# Which was adapted from https://github.com/mlcommons/training_results_v1.1/blob/main/NVIDIA/benchmarks/bert/implementations/pytorch/padding.py
|
6 |
+
|
7 |
+
"""Helper functions for padding and unpadding batches.
|
8 |
+
|
9 |
+
These functions are used extensively throughout the Mosaic BERT implementation
|
10 |
+
in `bert_layers.py`.
|
11 |
+
"""
|
12 |
+
|
13 |
+
from typing import Tuple, cast
|
14 |
+
|
15 |
+
import torch
|
16 |
+
import torch.nn.functional as F
|
17 |
+
from einops import rearrange, repeat
|
18 |
+
|
19 |
+
|
20 |
+
class IndexFirstAxis(torch.autograd.Function):
|
21 |
+
|
22 |
+
@staticmethod
|
23 |
+
def forward(ctx, input: torch.Tensor,
|
24 |
+
indices: torch.Tensor) -> torch.Tensor:
|
25 |
+
"""Get just the values of `input` which are at `indices`.
|
26 |
+
|
27 |
+
Arguments:
|
28 |
+
ctx: the autograd context object
|
29 |
+
input: (b, ...) 2+ dimensional tensor
|
30 |
+
indices: (num_idx) 1D tensor
|
31 |
+
"""
|
32 |
+
ctx.save_for_backward(indices)
|
33 |
+
assert input.ndim >= 2
|
34 |
+
ctx.first_axis_dim, other_shape = input.shape[0], input.shape[
|
35 |
+
1:] # type: ignore
|
36 |
+
second_dim = other_shape.numel(
|
37 |
+
) # product of sizes of all but first dimension
|
38 |
+
# TD [2022-03-04] For some reason torch.gather is a bit faster than indexing.
|
39 |
+
return torch.gather(
|
40 |
+
rearrange(input, 'b ... -> b (...)'), # (b, ...) -> (b, second_dim)
|
41 |
+
0,
|
42 |
+
repeat(indices, 'z -> z d',
|
43 |
+
d=second_dim) # (indices,) -> (indices, second_dim)
|
44 |
+
).reshape(-1, *other_shape) # (num_idx, ...)
|
45 |
+
|
46 |
+
@staticmethod
|
47 |
+
def backward(ctx, grad_output: torch.Tensor) -> Tuple[torch.Tensor, None]:
|
48 |
+
indices, = ctx.saved_tensors
|
49 |
+
assert grad_output.ndim >= 2
|
50 |
+
other_shape = grad_output.shape[1:]
|
51 |
+
grad_output = rearrange(grad_output, 'b ... -> b (...)')
|
52 |
+
grad_input = torch.zeros([ctx.first_axis_dim, grad_output.shape[1]],
|
53 |
+
device=grad_output.device,
|
54 |
+
dtype=grad_output.dtype)
|
55 |
+
# TD [2022-03-04] For some reason torch.scatter is a bit faster than indexing.
|
56 |
+
# grad_input[indices] = grad_output
|
57 |
+
grad_input.scatter_(0,
|
58 |
+
repeat(indices, 'z -> z d', d=grad_output.shape[1]),
|
59 |
+
grad_output)
|
60 |
+
return grad_input.reshape(ctx.first_axis_dim, *other_shape), None
|
61 |
+
|
62 |
+
|
63 |
+
index_first_axis = IndexFirstAxis.apply
|
64 |
+
|
65 |
+
|
66 |
+
class IndexPutFirstAxis(torch.autograd.Function):
|
67 |
+
|
68 |
+
@staticmethod
|
69 |
+
def forward(ctx, values: torch.Tensor, indices: torch.Tensor,
|
70 |
+
first_axis_dim) -> torch.Tensor:
|
71 |
+
ctx.save_for_backward(indices)
|
72 |
+
assert indices.ndim == 1
|
73 |
+
assert values.ndim >= 2
|
74 |
+
output = torch.zeros(first_axis_dim,
|
75 |
+
*values.shape[1:],
|
76 |
+
device=values.device,
|
77 |
+
dtype=values.dtype)
|
78 |
+
output[indices] = values
|
79 |
+
return output
|
80 |
+
|
81 |
+
@staticmethod
|
82 |
+
def backward(ctx,
|
83 |
+
grad_output: torch.Tensor) -> Tuple[torch.Tensor, None, None]:
|
84 |
+
indices, = ctx.saved_tensors
|
85 |
+
grad_values = grad_output[indices]
|
86 |
+
return grad_values, None, None
|
87 |
+
|
88 |
+
|
89 |
+
index_put_first_axis = IndexPutFirstAxis.apply
|
90 |
+
|
91 |
+
|
92 |
+
def unpad_input(
|
93 |
+
hidden_states: torch.Tensor,
|
94 |
+
attention_mask: torch.Tensor,
|
95 |
+
) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, int]:
|
96 |
+
"""Remove padding from input sequences.
|
97 |
+
|
98 |
+
Arguments:
|
99 |
+
hidden_states: (batch, seqlen, ...)
|
100 |
+
attention_mask: (batch, seqlen), bool / int, 1 means valid and 0 means not valid.
|
101 |
+
|
102 |
+
Returns:
|
103 |
+
hidden_states: (total_nnz, ...), where total_nnz = number of tokens in selected in attention_mask.
|
104 |
+
indices: (total_nnz)
|
105 |
+
cu_seqlens: (batch + 1), the cumulative sequence lengths, used to index into hidden_states.
|
106 |
+
max_seqlen_in_batch: int ()
|
107 |
+
"""
|
108 |
+
seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
|
109 |
+
indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
|
110 |
+
max_seqlen_in_batch = int(seqlens_in_batch.max().item())
|
111 |
+
cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.int32),
|
112 |
+
(1, 0))
|
113 |
+
# TD [2022-03-04] We don't want to index with a bool mask, because Pytorch will expand the
|
114 |
+
# bool mask, then call nonzero to get the indices, then index with those. The indices is @dim
|
115 |
+
# times larger than it needs to be, wasting memory. It's faster and more memory-efficient to
|
116 |
+
# index with integer indices. Moreover, torch's index is a bit slower than it needs to be,
|
117 |
+
# so we write custom forward and backward to make it a bit faster.
|
118 |
+
hidden_states = cast(
|
119 |
+
torch.Tensor,
|
120 |
+
index_first_axis(rearrange(hidden_states, 'b s ... -> (b s) ...'),
|
121 |
+
indices))
|
122 |
+
return hidden_states, indices, cu_seqlens, max_seqlen_in_batch
|
123 |
+
|
124 |
+
|
125 |
+
def unpad_input_only(
|
126 |
+
hidden_states: torch.Tensor,
|
127 |
+
attention_mask: torch.Tensor,
|
128 |
+
) -> torch.Tensor:
|
129 |
+
"""Like unpad_input, but only return the unpadded first tensor.
|
130 |
+
|
131 |
+
Save a small amount of overhead.
|
132 |
+
|
133 |
+
Arguments:
|
134 |
+
hidden_states: (batch, seqlen, ...)
|
135 |
+
attention_mask: (batch, seqlen), bool / int, 1 means valid and 0 means not valid.
|
136 |
+
|
137 |
+
Returns:
|
138 |
+
hidden_states: (total_nnz, ...), where total_nnz = number of tokens in selected in attention_mask.
|
139 |
+
"""
|
140 |
+
indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
|
141 |
+
rearranged = rearrange(hidden_states, 'b s ... -> (b s) ...')
|
142 |
+
return index_first_axis(rearranged, indices) # type: ignore
|
143 |
+
|
144 |
+
|
145 |
+
def pad_input(hidden_states: torch.Tensor, indices: torch.Tensor, batch: int,
|
146 |
+
seqlen: int) -> torch.Tensor:
|
147 |
+
"""Add padding to sequences.
|
148 |
+
|
149 |
+
Arguments:
|
150 |
+
hidden_states: (total_nnz, ...), where total_nnz = number of tokens in selected in attention_mask.
|
151 |
+
indices: (total_nnz)
|
152 |
+
batch: int batch_size
|
153 |
+
seqlen: int max sequence length
|
154 |
+
|
155 |
+
Returns:
|
156 |
+
hidden_states: (batch, seqlen, ...)
|
157 |
+
"""
|
158 |
+
output = index_put_first_axis(hidden_states, indices, batch * seqlen)
|
159 |
+
return rearrange(output, '(b s) ... -> b s ...', b=batch) # type: ignore
|
config.json
ADDED
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"_name_or_path": "aisingapore/sealion-bert-base",
|
3 |
+
"alibi_starting_size": 512,
|
4 |
+
"architectures": [
|
5 |
+
"BertForMaskedLM"
|
6 |
+
],
|
7 |
+
"attention_probs_dropout_prob": 0.0,
|
8 |
+
"auto_map": {
|
9 |
+
"AutoConfig": "configuration_bert.BertConfig",
|
10 |
+
"AutoModelForMaskedLM": "bert_layers.BertForMaskedLM"
|
11 |
+
},
|
12 |
+
"classifier_dropout": null,
|
13 |
+
"gradient_checkpointing": false,
|
14 |
+
"hidden_act": "gelu",
|
15 |
+
"hidden_dropout_prob": 0.1,
|
16 |
+
"hidden_size": 768,
|
17 |
+
"initializer_range": 0.02,
|
18 |
+
"intermediate_size": 3072,
|
19 |
+
"layer_norm_eps": 1e-12,
|
20 |
+
"max_position_embeddings": 512,
|
21 |
+
"model_type": "bert",
|
22 |
+
"num_attention_heads": 12,
|
23 |
+
"num_hidden_layers": 12,
|
24 |
+
"pad_token_id": 0,
|
25 |
+
"position_embedding_type": "absolute",
|
26 |
+
"transformers_version": "4.31.0",
|
27 |
+
"type_vocab_size": 2,
|
28 |
+
"use_cache": true,
|
29 |
+
"vocab_size": 256000
|
30 |
+
}
|
configuration_bert.py
ADDED
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright 2022 MosaicML Examples authors
|
2 |
+
# SPDX-License-Identifier: Apache-2.0
|
3 |
+
|
4 |
+
from transformers import BertConfig as TransformersBertConfig
|
5 |
+
|
6 |
+
|
7 |
+
class BertConfig(TransformersBertConfig):
|
8 |
+
def __init__(
|
9 |
+
self,
|
10 |
+
alibi_starting_size: int = 512,
|
11 |
+
attention_probs_dropout_prob: float = 0.0,
|
12 |
+
**kwargs,
|
13 |
+
):
|
14 |
+
"""Configuration class for MosaicBert.
|
15 |
+
|
16 |
+
Args:
|
17 |
+
alibi_starting_size (int): Use `alibi_starting_size` to determine how large of an alibi tensor to
|
18 |
+
create when initializing the model. You should be able to ignore this parameter in most cases.
|
19 |
+
Defaults to 512.
|
20 |
+
attention_probs_dropout_prob (float): By default, turn off attention dropout in Mosaic BERT
|
21 |
+
(otherwise, Flash Attention will be off by default). Defaults to 0.0.
|
22 |
+
"""
|
23 |
+
super().__init__(
|
24 |
+
attention_probs_dropout_prob=attention_probs_dropout_prob, **kwargs)
|
25 |
+
self.alibi_starting_size = alibi_starting_size
|
flash_attn_triton.py
ADDED
@@ -0,0 +1,1114 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright 2022 MosaicML Examples authors
|
2 |
+
# SPDX-License-Identifier: Apache-2.0
|
3 |
+
|
4 |
+
"""Triton implementation of Flash Attention.
|
5 |
+
|
6 |
+
# Copyright (c) 2022, Tri Dao.
|
7 |
+
#
|
8 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
9 |
+
# you may not use this file except in compliance with the License.
|
10 |
+
# You may obtain a copy of the License at
|
11 |
+
#
|
12 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
13 |
+
#
|
14 |
+
# Unless required by applicable law or agreed to in writing, software
|
15 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
16 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
17 |
+
# See the License for the specific language governing permissions and
|
18 |
+
# limitations under the License.
|
19 |
+
|
20 |
+
*Experimental* implementation of FlashAttention in Triton.
|
21 |
+
We use the FlashAttention implementation from Phil Tillet a starting point.
|
22 |
+
https://github.com/openai/triton/blob/master/python/tutorials/06-fused-attention.py
|
23 |
+
|
24 |
+
Changes:
|
25 |
+
- Implement both causal and non-causal attention.
|
26 |
+
- Implement both self-attention and cross-attention.
|
27 |
+
- Support arbitrary seqlens (not just multiples of 128), for both forward and backward.
|
28 |
+
- Support all head dimensions up to 128 (not just 16, 32, 64, 128), for both forward and backward.
|
29 |
+
- Support attention bias.
|
30 |
+
- Speed up the forward pass a bit, and only store the LSE instead of m and l.
|
31 |
+
- Make the backward for d=128 much faster by reducing register spilling.
|
32 |
+
- Optionally parallelize the backward pass across seqlen_k, to deal with the case of
|
33 |
+
small batch size * nheads.
|
34 |
+
|
35 |
+
Caution:
|
36 |
+
- If you plan to use headdim other than 64 and 128, you should test for race conditions
|
37 |
+
(due to the Triton compiler), as done in tests/test_flash_attn.py
|
38 |
+
"test_flash_attn_triton_race_condition". I've tested and fixed many race conditions
|
39 |
+
for different head dimensions (40, 48, 64, 128, 80, 88, 96), but I'm still not 100% confident
|
40 |
+
that there are none left for other head dimensions.
|
41 |
+
Differences between this Triton version and the CUDA version:
|
42 |
+
- Triton version doesn't support dropout.
|
43 |
+
- Triton forward is generally faster than CUDA forward.
|
44 |
+
- Triton backward is faster than CUDA backward when batch * nheads is small, and when headdim=64.
|
45 |
+
It is slightly slower when headdim=128 and batch * nheads is large.
|
46 |
+
- Triton version doesn't yet support different sequence lengths in a batch (i.e., RaggedTensor/NestedTensor).
|
47 |
+
"""
|
48 |
+
|
49 |
+
import math
|
50 |
+
|
51 |
+
import torch
|
52 |
+
# import triton # type: ignore (reportMissingImports)
|
53 |
+
# import triton.language as tl # type: ignore (reportMissingImports)
|
54 |
+
from einops import repeat
|
55 |
+
|
56 |
+
import triton_pre_mlir as triton
|
57 |
+
import triton_pre_mlir.language as tl
|
58 |
+
|
59 |
+
@triton.autotune(
|
60 |
+
configs=[
|
61 |
+
triton.Config({
|
62 |
+
'BLOCK_M': 128,
|
63 |
+
'BLOCK_N': 128
|
64 |
+
},
|
65 |
+
num_warps=8,
|
66 |
+
num_stages=1),
|
67 |
+
# This config has a race condition when EVEN_M == False, disabling it for now.
|
68 |
+
# triton.Config({"BLOCK_M": 64, "BLOCK_N": 64}, num_warps=4, num_stages=1),
|
69 |
+
],
|
70 |
+
key=[
|
71 |
+
'CACHE_KEY_SEQLEN_Q', 'CACHE_KEY_SEQLEN_K', 'BIAS_TYPE', 'IS_CAUSAL',
|
72 |
+
'BLOCK_HEADDIM'
|
73 |
+
])
|
74 |
+
@triton.heuristics({
|
75 |
+
'EVEN_M': lambda args: args['seqlen_q'] % args['BLOCK_M'] == 0,
|
76 |
+
'EVEN_N': lambda args: args['seqlen_k'] % args['BLOCK_N'] == 0,
|
77 |
+
'EVEN_HEADDIM': lambda args: args['headdim'] == args['BLOCK_HEADDIM'],
|
78 |
+
})
|
79 |
+
@triton.jit
|
80 |
+
def _fwd_kernel(
|
81 |
+
Q,
|
82 |
+
K,
|
83 |
+
V,
|
84 |
+
Bias,
|
85 |
+
Out,
|
86 |
+
Lse,
|
87 |
+
TMP, # NOTE: TMP is a scratchpad buffer to workaround a compiler bug
|
88 |
+
softmax_scale,
|
89 |
+
stride_qb,
|
90 |
+
stride_qh,
|
91 |
+
stride_qm,
|
92 |
+
stride_kb,
|
93 |
+
stride_kh,
|
94 |
+
stride_kn,
|
95 |
+
stride_vb,
|
96 |
+
stride_vh,
|
97 |
+
stride_vn,
|
98 |
+
stride_bb,
|
99 |
+
stride_bh,
|
100 |
+
stride_bm,
|
101 |
+
stride_ob,
|
102 |
+
stride_oh,
|
103 |
+
stride_om,
|
104 |
+
nheads,
|
105 |
+
seqlen_q,
|
106 |
+
seqlen_k,
|
107 |
+
seqlen_q_rounded,
|
108 |
+
headdim,
|
109 |
+
CACHE_KEY_SEQLEN_Q,
|
110 |
+
CACHE_KEY_SEQLEN_K,
|
111 |
+
BIAS_TYPE: tl.constexpr,
|
112 |
+
IS_CAUSAL: tl.constexpr,
|
113 |
+
BLOCK_HEADDIM: tl.constexpr,
|
114 |
+
EVEN_M: tl.constexpr,
|
115 |
+
EVEN_N: tl.constexpr,
|
116 |
+
EVEN_HEADDIM: tl.constexpr,
|
117 |
+
BLOCK_M: tl.constexpr,
|
118 |
+
BLOCK_N: tl.constexpr,
|
119 |
+
):
|
120 |
+
start_m = tl.program_id(0)
|
121 |
+
off_hb = tl.program_id(1)
|
122 |
+
off_b = off_hb // nheads
|
123 |
+
off_h = off_hb % nheads
|
124 |
+
# off_b = tl.program_id(1)
|
125 |
+
# off_h = tl.program_id(2)
|
126 |
+
# off_hb = off_b * nheads + off_h
|
127 |
+
# initialize offsets
|
128 |
+
offs_m = start_m * BLOCK_M + tl.arange(0, BLOCK_M)
|
129 |
+
offs_n = tl.arange(0, BLOCK_N)
|
130 |
+
offs_d = tl.arange(0, BLOCK_HEADDIM)
|
131 |
+
# Initialize pointers to Q, K, V
|
132 |
+
# Adding parenthesis around indexing might use int32 math instead of int64 math?
|
133 |
+
# https://github.com/openai/triton/issues/741
|
134 |
+
# I'm seeing a tiny bit of difference (5-7us)
|
135 |
+
q_ptrs = Q + off_b * stride_qb + off_h * stride_qh + (
|
136 |
+
offs_m[:, None] * stride_qm + offs_d[None, :])
|
137 |
+
k_ptrs = K + off_b * stride_kb + off_h * stride_kh + (
|
138 |
+
offs_n[:, None] * stride_kn + offs_d[None, :])
|
139 |
+
v_ptrs = V + off_b * stride_vb + off_h * stride_vh + (
|
140 |
+
offs_n[:, None] * stride_vn + offs_d[None, :])
|
141 |
+
if BIAS_TYPE == 'vector':
|
142 |
+
b_ptrs = Bias + off_b * stride_bb + off_h * stride_bh + offs_n
|
143 |
+
elif BIAS_TYPE == 'matrix':
|
144 |
+
b_ptrs = Bias + off_b * stride_bb + off_h * stride_bh + (
|
145 |
+
offs_m[:, None] * stride_bm + offs_n[None, :])
|
146 |
+
else:
|
147 |
+
raise ValueError("BIAS_TYPE must be one of {'vector', 'matrix'}")
|
148 |
+
# initialize pointer to m and l
|
149 |
+
t_ptrs = TMP + off_hb * seqlen_q_rounded + offs_m
|
150 |
+
lse_i = tl.zeros([BLOCK_M], dtype=tl.float32) - float('inf')
|
151 |
+
m_i = tl.zeros([BLOCK_M], dtype=tl.float32) - float('inf')
|
152 |
+
acc_o = tl.zeros([BLOCK_M, BLOCK_HEADDIM], dtype=tl.float32)
|
153 |
+
# load q: it will stay in SRAM throughout
|
154 |
+
# [2022-10-30] TD: Triton bug - in the case of EVEN_M=True and EVEN_N=False, if we just call
|
155 |
+
# tl.load(q_ptrs), we get the wrong output!
|
156 |
+
if EVEN_M & EVEN_N:
|
157 |
+
if EVEN_HEADDIM:
|
158 |
+
q = tl.load(q_ptrs)
|
159 |
+
else:
|
160 |
+
q = tl.load(q_ptrs, mask=offs_d[None, :] < headdim, other=0.0)
|
161 |
+
else:
|
162 |
+
if EVEN_HEADDIM:
|
163 |
+
q = tl.load(q_ptrs, mask=offs_m[:, None] < seqlen_q, other=0.0)
|
164 |
+
else:
|
165 |
+
q = tl.load(q_ptrs,
|
166 |
+
mask=(offs_m[:, None] < seqlen_q) &
|
167 |
+
(offs_d[None, :] < headdim),
|
168 |
+
other=0.0)
|
169 |
+
# loop over k, v and update accumulator
|
170 |
+
end_n = seqlen_k if not IS_CAUSAL else tl.minimum(
|
171 |
+
(start_m + 1) * BLOCK_M, seqlen_k)
|
172 |
+
for start_n in range(0, end_n, BLOCK_N):
|
173 |
+
start_n = tl.multiple_of(start_n, BLOCK_N)
|
174 |
+
# -- compute qk ----
|
175 |
+
if EVEN_N & EVEN_M: # If we just do "if EVEN_N", there seems to be some race condition
|
176 |
+
if EVEN_HEADDIM:
|
177 |
+
k = tl.load(k_ptrs + start_n * stride_kn)
|
178 |
+
else:
|
179 |
+
k = tl.load(k_ptrs + start_n * stride_kn,
|
180 |
+
mask=offs_d[None, :] < headdim,
|
181 |
+
other=0.0)
|
182 |
+
else:
|
183 |
+
if EVEN_HEADDIM:
|
184 |
+
k = tl.load(k_ptrs + start_n * stride_kn,
|
185 |
+
mask=(start_n + offs_n)[:, None] < seqlen_k,
|
186 |
+
other=0.0)
|
187 |
+
else:
|
188 |
+
k = tl.load(k_ptrs + start_n * stride_kn,
|
189 |
+
mask=((start_n + offs_n)[:, None] < seqlen_k) &
|
190 |
+
(offs_d[None, :] < headdim),
|
191 |
+
other=0.0)
|
192 |
+
qk = tl.zeros([BLOCK_M, BLOCK_N], dtype=tl.float32)
|
193 |
+
qk += tl.dot(q, k, trans_b=True)
|
194 |
+
# Trying to combine the two masks seem to make the result wrong
|
195 |
+
if not EVEN_N: # Need to mask out otherwise the softmax is wrong
|
196 |
+
qk += tl.where((start_n + offs_n)[None, :] < seqlen_k, 0,
|
197 |
+
float('-inf'))
|
198 |
+
if IS_CAUSAL:
|
199 |
+
qk += tl.where(offs_m[:, None] >= (start_n + offs_n)[None, :], 0,
|
200 |
+
float('-inf'))
|
201 |
+
if BIAS_TYPE != 'none':
|
202 |
+
if BIAS_TYPE == 'vector':
|
203 |
+
if EVEN_N:
|
204 |
+
bias = tl.load(b_ptrs + start_n).to(tl.float32)
|
205 |
+
else:
|
206 |
+
bias = tl.load(b_ptrs + start_n,
|
207 |
+
mask=(start_n + offs_n) < seqlen_k,
|
208 |
+
other=0.0).to(tl.float32)
|
209 |
+
bias = bias[None, :]
|
210 |
+
elif BIAS_TYPE == 'matrix':
|
211 |
+
if EVEN_M & EVEN_N:
|
212 |
+
bias = tl.load(b_ptrs + start_n).to(tl.float32)
|
213 |
+
else:
|
214 |
+
bias = tl.load(b_ptrs + start_n,
|
215 |
+
mask=(offs_m[:, None] < seqlen_q) &
|
216 |
+
((start_n + offs_n)[None, :] < seqlen_k),
|
217 |
+
other=0.0).to(tl.float32)
|
218 |
+
else:
|
219 |
+
raise ValueError(
|
220 |
+
"BIAS_TYPE must be one of {'vector', 'matrix'}")
|
221 |
+
# Slightly faster to multiply the softmax_scale in the tl.exp below since the compiler
|
222 |
+
# can then fuse the mult and add into an fma instruction. But if we have bias we need to
|
223 |
+
# to multiply with softmax_scale here.
|
224 |
+
qk = qk * softmax_scale + bias
|
225 |
+
m_ij = tl.maximum(tl.max(qk, 1), lse_i)
|
226 |
+
p = tl.exp(qk - m_ij[:, None])
|
227 |
+
else:
|
228 |
+
m_ij = tl.maximum(tl.max(qk, 1) * softmax_scale, lse_i)
|
229 |
+
p = tl.exp(qk * softmax_scale - m_ij[:, None])
|
230 |
+
l_ij = tl.sum(p, 1)
|
231 |
+
|
232 |
+
# scale acc_o
|
233 |
+
acc_o_scale = tl.exp(m_i - m_ij)
|
234 |
+
|
235 |
+
# # -- update output accumulator --
|
236 |
+
# BUG: have to store and immediately load
|
237 |
+
tl.store(t_ptrs, acc_o_scale)
|
238 |
+
acc_o_scale = tl.load(t_ptrs)
|
239 |
+
acc_o = acc_o * acc_o_scale[:, None]
|
240 |
+
# update acc_o
|
241 |
+
if EVEN_N & EVEN_M: # If we just do "if EVEN_N", there seems to be some race condition
|
242 |
+
if EVEN_HEADDIM:
|
243 |
+
v = tl.load(v_ptrs + start_n * stride_vn)
|
244 |
+
else:
|
245 |
+
v = tl.load(v_ptrs + start_n * stride_vn,
|
246 |
+
mask=offs_d[None, :] < headdim,
|
247 |
+
other=0.0)
|
248 |
+
else:
|
249 |
+
if EVEN_HEADDIM:
|
250 |
+
v = tl.load(v_ptrs + start_n * stride_vn,
|
251 |
+
mask=(start_n + offs_n)[:, None] < seqlen_k,
|
252 |
+
other=0.0)
|
253 |
+
else:
|
254 |
+
v = tl.load(v_ptrs + start_n * stride_vn,
|
255 |
+
mask=((start_n + offs_n)[:, None] < seqlen_k) &
|
256 |
+
(offs_d[None, :] < headdim),
|
257 |
+
other=0.0)
|
258 |
+
p = p.to(v.dtype)
|
259 |
+
acc_o += tl.dot(p, v)
|
260 |
+
|
261 |
+
# -- update statistics
|
262 |
+
m_i = m_ij
|
263 |
+
l_i_new = tl.exp(lse_i - m_ij) + l_ij
|
264 |
+
lse_i = m_ij + tl.log(l_i_new)
|
265 |
+
|
266 |
+
o_scale = tl.exp(m_i - lse_i)
|
267 |
+
# BUG: have to store and immediately load
|
268 |
+
tl.store(t_ptrs, o_scale)
|
269 |
+
o_scale = tl.load(t_ptrs)
|
270 |
+
acc_o = acc_o * o_scale[:, None]
|
271 |
+
# rematerialize offsets to save registers
|
272 |
+
start_m = tl.program_id(0)
|
273 |
+
offs_m = start_m * BLOCK_M + tl.arange(0, BLOCK_M)
|
274 |
+
# write back l and m
|
275 |
+
lse_ptrs = Lse + off_hb * seqlen_q_rounded + offs_m
|
276 |
+
tl.store(lse_ptrs, lse_i)
|
277 |
+
# initialize pointers to output
|
278 |
+
offs_n = tl.arange(0, BLOCK_HEADDIM)
|
279 |
+
out_ptrs = Out + off_b * stride_ob + off_h * stride_oh + (
|
280 |
+
offs_m[:, None] * stride_om + offs_n[None, :])
|
281 |
+
if EVEN_M:
|
282 |
+
if EVEN_HEADDIM:
|
283 |
+
tl.store(out_ptrs, acc_o)
|
284 |
+
else:
|
285 |
+
tl.store(out_ptrs, acc_o, mask=offs_d[None, :] < headdim)
|
286 |
+
else:
|
287 |
+
if EVEN_HEADDIM:
|
288 |
+
tl.store(out_ptrs, acc_o, mask=offs_m[:, None] < seqlen_q)
|
289 |
+
else:
|
290 |
+
tl.store(out_ptrs,
|
291 |
+
acc_o,
|
292 |
+
mask=(offs_m[:, None] < seqlen_q) &
|
293 |
+
(offs_d[None, :] < headdim))
|
294 |
+
|
295 |
+
|
296 |
+
@triton.jit
|
297 |
+
def _bwd_preprocess_do_o_dot(
|
298 |
+
Out,
|
299 |
+
DO,
|
300 |
+
Delta,
|
301 |
+
stride_ob,
|
302 |
+
stride_oh,
|
303 |
+
stride_om,
|
304 |
+
stride_dob,
|
305 |
+
stride_doh,
|
306 |
+
stride_dom,
|
307 |
+
nheads,
|
308 |
+
seqlen_q,
|
309 |
+
seqlen_q_rounded,
|
310 |
+
headdim,
|
311 |
+
BLOCK_M: tl.constexpr,
|
312 |
+
BLOCK_HEADDIM: tl.constexpr,
|
313 |
+
):
|
314 |
+
start_m = tl.program_id(0)
|
315 |
+
off_hb = tl.program_id(1)
|
316 |
+
off_b = off_hb // nheads
|
317 |
+
off_h = off_hb % nheads
|
318 |
+
# initialize offsets
|
319 |
+
offs_m = start_m * BLOCK_M + tl.arange(0, BLOCK_M)
|
320 |
+
offs_d = tl.arange(0, BLOCK_HEADDIM)
|
321 |
+
# load
|
322 |
+
o = tl.load(Out + off_b * stride_ob + off_h * stride_oh +
|
323 |
+
offs_m[:, None] * stride_om + offs_d[None, :],
|
324 |
+
mask=(offs_m[:, None] < seqlen_q) & (offs_d[None, :] < headdim),
|
325 |
+
other=0.0).to(tl.float32)
|
326 |
+
do = tl.load(DO + off_b * stride_dob + off_h * stride_doh +
|
327 |
+
offs_m[:, None] * stride_dom + offs_d[None, :],
|
328 |
+
mask=(offs_m[:, None] < seqlen_q) &
|
329 |
+
(offs_d[None, :] < headdim),
|
330 |
+
other=0.0).to(tl.float32)
|
331 |
+
delta = tl.sum(o * do, axis=1)
|
332 |
+
# write-back
|
333 |
+
tl.store(Delta + off_hb * seqlen_q_rounded + offs_m, delta)
|
334 |
+
|
335 |
+
|
336 |
+
@triton.jit
|
337 |
+
def _bwd_kernel_one_col_block(
|
338 |
+
start_n,
|
339 |
+
Q,
|
340 |
+
K,
|
341 |
+
V,
|
342 |
+
Bias,
|
343 |
+
DO,
|
344 |
+
DQ,
|
345 |
+
DK,
|
346 |
+
DV,
|
347 |
+
LSE,
|
348 |
+
D,
|
349 |
+
softmax_scale,
|
350 |
+
stride_qm,
|
351 |
+
stride_kn,
|
352 |
+
stride_vn,
|
353 |
+
stride_bm,
|
354 |
+
stride_dom,
|
355 |
+
stride_dqm,
|
356 |
+
stride_dkn,
|
357 |
+
stride_dvn,
|
358 |
+
seqlen_q,
|
359 |
+
seqlen_k,
|
360 |
+
headdim,
|
361 |
+
ATOMIC_ADD: tl.constexpr,
|
362 |
+
BIAS_TYPE: tl.constexpr,
|
363 |
+
IS_CAUSAL: tl.constexpr,
|
364 |
+
BLOCK_HEADDIM: tl.constexpr,
|
365 |
+
EVEN_M: tl.constexpr,
|
366 |
+
EVEN_N: tl.constexpr,
|
367 |
+
EVEN_HEADDIM: tl.constexpr,
|
368 |
+
BLOCK_M: tl.constexpr,
|
369 |
+
BLOCK_N: tl.constexpr,
|
370 |
+
):
|
371 |
+
# We need to make sure begin_m is a multiple of BLOCK_M (not BLOCK_N)
|
372 |
+
begin_m = 0 if not IS_CAUSAL else ((start_n * BLOCK_N) // BLOCK_M) * BLOCK_M
|
373 |
+
# initialize row/col offsets
|
374 |
+
offs_qm = begin_m + tl.arange(0, BLOCK_M)
|
375 |
+
offs_n = start_n * BLOCK_N + tl.arange(0, BLOCK_N)
|
376 |
+
offs_m = tl.arange(0, BLOCK_M)
|
377 |
+
offs_d = tl.arange(0, BLOCK_HEADDIM)
|
378 |
+
# initialize pointers to value-like data
|
379 |
+
q_ptrs = Q + (offs_qm[:, None] * stride_qm + offs_d[None, :])
|
380 |
+
k_ptrs = K + (offs_n[:, None] * stride_kn + offs_d[None, :])
|
381 |
+
v_ptrs = V + (offs_n[:, None] * stride_vn + offs_d[None, :])
|
382 |
+
do_ptrs = DO + (offs_qm[:, None] * stride_dom + offs_d[None, :])
|
383 |
+
dq_ptrs = DQ + (offs_qm[:, None] * stride_dqm + offs_d[None, :])
|
384 |
+
if BIAS_TYPE == 'vector':
|
385 |
+
b_ptrs = Bias + offs_n
|
386 |
+
elif BIAS_TYPE == 'matrix':
|
387 |
+
b_ptrs = Bias + (offs_qm[:, None] * stride_bm + offs_n[None, :])
|
388 |
+
else:
|
389 |
+
raise ValueError("BIAS_TYPE must be one of {'vector', 'matrix'}")
|
390 |
+
# initialize dv and dk
|
391 |
+
dv = tl.zeros([BLOCK_N, BLOCK_HEADDIM], dtype=tl.float32)
|
392 |
+
dk = tl.zeros([BLOCK_N, BLOCK_HEADDIM], dtype=tl.float32)
|
393 |
+
# k and v stay in SRAM throughout
|
394 |
+
# [2022-10-30] TD: Same bug as the fwd. In the case of EVEN_N=True and EVEN_M=False,
|
395 |
+
# if we just call tl.load(k_ptrs), we get the wrong output!
|
396 |
+
if EVEN_N & EVEN_M:
|
397 |
+
if EVEN_HEADDIM:
|
398 |
+
k = tl.load(k_ptrs)
|
399 |
+
v = tl.load(v_ptrs)
|
400 |
+
else:
|
401 |
+
k = tl.load(k_ptrs, mask=offs_d[None, :] < headdim, other=0.0)
|
402 |
+
v = tl.load(v_ptrs, mask=offs_d[None, :] < headdim, other=0.0)
|
403 |
+
else:
|
404 |
+
if EVEN_HEADDIM:
|
405 |
+
k = tl.load(k_ptrs, mask=offs_n[:, None] < seqlen_k, other=0.0)
|
406 |
+
v = tl.load(v_ptrs, mask=offs_n[:, None] < seqlen_k, other=0.0)
|
407 |
+
else:
|
408 |
+
k = tl.load(k_ptrs,
|
409 |
+
mask=(offs_n[:, None] < seqlen_k) &
|
410 |
+
(offs_d[None, :] < headdim),
|
411 |
+
other=0.0)
|
412 |
+
v = tl.load(v_ptrs,
|
413 |
+
mask=(offs_n[:, None] < seqlen_k) &
|
414 |
+
(offs_d[None, :] < headdim),
|
415 |
+
other=0.0)
|
416 |
+
# loop over rows
|
417 |
+
num_block_m = tl.cdiv(seqlen_q, BLOCK_M)
|
418 |
+
for start_m in range(begin_m, num_block_m * BLOCK_M, BLOCK_M):
|
419 |
+
start_m = tl.multiple_of(start_m, BLOCK_M)
|
420 |
+
offs_m_curr = start_m + offs_m
|
421 |
+
# load q, k, v, do on-chip
|
422 |
+
# Same bug as below. Otherwise gives wrong result for headdim=40, seqlen=(128, 117)
|
423 |
+
if EVEN_M & EVEN_HEADDIM:
|
424 |
+
q = tl.load(q_ptrs)
|
425 |
+
else:
|
426 |
+
if EVEN_HEADDIM:
|
427 |
+
q = tl.load(q_ptrs,
|
428 |
+
mask=offs_m_curr[:, None] < seqlen_q,
|
429 |
+
other=0.0)
|
430 |
+
else:
|
431 |
+
q = tl.load(q_ptrs,
|
432 |
+
mask=(offs_m_curr[:, None] < seqlen_q) &
|
433 |
+
(offs_d[None, :] < headdim),
|
434 |
+
other=0.0)
|
435 |
+
# recompute p = softmax(qk, dim=-1).T
|
436 |
+
qk = tl.dot(q, k, trans_b=True)
|
437 |
+
# Trying to combine the two masks seem to make the result wrong
|
438 |
+
if not EVEN_N: # Need to mask out otherwise the softmax is wrong
|
439 |
+
qk = tl.where(offs_n[None, :] < seqlen_k, qk, float('-inf'))
|
440 |
+
if IS_CAUSAL:
|
441 |
+
qk = tl.where(offs_m_curr[:, None] >= (offs_n[None, :]), qk,
|
442 |
+
float('-inf'))
|
443 |
+
if BIAS_TYPE != 'none':
|
444 |
+
if BIAS_TYPE == 'vector':
|
445 |
+
if EVEN_N:
|
446 |
+
bias = tl.load(b_ptrs).to(tl.float32)
|
447 |
+
else:
|
448 |
+
bias = tl.load(b_ptrs, mask=offs_n < seqlen_k,
|
449 |
+
other=0.0).to(tl.float32)
|
450 |
+
bias = bias[None, :]
|
451 |
+
elif BIAS_TYPE == 'matrix':
|
452 |
+
if EVEN_M & EVEN_N:
|
453 |
+
bias = tl.load(b_ptrs).to(tl.float32)
|
454 |
+
else:
|
455 |
+
bias = tl.load(b_ptrs,
|
456 |
+
mask=(offs_m_curr[:, None] < seqlen_q) &
|
457 |
+
(offs_n[None, :] < seqlen_k),
|
458 |
+
other=0.0).to(tl.float32)
|
459 |
+
else:
|
460 |
+
raise ValueError(
|
461 |
+
"BIAS_TYPE must be one of {'vector', 'matrix'}")
|
462 |
+
qk = qk * softmax_scale + bias
|
463 |
+
# There seems to be a race condition when headdim=48/96, and dq, dk, dv are wrong.
|
464 |
+
# Also wrong for headdim=64.
|
465 |
+
if not (EVEN_M & EVEN_HEADDIM):
|
466 |
+
tl.debug_barrier()
|
467 |
+
lse_i = tl.load(LSE + offs_m_curr)
|
468 |
+
if BIAS_TYPE == 'none':
|
469 |
+
p = tl.exp(qk * softmax_scale - lse_i[:, None])
|
470 |
+
else:
|
471 |
+
p = tl.exp(qk - lse_i[:, None])
|
472 |
+
# compute dv
|
473 |
+
# [2022-10-30] TD: A Triton bug: if EVEN_M=True and EVEN_HEADDIM=False, if we call
|
474 |
+
# do = tl.load(do_ptrs, mask=offs_d[None, :] < headdim, other=0.0), we get wrong outputs
|
475 |
+
# in the case of headdim=48/96, seqlen_q & seqlen_k >= 512. If headdim=40 or seqlen < 512,
|
476 |
+
# the output is correct.
|
477 |
+
if EVEN_M & EVEN_HEADDIM:
|
478 |
+
do = tl.load(do_ptrs)
|
479 |
+
else:
|
480 |
+
# [2022-11-01] TD: Triton bug, there's a race condition if we just use m_mask and not d_mask.
|
481 |
+
do = tl.load(do_ptrs,
|
482 |
+
mask=(offs_m_curr[:, None] < seqlen_q) &
|
483 |
+
(offs_d[None, :] < headdim),
|
484 |
+
other=0.0)
|
485 |
+
# if EVEN_M:
|
486 |
+
# if EVEN_HEADDIM:
|
487 |
+
# do = tl.load(do_ptrs)
|
488 |
+
# else:
|
489 |
+
# do = tl.load(do_ptrs, mask=offs_d[None, :] < headdim, other=0.0)
|
490 |
+
# else:
|
491 |
+
# if EVEN_HEADDIM:
|
492 |
+
# do = tl.load(do_ptrs, mask=offs_m_curr[:, None] < seqlen_q, other=0.0)
|
493 |
+
# else:
|
494 |
+
# do = tl.load(do_ptrs, mask=(offs_m_curr[:, None] < seqlen_q)
|
495 |
+
# & (offs_d[None, :] < headdim), other=0.0)
|
496 |
+
dv += tl.dot(p.to(do.dtype), do, trans_a=True)
|
497 |
+
# compute dp = dot(v, do)
|
498 |
+
# There seems to be a race condition when headdim=48/96, and dq, dk are wrong.
|
499 |
+
# Also wrong for headdim=128, seqlen=(108, 256), and ATOMIC_ADD=True
|
500 |
+
# Also wrong for headdim=64, seqlen=(1023, 1024), and ATOMIC_ADD=False
|
501 |
+
if not (EVEN_M & EVEN_HEADDIM):
|
502 |
+
tl.debug_barrier()
|
503 |
+
dp = tl.dot(do, v, trans_b=True)
|
504 |
+
# There's a race condition for headdim=48
|
505 |
+
if not EVEN_HEADDIM:
|
506 |
+
tl.debug_barrier()
|
507 |
+
# compute ds = p * (dp - delta[:, None])
|
508 |
+
# Putting the subtraction after the dp matmul (instead of before) is slightly faster
|
509 |
+
Di = tl.load(D + offs_m_curr)
|
510 |
+
# Converting ds to q.dtype here reduces register pressure and makes it much faster
|
511 |
+
# for BLOCK_HEADDIM=128
|
512 |
+
ds = (p * (dp - Di[:, None]) * softmax_scale).to(q.dtype)
|
513 |
+
# compute dk = dot(ds.T, q)
|
514 |
+
dk += tl.dot(ds, q, trans_a=True)
|
515 |
+
# compute dq
|
516 |
+
if not ATOMIC_ADD:
|
517 |
+
if EVEN_M & EVEN_HEADDIM: # Race condition if we just do EVEN_M
|
518 |
+
dq = tl.load(dq_ptrs, eviction_policy='evict_last')
|
519 |
+
dq += tl.dot(ds, k)
|
520 |
+
tl.store(dq_ptrs, dq, eviction_policy='evict_last')
|
521 |
+
else:
|
522 |
+
if EVEN_HEADDIM:
|
523 |
+
dq = tl.load(dq_ptrs,
|
524 |
+
mask=offs_m_curr[:, None] < seqlen_q,
|
525 |
+
other=0.0,
|
526 |
+
eviction_policy='evict_last')
|
527 |
+
dq += tl.dot(ds, k)
|
528 |
+
tl.store(dq_ptrs,
|
529 |
+
dq,
|
530 |
+
mask=offs_m_curr[:, None] < seqlen_q,
|
531 |
+
eviction_policy='evict_last')
|
532 |
+
else:
|
533 |
+
dq = tl.load(dq_ptrs,
|
534 |
+
mask=(offs_m_curr[:, None] < seqlen_q) &
|
535 |
+
(offs_d[None, :] < headdim),
|
536 |
+
other=0.0,
|
537 |
+
eviction_policy='evict_last')
|
538 |
+
dq += tl.dot(ds, k)
|
539 |
+
tl.store(dq_ptrs,
|
540 |
+
dq,
|
541 |
+
mask=(offs_m_curr[:, None] < seqlen_q) &
|
542 |
+
(offs_d[None, :] < headdim),
|
543 |
+
eviction_policy='evict_last')
|
544 |
+
else: # If we're parallelizing across the seqlen_k dimension
|
545 |
+
dq = tl.dot(ds, k)
|
546 |
+
if EVEN_M & EVEN_HEADDIM: # Race condition if we just do EVEN_M
|
547 |
+
tl.atomic_add(dq_ptrs, dq)
|
548 |
+
else:
|
549 |
+
if EVEN_HEADDIM:
|
550 |
+
tl.atomic_add(dq_ptrs,
|
551 |
+
dq,
|
552 |
+
mask=offs_m_curr[:, None] < seqlen_q)
|
553 |
+
else:
|
554 |
+
tl.atomic_add(dq_ptrs,
|
555 |
+
dq,
|
556 |
+
mask=(offs_m_curr[:, None] < seqlen_q) &
|
557 |
+
(offs_d[None, :] < headdim))
|
558 |
+
# increment pointers
|
559 |
+
dq_ptrs += BLOCK_M * stride_dqm
|
560 |
+
q_ptrs += BLOCK_M * stride_qm
|
561 |
+
do_ptrs += BLOCK_M * stride_dom
|
562 |
+
if BIAS_TYPE == 'matrix':
|
563 |
+
b_ptrs += BLOCK_M * stride_bm
|
564 |
+
# write-back
|
565 |
+
dv_ptrs = DV + (offs_n[:, None] * stride_dvn + offs_d[None, :])
|
566 |
+
dk_ptrs = DK + (offs_n[:, None] * stride_dkn + offs_d[None, :])
|
567 |
+
# [2022-11-01] TD: Same bug. In the case of EVEN_N=True and EVEN_M=False,
|
568 |
+
# if we just call tl.store(dv_ptrs), there's a race condition
|
569 |
+
if EVEN_N & EVEN_M:
|
570 |
+
if EVEN_HEADDIM:
|
571 |
+
tl.store(dv_ptrs, dv)
|
572 |
+
tl.store(dk_ptrs, dk)
|
573 |
+
else:
|
574 |
+
tl.store(dv_ptrs, dv, mask=offs_d[None, :] < headdim)
|
575 |
+
tl.store(dk_ptrs, dk, mask=offs_d[None, :] < headdim)
|
576 |
+
else:
|
577 |
+
if EVEN_HEADDIM:
|
578 |
+
tl.store(dv_ptrs, dv, mask=offs_n[:, None] < seqlen_k)
|
579 |
+
tl.store(dk_ptrs, dk, mask=offs_n[:, None] < seqlen_k)
|
580 |
+
else:
|
581 |
+
tl.store(dv_ptrs,
|
582 |
+
dv,
|
583 |
+
mask=(offs_n[:, None] < seqlen_k) &
|
584 |
+
(offs_d[None, :] < headdim))
|
585 |
+
tl.store(dk_ptrs,
|
586 |
+
dk,
|
587 |
+
mask=(offs_n[:, None] < seqlen_k) &
|
588 |
+
(offs_d[None, :] < headdim))
|
589 |
+
|
590 |
+
|
591 |
+
def init_to_zero(name):
|
592 |
+
return lambda nargs: nargs[name].zero_()
|
593 |
+
|
594 |
+
|
595 |
+
@triton.autotune(
|
596 |
+
configs=[
|
597 |
+
triton.Config(
|
598 |
+
{
|
599 |
+
'BLOCK_M': 128,
|
600 |
+
'BLOCK_N': 128,
|
601 |
+
'SEQUENCE_PARALLEL': False
|
602 |
+
},
|
603 |
+
num_warps=8,
|
604 |
+
num_stages=1,
|
605 |
+
pre_hook=init_to_zero('DQ')),
|
606 |
+
triton.Config(
|
607 |
+
{
|
608 |
+
'BLOCK_M': 128,
|
609 |
+
'BLOCK_N': 128,
|
610 |
+
'SEQUENCE_PARALLEL': True
|
611 |
+
},
|
612 |
+
num_warps=8,
|
613 |
+
num_stages=1,
|
614 |
+
pre_hook=init_to_zero('DQ')),
|
615 |
+
# Other configs seem to give wrong results when seqlen_q % 128 != 0, disabling them for now
|
616 |
+
# # Kernel is buggy (give wrong result) if we set BLOCK_m=128, BLOCK_n=64, num_warps=*4*
|
617 |
+
# triton.Config({"BLOCK_M": 128, "BLOCK_N": 64, "SEQUENCE_PARALLEL": False}, num_warps=8, num_stages=1, pre_hook=init_to_zero('DQ')),
|
618 |
+
# triton.Config({"BLOCK_M": 128, "BLOCK_N": 64, "SEQUENCE_PARALLEL": True}, num_warps=8, num_stages=1, pre_hook=init_to_zero('DQ')),
|
619 |
+
# triton.Config({"BLOCK_M": 64, "BLOCK_N": 64, "SEQUENCE_PARALLEL": False}, num_warps=4, num_stages=1, pre_hook=init_to_zero('DQ')),
|
620 |
+
# triton.Config({"BLOCK_M": 64, "BLOCK_N": 64, "SEQUENCE_PARALLEL": True}, num_warps=4, num_stages=1, pre_hook=init_to_zero('DQ')),
|
621 |
+
],
|
622 |
+
key=[
|
623 |
+
'CACHE_KEY_SEQLEN_Q', 'CACHE_KEY_SEQLEN_K', 'BIAS_TYPE', 'IS_CAUSAL',
|
624 |
+
'BLOCK_HEADDIM'
|
625 |
+
],
|
626 |
+
)
|
627 |
+
@triton.heuristics({
|
628 |
+
'EVEN_M': lambda args: args['seqlen_q'] % args['BLOCK_M'] == 0,
|
629 |
+
'EVEN_N': lambda args: args['seqlen_k'] % args['BLOCK_N'] == 0,
|
630 |
+
'EVEN_HEADDIM': lambda args: args['headdim'] == args['BLOCK_HEADDIM'],
|
631 |
+
})
|
632 |
+
@triton.jit
|
633 |
+
def _bwd_kernel(
|
634 |
+
Q,
|
635 |
+
K,
|
636 |
+
V,
|
637 |
+
Bias,
|
638 |
+
DO,
|
639 |
+
DQ,
|
640 |
+
DK,
|
641 |
+
DV,
|
642 |
+
LSE,
|
643 |
+
D,
|
644 |
+
softmax_scale,
|
645 |
+
stride_qb,
|
646 |
+
stride_qh,
|
647 |
+
stride_qm,
|
648 |
+
stride_kb,
|
649 |
+
stride_kh,
|
650 |
+
stride_kn,
|
651 |
+
stride_vb,
|
652 |
+
stride_vh,
|
653 |
+
stride_vn,
|
654 |
+
stride_bb,
|
655 |
+
stride_bh,
|
656 |
+
stride_bm,
|
657 |
+
stride_dob,
|
658 |
+
stride_doh,
|
659 |
+
stride_dom,
|
660 |
+
stride_dqb,
|
661 |
+
stride_dqh,
|
662 |
+
stride_dqm,
|
663 |
+
stride_dkb,
|
664 |
+
stride_dkh,
|
665 |
+
stride_dkn,
|
666 |
+
stride_dvb,
|
667 |
+
stride_dvh,
|
668 |
+
stride_dvn,
|
669 |
+
nheads,
|
670 |
+
seqlen_q,
|
671 |
+
seqlen_k,
|
672 |
+
seqlen_q_rounded,
|
673 |
+
headdim,
|
674 |
+
CACHE_KEY_SEQLEN_Q,
|
675 |
+
CACHE_KEY_SEQLEN_K,
|
676 |
+
BIAS_TYPE: tl.constexpr,
|
677 |
+
IS_CAUSAL: tl.constexpr,
|
678 |
+
BLOCK_HEADDIM: tl.constexpr,
|
679 |
+
SEQUENCE_PARALLEL: tl.constexpr,
|
680 |
+
EVEN_M: tl.constexpr,
|
681 |
+
EVEN_N: tl.constexpr,
|
682 |
+
EVEN_HEADDIM: tl.constexpr,
|
683 |
+
BLOCK_M: tl.constexpr,
|
684 |
+
BLOCK_N: tl.constexpr,
|
685 |
+
):
|
686 |
+
off_hb = tl.program_id(1)
|
687 |
+
off_b = off_hb // nheads
|
688 |
+
off_h = off_hb % nheads
|
689 |
+
# offset pointers for batch/head
|
690 |
+
Q += off_b * stride_qb + off_h * stride_qh
|
691 |
+
K += off_b * stride_kb + off_h * stride_kh
|
692 |
+
V += off_b * stride_vb + off_h * stride_vh
|
693 |
+
DO += off_b * stride_dob + off_h * stride_doh
|
694 |
+
DQ += off_b * stride_dqb + off_h * stride_dqh
|
695 |
+
DK += off_b * stride_dkb + off_h * stride_dkh
|
696 |
+
DV += off_b * stride_dvb + off_h * stride_dvh
|
697 |
+
if BIAS_TYPE != 'none':
|
698 |
+
Bias += off_b * stride_bb + off_h * stride_bh
|
699 |
+
# pointer to row-wise quantities in value-like data
|
700 |
+
D += off_hb * seqlen_q_rounded
|
701 |
+
LSE += off_hb * seqlen_q_rounded
|
702 |
+
if not SEQUENCE_PARALLEL:
|
703 |
+
num_block_n = tl.cdiv(seqlen_k, BLOCK_N)
|
704 |
+
for start_n in range(0, num_block_n):
|
705 |
+
_bwd_kernel_one_col_block(start_n,
|
706 |
+
Q,
|
707 |
+
K,
|
708 |
+
V,
|
709 |
+
Bias,
|
710 |
+
DO,
|
711 |
+
DQ,
|
712 |
+
DK,
|
713 |
+
DV,
|
714 |
+
LSE,
|
715 |
+
D,
|
716 |
+
softmax_scale,
|
717 |
+
stride_qm,
|
718 |
+
stride_kn,
|
719 |
+
stride_vn,
|
720 |
+
stride_bm,
|
721 |
+
stride_dom,
|
722 |
+
stride_dqm,
|
723 |
+
stride_dkn,
|
724 |
+
stride_dvn,
|
725 |
+
seqlen_q,
|
726 |
+
seqlen_k,
|
727 |
+
headdim,
|
728 |
+
ATOMIC_ADD=False,
|
729 |
+
BIAS_TYPE=BIAS_TYPE,
|
730 |
+
IS_CAUSAL=IS_CAUSAL,
|
731 |
+
BLOCK_HEADDIM=BLOCK_HEADDIM,
|
732 |
+
EVEN_M=EVEN_M,
|
733 |
+
EVEN_N=EVEN_N,
|
734 |
+
EVEN_HEADDIM=EVEN_HEADDIM,
|
735 |
+
BLOCK_M=BLOCK_M,
|
736 |
+
BLOCK_N=BLOCK_N)
|
737 |
+
else:
|
738 |
+
start_n = tl.program_id(0)
|
739 |
+
_bwd_kernel_one_col_block(start_n,
|
740 |
+
Q,
|
741 |
+
K,
|
742 |
+
V,
|
743 |
+
Bias,
|
744 |
+
DO,
|
745 |
+
DQ,
|
746 |
+
DK,
|
747 |
+
DV,
|
748 |
+
LSE,
|
749 |
+
D,
|
750 |
+
softmax_scale,
|
751 |
+
stride_qm,
|
752 |
+
stride_kn,
|
753 |
+
stride_vn,
|
754 |
+
stride_bm,
|
755 |
+
stride_dom,
|
756 |
+
stride_dqm,
|
757 |
+
stride_dkn,
|
758 |
+
stride_dvn,
|
759 |
+
seqlen_q,
|
760 |
+
seqlen_k,
|
761 |
+
headdim,
|
762 |
+
ATOMIC_ADD=True,
|
763 |
+
BIAS_TYPE=BIAS_TYPE,
|
764 |
+
IS_CAUSAL=IS_CAUSAL,
|
765 |
+
BLOCK_HEADDIM=BLOCK_HEADDIM,
|
766 |
+
EVEN_M=EVEN_M,
|
767 |
+
EVEN_N=EVEN_N,
|
768 |
+
EVEN_HEADDIM=EVEN_HEADDIM,
|
769 |
+
BLOCK_M=BLOCK_M,
|
770 |
+
BLOCK_N=BLOCK_N)
|
771 |
+
|
772 |
+
|
773 |
+
def _flash_attn_forward(q, k, v, bias=None, causal=False, softmax_scale=None):
|
774 |
+
# shape constraints
|
775 |
+
batch, seqlen_q, nheads, d = q.shape
|
776 |
+
_, seqlen_k, _, _ = k.shape
|
777 |
+
assert k.shape == (batch, seqlen_k, nheads, d)
|
778 |
+
assert v.shape == (batch, seqlen_k, nheads, d)
|
779 |
+
assert d <= 128, 'FlashAttention only support head dimensions up to 128'
|
780 |
+
assert q.dtype == k.dtype == v.dtype, 'All tensors must have the same type'
|
781 |
+
assert q.dtype in [torch.float16,
|
782 |
+
torch.bfloat16], 'Only support fp16 and bf16'
|
783 |
+
assert q.is_cuda and k.is_cuda and v.is_cuda
|
784 |
+
softmax_scale = softmax_scale or 1.0 / math.sqrt(d)
|
785 |
+
|
786 |
+
has_bias = bias is not None
|
787 |
+
bias_type = 'none'
|
788 |
+
if has_bias:
|
789 |
+
assert bias.dtype in [q.dtype, torch.float]
|
790 |
+
assert bias.is_cuda
|
791 |
+
assert bias.dim() == 4
|
792 |
+
if bias.stride(-1) != 1:
|
793 |
+
bias = bias.contiguous()
|
794 |
+
if bias.shape[2:] == (1, seqlen_k):
|
795 |
+
bias_type = 'vector'
|
796 |
+
elif bias.shape[2:] == (seqlen_q, seqlen_k):
|
797 |
+
bias_type = 'matrix'
|
798 |
+
else:
|
799 |
+
raise RuntimeError('Last 2 dimensions of bias must be (1, seqlen_k)'
|
800 |
+
' or (seqlen_q, seqlen_k)')
|
801 |
+
if bias.shape[:2] == (1, nheads):
|
802 |
+
bias = repeat(bias, '1 h ... -> b h ...', b=batch)
|
803 |
+
elif bias.shape[:2] == (batch, 1):
|
804 |
+
bias = repeat(bias, 'b 1 ... -> b h ...', h=nheads)
|
805 |
+
elif bias.shape[:2] == (1, 1):
|
806 |
+
bias = repeat(bias, '1 h ... -> b h ...', b=batch)
|
807 |
+
bias = repeat(bias, 'b 1 ... -> b h ...', h=nheads)
|
808 |
+
assert bias.shape[:2] == (
|
809 |
+
batch, nheads
|
810 |
+
), f'First 2 dimensions of bias must be broadcastible to (batch, nheads) = ({batch, nheads}). Bias has shape: {bias.shape}'
|
811 |
+
assert bias is not None # for type checking
|
812 |
+
bias_strides = (bias.stride(0), bias.stride(1),
|
813 |
+
bias.stride(2)) if has_bias else (0, 0, 0)
|
814 |
+
|
815 |
+
seqlen_q_rounded = math.ceil(seqlen_q / 128) * 128
|
816 |
+
lse = torch.empty((batch, nheads, seqlen_q_rounded),
|
817 |
+
device=q.device,
|
818 |
+
dtype=torch.float32)
|
819 |
+
tmp = torch.empty((batch, nheads, seqlen_q_rounded),
|
820 |
+
device=q.device,
|
821 |
+
dtype=torch.float32)
|
822 |
+
o = torch.empty_like(q)
|
823 |
+
|
824 |
+
BLOCK_HEADDIM = max(triton.next_power_of_2(d), 16)
|
825 |
+
# BLOCK = 128
|
826 |
+
# num_warps = 4 if d <= 64 else 8
|
827 |
+
grid = lambda META: (triton.cdiv(seqlen_q, META['BLOCK_M']), batch * nheads)
|
828 |
+
_fwd_kernel[grid]( # type: ignore
|
829 |
+
q,
|
830 |
+
k,
|
831 |
+
v,
|
832 |
+
bias,
|
833 |
+
o,
|
834 |
+
lse,
|
835 |
+
tmp,
|
836 |
+
softmax_scale,
|
837 |
+
q.stride(0),
|
838 |
+
q.stride(2),
|
839 |
+
q.stride(1),
|
840 |
+
k.stride(0),
|
841 |
+
k.stride(2),
|
842 |
+
k.stride(1),
|
843 |
+
v.stride(0),
|
844 |
+
v.stride(2),
|
845 |
+
v.stride(1),
|
846 |
+
*bias_strides,
|
847 |
+
o.stride(0),
|
848 |
+
o.stride(2),
|
849 |
+
o.stride(1),
|
850 |
+
nheads,
|
851 |
+
seqlen_q,
|
852 |
+
seqlen_k,
|
853 |
+
seqlen_q_rounded,
|
854 |
+
d,
|
855 |
+
seqlen_q // 32,
|
856 |
+
seqlen_k // 32, # key for triton cache (limit number of compilations)
|
857 |
+
# Can't use kwargs here because triton autotune expects key to be args, not kwargs
|
858 |
+
# IS_CAUSAL=causal, BLOCK_HEADDIM=d,
|
859 |
+
bias_type,
|
860 |
+
causal,
|
861 |
+
BLOCK_HEADDIM,
|
862 |
+
# BLOCK_M=BLOCK, BLOCK_N=BLOCK,
|
863 |
+
# num_warps=num_warps,
|
864 |
+
# num_stages=1,
|
865 |
+
)
|
866 |
+
return o, lse, softmax_scale # softmax_scale could have been updated
|
867 |
+
|
868 |
+
|
869 |
+
def _flash_attn_backward(do,
|
870 |
+
q,
|
871 |
+
k,
|
872 |
+
v,
|
873 |
+
o,
|
874 |
+
lse,
|
875 |
+
dq,
|
876 |
+
dk,
|
877 |
+
dv,
|
878 |
+
bias=None,
|
879 |
+
causal=False,
|
880 |
+
softmax_scale=None):
|
881 |
+
# Make sure that the last dimension is contiguous
|
882 |
+
if do.stride(-1) != 1:
|
883 |
+
do = do.contiguous()
|
884 |
+
batch, seqlen_q, nheads, d = q.shape
|
885 |
+
_, seqlen_k, _, _ = k.shape
|
886 |
+
# assert d in {16, 32, 64, 128}
|
887 |
+
assert d <= 128
|
888 |
+
seqlen_q_rounded = math.ceil(seqlen_q / 128) * 128
|
889 |
+
assert lse.shape == (batch, nheads, seqlen_q_rounded)
|
890 |
+
assert q.stride(-1) == k.stride(-1) == v.stride(-1) == o.stride(-1) == 1
|
891 |
+
assert dq.stride(-1) == dk.stride(-1) == dv.stride(-1) == 1
|
892 |
+
softmax_scale = softmax_scale or 1.0 / math.sqrt(d)
|
893 |
+
# dq_accum = torch.zeros_like(q, dtype=torch.float32)
|
894 |
+
dq_accum = torch.empty_like(q, dtype=torch.float32)
|
895 |
+
delta = torch.empty_like(lse)
|
896 |
+
# delta = torch.zeros_like(lse)
|
897 |
+
|
898 |
+
BLOCK_HEADDIM = max(triton.next_power_of_2(d), 16)
|
899 |
+
grid = lambda META: (triton.cdiv(seqlen_q, META['BLOCK_M']), batch * nheads)
|
900 |
+
_bwd_preprocess_do_o_dot[grid]( # type: ignore
|
901 |
+
o,
|
902 |
+
do,
|
903 |
+
delta,
|
904 |
+
o.stride(0),
|
905 |
+
o.stride(2),
|
906 |
+
o.stride(1),
|
907 |
+
do.stride(0),
|
908 |
+
do.stride(2),
|
909 |
+
do.stride(1),
|
910 |
+
nheads,
|
911 |
+
seqlen_q,
|
912 |
+
seqlen_q_rounded,
|
913 |
+
d,
|
914 |
+
BLOCK_M=128,
|
915 |
+
BLOCK_HEADDIM=BLOCK_HEADDIM,
|
916 |
+
)
|
917 |
+
|
918 |
+
has_bias = bias is not None
|
919 |
+
bias_type = 'none'
|
920 |
+
if has_bias:
|
921 |
+
assert bias.dtype in [q.dtype, torch.float]
|
922 |
+
assert bias.is_cuda
|
923 |
+
assert bias.dim() == 4
|
924 |
+
assert bias.stride(-1) == 1
|
925 |
+
if bias.shape[2:] == (1, seqlen_k):
|
926 |
+
bias_type = 'vector'
|
927 |
+
elif bias.shape[2:] == (seqlen_q, seqlen_k):
|
928 |
+
bias_type = 'matrix'
|
929 |
+
else:
|
930 |
+
raise RuntimeError('Last 2 dimensions of bias must be (1, seqlen_k)'
|
931 |
+
' or (seqlen_q, seqlen_k)')
|
932 |
+
if bias.shape[:2] == (1, nheads):
|
933 |
+
bias = repeat(bias, '1 h ... -> b h ...', b=batch)
|
934 |
+
elif bias.shape[:2] == (batch, 1):
|
935 |
+
bias = repeat(bias, 'b 1 ... -> b h ...', h=nheads)
|
936 |
+
elif bias.shape[:2] == (1, 1):
|
937 |
+
bias = repeat(bias, '1 h ... -> b h ...', b=batch)
|
938 |
+
bias = repeat(bias, 'b 1 ... -> b h ...', h=nheads)
|
939 |
+
assert bias.shape[:2] == (
|
940 |
+
batch, nheads
|
941 |
+
), f'First 2 dimensions of bias must be broadcastible to (batch, nheads) = ({batch, nheads}). Bias has shape: {bias.shape}'
|
942 |
+
assert bias is not None # type checking
|
943 |
+
bias_strides = (bias.stride(0), bias.stride(1),
|
944 |
+
bias.stride(2)) if has_bias else (0, 0, 0)
|
945 |
+
|
946 |
+
# BLOCK_M = 128
|
947 |
+
# BLOCK_N = 64
|
948 |
+
# num_warps = 4
|
949 |
+
grid = lambda META: (triton.cdiv(seqlen_k, META['BLOCK_N'])
|
950 |
+
if META['SEQUENCE_PARALLEL'] else 1, batch * nheads)
|
951 |
+
_bwd_kernel[grid]( # type: ignore
|
952 |
+
q,
|
953 |
+
k,
|
954 |
+
v,
|
955 |
+
bias,
|
956 |
+
do,
|
957 |
+
dq_accum,
|
958 |
+
dk,
|
959 |
+
dv,
|
960 |
+
lse,
|
961 |
+
delta,
|
962 |
+
softmax_scale,
|
963 |
+
q.stride(0),
|
964 |
+
q.stride(2),
|
965 |
+
q.stride(1),
|
966 |
+
k.stride(0),
|
967 |
+
k.stride(2),
|
968 |
+
k.stride(1),
|
969 |
+
v.stride(0),
|
970 |
+
v.stride(2),
|
971 |
+
v.stride(1),
|
972 |
+
*bias_strides,
|
973 |
+
do.stride(0),
|
974 |
+
do.stride(2),
|
975 |
+
do.stride(1),
|
976 |
+
dq_accum.stride(0),
|
977 |
+
dq_accum.stride(2),
|
978 |
+
dq_accum.stride(1),
|
979 |
+
dk.stride(0),
|
980 |
+
dk.stride(2),
|
981 |
+
dk.stride(1),
|
982 |
+
dv.stride(0),
|
983 |
+
dv.stride(2),
|
984 |
+
dv.stride(1),
|
985 |
+
nheads,
|
986 |
+
seqlen_q,
|
987 |
+
seqlen_k,
|
988 |
+
seqlen_q_rounded,
|
989 |
+
d,
|
990 |
+
seqlen_q // 32,
|
991 |
+
seqlen_k // 32, # key for triton cache (limit number of compilations)
|
992 |
+
# Can't use kwargs here because triton autotune expects key to be args, not kwargs
|
993 |
+
# IS_CAUSAL=causal, BLOCK_HEADDIM=d,
|
994 |
+
bias_type,
|
995 |
+
causal,
|
996 |
+
BLOCK_HEADDIM,
|
997 |
+
# SEQUENCE_PARALLEL=False,
|
998 |
+
# BLOCK_M=BLOCK_M, BLOCK_N=BLOCK_N,
|
999 |
+
# num_warps=num_warps,
|
1000 |
+
# num_stages=1,
|
1001 |
+
)
|
1002 |
+
dq.copy_(dq_accum)
|
1003 |
+
|
1004 |
+
|
1005 |
+
class _FlashAttnQKVPackedFunc(torch.autograd.Function):
|
1006 |
+
|
1007 |
+
@staticmethod
|
1008 |
+
def forward(ctx, qkv, bias=None, causal=False, softmax_scale=None):
|
1009 |
+
"""Forward pass for packed FlashAttention.
|
1010 |
+
|
1011 |
+
Args:
|
1012 |
+
ctx: autograd context
|
1013 |
+
qkv: (batch, seqlen, 3, nheads, headdim)
|
1014 |
+
bias: optional, shape broadcastible to (batch, nheads, seqlen, seqlen).
|
1015 |
+
For example, ALiBi mask for causal would have shape (1, nheads, 1, seqlen).
|
1016 |
+
ALiBi mask for non-causal would have shape (1, nheads, seqlen, seqlen)
|
1017 |
+
causal (bool): whether to incorporate causal attention masking
|
1018 |
+
softmax_scale (float, optional): scale factor for softmax
|
1019 |
+
"""
|
1020 |
+
# Make sure that the last dimension is contiguous
|
1021 |
+
if qkv.stride(-1) != 1:
|
1022 |
+
qkv = qkv.contiguous()
|
1023 |
+
o, lse, ctx.softmax_scale = _flash_attn_forward(
|
1024 |
+
qkv[:, :, 0],
|
1025 |
+
qkv[:, :, 1],
|
1026 |
+
qkv[:, :, 2],
|
1027 |
+
bias=bias,
|
1028 |
+
causal=causal,
|
1029 |
+
softmax_scale=softmax_scale)
|
1030 |
+
ctx.save_for_backward(qkv, o, lse, bias)
|
1031 |
+
ctx.causal = causal
|
1032 |
+
return o
|
1033 |
+
|
1034 |
+
@staticmethod
|
1035 |
+
def backward(ctx, do):
|
1036 |
+
qkv, o, lse, bias = ctx.saved_tensors
|
1037 |
+
assert not ctx.needs_input_grad[
|
1038 |
+
1], 'FlashAttention does not support bias gradient yet'
|
1039 |
+
# Triton's autotune causes the Tensor._version to change, and so Pytorch autograd
|
1040 |
+
# does a memcpy. To avoid this we run in inference_mode, which doesn't track the version.
|
1041 |
+
with torch.inference_mode():
|
1042 |
+
dqkv = torch.empty_like(qkv)
|
1043 |
+
_flash_attn_backward(do,
|
1044 |
+
qkv[:, :, 0],
|
1045 |
+
qkv[:, :, 1],
|
1046 |
+
qkv[:, :, 2],
|
1047 |
+
o,
|
1048 |
+
lse,
|
1049 |
+
dqkv[:, :, 0],
|
1050 |
+
dqkv[:, :, 1],
|
1051 |
+
dqkv[:, :, 2],
|
1052 |
+
bias=bias,
|
1053 |
+
causal=ctx.causal,
|
1054 |
+
softmax_scale=ctx.softmax_scale)
|
1055 |
+
return dqkv, None, None, None
|
1056 |
+
|
1057 |
+
|
1058 |
+
flash_attn_qkvpacked_func = _FlashAttnQKVPackedFunc.apply
|
1059 |
+
|
1060 |
+
|
1061 |
+
class _FlashAttnFunc(torch.autograd.Function):
|
1062 |
+
|
1063 |
+
@staticmethod
|
1064 |
+
def forward(ctx, q, k, v, bias=None, causal=False, softmax_scale=None):
|
1065 |
+
"""Forward pass for FlashAttention.
|
1066 |
+
|
1067 |
+
Args:
|
1068 |
+
ctx: autograd context
|
1069 |
+
q: (batch_size, seqlen_q, nheads, headdim)
|
1070 |
+
k: (batch_size, seqlen_k, nheads, headdim)
|
1071 |
+
v: (batch_size, seqlen_k, nheads, headdim)
|
1072 |
+
bias: optional, shape broadcastible to (batch, nheads, seqlen_q, seqlen_k).
|
1073 |
+
For example, ALiBi mask for causal would have shape (1, nheads, 1, seqlen_k).
|
1074 |
+
ALiBi mask for non-causal would have shape (1, nheads, seqlen_q, seqlen_k)
|
1075 |
+
causal (bool): whether to incorporate causal attention masking
|
1076 |
+
softmax_scale (float, optional): scale factor for softmax
|
1077 |
+
"""
|
1078 |
+
# Make sure that the last dimension is contiguous
|
1079 |
+
q, k, v = [
|
1080 |
+
x if x.stride(-1) == 1 else x.contiguous() for x in [q, k, v]
|
1081 |
+
]
|
1082 |
+
o, lse, ctx.softmax_scale = _flash_attn_forward(
|
1083 |
+
q, k, v, bias=bias, causal=causal, softmax_scale=softmax_scale)
|
1084 |
+
ctx.save_for_backward(q, k, v, o, lse, bias)
|
1085 |
+
ctx.causal = causal
|
1086 |
+
return o
|
1087 |
+
|
1088 |
+
@staticmethod
|
1089 |
+
def backward(ctx, do):
|
1090 |
+
q, k, v, o, lse, bias = ctx.saved_tensors
|
1091 |
+
assert not ctx.needs_input_grad[
|
1092 |
+
3], 'FlashAttention does not support bias gradient yet'
|
1093 |
+
# Triton's autotune causes the Tensor._version to change, and so Pytorch autograd
|
1094 |
+
# does a memcpy. To avoid this we run in inference_mode, which doesn't track the version.
|
1095 |
+
with torch.inference_mode():
|
1096 |
+
dq = torch.empty_like(q)
|
1097 |
+
dk = torch.empty_like(k)
|
1098 |
+
dv = torch.empty_like(v)
|
1099 |
+
_flash_attn_backward(do,
|
1100 |
+
q,
|
1101 |
+
k,
|
1102 |
+
v,
|
1103 |
+
o,
|
1104 |
+
lse,
|
1105 |
+
dq,
|
1106 |
+
dk,
|
1107 |
+
dv,
|
1108 |
+
bias=bias,
|
1109 |
+
causal=ctx.causal,
|
1110 |
+
softmax_scale=ctx.softmax_scale)
|
1111 |
+
return dq, dk, dv, None, None, None
|
1112 |
+
|
1113 |
+
|
1114 |
+
flash_attn_func = _FlashAttnFunc.apply
|
pytorch_model.bin
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:dbb1a038c13fd313a6afb560c853b4f5a85a1ea71375f5523072c8c29ded443d
|
3 |
+
size 1243213121
|
special_tokens_map.json
ADDED
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"bos_token": "<|bos|>",
|
3 |
+
"eos_token": "<|eos|>",
|
4 |
+
"mask_token": "<|mask|>",
|
5 |
+
"pad_token": "<|pad|>",
|
6 |
+
"unk_token": "<|unk|>"
|
7 |
+
}
|
tokenization_SEA_BPE.py
ADDED
@@ -0,0 +1,292 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
from shutil import copyfile
|
3 |
+
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple
|
4 |
+
import sentencepiece as spm
|
5 |
+
from tokenizers import processors
|
6 |
+
|
7 |
+
|
8 |
+
from transformers.tokenization_utils import AddedToken, PreTrainedTokenizer
|
9 |
+
from transformers.utils import logging
|
10 |
+
|
11 |
+
logger = logging.get_logger(__name__)
|
12 |
+
VOCAB_FILES_NAMES = {"vocab_file": "tokenizer.model"}
|
13 |
+
SPIECE_UNDERLINE = "▁"
|
14 |
+
|
15 |
+
class SEABPETokenizer(PreTrainedTokenizer):
|
16 |
+
"""
|
17 |
+
Construct a Llama tokenizer. Based on byte-level Byte-Pair-Encoding. The default padding token is unset as there is
|
18 |
+
no padding token in the original model.
|
19 |
+
|
20 |
+
Args:
|
21 |
+
vocab_file (`str`):
|
22 |
+
Path to the vocabulary file.
|
23 |
+
legacy (`bool`, *optional*, defaults to `True`):
|
24 |
+
Whether or not the `legacy` behaviour of the tokenizer should be used. Legacy is before the merge of #24622
|
25 |
+
which includes fixes to properly handle tokens that appear after special tokens.
|
26 |
+
legacy means we are not modifying existing tokenizers without knowing. (And we need to manually update those core tokenizers)
|
27 |
+
|
28 |
+
A simple example:
|
29 |
+
|
30 |
+
- `legacy=True`:
|
31 |
+
```python
|
32 |
+
>>> from transformers import T5Tokenizer
|
33 |
+
|
34 |
+
>>> tokenizer = T5Tokenizer.from_pretrained("t5-base", legacy=True)
|
35 |
+
>>> tokenizer.encode("Hello <extra_id_0>.")
|
36 |
+
[8774, 32099, 3, 5, 1]
|
37 |
+
```
|
38 |
+
- `legacy=False`:
|
39 |
+
```python
|
40 |
+
>>> from transformers import T5Tokenizer
|
41 |
+
|
42 |
+
>>> tokenizer = T5Tokenizer.from_pretrained("t5-base", legacy=False)
|
43 |
+
>>> tokenizer.encode("Hello <extra_id_0>.") # the extra space `[3]` is no longer here
|
44 |
+
[8774, 32099, 5, 1]
|
45 |
+
```
|
46 |
+
Checkout the pull request and the issue [here](https://github.com/huggingface/transformers/pull/24565) for
|
47 |
+
more details.
|
48 |
+
|
49 |
+
"""
|
50 |
+
|
51 |
+
vocab_files_names = VOCAB_FILES_NAMES
|
52 |
+
|
53 |
+
def __init__(
|
54 |
+
self,
|
55 |
+
vocab_file,
|
56 |
+
unk_token='<|unk|>',
|
57 |
+
bos_token='<|bos|>',
|
58 |
+
eos_token='<|eos|>',
|
59 |
+
pad_token='<|pad|>',
|
60 |
+
mask_token='<|mask|>',
|
61 |
+
sp_model_kwargs: Optional[Dict[str, Any]] = None,
|
62 |
+
add_bos_token=False,
|
63 |
+
add_eos_token=False,
|
64 |
+
clean_up_tokenization_spaces=False,
|
65 |
+
legacy=None,
|
66 |
+
**kwargs,
|
67 |
+
):
|
68 |
+
mask_token = AddedToken(mask_token, lstrip=True, rstrip=True, special=True) if isinstance(mask_token, str) else mask_token
|
69 |
+
|
70 |
+
self.sp_model_kwargs = {} if sp_model_kwargs is None else sp_model_kwargs
|
71 |
+
self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
|
72 |
+
self.sp_model.Load(vocab_file)
|
73 |
+
|
74 |
+
super().__init__(
|
75 |
+
bos_token=bos_token,
|
76 |
+
eos_token=eos_token,
|
77 |
+
unk_token=unk_token,
|
78 |
+
pad_token=pad_token,
|
79 |
+
mask_token=mask_token,
|
80 |
+
add_bos_token=add_bos_token,
|
81 |
+
add_eos_token=add_eos_token,
|
82 |
+
sp_model_kwargs=self.sp_model_kwargs,
|
83 |
+
clean_up_tokenization_spaces=clean_up_tokenization_spaces,
|
84 |
+
legacy=legacy,
|
85 |
+
**kwargs,
|
86 |
+
)
|
87 |
+
if legacy is None:
|
88 |
+
logger.warning_once(
|
89 |
+
f"You are using the default legacy behaviour of the {self.__class__}. This means that tokens that come after special tokens will not be properly handled. We recommend you to"
|
90 |
+
" read the related pull request available at https://github.com/huggingface/transformers/pull/24565, and set the legacy attribute accordingly."
|
91 |
+
)
|
92 |
+
legacy = True
|
93 |
+
|
94 |
+
self.legacy = legacy
|
95 |
+
self.vocab_file = vocab_file
|
96 |
+
self.add_bos_token = add_bos_token
|
97 |
+
self.add_eos_token = add_eos_token
|
98 |
+
|
99 |
+
def __getstate__(self):
|
100 |
+
state = self.__dict__.copy()
|
101 |
+
state["sp_model"] = None
|
102 |
+
state["sp_model_proto"] = self.sp_model.serialized_model_proto()
|
103 |
+
return state
|
104 |
+
|
105 |
+
def __setstate__(self, d):
|
106 |
+
self.__dict__ = d
|
107 |
+
self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
|
108 |
+
self.sp_model.LoadFromSerializedProto(self.sp_model_proto)
|
109 |
+
|
110 |
+
def build_inputs_with_special_tokens(
|
111 |
+
self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
|
112 |
+
) -> List[int]:
|
113 |
+
"""
|
114 |
+
Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
|
115 |
+
adding special tokens. An sequence has the following format:
|
116 |
+
|
117 |
+
- single sequence: `<|bos|> X <|eos|>`
|
118 |
+
- pair of sequences: `<|bos|> A <|eos|><|bos|> B <|eos|>`
|
119 |
+
|
120 |
+
Args:
|
121 |
+
token_ids_0 (`List[int]`):
|
122 |
+
List of IDs to which the special tokens will be added.
|
123 |
+
token_ids_1 (`List[int]`, *optional*):
|
124 |
+
Optional second list of IDs for sequence pairs.
|
125 |
+
|
126 |
+
Returns:
|
127 |
+
`List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
|
128 |
+
"""
|
129 |
+
|
130 |
+
bos_token_id = [self.bos_token_id] if self.add_bos_token else []
|
131 |
+
eos_token_id = [self.eos_token_id] if self.add_eos_token else []
|
132 |
+
|
133 |
+
output = bos_token_id + token_ids_0 + eos_token_id
|
134 |
+
|
135 |
+
if token_ids_1 is not None:
|
136 |
+
output = output + bos_token_id + token_ids_1 + eos_token_id
|
137 |
+
|
138 |
+
return output
|
139 |
+
|
140 |
+
def get_special_tokens_mask(
|
141 |
+
self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False
|
142 |
+
) -> List[int]:
|
143 |
+
"""
|
144 |
+
Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
|
145 |
+
special tokens using the tokenizer `prepare_for_model` method.
|
146 |
+
|
147 |
+
Args:
|
148 |
+
token_ids_0 (`List[int]`):
|
149 |
+
List of IDs.
|
150 |
+
token_ids_1 (`List[int]`, *optional*):
|
151 |
+
Optional second list of IDs for sequence pairs.
|
152 |
+
already_has_special_tokens (`bool`, *optional*, defaults to `False`):
|
153 |
+
Whether or not the token list is already formatted with special tokens for the model.
|
154 |
+
|
155 |
+
Returns:
|
156 |
+
`List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
|
157 |
+
"""
|
158 |
+
|
159 |
+
if already_has_special_tokens:
|
160 |
+
return super().get_special_tokens_mask(
|
161 |
+
token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
|
162 |
+
)
|
163 |
+
|
164 |
+
|
165 |
+
if token_ids_1 is None:
|
166 |
+
return [1] + ([0] * len(token_ids_0)) + [1]
|
167 |
+
|
168 |
+
return [1] + ([0] * len(token_ids_0)) + [1, 1] + ([0] * len(token_ids_1)) + [1]
|
169 |
+
|
170 |
+
def create_token_type_ids_from_sequences(
|
171 |
+
self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
|
172 |
+
) -> List[int]:
|
173 |
+
"""
|
174 |
+
Create a mask from the two sequences passed to be used in a sequence-pair classification task. A BERT sequence
|
175 |
+
pair mask has the following format:
|
176 |
+
|
177 |
+
```
|
178 |
+
0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1
|
179 |
+
| first sequence | second sequence |
|
180 |
+
```
|
181 |
+
|
182 |
+
If `token_ids_1` is `None`, this method only returns the first portion of the mask (0s).
|
183 |
+
|
184 |
+
Args:
|
185 |
+
token_ids_0 (`List[int]`):
|
186 |
+
List of IDs.
|
187 |
+
token_ids_1 (`List[int]`, *optional*):
|
188 |
+
Optional second list of IDs for sequence pairs.
|
189 |
+
|
190 |
+
Returns:
|
191 |
+
`List[int]`: List of zeros.
|
192 |
+
|
193 |
+
"""
|
194 |
+
|
195 |
+
bos_token_id = [self.bos_token_id] if self.add_bos_token else []
|
196 |
+
eos_token_id = [self.eos_token_id] if self.add_eos_token else []
|
197 |
+
|
198 |
+
if token_ids_1 is None:
|
199 |
+
return len(bos_token_id + token_ids_0 + eos_token_id) * [0]
|
200 |
+
return len(bos_token_id + token_ids_0 + eos_token_id) * [0] + len(bos_token_id + token_ids_1 + eos_token_id) * [1]
|
201 |
+
|
202 |
+
@property
|
203 |
+
def vocab_size(self):
|
204 |
+
"""Returns vocab size"""
|
205 |
+
return self.sp_model.get_piece_size()
|
206 |
+
|
207 |
+
def get_vocab(self):
|
208 |
+
"""Returns vocab as a dict"""
|
209 |
+
vocab = {self.convert_ids_to_tokens(i): i for i in range(self.vocab_size)}
|
210 |
+
vocab.update(self.added_tokens_encoder)
|
211 |
+
return vocab
|
212 |
+
|
213 |
+
def tokenize(self, text, **kwargs) -> List[str]:
|
214 |
+
if not self.legacy:
|
215 |
+
text = SPIECE_UNDERLINE + text.replace(SPIECE_UNDERLINE, " ")
|
216 |
+
return super().tokenize(text, **kwargs)
|
217 |
+
|
218 |
+
def _tokenize(self, text):
|
219 |
+
"""
|
220 |
+
Returns a tokenized string.
|
221 |
+
|
222 |
+
Since the sentencepiece internal model always adds a SPIECE_UNDERLINE, at the beginning of the provided text,
|
223 |
+
we need to remove it by hand when the current text is a subsequence. This happens whenever the `self.tokenize`
|
224 |
+
function is called with specials tokens: the input is split on the special tokens, and each subsequence is
|
225 |
+
passed to `_tokenize`. Thus if a subsequence did not start with a `" "` or SPIECE_UNDERLINE, we have to remove
|
226 |
+
the extra `SPIECE_UNDERLINE` prepended.
|
227 |
+
"""
|
228 |
+
if not self.legacy:
|
229 |
+
is_first = text.startswith(SPIECE_UNDERLINE)
|
230 |
+
if is_first:
|
231 |
+
text = text[1:]
|
232 |
+
tokens = self.sp_model.encode(text, out_type=str)
|
233 |
+
|
234 |
+
if not self.legacy and not is_first and not text.startswith(" ") and tokens[0].startswith(SPIECE_UNDERLINE):
|
235 |
+
tokens = ([tokens[0][1:]] if len(tokens[0]) > 1 else []) + tokens[1:]
|
236 |
+
|
237 |
+
return tokens
|
238 |
+
|
239 |
+
def _convert_token_to_id(self, token):
|
240 |
+
"""Converts a token (str) in an id using the vocab."""
|
241 |
+
return self.sp_model.piece_to_id(token)
|
242 |
+
|
243 |
+
def _convert_id_to_token(self, index):
|
244 |
+
"""Converts an index (integer) in a token (str) using the vocab."""
|
245 |
+
token = self.sp_model.IdToPiece(index)
|
246 |
+
return token
|
247 |
+
|
248 |
+
def convert_tokens_to_string(self, tokens):
|
249 |
+
"""Converts a sequence of tokens (string) in a single string."""
|
250 |
+
current_sub_tokens = []
|
251 |
+
out_string = ""
|
252 |
+
prev_is_special = False
|
253 |
+
for i, token in enumerate(tokens):
|
254 |
+
# make sure that special tokens are not decoded using sentencepiece model
|
255 |
+
if token in self.all_special_tokens:
|
256 |
+
if not prev_is_special and i != 0:
|
257 |
+
out_string += " "
|
258 |
+
out_string += self.sp_model.decode(current_sub_tokens) + token
|
259 |
+
prev_is_special = True
|
260 |
+
current_sub_tokens = []
|
261 |
+
else:
|
262 |
+
current_sub_tokens.append(token)
|
263 |
+
prev_is_special = False
|
264 |
+
out_string += self.sp_model.decode(current_sub_tokens)
|
265 |
+
return out_string
|
266 |
+
|
267 |
+
def save_vocabulary(self, save_directory, filename_prefix: Optional[str] = None) -> Tuple[str]:
|
268 |
+
"""
|
269 |
+
Save the vocabulary and special tokens file to a directory.
|
270 |
+
|
271 |
+
Args:
|
272 |
+
save_directory (`str`):
|
273 |
+
The directory in which to save the vocabulary.
|
274 |
+
|
275 |
+
Returns:
|
276 |
+
`Tuple(str)`: Paths to the files saved.
|
277 |
+
"""
|
278 |
+
if not os.path.isdir(save_directory):
|
279 |
+
logger.error(f"Vocabulary path ({save_directory}) should be a directory")
|
280 |
+
return
|
281 |
+
out_vocab_file = os.path.join(
|
282 |
+
save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
|
283 |
+
)
|
284 |
+
|
285 |
+
if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file) and os.path.isfile(self.vocab_file):
|
286 |
+
copyfile(self.vocab_file, out_vocab_file)
|
287 |
+
elif not os.path.isfile(self.vocab_file):
|
288 |
+
with open(out_vocab_file, "wb") as fi:
|
289 |
+
content_spiece_model = self.sp_model.serialized_model_proto()
|
290 |
+
fi.write(content_spiece_model)
|
291 |
+
|
292 |
+
return (out_vocab_file,)
|
tokenizer.model
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:170a13cb9d99871ae000c2b45c6b9e5765ce0701cf2d027964e14d00d37e75e7
|
3 |
+
size 4843534
|
tokenizer_config.json
ADDED
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"add_bos_token": true,
|
3 |
+
"add_eos_token": true,
|
4 |
+
"auto_map": {
|
5 |
+
"AutoTokenizer": ["tokenization_SEA_BPE.SEABPETokenizer", null]
|
6 |
+
},
|
7 |
+
"bos_token": "<|bos|>",
|
8 |
+
"clean_up_tokenization_spaces": false,
|
9 |
+
"eos_token": "<|eos|>",
|
10 |
+
"legacy": true,
|
11 |
+
"mask_token": "<|mask|>",
|
12 |
+
"model_max_length": 1000000000000000019884624838656,
|
13 |
+
"pad_token": "<|pad|>",
|
14 |
+
"sp_model_kwargs": {},
|
15 |
+
"tokenizer_class": "SEABPETokenizer",
|
16 |
+
"unk_token": "<|unk|>"
|
17 |
+
}
|