Skip to Content
AgriEngineeringAgriEngineering
  • Article
  • Open Access

1 December 2026

28 Pages

SwinePath-CLIP: Domain-Guided Cross-Modal Retrieval for Swine Gross Pathology

,
,
,
and
College of Mathematics and Informatics, South China Agricultural University, Guangzhou 510642, China
*
Author to whom correspondence should be addressed.
AgriEngineering2026, 8(12), 520;https://doi.org/10.3390/agriengineering8120520 
(registering DOI)
This article belongs to the Special Issue Computer Vision for Smart Agriculture

Abstract

Swine gross pathology images and veterinary descriptions vary in lesion appearance, anatomical detail, and reporting style, making it difficult to retrieve relevant records across modalities. We construct SwinePath, a paired image–text dataset, and develop SwinePath-CLIP for the bidirectional retrieval of pathology images and descriptions. To better use the information contained in veterinary language, Veterinary Phrase Salience Guidance (VPSG) creates auxiliary text views that retain informative pathological phrases. To strengthen the association between descriptions and visible lesions, Lesion-Cued Visual Bridge Regularization (LC-VBR) applies caption-guided patch weighting and a cross-modal bridge target, encouraging the model to attend to relevant local image regions. During retrieval, Transport-Calibrated Support (TC-CSLS) adjusts candidate scores by combining local density correction with balanced transport support. On the SwinePath test set, SwinePath-CLIP achieves Recall@1 of 36.60% for image-to-text retrieval and 35.53% for text-to-image retrieval. Its mean recall (mR) reaches 61.45%, compared with 55.04% for OpenCLIP. Ablation experiments show improvements from both VPSG and LC-VBR, followed by an additional gain from ranking calibration. These findings suggest that preserving salient veterinary phrases and emphasizing lesion-related visual evidence can improve the cross-modal retrieval of swine gross pathology records.

1. Introduction

Timely access to reliable disease information supports prevention, treatment, and herd-health management in swine production. Veterinary atlases are important sources for interpreting disease-related observations. Their images and descriptions, however, are dispersed across resources with different formats and terminology. Cross-modal retrieval helps users to find relevant records by matching lesion images with veterinary descriptions.
Machine learning has been applied to livestock disease surveillance, symptom monitoring, respiratory health analysis, infection prediction, and veterinary decision support [1,2,3,4]. Wang et al. [5] combined illness state text reports with a disease knowledge graph for dairy cow disease diagnosis. Li et al. [6] fused excretion behavior and fecal characteristics at the decision level for pig disease identification, while Yang et al. [7] combined swine disease images with veterinary case reports. Medical vision–language studies have also used paired and unpaired images and descriptions to learn cross-modal representations [8,9,10]. GLoRIA learns global and local medical image–text representations by contrasting image subregions with words in paired reports [11]. These approaches provide a basis for retrieving swine pathology records through their visual appearance and textual content.
Agricultural disease information is increasingly represented through complementary visual and textual evidence: images convey lesion appearance and distribution, whereas descriptions encode symptoms, context, and expert terminology. Because either modality alone provides only a partial account, recent systems have enabled bidirectional search from disease images to descriptions and from textual queries to visually similar cases, accelerating the adoption of cross-modal retrieval in plant disease applications [12,13]. Recent agricultural image–text retrieval studies cover several disease and pest settings. LAFANet combines Vision Transformer (ViT) and Bidirectional Encoder Representations from Transformers (BERT) features, learnable fusion attention, and false negative handling for tomato leaf disease retrieval [12]. FHTW-Net introduces a rice leaf benchmark and combines fine-grained feature sequences with two-way mixed self-attention, false negative elimination, hard-negative mining, and learning rate optimization [14]. Wolfberry pest retrieval uses hash representations, two-level feature fusion, and label enhancement based on species distribution information [15]. Other tomato pest and disease work combines triplet contrastive learning, hyperbolic semantic modeling, an adaptive classification loss, and local lesion features to address class imbalance [16]. CPCR uses large language model (LLM)-generated prior instructions, progressive attention, and an association loss for crop pest retrieval [17], while fish disease retrieval focuses on common perch diseases and lesion matching [18]. These studies often use predefined categories, structured or generated descriptions, or category-aware supervision. In veterinary practice, swine disease records cover organ lesions, external clinical signs, and whole-animal observations. Similar visual changes can occur in different disease contexts, and descriptions combine lesion morphology and anatomical location with clinical background and negated findings. Retrieving a relevant case therefore requires matching these attributes despite differences in image scale, presentation, and reporting style.
Image–text retrieval methods commonly use cross-attention matching or shared embeddings. Dual encoders map images and text into a common space, allowing their features to be cached and compared efficiently. Contrastive Language–Image Pre-training (CLIP) and OpenCLIP established large-scale contrastive alignment [19,20], while ALBEF and BLIP developed vision–language pretraining and fusion methods [21,22]. SigLIP uses a sigmoid loss in place of the softmax contrastive objective [23], and EVA-CLIP improves large-scale CLIP training [24]. FineCLIP further enhances local representations through self-distillation and region–text contrastive learning [25]. Adapting these models to swine gross pathology requires attention to local lesion evidence and the anatomical and pathological detail expressed in veterinary descriptions.
Three challenges are central to this task. First, veterinary descriptions mix anatomical sites, lesion morphology, color, distribution, and contextual observations. Repeated background wording can obscure the phrases that are the most useful in matching an image. Second, lesions vary in size and location and often appear alongside unaffected tissue. A global image representation can dilute these local cues. Third, different cases can share organs, lesion appearances, and pathological terms, causing a few broadly similar candidates to recur near the top of many retrieval lists. This concentration of nearest-neighbor occurrences is characteristic of hubness in high-dimensional spaces [26].
To address these challenges, we propose SwinePath-CLIP for the bidirectional retrieval of swine gross pathology images and veterinary descriptions. Its three modules correspond to the challenges above: Veterinary Phrase Salience Guidance (VPSG) emphasizes informative pathological phrases, Lesion-Cued Visual Bridge Regularization (LC-VBR) incorporates caption-guided local visual evidence, and Transport-Calibrated Support (TC-CSLS), which uses cross-domain similarity local scaling (CSLS), mitigates hubness in retrieval rankings. Lighting and viewpoint variations can alter overall color and organ appearance, while farm backgrounds introduce potentially distracting visual content. LC-VBR uses pathological phrases to emphasize caption-relevant patches while retaining the broader anatomical context, encouraging retrieval to draw on visible local lesion details rather than global appearance alone. VPSG complements this visual guidance by emphasizing the anatomical and pathological attributes expressed in the descriptions.
Figure 1 illustrates the visual basis of the second and third challenges using representative Noah’s Arkive records included in SwinePath. In the upper panel, small pale foci occupy only a limited region of an otherwise complete liver view, so their contribution can be weakened when the image is summarized by a global representation. In the lower panel, two kidney cases share a closely matched organ shape, viewpoint, and overall color, while the distinguishing evidence lies in the density and spatial distribution of fine red punctate lesions. The source records associate these visually similar kidneys with different diagnoses—nephritis with streptococcal septicemia and thrombocytopenic purpura—demonstrating that a similar global appearance can correspond to different pathological descriptions. These examples motivate representations that preserve localized visual evidence and align it with the anatomical and pathological phrases expressed in veterinary text.
Figure 1. Representative visual challenges in SwinePath. (Top) Small pale foci occupy a limited region of an otherwise complete liver view; the boxed region is enlarged at the right. (Bottom) Two kidney cases have a similar global appearance but different recorded diagnoses; circles highlight representative differences in the density and distribution of punctate lesions.
This study makes the following contributions:
(1)
To study and evaluate pathological phrase representation, local visual evidence extraction, and candidate ranking within the same task, we construct SwinePath, a paired image–text dataset for swine gross pathology, and establish SwinePath-CLIP as a bidirectional retrieval framework.
(2)
To address the obscuring of key pathological phrases by background wording, we propose VPSG, which constructs auxiliary phrase-level text views to emphasize anatomical sites, lesion morphology, and symptoms during image–text alignment training.
(3)
To address the limited representation of local pathological cues in global image–text alignment, we propose LC-VBR, which combines description-guided patch weighting with cross-modal bridge regularization to incorporate local visual evidence into training.
(4)
To address hubness, where a few similar candidates repeatedly receive high rankings across multiple queries, we propose TC-CSLS, which combines local density correction with balanced transport during retrieval to calibrate candidate scores.

2. Materials and Methods

2.1. Construction of the Curated SwinePath Dataset

We constructed SwinePath as a paired image–text dataset from eight veterinary atlases [27,28,29,30,31,32,33,34] and the publicly accessible Noah’s Arkive maintained by the Davis-Thompson Foundation (https://davisthompsonfoundation.org/noahs-arkive/; accessed on 15 September 2026). SwinePath includes organ-level gross pathology, skin and limb lesions, whole-animal observations, and farm scenes. Differences in framing, clarity, and color rendering across sources may affect the anatomical context and pathological detail available for image–text matching.
We excluded non-swine images, histological micrographs, and schematic illustrations. Atlas images were checked against the original books to verify image–caption correspondence, and ambiguously paired images were excluded. SHA-256 file hashes were used to check for duplicate files. The resulting 4706 images were organized into eight broad categories: bacterial diseases, viral diseases, parasitic diseases, fungal diseases, toxic diseases, nutritional and metabolic diseases, syndromes and organ lesions, and normal, post-mortem, or nonspecific disease states. The category sizes ranged from 48 to 1764 images, reflecting the distribution of the collected veterinary records.
The veterinary atlases provided the original descriptions, which were machine-translated into English. We compiled a veterinary terminology glossary from official materials published by the Chinese Veterinary Medical Association and checked the disease, organ, and pathology terms against it. Veterinary pathologists reviewed the translations alongside the source texts and corresponding images, checking the disease names, anatomical sites, lesion attributes, and negation. Noah’s Arkive records provide the structured fields CONTRIB_NAME, INST_NAME, SPECIES_NAME, SYSTEM_NAME, ORGAN_NAME, GENPATH_NAME, and Diagnosis. These fields were organized directly into standardized English captions using the unified template “Gross appearance of the porcine [organ or anatomical site] showing [diagnosis or lesion description], consistent with [general pathological process].” For example, a liver record describing massive necrosis and coagulative necrosis was rendered as “Gross appearance of the porcine liver showing massive necrosis, consistent with coagulative necrosis.” Each generated caption was manually reviewed against the structured record and its corresponding image. Figure 2 shows example image–text pairs for bacterial, viral, and parasitic diseases, with each source image accompanied by its standardized English description.
Figure 2. Examples of Noah’s Arkive image–text pairs included in SwinePath. The rows present bacterial, viral, and parasitic disease cases, respectively, with each image paired with its standardized English veterinary description.
We randomly divided the 4706 images into training, validation, and test subsets at an 80:10:10 ratio before text augmentation, yielding 3765, 471, and 470 images, respectively. Data partitioning was performed at the image level because the source materials did not provide sufficient case identifiers for case-level grouping. Different images from the same case may therefore occur in different subsets. Table 1 reports the number of images contributed by each source to the training, validation, and test sets.
Table 1. Distribution of images by source and dataset split in SwinePath.
Text augmentation was applied only to the training set. Each finalized caption received four additional descriptions through controlled synonym-based rewriting. The rewrites substituted synonymous pathological terms, reordered lesion and background phrases, split or merged clauses, and adjusted noncritical modifiers. Disease, organ, and lesion information and the scope of negation were preserved. The experts also reviewed the rewritten descriptions against the finalized captions and corresponding images using the same criteria. This produced 18,825 training pairs, with five descriptions per image. The validation and test sets retained 471 and 470 one-to-one pairs. The full dataset contains 19,766 image–text pairs.
The curation workflow applies to swine gross pathology images and related whole-animal or farm observations accompanied by identifiable source captions or structured veterinary records. It requires sufficient source information to establish image–text correspondence and check the anatomical and pathological content of each description. The resulting coverage depends on the diseases, anatomical sites, and visual findings represented in the source collections. Caption standardization and text augmentation preserve the available source information but do not supply missing clinical histories or case identifiers. Records with ambiguous image–text correspondence are excluded, and sources without sufficient case identifiers support image-level rather than case-level partitioning.

2.2. Model Framework

SwinePath-CLIP uses a shared-embedding architecture for bidirectional retrieval. Image and text encoders learn global representations through a paired contrastive objective. VPSG adds a phrase-masked text view, and LC-VBR adds caption-guided visual regularization during training. At inference, the cosine similarity is computed from the embeddings, and TC-CSLS calibrates the resulting scores for ranking.

2.2.1. Feature Extraction Component

SwinePath-CLIP builds on the CLIP dual-encoder framework and uses an OpenCLIP ViT-B/16 model initialized from pretrained weights [19,20]. The visual and textual encoders independently process an image I i and its paired description T i and then project their representations into a shared normalized embedding space. Figure 3 shows the text-side regularization from VPSG and image-side regularization from LC-VBR during training. At inference, the encoders produce embeddings whose similarity scores are calibrated by TC-CSLS. Image and text embeddings can be precomputed and cached independently.
Figure 3. Overall architecture of SwinePath-CLIP. (a) During training, the OpenCLIP dual encoders, an open-source implementation of Contrastive Language–Image Pre-training (CLIP), are optimized using the standard image–text contrastive objective together with Veterinary Phrase Salience Guidance (VPSG) text-view regularization and Lesion-Cued Visual Bridge Regularization (LC-VBR) visual regularization. Green denotes the image encoder, and orange denotes the text encoder. (b) During inference, the trained encoders produce fixed image and text embeddings, which are subsequently processed by Transport-Calibrated Support (TC-CSLS), which uses cross-domain similarity local scaling (CSLS), for bidirectional reranking.
For the visual branch, the ViT encoder divides I i into nonoverlapping patches, maps each patch to a token embedding, appends a learnable class token, and processes the resulting sequence using stacked Transformer blocks. The projected class token representation is L2-normalized to obtain the global image embedding v i in R d , written as v i = Norm P v E v I i , where E v and P v denote the visual encoder and projection layer, respectively. The global representation captures the image-level disease context, while the projected patch tokens remain available to LC-VBR for modeling local visual evidence during training.
For the textual branch, caption T i is tokenized and processed by the Transformer text encoder. The end-of-text representation is projected into the shared embedding dimension and L2-normalized to obtain the global text embedding t i in R d , written as t i = Norm P t E t T i , where E t and P t denote the text encoder and text projection layer, respectively. The same text encoder processes the original caption, the phrase-masked view generated by VPSG, and the phrase guidance used by LC-VBR, thereby maintaining a consistent semantic space across the main and auxiliary training objectives.
For a mini-batch of B distinct images, each paired with one sampled caption, the normalized image and text embeddings are used to construct temperature-scaled similarity logits. The paired samples occupy the diagonal of the similarity matrix, and the symmetric CLIP objective jointly optimizes the image-to-text (I2T) and text-to-image (T2I) alignment.
l i j = v i t j T τ c
L CLIP I 2 T = − 1 B ∑ i = 1 B log ( exp ( ℓ i i ) ∑ j = 1 B exp ( ℓ i j ) )
L CLIP T 2 I = − 1 B ∑ i = 1 B log ( exp ( ℓ i i ) ∑ j = 1 B exp ( ℓ j i ) )
L CLIP = 1 2 ( L CLIP I 2 T + L CLIP T 2 I )
where ℓ i j denotes the temperature-scaled similarity between image I i and caption T j , τ c = 1 s is the contrastive temperature associated with the trainable logit scale s, and B is the mini-batch size. The diagonal pair ( i , i ) is treated as the positive match, while the remaining within-batch pairs provide negative comparisons. The final objective averages the image-to-text and text-to-image losses. VPSG and LC-VBR supplement this objective with text-side and image-side regularization during training, respectively.

2.2.2. VPSG

Veterinary captions describe anatomical sites, lesion morphology, color, severity, and clinical manifestations. VPSG constructs an auxiliary phrase-masked caption by assigning lower masking priorities to spans containing pathology-related cues.
VPSG uses four fixed English rule lexicons. The pathology/anatomy lexicon was compiled from the Saunders Comprehensive Veterinary Dictionary, 5th edition [35], by selecting terms describing anatomical sites, gross lesion morphology, color, distribution, and clinical signs relevant to swine gross pathology. The other three lexicons contain common function words, generic pig and scene terms, and negation expressions, respectively. All entries use lowercase word forms for matching.
For a caption T i , tokenization extracts alphanumeric word sequences, including those containing an internal hyphen or apostrophe, and matching uses lowercase forms. Stopwords, generic terms, negation terms, and single-character tokens delimit candidate spans. Consecutive remaining words form the candidate phrases:
P i = { ϕ i 1 , ϕ i 2 , … , ϕ i M i } ,
where M i is the number of candidates. Punctuation does not delimit spans. If no candidates are obtained, word-level candidates are used.
Let N ( ϕ ) normalize a phrase by joining its lowercase word tokens with single spaces. Its mini-batch frequency, which counts exact normalized candidate occurrences including repetitions within one caption, is
f ϕ = ∑ i = 1 B ∑ j = 1 M i 1 N ( ϕ i j ) = N ( ϕ ) .
Word forms are preserved during normalization. For each candidate, the masking priority score is
s mask ( ϕ ) = Q B ( ϕ ) − S path ( ϕ ) + ε ϕ ,
where the components are
Q B ( ϕ ) = a ℓ ℓ ϕ + a f ( f ϕ − 1 ) + + a g n generic ( ϕ ) , S path ( ϕ ) = a d n domain ( ϕ ) + a n I neg ( ϕ ) ,
Here, ℓ ϕ is the word count and ( x ) + = max ( x , 0 ) . The counts n generic and n domain use exact whole-word matching against the corresponding lexicons. The score applies to ordinary and fallback candidates; generic term exclusion results in n generic = 0 for ordinary candidates. I neg = 1 when a predefined negation term occurs within the 32 characters preceding the original phrase span, and it is zero otherwise.
We set ( a ℓ , a f , a g , a d , a n ) = ( 0.15 , 0.35 , 0.25 , 0.45 , 1.0 ) and ε ϕ = 0.01 u ϕ , where u ϕ ∼ U [ 0 , 1 ) . Length, repetition, and generic term matches increase the masking priority, while domain term and preceding negation matches favor retention. The random perturbation resolves ties and varies the ordering of near-tied candidates. VPSG removes complete phrases in descending score order according to the prescribed masking ratio while retaining sufficient text for encoding. The remaining text preserves its original order and is whitespace-normalized to obtain the auxiliary caption T ˜ i .
Let v i and t ˜ i denote the normalized representations of image I i and masked caption T ˜ i , respectively. VPSG applies the symmetric contrastive objective
ℓ ˜ i j = v i T t ˜ j τ VPSG
L VPSG I 2 T = − 1 B ∑ i = 1 B log ( exp ( ℓ ˜ i i ) ∑ j = 1 B exp ( ℓ ˜ i j ) )
L VPSG T 2 I = − 1 B ∑ i = 1 B log ( exp ( ℓ ˜ i i ) ∑ j = 1 B exp ( ℓ ˜ j i ) )
L VPSG = 1 2 ( L VPSG I 2 T + L VPSG T 2 I )
Here, B is the mini-batch size and τ VPSG = 0.07 is the contrastive temperature. The symmetric objective aligns images with the descriptive information retained in the auxiliary captions.

2.2.3. LC-VBR

As shown in Figure 4, LC-VBR combines pathology-guided local evidence aggregation with latent-space bridge regularization [36]. Caption-derived phrases guide the weighting of image patches associated with lesions and anatomy. A bridge target formed from the paired image and text embeddings then constrains the fused local–global representation.
Figure 4. LC-VBR uses caption-derived pathology phrases to weight augmented image patches and regularizes the fused local–global representation toward the image–text bridge target. Green and orange denote the image and text encoders and their corresponding feature points, respectively.
For an image–caption pair ( I i , T i ) , let v i and t i denote the L2-normalized global embeddings of the original image and caption, respectively. LC-VBR constructs a cross-modal bridge target between the paired representations:
b i = Norm ( η bridge v i + ( 1 − η bridge ) t i )
Here, η bridge = 0.50 gives equal interpolation weight to the normalized image and text embeddings, and Norm ( · ) denotes L2 normalization. The bridge target provides a cross-modal reference for regularizing the augmented visual representation.
LC-VBR uses the same rule lexicons, candidate phrase extraction procedure, and mini-batch phrase frequencies as VPSG (Section 2.2.2). It assigns each candidate phrase a separate guidance score:
s guide ( ϕ ) = b ℓ ℓ ϕ + b d n domain ( ϕ ) − b f ( f ϕ − 1 ) + + b n I neg ( ϕ ) ,
where ( b ℓ , b d , b f , b n ) = ( 0.4 , 1.2 , 0.2 , 0.5 ) . The phrase length, domain term matches, and preceding negation increase the selection priority, while mini-batch repetition reduces it. The number of selected phrases is
M i guide = min 8 , max 1 , round ( 0.5 M i ) .
The highest-scoring phrases are used to construct the guidance text, with preceding negation terms recovered from the same 32-character window used in VPSG. The shared text encoder converts this text into the guidance embedding g i . The augmented image is processed by the visual encoder to obtain both a global embedding v i aug and patch representations p i j . The relevance of the j-th patch to the caption-derived guidance is measured by
a i j = p i j T g i τ patch .
Here, τ patch = 0.07 controls the sharpness of the relevance distribution. Let S i contain the indices of the K = max ( 1 , round ( r N ) ) highest-scoring patches, where r = 0.90 is the patch selection ratio. Let σ S i denote the softmax over the selected scores, and let sg ( · ) denote the stop gradient operation used for maximum-value normalization. The patch weights are
ω i j = β min + ( 1 − β min ) σ S i ( a i j ) sg max k ∈ S i σ S i ( a i k ) , j ∈ S i , β min , j ∉ S i .
Here, β min = 0.80 is the minimum patch weight. The highest-scoring selected patch therefore receives unit weight, the remaining selected patches receive values between β min and 1, and patches outside S i retain the baseline weight β min . The resulting weights aggregate local visual evidence according to
v i loc = ∑ j = 1 N ω i j p i j ∑ j = 1 N ω i j .
The weighted representation v i loc emphasizes caption-compatible local evidence while retaining broader anatomical and contextual information. It is combined with the augmented image’s global representation to obtain
z i LC = Norm ( ( 1 − α loc ) v i aug + α loc v i loc ) .
Here, α loc = 0.20 controls the contribution of the local representation. The bridge coefficient η bridge , patch temperature τ patch , and local fusion coefficient α loc were assigned fixed empirical values.
The fused representation is regularized toward the paired cross-modal bridge target:
L LC - VBR = 1 B ∑ i = 1 B z i LC − b i 2 2 .
Here, B is the mini-batch size.
The overall training objective combines the main contrastive loss with the two auxiliary losses:
L total = L CLIP + λ VPSG L VPSG + λ LC - VBR L LC - VBR .
The main contrastive loss has unit weight. We use λ VPSG = 0.005 and λ LC - VBR = 0.05 to scale the contributions of phrase-masked alignment and local visual regularization, respectively. Joint optimization aligns the global image–text representations while incorporating the phrase-guided auxiliary constraints.

2.2.4. TC-CSLS

TC-CSLS combines local density correction with transport-calibrated support to rerank the cosine similarity matrix without modifying the embeddings. CSLS adjusts the pairwise scores relative to the cross-modal neighborhood similarities, whereas transport calibration balances support across the query–candidate matrix. Both branches operate on the same cosine similarity matrix, and their standardized outputs are combined for bidirectional retrieval. The retrieval-stage score calibration component is shown in Figure 5.
Figure 5. TC-CSLS combines local density correction with transport-calibrated support for bidirectional reranking. In (b), warm-colored cells schematically indicate higher similarity scores (left) or transport-calibrated support values (right), whereas blue cells indicate lower values.
Given normalized image embeddings V = { v i } i = 1 n I and text embeddings T = { t j } j = 1 n T , their cosine similarity matrix is denoted by S ∈ R n I × n T , with S i j = v i T t j . TC-CSLS first applies cross-domain similarity local scaling (CSLS) [37] to evaluate each entry relative to the local neighborhoods formed on both sides of the matrix. Let N k csls T ( i ) and N k csls I ( j ) denote the corresponding top- k csls cross-modal neighborhoods, where k csls = 5 . The local density calibration is expressed as
r i = 1 k csls ∑ j ∈ N k csls T ( i ) S i j
c j = 1 k csls ∑ i ∈ N k csls I ( j ) S i j
S CSLS , i j = 2 S i j − r i − c j
The terms r i and c j summarize the similarity within the two cross-modal neighborhoods. Subtracting them from twice the pairwise similarity gives S CSLS , i j , a score adjusted for the local similarity environment.
TC-CSLS also computes a support representation across all query–candidate pairs. For an input score matrix X, the scores are first standardized and converted into a positive kernel:
Std ( X ) = X − μ X max σ X , ε z
K ( X ) = exp clip γ tr Std ( X )
P ( 0 ) = K ( X ) ∑ i , j K i j ( X ) .
Here, μ X and σ X are the mean and population standard deviation over all entries of X, respectively. We use ε z = 10 − 6 , γ tr = 3 , and clipping bounds of [ − 20 , 20 ] .
Let A = log K ( X ) . For an input matrix with m rows and n columns, the associated entropy-regularized transport objective is as defined in Equation (28):
Q ★ = arg max Q ∈ U ( a , b ) ⟨ A , Q ⟩ − ∑ i j Q i j log Q i j .
The feasible set and uniform marginals are specified in Equation (29):
U ( a , b ) = Q ≥ 0 : Q 1 n = a , Q ⊤ 1 m = b , a i = 1 m , b j = 1 n .
Uniform marginals impose a score-balancing assumption rather than a clinical one-to-one matching constraint. Lagrangian stationarity yields the scaling form in Equation (30):
Q ★ = diag ( u ) K ( X ) diag ( w ) , u = a K ( X ) w , w = b K ( X ) ⊤ u ,
with elementwise division. These relations motivate the alternation of row and column normalization. The initial global normalization in Equation (27) does not affect subsequent normalization cycles when denominator floors are inactive.
For P ∈ R + n I × n T , the row and column normalization operators are defined as
[ R ( P ) ] i j = P i j max ∑ k = 1 n T P i k , ε , [ C ( P ) ] i j = P i j max ∑ k = 1 n I P k j , ε .
The operators R and C perform row and column normalization, respectively; n I and n T denote the numbers of images and texts; and ε = 10 − 12 provides a lower bound for the denominator. We apply row normalization followed by column normalization for L = 20 iterations:
P l + 1 2 = R P ( l ) ,
P ( l + 1 ) = C P l + 1 2 , l = 0 , … , L − 1 .
For an input matrix with m rows and n columns, P ( L ) / n provides a finite-iteration approximation to the uniform-marginal transport solution when denominator floors are inactive. At convergence, P has column sums of 1 and row sums of n / m .
The resulting matrix is log-transformed and standardized over all entries, yielding the support score H ( X ) for each image–text pair:
H ( X ) = Std log max P ( L ) , ε .
The local density and balanced support scores are combined as follows:
S TC - CSLS I → T = ( 1 − α TC ) Std S CSLS + α TC H ( S )
S TC - CSLS T → I = ( 1 − α TC ) Std S CSLS ⊤ + α TC H S ⊤ ⊤
Here, α TC = 0.05 controls the contribution of transport support. Finite diagonal scaling gives P ( L ) = diag ( u ( L ) ) K ( X ) diag ( w ( L ) ) , with the initial global scale absorbed into the scaling factors. Before applying the logarithmic floor, the decomposition in Equation (37) holds:
log P i j ( L ) = A i j + log u i ( L ) + log w j ( L ) .
Thus, transport support introduces globally estimated row and column adjustments that complement local CSLS correction. The final mixture is an empirical scoring rule rather than the transport optimum itself. Image-to-text retrieval applies these operations to S, whereas text-to-image retrieval recomputes them on S ⊤ . Calibration therefore depends on the supplied query–candidate matrix.

3. Results

3.1. Preparation of Experimental Environment

All OpenCLIP-based experiments were conducted on a single-GPU workstation equipped with one NVIDIA RTX 4090D GPU (24 GB) and a 15-vCPU Intel Xeon Platinum 8474C processor. The software environment comprised Ubuntu 22.04, Python 3.10, PyTorch 2.1.2, and CUDA 11.8.
SwinePath-CLIP used the OpenCLIP ViT-B/16 dual encoder initialized from pretrained OpenCLIP weights. The Vision Transformer extracted global and patch-level image features from 224 × 224 RGB inputs with 16 × 16 patches. The paired OpenCLIP Transformer extracted text features from captions tokenized with the OpenCLIP SimpleTokenizer. Captions were padded or truncated to 77 tokens, and both encoder towers were fine-tuned.
Training was performed for 150 epochs with a batch size of 32 using AdamW. The initial learning rate was 1 × 10 − 5 , with weight decay of 0.01 and first and second moment coefficients of β 1 = 0.9 and β 2 = 0.98 , respectively. A cosine schedule with 1000 warm-up steps was applied. Automatic mixed-precision training was used, with the maximum gradient norm set to 1.0.
Image filepaths defined the training sample groups. At each epoch, the sampler randomly selected one of the five descriptions for each image, yielding 3765 image–text pairs. Each mini-batch contained distinct image filepaths.
Training images underwent random resized cropping, light color perturbation, and low-probability Gaussian blur before OpenCLIP normalization. Validation and test images used shortest-edge resizing and center cropping. For LC-VBR, the patch retention ratio and minimum patch weight were fixed at 0.90 and 0.80, respectively. These configurations were maintained consistently across the corresponding comparison and ablation experiments.

3.2. Metrics for Evaluation

Following established image–text retrieval practice [38], we use the recall at K ( R @ K , with K = 1 , 5 , 10 ) and mean recall (mR). Candidates are ranked by cross-modal similarity. R @ K is the percentage of queries whose paired image or caption appears in the first K positions. mR averages the six recall values across image-to-text and text-to-image retrieval [39]. Each validation and test image has one reference description that defines its paired retrieval target.
At cutoff K, a query counts as a true positive if its paired target is among the top K results and as a false negative otherwise. Recall is calculated as
R @ K = TP TP + FN
Here, TP is the number of queries with a paired target in the top K results, and FN is the number without one. R@1, R@5, and R@10 use the first, fifth, and tenth rank as the cutoff, respectively.
The mean reciprocal rank (MRR) measures the rank of the paired target in each retrieval direction:
MRR = 1 Q ∑ q = 1 Q 1 r q ,
where Q denotes the number of queries and r q denotes the one-based rank of the paired target in the full candidate ranking. MRR values are expressed as percentages. Recall@K and MRR assess paired-record retrieval using the original image–text pairing as the relevance criterion, rather than broader clinical semantic relevance.

3.3. Main Retrieval Performance and External Baselines

Table 2 compares SwinePath-CLIP with five representative vision–language models on the SwinePath test set. BLIP and ALBEF represent fusion-oriented pretraining architectures [21,22], whereas SigLIP, EVA-CLIP, and OpenCLIP learn shared image–text embedding spaces through contrastive objectives [20,23,24]. All models followed the shared fine-tuning settings in Section 3.1, with the model-specific input configurations detailed below. For each model, the checkpoint with the highest validation mR provided the test results.
Table 2. Comparison of SwinePath-CLIP with representative vision–language models on the SwinePath dataset.
For BLIP, we used the Base model with a ViT-B/16 visual backbone and a MED text encoder, initialized from the Salesforce/blip-itm-base-coco checkpoint, which had undergone retrieval fine-tuning on COCO. ALBEF used the official 14M-pretrained checkpoint with a ViT-B/16 visual backbone and a BERT-base-uncased text encoder. SigLIP used the first-generation Base/16 model initialized from google/siglip-base-patch16-224, pretrained on English image–text pairs from WebLI. EVA-CLIP used EVA02-B-16 with the merged2b_s8b_b131k weights. The OpenCLIP baseline used the ViT-B-16 implementation initialized with OpenAI CLIP weights. The image input resolutions were 384 × 384 for BLIP, 256 × 256 for ALBEF, and 224 × 224 for the remaining models. SigLIP used a maximum text length of 64 tokens, while BLIP, ALBEF, EVA-CLIP, OpenCLIP, and SwinePath-CLIP used 77 tokens. The retrieval embedding dimensions were 256 for BLIP and ALBEF, 768 for SigLIP, and 512 for EVA-CLIP, OpenCLIP, and SwinePath-CLIP.
SwinePath-CLIP used the same ViT-B-16 architecture and OpenAI initialization weights as the OpenCLIP baseline. Both encoder towers were fine-tuned on SwinePath, with VPSG providing auxiliary phrase-level text views and LC-VBR introducing caption-guided visual regularization. During retrieval, the complete SwinePath-CLIP pipeline used TC-CSLS to rerank candidates based on the similarity scores computed from the learned image and text embeddings. The shared backbone and initialization provide a direct basis for comparison with the OpenCLIP baseline.
All models used the same test queries and candidate pools. The external baselines and SwinePath-CLIP without TC-CSLS ranked candidates via the cosine similarity between L2-normalized image and text embeddings. SwinePath-CLIP with TC-CSLS applied the score calibration described in Section 2.2.4. The evaluation used no image–text matching (ITM) reranking.
OpenCLIP had the highest mR among the external baselines, at 55.04%. SigLIP and EVA-CLIP shared the highest external I2T R@1, at 29.79%, while SigLIP achieved the highest external T2I R@1, at 31.49%. OpenCLIP performed best among the external baselines at the other recall cutoffs, sharing the highest T2I R@10 with SigLIP.
SwinePath-CLIP also achieved the highest MRR in both retrieval directions, reaching 50.98% for image-to-text retrieval and 50.68% for text-to-image retrieval. Compared with SigLIP, which achieved the highest MRR among the external baselines in both directions, these values represent gains of 7.08 and 5.36 percentage points, respectively. These results complement the Recall@K findings by showing the improved ranking of the original paired targets.
SwinePath-CLIP with TC-CSLS ranked first on all six recall metrics and mR. Its mR of 61.45% exceeded that of OpenCLIP by 6.42 percentage points, calculated from the unrounded results. The I2T R@1 reached 36.60%, 6.81 points above SigLIP and EVA-CLIP, and the T2I R@1 reached 35.53%, 4.04 points above SigLIP. The gains extended to the top-five and top-ten results. Relative to OpenCLIP, the I2T R@5 rose from 61.49% to 68.51% and R@10 from 74.89% to 79.57%, gains of 7.02 and 4.68 percentage points. The T2I R@5 rose from 62.34% to 69.15% and R@10 from 74.26% to 79.36%, gains of 6.81 and 5.10 points. Relative to the variant without TC-CSLS, score calibration increased mR by 2.02 percentage points, with additional gains of 2.56 points in I2T R@1 and 1.27 points in T2I R@1.
BLIP and ALBEF achieved lower recall than SigLIP, EVA-CLIP, and OpenCLIP under the evaluated global-embedding retrieval protocol without ITM reranking. SwinePath-CLIP without TC-CSLS achieved higher recall than OpenCLIP with the same backbone, initialization, and cosine ranking rule, supporting the contribution of domain-guided representation learning through VPSG and LC-VBR. Applying TC-CSLS to the learned embeddings provided a further improvement through retrieval-stage score calibration. Together, these comparisons support improvements from representation learning and candidate ranking while retaining the same encoder architecture.
To assess the effect of training variability on the main retrieval comparison, we repeated the experiment with three random seeds (Table 3).
Table 3. Test-set retrieval performance across three independent training runs (mean ± sample standard deviation, %).
SwinePath-CLIP with TC-CSLS achieved higher test mR than OpenCLIP with cosine similarity for each of the three random seeds. These repeated runs show that the advantage observed in the main comparison persisted when both models were retrained with different random seeds.

3.4. Ablation Study

The ablation study used OpenCLIP as the baseline to evaluate the contributions of VPSG, LC-VBR, and TC-CSLS on the SwinePath test set. Configurations with VPSG and LC-VBR individually and jointly assessed their training-stage contributions, while TC-CSLS assessed the additional effect of retrieval-stage score calibration. Table 4 reports the bidirectional R@1, R@5, R@10, and mR, together with 95% percentile confidence intervals for mR based on 1,000,000 bootstrap resamples of test image–text pairs.
Table 4. Ablation results for the proposed components.
VPSG and LC-VBR increased mR from the OpenCLIP baseline of 55.04% to 58.55% and 57.84%, respectively. LC-VBR achieved higher I2T R@1, whereas VPSG achieved higher T2I recall at all three cutoffs. Combining both modules further increased mR to 59.43%, with the I2T R@1 and T2I R@1 reaching 34.04% and 34.26%, respectively. These results support the joint use of phrase-level text guidance and caption-guided visual regularization.
TC-CSLS increased mR from 55.04% to 57.41% for OpenCLIP and from 59.43% to 61.45% for the VPSG + LC-VBR model, showing additional retrieval gains from score calibration.
LC-VBR + TC-CSLS and VPSG + TC-CSLS achieved mR values of 59.47% and 60.11%, respectively, below the full model’s 61.45%. The full combination therefore achieved the highest mR among the evaluated configurations.

3.5. Hyperparameter Sensitivity Analysis

The sensitivity analysis examined the LC-VBR patch weighting parameters and TC-CSLS transport parameters on the SwinePath validation set. Each experiment varied one parameter while keeping the remaining settings fixed. Figure 6 presents the results for the patch retention ratio r, minimum patch weight β min , transport scale γ tr , and transport support weight α TC .
Figure 6. Validation-set sensitivity of SwinePath-CLIP to LC-VBR and TC-CSLS hyperparameters: (a) patch retention ratio r; (b) minimum patch weight β min ; (c) transport scale γ tr ; and (d) transport support weight α TC . Each parameter is varied with the remaining settings fixed. Open circles indicate the reported configuration.
The minimum patch weight β min controls the contrast between caption-guided patch weights and the baseline contribution of other patches. With r = 0.90 , the validation mR reached 62.74% at β min = 0.80 , compared with 61.00% under uniform weighting at β min = 1.00 . This comparison highlights the benefit of differentiating patch contributions according to caption-derived relevance. The patch retention ratio also achieved its highest validation mR at r = 0.90 . This configuration applies caption-guided weighting to high-scoring patches while retaining baseline contributions from the remaining patches, combining selective emphasis with broader visual context.
The TC-CSLS transport scale γ tr controls the concentration of the transport kernel, while α TC determines the contribution of transport support to the final calibrated score. The validation mR varied by approximately 0.14 and 0.21 percentage points across their respective tested ranges, reaching 62.74% at γ tr = 3.0 and α TC = 0.05 . The retrieval performance remained relatively stable across the tested transport scales and support weights.
Figure 7 examines the auxiliary loss weights around the reference configuration of λ VPSG = 0.005 and λ LC - VBR = 0.05 . Each experiment independently halved or doubled one coefficient while keeping all other settings fixed.
Figure 7. Validation-set sensitivity to the auxiliary loss weights. (a) VPSG loss weight λ VPSG . (b) LC-VBR loss weight λ LC - VBR . Open circles indicate the reference configuration.
The reference configuration achieved the highest validation mR of 62.74%. Halving λ VPSG and λ LC - VBR yielded 61.39% and 61.36%, respectively, while doubling them yielded 62.56% and 62.31%. For both auxiliary objectives, reducing the loss weight produced a larger performance decrease than increasing it. This pattern indicates that the contribution of phrase-level alignment and local visual regularization depends on their weighting within the joint training objective.

3.6. LC-VBR Mechanism Analysis

We compared four variants to examine LC-VBR: global augmentation consistency, bridge target regularization without patch weighting, bridge target regularization with random weighting, and full LC-VBR with phrase-guided weighting. Table 5 separates the effects of the bridge target and the patch weighting strategy. All variants were evaluated on the test set with VPSG and TC-CSLS disabled.
Table 5. LC-VBR mechanism controls for image-to-text retrieval.
These controls examine two aspects of LC-VBR: the reference used to regularize the augmented visual representation and the weighting used to aggregate local evidence. Global augmentation consistency provides an image-based reference, whereas the bridge target incorporates semantics from the paired description. Comparing the bridge-only variant with full LC-VBR examines the contribution of local evidence aggregation. The random-weighting control further tests whether the observed benefit depends on caption-derived guidance rather than patch reweighting alone.
Global augmentation consistency gave R@1, R@5, and R@10 values of 29.15%, 62.34%, and 72.98%. Introducing the bridge target raised them to 31.06%, 62.98%, and 74.26%. The target constrains the augmented visual representation using an interpolation of the paired global image and text embeddings. Phrase-guided patch weighting further raised R@1, R@5, and R@10 to 32.98%, 64.26%, and 76.81%, constituting gains of 1.92, 1.28, and 2.55 percentage points over the bridge-only variant. The phrase guidance weights patches by their correspondence to the caption, directing the local representation toward relevant lesion and anatomical features. Phrase-guided weighting exceeded random weighting by 1.49 points at R@1 and 0.86 points at R@5. Both reached 76.81% at R@10.
Taken together, the comparisons suggest that the bridge target and phrase-guided weighting contribute through different parts of the regularization process. The bridge target provides a shared image–text reference, while patch weighting determines the local evidence included in the fused visual representation. Random weighting also yields competitive results, indicating that part of the benefit can arise without semantic guidance. Nevertheless, phrase-guided weighting performs better at R@1 and R@5, while matching random weighting at R@10. Its advantage is therefore concentrated in the leading retrieval positions, consistent with the usefulness of caption-compatible local evidence for distinguishing records with similar overall appearances. For gross pathology retrieval, this distinction is relevant when the organ is readily recognizable but the matching description depends on finer lesion characteristics.

3.7. VPSG Parameter Sensitivity and Masking Strategy Analysis

This section examines VPSG in terms of the masking ratio and masking strategy. The mask ratio experiment evaluates how the extent of caption reduction affects the retrieval performance, while the masking strategy experiment compares different approaches to selecting the removed content. Together, these experiments examine the relationship between auxiliary text view construction and retrieval performance.
Table 6 reports the test-set results for OpenCLIP with VPSG alone; the mask ratio was selected on the validation set.
Table 6. Sensitivity of retrieval performance to the VPSG mask ratio.
Increasing the ratio from 0.20 to 0.40 raised mR from 57.16% to 58.55%, whereas ratios of 0.50 and 0.60 yielded 57.55% and 58.05%, respectively. This pattern suggests a balance between auxiliary view variation and the preservation of descriptive context.
Table 7 compares random token masking, random phrase masking, and VPSG at the selected ratio. All masking strategies used the same configuration as in Table 6, with a mask ratio of 0.40. Random token masking operates on individual tokens and can separate words that jointly describe an anatomical site or pathological attribute. Random phrase masking removes complete phrases, preserving the internal semantic structure of those that remain. VPSG further incorporates content selection into phrase-level masking: its masking priority score favors the retention of lesion, symptom, and anatomical information while reducing repetitive background wording. The comparison therefore examines both masking granularity and differences in the content retained in the auxiliary view.
Table 7. Comparison of VPSG masking strategies.
VPSG achieved the highest mR of 58.55%, exceeding random token masking and random phrase masking by 0.93 and 0.57 percentage points, respectively. It also attained the highest I2T R@1 of 32.13%. Relative to random phrase masking, VPSG improved the I2T and T2I R@1 by 0.64 and 1.48 percentage points, respectively. These results support incorporating domain-informed content selection into phrase-level masking. Preserving descriptions associated with visual lesions yielded better aggregate retrieval performance than randomly selecting phrases for removal. Phrase-level operations maintain the grouping of related words, while salience guidance further adjusts the informational emphasis of the auxiliary caption in accordance with the design of VPSG. The strategies exhibited different performance patterns across the two retrieval directions. Random token masking achieved the highest T2I R@1 of 33.19%, whereas VPSG performed better in the I2T R@1 and mR. I2T retrieval requires an image representation to identify its matching description among candidate texts, while T2I retrieval requires a text representation to distinguish the matching image from candidate images. These tasks place different demands on cross-modal ranking. Moreover, R@1 measures whether the correct match occupies the leading position, whereas mR aggregates the recall across both directions and multiple ranking thresholds. Considering these metrics jointly provides a more comprehensive assessment of how auxiliary text view construction affects retrieval performance.
Taken together, Table 6 and Table 7 characterize the effects of the masking extent and content selection in VPSG. A mask ratio of 0.40 achieved the highest observed mR among the evaluated ratios, while the masking strategy comparison supports the benefit of salience-guided phrase selection. These findings are consistent with a balance between auxiliary view variation and the preservation of pathological and anatomical information.

3.8. Standard CSLS Reranking and Incremental Transport Calibration

Table 8 compares cosine ranking, standard CSLS, and TC-CSLS on fixed embeddings from the same VPSG + LC-VBR checkpoint. Keeping the embeddings fixed isolates the effect of the ranking method.
Table 8. Effect of inference-time reranking. Values are percentages.
Standard CSLS raised mR from 59.43% with cosine ranking to 61.24%, a gain of 1.81 percentage points. The I2T R@1 increased from 34.04% to 36.17%, and the T2I R@5 rose from 67.02% to 68.72%. These gains followed the adjustment of the pairwise scores for local cross-modal density, reducing the ranking advantage of candidates with high similarity to many queries. This is relevant to SwinePath, where similar lesion appearances and repeated anatomical terms can produce high similarity across multiple records.
TC-CSLS raised mR to 61.45%, 0.21 percentage points above standard CSLS and 2.02 percentage points above cosine ranking. The T2I R@5 rose from 68.72% to 69.15%, while the T2I R@1 and R@10 matched those of standard CSLS. The balanced support term derives support from the full query–candidate score matrix, accounting for competing matches on both sides and providing an additional criterion for candidate ordering.
Figure 8 shows how the ranking methods affected candidate concentration. TC-CSLS reduced the top-1% share from 3.11% to 2.44% in I2T retrieval and from 2.91% to 2.40% in T2I retrieval. The Gini coefficient fell from 0.331 to 0.214 for I2T and from 0.294 to 0.211 for T2I. Both measures indicate that appearances in the top-5 lists were distributed more evenly across candidates. Thus, the recall gains in Table 8 were accompanied by lower candidate concentration.
Figure 8. Candidate concentration comparison between cosine ranking and TC-CSLS in image-to-text (I2T) and text-to-image (T2I) retrieval. Top-1% share represents the proportion of top-5 retrieval occurrences accounted for by the most frequently retrieved 1% of candidates, while the Gini coefficient measures the overall inequality of candidate occurrence. Lower values indicate a more balanced candidate distribution. Bars show the mean across three runs with different random seeds (0, 1, and 2), and error bars indicate ± 1 sample standard deviation.
Together, Table 8 and Figure 8 show that TC-CSLS improved the retrieval recall while reducing candidate concentration relative to cosine ranking. The higher recall indicates the better placement of the paired records, while the lower top-1% share and Gini coefficient show that top-5 appearances were distributed more evenly across candidates. These results connect retrieval accuracy with the distribution of retrieved records. Standard CSLS provided most of the recall improvement.

3.9. Qualitative Retrieval and Visual Evidence

Color coding compares anatomical and lesion attributes in the query and retrieved descriptions, using paired descriptions to represent images. Green indicates agreement in the organ and all explicitly specified key lesion attributes. Orange indicates organ agreement with partial attribute support and no explicit contradiction, including cases with missing information. Red indicates an organ mismatch or an explicit contradiction in a key lesion attribute.
Figure 9 compares the top-five image-to-text results for a gross spleen query. The query image appears on the left, followed by the captions retrieved by the baseline and SwinePath-CLIP in ranked order. Both models retrieved spleen-related descriptions. The baseline ranked the description of surface protrusions and blue–purple discoloration fourth, whereas SwinePath-CLIP placed it first. SwinePath-CLIP therefore brought the description matching both the lesion color and surface morphology to the top of the list.
Figure 9. Illustrative I2T retrieval for a spleen query. Colors denote author-assessed overlap between the query and retrieved anatomical and lesion attributes.
Figure 10 compares the top-five T2I results for a porcine lung query describing embolic pneumonia, pleuropneumonia, and microabscesses. The baseline retrieved five images with partial attribute agreement, whereas SwinePath-CLIP ranked an image matching the anatomical site and key lesion attributes first. This example illustrates the improved prioritization of a matching record for a query containing multiple pathological attributes.
Figure 10. Illustrative T2I retrieval for a porcine lung lesion query. Colors denote author-assessed overlap between the query and retrieved anatomical and lesion attributes.
Figure 11 presents three test-set top-1 I2T retrieval mismatches relative to the original paired descriptions.
Figure 11. Selected top-1 image-to-text retrieval failures of SwinePath-CLIP with TC-CSLS on the test set: (a) same-organ description mismatch; (b) normal-versus-ulceration description mismatch; and (c) abscess-related descriptions referring to different organs. Each panel shows the query image, its original paired description, and the top-1 retrieved description.
In Figure 11a, the retrieved description matches the lung and inflammatory context but differs in the specific disease description. Figure 11b shows a normal-versus-ulceration mismatch, while Figure 11c matches the abscess attribute but identifies the brain instead of the lung. These cases show that agreement in shared anatomical or lesion features can coexist with mismatches in disease description, pathological status, or organ identity.
Figure 12 visualizes the LC-VBR patch weights for four representative image–text pairs.
Figure 12. Visualization of LC-VBR patch weights for representative image–text pairs in SwinePath. Each panel shows the paired description above the original image (left) and the corresponding heatmap overlay (right). Warmer colors indicate stronger responses. (a) Cutaneous pityriasis rosea. (b) Chronic ulceration of the pars esophagea. (c) Vertebral abscess. (d) Tarsal joint abscess.
High-weight regions overlap with annular skin lesions in Figure 12a, the ulcerated pars esophagea in Figure 12b, and the vertebral and tarsal abscess regions in Figure 12c,d. These visualizations illustrate spatial correspondence between the LC-VBR patch weights and the visible lesion regions.

3.10. Performance and Efficiency Analysis

Table 9 reports the retrieval performance, input resolution, deployment parameters, image-side GFLOPs, and image encoding latency. To compare the encoder-level efficiency, SwinePath-CLIP is evaluated without TC-CSLS, which operates on the similarity matrix after feature extraction and introduces a separate ranking cost that depends on the numbers of queries and candidates. Measurements were conducted in the environment described in Section 3.1.
Table 9. Comparison of retrieval performance and computational efficiency under the evaluated model configurations. Deployment parameters refer to the model parameters retained during inference. Image encoding latency is reported as the mean ± standard deviation in milliseconds per image. Input resolution is listed as part of the evaluated configuration for each method.
Among the external baselines, OpenCLIP achieved mR of 55.04% with 149.62 M deployment parameters, 17.56 GFLOPs per image, and image encoding latency of 2.467 ± 0.015 ms/image. SwinePath-CLIP with cosine ranking increased mR to 59.43%, corresponding to an improvement of 4.39 percentage points. Its deployment parameters and image-side computational cost remained unchanged from those of OpenCLIP, while its image encoding latency was 2.467 ± 0.104 ms/image. Within the methods using 224 × 224 image inputs, SwinePath-CLIP achieved the highest mR while maintaining a compact computational configuration. Compared with SigLIP, it used fewer deployment parameters and slightly fewer GFLOPs per image, while increasing mR from 54.50% to 59.43%. Compared with EVA-CLIP, SwinePath-CLIP had a comparable parameter count and the same reported image-side GFLOPs, while improving mR by 6.42 percentage points. Its image encoding latency was 2.467 ± 0.104 ms/image, compared with 3.013 ± 0.428 ms/image for SigLIP and 4.981 ± 0.484 ms/image for EVA-CLIP. The unchanged deployment parameter count and image-side GFLOPs reflect how VPSG and LC-VBR are incorporated into the framework. Both components guide representation learning during training, while retrieval uses the same dual-encoder architecture as OpenCLIP. The auxiliary text view and caption-guided visual regularization therefore improve the learned representations without adding an inference-time encoding branch.
The 4.39-point gain in mR was obtained through domain-guided training rather than an increase in input resolution or encoder size. The dual-encoder structure also allows candidate embeddings to be computed in advance and reused during retrieval. Once the candidate records have been encoded, a query can be matched against their stored representations without repeatedly processing each image–text pair through the encoders. TC-CSLS adds a subsequent score calibration step, separating representation extraction from ranking refinement. Table 9 and Section 3.8 therefore describe two complementary aspects of the framework: VPSG and LC-VBR improve retrieval at the same reported encoder cost as OpenCLIP, while TC-CSLS provides a further recall gain through additional score matrix operations.
Latency measurements used the hardware configuration described in Section 3.1 and batches of 470 queries. Timing covered the complete retrieval pipeline of SwinePath-CLIP with TC-CSLS, from in-memory image bytes or raw text to the CPU availability of the top-10 results for all queries. Candidate embeddings remained preloaded in memory. Each setting included three warm-up runs followed by ten timed runs, with the two gallery sizes tested in alternating order. GPU synchronization before and after each timed run ensured complete execution within the measurement interval. Table 10 reports the median and interquartile range (IQR) of the batch latency.
Table 10. End-to-end batch retrieval latency of SwinePath-CLIP with TC-CSLS at two gallery sizes.
With candidate embeddings preloaded and 470 queries per batch, expanding the gallery from 470 to 4700 items had little effect on the end-to-end batch latency, indicating limited additional latency from gallery expansion within the evaluated range.

4. Discussion

This study develops SwinePath-CLIP, a domain-guided framework for the bidirectional retrieval of swine gross pathology images and veterinary descriptions, together with the curated SwinePath dataset. Its three components address complementary aspects of retrieval: VPSG emphasizes informative veterinary phrases through auxiliary text views; LC-VBR incorporates caption-guided local visual evidence through patch weighting and cross-modal bridge regularization; and TC-CSLS adjusts candidate rankings using local density correction and balanced transport support. The experimental findings support the combination of these training and ranking strategies to improve the retrieval of paired pathology records.
The training module comparisons highlight the value of incorporating domain guidance into both text and visual representation learning (Table 4). Although SwinePath descriptions are curated, their constituent phrases differ in the anatomical and pathological information that they convey. VPSG provides an auxiliary view that prioritizes these attributes. Its higher mR than random token and random phrase masking supports domain-informed content selection when constructing auxiliary text views (Table 7). On the visual side, LC-VBR gives caption-compatible patch features an explicit role in training, while the bridge target connects the fused local–global representation with paired textual semantics. The mechanism comparisons show retrieval improvements from introducing the bridge target and further gains from phrase-guided patch weighting (Table 5). These findings support the combination of a cross-modal regularization target and description-guided local evidence aggregation.
TC-CSLS extends these improvements to the ranking stage. By combining neighborhood-based density correction with matrix-wide support balancing, it adjusts candidate scores according to the similarity relationships within the query–candidate collection. The fixed-embedding comparison separates this ranking effect from representation learning (Table 8). Compared with cosine ranking, TC-CSLS improves the retrieval recall and reduces candidate concentration in the top-five results (Figure 8). These findings support score calibration as a complementary step after domain-guided representation learning.
The framework retains the deployment advantages of independently computable image and text embeddings. VPSG and LC-VBR operate during training, preserving the baseline encoder’s deployment parameter count and image encoding cost (Table 9). Candidate features can be cached for repeated searches, while TC-CSLS operates after feature extraction.
Several limitations remain. First, SwinePath consists of curated veterinary atlas and archival image–text pairs. Its evaluation setting differs from routine farm records, which may contain more variable image backgrounds, acquisition quality, and descriptions. Further evaluation on such records is needed to assess performance under practical conditions. Second, the uneven category distribution may limit the diversity of training examples for underrepresented categories. Categories with more test queries also contribute more strongly to aggregate retrieval metrics, which may obscure performance differences across categories. Third, the retrieval and mechanism comparisons support the contribution of LC-VBR to the retrieval performance, while the patch weight visualizations provide qualitative observations of local visual correspondence. Quantifying this correspondence requires independent expert annotations of lesion regions.
Medical vision–language models such as GLoRIA [11] and MedCLIP [9] offer additional directions for investigating domain transfer. GLoRIA’s alignment of image regions with report words could inform the association between local visual evidence and veterinary phrases. MedCLIP’s semantic matching objective could inform approaches to false negatives when records from different cases describe similar lesions. Their use in swine gross pathology retrieval requires evaluation across differences in image modality, species anatomy, and terminology. Comparing zero-shot transfer and fine-tuning on the SwinePath training split, using the same test split and bidirectional retrieval metrics, could clarify the value of medical pretraining in this setting.
Future work will incorporate real-world swine farm images and original records to evaluate retrieval under varied textual and visual conditions. Expert-annotated lesion regions will support the quantitative assessment of local visual–textual correspondence and guide the refinement of caption-guided visual learning. Further evaluation in larger, continuously updated archives will examine feature indexing, ranking updates, and query latency. Together, these efforts will extend the evaluation from curated paired-record retrieval toward practical veterinary archive searches.

5. Conclusions

This study developed SwinePath-CLIP and the curated SwinePath dataset for the bidirectional retrieval of swine gross pathology images and veterinary descriptions. The framework combines domain-guided representation learning with retrieval-stage score calibration, achieving a test-set mR value of 61.45%. The ablation and mechanism comparisons support the contributions of phrase-level text guidance, description-guided patch weighting, and cross-modal bridge regularization. The fixed-embedding ranking experiments further show that TC-CSLS improves the recall and reduces candidate concentration compared with cosine ranking. Together, these findings highlight the value of incorporating veterinary information into representation learning and accounting for query–candidate similarity relationships during ranking.
The framework preserves independently computable image and text embeddings, allowing candidate features to be cached for repeated searches. VPSG and LC-VBR operate during training, retaining the baseline encoder’s deployment parameter count and image encoding cost. These properties provide a practical basis for the further development of veterinary archive retrieval systems.
Future work will evaluate retrieval under variations in farm image quality and veterinary descriptions and assess query latency and ranking updates in larger, continuously updated archives.

Author Contributions

Z.Z. and Z.D. were responsible for conceptualization and writing the original draft; Z.W., X.L., and B.W. contributed to review and editing; Z.D. and Z.Z. coordinated project administration and funding acquisition; B.W. designed the methodology; Z.Z. performed software implementation; and Z.Z. and Z.D. conducted validation. All authors have read and agreed to the published version of the manuscript.

Funding

This study was supported by the Major Special Project of the Guangdong Provincial Science and Technology Plan, China (funder: Department of Science and Technology of Guangdong Province; Grant No. 2016B010110005).

Institutional Review Board Statement

The development and evaluation of SwinePath-CLIP were conducted in accordance with established ethical and transparency standards. All datasets used were open-source or derived from university-approved agricultural materials, ensuring proper data usage and copyright adherence. No human participants or prospective live-animal experiments were involved, and no personal or sensitive data were collected.

Data Availability Statement

Publicly accessible source materials are available from Noah’s Arkive of the Davis-Thompson Foundation at https://davisthompsonfoundation.org/noahs-arkive/ (accessed on 15 September 2026).

Acknowledgments

During the preparation of this manuscript, the authors used generative artificial intelligence tools solely to assist with translating the manuscript. The authors reviewed and edited all translated content and take full responsibility for the content of this publication.

Conflicts of Interest

The authors declare no conflicts of interest. The funders had no role in the design of the study; in the collection, analyses, or interpretation of the data; in the writing of the manuscript; or in the decision to publish the results.

References

  1. Garcia, R.; Aguilar, J.; Toro, M.; Pinto, A.; Rodriguez, P. A systematic literature review on the use of machine learning in precision livestock farming. Comput. Electron. Agric. 2020, 179, 105826. [Google Scholar] [CrossRef] [Scilit]
  2. Halev, A.; Martinez-Lopez, B.; Clavijo, M.; Gonzalez-Crespo, C.; Kim, J.; Huang, C.; Krantz, S.; Robbins, R.; Liu, X. Infection prediction in swine populations with machine learning. Sci. Rep. 2023, 13, 17738. [Google Scholar] [CrossRef] [Scilit] [PubMed]
  3. Reza, M.N.; Lee, K.-H.; Habineza, E.; Samsuzzaman; Kyoung, H.; Choi, Y.K.; Kim, G.; Chung, S.-O. RGB-based machine vision for enhanced pig disease symptoms monitoring and health management: A review. J. Anim. Sci. Technol. 2025, 67, 17–42. [Google Scholar] [CrossRef] [Scilit] [PubMed]
  4. Xiao, S.; Dhand, N.K.; Wang, Z.; Hu, K.; Thomson, P.C.; House, J.K.; Khatkar, M.S. Review of applications of deep learning in veterinary diagnostics and animal health. Front. Vet. Sci. 2025, 12, 1511522. [Google Scholar] [CrossRef] [Scilit] [PubMed]
  5. Wang, H.; Shen, W.; Zhang, Y.; Gao, M.; Zhang, Q.; A, X.; Du, H.; Qiu, B. Diagnosis of dairy cow diseases by knowledge-driven deep learning based on the text reports of illness state. Comput. Electron. Agric. 2023, 205, 107564. [Google Scholar] [CrossRef] [Scilit]
  6. Li, H.; Li, B.; Li, H.; Chen, M.; Song, Y.; Liu, Z. A lightweight decision-level fusion model for pig disease identification using multi-modal data. Comput. Electron. Agric. 2025, 231, 109936. [Google Scholar] [CrossRef] [Scilit]
  7. Yang, G.; Li, Q.; Zhao, C.; Wang, C.; Yan, H.; Meng, R.; Liu, Y.; Yu, L. TGFN-SD: A text-guided multimodal fusion network for swine disease diagnosis. Artif. Intell. Agric. 2025, 15, 266–279. [Google Scholar] [CrossRef] [Scilit]
  8. Zhang, Y.; Jiang, H.; Miura, Y.; Manning, C.D.; Langlotz, C.P. Contrastive learning of medical visual representations from paired images and text. arXiv 2020, arXiv:2010.00747. [Google Scholar] [CrossRef] [Scilit]
  9. Wang, Z.; Wu, Z.; Agarwal, D.; Sun, J. MedCLIP: Contrastive learning from unpaired medical images and text. In Proceedings of the 2022 Conference on Empirical Methods in Natural Language Processing, Abu Dhabi, United Arab Emirates, December 2022; Association for Computational Linguistics: Stroudsburg, PA, USA, 2022; pp. 3876–3887. [Google Scholar] [CrossRef] [Scilit] [PubMed]
  10. Huang, Z.; Bianchi, F.; Yuksekgonul, M.; Montine, T.J.; Zou, J. A visual-language foundation model for pathology image analysis using medical Twitter. Nat. Med. 2023, 29, 2307–2316. [Google Scholar] [CrossRef] [Scilit] [PubMed]
  11. Huang, S.-C.; Shen, L.; Lungren, M.P.; Yeung, S. GLoRIA: A multimodal global-local representation learning framework for label-efficient medical image recognition. In Proceedings of the IEEE/CVF International Conference on Computer Vision, Montreal, QC, Canada, 10–17 October 2021; IEEE: Piscataway, NJ, USA, 2021; pp. 3942–3951. [Google Scholar] [CrossRef] [Scilit]
  12. Xu, J.; Zhou, H.; Hu, Y.; Xue, Y.; Zhou, G.; Li, L.; Dai, W.; Li, J. High-accuracy tomato leaf disease image-text retrieval method utilizing LAFANet. Plants 2024, 13, 1176. [Google Scholar] [CrossRef] [Scilit] [PubMed]
  13. Wei, T.; Chen, Z.; Yu, X. Snap and diagnose: An advanced multimodal retrieval system for identifying plant diseases in the wild. In Proceedings of the 6th ACM International Conference on Multimedia in Asia, Auckland, New Zealand, 4–6 December 2024; Association for Computing Machinery: New York, NY, USA, 2024; Article 131; pp. 1–3. [Google Scholar] [CrossRef] [Scilit]
  14. Zhou, H.; Hu, Y.; Liu, S.; Zhou, G.; Xu, J.; Chen, A.; Wang, Y.; Li, L.; Hu, Y. A precise framework for rice leaf disease image-text retrieval using FHTW-Net. Plant Phenomics 2024, 6, 0168. [Google Scholar] [CrossRef] [Scilit] [PubMed]
  15. Yu, J.; Li, Z.; Hao, L.; Tian, E.; Shu, Z. Cross-modal wolfberry pest retrieval based image and text hash feature learning. Trans. Chin. Soc. Agric. Eng. 2025, 41, 202–210. [Google Scholar] [CrossRef]
  16. Zhu, H.; Lu, X.; Zhang, L. Research on image-text retrieval method for tomato leaf diseases and pests with class imbalance based on contrastive learning. J. Shandong Agric. Univ. (Nat. Sci. Ed.) 2026, 57, 166–178. [Google Scholar] [CrossRef]
  17. Yu, K.; Ma, W.; Chen, S.; Wu, X.; Wang, Y.; Zhou, T. CPCR: Crop pests cross-modal retrieval with prior instruction via multimodal large language model. Comput. Electron. Agric. 2026, 245, 111546. [Google Scholar] [CrossRef] [Scilit]
  18. Xu, X.; Yang, X.; Li, S.; Ye, Y.; Zhou, C. Fish disease cross-modal image-text retrieval model in aquaculture. J. ASABE 2026, 69, 119–132. [Google Scholar] [CrossRef] [Scilit]
  19. Radford, A.; Kim, J.W.; Hallacy, C.; Ramesh, A.; Goh, G.; Agarwal, S.; Sastry, G.; Askell, A.; Mishkin, P.; Clark, J.; et al. Learning transferable visual models from natural language supervision. In Proceedings of the 38th International Conference on Machine Learning, Virtual Event, 18–24 July 2021; PMLR: Cambridge, MA, USA, 2021; Volume 139, pp. 8748–8763. Available online: https://proceedings.mlr.press/v139/radford21a.html (accessed on 10 November 2026).
  20. Cherti, M.; Beaumont, R.; Wightman, R.; Wortsman, M.; Ilharco, G.; Gordon, C.; Schuhmann, C.; Schmidt, L.; Jitsev, J. Reproducible scaling laws for contrastive language-image learning. In Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition, Vancouver, BC, Canada, 18–22 June 2023; IEEE: Piscataway, NJ, USA, 2023; pp. 2818–2829. [Google Scholar] [CrossRef] [Scilit]
  21. Li, J.; Selvaraju, R.R.; Gotmare, A.D.; Joty, S.; Xiong, C.; Hoi, S.C.H. Align before fuse: Vision and language representation learning with momentum distillation. Adv. Neural Inf. Process. Syst. 2021, 34, 9694–9705. Available online: https://proceedings.neurips.cc/paper/2021/hash/505259756244493872b7709a8a01b536-Abstract.html (accessed on 10 November 2026).
  22. Li, J.; Li, D.; Xiong, C.; Hoi, S.C.H. BLIP: Bootstrapping language-image pre-training for unified vision-language understanding and generation. In Proceedings of the 39th International Conference on Machine Learning, Baltimore, MD, USA, 17–23 July 2022; PMLR: Cambridge, MA, USA, 2022; Volume 162, pp. 12888–12900. Available online: https://proceedings.mlr.press/v162/li22n.html (accessed on 10 November 2026).
  23. Zhai, X.; Mustafa, B.; Kolesnikov, A.; Beyer, L. Sigmoid loss for language image pre-training. In Proceedings of the IEEE/CVF International Conference on Computer Vision, Paris, France, 1–6 October 2023; IEEE: Piscataway, NJ, USA, 2023; pp. 11975–11986. [Google Scholar] [CrossRef] [Scilit]
  24. Sun, Q.; Fang, Y.; Wu, L.; Wang, X.; Cao, Y. EVA-CLIP: Improved training techniques for CLIP at scale. arXiv 2023, arXiv:2303.15389. [Google Scholar] [CrossRef] [Scilit]
  25. Jing, D.; He, X.; Luo, Y.; Fei, N.; Yang, G.; Wei, W.; Zhao, H.; Lu, Z. FineCLIP: Self-distilled region-based CLIP for better fine-grained understanding. Adv. Neural Inf. Process. Syst. 2024, 37, 27896–27918. [Google Scholar] [CrossRef] [Scilit]
  26. Radovanovic, M.; Nanopoulos, A.; Ivanovic, M. Hubs in space: Popular nearest neighbors in high-dimensional data. J. Mach. Learn. Res. 2010, 11, 2487–2531. Available online: https://www.jmlr.org/papers/v11/radovanovic10a.html (accessed on 10 November 2026).
  27. Xi, K. A Practical Guide to Diagnosis and Treatment of Swine Diseases; China Machine Press: Beijing, China, 2017. [Google Scholar]
  28. Zheng, R.; Wang, Y. Pictorial Guide to Diagnosis and Treatment of Swine Diseases; China Machine Press: Beijing, China, 2017. [Google Scholar]
  29. Li, X. Rapid Diagnosis, Prevention, and Control Techniques for Swine Diseases: Video-Updated Edition; China Machine Press: Beijing, China, 2018. [Google Scholar]
  30. Pan, Y.; Liu, X. Color Atlas of Diagnosis and Treatment of Swine Diseases; China Agriculture Press: Beijing, China, 2010. [Google Scholar]
  31. Ma, Y.; Gu, F.; Meng, F.; Wang, F.; Song, C.; Wang, H.; Li, S. Questions and Answers on Diagnosis and Treatment of Swine Diseases; China Machine Press: Beijing, China, 2014. [Google Scholar]
  32. Zhu, L.; Wang, C. Full-Color Atlas of Diagnosis and Treatment of Swine Diseases; China Machine Press: Beijing, China, 2018. [Google Scholar]
  33. Wang, Z.; Gao, F.; Sun, H. Illustrated Differential Diagnosis, Prevention, and Control of Swine Diseases; China Machine Press: Beijing, China, 2017. [Google Scholar]
  34. Gu, F.; Ma, Y.; Wang, Z. Color Atlas of Clinical Diagnosis and Treatment of Swine Diseases; China Machine Press: Beijing, China, 2015. [Google Scholar]
  35. Studdert, V.P.; Gay, C.C.; Hinchcliff, K.W. Saunders Comprehensive Veterinary Dictionary, 5th ed.; Elsevier: Amsterdam, The Netherlands, 2020; ISBN 9780702074639. [Google Scholar]
  36. Jiang, Q.; Chen, C.; Zhao, H.; Chen, L.; Ping, Q.; Tran, S.D.; Xu, Y.; Zeng, B.; Chilimbi, T. Understanding and constructing latent modality structures in multi-modal representation learning. In Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition, Vancouver, BC, Canada, 18–22 June 2023; IEEE: Piscataway, NJ, USA, 2023; pp. 7661–7671. [Google Scholar] [CrossRef] [Scilit]
  37. Conneau, A.; Lample, G.; Ranzato, M.; Denoyer, L.; Jegou, H. Word translation without parallel data. In Proceedings of the 6th International Conference on Learning Representations, Vancouver, BC, Canada, 30 April–3 May 2018; Available online: https://openreview.net/forum?id=H196sainb (accessed on 10 November 2026).
  38. Lee, K.-H.; Chen, X.; Hua, G.; Hu, H.; He, X. Stacked cross attention for image-text matching. In Proceedings of the European Conference on Computer Vision; Springer: Cham, Switzerland, 2018; pp. 201–216. Available online: https://www.ecva.net/papers/eccv_2018/papers_ECCV/html/Kuang-Huei_Lee_Stacked_Cross_Attention_ECCV_2018_paper.php (accessed on 10 November 2026).
  39. Geigle, G.; Pfeiffer, J.; Reimers, N.; Vulić, I.; Gurevych, I. Retrieve fast, rerank smart: Cooperative and joint approaches for improved cross-modal retrieval. Trans. Assoc. Comput. Linguist. 2022, 10, 503–521. [Google Scholar] [CrossRef] [Scilit]
Disclaimer/Publisher’s Note: The statements, opinions and data contained in all publications are solely those of the individual author(s) and contributor(s) and not of MDPI and/or the editor(s). MDPI and/or the editor(s) disclaim responsibility for any injury to people or property resulting from any ideas, methods, instructions or products referred to in the content.

Article Metrics

Citations

Article Access Statistics

Article metric data becomes available approximately 24 hours after publication online.