-
Notifications
You must be signed in to change notification settings - Fork 18
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
matatonic
committed
May 18, 2024
1 parent
c8d0fe3
commit fe3c8c8
Showing
10 changed files
with
213 additions
and
8 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,65 @@ | ||
from transformers import AutoTokenizer, AutoModelForCausalLM | ||
|
||
import transformers | ||
import warnings | ||
# disable some warnings | ||
transformers.logging.set_verbosity_error() | ||
warnings.filterwarnings('ignore') | ||
|
||
from vision_qna import * | ||
# "qihoo360/360VL-8B" | ||
# "qihoo360/360VL-70B" | ||
|
||
class VisionQnA(VisionQnABase): | ||
model_name: str = "360vl" | ||
format = "llama3" | ||
|
||
def __init__(self, model_id: str, device: str, device_map: str = 'auto', extra_params = {}, format = None): | ||
super().__init__(model_id, device, device_map, extra_params, format) | ||
|
||
if not format: | ||
self.format = guess_model_format(model_id) | ||
|
||
self.tokenizer = AutoTokenizer.from_pretrained(model_id, trust_remote_code=self.params.get('trust_remote_code', False)) | ||
self.model = AutoModelForCausalLM.from_pretrained(**self.params).eval() | ||
|
||
self.vision_tower = self.model.get_vision_tower() | ||
self.vision_tower.load_model() | ||
self.vision_tower.to(device=self.device, dtype=self.dtype) | ||
self.image_processor = self.vision_tower.image_processor | ||
self.tokenizer.pad_token = self.tokenizer.eos_token | ||
self.terminators = [ | ||
self.tokenizer.convert_tokens_to_ids("<|eot_id|>",) | ||
] | ||
|
||
print(f"Loaded on device: {self.model.device} with dtype: {self.model.dtype}") | ||
|
||
async def chat_with_images(self, request: ImageChatRequest) -> str: | ||
images, prompt = await llama3_prompt_from_messages(request.messages, img_tok = "<|reserved_special_token_44|>\n") | ||
|
||
default_system = "You are a multilingual, helpful, respectful and honest assistant who can respond in the same language, depending on the language of the question. Try to be as helpful as possible while still being safe. Your answer should not contain anything that is false, unhealthy, harmful, immoral, racist, sexist, toxic, dangerous, or illegal, and if the question relates to such content, please decline to answer. Make sure your answer is socially fair and positive. If a question doesn't make any sense, or is inconsistent with the facts, explain why instead of answering the wrong answer. If you don't know the answer to a question, don't share false information." | ||
|
||
input_ids = self.tokenizer.encode(prompt, return_tensors="pt") | ||
|
||
input_id_list = input_ids[0].tolist() | ||
input_id_list[input_id_list.index(128049)]=-200 | ||
input_ids = torch.tensor(input_id_list, dtype=input_ids.dtype, device=input_ids.device).unsqueeze(0) | ||
|
||
image_tensor = self.model.process_images_slid_window(images[0], self.image_processor).unsqueeze(0) | ||
|
||
default_params = dict( | ||
do_sample=False, | ||
num_beams=1, | ||
) | ||
|
||
params = self.get_generation_params(request, default_params) | ||
|
||
output_ids = self.model.generate( | ||
input_ids=input_ids.to(device=self.device, non_blocking=True), | ||
images=image_tensor.to(dtype=self.dtype, device=self.device, non_blocking=True), | ||
eos_token_id=self.terminators, | ||
**params) | ||
|
||
outputs = self.tokenizer.batch_decode(output_ids[:, input_ids.shape[1]:], skip_special_tokens=True)[0] | ||
|
||
return outputs.strip() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,75 @@ | ||
import torch | ||
from transformers import AutoTokenizer, AutoModelForCausalLM | ||
from accelerate import init_empty_weights, infer_auto_device_map, load_checkpoint_and_dispatch | ||
from huggingface_hub import snapshot_download | ||
|
||
from vision_qna import * | ||
|
||
# "BAAI/Emu2-Chat" | ||
|
||
class VisionQnA(VisionQnABase): | ||
model_name: str = 'emu' | ||
format: str = 'emu' | ||
|
||
def __init__(self, model_id: str, device: str, device_map: str = 'auto', extra_params = {}, format = None): | ||
super().__init__(model_id, device, device_map, extra_params, format) | ||
|
||
if self.params['torch_dtype'] == torch.bfloat16: | ||
self.params['torch_dtype'] = torch.float16 | ||
|
||
checkpoint = snapshot_download(model_id) | ||
with init_empty_weights(): | ||
self.model = AutoModelForCausalLM.from_pretrained(**self.params) | ||
|
||
max_memory=extra_params.get('max_memory', None) | ||
|
||
device_map = infer_auto_device_map(self.model, max_memory=max_memory, no_split_module_classes=['Block','LlamaDecoderLayer']) | ||
# input and output logits should be on same device | ||
device_map["model.decoder.lm.lm_head"] = 0 | ||
|
||
self.model = load_checkpoint_and_dispatch(self.model, checkpoint=checkpoint, device_map=device_map).eval() | ||
""" | ||
self.model = AutoModelForCausalLM.from_pretrained(**self.params).eval() | ||
""" | ||
|
||
# bitsandbytes already moves the model to the device, so we don't need to do it again. | ||
if not (extra_params.get('load_in_4bit', False) or extra_params.get('load_in_8bit', False)): | ||
self.model = self.model.to(self.device) | ||
|
||
self.tokenizer = AutoTokenizer.from_pretrained(model_id) | ||
|
||
# self.model.device/dtype are overloaded with some other object | ||
print(f"Loaded on device: {self.device} with dtype: {self.dtype}") | ||
|
||
async def chat_with_images(self, request: ImageChatRequest) -> str: | ||
images, prompt, system = await emu_images_prompt_system_from_messages(request.messages) | ||
|
||
if not system: | ||
system = "You are a helpful assistant, dedicated to delivering comprehensive and meticulous responses." | ||
|
||
prompt = system + prompt | ||
|
||
inputs = self.model.build_input_ids( | ||
text=[prompt], | ||
tokenizer=self.tokenizer, | ||
image=images | ||
) | ||
# .cuda() | ||
|
||
default_params = { | ||
'length_penalty': -1, | ||
} | ||
|
||
params = self.get_generation_params(request, default_params) | ||
|
||
with torch.no_grad(): | ||
outputs = self.model.generate( | ||
input_ids=inputs["input_ids"], | ||
attention_mask=inputs["attention_mask"], | ||
image=inputs["image"].to(torch.float16), # should be torch.float16 | ||
**params, | ||
) | ||
|
||
response = self.tokenizer.batch_decode(outputs, skip_special_tokens=True)[0] | ||
|
||
return response |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -42,6 +42,9 @@ transformers_stream_generator | |
loguru | ||
sse_starlette | ||
|
||
# 360vl | ||
logger | ||
|
||
# alt | ||
#transformers==4.36.2 | ||
|
||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters