#!/usr/bin/env python3 """ PART 1 (CPU ONLY): Generate prompts + check available data ============================================================ No GPU needed. Run this first to prepare everything. """ import json, random, string from pathlib import Path from google.colab import drive drive.mount("/content/drive", force_remount=False) OUT = Path("/content/drive/MyDrive/topohd_scaled_gib") OUT.mkdir(exist_ok=True, parents=True) print("=" * 65) print("PART 1: Generate Prompts + Check Data") print("=" * 65) # ---- Check what direction files exist ---- print("\n[1/2] Checking available direction files ...") import numpy as np DIRS_PATHS = { "vista_nullu": Path("/content/drive/MyDrive/topohd_vista_nullu/directions.npz"), "illusion": Path("/content/drive/MyDrive/topohd_illusion/subspaces.npz"), "contrastive": Path("/content/drive/MyDrive/topohd_contrastive_valid/subspaces_3methods.npz"), "exp5_generic": Path("/content/drive/MyDrive/topohd_exp5/generic_geometry.npz"), "exp6_perturb": Path("/content/drive/MyDrive/topohd_exp6/perturb_directions.npz"), } TARGET_LAYERS = [8, 16, 24, 32] available_methods = {} random_basis = None HDIM = None for source_name, path in DIRS_PATHS.items(): if path.exists(): print(f" FOUND: {path}") data = np.load(path) print(f" Keys: {list(data.files)[:10]}{'...' if len(data.files) > 10 else ''}") if "random_basis" in data and random_basis is None: random_basis = data["random_basis"] HDIM = random_basis.shape[1] if "HDIM" in data and HDIM is None: HDIM = int(data["HDIM"][0]) # Extract methods for key in data.files: if key in ["random_basis", "HDIM"]: continue for l in TARGET_LAYERS: suffix = f"_{l}" if key.endswith(suffix): mname = key[:-len(suffix)] if mname not in available_methods: available_methods[mname] = set() available_methods[mname].add(l) else: print(f" MISSING: {path}") print(f"\n HDIM: {HDIM}") print(f" Available methods ({len(available_methods)}):") for m, layers in sorted(available_methods.items()): print(f" {m:<25} layers: {sorted(layers)}") if random_basis is not None: print(f" Random basis: {random_basis.shape}") # Save metadata meta = { "HDIM": HDIM, "methods": {m: sorted(list(ls)) for m, ls in available_methods.items()}, "sources_found": [str(p) for n, p in DIRS_PATHS.items() if p.exists()], } with open(OUT / "data_check.json", "w") as f: json.dump(meta, f, indent=2) # ---- Generate 1000 prompts per type ---- print(f"\n[2/2] Generating 1000 prompts per type ...") SCENES = [ "kitchen", "bedroom", "bathroom", "living room", "office", "classroom", "restaurant", "park", "beach", "street", "farm", "zoo", "airport", "hospital", "library", "market", "harbor", "forest", "mountain trail", "garden", "playground", "parking lot", "stadium", "museum", "train station", "bus stop", "rooftop", "basement", "garage", "backyard", "swimming pool", "gym", "coffee shop", "bookstore", "pet store", "flower shop", "bakery", "butcher shop", "laundromat", "bank", "church", "temple", "school hallway", "art studio", "workshop", "warehouse", "factory", "lobby", "balcony", "attic", ] OBJECTS = [ "table", "chair", "lamp", "couch", "television", "refrigerator", "oven", "sink", "toilet", "bed", "desk", "bookshelf", "clock", "vase", "plant", "dog", "cat", "bird", "horse", "cow", "car", "bus", "truck", "bicycle", "motorcycle", "airplane", "boat", "train", "traffic light", "fire hydrant", "bench", "umbrella", "backpack", "suitcase", "bottle", "cup", "fork", "knife", "spoon", "bowl", "banana", "apple", "sandwich", "pizza", "cake", "donut", "broccoli", "carrot", "hot dog", "surfboard", "skateboard", "tennis racket", "kite", "baseball bat", "frisbee", "skis", "snowboard", "teddy bear", "toothbrush", "laptop", "keyboard", "mouse", "cell phone", "microwave", "toaster", "scissors", "book", "remote", "wine glass", "potted plant", "dining table", "curtains", "pillow", "blanket", "mirror", "painting", "rug", "candle", "guitar", ] TEMPLATES_VIS = [ "A {scene} with {o1}, {o2}, and {o3}.", "A photograph of a {scene} containing {o1} and {o2}.", "A {scene} scene with {o1}, {o2}, {o3}, and {o4}.", "Inside a {scene}, there is {o1} next to {o2}.", "A {scene} with {o1} on the left and {o2} on the right.", "A busy {scene} full of {o1} and {o2}.", "A quiet {scene} with {o1} and {o2} nearby.", "{o1}, {o2}, and {o3} arranged in a {scene}.", "A large {scene} featuring {o1} beside {o2}.", "A small {scene} with {o1}, {o2}, and a {o3}.", ] TOPICS = [ "photosynthesis", "evolution", "gravity", "magnetism", "electricity", "the water cycle", "plate tectonics", "climate change", "DNA replication", "cellular respiration", "the immune system", "nuclear fusion", "quantum mechanics", "thermodynamics", "organic chemistry", "the French Revolution", "World War Two", "the Roman Empire", "the Renaissance", "the Industrial Revolution", "ancient Egypt", "the Cold War", "medieval Europe", "the Silk Road", "colonialism", "democracy", "capitalism", "socialism", "globalization", "inflation", "supply and demand", "monetary policy", "fiscal policy", "trade deficits", "the stock market", "blockchain", "artificial intelligence", "machine learning", "computer networking", "encryption", "operating systems", "databases", "cloud computing", "cybersecurity", "software engineering", "antibiotics", "vaccines", "gene therapy", "stem cells", "the nervous system", ] TEMPLATES_FACT = [ "Explain how {t} works.", "What is {t} and why does it matter?", "Describe the process of {t}.", "What are the principles behind {t}?", "How does {t} affect daily life?", "What is the history of {t}?", "Explain {t} simply.", "What are the key parts of {t}?", "How was {t} discovered?", "What are current debates about {t}?", ] CONCEPTS = [ "the Pythagorean theorem", "the quadratic formula", "the fundamental theorem of calculus", "Euler's identity", "the prime number theorem", "the central limit theorem", "Bayes theorem", "the binomial theorem", "Taylor series", "Fourier transforms", "eigenvalues", "eigenvectors", "group theory", "ring theory", "topology", "differential equations", "partial derivatives", "integration by parts", "the chain rule", "L'Hopital's rule", "the mean value theorem", "mathematical induction", "proof by contradiction", "modular arithmetic", "complex numbers", "matrix multiplication", "determinants", "vector spaces", "linear transformations", "inner product spaces", "metric spaces", "Banach spaces", "Hilbert spaces", "measure theory", "probability axioms", "Markov chains", "graph theory", "combinatorics", "number theory", "the Riemann hypothesis", "Fermat's last theorem", "the Goldbach conjecture", "Godel's incompleteness theorems", "the axiom of choice", "Zorn's lemma", "singular value decomposition", "the Jordan normal form", "the spectral theorem", "the Hahn-Banach theorem", "Cauchy sequences", "uniform convergence", ] TEMPLATES_MATH = [ "Prove {c}.", "Explain {c} and its significance.", "Derive {c} from first principles.", "What is {c}?", "State and explain {c}.", "How is {c} used in practice?", "Give an example of {c}.", "What prerequisites does {c} need?", "Compare {c} with related results.", "What is the intuition behind {c}?", ] def gen_visual(n, seed=42): rng = random.Random(seed) out = set() attempts = 0 while len(out) < n and attempts < n * 20: t = rng.choice(TEMPLATES_VIS) s = rng.choice(SCENES) os_ = rng.sample(OBJECTS, 4) p = t.format(scene=s, o1=os_[0], o2=os_[1], o3=os_[2], o4=os_[3]) out.add(p) attempts += 1 # If not enough unique, add numbered variants out = list(out) i = 0 while len(out) < n: out.append(out[i % len(out)] + f" Scene {len(out)}.") i += 1 return out[:n] def gen_factual(n, seed=42): rng = random.Random(seed) out = set() attempts = 0 while len(out) < n and attempts < n * 20: t = rng.choice(TEMPLATES_FACT) topic = rng.choice(TOPICS) out.add(t.format(t=topic)) attempts += 1 out = list(out) i = 0 while len(out) < n: out.append(out[i % len(out)] + f" Part {len(out)}.") i += 1 return out[:n] def gen_math(n, seed=42): rng = random.Random(seed) out = set() attempts = 0 while len(out) < n and attempts < n * 20: t = rng.choice(TEMPLATES_MATH) c = rng.choice(CONCEPTS) out.add(t.format(c=c)) attempts += 1 out = list(out) i = 0 while len(out) < n: out.append(out[i % len(out)] + f" Part {len(out)}.") i += 1 return out[:n] def gen_gibberish(n, seed=42): rng = random.Random(seed) out = [] for _ in range(n): nw = rng.randint(4, 8) words = [''.join(rng.choices(string.ascii_lowercase, k=rng.randint(3, 7))) for _ in range(nw)] out.append(' '.join(words) + '.') return out N = 1000 PROMPTS_FILE = OUT / "prompts_1000.json" # Load existing prompts if any if PROMPTS_FILE.exists(): with open(PROMPTS_FILE) as f: prompts = json.load(f) print(f" Loaded existing prompts file") else: prompts = {} generators = { "visual": gen_visual, "factual": gen_factual, "math": gen_math, "gibberish": gen_gibberish, } for ptype, gen_fn in generators.items(): existing = len(prompts.get(ptype, [])) if existing >= N: print(f" {ptype}: already have {existing} prompts. Skipping.") continue print(f" {ptype}: generating {N} prompts ...") prompts[ptype] = gen_fn(N) # Save after each type completes with open(PROMPTS_FILE, "w") as f: json.dump(prompts, f) print(f" Saved {len(prompts[ptype])} {ptype} prompts to disk") print(f" Example: '{prompts[ptype][0][:70]}...'") print(f" Saved data check to {OUT}/data_check.json") print(f"\n Next: run PART 2 (GPU) with scaled_gibberish_gpu.py")