Download app.py from Delower/dpp4-molgemma-generator: direct link, hf CLI and curl.
- Browser
- Download file 12.3 kB
-
https://huggingface.co/spaces/Delower/dpp4-molgemma-generator/resolve/main/app.py
- Command line
-
hf download hf://spaces/Delower/dpp4-molgemma-generator/app.py
-
curl -L -o app.py https://huggingface.co/spaces/Delower/dpp4-molgemma-generator/resolve/main/app.py
12.3 kB
| """MolGemma — DPP-4 molecule generator. | |
| Generates candidate DPP-4 inhibitor SMILES from the fine-tuned MolGemma | |
| checkpoint (Delower/dpp4-molgemma-finetuned: epoch 4, best val loss | |
| 0.1800; base model Delower/MolGemma), validates them with RDKit, checks | |
| novelty against the 6,835 canonical compounds of the fine-tune set, and | |
| scores valid molecules with the deployed tuned DPP-4 LTN pIC50 model | |
| (Delower/dpp4-pic50-ltn bundle). | |
| Sampling replicates the project generation protocol exactly | |
| (kaggle_molgemma_generation_only.py): seed token 'C', autoregressive | |
| temperature sampling over GEN_STEPS=86 steps, batch chunks of 250, one | |
| np.random.default_rng(seed) stream. Optional top-p / top-k truncation | |
| is applied to the raw logits BEFORE temperature scaling; with the | |
| defaults (top-p 1.0, top-k 0) the sampler is the unmodified protocol | |
| sampler. | |
| """ | |
| import os | |
| os.environ.setdefault("TF_CPP_MIN_LOG_LEVEL", "3") | |
| os.environ.setdefault("KERAS_BACKEND", "tensorflow") | |
| import numpy as np | |
| import pandas as pd | |
| import gradio as gr | |
| import spaces | |
| from huggingface_hub import hf_hub_download | |
| from rdkit import Chem | |
| from rdkit import RDLogger | |
| RDLogger.DisableLog("rdApp.*") | |
| from tokenizer import DeepChemTokenizer | |
| import infer as ltn_infer # bundled copy of the DPP-4 LTN inference module | |
| HERE = os.path.dirname(os.path.abspath(__file__)) | |
| FT_REPO = "Delower/dpp4-molgemma-finetuned" | |
| BASE_REPO = "Delower/MolGemma" | |
| PROTOCOL_STEPS = 86 | |
| # ---------------- tokenizer + novelty reference (loaded once) ---------------- | |
| TOK = DeepChemTokenizer(os.path.join(HERE, "vocab_deepchem_2.4.0.txt")) | |
| PAD_ID = TOK.stoi["[PAD]"] | |
| SEED_TOKEN_ID = TOK.stoi["C"] | |
| with open(os.path.join(HERE, "finetune_canon.txt")) as f: | |
| FINETUNE_CANON = {ln.strip() for ln in f if ln.strip()} | |
| # ---------------- model files (downloaded once at startup) ---------------- | |
| def _fetch_model_files(): | |
| """Prefer the full fine-tuned .keras in the model repo; fall back to | |
| base architecture (.keras from Delower/MolGemma) + fine-tuned weights.""" | |
| try: | |
| p = hf_hub_download(FT_REPO, "molgemma_finetuned_dpp4.keras") | |
| print("model source: full fine-tuned .keras from", FT_REPO, flush=True) | |
| return {"kind": "full", "full": p} | |
| except Exception as e: | |
| print("full .keras not available in repo (", repr(e), | |
| ") — falling back to architecture + weights", flush=True) | |
| arch = hf_hub_download(BASE_REPO, | |
| "output-gemma-seed42-fp16-last.model.keras") | |
| wts = hf_hub_download(FT_REPO, "molgemma_best.weights.h5") | |
| print("model source: architecture from", BASE_REPO, | |
| "+ fine-tuned weights from", FT_REPO, flush=True) | |
| return {"kind": "arch+weights", "arch": arch, "weights": wts} | |
| MODEL_FILES = _fetch_model_files() | |
| _MODEL = None | |
| def _ensure_model(): | |
| """Load the model lazily inside the first GPU call so TensorFlow's | |
| device discovery happens while the ZeroGPU device is visible.""" | |
| global _MODEL | |
| if _MODEL is None: | |
| import keras | |
| import keras_nlp # noqa: F401 (needed to deserialize GemmaDecoderBlock) | |
| if MODEL_FILES["kind"] == "full": | |
| _MODEL = keras.models.load_model(MODEL_FILES["full"]) | |
| else: | |
| m = keras.models.load_model(MODEL_FILES["arch"]) | |
| m.load_weights(MODEL_FILES["weights"]) | |
| _MODEL = m | |
| print("model loaded | output shape:", _MODEL.output_shape, flush=True) | |
| return _MODEL | |
| # ---------------- sampler (project protocol + optional truncation) ---------------- | |
| def _sample_batch(model, n, temp, steps, seed, top_p, top_k, bs=250): | |
| rng = np.random.default_rng(seed) | |
| out = [] | |
| for start in range(0, n, bs): | |
| m = min(bs, n - start) | |
| x = np.full((m, 1), SEED_TOKEN_ID, dtype=np.int32) | |
| for _ in range(steps): | |
| logits = model({"token_ids": x, | |
| "padding_mask": (x != PAD_ID).astype(np.int32)}, | |
| training=False).numpy() | |
| lg = logits[:, -1, :].astype(np.float64) | |
| # Optional truncation of the distribution (raw logits, | |
| # before temperature scaling). Defaults disable both, which | |
| # makes this exactly the protocol sampler. | |
| if top_k and int(top_k) > 0: | |
| k = min(int(top_k), lg.shape[-1]) | |
| idx = np.argpartition(lg, -k, axis=-1)[:, -k:] | |
| masked = np.full(lg.shape, -np.inf) | |
| np.put_along_axis( | |
| masked, idx, np.take_along_axis(lg, idx, axis=-1), axis=-1) | |
| lg = masked | |
| if top_p is not None and float(top_p) < 1.0: | |
| p0 = np.exp(lg - lg.max(axis=-1, keepdims=True)) | |
| p0 /= p0.sum(axis=-1, keepdims=True) | |
| order = np.argsort(-p0, axis=-1) | |
| sorted_p = np.take_along_axis(p0, order, axis=-1) | |
| cum = np.cumsum(sorted_p, axis=-1) | |
| keep_sorted = (cum - sorted_p) < float(top_p) | |
| keep = np.zeros(lg.shape, dtype=bool) | |
| np.put_along_axis(keep, order, keep_sorted, axis=-1) | |
| lg = np.where(keep, lg, -np.inf) | |
| lg = lg / float(temp) | |
| lg -= lg.max(axis=-1, keepdims=True) | |
| p = np.exp(lg) | |
| p /= p.sum(axis=-1, keepdims=True) | |
| nxt = np.array([rng.choice(p.shape[-1], p=row) for row in p], | |
| dtype=np.int32)[:, None] | |
| x = np.concatenate([x, nxt], axis=1) | |
| for row in x: | |
| out.append(TOK.decode([int(i) for i in row])) | |
| return out | |
| # ---------------- main action ---------------- | |
| def run_generation(n_samples, temp_sel, seed, max_steps, top_p, top_k): | |
| n_samples = int(n_samples) | |
| seed = int(seed) | |
| max_steps = int(max_steps) | |
| top_p = float(top_p) | |
| top_k = int(top_k) | |
| if temp_sel == "Both": | |
| n_a = (n_samples + 1) // 2 | |
| jobs = [(n_a, 0.8, seed), (n_samples - n_a, 1.0, seed + 101)] | |
| temp_desc = "Both (0.8 + 1.0)" | |
| elif temp_sel == "1.0": | |
| jobs = [(n_samples, 1.0, seed)] | |
| temp_desc = "1.0" | |
| else: | |
| jobs = [(n_samples, 0.8, seed)] | |
| temp_desc = "0.8" | |
| model = _ensure_model() | |
| raw_all = [] | |
| for nj, temp, sd in jobs: | |
| if nj <= 0: | |
| continue | |
| for s in _sample_batch(model, nj, temp, max_steps, sd, top_p, top_k): | |
| raw_all.append((s, temp)) | |
| # RDKit validation + novelty | |
| rows = [] | |
| for raw, temp in raw_all: | |
| mol = Chem.MolFromSmiles(raw) if raw else None | |
| can = Chem.MolToSmiles(mol) if mol is not None else None | |
| rows.append({"raw": raw, "temp": temp, "canonical": can}) | |
| # LTN pIC50 for the unique valid molecules, mapped back to rows | |
| uniq = sorted({r["canonical"] for r in rows if r["canonical"]}) | |
| scores = {} | |
| if uniq: | |
| ltn_model = ltn_infer.load_model() | |
| feats = ltn_infer.featurise_4608(uniq) | |
| preds = ltn_model.predict(feats, verbose=0).ravel() | |
| scores = {s: float(p) for s, p in zip(uniq, preds)} | |
| table = [] | |
| n_valid = 0 | |
| n_novel = 0 | |
| for i, r in enumerate(rows, start=1): | |
| can = r["canonical"] | |
| if can is None: | |
| table.append([i, r["raw"], "No", "—", "", "", ""]) | |
| continue | |
| n_valid += 1 | |
| novel = can not in FINETUNE_CANON | |
| if novel: | |
| n_novel += 1 | |
| p = scores.get(can) | |
| table.append([i, can, "Yes", "Yes" if novel else "No", | |
| round(p, 3) if p is not None else "", | |
| round(10 ** (9 - p), 2) if p is not None else "", | |
| ltn_infer.classify(p) if p is not None else ""]) | |
| n_unique = len(uniq) | |
| valid_pct = round(100.0 * n_valid / len(rows), 1) if rows else 0.0 | |
| args_line = (f"n={n_samples} · temperature={temp_desc} · seed={seed} · " | |
| f"max_steps={max_steps} · top_p={top_p} · top_k={top_k}") | |
| summary = (f"**Generated {len(rows)} molecules** — valid (RDKit): " | |
| f"**{n_valid}** ({valid_pct}%) · unique valid: **{n_unique}** · " | |
| f"novel vs fine-tune set: **{n_novel}**\n\n" | |
| f"Arguments: {args_line}") | |
| # Downloadable CSV with a parameter header block | |
| df = pd.DataFrame( | |
| table, | |
| columns=["n", "smiles", "valid_rdkit", "novel_vs_finetune", | |
| "pred_pIC50_LTN", "pred_IC50_nM_LTN", "potency_class_LTN"]) | |
| csv_path = "/tmp/molgemma_generations.csv" | |
| with open(csv_path, "w") as f: | |
| f.write("# MolGemma - DPP-4 fine-tuned (epoch 4, val loss 0.1800) " | |
| "generation output\n") | |
| f.write(f"# base model: Delower/MolGemma | weights: {FT_REPO}\n") | |
| f.write(f"# {args_line}\n") | |
| f.write("# novelty reference: 6,835 canonical compounds of the " | |
| "fine-tune set\n") | |
| f.write("# pIC50/IC50/class: tuned DPP-4 LTN (Delower/dpp4-pic50-ltn)\n") | |
| df.to_csv(f, index=False) | |
| return summary, table, csv_path | |
| ABOUT = """ | |
| ## Model | |
| **MolGemma — DPP-4 fine-tuned (epoch 4, val loss 0.1800)**, a fine-tune of | |
| Delower/MolGemma on the DPP-4 potent+moderate+FDA-12 set (9,338 SMILES, | |
| AdamW lr 2e-5, batch 32, DeepChem-591 tokenizer). Training was stopped | |
| after epoch 4; this app serves that best checkpoint. | |
| ## How generation works | |
| Autoregressive temperature sampling seeded with the token `C`, exactly as | |
| in the project generation protocol (86 steps = token-length p99 + 5). | |
| With **top-p = 1.0** and **top-k = 0** (the defaults) the sampler is the | |
| unmodified protocol sampler. Setting top-p or top-k truncates the | |
| distribution before temperature scaling. | |
| ## Validation & scoring columns | |
| - **Valid (RDKit)** — the sampled string parses as a molecule; the SMILES | |
| shown is the RDKit canonical form. | |
| - **Novel vs fine-tune set** — canonical SMILES is not among the 6,835 | |
| canonical compounds of the fine-tune set. | |
| - **pIC50 / IC50 / class** — the deployed tuned DPP-4 LTN model | |
| (Delower/dpp4-pic50-ltn; fingerprint-4608 features). Classes from the | |
| LTN bundle: potent pIC50 ≥ 7 · moderate 5–7 · weak < 5. | |
| ## Notes | |
| Generation runs on a ZeroGPU A10G. Very large requests (1,000 samples at | |
| 160 steps) can approach the free GPU time limit per call; if a call times | |
| out, reduce the sample count or steps. | |
| """ | |
| with gr.Blocks(title="MolGemma DPP-4 Generator") as demo: | |
| gr.Markdown( | |
| "# 🧪 MolGemma — DPP-4 Molecule Generator\n" | |
| "**Model: MolGemma — DPP-4 fine-tuned (epoch 4, val loss 0.1800)** · " | |
| "base: Delower/MolGemma · weights: Delower/dpp4-molgemma-finetuned") | |
| with gr.Row(): | |
| n_in = gr.Radio(choices=[100, 250, 500, 1000], value=100, | |
| label="Number of samples") | |
| temp_in = gr.Radio(choices=["0.8", "1.0", "Both"], value="0.8", | |
| label="Temperature") | |
| seed_in = gr.Number(value=101, precision=0, label="Seed") | |
| with gr.Accordion("Advanced generation arguments", open=False): | |
| steps_in = gr.Slider(minimum=40, maximum=160, value=PROTOCOL_STEPS, | |
| step=1, | |
| label="Max generation length (steps) — " | |
| "protocol value 86 = token p99 + 5") | |
| topp_in = gr.Slider(minimum=0.0, maximum=1.0, value=1.0, step=0.01, | |
| label="Top-p (nucleus) — 1.0 = off " | |
| "(protocol-identical)") | |
| topk_in = gr.Number(value=0, precision=0, | |
| label="Top-k — 0 = off (protocol-identical)") | |
| btn = gr.Button("Generate molecules", variant="primary") | |
| summary_out = gr.Markdown() | |
| table_out = gr.Dataframe( | |
| headers=["#", "SMILES", "Valid (RDKit)", "Novel vs fine-tune set", | |
| "Predicted pIC50 (LTN)", "IC50 (nM)", "Potency class"], | |
| label="Generated molecules") | |
| dl_out = gr.File(label="Download results CSV") | |
| btn.click(run_generation, | |
| inputs=[n_in, temp_in, seed_in, steps_in, topp_in, topk_in], | |
| outputs=[summary_out, table_out, dl_out]) | |
| with gr.Accordion("About this app", open=False): | |
| gr.Markdown(ABOUT) | |
| if __name__ == "__main__": | |
| demo.launch(server_name="0.0.0.0", | |
| server_port=int(os.environ.get("PORT", 7860))) | |