| 1 |
# Copyright 2024 The HuggingFace Inc. team. All rights reserved. |
| 2 |
# |
| 3 |
# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 |
# you may not use this file except in compliance with the License. |
| 5 |
# You may obtain a copy of the License at |
| 6 |
# |
| 7 |
# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 |
# |
| 9 |
# Unless required by applicable law or agreed to in writing, software |
| 10 |
# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 |
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 |
# See the License for the specific language governing permissions and |
| 13 |
# limitations under the License. |
| 14 |
|
| 15 |
import json |
| 16 |
import os |
| 17 |
import pathlib |
| 18 |
import queue |
| 19 |
from concurrent.futures import ThreadPoolExecutor |
| 20 |
from functools import partial |
| 21 |
from typing import Union |
| 22 |
|
| 23 |
import fire |
| 24 |
import torch |
| 25 |
import webdataset as wds |
| 26 |
from huggingface_hub.utils import insecure_hashlib |
| 27 |
from PIL import Image |
| 28 |
from tqdm import tqdm |
| 29 |
from transformers import AutoModelForCausalLM, AutoProcessor |
| 30 |
|
| 31 |
from accelerate import PartialState |
| 32 |
|
| 33 |
|
| 34 |
""" |
| 35 |
Additional requirements: flash_attn einops timm webdataset fire tqdm huggingface_hub |
| 36 |
pip install flash_attn einops timm webdataset fire tqdm huggingface_hub |
| 37 |
|
| 38 |
Example: |
| 39 |
|
| 40 |
accelerate launch --num_processes=2 florence2.py --data_path "https://huggingface.co/datasets/pixparse/cc3m-wds/resolve/main/cc3m-train-0000.tar" --output_path outputs --batch_size 12 --num_workers 1 --prompt "<CAPTION>" |
| 41 |
""" |
| 42 |
|
| 43 |
|
| 44 |
def main( |
| 45 |
data_path: str, |
| 46 |
output_path: str, |
| 47 |
batch_size: int, |
| 48 |
num_workers: int, |
| 49 |
prompt: str = "<MORE_DETAILED_CAPTION>", |
| 50 |
model_name: str = "microsoft/Florence-2-large", |
| 51 |
max_new_tokens: int = 1024, |
| 52 |
num_beams: int = 3, |
| 53 |
): |
| 54 |
output_dir = pathlib.Path(output_path) |
| 55 |
|
| 56 |
distributed_state = PartialState() |
| 57 |
|
| 58 |
if distributed_state.is_main_process: |
| 59 |
output_dir.mkdir(exist_ok=True) |
| 60 |
|
| 61 |
model = AutoModelForCausalLM.from_pretrained( |
| 62 |
model_name, |
| 63 |
device_map=distributed_state.device, |
| 64 |
torch_dtype=torch.float16, |
| 65 |
trust_remote_code=True, |
| 66 |
) |
| 67 |
|
| 68 |
processor = AutoProcessor.from_pretrained(model_name, trust_remote_code=True, clean_up_tokenization_spaces=True) |
| 69 |
|
| 70 |
class ExistsFilter: |
| 71 |
def __init__(self, output_dir: Union[pathlib.Path, str]): |
| 72 |
current_training_img_hashes = [f.split(".jpg")[0] for f in os.listdir(output_dir) if f.endswith(".jpg")] |
| 73 |
self.current_training_img_hashes = set(current_training_img_hashes) |
| 74 |
if distributed_state.is_main_process: |
| 75 |
print(f"Existing images found: {len(self.current_training_img_hashes)}.") |
| 76 |
|
| 77 |
def __call__(self, x): |
| 78 |
if len(self.current_training_img_hashes) > 0: |
| 79 |
if x["img_hash"] in self.current_training_img_hashes: |
| 80 |
return False |
| 81 |
else: |
| 82 |
return True |
| 83 |
else: |
| 84 |
return True |
| 85 |
|
| 86 |
def preprocess_fn(sample, processor): |
| 87 |
image: Image.Image = sample["jpg"].convert("RGB") |
| 88 |
img_hash = insecure_hashlib.sha1(image.tobytes()).hexdigest() |
| 89 |
inputs = processor( |
| 90 |
text=prompt, |
| 91 |
images=image, |
| 92 |
return_tensors="pt", |
| 93 |
) |
| 94 |
return { |
| 95 |
"input_ids": inputs["input_ids"], |
| 96 |
"pixel_values": inputs["pixel_values"], |
| 97 |
"image": image, |
| 98 |
"img_hash": img_hash, |
| 99 |
"original_caption": sample["txt"], |
| 100 |
} |
| 101 |
|
| 102 |
def collate_fn(examples): |
| 103 |
input_ids = torch.cat([example["input_ids"] for example in examples]) |
| 104 |
pixel_values = torch.cat([example["pixel_values"] for example in examples]) |
| 105 |
images = [example["image"] for example in examples] |
| 106 |
img_hashes = [example["img_hash"] for example in examples] |
| 107 |
captions = [example["original_caption"] for example in examples] |
| 108 |
return { |
| 109 |
"input_ids": input_ids, |
| 110 |
"pixel_values": pixel_values, |
| 111 |
"images": images, |
| 112 |
"img_hashes": img_hashes, |
| 113 |
"original_captions": captions, |
| 114 |
} |
| 115 |
|
| 116 |
exist_filter = ExistsFilter(output_dir) |
| 117 |
dataset = ( |
| 118 |
wds.WebDataset( |
| 119 |
data_path, |
| 120 |
handler=wds.warn_and_continue, |
| 121 |
nodesplitter=None, |
| 122 |
shardshuffle=False, |
| 123 |
empty_check=False, |
| 124 |
) |
| 125 |
.decode("pil", handler=wds.warn_and_continue) |
| 126 |
.map(partial(preprocess_fn, processor=processor), handler=wds.warn_and_continue) |
| 127 |
) |
| 128 |
if len(exist_filter.current_training_img_hashes) > 0: |
| 129 |
dataset = dataset.select(exist_filter) |
| 130 |
dataset = dataset.batched( |
| 131 |
batch_size, |
| 132 |
partial=False, |
| 133 |
collation_fn=collate_fn, |
| 134 |
) |
| 135 |
dataloader = wds.WebLoader( |
| 136 |
dataset, |
| 137 |
batch_size=None, |
| 138 |
num_workers=num_workers, |
| 139 |
pin_memory=True, |
| 140 |
persistent_workers=True, |
| 141 |
) |
| 142 |
|
| 143 |
def save_results(output_queue: queue.Queue, output_dir: pathlib.Path, processor): |
| 144 |
while True: |
| 145 |
try: |
| 146 |
item = output_queue.get(timeout=5) |
| 147 |
if item is None: |
| 148 |
break |
| 149 |
original_captions, predictions, images, img_hashes = item |
| 150 |
predicted_captions = processor.batch_decode( |
| 151 |
predictions, |
| 152 |
skip_special_tokens=False, |
| 153 |
) |
| 154 |
for caption, pred_caption, image, img_hash in zip( |
| 155 |
original_captions, predicted_captions, images, img_hashes |
| 156 |
): |
| 157 |
processed_caption = processor.post_process_generation( |
| 158 |
pred_caption, task=prompt, image_size=(image.width, image.height) |
| 159 |
)[prompt] |
| 160 |
img_path = output_dir.joinpath(f"{img_hash}.jpg") |
| 161 |
image.save(img_path) |
| 162 |
|
| 163 |
caption_dict = {"original": caption, "predicted": processed_caption} |
| 164 |
with output_dir.joinpath(f"{img_hash}_caption.json").open("w") as f: |
| 165 |
json.dump(caption_dict, f, indent=4) |
| 166 |
|
| 167 |
except queue.Empty: |
| 168 |
continue |
| 169 |
|
| 170 |
output_queue = queue.Queue() |
| 171 |
save_thread = ThreadPoolExecutor(max_workers=num_workers) |
| 172 |
save_future = save_thread.submit(save_results, output_queue, output_dir, processor) |
| 173 |
|
| 174 |
try: |
| 175 |
for _, batch_raw in tqdm( |
| 176 |
enumerate(dataloader), |
| 177 |
disable=not distributed_state.is_main_process, |
| 178 |
): |
| 179 |
with distributed_state.split_between_processes(batch_raw) as batch: |
| 180 |
outputs = model.generate( |
| 181 |
input_ids=batch["input_ids"].to(distributed_state.device), |
| 182 |
pixel_values=batch["pixel_values"].to(distributed_state.device, model.dtype), |
| 183 |
max_new_tokens=max_new_tokens, |
| 184 |
num_beams=num_beams, |
| 185 |
) |
| 186 |
output_queue.put( |
| 187 |
( |
| 188 |
batch["original_captions"], |
| 189 |
outputs, |
| 190 |
batch["images"], |
| 191 |
batch["img_hashes"], |
| 192 |
) |
| 193 |
) |
| 194 |
finally: |
| 195 |
output_queue.put(None) |
| 196 |
save_thread.shutdown(wait=True) |
| 197 |
|
| 198 |
save_future.result() |
| 199 |
|
| 200 |
|
| 201 |
if __name__ == "__main__": |
| 202 |
fire.Fire(main) |