svjack commited on
Commit
77fe89a
·
verified ·
1 Parent(s): 82de527

Create run_caption_ds.py

Browse files
Files changed (1) hide show
  1. run_caption_ds.py +143 -0
run_caption_ds.py ADDED
@@ -0,0 +1,143 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 datasets import load_dataset # 引入 Hugging Face Dataset
7
+ from tqdm import tqdm # 引入 tqdm 用于显示进度条
8
+
9
+ # Constants
10
+ CLIP_PATH = "google/siglip-so400m-patch14-384"
11
+ VLM_PROMPT = "A descriptive caption for this image:\n"
12
+ MODEL_PATH = "meta-llama/Meta-Llama-3.1-8B"
13
+ CHECKPOINT_PATH = Path("wpkklhc6")
14
+
15
+ # Image Adapter
16
+ class ImageAdapter(nn.Module):
17
+ def __init__(self, input_features: int, output_features: int):
18
+ super().__init__()
19
+ self.linear1 = nn.Linear(input_features, output_features)
20
+ self.activation = nn.GELU()
21
+ self.linear2 = nn.Linear(output_features, output_features)
22
+
23
+ def forward(self, vision_outputs: torch.Tensor):
24
+ x = self.linear1(vision_outputs)
25
+ x = self.activation(x)
26
+ x = self.linear2(x)
27
+ return x
28
+
29
+ # Load models
30
+ def load_models():
31
+ print("Loading CLIP")
32
+ clip_processor = AutoProcessor.from_pretrained(CLIP_PATH)
33
+ clip_model = AutoModel.from_pretrained(CLIP_PATH)
34
+ clip_model = clip_model.vision_model
35
+ clip_model.eval()
36
+ clip_model.requires_grad_(False)
37
+ clip_model.to("cuda")
38
+
39
+ print("Loading tokenizer")
40
+ tokenizer = AutoTokenizer.from_pretrained(MODEL_PATH, use_fast=False)
41
+ assert isinstance(tokenizer, PreTrainedTokenizer) or isinstance(tokenizer, PreTrainedTokenizerFast), f"Tokenizer is of type {type(tokenizer)}"
42
+
43
+ print("Loading LLM")
44
+ text_model = AutoModelForCausalLM.from_pretrained(MODEL_PATH, device_map="auto", torch_dtype=torch.bfloat16)
45
+ text_model.eval()
46
+
47
+ print("Loading image adapter")
48
+ image_adapter = ImageAdapter(clip_model.config.hidden_size, text_model.config.hidden_size)
49
+ image_adapter.load_state_dict(torch.load(CHECKPOINT_PATH / "image_adapter.pt", map_location="cpu"))
50
+ image_adapter.eval()
51
+ image_adapter.to("cuda")
52
+
53
+ return clip_processor, clip_model, tokenizer, text_model, image_adapter
54
+
55
+ # Generate caption
56
+ @torch.no_grad()
57
+ def generate_caption(input_image, clip_processor, clip_model, tokenizer, text_model, image_adapter):
58
+ torch.cuda.empty_cache()
59
+
60
+ # Preprocess image
61
+ image = clip_processor(images=input_image, return_tensors='pt').pixel_values
62
+ image = image.to('cuda')
63
+
64
+ # Tokenize the prompt
65
+ prompt = tokenizer.encode(VLM_PROMPT, return_tensors='pt', padding=False, truncation=False, add_special_tokens=False)
66
+
67
+ # Embed image
68
+ with torch.amp.autocast_mode.autocast('cuda', enabled=True):
69
+ vision_outputs = clip_model(pixel_values=image, output_hidden_states=True)
70
+ image_features = vision_outputs.hidden_states[-2]
71
+ embedded_images = image_adapter(image_features)
72
+ embedded_images = embedded_images.to('cuda')
73
+
74
+ # Embed prompt
75
+ prompt_embeds = text_model.model.embed_tokens(prompt.to('cuda'))
76
+ 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)}"
77
+ embedded_bos = text_model.model.embed_tokens(torch.tensor([[tokenizer.bos_token_id]], device=text_model.device, dtype=torch.int64))
78
+
79
+ # Construct prompts
80
+ inputs_embeds = torch.cat([
81
+ embedded_bos.expand(embedded_images.shape[0], -1, -1),
82
+ embedded_images.to(dtype=embedded_bos.dtype),
83
+ prompt_embeds.expand(embedded_images.shape[0], -1, -1),
84
+ ], dim=1)
85
+
86
+ input_ids = torch.cat([
87
+ torch.tensor([[tokenizer.bos_token_id]], dtype=torch.long),
88
+ torch.zeros((1, embedded_images.shape[1]), dtype=torch.long),
89
+ prompt,
90
+ ], dim=1).to('cuda')
91
+ attention_mask = torch.ones_like(input_ids)
92
+
93
+ 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)
94
+
95
+ # Trim off the prompt
96
+ generate_ids = generate_ids[:, input_ids.shape[1]:]
97
+ if generate_ids[0][-1] == tokenizer.eos_token_id:
98
+ generate_ids = generate_ids[:, :-1]
99
+
100
+ caption = tokenizer.batch_decode(generate_ids, skip_special_tokens=False, clean_up_tokenization_spaces=False)[0]
101
+
102
+ return caption.strip()
103
+
104
+ # Main function
105
+ def main():
106
+ parser = argparse.ArgumentParser(description="Generate captions for images in a Hugging Face Dataset.")
107
+ parser.add_argument("dataset_name", type=str, help="Name of the Hugging Face Dataset")
108
+ parser.add_argument("--image_column", type=str, default="image", help="Name of the column containing images (default: 'image')")
109
+ parser.add_argument("--caption_column", type=str, default="caption", help="Name of the column to save captions (default: 'caption')")
110
+ parser.add_argument("--output_path", type=str, required=True, help="Path to save the dataset with captions")
111
+ args = parser.parse_args()
112
+
113
+ # Load models
114
+ clip_processor, clip_model, tokenizer, text_model, image_adapter = load_models()
115
+
116
+ # Load dataset
117
+ print(f"Loading dataset: {args.dataset_name}")
118
+ dataset = load_dataset(args.dataset_name)
119
+
120
+ # Generate captions for each image in the dataset
121
+ def add_caption(example):
122
+ try:
123
+ # Generate caption
124
+ caption = generate_caption(example[args.image_column], clip_processor, clip_model, tokenizer, text_model, image_adapter)
125
+ # Add caption to the example
126
+ example[args.caption_column] = caption
127
+ except Exception as e:
128
+ print(f"Error processing image: {e}")
129
+ example[args.caption_column] = "" # 如果出错,保存空字符串
130
+ return example
131
+
132
+ # Apply the function to the dataset
133
+ print("Generating captions...")
134
+ dataset = dataset.map(add_caption, desc="Generating captions")
135
+
136
+ # Save the dataset with captions
137
+ print(f"Saving dataset to {args.output_path}")
138
+ dataset.save_to_disk(args.output_path)
139
+
140
+ print("Done!")
141
+
142
+ if __name__ == "__main__":
143
+ main()