Spaces:
Running on Zero
Running on Zero
Download app.py from hugging-apps/inkling-2-mini-3d-coder: direct link, hf CLI and curl.
- Browser
- Download file 15.2 kB
-
https://huggingface.co/spaces/hugging-apps/inkling-2-mini-3d-coder/resolve/main/app.py
- Command line
-
hf download hf://spaces/hugging-apps/inkling-2-mini-3d-coder/app.py
-
curl -L -o app.py https://huggingface.co/spaces/hugging-apps/inkling-2-mini-3d-coder/resolve/main/app.py
15.2 kB
| """Inkling 2 Mini-3D-Coder: text -> interactive Three.js scene, on ZeroGPU. | |
| The fine-tune (ccore/Inkling-2-Mini-3D-Coder, a LoRA merged into thinkingmachines/Inkling-2-Mini) currently ships only | |
| as GGUF, so this Space runs the Q8_0 GGUF on llama.cpp (llama-cpp-python built with CUDA for the Blackwell ZeroGPU | |
| slice). Scenes are long generations (reasoning + a full HTML file), so the generation is split into consecutive GPU | |
| calls; each call resumes from the text generated so far. | |
| """ | |
| import ctypes | |
| import html as html_lib | |
| import importlib | |
| import importlib.util | |
| import os | |
| import re | |
| import site | |
| import subprocess | |
| import sys | |
| import tempfile | |
| import time | |
| # The CUDA build of llama-cpp-python ships in this repo (requirements.txt is installed before repo files exist). | |
| WHEEL = os.path.join(os.path.dirname(os.path.abspath(__file__)), "wheels", "llama_cpp_python-0.3.38-py3-none-linux_x86_64.whl") | |
| if importlib.util.find_spec("llama_cpp") is None: | |
| subprocess.run([sys.executable, "-m", "pip", "install", "--no-deps", "--no-cache-dir", WHEEL], check=True) | |
| importlib.invalidate_caches() | |
| import spaces # noqa: E402 | |
| import gradio as gr # noqa: E402 | |
| from huggingface_hub import hf_hub_download # noqa: E402 | |
| REPO = "ccore/Inkling-2-Mini-3D-Coder" | |
| GGUF = "gguf/Inkling-2-Mini-3D-Coder-Q8_0.gguf" | |
| CTX = 65536 # the context used for training and evaluation | |
| CHUNK_SECONDS = 100 # wall time per GPU call (load + prefill + generation) | |
| GPU_DURATION = 115 # measured: ~100 s pass + ~15% margin | |
| MAX_PASSES = 12 # ~5K tokens per pass -> up to ~55K tokens | |
| # Exact system prompt from the model card (matches training and evaluation). | |
| SYSTEM_PROMPT = ( | |
| "Use only the Three.js core ES module from https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js. " | |
| "Do not import addons or legacy examples/js paths; implement any camera controls directly inside the HTML." | |
| ) | |
| EFFORT = {"low (0.2) · ~3 min": "0.2", "medium (0.7)": "0.7", "high (0.9, card's evaluation setting) · ~10+ min": "0.9"} | |
| DEFAULT_EFFORT = "low (0.2) · ~3 min" | |
| STOP_PIECES = ("<|content_model_end_sampling|>", "<|endoftext|>") | |
| print("Downloading", GGUF, flush=True) | |
| MODEL_PATH = hf_hub_download(REPO, GGUF) | |
| print("Model ready at", MODEL_PATH, flush=True) | |
| _LLM = None # cached inside a warm GPU worker | |
| def _preload_cuda_libs(): | |
| """llama-cpp-python's CUDA build links libcudart/libcublas dynamically; load them from the pip NVIDIA packages.""" | |
| for rel in ("nvidia/cuda_runtime/lib/libcudart.so.12", "nvidia/cublas/lib/libcublasLt.so.12", "nvidia/cublas/lib/libcublas.so.12"): | |
| for sp in site.getsitepackages(): | |
| p = os.path.join(sp, rel) | |
| if os.path.exists(p): | |
| ctypes.CDLL(p, mode=ctypes.RTLD_GLOBAL) | |
| break | |
| def _get_llm(): | |
| global _LLM | |
| if _LLM is None: | |
| _preload_cuda_libs() | |
| from llama_cpp import Llama | |
| _LLM = Llama(model_path=MODEL_PATH, n_gpu_layers=-1, n_ctx=CTX, n_batch=512, n_ubatch=512, | |
| flash_attn=True, swa_full=False, verbose=True) | |
| return _LLM | |
| def build_prompt(scene: str, effort_value: str) -> str: | |
| """Inkling 2 chat template: system turn, thinking-effort turn, user turn (the model opens its own turn).""" | |
| return ( | |
| "<|message_system|><|content_text|>" + SYSTEM_PROMPT + "<|end_message|>" | |
| "<|message_system|><|content_text|>Thinking effort level: " + effort_value + "<|end_message|>" | |
| "<|message_user|><|content_text|>" + scene.strip() + "<|end_message|>" | |
| ) | |
| def _gen_chunk(prompt: str, generated: str, budget: int, temperature: float, seed: int): | |
| """Continue generation from prompt+generated for up to CHUNK_SECONDS or `budget` tokens. | |
| Yields (new_text, n_new_tokens, finished).""" | |
| t0 = time.time() | |
| llm = _get_llm() | |
| ids = llm.tokenize((prompt + generated).encode("utf-8"), add_bos=False, special=True) | |
| budget = max(0, min(int(budget), CTX - len(ids) - 1)) | |
| if budget == 0: | |
| yield "", 0, True | |
| return | |
| llm.set_seed(int(seed)) | |
| t1 = time.time() | |
| buf, n, finished = b"", 0, False | |
| pending, pending_n = "", 0 | |
| for tok in llm.generate(ids, temp=float(temperature), top_p=1.0, top_k=0, min_p=0.0, repeat_penalty=1.0, reset=True): | |
| piece_b = llm.detokenize([tok], special=True) | |
| if tok == llm.token_eos() or piece_b.decode("utf-8", errors="ignore") in STOP_PIECES: | |
| finished = True | |
| break | |
| n += 1 | |
| buf += piece_b | |
| try: | |
| text, buf = buf.decode("utf-8"), b"" | |
| except UnicodeDecodeError: | |
| text = "" | |
| if len(buf) > 8: | |
| text, buf = buf.decode("utf-8", errors="ignore"), b"" | |
| if n >= budget: | |
| finished = True | |
| pending += text | |
| pending_n += 1 | |
| break | |
| pending += text | |
| pending_n += 1 | |
| if pending_n >= 32: | |
| yield pending, pending_n, False | |
| pending, pending_n = "", 0 | |
| if time.time() - t0 > CHUNK_SECONDS: | |
| break | |
| dt = time.time() - t1 | |
| print(f"chunk: prompt {len(ids)} tok, load {t1 - t0:.1f}s, {n} tok in {dt:.1f}s ({n / max(1e-6, dt):.1f} tok/s)", flush=True) | |
| yield pending + buf.decode("utf-8", errors="ignore"), pending_n, finished | |
| def split_channels(raw: str): | |
| """Split the model's raw output into (thinking, answer).""" | |
| thinking, answer, channel = [], [], "text" | |
| for part in re.split(r"(<\|[a-z_0-9]+\|>)", raw): | |
| if part == "<|content_thinking|>": | |
| channel = "think" | |
| elif part == "<|content_text|>": | |
| channel = "text" | |
| elif re.fullmatch(r"<\|[a-z_0-9]+\|>", part or ""): | |
| continue | |
| elif channel == "think": | |
| thinking.append(part) | |
| else: | |
| answer.append(part) | |
| return "".join(thinking), "".join(answer) | |
| def extract_html(answer: str): | |
| m = re.search(r"```html\s*\n(.*?)```", answer, re.S | re.I) | |
| if m and "</html>" in m.group(1).lower(): | |
| return m.group(1).strip() | |
| m = re.search(r"(<!DOCTYPE html.*?</html>|<html.*?</html>)", answer, re.S | re.I) | |
| return m.group(1).strip() if m else None | |
| def iframe(doc: str) -> str: | |
| return ( | |
| f'<iframe srcdoc="{html_lib.escape(doc, quote=True)}" sandbox="allow-scripts allow-pointer-lock" ' | |
| 'style="width:100%;height:640px;border:0;border-radius:12px;background:#111" ' | |
| 'allow="fullscreen"></iframe>' | |
| ) | |
| PLACEHOLDER = ( | |
| '<div style="height:640px;display:flex;align-items:center;justify-content:center;border-radius:12px;' | |
| 'background:#111;color:#bbb;font-family:sans-serif;text-align:center;padding:24px">{}</div>' | |
| ) | |
| def _finalize(raw: str, n_total: int, passes: int): | |
| thinking, answer = split_channels(raw) | |
| doc = extract_html(answer) | |
| path = os.path.join(tempfile.mkdtemp(), "index.html") | |
| if doc: | |
| with open(path, "w") as f: | |
| f.write(doc) | |
| status = f"✅ Done · {n_total:,} tokens · {passes} GPU pass(es)" | |
| return iframe(doc), doc, thinking, path, status | |
| msg = ("The model did not finish a complete HTML file within the token budget. " | |
| "Try again with another seed or a lower thinking effort.") | |
| with open(path, "w") as f: | |
| f.write(f"<!-- {msg} -->\n" + answer) | |
| return PLACEHOLDER.format(msg), answer, thinking, path, "⚠️ " + msg | |
| def start(scene: str): | |
| """Reset the generation state for a new scene.""" | |
| if not scene or not scene.strip(): | |
| raise gr.Error("Describe a scene first.") | |
| return (PLACEHOLDER.format("Waiting for a GPU… (the scene renders here once the HTML is complete)"), | |
| "", "", None, "Starting…", "", 0, 0, False) | |
| def generate_pass(scene: str, effort: str = DEFAULT_EFFORT, temperature: float = 0.9, max_new_tokens: int = 60000, | |
| seed: int = 67, raw: str = "", n_total: int = 0, passes: int = 0, done: bool = False): | |
| """Run one GPU pass (~100 s) of scene generation, continuing from the raw text generated so far. | |
| Call repeatedly, feeding back `raw`, `n_total`, `passes` and `done`, until `done` is True. | |
| Args: | |
| scene: description of the 3D scene to build. | |
| effort: thinking-effort level, one of the keys of EFFORT (low / medium / high). | |
| temperature: sampling temperature. | |
| max_new_tokens: cap on generated tokens (reasoning + HTML) over all passes. | |
| seed: random seed. | |
| raw: raw model output so far ("" for a new scene). | |
| n_total: tokens generated so far. | |
| passes: GPU passes run so far. | |
| done: whether generation already finished (the call is then a no-op). | |
| Returns: | |
| Rendered scene (iframe HTML), HTML source / answer, reasoning, HTML file, status, raw, n_total, passes, done. | |
| """ | |
| if done or not scene or not scene.strip(): | |
| yield (gr.update(),) * 9 | |
| return | |
| n_total, passes, max_new_tokens = int(n_total or 0), int(passes or 0), int(max_new_tokens) | |
| raw = raw or "" | |
| prompt = build_prompt(scene, EFFORT.get(effort, "0.2")) | |
| before, finished = len(raw), False | |
| for text, n_new, finished in _gen_chunk(prompt, raw, max_new_tokens - n_total, float(temperature), | |
| int(seed) + passes): | |
| raw += text | |
| n_total += n_new | |
| if len(raw) - before > 400 and not finished: | |
| before = len(raw) | |
| thinking, answer = split_channels(raw) | |
| phase = "writing the HTML" if answer.strip() else "thinking" | |
| status = f"⏳ Pass {passes + 1} · {phase} · {n_total:,} tokens" | |
| yield (gr.update(), answer[-6000:], thinking[-4000:], gr.update(), status, | |
| gr.update(), gr.update(), gr.update(), gr.update()) | |
| passes += 1 | |
| if n_total >= max_new_tokens or passes >= MAX_PASSES: | |
| finished = True | |
| if finished: | |
| yield (*_finalize(raw, n_total, passes), raw, n_total, passes, True) | |
| else: | |
| thinking, answer = split_channels(raw) | |
| status = f"⏳ Pass {passes} done · {n_total:,} tokens · continuing…" | |
| yield (gr.update(), answer[-6000:], thinking[-4000:], gr.update(), status, raw, n_total, passes, False) | |
| EXAMPLES = [ | |
| ["Create a single self-contained HTML file using Three.js from cdnjs for a voxel red panda sitting on a mossy branch, " | |
| "with a readable face, visible paws and a curled striped tail. Add orbit-style camera controls and soft forest lighting."], | |
| ["Please use Three.js from cdnjs for a voxel scene based on this idea: sakura bonsai. Build a small bonsai tree in a " | |
| "ceramic pot with pink blossoms across the canopy and a few falling petals. Let users orbit and zoom the camera."], | |
| ["Create a single self-contained HTML file using Three.js from cdnjs that shows a family home cutaway: two floors, a " | |
| "central staircase connecting the levels, labeled ground-floor rooms and furniture. Let users rotate the view and " | |
| "toggle the roof and upper floor."], | |
| ["Create a single self-contained HTML file using Three.js from cdnjs for a Mars cargo landing zone: a central habitat, " | |
| "cargo decks, cranes and a marked rover route across red terrain. Include a slowly driving rover and camera controls."], | |
| ] | |
| EXAMPLE_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "examples") | |
| def load_example(scene: str): | |
| """Show the precomputed scene for an example prompt (generated by this Space at low effort, seed 67).""" | |
| for i, (p,) in enumerate(EXAMPLES): | |
| path = os.path.join(EXAMPLE_DIR, f"example_{i}.html") | |
| if p == scene and os.path.exists(path): | |
| doc = open(path).read() | |
| return (iframe(doc), doc, "(precomputed example — press Generate scene for a fresh one)", path, | |
| "Precomputed example output · press **Generate scene** to run the model on this prompt") | |
| return (PLACEHOLDER.format("Press Generate scene to build this example."), "", "", None, "") | |
| CSS = """ | |
| #col-container { max-width: 1200px; margin: 0 auto; } | |
| .dark .gradio-container { color: var(--body-text-color); } | |
| """ | |
| with gr.Blocks(title="Inkling 2 Mini-3D-Coder") as demo: | |
| with gr.Column(elem_id="col-container"): | |
| gr.Markdown( | |
| "# Inkling 2 Mini-3D-Coder\n" | |
| "Describe a 3D scene and [ccore/Inkling-2-Mini-3D-Coder](https://huggingface.co/ccore/Inkling-2-Mini-3D-Coder) " | |
| "(a LoRA fine-tune of [Inkling 2 Mini](https://huggingface.co/thinkingmachines/Inkling-2-Mini)) writes a " | |
| "standalone, interactive Three.js scene, rendered live below. Runs the Q8_0 GGUF on llama.cpp.\n\n" | |
| "⏳ Scenes are long generations (reasoning + a full HTML file), split over several GPU passes. The default " | |
| "*low* thinking effort finishes most scenes in ~3 minutes; *high* (the card's evaluation setting, 20–40K " | |
| "tokens) can take 10+ minutes." | |
| ) | |
| with gr.Row(): | |
| scene = gr.Textbox(show_label=False, placeholder="Describe a 3D scene…", lines=3, scale=5) | |
| run = gr.Button("Generate scene", variant="primary", scale=1) | |
| status = gr.Markdown("") | |
| viewer = gr.HTML(PLACEHOLDER.format("Your interactive scene will appear here."), label="Scene") | |
| with gr.Row(): | |
| html_file = gr.File(label="index.html") | |
| with gr.Accordion("HTML source", open=False): | |
| code = gr.Code(language="html", label="Generated HTML") | |
| with gr.Accordion("Model reasoning", open=False): | |
| thinking = gr.Textbox(lines=12, max_lines=20, show_label=False) | |
| with gr.Accordion("Advanced settings", open=False): | |
| effort = gr.Dropdown(list(EFFORT), value=DEFAULT_EFFORT, label="Thinking effort") | |
| temperature = gr.Slider(0.0, 1.5, value=0.9, step=0.05, label="Temperature") | |
| max_new_tokens = gr.Slider(2048, 64000, value=60000, step=1024, label="Max new tokens (reasoning + HTML)") | |
| seed = gr.Number(value=67, precision=0, label="Seed") | |
| raw_box = gr.Textbox(visible=False) | |
| ntok_box = gr.Number(value=0, visible=False, precision=0) | |
| pass_box = gr.Number(value=0, visible=False, precision=0) | |
| done_box = gr.Checkbox(value=False, visible=False) | |
| outputs = [viewer, code, thinking, html_file, status] | |
| state = [raw_box, ntok_box, pass_box, done_box] | |
| gr.Examples(examples=EXAMPLES, inputs=[scene], outputs=outputs, fn=load_example, label="Examples (precomputed outputs from this Space, low effort)", | |
| cache_examples=False, run_on_click=True) | |
| pass_inputs = [scene, effort, temperature, max_new_tokens, seed] + state | |
| for trigger in (run.click, scene.submit): | |
| ev = trigger(start, inputs=[scene], outputs=outputs + state, api_name=False) | |
| for k in range(MAX_PASSES): | |
| ev = ev.then(generate_pass, inputs=pass_inputs, outputs=outputs + state, | |
| api_name="generate_pass" if (k == 0 and trigger == run.click) else False) | |
| if __name__ == "__main__": | |
| demo.launch(theme=gr.themes.Citrus(), css=CSS, mcp_server=True) | |