Spaces:
Running
on
Zero
Running
on
Zero
fancyfeast
commited on
Commit
•
5adadb0
1
Parent(s):
c44e8f2
Initial munge
Browse files- app.py +119 -56
- h2vtfhad/config.yaml +32 -0
- h2vtfhad/image_adapter.pt +3 -0
- requirements.txt +5 -1
app.py
CHANGED
@@ -1,62 +1,125 @@
|
|
|
|
1 |
import gradio as gr
|
2 |
from huggingface_hub import InferenceClient
|
|
|
|
|
|
|
|
|
|
|
|
|
3 |
|
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 |
-
|
42 |
-
""
|
43 |
-
|
44 |
-
|
45 |
-
|
46 |
-
|
47 |
-
|
48 |
-
|
49 |
-
|
50 |
-
|
51 |
-
|
52 |
-
|
53 |
-
|
54 |
-
|
55 |
-
|
56 |
-
|
57 |
-
|
58 |
-
|
59 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
60 |
|
61 |
|
62 |
if __name__ == "__main__":
|
|
|
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 |
|
11 |
+
|
12 |
+
CLIP_PATH = "google/siglip-so400m-patch14-384"
|
13 |
+
VLM_PROMPT = "A descriptive caption for this image:\n"
|
14 |
+
MODEL_PATH = "meta-llama/Meta-Llama-3.1-8B"
|
15 |
+
CHECKPOINT_PATH = Path("h2vtfhad")
|
16 |
+
TITLE = "<h1><center>Foo</center></h1>"
|
17 |
+
|
18 |
+
|
19 |
+
class ImageAdapter(nn.Module):
|
20 |
+
def __init__(self, input_features: int, output_features: int):
|
21 |
+
super().__init__()
|
22 |
+
self.linear1 = nn.Linear(input_features, output_features)
|
23 |
+
self.activation = nn.GELU()
|
24 |
+
self.linear2 = nn.Linear(output_features, output_features)
|
25 |
+
|
26 |
+
def forward(self, vision_outputs: torch.Tensor):
|
27 |
+
x = self.linear1(vision_outputs)
|
28 |
+
x = self.activation(x)
|
29 |
+
x = self.linear2(x)
|
30 |
+
return x
|
31 |
+
|
32 |
+
|
33 |
+
# Load CLIP
|
34 |
+
print("Loading CLIP")
|
35 |
+
clip_processor = AutoProcessor.from_pretrained(CLIP_PATH)
|
36 |
+
clip_model = AutoModel.from_pretrained(CLIP_PATH)
|
37 |
+
clip_model = clip_model.vision_model
|
38 |
+
clip_model.eval()
|
39 |
+
clip_model.requires_grad_(False)
|
40 |
+
clip_model.to("cuda")
|
41 |
+
|
42 |
+
|
43 |
+
# Tokenizer
|
44 |
+
print("Loading tokenizer")
|
45 |
+
tokenizer = AutoTokenizer.from_pretrained(MODEL_PATH, use_fast=False)
|
46 |
+
assert isinstance(tokenizer, PreTrainedTokenizer) or isinstance(tokenizer, PreTrainedTokenizerFast), f"Tokenizer is of type {type(tokenizer)}"
|
47 |
+
|
48 |
+
# LLM
|
49 |
+
print("Loading LLM")
|
50 |
+
text_model = AutoModelForCausalLM.from_pretrained(MODEL_PATH, device_map="auto", torch_dtype=torch.bfloat16)
|
51 |
+
text_model.eval()
|
52 |
+
|
53 |
+
# Image Adapter
|
54 |
+
print("Loading image adapter")
|
55 |
+
image_adapter = ImageAdapter(clip_model.config.hidden_size, text_model.config.hidden_size)
|
56 |
+
image_adapter.load_state_dict(torch.load(CHECKPOINT_PATH / "image_adapter.pt", map_location="cpu"))
|
57 |
+
image_adapter.eval()
|
58 |
+
image_adapter.to("cuda")
|
59 |
+
|
60 |
+
|
61 |
+
@spaces.GPU()
|
62 |
+
@torch.no_grad()
|
63 |
+
def stream_chat(input_image: Image.Image):
|
64 |
+
torch.cuda.empty_cache()
|
65 |
+
|
66 |
+
# Preprocess image
|
67 |
+
image = clip_processor(images=input_image, return_tensors='pt').pixel_values
|
68 |
+
image = image.to('cuda')
|
69 |
+
|
70 |
+
# Tokenize the prompt
|
71 |
+
prompt = tokenizer.encode(VLM_PROMPT, return_tensors='pt', padding=False, truncation=False, add_special_tokens=False)
|
72 |
+
|
73 |
+
# Embed image
|
74 |
+
with torch.amp.autocast_mode.autocast('cuda', enabled=True):
|
75 |
+
vision_outputs = clip_model(pixel_values=image, output_hidden_states=True)
|
76 |
+
image_features = vision_outputs.hidden_states[-2]
|
77 |
+
embedded_images = image_adapter(image_features)
|
78 |
+
embedded_images = embedded_images.to('cuda')
|
79 |
+
|
80 |
+
# Embed prompt
|
81 |
+
prompt_embeds = text_model.model.embed_tokens(prompt.to('cuda'))
|
82 |
+
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)}"
|
83 |
+
embedded_bos = text_model.model.embed_tokens(torch.tensor([[tokenizer.bos_token_id]], device=text_model.device, dtype=torch.int64))
|
84 |
+
|
85 |
+
# Construct prompts
|
86 |
+
inputs_embeds = torch.cat([
|
87 |
+
embedded_bos.expand(embedded_images.shape[0], -1, -1),
|
88 |
+
embedded_images.to(dtype=embedded_bos.dtype),
|
89 |
+
prompt_embeds.expand(embedded_images.shape[0], -1, -1),
|
90 |
+
], dim=1)
|
91 |
+
|
92 |
+
input_ids = torch.cat([
|
93 |
+
torch.tensor([[tokenizer.bos_token_id]], dtype=torch.long),
|
94 |
+
torch.zeros((1, embedded_images.shape[1]), dtype=torch.long),
|
95 |
+
prompt,
|
96 |
+
], dim=1).to('cuda')
|
97 |
+
attention_mask = torch.ones_like(input_ids)
|
98 |
+
|
99 |
+
#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)
|
100 |
+
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)
|
101 |
+
|
102 |
+
# Trim off the prompt
|
103 |
+
generate_ids = generate_ids[:, input_ids.shape[1]:]
|
104 |
+
if generate_ids[0][-1] == tokenizer.eos_token_id:
|
105 |
+
generate_ids = generate_ids[:, :-1]
|
106 |
+
|
107 |
+
caption = tokenizer.batch_decode(generate_ids, skip_special_tokens=False, clean_up_tokenization_spaces=False)[0]
|
108 |
+
|
109 |
+
return [caption]
|
110 |
+
|
111 |
+
|
112 |
+
with gr.Blocks() as demo:
|
113 |
+
gr.HTML(TITLE)
|
114 |
+
with gr.Row():
|
115 |
+
with gr.Column():
|
116 |
+
input_image = gr.Image(type="pil", label="Input Image")
|
117 |
+
run_button = gr.Button("Caption")
|
118 |
+
|
119 |
+
with gr.Column():
|
120 |
+
output_caption = gr.Textbox(label="Caption", default="")
|
121 |
+
|
122 |
+
run_button.click(fn=stream_chat, inputs=[input_image], outputs=[output_caption])
|
123 |
|
124 |
|
125 |
if __name__ == "__main__":
|
h2vtfhad/config.yaml
ADDED
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
wandb_project: joy-caption-1
|
2 |
+
device_batch_size: 2
|
3 |
+
batch_size: 256
|
4 |
+
learning_rate: 0.001
|
5 |
+
warmup_samples: 18000
|
6 |
+
max_samples: 500000
|
7 |
+
save_every: 50000
|
8 |
+
test_every: 50000
|
9 |
+
use_amp: true
|
10 |
+
grad_scaler: true
|
11 |
+
lr_scheduler_type: cosine
|
12 |
+
min_lr_ratio: 0.0
|
13 |
+
allow_tf32: true
|
14 |
+
seed: 42
|
15 |
+
num_workers: 8
|
16 |
+
optimizer_type: adamw
|
17 |
+
adam_beta1: 0.9
|
18 |
+
adam_beta2: 0.999
|
19 |
+
adam_eps: 1.0e-08
|
20 |
+
adam_weight_decay: 0.0
|
21 |
+
clip_grad_norm: 1.0
|
22 |
+
dataset: fancyfeast/joy-captioning-20240720a
|
23 |
+
clip_model: google/siglip-so400m-patch14-384
|
24 |
+
text_model: meta-llama/Meta-Llama-3.1-8B
|
25 |
+
resume: null
|
26 |
+
gradient_checkpointing: false
|
27 |
+
test_size: 2048
|
28 |
+
grad_scaler_init: 65536.0
|
29 |
+
max_caption_length: 257
|
30 |
+
num_image_tokens: 32
|
31 |
+
adapter_type: mlp
|
32 |
+
text_model_dtype: float16
|
h2vtfhad/image_adapter.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:b06f70ede9f072d92855f91458a3ec09fdc27a3fddf859a4b1381cccff730fea
|
3 |
+
size 86018240
|
requirements.txt
CHANGED
@@ -1 +1,5 @@
|
|
1 |
-
huggingface_hub==0.22.2
|
|
|
|
|
|
|
|
|
|
1 |
+
huggingface_hub==0.22.2
|
2 |
+
accelerate
|
3 |
+
torch
|
4 |
+
transformers
|
5 |
+
sentencepiece
|