""" vision.py — nhánh đọc ảnh của GromGPT. Gồm 2 phần: 1) PictureDataset : đọc nhãn trực tiếp data/picture// hoặc nhãn được nhóm data/picture///. 2) ImageEncoder : ViT nhỏ. Cắt ảnh thành patch -> Transformer -> vài "token ảnh" (n_img_tokens) cùng chiều n_embd với GPT, để nối vào TRƯỚC chuỗi văn bản. Cấu trúc thư mục: data/picture/ xe_may/ anh_001.jpg anh_002.png ... o_to/ ... may_bay/ ... xin_chao/ ... <- "từ ngữ" cũng là một nhãn, ảnh chứa chữ Thư mục lớp = nhãn; thư mục nhóm có thư mục con sẽ không tự tạo nhãn. Model sẽ học: ảnh -> "Đây là ". Để in ra đẹp hơn, đặt tên hiển thị trong data/picture/labels.json (không bắt buộc), ví dụ: {"xe_may": "xe máy", "o_to": "ô tô"} """ from __future__ import annotations import json import random from grom_runtime import AI_NAME, DEVELOPER_NAME from pathlib import Path try: import numpy as np except ImportError: # text-only/low-resource training does not require NumPy np = None import torch import torch.nn as nn from PIL import Image IMG_EXTS = {".jpg", ".jpeg", ".png", ".bmp", ".webp", ".gif"} # Chuẩn hóa kiểu ImageNet. Tạo mảng NumPy chỉ khi thực sự đọc ảnh, # để text-only training không phụ thuộc NumPy. _MEAN_VALUES = (0.485, 0.456, 0.406) _STD_VALUES = (0.229, 0.224, 0.225) # --------------------------------------------------------------------------- # Tiền xử lý ảnh # --------------------------------------------------------------------------- def load_image(path, size: int, augment: bool = False) -> torch.Tensor: """Đọc ảnh -> tensor float [3, size, size], đã chuẩn hóa. Resize giữ tỉ lệ rồi pad (letterbox) để không méo ảnh — quan trọng với ảnh chứa chữ. Nếu augment=True thì thêm lật ngang + đổi độ sáng nhẹ (KHÔNG lật ngang với ảnh có chữ, xem PictureDataset.flip_labels). """ img = Image.open(path) img = img.convert("RGB") w, h = img.size scale = size / max(w, h) nw, nh = max(1, round(w * scale)), max(1, round(h * scale)) img = img.resize((nw, nh), Image.BICUBIC) if np is None: raise RuntimeError("NumPy is required only for image training; install NumPy to enable vision mode.") canvas = Image.new("RGB", (size, size), (127, 127, 127)) canvas.paste(img, ((size - nw) // 2, (size - nh) // 2)) arr = np.asarray(canvas, dtype=np.float32) / 255.0 if augment: arr = np.clip(arr * random.uniform(0.85, 1.15), 0.0, 1.0) mean = np.asarray(_MEAN_VALUES, dtype=np.float32) std = np.asarray(_STD_VALUES, dtype=np.float32) arr = (arr - mean) / std return torch.from_numpy(arr).permute(2, 0, 1).contiguous() # --------------------------------------------------------------------------- # Dataset # --------------------------------------------------------------------------- def _visible_dirs(p: Path) -> list[Path]: """Thư mục con không ẩn. Tên bắt đầu bằng '.' hoặc '_' (vd _unsorted) bị bỏ qua.""" return sorted(d for d in p.iterdir() if d.is_dir() and not d.name.startswith((".", "_"))) def _images(folder: Path) -> list[Path]: """Mọi ảnh trong folder, bỏ qua thư mục ẩn/_unsorted ở bên trong.""" out = [] for p in folder.rglob("*"): if p.suffix.lower() not in IMG_EXTS: continue if any(part.startswith((".", "_")) for part in p.relative_to(folder).parts[:-1]): continue out.append(p) return sorted(out) def scan_picture_dir(root) -> tuple[list[str], list[tuple[Path, int]]]: """Quét ảnh; nhãn lấy từ TÊN THƯ MỤC, tên file ảnh không quan trọng. vehicle// -> nhãn = (car, bus...) creature//// -> nhãn = _ vd creature/other animals/human/boy/ -> human_boy creature/other animals/dog/female/ -> dog_female creature/// (không có thư mục con giới tính) -> nhãn = Thư mục bắt đầu bằng '.' hoặc '_' (vd _unsorted: ảnh chưa phân loại) bị bỏ qua. """ root = Path(root) if not root.exists(): return [], [] classes: list[tuple[str, Path]] = [] for group in _visible_dirs(root): children = _visible_dirs(group) if group.name in ("creature", "animal"): for kind in children: # vd "other animals" for species in _visible_dirs(kind): subs = _visible_dirs(species) if subs: classes.extend((f"{species.name}_{s.name}", s) for s in subs) else: classes.append((species.name, species)) elif group.name == "vehicle" and children: classes.extend((child.name, child) for child in children) else: # Giữ các nhãn cấp đầu khác (vd "hello") kể cả khi có thư mục con. classes.append((group.name, group)) items: list[tuple[Path, int]] = [] kept_labels: list[str] = [] for name, folder in sorted(classes, key=lambda item: item[0]): files = _images(folder) if not files: continue # thư mục rỗng -> bỏ, tránh nhãn không có dữ liệu idx = len(kept_labels) kept_labels.append(name) items.extend((f, idx) for f in files) return kept_labels, items def load_display_names(root) -> dict[str, str]: p = Path(root) / "labels.json" if p.exists(): try: return json.loads(p.read_text(encoding="utf-8")) except Exception: pass return {} _SEX_VI = {"male": "đực", "female": "cái", "boy": "nam", "girl": "nữ"} def pretty(label: str, names: dict[str, str] | None = None) -> str: """Tên thư mục -> tên đọc được. 'dog_female' -> 'chó cái', 'human_boy' -> 'người nam'.""" if names and label in names: return names[label] base, _, sex = label.rpartition("_") if base and sex in _SEX_VI: return f"{pretty(base, names)} {_SEX_VI[sex]}" return label.replace("_", " ").replace("-", " ") class PictureDataset: """Dữ liệu ảnh -> (tensor ảnh, id nhãn). Chia train/val theo từng nhãn. Không tải hết ảnh vào RAM: chỉ giữ đường dẫn, đọc ảnh khi cần (an toàn khi số ảnh lớn). """ def __init__(self, root, img_size: int = 224, val_ratio: float = 0.1, seed: int = 1337): self.root = Path(root) self.img_size = img_size self.labels, items = scan_picture_dir(self.root) self.names = load_display_names(self.root) rng = random.Random(seed) by_label: dict[int, list[Path]] = {} for path, idx in items: by_label.setdefault(idx, []).append(path) self.train: list[tuple[Path, int]] = [] self.val: list[tuple[Path, int]] = [] for idx, paths in by_label.items(): paths = paths[:] rng.shuffle(paths) # Mỗi nhãn giữ ít nhất 1 ảnh cho train; chỉ tách val khi có >= 5 ảnh n_val = int(len(paths) * val_ratio) if len(paths) >= 5 else 0 self.val.extend((p, idx) for p in paths[:n_val]) self.train.extend((p, idx) for p in paths[n_val:]) def __len__(self) -> int: return len(self.train) @property def num_labels(self) -> int: return len(self.labels) def display(self, idx: int) -> str: return pretty(self.labels[idx], self.names) def batch(self, batch_size: int, split: str = "train", augment: bool = True): pool = self.train if split == "train" else self.val picks = random.choices(pool, k=batch_size) imgs = torch.stack([load_image(p, self.img_size, augment=augment and split == "train") for p, _ in picks]) ids = torch.tensor([i for _, i in picks], dtype=torch.long) return imgs, ids # --------------------------------------------------------------------------- # Bộ mã hóa ảnh (ViT nhỏ) # --------------------------------------------------------------------------- class ImageEncoder(nn.Module): """Ảnh [B,3,S,S] -> [B, n_img_tokens, n_embd]. patch -> Linear -> +pos -> TransformerEncoder -> gom về n_img_tokens bằng cross-attention với các "query" học được (kiểu Perceiver/Q-Former), nên số token ảnh nối vào GPT luôn cố định dù ảnh to hay nhỏ. """ def __init__( self, n_embd: int, img_size: int = 224, patch_size: int = 16, vit_dim: int = 384, vit_layers: int = 6, vit_heads: int = 6, n_img_tokens: int = 16, dropout: float = 0.0, ): super().__init__() assert img_size % patch_size == 0, "img_size phải chia hết cho patch_size" assert vit_dim % vit_heads == 0, "vit_dim phải chia hết cho vit_heads" self.img_size = img_size self.patch_size = patch_size self.n_img_tokens = n_img_tokens n_patches = (img_size // patch_size) ** 2 self.patch = nn.Conv2d(3, vit_dim, kernel_size=patch_size, stride=patch_size) self.cls = nn.Parameter(torch.zeros(1, 1, vit_dim)) self.pos = nn.Parameter(torch.zeros(1, n_patches + 1, vit_dim)) layer = nn.TransformerEncoderLayer( d_model=vit_dim, nhead=vit_heads, dim_feedforward=4 * vit_dim, dropout=dropout, batch_first=True, activation="gelu", norm_first=True, ) self.blocks = nn.TransformerEncoder(layer, num_layers=vit_layers) self.norm = nn.LayerNorm(vit_dim) # Gom về n_img_tokens: query học được (n_embd) nhìn vào toàn bộ patch self.queries = nn.Parameter(torch.zeros(1, n_img_tokens, n_embd)) self.kv_proj = nn.Linear(vit_dim, n_embd) self.pool = nn.MultiheadAttention(n_embd, num_heads=8 if n_embd % 8 == 0 else 1, batch_first=True) self.out_norm = nn.LayerNorm(n_embd) nn.init.normal_(self.cls, std=0.02) nn.init.normal_(self.pos, std=0.02) nn.init.normal_(self.queries, std=0.02) def forward(self, images: torch.Tensor) -> torch.Tensor: x = self.patch(images) # [B, D, H/p, W/p] x = x.flatten(2).transpose(1, 2) # [B, N, D] cls = self.cls.expand(x.size(0), -1, -1) x = torch.cat([cls, x], dim=1) + self.pos x = self.norm(self.blocks(x)) # [B, N+1, D] kv = self.kv_proj(x) # [B, N+1, n_embd] q = self.queries.expand(x.size(0), -1, -1) out, _ = self.pool(q, kv, kv, need_weights=False) return self.out_norm(out) # [B, n_img_tokens, n_embd] # --------------------------------------------------------------------------- # Sinh mẫu hội thoại từ ảnh (dùng chung cho train.py và chat.py) # --------------------------------------------------------------------------- QUESTIONS = [ "Đây là gì?", "Trong ảnh là gì vậy?", "Hãy cho biết ảnh này là gì.", "Ảnh này thể hiện điều gì?", "Bạn nhìn thấy gì trong ảnh?", "Nhận diện giúp tôi ảnh này.", ] def make_image_turn(question: str, label_text: str) -> str: """Đúng khuôn GromGPT (xem data/README.md): nghĩ rồi trả lời.""" return ( f"Người dùng: {question}\n" f"{AI_NAME}:\n" f"\n" f"Người dùng gửi kèm một ảnh và hỏi nội dung ảnh. Nhìn đặc điểm hình ảnh " f"thì đây là {label_text}.\n" f"\n" f"\n" f"Đây là {label_text}.\n" f"\n" ) def image_prompt(question: str) -> str: """Phần prompt (không có câu trả lời) — dùng khi suy luận trong chat.py.""" return f"Người dùng: {question}\n{AI_NAME}:"