Spaces:
Running
Running
File size: 14,703 Bytes
c374021 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 | """
data_prep.py
============
Unified data loading for all VLM architectures:
- BLIP β BlipProcessor
- ViT-GPT2 β ViTImageProcessor + GPT-2 tokenizer
- GIT β AutoProcessor
- Custom VLM β ViTImageProcessor + character-level tokenizer
Data Preparation Strategies (controlled via cfg.caption_strategy):
'raw' β any random caption (no filtering)
'filtered' β captions between cfg.caption_min_words and cfg.caption_max_words
'short' β captions β€ cfg.caption_min_words words
'long' β captions β₯ cfg.caption_max_words words
'mixed' β randomly choose among short / medium / long each call
"""
import random
import aiohttp
import torch
from torch.utils.data import DataLoader, Dataset
from datasets import load_dataset
from PIL import Image
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# Seeding
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def seed_all(seed: int):
import numpy as np
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
if torch.cuda.is_available():
torch.cuda.manual_seed_all(seed)
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# BLIP DataLoader (original, kept for backward-compat)
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def get_dataloaders(cfg, processor):
"""
Backward-compatible BLIP dataloader.
Uses BlipProcessor to build pixel_values + input_ids + labels.
"""
seed_all(cfg.seed)
print(f"Loading dataset: {cfg.dataset_id}...")
ds = load_dataset(
cfg.dataset_id,
storage_options={"client_kwargs": {"timeout": aiohttp.ClientTimeout(total=3600)}},
)
train_split = "train"
val_split = "validation" if "validation" in ds else ("val" if "val" in ds else "train")
train_ds = ds[train_split].shuffle(seed=cfg.seed).select(
range(min(cfg.train_samples, len(ds[train_split])))
)
val_ds = ds[val_split].shuffle(seed=cfg.seed + 1).select(
range(min(cfg.val_samples, len(ds[val_split])))
)
print(f"β
Training samples: {len(train_ds)} | Validation samples: {len(val_ds)}")
def collate_fn(examples):
images = [ex["image"].convert("RGB") for ex in examples]
captions = []
for ex in examples:
caps = [c for c in ex["captions"] if len(c.split()) > 3] or ex["captions"]
captions.append(random.choice(caps))
encoding = processor(
images=images,
text=captions,
padding="max_length",
truncation=True,
max_length=cfg.max_target_len,
return_tensors="pt",
)
encoding["labels"] = encoding["input_ids"].clone()
return encoding
loader_kwargs = dict(
batch_size=cfg.batch_size,
num_workers=cfg.num_workers,
collate_fn=collate_fn,
pin_memory=torch.cuda.is_available(),
)
train_loader = DataLoader(train_ds, shuffle=True, **loader_kwargs)
val_loader = DataLoader(val_ds, shuffle=False, **loader_kwargs)
return train_loader, val_loader
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# Unified HuggingFace Model DataLoader (BLIP / ViT-GPT2 / GIT)
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# Caption Quality Filtering
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def filter_low_quality_captions(captions: list, min_words: int = 5,
max_words: int = 25) -> list:
"""
Filter captions to only those within the specified word count range.
Args:
captions : list of caption strings
min_words : minimum word count (inclusive)
max_words : maximum word count (inclusive)
Returns:
filtered list; may be empty if no captions pass the filter
"""
return [
c for c in captions
if min_words <= len(c.split()) <= max_words
]
def pick_caption_by_strategy(captions: list, strategy: str = "filtered",
min_words: int = 5, max_words: int = 25) -> str:
"""
Pick one caption from the list using the specified strategy.
Strategies:
'raw' β random choice with no filter
'filtered' β random from captions in [min_words, max_words]; fallback raw
'short' β random from captions β€ min_words words; fallback raw
'long' β random from captions β₯ max_words words; fallback raw
'mixed' β each call randomly picks one of the above strategies
Returns:
one caption string
"""
if strategy == "mixed":
strategy = random.choice(["filtered", "short", "long"])
if strategy == "raw":
return random.choice(captions)
elif strategy == "filtered":
pool = filter_low_quality_captions(captions, min_words, max_words)
return random.choice(pool) if pool else random.choice(captions)
elif strategy == "short":
pool = [c for c in captions if len(c.split()) <= min_words]
return random.choice(pool) if pool else random.choice(captions)
elif strategy == "long":
pool = [c for c in captions if len(c.split()) >= max_words]
return random.choice(pool) if pool else random.choice(captions)
else:
# Treat unknown strategy as filtered
pool = filter_low_quality_captions(captions, min_words, max_words)
return random.choice(pool) if pool else random.choice(captions)
def _pick_caption(example, cfg=None):
"""
Pick one caption using cfg.caption_strategy (default: 'filtered').
Falls back to any caption > 3 words if cfg is None.
"""
if cfg is None:
caps = [c for c in example["captions"] if len(c.split()) > 3]
return random.choice(caps) if caps else random.choice(example["captions"])
return pick_caption_by_strategy(
example["captions"],
strategy=getattr(cfg, "caption_strategy", "filtered"),
min_words=getattr(cfg, "caption_min_words", 5),
max_words=getattr(cfg, "caption_max_words", 25),
)
def get_dataloaders_for_model(cfg, model_type: str, processor, tokenizer=None):
"""
Unified dataloader factory for BLIP, ViT-GPT2, and GIT.
Args:
cfg : CFG dataclass
model_type : 'blip' | 'vit_gpt2' | 'git'
processor : image processor / AutoProcessor
tokenizer : text tokenizer (required only for 'vit_gpt2')
Returns:
train_loader, val_loader
"""
seed_all(cfg.seed)
print(f"Loading dataset ({model_type}): {cfg.dataset_id}...")
ds = load_dataset(
cfg.dataset_id,
storage_options={"client_kwargs": {"timeout": aiohttp.ClientTimeout(total=3600)}},
)
train_split = "train"
val_split = "validation" if "validation" in ds else ("val" if "val" in ds else "train")
train_ds = ds[train_split].shuffle(seed=cfg.seed).select(
range(min(cfg.train_samples, len(ds[train_split])))
)
val_ds = ds[val_split].shuffle(seed=cfg.seed + 1).select(
range(min(cfg.val_samples, len(ds[val_split])))
)
print(f"β
Training: {len(train_ds)} | Validation: {len(val_ds)}")
if model_type == "blip":
def collate_fn(examples):
images = [ex["image"].convert("RGB") for ex in examples]
captions = [_pick_caption(ex) for ex in examples]
encoding = processor(
images=images, text=captions,
padding="max_length", truncation=True,
max_length=cfg.max_target_len, return_tensors="pt",
)
encoding["labels"] = encoding["input_ids"].clone()
return encoding
elif model_type == "vit_gpt2":
assert tokenizer is not None, "tokenizer required for vit_gpt2"
def collate_fn(examples):
images = [ex["image"].convert("RGB") for ex in examples]
captions = [_pick_caption(ex) for ex in examples]
pixel_values = processor(images=images, return_tensors="pt")["pixel_values"]
text_enc = tokenizer(
captions, padding="max_length", truncation=True,
max_length=cfg.max_target_len, return_tensors="pt",
)
labels = text_enc["input_ids"].clone()
labels[labels == tokenizer.pad_token_id] = -100
return {
"pixel_values": pixel_values,
"labels": labels,
"decoder_attention_mask": text_enc["attention_mask"],
}
elif model_type == "git":
def collate_fn(examples):
images = [ex["image"].convert("RGB") for ex in examples]
captions = [_pick_caption(ex) for ex in examples]
encoding = processor(
images=images, text=captions,
padding="max_length", truncation=True,
max_length=cfg.max_target_len, return_tensors="pt",
)
labels = encoding["input_ids"].clone()
labels[labels == processor.tokenizer.pad_token_id] = -100
encoding["labels"] = labels
return encoding
else:
raise ValueError(f"Unknown model_type: {model_type}")
loader_kwargs = dict(
batch_size=cfg.batch_size,
num_workers=cfg.num_workers,
collate_fn=collate_fn,
pin_memory=torch.cuda.is_available(),
)
train_loader = DataLoader(train_ds, shuffle=True, **loader_kwargs)
val_loader = DataLoader(val_ds, shuffle=False, **loader_kwargs)
return train_loader, val_loader
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# Custom VLM DataLoader (Character-Level Tokenization)
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
class COCOCharDataset(Dataset):
"""
Maps COCO images β (pixel_values, text_input_ids, text_targets)
using a character-level vocabulary built from the Shakespeare corpus.
"""
def __init__(self, hf_dataset, image_processor, char_to_idx, max_target_len):
self.ds = hf_dataset
self.image_processor = image_processor
self.char_to_idx = char_to_idx
self.max_target_len = max_target_len
self.unk_idx = char_to_idx.get(" ", 0)
def _encode_text(self, text):
"""Encode a string to a fixed-length char index tensor."""
ids = [self.char_to_idx.get(c, self.unk_idx) for c in text[:self.max_target_len]]
# Pad with 0s if shorter
ids += [0] * (self.max_target_len - len(ids))
return ids
def __len__(self):
return len(self.ds)
def __getitem__(self, idx):
ex = self.ds[idx]
image = ex["image"].convert("RGB")
pixel_values = self.image_processor(images=image, return_tensors="pt")["pixel_values"].squeeze(0)
# Pick one caption
caps = [c for c in ex["captions"] if len(c.split()) > 3] or ex["captions"]
caption = random.choice(caps).lower()
src_ids = self._encode_text(caption[:-1]) # input: all but last char
tgt_ids = self._encode_text(caption[1:]) # target: shifted right by 1
return {
"pixel_values": pixel_values,
"text_input_ids": torch.tensor(src_ids, dtype=torch.long),
"text_targets": torch.tensor(tgt_ids, dtype=torch.long),
}
def get_custom_vlm_dataloader(cfg, char_to_idx):
"""
Returns (train_loader, val_loader) for the Custom VLM using COCO images
and character-level tokenization.
Requires the ViT image processor separately.
"""
from transformers import ViTImageProcessor
seed_all(cfg.seed)
image_processor = ViTImageProcessor.from_pretrained(cfg.vit_encoder_id, use_fast=True)
print(f"Loading dataset (Custom VLM): {cfg.dataset_id}...")
ds = load_dataset(
cfg.dataset_id,
storage_options={"client_kwargs": {"timeout": aiohttp.ClientTimeout(total=3600)}},
)
train_split = "train"
val_split = "validation" if "validation" in ds else ("val" if "val" in ds else "train")
train_hf = ds[train_split].shuffle(seed=cfg.seed).select(
range(min(cfg.train_samples, len(ds[train_split])))
)
val_hf = ds[val_split].shuffle(seed=cfg.seed + 1).select(
range(min(cfg.val_samples, len(ds[val_split])))
)
train_ds = COCOCharDataset(train_hf, image_processor, char_to_idx, cfg.max_target_len)
val_ds = COCOCharDataset(val_hf, image_processor, char_to_idx, cfg.max_target_len)
print(f"β
Custom VLM β Training: {len(train_ds)} | Validation: {len(val_ds)}")
loader_kwargs = dict(
batch_size=cfg.batch_size,
num_workers=cfg.num_workers,
pin_memory=torch.cuda.is_available(),
)
train_loader = DataLoader(train_ds, shuffle=True, **loader_kwargs)
val_loader = DataLoader(val_ds, shuffle=False, **loader_kwargs)
return train_loader, val_loader
|