File size: 20,343 Bytes
34e468d | 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 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 | import os
import argparse
import math
from cli_utils import parse_count, format_count
def analyze_maze_predictions(file_path, multitasks=False, no_task_tag=False):
"""
Analyze maze predictions from test output file.
Args:
file_path: Path to the prediction file
multitasks: If True, separate analysis for Task A and Task B
no_task_tag: If True, data files do not contain task identifiers
Returns:
Dictionary with overall stats and per-task stats if multitasks=True
"""
total = 0
correct = 0
illegal_direction = 0
incorrect_target = 0
syntax_error = 0
overall_high_conf = 0
overall_low_conf = 0
# Per-task statistics
taskA_stats = {'total': 0, 'correct': 0, 'syntax_error': 0, 'illegal_direction': 0, 'incorrect_target': 0,
'high_conf_mistake': 0, 'low_conf_mistake': 0}
taskB_stats = {'total': 0, 'correct': 0, 'syntax_error': 0, 'incorrect_target_label': 0, 'incorrect_neighbor_label': 0,
'high_conf_mistake': 0, 'low_conf_mistake': 0}
taskC_stats = {'total': 0, 'correct': 0, 'syntax_error': 0, 'illegal_direction': 0, 'incorrect_target': 0,
'incorrect_label': 0, 'high_conf_mistake': 0, 'low_conf_mistake': 0}
taskD_stats = {'total': 0, 'correct': 0, 'syntax_error': 0, 'illegal_direction': 0, 'incorrect_target': 0,
'high_conf_mistake': 0, 'low_conf_mistake': 0}
taskE_stats = {'total': 0, 'correct': 0, 'syntax_error': 0, 'illegal_direction': 0, 'incorrect_target': 0,
'incorrect_label': 0, 'high_conf_mistake': 0, 'low_conf_mistake': 0}
taskF_stats = {'total': 0, 'correct': 0, 'syntax_error': 0, 'incorrect_target_label': 0,
'high_conf_mistake': 0, 'low_conf_mistake': 0}
taskG_stats = {'total': 0, 'correct': 0, 'syntax_error': 0, 'illegal_direction': 0, 'incorrect_target': 0,
'high_conf_mistake': 0, 'low_conf_mistake': 0}
taskH_stats = {'total': 0, 'correct': 0, 'syntax_error': 0, 'illegal_direction': 0, 'incorrect_target': 0,
'high_conf_mistake': 0, 'low_conf_mistake': 0}
task_stats_map = {
'A': taskA_stats, 'B': taskB_stats, 'C': taskC_stats,
'D': taskD_stats, 'E': taskE_stats, 'F': taskF_stats, 'G': taskG_stats,
'H': taskH_stats
}
with open(file_path, 'r') as f:
for line in f:
line = line.strip()
if not line:
continue
total += 1
parts = line.split()
# Detect task ID (A, B, C, D, E, F, G)
task_id = None
task_offset = 0
if not no_task_tag:
# Original logic with task tags
if len(parts) > 0 and parts[0] in ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H']:
task_id = parts[0]
task_offset = 1
else:
# In no_task_tag mode, read task type from parentheses in the line
if line.startswith('(') and ')' in line:
end_paren = line.find(')')
task_id_str = line[1:end_paren]
if task_id_str in ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H']:
task_id = task_id_str
line_without_label = line[end_paren+1:].strip()
parts = line_without_label.split()
task_offset = 0
if task_id is None:
if ':' in line:
colon_idx = line.index(':')
prompt_part = line[:colon_idx].strip()
prompt_tokens = prompt_part.split()
if len(prompt_tokens) >= 2:
answer_part = line[colon_idx + 1:].strip()
answer_tokens = answer_part.split()
if len(answer_tokens) >= 2 and answer_tokens[1] in ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']:
task_id = 'E'
elif any(tok in ['L', 'R', 'F', 'T'] for tok in answer_tokens):
task_id = 'C'
elif len(prompt_tokens) == 2 and prompt_tokens[0].isdigit() and prompt_tokens[1].isdigit():
task_id = 'A'
elif prompt_tokens[0].isdigit() and prompt_tokens[1] in ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']:
task_id = 'D'
elif prompt_tokens[0] in ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']:
task_id = 'F'
elif len(prompt_tokens) == 4 and all(token.isdigit() for token in prompt_tokens):
task_id = 'G'
elif prompt_tokens[0].isdigit():
if len(answer_tokens) == 5:
task_id = 'B'
if multitasks and task_id in task_stats_map:
task_stats_map[task_id]['total'] += 1
# Confidence tracking
is_high = 'HIGH-CONF' in line
is_low = 'LOW-CONF' in line
if is_high:
overall_high_conf += 1
if task_id in task_stats_map:
task_stats_map[task_id]['high_conf_mistake'] += 1
elif is_low:
overall_low_conf += 1
if task_id in task_stats_map:
task_stats_map[task_id]['low_conf_mistake'] += 1
if 'is illegal' in line or 'exceeds feasible count' in line or 'invalid index' in line or 'no feasible edges' in line:
illegal_direction += 1
if task_id in task_stats_map and 'illegal_direction' in task_stats_map[task_id]:
task_stats_map[task_id]['illegal_direction'] += 1
continue
if 'syntax error' in line:
syntax_error += 1
if task_id in task_stats_map:
task_stats_map[task_id]['syntax_error'] += 1
continue
if 'incorrect neighbor label' in line:
if task_id == 'B':
taskB_stats['incorrect_neighbor_label'] += 1
incorrect_target += 1
continue
if 'incorrect target node label' in line:
if task_id == 'B':
taskB_stats['incorrect_target_label'] += 1
incorrect_target += 1
continue
if 'incorrect target label' in line:
if task_id == 'F':
taskF_stats['incorrect_target_label'] += 1
incorrect_target += 1
continue
if 'incorrect label' in line:
if task_id == 'C':
taskC_stats['incorrect_label'] += 1
elif task_id == 'E':
taskE_stats['incorrect_label'] += 1
incorrect_target += 1
continue
if 'incorrect target node' in line:
incorrect_target += 1
if task_id in task_stats_map and 'incorrect_target' in task_stats_map[task_id]:
task_stats_map[task_id]['incorrect_target'] += 1
continue
correct += 1
if task_id in task_stats_map:
task_stats_map[task_id]['correct'] += 1
stats = {
'total': total,
'correct': correct,
'syntax_error': syntax_error,
'illegal_direction': illegal_direction,
'incorrect_target': incorrect_target,
'high_conf_mistake': overall_high_conf,
'low_conf_mistake': overall_low_conf
}
if multitasks:
stats['taskA'] = taskA_stats
stats['taskB'] = taskB_stats
stats['taskC'] = taskC_stats
stats['taskD'] = taskD_stats
stats['taskE'] = taskE_stats
stats['taskF'] = taskF_stats
stats['taskG'] = taskG_stats
stats['taskH'] = taskH_stats
return stats
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='Analyze prediction results from test_maze.py')
parser.add_argument('--ckpt_iter', type=int, default=10000, help='Checkpoint iteration')
parser.add_argument('--model', type=str, default='transformer', choices=['transformer', 'transformer-rope', 'transformer-nextlat', 'mamba', 'mamba2', 'gated-deltanet', 'gru'],
help='Model architecture; selects the out/<model>/ directory')
parser.add_argument('--config', type=str, default='1_1_120', help='Model config')
parser.add_argument('--dataset', type=str, default='maze', help='Dataset name')
parser.add_argument('--num_nodes', type=int, default=100, help='Number of nodes')
parser.add_argument('--num_of_paths', type=int, default=20, help='Number of paths')
parser.add_argument('--multitasks', action=argparse.BooleanOptionalAction, default=True,
help='Use multitask data (default: True)')
parser.add_argument('--num_train_dataset', type=parse_count, default=50000,
help='Number of multitask training entries (supports K/M/B, default: 50000)')
parser.add_argument('--num_test_dataset', type=parse_count, default=10000,
help='Number of multitask test entries (supports K/M/B, default: 10000)')
parser.add_argument('--tasks', type=str, default='A1',
help='Task specification (e.g., A1, A1B1, A3B2, A1D1F1). Default: A1')
parser.add_argument('--CL', action=argparse.BooleanOptionalAction, default=False,
help='Task C turn-label mode (default: False)')
parser.add_argument('--batch_size', type=int, default=100,
help='Batch size used during prediction (matches test_maze.py)')
parser.add_argument('--num_iters', type=int, default=10,
help='Number of batches used during prediction (matches test_maze.py)')
parser.add_argument('--path_type', type=str, default='RWa', choices=['RWc', 'RWa', 'RWs'],
help='Path generation type: RWc (random walk with cycles), RWa (random walk acyclic, default), RWs (single source random walk).')
parser.add_argument('--partial', action='store_true', default=False,
help='Analyze partial prefix test results (default: False)')
parser.add_argument('--temperature', type=float, default=1.0,
help='Sampling temperature used during prediction (default: 1.0). Affects output filenames.')
# Add --no_task_tag argument
parser.add_argument('--no_task_tag', action='store_true', default=False,
help='Data files do not contain task identifiers (A, B, C, etc.). This should match the setting used during data generation and testing.')
parser.add_argument('--PostGRU', action='store_true', default=False,
help='Analyze PostGRU predictions (adds _PGR suffix to filenames)')
parser.add_argument('--NLS', action='store_true', default=False,
help='Analyze NLS predictions (adds _NLS suffix to filenames)')
args = parser.parse_args()
tasks_str = args.tasks
tasks_tag = f"{tasks_str}_CL" if args.CL else tasks_str
# Add path type tag for filenames (RWc = cyclic, RWa = acyclic, RWs = single source)
path_type_tag = args.path_type
tasks_tag = f"{tasks_tag}_{path_type_tag}"
# Add _NT_ tag to tasks_tag when no_task_tag is enabled
if args.no_task_tag:
tasks_tag = f"{tasks_tag}_NT"
# Add _NL tag for transformer-nextlat
if args.model == 'transformer-nextlat':
tasks_tag = f"{tasks_tag}_NL"
# Add _PGR tag when PostGRU is enabled
if args.PostGRU:
tasks_tag = f"{tasks_tag}_PGR"
# Add _NLS tag when NLS is enabled
if args.NLS:
tasks_tag = f"{tasks_tag}_NLS"
test_dataset_label = format_count(args.num_test_dataset)
run_test_label = args.batch_size * args.num_iters
nt_suffix = '_NT' if args.no_task_tag else ''
out_dir = f'out/{args.model.replace("-", "_")}/{args.dataset}_{args.config}_{args.num_nodes}{nt_suffix}/'
def pick_first_existing(paths):
for path in paths:
if os.path.exists(path):
return path
return paths[0]
# Add _partial suffix if partial mode is enabled
partial_suffix = '_partial' if args.partial else ''
# Add temperature suffix when temperature is not default (1.0)
temp_suffix = f'_t{args.temperature}' if args.temperature != 1.0 else ''
pred_candidates = (
[
os.path.join(out_dir, f'pred_test_{tasks_tag}_{args.ckpt_iter}_{run_test_label}{temp_suffix}{partial_suffix}.txt'),
# primary (matches test_maze.py)
os.path.join(out_dir, f'pred_test_{tasks_tag}_{args.ckpt_iter}_{test_dataset_label}{temp_suffix}{partial_suffix}.txt'),
os.path.join(out_dir,
f'pred_test_{tasks_tag}_{args.ckpt_iter}_{args.num_test_dataset}{temp_suffix}{partial_suffix}.txt'),
os.path.join(out_dir, f'pred_test_{tasks_str}_{args.ckpt_iter}_{run_test_label}{temp_suffix}{partial_suffix}.txt'),
os.path.join(out_dir, f'pred_test_{tasks_str}_{args.ckpt_iter}_{test_dataset_label}{temp_suffix}{partial_suffix}.txt'),
os.path.join(out_dir,
f'pred_test_{tasks_str}_{args.ckpt_iter}_{args.num_test_dataset}{temp_suffix}{partial_suffix}.txt'),
]
if args.multitasks else [
os.path.join(out_dir, f'pred_test_{args.ckpt_iter}_{args.num_of_paths}{temp_suffix}{partial_suffix}.txt')]
)
file_path = pick_first_existing(pred_candidates)
if os.path.exists(file_path):
# Ensure output directory exists
os.makedirs(out_dir, exist_ok=True)
# Analyze predictions
stats = analyze_maze_predictions(file_path, multitasks=args.multitasks, no_task_tag=args.no_task_tag)
def pct_and_se(count, total):
if total <= 0:
return 0.0, 0.0
p = count / total
se = math.sqrt(p * (1 - p) / total) * 100
return p * 100, se
# Format output
separator = "=" * 70
output_lines = [
separator,
"Accuracy Test Results",
separator,
f"Task tag: {'DISABLED' if args.no_task_tag else 'ENABLED'}",
f"Config: {args.config}",
f"Checkpoint iteration: {args.ckpt_iter}",
f"Number of nodes: {args.num_nodes}",
f"Task configuration: {args.tasks}" if args.multitasks else "",
separator,
]
# Overall statistics
total_preds = stats['total'] if stats['total'] > 0 else 1
corr_pct, corr_se = pct_and_se(stats['correct'], total_preds)
syn_pct, _ = pct_and_se(stats['syntax_error'], total_preds)
ill_pct, _ = pct_and_se(stats['illegal_direction'], total_preds)
tgt_pct, _ = pct_and_se(stats['incorrect_target'], total_preds)
high_pct, _ = pct_and_se(stats['high_conf_mistake'], total_preds)
low_pct, _ = pct_and_se(stats['low_conf_mistake'], total_preds)
output_lines.extend([
"OVERALL STATISTICS:",
f" Total predictions: {stats['total']}",
f" Correct (accuracy with standard error): {stats['correct']} ({corr_pct:.2f}% ± {corr_se:.2f}%)",
f" Syntax error: {stats['syntax_error']} ({syn_pct:.2f}%)",
f" Illegal direction: {stats['illegal_direction']} ({ill_pct:.2f}%)",
f" Incorrect target: {stats['incorrect_target']} ({tgt_pct:.2f}%)",
f" - High confidence mistakes: {stats['high_conf_mistake']} ({high_pct:.2f}%)",
f" - Low confidence mistakes: {stats['low_conf_mistake']} ({low_pct:.2f}%)",
])
# Per-task statistics if multitasks
if args.multitasks:
task_mapping = {
'taskA': ('A', 'Pathfinding'),
'taskB': ('B', 'Target Identification'),
'taskC': ('C', 'Turn-based pathfinding'),
'taskD': ('D', 'Pathfinding to label'),
'taskE': ('E', 'Pathfinding with labels'),
'taskF': ('F', 'Target label identification'),
'taskG': ('G', 'Reachability choice'),
'taskH': ('H', 'Relative clockwise-index path')
}
for key, (tid, name) in task_mapping.items():
if key in stats and stats[key]['total'] > 0:
s = stats[key]
t_total = s['total']
t_corr, t_se = pct_and_se(s['correct'], t_total)
t_syn, _ = pct_and_se(s['syntax_error'], t_total)
t_high, _ = pct_and_se(s['high_conf_mistake'], t_total)
t_low, _ = pct_and_se(s['low_conf_mistake'], t_total)
output_lines.extend([
"",
separator,
f"TASK {tid} ({name}) STATISTICS:",
f" Total: {t_total}",
f" Correct (accuracy with standard error): {s['correct']} ({t_corr:.2f}% ± {t_se:.2f}%)",
f" Syntax error: {s['syntax_error']} ({t_syn:.2f}%)",
])
if 'illegal_direction' in s:
t_ill, _ = pct_and_se(s['illegal_direction'], t_total)
output_lines.append(f" Illegal direction: {s['illegal_direction']} ({t_ill:.2f}%)")
if tid == 'B':
t_lbl, _ = pct_and_se(s['incorrect_target_label'], t_total)
t_nbr, _ = pct_and_se(s['incorrect_neighbor_label'], t_total)
output_lines.append(
f" Incorrect target node label: {s['incorrect_target_label']} ({t_lbl:.2f}%)")
output_lines.append(
f" Incorrect neighbor label: {s['incorrect_neighbor_label']} ({t_nbr:.2f}%)")
elif tid == 'F':
t_lbl, _ = pct_and_se(s['incorrect_target_label'], t_total)
output_lines.append(f" Incorrect target label: {s['incorrect_target_label']} ({t_lbl:.2f}%)")
else:
if 'incorrect_target' in s:
t_tgt, _ = pct_and_se(s['incorrect_target'], t_total)
output_lines.append(f" Incorrect target: {s['incorrect_target']} ({t_tgt:.2f}%)")
if 'incorrect_label' in s:
t_lbl, _ = pct_and_se(s['incorrect_label'], t_total)
lbl_text = "Incorrect label (CL mode)" if tid == 'C' else "Incorrect label"
output_lines.append(f" {lbl_text}: {s['incorrect_label']} ({t_lbl:.2f}%)")
output_lines.extend([
f" - High confidence mistakes: {s['high_conf_mistake']} ({t_high:.2f}%)",
f" - Low confidence mistakes: {s['low_conf_mistake']} ({t_low:.2f}%)",
])
output_lines.append(separator)
output_text = "\n".join(output_lines)
# Print to console
print("\n" + output_text + "\n")
# Save to file
output_file = os.path.join(
out_dir,
f"accuracy_{tasks_tag}_{args.ckpt_iter}_{args.num_test_dataset}{temp_suffix}{partial_suffix}.txt" if args.multitasks else f"accuracy_{args.ckpt_iter}_{args.num_of_paths}{temp_suffix}{partial_suffix}.txt"
)
with open(output_file, 'w') as f:
f.write(output_text + "\n")
print(f"Results saved to {output_file}")
else:
print(f"File {file_path} not found.") |