File size: 3,533 Bytes
70a7f67
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
import math

# 1. 加载模型和分词器
# 注意:第一次运行会自动从 Hugging Face 下载模型,约需 3GB 显存或内存
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)

    # 计算 Loss (NLL)
    # labels=input_ids 会让模型自动计算 CrossEntropyLoss
    with torch.no_grad():
        outputs = model(input_ids, labels=input_ids)
        loss = outputs.loss

    # PPL = exp(Loss)
    ppl = torch.exp(loss).item()
    return ppl

# ==========================================
# 场景 1: 2048 游戏
# ==========================================
def run_2048_test():
    # 模拟一个 2048 的原始符号状态 (Raw Symbolic State)
    # 论文指出这种原始数字矩阵通常具有较高的 PPL
    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"
    # 2048 的随机基准:数字种类 (0, 2, 4, 8... 2048) 约为 12 种
    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 环境 (模型对这种排列很熟悉)")

# ==========================================
# 场景 2: 二阶魔方 (2x2 Rubik's Cube)
# ==========================================
def run_cube_test():
    # 模拟一个二阶魔方的展开图状态 (Raw Symbolic State)
    # U=Up, F=Front, R=Right, D=Down, L=Left, B=Back
    # 这里模拟一个打乱后的状态
    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"
    )
    
    # 魔方的随机基准:只有 6 种颜色
    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()