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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
```
|
| 2 |
+
import re
|
| 3 |
+
import torch
|
| 4 |
+
import pandas as pd
|
| 5 |
+
from tqdm import tqdm
|
| 6 |
+
from collections import defaultdict
|
| 7 |
+
from datasets import load_dataset
|
| 8 |
+
from transformers import AutoModelForCausalLM, PreTrainedTokenizerFast
|
| 9 |
+
|
| 10 |
+
# --- Configuration ---
|
| 11 |
+
MODEL_ID = "THIS REPO"
|
| 12 |
+
DATASET_ID = "kreasof-ai/ECA-Zero"
|
| 13 |
+
BATCH_SIZE = 64
|
| 14 |
+
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
|
| 15 |
+
|
| 16 |
+
# From the dataset generation script
|
| 17 |
+
WOLFRAM_CLASSES_MAP = {
|
| 18 |
+
1: [0, 8, 32, 40, 128, 136, 160, 168],
|
| 19 |
+
2: [1, 19, 23, 29, 37, 50, 108, 178],
|
| 20 |
+
3: [30, 45, 60, 90, 105, 126, 150],
|
| 21 |
+
4: [54, 106, 110, 124, 137, 147, 193]
|
| 22 |
+
}
|
| 23 |
+
|
| 24 |
+
# Invert for fast lookup: Rule -> Class
|
| 25 |
+
RULE_TO_CLASS = {}
|
| 26 |
+
for cls, rules in WOLFRAM_CLASSES_MAP.items():
|
| 27 |
+
for r in rules:
|
| 28 |
+
RULE_TO_CLASS[r] = cls
|
| 29 |
+
|
| 30 |
+
class ECAVerifier:
|
| 31 |
+
def __init__(self):
|
| 32 |
+
self.re_rule = re.compile(r"Rule: (\d+)")
|
| 33 |
+
self.re_start = re.compile(r"Start: ([01]+)")
|
| 34 |
+
self.re_end = re.compile(r"End: ([01]+)")
|
| 35 |
+
self.re_steps = re.compile(r"Steps: (\d+)")
|
| 36 |
+
self.re_hint_class = re.compile(r"Hint: Class (\d)")
|
| 37 |
+
self.re_tt = re.compile(r"([01]{3})->([01])")
|
| 38 |
+
|
| 39 |
+
def get_wolfram_class(self, prompt):
|
| 40 |
+
# 1. Check for explicit Hint (Induction tasks)
|
| 41 |
+
m = self.re_hint_class.search(prompt)
|
| 42 |
+
if m:
|
| 43 |
+
return int(m.group(1))
|
| 44 |
+
|
| 45 |
+
# 2. Check for Rule ID (Deduction/Abduction) and look up
|
| 46 |
+
m = self.re_rule.search(prompt)
|
| 47 |
+
if m:
|
| 48 |
+
rule = int(m.group(1))
|
| 49 |
+
return RULE_TO_CLASS.get(rule, 0) # 0 = Unknown/Other
|
| 50 |
+
|
| 51 |
+
return 0
|
| 52 |
+
|
| 53 |
+
def get_next_state(self, state, rule):
|
| 54 |
+
next_state = []
|
| 55 |
+
L = len(state)
|
| 56 |
+
for i in range(L):
|
| 57 |
+
l, c, r = state[(i - 1) % L], state[i], state[(i + 1) % L]
|
| 58 |
+
pattern = (l << 2) | (c << 1) | r
|
| 59 |
+
bit = 1 if (rule & (1 << pattern)) else 0
|
| 60 |
+
next_state.append(bit)
|
| 61 |
+
return next_state
|
| 62 |
+
|
| 63 |
+
def simulate(self, start_state, rule, steps):
|
| 64 |
+
current = list(start_state)
|
| 65 |
+
for _ in range(steps):
|
| 66 |
+
current = self.get_next_state(current, rule)
|
| 67 |
+
return current
|
| 68 |
+
|
| 69 |
+
def parse_rule_string(self, text):
|
| 70 |
+
matches = self.re_tt.findall(text)
|
| 71 |
+
if not matches: return None
|
| 72 |
+
rule = 0
|
| 73 |
+
for pat, res in matches:
|
| 74 |
+
if res == '1': rule |= (1 << int(pat, 2))
|
| 75 |
+
return rule
|
| 76 |
+
|
| 77 |
+
def verify(self, task_type, prompt, model_output_str):
|
| 78 |
+
try:
|
| 79 |
+
steps = int(self.re_steps.search(prompt).group(1))
|
| 80 |
+
start_match = self.re_start.search(prompt)
|
| 81 |
+
start_state = [int(x) for x in start_match.group(1)] if start_match else None
|
| 82 |
+
end_match = self.re_end.search(prompt)
|
| 83 |
+
end_state = [int(x) for x in end_match.group(1)] if end_match else None
|
| 84 |
+
rule_match = self.re_rule.search(prompt)
|
| 85 |
+
rule = int(rule_match.group(1)) if rule_match else None
|
| 86 |
+
except AttributeError:
|
| 87 |
+
return False
|
| 88 |
+
|
| 89 |
+
answer = model_output_str.strip()
|
| 90 |
+
try:
|
| 91 |
+
if task_type == 'deduction':
|
| 92 |
+
pred_state = [int(x) for x in answer if x in '01']
|
| 93 |
+
if not pred_state: return False
|
| 94 |
+
expected = self.simulate(start_state, rule, steps)
|
| 95 |
+
return pred_state == expected
|
| 96 |
+
|
| 97 |
+
elif task_type == 'induction':
|
| 98 |
+
pred_rule = self.parse_rule_string(answer)
|
| 99 |
+
if pred_rule is None: return False
|
| 100 |
+
sim_end = self.simulate(start_state, pred_rule, steps)
|
| 101 |
+
return sim_end == end_state
|
| 102 |
+
|
| 103 |
+
elif task_type == 'abduction':
|
| 104 |
+
pred_start = [int(x) for x in answer if x in '01']
|
| 105 |
+
if not pred_start or len(pred_start) != len(end_state): return False
|
| 106 |
+
sim_end = self.simulate(pred_start, rule, steps)
|
| 107 |
+
return sim_end == end_state
|
| 108 |
+
except Exception:
|
| 109 |
+
return False
|
| 110 |
+
return False
|
| 111 |
+
|
| 112 |
+
def main():
|
| 113 |
+
print(f"Loading tokenizer from {MODEL_ID}...")
|
| 114 |
+
try:
|
| 115 |
+
tokenizer = PreTrainedTokenizerFast.from_pretrained(MODEL_ID)
|
| 116 |
+
except:
|
| 117 |
+
from transformers import AutoTokenizer
|
| 118 |
+
tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)
|
| 119 |
+
|
| 120 |
+
if tokenizer.pad_token is None:
|
| 121 |
+
tokenizer.pad_token = tokenizer.eos_token
|
| 122 |
+
|
| 123 |
+
print(f"Loading model from {MODEL_ID}...")
|
| 124 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 125 |
+
MODEL_ID,
|
| 126 |
+
torch_dtype=torch.bfloat16,
|
| 127 |
+
device_map=DEVICE,
|
| 128 |
+
attn_implementation="flash_attention_2"
|
| 129 |
+
)
|
| 130 |
+
model.eval()
|
| 131 |
+
|
| 132 |
+
print("Loading Test Set...")
|
| 133 |
+
dataset = load_dataset(DATASET_ID, split="test")
|
| 134 |
+
verifier = ECAVerifier()
|
| 135 |
+
|
| 136 |
+
# Storage: results[task][class_id] = [True, False, ...]
|
| 137 |
+
results = defaultdict(lambda: defaultdict(list))
|
| 138 |
+
|
| 139 |
+
print("Starting Stratified Evaluation...")
|
| 140 |
+
|
| 141 |
+
for i in tqdm(range(0, len(dataset), BATCH_SIZE)):
|
| 142 |
+
batch = dataset[i : i + BATCH_SIZE]
|
| 143 |
+
tasks = batch['task']
|
| 144 |
+
inputs = batch['input']
|
| 145 |
+
|
| 146 |
+
prompts = [f"{tokenizer.bos_token}{inp}\n<think>\n" for inp in inputs]
|
| 147 |
+
|
| 148 |
+
# FIX: Added return_token_type_ids=False
|
| 149 |
+
encodings = tokenizer(
|
| 150 |
+
prompts,
|
| 151 |
+
return_tensors="pt",
|
| 152 |
+
padding=True,
|
| 153 |
+
truncation=True,
|
| 154 |
+
max_length=2048,
|
| 155 |
+
return_token_type_ids=False
|
| 156 |
+
).to(DEVICE)
|
| 157 |
+
|
| 158 |
+
with torch.no_grad():
|
| 159 |
+
generated_ids = model.generate(
|
| 160 |
+
**encodings,
|
| 161 |
+
max_new_tokens=2048,
|
| 162 |
+
do_sample=False,
|
| 163 |
+
pad_token_id=tokenizer.pad_token_id,
|
| 164 |
+
eos_token_id=tokenizer.eos_token_id
|
| 165 |
+
)
|
| 166 |
+
|
| 167 |
+
decoded_outputs = tokenizer.batch_decode(generated_ids, skip_special_tokens=False)
|
| 168 |
+
|
| 169 |
+
for j, raw_output in enumerate(decoded_outputs):
|
| 170 |
+
if "</think>" in raw_output:
|
| 171 |
+
final_answer = raw_output.split("</think>")[-1].replace(tokenizer.eos_token, "").strip()
|
| 172 |
+
else:
|
| 173 |
+
final_answer = ""
|
| 174 |
+
|
| 175 |
+
# Determine Class
|
| 176 |
+
w_class = verifier.get_wolfram_class(inputs[j])
|
| 177 |
+
|
| 178 |
+
# Verify
|
| 179 |
+
is_correct = verifier.verify(tasks[j], inputs[j], final_answer)
|
| 180 |
+
|
| 181 |
+
# Store
|
| 182 |
+
results[tasks[j]][w_class].append(is_correct)
|
| 183 |
+
results[tasks[j]]["ALL"].append(is_correct)
|
| 184 |
+
|
| 185 |
+
# --- Print Report ---
|
| 186 |
+
print("\n" + "="*60)
|
| 187 |
+
print("STRATIFIED RESULTS (Accuracy by Wolfram Class)")
|
| 188 |
+
print("="*60)
|
| 189 |
+
|
| 190 |
+
# Define column headers
|
| 191 |
+
print(f"{'Task':<12} | {'Class 1':<10} | {'Class 2':<10} | {'Class 3':<10} | {'Class 4':<10} | {'OVERALL':<10}")
|
| 192 |
+
print("-" * 75)
|
| 193 |
+
|
| 194 |
+
for task in ["deduction", "induction", "abduction"]:
|
| 195 |
+
row_str = f"{task.capitalize():<12} | "
|
| 196 |
+
|
| 197 |
+
for c in [1, 2, 3, 4]:
|
| 198 |
+
outcomes = results[task][c]
|
| 199 |
+
if outcomes:
|
| 200 |
+
acc = sum(outcomes) / len(outcomes)
|
| 201 |
+
row_str += f"{acc:.1%} ({len(outcomes):<3}) | " # concise
|
| 202 |
+
else:
|
| 203 |
+
row_str += "N/A | "
|
| 204 |
+
|
| 205 |
+
# Overall
|
| 206 |
+
all_outcomes = results[task]["ALL"]
|
| 207 |
+
if all_outcomes:
|
| 208 |
+
total_acc = sum(all_outcomes) / len(all_outcomes)
|
| 209 |
+
row_str += f"{total_acc:.1%} ({len(all_outcomes)})"
|
| 210 |
+
|
| 211 |
+
print(row_str)
|
| 212 |
+
|
| 213 |
+
print("="*60)
|
| 214 |
+
print("Class Legend:")
|
| 215 |
+
print("1: Uniform (Trivial) | 2: Periodic (Easy) | 3: Chaotic (Hard) | 4: Complex (Hardest)")
|
| 216 |
+
|
| 217 |
+
if __name__ == "__main__":
|
| 218 |
+
main()
|
| 219 |
+
```
|
| 220 |
+
|
| 221 |
+
```
|
| 222 |
+
============================================================
|
| 223 |
+
STRATIFIED RESULTS (Accuracy by Wolfram Class)
|
| 224 |
+
============================================================
|
| 225 |
+
Task | Class 1 | Class 2 | Class 3 | Class 4 | OVERALL
|
| 226 |
+
---------------------------------------------------------------------------
|
| 227 |
+
Deduction | 31.0% (113) | 27.4% (226) | 35.9% (412) | 27.6% (410) | 30.8% (1161)
|
| 228 |
+
Induction | 30.1% (113) | 54.6% (227) | 60.9% (414) | 49.1% (411) | 52.5% (1165)
|
| 229 |
+
Abduction | 14.9% (47 ) | 8.1% (185) | 12.4% (388) | 13.4% (387) | 12.1% (1007)
|
| 230 |
+
============================================================
|
| 231 |
+
Class Legend:
|
| 232 |
+
1: Uniform (Trivial) | 2: Periodic (Easy) | 3: Chaotic (Hard) | 4: Complex (Hardest)
|
| 233 |
+
```
|