svjack commited on
Commit
13f60c5
·
verified ·
1 Parent(s): 9c5f4be

Create run_caption.py

Browse files
Files changed (1) hide show
  1. run_caption.py +133 -0
run_caption.py ADDED
@@ -0,0 +1,133 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ from pathlib import Path
3
+ import torch
4
+ from torch import nn
5
+ from transformers import AutoModel, AutoProcessor, AutoTokenizer, PreTrainedTokenizer, PreTrainedTokenizerFast, AutoModelForCausalLM
6
+ from PIL import Image
7
+ import shutil
8
+
9
+ CLIP_PATH = "google/siglip-so400m-patch14-384"
10
+ VLM_PROMPT = "A descriptive caption for this image:\n"
11
+ MODEL_PATH = "meta-llama/Meta-Llama-3.1-8B"
12
+ CHECKPOINT_PATH = Path("wpkklhc6")
13
+
14
+ class ImageAdapter(nn.Module):
15
+ def __init__(self, input_features: int, output_features: int):
16
+ super().__init__()
17
+ self.linear1 = nn.Linear(input_features, output_features)
18
+ self.activation = nn.GELU()
19
+ self.linear2 = nn.Linear(output_features, output_features)
20
+
21
+ def forward(self, vision_outputs: torch.Tensor):
22
+ x = self.linear1(vision_outputs)
23
+ x = self.activation(x)
24
+ x = self.linear2(x)
25
+ return x
26
+
27
+ def load_models():
28
+ print("Loading CLIP")
29
+ clip_processor = AutoProcessor.from_pretrained(CLIP_PATH)
30
+ clip_model = AutoModel.from_pretrained(CLIP_PATH)
31
+ clip_model = clip_model.vision_model
32
+ clip_model.eval()
33
+ clip_model.requires_grad_(False)
34
+ clip_model.to("cuda")
35
+
36
+ print("Loading tokenizer")
37
+ tokenizer = AutoTokenizer.from_pretrained(MODEL_PATH, use_fast=False)
38
+ assert isinstance(tokenizer, PreTrainedTokenizer) or isinstance(tokenizer, PreTrainedTokenizerFast), f"Tokenizer is of type {type(tokenizer)}"
39
+
40
+ print("Loading LLM")
41
+ text_model = AutoModelForCausalLM.from_pretrained(MODEL_PATH, device_map="auto", torch_dtype=torch.bfloat16)
42
+ text_model.eval()
43
+
44
+ print("Loading image adapter")
45
+ image_adapter = ImageAdapter(clip_model.config.hidden_size, text_model.config.hidden_size)
46
+ image_adapter.load_state_dict(torch.load(CHECKPOINT_PATH / "image_adapter.pt", map_location="cpu"))
47
+ image_adapter.eval()
48
+ image_adapter.to("cuda")
49
+
50
+ return clip_processor, clip_model, tokenizer, text_model, image_adapter
51
+
52
+ @torch.no_grad()
53
+ def generate_caption(input_image: Image.Image, clip_processor, clip_model, tokenizer, text_model, image_adapter):
54
+ torch.cuda.empty_cache()
55
+
56
+ # Preprocess image
57
+ image = clip_processor(images=input_image, return_tensors='pt').pixel_values
58
+ image = image.to('cuda')
59
+
60
+ # Tokenize the prompt
61
+ prompt = tokenizer.encode(VLM_PROMPT, return_tensors='pt', padding=False, truncation=False, add_special_tokens=False)
62
+
63
+ # Embed image
64
+ with torch.amp.autocast_mode.autocast('cuda', enabled=True):
65
+ vision_outputs = clip_model(pixel_values=image, output_hidden_states=True)
66
+ image_features = vision_outputs.hidden_states[-2]
67
+ embedded_images = image_adapter(image_features)
68
+ embedded_images = embedded_images.to('cuda')
69
+
70
+ # Embed prompt
71
+ prompt_embeds = text_model.model.embed_tokens(prompt.to('cuda'))
72
+ 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)}"
73
+ embedded_bos = text_model.model.embed_tokens(torch.tensor([[tokenizer.bos_token_id]], device=text_model.device, dtype=torch.int64))
74
+
75
+ # Construct prompts
76
+ inputs_embeds = torch.cat([
77
+ embedded_bos.expand(embedded_images.shape[0], -1, -1),
78
+ embedded_images.to(dtype=embedded_bos.dtype),
79
+ prompt_embeds.expand(embedded_images.shape[0], -1, -1),
80
+ ], dim=1)
81
+
82
+ input_ids = torch.cat([
83
+ torch.tensor([[tokenizer.bos_token_id]], dtype=torch.long),
84
+ torch.zeros((1, embedded_images.shape[1]), dtype=torch.long),
85
+ prompt,
86
+ ], dim=1).to('cuda')
87
+ attention_mask = torch.ones_like(input_ids)
88
+
89
+ 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)
90
+
91
+ # Trim off the prompt
92
+ generate_ids = generate_ids[:, input_ids.shape[1]:]
93
+ if generate_ids[0][-1] == tokenizer.eos_token_id:
94
+ generate_ids = generate_ids[:, :-1]
95
+
96
+ caption = tokenizer.batch_decode(generate_ids, skip_special_tokens=False, clean_up_tokenization_spaces=False)[0]
97
+
98
+ return caption.strip()
99
+
100
+ def main():
101
+ parser = argparse.ArgumentParser(description="Generate a caption for an image and save it to a text file.")
102
+ parser.add_argument("input_image", type=str, help="Path to the input image")
103
+ parser.add_argument("output_path", type=str, help="Path to save the output image and caption text file")
104
+ args = parser.parse_args()
105
+
106
+ # Load models
107
+ clip_processor, clip_model, tokenizer, text_model, image_adapter = load_models()
108
+
109
+ # Open the input image
110
+ input_image = Image.open(args.input_image)
111
+
112
+ # Generate caption
113
+ caption = generate_caption(input_image, clip_processor, clip_model, tokenizer, text_model, image_adapter)
114
+
115
+ # Process output path
116
+ output_path = Path(args.output_path)
117
+ output_path.mkdir(parents=True, exist_ok=True)
118
+
119
+ # Copy image to output path
120
+ image_name = Path(args.input_image).name
121
+ image_name = image_name.replace(" ", "_") # Replace spaces with underscores
122
+ output_image_path = output_path / image_name
123
+ shutil.copy(args.input_image, output_image_path)
124
+
125
+ # Save caption to txt file
126
+ txt_file_path = output_path / f"{output_image_path.stem}.txt"
127
+ with open(txt_file_path, "w") as f:
128
+ f.write(caption)
129
+
130
+ print(f"Caption saved to {txt_file_path}")
131
+
132
+ if __name__ == "__main__":
133
+ main()