Download src/common.py from huohuo0345/0716: direct link, hf CLI and curl.
- Browser
- Download file 6.43 kB
-
https://huggingface.co/datasets/huohuo0345/0716/resolve/main/src/common.py
- Command line
-
hf download hf://datasets/huohuo0345/0716/src/common.py
-
curl -L -o common.py https://huggingface.co/datasets/huohuo0345/0716/resolve/main/src/common.py
6.43 kB
| 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") | |