Download conversion/coreml_model.py from helmo/DecidaBERT-large-v2-coreml: direct link, hf CLI and curl.
- Browser
- Download file 5.13 kB
-
https://huggingface.co/helmo/DecidaBERT-large-v2-coreml/resolve/main/conversion/coreml_model.py
- Command line
-
hf download hf://helmo/DecidaBERT-large-v2-coreml/conversion/coreml_model.py
-
curl -L -o coreml_model.py https://huggingface.co/helmo/DecidaBERT-large-v2-coreml/resolve/main/conversion/coreml_model.py
5.13 kB
| """A fixed-length, traceable DecidaBERT for Core ML: token ids + attention mask in, the three head logits at every | |
| position out ([1, 3, L]: noul, choice, score). Swift reads the marker positions from that. | |
| It reuses the trained modules of the Hugging Face ModernBERT encoder and only replaces how attention is laid out: | |
| - full-attention layers call scaled_dot_product_attention with a key-padding mask (Core ML has a native SDPA op); | |
| - sliding layers (window |i - j| <= 64) attend block-wise: each 128-token block sees its previous, own and next block | |
| (384 keys). That is exact for a +-64 window and avoids an L x L band mask, which at 8,192 tokens would be a 128 MB | |
| constant per bucket and quadratic work. | |
| Masked scores use a finite -1e4 rather than -inf so a row with no visible key (a padding query in a padding-only | |
| window) gives a uniform softmax instead of NaN; NaN values would otherwise leak into real rows through 0 * NaN. | |
| """ | |
| from __future__ import annotations | |
| import torch | |
| import torch.nn.functional as F | |
| from torch import nn | |
| NEG = -1e4 | |
| BLOCK = 128 | |
| def _rope(x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor, h: int) -> torch.Tensor: | |
| # h (half the head size) is passed as a Python int: x.shape[-1] would be traced as a shape op Core ML rejects | |
| return x * cos + torch.cat((-x[..., h:], x[..., :h]), dim=-1) * sin | |
| class FixedLengthDecida(nn.Module): | |
| def __init__(self, model, length: int): | |
| """`model` is a loaded DecidaBERTv2 (reference inference code); `length` is the bucket, a multiple of 128.""" | |
| super().__init__() | |
| assert length % BLOCK == 0 | |
| enc = model.encoder | |
| cfg = enc.config | |
| self.length, self.heads, self.dim = length, cfg.num_attention_heads, cfg.hidden_size // cfg.num_attention_heads | |
| self.window = cfg.sliding_window # 64: half of local_attention | |
| self.embeddings, self.layers, self.final_norm = enc.embeddings, enc.layers, enc.final_norm | |
| self.noul_head, self.choice_head, self.score_head = model.noul_head, model.choice_head, model.score_head | |
| pos = torch.arange(length).unsqueeze(0) | |
| x = torch.zeros(1, length, cfg.hidden_size) | |
| for kind in ("full_attention", "sliding_attention"): | |
| cos, sin = enc.rotary_emb(x, pos, kind) # [1, L, dim] | |
| self.register_buffer(f"{kind}_cos", cos[:, None], persistent=False) | |
| self.register_buffer(f"{kind}_sin", sin[:, None], persistent=False) | |
| # Band inside a block's 384-key window: query offset a (0..127) sees key c (block start - 128 + c) when | |
| # |a - (c - 128)| <= window. Small constant, shared by every block. | |
| a = torch.arange(BLOCK)[:, None] | |
| c = torch.arange(3 * BLOCK)[None, :] - BLOCK | |
| self.register_buffer("band", torch.where((a - c).abs() <= self.window, 0.0, NEG), persistent=False) | |
| def _qkv(self, layer, h: torch.Tensor, kind: str): | |
| qkv = layer.attn.Wqkv(h).view(1, self.length, 3, self.heads, self.dim) | |
| q, k, v = (t.transpose(1, 2) for t in qkv.unbind(dim=2)) # [1, H, L, D] | |
| cos, sin = getattr(self, f"{kind}_cos"), getattr(self, f"{kind}_sin") | |
| return _rope(q, cos, sin, self.dim // 2), _rope(k, cos, sin, self.dim // 2), v | |
| def _full(self, q, k, v, key_mask): | |
| return F.scaled_dot_product_attention(q, k, v, attn_mask=key_mask[:, None, None, :]) # [1, H, L, D] | |
| def _sliding(self, q, k, v, key_mask): | |
| nb, H, D = self.length // BLOCK, self.heads, self.dim | |
| def windows(t): # [1, H, L, D] -> [nb, H, 384, D]: previous, own and next block of keys | |
| b = t.reshape(H, nb, BLOCK, D).transpose(0, 1) # [nb, H, 128, D] | |
| z = torch.zeros_like(b[:1]) | |
| return torch.cat((torch.cat((z, b[:-1])), b, torch.cat((b[1:], z))), dim=2) | |
| qb = q.reshape(H, nb, BLOCK, D).transpose(0, 1) | |
| mb = key_mask.view(nb, BLOCK) | |
| edge = torch.full_like(mb[:1], NEG) # keys before the start / after the end do not exist | |
| mw = torch.cat((torch.cat((edge, mb[:-1])), mb, torch.cat((mb[1:], edge))), dim=1) # [nb, 384] | |
| mask = self.band[None, None] + mw[:, None, None, :] # [nb, 1, 128, 384] | |
| o = F.scaled_dot_product_attention(qb, windows(k), windows(v), attn_mask=mask) # [nb, H, 128, D] | |
| return o.transpose(0, 1).reshape(1, H, self.length, D) | |
| def forward(self, input_ids: torch.Tensor, attention_mask: torch.Tensor) -> torch.Tensor: | |
| key_mask = (1.0 - attention_mask.float()) * NEG # [1, L]: 0 for real tokens, -1e4 for padding | |
| h = self.embeddings(input_ids=input_ids) | |
| for layer in self.layers: | |
| kind = layer.attention_type | |
| q, k, v = self._qkv(layer, layer.attn_norm(h), kind) | |
| o = (self._full if kind == "full_attention" else self._sliding)(q, k, v, key_mask) | |
| h = h + layer.attn.Wo(o.transpose(1, 2).reshape(1, self.length, -1)) | |
| h = h + layer.mlp(layer.mlp_norm(h)) | |
| h = self.final_norm(h) | |
| logits = torch.cat([hd(h) for hd in (self.noul_head, self.choice_head, self.score_head)], dim=-1) # [1, L, 3] | |
| return logits.transpose(1, 2) | |