Feature Extraction
sentence-transformers
PyTorch
Chinese
tiny_custom_embed
sentence-similarity
text-embeddings-inference
mteb
chinese
tiny
Instructions to use dynasty-ai/tiny-embed-61m with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- sentence-transformers
How to use dynasty-ai/tiny-embed-61m with sentence-transformers:
from sentence_transformers import SentenceTransformer model = SentenceTransformer("dynasty-ai/tiny-embed-61m") sentences = [ "The weather is lovely today.", "It's so sunny outside!", "He drove to the stadium." ] embeddings = model.encode(sentences) similarities = model.similarity(embeddings, embeddings) print(similarities.shape) # [3, 3] - Notebooks
- Google Colab
- Kaggle
Download tiny_st_module.py from dynasty-ai/tiny-embed-61m: direct link, hf CLI and curl.
- Browser
- Download file 7.75 kB
-
https://huggingface.co/dynasty-ai/tiny-embed-61m/resolve/main/tiny_st_module.py
- Command line
-
hf download hf://dynasty-ai/tiny-embed-61m/tiny_st_module.py
-
curl -L -o tiny_st_module.py https://huggingface.co/dynasty-ai/tiny-embed-61m/resolve/main/tiny_st_module.py
7.75 kB
| # -*- coding: utf-8 -*- | |
| """TinyCustomEmbed 的 sentence-transformers 自包含模块(由 export_sentence_transformers.py 生成)。""" | |
| from __future__ import annotations | |
| import json | |
| import os | |
| import torch | |
| from torch import nn | |
| class RMSNorm(nn.Module): | |
| def __init__(self, hidden_size: int, eps: float = 1e-6): | |
| super().__init__() | |
| self.weight = nn.Parameter(torch.ones(hidden_size)) | |
| self.eps = eps | |
| def forward(self, x): | |
| rms = x.float().pow(2).mean(-1, keepdim=True) | |
| return (x * torch.rsqrt(rms + self.eps)).to(x.dtype) * self.weight | |
| class RotaryEmbedding(nn.Module): | |
| def __init__(self, dim: int, theta: float = 10000.0): | |
| super().__init__() | |
| inv_freq = 1.0 / (theta ** (torch.arange(0, dim, 2).float() / dim)) | |
| self.register_buffer("inv_freq", inv_freq, persistent=False) | |
| def forward(self, seq_len, device, dtype): | |
| t = torch.arange(seq_len, device=device, dtype=self.inv_freq.dtype) | |
| freqs = torch.outer(t, self.inv_freq) | |
| return freqs.cos().to(dtype), freqs.sin().to(dtype) | |
| def _rotate_half(x): | |
| x1, x2 = x.chunk(2, dim=-1) | |
| return torch.cat((-x2, x1), dim=-1) | |
| def _apply_rope(x, cos, sin): | |
| seq_len = x.shape[-3] | |
| cos = cos[:seq_len].unsqueeze(0).unsqueeze(2) | |
| sin = sin[:seq_len].unsqueeze(0).unsqueeze(2) | |
| return x * cos + _rotate_half(x) * sin | |
| class _Attn(nn.Module): | |
| def __init__(self, hidden, heads, window, qk_norm, full): | |
| super().__init__() | |
| self.heads, self.head_dim = heads, hidden // heads | |
| self.window, self.full = window, full | |
| self.q_proj = nn.Linear(hidden, hidden, bias=False) | |
| self.k_proj = nn.Linear(hidden, hidden, bias=False) | |
| self.v_proj = nn.Linear(hidden, hidden, bias=False) | |
| self.o_proj = nn.Linear(hidden, hidden, bias=False) | |
| self.q_norm = RMSNorm(self.head_dim) if qk_norm else None | |
| self.k_norm = RMSNorm(self.head_dim) if qk_norm else None | |
| def forward(self, x, cos, sin, pad_mask): | |
| B, L, _ = x.shape | |
| q = self.q_proj(x).view(B, L, self.heads, self.head_dim) | |
| k = self.k_proj(x).view(B, L, self.heads, self.head_dim) | |
| v = self.v_proj(x).view(B, L, self.heads, self.head_dim) | |
| if cos is not None: | |
| q, k = _apply_rope(q, cos, sin), _apply_rope(k, cos, sin) | |
| if self.q_norm is not None: | |
| q, k = self.q_norm(q), self.k_norm(k) | |
| qh, kh, vh = q.transpose(1, 2), k.transpose(1, 2), v.transpose(1, 2) | |
| use_win = (self.window > 0) and (not self.full) and L > self.window | |
| keep = pad_mask.bool()[:, None, :].expand(B, L, L).clone() | |
| if use_win: | |
| half = self.window // 2 | |
| idx = torch.arange(L, device=x.device) | |
| keep &= (idx[:, None] - idx[None, :]).abs().le(half)[None] | |
| pos = torch.arange(L, device=x.device) | |
| keep |= (pos[None, :] == pos[:, None])[None] | |
| out = torch.nn.functional.scaled_dot_product_attention(qh, kh, vh, | |
| attn_mask=keep[:, None]) | |
| return self.o_proj(out.transpose(1, 2).reshape(B, L, -1)) | |
| class _GeGLU(nn.Module): | |
| def __init__(self, hidden, inter, bias=False): | |
| super().__init__() | |
| self.gate_proj = nn.Linear(hidden, inter, bias=bias) | |
| self.up_proj = nn.Linear(hidden, inter, bias=bias) | |
| self.down_proj = nn.Linear(inter, hidden, bias=bias) | |
| def forward(self, x): | |
| return self.down_proj(torch.nn.functional.gelu(self.gate_proj(x)) * self.up_proj(x)) | |
| class _Layer(nn.Module): | |
| def __init__(self, hidden, inter, heads, window, qk_norm, full): | |
| super().__init__() | |
| self.pre_attn_norm, self.post_attn_norm = RMSNorm(hidden), RMSNorm(hidden) | |
| self.self_attn = _Attn(hidden, heads, window, qk_norm, full) | |
| self.ffn = _GeGLU(hidden, inter) | |
| def forward(self, x, cos, sin, pad_mask, is_global): | |
| x = x + self.self_attn(self.pre_attn_norm(x), cos, sin, pad_mask) # full/window 在 _Attn 构造时已定 | |
| return x + self.ffn(self.post_attn_norm(x)) | |
| class TinyEmbedTransformer(nn.Module): | |
| """ST Transformer 模块:加载 TinyCustomEmbed 权重并输出 token_embeddings。""" | |
| def __init__(self, model_path: str = ".", max_length: int = 512, **kwargs): | |
| super().__init__() | |
| with open(os.path.join(model_path, "config.json"), encoding="utf-8") as f: | |
| c = json.load(f) | |
| self.config = c | |
| H = c["hidden_size"] | |
| self.token_embedding = nn.Embedding(c["vocab_size"], H) | |
| # 只建 num_unique_layers 个真实层(与原模型 state_dict 一致), | |
| # forward 按 li % num_unique_layers 复用(权重共享语义) | |
| uniq = c["num_unique_layers"] | |
| self.num_unique_layers = uniq | |
| self.layers = nn.ModuleList([ | |
| _Layer(H, c["intermediate_size"], c["num_attention_heads"], | |
| c["sliding_window"], c.get("use_qk_norm", True), | |
| ui in (0, uniq - 1)) | |
| for ui in range(uniq)]) | |
| self.final_norm = RMSNorm(H) | |
| self.rope = (RotaryEmbedding(c["head_dim"] * 2, c.get("rope_theta", 10000.0)) | |
| if c.get("positional_encoding", "rope") == "rope" else None) | |
| self.position_embedding = (nn.Embedding(c["max_position_embeddings"], H) | |
| if c.get("positional_encoding") == "abs" else None) | |
| if self.position_embedding is not None and os.path.exists(os.path.join(model_path, "pytorch_model.bin")): | |
| pass # 权重统一由 load_state_dict 装载 | |
| # loop_embedding / pos_adapters / layer_gates 如存在则按 config 重建 | |
| self.loop_embedding = (nn.Embedding(c["effective_num_layers"], H) | |
| if c.get("loop_index_embedding") else None) | |
| r = c.get("pos_adapter_rank", 0) | |
| self.pos_adapters = None | |
| self._model_path = model_path | |
| self.max_seq_length = max_length | |
| from transformers import AutoTokenizer | |
| self.tokenizer = AutoTokenizer.from_pretrained(model_path) | |
| def tokenize(self, texts, **kwargs): | |
| return self.tokenizer(list(texts), padding=True, truncation=True, | |
| max_length=self.max_seq_length, return_tensors="pt", **kwargs) | |
| def forward(self, features): | |
| ids = features["input_ids"] | |
| am = features["attention_mask"] | |
| h = self.token_embedding(ids) | |
| if self.position_embedding is not None: | |
| h = h + self.position_embedding(torch.arange(ids.shape[1], device=ids.device)) | |
| cos = sin = None | |
| if self.rope is not None: | |
| cos, sin = self.rope(ids.shape[1], ids.device, h.dtype) | |
| uniq = self.num_unique_layers | |
| for li in range(self.config["effective_num_layers"]): | |
| if self.loop_embedding is not None: | |
| h = h + self.loop_embedding.weight[li].to(h.dtype) | |
| ui = li % uniq | |
| h = self.layers[ui](h, cos, sin, am, ui in (0, uniq - 1)) | |
| features["token_embeddings"] = self.final_norm(h) | |
| return features | |
| def save(self, output_path, *args, **kwargs): | |
| torch.save(self.state_dict(), os.path.join(output_path, "pytorch_model.bin")) | |
| def load(input_path): | |
| module = TinyEmbedTransformer(model_path=input_path) | |
| # ST 对远程代码模块不会自动装载权重,必须在 load() 里自己完成 | |
| state = torch.load(os.path.join(input_path, "pytorch_model.bin"), | |
| map_location="cpu") | |
| module.load_state_dict(state, strict=True) | |
| return module | |
| def get_word_embedding_dimension(self): | |
| return self.config["hidden_size"] | |