File size: 63,184 Bytes
328fef0 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 | """Core CellGemma Two-Stage Single-Cell Inference & 3D Molecular/Network Engine."""
from __future__ import annotations
import json
import math
import os
import queue
import re
import threading
import time
from pathlib import Path
from typing import Any, Iterator
import numpy as np
import safetensors.torch
import torch
from huggingface_hub import hf_hub_download
from rdkit import Chem
from rdkit.Chem import AllChem, Descriptors, rdDepictor, rdMolDescriptors
from torch import nn
from transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer
DEFAULT_MODEL_ID = os.environ.get("CELLGEMMA_MODEL_ID", "google/cellgemma-e4b")
IS_ZEROGPU = os.environ.get("SPACES_ZERO_GPU") == "1"
PREAMBLE = (
"Examine how the single-cell sample, captured in 'Source:', responds "
"transcriptionally to the perturbation under the stated experimental "
"conditions. You are given the dataset-wide average prediction in 'Mean "
"Global prediction:' and you need to predict the residual from that mean "
"to the true final expression."
)
SMILES_ALLOW_RE = re.compile(r"^[A-Za-z0-9@+\-\[\]\(\)=#$%/\\.,]{1,200}$")
GENE_ALLOW_RE = re.compile(r"^[A-Z0-9\-]{1,20}$")
# Single-cell showcase presets grounded in controls_sample.json
CURATED_PRESETS: list[dict[str, Any]] = [
{
"id": "panobinostat",
"dataset": "tahoe",
"kind": "drug",
"name": "Panobinostat",
"role": "HDAC Inhibitor 路 Unpacks DNA & Raises Surface Flags",
"smiles": "Cc1[nH]c2ccccc2c1CCNCc1ccc(/C=C/C(=O)NO)cc1",
"concentration_um": 0.5,
"cell_idx": 0,
"summary": "Relaxes tightly packed chromatin in A549 lung-cancer cells, turning up histones (+H1-0, +H3-3B) and 'eat-me' surface flag +CALR while turning down p53 brake -MDM2.",
},
{
"id": "dasatinib",
"dataset": "tahoe",
"kind": "drug",
"name": "Dasatinib",
"role": "Kinase Inhibitor 路 Blocks Invasion Receptors",
"smiles": "Cc1nc(Nc2ncc(C(=O)Nc3c(C)cccc3Cl)s2)cc(N2CCN(CCO)CC2)n1",
"concentration_um": 0.5,
"cell_idx": 0,
"summary": "Inhibits SRC/ABL/EPHA2 kinases in A549 lung-cancer cells, turning down invasion & growth receptors (-LRP1, -IGFBP3) while remodeling structural filaments (+VIM, +PLOD2).",
},
{
"id": "trametinib",
"dataset": "tahoe",
"kind": "drug",
"name": "Trametinib",
"role": "MEK1/2 Inhibitor 路 Cuts MAPK Growth Relay",
"smiles": "CC(=O)Nc1cccc(-n2c(=O)n(C3CC3)c(=O)c3c(Nc4ccc(I)cc4F)n(C)c(=O)c(C)c32)c1",
"concentration_um": 0.5,
"cell_idx": 0,
"summary": "Blocks MEK1/2 signaling downstream of KRAS in A549 cells, suppressing migration/MAPK feedback genes (-ARHGAP26, -LRP1, -DUSP5) and boosting redox defense (+TXNRD1).",
},
{
"id": "myc_kd",
"dataset": "k562",
"kind": "crispr",
"name": "Mute MYC",
"role": "Master Growth Oncogene 路 Collapses Ribosome Factories",
"gene": "MYC",
"concentration_um": 1.0,
"cell_idx": 0,
"summary": "CRISPRi knockdown of master growth switch MYC in K562 leukemia cells shuts down ribosome & polyamine factories (-C1QBP, -SRM, -WDR43, -RRP1B) and switches on red-blood-cell maturation (+GYPB, +HBZ, +ALAS2, +HBG2).",
},
{
"id": "dnmt1_kd",
"dataset": "k562",
"kind": "crispr",
"name": "Mute DNMT1",
"role": "DNA Methylation Lock 路 Lifts Epigenetic Silencing",
"gene": "DNMT1",
"concentration_um": 1.0,
"cell_idx": 0,
"summary": "CRISPRi knockdown of DNA methyltransferase DNMT1 lifts epigenetic silencing, exposing surface & secreted proteins (+SLC7A8, +LGALS1, +MDK) while suppressing nucleolar assembly (-NOLC1, -MRTO4).",
},
]
# Subcellular location ("surface" | "nucleus" | "cytoplasm"), plain-English nickname, & explanation
GENE_ANNOTATIONS: dict[str, tuple[str, str, str]] = {
# Surface receptors, adhesion molecules, transporters & immune flags
"CALR": ("surface", "Calreticulin 'Eat-Me' Flag", "Surface chaperone that flags stressed tumor cells for immune engulfment."),
"B2M": ("surface", "MHC-I Antigen Presentation", "Essential MHC Class I subunit enabling T-cells to inspect tumor antigens."),
"GPNMB": ("surface", "CAR-T Surface Beacon", "Transmembrane glycoprotein targeted by solid-tumor CAR-T immunotherapies."),
"MAGEA10": ("surface", "Cancer-Testis Immune Antigen", "Normally silent germline antigen unmasked on demethylated tumor cells."),
"PAGE5": ("surface", "Unmasked Tumor Antigen", "Cancer-testis antigen awakened when DNA methylation locks are removed."),
"GYPB": ("surface", "Glycophorin B Red-Cell Coat", "Major red-blood-cell membrane coat protein induced as K562 matures."),
"GYPC": ("surface", "Glycophorin C Membrane Coat", "Erythroid plasma-membrane glycoprotein stabilizing mature red cells."),
"LGALS1": ("surface", "Galectin-1 Surface Lectin", "Cell-surface carbohydrate-binding protein remodeled during lineage shifts."),
"MDK": ("surface", "Midkine Secreted Signal", "Secreted growth/immune signaling factor induced upon epigenetic remodeling."),
"SLC7A8": ("surface", "LAT2 Surface Transporter", "Plasma-membrane neutral amino-acid channel awakened after demethylation."),
"AQP3": ("surface", "Aquaporin-3 Water Channel", "Cell-membrane water/glycerol pore upregulated during differentiation."),
"CAVIN1": ("surface", "Caveolae Membrane Sculptor", "Stabilizes plasma-membrane signaling pockets under MEK blockade."),
"AREG": ("surface", "Amphiregulin EGFR Ligand", "Secreted cell-surface growth-factor feedback signal."),
"LRP1": ("surface", "LRP1 Invasion Receptor", "Large cell-surface endocytic & migration receptor suppressed by kinase blockade."),
"PTPRJ": ("surface", "DEP-1 Surface Phosphatase", "Transmembrane receptor tyrosine phosphatase remodeled at cell junctions."),
"CA12": ("surface", "Hypoxia Acid-Shield (CA12)", "Cell-surface carbonic anhydrase helping tumor cells survive acidic niches."),
"SERPINE1": ("surface", "PAI-1 Matrix Invasion Shield", "Secreted adhesion & extracellular matrix regulator driving tumor migration."),
"IGFBP3": ("surface", "IGF Growth-Factor Carrier", "Extracellular growth-factor binding protein suppressed by kinase inhibition."),
"STC1": ("surface", "Stanniocalcin-1 Secreted Signal", "Secreted calcium/hypoxia survival hormone downregulated by MEK inhibition."),
"ADAM9": ("surface", "ADAM9 Surface Sheddase", "Membrane metalloprotease remodeling cell-surface receptors."),
"MYOF": ("surface", "Myoferlin Membrane Repair", "Plasma-membrane repair protein induced under signaling stress."),
"EPHA2": ("surface", "EPHA2 Surface Kinase", "Ephrin receptor tyrosine kinase regulating adhesion and surface antigen levels."),
"EGFR": ("surface", "EGFR Growth Receptor", "Transmembrane growth-factor antenna driving epithelial proliferation."),
"ITGA2": ("surface", "Integrin Alpha-2 Hook", "Surface collagen-adhesion receptor downregulated when MAPK signaling drops."),
"ICAM1": ("surface", "ICAM-1 Immune Docking Velcro", "Adhesion ligand stabilizing physical contact with immune T-cells."),
"ANXA1": ("surface", "Annexin A1 Membrane Signal", "Phospholipid-binding surface modulator induced during differentiation."),
"SEMA4B": ("surface", "Semaphorin-4B Surface Cue", "Transmembrane guidance receptor remodeled under Src/RTK kinase blockade."),
# Nuclear chromatin, histones, transcription factors & nucleolar ribosome assembly
"H1-0": ("nucleus", "Linker Histone H1.0", "Terminal-differentiation histone induced when HDAC inhibitors unpack DNA."),
"H3-3B": ("nucleus", "Active Histone H3.3B", "Replacement histone loaded into newly opened, active DNA regions."),
"H1-2": ("nucleus", "Linker Histone H1.2", "Nuclear chromatin-compaction histone remodeled upon cell-cycle exit."),
"H1-4": ("nucleus", "Replication Histone H1.4", "S-phase chromatin linker downregulated as rapid division slows."),
"NAP1L1": ("nucleus", "Histone Chaperone NAP1L1", "Shuttles histones into the nucleus to assemble nucleosomes."),
"SMAD3": ("nucleus", "TGF-Beta Nuclear Regulator", "Transcription factor driving pro-tumor mesenchymal & survival programs."),
"MDM2": ("nucleus", "p53 Suppressor Brake (MDM2)", "Destroys tumor-suppressor p53; turning MDM2 down unleashes p53 checkpoints."),
"NRIP1": ("nucleus", "Nuclear Receptor Co-Repressor", "Transcriptional co-regulator modulating hormone and metabolic genes."),
"CDKN1A": ("nucleus", "p21 Cell-Division Brake", "Directly locks nuclear cyclin-CDK motors to halt tumor cell division."),
"GADD45A": ("nucleus", "DNA Stress Arrest Sensor", "Nuclear checkpoint protein induced when MYC proliferation stops."),
"CCND3": ("nucleus", "Cyclin D3 Lineage Switch", "Coordinates final erythroid maturation divisions before growth exit."),
"MYC": ("nucleus", "MYC Master Growth Switch", "Oncogenic transcription factor driving cell division and ribosome production."),
"DNMT1": ("nucleus", "DNA Methylation Lock (DNMT1)", "Copies repressive methyl marks onto DNA to keep genes silenced."),
"USP34": ("nucleus", "Wnt Signaling Stabilizer", "Deubiquitinase sustaining nuclear beta-catenin survival transcription."),
"DUSP5": ("nucleus", "Nuclear ERK Phosphatase", "Direct nuclear feedback readout of active MAPK/ERK growth signaling; drops under MEK blockade."),
"ZC3H11A": ("nucleus", "Nuclear mRNA Export Complex", "TREX-associated nuclear export factor required under rapid growth."),
"ZCCHC7": ("nucleus", "Nuclear RNA Surveillance", "Nucleolar TRAMP-complex cofactor degrading aberrant RNAs."),
"MSI2": ("nucleus", "Stemness RNA Regulator MSI2", "Maintains undifferentiated leukemia/tumor stem-cell programs."),
"SF3B1": ("nucleus", "Core Spliceosome Hub SF3B1", "Nuclear pre-mRNA splicing factor downregulated as proliferation slows."),
"PTMA": ("nucleus", "Prothymosin-Alpha Chromatin", "MYC-regulated nuclear protein keeping proliferating chromatin accessible."),
"HMGA1": ("nucleus", "HMGA1 Chromatin Architect", "Oncogenic architectural DNA protein repressed when MYC is silenced."),
"RRP1B": ("nucleus", "Nucleolar rRNA Processor 1B", "Direct MYC target building 60S ribosomes inside the nucleolus."),
"WDR43": ("nucleus", "Small-Subunit Processome", "Essential nucleolar ribosome-assembly protein; collapses without MYC."),
"TSR1": ("nucleus", "40S Ribosome Maturation", "Nucleolar assembly factor suppressed when growth signaling drops."),
"MRTO4": ("nucleus", "60S Ribosome Stalk Loader", "Nuclear pre-60S ribosome assembly factor downregulated on demethylation."),
"NOLC1": ("nucleus", "Nucleolar Scaffold NOLC1", "Core nucleolar organizer linking RNA Pol I transcription to ribosome assembly."),
"NOP16": ("nucleus", "Nucleolar 60S Factor NOP16", "MYC-responsive nucleolar protein assembling large ribosomal subunits."),
"RRP9": ("nucleus", "U3 snoRNP Cleavage Factor", "Processes precursor rRNA inside the nucleolus."),
"SNU13": ("nucleus", "Box C/D snoRNP Core", "Essential nucleolar rRNA-modification & spliceosome protein."),
"EXOSC7": ("nucleus", "Nuclear RNA Exosome Core", "Trims ribosomal RNA precursors in rapidly dividing cells."),
"NCL": ("nucleus", "Nucleolin Ribosome Hub", "Major nucleolar protein driving rRNA synthesis in cancer cells."),
"NPM1": ("nucleus", "Nucleophosmin Growth Hub", "Central nucleolar chaperone shuttling ribosomal subunits."),
"DCTPP1": ("nucleus", "dCTP Nucleotide Sanitizer", "Maintains DNA replication nucleotide pools in dividing tumor cells."),
"GPATCH2L": ("nucleus", "G-Patch RNA Splicing Factor", "Nuclear G-patch domain cofactor partnering with RNA helicases during splicing."),
# Cytoplasmic chaperones, ribosomes, mitochondria, cytoskeleton & metabolism
"HSPA5": ("cytoplasm", "BiP ER Stress Chaperone", "Master endoplasmic-reticulum protein-folding sensor induced by HDAC inhibition."),
"HSP90B1": ("cytoplasm", "Grp94 Folding Chaperone", "ER chaperone folding secreted & immune-presentation proteins."),
"HSP90AA1": ("cytoplasm", "HSP90-Alpha Chaperone", "Stress-inducible cytosolic chaperone hyperacetylated by Panobinostat."),
"HSPD1": ("cytoplasm", "HSP60 Mitochondrial Chaperone", "Refolds proteins inside mitochondria under kinase/metabolic stress."),
"CRYAB": ("cytoplasm", "Alpha-B Crystallin Shield", "Small heat-shock protein stabilizing cytoskeleton filaments."),
"HBZ": ("cytoplasm", "Embryonic Zeta-Globin", "Oxygen-binding hemoglobin chain switched on as K562 matures into a red cell."),
"HBG2": ("cytoplasm", "Fetal Hemoglobin Gamma-2", "Hallmark oxygen-carrying hemoglobin induced during leukemia differentiation."),
"HBG1": ("cytoplasm", "Fetal Hemoglobin Gamma-1", "Beta-like globin chain marking K562 red-blood-cell maturation."),
"HBA1": ("cytoplasm", "Adult Hemoglobin Alpha-1", "Core alpha-globin subunit awakened upon erythroid differentiation."),
"ALAS2": ("cytoplasm", "Heme Synthesis Enzyme ALAS2", "Rate-limiting enzyme building red-blood-cell heme groups."),
"BLVRB": ("cytoplasm", "Biliverdin Reductase B", "Erythroid heme-metabolism enzyme tracking red-cell commitment."),
"SLC25A37": ("cytoplasm", "Mitoferrin-1 Iron Importer", "Pumps iron into mitochondria to build hemoglobin in maturing cells."),
"C1QBP": ("cytoplasm", "Mitochondrial Protein Factory", "Direct MYC target powering oxidative metabolism; drops sharply when MYC is muted."),
"SRM": ("cytoplasm", "Spermidine Synthase (MYC Target)", "Canonical MYC-driven polyamine growth enzyme; collapses on MYC knockdown."),
"PPA1": ("cytoplasm", "Pyrophosphatase Energy Driver", "Fuels biosynthetic reactions in rapidly dividing cells; drops without MYC."),
"EIF3B": ("cytoplasm", "Translation Initiation eIF3B", "Core scaffold starting mRNA-to-protein translation in growing cells."),
"MRPL15": ("cytoplasm", "Mitochondrial Ribosome L15", "Synthesizes respiratory proteins inside mitochondria; downregulated on MYC loss."),
"PABPC4": ("cytoplasm", "mRNA Poly(A) Stabilizer", "Binds mRNA tails to boost cytoplasmic translation."),
"TOMM40": ("cytoplasm", "Mitochondrial Import Pore", "Main outer-membrane channel importing proteins into mitochondria."),
"TXNIP": ("cytoplasm", "Glucose Uptake Brake TXNIP", "Blocks tumor sugar import (GLUT1) and restrains Warburg growth."),
"MYL6": ("cytoplasm", "Myosin Light Chain 6", "Regulatory actomyosin motor subunit remodeled as cell migration halts."),
"RND3": ("cytoplasm", "RhoE Cytoskeletal GTPase", "Antagonizes RhoA-ROCK stress fibers upon Src/tyrosine kinase inhibition."),
"RPL36": ("cytoplasm", "60S Ribosomal Subunit L36", "Large-subunit ribosomal protein rebalanced during translational arrest."),
"TXNRD1": ("cytoplasm", "Thioredoxin Reductase Antioxidant", "Protects cells against oxidative stress when MAPK signaling is blocked."),
"PLOD2": ("cytoplasm", "Collagen Cross-Linking Enzyme", "ER hydroxylase remodeled during tyrosine-kinase inhibition."),
"VIM": ("cytoplasm", "Vimentin Structural Filament", "Intermediate cytoskeleton filament reorganized as cell shape & motility shift."),
"MYH9": ("cytoplasm", "Myosin-IIA Contractile Motor", "Actin-bundling motor remodeling cell tension and morphology."),
"MYO10": ("cytoplasm", "Myosin-X Filopodia Motor", "Cytoskeletal motor reorganized upon MEK pathway inhibition."),
"ACTG1": ("cytoplasm", "Gamma-Actin Cytoskeleton", "Core structural microfilament remodeled during chromatin unpacking."),
"SPTBN1": ("cytoplasm", "Beta-II Spectrin Scaffold", "Membrane-cytoskeleton linker modulated alongside TGF-beta/SMAD3."),
"TRIO": ("cytoplasm", "Rho/Rac Cytoskeleton Relay", "Guanine exchange factor remodeling actin architecture."),
"ARHGAP26": ("cytoplasm", "FAK/Rho Migration Regulator", "Focal-adhesion GTPase regulator downregulated when MEK signaling stops."),
"ARHGAP5": ("cytoplasm", "p190-B RhoGAP Motility Relay", "Integrin/cytoskeleton signaling relay reduced under MEK blockade."),
"NPC1": ("cytoplasm", "Cholesterol Trafficking Pore", "Endosomal lipid transporter downregulated when growth kinases are blocked."),
"GRB10": ("cytoplasm", "Growth-Receptor Adapter GRB10", "Cytoplasmic signaling adapter linking RTK/mTOR pathways."),
"AKT3": ("cytoplasm", "AKT3 Survival Kinase", "Pro-survival PI3K-AKT kinase suppressed by Panobinostat."),
"SOD2": ("cytoplasm", "Mitochondrial Superoxide Shield", "Antioxidant enzyme inside mitochondria remodeled under HDAC inhibition."),
"ALDOA": ("cytoplasm", "Aldolase-A Glycolysis Enzyme", "Core sugar-splitting enzyme adjusted during metabolic reprogramming."),
"GPI": ("cytoplasm", "Glucose-6-Phosphate Isomerase", "Glycolytic metabolic enzyme modulated under MEK inhibition."),
"GBE1": ("cytoplasm", "Glycogen Branching Enzyme", "Hypoxia-linked energy-storage enzyme downregulated after HDAC inhibition."),
"DHRS2": ("cytoplasm", "Dicarbonyl Stress Reductase", "Detoxifies reactive lipid/carbonyl species in stressed cells."),
"FTL": ("cytoplasm", "Ferritin Light-Chain Iron Cage", "Safely stores intracellular iron to prevent oxidative damage."),
"ATG7": ("cytoplasm", "Autophagy Recycling Enzyme", "Core E1-like enzyme driving autophagosome membrane assembly."),
"RPS27A": ("cytoplasm", "40S Ribosome-Ubiquitin S27a", "Small ribosomal subunit protein coupling translation to ubiquitin."),
"RPS17": ("cytoplasm", "40S Ribosomal Subunit S17", "Cytoplasmic small ribosomal subunit protein."),
"RPS5": ("cytoplasm", "40S Ribosomal Subunit S5", "Decoding-center protein of the 40S ribosome."),
"RPS6": ("cytoplasm", "40S Ribosomal Sensor S6", "mTOR/S6K-regulated ribosomal subunit tracking growth state."),
"RPL7": ("cytoplasm", "60S Ribosomal Subunit L7", "Large ribosomal subunit protein assembling peptides."),
"RPL23": ("cytoplasm", "60S Ribosomal Subunit L23", "Large ribosomal protein that also regulates MDM2-p53 feedback."),
"RPL26": ("cytoplasm", "60S Ribosomal Subunit L26", "Large ribosomal subunit boosting p53 translation under stress."),
"RPL31": ("cytoplasm", "60S Ribosomal Subunit L31", "Polypeptide exit-tunnel subunit of the 60S ribosome."),
"MT-ND1": ("cytoplasm", "Mitochondrial Complex I (ND1)", "Core electron-transport chain subunit inside mitochondria."),
"MT-ND2": ("cytoplasm", "Mitochondrial Complex I (ND2)", "Proton-pumping respiratory subunit inside mitochondria."),
"FNDC3B": ("cytoplasm", "FNDC3B ER-Membrane Adhesion", "Endoplasmic-reticulum membrane regulator promoting cell migration and stress survival."),
"NDRG1": ("cytoplasm", "NDRG1 Stress/Hypoxia Sensor", "Iron- and stress-regulated protein modulating lipid trafficking and differentiation."),
"FTH1": ("cytoplasm", "Ferritin Heavy-Chain Iron Cage", "Ferroxidase iron-storage subunit preventing labile iron oxidative stress."),
"PABPC1": ("cytoplasm", "mRNA Poly(A) Translation Hub", "Cytoplasmic poly(A)-binding protein stabilizing mRNA tails for translation."),
"IRAK2": ("cytoplasm", "IRAK2 Innate Signaling Kinase", "Receptor-proximal kinase relaying stress and inflammatory NF-kB signals."),
"CRYM": ("cytoplasm", "Mu-Crystallin Thyroid Binder", "Cytosolic ketimine reductase & thyroid-hormone binding protein awakened on differentiation."),
"CPXM1": ("surface", "CPXM1 Matrix Metallocarboxypeptidase", "Secreted cell-surface/extraceullar matrix remodeling protein unmasked on demethylation."),
"NOSIP": ("cytoplasm", "NOSIP Ubiquitin E3 Modulator", "Regulates protein turnover and mitotic/erythropoietic maturation."),
"GAL": ("surface", "Galanin Secreted Neuropeptide", "Normally silent secreted signaling peptide unmasked when DNMT1 methylation drops."),
"PSAP": ("cytoplasm", "Prosaposin Lysosomal Factor", "Lysosomal sphingolipid activator & secreted trophic factor remodeled during differentiation."),
"SNRPD1": ("nucleus", "Spliceosome Core Sm-D1", "Essential Sm-ring core subunit of nuclear U1/U2/U4/U5 spliceosomal snRNPs; drops when MYC is muted."),
"SNRPD2": ("nucleus", "Spliceosome Core Sm-D2", "Nuclear Sm-ring subunit assembling spliceosomal snRNPs during active proliferation."),
"SNRPD3": ("nucleus", "Spliceosome Core Sm-D3", "Core nuclear spliceosome scaffold required for pre-mRNA splicing in dividing cells."),
"SNRPE": ("nucleus", "Spliceosome Core Sm-E", "Nuclear snRNP core ring protein downregulated upon cell-cycle exit."),
"SNRPF": ("nucleus", "Spliceosome Core Sm-F", "Nuclear pre-mRNA spliceosome assembly subunit."),
"SNRPG": ("nucleus", "Spliceosome Core Sm-G", "Heptameric Sm-ring nuclear splicing subunit."),
"HSP90AB1": ("cytoplasm", "HSP90-Beta Folding Chaperone", "Constitutive cytosolic chaperone stabilizing signaling kinases and steroid receptors."),
"HSPA8": ("cytoplasm", "HSC70 Constitutive Chaperone", "Housekeeping cytosolic clathrin-uncoating and protein-folding ATPase."),
"HSPE1": ("cytoplasm", "HSP10 Mitochondrial Co-Chaperone", "Partners with mitochondrial HSP60 to fold respiratory enzymes."),
"FKBP4": ("cytoplasm", "FKBP52 HSP90 Co-Chaperone", "MYC-regulated immunophilin co-chaperone assisting HSP90 protein complexes."),
"PPP1R15A": ("cytoplasm", "GADD34 Stress Phosphatase", "Integrated stress-response feedback subunit dephosphorylating eIF2-alpha."),
"DDIT3": ("nucleus", "CHOP ER-Stress Factor (DDIT3)", "Nuclear transcription factor activated by unfolded-protein and metabolic stress."),
"BTG1": ("nucleus", "BTG1 Anti-Proliferation Brake", "Nuclear mRNA deadenylation regulator enforcing cell-cycle exit and differentiation."),
"BTG2": ("nucleus", "BTG2 p53-Linked Growth Brake", "Anti-proliferative nuclear checkpoint cofactor halting G1/S progression."),
"ODC1": ("cytoplasm", "Ornithine Decarboxylase (MYC)", "Direct MYC-driven rate-limiting enzyme of polyamine synthesis for cell growth."),
"PAICS": ("cytoplasm", "Purine Synthesis Enzyme PAICS", "MYC-activated de novo purine nucleotide synthesis enzyme fueling DNA replication."),
"NME1": ("cytoplasm", "Nucleoside Kinase A (NME1)", "MYC-responsive nucleotide pool kinase synthesizing NTPs."),
"TFRC": ("surface", "CD71 Transferrin Iron Receptor", "Cell-surface iron-uptake receptor supporting heme synthesis and proliferation."),
"SLC3A2": ("surface", "CD98 Amino-Acid Transporter", "Plasma-membrane heavy chain importing essential amino acids for mTOR growth."),
"CD63": ("surface", "CD63 Tetraspanin Membrane Coat", "Cell-surface & endolysosomal tetraspanin scaffold remodeled during differentiation."),
"GP1BB": ("surface", "Glycoprotein Ib-Beta Receptor", "Myeloid/megakaryocytic lineage surface membrane glycoprotein."),
"MIF": ("surface", "MIF Secreted Cytokine Signal", "Secreted pro-survival cytokine modulated upon growth-factor or MYC blockade."),
"HNRNPA1": ("nucleus", "hnRNP-A1 Splicing Regulator", "MYC-regulated nuclear RNA-binding protein controlling alternative splicing."),
"HNRNPH1": ("nucleus", "hnRNP-H1 Nuclear RNA Splicer", "Nuclear G-quadruplex RNA splicing factor."),
"EGR1": ("nucleus", "EGR1 Immediate-Early Factor", "Nuclear zinc-finger transcription factor directly tracking MAPK/ERK signaling."),
"NFE2L1": ("nucleus", "NRF1 Proteasome Stress Sensor", "ER-tethered nuclear transcription factor maintaining proteasome homeostasis."),
"HMGA2": ("nucleus", "HMGA2 Chromatin Architect", "Architectural nuclear DNA-bending protein sustaining proliferative plasticity."),
"H2AZ1": ("nucleus", "Variant Histone H2A.Z", "Promoter-poising nuclear histone variant remodeled during transcriptional shifts."),
"H1-3": ("nucleus", "Linker Histone H1.3", "Replication-coupled nuclear chromatin compaction histone."),
"H1-5": ("nucleus", "Linker Histone H1.5", "Nuclear heterochromatin linker histone downregulated as division slows."),
"RANBP1": ("nucleus", "Ran-GTP Nuclear Transport", "Regulates nuclear-pore cargo import/export in proliferating cells."),
"ANP32B": ("nucleus", "Histone Chaperone ANP32B", "Nuclear chromatin assembly & mRNA export regulator."),
"ACTB": ("cytoplasm", "Beta-Actin Cytoskeleton", "Essential contractile microfilament driving cell shape and motility."),
"GAPDH": ("cytoplasm", "GAPDH Glycolytic Dehydrogenase", "Central cytoplasmic glycolysis enzyme coupling ATP production to redox state."),
"EEF2": ("cytoplasm", "Elongation Factor eEF2", "Ribosomal translocation GTPase driving polypeptide chain elongation."),
"EEF1A1": ("cytoplasm", "Elongation Factor eEF1A1", "Delivers aminoacyl-tRNAs to the ribosome during translation."),
"VDAC1": ("cytoplasm", "Mitochondrial Porin VDAC1", "Outer mitochondrial membrane metabolite and ATP channel."),
"PHB2": ("cytoplasm", "Prohibitin-2 Inner Mito Scaffold", "Stabilizes mitochondrial respiratory cristae and mitophagy signaling."),
"FABP5": ("cytoplasm", "Fatty-Acid Binding Protein 5", "Intracellular lipid chaperone fueling membrane synthesis."),
"S100A11": ("cytoplasm", "S100A11 Calcium Membrane Linker", "Calcium-sensing cytoskeletal & plasma-membrane repair adapter."),
"MT-CO1": ("cytoplasm", "Cytochrome c Oxidase I (CO1)", "Catalytic mitochondrial Complex IV respiratory subunit."),
"MT-CO3": ("cytoplasm", "Cytochrome c Oxidase III (CO3)", "Core mitochondrial Complex IV electron-transport subunit."),
"MT-ATP6": ("cytoplasm", "Mitochondrial ATP Synthase 6", "Proton-channel subunit driving mitochondrial ATP synthesis."),
"MT-CYB": ("cytoplasm", "Mitochondrial Cytochrome b", "Central Complex III electron-transfer subunit inside mitochondria."),
"MT-ND4": ("cytoplasm", "Mitochondrial Complex I (ND4)", "Proton-pumping NADH dehydrogenase subunit inside mitochondria."),
"MT-ND6": ("cytoplasm", "Mitochondrial Complex I (ND6)", "Essential membrane subunit of mitochondrial respiratory Complex I."),
}
_LOC_CODE_MAP = {"n": "nucleus", "s": "surface", "c": "cytoplasm"}
def _load_gene_catalog() -> dict[str, list[str]]:
"""Loads the 19,881-gene HGNC/HPA compartment & protein-name lookup catalog."""
here = Path(__file__).resolve().parent
for candidate in (here / "gene_catalog.json", here.parent / "data" / "gene_catalog.json"):
if candidate.is_file():
try:
with open(candidate, encoding="utf-8") as f:
return json.load(f)
except Exception:
return {}
return {}
GENE_CATALOG: dict[str, list[str]] = _load_gene_catalog()
def _infer_fallback_annotation(gene: str, partners: list[str]) -> tuple[str, str, str]:
"""Provides biologically grounded compartment & protein name for every HGNC symbol."""
partner_str = f" Interacts with {', '.join(partners[:4])}." if partners else ""
cat = GENE_CATALOG.get(gene)
if cat and len(cat) >= 2:
loc = _LOC_CODE_MAP.get(cat[0], "cytoplasm")
short_name = cat[1]
return (loc, short_name, f"{short_name} ({gene}).{partner_str}")
if gene.startswith(("RPL", "RPS")):
return ("cytoplasm", f"Ribosomal Subunit ({gene})", f"Cytoplasmic protein-synthesis ribosome component.{partner_str}")
if gene.startswith("MRPL") or gene.startswith("MRPS") or gene.startswith("MT-"):
return ("cytoplasm", f"Mitochondrial Energy Subunit ({gene})", f"Mitochondrial respiratory or translation subunit.{partner_str}")
if gene.startswith(("H1-", "H2A", "H2B", "H3-", "H4", "HIST", "ZNF", "POLR", "SNRP", "SF3", "SRSF", "HNRNP")):
return ("nucleus", f"Nuclear Splicing / Chromatin ({gene})", f"Nuclear RNA processing or chromatin regulator.{partner_str}")
if gene.startswith(("SLC", "CD", "HLA-", "ITG", "EPH", "FZD", "GPR", "TMEM", "ATP1", "AQP")):
return ("surface", f"Membrane Channel / Receptor ({gene})", f"Cell-surface transmembrane transport or signaling protein.{partner_str}")
if gene.startswith(("HSP", "DNAJ", "BAG")):
return ("cytoplasm", f"Protein-Folding Chaperone ({gene})", f"Cellular stress-response folding chaperone.{partner_str}")
return ("cytoplasm", f"{gene} Cellular Factor", f"Differentially expressed protein-coding gene ({gene}).{partner_str}")
class ExpressionDecoder(nn.Module):
"""Dataset-specific Stage 2 MLP reconstructing continuous residual deltas."""
def __init__(self, input_dim: int, hidden_dims: list[int], max_exp_arg: float = 88.0):
super().__init__()
self.input_dim = input_dim
self.max_exp_arg = max_exp_arg
self.bn0 = nn.BatchNorm1d(input_dim + 1)
layers: list[nn.Module] = [self.bn0]
d = input_dim + 1
for h in hidden_dims:
layers += [nn.Linear(d, h), nn.ReLU()]
d = h
self.mlp = nn.Sequential(*layers, nn.Linear(d, 1))
def forward(self, features: torch.Tensor, control_expression: torch.Tensor) -> torch.Tensor:
eps = 1e-6
ctrl = control_expression.view(-1, 1)
x = self.mlp(torch.cat([features, ctrl], dim=1))
ctrl_safe = ctrl - torch.where(x >= 0, eps, -eps)
exp_term = (x / ctrl_safe).clamp(max=self.max_exp_arg)
neg_delta = ctrl_safe * (torch.exp(exp_term) - 1.0)
return torch.where(x > 0, x, neg_delta) + eps
def parse_smiles_2d(smiles: str, new_atom_start: int | None = None) -> dict[str, Any]:
"""Validates SMILES, canonicalizes via RDKit, and computes 3D ETKDGv3/MMFF94 coordinates."""
cleaned = smiles.strip()
if not SMILES_ALLOW_RE.match(cleaned):
raise ValueError("Invalid characters or length in SMILES string.")
mol = Chem.MolFromSmiles(cleaned)
if mol is None or mol.GetNumAtoms() == 0 or mol.GetNumAtoms() > 120:
raise ValueError("Could not parse chemical SMILES into a valid molecule.")
canonical = Chem.MolToSmiles(mol, canonical=True)
mol_base = Chem.MolFromSmiles(canonical)
assert mol_base is not None
rdDepictor.Compute2DCoords(mol_base)
conf_2d = mol_base.GetConformer()
coords_3d: list[tuple[float, float, float]] = []
try:
mol_h = Chem.AddHs(Chem.MolFromSmiles(canonical))
params = AllChem.ETKDGv3()
params.randomSeed = 42
status = AllChem.EmbedMolecule(mol_h, params)
if status == 0:
AllChem.MMFFOptimizeMolecule(mol_h, maxIters=100)
mol_3d = Chem.RemoveHs(mol_h)
conf_3d = mol_3d.GetConformer()
for idx in range(mol_3d.GetNumAtoms()):
p = conf_3d.GetAtomPosition(idx)
coords_3d.append((float(p.x), float(p.y), float(p.z)))
except Exception:
coords_3d = []
if len(coords_3d) != mol_base.GetNumAtoms():
coords_3d = []
for idx in range(mol_base.GetNumAtoms()):
p = conf_2d.GetAtomPosition(idx)
coords_3d.append((float(p.x), float(-p.y), math.sin(idx * 0.9) * 0.25))
arr = np.array(coords_3d, dtype=np.float64)
arr -= arr.mean(axis=0, keepdims=True)
max_r = float(np.max(np.linalg.norm(arr, axis=1))) if len(arr) > 1 else 1.0
scale = 1.85 / max(1.0, max_r)
arr *= scale
nodes = []
for idx, atom in enumerate(mol_base.GetAtoms()):
p2 = conf_2d.GetAtomPosition(idx)
nodes.append({
"id": idx,
"elem": atom.GetSymbol(),
"x": round(float(arr[idx, 0]), 4),
"y": round(float(arr[idx, 1]), 4),
"z": round(float(arr[idx, 2]), 4),
"x2d": round(float(p2.x), 4),
"y2d": round(float(-p2.y), 4),
"aromatic": bool(atom.GetIsAromatic()),
"isNew": bool(new_atom_start is not None and idx >= new_atom_start),
})
edges = []
for bond in mol_base.GetBonds():
btype = bond.GetBondTypeAsDouble()
edges.append({
"a": bond.GetBeginAtomIdx(),
"b": bond.GetEndAtomIdx(),
"order": 2 if btype == 2.0 else (3 if btype == 3.0 else 1),
"aromatic": bool(bond.GetIsAromatic()),
})
return {
"mode": "drug",
"canonical_smiles": canonical,
"num_atoms": mol_base.GetNumHeavyAtoms(),
"mol_weight": round(float(Descriptors.MolWt(mol_base)), 1),
"num_rings": int(rdMolDescriptors.CalcNumRings(mol_base)),
"nodes": nodes,
"edges": edges,
}
class CellGemmaEngine:
"""Manages single-cell controls, 3D molecular/network inputs, and live CellGemma inference."""
def __init__(self, model_id: str = DEFAULT_MODEL_ID):
self.model_id = model_id
self.hf_token = os.environ.get("HF_TOKEN") or None
self.device, self.dtype = self._select_device()
self._model: AutoModelForCausalLM | None = None
self._tokenizer: AutoTokenizer | None = None
self._model_lock = threading.Lock()
self._load_lock = threading.Lock()
self.model_load_state: str = "not_loaded"
self.model_load_started_at: float = 0.0
self.model_load_error: str = ""
self.controls_all: dict[str, Any] = {}
self.kg: dict[str, str] = {}
self.decoders: dict[str, tuple[ExpressionDecoder, dict[str, float]]] = {}
self.genes_by_ds: dict[str, list[str]] = {}
self.gene_to_idx_by_ds: dict[str, dict[str, int]] = {}
self._load_lightweight_assets()
# On Hugging Face ZeroGPU, weights MUST be loaded and moved .to("cuda")
# synchronously on the main thread before gr.Blocks.launch() packs tensors.
if IS_ZEROGPU:
self.ensure_model_loaded()
@staticmethod
def _select_device() -> tuple[str, torch.dtype]:
if IS_ZEROGPU or torch.cuda.is_available():
return "cuda", torch.bfloat16
if torch.backends.mps.is_available():
return "mps", torch.bfloat16
default_threads = min(32, max(4, (os.cpu_count() or 8) // 2))
cpu_threads = int(os.environ.get("CELLGEMMA_CPU_THREADS", str(default_threads)))
torch.set_num_threads(cpu_threads)
return "cpu", torch.float32
def _download_json(self, filename: str) -> Any:
path = hf_hub_download(self.model_id, filename, token=self.hf_token)
with open(path, encoding="utf-8") as f:
return json.load(f)
def _load_lightweight_assets(self) -> None:
"""Loads controls_sample.json, kg_sentences.json, and Stage 2 decoders."""
self.controls_all = self._download_json("controls_sample.json")
self.kg = self._download_json("kg_sentences.json")
for ds in ("tahoe", "k562"):
cfg = self._download_json(f"decoders/{ds}/config.json")
dec = ExpressionDecoder(cfg["input_dim"], cfg["hidden_dims"])
weights_path = hf_hub_download(
self.model_id, f"decoders/{ds}/model.safetensors", token=self.hf_token
)
dec.load_state_dict(safetensors.torch.load_file(weights_path))
dec.eval()
raw_deltas = self._download_json(f"decoders/{ds}/mean_delta_global.json")
mean_deltas = {k.upper(): float(v) for k, v in raw_deltas.items()}
self.decoders[ds] = (dec, mean_deltas)
genes = [g.upper() for g in self.controls_all[ds]["genes"]]
self.genes_by_ds[ds] = genes
self.gene_to_idx_by_ds[ds] = {g: i for i, g in enumerate(genes)}
def get_cell_baseline_summary(self, dataset: str, cell_idx: int = 0) -> dict[str, Any]:
"""Returns baseline expression facts for a single untreated control cell."""
if dataset not in ("tahoe", "k562"):
raise ValueError("Unknown dataset.")
cells = self.controls_all[dataset]["cells"]
idx = max(0, min(len(cells) - 1, int(cell_idx)))
vec = np.array(cells[idx]["expression"], dtype=np.float32)
genes = self.genes_by_ds[dataset]
nz_count = int(np.sum(vec > 0))
top_order = np.argsort(-vec)[:8]
top_list = [
{"gene": genes[int(i)], "expr": round(float(vec[int(i)]), 2)}
for i in top_order
if vec[int(i)] > 0
]
cell_line = "A549 Lung Carcinoma" if dataset == "tahoe" else "K562 Chronic Myeloid Leukemia"
return {
"dataset": dataset,
"cell_idx": idx,
"cell_id": cells[idx]["cell_id"],
"cell_line": cell_line,
"total_genes": len(genes),
"expressed_genes": nz_count,
"top_baseline_genes": top_list,
}
def get_gene_graph(self, gene: str, max_spokes: int = 10) -> dict[str, Any]:
"""Extracts STRING functional interaction spokes in 3D spherical coordinates."""
sym = gene.strip().upper()
if not GENE_ALLOW_RE.match(sym) or sym not in self.kg:
raise ValueError(f"Unknown human gene symbol: {sym}")
lines = self.kg[sym].strip().splitlines()
partners: list[str] = []
for line in lines[1:]:
parts = line.split()
if len(parts) >= 3 and parts[1] == "functional":
other = parts[2].upper()
if other != sym and other not in partners:
partners.append(other)
if len(partners) >= max_spokes:
break
nodes = [{"id": 0, "elem": sym, "x": 0.0, "y": 0.0, "z": 0.0, "isHub": True}]
edges = []
n = max(1, len(partners))
golden = math.pi * (3.0 - math.sqrt(5.0))
for idx, p_sym in enumerate(partners):
y_norm = 1.0 - (2.0 * (idx + 0.5) / n)
rad_xy = math.sqrt(max(0.0, 1.0 - y_norm * y_norm))
theta = golden * idx
r = 1.65
nodes.append({
"id": idx + 1,
"elem": p_sym,
"x": round(math.cos(theta) * rad_xy * r, 4),
"y": round(y_norm * r * 0.85, 4),
"z": round(math.sin(theta) * rad_xy * r, 4),
"isSpoke": True,
})
edges.append({"a": 0, "b": idx + 1, "order": 1, "dashed": True})
return {
"mode": "crispr",
"gene": sym,
"total_edges": max(0, len(lines) - 1),
"partners": partners,
"nodes": nodes,
"edges": edges,
}
def start_background_preload(self) -> None:
"""Pre-warms CellGemma weights in the background on local GPU / MPS."""
if IS_ZEROGPU or self.model_load_state in ("loading", "ready"):
return
threading.Thread(target=self.ensure_model_loaded, daemon=True).start()
def get_model_status(self) -> dict[str, Any]:
elapsed = (
round(max(0.0, time.perf_counter() - self.model_load_started_at), 1)
if self.model_load_state == "loading" and self.model_load_started_at > 0
else 0.0
)
return {
"device": self.device,
"dtype": str(self.dtype).replace("torch.", ""),
"state": self.model_load_state,
"elapsed_s": elapsed,
"error": self.model_load_error,
}
def ensure_model_loaded(self) -> None:
"""Loads the Gemma4ForCausalLM checkpoint onto CUDA (ZeroGPU-safe), MPS, or CPU."""
if self._model is not None and self._tokenizer is not None:
self.model_load_state = "ready"
return
with self._load_lock:
if self._model is not None and self._tokenizer is not None:
self.model_load_state = "ready"
return
self.model_load_state = "loading"
self.model_load_started_at = time.perf_counter()
self.model_load_error = ""
try:
self._tokenizer = AutoTokenizer.from_pretrained(
self.model_id, token=self.hf_token
)
if self.device == "mps":
try:
model = AutoModelForCausalLM.from_pretrained(
self.model_id,
dtype=self.dtype,
low_cpu_mem_usage=True,
attn_implementation="eager",
token=self.hf_token,
).to("mps")
except Exception:
self.dtype = torch.float16
model = AutoModelForCausalLM.from_pretrained(
self.model_id,
dtype=self.dtype,
low_cpu_mem_usage=True,
attn_implementation="eager",
token=self.hf_token,
).to("mps")
elif self.device == "cuda":
# Move weights directly onto CUDA for ZeroGPU tensor packing
model = AutoModelForCausalLM.from_pretrained(
self.model_id,
dtype=self.dtype,
low_cpu_mem_usage=True,
token=self.hf_token,
).to("cuda")
else:
model = AutoModelForCausalLM.from_pretrained(
self.model_id,
dtype=self.dtype,
low_cpu_mem_usage=True,
token=self.hf_token,
)
self._model = model.eval()
self.model_load_state = "ready"
except Exception as exc:
self.model_load_state = "error"
self.model_load_error = str(exc)
raise
def prepare_cell_and_prompt(
self,
dataset: str,
cell_idx: int,
kind: str,
drug_name: str = "",
smiles: str = "",
concentration_um: float = 0.5,
gene: str = "",
) -> tuple[np.ndarray, np.ndarray, str, dict[str, Any]]:
"""Builds Stage 1 prompt and returns (ctrl_expr, baseline, prompt, input_viz)."""
if dataset not in ("tahoe", "k562"):
raise ValueError("Dataset must be 'tahoe' or 'k562'.")
cells = self.controls_all[dataset]["cells"]
if not (0 <= cell_idx < len(cells)):
raise ValueError(f"cell_idx must be between 0 and {len(cells) - 1}.")
genes = self.genes_by_ds[dataset]
_, mean_deltas = self.decoders[dataset]
ctrl_expr = np.array(cells[cell_idx]["expression"], dtype=np.float32)
mean_vec = np.array([mean_deltas.get(g, 0.0) for g in genes], dtype=np.float32)
baseline = np.maximum(0.0, ctrl_expr + mean_vec)
if kind == "drug":
mol_info = parse_smiles_2d(smiles)
safe_name = re.sub(r"[^A-Za-z0-9 \-()_/+]", "", drug_name or "Custom Compound")[:60].strip()
perturbation_text = (
f"Drug name: {safe_name}\n"
f"Drug SMILES: {mol_info['canonical_smiles']}\n"
f"Concentration: {concentration_um} uM"
)
viz = mol_info
elif kind == "crispr":
sym = gene.strip().upper()
viz = self.get_gene_graph(sym)
kg_sent = self.kg[sym].strip()
perturbation_text = f"Gene knockdown: {kg_sent}"
else:
raise ValueError("kind must be 'drug' or 'crispr'.")
def top_k_genes(vec: np.ndarray, k: int = 1000) -> str:
order = np.argsort(vec)[::-1]
ranked = [genes[i] for i in order if vec[i] > 0][:k]
return " ".join(ranked)
prompt = (
f"{PREAMBLE}\n\n{perturbation_text}\n\n"
f"Source: {top_k_genes(ctrl_expr)}\n\n"
f"Mean Global prediction: {top_k_genes(baseline)}\n"
"Target: "
)
return ctrl_expr, baseline, prompt, viz
def _build_gene_entry(
self,
signed_sym: str,
g: str,
emit_order: int,
dir_rank: int,
ctrl_val: float,
base_val: float,
pred_val: float,
lfc_val: float,
res_val: float,
) -> dict[str, Any]:
partners: list[str] = []
if g in self.kg:
for ln in self.kg[g].splitlines()[1:6]:
ps = ln.split()
if len(ps) >= 3:
partners.append(ps[2])
if g in GENE_ANNOTATIONS:
loc, nick, desc = GENE_ANNOTATIONS[g]
else:
loc, nick, desc = _infer_fallback_annotation(g, partners)
return {
"rank": emit_order,
"dir_rank": dir_rank,
"sym": signed_sym,
"gene": g,
"loc": loc,
"ctrl_expr": round(ctrl_val, 3),
"base_expr": round(base_val, 3),
"pred_expr": round(pred_val, 3),
"lfc": round(lfc_val, 4),
"residual": round(res_val, 4),
"mean_shift": round(base_val - ctrl_val, 4),
"nick": nick,
"desc": desc,
"partners": partners[:4],
"annotated": g in GENE_ANNOTATIONS,
}
def reconstruct_and_summarize(
self,
dataset: str,
cell_idx: int,
raw_text: str,
ctrl_expr: np.ndarray,
baseline: np.ndarray,
top_n_genes: int = 48,
is_truncated: bool = False,
include_all_genes: bool = False,
) -> dict[str, Any]:
"""Runs Stage 2 ExpressionDecoder on a single cell with balanced +UP and -DOWN rankings."""
g2i = self.gene_to_idx_by_ds[dataset]
decoder, _ = self.decoders[dataset]
up: list[str] = []
down: list[str] = []
interleaved: list[tuple[str, str, int]] = []
seen: set[str] = set()
for tok in raw_text.split():
if len(tok) < 2 or tok[0] not in ("+", "-"):
continue
sym = tok[1:].upper()
if sym in g2i and sym not in seen:
seen.add(sym)
if tok[0] == "+":
up.append(sym)
interleaved.append(("+" + sym, sym, len(up)))
else:
down.append(sym)
interleaved.append(("-" + sym, sym, len(down)))
residual_vec = np.zeros_like(baseline)
if up or down:
task_oh = [0.0] * 7 + [1.0]
eff_up = float(max(len(up), 550) if is_truncated else len(up))
eff_dn = float(max(len(down), 550) if is_truncated else len(down))
feats: list[list[float]] = []
ctrl_vals: list[float] = []
idxs: list[int] = []
for is_up, g_list in ((1.0, up), (0.0, down)):
for rank, g in enumerate(g_list):
idx = g2i[g]
feats.append([is_up, float(rank), eff_up, eff_dn] + task_oh)
ctrl_vals.append(float(baseline[idx]))
idxs.append(idx)
with torch.no_grad():
deltas = decoder(
torch.tensor(feats, dtype=torch.float32),
torch.tensor(ctrl_vals, dtype=torch.float32),
)
residual_vec[idxs] = deltas.cpu().numpy().flatten()
predicted_expr = baseline + residual_vec
predicted_lfc = predicted_expr - ctrl_expr
all_entries: list[dict[str, Any]] = []
for emit_idx, (signed_sym, g, dir_rank) in enumerate(interleaved):
idx = g2i[g]
all_entries.append(
self._build_gene_entry(
signed_sym=signed_sym,
g=g,
emit_order=emit_idx + 1,
dir_rank=dir_rank,
ctrl_val=float(ctrl_expr[idx]),
base_val=float(baseline[idx]),
pred_val=float(predicted_expr[idx]),
lfc_val=float(predicted_lfc[idx]),
res_val=float(residual_vec[idx]),
)
)
up_entries = sorted(
[e for e in all_entries if e["sym"].startswith("+")],
key=lambda e: (-abs(e["residual"]), e["dir_rank"]),
)
down_entries = sorted(
[e for e in all_entries if e["sym"].startswith("-")],
key=lambda e: (-abs(e["residual"]), e["dir_rank"]),
)
half = max(12, top_n_genes // 2)
combined = sorted(
up_entries[:half] + down_entries[:half],
key=lambda e: -abs(e["residual"]),
)[:top_n_genes]
verdict = self._synthesize_verdict(
dataset=dataset,
up_entries=up_entries,
down_entries=down_entries,
count_up=len(up),
count_down=len(down),
)
cell_meta = self.get_cell_baseline_summary(dataset, cell_idx)
out_payload: dict[str, Any] = {
"dataset": dataset,
"cell_idx": cell_idx,
"cell_id": cell_meta["cell_id"],
"cell_line": cell_meta["cell_line"],
"total_genes": cell_meta["total_genes"],
"count_up": len(up),
"count_down": len(down),
"verdict": verdict,
"top_up": up_entries[:12],
"top_down": down_entries[:12],
"gene_stars": combined,
}
if include_all_genes or not is_truncated:
out_payload["all_genes"] = up_entries + down_entries
return out_payload
def _synthesize_verdict(
self,
dataset: str,
up_entries: list[dict[str, Any]],
down_entries: list[dict[str, Any]],
count_up: int,
count_down: int,
) -> dict[str, Any]:
"""Builds a plain-English summary and pins signature genes for graphic callouts."""
up_syms = {e["gene"] for e in up_entries[:15]}
dn_syms = {e["gene"] for e in down_entries[:15]}
lead_up = ", ".join(f"{e['sym']} ({e['nick']})" for e in up_entries[:2]) or "none"
lead_dn = ", ".join(f"{e['sym']} ({e['nick']})" for e in down_entries[:2]) or "none"
def _first_match(entries: list[dict[str, Any]], candidates: set[str], limit: int = 1) -> list[str]:
found = [e["sym"] for e in entries[:15] if e["gene"] in candidates]
return found[:limit]
if {"GYPB", "HBZ", "ALAS2"} & up_syms and ({"C1QBP", "SRM", "RRP1B", "WDR43"} & dn_syms):
return {
"badge": "Growth Engine Shut Down 路 Red-Cell Genes On",
"headline": "Leukemia Cell Shuts Down Ribosome Factories and Switches On Red-Blood-Cell Genes",
"summary": (
f"In this K562 cell, muting MYC collapses protein & polyamine growth factories "
f"({lead_dn}) while turning up oxygen-carrying globin and red-cell surface genes ({lead_up})."
),
"featured_up": _first_match(up_entries, {"GYPB", "HBZ", "ALAS2", "HBG2"}),
"featured_down": _first_match(down_entries, {"C1QBP", "SRM", "WDR43", "RRP1B"}),
}
if {"SLC7A8", "LGALS1", "MDK"} & up_syms and ({"NOLC1", "MRTO4"} & dn_syms):
return {
"badge": "DNA Silencing Lifted 路 Surface Proteins Up",
"headline": "Lifting DNA Methylation Turns Up Surface Transporters & Slows Nucleolar Assembly",
"summary": (
f"In this K562 cell, muting DNMT1 turns up previously quiet membrane & secreted genes "
f"({lead_up}) while dialing down nucleolar ribosome builders ({lead_dn})."
),
"featured_up": _first_match(up_entries, {"SLC7A8", "LGALS1", "MDK"}),
"featured_down": _first_match(down_entries, {"NOLC1", "MRTO4"}),
}
if {"CALR", "H1-0", "H3-3B"} <= up_syms and "MDM2" in dn_syms:
return {
"badge": "Chromatin Unpacked 路 Surface Flag Raised",
"headline": "Unpacked DNA Raises 'Eat-Me' Surface Flag (+CALR) and Lowers p53 Brake (-MDM2)",
"summary": (
f"In this A549 lung-cancer cell, Panobinostat turns up chromatin histones and surface chaperone +CALR "
f"while turning down tumor survival regulators ({lead_dn})."
),
"featured_up": ["+CALR"],
"featured_down": ["-MDM2"],
}
if "LRP1" in dn_syms and ({"PLOD2", "VIM"} & up_syms):
return {
"badge": "Invasion Receptor Down 路 Cytoskeleton Shifted",
"headline": "Kinase Blockade Turns Down Invasion Receptors (-LRP1) and Remodels Filaments",
"summary": (
f"In this A549 lung-cancer cell, blocking SRC/ABL/EPHA2 kinases lowers migration & growth "
f"receptors ({lead_dn}) while shifting structural & chaperone genes ({lead_up})."
),
"featured_up": _first_match(up_entries, {"VIM", "PLOD2"}),
"featured_down": ["-LRP1"],
}
if "TXNRD1" in up_syms and "ARHGAP26" in dn_syms:
return {
"badge": "MAPK Relay Cut 路 Stress Defense Up",
"headline": "Blocking MEK1/2 Lowers Motility Signaling and Turns Up Antioxidant Defense (+TXNRD1)",
"summary": (
f"In this A549 cell, cutting the MEK growth relay dials down motility & MAPK feedback genes "
f"({lead_dn}) while boosting redox & membrane stabilizers ({lead_up})."
),
"featured_up": ["+TXNRD1"],
"featured_down": ["-ARHGAP26"],
}
cell_label = "A549 lung-cancer cell" if dataset == "tahoe" else "K562 leukemia cell"
return {
"badge": f"{count_up + count_down} Gene Knobs Shifted",
"headline": f"CellGemma Predicted {count_up} Upregulated (+) and {count_down} Downregulated (-) Genes",
"summary": f"Inside this single {cell_label}, top increases are {lead_up} and top decreases are {lead_dn}.",
"featured_up": [e["sym"] for e in up_entries[:1]],
"featured_down": [e["sym"] for e in down_entries[:1]],
}
def stream_predict(
self,
dataset: str,
cell_idx: int,
kind: str,
drug_name: str = "",
smiles: str = "",
concentration_um: float = 0.5,
gene: str = "",
max_new_tokens: int = 180,
temperature: float = 0.0,
) -> Iterator[dict[str, Any]]:
"""Streams live heartbeats, Stage 1 gene tokens, and Stage 2 single-cell reconstructions."""
ctrl_expr, baseline, prompt, input_viz = self.prepare_cell_and_prompt(
dataset=dataset,
cell_idx=cell_idx,
kind=kind,
drug_name=drug_name,
smiles=smiles,
concentration_um=concentration_um,
gene=gene,
)
hw_map = {"mps": "Apple Metal GPU (MPS)", "cuda": "NVIDIA CUDA GPU", "cpu": "Multi-Core CPU"}
hw_label = hw_map.get(self.device, self.device.upper())
dtype_label = str(self.dtype).replace("torch.", "")
if self._model is None or self._tokenizer is None:
load_t0 = time.perf_counter()
if IS_ZEROGPU:
self.ensure_model_loaded()
else:
self.start_background_preload()
while self.model_load_state == "loading" or (
self.model_load_state == "not_loaded" and self._model is None
):
elapsed_load = round(time.perf_counter() - load_t0, 1)
yield {
"type": "heartbeat",
"step": 1,
"phase": "loading_model",
"device": hw_label,
"elapsed_s": elapsed_load,
"message": f"Loading CellGemma E4B weights onto {hw_label} ({dtype_label})... {elapsed_load:.1f}s",
"input_viz": input_viz,
}
time.sleep(0.4)
if self.model_load_state == "error" or self._model is None:
raise RuntimeError(self.model_load_error or "Failed to load CellGemma E4B weights.")
assert self._model is not None and self._tokenizer is not None
with self._model_lock:
formatted = f"<bos><|turn>user\n{prompt}<turn|>\n<|turn>model\n"
inputs = self._tokenizer(
formatted, return_tensors="pt", add_special_tokens=False
).to(self.device)
prompt_tok_len = int(inputs["input_ids"].shape[1])
eot_id = self._tokenizer.convert_tokens_to_ids("<turn|>")
streamer = TextIteratorStreamer(
self._tokenizer, skip_prompt=True, skip_special_tokens=True
)
capped_max = max(32, min(1024, int(max_new_tokens)))
temp_val = max(0.0, min(1.5, float(temperature)))
gen_kwargs: dict[str, Any] = dict(
**inputs,
streamer=streamer,
max_new_tokens=capped_max,
do_sample=temp_val > 0.01,
pad_token_id=self._tokenizer.pad_token_id,
eos_token_id=[self._tokenizer.eos_token_id, eot_id],
)
if temp_val > 0.01:
gen_kwargs["temperature"] = temp_val
chunk_q: queue.Queue[str | None] = queue.Queue()
gen_error: list[Exception] = []
def _run_gen() -> None:
try:
with torch.no_grad():
self._model.generate(**gen_kwargs)
except Exception as exc: # pragma: no cover
gen_error.append(exc)
finally:
try:
streamer.end()
except Exception:
pass
def _pump_streamer() -> None:
try:
for piece in streamer:
if piece:
chunk_q.put(piece)
finally:
chunk_q.put(None)
start_t = time.perf_counter()
worker = threading.Thread(target=_run_gen, daemon=True)
pumper = threading.Thread(target=_pump_streamer, daemon=True)
worker.start()
pumper.start()
yield {
"type": "started",
"step": 2,
"phase": "encoding_cell",
"device": hw_label,
"prompt_tokens": prompt_tok_len,
"max_new_tokens": capped_max,
"input_viz": input_viz,
"message": f"Encoding Single Cell #{cell_idx} ({prompt_tok_len:,} tokens) on {hw_label}...",
}
accumulated_chunks: list[str] = []
last_reconstruct_tokens = 0
first_token_seen = False
while True:
try:
piece = chunk_q.get(timeout=0.4)
except queue.Empty:
elapsed = round(time.perf_counter() - start_t, 1)
if not first_token_seen:
yield {
"type": "heartbeat",
"step": 2,
"phase": "encoding_cell",
"device": hw_label,
"prompt_tokens": prompt_tok_len,
"elapsed_s": elapsed,
"message": f"Reading 1,000 baseline cell genes & perturbation ({prompt_tok_len:,} tokens)... {elapsed:.1f}s",
}
continue
if piece is None:
break
first_token_seen = True
accumulated_chunks.append(piece)
full_text = "".join(accumulated_chunks)
words = full_text.split()
if not full_text.endswith((" ", "\n")) and words:
complete_words = words[:-1]
else:
complete_words = words
toks = [t for t in complete_words if len(t) >= 2 and t[0] in ("+", "-")]
elapsed = max(1e-3, time.perf_counter() - start_t)
if len(toks) >= 1 and (last_reconstruct_tokens == 0 or len(toks) - last_reconstruct_tokens >= 2):
last_reconstruct_tokens = len(toks)
partial_state = self.reconstruct_and_summarize(
dataset=dataset,
cell_idx=cell_idx,
raw_text=" ".join(toks),
ctrl_expr=ctrl_expr,
baseline=baseline,
is_truncated=True,
)
latest_sym = toks[-1]
bare_latest = latest_sym[1:].upper()
latest_nick = GENE_ANNOTATIONS.get(bare_latest, ("cytoplasm", "Gene Shift", ""))[1]
yield {
"type": "partial",
"step": 3,
"phase": "streaming_genes",
"device": hw_label,
"elapsed_s": round(elapsed, 2),
"tok_per_s": round(len(toks) / elapsed, 1),
"gene_count": len(toks),
"latest_gene": {"sym": latest_sym, "nick": latest_nick},
"recent_tokens": toks[-8:],
"state": partial_state,
}
worker.join()
pumper.join()
if gen_error:
raise RuntimeError(f"Model generation failed on {hw_label}: {gen_error[0]}") from gen_error[0]
total_elapsed = max(1e-3, time.perf_counter() - start_t)
final_text = "".join(accumulated_chunks).strip()
gen_subword_count = len(self._tokenizer.encode(final_text, add_special_tokens=False))
hit_cap = gen_subword_count >= int(capped_max * 0.85) and int(capped_max) < 2048
final_state = self.reconstruct_and_summarize(
dataset=dataset,
cell_idx=cell_idx,
raw_text=final_text,
ctrl_expr=ctrl_expr,
baseline=baseline,
is_truncated=hit_cap,
include_all_genes=True,
)
final_toks = final_state["count_up"] + final_state["count_down"]
yield {
"type": "complete",
"step": 4,
"phase": "complete",
"device": hw_label,
"elapsed_s": round(total_elapsed, 2),
"tok_per_s": round(max(1, final_toks) / total_elapsed, 1),
"prompt_tokens": prompt_tok_len,
"prompt": prompt,
"raw_text": final_text,
"input_viz": input_viz,
"state": final_state,
}
|