File size: 6,427 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
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
from __future__ import annotations

import hashlib
import json
import os
from pathlib import Path
from typing import Any, Dict, Iterable, List, Sequence

import torch


CAMERA_ORDER = [
    "CAM_FRONT",
    "CAM_FRONT_LEFT",
    "CAM_FRONT_RIGHT",
    "CAM_BACK",
    "CAM_BACK_LEFT",
    "CAM_BACK_RIGHT",
]

SYSTEM_PROMPT = (
    "You are an expert autonomous-driving assistant. Analyze the camera "
    "views carefully and answer the driving-scene question accurately, "
    "safely, and concisely. Do not invent objects that are not visible."
)


def camera_names(num_views: int) -> List[str]:
    if not 1 <= num_views <= len(CAMERA_ORDER):
        raise ValueError(f"num_views must be in [1, 6], got {num_views}")
    return CAMERA_ORDER[:num_views]


def load_rows(data_dir: str, split: str) -> List[Dict[str, Any]]:
    root = Path(data_dir)
    candidates = [
        root / f"{split}.json",
        root / f"drivelm_{split}.json",
        root / f"{split}.jsonl",
    ]
    path = next((item for item in candidates if item.is_file()), None)
    if path is None:
        raise FileNotFoundError(
            f"No {split} JSON/JSONL file under {root}. Expected one of: "
            + ", ".join(str(item) for item in candidates)
        )
    if path.suffix == ".jsonl":
        rows = []
        with path.open("r", encoding="utf-8") as handle:
            for line_no, line in enumerate(handle, 1):
                if line.strip():
                    row = json.loads(line)
                    if not isinstance(row, dict):
                        raise TypeError(f"{path}:{line_no} is not an object")
                    rows.append(row)
        return rows
    with path.open("r", encoding="utf-8") as handle:
        payload = json.load(handle)
    if not isinstance(payload, list):
        raise TypeError(
            f"{path} must be a list of flattened QA rows. Convert raw DriveLM first."
        )
    return payload


def normalized_row(row: Dict[str, Any]) -> Dict[str, Any]:
    question = str(row.get("question", row.get("query", ""))).strip()
    answer = str(row.get("answer", row.get("response", ""))).strip()
    image_paths = row.get("image_paths") or {}
    if not isinstance(image_paths, dict):
        raise TypeError("image_paths must be an object keyed by camera name")
    return {
        "scene_id": str(row.get("scene_id", "")),
        "frame_token": str(row.get("frame_token", "")),
        "task_type": str(row.get("task_type", row.get("category", "unknown"))),
        "question": question,
        "answer": answer,
        "image_paths": {str(key): str(value) for key, value in image_paths.items()},
    }


def validate_image_paths(
    image_paths: Dict[str, str],
    num_views: int,
    allow_missing: bool = False,
) -> List[str]:
    selected = []
    missing = []
    for camera in camera_names(num_views):
        value = str(image_paths.get(camera, ""))
        if not value or not os.path.isfile(value):
            missing.append(f"{camera}={value!r}")
        selected.append(value)
    if missing and not allow_missing:
        raise FileNotFoundError("Missing required camera images: " + "; ".join(missing))
    return selected


def build_messages(
    question: str,
    image_paths: Dict[str, str],
    num_views: int,
    answer: str | None = None,
) -> List[Dict[str, Any]]:
    paths = validate_image_paths(image_paths, num_views, allow_missing=False)
    content: List[Dict[str, str]] = [
        {"type": "image", "path": path} for path in paths
    ]
    content.append({"type": "text", "text": question})
    messages: List[Dict[str, Any]] = [
        {
            "role": "system",
            "content": [{"type": "text", "text": SYSTEM_PROMPT}],
        },
        {"role": "user", "content": content},
    ]
    if answer is not None:
        messages.append(
            {
                "role": "assistant",
                "content": [{"type": "text", "text": answer}],
            }
        )
    return messages


def apply_chat_template(
    processor,
    messages: Sequence[Dict[str, Any]],
    *,
    add_generation_prompt: bool,
    max_length: int,
):
    return processor.apply_chat_template(
        list(messages),
        add_generation_prompt=add_generation_prompt,
        tokenize=True,
        return_dict=True,
        return_tensors="pt",
        truncation=True,
        max_length=max_length,
    )


def move_to_device(batch: Dict[str, Any], device: torch.device) -> Dict[str, Any]:
    return {
        key: value.to(device) if torch.is_tensor(value) else value
        for key, value in batch.items()
    }


def append_response_ids(
    prompt_batch: Dict[str, Any],
    response_ids: torch.Tensor,
) -> tuple[Dict[str, Any], int]:
    input_ids = prompt_batch["input_ids"]
    if input_ids.shape[0] != 1 or response_ids.shape[0] != 1:
        raise ValueError("The first online OPD implementation requires batch size 1")
    prompt_len = int(input_ids.shape[1])
    result: Dict[str, Any] = {}
    for key, value in prompt_batch.items():
        if key in {"input_ids", "attention_mask", "position_ids", "cache_position"}:
            continue
        result[key] = value
    result["input_ids"] = torch.cat([input_ids, response_ids], dim=1)
    prompt_mask = prompt_batch.get("attention_mask", torch.ones_like(input_ids))
    response_mask = torch.ones_like(response_ids, dtype=prompt_mask.dtype)
    result["attention_mask"] = torch.cat([prompt_mask, response_mask], dim=1)
    return result, prompt_len


def tokenizer_fingerprint(tokenizer) -> str:
    """Hash token-id mapping and special tokens; OPD requires an exact match."""
    digest = hashlib.sha256()
    digest.update(str(len(tokenizer)).encode("utf-8"))
    for index in range(len(tokenizer)):
        token = tokenizer.convert_ids_to_tokens(index)
        digest.update(index.to_bytes(4, "little", signed=False))
        digest.update(str(token).encode("utf-8", errors="surrogatepass"))
        digest.update(b"\0")
    digest.update(
        json.dumps(
            tokenizer.special_tokens_map,
            ensure_ascii=False,
            sort_keys=True,
        ).encode("utf-8")
    )
    return digest.hexdigest()


def infer_input_device(model) -> torch.device:
    for parameter in model.parameters():
        if parameter.device.type != "meta":
            return parameter.device
    raise RuntimeError("Could not infer a real model input device")