NanoI1-155M-Instruct / modeling_nanoi1.py
anuj0456's picture
Upload folder using huggingface_hub
913fd49 verified
Raw History Blame Contribute Delete
4.14 kB
"""
Load NanoI1 from a Hugging Face repo or a local folder exported by export_hf.py.
from modeling_nanoi1 import from_pretrained, chat
model, tok = from_pretrained("KiteFishAI/NanoI1-155M-Instruct") # or a local folder
print(chat(model, tok, [{"role": "user", "content": "Explain KYC in two sentences."}]))
Base model: use model(...) for logits, or chat.generate(...) on plain token ids.
"""
import json
import os
import re
import torch
# Weight names: model.py (native) <-> Transformers layout (modeling_nanoi1_hf.py, used by AutoModel and vLLM).
_LAYER = [("rms_norm1.", "input_layernorm."), ("rms_norm2.", "post_attention_layernorm."),
("mla_block.w_q.", "self_attn.q_proj."), ("mla_block.w_dkv.", "self_attn.kv_down_proj."),
("mla_block.w_uk.", "self_attn.k_up_proj."), ("mla_block.w_uv.", "self_attn.v_up_proj."),
("mla_block.w_o.", "self_attn.o_proj."), ("mla_block.q_norm.", "self_attn.q_norm."),
("mla_block.k_norm.", "self_attn.k_norm."), ("ffn.fc1.", "mlp.gate_proj."),
("ffn.fc2.", "mlp.up_proj."), ("ffn.fc3.", "mlp.down_proj.")]
_TOP = [("input_embedding.", "model.embed_tokens."), ("final_norm.", "model.norm."),
("output_linear.linear.", "lm_head.")]
def native_to_hf(name):
m = re.match(r"transformer_blocks\.(\d+)\.(.*)", name)
if m:
for a, b in _LAYER:
if m.group(2).startswith(a):
return f"model.layers.{m.group(1)}.{b}{m.group(2)[len(a):]}"
for a, b in _TOP:
if name.startswith(a):
return b + name[len(a):]
raise KeyError(f"no Transformers name for weight {name}")
def hf_to_native(name):
m = re.match(r"model\.layers\.(\d+)\.(.*)", name)
if m:
for a, b in _LAYER:
if m.group(2).startswith(b):
return f"transformer_blocks.{m.group(1)}.{a}{m.group(2)[len(b):]}"
for a, b in _TOP:
if name.startswith(b):
return a + name[len(b):]
raise KeyError(f"no native name for weight {name}")
def _local_dir(name_or_path, revision=None):
if os.path.isdir(name_or_path):
return name_or_path
from huggingface_hub import snapshot_download
return snapshot_download(name_or_path, revision=revision,
allow_patterns=["*.json", "*.safetensors", "*.py"])
def from_pretrained(name_or_path, device=None, dtype=None, revision=None):
"""Returns (model in eval mode, tokenizers.Tokenizer)."""
from safetensors.torch import load_file
from tokenizers import Tokenizer
from model import NanoI1Model
d = _local_dir(name_or_path, revision)
cfg = json.load(open(os.path.join(d, "config.json")))
keys = ("vocab_size", "embed_dim", "num_heads", "transformer_layers", "head_dim", "context_len", "qk_norm",
"ffn_hidden_dim", "latent_dim", "rope_theta", "rms_norm_eps", "tie_embeddings")
model = NanoI1Model(**{k: cfg[k] for k in keys if k in cfg})
sd = load_file(os.path.join(d, "model.safetensors"))
if any(k.startswith(("model.", "lm_head.")) for k in sd): # Transformers-layout export
sd = {hf_to_native(k): v for k, v in sd.items()}
model.load_state_dict(sd)
device = torch.device(device or ("cuda" if torch.cuda.is_available() else "cpu"))
dtype = dtype or (torch.bfloat16 if device.type == "cuda" else torch.float32)
model.to(device=device, dtype=dtype).eval()
# generate within the context length the model was trained at
model.config = {**model.config, "context_len": min(cfg["context_len"], cfg.get("trained_context_len", 2048))}
return model, Tokenizer.from_file(os.path.join(d, "tokenizer.json"))
@torch.no_grad()
def chat(model, tok, messages, max_new_tokens=512, temperature=0.7, top_p=0.9, repetition_penalty=1.1):
"""messages: [{"role": "system"|"user"|"assistant", "content": str}, ...]. temperature=0 -> greedy."""
from chat import generate_reply
from chat_format import sanitize
msgs = [{**m, "content": sanitize(m["content"], tok)} for m in messages]
return generate_reply(model, tok, msgs, max_new_tokens, temperature, top_p, repetition_penalty)