Spaces:
Running on Zero

File size: 10,973 Bytes
c8f167d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c4ac8d1
c8f167d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c4ac8d1
c8f167d
 
 
 
 
c4ac8d1
 
 
 
 
 
 
 
 
 
 
 
 
 
c8f167d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c4ac8d1
 
 
 
 
 
 
 
 
 
 
2469c81
c8f167d
 
 
 
 
 
 
 
 
 
 
2469c81
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
"""Drop anything: objects made from photos are dropped and dragged on a table, and a learned particle world model
predicts the next 2 seconds. A Gradio app for a Hugging Face Space on ZeroGPU: each visitor has their own table, and each
Run predicts 3 model windows (48 frames) in one GPU call.

The models and their code come from a private model repository (PWM_MODEL_REPO, read with the Space's HF_TOKEN secret),
or from a local copy (PWM_MODEL_DIR) when testing: pwm_infer (the library's inference modules), weights/, shelf/.

The page is one custom component (web/viewer.*: three.js, the live demo's renderer). It sends {op, actions, req} with
trigger('click', ...); the reply (JSON text) goes to a hidden Textbox and back to the page with a client-side .then().
Light lookups (the shelf, an object's drawing) are server functions; only the model call uses the GPU queue.
"""
from __future__ import annotations

import json
import os
import re
import secrets
import sys
import time
from pathlib import Path

import gradio as gr
import numpy as np
import spaces

APP = Path(__file__).resolve().parent


def model_dir():
    local = os.environ.get("PWM_MODEL_DIR")
    if local:
        return Path(local)
    from huggingface_hub import snapshot_download
    # real files in a plain folder, not the cache's symlinks: Gradio serves the shelf thumbnails only from inside the
    # folder it was given, and a symlink's target lies elsewhere
    return Path(snapshot_download(os.environ["PWM_MODEL_REPO"], token=os.environ.get("HF_TOKEN"),
                                  local_dir=str(APP / "model"), ignore_patterns=["**/__pycache__/**", "*.pyc"]))


MODEL = model_dir()
sys.path.insert(0, str(MODEL))
import pwm_infer  # noqa: E402

pwm_infer.install()

from demo import config, golden  # noqa: E402
from demo.encode import frames_text  # noqa: E402
from demo.engine import Engine  # noqa: E402
from demo.shelf import Shelf  # noqa: E402
from demo.world import World  # noqa: E402

ENGINE = Engine(pwm_infer.WEIGHTS, device="cuda")       # ZeroGPU: models go to cuda at start, the GPU comes per call
SHELF = Shelf(pwm_infer.SHELF)
THUMBS = (pwm_infer.SHELF / "thumbs").resolve()
gr.set_static_paths(paths=[str(THUMBS)])
MAX_ACTIONS = 25


def gpu_seconds(state, windows):
    """The GPU time to ask for: generous for the objects on the table (a window takes about 0.1-0.6 s on a full card)."""
    n = len(state["objects"]) + sum(1 for _, a in state["due"] if a["kind"] == "drop")
    return int(min(60, 15 + windows * (1 + 0.2 * n)))


@spaces.GPU(duration=gpu_seconds)
def advance(state, windows):
    """Predict up to `windows` windows of a table (its plain state) on the GPU: (frames [L, N, 3] or None, first frame,
    the new state, timings)."""
    import torch
    world = World.from_state(ENGINE, SHELF, state)
    outs = []
    for _ in range(windows):
        out = world.step()
        if out is None:
            break
        outs.append(out)
    info = dict(gpu=torch.cuda.get_device_name() if torch.cuda.is_available() else "cpu",
                models=[o["model"] for o in outs], ms=[round(o["ms"], 1) for o in outs])
    frames = np.concatenate([o["frames"] for o in outs]) if outs else None
    return frames, (outs[0]["first"] if outs else None), world.export_state(), info


@spaces.GPU(duration=60)
def check_model():
    """The golden scenes on this GPU against the training cluster's frames (demo/golden.py)."""
    import torch
    frames = golden.run_scenes(ENGINE, golden.load_scenes(MODEL / "golden" / "scenes.npz"))
    rows = golden.compare(frames, MODEL / "golden" / "original.npz")
    return dict(gpu=torch.cuda.get_device_name() if torch.cuda.is_available() else "cpu", torch=torch.__version__,
                cuda=str(torch.version.cuda), scenes=rows)


def apply_action(world, a):
    """One visitor action onto the table (applied at the next window boundary): None or why it was refused."""
    kind = a.get("type")
    if kind == "drop":
        mat = a.get("material")
        _, err = world.drop(str(a["id"]), float(a["x"]), float(a["y"]), float(a.get("height", 0.25)),
                            None if mat is None else int(mat), None if a.get("E") is None else float(a["E"]))
        return err
    if kind == "rain":
        return None if world.rain(int(a.get("count", 5))) else "the table is full"
    if kind == "pull":
        return world.pull(int(a["uid"]), (float(a["dx"]), float(a["dy"])))
    if kind == "lift":
        return world.pull(int(a["uid"]), None, lift=True, height=float(a.get("height", 0.12)))
    if kind == "material":
        return world.material(int(a["uid"]), int(a["material"]), float(a["E"]))
    return f"unknown action {kind!r}"


def reply(world, req, frames=None, first=None, info=None, notes=()):
    """What the page needs: the objects (uid, shelf id, particle range, material), the run's frames (from `first`), the
    table's last frame (so a page that missed something can show it), whether anything still moves, notes."""
    objects = [dict(uid=o["uid"], shelf_id=o["shelf_id"], label=o["label"].replace("_", " "), start=o["start"], n=o["n"],
                    material=int(o["mat_type"]), E=float(o["E"])) for o in world.objects]
    out = dict(req=req, version=world.version, objects=objects, frame=world.frame, still=world.still(),
               notes=list(notes), last=frames_text(world.frames[-1:], world.frame) if world.objects else None)
    if frames is not None:
        out.update(first=int(first), count=int(len(frames)), frames=frames_text(frames, first))
    if info:
        out.update(info)
    return json.dumps(out)


def on_viewer(state, evt: gr.EventData):
    """The page's request: {op: run | reset, actions: [...], req}. Returns (reply JSON, the new state)."""
    data = getattr(evt, "_data", None) or {}
    req = data.get("req")
    world = World.from_state(ENGINE, SHELF, state) if state else World(ENGINE, SHELF, seed=secrets.randbits(31))
    if data.get("op") == "reset":
        world.reset()
        return reply(world, req, notes=["The table is clear."]), world.export_state()
    if data.get("op") == "check":                    # the maintainer's self-check (the page shows it with ?check=1)
        try:
            c = check_model()
        except Exception as e:
            return reply(world, req, notes=[f"The self-check could not run: {e}"]), state
        rows = list(c["scenes"].values())
        same = all(r["identical"] for r in rows)
        means = ", ".join("%.2f" % r["mean_mm"] for r in rows)
        worst = max(r["max_mm"] for r in rows)
        where = "Self-check on %s (torch %s, CUDA %s): the 4 golden scenes are " % (c["gpu"], c["torch"], c["cuda"])
        note = where + ("bit-identical to the training cluster's frames." if same else
                        "not bit-identical; mean differences %s mm, largest %.1f mm (floating-point rounding; a different "
                        "seed moves frames 10-25 mm)." % (means, worst))
        print(note, c, flush=True)
        return reply(world, req, notes=[note]), state
    notes = []
    for a in (data.get("actions") or [])[:MAX_ACTIONS]:
        try:
            err = apply_action(world, a)
        except (KeyError, TypeError, ValueError) as e:
            err = f"a malformed action ({type(e).__name__})"
        if err:
            notes.append(err)
    if world.still():
        return reply(world, req, notes=notes or ["Nothing to predict: drop or pull something first."]), world.export_state()
    t = time.perf_counter()
    try:
        frames, first, new_state, info = advance(world.export_state(), config.RUN_WINDOWS)
    except Exception as e:                           # e.g. the visitor's daily GPU time is used up
        return reply(world, req, notes=notes + [gpu_note(e)]), state
    info["call_s"] = round(time.perf_counter() - t, 2)
    world = World.from_state(ENGINE, SHELF, new_state)
    return reply(world, req, frames, first, info, notes), new_state


def gpu_note(e):
    """What to tell the visitor when the model call fails; ZeroGPU's limits in plain words (spaces 0.51: a visitor
    without a login gets a few runs a day, "runs limit"; a logged-in one a daily quota with "Try again in h:mm:ss")."""
    text = str(e)
    low = text.lower()
    if "runs limit" in low or "reached its gpu limit" in low:
        return ("The free GPU runs for visitors without a login are used up for today. Log in to Hugging Face to keep "
                "going: free accounts get 5 GPU minutes a day.")
    if "quota" in low:
        wait = re.search(r"try again in ([0-9:]+)", low)
        return "Your Hugging Face GPU time for today is used up." + (f" It comes back in {wait.group(1)}." if wait else "")
    return f"The model could not run: {text}"


def shelf_menu(args=None):
    return SHELF.menu(lambda path: f"/gradio_api/file={path}")


def object_drawing(args):
    shelf_id = args[0] if isinstance(args, (list, tuple)) else args
    if SHELF.entry(shelf_id) is None:
        raise gr.Error("unknown object")
    return SHELF.drawing(shelf_id)


def read(name):
    return (APP / "web" / name).read_text()


FONTS = ('<link rel="preconnect" href="https://fonts.googleapis.com"><link rel="preconnect" href="https://fonts.gstatic.com" '
         'crossorigin><link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Instrument+Sans:wght@400;500;600;700'
         '&display=swap">')
# one light look in both of Gradio's themes (the 3D view is drawn light); the page around the component matches it
PAGE_CSS = """
:root, .dark { --body-background-fill: #f4f5f2; --background-fill-primary: #f4f5f2; --body-text-color: #1d2124;
  --body-text-color-subdued: #5d6670; --border-color-primary: rgba(29, 33, 36, 0.1); color-scheme: light; }
body, gradio-app, .gradio-container { background: #f4f5f2 !important; }
.gradio-container { width: 100% !important; max-width: 1480px !important; margin: 0 auto !important; }
"""

with gr.Blocks(title="GPWM Simulation", fill_width=True) as demo:
    state = gr.State(None)
    viewer = gr.HTML(html_template=read("viewer.html"), css_template=read("viewer.css"), js_on_load=read("viewer.js"),
                     server_functions=[shelf_menu, object_drawing], apply_default_css=False, container=False,
                     elem_id="drop-anything")
    answer = gr.Textbox(visible=False)
    viewer.click(on_viewer, inputs=[state], outputs=[answer, state], show_progress="hidden").then(
        None, inputs=[answer], outputs=None,
        js="(text) => { if (window.dropAnything) window.dropAnything.receive(text); return []; }")

if __name__ == "__main__":
    demo.queue(default_concurrency_limit=4).launch(server_name=os.environ.get("HOST", "0.0.0.0"),
                                                   server_port=int(os.environ.get("PORT", 7860)), footer_links=[],
                                                   css=PAGE_CSS, head=FONTS)   # Gradio 6: page css and head go to launch()