musashihinck
commited on
Commit
•
3eaf39c
1
Parent(s):
6e532d5
Adding usage and preprocessing script
Browse files- README.md +42 -1
- processing_llavagemma.py +138 -0
- usage.py +38 -0
README.md
CHANGED
@@ -25,7 +25,48 @@ This model has not been assessed for harm or biases, and should not be used for
|
|
25 |
|
26 |
## How to Get Started with the Model
|
27 |
|
28 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
29 |
|
30 |
|
31 |
|
|
|
25 |
|
26 |
## How to Get Started with the Model
|
27 |
|
28 |
+
Currently using `llava-gemma` requires a [modified preprocessor](/processing_llavagemma.py).
|
29 |
+
|
30 |
+
For example usage, see [`usage.py`](/usage.py) or the following code block:
|
31 |
+
|
32 |
+
|
33 |
+
```python
|
34 |
+
import requests
|
35 |
+
from PIL import Image
|
36 |
+
from transformers import (
|
37 |
+
LlavaForConditionalGeneration,
|
38 |
+
AutoTokenizer,
|
39 |
+
CLIPImageProcessor
|
40 |
+
)
|
41 |
+
from processing_llavagemma import LlavaGemmaProcessor # This is in this repo
|
42 |
+
|
43 |
+
checkpoint = "Intel/llava-gemma-2b"
|
44 |
+
|
45 |
+
# Load model
|
46 |
+
model = LlavaForConditionalGeneration.from_pretrained(checkpoint)
|
47 |
+
processor = LlavaGemmaProcessor(
|
48 |
+
tokenizer=AutoTokenizer.from_pretrained(checkpoint),
|
49 |
+
image_processor=CLIPImageProcessor.from_pretrained(checkpoint)
|
50 |
+
)
|
51 |
+
|
52 |
+
# Prepare inputs
|
53 |
+
# Use gemma chat template
|
54 |
+
prompt = processor.tokenizer.apply_chat_template(
|
55 |
+
[{'role': 'user', 'content': "What's the content of the image?<image>"}],
|
56 |
+
tokenize=False,
|
57 |
+
add_generation_prompt=True
|
58 |
+
)
|
59 |
+
url = "https://www.ilankelman.org/stopsigns/australia.jpg"
|
60 |
+
image = Image.open(requests.get(url, stream=True).raw)
|
61 |
+
inputs = processor(text=prompt, images=image, return_tensors="pt")
|
62 |
+
inputs = {k: v.to('cuda') for k, v in inputs.items()}
|
63 |
+
|
64 |
+
# Generate
|
65 |
+
generate_ids = model.generate(**inputs, max_length=30)
|
66 |
+
output = processor.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
|
67 |
+
print(output)
|
68 |
+
|
69 |
+
```
|
70 |
|
71 |
|
72 |
|
processing_llavagemma.py
ADDED
@@ -0,0 +1,138 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# coding=utf-8
|
2 |
+
# Copyright 2023 The HuggingFace Inc. team.
|
3 |
+
#
|
4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
5 |
+
# you may not use this file except in compliance with the License.
|
6 |
+
# You may obtain a copy of the License at
|
7 |
+
#
|
8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
9 |
+
#
|
10 |
+
# Unless required by applicable law or agreed to in writing, software
|
11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
13 |
+
# See the License for the specific language governing permissions and
|
14 |
+
# limitations under the License.
|
15 |
+
"""
|
16 |
+
Processor class for Llava.
|
17 |
+
Modified to include support for Gemma tokenizer.
|
18 |
+
"""
|
19 |
+
|
20 |
+
|
21 |
+
from typing import List, Optional, Union
|
22 |
+
|
23 |
+
from transformers.feature_extraction_utils import BatchFeature
|
24 |
+
from transformers.image_utils import ImageInput
|
25 |
+
from transformers.processing_utils import ProcessorMixin
|
26 |
+
from transformers.tokenization_utils_base import PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy
|
27 |
+
from transformers.utils import TensorType
|
28 |
+
|
29 |
+
|
30 |
+
class LlavaGemmaProcessor(ProcessorMixin):
|
31 |
+
r"""
|
32 |
+
Constructs a Llava processor which wraps a Llava image processor and a Llava tokenizer into a single processor.
|
33 |
+
|
34 |
+
[`LlavaProcessor`] offers all the functionalities of [`CLIPImageProcessor`] and [`LlamaTokenizerFast`]. See the
|
35 |
+
[`~LlavaProcessor.__call__`] and [`~LlavaProcessor.decode`] for more information.
|
36 |
+
|
37 |
+
Args:
|
38 |
+
image_processor ([`CLIPImageProcessor`], *optional*):
|
39 |
+
The image processor is a required input.
|
40 |
+
tokenizer ([`LlamaTokenizerFast`], *optional*):
|
41 |
+
The tokenizer is a required input.
|
42 |
+
"""
|
43 |
+
|
44 |
+
attributes = ["image_processor", "tokenizer"]
|
45 |
+
image_processor_class = "CLIPImageProcessor"
|
46 |
+
tokenizer_class = ("LlamaTokenizer", "LlamaTokenizerFast",
|
47 |
+
"GemmaTokenizer", "GemmaTokenizerFast")
|
48 |
+
|
49 |
+
def __init__(self, image_processor=None, tokenizer=None):
|
50 |
+
super().__init__(image_processor, tokenizer)
|
51 |
+
|
52 |
+
def __call__(
|
53 |
+
self,
|
54 |
+
text: Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None,
|
55 |
+
images: ImageInput = None,
|
56 |
+
padding: Union[bool, str, PaddingStrategy] = False,
|
57 |
+
truncation: Union[bool, str, TruncationStrategy] = None,
|
58 |
+
max_length=None,
|
59 |
+
return_tensors: Optional[Union[str, TensorType]] = TensorType.PYTORCH,
|
60 |
+
) -> BatchFeature:
|
61 |
+
"""
|
62 |
+
Main method to prepare for the model one or several sequences(s) and image(s). This method forwards the `text`
|
63 |
+
and `kwargs` arguments to LlamaTokenizerFast's [`~LlamaTokenizerFast.__call__`] if `text` is not `None` to encode
|
64 |
+
the text. To prepare the image(s), this method forwards the `images` and `kwrags` arguments to
|
65 |
+
CLIPImageProcessor's [`~CLIPImageProcessor.__call__`] if `images` is not `None`. Please refer to the doctsring
|
66 |
+
of the above two methods for more information.
|
67 |
+
|
68 |
+
Args:
|
69 |
+
text (`str`, `List[str]`, `List[List[str]]`):
|
70 |
+
The sequence or batch of sequences to be encoded. Each sequence can be a string or a list of strings
|
71 |
+
(pretokenized string). If the sequences are provided as list of strings (pretokenized), you must set
|
72 |
+
`is_split_into_words=True` (to lift the ambiguity with a batch of sequences).
|
73 |
+
images (`PIL.Image.Image`, `np.ndarray`, `torch.Tensor`, `List[PIL.Image.Image]`, `List[np.ndarray]`, `List[torch.Tensor]`):
|
74 |
+
The image or batch of images to be prepared. Each image can be a PIL image, NumPy array or PyTorch
|
75 |
+
tensor. In case of a NumPy array/PyTorch tensor, each image should be of shape (C, H, W), where C is a
|
76 |
+
number of channels, H and W are image height and width.
|
77 |
+
padding (`bool`, `str` or [`~utils.PaddingStrategy`], *optional*, defaults to `False`):
|
78 |
+
Select a strategy to pad the returned sequences (according to the model's padding side and padding
|
79 |
+
index) among:
|
80 |
+
- `True` or `'longest'`: Pad to the longest sequence in the batch (or no padding if only a single
|
81 |
+
sequence if provided).
|
82 |
+
- `'max_length'`: Pad to a maximum length specified with the argument `max_length` or to the maximum
|
83 |
+
acceptable input length for the model if that argument is not provided.
|
84 |
+
- `False` or `'do_not_pad'` (default): No padding (i.e., can output a batch with sequences of different
|
85 |
+
lengths).
|
86 |
+
max_length (`int`, *optional*):
|
87 |
+
Maximum length of the returned list and optionally padding length (see above).
|
88 |
+
truncation (`bool`, *optional*):
|
89 |
+
Activates truncation to cut input sequences longer than `max_length` to `max_length`.
|
90 |
+
return_tensors (`str` or [`~utils.TensorType`], *optional*):
|
91 |
+
If set, will return tensors of a particular framework. Acceptable values are:
|
92 |
+
|
93 |
+
- `'tf'`: Return TensorFlow `tf.constant` objects.
|
94 |
+
- `'pt'`: Return PyTorch `torch.Tensor` objects.
|
95 |
+
- `'np'`: Return NumPy `np.ndarray` objects.
|
96 |
+
- `'jax'`: Return JAX `jnp.ndarray` objects.
|
97 |
+
|
98 |
+
Returns:
|
99 |
+
[`BatchFeature`]: A [`BatchFeature`] with the following fields:
|
100 |
+
|
101 |
+
- **input_ids** -- List of token ids to be fed to a model. Returned when `text` is not `None`.
|
102 |
+
- **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when
|
103 |
+
`return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names` and if `text` is not
|
104 |
+
`None`).
|
105 |
+
- **pixel_values** -- Pixel values to be fed to a model. Returned when `images` is not `None`.
|
106 |
+
"""
|
107 |
+
if images is not None:
|
108 |
+
pixel_values = self.image_processor(images, return_tensors=return_tensors)["pixel_values"]
|
109 |
+
else:
|
110 |
+
pixel_values = None
|
111 |
+
text_inputs = self.tokenizer(
|
112 |
+
text, return_tensors=return_tensors, padding=padding, truncation=truncation, max_length=max_length
|
113 |
+
)
|
114 |
+
|
115 |
+
return BatchFeature(data={**text_inputs, "pixel_values": pixel_values})
|
116 |
+
|
117 |
+
# Copied from transformers.models.clip.processing_clip.CLIPProcessor.batch_decode with CLIP->Llama
|
118 |
+
def batch_decode(self, *args, **kwargs):
|
119 |
+
"""
|
120 |
+
This method forwards all its arguments to LlamaTokenizerFast's [`~PreTrainedTokenizer.batch_decode`]. Please
|
121 |
+
refer to the docstring of this method for more information.
|
122 |
+
"""
|
123 |
+
return self.tokenizer.batch_decode(*args, **kwargs)
|
124 |
+
|
125 |
+
# Copied from transformers.models.clip.processing_clip.CLIPProcessor.decode with CLIP->Llama
|
126 |
+
def decode(self, *args, **kwargs):
|
127 |
+
"""
|
128 |
+
This method forwards all its arguments to LlamaTokenizerFast's [`~PreTrainedTokenizer.decode`]. Please refer to
|
129 |
+
the docstring of this method for more information.
|
130 |
+
"""
|
131 |
+
return self.tokenizer.decode(*args, **kwargs)
|
132 |
+
|
133 |
+
@property
|
134 |
+
# Copied from transformers.models.clip.processing_clip.CLIPProcessor.model_input_names
|
135 |
+
def model_input_names(self):
|
136 |
+
tokenizer_input_names = self.tokenizer.model_input_names
|
137 |
+
image_processor_input_names = self.image_processor.model_input_names
|
138 |
+
return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names))
|
usage.py
ADDED
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import transformers
|
2 |
+
|
3 |
+
print(transformers.__version__)
|
4 |
+
|
5 |
+
import requests
|
6 |
+
from PIL import Image
|
7 |
+
from transformers import (
|
8 |
+
LlavaForConditionalGeneration,
|
9 |
+
AutoTokenizer,
|
10 |
+
CLIPImageProcessor
|
11 |
+
)
|
12 |
+
from processing_llavagemma import LlavaGemmaProcessor
|
13 |
+
|
14 |
+
checkpoint = "Intel/llava-gemma-2b"
|
15 |
+
|
16 |
+
model = LlavaForConditionalGeneration.from_pretrained(checkpoint)
|
17 |
+
processor = LlavaGemmaProcessor(
|
18 |
+
tokenizer=AutoTokenizer.from_pretrained(checkpoint),
|
19 |
+
image_processor=CLIPImageProcessor.from_pretrained(checkpoint)
|
20 |
+
)
|
21 |
+
|
22 |
+
model.to('cuda')
|
23 |
+
|
24 |
+
|
25 |
+
prompt = processor.tokenizer.apply_chat_template(
|
26 |
+
[{'role': 'user', 'content': "What's the content of the image?<image>"}],
|
27 |
+
tokenize=False,
|
28 |
+
add_generation_prompt=True
|
29 |
+
)
|
30 |
+
url = "https://www.ilankelman.org/stopsigns/australia.jpg"
|
31 |
+
image = Image.open(requests.get(url, stream=True).raw)
|
32 |
+
inputs = processor(text=prompt, images=image, return_tensors="pt")
|
33 |
+
inputs = {k: v.to('cuda') for k, v in inputs.items()}
|
34 |
+
|
35 |
+
# Generate
|
36 |
+
generate_ids = model.generate(**inputs, max_length=30)
|
37 |
+
output = processor.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
|
38 |
+
print(output)
|