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/decoder.py
ADDED
|
@@ -0,0 +1,222 @@
|
|
|
1
|
+
"""Pure-NumPy Stage-2 CellGemma ExpressionDecoder (zero PyTorch dependency).
|
|
2
|
+
|
|
3
|
+
Implements the exact MLP architecture from google/cellgemma-e4b/README.md:
|
|
4
|
+
BatchNorm1d(input_dim + 1) -> [Linear -> ReLU] * len(hidden_dims) -> Linear(h, 1)
|
|
5
|
+
followed by the ELU-like activation scaled by control/baseline expression so that
|
|
6
|
+
predicted_expr = baseline + delta >= 0 everywhere.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
from dataclasses import dataclass
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
from typing import Any
|
|
14
|
+
|
|
15
|
+
import numpy as np
|
|
16
|
+
from safetensors import safe_open
|
|
17
|
+
|
|
18
|
+
from cellscreen.prompts import parse_residual_genes
|
|
19
|
+
from cellscreen.schemas import GeneEffect
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
@dataclass
|
|
23
|
+
class ReconstructionResult:
|
|
24
|
+
"""Continuous Stage-2 expression reconstruction for a single perturbation."""
|
|
25
|
+
|
|
26
|
+
up_genes: list[str]
|
|
27
|
+
down_genes: list[str]
|
|
28
|
+
predicted_expr: np.ndarray
|
|
29
|
+
predicted_lfc: np.ndarray
|
|
30
|
+
residual_vec: np.ndarray
|
|
31
|
+
top_up: list[GeneEffect]
|
|
32
|
+
top_down: list[GeneEffect]
|
|
33
|
+
max_abs_lfc: float
|
|
34
|
+
mean_abs_lfc: float
|
|
35
|
+
l2_lfc: float
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class ExpressionDecoder:
|
|
39
|
+
"""Lightweight dataset-specific MLP mapping ranked (+GENE / -GENE) tokens to continuous LFC."""
|
|
40
|
+
|
|
41
|
+
def __init__(
|
|
42
|
+
self,
|
|
43
|
+
input_dim: int,
|
|
44
|
+
hidden_dims: list[int],
|
|
45
|
+
weights: dict[str, np.ndarray],
|
|
46
|
+
*,
|
|
47
|
+
bn_eps: float = 1e-5,
|
|
48
|
+
max_exp_arg: float = 88.0,
|
|
49
|
+
) -> None:
|
|
50
|
+
self.input_dim = int(input_dim)
|
|
51
|
+
self.hidden_dims = [int(h) for h in hidden_dims]
|
|
52
|
+
self.bn_eps = float(bn_eps)
|
|
53
|
+
self.max_exp_arg = float(max_exp_arg)
|
|
54
|
+
|
|
55
|
+
# BatchNorm1d parameters (either bn0.* or mlp.0.*)
|
|
56
|
+
bn_prefix = "bn0" if "bn0.weight" in weights else "mlp.0"
|
|
57
|
+
self.bn_weight = weights[f"{bn_prefix}.weight"].astype(np.float32)
|
|
58
|
+
self.bn_bias = weights[f"{bn_prefix}.bias"].astype(np.float32)
|
|
59
|
+
self.bn_mean = weights[f"{bn_prefix}.running_mean"].astype(np.float32)
|
|
60
|
+
self.bn_var = weights[f"{bn_prefix}.running_var"].astype(np.float32)
|
|
61
|
+
self._bn_inv_std = (1.0 / np.sqrt(self.bn_var + self.bn_eps)).astype(np.float32)
|
|
62
|
+
|
|
63
|
+
# Linear layers live at indices 1, 3, 5, ..., 2*len(hidden_dims)+1 in nn.Sequential
|
|
64
|
+
self.linear_layers: list[tuple[np.ndarray, np.ndarray]] = []
|
|
65
|
+
n_linear = len(self.hidden_dims) + 1
|
|
66
|
+
for i in range(n_linear):
|
|
67
|
+
seq_idx = 2 * i + 1
|
|
68
|
+
w = weights[f"mlp.{seq_idx}.weight"].astype(np.float32)
|
|
69
|
+
b = weights[f"mlp.{seq_idx}.bias"].astype(np.float32)
|
|
70
|
+
self.linear_layers.append((w, b))
|
|
71
|
+
|
|
72
|
+
@classmethod
|
|
73
|
+
def from_safetensors(
|
|
74
|
+
cls,
|
|
75
|
+
config: dict[str, Any],
|
|
76
|
+
weights_path: str | Path,
|
|
77
|
+
) -> ExpressionDecoder:
|
|
78
|
+
weights: dict[str, np.ndarray] = {}
|
|
79
|
+
with safe_open(str(weights_path), framework="numpy") as f:
|
|
80
|
+
for key in f.keys(): # noqa: SIM118
|
|
81
|
+
weights[key] = f.get_tensor(key)
|
|
82
|
+
return cls(
|
|
83
|
+
input_dim=int(config["input_dim"]),
|
|
84
|
+
hidden_dims=[int(h) for h in config["hidden_dims"]],
|
|
85
|
+
weights=weights,
|
|
86
|
+
)
|
|
87
|
+
|
|
88
|
+
def forward(
|
|
89
|
+
self,
|
|
90
|
+
features: np.ndarray,
|
|
91
|
+
control_expression: np.ndarray,
|
|
92
|
+
) -> np.ndarray:
|
|
93
|
+
"""Compute residual expression delta relative to the mean-shift baseline.
|
|
94
|
+
|
|
95
|
+
Matches DeepMind's reference PyTorch implementation:
|
|
96
|
+
eps = 1e-6
|
|
97
|
+
x = mlp(concat([features, ctrl], dim=1))
|
|
98
|
+
ctrl_safe = ctrl - where(x >= 0, eps, -eps)
|
|
99
|
+
exp_term = clamp(x / ctrl_safe, max=88.0)
|
|
100
|
+
neg_delta = ctrl_safe * (exp(exp_term) - 1.0)
|
|
101
|
+
return where(x > 0, x, neg_delta) + eps
|
|
102
|
+
"""
|
|
103
|
+
feats = np.asarray(features, dtype=np.float32)
|
|
104
|
+
ctrl = np.asarray(control_expression, dtype=np.float32).reshape(-1, 1)
|
|
105
|
+
if feats.ndim != 2 or feats.shape[1] != self.input_dim:
|
|
106
|
+
raise ValueError(
|
|
107
|
+
f"Expected features shape (N, {self.input_dim}), got {feats.shape}"
|
|
108
|
+
)
|
|
109
|
+
if ctrl.shape[0] != feats.shape[0]:
|
|
110
|
+
raise ValueError(
|
|
111
|
+
f"Batch size mismatch: features={feats.shape[0]}, control={ctrl.shape[0]}"
|
|
112
|
+
)
|
|
113
|
+
|
|
114
|
+
x = np.concatenate([feats, ctrl], axis=1)
|
|
115
|
+
# Eval-mode BatchNorm1d
|
|
116
|
+
x = (x - self.bn_mean) * self._bn_inv_std * self.bn_weight + self.bn_bias
|
|
117
|
+
|
|
118
|
+
# Hidden Linear + ReLU layers
|
|
119
|
+
for w, b in self.linear_layers[:-1]:
|
|
120
|
+
x = np.maximum(0.0, x @ w.T + b)
|
|
121
|
+
|
|
122
|
+
# Output Linear layer
|
|
123
|
+
w_out, b_out = self.linear_layers[-1]
|
|
124
|
+
x = x @ w_out.T + b_out
|
|
125
|
+
|
|
126
|
+
eps = np.float32(1e-6)
|
|
127
|
+
ctrl_safe = ctrl - np.where(x >= 0.0, eps, -eps)
|
|
128
|
+
exp_term = np.minimum(x / ctrl_safe, np.float32(self.max_exp_arg))
|
|
129
|
+
neg_delta = ctrl_safe * (np.exp(exp_term) - np.float32(1.0))
|
|
130
|
+
out = np.where(x > 0.0, x, neg_delta) + eps
|
|
131
|
+
return out.reshape(-1).astype(np.float32)
|
|
132
|
+
|
|
133
|
+
def reconstruct(
|
|
134
|
+
self,
|
|
135
|
+
raw_text: str,
|
|
136
|
+
genes: list[str],
|
|
137
|
+
ctrl_expr: np.ndarray,
|
|
138
|
+
baseline: np.ndarray,
|
|
139
|
+
*,
|
|
140
|
+
top_n_summary: int = 25,
|
|
141
|
+
) -> ReconstructionResult:
|
|
142
|
+
"""Map Stage-1 (+GENE / -GENE) text to continuous expression, LFC, and top-gene summaries."""
|
|
143
|
+
gene_to_idx = {g.upper(): i for i, g in enumerate(genes)}
|
|
144
|
+
up, down = parse_residual_genes(raw_text, gene_to_idx)
|
|
145
|
+
|
|
146
|
+
ctrl_arr = np.asarray(ctrl_expr, dtype=np.float32)
|
|
147
|
+
base_arr = np.asarray(baseline, dtype=np.float32)
|
|
148
|
+
residual_vec = np.zeros_like(base_arr, dtype=np.float32)
|
|
149
|
+
|
|
150
|
+
if up or down:
|
|
151
|
+
# 8-dim one-hot task vector for mean_global residual reconstruction (index 7 = 1.0)
|
|
152
|
+
task_oh = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0]
|
|
153
|
+
feats: list[list[float]] = []
|
|
154
|
+
ctrl_vals: list[float] = []
|
|
155
|
+
idxs: list[int] = []
|
|
156
|
+
|
|
157
|
+
n_up = float(len(up))
|
|
158
|
+
n_down = float(len(down))
|
|
159
|
+
for is_up, g_list in ((1.0, up), (0.0, down)):
|
|
160
|
+
for rank, g in enumerate(g_list):
|
|
161
|
+
idx = gene_to_idx[g]
|
|
162
|
+
feats.append([is_up, float(rank), n_up, n_down, *task_oh])
|
|
163
|
+
ctrl_vals.append(float(base_arr[idx]))
|
|
164
|
+
idxs.append(idx)
|
|
165
|
+
|
|
166
|
+
deltas = self.forward(
|
|
167
|
+
np.asarray(feats, dtype=np.float32),
|
|
168
|
+
np.asarray(ctrl_vals, dtype=np.float32),
|
|
169
|
+
)
|
|
170
|
+
residual_vec[idxs] = deltas
|
|
171
|
+
|
|
172
|
+
predicted_expr = np.maximum(0.0, base_arr + residual_vec).astype(np.float32)
|
|
173
|
+
predicted_lfc = (predicted_expr - ctrl_arr).astype(np.float32)
|
|
174
|
+
|
|
175
|
+
# Build ranked GeneEffect tables for report & JSONL summaries
|
|
176
|
+
up_effects = [
|
|
177
|
+
GeneEffect(
|
|
178
|
+
gene=g,
|
|
179
|
+
direction="up",
|
|
180
|
+
rank=rank,
|
|
181
|
+
control_expr=float(ctrl_arr[gene_to_idx[g]]),
|
|
182
|
+
baseline_expr=float(base_arr[gene_to_idx[g]]),
|
|
183
|
+
predicted_expr=float(predicted_expr[gene_to_idx[g]]),
|
|
184
|
+
lfc=float(predicted_lfc[gene_to_idx[g]]),
|
|
185
|
+
residual_delta=float(residual_vec[gene_to_idx[g]]),
|
|
186
|
+
)
|
|
187
|
+
for rank, g in enumerate(up)
|
|
188
|
+
]
|
|
189
|
+
down_effects = [
|
|
190
|
+
GeneEffect(
|
|
191
|
+
gene=g,
|
|
192
|
+
direction="down",
|
|
193
|
+
rank=rank,
|
|
194
|
+
control_expr=float(ctrl_arr[gene_to_idx[g]]),
|
|
195
|
+
baseline_expr=float(base_arr[gene_to_idx[g]]),
|
|
196
|
+
predicted_expr=float(predicted_expr[gene_to_idx[g]]),
|
|
197
|
+
lfc=float(predicted_lfc[gene_to_idx[g]]),
|
|
198
|
+
residual_delta=float(residual_vec[gene_to_idx[g]]),
|
|
199
|
+
)
|
|
200
|
+
for rank, g in enumerate(down)
|
|
201
|
+
]
|
|
202
|
+
|
|
203
|
+
up_effects.sort(key=lambda e: e.lfc, reverse=True)
|
|
204
|
+
down_effects.sort(key=lambda e: e.lfc)
|
|
205
|
+
|
|
206
|
+
abs_lfc = np.abs(predicted_lfc)
|
|
207
|
+
max_abs = float(np.max(abs_lfc)) if abs_lfc.size else 0.0
|
|
208
|
+
mean_abs = float(np.mean(abs_lfc)) if abs_lfc.size else 0.0
|
|
209
|
+
l2_norm = float(np.linalg.norm(predicted_lfc)) if abs_lfc.size else 0.0
|
|
210
|
+
|
|
211
|
+
return ReconstructionResult(
|
|
212
|
+
up_genes=up,
|
|
213
|
+
down_genes=down,
|
|
214
|
+
predicted_expr=predicted_expr,
|
|
215
|
+
predicted_lfc=predicted_lfc,
|
|
216
|
+
residual_vec=residual_vec,
|
|
217
|
+
top_up=up_effects[:top_n_summary],
|
|
218
|
+
top_down=down_effects[:top_n_summary],
|
|
219
|
+
max_abs_lfc=max_abs,
|
|
220
|
+
mean_abs_lfc=mean_abs,
|
|
221
|
+
l2_lfc=l2_norm,
|
|
222
|
+
)
|
cellscreen/fanner.py
ADDED
|
@@ -0,0 +1,366 @@
|
|
|
1
|
+
"""Stateless async perturbation fanner for CellScreen.
|
|
2
|
+
|
|
3
|
+
Reads pending perturbations from a run directory's manifest.json + results.jsonl,
|
|
4
|
+
fans out concurrent requests to the local CellScreen MLX server, reconstructs continuous
|
|
5
|
+
post-perturbation expression & LFC via Stage-2 ExpressionDecoder, and atomically appends
|
|
6
|
+
each result to results.jsonl so any coding agent can pause/resume seamlessly.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import asyncio
|
|
12
|
+
import time
|
|
13
|
+
from collections.abc import Callable
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
|
|
16
|
+
import httpx
|
|
17
|
+
|
|
18
|
+
from cellscreen.assets import CellGemmaAssetManager, ControlCellData
|
|
19
|
+
from cellscreen.constants import (
|
|
20
|
+
DEFAULT_CONCURRENCY,
|
|
21
|
+
DEFAULT_REQUEST_TIMEOUT_S,
|
|
22
|
+
GEMMA4_EOS_TOKEN_ID,
|
|
23
|
+
GEMMA4_TURN_END,
|
|
24
|
+
GEMMA4_TURN_END_TOKEN_ID,
|
|
25
|
+
)
|
|
26
|
+
from cellscreen.decoder import ExpressionDecoder
|
|
27
|
+
from cellscreen.prompts import (
|
|
28
|
+
build_cellgemma_prompt,
|
|
29
|
+
format_perturbation_text,
|
|
30
|
+
wrap_gemma4_turn,
|
|
31
|
+
)
|
|
32
|
+
from cellscreen.schemas import PerturbationSpec, RunManifest, RunStatusSummary, ScreenResultRecord
|
|
33
|
+
from cellscreen.store import RunStore
|
|
34
|
+
|
|
35
|
+
ProgressCallback = Callable[[ScreenResultRecord, int, int], None]
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class AsyncScreenFanner:
|
|
39
|
+
"""Stateless async fan-out runner backed by RunStore + local MLX server + ExpressionDecoder."""
|
|
40
|
+
|
|
41
|
+
def __init__(
|
|
42
|
+
self,
|
|
43
|
+
store: RunStore,
|
|
44
|
+
*,
|
|
45
|
+
assets: CellGemmaAssetManager | None = None,
|
|
46
|
+
decoder: ExpressionDecoder | None = None,
|
|
47
|
+
control_cells: dict[int, ControlCellData] | None = None,
|
|
48
|
+
kg_sentences: dict[str, str] | None = None,
|
|
49
|
+
server_url: str | None = None,
|
|
50
|
+
concurrency: int = DEFAULT_CONCURRENCY,
|
|
51
|
+
timeout_s: float = DEFAULT_REQUEST_TIMEOUT_S,
|
|
52
|
+
max_retries: int = 2,
|
|
53
|
+
http_client: httpx.AsyncClient | None = None,
|
|
54
|
+
) -> None:
|
|
55
|
+
self.store = store
|
|
56
|
+
self._assets = assets
|
|
57
|
+
self._decoder = decoder
|
|
58
|
+
self._control_cells: dict[int, ControlCellData] = dict(control_cells or {})
|
|
59
|
+
self._kg_sentences = kg_sentences
|
|
60
|
+
self.server_url_override = server_url
|
|
61
|
+
self.concurrency = max(1, int(concurrency))
|
|
62
|
+
self.timeout_s = float(timeout_s)
|
|
63
|
+
self.max_retries = max(0, int(max_retries))
|
|
64
|
+
self._external_client = http_client
|
|
65
|
+
|
|
66
|
+
def _get_assets(self, manifest: RunManifest) -> CellGemmaAssetManager:
|
|
67
|
+
if self._assets is None:
|
|
68
|
+
self._assets = CellGemmaAssetManager(model_id=manifest.model_id)
|
|
69
|
+
return self._assets
|
|
70
|
+
|
|
71
|
+
def _get_decoder(self, manifest: RunManifest) -> ExpressionDecoder:
|
|
72
|
+
if self._decoder is None:
|
|
73
|
+
assets = self._get_assets(manifest)
|
|
74
|
+
cfg, weights_path, _ = assets.load_decoder_artifacts(manifest.dataset)
|
|
75
|
+
self._decoder = ExpressionDecoder.from_safetensors(cfg, weights_path)
|
|
76
|
+
return self._decoder
|
|
77
|
+
|
|
78
|
+
def _get_control_cell(self, manifest: RunManifest, cell_idx: int) -> ControlCellData:
|
|
79
|
+
if cell_idx not in self._control_cells:
|
|
80
|
+
assets = self._get_assets(manifest)
|
|
81
|
+
self._control_cells[cell_idx] = assets.load_control_cell(manifest.dataset, cell_idx)
|
|
82
|
+
return self._control_cells[cell_idx]
|
|
83
|
+
|
|
84
|
+
def _needs_kg(self, specs: list[PerturbationSpec]) -> bool:
|
|
85
|
+
for spec in specs:
|
|
86
|
+
for comp in spec.as_components():
|
|
87
|
+
if comp.modality in ("crispr", "cytokine") and not comp.kg_sentence:
|
|
88
|
+
return True
|
|
89
|
+
return False
|
|
90
|
+
|
|
91
|
+
def _get_kg_sentences(
|
|
92
|
+
self, manifest: RunManifest, specs: list[PerturbationSpec]
|
|
93
|
+
) -> dict[str, str] | None:
|
|
94
|
+
if self._kg_sentences is not None:
|
|
95
|
+
return self._kg_sentences
|
|
96
|
+
if self._needs_kg(specs):
|
|
97
|
+
self._kg_sentences = self._get_assets(manifest).load_kg_sentences()
|
|
98
|
+
return self._kg_sentences
|
|
99
|
+
|
|
100
|
+
async def _request_completion(
|
|
101
|
+
self,
|
|
102
|
+
client: httpx.AsyncClient,
|
|
103
|
+
base_url: str,
|
|
104
|
+
manifest: RunManifest,
|
|
105
|
+
wrapped_prompt: str,
|
|
106
|
+
) -> dict:
|
|
107
|
+
payload = {
|
|
108
|
+
"model": manifest.model_id,
|
|
109
|
+
"prompt": wrapped_prompt,
|
|
110
|
+
"max_tokens": manifest.generation.max_new_tokens,
|
|
111
|
+
"temperature": manifest.generation.temperature,
|
|
112
|
+
"top_p": manifest.generation.top_p,
|
|
113
|
+
"top_k": manifest.generation.top_k,
|
|
114
|
+
"stop": [GEMMA4_TURN_END],
|
|
115
|
+
"stop_token_ids": [GEMMA4_EOS_TOKEN_ID, GEMMA4_TURN_END_TOKEN_ID],
|
|
116
|
+
"add_special_tokens": False,
|
|
117
|
+
}
|
|
118
|
+
if manifest.generation.seed is not None:
|
|
119
|
+
payload["seed"] = manifest.generation.seed
|
|
120
|
+
|
|
121
|
+
endpoint = f"{base_url.rstrip('/')}/v1/completions"
|
|
122
|
+
last_exc: Exception | None = None
|
|
123
|
+
|
|
124
|
+
for attempt in range(self.max_retries + 1):
|
|
125
|
+
try:
|
|
126
|
+
resp = await client.post(endpoint, json=payload, timeout=self.timeout_s)
|
|
127
|
+
resp.raise_for_status()
|
|
128
|
+
return resp.json()
|
|
129
|
+
except (httpx.HTTPError, httpx.TimeoutException) as exc:
|
|
130
|
+
last_exc = exc
|
|
131
|
+
if attempt < self.max_retries:
|
|
132
|
+
await asyncio.sleep(min(8.0, 0.75 * (2**attempt)))
|
|
133
|
+
else:
|
|
134
|
+
raise
|
|
135
|
+
|
|
136
|
+
assert last_exc is not None
|
|
137
|
+
raise last_exc
|
|
138
|
+
|
|
139
|
+
async def run(
|
|
140
|
+
self,
|
|
141
|
+
*,
|
|
142
|
+
retry_errors: bool = False,
|
|
143
|
+
limit: int | None = None,
|
|
144
|
+
on_progress: ProgressCallback | None = None,
|
|
145
|
+
) -> RunStatusSummary:
|
|
146
|
+
"""Execute all pending perturbations in the run directory and return final disk status."""
|
|
147
|
+
with self.store.acquire_lock():
|
|
148
|
+
manifest = self.store.load_manifest()
|
|
149
|
+
pending = self.store.pending_perturbations(retry_errors=retry_errors)
|
|
150
|
+
if limit is not None and limit >= 0:
|
|
151
|
+
pending = pending[:limit]
|
|
152
|
+
|
|
153
|
+
if not pending:
|
|
154
|
+
return self.store.status()
|
|
155
|
+
|
|
156
|
+
base_url = self.server_url_override or manifest.server_url
|
|
157
|
+
decoder = self._get_decoder(manifest)
|
|
158
|
+
kg_sentences = self._get_kg_sentences(manifest, pending)
|
|
159
|
+
|
|
160
|
+
# Preload unique control cells used by pending items
|
|
161
|
+
needed_cells = {
|
|
162
|
+
spec.cell_idx if spec.cell_idx is not None else manifest.cell_idx
|
|
163
|
+
for spec in pending
|
|
164
|
+
}
|
|
165
|
+
for cidx in needed_cells:
|
|
166
|
+
self._get_control_cell(manifest, cidx)
|
|
167
|
+
|
|
168
|
+
sem = asyncio.Semaphore(self.concurrency)
|
|
169
|
+
write_lock = asyncio.Lock()
|
|
170
|
+
total_batch = len(pending)
|
|
171
|
+
done_count = 0
|
|
172
|
+
|
|
173
|
+
async def _process_one(
|
|
174
|
+
client: httpx.AsyncClient, spec: PerturbationSpec
|
|
175
|
+
) -> ScreenResultRecord:
|
|
176
|
+
nonlocal done_count
|
|
177
|
+
cidx = spec.cell_idx if spec.cell_idx is not None else manifest.cell_idx
|
|
178
|
+
cell = self._control_cells[cidx]
|
|
179
|
+
t0 = time.perf_counter()
|
|
180
|
+
|
|
181
|
+
async with sem:
|
|
182
|
+
try:
|
|
183
|
+
pert_text = format_perturbation_text(spec, kg_sentences=kg_sentences)
|
|
184
|
+
inner_prompt = build_cellgemma_prompt(
|
|
185
|
+
pert_text,
|
|
186
|
+
cell.genes,
|
|
187
|
+
cell.ctrl_expr,
|
|
188
|
+
cell.baseline,
|
|
189
|
+
)
|
|
190
|
+
wrapped = wrap_gemma4_turn(inner_prompt)
|
|
191
|
+
data = await self._request_completion(client, base_url, manifest, wrapped)
|
|
192
|
+
|
|
193
|
+
raw_text = data["choices"][0]["text"]
|
|
194
|
+
usage = data.get("usage", {})
|
|
195
|
+
prompt_tokens = int(usage.get("prompt_tokens", 0))
|
|
196
|
+
completion_tokens = int(usage.get("completion_tokens", 0))
|
|
197
|
+
|
|
198
|
+
recon = decoder.reconstruct(
|
|
199
|
+
raw_text,
|
|
200
|
+
cell.genes,
|
|
201
|
+
cell.ctrl_expr,
|
|
202
|
+
cell.baseline,
|
|
203
|
+
)
|
|
204
|
+
vector_rel = self.store.save_vectors(
|
|
205
|
+
spec.item_id,
|
|
206
|
+
cell.genes,
|
|
207
|
+
cell.ctrl_expr,
|
|
208
|
+
cell.baseline,
|
|
209
|
+
recon.predicted_expr,
|
|
210
|
+
recon.predicted_lfc,
|
|
211
|
+
)
|
|
212
|
+
elapsed_ms = (time.perf_counter() - t0) * 1000.0
|
|
213
|
+
record = ScreenResultRecord(
|
|
214
|
+
item_id=spec.item_id,
|
|
215
|
+
label=spec.label,
|
|
216
|
+
modality=spec.modality,
|
|
217
|
+
dataset=manifest.dataset,
|
|
218
|
+
cell_idx=cidx,
|
|
219
|
+
status="ok",
|
|
220
|
+
latency_ms=round(elapsed_ms, 2),
|
|
221
|
+
prompt_tokens=prompt_tokens,
|
|
222
|
+
completion_tokens=completion_tokens,
|
|
223
|
+
perturbation_text=pert_text,
|
|
224
|
+
raw_text=raw_text,
|
|
225
|
+
up_genes=recon.up_genes,
|
|
226
|
+
down_genes=recon.down_genes,
|
|
227
|
+
top_up=recon.top_up,
|
|
228
|
+
top_down=recon.top_down,
|
|
229
|
+
n_up=len(recon.up_genes),
|
|
230
|
+
n_down=len(recon.down_genes),
|
|
231
|
+
max_abs_lfc=round(recon.max_abs_lfc, 5),
|
|
232
|
+
mean_abs_lfc=round(recon.mean_abs_lfc, 5),
|
|
233
|
+
l2_lfc=round(recon.l2_lfc, 5),
|
|
234
|
+
vector_file=vector_rel,
|
|
235
|
+
metadata=spec.metadata,
|
|
236
|
+
)
|
|
237
|
+
except Exception as exc: # noqa: BLE001
|
|
238
|
+
elapsed_ms = (time.perf_counter() - t0) * 1000.0
|
|
239
|
+
record = ScreenResultRecord(
|
|
240
|
+
item_id=spec.item_id,
|
|
241
|
+
label=spec.label,
|
|
242
|
+
modality=spec.modality,
|
|
243
|
+
dataset=manifest.dataset,
|
|
244
|
+
cell_idx=cidx,
|
|
245
|
+
status="error",
|
|
246
|
+
latency_ms=round(elapsed_ms, 2),
|
|
247
|
+
error=f"{type(exc).__name__}: {exc}",
|
|
248
|
+
metadata=spec.metadata,
|
|
249
|
+
)
|
|
250
|
+
|
|
251
|
+
async with write_lock:
|
|
252
|
+
self.store.append_result(record)
|
|
253
|
+
done_count += 1
|
|
254
|
+
if on_progress is not None:
|
|
255
|
+
on_progress(record, done_count, total_batch)
|
|
256
|
+
return record
|
|
257
|
+
|
|
258
|
+
if self._external_client is not None:
|
|
259
|
+
await asyncio.gather(*(_process_one(self._external_client, s) for s in pending))
|
|
260
|
+
else:
|
|
261
|
+
async with httpx.AsyncClient() as client:
|
|
262
|
+
await asyncio.gather(*(_process_one(client, s) for s in pending))
|
|
263
|
+
|
|
264
|
+
return self.store.status()
|
|
265
|
+
|
|
266
|
+
|
|
267
|
+
def run_fanner_sync(
|
|
268
|
+
run_dir: str | Path,
|
|
269
|
+
*,
|
|
270
|
+
server_url: str | None = None,
|
|
271
|
+
concurrency: int = DEFAULT_CONCURRENCY,
|
|
272
|
+
retry_errors: bool = False,
|
|
273
|
+
limit: int | None = None,
|
|
274
|
+
timeout_s: float = DEFAULT_REQUEST_TIMEOUT_S,
|
|
275
|
+
max_retries: int = 2,
|
|
276
|
+
on_progress: ProgressCallback | None = None,
|
|
277
|
+
) -> RunStatusSummary:
|
|
278
|
+
"""Synchronous wrapper used by both `cellscreen run` and `cellscreen-fan`."""
|
|
279
|
+
store = RunStore(run_dir)
|
|
280
|
+
fanner = AsyncScreenFanner(
|
|
281
|
+
store,
|
|
282
|
+
server_url=server_url,
|
|
283
|
+
concurrency=concurrency,
|
|
284
|
+
timeout_s=timeout_s,
|
|
285
|
+
max_retries=max_retries,
|
|
286
|
+
)
|
|
287
|
+
return asyncio.run(
|
|
288
|
+
fanner.run(
|
|
289
|
+
retry_errors=retry_errors,
|
|
290
|
+
limit=limit,
|
|
291
|
+
on_progress=on_progress,
|
|
292
|
+
)
|
|
293
|
+
)
|
|
294
|
+
|
|
295
|
+
|
|
296
|
+
def main() -> None:
|
|
297
|
+
"""Standalone console entrypoint (`cellscreen-fan`)."""
|
|
298
|
+
import argparse
|
|
299
|
+
|
|
300
|
+
from rich.console import Console
|
|
301
|
+
from rich.progress import (
|
|
302
|
+
BarColumn,
|
|
303
|
+
MofNCompleteColumn,
|
|
304
|
+
Progress,
|
|
305
|
+
SpinnerColumn,
|
|
306
|
+
TextColumn,
|
|
307
|
+
TimeElapsedColumn,
|
|
308
|
+
)
|
|
309
|
+
|
|
310
|
+
parser = argparse.ArgumentParser(
|
|
311
|
+
description="Stateless async fanner for a CellScreen run directory"
|
|
312
|
+
)
|
|
313
|
+
parser.add_argument("run_dir", help="Path to CellScreen run directory containing manifest.json")
|
|
314
|
+
parser.add_argument("--server-url", default=None, help="Override server URL from manifest.json")
|
|
315
|
+
parser.add_argument("--concurrency", type=int, default=DEFAULT_CONCURRENCY)
|
|
316
|
+
parser.add_argument("--retry-errors", action="store_true")
|
|
317
|
+
parser.add_argument("--limit", type=int, default=None)
|
|
318
|
+
parser.add_argument("--timeout", type=float, default=DEFAULT_REQUEST_TIMEOUT_S)
|
|
319
|
+
args = parser.parse_args()
|
|
320
|
+
|
|
321
|
+
console = Console()
|
|
322
|
+
store = RunStore(args.run_dir)
|
|
323
|
+
pre_status = store.status()
|
|
324
|
+
pending_n = len(store.pending_perturbations(retry_errors=args.retry_errors))
|
|
325
|
+
if args.limit is not None:
|
|
326
|
+
pending_n = min(pending_n, args.limit)
|
|
327
|
+
|
|
328
|
+
if pending_n == 0:
|
|
329
|
+
console.print(
|
|
330
|
+
f"[green]Run '{pre_status.run_id}' already up to date[/green] "
|
|
331
|
+
f"({pre_status.completed}/{pre_status.total} completed, {pre_status.failed} failed)."
|
|
332
|
+
)
|
|
333
|
+
return
|
|
334
|
+
|
|
335
|
+
with Progress(
|
|
336
|
+
SpinnerColumn(),
|
|
337
|
+
TextColumn("[bold]{task.description}"),
|
|
338
|
+
BarColumn(),
|
|
339
|
+
MofNCompleteColumn(),
|
|
340
|
+
TimeElapsedColumn(),
|
|
341
|
+
console=console,
|
|
342
|
+
) as progress:
|
|
343
|
+
task_id = progress.add_task(f"Screening {pre_status.run_id}", total=pending_n)
|
|
344
|
+
|
|
345
|
+
def _on_prog(rec: ScreenResultRecord, done: int, total: int) -> None:
|
|
346
|
+
icon = "[green]OK[/green]" if rec.status == "ok" else "[red]ERR[/red]"
|
|
347
|
+
progress.update(
|
|
348
|
+
task_id,
|
|
349
|
+
completed=done,
|
|
350
|
+
description=f"{icon} {rec.label[:34]} (+{rec.n_up}/-{rec.n_down})",
|
|
351
|
+
)
|
|
352
|
+
|
|
353
|
+
summary = run_fanner_sync(
|
|
354
|
+
args.run_dir,
|
|
355
|
+
server_url=args.server_url,
|
|
356
|
+
concurrency=args.concurrency,
|
|
357
|
+
retry_errors=args.retry_errors,
|
|
358
|
+
limit=args.limit,
|
|
359
|
+
timeout_s=args.timeout,
|
|
360
|
+
on_progress=_on_prog,
|
|
361
|
+
)
|
|
362
|
+
|
|
363
|
+
console.print(
|
|
364
|
+
f"[bold]Done:[/bold] {summary.completed}/{summary.total} ok, "
|
|
365
|
+
f"{summary.failed} failed, {summary.pending} pending."
|
|
366
|
+
)
|