| import os
|
| from model.transformer import GPTConfig, GPT
|
| from model.transformer_rope import GPTRoPEConfig, GPTRoPE
|
| from model.transformer_nextlat import TransformerNextLatConfig, TransformerNextLat
|
| from model.mamba import MambaConfig, Mamba
|
| from model.mamba2 import Mamba2Config, Mamba2
|
| from model.gated_deltanet import GatedDeltaNetConfig, GatedDeltaNet
|
| from model.gru import GRUConfig, GRU
|
| import numpy as np
|
| import networkx as nx
|
| import argparse
|
| import pickle
|
| import re
|
| import torch
|
| import math
|
| from torch.nn.utils.rnn import pad_sequence
|
| from cli_utils import parse_count, format_count
|
|
|
|
|
| def parse_args():
|
| parser = argparse.ArgumentParser()
|
| parser.add_argument('--ckpt_iter', type=int, default=10000)
|
| parser.add_argument('--model', type=str, default='transformer', choices=['transformer', 'transformer-rope', 'transformer-nextlat', 'mamba', 'mamba2', 'gated-deltanet', 'gru'],
|
| help='Model architecture; selects out/<model>/ and how the checkpoint is built.')
|
| parser.add_argument('--config', type=str, default='12_12_576')
|
| parser.add_argument('--temperature', type=float, default=1)
|
| parser.add_argument('--device', type=str, default='cuda:0')
|
| parser.add_argument('--num_nodes', type=int, default=100)
|
| parser.add_argument('--num_of_paths', type=int, default=20)
|
| parser.add_argument('--batch_size', type=int, default=100)
|
| parser.add_argument('--num_iters', type=int, default=10)
|
| 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='10M',
|
| 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='H1',
|
| 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('--graph_file', type=str, default=None,
|
| help='Optional GraphML path; if provided, load this graph instead of the default')
|
| parser.add_argument('--B_graph_file', type=str, default=None,
|
| help='Optional GraphML path for Task B; if provided, use this graph for Task B validation instead of the default')
|
| parser.add_argument('--local', action='store_true', default=False,
|
| help='Disable flash attention for local GPU compatibility (default: False)')
|
| parser.add_argument('--path_type', type=str, default='RWs', 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='Test with partial prefixes: use a random portion of the path as prompt instead of just "A source target:" (default: False)')
|
|
|
| parser.add_argument('--no_task_tag', action='store_true', default=False,
|
| help='Data files do not contain task identifiers (A, B, C, etc.). When enabled, task tokens will not be considered in data processing. This should match the setting used during data generation.')
|
| parser.add_argument('--num_labels', type=int, default=10,
|
| help='Number of distinct node labels (default: 10). Must match data generation.')
|
| parser.add_argument('--PostGRU', action='store_true', default=False,
|
| help='Load PostGRU checkpoint (adds _PGR suffix to checkpoint filename)')
|
| parser.add_argument('--NLS', action='store_true', default=False,
|
| help='Load NLS checkpoint (adds _NLS suffix to checkpoint filename)')
|
| parser.add_argument('--DyadicAttn', action='store_true', default=False,
|
| help='Load DyadicAttn checkpoint (adds _DA suffix to checkpoint filename)')
|
| parser.add_argument('--DyadicHybrid', action='store_true', default=False,
|
| help='Load DyadicHybrid checkpoint (adds _DH suffix to checkpoint filename)')
|
| parser.add_argument('--ckpt_suffix', type=str, default='',
|
| help='Extra checkpoint tag to select a specific variant trained by '
|
| 'train_taskC.py (e.g. "SA" loads ..._{tasks_tag}_SA_{train_label}.pt). '
|
| 'Default empty = baseline model.')
|
|
|
| return parser.parse_args()
|
|
|
|
|
| args = parse_args()
|
| dataset = 'maze'
|
| ckpt_iter = args.ckpt_iter
|
| device = args.device
|
| temperature = args.temperature
|
| num_nodes = args.num_nodes
|
| num_of_paths = args.num_of_paths
|
| config = args.config
|
| multitasks = args.multitasks
|
| num_train_dataset = args.num_train_dataset
|
| num_test_dataset = args.num_test_dataset
|
| train_label = format_count(num_train_dataset)
|
| test_dataset_label = format_count(num_test_dataset)
|
| run_test_label = args.batch_size * args.num_iters
|
| no_task_tag = args.no_task_tag
|
|
|
| tasks_str = args.tasks
|
| tasks_tag = f"{tasks_str}_CL" if args.CL else tasks_str
|
|
|
| allow_cycles = (args.path_type in ['RWc', 'RWs'])
|
| path_type_tag = args.path_type
|
| tasks_tag = f"{tasks_tag}_{path_type_tag}"
|
|
|
| if args.num_labels != 10:
|
| tasks_tag = f"{tasks_tag}_L{args.num_labels}"
|
|
|
| if args.no_task_tag:
|
| tasks_tag = f"{tasks_tag}_NT"
|
|
|
| data_tasks_tag = tasks_tag
|
|
|
| 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"
|
|
|
| if args.DyadicAttn:
|
| tasks_tag = f"{tasks_tag}_DA"
|
| if args.DyadicHybrid:
|
| tasks_tag = f"{tasks_tag}_DH"
|
|
|
|
|
| if args.ckpt_suffix:
|
| tasks_tag = f"{tasks_tag}_{args.ckpt_suffix}"
|
|
|
| graph_tag = f"{tasks_str}_CL" if args.CL else tasks_str
|
| graph_tag = f"{graph_tag}_{path_type_tag}"
|
|
|
| if args.num_labels != 10:
|
| graph_tag = f"{graph_tag}_L{args.num_labels}"
|
|
|
| if args.no_task_tag:
|
| graph_tag = f"{graph_tag}_NT"
|
|
|
| data_path = f'data/{dataset}/{num_nodes}'
|
|
|
|
|
| def pick_first_existing_meta(candidates):
|
| for path in candidates:
|
| if os.path.exists(path):
|
| return path
|
| return candidates[0]
|
|
|
|
|
| meta_path = pick_first_existing_meta([
|
| f'{data_path}/meta_{data_tasks_tag}.pkl',
|
| f'{data_path}/meta_{tasks_str}.pkl',
|
| f'{data_path}/meta.pkl',
|
| ])
|
|
|
| print(f"Loading meta from {meta_path}...")
|
| with open(meta_path, 'rb') as f:
|
| meta = pickle.load(f)
|
|
|
| stoi, itos = meta['stoi'], meta['itos']
|
| max_new_tokens = meta['block_size']
|
| top_k = len(itos)
|
| simple_format = meta['simple_format']
|
|
|
|
|
| if 'no_task_tag' in meta:
|
| meta_no_task_tag = meta['no_task_tag']
|
|
|
| nt_suffix = '_NT' if no_task_tag else ''
|
| out_dir = f'out/{args.model.replace("-", "_")}/{dataset}_{config}_{num_nodes}{nt_suffix}/'
|
|
|
|
|
| def pick_first_existing(candidates):
|
| for path in candidates:
|
| if os.path.exists(path):
|
| return path
|
| return candidates[0]
|
|
|
|
|
| if multitasks:
|
| candidate_ckpts = [
|
| os.path.join(out_dir, f'{ckpt_iter}_ckpt_maze_{tasks_tag}_{train_label}.pt'),
|
| os.path.join(out_dir, f'{ckpt_iter}_ckpt_maze_{tasks_tag}_{num_train_dataset}.pt'),
|
| os.path.join(out_dir, f'{ckpt_iter}_ckpt_maze_{tasks_str}_{train_label}.pt'),
|
| os.path.join(out_dir, f'{ckpt_iter}_ckpt_maze_{tasks_str}_{num_train_dataset}.pt'),
|
| os.path.join(out_dir, f'{ckpt_iter}_ckpt_maze_{num_of_paths}.pt'),
|
| os.path.join(out_dir, f'{ckpt_iter}_ckpt_maze.pt'),
|
| ]
|
| ckpt_path = pick_first_existing(candidate_ckpts)
|
| else:
|
| if (num_of_paths == 0):
|
| ckpt_path = os.path.join(out_dir, f'{ckpt_iter}_ckpt_maze.pt')
|
| else:
|
| ckpt_path = os.path.join(out_dir, f'{ckpt_iter}_ckpt_maze_{num_of_paths}.pt')
|
| checkpoint = torch.load(ckpt_path, map_location=device, weights_only=False)
|
| model_args = checkpoint['model_args']
|
| ckpt_model_type = checkpoint.get('model_type', args.model)
|
| if ckpt_model_type == 'mamba':
|
| model = Mamba(MambaConfig(**model_args))
|
| elif ckpt_model_type == 'mamba2':
|
| model = Mamba2(Mamba2Config(**model_args))
|
| elif ckpt_model_type == 'gated-deltanet':
|
| model = GatedDeltaNet(GatedDeltaNetConfig(**model_args))
|
| elif ckpt_model_type == 'gru':
|
| model = GRU(GRUConfig(**model_args))
|
| elif ckpt_model_type == 'transformer-nextlat':
|
| if args.local:
|
| model_args['use_flash'] = False
|
| model = TransformerNextLat(TransformerNextLatConfig(**model_args))
|
| elif ckpt_model_type == 'transformer-rope':
|
| if args.local:
|
| model_args['use_flash'] = False
|
| model = GPTRoPE(GPTRoPEConfig(**model_args))
|
| else:
|
| if args.local:
|
| model_args['use_flash'] = False
|
| gptconf = GPTConfig(**model_args)
|
| model = GPT(gptconf)
|
| state_dict = checkpoint['model']
|
| unwanted_prefix = '_orig_mod.'
|
| for k, v in list(state_dict.items()):
|
| if k.startswith(unwanted_prefix):
|
| state_dict[k[len(unwanted_prefix):]] = state_dict.pop(k)
|
| model.load_state_dict(state_dict)
|
|
|
| model.eval()
|
| model.to(device)
|
|
|
| graph_file = args.graph_file
|
| if graph_file is not None:
|
| maze_graph_path = graph_file if os.path.isabs(graph_file) else os.path.join(data_path, graph_file)
|
| else:
|
| if multitasks:
|
| maze_graph_path = pick_first_existing([
|
| f'{data_path}/maze_graph_{graph_tag}.graphml',
|
| f'{data_path}/maze_graph_{tasks_str}.graphml',
|
| f'{data_path}/maze_graph.graphml',
|
| ])
|
| else:
|
| maze_graph_path = f'{data_path}/maze_graph.graphml'
|
| maze_graph = nx.read_graphml(maze_graph_path)
|
|
|
|
|
| graph_node_labels = set(attrs.get('label', '?') for _, attrs in maze_graph.nodes(data=True))
|
| print(f"Graph labels ({len(graph_node_labels)}): {sorted(graph_node_labels)[:10]}{'...' if len(graph_node_labels) > 10 else ''}")
|
|
|
|
|
| B_graph_file = args.B_graph_file
|
| if B_graph_file is not None:
|
| B_graph_path = B_graph_file if os.path.isabs(B_graph_file) else os.path.join(data_path, B_graph_file)
|
| print(f"Loading Task B graph from {B_graph_path}...")
|
| maze_graph_B = nx.read_graphml(B_graph_path)
|
| else:
|
| maze_graph_B = maze_graph
|
|
|
|
|
| n = int(math.sqrt(num_nodes))
|
|
|
|
|
| def find_third_number_position(number_string):
|
| numbers = number_string.split()
|
| if no_task_tag:
|
|
|
| third_number_index = 2
|
| else:
|
|
|
| if numbers[0] in ['A', 'B', 'C', 'D', 'E', 'F', 'G']:
|
|
|
| third_number_index = 3
|
| else:
|
|
|
| third_number_index = 2
|
| position = sum(len(num) for num in numbers[:third_number_index]) + third_number_index - 1
|
| return position
|
|
|
|
|
| def encode(s):
|
| ss = s.split(" ")
|
| encoded_string = [stoi[ch] for ch in ss]
|
| return encoded_string
|
|
|
|
|
| def decode(l):
|
| dec = ""
|
| for i in l:
|
| dec = dec + itos[i] + " "
|
| return dec[:-1]
|
|
|
|
|
| def check_maze_path(G, gen_str, n, prefix_dir_count=0):
|
| """
|
| Check if a maze path in direction format is valid.
|
| Format: "task_id source_node target_node direction_sequence" or "source_node target_node direction_sequence"
|
| Task IDs: A, B, C, D, E, F, G (optional, for multi-task support)
|
| Directions: N (north/up), S (south/down), E (east/right), W (west/left)
|
|
|
| Args:
|
| G: The graph
|
| gen_str: The generated string to check
|
| n: Grid size
|
| prefix_dir_count: Number of prefix directions (for partial mode, step numbers in errors will be offset)
|
|
|
| Returns:
|
| '' if path is correct
|
| error message otherwise
|
| """
|
| tokens = [t for t in gen_str.split() if t != ':' and t != '>']
|
|
|
|
|
| task_offset = 0
|
| if not no_task_tag and len(tokens) > 0 and tokens[0] in ['A', 'B', 'C', 'D', 'E', 'F', 'G']:
|
| task_offset = 1
|
|
|
|
|
| if len(tokens) < 2 + task_offset:
|
| return 'syntax error'
|
|
|
| try:
|
| source = int(tokens[task_offset])
|
| target = int(tokens[task_offset + 1])
|
| except (ValueError, IndexError):
|
| return 'syntax error'
|
|
|
|
|
| if source < 0 or source >= num_nodes or target < 0 or target >= num_nodes:
|
| return 'syntax error'
|
|
|
|
|
| directions = tokens[2 + task_offset:]
|
|
|
|
|
| current_node = source
|
|
|
|
|
| for i, direction in enumerate(directions):
|
| if direction not in ['N', 'S', 'E', 'W']:
|
| return 'syntax error'
|
|
|
|
|
| next_node = None
|
| if direction == 'N':
|
| next_node = current_node - n
|
| elif direction == 'S':
|
| next_node = current_node + n
|
| elif direction == 'E':
|
| next_node = current_node + 1
|
| elif direction == 'W':
|
| next_node = current_node - 1
|
|
|
|
|
|
|
| suffix_step = i - prefix_dir_count
|
| if next_node is None or next_node < 0 or next_node >= num_nodes:
|
| if prefix_dir_count > 0 and suffix_step >= 0:
|
| return f'suffix_step {suffix_step} node {current_node} direction {direction} is illegal'
|
| else:
|
| return f'step {i} node {current_node} direction {direction} is illegal'
|
|
|
|
|
| if not G.has_edge(str(current_node), str(next_node)):
|
| if prefix_dir_count > 0 and suffix_step >= 0:
|
| return f'suffix_step {suffix_step} node {current_node} direction {direction} is illegal'
|
| else:
|
| return f'step {i} node {current_node} direction {direction} is illegal'
|
|
|
|
|
| current_node = next_node
|
|
|
|
|
| if current_node != target:
|
| return 'incorrect target node'
|
|
|
| return ''
|
|
|
|
|
| def check_turn_path(G, gen_str, n, cl_mode=False):
|
| """Validate a path expressed as relative turns (L/R/F/T).
|
|
|
| The agent starts facing East at the source node. Each token both turns
|
| and advances one step in the grid.
|
|
|
| When cl_mode is True, after each L or R turn token, there should be a
|
| node label token matching the current node (before moving).
|
| """
|
|
|
| tokens = [t for t in gen_str.split() if t != ':']
|
|
|
| task_offset = 0
|
| if not no_task_tag and len(tokens) > 0 and tokens[0] in TASK_TOKENS:
|
| task_offset = 1
|
|
|
| if len(tokens) < 2 + task_offset:
|
| return 'syntax error'
|
|
|
| try:
|
| source = int(tokens[task_offset])
|
| target = int(tokens[task_offset + 1])
|
| except (ValueError, IndexError):
|
| return 'syntax error'
|
|
|
| if source < 0 or source >= num_nodes or target < 0 or target >= num_nodes:
|
| return 'syntax error'
|
|
|
| actions = tokens[2 + task_offset:]
|
| orientation = 'E'
|
| current_node = source
|
|
|
| left_of = {'N': 'W', 'W': 'S', 'S': 'E', 'E': 'N'}
|
| right_of = {v: k for k, v in left_of.items()}
|
| opposite_of = {'N': 'S', 'S': 'N', 'E': 'W', 'W': 'E'}
|
| delta = {'N': -n, 'S': n, 'E': 1, 'W': -1}
|
| node_labels = graph_node_labels
|
|
|
| action_idx = 0
|
| step = 0
|
| while action_idx < len(actions):
|
| action = actions[action_idx]
|
| if action not in ['L', 'R', 'F', 'T']:
|
| return 'syntax error'
|
|
|
| if action == 'F':
|
| next_orientation = orientation
|
| elif action == 'L':
|
| next_orientation = left_of[orientation]
|
| elif action == 'R':
|
| next_orientation = right_of[orientation]
|
| else:
|
| next_orientation = opposite_of[orientation]
|
|
|
| next_node = current_node + delta[next_orientation]
|
| if next_node < 0 or next_node >= num_nodes:
|
| return f'step {step} node {current_node} direction {action} is illegal'
|
| if not G.has_edge(str(current_node), str(next_node)):
|
| return f'step {step} node {current_node} direction {action} is illegal'
|
|
|
|
|
| if cl_mode and action in ['L', 'R']:
|
| if action_idx + 1 >= len(actions):
|
| return 'syntax error'
|
| label_token = actions[action_idx + 1]
|
| if label_token not in node_labels:
|
| return 'syntax error'
|
| expected_label = G.nodes[str(current_node)]['label']
|
| if label_token != expected_label:
|
| return f'step {step} incorrect label {label_token} (expected {expected_label})'
|
| action_idx += 1
|
|
|
| orientation = next_orientation
|
| current_node = next_node
|
| action_idx += 1
|
| step += 1
|
|
|
| if current_node != target:
|
| return 'incorrect target node'
|
|
|
| return ''
|
|
|
|
|
|
|
| TASK_TOKENS = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I'}
|
|
|
|
|
| def check_correctness_taskA(G, gen_str, n, prefix_dir_count=0):
|
|
|
| return check_maze_path(G, gen_str, n, prefix_dir_count=prefix_dir_count)
|
|
|
|
|
| def check_correctness_taskB(G, gen_str, n, prompt_tokens=None):
|
|
|
| if prompt_tokens is None:
|
| return 'syntax error'
|
|
|
| def strip_colon(seq):
|
| return [t for t in seq if t != ':']
|
|
|
| tokens_raw = gen_str.strip().split()
|
| if no_task_tag:
|
|
|
| if ':' not in tokens_raw:
|
| return 'syntax error'
|
| colon_idx = tokens_raw.index(':')
|
| prompt_part = tokens_raw[:colon_idx]
|
| answer_part = tokens_raw[colon_idx + 1:]
|
| else:
|
|
|
| if not tokens_raw or tokens_raw[0] != 'B':
|
| return 'syntax error'
|
| if ':' not in tokens_raw:
|
| return 'syntax error'
|
| colon_idx = tokens_raw.index(':')
|
| prompt_part = tokens_raw[:colon_idx]
|
| answer_part = tokens_raw[colon_idx + 1:]
|
|
|
| prompt_clean = strip_colon(prompt_tokens)
|
| if no_task_tag:
|
| if len(prompt_clean) < 1:
|
| return 'syntax error'
|
| try:
|
| start_node = int(prompt_clean[0])
|
| except Exception:
|
| return 'syntax error'
|
| directions = prompt_clean[1:]
|
| else:
|
| if len(prompt_clean) < 2 or prompt_clean[0] != 'B':
|
| return 'syntax error'
|
| try:
|
| start_node = int(prompt_clean[1])
|
| except Exception:
|
| return 'syntax error'
|
| directions = prompt_clean[2:]
|
|
|
|
|
| current = start_node
|
| for direction in directions:
|
| if direction not in ['N', 'S', 'E', 'W']:
|
| return 'syntax error'
|
| if direction == 'N':
|
| next_node = current - n
|
| elif direction == 'S':
|
| next_node = current + n
|
| elif direction == 'E':
|
| next_node = current + 1
|
| else:
|
| next_node = current - 1
|
|
|
| if next_node < 0 or next_node >= len(G.nodes):
|
| return 'syntax error'
|
| if not G.has_edge(str(current), str(next_node)):
|
| return 'syntax error'
|
| current = next_node
|
|
|
| true_end = current
|
|
|
|
|
| if len(answer_part) != 5:
|
| return 'syntax error'
|
|
|
| pred_label = answer_part[0]
|
| true_label = G.nodes[str(true_end)]['label']
|
| if pred_label != true_label:
|
| return 'incorrect target node label'
|
|
|
| pred_neighbors = answer_part[1:5]
|
|
|
| neighbors_order = [(1, 'east'), (n, 'south'), (-1, 'west'), (-n, 'north')]
|
| for idx, (offset, dir_name) in enumerate(neighbors_order):
|
| neighbor_id = true_end + offset
|
| has_neighbor = G.has_edge(str(true_end), str(neighbor_id))
|
| true_neighbor_label = G.nodes[str(neighbor_id)]['label'] if has_neighbor else '/'
|
| if pred_neighbors[idx] != true_neighbor_label:
|
| return f'incorrect neighbor label {dir_name}'
|
|
|
| return ''
|
|
|
|
|
| def check_correctness_taskC(G, gen_str, n, cl_mode=False):
|
| return check_turn_path(G, gen_str, n, cl_mode=cl_mode)
|
|
|
|
|
| def check_correctness_taskD(G, gen_str, n, prompt_tokens=None):
|
| if prompt_tokens is None:
|
| return 'syntax error'
|
|
|
| prompt_clean = [t for t in prompt_tokens if t != ':']
|
| if no_task_tag:
|
| if len(prompt_clean) < 2:
|
| return 'syntax error'
|
| try:
|
| source = int(prompt_clean[0])
|
| except Exception:
|
| return 'syntax error'
|
| target_label = prompt_clean[1]
|
| else:
|
| if len(prompt_clean) < 3 or prompt_clean[0] != 'D':
|
| return 'syntax error'
|
| try:
|
| source = int(prompt_clean[1])
|
| except Exception:
|
| return 'syntax error'
|
| target_label = prompt_clean[2]
|
|
|
| node_labels = graph_node_labels
|
| if target_label not in node_labels:
|
| return 'syntax error'
|
|
|
| tokens_raw = gen_str.strip().split()
|
| if no_task_tag:
|
| if ':' not in tokens_raw:
|
| return 'syntax error'
|
| answer_part = tokens_raw[tokens_raw.index(':') + 1:]
|
| else:
|
| if not tokens_raw or tokens_raw[0] != 'D' or ':' not in tokens_raw:
|
| return 'syntax error'
|
| answer_part = tokens_raw[tokens_raw.index(':') + 1:]
|
|
|
| if not answer_part:
|
| return 'syntax error'
|
|
|
| current_node = source
|
| for i, direction in enumerate(answer_part):
|
| if direction not in ['N', 'S', 'E', 'W']:
|
| return 'syntax error'
|
| if direction == 'N':
|
| next_node = current_node - n
|
| elif direction == 'S':
|
| next_node = current_node + n
|
| elif direction == 'E':
|
| next_node = current_node + 1
|
| else:
|
| next_node = current_node - 1
|
|
|
| if next_node < 0 or next_node >= num_nodes:
|
| return f'step {i} node {current_node} direction {direction} is illegal'
|
| if not G.has_edge(str(current_node), str(next_node)):
|
| return f'step {i} node {current_node} direction {direction} is illegal'
|
| current_node = next_node
|
|
|
| end_label = G.nodes[str(current_node)]['label']
|
| if end_label != target_label:
|
| return 'incorrect target node'
|
|
|
| lengths = nx.single_source_shortest_path_length(G, str(source))
|
| min_dist = None
|
| for node_id, attrs in G.nodes(data=True):
|
| if attrs.get('label') != target_label:
|
| continue
|
| dist = lengths.get(str(node_id))
|
| if dist is None:
|
| continue
|
| if min_dist is None or dist < min_dist:
|
| min_dist = dist
|
| if min_dist is None or len(answer_part) != min_dist:
|
| return 'incorrect target node'
|
|
|
| return ''
|
|
|
|
|
| def check_correctness_taskE(G, gen_str, n, prompt_tokens=None):
|
| if prompt_tokens is None:
|
| return "syntax error"
|
|
|
| prompt_clean = [t for t in prompt_tokens if t != ':']
|
| if no_task_tag:
|
| if len(prompt_clean) < 2:
|
| return "syntax error"
|
| try:
|
| source = int(prompt_clean[0]); target = int(prompt_clean[1])
|
| except Exception:
|
| return "syntax error"
|
| else:
|
| if len(prompt_clean) < 3 or prompt_clean[0] != 'E':
|
| return "syntax error"
|
| try:
|
| source = int(prompt_clean[1]); target = int(prompt_clean[2])
|
| except Exception:
|
| return "syntax error"
|
|
|
| tokens_raw = gen_str.strip().split()
|
| if no_task_tag:
|
| if ':' not in tokens_raw:
|
| return "syntax error"
|
| answer_part = tokens_raw[tokens_raw.index(':') + 1:]
|
| else:
|
| if not tokens_raw or tokens_raw[0] != 'E' or ':' not in tokens_raw:
|
| return "syntax error"
|
| answer_part = tokens_raw[tokens_raw.index(':') + 1:]
|
|
|
| if not answer_part:
|
| return "syntax error"
|
|
|
| if len(answer_part) % 2 != 0:
|
| return f"step {len(answer_part) - 1} syntax error"
|
|
|
| node_labels = graph_node_labels
|
| dirs = {'N', 'S', 'E', 'W'}
|
|
|
| runs = []
|
| for i in range(0, len(answer_part), 2):
|
| d = answer_part[i]
|
| lab = answer_part[i + 1]
|
| if d not in dirs:
|
| return f"step {i} syntax error"
|
| if lab not in node_labels:
|
| return f"step {i + 1} syntax error"
|
|
|
| if not runs or runs[-1][0] != d or runs[-1][1] != lab:
|
| runs.append([d, lab, 1, i])
|
| else:
|
| runs[-1][2] += 1
|
|
|
| try:
|
| total_nodes = G.number_of_nodes()
|
| except Exception:
|
| total_nodes = None
|
|
|
| current = source
|
|
|
| def step(node, direction):
|
| if direction == 'N': return node - n
|
| if direction == 'S': return node + n
|
| if direction == 'E': return node + 1
|
| return node - 1
|
|
|
| for run_idx, (direction, lab, k, start_tok_idx) in enumerate(runs):
|
| seen = 0
|
| step_cap = total_nodes + 5 if total_nodes is not None else 10000
|
| steps = 0
|
|
|
| while True:
|
| steps += 1
|
| if steps > step_cap:
|
| return f"step {start_tok_idx} run seems non-terminating"
|
|
|
| nxt = step(current, direction)
|
|
|
| if total_nodes is not None and (nxt < 0 or nxt >= total_nodes):
|
| return f"step {start_tok_idx} node {current} direction {direction} is illegal"
|
|
|
| if not G.has_edge(str(current), str(nxt)):
|
| return f"step {start_tok_idx} node {current} direction {direction} is illegal"
|
|
|
| current = nxt
|
| node_label = G.nodes[str(current)]['label']
|
|
|
| if node_label == lab:
|
| seen += 1
|
| if seen == k:
|
| break
|
|
|
| if current != target:
|
| return "incorrect target node"
|
|
|
| return ""
|
|
|
|
|
| def check_correctness_taskF(G, gen_str, n, prompt_tokens=None):
|
| if prompt_tokens is None:
|
| return 'syntax error'
|
|
|
| prompt_clean = [t for t in prompt_tokens if t != ':']
|
| if no_task_tag:
|
| if len(prompt_clean) < 1:
|
| return 'syntax error'
|
| start_label = prompt_clean[0]
|
| directions = prompt_clean[1:]
|
| else:
|
| if len(prompt_clean) < 3 or prompt_clean[0] != 'F':
|
| return 'syntax error'
|
| start_label = prompt_clean[1]
|
| directions = prompt_clean[2:]
|
|
|
| if start_label not in graph_node_labels:
|
| return 'syntax error'
|
|
|
| valid_target_labels = set()
|
| any_start = False
|
|
|
| for node_id, attrs in G.nodes(data=True):
|
| if attrs.get('label') != start_label:
|
| continue
|
| any_start = True
|
| current_node = int(node_id)
|
| for direction in directions:
|
| if direction not in ['N', 'S', 'E', 'W']:
|
| return 'syntax error'
|
| if direction == 'N':
|
| next_node = current_node - n
|
| elif direction == 'S':
|
| next_node = current_node + n
|
| elif direction == 'E':
|
| next_node = current_node + 1
|
| else:
|
| next_node = current_node - 1
|
| if next_node < 0 or next_node >= num_nodes:
|
| current_node = None
|
| break
|
| if not G.has_edge(str(current_node), str(next_node)):
|
| current_node = None
|
| break
|
| current_node = next_node
|
| if current_node is not None:
|
| valid_target_labels.add(G.nodes[str(current_node)]['label'])
|
|
|
| if not any_start or not valid_target_labels:
|
| return 'syntax error'
|
|
|
| tokens_raw = gen_str.strip().split()
|
| if no_task_tag:
|
| if ':' not in tokens_raw:
|
| return 'syntax error'
|
| answer_part = tokens_raw[tokens_raw.index(':') + 1:]
|
| else:
|
| if not tokens_raw or tokens_raw[0] != 'F' or ':' not in tokens_raw:
|
| return 'syntax error'
|
| answer_part = tokens_raw[tokens_raw.index(':') + 1:]
|
|
|
| if len(answer_part) != 1:
|
| return 'syntax error'
|
|
|
| if answer_part[0] not in valid_target_labels:
|
| return 'incorrect target label'
|
|
|
| return ''
|
|
|
|
|
| def check_correctness_taskG(G, gen_str, n, prompt_tokens=None):
|
| if prompt_tokens is None:
|
| return 'syntax error'
|
|
|
| prompt_clean = [t for t in prompt_tokens if t != ':']
|
| if no_task_tag:
|
| if len(prompt_clean) < 4:
|
| return 'syntax error'
|
| try:
|
| source1 = int(prompt_clean[0])
|
| source2 = int(prompt_clean[1])
|
| target1 = int(prompt_clean[2])
|
| target2 = int(prompt_clean[3])
|
| except Exception:
|
| return 'syntax error'
|
| else:
|
| if len(prompt_clean) < 5 or prompt_clean[0] != 'G':
|
| return 'syntax error'
|
| try:
|
| source1 = int(prompt_clean[1])
|
| source2 = int(prompt_clean[2])
|
| target1 = int(prompt_clean[3])
|
| target2 = int(prompt_clean[4])
|
| except Exception:
|
| return 'syntax error'
|
|
|
| tokens_raw = gen_str.strip().split()
|
| if no_task_tag:
|
| if ':' not in tokens_raw:
|
| return 'syntax error'
|
| answer_part = tokens_raw[tokens_raw.index(':') + 1:]
|
| else:
|
| if not tokens_raw or tokens_raw[0] != 'G' or ':' not in tokens_raw:
|
| return 'syntax error'
|
| answer_part = tokens_raw[tokens_raw.index(':') + 1:]
|
|
|
| if len(answer_part) < 3:
|
| return 'syntax error'
|
|
|
| try:
|
| chosen_source = int(answer_part[0])
|
| chosen_target = int(answer_part[1])
|
| except Exception:
|
| return 'syntax error'
|
|
|
| if (chosen_source, chosen_target) not in [(source1, target1), (source2, target2)]:
|
| return 'syntax error'
|
|
|
| if not nx.has_path(G, str(chosen_source), str(chosen_target)):
|
| return 'incorrect target node'
|
|
|
| directions = answer_part[2:]
|
| current_node = chosen_source
|
| for i, direction in enumerate(directions):
|
| if direction not in ['N', 'S', 'E', 'W']:
|
| return 'syntax error'
|
| if direction == 'N':
|
| next_node = current_node - n
|
| elif direction == 'S':
|
| next_node = current_node + n
|
| elif direction == 'E':
|
| next_node = current_node + 1
|
| else:
|
| next_node = current_node - 1
|
| if next_node < 0 or next_node >= num_nodes:
|
| return f'step {i} node {current_node} direction {direction} is illegal'
|
| if not G.has_edge(str(current_node), str(next_node)):
|
| return f'step {i} node {current_node} direction {direction} is illegal'
|
| current_node = next_node
|
|
|
| if current_node != chosen_target:
|
| return 'incorrect target node'
|
|
|
| return ''
|
|
|
|
|
| def check_correctness_taskH(G, gen_str, n, prompt_tokens=None):
|
| """Validate Task H: relative clockwise-index path encoding.
|
|
|
| The walker starts facing East. Each answer token is a 1-based index
|
| into the feasible edges enumerated clockwise starting from the first
|
| direction after the current facing direction.
|
| """
|
| if prompt_tokens is None:
|
| return 'syntax error'
|
|
|
| prompt_clean = [t for t in prompt_tokens if t != ':']
|
| if no_task_tag:
|
| if len(prompt_clean) < 2:
|
| return 'syntax error'
|
| try:
|
| source = int(prompt_clean[0])
|
| target = int(prompt_clean[1])
|
| except Exception:
|
| return 'syntax error'
|
| else:
|
| if len(prompt_clean) < 3 or prompt_clean[0] != 'H':
|
| return 'syntax error'
|
| try:
|
| source = int(prompt_clean[1])
|
| target = int(prompt_clean[2])
|
| except Exception:
|
| return 'syntax error'
|
|
|
| tokens_raw = gen_str.strip().split()
|
| if no_task_tag:
|
| if ':' not in tokens_raw:
|
| return 'syntax error'
|
| answer_part = tokens_raw[tokens_raw.index(':') + 1:]
|
| else:
|
| if not tokens_raw or tokens_raw[0] != 'H' or ':' not in tokens_raw:
|
| return 'syntax error'
|
| answer_part = tokens_raw[tokens_raw.index(':') + 1:]
|
|
|
| if not answer_part:
|
| return 'syntax error'
|
|
|
| CLOCKWISE_SCAN = {
|
| 'N': ['N', 'E', 'S', 'W'],
|
| 'E': ['E', 'S', 'W', 'N'],
|
| 'S': ['S', 'W', 'N', 'E'],
|
| 'W': ['W', 'N', 'E', 'S'],
|
| }
|
| DELTA = {'N': -n, 'S': n, 'E': 1, 'W': -1}
|
|
|
| facing = 'E'
|
| current = source
|
|
|
| for step_idx, token in enumerate(answer_part):
|
| try:
|
| idx = int(token)
|
| except ValueError:
|
| return f'step {step_idx} syntax error'
|
|
|
| if idx < 1 or idx > 4:
|
| return f'step {step_idx} invalid index {idx}'
|
|
|
|
|
| scan_order = CLOCKWISE_SCAN[facing]
|
| feasible = []
|
| for d in scan_order:
|
| neighbor = current + DELTA[d]
|
| if 0 <= neighbor < num_nodes and G.has_edge(str(current), str(neighbor)):
|
| feasible.append(d)
|
|
|
| if not feasible:
|
| return f'step {step_idx} no feasible edges from node {current}'
|
|
|
| if idx > len(feasible):
|
| return f'step {step_idx} index {idx} exceeds feasible count {len(feasible)}'
|
|
|
| direction = feasible[idx - 1]
|
| next_node = current + DELTA[direction]
|
|
|
| facing = direction
|
| current = next_node
|
|
|
| if current != target:
|
| return 'incorrect target node'
|
|
|
| return ''
|
|
|
|
|
| def check_correctness_taskI(G, gen_str, n, prompt_tokens=None):
|
| """Validate Task I: absolute clockwise-index path encoding (fixed North).
|
|
|
| Like Task H but feasible edges are always enumerated clockwise from a
|
| FIXED North reference (N, E, S, W); the walker does not track facing.
|
| Each answer token is the 1-based index into the node's feasible edges
|
| in this fixed order.
|
| """
|
| if prompt_tokens is None:
|
| return 'syntax error'
|
|
|
| prompt_clean = [t for t in prompt_tokens if t != ':']
|
| if no_task_tag:
|
| if len(prompt_clean) < 2:
|
| return 'syntax error'
|
| try:
|
| source = int(prompt_clean[0])
|
| target = int(prompt_clean[1])
|
| except Exception:
|
| return 'syntax error'
|
| else:
|
| if len(prompt_clean) < 3 or prompt_clean[0] != 'I':
|
| return 'syntax error'
|
| try:
|
| source = int(prompt_clean[1])
|
| target = int(prompt_clean[2])
|
| except Exception:
|
| return 'syntax error'
|
|
|
| tokens_raw = gen_str.strip().split()
|
| if no_task_tag:
|
| if ':' not in tokens_raw:
|
| return 'syntax error'
|
| answer_part = tokens_raw[tokens_raw.index(':') + 1:]
|
| else:
|
| if not tokens_raw or tokens_raw[0] != 'I' or ':' not in tokens_raw:
|
| return 'syntax error'
|
| answer_part = tokens_raw[tokens_raw.index(':') + 1:]
|
|
|
| if not answer_part:
|
| return 'syntax error'
|
|
|
| FIXED_SCAN = ['N', 'E', 'S', 'W']
|
| DELTA = {'N': -n, 'S': n, 'E': 1, 'W': -1}
|
|
|
| current = source
|
|
|
| for step_idx, token in enumerate(answer_part):
|
| try:
|
| idx = int(token)
|
| except ValueError:
|
| return f'step {step_idx} syntax error'
|
|
|
| if idx < 1 or idx > 4:
|
| return f'step {step_idx} invalid index {idx}'
|
|
|
|
|
| feasible = []
|
| for d in FIXED_SCAN:
|
| neighbor = current + DELTA[d]
|
| if 0 <= neighbor < num_nodes and G.has_edge(str(current), str(neighbor)):
|
| feasible.append(d)
|
|
|
| if not feasible:
|
| return f'step {step_idx} no feasible edges from node {current}'
|
|
|
| if idx > len(feasible):
|
| return f'step {step_idx} index {idx} exceeds feasible count {len(feasible)}'
|
|
|
| direction = feasible[idx - 1]
|
| current = current + DELTA[direction]
|
|
|
| if current != target:
|
| return 'incorrect target node'
|
|
|
| return ''
|
|
|
|
|
| def check_path_unreachable(G, gen_str, gt):
|
| path = re.findall(r'\d+|x', gen_str)
|
| if 'x' in path and len(path) < 4:
|
| return 0 if 'x' in gt else 1
|
|
|
| if 'x' in gt and 'x' not in gen_str:
|
| return 1
|
|
|
| return check_maze_path(G, gen_str, n)
|
|
|
|
|
| typedata = 'test'
|
| typedata_candidates = (
|
| [
|
| os.path.join(data_path, f'test_{data_tasks_tag}_{test_dataset_label}.txt'),
|
| os.path.join(data_path, f'test_{data_tasks_tag}_{num_test_dataset}.txt'),
|
| os.path.join(data_path, f'test_{data_tasks_tag}_{run_test_label}.txt'),
|
| os.path.join(data_path, f'test_{tasks_str}_{test_dataset_label}.txt'),
|
| os.path.join(data_path, f'test_{tasks_str}_{num_test_dataset}.txt'),
|
| ]
|
| if multitasks else [os.path.join(data_path, f'{typedata}.txt')]
|
| )
|
| typedata_path = pick_first_existing(typedata_candidates)
|
| f = open(typedata_path, encoding='gbk')
|
| texts = []
|
| encode_texts = []
|
| ground_truth = []
|
| full_lines = []
|
|
|
| for line in f:
|
| line = line.strip()
|
| if not line:
|
| continue
|
| full_lines.append(line)
|
| if multitasks:
|
| texts.append(line.split(':')[0] + ':')
|
| encode_texts.append(encode(line.split(':')[0] + ':'))
|
| else:
|
| pos = find_third_number_position(line)
|
| if (line[:pos] != ''):
|
| texts.append(line[:pos])
|
| encode_texts.append(encode(line[:pos]))
|
|
|
| ground_truth.append(line)
|
|
|
| ground_truth = np.array(ground_truth)
|
|
|
| encode_texts = [torch.tensor(seq, dtype=torch.long).to(device) for seq in encode_texts]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| from tqdm import tqdm
|
| import random
|
|
|
| batch_size = args.batch_size
|
|
|
|
|
| temp_suffix = f'_t{temperature}' if temperature != 1.0 else ''
|
|
|
|
|
| if args.partial:
|
| pred_filename = (
|
| f'pred_{typedata}_{tasks_tag}_{ckpt_iter}_{run_test_label}{temp_suffix}_partial.txt'
|
| if multitasks else f'pred_{typedata}_{ckpt_iter}_{num_of_paths}{temp_suffix}_partial.txt'
|
| )
|
| else:
|
| pred_filename = (
|
| f'pred_{typedata}_{tasks_tag}_{ckpt_iter}_{run_test_label}{temp_suffix}.txt'
|
| if multitasks else f'pred_{typedata}_{ckpt_iter}_{num_of_paths}{temp_suffix}.txt'
|
| )
|
|
|
| with open(out_dir + pred_filename, 'w') as f:
|
| pass
|
|
|
| wrong = 0
|
| total = 0
|
| partial_prefix_lengths = []
|
| j = 1
|
|
|
| for i in tqdm(range(args.num_iters), desc="Testing batches"):
|
| ix = torch.randint(len(encode_texts), (batch_size,))
|
|
|
| if args.partial:
|
|
|
| x_list = []
|
| partial_texts = []
|
| prefix_dir_counts = []
|
| for idx in ix:
|
| full_line = full_lines[idx]
|
|
|
| if ':' in full_line:
|
| prompt_part = full_line.split(':')[0] + ':'
|
| path_part = full_line.split(':')[1].strip()
|
| path_tokens = path_part.split()
|
|
|
| if len(path_tokens) > 0:
|
|
|
| max_prefix_len = max(1, len(path_tokens) - 1)
|
| prefix_len = random.randint(1, max_prefix_len)
|
| partial_prefix_lengths.append(prefix_len)
|
| prefix_dir_counts.append(prefix_len)
|
|
|
|
|
| partial_prefix = prompt_part + ' ' + ' '.join(path_tokens[:prefix_len])
|
| partial_texts.append(partial_prefix)
|
| x_list.append(torch.tensor(encode(partial_prefix), dtype=torch.long).to(device).unsqueeze(0))
|
| else:
|
|
|
| partial_texts.append(prompt_part)
|
| prefix_dir_counts.append(0)
|
| x_list.append(encode_texts[idx].unsqueeze(0))
|
| else:
|
|
|
| partial_texts.append(texts[idx])
|
| prefix_dir_counts.append(0)
|
| x_list.append(encode_texts[idx].unsqueeze(0))
|
| else:
|
| x_list = [encode_texts[idx].unsqueeze(0) for idx in ix]
|
|
|
| x_gt = ground_truth[ix]
|
|
|
| with torch.no_grad():
|
| y_pred_list = []
|
| confidence_list = []
|
| top3_tokens_list = []
|
| top3_probs_list = []
|
|
|
|
|
|
|
|
|
|
|
| from collections import defaultdict
|
| groups = defaultdict(list)
|
| for orig_i, x in enumerate(x_list):
|
| groups[x.size(1)].append((orig_i, x))
|
|
|
|
|
| y_pred_list = [None] * len(x_list)
|
| confidence_list = [None] * len(x_list)
|
| top3_tokens_list = [None] * len(x_list)
|
| top3_probs_list = [None] * len(x_list)
|
|
|
| for prompt_len, items in groups.items():
|
| xb = torch.cat([x for _, x in items], dim=0)
|
| yb, conf_b, t3t_b, t3p_b = model.generate(
|
| xb, max_new_tokens, temperature=temperature, top_k=top_k, return_confidence=True)
|
| B = xb.size(0)
|
| if B == 1:
|
|
|
| orig_i = items[0][0]
|
| y_pred_list[orig_i] = decode(yb[0].tolist()).split('\n')[0]
|
| confidence_list[orig_i] = conf_b
|
| top3_tokens_list[orig_i] = t3t_b
|
| top3_probs_list[orig_i] = t3p_b
|
| else:
|
| for k, (orig_i, _) in enumerate(items):
|
| y_pred_list[orig_i] = decode(yb[k].tolist()).split('\n')[0]
|
| confidence_list[orig_i] = conf_b[k]
|
| top3_tokens_list[orig_i] = t3t_b[k]
|
| top3_probs_list[orig_i] = t3p_b[k]
|
|
|
| y_pred = y_pred_list
|
|
|
| batch_wrong = 0
|
| with open(out_dir + pred_filename, 'a') as f:
|
| for t, item in enumerate(y_pred):
|
| total += 1
|
| tokens = item.split()
|
|
|
| if no_task_tag:
|
| original_prompt = texts[ix[t]].split() if not args.partial else partial_texts[t].split()
|
| if ':' in item:
|
| colon_idx_char = item.index(':')
|
| answer_part = item[colon_idx_char + 1:].strip()
|
| answer_tokens = answer_part.split()
|
|
|
| if len(original_prompt) >= 2 and original_prompt[0].isdigit() and original_prompt[1].isdigit():
|
| if len(answer_tokens) >= 2 and answer_tokens[1] in graph_node_labels:
|
| task_id = 'E'
|
| elif any(tok in ['L', 'R', 'F', 'T'] for tok in answer_tokens):
|
| task_id = 'C'
|
| else:
|
| task_id = 'A'
|
| elif len(original_prompt) >= 2 and original_prompt[0].isdigit():
|
| has_directions_in_prompt = any(tok in ['N', 'S', 'E', 'W'] for tok in original_prompt[1:])
|
| task_id = 'B' if (has_directions_in_prompt and len(answer_tokens) == 5) else None
|
| elif len(original_prompt) >= 2 and original_prompt[0].isdigit() and \
|
| original_prompt[1] in graph_node_labels:
|
| task_id = 'D'
|
| elif len(original_prompt) >= 2 and original_prompt[0] in graph_node_labels:
|
| task_id = 'F'
|
| elif len(original_prompt) >= 4 and all(token.isdigit() for token in original_prompt[:4]):
|
| task_id = 'G'
|
| else:
|
| task_id = None
|
| else:
|
| task_id = None
|
| else:
|
| task_id = tokens[0] if len(tokens) > 0 and tokens[0] in TASK_TOKENS else None
|
|
|
| prompt_tokens = texts[ix[t]].split() if not args.partial else partial_texts[t].split()
|
| pdc = prefix_dir_counts[t] if args.partial else 0
|
| output_task_label = f"({task_id}) " if (no_task_tag and task_id) else ""
|
|
|
| if task_id == 'A' or (task_id is None and not multitasks):
|
| symbol = check_correctness_taskA(maze_graph, item, n, prefix_dir_count=pdc)
|
| elif task_id == 'B':
|
| symbol = check_correctness_taskB(maze_graph_B, item, n, prompt_tokens=prompt_tokens)
|
| elif task_id == 'C':
|
| symbol = check_correctness_taskC(maze_graph, item, n, cl_mode=args.CL)
|
| elif task_id == 'D':
|
| symbol = check_correctness_taskD(maze_graph, item, n, prompt_tokens=prompt_tokens)
|
| elif task_id == 'E':
|
| symbol = check_correctness_taskE(maze_graph, item, n, prompt_tokens=prompt_tokens)
|
| elif task_id == 'F':
|
| symbol = check_correctness_taskF(maze_graph, item, n, prompt_tokens=prompt_tokens)
|
| elif task_id == 'G':
|
| symbol = check_correctness_taskG(maze_graph, item, n, prompt_tokens=prompt_tokens)
|
| elif task_id == 'H':
|
| symbol = check_correctness_taskH(maze_graph, item, n, prompt_tokens=prompt_tokens)
|
| elif task_id == 'I':
|
| symbol = check_correctness_taskI(maze_graph, item, n, prompt_tokens=prompt_tokens)
|
| else:
|
| symbol = check_maze_path(maze_graph, item, n, prefix_dir_count=pdc)
|
|
|
| if (symbol != ""):
|
| wrong += 1
|
| batch_wrong += 1
|
|
|
| error_confidence_info = ""
|
| if symbol != "" and t < len(confidence_list):
|
| error_pos = None
|
|
|
|
|
| step_match = re.search(r'(?:step|suffix_step|run)\s+(\d+)', symbol)
|
| if step_match:
|
| error_pos = int(step_match.group(1))
|
|
|
|
|
| elif symbol == 'incorrect target node' or 'syntax error' in symbol:
|
| gen_tokens = item.split()
|
| if ':' in gen_tokens:
|
|
|
| error_pos = len(gen_tokens) - gen_tokens.index(':') - 1
|
|
|
|
|
| elif 'incorrect' in symbol and 'label' in symbol:
|
| gen_tokens = item.split()
|
| if ':' in gen_tokens:
|
|
|
| error_pos = 0
|
|
|
|
|
| if error_pos is not None and error_pos < len(confidence_list[t]):
|
| error_conf = confidence_list[t][error_pos]
|
| top3_tok = top3_tokens_list[t][error_pos]
|
| top3_prob = top3_probs_list[t][error_pos]
|
| top3_strs = [itos[tok] if tok < len(itos) else f"<{tok}>" for tok in top3_tok]
|
|
|
|
|
| if (top3_prob[0] - error_conf) > 0.4:
|
| mistake_type = "LOW-CONF"
|
| else:
|
| mistake_type = "HIGH-CONF"
|
|
|
| error_confidence_info = f" [{mistake_type}: conf={error_conf:.4f}, top3={top3_strs}, probs=[{top3_prob[0]:.4f},{top3_prob[1]:.4f},{top3_prob[2]:.4f}]]"
|
|
|
| if args.partial:
|
| gen_tokens = item.split()
|
| if ':' in gen_tokens:
|
| colon_idx = gen_tokens.index(':')
|
| marker_pos = colon_idx + 1 + pdc
|
| if marker_pos <= len(gen_tokens):
|
| gen_tokens.insert(marker_pos, '>')
|
| marked_item = ' '.join(gen_tokens)
|
| else:
|
| marked_item = item
|
| f.write(output_task_label + marked_item + " " + symbol + error_confidence_info + '\n')
|
| else:
|
| f.write(output_task_label + item + " " + symbol + error_confidence_info + '\n')
|
|
|
|
|
| batch_correct = batch_size - batch_wrong
|
| batch_accuracy = 100.0 * batch_correct / batch_size
|
|
|
| print(f"Batch {j}/{args.num_iters}: Accuracy = {batch_accuracy:.2f}% ({batch_correct}/{batch_size})")
|
| j = j + 1
|
|
|
|
|
| overall_accuracy = 100.0 * (total - wrong) / total if total > 0 else 0.0
|
|
|
|
|
| overall_accuracy = 100.0 * (total - wrong) / total if total > 0 else 0.0
|
| print(f"\nTotal predictions: {total}")
|
| print(f"Correct predictions: {total - wrong}")
|
| print(f"Wrong predictions: {wrong}")
|
| print(f"Overall accuracy: {overall_accuracy:.2f}%")
|
|
|
|
|
| if args.partial and partial_prefix_lengths:
|
| avg_prefix_len = sum(partial_prefix_lengths) / len(partial_prefix_lengths)
|
| print(f"\nPartial prefix mode statistics:")
|
| print(f" Average prefix length: {avg_prefix_len:.2f} tokens")
|
| print(f" Min prefix length: {min(partial_prefix_lengths)}")
|
| print(f" Max prefix length: {max(partial_prefix_lengths)}")
|
|
|
|
|
| import subprocess
|
| import sys
|
|
|
| print("\n" + "=" * 60)
|
| print("Running analyze_maze.py...")
|
| print("=" * 60)
|
|
|
| analyze_cmd = [
|
| sys.executable, 'analyze_maze.py',
|
| '--ckpt_iter', str(args.ckpt_iter),
|
| '--model', args.model,
|
| '--config', config,
|
| '--dataset', dataset,
|
| '--num_nodes', str(args.num_nodes),
|
| '--num_of_paths', str(args.num_of_paths),
|
| '--num_train_dataset', str(num_train_dataset),
|
| '--num_test_dataset', str(num_test_dataset),
|
| '--tasks', tasks_str,
|
| '--batch_size', str(args.batch_size),
|
| '--num_iters', str(args.num_iters),
|
| '--path_type', args.path_type,
|
| ]
|
|
|
| if args.multitasks:
|
| analyze_cmd.append('--multitasks')
|
| else:
|
| analyze_cmd.append('--no-multitasks')
|
|
|
| if args.CL:
|
| analyze_cmd.append('--CL')
|
|
|
| if args.partial:
|
| analyze_cmd.append('--partial')
|
|
|
| if args.no_task_tag:
|
| analyze_cmd.append('--no_task_tag')
|
|
|
| if args.PostGRU:
|
| analyze_cmd.append('--PostGRU')
|
|
|
| if args.NLS:
|
| analyze_cmd.append('--NLS')
|
|
|
| if args.DyadicAttn:
|
| analyze_cmd.append('--DyadicAttn')
|
|
|
| if args.DyadicHybrid:
|
| analyze_cmd.append('--DyadicHybrid')
|
|
|
| if args.temperature != 1.0:
|
| analyze_cmd.extend(['--temperature', str(args.temperature)])
|
|
|
| subprocess.run(analyze_cmd) |