"""stepmold on a GPU: run an example pack on Qwen3 8B with Hugging Face ZeroGPU. The companion to the static stepmold Space (huggingface.co/spaces/ahkamboh/stepmold). When a visitor there picks "HF GPU", the page calls `run_pack` here through @gradio/client. One call walks the whole pack inside one GPU allocation, and every step's JSON schema is enforced during decoding by xgrammar, the same grammar engine the in-browser mode uses. stepmold itself is unchanged: the pinned copy in stepmold-bundle.json is written to disk at startup, exactly as the static Space writes it into Pyodide, and walk.py is the same file. For a local test with no GPU, set STEPMOLD_BACKEND=openai and point it at any OpenAI-compatible endpoint (STEPMOLD_BASE_URL, STEPMOLD_MODEL_NAME, and a key in STEPMOLD_API_KEY). Nothing in this Space holds a key. """ import functools import json import os import queue import sys import tempfile import threading import gradio as gr try: import spaces except ImportError: # a local run without the ZeroGPU package spaces = None HERE = os.path.dirname(os.path.abspath(__file__)) MODEL_ID = "Qwen/Qwen3-8B" BACKEND = os.environ.get("STEPMOLD_BACKEND", "hf") MAX_INPUT_CHARS = 20000 def _unpack_bundle(): """Write the pinned stepmold copy and its example packs to disk and import from there.""" root = os.path.join(tempfile.gettempdir(), "stepmold-gpu") with open(os.path.join(HERE, "stepmold-bundle.json"), encoding="utf-8") as handle: files = json.load(handle)["files"] for path, text in files.items(): full = os.path.join(root, path) os.makedirs(os.path.dirname(full), exist_ok=True) with open(full, "w", encoding="utf-8") as out: out.write(text) sys.path.insert(0, root) os.environ["STEPMOLD_EXAMPLES"] = os.path.join(root, "examples") _unpack_bundle() import walk # noqa: E402 the bundle has to be on sys.path first CATALOG = {pack["dir"]: pack for pack in json.loads(walk.catalog())["packs"]} # ----------------------------------------------------------------------------- model if BACKEND == "hf": import torch import xgrammar as xgr from transformers import AutoModelForCausalLM, AutoTokenizer, GenerationConfig from xgrammar.contrib.hf import LogitsProcessor LABEL = "Qwen3 8B on Hugging Face's GPU" TOKENIZER = AutoTokenizer.from_pretrained(MODEL_ID) # On ZeroGPU the model goes to cuda here, at import; a real GPU is attached only # inside the @spaces.GPU function below. MODEL = AutoModelForCausalLM.from_pretrained(MODEL_ID, dtype=torch.bfloat16) MODEL.to("cuda") MODEL.eval() COMPILER = xgr.GrammarCompiler( xgr.TokenizerInfo.from_huggingface(TOKENIZER, vocab_size=MODEL.config.vocab_size)) STOP = MODEL.generation_config.eos_token_id PAD = TOKENIZER.pad_token_id if TOKENIZER.pad_token_id is not None else STOP @functools.lru_cache(maxsize=None) def compiled(schema_json): # Compact JSON only: free whitespace is where a constrained small model can loop. return COMPILER.compile_json_schema(schema_json, strict_mode=True, any_whitespace=False) # Every grammar in every pack, compiled now on the CPU so no GPU second is spent on it. for pack in CATALOG.values(): for node in pack["nodes"]: if node.get("grammar"): compiled(json.dumps(node["grammar"], sort_keys=True)) class QwenOnGPU: """stepmold's Model protocol over transformers, with the schema enforced per token.""" def generate(self, prompt, grammar=None, max_tokens=512, sampling=None): # Thinking off: stepmold budgets tokens for the answer, and a two-stage step # asks for its notes in a call of its own. text = TOKENIZER.apply_chat_template( [{"role": "user", "content": prompt}], tokenize=False, add_generation_prompt=True, enable_thinking=False) inputs = TOKENIZER(text, return_tensors="pt").to("cuda") temperature = sampling.temperature if sampling is not None else 0.0 if temperature and temperature > 0: if sampling.seed is not None: torch.manual_seed(sampling.seed) config = GenerationConfig(max_new_tokens=max_tokens, do_sample=True, temperature=temperature, top_p=1.0, top_k=0, eos_token_id=STOP, pad_token_id=PAD) else: config = GenerationConfig(max_new_tokens=max_tokens, do_sample=False, eos_token_id=STOP, pad_token_id=PAD) schema = grammar.get("schema") if isinstance(grammar, dict) and "schema" in grammar else grammar processors = [] if schema is not None: processors.append(LogitsProcessor(compiled(json.dumps(schema, sort_keys=True)))) with torch.inference_mode(): output = MODEL.generate(**inputs, generation_config=config, logits_processor=processors) new_tokens = output[0][inputs["input_ids"].shape[1]:] return TOKENIZER.decode(new_tokens, skip_special_tokens=True).strip() MODEL_FOR_RUN = QwenOnGPU() elif BACKEND == "openai": from stepmold.backends.openai_compat import OpenAICompatModel LABEL = "%s (local test)" % os.environ["STEPMOLD_MODEL_NAME"] MODEL_FOR_RUN = OpenAICompatModel( base_url=os.environ["STEPMOLD_BASE_URL"], model=os.environ["STEPMOLD_MODEL_NAME"], reasoning_reserve=int(os.environ.get("STEPMOLD_REASONING_RESERVE", "0"))) else: raise SystemExit("STEPMOLD_BACKEND must be 'hf' or 'openai', got %r" % BACKEND) # ---------------------------------------------------------------------------- the run def gpu_seconds(pack, inputs_json, case_index): """How much GPU time to ask ZeroGPU for: enough for each AI step to retry once. A shorter request queues sooner and fits more often in a visitor's daily quota. """ steps = sum(1 for node in CATALOG.get(pack, {}).get("nodes", []) if node["type"] == "generate") return min(120, 15 + 8 * steps) def _on_gpu(function): return spaces.GPU(duration=gpu_seconds)(function) if spaces is not None else function def _problem(pack, inputs_json): if pack not in CATALOG: return "no example pack named %r" % pack if len(inputs_json or "") > MAX_INPUT_CHARS: return "the input is longer than %d characters" % MAX_INPUT_CHARS try: json.loads(inputs_json) except ValueError: return "the input is not valid JSON" return None @_on_gpu def run_pack(pack, inputs_json, case_index): """Walk one example pack on the model. Yields `{"progress": ...}` as each model call starts, so a page can draw the steps as they happen, and then the whole walk. The walk runs in a thread of its own because stepmold calls the model and waits; this generator only passes the news along. """ problem = _problem(pack, inputs_json) if problem: yield {"error": problem} return index = int(case_index) if case_index not in (None, "") and int(case_index) >= 0 else None news = queue.Queue() finished = {} def walk_pack(): try: finished["result"] = json.loads( walk.run_model(pack, inputs_json, index, MODEL_FOR_RUN, LABEL, on_call=news.put)) except Exception as exc: # whatever the walk itself did not turn into a result finished["result"] = {"error": "%s: %s" % (type(exc).__name__, exc)} finally: news.put(None) threading.Thread(target=walk_pack, daemon=True).start() while True: call = news.get() if call is None: break yield {"progress": call} yield finished["result"] # --------------------------------------------------------------------------------- UI def gold_input(pack, case_index): cases = CATALOG[pack]["cases"] index = int(case_index or 0) return json.dumps(cases[index]["input"] if 0 <= index < len(cases) else {}, indent=2) with gr.Blocks(title="stepmold on a GPU") as demo: gr.Markdown( "# stepmold on a GPU\n" "Runs a stepmold example pack on **Qwen3 8B** with Hugging Face ZeroGPU. Every step's " "answer is held to its JSON schema while it is generated, then checked by stepmold " "before it is saved. The full demo, with the step-by-step view, is " "[ahkamboh/stepmold](https://huggingface.co/spaces/ahkamboh/stepmold).") with gr.Row(): pack_box = gr.Dropdown(sorted(CATALOG), value="support_triage", label="Pack") case_box = gr.Number(value=0, precision=0, minimum=0, label="Example (0 is the first)") input_box = gr.Code(value=gold_input("support_triage", 0), language="json", label="Input") run_button = gr.Button("Run on the GPU", variant="primary") result_box = gr.JSON(label="Result") run_button.click(run_pack, [pack_box, input_box, case_box], result_box, api_name="run_pack") pack_box.change(gold_input, [pack_box, case_box], input_box, api_visibility="private") case_box.change(gold_input, [pack_box, case_box], input_box, api_visibility="private") demo.queue(default_concurrency_limit=1).launch()