import torch
import torch.nn as nn
import torch.nn.functional as F
from safetensors.torch import load_file
from transformers import AutoTokenizer
from huggingface_hub import hf_hub_download
EFFORT_MAP = {"low": 1, "medium": 2, "high": 3, "xhigh": 4}
DEFAULT_SYS = (
"Sen Loop7B v3 adında, dinamik 4-döngülü (Looped Transformer) Türkçe ve İngilizce "
"akıllı bir yapay zeka asistanısın. Karmaşık sorularda ... içinde adım adım "
"düşün, araç gerektiğinde kullan, emin olmadığın konularda bilmediğini dürüstçe söyle."
)
class RMSNorm(nn.Module):
def __init__(self, dim, eps=1e-6):
super().__init__()
self.weight = nn.Parameter(torch.ones(dim))
self.eps = eps
def forward(self, x):
xf = x.float()
return (xf * torch.rsqrt(xf.pow(2).mean(-1, keepdim=True) + self.eps)).to(x.dtype) * self.weight
def precompute_rope(head_dim, max_seq_len=1024, theta=500000.0, dtype=torch.bfloat16):
freqs = 1.0 / (theta ** (torch.arange(0, head_dim, 2, dtype=torch.float32) / head_dim))
angles = torch.outer(torch.arange(max_seq_len, dtype=torch.float32), freqs)
c, s = torch.cos(angles).to(dtype), torch.sin(angles).to(dtype)
return torch.cat((c, c), dim=-1), torch.cat((s, s), dim=-1)
def apply_rope(x, cos, sin):
T = x.size(2)
c, s = cos[:T].unsqueeze(0).unsqueeze(0), sin[:T].unsqueeze(0).unsqueeze(0)
x1, x2 = x.chunk(2, dim=-1)
return (x * c) + (torch.cat((-x2, x1), dim=-1) * s)
class GQAAttention(nn.Module):
def __init__(self, dim=4096, n_heads=32, n_kv_heads=8):
super().__init__()
self.n_heads, self.n_kv_heads = n_heads, n_kv_heads
self.n_rep, self.head_dim = n_heads // n_kv_heads, dim // n_heads
self.q_proj = nn.Linear(dim, n_heads * self.head_dim, bias=False)
self.k_proj = nn.Linear(dim, n_kv_heads * self.head_dim, bias=False)
self.v_proj = nn.Linear(dim, n_kv_heads * self.head_dim, bias=False)
self.o_proj = nn.Linear(dim, dim, bias=False)
def forward(self, x, cos, sin):
B, T, C = x.shape
q = apply_rope(self.q_proj(x).view(B, T, self.n_heads, self.head_dim).transpose(1, 2), cos, sin)
k = apply_rope(self.k_proj(x).view(B, T, self.n_kv_heads, self.head_dim).transpose(1, 2), cos, sin)
v = self.v_proj(x).view(B, T, self.n_kv_heads, self.head_dim).transpose(1, 2)
if self.n_rep > 1:
k = k.repeat_interleave(self.n_rep, dim=1)
v = v.repeat_interleave(self.n_rep, dim=1)
out = F.scaled_dot_product_attention(q, k, v, is_causal=True)
return self.o_proj(out.transpose(1, 2).contiguous().view(B, T, C))
class SwiGLUMLP(nn.Module):
def __init__(self, dim=4096, ffn_dim=12288):
super().__init__()
self.gate_proj = nn.Linear(dim, ffn_dim, bias=False)
self.up_proj = nn.Linear(dim, ffn_dim, bias=False)
self.down_proj = nn.Linear(ffn_dim, dim, bias=False)
def forward(self, x):
return self.down_proj(F.silu(self.gate_proj(x)) * self.up_proj(x))
class LoopedBlock(nn.Module):
def __init__(self, dim=4096, n_heads=32, n_kv_heads=8, ffn_dim=12288):
super().__init__()
self.norm1, self.attn = RMSNorm(dim), GQAAttention(dim, n_heads, n_kv_heads)
self.norm2, self.mlp = RMSNorm(dim), SwiGLUMLP(dim, ffn_dim)
def forward(self, x, step_emb, cos, sin):
x = x + self.attn(self.norm1(x + step_emb), cos, sin)
x = x + self.mlp(self.norm2(x))
return x
class Loop7Bv3Model(nn.Module):
def __init__(self, vocab_size=151680, dim=4096, core_layers=32, n_heads=32, n_kv_heads=8,
ffn_dim=12288, max_loops=4, mtp_heads=4, max_seq_len=1024, dtype=torch.bfloat16):
super().__init__()
self.embed = nn.Embedding(vocab_size, dim)
self.loop_embs = nn.Parameter(torch.zeros(max_loops, 1, 1, dim))
self.loop_alpha = nn.Parameter(torch.tensor(0.05))
self.layers = nn.ModuleList([LoopedBlock(dim, n_heads, n_kv_heads, ffn_dim) for _ in range(core_layers)])
self.norm = RMSNorm(dim)
self.mtp_projs = nn.ModuleList([
nn.Identity() if k == 0 else nn.Sequential(RMSNorm(dim), nn.Linear(dim, dim, bias=False))
for k in range(mtp_heads)
])
self.lm_head = nn.Linear(dim, vocab_size, bias=False)
self.lm_head.weight = self.embed.weight
cos, sin = precompute_rope(dim // n_heads, max_seq_len=max_seq_len, dtype=dtype)
self.register_buffer("rope_cos", cos, persistent=False)
self.register_buffer("rope_sin", sin, persistent=False)
@torch.inference_mode()
def forward_logits(self, input_ids, num_loops=2):
x_embed = self.embed(input_ids)
xf = x_embed.float()
x_inj = (xf * torch.rsqrt(xf.pow(2).mean(-1, keepdim=True) + 1e-6)).to(x_embed.dtype)
x = x_embed
for l in range(num_loops):
if l > 0:
x = x + self.loop_alpha.to(x.dtype) * x_inj
for layer in self.layers:
x = layer(x, self.loop_embs[l], self.rope_cos, self.rope_sin)
return self.lm_head(self.norm(x)[:, -1:, :])
def load_loop7b(repo_id, device="cuda", dtype=torch.bfloat16):
tokenizer = AutoTokenizer.from_pretrained(repo_id)
weights_path = hf_hub_download(repo_id=repo_id, filename="model.safetensors")
sd = {k: v.to(dtype) for k, v in load_file(weights_path).items()}
with torch.device("meta"):
model = Loop7Bv3Model(dtype=dtype)
model.to_empty(device="cpu")
model.load_state_dict(sd, strict=False, assign=True)
model.lm_head.weight = model.embed.weight
model.rope_cos, model.rope_sin = precompute_rope(128, max_seq_len=1024, dtype=dtype)
return model.to(device=device, dtype=dtype).eval(), tokenizer