Morph2Mol-demo / runtime.py
zchx's picture
update model name
4af13ea verified
Raw History Blame Contribute Delete
6.15 kB
"""Same Morph2Mol operators as the released CLI, with persistent ZeroGPU models.
No CUDA subprocesses. Small-ROI segmentation preserves upstream scale/blue-channel protocol.
"""
import os
from pathlib import Path
import numpy as np
import torch
from huggingface_hub import snapshot_download, hf_hub_download
from predict.model import Morph2Mol
from predict.segment import load_model, segment_window, polygons_from_labels, MPP_REF, MIN_AREA_PX
from predict.inputs import open_slide
from predict.covariates import geometry
from predict.spatial_context import TargetContextPlan, TargetContextDataset, commit_target_rows
from morph2mol.release import Release
from morph2mol.retrieval import ReferenceBank
from morph2mol.gate_rules import select_gate, validate_gate_genes
from morph2mol.gate import apply_gate
from validation import MAX_CELLS
from PIL import Image
class Runtime:
def __init__(self):
folder = os.environ.get('MORPH2MOL_RELEASE','/tmp/morph2mol-model')
snapshot_download('zchx/Morph2Mol', local_dir=folder, revision=os.environ['MORPH2MOL_REVISION'])
hf_hub_download('MahmoodLab/UNI2-h','pytorch_model.bin',local_dir=f'{folder}/uni2h')
self.release = Release(folder)
# Startup CUDA placement is supported by ZeroGPU emulation.
self.model = Morph2Mol(self.release,'cuda','bf16')
self.segmenter = load_model(gpu=True)
self.bank = ReferenceBank(self.release.paths['bank'],device='cuda')
validate_gate_genes(self.release.gate,self.model.genes.tolist())
def segment(self, image, mpp, destination):
width,height=image.size
# Mirror CLI's single window with a 128-pixel zero context border.
rgb=Image.new('RGB',(width+256,height+256),'black');rgb.paste(image,(128,128))
scale=mpp/MPP_REF
sw,sh=max(32,round(rgb.width*scale)),max(32,round(rgb.height*scale))
labels=segment_window(self.segmenter,np.asarray(rgb.resize((sw,sh),Image.Resampling.BILINEAR)),3,250,.4,0.)
ix,iy=rgb.width/sw,rgb.height/sh
cells=[]
for x,y,area,poly in polygons_from_labels(labels,MIN_AREA_PX):
x,y=x*ix-128,y*iy-128
if 0<=x<width and 0<=y<height:
poly=poly.copy();poly[:,0]=poly[:,0]*ix-128;poly[:,1]=poly[:,1]*iy-128
cells.append((x,y,area*ix*iy,poly))
if not cells: raise ValueError('No nuclei found. Check the H&E image and physical resolution.')
if len(cells)>MAX_CELLS: raise ValueError(f'Found {len(cells)} nuclei; this free demo supports {MAX_CELLS}. Upload a smaller crop. No cells have been silently discarded.')
polys=[c[3] for c in cells];vertices=np.concatenate(polys)
np.savez_compressed(destination,x_pixel=np.array([c[0] for c in cells],np.float32),y_pixel=np.array([c[1] for c in cells],np.float32),area_px=np.array([c[2] for c in cells],np.float32),indptr=np.r_[0,np.cumsum([len(p) for p in polys])],vertex_x=vertices[:,0],vertex_y=vertices[:,1],cell_id=np.array([f'cell_{i}' for i in range(len(cells))]),mpp=np.float32(mpp))
return polys
@torch.inference_mode()
def predict(self, image_path, cells_path, mpp, names, tissue, sample_id):
import anndata as ad
import pandas as pd
src=open_slide(str(image_path),str(cells_path),None,mpp)
try:
pos,area,rel,_=geometry(src,mpp)
plan=TargetContextPlan(pos,sample_id)
head={g:i for i,g in enumerate(self.model.genes)}
panel=np.array([head[g] for g in names],np.int64)
n,g=len(src),len(names)
direct=np.empty((n,g),np.float32);h1=np.empty((n,1536),np.float32);h2=np.empty_like(h1)
spatial=np.empty((n,self.model.args['d_model']),np.float32)
written=np.zeros(n,np.uint8)
tensor=lambda x:torch.as_tensor(np.ascontiguousarray(x),device='cuda')
hi=tensor(panel)
for images,masks,indices,nt in TargetContextDataset(src,plan):
indices=np.asarray(indices);nt=int(nt)
images,masks=tensor(images),tensor(masks)
f2=self.model.encode(images,masks,'stage2',32)
a,z=self.model.decode(f2,tensor(pos[indices]),tensor(area[indices]),tensor(rel[indices]),hi)
f1=self.model.encode(images[:nt],masks[:nt],'phase1',32)
commit_target_rows(indices,nt,written,[(direct,a.cpu().numpy()),(h2,f2.cpu().numpy()),(spatial,z.cpu().numpy())])
h1[indices[:nt]]=f1.cpu().numpy()
if not np.all(written==1):raise RuntimeError('Each target cell must be written exactly once.')
source,beta_map=select_gate(self.release.gate,tissue,g)
self.bank.configure(panel)
retrieved=np.empty_like(direct);fused=np.empty_like(direct)
for start in range(0,n,64):
end=min(n,start+64);r,_=self.bank.retrieve(h1[start:end],50)
fused[start:end],beta=apply_gate(direct[start:end],r,panel,beta_map)
retrieved[start:end]=r
if not all(np.isfinite(a).all() for a in [direct,fused,h1,h2,spatial]):raise RuntimeError('Model produced nonfinite values.')
obs=pd.DataFrame({'x_pixel':src.pos[:,1],'y_pixel':src.pos[:,0]},index=pd.Index(src.ids,name='cell_id'))
var=pd.DataFrame({'global_gene_id':panel,'beta':beta,'covered':self.bank.covered},index=pd.Index(names,name='gene'))
result=ad.AnnData(X=fused,obs=obs,var=var,layers={'A':direct,'R':retrieved},obsm={'spatial':src.pos[:,::-1].copy(),'X_morph2mol_phase1':h1,'X_morph2mol_stage2':h2,'X_morph2mol_se2':spatial})
result.uns['morph2mol']={'model_revision':os.environ['MORPH2MOL_REVISION'],'mpp':mpp,'sample_id':sample_id,'gate_source':source,'spatial_context':plan.metadata(),'score_scale':'beta*A+(1-beta)*R; per-gene scores, not molecule counts','segmentation':'Cellpose-SAM nuclei; not full-cell boundaries','stage2_sha256':self.release.hashes['stage2'],'reference_exclusion':'none; full reference bank'}
return result
finally:
if getattr(src,'_rd',None) is not None: src._rd.close()