WorldModelForMaze / data /maze /prepare_multitask_minigpt.py
Kalso42's picture
Upload folder using huggingface_hub
34e468d verified
Raw
History Blame Contribute Delete
13.2 kB
import os
import sys
import pickle
import numpy as np
import re
import argparse
from tqdm import tqdm
# Ensure project root is importable when running this script directly
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..')))
from cli_utils import parse_count, format_count
parser = argparse.ArgumentParser(description='Create the multitask dataset based on the given parameters.')
parser.add_argument('--num_nodes', type=int, default=100, help='Number of nodes in the graph')
parser.add_argument('--num_train_dataset', type=parse_count, default='10M',
help='Number of training data entries to use (supports K/M/B, default: 50000)')
parser.add_argument('--num_test_dataset', type=parse_count, default=10000,
help='Number of test data entries to use (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='Enable Task C label mode (append node labels after L/R turns) and add _CL_ in filenames')
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).')
# Arguments for task tag handling
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 included in vocabulary and data parsing will skip task tags.')
parser.add_argument('--both', action='store_true', default=False,
help='Process both versions (with and without task tags). When set, --no_task_tag is ignored and two sets of bin files and meta files are produced.')
parser.add_argument('--num_labels', type=int, default=10,
help='Number of distinct node labels (default: 10). Must match the value used in data generation.')
parser.add_argument('--num_workers', type=int, default=1,
help='Number of parallel worker processes for encoding (default: 1 = serial). Uses fork; requires Linux/macOS.')
args = parser.parse_args()
num_nodes = args.num_nodes
tasks_str = args.tasks
tasks_tag_base = f"{tasks_str}_CL" if args.CL else tasks_str
# Add path type tag for filenames
path_type_tag = args.path_type
tasks_tag_base = f"{tasks_tag_base}_{path_type_tag}"
# Include num_labels in tag when non-default (match create_multitask_maze.py)
if args.num_labels != 10:
tasks_tag_base = f"{tasks_tag_base}_L{args.num_labels}"
train_label = format_count(args.num_train_dataset)
test_label = format_count(args.num_test_dataset)
num_labels = args.num_labels
def first_existing(paths):
for p in paths:
if os.path.exists(p):
return p
return paths[0]
def process_data_for_tag_mode(no_task_tag_mode, tasks_tag_suffix=""):
"""Process data for a specific task tag mode."""
# Construct tasks_tag for this mode
if no_task_tag_mode:
tasks_tag = f"{tasks_tag_base}_NT"
if tasks_tag_suffix:
tasks_tag = f"{tasks_tag}_{tasks_tag_suffix}"
else:
tasks_tag = tasks_tag_base
if tasks_tag_suffix:
tasks_tag = f"{tasks_tag}_{tasks_tag_suffix}"
# Find input files
train_file_path = first_existing([
os.path.join(os.path.dirname(__file__), f'{args.num_nodes}/train_{tasks_tag}_{train_label}.txt'),
os.path.join(os.path.dirname(__file__), f'{args.num_nodes}/train_{tasks_tag}_{args.num_train_dataset}.txt'),
os.path.join(os.path.dirname(__file__), f'{args.num_nodes}/train_{tasks_str}_{train_label}.txt'),
os.path.join(os.path.dirname(__file__), f'{args.num_nodes}/train_{tasks_str}_{args.num_train_dataset}.txt'),
])
val_file_path = first_existing([
os.path.join(os.path.dirname(__file__), f'{args.num_nodes}/test_{tasks_tag}_{test_label}.txt'),
os.path.join(os.path.dirname(__file__), f'{args.num_nodes}/test_{tasks_tag}_{args.num_test_dataset}.txt'),
os.path.join(os.path.dirname(__file__), f'{args.num_nodes}/test_{tasks_str}_{test_label}.txt'),
os.path.join(os.path.dirname(__file__), f'{args.num_nodes}/test_{tasks_str}_{args.num_test_dataset}.txt'),
])
print(f"\nProcessing mode: {'Without task tags' if no_task_tag_mode else 'With task tags'}")
print(f"Training file: {train_file_path}")
print(f"Test file: {val_file_path}")
with open(train_file_path, 'r') as f:
train_data = f.read()
print(f"length of train dataset in characters: {len(train_data):,}")
with open(val_file_path, 'r') as f:
val_data = f.read()
print(f"length of val dataset in characters: {len(val_data):,}")
all_data = train_data + val_data
chars = sorted(list(find_characters(all_data)))
direction_tokens = ['N', 'S', 'E', 'W', 'L', 'R', 'F', 'T']
# Only include task tokens if no_task_tag_mode is False
task_tokens = [] if no_task_tag_mode else ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I']
label_tokens = ([chr(ord('a') + i) for i in range(num_labels)] if num_labels <= 26
else [f'l{i}' for i in range(num_labels)])
label_tokens.append('/') # separator token for neighbor labels
special_tokens = [':']
# Adjust vocab_size calculation
vocab_size = num_nodes + 2 + len(direction_tokens) + len(task_tokens) + len(label_tokens) + len(special_tokens)
print("all the unique characters:", ' '.join(chars))
print(f"vocab size: {vocab_size:,}")
print(f"No task tag mode: {'Enabled' if no_task_tag_mode else 'Disabled'}")
stoi = {}
itos = {}
for i in range(num_nodes):
stoi[str(i)] = i + 2
itos[i + 2] = str(i)
base = 2 + num_nodes
for idx, tok in enumerate(direction_tokens):
stoi[tok] = base + idx
itos[base + idx] = tok
# Only add task tokens to vocabulary if no_task_tag_mode is False
if not no_task_tag_mode:
base = 2 + num_nodes + len(direction_tokens)
for idx, tok in enumerate(task_tokens):
stoi[tok] = base + idx
itos[base + idx] = tok
base = 2 + num_nodes + len(direction_tokens) + len(task_tokens)
else:
base = 2 + num_nodes + len(direction_tokens)
for idx, tok in enumerate(label_tokens):
stoi[tok] = base + idx
itos[base + idx] = tok
base = base + len(label_tokens)
for idx, tok in enumerate(special_tokens):
stoi[tok] = base + idx
itos[base + idx] = tok
stoi['[PAD]'] = 0
itos[0] = '[PAD]'
stoi['\n'] = 1
itos[1] = '\n'
def encode(s):
ss = s.split(" ")
return [stoi[ch] for ch in ss]
def decode(l):
return ' '.join(itos[i] for i in l)
# Calculate block_size with theoretical minimum
n = int(num_nodes ** 0.5) # grid size
if no_task_tag_mode:
theoretical_min_tokens = num_nodes + 3
else:
theoretical_min_tokens = num_nodes + 4
theoretical_min_block_size = (theoretical_min_tokens // 32 + 1) * 32
nw = args.num_workers
def get_block_size(s, desc="scan block size"):
split_text = s.split('\n')
if nw and nw > 1 and len(split_text) > 0:
import multiprocessing as mp
chunk_size = max(1, min(20000, len(split_text) // (nw * 50) or 1))
chunks = _chunk_list(split_text, chunk_size)
ctx = mp.get_context('fork')
bs = 0
with ctx.Pool(processes=nw) as pool:
with tqdm(total=len(split_text), desc=desc) as pbar:
for r in pool.imap_unordered(_prep_max_len_batch, chunks):
if r > bs:
bs = r
pbar.update(chunk_size if pbar.n + chunk_size <= len(split_text)
else len(split_text) - pbar.n)
return bs
# Serial
bs = 0
for st in tqdm(split_text, desc=desc):
if st != "":
enc_str = encode(st) + [1]
bs = max(bs, len(enc_str))
return bs
data_block_size = (max(get_block_size(train_data, desc="scan train block size"),
get_block_size(val_data, desc="scan val block size")) // 32 + 1) * 32
block_size = max(theoretical_min_block_size, data_block_size)
print(
f"the block size is {block_size} (theoretical min: {theoretical_min_block_size}, data-based: {data_block_size})")
def process_reasoning(s, desc="encode"):
split_text = s.split('\n')
if nw and nw > 1 and len(split_text) > 0:
import multiprocessing as mp
chunk_size = max(1, min(10000, len(split_text) // (nw * 100) or 1))
chunks = _chunk_list(split_text, chunk_size)
ctx = mp.get_context('fork')
ret = []
with ctx.Pool(processes=nw,
initializer=_prep_worker_init,
initargs=(stoi, block_size)) as pool:
with tqdm(total=len(split_text), desc=desc) as pbar:
# Use imap (ordered) to preserve original line order in output.
for i, r in enumerate(pool.imap(_prep_encode_batch, chunks)):
ret.extend(r)
step = len(chunks[i])
pbar.update(step)
return ret
# Serial
ret = []
for st in tqdm(split_text, desc=desc):
if st != "":
enc_str = encode(st) + [1]
ret += enc_str + [0] * (block_size + 1 - len(enc_str))
return ret
train_ids = process_reasoning(train_data, desc="encode train")
val_ids = process_reasoning(val_data, desc="encode val")
print(f"train has {len(train_ids):,} tokens")
print(f"val has {len(val_ids):,} tokens")
train_ids = np.array(train_ids, dtype=np.uint16)
val_ids = np.array(val_ids, dtype=np.uint16)
# Save bin files with appropriate tag
train_ids.tofile(os.path.join(os.path.dirname(__file__), f'{args.num_nodes}/train_{tasks_tag}_{train_label}.bin'))
val_ids.tofile(os.path.join(os.path.dirname(__file__), f'{args.num_nodes}/val_{tasks_tag}_{test_label}.bin'))
unreachable = 'x' in chars
simple_format = ':' not in chars
meta = {
'unreachable': unreachable,
'simple_format': simple_format,
'block_size': block_size,
'vocab_size': vocab_size,
'itos': itos,
'stoi': stoi,
'no_task_tag': no_task_tag_mode,
}
print(stoi)
print(itos)
with open(os.path.join(os.path.dirname(__file__), f'{args.num_nodes}/meta_{tasks_tag}.pkl'), 'wb') as f:
pickle.dump(meta, f)
print(f"Saved files with tag: {tasks_tag}")
return tasks_tag
def find_characters(data_string):
pattern = r'\d+|\D'
matches = re.findall(pattern, data_string)
return set(matches)
# ---- Parallel worker helpers (must be at module scope for pickling) ----
_W_STOI = None
_W_BLOCK_SIZE = None
def _prep_worker_init(stoi_arg, block_size_arg):
global _W_STOI, _W_BLOCK_SIZE
_W_STOI = stoi_arg
_W_BLOCK_SIZE = block_size_arg
def _prep_max_len_batch(lines):
"""Return the max encoded length (tokens + EOL) over a batch of lines."""
bs = 0
for st in lines:
if st == "":
continue
# encoded length = number of space-separated tokens + 1 (EOL token)
L = st.count(" ") + 2
if L > bs:
bs = L
return bs
def _prep_encode_batch(lines):
"""Encode + pad a batch of lines; returns a flat list of token IDs."""
stoi = _W_STOI
bs1 = _W_BLOCK_SIZE + 1
out = []
for st in lines:
if st == "":
continue
enc = [stoi[ch] for ch in st.split(" ")]
enc.append(1)
out.extend(enc)
out.extend([0] * (bs1 - len(enc)))
return out
def _chunk_list(lst, chunk_size):
return [lst[i:i + chunk_size] for i in range(0, len(lst), chunk_size)]
# Main execution
if args.both:
# Process both versions
print("=" * 60)
print("Generating both with-tag and without-tag versions")
print("=" * 60)
# Process with task tags
process_data_for_tag_mode(no_task_tag_mode=False)
# Process without task tags
process_data_for_tag_mode(no_task_tag_mode=True)
print("=" * 60)
print("Successfully generated both with-tag and without-tag datasets.")
print("=" * 60)
else:
# Original logic: generate only one version based on no_task_tag
process_data_for_tag_mode(no_task_tag_mode=args.no_task_tag)