---
title: 'COSFormer: Continual WSI Analysis'
url: https://www.emergentmind.com/topics/cosformer
type: topic
---

# COSFormer: Continual WSI Analysis

COSFormer is a unified Transformer-based framework for continual whole-slide-image (WSI) analysis that is designed to learn sequentially from new tasks without revisiting the full historical data. Introduced for multi-task WSI analysis, it integrates three components—Expert Consultation (EC), a Transformer encoder–decoder backbone, and autoregressive inference—within a single model that can grow dynamically as new tasks arrive. The framework is evaluated on a sequence of seven WSI datasets spanning seven organs and six WSI-related tasks under both task-incremental and class-incremental settings, where it is reported to show superior generalizability and effectiveness relative to the listed continual-learning baselines [2508.02220].

## 1. Problem formulation and domain setting

COSFormer is situated in continual learning for gigapixel pathology images. Whole Slide Images reveal detailed tissue structures in magnified views and are central to cancer diagnosis and prognosis, but their giga-sized nature imposes substantial storage and computational costs. The motivating requirement is a continual learning system that can adapt an existing model to new tasks without retraining or fine-tuning on previous tasks while maintaining high performance and resource efficiency [2508.02220].

The framework assumes a sequential task stream. At step \(t\), the model observes dataset \(\mathcal D_t\), learns to classify its \(c_t\) classes, and must retain performance on \(\{\mathcal D_1,\dots,\mathcal D_{t-1}\}\). Two standard continual-learning regimes are used. In **TASK-IL**, the active task is known and prediction is restricted to its \(c_t\) classes. In **CLASS-IL**, the task is unknown and the model must discriminate jointly among all classes accumulated up to step \(t\), namely \(\sum_{i=1}^{t} c_i\). This distinction is operationally important because COSFormer’s inference procedure uses task-conditioned masking only in TASK-IL, whereas CLASS-IL requires generation over the full label vocabulary [2508.02220].

A notable design choice is to cast classification as sequence generation rather than fixed-head discriminative prediction. This suggests that COSFormer is intended not merely as a rehearsal-based classifier, but as a label-generation system whose output space can expand as new diagnostic terms appear. The paper explicitly frames this as support for a dynamically growing vocabulary of diagnostic terms, thereby avoiding architecture redesign when classes change [2508.02220].

## 2. Core architecture

The model begins with WSI tiling and frozen visual feature extraction. Each WSI is partitioned into non-overlapping patches, and a frozen visual encoder \(F_{\mathrm{visual}}\), with UNI given as an example, maps patch \(x_{i,j}\) to feature vector \(z^v_{i,j}\in\mathbb R^{d_f}\). For slide \(i\), the patch embeddings are collected as \(\mathbf z_i=\{z^v_{i,j}\}_{j=1}^{N_i}\) [2508.02220].

These visual features are projected into the Transformer embedding space through the EC module, producing \(\mathbf z' \in \mathbb R^{N\times d_{\mathrm{model}}}\). The projected sequence is then processed by a Transformer encoder \(\mathcal E\) with \(N_e\) layers using Nystrom self-attention to model long-range patch interactions:
\[
\mathbf z^{(\ell+1)} = \mathbf z^{(\ell)}+\mathrm{Norm}\bigl(\mathrm{NA}(\mathbf z^{(\ell)})\bigr),\quad \ell=0,\dots,N_e-1.
\]
The decoder \(\mathcal D\), with \(N_d\) layers, performs standard Transformer decoding using multi-head self-attention over prior word embeddings, cross-attention over the encoder output, and a feed-forward network after each cross-attention block. If \(\mathbf h^{(k)}\) denotes the decoder state at time step \(k\), the next-word logits are
\[
p^{(k+1)} = \mathrm{Linear}\bigl(\mathbf h_{N_d}^{(k)}\bigr)\in\mathbb R^{|\mathcal V|}.
\]
This encoder–decoder factorization links patch-level slide representation to token-level label generation [2508.02220].

The architecture therefore differs from fixed-output continual classifiers in two ways. First, representation learning is task-adaptive at the input projection stage through EC. Second, prediction is autoregressive rather than single-shot. A plausible implication is that COSFormer’s extensibility is distributed across both the input-conditioning mechanism and the output vocabulary, rather than localized in a task-specific classifier head.

## 3. Expert Consultation module

The Expert Consultation module is the defining mechanism of COSFormer. It maintains one generalist weight matrix \(\theta_{\mathrm{gen}}\in\mathbb R^{d_f\times d_{\mathrm{model}}}\) and one expert matrix \(\theta_k\in\mathbb R^{d_f\times d_{\mathrm{model}}}\) for each of the \(N_T\) tasks observed so far. A router network \(\mathcal R\) computes unnormalized task scores for a patch embedding sequence:
\[
\mathbf W = \{\mathbf w_k\}_{k=1}^{N_T}
= \mathrm{FC}_2\bigl(\mathrm{ReLU}(\mathrm{FC}_1(\mathbf z))\bigr),\quad
\mathbf w_k\in\mathbb R^N.
\]
The current task \(\mathcal T\) is emphasized by scaling and averaging:
\[
\tilde w_{k,j}
= \frac{\exp\bigl(\mathbbm1_{k=\mathcal T}(\mathbf w_k\cdot\mathbf1)\gamma+\mathbbm1_{k\neq\mathcal T}\mathbf w_k(j)\bigr)}
{\sum_{k'\neq\mathcal T}\exp(\mathbf w_{k'}(j))+\exp(\mathbf w_{\mathcal T}\cdot\mathbf1\,\gamma)},
\]
\[
\bar w_k
= \frac1N\sum_{j=1}^N\tilde w_{k,j} + \mathbbm1_{k=\mathcal T}\,\beta.
\]
The final projection is
\[
\theta_{EC}
= \theta_{\mathrm{gen}} + \sum_{k=1}^{N_T}\bar w_k\,\theta_k,
\qquad
\mathbf z' = \mathbf z\,\theta_{EC}.
\]
The paper explicitly interprets EC as a Mixture-of-Experts layer in which each \(\theta_k\) specializes in one task, while \(\theta_{\mathrm{gen}}\) provides a shared component [2508.02220].

This mechanism is described as “doctor-like” expert consultation, with task-adaptive embeddings intended to mitigate inter-task interference. The claim is architectural rather than metaphorical: the router computes patch-wise task weights, emphasizes the current task through the scaling factor \(\gamma\), averages across patches, and fuses the experts into a single projection matrix. In effect, task adaptation occurs before the slide enters the Transformer proper. This suggests that COSFormer treats continual learning primarily as conditional representation routing, supplemented by replay and autoregressive decoding, rather than as parameter isolation alone [2508.02220].

The parameter-growth behavior is also explicit. The parameter budget increases by \(d_f\times d_{\mathrm{model}}\) for each new task, since a new expert matrix is added per task. The paper identifies this as a limitation and points to more parameter-efficient expert modules as a future direction [2508.02220].

## 4. Autoregressive inference and continual-learning objective

COSFormer formulates diagnosis as sequence generation. Starting from a beginning-of-sequence token \(\langle\mathrm{BOS}\rangle\), the decoder iteratively emits
\[
\hat y^{(k)}=\arg\max_u\,p^{(k)}_u.
\]
The conditional factorization over a diagnostic label sequence \((y_1,\dots,y_K)\) is
\[
P(y_1,\dots,y_K\mid x)
= \prod_{k=1}^K P(y_k\mid y_{<k}, x).
\]
Equivalently, the decoder produces next-token logits conditioned on both the encoder output and previously generated tokens:
\[
\hat p^{(k+1)} \;=\; \mathcal D\bigl(\mathcal E(\mathbf z') \mid \hat p^{(k)}\bigr).
\]
Under TASK-IL, irrelevant words outside a task-specific “Words of Interest” set are masked at each step:
\[
\hat p_j^{(k)} =
\begin{cases}
\hat p_j^{(k)}, & \text{if } w_j\in \mathrm{WoI}_{\mathcal T},\\
-\infty, & \text{otherwise.}
\end{cases}
\]
Under CLASS-IL, no mask is used, so the model must select from the full vocabulary [2508.02220].

The training objective combines current-task learning, replay, and dark replay. For slide \(x_i\) and decoding step \(k\),
\[
\mathcal L
=
\underbrace{\mathcal L_{\mathrm{CE}}\bigl(p^{(k)}_{t,i},y^{(k)}_i\mid x_i\in\mathcal D_t\bigr)}_{\text{current task}}
+
\underbrace{\mathcal L_{\mathrm{CE}}\bigl(p^{(k)}_{t,i},y^{(k)}_i\mid x_i\in\mathcal B_r\bigr)}_{\text{replay}}
+
\underbrace{\lambda_{\mathrm{MSE}}\,
\mathcal L_{\mathrm{MSE}}\bigl(p^{(k)}_{t,i},p^{(k)}_{t-1,i}\mid x_i\in\mathcal B_r\bigr)}_{\text{dark replay}}.
\]
Here \(\mathcal B_r\) denotes a small replay buffer, and the MSE term aligns current logits with those from the previous model on replayed samples in order to mitigate forgetting [2508.02220].

This design ties the continual-learning objective to the autoregressive formulation. Because the model replays token-level outputs rather than only class logits from a fixed head, the dark-replay term regularizes the evolving vocabulary-conditioned decoder. A plausible implication is that forgetting can arise not only in class boundaries but also in the sequential structure of label generation, which the formulation attempts to preserve.

## 5. Training protocol, buffer construction, and evaluation

The reported task order is CAMELYON16 \(\to\) TCGA-NSCLC \(\to\) TCGA-BRCA \(\to\) TCGA-RCC \(\to\) TCGA-ESCA \(\to\) TCGA-TGCT \(\to\) TCGA-CESC, together with the reverse order. The model hyperparameters are specified as embedding dimension \(d_{\mathrm{model}}=512\), \(N_e=N_d=2\), router scaling \(\gamma=5\), shift \(\beta=1\), replay buffer size \(|\mathcal B_r|\le 26\) WSIs, Lookahead-RAdam with learning rate \(10^{-5}\), and early stopping after 5 epochs. Accuracy is the primary metric and F1 score is also reported. The listed baselines are GDumb, A-GEM, ER-ACE, and DER++, all using the same Transformer-encoder backbone [2508.02220].

Replay-buffer construction uses a text-based retrieval strategy. The most representative slide per class cluster is selected by computing the similarity
\[
s_i = \max_j\langle z^v_{i,j},\,F_{\mathrm{text}}(\operatorname{Text}(c))\rangle
\]
and then applying \(k\)-means to enforce diversity. The paper characterizes this strategy as ensuring both representativeness and diversity in stored exemplars, improving replay quality [2508.02220].

The empirical results are reported for both continual-learning regimes.

| Setting | COSFormer | DER++ |
|---|---:|---:|
| TASK-IL, forward order | 93.1% | 92.2% |
| TASK-IL, reverse order | 91.14% | 90.9% |
| CLASS-IL, forward order | 81.09% | 71.20% |
| CLASS-IL, reverse order | 79.36% | 77.75% |

In the ablation study, removing task-ID \((\mathcal T)\) or Words-of-Interest masking degrades performance by up to 12% in CLASS-IL. Omitting EC, the autoregressive decoder, or the text-based buffer each lowers accuracy by up to 11% in CLASS-IL. The t-SNE visualization in Figure 6 is reported to show that COSFormer embeddings have the highest silhouette scores, which the paper interprets as evidence of well-separated task clusters [2508.02220].

The evaluation scope is substantial within the stated setup: seven WSI datasets, seven organs, six WSI-related tasks, and two task orders. At the same time, the paper notes that only two task orders were tested, and indicates that more randomized sequences would probe robustness further [2508.02220].

## 6. Interpretation, limitations, and nomenclature

The paper attributes COSFormer’s performance to the interaction of three mechanisms: expert consultation for task-adaptive embeddings, autoregressive decoding for dynamically growing diagnostic vocabularies, and text-based buffer sampling for representative and diverse rehearsal data. These are presented as complementary rather than interchangeable components, which is consistent with the ablation results showing performance drops when any of them is removed [2508.02220].

Several limitations are stated directly. Per-task performance can vary, and some tasks, such as TCGA-BRCA in CLASS-IL, showed lower accuracy. Only two task orders were examined. The parameter budget grows by \(d_f\times d_{\mathrm{model}}\) with each new task because each task introduces a new expert matrix. Autoregressive decoding adds inference overhead, motivating future work on faster decoding or distillation. The paper also identifies extension to other pathology tasks, including survival prediction and treatment-response, as a natural next step [2508.02220].

A recurrent source of confusion is nomenclature. **COSFormer** in WSI continual learning should be distinguished from **“cosFormer: Rethinking Softmax in Attention”**, a linear Transformer that replaces the softmax kernel with a ReLU-based linear kernel and cosine distance re-weighting for efficient attention [2202.08791], and from **“CoSformer: Detecting Co-Salient Object with Transformers”**, which addresses co-salient object detection through Transformer-based intra-image and inter-image modeling with contrastive learning [2104.14729]. The names are similar, but the problem settings, architectures, and objectives are different. This suggests that the capitalization variants map to separate research lines rather than successive versions of a single method.

Source: https://www.emergentmind.com/topics/cosformer