Views
No views yet

1User: You carefully study the image, and respond accurately, but succinctly. Think step-by-step.
2<image>What is shown in this image, and what is the relevance for materials design? Include a discussion of multi-agent AI.<end_of_utterance>
3Assistant:Assistant: . For multi-turn conversations, the prompt should be formatted as follows:1User: You carefully study the image, and respond accurately, but succinctly. Think step-by-step.
2<image>What is shown in this image, and what is the relevance for materials design? Include a discussion of multi-agent AI.<end_of_utterance>
3Assistant: The image depicts ants climbing a vertical surface using their legs and claws. This behavior is observed in nature and can inspire the design of multi-agent AI systems that mimic the coordinated movement of these insects. The relevance lies in the potential application of such systems in robotics and materials science, where efficient and adaptive movement is crucial.<end_of_utterance>
4User: How could this be used to design a fracture resistant material?<end_of_utterance>
5Assistant:IDEFICS2_CHAT_TEMPLATE = "{% for message in messages %}{{message['role'].capitalize()}}{% if message['content'][0]['type'] == 'image' %}{{':'}}{% else %}{{': '}}{% endif %}{% for line in message['content'] %}{% if line['type'] == 'text' %}{{line['text']}}{% elif line['type'] == 'image' %}{{ '<image>' }}{% endif %}{% endfor %}<end_of_utterance>\n{% endfor %}{% if add_generation_prompt %}{{ 'Assistant:' }}{% endif %}"1from PIL import Image
2import requests
3
4DEVICE='cuda:0'
5
6from transformers import AutoProcessor, Idefics2ForConditionalGeneration
7from tqdm.notebook import tqdm
8
9model_id='lamm-mit/Cephalo-Idefics-2-vision-12b-alpha'
10
11model = Idefics2ForConditionalGeneration.from_pretrained( model_id,
12 torch_dtype=torch.bfloat16, #if your GPU allows
13 _attn_implementation="flash_attention_2", #make sure Flash Attention 2 is installed
14 trust_remote_code=True,
15 ).to (DEVICE)
16processor = AutoProcessor.from_pretrained(
17 f"{model_id}",
18 do_image_splitting=True
19)1IDEFICS2_CHAT_TEMPLATE = "{% for message in messages %}{{message['role'].capitalize()}}{% if message['content'][0]['type'] == 'image' %}{{':'}}{% else %}{{': '}}{% endif %}{% for line in message['content'] %}{% if line['type'] == 'text' %}{{line['text']}}{% elif line['type'] == 'image' %}{{ '<image>' }}{% endif %}{% endfor %}<end_of_utterance>\n{% endfor %}{% if add_generation_prompt %}{{ 'Assistant:' }}{% endif %}"
2tokenizer = AutoTokenizer.from_pretrained(base_model_id, use_fast=True)
3tokenizer.chat_template = IDEFICS2_CHAT_TEMPLATE
4processor.tokenizer = tokenizerfrom transformers.image_utils import load_image
image = load_image("https://d2r55xnwy6nx47.cloudfront.net/uploads/2018/02/Ants_Lede1300.jpg")
# Create inputs
messages = [
{
"role": "user",
"content": [
{"type": "image"},
{"type": "text", "text": "What is shown in this image, and what is the relevance for materials design? Include a discussion of multi-agent AI."},
]
},
]
prompt = processor.apply_chat_template(messages, add_generation_prompt=True)
# Get inputs using the processor
inputs = processor(text=prompt, images=[image], return_tensors="pt")
inputs = {k: v.to(DEVICE) for k, v in inputs.items()}
# Generate
generated_ids = model.generate(**inputs, max_new_tokens=500)
generated_texts = processor.batch_decode(generated_ids, skip_special_tokens=True)
print(generated_texts)1def ask_about_image (model, processor, question,
2 images_input=[],
3 verbatim=False,
4 temperature=0.1,
5 show_image=False,
6 system="You are a biomaterials scientist who responds accurately. ",
7 init_instr = "",
8 show_conversation=True,
9 max_new_tokens=256,
10 messages=[],
11 images=[],
12 use_Markdown=False,
13 ):
14
15
16 query = question
17 images_input=ensure_list(images_input)
18 if len (images)==0:
19 if len (images_input)>0:
20 for image in tqdm (images_input) :
21 if is_url(image):
22 image= load_image(image)
23 images.append (image)
24
25 if show_image:
26 display ( image )
27 if len (messages)==0:
28
29 base_message = {
30 "role": "user",
31 "content": [
32 {"type": "text", "text": system + init_instr},
33 # Image messages will be added dynamically here
34 {"type": "text", "text": query}
35 ]
36 }
37
38 # Ensure the images_input is a list
39 images_input = ensure_list(images_input)
40
41 # Add image messages dynamically
42 image_messages = [{"type": "image"} for _ in images_input]
43 base_message["content"][1:1] = image_messages # Insert image messages before the last text message
44
45 # Append the constructed message to messages list
46 messages.append(base_message)
47
48 else:
49 messages.append (
50 {
51 "role": "user",
52 "content": [
53 {"type": "text", "text": query
54 }
55 ]
56 }
57 )
58 if verbatim:
59 print (messages)
60
61 text = processor.apply_chat_template(messages, add_generation_prompt=True)
62 inputs = processor(text=[text.strip()], images=images, return_tensors="pt", padding=True).to(DEVICE)
63
64 generated_ids = model.generate(**inputs, max_new_tokens=max_new_tokens, temperature=temperature, do_sample=True)
65 generated_texts = processor.batch_decode(generated_ids[:, inputs["input_ids"].size(1):], skip_special_tokens=True)
66
67 messages.append (
68 {
69 "role": "assistant",
70 "content": [ {"type": "text", "text": generated_texts[0]}, ]
71 }
72 )
73 formatted_conversation = format_conversation(messages, images)
74
75 # Display the formatted conversation, e.g. in Jupyter Notebook
76 if show_conversation:
77
78 if use_Markdown:
79 display(Markdown(formatted_conversation))
80 else:
81 display(HTML(formatted_conversation))
82
83 return generated_texts, messages, images
84
85question = "What is shown in this image, and what is the relevance for materials design? Include a discussion of multi-agent AI."
86
87url1 = "https://d2r55xnwy6nx47.cloudfront.net/uploads/2018/02/Ants_Lede1300.jpg"
88
89response, messages,images= ask_about_image ( model, processor, question,
90 images_input=[url1,],
91 temperature=0.1,
92 system= '', init_instr='You carefully study the image and provide detailed answers. Think step-by-step.\n\n',
93 show_conversation=True,
94 max_new_tokens=512, messages=[], images=[])

torch.float16 or torch.bfloat16).1model = AutoModelForVision2Seq.from_pretrained(
2 "lamm-mit/Cephalo-Idefics-2-vision-12b-alpha",
3+ torch_dtype=torch.float16,
4).to(DEVICE)do_image_splitting=False when initializing the processor (AutoProcessor.from_pretrained). There are no changes required on the model side. Note that only the sft model has been trained with image splitting.size= {"longest_edge": 448, "shortest_edge": 378} when initializing the processor (AutoProcessor.from_pretrained). In particular, the longest_edge value can be adapted to fit the need (the default value is 980). We recommend using values that are multiples of 14. There are no changes required on the model side.do_image_splitting=True is especially needed to boost performance on complex tasks where a very large image is used as input. The model was fine-tuned with image splitting turned on. For simple tasks, this argument can be safely set to False.flash-attn. Refer to the original repository of Flash Attention for the package installation. Simply change the snippet above with:1model = AutoModelForVision2Seq.from_pretrained(
2 "lamm-mit/Cephalo-Idefics-2-vision-12b-alpha",
3+ torch_dtype=torch.bfloat16,
4+ _attn_implementation="flash_attention_2",
5).to(DEVICE)1+ from transformers import BitsAndBytesConfig
2
3quantization_config = BitsAndBytesConfig(
4 load_in_4bit=True,
5 bnb_4bit_quant_type="nf4",
6 bnb_4bit_use_double_quant=True,
7 bnb_4bit_compute_dtype=torch.bfloat16
8)
9model = AutoModelForVision2Seq.from_pretrained(
10 "lamm-mit/Cephalo-Idefics-2-vision-12b-alpha",
11+ torch_dtype=torch.bfloat16,
12+ quantization_config=quantization_config,
13).to(DEVICE)1@article{Buehler_Cephalo_2024,
2 title={Cephalo: Multi-Modal Vision-Language Models for Bio-Inspired Materials Analysis and Design},
3 author={Markus J. Buehler},
4 journal={arXiv preprint arXiv:2405.19076},
5 year={2024}
6}