import os import re 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.transformer_rope import GPTRoPEConfig, GPTRoPE 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, ) 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) elif ckpt_model_type == 'transformer-rope': if local and 'use_flash' in model_args: model_args['use_flash'] = False conf = GPTRoPEConfig(**model_args) model = GPTRoPE(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 check_maze_path(G, gen_str, n, num_nodes, no_task_tag=False): """ 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 (optional, for multi-task support) Directions: N (north/up), S (south/down), E (east/right), W (west/left) Returns: '' if path is correct error message otherwise """ tokens = [t for t in gen_str.split() if t != ':'] # Check if first token is a task ID (only if no_task_tag is False) 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 # Check basic syntax: need at least source and target (after task ID if present) 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' # Validate node IDs if source < 0 or source >= num_nodes or target < 0 or target >= num_nodes: return 'syntax error' # Extract direction sequence (everything after task_id, source and target) directions = tokens[2 + task_offset:] # Start from source node current_node = source # Follow each direction for i, direction in enumerate(directions): if direction not in ['N', 'S', 'E', 'W']: return 'syntax error' # Calculate next node based on direction next_node = None if direction == 'N': # North (up) next_node = current_node - n elif direction == 'S': # South (down) next_node = current_node + n elif direction == 'E': # East (right) next_node = current_node + 1 elif direction == 'W': # West (left) next_node = current_node - 1 # Check if next_node is valid if next_node is None or next_node < 0 or next_node >= num_nodes: return f'step {i} node {current_node} direction {direction} is illegal' # Check if edge exists in the graph if not G.has_edge(str(current_node), str(next_node)): return f'step {i} node {current_node} direction {direction} is illegal' # Move to next node current_node = next_node # Check if we reached the target if current_node != target: return 'incorrect target node' return '' def check_turn_path(G, gen_str, n, num_nodes, cl_mode=False, no_task_tag=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). """ 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' actions = tokens[2 + task_offset:] orientation = 'E' # starts facing east 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 = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'} 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: # 'T' 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' # In CL mode, after L or R, expect a node label for the current node (checked after direction validity) if cl_mode and action in ['L', 'R']: if action_idx + 1 >= len(actions): return 'syntax error' # missing label after L/R label_token = actions[action_idx + 1] if label_token not in node_labels: return 'syntax error' # expected a node label 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 # skip the label token orientation = next_orientation current_node = next_node action_idx += 1 step += 1 if current_node != target: return 'incorrect target node' return '' def check_task_e_path(G, gen_str, n, num_nodes, no_task_tag=False): """Validate a Task E path (pathfinding with label observations). Validation logic: - Parse direction-label pairs (e.g., N a, N b, E c) - Process each pair sequentially: "Move in direction D until a node with label L is found." - Any nodes encountered with labels != L are skipped over. - Once L is found, the segment for this pair ends at that node. - If boundary/no-edge is hit before finding L, it's an error. - After all pairs, must be at target. """ 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 # Cap max steps per segment to prevent infinite loops in cyclic graphs steps_in_segment = 0 max_steps = num_nodes + 5 while not found and steps_in_segment < max_steps: # Calculate next node 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 # Check bounds if next_node < 0 or next_node >= num_nodes: return f'step {total_step} node {current_node} direction {direction} is illegal (boundary)' # Check edge 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)' # Move current_node = next_node total_step += 1 steps_in_segment += 1 # Check label node_label = G.nodes[str(current_node)]['label'] if node_label == target_label: found = True if not found: return f'step {total_step} could not find label {target_label} in direction {direction}' # Check if we reached the target 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 check_task_h_path(G, gen_str, n, num_nodes, no_task_tag=False): """Validate a Task H path (relative clockwise-index encoding). The agent starts at source facing East. Each token is the 1-based index of the chosen direction among feasible edges, enumerated clockwise starting from the current facing. After moving, facing updates to the chosen direction. """ TASK_TOKENS = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'} 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:] delta = {'N': -n, 'S': n, 'E': 1, 'W': -1} facing = 'E' current_node = source for step, tok in enumerate(actions): if tok not in ['1', '2', '3', '4']: return 'syntax error' idx = int(tok) feasible = _task_h_feasible_dirs(G, current_node, facing, n, num_nodes) if idx < 1 or idx > len(feasible): return f'step {step} node {current_node} index {tok} is illegal' d = feasible[idx - 1] current_node = current_node + delta[d] facing = d if current_node != target: return 'incorrect target node' return '' # ---- 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 check_task_i_path(G, gen_str, n, num_nodes, no_task_tag=False): """Validate a Task I path (absolute clockwise-index encoding, fixed North). The agent starts at source. Each token is the 1-based index of the chosen direction among feasible edges, enumerated clockwise from a fixed North reference (N->E->S->W). There is no facing state. """ TASK_TOKENS = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I'} 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:] delta = {'N': -n, 'S': n, 'E': 1, 'W': -1} current_node = source for step, tok in enumerate(actions): if tok not in ['1', '2', '3', '4']: return 'syntax error' idx = int(tok) feasible = _task_i_feasible_dirs(G, current_node, n, num_nodes) if idx < 1 or idx > len(feasible): return f'step {step} node {current_node} index {tok} is illegal' d = feasible[idx - 1] current_node = current_node + delta[d] if current_node != target: return 'incorrect target node' return '' def validate_suffix(G, prefix, suffix, n, num_nodes, task_id, cl_mode=False, no_task_tag=False): """Validate if concatenating prefix and suffix forms a valid path. Args: G: The maze graph prefix: List of prefix tokens (e.g., ['A', '0', '5', 'E', 'S']) suffix: List of suffix tokens (e.g., ['E', 'S']) n: Grid size num_nodes: Total number of nodes task_id: Task identifier ('A', 'C', or 'E') cl_mode: Whether CL mode is enabled for Task C no_task_tag: Whether data does not contain task identifiers Returns: '' if valid, error message otherwise """ # Concatenate prefix and suffix into a full path string full_path = ' '.join(list(prefix) + list(suffix)) # Calculate prefix direction count (steps before suffix) task_offset = 0 if no_task_tag else (1 if task_id in ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I'] else 0) has_colon = 1 if ':' in prefix else 0 if task_id == 'E': # For Task E, count direction-label pairs # Prefix format: [task_id, source, target, ':', dir1, label1, dir2, label2, ...] # or without task tag: [source, target, ':', dir1, label1, dir2, label2, ...] prefix_pairs = len(prefix) - 2 - task_offset - has_colon if prefix_pairs % 2 != 0: return 'syntax error' prefix_direction_count = prefix_pairs // 2 else: prefix_direction_count = len(prefix) - 2 - task_offset - has_colon if task_id == 'A': error = check_maze_path(G, full_path, n, num_nodes, no_task_tag=no_task_tag) elif task_id == 'C': error = check_turn_path(G, full_path, n, num_nodes, cl_mode=cl_mode, no_task_tag=no_task_tag) elif task_id == 'E': error = check_task_e_path(G, full_path, n, num_nodes, no_task_tag=no_task_tag) elif task_id == 'H': error = check_task_h_path(G, full_path, n, num_nodes, no_task_tag=no_task_tag) elif task_id == 'I': error = check_task_i_path(G, full_path, n, num_nodes, no_task_tag=no_task_tag) else: # Fallback to maze path check error = check_maze_path(G, full_path, n, num_nodes, no_task_tag=no_task_tag) # Adjust step numbers to be relative to suffix (for detailed diagnostics) if 'is illegal' in error: match = re.search(r'step (\d+)', error) if match: full_step = int(match.group(1)) suffix_step = full_step - prefix_direction_count # Replace the step number with suffix-relative step error = re.sub(r'step \d+', f'step {suffix_step}', error) return error 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): # Collect candidate (direction, prev_state) pairs 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 no candidates exist, stop early and use the partial walk if not candidates: break direction, prev_state = random.choice(candidates) direction_list.append(direction) state = prev_state visited.add(state) # Append end_node and current state, then reverse to get forward order 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): """Encode a string (space-separated tokens) into token IDs.""" ss = s.split(" ") encoded_string = [stoi[ch] for ch in ss] return encoded_string def decode(l, itos): """Decode token IDs back to space-separated string.""" dec = "" for i in l: dec = dec + itos[i] + " " return dec[:-1] 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): """ Compute the conditional probability of each suffix given a prefix. Returns a list of probability arrays for each suffix. """ prefix_len = len(prefix) max_suffix_len = max(len(suffix) for suffix in suffixes) input_ids = [] for suffix in suffixes: full_sequence = prefix + suffix encoded_seq = encode(" ".join(full_sequence), stoi) input_ids.append(encoded_seq) # Pad input_ids to the same length padded_input_ids = [] attention_masks = [] for ids in input_ids: # Truncate or pad to block_size 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) # Get logits from model 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(): # Use model forward with targets to get full-sequence logits (no attention mask support) 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) # Get probabilities of next tokens in the suffix part # For each position in the suffix, gather the probability of the actual next token next_token_probs = torch.gather(probs[:, :-1], dim=-1, index=padded_input_ids[:, 1:].unsqueeze(-1))[:, :, 0] # Extract suffix probabilities (skip the prefix tokens) num_suffixes = len(suffixes) suffix_probs = [] for j in range(num_suffixes): suffix_len = len(suffixes[j]) # Probabilities from position (prefix_len-1) to (prefix_len + suffix_len - 1) 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 parse_args(): parser = argparse.ArgumentParser(description='Compression 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-rope', '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('--use_untrained_model', action='store_true', help='Use untrained model') 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 for file naming (e.g., A1, A1B1, A3B2, A1D1F1). Default: A1') parser.add_argument('--cmpr_tasks', type=str, default=None, help='Task specification for compression prefix generation (e.g., A1, A1C1). If not specified, uses --tasks value. Syntax same as --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 num_suffix_samples = args.num_suffix_samples epsilon = args.epsilon temperature = args.temperature num_trials = args.num_trials 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 no_task_tag = args.no_task_tag # Get the no_task_tag flag # Parse path_type for filenames (RWc = cyclic, RWa = acyclic, RWs = single source) allow_cycles = (args.path_type in ['RWc', 'RWs']) path_type_tag = args.path_type tasks_tag = f"{tasks_tag}_{path_type_tag}" # Add _NT_ tag to tasks_tag when no_task_tag is enabled if args.no_task_tag: tasks_tag = f"{tasks_tag}_NT" # Graph tag includes path type to match generated graph files graph_tag = f"{tasks_str}_CL" if cl_mode else tasks_str graph_tag = f"{graph_tag}_{path_type_tag}" # Add _NT_ tag to graph_tag when no_task_tag is enabled if args.no_task_tag: graph_tag = f"{graph_tag}_NT" # Load meta 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'] # Override no_task_tag from metadata if available if 'no_task_tag' in meta: no_task_tag = meta['no_task_tag'] print(f"Overriding no_task_tag from metadata: {no_task_tag}") # Detect if model supports task IDs (considering no_task_tag flag) use_task_id = detect_task_id_support(stoi, no_task_tag) # Use cmpr_tasks for prefix generation if specified, otherwise fall back to tasks cmpr_tasks_str = args.cmpr_tasks if args.cmpr_tasks is not None else tasks_str task_weights = parse_task_distribution(cmpr_tasks_str, default_task='A') task_id = 'A' if use_task_id: print(f"Task ID support detected. Sampling compression prefix tasks using weights: {task_weights}") if args.cmpr_tasks is not None: print(f" (cmpr_tasks={cmpr_tasks_str} overrides tasks={tasks_str} for prefix generation)") else: print(f"No task ID support detected. No task tag mode: {'Enabled' if no_task_tag else 'Disabled'}") # Load model checkpoint 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) # Load maze graph 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)) # Build valid_turns and node_and_direction_to_neighbor from graph 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) # Determine direction based on node positions in grid 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: # Non-standard edge, skip or handle continue valid_turns[node].append(direction) node_and_direction_to_neighbor[(node, direction)] = neighbor # Add end sentinels all_nodes = list(valid_turns.keys()) for node in all_nodes: node_and_direction_to_neighbor[(node, 'end')] = 'end' node_and_direction_to_neighbor[('end', 'end')] = 'end' # Create reverse maps valid_previous_turns, node_and_previous_direction_to_neighbors = create_reverse_maps( valid_turns, node_and_direction_to_neighbor ) # Generate all_pairs (source, target) from nodes with valid moves 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") # Helpers to build task-specific prefixes def build_task_prefix(start_node, end_node, prefix_len, task_id_local): """Build a task-specific prefix. Returns: For Task A: (prefix_tokens, valid_dirs, None, None) For Task C: (prefix_tokens, valid_dirs, final_orientation, None) For Task E: (prefix_tokens, valid_dir_label_pairs, None, None) None if prefix generation fails """ 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_id_local, 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 = None valid_dir_label_pairs = None if task_id_local == 'C': path_dirs = directions_to_turns(path_dirs) valid_dirs = {'L', 'R', 'F', 'T'} # Track orientation as we walk through the turns 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} # In CL mode, insert node labels after L/R turns if cl_mode: augmented_dirs = [] for turn in path_dirs: augmented_dirs.append(turn) if turn in ['L', 'R']: # Add label of current node (before moving) label = G.nodes[str(current)]['label'] augmented_dirs.append(label) # Update orientation and move if turn == 'F': next_orientation = orientation elif turn == 'L': next_orientation = left_of[orientation] elif turn == 'R': next_orientation = right_of[orientation] else: # 'T' next_orientation = opposite_of[orientation] current = current + delta[next_orientation] orientation = next_orientation path_dirs = augmented_dirs else: # Still need to track final orientation even without CL mode 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: # 'T' next_orientation = opposite_of[orientation] current = current + delta[next_orientation] orientation = next_orientation final_orientation = orientation elif task_id_local == 'E': # For Task E, we need to convert direction sequence to direction-label pairs # Follow the same compression rules as in create_multitask_maze.py # 1. Split only by turns (direction changes) # 2. For each straight segment, end_label is the label at the last node of this segment # 3. In that segment, keep ONLY positions whose label == end_label # 4. Emit (dir, end_label) once for each kept position # First, simulate the path to get labels 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 # Invalid direction path_nodes.append(next_node) current_node = next_node # Now apply Task E compression rules 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'] # Direction changed => flush previous run, then start new 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) # Start new run run_dir = direction run_labels = [label] else: # Still same direction => accumulate run_labels.append(label) # Flush last run 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_dir_label_pairs = [] for dir_token in ['N', 'S', 'E', 'W']: for label_token in ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']: valid_dir_label_pairs.append((dir_token, label_token)) elif task_id_local == 'H': # Convert absolute directions to Task H clockwise-index tokens, # tracking the final orientation (facing) at the merge node. 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_id_local == 'I': # Convert absolute directions to Task I fixed-North index tokens. # No facing state, so final_orientation stays None. 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'} else: # Task A or other direction-based tasks valid_dirs = {'N', 'S', 'E', 'W'} 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, valid_dir_label_pairs # Compression test def perform_single_compression_test(): """Perform one trial of the compression test with random walk prefixes.""" try: state_ind = np.random.choice(len(all_pairs)) start_node, end_node = all_pairs[state_ind] # Random prefix length (leave room for prefix + suffix) max_prefix_len = block_size // 3 prefix_len = np.random.choice(range(1, min(max_prefix_len + 1, 50))) # Sample task based on task_weights (includes A, C, E, H) task_choice = sample_task(task_weights, {'A', 'C', 'E', 'H', 'I'}) prefix1_build = build_task_prefix(start_node, end_node, prefix_len, task_choice) if prefix1_build is None: return None prefix1, valid_directions, orientation1, valid_dir_label_pairs = prefix1_build prefix2_build = build_task_prefix(start_node, end_node, prefix_len, task_choice) if prefix2_build is None: return None prefix2, _, orientation2, _ = prefix2_build if prefix1 == prefix2: return None # For Task C/H, both prefixes must end with the same orientation # so they have equivalent suffix distributions if task_choice in ('C', 'H') and orientation1 != orientation2: return None prefix1_ids = torch.tensor([encode(" ".join(prefix1), stoi)], device=device) max_new_tokens = block_size - len(prefix1) - 5 if max_new_tokens <= 0: return None with torch.no_grad(): suffixes = [] suffix_validations = [] # Store validation results for each suffix for _ in range(num_suffix_samples): # Implement step-by-step generation with epsilon cutoff curr_idx = prefix1_ids for _step in range(max_new_tokens): # Forward the model to get logits for the last token idx_cond = curr_idx if curr_idx.size(1) <= block_size else curr_idx[:, -block_size:] logits, _ = model(idx_cond) logits = logits[:, -1, :] / temperature # Apply epsilon cutoff: zero out probabilities < epsilon probs = torch.softmax(logits, dim=-1) mask = probs < epsilon logits[mask] = -float('Inf') # Re-calculate probabilities and sample probs = torch.softmax(logits, dim=-1) idx_next = torch.multinomial(probs, num_samples=1) curr_idx = torch.cat((curr_idx, idx_next), dim=1) # Break if newline/end of sequence token is sampled if idx_next.item() == stoi.get('\n', -1): break generated_tokens = curr_idx[0, len(prefix1_ids[0]):].tolist() suffix_str = decode(generated_tokens, itos) suffix = suffix_str.split() # Filter suffix based on task type filtered_suffix = [] if task_choice == 'E': # For Task E, filter for direction-label pairs # Need to pair tokens as they come i = 0 while i < len(suffix): if suffix[i] in ['N', 'S', 'E', 'W']: if i + 1 < len(suffix) and suffix[i + 1] in ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']: filtered_suffix.append(suffix[i]) filtered_suffix.append(suffix[i + 1]) i += 2 else: break else: break else: # For Task A, C or H, filter based on valid directions for token in suffix: if task_choice == 'C': if token in ['L', 'R', 'F', 'T']: filtered_suffix.append(token) else: break elif task_choice == 'H': if token in ['1', '2', '3', '4']: filtered_suffix.append(token) else: break elif task_choice == 'I': if token in ['1', '2', '3', '4']: filtered_suffix.append(token) else: break else: # Task A if token in ['N', 'S', 'E', 'W']: filtered_suffix.append(token) else: break if filtered_suffix: suffixes.append(filtered_suffix) # Validate suffix when concatenated with prefix1 error = validate_suffix(G, prefix1, filtered_suffix, n, num_nodes, task_choice, cl_mode=cl_mode, no_task_tag=no_task_tag) suffix_validations.append(error) # '' if valid, error message if not if not suffixes: return None suffix_probs_prefix2 = get_conditional_probability_of_suffixes_after_prefix( prefix2, suffixes, model, stoi, itos, device, block_size ) precision = all([all(suffix_probs_prefix2[i] > epsilon) for i in range(len(suffixes))]) return float(precision), tuple(prefix1), tuple(prefix2), tuple([tuple(s) for s in suffixes]), suffix_probs_prefix2, start_node, end_node, task_choice, suffix_validations except Exception: return None # Run trials state_pair_to_prefixes_to_score = defaultdict(lambda: defaultdict(list)) compression_data = [] # Store detailed data for output file # Statistics for suffix validation - per task task_stats = { 'A': {'total_suffixes': 0, 'valid_suffixes': 0, 'total_trials': 0, 'precisions': []}, 'C': {'total_suffixes': 0, 'valid_suffixes': 0, 'total_trials': 0, 'precisions': []}, 'E': {'total_suffixes': 0, 'valid_suffixes': 0, 'total_trials': 0, 'precisions': []}, 'H': {'total_suffixes': 0, 'valid_suffixes': 0, 'total_trials': 0, 'precisions': []} } total_suffixes = 0 valid_suffixes = 0 error_categories = defaultdict(int) # Count errors by category iteration_accuracies = [] # Track accuracy per iteration bar = tqdm(range(num_trials)) for trial in bar: result = perform_single_compression_test() if result is not None: precision, prefix1, prefix2, suffixes, suffix_probs, start_node, end_node, task_choice, suffix_validations = result state_pair_to_prefixes_to_score[(start_node, end_node)][(prefix1, prefix2)].append(precision) # Update task-specific statistics if task_choice in task_stats: task_stats[task_choice]['precisions'].append(precision) task_stats[task_choice]['total_trials'] += 1 # Update suffix validation stats for this task iter_total = len(suffix_validations) iter_valid = sum(1 for v in suffix_validations if v == '') task_stats[task_choice]['total_suffixes'] += iter_total task_stats[task_choice]['valid_suffixes'] += iter_valid # Track overall suffix validation statistics iter_total = len(suffix_validations) iter_valid = sum(1 for v in suffix_validations if v == '') total_suffixes += iter_total valid_suffixes += iter_valid # Track accuracy for this iteration iter_accuracy = iter_valid / iter_total if iter_total > 0 else 0.0 iteration_accuracies.append(iter_accuracy) # Count error categories (aggregate illegal directions) for error in suffix_validations: if error != '': if 'is illegal' in error: error_categories['illegal direction'] += 1 elif 'incorrect label' in error: error_categories['incorrect label'] += 1 else: error_categories[error] += 1 # Store detailed data compression_data.append({ 'prefix1': prefix1, 'prefix2': prefix2, 'suffixes': suffixes, 'suffix_probs': suffix_probs, 'start_node': start_node, 'end_node': end_node, 'task_id': task_choice, 'suffix_validations': suffix_validations }) # Compute running stats average_precisions = [ [np.mean(v) for k, v in inner_dict.items()] for k1, inner_dict in state_pair_to_prefixes_to_score.items() ] running_suffix_accuracy = valid_suffixes / total_suffixes if total_suffixes > 0 else 0.0 if average_precisions: average_precisions = [item for sublist in average_precisions for item in sublist] mean_precision = np.mean(average_precisions) std = np.std(average_precisions) / np.sqrt(len(average_precisions) + 1e-6) bar.set_description(f"Precision: {mean_precision:.3f} | Suffix Acc: {running_suffix_accuracy:.3f}") # Final summary print("\n" + "=" * 60) print("Compression Test Results") print("=" * 60) # Prepare output filenames (use ckpt_iter and num_trials as requested) # Temperature tag for filenames (only when temperature != 1) temp_tag = f't{temperature}' if temperature != 1 else '' if multitasks: output_filename = f"compression_{tasks_tag}_{ckpt_iter}_{num_trials}_{temp_tag}.txt" data_filename = f"cpress_data_{tasks_tag}_{ckpt_iter}_{num_trials}_{temp_tag}.txt" else: output_filename = f"compression_{ckpt_iter}_{num_trials}_{temp_tag}.txt" data_filename = f"cpress_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) # Calculate overall suffix validation statistics final_suffix_accuracy = valid_suffixes / total_suffixes if total_suffixes > 0 else 0.0 avg_iteration_accuracy = np.mean(iteration_accuracies) if iteration_accuracies else 0.0 if state_pair_to_prefixes_to_score: average_precisions = [ [np.mean(v) for k, v in inner_dict.items()] for k1, inner_dict in state_pair_to_prefixes_to_score.items() ] average_precisions = [item for sublist in average_precisions for item in sublist] mean_precision = np.mean(average_precisions) std = np.std(average_precisions) / np.sqrt(len(average_precisions) + 1e-6) # Print to console print(f"Mean compression precision: {mean_precision:.4f}") print(f"Standard error: {std:.4f}") print(f"Total valid trials: {len(average_precisions)}") # Print task-specific statistics print("\nTask-specific statistics:") for task_id, stats in task_stats.items(): if stats['total_trials'] > 0: task_precision = np.mean(stats['precisions']) if stats['precisions'] else 0.0 task_suffix_acc = stats['valid_suffixes'] / stats['total_suffixes'] if stats[ 'total_suffixes'] > 0 else 0.0 print(f" Task {task_id}:") print(f" Trials: {stats['total_trials']}") print(f" Precision: {task_precision:.4f}") print( f" Suffix accuracy: {task_suffix_acc:.4f} ({stats['valid_suffixes']}/{stats['total_suffixes']})") print("-" * 60) print("Overall Suffix Validation Statistics:") print(f" Total suffixes generated: {total_suffixes}") print(f" Valid suffixes: {valid_suffixes}") print(f" Invalid suffixes: {total_suffixes - valid_suffixes}") print(f" Average accuracy per iteration: {avg_iteration_accuracy:.4f}") print(f" Final overall accuracy: {final_suffix_accuracy:.4f}") if error_categories: print(" Error categories:") for error, count in sorted(error_categories.items(), key=lambda x: -x[1]): print(f" {error}: {count}") print("=" * 60 + "\n") # Save summary to file with open(output_path, 'w') as f: f.write("=" * 60 + "\n") f.write("Compression 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"No task tag mode: {'Enabled' if no_task_tag else 'Disabled'}\n") if multitasks: f.write(f"Training data task configuration: {tasks_str}\n") f.write(f"Compression test task configuration: {cmpr_tasks_str}\n") f.write("\n") f.write(f"Mean compression precision: {mean_precision:.4f}\n") f.write(f"Standard error: {std:.4f}\n") f.write(f"Total valid trials: {len(average_precisions)}\n") # Save task-specific statistics f.write("\nTask-specific statistics:\n") for task_id, stats in task_stats.items(): if stats['total_trials'] > 0: task_precision = np.mean(stats['precisions']) if stats['precisions'] else 0.0 task_suffix_acc = stats['valid_suffixes'] / stats['total_suffixes'] if stats[ 'total_suffixes'] > 0 else 0.0 f.write(f" Task {task_id}:\n") f.write(f" Trials: {stats['total_trials']}\n") f.write(f" Precision: {task_precision:.4f}\n") f.write( f" Suffix accuracy: {task_suffix_acc:.4f} ({stats['valid_suffixes']}/{stats['total_suffixes']})\n") f.write("-" * 60 + "\n") f.write("Overall Suffix Validation Statistics:\n") f.write(f" Total suffixes generated: {total_suffixes}\n") f.write(f" Valid suffixes: {valid_suffixes}\n") f.write(f" Invalid suffixes: {total_suffixes - valid_suffixes}\n") f.write(f" Average accuracy per iteration: {avg_iteration_accuracy:.4f}\n") f.write(f" Final overall accuracy: {final_suffix_accuracy:.4f}\n") if error_categories: f.write(" Error categories:\n") for error, count in sorted(error_categories.items(), key=lambda x: -x[1]): f.write(f" {error}: {count}\n") f.write("=" * 60 + "\n") # Save detailed data to file with open(data_path, 'w') as f: f.write("=" * 60 + "\n") f.write("Compression 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"No task tag mode: {'Enabled' if no_task_tag else 'Disabled'}\n") if multitasks: f.write(f"Training data task configuration: {tasks_str}\n") f.write(f"Compression test task configuration: {cmpr_tasks_str}\n") f.write("=" * 60 + "\n\n") for idx, data in enumerate(compression_data): # Calculate iteration accuracy iter_validations = data.get('suffix_validations', []) iter_valid = sum(1 for v in iter_validations if v == '') iter_total = len(iter_validations) iter_acc = iter_valid / iter_total if iter_total > 0 else 0.0 f.write(f"Iteration {idx + 1}:\n") f.write(f" Task: {data.get('task_id', 'A')}\n") f.write(f" Merge node: {data['start_node']}\n") f.write(f" Target node: {data['end_node']}\n") f.write(f" prefix1: {' '.join(data['prefix1'])}\n") f.write(f" prefix2: {' '.join(data['prefix2'])}\n") f.write(f" Iteration suffix accuracy: {iter_acc:.4f} ({iter_valid}/{iter_total})\n") f.write(f"\n") # Write sampled suffixes with their probability vectors side by side f.write(f" Suffix comparisons (from prefix1 vs probabilities after prefix2):\n") for suffix_idx, suffix in enumerate(data['suffixes']): suffix_str = ' '.join(suffix) # Format probabilities to 3 decimal places probs = data['suffix_probs'][suffix_idx] probs_str = ", ".join([f"{p:.3f}" for p in probs]) # Get validation result validation_error = iter_validations[suffix_idx] if suffix_idx < len(iter_validations) else '' validation_status = "VALID" if validation_error == '' else f"ERROR: {validation_error}" f.write(f" suffix_{suffix_idx}: {suffix_str}\n") f.write(f" suffix_{suffix_idx}_probs: [{probs_str}]\n") f.write(f" suffix_{suffix_idx}_validation: {validation_status}\n") f.write(f"\n") f.write("\n") print(f"Detailed data saved to {data_path}") print(f"Results saved to {output_path}") else: print("No valid trials completed.") print("=" * 60 + "\n") if __name__ == "__main__": main()