Instructions to use khanhnd61/pop-so101 with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- LeRobot
How to use khanhnd61/pop-so101 with LeRobot:
# No code snippets available yet for this library. # To use this model, check the repository files and the library's documentation. # Want to help? PRs adding snippets are welcome at: # https://github.com/huggingface/huggingface.js
- Notebooks
- Google Colab
- Kaggle
Download code/popt/t5.py from khanhnd61/pop-so101: direct link, hf CLI and curl.
- Browser
- Download file 7.1 kB
-
https://huggingface.co/khanhnd61/pop-so101/resolve/main/code/popt/t5.py
- Command line
-
hf download hf://khanhnd61/pop-so101/code/popt/t5.py
-
curl -L -o t5.py https://huggingface.co/khanhnd61/pop-so101/resolve/main/code/popt/t5.py
7.1 kB
| """T5-Efficient-Tiny encoder in plain PyTorch, and its sentencepiece tokenizer. | |
| The text encoder of the sentence-embedding and OTTER-style baselines (PLAN.md section 5, interfaces 2 and 3) and, | |
| from V3, of PoP's parser. Written out here because transformers releases that run on the pinned torch 2.5.1 need an | |
| older huggingface_hub than the one installed. Matches transformers' T5EncoderModel (relu feed-forward, relative | |
| position bias computed in the first block and shared, RMS layer norm, unscaled attention); checked against it by | |
| scripts/check_t5.py. Parameter names follow the Hugging Face checkpoint, so pytorch_model.bin loads directly. | |
| Weights: google/t5-efficient-tiny at revision 3441d7e8bf3f89841f366d39452b95200416e4a9, in data/weights/t5_efficient_tiny. | |
| """ | |
| from __future__ import annotations | |
| import json | |
| import math | |
| import os | |
| import torch | |
| import torch.nn as nn | |
| import torch.nn.functional as F | |
| # Copied from the PoP repository (pop/model/t5.py at 5be9239); only this default path differs. | |
| T5_DIR = os.environ.get("POPT_T5_DIR", "") | |
| T5_REVISION = "3441d7e8bf3f89841f366d39452b95200416e4a9" | |
| class RMSNorm(nn.Module): | |
| def __init__(self, d: int, eps: float): | |
| super().__init__() | |
| self.weight = nn.Parameter(torch.ones(d)) | |
| self.eps = eps | |
| def forward(self, x): | |
| var = x.float().pow(2).mean(-1, keepdim=True) | |
| return (x.float() * torch.rsqrt(var + self.eps)).to(x.dtype) * self.weight.to(x.dtype) | |
| class SelfAttention(nn.Module): | |
| def __init__(self, d: int, heads: int, d_kv: int, bias: bool, buckets: int, p: float): | |
| super().__init__() | |
| inner = heads * d_kv | |
| self.p = p | |
| self.q, self.k, self.v = (nn.Linear(d, inner, bias=False) for _ in range(3)) | |
| self.o = nn.Linear(inner, d, bias=False) | |
| self.heads, self.d_kv, self.buckets = heads, d_kv, buckets | |
| if bias: | |
| self.relative_attention_bias = nn.Embedding(buckets, heads) | |
| def bucket(rel: torch.Tensor, num_buckets: int, max_distance: int = 128) -> torch.Tensor: | |
| """Bidirectional relative-position buckets (transformers T5Attention._relative_position_bucket).""" | |
| num_buckets //= 2 | |
| out = (rel > 0).long() * num_buckets | |
| rel = rel.abs() | |
| max_exact = num_buckets // 2 | |
| large = max_exact + (torch.log(rel.float() / max_exact) / math.log(max_distance / max_exact) | |
| * (num_buckets - max_exact)).long() | |
| large = large.clamp(max=num_buckets - 1) | |
| return out + torch.where(rel < max_exact, rel, large) | |
| def position_bias(self, L: int, device) -> torch.Tensor: | |
| pos = torch.arange(L, device=device) | |
| rel = pos[None, :] - pos[:, None] # key position - query position | |
| return self.relative_attention_bias(self.bucket(rel, self.buckets)).permute(2, 0, 1)[None] # (1, H, L, L) | |
| def forward(self, x, bias): | |
| B, L, _ = x.shape | |
| sh = lambda t: t.view(B, L, self.heads, self.d_kv).transpose(1, 2) | |
| q, k, v = sh(self.q(x)), sh(self.k(x)), sh(self.v(x)) | |
| s = torch.matmul(q.float(), k.float().transpose(-1, -2)) + bias # T5 does not scale by sqrt(d_kv) | |
| a = F.dropout(s.softmax(-1), self.p, self.training).to(v.dtype) | |
| return self.o(torch.matmul(a, v).transpose(1, 2).reshape(B, L, -1)) | |
| class AttnLayer(nn.Module): | |
| def __init__(self, cfg, bias: bool): | |
| super().__init__() | |
| self.SelfAttention = SelfAttention(cfg["d_model"], cfg["num_heads"], cfg["d_kv"], bias, | |
| cfg["relative_attention_num_buckets"], cfg["dropout_rate"]) | |
| self.layer_norm = RMSNorm(cfg["d_model"], cfg["layer_norm_epsilon"]) | |
| class DenseReluDense(nn.Module): | |
| def __init__(self, d: int, ff: int, p: float): | |
| super().__init__() | |
| self.wi = nn.Linear(d, ff, bias=False) | |
| self.wo = nn.Linear(ff, d, bias=False) | |
| self.drop = nn.Dropout(p) | |
| def forward(self, x): | |
| return self.wo(self.drop(F.relu(self.wi(x)))) | |
| class FFLayer(nn.Module): | |
| def __init__(self, cfg): | |
| super().__init__() | |
| self.DenseReluDense = DenseReluDense(cfg["d_model"], cfg["d_ff"], cfg["dropout_rate"]) | |
| self.layer_norm = RMSNorm(cfg["d_model"], cfg["layer_norm_epsilon"]) | |
| class Block(nn.Module): | |
| def __init__(self, cfg, bias: bool): | |
| super().__init__() | |
| self.layer = nn.ModuleList([AttnLayer(cfg, bias), FFLayer(cfg)]) | |
| self.drop = nn.Dropout(cfg["dropout_rate"]) | |
| def forward(self, x, bias): | |
| a, f = self.layer | |
| x = x + self.drop(a.SelfAttention(a.layer_norm(x), bias)) | |
| return x + self.drop(f.DenseReluDense(f.layer_norm(x))) | |
| class T5Encoder(nn.Module): | |
| """Token ids (B, L) and attention mask (B, L, bool) -> per-token features (B, L, 256).""" | |
| def __init__(self, pretrained: bool = True, root: str = T5_DIR, dropout: float | None = None): | |
| super().__init__() | |
| cfg = json.load(open(os.path.join(root, "config.json"))) | |
| assert cfg["feed_forward_proj"] == "relu", cfg["feed_forward_proj"] | |
| if dropout is not None: | |
| cfg["dropout_rate"] = dropout | |
| self.dim = cfg["d_model"] | |
| self.embed_tokens = nn.Embedding(cfg["vocab_size"], cfg["d_model"]) | |
| self.block = nn.ModuleList([Block(cfg, bias=(i == 0)) for i in range(cfg["num_layers"])]) | |
| self.final_layer_norm = RMSNorm(cfg["d_model"], cfg["layer_norm_epsilon"]) | |
| self.drop = nn.Dropout(cfg["dropout_rate"]) | |
| if pretrained: | |
| sd = torch.load(os.path.join(root, "pytorch_model.bin"), map_location="cpu", weights_only=True) | |
| enc = {k[len("encoder."):]: v for k, v in sd.items() if k.startswith("encoder.")} | |
| enc["embed_tokens.weight"] = sd["shared.weight"] # tied input embedding | |
| missing, unexpected = self.load_state_dict(enc, strict=False) | |
| assert not missing and not unexpected, (missing, unexpected) | |
| def forward(self, ids, mask): | |
| x = self.drop(self.embed_tokens(ids)) | |
| L = ids.shape[1] | |
| bias = self.block[0].layer[0].SelfAttention.position_bias(L, ids.device).float() | |
| bias = bias + (~mask)[:, None, None, :].float() * torch.finfo(torch.float32).min | |
| for blk in self.block: | |
| x = blk(x, bias) | |
| return self.drop(self.final_layer_norm(x)) | |
| class Tokenizer: | |
| """sentencepiece T5 tokenizer: pieces + end-of-sequence (id 1); padding id 0.""" | |
| EOS, PAD = 1, 0 | |
| def __init__(self, root: str = T5_DIR): | |
| import sentencepiece as spm | |
| self.sp = spm.SentencePieceProcessor(model_file=os.path.join(root, "spiece.model")) | |
| def encode(self, text: str) -> list[int]: | |
| return self.sp.encode(text.strip()) + [self.EOS] | |
| def batch(self, texts: list[str]) -> tuple[torch.Tensor, torch.Tensor]: | |
| seqs = [self.encode(t) for t in texts] | |
| L = max(len(s) for s in seqs) | |
| ids = torch.full((len(seqs), L), self.PAD, dtype=torch.long) | |
| for i, s in enumerate(seqs): | |
| ids[i, :len(s)] = torch.tensor(s) | |
| return ids, ids != self.PAD | |