(args: argparse.Namespace, dataset)
| 148 | |
| 149 | @beartype |
| 150 | def run(args: argparse.Namespace, dataset) -> None: |
| 151 | attack_fn = get_attack_fn(args.attack) |
| 152 | |
| 153 | idx = 0 |
| 154 | for example in dataset: |
| 155 | if "target_caption_clip" not in example: |
| 156 | continue |
| 157 | |
| 158 | if args.index is not None and ( |
| 159 | idx not in list(range(args.index * args.batch_size, (args.index + 1) * args.batch_size)) |
| 160 | ): |
| 161 | idx += 1 |
| 162 | continue |
| 163 | idx += 1 |
| 164 | print(f"Running attack on example {example['id']}") |
| 165 | |
| 166 | victim_image = example["victim_image"] |
| 167 | target_caption_clip = example["target_caption_clip"] |
| 168 | victim_caption_clip = example["victim_caption_clip"] |
| 169 | |
| 170 | all_images = [] |
| 171 | all_captions = [] |
| 172 | for size in [180]: |
| 173 | attack_out_dict = attack_fn(victim_image, target_caption_clip, victim_caption_clip, iters=1000, size=size) |
| 174 | adv_images = attack_out_dict["adv_images"] |
| 175 | |
| 176 | # Evaluate with GPT-4V |
| 177 | model = get_model(args.model) |
| 178 | prompt_fn = model.get_captioning_prompt_fn() |
| 179 | for step, adv_image in adv_images.items(): |
| 180 | all_images.append(adv_image) |
| 181 | |
| 182 | while True: |
| 183 | try: |
| 184 | gen_text = model.generate_answer( |
| 185 | [adv_image], |
| 186 | [prompt_fn()], |
| 187 | )[0] |
| 188 | break |
| 189 | except Exception as e: |
| 190 | print(e) |
| 191 | # Sleep a random time between 30-90 seconds |
| 192 | time.sleep(30 + 60 * random.random()) |
| 193 | print(f"Generated caption ({example['id']}, step {step}, size {size}): {gen_text}") |
| 194 | all_captions.append(gen_text) |
| 195 | |
| 196 | # Choose the best image and caption |
| 197 | best_idx = get_best_idx(all_captions, target_caption_clip, victim_caption_clip) |
| 198 | adv_image = all_images[best_idx] |
| 199 | adv_caption = all_captions[best_idx] |
| 200 | |
| 201 | # Save the image |
| 202 | adv_image.save( |
| 203 | os.path.join( |
| 204 | "exp_data", |
| 205 | "agent_adv", |
| 206 | example["id"], |
| 207 | f"{args.attack}_{f'{args.model}_' if args.model != 'gpt-4-vision-preview' else ''}attack_image.png", |
no test coverage detected