Spaces:
Runtime error
Runtime error
import os | |
os.system("cd open_flamingo && pip install .") | |
import numpy as np | |
import torch | |
from PIL import Image | |
from open_flamingo.train.distributed import init_distributed_device, world_info_from_env | |
import string | |
import gradio as gr | |
import torch | |
from PIL import Image | |
from huggingface_hub import hf_hub_download, login | |
from open_flamingo.src.factory import create_model_and_transforms | |
flamingo, image_processor, tokenizer, vis_embed_size = create_model_and_transforms( | |
"ViT-L-14", | |
"datacomp_xl_s13b_b90k", | |
"facebook/opt-350m", | |
"facebook/opt-350m", | |
add_visual_grounding=True, | |
location_token_num=1000, | |
add_visual_token = True, | |
use_format_v2 = True, | |
) | |
checkpoint_path = hf_hub_download("chendl/mm", "checkpoint_opt350m.pt") | |
checkpoint = torch.load(args.checkpoint_path, map_location="cpu") | |
model_state_dict = {} | |
for key in checkpoint["model_state_dict"].keys(): | |
model_state_dict[key.replace("module.", "")] = checkpoint["model_state_dict"][key] | |
if "vision_encoder.logit_scale"in model_state_dict: | |
# previous checkpoint has some unnecessary weights | |
del model_state_dict["vision_encoder.logit_scale"] | |
del model_state_dict["vision_encoder.visual.proj"] | |
del model_state_dict["vision_encoder.visual.ln_post.weight"] | |
del model_state_dict["vision_encoder.visual.ln_post.bias"] | |
flamingo.load_state_dict(model_state_dict, strict=True) | |
def generate( | |
idx, | |
image, | |
text, | |
tsvfile, | |
vis_embed_size=256, | |
rank=0, | |
world_size=1, | |
): | |
if image is None: | |
raise gr.Error("Please upload an image.") | |
flamingo.eval().cuda() | |
loc_token_ids = [] | |
for i in range(1000): | |
loc_token_ids.append(int(tokenizer(f"<loc_{i}>", add_special_tokens=False)["input_ids"][-1])) | |
media_token_id = tokenizer("<|#image#|>", add_special_tokens=False)["input_ids"][-1] | |
endofchunk_token_id = tokenizer("<|endofchunk|>", add_special_tokens=False)["input_ids"][-1] | |
endofmedia_token_id = tokenizer("<|#endofimage#|>", add_special_tokens=False)["input_ids"][-1] | |
pad_token_id = tokenizer(tokenizer.pad_token, add_special_tokens=False)["input_ids"][-1] | |
bos_token_id = tokenizer(tokenizer.bos_token, add_special_tokens=False)["input_ids"][-1] | |
all_ids = set(range(flamingo.lang_encoder.lm_head.out_features)) | |
bad_words_ids = list(all_ids - set(loc_token_ids)) | |
bad_words_ids = [[b] for b in bad_words_ids] | |
min_loc_token_id = min(loc_token_ids) | |
max_loc_token_id = max(loc_token_ids) | |
image = Image.open(image).convert("RGB") | |
width = image.width | |
height = image.height | |
image = image.resize((224, 224)) | |
batch_images = image_processor(image).unsqueeze(0).unsqueeze(1).unsqueeze(0) | |
prompt = [f"<|#image#|>{tokenizer.pad_token*vis_embed_size}<|#endofimage#|><|#obj#|>{text.rstrip('.')}"] | |
encodings = tokenizer( | |
prompt, | |
padding="longest", | |
truncation=True, | |
return_tensors="pt", | |
max_length=2000, | |
) | |
input_ids = encodings["input_ids"] | |
attention_mask = encodings["attention_mask"] | |
image_start_index_list = ((input_ids == media_token_id).nonzero(as_tuple=True)[-1] + 1).tolist() | |
image_start_index_list = [[x] for x in image_start_index_list] | |
image_nums = [1] * len(input_ids) | |
outputs = get_outputs( | |
model=flamingo, | |
batch_images=batch_images.cuda(), | |
attention_mask=attention_mask.cuda(), | |
max_generation_length=5, | |
min_generation_length=4, | |
num_beams=1, | |
length_penalty=1.0, | |
input_ids=input_ids.cuda(), | |
bad_words_ids=bad_words_ids, | |
image_start_index_list=image_start_index_list, | |
image_nums=image_nums, | |
) | |
box = [] | |
for o in outputs[0]: | |
if o >= min_loc_token_id and o <= max_loc_token_id: | |
box.append(o.item() - min_loc_token_id) | |
if len(box) == 4: | |
break | |
# else: | |
# tqdm.write(f"output: {tokenizer.batch_decode(outputs)}") | |
# tqdm.write(f"prompt: {prompt}") | |
gen_text = tokenizer.batch_decode(outputs) | |
return ( | |
f"Output:{gen_text}" | |
if idx != 2 | |
else f"Question: {text.strip()} Answer: {gen_text}" | |
) | |
with gr.Blocks() as demo: | |
gr.Markdown( | |
""" | |
# 🦩 OpenFlamingo Demo | |
Blog posts: #1 [Announcing OpenFlamingo: An open-source framework for training vision-language models with in-context learning](https://laion.ai/blog/open-flamingo/) // #2 [OpenFlamingo v2: New Models and Enhanced Training Setup](https://laion.ai/blog/open-flamingo-v2/) | |
GitHub: [open_flamingo](https://github.com/mlfoundations/open_flamingo) | |
In this demo we showcase the in-context learning capabilities of the OpenFlamingo-9B model, a large multimodal model trained on top of mpt-7b. Note that we add two additional demonstrations to the ones presented to improve the demo experience. | |
The model is trained on an interleaved mixture of text and images and is able to generate text conditioned on sequences of images/text. To safeguard against harmful generations, we detect toxic text in the model output and reject it. However, we understand that this is not a perfect solution and we encourage you to use this demo responsibly. If you find that the model is generating harmful text, please report it using this [form](https://forms.gle/StbcPvyyW2p3Pc7z6). | |
""" | |
) | |
with gr.Accordion("See terms and conditions"): | |
gr.Markdown("""**Please read the following information carefully before proceeding.** | |
[OpenFlamingo-9B](https://huggingface.co/openflamingo/OpenFlamingo-9B-vitl-mpt7b) is a **research prototype** that aims to enable users to interact with AI through both language and images. AI agents equipped with both language and visual understanding can be useful on a larger variety of tasks compared to models that communicate solely via language. By releasing an open-source research prototype, we hope to help the research community better understand the risks and limitations of modern visual-language AI models and accelerate the development of safer and more reliable methods. | |
**Limitations.** OpenFlamingo-9B is built on top of the [MPT-7B](https://huggingface.co/mosaicml/mpt-7b) large language model developed by Together.xyz. Large language models are trained on mostly unfiltered internet data, and have been shown to be able to produce toxic, unethical, inaccurate, and harmful content. On top of this, OpenFlamingo’s ability to support visual inputs creates additional risks, since it can be used in a wider variety of applications; image+text models may carry additional risks specific to multimodality. Please use discretion when assessing the accuracy or appropriateness of the model’s outputs, and be mindful before sharing its results. | |
**Privacy and data collection.** This demo does NOT store any personal information on its users, and it does NOT store user queries.""") | |
with gr.Tab("📷 Image Captioning"): | |
with gr.Row(): | |
query_image = gr.Image(type="pil") | |
with gr.Row(): | |
chat_input = gr.Textbox(lines=1, label="Chat Input") | |
text_output = gr.Textbox(value="Output:", label="Model output") | |
run_btn = gr.Button("Run model") | |
def on_click_fn(img,text): return generate(0, img, text) | |
run_btn.click(on_click_fn, inputs=[query_image,chat_input], outputs=[text_output]) | |
with gr.Tab("🦓 Grounding"): | |
with gr.Row(): | |
query_image = gr.Image(type="pil") | |
with gr.Row(): | |
chat_input = gr.Textbox(lines=1, label="Chat Input") | |
text_output = gr.Textbox(value="Output:", label="Model output") | |
run_btn = gr.Button("Run model") | |
def on_click_fn(img,text): return generate(0, img, text) | |
run_btn.click(on_click_fn, inputs=[query_image,chat_input], outputs=[text_output]) | |
with gr.Tab("🔢 Counting objects"): | |
with gr.Row(): | |
query_image = gr.Image(type="pil") | |
with gr.Row(): | |
chat_input = gr.Textbox(lines=1, label="Chat Input") | |
text_output = gr.Textbox(value="Output:", label="Model output") | |
run_btn = gr.Button("Run model") | |
def on_click_fn(img,text): return generate(0, img, text) | |
run_btn.click(on_click_fn, inputs=[query_image, chat_input], outputs=[text_output]) | |
with gr.Tab("🕵️ Visual Question Answering"): | |
with gr.Row(): | |
query_image = gr.Image(type="pil") | |
with gr.Row(): | |
question = gr.Textbox(lines=1, label="Question") | |
text_output = gr.Textbox(value="Output:", label="Model output") | |
run_btn = gr.Button("Run model") | |
def on_click_fn(img, txt): return generate(2, img, txt) | |
run_btn.click( | |
on_click_fn, inputs=[query_image, question], outputs=[text_output] | |
) | |
with gr.Tab("🌎 Custom"): | |
gr.Markdown( | |
"""### Customize the demonstration by uploading your own images and text samples. | |
### **Note: Any text prompt you use will be prepended with an 'Output:', so you don't need to include it in your prompt.**""" | |
) | |
with gr.Row(): | |
query_image = gr.Image(type="pil") | |
with gr.Row(): | |
question = gr.Textbox(lines=1, label="Question") | |
text_output = gr.Textbox(value="Output:", label="Model output") | |
run_btn = gr.Button("Run model") | |
def on_click_fn(img, txt): return generate(2, img, txt) | |
run_btn.click( | |
on_click_fn, inputs=[query_image, question], outputs=[text_output] | |
) | |
demo.queue(concurrency_count=1) | |
demo.launch() |