Upload extensions_built_in/dataset_tools/tools/llava_utils.py with huggingface_hub
Browse files
extensions_built_in/dataset_tools/tools/llava_utils.py
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
from .caption import default_long_prompt, default_short_prompt, default_replacements, clean_caption
|
| 3 |
+
|
| 4 |
+
import torch
|
| 5 |
+
from PIL import Image, ImageOps
|
| 6 |
+
|
| 7 |
+
from transformers import AutoTokenizer, BitsAndBytesConfig, CLIPImageProcessor
|
| 8 |
+
|
| 9 |
+
img_ext = ['.jpg', '.jpeg', '.png', '.webp']
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class LLaVAImageProcessor:
|
| 13 |
+
def __init__(self, device='cuda'):
|
| 14 |
+
try:
|
| 15 |
+
from llava.model import LlavaLlamaForCausalLM
|
| 16 |
+
except ImportError:
|
| 17 |
+
# print("You need to manually install llava -> pip install --no-deps git+https://github.com/haotian-liu/LLaVA.git")
|
| 18 |
+
print(
|
| 19 |
+
"You need to manually install llava -> pip install --no-deps git+https://github.com/haotian-liu/LLaVA.git")
|
| 20 |
+
raise
|
| 21 |
+
self.device = device
|
| 22 |
+
self.model: LlavaLlamaForCausalLM = None
|
| 23 |
+
self.tokenizer: AutoTokenizer = None
|
| 24 |
+
self.image_processor: CLIPImageProcessor = None
|
| 25 |
+
self.is_loaded = False
|
| 26 |
+
|
| 27 |
+
def load_model(self):
|
| 28 |
+
from llava.model import LlavaLlamaForCausalLM
|
| 29 |
+
|
| 30 |
+
model_path = "4bit/llava-v1.5-13b-3GB"
|
| 31 |
+
# kwargs = {"device_map": "auto"}
|
| 32 |
+
kwargs = {"device_map": self.device}
|
| 33 |
+
kwargs['load_in_4bit'] = True
|
| 34 |
+
kwargs['quantization_config'] = BitsAndBytesConfig(
|
| 35 |
+
load_in_4bit=True,
|
| 36 |
+
bnb_4bit_compute_dtype=torch.float16,
|
| 37 |
+
bnb_4bit_use_double_quant=True,
|
| 38 |
+
bnb_4bit_quant_type='nf4'
|
| 39 |
+
)
|
| 40 |
+
self.model = LlavaLlamaForCausalLM.from_pretrained(model_path, low_cpu_mem_usage=True, **kwargs)
|
| 41 |
+
self.tokenizer = AutoTokenizer.from_pretrained(model_path, use_fast=False)
|
| 42 |
+
vision_tower = self.model.get_vision_tower()
|
| 43 |
+
if not vision_tower.is_loaded:
|
| 44 |
+
vision_tower.load_model()
|
| 45 |
+
vision_tower.to(device=self.device)
|
| 46 |
+
self.image_processor = vision_tower.image_processor
|
| 47 |
+
self.is_loaded = True
|
| 48 |
+
|
| 49 |
+
def generate_caption(
|
| 50 |
+
self, image:
|
| 51 |
+
Image, prompt: str = default_long_prompt,
|
| 52 |
+
replacements=default_replacements,
|
| 53 |
+
max_new_tokens=512
|
| 54 |
+
):
|
| 55 |
+
from llava.conversation import conv_templates, SeparatorStyle
|
| 56 |
+
from llava.utils import disable_torch_init
|
| 57 |
+
from llava.constants import IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_TOKEN, DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN
|
| 58 |
+
from llava.mm_utils import tokenizer_image_token, KeywordsStoppingCriteria
|
| 59 |
+
# question = "how many dogs are in the picture?"
|
| 60 |
+
disable_torch_init()
|
| 61 |
+
conv_mode = "llava_v0"
|
| 62 |
+
conv = conv_templates[conv_mode].copy()
|
| 63 |
+
roles = conv.roles
|
| 64 |
+
image_tensor = self.image_processor.preprocess([image], return_tensors='pt')['pixel_values'].half().cuda()
|
| 65 |
+
|
| 66 |
+
inp = f"{roles[0]}: {prompt}"
|
| 67 |
+
inp = DEFAULT_IM_START_TOKEN + DEFAULT_IMAGE_TOKEN + DEFAULT_IM_END_TOKEN + '\n' + inp
|
| 68 |
+
conv.append_message(conv.roles[0], inp)
|
| 69 |
+
conv.append_message(conv.roles[1], None)
|
| 70 |
+
raw_prompt = conv.get_prompt()
|
| 71 |
+
input_ids = tokenizer_image_token(raw_prompt, self.tokenizer, IMAGE_TOKEN_INDEX,
|
| 72 |
+
return_tensors='pt').unsqueeze(0).cuda()
|
| 73 |
+
stop_str = conv.sep if conv.sep_style != SeparatorStyle.TWO else conv.sep2
|
| 74 |
+
keywords = [stop_str]
|
| 75 |
+
stopping_criteria = KeywordsStoppingCriteria(keywords, self.tokenizer, input_ids)
|
| 76 |
+
with torch.inference_mode():
|
| 77 |
+
output_ids = self.model.generate(
|
| 78 |
+
input_ids, images=image_tensor, do_sample=True, temperature=0.1,
|
| 79 |
+
max_new_tokens=max_new_tokens, use_cache=True, stopping_criteria=[stopping_criteria],
|
| 80 |
+
top_p=0.8
|
| 81 |
+
)
|
| 82 |
+
outputs = self.tokenizer.decode(output_ids[0, input_ids.shape[1]:]).strip()
|
| 83 |
+
conv.messages[-1][-1] = outputs
|
| 84 |
+
output = outputs.rsplit('</s>', 1)[0]
|
| 85 |
+
return clean_caption(output, replacements=replacements)
|