#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ LULUV2 live local inference engine. This is the runtime bridge for the LULUV2 fine-tuned checkpoint: LULU2_instruct_ddp.pt / LULU2_base_ddp.pt / LULU2.pt It imports the actual LULUV2 architecture file, loads the checkpoint, restores pass2_state when present, uses the local tokenizer folder, and streams tokens with live metrics. No AutoModelForCausalLM.from_pretrained call is used here. No external model weights are loaded. """ from __future__ import annotations import importlib.util import json import math import os import platform import time from contextlib import nullcontext from dataclasses import dataclass, asdict from pathlib import Path from types import SimpleNamespace from typing import Any, Dict, Generator, List, Optional, Tuple import torch import torch.nn.functional as F try: import psutil except Exception: psutil = None try: import pynvml except Exception: pynvml = None STOP_STRINGS = [ "<|im_start|>", "<|im_end|>", "<|user|>", "<|system|>", "<|assistant|>", "User:", "Assistant:", "\nuser:", "\nassistant:", ] @dataclass class GenerationConfig: max_new_tokens: int = 512 temperature: float = 0.65 top_k: int = 40 top_p: float = 0.90 min_p: float = 0.03 repetition_penalty: float = 1.10 frequency_penalty: float = 0.02 greedy: bool = False no_repeat_ngram: int = 4 stream_every: int = 1 max_context_tokens: int = 4096 return_pass_metrics: bool = True @dataclass class GenerationStats: prompt_tokens: int = 0 generated_tokens: int = 0 elapsed_sec: float = 0.0 tokens_per_sec: float = 0.0 last_token: str = "" last_token_id: int = -1 last_token_prob: float = 0.0 last_entropy: float = 0.0 finish_reason: str = "none" pass1_pass2_kl: Optional[float] = None pass1_pass2_logit_cosine: Optional[float] = None def setup_torch(): if torch.cuda.is_available(): try: torch.backends.cuda.matmul.allow_tf32 = True torch.backends.cudnn.allow_tf32 = True except Exception: pass try: torch.backends.cuda.enable_flash_sdp(True) torch.backends.cuda.enable_mem_efficient_sdp(True) torch.backends.cuda.enable_math_sdp(False) except Exception: pass if hasattr(torch, "set_float32_matmul_precision"): try: torch.set_float32_matmul_precision("high") except Exception: pass def human_bytes(num: float) -> str: for unit in ["B", "KB", "MB", "GB", "TB"]: if abs(num) < 1024.0: return f"{num:.2f} {unit}" num /= 1024.0 return f"{num:.2f} PB" def _value_to_text(value: Any) -> str: """Coerce Gradio/Textbox/Multimodal values into plain text. Some Gradio versions send messages as {"text": ..., "files": ...} or content blocks like [{"type": "text", "text": ...}]. The local UI is text-only, so we aggressively unwrap these before tokenization. """ if value is None: return "" if isinstance(value, str): return value if isinstance(value, dict): if "text" in value: return _value_to_text(value.get("text")) if "content" in value: return _value_to_text(value.get("content")) if "value" in value: return _value_to_text(value.get("value")) return "\n".join(_value_to_text(v) for v in value.values() if _value_to_text(v)) if isinstance(value, (list, tuple)): return "\n".join(_value_to_text(v) for v in value if _value_to_text(v)) return str(value) def clean_text(text: Any) -> str: text = _value_to_text(text).replace("\\n", "\n") # Cut only after obvious turn-control strings that appear in generated text. cut_points = [text.find(s) for s in STOP_STRINGS if s in text and text.find(s) > 0] if cut_points: text = text[: min(cut_points)] for s in STOP_STRINGS: text = text.replace(s, "") # Remove common role remnants and JSON-ish UI artifacts. for prefix in ("assistant\n", "Assistant:", "Lulu:", "assistant:"): if text.lstrip().startswith(prefix): text = text.lstrip()[len(prefix):] text = text.replace("{'type': 'text'}", "").replace('{"type": "text"}', "") text = "\n".join(line.rstrip() for line in text.strip().splitlines()) text = "\n".join(line for line in text.splitlines() if not line.strip().startswith("type: 'text'")) return text.strip() def normalize_history(history: Any) -> List[Dict[str, str]]: out: List[Dict[str, str]] = [] if not history: return out for item in history: if isinstance(item, dict): role = item.get("role") content = clean_text(item.get("content", "")) if role in {"user", "assistant"} and content: out.append({"role": role, "content": content}) elif isinstance(item, (tuple, list)) and len(item) >= 2: u = clean_text(item[0]) a = clean_text(item[1]) if u: out.append({"role": "user", "content": u}) if a: out.append({"role": "assistant", "content": a}) return out def resolve_model_py(model_py: Optional[str] = None) -> str: candidates = [] if model_py: candidates.append(model_py) candidates.extend(["luluv2_inference_runtime.py"]) for c in candidates: p = Path(c) if p.exists(): return str(p.resolve()) raise FileNotFoundError( "Could not find the LULUV2 model file. Pass --model-py or put " "luluv2_inference_runtime.py next to this UI." ) def import_model_py(model_py: Optional[str] = None): path = resolve_model_py(model_py) spec = importlib.util.spec_from_file_location("luluv2_runtime_module", path) if spec is None or spec.loader is None: raise RuntimeError(f"Could not import model file: {path}") mod = importlib.util.module_from_spec(spec) spec.loader.exec_module(mod) return mod, path class LULUV2LiveEngine: def __init__( self, ckpt_path: str, model_py: Optional[str] = None, tokenizer_dir: Optional[str] = None, device: Optional[str] = None, dtype: str = "bf16", local_files_only: bool = True, no_config_download: bool = True, force_base_only: bool = False, ): setup_torch() self.ckpt_path = str(ckpt_path) self.ckpt_dir = Path(self.ckpt_path).resolve().parent self.device = self._select_device(device) self.dtype = self._dtype_from_name(dtype) self.local_files_only = bool(local_files_only) self.no_config_download = bool(no_config_download) self.force_base_only = bool(force_base_only) self.last_stats = GenerationStats() self.recent_tokens: List[Dict[str, Any]] = [] self.goku, self.model_py_path = import_model_py(model_py) # args object expected by the embedded LULUV2 runtime helpers. self.args = SimpleNamespace( checkpoint=self.ckpt_path, tokenizer=tokenizer_dir or "", model_id="", no_config_download=self.no_config_download, local_files_only=self.local_files_only, ) print("[guard] LULUV2 local UI: no AutoModelForCausalLM.from_pretrained call and no external model weights loaded.") print(f"[load] checkpoint={self.ckpt_path}") self.base_ckpt, base = self.goku.load_lulu2_base(self.args, self.device, self.dtype) self.tokenizer = self._load_tokenizer(tokenizer_dir) self.model, self.has_pass2 = self._maybe_wrap_pass2(base) self.model.eval() self.model_info = self._build_model_info() def _select_device(self, device: Optional[str]): if device: return torch.device(device) if torch.cuda.is_available(): return torch.device("cuda") return torch.device("cpu") def _dtype_from_name(self, name: str): name = (name or "bf16").lower() if name in {"bf16", "bfloat16"}: return torch.bfloat16 if name in {"fp16", "float16", "half"}: return torch.float16 return torch.float32 def _load_tokenizer(self, tokenizer_dir: Optional[str]): # Prefer explicit path, then sibling tokenizer folder, then checkpoint metadata. if tokenizer_dir: self.args.tokenizer = tokenizer_dir else: sibling = self.ckpt_dir / "tokenizer" if sibling.is_dir(): self.args.tokenizer = str(sibling) tok = self.goku.load_tokenizer(self.args, self.base_ckpt) if getattr(tok, "pad_token_id", None) is None and getattr(tok, "eos_token_id", None) is not None: try: tok.pad_token = tok.eos_token except Exception: pass return tok def _maybe_wrap_pass2(self, base): ckpt = self.base_ckpt if self.force_base_only or "pass2_state" not in ckpt: print("[pass2] no pass2_state loaded; running base LULUV2 forward") return base.to(self.device).eval(), False cfg_dict = dict(ckpt.get("pass2_config") or {}) Pass2Config = self.goku.Pass2Config pass2_cfg = Pass2Config(**{k: v for k, v in cfg_dict.items() if k in Pass2Config.__dataclass_fields__}) model = self.goku.Lulu2TwoPassForCausalLM(base, pass2_cfg) missing, unexpected = model.load_state_dict(ckpt["pass2_state"], strict=False) print(f"[pass2] loaded pass2_state missing={len(missing)} unexpected={len(unexpected)}") model.to(device=self.device, dtype=self.dtype) model.eval() return model, True def _build_model_info(self) -> Dict[str, Any]: total_params = sum(p.numel() for p in self.model.parameters()) trainable_params = sum(p.numel() for p in self.model.parameters() if p.requires_grad) c_codes = [(n, p.numel()) for n, p in self.model.named_parameters() if n.endswith(".c")] gate_mean = None adapter_gate_mean = None if self.has_pass2: with torch.no_grad(): gate_mean = float(torch.sigmoid(self.model.layer_gates.float()).mean().item()) vals = [] for ad in self.model.adapters: vals.append(float(torch.sigmoid(ad.gate.float()).item())) adapter_gate_mean = float(sum(vals) / max(1, len(vals))) ckpt_size = Path(self.ckpt_path).stat().st_size if Path(self.ckpt_path).exists() else 0 cfg = getattr(self.model.base if self.has_pass2 else self.model, "config", None) return { "checkpoint": self.ckpt_path, "checkpoint_size": human_bytes(ckpt_size), "model_py": self.model_py_path, "device": str(self.device), "dtype": str(self.dtype).replace("torch.", ""), "has_pass2": self.has_pass2, "total_params": total_params, "trainable_params": trainable_params, "vwm_c_modules": len(c_codes), "vwm_c_params": sum(n for _, n in c_codes), "pass2_layer_gate_mean": gate_mean, "pass2_adapter_gate_mean": adapter_gate_mean, "hidden_size": getattr(cfg, "hidden_size", None), "layers": getattr(cfg, "num_hidden_layers", None), "heads": getattr(cfg, "num_attention_heads", None), "kv_heads": getattr(cfg, "num_key_value_heads", None), "max_position_embeddings": getattr(cfg, "max_position_embeddings", None), } def amp_context(self): if self.device.type == "cuda" and self.dtype in (torch.bfloat16, torch.float16): return torch.autocast("cuda", dtype=self.dtype) return nullcontext() def build_chat_prompt( self, message: str, history: Any, system_prompt: str, memory_notes: str = "", history_turns: int = 4, extra_context: str = "", ) -> str: history = normalize_history(history) recent = history[-max(0, int(history_turns)) * 2:] if history_turns else [] system_chunks = [] if system_prompt.strip(): system_chunks.append(system_prompt.strip()) if memory_notes.strip(): system_chunks.append("Useful memory notes:\n" + memory_notes.strip()) if extra_context.strip(): system_chunks.append("Relevant local context:\n" + extra_context.strip()) system = "\n\n".join(system_chunks) messages = [] if system: messages.append({"role": "system", "content": system}) messages.extend(recent) messages.append({"role": "user", "content": clean_text(message)}) try: return self.tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True) except Exception: parts = [] if system: parts.append(f"<|im_start|>system\n{system}<|im_end|>") for item in recent: parts.append(f"<|im_start|>{item['role']}\n{item['content']}<|im_end|>") parts.append(f"<|im_start|>user\n{clean_text(message)}<|im_end|>") parts.append("<|im_start|>assistant\n") return "\n".join(parts) def encode(self, text: str, max_context_tokens: int = 4096) -> torch.Tensor: enc = self.tokenizer(text, return_tensors="pt", truncation=True, max_length=int(max_context_tokens)) ids = enc.input_ids.to(self.device) return ids @torch.no_grad() def pass_metrics_for_ids(self, ids: torch.Tensor) -> Tuple[Optional[float], Optional[float]]: if not self.has_pass2: return None, None try: with self.amp_context(): out = self.model(ids, return_pass1_logits=True) if out.pass1_logits is None: return None, None l1 = out.pass1_logits[:, -1, :].float() l2 = out.logits[:, -1, :].float() kl = F.kl_div(F.log_softmax(l2, dim=-1), F.softmax(l1, dim=-1), reduction="batchmean") cos = F.cosine_similarity(l1, l2, dim=-1).mean() return float(kl.item()), float(cos.item()) except Exception as exc: print(f"[metrics] pass metrics failed: {type(exc).__name__}: {exc}") return None, None def _apply_penalties(self, logits: torch.Tensor, generated: torch.Tensor, cfg: GenerationConfig) -> torch.Tensor: if generated.numel() == 0: return logits out = logits.clone() uniq, counts = torch.unique(generated.view(-1), return_counts=True) if cfg.repetition_penalty != 1.0: selected = out[:, uniq] selected = torch.where(selected > 0, selected / float(cfg.repetition_penalty), selected * float(cfg.repetition_penalty)) out[:, uniq] = selected if cfg.frequency_penalty: out[:, uniq] -= float(cfg.frequency_penalty) * counts.to(out.dtype).unsqueeze(0) n = int(cfg.no_repeat_ngram) if n > 1 and generated.size(1) >= n - 1: seq = generated[0].tolist() prefix = tuple(seq[-(n - 1):]) banned = [] for i in range(len(seq) - n + 1): if tuple(seq[i:i + n - 1]) == prefix: banned.append(seq[i + n - 1]) if banned: out[:, list(set(banned))] = -float("inf") return out @torch.no_grad() def _sample_next(self, logits: torch.Tensor, generated: torch.Tensor, cfg: GenerationConfig) -> Tuple[torch.Tensor, Dict[str, Any]]: work = self._apply_penalties(logits.float(), generated, cfg) if cfg.greedy or cfg.temperature <= 0: probs = torch.softmax(work, dim=-1) next_id = torch.argmax(work, dim=-1, keepdim=True) else: work = work / max(float(cfg.temperature), 1e-6) if cfg.top_k > 0: k = min(int(cfg.top_k), work.size(-1)) thresh = torch.topk(work, k, dim=-1).values[..., -1, None] work = torch.where(work >= thresh, work, torch.full_like(work, -float("inf"))) if 0.0 < cfg.top_p < 1.0: sorted_logits, sorted_idx = torch.sort(work, descending=True, dim=-1) sorted_probs = torch.softmax(sorted_logits, dim=-1) cumprobs = torch.cumsum(sorted_probs, dim=-1) remove = cumprobs > float(cfg.top_p) shifted = remove.clone() shifted[..., 1:] = remove[..., :-1] shifted[..., 0] = False sorted_logits = sorted_logits.masked_fill(shifted, -float("inf")) work = torch.full_like(work, -float("inf")).scatter(1, sorted_idx, sorted_logits) if 0.0 < cfg.min_p < 1.0: probs_for_minp = torch.softmax(work, dim=-1) max_prob = probs_for_minp.max(dim=-1, keepdim=True).values keep = probs_for_minp >= float(cfg.min_p) * max_prob work = work.masked_fill(~keep, -float("inf")) probs = torch.softmax(work, dim=-1) if torch.isnan(probs).any() or not torch.isfinite(probs.sum()) or float(probs.sum()) <= 0: next_id = torch.argmax(logits, dim=-1, keepdim=True) probs = torch.softmax(logits.float(), dim=-1) else: next_id = torch.multinomial(probs, 1) prob = float(probs.gather(1, next_id).item()) if probs.numel() else 0.0 entropy = float((-(probs * torch.log(probs.clamp_min(1e-12))).sum(dim=-1)).mean().item()) if probs.numel() else 0.0 return next_id, {"prob": prob, "entropy": entropy} @torch.no_grad() def generate(self, prompt: str, cfg: GenerationConfig) -> Generator[str, None, None]: self.model.eval() self.recent_tokens = [] ids = self.encode(prompt, max_context_tokens=cfg.max_context_tokens) prompt_len = int(ids.shape[1]) t0 = time.time() pass_kl, pass_cos = (None, None) if cfg.return_pass_metrics: pass_kl, pass_cos = self.pass_metrics_for_ids(ids) eos_id = getattr(self.tokenizer, "eos_token_id", None) last_text = "" finish_reason = "length" for step in range(int(cfg.max_new_tokens)): ctx = ids[:, -int(cfg.max_context_tokens):] with self.amp_context(): out = self.model(ctx) logits = out.logits[:, -1, :].float() generated = ids[:, prompt_len:] next_id, tok_stats = self._sample_next(logits, generated, cfg) ids = torch.cat([ids, next_id.to(ids.device)], dim=-1) token_id = int(next_id.item()) token_text = self.tokenizer.decode([token_id], skip_special_tokens=False) self.recent_tokens.append({ "i": step + 1, "id": token_id, "text": token_text, "prob": tok_stats["prob"], "entropy": tok_stats["entropy"], }) self.recent_tokens = self.recent_tokens[-32:] if eos_id is not None and token_id == int(eos_id): finish_reason = "eos" break if (step + 1) % int(cfg.stream_every) == 0 or step == 0: raw = self.tokenizer.decode(ids[0, prompt_len:], skip_special_tokens=True) if any(s in raw for s in STOP_STRINGS): finish_reason = "stop_string" break text = clean_text(raw) if text and text != last_text: elapsed = time.time() - t0 gen = int(ids.shape[1]) - prompt_len self.last_stats = GenerationStats( prompt_tokens=prompt_len, generated_tokens=gen, elapsed_sec=elapsed, tokens_per_sec=gen / max(elapsed, 1e-9), last_token=token_text, last_token_id=token_id, last_token_prob=tok_stats["prob"], last_entropy=tok_stats["entropy"], finish_reason="streaming", pass1_pass2_kl=pass_kl, pass1_pass2_logit_cosine=pass_cos, ) last_text = text yield text raw = self.tokenizer.decode(ids[0, prompt_len:], skip_special_tokens=True) final = clean_text(raw) elapsed = time.time() - t0 gen = int(ids.shape[1]) - prompt_len self.last_stats = GenerationStats( prompt_tokens=prompt_len, generated_tokens=gen, elapsed_sec=elapsed, tokens_per_sec=gen / max(elapsed, 1e-9), last_token=self.recent_tokens[-1]["text"] if self.recent_tokens else "", last_token_id=self.recent_tokens[-1]["id"] if self.recent_tokens else -1, last_token_prob=self.recent_tokens[-1]["prob"] if self.recent_tokens else 0.0, last_entropy=self.recent_tokens[-1]["entropy"] if self.recent_tokens else 0.0, finish_reason=finish_reason, pass1_pass2_kl=pass_kl, pass1_pass2_logit_cosine=pass_cos, ) if final: yield final def stats_dict(self) -> Dict[str, Any]: d = asdict(self.last_stats) d["model"] = self.model_info d["system"] = system_snapshot(self) return d def stats_text(self) -> str: s = self.last_stats lines = [ f"Prompt tokens: {s.prompt_tokens}", f"Generated tokens: {s.generated_tokens}", f"Elapsed: {s.elapsed_sec:.2f}s", f"Decode speed: {s.tokens_per_sec:.2f} tok/s", f"Finish reason: {s.finish_reason}", f"Last token: {s.last_token!r} id={s.last_token_id} p={s.last_token_prob:.4f}", f"Last entropy: {s.last_entropy:.3f}", ] if s.pass1_pass2_kl is not None: lines.append(f"Pass1→Pass2 KL: {s.pass1_pass2_kl:.6f}") if s.pass1_pass2_logit_cosine is not None: lines.append(f"Pass1/Pass2 logit cosine: {s.pass1_pass2_logit_cosine:.6f}") lines.extend([ "", f"Checkpoint: {self.model_info['checkpoint']}", f"Checkpoint size: {self.model_info['checkpoint_size']}", f"Device: {self.model_info['device']} dtype={self.model_info['dtype']}", f"Pass2 active: {self.model_info['has_pass2']}", f"Params: {self.model_info['total_params']:,}", f"VWM c modules: {self.model_info['vwm_c_modules']} ({self.model_info['vwm_c_params']:,} c params)", f"Layer gate mean: {self.model_info['pass2_layer_gate_mean']}", f"Adapter gate mean: {self.model_info['pass2_adapter_gate_mean']}", ]) return "\n".join(lines) def token_trace_text(self) -> str: if not self.recent_tokens: return "No tokens generated yet." rows = [] for t in self.recent_tokens[-24:]: safe = repr(t["text"])[1:-1] rows.append(f"{t['i']:04d} id={t['id']:<7} p={t['prob']:.4f} H={t['entropy']:.2f} {safe}") return "\n".join(rows) def system_snapshot(engine: Optional[LULUV2LiveEngine] = None) -> Dict[str, Any]: """Return compact live edge-device metrics for the UI cards. Values are safe for JSON/HTML display. NVML is used when available for whole-device VRAM/utilization; PyTorch counters are always included. """ snap: Dict[str, Any] = { "python_ram": "n/a", "system_ram": "n/a", "system_ram_percent": 0.0, "cpu_percent": 0.0, "gpu_name": "CUDA unavailable", "vram_allocated": "n/a", "vram_reserved": "n/a", "vram_used": "n/a", "vram_total": "n/a", "vram_percent": 0.0, "gpu_util_percent": None, "gpu_temp_c": None, } if psutil is not None: try: proc = psutil.Process(os.getpid()) vm = psutil.virtual_memory() snap.update({ "python_ram": human_bytes(proc.memory_info().rss), "system_ram": f"{human_bytes(vm.used)} / {human_bytes(vm.total)}", "system_ram_percent": float(vm.percent), "cpu_percent": float(psutil.cpu_percent(interval=0.0)), }) except Exception: pass if torch.cuda.is_available(): try: idx = torch.cuda.current_device() props = torch.cuda.get_device_properties(idx) allocated = int(torch.cuda.memory_allocated(idx)) reserved = int(torch.cuda.memory_reserved(idx)) total = int(props.total_memory) snap.update({ "gpu_name": props.name, "vram_allocated": human_bytes(allocated), "vram_reserved": human_bytes(reserved), "vram_used": human_bytes(allocated), "vram_total": human_bytes(total), "vram_percent": (100.0 * allocated / max(total, 1)), }) if pynvml is not None: try: pynvml.nvmlInit() handle = pynvml.nvmlDeviceGetHandleByIndex(idx) util = pynvml.nvmlDeviceGetUtilizationRates(handle) mem = pynvml.nvmlDeviceGetMemoryInfo(handle) temp = pynvml.nvmlDeviceGetTemperature(handle, pynvml.NVML_TEMPERATURE_GPU) snap.update({ "gpu_util_percent": int(util.gpu), "vram_used": human_bytes(int(mem.used)), "vram_total": human_bytes(int(mem.total)), "vram_percent": (100.0 * float(mem.used) / max(float(mem.total), 1.0)), "gpu_temp_c": int(temp), }) except Exception: pass except Exception: pass return snap def system_usage(engine: Optional[LULUV2LiveEngine] = None) -> str: lines = [f"OS: {platform.system()} {platform.release()}"] if psutil is not None: proc = psutil.Process(os.getpid()) vm = psutil.virtual_memory() lines += [ f"Python RAM: {human_bytes(proc.memory_info().rss)}", f"System RAM: {human_bytes(vm.used)} / {human_bytes(vm.total)} ({vm.percent:.1f}%)", f"CPU: {psutil.cpu_percent(interval=0.0):.1f}%", ] else: lines.append("psutil unavailable") if torch.cuda.is_available(): idx = torch.cuda.current_device() props = torch.cuda.get_device_properties(idx) lines += [ "", f"GPU: {props.name}", f"VRAM allocated: {human_bytes(torch.cuda.memory_allocated(idx))}", f"VRAM reserved: {human_bytes(torch.cuda.memory_reserved(idx))}", f"VRAM total: {human_bytes(props.total_memory)}", ] if pynvml is not None: try: pynvml.nvmlInit() handle = pynvml.nvmlDeviceGetHandleByIndex(idx) util = pynvml.nvmlDeviceGetUtilizationRates(handle) mem = pynvml.nvmlDeviceGetMemoryInfo(handle) temp = pynvml.nvmlDeviceGetTemperature(handle, pynvml.NVML_TEMPERATURE_GPU) lines += [ f"GPU util: {util.gpu}%", f"GPU memory: {human_bytes(mem.used)} / {human_bytes(mem.total)}", f"GPU temperature: {temp} C", ] except Exception as exc: lines.append(f"NVML unavailable: {type(exc).__name__}: {exc}") else: lines += ["", "GPU: CUDA unavailable"] if engine is not None: lines += ["", engine.stats_text()] return "\n".join(lines)