File size: 2,971 Bytes
d5049a2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from __future__ import annotations

from typing import Any, Dict, List

import torch
from torch.utils.data import Dataset

from .common import apply_chat_template, build_messages, normalized_row


class DriveDataset(Dataset):
    def __init__(self, rows: List[Dict[str, Any]]) -> None:
        self.rows = [normalized_row(row) for row in rows]

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

    def __getitem__(self, index: int) -> Dict[str, Any]:
        return self.rows[index]


class RawBatchCollator:
    """Keep raw examples for online generation. Batch size must be one/GPU."""

    def __call__(self, features: List[Dict[str, Any]]) -> Dict[str, Any]:
        if len(features) != 1:
            raise ValueError("Online OPD requires per-device batch size 1")
        return {"row": features[0]}


class SFTCollator:
    def __init__(self, processor, num_views: int, max_length: int) -> None:
        self.processor = processor
        self.num_views = num_views
        self.max_length = max_length

    def __call__(self, features: List[Dict[str, Any]]) -> Dict[str, torch.Tensor]:
        if len(features) != 1:
            raise ValueError(
                "This safe multimodal collator requires per-device batch size 1; "
                "use gradient accumulation for the effective batch size"
            )
        row = features[0]
        if not row["question"] or not row["answer"]:
            raise ValueError("question and answer must both be non-empty")

        prompt_messages = build_messages(
            row["question"], row["image_paths"], self.num_views
        )
        full_messages = build_messages(
            row["question"], row["image_paths"], self.num_views, row["answer"]
        )
        prompt = apply_chat_template(
            self.processor,
            prompt_messages,
            add_generation_prompt=True,
            max_length=self.max_length,
        )
        full = apply_chat_template(
            self.processor,
            full_messages,
            add_generation_prompt=False,
            max_length=self.max_length,
        )
        prompt_ids = prompt["input_ids"]
        full_ids = full["input_ids"]
        prompt_len = int(prompt_ids.shape[1])
        if full_ids.shape[1] <= prompt_len:
            raise ValueError(
                "Answer was fully truncated. Increase --max-length or shorten input."
            )
        if not torch.equal(full_ids[:, :prompt_len], prompt_ids):
            raise RuntimeError(
                "The full chat template is not prefixed by the generation prompt. "
                "Refusing to guess the assistant loss mask; inspect the local processor."
            )
        labels = full_ids.clone()
        labels[:, :prompt_len] = -100
        attention_mask = full.get("attention_mask")
        if attention_mask is not None:
            labels = labels.masked_fill(attention_mask.eq(0), -100)
        full["labels"] = labels
        return full