| 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
|
|
|
|
|
| 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()
|
|
|
|
|
| task_id = None
|
| task_offset = 0
|
|
|
| if not no_task_tag:
|
|
|
| if len(parts) > 0 and parts[0] in ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H']:
|
| task_id = parts[0]
|
| task_offset = 1
|
| else:
|
|
|
| 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
|
|
|
|
|
| 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.')
|
|
|
| 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
|
|
|
| path_type_tag = args.path_type
|
| tasks_tag = f"{tasks_tag}_{path_type_tag}"
|
|
|
| if args.no_task_tag:
|
| tasks_tag = f"{tasks_tag}_NT"
|
|
|
| if args.model == 'transformer-nextlat':
|
| tasks_tag = f"{tasks_tag}_NL"
|
|
|
| if args.PostGRU:
|
| tasks_tag = f"{tasks_tag}_PGR"
|
|
|
| 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]
|
|
|
|
|
|
|
| partial_suffix = '_partial' if args.partial else ''
|
|
|
| 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'),
|
|
|
| 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):
|
|
|
| os.makedirs(out_dir, exist_ok=True)
|
|
|
|
|
| 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
|
|
|
|
|
|
|
| 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,
|
| ]
|
|
|
|
|
| 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}%)",
|
| ])
|
|
|
|
|
| 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("\n" + output_text + "\n")
|
|
|
|
|
| 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.") |