Views
No views yet
pip install torch transformers accelerate pillow1import torch
2import transformers
3from transformers import AutoModelForCausalLM, AutoTokenizer
4from PIL import Image
5import warnings
6import io
7import requests
8
9# disable some warnings
10transformers.logging.set_verbosity_error()
11transformers.logging.disable_progress_bar()
12warnings.filterwarnings('ignore')
13
14# Set Device
15device = 'cuda' # or cpu
16torch.set_default_device(device)
17
18# Create Model
19model = AutoModelForCausalLM.from_pretrained(
20 'scb10x/llama-3-typhoon-v1.5-8b-instruct-vision-preview',
21 torch_dtype=torch.float16, # float32 for cpu
22 device_map='auto',
23 trust_remote_code=True)
24tokenizer = AutoTokenizer.from_pretrained(
25 'scb10x/llama-3-typhoon-v1.5-8b-instruct-vision-preview',
26 trust_remote_code=True)
27
28def prepare_inputs(text, has_image=False, device='cuda'):
29 messages = [
30 {"role": "system", "content": "You are a helpful vision-capable assistant who eagerly converses with the user in their language."},
31 ]
32
33 if has_image:
34 messages.append({"role": "user", "content": "<|image|>\n" + text})
35 else:
36 messages.append({"role": "user", "content": text})
37
38 inputs_formatted = tokenizer.apply_chat_template(
39 messages,
40 add_generation_prompt=True,
41 tokenize=False
42 )
43
44 if has_image:
45 text_chunks = [tokenizer(chunk).input_ids for chunk in inputs_formatted.split('<|image|>')]
46 input_ids = torch.tensor(text_chunks[0] + [-200] + text_chunks[1][1:], dtype=torch.long).unsqueeze(0).to(device)
47 attention_mask = torch.ones_like(input_ids).to(device)
48 else:
49 input_ids = torch.tensor(tokenizer(inputs_formatted).input_ids, dtype=torch.long).unsqueeze(0).to(device)
50 attention_mask = torch.ones_like(input_ids).to(device)
51
52 return input_ids, attention_mask
53
54# Example Inputs (try replacing with your own url)
55prompt = 'บอกทุกอย่างที่เห็นในรูป'
56img_url = "https://img.traveltriangle.com/blog/wp-content/uploads/2020/01/cover-for-Thailand-In-May_27th-Jan.jpg"
57image = Image.open(io.BytesIO(requests.get(img_url).content))
58image_tensor = model.process_images([image], model.config).to(dtype=model.dtype, device=device)
59input_ids, attention_mask = prepare_inputs(prompt, has_image=True, device=device)
60
61# Generate
62output_ids = model.generate(
63 input_ids,
64 images=image_tensor,
65 max_new_tokens=1000,
66 use_cache=True,
67 temperature=0.2,
68 top_p=0.2,
69 repetition_penalty=1.0 # increase this to avoid chattering,
70)[0]
71
72print(tokenizer.decode(output_ids[input_ids.shape[1]:], skip_special_tokens=True).strip())| Model | MMBench (Dev) | Pope | GQA | GQA (Thai) |
|---|---|---|---|---|
| Typhoon-Vision 8B Preview | 70.9 | 84.8 | 62.0 | 43.6 |
| SeaLMMM 7B v0.1 | 64.8 | 86.3 | 61.4 | 25.3 |
| Bunny Llama3 8B Vision | 76.0 | 86.9 | 64.8 | 24.0 |
| GPT-4o Mini | 69.8 | 45.4 | 42.6 | 18.1 |