Abstract
Foundation models offer a promising paradigm for modeling spatial transcriptomics, but capturing tissue context over cellular graphs makes training at scale challenging. We introduce spaGFM, a graph foundation model that serializes cellular neighborhoods through random walks to generate transformer-compatible representations of tissue organization. By replacing classical graph message passing with augmented self-supervised neighborhood reconstruction, spaGFM captures higher-order spatial context while allowing scaling at the atlas level. Pretrained on 43.9 million cells from 132 image-based spatial transcriptomics datasets, spaGFM produces robust representations at both the neighborhood and cell level that transfer across tissues, disease contexts, and spatial technologies. SpaGFM identifies tertiary lymphoid structures across cancer cohorts and spatial platforms, captures cell-level transcriptomic perturbation responses associated with T cell vicinity in spatial CRISPR experiments, and characterizes glomerular organization associated with pathological grade in diabetic kidney disease biopsies. Overall, spaGFM establishes a graph foundation-model framework for learning cellular organization and its functional consequences.
A central question in biology is how diverse molecular states and cellular relationships collectively give rise to tissue organization, function, and disease. The rapid accumulation of single-cell and spatially resolved transcriptomics (SRT) provides an unprecedented opportunity to learn generalizable principles of cellular identity and state rather than to analyze each dataset in isolation. Single-cell foundation models such as scGPT1, scFoundation2, and GeneFormer3 have been further motivated by scaling laws first characterized in natural language processing, in which model performance improves predictably as the amounts of training data, computation, and model parameters increase4. However, high-resolution SRT measures cellular gene expression within intact tissue architecture. The quantified spatial relationships among cells are non-linear and graph-structured, creating a mismatch with sequence-based tokenization and complicating the direct application of transformer scaling strategies to SRT.
Current foundation models for SRT can be broadly categorized into expression-based and graph-based approaches. Expression-based models adapt pretraining paradigms for single-cell transcriptomics and incorporate spatial information during adaptation and applications. For example, Nicheformer5 learns representations from gene expression tokens augmented with spatial metadata, scGPT-spatial6 extends scGPT through continual pretraining with spatially-aware sampling and neighborhood reconstruction objectives. Graph-based methods instead represent tissue architecture explicitly as cellular graphs, with nodes corresponding to cells and edges encoding spatial proximity. CellTransformer7 and Novae8 leveraged graph neural networks (GNNs)9 to learn representations of local cellular neighborhoods. Compared with expression-based models, graph modeling explicitly assumes the local cellular neighborhood should share similar representations, thereby capturing multicellular organization that may be difficult to encode as auxiliary objectives. However, conventional GNNs rely on iterative message-passing mechanisms susceptible to over-smoothing, over-squashing, and difficulty representing long-range dependencies10, which complicate the joint scaling of receptive field and model capacity.
Here, we introduce spaGFM, a graph foundation model for spatial transcriptomics that scales relation model capacity with parameter size and sampled spatial context at the atlas level. spaGFM represents cell relations in SRT as cellular graphs but avoids the iterative message-passing bottleneck of GNNs by serializing local cellular neighborhoods through random walks and converting graph-structured spatial context into scalable transformer-compatible token sets. Graph structure determines which cells are co-sampled and augmented within each neighborhood, whereas a self-supervised reconstruction objective learns relationships among the sampled representations. We pretrained spaGFM on atlas-level SRT data to learn transferable representations of cellular and neighborhood organization.
We evaluated spaGFM across various spatial biological settings and at both cellular and neighborhood scales, and examined how representation quality scaled with model size, pretraining progress, and sampled spatial context. We further showed generalizability to unseen tissues and technologies, and assessed the scalability, transferability, and biological utility of spaGFM across diverse spatial biological research with SRT. With lightweight task-specific adaptation, spaGFM enables robust detection of tertiary lymphoid structures (TLSs) across multiple spatial transcriptomics platforms, characterization of cell-level transcriptomic perturbation responses associated with T cell vicinity, and accurate identification of glomeruli in diabetic kidney disease (DKD). As spatial datasets continuously grow in size, scalable models such as spaGFM that jointly represent molecular state and tissue organization will become increasingly important for linking cell atlases to mechanisms underlying tissue function and disease.
Results
Overview of spaGFM
spaGFM is a scalable graph-based foundation model that learns cell organization representations from local spatial neighborhoods in SRT. Given a cellular-resolution SRT sample, spaGFM models the tissue as a cellular graph in which nodes encode cell-level gene expression profiles and edges are constructed from spatial coordinates using Delaunay triangulation11. The resulting graph is serialized into sets of neighborhood tokens by sampling local subgraphs through random walks (Fig. 1a). Inspired by previous works12,13, spaGFM is pretrained using a self-supervised masked autoencoder (MAE) objective that reconstructs masked neighborhood elements from observed context (Supplementary Fig. 1a). A variance regularization term is additionally adapted to reduce embedding collapse (Supplementary Fig. 2). In contrast to conventional GNNs, increasing the number and length of random walks augments the sampled spatial context without a performance bottleneck from deeper message-passing stack (Supplementary Fig. 3).
Fig. 1.

Schematics of spaGFM framework. (a) Overview of spaGFM model. spaGFM is pretrained on single-cell-resolution spatial transcriptomics data with self-supervised learning. Given the input spatial transcriptomics samples, cellular graphs are created by Delaunay Triangulation, and each graph is sampled into multiple neighborhood token sets using random walks. Each node represents a single cell characterized by its gene expression profile, with colors conceptually indicating cell types. spaGFM learns sampled neighborhood views by reconstructing masked walk sets with a Masked Autoencoder. This pretrained model supports multiple downstream applications. (b-c) The distribution of the pretraining datasets illustrated by tissue type and spatial transcriptomics platform. (d) UMAP of neighborhood-level and cell-level embeddings from the human pre-training datasets. For visualization, 10% of cells were subsampled from each dataset and colored by tissue type according to the color scheme in (b).
spaGFM is pretrained on an assembled large-scale corpus of image-based SRT data comprising three major platforms with cellular and subcellular resolutions, including 10X Xenium, CosMx SMI, and MERSCOPE (Methods). This corpus includes 43.9 million cells from 132 human and mouse samples spanning 20 tissues and diverse experimental conditions (Fig. 1b, c).
spaGFM learns hierarchical representations at both the cell and neighborhood scales within a unified framework. Cell-level representations support characterization of individual cells conditioned on their local context, whereas neighborhood-level representations summarize local tissue composition and organization (Supplementary Fig. 1b). In human samples, neighborhood representations preserved tissue-associated structure, whereas cell-level embeddings showed greater overlap across tissues (Fig. 1d). The pretrained representations can be used directly or adapted with lightweight task-specific models for prediction and spatial subgraph analyses (Fig. 1a). The framework can also incorporate gene-level prior knowledge for predicting spatial context-specific perturbation responses.
spaGFM scales representation performance with model capacity and sampled neighborhood context
We benchmarked spaGFM’s hierarchical representations at both the cellular and neighborhood spatial scales in human and mouse datasets. Cell embeddings at the cellular level were evaluated for cell type prediction and neighborhood embeddings at neighborhood level were evaluated for niche identification, with comparisons to Novae, Nicheformer, and scGPT-spatial. To evaluate the quality of frozen representations directly from the spaGFM model, embeddings were extracted without task-specific encoder fine-tuning and assessed using linear probing, k-nearest neighbors (KNN) classification, and unsupervised clustering (Methods).
Under linear probing, spaGFM performance increased with model size and pre-training progress across multiple tissues (Fig. 2a). Consistent with the hierarchical representation design, cell embeddings performed best for cell type classification, whereas neighborhood embeddings were most effective for niche identification (Supplementary Fig. 4a). Across the tested parameter range, performance improved up to the 317-million-parameter model. spaGFM also showed strong performance relative to the comparison methods under KNN classification and clustering across human (Fig. 2b) and mouse datasets (Supplementary Fig. 5). To assess transferability across individuals, we further evaluated niche label transfer in unseen human idiopathic pulmonary fibrosis (IPF) lung tissue14 and supratentorial ependymoma brain tissue15, where spaGFM outperformed Novae and supported more fine-grained niche annotation on both datasets (Fig. 2c, Supplementary Fig. 6).
Fig. 2.

Evaluation of spaGFM on neighborhood and cell-level tasks. (a) Predictive performance of spaGFM as a function of model size (top): 3M, 15M, 36M and 317M; number of sampled random walks (middle): 16, 32, 64 and 128; and pretraining progress (bottom): 15k, 45k, 75k and 150k; across niche (left column) and cell type (right column) classification tasks. In linear-probing settings, three CosMx human tissues were used to compare spaGFM with baseline models, including Nicheformer, Novae, and scGPT-spatial. (b) Performance of niche tasks in multiple human tissues under KNN classification (F1-macro, Accuracy, and MCC; top) and K-means clustering (ARI and NMI; bottom), averaged across samples within each tissue. (c) Cross-patient evaluation of niche representations in human lung on the Xenium platform. Evaluation scheme for zero-shot niche-label transfer using embeddings derived from spaGFM or Novae in the human lung (top) datasets. Spatial visualization of niche predictions (bottom) for the representative sample across methods. (d) Schematic illustrations of topological-noise simulation (top left) and geometric boundary-perturbation simulation (bottom left) in the human lung with CosMx technologies. Under linear probing settings, performance was evaluated across varying levels of graph noise and geometric boundary perturbations (right). MCC: Matthews Correlation Coefficient. ARI: Adjusted Rand Index. NMI: Normalized Mutual Information.
Notably, niche identification was more dependent on graph context and walk-based augmentation than cell type classification (Fig. 2a), where increasing walk length and contextual coverage consistently improved niche characterization by providing a broader approximation of the local cellular environment. Across tissues, longer walks and more walks per cell provided robust niche-level characterization spanning a range of cellular densities (Supplementary Figs. 9a-b, 10a-b, 11a-b, 12a-b, 13). Tissues with higher cellular heterogeneity tended to require longer walks to characterize the niche than tissues with more homogeneous cell-type compositions (Supplementary Figs. 9c, 10c, 11c, 12c). These results suggest that neighborhood-level tasks benefit from higher-order spatial context and that the useful receptive field is tissue-dependent. Although spaGFM was pretrained with a fixed, relatively short walk length (Methods), variable walk lengths can be used at inference to adapt aggregation of spatial context without retraining.
To assess the modeling robustness16, we evaluated spaGFM under topological corruption and geometric perturbations (Fig. 2d; Methods). We observed that simulated node feature shuffling disrupted local cell-type composition, whereas coordinate perturbation distorted graph topology (Supplementary Fig. 14). The linear probing performance reasonably declined gradually as corruption increased, without an abrupt collapse. In approximating segmentation-related geometric perturbations17 with simulated translation, rotation, scaling, and shear of cell boundaries (Fig. 2d; Methods), neighborhood embeddings remained comparatively stable, supporting formulation robustness to this topological and geometric noise.
We next tested whether random-walk sampling and augmentation alone improved niche prediction. The neighborhood-level representations of the comparative baselines were constructed by max- or mean-pooling cell embeddings sampled along the same random walk without graph structure (Supplementary Fig. 7a). spaGFM consistently outperformed these pooled baselines across datasets (Supplementary Fig. 7b), indicating that random-walk sampling on the modelled cellular graph effectively improved niche prediction.
spaGFM identifies Tertiary Lymphoid Structures across spatial transcriptomics platforms
Tertiary lymphoid structures (TLSs) are ectopic lymphoid aggregates that develop in non-lymphoid tissues at sites of chronic inflammation18, where their presence and maturation state are associated with prognosis, immunotherapy response, and disease progression across multiple cancers and inflammatory diseases. Despite their clinical importance, identifying TLS from SRT remains challenging. The widely used 10x Visium platform captures transcripts from multiple cells within each spot, resulting in mixed cellular signals that obscure TLS boundaries. Furthermore, TLSs span a continuum of maturation states, from diffuse lymphoid aggregates to germinal center-like structures, limiting the effectiveness of marker-based approaches19,20.
We investigated spaGFM on previously unseen 10x Visium datasets. Because spaGFM was pretrained exclusively on higher-resolution imaging-based SRT datasets, transfer to spot-level Visium data provides a test of generalization across technologies and resolutions. To accommodate Visium profiles, we adapted scGPT to Visium data using scPEFT21 and used the resulting spot embeddings as input for spaGFM. spaGFM was fine-tuned to distinguish mature TLSs, early-stage TLSs, and non-TLS regions with expert annotations (Methods).
We first evaluated spaGFM on a 10x Visium lung cancer dataset22. The sample containing the most abundant early-stage and mature TLS regions (LC3) was reserved as an independent test set, whereas the remaining four samples were used for four-fold cross-validation (Fig. 3a). We compared spaGFM with native scGPT, fine-tuned scGPT without spatial modeling, NicheCompass23, and the spatial foundation models Novae and scGPT-spatial. Across all validation folds in this pipeline-level comparison, spaGFM achieved the highest F1-macro score and consistently outperformed all competing methods (Fig. 3b). The improvement over fine-tuned scGPT, which provided the spot-level expression embeddings used by spaGFM, underscored the value of incorporating spatial context via graph-based random-walk tokenization and Transformer-based representation learning. Moreover, spaGFM consistently outperformed NicheCompass, Novae and scGPT-spatial, indicating that spatial representations learned from high-resolution imaging datasets transfer effectively to lower-resolution Visium data.
Fig. 3.

Benchmarking spaGFM for TLS identification across cancer types. (a) Cross-validation scheme and TLS annotation subsampling strategy on the 10x Visium lung cancer spatial transcriptomics dataset, with the proportion of annotated TLS spots. (b) F1-macro scores of spaGFM and comparison methods on the lung cancer dataset. (c) Workflow where spaGFM was fine-tuned on the 10x Visium kidney cancer dataset and evaluated on the independent renal cell carcinoma cohort (GSE175540). Bar plots show the proportions of TLS annotations in both datasets. The displayed y-axis begins at 90%. (d) F1-macro scores of spaGFM and comparison methods on GSE175540. (e) spaGFM-predicted TLS regions (shown in brown) overlaid on the H&E image of sample S1 from GSE175540. (f) Pathologist-annotated TLS regions (brown spots) overlaid on the same tissue section. (g) Moran’s I for pathologist annotations and predictions generated by spaGFM and comparison methods across the samples from GSE175540. (h) Neighborhood purity of pathologist annotations and model predictions across the same samples. (i) TLS signature score as mean log-normalized expression of 21 canonical TLS marker genes across TLS and non-TLS regions. Spot-level statistical comparisons were performed (two-sided Mann-Whitney U test with Bonferroni correction, all P < 10−6; ***). (j) Log2 fold-change in expression of 21 canonical TLS marker genes between TLS and non-TLS regions pooled across all five samples from the kidney cancer dataset, based on pathologist annotations (top) and spaGFM predictions (bottom). Genes are grouped by their associated TLS cellular or functional compartments. Colors indicate log2 fold-change (TLS/non-TLS). Statistical significance was assessed using two-sided Mann-Whitney U tests with Benjamini-Hochberg correction across the 21 genes (q < 0.05, q < 0.01, q < 0.001). (k) Spatial expression heatmaps of 21 TLS markers, CCL19, and MS4A1 overlaid on the H&E image. TLS: tertiary lymphoid structure.
We next evaluated cross-dataset generalization using an independent renal cell carcinoma Visium dataset (GSE175540)24. spaGFM was fine-tuned using a 10x Visium kidney cancer dataset22 with three labels (mature TLS, early-stage TLS, and non-TLS) and directly applied to the kidney cancer dataset without additional retraining (Fig. 3c). Because the kidney cohort contains only binary TLS annotations, predictions of mature and early-stage TLSs were merged into a single TLS category for evaluation. Under this setting, NicheCompass and scGPT-spatial failed to identify TLS regions, and other comparison methods showed limited discriminative performance. In contrast, spaGFM consistently achieved the highest performance, improving F1-macro by approximately 10 percentage points relative to competing approaches (Fig. 3d).
spaGFM predicted TLS regions overlapped with pathologist-annotated TLSs on corresponding H&E images (Fig. 3e, f). Moran’s I and neighborhood purity analyses showed that spaGFM predictions were more spatially coherent than those of the comparison methods across the kidney cancer samples (Fig. 3g, h). We further assessed biological consistency using the expression of 21 canonical TLS marker genes (Methods). TLS signature scores25 (Mean log-normalized expression scores) were substantially higher in predicted TLS regions than in non-TLS regions (Fig. 3i), and predicted TLS regions recapitulated marker expression patterns observed in annotated TLSs (Fig. 3j, k). These results were further confirmed by spatial expression of CCL19 and MS4A1 colocalizing with spaGFM-predicted TLS regions (Fig. 3l), consistent with organized T-cell and B-cell compartments in TLSs26.
spaGFM captures spatially conditioned perturbation responses
High-throughput genetic perturbation experiments, including Perturb-seq, are widely used to infer gene function from transcriptional responses at single-cell resolution. Perturb-FISH27 extends this paradigm to intact tissue by combining imaging-based SRT with in situ optical detection of guide RNAs, thereby capturing both cell-intrinsic perturbation responses and responses associated with the surrounding cellular microenvironment.
We applied spaGFM to a Perturb-FISH tumor study perturbing NF-κB genes to investigate context-dependent perturbation responses (Fig. 4a). Tumor cells carrying the same genetic perturbation occupied distinct spatial neighborhoods, allowing us to determine whether neighboring immune cells modulate transcriptional responses (Fig. 4b, Supplementary Fig. 15a).
Fig. 4.

spaGFM predicts environment-dependent perturbation responses in spatial CRISPR (Perturb-FISH) tumor research. (a) Schematic of the prediction task. LFCs are calculated separately for tumor cells with and without T-cell neighbors. g1, …, g500 denote the 500 Perturb-FISH panel genes. Exemplary g2 illustrates a context-dependent change in LFC direction, whereas g1 and g3 illustrate changes in LFC magnitude but independent of spatial context. (b) Spatial distribution of IRAK1-knockout and control cells across the slide. Insets show a T-cell-proximal region (top) and a T-cell-distal region (bottom). (c) Validation and benchmarking. Top left, AUC for predicting T-cell proximity from the spaGFM embedding (red) versus an scGPT-based representation (yellow). Bottom left, R2 between the predicted LFC residual across methods (Pure spatial, scGPT, spaGFM) and the LFC provided in the original publication. (d) Prediction performance on held-out perturbations, shown as balanced accuracy for spaGFM, GenePT*, GEARS and Celcomen. Bars indicate the mean. GenePT* is the spatial-ablated control (Methods). *P < 0.05; **P < 0.01; ***P < 0.001. (e) Gene-level comparison of ground-truth and predicted effects for perturbed genes against target genes, colored by down-regulation (blue) to up-regulation (red). Top panel, ground-truth LFC. Bottom panel, spaGFM prediction confidence. Each upper-left triangle shows the target gene response to a perturbed gene in tumor cells with T cell neighbors, each lower-right triangle in tumor cells without T cell neighbors. Genes on the Y-axis represent perturbed genes, and genes on the X-axis represent responding genes. Dots mark entries with Wilcoxon Benjamini-Hochberg adjusted q < 0.1. (f) Predicted regulatory maps for canonical NF-κB pathway genes absent from the screen, linking upstream regulators to NF-κB targets in tumor cells with (left) and without (right) T cell neighbors. Targets represent inflammatory output (IL-6, CXCL1 and CXCL2), pathway feedback (NFKB1 and NFKB2) and cytoprotection (SOD2). Regulator nodes are colored by pathway annotation: negative regulator (red), positive transducer (blue), or interferon-pathway crosstalk component (purple). Target nodes are gray. Edge color denotes predicted up- (red) or down-regulation (blue) following regulator knockout, and edge width denotes confidence. LFC: log-fold change. AUC: area under the curve.
Without explicit neighborhood annotations, spaGFM identified tumor cells with and without neighboring T cells in its learned embedding space (Supplementary Fig. 15b). This separation was quantitatively reflected by an AUC of 0.913 for predicting T-cell proximity from spaGFM embeddings, substantially exceeding the performance obtained using averaged scGPT embeddings of neighboring cells (AUC=0.721, Fig. 4c, top). This prediction power was further investigated to quantify spatial effects on perturbation responses. In leave-one-perturbation-out cross-validation across the 50 most variable genes, embeddings learned by spaGFM explained substantially more residual transcriptional variation than label-free neighborhood representations derived from averaged scGPT embeddings, approaching the performance of handcrafted spatial features that explicitly encode T-cell proximity (Fig. 4c, bottom). Further analysis revealed a small but statistically significant difference from the learned attention maps in the spatial space between T-cell-proximal and distal tumor cells (Cliff’s , permutation P-value = 5×10−4, Benjamini-Hochberg-adjusted P-value = 1.4×10−5; Supplementary Fig. 15c, d), suggesting that the embedding contains information associated with T-cell proximity.
We next evaluated whether spatial representations improved prediction of unseen perturbations. spaGFM and GenePT28 could be evaluated on 70 held-out split-perturbation pairs, whereas GEARS29 and Celcomen30 supported only a subset of perturbations. For a strictly matched four-method comparison, we therefore restricted to the same 24 shared pairs (Supplementary Fig. 15e). The results show spaGFM significantly outperformed all comparison methods on this matched benchmark (Fig. 4d), where spaGFM specifically outperformed GenePT when retaining the full set of 70 pairs (Supplementary Fig. 15f).
At the individual gene level, spaGFM recovered the regulatory direction of selected transcriptional responses and assigned higher confidence to some larger perturbation effects. For example, perturbation of MAP3K7, an upstream activator of NF-κB signaling, produced the largest measured transcriptional changes that were reflected in model predictions (Fig. 4e). The model also predicted the correct direction for lower-magnitude effects, including the CHUK-LGALS9, MYD88-VEGFA and RELA-ITGB2, providing selected examples spanning a range of measured spatial effect sizes.
Finally, we investigated whether spaGFM could generate hypotheses for perturbations absent from the experimental screen. Canonical NF-κB regulators outside the Perturb-FISH panel were approximated by their nearest neighbors in GenePT embedding space, and then inferred their effects on canonical NF-κB targets31. The predicted results differed substantially between tumor cells with and without neighboring T cells (Fig. 4f), indicating candidate immune microenvironment-dependent perturbation effects. Many of the predicted outcomes were consistent with established functions of these regulators. For example, predicted loss of the negative regulators IRAK3 and CYLD increased inflammatory target expression in T-cell-proximal cells, consistent with prior reports32,33. In contrast, the predicted loss of the positive regulator UBE2N, a K63 ubiquitin-conjugating enzyme required for TAK1 and IKK activation, reduced the same targets34. STAT1 showed context-dependent predicted effects, including differential regulation of CXCL2 between T-cell-proximal and distal tumor cells, consistent with context-dependent interactions between interferon-STAT1 and NF-κB signaling35,36. These zero-shot predictions represent hypotheses for targeted validation rather than measured effects, thereby extending them to biologically plausible regulatory interactions beyond experimentally assayed perturbations.
spaGFM characterizes glomerular organization associated with pathological grade in diabetic kidney disease
The kidney has a highly organized tissue architecture, and accurate identification of disease-associated glomeruli, a principal functional tissue unit, remains challenging in computational pathology and SRT analyses because the underlying glomerular cell types are significantly altered in expression and morphology by disease37,38. We analyzed four SRT cores (Splits 1–4) from a diabetic kidney disease (DKD) patient biopsy39. Cell identities and glomerular boundaries were manually annotated, and renal pathologists assigned each glomerulus to one of four pathological grades based on H&E morphology: no evident glomerular pathology (Grade 0), mild (Grade 1), moderate (Grade 2), and severe nodular mesangial sclerosis (Grade 3) (Fig. 5a, Supplementary Fig. 16a).
Fig. 5.

spaGFM resolves glomerular structure and pathological heterogeneity in diabetic kidney disease. (a) H&E-stained kidney biopsy from a diabetic kidney disease patient with 10X Xenium spatial transcriptomics shown alongside the spatial map of annotations by pathologists. Glomerular cells are colored by annotated pathological grade (Grade 0, no evident glomerular pathology; Grade 1, mild; Grade 2, moderate; Grade 3, severe), with non-glomerular cells labeled −1. (b) Spatial domains identified by manual annotation (left, red denotes glomerular cells, whereas gray denotes all other tissue), spaGFM (middle), and Novae (right) on the same kidney tissue section. Each cell is colored by its assigned domain label. Red circles exemplify the case where spaGFM identifies a more accurate glomerular structure than Novae. Arrows denote sample spatial orientation. (c) UMAP of glomerular cell embeddings with pseudo-time trajectory overlaid by Slingshot. Cells are colored by pathological grade (Grades 0–3); the inferred trajectory terminates in a region enriched for Grade 3 cells and is interpreted as a grade-associated ordering rather than longitudinal progression. (d) Glomerulus detection by the fine-tuned model. spaGFM model prediction (left; blue = none, green = predicted glomerulus, red circles highlight predicted glomerular regions), and spatial high expression of the podocyte marker NPHS2 (right) providing molecular support for the additional candidate regions. (e) Random-walk-derived cell-type composition for each glomerular grade. (f) Violin plot of curl of the Head 1 attention field across grades (0–3); higher curl in Grade 3 indicates a difference in the geometry of the inferred attention field (pairwise significance: two-sided Mann-Whitney U test, P-value< 0.05, *). The number of glomeruli across grades: 8 (grade 0); 3 (grade 1); 1 (grade 2); 3 (grade 3).
We first clustered zero-shot neighborhood embeddings and observed that the resulting spatial domains delineated glomerular structures. spaGFM partitioned the tissue into 11 spatial domains, with domain 2 closely corresponding to the manually annotated glomeruli. In comparison with Novae, the spaGFM-derived glomerular regions indicated greater structural continuity (Fig. 5b, Supplementary Fig. 16b-e). Trajectory analysis of neighborhood embedding revealed a continuous severity-associated ordering of glomerular cells across the four annotated categories (Fig. 5c), indicating the learned representations captured variation associated with pathological grade.
We further fine-tuned the spaGFM for per-cell glomerulus identification using 13 annotated glomeruli from Split 2 for training, five glomeruli from Split 4 for validation, and the remaining two sections for testing. spaGFM achieved greater than 90% accuracy and approximately 0.97 recall (Supplementary Fig. 16f). These predicted glomerular regions were confirmed with the expression of the podocyte marker gene NPHS240 (Fig. 5d). When pathological grades were collapsed into Grade 0 and Grades 1–3 categories, the fine-tuned model maintained approximately 90% accuracy (Supplementary Fig. 16h). Notably, spaGFM performance scales with model sizes in this glomeruli-identification task. We compared the results between a reduced model of 36-million-parameters and the full model with 317-million-parameters and observed a performance gain in the representation benchmarks, including elimination of mis-annotations due to technical artifacts at the edge of the tissue (Supplementary Fig. 16).
To investigate the biological basis of the predictions, we analyzed the neighborhood composition captured along the augmented random paths in spaGFM. Neighborhood cell proportions showed grade-associated changes consistent with known DKD pathology (Fig. 5e). In particular, the relative loss of podocytes was consistent with disruption of the glomerular filtration barrier and podocytopathy frequently observed in advanced DKD. In contrast, expansion of the kidney stromal cells and parietal epithelial cells is consistent with mesangial expansion and pericapsular fibrosis, respectively, in diabetic kidney disease. Finally, myeloid and other immune cell populations were enriched in glomeruli with advanced disease.
Outside of Glomeruli, spaGFM was able to localize disease-state niches more precisely than Novae. For example, niche 7 corresponds to a fibro-immune niche (Supplementary Fig. 17). spaGFM distinctly maps niche 7 to its appropriate underlying histology (Supplementary Fig. 17a). Compared to a healthy proximal tubular niche (niche 2), we observed a corresponding fibrosis signature in niche 7 (Supplementary Fig. 17b, c). Novae was unable to precisely map niche 7 as these were broadly distributed and mixed among other niches.
We additionally examined the learned attention patterns as a potential source of model interpretation. Attention Head 1 emphasized Grade 3 cells, with high-attention regions enriched for pathological severity (Supplementary Fig. 18). We represented attention in physical space as a vector field and summarized its local geometric organization using curl and divergence. These quantities statistically differed in Grade 3 glomeruli (Fig. 5f) related to patterns across additional multiple attention heads (Supplementary Fig. 19a, b), which provides descriptive associations between attention geometry and pathological grade.
Discussion
Rapidly accumulated atlas-level SRT data brought both challenges and opportunities in data modeling. spaGFM establishes a scalable graph foundation-model framework by converting spatial cellular graphs into random-walk neighborhood token sets that can be processed by transformer architectures. Compared to the conventional approaches (Supplementary Table 1), the central design separates the size of the sampled spatial context from the depth of graph message passing: local graph structure determines which cells are co-sampled, while self-supervised transformer learning models relationships among the sampled representations. Across the comprehensive experiments on different tissues, representation performance increased with model size, pretraining progress, and sampled neighborhood context. These observations support the scalability of the framework over the tested ranges, although we tested up to 317-million-parameters due to computational availability. A formal scaling-law analysis across data, parameters, and compute remains an important direction for future work.
Generalizability is a central characteristic of a foundation model. spaGFM uses Delaunay triangulation to construct spatial cellular graphs11, providing a consistent geometry-based inductive bias applicable across SRT datasets represented in two-dimensional Euclidean coordinates. This setting provides transferability in the modeled triangle-composed planar spatial cellular graphs under uniform Euclidean geometries41, which enables high-quality zero-shot learning and label transfer in diverse scenarios in SRT data.
The attention-vector-field analysis provides a complementary way to interpret spatial patterns learned by spaGFM. Visualizing learnt attention in physical space enables descriptive summaries of local orientation, curl, and divergence. In the DKD case study, these quantities were identified to be associated with pathological grade. Because attention weights are model-derived and are not equivalent to causal explanations, these results should be interpreted as exploratory measures of representation geometry rather than direct evidence of biological mechanisms.
A key feature of spaGFM is its ability to learn hierarchical representations across cellular and tissue-neighborhood scales. Cell-level embeddings capture information relevant to cell-state characterization, whereas neighborhood-level embeddings integrate local tissue composition and spatial organization, providing representations suited to niche-level analyses. Benchmarking and ablation experiments (Supplementary Table 2–4) further indicate that higher-order spatial context is particularly important for neighborhood-level tasks (Supplementary Fig. 7), with flexible random-walk sampling allowing the effective receptive field to be adjusted at inference without retraining. This flexibility is accompanied by favorable computational scaling: across the tested range, inference time increased approximately linearly with cell number, with limited sensitivity to tissue density or spatial architecture (Supplementary Fig. 4b). Although spaGFM can therefore be directly applied across datasets with distinct spatial characteristics, lightweight adaptation to previously unseen datasets can further improve predictive accuracy (Supplementary Fig. 8), highlighting a practical balance between generalizability and dataset-specific refinement.
The downstream applications illustrate the versatility of these pretrained representations. In cancer datasets, spaGFM was transferred from high-resolution imaging platforms to 10x Genomics Visium data, identifying TLS-associated regions across lung and renal cancer cohorts. In Perturb-FISH data, spaGFM embeddings captured spatial context associated with T-cell proximity and enabled prediction of held-out perturbation responses. Predictions for unmeasured NF-κB regulators extend this analysis to hypothesis generation, may facilitate prioritization of context-dependent perturbations for future Perturb-FISH, spatial CRISPR, and targeted validation studies. In the DKD study, zero-shot embedding and lightweight fine-tuning supported glomerulus identification and captured grade-associated spatial organization, while additional NPHS2-positive candidate regions suggested that molecular and spatial representations can complement morphology-based annotation.
There are still several limitations. First, spaGFM currently represents gene expression using pretrained cell embeddings rather than gene-level tokens, which limits direct modeling of gene-level regulatory programs and results in missing transcripts. Joint modeling of gene-level and neighborhood-context representations could connect intracellular regulation and intercellular organization. Second, spaGFM relies on predefined spatial graphs and random-walk sampling, therefore it depends on assumptions about tissue connectivity and spatial scale. Adaptive graph construction, histology-informed connectivity, and learned receptive fields may improve modeling of more complex tissue architectures. Third, although spaGFM was pretrained across multiple imaging-based SRT technologies and transferred to independent tissues and Visium datasets, broader validation across additional patients, sequencing-based and multimodal spatial assays, and three-dimensional tissues will be important for defining its generalizability. Finally, the DKD analysis derives from one patient, and the unmeasured perturbation predictions are not experimentally validated, which should therefore be regarded as proof-of-concept and hypothesis-generating analyses, respectively.
Methods
Spatial cellular graph construction
spaGFM models the SRT slice with single-cell resolution as a graph , where is the set of cells as nodes and as edges connecting each cell tessellated by Delaunay triangulation11. For each cell , its two-dimensional spatial coordinates are denoted as . To alleviate unreasonable connections between distant cells, suspicious edge connections are filtered by a distance threshold of spatial coordinates. The processed , where is 99th quantile of the edge distance distribution for slice . To harmonize gene panels across datasets, we initialized node features using the frozen scGPT1 whole-human pretrained checkpoint. For both human and mouse datasets, genes were matched to the scGPT vocabulary by gene symbol, and only genes with matching symbols were used to generate the -dimensional scGPT cell embeddings. Together, the full unweighted graph representation for slice with cell organization information is denoted as where .
Random-walk tokenization
The cellular graph of the slice is further sampled into sets of neighborhood nodes by using a random-walk sampler. From each source node , the walk sampler continuously travels through the graph according to its adjacency, generating a random walk with length , and . We used the idea from Node2Vec42, balancing the walking process between Breadth-First Search (BFS) and Depth-First Search (DFS). We denote as the node in the walk. Each step of the walk is sampled in Eq. (1), where is the transition probability matrix between nodes and with as a normalized constant. The transition probability is determined by the shortest path distance denoted by , between the node and the node , where .
| (1) |
Here we parameterized , and set as 1 as SRT is represented as unweighted graphs. This random-walk sampling was repeated and augmented times independently for each node in slice to enrich the neighborhood representation, denoted as , where the walk constitutes nodes generated during random walk sampling.
Given the pair representation of node features and its neighborhood of source node in slice , we tokenized the sampled neighborhood through transformer-based encoding12, denoted as , where and . For the sampled neighborhood, each token encodes the node with features , and projects into high dimension representation by transformer encoder43 , across steps. Spatial-aware cell embedding for the source node represents as . The trainable tokenization per walk denoted as was averaged across steps via mean pooling in Eq. (2).
| (2) |
Self-supervised pretraining for spaGFM
spaGFM uses a masked autoencoder (MAE) framework44 to learn the semantic representation of each cellular neighborhood in a self-supervised learning formulation (Supplementary Fig. 1a). Encoder encodes the semantic relationship denoted as , between visible walks, where . Decoder reconstructs masked walk representations, denoted as , out of total walks, conditional on visible walks along with masked tokens in Eq. (3).
| (3) |
and are standard transformer models parameterized by and , respectively43. In our setting, and . This formulation is conceptually analogous to masked patch representation learning in computer vision44. We do not employ positional encoding either within or across walks. Consequently, each sampled walk is treated as a permutation-invariant multiset of neighborhood tokens rather than as an order-sensitive trajectory.
Because ground-truth walk representations are unavailable, we adopted an online-target learning strategy for reconstruction optimization13,45. The online targets were constructed by the same encoder structure with gradient propagation stopped, denoted as , during the training process in Eq. (4).
| (4) |
Only the target (teacher) parameters in and were updated by Exponential Moving Average (EMA) rules in Eq. (5). We updated every 10 optimization steps with . The online (student) encoder and decoder were optimized by backpropagation and received the reconstruction- and variance-loss gradients.
| (5) |
The reconstruction objective is to minimize mean-squared error over masked positions in Eq. (6).
| (6) |
To prevent the variance of each embedding dimension from collapsing to a trivial solution, we added a penalty loss over the latent neighborhood representation to prevent its variance across the batch dimension below a threshold46 in Eq. (7). We define , which is the mean-pooled representation over the visible walks. , where is the target threshold of standard deviation and is a small scalar for numerical stability. Here, we used with as the default value.
| (7) |
Together, the overall objective loss is defined as Eq. (8), the sum of reconstruction loss in Eq. (6) and variance loss in Eq. (7).
| (8) |
Additional methodology details can refer to Supplementary Fig. 1.
Cellular and Neighborhood representations in spaGFM
Cellular and neighborhood levels of cellular organization differ in granularity and impose distinct representational requirements within a unified embedding space. spaGFM addresses this challenge by learning representations at multiple levels during pre-training (Supplementary Fig. 1b). During inference, for a cell in slice , we define neighborhood embedding as which performs mean aggregation over walks for neighborhood-level characterization. For cell-level tasks, we use the cell embedding . Cell embeddings capture the source cellular representations while conditioning on the local spatial neighborhood, enabling cell-level characterization within its spatial context. In contrast, neighborhood-level embeddings aggregate information from the surrounding cellular environment, capturing both the composition and spatial organization of the local microenvironment for neighborhood-level analyses.
The implementation of model pretraining
We developed a customized data loader to efficiently process large-scale spatial transcriptomics datasets during pretraining. Each slice was treated as an individual spatial cellular graph, and a mini-batch of nodes were selected across all graphs. In each training step, a batch of 256 cells was randomly sampled across all tissue slices. To avoid sampling bias toward larger graphs, nodes from smaller graphs were repeatedly resampled once exhausted during training. Models were pretrained using mixed-precision training (BF16) with the AdamW optimizer and a learning rate of 1 × 10−4). We employed a warmup-stable-decay scheduler with 3% warm-up steps and 90% stable steps. Human and Mouse models were pretrained independently. Training was performed on four NVIDIA H100 GPUs for 150k steps for the Human model and 100k steps for the Mouse model.
Model scaling with parameter sizes
spaGFM scales model parameters primarily by increasing the width and depth of the transformer encoder (Supplementary Fig. 1c), denoted as , and the transformer decoder, denoted as . The encoder and decoder widths are denoted by , corresponding to the hidden dimension of each transformer block, where . The encoder and decoder depths are denoted by and , respectively, corresponding to the number of transformer layers, where and . We use a fixed attention head dimension of 64 for all models, with the number of heads , and feedforward width . We trained four spaGFM variants with different hidden dimensions and numbers of transformer layers, resulting in spaGFM-3M, spaGFM-15M, spaGFM-36M, and spaGFM-317M with 3, 15, 36, and 317 million parameters, respectively. Notably, we use full-size spaGFM-317M in all the case studies.
Ablation tests in model and applications
To validate the contribution of each computational component of spaGFM, we performed sophisticated ablation analysis of the spaGFM model, including initial representation, graph representation, transformer backbone, and variance regularization was summarized in Supplementary Table 2. The ablation analysis in applications was summarized in Supplementary Tables 3 and 4.
Data collection and preprocessing
Pretrained datasets for spaGFM
Pre-training spatial transcriptomics datasets were collected and downloaded from their official depositories (Data Availability). We filtered out cells with fewer than 10 expressed genes and genes detected in fewer than 5 cells. Expression counts were normalized by the median cell-by-gene count depth and log1p-transformed. We selected the CosMx Human Lung, Liver, and Cortex datasets and the CosMx Mouse Brain dataset for downstream evaluation because they include annotated cell-type and niche labels. These datasets were excluded from the pretraining corpus and used only for downstream evaluation.
Human idiopathic pulmonary fibrosis (IPF) lung and supratentorial ependymoma brain in 10x Xenium spatial transcriptomics
Human lung (GSE25034614) and brain (GSE30014615) datasets were obtained from the GEO database. We directly used their pre-processed datasets without post-processing steps.
Tertiary Lymphoid Structures studies in 10x Visium spatial transcriptomics
We evaluated spaGFM using a 10x Genomics Visium spatial transcriptomics dataset22 comprising lung and kidney tumors with diverse tertiary lymphoid structure (TLS) architectures. The dataset includes three kidney cancer samples (KC1-KC3) and five lung cancer samples (LC1-LC5) derived from FFPE tumor sections. Tissue sections (5 μm) were profiled using the Visium Spatial Gene Expression platform with the Human Probe Set v1, followed by H&E staining, library preparation, and sequencing on an Illumina NovaSeq 6000. Spatial transcriptomic data were processed with Space Ranger v2.1.0, and Visium spots were manually annotated by expert pathologists as mature TLS, early TLS, immune region, tumor region, normal tissue, or unlabeled. Unlabeled spots were excluded from downstream analyses. This dataset was used to assess the ability of spaGFM to identify TLS-associated microenvironments across multiple cancer types and TLS developmental states.
To evaluate cross-dataset generalization, we further analyzed an independent renal cell carcinoma spatial transcriptomics dataset24. This dataset comprises five tumor samples generated from both FFPE and fresh-frozen tissues and sequenced on the Illumina NovaSeq 6000 platform. Spatial regions were annotated as TLS-associated or non-TLS-associated niches. We used this cohort to assess whether spaGFM can transfer learned spatial representations across independent datasets, cancer cohorts, and tissue-processing protocols.
CRISPR screening and spatial transcriptomics of Mouse Xenograft models in Perturb-FISH
To benchmark spatially-resolved genetic-perturbation prediction, we used the perturb-FISH in mouse tumor dataset, downloaded from the Brain Image Library (https://download.brainimagelibrary.org/0c/bd/0cbd479c521afff9/extras/tumors/processed/finaltables/). For each sample, we assembled an AnnData (.h5ad) object from the two provided final tables: merfishcounttable.csv, the MERFISH gene-by-cell count matrix, and coordinates.csv, the spatial centroid (x, y) of every segmented cell. The two tables were joined on cell identifier so that each cell’s expression profile was paired with its spatial coordinate, and tumor versus T-cell identity labels together with the CRISPR perturbation (target gene) assigned to each cell were read from the matching records of the count table by cell-number matching. Because the original perturb-FISH analysis derives each cell’s microenvironment from segmented cell boundaries (membrane-to-membrane contact), whereas the public tables provide only cell centroids and not boundary polygons, we reconstructed the neighborhood graph from centroids and benchmarked several approximation strategies against the boundary-derived reference, including k-nearest-neighbors, nearest-cell classification, a preliminary distance-based classifier, and a size-aware classifier, across a range of parameters. A k-nearest-neighbor graph with most closely reproduced the original boundary-based neighbor relationships and was therefore adopted for all downstream spatial analyses. Ground-truth perturbation effects (log-fold changes) were computed with the FR-Perturb framework using the FR-PerturbnoNorm.py script from the Perturb-Fish GitHub repository.
Human diabetic kidney disease (DKD) studies in 10x Xenium spatial transcriptomics
Spatially resolved single-cell transcriptomic profiling of a human diabetic kidney disease specimen (sample ID IU04) was generated on the 10x Genomics Xenium platform39. The severity of glomerular injury was manually annotated by biologists with nephropathologist expertise.
Tissue and assay.
A formalin-fixed paraffin-embedded (FFPE) human kidney section was assayed on the Xenium Analyzer (instrument XETG00126, slide 0015383) using the Xenium chemistry v1 with the Xenium Multi-Tissue segmentation stain, and decoded with Xenium Ranger analysis software (v3.2.0). Transcripts were imaged across a tissue region of ≈34.3 mm2. A total of 15,786,934 transcripts were detected, of which 13,172,460 (83%) were high-quality decoded transcripts and 78.3% were assigned to cells.
Gene panel.
Detection used a custom 300-plex human kidney panel (hKidney_300g, panel design BMU84Y, organism Homo sapiens, tissue type Kidney). The feature matrix retains all 541 codewords reported by Xenium (300 Gene Expression targets, 20 Negative Control Probes, 41 Negative Control Codewords, and 180 Unassigned Codewords), enabling background/false-discovery estimation. Only the 300 Gene Expression features should be used for downstream biological analysis. Negative-control signal was negligible (216 negative-control-probe and 0 genomic-control counts across all cells).
Cells and segmentation.
After cell segmentation, the dataset comprises 84,647 cells by 541 features (300 genes). Cells were segmented primarily by interior 18S stain (73,402 cells, 86.7%), supplemented by boundary stain (ATP1A1+CD45+E-Cadherin; 6,290 cells, 7.4%) and nuclear-expansion segmentation (4,955 cells, 5.9%). On average, cells contained a median of 89 transcripts (mean 121.8) spanning a median of 41 detected genes (mean 41.7), with a median cell area of .
Evaluation settings for downstream tasks
Benchmarking embedding representations in Human and Mouse datasets
Each CosMx human and mouse tissue slice was evaluated independently to assess cross-graph inductive transfer under a transductive target-graph setting, in which the frozen pretrained encoder generated cell embeddings using the full topology of each target graph. This design was chosen because niche or cell type annotations can be sample-specific and may not correspond one-to-one across patients. For zero-shot evaluation, the pretrained model was frozen and applied directly to each held-out dataset to generate cell embeddings. For linear probing, a linear classifier was trained to predict niche labels for 100 epochs using a learning rate of 0.01 and a weight decay of 0.001. For k-nearest-neighbor (k-NN) evaluation, we used k equals 5.
For both supervised evaluation settings, cells within each slice were randomly partitioned into training, validation, and test sets at ratios of 0.1, 0.1, and 0.8, respectively. Label stratification was not enforced, reflecting a generic low-label sampling setting. This procedure was repeated ten times using independent random seeds to account for sampling variability. For unsupervised evaluation, k-means clustering was performed on the full set of cell embeddings from each slice in ten independent runs with different random seeds. Final performance metrics were reported as the mean across the ten runs.
For the Xenium human lung and brain datasets, in which niche annotations were shared across samples, we additionally evaluated cross-sample label transfer. Samples were randomly partitioned into training and test sets at a ratio of 0.2:0.8. Cell embeddings from the training samples were used as the reference set for k-NN-based label transfer to cells in the held-out test samples, with k=5. This sample-level split ensured that cells from each test sample were excluded from the reference set used for label transfer. The evaluation was repeated ten times using independent random seeds, and performance was summarized as the mean across runs.
For comparison with existing methods, we followed the recommended settings for each benchmark model and extracted zero-shot cell representations from Novae, Nicheformer, and scGPT-spatial. We used the human-pretrained Novae model for the CosMx human datasets and the mouse-pretrained Novae model for the CosMx mouse brain datasets. The resulting representations were evaluated using the same downstream protocols as those applied to spaGFM.
Simulation of graph corruption and cell segmentation artifacts in CosMx Human Lung
Topological noises.
We simulated two types of noise for graph topology: node feature shuffling and node position shifting. For each slice , we constructed spatial cellular graphs with corrupted nodes at four proportions: {0, 0.1, 0.3, 0.5}. In the node feature shuffling setting, node features were randomly permuted according to the specified corruption ratios. In the node position-shifting setting, candidate node coordinates were perturbed using offsets sampled from a Gaussian distribution with mean 0 and standard deviation 10, scaled by the centroid distance to their k-nearest neighbors .
Geometric boundary perturbations.
To evaluate sensitivity to cell-boundary geometry in CosMx data, we perturb each cell boundary polygon independently with a randomized affine transformation whose magnitude is controlled by a single intensity scalar . Let a cell located at coordinates be represented by its boundary vertices with centroid . We first center the polygon, , and then apply a sequence of a rotation, an isotropic scaling, an anisotropic shear, and a translation. The transformation parameters are drawn independently per cell from uniform distributions whose ranges scale linearly with :
Here, denotes a uniform distribution over the interval is the rotation angle, is the isotropic scaling factor applied equally to both spatial dimensions, and are the shear angles along the - and -directions, respectively, and is the translation vector along the two spatial axes. The parameter jointly governs the maximum rotation (15°), area scaling (±10%), shear (5°), and translation (10 px) at (we use by default). Each centered vertex is first rotated,
then uniformly scaled with isotropic scaling factor , and sheared sequentially along and :
Note that the -shear is applied to the already -sheared coordinate , giving a mildly non-orthogonal composite shear. Finally, the polygon is re-centered and translated, , and vertices are rounded to integer pixel coordinates.
To preserve physically plausible cell segmentations, we enforce non-overlap through rejection sampling. For each cell, up to candidate transformations (default ) were generated, and the first candidate that produced a geometrically valid polygon (repaired using a zero-width buffer operation where necessary) without intersecting any previously accepted cell was retained. Cells with fewer than four vertices or topologically invalid boundaries were excluded from perturbation. This procedure generated controlled, spatially coherent geometric perturbations while maintaining a valid, non-overlapping tessellation of the tissue.
The identification of Tertiary Lymphoid Structures (TLS) in 10x Visium Human Lung and Kidney
To predict TLS regions, we employed a randomly initialized attention-based TLS decoder, , which transformed each neighborhood representation from Eq. (2) into a TLS prediction . The decoder and spaGFM parameters were jointly optimized using the cross-entropy loss , where denotes the annotated TLS annotation. Model training was performed using the Adam optimizer with a learning rate of 0.01 and weight decay of 0.001 for 50 epochs. Spots lacking TLS annotations were excluded from both training and evaluation. We compared spaGFM with Scanpy, NicheCompass, Novae, scGPT-spatial, native scGPT and fine-tuned scGPT. For these competitive methods, TLS regions were identified using the corresponding label-transfer workflows. Briefly, embeddings of query spots were compared with embeddings of annotated reference spots, and the k-nearest neighbors (, following the scGPT study) were identified in the embedding space. The TLS label for each query spot was assigned by majority vote among its nearest annotated neighbors. Given the class imbalance among early-stage TLS, mature TLS, and non-TLS spots, model performance was assessed using the F1-macro score. In addition, we calculated a continuous TLS signature score for each spot as the mean log-normalized expression of 21 canonical TLS marker genes (MS4A1, CD79A, CD79B, MZB1, IGHG1, CCL19, CCL21, CCR7, SELL, LAMP3, CR2, BCL6, CXCL13, CXCR5, CD3D, CD3E, CD8A, PDCD1 and CHST4, CHST2, and MADCAM1)18,26,47,48, capturing coordinated B-cell, T-cell and follicular chemokine programs associated with TLS formation. To assess whether predicted TLS regions formed spatially coherent structures rather than dispersed predictions, we constructed a spatial neighborhood graph by connecting each spot to its six nearest neighbors. Spatial organization was quantified using Moran’s I, a global measure of spatial autocorrelation computed on predicted or annotated TLS labels49,50. Moran’s I ranges from approximately −1 (spatial dispersion) to +1 (strong spatial clustering), with values near zero indicating spatial randomness. As a complementary metric, we calculated neighborhood purity51,52 as the fraction of the six nearest neighbors sharing the same TLS label as the focal spot and reported the average purity across all spots. Neighborhood purity quantifies the local consistency of TLS predictions, with a value of 1 indicating perfectly homogeneous neighborhoods. Accordingly, this analysis compares method-specific prediction pipelines rather than frozen representations under a common downstream classifier.
Prediction of spatially conditioned perturbation responses in Perturb-FISH mouse xenografts
We analyzed a spatial CRISPR perturbation atlas generated by perturb-FISH, an imaging-based spatial transcriptomics assay. The dataset comprises approximately 153,000 cells profiled with a 500-gene MERFISH panel. Each cell is annotated with a single-gene knockout (KO) or non-targeting control label, two-dimensional spatial coordinates, and a 500-dimensional gene expression profile.
For every perturbed cell, the effect of each panel gene was quantified as the log-fold change (LFC) relative to identity-matched control cells. LFC values were estimated using the Factorize-Recover framework (FR-Perturb) following the original Perturb-FISH study and served as supervision targets throughout model training. GPT-3.5 gene embeddings were obtained from GenePT28 for every perturbation gene and kept fixed across all experiments.
To operationally define T-cell neighborhood status, we evaluated candidate spatial definitions according to whether adding the resulting binary neighbor indicator improved prediction of perturbation-induced expression classes beyond perturbation identity alone. For each candidate definition, tumor cells were partitioned into neighbor-positive and neighbor-negative groups, perturbation-specific LFC profiles were re-estimated separately for the two groups, and gene-level LFCs were discretized as downregulated, unchanged, or upregulated using margins of 0.05, 0.10, 0.15, and 0.20. Ridge classifiers were then fit using either the compressed GenePT perturbation embedding alone or the GenePT embedding together with the binary neighbor indicator. Based on this analysis, local T-cell proximity was defined as the mean Euclidean distance to the four nearest T cells. Tumor cells at or below the 55th percentile of this distribution were classified as T-cell-proximal (with T-cell neighbors), whereas the remaining cells were classified as T-cell-distal (without T-cell neighbors). This binary label was used to define T-cell context and was not used as an input to the downstream spaGFM perturbation-prediction model. The tissue graph was constructed as described in the “Spatial cellular graph construction” section. A pretrained spaGFM model generated a 1,280-dimensional cell embedding that served as the spatial input for subsequent analyses.
Perturbation prediction was formulated as a binary classification task. For every perturbed cell and panel gene, the model predicted whether the corresponding LFC was positive or negative. The predictor comprised two multilayer perceptron branches. The gene branch encoded the fixed GenePT embedding, whereas the spatial branch received the spaGFM embedding. Both branches projected their inputs into a shared 256-dimensional latent space through a linear layer followed by ReLU activation and dropout. Their outputs were concatenated and passed through a multilayer fusion network to produce a single logit, which was converted into a probability using a sigmoid function. Prediction confidence for each perturbation, gene, and T-cell context was summarized by averaging sigmoid probabilities across cells. Scores were linearly rescaled from [0,1] to [−1,1]. The sign denotes the predicted regulation direction, whereas the magnitude reflects classification confidence. For the effect-size-stratified analysis in Supplementary Fig. 15g, this signed confidence score was compared with observed LFC profiles using Spearman correlation; this statistic assesses confidence-to-LFC concordance rather than output from a separate effect-size regression model.
All methods were optimized with class-weighted binary cross-entropy loss. Gene-specific positive weights compensated for class imbalance. Optimization employed AdamW with a learning rate of 1 × 10−3) and a weight decay of 1 × 10−4. Models were trained with a batch size of 256 for up to 200 epochs. Early stopping was monitored on a validation set containing 10% of the training data, with a patience of 20 epochs. A fixed random seed of 42 was used throughout. The embedding-based comparators shared an identical architecture and optimization schedule and differed only in the spatial input. spaGFM received pretrained spaGFM embeddings. The MLP baseline replaced the spatial input with an all-zero vector. Celcomen served as a spatial counterfactual comparator. It generates perturbation effects natively and shares neither the architecture nor the optimization schedule of the embedding-based arms. Fitted on the same tissue graph, it produced a counterfactual by setting the target gene to its knockout state in the perturbed cell, and the predicted direction was taken as the sign of the counterfactual-minus-observed difference. GEARS served as a non-spatial baseline. It was trained for 20 epochs with a hidden dimension of 64. Predicted perturbation effects were converted to LFC values relative to the local control mean and assigned to all cells belonging to the corresponding perturbation.
Performance was evaluated using ten predefined leave-perturbation-out splits, with a minimum of 20 test cells required for each split-perturbation pair. This yielded 70 evaluable pairs for spaGFM and GenePT. For the direct four-method comparison, we further retained only perturbations whose target genes were represented in the measured panel and were therefore jointly evaluable by GEARS and Celcomen, resulting in 10 eligible perturbations and 24 common split-perturbation pairs. Fig. 4d reports all four methods on exactly these 24 pairs, whereas analyses involving only spaGFM and GenePT retained all 70 pairs.
The T-cell spatial context was evaluated by predicting the binary T-cell proximity label from cell embeddings using logistic regression under five-fold stratified cross-validation. Spatially driven heterogeneity was quantified using residual LFC, defined as the difference between the observed LFC of a cell and the mean LFC of its perturbation. Ridge regression was used to predict residual LFC for the 50 genes with the largest residual variance among the 11 perturbations containing at least 20 cells. Prediction followed leave-one-perturbation-out cross-validation. Three feature sets were compared. The first comprised handcrafted T-cell spatial descriptors, including nearest-neighbor identity, k-nearest-neighbor composition, cell-size-aware neighborhood membership, and the number of neighboring T cells. The second comprised PCA-reduced scGPT niche embeddings computed from non-T cells within a radius of 300 spatial units. The third comprised PCA-reduced spaGFM embeddings generated with a walk length of nine.
In attention analysis, reach was defined for each focal perturbed tumor cell as the attention-weighted mean Euclidean distance to its walk-reachable neighboring cells. Cliff’s delta was calculated as , where and denote attention-reach values for T-cell-proximal and T-cell-distal tumor cells, respectively. Statistical significance was assessed using two-sided paired Wilcoxon signed-rank tests by comparing spaGFM with each competing method across matched perturbation-split pairs. Cross-validation AUC and R2 are reported as mean ± standard deviation across folds.
The characterization of glomerulus organizations in 10x Xenium Human Kidney
Dataset and pathological annotation.
We analyzed a kidney biopsy from a DKD patient within the KPMP atlas. The sample comprised four serial sections (Splits 1–4) profiled by SRT on the 10x Genomics Xenium platform. For each section, cell-type identities and glomerular boundaries were manually annotated. A pathologist graded glomerular pathological severity from H&E morphology into four categories: no evident glomerular pathology (Grade 0), mild (Grade 1), moderate (Grade 2), and severe (Grade 3). Cell embeddings were generated with spaGFM as described before. For the zero-shot analyses, embeddings were used directly from the pretrained model without any task-specific training on the kidney data.
Zero-shot glomerulus identification.
To assess whether spaGFM resolves glomerular microstructure without supervision, we performed Leiden clustering (resolution = 0.5) on the Novae zero-shot cell embeddings, yielding 11 spatial domains. We then applied Leiden clustering to the spaGFM zero-shot cell embeddings, adjusting the resolution parameter to obtain the same number of clusters for comparison.
Trajectory and pseudo-time analysis.
Glomerular cells were extracted by manual annotations, and their embeddings were embedded in two dimensions with UMAP and clustered. Pseudo-time trajectories were inferred with Slingshot53 over the UMAP representation.
Glomerulus and disease-state classification.
For supervised detection, we attached an MLP classifier to the model and fine-tuned on 13 annotated glomeruli from Split 2, validated on five glomeruli from Split 4, and tested on the remaining two sections. Two tasks were performed: (i) per-cell binary classification of glomerulus versus non-glomerulus, and (ii) Grade 0 versus Grades 1–3 glomerulus classification, for which Grades 1 to 3 were merged into a single diseased category. Performance was quantified by accuracy, precision, recall, and F1 score. Fine-tuning settings are detailed in the “Fine-tuning” section.
Attention-weight analysis.
For each attention head, we represented its attention pattern as a two-dimensional vector field over the spatial coordinates of the tissue and treated this field as a spatial flow. Each vector encodes both the direction and magnitude of attention flow between cells. The vector direction indicates the dominant spatial orientation along which attention is propagated, whereas the vector magnitude reflects the strength of the corresponding attention flow. We characterized its local geometry with two standard differential operators. The curl,
measures the local rotational structure of the flow, and the divergence,
measures local expansion or contraction, with positive values indicating a source (attention spreading outward) and negative values a sink (attention concentrating inward). For each glomerulus, the spatial derivatives of the vector components were jointly estimated from the attention vector and coordinate differences among cells within that glomerulus using least-squares fitting of the spatial gradients. The resulting derivatives were used to calculate glomerulus-level divergence and absolute curl. Statistical comparisons across grades were performed using two-sided Mann-Whitney U tests.
Supplementary Files
This is a list of supplementary files associated with this preprint. Click to download.
Acknowledgements
This work is supported by National Institutes of Health grants R01DK138504 (to J.W., Q.M., M.E.), R01LM015252 (to J.W., D.X.), R35GM126985 (to D.X.), R01GM152585, P01CA278732, U54AG075931, and P01AI177687 (to Q.M.), the AnalytiXIN initiative (to J.W.), as well as the Pelotonia Institute of Immuno-Oncology (PIIO) (to Q.M. and A.J.G.).
Footnotes
Additional Declarations: There is NO Competing Interest.
Data availability
Pre-training datasets are publicly available from the corresponding official repositories: Xenium (https://www.10xgenomics.com/datasets), CosMx (https://brukerspatialbiology.com/products/cosmx-spatial-molecular-imager/ffpe-dataset) and MERSCOPE (https://vizgen.com/data-release-program). Sample-level metadata is available at Supplementary Data 1. The HuBMAP reference or diseased tissue data can be accessed through the HuBMAP publication page upon acceptance of the peer-reviewed manuscript. Source data are provided with this paper.
Code availability
The official repository of spaGFM is available at GitHub (https://github.com/yzhong36/spaGFM). The reproducibility repository of spaGFM is available at GitHub (https://github.com/yzhong36/spaGFM_reproducibility).
References
- 1.Cui H. et al. scGPT: toward building a foundation model for single-cell multi-omics using generative AI. Nature methods 21, 1470–1480 (2024). 10.1038/s41592-024-02201-0 [DOI] [PubMed] [Google Scholar]
- 2.Hao M. et al. Large-scale foundation model on single-cell transcriptomics. Nature methods 21, 1481–1491 (2024). 10.1038/s41592-024-02305-7 [DOI] [PubMed] [Google Scholar]
- 3.Theodoris C. V. et al. Transfer learning enables predictions in network biology. Nature 618, 616–624 (2023). 10.1038/s41586-023-06139-9 [DOI] [PMC free article] [PubMed] [Google Scholar]
- 4.Kaplan J. et al. Scaling laws for neural language models. arXiv preprint arXiv:2001.08361 (2020). [Google Scholar]
- 5.Tejada-Lapuerta A. et al. Nicheformer: a foundation model for single-cell and spatial omics. Nature methods 22, 2525–2538 (2025). 10.1038/s41592-025-02814-z [DOI] [PMC free article] [PubMed] [Google Scholar]
- 6.Wang C. et al. scGPT-spatial: Continual pretraining of single-cell foundation model for spatial transcriptomics. bioRxiv, 2025.2002. 2005.636714 (2025). [Google Scholar]
- 7.Lee A. J. et al. Data-driven fine-grained region discovery in the mouse brain with transformers. Nature communications 16, 8536–8536 (2025). 10.1038/s41467-025-64259-4 [DOI] [PMC free article] [PubMed] [Google Scholar]
- 8.Blampey Q. et al. Novae: a graph-based foundation model for spatial transcriptomics data. Nature methods 22, 2539–2550 (2025). 10.1038/s41592-025-02899-6 [DOI] [PubMed] [Google Scholar]
- 9.Wang J. et al. scGNN is a novel graph neural network framework for single-cell RNA-Seq analyses. Nat Commun 12, 1882 (2021). 10.1038/s41467-021-22197-x [DOI] [PMC free article] [PubMed] [Google Scholar]
- 10.Rusch T. K., Bronstein M. M. & Mishra S. A survey on oversmoothing in graph neural networks. arXiv preprint arXiv:2303.10993 (2023). [Google Scholar]
- 11.Yu Y. et al. TrimNN: characterizing cellular community motifs for studying multicellular topological organization in complex tissues. Nature Communications 16, 7737 (2025). [DOI] [PMC free article] [PubMed] [Google Scholar]
- 12.Wang Z. et al. Beyond Message Passing: Neural Graph Pattern Machine. arXiv preprint arXiv:2501.18739 (2025). [Google Scholar]
- 13.Wang Z., Zhang Z., Ma T., Zhang C. & Ye Y. Generative graph pattern machine. Advances in Neural Information Processing Systems 38, 30068–30091 (2026). [Google Scholar]
- 14.Vannan A. et al. Spatial transcriptomics identifies molecular niche dysregulation associated with distal lung remodeling in pulmonary fibrosis. Nature genetics 57, 647–658 (2025). [DOI] [PMC free article] [PubMed] [Google Scholar]
- 15.Jeong D. et al. Multidimensional profiling of heterogeneity in supratentorial ependymomas. Nature 652, 1016–1026 (2026). [DOI] [PMC free article] [PubMed] [Google Scholar]
- 16.Bilous M. et al. Resolving sensitivity, specificity and signal contamination in Xenium spatial transcriptomics. Nature Methods (2026). 10.1038/s41592-026-03089-8 [DOI] [PMC free article] [PubMed] [Google Scholar]
- 17.Petukhov V. et al. Cell segmentation in imaging-based spatial transcriptomics. Nature biotechnology 40, 345–354 (2022). 10.1038/s41587-021-01044-w [DOI] [PubMed] [Google Scholar]
- 18.Sautès-Fridman C., Petitprez F., Calderaro J. & Fridman W. H. Tertiary lymphoid structures in the era of cancer immunotherapy. Nature Reviews Cancer 19, 307–325 (2019). [DOI] [PubMed] [Google Scholar]
- 19.Fridman W. H. et al. Tertiary lymphoid structures and B cells: An intratumoral immunity cycle. Immunity 56, 2254–2269 (2023). [DOI] [PubMed] [Google Scholar]
- 20.van Rijthoven M. et al. Multi-resolution deep learning characterizes tertiary lymphoid structures and their prognostic relevance in solid tumors. Communications Medicine 4, 5 (2024). [DOI] [PMC free article] [PubMed] [Google Scholar]
- 21.He F. et al. Harnessing the power of single-cell large language models with parameter-efficient fine-tuning using scPEFT. Nature Machine Intelligence 8, 118–133 (2026). [Google Scholar]
- 22.Dawo S., Nonchev K. & Silina K. 10x Visium Spatial Transcriptomics Dataset: Kidney (3) and Lung (5) Cancer with Tertiary Lymphoid Structures (Zenodo, 2025). [Google Scholar]
- 23.Birk S. et al. Quantitative characterization of cell niches in spatially resolved omics data. Nature genetics 57, 897–909 (2025). [DOI] [PMC free article] [PubMed] [Google Scholar]
- 24.Meylan M. et al. Tertiary lymphoid structures generate and propagate anti-tumor antibody-producing plasma cells in renal cell cancer. Immunity 55, 527–541. e525 (2022). [DOI] [PubMed] [Google Scholar]
- 25.Liu J. et al. STAID: A Self-Refining Deep Learning Framework for Spatial Cell-Type Deconvolution with Biologically Informed Modeling. Advanced Science, e75607 (2026). [DOI] [PMC free article] [PubMed] [Google Scholar]
- 26.Cabrita R. et al. Tertiary lymphoid structures improve immunotherapy and survival in melanoma. Nature 577, 561–565 (2020). [DOI] [PubMed] [Google Scholar]
- 27.Binan L. et al. Simultaneous CRISPR screening and spatial transcriptomics reveal intracellular, intercellular, and functional transcriptional circuits. Cell 188, 2141–2158. e2118 (2025). [DOI] [PMC free article] [PubMed] [Google Scholar]
- 28.Chen Y. & Zou J. GenePT: a simple but effective foundation model for genes and cells built from ChatGPT. BioRxiv, 2023.2010. 2016.562533 (2024). [Google Scholar]
- 29.Roohani Y., Huang K. & Leskovec J. Predicting transcriptional outcomes of novel multigene perturbations with GEARS. Nature Biotechnology 42, 927–935 (2024). [DOI] [PMC free article] [PubMed] [Google Scholar]
- 30.Megas S. et al. Celcomen: spatial causal disentanglement for single-cell and tissue perturbation modeling. Nature Communications 17, 4126 (2026). [DOI] [PMC free article] [PubMed] [Google Scholar]
- 31.Pahl H. L. Activators and target genes of Rel/NF-κB transcription factors. Oncogene 18, 6853–6866 (1999). [DOI] [PubMed] [Google Scholar]
- 32.Rothschild D. E. et al. Enhanced mucosal defense and reduced tumor burden in mice with the compromised negative regulator IRAK-M. EBioMedicine 15, 36–47 (2017). [DOI] [PMC free article] [PubMed] [Google Scholar]
- 33.Xie Q., Gan L., Wang J., Wilson I. & Li L. Loss of the innate immunity negative regulator IRAK-M leads to enhanced host immune defense against tumor growth. Molecular immunology 44, 3453–3461 (2007). [DOI] [PMC free article] [PubMed] [Google Scholar]
- 34.Reiley W. W. et al. Deubiquitinating enzyme CYLD negatively regulates the ubiquitin-dependent kinase Tak1 and prevents abnormal T cell responses. The Journal of experimental medicine 204, 1475–1485 (2007). [DOI] [PMC free article] [PubMed] [Google Scholar]
- 35.Hu X. & Ivashkiv L. B. Cross-regulation of signaling pathways by interferon-γ: implications for immune responses and autoimmune diseases. Immunity 31, 539–550 (2009). [DOI] [PMC free article] [PubMed] [Google Scholar]
- 36.Chang J.-H. et al. Ubc13 maintains the suppressive function of regulatory T cells and prevents their conversion into effector-like T cells. Nature immunology 13, 481–490 (2012). [DOI] [PMC free article] [PubMed] [Google Scholar]
- 37.Lake B. B. et al. An atlas of healthy and injured cell states and niches in the human kidney. Nature 619, 585–594 (2023). [DOI] [PMC free article] [PubMed] [Google Scholar]
- 38.Li H. et al. Transcriptomic, epigenomic, and spatial metabolomic cell profiling redefines regional human kidney anatomy. Cell metabolism 36, 1105–1125. e1110 (2024). [DOI] [PMC free article] [PubMed] [Google Scholar]
- 39.Ferreira R. M. et al. A MEF2C transcription factor network regulates proliferation of glomerular endothelial cells in diabetic kidney disease. Kidney international (2026). [DOI] [PMC free article] [PubMed] [Google Scholar]
- 40.Zhou Q. et al. Association Between NPHS2 p. R229Q and Focal Segmental Glomerular Sclerosis/Steroid-Resistant Nephrotic Syndrome. Frontiers in Medicine 9, 937122 (2022). [DOI] [PMC free article] [PubMed] [Google Scholar]
- 41.Zhang H. et al. GraphShaper: Geometry-aware Alignment for Improving Transfer Learning in Text-Attributed Graphs. arXiv preprint arXiv:2510.12085 (2025). [Google Scholar]
- 42.Grover A. & Leskovec J. in Proceedings of the 22nd ACM SIGKDD international conference on Knowledge discovery and data mining. 855–864. [DOI] [PMC free article] [PubMed]
- 43.Vaswani A. et al. Attention is all you need. Advances in neural information processing systems 30 (2017). [Google Scholar]
- 44.He K. et al. in Proceedings of the IEEE/CVF conference on computer vision and pattern recognition. 16000–16009.
- 45.Grill J.-B. et al. Bootstrap your own latent-a new approach to self-supervised learning. Advances in neural information processing systems 33, 21271–21284 (2020). [Google Scholar]
- 46.Bardes A., Ponce J. & LeCun Y. Vicreg: Variance-invariance-covariance regularization for self-supervised learning. arXiv preprint arXiv:2105.04906 (2021). [Google Scholar]
- 47.Rangel-Moreno J. et al. The development of inducible bronchus-associated lymphoid tissue depends on IL-17. Nature immunology 12, 639–646 (2011). [DOI] [PMC free article] [PubMed] [Google Scholar]
- 48.Cho K. S. et al. Pan-cancer spatial atlas of tertiary lymphoid structures. Science 392, eadz2742 (2026). [DOI] [PubMed] [Google Scholar]
- 49.Qiu Z. et al. Detection of differentially expressed genes in spatial transcriptomics data by spatial analysis of spatial transcriptomics: A novel method based on spatial statistics. Frontiers in Neuroscience 16, 1086168 (2022). [DOI] [PMC free article] [PubMed] [Google Scholar]
- 50.Moses L., Herault A., Cabon L. & Dumitrascu B. Wayfarer: A multiscale framework for spatial analysis of tumor progression. bioRxiv, 2026.2002. 2016.706245 (2026). [Google Scholar]
- 51.Schürch C. M. et al. Coordinated cellular neighborhoods orchestrate antitumoral immunity at the colorectal cancer invasive front. Cell 182, 1341–1359. e1319 (2020). [DOI] [PMC free article] [PubMed] [Google Scholar]
- 52.Gaglia G. et al. Lymphocyte networks are dynamic cellular communities in the immunoregulatory landscape of lung adenocarcinoma. Cancer cell 41, 871–886. e810 (2023). [DOI] [PMC free article] [PubMed] [Google Scholar]
- 53.Street K. et al. Slingshot: cell lineage and pseudotime inference for single-cell transcriptomics. BMC genomics 19, 477 (2018). [DOI] [PMC free article] [PubMed] [Google Scholar]
Associated Data
This section collects any data citations, data availability statements, or supplementary materials included in this article.
Data Availability Statement
Pre-training datasets are publicly available from the corresponding official repositories: Xenium (https://www.10xgenomics.com/datasets), CosMx (https://brukerspatialbiology.com/products/cosmx-spatial-molecular-imager/ffpe-dataset) and MERSCOPE (https://vizgen.com/data-release-program). Sample-level metadata is available at Supplementary Data 1. The HuBMAP reference or diseased tissue data can be accessed through the HuBMAP publication page upon acceptance of the peer-reviewed manuscript. Source data are provided with this paper.
The official repository of spaGFM is available at GitHub (https://github.com/yzhong36/spaGFM). The reproducibility repository of spaGFM is available at GitHub (https://github.com/yzhong36/spaGFM_reproducibility).
