"""Step 4: verify the collator->PR-model mask remap is pixel-accurate.""" import json import logging import sys import numpy as np import torch sys.path.insert(0, "/work/Xiaomi-Lens-0/src") logging.basicConfig(level=logging.INFO) from transformers import AutoProcessor # noqa: E402 from xiaomi_lens.constants import MASK_TOKEN # noqa: E402 from xiaomi_lens.train.collator import LazyCollator # noqa: E402 from xiaomi_lens.train.data.io import load_dataset_config, resolve_sample_images # noqa: E402 from xiaomi_lens.train.data.preprocess import encode_sample # noqa: E402 from xiaomi_lens.train.trainer import MASK_CANVAS_SCALE # noqa: E402 REPO = "/work/Xiaomi-Lens-0" MANIFEST = f"{REPO}/examples/train/stage2.yaml" def decode_rle(rle: dict) -> np.ndarray: """Inverse of the toy generator's encode_rle: column-major uncompressed RLE.""" h, w = rle["size"] flat = np.zeros(h * w, dtype=np.uint8) pos, val = 0, 0 for run in rle["counts"]: run = int(run) if val: flat[pos : pos + run] = 1 pos += run val = 1 - val if pos != h * w: raise ValueError(f"RLE length {pos} != {h * w}") return flat.reshape((w, h)).T # inverse of F-order flatten def remap_masks(batch, grid_thw, images_per_sample): """Collator ragged per-sample keys -> PR model mask_labels/mask_labels_valid_mask. Packed canvases are per-mask np.packbits(pixel_mask.flatten()) at (grid_h*16, grid_w*16), MSB-first (bitorder='big'), row-major layout — verified against trainer.py _build_mask_inputs and data/preprocess.py. """ mask_labels, mask_labels_valid_mask = [], [] cum = 0 for b, n_imgs in enumerate(images_per_sample): for img in range(cum, cum + n_imgs): gh, gw = int(grid_thw[img][1]), int(grid_thw[img][2]) # (t, grid_h, grid_w) H, W = gh * MASK_CANVAS_SCALE, gw * MASK_CANVAS_SCALE positions = batch["_per_sample_mask_positions"][b] valid = batch["_per_sample_mask_valid_mask"][b] packed = batch["_per_sample_mask_pixel_masks"][b] # per-mask image_index binds each <|mask|> to its nearest preceding image masks, vmasks = [], [] for k in range(len(positions)): bound_ok = k < len(batch["_per_sample_mask_image_index"][b]) and ( int(batch["_per_sample_mask_image_index"][b][k]) == img - cum ) is_valid = bound_ok and k < len(valid) and valid[k] > 0 and packed[k] if is_valid: arr = np.unpackbits( np.frombuffer(packed[k], dtype=np.uint8), count=H * W ).reshape(H, W) masks.append(torch.from_numpy(arr.copy())) vmasks.append(torch.ones((H, W), dtype=torch.bool)) else: masks.append(torch.zeros((H, W), dtype=torch.bool)) vmasks.append(torch.zeros((H, W), dtype=torch.bool)) mask_labels.append(torch.stack(masks) if masks else torch.zeros((0, H, W), dtype=torch.bool)) mask_labels_valid_mask.append( torch.stack(vmasks) if vmasks else torch.zeros((0, H, W), dtype=torch.bool) ) cum += n_imgs return mask_labels, mask_labels_valid_mask def main(): processor = AutoProcessor.from_pretrained("guarin/Xiaomi-Lens-0") processor.tokenizer.model_max_length = 8192 ip = processor.image_processor ip.max_pixels = 4194304 ip.min_pixels = 65536 mask_token_id = processor.tokenizer.convert_tokens_to_ids(MASK_TOKEN) print("mask_token_id:", mask_token_id) collator = LazyCollator( processor, mask_token_id=mask_token_id, model_max_length=8192, max_pixels=4194304, min_pixels=65536, ) entries = load_dataset_config(MANIFEST, split="train") entry = entries[0] rows = [] with open(entry.path) as f: for line in f: rows.append(resolve_sample_images(json.loads(line), entry.image_folder)) rows = rows[:8] # Pre-encode so we know which rows survive (encode_sample needs image_folder # in resolved paths, which resolve_sample_images already baked in). images_per_sample = [] kept = [] for row in rows: try: enc = encode_sample( row, processor=processor, mask_token_id=mask_token_id, model_max_length=8192, max_pixels=4194304, min_pixels=65536, ) except Exception as exc: print(f"dropped row (images={row.get('images')}): {exc}") continue kept.append(row) images_per_sample.append(len(row.get("images") or [])) print("kept", len(kept), "of", len(rows), "images_per_sample:", images_per_sample) batch = collator(kept) print("collate keys:", sorted(k for k in batch.keys())) print("input_ids shape:", tuple(batch["input_ids"].shape)) grid_thw = batch["image_grid_thw"] print("image_grid_thw:", grid_thw.tolist()) K = max((len(p) for p in batch["_per_sample_mask_positions"]), default=0) print("max masks per sample K:", K) assert grid_thw.shape[0] == sum(images_per_sample) mask_labels, mask_labels_valid_mask = remap_masks(batch, grid_thw, images_per_sample) for img in range(grid_thw.shape[0]): gh, gw = int(grid_thw[img][1]), int(grid_thw[img][2]) # (t, grid_h, grid_w) H, W = gh * MASK_CANVAS_SCALE, gw * MASK_CANVAS_SCALE ml = mask_labels[img] assert ml.shape[1:] == (H, W), (ml.shape, H, W) print(f"image {img}: grid=({gh},{gw}) -> ({H},{W}), num_masks={ml.shape[0]}, " f"valid={int(mask_labels_valid_mask[img].any(dim=(1, 2)).sum())}") ok = True for b, row in enumerate(kept): if not row.get("segmentation"): continue if int(batch["_per_sample_mask_valid_mask"][b][0]) <= 0: print(f"sample {b}: first mask invalid (truncated?), skipped") continue k = 0 # first mask of the sample binds to its own first image packed = batch["_per_sample_mask_pixel_masks"][b][k] gidx = sum(images_per_sample[:b]) + 0 # global image index of sample b's image 0 gh, gw = int(grid_thw[gidx][1]), int(grid_thw[gidx][2]) H, W = gh * 16, gw * 16 rle = row["segmentation"][0] src_h, src_w = rle["size"] area = int(decode_rle(rle).sum()) got = int(mask_labels[gidx][k].sum().item()) # repo rasterization: decode RLE at source size, PIL-NEAREST to canvas from PIL import Image src = decode_rle(rle) ref = np.asarray( Image.fromarray(src, mode="L").resize((W, H), resample=Image.Resampling.NEAREST), dtype=np.uint8, ) ref_sum = int(ref.sum()) elem = bool((mask_labels[gidx][k].numpy().astype(np.uint8) == ref).all()) status = "MATCH" if got == ref_sum and elem else "MISMATCH" ok = ok and (got == ref_sum) and elem print(f"sample {b} (image 0, canvas {H}x{W}): RLE src area={area} " f"(src {src_h}x{src_w}) NN-resized ref={ref_sum} remapped_sum={got} " f"elementwise={elem} {status}") print("REMAP", "OK" if ok else "FAILED") if __name__ == "__main__": main()