Instructions to use FrontiersMind/Nandi-Mini-600M-Early-Checkpoint with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use FrontiersMind/Nandi-Mini-600M-Early-Checkpoint with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("text-generation", model="FrontiersMind/Nandi-Mini-600M-Early-Checkpoint", trust_remote_code=True)# Load model directly from transformers import AutoModelForCausalLM model = AutoModelForCausalLM.from_pretrained("FrontiersMind/Nandi-Mini-600M-Early-Checkpoint", trust_remote_code=True, dtype="auto") - Notebooks
- Google Colab
- Kaggle
- Local Apps
- vLLM
How to use FrontiersMind/Nandi-Mini-600M-Early-Checkpoint with vLLM:
Install from pip and serve model
# Install vLLM from pip: pip install vllm # Start the vLLM server: vllm serve "FrontiersMind/Nandi-Mini-600M-Early-Checkpoint" # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:8000/v1/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "FrontiersMind/Nandi-Mini-600M-Early-Checkpoint", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }'Use Docker
docker model run hf.co/FrontiersMind/Nandi-Mini-600M-Early-Checkpoint
- SGLang
How to use FrontiersMind/Nandi-Mini-600M-Early-Checkpoint with SGLang:
Install from pip and serve model
# Install SGLang from pip: pip install sglang # Start the SGLang server: python3 -m sglang.launch_server \ --model-path "FrontiersMind/Nandi-Mini-600M-Early-Checkpoint" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "FrontiersMind/Nandi-Mini-600M-Early-Checkpoint", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }'Use Docker images
docker run --gpus all \ --shm-size 32g \ -p 30000:30000 \ -v ~/.cache/huggingface:/root/.cache/huggingface \ --env "HF_TOKEN=<secret>" \ --ipc=host \ lmsysorg/sglang:latest \ python3 -m sglang.launch_server \ --model-path "FrontiersMind/Nandi-Mini-600M-Early-Checkpoint" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "FrontiersMind/Nandi-Mini-600M-Early-Checkpoint", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }' - Docker Model Runner
How to use FrontiersMind/Nandi-Mini-600M-Early-Checkpoint with Docker Model Runner:
docker model run hf.co/FrontiersMind/Nandi-Mini-600M-Early-Checkpoint
Upload 8 files
Browse files- .gitattributes +1 -0
- config.json +41 -0
- configuration_nandi.py +147 -0
- convert_smoltron_to_hf.py +320 -0
- model.safetensors +3 -0
- modeling_nandi.py +533 -0
- tokenization_nandi.py +143 -0
- tokenizer.json +3 -0
- tokenizer_config.json +15 -0
.gitattributes
CHANGED
|
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
| 36 |
+
tokenizer.json filter=lfs diff=lfs merge=lfs -text
|
config.json
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"architectures": [
|
| 3 |
+
"NandiForCausalLM"
|
| 4 |
+
],
|
| 5 |
+
"auto_map": {
|
| 6 |
+
"AutoConfig": "configuration_nandi.NandiConfig",
|
| 7 |
+
"AutoModel": "modeling_nandi.NandiModel",
|
| 8 |
+
"AutoModelForCausalLM": "modeling_nandi.NandiForCausalLM"
|
| 9 |
+
},
|
| 10 |
+
"model_type": "nandi",
|
| 11 |
+
"vocab_size": 131072,
|
| 12 |
+
"hidden_size": 1248,
|
| 13 |
+
"intermediate_size": 3556,
|
| 14 |
+
"num_hidden_layers": 28,
|
| 15 |
+
"num_attention_heads": 16,
|
| 16 |
+
"num_key_value_heads": 8,
|
| 17 |
+
"head_dim": 78,
|
| 18 |
+
"hidden_act": "silu",
|
| 19 |
+
"max_position_embeddings": 2048,
|
| 20 |
+
"initializer_range": 0.008,
|
| 21 |
+
"rms_norm_eps": 1e-06,
|
| 22 |
+
"use_cache": true,
|
| 23 |
+
"pad_token_id": null,
|
| 24 |
+
"bos_token_id": 1,
|
| 25 |
+
"eos_token_id": 0,
|
| 26 |
+
"tie_word_embeddings": true,
|
| 27 |
+
"rope_parameters": {
|
| 28 |
+
"rope_theta": 1000000.0
|
| 29 |
+
},
|
| 30 |
+
"attention_bias": false,
|
| 31 |
+
"attention_dropout": 0.0,
|
| 32 |
+
"mlp_bias": false,
|
| 33 |
+
"factorized_embedding": false,
|
| 34 |
+
"embedding_rank": 768,
|
| 35 |
+
"layer_sharing": false,
|
| 36 |
+
"layer_sharing_repeats": 2,
|
| 37 |
+
"qk_norm": true,
|
| 38 |
+
"shared_kv": true,
|
| 39 |
+
"kv_cache_mode": "shared",
|
| 40 |
+
"torch_dtype": "bfloat16"
|
| 41 |
+
}
|
configuration_nandi.py
ADDED
|
@@ -0,0 +1,147 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2026 RTA AI Labs. 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 |
+
|
| 15 |
+
from transformers.configuration_utils import PretrainedConfig
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
class NandiConfig(PretrainedConfig):
|
| 19 |
+
r"""
|
| 20 |
+
Configuration class for the Nandi model.
|
| 21 |
+
|
| 22 |
+
Example:
|
| 23 |
+
|
| 24 |
+
```python
|
| 25 |
+
>>> from transformers import AutoConfig, AutoModelForCausalLM
|
| 26 |
+
|
| 27 |
+
>>> configuration = AutoConfig.from_pretrained("Rta-AILabs/Nandi-500M-remote", trust_remote_code=True)
|
| 28 |
+
|
| 29 |
+
>>> model = AutoModelForCausalLM.from_pretrained("Rta-AILabs/Nandi-500M-remote", trust_remote_code=True)
|
| 30 |
+
|
| 31 |
+
>>> configuration = model.config
|
| 32 |
+
```
|
| 33 |
+
"""
|
| 34 |
+
|
| 35 |
+
model_type = "nandi"
|
| 36 |
+
keys_to_ignore_at_inference = ["past_key_values"]
|
| 37 |
+
|
| 38 |
+
base_model_tp_plan = {
|
| 39 |
+
"layers.*.self_attn.q_proj": "colwise",
|
| 40 |
+
"layers.*.self_attn.k_proj": "colwise",
|
| 41 |
+
"layers.*.self_attn.v_proj": "colwise",
|
| 42 |
+
"layers.*.self_attn.o_proj": "rowwise",
|
| 43 |
+
"layers.*.mlp.gate_proj": "colwise",
|
| 44 |
+
"layers.*.mlp.up_proj": "colwise",
|
| 45 |
+
"layers.*.mlp.down_proj": "rowwise",
|
| 46 |
+
}
|
| 47 |
+
|
| 48 |
+
def __init__(
|
| 49 |
+
self,
|
| 50 |
+
vocab_size=131072,
|
| 51 |
+
hidden_size=1248,
|
| 52 |
+
intermediate_size=3556,
|
| 53 |
+
num_hidden_layers=28,
|
| 54 |
+
num_attention_heads=16,
|
| 55 |
+
num_key_value_heads=8,
|
| 56 |
+
head_dim=None,
|
| 57 |
+
hidden_act="silu",
|
| 58 |
+
max_position_embeddings=2048,
|
| 59 |
+
initializer_range=0.008,
|
| 60 |
+
rms_norm_eps=1e-6,
|
| 61 |
+
use_cache=True,
|
| 62 |
+
pad_token_id=None,
|
| 63 |
+
bos_token_id=1,
|
| 64 |
+
eos_token_id=0,
|
| 65 |
+
pretraining_tp=1,
|
| 66 |
+
tie_word_embeddings=True,
|
| 67 |
+
rope_parameters=None,
|
| 68 |
+
attention_bias=False,
|
| 69 |
+
attention_dropout=0.0,
|
| 70 |
+
mlp_bias=False,
|
| 71 |
+
factorized_embedding=False,
|
| 72 |
+
embedding_rank=768,
|
| 73 |
+
layer_sharing=False,
|
| 74 |
+
layer_sharing_repeats=1,
|
| 75 |
+
qk_norm=True,
|
| 76 |
+
shared_kv=True,
|
| 77 |
+
kv_cache_mode="shared",
|
| 78 |
+
**kwargs,
|
| 79 |
+
):
|
| 80 |
+
self.vocab_size = vocab_size
|
| 81 |
+
self.hidden_size = hidden_size
|
| 82 |
+
self.intermediate_size = intermediate_size
|
| 83 |
+
self.num_hidden_layers = num_hidden_layers
|
| 84 |
+
self.num_attention_heads = num_attention_heads
|
| 85 |
+
self.num_key_value_heads = num_key_value_heads if num_key_value_heads is not None else num_attention_heads
|
| 86 |
+
self.head_dim = head_dim if head_dim is not None else hidden_size // num_attention_heads
|
| 87 |
+
self.hidden_act = hidden_act
|
| 88 |
+
self.max_position_embeddings = max_position_embeddings
|
| 89 |
+
self.initializer_range = initializer_range
|
| 90 |
+
self.rms_norm_eps = rms_norm_eps
|
| 91 |
+
self.use_cache = use_cache
|
| 92 |
+
self.pretraining_tp = pretraining_tp
|
| 93 |
+
self.rope_parameters = rope_parameters if rope_parameters is not None else {"rope_theta": 1000000.0}
|
| 94 |
+
self.attention_bias = attention_bias
|
| 95 |
+
self.attention_dropout = attention_dropout
|
| 96 |
+
self.mlp_bias = mlp_bias
|
| 97 |
+
self.factorized_embedding = factorized_embedding
|
| 98 |
+
self.embedding_rank = embedding_rank
|
| 99 |
+
self.layer_sharing = layer_sharing
|
| 100 |
+
# Smoltron training loops over `layer_sharing_repeats` unconditionally
|
| 101 |
+
# (it does NOT check `layer_sharing`). Preserve the raw value here so
|
| 102 |
+
# the modeling code can honor it; the `layer_sharing` bool is now just
|
| 103 |
+
# metadata describing intent.
|
| 104 |
+
self.layer_sharing_repeats = max(1, int(layer_sharing_repeats or 1))
|
| 105 |
+
self.qk_norm = qk_norm
|
| 106 |
+
# `shared_kv` records that V was tied to K at pretraining time. In the
|
| 107 |
+
# HF model V is recomputed from `k_proj` at runtime (no `v_proj` module
|
| 108 |
+
# is materialised); see `NandiAttention.forward`.
|
| 109 |
+
self.shared_kv = shared_kv
|
| 110 |
+
# `kv_cache_mode` controls the inference-time K/V cache strategy when
|
| 111 |
+
# `shared_kv=True`. Both modes produce identical outputs (numerical
|
| 112 |
+
# round-off only); they trade memory for compute:
|
| 113 |
+
# "shared" -> cache ONLY raw K (single tensor per layer). Each
|
| 114 |
+
# decode step re-applies k_norm + RoPE to the full
|
| 115 |
+
# cached raw K. Halves KV-cache memory.
|
| 116 |
+
# "vanilla" -> cache post-norm post-RoPE K AND raw V (two tensors
|
| 117 |
+
# per layer). k_norm + RoPE are applied only to the
|
| 118 |
+
# current step's tokens. Standard HF behavior.
|
| 119 |
+
# Ignored when `shared_kv=False`. Defaults to "shared".
|
| 120 |
+
if kv_cache_mode not in ("shared", "vanilla"):
|
| 121 |
+
raise ValueError(
|
| 122 |
+
f"`kv_cache_mode` must be 'shared' or 'vanilla', got {kv_cache_mode!r}."
|
| 123 |
+
)
|
| 124 |
+
self.kv_cache_mode = kv_cache_mode
|
| 125 |
+
|
| 126 |
+
if self.factorized_embedding and self.embedding_rank <= 0:
|
| 127 |
+
raise ValueError(
|
| 128 |
+
f"`embedding_rank` must be positive when `factorized_embedding=True`, got {self.embedding_rank}."
|
| 129 |
+
)
|
| 130 |
+
if self.hidden_size % self.num_attention_heads != 0:
|
| 131 |
+
raise ValueError(
|
| 132 |
+
f"`hidden_size` ({self.hidden_size}) must be divisible by "
|
| 133 |
+
f"`num_attention_heads` ({self.num_attention_heads})."
|
| 134 |
+
)
|
| 135 |
+
if self.layer_sharing_repeats < 1:
|
| 136 |
+
raise ValueError(f"`layer_sharing_repeats` must be >= 1, got {self.layer_sharing_repeats}.")
|
| 137 |
+
|
| 138 |
+
super().__init__(
|
| 139 |
+
pad_token_id=pad_token_id,
|
| 140 |
+
bos_token_id=bos_token_id,
|
| 141 |
+
eos_token_id=eos_token_id,
|
| 142 |
+
tie_word_embeddings=tie_word_embeddings,
|
| 143 |
+
**kwargs,
|
| 144 |
+
)
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
__all__ = ["NandiConfig"]
|
convert_smoltron_to_hf.py
ADDED
|
@@ -0,0 +1,320 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Convert a Smoltron (nanotron LlamaForTraining) on-disk checkpoint into an HF
|
| 2 |
+
Nandi (`NandiForCausalLM`) checkpoint with custom code support.
|
| 3 |
+
|
| 4 |
+
This script reads the per-parameter safetensors shards that nanotron writes
|
| 5 |
+
to disk and re-bundles them into a single ``model.safetensors`` + ``config.json``
|
| 6 |
+
that matches ``NandiConfig`` / ``NandiForCausalLM`` (see the sibling
|
| 7 |
+
``configuration_nandi.py`` / ``modeling_nandi.py`` files).
|
| 8 |
+
|
| 9 |
+
Why this script (and not ``Smoltron/examples/llama/convert_nanotron_to_hf.py``):
|
| 10 |
+
- The official converter has to instantiate a full nanotron model on CUDA
|
| 11 |
+
to call ``nanotron.serialize.load_weights``. Here we only need the tensors,
|
| 12 |
+
not the parallel runtime, so we read the safetensors files straight from
|
| 13 |
+
the layout that ``nanotron.serialize.save_weights`` produced.
|
| 14 |
+
- The 500M run uses ``shared_kv=True`` (V tied to K) and ``qk_norm=True``,
|
| 15 |
+
which the existing converter only knows how to express in a separate
|
| 16 |
+
``transformers``-5.x environment (see ``build_nandi_hf_from_dump.py``).
|
| 17 |
+
This script collapses both phases into a single dependency-light step
|
| 18 |
+
(``torch`` + ``safetensors``) so we can run it locally.
|
| 19 |
+
|
| 20 |
+
Layout we expect under ``--checkpoint_path``:
|
| 21 |
+
|
| 22 |
+
model_config.json
|
| 23 |
+
model/
|
| 24 |
+
token_position_embeddings/pp_block/token_embedding/model_weight_*.safetensors
|
| 25 |
+
final_layer_norm/pp_block/model_weight.safetensors
|
| 26 |
+
decoder/{i}/pp_block/attn/qkv_proj/model_weight_*.safetensors
|
| 27 |
+
decoder/{i}/pp_block/attn/o_proj/model_weight_*.safetensors
|
| 28 |
+
decoder/{i}/pp_block/attn/q_norm/model_weight.safetensors # if qk_norm
|
| 29 |
+
decoder/{i}/pp_block/attn/k_norm/model_weight.safetensors # if qk_norm
|
| 30 |
+
decoder/{i}/pp_block/mlp/gate_up_proj/model_weight_*.safetensors
|
| 31 |
+
decoder/{i}/pp_block/mlp/down_proj/model_weight_*.safetensors
|
| 32 |
+
decoder/{i}/pp_block/input_layernorm/model_weight.safetensors
|
| 33 |
+
decoder/{i}/pp_block/post_attention_layernorm/model_weight.safetensors
|
| 34 |
+
(optionally) lm_head/pp_block/model_weight_*.safetensors # if not tied
|
| 35 |
+
(optionally) token_position_embeddings/pp_block/embedding_proj/... # if factorized
|
| 36 |
+
|
| 37 |
+
Each per-parameter file stores a single tensor under the key ``"data"``.
|
| 38 |
+
|
| 39 |
+
Usage::
|
| 40 |
+
|
| 41 |
+
python convert_smoltron_to_hf.py \
|
| 42 |
+
--checkpoint_path /path/to/checkpoint_45000 \
|
| 43 |
+
--save_path /path/to/Nandi-Mini-500M \
|
| 44 |
+
--dtype bfloat16
|
| 45 |
+
|
| 46 |
+
When ``--save_path`` already contains the Nandi custom code files (this is the
|
| 47 |
+
intended layout for the Nandi-Mini-500M HF repo), they are left untouched and
|
| 48 |
+
only ``config.json`` + ``model.safetensors`` are (over)written.
|
| 49 |
+
"""
|
| 50 |
+
|
| 51 |
+
from __future__ import annotations
|
| 52 |
+
|
| 53 |
+
import argparse
|
| 54 |
+
import json
|
| 55 |
+
import os
|
| 56 |
+
from pathlib import Path
|
| 57 |
+
|
| 58 |
+
import torch
|
| 59 |
+
from safetensors.torch import load_file, save_file
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
DTYPE_MAP = {"float32": torch.float32, "float16": torch.float16, "bfloat16": torch.bfloat16}
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def _resolve(path: Path) -> Path:
|
| 66 |
+
"""Return the safetensors file inside ``path``.
|
| 67 |
+
|
| 68 |
+
Nanotron writes either ``model_weight.safetensors`` (replicated tensors:
|
| 69 |
+
norms, embeddings under TP=1) or ``model_weight_pp-rank-*-of-*_tp-rank-*-of-*.safetensors``
|
| 70 |
+
(sharded tensors). With pp=tp=1 there's exactly one file in either case.
|
| 71 |
+
"""
|
| 72 |
+
if not path.is_dir():
|
| 73 |
+
raise FileNotFoundError(f"Expected directory: {path}")
|
| 74 |
+
candidates = sorted(p for p in path.iterdir() if p.suffix == ".safetensors")
|
| 75 |
+
if not candidates:
|
| 76 |
+
raise FileNotFoundError(f"No safetensors files in {path}")
|
| 77 |
+
if len(candidates) > 1:
|
| 78 |
+
# Multiple shards (pp>1 or tp>1) — would need to concat along the right dim,
|
| 79 |
+
# which depends on the parameter. We don't support that here.
|
| 80 |
+
raise NotImplementedError(
|
| 81 |
+
f"Multiple shards under {path}; this script only supports pp=tp=1 checkpoints."
|
| 82 |
+
)
|
| 83 |
+
return candidates[0]
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def _load_tensor(path: Path) -> torch.Tensor:
|
| 87 |
+
f = _resolve(path)
|
| 88 |
+
sd = load_file(str(f))
|
| 89 |
+
if "data" not in sd:
|
| 90 |
+
raise KeyError(f"Expected key 'data' in {f}, got {list(sd)}")
|
| 91 |
+
return sd["data"]
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def build_hf_state_dict(
|
| 95 |
+
checkpoint_path: Path,
|
| 96 |
+
nt_cfg: dict,
|
| 97 |
+
dtype: torch.dtype,
|
| 98 |
+
) -> dict[str, torch.Tensor]:
|
| 99 |
+
"""Read the nanotron on-disk layout and produce an HF Nandi state_dict."""
|
| 100 |
+
n_layers = nt_cfg["num_hidden_layers"]
|
| 101 |
+
n_q = nt_cfg["num_attention_heads"]
|
| 102 |
+
n_kv = nt_cfg["num_key_value_heads"]
|
| 103 |
+
hidden = nt_cfg["hidden_size"]
|
| 104 |
+
head_dim = hidden // n_q
|
| 105 |
+
inter = nt_cfg["intermediate_size"]
|
| 106 |
+
hq = n_q * head_dim
|
| 107 |
+
hk = n_kv * head_dim
|
| 108 |
+
|
| 109 |
+
shared_kv = bool(nt_cfg.get("shared_kv", False))
|
| 110 |
+
qk_norm = bool(nt_cfg.get("qk_norm", False))
|
| 111 |
+
factorized_embedding = bool(nt_cfg.get("factorized_embedding", False))
|
| 112 |
+
tied = bool(nt_cfg.get("tie_word_embeddings", True))
|
| 113 |
+
|
| 114 |
+
# Nanotron writes parameters under ``<root_folder>/model/<param_path>``.
|
| 115 |
+
# Smoltron historically called ``serialize.save_weights(root_folder=<ckpt>/model)``,
|
| 116 |
+
# producing a ``<ckpt>/model/model/...`` layout, which is what we see in the wild.
|
| 117 |
+
# Accept either nesting depth so the script also works on freshly produced ckpts.
|
| 118 |
+
candidate_roots = [
|
| 119 |
+
checkpoint_path / "model" / "model",
|
| 120 |
+
checkpoint_path / "model",
|
| 121 |
+
]
|
| 122 |
+
for c in candidate_roots:
|
| 123 |
+
if (c / "token_position_embeddings").is_dir():
|
| 124 |
+
root = c
|
| 125 |
+
break
|
| 126 |
+
else:
|
| 127 |
+
raise FileNotFoundError(
|
| 128 |
+
f"Could not locate the nanotron weight tree under {checkpoint_path}; "
|
| 129 |
+
f"looked at {[str(c) for c in candidate_roots]}"
|
| 130 |
+
)
|
| 131 |
+
print(f" resolved weight root -> {root}")
|
| 132 |
+
sd: dict[str, torch.Tensor] = {}
|
| 133 |
+
|
| 134 |
+
embed = _load_tensor(root / "token_position_embeddings" / "pp_block" / "token_embedding")
|
| 135 |
+
sd["model.embed_tokens.weight"] = embed
|
| 136 |
+
sd["model.norm.weight"] = _load_tensor(root / "final_layer_norm" / "pp_block")
|
| 137 |
+
|
| 138 |
+
if factorized_embedding:
|
| 139 |
+
# Either side may live in one of a few possible directories depending on
|
| 140 |
+
# the Smoltron version that wrote the checkpoint.
|
| 141 |
+
candidates_in = [
|
| 142 |
+
root / "token_position_embeddings" / "pp_block" / "embedding_proj",
|
| 143 |
+
root / "token_position_embeddings" / "pp_block" / "token_embedding_projection",
|
| 144 |
+
root / "embedding_proj" / "pp_block",
|
| 145 |
+
]
|
| 146 |
+
for c in candidates_in:
|
| 147 |
+
if c.is_dir():
|
| 148 |
+
sd["model.embedding_proj.weight"] = _load_tensor(c)
|
| 149 |
+
break
|
| 150 |
+
else:
|
| 151 |
+
raise FileNotFoundError(
|
| 152 |
+
f"factorized_embedding=True but no embedding_proj dir under {root}"
|
| 153 |
+
)
|
| 154 |
+
|
| 155 |
+
candidates_out = [
|
| 156 |
+
root / "lm_head_proj" / "pp_block",
|
| 157 |
+
root / "lm_head" / "pp_block" / "lm_head_proj",
|
| 158 |
+
]
|
| 159 |
+
for c in candidates_out:
|
| 160 |
+
if c.is_dir():
|
| 161 |
+
sd["lm_head_proj.weight"] = _load_tensor(c)
|
| 162 |
+
break
|
| 163 |
+
else:
|
| 164 |
+
raise FileNotFoundError(
|
| 165 |
+
f"factorized_embedding=True but no lm_head_proj dir under {root}"
|
| 166 |
+
)
|
| 167 |
+
|
| 168 |
+
if not tied:
|
| 169 |
+
sd["lm_head.weight"] = _load_tensor(root / "lm_head" / "pp_block")
|
| 170 |
+
|
| 171 |
+
for i in range(n_layers):
|
| 172 |
+
layer_root = root / "decoder" / str(i) / "pp_block"
|
| 173 |
+
hf_p = f"model.layers.{i}"
|
| 174 |
+
|
| 175 |
+
# Combined qkv -> q, k, v.
|
| 176 |
+
qkv = _load_tensor(layer_root / "attn" / "qkv_proj")
|
| 177 |
+
expected_first = hq + hk if shared_kv else hq + 2 * hk
|
| 178 |
+
if qkv.shape[0] != expected_first:
|
| 179 |
+
raise ValueError(
|
| 180 |
+
f"Layer {i}: qkv_proj first dim {qkv.shape[0]} != expected {expected_first} "
|
| 181 |
+
f"(hq={hq}, hk={hk}, shared_kv={shared_kv})"
|
| 182 |
+
)
|
| 183 |
+
sd[f"{hf_p}.self_attn.q_proj.weight"] = qkv[:hq].contiguous()
|
| 184 |
+
sd[f"{hf_p}.self_attn.k_proj.weight"] = qkv[hq : hq + hk].contiguous()
|
| 185 |
+
if not shared_kv:
|
| 186 |
+
sd[f"{hf_p}.self_attn.v_proj.weight"] = qkv[hq + hk : hq + 2 * hk].contiguous()
|
| 187 |
+
# else: `shared_kv=True` -> the HF `NandiAttention` has no v_proj module;
|
| 188 |
+
# V is recomputed from `k_proj` inside attention. Skip writing v_proj.weight.
|
| 189 |
+
|
| 190 |
+
sd[f"{hf_p}.self_attn.o_proj.weight"] = _load_tensor(layer_root / "attn" / "o_proj")
|
| 191 |
+
|
| 192 |
+
if qk_norm:
|
| 193 |
+
sd[f"{hf_p}.self_attn.q_norm.weight"] = _load_tensor(layer_root / "attn" / "q_norm")
|
| 194 |
+
sd[f"{hf_p}.self_attn.k_norm.weight"] = _load_tensor(layer_root / "attn" / "k_norm")
|
| 195 |
+
|
| 196 |
+
# Combined gate_up -> gate, up.
|
| 197 |
+
gate_up = _load_tensor(layer_root / "mlp" / "gate_up_proj")
|
| 198 |
+
if gate_up.shape[0] != 2 * inter:
|
| 199 |
+
raise ValueError(
|
| 200 |
+
f"Layer {i}: gate_up_proj first dim {gate_up.shape[0]} != 2*inter={2 * inter}"
|
| 201 |
+
)
|
| 202 |
+
sd[f"{hf_p}.mlp.gate_proj.weight"] = gate_up[:inter].contiguous()
|
| 203 |
+
sd[f"{hf_p}.mlp.up_proj.weight"] = gate_up[inter:].contiguous()
|
| 204 |
+
sd[f"{hf_p}.mlp.down_proj.weight"] = _load_tensor(layer_root / "mlp" / "down_proj")
|
| 205 |
+
|
| 206 |
+
sd[f"{hf_p}.input_layernorm.weight"] = _load_tensor(layer_root / "input_layernorm")
|
| 207 |
+
sd[f"{hf_p}.post_attention_layernorm.weight"] = _load_tensor(layer_root / "post_attention_layernorm")
|
| 208 |
+
|
| 209 |
+
# Cast every tensor to the requested dtype (after slicing so we slice the
|
| 210 |
+
# original storage, not a copy).
|
| 211 |
+
for k, v in list(sd.items()):
|
| 212 |
+
v = v.detach().to(dtype)
|
| 213 |
+
if not v.is_contiguous():
|
| 214 |
+
v = v.contiguous()
|
| 215 |
+
sd[k] = v
|
| 216 |
+
|
| 217 |
+
return sd
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
def build_hf_config(nt_cfg: dict) -> dict:
|
| 221 |
+
"""Build the dict that ends up as ``config.json``."""
|
| 222 |
+
hidden = nt_cfg["hidden_size"]
|
| 223 |
+
n_heads = nt_cfg["num_attention_heads"]
|
| 224 |
+
head_dim = hidden // n_heads
|
| 225 |
+
|
| 226 |
+
return {
|
| 227 |
+
"architectures": ["NandiForCausalLM"],
|
| 228 |
+
"auto_map": {
|
| 229 |
+
"AutoConfig": "configuration_nandi.NandiConfig",
|
| 230 |
+
"AutoModel": "modeling_nandi.NandiModel",
|
| 231 |
+
"AutoModelForCausalLM": "modeling_nandi.NandiForCausalLM",
|
| 232 |
+
},
|
| 233 |
+
"model_type": "nandi",
|
| 234 |
+
"vocab_size": nt_cfg["vocab_size"],
|
| 235 |
+
"hidden_size": hidden,
|
| 236 |
+
"intermediate_size": nt_cfg["intermediate_size"],
|
| 237 |
+
"num_hidden_layers": nt_cfg["num_hidden_layers"],
|
| 238 |
+
"num_attention_heads": n_heads,
|
| 239 |
+
"num_key_value_heads": nt_cfg["num_key_value_heads"],
|
| 240 |
+
"head_dim": head_dim,
|
| 241 |
+
"hidden_act": nt_cfg["hidden_act"],
|
| 242 |
+
"max_position_embeddings": nt_cfg["max_position_embeddings"],
|
| 243 |
+
"initializer_range": nt_cfg.get("initializer_range", 0.008),
|
| 244 |
+
"rms_norm_eps": nt_cfg["rms_norm_eps"],
|
| 245 |
+
"use_cache": True,
|
| 246 |
+
"pad_token_id": nt_cfg.get("pad_token_id", None),
|
| 247 |
+
"bos_token_id": nt_cfg["bos_token_id"],
|
| 248 |
+
"eos_token_id": nt_cfg["eos_token_id"],
|
| 249 |
+
"tie_word_embeddings": bool(nt_cfg.get("tie_word_embeddings", True)),
|
| 250 |
+
"rope_parameters": {"rope_theta": float(nt_cfg["rope_theta"])},
|
| 251 |
+
"attention_bias": bool(nt_cfg.get("attention_bias", False)),
|
| 252 |
+
"attention_dropout": 0.0,
|
| 253 |
+
"mlp_bias": bool(nt_cfg.get("mlp_bias", False)),
|
| 254 |
+
"factorized_embedding": bool(nt_cfg.get("factorized_embedding", False)),
|
| 255 |
+
"embedding_rank": nt_cfg.get("embedding_rank", hidden),
|
| 256 |
+
"layer_sharing": bool(nt_cfg.get("layer_sharing", False)),
|
| 257 |
+
"layer_sharing_repeats": nt_cfg.get("layer_sharing_repeats", 1),
|
| 258 |
+
"qk_norm": bool(nt_cfg.get("qk_norm", False)),
|
| 259 |
+
"shared_kv": bool(nt_cfg.get("shared_kv", False)),
|
| 260 |
+
# Default inference-time cache strategy for shared_kv layers. "shared"
|
| 261 |
+
# caches raw K only (memory-saver, recomputes k_norm+RoPE per step);
|
| 262 |
+
# "vanilla" caches post-norm post-RoPE K and raw V separately (standard
|
| 263 |
+
# HF layout, faster decode). User can flip at runtime by setting
|
| 264 |
+
# `model.config.kv_cache_mode = "vanilla"` before generate.
|
| 265 |
+
"kv_cache_mode": "shared",
|
| 266 |
+
"torch_dtype": "bfloat16",
|
| 267 |
+
}
|
| 268 |
+
|
| 269 |
+
|
| 270 |
+
def main() -> None:
|
| 271 |
+
p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
| 272 |
+
p.add_argument("--checkpoint_path", type=Path, required=True, help="Smoltron checkpoint directory")
|
| 273 |
+
p.add_argument("--save_path", type=Path, required=True, help="Output HF directory")
|
| 274 |
+
p.add_argument("--dtype", choices=list(DTYPE_MAP), default="bfloat16")
|
| 275 |
+
args = p.parse_args()
|
| 276 |
+
|
| 277 |
+
dtype = DTYPE_MAP[args.dtype]
|
| 278 |
+
cfg_path = args.checkpoint_path / "model_config.json"
|
| 279 |
+
if not cfg_path.is_file():
|
| 280 |
+
raise FileNotFoundError(f"Missing nanotron config: {cfg_path}")
|
| 281 |
+
with open(cfg_path) as f:
|
| 282 |
+
nt_cfg = json.load(f)
|
| 283 |
+
|
| 284 |
+
print(
|
| 285 |
+
f"Source: {args.checkpoint_path}\n"
|
| 286 |
+
f" layers={nt_cfg['num_hidden_layers']} "
|
| 287 |
+
f"hidden={nt_cfg['hidden_size']} "
|
| 288 |
+
f"heads={nt_cfg['num_attention_heads']} "
|
| 289 |
+
f"kv_heads={nt_cfg['num_key_value_heads']} "
|
| 290 |
+
f"shared_kv={nt_cfg.get('shared_kv', False)} "
|
| 291 |
+
f"qk_norm={nt_cfg.get('qk_norm', False)} "
|
| 292 |
+
f"factorized_embedding={nt_cfg.get('factorized_embedding', False)} "
|
| 293 |
+
f"tied_embeddings={nt_cfg.get('tie_word_embeddings', True)}"
|
| 294 |
+
)
|
| 295 |
+
|
| 296 |
+
print("Reading & remapping tensors...")
|
| 297 |
+
sd = build_hf_state_dict(args.checkpoint_path, nt_cfg, dtype)
|
| 298 |
+
print(f" built {len(sd)} HF tensors")
|
| 299 |
+
|
| 300 |
+
args.save_path.mkdir(parents=True, exist_ok=True)
|
| 301 |
+
|
| 302 |
+
cfg = build_hf_config(nt_cfg)
|
| 303 |
+
cfg_out = args.save_path / "config.json"
|
| 304 |
+
with open(cfg_out, "w") as f:
|
| 305 |
+
json.dump(cfg, f, indent=2)
|
| 306 |
+
print(f"Wrote {cfg_out}")
|
| 307 |
+
|
| 308 |
+
weights_out = args.save_path / "model.safetensors"
|
| 309 |
+
save_file(sd, str(weights_out), metadata={"format": "pt"})
|
| 310 |
+
n_params = sum(v.numel() for v in sd.values())
|
| 311 |
+
print(
|
| 312 |
+
f"Wrote {weights_out} "
|
| 313 |
+
f"({os.path.getsize(weights_out) / 1e6:.1f} MB, ~{n_params / 1e6:.1f}M tensors elements)"
|
| 314 |
+
)
|
| 315 |
+
|
| 316 |
+
print("Done.")
|
| 317 |
+
|
| 318 |
+
|
| 319 |
+
if __name__ == "__main__":
|
| 320 |
+
main()
|
model.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:d6a1debc23b05874a5bc3a0d7f2f399714f7e6cef3ba1795542ee00d192b400d
|
| 3 |
+
size 1290954432
|
modeling_nandi.py
ADDED
|
@@ -0,0 +1,533 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from collections.abc import Callable
|
| 2 |
+
|
| 3 |
+
import torch
|
| 4 |
+
import torch.nn as nn
|
| 5 |
+
|
| 6 |
+
from transformers.activations import ACT2FN
|
| 7 |
+
from transformers.cache_utils import Cache, DynamicCache, DynamicLayer
|
| 8 |
+
from transformers.generation import GenerationMixin
|
| 9 |
+
from transformers.integrations import use_kernel_forward_from_hub
|
| 10 |
+
from transformers.masking_utils import create_causal_mask
|
| 11 |
+
from transformers.modeling_layers import GradientCheckpointingLayer
|
| 12 |
+
from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
|
| 13 |
+
from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
|
| 14 |
+
from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
|
| 15 |
+
from transformers.processing_utils import Unpack
|
| 16 |
+
from transformers.utils import TransformersKwargs, auto_docstring
|
| 17 |
+
from transformers.utils.deprecation import deprecate_kwarg
|
| 18 |
+
from transformers.utils.generic import can_return_tuple, merge_with_config_defaults
|
| 19 |
+
from transformers.utils.output_capturing import capture_outputs
|
| 20 |
+
from .configuration_nandi import NandiConfig
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
@use_kernel_forward_from_hub("RMSNorm")
|
| 24 |
+
class NandiRMSNorm(nn.Module):
|
| 25 |
+
def __init__(self, hidden_size, eps=1e-6):
|
| 26 |
+
super().__init__()
|
| 27 |
+
self.weight = nn.Parameter(torch.ones(hidden_size))
|
| 28 |
+
self.variance_epsilon = eps
|
| 29 |
+
|
| 30 |
+
def forward(self, hidden_states):
|
| 31 |
+
input_dtype = hidden_states.dtype
|
| 32 |
+
hidden_states = hidden_states.to(torch.float32)
|
| 33 |
+
variance = hidden_states.pow(2).mean(-1, keepdim=True)
|
| 34 |
+
hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
|
| 35 |
+
return self.weight * hidden_states.to(input_dtype)
|
| 36 |
+
|
| 37 |
+
def extra_repr(self):
|
| 38 |
+
return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
class NandiRotaryEmbedding(nn.Module):
|
| 42 |
+
inv_freq: torch.Tensor
|
| 43 |
+
|
| 44 |
+
def __init__(self, config: NandiConfig, device=None):
|
| 45 |
+
super().__init__()
|
| 46 |
+
self.max_seq_len_cached = config.max_position_embeddings
|
| 47 |
+
self.original_max_seq_len = config.max_position_embeddings
|
| 48 |
+
|
| 49 |
+
self.config = config
|
| 50 |
+
self.rope_type = self.config.rope_parameters.get("rope_type", "default")
|
| 51 |
+
rope_init_fn: Callable = self.compute_default_rope_parameters
|
| 52 |
+
if self.rope_type != "default":
|
| 53 |
+
rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
|
| 54 |
+
inv_freq, self.attention_scaling = rope_init_fn(self.config, device)
|
| 55 |
+
|
| 56 |
+
self.register_buffer("inv_freq", inv_freq, persistent=False)
|
| 57 |
+
self.register_buffer("original_inv_freq", inv_freq.clone(), persistent=False)
|
| 58 |
+
|
| 59 |
+
@staticmethod
|
| 60 |
+
def compute_default_rope_parameters(
|
| 61 |
+
config: NandiConfig | None = None,
|
| 62 |
+
device: torch.device | None = None,
|
| 63 |
+
seq_len: int | None = None,
|
| 64 |
+
) -> tuple[torch.Tensor, float]:
|
| 65 |
+
del seq_len
|
| 66 |
+
base = config.rope_parameters["rope_theta"]
|
| 67 |
+
dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads
|
| 68 |
+
attention_factor = 1.0
|
| 69 |
+
inv_freq = 1.0 / (
|
| 70 |
+
base ** (torch.arange(0, dim, 2, dtype=torch.int64).to(device=device, dtype=torch.float) / dim)
|
| 71 |
+
)
|
| 72 |
+
return inv_freq, attention_factor
|
| 73 |
+
|
| 74 |
+
@torch.no_grad()
|
| 75 |
+
@dynamic_rope_update
|
| 76 |
+
def forward(self, x, position_ids):
|
| 77 |
+
inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
|
| 78 |
+
position_ids_expanded = position_ids[:, None, :].float()
|
| 79 |
+
|
| 80 |
+
device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
|
| 81 |
+
with torch.autocast(device_type=device_type, enabled=False):
|
| 82 |
+
freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
|
| 83 |
+
emb = torch.cat((freqs, freqs), dim=-1)
|
| 84 |
+
cos = emb.cos() * self.attention_scaling
|
| 85 |
+
sin = emb.sin() * self.attention_scaling
|
| 86 |
+
|
| 87 |
+
return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def rotate_half(x):
|
| 91 |
+
"""Rotates half the hidden dims of the input."""
|
| 92 |
+
x1 = x[..., : x.shape[-1] // 2]
|
| 93 |
+
x2 = x[..., x.shape[-1] // 2 :]
|
| 94 |
+
return torch.cat((-x2, x1), dim=-1)
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
|
| 98 |
+
del position_ids
|
| 99 |
+
cos = cos.unsqueeze(unsqueeze_dim)
|
| 100 |
+
sin = sin.unsqueeze(unsqueeze_dim)
|
| 101 |
+
q_embed = (q * cos) + (rotate_half(q) * sin)
|
| 102 |
+
k_embed = (k * cos) + (rotate_half(k) * sin)
|
| 103 |
+
return q_embed, k_embed
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
|
| 107 |
+
batch, num_key_value_heads, slen, head_dim = hidden_states.shape
|
| 108 |
+
if n_rep == 1:
|
| 109 |
+
return hidden_states
|
| 110 |
+
hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
|
| 111 |
+
return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
def eager_attention_forward(
|
| 115 |
+
module: nn.Module,
|
| 116 |
+
query: torch.Tensor,
|
| 117 |
+
key: torch.Tensor,
|
| 118 |
+
value: torch.Tensor,
|
| 119 |
+
attention_mask: torch.Tensor | None,
|
| 120 |
+
scaling: float,
|
| 121 |
+
dropout: float = 0.0,
|
| 122 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 123 |
+
):
|
| 124 |
+
del kwargs
|
| 125 |
+
key_states = repeat_kv(key, module.num_key_value_groups)
|
| 126 |
+
value_states = repeat_kv(value, module.num_key_value_groups)
|
| 127 |
+
|
| 128 |
+
attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
|
| 129 |
+
if attention_mask is not None:
|
| 130 |
+
causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
|
| 131 |
+
attn_weights = attn_weights + causal_mask
|
| 132 |
+
|
| 133 |
+
attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
|
| 134 |
+
attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
|
| 135 |
+
attn_output = torch.matmul(attn_weights, value_states)
|
| 136 |
+
attn_output = attn_output.transpose(1, 2).contiguous()
|
| 137 |
+
|
| 138 |
+
return attn_output, attn_weights
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
class NandiAttention(nn.Module):
|
| 142 |
+
def __init__(self, config: NandiConfig, layer_idx: int):
|
| 143 |
+
super().__init__()
|
| 144 |
+
self.config = config
|
| 145 |
+
self.layer_idx = layer_idx
|
| 146 |
+
self.head_dim = config.head_dim
|
| 147 |
+
self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
|
| 148 |
+
self.scaling = self.head_dim**-0.5
|
| 149 |
+
self.attention_dropout = config.attention_dropout
|
| 150 |
+
self.is_causal = True
|
| 151 |
+
|
| 152 |
+
self.shared_kv = getattr(config, "shared_kv", False)
|
| 153 |
+
|
| 154 |
+
self.q_proj = nn.Linear(
|
| 155 |
+
config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias
|
| 156 |
+
)
|
| 157 |
+
self.k_proj = nn.Linear(
|
| 158 |
+
config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
|
| 159 |
+
)
|
| 160 |
+
if self.shared_kv:
|
| 161 |
+
self.v_proj = None
|
| 162 |
+
else:
|
| 163 |
+
self.v_proj = nn.Linear(
|
| 164 |
+
config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
|
| 165 |
+
)
|
| 166 |
+
self.o_proj = nn.Linear(
|
| 167 |
+
config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.attention_bias
|
| 168 |
+
)
|
| 169 |
+
|
| 170 |
+
self.qk_norm = getattr(config, "qk_norm", False)
|
| 171 |
+
if self.qk_norm:
|
| 172 |
+
self.q_norm = NandiRMSNorm(self.head_dim, eps=config.rms_norm_eps)
|
| 173 |
+
self.k_norm = NandiRMSNorm(self.head_dim, eps=config.rms_norm_eps)
|
| 174 |
+
else:
|
| 175 |
+
self.q_norm = None
|
| 176 |
+
self.k_norm = None
|
| 177 |
+
|
| 178 |
+
@deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
|
| 179 |
+
def forward(
|
| 180 |
+
self,
|
| 181 |
+
hidden_states: torch.Tensor,
|
| 182 |
+
position_embeddings: tuple[torch.Tensor, torch.Tensor],
|
| 183 |
+
attention_mask: torch.Tensor | None,
|
| 184 |
+
past_key_values: Cache | None = None,
|
| 185 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 186 |
+
) -> tuple[torch.Tensor, torch.Tensor]:
|
| 187 |
+
input_shape = hidden_states.shape[:-1]
|
| 188 |
+
hidden_shape = (*input_shape, -1, self.head_dim)
|
| 189 |
+
|
| 190 |
+
query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
|
| 191 |
+
k_raw = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
|
| 192 |
+
|
| 193 |
+
if self.shared_kv:
|
| 194 |
+
kv_cache_mode = getattr(self.config, "kv_cache_mode", "shared")
|
| 195 |
+
|
| 196 |
+
if self.qk_norm:
|
| 197 |
+
query_states = self.q_norm(query_states)
|
| 198 |
+
|
| 199 |
+
if kv_cache_mode == "shared":
|
| 200 |
+
if past_key_values is not None:
|
| 201 |
+
empty_v = torch.empty(
|
| 202 |
+
k_raw.shape[0],
|
| 203 |
+
k_raw.shape[1],
|
| 204 |
+
0,
|
| 205 |
+
k_raw.shape[3],
|
| 206 |
+
device=k_raw.device,
|
| 207 |
+
dtype=k_raw.dtype,
|
| 208 |
+
)
|
| 209 |
+
k_raw_full, _ = past_key_values.update(k_raw, empty_v, self.layer_idx)
|
| 210 |
+
else:
|
| 211 |
+
k_raw_full = k_raw
|
| 212 |
+
|
| 213 |
+
value_states = k_raw_full
|
| 214 |
+
key_states = self.k_norm(k_raw_full) if self.qk_norm else k_raw_full
|
| 215 |
+
|
| 216 |
+
cos, sin = position_embeddings
|
| 217 |
+
q_len = query_states.shape[-2]
|
| 218 |
+
cos_q = cos[..., -q_len:, :]
|
| 219 |
+
sin_q = sin[..., -q_len:, :]
|
| 220 |
+
query_states, _ = apply_rotary_pos_emb(query_states, query_states, cos_q, sin_q)
|
| 221 |
+
_, key_states = apply_rotary_pos_emb(key_states, key_states, cos, sin)
|
| 222 |
+
|
| 223 |
+
else:
|
| 224 |
+
key_states = self.k_norm(k_raw) if self.qk_norm else k_raw
|
| 225 |
+
value_states = k_raw
|
| 226 |
+
|
| 227 |
+
cos, sin = position_embeddings
|
| 228 |
+
query_states, key_states = apply_rotary_pos_emb(
|
| 229 |
+
query_states, key_states, cos, sin
|
| 230 |
+
)
|
| 231 |
+
|
| 232 |
+
if past_key_values is not None:
|
| 233 |
+
key_states, value_states = past_key_values.update(
|
| 234 |
+
key_states, value_states, self.layer_idx
|
| 235 |
+
)
|
| 236 |
+
|
| 237 |
+
else:
|
| 238 |
+
value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
|
| 239 |
+
key_states = k_raw
|
| 240 |
+
|
| 241 |
+
if self.qk_norm:
|
| 242 |
+
query_states = self.q_norm(query_states)
|
| 243 |
+
key_states = self.k_norm(key_states)
|
| 244 |
+
|
| 245 |
+
cos, sin = position_embeddings
|
| 246 |
+
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
|
| 247 |
+
|
| 248 |
+
if past_key_values is not None:
|
| 249 |
+
key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx)
|
| 250 |
+
|
| 251 |
+
attention_interface: Callable = eager_attention_forward
|
| 252 |
+
if self.config._attn_implementation != "eager":
|
| 253 |
+
attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
|
| 254 |
+
|
| 255 |
+
attn_output, attn_weights = attention_interface(
|
| 256 |
+
self,
|
| 257 |
+
query_states,
|
| 258 |
+
key_states,
|
| 259 |
+
value_states,
|
| 260 |
+
attention_mask,
|
| 261 |
+
dropout=0.0 if not self.training else self.attention_dropout,
|
| 262 |
+
scaling=self.scaling,
|
| 263 |
+
**kwargs,
|
| 264 |
+
)
|
| 265 |
+
|
| 266 |
+
attn_output = attn_output.reshape(*input_shape, -1).contiguous()
|
| 267 |
+
attn_output = self.o_proj(attn_output)
|
| 268 |
+
return attn_output, attn_weights
|
| 269 |
+
|
| 270 |
+
|
| 271 |
+
class NandiMLP(nn.Module):
|
| 272 |
+
def __init__(self, config):
|
| 273 |
+
super().__init__()
|
| 274 |
+
self.gate_proj = nn.Linear(config.hidden_size, config.intermediate_size, bias=config.mlp_bias)
|
| 275 |
+
self.up_proj = nn.Linear(config.hidden_size, config.intermediate_size, bias=config.mlp_bias)
|
| 276 |
+
self.down_proj = nn.Linear(config.intermediate_size, config.hidden_size, bias=config.mlp_bias)
|
| 277 |
+
self.act_fn = ACT2FN[config.hidden_act]
|
| 278 |
+
|
| 279 |
+
def forward(self, x):
|
| 280 |
+
return self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
|
| 281 |
+
|
| 282 |
+
|
| 283 |
+
class NandiDecoderLayer(GradientCheckpointingLayer):
|
| 284 |
+
def __init__(self, config: NandiConfig, layer_idx: int):
|
| 285 |
+
super().__init__()
|
| 286 |
+
self.hidden_size = config.hidden_size
|
| 287 |
+
self.self_attn = NandiAttention(config=config, layer_idx=layer_idx)
|
| 288 |
+
self.mlp = NandiMLP(config)
|
| 289 |
+
self.input_layernorm = NandiRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
| 290 |
+
self.post_attention_layernorm = NandiRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
| 291 |
+
|
| 292 |
+
@deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
|
| 293 |
+
def forward(
|
| 294 |
+
self,
|
| 295 |
+
hidden_states: torch.Tensor,
|
| 296 |
+
attention_mask: torch.Tensor | None = None,
|
| 297 |
+
position_ids: torch.LongTensor | None = None,
|
| 298 |
+
past_key_values: Cache | None = None,
|
| 299 |
+
use_cache: bool | None = False,
|
| 300 |
+
position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
|
| 301 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 302 |
+
) -> torch.Tensor:
|
| 303 |
+
residual = hidden_states
|
| 304 |
+
hidden_states = self.input_layernorm(hidden_states)
|
| 305 |
+
|
| 306 |
+
hidden_states, _ = self.self_attn(
|
| 307 |
+
hidden_states=hidden_states,
|
| 308 |
+
attention_mask=attention_mask,
|
| 309 |
+
position_ids=position_ids,
|
| 310 |
+
past_key_values=past_key_values,
|
| 311 |
+
use_cache=use_cache,
|
| 312 |
+
position_embeddings=position_embeddings,
|
| 313 |
+
**kwargs,
|
| 314 |
+
)
|
| 315 |
+
hidden_states = residual + hidden_states
|
| 316 |
+
|
| 317 |
+
residual = hidden_states
|
| 318 |
+
hidden_states = self.post_attention_layernorm(hidden_states)
|
| 319 |
+
hidden_states = self.mlp(hidden_states)
|
| 320 |
+
hidden_states = residual + hidden_states
|
| 321 |
+
return hidden_states
|
| 322 |
+
|
| 323 |
+
|
| 324 |
+
class _VirtualLayerCache:
|
| 325 |
+
"""Proxy that shifts cache layer indices by `offset` to give each repeat its own virtual slots."""
|
| 326 |
+
|
| 327 |
+
def __init__(self, cache: Cache, offset: int):
|
| 328 |
+
self._cache = cache
|
| 329 |
+
self._offset = offset
|
| 330 |
+
|
| 331 |
+
def __getattr__(self, name):
|
| 332 |
+
return getattr(self._cache, name)
|
| 333 |
+
|
| 334 |
+
def update(self, key_states, value_states, layer_idx, cache_kwargs=None):
|
| 335 |
+
virtual_idx = layer_idx + self._offset
|
| 336 |
+
# grow the backing cache if generate() pre-allocated fewer slots than needed
|
| 337 |
+
while len(self._cache.layers) <= virtual_idx:
|
| 338 |
+
self._cache.layers.append(DynamicLayer())
|
| 339 |
+
return self._cache.update(key_states, value_states, virtual_idx, cache_kwargs)
|
| 340 |
+
|
| 341 |
+
def get_seq_length(self, layer_idx: int = 0) -> int:
|
| 342 |
+
return self._cache.get_seq_length(layer_idx + self._offset)
|
| 343 |
+
|
| 344 |
+
|
| 345 |
+
@auto_docstring
|
| 346 |
+
class NandiPreTrainedModel(PreTrainedModel):
|
| 347 |
+
config: NandiConfig
|
| 348 |
+
base_model_prefix = "model"
|
| 349 |
+
supports_gradient_checkpointing = True
|
| 350 |
+
_no_split_modules = ["NandiDecoderLayer"]
|
| 351 |
+
_skip_keys_device_placement = ["past_key_values"]
|
| 352 |
+
_supports_flash_attn = True
|
| 353 |
+
_supports_sdpa = True
|
| 354 |
+
_supports_flex_attn = True
|
| 355 |
+
_can_compile_fullgraph = True
|
| 356 |
+
_supports_attention_backend = True
|
| 357 |
+
_can_record_outputs = {
|
| 358 |
+
"hidden_states": NandiDecoderLayer,
|
| 359 |
+
"attentions": NandiAttention,
|
| 360 |
+
}
|
| 361 |
+
|
| 362 |
+
def __init__(self, config: NandiConfig):
|
| 363 |
+
super().__init__(config)
|
| 364 |
+
|
| 365 |
+
|
| 366 |
+
@auto_docstring
|
| 367 |
+
class NandiModel(NandiPreTrainedModel):
|
| 368 |
+
def __init__(self, config: NandiConfig):
|
| 369 |
+
super().__init__(config)
|
| 370 |
+
self.padding_idx = config.pad_token_id
|
| 371 |
+
self.vocab_size = config.vocab_size
|
| 372 |
+
embedding_dim = config.embedding_rank if config.factorized_embedding else config.hidden_size
|
| 373 |
+
|
| 374 |
+
self.embed_tokens = nn.Embedding(config.vocab_size, embedding_dim, self.padding_idx)
|
| 375 |
+
self.embedding_proj = (
|
| 376 |
+
nn.Linear(config.embedding_rank, config.hidden_size, bias=False) if config.factorized_embedding else None
|
| 377 |
+
)
|
| 378 |
+
self.layers = nn.ModuleList(
|
| 379 |
+
[NandiDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
|
| 380 |
+
)
|
| 381 |
+
self.norm = NandiRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
| 382 |
+
self.rotary_emb = NandiRotaryEmbedding(config=config)
|
| 383 |
+
self.gradient_checkpointing = False
|
| 384 |
+
|
| 385 |
+
self.post_init()
|
| 386 |
+
|
| 387 |
+
@merge_with_config_defaults
|
| 388 |
+
@capture_outputs
|
| 389 |
+
@auto_docstring
|
| 390 |
+
def forward(
|
| 391 |
+
self,
|
| 392 |
+
input_ids: torch.LongTensor | None = None,
|
| 393 |
+
attention_mask: torch.Tensor | None = None,
|
| 394 |
+
position_ids: torch.LongTensor | None = None,
|
| 395 |
+
past_key_values: Cache | None = None,
|
| 396 |
+
inputs_embeds: torch.FloatTensor | None = None,
|
| 397 |
+
use_cache: bool | None = None,
|
| 398 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 399 |
+
) -> BaseModelOutputWithPast:
|
| 400 |
+
if (input_ids is None) ^ (inputs_embeds is not None):
|
| 401 |
+
raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
|
| 402 |
+
|
| 403 |
+
if inputs_embeds is None:
|
| 404 |
+
inputs_embeds = self.embed_tokens(input_ids)
|
| 405 |
+
|
| 406 |
+
if self.embedding_proj is not None:
|
| 407 |
+
inputs_embeds = self.embedding_proj(inputs_embeds)
|
| 408 |
+
repeats = max(1, int(getattr(self.config, "layer_sharing_repeats", 1) or 1))
|
| 409 |
+
|
| 410 |
+
if use_cache and past_key_values is None:
|
| 411 |
+
past_key_values = DynamicCache()
|
| 412 |
+
|
| 413 |
+
if position_ids is None:
|
| 414 |
+
past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
|
| 415 |
+
position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device) + past_seen_tokens
|
| 416 |
+
position_ids = position_ids.unsqueeze(0)
|
| 417 |
+
|
| 418 |
+
causal_mask = create_causal_mask(
|
| 419 |
+
config=self.config,
|
| 420 |
+
inputs_embeds=inputs_embeds,
|
| 421 |
+
attention_mask=attention_mask,
|
| 422 |
+
past_key_values=past_key_values,
|
| 423 |
+
position_ids=position_ids,
|
| 424 |
+
)
|
| 425 |
+
|
| 426 |
+
hidden_states = inputs_embeds
|
| 427 |
+
kv_cache_mode = getattr(self.config, "kv_cache_mode", "shared")
|
| 428 |
+
if (
|
| 429 |
+
getattr(self.config, "shared_kv", False)
|
| 430 |
+
and kv_cache_mode == "shared"
|
| 431 |
+
and past_key_values is not None
|
| 432 |
+
):
|
| 433 |
+
past_len = past_key_values.get_seq_length(0)
|
| 434 |
+
cur_len = inputs_embeds.shape[1]
|
| 435 |
+
full_position_ids = torch.arange(
|
| 436 |
+
past_len + cur_len, device=inputs_embeds.device
|
| 437 |
+
).unsqueeze(0)
|
| 438 |
+
position_embeddings = self.rotary_emb(hidden_states, position_ids=full_position_ids)
|
| 439 |
+
else:
|
| 440 |
+
position_embeddings = self.rotary_emb(hidden_states, position_ids=position_ids)
|
| 441 |
+
|
| 442 |
+
for decoder_layer in self.layers[: self.config.num_hidden_layers]:
|
| 443 |
+
for repeat_idx in range(repeats):
|
| 444 |
+
|
| 445 |
+
repeat_cache = (
|
| 446 |
+
_VirtualLayerCache(past_key_values, repeat_idx * self.config.num_hidden_layers)
|
| 447 |
+
if (past_key_values is not None and repeat_idx > 0)
|
| 448 |
+
else past_key_values
|
| 449 |
+
)
|
| 450 |
+
hidden_states = decoder_layer(
|
| 451 |
+
hidden_states,
|
| 452 |
+
attention_mask=causal_mask,
|
| 453 |
+
position_embeddings=position_embeddings,
|
| 454 |
+
position_ids=position_ids,
|
| 455 |
+
past_key_values=repeat_cache,
|
| 456 |
+
use_cache=use_cache,
|
| 457 |
+
**kwargs,
|
| 458 |
+
)
|
| 459 |
+
|
| 460 |
+
hidden_states = self.norm(hidden_states)
|
| 461 |
+
return BaseModelOutputWithPast(
|
| 462 |
+
last_hidden_state=hidden_states,
|
| 463 |
+
past_key_values=past_key_values,
|
| 464 |
+
)
|
| 465 |
+
|
| 466 |
+
|
| 467 |
+
@auto_docstring
|
| 468 |
+
class NandiForCausalLM(NandiPreTrainedModel, GenerationMixin):
|
| 469 |
+
_tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"}
|
| 470 |
+
_tp_plan = {"lm_head": "colwise_gather_output"}
|
| 471 |
+
_pp_plan = {
|
| 472 |
+
"lm_head_proj": (["hidden_states"], ["hidden_states"]),
|
| 473 |
+
"lm_head": (["hidden_states"], ["logits"]),
|
| 474 |
+
}
|
| 475 |
+
|
| 476 |
+
def __init__(self, config):
|
| 477 |
+
super().__init__(config)
|
| 478 |
+
self.model = NandiModel(config)
|
| 479 |
+
self.vocab_size = config.vocab_size
|
| 480 |
+
|
| 481 |
+
lm_head_in_features = config.embedding_rank if config.factorized_embedding else config.hidden_size
|
| 482 |
+
self.lm_head_proj = (
|
| 483 |
+
nn.Linear(config.hidden_size, config.embedding_rank, bias=False) if config.factorized_embedding else None
|
| 484 |
+
)
|
| 485 |
+
self.lm_head = nn.Linear(lm_head_in_features, config.vocab_size, bias=False)
|
| 486 |
+
|
| 487 |
+
self.post_init()
|
| 488 |
+
|
| 489 |
+
@can_return_tuple
|
| 490 |
+
@auto_docstring
|
| 491 |
+
def forward(
|
| 492 |
+
self,
|
| 493 |
+
input_ids: torch.LongTensor | None = None,
|
| 494 |
+
attention_mask: torch.Tensor | None = None,
|
| 495 |
+
position_ids: torch.LongTensor | None = None,
|
| 496 |
+
past_key_values: Cache | None = None,
|
| 497 |
+
inputs_embeds: torch.FloatTensor | None = None,
|
| 498 |
+
labels: torch.LongTensor | None = None,
|
| 499 |
+
use_cache: bool | None = None,
|
| 500 |
+
logits_to_keep: int | torch.Tensor = 0,
|
| 501 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 502 |
+
) -> CausalLMOutputWithPast:
|
| 503 |
+
outputs: BaseModelOutputWithPast = self.model(
|
| 504 |
+
input_ids=input_ids,
|
| 505 |
+
attention_mask=attention_mask,
|
| 506 |
+
position_ids=position_ids,
|
| 507 |
+
past_key_values=past_key_values,
|
| 508 |
+
inputs_embeds=inputs_embeds,
|
| 509 |
+
use_cache=use_cache,
|
| 510 |
+
**kwargs,
|
| 511 |
+
)
|
| 512 |
+
|
| 513 |
+
hidden_states = outputs.last_hidden_state
|
| 514 |
+
if self.lm_head_proj is not None:
|
| 515 |
+
hidden_states = self.lm_head_proj(hidden_states)
|
| 516 |
+
|
| 517 |
+
slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
|
| 518 |
+
logits = self.lm_head(hidden_states[:, slice_indices, :])
|
| 519 |
+
|
| 520 |
+
loss = None
|
| 521 |
+
if labels is not None:
|
| 522 |
+
loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)
|
| 523 |
+
|
| 524 |
+
return CausalLMOutputWithPast(
|
| 525 |
+
loss=loss,
|
| 526 |
+
logits=logits,
|
| 527 |
+
past_key_values=outputs.past_key_values,
|
| 528 |
+
hidden_states=outputs.hidden_states,
|
| 529 |
+
attentions=outputs.attentions,
|
| 530 |
+
)
|
| 531 |
+
|
| 532 |
+
|
| 533 |
+
__all__ = ["NandiPreTrainedModel", "NandiModel", "NandiForCausalLM"]
|
tokenization_nandi.py
ADDED
|
@@ -0,0 +1,143 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2026 The HuggingFace Inc. team. 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 |
+
"""Tokenization classes for the Nandi family."""
|
| 15 |
+
|
| 16 |
+
from tokenizers import Regex, Tokenizer, decoders, normalizers, pre_tokenizers
|
| 17 |
+
from tokenizers.models import BPE
|
| 18 |
+
|
| 19 |
+
from transformers.tokenization_utils_tokenizers import TokenizersBackend
|
| 20 |
+
from transformers.utils import logging
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
logger = logging.get_logger(__name__)
|
| 24 |
+
|
| 25 |
+
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+"""
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
class NandiTokenizer(TokenizersBackend):
|
| 29 |
+
model_input_names = ["input_ids", "attention_mask"]
|
| 30 |
+
model = BPE
|
| 31 |
+
|
| 32 |
+
def __init__(
|
| 33 |
+
self,
|
| 34 |
+
vocab: str | dict[str, int] | None = None,
|
| 35 |
+
merges: str | list[str] | None = None,
|
| 36 |
+
vocab_file=None,
|
| 37 |
+
merges_file=None,
|
| 38 |
+
unk_token: str = "<|endoftext|>",
|
| 39 |
+
bos_token: str = "<|im_start|>",
|
| 40 |
+
eos_token: str = "<|endoftext|>",
|
| 41 |
+
pad_token: str = "<|pad|>",
|
| 42 |
+
add_prefix_space: bool | None = None,
|
| 43 |
+
**kwargs,
|
| 44 |
+
):
|
| 45 |
+
self._vocab = (
|
| 46 |
+
vocab
|
| 47 |
+
if vocab is not None
|
| 48 |
+
else {
|
| 49 |
+
"<|endoftext|>": 0,
|
| 50 |
+
}
|
| 51 |
+
)
|
| 52 |
+
self._merges = merges or []
|
| 53 |
+
|
| 54 |
+
self._tokenizer = Tokenizer(
|
| 55 |
+
BPE(
|
| 56 |
+
vocab=self._vocab,
|
| 57 |
+
merges=self._merges,
|
| 58 |
+
dropout=None,
|
| 59 |
+
unk_token=None,
|
| 60 |
+
continuing_subword_prefix="",
|
| 61 |
+
end_of_word_suffix="",
|
| 62 |
+
fuse_unk=False,
|
| 63 |
+
byte_fallback=False,
|
| 64 |
+
)
|
| 65 |
+
)
|
| 66 |
+
self._tokenizer.decoder = decoders.ByteLevel()
|
| 67 |
+
self._tokenizer.normalizer = normalizers.NFC()
|
| 68 |
+
self._tokenizer.pre_tokenizer = pre_tokenizers.Sequence(
|
| 69 |
+
[
|
| 70 |
+
pre_tokenizers.Split(
|
| 71 |
+
Regex(PRETOKENIZE_REGEX),
|
| 72 |
+
behavior="isolated",
|
| 73 |
+
invert=False,
|
| 74 |
+
),
|
| 75 |
+
pre_tokenizers.ByteLevel(
|
| 76 |
+
add_prefix_space=False,
|
| 77 |
+
trim_offsets=True,
|
| 78 |
+
use_regex=False
|
| 79 |
+
),
|
| 80 |
+
]
|
| 81 |
+
)
|
| 82 |
+
|
| 83 |
+
super().__init__(
|
| 84 |
+
vocab_file=vocab_file,
|
| 85 |
+
merges_file=merges_file,
|
| 86 |
+
unk_token=unk_token,
|
| 87 |
+
bos_token=bos_token,
|
| 88 |
+
eos_token=eos_token,
|
| 89 |
+
pad_token=pad_token,
|
| 90 |
+
add_prefix_space=add_prefix_space,
|
| 91 |
+
**kwargs,
|
| 92 |
+
)
|
| 93 |
+
|
| 94 |
+
def __call__(self, text, *args, **kwargs):
|
| 95 |
+
add_special_tokens = kwargs.get("add_special_tokens", False)
|
| 96 |
+
|
| 97 |
+
def add_prefix(t):
|
| 98 |
+
if isinstance(t, str):
|
| 99 |
+
return "<|im_start|> " + t
|
| 100 |
+
return t
|
| 101 |
+
|
| 102 |
+
# Only inject when special tokens are disabled
|
| 103 |
+
if not add_special_tokens:
|
| 104 |
+
if isinstance(text, list):
|
| 105 |
+
text = [add_prefix(t) for t in text]
|
| 106 |
+
else:
|
| 107 |
+
text = add_prefix(text)
|
| 108 |
+
|
| 109 |
+
return super().__call__(text, *args, **kwargs)
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
# def encode(
|
| 114 |
+
# self,
|
| 115 |
+
# text,
|
| 116 |
+
# text_pair=None,
|
| 117 |
+
# add_special_tokens: bool = True,
|
| 118 |
+
# padding=False,
|
| 119 |
+
# truncation=None,
|
| 120 |
+
# max_length=None,
|
| 121 |
+
# stride: int = 0,
|
| 122 |
+
# padding_side=None,
|
| 123 |
+
# return_tensors=None,
|
| 124 |
+
# **kwargs,
|
| 125 |
+
# ):
|
| 126 |
+
# if isinstance(text, str):
|
| 127 |
+
# # This is a temporary fix to match the behaviour of the training pipeline
|
| 128 |
+
# text = "<|im_start|>" + " " + text
|
| 129 |
+
# return super().encode(
|
| 130 |
+
# text,
|
| 131 |
+
# text_pair=text_pair,
|
| 132 |
+
# add_special_tokens=add_special_tokens,
|
| 133 |
+
# padding=padding,
|
| 134 |
+
# truncation=truncation,
|
| 135 |
+
# max_length=max_length,
|
| 136 |
+
# stride=stride,
|
| 137 |
+
# padding_side=padding_side,
|
| 138 |
+
# return_tensors=return_tensors,
|
| 139 |
+
# **kwargs,
|
| 140 |
+
# )
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
__all__ = ["NandiTokenizer"]
|
tokenizer.json
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:dc858b896e5a8c86097420a23a90b8a0ad4d2ad23250e1fae99b89f525120c90
|
| 3 |
+
size 12460256
|
tokenizer_config.json
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"backend": "tokenizers",
|
| 3 |
+
"bos_token": "<|im_start|>",
|
| 4 |
+
"bos_token_id": 1,
|
| 5 |
+
"eos_token": "<|endoftext|>",
|
| 6 |
+
"eos_token_id": 0,
|
| 7 |
+
"pad_token": "<|pad|>",
|
| 8 |
+
"pad_token_id": 3,
|
| 9 |
+
"model_max_length": 2048,
|
| 10 |
+
"tokenizer_class": "NandiTokenizer",
|
| 11 |
+
"unk_token": "<|endoftext|>",
|
| 12 |
+
"auto_map": {
|
| 13 |
+
"AutoTokenizer": ["tokenization_nandi.NandiTokenizer", null]
|
| 14 |
+
}
|
| 15 |
+
}
|