File size: 13,243 Bytes
19ea5c5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
import os
import random
from typing import Dict, List, Optional, Tuple

import torch
from PIL import Image
from torch import Tensor
from torch.utils.data import DataLoader, Dataset, Subset
from torchvision import transforms
from transformers import GPT2TokenizerFast

from .config import PathsConfig, TrainingConfig


IMAGENET_MEAN = [0.485, 0.456, 0.406]
IMAGENET_STD = [0.229, 0.224, 0.225]


def train_image_transform() -> transforms.Compose:
    """
    Image preprocessing for training with random augmentation to improve
    generalization. Augmentations are kept moderate to avoid changing the
    semantic content of the scene.
    """

    return transforms.Compose(
        [
            transforms.Resize(256),
            transforms.RandomResizedCrop(224, scale=(0.8, 1.0)),
            transforms.RandomHorizontalFlip(p=0.5),
            transforms.ColorJitter(
                brightness=0.2,
                contrast=0.2,
                saturation=0.2,
                hue=0.05,
            ),
            transforms.ToTensor(),
            transforms.Normalize(mean=IMAGENET_MEAN, std=IMAGENET_STD),
        ]
    )


def eval_image_transform() -> transforms.Compose:
    """
    Deterministic preprocessing for validation and test: resize, center-crop
    to 224x224, normalize.
    """

    return transforms.Compose(
        [
            transforms.Resize(256),
            transforms.CenterCrop(224),
            transforms.ToTensor(),
            transforms.Normalize(mean=IMAGENET_MEAN, std=IMAGENET_STD),
        ]
    )


class ImageCaptionDataset(Dataset):
    """
    Custom Dataset for the visually impaired image captioning data.

    This implementation is tailored to your existing layout:
    - Images:  <data_root>/visual_dataset/*.jpg
    - Text:
        - visual.token.txt           (image#idx<TAB>caption)
        - visual.trainImages.txt     (one image filename per line)
        - visual.testImages.txt      (one image filename per line)
    """

    def __init__(
        self,
        paths_cfg: PathsConfig,
        tokenizer: GPT2TokenizerFast,
        split: str = "train",
        training_cfg: Optional[TrainingConfig] = None,
        transform: Optional[transforms.Compose] = None,
        random_caption: bool = True,
    ) -> None:
        super().__init__()

        if split not in {"train", "val", "test"}:
            raise ValueError("split must be one of {'train', 'val', 'test'}")

        self.paths_cfg = paths_cfg
        self.tokenizer = tokenizer
        self.training_cfg = training_cfg or TrainingConfig()
        # If no transform is provided, fall back to a deterministic eval
        # transform so this class can still be used directly. In practice,
        # create_dataloader() will supply train/eval-specific transforms.
        self.transform = transform or eval_image_transform()
        self.random_caption = random_caption

        self.max_length: int = int(self.training_cfg.max_caption_length)

        # Load all captions from visual.token.txt
        token_path = self.paths_cfg.token_file
        if not os.path.exists(token_path):
            raise FileNotFoundError(f"Caption file not found: {token_path}")

        self.captions_by_image: Dict[str, List[str]] = {}
        with open(token_path, "r", encoding="utf-8") as f:
            for line in f:
                line = line.strip()
                if not line:
                    continue
                try:
                    key, caption = line.split("\t", 1)
                except ValueError as exc:
                    raise ValueError(f"Malformed line in {token_path}: {line}") from exc

                img_name = key.split("#")[0]
                self.captions_by_image.setdefault(img_name, []).append(caption.strip())

        # Choose image list file based on split
        if split == "train":
            list_file = self.paths_cfg.train_list_file
        else:
            # We only have a single test list in this dataset; use it for both
            # 'val' and 'test' splits for now.
            list_file = self.paths_cfg.test_list_file

        if not os.path.exists(list_file):
            raise FileNotFoundError(f"Image list file for split '{split}' not found: {list_file}")

        self.image_ids: List[str] = []
        with open(list_file, "r", encoding="utf-8") as f:
            for line in f:
                img_name = line.strip()
                if not img_name:
                    continue
                if img_name not in self.captions_by_image:
                    # Skip images without captions to avoid runtime issues
                    continue
                self.image_ids.append(img_name)

        if not self.image_ids:
            raise RuntimeError(f"No images with captions found for split '{split}'.")

        print(f"Loaded {len(self.image_ids)} {split} images with captions.")

    def __len__(self) -> int:
        return len(self.image_ids)

    def __getitem__(self, idx: int) -> Dict[str, Tensor]:
        img_name = self.image_ids[idx]
        img_path = os.path.join(self.paths_cfg.images_dir, img_name)

        if not os.path.exists(img_path):
            raise FileNotFoundError(f"Image file not found: {img_path}")

        image = Image.open(img_path).convert("RGB")
        image_tensor = self.transform(image)

        caption_list = self.captions_by_image[img_name]
        if not caption_list:
            raise RuntimeError(f"No captions available for image {img_name}")

        # Choose a caption. During training we consider up to three different
        # captions per image and randomly sample among them; for evaluation we
        # always take the first caption. We only strip leading/trailing
        # whitespace so that the raw textual content is preserved and no
        # characters are dropped before tokenization.
        if self.random_caption:
            limited_captions = caption_list[:3]
            caption = random.choice(limited_captions)
        else:
            caption = caption_list[0]
        caption = caption.strip()

        # Convert caption text into token IDs without adding any extra special
        # tokens so we retain a direct mapping between the raw caption string
        # and the token sequence.
        token_ids: List[int] = self.tokenizer.encode(
            caption,
            add_special_tokens=False,
        )

        # Define explicit BOS (start-of-sentence) and EOS (end-of-sentence)
        # tokens so the model learns where captions begin and end. If the
        # tokenizer does not define a BOS token, we reuse EOS.
        bos_token_id = self.tokenizer.bos_token_id or self.tokenizer.eos_token_id
        eos_token_id = self.tokenizer.eos_token_id

        seq_ids: List[int] = [bos_token_id] + token_ids + [eos_token_id]

        # Truncate if necessary to respect max_length. To guarantee that the
        # full caption (including BOS/EOS) can be represented without cutting
        # tokens, ensure that training_cfg.max_caption_length is set large
        # enough for your data.
        if len(seq_ids) > self.max_length:
            seq_ids = seq_ids[: self.max_length]

        # Pad up to max_length with pad_token_id and build attention mask.
        pad_id = self.tokenizer.pad_token_id
        input_ids = torch.full(
            (self.max_length,),
            pad_id,
            dtype=torch.long,
        )
        attention_mask = torch.zeros(self.max_length, dtype=torch.long)

        seq_len = len(seq_ids)
        input_ids[:seq_len] = torch.tensor(seq_ids, dtype=torch.long)
        attention_mask[:seq_len] = 1

        # Labels are initially the same as input_ids; padding positions will
        # be set to -100 so they are ignored by the loss.
        labels = input_ids.clone()
        labels[attention_mask == 0] = -100

        return {
            "image": image_tensor,
            "input_ids": input_ids,
            "attention_mask": attention_mask,
            "labels": labels,
            "caption": caption,
            "image_id": img_name,
        }


def create_tokenizer() -> GPT2TokenizerFast:
    """
    Create a GPT-2 tokenizer with a defined pad token.
    """

    tokenizer = GPT2TokenizerFast.from_pretrained("gpt2")
    if tokenizer.pad_token is None:
        tokenizer.pad_token = tokenizer.eos_token
    return tokenizer


def _infer_category_from_filename(filename: str) -> str:
    """
    Infer a coarse category label from an image filename.

    Heuristic:
    - Strip directory and extension.
    - Remove trailing digits to group files like 'bench1.jpg', 'bench25.jpg'
      into the same category 'bench'.
    """

    base = os.path.basename(filename)
    stem, _ext = os.path.splitext(base)

    # Remove trailing digits
    i = len(stem)
    while i > 0 and stem[i - 1].isdigit():
        i -= 1
    category = stem[:i] or stem

    return category


def _balanced_train_val_indices(
    dataset: ImageCaptionDataset,
    val_ratio: float = 0.2,
) -> Tuple[List[int], List[int]]:
    """
    Split the dataset indices into train and validation sets.

    The validation set:
    - Targets approximately `val_ratio` of the total dataset size.
    - Is balanced across categories inferred from filenames, i.e., each
      category contributes (as much as possible) the same number of images.
    """

    num_items = len(dataset.image_ids)
    if num_items == 0:
        raise RuntimeError("Cannot create train/val split from an empty dataset.")

    # Group indices by inferred category
    category_to_indices: Dict[str, List[int]] = {}
    for idx, img_name in enumerate(dataset.image_ids):
        cat = _infer_category_from_filename(img_name)
        category_to_indices.setdefault(cat, []).append(idx)

    # Sort indices within each category for deterministic behavior
    for indices in category_to_indices.values():
        indices.sort()

    categories = sorted(category_to_indices.keys())
    num_categories = len(categories)

    # Desired total size for validation set
    target_val_size = max(1, int(round(val_ratio * num_items)))

    # Base number of validation samples per category, constrained by the
    # smallest category so we can keep counts balanced.
    min_cat_size = min(len(category_to_indices[cat]) for cat in categories)
    per_category = min(
        min_cat_size,
        max(1, int(round(target_val_size / max(1, num_categories)))),
    )

    val_indices: List[int] = []
    train_indices: List[int] = []

    for cat in categories:
        indices = category_to_indices[cat]
        val_for_cat = indices[:per_category]
        train_for_cat = indices[per_category:]
        val_indices.extend(val_for_cat)
        train_indices.extend(train_for_cat)

    return train_indices, val_indices


def create_dataloader(
    paths_cfg: PathsConfig,
    training_cfg: TrainingConfig,
    split: str,
    tokenizer: Optional[GPT2TokenizerFast] = None,
    shuffle: Optional[bool] = None,
) -> Tuple[DataLoader, GPT2TokenizerFast]:
    """
    Factory function to create a DataLoader for a given split.

    Parameters
    ----------
    paths_cfg:
        Paths configuration.
    training_cfg:
        Training configuration containing batch size, max caption length, etc.
    split:
        One of {'train', 'val', 'test'}.
    tokenizer:
        Optional pre-initialized GPT-2 tokenizer. If None, a new one is created.
    shuffle:
        Optional flag to override shuffle behavior. If None, shuffle is True
        for the 'train' split and False otherwise.
    """

    if tokenizer is None:
        tokenizer = create_tokenizer()

    if shuffle is None:
        shuffle = split == "train"

    # For training and validation, we build a single underlying dataset from
    # the training list file and then create a balanced 80/20 split by
    # category. The test split continues to use the dedicated test list file.
    if split == "test":
        random_caption = False
        dataset = ImageCaptionDataset(
            paths_cfg=paths_cfg,
            tokenizer=tokenizer,
            split="test",
            training_cfg=training_cfg,
            transform=eval_image_transform(),
            random_caption=random_caption,
        )
    else:
        # Underlying full training dataset
        full_train_dataset = ImageCaptionDataset(
            paths_cfg=paths_cfg,
            tokenizer=tokenizer,
            split="train",
            training_cfg=training_cfg,
            transform=train_image_transform(),
            random_caption=True,  # always randomize captions during training
        )

        train_indices, val_indices = _balanced_train_val_indices(
            full_train_dataset,
            val_ratio=0.2,
        )

        if split == "train":
            dataset = Subset(full_train_dataset, train_indices)
        elif split == "val":
            dataset = Subset(full_train_dataset, val_indices)
        else:
            raise ValueError("split must be one of {'train', 'val', 'test'}")

    dataloader = DataLoader(
        dataset,
        batch_size=training_cfg.batch_size,
        shuffle=shuffle,
        num_workers=training_cfg.num_workers,
        pin_memory=torch.cuda.is_available(),
    )

    return dataloader, tokenizer