Sentence Similarity
sentence-transformers
Safetensors
nandi_encoder
embeddings
feature-extraction
mteb
retrieval
multilingual
indic
long-context
frontiersmind
nandi
custom_code
Instructions to use FrontiersMind/EmbeddingNandi-450M with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- sentence-transformers
How to use FrontiersMind/EmbeddingNandi-450M with sentence-transformers:
from sentence_transformers import SentenceTransformer model = SentenceTransformer("FrontiersMind/EmbeddingNandi-450M", trust_remote_code=True) sentences = [ "task: sentence similarity | query: How do I return a damaged product?", "task: sentence similarity | query: खराब सामान वापस कैसे करें?", "task: sentence similarity | query: damaged product wapas kaise kare?", "task: sentence similarity | query: What is the weather like today?" ] embeddings = model.encode(sentences) similarities = model.similarity(embeddings, embeddings) print(similarities.shape) # [4, 4] - Notebooks
- Google Colab
- Kaggle
Release weights: equal average of two stage-2 runs; model card with MTEB results
Browse files- README.md +61 -6
- config.json +53 -0
- configuration_nandi_encoder.py +119 -0
- model.safetensors +3 -0
- modeling_nandi_encoder.py +516 -0
- tokenization_nandi_encoder.py +126 -0
- tokenizer.json +0 -0
- tokenizer_config.json +24 -0
README.md
CHANGED
|
@@ -64,16 +64,71 @@ EmbeddingNandi is a family of open, long-context embedding models for English, I
|
|
| 64 |
- **Deep, with efficient attention:** Inherited from NandiBERT-450M: 28 layers at 1,024 hidden size, with QK-norm and SwiGLU. Grouped-query attention with 8 query heads and 2 key-value heads keeps memory low on long inputs. The 100K-token vocabulary is stored as a rank-512 factorized embedding.
|
| 65 |
- **Embedding output:** 1,024-dimensional vectors. Mean pooling over all tokens (task prompt included), then L2 normalization, compared with cosine similarity. Trained with Matryoshka Representation Learning, so vectors can be cut to 768, 512, 256 or 128 dimensions.
|
| 66 |
- **Task prompts:** Short task prompts in the EmbeddingGemma format (for example `task: search result | query: `) steer the embedding for search, code search, classification, clustering and similarity.
|
| 67 |
-
- **Training:**
|
| 68 |
- **Built for retrieval:** A drop-in encoder for semantic search, retrieval-augmented generation, clustering, deduplication and similarity scoring, loadable with Sentence Transformers and Hugging Face `transformers`.
|
| 69 |
|
| 70 |
## Benchmark Results
|
| 71 |
|
| 72 |
-
|
| 73 |
|
| 74 |
-
| Benchmark | EmbeddingNandi-450M |
|
| 75 |
|---|---|---|---|---|
|
| 76 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 77 |
|
| 78 |
## Quick Start
|
| 79 |
|
|
@@ -160,10 +215,10 @@ model = SentenceTransformer("FrontiersMind/EmbeddingNandi-450M", trust_remote_co
|
|
| 160 |
|
| 161 |
### 3. Long Inputs
|
| 162 |
|
| 163 |
-
|
| 164 |
|
| 165 |
```python
|
| 166 |
-
model.max_seq_length =
|
| 167 |
```
|
| 168 |
|
| 169 |
## Usage with Transformers
|
|
|
|
| 64 |
- **Deep, with efficient attention:** Inherited from NandiBERT-450M: 28 layers at 1,024 hidden size, with QK-norm and SwiGLU. Grouped-query attention with 8 query heads and 2 key-value heads keeps memory low on long inputs. The 100K-token vocabulary is stored as a rank-512 factorized embedding.
|
| 65 |
- **Embedding output:** 1,024-dimensional vectors. Mean pooling over all tokens (task prompt included), then L2 normalization, compared with cosine similarity. Trained with Matryoshka Representation Learning, so vectors can be cut to 768, 512, 256 or 128 dimensions.
|
| 66 |
- **Task prompts:** Short task prompts in the EmbeddingGemma format (for example `task: search result | query: `) steer the embedding for search, code search, classification, clustering and similarity.
|
| 67 |
+
- **Training:** Contrastive training on top of NandiBERT-450M in three stages: weakly supervised text pairs with very large batches (16,384), then a curated pair set, then fine-tuning on labelled retrieval, code, classification, clustering, similarity and bitext data in English and Indic languages, with up to three mined hard negatives per query, a CoSENT loss for similarity data and documents up to 32K tokens. Matryoshka loss at 1024, 768, 512, 256 and 128 dimensions. The released weights are an equal average of two fine-tuning runs.
|
| 68 |
- **Built for retrieval:** A drop-in encoder for semantic search, retrieval-augmented generation, clustering, deduplication and similarity scoring, loadable with Sentence Transformers and Hugging Face `transformers`.
|
| 69 |
|
| 70 |
## Benchmark Results
|
| 71 |
|
| 72 |
+
Mean task scores on MTEB. EmbeddingNandi-450M is evaluated with the task prompts saved in the model. Scores for other models are their official numbers; "-" means not reported. Best score in each row is in bold.
|
| 73 |
|
| 74 |
+
| Benchmark | EmbeddingNandi-450M | EmbeddingGemma 2 (271M) | embeddinggemma-300m (308M) | Qwen3-Embedding-0.6B (596M) |
|
| 75 |
|---|---|---|---|---|
|
| 76 |
+
| MTEB(eng, v2), 41 tasks | 67.34 | 67.53 | 69.67 | **70.47** |
|
| 77 |
+
| MTEB(Code, v1), 12 tasks | 76.68 | **77.88** | 68.76 | 75.42 |
|
| 78 |
+
| MTEB(Indic, v1) | **76.68** | - | - | 65.32 |
|
| 79 |
+
|
| 80 |
+
<details>
|
| 81 |
+
<summary>MTEB(eng, v2) by task type</summary>
|
| 82 |
+
|
| 83 |
+
| Task type | EmbeddingNandi-450M | EmbeddingGemma 2 (271M) | embeddinggemma-300m (308M) | Qwen3-Embedding-0.6B (596M) |
|
| 84 |
+
|---|---|---|---|---|
|
| 85 |
+
| Mean (41) | 67.34 | 67.53 | 69.67 | **70.47** |
|
| 86 |
+
| Classification (8) | **89.43** | 88.82 | 87.55 | 84.56 |
|
| 87 |
+
| Clustering (8) | 52.02 | 51.70 | **56.55** | 54.05 |
|
| 88 |
+
| Pair Classification (3) | 83.49 | 86.39 | **87.29** | 84.37 |
|
| 89 |
+
| Reranking (2) | 47.72 | 46.03 | 47.43 | **48.18** |
|
| 90 |
+
| Retrieval (10) | 52.39 | 51.33 | 55.69 | **61.83** |
|
| 91 |
+
| STS (9) | 81.49 | 82.75 | 83.61 | **86.57** |
|
| 92 |
+
| Summarization (1) | 26.31 | 35.09 | **37.64** | 33.43 |
|
| 93 |
+
|
| 94 |
+
</details>
|
| 95 |
+
|
| 96 |
+
<details>
|
| 97 |
+
<summary>MTEB(Code, v1) by task</summary>
|
| 98 |
+
|
| 99 |
+
| Task | EmbeddingNandi-450M | EmbeddingGemma 2 (271M) | embeddinggemma-300m (308M) | Qwen3-Embedding-0.6B (596M) |
|
| 100 |
+
|---|---|---|---|---|
|
| 101 |
+
| Mean (12) | 76.68 | **77.88** | 68.76 | 75.42 |
|
| 102 |
+
| AppsRetrieval | 77.95 | **89.29** | 84.39 | 75.34 |
|
| 103 |
+
| COIRCodeSearchNetRetrieval | 85.84 | **86.91** | 75.54 | 84.69 |
|
| 104 |
+
| CodeEditSearchRetrieval | **80.88** | 80.50 | 62.10 | 64.42 |
|
| 105 |
+
| CodeFeedbackMT | 86.95 | 88.22 | 51.42 | **90.82** |
|
| 106 |
+
| CodeFeedbackST | **88.67** | 82.12 | 80.26 | 86.39 |
|
| 107 |
+
| CodeSearchNetCCRetrieval | 92.15 | **96.64** | 73.71 | 91.72 |
|
| 108 |
+
| CodeSearchNetRetrieval | 89.38 | 90.83 | 90.15 | **91.01** |
|
| 109 |
+
| CodeTransOceanContest | 84.25 | 83.74 | 85.51 | **86.05** |
|
| 110 |
+
| CodeTransOceanDL | 34.84 | **36.59** | 33.52 | 31.36 |
|
| 111 |
+
| CosQA | 43.67 | **51.35** | 43.59 | 36.48 |
|
| 112 |
+
| StackOverflowQA | **92.62** | 87.32 | 86.47 | 89.99 |
|
| 113 |
+
| SyntheticText2SQL | 63.00 | 61.10 | 58.42 | **76.74** |
|
| 114 |
+
|
| 115 |
+
</details>
|
| 116 |
+
|
| 117 |
+
<details>
|
| 118 |
+
<summary>MTEB(Indic, v1) by task type</summary>
|
| 119 |
+
|
| 120 |
+
| Task type | EmbeddingNandi-450M | multilingual-e5-large-instruct (560M) | harrier-oss-v1-0.6b (596M) | Qwen3-Embedding-0.6B (596M) |
|
| 121 |
+
|---|---|---|---|---|
|
| 122 |
+
| Mean | **76.68** | 70.15 | 70.78 | 65.32 |
|
| 123 |
+
| Bitext Mining | **88.84** | 80.37 | 80.32 | 67.17 |
|
| 124 |
+
| Classification | **73.76** | 66.96 | 68.85 | 64.71 |
|
| 125 |
+
| Clustering | **58.81** | 51.67 | 51.56 | 39.41 |
|
| 126 |
+
| Pair Classification | **85.16** | 76.31 | 79.47 | 77.23 |
|
| 127 |
+
| Reranking | 87.08 | **87.46** | 82.02 | 82.48 |
|
| 128 |
+
| Retrieval | **90.89** | 84.86 | 81.19 | 78.71 |
|
| 129 |
+
| STS | **58.06** | 53.69 | 53.28 | 38.98 |
|
| 130 |
+
|
| 131 |
+
</details>
|
| 132 |
|
| 133 |
## Quick Start
|
| 134 |
|
|
|
|
| 215 |
|
| 216 |
### 3. Long Inputs
|
| 217 |
|
| 218 |
+
The model takes inputs of up to 32,768 tokens, and `model.max_seq_length` is 32768 by default, so long documents are embedded whole. Texts longer than `model.max_seq_length` tokens are truncated. Longer inputs need more memory and time, so for short texts or limited memory you can lower the limit:
|
| 219 |
|
| 220 |
```python
|
| 221 |
+
model.max_seq_length = 1024
|
| 222 |
```
|
| 223 |
|
| 224 |
## Usage with Transformers
|
config.json
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"architectures": [
|
| 3 |
+
"NandiEncoderModel"
|
| 4 |
+
],
|
| 5 |
+
"attention_bias": false,
|
| 6 |
+
"attention_dropout": 0.0,
|
| 7 |
+
"auto_map": {
|
| 8 |
+
"AutoConfig": "configuration_nandi_encoder.NandiEncoderConfig",
|
| 9 |
+
"AutoModel": "modeling_nandi_encoder.NandiEncoderModel",
|
| 10 |
+
"AutoModelForMaskedLM": "modeling_nandi_encoder.NandiForMaskedLM",
|
| 11 |
+
"AutoModelForSequenceClassification": "modeling_nandi_encoder.NandiForSequenceClassification",
|
| 12 |
+
"AutoModelForTokenClassification": "modeling_nandi_encoder.NandiForTokenClassification"
|
| 13 |
+
},
|
| 14 |
+
"bos_token_id": 0,
|
| 15 |
+
"classifier_dropout": 0.0,
|
| 16 |
+
"classifier_pooling": "mean",
|
| 17 |
+
"dtype": "float32",
|
| 18 |
+
"embedding_rank": 512,
|
| 19 |
+
"eos_token_id": 0,
|
| 20 |
+
"factorized_embedding": true,
|
| 21 |
+
"head_dim": 128,
|
| 22 |
+
"hidden_act": "silu",
|
| 23 |
+
"hidden_size": 1024,
|
| 24 |
+
"initializer_range": 0.008,
|
| 25 |
+
"intermediate_size": 3712,
|
| 26 |
+
"layer_sharing": false,
|
| 27 |
+
"layer_sharing_repeats": 1,
|
| 28 |
+
"mask_token_id": 4,
|
| 29 |
+
"max_position_embeddings": 32768,
|
| 30 |
+
"mlm_head": "dense",
|
| 31 |
+
"mlm_head_act": "silu",
|
| 32 |
+
"mlm_head_decoder_bias": false,
|
| 33 |
+
"mlp_bias": false,
|
| 34 |
+
"model_type": "nandi_encoder",
|
| 35 |
+
"num_attention_heads": 8,
|
| 36 |
+
"num_hidden_layers": 28,
|
| 37 |
+
"num_key_value_heads": 2,
|
| 38 |
+
"pad_token_id": 3,
|
| 39 |
+
"qk_norm": true,
|
| 40 |
+
"rms_norm_eps": 1e-06,
|
| 41 |
+
"rope_parameters": {
|
| 42 |
+
"rope_theta": 1000000.0,
|
| 43 |
+
"rope_type": "default"
|
| 44 |
+
},
|
| 45 |
+
"smoltron_source": {
|
| 46 |
+
"checkpoint": "checkpoint_145000_tokens_385.35B",
|
| 47 |
+
"consumed_train_samples": 87600000,
|
| 48 |
+
"train_step": 145000
|
| 49 |
+
},
|
| 50 |
+
"tie_word_embeddings": false,
|
| 51 |
+
"transformers_version": "5.20.2",
|
| 52 |
+
"vocab_size": 100352
|
| 53 |
+
}
|
configuration_nandi_encoder.py
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2026 FrontiersMind. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
"""Configuration of the Nandi encoder (bidirectional Nandi trained with masked language modeling)."""
|
| 15 |
+
|
| 16 |
+
from transformers.configuration_utils import PretrainedConfig
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
class NandiEncoderConfig(PretrainedConfig):
|
| 20 |
+
r"""
|
| 21 |
+
Configuration for the Nandi encoder. The architecture is the Nandi decoder's (RMSNorm, SwiGLU, GQA, RoPE,
|
| 22 |
+
factorized embeddings, layer sharing) with full bidirectional attention and a masked-LM head (the tied LM head).
|
| 23 |
+
|
| 24 |
+
```python
|
| 25 |
+
>>> from transformers import AutoModelForMaskedLM, AutoTokenizer
|
| 26 |
+
>>> tok = AutoTokenizer.from_pretrained("FrontiersMind/nandi-bert-small", trust_remote_code=True)
|
| 27 |
+
>>> model = AutoModelForMaskedLM.from_pretrained("FrontiersMind/nandi-bert-small", trust_remote_code=True)
|
| 28 |
+
```
|
| 29 |
+
|
| 30 |
+
Args:
|
| 31 |
+
classifier_pooling (`str`, *optional*, defaults to `"mean"`):
|
| 32 |
+
Pooling for `NandiForSequenceClassification`: `"mean"` over non-padding tokens, or `"first"` (the
|
| 33 |
+
`<|endoftext|>` token every input starts with).
|
| 34 |
+
classifier_dropout (`float`, *optional*, defaults to 0.0):
|
| 35 |
+
Dropout before the classification heads.
|
| 36 |
+
"""
|
| 37 |
+
|
| 38 |
+
model_type = "nandi_encoder"
|
| 39 |
+
|
| 40 |
+
def __init__(
|
| 41 |
+
self,
|
| 42 |
+
vocab_size=131072,
|
| 43 |
+
hidden_size=832,
|
| 44 |
+
intermediate_size=2496,
|
| 45 |
+
num_hidden_layers=16,
|
| 46 |
+
num_attention_heads=16,
|
| 47 |
+
num_key_value_heads=4,
|
| 48 |
+
head_dim=None,
|
| 49 |
+
hidden_act="silu",
|
| 50 |
+
max_position_embeddings=2048,
|
| 51 |
+
initializer_range=0.02,
|
| 52 |
+
rms_norm_eps=1e-5,
|
| 53 |
+
pad_token_id=3,
|
| 54 |
+
bos_token_id=0,
|
| 55 |
+
eos_token_id=0,
|
| 56 |
+
mask_token_id=131062,
|
| 57 |
+
tie_word_embeddings=True,
|
| 58 |
+
rope_parameters=None,
|
| 59 |
+
attention_bias=False,
|
| 60 |
+
attention_dropout=0.0,
|
| 61 |
+
mlp_bias=False,
|
| 62 |
+
factorized_embedding=True,
|
| 63 |
+
embedding_rank=196,
|
| 64 |
+
layer_sharing=True,
|
| 65 |
+
layer_sharing_repeats=2,
|
| 66 |
+
classifier_pooling="mean",
|
| 67 |
+
classifier_dropout=0.0,
|
| 68 |
+
qk_norm=False,
|
| 69 |
+
mlm_head="tied_factorized",
|
| 70 |
+
mlm_head_act="silu",
|
| 71 |
+
mlm_head_decoder_bias=False,
|
| 72 |
+
**kwargs,
|
| 73 |
+
):
|
| 74 |
+
self.vocab_size = vocab_size
|
| 75 |
+
self.hidden_size = hidden_size
|
| 76 |
+
self.intermediate_size = intermediate_size
|
| 77 |
+
self.num_hidden_layers = num_hidden_layers
|
| 78 |
+
self.num_attention_heads = num_attention_heads
|
| 79 |
+
self.num_key_value_heads = num_key_value_heads if num_key_value_heads is not None else num_attention_heads
|
| 80 |
+
self.head_dim = head_dim if head_dim is not None else hidden_size // num_attention_heads
|
| 81 |
+
self.hidden_act = hidden_act
|
| 82 |
+
self.max_position_embeddings = max_position_embeddings
|
| 83 |
+
self.initializer_range = initializer_range
|
| 84 |
+
self.rms_norm_eps = rms_norm_eps
|
| 85 |
+
self.mask_token_id = mask_token_id
|
| 86 |
+
self.rope_parameters = rope_parameters if rope_parameters is not None else {"rope_type": "default", "rope_theta": 100000.0}
|
| 87 |
+
self.attention_bias = attention_bias
|
| 88 |
+
self.attention_dropout = attention_dropout
|
| 89 |
+
self.mlp_bias = mlp_bias
|
| 90 |
+
self.factorized_embedding = factorized_embedding
|
| 91 |
+
self.embedding_rank = embedding_rank
|
| 92 |
+
self.layer_sharing = layer_sharing
|
| 93 |
+
self.layer_sharing_repeats = layer_sharing_repeats if layer_sharing else 1
|
| 94 |
+
if classifier_pooling not in ("mean", "first"):
|
| 95 |
+
raise ValueError(f"`classifier_pooling` must be 'mean' or 'first', got {classifier_pooling!r}")
|
| 96 |
+
self.classifier_pooling = classifier_pooling
|
| 97 |
+
self.classifier_dropout = classifier_dropout
|
| 98 |
+
self.qk_norm = qk_norm # RMSNorm on Q and K per head (over head_dim) before RoPE
|
| 99 |
+
if mlm_head not in ("tied_factorized", "dense"):
|
| 100 |
+
raise ValueError(f"`mlm_head` must be 'tied_factorized' or 'dense', got {mlm_head!r}")
|
| 101 |
+
self.mlm_head = mlm_head # dense: dense -> act -> RMSNorm -> untied full-width decoder
|
| 102 |
+
self.mlm_head_act = mlm_head_act
|
| 103 |
+
self.mlm_head_decoder_bias = mlm_head_decoder_bias
|
| 104 |
+
|
| 105 |
+
if self.factorized_embedding and self.embedding_rank <= 0:
|
| 106 |
+
raise ValueError(f"`embedding_rank` must be positive when `factorized_embedding=True`, got {embedding_rank}.")
|
| 107 |
+
if self.layer_sharing_repeats < 1:
|
| 108 |
+
raise ValueError(f"`layer_sharing_repeats` must be >= 1, got {self.layer_sharing_repeats}.")
|
| 109 |
+
|
| 110 |
+
super().__init__(
|
| 111 |
+
pad_token_id=pad_token_id,
|
| 112 |
+
bos_token_id=bos_token_id,
|
| 113 |
+
eos_token_id=eos_token_id,
|
| 114 |
+
tie_word_embeddings=tie_word_embeddings,
|
| 115 |
+
**kwargs,
|
| 116 |
+
)
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
__all__ = ["NandiEncoderConfig"]
|
model.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:714e4f3808a81f1f88bb2d56fe84c54f1f43d4ead6aae9604d0b11801f11ae3b
|
| 3 |
+
size 1778680336
|
modeling_nandi_encoder.py
ADDED
|
@@ -0,0 +1,516 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2026 FrontiersMind. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
"""Nandi encoder: the Nandi decoder architecture with bidirectional attention, trained with masked language modeling.
|
| 15 |
+
|
| 16 |
+
Matches Smoltron's `NandiEncoderForTraining` (src/nanotron/models/nandi_encoder.py):
|
| 17 |
+
embed_tokens -> embedding_proj (factorized)
|
| 18 |
+
-> each of the N layers applied `layer_sharing_repeats` times back to back (0, 0, 1, 1, ...)
|
| 19 |
+
(pre-norm: x + attn(rmsnorm(x)), x + swiglu(rmsnorm(x)); GQA attention with RoPE, NOT causal)
|
| 20 |
+
-> final RMSNorm -> MLM head: either lm_head_proj (factorized) -> lm_head (tied to embed_tokens),
|
| 21 |
+
or (mlm_head='dense') dense -> act -> RMSNorm -> untied lm_head. Optional QK-norm (per head, before RoPE).
|
| 22 |
+
|
| 23 |
+
Inputs start with `<|endoftext|>` (the tokenizer adds it), as every training document did.
|
| 24 |
+
"""
|
| 25 |
+
|
| 26 |
+
from collections.abc import Callable
|
| 27 |
+
|
| 28 |
+
import torch
|
| 29 |
+
import torch.nn as nn
|
| 30 |
+
from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
|
| 31 |
+
|
| 32 |
+
from transformers.activations import ACT2FN
|
| 33 |
+
from transformers.masking_utils import create_bidirectional_mask
|
| 34 |
+
from transformers.modeling_layers import GradientCheckpointingLayer
|
| 35 |
+
from transformers.modeling_outputs import (
|
| 36 |
+
BaseModelOutput,
|
| 37 |
+
MaskedLMOutput,
|
| 38 |
+
SequenceClassifierOutput,
|
| 39 |
+
TokenClassifierOutput,
|
| 40 |
+
)
|
| 41 |
+
from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
|
| 42 |
+
from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
|
| 43 |
+
from transformers.processing_utils import Unpack
|
| 44 |
+
from transformers.utils import TransformersKwargs
|
| 45 |
+
|
| 46 |
+
from .configuration_nandi_encoder import NandiEncoderConfig
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
class NandiRMSNorm(nn.Module):
|
| 50 |
+
def __init__(self, hidden_size, eps=1e-5):
|
| 51 |
+
super().__init__()
|
| 52 |
+
self.weight = nn.Parameter(torch.ones(hidden_size))
|
| 53 |
+
self.variance_epsilon = eps
|
| 54 |
+
|
| 55 |
+
def forward(self, hidden_states):
|
| 56 |
+
# fp32 normalize AND weight multiply, then cast: matches flash-attn's Triton RMSNorm used in training
|
| 57 |
+
input_dtype = hidden_states.dtype
|
| 58 |
+
hidden_states = hidden_states.to(torch.float32)
|
| 59 |
+
variance = hidden_states.pow(2).mean(-1, keepdim=True)
|
| 60 |
+
hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
|
| 61 |
+
return (self.weight.float() * hidden_states).to(input_dtype)
|
| 62 |
+
|
| 63 |
+
def extra_repr(self):
|
| 64 |
+
return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
class NandiRotaryEmbedding(nn.Module):
|
| 68 |
+
inv_freq: torch.Tensor
|
| 69 |
+
|
| 70 |
+
def __init__(self, config: NandiEncoderConfig, device=None):
|
| 71 |
+
super().__init__()
|
| 72 |
+
self.max_seq_len_cached = config.max_position_embeddings
|
| 73 |
+
self.original_max_seq_len = config.max_position_embeddings
|
| 74 |
+
self.config = config
|
| 75 |
+
self.rope_type = self.config.rope_parameters.get("rope_type", "default")
|
| 76 |
+
rope_init_fn: Callable = self.compute_default_rope_parameters
|
| 77 |
+
if self.rope_type != "default":
|
| 78 |
+
rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
|
| 79 |
+
inv_freq, self.attention_scaling = rope_init_fn(self.config, device)
|
| 80 |
+
self.register_buffer("inv_freq", inv_freq, persistent=False)
|
| 81 |
+
self.register_buffer("original_inv_freq", inv_freq.clone(), persistent=False)
|
| 82 |
+
|
| 83 |
+
@staticmethod
|
| 84 |
+
def compute_default_rope_parameters(config=None, device=None, seq_len=None):
|
| 85 |
+
del seq_len
|
| 86 |
+
base = config.rope_parameters["rope_theta"]
|
| 87 |
+
dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads
|
| 88 |
+
inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2, dtype=torch.int64).to(device=device, dtype=torch.float) / dim))
|
| 89 |
+
return inv_freq, 1.0
|
| 90 |
+
|
| 91 |
+
@torch.no_grad()
|
| 92 |
+
@dynamic_rope_update
|
| 93 |
+
def forward(self, x, position_ids):
|
| 94 |
+
inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
|
| 95 |
+
position_ids_expanded = position_ids[:, None, :].float()
|
| 96 |
+
device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
|
| 97 |
+
with torch.autocast(device_type=device_type, enabled=False):
|
| 98 |
+
freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
|
| 99 |
+
emb = torch.cat((freqs, freqs), dim=-1)
|
| 100 |
+
cos = emb.cos() * self.attention_scaling
|
| 101 |
+
sin = emb.sin() * self.attention_scaling
|
| 102 |
+
return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def rotate_half(x):
|
| 106 |
+
x1 = x[..., : x.shape[-1] // 2]
|
| 107 |
+
x2 = x[..., x.shape[-1] // 2 :]
|
| 108 |
+
return torch.cat((-x2, x1), dim=-1)
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
def apply_rotary_pos_emb(q, k, cos, sin, unsqueeze_dim=1):
|
| 112 |
+
cos = cos.unsqueeze(unsqueeze_dim)
|
| 113 |
+
sin = sin.unsqueeze(unsqueeze_dim)
|
| 114 |
+
return (q * cos) + (rotate_half(q) * sin), (k * cos) + (rotate_half(k) * sin)
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
|
| 118 |
+
batch, num_key_value_heads, slen, head_dim = hidden_states.shape
|
| 119 |
+
if n_rep == 1:
|
| 120 |
+
return hidden_states
|
| 121 |
+
hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
|
| 122 |
+
return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
def eager_attention_forward(
|
| 126 |
+
module: nn.Module,
|
| 127 |
+
query: torch.Tensor,
|
| 128 |
+
key: torch.Tensor,
|
| 129 |
+
value: torch.Tensor,
|
| 130 |
+
attention_mask: torch.Tensor | None,
|
| 131 |
+
scaling: float,
|
| 132 |
+
dropout: float = 0.0,
|
| 133 |
+
**kwargs,
|
| 134 |
+
):
|
| 135 |
+
del kwargs
|
| 136 |
+
key_states = repeat_kv(key, module.num_key_value_groups)
|
| 137 |
+
value_states = repeat_kv(value, module.num_key_value_groups)
|
| 138 |
+
attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
|
| 139 |
+
if attention_mask is not None:
|
| 140 |
+
attn_weights = attn_weights + attention_mask[:, :, :, : key_states.shape[-2]]
|
| 141 |
+
attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
|
| 142 |
+
attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
|
| 143 |
+
attn_output = torch.matmul(attn_weights, value_states)
|
| 144 |
+
return attn_output.transpose(1, 2).contiguous(), attn_weights
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
class NandiEncoderAttention(nn.Module):
|
| 148 |
+
"""GQA self-attention with RoPE. Bidirectional: every token attends to every non-padding token."""
|
| 149 |
+
|
| 150 |
+
def __init__(self, config: NandiEncoderConfig, layer_idx: int):
|
| 151 |
+
super().__init__()
|
| 152 |
+
self.config = config
|
| 153 |
+
self.layer_idx = layer_idx
|
| 154 |
+
self.head_dim = config.head_dim
|
| 155 |
+
self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
|
| 156 |
+
self.scaling = self.head_dim**-0.5
|
| 157 |
+
self.attention_dropout = config.attention_dropout
|
| 158 |
+
self.is_causal = False
|
| 159 |
+
|
| 160 |
+
self.q_proj = nn.Linear(config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias)
|
| 161 |
+
self.k_proj = nn.Linear(config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias)
|
| 162 |
+
self.v_proj = nn.Linear(config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias)
|
| 163 |
+
self.o_proj = nn.Linear(config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.attention_bias)
|
| 164 |
+
self.qk_norm = getattr(config, "qk_norm", False)
|
| 165 |
+
if self.qk_norm:
|
| 166 |
+
self.q_norm = NandiRMSNorm(self.head_dim, eps=config.rms_norm_eps)
|
| 167 |
+
self.k_norm = NandiRMSNorm(self.head_dim, eps=config.rms_norm_eps)
|
| 168 |
+
|
| 169 |
+
def forward(
|
| 170 |
+
self,
|
| 171 |
+
hidden_states: torch.Tensor,
|
| 172 |
+
position_embeddings: tuple[torch.Tensor, torch.Tensor],
|
| 173 |
+
attention_mask: torch.Tensor | None,
|
| 174 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 175 |
+
) -> tuple[torch.Tensor, torch.Tensor]:
|
| 176 |
+
input_shape = hidden_states.shape[:-1]
|
| 177 |
+
hidden_shape = (*input_shape, -1, self.head_dim)
|
| 178 |
+
|
| 179 |
+
query_states = self.q_proj(hidden_states).view(hidden_shape)
|
| 180 |
+
key_states = self.k_proj(hidden_states).view(hidden_shape)
|
| 181 |
+
if self.qk_norm: # per head over head_dim, before RoPE (as in training)
|
| 182 |
+
query_states = self.q_norm(query_states)
|
| 183 |
+
key_states = self.k_norm(key_states)
|
| 184 |
+
query_states = query_states.transpose(1, 2)
|
| 185 |
+
key_states = key_states.transpose(1, 2)
|
| 186 |
+
value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
|
| 187 |
+
|
| 188 |
+
cos, sin = position_embeddings
|
| 189 |
+
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
|
| 190 |
+
|
| 191 |
+
attention_interface: Callable = eager_attention_forward
|
| 192 |
+
if self.config._attn_implementation != "eager":
|
| 193 |
+
attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
|
| 194 |
+
|
| 195 |
+
attn_output, attn_weights = attention_interface(
|
| 196 |
+
self,
|
| 197 |
+
query_states,
|
| 198 |
+
key_states,
|
| 199 |
+
value_states,
|
| 200 |
+
attention_mask,
|
| 201 |
+
dropout=0.0 if not self.training else self.attention_dropout,
|
| 202 |
+
scaling=self.scaling,
|
| 203 |
+
is_causal=False,
|
| 204 |
+
**kwargs,
|
| 205 |
+
)
|
| 206 |
+
attn_output = attn_output.reshape(*input_shape, -1).contiguous()
|
| 207 |
+
return self.o_proj(attn_output), attn_weights
|
| 208 |
+
|
| 209 |
+
|
| 210 |
+
class NandiMLP(nn.Module):
|
| 211 |
+
def __init__(self, config):
|
| 212 |
+
super().__init__()
|
| 213 |
+
self.gate_proj = nn.Linear(config.hidden_size, config.intermediate_size, bias=config.mlp_bias)
|
| 214 |
+
self.up_proj = nn.Linear(config.hidden_size, config.intermediate_size, bias=config.mlp_bias)
|
| 215 |
+
self.down_proj = nn.Linear(config.intermediate_size, config.hidden_size, bias=config.mlp_bias)
|
| 216 |
+
self.act_fn = ACT2FN[config.hidden_act]
|
| 217 |
+
|
| 218 |
+
def forward(self, x):
|
| 219 |
+
return self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
|
| 220 |
+
|
| 221 |
+
|
| 222 |
+
class NandiEncoderLayer(GradientCheckpointingLayer):
|
| 223 |
+
def __init__(self, config: NandiEncoderConfig, layer_idx: int):
|
| 224 |
+
super().__init__()
|
| 225 |
+
self.hidden_size = config.hidden_size
|
| 226 |
+
self.self_attn = NandiEncoderAttention(config=config, layer_idx=layer_idx)
|
| 227 |
+
self.mlp = NandiMLP(config)
|
| 228 |
+
self.input_layernorm = NandiRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
| 229 |
+
self.post_attention_layernorm = NandiRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
| 230 |
+
|
| 231 |
+
def forward(
|
| 232 |
+
self,
|
| 233 |
+
hidden_states: torch.Tensor,
|
| 234 |
+
attention_mask: torch.Tensor | None = None,
|
| 235 |
+
position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
|
| 236 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 237 |
+
) -> torch.Tensor:
|
| 238 |
+
residual = hidden_states
|
| 239 |
+
hidden_states, _ = self.self_attn(
|
| 240 |
+
hidden_states=self.input_layernorm(hidden_states),
|
| 241 |
+
attention_mask=attention_mask,
|
| 242 |
+
position_embeddings=position_embeddings,
|
| 243 |
+
**kwargs,
|
| 244 |
+
)
|
| 245 |
+
hidden_states = residual + hidden_states
|
| 246 |
+
residual = hidden_states
|
| 247 |
+
hidden_states = residual + self.mlp(self.post_attention_layernorm(hidden_states))
|
| 248 |
+
return hidden_states
|
| 249 |
+
|
| 250 |
+
|
| 251 |
+
class NandiEncoderPreTrainedModel(PreTrainedModel):
|
| 252 |
+
config_class = NandiEncoderConfig
|
| 253 |
+
config: NandiEncoderConfig
|
| 254 |
+
base_model_prefix = "model"
|
| 255 |
+
supports_gradient_checkpointing = True
|
| 256 |
+
_no_split_modules = ["NandiEncoderLayer"]
|
| 257 |
+
_supports_flash_attn = False # untested with bidirectional masks; use "sdpa" (default) or "eager"
|
| 258 |
+
_supports_sdpa = True
|
| 259 |
+
_supports_flex_attn = False
|
| 260 |
+
_supports_attention_backend = False
|
| 261 |
+
|
| 262 |
+
|
| 263 |
+
class NandiEncoderModel(NandiEncoderPreTrainedModel):
|
| 264 |
+
"""Bare encoder. `last_hidden_state` is after the final RMSNorm (what the MLM head and classifiers see)."""
|
| 265 |
+
|
| 266 |
+
def __init__(self, config: NandiEncoderConfig):
|
| 267 |
+
super().__init__(config)
|
| 268 |
+
self.vocab_size = config.vocab_size
|
| 269 |
+
embedding_dim = config.embedding_rank if config.factorized_embedding else config.hidden_size
|
| 270 |
+
# No padding_idx, as in training (the pad row gets gradients like any other token)
|
| 271 |
+
self.embed_tokens = nn.Embedding(config.vocab_size, embedding_dim)
|
| 272 |
+
self.embedding_proj = (
|
| 273 |
+
nn.Linear(config.embedding_rank, config.hidden_size, bias=False) if config.factorized_embedding else None
|
| 274 |
+
)
|
| 275 |
+
self.layers = nn.ModuleList([NandiEncoderLayer(config, i) for i in range(config.num_hidden_layers)])
|
| 276 |
+
self.norm = NandiRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
| 277 |
+
self.rotary_emb = NandiRotaryEmbedding(config=config)
|
| 278 |
+
self.gradient_checkpointing = False
|
| 279 |
+
self.post_init()
|
| 280 |
+
|
| 281 |
+
def get_input_embeddings(self):
|
| 282 |
+
return self.embed_tokens
|
| 283 |
+
|
| 284 |
+
def set_input_embeddings(self, value):
|
| 285 |
+
self.embed_tokens = value
|
| 286 |
+
|
| 287 |
+
def forward(
|
| 288 |
+
self,
|
| 289 |
+
input_ids: torch.LongTensor | None = None,
|
| 290 |
+
attention_mask: torch.Tensor | None = None,
|
| 291 |
+
position_ids: torch.LongTensor | None = None,
|
| 292 |
+
inputs_embeds: torch.FloatTensor | None = None,
|
| 293 |
+
output_hidden_states: bool | None = None,
|
| 294 |
+
return_dict: bool | None = None,
|
| 295 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 296 |
+
) -> BaseModelOutput:
|
| 297 |
+
if (input_ids is None) ^ (inputs_embeds is not None):
|
| 298 |
+
raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
|
| 299 |
+
output_hidden_states = (
|
| 300 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 301 |
+
)
|
| 302 |
+
if inputs_embeds is None:
|
| 303 |
+
inputs_embeds = self.embed_tokens(input_ids)
|
| 304 |
+
if self.embedding_proj is not None:
|
| 305 |
+
inputs_embeds = self.embedding_proj(inputs_embeds)
|
| 306 |
+
|
| 307 |
+
if position_ids is None:
|
| 308 |
+
# RoPE is relative, so any per-row offset (e.g. left padding) gives the same attention scores
|
| 309 |
+
position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device).unsqueeze(0)
|
| 310 |
+
|
| 311 |
+
bidirectional_mask = create_bidirectional_mask(
|
| 312 |
+
config=self.config, inputs_embeds=inputs_embeds, attention_mask=attention_mask
|
| 313 |
+
)
|
| 314 |
+
|
| 315 |
+
hidden_states = inputs_embeds
|
| 316 |
+
position_embeddings = self.rotary_emb(hidden_states, position_ids=position_ids)
|
| 317 |
+
all_hidden_states = (hidden_states,) if output_hidden_states else None
|
| 318 |
+
|
| 319 |
+
# Shared layers run back to back (layer 0, layer 0, layer 1, layer 1, ...), exactly as in training
|
| 320 |
+
repeats = self.config.layer_sharing_repeats if self.config.layer_sharing else 1
|
| 321 |
+
for layer in self.layers[: self.config.num_hidden_layers]:
|
| 322 |
+
for _ in range(repeats):
|
| 323 |
+
hidden_states = layer(
|
| 324 |
+
hidden_states,
|
| 325 |
+
attention_mask=bidirectional_mask,
|
| 326 |
+
position_embeddings=position_embeddings,
|
| 327 |
+
**kwargs,
|
| 328 |
+
)
|
| 329 |
+
if output_hidden_states:
|
| 330 |
+
all_hidden_states += (hidden_states,)
|
| 331 |
+
|
| 332 |
+
hidden_states = self.norm(hidden_states)
|
| 333 |
+
return BaseModelOutput(last_hidden_state=hidden_states, hidden_states=all_hidden_states)
|
| 334 |
+
|
| 335 |
+
|
| 336 |
+
class NandiPredictionHead(nn.Module):
|
| 337 |
+
"""`mlm_head: dense`: dense -> activation -> RMSNorm between the encoder's final norm and the decoder."""
|
| 338 |
+
|
| 339 |
+
def __init__(self, config):
|
| 340 |
+
super().__init__()
|
| 341 |
+
self.dense = nn.Linear(config.hidden_size, config.hidden_size, bias=False)
|
| 342 |
+
self.act = ACT2FN[config.mlm_head_act]
|
| 343 |
+
self.norm = NandiRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
| 344 |
+
|
| 345 |
+
def forward(self, hidden_states):
|
| 346 |
+
return self.norm(self.act(self.dense(hidden_states)))
|
| 347 |
+
|
| 348 |
+
|
| 349 |
+
class NandiForMaskedLM(NandiEncoderPreTrainedModel):
|
| 350 |
+
"""Masked LM head = the pretrained LM head: final norm (in the encoder) -> lm_head_proj -> tied lm_head."""
|
| 351 |
+
|
| 352 |
+
_tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"}
|
| 353 |
+
|
| 354 |
+
def __init__(self, config: NandiEncoderConfig):
|
| 355 |
+
super().__init__(config)
|
| 356 |
+
self.model = NandiEncoderModel(config)
|
| 357 |
+
self.vocab_size = config.vocab_size
|
| 358 |
+
if getattr(config, "mlm_head", "tied_factorized") == "dense":
|
| 359 |
+
# dense -> act -> RMSNorm, then an untied full-width decoder
|
| 360 |
+
self.head = NandiPredictionHead(config)
|
| 361 |
+
self.lm_head_proj = None
|
| 362 |
+
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=config.mlm_head_decoder_bias)
|
| 363 |
+
else:
|
| 364 |
+
self.head = None
|
| 365 |
+
lm_head_in = config.embedding_rank if config.factorized_embedding else config.hidden_size
|
| 366 |
+
self.lm_head_proj = (
|
| 367 |
+
nn.Linear(config.hidden_size, config.embedding_rank, bias=False) if config.factorized_embedding else None
|
| 368 |
+
)
|
| 369 |
+
self.lm_head = nn.Linear(lm_head_in, config.vocab_size, bias=False)
|
| 370 |
+
self.post_init()
|
| 371 |
+
|
| 372 |
+
def get_output_embeddings(self):
|
| 373 |
+
return self.lm_head
|
| 374 |
+
|
| 375 |
+
def set_output_embeddings(self, new_embeddings):
|
| 376 |
+
self.lm_head = new_embeddings
|
| 377 |
+
|
| 378 |
+
def forward(
|
| 379 |
+
self,
|
| 380 |
+
input_ids: torch.LongTensor | None = None,
|
| 381 |
+
attention_mask: torch.Tensor | None = None,
|
| 382 |
+
position_ids: torch.LongTensor | None = None,
|
| 383 |
+
inputs_embeds: torch.FloatTensor | None = None,
|
| 384 |
+
labels: torch.LongTensor | None = None,
|
| 385 |
+
output_hidden_states: bool | None = None,
|
| 386 |
+
return_dict: bool | None = None,
|
| 387 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 388 |
+
) -> MaskedLMOutput:
|
| 389 |
+
outputs = self.model(
|
| 390 |
+
input_ids=input_ids,
|
| 391 |
+
attention_mask=attention_mask,
|
| 392 |
+
position_ids=position_ids,
|
| 393 |
+
inputs_embeds=inputs_embeds,
|
| 394 |
+
output_hidden_states=output_hidden_states,
|
| 395 |
+
**kwargs,
|
| 396 |
+
)
|
| 397 |
+
hidden_states = outputs.last_hidden_state
|
| 398 |
+
if self.head is not None:
|
| 399 |
+
hidden_states = self.head(hidden_states)
|
| 400 |
+
if self.lm_head_proj is not None:
|
| 401 |
+
hidden_states = self.lm_head_proj(hidden_states)
|
| 402 |
+
logits = self.lm_head(hidden_states)
|
| 403 |
+
|
| 404 |
+
loss = None
|
| 405 |
+
if labels is not None: # -100 = not predicted
|
| 406 |
+
loss = nn.functional.cross_entropy(
|
| 407 |
+
logits.float().view(-1, self.vocab_size), labels.to(logits.device).view(-1), ignore_index=-100
|
| 408 |
+
)
|
| 409 |
+
return MaskedLMOutput(loss=loss, logits=logits, hidden_states=outputs.hidden_states)
|
| 410 |
+
|
| 411 |
+
|
| 412 |
+
def _pool(hidden_states: torch.Tensor, attention_mask: torch.Tensor | None, pooling: str) -> torch.Tensor:
|
| 413 |
+
if pooling == "first": # the <|endoftext|> every input starts with
|
| 414 |
+
return hidden_states[:, 0]
|
| 415 |
+
if attention_mask is None:
|
| 416 |
+
return hidden_states.mean(dim=1)
|
| 417 |
+
mask = attention_mask.to(hidden_states.dtype).unsqueeze(-1)
|
| 418 |
+
return (hidden_states * mask).sum(dim=1) / mask.sum(dim=1).clamp(min=1.0)
|
| 419 |
+
|
| 420 |
+
|
| 421 |
+
class NandiForSequenceClassification(NandiEncoderPreTrainedModel):
|
| 422 |
+
"""Pooled encoder output (`config.classifier_pooling`) -> dropout -> linear. The head is newly initialized."""
|
| 423 |
+
|
| 424 |
+
def __init__(self, config: NandiEncoderConfig):
|
| 425 |
+
super().__init__(config)
|
| 426 |
+
self.num_labels = config.num_labels
|
| 427 |
+
self.model = NandiEncoderModel(config)
|
| 428 |
+
self.dropout = nn.Dropout(config.classifier_dropout)
|
| 429 |
+
self.classifier = nn.Linear(config.hidden_size, config.num_labels)
|
| 430 |
+
self.post_init()
|
| 431 |
+
|
| 432 |
+
def forward(
|
| 433 |
+
self,
|
| 434 |
+
input_ids: torch.LongTensor | None = None,
|
| 435 |
+
attention_mask: torch.Tensor | None = None,
|
| 436 |
+
position_ids: torch.LongTensor | None = None,
|
| 437 |
+
inputs_embeds: torch.FloatTensor | None = None,
|
| 438 |
+
labels: torch.LongTensor | None = None,
|
| 439 |
+
output_hidden_states: bool | None = None,
|
| 440 |
+
return_dict: bool | None = None,
|
| 441 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 442 |
+
) -> SequenceClassifierOutput:
|
| 443 |
+
outputs = self.model(
|
| 444 |
+
input_ids=input_ids,
|
| 445 |
+
attention_mask=attention_mask,
|
| 446 |
+
position_ids=position_ids,
|
| 447 |
+
inputs_embeds=inputs_embeds,
|
| 448 |
+
output_hidden_states=output_hidden_states,
|
| 449 |
+
**kwargs,
|
| 450 |
+
)
|
| 451 |
+
pooled = _pool(outputs.last_hidden_state, attention_mask, self.config.classifier_pooling)
|
| 452 |
+
logits = self.classifier(self.dropout(pooled))
|
| 453 |
+
|
| 454 |
+
loss = None
|
| 455 |
+
if labels is not None:
|
| 456 |
+
labels = labels.to(logits.device)
|
| 457 |
+
if self.config.problem_type is None:
|
| 458 |
+
if self.num_labels == 1:
|
| 459 |
+
self.config.problem_type = "regression"
|
| 460 |
+
elif labels.dtype in (torch.long, torch.int):
|
| 461 |
+
self.config.problem_type = "single_label_classification"
|
| 462 |
+
else:
|
| 463 |
+
self.config.problem_type = "multi_label_classification"
|
| 464 |
+
if self.config.problem_type == "regression":
|
| 465 |
+
loss = MSELoss()(logits.squeeze(), labels.squeeze().to(logits.dtype)) if self.num_labels == 1 else MSELoss()(logits, labels)
|
| 466 |
+
elif self.config.problem_type == "single_label_classification":
|
| 467 |
+
loss = CrossEntropyLoss()(logits.view(-1, self.num_labels), labels.view(-1))
|
| 468 |
+
else:
|
| 469 |
+
loss = BCEWithLogitsLoss()(logits, labels.to(logits.dtype))
|
| 470 |
+
return SequenceClassifierOutput(loss=loss, logits=logits, hidden_states=outputs.hidden_states)
|
| 471 |
+
|
| 472 |
+
|
| 473 |
+
class NandiForTokenClassification(NandiEncoderPreTrainedModel):
|
| 474 |
+
"""Per-token encoder output -> dropout -> linear. The head is newly initialized."""
|
| 475 |
+
|
| 476 |
+
def __init__(self, config: NandiEncoderConfig):
|
| 477 |
+
super().__init__(config)
|
| 478 |
+
self.num_labels = config.num_labels
|
| 479 |
+
self.model = NandiEncoderModel(config)
|
| 480 |
+
self.dropout = nn.Dropout(config.classifier_dropout)
|
| 481 |
+
self.classifier = nn.Linear(config.hidden_size, config.num_labels)
|
| 482 |
+
self.post_init()
|
| 483 |
+
|
| 484 |
+
def forward(
|
| 485 |
+
self,
|
| 486 |
+
input_ids: torch.LongTensor | None = None,
|
| 487 |
+
attention_mask: torch.Tensor | None = None,
|
| 488 |
+
position_ids: torch.LongTensor | None = None,
|
| 489 |
+
inputs_embeds: torch.FloatTensor | None = None,
|
| 490 |
+
labels: torch.LongTensor | None = None,
|
| 491 |
+
output_hidden_states: bool | None = None,
|
| 492 |
+
return_dict: bool | None = None,
|
| 493 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 494 |
+
) -> TokenClassifierOutput:
|
| 495 |
+
outputs = self.model(
|
| 496 |
+
input_ids=input_ids,
|
| 497 |
+
attention_mask=attention_mask,
|
| 498 |
+
position_ids=position_ids,
|
| 499 |
+
inputs_embeds=inputs_embeds,
|
| 500 |
+
output_hidden_states=output_hidden_states,
|
| 501 |
+
**kwargs,
|
| 502 |
+
)
|
| 503 |
+
logits = self.classifier(self.dropout(outputs.last_hidden_state))
|
| 504 |
+
loss = None
|
| 505 |
+
if labels is not None:
|
| 506 |
+
loss = CrossEntropyLoss()(logits.view(-1, self.num_labels), labels.to(logits.device).view(-1))
|
| 507 |
+
return TokenClassifierOutput(loss=loss, logits=logits, hidden_states=outputs.hidden_states)
|
| 508 |
+
|
| 509 |
+
|
| 510 |
+
__all__ = [
|
| 511 |
+
"NandiEncoderPreTrainedModel",
|
| 512 |
+
"NandiEncoderModel",
|
| 513 |
+
"NandiForMaskedLM",
|
| 514 |
+
"NandiForSequenceClassification",
|
| 515 |
+
"NandiForTokenClassification",
|
| 516 |
+
]
|
tokenization_nandi_encoder.py
ADDED
|
@@ -0,0 +1,126 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2026 FrontiersMind. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
"""Tokenizer of the Nandi encoder: the Nandi BPE tokenizer, with `<|endoftext|>` prepended to every input
|
| 15 |
+
(`add_special_tokens=True`, the default) because every training document started with it. Unlike the decoder
|
| 16 |
+
tokenizer, no `<|im_start|>` and no extra space are added."""
|
| 17 |
+
|
| 18 |
+
import re
|
| 19 |
+
|
| 20 |
+
from tokenizers import Regex, Tokenizer, decoders, normalizers, pre_tokenizers
|
| 21 |
+
from tokenizers.models import BPE
|
| 22 |
+
|
| 23 |
+
from transformers.tokenization_utils_tokenizers import TokenizersBackend
|
| 24 |
+
from transformers.utils import logging
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
logger = logging.get_logger(__name__)
|
| 28 |
+
|
| 29 |
+
PRETOKENIZE_REGEX = r"""(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\r\n\p{L}\p{N}]?(?:\p{L}\p{M}*)+|\p{N}| ?[^\s\p{L}\p{N}]+[\r\n]*|\s*[\r\n]+|\s+(?!\S)|\s+"""
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
# Training replaced a masked word *token* (which carries its own leading space, e.g. " Paris") by <|mask|>, so a mask never
|
| 33 |
+
# has a separate space token in front of it, while newlines / indentation before a word stay as their own tokens.
|
| 34 |
+
# To get the same ids from natural text ("is <|mask|>."), exactly ONE space directly before <|mask|> is absorbed.
|
| 35 |
+
# (The mask is NOT lstrip: that would also swallow newlines and indentation, which training keeps.)
|
| 36 |
+
_SPACE_BEFORE_MASK = re.compile(r" (?=<\|mask\|>)")
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def _absorb_space_before_mask(x):
|
| 40 |
+
if isinstance(x, str):
|
| 41 |
+
return _SPACE_BEFORE_MASK.sub("", x)
|
| 42 |
+
if isinstance(x, list) and all(isinstance(i, str) for i in x):
|
| 43 |
+
return [_SPACE_BEFORE_MASK.sub("", i) for i in x]
|
| 44 |
+
return x
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
class NandiEncoderTokenizer(TokenizersBackend):
|
| 48 |
+
model_input_names = ["input_ids", "attention_mask"]
|
| 49 |
+
model = BPE
|
| 50 |
+
|
| 51 |
+
def _encode_plus(self, text, text_pair=None, *args, is_split_into_words=False, **kwargs):
|
| 52 |
+
if not is_split_into_words:
|
| 53 |
+
text, text_pair = _absorb_space_before_mask(text), _absorb_space_before_mask(text_pair)
|
| 54 |
+
return super()._encode_plus(text, text_pair, *args, is_split_into_words=is_split_into_words, **kwargs)
|
| 55 |
+
|
| 56 |
+
def __init__(
|
| 57 |
+
self,
|
| 58 |
+
vocab: str | dict[str, int] | None = None,
|
| 59 |
+
merges: str | list[str] | None = None,
|
| 60 |
+
vocab_file=None,
|
| 61 |
+
merges_file=None,
|
| 62 |
+
unk_token: str = "<|endoftext|>",
|
| 63 |
+
bos_token: str = "<|endoftext|>",
|
| 64 |
+
eos_token: str = "<|endoftext|>",
|
| 65 |
+
pad_token: str = "<|pad|>",
|
| 66 |
+
mask_token: str = "<|mask|>",
|
| 67 |
+
add_prefix_space: bool | None = None,
|
| 68 |
+
**kwargs,
|
| 69 |
+
):
|
| 70 |
+
self._vocab = (
|
| 71 |
+
vocab
|
| 72 |
+
if vocab is not None
|
| 73 |
+
else {
|
| 74 |
+
"<|endoftext|>": 0,
|
| 75 |
+
}
|
| 76 |
+
)
|
| 77 |
+
self._merges = merges or []
|
| 78 |
+
|
| 79 |
+
self._tokenizer = Tokenizer(
|
| 80 |
+
BPE(
|
| 81 |
+
vocab=self._vocab,
|
| 82 |
+
merges=self._merges,
|
| 83 |
+
dropout=None,
|
| 84 |
+
unk_token=None,
|
| 85 |
+
continuing_subword_prefix="",
|
| 86 |
+
end_of_word_suffix="",
|
| 87 |
+
fuse_unk=False,
|
| 88 |
+
byte_fallback=False,
|
| 89 |
+
)
|
| 90 |
+
)
|
| 91 |
+
self._tokenizer.decoder = decoders.ByteLevel()
|
| 92 |
+
self._tokenizer.normalizer = normalizers.NFC()
|
| 93 |
+
self._tokenizer.pre_tokenizer = pre_tokenizers.Sequence(
|
| 94 |
+
[
|
| 95 |
+
pre_tokenizers.Split(
|
| 96 |
+
Regex(PRETOKENIZE_REGEX),
|
| 97 |
+
behavior="isolated",
|
| 98 |
+
invert=False,
|
| 99 |
+
),
|
| 100 |
+
pre_tokenizers.ByteLevel(
|
| 101 |
+
add_prefix_space=False,
|
| 102 |
+
trim_offsets=True,
|
| 103 |
+
use_regex=False
|
| 104 |
+
),
|
| 105 |
+
]
|
| 106 |
+
)
|
| 107 |
+
|
| 108 |
+
# Every training document started with <|endoftext|> (the bos_token here): prepend it by default.
|
| 109 |
+
# Passed explicitly so TokenizersBackend builds the "<|endoftext|> $A" post-processor.
|
| 110 |
+
kwargs["add_bos_token"] = kwargs.get("add_bos_token", True)
|
| 111 |
+
kwargs["add_eos_token"] = kwargs.get("add_eos_token", False)
|
| 112 |
+
|
| 113 |
+
super().__init__(
|
| 114 |
+
vocab_file=vocab_file,
|
| 115 |
+
merges_file=merges_file,
|
| 116 |
+
unk_token=unk_token,
|
| 117 |
+
bos_token=bos_token,
|
| 118 |
+
eos_token=eos_token,
|
| 119 |
+
pad_token=pad_token,
|
| 120 |
+
mask_token=mask_token,
|
| 121 |
+
add_prefix_space=add_prefix_space,
|
| 122 |
+
**kwargs,
|
| 123 |
+
)
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
__all__ = ["NandiEncoderTokenizer"]
|
tokenizer.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
tokenizer_config.json
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"add_prefix_space": null,
|
| 3 |
+
"auto_map": {
|
| 4 |
+
"AutoTokenizer": [
|
| 5 |
+
"tokenization_nandi_encoder.NandiEncoderTokenizer",
|
| 6 |
+
null
|
| 7 |
+
]
|
| 8 |
+
},
|
| 9 |
+
"backend": "tokenizers",
|
| 10 |
+
"bos_token": "<|endoftext|>",
|
| 11 |
+
"bos_token_id": 0,
|
| 12 |
+
"eos_token": "<|endoftext|>",
|
| 13 |
+
"eos_token_id": 0,
|
| 14 |
+
"is_local": true,
|
| 15 |
+
"local_files_only": false,
|
| 16 |
+
"mask_token": "<|mask|>",
|
| 17 |
+
"mask_token_id": 4,
|
| 18 |
+
"merges_file": null,
|
| 19 |
+
"model_max_length": 32768,
|
| 20 |
+
"pad_token": "<|pad|>",
|
| 21 |
+
"pad_token_id": 3,
|
| 22 |
+
"tokenizer_class": "NandiEncoderTokenizer",
|
| 23 |
+
"unk_token": "<|endoftext|>"
|
| 24 |
+
}
|