Views
No views yet
🚨 Disclaimer: All models and datasets are intended for research purposes only.
1import logging
2from PIL import Image
3import torch
4from transformers import (
5 AutoModelForVision2Seq,
6 BitsAndBytesConfig,
7 AutoProcessor,
8)
9
10# Define Ultron template
11ULTRON_TEMPLATE = 'You are an excellent image sharing system that generates <RET> token with the following image description. The image description must be provided with the following format: <RET> <h> image description </h>. The following conversation is between {name} and AI assistant on {date}. The given image is {name}\'s appearance.\n{dialogue}'
12
13# Ultron model initialization
14def load_ultron_model(model_path):
15 """
16 Loads the Ultron model and processor.
17
18 Args:
19 model_path (str): Path to the pre-trained model.
20
21 Returns:
22 model: Loaded Vision-to-Seq model.
23 processor: Corresponding processor for the model.
24 """
25 logging.info(f"Loading Ultron model from {model_path}...")
26 quantization_config = BitsAndBytesConfig(
27 load_in_4bit=True,
28 bnb_4bit_compute_dtype=torch.bfloat16,
29 bnb_4bit_use_double_quant=True,
30 bnb_4bit_quant_type='nf4'
31 )
32 model_kwargs = dict(
33 torch_dtype=torch.bfloat16,
34 low_cpu_mem_usage=True,
35 trust_remote_code=True,
36 device_map="auto",
37 )
38 processor = AutoProcessor.from_pretrained(
39 'meta-llama/Llama-3.2-11B-Vision-Instruct', torch_dtype=torch.bfloat16
40 )
41 model = AutoModelForVision2Seq.from_pretrained(
42 model_path,
43 **model_kwargs
44 ).eval()
45 logging.info("Ultron model loaded successfully.")
46 return model, processor
47
48# Run Ultron model
49def run_ultron_model(model, processor, dialogue, name='Tom', date='2023.04.20', face_image_path='sample_face.png'):
50 """
51 Runs the Ultron model with a given dialogue, name, and image.
52
53 Args:
54 model: Pre-trained model instance.
55 processor: Processor for model input.
56 dialogue (str): Input dialogue for the assistant.
57 name (str): Name of the user.
58 date (str): Date of the conversation.
59 face_image_path (str): Path to the face image file.
60
61 Returns:
62 str: Description of the shared image.
63 """
64 logging.info("Running Ultron model...")
65 face_image = Image.open(face_image_path).convert("RGB")
66
67 prompt = ULTRON_TEMPLATE.format(
68 dialogue=dialogue,
69 name=name,
70 date=date
71 )
72 messages = [
73 {
74 "content": [
75 {"text": prompt, "type": "text"},
76 {"type": "image"}
77 ],
78 "role": "user"
79 },
80 ]
81
82 logging.info("Preparing input for Ultron model...")
83 prompt_input = processor.apply_chat_template(messages, add_generation_prompt=True)
84 inputs = processor(face_image, prompt_input, return_tensors='pt').to('cuda')
85
86 with torch.inference_mode():
87 logging.info("Generating output from Ultron model...")
88 output = model.generate(
89 **inputs,
90 do_sample=True,
91 temperature=0.9,
92 max_new_tokens=512,
93 top_p=1.0,
94 use_cache=True,
95 num_beams=1,
96 )
97
98 output_text = processor.decode(output[0], skip_special_token=True)
99 logging.info("Output generated successfully from Ultron model.")
100 return parse_ultron_output(output_text)
101
102# Parse Ultron output
103def parse_ultron_output(output):
104 """
105 Parses the output to extract the image description.
106
107 Args:
108 output (str): The generated output text from the model.
109
110 Returns:
111 str: Extracted image description.
112 """
113 logging.info("Parsing output from Ultron model...")
114 if '<RET>' in output:
115 return output.split('<h>')[-1].split('</h>')[0].strip()
116 else:
117 logging.warning("<RET> not found in output.")
118 return output
119
120# Example usage
121def main():
122 """
123 Example usage of Ultron model.
124 """
125 model_path = "passing2961/Ultron-11B"
126 model, processor = load_ultron_model(model_path)
127
128 dialogue = """Tom: I have so much work at the office, I'm exhausted...
129 Personal AI Assistant: How can I help you feel less tired?
130 Tom: Hmm.. I miss my dog Star at home.
131 Personal AI Assistant: """
132
133 image_description = run_ultron_model(model, processor, dialogue)
134 logging.info(f"Image description generated: {image_description}")
135
136if __name__ == "__main__":
137 main()@article{lee2024stark,
title={Stark: Social Long-Term Multi-Modal Conversation with Persona Commonsense Knowledge},
author={Lee, Young-Jun and Lee, Dokyong and Youn, Junyoung and Oh, Kyeongjin and Ko, Byungsoo and Hyeon, Jonghwan and Choi, Ho-Jin},
journal={arXiv preprint arXiv:2407.03958},
year={2024}
}