File size: 31,929 Bytes
250e8de
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
"""
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",
]