"""Inference & Dynamic LoRA Evaluation Suite for 2.0B Parameter Model. Benchmarks decoding throughput with and without KV-caching, verifies dynamic LoRA adapter hot-swapping at runtime, and generates decision-gate evaluation artifact. """ from __future__ import annotations import argparse import json import os import sys import time from pathlib import Path from typing import Any import torch from transformers import AutoTokenizer ROOT = Path(__file__).resolve().parents[1] if str(ROOT) not in sys.path: sys.path.insert(0, str(ROOT)) from continual_ai.gpu_transformer import ( GPUContinualTransformer, TransformerConfig, ) def get_device() -> torch.device: if torch.cuda.is_available(): return torch.device("cuda") return torch.device("cpu") def run_eval_2b() -> dict[str, Any]: device = get_device() print(f"=== Running 2.0B Model Inference Benchmark on {device} ({torch.cuda.get_device_name(0) if device.type == 'cuda' else 'CPU'}) ===") torch.manual_seed(42) if torch.cuda.is_available(): torch.cuda.manual_seed_all(42) # 1. Load Tokenizer print(">> Loading tokenizer (gpt2)...") tokenizer = AutoTokenizer.from_pretrained("gpt2") tokenizer.pad_token = tokenizer.eos_token # 2. Build 2.0B Model Configuration config = TransformerConfig.stage4_2b() dtype = torch.bfloat16 if device.type == "cuda" else torch.float32 print(f">> Initializing 2.0B GPUContinualTransformer (L={config.n_layers}, d={config.dim}, H={config.n_heads}, H_kv={config.n_kv_heads})...") model = GPUContinualTransformer(config).to(device=device, dtype=dtype) model.eval() total_params = model.count_parameters(trainable_only=False) print(f">> Model parameter count: {total_params:,} (~{total_params / 1e9:.2f}B)") # 3. Load Checkpoint checkpoint_dir = ROOT / "checkpoints" ckpt_path = checkpoint_dir / "stage4_2b.pt" lora_path = checkpoint_dir / "stage4_2b_lora.pt" if not ckpt_path.exists(): # Check remote default path if run inside lightning container alt_ckpt = Path("/home/zeus/continual_learning/checkpoints/stage4_2b.pt") if alt_ckpt.exists(): ckpt_path = alt_ckpt lora_path = Path("/home/zeus/continual_learning/checkpoints/stage4_2b_lora.pt") else: raise FileNotFoundError(f"Base checkpoint not found at {ckpt_path}") print(f">> Loading base model weights from {ckpt_path}...") ckpt_data = torch.load(str(ckpt_path), map_location="cpu") model.load_state_dict(ckpt_data["model_state"], strict=False) print(">> Base weights loaded successfully.") # 4. Benchmark 1: KV-Cache Accelerated Decoding prompt_text = "The continual learning architecture allows models to learn without" prompt_tokens = tokenizer(prompt_text, return_tensors="pt")["input_ids"].to(device) num_prompt_tokens = prompt_tokens.shape[1] num_gen_tokens = 30 print(f"\n>> Benchmark 1: Decoding {num_gen_tokens} tokens with KV Cache...") if device.type == "cuda": torch.cuda.synchronize() t0 = time.perf_counter() with torch.no_grad(): out_cached = model.generate_with_cache( prompt_tokens, max_new_tokens=num_gen_tokens, temperature=0.0, repetition_penalty=1.1, ) if device.type == "cuda": torch.cuda.synchronize() time_cached = time.perf_counter() - t0 tok_per_sec_cached = num_gen_tokens / time_cached ms_per_tok_cached = (time_cached / num_gen_tokens) * 1000.0 text_cached = tokenizer.decode(out_cached[0], skip_special_tokens=True) print(f" KV-Cache Time: {time_cached:.3f}s | Throughput: {tok_per_sec_cached:.2f} tok/s | Latency: {ms_per_tok_cached:.1f} ms/tok") print(f" Sample Output: \"{text_cached}\"") # 5. Benchmark 2: Baseline Decoding without Cache (re-evaluating full history) print(f"\n>> Benchmark 2: Decoding {num_gen_tokens} tokens without Cache (O(T^2))...") if device.type == "cuda": torch.cuda.synchronize() t1 = time.perf_counter() with torch.no_grad(): out_baseline = model.generate( prompt_tokens, max_new_tokens=num_gen_tokens, temperature=0.0, ) if device.type == "cuda": torch.cuda.synchronize() time_baseline = time.perf_counter() - t1 tok_per_sec_baseline = num_gen_tokens / time_baseline ms_per_tok_baseline = (time_baseline / num_gen_tokens) * 1000.0 text_baseline = tokenizer.decode(out_baseline[0], skip_special_tokens=True) speedup = tok_per_sec_cached / max(tok_per_sec_baseline, 1e-6) print(f" Baseline Time: {time_baseline:.3f}s | Throughput: {tok_per_sec_baseline:.2f} tok/s | Latency: {ms_per_tok_baseline:.1f} ms/tok") print(f" KV-Cache Speedup Factor: {speedup:.2f}x") # 6. Benchmark 3: Dynamic LoRA Hot-Swapping Verification print("\n>> Benchmark 3: Verifying Dynamic LoRA Hot-Swapping...") # Step A: Base Mode evaluation model.hot_swap_adapter(None) with torch.no_grad(): base_probe = model.generate_with_cache(prompt_tokens, max_new_tokens=15, temperature=0.0) base_text = tokenizer.decode(base_probe[0], skip_special_tokens=True) print(f" [Mode: Base Model] Output: \"{base_text}\"") # Step B: Load and hot swap to Domain 2 Expert LoRA adapter_name = "domain2_2b_expert" print(f" Loading adapter '{adapter_name}' from {lora_path}...") model.load_adapter(adapter_name, lora_path, r=16, lora_alpha=32.0) model.hot_swap_adapter(adapter_name) with torch.no_grad(): expert_probe = model.generate_with_cache(prompt_tokens, max_new_tokens=15, temperature=0.0) expert_text = tokenizer.decode(expert_probe[0], skip_special_tokens=True) print(f" [Mode: Expert LoRA ({adapter_name})] Output: \"{expert_text}\"") # Step C: Hot swap back to Base Mode print(" Hot-swapping back to Base Mode (None)...") model.hot_swap_adapter(None) with torch.no_grad(): base_restored_probe = model.generate_with_cache(prompt_tokens, max_new_tokens=15, temperature=0.0) base_restored_text = tokenizer.decode(base_restored_probe[0], skip_special_tokens=True) print(f" [Mode: Restored Base] Output: \"{base_restored_text}\"") # Check bit-exact equivalence of Base and Restored Base base_match = torch.equal(base_probe, base_restored_probe) print(f" Zero-overhead zero-drift verification: {'PASSED (Bit-Exact Match)' if base_match else 'FAILED'}") # VRAM stats peak_vram_mb = torch.cuda.max_memory_allocated() / (1024 * 1024) if device.type == "cuda" else 0.0 # Decision Gates checks = { "kv_cache_speedup_positive": bool(speedup >= 1.05), "adapter_hot_swap_functional": bool(model.active_adapter is None and len(model.adapters) > 0), "base_mode_restoration_bit_exact": bool(base_match), "output_tokens_non_empty": bool(len(text_cached) > len(prompt_text)), "peak_vram_within_budget": bool(peak_vram_mb < 24000), } all_passed = all(checks.values()) result = { "schema_version": "0.32.0", "stage": "Phase 6.32 — 2.0B Model Inference Acceleration & Dynamic LoRA Hot-Swapping", "hardware": { "device": str(device), "gpu_name": torch.cuda.get_device_name(0) if device.type == "cuda" else "CPU", "peak_vram_mb": round(peak_vram_mb, 1), "vram_limit_mb": 24000, }, "model": { "total_parameters": total_params, "architecture": { "layers": config.n_layers, "dim": config.dim, "heads": config.n_heads, "kv_heads": config.n_kv_heads, "hidden_dim": config.hidden_dim, "vocab_size": config.vocab_size, }, "active_adapters": list(model.adapters), }, "benchmarks": { "prompt": prompt_text, "tokens_generated": num_gen_tokens, "kv_cache": { "time_seconds": round(time_cached, 4), "throughput_tok_per_sec": round(tok_per_sec_cached, 2), "latency_ms_per_tok": round(ms_per_tok_cached, 2), "sample_output": text_cached, }, "baseline_uncached": { "time_seconds": round(time_baseline, 4), "throughput_tok_per_sec": round(tok_per_sec_baseline, 2), "latency_ms_per_tok": round(ms_per_tok_baseline, 2), "sample_output": text_baseline, }, "speedup_ratio": round(speedup, 2), "dynamic_hot_swap": { "base_text": base_text, "expert_text": expert_text, "base_restored_text": base_restored_text, "bit_exact_match": base_match, }, }, "checks": checks, "decision_gate": { "status": "PASS" if all_passed else "FAIL", "verdict": "2B_INFERENCE_ACCELERATION_VERIFIED" if all_passed else "REVISE_INFERENCE_ENGINE", }, } # Save artifact artifacts_dir = ROOT / "artifacts" artifacts_dir.mkdir(parents=True, exist_ok=True) out_path = artifacts_dir / "eval_2b_inference.json" with open(out_path, "w", encoding="utf-8") as f: json.dump(result, f, indent=2) print(f"\n>> Saved 2.0B inference evaluation artifact to {out_path}") print(f"=== Decision Gate Status: {result['decision_gate']['status']} ({result['decision_gate']['verdict']}) ===") return result if __name__ == "__main__": parser = argparse.ArgumentParser(description="2.0B Model Inference & Dynamic Hot-Swapping Evaluation") parser.add_argument("--interactive", action="store_true", help="Launch interactive prompt loop") args = parser.parse_args() run_eval_2b()