-
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
Sep 26, 2024
1 parent
96cc4e3
commit 6c45b53
Showing
13 changed files
with
485 additions
and
151 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
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,43 @@ | ||
from transformers import AutoTokenizer, AutoModel | ||
|
||
from vision_qna import * | ||
|
||
# ucaslcl/GOT-OCR2_0 | ||
|
||
DEFAULT_IMAGE_TOKEN = "<image>" | ||
DEFAULT_IMAGE_PATCH_TOKEN = '<imgpad>' | ||
DEFAULT_IM_START_TOKEN = '<img>' | ||
DEFAULT_IM_END_TOKEN = '</img>' | ||
|
||
class VisionQnA(VisionQnABase): | ||
model_name: str = "got_ocr2" | ||
format: str = "custom" | ||
visual_layers: List[str] = ['vision_tower_high', 'mm_projector_vary'] | ||
|
||
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) | ||
|
||
self.tokenizer = AutoTokenizer.from_pretrained(model_id, trust_remote_code=self.params.get('trust_remote_code', False)) | ||
self.model = AutoModel.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.loaded_banner() | ||
|
||
async def chat_with_images(self, request: ImageChatRequest) -> str: | ||
try: | ||
image = None | ||
for m in reversed(request.messages): | ||
for c in m.content: | ||
if c.type == 'image_url': | ||
image = await url_to_file(c.image_url.url) | ||
break | ||
|
||
response = self.model.chat(self.tokenizer, image, ocr_type='ocr') # TODO: support format and maybe convert to markdown? | ||
|
||
return response | ||
finally: | ||
if image: | ||
os.remove(image) |
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,46 @@ | ||
from transformers import MllamaForConditionalGeneration, AutoProcessor | ||
|
||
from vision_qna import * | ||
|
||
# meta-llama/Llama-3.2-11B-Vision-Instruct | ||
# meta-llama/Llama-3.2-90B-Vision-Instruct | ||
|
||
class VisionQnA(VisionQnABase): | ||
model_name: str = "mllama" | ||
format: str = "llama3" | ||
visual_layers: List[str] = ['vision_model', 'multi_modal_projector'] | ||
|
||
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) | ||
|
||
del self.params['trust_remote_code'] | ||
|
||
self.processor = AutoProcessor.from_pretrained(model_id) | ||
self.model = MllamaForConditionalGeneration.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.loaded_banner() | ||
|
||
async def stream_chat_with_images(self, request: ImageChatRequest) -> AsyncGenerator[str, None]: | ||
images, prompt = await llama3_prompt_from_messages(request.messages, img_tok = "<|image|>") | ||
|
||
if len(images) < 1: | ||
images = [ await url_to_image(black_pixel_url) ] | ||
prompt = "<|image|>" + prompt | ||
|
||
inputs = self.processor(images, prompt, return_tensors="pt").to(self.model.device) | ||
|
||
default_params = dict(do_sample=True) | ||
|
||
params = self.get_generation_params(request, default_params=default_params) | ||
|
||
generation_kwargs = dict( | ||
**inputs, | ||
**params, | ||
) | ||
|
||
for new_text in threaded_streaming_generator(generate=self.model.generate, tokenizer=self.processor, generation_kwargs=generation_kwargs): | ||
yield new_text |
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,77 @@ | ||
from transformers import AutoProcessor, AutoModelForCausalLM, GenerationConfig | ||
|
||
from vision_qna import * | ||
|
||
# allenai/MolmoE-1B-0924 | ||
# allenai/Molmo-7B-D-0924 | ||
# allenai/Molmo-7B-O-0924 | ||
# allenai/Molmo-72B-0924 | ||
|
||
# XXX To use, pip install tensorflow-cpu | ||
# https://huggingface.co/allenai/Molmo-7B-D-0924/blob/main/image_preprocessing_molmo.py#L88-L90 | ||
|
||
""" | ||
["allenai/MolmoE-1B-0924", "-A", "flash_attention_2", "--load-in-4bit"], | ||
["allenai/MolmoE-1B-0924", "-A", "flash_attention_2"], | ||
["allenai/Molmo-7B-D-0924", "-A", "flash_attention_2", "--load-in-4bit"], | ||
["allenai/Molmo-7B-D-0924", "-A", "flash_attention_2"], | ||
["allenai/Molmo-7B-O-0924", "-A", "flash_attention_2", "--load-in-4bit"], | ||
["allenai/Molmo-7B-O-0924", "-A", "flash_attention_2"], | ||
["allenai/Molmo-72B-0924", "--load-in-4bit"], | ||
""" | ||
|
||
class VisionQnA(VisionQnABase): | ||
model_name: str = "molmo" | ||
format: str = "chatml" | ||
visual_layers: List[str] = ['vision_backbone'] | ||
|
||
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) | ||
|
||
self.dtype = self.params['torch_dtype'] = 'auto' # torch.float32 | ||
|
||
self.processor = AutoProcessor.from_pretrained(model_id, trust_remote_code=self.params.get('trust_remote_code', False)) | ||
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.eos_token_id = self.processor.tokenizer.encode(self.processor.tokenizer.eos_token)[0] | ||
|
||
self.loaded_banner() | ||
|
||
async def stream_chat_with_images(self, request: ImageChatRequest) -> AsyncGenerator[str, None]: | ||
images, prompt = await chatml_prompt_from_messages(request.messages, img_tok = "<|image|>") | ||
|
||
if len(images) < 1: | ||
images = [ await url_to_image(black_pixel_url) ] | ||
prompt = "<|image|>" + prompt | ||
|
||
# process the image and text | ||
inputs = self.processor.process( | ||
images=images, | ||
text=prompt, | ||
) | ||
|
||
inputs = {k: v.to(self.model.device).unsqueeze(0) for k, v in inputs.items()} | ||
|
||
default_params = dict( | ||
eos_token_id=self.eos_token_id, | ||
pad_token_id=self.eos_token_id | ||
) | ||
|
||
params = self.get_generation_params(request, default_params) | ||
|
||
generation_kwargs = dict( | ||
batch=inputs, | ||
generation_config=GenerationConfig(**params) | ||
) | ||
|
||
for new_text in threaded_streaming_generator(generate=self.model.generate_from_batch, tokenizer=self.processor.tokenizer, generation_kwargs=generation_kwargs): | ||
end = new_text.find(self.processor.tokenizer.eos_token) | ||
if end == -1: | ||
yield new_text | ||
else: | ||
yield new_text[:end] | ||
break |
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,43 @@ | ||
#!/usr/bin/env python | ||
|
||
import torch | ||
import re | ||
import sys | ||
import pkg_resources | ||
|
||
def get_cuda_info(): | ||
print("---- cuda") | ||
print(f"CUDA version: {torch.version.cuda}") | ||
print(f"torch.cuda.is_available(): {torch.cuda.is_available()}") | ||
for i in range(0, torch.cuda.device_count()): | ||
print(f"CUDA device[{i}]{torch.cuda.get_device_capability(i)}: {torch.cuda.get_device_name(i)}") | ||
|
||
def get_python_version(): | ||
print("---- python") | ||
print(sys.version) | ||
|
||
def get_pip_packages(): | ||
print("---- pip") | ||
try: | ||
packages = set(["transformers"]) | ||
with open("requirements.txt", "r") as f: | ||
for line in f.readlines(): | ||
line = line.strip() | ||
if not line or line.startswith("#") or line.startswith("http:") or line.startswith("https:") or line.startswith("git+"): | ||
continue | ||
package = re.split(r"[=<>;#\[ ]", line)[0] | ||
packages.add(package) | ||
|
||
for package in sorted(list(packages)): | ||
try: | ||
version = pkg_resources.get_distribution(package).version | ||
print(f"{package}=={version}") | ||
except pkg_resources.DistributionNotFound: | ||
print(f"{package}: Not found") | ||
|
||
except FileNotFoundError: | ||
print("requirements.txt not found") | ||
|
||
get_cuda_info() | ||
get_python_version() | ||
get_pip_packages() |
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
Oops, something went wrong.