cheesyFishes
commited on
add back sentence-transformers files
Browse files- config_sentence_transformers.json +13 -0
- custom_st.py +153 -0
- modules.json +19 -0
config_sentence_transformers.json
ADDED
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"__version__": {
|
3 |
+
"sentence_transformers": "3.3.0",
|
4 |
+
"transformers": "4.46.2",
|
5 |
+
"pytorch": "2.2.2"
|
6 |
+
},
|
7 |
+
"prompts":{
|
8 |
+
"image": "<|im_start|>system\nYou are a helpful assistant.<|im_end|>\n<|im_start|>user\n<|vision_start|><|image_pad|><|vision_end|>What is shown in this image?<|im_end|>\n<|endoftext|>",
|
9 |
+
"query": "<|im_start|>system\nYou are a helpful assistant.<|im_end|>\n<|im_start|>user\n<|vision_start|><|image_pad|><|vision_end|>Query: %s<|im_end|>\n<|endoftext|>"
|
10 |
+
},
|
11 |
+
"default_prompt_name": null,
|
12 |
+
"similarity_fn_name": "cosine"
|
13 |
+
}
|
custom_st.py
ADDED
@@ -0,0 +1,153 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import base64
|
2 |
+
import json
|
3 |
+
import os
|
4 |
+
import math
|
5 |
+
from io import BytesIO
|
6 |
+
from typing import Any, Dict, List, Literal, Optional, Union
|
7 |
+
|
8 |
+
import requests
|
9 |
+
import torch
|
10 |
+
from PIL import Image
|
11 |
+
from torch import nn
|
12 |
+
from transformers import AutoProcessor, Qwen2VLForConditionalGeneration
|
13 |
+
|
14 |
+
class Transformer(nn.Module):
|
15 |
+
save_in_root: bool = True
|
16 |
+
|
17 |
+
def __init__(
|
18 |
+
self,
|
19 |
+
model_name_or_path: str = 'llamaindex/vdr-2b-multi-v1',
|
20 |
+
processor_name_or_path: Optional[str] = None,
|
21 |
+
max_pixels: int = 768 * 28 * 28,
|
22 |
+
min_pixels: int = 1 * 28 * 28,
|
23 |
+
dimension: int = 2048,
|
24 |
+
cache_dir: Optional[str] = None,
|
25 |
+
device: str = 'cuda:0',
|
26 |
+
**kwargs,
|
27 |
+
) -> None:
|
28 |
+
super(Transformer, self).__init__()
|
29 |
+
|
30 |
+
self.device = device
|
31 |
+
self.dimension = dimension
|
32 |
+
self.max_pixels = max_pixels
|
33 |
+
self.min_pixels = min_pixels
|
34 |
+
|
35 |
+
# Try to use flash attention if available, fallback to default attention if not
|
36 |
+
try:
|
37 |
+
self.model = Qwen2VLForConditionalGeneration.from_pretrained(
|
38 |
+
model_name_or_path,
|
39 |
+
attn_implementation="flash_attention_2",
|
40 |
+
torch_dtype=torch.bfloat16,
|
41 |
+
device_map=device,
|
42 |
+
cache_dir=cache_dir,
|
43 |
+
**kwargs
|
44 |
+
).eval()
|
45 |
+
except (ImportError, ValueError) as e:
|
46 |
+
print(f"Flash attention not available, falling back to default attention: {e}")
|
47 |
+
self.model = Qwen2VLForConditionalGeneration.from_pretrained(
|
48 |
+
model_name_or_path,
|
49 |
+
torch_dtype=torch.bfloat16,
|
50 |
+
device_map=device,
|
51 |
+
cache_dir=cache_dir,
|
52 |
+
**kwargs
|
53 |
+
).eval()
|
54 |
+
|
55 |
+
# Initialize processor
|
56 |
+
self.processor = AutoProcessor.from_pretrained(
|
57 |
+
processor_name_or_path or model_name_or_path,
|
58 |
+
min_pixels=min_pixels,
|
59 |
+
max_pixels=max_pixels,
|
60 |
+
cache_dir=cache_dir
|
61 |
+
)
|
62 |
+
|
63 |
+
self.model.padding_side = "left"
|
64 |
+
self.processor.tokenizer.padding_side = "left"
|
65 |
+
|
66 |
+
self.document_prompt = "<|im_start|>system\nYou are a helpful assistant.<|im_end|>\n<|im_start|>user\n<|vision_start|><|image_pad|><|vision_end|>What is shown in this image?<|im_end|>\n<|endoftext|>"
|
67 |
+
self.query_prompt = "<|im_start|>system\nYou are a helpful assistant.<|im_end|>\n<|im_start|>user\n<|vision_start|><|image_pad|><|vision_end|>Query: %s<|im_end|>\n<|endoftext|>"
|
68 |
+
|
69 |
+
def _smart_resize(self, height: int, width: int) -> tuple[int, int]:
|
70 |
+
h_bar = max(28, self._round_by_factor(height, 28))
|
71 |
+
w_bar = max(28, self._round_by_factor(width, 28))
|
72 |
+
if h_bar * w_bar > self.max_pixels:
|
73 |
+
beta = math.sqrt((height * width) / self.max_pixels)
|
74 |
+
h_bar = self._floor_by_factor(height / beta, 28)
|
75 |
+
w_bar = self._floor_by_factor(width / beta, 28)
|
76 |
+
elif h_bar * w_bar < self.min_pixels:
|
77 |
+
beta = math.sqrt(self.min_pixels / (height * width))
|
78 |
+
h_bar = self._ceil_by_factor(height * beta, 28)
|
79 |
+
w_bar = self._ceil_by_factor(width * beta, 28)
|
80 |
+
return w_bar, h_bar
|
81 |
+
|
82 |
+
@staticmethod
|
83 |
+
def _round_by_factor(number: float, factor: int) -> int:
|
84 |
+
return round(number / factor) * factor
|
85 |
+
|
86 |
+
@staticmethod
|
87 |
+
def _ceil_by_factor(number: float, factor: int) -> int:
|
88 |
+
return math.ceil(number / factor) * factor
|
89 |
+
|
90 |
+
@staticmethod
|
91 |
+
def _floor_by_factor(number: float, factor: int) -> int:
|
92 |
+
return math.floor(number / factor) * factor
|
93 |
+
|
94 |
+
def _resize_image(self, image: Image.Image) -> Image.Image:
|
95 |
+
new_size = self._smart_resize(image.height, image.width)
|
96 |
+
return image.resize(new_size)
|
97 |
+
|
98 |
+
@staticmethod
|
99 |
+
def _decode_data_image(data_image_str: str) -> Image.Image:
|
100 |
+
header, data = data_image_str.split(',', 1)
|
101 |
+
image_data = base64.b64decode(data)
|
102 |
+
return Image.open(BytesIO(image_data))
|
103 |
+
|
104 |
+
def _process_input(self, texts: List[Union[str, Image.Image]]) -> tuple[List[str], List[Image.Image]]:
|
105 |
+
processed_texts = []
|
106 |
+
processed_images = []
|
107 |
+
dummy_image = Image.new('RGB', (56, 56))
|
108 |
+
|
109 |
+
for sample in texts:
|
110 |
+
if isinstance(sample, str):
|
111 |
+
processed_texts.append(self.query_prompt % sample)
|
112 |
+
processed_images.append(dummy_image)
|
113 |
+
elif isinstance(sample, Image.Image):
|
114 |
+
processed_texts.append(self.document_prompt)
|
115 |
+
processed_images.append(self._resize_image(sample))
|
116 |
+
|
117 |
+
return processed_texts, processed_images
|
118 |
+
|
119 |
+
def forward(self, features: Dict[str, torch.Tensor]) -> Dict[str, torch.Tensor]:
|
120 |
+
cache_position = torch.arange(0, features['input_ids'].shape[0])
|
121 |
+
inputs = self.model.prepare_inputs_for_generation(
|
122 |
+
**features, cache_position=cache_position, use_cache=False
|
123 |
+
)
|
124 |
+
|
125 |
+
with torch.no_grad():
|
126 |
+
output = self.model(
|
127 |
+
**inputs,
|
128 |
+
return_dict=True,
|
129 |
+
output_hidden_states=True
|
130 |
+
)
|
131 |
+
|
132 |
+
embeddings = output.hidden_states[-1][:, -1]
|
133 |
+
features['sentence_embedding'] = torch.nn.functional.normalize(
|
134 |
+
embeddings[:, :self.dimension], p=2, dim=-1
|
135 |
+
)
|
136 |
+
return features
|
137 |
+
|
138 |
+
def tokenize(self, texts: List[Union[str, Image.Image]], padding: str = 'longest') -> Dict[str, torch.Tensor]:
|
139 |
+
processed_texts, processed_images = self._process_input(texts)
|
140 |
+
|
141 |
+
inputs = self.processor(
|
142 |
+
text=processed_texts,
|
143 |
+
images=processed_images,
|
144 |
+
videos=None,
|
145 |
+
padding=padding,
|
146 |
+
return_tensors='pt'
|
147 |
+
)
|
148 |
+
|
149 |
+
return {k: v.to(self.device) for k, v in inputs.items()}
|
150 |
+
|
151 |
+
def save(self, output_path: str, safe_serialization: bool = True) -> None:
|
152 |
+
self.model.save_pretrained(output_path, safe_serialization=safe_serialization)
|
153 |
+
self.processor.save_pretrained(output_path)
|
modules.json
ADDED
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
[
|
2 |
+
{
|
3 |
+
"idx": 0,
|
4 |
+
"name": "transformer",
|
5 |
+
"path": "",
|
6 |
+
"type": "custom_st.Transformer",
|
7 |
+
"model_name_or_path": "llamaindex/vdr-2b-multi-v1",
|
8 |
+
"dimension": 2048,
|
9 |
+
"max_pixels": 602112,
|
10 |
+
"min_pixels": 784,
|
11 |
+
"device": "cuda:0"
|
12 |
+
},
|
13 |
+
{
|
14 |
+
"idx": 1,
|
15 |
+
"name": "normalizer",
|
16 |
+
"path": "1_Normalize",
|
17 |
+
"type": "sentence_transformers.models.Normalize"
|
18 |
+
}
|
19 |
+
]
|