import os import math import random import pickle import argparse from collections import defaultdict from tqdm import tqdm import torch import numpy as np import networkx as nx from model.transformer import GPTConfig, GPT 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 from model.transformer_nextlat import TransformerNextLatConfig, TransformerNextLat from cli_utils import ( parse_count, format_count, parse_task_distribution, sample_task, directions_to_turns, turns_to_directions, ) def build_model_from_checkpoint(checkpoint, model_type, device, local=False): """Reconstruct the right architecture from a checkpoint, honoring its stored model_type.""" ckpt_model_type = checkpoint.get('model_type', model_type) model_args = checkpoint['model_args'] if ckpt_model_type == 'mamba': conf = MambaConfig(**model_args) model = Mamba(conf) elif ckpt_model_type == 'mamba2': conf = Mamba2Config(**model_args) model = Mamba2(conf) elif ckpt_model_type == 'gated-deltanet': conf = GatedDeltaNetConfig(**model_args) model = GatedDeltaNet(conf) elif ckpt_model_type == 'gru': conf = GRUConfig(**model_args) model = GRU(conf) elif ckpt_model_type == 'transformer-nextlat': conf = TransformerNextLatConfig(**model_args) model = TransformerNextLat(conf) else: if local and 'use_flash' in model_args: model_args['use_flash'] = False conf = GPTConfig(**model_args) model = GPT(conf) state_dict = checkpoint['model'] model.load_state_dict({k.replace('_orig_mod.', ''): v for k, v in state_dict.items()}) model.eval() model.to(device) return model, conf def detect_task_id_support(stoi, no_task_tag=False): """Detect if the model vocabulary includes task ID tokens (A, B, C, D, E, F, G).""" if no_task_tag: return False task_tokens = ['A', 'B', 'C', 'D', 'E', 'F', 'G'] return all(token in stoi for token in task_tokens) def create_reverse_maps(valid_turns, node_and_direction_to_neighbor): """Create reverse direction maps for backward random walk sampling.""" valid_previous_turns = defaultdict(list) node_and_previous_direction_to_neighbors = defaultdict(list) for node, moves in valid_turns.items(): for move in moves: next_move = node_and_direction_to_neighbor[(node, move)] valid_previous_turns[next_move].append(move) node_and_previous_direction_to_neighbors[(next_move, move)].append(node) return valid_previous_turns, node_and_previous_direction_to_neighbors def sample_length_k_prefix_from_state(current_state, end_state, k, valid_previous_turns, node_and_previous_direction_to_neighbors, use_task_id=False, task_id='A', allow_cycles=False, no_task_tag=False): """Sample a reverse random walk prefix up to length k ending at current_state. Args: current_state: Current node state end_state: Target end node k: Maximum length of the prefix valid_previous_turns: Valid previous turns mapping node_and_previous_direction_to_neighbors: Node and direction to neighbors mapping use_task_id: Whether to prepend task ID to the prefix task_id: Task identifier to prepend (default: 'A') allow_cycles: If False (default), path is acyclic. If True, path can contain cycles. no_task_tag: Whether data does not contain task identifiers """ state = current_state direction_list = [] visited = {state} for _ in range(k): candidates = [] for direction in valid_previous_turns[state]: for prev_state in node_and_previous_direction_to_neighbors[(state, direction)]: if allow_cycles or prev_state not in visited: candidates.append((direction, prev_state)) if not candidates: break direction, prev_state = random.choice(candidates) direction_list.append(direction) state = prev_state visited.add(state) direction_list.append(str(end_state)) direction_list.append(str(state)) direction_list = direction_list[::-1] # Prepend task ID if multi-task support is enabled and no_task_tag is False if use_task_id and not no_task_tag: direction_list = [task_id] + direction_list return direction_list def encode(s, stoi): return [stoi[ch] for ch in s.split(" ")] def decode(l, itos): return " ".join(itos[i] for i in l) def pick_first_existing(candidates): for path in candidates: if os.path.exists(path): return path return candidates[0] def get_conditional_probability_of_suffixes_after_prefix(prefix, suffixes, model, stoi, itos, device, block_size, batch_size=32): prefix_len = len(prefix) input_ids = [] for suffix in suffixes: full_sequence = prefix + suffix input_ids.append(encode(" ".join(full_sequence), stoi)) padded_input_ids = [] attention_masks = [] for ids in input_ids: if len(ids) > block_size: ids = ids[:block_size] padding_length = block_size - len(ids) padded_ids = ids + [stoi.get('', 0)] * padding_length attention_mask = [1] * len(ids) + [0] * padding_length padded_input_ids.append(padded_ids) attention_masks.append(attention_mask) padded_input_ids = torch.tensor(padded_input_ids, dtype=torch.long, device=device) attention_masks = torch.tensor(attention_masks, dtype=torch.long, device=device) num_batches = (len(padded_input_ids) - 1) // batch_size + 1 logits_list = [] for i in range(num_batches): start_idx = i * batch_size end_idx = start_idx + batch_size with torch.no_grad(): logits, _ = model( padded_input_ids[start_idx:end_idx], targets=padded_input_ids[start_idx:end_idx] ) logits_list.append(logits) logits = torch.cat(logits_list, dim=0) probs = torch.softmax(logits, dim=-1) next_token_probs = torch.gather(probs[:, :-1], dim=-1, index=padded_input_ids[:, 1:].unsqueeze(-1))[:, :, 0] suffix_probs = [] for j, suffix in enumerate(suffixes): suffix_len = len(suffix) suffix_prob = next_token_probs[j, (prefix_len - 1):(prefix_len + suffix_len - 1)].cpu().numpy() suffix_probs.append(suffix_prob) return suffix_probs def sample_model_suffixes_from_prefix(prefix, model, stoi, itos, device, block_size, num_suffix_samples, valid_directions, task_id='A', no_task_tag=False, temperature=1.0): prefix_ids = torch.tensor([encode(" ".join(prefix), stoi)], device=device) max_new_tokens = max(1, block_size - len(prefix) - 5) suffixes = [] with torch.no_grad(): for _ in range(num_suffix_samples): output = model.generate( prefix_ids, max_new_tokens=max_new_tokens, temperature=temperature, top_k=len(stoi) ) generated_tokens = output[0, len(prefix_ids[0]):].tolist() suffix_str = decode(generated_tokens, itos) raw_tokens = suffix_str.split() suffix = [] if task_id == 'E': idx = 0 while idx < len(raw_tokens): d = raw_tokens[idx] if d in ['N', 'S', 'E', 'W']: if idx + 1 < len(raw_tokens) and raw_tokens[idx + 1] in ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']: suffix.extend([d, raw_tokens[idx + 1]]) idx += 2 else: break else: break else: for token in raw_tokens: if token in valid_directions: suffix.append(token) else: break if suffix: suffixes.append(suffix) return suffixes def get_all_suffixes_from_state(start_state, end_state, max_len, valid_turns, node_and_direction_to_neighbor): suffixes = [] stack = [(start_state, [], {start_state})] while stack: state, moves, visited = stack.pop() if state == end_state: suffixes.append(moves) continue if len(moves) == max_len: continue for direction in valid_turns[state]: next_state = node_and_direction_to_neighbor[(state, direction)] if next_state in visited: continue stack.append((next_state, moves + [direction], visited | {next_state})) return suffixes def check_task_e_path(G, gen_str, n, num_nodes, no_task_tag=False): """Validate a Task E path (pathfinding with label observations).""" TASK_TOKENS = {'A', 'B', 'C', 'D', 'E', 'F', 'G'} 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' # Parse direction-label pairs action_tokens = tokens[2 + task_offset:] if len(action_tokens) % 2 != 0: return 'syntax error' current_node = source total_step = 0 # Process pairs sequentially for i in range(0, len(action_tokens), 2): direction = action_tokens[i] target_label = action_tokens[i + 1] if direction not in ['N', 'S', 'E', 'W']: return 'syntax error' if target_label not in ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']: return 'syntax error' # Simulate movement for this pair found = False steps_in_segment = 0 max_steps = num_nodes + 5 while not found and steps_in_segment < max_steps: 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 if next_node < 0 or next_node >= num_nodes: return f'step {total_step} node {current_node} direction {direction} is illegal (boundary)' if not G.has_edge(str(current_node), str(next_node)): return f'step {total_step} node {current_node} direction {direction} is illegal (no edge)' current_node = next_node total_step += 1 steps_in_segment += 1 if G.nodes[str(current_node)]['label'] == target_label: found = True if not found: return f'step {total_step} could not find label {target_label} in direction {direction}' if current_node != target: return 'incorrect target node' return '' # ---- Task H (relative clockwise-index encoding) helpers ---- _TASK_H_CLOCKWISE_SCAN = { 'N': ['N', 'E', 'S', 'W'], 'E': ['E', 'S', 'W', 'N'], 'S': ['S', 'W', 'N', 'E'], 'W': ['W', 'N', 'E', 'S'], } def _task_h_feasible_dirs(G, node, facing, n, num_nodes): """Feasible directions at `node`, scanned clockwise from `facing` (Task H).""" delta = {'N': -n, 'S': n, 'E': 1, 'W': -1} feasible = [] for d in _TASK_H_CLOCKWISE_SCAN[facing]: neighbor = node + delta[d] if 0 <= neighbor < num_nodes and G.has_edge(str(node), str(neighbor)): feasible.append(d) return feasible def encode_task_h_indices(G, source, path_dirs, n, num_nodes, start_facing='E'): """Convert an absolute-direction path into Task H clockwise-index tokens. Returns (tokens, final_facing); (None, None) if a direction is infeasible. """ delta = {'N': -n, 'S': n, 'E': 1, 'W': -1} facing = start_facing current = int(source) tokens = [] for d in path_dirs: feasible = _task_h_feasible_dirs(G, current, facing, n, num_nodes) if d not in feasible: return None, None tokens.append(str(feasible.index(d) + 1)) current = current + delta[d] facing = d return tokens, facing def decode_task_h_indices(G, source, idx_tokens, n, num_nodes, start_facing='E'): """Decode Task H index tokens from a state into absolute directions. Returns (abs_dirs, ok); ok is False if any index is illegal at its step. """ delta = {'N': -n, 'S': n, 'E': 1, 'W': -1} facing = start_facing current = int(source) dirs = [] for tok in idx_tokens: if tok not in ['1', '2', '3', '4']: return dirs, False idx = int(tok) feasible = _task_h_feasible_dirs(G, current, facing, n, num_nodes) if idx < 1 or idx > len(feasible): return dirs, False d = feasible[idx - 1] current = current + delta[d] facing = d dirs.append(d) return dirs, True # ---- Task I (absolute clockwise-index encoding, FIXED North reference) helpers ---- # Like Task H but feasible edges are always scanned clockwise from a fixed # North reference (N->E->S->W) regardless of the last move, so there is NO # facing state: the walker's state is the current node alone. _TASK_I_FIXED_SCAN = ['N', 'E', 'S', 'W'] def _task_i_feasible_dirs(G, node, n, num_nodes): """Feasible directions at `node`, scanned clockwise from fixed North (Task I).""" delta = {'N': -n, 'S': n, 'E': 1, 'W': -1} feasible = [] for d in _TASK_I_FIXED_SCAN: neighbor = node + delta[d] if 0 <= neighbor < num_nodes and G.has_edge(str(node), str(neighbor)): feasible.append(d) return feasible def encode_task_i_indices(G, source, path_dirs, n, num_nodes): """Convert an absolute-direction path into Task I fixed-North clockwise-index tokens. Returns tokens, or None if a direction is infeasible. No facing state.""" delta = {'N': -n, 'S': n, 'E': 1, 'W': -1} current = int(source) tokens = [] for d in path_dirs: feasible = _task_i_feasible_dirs(G, current, n, num_nodes) if d not in feasible: return None tokens.append(str(feasible.index(d) + 1)) current = current + delta[d] return tokens def decode_task_i_indices(G, source, idx_tokens, n, num_nodes): """Decode Task I index tokens from a node into absolute directions. Returns (abs_dirs, ok); ok is False if any index is illegal at its step. """ delta = {'N': -n, 'S': n, 'E': 1, 'W': -1} current = int(source) dirs = [] for tok in idx_tokens: if tok not in ['1', '2', '3', '4']: return dirs, False idx = int(tok) feasible = _task_i_feasible_dirs(G, current, n, num_nodes) if idx < 1 or idx > len(feasible): return dirs, False d = feasible[idx - 1] current = current + delta[d] dirs.append(d) return dirs, True def is_suffix_valid(suffix, current_state, end_state, valid_turns, node_and_direction_to_neighbor, check_end=True, debug=False): for direction in suffix: if debug: print( f"is_suffix_valid step: direction={direction}, current_state={current_state}, valid_moves={valid_turns[current_state]}") if direction not in valid_turns[current_state]: return False current_state = node_and_direction_to_neighbor[(current_state, direction)] if check_end: return current_state == end_state else: return True def get_true_mn_boundary(valid_suffixes1, valid_suffixes2, current_state2, end_state2, valid_turns, node_and_direction_to_neighbor): boundary = set() difference = [s for s in valid_suffixes1 if s not in valid_suffixes2] for example in difference: for i in range(1, len(example) + 1): if not is_suffix_valid(example[:i], current_state2, end_state2, valid_turns, node_and_direction_to_neighbor): boundary.add(tuple(example[:i])) break return [list(x) for x in boundary] def get_distinction_precision(prefix1, prefix2, start_node1, end_node1, start_node2, end_node2, model, stoi, itos, device, block_size, num_suffix_samples, epsilon, valid_turns, node_and_direction_to_neighbor, valid_directions, task_id='A', debug=False, no_task_tag=False, G=None, n=0, num_nodes=0, temperature=1.0, orientation='E'): if debug: print("-" * 40) print("DEBUG get_distinction_precision") print(f"prefix1: {' '.join(prefix1)}") print(f"prefix2: {' '.join(prefix2)}") suffixes1 = sample_model_suffixes_from_prefix(prefix1, model, stoi, itos, device, block_size, num_suffix_samples, valid_directions, task_id=task_id, no_task_tag=no_task_tag, temperature=temperature) if not suffixes1: return None, None, None suffix1_probs_prefix2 = get_conditional_probability_of_suffixes_after_prefix(prefix2, suffixes1, model, stoi, itos, device, block_size) mn_boundary_model = [] for i, suffix_prob in enumerate(suffix1_probs_prefix2): for j, prob in enumerate(suffix_prob): if prob <= epsilon: if task_id == 'E': cut_len = j + 1 if cut_len % 2 != 0: cut_len -= 1 if cut_len > 0: mn_boundary_model.append(suffixes1[i][:cut_len]) else: mn_boundary_model.append(suffixes1[i][:j + 1]) break if not mn_boundary_model: return 1.0, suffixes1, suffix1_probs_prefix2 intersection = 0 for suffix in mn_boundary_model: if task_id == 'E': path_str = ' '.join(suffix) full_str1 = f"{start_node1} {end_node1} : {path_str}" valid1 = (check_task_e_path(G, full_str1, n, num_nodes, no_task_tag=True) == '') full_str2 = f"{start_node2} {end_node2} : {path_str}" valid2 = (check_task_e_path(G, full_str2, n, num_nodes, no_task_tag=True) == '') elif task_id == 'H': _, valid1 = decode_task_h_indices(G, start_node1, suffix, n, num_nodes, start_facing=orientation) _, valid2 = decode_task_h_indices(G, start_node2, suffix, n, num_nodes, start_facing=orientation) elif task_id == 'I': _, valid1 = decode_task_i_indices(G, start_node1, suffix, n, num_nodes) _, valid2 = decode_task_i_indices(G, start_node2, suffix, n, num_nodes) else: suffix_for_check = turns_to_directions(suffix, start_orientation=orientation) if task_id == 'C' else suffix valid1 = is_suffix_valid(suffix_for_check, start_node1, end_node1, valid_turns, node_and_direction_to_neighbor, False, debug=debug) valid2 = is_suffix_valid(suffix_for_check, start_node2, end_node2, valid_turns, node_and_direction_to_neighbor, False, debug=debug) if valid1 and not valid2: intersection += 1 return intersection / len(mn_boundary_model), suffixes1, suffix1_probs_prefix2 def get_distinction_recall(prefix1, prefix2, start_node1, end_node1, start_node2, end_node2, model, stoi, itos, device, block_size, max_suffix_length, epsilon, valid_turns, node_and_direction_to_neighbor, task_id='A', G=None, n=0, orientation='E', num_nodes=0): valid_suffixes1 = get_all_suffixes_from_state(start_node1, end_node1, max_suffix_length, valid_turns, node_and_direction_to_neighbor) valid_suffixes2 = get_all_suffixes_from_state(start_node2, end_node2, max_suffix_length, valid_turns, node_and_direction_to_neighbor) mn_boundary_world = get_true_mn_boundary(valid_suffixes1, valid_suffixes2, start_node2, end_node2, valid_turns, node_and_direction_to_neighbor) if len(mn_boundary_world) == 0: return 1.0 boundary_for_model = [] if task_id == 'C': boundary_for_model = [directions_to_turns(suffix, start_orientation=orientation) for suffix in mn_boundary_world] elif task_id == 'E': for suffix in mn_boundary_world: current = start_node1 path_nodes = [current] for d in suffix: if d == 'N': current -= n elif d == 'S': current += n elif d == 'E': current += 1 elif d == 'W': current -= 1 path_nodes.append(current) compressed = [] if suffix: run_dir = suffix[0] run_labels = [] for step_idx, d in enumerate(suffix): node_id = path_nodes[step_idx + 1] if str(node_id) in G.nodes: label = G.nodes[str(node_id)]['label'] if d != run_dir: if run_labels: target_L = run_labels[-1] for _ in range(run_labels.count(target_L)): compressed.extend([run_dir, target_L]) run_dir, run_labels = d, [label] else: run_labels.append(label) if run_labels: target_L = run_labels[-1] for _ in range(run_labels.count(target_L)): compressed.extend([run_dir, target_L]) boundary_for_model.append(compressed) elif task_id == 'H': for suffix in mn_boundary_world: tokens, _ = encode_task_h_indices(G, start_node1, suffix, n, num_nodes, start_facing=orientation) boundary_for_model.append(tokens if tokens is not None else []) elif task_id == 'I': for suffix in mn_boundary_world: tokens = encode_task_i_indices(G, start_node1, suffix, n, num_nodes) boundary_for_model.append(tokens if tokens is not None else []) else: boundary_for_model = mn_boundary_world boundary_for_model = [s for s in boundary_for_model if s] if not boundary_for_model: return 1.0 model_suffix_probs1 = get_conditional_probability_of_suffixes_after_prefix(prefix1, boundary_for_model, model, stoi, itos, device, block_size) model_suffix_probs2 = get_conditional_probability_of_suffixes_after_prefix(prefix2, boundary_for_model, model, stoi, itos, device, block_size) model_accepts1 = set([tuple(boundary_for_model[k]) for k, suffix in enumerate(boundary_for_model) if all(model_suffix_probs1[k] > epsilon)]) model_accepts2 = set([tuple(boundary_for_model[k]) for k, suffix in enumerate(boundary_for_model) if all(model_suffix_probs2[k] > epsilon)]) model_difference = model_accepts1.difference(model_accepts2) return len(model_difference) / len(mn_boundary_world) def parse_args(): parser = argparse.ArgumentParser(description='Distinction test for maze paths') parser.add_argument('--ckpt_iter', type=int, default=10000, help='Checkpoint iteration') parser.add_argument('--config', type=str, default='6_6_384', help='Model config') parser.add_argument('--model', type=str, default='transformer', choices=['transformer', 'transformer-nextlat', 'mamba', 'mamba2', 'gru', 'gated-deltanet'], help='Model architecture; selects out// and how the checkpoint is built.') 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('--device', type=str, default='cuda:0', help='Device to use') parser.add_argument('--num_suffix_samples', type=int, default=30, help='Number of suffix samples') parser.add_argument('--epsilon', type=float, default=0.01, help='Probability threshold') parser.add_argument('--temperature', type=float, default=1.0, help='Sampling temperature for suffix generation (default: 1.0)') parser.add_argument('--num_trials', type=int, default=100, help='Number of trials') parser.add_argument('--max_suffix_length', type=int, default=5, help='Max suffix length for recall') parser.add_argument('--debug', action='store_true', help='Print prefixes and node pairs inside get_distinction_precision') 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='C1', help='Task specification (e.g., A1, A1B1, A3B2, A1D1F1). Default: A1') parser.add_argument('--dist_tasks', type=str, default=None, help='Task specification for distinction prefix generation (e.g., A1, A1C1). Defaults to --tasks') 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('--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). "shortest" is not implemented yet.') # New argument for no task tag mode parser.add_argument('--no_task_tag', action='store_true', default=False, help='Data does not contain task identifiers (A, B, C, etc.). When enabled, model assumes data starts directly with node numbers/labels without task tags.') return parser.parse_args() def main(): args = parse_args() dataset = 'maze' ckpt_iter = args.ckpt_iter device = args.device 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) tasks_str = args.tasks tasks_tag = f"{tasks_str}_CL" if args.CL else tasks_str cl_mode = args.CL num_suffix_samples = args.num_suffix_samples epsilon = args.epsilon temperature = args.temperature num_trials = args.num_trials max_suffix_length = args.max_suffix_length debug = args.debug no_task_tag = args.no_task_tag allow_cycles = (args.path_type in ['RWc', 'RWs']) 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" graph_tag = f"{tasks_str}_CL" if cl_mode else tasks_str graph_tag = f"{graph_tag}_{path_type_tag}" if args.no_task_tag: graph_tag = f"{graph_tag}_NT" data_path = f'data/{dataset}/{num_nodes}' meta_path = pick_first_existing([ f'{data_path}/meta_{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'] block_size = meta['block_size'] if 'no_task_tag' in meta: no_task_tag = meta['no_task_tag'] print(f"Overriding no_task_tag from metadata: {no_task_tag}") use_task_id = detect_task_id_support(stoi, no_task_tag) # Use dist_tasks for prefix generation if specified, otherwise fall back to tasks dist_tasks_str = args.dist_tasks if args.dist_tasks is not None else tasks_str task_weights = parse_task_distribution(dist_tasks_str, default_task='A') if use_task_id: print(f"Task ID support detected. Sampling distinction prefix tasks using weights: {task_weights}") else: print(f"No task ID support detected. No task tag mode: {'Enabled' if no_task_tag else 'Disabled'}") nt_suffix = '_NT' if no_task_tag else '' model_type = args.model out_dir = f'out/{model_type.replace("-", "_")}/{dataset}_{config}_{num_nodes}{nt_suffix}/' # transformer-nextlat checkpoints carry an extra _NL suffix on the task tag. ckpt_tag = f"{tasks_tag}_NL" if model_type == 'transformer-nextlat' else tasks_tag if multitasks: candidate_ckpts = [ os.path.join(out_dir, f'{ckpt_iter}_ckpt_maze_{ckpt_tag}_{train_label}.pt'), os.path.join(out_dir, f'{ckpt_iter}_ckpt_maze_{ckpt_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') print(f"Loading model from {ckpt_path}...") checkpoint = torch.load(ckpt_path, map_location=device, weights_only=False) model, _ = build_model_from_checkpoint(checkpoint, model_type, device, local=args.local) 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' print(f"Loading maze graph from {maze_graph_path}...") G = nx.read_graphml(maze_graph_path) n = int(math.sqrt(num_nodes)) print("Building navigation maps from graph...") valid_turns = defaultdict(list) node_and_direction_to_neighbor = {} for node_str in G.nodes(): node = int(node_str) for neighbor_str in G.neighbors(node_str): neighbor = int(neighbor_str) row_diff = neighbor // n - node // n col_diff = neighbor % n - node % n if row_diff == -1 and col_diff == 0: direction = 'N' elif row_diff == 1 and col_diff == 0: direction = 'S' elif row_diff == 0 and col_diff == 1: direction = 'E' elif row_diff == 0 and col_diff == -1: direction = 'W' else: continue valid_turns[node].append(direction) node_and_direction_to_neighbor[(node, direction)] = neighbor for node in list(valid_turns.keys()): node_and_direction_to_neighbor[(node, 'end')] = 'end' node_and_direction_to_neighbor[('end', 'end')] = 'end' valid_previous_turns, node_and_previous_direction_to_neighbors = create_reverse_maps( valid_turns, node_and_direction_to_neighbor ) all_nodes = list(valid_turns.keys()) all_pairs = [] for start in all_nodes: for end in all_nodes: if start != end: all_pairs.append((start, end)) print(f"Found {len(all_nodes)} nodes with valid moves") print(f"Generated {len(all_pairs)} source-target pairs") def build_task_prefix(start_node, end_node, prefix_len, task_choice): raw_prefix = sample_length_k_prefix_from_state( start_node, end_node, prefix_len, valid_previous_turns, node_and_previous_direction_to_neighbors, use_task_id, task_choice, allow_cycles=allow_cycles, no_task_tag=no_task_tag ) if raw_prefix is None: return None if use_task_id and not no_task_tag: task_id_from_raw, start_tok, end_tok, *path_dirs = raw_prefix else: start_tok, end_tok, *path_dirs = raw_prefix final_orientation = None valid_dirs = {'N', 'S', 'E', 'W'} if task_choice == 'C': path_dirs = directions_to_turns(path_dirs) valid_dirs = {'L', 'R', 'F', 'T'} current = int(start_tok) orientation = 'E' 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} if cl_mode: augmented_dirs = [] for turn in path_dirs: augmented_dirs.append(turn) if turn in ['L', 'R']: label = G.nodes[str(current)]['label'] augmented_dirs.append(label) if turn == 'F': next_orientation = orientation elif turn == 'L': next_orientation = left_of[orientation] elif turn == 'R': next_orientation = right_of[orientation] else: next_orientation = opposite_of[orientation] current = current + delta[next_orientation] orientation = next_orientation path_dirs = augmented_dirs else: for turn in path_dirs: if turn == 'F': next_orientation = orientation elif turn == 'L': next_orientation = left_of[orientation] elif turn == 'R': next_orientation = right_of[orientation] else: next_orientation = opposite_of[orientation] current = current + delta[next_orientation] orientation = next_orientation final_orientation = orientation elif task_choice == 'E': current_node = int(start_tok) path_nodes = [current_node] for direction in path_dirs: 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 else: return None path_nodes.append(next_node) current_node = next_node compressed_tokens = [] run_dir = path_dirs[0] if path_dirs else '' run_labels = [] for step_idx, direction in enumerate(path_dirs): node_id = path_nodes[step_idx + 1] label = G.nodes[str(node_id)]['label'] if direction != run_dir: if run_labels: end_label = run_labels[-1] cnt = sum(1 for x in run_labels if x == end_label) for _ in range(cnt): compressed_tokens.append(run_dir) compressed_tokens.append(end_label) run_dir = direction run_labels = [label] else: run_labels.append(label) if run_labels: end_label = run_labels[-1] cnt = sum(1 for x in run_labels if x == end_label) for _ in range(cnt): compressed_tokens.append(run_dir) compressed_tokens.append(end_label) path_dirs = compressed_tokens # valid_dirs remains N/S/E/W, label pairs handled in sampling elif task_choice == 'H': h_tokens, final_orientation = encode_task_h_indices( G, int(start_tok), path_dirs, n, num_nodes, start_facing='E') if h_tokens is None: return None path_dirs = h_tokens valid_dirs = {'1', '2', '3', '4'} elif task_choice == 'I': i_tokens = encode_task_i_indices(G, int(start_tok), path_dirs, n, num_nodes) if i_tokens is None: return None path_dirs = i_tokens valid_dirs = {'1', '2', '3', '4'} # fixed North reference -> no facing, final_orientation stays None if use_task_id and not no_task_tag: prefix_tokens = [str(task_id_from_raw), str(start_tok), str(end_tok), ':'] + path_dirs else: prefix_tokens = [str(start_tok), str(end_tok), ':'] + path_dirs return prefix_tokens, valid_dirs, final_orientation def perform_single_distinction_test(): try: state_inds = np.random.choice(len(all_pairs), 2, replace=False) (start_node1, end_node1), (start_node2, end_node2) = all_pairs[state_inds[0]], all_pairs[state_inds[1]] max_prefix_len = block_size // 3 prefix_len = np.random.choice(range(1, min(max_prefix_len + 1, 50))) task_choice = sample_task(task_weights, {'A', 'C', 'E', 'H', 'I'}) prefix1_build = build_task_prefix(start_node1, end_node1, prefix_len, task_choice) if prefix1_build is None: return None prefix1, valid_directions, orientation1 = prefix1_build prefix2_build = build_task_prefix(start_node2, end_node2, prefix_len, task_choice) if prefix2_build is None: return None prefix2, _, orientation2 = prefix2_build if prefix1 == prefix2: return None if task_choice in ('C', 'H') and orientation1 != orientation2: return None precision, suffixes, suffix_probs = get_distinction_precision( prefix1, prefix2, start_node1, end_node1, start_node2, end_node2, model, stoi, itos, device, block_size, num_suffix_samples, epsilon, valid_turns, node_and_direction_to_neighbor, valid_directions, task_id=task_choice, debug=debug, no_task_tag=no_task_tag, G=G, n=n, num_nodes=num_nodes, temperature=temperature, orientation=orientation1 ) if precision is None: return None recall = get_distinction_recall( prefix1, prefix2, start_node1, end_node1, start_node2, end_node2, model, stoi, itos, device, block_size, max_suffix_length, epsilon, valid_turns, node_and_direction_to_neighbor, task_id=task_choice, G=G, n=n, orientation=orientation1, num_nodes=num_nodes ) return precision, recall, tuple(prefix1), tuple( prefix2), start_node1, end_node1, start_node2, end_node2, task_choice, suffixes, suffix_probs except Exception: return None # Track results separately by task task_results = defaultdict(lambda: {'precisions': [], 'recalls': [], 'trials': 0}) distinction_data = [] bar = tqdm(range(num_trials)) for trial in bar: result = perform_single_distinction_test() if result is None: continue precision, recall, prefix1, prefix2, start_node1, end_node1, start_node2, end_node2, task_choice, suffixes, suffix_probs = result # Add to task-specific lists task_results[task_choice]['precisions'].append(precision) task_results[task_choice]['recalls'].append(recall) task_results[task_choice]['trials'] += 1 distinction_data.append({ 'trial': trial + 1, 'precision': precision, 'recall': recall, 'prefix1': prefix1, 'prefix2': prefix2, 'start_node1': start_node1, 'end_node1': end_node1, 'start_node2': start_node2, 'end_node2': end_node2, 'task': task_choice, 'suffixes': suffixes, 'suffix_probs': suffix_probs }) # Calculate current global mean all_precisions = [] all_recalls = [] for t in task_results: all_precisions.extend(task_results[t]['precisions']) all_recalls.extend(task_results[t]['recalls']) if all_precisions: mean_precision = np.mean(all_precisions) mean_recall = np.mean(all_recalls) bar.set_description(f"P: {mean_precision:.3f} | R: {mean_recall:.3f}") print("\n" + "=" * 60) print("Distinction Test Results") print("=" * 60) # Temperature tag for filenames (only when temperature != 1) temp_tag = f't{temperature}' if temperature != 1 else '' if multitasks: output_filename = f"distinction_{tasks_tag}_{ckpt_iter}_{num_trials}_{temp_tag}.txt" data_filename = f"dist_data_{tasks_tag}_{ckpt_iter}_{num_trials}_{temp_tag}.txt" else: output_filename = f"distinction_{ckpt_iter}_{num_trials}_{temp_tag}.txt" data_filename = f"dist_data_{ckpt_iter}_{num_trials}_{temp_tag}.txt" output_path = os.path.join(out_dir, output_filename) data_path = os.path.join(out_dir, data_filename) with open(output_path, 'w') as f: f.write("=" * 60 + "\n") f.write("Distinction Test Results\n") f.write("=" * 60 + "\n") f.write(f"Config: {config}\n") f.write(f"Checkpoint iteration: {ckpt_iter}\n") f.write(f"Number of nodes: {num_nodes}\n") f.write(f"Number of trials: {num_trials}\n") f.write(f"Epsilon: {epsilon}\n") f.write(f"Number of suffix samples: {num_suffix_samples}\n") f.write(f"Max suffix length: {max_suffix_length}\n") f.write(f"No task tag mode: {'Enabled' if no_task_tag else 'Disabled'}\n") if multitasks: f.write(f"Task configuration: {tasks_str}\n") f.write(f"Distinction task configuration: {dist_tasks_str}\n") f.write("\n") # Per-task statistics all_precisions = [] all_recalls = [] sorted_tasks = sorted(task_results.keys()) for t in sorted_tasks: precisions = task_results[t]['precisions'] recalls = task_results[t]['recalls'] trials = task_results[t]['trials'] all_precisions.extend(precisions) all_recalls.extend(recalls) p_mean = np.mean(precisions) if precisions else 0.0 p_std = np.std(precisions) / np.sqrt(len(precisions)) if len(precisions) > 0 else 0.0 r_mean = np.mean(recalls) if recalls else 0.0 r_std = np.std(recalls) / np.sqrt(len(recalls)) if len(recalls) > 0 else 0.0 print(f"Task {t} (n={trials}):") print(f" Precision: {p_mean:.4f} (SE: {p_std:.4f})") print(f" Recall: {r_mean:.4f} (SE: {r_std:.4f})") f.write(f"Task {t} (n={trials}):\n") f.write(f" Precision: {p_mean:.4f} (SE: {p_std:.4f})\n") f.write(f" Recall: {r_mean:.4f} (SE: {r_std:.4f})\n") f.write("-" * 30 + "\n") # Overall statistics if all_precisions: overall_p_mean = np.mean(all_precisions) overall_p_std = np.std(all_precisions) / np.sqrt(len(all_precisions)) overall_r_mean = np.mean(all_recalls) overall_r_std = np.std(all_recalls) / np.sqrt(len(all_recalls)) print("=" * 60) print("OVERALL:") print(f" Precision: {overall_p_mean:.4f} (SE: {overall_p_std:.4f})") print(f" Recall: {overall_r_mean:.4f} (SE: {overall_r_std:.4f})") print("=" * 60 + "\n") f.write("=" * 60 + "\n") f.write("OVERALL:\n") f.write(f" Precision: {overall_p_mean:.4f} (SE: {overall_p_std:.4f})\n") f.write(f" Recall: {overall_r_mean:.4f} (SE: {overall_r_std:.4f})\n") f.write("=" * 60 + "\n") else: print("No valid trials completed.") f.write("No valid trials completed.\n") with open(data_path, 'w') as f: f.write("=" * 60 + "\n") f.write("Distinction Test Detailed Data\n") f.write("=" * 60 + "\n") f.write(f"Config: {config}\n") f.write(f"Checkpoint iteration: {ckpt_iter}\n") f.write(f"Number of nodes: {num_nodes}\n") f.write(f"Epsilon: {epsilon}\n") f.write(f"Number of suffix samples: {num_suffix_samples}\n") f.write(f"Max suffix length: {max_suffix_length}\n") f.write(f"No task tag mode: {'Enabled' if no_task_tag else 'Disabled'}\n") if multitasks: f.write(f"Task configuration: {tasks_str}\n") f.write(f"Distinction task configuration: {dist_tasks_str}\n") f.write("=" * 60 + "\n\n") for idx, data in enumerate(distinction_data): f.write(f"Iteration {idx + 1}:\n") f.write(f" Task: {data.get('task', 'A')}\n") f.write(f" Precision: {data['precision']:.4f}\n") f.write(f" Recall: {data['recall']:.4f}\n") f.write(f" Pair 1: current={data['start_node1']}, end={data['end_node1']}\n") f.write(f" Pair 2: current={data['start_node2']}, end={data['end_node2']}\n") f.write(f" prefix1: {' '.join(data['prefix1'])}\n") f.write(f" prefix2: {' '.join(data['prefix2'])}\n") f.write(f"\n") f.write(f" Suffix comparisons (from prefix1 vs probabilities after prefix2):\n") suffixes = data.get('suffixes', []) suffix_probs = data.get('suffix_probs', []) for suffix_idx, suffix in enumerate(suffixes): suffix_str = ' '.join(suffix) if suffix_idx < len(suffix_probs): probs = suffix_probs[suffix_idx] probs_str = ", ".join([f"{p:.3f}" for p in probs]) else: probs_str = "N/A" f.write(f" suffix_{suffix_idx}: {suffix_str}\n") f.write(f" suffix_{suffix_idx}_probs: [{probs_str}]\n") f.write(f"\n") f.write("\n") print(f"Summary results saved to {output_path}") print(f"Detailed data saved to {data_path}") if __name__ == "__main__": main()