Datasets:
Download benchmark_nextgen_quant.py from aoiandroid/minicpm5-1b-quantization-benchmark: direct link, hf CLI and curl.
- Browser
- Download file 14.2 kB
-
https://huggingface.co/datasets/aoiandroid/minicpm5-1b-quantization-benchmark/resolve/main/benchmark_nextgen_quant.py
- Command line
-
hf download hf://datasets/aoiandroid/minicpm5-1b-quantization-benchmark/benchmark_nextgen_quant.py
-
curl -L -o benchmark_nextgen_quant.py https://huggingface.co/datasets/aoiandroid/minicpm5-1b-quantization-benchmark/resolve/main/benchmark_nextgen_quant.py
14.2 kB
| import os | |
| import sys | |
| import time | |
| import json | |
| import gc | |
| import torch | |
| from transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer, QuantoConfig | |
| from threading import Thread | |
| # 同一のテストケースセット | |
| TEST_CASES = [ | |
| { | |
| "id": "chat_roleplay_butler", | |
| "category": "基礎対話・ロールプレイ", | |
| "name": "執事風ロールプレイ・口調維持", | |
| "system": "あなたは主人に仕える有能で少し皮肉屋な執事です。常に慇懃無礼で丁寧な敬語を使い、主人の健康を気遣いつつもチクリと小言を挟む口調を維持してください。", | |
| "user": "仕事でヘトヘトに疲れたよ……何か温かくて落ち着く飲み物を用意してくれないか?", | |
| "max_new_tokens": 256 | |
| }, | |
| { | |
| "id": "chat_casual_talk", | |
| "category": "基礎対話・自然さ", | |
| "name": "フランクな日常会話・相談", | |
| "system": "あなたは親しみやすい友人のAIアシスタントです。自然でフランクな日本語(タメ口)で親身に答えてください。", | |
| "user": "今度の週末、大阪の梅田か難波あたりで美味しいB級グルメを食べ歩きしたいんだけど、おすすめのコースある?", | |
| "max_new_tokens": 256 | |
| }, | |
| { | |
| "id": "json_extraction_strict", | |
| "category": "JSON構造化出力・制約遵守", | |
| "name": "注文内容の抽出と厳密JSON出力", | |
| "system": "あなたは情報抽出エンジンです。ユーザーの注文テキストから情報を抽出し、指定されたJSONフォーマットのみを出力してください。Markdown記号(```jsonなど)や挨拶、説明文は一切含めず、純粋なJSON文字列のみを出力してください。\n\nキー構成:\n{\n \"customer_name\": string,\n \"items\": [{\"name\": string, \"quantity\": int, \"options\": string}],\n \"total_estimated_budget\": int or null,\n \"special_requests\": string or null\n}", | |
| "user": "佐藤です。ホットコーヒーを2つ(砂糖ミルク付き)と、チーズケーキ1個をお願いします。あと持ち帰り用の袋をつけてほしいです。予算は1500円くらいで収まりますか?", | |
| "max_new_tokens": 256 | |
| }, | |
| { | |
| "id": "negative_constraint", | |
| "category": "制約遵守・ネガティブ制約", | |
| "name": "禁止ワード遵守と文字数制限", | |
| "system": "あなたは指示を厳密に守るアシスタントです。", | |
| "user": "日本の現在の首都について、120文字以内の日本語で簡潔に説明してください。ただし、制約として『東京』という単語を一度も使ってはいけません。", | |
| "max_new_tokens": 150 | |
| }, | |
| { | |
| "id": "summarization_japanese", | |
| "category": "日本語要約・長文読解", | |
| "name": "技術ニュース記事の3点要約", | |
| "system": "あなたは文章要約の専門家です。提示されたテキストの要点を、客観的かつ正確に3つの箇条書き(各50文字程度)で要約してください。", | |
| "user": "次の文章を読んで要約してください:\n\n人工知能(AI)技術の急速な発展に伴い、これまでクラウドの大規模データセンターで行われていた大規模言語モデル(LLM)の推論を、パーソナルコンピュータやスマートフォンなどのエッジデバイス上で直接実行する「オンデバイスAI」への移行が加速している。従来のクラウド推論では、高い推論能力を提供する一方で、サーバー通信によるレイテンシの増大、通信コストの発生、さらにユーザーのプライバシーデータが外部サーバーに送信されるというセキュリティ上の課題が存在していた。これに対しオンデバイス推論は、モデルの量子化技術(4bitや8bitへの圧縮)や蒸留技術、軽量なTransformerアーキテクチャの採用により、数億から数GB程度のメモリフットプリントで実用的なテキスト生成や対話が可能となっている。これにより、オフライン環境での高速なレスポンスや機密情報の完全ローカル処理が実現し、ゲームのリアルタイムNPC対話や組み込み機器の自律制御など、新しい応用分野が次々と切り拓かれている。", | |
| "max_new_tokens": 256 | |
| }, | |
| { | |
| "id": "context_qa_hallucination", | |
| "category": "文脈QA・ハルシネーション耐性", | |
| "name": "架空世界観の文脈に基づくQA", | |
| "system": "以下の【コンテキスト】に書かれている情報のみに基づいて質問に答えてください。コンテキストに記載がない情報については、勝手に推測せず必ず「提供された情報からは判断できません」と回答してください。", | |
| "user": "【コンテキスト】\nネオ・トウキョウ第7区には、会員制クラブ『エデン』が存在する。エデンの入会には紹介者の承認が必要であり、店内での通貨として電子トークン『エデンコイン』のみが使用可能である。営業時間は午後8時から午前4時までとなっている。客席は1階がラウンジ、2階がVIP個室に分かれている。\n\n【質問】\nエデンコインの日本円換算レートはいくらですか?また、エデンの会員権の月額会費はいくらですか?", | |
| "max_new_tokens": 200 | |
| }, | |
| { | |
| "id": "logic_reasoning_order", | |
| "category": "論理推論", | |
| "name": "背丈の順序推論", | |
| "system": "論理的・論証的に思考して回答してください。思考過程を簡潔に示してから、最終結論を明記してください。", | |
| "user": "以下の条件が与えられています:\n1. AさんはBさんより背が高い。\n2. CさんはAさんより背が高い。\n3. DさんはBさんより背が高いが、Aさんよりは低い。\n\n4人を背の高い順(1位〜4位)に並べてください。", | |
| "max_new_tokens": 200 | |
| }, | |
| { | |
| "id": "math_word_problem", | |
| "category": "算数推論・ステップ計算", | |
| "name": "連立方程式の文章題", | |
| "system": "論理的かつステップバイステップで計算して回答してください。", | |
| "user": "リンゴ3個とミカン5個を買ったところ、代金の合計は1100円でした。リンゴ1個の値段はミカン1個の値段よりも100円高いです。リンゴ1個とミカン1個の値段はそれぞれ何円ですか?計算の過程も示してください。", | |
| "max_new_tokens": 300 | |
| } | |
| ] | |
| def run_quanto_benchmark(model_name: str, quant_type: str, output_results: dict): | |
| mode_name = f"quanto_{quant_type}" | |
| print(f"\n[INFO] =========================================") | |
| print(f"[INFO] Starting Next-Gen Benchmark Mode: {mode_name}") | |
| print(f"[INFO] Quantization: {quant_type.upper()}") | |
| print(f"[INFO] Model: {model_name}") | |
| print(f"[INFO] =========================================") | |
| gc.collect() | |
| if torch.cuda.is_available(): | |
| torch.cuda.empty_cache() | |
| torch.cuda.reset_peak_memory_stats() | |
| initial_vram = torch.cuda.memory_allocated() / (1024 ** 2) | |
| else: | |
| initial_vram = 0.0 | |
| load_start = time.perf_counter() | |
| tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True) | |
| qconfig = QuantoConfig(weights=quant_type) | |
| model = AutoModelForCausalLM.from_pretrained( | |
| model_name, | |
| device_map="cuda", | |
| quantization_config=qconfig, | |
| dtype=torch.bfloat16, | |
| trust_remote_code=True | |
| ) | |
| load_time = time.perf_counter() - load_start | |
| model.eval() | |
| if torch.cuda.is_available(): | |
| torch.cuda.synchronize() | |
| loaded_vram = torch.cuda.memory_allocated() / (1024 ** 2) | |
| model_vram = loaded_vram - initial_vram | |
| else: | |
| model_vram = 0.0 | |
| print(f"[INFO] {mode_name} Loaded in {load_time:.2f}s | Model VRAM: {model_vram:.1f} MB") | |
| # ウォームアップ | |
| print(f"[INFO] Warming up...") | |
| warmup_messages = [{"role": "user", "content": "こんにちは。テストです。"}] | |
| warmup_prompt = tokenizer.apply_chat_template(warmup_messages, tokenize=False, add_generation_prompt=True) | |
| warmup_inputs = tokenizer(warmup_prompt, return_tensors="pt").to("cuda") | |
| warmup_inputs.pop("token_type_ids", None) | |
| with torch.no_grad(): | |
| _ = model.generate(**warmup_inputs, max_new_tokens=10) | |
| if torch.cuda.is_available(): | |
| torch.cuda.synchronize() | |
| print(f"[INFO] Warmup complete.") | |
| mode_results = { | |
| "mode": mode_name, | |
| "quant_type": quant_type, | |
| "load_time_sec": load_time, | |
| "model_vram_mb": model_vram, | |
| "cases": [] | |
| } | |
| for idx, case in enumerate(TEST_CASES, 1): | |
| print(f"\n[RUN] Case {idx}/{len(TEST_CASES)}: [{case['category']}] {case['name']}") | |
| messages = [] | |
| if case.get("system"): | |
| messages.append({"role": "system", "content": case["system"]}) | |
| messages.append({"role": "user", "content": case["user"]}) | |
| prompt_text = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True) | |
| inputs = tokenizer(prompt_text, return_tensors="pt").to("cuda") | |
| inputs.pop("token_type_ids", None) | |
| input_token_count = inputs["input_ids"].shape[1] | |
| streamer = TextIteratorStreamer(tokenizer, skip_prompt=True, skip_special_tokens=True) | |
| gen_kwargs = dict( | |
| **inputs, | |
| streamer=streamer, | |
| max_new_tokens=case["max_new_tokens"], | |
| do_sample=False, | |
| repetition_penalty=1.05 | |
| ) | |
| if torch.cuda.is_available(): | |
| torch.cuda.reset_peak_memory_stats() | |
| torch.cuda.synchronize() | |
| start_time = time.perf_counter() | |
| thread = Thread(target=model.generate, kwargs=gen_kwargs) | |
| thread.start() | |
| generated_text = "" | |
| first_token_time = None | |
| for new_text in streamer: | |
| if first_token_time is None and new_text: | |
| first_token_time = time.perf_counter() | |
| generated_text += new_text | |
| thread.join() | |
| if torch.cuda.is_available(): | |
| torch.cuda.synchronize() | |
| end_time = time.perf_counter() | |
| total_time = end_time - start_time | |
| ttft = (first_token_time - start_time) if first_token_time else total_time | |
| output_tokens = tokenizer(generated_text, add_special_tokens=False)["input_ids"] | |
| generated_token_count = len(output_tokens) | |
| overall_tps = generated_token_count / total_time if total_time > 0 else 0 | |
| decode_time = (end_time - first_token_time) if first_token_time else total_time | |
| decode_tps = (generated_token_count - 1) / decode_time if (decode_time > 0 and generated_token_count > 1) else overall_tps | |
| peak_vram = torch.cuda.max_memory_allocated() / (1024 ** 2) if torch.cuda.is_available() else 0.0 | |
| print(f" - Generated Tokens: {generated_token_count} tokens (Prompt: {input_token_count} tokens)") | |
| print(f" - TTFT: {ttft*1000:.1f} ms | Decode TPS: {decode_tps:.1f} tok/s | Overall TPS: {overall_tps:.1f} tok/s") | |
| print(f" - Peak VRAM: {peak_vram:.1f} MB") | |
| print(f" - Output preview:\n {generated_text[:120]}...\n") | |
| case_record = { | |
| "id": case["id"], | |
| "category": case["category"], | |
| "name": case["name"], | |
| "prompt_tokens": input_token_count, | |
| "generated_tokens": generated_token_count, | |
| "total_time_sec": total_time, | |
| "ttft_ms": ttft * 1000, | |
| "decode_tps": decode_tps, | |
| "overall_tps": overall_tps, | |
| "peak_vram_mb": peak_vram, | |
| "output_text": generated_text | |
| } | |
| mode_results["cases"].append(case_record) | |
| output_results[mode_name] = mode_results | |
| del model | |
| del tokenizer | |
| gc.collect() | |
| if torch.cuda.is_available(): | |
| torch.cuda.empty_cache() | |
| def main(): | |
| model_name = "openbmb/MiniCPM5-1B" | |
| output_dir = os.path.join(os.getcwd(), "benchmarks") | |
| os.makedirs(output_dir, exist_ok=True) | |
| output_file = os.path.join(output_dir, "results_nextgen_quant.json") | |
| # 既存の測定結果をロードして追加・統合 | |
| base_file = os.path.join(output_dir, "results_minicpm5_1b.json") | |
| if os.path.exists(base_file): | |
| with open(base_file, "r", encoding="utf-8") as f: | |
| all_results = json.load(f) | |
| else: | |
| all_results = { | |
| "timestamp": time.strftime("%Y-%m-%d %H:%M:%S"), | |
| "model_name": model_name, | |
| "gpu_name": torch.cuda.get_device_name(0) if torch.cuda.is_available() else "CPU", | |
| "pytorch_version": torch.__version__, | |
| "modes": {} | |
| } | |
| # 1. 次世代 FP8 量子化 (Float8 e4m3fn) | |
| try: | |
| run_quanto_benchmark(model_name, "float8", all_results["modes"]) | |
| except Exception as e: | |
| print(f"[ERROR] Failed in Quanto float8 benchmark: {e}", file=sys.stderr) | |
| import traceback | |
| traceback.print_exc() | |
| # 2. 次世代 INT4 量子化 (Quanto int4) | |
| try: | |
| run_quanto_benchmark(model_name, "int4", all_results["modes"]) | |
| except Exception as e: | |
| print(f"[ERROR] Failed in Quanto int4 benchmark: {e}", file=sys.stderr) | |
| import traceback | |
| traceback.print_exc() | |
| # 結果保存 (統合版および次世代専用版) | |
| with open(output_file, "w", encoding="utf-8") as f: | |
| json.dump(all_results, f, ensure_ascii=False, indent=2) | |
| with open(base_file, "w", encoding="utf-8") as f: | |
| json.dump(all_results, f, ensure_ascii=False, indent=2) | |
| print(f"\n[DONE] Next-Gen Quantization benchmark complete! Results saved to: {output_file}") | |
| if __name__ == "__main__": | |
| main() | |