@@ -0,0 +1,121 @@ |
| 1 | +"""Vision-language generation path for `dlm prompt --image`. |
| 2 | + |
| 3 | +Mirrors `dlm.inference.generate` but drives an HF `AutoProcessor` |
| 4 | +(not a bare tokenizer) + `AutoModelForImageTextToText` through a |
| 5 | +prompt that carries one or more image placeholders. |
| 6 | + |
| 7 | +Shape contract matches what TRL 1.2's |
| 8 | +`DataCollatorForVisionLanguageModeling` emits at training time: the |
| 9 | +user's text carries the base's `image_token` placeholder (e.g. |
| 10 | +`<image>`) and the processor expands each occurrence into the base's |
| 11 | +`num_image_tokens` slots. This keeps prompt-time input aligned with |
| 12 | +training-time input — the same lesson the text path learned with |
| 13 | +`format_chat_prompt`. |
| 14 | + |
| 15 | +Heavy imports (`PIL`, `torch`) defer inside the functions so importing |
| 16 | +this module stays cheap. |
| 17 | +""" |
| 18 | + |
| 19 | +from __future__ import annotations |
| 20 | + |
| 21 | +from pathlib import Path |
| 22 | +from typing import Any |
| 23 | + |
| 24 | +from dlm.inference.generate import DEFAULT_MAX_NEW_TOKENS, build_generate_kwargs |
| 25 | + |
| 26 | + |
| 27 | +def format_vl_prompt( |
| 28 | + prompt: str, |
| 29 | + *, |
| 30 | + image_token: str, |
| 31 | + num_images: int, |
| 32 | +) -> str: |
| 33 | + """Build the VL-aware prompt text. |
| 34 | + |
| 35 | + When the user's prompt already contains `image_token`, pass it |
| 36 | + through — they explicitly placed the image. Otherwise prepend one |
| 37 | + `image_token` per image so the processor can slot the pixels in |
| 38 | + before the text; trailing newline separates the image block from |
| 39 | + the user's question the way every VL chat template does. |
| 40 | + |
| 41 | + This matches `sections_to_rows`' IMAGE emission at training time: |
| 42 | + `"<image>\\n<caption>"` — training and prompt-time input see the |
| 43 | + same token order. |
| 44 | + """ |
| 45 | + if image_token in prompt: |
| 46 | + return prompt |
| 47 | + tokens = image_token * num_images |
| 48 | + return f"{tokens}\n{prompt}" if prompt else tokens |
| 49 | + |
| 50 | + |
| 51 | +def load_images(paths: list[Path]) -> list[Any]: |
| 52 | + """Open each path as a PIL.Image in RGB mode. |
| 53 | + |
| 54 | + Raises `FileNotFoundError` on missing paths; a PIL `UnidentifiedImageError` |
| 55 | + on files that aren't a decodable image. Both bubble up to the CLI |
| 56 | + which converts them into typer exits. |
| 57 | + """ |
| 58 | + from PIL import Image |
| 59 | + |
| 60 | + images: list[Any] = [] |
| 61 | + for path in paths: |
| 62 | + if not path.exists(): |
| 63 | + raise FileNotFoundError(f"image not found: {path}") |
| 64 | + with Image.open(path) as pil: |
| 65 | + pil.load() |
| 66 | + images.append(pil.convert("RGB")) |
| 67 | + return images |
| 68 | + |
| 69 | + |
| 70 | +def generate_vl( # pragma: no cover |
| 71 | + model: Any, |
| 72 | + processor: Any, |
| 73 | + prompt: str, |
| 74 | + images: list[Any], |
| 75 | + *, |
| 76 | + image_token: str, |
| 77 | + max_new_tokens: int = DEFAULT_MAX_NEW_TOKENS, |
| 78 | + temperature: float = 0.0, |
| 79 | + top_p: float | None = None, |
| 80 | + top_k: int | None = None, |
| 81 | + repetition_penalty: float | None = None, |
| 82 | +) -> str: |
| 83 | + """Render VL prompt, run generation, decode response-only tokens. |
| 84 | + |
| 85 | + `processor` is an `AutoProcessor` for a VL base. `images` is a |
| 86 | + list of PIL.Image objects, one per `image_token` occurrence in |
| 87 | + `prompt` (or pre-prepended for the user). `image_token` comes from |
| 88 | + the base's `VlPreprocessorPlan`. |
| 89 | + |
| 90 | + Pragma'd from unit coverage because it calls `model.generate` on a |
| 91 | + real HF VL model; covered by the slow-marked integration test. |
| 92 | + """ |
| 93 | + import torch |
| 94 | + |
| 95 | + formatted = format_vl_prompt(prompt, image_token=image_token, num_images=len(images)) |
| 96 | + inputs = processor( |
| 97 | + images=images, |
| 98 | + text=formatted, |
| 99 | + return_tensors="pt", |
| 100 | + ).to(model.device) |
| 101 | + input_len = int(inputs["input_ids"].shape[-1]) |
| 102 | + |
| 103 | + gen_kwargs = build_generate_kwargs( |
| 104 | + max_new_tokens=max_new_tokens, |
| 105 | + temperature=temperature, |
| 106 | + top_p=top_p, |
| 107 | + top_k=top_k, |
| 108 | + repetition_penalty=repetition_penalty, |
| 109 | + ) |
| 110 | + |
| 111 | + tokenizer = getattr(processor, "tokenizer", processor) |
| 112 | + with torch.inference_mode(): |
| 113 | + output = model.generate( |
| 114 | + **inputs, |
| 115 | + **gen_kwargs, |
| 116 | + pad_token_id=tokenizer.pad_token_id, |
| 117 | + ) |
| 118 | + |
| 119 | + response_tokens = output[0, input_len:] |
| 120 | + decoded = tokenizer.decode(response_tokens, skip_special_tokens=True) |
| 121 | + return str(decoded) |