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/prompts.py ADDED
@@ -0,0 +1,142 @@
1
+ """Official CellGemma E4B prompt formatting, Gemma 4 turn wrapping, and DEG output parsing."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Mapping
6
+
7
+ import numpy as np
8
+
9
+ from cellscreen.constants import (
10
+ CELLGEMMA_PREAMBLE,
11
+ DEFAULT_TOP_K_GENES,
12
+ GEMMA4_BOS_TOKEN,
13
+ GEMMA4_TURN_END,
14
+ GEMMA4_TURN_START,
15
+ )
16
+ from cellscreen.schemas import PerturbationComponent, PerturbationSpec
17
+
18
+
19
+ def format_top_genes(values: np.ndarray, genes: list[str], k: int = DEFAULT_TOP_K_GENES) -> str:
20
+ """Format the top-k expressed genes (> 0), highest first, as a space-separated cell sentence."""
21
+ if values.ndim != 1 or len(values) != len(genes):
22
+ raise ValueError(
23
+ f"values length ({len(values)}) must match genes length ({len(genes)})"
24
+ )
25
+ positive_idx = np.flatnonzero(values > 0)
26
+ if positive_idx.size == 0:
27
+ return ""
28
+ order = positive_idx[np.argsort(values[positive_idx])[::-1]]
29
+ return " ".join(genes[int(i)].upper() for i in order[:k])
30
+
31
+
32
+ def format_component_text(
33
+ component: PerturbationComponent,
34
+ kg_sentences: Mapping[str, str] | None = None,
35
+ ) -> str:
36
+ """Format one perturbation component according to the CellGemma model card rules."""
37
+ if component.modality == "small_molecule":
38
+ return (
39
+ f"Drug name: {component.drug_name}\n"
40
+ f"Drug SMILES: {component.smiles}\n"
41
+ f"Concentration: {component.concentration}"
42
+ )
43
+
44
+ if component.modality == "crispr":
45
+ sentence = component.kg_sentence
46
+ if not sentence:
47
+ assert component.gene is not None
48
+ gene_key = component.gene.strip().upper()
49
+ if kg_sentences and gene_key in kg_sentences:
50
+ sentence = kg_sentences[gene_key].strip()
51
+ else:
52
+ raise KeyError(
53
+ f"Knowledge-graph sentence not found for gene '{gene_key}'. "
54
+ "Provide kg_sentences.json or pass explicit kg_sentence."
55
+ )
56
+ return f"Gene knockdown: {sentence.strip()}"
57
+
58
+ if component.modality == "cytokine":
59
+ gene_key = (component.gene or "").strip().upper()
60
+ sentence = component.kg_sentence
61
+ if not sentence:
62
+ if kg_sentences and gene_key in kg_sentences:
63
+ sentence = kg_sentences[gene_key].strip()
64
+ else:
65
+ raise KeyError(
66
+ f"Knowledge-graph sentence not found for cytokine gene '{gene_key}'. "
67
+ "Provide kg_sentences.json or pass explicit kg_sentence."
68
+ )
69
+ if gene_key:
70
+ return f"{gene_key}: {sentence.strip()}"
71
+ return sentence.strip()
72
+
73
+ if component.modality == "clinical":
74
+ assert component.treatment is not None
75
+ return component.treatment.strip()
76
+
77
+ if component.modality == "raw":
78
+ assert component.raw_text is not None
79
+ return component.raw_text.strip()
80
+
81
+ raise ValueError(f"Unsupported modality: {component.modality}")
82
+
83
+
84
+ def format_perturbation_text(
85
+ spec: PerturbationSpec,
86
+ kg_sentences: Mapping[str, str] | None = None,
87
+ ) -> str:
88
+ """Format a single or combinatorial perturbation spec into the exact prompt block."""
89
+ blocks = [format_component_text(comp, kg_sentences=kg_sentences) for comp in spec.as_components()]
90
+ return "\n".join(blocks)
91
+
92
+
93
+ def build_cellgemma_prompt(
94
+ perturbation_text: str,
95
+ genes: list[str],
96
+ ctrl_expr: np.ndarray,
97
+ baseline: np.ndarray,
98
+ top_k: int = DEFAULT_TOP_K_GENES,
99
+ ) -> str:
100
+ """Build the inner CellGemma prompt following exact section order and labels."""
101
+ source_sentence = format_top_genes(ctrl_expr, genes, k=top_k)
102
+ mean_global_sentence = format_top_genes(baseline, genes, k=top_k)
103
+ return (
104
+ f"{CELLGEMMA_PREAMBLE}\n\n"
105
+ f"{perturbation_text.strip()}\n\n"
106
+ f"Source: {source_sentence}\n\n"
107
+ f"Mean Global prediction: {mean_global_sentence}\n"
108
+ "Target: "
109
+ )
110
+
111
+
112
+ def wrap_gemma4_turn(prompt: str) -> str:
113
+ """Wrap an inner prompt in Gemma 4's exact non-thinking turn template.
114
+
115
+ Per the model card, tokenize with add_special_tokens=False so <bos> is not duplicated.
116
+ """
117
+ return f"{GEMMA4_BOS_TOKEN}{GEMMA4_TURN_START}user\n{prompt}{GEMMA4_TURN_END}\n{GEMMA4_TURN_START}model\n"
118
+
119
+
120
+ def parse_residual_genes(
121
+ text: str,
122
+ gene_to_idx: Mapping[str, int],
123
+ ) -> tuple[list[str], list[str]]:
124
+ """Parse CellGemma's ranked +GENE / -GENE tokens, preserving rank order and deduplicating."""
125
+ up: list[str] = []
126
+ down: list[str] = []
127
+ seen_up: set[str] = set()
128
+ seen_down: set[str] = set()
129
+
130
+ for raw_tok in text.split():
131
+ if raw_tok.startswith("+") and len(raw_tok) > 1:
132
+ gene = raw_tok[1:].upper()
133
+ if gene in gene_to_idx and gene not in seen_up:
134
+ up.append(gene)
135
+ seen_up.add(gene)
136
+ elif raw_tok.startswith("-") and len(raw_tok) > 1:
137
+ gene = raw_tok[1:].upper()
138
+ if gene in gene_to_idx and gene not in seen_down:
139
+ down.append(gene)
140
+ seen_down.add(gene)
141
+
142
+ return up, down
cellscreen/quantize.py ADDED
@@ -0,0 +1,118 @@
1
+ """PLE-safe Apple MLX quantization pipeline for DeepMind CellGemma E4B (Gemma 4 E4B).
2
+
3
+ Gemma 4 E4B uses Per-Layer Embeddings (PLE) and per-layer projections whose scaling pathways
4
+ amplify uniform 4-bit quantization noise, causing repetition collapse or degraded DEG ranks.
5
+ This module provides explicit quant_predicate builders that keep PLE and embedding pathways
6
+ in native bfloat16 (default) or 8-bit while safely compressing attention and MLP weights to 4-bit.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import json
12
+ from collections.abc import Callable
13
+ from dataclasses import asdict, dataclass
14
+ from datetime import UTC, datetime
15
+ from pathlib import Path
16
+ from typing import Any, Literal
17
+
18
+ from cellscreen.constants import DEFAULT_HF_MODEL_ID, PLE_PROTECTED_PATTERNS
19
+
20
+ QuantRecipe = Literal["ple_bf16", "ple_q8", "uniform"]
21
+
22
+
23
+ @dataclass(frozen=True)
24
+ class QuantizationSpec:
25
+ """Declarative specification for converting CellGemma E4B to MLX."""
26
+
27
+ hf_path: str = DEFAULT_HF_MODEL_ID
28
+ output_dir: str = "models/cellgemma-e4b-mlx-4bit-ple"
29
+ bits: int = 4
30
+ group_size: int = 64
31
+ mode: str = "affine"
32
+ recipe: QuantRecipe = "ple_bf16"
33
+ dtype: str = "bfloat16"
34
+ ple_bits: int = 8
35
+
36
+
37
+ def is_ple_protected_path(path: str) -> bool:
38
+ """Return True if a module path belongs to Gemma 4 PLE or token embedding pathways."""
39
+ lowered = path.lower()
40
+ return any(pattern in lowered for pattern in PLE_PROTECTED_PATTERNS)
41
+
42
+
43
+ def build_ple_quant_predicate(
44
+ recipe: QuantRecipe = "ple_bf16",
45
+ *,
46
+ group_size: int = 64,
47
+ mode: str = "affine",
48
+ ple_bits: int = 8,
49
+ ) -> Callable[[str, Any], bool | dict[str, Any]]:
50
+ """Build an mlx-lm quant_predicate(path, module) protecting Gemma 4 PLE pathways."""
51
+
52
+ def _predicate(path: str, module: Any) -> bool | dict[str, Any]:
53
+ # Guard against modules without quantizable weight dimensions
54
+ weight = getattr(module, "weight", None)
55
+ if weight is not None and hasattr(weight, "shape") and weight.shape[-1] % group_size != 0:
56
+ return False
57
+
58
+ if recipe == "uniform":
59
+ return True
60
+
61
+ if is_ple_protected_path(path):
62
+ if recipe == "ple_bf16":
63
+ return False
64
+ if recipe == "ple_q8":
65
+ return {"bits": ple_bits, "group_size": group_size, "mode": mode}
66
+
67
+ return True
68
+
69
+ return _predicate
70
+
71
+
72
+ def quantize_cellgemma(spec: QuantizationSpec, *, force: bool = False) -> Path:
73
+ """Download and convert google/cellgemma-e4b into a PLE-safe MLX checkpoint directory."""
74
+ import shutil
75
+
76
+ import mlx.core as mx
77
+ from mlx_lm import convert
78
+
79
+ out_path = Path(spec.output_dir).expanduser().resolve()
80
+ if out_path.exists():
81
+ if not force:
82
+ raise FileExistsError(
83
+ f"Output directory already exists: {out_path}. Pass force=True to replace it."
84
+ )
85
+ shutil.rmtree(out_path)
86
+
87
+ out_path.parent.mkdir(parents=True, exist_ok=True)
88
+ predicate = build_ple_quant_predicate(
89
+ recipe=spec.recipe,
90
+ group_size=spec.group_size,
91
+ mode=spec.mode,
92
+ ple_bits=spec.ple_bits,
93
+ )
94
+
95
+ # Convert on the CPU. Quantization doesn't need the GPU, and GPU command buffers that
96
+ # wait on weights streaming from external/network volumes (or swapped pages) trip the
97
+ # macOS GPU watchdog: kIOGPUCommandBufferCallbackErrorTimeout (ml-explore/mlx#3803).
98
+ with mx.stream(mx.cpu):
99
+ convert(
100
+ hf_path=spec.hf_path,
101
+ mlx_path=str(out_path),
102
+ quantize=True,
103
+ q_group_size=spec.group_size,
104
+ q_bits=spec.bits,
105
+ q_mode=spec.mode,
106
+ dtype=spec.dtype,
107
+ quant_predicate=predicate,
108
+ )
109
+
110
+ meta = {
111
+ **asdict(spec),
112
+ "output_dir": str(out_path),
113
+ "protected_patterns": list(PLE_PROTECTED_PATTERNS),
114
+ "converted_at": datetime.now(UTC).isoformat(),
115
+ }
116
+ meta_path = out_path / "cellscreen_quant_meta.json"
117
+ meta_path.write_text(json.dumps(meta, indent=2) + "\n", encoding="utf-8")
118
+ return out_path