"vllm/engine/async_llm_engine.py" did not exist on "da5ddcd544ac5ce6bc4f522af9cbdc315f94620e"
test_benchmark.py 42.4 KB
Newer Older
Ceng's avatar
Ceng committed
1
2
3
4
import sys
import os
import time
import re
5
import csv
6
import numpy as np
Ceng23333's avatar
Ceng23333 committed
7
from datasets import load_dataset, Dataset
Ceng's avatar
Ceng committed
8
9
10
from abc import ABC, abstractmethod


11
12
13
14
TOTAL_TOKENS = 0
TOTAL_TIME = 0.0


Ceng's avatar
Ceng committed
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
class BaseBenchmark(ABC):
    """Base class for benchmark evaluation with common tokenizer and generation utilities"""

    def encode_text(self, text):
        """Encode text to token IDs - reused across backends"""
        return self.tokenizer.encode(text)

    def decode_token(self, token_id):
        """Decode token ID to text - reused across backends"""
        return self.tokenizer.decode(token_id)

    @abstractmethod
    def render_input_content(self, *args, **kwargs):
        """Render input content - benchmark-specific implementation"""
        pass

    @abstractmethod
    def generate(self, *args, **kwargs):
        """Generate response - benchmark-specific implementation"""
        pass

    @abstractmethod
    def _generate_step(self, tokens, max_steps, topp_, topk_, temperature_):
        """Backend-specific generation implementation"""
        pass


class InfiniLMBenchmark(BaseBenchmark):
    """Wrapper class for InfiniLM cpp backend for benchmark evaluation"""

45
46
47
48
49
50
51
    def __init__(
        self,
        model_dir_path,
        device_type_str="cpu",
        ndev=1,
        backend="cpp",
        benchmark="ceval",
52
        enable_paged_attn=False,
53
    ):
Ceng's avatar
Ceng committed
54
        import transformers
55
56
57
58
59
        import infinicore
        from infinilm.modeling_utils import load_model_state_dict_by_file
        from infinilm.distributed import DistConfig
        from infinilm.cache import StaticKVCacheConfig, PagedKVCacheConfig
        from infinilm.infer_engine import InferEngine
Ceng's avatar
Ceng committed
60
61
62
63

        self.benchmark = benchmark

        # Map device type string to infinicore device
64
65
        # Note: These map to the Python device type strings used by infinicore.device()
        # which correspond to _TORCH_DEVICE_MAP values in InfiniCore/python/infinicore/device.py
Ceng's avatar
Ceng committed
66
67
68
        device_map = {
            "cpu": "cpu",
            "nvidia": "cuda",
69
            "cambricon": "mlu",
70
71
72
73
74
75
            "ascend": "npu",
            "metax": "cuda",
            "moore": "musa",
            "iluvatar": "cuda",
            "kunlun": "cuda",
            "hygon": "cuda",
76
            "ali": "cuda",
Ceng's avatar
Ceng committed
77
78
79
80
81
82
83
84
85
86
87
        }

        device_name = device_map.get(device_type_str.lower(), "cpu")
        # CUDA_VISIBLE_DEVICES is automatically respected by CUDA runtime API
        # When CUDA_VISIBLE_DEVICES=5 is set, CUDA only sees device 5 as device 0
        # So device index 0 will automatically map to the first visible device
        self.device = infinicore.device(device_name, 0)

        # Load config and tokenizer
        with open(os.path.join(model_dir_path, "config.json"), "r") as f:
            import json
88

Ceng's avatar
Ceng committed
89
90
91
92
93
94
95
            self.config_dict = json.load(f)

        # Align tokenizer initialization with jiuge backend (010)
        # Match the exact same initialization logic based on model type
        model_type = self.config_dict.get("model_type", "")
        if model_type == "llama":
            # For llama models: no trust_remote_code (matches jiuge line 465)
96
97
98
            self.tokenizer = transformers.AutoTokenizer.from_pretrained(
                model_dir_path, trust_remote_code=True
            )
Ceng's avatar
Ceng committed
99
100
101
102
103
104
105
        elif model_type in ["fm9g", "minicpm", "fm9g7b"]:
            # For fm9g/minicpm/fm9g7b models: use trust_remote_code=True (matches jiuge lines 493-495, 518-520)
            self.tokenizer = transformers.AutoTokenizer.from_pretrained(
                model_dir_path, trust_remote_code=True
            )
        elif model_type in ["qwen2", "qwen3"]:
            # For qwen2/qwen3 models: no trust_remote_code (matches jiuge line 534-536)
106
107
108
            self.tokenizer = transformers.AutoTokenizer.from_pretrained(
                model_dir_path, trust_remote_code=True
            )
Ceng's avatar
Ceng committed
109
110
111
112
113
114
115
116
117
118
119
        else:
            # Default: use trust_remote_code=True for other models
            self.tokenizer = transformers.AutoTokenizer.from_pretrained(
                model_dir_path, trust_remote_code=True
            )

        eos_token_id = self.config_dict.get("eos_token_id")
        self.eos_token_id = (
            [eos_token_id] if isinstance(eos_token_id, int) else eos_token_id
        )

120
121
122
        if backend != "cpp":
            raise ValueError(f"Unsupported backend: {backend}.")

Ceng's avatar
Ceng committed
123
124
        # Create model with cpp backend
        print("Loading model with cpp backend...")
125
        self.model = InferEngine(
Ceng's avatar
Ceng committed
126
127
128
            model_dir_path,
            device=self.device,
            distributed_config=DistConfig(ndev),
129
130
131
            cache_config=(
                PagedKVCacheConfig(128) if enable_paged_attn else StaticKVCacheConfig()
            ),
Ceng's avatar
Ceng committed
132
133
134
135
136
137
138
        )

        # Enable KV cache for generation
        self.model.use_cache = True

        # Load weights
        print("Loading model weights...")
139
140
        load_model_state_dict_by_file(
            self.model,
Ceng's avatar
Ceng committed
141
            model_dir_path,
142
            dtype=self.model.config.dtype,
Ceng's avatar
Ceng committed
143
144
145
146
147
148
149
150
151
        )
        print("Model loaded successfully")

    def max_context_len(self):
        return self.config_dict.get("max_position_embeddings", 2048)

    def render_input_content(self, *args, **kwargs):
        """Render input content based on benchmark type"""
        if self.benchmark == "ceval":
152
            return render_ceval(self.tokenizer, *args, **kwargs)
Ceng's avatar
Ceng committed
153
        elif self.benchmark == "mmlu":
154
            return render_mmlu(self.tokenizer, *args, **kwargs)
Ceng's avatar
Ceng committed
155
156
157
158
159
160
161
162
163
164
165
166
167
        else:
            raise ValueError(f"Unknown benchmark: {self.benchmark}")

    def generate(self, *args, max_steps=500, topp_=1.0, topk_=1, temperature_=1.0):
        """Generate response based on benchmark type"""
        # Render input content
        input_content = self.render_input_content(*args)
        print(input_content, end="", flush=True)

        # Encode input
        tokens = self.encode_text(input_content)

        # Delegate to backend-specific generation implementation
168
        output_content = self._generate_step(
Ceng's avatar
Ceng committed
169
170
171
            tokens, max_steps, topp_, topk_, temperature_
        )

172
        return output_content
Ceng's avatar
Ceng committed
173
174
175
176
177
178
179
180
181
182
183

    def _generate_step(self, tokens, max_steps, topp_, topk_, temperature_):
        """
        InfiniLM cpp backend-specific generation implementation

        NOTE: Validation confirmed input configs are identical between backends.
        The issue was that manual generation loop called InferEngine.generate() which
        doesn't maintain KV cache. Solution: Use model's built-in generate() method
        which properly handles KV cache through GenerationMixin.
        """
        # Convert tokens to infinicore format
184
185
186
        import infinicore
        from infinilm.infer_engine import GenerationConfig

Ceng's avatar
Ceng committed
187
        input_ids_list = [tokens]
188
        input_ids = infinicore.from_list(input_ids_list)
Ceng's avatar
Ceng committed
189

190
191
        start_time = time.perf_counter()

192
        # For cpp backend, reset cache before generation if use_cache is enabled
193
194
195
196
197
        if (
            self.model.use_cache
            and hasattr(self.model, "_model")
            and hasattr(self.model._model, "reset_cache")
        ):
198
199
200
            batch_size = input_ids.shape[0]
            seq_len = input_ids.shape[1]
            max_cache_len = max_steps + seq_len
201
202
203
            self.model.reset_cache(
                batch_size=batch_size, initial_capacity=max_cache_len
            )
204

Ceng's avatar
Ceng committed
205
206
        # Use model's built-in generate() method which properly handles KV cache
        # Pass sampling parameters (temperature, topk, topp) via kwargs
207
        output_ids = self.model.generate(
Ceng's avatar
Ceng committed
208
            input_ids=input_ids,
209
210
211
212
213
214
            generation_config=GenerationConfig(
                max_new_tokens=max_steps,
                temperature=temperature_,
                top_k=topk_,
                top_p=topp_,
            ),
Ceng's avatar
Ceng committed
215
        )
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236

        end_time = time.perf_counter()

        # ---- post process ----
        generated_ids = np.array([output_id.to_numpy()[0] for output_id in output_ids])
        output_text = self.tokenizer.decode(generated_ids)

        # ---- stats ----
        input_tokens = len(tokens)
        new_tokens = generated_ids.size
        total_tokens = input_tokens + new_tokens

        total_time = end_time - start_time
        throughput = total_tokens / total_time if total_time > 0 else 0.0
        print(output_text)
        print()
        print(f"Total time: {total_time * 1000:.2f} ms")
        print(f"Input tokens: {input_tokens}")
        print(f"New tokens: {new_tokens}")
        print(f"Total tokens processed: {total_tokens}")
        print(f"Throughput: {throughput:.2f} tok/s")
237
        global TOTAL_TOKENS, TOTAL_TIME
238
239
        TOTAL_TOKENS += total_tokens
        TOTAL_TIME += total_time
Ceng's avatar
Ceng committed
240

241
        return output_text
Ceng's avatar
Ceng committed
242
243
244
245
246
247
248

    def destroy_model_instance(self):
        # Cleanup if needed
        del self.model
        print("Model destroyed")


249
250
251
252
253
254
255
256
257
258
259
260
261
262
class TorchBenchmark(BaseBenchmark):
    """Torch backend using HuggingFace Transformers"""

    def __init__(self, model_dir_path, device_type_str="cpu", benchmark="ceval"):
        import torch
        import transformers

        self.benchmark = benchmark

        # Device
        if device_type_str == "nvidia":
            self.device = torch.device("cuda")
        elif device_type_str == "cpu":
            self.device = torch.device("cpu")
263
264
        elif device_type_str == "cambricon":
            self.device = torch.device("mlu")
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
        else:
            raise ValueError(
                f"Torch backend unsupported device type: {device_type_str}"
            )

        # Load tokenizer
        with open(os.path.join(model_dir_path, "config.json"), "r") as f:
            import json

            self.config_dict = json.load(f)

        model_type = self.config_dict.get("model_type", "")
        if model_type in ["fm9g", "minicpm", "fm9g7b"]:
            self.tokenizer = transformers.AutoTokenizer.from_pretrained(
                model_dir_path, trust_remote_code=True
            )
        else:
            self.tokenizer = transformers.AutoTokenizer.from_pretrained(
                model_dir_path, trust_remote_code=True
            )

        # Load model
        print("Loading model with torch backend...")
        self.model = transformers.AutoModelForCausalLM.from_pretrained(
            model_dir_path,
            torch_dtype=torch.bfloat16 if self.device.type == "cuda" else torch.float32,
            trust_remote_code=True,
        ).to(self.device)

        self.model.eval()
        print("Torch model loaded successfully")

        eos_token_id = self.config_dict.get("eos_token_id")
        self.eos_token_id = (
            [eos_token_id] if isinstance(eos_token_id, int) else eos_token_id
        )

    def max_context_len(self):
        return self.config_dict.get("max_position_embeddings", 2048)

    def render_input_content(self, *args, **kwargs):
        if self.benchmark == "ceval":
            return render_ceval(self.tokenizer, *args, **kwargs)
        elif self.benchmark == "mmlu":
            return render_mmlu(self.tokenizer, *args, **kwargs)
        else:
            raise ValueError(f"Unknown benchmark: {self.benchmark}")

    def _generate_step(self, tokens, max_steps, topp_, topk_, temperature_):
        import torch
        import time

        input_ids = torch.tensor([tokens], device=self.device)

        if self.device.type == "cuda":
            torch.cuda.synchronize()

        start_time = time.perf_counter()

        outputs = self.model.generate(
            input_ids=input_ids,
            max_new_tokens=max_steps,
            do_sample=temperature_ > 0,
            temperature=temperature_,
            top_k=topk_,
            top_p=topp_,
            eos_token_id=self.eos_token_id,
            pad_token_id=2,
        )

        # --- end sync ---
        if self.device.type == "cuda":
            torch.cuda.synchronize()

        end_time = time.perf_counter()

        # ---- post process ----
        generated_ids = outputs[0][len(tokens) :]
        output_text = self.tokenizer.decode(generated_ids)

        # ---- stats ----
        input_tokens = len(tokens)
        new_tokens = generated_ids.numel()
        total_tokens = input_tokens + new_tokens

        total_time = end_time - start_time
        throughput = total_tokens / total_time if total_time > 0 else 0.0
        print(output_text)
        print()
        print(f"Total time: {total_time * 1000:.2f} ms")
        print(f"Input tokens: {input_tokens}")
        print(f"New tokens: {new_tokens}")
        print(f"Total tokens processed: {total_tokens}")
        print(f"Throughput: {throughput:.2f} tok/s")
        global TOTAL_TOKENS, TOTAL_TIME
        TOTAL_TOKENS += total_tokens
        TOTAL_TIME += total_time

        return output_text

    def generate(self, *args, max_steps=500, topp_=1.0, topk_=1, temperature_=1.0):
        input_content = self.render_input_content(*args)
        print(input_content, end="", flush=True)

        tokens = self.encode_text(input_content)

        return self._generate_step(tokens, max_steps, topp_, topk_, temperature_)

    def destroy_model_instance(self):
        del self.model
        print("Torch model destroyed")


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
class VLLMBenchmark(BaseBenchmark):
    """vLLM backend using vllm.LLM"""

    def __init__(
        self,
        model_dir_path,
        device_type_str="nvidia",
        tensor_parallel_size=1,
        benchmark="ceval",
    ):
        import transformers
        from vllm import LLM

        if device_type_str == "cpu":
            raise ValueError("vLLM backend does not support CPU device type.")

        self.benchmark = benchmark

        # ---- tokenizer ----
        with open(os.path.join(model_dir_path, "config.json"), "r") as f:
            import json

            self.config_dict = json.load(f)

        model_type = self.config_dict.get("model_type", "")
        if model_type in ["qwen2", "qwen3"]:
            self.tokenizer = transformers.AutoTokenizer.from_pretrained(
                model_dir_path, trust_remote_code=True
            )
        else:
            self.tokenizer = transformers.AutoTokenizer.from_pretrained(
                model_dir_path, trust_remote_code=True
            )

        eos_token_id = self.config_dict.get("eos_token_id")
        self.eos_token_id = (
            [eos_token_id] if isinstance(eos_token_id, int) else eos_token_id
        )

        # ---- vLLM engine ----
        print("Loading model with vLLM backend...")
        self.llm = LLM(
            model=model_dir_path,
            tensor_parallel_size=tensor_parallel_size,
            trust_remote_code=True,
        )
        print("vLLM model loaded successfully")

    def max_context_len(self):
        return self.config_dict.get("max_position_embeddings", 2048)

    def render_input_content(self, *args, **kwargs):
        if self.benchmark == "ceval":
            return render_ceval(self.tokenizer, *args, **kwargs)
        elif self.benchmark == "mmlu":
            return render_mmlu(self.tokenizer, *args, **kwargs)
        else:
            raise ValueError(f"Unknown benchmark: {self.benchmark}")

    def generate(self, *args, max_steps=500, topp_=1.0, topk_=1, temperature_=1.0):
        input_content = self.render_input_content(*args)
        print(input_content, end="", flush=True)

        tokens = self.encode_text(input_content)
        return self._generate_step(tokens, max_steps, topp_, topk_, temperature_)

    def _generate_step(self, tokens, max_steps, topp_, topk_, temperature_):
        from vllm import SamplingParams

        prompt = self.tokenizer.decode(tokens)

        sampling_params = SamplingParams(
            max_tokens=max_steps,
            temperature=temperature_,
            top_p=topp_,
            top_k=topk_,
            stop_token_ids=self.eos_token_id,
        )

        start_time = time.perf_counter()

        outputs = self.llm.generate(
            prompts=[prompt],
            sampling_params=sampling_params,
        )

        end_time = time.perf_counter()

        # ---- post process ----
        output_text = outputs[0].outputs[0].text

        # ---- stats ----
        input_tokens = len(tokens)
        new_tokens = len(self.encode_text(output_text))
        total_tokens = input_tokens + new_tokens

        total_time = end_time - start_time
        throughput = total_tokens / total_time if total_time > 0 else 0.0

        print(output_text)
        print()
        print(f"Total time: {total_time * 1000:.2f} ms")
        print(f"Input tokens: {input_tokens}")
        print(f"New tokens: {new_tokens}")
        print(f"Total tokens processed: {total_tokens}")
        print(f"Throughput: {throughput:.2f} tok/s")

        global TOTAL_TOKENS, TOTAL_TIME
        TOTAL_TOKENS += total_tokens
        TOTAL_TIME += total_time

        return output_text

    def destroy_model_instance(self):
        del self.llm
        print("vLLM model destroyed")


496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
def render_ceval(_tokenizer, conversation):
    """Render C-Eval conversation to input content"""
    return (
        _tokenizer.apply_chat_template(
            conversation=conversation,
            add_generation_prompt=True,
            tokenize=False,
        )
        + "正确答案是"
    )


def render_mmlu(_tokenizer, question, choices):
    """Render MMLU question and choices to input content"""
    choices_text = "\n".join(
PanZezhong's avatar
PanZezhong committed
511
        [f"{chr(65 + i)}. {choice}" for i, choice in enumerate(choices)]
512
513
514
515
516
517
518
519
520
521
522
    )
    instruction = (
        "You are a multiple-choice question solver. "
        "Select the correct option and respond with only the letter A, B, C, or D."
    )
    prompt = f"{instruction}\n\nQuestion: {question}\n{choices_text}\nAnswer:"

    # Use chat template if available, otherwise return plain text
    if hasattr(_tokenizer, "apply_chat_template"):
        conversation = [
            {"role": "system", "content": instruction},
523
            {"role": "user", "content": f"{question}\n{choices_text}\n"},
524
525
        ]
        try:
526
527
528
529
530
531
532
            return (
                _tokenizer.apply_chat_template(
                    conversation=conversation,
                    add_generation_prompt=True,
                    tokenize=False,
                )
                + "The answer is: "
533
534
535
536
537
538
            )
        except Exception:
            return prompt
    return prompt


Ceng's avatar
Ceng committed
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
def extract_answer_ceval(output_content, answer):
    """Extract predicted answer from C-Eval output"""
    output_upper = output_content.upper().strip()
    position = 0
    ABCD = output_upper[position : position + 2]
    return answer in ABCD


def extract_answer_mmlu(output_content):
    """Extract predicted answer from MMLU output (returns 0-3 index or None)"""
    output_upper = output_content.upper().strip()

    # Find first meaningful token
    match = re.search(r"\b([ABCD])\b", output_upper)
    if match:
554
        return ord(match.group(1)) - ord("A")
Ceng's avatar
Ceng committed
555
556
557
558
559
560
561
    else:
        match_num = re.search(r"\b([0-3])\b", output_upper)
        if match_num:
            return int(match_num.group(1))
    return None


562
563
564
565
566
567
568
569
570
571
572
573
574
575
def evaluate_samples(model, samples, benchmark, max_new_tokens, subject_name=None):
    """Evaluate samples for a single subject and return results"""
    answers_list = []
    for idx, sample in enumerate(samples):
        if benchmark == "ceval":
            input_content = f"'question':{sample['question']},'A': {sample['A']}, 'B':{sample['B']}, 'C': {sample['C']},'D': {sample['D']}。"
            conversation = [
                {
                    "role": "system",
                    "content": "请从question的A,B,C,D四个选项中选择正确的选项。例如,标准答案:A。",
                },
                {"role": "user", "content": input_content},
            ]
            answer = sample["answer"]
576
577
578
579
580
581
            output_content = model.generate(
                conversation,
                max_steps=max_new_tokens,
                topp_=1.0,
                topk_=1,
                temperature_=1.0,
582
583
            )
            is_correct = extract_answer_ceval(output_content, answer)
584
585
586
587
588
589
590
591
592
            answers_list.append(
                {
                    "id": sample.get("id", idx),
                    "output_content": output_content,
                    "answer": answer,
                    "is_correct": is_correct,
                    "subject": subject_name,
                }
            )
593
594
595
596
            if benchmark == "ceval":
                print("标准答案:", answer)

        elif benchmark == "mmlu":
597
598
599
600
601
602
603
604
605
606
607
            question = sample["question"]
            choices = sample["choices"]
            answer_idx = sample["answer"]  # MMLU answer is 0-3 index

            output_content = model.generate(
                question,
                choices,
                max_steps=max_new_tokens,
                topp_=1.0,
                topk_=1,
                temperature_=1.0,
608
609
610
611
612
613
            )

            predicted_answer = extract_answer_mmlu(output_content)

            # Convert answer index to letter for display
            answer_letter = chr(65 + answer_idx) if answer_idx < 4 else "?"
614
615
616
617
618
            predicted_letter = (
                chr(65 + predicted_answer)
                if predicted_answer is not None and predicted_answer < 4
                else "?"
            )
619

620
621
622
            print(
                f"Sample {idx}: Correct answer: {answer_letter} ({answer_idx}), Predicted: {predicted_letter} ({predicted_answer})"
            )
623

624
625
626
627
628
629
630
631
632
            answers_list.append(
                {
                    "id": idx,
                    "output_content": output_content,
                    "answer": answer_idx,
                    "predicted": predicted_answer,
                    "subject": subject_name,
                }
            )
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

    # Evaluate results for this subject
    true_num = 0
    all_num = 0
    for cont in answers_list:
        id = cont["id"]
        all_num = all_num + 1

        if benchmark == "ceval":
            answer = cont["answer"]
            is_correct = cont["is_correct"]
            if is_correct:
                true_num = true_num + 1
                print(f"id {id} : ", "正确")
            else:
                print(f"id {id}: ", "错误")

        elif benchmark == "mmlu":
            answer = cont["answer"]
            predicted = cont["predicted"]
            if predicted is not None and predicted == answer:
                true_num = true_num + 1
                print(f"id {id}: Correct")
            else:
                answer_letter = chr(65 + answer) if answer < 4 else "?"
658
659
660
661
662
663
664
665
                predicted_letter = (
                    chr(65 + predicted)
                    if predicted is not None and predicted < 4
                    else "?"
                )
                print(
                    f"id {id}: Wrong (correct: {answer_letter}, predicted: {predicted_letter})"
                )
666
667
668
669
670
671
672
673
674
675
676
677

    accuracy = true_num / all_num if all_num > 0 else 0.0
    if benchmark == "ceval":
        print(f"成绩: {true_num}/{all_num}", accuracy)
    else:
        print(f"Accuracy: {true_num}/{all_num} = {accuracy:.2%}")

    return {
        "subject": subject_name or "all",
        "correct": true_num,
        "total": all_num,
        "accuracy": accuracy,
678
        "answers_list": answers_list,
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
    }


def _load_ceval_from_cache(cache_dir, subject_name, split, ceval_subjects):
    """
    Load CEval data from local cache avoiding network calls.
    Scans cached Arrow files under ceval___ceval-exam and filters by split.
    """
    split_names = (
        ["test"] if split == "test" else ["val"] if split == "val" else ["val", "test"]
    )

    base = os.path.join(cache_dir, "ceval___ceval-exam", subject_name)
    if os.path.isdir(base):
        records = []
        for root, _, files in os.walk(base):
            for fname in files:
                if not fname.endswith(".arrow"):
                    continue
                lower = fname.lower()
                if split == "test" and "test" not in lower:
                    continue
701
702
703
                if split == "val" and not any(
                    x in lower for x in ["val", "validation", "dev"]
                ):
704
                    continue
705
706
707
                if split == "all" and not any(
                    x in lower for x in ["val", "validation", "dev", "test"]
                ):
708
709
710
711
712
713
714
715
716
717
                    continue
                try:
                    ds = Dataset.from_file(os.path.join(root, fname))
                    records.extend(ds.to_list())
                except Exception:
                    continue
        if records:
            return records

    # If cache_dir provided and nothing loaded, fail without network
718
719
720
    raise FileNotFoundError(
        f"CEval cached data not found for subject '{subject_name}' with splits {split_names}"
    )
721
722
723
724
725
726
727


def _load_mmlu_from_cache(cache_dir, subject_name, split, mmlu_subjects):
    """
    Load MMLU data from local cache avoiding network calls.
    Scans cached Arrow files under cache_dir/cais___mmlu and filters by split.
    """
728

729
730
731
732
    def load_one(subj):
        split_names = (
            ["test"]
            if split == "test"
733
734
735
736
737
            else (
                ["validation", "dev"]
                if split == "val"
                else ["validation", "dev", "test"]
            )
738
739
740
741
742
743
744
745
746
747
748
749
750
751
        )

        base = os.path.join(cache_dir, "cais___mmlu", subj)
        if not os.path.isdir(base):
            raise FileNotFoundError(f"MMLU cache dir not found: {base}")

        records = []
        for root, _, files in os.walk(base):
            for fname in files:
                if not fname.endswith(".arrow"):
                    continue
                lower = fname.lower()
                if split == "test" and "test" not in lower:
                    continue
752
753
754
                if split == "val" and not any(
                    x in lower for x in ["validation", "dev"]
                ):
755
                    continue
756
757
758
                if split == "all" and not any(
                    x in lower for x in ["validation", "dev", "test"]
                ):
759
760
761
762
763
764
765
766
                    continue
                try:
                    ds = Dataset.from_file(os.path.join(root, fname))
                    records.extend(ds.to_list())
                except Exception:
                    continue
        if records:
            return records
767
768
769
        raise FileNotFoundError(
            f"MMLU cached data not found for subject '{subj}' with splits {split_names}"
        )
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787

    if subject_name == "all":
        # Use hardcoded list of MMLU subjects, excluding "all"
        all_samples = []
        for subj in mmlu_subjects:
            try:
                all_samples.extend(load_one(subj))
            except FileNotFoundError:
                continue
        if not all_samples:
            raise FileNotFoundError(
                f"No MMLU cached data found for any subject. Please ensure datasets are cached."
            )
        return all_samples, "all"

    return load_one(subject_name), subject_name


Ceng's avatar
Ceng committed
788
789
790
791
def test():
    # Parse arguments manually to handle device flags properly
    if len(sys.argv) < 4:
        print(
792
            "Usage: python test_benchmark.py [--cpu | --nvidia| --cambricon | --ascend | --metax | --moore | --iluvatar | --kunlun | --hygon | --ali] <path/to/model_dir> --bench [ceval|mmlu] [--backend cpp|torch|vllm] [--ndev N] [--subject SUBJECT] [--split {test|val|all}] [--num_samples N] [--max_new_tokens N] [--output_csv PATH] [--cache_dir PATH]"
Ceng's avatar
Ceng committed
793
794
795
796
797
798
799
800
801
802
803
        )
        sys.exit(1)

    # Parse device flag (first argument)
    device_flag = sys.argv[1]
    model_path = sys.argv[2]

    # Parse optional arguments
    backend = "cpp"
    ndev = 1
    benchmark = None
804
    subject = "all"  # Shared for both C-Eval and MMLU, can be comma-separated
805
    split = "test"  # test | val | all
Ceng's avatar
Ceng committed
806
807
    num_samples = None
    max_new_tokens = 500
808
809
    output_csv = None
    cache_dir = None
810
    enable_paged_attn = False
Ceng's avatar
Ceng committed
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825

    i = 3
    while i < len(sys.argv):
        if sys.argv[i] == "--bench" and i + 1 < len(sys.argv):
            benchmark = sys.argv[i + 1]
            i += 2
        elif sys.argv[i] == "--backend" and i + 1 < len(sys.argv):
            backend = sys.argv[i + 1]
            i += 2
        elif sys.argv[i] == "--ndev" and i + 1 < len(sys.argv):
            ndev = int(sys.argv[i + 1])
            i += 2
        elif sys.argv[i] == "--subject" and i + 1 < len(sys.argv):
            subject = sys.argv[i + 1]
            i += 2
826
827
        elif sys.argv[i] == "--split" and i + 1 < len(sys.argv):
            split = sys.argv[i + 1]
Ceng's avatar
Ceng committed
828
829
830
831
832
833
834
            i += 2
        elif sys.argv[i] == "--num_samples" and i + 1 < len(sys.argv):
            num_samples = int(sys.argv[i + 1])
            i += 2
        elif sys.argv[i] == "--max_new_tokens" and i + 1 < len(sys.argv):
            max_new_tokens = int(sys.argv[i + 1])
            i += 2
835
836
837
838
839
840
        elif sys.argv[i] == "--output_csv" and i + 1 < len(sys.argv):
            output_csv = sys.argv[i + 1]
            i += 2
        elif sys.argv[i] == "--cache_dir" and i + 1 < len(sys.argv):
            cache_dir = sys.argv[i + 1]
            i += 2
841
842
843
        elif sys.argv[i] == "--enable_paged_attn":
            enable_paged_attn = True
            i += 1
Ceng's avatar
Ceng committed
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
        else:
            i += 1

    if benchmark is None:
        print("Error: --bench argument is required. Choose 'ceval' or 'mmlu'")
        sys.exit(1)

    if benchmark not in ["ceval", "mmlu"]:
        print(f"Error: Unknown benchmark '{benchmark}'. Choose 'ceval' or 'mmlu'")
        sys.exit(1)

    # Parse device type
    device_type_str = "cpu"
    if device_flag == "--cpu":
        device_type_str = "cpu"
    elif device_flag == "--nvidia":
        device_type_str = "nvidia"
    elif device_flag == "--cambricon":
        device_type_str = "cambricon"
    elif device_flag == "--ascend":
        device_type_str = "ascend"
    elif device_flag == "--metax":
        device_type_str = "metax"
    elif device_flag == "--moore":
        device_type_str = "moore"
    elif device_flag == "--iluvatar":
        device_type_str = "iluvatar"
    elif device_flag == "--kunlun":
        device_type_str = "kunlun"
    elif device_flag == "--hygon":
        device_type_str = "hygon"
875
876
    elif device_flag == "--ali":
        device_type_str = "ali"
Ceng's avatar
Ceng committed
877
878
    else:
        print(
879
            "Usage: python test_benchmark.py [--cpu | --nvidia| --cambricon | --ascend | --metax | --moore | --iluvatar | --kunlun | --hygon | --ali] <path/to/model_dir> --bench [ceval|mmlu] [--backend cpp|torch|vllm] [--ndev N] [--subject SUBJECT] [--num_samples N] [--max_new_tokens N] [--output_csv PATH] [--cache_dir PATH]"
Ceng's avatar
Ceng committed
880
881
882
        )
        sys.exit(1)

883
884
885
886
887
    # Normalize cache_dir and force offline when provided
    if cache_dir:
        cache_dir = os.path.expanduser(cache_dir)
        os.environ["HF_DATASETS_OFFLINE"] = "1"
        os.environ["HF_HUB_OFFLINE"] = "1"
Ceng's avatar
Ceng committed
888

889
890
891
892
    # Parse comma-separated subjects
    if split not in ["test", "val", "all"]:
        print("Error: --split must be one of: test, val, all")
        sys.exit(1)
Ceng's avatar
Ceng committed
893

894
895
896
897
    if subject and subject != "all":
        subject_list = [s.strip() for s in subject.split(",")]
    else:
        subject_list = ["all"]
Ceng's avatar
Ceng committed
898

899
    # Create model based on backend (create once, reuse for all subjects)
900
901

    if backend == "torch":
902
        assert ndev == 1, "Torch backend only supports single-device evaluation"
903
        model = TorchBenchmark(model_path, device_type_str, benchmark)
904
905
    elif backend == "vllm":
        model = VLLMBenchmark(model_path, device_type_str, ndev, benchmark)
Ceng's avatar
Ceng committed
906
    else:
907
908
909
        model = InfiniLMBenchmark(
            model_path, device_type_str, ndev, backend, benchmark, enable_paged_attn
        )
Ceng's avatar
Ceng committed
910

911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
    # Define helper functions for loading datasets
    if benchmark == "ceval":
        ceval_subjects = [
            "accountant",
            "advanced_mathematics",
            "art_studies",
            "basic_medicine",
            "business_administration",
            "chinese_language_and_literature",
            "civil_servant",
            "clinical_medicine",
            "college_chemistry",
            "college_economics",
            "college_physics",
            "college_programming",
            "computer_architecture",
            "computer_network",
            "discrete_mathematics",
            "education_science",
            "electrical_engineer",
            "environmental_impact_assessment_engineer",
            "fire_engineer",
            "high_school_biology",
            "high_school_chemistry",
            "high_school_chinese",
            "high_school_geography",
            "high_school_history",
            "high_school_mathematics",
            "high_school_physics",
            "high_school_politics",
            "ideological_and_moral_cultivation",
            "law",
            "legal_professional",
            "logic",
            "mao_zedong_thought",
            "marxism",
            "metrology_engineer",
            "middle_school_biology",
            "middle_school_chemistry",
            "middle_school_geography",
            "middle_school_history",
            "middle_school_mathematics",
            "middle_school_physics",
            "middle_school_politics",
            "modern_chinese_history",
            "operating_system",
            "physician",
            "plant_protection",
            "probability_and_statistics",
            "professional_tour_guide",
            "sports_science",
            "tax_accountant",
            "teacher_qualification",
            "urban_and_rural_planner",
            "veterinary_medicine",
        ]

        def _load_ceval_subject(subj):
            print(f"Loading C-Eval dataset (subject: {subj})...")
            if cache_dir:
                return _load_ceval_from_cache(cache_dir, subj, split, ceval_subjects)
            # online fallback via HF load_dataset
            if split == "all":
                records = []
                for split_name in ["val", "test"]:
                    try:
977
978
979
                        ds = load_dataset(
                            r"ceval/ceval-exam", name=subj, split=split_name
                        )
980
981
982
983
984
                        records.extend(ds.to_list())
                    except Exception:
                        continue
                if records:
                    return records
985
986
987
                raise FileNotFoundError(
                    f"No ceval splits found online for subject {subj}"
                )
988
989
990
991
992
993
994
995
996
997
998
999
1000
            hf_split = "test" if split == "test" else "val"
            ds = load_dataset(r"ceval/ceval-exam", name=subj, split=hf_split)
            data = ds.to_list()
            return data

        def load_subject_samples(subj_name):
            if subj_name == "all":
                samples = []
                for subj in ceval_subjects:
                    samples.extend(_load_ceval_subject(subj))
                return samples, "all"
            else:
                if subj_name not in ceval_subjects:
1001
1002
1003
                    raise ValueError(
                        f"Unknown C-Eval subject '{subj_name}'. Available subjects: {', '.join(ceval_subjects)}"
                    )
1004
                return _load_ceval_subject(subj_name), subj_name
Ceng's avatar
Ceng committed
1005

1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
    elif benchmark == "mmlu":
        mmlu_subjects = [
            "abstract_algebra",
            "anatomy",
            "astronomy",
            "business_ethics",
            "clinical_knowledge",
            "college_biology",
            "college_chemistry",
            "college_computer_science",
            "college_mathematics",
            "college_medicine",
            "college_physics",
            "computer_security",
            "conceptual_physics",
            "econometrics",
            "electrical_engineering",
            "elementary_mathematics",
            "formal_logic",
            "global_facts",
            "high_school_biology",
            "high_school_chemistry",
            "high_school_computer_science",
            "high_school_european_history",
            "high_school_geography",
            "high_school_government_and_politics",
            "high_school_macroeconomics",
            "high_school_mathematics",
            "high_school_microeconomics",
            "high_school_physics",
            "high_school_psychology",
            "high_school_statistics",
            "high_school_us_history",
            "high_school_world_history",
            "human_aging",
            "human_sexuality",
            "international_law",
            "jurisprudence",
            "logical_fallacies",
            "machine_learning",
            "management",
            "marketing",
            "medical_genetics",
            "miscellaneous",
            "moral_disputes",
            "moral_scenarios",
            "nutrition",
            "philosophy",
            "prehistory",
            "professional_accounting",
            "professional_law",
            "professional_medicine",
            "professional_psychology",
            "public_relations",
            "security_studies",
            "sociology",
            "us_foreign_policy",
            "virology",
            "world_religions",
        ]

        def _load_mmlu_subject(subj):
            print(f"Loading MMLU dataset (subject: {subj})...")
            if cache_dir:
                return _load_mmlu_from_cache(cache_dir, subj, split, mmlu_subjects)
            if subj == "all":
                samples = []
1073
1074
1075
                splits_to_load = (
                    ["test"]
                    if split == "test"
1076
1077
1078
                    else ["validation"]
                    if split == "val"
                    else ["validation", "test"]
1079
                )
1080
1081
1082
1083
1084
                # Load each subject individually from hardcoded list, excluding "all"
                for subject_name in mmlu_subjects:
                    for sp in splits_to_load:
                        try:
                            dataset = load_dataset("cais/mmlu", subject_name, split=sp)
1085
                            if hasattr(dataset, "to_list"):
1086
1087
1088
1089
1090
1091
                                samples.extend(dataset.to_list())
                            else:
                                samples.extend(list(dataset))
                        except Exception:
                            continue
                if not samples:
1092
1093
1094
                    raise FileNotFoundError(
                        f"No MMLU data found for any subject in the list"
                    )
1095
1096
                return samples, "all"
            else:
1097
1098
1099
                splits_to_load = (
                    ["test"]
                    if split == "test"
1100
1101
1102
                    else ["validation"]
                    if split == "val"
                    else ["validation", "test"]
1103
                )
1104
1105
1106
1107
                records = []
                for sp in splits_to_load:
                    try:
                        dataset = load_dataset("cais/mmlu", subj, split=sp)
1108
                        if hasattr(dataset, "to_list"):
1109
1110
1111
1112
1113
1114
                            records.extend(dataset.to_list())
                        else:
                            records.extend(list(dataset))
                    except Exception:
                        continue
                if not records:
1115
1116
1117
                    raise FileNotFoundError(
                        f"MMLU subject {subj} split(s) {splits_to_load} not found"
                    )
1118
                return records, subj
Ceng's avatar
Ceng committed
1119

1120
1121
        def load_subject_samples(subj_name):
            return _load_mmlu_subject(subj_name)
Ceng's avatar
Ceng committed
1122

1123
1124
1125
1126
1127
1128
1129
1130
    # Expand "all" to individual subjects for per-subject reporting
    if "all" in subject_list:
        if benchmark == "ceval":
            # Replace "all" with all individual ceval subjects
            subject_list = [s for s in subject_list if s != "all"] + ceval_subjects
        elif benchmark == "mmlu":
            # Replace "all" with all individual mmlu subjects
            subject_list = [s for s in subject_list if s != "all"] + mmlu_subjects
Ceng's avatar
Ceng committed
1131

1132
1133
    # Evaluate each subject separately
    all_results = []
Ceng's avatar
Ceng committed
1134

1135
    for subj in subject_list:
PanZezhong's avatar
PanZezhong committed
1136
        print(f"\n{'=' * 60}")
1137
        print(f"Evaluating subject: {subj}")
PanZezhong's avatar
PanZezhong committed
1138
        print(f"{'=' * 60}\n")
Ceng's avatar
Ceng committed
1139

1140
1141
1142
1143
1144
1145
1146
        try:
            samples, actual_subj_name = load_subject_samples(subj)
            print(f"Loaded {len(samples)} samples for subject: {actual_subj_name}")
            # Limit number of samples if specified
            if num_samples is not None and num_samples > 0:
                original_count = len(samples)
                samples = samples[:num_samples]
1147
1148
1149
                print(
                    f"Limited to {len(samples)} samples for validation (from {original_count} total)"
                )
1150

PanZezhong's avatar
PanZezhong committed
1151
1152
1153
            if len(samples) == 0:
                print(f"No samples found for subject: {actual_subj_name}")
                continue
1154
1155

            # Evaluate samples for this subject
1156
1157
1158
            result = evaluate_samples(
                model, samples, benchmark, max_new_tokens, actual_subj_name
            )
1159
            all_results.append(result)
1160
1161
1162
            print(
                f"\nSubject '{actual_subj_name}' completed: {result['correct']}/{result['total']} = {result['accuracy']:.2%}"
            )
Ceng's avatar
Ceng committed
1163

1164
1165
1166
        except Exception as e:
            print(f"Error evaluating subject '{subj}': {e}")
            continue
Ceng's avatar
Ceng committed
1167
1168
1169

    model.destroy_model_instance()

1170
    # Calculate overall results
PanZezhong's avatar
PanZezhong committed
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
    print(f"\n{'=' * 60}")
    print("OVERALL RESULTS")
    print(f"{'=' * 60}")
    if len(all_results) == 0:
        print("No tests were run.")
        return
    elif len(all_results) > 1:
        for r in all_results:
            print(
                f"Subject '{r['subject']}': {r['correct']}/{r['total']} = {r['accuracy']:.2%}"
            )
1182
1183
    overall_correct = sum(r["correct"] for r in all_results)
    overall_total = sum(r["total"] for r in all_results)
1184
    overall_accuracy = overall_correct / overall_total if overall_total > 0 else 0.0
Ceng's avatar
Ceng committed
1185

PanZezhong's avatar
PanZezhong committed
1186
    print(f"{'=' * 60}")
Ceng's avatar
Ceng committed
1187
    if benchmark == "ceval":
1188
1189
1190
        print(
            f"Overall 成绩: {overall_correct}/{overall_total} = {overall_accuracy:.2%}"
        )
Ceng's avatar
Ceng committed
1191
    else:
1192
1193
1194
1195
1196
1197
        print(
            f"Overall Accuracy: {overall_correct}/{overall_total} = {overall_accuracy:.2%}"
        )

    print(f"Total Latency: {TOTAL_TIME} seconds")
    print(f"Total Tokens Processed: {TOTAL_TOKENS} tokens")
PanZezhong's avatar
PanZezhong committed
1198
    print(f"Overall Throughput: {TOTAL_TOKENS / TOTAL_TIME:.2f} tokens/s")
1199
1200
1201
1202

    # Write CSV if output path is specified
    if output_csv:
        print(f"\nWriting results to CSV: {output_csv}")
1203
        with open(output_csv, "w", newline="", encoding="utf-8") as csvfile:
1204
            writer = csv.writer(csvfile)
1205
            writer.writerow(["Subject", "Correct", "Total", "Accuracy"])
1206
            for result in all_results:
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
                writer.writerow(
                    [
                        result["subject"],
                        result["correct"],
                        result["total"],
                        f"{result['accuracy']:.4f}",
                    ]
                )
            writer.writerow(
                ["Overall", overall_correct, overall_total, f"{overall_accuracy:.4f}"]
            )
1218
        print(f"CSV file written successfully: {output_csv}")
Ceng's avatar
Ceng committed
1219
1220
1221
1222


if __name__ == "__main__":
    test()