Download scripts/modal_benchmark.py from peeache/maze-solving-qwen35: direct link, hf CLI and curl.
- Browser
- Download file 8.35 kB
-
https://huggingface.co/datasets/peeache/maze-solving-qwen35/resolve/main/scripts/modal_benchmark.py
- Command line
-
hf download hf://datasets/peeache/maze-solving-qwen35/scripts/modal_benchmark.py
-
curl -L -o modal_benchmark.py https://huggingface.co/datasets/peeache/maze-solving-qwen35/resolve/main/scripts/modal_benchmark.py
8.35 kB
| """Run the 13x13 difficulty benchmark on Qwen3.5-4B, as TEXT or as IMAGES. | |
| modal run scripts/modal_benchmark.py --mode text | |
| modal run scripts/modal_benchmark.py --mode image | |
| modal run scripts/modal_benchmark.py --mode image --think | |
| Same model, same mazes, same question, same scoring as the earlier | |
| Qwen3-4B-Instruct runs -- only the input format changes, which is the whole | |
| point of the comparison. Results land in data/benchmark. | |
| Notes on the setup: | |
| * Qwen3.5-4B is multimodal (its config carries a vision tower), so one | |
| model covers both modes. No second model, no size confound. | |
| * Thinking mode is off by default. See mm_runner for why. | |
| * The maze image is rendered inside the container from the same | |
| deterministic renderer used locally. | |
| """ | |
| import os | |
| from pathlib import Path | |
| import modal | |
| # Unique per run: two `modal run` invocations sharing one app name collide -- | |
| # when the first app stops it cancels the other's in-flight calls, killing | |
| # both mid-run (seen here, losing two part-finished 12-maze runs). Set | |
| # MAZE_RUN_TAG to run more than one of these at the same time. | |
| APP_NAME = "maze-lab-qwen35-" + os.environ.get("MAZE_RUN_TAG", "main") | |
| MODEL_ID = "Qwen/Qwen3.5-4B" | |
| # ~8GB in bf16 plus a vision tower and image tokens; A10 (24GB) is fine. | |
| GPU = "A10G" | |
| ROOT = Path(__file__).resolve().parents[1] | |
| PACKAGE = ROOT / "src" / "maze_lab" | |
| app = modal.App(APP_NAME) | |
| hf_cache = modal.Volume.from_name("maze-lab-hf-cache", create_if_missing=True) | |
| image = ( | |
| modal.Image.debian_slim(python_version="3.12") | |
| .pip_install( | |
| "torch>=2.4.0", | |
| "transformers", # unpinned on purpose: Qwen3.5 needs a recent release | |
| "accelerate>=1.0.0", | |
| "torchvision", # image transforms used by the processor | |
| "pillow>=10.0.0", # maze_image renders the maze | |
| "huggingface_hub>=0.25.0", | |
| ) | |
| .env({"HF_HOME": "/cache/hf"}) | |
| .add_local_dir(PACKAGE, remote_path="/root/maze_lab", | |
| ignore=["__pycache__", "**/__pycache__", "*.pyc"]) | |
| ) | |
| class Runner: | |
| def load(self): | |
| from maze_lab.mm_runner import load_model | |
| self.model, self.processor = load_model(MODEL_ID) | |
| hf_cache.commit() | |
| def solve(self, level: int, seed: int, mode: str = "text", sample: bool = False, | |
| max_tokens: int = 8192, fmt: str = "spaced", think: bool = False, | |
| labels: bool = True, answer: str = "string") -> dict: | |
| import time | |
| from maze_lab.benchmark import score, score_runs | |
| from maze_lab.difficulty import LEVEL_SPECS, analyse, build | |
| from maze_lab.mm_runner import extract_final_answer, generate | |
| from maze_lab.prompts import (MAZE_IMAGE_SYSTEM_PROMPT, | |
| MAZE_RUNS_IMAGE_SYSTEM_PROMPT, | |
| MAZE_RUNS_SYSTEM_PROMPT, MAZE_SYSTEM_PROMPT, | |
| maze_image_prompt, maze_presentation_prompt, | |
| maze_runs_image_prompt, maze_runs_prompt) | |
| maze = build(level, seed) | |
| st = analyse(maze) | |
| if answer not in ("string", "runs"): | |
| raise ValueError(f"answer must be 'string' or 'runs', got {answer!r}") | |
| as_runs = answer == "runs" | |
| if mode == "image": | |
| import io | |
| from PIL import Image | |
| from maze_lab.maze_image import render_png | |
| picture = Image.open(io.BytesIO(render_png(maze, labels=labels))).convert("RGB") | |
| text_part = maze_runs_image_prompt() if as_runs else maze_image_prompt() | |
| user = [{"type": "image", "image": picture}, | |
| {"type": "text", "text": text_part}] | |
| elif mode == "text": | |
| user = (maze_runs_prompt(maze, fmt) if as_runs | |
| else maze_presentation_prompt(maze, fmt)) | |
| else: | |
| raise ValueError(f"mode must be 'text' or 'image', got {mode!r}") | |
| # The system prompt has to match the input format. Sending the text | |
| # legend ("'#' = wall, '.' = open floor") alongside a picture told the | |
| # model a character grid existed when none was sent; replies then | |
| # quoted cells that were never there ("row 4: [5]=#") and, in one case, | |
| # "recall[ed]" a grid "in the user's initial description". That bug | |
| # confounded the first qwen35_image / qwen35_image_runs runs. | |
| system = ((MAZE_RUNS_IMAGE_SYSTEM_PROMPT if as_runs else MAZE_IMAGE_SYSTEM_PROMPT) | |
| if mode == "image" else | |
| (MAZE_RUNS_SYSTEM_PROMPT if as_runs else MAZE_SYSTEM_PROMPT)) | |
| messages = [{"role": "system", "content": system}, | |
| {"role": "user", "content": user}] | |
| t0 = time.time() | |
| reply = generate(self.model, self.processor, messages, | |
| cap=max_tokens, sample=sample, think=think) | |
| elapsed = time.time() - t0 | |
| return {"level": level, "level_name": LEVEL_SPECS[level].name, "seed": seed, | |
| "model": MODEL_ID, "mode": mode, "fmt": fmt if mode == "text" else "image", | |
| "think": think, "labels": labels if mode == "image" else None, | |
| "answer_format": answer, | |
| "optimal_moves": st["moves"], "decision_pts": st["decision_pts"], | |
| "deepest_wrong_turn": st["deepest_wrong_turn"], | |
| "seconds": round(elapsed, 1), "reply": reply, | |
| **((score_runs if as_runs else score)(maze, reply, extract_final_answer))} | |
| def main(mode: str = "text", levels: str = "1,2,3,4", sample: bool = False, | |
| max_tokens: int = 8192, fmt: str = "spaced", think: bool = False, | |
| labels: bool = True, answer: str = "string", out: str = ""): | |
| import json | |
| import sys | |
| sys.path.insert(0, str(ROOT / "src")) | |
| from maze_lab import difficulty | |
| wanted = {int(x) for x in levels.split(",")} | |
| jobs = [(lvl, seed, mode, sample, max_tokens, fmt, think, labels, answer) | |
| for lvl in sorted(difficulty.LEVELS) if lvl in wanted | |
| for seed in difficulty.LEVELS[lvl]] | |
| if not jobs: | |
| raise SystemExit(f"no mazes for levels {sorted(wanted)}") | |
| print(f"[qwen3.5] {len(jobs)} mazes on {GPU}, mode={mode}, " | |
| f"{'fmt=' + fmt + ', ' if mode == 'text' else f'labels={labels}, '}" | |
| f"think={think}, answer={answer}, max_tokens={max_tokens}") | |
| path = Path(out or f"data/benchmark/qwen35_{mode}" | |
| f"{'_runs' if answer == 'runs' else ''}{'_think' if think else ''}.json") | |
| path.parent.mkdir(parents=True, exist_ok=True) | |
| results = [] | |
| for r in Runner().solve.starmap(jobs): | |
| results.append(r) | |
| path.write_text(json.dumps(results, indent=2)) # save as we go, so a | |
| # crash keeps what ran | |
| mark = "PASS" if r["solved"] else "FAIL" | |
| detail = "" | |
| if not r["solved"]: | |
| detail = f" ({r['failure']}, {r['valid_prefix_len']} valid moves" | |
| detail += f", {r['dist_remaining']} from goal)" if r["dist_remaining"] is not None else ")" | |
| print(f" L{r['level']} {r['level_name']:<10} seed={r['seed']:<4} " | |
| f"{r['optimal_moves']:>2}mv/{r['decision_pts']}dp {mark}{detail} {r['seconds']}s", | |
| flush=True) | |
| print(f"\n[qwen3.5] pass rate by level (mode={mode})") | |
| for level in sorted({r["level"] for r in results}): | |
| got = [r for r in results if r["level"] == level] | |
| print(f" L{level} {difficulty.LEVEL_SPECS[level].name:<10} " | |
| f"{sum(r['solved'] for r in got)}/{len(got)}") | |
| print(f" overall {sum(r['solved'] for r in results)}/{len(results)}") | |
| path.write_text(json.dumps(results, indent=2)) | |
| print(f"[qwen3.5] wrote {path}") | |