Commit
•
3d35129
1
Parent(s):
e6247a6
Attempt to create a streaming version
Browse files- .gitattributes +2 -0
- README.md +44 -0
- added_tokens.json +40 -0
- config.json +15 -0
- configuration_moondream.py +96 -0
- generation_config.json +6 -0
- handler.py +58 -0
- merges.txt +0 -0
- model.safetensors +3 -0
- modeling_phi.py +1167 -0
- moondream.py +180 -0
- moondream2-mmproj-f16.gguf +3 -0
- moondream2-text-model-f16.gguf +3 -0
- special_tokens_map.json +5 -0
- tokenizer.json +0 -0
- tokenizer_config.json +323 -0
- versions.txt +7 -0
- vision_encoder.py +325 -0
- vocab.json +0 -0
.gitattributes
CHANGED
@@ -33,3 +33,5 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
36 |
+
moondream2-mmproj-f16.gguf filter=lfs diff=lfs merge=lfs -text
|
37 |
+
moondream2-text-model-f16.gguf filter=lfs diff=lfs merge=lfs -text
|
README.md
ADDED
@@ -0,0 +1,44 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
---
|
2 |
+
license: apache-2.0
|
3 |
+
pipeline_tag: image-text-to-text
|
4 |
+
---
|
5 |
+
|
6 |
+
moondream2 is a small vision language model designed to run efficiently on edge devices. Check out the [GitHub repository](https://github.com/vikhyat/moondream) for details, or try it out on the [Hugging Face Space](https://huggingface.co/spaces/vikhyatk/moondream2)!
|
7 |
+
|
8 |
+
**Benchmarks**
|
9 |
+
|
10 |
+
| Release | VQAv2 | GQA | TextVQA | DocVQA | TallyQA<br>(simple/full) | POPE<br>(rand/pop/adv) |
|
11 |
+
| --- | --- | --- | --- | --- | --- | --- |
|
12 |
+
| **2024-07-23** (latest) | 79.4 | 64.9 | 60.2 | 61.9 | 82.0 / 76.8 | 91.3 / 89.7 / 86.9 |
|
13 |
+
| 2024-05-20 | 79.4 | 63.1 | 57.2 | 30.5 | 82.1 / 76.6 | 91.5 / 89.6 / 86.2 |
|
14 |
+
| 2024-05-08 | 79.0 | 62.7 | 53.1 | 30.5 | 81.6 / 76.1 | 90.6 / 88.3 / 85.0 |
|
15 |
+
| 2024-04-02 | 77.7 | 61.7 | 49.7 | 24.3 | 80.1 / 74.2 | - |
|
16 |
+
| 2024-03-13 | 76.8 | 60.6 | 46.4 | 22.2 | 79.6 / 73.3 | - |
|
17 |
+
| 2024-03-06 | 75.4 | 59.8 | 43.1 | 20.9 | 79.5 / 73.2 | - |
|
18 |
+
| 2024-03-04 | 74.2 | 58.5 | 36.4 | - | - | - |
|
19 |
+
|
20 |
+
|
21 |
+
**Usage**
|
22 |
+
|
23 |
+
```bash
|
24 |
+
pip install transformers einops
|
25 |
+
```
|
26 |
+
|
27 |
+
```python
|
28 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
29 |
+
from PIL import Image
|
30 |
+
|
31 |
+
model_id = "vikhyatk/moondream2"
|
32 |
+
revision = "2024-07-23"
|
33 |
+
model = AutoModelForCausalLM.from_pretrained(
|
34 |
+
model_id, trust_remote_code=True, revision=revision
|
35 |
+
)
|
36 |
+
tokenizer = AutoTokenizer.from_pretrained(model_id, revision=revision)
|
37 |
+
|
38 |
+
image = Image.open('<IMAGE_PATH>')
|
39 |
+
enc_image = model.encode_image(image)
|
40 |
+
print(model.answer_question(enc_image, "Describe this image.", tokenizer))
|
41 |
+
```
|
42 |
+
|
43 |
+
The model is updated regularly, so we recommend pinning the model version to a
|
44 |
+
specific release as shown above.
|
added_tokens.json
ADDED
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"\t\t": 50294,
|
3 |
+
"\t\t\t": 50293,
|
4 |
+
"\t\t\t\t": 50292,
|
5 |
+
"\t\t\t\t\t": 50291,
|
6 |
+
"\t\t\t\t\t\t": 50290,
|
7 |
+
"\t\t\t\t\t\t\t": 50289,
|
8 |
+
"\t\t\t\t\t\t\t\t": 50288,
|
9 |
+
"\t\t\t\t\t\t\t\t\t": 50287,
|
10 |
+
" ": 50286,
|
11 |
+
" ": 50285,
|
12 |
+
" ": 50284,
|
13 |
+
" ": 50283,
|
14 |
+
" ": 50282,
|
15 |
+
" ": 50281,
|
16 |
+
" ": 50280,
|
17 |
+
" ": 50279,
|
18 |
+
" ": 50278,
|
19 |
+
" ": 50277,
|
20 |
+
" ": 50276,
|
21 |
+
" ": 50275,
|
22 |
+
" ": 50274,
|
23 |
+
" ": 50273,
|
24 |
+
" ": 50272,
|
25 |
+
" ": 50271,
|
26 |
+
" ": 50270,
|
27 |
+
" ": 50269,
|
28 |
+
" ": 50268,
|
29 |
+
" ": 50267,
|
30 |
+
" ": 50266,
|
31 |
+
" ": 50265,
|
32 |
+
" ": 50264,
|
33 |
+
" ": 50263,
|
34 |
+
" ": 50262,
|
35 |
+
" ": 50261,
|
36 |
+
" ": 50260,
|
37 |
+
" ": 50259,
|
38 |
+
" ": 50258,
|
39 |
+
" ": 50257
|
40 |
+
}
|
config.json
ADDED
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"architectures": [
|
3 |
+
"Moondream"
|
4 |
+
],
|
5 |
+
"auto_map": {
|
6 |
+
"AutoConfig": "configuration_moondream.MoondreamConfig",
|
7 |
+
"AutoModelForCausalLM": "moondream.Moondream"
|
8 |
+
},
|
9 |
+
"model_type": "moondream1",
|
10 |
+
"text_config": {
|
11 |
+
"model_type": "phi"
|
12 |
+
},
|
13 |
+
"torch_dtype": "float16",
|
14 |
+
"transformers_version": "4.36.2"
|
15 |
+
}
|
configuration_moondream.py
ADDED
@@ -0,0 +1,96 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from transformers import PretrainedConfig
|
2 |
+
|
3 |
+
|
4 |
+
class PhiConfig(PretrainedConfig):
|
5 |
+
model_type = "phi"
|
6 |
+
keys_to_ignore_at_inference = ["past_key_values"]
|
7 |
+
|
8 |
+
def __init__(
|
9 |
+
self,
|
10 |
+
vocab_size=51200,
|
11 |
+
hidden_size=2048,
|
12 |
+
intermediate_size=8192,
|
13 |
+
num_hidden_layers=24,
|
14 |
+
num_attention_heads=32,
|
15 |
+
num_key_value_heads=None,
|
16 |
+
resid_pdrop=0.0,
|
17 |
+
embd_pdrop=0.0,
|
18 |
+
attention_dropout=0.0,
|
19 |
+
hidden_act="gelu_new",
|
20 |
+
max_position_embeddings=2048,
|
21 |
+
initializer_range=0.02,
|
22 |
+
layer_norm_eps=1e-5,
|
23 |
+
use_cache=True,
|
24 |
+
tie_word_embeddings=False,
|
25 |
+
rope_theta=10000.0,
|
26 |
+
rope_scaling=None,
|
27 |
+
partial_rotary_factor=0.5,
|
28 |
+
bos_token_id=1,
|
29 |
+
eos_token_id=2,
|
30 |
+
**kwargs,
|
31 |
+
):
|
32 |
+
self.vocab_size = vocab_size
|
33 |
+
self.hidden_size = hidden_size
|
34 |
+
self.intermediate_size = intermediate_size
|
35 |
+
self.num_hidden_layers = num_hidden_layers
|
36 |
+
self.num_attention_heads = num_attention_heads
|
37 |
+
|
38 |
+
if num_key_value_heads is None:
|
39 |
+
num_key_value_heads = num_attention_heads
|
40 |
+
|
41 |
+
self.num_key_value_heads = num_key_value_heads
|
42 |
+
self.resid_pdrop = resid_pdrop
|
43 |
+
self.embd_pdrop = embd_pdrop
|
44 |
+
self.attention_dropout = attention_dropout
|
45 |
+
self.hidden_act = hidden_act
|
46 |
+
self.max_position_embeddings = max_position_embeddings
|
47 |
+
self.initializer_range = initializer_range
|
48 |
+
self.layer_norm_eps = layer_norm_eps
|
49 |
+
self.use_cache = use_cache
|
50 |
+
self.rope_theta = rope_theta
|
51 |
+
self.rope_scaling = rope_scaling
|
52 |
+
self.partial_rotary_factor = partial_rotary_factor
|
53 |
+
self._rope_scaling_validation()
|
54 |
+
|
55 |
+
super().__init__(
|
56 |
+
bos_token_id=bos_token_id,
|
57 |
+
eos_token_id=eos_token_id,
|
58 |
+
tie_word_embeddings=tie_word_embeddings,
|
59 |
+
**kwargs,
|
60 |
+
)
|
61 |
+
|
62 |
+
# Copied from transformers.models.llama.configuration_llama.LlamaConfig._rope_scaling_validation
|
63 |
+
def _rope_scaling_validation(self):
|
64 |
+
"""
|
65 |
+
Validate the `rope_scaling` configuration.
|
66 |
+
"""
|
67 |
+
if self.rope_scaling is None:
|
68 |
+
return
|
69 |
+
|
70 |
+
if not isinstance(self.rope_scaling, dict) or len(self.rope_scaling) != 2:
|
71 |
+
raise ValueError(
|
72 |
+
"`rope_scaling` must be a dictionary with with two fields, `type` and `factor`, "
|
73 |
+
f"got {self.rope_scaling}"
|
74 |
+
)
|
75 |
+
rope_scaling_type = self.rope_scaling.get("type", None)
|
76 |
+
rope_scaling_factor = self.rope_scaling.get("factor", None)
|
77 |
+
if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]:
|
78 |
+
raise ValueError(
|
79 |
+
f"`rope_scaling`'s type field must be one of ['linear', 'dynamic'], got {rope_scaling_type}"
|
80 |
+
)
|
81 |
+
if (
|
82 |
+
rope_scaling_factor is None
|
83 |
+
or not isinstance(rope_scaling_factor, float)
|
84 |
+
or rope_scaling_factor <= 1.0
|
85 |
+
):
|
86 |
+
raise ValueError(
|
87 |
+
f"`rope_scaling`'s factor field must be a float > 1, got {rope_scaling_factor}"
|
88 |
+
)
|
89 |
+
|
90 |
+
|
91 |
+
class MoondreamConfig(PretrainedConfig):
|
92 |
+
model_type = "moondream1"
|
93 |
+
|
94 |
+
def __init__(self, **kwargs):
|
95 |
+
self.text_config = PhiConfig(**kwargs.pop("text_config", {}))
|
96 |
+
super().__init__(**kwargs)
|
generation_config.json
ADDED
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"_from_model_config": true,
|
3 |
+
"bos_token_id": 1,
|
4 |
+
"eos_token_id": 2,
|
5 |
+
"transformers_version": "4.36.2"
|
6 |
+
}
|
handler.py
ADDED
@@ -0,0 +1,58 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
2 |
+
from PIL import Image
|
3 |
+
import torch
|
4 |
+
from io import BytesIO
|
5 |
+
import base64
|
6 |
+
|
7 |
+
class EndpointHandler:
|
8 |
+
def __init__(self, model_dir):
|
9 |
+
self.model_id = "vikhyatk/moondream2"
|
10 |
+
self.model = AutoModelForCausalLM.from_pretrained(self.model_id, trust_remote_code=True)
|
11 |
+
self.tokenizer = AutoTokenizer.from_pretrained("vikhyatk/moondream2", trust_remote_code=True)
|
12 |
+
|
13 |
+
# Check if CUDA (GPU support) is available and then set the device to GPU or CPU
|
14 |
+
self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
15 |
+
self.model.to(self.device)
|
16 |
+
|
17 |
+
def preprocess_image(self, encoded_image):
|
18 |
+
"""Decode and preprocess the input image."""
|
19 |
+
decoded_image = base64.b64decode(encoded_image)
|
20 |
+
img = Image.open(BytesIO(decoded_image)).convert("RGB")
|
21 |
+
return img
|
22 |
+
|
23 |
+
def __call__(self, data):
|
24 |
+
"""Handle the incoming request."""
|
25 |
+
try:
|
26 |
+
# Extract the inputs from the data
|
27 |
+
inputs = data.pop("inputs", data)
|
28 |
+
input_image = inputs['image']
|
29 |
+
question = inputs.get('question', "move to the red ball")
|
30 |
+
|
31 |
+
# Preprocess the image
|
32 |
+
img = self.preprocess_image(input_image)
|
33 |
+
|
34 |
+
# Perform inference
|
35 |
+
enc_image = self.model.encode_image(img).to(self.device)
|
36 |
+
answer = self.model.answer_question(enc_image, question, self.tokenizer)
|
37 |
+
|
38 |
+
# If the output is a tensor, move it back to CPU and convert to list
|
39 |
+
if isinstance(answer, torch.Tensor):
|
40 |
+
answer = answer.cpu().numpy().tolist()
|
41 |
+
|
42 |
+
# Create the response
|
43 |
+
response = {
|
44 |
+
"statusCode": 200,
|
45 |
+
"body": {
|
46 |
+
"answer": answer
|
47 |
+
}
|
48 |
+
}
|
49 |
+
return response
|
50 |
+
except Exception as e:
|
51 |
+
# Handle any errors
|
52 |
+
response = {
|
53 |
+
"statusCode": 500,
|
54 |
+
"body": {
|
55 |
+
"error": str(e)
|
56 |
+
}
|
57 |
+
}
|
58 |
+
return response
|
merges.txt
ADDED
The diff for this file is too large to render.
See raw diff
|
|
model.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:927694193ed81f83b9b269c0d1ffa8dc823dec90bce4703a54b22ebd6c9632b6
|
3 |
+
size 3733912224
|
modeling_phi.py
ADDED
@@ -0,0 +1,1167 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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License");
|
5 |
+
# you may not use this file except in compliance with the License.
|
6 |
+
# You may obtain a copy of the License at
|
7 |
+
#
|
8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
9 |
+
#
|
10 |
+
# Unless required by applicable law or agreed to in writing, software
|
11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
13 |
+
# See the License for the specific language governing permissions and
|
14 |
+
# limitations under the License.
|
15 |
+
|
16 |
+
""" PyTorch Phi model."""
|
17 |
+
|
18 |
+
|
19 |
+
from typing import List, Optional, Tuple, Union
|
20 |
+
|
21 |
+
import torch
|
22 |
+
import torch.nn.functional as F
|
23 |
+
import torch.utils.checkpoint
|
24 |
+
from torch import nn
|
25 |
+
from torch.nn import CrossEntropyLoss
|
26 |
+
|
27 |
+
from transformers.activations import ACT2FN
|
28 |
+
from transformers.cache_utils import Cache, DynamicCache
|
29 |
+
from transformers.modeling_attn_mask_utils import _prepare_4d_causal_attention_mask
|
30 |
+
from transformers.modeling_outputs import (
|
31 |
+
BaseModelOutputWithPast,
|
32 |
+
CausalLMOutputWithPast,
|
33 |
+
)
|
34 |
+
from transformers.modeling_utils import PreTrainedModel
|
35 |
+
from transformers.utils import (
|
36 |
+
is_flash_attn_2_available,
|
37 |
+
is_flash_attn_greater_or_equal_2_10,
|
38 |
+
logging,
|
39 |
+
)
|
40 |
+
from .configuration_moondream import PhiConfig
|
41 |
+
|
42 |
+
|
43 |
+
try: # noqa: SIM105
|
44 |
+
if is_flash_attn_2_available():
|
45 |
+
from flash_attn import flash_attn_func, flash_attn_varlen_func
|
46 |
+
from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input
|
47 |
+
except ImportError:
|
48 |
+
# Workaround for https://github.com/huggingface/transformers/issues/28459,
|
49 |
+
# don't move to contextlib.suppress(ImportError)
|
50 |
+
pass
|
51 |
+
|
52 |
+
|
53 |
+
logger = logging.get_logger(__name__)
|
54 |
+
|
55 |
+
|
56 |
+
# Copied from transformers.models.llama.modeling_llama._get_unpad_data
|
57 |
+
def _get_unpad_data(attention_mask):
|
58 |
+
seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
|
59 |
+
indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
|
60 |
+
max_seqlen_in_batch = seqlens_in_batch.max().item()
|
61 |
+
cu_seqlens = F.pad(
|
62 |
+
torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.torch.int32), (1, 0)
|
63 |
+
)
|
64 |
+
return (
|
65 |
+
indices,
|
66 |
+
cu_seqlens,
|
67 |
+
max_seqlen_in_batch,
|
68 |
+
)
|
69 |
+
|
70 |
+
|
71 |
+
# Copied from transformers.models.llama.modeling_llama.LlamaRotaryEmbedding with Llama->Phi
|
72 |
+
class PhiRotaryEmbedding(nn.Module):
|
73 |
+
def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
|
74 |
+
super().__init__()
|
75 |
+
|
76 |
+
self.dim = dim
|
77 |
+
self.max_position_embeddings = max_position_embeddings
|
78 |
+
self.base = base
|
79 |
+
inv_freq = 1.0 / (
|
80 |
+
self.base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim)
|
81 |
+
)
|
82 |
+
self.register_buffer("inv_freq", inv_freq, persistent=False)
|
83 |
+
|
84 |
+
# Build here to make `torch.jit.trace` work.
|
85 |
+
self._set_cos_sin_cache(
|
86 |
+
seq_len=max_position_embeddings,
|
87 |
+
device=self.inv_freq.device,
|
88 |
+
dtype=torch.get_default_dtype(),
|
89 |
+
)
|
90 |
+
|
91 |
+
def _set_cos_sin_cache(self, seq_len, device, dtype):
|
92 |
+
self.max_seq_len_cached = seq_len
|
93 |
+
t = torch.arange(
|
94 |
+
self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype
|
95 |
+
)
|
96 |
+
|
97 |
+
freqs = torch.outer(t, self.inv_freq)
|
98 |
+
# Different from paper, but it uses a different permutation in order to obtain the same calculation
|
99 |
+
emb = torch.cat((freqs, freqs), dim=-1)
|
100 |
+
self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
|
101 |
+
self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
|
102 |
+
|
103 |
+
def forward(self, x, seq_len=None):
|
104 |
+
# x: [bs, num_attention_heads, seq_len, head_size]
|
105 |
+
if seq_len > self.max_seq_len_cached:
|
106 |
+
self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)
|
107 |
+
|
108 |
+
return (
|
109 |
+
self.cos_cached[:seq_len].to(dtype=x.dtype),
|
110 |
+
self.sin_cached[:seq_len].to(dtype=x.dtype),
|
111 |
+
)
|
112 |
+
|
113 |
+
|
114 |
+
# Copied from transformers.models.llama.modeling_llama.LlamaLinearScalingRotaryEmbedding with Llama->Phi
|
115 |
+
class PhiLinearScalingRotaryEmbedding(PhiRotaryEmbedding):
|
116 |
+
"""PhiRotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendev"""
|
117 |
+
|
118 |
+
def __init__(
|
119 |
+
self,
|
120 |
+
dim,
|
121 |
+
max_position_embeddings=2048,
|
122 |
+
base=10000,
|
123 |
+
device=None,
|
124 |
+
scaling_factor=1.0,
|
125 |
+
):
|
126 |
+
self.scaling_factor = scaling_factor
|
127 |
+
super().__init__(dim, max_position_embeddings, base, device)
|
128 |
+
|
129 |
+
def _set_cos_sin_cache(self, seq_len, device, dtype):
|
130 |
+
self.max_seq_len_cached = seq_len
|
131 |
+
t = torch.arange(
|
132 |
+
self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype
|
133 |
+
)
|
134 |
+
t = t / self.scaling_factor
|
135 |
+
|
136 |
+
freqs = torch.outer(t, self.inv_freq)
|
137 |
+
# Different from paper, but it uses a different permutation in order to obtain the same calculation
|
138 |
+
emb = torch.cat((freqs, freqs), dim=-1)
|
139 |
+
self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
|
140 |
+
self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
|
141 |
+
|
142 |
+
|
143 |
+
# Copied from transformers.models.llama.modeling_llama.LlamaDynamicNTKScalingRotaryEmbedding with Llama->Phi
|
144 |
+
class PhiDynamicNTKScalingRotaryEmbedding(PhiRotaryEmbedding):
|
145 |
+
"""PhiRotaryEmbedding extended with Dynamic NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozilla"""
|
146 |
+
|
147 |
+
def __init__(
|
148 |
+
self,
|
149 |
+
dim,
|
150 |
+
max_position_embeddings=2048,
|
151 |
+
base=10000,
|
152 |
+
device=None,
|
153 |
+
scaling_factor=1.0,
|
154 |
+
):
|
155 |
+
self.scaling_factor = scaling_factor
|
156 |
+
super().__init__(dim, max_position_embeddings, base, device)
|
157 |
+
|
158 |
+
def _set_cos_sin_cache(self, seq_len, device, dtype):
|
159 |
+
self.max_seq_len_cached = seq_len
|
160 |
+
|
161 |
+
if seq_len > self.max_position_embeddings:
|
162 |
+
base = self.base * (
|
163 |
+
(self.scaling_factor * seq_len / self.max_position_embeddings)
|
164 |
+
- (self.scaling_factor - 1)
|
165 |
+
) ** (self.dim / (self.dim - 2))
|
166 |
+
inv_freq = 1.0 / (
|
167 |
+
base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim)
|
168 |
+
)
|
169 |
+
self.register_buffer("inv_freq", inv_freq, persistent=False)
|
170 |
+
|
171 |
+
t = torch.arange(
|
172 |
+
self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype
|
173 |
+
)
|
174 |
+
|
175 |
+
freqs = torch.outer(t, self.inv_freq)
|
176 |
+
# Different from paper, but it uses a different permutation in order to obtain the same calculation
|
177 |
+
emb = torch.cat((freqs, freqs), dim=-1)
|
178 |
+
self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
|
179 |
+
self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
|
180 |
+
|
181 |
+
|
182 |
+
# Copied from transformers.models.llama.modeling_llama.rotate_half
|
183 |
+
def rotate_half(x):
|
184 |
+
"""Rotates half the hidden dims of the input."""
|
185 |
+
x1 = x[..., : x.shape[-1] // 2]
|
186 |
+
x2 = x[..., x.shape[-1] // 2 :]
|
187 |
+
return torch.cat((-x2, x1), dim=-1)
|
188 |
+
|
189 |
+
|
190 |
+
# Copied from transformers.models.llama.modeling_llama.apply_rotary_pos_emb
|
191 |
+
def apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1):
|
192 |
+
"""Applies Rotary Position Embedding to the query and key tensors.
|
193 |
+
|
194 |
+
Args:
|
195 |
+
q (`torch.Tensor`): The query tensor.
|
196 |
+
k (`torch.Tensor`): The key tensor.
|
197 |
+
cos (`torch.Tensor`): The cosine part of the rotary embedding.
|
198 |
+
sin (`torch.Tensor`): The sine part of the rotary embedding.
|
199 |
+
position_ids (`torch.Tensor`):
|
200 |
+
The position indices of the tokens corresponding to the query and key tensors. For example, this can be
|
201 |
+
used to pass offsetted position ids when working with a KV-cache.
|
202 |
+
unsqueeze_dim (`int`, *optional*, defaults to 1):
|
203 |
+
The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
|
204 |
+
sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
|
205 |
+
that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
|
206 |
+
k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
|
207 |
+
cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
|
208 |
+
the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
|
209 |
+
Returns:
|
210 |
+
`tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
|
211 |
+
"""
|
212 |
+
cos = cos[position_ids].unsqueeze(unsqueeze_dim)
|
213 |
+
sin = sin[position_ids].unsqueeze(unsqueeze_dim)
|
214 |
+
q_embed = (q * cos) + (rotate_half(q) * sin)
|
215 |
+
k_embed = (k * cos) + (rotate_half(k) * sin)
|
216 |
+
return q_embed, k_embed
|
217 |
+
|
218 |
+
|
219 |
+
# Copied from transformers.models.clip.modeling_clip.CLIPMLP with CLIP->Phi
|
220 |
+
class PhiMLP(nn.Module):
|
221 |
+
def __init__(self, config):
|
222 |
+
super().__init__()
|
223 |
+
self.config = config
|
224 |
+
self.activation_fn = ACT2FN[config.hidden_act]
|
225 |
+
self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size)
|
226 |
+
self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size)
|
227 |
+
|
228 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
229 |
+
hidden_states = self.fc1(hidden_states)
|
230 |
+
hidden_states = self.activation_fn(hidden_states)
|
231 |
+
hidden_states = self.fc2(hidden_states)
|
232 |
+
return hidden_states
|
233 |
+
|
234 |
+
|
235 |
+
# Copied from transformers.models.llama.modeling_llama.repeat_kv with llama->phi
|
236 |
+
def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
|
237 |
+
"""
|
238 |
+
This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
|
239 |
+
num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
|
240 |
+
"""
|
241 |
+
batch, num_key_value_heads, slen, head_dim = hidden_states.shape
|
242 |
+
if n_rep == 1:
|
243 |
+
return hidden_states
|
244 |
+
hidden_states = hidden_states[:, :, None, :, :].expand(
|
245 |
+
batch, num_key_value_heads, n_rep, slen, head_dim
|
246 |
+
)
|
247 |
+
return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
|
248 |
+
|
249 |
+
|
250 |
+
class PhiAttention(nn.Module):
|
251 |
+
"""Multi-headed attention from 'Attention Is All You Need' paper"""
|
252 |
+
|
253 |
+
def __init__(self, config: PhiConfig, layer_idx: Optional[int] = None):
|
254 |
+
super().__init__()
|
255 |
+
self.config = config
|
256 |
+
self.layer_idx = layer_idx
|
257 |
+
if layer_idx is None:
|
258 |
+
logger.warning_once(
|
259 |
+
f"Instantiating {self.__class__.__name__} without passing `layer_idx` is not recommended and will "
|
260 |
+
"to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` "
|
261 |
+
"when creating this class."
|
262 |
+
)
|
263 |
+
|
264 |
+
self.attention_dropout = config.attention_dropout
|
265 |
+
self.hidden_size = config.hidden_size
|
266 |
+
self.num_heads = config.num_attention_heads
|
267 |
+
self.head_dim = self.hidden_size // self.num_heads
|
268 |
+
self.num_key_value_heads = config.num_key_value_heads
|
269 |
+
self.num_key_value_groups = self.num_heads // self.num_key_value_heads
|
270 |
+
self.max_position_embeddings = config.max_position_embeddings
|
271 |
+
self.rope_theta = config.rope_theta
|
272 |
+
self.partial_rotary_factor = config.partial_rotary_factor
|
273 |
+
self.is_causal = True
|
274 |
+
|
275 |
+
if (self.head_dim * self.num_heads) != self.hidden_size:
|
276 |
+
raise ValueError(
|
277 |
+
f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
|
278 |
+
f" and `num_heads`: {self.num_heads})."
|
279 |
+
)
|
280 |
+
|
281 |
+
self.Wqkv = nn.Linear(
|
282 |
+
self.hidden_size, 3 * self.num_heads * self.head_dim, bias=True
|
283 |
+
)
|
284 |
+
self.out_proj = nn.Linear(
|
285 |
+
self.num_heads * self.head_dim, self.hidden_size, bias=True
|
286 |
+
)
|
287 |
+
|
288 |
+
self._init_rope()
|
289 |
+
|
290 |
+
def _init_rope(self):
|
291 |
+
if self.config.rope_scaling is None:
|
292 |
+
self.rotary_emb = PhiRotaryEmbedding(
|
293 |
+
int(self.partial_rotary_factor * self.head_dim),
|
294 |
+
max_position_embeddings=self.max_position_embeddings,
|
295 |
+
base=self.rope_theta,
|
296 |
+
)
|
297 |
+
else:
|
298 |
+
scaling_type = self.config.rope_scaling["type"]
|
299 |
+
scaling_factor = self.config.rope_scaling["factor"]
|
300 |
+
if scaling_type == "linear":
|
301 |
+
self.rotary_emb = PhiLinearScalingRotaryEmbedding(
|
302 |
+
int(self.partial_rotary_factor * self.head_dim),
|
303 |
+
max_position_embeddings=self.max_position_embeddings,
|
304 |
+
scaling_factor=scaling_factor,
|
305 |
+
base=self.rope_theta,
|
306 |
+
)
|
307 |
+
elif scaling_type == "dynamic":
|
308 |
+
self.rotary_emb = PhiDynamicNTKScalingRotaryEmbedding(
|
309 |
+
int(self.partial_rotary_factor * self.head_dim),
|
310 |
+
max_position_embeddings=self.max_position_embeddings,
|
311 |
+
scaling_factor=scaling_factor,
|
312 |
+
base=self.rope_theta,
|
313 |
+
)
|
314 |
+
else:
|
315 |
+
raise ValueError(f"Unknown RoPE scaling type {scaling_type}")
|
316 |
+
|
317 |
+
def forward(
|
318 |
+
self,
|
319 |
+
hidden_states: torch.Tensor,
|
320 |
+
attention_mask: Optional[torch.Tensor] = None,
|
321 |
+
position_ids: Optional[torch.LongTensor] = None,
|
322 |
+
past_key_value: Optional[Cache] = None,
|
323 |
+
output_attentions: bool = False,
|
324 |
+
use_cache: bool = False,
|
325 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
326 |
+
bsz, q_len, _ = hidden_states.size()
|
327 |
+
|
328 |
+
query_states, key_states, value_states = self.Wqkv(hidden_states).chunk(
|
329 |
+
3, dim=-1
|
330 |
+
)
|
331 |
+
|
332 |
+
query_states = query_states.view(
|
333 |
+
bsz, q_len, self.num_heads, self.head_dim
|
334 |
+
).transpose(1, 2)
|
335 |
+
key_states = key_states.view(
|
336 |
+
bsz, q_len, self.num_key_value_heads, self.head_dim
|
337 |
+
).transpose(1, 2)
|
338 |
+
value_states = value_states.view(
|
339 |
+
bsz, q_len, self.num_key_value_heads, self.head_dim
|
340 |
+
).transpose(1, 2)
|
341 |
+
|
342 |
+
kv_seq_len = key_states.shape[-2]
|
343 |
+
if past_key_value is not None:
|
344 |
+
if self.layer_idx is None:
|
345 |
+
raise ValueError(
|
346 |
+
f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
|
347 |
+
"for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
|
348 |
+
"with a layer index."
|
349 |
+
)
|
350 |
+
kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
|
351 |
+
cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
|
352 |
+
|
353 |
+
# Partial rotary embedding
|
354 |
+
query_rot, query_pass = (
|
355 |
+
query_states[..., : self.rotary_emb.dim],
|
356 |
+
query_states[..., self.rotary_emb.dim :],
|
357 |
+
)
|
358 |
+
key_rot, key_pass = (
|
359 |
+
key_states[..., : self.rotary_emb.dim],
|
360 |
+
key_states[..., self.rotary_emb.dim :],
|
361 |
+
)
|
362 |
+
# [batch_size, seq_length, num_heads, head_dim // config.partial_rotary_factor]
|
363 |
+
query_rot, key_rot = apply_rotary_pos_emb(
|
364 |
+
query_rot, key_rot, cos, sin, position_ids
|
365 |
+
)
|
366 |
+
|
367 |
+
# [batch_size, seq_length, num_heads, head_dim]
|
368 |
+
query_states = torch.cat((query_rot, query_pass), dim=-1)
|
369 |
+
key_states = torch.cat((key_rot, key_pass), dim=-1)
|
370 |
+
|
371 |
+
if past_key_value is not None:
|
372 |
+
cache_kwargs = {
|
373 |
+
"sin": sin,
|
374 |
+
"cos": cos,
|
375 |
+
"partial_rotation_size": self.rotary_emb.dim,
|
376 |
+
}
|
377 |
+
key_states, value_states = past_key_value.update(
|
378 |
+
key_states, value_states, self.layer_idx, cache_kwargs
|
379 |
+
)
|
380 |
+
|
381 |
+
key_states = repeat_kv(key_states, self.num_key_value_groups)
|
382 |
+
value_states = repeat_kv(value_states, self.num_key_value_groups)
|
383 |
+
|
384 |
+
attn_output = torch.nn.functional.scaled_dot_product_attention(
|
385 |
+
query_states, key_states, value_states, attn_mask=attention_mask
|
386 |
+
)
|
387 |
+
|
388 |
+
attn_output = attn_output.transpose(1, 2).contiguous()
|
389 |
+
attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
|
390 |
+
|
391 |
+
attn_output = self.out_proj(attn_output)
|
392 |
+
|
393 |
+
if not output_attentions:
|
394 |
+
attn_weights = None
|
395 |
+
|
396 |
+
return attn_output, attn_weights, past_key_value
|
397 |
+
|
398 |
+
|
399 |
+
class PhiFlashAttention2(PhiAttention):
|
400 |
+
"""
|
401 |
+
Phi flash attention module. This module inherits from `PhiAttention` as the weights of the module stays
|
402 |
+
untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
|
403 |
+
flash attention and deal with padding tokens in case the input contains any of them.
|
404 |
+
"""
|
405 |
+
|
406 |
+
# Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2.__init__
|
407 |
+
def __init__(self, *args, **kwargs):
|
408 |
+
super().__init__(*args, **kwargs)
|
409 |
+
|
410 |
+
# TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
|
411 |
+
# flash_attn<2.1 generates top-left aligned causal mask, while what is needed here is bottom-right alignement, that was made default for flash_attn>=2.1. This attribute is used to handle this difference. Reference: https://github.com/Dao-AILab/flash-attention/releases/tag/v2.1.0.
|
412 |
+
# Beware that with flash_attn<2.1, using q_seqlen != k_seqlen (except for the case q_seqlen == 1) produces a wrong mask (top-left).
|
413 |
+
self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
|
414 |
+
|
415 |
+
def forward(
|
416 |
+
self,
|
417 |
+
hidden_states: torch.Tensor,
|
418 |
+
attention_mask: Optional[torch.LongTensor] = None,
|
419 |
+
position_ids: Optional[torch.LongTensor] = None,
|
420 |
+
past_key_value: Optional[Cache] = None,
|
421 |
+
output_attentions: bool = False,
|
422 |
+
use_cache: bool = False,
|
423 |
+
**kwargs,
|
424 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
425 |
+
# PhiFlashAttention2 attention does not support output_attentions
|
426 |
+
|
427 |
+
output_attentions = False
|
428 |
+
|
429 |
+
bsz, q_len, _ = hidden_states.size()
|
430 |
+
|
431 |
+
query_states, key_states, value_states = self.Wqkv(hidden_states).chunk(
|
432 |
+
3, dim=-1
|
433 |
+
)
|
434 |
+
|
435 |
+
# Flash attention requires the input to have the shape
|
436 |
+
# batch_size x seq_length x head_dim x hidden_dim
|
437 |
+
# therefore we just need to keep the original shape
|
438 |
+
query_states = query_states.view(
|
439 |
+
bsz, q_len, self.num_heads, self.head_dim
|
440 |
+
).transpose(1, 2)
|
441 |
+
key_states = key_states.view(
|
442 |
+
bsz, q_len, self.num_key_value_heads, self.head_dim
|
443 |
+
).transpose(1, 2)
|
444 |
+
value_states = value_states.view(
|
445 |
+
bsz, q_len, self.num_key_value_heads, self.head_dim
|
446 |
+
).transpose(1, 2)
|
447 |
+
|
448 |
+
kv_seq_len = key_states.shape[-2]
|
449 |
+
if past_key_value is not None:
|
450 |
+
kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
|
451 |
+
cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
|
452 |
+
|
453 |
+
# Partial rotary embedding
|
454 |
+
query_rot, query_pass = (
|
455 |
+
query_states[..., : self.rotary_emb.dim],
|
456 |
+
query_states[..., self.rotary_emb.dim :],
|
457 |
+
)
|
458 |
+
key_rot, key_pass = (
|
459 |
+
key_states[..., : self.rotary_emb.dim],
|
460 |
+
key_states[..., self.rotary_emb.dim :],
|
461 |
+
)
|
462 |
+
# [batch_size, seq_length, num_heads, head_dim // config.partial_rotary_factor]
|
463 |
+
query_rot, key_rot = apply_rotary_pos_emb(
|
464 |
+
query_rot, key_rot, cos, sin, position_ids
|
465 |
+
)
|
466 |
+
|
467 |
+
# [batch_size, seq_length, num_heads, head_dim]
|
468 |
+
query_states = torch.cat((query_rot, query_pass), dim=-1)
|
469 |
+
key_states = torch.cat((key_rot, key_pass), dim=-1)
|
470 |
+
|
471 |
+
if past_key_value is not None:
|
472 |
+
cache_kwargs = {
|
473 |
+
"sin": sin,
|
474 |
+
"cos": cos,
|
475 |
+
"partial_rotation_size": self.rotary_emb.dim,
|
476 |
+
}
|
477 |
+
key_states, value_states = past_key_value.update(
|
478 |
+
key_states, value_states, self.layer_idx, cache_kwargs
|
479 |
+
)
|
480 |
+
|
481 |
+
# TODO: These transpose are quite inefficient but Flash Attention requires the layout [batch_size, sequence_length, num_heads, head_dim]. We would need to refactor the KV cache
|
482 |
+
# to be able to avoid many of these transpose/reshape/view.
|
483 |
+
query_states = query_states.transpose(1, 2)
|
484 |
+
key_states = key_states.transpose(1, 2)
|
485 |
+
value_states = value_states.transpose(1, 2)
|
486 |
+
|
487 |
+
attn_dropout = self.attention_dropout if self.training else 0.0
|
488 |
+
|
489 |
+
# In PEFT, usually we cast the layer norms in float32 for training stability reasons
|
490 |
+
# therefore the input hidden states gets silently casted in float32. Hence, we need
|
491 |
+
# cast them back in the correct dtype just to be sure everything works as expected.
|
492 |
+
# This might slowdown training & inference so it is recommended to not cast the LayerNorms
|
493 |
+
# in fp32.
|
494 |
+
|
495 |
+
if query_states.dtype == torch.float32:
|
496 |
+
if torch.is_autocast_enabled():
|
497 |
+
target_dtype = torch.get_autocast_gpu_dtype()
|
498 |
+
# Handle the case where the model is quantized
|
499 |
+
elif hasattr(self.config, "_pre_quantization_dtype"):
|
500 |
+
target_dtype = self.config._pre_quantization_dtype
|
501 |
+
else:
|
502 |
+
target_dtype = self.q_proj.weight.dtype
|
503 |
+
|
504 |
+
logger.warning_once(
|
505 |
+
f"The input hidden states seems to be silently casted in float32, this might be related to"
|
506 |
+
f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
|
507 |
+
f" {target_dtype}."
|
508 |
+
)
|
509 |
+
|
510 |
+
query_states = query_states.to(target_dtype)
|
511 |
+
key_states = key_states.to(target_dtype)
|
512 |
+
value_states = value_states.to(target_dtype)
|
513 |
+
|
514 |
+
attn_output = self._flash_attention_forward(
|
515 |
+
query_states,
|
516 |
+
key_states,
|
517 |
+
value_states,
|
518 |
+
attention_mask,
|
519 |
+
q_len,
|
520 |
+
dropout=attn_dropout,
|
521 |
+
softmax_scale=None,
|
522 |
+
)
|
523 |
+
|
524 |
+
attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
|
525 |
+
attn_output = self.out_proj(attn_output)
|
526 |
+
|
527 |
+
if not output_attentions:
|
528 |
+
attn_weights = None
|
529 |
+
|
530 |
+
return attn_output, attn_weights, past_key_value
|
531 |
+
|
532 |
+
# Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2._flash_attention_forward
|
533 |
+
def _flash_attention_forward(
|
534 |
+
self,
|
535 |
+
query_states,
|
536 |
+
key_states,
|
537 |
+
value_states,
|
538 |
+
attention_mask,
|
539 |
+
query_length,
|
540 |
+
dropout=0.0,
|
541 |
+
softmax_scale=None,
|
542 |
+
):
|
543 |
+
"""
|
544 |
+
Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
|
545 |
+
first unpad the input, then computes the attention scores and pad the final attention scores.
|
546 |
+
|
547 |
+
Args:
|
548 |
+
query_states (`torch.Tensor`):
|
549 |
+
Input query states to be passed to Flash Attention API
|
550 |
+
key_states (`torch.Tensor`):
|
551 |
+
Input key states to be passed to Flash Attention API
|
552 |
+
value_states (`torch.Tensor`):
|
553 |
+
Input value states to be passed to Flash Attention API
|
554 |
+
attention_mask (`torch.Tensor`):
|
555 |
+
The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
|
556 |
+
position of padding tokens and 1 for the position of non-padding tokens.
|
557 |
+
dropout (`int`, *optional*):
|
558 |
+
Attention dropout
|
559 |
+
softmax_scale (`float`, *optional*):
|
560 |
+
The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
|
561 |
+
"""
|
562 |
+
if not self._flash_attn_uses_top_left_mask:
|
563 |
+
causal = self.is_causal
|
564 |
+
else:
|
565 |
+
# TODO: Remove the `query_length != 1` check once Flash Attention for RoCm is bumped to 2.1. For details, please see the comment in LlamaFlashAttention2 __init__.
|
566 |
+
causal = self.is_causal and query_length != 1
|
567 |
+
|
568 |
+
# Contains at least one padding token in the sequence
|
569 |
+
if attention_mask is not None:
|
570 |
+
batch_size = query_states.shape[0]
|
571 |
+
(
|
572 |
+
query_states,
|
573 |
+
key_states,
|
574 |
+
value_states,
|
575 |
+
indices_q,
|
576 |
+
cu_seq_lens,
|
577 |
+
max_seq_lens,
|
578 |
+
) = self._upad_input(
|
579 |
+
query_states, key_states, value_states, attention_mask, query_length
|
580 |
+
)
|
581 |
+
|
582 |
+
cu_seqlens_q, cu_seqlens_k = cu_seq_lens
|
583 |
+
max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
|
584 |
+
|
585 |
+
attn_output_unpad = flash_attn_varlen_func(
|
586 |
+
query_states,
|
587 |
+
key_states,
|
588 |
+
value_states,
|
589 |
+
cu_seqlens_q=cu_seqlens_q,
|
590 |
+
cu_seqlens_k=cu_seqlens_k,
|
591 |
+
max_seqlen_q=max_seqlen_in_batch_q,
|
592 |
+
max_seqlen_k=max_seqlen_in_batch_k,
|
593 |
+
dropout_p=dropout,
|
594 |
+
softmax_scale=softmax_scale,
|
595 |
+
causal=causal,
|
596 |
+
)
|
597 |
+
|
598 |
+
attn_output = pad_input(
|
599 |
+
attn_output_unpad, indices_q, batch_size, query_length
|
600 |
+
)
|
601 |
+
else:
|
602 |
+
attn_output = flash_attn_func(
|
603 |
+
query_states,
|
604 |
+
key_states,
|
605 |
+
value_states,
|
606 |
+
dropout,
|
607 |
+
softmax_scale=softmax_scale,
|
608 |
+
causal=causal,
|
609 |
+
)
|
610 |
+
|
611 |
+
return attn_output
|
612 |
+
|
613 |
+
# Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2._upad_input
|
614 |
+
def _upad_input(
|
615 |
+
self, query_layer, key_layer, value_layer, attention_mask, query_length
|
616 |
+
):
|
617 |
+
indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
|
618 |
+
batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape
|
619 |
+
|
620 |
+
key_layer = index_first_axis(
|
621 |
+
key_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim),
|
622 |
+
indices_k,
|
623 |
+
)
|
624 |
+
value_layer = index_first_axis(
|
625 |
+
value_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim),
|
626 |
+
indices_k,
|
627 |
+
)
|
628 |
+
if query_length == kv_seq_len:
|
629 |
+
query_layer = index_first_axis(
|
630 |
+
query_layer.reshape(batch_size * kv_seq_len, self.num_heads, head_dim),
|
631 |
+
indices_k,
|
632 |
+
)
|
633 |
+
cu_seqlens_q = cu_seqlens_k
|
634 |
+
max_seqlen_in_batch_q = max_seqlen_in_batch_k
|
635 |
+
indices_q = indices_k
|
636 |
+
elif query_length == 1:
|
637 |
+
max_seqlen_in_batch_q = 1
|
638 |
+
cu_seqlens_q = torch.arange(
|
639 |
+
batch_size + 1, dtype=torch.int32, device=query_layer.device
|
640 |
+
) # There is a memcpy here, that is very bad.
|
641 |
+
indices_q = cu_seqlens_q[:-1]
|
642 |
+
query_layer = query_layer.squeeze(1)
|
643 |
+
else:
|
644 |
+
# The -q_len: slice assumes left padding.
|
645 |
+
attention_mask = attention_mask[:, -query_length:]
|
646 |
+
query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(
|
647 |
+
query_layer, attention_mask
|
648 |
+
)
|
649 |
+
|
650 |
+
return (
|
651 |
+
query_layer,
|
652 |
+
key_layer,
|
653 |
+
value_layer,
|
654 |
+
indices_q,
|
655 |
+
(cu_seqlens_q, cu_seqlens_k),
|
656 |
+
(max_seqlen_in_batch_q, max_seqlen_in_batch_k),
|
657 |
+
)
|
658 |
+
|
659 |
+
|
660 |
+
PHI_ATTENTION_CLASSES = {
|
661 |
+
"eager": PhiAttention,
|
662 |
+
"flash_attention_2": PhiFlashAttention2,
|
663 |
+
}
|
664 |
+
|
665 |
+
|
666 |
+
class PhiDecoderLayer(nn.Module):
|
667 |
+
def __init__(self, config: PhiConfig, layer_idx: int):
|
668 |
+
super().__init__()
|
669 |
+
self.mixer = PHI_ATTENTION_CLASSES[config._attn_implementation](
|
670 |
+
config, layer_idx=layer_idx
|
671 |
+
)
|
672 |
+
self.mlp = PhiMLP(config)
|
673 |
+
self.ln = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
674 |
+
self.resid_dropout = nn.Dropout(config.resid_pdrop)
|
675 |
+
|
676 |
+
def forward(
|
677 |
+
self,
|
678 |
+
hidden_states: torch.Tensor,
|
679 |
+
attention_mask: Optional[torch.Tensor] = None,
|
680 |
+
position_ids: Optional[torch.LongTensor] = None,
|
681 |
+
output_attentions: Optional[bool] = False,
|
682 |
+
use_cache: Optional[bool] = False,
|
683 |
+
past_key_value: Optional[Tuple[torch.Tensor]] = None,
|
684 |
+
) -> Tuple[
|
685 |
+
torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]
|
686 |
+
]:
|
687 |
+
"""
|
688 |
+
Args:
|
689 |
+
hidden_states (`torch.FloatTensor`):
|
690 |
+
input to the layer of shape `(batch, seq_len, embed_dim)`
|
691 |
+
attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
|
692 |
+
`(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
|
693 |
+
position_ids (`torch.LongTensor` of shape `({0})`, *optional*):
|
694 |
+
Indices of positions of each input sequence tokens in the position embeddings. Selected in the range
|
695 |
+
`[0, config.n_positions - 1]`. [What are position IDs?](../glossary#position-ids)
|
696 |
+
output_attentions (`bool`, *optional*):
|
697 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
|
698 |
+
returned tensors for more detail.
|
699 |
+
use_cache (`bool`, *optional*):
|
700 |
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
|
701 |
+
(see `past_key_values`).
|
702 |
+
past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
|
703 |
+
"""
|
704 |
+
|
705 |
+
residual = hidden_states
|
706 |
+
|
707 |
+
hidden_states = self.ln(hidden_states)
|
708 |
+
|
709 |
+
# Self Attention
|
710 |
+
attn_outputs, self_attn_weights, present_key_value = self.mixer(
|
711 |
+
hidden_states=hidden_states,
|
712 |
+
attention_mask=attention_mask,
|
713 |
+
position_ids=position_ids,
|
714 |
+
past_key_value=past_key_value,
|
715 |
+
output_attentions=output_attentions,
|
716 |
+
use_cache=use_cache,
|
717 |
+
)
|
718 |
+
attn_outputs = self.resid_dropout(attn_outputs)
|
719 |
+
|
720 |
+
feed_forward_hidden_states = self.resid_dropout(self.mlp(hidden_states))
|
721 |
+
hidden_states = attn_outputs + feed_forward_hidden_states + residual
|
722 |
+
outputs = (hidden_states,)
|
723 |
+
|
724 |
+
if output_attentions:
|
725 |
+
outputs += (self_attn_weights,)
|
726 |
+
|
727 |
+
if use_cache:
|
728 |
+
outputs += (present_key_value,)
|
729 |
+
|
730 |
+
return outputs
|
731 |
+
|
732 |
+
|
733 |
+
class PhiPreTrainedModel(PreTrainedModel):
|
734 |
+
config_class = PhiConfig
|
735 |
+
base_model_prefix = "model"
|
736 |
+
supports_gradient_checkpointing = True
|
737 |
+
_no_split_modules = ["PhiDecoderLayer"]
|
738 |
+
_skip_keys_device_placement = "past_key_values"
|
739 |
+
_supports_flash_attn_2 = True
|
740 |
+
_supports_cache_class = True
|
741 |
+
|
742 |
+
def _init_weights(self, module):
|
743 |
+
std = self.config.initializer_range
|
744 |
+
if isinstance(module, nn.Linear):
|
745 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
746 |
+
if module.bias is not None:
|
747 |
+
module.bias.data.zero_()
|
748 |
+
elif isinstance(module, nn.Embedding):
|
749 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
750 |
+
if module.padding_idx is not None:
|
751 |
+
module.weight.data[module.padding_idx].zero_()
|
752 |
+
|
753 |
+
|
754 |
+
class Embedding(nn.Module):
|
755 |
+
def __init__(self, config: PhiConfig):
|
756 |
+
super().__init__()
|
757 |
+
self.wte = nn.Embedding(
|
758 |
+
config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id
|
759 |
+
)
|
760 |
+
|
761 |
+
def forward(self, input_ids: torch.LongTensor) -> torch.FloatTensor:
|
762 |
+
return self.wte(input_ids)
|
763 |
+
|
764 |
+
|
765 |
+
class PhiModel(PhiPreTrainedModel):
|
766 |
+
"""
|
767 |
+
Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`PhiDecoderLayer`]
|
768 |
+
|
769 |
+
Args:
|
770 |
+
config: PhiConfig
|
771 |
+
"""
|
772 |
+
|
773 |
+
def __init__(self, config: PhiConfig):
|
774 |
+
super().__init__(config)
|
775 |
+
self.padding_idx = config.pad_token_id
|
776 |
+
self.vocab_size = config.vocab_size
|
777 |
+
|
778 |
+
self.embd = Embedding(config)
|
779 |
+
self.embed_dropout = nn.Dropout(config.embd_pdrop)
|
780 |
+
self.h = nn.ModuleList(
|
781 |
+
[
|
782 |
+
PhiDecoderLayer(config, layer_idx)
|
783 |
+
for layer_idx in range(config.num_hidden_layers)
|
784 |
+
]
|
785 |
+
)
|
786 |
+
self._use_flash_attention_2 = config._attn_implementation == "flash_attention_2"
|
787 |
+
|
788 |
+
self.gradient_checkpointing = False
|
789 |
+
# Initialize weights and apply final processing
|
790 |
+
self.post_init()
|
791 |
+
|
792 |
+
def get_input_embeddings(self):
|
793 |
+
return self.embd.wte
|
794 |
+
|
795 |
+
def set_input_embeddings(self, value):
|
796 |
+
self.embd.wte = value
|
797 |
+
|
798 |
+
def forward(
|
799 |
+
self,
|
800 |
+
input_ids: torch.LongTensor = None,
|
801 |
+
attention_mask: Optional[torch.Tensor] = None,
|
802 |
+
position_ids: Optional[torch.LongTensor] = None,
|
803 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
804 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
805 |
+
use_cache: Optional[bool] = None,
|
806 |
+
output_attentions: Optional[bool] = None,
|
807 |
+
output_hidden_states: Optional[bool] = None,
|
808 |
+
return_dict: Optional[bool] = None,
|
809 |
+
) -> Union[Tuple, BaseModelOutputWithPast]:
|
810 |
+
output_attentions = (
|
811 |
+
output_attentions
|
812 |
+
if output_attentions is not None
|
813 |
+
else self.config.output_attentions
|
814 |
+
)
|
815 |
+
output_hidden_states = (
|
816 |
+
output_hidden_states
|
817 |
+
if output_hidden_states is not None
|
818 |
+
else self.config.output_hidden_states
|
819 |
+
)
|
820 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
821 |
+
|
822 |
+
return_dict = (
|
823 |
+
return_dict if return_dict is not None else self.config.use_return_dict
|
824 |
+
)
|
825 |
+
|
826 |
+
# retrieve input_ids and inputs_embeds
|
827 |
+
if input_ids is not None and inputs_embeds is not None:
|
828 |
+
raise ValueError(
|
829 |
+
"You cannot specify both input_ids and inputs_embeds at the same time"
|
830 |
+
)
|
831 |
+
elif input_ids is not None:
|
832 |
+
batch_size, seq_length = input_ids.shape[:2]
|
833 |
+
elif inputs_embeds is not None:
|
834 |
+
batch_size, seq_length = inputs_embeds.shape[:2]
|
835 |
+
else:
|
836 |
+
raise ValueError("You have to specify either input_ids or inputs_embeds")
|
837 |
+
|
838 |
+
past_key_values_length = 0
|
839 |
+
|
840 |
+
if self.gradient_checkpointing and self.training:
|
841 |
+
if use_cache:
|
842 |
+
logger.warning_once(
|
843 |
+
"`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
|
844 |
+
)
|
845 |
+
use_cache = False
|
846 |
+
|
847 |
+
if use_cache:
|
848 |
+
use_legacy_cache = not isinstance(past_key_values, Cache)
|
849 |
+
if use_legacy_cache:
|
850 |
+
past_key_values = DynamicCache.from_legacy_cache(past_key_values)
|
851 |
+
past_key_values_length = past_key_values.get_usable_length(seq_length)
|
852 |
+
|
853 |
+
if position_ids is None:
|
854 |
+
device = input_ids.device if input_ids is not None else inputs_embeds.device
|
855 |
+
position_ids = torch.arange(
|
856 |
+
past_key_values_length,
|
857 |
+
seq_length + past_key_values_length,
|
858 |
+
dtype=torch.long,
|
859 |
+
device=device,
|
860 |
+
)
|
861 |
+
position_ids = position_ids.unsqueeze(0)
|
862 |
+
|
863 |
+
if inputs_embeds is None:
|
864 |
+
inputs_embeds = self.embd(input_ids)
|
865 |
+
|
866 |
+
inputs_embeds = self.embed_dropout(inputs_embeds)
|
867 |
+
|
868 |
+
# Attention mask.
|
869 |
+
if self._use_flash_attention_2:
|
870 |
+
# 2d mask is passed through the layers
|
871 |
+
attention_mask = (
|
872 |
+
attention_mask
|
873 |
+
if (attention_mask is not None and 0 in attention_mask)
|
874 |
+
else None
|
875 |
+
)
|
876 |
+
else:
|
877 |
+
# 4d mask is passed through the layers
|
878 |
+
attention_mask = _prepare_4d_causal_attention_mask(
|
879 |
+
attention_mask,
|
880 |
+
(batch_size, seq_length),
|
881 |
+
inputs_embeds,
|
882 |
+
past_key_values_length,
|
883 |
+
)
|
884 |
+
|
885 |
+
hidden_states = inputs_embeds
|
886 |
+
|
887 |
+
# decoder layers
|
888 |
+
all_hidden_states = () if output_hidden_states else None
|
889 |
+
all_self_attns = () if output_attentions else None
|
890 |
+
next_decoder_cache = None
|
891 |
+
|
892 |
+
for decoder_layer in self.h:
|
893 |
+
if output_hidden_states:
|
894 |
+
all_hidden_states += (hidden_states,)
|
895 |
+
|
896 |
+
if self.gradient_checkpointing and self.training:
|
897 |
+
layer_outputs = self._gradient_checkpointing_func(
|
898 |
+
decoder_layer.__call__,
|
899 |
+
hidden_states,
|
900 |
+
attention_mask,
|
901 |
+
position_ids,
|
902 |
+
past_key_values,
|
903 |
+
output_attentions,
|
904 |
+
)
|
905 |
+
else:
|
906 |
+
layer_outputs = decoder_layer(
|
907 |
+
hidden_states,
|
908 |
+
attention_mask=attention_mask,
|
909 |
+
position_ids=position_ids,
|
910 |
+
past_key_value=past_key_values,
|
911 |
+
output_attentions=output_attentions,
|
912 |
+
use_cache=use_cache,
|
913 |
+
)
|
914 |
+
|
915 |
+
hidden_states = layer_outputs[0]
|
916 |
+
|
917 |
+
if use_cache:
|
918 |
+
next_decoder_cache = layer_outputs[2 if output_attentions else 1]
|
919 |
+
|
920 |
+
if output_attentions:
|
921 |
+
all_self_attns += (layer_outputs[1],)
|
922 |
+
|
923 |
+
# add hidden states from the last decoder layer
|
924 |
+
if output_hidden_states:
|
925 |
+
all_hidden_states += (hidden_states,)
|
926 |
+
|
927 |
+
next_cache = None
|
928 |
+
if use_cache:
|
929 |
+
next_cache = (
|
930 |
+
next_decoder_cache.to_legacy_cache()
|
931 |
+
if use_legacy_cache
|
932 |
+
else next_decoder_cache
|
933 |
+
)
|
934 |
+
if not return_dict:
|
935 |
+
return tuple(
|
936 |
+
v
|
937 |
+
for v in [hidden_states, next_cache, all_hidden_states, all_self_attns]
|
938 |
+
if v is not None
|
939 |
+
)
|
940 |
+
return BaseModelOutputWithPast(
|
941 |
+
last_hidden_state=hidden_states,
|
942 |
+
past_key_values=next_cache,
|
943 |
+
hidden_states=all_hidden_states,
|
944 |
+
attentions=all_self_attns,
|
945 |
+
)
|
946 |
+
|
947 |
+
|
948 |
+
class CausalLMHead(nn.Module):
|
949 |
+
"""Causal Language Modeling head. Simplified version."""
|
950 |
+
|
951 |
+
def __init__(self, config):
|
952 |
+
super().__init__()
|
953 |
+
self.ln = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
954 |
+
self.linear = nn.Linear(config.hidden_size, config.vocab_size)
|
955 |
+
|
956 |
+
def forward(self, hidden_states):
|
957 |
+
return self.linear(self.ln(hidden_states))
|
958 |
+
|
959 |
+
|
960 |
+
class PhiForCausalLM(PhiPreTrainedModel):
|
961 |
+
_tied_weights_keys = ["lm_head.linear.weight"]
|
962 |
+
|
963 |
+
# Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.__init__ with Llama->Phi,bias=False->bias=True
|
964 |
+
def __init__(self, config):
|
965 |
+
super().__init__(config)
|
966 |
+
self.transformer = PhiModel(config)
|
967 |
+
self.vocab_size = config.vocab_size
|
968 |
+
self.lm_head = CausalLMHead(config)
|
969 |
+
|
970 |
+
# Initialize weights and apply final processing
|
971 |
+
self.post_init()
|
972 |
+
|
973 |
+
# Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.get_input_embeddings
|
974 |
+
def get_input_embeddings(self):
|
975 |
+
return self.transformer.embd.wte
|
976 |
+
|
977 |
+
# Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.set_input_embeddings
|
978 |
+
def set_input_embeddings(self, value):
|
979 |
+
self.model.embd.wte = value
|
980 |
+
|
981 |
+
# Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.get_output_embeddings
|
982 |
+
def get_output_embeddings(self):
|
983 |
+
return self.lm_head.linear
|
984 |
+
|
985 |
+
# Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.set_output_embeddings
|
986 |
+
def set_output_embeddings(self, new_embeddings):
|
987 |
+
self.lm_head.linear = new_embeddings
|
988 |
+
|
989 |
+
# Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.set_decoder
|
990 |
+
def set_decoder(self, decoder):
|
991 |
+
self.model = decoder
|
992 |
+
|
993 |
+
# Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.get_decoder
|
994 |
+
def get_decoder(self):
|
995 |
+
return self.model
|
996 |
+
|
997 |
+
def forward(
|
998 |
+
self,
|
999 |
+
input_ids: torch.LongTensor = None,
|
1000 |
+
attention_mask: Optional[torch.Tensor] = None,
|
1001 |
+
position_ids: Optional[torch.LongTensor] = None,
|
1002 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
1003 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
1004 |
+
labels: Optional[torch.LongTensor] = None,
|
1005 |
+
use_cache: Optional[bool] = None,
|
1006 |
+
output_attentions: Optional[bool] = None,
|
1007 |
+
output_hidden_states: Optional[bool] = None,
|
1008 |
+
return_dict: Optional[bool] = None,
|
1009 |
+
) -> Union[Tuple, CausalLMOutputWithPast]:
|
1010 |
+
r"""
|
1011 |
+
Args:
|
1012 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
1013 |
+
Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
|
1014 |
+
config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
|
1015 |
+
(masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
|
1016 |
+
|
1017 |
+
Returns:
|
1018 |
+
|
1019 |
+
Example:
|
1020 |
+
|
1021 |
+
```python
|
1022 |
+
>>> from transformers import AutoTokenizer, PhiForCausalLM
|
1023 |
+
|
1024 |
+
>>> model = PhiForCausalLM.from_pretrained("microsoft/phi-1")
|
1025 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("microsoft/phi-1")
|
1026 |
+
|
1027 |
+
>>> prompt = "This is an example script ."
|
1028 |
+
>>> inputs = tokenizer(prompt, return_tensors="pt")
|
1029 |
+
|
1030 |
+
>>> # Generate
|
1031 |
+
>>> generate_ids = model.generate(inputs.input_ids, max_length=30)
|
1032 |
+
>>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
|
1033 |
+
'This is an example script .\n\n\n\nfrom typing import List\n\ndef find_most_common_letter(words: List[str'
|
1034 |
+
```"""
|
1035 |
+
|
1036 |
+
output_attentions = (
|
1037 |
+
output_attentions
|
1038 |
+
if output_attentions is not None
|
1039 |
+
else self.config.output_attentions
|
1040 |
+
)
|
1041 |
+
output_hidden_states = (
|
1042 |
+
output_hidden_states
|
1043 |
+
if output_hidden_states is not None
|
1044 |
+
else self.config.output_hidden_states
|
1045 |
+
)
|
1046 |
+
return_dict = (
|
1047 |
+
return_dict if return_dict is not None else self.config.use_return_dict
|
1048 |
+
)
|
1049 |
+
|
1050 |
+
# decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
|
1051 |
+
outputs = self.transformer(
|
1052 |
+
input_ids=input_ids,
|
1053 |
+
attention_mask=attention_mask,
|
1054 |
+
position_ids=position_ids,
|
1055 |
+
past_key_values=past_key_values,
|
1056 |
+
inputs_embeds=inputs_embeds,
|
1057 |
+
use_cache=use_cache,
|
1058 |
+
output_attentions=output_attentions,
|
1059 |
+
output_hidden_states=output_hidden_states,
|
1060 |
+
return_dict=return_dict,
|
1061 |
+
)
|
1062 |
+
|
1063 |
+
hidden_states = outputs[0]
|
1064 |
+
logits = self.lm_head(hidden_states)
|
1065 |
+
|
1066 |
+
loss = None
|
1067 |
+
if labels is not None:
|
1068 |
+
# Shift so that tokens < n predict n
|
1069 |
+
shift_logits = logits[..., :-1, :].contiguous()
|
1070 |
+
shift_labels = labels[..., 1:].contiguous()
|
1071 |
+
# Flatten the tokens
|
1072 |
+
loss_fct = CrossEntropyLoss()
|
1073 |
+
shift_logits = shift_logits.view(-1, self.config.vocab_size)
|
1074 |
+
shift_labels = shift_labels.view(-1)
|
1075 |
+
# Enable model parallelism
|
1076 |
+
shift_labels = shift_labels.to(shift_logits.device)
|
1077 |
+
loss = loss_fct(shift_logits, shift_labels)
|
1078 |
+
|
1079 |
+
if not return_dict:
|
1080 |
+
output = (logits,) + outputs[1:]
|
1081 |
+
return (loss,) + output if loss is not None else output
|
1082 |
+
|
1083 |
+
return CausalLMOutputWithPast(
|
1084 |
+
loss=loss,
|
1085 |
+
logits=logits,
|
1086 |
+
past_key_values=outputs.past_key_values,
|
1087 |
+
hidden_states=outputs.hidden_states,
|
1088 |
+
attentions=outputs.attentions,
|
1089 |
+
)
|
1090 |
+
|
1091 |
+
# Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.prepare_inputs_for_generation
|
1092 |
+
def prepare_inputs_for_generation(
|
1093 |
+
self,
|
1094 |
+
input_ids,
|
1095 |
+
past_key_values=None,
|
1096 |
+
attention_mask=None,
|
1097 |
+
inputs_embeds=None,
|
1098 |
+
**kwargs,
|
1099 |
+
):
|
1100 |
+
if past_key_values is not None:
|
1101 |
+
if isinstance(past_key_values, Cache):
|
1102 |
+
cache_length = past_key_values.get_seq_length()
|
1103 |
+
past_length = past_key_values.seen_tokens
|
1104 |
+
max_cache_length = past_key_values.get_max_length()
|
1105 |
+
else:
|
1106 |
+
cache_length = past_length = past_key_values[0][0].shape[2]
|
1107 |
+
max_cache_length = None
|
1108 |
+
|
1109 |
+
# Keep only the unprocessed tokens:
|
1110 |
+
# 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where
|
1111 |
+
# some of the inputs are exclusively passed as part of the cache (e.g. when passing input_embeds as
|
1112 |
+
# input)
|
1113 |
+
if (
|
1114 |
+
attention_mask is not None
|
1115 |
+
and attention_mask.shape[1] > input_ids.shape[1]
|
1116 |
+
):
|
1117 |
+
input_ids = input_ids[:, -(attention_mask.shape[1] - past_length) :]
|
1118 |
+
# 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens. We can discard
|
1119 |
+
# input_ids based on the past_length.
|
1120 |
+
elif past_length < input_ids.shape[1]:
|
1121 |
+
input_ids = input_ids[:, past_length:]
|
1122 |
+
# 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens.
|
1123 |
+
|
1124 |
+
# If we are about to go beyond the maximum cache length, we need to crop the input attention mask.
|
1125 |
+
if (
|
1126 |
+
max_cache_length is not None
|
1127 |
+
and attention_mask is not None
|
1128 |
+
and cache_length + input_ids.shape[1] > max_cache_length
|
1129 |
+
):
|
1130 |
+
attention_mask = attention_mask[:, -max_cache_length:]
|
1131 |
+
|
1132 |
+
position_ids = kwargs.get("position_ids", None)
|
1133 |
+
if attention_mask is not None and position_ids is None:
|
1134 |
+
# create position_ids on the fly for batch generation
|
1135 |
+
position_ids = attention_mask.long().cumsum(-1) - 1
|
1136 |
+
position_ids.masked_fill_(attention_mask == 0, 1)
|
1137 |
+
if past_key_values:
|
1138 |
+
position_ids = position_ids[:, -input_ids.shape[1] :]
|
1139 |
+
|
1140 |
+
# if `inputs_embeds` are passed, we only want to use them in the 1st generation step
|
1141 |
+
if inputs_embeds is not None and (input_ids is None or input_ids.shape[1] == 0):
|
1142 |
+
model_inputs = {"inputs_embeds": inputs_embeds}
|
1143 |
+
else:
|
1144 |
+
model_inputs = {"input_ids": input_ids}
|
1145 |
+
|
1146 |
+
model_inputs.update(
|
1147 |
+
{
|
1148 |
+
"position_ids": position_ids,
|
1149 |
+
"past_key_values": past_key_values,
|
1150 |
+
"use_cache": kwargs.get("use_cache"),
|
1151 |
+
"attention_mask": attention_mask,
|
1152 |
+
}
|
1153 |
+
)
|
1154 |
+
return model_inputs
|
1155 |
+
|
1156 |
+
@staticmethod
|
1157 |
+
# Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM._reorder_cache
|
1158 |
+
def _reorder_cache(past_key_values, beam_idx):
|
1159 |
+
reordered_past = ()
|
1160 |
+
for layer_past in past_key_values:
|
1161 |
+
reordered_past += (
|
1162 |
+
tuple(
|
1163 |
+
past_state.index_select(0, beam_idx.to(past_state.device))
|
1164 |
+
for past_state in layer_past
|
1165 |
+
),
|
1166 |
+
)
|
1167 |
+
return reordered_past
|
moondream.py
ADDED
@@ -0,0 +1,180 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
from .vision_encoder import VisionEncoder
|
3 |
+
from .configuration_moondream import MoondreamConfig
|
4 |
+
from transformers import PreTrainedModel, TextStreamer
|
5 |
+
|
6 |
+
from .modeling_phi import PhiForCausalLM
|
7 |
+
from .configuration_moondream import PhiConfig
|
8 |
+
|
9 |
+
class Moondream(PreTrainedModel):
|
10 |
+
config_class = MoondreamConfig
|
11 |
+
_supports_flash_attn_2 = True
|
12 |
+
|
13 |
+
def __init__(self, config):
|
14 |
+
super().__init__(config)
|
15 |
+
self.vision_encoder = VisionEncoder(
|
16 |
+
use_flash_attn=config._attn_implementation == "flash_attention_2"
|
17 |
+
)
|
18 |
+
|
19 |
+
if type(config.text_config) == dict:
|
20 |
+
phi_config = PhiConfig(
|
21 |
+
**config.text_config, attn_implementation=config._attn_implementation
|
22 |
+
)
|
23 |
+
else:
|
24 |
+
phi_config = config.text_config
|
25 |
+
self.text_model = PhiForCausalLM(phi_config)
|
26 |
+
|
27 |
+
@property
|
28 |
+
def device(self):
|
29 |
+
return self.text_model.device
|
30 |
+
|
31 |
+
def encode_image(self, image):
|
32 |
+
with torch.no_grad():
|
33 |
+
return self.vision_encoder(image)
|
34 |
+
|
35 |
+
def input_embeds(self, prompt, image_embeds, tokenizer):
|
36 |
+
def _tokenize(txt):
|
37 |
+
return tokenizer(
|
38 |
+
txt, return_tensors="pt", add_special_tokens=False
|
39 |
+
).input_ids.to(self.device)
|
40 |
+
|
41 |
+
text_emb = self.text_model.get_input_embeddings()
|
42 |
+
|
43 |
+
# Add BOS token
|
44 |
+
embeds = []
|
45 |
+
embeds.append(
|
46 |
+
text_emb((torch.tensor([[tokenizer.bos_token_id]], device=self.device)))
|
47 |
+
)
|
48 |
+
|
49 |
+
if "<image>" not in prompt:
|
50 |
+
embeds.append(text_emb(_tokenize(prompt)))
|
51 |
+
else:
|
52 |
+
assert prompt.count("<image>") == 1
|
53 |
+
before, after = prompt.split("<image>")
|
54 |
+
if len(before) > 0:
|
55 |
+
embeds.append(text_emb(_tokenize(before)))
|
56 |
+
embeds.append(image_embeds.to(self.device))
|
57 |
+
if len(after) > 0:
|
58 |
+
embeds.append(text_emb(_tokenize(after)))
|
59 |
+
|
60 |
+
return torch.cat(embeds, dim=1)
|
61 |
+
|
62 |
+
def get_input_embeddings(self):
|
63 |
+
return self.text_model.get_input_embeddings()
|
64 |
+
|
65 |
+
def generate(
|
66 |
+
self,
|
67 |
+
image_embeds,
|
68 |
+
prompt,
|
69 |
+
tokenizer,
|
70 |
+
max_new_tokens=128,
|
71 |
+
**kwargs,
|
72 |
+
):
|
73 |
+
generate_config = {
|
74 |
+
"eos_token_id": tokenizer.eos_token_id,
|
75 |
+
"bos_token_id": tokenizer.bos_token_id,
|
76 |
+
"pad_token_id": tokenizer.bos_token_id,
|
77 |
+
"max_new_tokens": max_new_tokens,
|
78 |
+
**kwargs,
|
79 |
+
}
|
80 |
+
|
81 |
+
with torch.no_grad():
|
82 |
+
inputs_embeds = self.input_embeds(prompt, image_embeds, tokenizer)
|
83 |
+
streamer = TextStreamer(inputs_embeds)
|
84 |
+
output_ids = self.text_model.generate(
|
85 |
+
inputs_embeds=inputs_embeds, streamer=streamer, **generate_config
|
86 |
+
)
|
87 |
+
print("OUTPUTIDS" + output_ids)
|
88 |
+
|
89 |
+
return tokenizer.batch_decode(output_ids, skip_special_tokens=True)
|
90 |
+
|
91 |
+
def answer_question(
|
92 |
+
self,
|
93 |
+
image_embeds,
|
94 |
+
question,
|
95 |
+
tokenizer,
|
96 |
+
chat_history="",
|
97 |
+
result_queue=None,
|
98 |
+
**kwargs,
|
99 |
+
):
|
100 |
+
prompt = f"<image>\n\n{chat_history}Question: {question}\n\nAnswer:"
|
101 |
+
answer = self.generate(
|
102 |
+
image_embeds,
|
103 |
+
prompt,
|
104 |
+
tokenizer=tokenizer,
|
105 |
+
max_new_tokens=512,
|
106 |
+
**kwargs,
|
107 |
+
)[0]
|
108 |
+
cleaned_answer = answer.strip()
|
109 |
+
|
110 |
+
# Use the result_queue to pass the result if it is provided
|
111 |
+
if result_queue:
|
112 |
+
result_queue.put(cleaned_answer)
|
113 |
+
else:
|
114 |
+
return cleaned_answer
|
115 |
+
|
116 |
+
def batch_answer(
|
117 |
+
self,
|
118 |
+
images,
|
119 |
+
prompts,
|
120 |
+
tokenizer,
|
121 |
+
**kwargs,
|
122 |
+
):
|
123 |
+
image_embeds = self.encode_image(images)
|
124 |
+
|
125 |
+
templated_prompts = [
|
126 |
+
f"<image>\n\nQuestion: {prompt}\n\nAnswer:" for prompt in prompts
|
127 |
+
]
|
128 |
+
prompt_embs = [
|
129 |
+
self.input_embeds(prompt, image_embed.unsqueeze(0), tokenizer)[0]
|
130 |
+
for prompt, image_embed in zip(templated_prompts, image_embeds)
|
131 |
+
]
|
132 |
+
|
133 |
+
bos_emb = prompt_embs[0][0]
|
134 |
+
max_len = max([p.shape[0] for p in prompt_embs])
|
135 |
+
|
136 |
+
inputs_embeds = torch.cat(
|
137 |
+
[
|
138 |
+
torch.cat([bos_emb.repeat(max_len - p.shape[0], 1), p]).unsqueeze(0)
|
139 |
+
for p in prompt_embs
|
140 |
+
],
|
141 |
+
dim=0,
|
142 |
+
)
|
143 |
+
attention_mask = torch.cat(
|
144 |
+
[
|
145 |
+
torch.cat(
|
146 |
+
[
|
147 |
+
torch.zeros(
|
148 |
+
1,
|
149 |
+
max_len - p.shape[0],
|
150 |
+
device=self.device,
|
151 |
+
dtype=torch.long,
|
152 |
+
),
|
153 |
+
torch.ones(1, p.shape[0], device=self.device, dtype=torch.long),
|
154 |
+
],
|
155 |
+
dim=1,
|
156 |
+
)
|
157 |
+
for p in prompt_embs
|
158 |
+
],
|
159 |
+
dim=0,
|
160 |
+
)
|
161 |
+
|
162 |
+
generate_config = {
|
163 |
+
"eos_token_id": tokenizer.eos_token_id,
|
164 |
+
"bos_token_id": tokenizer.bos_token_id,
|
165 |
+
"pad_token_id": tokenizer.bos_token_id,
|
166 |
+
"max_new_tokens": 512,
|
167 |
+
**kwargs,
|
168 |
+
}
|
169 |
+
|
170 |
+
with torch.no_grad():
|
171 |
+
output_ids = self.text_model.generate(
|
172 |
+
inputs_embeds=inputs_embeds,
|
173 |
+
attention_mask=attention_mask,
|
174 |
+
**generate_config,
|
175 |
+
)
|
176 |
+
|
177 |
+
return [
|
178 |
+
x.strip()
|
179 |
+
for x in tokenizer.batch_decode(output_ids, skip_special_tokens=True)
|
180 |
+
]
|
moondream2-mmproj-f16.gguf
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:4cc1cb3660d87ff56432ebeb7884ad35d67c48c7b9f6b2856f305e39c38eed8f
|
3 |
+
size 909777984
|
moondream2-text-model-f16.gguf
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:4e17e9107fb8781629b3c8ce177de57ffeae90fe14adcf7b99f0eef025889696
|
3 |
+
size 2839534976
|
special_tokens_map.json
ADDED
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"bos_token": "<|endoftext|>",
|
3 |
+
"eos_token": "<|endoftext|>",
|
4 |
+
"unk_token": "<|endoftext|>"
|
5 |
+
}
|
tokenizer.json
ADDED
The diff for this file is too large to render.
See raw diff
|
|
tokenizer_config.json
ADDED
@@ -0,0 +1,323 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"add_prefix_space": false,
|
3 |
+
"added_tokens_decoder": {
|
4 |
+
"50256": {
|
5 |
+
"content": "<|endoftext|>",
|
6 |
+
"lstrip": false,
|
7 |
+
"normalized": false,
|
8 |
+
"rstrip": false,
|
9 |
+
"single_word": false,
|
10 |
+
"special": true
|
11 |
+
},
|
12 |
+
"50257": {
|
13 |
+
"content": " ",
|
14 |
+
"lstrip": false,
|
15 |
+
"normalized": true,
|
16 |
+
"rstrip": false,
|
17 |
+
"single_word": false,
|
18 |
+
"special": false
|
19 |
+
},
|
20 |
+
"50258": {
|
21 |
+
"content": " ",
|
22 |
+
"lstrip": false,
|
23 |
+
"normalized": true,
|
24 |
+
"rstrip": false,
|
25 |
+
"single_word": false,
|
26 |
+
"special": false
|
27 |
+
},
|
28 |
+
"50259": {
|
29 |
+
"content": " ",
|
30 |
+
"lstrip": false,
|
31 |
+
"normalized": true,
|
32 |
+
"rstrip": false,
|
33 |
+
"single_word": false,
|
34 |
+
"special": false
|
35 |
+
},
|
36 |
+
"50260": {
|
37 |
+
"content": " ",
|
38 |
+
"lstrip": false,
|
39 |
+
"normalized": true,
|
40 |
+
"rstrip": false,
|
41 |
+
"single_word": false,
|
42 |
+
"special": false
|
43 |
+
},
|
44 |
+
"50261": {
|
45 |
+
"content": " ",
|
46 |
+
"lstrip": false,
|
47 |
+
"normalized": true,
|
48 |
+
"rstrip": false,
|
49 |
+
"single_word": false,
|
50 |
+
"special": false
|
51 |
+
},
|
52 |
+
"50262": {
|
53 |
+
"content": " ",
|
54 |
+
"lstrip": false,
|
55 |
+
"normalized": true,
|
56 |
+
"rstrip": false,
|
57 |
+
"single_word": false,
|
58 |
+
"special": false
|
59 |
+
},
|
60 |
+
"50263": {
|
61 |
+
"content": " ",
|
62 |
+
"lstrip": false,
|
63 |
+
"normalized": true,
|
64 |
+
"rstrip": false,
|
65 |
+
"single_word": false,
|
66 |
+
"special": false
|
67 |
+
},
|
68 |
+
"50264": {
|
69 |
+
"content": " ",
|
70 |
+
"lstrip": false,
|
71 |
+
"normalized": true,
|
72 |
+
"rstrip": false,
|
73 |
+
"single_word": false,
|
74 |
+
"special": false
|
75 |
+
},
|
76 |
+
"50265": {
|
77 |
+
"content": " ",
|
78 |
+
"lstrip": false,
|
79 |
+
"normalized": true,
|
80 |
+
"rstrip": false,
|
81 |
+
"single_word": false,
|
82 |
+
"special": false
|
83 |
+
},
|
84 |
+
"50266": {
|
85 |
+
"content": " ",
|
86 |
+
"lstrip": false,
|
87 |
+
"normalized": true,
|
88 |
+
"rstrip": false,
|
89 |
+
"single_word": false,
|
90 |
+
"special": false
|
91 |
+
},
|
92 |
+
"50267": {
|
93 |
+
"content": " ",
|
94 |
+
"lstrip": false,
|
95 |
+
"normalized": true,
|
96 |
+
"rstrip": false,
|
97 |
+
"single_word": false,
|
98 |
+
"special": false
|
99 |
+
},
|
100 |
+
"50268": {
|
101 |
+
"content": " ",
|
102 |
+
"lstrip": false,
|
103 |
+
"normalized": true,
|
104 |
+
"rstrip": false,
|
105 |
+
"single_word": false,
|
106 |
+
"special": false
|
107 |
+
},
|
108 |
+
"50269": {
|
109 |
+
"content": " ",
|
110 |
+
"lstrip": false,
|
111 |
+
"normalized": true,
|
112 |
+
"rstrip": false,
|
113 |
+
"single_word": false,
|
114 |
+
"special": false
|
115 |
+
},
|
116 |
+
"50270": {
|
117 |
+
"content": " ",
|
118 |
+
"lstrip": false,
|
119 |
+
"normalized": true,
|
120 |
+
"rstrip": false,
|
121 |
+
"single_word": false,
|
122 |
+
"special": false
|
123 |
+
},
|
124 |
+
"50271": {
|
125 |
+
"content": " ",
|
126 |
+
"lstrip": false,
|
127 |
+
"normalized": true,
|
128 |
+
"rstrip": false,
|
129 |
+
"single_word": false,
|
130 |
+
"special": false
|
131 |
+
},
|
132 |
+
"50272": {
|
133 |
+
"content": " ",
|
134 |
+
"lstrip": false,
|
135 |
+
"normalized": true,
|
136 |
+
"rstrip": false,
|
137 |
+
"single_word": false,
|
138 |
+
"special": false
|
139 |
+
},
|
140 |
+
"50273": {
|
141 |
+
"content": " ",
|
142 |
+
"lstrip": false,
|
143 |
+
"normalized": true,
|
144 |
+
"rstrip": false,
|
145 |
+
"single_word": false,
|
146 |
+
"special": false
|
147 |
+
},
|
148 |
+
"50274": {
|
149 |
+
"content": " ",
|
150 |
+
"lstrip": false,
|
151 |
+
"normalized": true,
|
152 |
+
"rstrip": false,
|
153 |
+
"single_word": false,
|
154 |
+
"special": false
|
155 |
+
},
|
156 |
+
"50275": {
|
157 |
+
"content": " ",
|
158 |
+
"lstrip": false,
|
159 |
+
"normalized": true,
|
160 |
+
"rstrip": false,
|
161 |
+
"single_word": false,
|
162 |
+
"special": false
|
163 |
+
},
|
164 |
+
"50276": {
|
165 |
+
"content": " ",
|
166 |
+
"lstrip": false,
|
167 |
+
"normalized": true,
|
168 |
+
"rstrip": false,
|
169 |
+
"single_word": false,
|
170 |
+
"special": false
|
171 |
+
},
|
172 |
+
"50277": {
|
173 |
+
"content": " ",
|
174 |
+
"lstrip": false,
|
175 |
+
"normalized": true,
|
176 |
+
"rstrip": false,
|
177 |
+
"single_word": false,
|
178 |
+
"special": false
|
179 |
+
},
|
180 |
+
"50278": {
|
181 |
+
"content": " ",
|
182 |
+
"lstrip": false,
|
183 |
+
"normalized": true,
|
184 |
+
"rstrip": false,
|
185 |
+
"single_word": false,
|
186 |
+
"special": false
|
187 |
+
},
|
188 |
+
"50279": {
|
189 |
+
"content": " ",
|
190 |
+
"lstrip": false,
|
191 |
+
"normalized": true,
|
192 |
+
"rstrip": false,
|
193 |
+
"single_word": false,
|
194 |
+
"special": false
|
195 |
+
},
|
196 |
+
"50280": {
|
197 |
+
"content": " ",
|
198 |
+
"lstrip": false,
|
199 |
+
"normalized": true,
|
200 |
+
"rstrip": false,
|
201 |
+
"single_word": false,
|
202 |
+
"special": false
|
203 |
+
},
|
204 |
+
"50281": {
|
205 |
+
"content": " ",
|
206 |
+
"lstrip": false,
|
207 |
+
"normalized": true,
|
208 |
+
"rstrip": false,
|
209 |
+
"single_word": false,
|
210 |
+
"special": false
|
211 |
+
},
|
212 |
+
"50282": {
|
213 |
+
"content": " ",
|
214 |
+
"lstrip": false,
|
215 |
+
"normalized": true,
|
216 |
+
"rstrip": false,
|
217 |
+
"single_word": false,
|
218 |
+
"special": false
|
219 |
+
},
|
220 |
+
"50283": {
|
221 |
+
"content": " ",
|
222 |
+
"lstrip": false,
|
223 |
+
"normalized": true,
|
224 |
+
"rstrip": false,
|
225 |
+
"single_word": false,
|
226 |
+
"special": false
|
227 |
+
},
|
228 |
+
"50284": {
|
229 |
+
"content": " ",
|
230 |
+
"lstrip": false,
|
231 |
+
"normalized": true,
|
232 |
+
"rstrip": false,
|
233 |
+
"single_word": false,
|
234 |
+
"special": false
|
235 |
+
},
|
236 |
+
"50285": {
|
237 |
+
"content": " ",
|
238 |
+
"lstrip": false,
|
239 |
+
"normalized": true,
|
240 |
+
"rstrip": false,
|
241 |
+
"single_word": false,
|
242 |
+
"special": false
|
243 |
+
},
|
244 |
+
"50286": {
|
245 |
+
"content": " ",
|
246 |
+
"lstrip": false,
|
247 |
+
"normalized": true,
|
248 |
+
"rstrip": false,
|
249 |
+
"single_word": false,
|
250 |
+
"special": false
|
251 |
+
},
|
252 |
+
"50287": {
|
253 |
+
"content": "\t\t\t\t\t\t\t\t\t",
|
254 |
+
"lstrip": false,
|
255 |
+
"normalized": true,
|
256 |
+
"rstrip": false,
|
257 |
+
"single_word": false,
|
258 |
+
"special": false
|
259 |
+
},
|
260 |
+
"50288": {
|
261 |
+
"content": "\t\t\t\t\t\t\t\t",
|
262 |
+
"lstrip": false,
|
263 |
+
"normalized": true,
|
264 |
+
"rstrip": false,
|
265 |
+
"single_word": false,
|
266 |
+
"special": false
|
267 |
+
},
|
268 |
+
"50289": {
|
269 |
+
"content": "\t\t\t\t\t\t\t",
|
270 |
+
"lstrip": false,
|
271 |
+
"normalized": true,
|
272 |
+
"rstrip": false,
|
273 |
+
"single_word": false,
|
274 |
+
"special": false
|
275 |
+
},
|
276 |
+
"50290": {
|
277 |
+
"content": "\t\t\t\t\t\t",
|
278 |
+
"lstrip": false,
|
279 |
+
"normalized": true,
|
280 |
+
"rstrip": false,
|
281 |
+
"single_word": false,
|
282 |
+
"special": false
|
283 |
+
},
|
284 |
+
"50291": {
|
285 |
+
"content": "\t\t\t\t\t",
|
286 |
+
"lstrip": false,
|
287 |
+
"normalized": true,
|
288 |
+
"rstrip": false,
|
289 |
+
"single_word": false,
|
290 |
+
"special": false
|
291 |
+
},
|
292 |
+
"50292": {
|
293 |
+
"content": "\t\t\t\t",
|
294 |
+
"lstrip": false,
|
295 |
+
"normalized": true,
|
296 |
+
"rstrip": false,
|
297 |
+
"single_word": false,
|
298 |
+
"special": false
|
299 |
+
},
|
300 |
+
"50293": {
|
301 |
+
"content": "\t\t\t",
|
302 |
+
"lstrip": false,
|
303 |
+
"normalized": true,
|
304 |
+
"rstrip": false,
|
305 |
+
"single_word": false,
|
306 |
+
"special": false
|
307 |
+
},
|
308 |
+
"50294": {
|
309 |
+
"content": "\t\t",
|
310 |
+
"lstrip": false,
|
311 |
+
"normalized": true,
|
312 |
+
"rstrip": false,
|
313 |
+
"single_word": false,
|
314 |
+
"special": false
|
315 |
+
}
|
316 |
+
},
|
317 |
+
"bos_token": "<|endoftext|>",
|
318 |
+
"clean_up_tokenization_spaces": true,
|
319 |
+
"eos_token": "<|endoftext|>",
|
320 |
+
"model_max_length": 2048,
|
321 |
+
"tokenizer_class": "CodeGenTokenizer",
|
322 |
+
"unk_token": "<|endoftext|>"
|
323 |
+
}
|
versions.txt
ADDED
@@ -0,0 +1,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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from typing import Union
|
2 |
+
|
3 |
+
import PIL.Image
|
4 |
+
import torch
|
5 |
+
import torch.nn.functional as F
|
6 |
+
from torch import nn
|
7 |
+
from einops import rearrange
|
8 |
+
import PIL
|
9 |
+
from torchvision.transforms.v2 import (
|
10 |
+
Compose,
|
11 |
+
Resize,
|
12 |
+
InterpolationMode,
|
13 |
+
ToImage,
|
14 |
+
ToDtype,
|
15 |
+
Normalize,
|
16 |
+
)
|
17 |
+
from transformers.utils import is_flash_attn_2_available
|
18 |
+
|
19 |
+
try:
|
20 |
+
if is_flash_attn_2_available():
|
21 |
+
from flash_attn.modules.mha import FlashSelfAttention
|
22 |
+
else:
|
23 |
+
FlashSelfAttention = None
|
24 |
+
except ImportError:
|
25 |
+
FlashSelfAttention = None
|
26 |
+
|
27 |
+
|
28 |
+
class Attention(nn.Module):
|
29 |
+
|
30 |
+
def __init__(self, dim, num_heads=16, use_flash_attn=False):
|
31 |
+
super().__init__()
|
32 |
+
assert dim % num_heads == 0, "dim should be divisible by num_heads"
|
33 |
+
|
34 |
+
self.num_heads = num_heads
|
35 |
+
self.head_dim = dim // num_heads
|
36 |
+
|
37 |
+
self.qkv = nn.Linear(dim, dim * 3)
|
38 |
+
self.proj = nn.Linear(dim, dim)
|
39 |
+
|
40 |
+
if use_flash_attn and FlashSelfAttention is not None:
|
41 |
+
self.flash_attn = FlashSelfAttention()
|
42 |
+
else:
|
43 |
+
self.flash_attn = None
|
44 |
+
|
45 |
+
torch.nn.init.kaiming_normal_(
|
46 |
+
self.qkv.weight, mode="fan_in", nonlinearity="relu"
|
47 |
+
)
|
48 |
+
torch.nn.init.kaiming_normal_(
|
49 |
+
self.proj.weight, mode="fan_in", nonlinearity="relu"
|
50 |
+
)
|
51 |
+
|
52 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
53 |
+
if self.flash_attn is not None:
|
54 |
+
qkv = self.qkv(x)
|
55 |
+
qkv = rearrange(
|
56 |
+
qkv, "... (three h d) -> ... three h d", three=3, h=self.num_heads
|
57 |
+
)
|
58 |
+
attn_output = self.flash_attn(qkv)
|
59 |
+
output = rearrange(attn_output, "... h d -> ... (h d)")
|
60 |
+
output = self.proj(output)
|
61 |
+
return output
|
62 |
+
else:
|
63 |
+
B, N, C = x.shape
|
64 |
+
qkv = (
|
65 |
+
self.qkv(x)
|
66 |
+
.reshape(B, N, 3, self.num_heads, self.head_dim)
|
67 |
+
.permute(2, 0, 3, 1, 4)
|
68 |
+
)
|
69 |
+
q, k, v = qkv.unbind(0)
|
70 |
+
|
71 |
+
x = F.scaled_dot_product_attention(q, k, v)
|
72 |
+
|
73 |
+
x = x.transpose(1, 2).reshape(B, N, C)
|
74 |
+
x = self.proj(x)
|
75 |
+
return x
|
76 |
+
|
77 |
+
|
78 |
+
class VitBlock(nn.Module):
|
79 |
+
|
80 |
+
def __init__(self, embed_dim, use_flash_attn=False):
|
81 |
+
super().__init__()
|
82 |
+
self.attn = Attention(embed_dim, use_flash_attn=use_flash_attn)
|
83 |
+
self.mlp = MLP(embed_dim, 4304)
|
84 |
+
self.norm1 = nn.LayerNorm(embed_dim)
|
85 |
+
self.norm2 = nn.LayerNorm(embed_dim)
|
86 |
+
|
87 |
+
def forward(self, x):
|
88 |
+
x = x + self.attn(self.norm1(x))
|
89 |
+
x = x + self.mlp(self.norm2(x))
|
90 |
+
return x
|
91 |
+
|
92 |
+
|
93 |
+
class VisionTransformer(nn.Module):
|
94 |
+
|
95 |
+
def __init__(self, use_flash_attn=False):
|
96 |
+
super().__init__()
|
97 |
+
|
98 |
+
embed_len = 729
|
99 |
+
embed_dim = 1152
|
100 |
+
|
101 |
+
self.patch_embed = LinearPatchEmbedding()
|
102 |
+
self.pos_embed = nn.Parameter(torch.randn(1, embed_len, embed_dim) * 0.02)
|
103 |
+
self.blocks = nn.Sequential(
|
104 |
+
*[VitBlock(embed_dim, use_flash_attn=use_flash_attn) for _ in range(27)]
|
105 |
+
)
|
106 |
+
self.norm = nn.LayerNorm(embed_dim)
|
107 |
+
|
108 |
+
def forward(self, x):
|
109 |
+
x = self.patch_embed(x)
|
110 |
+
x = x + self.pos_embed
|
111 |
+
for block in self.blocks:
|
112 |
+
x = block(x)
|
113 |
+
return self.norm(x)
|
114 |
+
|
115 |
+
|
116 |
+
class EncoderWrapper(nn.Module):
|
117 |
+
|
118 |
+
def __init__(self, use_flash_attn=False):
|
119 |
+
super().__init__()
|
120 |
+
self.model = nn.ModuleDict({"visual": VisionTransformer(use_flash_attn)})
|
121 |
+
|
122 |
+
def forward(self, x):
|
123 |
+
return self.model["visual"](x)
|
124 |
+
|
125 |
+
|
126 |
+
class LinearPatchEmbedding(nn.Module):
|
127 |
+
|
128 |
+
def __init__(self):
|
129 |
+
super().__init__()
|
130 |
+
self.linear = nn.Linear(588, 1152)
|
131 |
+
|
132 |
+
def forward(self, x):
|
133 |
+
b, c, hp1, wp2 = x.shape
|
134 |
+
p1, p2 = 14, 14
|
135 |
+
h, w = hp1 // p1, wp2 // p2
|
136 |
+
x = x.reshape(b, c, h, p1, w, p2)
|
137 |
+
x = x.permute(0, 2, 4, 1, 3, 5)
|
138 |
+
x = x.reshape(b, h * w, c * p1 * p2)
|
139 |
+
|
140 |
+
return self.linear(x)
|
141 |
+
|
142 |
+
|
143 |
+
class MLP(nn.Module):
|
144 |
+
def __init__(
|
145 |
+
self,
|
146 |
+
in_features: int,
|
147 |
+
hidden_features: int = None,
|
148 |
+
out_features: int = None,
|
149 |
+
) -> None:
|
150 |
+
super().__init__()
|
151 |
+
out_features = out_features or in_features
|
152 |
+
hidden_features = hidden_features or in_features
|
153 |
+
self.fc1 = nn.Linear(in_features, hidden_features)
|
154 |
+
self.act = nn.GELU(approximate="tanh")
|
155 |
+
self.fc2 = nn.Linear(hidden_features, out_features)
|
156 |
+
|
157 |
+
torch.nn.init.kaiming_normal_(
|
158 |
+
self.fc1.weight, mode="fan_in", nonlinearity="relu"
|
159 |
+
)
|
160 |
+
torch.nn.init.kaiming_normal_(
|
161 |
+
self.fc2.weight, mode="fan_in", nonlinearity="relu"
|
162 |
+
)
|
163 |
+
|
164 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
165 |
+
x = self.fc1(x)
|
166 |
+
x = self.act(x)
|
167 |
+
x = self.fc2(x)
|
168 |
+
return x
|
169 |
+
|
170 |
+
|
171 |
+
class VisionProjection(nn.Module):
|
172 |
+
def __init__(self):
|
173 |
+
super().__init__()
|
174 |
+
|
175 |
+
image_embedding_dim = 1152
|
176 |
+
model_dim = 2048
|
177 |
+
hidden_dim = model_dim * 4
|
178 |
+
|
179 |
+
self.mlp = MLP(image_embedding_dim * 2, hidden_dim, model_dim)
|
180 |
+
|
181 |
+
@property
|
182 |
+
def device(self):
|
183 |
+
return self.mlp.fc1.weight.device
|
184 |
+
|
185 |
+
def forward(self, x):
|
186 |
+
return self.mlp(x)
|
187 |
+
|
188 |
+
|
189 |
+
def create_patches(image, patch_size=(378, 378)):
|
190 |
+
assert image.dim() == 3, "Image must be in CHW format"
|
191 |
+
|
192 |
+
_, height, width = image.shape # Channels, Height, Width
|
193 |
+
patch_height, patch_width = patch_size
|
194 |
+
|
195 |
+
if height == patch_height and width == patch_width:
|
196 |
+
return []
|
197 |
+
|
198 |
+
# Iterate over the image and create patches
|
199 |
+
patches = []
|
200 |
+
for i in range(0, height, patch_height):
|
201 |
+
row_patches = []
|
202 |
+
for j in range(0, width, patch_width):
|
203 |
+
patch = image[:, i : i + patch_height, j : j + patch_width]
|
204 |
+
row_patches.append(patch)
|
205 |
+
patches.append(torch.stack(row_patches))
|
206 |
+
return patches
|
207 |
+
|
208 |
+
|
209 |
+
class VisionEncoder(nn.Module):
|
210 |
+
|
211 |
+
def __init__(self, use_flash_attn=False):
|
212 |
+
super().__init__()
|
213 |
+
|
214 |
+
self.encoder = EncoderWrapper(use_flash_attn)
|
215 |
+
self.projection = VisionProjection()
|
216 |
+
self.supported_sizes = [(378, 378), (378, 756), (756, 378), (756, 756)]
|
217 |
+
|
218 |
+
@property
|
219 |
+
def device(self):
|
220 |
+
return self.projection.mlp.fc1.weight.device
|
221 |
+
|
222 |
+
@property
|
223 |
+
def dtype(self):
|
224 |
+
return self.projection.mlp.fc1.weight.dtype
|
225 |
+
|
226 |
+
def preprocess(self, image: PIL.Image.Image):
|
227 |
+
width, height = image.size
|
228 |
+
max_dim = max(width, height)
|
229 |
+
if max_dim < 512:
|
230 |
+
im_size = (378, 378)
|
231 |
+
else:
|
232 |
+
aspect_ratio = width / height
|
233 |
+
im_size = min(
|
234 |
+
self.supported_sizes,
|
235 |
+
key=lambda size: (
|
236 |
+
abs((size[1] / size[0]) - aspect_ratio),
|
237 |
+
abs(size[0] - width) + abs(size[1] - height),
|
238 |
+
),
|
239 |
+
)
|
240 |
+
|
241 |
+
return Compose(
|
242 |
+
[
|
243 |
+
Resize(size=im_size, interpolation=InterpolationMode.BICUBIC),
|
244 |
+
ToImage(),
|
245 |
+
ToDtype(torch.float32, scale=True),
|
246 |
+
Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5]),
|
247 |
+
]
|
248 |
+
)(image)
|
249 |
+
|
250 |
+
def forward(
|
251 |
+
self, images: Union[PIL.Image.Image, list[PIL.Image.Image], torch.Tensor]
|
252 |
+
) -> torch.Tensor:
|
253 |
+
im_list = None
|
254 |
+
if isinstance(images, torch.Tensor):
|
255 |
+
# Input must have dimensions (B, C, H, W)
|
256 |
+
assert (
|
257 |
+
len(images.shape) == 4
|
258 |
+
), "Tensor input must have dimensions (B, C, H, W)"
|
259 |
+
im_list = list(images)
|
260 |
+
elif isinstance(images, PIL.Image.Image):
|
261 |
+
im_list = [images]
|
262 |
+
elif isinstance(images, list):
|
263 |
+
im_list = images
|
264 |
+
else:
|
265 |
+
raise ValueError(
|
266 |
+
"Input must be a PIL image, list of PIL images, or a tensor"
|
267 |
+
)
|
268 |
+
|
269 |
+
# Preprocess unless the images are already tensors (indicating that
|
270 |
+
# they have already been preprocessed)
|
271 |
+
if not isinstance(im_list[0], torch.Tensor):
|
272 |
+
im_list = [self.preprocess(im.convert("RGB")) for im in im_list]
|
273 |
+
|
274 |
+
patches = [create_patches(im) for im in im_list]
|
275 |
+
flat_patches = [patch for image_patches in patches for patch in image_patches]
|
276 |
+
|
277 |
+
# Images may be variable size, and need to be resized to a common size after
|
278 |
+
# creating patches.
|
279 |
+
resized_images = [
|
280 |
+
F.interpolate(im.unsqueeze(0), size=(378, 378), mode="bilinear")
|
281 |
+
for im in im_list
|
282 |
+
]
|
283 |
+
|
284 |
+
combined_images = torch.cat([*resized_images, *flat_patches], dim=0)
|
285 |
+
combined_images = combined_images.to(self.device, dtype=self.dtype)
|
286 |
+
|
287 |
+
combined_features = self.encoder(combined_images)
|
288 |
+
|
289 |
+
full_img_features = combined_features[: len(im_list)]
|
290 |
+
patch_features = (
|
291 |
+
combined_features[len(im_list) :].transpose(1, 2).view(-1, 1152, 27, 27)
|
292 |
+
)
|
293 |
+
|
294 |
+
# Reshape patch features back to their original structure
|
295 |
+
reshaped_patch_features = []
|
296 |
+
patch_idx = 0
|
297 |
+
for i, patch_set in enumerate(patches):
|
298 |
+
if len(patch_set) == 0:
|
299 |
+
reshaped_patch_features.append(
|
300 |
+
full_img_features[i].transpose(0, 1).view(1152, 27, 27)
|
301 |
+
)
|
302 |
+
else:
|
303 |
+
sample_features = []
|
304 |
+
for row_patches in patch_set:
|
305 |
+
row_len = len(row_patches)
|
306 |
+
row_features = patch_features[
|
307 |
+
patch_idx : patch_idx + row_len
|
308 |
+
] # row_len, T, C
|
309 |
+
row_features = torch.cat(
|
310 |
+
list(row_features), dim=2
|
311 |
+
) # T, C * row_len
|
312 |
+
patch_idx += row_len
|
313 |
+
sample_features.append(row_features)
|
314 |
+
sample_features = torch.cat(sample_features, dim=1)
|
315 |
+
sample_features = F.interpolate(
|
316 |
+
sample_features.unsqueeze(0), size=(27, 27), mode="bilinear"
|
317 |
+
).squeeze(0)
|
318 |
+
reshaped_patch_features.append(sample_features)
|
319 |
+
reshaped_patch_features = (
|
320 |
+
torch.stack(reshaped_patch_features).view(-1, 1152, 729).transpose(1, 2)
|
321 |
+
)
|
322 |
+
|
323 |
+
final_features = torch.cat([full_img_features, reshaped_patch_features], dim=2)
|
324 |
+
|
325 |
+
return self.projection(final_features)
|
vocab.json
ADDED
The diff for this file is too large to render.
See raw diff
|
|