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
add tiny-embed checkpoint (Apache-2.0, distilled)
Browse files- 1_Pooling/config.json +10 -0
- 2_Normalize/config.json +1 -0
- 3_Dense/config.json +6 -0
- 3_Dense/pytorch_model.bin +3 -0
- 4_Normalize/config.json +1 -0
- README.md +189 -0
- config.json +32 -0
- modules.json +32 -0
- pytorch_model.bin +3 -0
- special_tokens_map.json +37 -0
- tiny_st_module.py +178 -0
- tokenizer.json +0 -0
- tokenizer_config.json +58 -0
- vocab.txt +0 -0
1_Pooling/config.json
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"word_embedding_dimension": 512,
|
| 3 |
+
"pooling_mode": "mean",
|
| 4 |
+
"pooling_mode_cls_token": false,
|
| 5 |
+
"pooling_mode_mean_tokens": true,
|
| 6 |
+
"pooling_mode_max_tokens": false,
|
| 7 |
+
"pooling_mode_mean_sqrt_len_tokens": false,
|
| 8 |
+
"pooling_mode_weightedmean_tokens": false,
|
| 9 |
+
"pooling_mode_lasttoken": false
|
| 10 |
+
}
|
2_Normalize/config.json
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
{}
|
3_Dense/config.json
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"in_features": 512,
|
| 3 |
+
"out_features": 768,
|
| 4 |
+
"bias": false,
|
| 5 |
+
"activation_function": "torch.nn.modules.linear.Identity"
|
| 6 |
+
}
|
3_Dense/pytorch_model.bin
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:119a224a8f0bfdedd94588d111821401c0f8de9e6bcb6e6c713284ba16fc26e5
|
| 3 |
+
size 1574138
|
4_Normalize/config.json
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
{}
|
README.md
ADDED
|
@@ -0,0 +1,189 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
license: apache-2.0
|
| 3 |
+
language:
|
| 4 |
+
- zh
|
| 5 |
+
library_name: sentence-transformers
|
| 6 |
+
pipeline_tag: feature-extraction
|
| 7 |
+
tags:
|
| 8 |
+
- sentence-transformers
|
| 9 |
+
- feature-extraction
|
| 10 |
+
- sentence-similarity
|
| 11 |
+
- text-embeddings-inference
|
| 12 |
+
- mteb
|
| 13 |
+
- chinese
|
| 14 |
+
- tiny
|
| 15 |
+
---
|
| 16 |
+
|
| 17 |
+
# tiny-embed-61m
|
| 18 |
+
|
| 19 |
+
[Model Details](#model-details) | [Usage](#usage) | [Evaluation](#evaluation) | [Contact](#contact) | [License](#license)
|
| 20 |
+
|
| 21 |
+
`tiny-embed-61m` maps Chinese text to a low-dimensional dense vector which can be used for
|
| 22 |
+
tasks like retrieval, classification, clustering, or semantic search. It is a compact
|
| 23 |
+
(61.4M parameters, 768-dim) model distilled from larger open Chinese embedding models, and
|
| 24 |
+
it is designed to run cheaply on CPU or a single consumer GPU while keeping retrieval
|
| 25 |
+
quality close to `bge-base-zh-v1.5` (102M).
|
| 26 |
+
|
| 27 |
+
**No query instruction is required** — the model is trained and evaluated without any
|
| 28 |
+
prefix. Passages and queries both take the original text.
|
| 29 |
+
|
| 30 |
+
************* 🌟**Highlights**🌟 *************
|
| 31 |
+
|
| 32 |
+
- 61.4M parameters, **768-dim** output, 512 tokens max length.
|
| 33 |
+
- **0.6058** average on `MTEB(cmn, v1)` (31 tasks, no instruction), vs.
|
| 34 |
+
`bge-small-zh-v1.5` 0.5734 and `bge-base-zh-v1.5` 0.6270 measured on the same harness.
|
| 35 |
+
- Pure `sentence-transformers` pipeline: `Transformer → Pooling(mean) → Normalize → Dense(512→768) → Normalize`.
|
| 36 |
+
|
| 37 |
+
## Model Details
|
| 38 |
+
|
| 39 |
+
| Item | Value |
|
| 40 |
+
|---|---|
|
| 41 |
+
| Model type | Dense text embedding (bi-encoder) |
|
| 42 |
+
| Parameters | 61,425,664 (backbone) + 393,216 (projection head) |
|
| 43 |
+
| Embedding dimension | **768** |
|
| 44 |
+
| Backbone hidden size | 512 |
|
| 45 |
+
| Layers | 12 |
|
| 46 |
+
| Attention heads | 8 |
|
| 47 |
+
| Pooling | mean, then L2 normalize |
|
| 48 |
+
| Projection head | linear 512 → 768, bias-free, identity activation (part of the trained model, not a post-processing step) |
|
| 49 |
+
| Max sequence length | 512 |
|
| 50 |
+
| Tokenizer | Chinese BERT vocabulary (21,128 tokens) |
|
| 51 |
+
| Similarity | cosine (embeddings are L2-normalized) |
|
| 52 |
+
| Precision | fp16 / bf16 supported |
|
| 53 |
+
|
| 54 |
+
The model was distilled from `thenlper/gte-base-zh` at its native 768 dimensions, so the
|
| 55 |
+
student and the teacher share the same embedding space without dimensionality reduction.
|
| 56 |
+
|
| 57 |
+
### Training data & benchmark overlap
|
| 58 |
+
|
| 59 |
+
Training data are Chinese retrieval, STS and instruction corpora (webqa, cmedqa,
|
| 60 |
+
chinese_agriculture_qa, pawsx, wiki_zh, fineweb_edu_zh, clean_passages, alpaca_zh) plus
|
| 61 |
+
synthesized queries. Benchmark-related subsets are **explicitly declared** in the MTEB
|
| 62 |
+
model metadata:
|
| 63 |
+
|
| 64 |
+
| Status | Benchmark tasks |
|
| 65 |
+
|---|---|
|
| 66 |
+
| **Declared** (their corpora appear in training data) | `PAWSX`, `CmedqaRetrieval`, `CMedQAv1-reranking`, `CMedQAv2-reranking` |
|
| 67 |
+
| **Excluded** (corpora removed from training data → zero-shot) | `T2Retrieval`, `T2Reranking` (T2Ranking family), `DuRetrieval` (DuReader), `ATEC`, `BQ`, `LCQMC`, `STSB` |
|
| 68 |
+
|
| 69 |
+
## Usage
|
| 70 |
+
|
| 71 |
+
### Using Sentence-Transformers
|
| 72 |
+
|
| 73 |
+
```bash
|
| 74 |
+
pip install -U sentence-transformers
|
| 75 |
+
```
|
| 76 |
+
|
| 77 |
+
Two things are non-optional when loading this checkpoint:
|
| 78 |
+
|
| 79 |
+
1. `trust_remote_code=True` — the backbone is shipped as `tiny_st_module.py` inside this
|
| 80 |
+
repository.
|
| 81 |
+
2. **Keep the `3_Dense` module (512 → 768).** It is part of the trained model, not a
|
| 82 |
+
post-processing step: training used
|
| 83 |
+
`normalize(mean_pool(hidden)) → Dense(512→768) → normalize`, and the published scores
|
| 84 |
+
are measured on those 768-d outputs. Loading only the backbone and skipping `3_Dense`
|
| 85 |
+
yields 512-d embeddings that do **not** reproduce the scores below.
|
| 86 |
+
|
| 87 |
+
```python
|
| 88 |
+
from sentence_transformers import SentenceTransformer
|
| 89 |
+
|
| 90 |
+
sentences_1 = ["样例数据-1", "样例数据-2"]
|
| 91 |
+
sentences_2 = ["样例数据-3", "样例数据-4"]
|
| 92 |
+
|
| 93 |
+
model = SentenceTransformer("dynasty-ai/tiny-embed-61m", trust_remote_code=True)
|
| 94 |
+
embeddings_1 = model.encode(sentences_1, normalize_embeddings=True)
|
| 95 |
+
embeddings_2 = model.encode(sentences_2, normalize_embeddings=True)
|
| 96 |
+
similarity = embeddings_1 @ embeddings_2.T
|
| 97 |
+
print(similarity) # shape: (2, 768)
|
| 98 |
+
```
|
| 99 |
+
|
| 100 |
+
For short-query to long-passage retrieval, encode queries and passages the same way —
|
| 101 |
+
**no instruction is needed on either side**:
|
| 102 |
+
|
| 103 |
+
```python
|
| 104 |
+
queries = ["停经半年后又现点红是什么原因", "中医治疗失眠的方法"]
|
| 105 |
+
passages = ["样例文档-1", "样例文档-2"]
|
| 106 |
+
|
| 107 |
+
q_embeddings = model.encode(queries, normalize_embeddings=True)
|
| 108 |
+
p_embeddings = model.encode(passages, normalize_embeddings=True)
|
| 109 |
+
scores = q_embeddings @ p_embeddings.T
|
| 110 |
+
```
|
| 111 |
+
|
| 112 |
+
### Using Huggingface Transformers
|
| 113 |
+
|
| 114 |
+
The checkpoint also loads with `transformers`, but you must reproduce the pooling and the
|
| 115 |
+
projection head yourself:
|
| 116 |
+
|
| 117 |
+
```python
|
| 118 |
+
import torch
|
| 119 |
+
import torch.nn.functional as F
|
| 120 |
+
from transformers import AutoModel, AutoTokenizer
|
| 121 |
+
|
| 122 |
+
tokenizer = AutoTokenizer.from_pretrained("dynasty-ai/tiny-embed-61m", trust_remote_code=True)
|
| 123 |
+
model = AutoModel.from_pretrained("dynasty-ai/tiny-embed-61m", trust_remote_code=True)
|
| 124 |
+
model.eval()
|
| 125 |
+
|
| 126 |
+
sentences = ["样例数据-1", "样例数据-2"]
|
| 127 |
+
encoded_input = tokenizer(sentences, padding=True, truncation=True,
|
| 128 |
+
max_length=512, return_tensors="pt")
|
| 129 |
+
|
| 130 |
+
with torch.no_grad():
|
| 131 |
+
token_embeddings = model(**encoded_input)["token_embeddings"]
|
| 132 |
+
mask = encoded_input["attention_mask"].unsqueeze(-1).to(token_embeddings.dtype)
|
| 133 |
+
pooled = (token_embeddings * mask).sum(1) / mask.sum(1).clamp(min=1e-9)
|
| 134 |
+
pooled = F.normalize(pooled, p=2, dim=1) # mean pooling
|
| 135 |
+
head = torch.nn.Linear(512, 768, bias=False) # load from 3_Dense/pytorch_model.bin
|
| 136 |
+
head.load_state_dict({"weight": torch.load("3_Dense/pytorch_model.bin",
|
| 137 |
+
map_location="cpu")["linear.weight"]})
|
| 138 |
+
embeddings = F.normalize(head(pooled), p=2, dim=1)
|
| 139 |
+
|
| 140 |
+
print(embeddings.shape) # (2, 768)
|
| 141 |
+
```
|
| 142 |
+
|
| 143 |
+
For most users the `sentence-transformers` route above is simpler and bit-identical.
|
| 144 |
+
|
| 145 |
+
## Evaluation
|
| 146 |
+
|
| 147 |
+
`MTEB(cmn, v1)` — Chinese MTEB, 31 tasks, **no instruction prefix**, cosine similarity,
|
| 148 |
+
evaluated with `mteb` 1.39.7. Scores are the average of the standard task metric per task
|
| 149 |
+
group.
|
| 150 |
+
|
| 151 |
+
| Model | Dimension | Average | Retrieval (8) | Reranking (4) | Clustering (4) | Classification (9) | PairClassification (2) | STS (4) |
|
| 152 |
+
|---|---|---|---|---|---|---|---|---|
|
| 153 |
+
| **tiny-embed-61m** | **768** | **60.58** | 63.50 | **66.23** | **49.61** | 62.10 | 68.78 | 52.56 |
|
| 154 |
+
| bge-small-zh-v1.5 | 512 | 57.34 | 61.74 | 61.24 | 44.17 | 59.91 | 65.56 | 47.91 |
|
| 155 |
+
| bge-base-zh-v1.5 | 768 | 62.70 | 69.40 | 64.87 | 47.30 | 64.21 | **73.17** | 53.90 |
|
| 156 |
+
| gte-base-zh | 768 | **65.72** | **71.73** | 67.10 | 53.63 | **66.52** | 74.75 | **58.13** |
|
| 157 |
+
|
| 158 |
+
Same-harness observations:
|
| 159 |
+
|
| 160 |
+
- vs. `bge-small-zh-v1.5` (24M): **+3.24 average**, better in every task group.
|
| 161 |
+
- vs. `bge-base-zh-v1.5` (102M, 1.7× parameters): **−2.12 average** — competitive on
|
| 162 |
+
reranking / clustering / STS, still behind on retrieval.
|
| 163 |
+
|
| 164 |
+
Retrieval detail (T2Ranking dev, nDCG@10 / recall@10, no instruction): T2Retrieval
|
| 165 |
+
nDCG@10 78.21 / recall@10 **90.10**; MMarcoRetrieval 65.29.
|
| 166 |
+
|
| 167 |
+
> Note on benchmark tasks: `T2Retrieval` / `T2Reranking` are **zero-shot** for this model
|
| 168 |
+
> (T2Ranking corpora were excluded from training). Subsets that do appear in training data
|
| 169 |
+
> are listed in the MTEB model metadata.
|
| 170 |
+
|
| 171 |
+
## Contact
|
| 172 |
+
|
| 173 |
+
Questions, bug reports and suggestions are welcome:
|
| 174 |
+
|
| 175 |
+
- **Open a discussion** on the *Community* tab of this model page
|
| 176 |
+
([dynasty-ai/tiny-embed-61m](https://huggingface.co/dynasty-ai/tiny-embed-61m)) — this is
|
| 177 |
+
the model "issue tracker"; please include library versions, hardware and a minimal
|
| 178 |
+
reproduction.
|
| 179 |
+
- Or reach the maintainers of the **dynasty-ai** organization via their Hugging Face
|
| 180 |
+
profile: <https://huggingface.co/dynasty-ai>.
|
| 181 |
+
|
| 182 |
+
## License
|
| 183 |
+
|
| 184 |
+
`tiny-embed-61m` is licensed under the [Apache-2.0 License](https://www.apache.org/licenses/LICENSE-2.0).
|
| 185 |
+
|
| 186 |
+
It is produced by distillation from the MIT-licensed model `thenlper/gte-base-zh`; the
|
| 187 |
+
copyright notice and permission notice of the upstream work apply to the corresponding
|
| 188 |
+
upstream model. Training corpora retain their original licenses. The released weights can
|
| 189 |
+
be used for commercial purposes free of charge.
|
config.json
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"variant": "B",
|
| 3 |
+
"vocab_size": 21128,
|
| 4 |
+
"hidden_size": 512,
|
| 5 |
+
"num_unique_layers": 12,
|
| 6 |
+
"num_repeats": 1,
|
| 7 |
+
"intermediate_size": 2048,
|
| 8 |
+
"num_attention_heads": 8,
|
| 9 |
+
"sliding_window": 512,
|
| 10 |
+
"use_qk_norm": true,
|
| 11 |
+
"use_bias": false,
|
| 12 |
+
"activation": "geglu",
|
| 13 |
+
"pooling": "mean",
|
| 14 |
+
"latent_queries": 4,
|
| 15 |
+
"layer_scale": false,
|
| 16 |
+
"depth_attention": false,
|
| 17 |
+
"normalize": true,
|
| 18 |
+
"rope_theta": 10000.0,
|
| 19 |
+
"positional_encoding": "abs",
|
| 20 |
+
"loop_index_embedding": false,
|
| 21 |
+
"pos_adapter_rank": 0,
|
| 22 |
+
"pos_adapter_ffn": false,
|
| 23 |
+
"max_position_embeddings": 512,
|
| 24 |
+
"attention_dropout": 0.0,
|
| 25 |
+
"hidden_dropout": 0.0,
|
| 26 |
+
"attn_impl": "flash",
|
| 27 |
+
"pad_token_id": 0,
|
| 28 |
+
"gradient_checkpointing": false,
|
| 29 |
+
"head_dim": 64,
|
| 30 |
+
"effective_num_layers": 12,
|
| 31 |
+
"model_type": "tiny_custom_embed"
|
| 32 |
+
}
|
modules.json
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[
|
| 2 |
+
{
|
| 3 |
+
"idx": 0,
|
| 4 |
+
"name": "0",
|
| 5 |
+
"path": ".",
|
| 6 |
+
"type": "tiny_st_module.TinyEmbedTransformer"
|
| 7 |
+
},
|
| 8 |
+
{
|
| 9 |
+
"idx": 1,
|
| 10 |
+
"name": "1",
|
| 11 |
+
"path": "1_Pooling",
|
| 12 |
+
"type": "sentence_transformers.models.Pooling"
|
| 13 |
+
},
|
| 14 |
+
{
|
| 15 |
+
"idx": 2,
|
| 16 |
+
"name": "2",
|
| 17 |
+
"path": "2_Normalize",
|
| 18 |
+
"type": "sentence_transformers.models.Normalize"
|
| 19 |
+
},
|
| 20 |
+
{
|
| 21 |
+
"idx": 3,
|
| 22 |
+
"name": "3",
|
| 23 |
+
"path": "3_Dense",
|
| 24 |
+
"type": "sentence_transformers.models.Dense"
|
| 25 |
+
},
|
| 26 |
+
{
|
| 27 |
+
"idx": 4,
|
| 28 |
+
"name": "4",
|
| 29 |
+
"path": "4_Normalize",
|
| 30 |
+
"type": "sentence_transformers.models.Normalize"
|
| 31 |
+
}
|
| 32 |
+
]
|
pytorch_model.bin
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:0958ad4b4d137ed5f2c92195701ce10aca5236d6dc7e9079b9a0cb20ca3db00c
|
| 3 |
+
size 245754278
|
special_tokens_map.json
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cls_token": {
|
| 3 |
+
"content": "[CLS]",
|
| 4 |
+
"lstrip": false,
|
| 5 |
+
"normalized": false,
|
| 6 |
+
"rstrip": false,
|
| 7 |
+
"single_word": false
|
| 8 |
+
},
|
| 9 |
+
"mask_token": {
|
| 10 |
+
"content": "[MASK]",
|
| 11 |
+
"lstrip": false,
|
| 12 |
+
"normalized": false,
|
| 13 |
+
"rstrip": false,
|
| 14 |
+
"single_word": false
|
| 15 |
+
},
|
| 16 |
+
"pad_token": {
|
| 17 |
+
"content": "[PAD]",
|
| 18 |
+
"lstrip": false,
|
| 19 |
+
"normalized": false,
|
| 20 |
+
"rstrip": false,
|
| 21 |
+
"single_word": false
|
| 22 |
+
},
|
| 23 |
+
"sep_token": {
|
| 24 |
+
"content": "[SEP]",
|
| 25 |
+
"lstrip": false,
|
| 26 |
+
"normalized": false,
|
| 27 |
+
"rstrip": false,
|
| 28 |
+
"single_word": false
|
| 29 |
+
},
|
| 30 |
+
"unk_token": {
|
| 31 |
+
"content": "[UNK]",
|
| 32 |
+
"lstrip": false,
|
| 33 |
+
"normalized": false,
|
| 34 |
+
"rstrip": false,
|
| 35 |
+
"single_word": false
|
| 36 |
+
}
|
| 37 |
+
}
|
tiny_st_module.py
ADDED
|
@@ -0,0 +1,178 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
"""TinyCustomEmbed 的 sentence-transformers 自包含模块(由 export_sentence_transformers.py 生成)。"""
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import json
|
| 6 |
+
import os
|
| 7 |
+
|
| 8 |
+
import torch
|
| 9 |
+
from torch import nn
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class RMSNorm(nn.Module):
|
| 13 |
+
def __init__(self, hidden_size: int, eps: float = 1e-6):
|
| 14 |
+
super().__init__()
|
| 15 |
+
self.weight = nn.Parameter(torch.ones(hidden_size))
|
| 16 |
+
self.eps = eps
|
| 17 |
+
|
| 18 |
+
def forward(self, x):
|
| 19 |
+
rms = x.float().pow(2).mean(-1, keepdim=True)
|
| 20 |
+
return (x * torch.rsqrt(rms + self.eps)).to(x.dtype) * self.weight
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
class RotaryEmbedding(nn.Module):
|
| 24 |
+
def __init__(self, dim: int, theta: float = 10000.0):
|
| 25 |
+
super().__init__()
|
| 26 |
+
inv_freq = 1.0 / (theta ** (torch.arange(0, dim, 2).float() / dim))
|
| 27 |
+
self.register_buffer("inv_freq", inv_freq, persistent=False)
|
| 28 |
+
|
| 29 |
+
@torch.no_grad()
|
| 30 |
+
def forward(self, seq_len, device, dtype):
|
| 31 |
+
t = torch.arange(seq_len, device=device, dtype=self.inv_freq.dtype)
|
| 32 |
+
freqs = torch.outer(t, self.inv_freq)
|
| 33 |
+
return freqs.cos().to(dtype), freqs.sin().to(dtype)
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def _rotate_half(x):
|
| 37 |
+
x1, x2 = x.chunk(2, dim=-1)
|
| 38 |
+
return torch.cat((-x2, x1), dim=-1)
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def _apply_rope(x, cos, sin):
|
| 42 |
+
seq_len = x.shape[-3]
|
| 43 |
+
cos = cos[:seq_len].unsqueeze(0).unsqueeze(2)
|
| 44 |
+
sin = sin[:seq_len].unsqueeze(0).unsqueeze(2)
|
| 45 |
+
return x * cos + _rotate_half(x) * sin
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
class _Attn(nn.Module):
|
| 49 |
+
def __init__(self, hidden, heads, window, qk_norm, full):
|
| 50 |
+
super().__init__()
|
| 51 |
+
self.heads, self.head_dim = heads, hidden // heads
|
| 52 |
+
self.window, self.full = window, full
|
| 53 |
+
self.q_proj = nn.Linear(hidden, hidden, bias=False)
|
| 54 |
+
self.k_proj = nn.Linear(hidden, hidden, bias=False)
|
| 55 |
+
self.v_proj = nn.Linear(hidden, hidden, bias=False)
|
| 56 |
+
self.o_proj = nn.Linear(hidden, hidden, bias=False)
|
| 57 |
+
self.q_norm = RMSNorm(self.head_dim) if qk_norm else None
|
| 58 |
+
self.k_norm = RMSNorm(self.head_dim) if qk_norm else None
|
| 59 |
+
|
| 60 |
+
def forward(self, x, cos, sin, pad_mask):
|
| 61 |
+
B, L, _ = x.shape
|
| 62 |
+
q = self.q_proj(x).view(B, L, self.heads, self.head_dim)
|
| 63 |
+
k = self.k_proj(x).view(B, L, self.heads, self.head_dim)
|
| 64 |
+
v = self.v_proj(x).view(B, L, self.heads, self.head_dim)
|
| 65 |
+
if cos is not None:
|
| 66 |
+
q, k = _apply_rope(q, cos, sin), _apply_rope(k, cos, sin)
|
| 67 |
+
if self.q_norm is not None:
|
| 68 |
+
q, k = self.q_norm(q), self.k_norm(k)
|
| 69 |
+
qh, kh, vh = q.transpose(1, 2), k.transpose(1, 2), v.transpose(1, 2)
|
| 70 |
+
use_win = (self.window > 0) and (not self.full) and L > self.window
|
| 71 |
+
keep = pad_mask.bool()[:, None, :].expand(B, L, L).clone()
|
| 72 |
+
if use_win:
|
| 73 |
+
half = self.window // 2
|
| 74 |
+
idx = torch.arange(L, device=x.device)
|
| 75 |
+
keep &= (idx[:, None] - idx[None, :]).abs().le(half)[None]
|
| 76 |
+
pos = torch.arange(L, device=x.device)
|
| 77 |
+
keep |= (pos[None, :] == pos[:, None])[None]
|
| 78 |
+
out = torch.nn.functional.scaled_dot_product_attention(qh, kh, vh,
|
| 79 |
+
attn_mask=keep[:, None])
|
| 80 |
+
return self.o_proj(out.transpose(1, 2).reshape(B, L, -1))
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
class _GeGLU(nn.Module):
|
| 84 |
+
def __init__(self, hidden, inter, bias=False):
|
| 85 |
+
super().__init__()
|
| 86 |
+
self.gate_proj = nn.Linear(hidden, inter, bias=bias)
|
| 87 |
+
self.up_proj = nn.Linear(hidden, inter, bias=bias)
|
| 88 |
+
self.down_proj = nn.Linear(inter, hidden, bias=bias)
|
| 89 |
+
|
| 90 |
+
def forward(self, x):
|
| 91 |
+
return self.down_proj(torch.nn.functional.gelu(self.gate_proj(x)) * self.up_proj(x))
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
class _Layer(nn.Module):
|
| 95 |
+
def __init__(self, hidden, inter, heads, window, qk_norm, full):
|
| 96 |
+
super().__init__()
|
| 97 |
+
self.pre_attn_norm, self.post_attn_norm = RMSNorm(hidden), RMSNorm(hidden)
|
| 98 |
+
self.self_attn = _Attn(hidden, heads, window, qk_norm, full)
|
| 99 |
+
self.ffn = _GeGLU(hidden, inter)
|
| 100 |
+
|
| 101 |
+
def forward(self, x, cos, sin, pad_mask, is_global):
|
| 102 |
+
x = x + self.self_attn(self.pre_attn_norm(x), cos, sin, pad_mask) # full/window 在 _Attn 构造时已定
|
| 103 |
+
return x + self.ffn(self.post_attn_norm(x))
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
class TinyEmbedTransformer(nn.Module):
|
| 107 |
+
"""ST Transformer 模块:加载 TinyCustomEmbed 权重并输出 token_embeddings。"""
|
| 108 |
+
|
| 109 |
+
def __init__(self, model_path: str = ".", max_length: int = 512, **kwargs):
|
| 110 |
+
super().__init__()
|
| 111 |
+
with open(os.path.join(model_path, "config.json"), encoding="utf-8") as f:
|
| 112 |
+
c = json.load(f)
|
| 113 |
+
self.config = c
|
| 114 |
+
H = c["hidden_size"]
|
| 115 |
+
self.token_embedding = nn.Embedding(c["vocab_size"], H)
|
| 116 |
+
# 只建 num_unique_layers 个真实层(与原模型 state_dict 一致),
|
| 117 |
+
# forward 按 li % num_unique_layers 复用(权重共享语义)
|
| 118 |
+
uniq = c["num_unique_layers"]
|
| 119 |
+
self.num_unique_layers = uniq
|
| 120 |
+
self.layers = nn.ModuleList([
|
| 121 |
+
_Layer(H, c["intermediate_size"], c["num_attention_heads"],
|
| 122 |
+
c["sliding_window"], c.get("use_qk_norm", True),
|
| 123 |
+
ui in (0, uniq - 1))
|
| 124 |
+
for ui in range(uniq)])
|
| 125 |
+
self.final_norm = RMSNorm(H)
|
| 126 |
+
self.rope = (RotaryEmbedding(c["head_dim"] * 2, c.get("rope_theta", 10000.0))
|
| 127 |
+
if c.get("positional_encoding", "rope") == "rope" else None)
|
| 128 |
+
self.position_embedding = (nn.Embedding(c["max_position_embeddings"], H)
|
| 129 |
+
if c.get("positional_encoding") == "abs" else None)
|
| 130 |
+
if self.position_embedding is not None and os.path.exists(os.path.join(model_path, "pytorch_model.bin")):
|
| 131 |
+
pass # 权重统一由 load_state_dict 装载
|
| 132 |
+
# loop_embedding / pos_adapters / layer_gates 如存在则按 config 重建
|
| 133 |
+
self.loop_embedding = (nn.Embedding(c["effective_num_layers"], H)
|
| 134 |
+
if c.get("loop_index_embedding") else None)
|
| 135 |
+
r = c.get("pos_adapter_rank", 0)
|
| 136 |
+
self.pos_adapters = None
|
| 137 |
+
self._model_path = model_path
|
| 138 |
+
self.max_seq_length = max_length
|
| 139 |
+
from transformers import AutoTokenizer
|
| 140 |
+
|
| 141 |
+
self.tokenizer = AutoTokenizer.from_pretrained(model_path)
|
| 142 |
+
|
| 143 |
+
def tokenize(self, texts, **kwargs):
|
| 144 |
+
return self.tokenizer(list(texts), padding=True, truncation=True,
|
| 145 |
+
max_length=self.max_seq_length, return_tensors="pt", **kwargs)
|
| 146 |
+
|
| 147 |
+
def forward(self, features):
|
| 148 |
+
ids = features["input_ids"]
|
| 149 |
+
am = features["attention_mask"]
|
| 150 |
+
h = self.token_embedding(ids)
|
| 151 |
+
if self.position_embedding is not None:
|
| 152 |
+
h = h + self.position_embedding(torch.arange(ids.shape[1], device=ids.device))
|
| 153 |
+
cos = sin = None
|
| 154 |
+
if self.rope is not None:
|
| 155 |
+
cos, sin = self.rope(ids.shape[1], ids.device, h.dtype)
|
| 156 |
+
uniq = self.num_unique_layers
|
| 157 |
+
for li in range(self.config["effective_num_layers"]):
|
| 158 |
+
if self.loop_embedding is not None:
|
| 159 |
+
h = h + self.loop_embedding.weight[li].to(h.dtype)
|
| 160 |
+
ui = li % uniq
|
| 161 |
+
h = self.layers[ui](h, cos, sin, am, ui in (0, uniq - 1))
|
| 162 |
+
features["token_embeddings"] = self.final_norm(h)
|
| 163 |
+
return features
|
| 164 |
+
|
| 165 |
+
def save(self, output_path, *args, **kwargs):
|
| 166 |
+
torch.save(self.state_dict(), os.path.join(output_path, "pytorch_model.bin"))
|
| 167 |
+
|
| 168 |
+
@staticmethod
|
| 169 |
+
def load(input_path):
|
| 170 |
+
module = TinyEmbedTransformer(model_path=input_path)
|
| 171 |
+
# ST 对远程代码模块不会自动装载权重,必须在 load() 里自己完成
|
| 172 |
+
state = torch.load(os.path.join(input_path, "pytorch_model.bin"),
|
| 173 |
+
map_location="cpu")
|
| 174 |
+
module.load_state_dict(state, strict=True)
|
| 175 |
+
return module
|
| 176 |
+
|
| 177 |
+
def get_word_embedding_dimension(self):
|
| 178 |
+
return self.config["hidden_size"]
|
tokenizer.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
tokenizer_config.json
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"added_tokens_decoder": {
|
| 3 |
+
"0": {
|
| 4 |
+
"content": "[PAD]",
|
| 5 |
+
"lstrip": false,
|
| 6 |
+
"normalized": false,
|
| 7 |
+
"rstrip": false,
|
| 8 |
+
"single_word": false,
|
| 9 |
+
"special": true
|
| 10 |
+
},
|
| 11 |
+
"100": {
|
| 12 |
+
"content": "[UNK]",
|
| 13 |
+
"lstrip": false,
|
| 14 |
+
"normalized": false,
|
| 15 |
+
"rstrip": false,
|
| 16 |
+
"single_word": false,
|
| 17 |
+
"special": true
|
| 18 |
+
},
|
| 19 |
+
"101": {
|
| 20 |
+
"content": "[CLS]",
|
| 21 |
+
"lstrip": false,
|
| 22 |
+
"normalized": false,
|
| 23 |
+
"rstrip": false,
|
| 24 |
+
"single_word": false,
|
| 25 |
+
"special": true
|
| 26 |
+
},
|
| 27 |
+
"102": {
|
| 28 |
+
"content": "[SEP]",
|
| 29 |
+
"lstrip": false,
|
| 30 |
+
"normalized": false,
|
| 31 |
+
"rstrip": false,
|
| 32 |
+
"single_word": false,
|
| 33 |
+
"special": true
|
| 34 |
+
},
|
| 35 |
+
"103": {
|
| 36 |
+
"content": "[MASK]",
|
| 37 |
+
"lstrip": false,
|
| 38 |
+
"normalized": false,
|
| 39 |
+
"rstrip": false,
|
| 40 |
+
"single_word": false,
|
| 41 |
+
"special": true
|
| 42 |
+
}
|
| 43 |
+
},
|
| 44 |
+
"clean_up_tokenization_spaces": true,
|
| 45 |
+
"cls_token": "[CLS]",
|
| 46 |
+
"do_basic_tokenize": true,
|
| 47 |
+
"do_lower_case": false,
|
| 48 |
+
"extra_special_tokens": {},
|
| 49 |
+
"mask_token": "[MASK]",
|
| 50 |
+
"model_max_length": 512,
|
| 51 |
+
"never_split": null,
|
| 52 |
+
"pad_token": "[PAD]",
|
| 53 |
+
"sep_token": "[SEP]",
|
| 54 |
+
"strip_accents": null,
|
| 55 |
+
"tokenize_chinese_chars": true,
|
| 56 |
+
"tokenizer_class": "BertTokenizer",
|
| 57 |
+
"unk_token": "[UNK]"
|
| 58 |
+
}
|
vocab.txt
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|