""" Loop7B v3 — Yerel Sohbet Uygulamasi (4-bit NF4 / BF16 Otomatik + Per-Loop KV-Cache + Gradio) - 6 GB – 15 GB VRAM (RTX 4050, 4060, 3060 vb.): Otomatik 4-bit NF4 + BF16 karma (~4.7 GB VRAM) - 16 GB+ VRAM (RTX 4090, L4, A100, H200 vb.): Otomatik tam BF16 (~13.7 GB VRAM) """ import gc import json import os import time import threading import torch import torch.nn as nn import torch.nn.functional as F import gradio as gr from safetensors import safe_open from huggingface_hub import hf_hub_download from transformers import AutoTokenizer # ========================================== # AYARLAR # ========================================== DEFAULT_REPO_ID = os.environ.get("LOOP7B_REPO", "tm1324/Loop7B-v3-v0.1") QUANT_MODE = os.environ.get("LOOP7B_QUANT", "auto").lower() # "auto" | "4bit" | "bf16" MAX_CONTEXT_LEN = 1024 EFFORT_MAP = { "low (1 Loop / 32L - En Hizli)": 1, "medium (2 Loop / 64L - Dengeli)": 2, "high (3 Loop / 96L - Derin)": 3, "xhigh (4 Loop / 128L - En Derin)": 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." ) # ========================================== # MIMARI (4-bit NF4 / BF16 + PER-LOOP KV-CACHE) # ========================================== class RMSNorm(nn.Module): def __init__(self, dim: int, eps: float = 1e-6): super().__init__() self.weight = nn.Parameter(torch.ones(dim)) self.eps = eps def forward(self, x: torch.Tensor) -> torch.Tensor: 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: int, max_seq_len: int = 2048, theta: float = 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: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor, start_pos: int = 0) -> torch.Tensor: T = x.size(2) c = cos[start_pos : start_pos + T].unsqueeze(0).unsqueeze(0) s = sin[start_pos : start_pos + T].unsqueeze(0).unsqueeze(0) x1, x2 = x.chunk(2, dim=-1) return (x * c) + (torch.cat((-x2, x1), dim=-1) * s) def make_linear(weight_cpu: torch.Tensor, use_4bit: bool, compute_dtype: torch.dtype, device: str) -> nn.Module: out_features, in_features = weight_cpu.shape if use_4bit: import bitsandbytes as bnb layer = bnb.nn.Linear4bit( in_features, out_features, bias=False, compute_dtype=compute_dtype, compress_statistics=True, quant_type="nf4", ) layer.weight = bnb.nn.Params4bit( weight_cpu.to(dtype=torch.float16, device="cpu").contiguous(), requires_grad=False, compress_statistics=True, quant_type="nf4", ) return layer.to(device) else: layer = nn.Linear(in_features, out_features, bias=False) layer.weight = nn.Parameter( weight_cpu.to(device=device, dtype=compute_dtype).contiguous(), requires_grad=False ) return layer class GQAAttention(nn.Module): def __init__(self, dim=4096, n_heads=32, n_kv_heads=8): super().__init__() self.n_heads = n_heads self.n_kv_heads = n_kv_heads self.n_rep = n_heads // n_kv_heads self.head_dim = dim // n_heads self.q_proj = None self.k_proj = None self.v_proj = None self.o_proj = None def forward(self, x, cos, sin, start_pos=0, past_kv=None): 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, start_pos) k = apply_rope(self.k_proj(x).view(B, T, self.n_kv_heads, self.head_dim).transpose(1, 2), cos, sin, start_pos) v = self.v_proj(x).view(B, T, self.n_kv_heads, self.head_dim).transpose(1, 2) if past_kv is not None: k_past, v_past = past_kv k = torch.cat([k_past, k], dim=2) v = torch.cat([v_past, v], dim=2) new_kv = (k, v) if self.n_rep > 1: k_att = k.repeat_interleave(self.n_rep, dim=1) v_att = v.repeat_interleave(self.n_rep, dim=1) else: k_att, v_att = k, v out = F.scaled_dot_product_attention(q, k_att, v_att, is_causal=(T > 1)) return self.o_proj(out.transpose(1, 2).contiguous().view(B, T, C)), new_kv class SwiGLUMLP(nn.Module): def __init__(self): super().__init__() self.gate_proj = None self.up_proj = None self.down_proj = None 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): super().__init__() self.norm1 = RMSNorm(dim) self.attn = GQAAttention(dim, n_heads, n_kv_heads) self.norm2 = RMSNorm(dim) self.mlp = SwiGLUMLP() def forward(self, x, step_emb, cos, sin, start_pos=0, past_kv=None): attn_out, new_kv = self.attn(self.norm1(x + step_emb), cos, sin, start_pos=start_pos, past_kv=past_kv) x = x + attn_out x = x + self.mlp(self.norm2(x)) return x, new_kv class Loop7Bv3Local(nn.Module): def __init__(self, cfg: dict, compute_dtype=torch.bfloat16, device="cuda"): super().__init__() self.dim = cfg["dim"] self.core_layers = cfg["core_layers"] self.n_heads = cfg["n_heads"] self.n_kv_heads = cfg["n_kv_heads"] self.max_loops = cfg["max_loops"] self.vocab_size = cfg["vocab_size"] self.compute_dtype = compute_dtype self.device = device self.embed = nn.Embedding(self.vocab_size, self.dim) self.loop_embs = nn.Parameter(torch.zeros(self.max_loops, 1, 1, self.dim)) self.loop_alpha = nn.Parameter(torch.tensor(0.05)) self.layers = nn.ModuleList([ LoopedBlock(self.dim, self.n_heads, self.n_kv_heads) for _ in range(self.core_layers) ]) self.norm = RMSNorm(self.dim) cos, sin = precompute_rope( self.dim // self.n_heads, max_seq_len=max(2048, cfg.get("max_seq_len", 1024)), theta=cfg.get("rope_theta", 500000.0), dtype=compute_dtype, ) self.register_buffer("rope_cos", cos.to(device), persistent=False) self.register_buffer("rope_sin", sin.to(device), persistent=False) @torch.inference_mode() def forward_step(self, input_ids: torch.Tensor, num_loops: int, start_pos: int = 0, kv_cache=None): 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) if kv_cache is None: kv_cache = [[None] * self.core_layers for _ in range(num_loops)] x = x_embed for l in range(num_loops): if l > 0: x = x + self.loop_alpha.to(x.dtype) * x_inj step_emb = self.loop_embs[l] for i, layer in enumerate(self.layers): x, new_kv = layer( x, step_emb, self.rope_cos, self.rope_sin, start_pos=start_pos, past_kv=kv_cache[l][i], ) kv_cache[l][i] = new_kv logits = F.linear(self.norm(x)[:, -1:, :], self.embed.weight) return logits, kv_cache def resolve_files(repo_id: str): """Eger repo yerel klasore klonlandiysa lokal dosyalari kullanir, yoksa HF'ten indirir.""" here = os.path.dirname(os.path.abspath(__file__)) local_cfg = os.path.join(here, "config.json") local_w = os.path.join(here, "model.safetensors") if os.path.exists(local_cfg) and os.path.exists(local_w): print(f"Yerel model dosyalari bulundu: {here}") return local_cfg, local_w, here print(f"Hugging Face'ten indiriliyor / onbellekten yukleniyor: {repo_id}") cfg_path = hf_hub_download(repo_id=repo_id, filename="config.json") weights_path = hf_hub_download(repo_id=repo_id, filename="model.safetensors") return cfg_path, weights_path, repo_id def load_model(repo_id: str = DEFAULT_REPO_ID): if not torch.cuda.is_available(): raise RuntimeError( "NVIDIA CUDA GPU bulunamadi! PyTorch CUDA surumunun kurulu oldugundan emin ol." ) gpu_name = torch.cuda.get_device_name(0) total_vram_gb = torch.cuda.get_device_properties(0).total_memory / (1024 ** 3) compute_dtype = torch.bfloat16 if torch.cuda.is_bf16_supported() else torch.float16 if QUANT_MODE == "4bit": use_4bit = True elif QUANT_MODE == "bf16": use_4bit = False else: use_4bit = total_vram_gb < 15.5 # 6-12 GB GPU'larda otomatik 4-bit NF4 mode_str = "4-bit NF4 + BF16 (Embed/Loop/Norm)" if use_4bit else f"Tam {compute_dtype}" print(f"Aktif GPU: {gpu_name} ({total_vram_gb:.2f} GB VRAM) | Mod: {mode_str}") cfg_path, weights_path, tok_src = resolve_files(repo_id) tokenizer = AutoTokenizer.from_pretrained(tok_src) with open(cfg_path, "r", encoding="utf-8") as f: cfg = json.load(f) t0 = time.time() model = Loop7Bv3Local(cfg, compute_dtype=compute_dtype, device="cuda") with safe_open(weights_path, framework="pt", device="cpu") as f: model.embed.weight = nn.Parameter( f.get_tensor("embed.weight").to(device="cuda", dtype=compute_dtype), requires_grad=False ) model.loop_embs = nn.Parameter( f.get_tensor("loop_embs").to(device="cuda", dtype=compute_dtype), requires_grad=False ) model.loop_alpha = nn.Parameter( f.get_tensor("loop_alpha").to(device="cuda", dtype=torch.float32), requires_grad=False ) model.norm.weight = nn.Parameter( f.get_tensor("norm.weight").to(device="cuda", dtype=compute_dtype), requires_grad=False ) for i in range(cfg["core_layers"]): blk = model.layers[i] p = f"layers.{i}" blk.norm1.weight = nn.Parameter( f.get_tensor(f"{p}.norm1.weight").to(device="cuda", dtype=compute_dtype), requires_grad=False ) blk.norm2.weight = nn.Parameter( f.get_tensor(f"{p}.norm2.weight").to(device="cuda", dtype=compute_dtype), requires_grad=False ) blk.attn.q_proj = make_linear(f.get_tensor(f"{p}.attn.q_proj.weight"), use_4bit, compute_dtype, "cuda") blk.attn.k_proj = make_linear(f.get_tensor(f"{p}.attn.k_proj.weight"), use_4bit, compute_dtype, "cuda") blk.attn.v_proj = make_linear(f.get_tensor(f"{p}.attn.v_proj.weight"), use_4bit, compute_dtype, "cuda") blk.attn.o_proj = make_linear(f.get_tensor(f"{p}.attn.o_proj.weight"), use_4bit, compute_dtype, "cuda") blk.mlp.gate_proj = make_linear(f.get_tensor(f"{p}.mlp.gate_proj.weight"), use_4bit, compute_dtype, "cuda") blk.mlp.up_proj = make_linear(f.get_tensor(f"{p}.mlp.up_proj.weight"), use_4bit, compute_dtype, "cuda") blk.mlp.down_proj = make_linear(f.get_tensor(f"{p}.mlp.down_proj.weight"), use_4bit, compute_dtype, "cuda") if (i + 1) % 8 == 0 or (i + 1) == cfg["core_layers"]: vram_now = torch.cuda.memory_allocated() / (1024 ** 3) print(f" -> Katman {i + 1}/{cfg['core_layers']} yuklendi | VRAM: {vram_now:.2f} GB") gc.collect() torch.cuda.empty_cache() vram_gb = torch.cuda.memory_allocated() / (1024 ** 3) print(f"HAZIR! ({time.time() - t0:.1f} sn) | Kullanilan VRAM: {vram_gb:.2f} / {total_vram_gb:.2f} GB") return model.eval(), tokenizer, gpu_name, total_vram_gb, mode_str # ========================================== # URETIM (STREAMING + KV-CACHE) # ========================================== MODEL, TOKENIZER, GPU_NAME, TOTAL_VRAM_GB, MODE_STR = load_model(DEFAULT_REPO_ID) GEN_LOCK = threading.Lock() def build_chatml_prompt(history: list, user_msg: str, system_prompt: str) -> str: parts = [f"<|im_start|>system\n{system_prompt.strip()}<|im_end|>\n"] for msg in history: role = msg.get("role", "user") content = msg.get("content", "") if isinstance(content, list): content = "".join(c.get("text", "") if isinstance(c, dict) else str(c) for c in content) if role in ("user", "assistant") and content: parts.append(f"<|im_start|>{role}\n{content}<|im_end|>\n") parts.append(f"<|im_start|>user\n{user_msg}<|im_end|>\n<|im_start|>assistant\n") return "".join(parts) def sample_next_token(logits: torch.Tensor, generated_ids: list, temperature: float, top_p: float, rep_penalty: float) -> int: logits = logits[0, -1, :].float() if rep_penalty > 1.0 and generated_ids: for tid in set(generated_ids[-64:]): if logits[tid] > 0: logits[tid] /= rep_penalty else: logits[tid] *= rep_penalty if temperature <= 0.05: return int(torch.argmax(logits).item()) logits = logits / temperature sorted_logits, sorted_indices = torch.sort(logits, descending=True) probs = F.softmax(sorted_logits, dim=-1) cumprobs = torch.cumsum(probs, dim=-1) mask = cumprobs > top_p mask[..., 1:] = mask[..., :-1].clone() mask[..., 0] = False sorted_logits[mask] = float("-inf") probs = F.softmax(sorted_logits, dim=-1) next_idx = torch.multinomial(probs, num_samples=1) return int(sorted_indices[next_idx].item()) def respond(user_msg, history, effort_label, max_new_tokens, temperature, top_p, rep_penalty, system_prompt): if not user_msg or not user_msg.strip(): yield history, "" return num_loops = EFFORT_MAP[effort_label] im_end_id = TOKENIZER.convert_tokens_to_ids("<|im_end|>") eos_ids = {TOKENIZER.eos_token_id, im_end_id} prompt = build_chatml_prompt(history, user_msg.strip(), system_prompt) input_ids = TOKENIZER.encode(prompt, add_special_tokens=False) max_prompt_len = max(128, MAX_CONTEXT_LEN - int(max_new_tokens)) if len(input_ids) > max_prompt_len: input_ids = input_ids[-max_prompt_len:] new_history = list(history) + [ {"role": "user", "content": user_msg.strip()}, {"role": "assistant", "content": ""}, ] with GEN_LOCK: torch.cuda.empty_cache() t_start = time.time() generated = [] kv_cache = None try: inp = torch.tensor([input_ids], dtype=torch.long, device="cuda") logits, kv_cache = MODEL.forward_step(inp, num_loops=num_loops, start_pos=0, kv_cache=None) cur_pos = len(input_ids) t_decode_start = time.time() for _ in range(int(max_new_tokens)): if cur_pos >= MAX_CONTEXT_LEN: break next_id = sample_next_token(logits, generated, temperature, top_p, rep_penalty) if next_id in eos_ids: break generated.append(next_id) text = TOKENIZER.decode(generated, skip_special_tokens=False) new_history[-1]["content"] = text elapsed = max(1e-4, time.time() - t_decode_start) tps = len(generated) / elapsed vram_now = torch.cuda.memory_allocated() / (1024 ** 3) status = ( f"Loop: **{num_loops}L ({num_loops * 32} katman)** | " f"Hiz: **{tps:.1f} tok/s** | " f"Token: **{len(generated)}** | " f"VRAM: **{vram_now:.2f} / {TOTAL_VRAM_GB:.1f} GB**" ) yield new_history, status next_tensor = torch.tensor([[next_id]], dtype=torch.long, device="cuda") logits, kv_cache = MODEL.forward_step( next_tensor, num_loops=num_loops, start_pos=cur_pos, kv_cache=kv_cache ) cur_pos += 1 total_elapsed = max(1e-4, time.time() - t_start) tps = len(generated) / max(1e-4, time.time() - t_decode_start) vram_now = torch.cuda.memory_allocated() / (1024 ** 3) final_status = ( f"Tamamlandi ({total_elapsed:.1f}s) | Loop: **{num_loops}L** | " f"Hiz: **{tps:.1f} tok/s** | Token: **{len(generated)}** | " f"VRAM: **{vram_now:.2f} / {TOTAL_VRAM_GB:.1f} GB**" ) yield new_history, final_status finally: del kv_cache torch.cuda.empty_cache() # ========================================== # GRADIO ARAYUZU # ========================================== with gr.Blocks(title="Loop7B v3 Local") as demo: gr.Markdown( f"# Loop7B v3 — Yerel Sohbet Arayuzu\n" f"**Model:** `{DEFAULT_REPO_ID}` | **GPU:** `{GPU_NAME} ({TOTAL_VRAM_GB:.1f} GB)` | " f"**Mod:** `{MODE_STR}`" ) with gr.Row(): with gr.Column(scale=3): chatbot = gr.Chatbot(height=520, label="Loop7B v3") with gr.Row(): msg_box = gr.Textbox( placeholder="Mesajini yaz ve Enter'a bas...", show_label=False, scale=5, ) send_btn = gr.Button("Gonder", variant="primary", scale=1) status_md = gr.Markdown("Hazir.") with gr.Column(scale=1): effort_dd = gr.Dropdown( choices=list(EFFORT_MAP.keys()), value="medium (2 Loop / 64L - Dengeli)", label="Dusunme Derinligi (Loop Sayisi)", ) max_tokens_sl = gr.Slider(32, 512, value=256, step=16, label="Max Token") temp_sl = gr.Slider(0.0, 1.2, value=0.6, step=0.05, label="Temperature") top_p_sl = gr.Slider(0.1, 1.0, value=0.9, step=0.05, label="Top-P") rep_sl = gr.Slider(1.0, 1.4, value=1.12, step=0.02, label="Repetition Penalty") sys_box = gr.Textbox(value=DEFAULT_SYS, lines=5, label="Sistem Mesaji") clear_btn = gr.Button("Sohbeti Temizle") inputs = [msg_box, chatbot, effort_dd, max_tokens_sl, temp_sl, top_p_sl, rep_sl, sys_box] msg_box.submit(respond, inputs=inputs, outputs=[chatbot, status_md]).then(lambda: "", None, msg_box) send_btn.click(respond, inputs=inputs, outputs=[chatbot, status_md]).then(lambda: "", None, msg_box) clear_btn.click(lambda: ([], "Sohbet temizlendi."), None, [chatbot, status_md]) if __name__ == "__main__": demo.queue().launch(server_name="127.0.0.1", server_port=7860, inbrowser=True)