#!/usr/bin/env python3 # Copyright (c) 2026 Omni Intelligence LLC. # SPDX-License-Identifier: MIT (applies solely to this benchmark verification script; # the Cortivra-Apex binary distribution `cortivra-apex-v2.0.0-release.zip` is proprietary # software governed by `EULA_AND_TERMS.txt` — see `LICENSE` in this directory). """Measure physical GPU memory and generation output on a pretrained HuggingFace LLM.""" from __future__ import annotations import argparse import gc import pathlib import sys import zipfile import torch _HERE = pathlib.Path(__file__).resolve().parent def _bootstrap_cortivra_runtime() -> None: candidates = [ _HERE / "cortivra-apex.pyz", _HERE / "cortivra-apex-v2.0.0-release" / "cortivra-apex.pyz", _HERE.parent / "cortivra-apex.pyz", _HERE.parent / "dist" / "cortivra-apex-v2.0.0-release" / "cortivra-apex.pyz", _HERE, _HERE.parent, ] for candidate in candidates: if candidate.exists() and str(candidate) not in sys.path: sys.path.insert(0, str(candidate)) try: import cortivra_apex # noqa: F401 return except ModuleNotFoundError: pass for zip_candidate in (_HERE / "cortivra-apex-v2.0.0-release.zip", _HERE.parent / "cortivra-apex-v2.0.0-release.zip"): if zip_candidate.is_file(): extract_dir = _HERE / "cortivra-apex-v2.0.0-release" extract_dir.mkdir(parents=True, exist_ok=True) with zipfile.ZipFile(zip_candidate, "r") as zf: zf.extractall(extract_dir) pyz_extracted = extract_dir / "cortivra-apex.pyz" for item in (pyz_extracted, extract_dir): if item.exists() and str(item) not in sys.path: sys.path.insert(0, str(item)) return _bootstrap_cortivra_runtime() try: import cortivra_apex as apex except ModuleNotFoundError as exc: sys.stderr.write( "Could not locate the Cortivra-Apex runtime (`cortivra-apex.pyz`).\n" "Download `cortivra-apex-v2.0.0-release.zip` from https://cortivra-apex.com\n" "and place it in the same folder as `verify_real_llm_vram.py`.\n" ) raise SystemExit(1) from exc def main() -> int: parser = argparse.ArgumentParser(description="Verify 1-line weight compression on a pretrained HuggingFace model.") parser.add_argument( "--model", type=str, default="Qwen/Qwen2.5-Coder-3B-Instruct", help="HuggingFace model ID or local path", ) parser.add_argument( "--prompt", type=str, default="Explain in two clear sentences why high-bandwidth GPU memory makes AI faster:", help="Prompt to run before and after compression", ) args = parser.parse_args() try: from transformers import AutoModelForCausalLM, AutoTokenizer except ImportError: print("Install transformers first: pip install transformers accelerate") return 1 print("-" * 96) print(f"Model : {args.model}") print(f"Prompt : {args.prompt}") print("-" * 96) tok = AutoTokenizer.from_pretrained(args.model) if hasattr(tok, "apply_chat_template") and tok.chat_template: msgs = [{"role": "user", "content": args.prompt}] text = tok.apply_chat_template(msgs, tokenize=False, add_generation_prompt=True) else: text = args.prompt inputs = tok([text], return_tensors="pt").to("cuda") # 1. Baseline: Uncompressed PyTorch FP16 model on GPU torch.cuda.empty_cache() m_base = AutoModelForCausalLM.from_pretrained(args.model, dtype=torch.float16, low_cpu_mem_usage=True).cuda() torch.cuda.synchronize() base_fp16_gb = torch.cuda.memory_allocated() / (1024**3) base_fp32_gb = base_fp16_gb * 2.0 print(f"\n1. Uncompressed PyTorch VRAM : {base_fp16_gb:.2f} GB (FP16) / {base_fp32_gb:.2f} GB (FP32 eq.)") with torch.no_grad(): out_base = m_base.generate(**inputs, max_new_tokens=45, do_sample=False) reply_base = tok.decode(out_base[0][inputs.input_ids.shape[1]:], skip_special_tokens=True).strip() print(f" Output: {reply_base}") del m_base, out_base gc.collect() torch.cuda.empty_cache() # 2. Cortivra-Apex 8-Bit weight compression (load on CPU, stream-compress to GPU in 1 line) m_cpu8 = AutoModelForCausalLM.from_pretrained(args.model, dtype=torch.float16, low_cpu_mem_usage=True) m_apex8 = apex.boost(m_cpu8, compress_weights=True, bits=8) gc.collect() torch.cuda.synchronize() apex8_gb = torch.cuda.memory_allocated() / (1024**3) print(f"\n2. Cortivra-Apex 8-Bit VRAM : {apex8_gb:.2f} GB ({base_fp32_gb/apex8_gb:.2f}x vs FP32 | {base_fp16_gb/apex8_gb:.2f}x vs FP16)") with torch.no_grad(): out_8 = m_apex8.generate(**inputs, max_new_tokens=45, do_sample=False) reply_8 = tok.decode(out_8[0][inputs.input_ids.shape[1]:], skip_special_tokens=True).strip() print(f" Output: {reply_8}") del m_cpu8, m_apex8, out_8 gc.collect() torch.cuda.empty_cache() # 3. Cortivra-Apex 4-Bit weight compression (load on CPU, stream-compress to GPU in 1 line) m_cpu4 = AutoModelForCausalLM.from_pretrained(args.model, dtype=torch.float16, low_cpu_mem_usage=True) m_apex4 = apex.boost(m_cpu4, compress_weights=True, bits=4) gc.collect() torch.cuda.synchronize() apex4_gb = torch.cuda.memory_allocated() / (1024**3) print(f"\n3. Cortivra-Apex 4-Bit VRAM : {apex4_gb:.2f} GB ({base_fp32_gb/apex4_gb:.2f}x vs FP32 | {base_fp16_gb/apex4_gb:.2f}x vs FP16)") with torch.no_grad(): out_4 = m_apex4.generate(**inputs, max_new_tokens=45, do_sample=False) reply_4 = tok.decode(out_4[0][inputs.input_ids.shape[1]:], skip_special_tokens=True).strip() print(f" Output: {reply_4}") print("-" * 96) return 0 if __name__ == "__main__": sys.exit(main())