Upload folder using huggingface_hub
Browse files- config.json +23 -7
- configuration_nanoi1.py +54 -0
- model.safetensors +2 -2
- modeling_nanoi1.py +39 -1
- modeling_nanoi1_hf.py +338 -0
config.json
CHANGED
|
@@ -1,22 +1,38 @@
|
|
| 1 |
{
|
| 2 |
"model_type": "nanoi1",
|
| 3 |
"architectures": [
|
| 4 |
-
"
|
| 5 |
],
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6 |
"vocab_size": 50304,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 7 |
"embed_dim": 768,
|
| 8 |
"context_len": 131072,
|
| 9 |
"num_heads": 12,
|
| 10 |
-
"head_dim": 64,
|
| 11 |
-
"qk_norm": true,
|
| 12 |
"latent_dim": 256,
|
| 13 |
"ffn_hidden_dim": 2048,
|
| 14 |
"transformer_layers": 12,
|
| 15 |
-
"rope_theta": 5000000,
|
| 16 |
-
"rms_norm_eps": 1e-06,
|
| 17 |
"tie_embeddings": false,
|
| 18 |
"trained_context_len": 2048,
|
| 19 |
-
"torch_dtype": "bfloat16",
|
| 20 |
"num_parameters": 155293056,
|
| 21 |
-
"num_non_embedding_parameters": 116659584
|
|
|
|
|
|
|
|
|
|
| 22 |
}
|
|
|
|
| 1 |
{
|
| 2 |
"model_type": "nanoi1",
|
| 3 |
"architectures": [
|
| 4 |
+
"NanoI1ForCausalLM"
|
| 5 |
],
|
| 6 |
+
"auto_map": {
|
| 7 |
+
"AutoConfig": "configuration_nanoi1.NanoI1Config",
|
| 8 |
+
"AutoModel": "modeling_nanoi1_hf.NanoI1Model",
|
| 9 |
+
"AutoModelForCausalLM": "modeling_nanoi1_hf.NanoI1ForCausalLM"
|
| 10 |
+
},
|
| 11 |
"vocab_size": 50304,
|
| 12 |
+
"hidden_size": 768,
|
| 13 |
+
"intermediate_size": 2048,
|
| 14 |
+
"num_hidden_layers": 12,
|
| 15 |
+
"num_attention_heads": 12,
|
| 16 |
+
"num_key_value_heads": 12,
|
| 17 |
+
"head_dim": 64,
|
| 18 |
+
"kv_latent_dim": 256,
|
| 19 |
+
"qk_norm": true,
|
| 20 |
+
"rms_norm_eps": 1e-06,
|
| 21 |
+
"rope_theta": 5000000.0,
|
| 22 |
+
"max_position_embeddings": 2048,
|
| 23 |
+
"tie_word_embeddings": false,
|
| 24 |
+
"torch_dtype": "bfloat16",
|
| 25 |
"embed_dim": 768,
|
| 26 |
"context_len": 131072,
|
| 27 |
"num_heads": 12,
|
|
|
|
|
|
|
| 28 |
"latent_dim": 256,
|
| 29 |
"ffn_hidden_dim": 2048,
|
| 30 |
"transformer_layers": 12,
|
|
|
|
|
|
|
| 31 |
"tie_embeddings": false,
|
| 32 |
"trained_context_len": 2048,
|
|
|
|
| 33 |
"num_parameters": 155293056,
|
| 34 |
+
"num_non_embedding_parameters": 116659584,
|
| 35 |
+
"bos_token_id": 0,
|
| 36 |
+
"eos_token_id": 4,
|
| 37 |
+
"pad_token_id": 1
|
| 38 |
}
|
configuration_nanoi1.py
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Transformers config for NanoI1 (used with trust_remote_code by AutoModel / AutoModelForCausalLM and vLLM)."""
|
| 2 |
+
|
| 3 |
+
from transformers import PretrainedConfig
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
class NanoI1Config(PretrainedConfig):
|
| 7 |
+
model_type = "nanoi1"
|
| 8 |
+
keys_to_ignore_at_inference = ["past_key_values"]
|
| 9 |
+
|
| 10 |
+
def __init__(
|
| 11 |
+
self,
|
| 12 |
+
vocab_size=50304,
|
| 13 |
+
hidden_size=768,
|
| 14 |
+
intermediate_size=2048,
|
| 15 |
+
num_hidden_layers=12,
|
| 16 |
+
num_attention_heads=12,
|
| 17 |
+
num_key_value_heads=None,
|
| 18 |
+
head_dim=64,
|
| 19 |
+
kv_latent_dim=256, # MLA latent width (deliberately not called kv_lora_rank: see modeling file)
|
| 20 |
+
qk_norm=True,
|
| 21 |
+
rms_norm_eps=1e-6,
|
| 22 |
+
rope_theta=5_000_000.0,
|
| 23 |
+
max_position_embeddings=2048,
|
| 24 |
+
initializer_range=0.02,
|
| 25 |
+
use_cache=True,
|
| 26 |
+
bos_token_id=None,
|
| 27 |
+
eos_token_id=None,
|
| 28 |
+
pad_token_id=None,
|
| 29 |
+
tie_word_embeddings=False,
|
| 30 |
+
**kwargs,
|
| 31 |
+
):
|
| 32 |
+
self.vocab_size = vocab_size
|
| 33 |
+
self.hidden_size = hidden_size
|
| 34 |
+
self.intermediate_size = intermediate_size
|
| 35 |
+
self.num_hidden_layers = num_hidden_layers
|
| 36 |
+
self.num_attention_heads = num_attention_heads
|
| 37 |
+
# keys and values are expanded per head from the latent, so every query head has its own k/v head
|
| 38 |
+
self.num_key_value_heads = num_key_value_heads or num_attention_heads
|
| 39 |
+
self.head_dim = head_dim
|
| 40 |
+
self.kv_latent_dim = kv_latent_dim
|
| 41 |
+
self.qk_norm = qk_norm
|
| 42 |
+
self.rms_norm_eps = rms_norm_eps
|
| 43 |
+
self.rope_theta = rope_theta
|
| 44 |
+
self.max_position_embeddings = max_position_embeddings
|
| 45 |
+
self.initializer_range = initializer_range
|
| 46 |
+
self.use_cache = use_cache
|
| 47 |
+
self.attention_bias = True
|
| 48 |
+
self.hidden_act = "silu"
|
| 49 |
+
super().__init__(bos_token_id=bos_token_id, eos_token_id=eos_token_id, pad_token_id=pad_token_id,
|
| 50 |
+
tie_word_embeddings=tie_word_embeddings, **kwargs)
|
| 51 |
+
self.rope_theta = rope_theta # some transformers versions move it into rope_parameters; keep it readable
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
__all__ = ["NanoI1Config"]
|
model.safetensors
CHANGED
|
@@ -1,3 +1,3 @@
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
-
oid sha256:
|
| 3 |
-
size
|
|
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:bc6425a0b494908cbb6d706debb6933a7d84fb13ce6498af423d89aa0ec0d4d4
|
| 3 |
+
size 310613040
|
modeling_nanoi1.py
CHANGED
|
@@ -10,9 +10,44 @@ Base model: use model(...) for logits, or chat.generate(...) on plain token ids.
|
|
| 10 |
|
| 11 |
import json
|
| 12 |
import os
|
|
|
|
| 13 |
|
| 14 |
import torch
|
| 15 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
|
| 17 |
def _local_dir(name_or_path, revision=None):
|
| 18 |
if os.path.isdir(name_or_path):
|
|
@@ -33,7 +68,10 @@ def from_pretrained(name_or_path, device=None, dtype=None, revision=None):
|
|
| 33 |
keys = ("vocab_size", "embed_dim", "num_heads", "transformer_layers", "head_dim", "context_len", "qk_norm",
|
| 34 |
"ffn_hidden_dim", "latent_dim", "rope_theta", "rms_norm_eps", "tie_embeddings")
|
| 35 |
model = NanoI1Model(**{k: cfg[k] for k in keys if k in cfg})
|
| 36 |
-
|
|
|
|
|
|
|
|
|
|
| 37 |
device = torch.device(device or ("cuda" if torch.cuda.is_available() else "cpu"))
|
| 38 |
dtype = dtype or (torch.bfloat16 if device.type == "cuda" else torch.float32)
|
| 39 |
model.to(device=device, dtype=dtype).eval()
|
|
|
|
| 10 |
|
| 11 |
import json
|
| 12 |
import os
|
| 13 |
+
import re
|
| 14 |
|
| 15 |
import torch
|
| 16 |
|
| 17 |
+
# Weight names: model.py (native) <-> Transformers layout (modeling_nanoi1_hf.py, used by AutoModel and vLLM).
|
| 18 |
+
_LAYER = [("rms_norm1.", "input_layernorm."), ("rms_norm2.", "post_attention_layernorm."),
|
| 19 |
+
("mla_block.w_q.", "self_attn.q_proj."), ("mla_block.w_dkv.", "self_attn.kv_down_proj."),
|
| 20 |
+
("mla_block.w_uk.", "self_attn.k_up_proj."), ("mla_block.w_uv.", "self_attn.v_up_proj."),
|
| 21 |
+
("mla_block.w_o.", "self_attn.o_proj."), ("mla_block.q_norm.", "self_attn.q_norm."),
|
| 22 |
+
("mla_block.k_norm.", "self_attn.k_norm."), ("ffn.fc1.", "mlp.gate_proj."),
|
| 23 |
+
("ffn.fc2.", "mlp.up_proj."), ("ffn.fc3.", "mlp.down_proj.")]
|
| 24 |
+
_TOP = [("input_embedding.", "model.embed_tokens."), ("final_norm.", "model.norm."),
|
| 25 |
+
("output_linear.linear.", "lm_head.")]
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def native_to_hf(name):
|
| 29 |
+
m = re.match(r"transformer_blocks\.(\d+)\.(.*)", name)
|
| 30 |
+
if m:
|
| 31 |
+
for a, b in _LAYER:
|
| 32 |
+
if m.group(2).startswith(a):
|
| 33 |
+
return f"model.layers.{m.group(1)}.{b}{m.group(2)[len(a):]}"
|
| 34 |
+
for a, b in _TOP:
|
| 35 |
+
if name.startswith(a):
|
| 36 |
+
return b + name[len(a):]
|
| 37 |
+
raise KeyError(f"no Transformers name for weight {name}")
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def hf_to_native(name):
|
| 41 |
+
m = re.match(r"model\.layers\.(\d+)\.(.*)", name)
|
| 42 |
+
if m:
|
| 43 |
+
for a, b in _LAYER:
|
| 44 |
+
if m.group(2).startswith(b):
|
| 45 |
+
return f"transformer_blocks.{m.group(1)}.{a}{m.group(2)[len(b):]}"
|
| 46 |
+
for a, b in _TOP:
|
| 47 |
+
if name.startswith(b):
|
| 48 |
+
return a + name[len(b):]
|
| 49 |
+
raise KeyError(f"no native name for weight {name}")
|
| 50 |
+
|
| 51 |
|
| 52 |
def _local_dir(name_or_path, revision=None):
|
| 53 |
if os.path.isdir(name_or_path):
|
|
|
|
| 68 |
keys = ("vocab_size", "embed_dim", "num_heads", "transformer_layers", "head_dim", "context_len", "qk_norm",
|
| 69 |
"ffn_hidden_dim", "latent_dim", "rope_theta", "rms_norm_eps", "tie_embeddings")
|
| 70 |
model = NanoI1Model(**{k: cfg[k] for k in keys if k in cfg})
|
| 71 |
+
sd = load_file(os.path.join(d, "model.safetensors"))
|
| 72 |
+
if any(k.startswith(("model.", "lm_head.")) for k in sd): # Transformers-layout export
|
| 73 |
+
sd = {hf_to_native(k): v for k, v in sd.items()}
|
| 74 |
+
model.load_state_dict(sd)
|
| 75 |
device = torch.device(device or ("cuda" if torch.cuda.is_available() else "cpu"))
|
| 76 |
dtype = dtype or (torch.bfloat16 if device.type == "cuda" else torch.float32)
|
| 77 |
model.to(device=device, dtype=dtype).eval()
|
modeling_nanoi1_hf.py
ADDED
|
@@ -0,0 +1,338 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Transformers implementation of NanoI1, for AutoModelForCausalLM (trust_remote_code=True) and vLLM's
|
| 3 |
+
Transformers modeling backend. Numerically the same network as model.py (verified by export_hf.py --check).
|
| 4 |
+
|
| 5 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 6 |
+
tok = AutoTokenizer.from_pretrained(path, trust_remote_code=True)
|
| 7 |
+
model = AutoModelForCausalLM.from_pretrained(path, trust_remote_code=True, dtype="bfloat16")
|
| 8 |
+
|
| 9 |
+
vllm serve <path> --trust-remote-code --model-impl transformers --max-model-len 2048
|
| 10 |
+
|
| 11 |
+
Attention: Multi-Head Latent Attention. x -> latent c (kv_down_proj, 256-d) -> per-head k, v (k_up_proj,
|
| 12 |
+
v_up_proj); QK-norm, then RoPE on the full 64-d head. Because RoPE is applied after the up-projection, the
|
| 13 |
+
latent cannot be cached on its own with RoPE absorbed (DeepSeek-style), so this implementation (and vLLM)
|
| 14 |
+
caches the expanded k/v like standard multi-head attention. The model is identical; only the KV-cache
|
| 15 |
+
saving of the latent is not used here.
|
| 16 |
+
"""
|
| 17 |
+
|
| 18 |
+
from typing import Optional
|
| 19 |
+
|
| 20 |
+
import torch
|
| 21 |
+
import torch.nn.functional as F
|
| 22 |
+
from torch import nn
|
| 23 |
+
from transformers import GenerationMixin, PreTrainedModel
|
| 24 |
+
from transformers.activations import ACT2FN
|
| 25 |
+
from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
|
| 26 |
+
from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS
|
| 27 |
+
|
| 28 |
+
from .configuration_nanoi1 import NanoI1Config
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def _patch_vllm_lm_head_bias():
|
| 32 |
+
"""NanoI1's output layer has a bias. vLLM (<= 0.31) registers that bias while loading weights, outside its
|
| 33 |
+
device context, so it lands on the CPU and the first forward fails with a device mismatch. When this file
|
| 34 |
+
is imported inside vLLM, create the bias on the device of the head's weight instead. No-op elsewhere."""
|
| 35 |
+
import sys
|
| 36 |
+
if "vllm" not in sys.modules:
|
| 37 |
+
return
|
| 38 |
+
try:
|
| 39 |
+
from torch.nn import Parameter
|
| 40 |
+
from vllm.model_executor.layers.vocab_parallel_embedding import ParallelLMHead
|
| 41 |
+
from vllm.model_executor.utils import set_weight_attrs
|
| 42 |
+
except Exception:
|
| 43 |
+
return
|
| 44 |
+
if getattr(ParallelLMHead, "_nanoi1_bias_patch", False):
|
| 45 |
+
return
|
| 46 |
+
|
| 47 |
+
def _register_bias(self):
|
| 48 |
+
weight = getattr(self, "weight", None)
|
| 49 |
+
device = weight.device if isinstance(weight, torch.Tensor) and weight.device.type != "meta" else None
|
| 50 |
+
data = torch.empty(self.num_embeddings_per_partition, dtype=self.params_dtype, device=device)
|
| 51 |
+
self.bias = Parameter(data, requires_grad=False)
|
| 52 |
+
set_weight_attrs(self.bias, dict(output_dim=0, weight_loader=self.weight_loader))
|
| 53 |
+
|
| 54 |
+
ParallelLMHead._register_bias = _register_bias
|
| 55 |
+
ParallelLMHead._nanoi1_bias_patch = True
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
_patch_vllm_lm_head_bias()
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
class NanoI1RMSNorm(nn.Module):
|
| 62 |
+
def __init__(self, hidden_size, eps=1e-6):
|
| 63 |
+
super().__init__()
|
| 64 |
+
self.weight = nn.Parameter(torch.ones(hidden_size))
|
| 65 |
+
self.variance_epsilon = eps
|
| 66 |
+
|
| 67 |
+
def forward(self, hidden_states):
|
| 68 |
+
input_dtype = hidden_states.dtype
|
| 69 |
+
hidden_states = hidden_states.to(torch.float32)
|
| 70 |
+
variance = hidden_states.pow(2).mean(-1, keepdim=True)
|
| 71 |
+
hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
|
| 72 |
+
return self.weight * hidden_states.to(input_dtype)
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
class NanoI1RotaryEmbedding(nn.Module):
|
| 76 |
+
"""RoPE over the full head dim, rotate-half layout (as model.py). The inverse frequencies are recomputed
|
| 77 |
+
on every call (32 numbers) instead of kept in a buffer, so meta-device initialisation in Transformers
|
| 78 |
+
and vLLM can never leave them uninitialised."""
|
| 79 |
+
|
| 80 |
+
def __init__(self, config: NanoI1Config):
|
| 81 |
+
super().__init__()
|
| 82 |
+
self.dim = config.head_dim
|
| 83 |
+
self.base = float(config.rope_theta)
|
| 84 |
+
|
| 85 |
+
@torch.no_grad()
|
| 86 |
+
def forward(self, x, position_ids):
|
| 87 |
+
exponent = torch.arange(0, self.dim, 2, device=x.device, dtype=torch.int64).float() / self.dim
|
| 88 |
+
inv_freq = 1.0 / (self.base ** exponent)
|
| 89 |
+
freqs = position_ids[..., None].float() * inv_freq # [b, seq, dim/2]
|
| 90 |
+
emb = torch.cat((freqs, freqs), dim=-1)
|
| 91 |
+
return emb.cos().to(x.dtype), emb.sin().to(x.dtype)
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def rotate_half(x):
|
| 95 |
+
x1, x2 = x.chunk(2, dim=-1)
|
| 96 |
+
return torch.cat((-x2, x1), dim=-1)
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def apply_rotary_pos_emb(q, k, cos, sin):
|
| 100 |
+
cos, sin = cos.unsqueeze(1), sin.unsqueeze(1)
|
| 101 |
+
return (q * cos) + (rotate_half(q) * sin), (k * cos) + (rotate_half(k) * sin)
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def eager_attention_forward(module, query, key, value, attention_mask, scaling, dropout=0.0, **kwargs):
|
| 105 |
+
attn_weights = torch.matmul(query, key.transpose(2, 3)) * scaling
|
| 106 |
+
if attention_mask is not None:
|
| 107 |
+
attn_weights = attn_weights + attention_mask[:, :, :, : key.shape[-2]]
|
| 108 |
+
attn_weights = F.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
|
| 109 |
+
attn_weights = F.dropout(attn_weights, p=dropout, training=module.training)
|
| 110 |
+
attn_output = torch.matmul(attn_weights, value)
|
| 111 |
+
return attn_output.transpose(1, 2).contiguous(), attn_weights
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
class NanoI1Attention(nn.Module):
|
| 115 |
+
def __init__(self, config: NanoI1Config, layer_idx: int):
|
| 116 |
+
super().__init__()
|
| 117 |
+
self.config = config
|
| 118 |
+
self.layer_idx = layer_idx
|
| 119 |
+
self.num_heads = config.num_attention_heads
|
| 120 |
+
self.head_dim = config.head_dim
|
| 121 |
+
self.scaling = self.head_dim ** -0.5
|
| 122 |
+
self.is_causal = True
|
| 123 |
+
inner = self.num_heads * self.head_dim
|
| 124 |
+
self.q_proj = nn.Linear(config.hidden_size, inner, bias=True)
|
| 125 |
+
self.kv_down_proj = nn.Linear(config.hidden_size, config.kv_latent_dim, bias=True)
|
| 126 |
+
self.k_up_proj = nn.Linear(config.kv_latent_dim, inner, bias=True)
|
| 127 |
+
self.v_up_proj = nn.Linear(config.kv_latent_dim, inner, bias=True)
|
| 128 |
+
self.o_proj = nn.Linear(inner, config.hidden_size, bias=True)
|
| 129 |
+
if config.qk_norm:
|
| 130 |
+
self.q_norm = NanoI1RMSNorm(self.head_dim, eps=config.rms_norm_eps)
|
| 131 |
+
self.k_norm = NanoI1RMSNorm(self.head_dim, eps=config.rms_norm_eps)
|
| 132 |
+
else:
|
| 133 |
+
self.q_norm = nn.Identity()
|
| 134 |
+
self.k_norm = nn.Identity()
|
| 135 |
+
|
| 136 |
+
def forward(self, hidden_states, position_embeddings, attention_mask=None, past_key_values=None, **kwargs):
|
| 137 |
+
input_shape = hidden_states.shape[:-1]
|
| 138 |
+
hidden_shape = (*input_shape, -1, self.head_dim)
|
| 139 |
+
|
| 140 |
+
latent = self.kv_down_proj(hidden_states)
|
| 141 |
+
query_states = self.q_norm(self.q_proj(hidden_states).view(hidden_shape)).transpose(1, 2)
|
| 142 |
+
key_states = self.k_norm(self.k_up_proj(latent).view(hidden_shape)).transpose(1, 2)
|
| 143 |
+
value_states = self.v_up_proj(latent).view(hidden_shape).transpose(1, 2)
|
| 144 |
+
|
| 145 |
+
cos, sin = position_embeddings
|
| 146 |
+
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
|
| 147 |
+
|
| 148 |
+
if past_key_values is not None:
|
| 149 |
+
key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx)
|
| 150 |
+
|
| 151 |
+
attention_interface = ALL_ATTENTION_FUNCTIONS.get_interface(
|
| 152 |
+
self.config._attn_implementation, eager_attention_forward
|
| 153 |
+
)
|
| 154 |
+
attn_output, attn_weights = attention_interface(
|
| 155 |
+
self,
|
| 156 |
+
query_states,
|
| 157 |
+
key_states,
|
| 158 |
+
value_states,
|
| 159 |
+
attention_mask,
|
| 160 |
+
dropout=0.0,
|
| 161 |
+
scaling=self.scaling,
|
| 162 |
+
**kwargs,
|
| 163 |
+
)
|
| 164 |
+
attn_output = attn_output.reshape(*input_shape, -1).contiguous()
|
| 165 |
+
return self.o_proj(attn_output), attn_weights
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
class NanoI1MLP(nn.Module):
|
| 169 |
+
def __init__(self, config: NanoI1Config):
|
| 170 |
+
super().__init__()
|
| 171 |
+
self.gate_proj = nn.Linear(config.hidden_size, config.intermediate_size, bias=True)
|
| 172 |
+
self.up_proj = nn.Linear(config.hidden_size, config.intermediate_size, bias=True)
|
| 173 |
+
self.down_proj = nn.Linear(config.intermediate_size, config.hidden_size, bias=True)
|
| 174 |
+
self.act_fn = ACT2FN[config.hidden_act]
|
| 175 |
+
|
| 176 |
+
def forward(self, x):
|
| 177 |
+
return self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
class NanoI1DecoderLayer(nn.Module):
|
| 181 |
+
def __init__(self, config: NanoI1Config, layer_idx: int):
|
| 182 |
+
super().__init__()
|
| 183 |
+
self.self_attn = NanoI1Attention(config, layer_idx)
|
| 184 |
+
self.mlp = NanoI1MLP(config)
|
| 185 |
+
self.input_layernorm = NanoI1RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
| 186 |
+
self.post_attention_layernorm = NanoI1RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
| 187 |
+
|
| 188 |
+
def forward(self, hidden_states, position_embeddings, attention_mask=None, past_key_values=None, **kwargs):
|
| 189 |
+
residual = hidden_states
|
| 190 |
+
hidden_states = self.input_layernorm(hidden_states)
|
| 191 |
+
hidden_states, _ = self.self_attn(hidden_states, position_embeddings, attention_mask, past_key_values,
|
| 192 |
+
**kwargs)
|
| 193 |
+
hidden_states = residual + hidden_states
|
| 194 |
+
residual = hidden_states
|
| 195 |
+
hidden_states = self.mlp(self.post_attention_layernorm(hidden_states))
|
| 196 |
+
return residual + hidden_states
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
class NanoI1PreTrainedModel(PreTrainedModel):
|
| 200 |
+
config_class = NanoI1Config
|
| 201 |
+
base_model_prefix = "model"
|
| 202 |
+
supports_gradient_checkpointing = False
|
| 203 |
+
_no_split_modules = ["NanoI1DecoderLayer"]
|
| 204 |
+
_supports_sdpa = True
|
| 205 |
+
_supports_flash_attn = False
|
| 206 |
+
_supports_flex_attn = False
|
| 207 |
+
_supports_attention_backend = True
|
| 208 |
+
|
| 209 |
+
def _init_weights(self, module):
|
| 210 |
+
std = self.config.initializer_range
|
| 211 |
+
if isinstance(module, nn.Linear):
|
| 212 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
| 213 |
+
if module.bias is not None:
|
| 214 |
+
module.bias.data.zero_()
|
| 215 |
+
elif isinstance(module, nn.Embedding):
|
| 216 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
| 217 |
+
elif isinstance(module, NanoI1RMSNorm):
|
| 218 |
+
module.weight.data.fill_(1.0)
|
| 219 |
+
|
| 220 |
+
|
| 221 |
+
def _new_cache(config):
|
| 222 |
+
from transformers.cache_utils import DynamicCache
|
| 223 |
+
try:
|
| 224 |
+
return DynamicCache(config=config)
|
| 225 |
+
except TypeError:
|
| 226 |
+
return DynamicCache()
|
| 227 |
+
|
| 228 |
+
|
| 229 |
+
class NanoI1Model(NanoI1PreTrainedModel):
|
| 230 |
+
def __init__(self, config: NanoI1Config):
|
| 231 |
+
super().__init__(config)
|
| 232 |
+
self.padding_idx = config.pad_token_id
|
| 233 |
+
self.vocab_size = config.vocab_size
|
| 234 |
+
self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size)
|
| 235 |
+
self.layers = nn.ModuleList([NanoI1DecoderLayer(config, i) for i in range(config.num_hidden_layers)])
|
| 236 |
+
self.norm = NanoI1RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
| 237 |
+
self.rotary_emb = NanoI1RotaryEmbedding(config)
|
| 238 |
+
self.post_init()
|
| 239 |
+
|
| 240 |
+
def get_input_embeddings(self):
|
| 241 |
+
return self.embed_tokens
|
| 242 |
+
|
| 243 |
+
def set_input_embeddings(self, value):
|
| 244 |
+
self.embed_tokens = value
|
| 245 |
+
|
| 246 |
+
def _mask(self, attention_mask, q_len, past_len, dtype, device):
|
| 247 |
+
"""Additive [b, 1, q, kv] mask, or None when plain causal attention is enough."""
|
| 248 |
+
impl = self.config._attn_implementation
|
| 249 |
+
kv_len = past_len + q_len
|
| 250 |
+
has_pad = attention_mask is not None and not bool(attention_mask[:, -kv_len:].all())
|
| 251 |
+
if impl not in ("eager", "sdpa") or (impl == "sdpa" and not has_pad and (past_len == 0 or q_len == 1)):
|
| 252 |
+
return None # sdpa uses is_causal for a fresh prefill; vLLM and others handle masking themselves
|
| 253 |
+
q_pos = torch.arange(q_len, device=device)[:, None] + past_len
|
| 254 |
+
k_pos = torch.arange(kv_len, device=device)[None, :]
|
| 255 |
+
allowed = (k_pos <= q_pos)[None, None]
|
| 256 |
+
if attention_mask is not None:
|
| 257 |
+
keys = attention_mask[:, -kv_len:].to(device=device, dtype=torch.bool)
|
| 258 |
+
# each query may always see itself, so all-padding rows stay finite (as in model.py)
|
| 259 |
+
allowed = (allowed & keys[:, None, None, :]) | (k_pos == q_pos)[None, None]
|
| 260 |
+
mask = torch.zeros(allowed.shape, dtype=dtype, device=device)
|
| 261 |
+
return mask.masked_fill(~allowed, torch.finfo(dtype).min)
|
| 262 |
+
|
| 263 |
+
def forward(self, input_ids=None, attention_mask=None, position_ids=None, past_key_values=None,
|
| 264 |
+
inputs_embeds=None, use_cache=None, return_dict=None, **kwargs):
|
| 265 |
+
kwargs.pop("cache_position", None)
|
| 266 |
+
kwargs.pop("output_attentions", None)
|
| 267 |
+
kwargs.pop("output_hidden_states", None)
|
| 268 |
+
if (input_ids is None) == (inputs_embeds is None):
|
| 269 |
+
raise ValueError("pass exactly one of input_ids or inputs_embeds")
|
| 270 |
+
if inputs_embeds is None:
|
| 271 |
+
inputs_embeds = self.embed_tokens(input_ids)
|
| 272 |
+
use_cache = use_cache if use_cache is not None else (self.config.use_cache and not self.training)
|
| 273 |
+
if use_cache and past_key_values is None:
|
| 274 |
+
past_key_values = _new_cache(self.config)
|
| 275 |
+
if not use_cache:
|
| 276 |
+
past_key_values = None
|
| 277 |
+
past_len = past_key_values.get_seq_length() if past_key_values is not None else 0
|
| 278 |
+
q_len = inputs_embeds.shape[1]
|
| 279 |
+
if position_ids is None:
|
| 280 |
+
positions = torch.arange(past_len, past_len + q_len, device=inputs_embeds.device)
|
| 281 |
+
position_ids = positions.unsqueeze(0).expand(inputs_embeds.shape[0], -1)
|
| 282 |
+
|
| 283 |
+
mask = self._mask(attention_mask, q_len, past_len, inputs_embeds.dtype, inputs_embeds.device)
|
| 284 |
+
hidden_states = inputs_embeds
|
| 285 |
+
position_embeddings = self.rotary_emb(hidden_states, position_ids)
|
| 286 |
+
for layer in self.layers:
|
| 287 |
+
hidden_states = layer(hidden_states, position_embeddings, mask, past_key_values, **kwargs)
|
| 288 |
+
hidden_states = self.norm(hidden_states)
|
| 289 |
+
|
| 290 |
+
if return_dict is False:
|
| 291 |
+
return (hidden_states, past_key_values) if use_cache else (hidden_states,)
|
| 292 |
+
return BaseModelOutputWithPast(last_hidden_state=hidden_states, past_key_values=past_key_values)
|
| 293 |
+
|
| 294 |
+
|
| 295 |
+
class NanoI1ForCausalLM(NanoI1PreTrainedModel, GenerationMixin):
|
| 296 |
+
_tied_weights_keys = []
|
| 297 |
+
|
| 298 |
+
def __init__(self, config: NanoI1Config):
|
| 299 |
+
super().__init__(config)
|
| 300 |
+
self.model = NanoI1Model(config)
|
| 301 |
+
self.vocab_size = config.vocab_size
|
| 302 |
+
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=True)
|
| 303 |
+
self.post_init()
|
| 304 |
+
|
| 305 |
+
def get_input_embeddings(self):
|
| 306 |
+
return self.model.embed_tokens
|
| 307 |
+
|
| 308 |
+
def set_input_embeddings(self, value):
|
| 309 |
+
self.model.embed_tokens = value
|
| 310 |
+
|
| 311 |
+
def get_output_embeddings(self):
|
| 312 |
+
return self.lm_head
|
| 313 |
+
|
| 314 |
+
def set_output_embeddings(self, new_embeddings):
|
| 315 |
+
self.lm_head = new_embeddings
|
| 316 |
+
|
| 317 |
+
def get_decoder(self):
|
| 318 |
+
return self.model
|
| 319 |
+
|
| 320 |
+
def forward(self, input_ids=None, attention_mask=None, position_ids=None, past_key_values=None,
|
| 321 |
+
inputs_embeds=None, labels=None, use_cache=None, logits_to_keep=0, return_dict=None, **kwargs):
|
| 322 |
+
out = self.model(input_ids=input_ids, attention_mask=attention_mask, position_ids=position_ids,
|
| 323 |
+
past_key_values=past_key_values, inputs_embeds=inputs_embeds, use_cache=use_cache,
|
| 324 |
+
return_dict=True, **kwargs)
|
| 325 |
+
hidden_states = out.last_hidden_state
|
| 326 |
+
keep = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
|
| 327 |
+
logits = self.lm_head(hidden_states[:, keep, :])
|
| 328 |
+
loss = None
|
| 329 |
+
if labels is not None:
|
| 330 |
+
loss = F.cross_entropy(logits[:, :-1].float().reshape(-1, logits.size(-1)),
|
| 331 |
+
labels[:, 1:].reshape(-1), ignore_index=-100)
|
| 332 |
+
if return_dict is False:
|
| 333 |
+
res = (logits, out.past_key_values)
|
| 334 |
+
return ((loss,) + res) if loss is not None else res
|
| 335 |
+
return CausalLMOutputWithPast(loss=loss, logits=logits, past_key_values=out.past_key_values)
|
| 336 |
+
|
| 337 |
+
|
| 338 |
+
__all__ = ["NanoI1PreTrainedModel", "NanoI1Model", "NanoI1ForCausalLM"]
|