mjbuehler commited on
Commit
abc2829
1 Parent(s): 0d74807

Upload README.md

Browse files
Files changed (1) hide show
  1. README.md +304 -177
README.md CHANGED
@@ -1,199 +1,326 @@
1
  ---
 
 
 
2
  library_name: transformers
3
- tags: []
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4
  ---
 
5
 
6
- # Model Card for Model ID
7
 
8
- <!-- Provide a quick summary of what the model is/does. -->
9
 
 
10
 
 
11
 
12
- ## Model Details
13
 
14
- ### Model Description
15
 
16
- <!-- Provide a longer summary of what this model is. -->
17
 
18
- This is the model card of a 🤗 transformers model that has been pushed on the Hub. This model card has been automatically generated.
19
 
20
- - **Developed by:** [More Information Needed]
21
- - **Funded by [optional]:** [More Information Needed]
22
- - **Shared by [optional]:** [More Information Needed]
23
- - **Model type:** [More Information Needed]
24
- - **Language(s) (NLP):** [More Information Needed]
25
- - **License:** [More Information Needed]
26
- - **Finetuned from model [optional]:** [More Information Needed]
27
 
28
- ### Model Sources [optional]
 
 
 
 
 
29
 
30
- <!-- Provide the basic links for the model. -->
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
31
 
32
- - **Repository:** [More Information Needed]
33
- - **Paper [optional]:** [More Information Needed]
34
- - **Demo [optional]:** [More Information Needed]
35
 
36
- ## Uses
 
37
 
38
- <!-- Address questions around how the model is intended to be used, including the foreseeable users of the model and those affected by the model. -->
 
 
 
 
 
 
 
 
 
 
 
39
 
40
- ### Direct Use
41
 
42
- <!-- This section is for the model use without fine-tuning or plugging into a larger ecosystem/app. -->
43
 
44
- [More Information Needed]
45
 
46
- ### Downstream Use [optional]
47
 
48
- <!-- This section is for the model use when fine-tuned for a task, or when plugged into a larger ecosystem/app -->
49
-
50
- [More Information Needed]
51
-
52
- ### Out-of-Scope Use
53
-
54
- <!-- This section addresses misuse, malicious use, and uses that the model will not work well for. -->
55
-
56
- [More Information Needed]
57
-
58
- ## Bias, Risks, and Limitations
59
-
60
- <!-- This section is meant to convey both technical and sociotechnical limitations. -->
61
-
62
- [More Information Needed]
63
-
64
- ### Recommendations
65
-
66
- <!-- This section is meant to convey recommendations with respect to the bias, risk, and technical limitations. -->
67
-
68
- Users (both direct and downstream) should be made aware of the risks, biases and limitations of the model. More information needed for further recommendations.
69
-
70
- ## How to Get Started with the Model
71
-
72
- Use the code below to get started with the model.
73
-
74
- [More Information Needed]
75
-
76
- ## Training Details
77
-
78
- ### Training Data
79
-
80
- <!-- This should link to a Dataset Card, perhaps with a short stub of information on what the training data is all about as well as documentation related to data pre-processing or additional filtering. -->
81
-
82
- [More Information Needed]
83
-
84
- ### Training Procedure
85
-
86
- <!-- This relates heavily to the Technical Specifications. Content here should link to that section when it is relevant to the training procedure. -->
87
-
88
- #### Preprocessing [optional]
89
-
90
- [More Information Needed]
91
-
92
-
93
- #### Training Hyperparameters
94
-
95
- - **Training regime:** [More Information Needed] <!--fp32, fp16 mixed precision, bf16 mixed precision, bf16 non-mixed precision, fp16 non-mixed precision, fp8 mixed precision -->
96
-
97
- #### Speeds, Sizes, Times [optional]
98
-
99
- <!-- This section provides information about throughput, start/end time, checkpoint size if relevant, etc. -->
100
-
101
- [More Information Needed]
102
-
103
- ## Evaluation
104
-
105
- <!-- This section describes the evaluation protocols and provides the results. -->
106
-
107
- ### Testing Data, Factors & Metrics
108
-
109
- #### Testing Data
110
-
111
- <!-- This should link to a Dataset Card if possible. -->
112
-
113
- [More Information Needed]
114
-
115
- #### Factors
116
-
117
- <!-- These are the things the evaluation is disaggregating by, e.g., subpopulations or domains. -->
118
-
119
- [More Information Needed]
120
-
121
- #### Metrics
122
-
123
- <!-- These are the evaluation metrics being used, ideally with a description of why. -->
124
-
125
- [More Information Needed]
126
-
127
- ### Results
128
-
129
- [More Information Needed]
130
-
131
- #### Summary
132
-
133
-
134
-
135
- ## Model Examination [optional]
136
-
137
- <!-- Relevant interpretability work for the model goes here -->
138
-
139
- [More Information Needed]
140
-
141
- ## Environmental Impact
142
-
143
- <!-- Total emissions (in grams of CO2eq) and additional considerations, such as electricity usage, go here. Edit the suggested text below accordingly -->
144
-
145
- Carbon emissions can be estimated using the [Machine Learning Impact calculator](https://mlco2.github.io/impact#compute) presented in [Lacoste et al. (2019)](https://arxiv.org/abs/1910.09700).
146
-
147
- - **Hardware Type:** [More Information Needed]
148
- - **Hours used:** [More Information Needed]
149
- - **Cloud Provider:** [More Information Needed]
150
- - **Compute Region:** [More Information Needed]
151
- - **Carbon Emitted:** [More Information Needed]
152
-
153
- ## Technical Specifications [optional]
154
-
155
- ### Model Architecture and Objective
156
-
157
- [More Information Needed]
158
-
159
- ### Compute Infrastructure
160
-
161
- [More Information Needed]
162
-
163
- #### Hardware
164
-
165
- [More Information Needed]
166
-
167
- #### Software
168
-
169
- [More Information Needed]
170
-
171
- ## Citation [optional]
172
-
173
- <!-- If there is a paper or blog post introducing the model, the APA and Bibtex information for that should go in this section. -->
174
-
175
- **BibTeX:**
176
-
177
- [More Information Needed]
178
-
179
- **APA:**
180
-
181
- [More Information Needed]
182
-
183
- ## Glossary [optional]
184
-
185
- <!-- If relevant, include terms and calculations in this section that can help readers understand the model or model card. -->
186
-
187
- [More Information Needed]
188
-
189
- ## More Information [optional]
190
-
191
- [More Information Needed]
192
-
193
- ## Model Card Authors [optional]
194
-
195
- [More Information Needed]
196
-
197
- ## Model Card Contact
198
-
199
- [More Information Needed]
 
1
  ---
2
+ language:
3
+ - multilingual
4
+ license: apache-2.0
5
  library_name: transformers
6
+ tags:
7
+ - nlp
8
+ - code
9
+ - vision
10
+ - chemistry
11
+ - engineering
12
+ - biology
13
+ - bio-inspired
14
+ - text-generation-inference
15
+ - materials science
16
+ pipeline_tag: image-text-to-text
17
+ inference:
18
+ parameters:
19
+ temperature: 0.3
20
+ widget:
21
+ - messages:
22
+ - role: user
23
+ content: <|image_1|>Can you describe what you see in the image?
24
  ---
25
+ ## Model Summary
26
 
27
+ Cephalo is a series of multimodal materials science focused vision large language models (V-LLMs) designed to integrate visual and linguistic data for advanced understanding and interaction in human-AI or multi-agent AI frameworks.
28
 
29
+ A novel aspect of Cephalo's development is the innovative dataset generation method. The extraction process employs advanced algorithms to accurately detect and separate images and their corresponding textual descriptions from complex PDF documents. It involves extracting images and captions from PDFs to create well-reasoned image-text pairs, utilizing large language models (LLMs) for natural language processing. These image-text pairs are then refined and validated through LLM-based NLP processing, ensuring high-quality and contextually relevant data for training.
30
 
31
+ Cephalo can interpret complex visual scenes and generating contextually accurate language descriptions and answer queries.
32
 
33
+ The model is developed to process diverse inputs, including images and text, facilitating a broad range of applications such as image captioning, visual question answering, and multimodal content generation. The architecture combines a vision encoder model and an autoregressive transformer to process complex natural language understanding.
34
 
35
+ ![image/png](https://cdn-uploads.huggingface.co/production/uploads/623ce1c6b66fedf374859fe7/kl5GWBP9WS0D4uwd1t3S7.png)
36
 
37
+ Cephalo provides a robust framework for multimodal interaction and understanding, including the development of complex generative pipelines to create 2D and 3D renderings of material microstructures as input for additive manufacturing methods.
38
 
39
+ This version of Cephalo, lamm-mit/Cephalo-Phi-3-vision-128k-4b-alpha, is based on the HuggingFaceM4/idefics2-8b-chatty model. The model was trained on a combination of scientific text-image data extracted from Wikipedia and scientific papers. For further details on the base model, see: https://huggingface.co/HuggingFaceM4/idefics2-8b-chatty. More details about technical aspects of the model, training and example applications to materials science problems are provided in the paper (reference at the bottom).
40
 
41
+ ### Chat Format
42
 
43
+ The lamm-mit/Cephalo-Idefics-2-vision-8b-alpha is suiteable for one or more image inputs, wih prompts using the chat format as follows:
 
 
 
 
 
 
44
 
45
+ ```raw
46
+ User: You carefully study the image, and respond accurately, but succinctly. Think step-by-step.
47
+ <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>
48
+ Assistant:
49
+ ```
50
+ where the model generates the text after `Assistant:` . For multi-turn conversations, the prompt should be formatted as follows:
51
 
52
+ ```raw
53
+ User: You carefully study the image, and respond accurately, but succinctly. Think step-by-step.
54
+ <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>
55
+ Assistant: 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>
56
+ User: How could this be used to design a fracture resistant material?<end_of_utterance>
57
+ Assistant:
58
+ ```
59
+
60
+ If you need to manually set the chat template:
61
+
62
+ ```
63
+ IDEFICS2_CHAT_TEMPLATE = """{% if not add_generation_prompt is defined %}{% set add_generation_prompt = false %}{% endif %}A chat between a curious user and an artificial intelligence assistant. The assistant gives helpful, detailed, and polite answers to the user's questions. {% for message in messages %}{% if message['role'] == 'user' %}USER: {% else %}ASSISTANT: {% endif %}{% for item in message['content'] %}{% if item['type'] == 'text' %}{{ item['text'] }}{% elif item['type'] == 'image' %}<image>{% endif %}{% endfor %}{% if message['role'] == 'user' %} {% else %}{{eos_token}}{% endif %}{% endfor %}{% if add_generation_prompt %}ASSISTANT: {% endif %}"""
64
+ ```
65
+
66
+ ### Sample inference code
67
+
68
+ This code snippets show how to get quickly started on a GPU:
69
+
70
+ ```python
71
+ from PIL import Image
72
+ import requests
73
+
74
+ DEVICE='cuda:0'
75
+
76
+ from transformers import AutoProcessor, Idefics2ForConditionalGeneration
77
+ from tqdm.notebook import tqdm
78
+
79
+ model_id='lamm-mit/Cephalo-Idefics-2-vision-8b-alpha'
80
+
81
+ model = Idefics2ForConditionalGeneration.from_pretrained( model_id,
82
+ torch_dtype=torch.bfloat16, #if your GPU allows
83
+ _attn_implementation="flash_attention_2", #make sure Flash Attention 2 is installed
84
+ trust_remote_code=True,
85
+ ).to (DEVICE)
86
+ processor = AutoProcessor.from_pretrained(
87
+ f"{model_id}",
88
+ do_image_splitting=True
89
+ )
90
+ ```
91
+ See section towards the end for more comments on model optimization, including quantization.
92
+
93
+
94
+ If you need to manually set the chat template:
95
+
96
+ ```python
97
+ IDEFICS2_CHAT_TEMPLATE = """{% if not add_generation_prompt is defined %}{% set add_generation_prompt = false %}{% endif %}A chat between a curious user and an artificial intelligence assistant. The assistant gives helpful, detailed, and polite answers to the user's questions. {% for message in messages %}{% if message['role'] == 'user' %}USER: {% else %}ASSISTANT: {% endif %}{% for item in message['content'] %}{% if item['type'] == 'text' %}{{ item['text'] }}{% elif item['type'] == 'image' %}<image>{% endif %}{% endfor %}{% if message['role'] == 'user' %} {% else %}{{eos_token}}{% endif %}{% endfor %}{% if add_generation_prompt %}ASSISTANT: {% endif %}"""
98
+ tokenizer = AutoTokenizer.from_pretrained(base_model_id, use_fast=True)
99
+ tokenizer.chat_template = IDEFICS2_CHAT_TEMPLATE
100
+ processor.tokenizer = tokenizer
101
+ ```
102
+
103
+ Simple inference example:
104
+
105
+ ```
106
+ from transformers.image_utils import load_image
107
+
108
+ image = load_image("https://d2r55xnwy6nx47.cloudfront.net/uploads/2018/02/Ants_Lede1300.jpg")
109
+
110
+ # Create inputs
111
+ messages = [
112
+ {
113
+ "role": "user",
114
+ "content": [
115
+ {"type": "image"},
116
+ {"type": "text", "text": "What is shown in this image, and what is the relevance for materials design? Include a discussion of multi-agent AI."},
117
+ ]
118
+ },
119
+ ]
120
+ prompt = processor.apply_chat_template(messages, add_generation_prompt=True)
121
+
122
+ # Get inputs using the processor
123
+ inputs = processor(text=prompt, images=[image], return_tensors="pt")
124
+ inputs = {k: v.to(DEVICE) for k, v in inputs.items()}
125
+
126
+ # Generate
127
+ generated_ids = model.generate(**inputs, max_new_tokens=500)
128
+ generated_texts = processor.batch_decode(generated_ids, skip_special_tokens=True)
129
+
130
+ print(generated_texts)
131
+ ```
132
+
133
+ Next we provide a convenience function for inference. This function takes the model, processor, question, and images, along with messages and images objects for repeated chat-like interactions with the model.
134
+
135
+ ```python
136
+ def ask_about_image (model, processor, question,
137
+ images_input=[],
138
+ verbatim=False,
139
+ temperature=0.1,
140
+ show_image=False,
141
+ system="You are a biomaterials scientist who responds accurately. ",
142
+ init_instr = "",
143
+ show_conversation=True,
144
+ max_new_tokens=256,
145
+ messages=[],
146
+ images=[],
147
+ use_Markdown=False,
148
+ ):
149
+
150
+
151
+ query = question
152
+ images_input=ensure_list(images_input)
153
+ if len (images)==0:
154
+ if len (images_input)>0:
155
+ for image in tqdm (images_input) :
156
+ if is_url(image):
157
+ image= load_image(image)
158
+ images.append (image)
159
+
160
+ if show_image:
161
+ display ( image )
162
+ if len (messages)==0:
163
+
164
+ base_message = {
165
+ "role": "user",
166
+ "content": [
167
+ {"type": "text", "text": system + init_instr},
168
+ # Image messages will be added dynamically here
169
+ {"type": "text", "text": query}
170
+ ]
171
+ }
172
+
173
+ # Ensure the images_input is a list
174
+ images_input = ensure_list(images_input)
175
+
176
+ # Add image messages dynamically
177
+ image_messages = [{"type": "image"} for _ in images_input]
178
+ base_message["content"][1:1] = image_messages # Insert image messages before the last text message
179
+
180
+ # Append the constructed message to messages list
181
+ messages.append(base_message)
182
+
183
+ else:
184
+ messages.append (
185
+ {
186
+ "role": "user",
187
+ "content": [
188
+ {"type": "text", "text": query
189
+ }
190
+ ]
191
+ }
192
+ )
193
+ if verbatim:
194
+ print (messages)
195
+
196
+ text = processor.apply_chat_template(messages, add_generation_prompt=True)
197
+ inputs = processor(text=[text.strip()], images=images, return_tensors="pt", padding=True).to(DEVICE)
198
+
199
+ generated_ids = model.generate(**inputs, max_new_tokens=max_new_tokens, temperature=temperature, do_sample=True)
200
+ generated_texts = processor.batch_decode(generated_ids[:, inputs["input_ids"].size(1):], skip_special_tokens=True)
201
+
202
+ messages.append (
203
+ {
204
+ "role": "assistant",
205
+ "content": [ {"type": "text", "text": generated_texts[0]}, ]
206
+ }
207
+ )
208
+ formatted_conversation = format_conversation(messages, images)
209
+
210
+ # Display the formatted conversation, e.g. in Jupyter Notebook
211
+ if show_conversation:
212
+
213
+ if use_Markdown:
214
+ display(Markdown(formatted_conversation))
215
+ else:
216
+ display(HTML(formatted_conversation))
217
+
218
+ return generated_texts, messages, images
219
+
220
+ question = "What is shown in this image, and what is the relevance for materials design? Include a discussion of multi-agent AI."
221
+
222
+ url1 = "https://d2r55xnwy6nx47.cloudfront.net/uploads/2018/02/Ants_Lede1300.jpg"
223
+
224
+ response, messages,images= ask_about_image ( model, processor, question,
225
+ images_input=[url1,],
226
+ temperature=0.1,
227
+ system= '', init_instr='You carefully study the image, and respond accurately, but succinctly. Think step-by-step.\n\n',
228
+ show_conversation=True,
229
+ max_new_tokens=512, messages=[], images=[])
230
+ ```
231
+
232
+ Sample output:
233
+
234
+ ![image/png](https://cdn-uploads.huggingface.co/production/uploads/623ce1c6b66fedf374859fe7/5n6oRNHrfwHkBX0QertZp.png)
235
+ <small>Image by [Vaishakh Manohar](https://www.quantamagazine.org/the-simple-algorithm-that-ants-use-to-build-bridges-20180226/)</small>
236
+
237
+ <pre style="white-space: pre-wrap;">
238
+ The image depicts a group of ants moving in a coordinated manner, demonstrating their ability to navigate complex environments and adapt to changing conditions. This behavior is relevant for materials design because it highlights the potential of multi-agent AI systems to mimic natural systems and develop new materials with enhanced properties.
239
+
240
+ Multi-agent AI refers to the use of multiple autonomous agents working together to solve complex problems. These agents can learn from each other and adapt to new situations, similar to how ants can navigate their environment and communicate with one another. By applying these principles to materials design, researchers can develop new materials that exhibit improved performance, such as enhanced strength, flexibility, and adaptability.
241
+
242
+ The relevance of this image for materials design lies in the inspiration it provides for developing new materials that can mimic the natural efficiency and adaptability of ants. By studying the behavior of ants, researchers can gain insights into how to design materials that can respond dynamically to changes in their environment, leading to improved performance and functionality.
243
+ </pre>
244
+
245
+ ## Dataset generation
246
+
247
+ The schematic below shows a visualization of the approach to generate datasets for training the vision model. The extraction process employs advanced algorithms to accurately detect and separate images and their corresponding textual descriptions from complex PDF documents. It involves extracting images and captions from PDFs to create well-reasoned image-text pairs, utilizing large language models (LLMs) for natural language processing. These image-text pairs are then refined and validated through LLM-based NLP processing, ensuring high-quality and contextually relevant data for training.
248
+
249
+ The image below shows reproductions of two representative pages of the scientific article (here, Spivak, Buehler, et al., 2011), and how they are used to extract visual scientific data for training the Cephalo model.
250
+
251
+ ![image/png](https://cdn-uploads.huggingface.co/production/uploads/623ce1c6b66fedf374859fe7/qHURSBRWEDgHy4o56escN.png)
252
+
253
+ # Further model optimizations
254
+
255
+ If your GPU allows, load and run inference in half precision (`torch.float16` or `torch.bfloat16`).
256
+
257
+ ```diff
258
+ model = AutoModelForVision2Seq.from_pretrained(
259
+ "lamm-mit/Cephalo-Idefics-2-vision-8b-alpha",
260
+ + torch_dtype=torch.float16,
261
+ ).to(DEVICE)
262
+ ```
263
+
264
+ **Vision encoder efficiency**
265
+
266
+ Given the high resolution supported, the vision part of the model can be memory hungry depending on your configuration. If you are GPU-memory-constrained, you can:
267
+ - **deactivate the image splitting.** To do so, add `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.
268
+ - **decrease the maximum image resolution.** To do so, add `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.
269
+
270
+ `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`.
271
+
272
+ **Using Flash-attention 2 to speed up generation**
273
+
274
+ <details><summary>Click to expand.</summary>
275
+
276
+ Mke sure to install `flash-attn`. Refer to the [original repository of Flash Attention](https://github.com/Dao-AILab/flash-attention) for the package installation. Simply change the snippet above with:
277
+
278
+ ```diff
279
+ model = AutoModelForVision2Seq.from_pretrained(
280
+ "lamm-mit/Cephalo-Idefics-2-vision-8b-alpha",
281
+ + torch_dtype=torch.bfloat16,
282
+ + _attn_implementation="flash_attention_2",
283
+ ).to(DEVICE)
284
+ ```
285
+
286
+ </details>
287
+
288
+ **4 bit quantization with bitsandbytes**
289
 
290
+ <details><summary>Click to expand.</summary>
291
+ It is possible to load Idefics2 in 4bits with `bitsandbytes`. Make sure that you have `accelerate` and `bitsandbytes` installed.
 
292
 
293
+ ```diff
294
+ + from transformers import BitsAndBytesConfig
295
 
296
+ quantization_config = BitsAndBytesConfig(
297
+ load_in_4bit=True,
298
+ bnb_4bit_quant_type="nf4",
299
+ bnb_4bit_use_double_quant=True,
300
+ bnb_4bit_compute_dtype=torch.bfloat16
301
+ )
302
+ model = AutoModelForVision2Seq.from_pretrained(
303
+ "lamm-mit/Cephalo-Idefics-2-vision-8b-alpha",
304
+ + torch_dtype=torch.bfloat16,
305
+ + quantization_config=quantization_config,
306
+ ).to(DEVICE)
307
+ ```
308
 
309
+ </details>
310
 
 
311
 
312
+ ## Citation
313
 
314
+ Please cite as:
315
 
316
+ ```bibtex
317
+ @article{Buehler_Cephalo_2024,
318
+ title = {Cephalo, a series of multi-modal vision-language models for bio-inspired materials and mechanics},
319
+ author = {M.J. Buehler},
320
+ journal = {},
321
+ year = {2024},
322
+ volume = {},
323
+ pages = {},
324
+ url = {}
325
+ }
326
+ ```