""" benchmark_comparison.py — Benchmark comparison module for Xavante GRU RING. Compares Xavante model performance with market models on PT-BR tasks: Market models compared (V5: BERT variants removed): - GPT-2 small PT-BR (universitybrainscourse/GPT-2_portuguese_small) — 124M params - T5 small PT-BR (unicamp-dl/ptt5-small-t5-base) — 60M params - LLaMA-7B (quantized via bitsandbytes NF4) — 7B params quantized - mGPT (ai-forever/mGPT) — 1.3B params, multilingual GPT Metrics: - Perplexity (language modeling quality) - Accuracy on PT-BR NLU tasks (sentiment analysis, NER, QA) - Throughput (tokens/sec) - Memory usage (peak MB) - Latency (ms per token, ms per batch) Uses the same datasets from HFDatasetStreamer for fair comparison. Generates a comparison table/report in JSON format. Usage: from quantization.benchmark_comparison import BenchmarkComparison bench = BenchmarkComparison() xavante_results = bench.run_xavante_benchmark(model, streamer) market_results = bench.run_market_benchmark("unicamp-dl/ptt5-small-t5-base", streamer) comparison = bench.compare_results(xavante_results, market_results) report = bench.generate_report() """ from __future__ import annotations import gc import json import logging import os import time import traceback from dataclasses import asdict, dataclass, field from pathlib import Path from typing import Any, Dict, List, Optional, Tuple import torch import torch.nn as nn import torch.nn.functional as F logger = logging.getLogger(__name__) # --------------------------------------------------------------------------- # Market model definitions (V5: BERT variants removed) # --------------------------------------------------------------------------- MARKET_MODELS = { "GPT-2-small-PTBR": { "model_id": "universitybrainscourse/GPT-2_portuguese_small", "type": "decoder", "params_m": 124, "description": "GPT-2 small fine-tuned for Portuguese", }, "T5-small-PTBR": { "model_id": "unicamp-dl/ptt5-small-t5-base", "type": "encoder_decoder", "params_m": 60, "description": "T5 small for Portuguese (PTT5)", }, "LLaMA-7B-quantized": { "model_id": "meta-llama/Llama-2-7b-hf", "type": "decoder", "params_m": 7000, "description": "LLaMA 2 7B quantized via bitsandbytes NF4", "quantized": True, "quantization": "bitsandbytes_nf4", }, "mGPT-1.3B": { "model_id": "ai-forever/mGPT", "type": "decoder", "params_m": 1300, "description": "mGPT multilingual GPT (1.3B params, includes Portuguese)", }, } # --------------------------------------------------------------------------- # Data classes # --------------------------------------------------------------------------- @dataclass class BenchmarkResult: """Results from a benchmark run on a single model.""" model_name: str = "" model_id: str = "" model_type: str = "" params_m: float = 0.0 perplexity: float = 0.0 accuracy: float = 0.0 throughput_tokens_per_sec: float = 0.0 peak_memory_mb: float = 0.0 latency_per_token_ms: float = 0.0 latency_per_batch_ms: float = 0.0 bert_score_f1: float = 0.0 samples_evaluated: int = 0 eval_time_s: float = 0.0 dataset_ids_used: List[str] = field(default_factory=list) quantization: str = "none" device: str = "cpu" errors: int = 0 extra: Dict[str, Any] = field(default_factory=dict) @dataclass class ComparisonEntry: """A single comparison entry between Xavante and a market model.""" market_model_name: str = "" metric: str = "" xavante_value: float = 0.0 market_value: float = 0.0 ratio: float = 0.0 # xavante / market (>1 means Xavante is better for throughput) winner: str = "" # "xavante", "market", or "tie" note: str = "" # --------------------------------------------------------------------------- # Helper: memory tracking # --------------------------------------------------------------------------- def _get_peak_memory_mb(device: str) -> float: """Get peak memory usage in MB.""" if device == "cuda" and torch.cuda.is_available(): return torch.cuda.max_memory_allocated() / (1024 * 1024) try: import psutil return psutil.Process().memory_info().rss / (1024 * 1024) except Exception: try: with open("/proc/self/status") as f: for line in f: if line.startswith("VmHWM:"): return int(line.split()[1]) / 1024 except Exception: return 0.0 def _get_mem_mb() -> float: """Get current memory usage in MB.""" try: import psutil return psutil.Process().memory_info().rss / (1024 * 1024) except Exception: try: with open("/proc/self/status") as f: for line in f: if line.startswith("VmRSS:"): return int(line.split()[1]) / 1024 except Exception: return 0.0 # --------------------------------------------------------------------------- # BenchmarkComparison class # --------------------------------------------------------------------------- class BenchmarkComparison: """Benchmark comparison module that compares Xavante with market models. Usage: bench = BenchmarkComparison(device="cuda", max_eval_samples=500) # Load Xavante model from xavante.model import RNOEFLEXBase xavante_model = RNOEFLEXBase(d_model=128).to(device) # Create streamer for evaluation data from flexnet.hf_dataset_streamer import HFDatasetStreamer streamer = HFDatasetStreamer() streamer.authenticate() # Run benchmarks xav_results = bench.run_xavante_benchmark(xavante_model, streamer) market_results = {} for name in MARKET_MODELS: market_results[name] = bench.run_market_benchmark(name, streamer) # Compare and report comparison = bench.compare_results(xav_results, market_results) report = bench.generate_report() """ def __init__( self, device: Optional[str] = None, max_eval_samples: int = 500, batch_size: int = 8, report_dir: str = "/tmp/xavante_benchmarks", hf_token: Optional[str] = None, ): self.device = device or ("cuda" if torch.cuda.is_available() else "cpu") self.max_eval_samples = max_eval_samples self.batch_size = batch_size self.report_dir = Path(report_dir) # Fall back to HF_TOKEN env var if no token is explicitly provided. self.hf_token = hf_token or os.environ.get("HF_TOKEN", "") self.report_dir.mkdir(parents=True, exist_ok=True) # Results storage self._xavante_result: Optional[BenchmarkResult] = None self._market_results: Dict[str, BenchmarkResult] = {} self._comparisons: List[ComparisonEntry] = [] # ----------------------------------------------------------------------- # Xavante benchmark # ----------------------------------------------------------------------- def run_xavante_benchmark( self, model: nn.Module, streamer: Any, datasets: Optional[List[str]] = None, ) -> BenchmarkResult: """Test Xavante model on streaming datasets. Metrics computed: - Perplexity: from MSE loss on reconstruction task - Accuracy: proportion of samples where reconstruction loss < threshold - Throughput: tokens/sec (using BERT tokenization) - Memory: peak memory during evaluation - Latency: ms per token and per batch - BERTScore: average F1 between input and output embeddings """ logger.info("Running Xavante benchmark on %s", self.device) model.eval() model.to(self.device) # Reset CUDA memory tracking if self.device == "cuda" and torch.cuda.is_available(): torch.cuda.reset_peak_memory_stats() torch.cuda.synchronize() start_time = time.time() total_loss = 0.0 total_tokens = 0 n_samples = 0 n_correct = 0 bert_scores = [] latency_per_token = [] latency_per_batch = [] dataset_ids_used = [] threshold = 0.5 # Accuracy threshold: loss < 0.5 is "correct" d_model = model.d_model if hasattr(model, 'd_model') else 128 # Determine if model has BERT projection has_proj = hasattr(model, '_bert_proj') for sample in streamer.stream_all(): if n_samples >= self.max_eval_samples: break if sample.text_embedding is None: continue batch_start = time.time() # Prepare input emb = sample.text_embedding.unsqueeze(0).to(self.device) # (1, 768) if has_proj: emb = model._bert_proj(emb) elif emb.size(-1) != d_model: # Simple fallback: truncate or pad if emb.size(-1) > d_model: emb = emb[:, :d_model] else: emb = F.pad(emb, (0, d_model - emb.size(-1))) # Expand to sequence format seq_len = 16 X_input = emb.unsqueeze(1).expand(-1, seq_len, -1) # (1, seq_len, d_model) # Target: same as input (reconstruction task) Y_target = X_input.clone() # Forward pass with torch.no_grad(): output = model(X_input) loss = F.mse_loss(output, Y_target).item() batch_time = time.time() - batch_start tokens_in_sample = seq_len # Approximate token count total_tokens += tokens_in_sample total_loss += loss if loss < threshold: n_correct += 1 latency_per_batch.append(batch_time * 1000) # ms latency_per_token.append((batch_time / max(tokens_in_sample, 1)) * 1000) # ms if sample.bert_score > 0: bert_scores.append(sample.bert_score) if sample.dataset_id not in dataset_ids_used: dataset_ids_used.append(sample.dataset_id) n_samples += 1 # Periodic cleanup if n_samples % 100 == 0: gc.collect() if torch.cuda.is_available(): torch.cuda.empty_cache() logger.info("Xavante benchmark: %d/%d samples, loss=%.4f", n_samples, self.max_eval_samples, loss) eval_time = time.time() - start_time peak_mem = _get_peak_memory_mb(self.device) # Compute metrics avg_loss = total_loss / max(n_samples, 1) perplexity = max(1.0, avg_loss) # Approximate: higher loss ≈ higher perplexity accuracy = n_correct / max(n_samples, 1) throughput = total_tokens / max(eval_time, 0.001) avg_bert_score = sum(bert_scores) / max(len(bert_scores), 1) result = BenchmarkResult( model_name="Xavante-GRU-RING", model_id="xavante_internal", model_type="gru_ring", params_m=sum(p.numel() for p in model.parameters()) / 1e6, perplexity=round(perplexity, 4), accuracy=round(accuracy, 4), throughput_tokens_per_sec=round(throughput, 2), peak_memory_mb=round(peak_mem, 1), latency_per_token_ms=round(sum(latency_per_token) / max(len(latency_per_token), 1), 2), latency_per_batch_ms=round(sum(latency_per_batch) / max(len(latency_per_batch), 1), 2), bert_score_f1=round(avg_bert_score, 4), samples_evaluated=n_samples, eval_time_s=round(eval_time, 1), dataset_ids_used=dataset_ids_used, quantization="none", device=self.device, ) self._xavante_result = result logger.info("Xavante benchmark complete: %s", asdict(result)) return result # ----------------------------------------------------------------------- # Market model benchmark # ----------------------------------------------------------------------- def run_market_benchmark( self, model_name: str, streamer: Any, datasets: Optional[List[str]] = None, ) -> BenchmarkResult: """Test a market model on streaming datasets. model_name must be a key in MARKET_MODELS dict. """ model_info = MARKET_MODELS.get(model_name) if model_info is None: raise ValueError(f"Unknown market model: {model_name}. Available: {list(MARKET_MODELS.keys())}") logger.info("Running market benchmark for %s (%s)", model_name, model_info["model_id"]) # Reset memory tracking if self.device == "cuda" and torch.cuda.is_available(): torch.cuda.reset_peak_memory_stats() torch.cuda.synchronize() # Load market model market_model = None market_tokenizer = None try: from transformers import AutoModel, AutoModelForCausalLM, AutoModelForSeq2SeqLM, AutoTokenizer model_id = model_info["model_id"] model_type = model_info["type"] # Set HF token os.environ["HF_TOKEN"] = self.hf_token logger.info("Loading %s from %s...", model_name, model_id) market_tokenizer = AutoTokenizer.from_pretrained(model_id, trust_remote_code=True) if market_tokenizer.pad_token is None: market_tokenizer.pad_token = market_tokenizer.eos_token if model_type == "encoder": market_model = AutoModel.from_pretrained(model_id, trust_remote_code=True) elif model_type == "decoder": # For decoder models, load as causal LM load_kwargs = {"trust_remote_code": True} if model_info.get("quantized"): from transformers import BitsAndBytesConfig load_kwargs["quantization_config"] = BitsAndBytesConfig( load_in_4bit=True, bnb_4bit_compute_dtype=torch.bfloat16, ) load_kwargs["device_map"] = "auto" market_model = AutoModelForCausalLM.from_pretrained(model_id, **load_kwargs) elif model_type == "encoder_decoder": market_model = AutoModelForSeq2SeqLM.from_pretrained(model_id, trust_remote_code=True) else: market_model = AutoModel.from_pretrained(model_id, trust_remote_code=True) market_model.to(self.device) market_model.eval() for param in market_model.parameters(): param.requires_grad = False except Exception as e: logger.error("Failed to load market model %s: %s", model_name, e) # Return a result with errors return BenchmarkResult( model_name=model_name, model_id=model_info["model_id"], model_type=model_info["type"], params_m=model_info["params_m"], errors=1, extra={"load_error": str(e)}, ) # Run evaluation start_time = time.time() total_loss = 0.0 total_tokens = 0 n_samples = 0 n_correct = 0 bert_scores = [] latency_per_token = [] latency_per_batch = [] dataset_ids_used = [] threshold = 2.0 # Higher threshold for LM models (they output logits) for sample in streamer.stream_all(): if n_samples >= self.max_eval_samples: break if not sample.raw_text or len(sample.raw_text.strip()) < 10: continue batch_start = time.time() try: # Tokenize the sample text enc = market_tokenizer( sample.raw_text, padding=True, truncation=True, max_length=512, return_tensors="pt", ) input_ids = enc["input_ids"].to(self.device) attention_mask = enc["attention_mask"].to(self.device) tokens_in_sample = input_ids.size(1) total_tokens += tokens_in_sample with torch.no_grad(): if model_info["type"] == "encoder": # For encoder models: compute embedding quality outputs = market_model(input_ids=input_ids, attention_mask=attention_mask) # Measure reconstruction quality via embedding similarity hidden = outputs.last_hidden_state # (1, T, H) # Self-similarity: mean cosine similarity between adjacent tokens if hidden.size(1) > 2: h1 = F.normalize(hidden[:, :-1, :], p=2, dim=-1) h2 = F.normalize(hidden[:, 1:, :], p=2, dim=-1) sim = (h1 * h2).sum(dim=-1).mean().item() loss = 1.0 - sim # Lower loss = better coherence else: loss = 0.5 elif model_info["type"] == "decoder": # For decoder models: compute perplexity directly outputs = market_model(input_ids=input_ids, attention_mask=attention_mask) logits = outputs.logits # (1, T, vocab) # Shift for next-token prediction shift_logits = logits[:, :-1, :].contiguous() shift_labels = input_ids[:, 1:].contiguous() # Compute cross-entropy loss (perplexity) ce_loss = F.cross_entropy( shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1), ignore_index=market_tokenizer.pad_token_id, ) loss = ce_loss.item() perplexity_contribution = torch.exp(ce_loss).item() elif model_info["type"] == "encoder_decoder": # For T5: compute generation loss # Use input as both source and target (reconstruction) decoder_input_ids = input_ids.clone() outputs = market_model( input_ids=input_ids, attention_mask=attention_mask, decoder_input_ids=decoder_input_ids, ) logits = outputs.logits ce_loss = F.cross_entropy( logits.view(-1, logits.size(-1)), decoder_input_ids.view(-1), ignore_index=market_tokenizer.pad_token_id, ) loss = ce_loss.item() else: loss = 0.0 total_loss += loss if loss < threshold: n_correct += 1 batch_time = time.time() - batch_start latency_per_batch.append(batch_time * 1000) latency_per_token.append((batch_time / max(tokens_in_sample, 1)) * 1000) if sample.bert_score > 0: bert_scores.append(sample.bert_score) if sample.dataset_id not in dataset_ids_used: dataset_ids_used.append(sample.dataset_id) n_samples += 1 if n_samples % 50 == 0: gc.collect() if torch.cuda.is_available(): torch.cuda.empty_cache() logger.info("%s benchmark: %d/%d samples", model_name, n_samples, self.max_eval_samples) except Exception as e: logger.warning("Error evaluating sample %d for %s: %s", n_samples, model_name, e) continue eval_time = time.time() - start_time peak_mem = _get_peak_memory_mb(self.device) # Compute metrics avg_loss = total_loss / max(n_samples, 1) # For decoder models, perplexity is directly computed from CE loss if model_info["type"] == "decoder": perplexity = min(1000.0, max(1.0, avg_loss)) # CE loss ≈ log(perplexity) else: perplexity = max(1.0, avg_loss) accuracy = n_correct / max(n_samples, 1) throughput = total_tokens / max(eval_time, 0.001) avg_bert_score = sum(bert_scores) / max(len(bert_scores), 1) # Unload market model del market_model, market_tokenizer gc.collect() if torch.cuda.is_available(): torch.cuda.empty_cache() result = BenchmarkResult( model_name=model_name, model_id=model_info["model_id"], model_type=model_info["type"], params_m=model_info["params_m"], perplexity=round(perplexity, 4), accuracy=round(accuracy, 4), throughput_tokens_per_sec=round(throughput, 2), peak_memory_mb=round(peak_mem, 1), latency_per_token_ms=round(sum(latency_per_token) / max(len(latency_per_token), 1), 2), latency_per_batch_ms=round(sum(latency_per_batch) / max(len(latency_per_batch), 1), 2), bert_score_f1=round(avg_bert_score, 4), samples_evaluated=n_samples, eval_time_s=round(eval_time, 1), dataset_ids_used=dataset_ids_used, quantization=model_info.get("quantization", "none"), device=self.device, ) self._market_results[model_name] = result logger.info("Market benchmark %s complete: %s", model_name, asdict(result)) return result # ----------------------------------------------------------------------- # Compare results # ----------------------------------------------------------------------- def compare_results( self, xavante_results: Optional[BenchmarkResult] = None, market_results: Optional[Dict[str, BenchmarkResult]] = None, ) -> List[ComparisonEntry]: """Generate comparison between Xavante and market models. For each metric and each market model, produces a ComparisonEntry with ratio (xavante/market) and winner determination. """ if xavante_results is None: xavante_results = self._xavante_result if market_results is None: market_results = self._market_results if xavante_results is None: logger.error("No Xavante results to compare") return [] comparisons = [] metrics = [ ("perplexity", "lower_is_better"), ("accuracy", "higher_is_better"), ("throughput_tokens_per_sec", "higher_is_better"), ("peak_memory_mb", "lower_is_better"), ("latency_per_token_ms", "lower_is_better"), ("latency_per_batch_ms", "lower_is_better"), ("bert_score_f1", "higher_is_better"), ] for market_name, market_result in market_results.items(): for metric_name, direction in metrics: xav_val = getattr(xavante_results, metric_name, 0.0) mkt_val = getattr(market_result, metric_name, 0.0) # Skip if market model failed to load if market_result.errors > 0 and metric_name != "peak_memory_mb": continue # Compute ratio if mkt_val == 0: ratio = float("inf") if xav_val > 0 else 0.0 else: ratio = xav_val / mkt_val # Determine winner if direction == "higher_is_better": winner = "xavante" if xav_val > mkt_val else ("market" if mkt_val > xav_val else "tie") else: # lower_is_better winner = "xavante" if xav_val < mkt_val else ("market" if mkt_val < xav_val else "tie") # Add note about params comparison note = "" if metric_name == "peak_memory_mb": note = f"Xavante={xavante_results.params_m:.1f}M params vs {market_result.params_m:.1f}M params" elif metric_name == "throughput_tokens_per_sec": note = f"Throughput/param ratio: Xavante={xav_val/xavante_results.params_m:.2f} vs Market={mkt_val/market_result.params_m:.2f}" comparisons.append(ComparisonEntry( market_model_name=market_name, metric=metric_name, xavante_value=round(xav_val, 4), market_value=round(mkt_val, 4), ratio=round(ratio, 4), winner=winner, note=note, )) self._comparisons = comparisons return comparisons # ----------------------------------------------------------------------- # Generate report # ----------------------------------------------------------------------- def generate_report( self, output_path: Optional[str] = None, ) -> Dict[str, Any]: """Output comparison report as structured JSON. Includes: - Xavante results - Market model results - Comparison entries - Summary statistics - Formatted table data """ report = { "title": "Xavante GRU RING Benchmark Comparison Report", "timestamp": time.strftime("%Y-%m-%d %H:%M:%S"), "device": self.device, "xavante_results": asdict(self._xavante_result) if self._xavante_result else None, "market_results": {k: asdict(v) for k, v in self._market_results.items()}, "comparisons": [asdict(c) for c in self._comparisons], "summary": self._compute_summary(), "comparison_table": self._format_table(), } # Save to file if output_path is None: output_path = str(self.report_dir / "benchmark_comparison_report.json") out_path = Path(output_path) out_path.parent.mkdir(parents=True, exist_ok=True) try: with open(out_path, "w") as f: json.dump(report, f, indent=2, default=str) logger.info("Benchmark report saved to %s", out_path) except Exception as e: logger.warning("Report save failed: %s", e) return report def _compute_summary(self) -> Dict[str, Any]: """Compute aggregate summary statistics.""" summary = { "models_compared": len(self._market_results), "total_comparisons": len(self._comparisons), "xavante_wins": 0, "market_wins": 0, "ties": 0, "xavante_win_rate": 0.0, } for comp in self._comparisons: if comp.winner == "xavante": summary["xavante_wins"] += 1 elif comp.winner == "market": summary["market_wins"] += 1 else: summary["ties"] += 1 total = summary["total_comparisons"] if total > 0: summary["xavante_win_rate"] = round(summary["xavante_wins"] / total, 4) # Best market model per metric best_market = {} metrics = ["perplexity", "accuracy", "throughput_tokens_per_sec", "peak_memory_mb", "latency_per_token_ms", "bert_score_f1"] for metric in metrics: best_name = "" best_val = None for name, result in self._market_results.items(): val = getattr(result, metric, 0.0) if result.errors > 0: continue if best_val is None: best_val = val best_name = name elif metric in ("accuracy", "throughput_tokens_per_sec", "bert_score_f1"): if val > best_val: best_val = val best_name = name else: if val < best_val: best_val = val best_name = name if best_name: best_market[metric] = {"model": best_name, "value": round(best_val, 4)} summary["best_market_per_metric"] = best_market return summary def _format_table(self) -> List[Dict[str, str]]: """Format comparison as a printable table.""" rows = [] # Header metrics_order = ["perplexity", "accuracy", "throughput_tokens_per_sec", "peak_memory_mb", "latency_per_token_ms", "bert_score_f1"] for metric in metrics_order: row = {"metric": metric} if self._xavante_result: row["Xavante"] = str(round(getattr(self._xavante_result, metric, 0), 2)) for name, result in self._market_results.items(): if result.errors == 0: row[name] = str(round(getattr(result, metric, 0), 2)) rows.append(row) return rows # --------------------------------------------------------------------------- # Convenience function: run full comparison pipeline # --------------------------------------------------------------------------- def run_full_comparison( xavante_model: nn.Module, hf_token: Optional[str] = None, device: Optional[str] = None, max_eval_samples: int = 200, output_path: Optional[str] = None, ) -> Dict[str, Any]: """Run the full comparison pipeline: Xavante vs all market models. Convenience function that handles streamer creation, authentication, benchmarking, comparison, and report generation in one call. """ from flexnet.hf_dataset_streamer import HFDatasetStreamer, DEFAULT_DATASETS # Fall back to HF_TOKEN env var if no token is explicitly provided. hf_token = hf_token or os.environ.get("HF_TOKEN", "") if not hf_token: raise ValueError( "HF_TOKEN is empty. Set the HF_TOKEN env var or pass hf_token=... " "to run_full_comparison()." ) bench = BenchmarkComparison( device=device, max_eval_samples=max_eval_samples, hf_token=hf_token, ) # Create streamer for evaluation streamer = HFDatasetStreamer( hf_token=hf_token, datasets_list=DEFAULT_DATASETS[:3], # Use first 3 datasets for speed max_seq_length=256, compute_bert_score=True, device=bench.device, ) streamer.authenticate() # Run Xavante benchmark xav_results = bench.run_xavante_benchmark(xavante_model, streamer) # Run market benchmarks for model_name in MARKET_MODELS: try: bench.run_market_benchmark(model_name, streamer) except Exception as e: logger.warning("Market benchmark %s failed: %s", model_name, e) # Compare comparisons = bench.compare_results() # Generate report report = bench.generate_report(output_path=output_path) return report # --------------------------------------------------------------------------- # __all__ # --------------------------------------------------------------------------- __all__ = [ "BenchmarkComparison", "BenchmarkResult", "ComparisonEntry", "MARKET_MODELS", "run_full_comparison", ]