"""Run the supplied Tahoe or K562 example; optionally measure repeated inference. Apache-2.0. Prompt and expression reconstruction follow Google's CellGemma card. Run from this project with `python -m cellgemma.examples.predict --model PATH`. The Hub export places biology.py and decoder.py beside this script. """ from __future__ import annotations import argparse import csv from datetime import datetime, timezone import hashlib import importlib.metadata import json import os from pathlib import Path import platform import statistics import time import mlx.core as mx from mlx_lm import load, stream_generate from mlx_lm.sample_utils import make_sampler import numpy as np if __package__: from ..engine.biology import DRUG_EXAMPLE, build_prompt, mean_baseline, ranked_genes, reconstruct from ..engine.decoder import ExpressionDecoder else: from biology import DRUG_EXAMPLE, build_prompt, mean_baseline, ranked_genes, reconstruct from decoder import ExpressionDecoder def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--model", type=Path, default=Path(__file__).resolve().parents[1]) parser.add_argument("--dataset", choices=["tahoe", "k562"], default="tahoe") parser.add_argument("--cell-index", type=int, default=0) parser.add_argument("--knockdown-gene", default="MYC", help="K562 only") parser.add_argument("--max-tokens", type=int, default=512, help="Use 8192 for the upstream output budget") parser.add_argument("--seed", type=int, default=42) parser.add_argument("--runs", type=int, default=1) parser.add_argument("--warmup", type=int, default=0, help="Untimed-summary warmup runs, still retained in JSON") parser.add_argument("--output", type=Path, default=Path("cellgemma-result")) args = parser.parse_args() if not 1 <= args.max_tokens <= 8192 or args.runs < 1 or args.warmup < 0: parser.error("Use 1 to 8192 tokens, at least one run and non-negative warmup.") if args.output.exists() and any(args.output.iterdir()): parser.error("Output directory is not empty; choose a new --output path.") args.output.mkdir(parents=True, exist_ok=True) path = args.model.resolve() conversion = json.loads((path / "conversion.json").read_text()) device = mx.device_info() weight_bytes = sum(p.stat().st_size for p in path.glob("*.safetensors")) mx.set_cache_limit(256 * 1024**2) mx.set_wired_limit(min(int(device["max_recommended_working_set_size"]), int(device["memory_size"] * 0.75), weight_bytes + 2 * 1024**3)) started = time.perf_counter() model, tokenizer = load(str(path)) mx.synchronize() load_seconds = time.perf_counter() - started print(f"Model loaded in {load_seconds:.2f}s", flush=True) tokenizer.add_eos_token("") sample = json.loads((path / "controls_sample.json").read_text())[args.dataset] if not 0 <= args.cell_index < len(sample["cells"]): parser.error("Cell index is outside the supplied sample.") genes = [g.upper() for g in sample["genes"]] cell = sample["cells"][args.cell_index] control = np.asarray(cell["expression"], dtype=np.float32) decoder = ExpressionDecoder(path / "decoders" / args.dataset) mx.eval(decoder.weights) baseline = mean_baseline(genes, control, decoder.means) perturbation = DRUG_EXAMPLE if args.dataset == "k562": knowledge = json.loads((path / "kg_sentences.json").read_text()) gene = args.knockdown_gene.upper() if gene not in knowledge: parser.error(f"No supplied gene description for {gene}") perturbation = f"Gene knockdown: {knowledge[gene].strip()}" prompt = build_prompt(perturbation, genes, control, baseline) tokens = tokenizer.encode(prompt, add_special_tokens=False) if len(tokens) + args.max_tokens > 16384: parser.error("Prompt and output budget exceed the documented 16K context.") assert tokens.count(tokenizer.bos_token_id) == 1 report = { "created_at": datetime.now(timezone.utc).isoformat(), "kind": "local_inference_timing", "biological_benchmark": False, "model": {"bits": conversion["bits"], "source": conversion["source"], "source_revision": conversion["source_revision"], "weight_file_bytes": weight_bytes}, "environment": {"device": device["device_name"], "unified_memory_bytes": device["memory_size"], "macos": platform.mac_ver()[0], "python": platform.python_version(), "versions": {p: importlib.metadata.version(p) for p in ("mlx", "mlx-lm", "transformers", "numpy", "huggingface-hub")}, "load_average_at_start": os.getloadavg(), "other_applications_stopped": False}, "settings": {"dataset": args.dataset, "cell_index": args.cell_index, "cell_id": cell["cell_id"], "perturbation": perturbation, "prompt_tokens": len(tokens), "prompt_sha256": hashlib.sha256(prompt.encode()).hexdigest(), "max_tokens": args.max_tokens, "seed": args.seed, "temperature": 0.7, "top_p": 0.95, "top_k": 64, "prefill_step_size": 256, "warmup_runs": args.warmup, "measured_runs": args.runs, "prompt_cache_reused": False}, "model_load_seconds": load_seconds, "runs": [], "limitations": "Local timing on one control cell, not biological evaluation. Other desktop apps remained open. Download and model load are excluded from run times. MLX peak allocation is not total system memory." } report_path = args.output / "benchmark.json" report_path.write_text(json.dumps(report, indent=2) + "\n") for i in range(args.warmup + args.runs): mx.reset_peak_memory() mx.random.seed(args.seed) mx.synchronize() started = time.perf_counter() first_token_seconds = None text, last = "", None def prefill_progress(done, total): if done % 1024 == 0 or done == total: print(f"Run {i + 1}: prompt {done}/{total}", flush=True) for response in stream_generate(model, tokenizer, prompt=tokens, max_tokens=args.max_tokens, prefill_step_size=256, prompt_progress_callback=prefill_progress, sampler=make_sampler(temp=0.7, top_p=0.95, top_k=64)): if first_token_seconds is None: first_token_seconds = time.perf_counter() - started text += response.text last = response mx.synchronize() generation_seconds = time.perf_counter() - started if last is None: raise RuntimeError("No generated tokens") up, down = ranked_genes(text, genes) if not up and not down: raise RuntimeError("No recognized signed genes; inspect the prompt and model files") predicted, change = reconstruct(text, genes, control, baseline, decoder) run = {"index": i + 1, "warmup": i < args.warmup, "first_token_seconds": first_token_seconds, "generation_seconds": generation_seconds, "prediction_seconds": time.perf_counter() - started, "prompt_tokens_per_second": last.prompt_tps, "generation_tokens_per_second": last.generation_tps, "generated_tokens": last.generation_tokens, "finish_reason": last.finish_reason, "truncated": last.finish_reason == "length", "mlx_peak_memory_gb": mx.get_peak_memory() / 1e9, "recognized_up_entries": len(up), "recognized_down_entries": len(down), "expression_rows": len(genes), "output_sha256": hashlib.sha256(text.encode()).hexdigest()} report["runs"].append(run) report_path.write_text(json.dumps(report, indent=2) + "\n") (args.output / "residual_genes.txt").write_text(text + "\n") with (args.output / "expression.csv").open("w", newline="") as handle: writer = csv.writer(handle) writer.writerow(["gene", "control", "mean_baseline", "predicted_expression", "change"]) writer.writerows(zip(genes, control, baseline, predicted, change)) print(json.dumps(run), flush=True) measured = [run for run in report["runs"] if not run["warmup"]] report["summary"] = {key: {"median": statistics.median(run[key] for run in measured), "min": min(run[key] for run in measured), "max": max(run[key] for run in measured)} for key in ("first_token_seconds", "prediction_seconds", "generation_tokens_per_second", "mlx_peak_memory_gb")} report_path.write_text(json.dumps(report, indent=2) + "\n") print(f"Saved {len(genes)} expression rows and timing details to {args.output}") if __name__ == "__main__": main()