cellscreen 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- cellscreen/__init__.py +3 -0
- cellscreen/_bundled/examples/k562_crispr.json +42 -0
- cellscreen/_bundled/examples/tahoe_drugs.json +53 -0
- cellscreen/_bundled/skills/agents/cellscreen/SKILL.md +59 -0
- cellscreen/_bundled/skills/agents/cellscreen/references/reference.md +86 -0
- cellscreen/_bundled/skills/claude/cellscreen/SKILL.md +59 -0
- cellscreen/assets.py +125 -0
- cellscreen/bundled.py +154 -0
- cellscreen/cli.py +513 -0
- cellscreen/constants.py +117 -0
- cellscreen/decoder.py +222 -0
- cellscreen/fanner.py +366 -0
- cellscreen/prompts.py +142 -0
- cellscreen/quantize.py +118 -0
- cellscreen/report.py +1359 -0
- cellscreen/schemas.py +217 -0
- cellscreen/server.py +395 -0
- cellscreen/store.py +313 -0
- cellscreen-0.1.0.dist-info/METADATA +198 -0
- cellscreen-0.1.0.dist-info/RECORD +24 -0
- cellscreen-0.1.0.dist-info/WHEEL +4 -0
- cellscreen-0.1.0.dist-info/entry_points.txt +4 -0
- cellscreen-0.1.0.dist-info/licenses/LICENSE +202 -0
- cellscreen-0.1.0.dist-info/licenses/NOTICE +10 -0
cellscreen/cli.py
ADDED
|
@@ -0,0 +1,513 @@
|
|
|
1
|
+
"""Unified Typer + Rich CLI for CellScreen.
|
|
2
|
+
|
|
3
|
+
Every command operates statelessly on a run directory (`manifest.json` + `results.jsonl`)
|
|
4
|
+
so Claude Code, Codex, and Antigravity can start, inspect, resume, and report on any run
|
|
5
|
+
without sharing session memory.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import json
|
|
11
|
+
import re
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
|
|
14
|
+
import httpx
|
|
15
|
+
import typer
|
|
16
|
+
from rich.console import Console
|
|
17
|
+
from rich.panel import Panel
|
|
18
|
+
from rich.progress import (
|
|
19
|
+
BarColumn,
|
|
20
|
+
MofNCompleteColumn,
|
|
21
|
+
Progress,
|
|
22
|
+
SpinnerColumn,
|
|
23
|
+
TextColumn,
|
|
24
|
+
TimeElapsedColumn,
|
|
25
|
+
)
|
|
26
|
+
from rich.table import Table
|
|
27
|
+
|
|
28
|
+
from cellscreen import __version__
|
|
29
|
+
from cellscreen.bundled import (
|
|
30
|
+
EXAMPLE_SPECS,
|
|
31
|
+
install_agent_skills,
|
|
32
|
+
resolve_example_path,
|
|
33
|
+
)
|
|
34
|
+
from cellscreen.constants import (
|
|
35
|
+
DATASET_REGISTRY,
|
|
36
|
+
DEFAULT_CONCURRENCY,
|
|
37
|
+
DEFAULT_HF_MODEL_ID,
|
|
38
|
+
DEFAULT_MAX_NEW_TOKENS,
|
|
39
|
+
DEFAULT_REQUEST_TIMEOUT_S,
|
|
40
|
+
DEFAULT_SERVER_HOST,
|
|
41
|
+
DEFAULT_SERVER_PORT,
|
|
42
|
+
DEFAULT_TEMPERATURE,
|
|
43
|
+
)
|
|
44
|
+
from cellscreen.fanner import run_fanner_sync
|
|
45
|
+
from cellscreen.quantize import QuantizationSpec, QuantRecipe, quantize_cellgemma
|
|
46
|
+
from cellscreen.report import generate_report
|
|
47
|
+
from cellscreen.schemas import GenerationConfig, PerturbationSpec, RunManifest, ScreenResultRecord
|
|
48
|
+
from cellscreen.server import run_server
|
|
49
|
+
from cellscreen.store import RunStore
|
|
50
|
+
|
|
51
|
+
app = typer.Typer(
|
|
52
|
+
name="cellscreen",
|
|
53
|
+
help="Open-source, Mac-local, stateless cellular perturbation screening with DeepMind CellGemma E4B on Apple MLX.",
|
|
54
|
+
no_args_is_help=True,
|
|
55
|
+
add_completion=False,
|
|
56
|
+
)
|
|
57
|
+
console = Console()
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def _slugify(text: str) -> str:
|
|
61
|
+
slug = re.sub(r"[^a-z0-9]+", "-", text.lower()).strip("-")
|
|
62
|
+
return slug or "screen-run"
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
@app.command("version")
|
|
66
|
+
def version_cmd() -> None:
|
|
67
|
+
"""Print CellScreen version."""
|
|
68
|
+
console.print(f"cellscreen {__version__}")
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
@app.command("list-decoders")
|
|
72
|
+
def list_decoders_cmd(
|
|
73
|
+
as_json: bool = typer.Option(False, "--json", help="Emit JSON for coding agents"),
|
|
74
|
+
) -> None:
|
|
75
|
+
"""List all 13 pretrained CellGemma Stage-2 ExpressionDecoders."""
|
|
76
|
+
if as_json:
|
|
77
|
+
typer.echo(json.dumps(DATASET_REGISTRY, indent=2))
|
|
78
|
+
return
|
|
79
|
+
|
|
80
|
+
table = Table(title="CellGemma E4B Pretrained ExpressionDecoders")
|
|
81
|
+
table.add_column("Dataset", style="bold cyan")
|
|
82
|
+
table.add_column("Modality", style="magenta")
|
|
83
|
+
table.add_column("Benchmark", style="bold")
|
|
84
|
+
table.add_column("Description")
|
|
85
|
+
for key, info in DATASET_REGISTRY.items():
|
|
86
|
+
table.add_row(key, info["modality"], info["label"], info["description"])
|
|
87
|
+
console.print(table)
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
@app.command("quantize")
|
|
91
|
+
def quantize_cmd(
|
|
92
|
+
hf_path: str = typer.Option(DEFAULT_HF_MODEL_ID, "--model", help="Source Hugging Face repo or local path"),
|
|
93
|
+
output_dir: Path = typer.Option(
|
|
94
|
+
Path("models/cellgemma-e4b-mlx-4bit-ple"),
|
|
95
|
+
"--output",
|
|
96
|
+
"-o",
|
|
97
|
+
help="Destination directory for PLE-safe MLX checkpoint",
|
|
98
|
+
),
|
|
99
|
+
bits: int = typer.Option(4, "--bits", help="Quantization bit-width for attention/MLP layers (4 or 8)"),
|
|
100
|
+
group_size: int = typer.Option(64, "--group-size", help="Quantization group size"),
|
|
101
|
+
recipe: QuantRecipe = typer.Option(
|
|
102
|
+
"ple_bf16",
|
|
103
|
+
"--recipe",
|
|
104
|
+
help="Quantization recipe: ple_bf16 (recommended, keeps PLE/embeddings in bf16), ple_q8, or uniform",
|
|
105
|
+
),
|
|
106
|
+
force: bool = typer.Option(False, "--force", help="Overwrite destination directory if it exists"),
|
|
107
|
+
) -> None:
|
|
108
|
+
"""Convert google/cellgemma-e4b to a PLE-safe quantized Apple MLX checkpoint."""
|
|
109
|
+
spec = QuantizationSpec(
|
|
110
|
+
hf_path=hf_path,
|
|
111
|
+
output_dir=str(output_dir),
|
|
112
|
+
bits=bits,
|
|
113
|
+
group_size=group_size,
|
|
114
|
+
recipe=recipe,
|
|
115
|
+
)
|
|
116
|
+
console.print(
|
|
117
|
+
Panel.fit(
|
|
118
|
+
f"[bold]Source:[/bold] {spec.hf_path}\n"
|
|
119
|
+
f"[bold]Output:[/bold] {spec.output_dir}\n"
|
|
120
|
+
f"[bold]Recipe:[/bold] {spec.recipe} ({spec.bits}-bit attn/MLP, group_size={spec.group_size})",
|
|
121
|
+
title="CellScreen PLE-Safe MLX Quantization",
|
|
122
|
+
border_style="cyan",
|
|
123
|
+
)
|
|
124
|
+
)
|
|
125
|
+
out_path = quantize_cellgemma(spec, force=force)
|
|
126
|
+
console.print(f"[green]Quantized MLX checkpoint saved to:[/green] {out_path}")
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
@app.command("serve")
|
|
130
|
+
def serve_cmd(
|
|
131
|
+
model: str = typer.Option(
|
|
132
|
+
DEFAULT_HF_MODEL_ID,
|
|
133
|
+
"--model",
|
|
134
|
+
"-m",
|
|
135
|
+
help="Path to PLE-safe MLX checkpoint directory or HF model id",
|
|
136
|
+
),
|
|
137
|
+
host: str = typer.Option(DEFAULT_SERVER_HOST, "--host"),
|
|
138
|
+
port: int = typer.Option(DEFAULT_SERVER_PORT, "--port", "-p"),
|
|
139
|
+
mock: bool = typer.Option(
|
|
140
|
+
False,
|
|
141
|
+
"--mock",
|
|
142
|
+
help="Start deterministic mock backend for offline testing without weights",
|
|
143
|
+
),
|
|
144
|
+
) -> None:
|
|
145
|
+
"""Start the thin, stateless local Apple MLX inference server."""
|
|
146
|
+
console.print(
|
|
147
|
+
f"[bold cyan]CellScreen Server[/bold cyan] listening on http://{host}:{port} "
|
|
148
|
+
f"([bold]{'mock' if mock else 'mlx'}[/bold] backend · model={model})"
|
|
149
|
+
)
|
|
150
|
+
run_server(model, host=host, port=port, mock=mock)
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def _try_json_dict(resp: httpx.Response) -> dict | None:
|
|
154
|
+
if resp.status_code != 200 or not resp.content:
|
|
155
|
+
return None
|
|
156
|
+
try:
|
|
157
|
+
data = resp.json()
|
|
158
|
+
except ValueError:
|
|
159
|
+
return None
|
|
160
|
+
return data if isinstance(data, dict) else None
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def probe_server_health(
|
|
164
|
+
server_url: str,
|
|
165
|
+
*,
|
|
166
|
+
client: httpx.Client | None = None,
|
|
167
|
+
timeout: float = 5.0,
|
|
168
|
+
) -> dict:
|
|
169
|
+
"""Inspect a CellScreen MLX/mock server or fall back to OpenAI-compatible /v1/models (vLLM)."""
|
|
170
|
+
base = server_url.rstrip("/")
|
|
171
|
+
own_client = client is None
|
|
172
|
+
http = client if client is not None else httpx.Client(timeout=timeout)
|
|
173
|
+
try:
|
|
174
|
+
health_resp = http.get(f"{base}/health", timeout=timeout)
|
|
175
|
+
health_json = _try_json_dict(health_resp)
|
|
176
|
+
|
|
177
|
+
# Native CellScreen server exposes JSON /health (with "backend") and JSON /metrics.
|
|
178
|
+
if health_json is not None and "backend" in health_json:
|
|
179
|
+
metrics_resp = http.get(f"{base}/metrics", timeout=timeout)
|
|
180
|
+
metrics_json = _try_json_dict(metrics_resp)
|
|
181
|
+
return {"health": health_json, "metrics": metrics_json}
|
|
182
|
+
|
|
183
|
+
# vLLM (empty 200 /health + Prometheus text /metrics) or any OpenAI-compatible server.
|
|
184
|
+
models_resp = http.get(f"{base}/v1/models", timeout=timeout)
|
|
185
|
+
models_resp.raise_for_status()
|
|
186
|
+
models_data = models_resp.json()
|
|
187
|
+
entries = models_data.get("data", []) if isinstance(models_data, dict) else []
|
|
188
|
+
model_ids = [str(item["id"]) for item in entries if isinstance(item, dict) and "id" in item]
|
|
189
|
+
owned_by = {
|
|
190
|
+
str(item.get("owned_by", "")).lower() for item in entries if isinstance(item, dict)
|
|
191
|
+
}
|
|
192
|
+
backend = "vllm" if "vllm" in owned_by else "openai-compatible"
|
|
193
|
+
return {
|
|
194
|
+
"health": {
|
|
195
|
+
"status": "ok",
|
|
196
|
+
"backend": backend,
|
|
197
|
+
"model": model_ids[0] if model_ids else "unknown",
|
|
198
|
+
"models": model_ids,
|
|
199
|
+
},
|
|
200
|
+
"metrics": None,
|
|
201
|
+
}
|
|
202
|
+
finally:
|
|
203
|
+
if own_client:
|
|
204
|
+
http.close()
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
@app.command("health")
|
|
208
|
+
def health_cmd(
|
|
209
|
+
server_url: str = typer.Option(
|
|
210
|
+
f"http://{DEFAULT_SERVER_HOST}:{DEFAULT_SERVER_PORT}",
|
|
211
|
+
"--server-url",
|
|
212
|
+
),
|
|
213
|
+
as_json: bool = typer.Option(False, "--json"),
|
|
214
|
+
) -> None:
|
|
215
|
+
"""Check health of a CellScreen MLX/mock server or an OpenAI-compatible server (e.g. vLLM)."""
|
|
216
|
+
try:
|
|
217
|
+
payload = probe_server_health(server_url)
|
|
218
|
+
except Exception as exc:
|
|
219
|
+
console.print(f"[red]Server unreachable at {server_url}:[/red] {exc}")
|
|
220
|
+
raise typer.Exit(code=1) from exc
|
|
221
|
+
|
|
222
|
+
if as_json:
|
|
223
|
+
typer.echo(json.dumps(payload, indent=2))
|
|
224
|
+
return
|
|
225
|
+
|
|
226
|
+
health = payload["health"]
|
|
227
|
+
metrics = payload.get("metrics")
|
|
228
|
+
lines = [f"[green]Status:[/green] {health.get('status', 'ok')}"]
|
|
229
|
+
if "metal_available" in health:
|
|
230
|
+
lines.append(
|
|
231
|
+
f"[bold]Backend:[/bold] {health['backend']} (Metal={health['metal_available']})"
|
|
232
|
+
)
|
|
233
|
+
else:
|
|
234
|
+
lines.append(f"[bold]Backend:[/bold] {health.get('backend', 'unknown')}")
|
|
235
|
+
lines.append(f"[bold]Model:[/bold] {health.get('model', 'unknown')}")
|
|
236
|
+
if isinstance(metrics, dict):
|
|
237
|
+
lines.append(
|
|
238
|
+
f"[bold]Requests:[/bold] {metrics['requests_ok']}/{metrics['requests_total']} ok "
|
|
239
|
+
f"(avg {metrics['avg_generation_tps']} tok/s, peak {metrics['peak_memory_gb']} GB)"
|
|
240
|
+
)
|
|
241
|
+
console.print(Panel.fit("\n".join(lines), title=f"CellScreen Server · {server_url}"))
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
@app.command("init")
|
|
245
|
+
def init_cmd(
|
|
246
|
+
run_dir: Path = typer.Argument(..., help="Target directory for the stateless run"),
|
|
247
|
+
spec_file: Path | None = typer.Option(
|
|
248
|
+
None,
|
|
249
|
+
"--from",
|
|
250
|
+
"-f",
|
|
251
|
+
exists=True,
|
|
252
|
+
readable=True,
|
|
253
|
+
help="JSON file defining perturbations (full RunManifest or list of PerturbationSpec)",
|
|
254
|
+
),
|
|
255
|
+
example: str | None = typer.Option(
|
|
256
|
+
None,
|
|
257
|
+
"--example",
|
|
258
|
+
"-e",
|
|
259
|
+
help="Use a bundled example screen ('tahoe' or 'k562') instead of --from",
|
|
260
|
+
),
|
|
261
|
+
dataset: str | None = typer.Option(None, "--dataset", "-d", help="Override decoder dataset"),
|
|
262
|
+
cell_idx: int | None = typer.Option(None, "--cell-idx", help="Override control cell index"),
|
|
263
|
+
server_url: str | None = typer.Option(None, "--server-url", help="Override local MLX server URL"),
|
|
264
|
+
temperature: float | None = typer.Option(None, "--temperature"),
|
|
265
|
+
max_tokens: int | None = typer.Option(None, "--max-tokens"),
|
|
266
|
+
overwrite: bool = typer.Option(False, "--overwrite"),
|
|
267
|
+
) -> None:
|
|
268
|
+
"""Initialize a self-contained stateless CellScreen run directory (manifest.json + results.jsonl)."""
|
|
269
|
+
if (spec_file is None) == (example is None):
|
|
270
|
+
raise typer.BadParameter("Specify exactly one of --from <file.json> or --example <name>.")
|
|
271
|
+
if example is not None:
|
|
272
|
+
try:
|
|
273
|
+
spec_file = resolve_example_path(example)
|
|
274
|
+
except KeyError as exc:
|
|
275
|
+
raise typer.BadParameter(str(exc)) from exc
|
|
276
|
+
assert spec_file is not None
|
|
277
|
+
raw = json.loads(spec_file.read_text(encoding="utf-8"))
|
|
278
|
+
if isinstance(raw, list):
|
|
279
|
+
if not dataset:
|
|
280
|
+
raise typer.BadParameter("--dataset is required when --from contains a bare perturbation list")
|
|
281
|
+
manifest = RunManifest(
|
|
282
|
+
run_id=_slugify(run_dir.name),
|
|
283
|
+
title=f"CellScreen · {run_dir.name}",
|
|
284
|
+
dataset=dataset.lower(),
|
|
285
|
+
cell_idx=cell_idx if cell_idx is not None else 0,
|
|
286
|
+
server_url=server_url or f"http://{DEFAULT_SERVER_HOST}:{DEFAULT_SERVER_PORT}",
|
|
287
|
+
generation=GenerationConfig(
|
|
288
|
+
temperature=temperature if temperature is not None else DEFAULT_TEMPERATURE,
|
|
289
|
+
max_new_tokens=max_tokens if max_tokens is not None else DEFAULT_MAX_NEW_TOKENS,
|
|
290
|
+
),
|
|
291
|
+
perturbations=[PerturbationSpec.model_validate(item) for item in raw],
|
|
292
|
+
)
|
|
293
|
+
else:
|
|
294
|
+
if dataset is not None:
|
|
295
|
+
raw["dataset"] = dataset.lower()
|
|
296
|
+
if cell_idx is not None:
|
|
297
|
+
raw["cell_idx"] = cell_idx
|
|
298
|
+
if server_url is not None:
|
|
299
|
+
raw["server_url"] = server_url
|
|
300
|
+
if "run_id" not in raw or not raw["run_id"]:
|
|
301
|
+
raw["run_id"] = _slugify(run_dir.name)
|
|
302
|
+
gen = dict(raw.get("generation") or {})
|
|
303
|
+
if temperature is not None:
|
|
304
|
+
gen["temperature"] = temperature
|
|
305
|
+
if max_tokens is not None:
|
|
306
|
+
gen["max_new_tokens"] = max_tokens
|
|
307
|
+
if gen:
|
|
308
|
+
raw["generation"] = gen
|
|
309
|
+
manifest = RunManifest.model_validate(raw)
|
|
310
|
+
|
|
311
|
+
if manifest.dataset not in DATASET_REGISTRY:
|
|
312
|
+
valid = ", ".join(sorted(DATASET_REGISTRY))
|
|
313
|
+
raise typer.BadParameter(f"Unknown dataset '{manifest.dataset}'. Choose from: {valid}")
|
|
314
|
+
|
|
315
|
+
store = RunStore(run_dir)
|
|
316
|
+
store.init(manifest, overwrite=overwrite)
|
|
317
|
+
console.print(
|
|
318
|
+
f"[green]Initialized run[/green] [bold]{manifest.run_id}[/bold] at {store.run_dir} "
|
|
319
|
+
f"({len(manifest.perturbations)} perturbations, dataset={manifest.dataset})."
|
|
320
|
+
)
|
|
321
|
+
|
|
322
|
+
|
|
323
|
+
@app.command("run")
|
|
324
|
+
def run_cmd(
|
|
325
|
+
run_dir: Path = typer.Argument(..., help="Run directory containing manifest.json"),
|
|
326
|
+
server_url: str | None = typer.Option(None, "--server-url", help="Override MLX server URL"),
|
|
327
|
+
concurrency: int = typer.Option(DEFAULT_CONCURRENCY, "--concurrency", "-c", min=1),
|
|
328
|
+
retry_errors: bool = typer.Option(False, "--retry-errors", help="Retry previously failed items"),
|
|
329
|
+
limit: int | None = typer.Option(None, "--limit", help="Process at most N pending perturbations"),
|
|
330
|
+
timeout: float = typer.Option(
|
|
331
|
+
DEFAULT_REQUEST_TIMEOUT_S, "--timeout", help="Per-request HTTP timeout in seconds"
|
|
332
|
+
),
|
|
333
|
+
no_report: bool = typer.Option(False, "--no-report", help="Skip regenerating report.html after run"),
|
|
334
|
+
) -> None:
|
|
335
|
+
"""Statelessly run or resume pending perturbations in a run directory and update report.html."""
|
|
336
|
+
store = RunStore(run_dir)
|
|
337
|
+
pre = store.status()
|
|
338
|
+
pending = store.pending_perturbations(retry_errors=retry_errors)
|
|
339
|
+
if limit is not None:
|
|
340
|
+
pending = pending[:limit]
|
|
341
|
+
|
|
342
|
+
if not pending:
|
|
343
|
+
console.print(
|
|
344
|
+
f"[green]Run '{pre.run_id}' already complete[/green] "
|
|
345
|
+
f"({pre.completed}/{pre.total} ok, {pre.failed} failed)."
|
|
346
|
+
)
|
|
347
|
+
if not no_report:
|
|
348
|
+
report_path = generate_report(run_dir)
|
|
349
|
+
console.print(f"[cyan]Report ready:[/cyan] {report_path}")
|
|
350
|
+
return
|
|
351
|
+
|
|
352
|
+
with Progress(
|
|
353
|
+
SpinnerColumn(),
|
|
354
|
+
TextColumn("[bold]{task.description}"),
|
|
355
|
+
BarColumn(),
|
|
356
|
+
MofNCompleteColumn(),
|
|
357
|
+
TimeElapsedColumn(),
|
|
358
|
+
console=console,
|
|
359
|
+
) as progress:
|
|
360
|
+
task_id = progress.add_task(f"Screening {pre.run_id}", total=len(pending))
|
|
361
|
+
|
|
362
|
+
def _on_progress(rec: ScreenResultRecord, done: int, total: int) -> None:
|
|
363
|
+
tag = "[green]OK[/green]" if rec.status == "ok" else "[red]ERR[/red]"
|
|
364
|
+
progress.update(
|
|
365
|
+
task_id,
|
|
366
|
+
completed=done,
|
|
367
|
+
description=f"{tag} {rec.label[:34]} (+{rec.n_up}/−{rec.n_down})",
|
|
368
|
+
)
|
|
369
|
+
|
|
370
|
+
summary = run_fanner_sync(
|
|
371
|
+
run_dir,
|
|
372
|
+
server_url=server_url,
|
|
373
|
+
concurrency=concurrency,
|
|
374
|
+
retry_errors=retry_errors,
|
|
375
|
+
limit=limit,
|
|
376
|
+
timeout_s=timeout,
|
|
377
|
+
on_progress=_on_progress,
|
|
378
|
+
)
|
|
379
|
+
|
|
380
|
+
console.print(
|
|
381
|
+
f"[bold]Run '{summary.run_id}':[/bold] {summary.completed}/{summary.total} completed, "
|
|
382
|
+
f"{summary.failed} failed, {summary.pending} pending."
|
|
383
|
+
)
|
|
384
|
+
if not no_report:
|
|
385
|
+
report_path = generate_report(run_dir)
|
|
386
|
+
console.print(f"[cyan]Interactive HTML report:[/cyan] {report_path}")
|
|
387
|
+
|
|
388
|
+
|
|
389
|
+
@app.command("status")
|
|
390
|
+
def status_cmd(
|
|
391
|
+
run_dir: Path = typer.Argument(..., help="Run directory to inspect"),
|
|
392
|
+
as_json: bool = typer.Option(False, "--json", help="Emit machine-readable JSON"),
|
|
393
|
+
) -> None:
|
|
394
|
+
"""Statelessly inspect a run directory's exact progress from disk."""
|
|
395
|
+
store = RunStore(run_dir)
|
|
396
|
+
summary = store.status()
|
|
397
|
+
if as_json:
|
|
398
|
+
typer.echo(summary.model_dump_json(indent=2))
|
|
399
|
+
return
|
|
400
|
+
|
|
401
|
+
latest = store.load_latest_results()
|
|
402
|
+
console.print(
|
|
403
|
+
Panel.fit(
|
|
404
|
+
f"[bold]Run ID:[/bold] {summary.run_id}\n"
|
|
405
|
+
f"[bold]Dataset:[/bold] {summary.dataset}\n"
|
|
406
|
+
f"[bold]Progress:[/bold] {summary.completed}/{summary.total} ok · "
|
|
407
|
+
f"{summary.failed} failed · {summary.pending} pending\n"
|
|
408
|
+
f"[bold]Report:[/bold] {'report.html present' if summary.report_exists else 'not generated'}",
|
|
409
|
+
title=summary.title,
|
|
410
|
+
border_style="green" if summary.is_complete else "cyan",
|
|
411
|
+
)
|
|
412
|
+
)
|
|
413
|
+
|
|
414
|
+
if latest:
|
|
415
|
+
table = Table(title="Latest Results")
|
|
416
|
+
table.add_column("Label", style="bold")
|
|
417
|
+
table.add_column("Status")
|
|
418
|
+
table.add_column("+DEGs", justify="right", style="red")
|
|
419
|
+
table.add_column("-DEGs", justify="right", style="blue")
|
|
420
|
+
table.add_column("Max |LFC|", justify="right")
|
|
421
|
+
table.add_column("Top Up")
|
|
422
|
+
for rec in sorted(latest.values(), key=lambda r: r.max_abs_lfc, reverse=True):
|
|
423
|
+
st = "[green]ok[/green]" if rec.status == "ok" else "[red]error[/red]"
|
|
424
|
+
top_u = ", ".join(g.gene for g in rec.top_up[:3]) or "—"
|
|
425
|
+
table.add_row(
|
|
426
|
+
rec.label,
|
|
427
|
+
st,
|
|
428
|
+
str(rec.n_up),
|
|
429
|
+
str(rec.n_down),
|
|
430
|
+
f"{rec.max_abs_lfc:.3f}",
|
|
431
|
+
top_u,
|
|
432
|
+
)
|
|
433
|
+
console.print(table)
|
|
434
|
+
|
|
435
|
+
|
|
436
|
+
@app.command("report")
|
|
437
|
+
def report_cmd(
|
|
438
|
+
run_dir: Path = typer.Argument(..., help="Run directory containing manifest.json + results.jsonl"),
|
|
439
|
+
output: Path | None = typer.Option(None, "--output", "-o", help="Custom output HTML path"),
|
|
440
|
+
) -> None:
|
|
441
|
+
"""Regenerate the self-contained interactive HTML report for a run directory."""
|
|
442
|
+
path = generate_report(run_dir, output_path=output)
|
|
443
|
+
console.print(f"[green]Generated interactive report:[/green] {path}")
|
|
444
|
+
|
|
445
|
+
|
|
446
|
+
@app.command("handoff")
|
|
447
|
+
def handoff_cmd(
|
|
448
|
+
run_dir: Path = typer.Argument(..., help="Run directory to summarize for another coding agent"),
|
|
449
|
+
write_file: bool = typer.Option(
|
|
450
|
+
False,
|
|
451
|
+
"--write",
|
|
452
|
+
help="Also write HANDOFF.md inside the run directory",
|
|
453
|
+
),
|
|
454
|
+
) -> None:
|
|
455
|
+
"""Print (and optionally write) a stateless Markdown handoff brief for switching coding agents mid-task."""
|
|
456
|
+
store = RunStore(run_dir)
|
|
457
|
+
md = store.render_handoff_markdown()
|
|
458
|
+
if write_file:
|
|
459
|
+
target = store.run_dir / "HANDOFF.md"
|
|
460
|
+
target.write_text(md, encoding="utf-8")
|
|
461
|
+
console.print(f"[green]Wrote handoff brief:[/green] {target}")
|
|
462
|
+
else:
|
|
463
|
+
typer.echo(md)
|
|
464
|
+
|
|
465
|
+
|
|
466
|
+
@app.command("examples")
|
|
467
|
+
def examples_cmd(
|
|
468
|
+
show: str | None = typer.Option(
|
|
469
|
+
None,
|
|
470
|
+
"--show",
|
|
471
|
+
help="Print the raw JSON of one bundled example (e.g. 'tahoe' or 'k562')",
|
|
472
|
+
),
|
|
473
|
+
) -> None:
|
|
474
|
+
"""List or print bundled example perturbation screens usable with `cellscreen init --example`."""
|
|
475
|
+
if show is not None:
|
|
476
|
+
try:
|
|
477
|
+
path = resolve_example_path(show)
|
|
478
|
+
except KeyError as exc:
|
|
479
|
+
raise typer.BadParameter(str(exc)) from exc
|
|
480
|
+
typer.echo(path.read_text(encoding="utf-8"), nl=False)
|
|
481
|
+
return
|
|
482
|
+
|
|
483
|
+
table = Table(title="Bundled CellScreen Examples")
|
|
484
|
+
table.add_column("Name", style="bold cyan")
|
|
485
|
+
table.add_column("File", style="dim")
|
|
486
|
+
table.add_column("Description")
|
|
487
|
+
for key, (filename, desc) in EXAMPLE_SPECS.items():
|
|
488
|
+
table.add_row(key, filename, desc)
|
|
489
|
+
console.print(table)
|
|
490
|
+
console.print(
|
|
491
|
+
"Initialize directly with: [bold]cellscreen init runs/demo --example tahoe[/bold]"
|
|
492
|
+
)
|
|
493
|
+
|
|
494
|
+
|
|
495
|
+
@app.command("install-skills")
|
|
496
|
+
def install_skills_cmd(
|
|
497
|
+
agent: list[str] | None = typer.Option(
|
|
498
|
+
None,
|
|
499
|
+
"--agent",
|
|
500
|
+
help="Install only for specific agent(s): claude, codex, antigravity (repeatable)",
|
|
501
|
+
),
|
|
502
|
+
force: bool = typer.Option(False, "--force", help="Overwrite existing installed skill directories"),
|
|
503
|
+
dry_run: bool = typer.Option(False, "--dry-run", help="Show what would be installed without writing"),
|
|
504
|
+
) -> None:
|
|
505
|
+
"""Install bundled CellScreen skills for Claude Code, Codex, and Antigravity."""
|
|
506
|
+
results = install_agent_skills(agents=agent, force=force, dry_run=dry_run)
|
|
507
|
+
for res in results:
|
|
508
|
+
if res.action == "installed":
|
|
509
|
+
console.print(f"[green]Installed[/green] {res.agent} skill -> {res.destination}")
|
|
510
|
+
elif res.action == "would_install":
|
|
511
|
+
console.print(f"[cyan]Would install[/cyan] {res.agent} skill -> {res.destination}")
|
|
512
|
+
else:
|
|
513
|
+
console.print(f"[yellow]Skipped[/yellow] {res.agent} ({res.destination}): {res.note}")
|
cellscreen/constants.py
ADDED
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
"""Constants and reference metadata from the google/cellgemma-e4b model card."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
DEFAULT_HF_MODEL_ID = "google/cellgemma-e4b"
|
|
6
|
+
DEFAULT_SERVER_HOST = "127.0.0.1"
|
|
7
|
+
DEFAULT_SERVER_PORT = 8410
|
|
8
|
+
|
|
9
|
+
# Verbatim preamble required by google/cellgemma-e4b.
|
|
10
|
+
# Changing this wording degrades biological prediction quality per the model card.
|
|
11
|
+
CELLGEMMA_PREAMBLE = (
|
|
12
|
+
"Examine how the single-cell sample, captured in 'Source:', responds "
|
|
13
|
+
"transcriptionally to the perturbation under the stated experimental "
|
|
14
|
+
"conditions. You are given the dataset-wide average prediction in 'Mean "
|
|
15
|
+
"Global prediction:' and you need to predict the residual from that mean "
|
|
16
|
+
"to the true final expression."
|
|
17
|
+
)
|
|
18
|
+
|
|
19
|
+
# Gemma 4 turn wrapper tokens (must be tokenized with add_special_tokens=False)
|
|
20
|
+
GEMMA4_BOS_TOKEN = "<bos>"
|
|
21
|
+
GEMMA4_TURN_START = "<|turn>"
|
|
22
|
+
GEMMA4_TURN_END = "<turn|>"
|
|
23
|
+
# Token ids the model card stops on: generate(eos_token_id=[<eos>, <turn|>]).
|
|
24
|
+
# Sent as `stop_token_ids` because vLLM drops special tokens before matching `stop` strings.
|
|
25
|
+
GEMMA4_EOS_TOKEN_ID = 1
|
|
26
|
+
GEMMA4_TURN_END_TOKEN_ID = 106
|
|
27
|
+
|
|
28
|
+
DEFAULT_TEMPERATURE = 0.7
|
|
29
|
+
DEFAULT_MAX_NEW_TOKENS = 8192
|
|
30
|
+
DEFAULT_TOP_K_GENES = 1000
|
|
31
|
+
DEFAULT_CONCURRENCY = 2
|
|
32
|
+
# A full 8,192-token perturbation takes ~7-9 minutes on M4 MLX or L4 vLLM.
|
|
33
|
+
DEFAULT_REQUEST_TIMEOUT_S = 1800.0
|
|
34
|
+
|
|
35
|
+
# All 13 pretrained ExpressionDecoders bundled in google/cellgemma-e4b
|
|
36
|
+
DATASET_REGISTRY: dict[str, dict[str, str]] = {
|
|
37
|
+
# Small-molecule chemical screens
|
|
38
|
+
"tahoe": {
|
|
39
|
+
"modality": "small_molecule",
|
|
40
|
+
"label": "Tahoe-100M",
|
|
41
|
+
"description": "High-throughput single-cell cancer line drug screen across broad doses.",
|
|
42
|
+
},
|
|
43
|
+
"l1000": {
|
|
44
|
+
"modality": "small_molecule",
|
|
45
|
+
"label": "LINCS L1000",
|
|
46
|
+
"description": "High-throughput bulk chemical screen across human cancer cell lines.",
|
|
47
|
+
},
|
|
48
|
+
"emeraldbay": {
|
|
49
|
+
"modality": "small_molecule",
|
|
50
|
+
"label": "EmeraldBay",
|
|
51
|
+
"description": "Single-cell cancer pharmacology screen for targeted drugs and combinations.",
|
|
52
|
+
},
|
|
53
|
+
"sciplex": {
|
|
54
|
+
"modality": "small_molecule",
|
|
55
|
+
"label": "SciPlex 3",
|
|
56
|
+
"description": "Single-cell chemical screen across A549, K562, and MCF7 cell lines.",
|
|
57
|
+
},
|
|
58
|
+
# CRISPR genetic perturbation screens
|
|
59
|
+
"hepg2": {
|
|
60
|
+
"modality": "crispr",
|
|
61
|
+
"label": "Nadig/Replogle HepG2",
|
|
62
|
+
"description": "Genome-scale single-cell CRISPRi knockdown screen in HepG2 cells.",
|
|
63
|
+
},
|
|
64
|
+
"jurkat": {
|
|
65
|
+
"modality": "crispr",
|
|
66
|
+
"label": "Nadig/Replogle Jurkat",
|
|
67
|
+
"description": "Genome-scale single-cell CRISPRi knockdown screen in Jurkat T-cells.",
|
|
68
|
+
},
|
|
69
|
+
"k562": {
|
|
70
|
+
"modality": "crispr",
|
|
71
|
+
"label": "Nadig/Replogle K562",
|
|
72
|
+
"description": "Genome-scale single-cell CRISPRi knockdown screen in K562 cells.",
|
|
73
|
+
},
|
|
74
|
+
"rpe1": {
|
|
75
|
+
"modality": "crispr",
|
|
76
|
+
"label": "Nadig/Replogle RPE1",
|
|
77
|
+
"description": "Genome-scale single-cell CRISPRi knockdown screen in RPE1 cells.",
|
|
78
|
+
},
|
|
79
|
+
"vcc": {
|
|
80
|
+
"modality": "crispr",
|
|
81
|
+
"label": "Virtual Cell Challenge (VCC)",
|
|
82
|
+
"description": "Single-cell CRISPR knockdown screen in human embryonic stem cells.",
|
|
83
|
+
},
|
|
84
|
+
"norman": {
|
|
85
|
+
"modality": "crispr",
|
|
86
|
+
"label": "Norman Combinatorial CRISPRa",
|
|
87
|
+
"description": "Single and pairwise CRISPR activation Perturb-seq screen in K562 cells.",
|
|
88
|
+
},
|
|
89
|
+
# Cytokine & clinical cohorts
|
|
90
|
+
"parse": {
|
|
91
|
+
"modality": "cytokine",
|
|
92
|
+
"label": "Parse 10M PBMC",
|
|
93
|
+
"description": "Combinatorial single-cell PBMC screen across donors and cytokine panels.",
|
|
94
|
+
},
|
|
95
|
+
"dong": {
|
|
96
|
+
"modality": "cytokine",
|
|
97
|
+
"label": "Dong PBMC",
|
|
98
|
+
"description": "Single-cell PBMC subpopulation screen under single/combinatorial cytokines.",
|
|
99
|
+
},
|
|
100
|
+
"tisch": {
|
|
101
|
+
"modality": "clinical",
|
|
102
|
+
"label": "TISCH2 Clinical Cohorts",
|
|
103
|
+
"description": "Patient tumor microenvironment single-cell clinical therapy cohorts.",
|
|
104
|
+
},
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
# Gemma 4 E4B weight path patterns that MUST stay in higher precision (bf16 / unquantized)
|
|
108
|
+
# to prevent Per-Layer Embedding (PLE) quantization collapse on Apple MLX.
|
|
109
|
+
PLE_PROTECTED_PATTERNS: tuple[str, ...] = (
|
|
110
|
+
"embed_tokens",
|
|
111
|
+
"embed_tokens_per_layer",
|
|
112
|
+
"per_layer_model_projection",
|
|
113
|
+
"per_layer_projection",
|
|
114
|
+
"per_layer_input_gate",
|
|
115
|
+
"per_layer_projection_norm",
|
|
116
|
+
"lm_head",
|
|
117
|
+
)
|