|
| 1 | +import logging |
| 2 | +from collections.abc import Iterator |
| 3 | + |
| 4 | +from datasets import Dataset |
| 5 | + |
| 6 | +from leap_finetune.data_loading.image_loader import get_image_size |
| 7 | + |
| 8 | +logger = logging.getLogger(__name__) |
| 9 | +VLM_TILE_COUNT_COLUMN = "_vlm_tile_count" |
| 10 | + |
| 11 | + |
| 12 | +def _image_sources(value) -> Iterator[str]: |
| 13 | + if isinstance(value, dict): |
| 14 | + if value.get("type") == "image" and isinstance(value.get("image"), str): |
| 15 | + yield value["image"] |
| 16 | + return |
| 17 | + for child in value.values(): |
| 18 | + yield from _image_sources(child) |
| 19 | + elif isinstance(value, (list, tuple)): |
| 20 | + for child in value: |
| 21 | + yield from _image_sources(child) |
| 22 | + |
| 23 | + |
| 24 | +def _row_image_sources(row: dict) -> Iterator[str]: |
| 25 | + for key in ("messages", "prompt", "chosen", "rejected"): |
| 26 | + if key in row: |
| 27 | + yield from _image_sources(row[key]) |
| 28 | + if isinstance(row.get("image"), str): |
| 29 | + yield row["image"] |
| 30 | + if isinstance(row.get("images"), (list, tuple)): |
| 31 | + yield from (image for image in row["images"] if isinstance(image, str)) |
| 32 | + |
| 33 | + |
| 34 | +def _tile_count(image_processor, height: int, width: int) -> int: |
| 35 | + """Match LFM2-VL's grid decision without running pixel preprocessing.""" |
| 36 | + if not getattr(image_processor, "do_image_splitting", False): |
| 37 | + return 1 |
| 38 | + |
| 39 | + is_too_large = getattr(image_processor, "_is_image_too_large", None) |
| 40 | + get_grid_layout = getattr(image_processor, "_get_grid_layout", None) |
| 41 | + if is_too_large is None or get_grid_layout is None: |
| 42 | + return 1 |
| 43 | + |
| 44 | + kwargs = { |
| 45 | + "max_image_tokens": int(getattr(image_processor, "max_image_tokens", 256)), |
| 46 | + "encoder_patch_size": int(getattr(image_processor, "encoder_patch_size", 16)), |
| 47 | + "downsample_factor": int(getattr(image_processor, "downsample_factor", 2)), |
| 48 | + "max_pixels_tolerance": float( |
| 49 | + getattr(image_processor, "max_pixels_tolerance", 2.0) |
| 50 | + ), |
| 51 | + } |
| 52 | + if not is_too_large(height=height, width=width, **kwargs): |
| 53 | + return 1 |
| 54 | + |
| 55 | + _, _, _, _, tiles = get_grid_layout( |
| 56 | + height=height, |
| 57 | + width=width, |
| 58 | + min_tiles=int(getattr(image_processor, "min_tiles", 2)), |
| 59 | + max_tiles=int(getattr(image_processor, "max_tiles", 10)), |
| 60 | + tile_size=int(getattr(image_processor, "tile_size", 512)), |
| 61 | + ) |
| 62 | + if getattr(image_processor, "use_thumbnail", True) and tiles > 1: |
| 63 | + tiles += 1 |
| 64 | + return int(tiles) |
| 65 | + |
| 66 | + |
| 67 | +def estimate_vlm_tile_count(row: dict, processor) -> int: |
| 68 | + """Estimate processed visual tiles for one normalized VLM row.""" |
| 69 | + image_processor = getattr(processor, "image_processor", None) |
| 70 | + if image_processor is None: |
| 71 | + return 0 |
| 72 | + |
| 73 | + count = 0 |
| 74 | + for source in _row_image_sources(row): |
| 75 | + try: |
| 76 | + width, height = get_image_size(source) |
| 77 | + count += _tile_count(image_processor, height, width) |
| 78 | + except Exception: |
| 79 | + logger.debug( |
| 80 | + "Could not estimate VLM tile count for %s", source, exc_info=True |
| 81 | + ) |
| 82 | + count += 1 |
| 83 | + return count |
| 84 | + |
| 85 | + |
| 86 | +def add_vlm_tile_counts(dataset: Dataset | None, processor) -> Dataset | None: |
| 87 | + """Add local, non-training metadata used by the VLM batch sampler.""" |
| 88 | + if dataset is None or VLM_TILE_COUNT_COLUMN in dataset.column_names: |
| 89 | + return dataset |
| 90 | + counts = [estimate_vlm_tile_count(row, processor) for row in dataset] |
| 91 | + return dataset.add_column(VLM_TILE_COUNT_COLUMN, counts) |
0 commit comments