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/schemas.py
ADDED
|
@@ -0,0 +1,217 @@
|
|
|
1
|
+
"""Pydantic v2 schemas for CellScreen stateless run manifests, perturbations, and results."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import hashlib
|
|
6
|
+
import json
|
|
7
|
+
from datetime import UTC, datetime
|
|
8
|
+
from typing import Any, Literal
|
|
9
|
+
|
|
10
|
+
from pydantic import BaseModel, Field, model_validator
|
|
11
|
+
|
|
12
|
+
from cellscreen.constants import (
|
|
13
|
+
DEFAULT_HF_MODEL_ID,
|
|
14
|
+
DEFAULT_MAX_NEW_TOKENS,
|
|
15
|
+
DEFAULT_SERVER_HOST,
|
|
16
|
+
DEFAULT_SERVER_PORT,
|
|
17
|
+
DEFAULT_TEMPERATURE,
|
|
18
|
+
)
|
|
19
|
+
|
|
20
|
+
Modality = Literal[
|
|
21
|
+
"small_molecule",
|
|
22
|
+
"crispr",
|
|
23
|
+
"cytokine",
|
|
24
|
+
"clinical",
|
|
25
|
+
"combinatorial",
|
|
26
|
+
"raw",
|
|
27
|
+
]
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class PerturbationComponent(BaseModel):
|
|
31
|
+
"""Single perturbation entry (also used inside combinatorial perturbations)."""
|
|
32
|
+
|
|
33
|
+
modality: Literal["small_molecule", "crispr", "cytokine", "clinical", "raw"]
|
|
34
|
+
# Small molecule fields
|
|
35
|
+
drug_name: str | None = None
|
|
36
|
+
smiles: str | None = None
|
|
37
|
+
concentration: str | None = None
|
|
38
|
+
# Genetic knockdown / cytokine fields
|
|
39
|
+
gene: str | None = None
|
|
40
|
+
kg_sentence: str | None = None
|
|
41
|
+
# Clinical treatment plain-text name
|
|
42
|
+
treatment: str | None = None
|
|
43
|
+
# Raw preformatted perturbation text escape hatch
|
|
44
|
+
raw_text: str | None = None
|
|
45
|
+
|
|
46
|
+
@model_validator(mode="after")
|
|
47
|
+
def _validate_modality_fields(self) -> PerturbationComponent:
|
|
48
|
+
if self.modality == "small_molecule":
|
|
49
|
+
if not (self.drug_name and self.smiles and self.concentration):
|
|
50
|
+
raise ValueError(
|
|
51
|
+
"small_molecule perturbation requires drug_name, smiles, and concentration"
|
|
52
|
+
)
|
|
53
|
+
elif self.modality in ("crispr", "cytokine"):
|
|
54
|
+
if not (self.gene or self.kg_sentence):
|
|
55
|
+
raise ValueError(
|
|
56
|
+
f"{self.modality} perturbation requires gene (or explicit kg_sentence)"
|
|
57
|
+
)
|
|
58
|
+
elif self.modality == "clinical":
|
|
59
|
+
if not self.treatment:
|
|
60
|
+
raise ValueError("clinical perturbation requires treatment")
|
|
61
|
+
elif self.modality == "raw" and not self.raw_text:
|
|
62
|
+
raise ValueError("raw perturbation requires raw_text")
|
|
63
|
+
return self
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
class PerturbationSpec(BaseModel):
|
|
67
|
+
"""One screening condition to evaluate against CellGemma E4B."""
|
|
68
|
+
|
|
69
|
+
item_id: str = ""
|
|
70
|
+
label: str = Field(..., description="Human-readable display name for this screen entry")
|
|
71
|
+
modality: Modality
|
|
72
|
+
# Direct fields for single perturbations
|
|
73
|
+
drug_name: str | None = None
|
|
74
|
+
smiles: str | None = None
|
|
75
|
+
concentration: str | None = None
|
|
76
|
+
gene: str | None = None
|
|
77
|
+
kg_sentence: str | None = None
|
|
78
|
+
treatment: str | None = None
|
|
79
|
+
raw_text: str | None = None
|
|
80
|
+
# For combinatorial perturbations (e.g. dual CRISPR or drug + cytokine)
|
|
81
|
+
components: list[PerturbationComponent] = Field(default_factory=list)
|
|
82
|
+
# Optional override of control cell index for this item
|
|
83
|
+
cell_idx: int | None = None
|
|
84
|
+
# Arbitrary user tags / metadata (e.g. MoA, pathway, plate well)
|
|
85
|
+
metadata: dict[str, Any] = Field(default_factory=dict)
|
|
86
|
+
|
|
87
|
+
@model_validator(mode="after")
|
|
88
|
+
def _validate_and_hash(self) -> PerturbationSpec:
|
|
89
|
+
if self.modality == "combinatorial":
|
|
90
|
+
if len(self.components) < 2:
|
|
91
|
+
raise ValueError("combinatorial perturbation requires at least 2 components")
|
|
92
|
+
else:
|
|
93
|
+
# Validate via PerturbationComponent rules
|
|
94
|
+
PerturbationComponent(
|
|
95
|
+
modality=self.modality,
|
|
96
|
+
drug_name=self.drug_name,
|
|
97
|
+
smiles=self.smiles,
|
|
98
|
+
concentration=self.concentration,
|
|
99
|
+
gene=self.gene,
|
|
100
|
+
kg_sentence=self.kg_sentence,
|
|
101
|
+
treatment=self.treatment,
|
|
102
|
+
raw_text=self.raw_text,
|
|
103
|
+
)
|
|
104
|
+
|
|
105
|
+
if not self.item_id:
|
|
106
|
+
payload = self.model_dump(exclude={"item_id", "metadata"}, exclude_none=True)
|
|
107
|
+
digest = hashlib.sha256(
|
|
108
|
+
json.dumps(payload, sort_keys=True, separators=(",", ":")).encode("utf-8")
|
|
109
|
+
).hexdigest()[:12]
|
|
110
|
+
slug = "".join(c if c.isalnum() else "-" for c in self.label.lower()).strip("-")[:24]
|
|
111
|
+
self.item_id = f"{slug}-{digest}" if slug else f"item-{digest}"
|
|
112
|
+
return self
|
|
113
|
+
|
|
114
|
+
def as_components(self) -> list[PerturbationComponent]:
|
|
115
|
+
if self.modality == "combinatorial":
|
|
116
|
+
return self.components
|
|
117
|
+
return [
|
|
118
|
+
PerturbationComponent(
|
|
119
|
+
modality=self.modality,
|
|
120
|
+
drug_name=self.drug_name,
|
|
121
|
+
smiles=self.smiles,
|
|
122
|
+
concentration=self.concentration,
|
|
123
|
+
gene=self.gene,
|
|
124
|
+
kg_sentence=self.kg_sentence,
|
|
125
|
+
treatment=self.treatment,
|
|
126
|
+
raw_text=self.raw_text,
|
|
127
|
+
)
|
|
128
|
+
]
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
class GenerationConfig(BaseModel):
|
|
132
|
+
"""Sampling parameters matching the CellGemma model card defaults."""
|
|
133
|
+
|
|
134
|
+
temperature: float = Field(default=DEFAULT_TEMPERATURE, ge=0.0, le=2.0)
|
|
135
|
+
max_new_tokens: int = Field(default=DEFAULT_MAX_NEW_TOKENS, ge=16, le=16384)
|
|
136
|
+
top_p: float = Field(default=0.95, gt=0.0, le=1.0)
|
|
137
|
+
top_k: int = Field(default=64, ge=0)
|
|
138
|
+
seed: int | None = None
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
class RunManifest(BaseModel):
|
|
142
|
+
"""Stateless, immutable specification of a CellScreen run stored at manifest.json."""
|
|
143
|
+
|
|
144
|
+
schema_version: str = "1.0"
|
|
145
|
+
run_id: str
|
|
146
|
+
title: str = "CellScreen Perturbation Screen"
|
|
147
|
+
notes: str = ""
|
|
148
|
+
dataset: str = Field(..., description="One of the 13 pretrained CellGemma ExpressionDecoder datasets")
|
|
149
|
+
cell_idx: int = Field(default=0, ge=0, description="Default control cell index in controls_sample.json")
|
|
150
|
+
model_id: str = DEFAULT_HF_MODEL_ID
|
|
151
|
+
server_url: str = f"http://{DEFAULT_SERVER_HOST}:{DEFAULT_SERVER_PORT}"
|
|
152
|
+
generation: GenerationConfig = Field(default_factory=GenerationConfig)
|
|
153
|
+
perturbations: list[PerturbationSpec] = Field(default_factory=list)
|
|
154
|
+
created_at: str = Field(
|
|
155
|
+
default_factory=lambda: datetime.now(UTC).isoformat()
|
|
156
|
+
)
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
class GeneEffect(BaseModel):
|
|
160
|
+
"""One reconstructed differentially expressed gene entry."""
|
|
161
|
+
|
|
162
|
+
gene: str
|
|
163
|
+
direction: Literal["up", "down"]
|
|
164
|
+
rank: int
|
|
165
|
+
control_expr: float
|
|
166
|
+
baseline_expr: float
|
|
167
|
+
predicted_expr: float
|
|
168
|
+
lfc: float
|
|
169
|
+
residual_delta: float
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
class ScreenResultRecord(BaseModel):
|
|
173
|
+
"""One append-only line in results.jsonl."""
|
|
174
|
+
|
|
175
|
+
item_id: str
|
|
176
|
+
label: str
|
|
177
|
+
modality: Modality
|
|
178
|
+
dataset: str
|
|
179
|
+
cell_idx: int
|
|
180
|
+
status: Literal["ok", "error"]
|
|
181
|
+
completed_at: str = Field(
|
|
182
|
+
default_factory=lambda: datetime.now(UTC).isoformat()
|
|
183
|
+
)
|
|
184
|
+
latency_ms: float = 0.0
|
|
185
|
+
prompt_tokens: int = 0
|
|
186
|
+
completion_tokens: int = 0
|
|
187
|
+
perturbation_text: str = ""
|
|
188
|
+
raw_text: str = ""
|
|
189
|
+
up_genes: list[str] = Field(default_factory=list)
|
|
190
|
+
down_genes: list[str] = Field(default_factory=list)
|
|
191
|
+
top_up: list[GeneEffect] = Field(default_factory=list)
|
|
192
|
+
top_down: list[GeneEffect] = Field(default_factory=list)
|
|
193
|
+
n_up: int = 0
|
|
194
|
+
n_down: int = 0
|
|
195
|
+
max_abs_lfc: float = 0.0
|
|
196
|
+
mean_abs_lfc: float = 0.0
|
|
197
|
+
l2_lfc: float = 0.0
|
|
198
|
+
vector_file: str | None = None
|
|
199
|
+
error: str | None = None
|
|
200
|
+
metadata: dict[str, Any] = Field(default_factory=dict)
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
class RunStatusSummary(BaseModel):
|
|
204
|
+
"""Stateless progress snapshot computed purely from manifest.json + results.jsonl."""
|
|
205
|
+
|
|
206
|
+
run_dir: str
|
|
207
|
+
run_id: str
|
|
208
|
+
title: str
|
|
209
|
+
dataset: str
|
|
210
|
+
total: int
|
|
211
|
+
completed: int
|
|
212
|
+
failed: int
|
|
213
|
+
pending: int
|
|
214
|
+
is_complete: bool
|
|
215
|
+
report_exists: bool
|
|
216
|
+
pending_ids: list[str] = Field(default_factory=list)
|
|
217
|
+
failed_ids: list[str] = Field(default_factory=list)
|
cellscreen/server.py
ADDED
|
@@ -0,0 +1,395 @@
|
|
|
1
|
+
"""Thin, stateless Apple MLX inference server for CellGemma E4B.
|
|
2
|
+
|
|
3
|
+
Exposes OpenAI-compatible /v1/completions + /v1/models alongside /health and /metrics.
|
|
4
|
+
Zero session state is held in memory: any coding agent or fanner process can connect,
|
|
5
|
+
disconnect, restart the server, and resume screening runs from disk cleanly.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import asyncio
|
|
11
|
+
import hashlib
|
|
12
|
+
import time
|
|
13
|
+
import uuid
|
|
14
|
+
from concurrent.futures import ThreadPoolExecutor
|
|
15
|
+
from dataclasses import dataclass
|
|
16
|
+
from typing import Any, Protocol
|
|
17
|
+
|
|
18
|
+
import uvicorn
|
|
19
|
+
from fastapi import FastAPI, HTTPException
|
|
20
|
+
from pydantic import BaseModel, Field
|
|
21
|
+
|
|
22
|
+
from cellscreen.constants import (
|
|
23
|
+
DEFAULT_HF_MODEL_ID,
|
|
24
|
+
DEFAULT_MAX_NEW_TOKENS,
|
|
25
|
+
DEFAULT_SERVER_HOST,
|
|
26
|
+
DEFAULT_SERVER_PORT,
|
|
27
|
+
DEFAULT_TEMPERATURE,
|
|
28
|
+
GEMMA4_TURN_END,
|
|
29
|
+
)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class CompletionRequest(BaseModel):
|
|
33
|
+
"""OpenAI-compatible text completion request tailored for CellGemma."""
|
|
34
|
+
|
|
35
|
+
model: str = DEFAULT_HF_MODEL_ID
|
|
36
|
+
prompt: str
|
|
37
|
+
max_tokens: int = Field(default=DEFAULT_MAX_NEW_TOKENS, ge=1, le=16384)
|
|
38
|
+
temperature: float = Field(default=DEFAULT_TEMPERATURE, ge=0.0, le=2.0)
|
|
39
|
+
top_p: float = Field(default=0.95, gt=0.0, le=1.0)
|
|
40
|
+
top_k: int = Field(default=64, ge=0)
|
|
41
|
+
stop: list[str] | str | None = None
|
|
42
|
+
seed: int | None = None
|
|
43
|
+
# CellGemma prompts are pre-wrapped with <bos><|turn>user... so default False avoids duplicate <bos>.
|
|
44
|
+
add_special_tokens: bool = False
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
@dataclass
|
|
48
|
+
class EngineGeneration:
|
|
49
|
+
"""Normalized generation result returned by an InferenceEngine."""
|
|
50
|
+
|
|
51
|
+
text: str
|
|
52
|
+
prompt_tokens: int
|
|
53
|
+
completion_tokens: int
|
|
54
|
+
finish_reason: str
|
|
55
|
+
prompt_tps: float = 0.0
|
|
56
|
+
generation_tps: float = 0.0
|
|
57
|
+
peak_memory_gb: float = 0.0
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
class InferenceEngine(Protocol):
|
|
61
|
+
"""Protocol implemented by both the real MLX engine and the deterministic mock engine."""
|
|
62
|
+
|
|
63
|
+
model_id: str
|
|
64
|
+
backend: str
|
|
65
|
+
|
|
66
|
+
def generate(self, req: CompletionRequest) -> EngineGeneration: ...
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
class MLXCellGemmaEngine:
|
|
70
|
+
"""Apple Silicon MLX inference backend for quantized CellGemma E4B."""
|
|
71
|
+
|
|
72
|
+
backend = "mlx"
|
|
73
|
+
|
|
74
|
+
def __init__(self, model_path: str) -> None:
|
|
75
|
+
# MLX streams are thread-local: the model must be loaded and run on one thread, or
|
|
76
|
+
# generation fails with "There is no Stream(gpu, N) in current thread". All MLX work
|
|
77
|
+
# goes through this single-worker executor (the pattern mlx-lm's own server uses).
|
|
78
|
+
self._mlx_thread = ThreadPoolExecutor(max_workers=1, thread_name_prefix="cellscreen-mlx")
|
|
79
|
+
self.model_id = model_path
|
|
80
|
+
self._mlx_thread.submit(self._load, model_path).result()
|
|
81
|
+
|
|
82
|
+
def _load(self, model_path: str) -> None:
|
|
83
|
+
import mlx.core as mx
|
|
84
|
+
from mlx_lm import load
|
|
85
|
+
|
|
86
|
+
self._mx = mx
|
|
87
|
+
self.model, self.tokenizer = load(model_path)
|
|
88
|
+
|
|
89
|
+
# Resolve Gemma 4 end-of-turn token id (<turn|>) so generation stops right after DEG list
|
|
90
|
+
self._stop_token_ids: set[int] = set()
|
|
91
|
+
raw_tok = getattr(self.tokenizer, "_tokenizer", self.tokenizer)
|
|
92
|
+
eot_id = raw_tok.convert_tokens_to_ids(GEMMA4_TURN_END)
|
|
93
|
+
if isinstance(eot_id, int) and eot_id >= 0:
|
|
94
|
+
self._stop_token_ids.add(eot_id)
|
|
95
|
+
if hasattr(self.tokenizer, "eos_token_ids"):
|
|
96
|
+
self._stop_token_ids.update(self.tokenizer.eos_token_ids)
|
|
97
|
+
elif getattr(raw_tok, "eos_token_id", None) is not None:
|
|
98
|
+
self._stop_token_ids.add(int(raw_tok.eos_token_id))
|
|
99
|
+
|
|
100
|
+
def generate(self, req: CompletionRequest) -> EngineGeneration:
|
|
101
|
+
return self._mlx_thread.submit(self._generate, req).result()
|
|
102
|
+
|
|
103
|
+
def _generate(self, req: CompletionRequest) -> EngineGeneration:
|
|
104
|
+
from mlx_lm import stream_generate
|
|
105
|
+
from mlx_lm.sample_utils import make_sampler
|
|
106
|
+
|
|
107
|
+
if req.seed is not None:
|
|
108
|
+
self._mx.random.seed(req.seed)
|
|
109
|
+
|
|
110
|
+
raw_tok = getattr(self.tokenizer, "_tokenizer", self.tokenizer)
|
|
111
|
+
prompt_ids: list[int] = raw_tok.encode(
|
|
112
|
+
req.prompt,
|
|
113
|
+
add_special_tokens=req.add_special_tokens,
|
|
114
|
+
)
|
|
115
|
+
|
|
116
|
+
stop_strings = self._normalize_stop_strings(req.stop)
|
|
117
|
+
sampler = make_sampler(
|
|
118
|
+
temp=req.temperature,
|
|
119
|
+
top_p=req.top_p,
|
|
120
|
+
top_k=req.top_k,
|
|
121
|
+
)
|
|
122
|
+
|
|
123
|
+
chunks: list[str] = []
|
|
124
|
+
prompt_tokens = len(prompt_ids)
|
|
125
|
+
completion_tokens = 0
|
|
126
|
+
prompt_tps = 0.0
|
|
127
|
+
generation_tps = 0.0
|
|
128
|
+
peak_memory = 0.0
|
|
129
|
+
finish_reason = "length"
|
|
130
|
+
|
|
131
|
+
for resp in stream_generate(
|
|
132
|
+
self.model,
|
|
133
|
+
self.tokenizer,
|
|
134
|
+
prompt=prompt_ids,
|
|
135
|
+
max_tokens=req.max_tokens,
|
|
136
|
+
sampler=sampler,
|
|
137
|
+
):
|
|
138
|
+
prompt_tokens = resp.prompt_tokens
|
|
139
|
+
completion_tokens = resp.generation_tokens
|
|
140
|
+
prompt_tps = resp.prompt_tps
|
|
141
|
+
generation_tps = resp.generation_tps
|
|
142
|
+
peak_memory = resp.peak_memory
|
|
143
|
+
|
|
144
|
+
if resp.token in self._stop_token_ids:
|
|
145
|
+
finish_reason = "stop"
|
|
146
|
+
break
|
|
147
|
+
|
|
148
|
+
chunks.append(resp.text)
|
|
149
|
+
if resp.finish_reason == "stop":
|
|
150
|
+
finish_reason = "stop"
|
|
151
|
+
break
|
|
152
|
+
|
|
153
|
+
if stop_strings:
|
|
154
|
+
joined = "".join(chunks)
|
|
155
|
+
hit = next((s for s in stop_strings if s in joined), None)
|
|
156
|
+
if hit is not None:
|
|
157
|
+
chunks = [joined.split(hit, 1)[0]]
|
|
158
|
+
finish_reason = "stop"
|
|
159
|
+
break
|
|
160
|
+
|
|
161
|
+
text = "".join(chunks).strip()
|
|
162
|
+
return EngineGeneration(
|
|
163
|
+
text=text,
|
|
164
|
+
prompt_tokens=prompt_tokens,
|
|
165
|
+
completion_tokens=completion_tokens,
|
|
166
|
+
finish_reason=finish_reason,
|
|
167
|
+
prompt_tps=prompt_tps,
|
|
168
|
+
generation_tps=generation_tps,
|
|
169
|
+
peak_memory_gb=peak_memory,
|
|
170
|
+
)
|
|
171
|
+
|
|
172
|
+
@staticmethod
|
|
173
|
+
def _normalize_stop_strings(stop: list[str] | str | None) -> list[str]:
|
|
174
|
+
stops = [GEMMA4_TURN_END]
|
|
175
|
+
if isinstance(stop, str):
|
|
176
|
+
stops.append(stop)
|
|
177
|
+
elif isinstance(stop, list):
|
|
178
|
+
stops.extend(s for s in stop if s)
|
|
179
|
+
return stops
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
class MockCellGemmaEngine:
|
|
183
|
+
"""Deterministic lightweight engine for offline smoke tests and CI without 16 GB weights."""
|
|
184
|
+
|
|
185
|
+
backend = "mock"
|
|
186
|
+
|
|
187
|
+
def __init__(self, model_id: str = "mock/cellgemma-e4b") -> None:
|
|
188
|
+
self.model_id = model_id
|
|
189
|
+
|
|
190
|
+
def generate(self, req: CompletionRequest) -> EngineGeneration:
|
|
191
|
+
# Extract candidate genes from the prompt's Source: line so mock DEGs always match the dataset
|
|
192
|
+
source_genes: list[str] = []
|
|
193
|
+
for line in req.prompt.splitlines():
|
|
194
|
+
if line.startswith("Source:"):
|
|
195
|
+
source_genes = [g.strip().upper() for g in line[len("Source:") :].split() if g.strip()]
|
|
196
|
+
break
|
|
197
|
+
if len(source_genes) < 12:
|
|
198
|
+
source_genes = [
|
|
199
|
+
"CDKN1A", "GDF15", "HSPA1A", "DDIT3", "ATF3", "MYC",
|
|
200
|
+
"TP53", "MKI67", "TOP2A", "CDK1", "CCNB1", "BIRC5",
|
|
201
|
+
"FOS", "JUN", "EGR1", "STAT1", "ISG15", "IFIT1",
|
|
202
|
+
]
|
|
203
|
+
|
|
204
|
+
digest = hashlib.sha256(req.prompt.encode("utf-8")).digest()
|
|
205
|
+
n = len(source_genes)
|
|
206
|
+
used: set[str] = set()
|
|
207
|
+
tokens: list[str] = []
|
|
208
|
+
for i in range(min(18, n)):
|
|
209
|
+
idx = (digest[i % len(digest)] + i * 7) % n
|
|
210
|
+
gene = source_genes[idx]
|
|
211
|
+
if gene in used:
|
|
212
|
+
continue
|
|
213
|
+
used.add(gene)
|
|
214
|
+
sign = "+" if (digest[(i + 5) % len(digest)] % 2 == 0) else "-"
|
|
215
|
+
tokens.append(f"{sign}{gene}")
|
|
216
|
+
|
|
217
|
+
text = " ".join(tokens)
|
|
218
|
+
return EngineGeneration(
|
|
219
|
+
text=text,
|
|
220
|
+
prompt_tokens=max(1, len(req.prompt.split())),
|
|
221
|
+
completion_tokens=len(tokens),
|
|
222
|
+
finish_reason="stop",
|
|
223
|
+
prompt_tps=1200.0,
|
|
224
|
+
generation_tps=140.0,
|
|
225
|
+
peak_memory_gb=0.1,
|
|
226
|
+
)
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
class ServerTelemetry:
|
|
230
|
+
"""In-process stateless operational counters for /health and /metrics."""
|
|
231
|
+
|
|
232
|
+
def __init__(self) -> None:
|
|
233
|
+
self.started_at = time.monotonic()
|
|
234
|
+
self.active_requests = 0
|
|
235
|
+
self.requests_total = 0
|
|
236
|
+
self.requests_ok = 0
|
|
237
|
+
self.requests_err = 0
|
|
238
|
+
self.prompt_tokens_total = 0
|
|
239
|
+
self.completion_tokens_total = 0
|
|
240
|
+
self.total_generation_seconds = 0.0
|
|
241
|
+
self.peak_memory_gb = 0.0
|
|
242
|
+
|
|
243
|
+
def snapshot(self, *, model_id: str, backend: str) -> dict[str, Any]:
|
|
244
|
+
uptime = max(0.001, time.monotonic() - self.started_at)
|
|
245
|
+
avg_tps = (
|
|
246
|
+
self.completion_tokens_total / self.total_generation_seconds
|
|
247
|
+
if self.total_generation_seconds > 0
|
|
248
|
+
else 0.0
|
|
249
|
+
)
|
|
250
|
+
return {
|
|
251
|
+
"model": model_id,
|
|
252
|
+
"backend": backend,
|
|
253
|
+
"uptime_s": round(uptime, 2),
|
|
254
|
+
"active_requests": self.active_requests,
|
|
255
|
+
"requests_total": self.requests_total,
|
|
256
|
+
"requests_ok": self.requests_ok,
|
|
257
|
+
"requests_err": self.requests_err,
|
|
258
|
+
"prompt_tokens_total": self.prompt_tokens_total,
|
|
259
|
+
"completion_tokens_total": self.completion_tokens_total,
|
|
260
|
+
"avg_generation_tps": round(avg_tps, 2),
|
|
261
|
+
"peak_memory_gb": round(self.peak_memory_gb, 3),
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
|
|
265
|
+
def create_app(engine: InferenceEngine) -> FastAPI:
|
|
266
|
+
"""Build the stateless FastAPI application around any InferenceEngine."""
|
|
267
|
+
app = FastAPI(
|
|
268
|
+
title="CellScreen MLX Inference Server",
|
|
269
|
+
version="0.1.0",
|
|
270
|
+
description="Stateless local Apple MLX inference server for DeepMind CellGemma E4B.",
|
|
271
|
+
)
|
|
272
|
+
gpu_lock = asyncio.Lock()
|
|
273
|
+
telemetry = ServerTelemetry()
|
|
274
|
+
|
|
275
|
+
@app.get("/health")
|
|
276
|
+
async def health() -> dict[str, Any]:
|
|
277
|
+
metal_available = False
|
|
278
|
+
try:
|
|
279
|
+
import mlx.core as mx
|
|
280
|
+
|
|
281
|
+
metal_available = bool(mx.metal.is_available())
|
|
282
|
+
except Exception: # noqa: BLE001
|
|
283
|
+
metal_available = False
|
|
284
|
+
|
|
285
|
+
return {
|
|
286
|
+
"status": "ok",
|
|
287
|
+
"model": engine.model_id,
|
|
288
|
+
"backend": engine.backend,
|
|
289
|
+
"metal_available": metal_available,
|
|
290
|
+
"active_requests": telemetry.active_requests,
|
|
291
|
+
"uptime_s": round(time.monotonic() - telemetry.started_at, 2),
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
@app.get("/metrics")
|
|
295
|
+
async def metrics() -> dict[str, Any]:
|
|
296
|
+
return telemetry.snapshot(model_id=engine.model_id, backend=engine.backend)
|
|
297
|
+
|
|
298
|
+
@app.get("/v1/models")
|
|
299
|
+
async def list_models() -> dict[str, Any]:
|
|
300
|
+
return {
|
|
301
|
+
"object": "list",
|
|
302
|
+
"data": [
|
|
303
|
+
{
|
|
304
|
+
"id": engine.model_id,
|
|
305
|
+
"object": "model",
|
|
306
|
+
"owned_by": "google-deepmind",
|
|
307
|
+
"backend": engine.backend,
|
|
308
|
+
}
|
|
309
|
+
],
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
@app.post("/v1/completions")
|
|
313
|
+
async def completions(req: CompletionRequest) -> dict[str, Any]:
|
|
314
|
+
telemetry.requests_total += 1
|
|
315
|
+
telemetry.active_requests += 1
|
|
316
|
+
t0 = time.perf_counter()
|
|
317
|
+
try:
|
|
318
|
+
# Serialize Metal GPU execution cleanly so concurrent HTTP clients never contend on Metal buffers
|
|
319
|
+
async with gpu_lock:
|
|
320
|
+
gen = await asyncio.to_thread(engine.generate, req)
|
|
321
|
+
elapsed = time.perf_counter() - t0
|
|
322
|
+
telemetry.requests_ok += 1
|
|
323
|
+
telemetry.prompt_tokens_total += gen.prompt_tokens
|
|
324
|
+
telemetry.completion_tokens_total += gen.completion_tokens
|
|
325
|
+
telemetry.total_generation_seconds += elapsed
|
|
326
|
+
telemetry.peak_memory_gb = max(telemetry.peak_memory_gb, gen.peak_memory_gb)
|
|
327
|
+
|
|
328
|
+
return {
|
|
329
|
+
"id": f"cmpl-{uuid.uuid4().hex[:16]}",
|
|
330
|
+
"object": "text_completion",
|
|
331
|
+
"created": int(time.time()),
|
|
332
|
+
"model": engine.model_id,
|
|
333
|
+
"choices": [
|
|
334
|
+
{
|
|
335
|
+
"index": 0,
|
|
336
|
+
"text": gen.text,
|
|
337
|
+
"logprobs": None,
|
|
338
|
+
"finish_reason": gen.finish_reason,
|
|
339
|
+
}
|
|
340
|
+
],
|
|
341
|
+
"usage": {
|
|
342
|
+
"prompt_tokens": gen.prompt_tokens,
|
|
343
|
+
"completion_tokens": gen.completion_tokens,
|
|
344
|
+
"total_tokens": gen.prompt_tokens + gen.completion_tokens,
|
|
345
|
+
},
|
|
346
|
+
"cellscreen_metrics": {
|
|
347
|
+
"latency_ms": round(elapsed * 1000.0, 2),
|
|
348
|
+
"prompt_tps": round(gen.prompt_tps, 2),
|
|
349
|
+
"generation_tps": round(gen.generation_tps, 2),
|
|
350
|
+
"peak_memory_gb": round(gen.peak_memory_gb, 3),
|
|
351
|
+
},
|
|
352
|
+
}
|
|
353
|
+
except Exception as exc:
|
|
354
|
+
telemetry.requests_err += 1
|
|
355
|
+
raise HTTPException(status_code=500, detail=str(exc)) from exc
|
|
356
|
+
finally:
|
|
357
|
+
telemetry.active_requests -= 1
|
|
358
|
+
|
|
359
|
+
return app
|
|
360
|
+
|
|
361
|
+
|
|
362
|
+
def run_server(
|
|
363
|
+
model_path: str = DEFAULT_HF_MODEL_ID,
|
|
364
|
+
*,
|
|
365
|
+
host: str = DEFAULT_SERVER_HOST,
|
|
366
|
+
port: int = DEFAULT_SERVER_PORT,
|
|
367
|
+
mock: bool = False,
|
|
368
|
+
) -> None:
|
|
369
|
+
"""Launch the local stateless CellScreen MLX server."""
|
|
370
|
+
engine: InferenceEngine = (
|
|
371
|
+
MockCellGemmaEngine(model_id=model_path) if mock else MLXCellGemmaEngine(model_path)
|
|
372
|
+
)
|
|
373
|
+
app = create_app(engine)
|
|
374
|
+
uvicorn.run(app, host=host, port=port, log_level="info")
|
|
375
|
+
|
|
376
|
+
|
|
377
|
+
def main() -> None:
|
|
378
|
+
"""Standalone console entrypoint (`cellscreen-server`)."""
|
|
379
|
+
import argparse
|
|
380
|
+
|
|
381
|
+
parser = argparse.ArgumentParser(description="CellScreen local MLX inference server")
|
|
382
|
+
parser.add_argument(
|
|
383
|
+
"--model",
|
|
384
|
+
default=DEFAULT_HF_MODEL_ID,
|
|
385
|
+
help="Path to PLE-safe MLX model directory or Hugging Face repo id",
|
|
386
|
+
)
|
|
387
|
+
parser.add_argument("--host", default=DEFAULT_SERVER_HOST)
|
|
388
|
+
parser.add_argument("--port", type=int, default=DEFAULT_SERVER_PORT)
|
|
389
|
+
parser.add_argument(
|
|
390
|
+
"--mock",
|
|
391
|
+
action="store_true",
|
|
392
|
+
help="Run deterministic mock engine for testing without downloading weights",
|
|
393
|
+
)
|
|
394
|
+
args = parser.parse_args()
|
|
395
|
+
run_server(args.model, host=args.host, port=args.port, mock=args.mock)
|