EthanReid
commited on
Commit
·
1c87faa
1
Parent(s):
e3e72bc
Initial import of code and 4-bit weights
Browse files- .gitattributes +1 -0
- README.md +79 -0
- added_tokens.json +40 -0
- config.json +13 -0
- config.py +87 -0
- configuration_moondream.py +96 -0
- fourier_features.py +18 -0
- generation_config.json +4 -0
- handler.py +58 -0
- hf_moondream.py +142 -0
- image_crops.py +208 -0
- layers.py +123 -0
- merges.txt +0 -0
- model.safetensors +3 -0
- modeling_phi.py +1463 -0
- moondream.py +723 -0
- moondream2-mmproj-f16.gguf +3 -0
- moondream2-text-model-f16.gguf +3 -0
- region.py +89 -0
- region_model.py +43 -0
- requirements.txt +3 -0
- rope.py +48 -0
- special_tokens_map.json +5 -0
- text.py +155 -0
- tokenizer.json +0 -0
- tokenizer_config.json +323 -0
- utils.py +41 -0
- versions.txt +11 -0
- vision.py +147 -0
- vision_encoder.py +325 -0
- vocab.json +0 -0
- weights.py +249 -0
.gitattributes
CHANGED
@@ -33,3 +33,4 @@ 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 |
+
*.gguf filter=lfs diff=lfs merge=lfs -text
|
README.md
ADDED
@@ -0,0 +1,79 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
---
|
2 |
+
license: apache-2.0
|
3 |
+
pipeline_tag: image-text-to-text
|
4 |
+
---
|
5 |
+
|
6 |
+
Moondream is a small vision language model designed to run efficiently everywhere.
|
7 |
+
|
8 |
+
[Website](https://moondream.ai/) / [Demo](https://moondream.ai/playground) / [GitHub](https://github.com/vikhyat/moondream)
|
9 |
+
|
10 |
+
This repository contains the latest (2025-05-30) **int4**gitrelease of Moondream, as well as [historical releases](https://huggingface.co/vikhyatk/moondream2/blob/main/versions.txt). The model is updated frequently, so we recommend specifying a revision as shown below if you're using it in a production application.
|
11 |
+
|
12 |
+
Make sure to install the requirements:
|
13 |
+
```
|
14 |
+
pip install -r https://depot.moondream.ai/transformers/requirements.txt
|
15 |
+
```
|
16 |
+
|
17 |
+
### Usage
|
18 |
+
|
19 |
+
```python
|
20 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
21 |
+
from PIL import Image
|
22 |
+
|
23 |
+
model = AutoModelForCausalLM.from_pretrained(
|
24 |
+
"moondream/moondream-2b-2025-04-14-4bit",
|
25 |
+
trust_remote_code=True,
|
26 |
+
# Uncomment to run on GPU.
|
27 |
+
# device_map={"": "cuda"}
|
28 |
+
)
|
29 |
+
|
30 |
+
# Captioning
|
31 |
+
print("Short caption:")
|
32 |
+
print(model.caption(image, length="short")["caption"])
|
33 |
+
|
34 |
+
print("\nNormal caption:")
|
35 |
+
for t in model.caption(image, length="normal", stream=True)["caption"]:
|
36 |
+
# Streaming generation example, supported for caption() and detect()
|
37 |
+
print(t, end="", flush=True)
|
38 |
+
print(model.caption(image, length="normal"))
|
39 |
+
|
40 |
+
# Visual Querying
|
41 |
+
print("\nVisual query: 'How many people are in the image?'")
|
42 |
+
print(model.query(image, "How many people are in the image?")["answer"])
|
43 |
+
|
44 |
+
# Object Detection
|
45 |
+
print("\nObject detection: 'face'")
|
46 |
+
objects = model.detect(image, "face")["objects"]
|
47 |
+
print(f"Found {len(objects)} face(s)")
|
48 |
+
|
49 |
+
# Pointing
|
50 |
+
print("\nPointing: 'person'")
|
51 |
+
points = model.point(image, "person")["points"]
|
52 |
+
print(f"Found {len(points)} person(s)")
|
53 |
+
```
|
54 |
+
|
55 |
+
### Changelog
|
56 |
+
**int4-2025-04-15** ([full release notes](https://moondream.ai/blog/moondream-2025-04-14-release))
|
57 |
+
1. Moondream uses a whole lot less memory (4.12 down to 2.47GB)
|
58 |
+
2. Small device get a big speed up (44.54 to 67.84 tok/sec on a RTX 4050 Mobile)
|
59 |
+
3. Improved spatial understanding (RealWorldQA up from 58.3 to 60.13)
|
60 |
+
|
61 |
+
|
62 |
+
**2025-04-15** ([full release notes](https://moondream.ai/blog/moondream-2025-04-14-release))
|
63 |
+
|
64 |
+
1. Improved chart understanding (ChartQA up from 74.8 to 77.5, 82.2 with PoT)
|
65 |
+
2. Added temperature and nucleus sampling to reduce repetitive outputs
|
66 |
+
3. Better OCR for documents and tables (prompt with “Transcribe the text” or “Transcribe the text in natural reading order”)
|
67 |
+
4. Object detection supports document layout detection (figure, formula, text, etc)
|
68 |
+
5. UI understanding (ScreenSpot F1\@0.5 up from 53.3 to 60.3)
|
69 |
+
6. Improved text understanding (DocVQA up from 76.5 to 79.3, TextVQA up from 74.6 to 76.3)
|
70 |
+
|
71 |
+
**2025-03-27** ([full release notes](https://moondream.ai/blog/moondream-2025-03-27-release))
|
72 |
+
|
73 |
+
1. Added support for long-form captioning
|
74 |
+
2. Open vocabulary image tagging
|
75 |
+
3. Improved counting accuracy (e.g. CountBenchQA increased from 80 to 86.4)
|
76 |
+
4. Improved text understanding (e.g. OCRBench increased from 58.3 to 61.2)
|
77 |
+
5. Improved object detection, especially for small objects (e.g. COCO up from 30.5 to 51.2)
|
78 |
+
6. Fixed token streaming bug affecting multi-byte unicode characters
|
79 |
+
7. gpt-fast style `compile()` now supported in HF Transformers implementation
|
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,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"architectures": [
|
3 |
+
"HfMoondream"
|
4 |
+
],
|
5 |
+
"auto_map": {
|
6 |
+
"AutoConfig": "hf_moondream.HfConfig",
|
7 |
+
"AutoModelForCausalLM": "hf_moondream.HfMoondream"
|
8 |
+
},
|
9 |
+
"config": {},
|
10 |
+
"model_type": "moondream1",
|
11 |
+
"torch_dtype": "float16",
|
12 |
+
"transformers_version": "4.44.0"
|
13 |
+
}
|
config.py
ADDED
@@ -0,0 +1,87 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from dataclasses import dataclass, field
|
2 |
+
from typing import Dict, List, Optional
|
3 |
+
|
4 |
+
|
5 |
+
@dataclass(frozen=True)
|
6 |
+
class TextConfig:
|
7 |
+
dim: int = 2048
|
8 |
+
ff_dim: int = 8192
|
9 |
+
n_layers: int = 24
|
10 |
+
vocab_size: int = 51200
|
11 |
+
max_context: int = 2048
|
12 |
+
n_heads: int = 32
|
13 |
+
n_kv_heads: int = 32
|
14 |
+
prefix_attn: int = 730
|
15 |
+
group_size: int = 128
|
16 |
+
|
17 |
+
|
18 |
+
@dataclass(frozen=True)
|
19 |
+
class VisionConfig:
|
20 |
+
enc_dim: int = 1152
|
21 |
+
enc_patch_size: int = 14
|
22 |
+
enc_n_layers: int = 27
|
23 |
+
enc_ff_dim: int = 4304
|
24 |
+
enc_n_heads: int = 16
|
25 |
+
proj_out_dim: int = 2048
|
26 |
+
crop_size: int = 378
|
27 |
+
in_channels: int = 3
|
28 |
+
max_crops: int = 12
|
29 |
+
overlap_margin: int = 4
|
30 |
+
proj_inner_dim: int = 8192
|
31 |
+
|
32 |
+
|
33 |
+
@dataclass(frozen=True)
|
34 |
+
class RegionConfig:
|
35 |
+
dim: int = 2048
|
36 |
+
coord_feat_dim: int = 256
|
37 |
+
coord_out_dim: int = 1024
|
38 |
+
size_feat_dim: int = 512
|
39 |
+
size_out_dim: int = 2048
|
40 |
+
inner_dim: int = 8192
|
41 |
+
|
42 |
+
|
43 |
+
@dataclass(frozen=True)
|
44 |
+
class TokenizerConfig:
|
45 |
+
bos_id: int = 50256
|
46 |
+
eos_id: int = 50256
|
47 |
+
templates: Dict[str, Optional[Dict[str, List[int]]]] = field(
|
48 |
+
default_factory=lambda: {
|
49 |
+
"caption": {
|
50 |
+
"short": [198, 198, 16438, 8305, 25],
|
51 |
+
"normal": [198, 198, 24334, 1159, 25],
|
52 |
+
"long": [198, 198, 14617, 8305, 25],
|
53 |
+
},
|
54 |
+
"query": {"prefix": [198, 198, 24361, 25], "suffix": [198, 198, 33706, 25]},
|
55 |
+
"detect": {"prefix": [198, 198, 47504, 25], "suffix": [628]},
|
56 |
+
"point": {"prefix": [198, 198, 12727, 25], "suffix": [628]},
|
57 |
+
}
|
58 |
+
)
|
59 |
+
|
60 |
+
|
61 |
+
@dataclass(frozen=True)
|
62 |
+
class MoondreamConfig:
|
63 |
+
text: TextConfig = TextConfig()
|
64 |
+
vision: VisionConfig = VisionConfig()
|
65 |
+
region: RegionConfig = RegionConfig()
|
66 |
+
tokenizer: TokenizerConfig = TokenizerConfig()
|
67 |
+
|
68 |
+
@classmethod
|
69 |
+
def from_dict(cls, config_dict: dict):
|
70 |
+
text_config = TextConfig(**config_dict.get("text", {}))
|
71 |
+
vision_config = VisionConfig(**config_dict.get("vision", {}))
|
72 |
+
region_config = RegionConfig(**config_dict.get("region", {}))
|
73 |
+
tokenizer_config = TokenizerConfig(**config_dict.get("tokenizer", {}))
|
74 |
+
return cls(
|
75 |
+
text=text_config,
|
76 |
+
vision=vision_config,
|
77 |
+
region=region_config,
|
78 |
+
tokenizer=tokenizer_config,
|
79 |
+
)
|
80 |
+
|
81 |
+
def to_dict(self):
|
82 |
+
return {
|
83 |
+
"text": self.text.__dict__,
|
84 |
+
"vision": self.vision.__dict__,
|
85 |
+
"region": self.region.__dict__,
|
86 |
+
"tokenizer": self.tokenizer.__dict__,
|
87 |
+
}
|
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)
|
fourier_features.py
ADDED
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Adopted from https://github.com/crowsonkb/k-diffusion/blob/transformer-model-v2/k_diffusion/layers.py
|
2 |
+
|
3 |
+
import torch
|
4 |
+
import torch.nn as nn
|
5 |
+
import math
|
6 |
+
|
7 |
+
|
8 |
+
class FourierFeatures(nn.Module):
|
9 |
+
def __init__(self, in_features, out_features, std=1.0):
|
10 |
+
super().__init__()
|
11 |
+
assert out_features % 2 == 0
|
12 |
+
self.register_buffer(
|
13 |
+
"weight", torch.randn([out_features // 2, in_features]) * std
|
14 |
+
)
|
15 |
+
|
16 |
+
def forward(self, input):
|
17 |
+
f = 2 * math.pi * input @ self.weight.T
|
18 |
+
return torch.cat([f.cos(), f.sin()], dim=-1)
|
generation_config.json
ADDED
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"_from_model_config": true,
|
3 |
+
"transformers_version": "4.44.0"
|
4 |
+
}
|
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
|
hf_moondream.py
ADDED
@@ -0,0 +1,142 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from transformers import PreTrainedModel, PretrainedConfig
|
2 |
+
|
3 |
+
from .config import MoondreamConfig
|
4 |
+
from .moondream import MoondreamModel
|
5 |
+
|
6 |
+
# Files sometimes don't get loaded without these...
|
7 |
+
from .image_crops import *
|
8 |
+
from .vision import *
|
9 |
+
from .text import *
|
10 |
+
from .region import *
|
11 |
+
from .utils import *
|
12 |
+
|
13 |
+
|
14 |
+
def extract_question(text):
|
15 |
+
prefix = "<image>\n\nQuestion: "
|
16 |
+
suffix = "\n\nAnswer:"
|
17 |
+
|
18 |
+
if text.startswith(prefix) and text.endswith(suffix):
|
19 |
+
return text[len(prefix) : -len(suffix)]
|
20 |
+
else:
|
21 |
+
return None
|
22 |
+
|
23 |
+
|
24 |
+
class HfConfig(PretrainedConfig):
|
25 |
+
_auto_class = "AutoConfig"
|
26 |
+
model_type = "moondream1"
|
27 |
+
|
28 |
+
def __init__(self, **kwargs):
|
29 |
+
super().__init__(**kwargs)
|
30 |
+
self.config = {}
|
31 |
+
|
32 |
+
|
33 |
+
class HfMoondream(PreTrainedModel):
|
34 |
+
_auto_class = "AutoModelForCausalLM"
|
35 |
+
config_class = HfConfig
|
36 |
+
|
37 |
+
def __init__(self, config):
|
38 |
+
super().__init__(config)
|
39 |
+
self.model = MoondreamModel(
|
40 |
+
MoondreamConfig.from_dict(config.config), setup_caches=False
|
41 |
+
)
|
42 |
+
self._is_kv_cache_setup = False
|
43 |
+
|
44 |
+
def _setup_caches(self):
|
45 |
+
if not self._is_kv_cache_setup:
|
46 |
+
self.model._setup_caches()
|
47 |
+
self._is_kv_cache_setup = True
|
48 |
+
|
49 |
+
@property
|
50 |
+
def encode_image(self):
|
51 |
+
self._setup_caches()
|
52 |
+
return self.model.encode_image
|
53 |
+
|
54 |
+
@property
|
55 |
+
def query(self):
|
56 |
+
self._setup_caches()
|
57 |
+
return self.model.query
|
58 |
+
|
59 |
+
@property
|
60 |
+
def caption(self):
|
61 |
+
self._setup_caches()
|
62 |
+
return self.model.caption
|
63 |
+
|
64 |
+
@property
|
65 |
+
def detect(self):
|
66 |
+
self._setup_caches()
|
67 |
+
return self.model.detect
|
68 |
+
|
69 |
+
@property
|
70 |
+
def point(self):
|
71 |
+
self._setup_caches()
|
72 |
+
return self.model.point
|
73 |
+
|
74 |
+
@property
|
75 |
+
def detect_gaze(self):
|
76 |
+
self._setup_caches()
|
77 |
+
return self.model.detect_gaze
|
78 |
+
|
79 |
+
def answer_question(
|
80 |
+
self,
|
81 |
+
image_embeds,
|
82 |
+
question,
|
83 |
+
tokenizer=None,
|
84 |
+
chat_history="",
|
85 |
+
result_queue=None,
|
86 |
+
max_new_tokens=256,
|
87 |
+
**kwargs
|
88 |
+
):
|
89 |
+
answer = self.query(image_embeds, question)["answer"].strip()
|
90 |
+
|
91 |
+
if result_queue is not None:
|
92 |
+
result_queue.put(answer)
|
93 |
+
return answer
|
94 |
+
|
95 |
+
def batch_answer(self, images, prompts, tokenizer=None, **kwargs):
|
96 |
+
answers = []
|
97 |
+
for image, prompt in zip(images, prompts):
|
98 |
+
answers.append(self.query(image, prompt)["answer"].strip())
|
99 |
+
return answers
|
100 |
+
|
101 |
+
def _unsupported_exception(self):
|
102 |
+
raise NotImplementedError(
|
103 |
+
"This method is not supported in the latest version of moondream. "
|
104 |
+
"Consider upgrading to the updated API spec, or alternately pin "
|
105 |
+
"to 'revision=2024-08-26'."
|
106 |
+
)
|
107 |
+
|
108 |
+
def generate(self, image_embeds, prompt, tokenizer, max_new_tokens=128, **kwargs):
|
109 |
+
"""
|
110 |
+
Function definition remains unchanged for backwards compatibility.
|
111 |
+
Be aware that tokenizer, max_new_takens, and kwargs are ignored.
|
112 |
+
"""
|
113 |
+
prompt_extracted = extract_question(prompt)
|
114 |
+
if prompt_extracted is not None:
|
115 |
+
answer = self.model.query(
|
116 |
+
image=image_embeds, question=prompt_extracted, stream=False
|
117 |
+
)["answer"]
|
118 |
+
else:
|
119 |
+
image_embeds = self.encode_image(image_embeds)
|
120 |
+
prompt_tokens = torch.tensor(
|
121 |
+
[self.model.tokenizer.encode(prompt).ids],
|
122 |
+
device=self.device,
|
123 |
+
)
|
124 |
+
|
125 |
+
def generator():
|
126 |
+
for token in self.model._generate_text(
|
127 |
+
prompt_tokens,
|
128 |
+
image_embeds.kv_cache,
|
129 |
+
image_embeds.pos,
|
130 |
+
max_new_tokens,
|
131 |
+
):
|
132 |
+
yield token
|
133 |
+
|
134 |
+
answer = "".join(list(generator()))
|
135 |
+
|
136 |
+
return [answer]
|
137 |
+
|
138 |
+
def get_input_embeddings(self):
|
139 |
+
return super().get_input_embeddings()
|
140 |
+
|
141 |
+
def input_embeds(self, *args, **kwargs):
|
142 |
+
self._unsupported_exception()
|
image_crops.py
ADDED
@@ -0,0 +1,208 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import math
|
2 |
+
import numpy as np
|
3 |
+
import torch
|
4 |
+
import pyvips
|
5 |
+
|
6 |
+
from typing import TypedDict
|
7 |
+
|
8 |
+
|
9 |
+
def select_tiling(
|
10 |
+
height: int, width: int, crop_size: int, max_crops: int
|
11 |
+
) -> tuple[int, int]:
|
12 |
+
"""
|
13 |
+
Determine the optimal number of tiles to cover an image with overlapping crops.
|
14 |
+
"""
|
15 |
+
if height <= crop_size or width <= crop_size:
|
16 |
+
return (1, 1)
|
17 |
+
|
18 |
+
# Minimum required tiles in each dimension
|
19 |
+
min_h = math.ceil(height / crop_size)
|
20 |
+
min_w = math.ceil(width / crop_size)
|
21 |
+
|
22 |
+
# If minimum required tiles exceed max_crops, return proportional distribution
|
23 |
+
if min_h * min_w > max_crops:
|
24 |
+
ratio = math.sqrt(max_crops / (min_h * min_w))
|
25 |
+
return (max(1, math.floor(min_h * ratio)), max(1, math.floor(min_w * ratio)))
|
26 |
+
|
27 |
+
# Perfect aspect-ratio tiles that satisfy max_crops
|
28 |
+
h_tiles = math.floor(math.sqrt(max_crops * height / width))
|
29 |
+
w_tiles = math.floor(math.sqrt(max_crops * width / height))
|
30 |
+
|
31 |
+
# Ensure we meet minimum tile requirements
|
32 |
+
h_tiles = max(h_tiles, min_h)
|
33 |
+
w_tiles = max(w_tiles, min_w)
|
34 |
+
|
35 |
+
# If we exceeded max_crops, scale down the larger dimension
|
36 |
+
if h_tiles * w_tiles > max_crops:
|
37 |
+
if w_tiles > h_tiles:
|
38 |
+
w_tiles = math.floor(max_crops / h_tiles)
|
39 |
+
else:
|
40 |
+
h_tiles = math.floor(max_crops / w_tiles)
|
41 |
+
|
42 |
+
return (max(1, h_tiles), max(1, w_tiles))
|
43 |
+
|
44 |
+
|
45 |
+
class OverlapCropOutput(TypedDict):
|
46 |
+
crops: np.ndarray
|
47 |
+
tiling: tuple[int, int]
|
48 |
+
|
49 |
+
|
50 |
+
def overlap_crop_image(
|
51 |
+
image: np.ndarray,
|
52 |
+
overlap_margin: int,
|
53 |
+
max_crops: int,
|
54 |
+
base_size: tuple[int, int] = (378, 378),
|
55 |
+
patch_size: int = 14,
|
56 |
+
) -> OverlapCropOutput:
|
57 |
+
"""
|
58 |
+
Process an image using an overlap-and-resize cropping strategy with margin handling.
|
59 |
+
|
60 |
+
This function takes an input image and creates multiple overlapping crops with
|
61 |
+
consistent margins. It produces:
|
62 |
+
1. A single global crop resized to base_size
|
63 |
+
2. Multiple overlapping local crops that maintain high resolution details
|
64 |
+
3. A patch ordering matrix that tracks correspondence between crops
|
65 |
+
|
66 |
+
The overlap strategy ensures:
|
67 |
+
- Smooth transitions between adjacent crops
|
68 |
+
- No loss of information at crop boundaries
|
69 |
+
- Proper handling of features that cross crop boundaries
|
70 |
+
- Consistent patch indexing across the full image
|
71 |
+
|
72 |
+
Args:
|
73 |
+
image (np.ndarray): Input image as numpy array with shape (H,W,C)
|
74 |
+
base_size (tuple[int,int]): Target size for crops, default (378,378)
|
75 |
+
patch_size (int): Size of patches in pixels, default 14
|
76 |
+
overlap_margin (int): Margin size in patch units, default 4
|
77 |
+
max_crops (int): Maximum number of crops allowed, default 12
|
78 |
+
|
79 |
+
Returns:
|
80 |
+
OverlapCropOutput: Dictionary containing:
|
81 |
+
- crops: A numpy array containing the global crop of the full image (index 0)
|
82 |
+
followed by the overlapping cropped regions (indices 1+)
|
83 |
+
- tiling: Tuple of (height,width) tile counts
|
84 |
+
"""
|
85 |
+
original_h, original_w = image.shape[:2]
|
86 |
+
|
87 |
+
# Convert margin from patch units to pixels
|
88 |
+
margin_pixels = patch_size * overlap_margin
|
89 |
+
total_margin_pixels = margin_pixels * 2 # Both sides
|
90 |
+
|
91 |
+
# Calculate crop parameters
|
92 |
+
crop_patches = base_size[0] // patch_size # patches per crop dimension
|
93 |
+
crop_window_patches = crop_patches - (2 * overlap_margin) # usable patches
|
94 |
+
crop_window_size = crop_window_patches * patch_size # usable size in pixels
|
95 |
+
|
96 |
+
# Determine tiling
|
97 |
+
tiling = select_tiling(
|
98 |
+
original_h - total_margin_pixels,
|
99 |
+
original_w - total_margin_pixels,
|
100 |
+
crop_window_size,
|
101 |
+
max_crops,
|
102 |
+
)
|
103 |
+
|
104 |
+
# Pre-allocate crops.
|
105 |
+
n_crops = tiling[0] * tiling[1] + 1 # 1 = global crop
|
106 |
+
crops = np.zeros(
|
107 |
+
(n_crops, base_size[0], base_size[1], image.shape[2]), dtype=np.uint8
|
108 |
+
)
|
109 |
+
|
110 |
+
# Resize image to fit tiling
|
111 |
+
target_size = (
|
112 |
+
tiling[0] * crop_window_size + total_margin_pixels,
|
113 |
+
tiling[1] * crop_window_size + total_margin_pixels,
|
114 |
+
)
|
115 |
+
|
116 |
+
# Convert to vips for resizing
|
117 |
+
vips_image = pyvips.Image.new_from_array(image)
|
118 |
+
scale_x = target_size[1] / image.shape[1]
|
119 |
+
scale_y = target_size[0] / image.shape[0]
|
120 |
+
resized = vips_image.resize(scale_x, vscale=scale_y)
|
121 |
+
image = resized.numpy()
|
122 |
+
|
123 |
+
# Create global crop
|
124 |
+
scale_x = base_size[1] / vips_image.width
|
125 |
+
scale_y = base_size[0] / vips_image.height
|
126 |
+
global_vips = vips_image.resize(scale_x, vscale=scale_y)
|
127 |
+
crops[0] = global_vips.numpy()
|
128 |
+
|
129 |
+
for i in range(tiling[0]):
|
130 |
+
for j in range(tiling[1]):
|
131 |
+
# Calculate crop coordinates
|
132 |
+
y0 = i * crop_window_size
|
133 |
+
x0 = j * crop_window_size
|
134 |
+
|
135 |
+
# Extract crop with padding if needed
|
136 |
+
y_end = min(y0 + base_size[0], image.shape[0])
|
137 |
+
x_end = min(x0 + base_size[1], image.shape[1])
|
138 |
+
|
139 |
+
crop_region = image[y0:y_end, x0:x_end]
|
140 |
+
crops[
|
141 |
+
1 + i * tiling[1] + j, : crop_region.shape[0], : crop_region.shape[1]
|
142 |
+
] = crop_region
|
143 |
+
|
144 |
+
return {"crops": crops, "tiling": tiling}
|
145 |
+
|
146 |
+
|
147 |
+
def reconstruct_from_crops(
|
148 |
+
crops: torch.Tensor,
|
149 |
+
tiling: tuple[int, int],
|
150 |
+
overlap_margin: int,
|
151 |
+
patch_size: int = 14,
|
152 |
+
) -> torch.Tensor:
|
153 |
+
"""
|
154 |
+
Reconstruct the original image from overlapping crops into a single seamless image.
|
155 |
+
|
156 |
+
Takes a list of overlapping image crops along with their positional metadata and
|
157 |
+
reconstructs them into a single coherent image by carefully stitching together
|
158 |
+
non-overlapping regions. Handles both numpy arrays and PyTorch tensors.
|
159 |
+
|
160 |
+
Args:
|
161 |
+
crops: List of image crops as numpy arrays or PyTorch tensors with shape
|
162 |
+
(H,W,C)
|
163 |
+
tiling: Tuple of (height,width) indicating crop grid layout
|
164 |
+
patch_size: Size in pixels of each patch, default 14
|
165 |
+
overlap_margin: Number of overlapping patches on each edge, default 4
|
166 |
+
|
167 |
+
Returns:
|
168 |
+
Reconstructed image as numpy array or PyTorch tensor matching input type,
|
169 |
+
with shape (H,W,C) where H,W are the original image dimensions
|
170 |
+
"""
|
171 |
+
tiling_h, tiling_w = tiling
|
172 |
+
crop_height, crop_width = crops[0].shape[:2]
|
173 |
+
margin_pixels = overlap_margin * patch_size
|
174 |
+
|
175 |
+
# Calculate output size (only adding margins once)
|
176 |
+
output_h = (crop_height - 2 * margin_pixels) * tiling_h + 2 * margin_pixels
|
177 |
+
output_w = (crop_width - 2 * margin_pixels) * tiling_w + 2 * margin_pixels
|
178 |
+
|
179 |
+
reconstructed = torch.zeros(
|
180 |
+
(output_h, output_w, crops[0].shape[2]),
|
181 |
+
device=crops[0].device,
|
182 |
+
dtype=crops[0].dtype,
|
183 |
+
)
|
184 |
+
|
185 |
+
for i, crop in enumerate(crops):
|
186 |
+
tile_y = i // tiling_w
|
187 |
+
tile_x = i % tiling_w
|
188 |
+
|
189 |
+
# For each tile, determine which part to keep
|
190 |
+
# Keep left margin only for first column
|
191 |
+
x_start = 0 if tile_x == 0 else margin_pixels
|
192 |
+
# Keep right margin only for last column
|
193 |
+
x_end = crop_width if tile_x == tiling_w - 1 else crop_width - margin_pixels
|
194 |
+
# Keep top margin only for first row
|
195 |
+
y_start = 0 if tile_y == 0 else margin_pixels
|
196 |
+
# Keep bottom margin only for last row
|
197 |
+
y_end = crop_height if tile_y == tiling_h - 1 else crop_height - margin_pixels
|
198 |
+
|
199 |
+
# Calculate where this piece belongs in the output
|
200 |
+
out_x = tile_x * (crop_width - 2 * margin_pixels)
|
201 |
+
out_y = tile_y * (crop_height - 2 * margin_pixels)
|
202 |
+
|
203 |
+
# Place the piece
|
204 |
+
reconstructed[
|
205 |
+
out_y + y_start : out_y + y_end, out_x + x_start : out_x + x_end
|
206 |
+
] = crop[y_start:y_end, x_start:x_end]
|
207 |
+
|
208 |
+
return reconstructed
|
layers.py
ADDED
@@ -0,0 +1,123 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import bitblas
|
2 |
+
import torch
|
3 |
+
import torch.nn as nn
|
4 |
+
|
5 |
+
from dataclasses import dataclass
|
6 |
+
from typing import Literal
|
7 |
+
from bitblas.cache import OperatorCache
|
8 |
+
from torch.nn import functional as F
|
9 |
+
|
10 |
+
|
11 |
+
def gelu_approx(x):
|
12 |
+
return F.gelu(x, approximate="tanh")
|
13 |
+
|
14 |
+
|
15 |
+
@dataclass
|
16 |
+
class LinearWeights:
|
17 |
+
weight: torch.Tensor
|
18 |
+
bias: torch.Tensor
|
19 |
+
|
20 |
+
|
21 |
+
class Linear(nn.Module):
|
22 |
+
"""
|
23 |
+
Linear layer with support for bitblas quantization.
|
24 |
+
If dtype is torch.int8, it uses bitblas for quantization.
|
25 |
+
Otherwise, it uses a standard nn.Linear layer.
|
26 |
+
"""
|
27 |
+
|
28 |
+
def __init__(
|
29 |
+
self,
|
30 |
+
in_features: int,
|
31 |
+
out_features: int,
|
32 |
+
bias: bool = True,
|
33 |
+
dtype: torch.dtype = None,
|
34 |
+
group_size: int = 128,
|
35 |
+
):
|
36 |
+
super().__init__()
|
37 |
+
|
38 |
+
if dtype == torch.int8:
|
39 |
+
self.linear = bitblas.Linear(
|
40 |
+
in_features=in_features,
|
41 |
+
out_features=out_features,
|
42 |
+
bias=bias,
|
43 |
+
with_zeros=True,
|
44 |
+
zeros_mode="original",
|
45 |
+
with_scaling=True,
|
46 |
+
A_dtype="float16",
|
47 |
+
W_dtype="uint4",
|
48 |
+
accum_dtype="float16",
|
49 |
+
out_dtype="float16",
|
50 |
+
fast_decoding=True,
|
51 |
+
enable_tuning=True,
|
52 |
+
group_size=group_size,
|
53 |
+
)
|
54 |
+
else:
|
55 |
+
self.linear = nn.Linear(
|
56 |
+
in_features=in_features,
|
57 |
+
out_features=out_features,
|
58 |
+
bias=bias,
|
59 |
+
dtype=torch.float16,
|
60 |
+
)
|
61 |
+
|
62 |
+
def forward(self, x):
|
63 |
+
return self.linear(x)
|
64 |
+
|
65 |
+
@property
|
66 |
+
def weight(self) -> torch.Tensor:
|
67 |
+
try:
|
68 |
+
return self.linear.weight
|
69 |
+
except AttributeError:
|
70 |
+
return self.linear.qweight
|
71 |
+
|
72 |
+
@property
|
73 |
+
def bias(self) -> torch.Tensor:
|
74 |
+
return self.linear.bias
|
75 |
+
|
76 |
+
|
77 |
+
def linear(x: torch.Tensor, w: LinearWeights) -> torch.Tensor:
|
78 |
+
return F.linear(x, w.weight, w.bias)
|
79 |
+
|
80 |
+
|
81 |
+
@dataclass
|
82 |
+
class LayerNormWeights:
|
83 |
+
weight: torch.Tensor
|
84 |
+
bias: torch.Tensor
|
85 |
+
|
86 |
+
|
87 |
+
def layer_norm(x: torch.Tensor, w: LayerNormWeights) -> torch.Tensor:
|
88 |
+
return F.layer_norm(x, w.bias.shape, w.weight, w.bias)
|
89 |
+
|
90 |
+
|
91 |
+
@dataclass
|
92 |
+
class MLPWeights:
|
93 |
+
fc1: LinearWeights
|
94 |
+
fc2: LinearWeights
|
95 |
+
act: Literal["gelu_approx"] = "gelu_approx"
|
96 |
+
|
97 |
+
|
98 |
+
def mlp(x: torch.Tensor, w: MLPWeights) -> torch.Tensor:
|
99 |
+
|
100 |
+
x = w.fc1(x)
|
101 |
+
x = gelu_approx(x)
|
102 |
+
x = w.fc2(x)
|
103 |
+
return x
|
104 |
+
|
105 |
+
|
106 |
+
@dataclass
|
107 |
+
class AttentionWeights:
|
108 |
+
qkv: LinearWeights
|
109 |
+
proj: LinearWeights
|
110 |
+
|
111 |
+
|
112 |
+
def attn(x: torch.Tensor, w: AttentionWeights, n_heads: int) -> torch.Tensor:
|
113 |
+
bsz, q_len, d_model = x.shape
|
114 |
+
head_dim = d_model // n_heads
|
115 |
+
|
116 |
+
q, k, v = [
|
117 |
+
t.view(bsz, q_len, n_heads, head_dim).transpose(1, 2)
|
118 |
+
for t in linear(x, w.qkv).chunk(3, dim=-1)
|
119 |
+
]
|
120 |
+
out = F.scaled_dot_product_attention(q, k, v)
|
121 |
+
out = out.transpose(1, 2).reshape(bsz, q_len, d_model)
|
122 |
+
out = linear(out, w.proj)
|
123 |
+
return out
|
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:73e9da0d1091d61630477994669a22011c830c7539e27e659fb63a4d6818f8a2
|
3 |
+
size 2080370912
|
modeling_phi.py
ADDED
@@ -0,0 +1,1463 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# coding=utf-8
|
2 |
+
# Copyright 2023 Microsoft and the HuggingFace Inc. team. All rights reserved.
|
3 |
+
#
|
4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
5 |
+
# you may not use this file except in compliance with the License.
|
6 |
+
# You may obtain a copy of the License at
|
7 |
+
#
|
8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
9 |
+
#
|
10 |
+
# Unless required by applicable law or agreed to in writing, software
|
11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
13 |
+
# See the License for the specific language governing permissions and
|
14 |
+
# limitations under the License.
|
15 |
+
|
16 |
+
"""PyTorch Phi model."""
|
17 |
+
|
18 |
+
import math
|
19 |
+
from typing import List, Optional, Tuple, Union
|
20 |
+
|
21 |
+
import torch
|
22 |
+
import torch.utils.checkpoint
|
23 |
+
from packaging import version
|
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, StaticCache
|
29 |
+
from transformers.modeling_attn_mask_utils import AttentionMaskConverter
|
30 |
+
from transformers.modeling_outputs import (
|
31 |
+
BaseModelOutputWithPast,
|
32 |
+
CausalLMOutputWithPast,
|
33 |
+
)
|
34 |
+
from transformers.modeling_utils import PreTrainedModel
|
35 |
+
from transformers.utils import (
|
36 |
+
add_start_docstrings,
|
37 |
+
add_start_docstrings_to_model_forward,
|
38 |
+
get_torch_version,
|
39 |
+
is_flash_attn_2_available,
|
40 |
+
is_flash_attn_greater_or_equal_2_10,
|
41 |
+
is_torchdynamo_compiling,
|
42 |
+
logging,
|
43 |
+
replace_return_docstrings,
|
44 |
+
)
|
45 |
+
from .configuration_moondream import PhiConfig
|
46 |
+
|
47 |
+
|
48 |
+
if is_flash_attn_2_available():
|
49 |
+
from transformers.modeling_flash_attention_utils import _flash_attention_forward
|
50 |
+
|
51 |
+
|
52 |
+
logger = logging.get_logger(__name__)
|
53 |
+
|
54 |
+
_CONFIG_FOR_DOC = "PhiConfig"
|
55 |
+
|
56 |
+
|
57 |
+
# Copied from transformers.models.llama.modeling_llama._prepare_4d_causal_attention_mask_with_cache_position
|
58 |
+
def _prepare_4d_causal_attention_mask_with_cache_position(
|
59 |
+
attention_mask: torch.Tensor,
|
60 |
+
sequence_length: int,
|
61 |
+
target_length: int,
|
62 |
+
dtype: torch.dtype,
|
63 |
+
device: torch.device,
|
64 |
+
min_dtype: float,
|
65 |
+
cache_position: torch.Tensor,
|
66 |
+
batch_size: int,
|
67 |
+
):
|
68 |
+
"""
|
69 |
+
Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
|
70 |
+
`(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.
|
71 |
+
|
72 |
+
Args:
|
73 |
+
attention_mask (`torch.Tensor`):
|
74 |
+
A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape `(batch_size, 1, query_length, key_value_length)`.
|
75 |
+
sequence_length (`int`):
|
76 |
+
The sequence length being processed.
|
77 |
+
target_length (`int`):
|
78 |
+
The target length: when generating with static cache, the mask should be as long as the static cache, to account for the 0 padding, the part of the cache that is not filled yet.
|
79 |
+
dtype (`torch.dtype`):
|
80 |
+
The dtype to use for the 4D attention mask.
|
81 |
+
device (`torch.device`):
|
82 |
+
The device to plcae the 4D attention mask on.
|
83 |
+
min_dtype (`float`):
|
84 |
+
The minimum value representable with the dtype `dtype`.
|
85 |
+
cache_position (`torch.Tensor`):
|
86 |
+
Indices depicting the position of the input sequence tokens in the sequence.
|
87 |
+
batch_size (`torch.Tensor`):
|
88 |
+
Batch size.
|
89 |
+
"""
|
90 |
+
if attention_mask is not None and attention_mask.dim() == 4:
|
91 |
+
# In this case we assume that the mask comes already in inverted form and requires no inversion or slicing.
|
92 |
+
causal_mask = attention_mask
|
93 |
+
else:
|
94 |
+
causal_mask = torch.full(
|
95 |
+
(sequence_length, target_length),
|
96 |
+
fill_value=min_dtype,
|
97 |
+
dtype=dtype,
|
98 |
+
device=device,
|
99 |
+
)
|
100 |
+
if sequence_length != 1:
|
101 |
+
causal_mask = torch.triu(causal_mask, diagonal=1)
|
102 |
+
causal_mask *= torch.arange(
|
103 |
+
target_length, device=device
|
104 |
+
) > cache_position.reshape(-1, 1)
|
105 |
+
causal_mask = causal_mask[None, None, :, :].expand(batch_size, 1, -1, -1)
|
106 |
+
if attention_mask is not None:
|
107 |
+
causal_mask = (
|
108 |
+
causal_mask.clone()
|
109 |
+
) # copy to contiguous memory for in-place edit
|
110 |
+
mask_length = attention_mask.shape[-1]
|
111 |
+
padding_mask = (
|
112 |
+
causal_mask[:, :, :, :mask_length] + attention_mask[:, None, None, :]
|
113 |
+
)
|
114 |
+
padding_mask = padding_mask == 0
|
115 |
+
causal_mask[:, :, :, :mask_length] = causal_mask[
|
116 |
+
:, :, :, :mask_length
|
117 |
+
].masked_fill(padding_mask, min_dtype)
|
118 |
+
|
119 |
+
return causal_mask
|
120 |
+
|
121 |
+
|
122 |
+
# Copied from transformers.models.mixtral.modeling_mixtral.MixtralRotaryEmbedding with Mixtral->Phi
|
123 |
+
class PhiRotaryEmbedding(nn.Module):
|
124 |
+
def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
|
125 |
+
super().__init__()
|
126 |
+
|
127 |
+
self.dim = dim
|
128 |
+
self.max_position_embeddings = max_position_embeddings
|
129 |
+
self.base = base
|
130 |
+
inv_freq = 1.0 / (
|
131 |
+
self.base
|
132 |
+
** (
|
133 |
+
torch.arange(0, self.dim, 2, dtype=torch.int64).float().to(device)
|
134 |
+
/ self.dim
|
135 |
+
)
|
136 |
+
)
|
137 |
+
self.register_buffer("inv_freq", inv_freq, persistent=False)
|
138 |
+
|
139 |
+
# Build here to make `torch.jit.trace` work.
|
140 |
+
self._set_cos_sin_cache(
|
141 |
+
seq_len=max_position_embeddings,
|
142 |
+
device=self.inv_freq.device,
|
143 |
+
dtype=torch.get_default_dtype(),
|
144 |
+
)
|
145 |
+
|
146 |
+
def _set_cos_sin_cache(self, seq_len, device, dtype):
|
147 |
+
self.max_seq_len_cached = seq_len
|
148 |
+
t = torch.arange(
|
149 |
+
self.max_seq_len_cached, device=device, dtype=torch.int64
|
150 |
+
).type_as(self.inv_freq)
|
151 |
+
|
152 |
+
freqs = torch.outer(t, self.inv_freq)
|
153 |
+
# Different from paper, but it uses a different permutation in order to obtain the same calculation
|
154 |
+
emb = torch.cat((freqs, freqs), dim=-1)
|
155 |
+
self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
|
156 |
+
self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
|
157 |
+
|
158 |
+
def forward(self, x, seq_len=None):
|
159 |
+
# x: [bs, num_attention_heads, seq_len, head_size]
|
160 |
+
if seq_len > self.max_seq_len_cached:
|
161 |
+
self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)
|
162 |
+
|
163 |
+
return (
|
164 |
+
self.cos_cached[:seq_len].to(dtype=x.dtype),
|
165 |
+
self.sin_cached[:seq_len].to(dtype=x.dtype),
|
166 |
+
)
|
167 |
+
|
168 |
+
|
169 |
+
# Copied from transformers.models.falcon.modeling_falcon.FalconLinearScalingRotaryEmbedding with Falcon->Phi
|
170 |
+
class PhiLinearScalingRotaryEmbedding(PhiRotaryEmbedding):
|
171 |
+
"""PhiRotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendev"""
|
172 |
+
|
173 |
+
def __init__(
|
174 |
+
self,
|
175 |
+
dim,
|
176 |
+
max_position_embeddings=2048,
|
177 |
+
base=10000,
|
178 |
+
device=None,
|
179 |
+
scaling_factor=1.0,
|
180 |
+
):
|
181 |
+
self.scaling_factor = scaling_factor
|
182 |
+
super().__init__(dim, max_position_embeddings, base, device)
|
183 |
+
|
184 |
+
def _set_cos_sin_cache(self, seq_len, device, dtype):
|
185 |
+
self.max_seq_len_cached = seq_len
|
186 |
+
t = torch.arange(
|
187 |
+
self.max_seq_len_cached, device=device, dtype=torch.int64
|
188 |
+
).type_as(self.inv_freq)
|
189 |
+
t = t / self.scaling_factor
|
190 |
+
|
191 |
+
freqs = torch.outer(t, self.inv_freq)
|
192 |
+
# Different from paper, but it uses a different permutation in order to obtain the same calculation
|
193 |
+
emb = torch.cat((freqs, freqs), dim=-1)
|
194 |
+
self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
|
195 |
+
self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
|
196 |
+
|
197 |
+
|
198 |
+
# Copied from transformers.models.falcon.modeling_falcon.FalconDynamicNTKScalingRotaryEmbedding with Falcon->Phi
|
199 |
+
class PhiDynamicNTKScalingRotaryEmbedding(PhiRotaryEmbedding):
|
200 |
+
"""PhiRotaryEmbedding extended with Dynamic NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozilla"""
|
201 |
+
|
202 |
+
def __init__(
|
203 |
+
self,
|
204 |
+
dim,
|
205 |
+
max_position_embeddings=2048,
|
206 |
+
base=10000,
|
207 |
+
device=None,
|
208 |
+
scaling_factor=1.0,
|
209 |
+
):
|
210 |
+
self.scaling_factor = scaling_factor
|
211 |
+
super().__init__(dim, max_position_embeddings, base, device)
|
212 |
+
|
213 |
+
def _set_cos_sin_cache(self, seq_len, device, dtype):
|
214 |
+
self.max_seq_len_cached = seq_len
|
215 |
+
|
216 |
+
if seq_len > self.max_position_embeddings:
|
217 |
+
base = self.base * (
|
218 |
+
(self.scaling_factor * seq_len / self.max_position_embeddings)
|
219 |
+
- (self.scaling_factor - 1)
|
220 |
+
) ** (self.dim / (self.dim - 2))
|
221 |
+
inv_freq = 1.0 / (
|
222 |
+
base
|
223 |
+
** (
|
224 |
+
torch.arange(0, self.dim, 2, dtype=torch.int64).float().to(device)
|
225 |
+
/ self.dim
|
226 |
+
)
|
227 |
+
)
|
228 |
+
self.register_buffer("inv_freq", inv_freq, persistent=False)
|
229 |
+
|
230 |
+
t = torch.arange(
|
231 |
+
self.max_seq_len_cached, device=device, dtype=torch.int64
|
232 |
+
).type_as(self.inv_freq)
|
233 |
+
|
234 |
+
freqs = torch.outer(t, self.inv_freq)
|
235 |
+
# Different from paper, but it uses a different permutation in order to obtain the same calculation
|
236 |
+
emb = torch.cat((freqs, freqs), dim=-1)
|
237 |
+
self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
|
238 |
+
self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
|
239 |
+
|
240 |
+
|
241 |
+
# Copied from transformers.models.llama.modeling_llama.rotate_half
|
242 |
+
def rotate_half(x):
|
243 |
+
"""Rotates half the hidden dims of the input."""
|
244 |
+
x1 = x[..., : x.shape[-1] // 2]
|
245 |
+
x2 = x[..., x.shape[-1] // 2 :]
|
246 |
+
return torch.cat((-x2, x1), dim=-1)
|
247 |
+
|
248 |
+
|
249 |
+
# Copied from transformers.models.mixtral.modeling_mixtral.apply_rotary_pos_emb
|
250 |
+
def apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1):
|
251 |
+
"""Applies Rotary Position Embedding to the query and key tensors.
|
252 |
+
|
253 |
+
Args:
|
254 |
+
q (`torch.Tensor`): The query tensor.
|
255 |
+
k (`torch.Tensor`): The key tensor.
|
256 |
+
cos (`torch.Tensor`): The cosine part of the rotary embedding.
|
257 |
+
sin (`torch.Tensor`): The sine part of the rotary embedding.
|
258 |
+
position_ids (`torch.Tensor`):
|
259 |
+
The position indices of the tokens corresponding to the query and key tensors. For example, this can be
|
260 |
+
used to pass offsetted position ids when working with a KV-cache.
|
261 |
+
unsqueeze_dim (`int`, *optional*, defaults to 1):
|
262 |
+
The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
|
263 |
+
sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
|
264 |
+
that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
|
265 |
+
k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
|
266 |
+
cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
|
267 |
+
the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
|
268 |
+
Returns:
|
269 |
+
`tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
|
270 |
+
"""
|
271 |
+
cos = cos[position_ids].unsqueeze(unsqueeze_dim)
|
272 |
+
sin = sin[position_ids].unsqueeze(unsqueeze_dim)
|
273 |
+
q_embed = (q * cos) + (rotate_half(q) * sin)
|
274 |
+
k_embed = (k * cos) + (rotate_half(k) * sin)
|
275 |
+
return q_embed, k_embed
|
276 |
+
|
277 |
+
|
278 |
+
# Copied from transformers.models.clip.modeling_clip.CLIPMLP with CLIP->Phi
|
279 |
+
class PhiMLP(nn.Module):
|
280 |
+
def __init__(self, config):
|
281 |
+
super().__init__()
|
282 |
+
self.config = config
|
283 |
+
self.activation_fn = ACT2FN[config.hidden_act]
|
284 |
+
self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size)
|
285 |
+
self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size)
|
286 |
+
|
287 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
288 |
+
hidden_states = self.fc1(hidden_states)
|
289 |
+
hidden_states = self.activation_fn(hidden_states)
|
290 |
+
hidden_states = self.fc2(hidden_states)
|
291 |
+
return hidden_states
|
292 |
+
|
293 |
+
|
294 |
+
# Copied from transformers.models.llama.modeling_llama.repeat_kv with llama->phi
|
295 |
+
def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
|
296 |
+
"""
|
297 |
+
This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
|
298 |
+
num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
|
299 |
+
"""
|
300 |
+
batch, num_key_value_heads, slen, head_dim = hidden_states.shape
|
301 |
+
if n_rep == 1:
|
302 |
+
return hidden_states
|
303 |
+
hidden_states = hidden_states[:, :, None, :, :].expand(
|
304 |
+
batch, num_key_value_heads, n_rep, slen, head_dim
|
305 |
+
)
|
306 |
+
return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
|
307 |
+
|
308 |
+
|
309 |
+
class PhiAttention(nn.Module):
|
310 |
+
"""Multi-headed attention from 'Attention Is All You Need' paper"""
|
311 |
+
|
312 |
+
def __init__(self, config: PhiConfig, layer_idx: Optional[int] = None):
|
313 |
+
super().__init__()
|
314 |
+
self.config = config
|
315 |
+
self.layer_idx = layer_idx
|
316 |
+
if layer_idx is None:
|
317 |
+
logger.warning_once(
|
318 |
+
f"Instantiating {self.__class__.__name__} without passing a `layer_idx` is not recommended and will "
|
319 |
+
"lead to errors during the forward call if caching is used. Please make sure to provide a `layer_idx` "
|
320 |
+
"when creating this class."
|
321 |
+
)
|
322 |
+
|
323 |
+
self.attention_dropout = config.attention_dropout
|
324 |
+
self.hidden_size = config.hidden_size
|
325 |
+
self.num_heads = config.num_attention_heads
|
326 |
+
self.head_dim = self.hidden_size // self.num_heads
|
327 |
+
self.num_key_value_heads = config.num_key_value_heads
|
328 |
+
self.num_key_value_groups = self.num_heads // self.num_key_value_heads
|
329 |
+
self.max_position_embeddings = config.max_position_embeddings
|
330 |
+
self.rope_theta = config.rope_theta
|
331 |
+
self.partial_rotary_factor = config.partial_rotary_factor
|
332 |
+
self.is_causal = True
|
333 |
+
|
334 |
+
if (self.head_dim * self.num_heads) != self.hidden_size:
|
335 |
+
raise ValueError(
|
336 |
+
f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
|
337 |
+
f" and `num_heads`: {self.num_heads})."
|
338 |
+
)
|
339 |
+
|
340 |
+
self.Wqkv = nn.Linear(
|
341 |
+
self.hidden_size, 3 * self.num_heads * self.head_dim, bias=True
|
342 |
+
)
|
343 |
+
self.out_proj = nn.Linear(
|
344 |
+
self.num_heads * self.head_dim, self.hidden_size, bias=True
|
345 |
+
)
|
346 |
+
|
347 |
+
self._init_rope()
|
348 |
+
|
349 |
+
def _init_rope(self):
|
350 |
+
if self.config.rope_scaling is None:
|
351 |
+
self.rotary_emb = PhiRotaryEmbedding(
|
352 |
+
int(self.partial_rotary_factor * self.head_dim),
|
353 |
+
max_position_embeddings=self.max_position_embeddings,
|
354 |
+
base=self.rope_theta,
|
355 |
+
)
|
356 |
+
else:
|
357 |
+
scaling_type = self.config.rope_scaling["type"]
|
358 |
+
scaling_factor = self.config.rope_scaling["factor"]
|
359 |
+
if scaling_type == "linear":
|
360 |
+
self.rotary_emb = PhiLinearScalingRotaryEmbedding(
|
361 |
+
int(self.partial_rotary_factor * self.head_dim),
|
362 |
+
max_position_embeddings=self.max_position_embeddings,
|
363 |
+
scaling_factor=scaling_factor,
|
364 |
+
base=self.rope_theta,
|
365 |
+
)
|
366 |
+
elif scaling_type == "dynamic":
|
367 |
+
self.rotary_emb = PhiDynamicNTKScalingRotaryEmbedding(
|
368 |
+
int(self.partial_rotary_factor * self.head_dim),
|
369 |
+
max_position_embeddings=self.max_position_embeddings,
|
370 |
+
scaling_factor=scaling_factor,
|
371 |
+
base=self.rope_theta,
|
372 |
+
)
|
373 |
+
else:
|
374 |
+
raise ValueError(f"Unknown RoPE scaling type {scaling_type}")
|
375 |
+
|
376 |
+
def forward(
|
377 |
+
self,
|
378 |
+
hidden_states: torch.Tensor,
|
379 |
+
attention_mask: Optional[torch.Tensor] = None,
|
380 |
+
position_ids: Optional[torch.LongTensor] = None,
|
381 |
+
past_key_value: Optional[Cache] = None,
|
382 |
+
output_attentions: bool = False,
|
383 |
+
use_cache: bool = False,
|
384 |
+
cache_position: Optional[torch.LongTensor] = None,
|
385 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
386 |
+
bsz, q_len, _ = hidden_states.size()
|
387 |
+
|
388 |
+
query_states, key_states, value_states = self.Wqkv(hidden_states).chunk(
|
389 |
+
3, dim=-1
|
390 |
+
)
|
391 |
+
|
392 |
+
query_states = query_states.view(
|
393 |
+
bsz, q_len, self.num_heads, self.head_dim
|
394 |
+
).transpose(1, 2)
|
395 |
+
key_states = key_states.view(
|
396 |
+
bsz, q_len, self.num_key_value_heads, self.head_dim
|
397 |
+
).transpose(1, 2)
|
398 |
+
value_states = value_states.view(
|
399 |
+
bsz, q_len, self.num_key_value_heads, self.head_dim
|
400 |
+
).transpose(1, 2)
|
401 |
+
|
402 |
+
kv_seq_len = key_states.shape[-2]
|
403 |
+
if past_key_value is not None:
|
404 |
+
if self.layer_idx is None:
|
405 |
+
raise ValueError(
|
406 |
+
f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
|
407 |
+
"for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
|
408 |
+
"with a layer index."
|
409 |
+
)
|
410 |
+
kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
|
411 |
+
cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
|
412 |
+
|
413 |
+
# Partial rotary embedding
|
414 |
+
query_rot, query_pass = (
|
415 |
+
query_states[..., : self.rotary_emb.dim],
|
416 |
+
query_states[..., self.rotary_emb.dim :],
|
417 |
+
)
|
418 |
+
key_rot, key_pass = (
|
419 |
+
key_states[..., : self.rotary_emb.dim],
|
420 |
+
key_states[..., self.rotary_emb.dim :],
|
421 |
+
)
|
422 |
+
# [batch_size, seq_length, num_heads, head_dim // config.partial_rotary_factor]
|
423 |
+
query_rot, key_rot = apply_rotary_pos_emb(
|
424 |
+
query_rot, key_rot, cos, sin, position_ids
|
425 |
+
)
|
426 |
+
|
427 |
+
# [batch_size, seq_length, num_heads, head_dim]
|
428 |
+
query_states = torch.cat((query_rot, query_pass), dim=-1)
|
429 |
+
key_states = torch.cat((key_rot, key_pass), dim=-1)
|
430 |
+
|
431 |
+
if past_key_value is not None:
|
432 |
+
cache_kwargs = {
|
433 |
+
"sin": sin,
|
434 |
+
"cos": cos,
|
435 |
+
"partial_rotation_size": self.rotary_emb.dim,
|
436 |
+
"cache_position": cache_position,
|
437 |
+
}
|
438 |
+
key_states, value_states = past_key_value.update(
|
439 |
+
key_states, value_states, self.layer_idx, cache_kwargs
|
440 |
+
)
|
441 |
+
|
442 |
+
key_states = repeat_kv(key_states, self.num_key_value_groups)
|
443 |
+
value_states = repeat_kv(value_states, self.num_key_value_groups)
|
444 |
+
|
445 |
+
# Queries and keys upcast to fp32 is required by Phi-2 to avoid overflow
|
446 |
+
attn_weights = torch.matmul(
|
447 |
+
query_states.to(torch.float32), key_states.to(torch.float32).transpose(2, 3)
|
448 |
+
) / math.sqrt(self.head_dim)
|
449 |
+
|
450 |
+
if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
|
451 |
+
raise ValueError(
|
452 |
+
f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
|
453 |
+
f" {attn_weights.size()}"
|
454 |
+
)
|
455 |
+
|
456 |
+
if attention_mask is not None:
|
457 |
+
causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
|
458 |
+
attn_weights += causal_mask
|
459 |
+
|
460 |
+
# upcast attention to fp32
|
461 |
+
attn_weights = nn.functional.softmax(
|
462 |
+
attn_weights, dim=-1, dtype=torch.float32
|
463 |
+
).to(value_states.dtype)
|
464 |
+
attn_weights = nn.functional.dropout(
|
465 |
+
attn_weights, p=self.attention_dropout, training=self.training
|
466 |
+
)
|
467 |
+
|
468 |
+
attn_output = torch.matmul(attn_weights, value_states)
|
469 |
+
|
470 |
+
if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
|
471 |
+
raise ValueError(
|
472 |
+
f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
|
473 |
+
f" {attn_output.size()}"
|
474 |
+
)
|
475 |
+
|
476 |
+
attn_output = attn_output.transpose(1, 2).contiguous()
|
477 |
+
attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
|
478 |
+
|
479 |
+
attn_output = self.out_proj(attn_output)
|
480 |
+
|
481 |
+
if not output_attentions:
|
482 |
+
attn_weights = None
|
483 |
+
|
484 |
+
return attn_output, attn_weights, past_key_value
|
485 |
+
|
486 |
+
|
487 |
+
class PhiFlashAttention2(PhiAttention):
|
488 |
+
"""
|
489 |
+
Phi flash attention module. This module inherits from `PhiAttention` as the weights of the module stays
|
490 |
+
untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
|
491 |
+
flash attention and deal with padding tokens in case the input contains any of them.
|
492 |
+
"""
|
493 |
+
|
494 |
+
# Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2.__init__
|
495 |
+
def __init__(self, *args, **kwargs):
|
496 |
+
super().__init__(*args, **kwargs)
|
497 |
+
|
498 |
+
# TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
|
499 |
+
# 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.
|
500 |
+
# 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).
|
501 |
+
self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
|
502 |
+
|
503 |
+
def forward(
|
504 |
+
self,
|
505 |
+
hidden_states: torch.Tensor,
|
506 |
+
attention_mask: Optional[torch.LongTensor] = None,
|
507 |
+
position_ids: Optional[torch.LongTensor] = None,
|
508 |
+
past_key_value: Optional[Cache] = None,
|
509 |
+
output_attentions: bool = False,
|
510 |
+
use_cache: bool = False,
|
511 |
+
cache_position: Optional[torch.LongTensor] = None,
|
512 |
+
**kwargs,
|
513 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
514 |
+
# PhiFlashAttention2 attention does not support output_attentions
|
515 |
+
|
516 |
+
output_attentions = False
|
517 |
+
|
518 |
+
bsz, q_len, _ = hidden_states.size()
|
519 |
+
|
520 |
+
query_states, key_states, value_states = self.Wqkv(hidden_states).chunk(
|
521 |
+
3, dim=-1
|
522 |
+
)
|
523 |
+
|
524 |
+
# Flash attention requires the input to have the shape
|
525 |
+
# batch_size x seq_length x head_dim x hidden_dim
|
526 |
+
# therefore we just need to keep the original shape
|
527 |
+
query_states = query_states.view(
|
528 |
+
bsz, q_len, self.num_heads, self.head_dim
|
529 |
+
).transpose(1, 2)
|
530 |
+
key_states = key_states.view(
|
531 |
+
bsz, q_len, self.num_key_value_heads, self.head_dim
|
532 |
+
).transpose(1, 2)
|
533 |
+
value_states = value_states.view(
|
534 |
+
bsz, q_len, self.num_key_value_heads, self.head_dim
|
535 |
+
).transpose(1, 2)
|
536 |
+
|
537 |
+
kv_seq_len = key_states.shape[-2]
|
538 |
+
if past_key_value is not None:
|
539 |
+
kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
|
540 |
+
cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
|
541 |
+
|
542 |
+
# Partial rotary embedding
|
543 |
+
query_rot, query_pass = (
|
544 |
+
query_states[..., : self.rotary_emb.dim],
|
545 |
+
query_states[..., self.rotary_emb.dim :],
|
546 |
+
)
|
547 |
+
key_rot, key_pass = (
|
548 |
+
key_states[..., : self.rotary_emb.dim],
|
549 |
+
key_states[..., self.rotary_emb.dim :],
|
550 |
+
)
|
551 |
+
# [batch_size, seq_length, num_heads, head_dim // config.partial_rotary_factor]
|
552 |
+
query_rot, key_rot = apply_rotary_pos_emb(
|
553 |
+
query_rot, key_rot, cos, sin, position_ids
|
554 |
+
)
|
555 |
+
|
556 |
+
# [batch_size, seq_length, num_heads, head_dim]
|
557 |
+
query_states = torch.cat((query_rot, query_pass), dim=-1)
|
558 |
+
key_states = torch.cat((key_rot, key_pass), dim=-1)
|
559 |
+
|
560 |
+
if past_key_value is not None:
|
561 |
+
cache_kwargs = {
|
562 |
+
"sin": sin,
|
563 |
+
"cos": cos,
|
564 |
+
"partial_rotation_size": self.rotary_emb.dim,
|
565 |
+
"cache_position": cache_position,
|
566 |
+
}
|
567 |
+
key_states, value_states = past_key_value.update(
|
568 |
+
key_states, value_states, self.layer_idx, cache_kwargs
|
569 |
+
)
|
570 |
+
|
571 |
+
# 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
|
572 |
+
# to be able to avoid many of these transpose/reshape/view.
|
573 |
+
query_states = query_states.transpose(1, 2)
|
574 |
+
key_states = key_states.transpose(1, 2)
|
575 |
+
value_states = value_states.transpose(1, 2)
|
576 |
+
|
577 |
+
attn_dropout = self.attention_dropout if self.training else 0.0
|
578 |
+
|
579 |
+
# In PEFT, usually we cast the layer norms in float32 for training stability reasons
|
580 |
+
# therefore the input hidden states gets silently casted in float32. Hence, we need
|
581 |
+
# cast them back in the correct dtype just to be sure everything works as expected.
|
582 |
+
# This might slowdown training & inference so it is recommended to not cast the LayerNorms
|
583 |
+
# in fp32.
|
584 |
+
|
585 |
+
if query_states.dtype == torch.float32:
|
586 |
+
if torch.is_autocast_enabled():
|
587 |
+
target_dtype = torch.get_autocast_gpu_dtype()
|
588 |
+
# Handle the case where the model is quantized
|
589 |
+
elif hasattr(self.config, "_pre_quantization_dtype"):
|
590 |
+
target_dtype = self.config._pre_quantization_dtype
|
591 |
+
else:
|
592 |
+
target_dtype = self.q_proj.weight.dtype
|
593 |
+
|
594 |
+
logger.warning_once(
|
595 |
+
f"The input hidden states seems to be silently casted in float32, this might be related to"
|
596 |
+
f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
|
597 |
+
f" {target_dtype}."
|
598 |
+
)
|
599 |
+
|
600 |
+
query_states = query_states.to(target_dtype)
|
601 |
+
key_states = key_states.to(target_dtype)
|
602 |
+
value_states = value_states.to(target_dtype)
|
603 |
+
|
604 |
+
attn_output = _flash_attention_forward(
|
605 |
+
query_states,
|
606 |
+
key_states,
|
607 |
+
value_states,
|
608 |
+
attention_mask,
|
609 |
+
q_len,
|
610 |
+
position_ids=position_ids,
|
611 |
+
dropout=attn_dropout,
|
612 |
+
softmax_scale=None,
|
613 |
+
use_top_left_mask=self._flash_attn_uses_top_left_mask,
|
614 |
+
is_causal=self.is_causal,
|
615 |
+
)
|
616 |
+
|
617 |
+
attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
|
618 |
+
attn_output = self.out_proj(attn_output)
|
619 |
+
|
620 |
+
if not output_attentions:
|
621 |
+
attn_weights = None
|
622 |
+
|
623 |
+
return attn_output, attn_weights, past_key_value
|
624 |
+
|
625 |
+
|
626 |
+
class PhiSdpaAttention(PhiAttention):
|
627 |
+
def __init__(self, *args, **kwargs):
|
628 |
+
super().__init__(*args, **kwargs)
|
629 |
+
self.require_contiguous_qkv = version.parse(
|
630 |
+
get_torch_version()
|
631 |
+
) < version.parse("2.2.0")
|
632 |
+
|
633 |
+
"""
|
634 |
+
SDPA attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
|
635 |
+
`PhiAttention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
|
636 |
+
SDPA API.
|
637 |
+
"""
|
638 |
+
|
639 |
+
# Adapted from PhiAttention.forward
|
640 |
+
def forward(
|
641 |
+
self,
|
642 |
+
hidden_states: torch.Tensor,
|
643 |
+
attention_mask: Optional[torch.Tensor] = None,
|
644 |
+
position_ids: Optional[torch.LongTensor] = None,
|
645 |
+
past_key_value: Optional[Cache] = None,
|
646 |
+
output_attentions: bool = False,
|
647 |
+
use_cache: bool = False,
|
648 |
+
cache_position: Optional[torch.LongTensor] = None,
|
649 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
650 |
+
if output_attentions:
|
651 |
+
# TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented.
|
652 |
+
logger.warning_once(
|
653 |
+
"PhiModel is using PhiSdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not "
|
654 |
+
"support `output_attentions=True`. Falling back to the manual attention implementation, but specifying "
|
655 |
+
"the manual implementation will be required from Transformers version v5.0.0 onwards. This warning can "
|
656 |
+
'be removed using the argument `attn_implementation="eager"` when loading the model.'
|
657 |
+
)
|
658 |
+
return super().forward(
|
659 |
+
hidden_states=hidden_states,
|
660 |
+
attention_mask=attention_mask,
|
661 |
+
position_ids=position_ids,
|
662 |
+
past_key_value=past_key_value,
|
663 |
+
output_attentions=output_attentions,
|
664 |
+
use_cache=use_cache,
|
665 |
+
)
|
666 |
+
|
667 |
+
bsz, q_len, _ = hidden_states.size()
|
668 |
+
|
669 |
+
query_states, key_states, value_states = self.Wqkv(hidden_states).chunk(
|
670 |
+
3, dim=-1
|
671 |
+
)
|
672 |
+
|
673 |
+
query_states = query_states.view(
|
674 |
+
bsz, q_len, self.num_heads, self.head_dim
|
675 |
+
).transpose(1, 2)
|
676 |
+
key_states = key_states.view(
|
677 |
+
bsz, q_len, self.num_key_value_heads, self.head_dim
|
678 |
+
).transpose(1, 2)
|
679 |
+
value_states = value_states.view(
|
680 |
+
bsz, q_len, self.num_key_value_heads, self.head_dim
|
681 |
+
).transpose(1, 2)
|
682 |
+
|
683 |
+
kv_seq_len = key_states.shape[-2]
|
684 |
+
if past_key_value is not None:
|
685 |
+
if self.layer_idx is None:
|
686 |
+
raise ValueError(
|
687 |
+
f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
|
688 |
+
"for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
|
689 |
+
"with a layer index."
|
690 |
+
)
|
691 |
+
kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
|
692 |
+
cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
|
693 |
+
|
694 |
+
# Partial rotary embedding
|
695 |
+
query_rot, query_pass = (
|
696 |
+
query_states[..., : self.rotary_emb.dim],
|
697 |
+
query_states[..., self.rotary_emb.dim :],
|
698 |
+
)
|
699 |
+
key_rot, key_pass = (
|
700 |
+
key_states[..., : self.rotary_emb.dim],
|
701 |
+
key_states[..., self.rotary_emb.dim :],
|
702 |
+
)
|
703 |
+
# [batch_size, seq_length, num_heads, head_dim // config.partial_rotary_factor]
|
704 |
+
query_rot, key_rot = apply_rotary_pos_emb(
|
705 |
+
query_rot, key_rot, cos, sin, position_ids
|
706 |
+
)
|
707 |
+
|
708 |
+
# [batch_size, seq_length, num_heads, head_dim]
|
709 |
+
query_states = torch.cat((query_rot, query_pass), dim=-1)
|
710 |
+
key_states = torch.cat((key_rot, key_pass), dim=-1)
|
711 |
+
|
712 |
+
if past_key_value is not None:
|
713 |
+
cache_kwargs = {
|
714 |
+
"sin": sin,
|
715 |
+
"cos": cos,
|
716 |
+
"partial_rotation_size": self.rotary_emb.dim,
|
717 |
+
"cache_position": cache_position,
|
718 |
+
}
|
719 |
+
key_states, value_states = past_key_value.update(
|
720 |
+
key_states, value_states, self.layer_idx, cache_kwargs
|
721 |
+
)
|
722 |
+
|
723 |
+
key_states = repeat_kv(key_states, self.num_key_value_groups)
|
724 |
+
value_states = repeat_kv(value_states, self.num_key_value_groups)
|
725 |
+
|
726 |
+
causal_mask = attention_mask
|
727 |
+
if attention_mask is not None:
|
728 |
+
causal_mask = causal_mask[:, :, :, : key_states.shape[-2]]
|
729 |
+
|
730 |
+
# SDPA with memory-efficient backend is broken in torch==2.1.2 when using non-contiguous inputs and a custom
|
731 |
+
# attn_mask, so we need to call `.contiguous()` here. This was fixed in torch==2.2.0.
|
732 |
+
# Reference: https://github.com/pytorch/pytorch/issues/112577
|
733 |
+
if (
|
734 |
+
self.require_contiguous_qkv
|
735 |
+
and query_states.device.type == "cuda"
|
736 |
+
and attention_mask is not None
|
737 |
+
):
|
738 |
+
query_states = query_states.contiguous()
|
739 |
+
key_states = key_states.contiguous()
|
740 |
+
value_states = value_states.contiguous()
|
741 |
+
|
742 |
+
# We dispatch to SDPA's Flash Attention or Efficient kernels via this `is_causal` if statement instead of an inline conditional assignment
|
743 |
+
# in SDPA to support both torch.compile's dynamic shapes and full graph options. An inline conditional prevents dynamic shapes from compiling.
|
744 |
+
is_causal = True if causal_mask is None and q_len > 1 else False
|
745 |
+
|
746 |
+
attn_output = torch.nn.functional.scaled_dot_product_attention(
|
747 |
+
query_states,
|
748 |
+
key_states,
|
749 |
+
value_states,
|
750 |
+
attn_mask=causal_mask,
|
751 |
+
dropout_p=self.attention_dropout if self.training else 0.0,
|
752 |
+
is_causal=is_causal,
|
753 |
+
)
|
754 |
+
|
755 |
+
attn_output = attn_output.transpose(1, 2).contiguous()
|
756 |
+
attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
|
757 |
+
|
758 |
+
attn_output = self.out_proj(attn_output)
|
759 |
+
|
760 |
+
return attn_output, None, past_key_value
|
761 |
+
|
762 |
+
|
763 |
+
PHI_ATTENTION_CLASSES = {
|
764 |
+
"eager": PhiAttention,
|
765 |
+
"flash_attention_2": PhiFlashAttention2,
|
766 |
+
"sdpa": PhiSdpaAttention,
|
767 |
+
}
|
768 |
+
|
769 |
+
|
770 |
+
class PhiDecoderLayer(nn.Module):
|
771 |
+
def __init__(self, config: PhiConfig, layer_idx: int):
|
772 |
+
super().__init__()
|
773 |
+
self.mixer = PHI_ATTENTION_CLASSES[config._attn_implementation](
|
774 |
+
config, layer_idx=layer_idx
|
775 |
+
)
|
776 |
+
self.mlp = PhiMLP(config)
|
777 |
+
self.ln = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
778 |
+
self.resid_dropout = nn.Dropout(config.resid_pdrop)
|
779 |
+
|
780 |
+
def forward(
|
781 |
+
self,
|
782 |
+
hidden_states: torch.Tensor,
|
783 |
+
attention_mask: Optional[torch.Tensor] = None,
|
784 |
+
position_ids: Optional[torch.LongTensor] = None,
|
785 |
+
output_attentions: Optional[bool] = False,
|
786 |
+
use_cache: Optional[bool] = False,
|
787 |
+
past_key_value: Optional[Tuple[torch.Tensor]] = None,
|
788 |
+
cache_position: Optional[torch.LongTensor] = None,
|
789 |
+
**kwargs,
|
790 |
+
) -> Tuple[
|
791 |
+
torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]
|
792 |
+
]:
|
793 |
+
"""
|
794 |
+
Args:
|
795 |
+
hidden_states (`torch.FloatTensor`):
|
796 |
+
input to the layer of shape `(batch, seq_len, embed_dim)`
|
797 |
+
attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
|
798 |
+
`(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
|
799 |
+
position_ids (`torch.LongTensor` of shape `({0})`, *optional*):
|
800 |
+
Indices of positions of each input sequence tokens in the position embeddings. Selected in the range
|
801 |
+
`[0, config.n_positions - 1]`. [What are position IDs?](../glossary#position-ids)
|
802 |
+
output_attentions (`bool`, *optional*):
|
803 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
|
804 |
+
returned tensors for more detail.
|
805 |
+
use_cache (`bool`, *optional*):
|
806 |
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
|
807 |
+
(see `past_key_values`).
|
808 |
+
past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
|
809 |
+
cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
|
810 |
+
Indices depicting the position of the input sequence tokens in the sequence
|
811 |
+
kwargs (`dict`, *optional*):
|
812 |
+
Arbitrary kwargs to be ignored, used for FSDP and other methods that injects code
|
813 |
+
into the model
|
814 |
+
"""
|
815 |
+
|
816 |
+
residual = hidden_states
|
817 |
+
|
818 |
+
hidden_states = self.ln(hidden_states)
|
819 |
+
|
820 |
+
# Self Attention
|
821 |
+
attn_outputs, self_attn_weights, present_key_value = self.mixer(
|
822 |
+
hidden_states=hidden_states,
|
823 |
+
attention_mask=attention_mask,
|
824 |
+
position_ids=position_ids,
|
825 |
+
past_key_value=past_key_value,
|
826 |
+
output_attentions=output_attentions,
|
827 |
+
use_cache=use_cache,
|
828 |
+
cache_position=cache_position,
|
829 |
+
)
|
830 |
+
attn_outputs = self.resid_dropout(attn_outputs)
|
831 |
+
|
832 |
+
feed_forward_hidden_states = self.resid_dropout(self.mlp(hidden_states))
|
833 |
+
hidden_states = attn_outputs + feed_forward_hidden_states + residual
|
834 |
+
outputs = (hidden_states,)
|
835 |
+
|
836 |
+
if output_attentions:
|
837 |
+
outputs += (self_attn_weights,)
|
838 |
+
|
839 |
+
if use_cache:
|
840 |
+
outputs += (present_key_value,)
|
841 |
+
|
842 |
+
return outputs
|
843 |
+
|
844 |
+
|
845 |
+
PHI_START_DOCSTRING = r"""
|
846 |
+
This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
|
847 |
+
library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
|
848 |
+
etc.)
|
849 |
+
|
850 |
+
This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
|
851 |
+
Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
|
852 |
+
and behavior.
|
853 |
+
|
854 |
+
Parameters:
|
855 |
+
config ([`PhiConfig`]):
|
856 |
+
Model configuration class with all the parameters of the model. Initializing with a config file does not
|
857 |
+
load the weights associated with the model, only the configuration. Check out the
|
858 |
+
[`~PreTrainedModel.from_pretrained`] method to load the model weights.
|
859 |
+
"""
|
860 |
+
|
861 |
+
|
862 |
+
@add_start_docstrings(
|
863 |
+
"The bare Phi Model outputting raw hidden-states without any specific head on top.",
|
864 |
+
PHI_START_DOCSTRING,
|
865 |
+
)
|
866 |
+
class PhiPreTrainedModel(PreTrainedModel):
|
867 |
+
config_class = PhiConfig
|
868 |
+
base_model_prefix = "model"
|
869 |
+
supports_gradient_checkpointing = True
|
870 |
+
_no_split_modules = ["PhiDecoderLayer"]
|
871 |
+
_skip_keys_device_placement = "past_key_values"
|
872 |
+
_supports_flash_attn_2 = True
|
873 |
+
_supports_sdpa = True
|
874 |
+
_supports_cache_class = True
|
875 |
+
|
876 |
+
def _init_weights(self, module):
|
877 |
+
std = self.config.initializer_range
|
878 |
+
if isinstance(module, nn.Linear):
|
879 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
880 |
+
if module.bias is not None:
|
881 |
+
module.bias.data.zero_()
|
882 |
+
elif isinstance(module, nn.Embedding):
|
883 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
884 |
+
if module.padding_idx is not None:
|
885 |
+
module.weight.data[module.padding_idx].zero_()
|
886 |
+
|
887 |
+
|
888 |
+
class Embedding(nn.Module):
|
889 |
+
def __init__(self, config: PhiConfig):
|
890 |
+
super().__init__()
|
891 |
+
self.wte = nn.Embedding(
|
892 |
+
config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id
|
893 |
+
)
|
894 |
+
|
895 |
+
def forward(self, input_ids: torch.LongTensor) -> torch.FloatTensor:
|
896 |
+
return self.wte(input_ids)
|
897 |
+
|
898 |
+
PHI_INPUTS_DOCSTRING = r"""
|
899 |
+
Args:
|
900 |
+
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
|
901 |
+
Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
|
902 |
+
it.
|
903 |
+
|
904 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
905 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
906 |
+
|
907 |
+
[What are input IDs?](../glossary#input-ids)
|
908 |
+
attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
909 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
910 |
+
|
911 |
+
- 1 for tokens that are **not masked**,
|
912 |
+
- 0 for tokens that are **masked**.
|
913 |
+
|
914 |
+
[What are attention masks?](../glossary#attention-mask)
|
915 |
+
|
916 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
917 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
918 |
+
|
919 |
+
If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
|
920 |
+
`past_key_values`).
|
921 |
+
|
922 |
+
If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
|
923 |
+
and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
|
924 |
+
information on the default strategy.
|
925 |
+
|
926 |
+
- 1 indicates the head is **not masked**,
|
927 |
+
- 0 indicates the head is **masked**.
|
928 |
+
position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
929 |
+
Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
|
930 |
+
config.n_positions - 1]`.
|
931 |
+
|
932 |
+
[What are position IDs?](../glossary#position-ids)
|
933 |
+
past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
|
934 |
+
Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
|
935 |
+
blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
|
936 |
+
returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
|
937 |
+
|
938 |
+
Two formats are allowed:
|
939 |
+
- a [`~cache_utils.Cache`] instance;
|
940 |
+
- Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
|
941 |
+
shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
|
942 |
+
cache format.
|
943 |
+
|
944 |
+
The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
|
945 |
+
legacy cache format will be returned.
|
946 |
+
|
947 |
+
If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
|
948 |
+
have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
|
949 |
+
of shape `(batch_size, sequence_length)`.
|
950 |
+
inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
|
951 |
+
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
|
952 |
+
is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
|
953 |
+
model's internal embedding lookup matrix.
|
954 |
+
use_cache (`bool`, *optional*):
|
955 |
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
|
956 |
+
`past_key_values`).
|
957 |
+
output_attentions (`bool`, *optional*):
|
958 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
959 |
+
tensors for more detail.
|
960 |
+
output_hidden_states (`bool`, *optional*):
|
961 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
962 |
+
more detail.
|
963 |
+
return_dict (`bool`, *optional*):
|
964 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
965 |
+
cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
|
966 |
+
Indices depicting the position of the input sequence tokens in the sequence. Contrarily to `position_ids`,
|
967 |
+
this tensor is not affected by padding. It is used to update the cache in the correct position and to infer
|
968 |
+
the complete sequence length.
|
969 |
+
"""
|
970 |
+
|
971 |
+
|
972 |
+
@add_start_docstrings(
|
973 |
+
"The bare Phi Model outputting raw hidden-states without any specific head on top.",
|
974 |
+
PHI_START_DOCSTRING,
|
975 |
+
)
|
976 |
+
class PhiModel(PhiPreTrainedModel):
|
977 |
+
"""
|
978 |
+
Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`PhiDecoderLayer`]
|
979 |
+
|
980 |
+
Args:
|
981 |
+
config: PhiConfig
|
982 |
+
"""
|
983 |
+
|
984 |
+
def __init__(self, config: PhiConfig):
|
985 |
+
super().__init__(config)
|
986 |
+
self.padding_idx = config.pad_token_id
|
987 |
+
self.vocab_size = config.vocab_size
|
988 |
+
|
989 |
+
self.embd = Embedding(config)
|
990 |
+
self.embed_dropout = nn.Dropout(config.embd_pdrop)
|
991 |
+
self.h = nn.ModuleList(
|
992 |
+
[
|
993 |
+
PhiDecoderLayer(config, layer_idx)
|
994 |
+
for layer_idx in range(config.num_hidden_layers)
|
995 |
+
]
|
996 |
+
)
|
997 |
+
|
998 |
+
self._use_flash_attention_2 = config._attn_implementation == "flash_attention_2"
|
999 |
+
self._use_sdpa = config._attn_implementation == "sdpa"
|
1000 |
+
|
1001 |
+
self.gradient_checkpointing = False
|
1002 |
+
# Initialize weights and apply final processing
|
1003 |
+
self.post_init()
|
1004 |
+
|
1005 |
+
def get_input_embeddings(self):
|
1006 |
+
return self.embd.wte
|
1007 |
+
|
1008 |
+
def set_input_embeddings(self, value):
|
1009 |
+
self.embd.wte = value
|
1010 |
+
|
1011 |
+
@add_start_docstrings_to_model_forward(PHI_INPUTS_DOCSTRING)
|
1012 |
+
def forward(
|
1013 |
+
self,
|
1014 |
+
input_ids: torch.LongTensor = None,
|
1015 |
+
attention_mask: Optional[torch.Tensor] = None,
|
1016 |
+
position_ids: Optional[torch.LongTensor] = None,
|
1017 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
1018 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
1019 |
+
use_cache: Optional[bool] = None,
|
1020 |
+
output_attentions: Optional[bool] = None,
|
1021 |
+
output_hidden_states: Optional[bool] = None,
|
1022 |
+
return_dict: Optional[bool] = None,
|
1023 |
+
cache_position: Optional[torch.LongTensor] = None,
|
1024 |
+
) -> Union[Tuple, BaseModelOutputWithPast]:
|
1025 |
+
output_attentions = (
|
1026 |
+
output_attentions
|
1027 |
+
if output_attentions is not None
|
1028 |
+
else self.config.output_attentions
|
1029 |
+
)
|
1030 |
+
output_hidden_states = (
|
1031 |
+
output_hidden_states
|
1032 |
+
if output_hidden_states is not None
|
1033 |
+
else self.config.output_hidden_states
|
1034 |
+
)
|
1035 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
1036 |
+
|
1037 |
+
return_dict = (
|
1038 |
+
return_dict if return_dict is not None else self.config.use_return_dict
|
1039 |
+
)
|
1040 |
+
|
1041 |
+
if (input_ids is None) ^ (inputs_embeds is not None):
|
1042 |
+
raise ValueError(
|
1043 |
+
"You cannot specify both input_ids and inputs_embeds at the same time, and must specify either one"
|
1044 |
+
)
|
1045 |
+
|
1046 |
+
if self.gradient_checkpointing and self.training:
|
1047 |
+
if use_cache:
|
1048 |
+
logger.warning_once(
|
1049 |
+
"`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
|
1050 |
+
)
|
1051 |
+
use_cache = False
|
1052 |
+
|
1053 |
+
use_legacy_cache = False
|
1054 |
+
if use_cache and not isinstance(past_key_values, Cache) and not self.training:
|
1055 |
+
use_legacy_cache = True
|
1056 |
+
past_key_values = DynamicCache.from_legacy_cache(past_key_values)
|
1057 |
+
logger.warning_once(
|
1058 |
+
"We detected that you are passing `past_key_values` as a tuple and this is deprecated and will be removed in v4.43. "
|
1059 |
+
"Please use an appropriate `Cache` class (https://huggingface.co/docs/transformers/internal/generation_utils#transformers.Cache)"
|
1060 |
+
)
|
1061 |
+
|
1062 |
+
if inputs_embeds is None:
|
1063 |
+
inputs_embeds = self.embd(input_ids)
|
1064 |
+
|
1065 |
+
if cache_position is None:
|
1066 |
+
past_seen_tokens = (
|
1067 |
+
past_key_values.get_seq_length() if past_key_values is not None else 0
|
1068 |
+
)
|
1069 |
+
cache_position = torch.arange(
|
1070 |
+
past_seen_tokens,
|
1071 |
+
past_seen_tokens + inputs_embeds.shape[1],
|
1072 |
+
device=inputs_embeds.device,
|
1073 |
+
)
|
1074 |
+
if position_ids is None:
|
1075 |
+
position_ids = cache_position.unsqueeze(0)
|
1076 |
+
|
1077 |
+
causal_mask = self._update_causal_mask(
|
1078 |
+
attention_mask,
|
1079 |
+
inputs_embeds,
|
1080 |
+
cache_position,
|
1081 |
+
past_key_values,
|
1082 |
+
output_attentions,
|
1083 |
+
)
|
1084 |
+
|
1085 |
+
hidden_states = inputs_embeds
|
1086 |
+
|
1087 |
+
# decoder layers
|
1088 |
+
all_hidden_states = () if output_hidden_states else None
|
1089 |
+
all_self_attns = () if output_attentions else None
|
1090 |
+
next_decoder_cache = None
|
1091 |
+
|
1092 |
+
for decoder_layer in self.h:
|
1093 |
+
if output_hidden_states:
|
1094 |
+
all_hidden_states += (hidden_states,)
|
1095 |
+
|
1096 |
+
if self.gradient_checkpointing and self.training:
|
1097 |
+
layer_outputs = self._gradient_checkpointing_func(
|
1098 |
+
decoder_layer.__call__,
|
1099 |
+
hidden_states,
|
1100 |
+
causal_mask,
|
1101 |
+
position_ids,
|
1102 |
+
output_attentions,
|
1103 |
+
use_cache,
|
1104 |
+
past_key_values,
|
1105 |
+
cache_position,
|
1106 |
+
)
|
1107 |
+
else:
|
1108 |
+
layer_outputs = decoder_layer(
|
1109 |
+
hidden_states,
|
1110 |
+
attention_mask=causal_mask,
|
1111 |
+
position_ids=position_ids,
|
1112 |
+
past_key_value=past_key_values,
|
1113 |
+
output_attentions=output_attentions,
|
1114 |
+
use_cache=use_cache,
|
1115 |
+
cache_position=cache_position,
|
1116 |
+
)
|
1117 |
+
|
1118 |
+
hidden_states = layer_outputs[0]
|
1119 |
+
|
1120 |
+
if use_cache:
|
1121 |
+
next_decoder_cache = layer_outputs[2 if output_attentions else 1]
|
1122 |
+
|
1123 |
+
if output_attentions:
|
1124 |
+
all_self_attns += (layer_outputs[1],)
|
1125 |
+
|
1126 |
+
# add hidden states from the last decoder layer
|
1127 |
+
if output_hidden_states:
|
1128 |
+
all_hidden_states += (hidden_states,)
|
1129 |
+
|
1130 |
+
next_cache = None
|
1131 |
+
if use_cache:
|
1132 |
+
next_cache = (
|
1133 |
+
next_decoder_cache.to_legacy_cache()
|
1134 |
+
if use_legacy_cache
|
1135 |
+
else next_decoder_cache
|
1136 |
+
)
|
1137 |
+
if not return_dict:
|
1138 |
+
return tuple(
|
1139 |
+
v
|
1140 |
+
for v in [hidden_states, next_cache, all_hidden_states, all_self_attns]
|
1141 |
+
if v is not None
|
1142 |
+
)
|
1143 |
+
return BaseModelOutputWithPast(
|
1144 |
+
last_hidden_state=hidden_states,
|
1145 |
+
past_key_values=next_cache,
|
1146 |
+
hidden_states=all_hidden_states,
|
1147 |
+
attentions=all_self_attns,
|
1148 |
+
)
|
1149 |
+
|
1150 |
+
# Copied from transformers.models.llama.modeling_llama.LlamaModel._update_causal_mask
|
1151 |
+
def _update_causal_mask(
|
1152 |
+
self,
|
1153 |
+
attention_mask: torch.Tensor,
|
1154 |
+
input_tensor: torch.Tensor,
|
1155 |
+
cache_position: torch.Tensor,
|
1156 |
+
past_key_values: Cache,
|
1157 |
+
output_attentions: bool,
|
1158 |
+
):
|
1159 |
+
# TODO: As of torch==2.2.0, the `attention_mask` passed to the model in `generate` is 2D and of dynamic length even when the static
|
1160 |
+
# KV cache is used. This is an issue for torch.compile which then recaptures cudagraphs at each decode steps due to the dynamic shapes.
|
1161 |
+
# (`recording cudagraph tree for symint key 13`, etc.), which is VERY slow. A workaround is `@torch.compiler.disable`, but this prevents using
|
1162 |
+
# `fullgraph=True`. See more context in https://github.com/huggingface/transformers/pull/29114
|
1163 |
+
|
1164 |
+
if self.config._attn_implementation == "flash_attention_2":
|
1165 |
+
if attention_mask is not None and 0.0 in attention_mask:
|
1166 |
+
return attention_mask
|
1167 |
+
return None
|
1168 |
+
|
1169 |
+
# For SDPA, when possible, we will rely on its `is_causal` argument instead of its `attn_mask` argument, in
|
1170 |
+
# order to dispatch on Flash Attention 2. This feature is not compatible with static cache, as SDPA will fail
|
1171 |
+
# to infer the attention mask.
|
1172 |
+
past_seen_tokens = (
|
1173 |
+
past_key_values.get_seq_length() if past_key_values is not None else 0
|
1174 |
+
)
|
1175 |
+
using_static_cache = isinstance(past_key_values, StaticCache)
|
1176 |
+
|
1177 |
+
# When output attentions is True, sdpa implementation's forward method calls the eager implementation's forward
|
1178 |
+
if (
|
1179 |
+
self.config._attn_implementation == "sdpa"
|
1180 |
+
and not using_static_cache
|
1181 |
+
and not output_attentions
|
1182 |
+
):
|
1183 |
+
if AttentionMaskConverter._ignore_causal_mask_sdpa(
|
1184 |
+
attention_mask,
|
1185 |
+
inputs_embeds=input_tensor,
|
1186 |
+
past_key_values_length=past_seen_tokens,
|
1187 |
+
is_training=self.training,
|
1188 |
+
):
|
1189 |
+
return None
|
1190 |
+
|
1191 |
+
dtype, device = input_tensor.dtype, input_tensor.device
|
1192 |
+
min_dtype = torch.finfo(dtype).min
|
1193 |
+
sequence_length = input_tensor.shape[1]
|
1194 |
+
if using_static_cache:
|
1195 |
+
target_length = past_key_values.get_max_length()
|
1196 |
+
else:
|
1197 |
+
target_length = (
|
1198 |
+
attention_mask.shape[-1]
|
1199 |
+
if isinstance(attention_mask, torch.Tensor)
|
1200 |
+
else past_seen_tokens + sequence_length + 1
|
1201 |
+
)
|
1202 |
+
|
1203 |
+
# In case the provided `attention` mask is 2D, we generate a causal mask here (4D).
|
1204 |
+
causal_mask = _prepare_4d_causal_attention_mask_with_cache_position(
|
1205 |
+
attention_mask,
|
1206 |
+
sequence_length=sequence_length,
|
1207 |
+
target_length=target_length,
|
1208 |
+
dtype=dtype,
|
1209 |
+
device=device,
|
1210 |
+
min_dtype=min_dtype,
|
1211 |
+
cache_position=cache_position,
|
1212 |
+
batch_size=input_tensor.shape[0],
|
1213 |
+
)
|
1214 |
+
|
1215 |
+
if (
|
1216 |
+
self.config._attn_implementation == "sdpa"
|
1217 |
+
and attention_mask is not None
|
1218 |
+
and attention_mask.device.type == "cuda"
|
1219 |
+
and not output_attentions
|
1220 |
+
):
|
1221 |
+
# Attend to all tokens in fully masked rows in the causal_mask, for example the relevant first rows when
|
1222 |
+
# using left padding. This is required by F.scaled_dot_product_attention memory-efficient attention path.
|
1223 |
+
# Details: https://github.com/pytorch/pytorch/issues/110213
|
1224 |
+
causal_mask = AttentionMaskConverter._unmask_unattended(
|
1225 |
+
causal_mask, min_dtype
|
1226 |
+
)
|
1227 |
+
|
1228 |
+
return causal_mask
|
1229 |
+
|
1230 |
+
|
1231 |
+
class CausalLMHead(nn.Module):
|
1232 |
+
"""Causal Language Modeling head. Simplified version."""
|
1233 |
+
|
1234 |
+
def __init__(self, config):
|
1235 |
+
super().__init__()
|
1236 |
+
self.ln = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
1237 |
+
self.linear = nn.Linear(config.hidden_size, config.vocab_size)
|
1238 |
+
|
1239 |
+
def forward(self, hidden_states):
|
1240 |
+
return self.linear(self.ln(hidden_states))
|
1241 |
+
|
1242 |
+
|
1243 |
+
class PhiForCausalLM(PhiPreTrainedModel):
|
1244 |
+
|
1245 |
+
# Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.__init__ with Llama->Phi,bias=False->bias=True
|
1246 |
+
def __init__(self, config):
|
1247 |
+
super().__init__(config)
|
1248 |
+
self.transformer = PhiModel(config)
|
1249 |
+
self.vocab_size = config.vocab_size
|
1250 |
+
self.lm_head = CausalLMHead(config)
|
1251 |
+
|
1252 |
+
# Initialize weights and apply final processing
|
1253 |
+
self.post_init()
|
1254 |
+
|
1255 |
+
# Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.get_input_embeddings
|
1256 |
+
def get_input_embeddings(self):
|
1257 |
+
return self.transformer.embd.wte
|
1258 |
+
|
1259 |
+
# Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.set_input_embeddings
|
1260 |
+
def set_input_embeddings(self, value):
|
1261 |
+
self.transformer.embd.wte = value
|
1262 |
+
|
1263 |
+
# Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.get_output_embeddings
|
1264 |
+
def get_output_embeddings(self):
|
1265 |
+
return self.lm_head.linear
|
1266 |
+
|
1267 |
+
# Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.set_output_embeddings
|
1268 |
+
def set_output_embeddings(self, new_embeddings):
|
1269 |
+
self.lm_head.linear = new_embeddings
|
1270 |
+
|
1271 |
+
# Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.set_decoder
|
1272 |
+
def set_decoder(self, decoder):
|
1273 |
+
self.model = decoder
|
1274 |
+
|
1275 |
+
# Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.get_decoder
|
1276 |
+
def get_decoder(self):
|
1277 |
+
return self.model
|
1278 |
+
|
1279 |
+
@add_start_docstrings_to_model_forward(PHI_INPUTS_DOCSTRING)
|
1280 |
+
@replace_return_docstrings(
|
1281 |
+
output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC
|
1282 |
+
)
|
1283 |
+
def forward(
|
1284 |
+
self,
|
1285 |
+
input_ids: torch.LongTensor = None,
|
1286 |
+
attention_mask: Optional[torch.Tensor] = None,
|
1287 |
+
position_ids: Optional[torch.LongTensor] = None,
|
1288 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
1289 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
1290 |
+
labels: Optional[torch.LongTensor] = None,
|
1291 |
+
use_cache: Optional[bool] = None,
|
1292 |
+
output_attentions: Optional[bool] = None,
|
1293 |
+
output_hidden_states: Optional[bool] = None,
|
1294 |
+
return_dict: Optional[bool] = None,
|
1295 |
+
cache_position: Optional[torch.LongTensor] = None,
|
1296 |
+
num_logits_to_keep: int = 0,
|
1297 |
+
) -> Union[Tuple, CausalLMOutputWithPast]:
|
1298 |
+
r"""
|
1299 |
+
Args:
|
1300 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
1301 |
+
Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
|
1302 |
+
config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
|
1303 |
+
(masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
|
1304 |
+
|
1305 |
+
num_logits_to_keep (`int`, *optional*):
|
1306 |
+
Calculate logits for the last `num_logits_to_keep` tokens. If `0`, calculate logits for all
|
1307 |
+
`input_ids` (special case). Only last token logits are needed for generation, and calculating them only for that
|
1308 |
+
token can save memory, which becomes pretty significant for long sequences or large vocabulary size.
|
1309 |
+
|
1310 |
+
Returns:
|
1311 |
+
|
1312 |
+
Example:
|
1313 |
+
|
1314 |
+
```python
|
1315 |
+
>>> from transformers import AutoTokenizer, PhiForCausalLM
|
1316 |
+
|
1317 |
+
>>> model = PhiForCausalLM.from_pretrained("microsoft/phi-1")
|
1318 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("microsoft/phi-1")
|
1319 |
+
|
1320 |
+
>>> prompt = "This is an example script ."
|
1321 |
+
>>> inputs = tokenizer(prompt, return_tensors="pt")
|
1322 |
+
|
1323 |
+
>>> # Generate
|
1324 |
+
>>> generate_ids = model.generate(inputs.input_ids, max_length=30)
|
1325 |
+
>>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
|
1326 |
+
'This is an example script .\n\n\n\nfrom typing import List\n\ndef find_most_common_letter(words: List[str'
|
1327 |
+
```"""
|
1328 |
+
|
1329 |
+
output_attentions = (
|
1330 |
+
output_attentions
|
1331 |
+
if output_attentions is not None
|
1332 |
+
else self.config.output_attentions
|
1333 |
+
)
|
1334 |
+
output_hidden_states = (
|
1335 |
+
output_hidden_states
|
1336 |
+
if output_hidden_states is not None
|
1337 |
+
else self.config.output_hidden_states
|
1338 |
+
)
|
1339 |
+
return_dict = (
|
1340 |
+
return_dict if return_dict is not None else self.config.use_return_dict
|
1341 |
+
)
|
1342 |
+
|
1343 |
+
# decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
|
1344 |
+
outputs = self.transformer(
|
1345 |
+
input_ids=input_ids,
|
1346 |
+
attention_mask=attention_mask,
|
1347 |
+
position_ids=position_ids,
|
1348 |
+
past_key_values=past_key_values,
|
1349 |
+
inputs_embeds=inputs_embeds,
|
1350 |
+
use_cache=use_cache,
|
1351 |
+
output_attentions=output_attentions,
|
1352 |
+
output_hidden_states=output_hidden_states,
|
1353 |
+
return_dict=return_dict,
|
1354 |
+
cache_position=cache_position,
|
1355 |
+
)
|
1356 |
+
|
1357 |
+
hidden_states = outputs[0]
|
1358 |
+
logits = self.lm_head(hidden_states[:, -num_logits_to_keep:, :]).float()
|
1359 |
+
|
1360 |
+
loss = None
|
1361 |
+
if labels is not None:
|
1362 |
+
# Upcast to float if we need to compute the loss to avoid potential precision issues
|
1363 |
+
logits = logits.float()
|
1364 |
+
# Shift so that tokens < n predict n
|
1365 |
+
shift_logits = logits[..., :-1, :].contiguous()
|
1366 |
+
shift_labels = labels[..., 1:].contiguous()
|
1367 |
+
# Flatten the tokens
|
1368 |
+
loss_fct = CrossEntropyLoss()
|
1369 |
+
shift_logits = shift_logits.view(-1, self.config.vocab_size)
|
1370 |
+
shift_labels = shift_labels.view(-1)
|
1371 |
+
# Enable model parallelism
|
1372 |
+
shift_labels = shift_labels.to(shift_logits.device)
|
1373 |
+
loss = loss_fct(shift_logits, shift_labels)
|
1374 |
+
|
1375 |
+
if not return_dict:
|
1376 |
+
output = (logits,) + outputs[1:]
|
1377 |
+
return (loss,) + output if loss is not None else output
|
1378 |
+
|
1379 |
+
return CausalLMOutputWithPast(
|
1380 |
+
loss=loss,
|
1381 |
+
logits=logits,
|
1382 |
+
past_key_values=outputs.past_key_values,
|
1383 |
+
hidden_states=outputs.hidden_states,
|
1384 |
+
attentions=outputs.attentions,
|
1385 |
+
)
|
1386 |
+
|
1387 |
+
# Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.prepare_inputs_for_generation
|
1388 |
+
def prepare_inputs_for_generation(
|
1389 |
+
self,
|
1390 |
+
input_ids,
|
1391 |
+
past_key_values=None,
|
1392 |
+
attention_mask=None,
|
1393 |
+
inputs_embeds=None,
|
1394 |
+
cache_position=None,
|
1395 |
+
position_ids=None,
|
1396 |
+
use_cache=True,
|
1397 |
+
num_logits_to_keep=0,
|
1398 |
+
**kwargs,
|
1399 |
+
):
|
1400 |
+
# If we have cache: let's slice `input_ids` through `cache_position`, to keep only the unprocessed tokens
|
1401 |
+
# Exception 1: when passing input_embeds, input_ids may be missing entries
|
1402 |
+
# Exception 2: some generation methods do special slicing of input_ids, so we don't need to do it here
|
1403 |
+
if past_key_values is not None:
|
1404 |
+
if inputs_embeds is not None: # Exception 1
|
1405 |
+
input_ids = input_ids[:, -cache_position.shape[0] :]
|
1406 |
+
elif (
|
1407 |
+
input_ids.shape[1] != cache_position.shape[0]
|
1408 |
+
): # Default case (the "else", a no op, is Exception 2)
|
1409 |
+
input_ids = input_ids[:, cache_position]
|
1410 |
+
|
1411 |
+
if attention_mask is not None and position_ids is None:
|
1412 |
+
# create position_ids on the fly for batch generation
|
1413 |
+
position_ids = attention_mask.long().cumsum(-1) - 1
|
1414 |
+
position_ids.masked_fill_(attention_mask == 0, 1)
|
1415 |
+
if past_key_values:
|
1416 |
+
position_ids = position_ids[:, -input_ids.shape[1] :]
|
1417 |
+
|
1418 |
+
# This `clone` call is needed to avoid recapturing cuda graphs with `torch.compile`'s `mode="reduce-overhead`, as otherwise the input `position_ids` would have various stride during the decoding. Here, simply using `.contiguous()` is not sufficient as in the batch size = 1 case, `position_ids` is already contiguous but with varying stride which retriggers a capture.
|
1419 |
+
position_ids = position_ids.clone(memory_format=torch.contiguous_format)
|
1420 |
+
|
1421 |
+
# if `inputs_embeds` are passed, we only want to use them in the 1st generation step
|
1422 |
+
if inputs_embeds is not None and cache_position[0] == 0:
|
1423 |
+
model_inputs = {"inputs_embeds": inputs_embeds, "input_ids": None}
|
1424 |
+
else:
|
1425 |
+
# The clone here is for the same reason as for `position_ids`.
|
1426 |
+
model_inputs = {
|
1427 |
+
"input_ids": input_ids.clone(memory_format=torch.contiguous_format),
|
1428 |
+
"inputs_embeds": None,
|
1429 |
+
}
|
1430 |
+
|
1431 |
+
if isinstance(past_key_values, StaticCache) and attention_mask.ndim == 2:
|
1432 |
+
if model_inputs["inputs_embeds"] is not None:
|
1433 |
+
batch_size, sequence_length, _ = model_inputs["inputs_embeds"].shape
|
1434 |
+
device = model_inputs["inputs_embeds"].device
|
1435 |
+
else:
|
1436 |
+
batch_size, sequence_length = model_inputs["input_ids"].shape
|
1437 |
+
device = model_inputs["input_ids"].device
|
1438 |
+
|
1439 |
+
dtype = self.lm_head.weight.dtype
|
1440 |
+
min_dtype = torch.finfo(dtype).min
|
1441 |
+
|
1442 |
+
attention_mask = _prepare_4d_causal_attention_mask_with_cache_position(
|
1443 |
+
attention_mask,
|
1444 |
+
sequence_length=sequence_length,
|
1445 |
+
target_length=past_key_values.get_max_length(),
|
1446 |
+
dtype=dtype,
|
1447 |
+
device=device,
|
1448 |
+
min_dtype=min_dtype,
|
1449 |
+
cache_position=cache_position,
|
1450 |
+
batch_size=batch_size,
|
1451 |
+
)
|
1452 |
+
|
1453 |
+
model_inputs.update(
|
1454 |
+
{
|
1455 |
+
"position_ids": position_ids,
|
1456 |
+
"cache_position": cache_position,
|
1457 |
+
"past_key_values": past_key_values,
|
1458 |
+
"use_cache": use_cache,
|
1459 |
+
"attention_mask": attention_mask,
|
1460 |
+
"num_logits_to_keep": num_logits_to_keep,
|
1461 |
+
}
|
1462 |
+
)
|
1463 |
+
return model_inputs
|
moondream.py
ADDED
@@ -0,0 +1,723 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
import torch.nn as nn
|
3 |
+
import random
|
4 |
+
|
5 |
+
from typing import Literal, Tuple, TypedDict, Union, Dict, Any, Optional, List
|
6 |
+
from PIL import Image
|
7 |
+
from dataclasses import dataclass
|
8 |
+
from tokenizers import Tokenizer
|
9 |
+
|
10 |
+
from .config import MoondreamConfig
|
11 |
+
from .image_crops import reconstruct_from_crops
|
12 |
+
from .vision import vision_encoder, vision_projection, prepare_crops, build_vision_model
|
13 |
+
from .text import build_text_model, text_encoder, lm_head, text_decoder
|
14 |
+
from .region import decode_coordinate, encode_coordinate, decode_size, encode_size
|
15 |
+
from .utils import remove_outlier_points
|
16 |
+
|
17 |
+
|
18 |
+
TextSamplingSettings = TypedDict(
|
19 |
+
"TextSamplingSettings",
|
20 |
+
{
|
21 |
+
"max_tokens": int,
|
22 |
+
"temperature": float,
|
23 |
+
"top_p": float,
|
24 |
+
},
|
25 |
+
total=False,
|
26 |
+
)
|
27 |
+
|
28 |
+
ObjectSamplingSettings = TypedDict(
|
29 |
+
"ObjectSamplingSettings",
|
30 |
+
{"max_objects": int},
|
31 |
+
total=False,
|
32 |
+
)
|
33 |
+
|
34 |
+
DEFAULT_MAX_TOKENS = 768
|
35 |
+
DEFAULT_TEMPERATURE = 0.5
|
36 |
+
DEFAULT_TOP_P = 0.3
|
37 |
+
DEFAULT_MAX_OBJECTS = 50
|
38 |
+
|
39 |
+
|
40 |
+
@dataclass(frozen=True)
|
41 |
+
class EncodedImage:
|
42 |
+
pos: int
|
43 |
+
caches: List[Tuple[torch.Tensor, torch.Tensor]]
|
44 |
+
|
45 |
+
|
46 |
+
class KVCache(nn.Module):
|
47 |
+
|
48 |
+
def __init__(self, n_heads, n_kv_heads, max_context, dim, device, dtype):
|
49 |
+
super().__init__()
|
50 |
+
cache_shape = (1, n_kv_heads, max_context, dim // n_heads)
|
51 |
+
self.register_buffer(
|
52 |
+
"k_cache", torch.zeros(*cache_shape, device=device, dtype=dtype)
|
53 |
+
)
|
54 |
+
self.register_buffer(
|
55 |
+
"v_cache", torch.zeros(*cache_shape, device=device, dtype=dtype)
|
56 |
+
)
|
57 |
+
|
58 |
+
def update(self, pos_ids, k, v):
|
59 |
+
kout, vout = self.k_cache, self.v_cache
|
60 |
+
kout[:, :, pos_ids, :] = k
|
61 |
+
vout[:, :, pos_ids, :] = v
|
62 |
+
return kout, vout
|
63 |
+
|
64 |
+
|
65 |
+
class MoondreamModel(nn.Module):
|
66 |
+
def __init__(self, config: MoondreamConfig, dtype=torch.float16, setup_caches=True):
|
67 |
+
super().__init__()
|
68 |
+
self.config = config
|
69 |
+
self.dtype = dtype
|
70 |
+
self.setup_caches_flag = setup_caches
|
71 |
+
|
72 |
+
self.tokenizer = Tokenizer.from_pretrained(
|
73 |
+
"vikhyatk/moondream2", revision="2025-01-09"
|
74 |
+
)
|
75 |
+
|
76 |
+
self.vision = build_vision_model(config.vision, dtype)
|
77 |
+
|
78 |
+
self.text = build_text_model(config.text, torch.int8)
|
79 |
+
|
80 |
+
# Region Model
|
81 |
+
self.region = nn.ModuleDict(
|
82 |
+
{
|
83 |
+
"coord_encoder": nn.Linear(
|
84 |
+
config.region.coord_feat_dim, config.region.dim, dtype=dtype
|
85 |
+
),
|
86 |
+
"coord_decoder": nn.ModuleDict(
|
87 |
+
{
|
88 |
+
"fc1": nn.Linear(
|
89 |
+
config.region.dim, config.region.inner_dim, dtype=dtype
|
90 |
+
),
|
91 |
+
"fc2": nn.Linear(
|
92 |
+
config.region.inner_dim,
|
93 |
+
config.region.coord_out_dim,
|
94 |
+
dtype=dtype,
|
95 |
+
),
|
96 |
+
}
|
97 |
+
),
|
98 |
+
"size_encoder": nn.Linear(
|
99 |
+
config.region.size_feat_dim, config.region.dim, dtype=dtype
|
100 |
+
),
|
101 |
+
"size_decoder": nn.ModuleDict(
|
102 |
+
{
|
103 |
+
"fc1": nn.Linear(
|
104 |
+
config.region.dim, config.region.inner_dim, dtype=dtype
|
105 |
+
),
|
106 |
+
"fc2": nn.Linear(
|
107 |
+
config.region.inner_dim,
|
108 |
+
config.region.size_out_dim,
|
109 |
+
dtype=dtype,
|
110 |
+
),
|
111 |
+
}
|
112 |
+
),
|
113 |
+
}
|
114 |
+
)
|
115 |
+
self.region.coord_features = nn.Parameter(
|
116 |
+
torch.empty(config.region.coord_feat_dim // 2, 1, dtype=dtype).T
|
117 |
+
)
|
118 |
+
self.region.size_features = nn.Parameter(
|
119 |
+
torch.empty(config.region.size_feat_dim // 2, 2, dtype=dtype).T
|
120 |
+
)
|
121 |
+
|
122 |
+
attn_mask = torch.tril(
|
123 |
+
torch.ones(
|
124 |
+
1, 1, config.text.max_context, config.text.max_context, dtype=torch.bool
|
125 |
+
)
|
126 |
+
)
|
127 |
+
patch_w = config.vision.crop_size // config.vision.enc_patch_size
|
128 |
+
prefix_attn_len = 1 + patch_w**2
|
129 |
+
attn_mask[..., :prefix_attn_len, :prefix_attn_len] = 1
|
130 |
+
self.register_buffer("attn_mask", attn_mask, persistent=False)
|
131 |
+
|
132 |
+
def _setup_caches(self):
|
133 |
+
"""Setup KV caches for the text model"""
|
134 |
+
if self.text is None:
|
135 |
+
return # Can't set up caches without text model
|
136 |
+
|
137 |
+
c = self.config.text
|
138 |
+
for b in self.text.blocks:
|
139 |
+
b.kv_cache = KVCache(
|
140 |
+
c.n_heads,
|
141 |
+
c.n_kv_heads,
|
142 |
+
c.max_context,
|
143 |
+
c.dim,
|
144 |
+
device=self.device,
|
145 |
+
dtype=self.vision.pos_emb.dtype,
|
146 |
+
)
|
147 |
+
|
148 |
+
@property
|
149 |
+
def device(self):
|
150 |
+
return self.vision.pos_emb.device
|
151 |
+
|
152 |
+
def _vis_enc(self, x: torch.Tensor):
|
153 |
+
return vision_encoder(x, self.vision, self.config.vision)
|
154 |
+
|
155 |
+
def _vis_proj(self, g: torch.Tensor, r: torch.Tensor):
|
156 |
+
return vision_projection(g, r, self.vision, self.config.vision)
|
157 |
+
|
158 |
+
def _prefill(self, x: torch.Tensor, attn_mask: torch.Tensor, pos_ids: torch.Tensor):
|
159 |
+
return text_decoder(x, self.text, attn_mask, pos_ids, self.config.text)
|
160 |
+
|
161 |
+
def _decode_one_tok(
|
162 |
+
self, x: torch.Tensor, attn_mask: torch.Tensor, pos_ids: torch.Tensor
|
163 |
+
):
|
164 |
+
hidden = text_decoder(x, self.text, attn_mask, pos_ids, self.config.text)
|
165 |
+
logits = lm_head(hidden, self.text)
|
166 |
+
return logits, hidden
|
167 |
+
|
168 |
+
def compile(self):
|
169 |
+
# TODO: vision_projection is not being compiled
|
170 |
+
self._vis_enc = torch.compile(
|
171 |
+
self._vis_enc, fullgraph=False, mode="reduce-overhead"
|
172 |
+
)
|
173 |
+
self._prefill = torch.compile(self._prefill)
|
174 |
+
self._decode_one_tok = torch.compile(self._decode_one_tok)
|
175 |
+
|
176 |
+
def _run_vision_encoder(self, image: Image.Image) -> torch.Tensor:
|
177 |
+
all_crops, tiling = prepare_crops(image, self.config.vision, device=self.device)
|
178 |
+
torch._dynamo.mark_dynamic(all_crops, 0)
|
179 |
+
|
180 |
+
outputs = self._vis_enc(all_crops)
|
181 |
+
|
182 |
+
global_features = outputs[0]
|
183 |
+
local_features = outputs[1:].view(
|
184 |
+
-1,
|
185 |
+
self.config.vision.enc_n_layers,
|
186 |
+
self.config.vision.enc_n_layers,
|
187 |
+
self.config.vision.enc_dim,
|
188 |
+
)
|
189 |
+
|
190 |
+
reconstructed = reconstruct_from_crops(
|
191 |
+
local_features,
|
192 |
+
tiling,
|
193 |
+
patch_size=1,
|
194 |
+
overlap_margin=self.config.vision.overlap_margin,
|
195 |
+
)
|
196 |
+
|
197 |
+
return self._vis_proj(global_features, reconstructed)
|
198 |
+
|
199 |
+
def encode_image(self, image: Union[Image.Image, EncodedImage]) -> EncodedImage:
|
200 |
+
if isinstance(image, EncodedImage):
|
201 |
+
return image
|
202 |
+
elif not isinstance(image, Image.Image):
|
203 |
+
raise ValueError("image must be a PIL Image or EncodedImage")
|
204 |
+
|
205 |
+
# Run through text model in addition to the vision encoder, to minimize
|
206 |
+
# re-computation if multiple queries are performed on this image.
|
207 |
+
|
208 |
+
with torch.inference_mode():
|
209 |
+
img_emb = self._run_vision_encoder(image)
|
210 |
+
bos_emb = text_encoder(
|
211 |
+
torch.tensor([[self.config.tokenizer.bos_id]], device=self.device),
|
212 |
+
self.text,
|
213 |
+
)
|
214 |
+
inputs_embeds = torch.cat([bos_emb, img_emb[None]], dim=1)
|
215 |
+
mask = self.attn_mask[:, :, 0 : inputs_embeds.size(1), :]
|
216 |
+
pos_ids = torch.arange(inputs_embeds.size(1), dtype=torch.long)
|
217 |
+
self._prefill(inputs_embeds, mask, pos_ids)
|
218 |
+
|
219 |
+
return EncodedImage(
|
220 |
+
pos=inputs_embeds.size(1),
|
221 |
+
caches=[
|
222 |
+
(
|
223 |
+
b.kv_cache.k_cache[:, :, : inputs_embeds.size(1), :].clone(),
|
224 |
+
b.kv_cache.v_cache[:, :, : inputs_embeds.size(1), :].clone(),
|
225 |
+
)
|
226 |
+
for b in self.text.blocks
|
227 |
+
],
|
228 |
+
)
|
229 |
+
|
230 |
+
def _apply_top_p(self, probs: torch.Tensor, top_p: float):
|
231 |
+
probs_sort, probs_idx = torch.sort(probs, dim=-1, descending=True)
|
232 |
+
probs_sum = torch.cumsum(probs_sort, dim=-1)
|
233 |
+
mask = probs_sum - probs_sort > top_p
|
234 |
+
probs_sort[mask] = 0.0
|
235 |
+
probs_sort.div_(probs_sort.sum(dim=-1, keepdim=True))
|
236 |
+
next_probs = torch.zeros_like(probs)
|
237 |
+
next_probs.scatter_(dim=-1, index=probs_idx, src=probs_sort)
|
238 |
+
return next_probs
|
239 |
+
|
240 |
+
def _prefill_prompt(
|
241 |
+
self, prompt_tokens: torch.Tensor, pos: int, temperature: float, top_p: float
|
242 |
+
):
|
243 |
+
|
244 |
+
with torch.inference_mode():
|
245 |
+
prompt_emb = text_encoder(prompt_tokens, self.text)
|
246 |
+
torch._dynamo.mark_dynamic(prompt_emb, 1)
|
247 |
+
mask = self.attn_mask[:, :, pos : pos + prompt_emb.size(1), :]
|
248 |
+
pos_ids = torch.arange(pos, pos + prompt_emb.size(1), dtype=torch.long)
|
249 |
+
hidden = self._prefill(prompt_emb, mask, pos_ids)
|
250 |
+
logits = lm_head(hidden, self.text)
|
251 |
+
|
252 |
+
if temperature == 0:
|
253 |
+
next_token = torch.argmax(logits, dim=-1).unsqueeze(1)
|
254 |
+
else:
|
255 |
+
probs = torch.softmax(logits / temperature, dim=-1)
|
256 |
+
probs = self._apply_top_p(probs, top_p)
|
257 |
+
next_token = torch.multinomial(probs, num_samples=1)
|
258 |
+
|
259 |
+
pos = pos + prompt_emb.size(1)
|
260 |
+
return logits, hidden, next_token, pos
|
261 |
+
|
262 |
+
def _generate_text(
|
263 |
+
self,
|
264 |
+
prompt_tokens: torch.Tensor,
|
265 |
+
pos: int,
|
266 |
+
settings: Optional[TextSamplingSettings] = None,
|
267 |
+
):
|
268 |
+
max_tokens = (
|
269 |
+
settings.get("max_tokens", DEFAULT_MAX_TOKENS)
|
270 |
+
if settings
|
271 |
+
else DEFAULT_MAX_TOKENS
|
272 |
+
)
|
273 |
+
temperature = (
|
274 |
+
settings.get("temperature", DEFAULT_TEMPERATURE)
|
275 |
+
if settings
|
276 |
+
else DEFAULT_TEMPERATURE
|
277 |
+
)
|
278 |
+
top_p = settings.get("top_p", DEFAULT_TOP_P) if settings else DEFAULT_TOP_P
|
279 |
+
|
280 |
+
_, _, next_token, pos = self._prefill_prompt(
|
281 |
+
prompt_tokens, pos, temperature, top_p
|
282 |
+
)
|
283 |
+
|
284 |
+
def generator(next_token, pos):
|
285 |
+
mask = torch.zeros(1, 1, 2048, device=self.device, dtype=torch.bool)
|
286 |
+
mask[:, :, :pos] = 1
|
287 |
+
pos_ids = torch.tensor([pos], device=self.device, dtype=torch.long)
|
288 |
+
generated_tokens = 0
|
289 |
+
|
290 |
+
# For properly handling token streaming with Unicode
|
291 |
+
token_cache = []
|
292 |
+
print_len = 0
|
293 |
+
|
294 |
+
while (
|
295 |
+
next_token_id := next_token.item()
|
296 |
+
) != self.config.tokenizer.eos_id and generated_tokens < max_tokens:
|
297 |
+
# Add token to our cache
|
298 |
+
token_cache.append(next_token_id)
|
299 |
+
|
300 |
+
# Decode all tokens collected so far
|
301 |
+
text = self.tokenizer.decode(token_cache)
|
302 |
+
|
303 |
+
# After a newline, we flush the cache completely
|
304 |
+
if text.endswith("\n"):
|
305 |
+
printable_text = text[print_len:]
|
306 |
+
token_cache = []
|
307 |
+
print_len = 0
|
308 |
+
if printable_text:
|
309 |
+
yield printable_text
|
310 |
+
# If the last token is a CJK character, we can safely print it
|
311 |
+
elif len(text) > 0 and _is_cjk_char(ord(text[-1])):
|
312 |
+
printable_text = text[print_len:]
|
313 |
+
print_len += len(printable_text)
|
314 |
+
if printable_text:
|
315 |
+
yield printable_text
|
316 |
+
# Otherwise, only print up to the last space to avoid cutting words
|
317 |
+
else:
|
318 |
+
last_space_idx = text.rfind(" ", print_len)
|
319 |
+
if last_space_idx >= print_len:
|
320 |
+
printable_text = text[print_len : last_space_idx + 1]
|
321 |
+
print_len += len(printable_text)
|
322 |
+
if printable_text:
|
323 |
+
yield printable_text
|
324 |
+
|
325 |
+
with torch.inference_mode():
|
326 |
+
next_emb = text_encoder(next_token, self.text)
|
327 |
+
mask[:, :, pos], pos_ids[0] = 1, pos
|
328 |
+
logits, _ = self._decode_one_tok(next_emb, mask, pos_ids)
|
329 |
+
pos += 1
|
330 |
+
|
331 |
+
if temperature == 0:
|
332 |
+
next_token = torch.argmax(logits, dim=-1).unsqueeze(1) # (1, 1)
|
333 |
+
else:
|
334 |
+
probs = torch.softmax(logits / temperature, dim=-1) # (1, V)
|
335 |
+
probs = self._apply_top_p(probs, top_p)
|
336 |
+
next_token = torch.multinomial(probs, num_samples=1) # (1, 1)
|
337 |
+
|
338 |
+
generated_tokens += 1
|
339 |
+
|
340 |
+
# Flush any remaining text in the cache
|
341 |
+
if token_cache:
|
342 |
+
text = self.tokenizer.decode(token_cache)
|
343 |
+
printable_text = text[print_len:]
|
344 |
+
if printable_text:
|
345 |
+
yield printable_text
|
346 |
+
|
347 |
+
return generator(next_token, pos)
|
348 |
+
|
349 |
+
def query(
|
350 |
+
self,
|
351 |
+
image: Union[Image.Image, EncodedImage],
|
352 |
+
question: str,
|
353 |
+
stream: bool = False,
|
354 |
+
settings: Optional[TextSamplingSettings] = None,
|
355 |
+
):
|
356 |
+
if self.config.tokenizer.templates["query"] is None:
|
357 |
+
raise NotImplementedError("Model does not support querying.")
|
358 |
+
|
359 |
+
image = self.encode_image(image)
|
360 |
+
self.load_encoded_image(image)
|
361 |
+
|
362 |
+
prompt_tokens = torch.tensor(
|
363 |
+
[
|
364 |
+
self.config.tokenizer.templates["query"]["prefix"]
|
365 |
+
+ self.tokenizer.encode(" " + question).ids
|
366 |
+
+ self.config.tokenizer.templates["query"]["suffix"]
|
367 |
+
],
|
368 |
+
device=self.device,
|
369 |
+
)
|
370 |
+
|
371 |
+
def generator():
|
372 |
+
for token in self._generate_text(prompt_tokens, image.pos, settings):
|
373 |
+
yield token
|
374 |
+
|
375 |
+
if stream:
|
376 |
+
return {"answer": generator()}
|
377 |
+
else:
|
378 |
+
return {"answer": "".join(list(generator()))}
|
379 |
+
|
380 |
+
def load_encoded_image(self, encoded_image: EncodedImage):
|
381 |
+
for b, (k, v) in zip(self.text.blocks, encoded_image.caches):
|
382 |
+
b.kv_cache.k_cache[:, :, : k.size(2), :] = k
|
383 |
+
b.kv_cache.v_cache[:, :, : v.size(2), :] = v
|
384 |
+
|
385 |
+
def caption(
|
386 |
+
self,
|
387 |
+
image: Union[Image.Image, EncodedImage],
|
388 |
+
length: Literal["normal", "short", "long"] = "normal",
|
389 |
+
stream: bool = False,
|
390 |
+
settings: Optional[TextSamplingSettings] = None,
|
391 |
+
):
|
392 |
+
if self.config.tokenizer.templates["caption"] is None:
|
393 |
+
raise NotImplementedError("Model does not support captioning.")
|
394 |
+
if length not in self.config.tokenizer.templates["caption"]:
|
395 |
+
raise ValueError(f"Model does not support caption length '{length}'.")
|
396 |
+
|
397 |
+
image = self.encode_image(image)
|
398 |
+
self.load_encoded_image(image)
|
399 |
+
|
400 |
+
prompt_tokens = torch.tensor(
|
401 |
+
[self.config.tokenizer.templates["caption"][length]], device=self.device
|
402 |
+
)
|
403 |
+
|
404 |
+
def generator():
|
405 |
+
for token in self._generate_text(prompt_tokens, image.pos, settings):
|
406 |
+
yield token
|
407 |
+
|
408 |
+
if stream:
|
409 |
+
return {"caption": generator()}
|
410 |
+
else:
|
411 |
+
return {"caption": "".join(list(generator()))}
|
412 |
+
|
413 |
+
def _generate_points(
|
414 |
+
self,
|
415 |
+
hidden: torch.Tensor,
|
416 |
+
next_token: torch.Tensor,
|
417 |
+
pos: int,
|
418 |
+
include_size: bool = True,
|
419 |
+
max_objects: int = DEFAULT_MAX_OBJECTS,
|
420 |
+
):
|
421 |
+
out = []
|
422 |
+
mask = torch.zeros(1, 1, 2048, device=self.device, dtype=torch.bool)
|
423 |
+
mask[:, :, :pos] = 1
|
424 |
+
pos_ids = torch.tensor([pos], device=self.device, dtype=torch.long)
|
425 |
+
|
426 |
+
with torch.inference_mode():
|
427 |
+
while (
|
428 |
+
next_token.item() != self.config.tokenizer.eos_id
|
429 |
+
and len(out) < max_objects
|
430 |
+
):
|
431 |
+
x_logits = decode_coordinate(hidden, self.region)
|
432 |
+
x_center = torch.argmax(x_logits, dim=-1) / x_logits.size(-1)
|
433 |
+
next_emb = encode_coordinate(
|
434 |
+
x_center.to(dtype=x_logits.dtype), self.region
|
435 |
+
).unsqueeze(0)
|
436 |
+
|
437 |
+
# Decode y-coordinate
|
438 |
+
mask[:, :, pos], pos_ids[0] = 1, pos
|
439 |
+
_, hidden = self._decode_one_tok(next_emb, mask, pos_ids)
|
440 |
+
pos += 1
|
441 |
+
y_logits = decode_coordinate(hidden, self.region)
|
442 |
+
y_center = torch.argmax(y_logits, dim=-1) / y_logits.size(-1)
|
443 |
+
next_emb = encode_coordinate(
|
444 |
+
y_center.to(dtype=y_logits.dtype), self.region
|
445 |
+
).unsqueeze(0)
|
446 |
+
|
447 |
+
# Decode size
|
448 |
+
if include_size:
|
449 |
+
mask[:, :, pos], pos_ids[0] = 1, pos
|
450 |
+
logits, hidden = self._decode_one_tok(next_emb, mask, pos_ids)
|
451 |
+
pos += 1
|
452 |
+
size_logits = decode_size(hidden, self.region)
|
453 |
+
|
454 |
+
# Get bin indices from the logits
|
455 |
+
w_bin = torch.argmax(size_logits[0], dim=-1)
|
456 |
+
h_bin = torch.argmax(size_logits[1], dim=-1)
|
457 |
+
|
458 |
+
# Convert from bin indices to actual size values using the inverse of the log-scale mapping
|
459 |
+
# Formula: size = 2^((bin / 1023.0) * 10.0 - 10.0)
|
460 |
+
w = torch.pow(2.0, (w_bin.float() / 1023.0) * 10.0 - 10.0)
|
461 |
+
h = torch.pow(2.0, (h_bin.float() / 1023.0) * 10.0 - 10.0)
|
462 |
+
|
463 |
+
next_emb = (
|
464 |
+
encode_size(
|
465 |
+
torch.tensor(
|
466 |
+
[w, h], device=self.device, dtype=size_logits.dtype
|
467 |
+
),
|
468 |
+
self.region,
|
469 |
+
)
|
470 |
+
.unsqueeze(0)
|
471 |
+
.unsqueeze(0)
|
472 |
+
)
|
473 |
+
|
474 |
+
# Add object
|
475 |
+
out.append(
|
476 |
+
{
|
477 |
+
"x_min": x_center.item() - w.item() / 2,
|
478 |
+
"y_min": y_center.item() - h.item() / 2,
|
479 |
+
"x_max": x_center.item() + w.item() / 2,
|
480 |
+
"y_max": y_center.item() + h.item() / 2,
|
481 |
+
}
|
482 |
+
)
|
483 |
+
else:
|
484 |
+
out.append({"x": x_center.item(), "y": y_center.item()})
|
485 |
+
|
486 |
+
# Decode next token (x-coordinate, or eos)
|
487 |
+
mask[:, :, pos], pos_ids[0] = 1, pos
|
488 |
+
logits, hidden = self._decode_one_tok(next_emb, mask, pos_ids)
|
489 |
+
pos += 1
|
490 |
+
next_token = torch.argmax(logits, dim=-1)
|
491 |
+
|
492 |
+
return out
|
493 |
+
|
494 |
+
def detect(
|
495 |
+
self,
|
496 |
+
image: Union[Image.Image, EncodedImage],
|
497 |
+
object: str,
|
498 |
+
settings: Optional[ObjectSamplingSettings] = None,
|
499 |
+
):
|
500 |
+
if self.config.tokenizer.templates["detect"] is None:
|
501 |
+
raise NotImplementedError("Model does not support object detection.")
|
502 |
+
|
503 |
+
image = self.encode_image(image)
|
504 |
+
self.load_encoded_image(image)
|
505 |
+
|
506 |
+
prompt_tokens = torch.tensor(
|
507 |
+
[
|
508 |
+
self.config.tokenizer.templates["detect"]["prefix"]
|
509 |
+
+ self.tokenizer.encode(" " + object).ids
|
510 |
+
+ self.config.tokenizer.templates["detect"]["suffix"]
|
511 |
+
],
|
512 |
+
device=self.device,
|
513 |
+
)
|
514 |
+
|
515 |
+
_, hidden, next_token, pos = self._prefill_prompt(
|
516 |
+
prompt_tokens, image.pos, temperature=0, top_p=0
|
517 |
+
)
|
518 |
+
hidden = hidden[:, -1:, :]
|
519 |
+
|
520 |
+
max_objects = (
|
521 |
+
settings.get("max_objects", DEFAULT_MAX_OBJECTS)
|
522 |
+
if settings
|
523 |
+
else DEFAULT_MAX_OBJECTS
|
524 |
+
)
|
525 |
+
objects = self._generate_points(
|
526 |
+
hidden, next_token, pos, include_size=True, max_objects=max_objects
|
527 |
+
)
|
528 |
+
|
529 |
+
return {"objects": objects}
|
530 |
+
|
531 |
+
def point(
|
532 |
+
self,
|
533 |
+
image: Union[Image.Image, EncodedImage],
|
534 |
+
object: str,
|
535 |
+
settings: Optional[ObjectSamplingSettings] = None,
|
536 |
+
):
|
537 |
+
if self.config.tokenizer.templates["point"] is None:
|
538 |
+
raise NotImplementedError("Model does not support pointing.")
|
539 |
+
|
540 |
+
image = self.encode_image(image)
|
541 |
+
self.load_encoded_image(image)
|
542 |
+
|
543 |
+
prompt_tokens = torch.tensor(
|
544 |
+
[
|
545 |
+
self.config.tokenizer.templates["point"]["prefix"]
|
546 |
+
+ self.tokenizer.encode(" " + object).ids
|
547 |
+
+ self.config.tokenizer.templates["point"]["suffix"]
|
548 |
+
],
|
549 |
+
device=self.device,
|
550 |
+
)
|
551 |
+
|
552 |
+
_, hidden, next_token, pos = self._prefill_prompt(
|
553 |
+
prompt_tokens, image.pos, temperature=0, top_p=0
|
554 |
+
)
|
555 |
+
hidden = hidden[:, -1:, :]
|
556 |
+
|
557 |
+
max_objects = (
|
558 |
+
settings.get("max_objects", DEFAULT_MAX_OBJECTS)
|
559 |
+
if settings
|
560 |
+
else DEFAULT_MAX_OBJECTS
|
561 |
+
)
|
562 |
+
objects = self._generate_points(
|
563 |
+
hidden, next_token, pos, include_size=False, max_objects=max_objects
|
564 |
+
)
|
565 |
+
|
566 |
+
return {"points": objects}
|
567 |
+
|
568 |
+
def _detect_gaze(
|
569 |
+
self,
|
570 |
+
image: EncodedImage,
|
571 |
+
source: Tuple[float, float],
|
572 |
+
force_detect: bool = False,
|
573 |
+
):
|
574 |
+
with torch.inference_mode():
|
575 |
+
before_emb = text_encoder(
|
576 |
+
torch.tensor(
|
577 |
+
[self.tokenizer.encode("\n\nPoint:").ids], device=self.device
|
578 |
+
),
|
579 |
+
self.text,
|
580 |
+
)
|
581 |
+
after_emb = text_encoder(
|
582 |
+
torch.tensor(
|
583 |
+
[self.tokenizer.encode(" gaze\n\n").ids], device=self.device
|
584 |
+
),
|
585 |
+
self.text,
|
586 |
+
)
|
587 |
+
x_emb = encode_coordinate(
|
588 |
+
torch.tensor([[[source[0]]]], device=self.device, dtype=torch.float16),
|
589 |
+
self.region,
|
590 |
+
)
|
591 |
+
y_emb = encode_coordinate(
|
592 |
+
torch.tensor([[[source[1]]]], device=self.device, dtype=torch.float16),
|
593 |
+
self.region,
|
594 |
+
)
|
595 |
+
|
596 |
+
prompt_emb = torch.cat([before_emb, x_emb, y_emb, after_emb], dim=1)
|
597 |
+
|
598 |
+
self.load_encoded_image(image)
|
599 |
+
|
600 |
+
mask = self.attn_mask[:, :, image.pos : image.pos + prompt_emb.size(1), :]
|
601 |
+
pos_ids = torch.arange(
|
602 |
+
image.pos, image.pos + prompt_emb.size(1), dtype=torch.long
|
603 |
+
)
|
604 |
+
hidden = self._prefill(prompt_emb, mask, pos_ids)
|
605 |
+
logits = lm_head(hidden, self.text)
|
606 |
+
next_token = torch.argmax(logits, dim=-1)
|
607 |
+
pos = image.pos + prompt_emb.size(1)
|
608 |
+
hidden = hidden[:, -1:, :]
|
609 |
+
|
610 |
+
if force_detect:
|
611 |
+
next_token = torch.tensor([[0]], device=self.device)
|
612 |
+
|
613 |
+
if next_token.item() == self.config.tokenizer.eos_id:
|
614 |
+
return None
|
615 |
+
|
616 |
+
gaze = self._generate_points(
|
617 |
+
hidden, next_token, pos, include_size=False, max_objects=1
|
618 |
+
)
|
619 |
+
return gaze[0]
|
620 |
+
|
621 |
+
def detect_gaze(
|
622 |
+
self,
|
623 |
+
image: Union[Image.Image, EncodedImage],
|
624 |
+
eye: Optional[Tuple[float, float]] = None,
|
625 |
+
face: Optional[Dict[str, float]] = None,
|
626 |
+
unstable_settings: Dict[str, Any] = {},
|
627 |
+
):
|
628 |
+
if "force_detect" in unstable_settings:
|
629 |
+
force_detect = unstable_settings["force_detect"]
|
630 |
+
else:
|
631 |
+
force_detect = False
|
632 |
+
|
633 |
+
if "prioritize_accuracy" in unstable_settings:
|
634 |
+
prioritize_accuracy = unstable_settings["prioritize_accuracy"]
|
635 |
+
else:
|
636 |
+
prioritize_accuracy = False
|
637 |
+
|
638 |
+
if not prioritize_accuracy:
|
639 |
+
if eye is None:
|
640 |
+
raise ValueError("eye must be provided when prioritize_accuracy=False")
|
641 |
+
image = self.encode_image(image)
|
642 |
+
return {"gaze": self._detect_gaze(image, eye, force_detect=force_detect)}
|
643 |
+
else:
|
644 |
+
if (
|
645 |
+
not isinstance(image, Image.Image)
|
646 |
+
and "flip_enc_img" not in unstable_settings
|
647 |
+
):
|
648 |
+
raise ValueError(
|
649 |
+
"image must be a PIL Image when prioritize_accuracy=True, "
|
650 |
+
"or flip_enc_img must be provided"
|
651 |
+
)
|
652 |
+
if face is None:
|
653 |
+
raise ValueError("face must be provided when prioritize_accuracy=True")
|
654 |
+
|
655 |
+
encoded_image = self.encode_image(image)
|
656 |
+
if (
|
657 |
+
isinstance(image, Image.Image)
|
658 |
+
and "flip_enc_img" not in unstable_settings
|
659 |
+
):
|
660 |
+
flipped_pil = image.copy()
|
661 |
+
flipped_pil = flipped_pil.transpose(method=Image.FLIP_LEFT_RIGHT)
|
662 |
+
encoded_flipped_image = self.encode_image(flipped_pil)
|
663 |
+
else:
|
664 |
+
encoded_flipped_image = unstable_settings["flip_enc_img"]
|
665 |
+
|
666 |
+
N = 10
|
667 |
+
|
668 |
+
detections = [
|
669 |
+
self._detect_gaze(
|
670 |
+
encoded_image,
|
671 |
+
(
|
672 |
+
random.uniform(face["x_min"], face["x_max"]),
|
673 |
+
random.uniform(face["y_min"], face["y_max"]),
|
674 |
+
),
|
675 |
+
force_detect=force_detect,
|
676 |
+
)
|
677 |
+
for _ in range(N)
|
678 |
+
]
|
679 |
+
detections = [
|
680 |
+
(gaze["x"], gaze["y"]) for gaze in detections if gaze is not None
|
681 |
+
]
|
682 |
+
flipped_detections = [
|
683 |
+
self._detect_gaze(
|
684 |
+
encoded_flipped_image,
|
685 |
+
(
|
686 |
+
1 - random.uniform(face["x_min"], face["x_max"]),
|
687 |
+
random.uniform(face["y_min"], face["y_max"]),
|
688 |
+
),
|
689 |
+
force_detect=force_detect,
|
690 |
+
)
|
691 |
+
for _ in range(N)
|
692 |
+
]
|
693 |
+
detections.extend(
|
694 |
+
[
|
695 |
+
(1 - gaze["x"], gaze["y"])
|
696 |
+
for gaze in flipped_detections
|
697 |
+
if gaze is not None
|
698 |
+
]
|
699 |
+
)
|
700 |
+
|
701 |
+
if len(detections) < N:
|
702 |
+
return {"gaze": None}
|
703 |
+
|
704 |
+
detections = remove_outlier_points(detections)
|
705 |
+
mean_gaze = (
|
706 |
+
sum(gaze[0] for gaze in detections) / len(detections),
|
707 |
+
sum(gaze[1] for gaze in detections) / len(detections),
|
708 |
+
)
|
709 |
+
|
710 |
+
return {"gaze": {"x": mean_gaze[0], "y": mean_gaze[1]}}
|
711 |
+
|
712 |
+
|
713 |
+
def _is_cjk_char(cp):
|
714 |
+
"""Checks whether CP is the codepoint of a CJK character."""
|
715 |
+
# This defines a "chinese character" as anything in the CJK Unicode block:
|
716 |
+
# https://en.wikipedia.org/wiki/CJK_Unified_Ideographs_(Unicode_block)
|
717 |
+
if (
|
718 |
+
(cp >= 0x4E00 and cp <= 0x9FFF)
|
719 |
+
or (cp >= 0x3400 and cp <= 0x4DBF)
|
720 |
+
or (cp >= 0x2F800 and cp <= 0x2FA1F)
|
721 |
+
):
|
722 |
+
return True
|
723 |
+
return False
|
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
|
region.py
ADDED
@@ -0,0 +1,89 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
import torch.nn as nn
|
3 |
+
import math
|
4 |
+
|
5 |
+
from .layers import linear, mlp
|
6 |
+
|
7 |
+
|
8 |
+
def fourier_features(x: torch.Tensor, w: torch.Tensor) -> torch.Tensor:
|
9 |
+
"""
|
10 |
+
Applies Fourier feature mapping to input tensor x using frequency matrix w. This
|
11 |
+
projects inputs through sinusoidal functions to create higher dimensional features
|
12 |
+
that help mitigate spectral bias - the tendency of neural networks to learn
|
13 |
+
low-frequency functions more easily than high-frequency ones. By explicitly
|
14 |
+
mapping inputs to higher frequencies through sin/cos transformations, we enable
|
15 |
+
better learning of fine details and higher frequency patterns.
|
16 |
+
|
17 |
+
Args:
|
18 |
+
x: Input tensor to transform
|
19 |
+
w: Matrix of frequencies for the Fourier features transformation
|
20 |
+
|
21 |
+
Returns:
|
22 |
+
Concatenated cosine and sine transformed features as a tensor
|
23 |
+
"""
|
24 |
+
f = 2 * math.pi * x @ w
|
25 |
+
return torch.cat([f.cos(), f.sin()], dim=-1)
|
26 |
+
|
27 |
+
|
28 |
+
def encode_coordinate(coord: torch.Tensor, w: nn.Module) -> torch.Tensor:
|
29 |
+
"""
|
30 |
+
Takes as input a tensor containing a single float coordinate value (x or y)
|
31 |
+
and encodes it into hidden states for input to the text model.
|
32 |
+
|
33 |
+
Args:
|
34 |
+
coord: Tensor with single float coordinate value
|
35 |
+
|
36 |
+
Returns:
|
37 |
+
Encoded hidden states tensor for input to text model
|
38 |
+
"""
|
39 |
+
return linear(fourier_features(coord, w.coord_features), w.coord_encoder)
|
40 |
+
|
41 |
+
|
42 |
+
def decode_coordinate(hidden_state: torch.Tensor, w: nn.Module) -> torch.Tensor:
|
43 |
+
"""
|
44 |
+
Takes as input the last hidden state from the text model and outputs a single logit
|
45 |
+
representing either an x or y coordinate prediction.
|
46 |
+
|
47 |
+
Args:
|
48 |
+
hidden_state: The final hidden state tensor from the text model.
|
49 |
+
|
50 |
+
Returns:
|
51 |
+
A single logit representing the predicted coordinate value (x or y)
|
52 |
+
"""
|
53 |
+
return mlp(hidden_state, w.coord_decoder)
|
54 |
+
|
55 |
+
|
56 |
+
def encode_size(size: torch.Tensor, w: nn.Module) -> torch.Tensor:
|
57 |
+
"""
|
58 |
+
Takes a tensor containing width and height values and encodes them into
|
59 |
+
hidden states for input to the text model.
|
60 |
+
|
61 |
+
Args:
|
62 |
+
size: Tensor with two floats for width and height
|
63 |
+
|
64 |
+
Returns:
|
65 |
+
Encoded hidden states tensor for input to text model
|
66 |
+
"""
|
67 |
+
return linear(fourier_features(size, w.size_features), w.size_encoder)
|
68 |
+
|
69 |
+
|
70 |
+
def decode_size(hidden_state: torch.Tensor, w: nn.Module) -> torch.Tensor:
|
71 |
+
"""
|
72 |
+
Takes as input the last hidden state from the text model and outputs logits
|
73 |
+
for 1024 bins representing width and height in log-scale.
|
74 |
+
|
75 |
+
The bins are distributed according to the formula:
|
76 |
+
bin = (log2(size) + 10.0) / 10.0 * 1023.0
|
77 |
+
where size values are clamped to be at least 1/1024.
|
78 |
+
|
79 |
+
To convert from bin back to size:
|
80 |
+
size = 2^((bin / 1023.0) * 10.0 - 10.0)
|
81 |
+
|
82 |
+
Args:
|
83 |
+
hidden_state: The final hidden state tensor from the text model.
|
84 |
+
|
85 |
+
Returns:
|
86 |
+
A tensor containing logits for 1024 bins for width and height.
|
87 |
+
Shape is (2, 1024) where the first dimension corresponds to width and height.
|
88 |
+
"""
|
89 |
+
return mlp(hidden_state, w.size_decoder).view(2, -1)
|
region_model.py
ADDED
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
import torch.nn as nn
|
3 |
+
from .fourier_features import FourierFeatures
|
4 |
+
|
5 |
+
class RegionModel(nn.Module):
|
6 |
+
def __init__(self):
|
7 |
+
super().__init__()
|
8 |
+
|
9 |
+
self.position_features = FourierFeatures(2, 256)
|
10 |
+
self.position_encoder = nn.Linear(256, 2048)
|
11 |
+
self.size_features = FourierFeatures(2, 256)
|
12 |
+
self.size_encoder = nn.Linear(256, 2048)
|
13 |
+
|
14 |
+
self.position_decoder = nn.Linear(2048, 2)
|
15 |
+
self.size_decoder = nn.Linear(2048, 2)
|
16 |
+
self.confidence_decoder = nn.Linear(2048, 1)
|
17 |
+
|
18 |
+
def encode_position(self, position):
|
19 |
+
return self.position_encoder(self.position_features(position))
|
20 |
+
|
21 |
+
def encode_size(self, size):
|
22 |
+
return self.size_encoder(self.size_features(size))
|
23 |
+
|
24 |
+
def decode_position(self, x):
|
25 |
+
return self.position_decoder(x)
|
26 |
+
|
27 |
+
def decode_size(self, x):
|
28 |
+
return self.size_decoder(x)
|
29 |
+
|
30 |
+
def decode_confidence(self, x):
|
31 |
+
return self.confidence_decoder(x)
|
32 |
+
|
33 |
+
def encode(self, position, size):
|
34 |
+
return torch.stack(
|
35 |
+
[self.encode_position(position), self.encode_size(size)], dim=0
|
36 |
+
)
|
37 |
+
|
38 |
+
def decode(self, position_logits, size_logits):
|
39 |
+
return (
|
40 |
+
self.decode_position(position_logits),
|
41 |
+
self.decode_size(size_logits),
|
42 |
+
self.decode_confidence(size_logits),
|
43 |
+
)
|
requirements.txt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
einops
|
2 |
+
pyvips-binary==8.16.0
|
3 |
+
pyvips==2.2.3
|
rope.py
ADDED
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Ethically sourced from https://github.com/xjdr-alt/entropix
|
2 |
+
|
3 |
+
import torch
|
4 |
+
|
5 |
+
|
6 |
+
def precompute_freqs_cis(
|
7 |
+
dim: int,
|
8 |
+
end: int,
|
9 |
+
theta: float = 10000.0,
|
10 |
+
use_scaled: bool = False,
|
11 |
+
dtype: torch.dtype = torch.float32,
|
12 |
+
) -> torch.Tensor:
|
13 |
+
freqs = 1.0 / (theta ** (torch.arange(0, dim, 2, dtype=dtype)[: (dim // 2)] / dim))
|
14 |
+
t = torch.arange(end, dtype=dtype).unsqueeze(1)
|
15 |
+
freqs = t * freqs.unsqueeze(0)
|
16 |
+
freqs = torch.exp(1j * freqs)
|
17 |
+
return torch.stack([freqs.real, freqs.imag], dim=-1)
|
18 |
+
|
19 |
+
|
20 |
+
def apply_rotary_emb(
|
21 |
+
x: torch.Tensor,
|
22 |
+
freqs_cis: torch.Tensor,
|
23 |
+
position_ids: torch.Tensor,
|
24 |
+
num_heads: int,
|
25 |
+
rot_dim: int = 32,
|
26 |
+
interleave: bool = False,
|
27 |
+
) -> torch.Tensor:
|
28 |
+
assert rot_dim == freqs_cis.shape[-2] * 2
|
29 |
+
assert num_heads == x.shape[1]
|
30 |
+
|
31 |
+
x_rot, x_pass = x[..., :rot_dim], x[..., rot_dim:]
|
32 |
+
|
33 |
+
if interleave:
|
34 |
+
xq_r = x_rot.float().reshape(*x_rot.shape[:-1], -1, 2)[..., 0]
|
35 |
+
xq_i = x_rot.float().reshape(*x_rot.shape[:-1], -1, 2)[..., 1]
|
36 |
+
else:
|
37 |
+
d_q = x_rot.shape[-1] // 2
|
38 |
+
xq_r, xq_i = x_rot[..., :d_q], x_rot[..., d_q:]
|
39 |
+
|
40 |
+
freqs_cos = freqs_cis[..., 0][position_ids, :].unsqueeze(0).unsqueeze(0)
|
41 |
+
freqs_sin = freqs_cis[..., 1][position_ids, :].unsqueeze(0).unsqueeze(0)
|
42 |
+
|
43 |
+
# Complex multiplication: (a + bi) * (c + di) = (ac - bd) + (ad + bc)i
|
44 |
+
xq_out_r = xq_r * freqs_cos - xq_i * freqs_sin
|
45 |
+
xq_out_i = xq_r * freqs_sin + xq_i * freqs_cos
|
46 |
+
xq_out = torch.stack((xq_out_r, xq_out_i), dim=-1).flatten(-2)
|
47 |
+
|
48 |
+
return torch.cat([xq_out.to(x.dtype), x_pass], dim=-1)
|
special_tokens_map.json
ADDED
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"bos_token": "<|endoftext|>",
|
3 |
+
"eos_token": "<|endoftext|>",
|
4 |
+
"unk_token": "<|endoftext|>"
|
5 |
+
}
|
text.py
ADDED
@@ -0,0 +1,155 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
import torch.nn as nn
|
3 |
+
|
4 |
+
from torch.nn import functional as F
|
5 |
+
from bitblas.cache import OperatorCache
|
6 |
+
|
7 |
+
from .layers import layer_norm, mlp, Linear
|
8 |
+
from .rope import apply_rotary_emb, precompute_freqs_cis
|
9 |
+
from .config import TextConfig
|
10 |
+
|
11 |
+
|
12 |
+
def text_encoder(input_ids: torch.Tensor, w: nn.Module):
|
13 |
+
return F.embedding(input_ids, w.wte)
|
14 |
+
|
15 |
+
|
16 |
+
def attn(
|
17 |
+
x: torch.Tensor,
|
18 |
+
w: nn.Module,
|
19 |
+
freqs_cis: torch.Tensor,
|
20 |
+
kv_cache: nn.Module,
|
21 |
+
attn_mask: torch.Tensor,
|
22 |
+
n_heads: int,
|
23 |
+
n_kv_heads: int,
|
24 |
+
position_ids: torch.Tensor,
|
25 |
+
):
|
26 |
+
bsz, q_len, d_model = x.shape
|
27 |
+
head_dim = d_model // n_heads
|
28 |
+
|
29 |
+
qkv_out = w.qkv(x) # shape: (bsz, q_len, (n_heads + 2*n_kv_heads)*head_dim)
|
30 |
+
|
31 |
+
q_dim = n_heads * head_dim
|
32 |
+
kv_dim = n_kv_heads * head_dim
|
33 |
+
|
34 |
+
q = qkv_out[..., :q_dim].view(bsz, q_len, n_heads, head_dim).transpose(1, 2)
|
35 |
+
k = (
|
36 |
+
qkv_out[..., q_dim : q_dim + kv_dim]
|
37 |
+
.view(bsz, q_len, n_kv_heads, head_dim)
|
38 |
+
.transpose(1, 2)
|
39 |
+
)
|
40 |
+
v = (
|
41 |
+
qkv_out[..., q_dim + kv_dim :]
|
42 |
+
.view(bsz, q_len, n_kv_heads, head_dim)
|
43 |
+
.transpose(1, 2)
|
44 |
+
)
|
45 |
+
|
46 |
+
q = apply_rotary_emb(q, freqs_cis, position_ids, n_heads)
|
47 |
+
k = apply_rotary_emb(k, freqs_cis, position_ids, n_kv_heads)
|
48 |
+
|
49 |
+
if kv_cache is not None:
|
50 |
+
k, v = kv_cache.update(position_ids, k, v)
|
51 |
+
|
52 |
+
out = F.scaled_dot_product_attention(
|
53 |
+
q, k, v, attn_mask=attn_mask, enable_gqa=n_heads != n_kv_heads
|
54 |
+
)
|
55 |
+
out = out.transpose(1, 2).reshape(bsz, q_len, d_model)
|
56 |
+
out = w.proj(out)
|
57 |
+
return out
|
58 |
+
|
59 |
+
|
60 |
+
def text_decoder(
|
61 |
+
x: torch.Tensor,
|
62 |
+
w: nn.Module,
|
63 |
+
attn_mask: torch.Tensor,
|
64 |
+
position_ids: torch.Tensor,
|
65 |
+
config: TextConfig,
|
66 |
+
):
|
67 |
+
for i, block in enumerate(w.blocks):
|
68 |
+
l_in = layer_norm(x, block.ln)
|
69 |
+
l_attn = attn(
|
70 |
+
l_in,
|
71 |
+
block.attn,
|
72 |
+
freqs_cis=w.freqs_cis,
|
73 |
+
kv_cache=block.kv_cache,
|
74 |
+
attn_mask=attn_mask,
|
75 |
+
n_heads=config.n_heads,
|
76 |
+
n_kv_heads=config.n_kv_heads,
|
77 |
+
position_ids=position_ids,
|
78 |
+
)
|
79 |
+
|
80 |
+
l_mlp = mlp(l_in, block.mlp)
|
81 |
+
x = x + l_attn + l_mlp
|
82 |
+
|
83 |
+
return x
|
84 |
+
|
85 |
+
|
86 |
+
def lm_head(hidden_BTC: torch.Tensor, w: nn.Module):
|
87 |
+
hidden_BC = hidden_BTC[:, -1, :]
|
88 |
+
hidden_BC = layer_norm(hidden_BC, w.post_ln)
|
89 |
+
logits = w.lm_head(hidden_BC)
|
90 |
+
return logits
|
91 |
+
|
92 |
+
|
93 |
+
def build_text_model(
|
94 |
+
config: TextConfig,
|
95 |
+
linear_dtype: torch.dtype = torch.float16,
|
96 |
+
layernorm_dtype: torch.dtype = torch.float16,
|
97 |
+
) -> nn.Module:
|
98 |
+
# note : layernorm dtype is used for layernorm, lm_head and wte not just layernorm
|
99 |
+
print(
|
100 |
+
"Initializing quantized backend. This only has to run once, but may take a few minutes."
|
101 |
+
)
|
102 |
+
qkv_dim = int(config.dim * (1 + 2 * config.n_kv_heads / config.n_heads))
|
103 |
+
|
104 |
+
group_size = None
|
105 |
+
if linear_dtype == torch.int8:
|
106 |
+
|
107 |
+
group_size = config.group_size
|
108 |
+
|
109 |
+
def create_linear(in_features, out_features, dtype=linear_dtype):
|
110 |
+
# factory function for creating Linear layers so we dont have to pass everything again and again
|
111 |
+
return Linear(
|
112 |
+
in_features=in_features,
|
113 |
+
out_features=out_features,
|
114 |
+
dtype=dtype,
|
115 |
+
group_size=group_size,
|
116 |
+
)
|
117 |
+
|
118 |
+
text = nn.ModuleDict(
|
119 |
+
{
|
120 |
+
"blocks": nn.ModuleList(
|
121 |
+
[
|
122 |
+
nn.ModuleDict(
|
123 |
+
{
|
124 |
+
"ln": nn.LayerNorm(config.dim, dtype=layernorm_dtype),
|
125 |
+
"attn": nn.ModuleDict(
|
126 |
+
{
|
127 |
+
"qkv": create_linear(config.dim, qkv_dim),
|
128 |
+
"proj": create_linear(config.dim, config.dim),
|
129 |
+
}
|
130 |
+
),
|
131 |
+
"mlp": nn.ModuleDict(
|
132 |
+
{
|
133 |
+
"fc1": create_linear(config.dim, config.ff_dim),
|
134 |
+
"fc2": create_linear(config.ff_dim, config.dim),
|
135 |
+
}
|
136 |
+
),
|
137 |
+
}
|
138 |
+
)
|
139 |
+
for _ in range(config.n_layers)
|
140 |
+
]
|
141 |
+
),
|
142 |
+
"post_ln": nn.LayerNorm(config.dim, dtype=layernorm_dtype),
|
143 |
+
"lm_head": nn.Linear(config.dim, config.vocab_size, dtype=layernorm_dtype),
|
144 |
+
}
|
145 |
+
)
|
146 |
+
text.wte = nn.Parameter(
|
147 |
+
torch.empty(config.vocab_size, config.dim, dtype=layernorm_dtype)
|
148 |
+
)
|
149 |
+
text.register_buffer(
|
150 |
+
"freqs_cis",
|
151 |
+
precompute_freqs_cis(config.dim // (2 * config.n_heads), config.max_context),
|
152 |
+
persistent=False,
|
153 |
+
)
|
154 |
+
|
155 |
+
return text
|
tokenizer.json
ADDED
The diff for this file is too large to render.
See raw diff
|
|
tokenizer_config.json
ADDED
@@ -0,0 +1,323 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
}
|
utils.py
ADDED
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import numpy as np
|
2 |
+
|
3 |
+
|
4 |
+
def remove_outlier_points(points_tuples, k_nearest=2, threshold=2.0):
|
5 |
+
"""
|
6 |
+
Robust outlier detection for list of (x,y) tuples.
|
7 |
+
Only requires numpy.
|
8 |
+
|
9 |
+
Args:
|
10 |
+
points_tuples: list of (x,y) tuples
|
11 |
+
k_nearest: number of neighbors to consider
|
12 |
+
threshold: multiplier for median distance
|
13 |
+
|
14 |
+
Returns:
|
15 |
+
list: filtered list of (x,y) tuples with outliers removed
|
16 |
+
list: list of booleans indicating which points were kept (True = kept)
|
17 |
+
"""
|
18 |
+
points = np.array(points_tuples)
|
19 |
+
n_points = len(points)
|
20 |
+
|
21 |
+
# Calculate pairwise distances manually
|
22 |
+
dist_matrix = np.zeros((n_points, n_points))
|
23 |
+
for i in range(n_points):
|
24 |
+
for j in range(i + 1, n_points):
|
25 |
+
# Euclidean distance between points i and j
|
26 |
+
dist = np.sqrt(np.sum((points[i] - points[j]) ** 2))
|
27 |
+
dist_matrix[i, j] = dist
|
28 |
+
dist_matrix[j, i] = dist
|
29 |
+
|
30 |
+
# Get k nearest neighbors' distances
|
31 |
+
k = min(k_nearest, n_points - 1)
|
32 |
+
neighbor_distances = np.partition(dist_matrix, k, axis=1)[:, :k]
|
33 |
+
avg_neighbor_dist = np.mean(neighbor_distances, axis=1)
|
34 |
+
|
35 |
+
# Calculate mask using median distance
|
36 |
+
median_dist = np.median(avg_neighbor_dist)
|
37 |
+
mask = avg_neighbor_dist <= threshold * median_dist
|
38 |
+
|
39 |
+
# Return filtered tuples and mask
|
40 |
+
filtered_tuples = [t for t, m in zip(points_tuples, mask) if m]
|
41 |
+
return filtered_tuples
|
versions.txt
ADDED
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
2024-03-04
|
2 |
+
2024-03-06
|
3 |
+
2024-03-13
|
4 |
+
2024-04-02
|
5 |
+
2024-05-08
|
6 |
+
2024-05-20
|
7 |
+
2024-07-23
|
8 |
+
2024-08-26
|
9 |
+
2025-01-09
|
10 |
+
2025-03-27
|
11 |
+
2025-04-14
|
vision.py
ADDED
@@ -0,0 +1,147 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
import torch.nn as nn
|
3 |
+
import torch.nn.functional as F
|
4 |
+
import numpy as np
|
5 |
+
|
6 |
+
from typing import Union, Tuple
|
7 |
+
from PIL import Image
|
8 |
+
|
9 |
+
from .layers import attn, layer_norm, linear, mlp
|
10 |
+
from .image_crops import overlap_crop_image
|
11 |
+
from .config import VisionConfig
|
12 |
+
|
13 |
+
if torch.backends.mps.is_available():
|
14 |
+
# Non-divisible input sizes are not implemented on MPS device yet.
|
15 |
+
# https://github.com/pytorch/pytorch/issues/96056
|
16 |
+
def adaptive_avg_pool2d(input, output_size):
|
17 |
+
return F.adaptive_avg_pool2d(input.to("cpu"), output_size).to("mps")
|
18 |
+
|
19 |
+
else:
|
20 |
+
adaptive_avg_pool2d = F.adaptive_avg_pool2d
|
21 |
+
|
22 |
+
DeviceLike = Union[str, torch.device, int]
|
23 |
+
|
24 |
+
|
25 |
+
def prepare_crops(
|
26 |
+
image: Image.Image, config: VisionConfig, device: DeviceLike
|
27 |
+
) -> Tuple[torch.Tensor, Tuple[int, int]]:
|
28 |
+
np_image = np.array(image.convert("RGB"))
|
29 |
+
overlap_crops = overlap_crop_image(
|
30 |
+
np_image, max_crops=config.max_crops, overlap_margin=config.overlap_margin
|
31 |
+
)
|
32 |
+
all_crops = overlap_crops["crops"]
|
33 |
+
all_crops = np.transpose(all_crops, (0, 3, 1, 2))
|
34 |
+
all_crops = (
|
35 |
+
torch.from_numpy(all_crops)
|
36 |
+
.to(device=device, dtype=torch.float16)
|
37 |
+
.div_(255.0)
|
38 |
+
.sub_(0.5)
|
39 |
+
.div_(0.5)
|
40 |
+
)
|
41 |
+
return all_crops, overlap_crops["tiling"]
|
42 |
+
|
43 |
+
|
44 |
+
def create_patches(x, patch_size):
|
45 |
+
# Original shape: [B, C, H, W]
|
46 |
+
B, C, H, W = x.shape
|
47 |
+
P1 = P2 = patch_size
|
48 |
+
|
49 |
+
# Step 1: Split H and W dimensions into patches
|
50 |
+
# [B, C, H/P1, P1, W/P2, P2]
|
51 |
+
x = x.reshape(B, C, H // P1, P1, W // P2, P2)
|
52 |
+
|
53 |
+
# Step 2: Rearrange dimensions to match target shape
|
54 |
+
# [B, H/P1, W/P2, C, P1, P2]
|
55 |
+
x = x.permute(0, 2, 4, 1, 3, 5)
|
56 |
+
|
57 |
+
# Step 3: Combine dimensions to get final shape
|
58 |
+
# [B, (H/P1)*(W/P2), C*P1*P2]
|
59 |
+
x = x.reshape(B, (H // P1) * (W // P2), C * P1 * P2)
|
60 |
+
|
61 |
+
return x
|
62 |
+
|
63 |
+
|
64 |
+
def vision_encoder(input_BCHW: torch.Tensor, w: nn.Module, config: VisionConfig):
|
65 |
+
x = create_patches(input_BCHW, config.enc_patch_size)
|
66 |
+
|
67 |
+
x = linear(x, w.patch_emb)
|
68 |
+
x = x + w.pos_emb
|
69 |
+
for block in w.blocks:
|
70 |
+
x = x + attn(layer_norm(x, block.ln1), block.attn, n_heads=config.enc_n_heads)
|
71 |
+
x = x + mlp(layer_norm(x, block.ln2), block.mlp)
|
72 |
+
x = layer_norm(x, w.post_ln)
|
73 |
+
|
74 |
+
return x
|
75 |
+
|
76 |
+
|
77 |
+
def vision_projection(
|
78 |
+
global_features: torch.Tensor,
|
79 |
+
reconstructed: torch.Tensor,
|
80 |
+
w: nn.Module,
|
81 |
+
config: VisionConfig,
|
82 |
+
):
|
83 |
+
reconstructed = reconstructed.permute(2, 0, 1)
|
84 |
+
reconstructed = adaptive_avg_pool2d(
|
85 |
+
reconstructed, output_size=(config.enc_n_layers, config.enc_n_layers)
|
86 |
+
)
|
87 |
+
reconstructed = reconstructed.permute(1, 2, 0).view(729, config.enc_dim)
|
88 |
+
final_features = torch.cat([global_features, reconstructed], dim=-1)
|
89 |
+
return mlp(final_features, w.proj_mlp)
|
90 |
+
|
91 |
+
|
92 |
+
def build_vision_model(config: VisionConfig, dtype: torch.dtype):
|
93 |
+
patch_dim = config.enc_patch_size * config.enc_patch_size * config.in_channels
|
94 |
+
grid_size = config.crop_size // config.enc_patch_size
|
95 |
+
num_patches = grid_size * grid_size
|
96 |
+
|
97 |
+
vision = nn.ModuleDict(
|
98 |
+
{
|
99 |
+
"patch_emb": nn.Linear(patch_dim, config.enc_dim, dtype=dtype),
|
100 |
+
"blocks": nn.ModuleList(
|
101 |
+
[
|
102 |
+
nn.ModuleDict(
|
103 |
+
{
|
104 |
+
"ln1": nn.LayerNorm(config.enc_dim, dtype=dtype),
|
105 |
+
"attn": nn.ModuleDict(
|
106 |
+
{
|
107 |
+
"qkv": nn.Linear(
|
108 |
+
config.enc_dim, 3 * config.enc_dim, dtype=dtype
|
109 |
+
),
|
110 |
+
"proj": nn.Linear(
|
111 |
+
config.enc_dim, config.enc_dim, dtype=dtype
|
112 |
+
),
|
113 |
+
}
|
114 |
+
),
|
115 |
+
"ln2": nn.LayerNorm(config.enc_dim, dtype=dtype),
|
116 |
+
"mlp": nn.ModuleDict(
|
117 |
+
{
|
118 |
+
"fc1": nn.Linear(
|
119 |
+
config.enc_dim, config.enc_ff_dim, dtype=dtype
|
120 |
+
),
|
121 |
+
"fc2": nn.Linear(
|
122 |
+
config.enc_ff_dim, config.enc_dim, dtype=dtype
|
123 |
+
),
|
124 |
+
}
|
125 |
+
),
|
126 |
+
}
|
127 |
+
)
|
128 |
+
for _ in range(config.enc_n_layers)
|
129 |
+
]
|
130 |
+
),
|
131 |
+
"post_ln": nn.LayerNorm(config.enc_dim, dtype=dtype),
|
132 |
+
"proj_mlp": nn.ModuleDict(
|
133 |
+
{
|
134 |
+
"fc1": nn.Linear(
|
135 |
+
config.enc_dim * 2, config.proj_inner_dim, dtype=dtype
|
136 |
+
),
|
137 |
+
"fc2": nn.Linear(
|
138 |
+
config.proj_inner_dim, config.proj_out_dim, dtype=dtype
|
139 |
+
),
|
140 |
+
}
|
141 |
+
),
|
142 |
+
}
|
143 |
+
)
|
144 |
+
vision.pos_emb = nn.Parameter(
|
145 |
+
torch.zeros(1, num_patches, config.enc_dim, dtype=dtype)
|
146 |
+
)
|
147 |
+
return vision
|
vision_encoder.py
ADDED
@@ -0,0 +1,325 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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
|
|
weights.py
ADDED
@@ -0,0 +1,249 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import safetensors
|
2 |
+
import torch
|
3 |
+
import torch.nn as nn
|
4 |
+
import re
|
5 |
+
|
6 |
+
from contextlib import contextmanager
|
7 |
+
from typing import Callable, List
|
8 |
+
|
9 |
+
from .text import build_text_model
|
10 |
+
from .config import TextConfig
|
11 |
+
|
12 |
+
|
13 |
+
# Our custom linear has an module named linear, so we add linear to the name
|
14 |
+
def add_linear_to_key(k: str) -> str:
|
15 |
+
k = k.replace("model.", "")
|
16 |
+
if k.startswith("text.") and ".linear." not in k:
|
17 |
+
k = re.sub(
|
18 |
+
r"(attn\.(?:qkv|proj)|mlp\.fc[12])\.(weight|bias)$",
|
19 |
+
r"\1.linear.\2",
|
20 |
+
k,
|
21 |
+
)
|
22 |
+
return k
|
23 |
+
|
24 |
+
|
25 |
+
@contextmanager
|
26 |
+
def safetensors_open(safetensors_file: str):
|
27 |
+
"""
|
28 |
+
Simplify interfacing with safetensors files. Eliminates the need to ignore
|
29 |
+
type errors when using the `safe_open` function.
|
30 |
+
"""
|
31 |
+
with safetensors.safe_open(
|
32 |
+
safetensors_file, framework="pt"
|
33 |
+
) as st: # pyright: ignore
|
34 |
+
|
35 |
+
def get_tensor(name: str) -> torch.Tensor:
|
36 |
+
return st.get_tensor(name)
|
37 |
+
|
38 |
+
def get_keys() -> List[str]:
|
39 |
+
return st.keys()
|
40 |
+
|
41 |
+
get_tensor.keys = get_keys
|
42 |
+
|
43 |
+
yield get_tensor
|
44 |
+
|
45 |
+
|
46 |
+
def _load_weights(
|
47 |
+
get_tensor: Callable[[str], torch.Tensor],
|
48 |
+
model: nn.Module,
|
49 |
+
is_quantized: bool = False,
|
50 |
+
) -> None:
|
51 |
+
"""Internal function to load weights using a tensor getter function."""
|
52 |
+
model = model.to(dtype=torch.float16)
|
53 |
+
|
54 |
+
vision = model.vision
|
55 |
+
region = model.region
|
56 |
+
|
57 |
+
weight_map = {
|
58 |
+
"vision_encoder.encoder.model.visual.patch_embed.linear.weight": vision[
|
59 |
+
"patch_emb"
|
60 |
+
].weight,
|
61 |
+
"vision_encoder.encoder.model.visual.patch_embed.linear.bias": vision[
|
62 |
+
"patch_emb"
|
63 |
+
].bias,
|
64 |
+
"vision_encoder.encoder.model.visual.pos_embed": vision.pos_emb,
|
65 |
+
"vision_encoder.encoder.model.visual.norm.weight": vision["post_ln"].weight,
|
66 |
+
"vision_encoder.encoder.model.visual.norm.bias": vision["post_ln"].bias,
|
67 |
+
"vision_encoder.projection.mlp.fc1.weight": vision["proj_mlp"]["fc1"].weight,
|
68 |
+
"vision_encoder.projection.mlp.fc1.bias": vision["proj_mlp"]["fc1"].bias,
|
69 |
+
"vision_encoder.projection.mlp.fc2.weight": vision["proj_mlp"]["fc2"].weight,
|
70 |
+
"vision_encoder.projection.mlp.fc2.bias": vision["proj_mlp"]["fc2"].bias,
|
71 |
+
"text_model.transformer.embd.wte.weight": model.text.wte,
|
72 |
+
"text_model.lm_head.ln.weight": model.text["post_ln"].weight,
|
73 |
+
"text_model.lm_head.ln.bias": model.text["post_ln"].bias,
|
74 |
+
"text_model.lm_head.linear.weight": model.text["lm_head"].weight,
|
75 |
+
"text_model.lm_head.linear.bias": model.text["lm_head"].bias,
|
76 |
+
"region_model.coordinate_encoder.weight": region["coord_encoder"].weight,
|
77 |
+
"region_model.coordinate_encoder.bias": region["coord_encoder"].bias,
|
78 |
+
"region_model.coordinate_decoder.fc1.weight": region["coord_decoder"][
|
79 |
+
"fc1"
|
80 |
+
].weight,
|
81 |
+
"region_model.coordinate_decoder.fc1.bias": region["coord_decoder"]["fc1"].bias,
|
82 |
+
"region_model.coordinate_decoder.fc2.weight": region["coord_decoder"][
|
83 |
+
"fc2"
|
84 |
+
].weight,
|
85 |
+
"region_model.coordinate_decoder.fc2.bias": region["coord_decoder"]["fc2"].bias,
|
86 |
+
"region_model.size_encoder.weight": region["size_encoder"].weight,
|
87 |
+
"region_model.size_encoder.bias": region["size_encoder"].bias,
|
88 |
+
"region_model.size_decoder.fc1.weight": region["size_decoder"]["fc1"].weight,
|
89 |
+
"region_model.size_decoder.fc1.bias": region["size_decoder"]["fc1"].bias,
|
90 |
+
"region_model.size_decoder.fc2.weight": region["size_decoder"]["fc2"].weight,
|
91 |
+
"region_model.size_decoder.fc2.bias": region["size_decoder"]["fc2"].bias,
|
92 |
+
}
|
93 |
+
|
94 |
+
for i in range(len(model.vision["blocks"])):
|
95 |
+
prefix = f"vision_encoder.encoder.model.visual.blocks.{i}"
|
96 |
+
blk = model.vision["blocks"][i]
|
97 |
+
weight_map.update(
|
98 |
+
{
|
99 |
+
f"{prefix}.norm1.weight": blk["ln1"].weight,
|
100 |
+
f"{prefix}.norm1.bias": blk["ln1"].bias,
|
101 |
+
f"{prefix}.norm2.weight": blk["ln2"].weight,
|
102 |
+
f"{prefix}.norm2.bias": blk["ln2"].bias,
|
103 |
+
f"{prefix}.attn.qkv.weight": blk["attn"]["qkv"].weight,
|
104 |
+
f"{prefix}.attn.qkv.bias": blk["attn"]["qkv"].bias,
|
105 |
+
f"{prefix}.attn.proj.weight": blk["attn"]["proj"].weight,
|
106 |
+
f"{prefix}.attn.proj.bias": blk["attn"]["proj"].bias,
|
107 |
+
f"{prefix}.mlp.fc1.weight": blk["mlp"]["fc1"].weight,
|
108 |
+
f"{prefix}.mlp.fc1.bias": blk["mlp"]["fc1"].bias,
|
109 |
+
f"{prefix}.mlp.fc2.weight": blk["mlp"]["fc2"].weight,
|
110 |
+
f"{prefix}.mlp.fc2.bias": blk["mlp"]["fc2"].bias,
|
111 |
+
}
|
112 |
+
)
|
113 |
+
|
114 |
+
if not is_quantized:
|
115 |
+
for i in range(len(model.text["blocks"])):
|
116 |
+
prefix = f"text_model.transformer.h.{i}"
|
117 |
+
blk = model.text["blocks"][i]
|
118 |
+
weight_map.update(
|
119 |
+
{
|
120 |
+
f"{prefix}.ln.weight": blk["ln"].weight,
|
121 |
+
f"{prefix}.ln.bias": blk["ln"].bias,
|
122 |
+
f"{prefix}.mixer.Wqkv.weight": blk["attn"]["qkv"].weight,
|
123 |
+
f"{prefix}.mixer.Wqkv.bias": blk["attn"]["qkv"].bias,
|
124 |
+
f"{prefix}.mixer.out_proj.weight": blk["attn"]["proj"].weight,
|
125 |
+
f"{prefix}.mixer.out_proj.bias": blk["attn"]["proj"].bias,
|
126 |
+
f"{prefix}.mlp.fc1.weight": blk["mlp"]["fc1"].weight,
|
127 |
+
f"{prefix}.mlp.fc1.bias": blk["mlp"]["fc1"].bias,
|
128 |
+
f"{prefix}.mlp.fc2.weight": blk["mlp"]["fc2"].weight,
|
129 |
+
f"{prefix}.mlp.fc2.bias": blk["mlp"]["fc2"].bias,
|
130 |
+
}
|
131 |
+
)
|
132 |
+
else: # add special quantized path. this is specific to how bitblas expects weights to be loaded (.qweight)
|
133 |
+
for i in range(len(model.text["blocks"])):
|
134 |
+
prefix = f"text_model.transformer.h.{i}"
|
135 |
+
blk = model.text["blocks"][i]
|
136 |
+
weight_map.update(
|
137 |
+
{
|
138 |
+
f"{prefix}.ln.qweight": blk["ln"].weight,
|
139 |
+
f"{prefix}.ln.bias": blk["ln"].bias,
|
140 |
+
f"{prefix}.mixer.Wqkv.qweight": blk["attn"]["qkv"].weight,
|
141 |
+
f"{prefix}.mixer.Wqkv.bias": blk["attn"]["qkv"].bias,
|
142 |
+
f"{prefix}.mixer.out_proj.qweight": blk["attn"]["proj"].weight,
|
143 |
+
f"{prefix}.mixer.out_proj.bias": blk["attn"]["proj"].bias,
|
144 |
+
f"{prefix}.mlp.fc1.qweight": blk["mlp"]["fc1"].weight,
|
145 |
+
f"{prefix}.mlp.fc1.bias": blk["mlp"]["fc1"].bias,
|
146 |
+
f"{prefix}.mlp.fc2.qweight": blk["mlp"]["fc2"].weight,
|
147 |
+
f"{prefix}.mlp.fc2.bias": blk["mlp"]["fc2"].bias,
|
148 |
+
}
|
149 |
+
)
|
150 |
+
|
151 |
+
for key, tensor in weight_map.items():
|
152 |
+
tensor.data.copy_(get_tensor(key))
|
153 |
+
|
154 |
+
region.coord_features.data.copy_(
|
155 |
+
get_tensor("region_model.coordinate_features.weight").T
|
156 |
+
)
|
157 |
+
region.size_features.data.copy_(get_tensor("region_model.size_features.weight").T)
|
158 |
+
|
159 |
+
|
160 |
+
def load_weights_from_safetensors(weights_file: str, model: nn.Module) -> None:
|
161 |
+
"""Load weights from a safetensors file into a MoondreamModel instance."""
|
162 |
+
with safetensors_open(weights_file) as get_tensor:
|
163 |
+
all_keys = get_tensor.keys()
|
164 |
+
|
165 |
+
is_quantized = any(
|
166 |
+
".qweight" in key or "_quantized" in key or "quant." in key
|
167 |
+
for key in all_keys
|
168 |
+
)
|
169 |
+
|
170 |
+
if "text_model.transformer.h.0.ln.weight" in all_keys:
|
171 |
+
layernorm_dtype = get_tensor("text_model.transformer.h.0.ln.weight").dtype
|
172 |
+
else:
|
173 |
+
layernorm_dtype = torch.float16
|
174 |
+
|
175 |
+
linear_dtype = torch.int8 if is_quantized else torch.float16
|
176 |
+
|
177 |
+
model.text = build_text_model(
|
178 |
+
TextConfig, linear_dtype=linear_dtype, layernorm_dtype=layernorm_dtype
|
179 |
+
)
|
180 |
+
if model.setup_caches_flag:
|
181 |
+
model._setup_caches()
|
182 |
+
|
183 |
+
if (
|
184 |
+
"vision.blocks.0.attn.proj.bias" in all_keys
|
185 |
+
or "model.vision.blocks.0.attn.proj.bias" in all_keys
|
186 |
+
):
|
187 |
+
with safetensors_open(weights_file) as get_tensor:
|
188 |
+
tensors = {add_linear_to_key(k): get_tensor(k) for k in all_keys}
|
189 |
+
model.load_state_dict(tensors, strict=False)
|
190 |
+
else:
|
191 |
+
# Wrap the get_tensor function to handle key normalization
|
192 |
+
name_map = {k.replace("._orig_mod", ""): k for k in all_keys}
|
193 |
+
_load_weights(
|
194 |
+
lambda x: get_tensor(name_map[x]).to(dtype=torch.float16),
|
195 |
+
model,
|
196 |
+
is_quantized,
|
197 |
+
)
|
198 |
+
|
199 |
+
|
200 |
+
def load_weights_from_pt(weights_file: str, model: nn.Module) -> None:
|
201 |
+
"""Load weights from a PyTorch file into a MoondreamModel instance."""
|
202 |
+
tensors = torch.load(weights_file, map_location="cpu", weights_only=True)
|
203 |
+
all_keys = tensors.keys()
|
204 |
+
is_quantized = any(
|
205 |
+
".qweight" in key or "_quantized" in key or "quant." in key for key in all_keys
|
206 |
+
)
|
207 |
+
|
208 |
+
if "text.blocks.0.ln.weight" in all_keys:
|
209 |
+
layernorm_dtype = tensors["text.blocks.0.ln.weight"].dtype
|
210 |
+
else:
|
211 |
+
layernorm_dtype = torch.float16
|
212 |
+
|
213 |
+
linear_dtype = torch.int8 if is_quantized else torch.float16
|
214 |
+
model.text = build_text_model(
|
215 |
+
TextConfig, linear_dtype=linear_dtype, layernorm_dtype=layernorm_dtype
|
216 |
+
)
|
217 |
+
if model.setup_caches_flag:
|
218 |
+
model._setup_caches()
|
219 |
+
|
220 |
+
if (
|
221 |
+
"vision.blocks.0.attn.proj.bias" in all_keys
|
222 |
+
or "model.vision.blocks.0.attn.proj.bias" in all_keys
|
223 |
+
):
|
224 |
+
tensors = {add_linear_to_key(k): v for k, v in tensors.items()}
|
225 |
+
model.load_state_dict(tensors, strict=False)
|
226 |
+
else:
|
227 |
+
tensors = {
|
228 |
+
k.replace("._orig_mod", ""): v.to(dtype=torch.float16)
|
229 |
+
for k, v in tensors.items()
|
230 |
+
}
|
231 |
+
_load_weights(lambda x: tensors[x], model, is_quantized)
|
232 |
+
|
233 |
+
|
234 |
+
def load_weights_into_model(weights_file: str, model: nn.Module) -> None:
|
235 |
+
"""
|
236 |
+
Load weights from either a safetensors or PyTorch file directly into a MoondreamModel instance.
|
237 |
+
|
238 |
+
Args:
|
239 |
+
weights_file: Path to weights file (either .safetensors or .pt)
|
240 |
+
model: MoondreamModel instance to load weights into
|
241 |
+
"""
|
242 |
+
if weights_file.endswith(".safetensors"):
|
243 |
+
load_weights_from_safetensors(weights_file, model)
|
244 |
+
else:
|
245 |
+
load_weights_from_pt(weights_file, model)
|
246 |
+
|
247 |
+
# Make all parameters contiguous
|
248 |
+
for param in model.parameters():
|
249 |
+
param.data = param.data.contiguous()
|