Text Generation
MLX
Safetensors
English
gemma4_text
mlx-lm
apple-silicon
macos
cellgemma
gemma4
biology
single-cell
transcriptomics
gene-expression
perturbation-prediction
crispr
4-bit precision
Run this model with HF Jobs
Run bsisduck/cellgemma-e4b-mlx-4bit on Hugging Face's managed compute, monitor its progress, and retrieve the results when it's done.
Paste one of these prompts into your coding agent:
Fine-tune on my dataset
Use HF Jobs to fine-tune https://huggingface.co/bsisduck/cellgemma-e4b-mlx-4bit. Ask me which dataset to train on, then push the fine-tuned model to a new model repo. Run `hf jobs --help` first to learn the CLI.
Run batch inference
Use HF Jobs to run batch inference with https://huggingface.co/bsisduck/cellgemma-e4b-mlx-4bit on the inputs in a mounted HF Bucket. Ask me which Bucket to use, then write the outputs back to it and keep each input ID. Run `hf jobs --help` first to learn the CLI.
Evaluate on a benchmark
Use HF Jobs to evaluate https://huggingface.co/bsisduck/cellgemma-e4b-mlx-4bit. Ask me which benchmark to run, then save the scores and the per-example results to a new dataset repo. Run `hf jobs --help` first to learn the CLI.
Instructions to use bsisduck/cellgemma-e4b-mlx-4bit with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- MLX
How to use bsisduck/cellgemma-e4b-mlx-4bit with MLX:
# Make sure mlx-lm is installed # pip install --upgrade mlx-lm # if on a CUDA device, also pip install mlx[cuda] # Generate text with mlx-lm from mlx_lm import load, generate model, tokenizer = load("bsisduck/cellgemma-e4b-mlx-4bit") prompt = "Once upon a time in" text = generate(model, tokenizer, prompt=prompt, verbose=True) - Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- LM Studio
- MLX LM
How to use bsisduck/cellgemma-e4b-mlx-4bit with MLX LM:
Generate or start a chat session
# Install MLX LM uv tool install mlx-lm # Generate some text mlx_lm.generate --model "bsisduck/cellgemma-e4b-mlx-4bit" --prompt "Once upon a time"
- Atomic Chat
File size: 9,025 Bytes
374f684 | 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 | """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("<turn|>")
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()
|