figurec
PathRWKV: Enhancing Whole Slide Image Inference with Asymmetric Recurrent Modeling
2Nhu Department of Electrical Engineering and Computer Science, University of California, Irvine
3PuzzleLogic Pte Ltd, Singapore 229594, Singapore
Corresponding author: Fei Xia<fei.xia@uci.edu>, Zeyu Liu<zeyuliu@puzzlelogic.com>, Yueming Jin<ymjin@nus.edu.sg>
)
Abstract
Whole Slide Imaging (WSI) has become a gold standard in cancer diagnosis, inspecting multi-scale information from cellular to tissue levels. Processing an entire WSI directly is infeasible due to GPU memory constraints; thus, Multiple Instance Learning (MIL) has emerged as the standard solution by partitioning WSIs into tiles. While recent two-stage MIL frameworks partially achieve memory efficiency by decoupling tile-level extraction from slide-level modeling, they still face four limitations: (1) the conflict between training throughput and inference memory efficiency, (2) the high susceptibility to overfitting on small-scale WSI datasets with sparse supervision, (3) the disruption of spatial structural integrity during sampling-based training, and (4) the inadequate modeling of multi-scale feature interactions within long sequences. We therefore introduce PathRWKV, a novel State Space Model designed for efficient and robust WSI analysis. To resolve the computational trade-off, we propose an asymmetric structure utilizing max pooling aggregation, enabling parallelized training for high throughput and recurrent inference with constant () memory complexity. To mitigate overfitting, we employ random sampling to enhance data diversity, with a multi-task learning module to regularize feature learning on limited data. To restore spatial context, we introduce 2D sinusoidal position encoding to perceive the relative locations of tissue tiles. To capture comprehensive representations, we integrate TimeMix and ChannelMix modules, enabling dynamic multi-scale feature modeling across temporal and spatial dimensions. Experiments on 29,073 WSIs across 11 datasets demonstrate that PathRWKV outperforms 11 state-of-the-art methods on 10 datasets, establishing it as a scalable and solution with application potential.
Keywords Whole slide image analysis multiple instance learning multi-task learning state space model
1 Introduction
Pathology diagnosis plays an essential role in clinical practice, leveraging the analysis of pathological images [35, 10] to ensure accurate cancer diagnosis and treatment planning. The process begins with tissue biopsy/grossing by a specialist, and sample preparation workflows digitize these samples. This creates gigapixel-scale Whole Slide Images (WSIs) capturing both cell-level and tissue-level morphological details [10]. While WSIs contain rich, high-dimensional, multi-scale features, their colossal sizes make manual review labor-intensive and require highly specialized expertise, leading to inconsistent diagnoses across sites that could negatively impact the quality of healthcare [21, 1]. Deep learning–driven computational pathology techniques have emerged to ease pathologists’ burden and promote high-quality diagnosis by automatically identifying critical patterns in WSIs [3, 19, 31]. Recent studies have further advanced this by quantifying pathologists’ visual patterns to integrate expert cognitive strategies into diagnostic models, thereby aiming to minimize workload while maintaining precision [20]. Nevertheless, the complex, multi-scale nature of WSIs sets challenges for deep learning models to capture and integrate features robustly across different scales [37, 5].
Specifically, end-to-end training on raw, high-resolution WSIs remains infeasible due to GPU memory constraints and extreme dimensionality [31, 3]. Some studies downsample WSI to a thumbnail, while reduce computational complexity, this incurs significant information loss by discarding high-resolution details (e.g., cell morphology) critical for assessing disease progression [24, 14]. Consequently, most pipelines predominantly adopt Multiple Instance Learning (MIL) as a practical two-stage solution [13]. This approach breaks WSIs into smaller tiles (e.g., pixels from an -pixel slide) and encodes them into dense feature representations using a foundation model (e.g., Prov-GigaPath [33]). Subsequently, a slide-level backbone aggregates these compressed tile features to generate slide-level predictions [19, 28, 36]. This paradigm robustly enhances performance by enabling the processing of a larger number of tiles per iteration and leveraging the robust prior knowledge embedded in the foundation model. Accordingly, these advantages contribute to the high accuracy achieved by modern MIL frameworks [29, 20]. However, critical challenges remain unresolved as detailed below:
A primary challenge in WSI analysis arises from the drastic variation in the number of tiles per slide due to diverse tissue dimensions [29]. During training, a fixed number of tiles (e.g., 2,000) is uniformly sampled from each WSI to leverage a larger batch size. This maximizes GPU parallelization efficiency, and stabilizes gradient descent, thereby enhancing overall performance [31]. Conversely, during inference, to cover all regions for diagnostic evidences, the batch size is generally set to one to process all available tiles [3]. However, given the immense disparity in WSI dimensions (e.g., from 1,000 to over 40,000 tiles in the CAMELYON16 dataset [1] at 0.5 mpp with a 224224 patch size), processing large-scale slides can easily exceed GPU memory limits, particularly when deploying recent effective yet complex Transformers on resource-constrained edge devices [6]. This necessitates a slide-level structure that possesses parallel computing capabilities during training to handle large batch sizes, while retaining sequential processing efficiency during inference to model entire WSIs with minimal memory overhead [23].
Another critical challenge stems from the severe data inefficiency in WSI analysis, where high-capacity models struggle to generalize under the dual constraints of data scarcity and sparse supervision [27, 26]. Specifically, obtaining annotated cohorts is prohibitive, often restricting datasets to limited sizes (e.g., fewer than 3,000 slides) [35]. This scarcity is exacerbated by the weak nature of slide-level labels, which provide supervision for only a fraction of the gigapixel-resolution tissue information [3]. Consequently, despite the improved feature representations from foundation models [33, 31], the downstream aggregators remain prone to overfitting. Notably, complex structures like TransMIL [28] frequently underperform compared to simpler baselines (e.g., CLAM [19]) in such low-data regimes [27]. This necessitates strategies that maximize the utility of limited slide-level data to enhance model generalization [39, 17].
Furthermore, the disruption of spatial structural integrity during sampling-based MIL training significantly impedes the performance of permutation-variant methods. Conventional mini-batch training requires a fixed input size, and current methods primarily address this by selecting a subset of tiles to represent the whole WSI [13]. This inevitably disrupts the global spatial context. While this issue is negligible for permutation-invariant Attention-based methods (e.g., CLAM [19]), it poses a critical challenge for the current permutation-variant state-of-the-art (SOTA) paradigms, like Transformers (e.g., TransMIL [28]) and State Space Models (SSMs) (e.g., MambaMIL [34]). All of them rely on explicit modeling of spatial relationships and contextual dependencies. Consequently, the spatial information loss induced by sampling severely compromises the modeling capabilities of these structures [15]. It is imperative to develop a mechanism that can effectively recover this missing spatial context [38].
The final challenge arises as most current methods face difficulties in adequately handling multi-scale feature interactions within long sequences. Effective diagnosis relies on the complementarity between fine-grained details (e.g., cell nuclei at 40) and coarse-grained context (e.g., tissue structure at 4), and the inherent ambiguity of cellular structures theoretically necessitates fuzzy logic or high-order topological modeling [12]. This requires a multi-scale modeling capability to simultaneously handle the relationships between fine-grained local homogeneity and coarse-grained global heterogeneity [39]. However, existing methods demonstrate an inability to conduct effective multi-scale feature analysis for slide-level conclusions. Lightweight Attention-based methods benefit from simple, permutation-invariant structures but lack the capacity to capture intricate fine-grained relationships (e.g., inter-cell interactions). Conversely, while large Transformers excel at modeling local details, their generic structures often struggle to effectively align and fuse these heterogeneous multi-scale features into a unified slide-level representation. A promising solution is to model features from multiple perspectives, incorporating diverse indicators to construct a robust multi-scale understanding.

Due to the similar requirements of long context modeling and multi-scale understanding between natural language processing (NLP) and MIL, previous MIL approaches based on NLP structures have proven effective (e.g., TransMIL [28] from Transformer, MambaMIL [34] from Mamba). Among them, RWKV [23] stands out by uniquely combining the efficient parallelizable training of Transformers with the linear complexity inference of RNNs. This makes it exceptionally suitable for processing the massive, sequential feature representations inherent in WSI analysis. Motivated by these properties, we propose PathRWKV, a time-decayed SSM tailored for efficient and robust WSI analysis.
To resolve the asymmetric memory and efficiency constraints, we propose an asymmetric structure (Fig. 1) that integrates max pooling aggregation with linear attention. This design enables a seamless transition between Transformer-like parallelization for high-throughput training and RNN-like sequential processing for inference, achieving constant () memory complexity regardless of slide size. Consequently, it achieves high throughput during training while ensuring exceptional memory efficiency during inference.
To mitigate overfitting and data scarcity inherent in weak supervision, we adopt a random sampling strategy with the multi-task learning (MTL) module. Random sampling acts as a dynamic data augmentation technique, counteracting the inductive bias of deterministic sampling and exposing the model to diverse subsets of tissue regions. The MTL module introduces auxiliary supervision signals to regularize feature space, preventing the model from memorizing noise in limited training samples. Together, these strategies exploit the potential of limited annotations and bolster model generalizability by capturing intrinsic inter-task dependencies.
To address the disruption of spatial structural integrity caused by random sampling, we leverage 2D sinusoidal position encoding (2D PE) to embed unique coordinate-based information into each tile feature. It is critical for the permutation-variant PathRWKV to recognize relative positions and reconstruct spatial relationships. This design effectively equips the model to preserve global spatial context, bridging the significant distributional gap between the stochastic bag-of-tiles input used during training and the ordered, sequential slide processing required for inference.
To tackle complex multi-scale feature interactions, we incorporate TimeMix and ChannelMix modules. The TimeMix module focuses on capturing long-range spatial dependencies and local homogeneity across the sequence of tiles, while the ChannelMix module focuses on high-level abstract semantic patterns. By jointly modeling these dimensions, the structure ensures a robust representation that encompasses both fine-grained cellular details and coarse-grained global tissue heterogeneity across the entire slide.
This work makes the following contributions:
-
•
We propose PathRWKV, a novel SSM for efficient and robust slide-level modeling in computational pathology.
-
•
We design an asymmetric slide-level structure that combines max pooling aggregation, enabling efficient parallelized training and recurrent inference with constant () memory complexity. Built upon this structure, we further introduce random sampling strategy and MTL module to mitigate overfitting under weak supervision and improve data efficiency and generalization.
-
•
We restore spatial context by incorporating 2D PE, and enhance multi-scale representation learning via TimeMix and ChannelMix modules, enabling dynamic interaction between fine-grained cellular features and coarse-grained tissue structures.
-
•
We conduct extensive experiments on 29,073 WSIs across 11 public datasets, demonstrating SOTA performance on 10 datasets. Beyond accuracy, these results highlight PathRWKV’s potential as a scalable and reliable framework for large-scale pathological analysis, establishing a new perspective where the asymmetry between training and inference serves as a powerful inductive principle for computational pathology. The code is publicly available at https://github.com/Puzzle-Logic/PathRWKV.
2 Related Work
The two-stage MIL paradigm becomes the mainstream recently, with the first stage extracts tile-level features, and the second aggregates them for slide-level predictions. Initial attempts within this paradigm employed simple aggregation strategies, such as average pooling (SlideAve) and max pooling (SlideMax) from MINNs [30], to combine tile features into a slide-level representation. While computationally efficient, these methods simply treat all tiles embeddings equally or focus exclusively on the most salient one, often failing to capture the complex, fine-grained information required for accurate diagnosis. To address this limitation, ABMIL [13] introduced a gated attention mechanism that adaptively weights tiles to enable instance-level interpretability. This simple yet effective mechanism has been widely adopted by most modern methods. Building on this, CLAM [19] imposes instance clustering constraints to encourage diverse and discriminative feature learning, thereby improving model generalization. DSMIL [16] further incorporates contrastive learning by combining instance- and bag-level supervision to better distinguish informative tiles. To address the challenge of limited data scale, DTFD-MIL [36] proposes a double-tier feature distillation framework that utilizes pseudo-bags to virtually expand the training set, enhancing robustness in small-sample scenarios. Despite their widespread adoption, these attention-based methods often struggle to fully capture complex spatial dependencies within WSIs due to their inherent permutation invariance.
Transformers have been introduced to alleviate the permutation invariance of attention-based methods and improve global context modeling. A representative method, TransMIL [28], employs a Transformer-based structure that explicitly encodes positional and structural relationships among tiles, enabling more effective global spatial reasoning. Furthermore, Prov-GigaPath [33] enhances global information flow through a dilated attention mechanism, leveraging efficient sequence modeling structures like LongNet [6] to improve scalability. Despite these advancements, Transformers still face challenges regarding overfitting and high memory consumption, especially when trained on small-scale datasets.
State Space Models (SSMs) have emerged as a compelling alternative, balancing the efficiency of conventional attention methods with the long-range modeling capabilities of Transformers. S4MIL [9] introduces the Structured State Space Sequence (S4) model to capture long-range dependencies across tiles. By imposing a structured state representation, it mitigates the overfitting risks associated with data-hungry Transformers. Building on this, MambaMIL [34] integrates the selective state space model, Mamba, into the MIL pipeline, enabling linear scaling and selective information flow across tiles. Similarly, MamMIL [8] adapts the Mamba structure to model WSIs as long sequences, effectively capturing bidirectional contextual dependencies with minimal computational overhead. These SSM-based approaches not only offer superior scalability but also enhance generalization through their inherent inductive biases, making them particularly well-suited for WSI analysis on limited datasets. However, most current SSM-based approaches retain attention-based pooling mechanisms for final aggregation. This design necessitates storing features from all tiles, reintroducing an memory bottleneck during inference that undermines the inherent linear efficiency of the SSM backbone.
3 Methods

3.1 Overview of the MIL Pipeline
Fig. 2a illustrates the overall PathRWKV pipeline. Following existing works [18], each WSI is first loaded at a target resolution (e.g., 0.5 microns per pixel (mpp)) and partitioned into a non-overlapping grid of tiles of size . To ensure data quality, a two-stage filtering protocol is employed. First, tiles with tissue coverage below a predefined threshold (e.g., of the tile area) are discarded. Second, tiles with pixel variance falling below a quantitative cutoff (e.g., , where denotes the normalized pixel intensity in [0,1]) are removed. This ensures that only informative tiles are retained for downstream tasks. After pre-processing and filtering, each tile is embedded into a dense semantic feature vector (Fig. 2a) using a pathological foundation model (e.g., Prov-GigaPath [33]). This embedding process enhances both the training efficiency and performance of the slide-level MIL. During training, PathRWKV processes a randomly shuffled subset of tiles to facilitate efficient multi-slide learning; conversely, during inference, it utilizes the complete sequential tile sequence from the WSI. Finally, the slide-level output features from PathRWKV are passed to the MTL module to generate predictions for each task (e.g., cancer subtyping, tumor grading, overall survival).
3.2 The PathRWKV Slide-level Backbone
PathRWKV serves as the backbone for slide-level feature modeling, consisting of 2 blocks with a hidden dimension of 768, and 12 heads. The input tile features are first combined with 2D sinusoidal Position Encoding (2D PE) to restore spatial relationships disrupted during the sampling process. Subsequently, these features are processed by the PathRWKV blocks (Fig. 2b). Each block comprises a TimeMix module and a ChannelMix module, integrated with layer normalization and residual connections. The TimeMix module dynamically captures multi-scale inter-tile dependencies via the temporal dimension, while the ChannelMix module focuses on intra-tile feature interactions across the channel dimension. Output features from the final PathRWKV block are aggregated via max pooling to produce the final slide-level representation.
Fig. 2c illustrates the key mathematical operations within the TimeMix and ChannelMix modules. The TimeMix module is specifically designed to capture multi-scale temporal dependencies among tiles. It effectively integrates fine-grained local interactions via token shifting and interpolation with coarse-grained global context via time-decayed linear attention, combining the strengths of Transformers [7] and RNNs [11].
To capture short-range, fine-grained dependencies between adjacent tiles, the module first employs a token-shift mechanism, TimeShift. A shifted version of the input , denoted as , is generated using zero-padding:
| (1) |
The current input is then mixed with via data-dependent linear interpolation (ddlerp). Unlike static interpolation, ddlerp dynamically computes the mixing coefficient using a Low-Rank Adaptation (LoRA) mechanism:
| (2) | ||||
This mechanism allows the model to adaptively aggregate local information from the immediate predecessor based on the current context, ensuring that high-frequency local variations are preserved before global processing.
Following local aggregation, the interpolated features are projected into five vectors: receptance , key , value , time-decay , and gate . To capture long-range, coarse-grained dependencies across the entire slide sequence, we employ a time-decayed linear attention mechanism. Notably, the decay rate is modulated by a LoRA projection, allowing for data-dependent decay speeds that can adaptively focus on relevant historical context. The global linear attention is computed efficiently as:
| (3) |
Crucially, this formulation can be switched to a recurrent structure, which underpins our asymmetric design. By maintaining a recurrent state , the model propagates global context sequentially:
| (4) | ||||
Finally, the output is gated by and projected by :
| (5) |
The ChannelMix module focuses on intra-tile feature interactions. Specifically, it employs learnable linear projections () to blend information across the channel dimension for each tile independently. This is coupled with a Squared ReLU activation:
| (6) |
which induce robust non-linear transformations, enabling the extraction of complex morphological features within each tile.
3.3 Asymmetric Structure and Max Pooling Aggregation
As illustrated in Fig. 1, distinct from the standard token-by-token processing in original RWKV, we propose a novel hybrid set-by-set recurrent architecture tailored for high-resolution WSI analysis. While leveraging the mathematical efficiency of linear attention, our core innovation lies in the asymmetric formulation of slide-level modeling to resolve the memory bottlenecks inherent in existing SSMs.
During the training phase, we adopt a set-based parallel strategy to maximize throughput. Instead of processing tiles sequentially, the model ingests a fixed number of sampled tiles as a dense batch. By utilizing a parallel CUDA kernel, we compute cumulative states and gradients simultaneously. This design fully exploits the massive parallelism of modern GPUs, facilitating rapid backpropagation and stable convergence compared to pure recurrent training.
During the inference phase, we introduce a streaming recurrent mechanism to achieve constant spatial complexity. A critical limitation in previous SSM-MIL methods (e.g., S4MIL, MambaMIL) is their reliance on Attention-based aggregation, which necessitates storing all tile features () for the final calculation, causing memory overflows on gigapixel slides. To overcome this, our architecture decomposes the WSI into sequential chunks. A latent state S (of size HeadSizeHeadSize) acts as a memory carrier, propagating context across chunks via a recurrent kernel.
Furthermore, a critical bottleneck remains in the aggregation mechanism of existing frameworks, including recent SSMs. While SSM backbones theoretically allow constant spatial complexity () during inference, they typically adapt the Gated Attention mechanism from ABMIL [13] for slide-level aggregation. This approach necessitates computing a global Softmax normalization term across all tiles:
| (7) |
Consequently, the feature vectors of all tiles must be retained in GPU memory to calculate the denominator until the entire slide is processed, forcing the inference memory complexity to scale linearly with the slide size (). This disrupts the memory efficiency gained by the SSM backbone.
To achieve a fully memory-efficient pipeline, we integrate the backbone’s sequential processing with a streaming aggregation strategy. We decompose the WSI into bags aligned with the inference chunks, and identify the feature-wise max operation as the optimal choice due to its recursive update property. Given the tile encoder , we define the local summary and the combination rule as:
| (8) |
We then update the slide-level representation sequentially:
| (9) |
where represents the summary of the first bags. Unlike attention mechanisms, this design decouples memory usage from sequence length, achieving true space complexity during inference. This enables PathRWKV to process arbitrarily large slides on edge devices while preserving consistency with the ideal global computation. Comprehensive theoretical analysis, including proofs for the unbiased nature of the gradients and memory complexity comparisons, are provided in the supplementary materials.
3.4 Random Sampling and 2D Position Encoding
Given the high dimensionality of WSIs and the sparse supervision signal, models are prone to overfitting. To mitigate this, we employ the random sampling strategy during training. Instead of processing the entire slide or a fixed region, we randomly sample a subset of tiles from the WSI in each iteration. This approach acts as a strong data augmentation technique, preventing the model from memorizing specific tile sequences and enhancing its generalization capabilities.
However, a critical side effect of random sampling is the disruption of the intrinsic 2D spatial structure and the anatomical adjacency of the tissue microenvironment. This is the main advantage of recent permutation-variant methods (e.g., MmabaMIL [34]) compared to early permutation-invariant methods (e.g., ABMIL [13]). To compensate for this loss of spatial context and enable PathRWKV to model geometry-aware dependencies, we introduce a 2D PE. Formally, let denote the feature embedding of the -th tile, and represent its normalized spatial coordinates. We employ sinusoidal functions to map these coordinates into a continuous embedding space:
| (10) | ||||
where is a scaling factor and . The final spatial embedding is constructed by concatenating the encodings of horizontal and vertical coordinates and injected into the tile features via addition: . This ensures that geometric relationships are restored regardless of the sampling order.
3.5 Multi-task Learning
Finally, to maximize the utility of limited annotated data and enhance training efficiency, we incorporate a multi-task learning (MTL) module. It comprises multiple prediction heads, allowing the model to learn from diverse clinical objectives simultaneously. By leveraging task-wise correlations, the model extracts more discriminative features, further reducing the risk of overfitting on the feature distribution of a single task. We employ Cross-Entropy, Cox proportional hazards, and L1 losses for classification, survival analysis, and regression tasks, respectively. The total loss is aggregated as , where represents the number of task heads. Crucially, gradients are computed only for tasks with available labels, enabling flexible training on partially annotated datasets.
| Dataset | Metric | SlideAve | SlideMax | ABMIL | CLAM | DSMIL | DTFD-MIL | TransMIL | GigaPath | S4MIL | MamMIL | MambaMIL | PathRWKV |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| [30] | [30] | [13] | [19] | [16] | [36] | [28] | [33] | [9] | [8] | [34] | Ours | ||
| PANDA | Acc.[%] | 63.92‡ | 62.74‡ | 76.06† | 75.97∗ | 76.39∗ | 75.53† | 75.79∗ | 73.58† | 75.93† | 75.70† | 75.99† | 76.45 |
| AUC[%] | 89.53‡ | 88.54‡ | 94.71† | 94.74∗ | 94.20∗ | 93.93∗ | 93.87∗ | 93.67∗ | 94.07∗ | 94.81∗ | 94.30† | 94.89 | |
| F1[%] | 60.76‡ | 55.94‡ | 70.30† | 69.90∗ | 70.12∗ | 70.03∗ | 69.02† | 68.06† | 70.70† | 69.94∗ | 70.56† | 70.81 | |
| CAMELYON16 | Acc.[%] | 68.99‡ | 72.87‡ | 98.45∗ | 98.45∗ | 92.25∗ | 98.45∗ | 98.45∗ | 98.45∗ | 98.45∗ | 97.67∗ | 97.67∗ | 98.45 |
| AUC[%] | 55.19‡ | 74.44‡ | 97.90∗ | 98.77∗ | 96.51† | 98.65∗ | 98.80∗ | 97.93† | 98.92∗ | 98.67∗ | 99.03† | 99.11 | |
| F1[%] | 62.70‡ | 70.29† | 98.34∗ | 98.34∗ | 91.47† | 98.34∗ | 98.34∗ | 98.34∗ | 98.34∗ | 97.52∗ | 97.50∗ | 98.34 | |
| IMP-CRS-2024 | Acc.[%] | 92.33‡ | 91.67† | 94.67∗ | 94.22† | 94.44∗ | 94.33∗ | 94.44∗ | 94.56∗ | 94.78∗ | 94.22† | 94.33∗ | 94.78 |
| AUC[%] | 98.59‡ | 98.56† | 99.36† | 99.42∗ | 99.40† | 99.41† | 99.44† | 99.43† | 99.44∗ | 99.41† | 99.43∗ | 99.45 | |
| F1[%] | 92.67‡ | 92.08† | 94.90∗ | 94.40‡ | 94.69∗ | 94.67∗ | 94.54† | 94.83∗ | 94.85∗ | 94.41∗ | 94.52∗ | 95.09 | |
| TCGA-BRCA | Acc.[%] | 59.20∗ | 55.19∗ | 59.30† | 59.39† | 59.39† | 59.30† | 59.84† | 59.30† | 59.39† | 59.30† | 59.30∗ | 60.11 |
| AUC[%] | 61.14† | 56.97∗ | 63.42† | 63.10∗ | 64.32∗ | 64.18∗ | 61.47† | 64.12∗ | 63.71∗ | 59.84∗ | 59.67† | 64.35 | |
| F1[%] | 25.82∗ | 26.09∗ | 27.54† | 30.00∗ | 30.04∗ | 28.64∗ | 26.57∗ | 29.41∗ | 29.59† | 28.73∗ | 25.88∗ | 30.40 | |
| TCGA-GBM | Acc.[%] | 98.60∗ | 97.90† | 98.60∗ | 98.60∗ | 99.30† | 98.60∗ | 97.90† | 99.30∗ | 99.30∗ | 98.60∗ | 99.30† | 100.00 |
| AUC[%] | 66.27† | 65.71∗ | 66.67∗ | 66.67† | 66.51∗ | 66.19∗ | 65.87∗ | 66.59† | 66.67∗ | 66.67∗ | 66.67∗ | 66.67 | |
| F1[%] | 74.65∗ | 49.47∗ | 74.65† | 74.65∗ | 74.65† | 74.65∗ | 49.47∗ | 89.82† | 89.82∗ | 74.65∗ | 89.82∗ | 100.00 | |
| TCGA-LGG | Acc.[%] | 68.81† | 68.81† | 68.14† | 61.07∗ | 68.47∗ | 68.15† | 68.44† | 68.46† | 66.44∗ | 68.50† | 68.14∗ | 69.13 |
| AUC[%] | 71.80† | 71.67† | 71.89∗ | 67.59∗ | 71.95† | 71.79† | 67.88† | 71.68∗ | 72.10∗ | 71.68∗ | 71.89∗ | 72.61 | |
| F1[%] | 68.54† | 68.00† | 68.23† | 60.28∗ | 68.46∗ | 68.38∗ | 66.44∗ | 62.35 | 63.89∗ | 68.18∗ | 66.69† | 68.96 | |
| TCGA-CESC | Acc.[%] | 62.96∗ | 62.96† | 59.26† | 66.67∗ | 70.37† | 59.26∗ | 66.67∗ | 67.78† | 55.56† | 66.67† | 59.26∗ | 70.37 |
| AUC[%] | 68.13† | 56.59† | 62.09† | 65.93† | 70.88∗ | 68.13† | 70.33∗ | 71.43∗ | 56.04‡ | 67.03∗ | 58.24‡ | 75.27 | |
| F1[%] | 62.50∗ | 62.91∗ | 59.03† | 66.67∗ | 69.32† | 58.35∗ | 66.48∗ | 67.75† | 55.49† | 65.92∗ | 58.35† | 70.33 | |
| TCGA-ESCA | Acc.[%] | 47.22† | 38.89† | 47.22† | 55.56† | 47.22† | 47.22† | 47.22∗ | 55.56∗ | 50.00† | 50.00∗ | 55.56∗ | 55.56 |
| AUC[%] | 65.00∗ | 48.57† | 63.35∗ | 65.09† | 64.39† | 65.33∗ | 64.68† | 65.35† | 65.10† | 65.09∗ | 65.47† | 65.96 | |
| F1[%] | 38.67∗ | 28.94† | 39.09† | 37.20† | 26.67∗ | 32.46† | 41.44† | 44.14† | 43.52† | 35.08† | 32.22† | 48.31 | |
| TCGA-LIHC | C-Index | 0.522† | 0.533∗ | 0.549† | 0.546∗ | 0.553∗ | 0.581† | 0.575∗ | 0.573∗ | 0.550† | 0.529† | 0.574∗ | 0.584 |
| TCGA-BLCA | C-Index | 0.472∗ | 0.561∗ | 0.573∗ | 0.572† | 0.571† | 0.567† | 0.559† | 0.572∗ | 0.576† | 0.538† | 0.575∗ | 0.579 |
| TCGA-LUNG | C-Index | 0.490† | 0.534∗ | 0.537† | 0.550† | 0.518∗ | 0.535∗ | 0.543∗ | 0.505† | 0.525† | 0.529† | 0.547∗ | 0.518 |
4 Experiments
4.1 Datasets and Downstream Tasks
We evaluated PathRWKV on 11 datasets across 9 downstream tasks covering diverse diagnostic scenarios, as shown in Fig. 3, to demonstrate its performance and generalizability. The PANDA [2] dataset with the ISUP Grade task assesses prostate cancer aggressiveness; CAMELYON16 [1] with the Breast Metastasis task classifies lymph nodes as normal or tumorous; IMP-CRS-2024 [22] with the CRC-Tumor task identifies tumor tissues in colorectal images. The TCGA [4] datasets cover multiple cancer types and tasks: TCGA-BRCA with the IHC-HER2 task predicts HER2 receptor status from H&E-stained slides; TCGA-GBM with the Histological Diagnosis task classifies glioblastoma subtypes based on morphology; TCGA-LGG with the Tumor Stage task predicts the WHO grade of lower-grade gliomas; TCGA-CESC with the Lymphovascular Involvement task detects the presence of lymphovascular invasion; TCGA-ESCA with the Cancer Grade task assesses the histological differentiation grade of esophageal carcinoma; and TCGA-LIHC, TCGA-BLCA, and TCGA-LUNG, the combination of TCGA-LUAD and TCGA-LUSC, with the Overall Survival task predict patient survival time in months from liver, bladder, and lung tissue morphology, respectively.

4.2 Implementation Details
We use the UnPuzzle framework [18] for preprocessing, where each WSI is tessellated into patches at 0.5 mpp and embedded using the tile-level encoder of Prov-GigaPath [33]. All models are initialized from scratch and trained for 100 epochs using the AdamW optimizer and a cosine decay scheduler with a final learning rate factor of 0.1. We conduct a grid search over ten learning rates ( to ) and employ early stopping with a patience of 10 epochs based on validation loss. During training, we use a batch size of 4 and randomly sample a maximum of 2,000 tiles per WSI. For evaluation, we select the checkpoint with the lowest validation loss, use a batch size of 1, and process all tiles per WSI. We report the average performance of the top-3 results for each metric. For statistical reporting, significance was evaluated using Welch’s t-test [32] across these top-3 performing learning rate configurations to compare each method against PathRWKV. All experiments were conducted on 4 NVIDIA RTX4090 GPUs using Python 3.12.12, PyTorch 2.9.1, and CUDA 12.8.
4.3 Comparison with SOTA Methods
To demonstrate the effectiveness of PathRWKV for slide-level WSI modeling, we compared it against 11 state-of-the-art (SOTA) methods, including SlideAve and SlideMax from MINNs [30], ABMIL [13], CLAM [19], DSMIL [16], DTFD-MIL [36], TransMIL [28], Prov-GigaPath [33], S4MIL [9], MambaMIL [34], and MamMIL [8].
As presented in Tab. 1, PathRWKV demonstrates superior performance and robust generalizability, achieving SOTA results on 10 out of 11 datasets across 9 distinct downstream tasks. Specifically, on standard classification benchmarks such as CAMELYON16 and IMP-CRS-2024, most deep learning-based methods achieve high metrics ( Accuracy, AUC, and F1), with the exception of simple pooling strategies, SlideAve and SlideMax, that lack the representational capacity for comprehensive slide-level modeling. Among high-performing models, PathRWKV consistently secures the highest scores across all three metrics.
In contrast, the TCGA datasets present a significantly more challenging scenario, where the average performance of most methods drops to approximately 70% due to the intrinsic complexity and heterogeneity of the samples. Despite these challenges, PathRWKV establishes its efficacy on the majority of TCGA datasets, validating the capability of the proposed TimeMix and ChannelMix modules to capture complex pathological dependencies. However, we observe a performance gap on the TCGA-LUNG overall survival task, where MambaMIL achieves the leading performance. We attribute this to the inherent trade-off of our max pooling strategy. While it ensures inference memory, it focuses on the most salient features and may inadvertently discard global contextual cues (e.g., total tumor burden) that are beneficial for specific prognostic predictions, which Attention mechanism in MambaMIL preserve better. Nevertheless, the strong performance of both PathRWKV and MambaMIL underscores the structural advantage of SSMs over conventional pooling models and Transformers in modeling multi-scale relationships within WSIs.


A core innovation of PathRWKV is its asymmetric design, which fundamentally optimizes GPU memory utilization during inference. Fig. 5 compares the memory consumption profiles of various methods as the number of input tiles increases. Conventional attention-based methods (e.g., ABMIL, CLAM), Transformers (e.g., TransMIL, Prov-GigaPath), and even recent linear-complexity models (e.g., MambaMIL) exhibit linear memory growth (). Although these SSM-based approaches utilize linear attention mechanisms similar to PathRWKV, they typically rely on the Gated Attention mechanism from ABMIL [13] for final aggregation. This strategy requires matrix multiplication between the complete input and output tensors to compute attention scores, necessitating the retention of the entire input tensor in GPU memory until the output is generated. This dependency causes memory usage to scale linearly with sequence length, effectively negating the inherent efficiency advantages of the SSM backbone and severely constraining applicability to large-scale WSIs in resource-limited environments. In contrast, by equal contribution of linear attention and max aggregation strategy, PathRWKV achieves constant memory consumption (), as evidenced by the flat trajectory in Fig. 5. This efficiency confirms that our recurrent inference formulation enables sequential iteration over WSI tiles without caching historical states, successfully resolving the trade-off between training efficiency and inference scalability. Notably, while PathRWKV exhibits linear time complexity () same with other methods, it maintains a competitive inference speed, effectively balancing its relatively large parameter size for complex feature modeling with computational efficiency.
To further assess the interpretability of our framework, Fig. 4 visualizes the Class Activation Maps (CAMs) for representative samples from the CAMELYON16 dataset. Note that, as standard attention maps are not directly obtainable from Prov-GigaPath and S4MIL, we visualize their saliency maps instead. Consistent with quantitative findings, SlideAve and SlideMax fail to generate meaningful activation patterns due to their simplistic aggregation logic. Compared with the ground truth, attention-based methods (e.g., ABMIL, CLAM) tend to assign uniform weights across the entire region of interest, demonstrating a limited capacity to distinguish fine-grained intratumoral heterogeneity. Furthermore, they exhibit relatively higher attention scores in normal regions. Among transformers, TransMIL misdirects attention to incorrect areas, while Prov-GigaPath focuses on normal regions in the second sample; this is likely attributable to overfitting on the small-scale dataset. In contrast, all SSMs successfully detect the accurate regions. Notably, PathRWKV not only accurately highlights global tumor regions but also delineates local feature intensity variances through its heatmap distribution. This visualization validates the effectiveness of the multi-scale modeling facilitated by the Time Mix and Channel Mix modules, demonstrating PathRWKV’s ability to extract hierarchically significant pathological features.

5 Discussion
To rigorously evaluate the contribution of each component within PathRWKV and validate our design choices, we conducted a comprehensive series of ablation studies. The results are summarized in Fig. 6.
5.1 Validation of Asymmetric Design and Aggregation
A core innovation of PathRWKV is the asymmetric structure, designed to resolve the conflict between training throughput and inference memory efficiency. This design is predicated on two critical hypotheses: first, that a model trained on short sequences can effectively generalize to full-length WSIs during inference; and second, that max pooling serves as a sufficient and efficient aggregator for slide-level features. To validate these premises, we conducted ablation studies on each component.
Inference Scalability. Our asymmetric protocol involves training on a fixed subsample (2,000 tiles) while inferring on the entire WSI (up to 40,000+ tiles). Fig. 6a analyzes the impact of inference sequence length on performance. Despite the potential distribution shift caused by the length discrepancy, PathRWKV exhibits a continuous performance improvement as the number of inference tiles increases. The steepest performance gains coincide with the peak of the WSI tile count distribution (approx. 8,000–12,000 tiles), indicating that the model effectively integrates information from the entire slide. This confirms that our recurrent backbone successfully captures long-range dependencies and generalizes well to sequence lengths far exceeding those seen during training.
Aggregation Strategy. The choice of aggregation function dictates both the representation quality and memory complexity. While Gated Attention (Attn) is the standard in MIL, it necessitates storing all tile features in memory to compute global softmax weights, leading to memory usage. In contrast, our proposed streaming max pooling strategy maintains complexity. As shown in Fig. 6b, max pooling demonstrates remarkable competitiveness. Compared to Attention, it achieves comparable performance on CAMELYON16 and substantially higher Accuracy and F1 scores on TCGA-GBM (Acc: 0.993 vs. 0.986; F1: 1.000 vs. 0.747). Crucially, max pooling aligns with the worst-pattern diagnostic principle in pathology, where the presence of a specific high-grade lesion often dictates the diagnosis, rendering the global average less relevant. However, we acknowledge the limitation that strictly selecting the maximum feature may discard information regarding tumor burden and the global microenvironment, which are valuable for survival analysis. This is reflected in the TCGA-LIHC task, where Attention slightly outperforms max pooling (0.600 vs. 0.584) by capturing global context. Nevertheless, given the massive efficiency gain ( vs. memory), max pooling represents an optimal trade-off for efficient WSI modeling.
5.2 Spatial-Temporal Robustness
To address the overfitting risks on small-scale datasets and the loss of spatial structure due to sampling, we introduced random sampling paired with 2D PE.
Sampling Strategy. Fig. 6c compares four sampling strategies. Sequential sampling feeds image features and coordinates according to their original extraction order, maintaining a deterministic sequence. Random sampling introduces a global random permutation, mitigating potential biases associated with the raster scanning order. Z-order sampling [25] utilizes a space-filling curve to retain 2D spatial locality within the flattened 1D sequence. Local-box sampling prioritizes dense local contexts by randomly selecting centroids and querying spatial neighbors. Intuitively, structure-preserving strategies like Sequential or Z-Order might seem superior for an RNN-based model like PathRWKV. However, the empirical results counter-intuitively favor random sampling, which achieves the highest metrics on CAMELYON16 and TCGA-GBM. We hypothesize that random sampling acts as a potent data augmentation technique, breaking the model’s reliance on specific raster-scanning orders and preventing overfitting to incidental sequence patterns. While it disrupts local spatial continuity, it forces the model to learn more robust, permutation-invariant representations.
2D Position Encoding. The efficacy of random sampling is intrinsically linked to the inclusion of 2D PE. As random sampling discards the implicit spatial order, PE is essential for explicitly injecting coordinate information back into the features. Fig. 6d corroborates this, showing that adding PE consistently maintains or enhances performance across tasks (e.g., boosting TCGA-LIHC C-Index from 0.555 to 0.584). This confirms that PathRWKV utilizes these encodings to reconstruct the spatial context of the tissue microenvironment, thereby mitigating the structural information loss caused by random sampling.
5.3 Generalization and Optimization
Finally, we analyzed the components designed to enhance model generalization under data-constrained conditions.
Hidden Dimension. We investigated the impact of model capacity by varying the hidden dimension (Fig. 6e). Increasing does not linearly translate to better performance. While yields the highest AUC on CAMELYON16, it degrades performance on the smaller TCGA-LIHC dataset, likely due to overfitting. Conversely, offers the optimal balance, achieving the highest performance on TCGA-GBM and competitive results elsewhere. This finding underscores the importance of matching model complexity to the scale of available pathological data, validating our choice of 768 as the default configuration.
Multi-task Learning. The MTL module is designed to regularize feature learning by leveraging auxiliary tasks. Fig. 6f illustrates the performance of various backbones with and without MTL on the TCGA-LUNG dataset. The results demonstrate that our MTL module is a versatile plugin, improving the performance of most baselines (e.g., boosting ABMIL and CLAM). While there are marginal drops in specific cases for single-task specialists (e.g., a 0.4% drop for DSMIL on Tumor Stage), the overall trend signifies that learning shared representations across related clinical tasks effectively reduces overfitting and improves the robustness of the slide-level features.
Limitations. Despite the promising results, we acknowledge certain limitations in our current study. Specifically, there is a potential risk associated with the streaming max pooling strategy in other complex downstream clinical tasks, as it may discard subtle contextual cues. Furthermore, our current evaluation relies exclusively on Prov-GigaPath features, highlighting the need for future research to validate PathRWKV across a more diverse range of pathology foundation models.
6 Conclusion
In conclusion, this work proposed PathRWKV, a novel slide-level modeling framework that introduces an asymmetric training and inference paradigm, provides a principled solution to long-standing challenges in whole slide image analysis. To the best of our knowledge, PathRWKV is the first approach to explicitly decouple slide-level training and inference within a unified structure, enabling robust learning during parallelized training while preserving holistic slide reasoning at inference. Through the integration of asymmetric state space modeling, random tile sampling with multi-task learning regularization, 2D sinusoidal position encoding, and multi-scale feature mixing, PathRWKV effectively addresses weak supervision, data scarcity, disrupted spatial context, and heterogeneous multi-scale feature interactions. Extensive experiments on 29,073 whole slide images across 11 public datasets validating its effectiveness and reliability, demonstrating its strong potential to support real-world clinical workflows. We believe PathRWKV establishes a new perspective on slide-level modeling by showing that asymmetry between training and inference is not a limitation, but a powerful inductive principle for scalable and trustworthy computational pathology.
7 Acknowledgments
We gratefully acknowledge the contributions of several collaborators, particularly Haowen Hou from the National University of Singapore, for their invaluable support. We also extend our gratitude to Bo Peng from the RWKV Project under the Linux Foundation AI & Data for their insightful suggestions and guidance.
References
- [1] (2017) Diagnostic assessment of deep learning algorithms for detection of lymph node metastases in women with breast cancer. Jama 318 (22), pp. 2199–2210. Cited by: §1, §1, §4.1.
- [2] (2022) Artificial intelligence for diagnosis and gleason grading of prostate cancer: the panda challenge. Nature medicine 28 (1), pp. 154–163. Cited by: §4.1.
- [3] (2019) Clinical-grade computational pathology using weakly supervised deep learning on whole slide images. Nature medicine 25 (8), pp. 1301–1309. Cited by: §1, §1, §1, §1.
- [4] (2016) TCGAbiolinks: an r/bioconductor package for integrative analysis of tcga data. Nucleic acids research 44 (8), pp. e71–e71. Cited by: §4.1.
- [5] (2023) Deep multi-magnification similarity learning for histopathological image classification. IEEE Journal of Biomedical and Health Informatics 27 (3), pp. 1535–1545. Cited by: §1.
- [6] (2023) Longnet: scaling transformers to 1,000,000,000 tokens. arXiv preprint arXiv:2307.02486. Cited by: §1, §2.
- [7] (2020) An image is worth 16x16 words: transformers for image recognition at scale. arXiv preprint arXiv:2010.11929. Cited by: §3.2.
- [8] (2024) Mammil: multiple instance learning for whole slide images with state space models. In 2024 IEEE International Conference on Bioinformatics and Biomedicine (BIBM), pp. 3200–3205. Cited by: §2, Table 1, §4.3.
- [9] (2023) Structured state space models for multiple instance learning in digital pathology. In International Conference on Medical Image Computing and Computer-Assisted Intervention, pp. 594–604. Cited by: §2, Table 1, §4.3.
- [10] (2020) Whole slide imaging: technology and applications. Advances in Anatomic Pathology 27 (4), pp. 251–259. Cited by: §1.
- [11] (1997) Long short-term memory. Neural computation 9 (8), pp. 1735–1780. Cited by: §3.2.
- [12] (2024) High-order topology for deep single-cell multiview fuzzy clustering. IEEE Transactions on Fuzzy Systems 32 (8), pp. 4448–4459. Cited by: §1.
- [13] (2018) Attention-based deep multiple instance learning. In International conference on machine learning, pp. 2127–2136. Cited by: §1, §1, §2, §3.3, §3.4, Table 1, §4.3, §4.3.
- [14] (2024) Whole slide image understanding in pathology: what is the salient scale of analysis?. BioMedInformatics 4 (1), pp. 489–518. Cited by: §1.
- [15] (2023) Improving deep learning-based segmentation of diatoms in gigapixel-sized virtual slides by object-based tile positioning and object integrity constraint. Plos one 18 (2), pp. e0272103. Cited by: §1.
- [16] (2021) Dual-stream multiple instance learning network for whole slide image classification with self-supervised contrastive learning. In Proceedings of the IEEE/CVF conference on computer vision and pattern recognition, pp. 14318–14328. Cited by: §2, Table 1, §4.3.
- [17] (2023) Task-specific fine-tuning via variational information bottleneck for weakly-supervised pathology whole slide image classification. In Proceedings of the IEEE/CVF conference on computer vision and pattern recognition, pp. 7454–7463. Cited by: §1.
- [18] (2025) UnPuzzle: a unified framework for pathology image analysis. External Links: 2503.03152, Link Cited by: §3.1, §4.2.
- [19] (2021) Data-efficient and weakly supervised computational pathology on whole-slide images. Nature Biomedical Engineering 5 (6), pp. 555–570. Cited by: §1, §1, §1, §1, §2, Table 1, §4.3.
- [20] (2025) Deep learning quantifies pathologists’ visual patterns for whole slide image diagnosis. Nature Communications 16 (1), pp. 5493. Cited by: §1, §1.
- [21] (2019) Digital pathology and artificial intelligence. The lancet oncology 20 (5), pp. e253–e261. Cited by: §1.
- [22] (2021) CAD systems for colorectal cancer from wsi are still not ready for clinical acceptance. Scientific Reports 11 (1), pp. 14358. Cited by: §4.1.
- [23] (2024) Eagle and finch: rwkv with matrix-valued states and dynamic recurrence. arXiv preprint arXiv:2404.05892. Cited by: §1, §1.
- [24] (2019) To what extent does downsampling, compression, and data scarcity impact renal image analysis?. External Links: 1909.09945, Link Cited by: §1.
- [25] (2025) One leaf knows autumn: a piece of data-model facilitates efficient cancer prognosis with histological and genomic modalities. In Workshop on Large Language Models and Generative AI for Health at AAAI 2025, Cited by: §5.2.
- [26] (2024) Pathology-knowledge enhanced multi-instance prompt learning for few-shot whole slide image classification. In European conference on computer vision, pp. 196–212. Cited by: §1.
- [27] (2024) Dual-channel prototype network for few-shot pathology image classification. IEEE Journal of Biomedical and Health Informatics 28 (7), pp. 4132–4144. Cited by: §1.
- [28] (2021) Transmil: transformer based correlated multiple instance learning for whole slide image classification. Advances in neural information processing systems 34, pp. 2136–2147. Cited by: §1, §1, §1, §1, §2, Table 1, §4.3.
- [29] (2024) Advances in multiple instance learning for whole slide image analysis: techniques, challenges, and future directions. arXiv preprint arXiv:2408.09476. Cited by: §1, §1.
- [30] (2018) Revisiting multiple instance neural networks. Pattern recognition 74, pp. 15–24. Cited by: §2, Table 1, Table 1, §4.3.
- [31] (2021) TransPath: transformer-based self-supervised learning for histopathological image classification. In Medical Image Computing and Computer Assisted Intervention – MICCAI 2021, Cham, pp. 186–195. External Links: ISBN 978-3-030-87237-3 Cited by: §1, §1, §1, §1.
- [32] (1947) The generalization of ‘student’s’problem when several different population varlances are involved. Biometrika 34 (1-2), pp. 28–35. Cited by: §4.2.
- [33] (2024) A whole-slide foundation model for digital pathology from real-world data. Nature, pp. 1–8. Cited by: §1, §1, §2, §3.1, Table 1, §4.2, §4.3.
- [34] (2024) Mambamil: enhancing long sequence modeling with sequence reordering in computational pathology. In International Conference on Medical Image Computing and Computer-Assisted Intervention, pp. 296–306. Cited by: §1, §1, §2, §3.4, Table 1, §4.3.
- [35] (2023) CPIA dataset: a comprehensive pathological image analysis dataset for self-supervised learning pre-training. arXiv preprint arXiv:2310.17902. Cited by: §1, §1.
- [36] (2022) Dtfd-mil: double-tier feature distillation multiple instance learning for histopathology whole slide image classification. In Proceedings of the IEEE/CVF conference on computer vision and pattern recognition, pp. 18802–18812. Cited by: §1, §2, Table 1, §4.3.
- [37] (2022) Shuffle instances-based vision transformer for pancreatic cancer rose image classification. arXiv preprint arXiv:2208.06833. External Links: 2208.06833 Cited by: §1.
- [38] (2023) PuzzleTuning: explicitly bridge pathological and natural image with puzzles. arXiv preprint arXiv:2311.06712. Cited by: §1.
- [39] (2023) CellMix: a general instance relationship based method for data augmentation towards pathology image classification. arXiv preprint arXiv:2301.11513. External Links: 2301.11513 Cited by: §1, §1.
8 Theoretical Analysis of Asymmetric Structure
In the main text, we introduce an asymmetric structure that utilizes parallel processing during training and recurrent state-passing during inference. Here, we provide the mathematical proof demonstrating that the chunk-based recurrent inference is mathematically equivalent to processing the entire WSI sequence in a single pass.
It is worth noting that despite the difference in execution modes, both approaches rely on the same fundamental linear operations without introducing any complex approximations. As revealed by the non-trivial derivations of the closed-form solution (Eq. (16)) and the state-passing mechanism (Eq. (20)) below, the memory of the model is mathematically preserved through simple linear decays. This ensures that no global context information is lost due to the chunking strategy.
Recall the core state update rule of the PathRWKV block defined in Eq. (4) of the main text. For a sequence of tiles indexed by , the hidden state matrix and the output are computed as:
| (11) | ||||
| (12) |
where denotes element-wise multiplication, and represents the data-dependent decay at step . is initialized as a zero matrix.
Proposition 8.1 (Associativity and Inference Equivalence).
Let be the complete sequence of tiles from a WSI. Let denote the computation of the final state by processing all tiles continuously:
| (13) |
Let denote the computation where the sequence is split into two contiguous chunks and (where ). The inference is performed sequentially by passing the intermediate state:
| (14) | ||||
| (15) |
Then, the final states are identical: .
Proof.
The recursive update rule in Eq. (11) implies that the current state depends on the immediate past state, which in turn depends on its predecessor. By recursively unrolling this dependency back to the initial step , we can observe a pattern: the contribution of an input at step to the current state is scaled by the cumulative product of all subsequent decay factors. Mathematically, this accumulation allows us to express in a non-trivial closed form:
| (16) |
Assuming , the term involving vanishes.
Case 1: Global Continuous Inference () Applying Eq. (16) to the full sequence :
| (17) |
We can split this summation into two parts at index .
| (18) |
Notice that for Part 1, the decay product can be factored: .
Case 2: Chunked Sequential Inference () First, compute the state after the first chunk :
| (19) |
Next, use as the initial state for the second chunk . We apply the recursive definition starting from step to . Here, we treat similarly to in Eq. (16), but with a crucial difference: the historical information carried by must continue to decay as it propagates through the new sequence from to . By induction, the final state comprises two components: the decayed history from the previous chunk and the accumulated information from the current chunk:
| (20) |
Substitute into the equation above:
| (21) |
Distributing the decay term into the summation bracket exactly reconstructs the Part 1 term from Eq. (18), and the second term is identical to Part 2.
| (22) |
Thus, chunked inference with state passing is mathematically exact to global inference. ∎
9 Implementation Details and Hardware Acceleration
In this section, we provide a detailed description of the implementation of the PathRWKV backbone, specifically focusing on the custom CUDA kernels designed to enable the asymmetric training and inference structure described in Section 3.
9.1 Custom CUDA Kernels
To efficiently implement the mathematical duality of the Linear Attention mechanism, we implemented two distinct sets of CUDA kernels, corresponding to the parallel (training) and recurrent (inference) modes.
Parallel Kernel for Training. During training, we utilize the wkv6 parallel kernel. This kernel is optimized for maximizing throughput when the entire sequence is available in memory. It implements the time-decayed aggregation described in Eq. 3. Crucially, it fuses the computation of receptance (), key (), value (), and time-decay () processing into a single GPU kernel to minimize memory access overhead (HBM reads/writes). The backward pass kernel analytically computes gradients for all parameters, including the time-dependent decay rates, ensuring stable backpropagation through long sequences without the vanishing gradient problem typical of RNNs. The kernel leverages shared memory tiling and loop unrolling to accelerate the accumulation of attention scores along the sequence dimension .
State-based Kernel for Inference. For inference on gigapixel WSIs, we utilize the wkv6 state kernel. This kernel explicitly manages the recurrent state to support the chunked processing strategy. Unlike standard attention kernels, this kernel accepts an additional input tensor (the hidden state from the previous chunk) and outputs (the updated state). This directly implements the update rule derived in Proposition 8.1. To further accelerate inference, the state update loop is vectorized using float4 data types, allowing the GPU to process 4 floating-point numbers simultaneously per thread. The kernel performs internal accumulation in float32 to maintain numerical precision during the recursive updates, preventing error accumulation over long WSI sequences.
9.2 Chunked Inference Implementation
The code implementation orchestrates the interaction between the CUDA kernel and the WSI data to minimize memory footprint. Let be the total number of tiles and be the chunk size. The inference process proceeds as follows:
Initialization. A state tensor of shape is initialized to zeros, where is the number of heads and is the head dimension.
Sequential Processing. The WSI is split into chunks. For each chunk :
| (23) |
Here, calls the wkv6 state CUDA kernel, and represents the hidden state after processing the -th chunk. The state is passed strictly from CPU to GPU memory only once per chunk, minimizing PCI-e bandwidth usage.
Streaming Aggregation. Concurrently with feature extraction, the slide-level representation is updated using the streaming max pooling aggregation: . This ensures the GPU memory usage remains constant regardless of slide size.