fancyfeast commited on
Commit
5adadb0
1 Parent(s): c44e8f2

Initial munge

Browse files
Files changed (4) hide show
  1. app.py +119 -56
  2. h2vtfhad/config.yaml +32 -0
  3. h2vtfhad/image_adapter.pt +3 -0
  4. 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
- For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference
6
- """
7
- client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
8
-
9
-
10
- def respond(
11
- message,
12
- history: list[tuple[str, str]],
13
- system_message,
14
- max_tokens,
15
- temperature,
16
- top_p,
17
- ):
18
- messages = [{"role": "system", "content": system_message}]
19
-
20
- for val in history:
21
- if val[0]:
22
- messages.append({"role": "user", "content": val[0]})
23
- if val[1]:
24
- messages.append({"role": "assistant", "content": val[1]})
25
-
26
- messages.append({"role": "user", "content": message})
27
-
28
- response = ""
29
-
30
- for message in client.chat_completion(
31
- messages,
32
- max_tokens=max_tokens,
33
- stream=True,
34
- temperature=temperature,
35
- top_p=top_p,
36
- ):
37
- token = message.choices[0].delta.content
38
-
39
- response += token
40
- yield response
41
-
42
- """
43
- For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
44
- """
45
- demo = gr.ChatInterface(
46
- respond,
47
- additional_inputs=[
48
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
49
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
50
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
51
- gr.Slider(
52
- minimum=0.1,
53
- maximum=1.0,
54
- value=0.95,
55
- step=0.05,
56
- label="Top-p (nucleus sampling)",
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