Download other_transfer/src/physics_model/collator.py from hk239/PhysVLM: direct link, hf CLI and curl.
- Browser
- Download file 9.61 kB
-
https://huggingface.co/datasets/hk239/PhysVLM/resolve/main/other_transfer/src/physics_model/collator.py
- Command line
-
hf download hf://datasets/hk239/PhysVLM/other_transfer/src/physics_model/collator.py
-
curl -L -o collator.py https://huggingface.co/datasets/hk239/PhysVLM/resolve/main/other_transfer/src/physics_model/collator.py
9.61 kB
| """Optional-image chat collator with assistant-only loss and left-prompt truncate.""" | |
| from __future__ import annotations | |
| import logging | |
| from pathlib import Path | |
| from typing import Any | |
| import torch | |
| from PIL import Image | |
| from physics_sft.prompts import build_system_prompt | |
| from .load import VISION_TOKEN_IDS | |
| logger = logging.getLogger(__name__) | |
| IGNORE_INDEX = -100 | |
| SYSTEM_PROMPT = build_system_prompt() | |
| def resolve_image_file(image_path: str | None, repo_root: Path) -> Path | None: | |
| if not image_path: | |
| return None | |
| path = Path(image_path) | |
| if path.is_file(): | |
| return path | |
| candidate = repo_root / image_path | |
| if candidate.is_file(): | |
| return candidate | |
| raise FileNotFoundError(f"image_path does not exist: {image_path}") | |
| def build_messages( | |
| question: str, | |
| assistant: str | None, | |
| *, | |
| has_image: bool, | |
| ) -> list[dict[str, Any]]: | |
| user_content: list[dict[str, Any]] = [] | |
| if has_image: | |
| user_content.append({"type": "image"}) | |
| user_content.append({"type": "text", "text": question}) | |
| messages: list[dict[str, Any]] = [ | |
| {"role": "system", "content": [{"type": "text", "text": SYSTEM_PROMPT}]}, | |
| {"role": "user", "content": user_content}, | |
| ] | |
| if assistant is not None: | |
| messages.append({"role": "assistant", "content": [{"type": "text", "text": assistant}]}) | |
| return messages | |
| class PhysicsVLCollator: | |
| def __init__( | |
| self, | |
| processor, | |
| *, | |
| repo_root: str | Path, | |
| max_length: int = 4096, | |
| log_overflow: bool = True, | |
| ) -> None: | |
| self.processor = processor | |
| self.repo_root = Path(repo_root) | |
| self.max_length = max_length | |
| self.log_overflow = log_overflow | |
| self.overflow_count = 0 | |
| self.seen = 0 | |
| self.tokenizer = processor.tokenizer | |
| if self.tokenizer.pad_token_id is None: | |
| self.tokenizer.pad_token = self.tokenizer.eos_token | |
| self.tokenizer.padding_side = "right" | |
| def reset_stats(self) -> None: | |
| self.overflow_count = 0 | |
| self.seen = 0 | |
| def _open_image(self, example: dict[str, Any]) -> Image.Image | None: | |
| if not example.get("has_image"): | |
| return None | |
| path = resolve_image_file(example.get("image_path"), self.repo_root) | |
| if path is None: | |
| raise ValueError(f"has_image=true but image_path is empty for id={example.get('id')}") | |
| return Image.open(path).convert("RGB") | |
| def _encode_text( | |
| self, | |
| messages: list[dict[str, Any]], | |
| image: Image.Image | None, | |
| add_generation_prompt: bool, | |
| ) -> dict[str, torch.Tensor]: | |
| text = self.processor.apply_chat_template( | |
| messages, | |
| tokenize=False, | |
| add_generation_prompt=add_generation_prompt, | |
| ) | |
| kwargs: dict[str, Any] = { | |
| "text": [text], | |
| "return_tensors": "pt", | |
| "padding": False, | |
| } | |
| if image is not None: | |
| kwargs["images"] = [image] | |
| encoded = self.processor(**kwargs) | |
| return encoded | |
| def encode_example(self, example: dict[str, Any], *, include_assistant: bool = True) -> dict[str, torch.Tensor]: | |
| has_image = bool(example.get("has_image")) | |
| image = self._open_image(example) if has_image else None | |
| assistant = example.get("assistant") if include_assistant else None | |
| full_messages = build_messages(example["question"], assistant, has_image=has_image) | |
| prompt_messages = build_messages(example["question"], None, has_image=has_image) | |
| full = self._encode_text(full_messages, image, add_generation_prompt=not include_assistant) | |
| prompt = self._encode_text(prompt_messages, image, add_generation_prompt=True) | |
| input_ids = full["input_ids"][0] | |
| attention_mask = full["attention_mask"][0] | |
| prompt_len = int(prompt["input_ids"].shape[-1]) | |
| if prompt_len > int(input_ids.shape[-1]): | |
| prompt_len = int(input_ids.shape[-1]) | |
| input_ids, attention_mask, prompt_len = self._left_truncate_prompt(input_ids, attention_mask, prompt_len) | |
| labels = input_ids.clone() | |
| labels[:prompt_len] = IGNORE_INDEX | |
| pad_id = self.tokenizer.pad_token_id | |
| if pad_id is not None: | |
| labels[input_ids == pad_id] = IGNORE_INDEX | |
| for token_id in VISION_TOKEN_IDS: | |
| labels[input_ids == token_id] = IGNORE_INDEX | |
| out: dict[str, torch.Tensor] = { | |
| "input_ids": input_ids, | |
| "attention_mask": attention_mask, | |
| "labels": labels, | |
| } | |
| # Keep processor batch layout for vision tensors (concat across examples later). | |
| if "pixel_values" in full: | |
| out["pixel_values"] = full["pixel_values"] | |
| if "image_grid_thw" in full: | |
| out["image_grid_thw"] = full["image_grid_thw"] | |
| return out | |
| def _left_truncate_prompt( | |
| self, | |
| input_ids: torch.Tensor, | |
| attention_mask: torch.Tensor, | |
| prompt_len: int, | |
| ) -> tuple[torch.Tensor, torch.Tensor, int]: | |
| total = int(input_ids.shape[-1]) | |
| self.seen += 1 | |
| if total <= self.max_length: | |
| return input_ids, attention_mask, prompt_len | |
| self.overflow_count += 1 | |
| assistant_len = total - prompt_len | |
| if assistant_len >= self.max_length: | |
| if self.log_overflow: | |
| logger.warning( | |
| "assistant span %s >= max_length %s; keeping assistant tail", | |
| assistant_len, | |
| self.max_length, | |
| ) | |
| return input_ids[-self.max_length :], attention_mask[-self.max_length :], 0 | |
| drop = total - self.max_length | |
| keep_prompt = prompt_len - drop | |
| if self.log_overflow and self.overflow_count <= 8: | |
| logger.warning("left-truncating prompt by %s tokens (total=%s)", drop, total) | |
| return input_ids[drop:], attention_mask[drop:], keep_prompt | |
| def __call__(self, examples: list[dict[str, Any]]) -> dict[str, torch.Tensor]: | |
| flags = [bool(ex.get("has_image")) for ex in examples] | |
| if len(set(flags)) > 1: | |
| raise ValueError("mixed image/text batch: bucket by has_image before collating") | |
| encoded = [self.encode_example(ex, include_assistant=True) for ex in examples] | |
| return self.pad_batch(encoded) | |
| def pad_batch(self, encoded: list[dict[str, torch.Tensor]]) -> dict[str, torch.Tensor]: | |
| pad_id = self.tokenizer.pad_token_id if self.tokenizer.pad_token_id is not None else 0 | |
| max_len = max(int(item["input_ids"].shape[-1]) for item in encoded) | |
| input_ids = [] | |
| attention_mask = [] | |
| labels = [] | |
| for item in encoded: | |
| pad = max_len - int(item["input_ids"].shape[-1]) | |
| if pad: | |
| input_ids.append(torch.nn.functional.pad(item["input_ids"], (0, pad), value=pad_id)) | |
| attention_mask.append(torch.nn.functional.pad(item["attention_mask"], (0, pad), value=0)) | |
| labels.append(torch.nn.functional.pad(item["labels"], (0, pad), value=IGNORE_INDEX)) | |
| else: | |
| input_ids.append(item["input_ids"]) | |
| attention_mask.append(item["attention_mask"]) | |
| labels.append(item["labels"]) | |
| batch: dict[str, torch.Tensor] = { | |
| "input_ids": torch.stack(input_ids, dim=0), | |
| "attention_mask": torch.stack(attention_mask, dim=0), | |
| "labels": torch.stack(labels, dim=0), | |
| } | |
| if "pixel_values" in encoded[0]: | |
| batch["pixel_values"] = torch.cat([item["pixel_values"] for item in encoded], dim=0) | |
| if "image_grid_thw" in encoded[0]: | |
| batch["image_grid_thw"] = torch.cat([item["image_grid_thw"] for item in encoded], dim=0) | |
| return batch | |
| def summarize_label_mask(batch: dict[str, torch.Tensor]) -> dict[str, Any]: | |
| labels = batch["labels"] | |
| input_ids = batch["input_ids"] | |
| vision = torch.zeros_like(input_ids, dtype=torch.bool) | |
| for token_id in VISION_TOKEN_IDS: | |
| vision |= input_ids == token_id | |
| pad_id = None | |
| stats = { | |
| "n": int(labels.shape[0]), | |
| "seq_len": int(labels.shape[1]), | |
| "n_ignored": int((labels == IGNORE_INDEX).sum().item()), | |
| "n_supervised": int((labels != IGNORE_INDEX).sum().item()), | |
| "vision_unmasked": int(((labels != IGNORE_INDEX) & vision).sum().item()), | |
| } | |
| if pad_id is not None: | |
| stats["pad_unmasked"] = int(((labels != IGNORE_INDEX) & (input_ids == pad_id)).sum().item()) | |
| return stats | |
| def tensors_for_generate(encoded: dict[str, torch.Tensor], device: torch.device | str) -> dict[str, torch.Tensor]: | |
| """Move one encoded example onto device for greedy decode. Do not batch-unsqueeze vision tensors.""" | |
| batch: dict[str, torch.Tensor] = {} | |
| for key, value in encoded.items(): | |
| if key == "labels" or not torch.is_tensor(value): | |
| continue | |
| tensor = value | |
| if key in {"input_ids", "attention_mask"} and tensor.dim() == 1: | |
| tensor = tensor.unsqueeze(0) | |
| batch[key] = tensor.to(device) | |
| return batch | |
| def token_length_percentiles(lengths: list[int]) -> dict[str, float]: | |
| if not lengths: | |
| return {"p50": 0.0, "p95": 0.0, "max": 0.0, "n": 0} | |
| ordered = sorted(lengths) | |
| n = len(ordered) | |
| def pct(p: float) -> float: | |
| idx = min(n - 1, max(0, int(round((p / 100.0) * (n - 1))))) | |
| return float(ordered[idx]) | |
| return {"p50": pct(50), "p95": pct(95), "max": float(ordered[-1]), "n": n} | |