| import torch |
| from transformers import AutoModelForCausalLM, AutoTokenizer |
| import math |
|
|
| |
| |
| model_name = "Qwen/Qwen2.5-1.5B-Instruct" |
| device = "cuda" if torch.cuda.is_available() else "cpu" |
|
|
| print(f"Loading {model_name} on {device}...") |
| try: |
| tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True) |
| model = AutoModelForCausalLM.from_pretrained(model_name, device_map=device, trust_remote_code=True) |
| model.eval() |
| except Exception as e: |
| print(f"Error loading model: {e}") |
| exit() |
|
|
| def calculate_perplexity(text): |
| """ |
| 计算给定文本字符串的困惑度 (PPL) |
| """ |
| |
| encodings = tokenizer(text, return_tensors="pt") |
| input_ids = encodings.input_ids.to(device) |
|
|
| |
| |
| with torch.no_grad(): |
| outputs = model(input_ids, labels=input_ids) |
| loss = outputs.loss |
|
|
| |
| ppl = torch.exp(loss).item() |
| return ppl |
|
|
| |
| |
| |
| def run_2048_test(): |
| |
| |
| state_2048 = ( |
| "Turn 15:" |
| "#2 #4 #8 #2 \n . " |
| " #16 #64 #32 #512 \n " |
| ". #0 #2 #0 #256. . #0 #128 #0 #4 " |
| ) |
| "\nCurrent 2048 Grid:\nRow 1: [2, 4, 8, 2]\nRow 2: [16, 64, 32, 512]\nRow 3: [0, 2, 0, 256]\nRow 4: [0, 128, 0 4]\n" |
| |
| baseline_2048 = 12 |
| |
| ppl = calculate_perplexity(state_2048) |
| |
| print("-" * 30) |
| print("TASK: 2048 Game") |
| print(f"Input State:\n{state_2048}") |
| print(f"\nRandom Guess Baseline (#States): ~{baseline_2048}") |
| print(f"Model Perplexity (PPL): {ppl:.2f}") |
| |
| if ppl > baseline_2048: |
| print(">> 结论: OOD 环境 (模型看不懂这个数字矩阵)") |
| else: |
| print(">> 结论: In-Domain 环境 (模型对这种排列很熟悉)") |
|
|
| |
| |
| |
| def run_cube_test(): |
| |
| |
| |
| state_cube = ( |
| "Cube State:\n" |
| " U R\n" |
| " F U\n" |
| "L D F R B U\n" |
| "L B R D F L\n" |
| " D B\n" |
| " R B" |
| ) |
| |
| |
| baseline_cube = 6 |
| |
| ppl = calculate_perplexity(state_cube) |
| |
| print("-" * 30) |
| print("TASK: 2x2 Rubik's Cube") |
| print(f"Input State:\n{state_cube}") |
| print(f"\nRandom Guess Baseline (#States): {baseline_cube}") |
| print(f"Model Perplexity (PPL): {ppl:.2f}") |
| |
| if ppl > baseline_cube * 2: |
| print(">> 结论: OOD 环境 (模型难以解析空间展开图)") |
| else: |
| print(">> 结论: In-Domain 环境") |
|
|
| |
| |
| |
| if __name__ == "__main__": |
| print("Starting PPL Calculation based on paper methodology[cite: 174]...") |
| run_2048_test() |
| run_cube_test() |