initial sentence-transformers support
Browse files- config_sentence_transformers.json +13 -0
- custom_st.py +143 -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,143 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
# Initialize model
|
| 36 |
+
self.model = Qwen2VLForConditionalGeneration.from_pretrained(
|
| 37 |
+
model_name_or_path,
|
| 38 |
+
attn_implementation="flash_attention_2",
|
| 39 |
+
torch_dtype=torch.bfloat16,
|
| 40 |
+
device_map=device,
|
| 41 |
+
cache_dir=cache_dir,
|
| 42 |
+
**kwargs
|
| 43 |
+
).eval()
|
| 44 |
+
|
| 45 |
+
# Initialize processor
|
| 46 |
+
self.processor = AutoProcessor.from_pretrained(
|
| 47 |
+
processor_name_or_path or model_name_or_path,
|
| 48 |
+
min_pixels=min_pixels,
|
| 49 |
+
max_pixels=max_pixels,
|
| 50 |
+
cache_dir=cache_dir
|
| 51 |
+
)
|
| 52 |
+
|
| 53 |
+
self.model.padding_side = "left"
|
| 54 |
+
self.processor.tokenizer.padding_side = "left"
|
| 55 |
+
|
| 56 |
+
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|>"
|
| 57 |
+
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|>"
|
| 58 |
+
|
| 59 |
+
def _smart_resize(self, height: int, width: int) -> tuple[int, int]:
|
| 60 |
+
h_bar = max(28, self._round_by_factor(height, 28))
|
| 61 |
+
w_bar = max(28, self._round_by_factor(width, 28))
|
| 62 |
+
if h_bar * w_bar > self.max_pixels:
|
| 63 |
+
beta = math.sqrt((height * width) / self.max_pixels)
|
| 64 |
+
h_bar = self._floor_by_factor(height / beta, 28)
|
| 65 |
+
w_bar = self._floor_by_factor(width / beta, 28)
|
| 66 |
+
elif h_bar * w_bar < self.min_pixels:
|
| 67 |
+
beta = math.sqrt(self.min_pixels / (height * width))
|
| 68 |
+
h_bar = self._ceil_by_factor(height * beta, 28)
|
| 69 |
+
w_bar = self._ceil_by_factor(width * beta, 28)
|
| 70 |
+
return w_bar, h_bar
|
| 71 |
+
|
| 72 |
+
@staticmethod
|
| 73 |
+
def _round_by_factor(number: float, factor: int) -> int:
|
| 74 |
+
return round(number / factor) * factor
|
| 75 |
+
|
| 76 |
+
@staticmethod
|
| 77 |
+
def _ceil_by_factor(number: float, factor: int) -> int:
|
| 78 |
+
return math.ceil(number / factor) * factor
|
| 79 |
+
|
| 80 |
+
@staticmethod
|
| 81 |
+
def _floor_by_factor(number: float, factor: int) -> int:
|
| 82 |
+
return math.floor(number / factor) * factor
|
| 83 |
+
|
| 84 |
+
def _resize_image(self, image: Image.Image) -> Image.Image:
|
| 85 |
+
new_size = self._smart_resize(image.height, image.width)
|
| 86 |
+
return image.resize(new_size)
|
| 87 |
+
|
| 88 |
+
@staticmethod
|
| 89 |
+
def _decode_data_image(data_image_str: str) -> Image.Image:
|
| 90 |
+
header, data = data_image_str.split(',', 1)
|
| 91 |
+
image_data = base64.b64decode(data)
|
| 92 |
+
return Image.open(BytesIO(image_data))
|
| 93 |
+
|
| 94 |
+
def _process_input(self, texts: List[Union[str, Image.Image]]) -> tuple[List[str], List[Image.Image]]:
|
| 95 |
+
processed_texts = []
|
| 96 |
+
processed_images = []
|
| 97 |
+
dummy_image = Image.new('RGB', (56, 56))
|
| 98 |
+
|
| 99 |
+
for sample in texts:
|
| 100 |
+
if isinstance(sample, str):
|
| 101 |
+
processed_texts.append(self.query_prompt % sample)
|
| 102 |
+
processed_images.append(dummy_image)
|
| 103 |
+
elif isinstance(sample, Image.Image):
|
| 104 |
+
processed_texts.append(self.document_prompt)
|
| 105 |
+
processed_images.append(self._resize_image(sample))
|
| 106 |
+
|
| 107 |
+
return processed_texts, processed_images
|
| 108 |
+
|
| 109 |
+
def forward(self, features: Dict[str, torch.Tensor]) -> Dict[str, torch.Tensor]:
|
| 110 |
+
cache_position = torch.arange(0, features['input_ids'].shape[0])
|
| 111 |
+
inputs = self.model.prepare_inputs_for_generation(
|
| 112 |
+
**features, cache_position=cache_position, use_cache=False
|
| 113 |
+
)
|
| 114 |
+
|
| 115 |
+
with torch.no_grad():
|
| 116 |
+
output = self.model(
|
| 117 |
+
**inputs,
|
| 118 |
+
return_dict=True,
|
| 119 |
+
output_hidden_states=True
|
| 120 |
+
)
|
| 121 |
+
|
| 122 |
+
embeddings = output.hidden_states[-1][:, -1]
|
| 123 |
+
features['sentence_embedding'] = torch.nn.functional.normalize(
|
| 124 |
+
embeddings[:, :self.dimension], p=2, dim=-1
|
| 125 |
+
)
|
| 126 |
+
return features
|
| 127 |
+
|
| 128 |
+
def tokenize(self, texts: List[Union[str, Image.Image]], padding: str = 'longest') -> Dict[str, torch.Tensor]:
|
| 129 |
+
processed_texts, processed_images = self._process_input(texts)
|
| 130 |
+
|
| 131 |
+
inputs = self.processor(
|
| 132 |
+
text=processed_texts,
|
| 133 |
+
images=processed_images,
|
| 134 |
+
videos=None,
|
| 135 |
+
padding=padding,
|
| 136 |
+
return_tensors='pt'
|
| 137 |
+
)
|
| 138 |
+
|
| 139 |
+
return {k: v.to(self.device) for k, v in inputs.items()}
|
| 140 |
+
|
| 141 |
+
def save(self, output_path: str, safe_serialization: bool = True) -> None:
|
| 142 |
+
self.model.save_pretrained(output_path, safe_serialization=safe_serialization)
|
| 143 |
+
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 |
+
]
|