File size: 6,918 Bytes
ee15e43
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
"""Данные для PP-OSR-H: картинки + подписи.

Скачивает Flickr30k (31k фото × ~5 подписей), ресайзит в 128×128, кодирует
подписи токенизатором и складывает в три файла:

    images.npy   uint8 (N, 3, 128, 128)   — уже в 0..255
    captions.bin uint16                    — все подписи подряд
    meta.json    {(offsets, img_idx)}      — где чья подпись

Память: 30k картинок × 49 КБ ≈ 1.5 ГБ.
"""
from __future__ import annotations

import json
import os

import numpy as np

IMAGE_SIZE = 128


def _to_array(img, size: int = IMAGE_SIZE) -> np.ndarray:
    from PIL import Image

    if not isinstance(img, Image.Image):
        img = Image.fromarray(np.asarray(img))
    img = img.convert("RGB").resize((size, size), Image.BICUBIC)
    return np.asarray(img, dtype=np.uint8).transpose(2, 0, 1)  # (3,H,W)


CAPTION_KEYS = ("caption", "captions", "sentences_raw", "sentences", "text",
                "conversations", "answer", "label")
IMAGE_KEYS = ("image", "img", "images", "pixel_values")


def _extract_caption(ex: dict) -> list[str]:
    """Достать подписи из записи, как бы они ни назывались."""
    for k in CAPTION_KEYS:
        if k not in ex:
            continue
        v = ex[k]
        if isinstance(v, str):
            return [v]
        if isinstance(v, (list, tuple)):
            out = []
            for item in v:
                if isinstance(item, str):
                    out.append(item)
                elif isinstance(item, dict):
                    # llava-style: {"from": "gpt", "value": "..."}
                    val = item.get("value") or item.get("content")
                    if isinstance(val, str):
                        out.append(val)
            if out:
                return out
    return []


def _extract_image(ex: dict):
    for k in IMAGE_KEYS:
        v = ex.get(k)
        if v is not None and not isinstance(v, (str, int, float)):
            if isinstance(v, (list, tuple)) and v and not hasattr(v[0], "convert"):
                continue
            return v
    return None


def build(out_dir: str, tokenizer_dir: str, token: str | None = None,
          n_images: int = 30000, hf_name: str = "lmms-lab-encoder/COCO-Caption",
          split: str = "train", config: str | None = None) -> dict:
    from datasets import load_dataset
    from transformers import AutoTokenizer

    os.makedirs(out_dir, exist_ok=True)
    tok = AutoTokenizer.from_pretrained(tokenizer_dir, trust_remote_code=True)

    print(f"[vl] качаю {hf_name} (до {n_images} картинок)", flush=True)
    kw = dict(split=split, streaming=True, token=token)
    if config:
        kw["name"] = config
    ds = load_dataset(hf_name, **kw)

    images = np.zeros((n_images, 3, IMAGE_SIZE, IMAGE_SIZE), dtype=np.uint8)
    caps: list[np.ndarray] = []
    img_idx: list[int] = []
    offsets: list[int] = []
    pos = 0
    n = 0
    scanned = 0

    for ex in ds:
        if n >= n_images:
            break
        scanned += 1
        if scanned == 1:
            print(f"[vl] поля записи: {list(ex.keys())}", flush=True)
        img = _extract_image(ex)
        if img is None:
            continue
        captions = _extract_caption(ex)
        captions = [c for c in captions if c.strip()]
        if not captions:
            continue
        try:
            images[n] = _to_array(img)
        except Exception as exc:  # noqa: BLE001
            if scanned < 5:
                print(f"[vl] картинка не обработалась: {type(exc).__name__}", flush=True)
            continue
        for c in captions:
            ids = tok(c.strip(), add_special_tokens=False).input_ids[:255]
            if not ids:
                continue
            arr = np.asarray(ids + [tok.eos_token_id], dtype=np.uint16)
            offsets.append(pos)
            caps.append(arr)
            img_idx.append(n)
            pos += len(arr)
        n += 1
        if n % 2000 == 0:
            print(f"[vl]   {n} картинок, {len(caps)} подписей", flush=True)

    if n == 0:
        raise SystemExit("[vl] ни одной картинки не скачалось")

    images = images[:n]
    cat = np.concatenate(caps)
    np.save(os.path.join(out_dir, "images.npy"), images)
    cat.tofile(os.path.join(out_dir, "captions.bin"))
    np.save(os.path.join(out_dir, "captions_off.npy"), np.asarray(offsets, dtype=np.int64))
    np.save(os.path.join(out_dir, "captions_img.npy"), np.asarray(img_idx, dtype=np.int32))

    lens = np.diff(np.asarray(offsets + [pos]))
    meta = {"n_images": int(n), "n_captions": len(caps),
            "mean_caption_len": float(lens.mean()),
            "vocab_size": len(tok), "image_size": IMAGE_SIZE,
            "eos": tok.eos_token_id, "pad": tok.pad_token_id}
    with open(os.path.join(out_dir, "meta.json"), "w", encoding="utf-8") as fh:
        json.dump(meta, fh, ensure_ascii=False, indent=2)
    print(f"[vl] готово: {n} картинок, {len(caps)} подписей, "
          f"средняя длина {lens.mean():.1f} токенов", flush=True)
    return meta


class VLData:
    """Батчи (pixel_values, input_ids, labels) для обучения."""

    def __init__(self, out_dir: str, seed: int = 1337, max_len: int = 48):
        self.images = np.load(os.path.join(out_dir, "images.npy"), mmap_mode="r")
        self.captions = np.memmap(os.path.join(out_dir, "captions.bin"), dtype=np.uint16, mode="r")
        self.offsets = np.load(os.path.join(out_dir, "captions_off.npy"))
        self.img_of = np.load(os.path.join(out_dir, "captions_img.npy"))
        self.meta = json.load(open(os.path.join(out_dir, "meta.json"), encoding="utf-8"))
        self.max_len = max_len
        self.rng = np.random.default_rng(seed)
        self.pad = int(self.meta.get("pad") or 0) or 0

    def batch(self, n: int):
        import torch

        pick = self.rng.integers(0, len(self.offsets), size=n)
        ids = np.full((n, self.max_len), self.pad, dtype=np.int64)
        labels = np.full((n, self.max_len), -100, dtype=np.int64)
        px = np.empty((n, 3, IMAGE_SIZE, IMAGE_SIZE), dtype=np.float32)
        for row, ci in enumerate(pick):
            start = int(self.offsets[ci])
            end = int(self.offsets[ci + 1]) if ci + 1 < len(self.offsets) else len(self.captions)
            seq = np.asarray(self.captions[start:end], dtype=np.int64)[: self.max_len]
            ids[row, : len(seq)] = seq
            labels[row, : len(seq)] = seq
            img = np.asarray(self.images[int(self.img_of[ci])], dtype=np.float32)
            px[row] = img / 255.0 * 2.0 - 1.0        # в [-1, 1]
        return torch.from_numpy(px), torch.from_numpy(ids), torch.from_numpy(labels)