Spaces:
Sleeping
Sleeping
Initialize models after GPU allocation; add sampled trajectory playback and default GEOM generation
Browse filesFiles changed (3)
- app.py+82-25
- backend.py+125-8
- trajectory_view.pyAdded+80
1234561 unmodified line8910111213141516171817 unmodified lines363738394041425 unmodified lines4849505152535455565758596061626364659 unmodified lines75767778798019 unmodified lines1001011021031041051061071081091101111124 unmodified lines1171181191201211221231247 unmodified lines13213313413513613713813915 unmodified lines1551561571581591606 unmodified lines167168169170171172173174175176177178179180181182183"""Morph's public Gradio interface, with ZeroGPU generation."""import osimport spaces # Initialize ZeroGPU before importing torch through backend.import gradio as gr1 unmodified lineimport py3Dmolimport htmlfrom backend import REGISTRY, generate_graphs, load_models, presentfrom gpu_diagnostic import gpu_probeDEVICE = os.environ.get("MORPH_DEVICE", "cpu")USE_GPU = DEVICE.startswith("cuda")def description(key):17 unmodified linesif item is None:return "<p style='color:#65758b;padding:24px'>Generate molecules to explore their 3D structures.</p>"view = py3Dmol.view(width="100%", height=410)view.addModel(item["molblock"], "sdf")view.setStyle({"stick": {"radius": 0.15}, "sphere": {"scale": 0.23}})view.setBackgroundColor("#f7f9fc")view.zoomTo()5 unmodified lines)@spaces.GPU(duration=30)def sample_on_gpu(key, target_logp, target_n, count, seed):return generate_graphs(key, target_logp, target_n, count, seed)def generate(key, target_logp, target_n, count, seed):if not USE_GPU and count > 2:raise gr.Error("The CPU preview supports up to two molecules per request.")sampler = sample_on_gpu if USE_GPU else generate_graphsgraphs = sampler(key, target_logp, target_n, count, seed)gallery, rows, records, sdf, csv, status = present(graphs, key, target_logp, target_n, seed)choices = [str(record["index"]) for record in records]selected = choices[0] if choices else None9 unmodified linessdf,csv,status,)19 unmodified lineswith gr.Row():with gr.Column(scale=1, min_width=300):model = gr.Dropdown([(spec["label"], key) for key, spec in REGISTRY.items()],value="geom-logp",label="Model",interactive=True,)note = gr.Markdown(description("geom-logp"))target_logp = gr.Slider(-8, 9, value=2, step=0.1, label="Target logP")target_n = gr.Slider(3,120,4 unmodified lines)count = gr.Slider(1,8 if USE_GPU else 2,value=4 if USE_GPU else 1,step=1,label="Molecules",)7 unmodified linesbutton = gr.Button("Generate molecules", variant="primary", size="lg")gr.Markdown("Shared GPU 路 You may need to sign in to Hugging Face and wait in the queue. Changing the seed gives new samples."if USE_GPUelse "CPU preview 路 Generation can take a minute or more. Changing the seed gives new samples.")gr.Markdown("[Checkpoints & evaluation](https://huggingface.co/maltefranke/morph) 路 [Source](https://huggingface.co/spaces/maltefranke/morph-playground/tree/main)"15 unmodified lines)structure = gr.HTML(viewer([], None))gr.Markdown("Drag to rotate 路 Scroll to zoom")with gr.Tab("Properties"):table = gr.Dataframe(interactive=False, wrap=True, label="Every generation attempt"6 unmodified lines)model.change(change_model, model, [target_logp, target_n, note], queue=False)selected.change(viewer, [records, selected], structure, queue=False)button.click(generate,[model, target_logp, target_n, count, seed],[gallery, table, records, selected, structure, sdf, csv, status],api_name="generate",concurrency_limit=1,)if __name__ == "__main__":import torchprint(f"Runtime: torch={torch.__version__}, CUDA={torch.version.cuda}", flush=True)load_models(DEVICE)demo.queue(max_size=24).launch(ssr_mode=False)12345671 unmodified line91011121314151617181917 unmodified lines37383940414243444546475 unmodified lines53545556575859606162636465666768697071727374757677787980818283849 unmodified lines94959697989910010110210319 unmodified lines1231241251261271281291301311321331341351361371381391404 unmodified lines1451461471481491501511527 unmodified lines16016116216316416515 unmodified lines1811821831841851861871881891901911921931946 unmodified lines201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240"""Morph's public Gradio interface, with ZeroGPU generation."""import jsonfrom pathlib import Pathimport spaces # Initialize ZeroGPU before importing torch through backend.import gradio as gr1 unmodified lineimport py3Dmolimport htmlfrom trajectory_view import trajectory_viewerfrom gpu_diagnostic import gpu_probeROOT = Path(__file__).resolve().parentREGISTRY = json.loads((ROOT / "models.json").read_text())def description(key):17 unmodified linesif item is None:return "<p style='color:#65758b;padding:24px'>Generate molecules to explore their 3D structures.</p>"view = py3Dmol.view(width="100%", height=410)if item.get("molblock"):view.addModel(item["molblock"], "sdf")else:view.addModel()view.getModel().addAtoms(item["frames"][-1]["atoms"])view.setStyle({"stick": {"radius": 0.15}, "sphere": {"scale": 0.23}})view.setBackgroundColor("#f7f9fc")view.zoomTo()5 unmodified lines)@spaces.GPU(duration=45)def sample_on_gpu(key, target_logp, target_n, count, seed):# Some scientific dependencies probe CUDA while importing. Import them# only after ZeroGPU attaches the real device, keeping its parent clean.from backend import MODELS, generate_graphs, load_models, presentif key not in MODELS:load_models("cuda", keys=[key])result = generate_graphs(key, target_logp, target_n, count, seed, trajectory=True, require_gpu=True)return present(result["graphs"],key,target_logp,target_n,seed,trajectories=result["trajectories"],times=result["times"],runtime=result["runtime"],)def generate(key, target_logp, target_n, count, seed):gallery, rows, records, sdf, csv, status, archive, runtime = sample_on_gpu(key, target_logp, target_n, count, seed)choices = [str(record["index"]) for record in records]selected = choices[0] if choices else None9 unmodified linessdf,csv,status,gr.update(choices=choices, value=selected),trajectory_viewer(records, selected),archive,runtime,)19 unmodified lineswith gr.Row():with gr.Column(scale=1, min_width=300):model = gr.Dropdown([(REGISTRY[key]["label"], key)for key in ["geom", *[k for k in REGISTRY if k != "geom"]]],value="geom",label="Model",interactive=True,)note = gr.Markdown(description("geom"))target_logp = gr.Slider(-8, 9, value=2, step=0.1, label="Target logP", visible=False)target_n = gr.Slider(3,120,4 unmodified lines)count = gr.Slider(1,8,value=4,step=1,label="Molecules",)7 unmodified linesbutton = gr.Button("Generate molecules", variant="primary", size="lg")gr.Markdown("Shared GPU 路 You may need to sign in to Hugging Face and wait in the queue. Changing the seed gives new samples.")gr.Markdown("[Checkpoints & evaluation](https://huggingface.co/maltefranke/morph) 路 [Source](https://huggingface.co/spaces/maltefranke/morph-playground/tree/main)"15 unmodified lines)structure = gr.HTML(viewer([], None))gr.Markdown("Drag to rotate 路 Scroll to zoom")with gr.Tab("Trajectory"):trajectory_selected = gr.Dropdown(choices=[], label="Molecule", interactive=True)trajectory_player = gr.HTML(trajectory_viewer([], None))trajectory_file = gr.File(label="Download trajectories (JSON + XYZ)")with gr.Tab("Properties"):table = gr.Dataframe(interactive=False, wrap=True, label="Every generation attempt"6 unmodified lines)model.change(change_model, model, [target_logp, target_n, note], queue=False)selected.change(viewer, [records, selected], structure, queue=False)trajectory_selected.change(trajectory_viewer,[records, trajectory_selected],trajectory_player,queue=False,)runtime_info = gr.JSON(visible=False)button.click(generate,[model, target_logp, target_n, count, seed],[gallery,table,records,selected,structure,sdf,csv,status,trajectory_selected,trajectory_player,trajectory_file,runtime_info,],api_name="generate",concurrency_limit=1,)if __name__ == "__main__":from huggingface_hub import hf_hub_download# Download once at startup; model construction runs in the GPU worker.for spec in REGISTRY.values():hf_hub_download("maltefranke/morph", spec["checkpoint"], revision=spec["revision"])demo.queue(max_size=24).launch(ssr_mode=False)
10 unmodified lines11121314151676 unmodified lines939495969798991 unmodified line10110210310410510612 unmodified lines11912012112212312412512612712812913013113213333 unmodified lines1671681691701711721734 unmodified lines17817918018118218318418518618718810 unmodified linesimport randomimport sysimport tempfileROOT = Path(__file__).resolve().parentsys.path.insert(0, str(ROOT / "runtime"))76 unmodified linesraise ValueError("Choose an atom-count target between 3 and 120.")def generate_graphs(key, target_logp, target_n, count, seed):"""Run the same 100-step EMA sampler used for evaluation."""validate_request(key, target_logp, target_n, count, seed)torch.set_float32_matmul_precision("high")1 unmodified linenp.random.seed(int(seed))torch.manual_seed(int(seed))module, data, prior = MODELS[key]kind = REGISTRY[key]["kind"]graphs = []for n in torch.randint(prior[0], prior[1] + 1, (int(count),)):12 unmodified linesenabled=module.device.type == "cuda",),):generated = module.sample((batch, batch), 0)generated.to_inplace("cpu", non_blocking=False)outputs = generated.to_data_list()assert len(outputs) == int(count)assert all(torch.isfinite(graph.positions).all() for graph in outputs)return outputsdef present(graphs, key, target_logp, target_n, seed):"""Keep every attempt in the table; export sanitized structures to SDF."""_, data, _ = MODELS[key]vocab = data.vocab33 unmodified linesdisplay = Chem.RemoveHs(Chem.Mol(mol))rdDepictor.Compute2DCoords(display)thumbnail = Draw.MolToImage(display, size=(440, 320))records.append(dict(index=i, molblock=block))else:thumbnail = Image.new("RGB", (440, 320), "#f4f6f8")ImageDraw.Draw(thumbnail).text(4 unmodified linescaption += f" 路 logP={logp:.2f}"caption += " 路 valid" if valid else " 路 invalid"gallery.append((thumbnail, caption))writer.close()with csv_path.open("w", newline="") as handle:csv_writer = csv.DictWriter(handle, fieldnames=rows[0])csv_writer.writeheader()csv_writer.writerows(rows)status = f"**{valid_count} / {len(graphs)} chemically valid** 路 Seed {int(seed)}"status += "\n\nAll attempts are shown. SDF includes sanitized structures; CSV includes every attempt."return gallery, rows, records, str(sdf_path), str(csv_path), status10 unmodified lines1112131415161776 unmodified lines9495969798991001011021 unmodified line10410510610710810911011112 unmodified lines12412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920033 unmodified lines2342352362372382394 unmodified lines24424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430510 unmodified linesimport randomimport sysimport tempfileimport zipfileROOT = Path(__file__).resolve().parentsys.path.insert(0, str(ROOT / "runtime"))76 unmodified linesraise ValueError("Choose an atom-count target between 3 and 120.")def generate_graphs(key, target_logp, target_n, count, seed, *, trajectory=False, require_gpu=False):"""Run the same 100-step EMA sampler used for evaluation."""validate_request(key, target_logp, target_n, count, seed)torch.set_float32_matmul_precision("high")1 unmodified linenp.random.seed(int(seed))torch.manual_seed(int(seed))module, data, prior = MODELS[key]if require_gpu and module.device.type != "cuda":raise RuntimeError("This endpoint requires real CUDA inference.")kind = REGISTRY[key]["kind"]graphs = []for n in torch.randint(prior[0], prior[1] + 1, (int(count),)):12 unmodified linesenabled=module.device.type == "cuda",),):generated = module.sample((batch, batch), 0, return_traj=trajectory)if trajectory:outputs = [frames[-1] for frames in generated]else:generated.to_inplace("cpu", non_blocking=False)outputs = generated.to_data_list()assert len(outputs) == int(count)assert all(torch.isfinite(graph.positions).all() for graph in outputs)if not trajectory:return outputstimes = [0.0, *np.cumsum(module.integrator.get_time_steps()).tolist()]assert all(len(frames) == len(times) == 101 for frames in generated)runtime = dict(device=str(module.device),gpu=torch.cuda.get_device_name() if module.device.type == "cuda" else None,torch=torch.__version__,precision="bfloat16" if module.device.type == "cuda" else "float32",model=key,checkpoint_sha256=REGISTRY[key]["sha256"],initial_count_prior=list(prior),integration_steps=100,frames_per_molecule=101,coordinate_units="angstrom",time_grid="log; final integration boundary 0.999",)return dict(graphs=outputs, trajectories=generated, times=times, runtime=runtime)def frame_atoms(graph, vocab):"""Export raw graph geometry, including chemically invalid intermediate states."""positions = graph.positions.tolist()atom_types = graph.atom_types.tolist()charges = graph.charge_types.tolist()atoms = [dict(elem=vocab.atom_tokens[a],x=round(p[0], 5),y=round(p[1], 5),z=round(p[2], 5),charge=int(vocab.charge_tokens[c]),bonds=[],bondOrder=[],)for a, c, p in zip(atom_types, charges, positions, strict=True)]edge_types, edge_index = graph.get_edge_types_triu(no_bond_idx=list(vocab.edge_tokens).index("<NO_BOND>"))for edge, (a, b) in zip(edge_types.tolist(), edge_index.T.tolist(), strict=True):token = vocab.edge_tokens[edge]if token == "<NO_BOND>":continueorder = 1.5 if str(token) == "4" else float(token)atoms[a]["bonds"].append(b)atoms[a]["bondOrder"].append(order)atoms[b]["bonds"].append(a)atoms[b]["bondOrder"].append(order)return atomsdef present(graphs,key,target_logp,target_n,seed,*,trajectories=None,times=None,runtime=None,):"""Keep every attempt in the table; export sanitized structures to SDF."""_, data, _ = MODELS[key]vocab = data.vocab33 unmodified linesdisplay = Chem.RemoveHs(Chem.Mol(mol))rdDepictor.Compute2DCoords(display)thumbnail = Draw.MolToImage(display, size=(440, 320))else:thumbnail = Image.new("RGB", (440, 320), "#f4f6f8")ImageDraw.Draw(thumbnail).text(4 unmodified linescaption += f" 路 logP={logp:.2f}"caption += " 路 valid" if valid else " 路 invalid"gallery.append((thumbnail, caption))record = dict(index=i, molblock=block if mol is not None else None)if trajectories is not None:record["frames"] = [dict(time=float(t), atoms=frame_atoms(frame, vocab))for t, frame in zip(times, trajectories[i - 1], strict=True)]records.append(record)writer.close()with csv_path.open("w", newline="") as handle:csv_writer = csv.DictWriter(handle, fieldnames=rows[0])csv_writer.writeheader()csv_writer.writerows(rows)status = f"**{valid_count} / {len(graphs)} chemically valid** 路 Seed {int(seed)}"if runtime is not None and runtime["device"].startswith("cuda"):status += " 路 GPU"status += "\n\nAll attempts are shown. SDF includes sanitized structures; CSV includes every attempt."if trajectories is None:return gallery, rows, records, str(sdf_path), str(csv_path), statusarchive = directory / "trajectories.zip"with zipfile.ZipFile(archive, "w", compression=zipfile.ZIP_DEFLATED) as zip_file:zip_file.writestr("generation.json",json.dumps(dict(**runtime,seed=int(seed),target_logp=float(target_logp) if kind == "logp" else None,target_n=int(target_n) if kind == "count" else None,),indent=2,),)for record in records:zip_file.writestr(f"molecule_{record['index']}.json", json.dumps(record["frames"]))xyz = []for frame in record["frames"]:xyz.extend([str(len(frame["atoms"])),f"t={frame['time']:.9f}; coordinates in angstrom",])xyz.extend(f"{a['elem']} {a['x']:.5f} {a['y']:.5f} {a['z']:.5f}"for a in frame["atoms"])zip_file.writestr(f"molecule_{record['index']}.xyz", "\n".join(xyz) + "\n")return (gallery,rows,records,str(sdf_path),str(csv_path),status,str(archive),runtime,)
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980"""Client-side trajectory playback with changing atom counts and bonds."""
import htmlimport json
def trajectory_viewer(records, sample): record = next((r for r in records if r["index"] == int(sample or 0)), None) if record is None or not record.get("frames"): return "<p style='padding:24px;color:#65758b'>Generate molecules to play their trajectories.</p>" frames = json.dumps(record["frames"], separators=(",", ":")).replace("</", "<\\/") document = """<!doctype html><html><head><meta name="viewport" content="width=device-width, initial-scale=1"><script src="https://3Dmol.org/build/3Dmol-min.js"></script><style>body{margin:0;font:14px system-ui,sans-serif;color:#26364a;background:#f7f9fc}#scene{height:405px;position:relative;width:100%}.controls{padding:12px 14px;display:flex;gap:10px;align-items:center;flex-wrap:wrap}button,select{font:inherit;border:1px solid #ccd6e3;border-radius:7px;background:white;padding:7px 12px;cursor:pointer;color:#26364a}#play{background:#3478f6;color:white;border-color:#3478f6;min-width:73px}#scrub{width:100%;accent-color:#3478f6;margin:0 0 5px}#readout{font-variant-numeric:tabular-nums;margin-left:auto}.hint{margin:0;padding:0 14px 12px;color:#697a90;font-size:12px}</style></head><body><div id="scene" aria-label="Molecular trajectory"></div><div class="controls"><input id="scrub" aria-label="Trajectory frame" type="range" min="0" step="1" value="0"><button id="play">Play</button><button id="restart">Restart</button><label>Speed <select id="speed" aria-label="Playback speed"><option value="0.5">0.5脳</option><option value="1" selected>1脳</option><option value="2">2脳</option></select></label><label><input type="checkbox" id="loop" checked> Loop</label><label><input type="checkbox" id="bonds" checked> Bonds</label><span id="readout" aria-live="off"></span></div><p class="hint">Drag to rotate 路 Scroll to zoom 路 Frames show the sampled states, including atom insertions and deletions.</p><script>const frames=__FRAMES__;const viewer=$3Dmol.createViewer(document.getElementById('scene'),{backgroundColor:'#f7f9fc',antialias:true});const scrub=document.getElementById('scrub'),play=document.getElementById('play'),readout=document.getElementById('readout');scrub.max=frames.length-1;let frame=0,playing=false,last=0,pausedAtEnd=0;function draw(index,fit=false){ frame=Math.max(0,Math.min(frames.length-1,index)); const camera=fit?null:viewer.getView(); viewer.removeAllModels(); // 3Dmol mutates atom objects; each display gets a fresh copy of the raw frame. const atoms=frames[frame].atoms.map(a=>({...a,bonds:[...a.bonds],bondOrder:[...a.bondOrder]})); viewer.addModel().addAtoms(atoms); const style={sphere:{scale:0.23}}; if(document.getElementById('bonds').checked)style.stick={radius:0.10}; viewer.setStyle({},style); if(fit)viewer.zoomTo();else viewer.setView(camera); viewer.render();scrub.value=frame; readout.textContent=`t = ${frames[frame].time.toFixed(2)} 路 N = ${atoms.length}`; document.body.dataset.frame=String(frame);document.body.dataset.atomCount=String(atoms.length);}function pause(){playing=false;play.textContent='Play';}play.onclick=()=>{if(playing){pause();return;}if(frame===frames.length-1)draw(0);playing=true;last=0;pausedAtEnd=0;play.textContent='Pause';};document.getElementById('restart').onclick=()=>{pause();draw(0);};scrub.oninput=()=>{pause();draw(Number(scrub.value));};document.getElementById('bonds').onchange=()=>draw(frame);document.addEventListener('visibilitychange',()=>{if(document.hidden)pause();});function tick(now){ if(playing){ const interval=1000/(25*Number(document.getElementById('speed').value)); if(!last)last=now; if(frame===frames.length-1){ if(!document.getElementById('loop').checked)pause(); else{if(!pausedAtEnd)pausedAtEnd=now;if(now-pausedAtEnd>=1000){draw(0);last=now;pausedAtEnd=0;}} }else if(now-last>=interval){draw(frame+1);last=now;} } requestAnimationFrame(tick);}// Fit to the finished molecule, then keep its camera stable throughout playback.draw(frames.length-1,true);draw(0);requestAnimationFrame(tick);window.addEventListener('resize',()=>{viewer.resize();viewer.render();});</script></body></html>""".replace("__FRAMES__", frames) return ( '<iframe title="Trajectory player" sandbox="allow-scripts allow-same-origin" ' 'style="width:100%;height:555px;border:0;border-radius:12px" srcdoc="' + html.escape(document, quote=True) + '"></iframe>' )app.py+82-25
backend.py+125-8
trajectory_view.pyAdded+80