Download ppai/modeling_ppai_vl.py from AdminHugging/ppai-code: direct link, hf CLI and curl.
- Browser
- Download file 5.75 kB
-
https://huggingface.co/datasets/AdminHugging/ppai-code/resolve/main/ppai/modeling_ppai_vl.py
- Command line
-
hf download hf://datasets/AdminHugging/ppai-code/ppai/modeling_ppai_vl.py
-
curl -L -o modeling_ppai_vl.py https://huggingface.co/datasets/AdminHugging/ppai-code/resolve/main/ppai/modeling_ppai_vl.py
5.75 kB
| """PP-OSR-H (PacPerlar-OSR-Hydrogen) — модель, которая видит. | |
| Схема: ViT-энкодер картинки 128×128 → проектор → префикс из image-токенов, | |
| дальше обычный текстовый декодер PPAI. Loss считается только по токенам | |
| подписи, картинка маскируется (-100). | |
| Параметры: зрение ~7.3M + декодер ~43M ≈ 50M. | |
| """ | |
| from __future__ import annotations | |
| import torch | |
| import torch.nn as nn | |
| import torch.nn.functional as F | |
| from transformers.modeling_outputs import CausalLMOutputWithPast | |
| try: | |
| from .configuration_ppai import PPAIConfig | |
| from .modeling_ppai import PPAIForCausalLM, PPAIModel, PPAIPreTrainedModel | |
| except ImportError: | |
| from configuration_ppai import PPAIConfig | |
| from modeling_ppai import PPAIForCausalLM, PPAIModel, PPAIPreTrainedModel | |
| class ViTBlock(nn.Module): | |
| def __init__(self, d: int, heads: int, ffn: int, eps: float = 1e-6): | |
| super().__init__() | |
| self.ln1 = nn.LayerNorm(d, eps=eps) | |
| self.ln2 = nn.LayerNorm(d, eps=eps) | |
| self.wq = nn.Parameter(torch.empty(d, d)) | |
| self.wk = nn.Parameter(torch.empty(d, d)) | |
| self.wv = nn.Parameter(torch.empty(d, d)) | |
| self.wo = nn.Parameter(torch.empty(d, d)) | |
| self.w1 = nn.Parameter(torch.empty(ffn, d)) | |
| self.w2 = nn.Parameter(torch.empty(d, ffn)) | |
| self.heads = heads | |
| self.d = d | |
| def forward(self, x): | |
| B, N, d = x.shape | |
| h = self.heads | |
| hd = d // h | |
| a = self.ln1(x) | |
| q = F.linear(a, self.wq).reshape(B, N, h, hd).transpose(1, 2) | |
| k = F.linear(a, self.wk).reshape(B, N, h, hd).transpose(1, 2) | |
| v = F.linear(a, self.wv).reshape(B, N, h, hd).transpose(1, 2) | |
| o = F.scaled_dot_product_attention(q, k, v) | |
| o = o.transpose(1, 2).reshape(B, N, d) | |
| x = x + F.linear(o, self.wo) | |
| m = self.ln2(x) | |
| x = x + F.linear(F.gelu(F.linear(m, self.w1)), self.w2) | |
| return x | |
| class ImageEncoder(nn.Module): | |
| """Маленький ViT: патчи через свёртку, CLS-токен, позиционные эмбеддинги.""" | |
| def __init__(self, img_size: int = 128, patch: int = 8, d: int = 384, | |
| layers: int = 6, heads: int = 8, ffn: int = 1536): | |
| super().__init__() | |
| self.patch = patch | |
| self.n_patches = (img_size // patch) ** 2 | |
| self.proj = nn.Conv2d(3, d, kernel_size=patch, stride=patch) | |
| self.cls = nn.Parameter(torch.zeros(1, 1, d)) | |
| self.pos = nn.Parameter(torch.zeros(1, self.n_patches + 1, d)) | |
| self.blocks = nn.ModuleList(ViTBlock(d, heads, ffn) for _ in range(layers)) | |
| self.norm = nn.LayerNorm(d, eps=1e-6) | |
| self.d = d | |
| def forward(self, pixel_values: torch.Tensor) -> torch.Tensor: | |
| # pixel_values: (B, 3, H, W) в диапазоне [-1, 1] | |
| x = self.proj(pixel_values) # (B, d, h, w) | |
| x = x.flatten(2).transpose(1, 2) # (B, N, d) | |
| cls = self.cls.expand(x.shape[0], -1, -1) | |
| x = torch.cat([cls, x], dim=1) + self.pos | |
| for blk in self.blocks: | |
| x = blk(x) | |
| return self.norm(x) | |
| class PPAIVLForCausalLM(PPAIPreTrainedModel): | |
| """Текстовая PPAI + визуальный энкодер и проектор.""" | |
| def __init__(self, config: PPAIConfig): | |
| super().__init__(config) | |
| self.text = PPAIForCausalLM(config).model # сам декодер без LM-head обёртки | |
| self.vision = ImageEncoder( | |
| img_size=getattr(config, "image_size", 128), | |
| patch=getattr(config, "patch_size", 8), | |
| d=getattr(config, "vision_dim", 384), | |
| layers=getattr(config, "vision_layers", 6), | |
| heads=getattr(config, "vision_heads", 8), | |
| ffn=getattr(config, "vision_ffn", 1536), | |
| ) | |
| self.proj = nn.Linear(self.vision.d, config.d_model) | |
| self.image_size = getattr(config, "image_size", 128) | |
| self.post_init() | |
| def get_input_embeddings(self): | |
| return self.text.tok_emb | |
| def forward(self, input_ids=None, pixel_values=None, labels=None, attention_mask=None, | |
| past_key_values=None, use_cache=None, return_dict=None, **kwargs): | |
| use_cache = self.config.use_cache if use_cache is None else use_cache | |
| device = input_ids.device | |
| text_emb = self.text.tok_emb(input_ids).float() | |
| if pixel_values is not None: | |
| img = self.vision(pixel_values.to(device)) | |
| img_emb = self.proj(img) | |
| embeds = torch.cat([img_emb, text_emb], dim=1) | |
| n_img = img_emb.shape[1] | |
| else: | |
| embeds = text_emb | |
| n_img = 0 | |
| dt = torch.bfloat16 if device.type == "xla" else ( | |
| torch.bfloat16 if device.type == "cuda" and torch.cuda.get_device_capability(device)[0] >= 8 | |
| else torch.float16 if device.type == "cuda" else torch.float32) | |
| h, pkv = self.text(input_ids=None, inputs_embeds=embeds.to(dt), use_cache=use_cache) | |
| if n_img: | |
| h = h[:, n_img:] | |
| logits = F.linear(h, self.text.tok_emb.weight.to(h.dtype)).float() | |
| cap = self.config.logit_softcap | |
| if cap and cap > 0: | |
| logits = cap * torch.tanh(logits / cap) | |
| loss = None | |
| if labels is not None: | |
| loss = F.cross_entropy(logits[:, :-1].reshape(-1, logits.shape[-1]), | |
| labels[:, 1:].reshape(-1), ignore_index=-100) | |
| return CausalLMOutputWithPast(loss=loss, logits=logits, | |
| past_key_values=pkv if use_cache else None) | |