""" MADLAD400-3B-MT: FP16 + Flash Attention 2 精度最優先・高速化スクリプト 必要なパッケージ: pip install transformers torch accelerate sentencepiece pip install flash-attn --no-build-isolation # Flash Attention 2(要CUDA) 動作確認環境: RTX 4070 Ti (12GB VRAM), Python 3.10+, CUDA 11.8+ """ import time import torch from transformers import AutoModelForSeq2SeqLM, AutoTokenizer MODEL_ID = "google/madlad400-3b-mt" # ───────────────────────────────────────── # 1. モデル・トークナイザーのロード # ───────────────────────────────────────── print("Loading tokenizer...") tokenizer = AutoTokenizer.from_pretrained(MODEL_ID) print("Loading model (FP16 + Flash Attention 2)...") model = AutoModelForSeq2SeqLM.from_pretrained( MODEL_ID, torch_dtype=torch.float16, # FP16で読み込み(VRAM約6GB) device_map="auto", # GPU自動割り当て attn_implementation="flash_attention_2", # Flash Attention 2を有効化 ) model.eval() print(f"Device: {next(model.parameters()).device}") print(f"Dtype: {next(model.parameters()).dtype}") # ───────────────────────────────────────── # 2. 翻訳関数 # ───────────────────────────────────────── def translate(text: str, target_lang: str = "ja", max_new_tokens: int = 256) -> str: """ target_lang: ISO 639-1コード 例: "ja"=日本語, "en"=英語, "zh"=中国語, "ko"=韓国語, "fr"=フランス語 """ # MADLAD400はプレフィックスで言語を指定する input_text = f"<2{target_lang}> {text}" inputs = tokenizer(input_text, return_tensors="pt").to(model.device) with torch.no_grad(): outputs = model.generate( **inputs, max_new_tokens=max_new_tokens, num_beams=4, # ビームサーチ(精度重視) early_stopping=True, ) return tokenizer.decode(outputs[0], skip_special_tokens=True) # ───────────────────────────────────────── # 3. ベンチマーク(速度・精度確認) # ───────────────────────────────────────── test_cases = [ ("Hello, how are you?", "ja"), ("The weather is beautiful today.", "ja"), ("Machine learning is transforming industries.", "ja"), ("こんにちは、元気ですか?", "en"), ] print("\n" + "="*60) print("FP16 + Flash Attention 2 ベンチマーク") print("="*60) total_time = 0.0 for src, tgt in test_cases: start = time.perf_counter() result = translate(src, target_lang=tgt) elapsed = time.perf_counter() - start total_time += elapsed print(f"\n[{tgt}] {src}") print(f" → {result}") print(f" ⏱ {elapsed:.3f}s") print(f"\n平均翻訳時間: {total_time / len(test_cases):.3f}s") # ───────────────────────────────────────── # 4. VRAMの使用量確認 # ───────────────────────────────────────── if torch.cuda.is_available(): allocated = torch.cuda.memory_allocated() / 1e9 reserved = torch.cuda.memory_reserved() / 1e9 print(f"\nVRAM使用量: {allocated:.2f} GB allocated / {reserved:.2f} GB reserved")