Views
No views yet
| Model | Visual Encoder | Projector | Resolution | Pretraining Strategy | Fine-tuning Strategy | Pretrain Dataset | Fine-tune Dataset | Pretrain Epoch | Fine-tune Epoch |
|---|---|---|---|---|---|---|---|---|---|
| LLaVA-v1.5-7B | CLIP-L | MLP | 336 | Frozen LLM, Frozen ViT | Full LLM, Frozen ViT | LLaVA-PT (558K) | LLaVA-Mix (665K) | 1 | 1 |
| LLaVA-Llama-3-8B | CLIP-L | MLP | 336 | Frozen LLM, Frozen ViT | Full LLM, LoRA ViT | LLaVA-PT (558K) | LLaVA-Mix (665K) | 1 | 1 |
| LLaVA-Llama-3-8B-v1.1 | CLIP-L | MLP | 336 | Frozen LLM, Frozen ViT | Full LLM, LoRA ViT | ShareGPT4V-PT (1246K) | InternVL-SFT (1268K) | 1 | 1 |
| LLaVA-Phi-3-mini | CLIP-L | MLP | 336 | Frozen LLM, Frozen ViT | Full LLM, Full ViT | ShareGPT4V-PT (1246K) | InternVL-SFT (1268K) | 1 | 2 |
| Model | MMBench Test (EN) | MMMU Val | SEED-IMG | AI2D Test | ScienceQA Test | HallusionBench aAcc | POPE | GQA | TextVQA | MME | MMStar |
|---|---|---|---|---|---|---|---|---|---|---|---|
| LLaVA-v1.5-7B | 66.5 | 35.3 | 60.5 | 54.8 | 70.4 | 44.9 | 85.9 | 62.0 | 58.2 | 1511/348 | 30.3 |
| LLaVA-Llama-3-8B | 68.9 | 36.8 | 69.8 | 60.9 | 73.3 | 47.3 | 87.2 | 63.5 | 58.0 | 1506/295 | 38.2 |
| LLaVA-Llama-3-8B-v1.1 | 72.3 | 37.1 | 70.1 | 70.0 | 72.9 | 47.7 | 86.4 | 62.6 | 59.0 | 1469/349 | 45.1 |
| LLaVA-Phi-3-mini | 69.2 | 41.4 | 70.0 | 69.3 | 73.7 | 49.8 | 87.3 | 61.5 | 57.8 | 1477/313 | 43.7 |
pip install git+https://github.com/haotian-liu/LLaVA.git1import argparse
2from io import BytesIO
3
4import requests
5import torch
6from llava.constants import DEFAULT_IMAGE_TOKEN, IMAGE_TOKEN_INDEX
7from llava.conversation import Conversation, SeparatorStyle
8from llava.mm_utils import process_images, tokenizer_image_token
9from llava.model import LlavaLlamaForCausalLM
10from PIL import Image
11from transformers import (AutoTokenizer, BitsAndBytesConfig, StoppingCriteria,
12 StoppingCriteriaList, TextStreamer)
13
14
15def load_image(image_file):
16 if image_file.startswith('http://') or image_file.startswith('https://'):
17 response = requests.get(image_file)
18 image = Image.open(BytesIO(response.content)).convert('RGB')
19 else:
20 image = Image.open(image_file).convert('RGB')
21 return image
22
23
24class StopWordStoppingCriteria(StoppingCriteria):
25 """StopWord stopping criteria."""
26
27 def __init__(self, tokenizer, stop_word):
28 self.tokenizer = tokenizer
29 self.stop_word = stop_word
30 self.length = len(self.stop_word)
31
32 def __call__(self, input_ids, *args, **kwargs) -> bool:
33 cur_text = self.tokenizer.decode(input_ids[0])
34 cur_text = cur_text.replace('\r', '').replace('\n', '')
35 return cur_text[-self.length:] == self.stop_word
36
37
38def get_stop_criteria(tokenizer, stop_words=[]):
39 stop_criteria = StoppingCriteriaList()
40 for word in stop_words:
41 stop_criteria.append(StopWordStoppingCriteria(tokenizer, word))
42 return stop_criteria
43
44
45def main(args):
46 kwargs = {'device_map': args.device}
47 if args.load_8bit:
48 kwargs['load_in_8bit'] = True
49 elif args.load_4bit:
50 kwargs['load_in_4bit'] = True
51 kwargs['quantization_config'] = BitsAndBytesConfig(
52 load_in_4bit=True,
53 bnb_4bit_compute_dtype=torch.float16,
54 bnb_4bit_use_double_quant=True,
55 bnb_4bit_quant_type='nf4')
56 else:
57 kwargs['torch_dtype'] = torch.float16
58
59 tokenizer = AutoTokenizer.from_pretrained(args.model_path)
60 model = LlavaLlamaForCausalLM.from_pretrained(
61 args.model_path, low_cpu_mem_usage=True, **kwargs)
62 vision_tower = model.get_vision_tower()
63 if not vision_tower.is_loaded:
64 vision_tower.load_model(device_map=args.device)
65 image_processor = vision_tower.image_processor
66
67 conv = Conversation(
68 system=system='<|system|>\nAnswer the questions.',
69 roles=('<|user|>\n', '<|assistant|>\n'),
70 messages=[],
71 offset=0,
72 sep_style=SeparatorStyle.MPT,
73 sep='<|end|>',
74 )
75 roles = conv.roles
76
77 image = load_image(args.image_file)
78 image_size = image.size
79 image_tensor = process_images([image], image_processor, model.config)
80
81 if type(image_tensor) is list:
82 image_tensor = [
83 image.to(model.device, dtype=torch.float16)
84 for image in image_tensor
85 ]
86 else:
87 image_tensor = image_tensor.to(model.device, dtype=torch.float16)
88
89 while True:
90 try:
91 inp = input(f'{roles[0]}: ')
92 except EOFError:
93 inp = ''
94 if not inp:
95 print('exit...')
96 break
97
98 print(f'{roles[1]}: ', end='')
99
100 if image is not None:
101 inp = DEFAULT_IMAGE_TOKEN + '\n' + inp
102 image = None
103
104 conv.append_message(conv.roles[0], inp)
105 conv.append_message(conv.roles[1], None)
106 prompt = conv.get_prompt()
107
108 input_ids = tokenizer_image_token(
109 prompt, tokenizer, IMAGE_TOKEN_INDEX,
110 return_tensors='pt').unsqueeze(0).to(model.device)
111 stop_criteria = get_stop_criteria(
112 tokenizer=tokenizer, stop_words=[conv.sep])
113
114 streamer = TextStreamer(
115 tokenizer, skip_prompt=True, skip_special_tokens=True)
116
117 with torch.inference_mode():
118 output_ids = model.generate(
119 input_ids,
120 images=image_tensor,
121 image_sizes=[image_size],
122 do_sample=True if args.temperature > 0 else False,
123 temperature=args.temperature,
124 max_new_tokens=args.max_new_tokens,
125 streamer=streamer,
126 stopping_criteria=stop_criteria,
127 use_cache=True)
128
129 outputs = tokenizer.decode(output_ids[0]).strip()
130 conv.messages[-1][-1] = outputs
131
132 if args.debug:
133 print('\n', {'prompt': prompt, 'outputs': outputs}, '\n')
134
135
136if __name__ == '__main__':
137 parser = argparse.ArgumentParser()
138 parser.add_argument(
139 '--model-path', type=str, default='xtuner/llava-llama-3-8b-v1_1-hf')
140 parser.add_argument('--image-file', type=str, required=True)
141 parser.add_argument('--device', type=str, default='auto')
142 parser.add_argument('--temperature', type=float, default=0.2)
143 parser.add_argument('--max-new-tokens', type=int, default=512)
144 parser.add_argument('--load-8bit', action='store_true')
145 parser.add_argument('--load-4bit', action='store_true')
146 parser.add_argument('--debug', action='store_true')
147 args = parser.parse_args()
148 main(args)python ./cli.py --model-path xtuner/llava-phi-3-mini --image-file https://raw.githubusercontent.com/open-mmlab/mmdeploy/main/tests/data/tiger.jpeg --load-4bit1@misc{2023xtuner,
2 title={XTuner: A Toolkit for Efficiently Fine-tuning LLM},
3 author={XTuner Contributors},
4 howpublished = {\url{https://github.com/InternLM/xtuner}},
5 year={2023}
6}