Spaces:
Running on Zero

BoHuangLab commited on
Commit
a46a831
·
verified ·
1 Parent(s): 0f4badf

Import the CondenSeq app modules from cell_fm.apps.condenseq; add vit_cls

Browse files
app.py CHANGED
@@ -15,8 +15,7 @@ import matplotlib.pyplot as plt
15
  import numpy as np
16
  import pandas as pd
17
 
18
- import metrics
19
- import pipeline
20
 
21
  # gradio_client walks component API schemas to build /gradio_api/info. JSON Schema
22
  # allows `additionalProperties: true`, but the walker recurses into that bool as if
 
15
  import numpy as np
16
  import pandas as pd
17
 
18
+ from cell_fm.apps.condenseq import metrics, pipeline
 
19
 
20
  # gradio_client walks component API schemas to build /gradio_api/info. JSON Schema
21
  # allows `additionalProperties: true`, but the walker recurses into that bool as if
assets/anchor_cell.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8eca991a3e33c3009340143b77962515af449f99bf82ffb615882eb5c1fa4612
3
+ size 786560
assets/anchor_masks.npz ADDED
Binary file (2.73 kB). View file
 
cell_fm/apps/__init__.py ADDED
File without changes
cell_fm/apps/condenseq/__init__.py ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ """The CondenSeq titration app: sequence -> condensate probability curve, AUC and AAC.
2
+
3
+ These two modules used to live only in the (gitignored) huggingface_space/ working copy,
4
+ which meant the demo's logic existed solely inside a deployment artefact and was not on
5
+ GitHub at all. The Colab notebooks now fetch model code from the repo, so anything they
6
+ import has to be tracked -- hence this package. The Space imports the same modules from
7
+ here rather than keeping its own copy.
8
+ """
9
+
10
+ from . import metrics, pipeline # noqa: F401
cell_fm/apps/condenseq/metrics.py ADDED
@@ -0,0 +1,135 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Curve metrics for the condensate titration analysis.
2
+
3
+ Port of cell_diff/tasks/analysis/utils.py from CELL-Diff2-Dev, restricted to the
4
+ three quantities this demo reports:
5
+
6
+ AUC area under the moving-averaged condensate-probability curve
7
+ NR the same curve with everything past its maximum held flat ("no reentrant")
8
+ AAC NR - AUC, i.e. the area *above* the curve that reentrant dissolution opens up
9
+
10
+ All three integrate against log10(intensity) by default and are normalised by the
11
+ width of the integration domain, so they live in [0, 1] and are comparable across
12
+ sequences.
13
+ """
14
+
15
+ import numpy as np
16
+ import pandas as pd
17
+
18
+
19
+ def moving_average(y, window: int) -> np.ndarray:
20
+ """Centred rolling mean, shrinking the window at the edges rather than padding."""
21
+ y = np.asarray(y, dtype=float)
22
+ window = int(max(1, min(window, len(y))))
23
+ return (
24
+ pd.Series(y)
25
+ .rolling(window=window, center=True, min_periods=1)
26
+ .mean()
27
+ .to_numpy()
28
+ )
29
+
30
+
31
+ def integral(xs: np.ndarray, ys: np.ndarray) -> float:
32
+ xs = np.asarray(xs, dtype=float)
33
+ ys = np.asarray(ys, dtype=float)
34
+
35
+ if xs.ndim != 1 or ys.ndim != 1:
36
+ raise ValueError("xs and ys must be 1D arrays")
37
+ if xs.shape[0] != ys.shape[0]:
38
+ raise ValueError("xs and ys must have the same length")
39
+ if xs.shape[0] < 2:
40
+ return 0.0
41
+
42
+ return float(np.trapz(ys, xs))
43
+
44
+
45
+ def _prepare(df: pd.DataFrame, window_size: int, use_log_scale: bool):
46
+ """Return (x, curve) sorted by x, with x log10-scaled when requested.
47
+
48
+ Sorting happens once, before the moving average is taken, so the smoothing
49
+ always runs along increasing intensity.
50
+ """
51
+ intensity_levels = df["protein_intensity_level"].to_numpy(dtype=float)
52
+ predicted_classes = df["predicted_class"].to_numpy(dtype=float)
53
+
54
+ order = np.argsort(intensity_levels)
55
+ intensity_levels = intensity_levels[order]
56
+ predicted_classes = predicted_classes[order]
57
+
58
+ curve = moving_average(predicted_classes, window_size)
59
+
60
+ if use_log_scale:
61
+ # clip at 1.0 so that intensities below 1 do not send log10 negative/-inf
62
+ x = np.log10(np.clip(intensity_levels, a_min=1.0, a_max=None))
63
+ else:
64
+ x = intensity_levels
65
+
66
+ return x, curve
67
+
68
+
69
+ def _normalise(area: float, x: np.ndarray, normalize: bool) -> float:
70
+ if not normalize:
71
+ return area
72
+ total_area = (x[-1] - x[0]) * 1.0
73
+ return area / total_area
74
+
75
+
76
+ def compute_area_under_curve(
77
+ df: pd.DataFrame, window_size: int, normalize: bool = True, use_log_scale: bool = True
78
+ ) -> float:
79
+ """AUC: how much of the intensity range this sequence spends in the condensed state."""
80
+ x, curve = _prepare(df, window_size, use_log_scale)
81
+ return _normalise(integral(x, curve), x, normalize)
82
+
83
+
84
+ def no_reentrant_curve(curve: np.ndarray) -> np.ndarray:
85
+ """The curve it would have been without reentrant dissolution.
86
+
87
+ Everything past the maximum is held at the maximum, so the difference against
88
+ the real curve is exactly the dissolution that happens at high concentration.
89
+ """
90
+ max_index = int(np.argmax(curve))
91
+ out = curve.copy()
92
+ out[max_index:] = float(np.max(curve))
93
+ return out
94
+
95
+
96
+ def compute_area_if_no_reentrant(
97
+ df: pd.DataFrame, window_size: int, normalize: bool = True, use_log_scale: bool = True
98
+ ) -> float:
99
+ """Area under the curve after flattening everything past its maximum."""
100
+ x, curve = _prepare(df, window_size, use_log_scale)
101
+ return _normalise(integral(x, no_reentrant_curve(curve)), x, normalize)
102
+
103
+
104
+ def compute_area_if_no_reentrant_minus_auc(
105
+ df: pd.DataFrame, window_size: int, normalize: bool = True, use_log_scale: bool = True
106
+ ) -> float:
107
+ """AAC, the area *above* the curve: no-reentrant area minus the real area.
108
+
109
+ Zero when the curve never comes back down; larger the more the sequence
110
+ dissolves again at high concentration.
111
+ """
112
+ x, curve = _prepare(df, window_size, use_log_scale)
113
+ return _normalise(integral(x, no_reentrant_curve(curve) - curve), x, normalize)
114
+
115
+
116
+ # the paper's name for compute_area_if_no_reentrant_minus_auc
117
+ compute_area_above_curve = compute_area_if_no_reentrant_minus_auc
118
+
119
+
120
+ def compute_concentration(
121
+ df: pd.DataFrame, window_size: int, threshold_prob: float = 0.8
122
+ ) -> float:
123
+ """c_sat: the first intensity at which the smoothed curve reaches threshold_prob.
124
+
125
+ inf when the sequence never condenses over the scanned range.
126
+ """
127
+ intensity_levels = df["protein_intensity_level"].to_numpy(dtype=float)
128
+ predicted_classes = df["predicted_class"].to_numpy(dtype=float)
129
+
130
+ order = np.argsort(intensity_levels)
131
+ intensity_levels = intensity_levels[order]
132
+ curve = moving_average(predicted_classes[order], window_size)
133
+
134
+ hits = np.flatnonzero(curve >= threshold_prob)
135
+ return float(intensity_levels[hits[0]]) if hits.size else float("inf")
cell_fm/apps/condenseq/pipeline.py ADDED
@@ -0,0 +1,337 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """CELL-FM CondenSeq: sequence -> condensate titration curve.
2
+
3
+ The demo runs the same three stages as the offline analysis, in memory:
4
+
5
+ 1. generate CELL-FM CS samples one image per protein-intensity level, over a
6
+ log-spaced concentration ladder (evaluate_seq2img_dict.py)
7
+ 2. classify a ViT labels each image condensed / diffuse (evaluate_single_img.py)
8
+ 3. summarise a centred moving average over the binary calls gives the condensate
9
+ probability curve (ma_plot.py), and AUC / AAC integrate it
10
+ (analysis/ana_all_mutation_log_scale.py)
11
+
12
+ Weights come from a HF model repo by default; set CELLFM_LOCAL_WEIGHTS to a
13
+ directory holding the three .bin files to run against a local copy instead.
14
+ """
15
+
16
+ import os
17
+ from dataclasses import dataclass, field
18
+ from functools import lru_cache
19
+
20
+ import numpy as np
21
+ import pandas as pd
22
+ import torch
23
+
24
+ from cell_fm.criterions.cell_fm.unidiffuser import UniDiffCriterions
25
+ from cell_fm.models.cell_fm.cell_fm_cs_config import CELLFMConfig
26
+ from cell_fm.models.cell_fm.cell_fm_cs_model import CELLFMCSModel
27
+ from cell_fm.models.vit_cls_condenseq_img.config import ViTConfig
28
+ from cell_fm.models.vit_cls_condenseq_img.model import ViTModel
29
+
30
+ from . import metrics
31
+
32
+ MODEL_REPO = os.environ.get("CELLFM_MODEL_REPO", "BoHuangLab/CELL-FM")
33
+ LOCAL_WEIGHTS = os.environ.get("CELLFM_LOCAL_WEIGHTS", "")
34
+
35
+ # The weight repo holds one subfolder per model family, so paths are prefixed.
36
+ # CELLFM_LOCAL_WEIGHTS points at a flat directory, hence the basename() below.
37
+ GENERATOR_WEIGHTS = "condenseq/cellfm_seq2img.bin"
38
+ VAE_WEIGHTS = "condenseq/vae.bin"
39
+ CLASSIFIER_WEIGHTS = "condenseq/vit_cls.bin"
40
+ REFERENCE_NUCLEUS = "condenseq/reference_nucleus.npy"
41
+
42
+ # The concentration ladder. The offline runs scanned 4096 levels; the demo scans
43
+ # fewer for latency, and the moving-average window scales with it (see WINDOW_DIVISOR).
44
+ MIN_INTENSITY = 20.0
45
+ MAX_INTENSITY = 2048.0
46
+ WINDOW_DIVISOR = 8 # window = num_images // 8, matching ana_all_mutation_log_scale.py
47
+
48
+ VALID_AA = set("ACDEFGHIKLMNPQRSTVWY")
49
+
50
+ # CondenSeq is a fixed-length library: all 14,578 training sequences are exactly
51
+ # 66 residues. Anything else is off-distribution, so the demo requires this length
52
+ # rather than silently padding or cropping.
53
+ SEQUENCE_LENGTH = 66
54
+
55
+ # Generation starts from a random latent, so the curve moves a little between runs.
56
+ # The offline scripts fixed this at 6; keeping the same default makes the demo's
57
+ # numbers repeatable and comparable to them.
58
+ DEFAULT_SEED = 6
59
+
60
+ # Fixed sampling settings. The concentration ladder length and ODE step count match
61
+ # the offline runs, so demo numbers stay comparable to the published ones.
62
+ NUM_IMAGES = 512
63
+ NUM_STEPS = 100
64
+ BATCH_SIZE = 64
65
+
66
+
67
+ def resolve_weights(filename: str) -> str:
68
+ """Local directory if CELLFM_LOCAL_WEIGHTS is set, else pull from the model repo."""
69
+ if LOCAL_WEIGHTS:
70
+ path = os.path.join(LOCAL_WEIGHTS, os.path.basename(filename))
71
+ if not os.path.exists(path):
72
+ raise FileNotFoundError(f"{path} not found (CELLFM_LOCAL_WEIGHTS={LOCAL_WEIGHTS})")
73
+ return path
74
+
75
+ from huggingface_hub import hf_hub_download
76
+
77
+ return hf_hub_download(repo_id=MODEL_REPO, filename=filename)
78
+
79
+
80
+ def generator_config() -> CELLFMConfig:
81
+ """Hyperparameters from scripts/cell_fm_cs/evaluate_seq2img.sh."""
82
+ return CELLFMConfig(
83
+ img_resize=160,
84
+ img_crop_size=160,
85
+ img_type="GFP",
86
+ cell_image="nucl",
87
+ seq_zero_mask_ratio=0.0,
88
+ path_type="Linear",
89
+ prediction="velocity",
90
+ # VAE
91
+ num_down_blocks=3,
92
+ latent_channels=4,
93
+ vae_block_out_channels="128,256,512",
94
+ # CELL-FM
95
+ img_mask_ratio=0,
96
+ cond_out_channels="32,64",
97
+ sample_size=40,
98
+ esm_embedding="esmc_600m",
99
+ encoder_hidden_size=1152,
100
+ max_protein_sequence_len=2048,
101
+ encoder_num_hidden_layers=4,
102
+ num_heads=8,
103
+ dim_head=64,
104
+ dropout=0,
105
+ final_dropout=0,
106
+ encoder_patch_size=4,
107
+ # image generator
108
+ img_generator_num_layers=4,
109
+ img_generator_patch_size=2,
110
+ attention_head_dim=64,
111
+ num_attention_heads=8,
112
+ # image decoder
113
+ img_decoder_num_hidden_layers=2,
114
+ img_decoder_hidden_size=512,
115
+ img_decoder_num_heads=8,
116
+ img_decoder_dim_head=64,
117
+ cell_image_ratio=0.5,
118
+ # checkpoints
119
+ vae_loadcheck_path=resolve_weights(VAE_WEIGHTS),
120
+ loadcheck_path=resolve_weights(GENERATOR_WEIGHTS),
121
+ infer=True,
122
+ )
123
+
124
+
125
+ def classifier_config() -> ViTConfig:
126
+ """Hyperparameters from scripts/vit_cls_condenseq_img/pretrain.sh."""
127
+ return ViTConfig(
128
+ image_size=160,
129
+ in_channels=2,
130
+ patch_size=4,
131
+ num_layers=8,
132
+ num_heads=8,
133
+ hidden_dim=512,
134
+ mlp_dim=2048,
135
+ num_classes=2,
136
+ loadcheck_path=resolve_weights(CLASSIFIER_WEIGHTS),
137
+ infer=True,
138
+ )
139
+
140
+
141
+ def get_device() -> torch.device:
142
+ return torch.device("cuda" if torch.cuda.is_available() else "cpu")
143
+
144
+
145
+ @lru_cache(maxsize=1)
146
+ def load_models():
147
+ """Download the weights and build both models, on CPU.
148
+
149
+ Kept off the GPU deliberately: under ZeroGPU a CUDA device only exists inside a
150
+ @spaces.GPU call, and the 2.1 GB download plus model construction would eat that
151
+ budget. Call this once at startup, then models_on(device) inside the GPU call.
152
+ """
153
+ generator = CELLFMCSModel(config=generator_config(), loss_fn=UniDiffCriterions)
154
+ generator.eval()
155
+
156
+ classifier = ViTModel(config=classifier_config())
157
+ classifier.eval()
158
+
159
+ from esm.tokenization.sequence_tokenizer import EsmSequenceTokenizer
160
+
161
+ return generator, classifier, EsmSequenceTokenizer()
162
+
163
+
164
+ def models_on(device):
165
+ """Move the cached models to device. A no-op once they are already there."""
166
+ generator, classifier, vocab = load_models()
167
+ return generator.to(device), classifier.to(device), vocab
168
+
169
+
170
+ @lru_cache(maxsize=1)
171
+ def reference_nucleus() -> torch.Tensor:
172
+ """The DAPI channel every generated image is conditioned on, as (1, 1, 160, 160) in [-1, 1].
173
+
174
+ Taken from CondenSeq protein index 12626, image 0 -- the same one the offline
175
+ seq2img runs used, so demo curves are comparable to the published ones.
176
+ """
177
+ arr = np.load(resolve_weights(REFERENCE_NUCLEUS))
178
+ return torch.from_numpy(arr).float().unsqueeze(0)
179
+
180
+
181
+ def intensity_ladder(num_images: int) -> torch.Tensor:
182
+ """Log-spaced protein intensity levels, the x axis of the titration curve."""
183
+ return torch.logspace(
184
+ start=float(np.log10(MIN_INTENSITY)),
185
+ end=float(np.log10(MAX_INTENSITY)),
186
+ steps=num_images,
187
+ )
188
+
189
+
190
+ def clean_sequence(sequence: str) -> str:
191
+ """Strip FASTA headers, whitespace and case; reject anything not a standard residue."""
192
+ lines = [ln for ln in str(sequence).splitlines() if not ln.startswith(">")]
193
+ seq = "".join(lines).strip().upper()
194
+ seq = "".join(seq.split())
195
+
196
+ if not seq:
197
+ raise ValueError("Enter a protein sequence.")
198
+ bad = sorted(set(seq) - VALID_AA)
199
+ if bad:
200
+ raise ValueError(
201
+ f"Sequence contains non-standard residues: {', '.join(bad)}. "
202
+ "Use the 20 standard amino acids."
203
+ )
204
+ if len(seq) != SEQUENCE_LENGTH:
205
+ raise ValueError(
206
+ f"Sequence is {len(seq)} residues; CELL-FM CondenSeq takes exactly "
207
+ f"{SEQUENCE_LENGTH}. The whole training library is {SEQUENCE_LENGTH}-mers, "
208
+ "so other lengths are outside what the model has seen."
209
+ )
210
+ return seq
211
+
212
+
213
+ @dataclass
214
+ class Result:
215
+ sequence: str
216
+ intensities: np.ndarray # (N,) protein intensity levels
217
+ predictions: np.ndarray # (N,) 0 = diffuse, 1 = condensed
218
+ curve: np.ndarray # (N,) moving-averaged condensate probability
219
+ window: int
220
+ auc: float # area under the curve
221
+ aac: float # area above the curve (reentrant dissolution)
222
+ no_reentrant_auc: float
223
+ c_sat: float
224
+ images: np.ndarray = field(repr=False, default=None) # (K, 160, 160) sample panel
225
+ image_intensities: np.ndarray = field(repr=False, default=None)
226
+
227
+
228
+ @torch.no_grad()
229
+ def generate_images(sequence, num_images, num_steps, batch_size, seed=DEFAULT_SEED, progress=None):
230
+ """Stage 1: one generated image per intensity level, returned as uint16 (N, 2, 160, 160).
231
+
232
+ uint16 is not incidental -- the offline pipeline wrote a TIFF between generation
233
+ and classification, so the classifier saw quantised pixels. Keeping the same
234
+ round-trip here keeps demo numbers comparable to the published ones.
235
+ """
236
+ device = get_device()
237
+ generator, _, vocab = models_on(device)
238
+
239
+ from esm.utils import encoding
240
+
241
+ if seed is not None:
242
+ torch.manual_seed(int(seed))
243
+ if torch.cuda.is_available():
244
+ torch.cuda.manual_seed_all(int(seed))
245
+
246
+ tokens = encoding.tokenize_sequence(sequence, vocab, True).unsqueeze(0).to(device)
247
+ nucleus = reference_nucleus().to(device)
248
+ levels = intensity_ladder(num_images).to(device)
249
+
250
+ out = []
251
+ for start in range(0, num_images, batch_size):
252
+ end = min(start + batch_size, num_images)
253
+ n = end - start
254
+
255
+ if progress is not None:
256
+ progress(start / num_images, desc=f"Generating images {start}-{end} of {num_images}")
257
+
258
+ sample = generator.sequence_to_image(
259
+ tokens.repeat(n, 1),
260
+ nucleus.repeat(n, 1, 1, 1),
261
+ levels[start:end].unsqueeze(1),
262
+ num_steps=num_steps,
263
+ )
264
+
265
+ # channel 0 = nucleus (conditioning), channel 1 = generated protein
266
+ combined = torch.cat([nucleus.repeat(n, 1, 1, 1), sample], dim=1)
267
+ combined = ((combined + 1) / 2.0).clamp(0.0, 1.0)
268
+ out.append((combined * 65535).cpu().numpy().astype(np.uint16))
269
+
270
+ return np.concatenate(out, axis=0)
271
+
272
+
273
+ @torch.no_grad()
274
+ def classify_images(images, batch_size, progress=None):
275
+ """Stage 2: condensed (1) vs diffuse (0) for each generated image."""
276
+ device = get_device()
277
+ _, classifier, _ = models_on(device)
278
+
279
+ preds = []
280
+ for start in range(0, images.shape[0], batch_size):
281
+ end = min(start + batch_size, images.shape[0])
282
+
283
+ if progress is not None:
284
+ progress(start / images.shape[0], desc=f"Classifying {start}-{end} of {images.shape[0]}")
285
+
286
+ batch = torch.from_numpy(images[start:end].astype(np.float32)).to(device)
287
+ batch = batch / 65535.0 * 2.0 - 1.0 # back to [-1, 1]
288
+ logits = classifier.predict(batch)
289
+ preds.append(torch.argmax(logits, dim=1).cpu().numpy())
290
+
291
+ return np.concatenate(preds).astype(int)
292
+
293
+
294
+ def summarise(intensities, predictions, num_images):
295
+ """Stage 3: moving average, then AUC / AAC / c_sat over the smoothed curve."""
296
+ df = pd.DataFrame(
297
+ {"protein_intensity_level": intensities, "predicted_class": predictions}
298
+ )
299
+ window = max(1, num_images // WINDOW_DIVISOR)
300
+ kw = dict(window_size=window, use_log_scale=True)
301
+
302
+ return df, window, dict(
303
+ curve=metrics.moving_average(predictions, window),
304
+ auc=metrics.compute_area_under_curve(df, **kw),
305
+ aac=metrics.compute_area_above_curve(df, **kw),
306
+ no_reentrant_auc=metrics.compute_area_if_no_reentrant(df, **kw),
307
+ c_sat=metrics.compute_concentration(df, window_size=window),
308
+ )
309
+
310
+
311
+ def sample_panel(images, intensities, k=6):
312
+ """Pick k images spread evenly along the ladder, for the strip shown under the curve."""
313
+ idx = np.linspace(0, len(intensities) - 1, k).astype(int)
314
+ return images[idx, 1].astype(np.float32) / 65535.0, intensities[idx]
315
+
316
+
317
+ def run(sequence, num_images=NUM_IMAGES, num_steps=NUM_STEPS, batch_size=BATCH_SIZE,
318
+ seed=DEFAULT_SEED, progress=None) -> Result:
319
+ """The whole pipeline: sequence in, titration curve and its areas out."""
320
+ sequence = clean_sequence(sequence)
321
+
322
+ images = generate_images(sequence, num_images, num_steps, batch_size, seed, progress)
323
+ predictions = classify_images(images, batch_size, progress)
324
+
325
+ intensities = intensity_ladder(num_images).numpy()
326
+ _, window, stats = summarise(intensities, predictions, num_images)
327
+ panel, panel_x = sample_panel(images, intensities)
328
+
329
+ return Result(
330
+ sequence=sequence,
331
+ intensities=intensities,
332
+ predictions=predictions,
333
+ window=window,
334
+ images=panel,
335
+ image_intensities=panel_x,
336
+ **stats,
337
+ )
cell_fm/logging/loggers.py CHANGED
@@ -9,8 +9,9 @@ from loguru import logger
9
  from cell_fm.utils.dist_utils import is_master_node
10
  from transformers import TrainerCallback
11
 
12
- # wandb is only used by the training callback below. The demo Space never trains,
13
- # so it is optional here rather than a required install.
 
14
  try:
15
  import wandb # isort:skip
16
  except ImportError: # pragma: no cover
 
9
  from cell_fm.utils.dist_utils import is_master_node
10
  from transformers import TrainerCallback
11
 
12
+ # wandb is only used by the training callback below, so it is optional rather than a
13
+ # required install: the Colab notebooks import cell_fm through this module and Colab has
14
+ # no wandb, which would otherwise make every notebook fail at its first import.
15
  try:
16
  import wandb # isort:skip
17
  except ImportError: # pragma: no cover
cell_fm/models/vit_cls/__init__.py ADDED
File without changes
cell_fm/models/vit_cls/config.py ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ from dataclasses import dataclass
3
+ from transformers import PretrainedConfig
4
+
5
+ @dataclass
6
+ class ViTConfig(PretrainedConfig):
7
+ model_type: str = 'vit'
8
+
9
+ # Dataset parameters
10
+ data_path: str = ""
11
+ split_key: str = 'train'
12
+ phase: str = 'train' # 'train', 'val', 'test'
13
+
14
+ data_aug: bool = False
15
+ normalize: bool = False
16
+ img_resize: int = 256
17
+ img_crop_size: int = 1024
18
+
19
+ cell_image: str = 'nucl' # 'nucl', 'nucl,er', 'nucl,mt', 'nucl,er,mt'
20
+
21
+ # Model parameters
22
+ patch_size: int = 4
23
+ num_layers: int = 12
24
+ num_heads: int = 8
25
+ hidden_dim: int = 768
26
+ mlp_dim: int = 3072
27
+ num_classes: int = 1000
28
+
29
+ # Training parameters
30
+ loadcheck_path: str = '.'
31
+ ft: bool = False
32
+ infer: bool = False
33
+ ifresume: bool = False
34
+
35
+ output_dir: str = ""
36
+ learning_rate: float = 1e-4
37
+ weight_decay: float = 0.0
38
+ gradient_accumulation_steps: int = 1
39
+ per_device_train_batch_size: int = 2
40
+ per_device_eval_batch_size: int = 2
41
+
42
+ num_train_epochs: int = 10
43
+ fp16: bool = False
44
+ bf16: bool = False
45
+ logging_dir: str = ""
46
+ logging_steps: int = 10
47
+ max_steps: int = -1
48
+ warmup_steps: int = 1000
49
+ save_steps: int = 1000
50
+
51
+ dataloader_num_workers: int = 8
52
+ seed: int = 6
53
+
54
+ # evaluation
55
+ num_steps: int = 100
56
+
57
+ def __init__(self, **kwargs):
58
+ # Use `super().__init__` to handle arguments from PretrainedConfig
59
+ super().__init__(**kwargs)
cell_fm/models/vit_cls/model.py ADDED
@@ -0,0 +1,196 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import torch
3
+ import torch.nn as nn
4
+ from cell_fm.logging import logger
5
+ from transformers import PreTrainedModel
6
+ from .config import ViTConfig
7
+
8
+ from torchvision.models.vision_transformer import VisionTransformer
9
+ from functools import partial
10
+
11
+ from cell_fm.pipeline.utils import VanillaOutput
12
+ import json
13
+
14
+
15
+ class ViTModel(PreTrainedModel):
16
+ config_class = ViTConfig
17
+
18
+ def __init__(self, config: ViTConfig):
19
+ super().__init__(config)
20
+ self.config = config
21
+
22
+ self.loss = nn.CrossEntropyLoss()
23
+ self.net = ViT(config)
24
+
25
+ self.load_pretrained_weights(config, checkpoint_path=config.loadcheck_path)
26
+
27
+ def load_pretrained_weights(self, config, checkpoint_path):
28
+ """
29
+ Load pretrained weights from a given state_dict.
30
+ """
31
+ if config.ft or config.infer:
32
+ if config.ft:
33
+ logger.info(f"Finetune from checkpoint: {checkpoint_path}")
34
+ else:
35
+ logger.info(f"Infer from checkpoint: {checkpoint_path}")
36
+
37
+ if os.path.isdir(checkpoint_path):
38
+ with open(os.path.join(checkpoint_path, "pytorch_model.bin.index.json"), "r") as f:
39
+ index_data = json.load(f)
40
+
41
+ weight_map = index_data["weight_map"]
42
+
43
+ shard_files = set(weight_map.values())
44
+ shard_weights = {}
45
+ for shard_file in shard_files:
46
+ shard_weights[shard_file] = torch.load(os.path.join(checkpoint_path, shard_file), map_location="cpu")
47
+
48
+ checkpoints_state = {}
49
+ for param_name, shard_file in weight_map.items():
50
+ checkpoints_state[param_name] = shard_weights[shard_file][param_name]
51
+ elif os.path.splitext(checkpoint_path)[1] == '.safetensors':
52
+ from safetensors.torch import load_file
53
+ checkpoints_state = load_file(checkpoint_path)
54
+ else:
55
+ checkpoints_state = torch.load(checkpoint_path, map_location="cpu")
56
+
57
+ if "model" in checkpoints_state:
58
+ checkpoints_state = checkpoints_state["model"]
59
+ elif "module" in checkpoints_state:
60
+ checkpoints_state = checkpoints_state["module"]
61
+
62
+ model_state_dict = self.state_dict()
63
+ filtered_state_dict = {k: v for k, v in checkpoints_state.items() if k in model_state_dict and v.size() == model_state_dict[k].size()}
64
+
65
+ IncompatibleKeys = self.load_state_dict(filtered_state_dict, strict=False)
66
+ IncompatibleKeys = IncompatibleKeys._asdict()
67
+
68
+ missing_keys = []
69
+ for keys in IncompatibleKeys["missing_keys"]:
70
+ if keys.find("dummy") == -1:
71
+ missing_keys.append(keys)
72
+
73
+ unexpected_keys = []
74
+ for keys in IncompatibleKeys["unexpected_keys"]:
75
+ if keys.find("dummy") == -1:
76
+ unexpected_keys.append(keys)
77
+
78
+ if len(missing_keys) > 0:
79
+ logger.info(
80
+ "Missing keys in {}: {}".format(
81
+ checkpoint_path,
82
+ missing_keys,
83
+ )
84
+ )
85
+
86
+ if len(unexpected_keys) > 0:
87
+ logger.info(
88
+ "Unexpected keys {}: {}".format(
89
+ checkpoint_path,
90
+ unexpected_keys,
91
+ )
92
+ )
93
+
94
+ @torch.no_grad()
95
+ def prepare_data(self, batched_data):
96
+
97
+ if self.config.cell_image == 'nucl':
98
+ protein_img = batched_data['protein_img']
99
+ nucleus_img = batched_data['nucleus_img']
100
+ input_img = torch.cat([nucleus_img, protein_img], dim=1) # [B, 2, H, W]
101
+ elif self.config.cell_image == 'nucl,er':
102
+ protein_img = batched_data['protein_img']
103
+ nucleus_img = batched_data['nucleus_img']
104
+ ER_img = batched_data['ER_img']
105
+ input_img = torch.cat([nucleus_img, ER_img, protein_img], dim=1) # [B, 3, H, W]
106
+ elif self.config.cell_image == 'nucl,mt':
107
+ protein_img = batched_data['protein_img']
108
+ nucleus_img = batched_data['nucleus_img']
109
+ microtubules_img = batched_data['microtubules_img']
110
+ input_img = torch.cat([nucleus_img, microtubules_img, protein_img], dim=1) # [B, 3, H, W]
111
+ elif self.config.cell_image == 'nucl,er,mt':
112
+ protein_img = batched_data['protein_img']
113
+ nucleus_img = batched_data['nucleus_img']
114
+ ER_img = batched_data['ER_img']
115
+ microtubules_img = batched_data['microtubules_img']
116
+ input_img = torch.cat([nucleus_img, ER_img, microtubules_img, protein_img], dim=1) # [B, 4, H, W]
117
+
118
+ return input_img
119
+
120
+
121
+ def forward(self, batched_data, **kwargs):
122
+ input_img = self.prepare_data(batched_data)
123
+
124
+ labels = batched_data["protein_idx"]
125
+
126
+ logits = self.net(input_img) # [B, num_classes]
127
+
128
+ loss = self.loss(logits, labels.view(-1))
129
+ loss = loss.mean()
130
+
131
+ return VanillaOutput(loss=loss)
132
+
133
+ def embed(self, x: torch.Tensor):
134
+ with torch.no_grad():
135
+ embed = self.net.embed(x)
136
+ return embed
137
+
138
+
139
+ class ViT(VisionTransformer):
140
+ def __init__(self, config: ViTConfig):
141
+ super().__init__(
142
+ image_size=config.img_resize,
143
+ patch_size=config.patch_size,
144
+ num_layers=config.num_layers,
145
+ num_heads=config.num_heads,
146
+ hidden_dim=config.hidden_dim,
147
+ mlp_dim=config.mlp_dim,
148
+ dropout=0.0,
149
+ attention_dropout=0.0,
150
+ num_classes=config.num_classes,
151
+ representation_size=None,
152
+ norm_layer=partial(nn.LayerNorm, eps=1e-6),
153
+ conv_stem_configs=None,
154
+ )
155
+
156
+ old_conv = self.conv_proj
157
+
158
+ in_channels = len(config.cell_image.split(',')) + 1
159
+
160
+ self.conv_proj = nn.Conv2d(
161
+ in_channels=in_channels,
162
+ out_channels=old_conv.out_channels,
163
+ kernel_size=old_conv.kernel_size,
164
+ stride=old_conv.stride,
165
+ padding=old_conv.padding,
166
+ bias=old_conv.bias is not None,
167
+ )
168
+
169
+ def forward(self, x: torch.Tensor):
170
+ # Reshape and permute the input tensor
171
+ x = self._process_input(x)
172
+ n = x.shape[0]
173
+
174
+ # Expand the class token to the full batch
175
+ batch_class_token = self.class_token.expand(n, -1, -1)
176
+ x = torch.cat([batch_class_token, x], dim=1)
177
+
178
+ x = self.encoder(x)
179
+ x = x.mean(dim=1) # Global average pooling over the sequence length
180
+ x = self.heads(x)
181
+
182
+ return x
183
+
184
+ def embed(self, x: torch.Tensor):
185
+ # Reshape and permute the input tensor
186
+ x = self._process_input(x)
187
+ n = x.shape[0]
188
+
189
+ # Expand the class token to the full batch
190
+ batch_class_token = self.class_token.expand(n, -1, -1)
191
+ x = torch.cat([batch_class_token, x], dim=1)
192
+
193
+ x = self.encoder(x)
194
+ embed = x.mean(dim=1) # Global average pooling over the sequence length
195
+
196
+ return embed