Publish validated AMOS Core AI conversion with source provenance and runtime adapter
0415692 verified Download serve/amos/vision.py from maxffarrell/amos-1-medium-CoreAI: direct link, hf CLI and curl.
- Browser
- Download file 6.63 kB
-
https://huggingface.co/maxffarrell/amos-1-medium-CoreAI/resolve/main/serve/amos/vision.py
- Command line
-
hf download hf://maxffarrell/amos-1-medium-CoreAI/serve/amos/vision.py
-
curl -L -o vision.py https://huggingface.co/maxffarrell/amos-1-medium-CoreAI/resolve/main/serve/amos/vision.py
6.63 kB
| """SigLIP-architecture vision tower written from scratch (loads SigLIP 2 weights), plus the projector. | |
| An image becomes 14 x 14 patch vectors; the projector merges each 2 x 2 block (4x fewer tokens) and maps | |
| it into the text encoder's embedding space with a 2-layer MLP, giving 49 image tokens. | |
| """ | |
| import json | |
| import torch | |
| import torch.nn.functional as F | |
| from huggingface_hub import hf_hub_download | |
| from safetensors.torch import load_file | |
| from torch import nn | |
| IMAGE_SIZE, PATCH, GRID = 224, 16, 14 | |
| MERGED = (GRID // 2) ** 2 # image tokens per image after 2 x 2 merging | |
| def preprocess(image) -> torch.Tensor: | |
| """PIL image -> [3, 224, 224] in [-1, 1] (bilinear resize, as SigLIP's processor does).""" | |
| from PIL import Image | |
| image = image.convert("RGB").resize((IMAGE_SIZE, IMAGE_SIZE), Image.Resampling.BILINEAR) | |
| x = torch.frombuffer(bytearray(image.tobytes()), dtype=torch.uint8).view(IMAGE_SIZE, IMAGE_SIZE, 3) | |
| return x.permute(2, 0, 1).float() / 127.5 - 1 | |
| class Block(nn.Module): | |
| def __init__(self, d, heads, ff, eps): | |
| super().__init__() | |
| self.heads = heads | |
| self.layer_norm1, self.layer_norm2 = nn.LayerNorm(d, eps=eps), nn.LayerNorm(d, eps=eps) | |
| self.q_proj, self.k_proj, self.v_proj, self.out_proj = (nn.Linear(d, d) for _ in range(4)) | |
| self.fc1, self.fc2 = nn.Linear(d, ff), nn.Linear(ff, d) | |
| def forward(self, x): | |
| B, N, d = x.shape | |
| h = self.layer_norm1(x) | |
| q, k, v = (p(h).view(B, N, self.heads, -1).transpose(1, 2) for p in (self.q_proj, self.k_proj, self.v_proj)) | |
| x = x + self.out_proj(F.scaled_dot_product_attention(q, k, v).transpose(1, 2).reshape(B, N, d)) | |
| return x + self.fc2(F.gelu(self.fc1(self.layer_norm2(x)), approximate="tanh")) | |
| class VisionTower(nn.Module): | |
| def __init__(self, d=768, layers=12, heads=12, ff=3072, eps=1e-6): | |
| super().__init__() | |
| self.patch_embedding = nn.Conv2d(3, d, PATCH, PATCH) | |
| self.position_embedding = nn.Parameter(torch.zeros(GRID * GRID, d)) | |
| self.blocks = nn.ModuleList(Block(d, heads, ff, eps) for _ in range(layers)) | |
| self.post_layernorm = nn.LayerNorm(d, eps=eps) | |
| self.hidden_size = d | |
| def forward(self, pixels): # [B, 3, 224, 224] -> [B, 196, d] | |
| # cuDNN disabled: its runtime-compiled engines fail to load on some CUDA hosts. The one conv is a cheap patchify. | |
| from torch.nn.attention import SDPBackend, sdpa_kernel | |
| with torch.backends.cudnn.flags(enabled=False), sdpa_kernel([SDPBackend.FLASH_ATTENTION, SDPBackend.EFFICIENT_ATTENTION, SDPBackend.MATH]): | |
| x = self.patch_embedding(pixels).flatten(2).transpose(1, 2) + self.position_embedding | |
| for b in self.blocks: | |
| x = b(x) | |
| return self.post_layernorm(x) | |
| def from_pretrained(cls, repo: str) -> "VisionTower": | |
| with open(hf_hub_download(repo, "config.json")) as f: | |
| vc = json.load(f).get("vision_config", {}) | |
| m = cls(vc.get("hidden_size", 768), vc.get("num_hidden_layers", 12), vc.get("num_attention_heads", 12), | |
| vc.get("intermediate_size", 3072), vc.get("layer_norm_eps", 1e-6)) | |
| sd = {} | |
| for k, v in load_file(hf_hub_download(repo, "model.safetensors")).items(): | |
| if not k.startswith("vision_model.") or ".head." in k: | |
| continue | |
| k = k.removeprefix("vision_model.").replace("embeddings.", "").replace("encoder.layers.", "blocks.") | |
| k = k.replace("self_attn.", "").replace("mlp.", "") | |
| sd["position_embedding" if k == "position_embedding.weight" else k] = v | |
| m.load_state_dict(sd, strict=True) | |
| return m.eval().requires_grad_(False) | |
| class Projector(nn.Module): | |
| """2 x 2 patch merge (concatenate neighbours) + 2-layer MLP into the text embedding space.""" | |
| def __init__(self, d_vision: int, d_text: int): | |
| super().__init__() | |
| self.fc1, self.fc2 = nn.Linear(4 * d_vision, d_text), nn.Linear(d_text, d_text) | |
| def forward(self, feats): # [N, 196, dv] -> [N, 49, dt] | |
| N, _, dv = feats.shape | |
| g = GRID // 2 | |
| x = feats.view(N, g, 2, g, 2, dv).permute(0, 1, 3, 2, 4, 5).reshape(N, g * g, 4 * dv) | |
| return self.fc2(F.gelu(self.fc1(x))) | |
| def cell_boxes(rows: int = GRID // 2, cols: int = GRID // 2) -> torch.Tensor: | |
| """[rows * cols, 4] normalized (x0, y0, x1, y1) of each merged image token, row-major (49 by default).""" | |
| i = torch.arange(rows * cols) | |
| r, c = i // cols, i % cols | |
| return torch.stack([c / cols, r / rows, (c + 1) / cols, (r + 1) / rows], 1).float() | |
| def box_target(box, rows: int = GRID // 2, cols: int = GRID // 2) -> torch.Tensor: | |
| """Distribution over the cells proportional to overlap with a normalized box (x0, y0, x1, y1).""" | |
| cells, (x0, y0, x1, y1) = cell_boxes(rows, cols), box | |
| w = (cells[:, 2].clamp(max=x1) - cells[:, 0].clamp(min=x0)).clamp(min=0) | |
| h = (cells[:, 3].clamp(max=y1) - cells[:, 1].clamp(min=y0)).clamp(min=0) | |
| area = w * h | |
| return area / area.sum() if area.sum() > 0 else torch.full((len(cells),), 1 / len(cells)) | |
| def peak_box(p: torch.Tensor, rows: int, cols: int, keep: float) -> tuple[list[float], float]: | |
| """Box around the most likely cell and the cells 4-connected to it that hold at least `keep` of its probability -> | |
| (normalized (x0, y0, x1, y1), probability inside the box). keep=1 is (about) the most likely cell alone.""" | |
| g = p.view(rows, cols) | |
| r, c = divmod(int(p.argmax()), cols) | |
| on, seen, todo = (g >= keep * g[r, c]).tolist(), {(r, c)}, [(r, c)] | |
| while todo: | |
| i, j = todo.pop() | |
| for y, x in ((i + 1, j), (i - 1, j), (i, j + 1), (i, j - 1)): | |
| if 0 <= y < rows and 0 <= x < cols and on[y][x] and (y, x) not in seen: | |
| seen.add((y, x)) | |
| todo.append((y, x)) | |
| r0, r1 = min(y for y, _ in seen), max(y for y, _ in seen) + 1 | |
| c0, c1 = min(x for _, x in seen), max(x for _, x in seen) + 1 | |
| return [c0 / cols, r0 / rows, c1 / cols, r1 / rows], float(g[r0:r1, c0:c1].sum()) | |
| def box_scores(box, gold) -> tuple[bool, float]: | |
| """(the box's centre lies inside the gold box, intersection over union) of normalized (x0, y0, x1, y1) boxes.""" | |
| cx, cy = (box[0] + box[2]) / 2, (box[1] + box[3]) / 2 | |
| w = max(0.0, min(box[2], gold[2]) - max(box[0], gold[0])) | |
| h = max(0.0, min(box[3], gold[3]) - max(box[1], gold[1])) | |
| union = (box[2] - box[0]) * (box[3] - box[1]) + (gold[2] - gold[0]) * (gold[3] - gold[1]) - w * h | |
| return gold[0] <= cx <= gold[2] and gold[1] <= cy <= gold[3], w * h / union if union > 0 else 0.0 | |