Spaces:
Running
on
Zero
Running
on
Zero
Upload 4 files
Browse files- README.md +12 -12
- app.py +40 -129
- joycaption.py +250 -0
- requirements.txt +8 -5
README.md
CHANGED
|
@@ -1,13 +1,13 @@
|
|
| 1 |
-
---
|
| 2 |
-
title: Joy Caption Pre Alpha
|
| 3 |
-
emoji: 💬
|
| 4 |
-
colorFrom: yellow
|
| 5 |
-
colorTo: purple
|
| 6 |
-
sdk: gradio
|
| 7 |
-
sdk_version: 4.
|
| 8 |
-
app_file: app.py
|
| 9 |
-
pinned: false
|
| 10 |
-
license: mit
|
| 11 |
-
---
|
| 12 |
-
|
| 13 |
An example chatbot using [Gradio](https://gradio.app), [`huggingface_hub`](https://huggingface.co/docs/huggingface_hub/v0.22.2/en/index), and the [Hugging Face Inference API](https://huggingface.co/docs/api-inference/index).
|
|
|
|
| 1 |
+
---
|
| 2 |
+
title: Joy Caption Pre Alpha Mod
|
| 3 |
+
emoji: 💬
|
| 4 |
+
colorFrom: yellow
|
| 5 |
+
colorTo: purple
|
| 6 |
+
sdk: gradio
|
| 7 |
+
sdk_version: 4.43.0
|
| 8 |
+
app_file: app.py
|
| 9 |
+
pinned: false
|
| 10 |
+
license: mit
|
| 11 |
+
---
|
| 12 |
+
|
| 13 |
An example chatbot using [Gradio](https://gradio.app), [`huggingface_hub`](https://huggingface.co/docs/huggingface_hub/v0.22.2/en/index), and the [Hugging Face Inference API](https://huggingface.co/docs/api-inference/index).
|
app.py
CHANGED
|
@@ -1,129 +1,40 @@
|
|
| 1 |
-
import spaces
|
| 2 |
-
import gradio as gr
|
| 3 |
-
from
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
clip_model.eval()
|
| 42 |
-
clip_model.requires_grad_(False)
|
| 43 |
-
clip_model.to("cuda")
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
# Tokenizer
|
| 47 |
-
print("Loading tokenizer")
|
| 48 |
-
tokenizer = AutoTokenizer.from_pretrained(MODEL_PATH, use_fast=False)
|
| 49 |
-
assert isinstance(tokenizer, PreTrainedTokenizer) or isinstance(tokenizer, PreTrainedTokenizerFast), f"Tokenizer is of type {type(tokenizer)}"
|
| 50 |
-
|
| 51 |
-
# LLM
|
| 52 |
-
print("Loading LLM")
|
| 53 |
-
text_model = AutoModelForCausalLM.from_pretrained(MODEL_PATH, device_map="auto", torch_dtype=torch.bfloat16)
|
| 54 |
-
text_model.eval()
|
| 55 |
-
|
| 56 |
-
# Image Adapter
|
| 57 |
-
print("Loading image adapter")
|
| 58 |
-
image_adapter = ImageAdapter(clip_model.config.hidden_size, text_model.config.hidden_size)
|
| 59 |
-
image_adapter.load_state_dict(torch.load(CHECKPOINT_PATH / "image_adapter.pt", map_location="cpu"))
|
| 60 |
-
image_adapter.eval()
|
| 61 |
-
image_adapter.to("cuda")
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
@spaces.GPU()
|
| 65 |
-
@torch.no_grad()
|
| 66 |
-
def stream_chat(input_image: Image.Image):
|
| 67 |
-
torch.cuda.empty_cache()
|
| 68 |
-
|
| 69 |
-
# Preprocess image
|
| 70 |
-
image = clip_processor(images=input_image, return_tensors='pt').pixel_values
|
| 71 |
-
image = image.to('cuda')
|
| 72 |
-
|
| 73 |
-
# Tokenize the prompt
|
| 74 |
-
prompt = tokenizer.encode(VLM_PROMPT, return_tensors='pt', padding=False, truncation=False, add_special_tokens=False)
|
| 75 |
-
|
| 76 |
-
# Embed image
|
| 77 |
-
with torch.amp.autocast_mode.autocast('cuda', enabled=True):
|
| 78 |
-
vision_outputs = clip_model(pixel_values=image, output_hidden_states=True)
|
| 79 |
-
image_features = vision_outputs.hidden_states[-2]
|
| 80 |
-
embedded_images = image_adapter(image_features)
|
| 81 |
-
embedded_images = embedded_images.to('cuda')
|
| 82 |
-
|
| 83 |
-
# Embed prompt
|
| 84 |
-
prompt_embeds = text_model.model.embed_tokens(prompt.to('cuda'))
|
| 85 |
-
assert prompt_embeds.shape == (1, prompt.shape[1], text_model.config.hidden_size), f"Prompt shape is {prompt_embeds.shape}, expected {(1, prompt.shape[1], text_model.config.hidden_size)}"
|
| 86 |
-
embedded_bos = text_model.model.embed_tokens(torch.tensor([[tokenizer.bos_token_id]], device=text_model.device, dtype=torch.int64))
|
| 87 |
-
|
| 88 |
-
# Construct prompts
|
| 89 |
-
inputs_embeds = torch.cat([
|
| 90 |
-
embedded_bos.expand(embedded_images.shape[0], -1, -1),
|
| 91 |
-
embedded_images.to(dtype=embedded_bos.dtype),
|
| 92 |
-
prompt_embeds.expand(embedded_images.shape[0], -1, -1),
|
| 93 |
-
], dim=1)
|
| 94 |
-
|
| 95 |
-
input_ids = torch.cat([
|
| 96 |
-
torch.tensor([[tokenizer.bos_token_id]], dtype=torch.long),
|
| 97 |
-
torch.zeros((1, embedded_images.shape[1]), dtype=torch.long),
|
| 98 |
-
prompt,
|
| 99 |
-
], dim=1).to('cuda')
|
| 100 |
-
attention_mask = torch.ones_like(input_ids)
|
| 101 |
-
|
| 102 |
-
#generate_ids = text_model.generate(input_ids, inputs_embeds=inputs_embeds, attention_mask=attention_mask, max_new_tokens=300, do_sample=False, suppress_tokens=None)
|
| 103 |
-
generate_ids = text_model.generate(input_ids, inputs_embeds=inputs_embeds, attention_mask=attention_mask, max_new_tokens=300, do_sample=True, top_k=10, temperature=0.5, suppress_tokens=None)
|
| 104 |
-
|
| 105 |
-
# Trim off the prompt
|
| 106 |
-
generate_ids = generate_ids[:, input_ids.shape[1]:]
|
| 107 |
-
if generate_ids[0][-1] == tokenizer.eos_token_id:
|
| 108 |
-
generate_ids = generate_ids[:, :-1]
|
| 109 |
-
|
| 110 |
-
caption = tokenizer.batch_decode(generate_ids, skip_special_tokens=False, clean_up_tokenization_spaces=False)[0]
|
| 111 |
-
|
| 112 |
-
return caption.strip()
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
with gr.Blocks() as demo:
|
| 116 |
-
gr.HTML(TITLE)
|
| 117 |
-
with gr.Row():
|
| 118 |
-
with gr.Column():
|
| 119 |
-
input_image = gr.Image(type="pil", label="Input Image")
|
| 120 |
-
run_button = gr.Button("Caption")
|
| 121 |
-
|
| 122 |
-
with gr.Column():
|
| 123 |
-
output_caption = gr.Textbox(label="Caption")
|
| 124 |
-
|
| 125 |
-
run_button.click(fn=stream_chat, inputs=[input_image], outputs=[output_caption])
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
if __name__ == "__main__":
|
| 129 |
-
demo.launch()
|
|
|
|
| 1 |
+
import spaces
|
| 2 |
+
import gradio as gr
|
| 3 |
+
from joycaption import stream_chat_mod, get_text_model, change_text_model
|
| 4 |
+
|
| 5 |
+
JC_TITLE_MD = "<h1><center>JoyCaption Pre-Alpha Mod</center></h1>"
|
| 6 |
+
JC_DESC_MD = """This space is mod of [fancyfeast/joy-caption-pre-alpha](https://huggingface.co/spaces/fancyfeast/joy-caption-pre-alpha),
|
| 7 |
+
[Wi-zz/joy-caption-pre-alpha](https://huggingface.co/Wi-zz/joy-caption-pre-alpha)"""
|
| 8 |
+
|
| 9 |
+
css = """
|
| 10 |
+
.info {text-align:center; display:inline-flex; align-items:center !important}
|
| 11 |
+
"""
|
| 12 |
+
|
| 13 |
+
with gr.Blocks() as demo:
|
| 14 |
+
gr.HTML(JC_TITLE_MD)
|
| 15 |
+
with gr.Row():
|
| 16 |
+
with gr.Column():
|
| 17 |
+
with gr.Group():
|
| 18 |
+
jc_input_image = gr.Image(type="pil", label="Input Image", sources=["upload", "clipboard"], height=384)
|
| 19 |
+
with gr.Accordion("Advanced", open=False):
|
| 20 |
+
jc_text_model = gr.Dropdown(label="LLM Model", info="You can enter a huggingface model repo_id to want to use.",
|
| 21 |
+
choices=get_text_model(), value=get_text_model()[0],
|
| 22 |
+
allow_custom_value=True, interactive=True, min_width=320)
|
| 23 |
+
jc_use_inference_client = gr.Checkbox(label="Use Inference Client", value=False, visible=False)
|
| 24 |
+
with gr.Row():
|
| 25 |
+
jc_tokens = gr.Slider(minimum=1, maximum=4096, value=300, step=1, label="Max tokens")
|
| 26 |
+
jc_temperature = gr.Slider(minimum=0.1, maximum=4.0, value=0.5, step=0.1, label="Temperature")
|
| 27 |
+
jc_topk = gr.Slider(minimum=0, maximum=100, value=40, step=10, label="Top-k")
|
| 28 |
+
jc_run_button = gr.Button("Caption", variant="primary")
|
| 29 |
+
|
| 30 |
+
with gr.Column():
|
| 31 |
+
jc_output_caption = gr.Textbox(label="Caption", show_copy_button=True)
|
| 32 |
+
gr.Markdown(JC_DESC_MD, elem_classes="info")
|
| 33 |
+
|
| 34 |
+
jc_run_button.click(fn=stream_chat_mod, inputs=[jc_input_image, jc_tokens, jc_topk, jc_temperature], outputs=[jc_output_caption])
|
| 35 |
+
jc_text_model.change(change_text_model, [jc_text_model, jc_use_inference_client], [jc_text_model], show_api=False)
|
| 36 |
+
jc_use_inference_client.change(change_text_model, [jc_text_model, jc_use_inference_client], [jc_text_model], show_api=False)
|
| 37 |
+
|
| 38 |
+
if __name__ == "__main__":
|
| 39 |
+
demo.queue()
|
| 40 |
+
demo.launch()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
joycaption.py
ADDED
|
@@ -0,0 +1,250 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import spaces
|
| 2 |
+
import gradio as gr
|
| 3 |
+
from huggingface_hub import InferenceClient
|
| 4 |
+
from torch import nn
|
| 5 |
+
from transformers import AutoModel, AutoProcessor, AutoTokenizer, PreTrainedTokenizer, PreTrainedTokenizerFast, AutoModelForCausalLM
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
import torch
|
| 8 |
+
import torch.amp.autocast_mode
|
| 9 |
+
from PIL import Image
|
| 10 |
+
import os
|
| 11 |
+
import gc
|
| 12 |
+
|
| 13 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 14 |
+
|
| 15 |
+
llm_models = [
|
| 16 |
+
"Sao10K/Llama-3.1-8B-Stheno-v3.4",
|
| 17 |
+
"unsloth/Meta-Llama-3.1-8B-bnb-4bit",
|
| 18 |
+
"mergekit-community/L3.1-Boshima-b-FIX",
|
| 19 |
+
"meta-llama/Meta-Llama-3.1-8B",
|
| 20 |
+
]
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
CLIP_PATH = "google/siglip-so400m-patch14-384"
|
| 24 |
+
VLM_PROMPT = "A descriptive caption for this image:\n"
|
| 25 |
+
MODEL_PATH = llm_models[0]
|
| 26 |
+
CHECKPOINT_PATH = Path("wpkklhc6")
|
| 27 |
+
TITLE = "<h1><center>JoyCaption Pre-Alpha (2024-07-30a)</center></h1>"
|
| 28 |
+
|
| 29 |
+
HF_TOKEN = os.environ.get("HF_TOKEN", None)
|
| 30 |
+
use_inference_client = False
|
| 31 |
+
|
| 32 |
+
class ImageAdapter(nn.Module):
|
| 33 |
+
def __init__(self, input_features: int, output_features: int):
|
| 34 |
+
super().__init__()
|
| 35 |
+
self.linear1 = nn.Linear(input_features, output_features)
|
| 36 |
+
self.activation = nn.GELU()
|
| 37 |
+
self.linear2 = nn.Linear(output_features, output_features)
|
| 38 |
+
|
| 39 |
+
def forward(self, vision_outputs: torch.Tensor):
|
| 40 |
+
x = self.linear1(vision_outputs)
|
| 41 |
+
x = self.activation(x)
|
| 42 |
+
x = self.linear2(x)
|
| 43 |
+
return x
|
| 44 |
+
|
| 45 |
+
# https://huggingface.co/docs/transformers/main/en/main_classes/quantization#offload-between-cpu-and-gpu
|
| 46 |
+
# https://huggingface.co/google/flan-ul2/discussions/8
|
| 47 |
+
|
| 48 |
+
text_model_client = None
|
| 49 |
+
text_model = None
|
| 50 |
+
image_adapter = None
|
| 51 |
+
def load_text_model(model_name: str=MODEL_PATH):
|
| 52 |
+
global text_model
|
| 53 |
+
global image_adapter
|
| 54 |
+
global text_model_client
|
| 55 |
+
global use_inference_client
|
| 56 |
+
try:
|
| 57 |
+
print(f"Loading LLM: {model_name}")
|
| 58 |
+
if device == "cpu": text_model = AutoModelForCausalLM.from_pretrained(model_name, device_map=device, torch_dtype=torch.bfloat16).eval()
|
| 59 |
+
else: text_model = AutoModelForCausalLM.from_pretrained(model_name, device_map=device, torch_dtype=torch.bfloat16).eval()
|
| 60 |
+
print("Loading image adapter")
|
| 61 |
+
image_adapter = ImageAdapter(clip_model.config.hidden_size, text_model.config.hidden_size).eval().to("cpu")
|
| 62 |
+
image_adapter.load_state_dict(torch.load(CHECKPOINT_PATH / "image_adapter.pt", map_location="cpu", weights_only=True))
|
| 63 |
+
image_adapter.eval().to(device)
|
| 64 |
+
except Exception as e:
|
| 65 |
+
print(f"LLM load error: {e}")
|
| 66 |
+
raise Exception(f"LLM load error: {e}") from e
|
| 67 |
+
finally:
|
| 68 |
+
torch.cuda.empty_cache()
|
| 69 |
+
gc.collect()
|
| 70 |
+
|
| 71 |
+
load_text_model.zerogpu = True
|
| 72 |
+
|
| 73 |
+
# Load CLIP
|
| 74 |
+
print("Loading CLIP")
|
| 75 |
+
clip_processor = AutoProcessor.from_pretrained(CLIP_PATH)
|
| 76 |
+
clip_model = AutoModel.from_pretrained(CLIP_PATH).vision_model.eval().requires_grad_(False).to(device)
|
| 77 |
+
|
| 78 |
+
# Tokenizer
|
| 79 |
+
print("Loading tokenizer")
|
| 80 |
+
tokenizer = AutoTokenizer.from_pretrained(MODEL_PATH, use_fast=False)
|
| 81 |
+
assert isinstance(tokenizer, PreTrainedTokenizer) or isinstance(tokenizer, PreTrainedTokenizerFast), f"Tokenizer is of type {type(tokenizer)}"
|
| 82 |
+
|
| 83 |
+
# LLM
|
| 84 |
+
# Image Adapter
|
| 85 |
+
load_text_model()
|
| 86 |
+
|
| 87 |
+
@spaces.GPU()
|
| 88 |
+
@torch.no_grad()
|
| 89 |
+
def stream_chat(input_image: Image.Image):
|
| 90 |
+
torch.cuda.empty_cache()
|
| 91 |
+
|
| 92 |
+
# Preprocess image
|
| 93 |
+
image = clip_processor(images=input_image, return_tensors='pt').pixel_values
|
| 94 |
+
image = image.to(device)
|
| 95 |
+
|
| 96 |
+
# Tokenize the prompt
|
| 97 |
+
prompt = tokenizer.encode(VLM_PROMPT, return_tensors='pt', padding=False, truncation=False, add_special_tokens=False)
|
| 98 |
+
|
| 99 |
+
# Embed image
|
| 100 |
+
with torch.amp.autocast_mode.autocast(device, enabled=True):
|
| 101 |
+
vision_outputs = clip_model(pixel_values=image, output_hidden_states=True)
|
| 102 |
+
image_features = vision_outputs.hidden_states[-2]
|
| 103 |
+
embedded_images = image_adapter(image_features)
|
| 104 |
+
embedded_images = embedded_images.to(device)
|
| 105 |
+
|
| 106 |
+
# Embed prompt
|
| 107 |
+
prompt_embeds = text_model.model.embed_tokens(prompt.to(device))
|
| 108 |
+
assert prompt_embeds.shape == (1, prompt.shape[1], text_model.config.hidden_size), f"Prompt shape is {prompt_embeds.shape}, expected {(1, prompt.shape[1], text_model.config.hidden_size)}"
|
| 109 |
+
embedded_bos = text_model.model.embed_tokens(torch.tensor([[tokenizer.bos_token_id]], device=text_model.device, dtype=torch.int64))
|
| 110 |
+
|
| 111 |
+
# Construct prompts
|
| 112 |
+
inputs_embeds = torch.cat([
|
| 113 |
+
embedded_bos.expand(embedded_images.shape[0], -1, -1),
|
| 114 |
+
embedded_images.to(dtype=embedded_bos.dtype),
|
| 115 |
+
prompt_embeds.expand(embedded_images.shape[0], -1, -1),
|
| 116 |
+
], dim=1)
|
| 117 |
+
|
| 118 |
+
input_ids = torch.cat([
|
| 119 |
+
torch.tensor([[tokenizer.bos_token_id]], dtype=torch.long),
|
| 120 |
+
torch.zeros((1, embedded_images.shape[1]), dtype=torch.long),
|
| 121 |
+
prompt,
|
| 122 |
+
], dim=1).to(device)
|
| 123 |
+
attention_mask = torch.ones_like(input_ids)
|
| 124 |
+
|
| 125 |
+
#generate_ids = text_model.generate(input_ids, inputs_embeds=inputs_embeds, attention_mask=attention_mask, max_new_tokens=300, do_sample=False, suppress_tokens=None)
|
| 126 |
+
generate_ids = text_model.generate(input_ids, inputs_embeds=inputs_embeds, attention_mask=attention_mask, max_new_tokens=300, do_sample=True, top_k=10, temperature=0.5, suppress_tokens=None)
|
| 127 |
+
|
| 128 |
+
# Trim off the prompt
|
| 129 |
+
generate_ids = generate_ids[:, input_ids.shape[1]:]
|
| 130 |
+
if generate_ids[0][-1] == tokenizer.eos_token_id:
|
| 131 |
+
generate_ids = generate_ids[:, :-1]
|
| 132 |
+
|
| 133 |
+
caption = tokenizer.batch_decode(generate_ids, skip_special_tokens=False, clean_up_tokenization_spaces=False)[0]
|
| 134 |
+
|
| 135 |
+
return caption.strip()
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
@spaces.GPU()
|
| 139 |
+
@torch.no_grad()
|
| 140 |
+
def stream_chat_mod(input_image: Image.Image, max_new_tokens: int=300, top_k: int=10, temperature: float=0.5, progress=gr.Progress(track_tqdm=True)):
|
| 141 |
+
global use_inference_client
|
| 142 |
+
global text_model
|
| 143 |
+
torch.cuda.empty_cache()
|
| 144 |
+
gc.collect()
|
| 145 |
+
|
| 146 |
+
# Preprocess image
|
| 147 |
+
image = clip_processor(images=input_image, return_tensors='pt').pixel_values
|
| 148 |
+
image = image.to(device)
|
| 149 |
+
|
| 150 |
+
# Tokenize the prompt
|
| 151 |
+
prompt = tokenizer.encode(VLM_PROMPT, return_tensors='pt', padding=False, truncation=False, add_special_tokens=False)
|
| 152 |
+
|
| 153 |
+
# Embed image
|
| 154 |
+
with torch.amp.autocast_mode.autocast(device, enabled=True):
|
| 155 |
+
vision_outputs = clip_model(pixel_values=image, output_hidden_states=True)
|
| 156 |
+
image_features = vision_outputs.hidden_states[-2]
|
| 157 |
+
embedded_images = image_adapter(image_features)
|
| 158 |
+
embedded_images = embedded_images.to(device)
|
| 159 |
+
|
| 160 |
+
# Embed prompt
|
| 161 |
+
prompt_embeds = text_model.model.embed_tokens(prompt.to(device))
|
| 162 |
+
assert prompt_embeds.shape == (1, prompt.shape[1], text_model.config.hidden_size), f"Prompt shape is {prompt_embeds.shape}, expected {(1, prompt.shape[1], text_model.config.hidden_size)}"
|
| 163 |
+
embedded_bos = text_model.model.embed_tokens(torch.tensor([[tokenizer.bos_token_id]], device=text_model.device, dtype=torch.int64))
|
| 164 |
+
|
| 165 |
+
# Construct prompts
|
| 166 |
+
inputs_embeds = torch.cat([
|
| 167 |
+
embedded_bos.expand(embedded_images.shape[0], -1, -1),
|
| 168 |
+
embedded_images.to(dtype=embedded_bos.dtype),
|
| 169 |
+
prompt_embeds.expand(embedded_images.shape[0], -1, -1),
|
| 170 |
+
], dim=1)
|
| 171 |
+
|
| 172 |
+
input_ids = torch.cat([
|
| 173 |
+
torch.tensor([[tokenizer.bos_token_id]], dtype=torch.long),
|
| 174 |
+
torch.zeros((1, embedded_images.shape[1]), dtype=torch.long),
|
| 175 |
+
prompt,
|
| 176 |
+
], dim=1).to(device)
|
| 177 |
+
attention_mask = torch.ones_like(input_ids)
|
| 178 |
+
|
| 179 |
+
# https://huggingface.co/docs/huggingface_hub/guides/inference#openai-compatibility
|
| 180 |
+
# https://huggingface.co/docs/huggingface_hub/v0.24.6/en/package_reference/inference_client#huggingface_hub.InferenceClient.text_generation
|
| 181 |
+
#generate_ids = text_model.generate(input_ids, inputs_embeds=inputs_embeds, attention_mask=attention_mask, max_new_tokens=300, do_sample=False, suppress_tokens=None)
|
| 182 |
+
generate_ids = text_model.generate(input_ids, inputs_embeds=inputs_embeds, attention_mask=attention_mask,
|
| 183 |
+
max_new_tokens=max_new_tokens, do_sample=True, top_k=top_k, temperature=temperature, suppress_tokens=None)
|
| 184 |
+
|
| 185 |
+
# Trim off the prompt
|
| 186 |
+
generate_ids = generate_ids[:, input_ids.shape[1]:]
|
| 187 |
+
if generate_ids[0][-1] == tokenizer.eos_token_id:
|
| 188 |
+
generate_ids = generate_ids[:, :-1]
|
| 189 |
+
|
| 190 |
+
caption = tokenizer.batch_decode(generate_ids, skip_special_tokens=False, clean_up_tokenization_spaces=False)[0]
|
| 191 |
+
|
| 192 |
+
return caption.strip()
|
| 193 |
+
|
| 194 |
+
|
| 195 |
+
def is_repo_name(s):
|
| 196 |
+
import re
|
| 197 |
+
return re.fullmatch(r'^[^/,\s\"\']+/[^/,\s\"\']+$', s)
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
def is_repo_exists(repo_id):
|
| 201 |
+
from huggingface_hub import HfApi
|
| 202 |
+
api = HfApi()
|
| 203 |
+
try:
|
| 204 |
+
if api.repo_exists(repo_id=repo_id): return True
|
| 205 |
+
else: return False
|
| 206 |
+
except Exception as e:
|
| 207 |
+
print(f"Error: Failed to connect {repo_id}.")
|
| 208 |
+
print(e)
|
| 209 |
+
return True # for safe
|
| 210 |
+
|
| 211 |
+
|
| 212 |
+
def get_text_model():
|
| 213 |
+
return llm_models
|
| 214 |
+
|
| 215 |
+
|
| 216 |
+
@spaces.GPU()
|
| 217 |
+
def change_text_model(model_name: str=MODEL_PATH, use_client: bool=False, progress=gr.Progress(track_tqdm=True)):
|
| 218 |
+
global use_inference_client
|
| 219 |
+
global text_model
|
| 220 |
+
global llm_models
|
| 221 |
+
use_inference_client = use_client
|
| 222 |
+
try:
|
| 223 |
+
if not is_repo_name(model_name) or not is_repo_exists(model_name):
|
| 224 |
+
raise gr.Error(f"Repo doesn't exist: {model_name}")
|
| 225 |
+
if use_inference_client:
|
| 226 |
+
pass
|
| 227 |
+
else:
|
| 228 |
+
load_text_model(model_name)
|
| 229 |
+
if model_name not in llm_models: llm_models.append(model_name)
|
| 230 |
+
return gr.update(visible=True)
|
| 231 |
+
except Exception as e:
|
| 232 |
+
raise gr.Error(f"Model load error: {model_name}, {e}")
|
| 233 |
+
|
| 234 |
+
|
| 235 |
+
# original UI
|
| 236 |
+
with gr.Blocks() as demo:
|
| 237 |
+
gr.HTML(TITLE)
|
| 238 |
+
with gr.Row():
|
| 239 |
+
with gr.Column():
|
| 240 |
+
input_image = gr.Image(type="pil", label="Input Image")
|
| 241 |
+
run_button = gr.Button("Caption")
|
| 242 |
+
|
| 243 |
+
with gr.Column():
|
| 244 |
+
output_caption = gr.Textbox(label="Caption")
|
| 245 |
+
|
| 246 |
+
run_button.click(fn=stream_chat, inputs=[input_image], outputs=[output_caption])
|
| 247 |
+
|
| 248 |
+
|
| 249 |
+
if __name__ == "__main__":
|
| 250 |
+
demo.launch()
|
requirements.txt
CHANGED
|
@@ -1,5 +1,8 @@
|
|
| 1 |
-
huggingface_hub
|
| 2 |
-
accelerate
|
| 3 |
-
torch
|
| 4 |
-
transformers==4.43.3
|
| 5 |
-
sentencepiece
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
huggingface_hub
|
| 2 |
+
accelerate
|
| 3 |
+
torch
|
| 4 |
+
transformers==4.43.3
|
| 5 |
+
sentencepiece
|
| 6 |
+
bitsandbytes
|
| 7 |
+
Pillow
|
| 8 |
+
protobuf
|