Manuscript Offprint
arXiv:2610.02378THPL: A Vision-to-Language Decision Support Framework for Rainbow Trout Feeding Management in RAS
Affiliations
College of Biosystems Engineering and Food Science, Zhejiang University, Hangzhou 310058, Zhejiang, PR China
School of Mechanical and Aerospace Engineering, Nanyang Technological University, Singapore 639798, Singapore
College of Marine Technology and Environment, Dalian Ocean University, Dalian 116023, Liaoning, PR China
College of Engineering, Nanjing Agricultural University, Nanjing 210031, Jiangsu, PR China
Equal Contribution
*Corresponding Author: zhma_20@zju.edu.cn, liuyingzju@zju.edu.cn
Abstract
In Recirculating Aquaculture Systems (RAS), precision feeding serves as a critical prerequisite for minimizing operational costs and improving fish welfare. However, existing methodologies suffer from a lack of cognitive alignment between fish behavioral representations and aquaculture management knowledge, which impedes their direct translation into executable and interpretable feeding decisions. To address this challenge, this study proposes THPL, a generative feeding decision framework tailored for rainbow trout (Oncorhynchus mykiss) cultured in RAS. First, a Fishsort is utilized to extract schooling trajectories and establish an Activity Coefficient (AC) quantifying feeding intensity. Second, a Hierarchical Behavior Encoder (HBE) is constructed to sequentially model individual temporal progression and collective group dynamics using a Temporal Transformer and a Set Transformer, transforming trajectory tensors into a dual evidence behavioral representation comprising explicit physical tokens and implicit soft tokens. Finally, these behavioral tokens are integrated with masked multidimensional environmental parameters, aquaculture background data, and expert control rules to conduct Low Rank Adaptation (LoRA) fine-tuning on a large language model (LLM), followed by joint parameter optimization using counterfactual multimodal Direct Preference Optimization (mDPO) to reinforce causal reasoning capacity. Experimental results show that the AC exhibits a statistically significant monotonic positive correlation with expert annotated feeding intensity (Spearman , p < 0.001). Ablation experiments further indicate that the overall feeding decision accuracy improves from 33.33% for the text only baseline to 93.33% with the incorporation of dual evidence behavioral tokens. These findings confirm that continuous spatiotemporal behavioral tokens provide the necessary physical grounding for LLM, establishing precise alignment between fish spatiotemporal dynamics and expert feeding protocols. Compared with standard LoRA fine tuning, counterfactual mDPO alignment elevates overall decision accuracy from 93.33% to 96.67%, advances METEOR from 58.10% to 85.30%, reduces Self-BLEU-2 from 58.79% to 52.88%, and increases Distinct-3 from 6.68% to 7.81%, demonstrating that this strategy effectively suppresses templating and rectifies actuation biases while enriching adaptive reasoning diversity.
and reinforcing both causal consistency and operational safety. Overall, by integrating continuous spatiotemporal fish kinematics with causal reasoning in LLM, this study provides a novel decision support paradigm for precision feeding management in aquaculture.
1. Introduction
Precision feeding serves as a pivotal strategy for optimizing production efficiency within Recirculating Aquaculture Systems (RAS). Dynamically modulating feeding strategies according to fish feeding behavior can lower production costs while mitigating the adverse impacts of overfeeding on the aquaculture environment and fish welfare. In actual production, routine feeding decisions still predominantly rely on manual observation, empirical judgment, or predefined feeding schedules. Due to the lack of standardized, quantitative characterizations of schooling feeding states, feeding strategies struggle to adapt dynamically to behavioral variations, thereby escalating the risk of feed undersupply or oversupply. Feeding deviations lead to elevated feed conversion ratio (FCR), water quality deterioration, increased operating costs, and compromised fish welfare (Van Riel et al., 2023; Cho et al., 2024; Hvas et al., 2024). Therefore, there is a clear need to establish intelligent decision support systems capable of objectively quantifying fish schooling feeding states and dynamically adjusting feeding strategies accordingly, thereby elevating the precision, interpretability, and operational executability of feeding management.
In recent years, computer vision has been widely applied to fish feeding intensity assessment (FFIA) owing to its noninvasive nature, intuitive reflection of schooling behavior, and cost effectiveness. Building on this foundation, task-specific models (TSMs) based on machine learning and deep learning have further enhanced the accuracy and efficiency of feeding state quantification, providing quantitative criteria for feeding strategy optimization (Nielsen et al., 2016; Wang et al., 2021; Yang et al., 2021). In general, feeding intensity quantification methods can be categorized into indirect and direct approaches (Li et al., 2020). Indirect quantification mainly infers fish feeding states through secondary external manifestations such as surface disturbances or residual feed, including the analysis of light reflection, splash ripples, and the spatial distribution of uneaten feed. Recent deep learning methods have substantially improved the recognition performance of such manifestations, with splash feature based feeding intensity classification achieving accuracy exceeding 98.22% (Wu et al., 2024). However, although indirect visual indicators such as surface feeding splashes and uneaten pellets achieve high recognition accuracy in laboratory setups (Wu et al., 2024), discrepancies frequently persist between these secondary manifestations and authentic feeding behavior, impeding the stable and direct characterization of schooling feeding states (Li et al., 2020). Consequently, direct quantification methods that extract kinematic features such as sudden accelerations and sharp turns via TSMs have become an important pathway for objectively evaluating schooling feeding motivation (Fuchs and Caudill, 2019; Wei et al.,
2021; Gyllingberg et al., 2023). Nevertheless, in high density RAS environments, visual occlusions, fluctuating target counts, and frequent identity switches readily induce trajectory fragmentation and noise, thereby constraining the stability and robustness of trajectory driven TSMs (Zhao et al., 2026). Furthermore, most TSM driven FFIA systems remain confined to behavioral quantification and state recognition, struggling to translate numerical perceptual outputs into practical management decisions. Although rule based methods can categorize feeding states according to predetermined thresholds, they lack a comprehensive understanding of intricate aquaculture contexts, failing to deliver operational recommendations that combine interpretability with executability (Zhou et al., 2018).
In comparison, Large Language Models (LLMs) demonstrate strong capabilities in contextual logical reasoning, multi-source information synthesis, and semantic consistency (Okutu and Yumetoshi, 2024). However, applying them to real-world aquaculture control imposes rigorous requirements on physical grounding, biological constraints, and operational safety. Without effective constraints, general LLMs are prone to factual hallucinations or outputs inconsistent with authentic production conditions when interpreting complex biological phenomena and generating management recommendations (Jiang et al., 2025; Narisetty et al., 2025). Furthermore, LLMs cannot directly interpret continuous video streams and fish schooling trajectories, creating a fundamental need to transform visual behavioral information into representations accessible to language models. Although prior studies have explored cross-modal alignment between visual or temporal sequences and language models via Querying Transformers (Li et al., 2023) or temporal prototype reprogramming (Jin et al., 2024), these methodologies predominantly target static visual features or regular one-dimensional time series. Consequently, they struggle to effectively characterize the complex collective dynamics caused by fluctuating target counts, visual occlusions, and identity switches in high-density aquaculture environments.
Specifically, when converting visual behavioral information into representations intelligible to language models, explicit kinematic features possess clear physical meanings and favorable interpretability, yet they struggle to fully preserve fine grained spatiotemporal information within intricate collective dynamics. In contrast, implicit soft tokens can encode richer dynamic behavioral patterns, but they lack directly verifiable physical grounding (Butt et al., 2026). Therefore, establishing a behavior to language interface that unifies explicit physical evidence and implicit soft tokens is essential to reconcile behavioral richness with physical interpretability while supporting reliable and executable feeding decisions. To address these challenges, this study proposes THPL, a knowledge grounded vision to language decision support framework tailored for rainbow trout (O. mykiss) cultured in RAS, aiming to systematically unify behavioral richness, physical interpretability, and operational safety. The primary contributions of this work are threefold. First, we construct a dimensionless Activity Coefficient (AC) integrating displacement, velocity, and acceleration, and design a hierarchical behavior encoder to jointly model explicit kinematic features and implicit behavioral tokens. Second, we construct a vision to language feeding decision architecture coupling counterfactual mDPO alignment with expert rule constraints, enhancing the diversity, safety, and reliability of decision generation. Third, we establish a comprehensive methodological pipeline bridging fish schooling behavioral representations to intelligent feeding decisions, providing technical support for precise, safe, and interpretable feeding management in complex aquaculture environments.
2. Materials and methods
This study constructed and validated the THPL decision support framework through a methodological workflow, bridging continuous quantitative behavioral perception with intelligent feeding reasoning in RAS. As schematically mapped across the following subsections, the complete experimental and methodological pipeline comprises four interconnected phases. First, Section 2.1 details the controlled RAS experimental setup, video acquisition protocols, feeding trial design for O. mykiss, and the physical-consistent kinematic augmentation strategy used to construct the benchmark dataset. Second, Section 2.2 delineates the four-tiered system architecture, systematically covering the TSM for trajectory tracking and AC calculation, the HBE for extracting dual-evidence behavioral tokens, the PET for compiling structured environmental and rule prompts, and the active LLM decision engine. Third, Section 2.3 presents the multi-stage training pipeline, which sequentially coordinates HBE feature pretraining, multimodal supervised fine-tuning, and counterfactual mDPO alignment to reinforce physical causality and prevent decision trivialization. Finally, Section 2.4 outlines a multi-dimensional evaluation protocol to rigorously verify rule execution accuracy, operational safety boundaries, linguistic generation diversity, and causal decision stability against sensory perturbations.
2.1. Experimental design and dataset construction
2.1.1 Experiment system and data acquisition
This experiment was conducted as a controlled pilot study at Yuhang Smart Aquaculture Research Center (Hangzhou, Zhejiang Province, China). Building upon the Fishsort framework established by Zhao et al. (2026), the present study conducts further investigations into collective behavioral modeling, with specific experimental procedures and technical parameters regarding fish detection and multi-target tracking thoroughly documented in their original publication. The experimental setup is shown in Fig. 1. A total of 78 O. mykiss with an average body weight of 65g were placed in a RAS tank (1.60 m × 1.60 m). Throughout the experiment, the water temperature in the tank was maintained at 12 °C, pH level was maintained within the optimal range of 8.0, and the dissolved oxygen concentration was consistently maintained above 8 mg/L. The nutritional balance of the experimental feed was ensured by using commercially extruded feed specifically formulated for O. mykiss. Prior to the commencement of the experiment, the fish were subjected to a 7-day acclimatisation period in the rearing tanks. During the temporary rearing period and the 10-day formal experiment, the fish were fed at fixed times of 8:30 and 16:30 every day. Feeding commenced at 5-second intervals until the fish reached a satiated state and ceased feeding. Ten minutes after feeding concluded, remaining feed was removed to prevent water contamination.
The experimental data acquisition system comprised three main components, including video recording, water quality monitoring, and data processing units. A camera was mounted 1 m above the water surface to capture top-view footage, with a frame rate of 20 FPS and a resolution of . Video data from each feeding session were stored in a digital video recorder (DS-7816N-16P, Hikvision, China). The camera system started recording 2 minutes before feeding began and stopped recording when fish no longer feed, capture various feeding behavior states of fish school. During the experiment, the changes in the intensity of O. mykiss feeding were observed and recorded. In the water quality monitoring unit, a handheld sensor (DO200, YSI, USA) was used to measure dissolved oxygen (DO) and temperature during feeding.

Recirculating Aquaculture System
Edge Computing Device
Cloud Server
Fig. 1. Fish feeding monitoring, computing and analyzing in Recirculating Aquaculture Systems.
2.1.2. Data preprocessing, annotation, and Augmentation
A total of 299 five second video segments were isolated chronologically across complete feeding trials conducted over ten consecutive days, with each day comprising two discrete feeding sessions conducted in the morning and afternoon respectively. All acquired video recordings were converted into consecutive image frames of pixels. Ground truth feeding intensity categories were directly adopted from the benchmark dataset established in Zhao et al. (2026), where segments were evaluated by aquaculture experts following established behavioral criteria adapted from Wei et al. (2021). The dataset was partitioned chronologically into a training set of 239 raw segments from Days 1 to 8 (16 sessions), a validation set of 30 segments from Day 9 (2 sessions), and an independent test set of 30 segments from Day 10 (2 sessions) at an approximate 8 to 1 to 1 ratio. Because all recordings originated from a single continuous O. mykiss cohort, the 30 evaluation segments from Day 10 represent discrete behavioral evaluation units sampled across two separate feeding events following metabolic reset, evaluating within cohort temporal generalization rather than cross population biological replicates. Within Day 10, the 30 test segments were uniformly sampled across the two sessions to provide 10 balanced instances for each feeding intensity regime.
To enhance model generalization without introducing unphysical artifacts, a Physical Consistent Kinematic Augmentation (PCKA) pipeline was applied strictly to the 239 raw training segments, generating 2,868 transformed kinematic views to construct a composite training corpus of 3,107 instances (detailed in Table A.1, Appendix A). Because transformations primarily relied on rigid spatial rotations and reflections that preserve scalar velocity magnitudes, augmented instances naturally inherited their parent feeding intensity labels. The validation and test sets (30 raw samples each) remained strictly unaugmented raw sequences to ensure unbiased performance evaluation. Kinematic parameters were strictly recalculated from transformed spatial coordinates post augmentation using finite differences to maintain internal kinematic coherence. Bivariate correlation scatter matrices and two sample Kolmogorov Smirnov tests indicated that these geometric transformations did not induce severe statistical distributional drift or extreme numerical artifacts in low order kinematics (p > 0.05), though these empirical operations do not imply full hydrodynamic equivalence (Appendix A.1, Figs. A.1 and A.2). The resulting trajectory tensors and derived kinematic features were subsequently formatted into standardized sequence representations to serve as structured inputs for downstream behavioral modeling and decision reasoning.
2.2. Overall architecture of behavior-aware decision system
2.2.1. System architecture
As schematically illustrated in Fig. 2, the THPL framework operates as an integrated decision architecture comprising four cohesive functional tiers, including the task-specific behavioral perception tier (TSM), the hierarchical behavioral encoding tier (HBE), the prompt engineering tier (PET), and the policy decision tier (LLM). Within the perception tier, Fishsort executes multi-object tracking across top-view feeding video streams to extract continuous coordinates and construct trajectory sequences. Simultaneously, kinematic preprocessing extracts individual displacement, swimming velocity, and acceleration to compute the macroscopic Activity Coefficient (AC). Calibrated by data driven optimal thresholds, this metric reclassifies collective feeding vigor into weak, medium, and strong regimes, redirecting behavioral states to index expert rules within the PET and guide auxiliary classification supervision in HBE. Building upon these continuous trajectories, the HBE transforms trajectory coordinates into spatiotemporal tensors and cascades an entity-level Temporal Encoder with a group-level Set Encoder via a Temporal-Set Bidirectional Cross-Attention module to capture multi-agent dynamics without tracking order dependency. Under auxiliary class loss supervision, an explicit behavioral encode head pools macroscopic physical metrics into explicit tokens, while an implicit behavioral encode head distills high-dimensional dynamics into implicit soft tokens, which are concatenated into continuous behavioral prefix embeddings. In parallel, the PET coordinates a rule engine and prompt composer to formulate domain knowledge, organizing structured numerical context including water temperature and dissolved oxygen, categorical metadata, and expert knowledge rules indexed by the supervisory AC range into structured text tokens alongside standardized task queries. At the decision tier, the active policy model (Llama-3.1-8B with trainable LoRA) receives both the concatenated behavioral prefix tokens and structured text tokens, aligned through a counterfactual mDPO loss engine against a frozen reference model to reinforce causal reasoning. During online inference, the active model performs behavior-grounded reasoning to generate structured decision text encompassing feed amount, feeding interval, feeder state, and expert rationale, which is strictly verified by a deterministic output validator before dispatching actuation commands to automated feeders.

Fig. 2. Architectural overview of the THPL framework. The task-specific model (TSM) perception tier extracts multi-fish trajectories and computes Activity Coefficients (AC) to index candidate rules. The hierarchical behavior encoder (HBE) tier combines temporal and set encoders with bidirectional cross-attention to produce concatenated explicit and implicit behavioral tokens. The prompt engineering tier (PET) compiles environmental telemetry and expert rules into structured text tokens. The large language model (LLM) decision tier, fine-tuned via Low-Rank Adaptation (LoRA) and aligned through counterfactual multimodal Direct Preference Optimization (mDPO), synthesizes structured feeding actions verified by a deterministic post-generation validator.
2.2.2. Fish school trajectory tracking and Activity Coefficient formulation via TSM
In the TSM, Fishsort was employed to track fish schools across video sequences (Zhao et al., 2026), extracting continuous trajectories to construct a spatiotemporal trajectory tensor across T temporal segments ( ) and N tracked fish. To mitigate high frequency tracking oscillations and surface turbulence, each five second video sequence was uniformly discretized into 10 temporal windows of 0.5 s. As aligned with the encoder input space, this trajectory tensor encapsulates five explicit kinematic channels (F=5) comprising normalized centroid coordinates (cx, cy), planar velocity components (vx, vy), and instantaneous acceleration (acc). Concurrently, key kinematic parameters were computed across individuals via finite differences to formulate the macroscopic Activity Coefficient (AC). Individual displacement ( ) measures cumulative path length within each segment to reflect spatial foraging coverage. Swimming velocity ( ) captures instantaneous planar speed, and acceleration ( ) reflects burst turning dynamics. Because D and V covary across duration, an equal-weighting fusion was adopted after individual z-score standardization to balance cumulative exploration and burst kinetics, supported by the ablation in Appendix A. Variables were normalized using the global mean ( ) and standard deviation ( ) derived strictly from the 239 raw training sequences. As formulated in Eq. (1), the raw indicator averages these standardized features across valid fish within segment t. Finally, Eq. (2) scales this raw coefficient into a strictly bounded continuous interval using the global extrema from the training set to facilitate threshold partitioning, where constitutes a small constant preventing division by zero.
In addition to the mean-based formulation in Eqs. (1) and (2), candidate aggregation formulations based on group variance and kinetic energy were designed to evaluate physical representation efficacy across different statistical moments (detailed in Appendix A.2). To partition the continuous AC into discrete feeding intensity regimes, a data-driven grid-search optimization protocol was executed strictly on the independent validation set to determine optimal decision boundaries while preventing data leakage (formally defined in Appendix A.3, Eqs. A.4-A.6). Through this optimal thresholding procedure, the scalar AC reclassifies collective feeding intensity into weak, medium, and strong regimes as illustrated in Fig. 2. This reclassification establishes a dual redirection mechanism within the architecture. It redirects discrete behavioral states to index corresponding candidate control rules within PET, while concurrently supplying supervisory targets for auxiliary classification losses during HBE pretraining. Furthermore, to verify whether the derived kinematic index captures authentic biological phase transitions rather than optical tracking artifacts, local fish school density was incorporated as a spatial metric to evaluate its biomechanical alignment with collective feeding dispersal (detailed in Appendix A.4).
2.2.3. Hierarchical Behavior Encoder
As illustrated in Fig. 3, the HBE maps variable-length tracking data into fixed-size embedding tokens compatible with the LLM embedding space. To preserve localized kinematics while handling dynamic target quantities, the HBE employs a cascaded Temporal-then-Set structure driven by attention mechanisms (Appendix B, Eqs. B.1 to B.4). The input trajectory tensor is augmented with sinusoidal temporal position encodings along dimension . A key-padding mask filters out invalid coordinates and untracked padding instances across frames. Operating across the temporal dimension for each tracked fish independently, an individual-level Temporal Transformer leverages multi-head self-attention (Vaswani et al., 2017) to capture swimming dynamics and burst turning kinetics. This encoder extracts entity-level representations from the terminal valid temporal step. Subsequently, a Set Transformer processes across the entity dimension via Set Attention Blocks (Lee et al., 2019). This generates unpooled interaction tokens that preserve permutation equivariance over fish track indices without bottleneck compression.
Hierarchical Behavioral Encoder (HBE)

Fig. 3. Architecture of the Hierarchical Behavior Encoder. Trajectory tensors are processed through cascaded temporal and set Transformers to capture individual burst kinematics and permutation-invariant collective dynamics. An explicit head extracts macroscopic physical tokens, while an implicit head applies temporal-set bidirectional cross-attention to distill fine-grained soft tokens. Both token streams are concatenated into continuous prefix embeddings for language model grounding.
Building upon these representations, an explicit evidence head models macroscopic physical motion cues across displacement, velocity, acceleration, and school density. It applies learnable queries to cross-attention pool , yielding explicit behavioral tokens as defined in Eq. (3). To ensure dimensional compatibility with LLM while maintaining gradient propagation, these explicit tokens are projected into the continuous embedding space rather than unnormalized physical scalars, acting as physically targeted inductive priors. In parallel, an implicit behavioral head fuses individual kinematics with collective context via Temporal-Set Bidirectional Cross-Attention. Specifically, it computes temporal-contextualized features and set-contextualized features . These features are concatenated along the channel dimension to construct the joint behavioral context Then, learnable queries pool high-dimensional dynamics from to generate implicit behavioral soft tokens via Eq. (4). Through query-based attention pooling, both and achieve strict permutation invariance with respect to global fish indexing order. Rather than entering the encoder as a direct numeric input, the scalar AC functions strictly as an offline supervisory criterion to partition feeding regimes for multi-task loss supervision. The explicit and soft tokens are concatenated along the sequence dimension into dual-behavioral prefix embeddings , propagating gradients to ground downstream linguistic reasoning in visual kinematics.
2.2.4. Rule Engine and Prompt Composer
While the HBE generates continuous behavioral embeddings, the rule engine and prompt composer construct the semantic textual context to activate the reasoning capabilities of LLM without updating rule weights. As summarized in Table 1, the expert rule catalog defines operational control directives indexed by offline AC thresholds. The discrete parameters (5 s, 7 s, 10 s intervals; 20%, 50% reductions) serve as pre-configured heuristic baselines. For TH001 (Weak), the feeder halts immediately, with the 10 s interval defining a standby re-observation latency and the 50% quota specifying a provisional restart probing dose. To prevent shortcut retrieval, runtime prompts embed candidate rule specifications but exclude numerical AC values and ground-truth labels. By pairing the 239 raw training trajectories with sampled water quality conditions
(dissolved oxygen, temperature, and ammonia), 4,500 structured interaction records were synthesized. Among them, 3,000 records were allocated to Stage 2 supervised fine-tuning, while the remaining 1,500 paired records provided counterfactual rationales for Stage 3 preference alignment. Crucially, the independent validation split () remained completely isolated from this synthesis pipeline, sharing no parent trajectories, prompt variations, or counterfactual pairs with the training corpus.
Table 1
Expert rule catalog and offline behavioral intensity partitioning criteria based on AC.
| Rule ID | Feeding Intensity | AC Condition | Feeder State | Feeding Interval | Feed Amount |
|---|---|---|---|---|---|
| TH003 | Strong | Continue | Keep 5s | Keep 100% | |
| TH002 | Medium | Continue | Keep 7s | Reduce by 20% | |
| TH001 | Weak | Stop | Keep 10s | Reduce by 50% |
Note: Ground-truth feeding intensity is established via expert annotation (Section 2.1.2). AC ranges serve strictly as offline thresholds for rule indexing and loss supervision. Under TH001 (Weak), the feeder halts immediately. The 10 s interval defines a standby re-observation latency, and the 50% quota specifies a provisional restart probing dose. Operational parameters (5 s, 7 s, 10 s; 20%, 50%) are pre-configured expert heuristic baselines. Inference runs directly on behavioral prefix tokens without AC inputs.
The prompt composer dynamically formats heterogeneous inputs into an instruction prompt by concatenating discrete contextual blocks, as expressed in Eq. (5). Specifically, supplies qualitative water quality descriptors such as temperature, pH and dissolved oxygen (DO) condition levels, specifies aquaculture background parameters including species, biomass and tank specifications, injects candidate expert rules encompassing operational boundaries across 3 feeding regimes, provides the standardized task query, and acts as the generation delimiter. Prepending the behavioral prefix tokens to the embedded textual prompt establishes a unified input sequence at the embedding layer, compelling the model to ground decisions in visual kinematics while respecting environmental constraints. Formally, the sequential composition of the instruction prompt is defined in Eq. (5).
During parameter-efficient fine-tuning, the prompt text functions strictly as an unpenalized conditioning context rather than an autoregressive prediction target. A standard label mask of -100 is assigned across all positions corresponding to both the prepended behavioral tokens and the instruction prompt , excluding them from cross-entropy loss computation. Gradients are propagated exclusively over the subsequent response tokens containing structured control commands and expert diagnostic rationales, ensuring the model acquires domain reasoning without memorizing prompt templates.
2.2.5. Parameter-efficient LoRA fine-tuning, counterfactual mDPO alignment and validator
As illustrated in Fig. 2, the active policy language model is adapted and aligned through parameter-efficient fine-tuning coupled with mDPO (Wang et al., 2024) driven by counterfactual expert pairs. In this workflow, LoRA (Hu et al., 2021) is introduced by freezing the pre-trained weights and training low-rank decomposition matrices ( , ) across attention projection layers (Appendix B, Eq. B.5). To resolve unconditional preference shortcuts where multimodal architectures bypass visual inputs, the policy is aligned via counterfactual mDPO without training an external reward network. As shown in the mDPO optimization loop of Fig. 4, expert-curated counterfactual preference pairs are fed into both the active policy and a frozen reference policy . The mDPO loss engine computes log-probability ratios between and conditioned on behavioral prefix tokens to optimize the active LoRA weights, directly parameterizing the implicit reward function formulated in Eq. (6):
where v denotes behavioral prefix tokens ( ), y denotes candidate decision text, and governs the deviation temperature. To reinforce causal consistency across the environment-behavior-decision chain, counterfactual preference pairs were curated across five key operational dimensions comprising water temperature, dissolved oxygen, stocking density, feeding history, and cross-species physiological baselines (detailed in Table C.1, Appendix C). Crucially, counterfactual perturbations hold swimming kinematics v strictly invariant while altering environmental conditions to acute stress regimes, defining restrictive actuator actions as chosen responses and unconstrained feeding continuation as rejected responses . During inference, a deterministic output validator parses the generated text, verifying predicted feeder states, feeding intervals, and feed amounts against predefined expert thresholds before execution.
2.3. Multi-Stage Training Strategy
The unified training pipeline of the proposed architecture coordinates hierarchical optimization across three sequential phases to ensure representation fidelity, multimodal instruction following, and causal decision grounding, schematically illustrated in Fig. 4.
Stage1
HBE behavior token alignment training
Stage2
LLM
fine-tune training
Stage3
Counterfactual mDPO
fine-tune training
Fig. 4. Schematic overview of the three-stage training pipeline encompassing HBE behavior token alignment pretraining (Stage 1), LLM with LoRA training
(Stage 2), and counterfactual mDPO with LoRA training (Stage 3).
In Stage 1, the HBE is supervised by a composite multi-task loss function to extract discriminative and physically grounded features. Specifically, the core classification loss acts as the primary task supervisor across a mini-batch of size (indexed by sample ), computed via cross-entropy on the mean-pooled features of both explicit evidence tokens and soft tokens to distinguish feeding intensity according to Eq. (7). To explicitly preserve continuous physical properties, the attribute supervision loss formulated in Eq. (8) forces the pooled soft representations of each sample to regress true kinematic indicators via an attribute prediction head against ground-truth kinematic targets . An ordinal classification loss defined in Eq. (9) enforces the hierarchical relationship across the three ordered feeding levels ( ) using cumulative binary classifiers . To bridge the representation gap between physical metrics and latent features, the contrastive alignment loss expressed in Eq. (10) enforces cross-branch consensus between pooled soft representations and explicit representations across the batch. To prevent token dimensional degeneration and feature redundancy, a token diversity loss detailed in Eq. (11) penalizes excessive cosine similarity between distinct soft tokens among the queries beyond a margin threshold . Furthermore, a structural sensitivity loss presented in Eq. (12) enforces temporal sensitivity with a margin by penalizing the network if pooled soft representations remain invariant when temporal frame orders are randomly shuffled ( ). The final composite HBE pre-training objective established in Eq. (13) integrates these individual loss components through a weighted summation, where the weighting coefficients are empirically configured to [1.0, 1.0, 1.0, 0.5, 0.1, 0.1] respectively.
In Stage 2, the LLM policy undergoes supervised fine-tuning to map the combined behavioral prefix tokens and structured prompt text into structured textual decisions. The soft tokens and explicit tokens are prepended directly to the textual prefix as continuous prompt embeddings, where the fundamental single-token optimization target follows standard causal language modeling formulated in Eq. (14). To mitigate classification boundary drift associated with sparse minority events, a weighted Supervised Fine-Tuning loss formulated in Eq. (15) is applied across the batch . This loss is computed exclusively over the valid response tokens by assigning an ignore index of -100 to all prefix and prompt positions. While this masking restricts loss computation to response generation rather than prompt auto-completion, trainable parameters remain conditioned on the context. Mitigating rigid response templating is primarily governed by downstream counterfactual mDPO alignment. Weak intensity samples are upweighted ( ) to emphasize the critical penalty of feeding during anomalous states, while other classes retain a standard weight ( ).
To guarantee feature space consistency prior to Stage 3, behavioral prefix tokens were extracted offline using the strictly frozen, final checkpoint of the trained HBE and projector from Stage 2. The cached embedding files were version-locked and verified via cryptographic checksums against the corresponding model weights to eliminate latent feature drift across training stages. In Stage 3, the policy undergoes preference optimization adapted from the mDPO framework to enforce conditional reliance on trajectory evidence and resolve unconditional language shortcuts. This optimization objective adapts three log-sigmoid terms to evaluate the trainable policy against a frozen reference model . The response preference term formulated in Eq. (16) compels the model to favor the verified decision over the counterfactual error . When environmental safety thresholds enforce feeding termination, paired responses and differ in kinematic diagnostic rationales rather than forcing an invalid action flip. The behavior-evidence conditional preference term detailed in Eq. (17) contrasts response probabilities given valid trajectory tokens against an unconditioned baseline (zero-vector masking), penalizing the policy if it relies solely on language priors while ignoring physical inputs. The anchored preference term expressed in Eq. (18) regularizes training by penalizing absolute likelihood degradation on chosen responses relative to . Finally, the batch-level objective in Eq. (19) aggregates these components using deviation temperature and anchor weight .
2.4. Evaluation of LLM-generated feeding decisions
To comprehensively assess the performance of the fine-tuned large language model in the aquaculture feeding domain, evaluations were conducted on a balanced test set comprising 30 independent video segments (10 samples for each of the weak, medium, and strong feeding intensity classes). The evaluation framework is bifurcated into rule-constrained instruction execution and natural language semantic generation. The rule-constrained execution evaluation assesses the ability of the model to generate safe and actionable control commands conforming to expert protocols. Distinct from visual annotations ( ) and auxiliary kinematic supervision ( ), target labels in this stage denote expert reference policy actions specified by standardized aquaculture management regimes. Discrete action match rates evaluate individual prediction accuracy across feeder state, feeding interval, and feed amount. Because expert feeding regimes define a bijective mapping between schooling appetite and the tripartite actuator actions, overall decision accuracy ( ) requires simultaneous exact concordance across all three fields as formulated in Eq. (20), rendering overall accuracy bounded by the lowest performing dimension and quantifying execution compliance against prescriptive expert rules. To strictly penalize catastrophic errors such as issuing feeding commands during abnormal weak appetite, the Unsafe Continue Rate (USCR) is calculated via Eq. (21). Additional classification metrics including per-class recall and invalid generation rate are documented in Appendix B (Eqs. B.6-B.8).
The natural language semantic evaluation examines the linguistic fidelity, factual consistency, and reasoning robustness of generated rationales. Semantic similarity and cognitive diversity metrics encompassing BLEU, Self-BLEU, ROUGE-L, METEOR, and BERTScore are detailed in Appendix B (Eqs. B.9-B.16). To eliminate factual fabrications in water quality parameters or control logic, the Hallucination Penalty Score (HPS) formulated in Eq. (22) deducts severity-weighted penalties from a base score according to detected factual discrepancies . Furthermore, to evaluate causal robustness against tracking noise, the decision consistency rate defined in Eq. (23) measures the exact retention of generated action triplets under trajectory perturbation level relative to unperturbed executions.
3. Results
3.1. Kinematic modeling, threshold optimization, and spatial distribution verification
The quantitative characterization of fish school kinetics was established through the composite AC, which integrates individual displacement, velocity, and acceleration into a macroscopic indicator. To determine the optimal mathematical formulation for physical behavior aggregation among the candidate formulations designed in Section 2.2.2, a comparative evaluation investigating the standardized mean ( ), variance ( ), and magnitude energy ( ) was conducted across the experimental dataset. One-way ANOVA and effect size analyses confirmed that the mean-based formulation ( ) provided the highest between-group discriminatory capability, achieving an ANOVA F-statistic of 176.88 (p < 0.001) and an effect size of 0.9291, markedly outperforming the variance and energy formulations. The complete mathematical definitions, detailed statistical distribution comparisons, pairwise Cohen's d effect sizes, and correlation scatter matrices supporting this empirical selection are comprehensively documented in Appendix A (Figs. A.3-A.6). The performance degradation observed in the energy-based formulation occurs because zero-centered standardized deviations fold negative values into positive quadratic magnitudes, whereas physical kinetic energy models require non-negative raw velocity fields. Consequently, was definitively selected as the optimal kinematic aggregation metric.
As depicted in Fig. 5(a), the continuous AC exhibits a rigorous monotonic concordance with ground-truth feeding intensity rankings (Spearman , ; Kendall ), substantiated by a Jonckheere-Terpstra trend test ( , ). In Fig. 5(b), the kernel density distributions of the selected index across the 299 benchmark sequences display distinct behavioral boundaries corresponding to the three feeding intensity classes. Implementing the grid-search optimization protocol established in Section 2.2.2 yielded optimal decision boundaries at [0.00, 0.181] for weak feeding, (0.181, 0.462] for medium feeding, and (0.462, 1.00] for strong feeding. Under this optimal thresholding strategy, the AC derived from fish school trajectory features achieves a baseline classification accuracy of 95.32% (macro-F1 = 95.43%), correctly identifying 114 out of 117 weak feeding samples, 107 out of 113 medium feeding samples, and 64 out of 69 strong feeding samples. Furthermore, a stratified five-fold cross-validation protocol with fold-independent parameter re-estimation across the 299 benchmark sequences yielded an out-of-fold generalization accuracy of 94.31% (282/299 samples) under stable thresholds ( , ), confirming that the learned boundaries reflect authentic biomechanical phase transitions rather than sample-specific overfitting. The statistical consistency of the underlying kinematic data was further validated prior to model training, where bivariate correlation matrices and Kolmogorov-Smirnov tests confirmed that the augmented kinematic distributions exhibited no significant discrepancy from the raw experimental trajectories with all p-values exceeding 0.05, as comprehensively detailed in Appendix A (Figs. A.1 and A.2).
a
AC vs ground-truth feeding intensity
Spearman , JT z=17.79 (p=0.00e+00)

b
AC density with cross-validated thresholds
Fig. 5. Evaluation of the Activity Coefficient (AC) across 299 benchmark sequences. (a) monotonic correlation and trend verification against ground-truth feeding intensities with group means, 95% confidence intervals, and colored scatter distributions (Spearman , ). (b) class-wise kernel density distributions alongside cross-validated data-driven decision boundaries ( , ).
Corroborating the fidelity of the AC against spatial schooling distributions across 299 evaluation sequences confirmed that the quantified feeding intensity reflects physical schooling patterns. As documented in Appendix A (Fig. A.7), statistical evaluation demonstrated an exceptionally high negative correlation between local fish density and the AC (r = -0.9629, p < 0.001). The bivariate joint density heatmap in Fig. A7(a) reveals a continuous, high-concentration density progression from explosive foraging states toward dense resting aggregation, supported by a highly significant Chi-square association across behavioral regimes ( , p < 0.001, Fig. A7(b)). This empirical concordance confirms that the derived behavioral prior reliably captures the macro-level transition from cohesive aggregation during resting periods to spatial dispersal during voracious feeding.
3.2. Architectural ablation, disturbance robustness, and representation probing of HBE
To evaluate the internal mechanism of the HBE, systematic ablation studies were conducted using a five-fold cross-validation protocol. As illustrated in Fig. 6, the spatiotemporal topology comparison demonstrates that the proposed Temporal-then-Set architecture achieved the superior performance, attaining an accuracy of 97.0% and an F1-score of 0.967. Configurations lacking independent temporal sequence modeling for individual targets suffered substantial performance collapse, where the Set-Only and Set-then-Temporal models achieved accuracies of only 33.5% and 33.4% with F1-scores of 0.168 and 0.166, respectively. Although the Temporal-Only model achieved an accuracy of 90.2% and an F1-score of 0.895, it remained inferior to the proposed structure. These ablation outcomes confirm that accurately characterizing fish feeding states requires hierarchical modeling, wherein resolving individual temporal locomotion must precede collective aggregation to preserve transient burst kinematics while capturing permutation invariant group dynamics.

Fig. 6. Architectural ablation evaluations of the HBE including structural comparisons and input feature ablation under five-fold cross-validation.
Perturbation stress tests confirm that the policy network performs causal reasoning over continuous kinematics rather than relying on text. As shown in Fig. 7(a), corrupting trajectory inputs induces a monotonic decline in decision consistency rate relative to unperturbed executions, measuring the exact joint retention of feeder state, feeding interval, and feed amount. Minor perturbations at Tier 1 maintain 100.0% consistency, demonstrating an effective noise tolerance margin against subtle tracking oscillations. Increasing spatial Gaussian jitter steadily reduces consistency to 66.7% at the maximum severity tier, while temporal frame drop preserves 90.0% consistency under 70% frame loss. Completely ablating trajectory inputs with zeros collapses decision consistency to 33.3%, which matches the text-only baseline and confirms that structured action synthesis causally requires physical motion inputs. Kinematic distributions in Fig. 7(b) establish feeding states of these spatial features. Mean swimming velocity increases from 0.045 m/s in weak feeding to 0.121 m/s in strong feeding with a positive Spearman correlation of 0.95, whereas local spatial density drops from 542.4 to 321.5 with an inverse correlation of -0.93 as fish disperse during competitive feeding. These statistical patterns confirm that continuous trajectory coordinates preserve authentic biological dynamics, allowing the model to synthesize control decisions directly from continuous motion feature.
a

b
Fig. 7. Trajectory validity and distributions of spatial feature in HBE and LLM, showing (a) decision consistency rate across perturbation severity tiers under spatial jitter, temporal frame drop, and zero-trajectory control, where consistency denotes exact joint matching across feeder state, feeding interval, and feed amount relative to unperturbed inputs, and (b) distributions of mean swimming velocity and local spatial density across feeding intensity states.
In addition to continuous tracking noise, discrete identity switches caused by frequent fish occlusions represent another primary disturbance in dense aquaculture. To assess HBE robustness against tracking errors in dense aquaculture, artificial identity switches were introduced at 50, 100, 150, and 200 events per sequence. As shown in Fig. 8, the downstream LLM decision performance maintained complete stability with a variation delta of +0.0% across all swap frequencies. Specifically, Fig. 8(a) shows that the feeding intensity classification evaluated from the LLM's generated decisions preserved an overall accuracy of 93.3%, yielding 100.0% for weak, 100.0% for medium, and 80.0% for strong feeding under all conditions. In Fig. 8(b), the three structured decision action fields generated by the active policy LLM maintained identical match rates of 100.0% for feeder state, 93.3% for feeding interval, and 93.3% for feed amount. These results confirm that the temporal-then-set aggregation in HBE effectively decouples collective behavioral dynamics from individual tracking order, ensuring perturbation-free LLM reasoning.

Fig. 8. Robustness of downstream LLM (SFT) decision-making under 50, 100, 150, and 200 tracking ID switches, showing (a) LLM-derived classification accuracy across feeding intensities and (b) match rates of generated decision action fields.
Alongside collective spatial dispersion, fine-grained kinematic analyses revealed an intrinsic behavioral heterogeneity that cannot be captured by scalar activity metrics. As documented in Appendix A (Fig. A.9), sequences possessing comparable macroscopic AC baselines consistently bifurcate into distinct behavioral geometries, comprising heterogeneous distributions characterized by an actively foraging minority alongside an inactive majority, as well as homogeneous distributions reflecting uniform cruising across the entire school. To verify whether the Hierarchical Behavior Encoder preserves these underlying distribution geometries without dimensional information bottlenecks, linear regression probing under five-fold cross-validation was conducted across the extracted behavioral tokens. As visualized in Fig. A.8 (Appendix A), the learned continuous tokens demonstrate remarkable fidelity in recovering both the microscopic velocity dispersion quantified by the coefficient of variation ( , , ) and the macroscopic AC ( , , ). In sharp contrast, explicit kinematic features alone completely fail to recover velocity dispersion ( ). These empirical outcomes substantiate that the hierarchical continuous tokens successfully preserve higher-order velocity distribution moments, mitigating distributional insensitivity and equipping the downstream language model with robust physical representations.
3.3. Dual-evidence bottleneck verification
To investigate the individual and synergistic contributions of behavioral token representations, ablation experiments were conducted across four input configurations comprising the text only baseline with 0 tokens, the explicit only configuration with M=4, the soft only configuration with K=10, and the full dual evidence configuration with M+K=14. As illustrated in
Fig. 9(a), overall decision accuracy (Accdec) scales positively with the progressive incorporation of behavioral embeddings. The text only baseline yields an overall accuracy of only 33.33%, bounded by the lowest match rate across actuator fields. The confusion matrix in Fig. 9(c) reveals that this baseline suffers from severe majority class trivialization, predicting the medium feeding category for all thirty evaluation instances across weak, medium, and strong states due to the total absence of visual motion cues. Incorporating explicit physical tokens elevates overall decision accuracy to 46.67%, while utilizing implicit soft tokens alone achieves an accuracy of 86.67%. The full dual evidence model secures the highest decision accuracy of 93.33%, maintaining clear classification boundaries with only two strong feeding instances conservatively classified as medium feeding as depicted in Fig. 9(d).
The field specific evaluation presented in Fig. 9(b) highlights how dual evidence representations govern multi-dimensional control execution. In feeder state regulation, the soft only and full dual evidence configurations each achieve 100.00% match rates, outperforming the 66.67% rate obtained by explicit tokens alone and the text only baseline. For quantitative parameters, the complementary properties of the two feature streams become prominent. The feeding interval match rate reaches 93.33% under the full configuration, compared to 46.67% for explicit only, 86.67% for soft only tokens, and 33.33% for the text only baseline. Similarly, the feed amount match rate attains 93.33% in the full configuration, markedly improving upon the 46.67% achieved by explicit tokens alone, 86.67% achieved by soft tokens alone, and 66.67% from the text only baseline. Crucially, the dual-evidence synergy between explicit and implicit behavioral tokens drives the average decision accuracy across feeder state, feeding interval, and feed amount to 95.56%, substantially surpassing 91.11% obtained with implicit tokens alone, 53.33% with explicit tokens alone, and 55.56% from the text only baseline. These empirical outcomes confirm that continuous kinematic embeddings provide indispensable physical representation anchors for the language model, effectively mitigating decision bias in the absence of visual perception and establishing precise causal alignment between collective spatiotemporal dynamics and expert control protocols.

b
Text-Only Baseline (Acc=33.33%)
C
Explicit+Implicit+Text (M+K) (Acc=93.33%)
d
Fig. 9. Ablation evaluation of behavioral token configurations across decision performance and error distributions, showing (a) overall feeding decision accuracy (Acc ) across four input representations, (b) field-level match rates across three structured decision actions, (c) confusion matrix for the text only baseline demonstrating complete majority class collapse, and (d) confusion matrix for the full dual-evidence model.
3.4. LLM Structured decision performance, safety, and rule compliance
The decision-making capacity of the fine-tuned LLM was evaluated across thirty independent test samples representing the three distinct feeding intensities. As summarized in Table 2, counterfactual mDPO alignment substantially improved operational decision fidelity over standard Supervised Fine-Tuning (LoRA). The overall decision accuracy increased from 93.33% to 96.67%, with the macro recall elevating symmetrically to 96.67% while preserving a 0.00% invalid rate across all testing instances. In the baseline LoRA configuration, the model exhibited underfitting on intensive foraging states, where strong feeding yielded an accuracy of only 80.00% due to a conservative bias that misclassified 20.00% of strong instances as medium feeding. Implementing counterfactual mDPO completely resolved this classification bottleneck, elevating strong feeding accuracy to 100.00% while maintaining 100.00% accuracy in weak feeding identification. Across the three discrete control fields, counterfactual mDPO achieved matching rates of 96.67% for feeder state, feeding interval, and feed amount, where the sole discrepancy was a benign conservative adjustment from medium to weak feeding, confirming high execution precision in discrete actuator regulation.
Table 2
Structured decision performance detailing per-class accuracy, recall, and field-wise match rates across feeding intensities.
| Optimization Strategy | Feeding Intensity | Accuracy (%) | Recall (%) | Match Rate (%) | ||
|---|---|---|---|---|---|---|
| Feeder State | Feeding Interval | Feed Amount | ||||
| Supervised Fine-Tuning (LoRA) | Weak | 100.00 | 100.00 | 100.00 | 100.00 | 100.00 |
| Medium | 100.00 | 100.00 | 100.00 | 100.00 | 100.00 | |
| Strong | 80.00 | 80.00 | 100.00 | 80.00 | 80.00 | |
| Average | 93.33 | 93.33 | 100.00 | 93.33 | 93.33 | |
| Counterfactual mDPO + LoRA | Weak | 100.00 | 100.00 | 100.00 | 100.00 | 100.00 |
| Medium | 90.00 | 90.00 | 90.00 | 90.00 | 90.00 | |
| Strong | 100.00 | 100.00 | 100.00 | 100.00 | 100.00 | |
| Average | 96.67 | 96.67 | 96.67 | 96.67 | 96.67 | |
Note: Evaluations were conducted across 30 independent test video sequences, comprising 10 balanced samples per intensity class.
The operational safety and adherence to expert protocols were quantified under deterministic boundary validation. Both the baseline LoRA and preference-aligned mDPO models achieved 100.00% Hallucination Penalty Scores (HPS) across all feeding intensity states, confirming the complete eradication of fabricated environmental parameters and ungrounded statements. In evaluating catastrophic feeding error prevention, the critical Unsafe Continue Rate (USCR) demonstrated notable improvement. While the baseline LoRA configuration produced an unconstrained continuation judgment under safety critical withholding constraints yielding a USCR of 3.33% (1 out of 30 samples), counterfactual mDPO suppressed hazardous continuation commands, achieving a USCR of 0.00% (0 out of 30 samples) across all thirty evaluation scenarios. Detailed categorical distributions and safety diagnostics validating rule compliance are documented in Fig. C.2 (Appendix C). These empirical outcomes demonstrate that preference alignment enables the model to interpret subtle behavioral anomalies reliably and issue immediate feeding suspension commands to safeguard water quality.
3.5. Semantic fidelity, generation diversity, and decision interpretability
Discrete control directives and explanatory rationales were evaluated independently. Discrete operational actions were assessed via categorical accuracy, while natural language metrics evaluated explanatory rationales against expert reference texts under greedy decoding (temperature = 0), as shown in Fig. 10. In Fig. 10(a), the standard Supervised Fine-Tuning baseline exhibited an asymmetric profile with high ROUGE-1 Recall (97.40%) alongside low Precision (22.70%), yielding ROUGE-1 and ROUGE-L F1 scores of 31.70% and 31.60% respectively, and a METEOR score of 58.10%. Counterfactual mDPO alignment improved lexical precision across generated rationales, raising ROUGE-1 Recall to 99.40% and ROUGE-1 Precision to 55.80%, which increased the ROUGE-L F1 score to 67.90% and the METEOR score to 85.30%. This gain confirms that preference alignment curtails redundant phrasing while preserving relevant diagnostic terminology. Precision-oriented BLEU evaluations in Fig. 10(b) showed consistent improvements. Counterfactual mDPO increased scores across n-gram orders, advancing BLEU-1 from 27.50% to 55.90% and BLEU-4 from 24.80% to 53.30%. The small score drop of 2.60% from 1-gram to 4-gram indicates higher n-gram precision across multi-word diagnostic phrases in generated rationales.
To measure generation redundancy, generation diversity on explanatory text was benchmarked in Table 3. Preference alignment improved lexical variety, elevating Distinct-3 from 6.68% to 7.81% while reducing output repetition, as Self-BLEU-2 and Self-BLEU-4 decreased to 52.88% and 49.07%, respectively. Class-wise Distinct-1 metrics showed consistent gains across all feeding categories, reaching 6.90% for weak, 8.99% for medium, and 5.46% for strong feeding regimes. Lower Self-BLEU values reflect reduced phrasing redundancy across distinct test cases rather than unconstrained action variation. Discrete operational directives remain strictly standardized.

b

Fig. 10. Comparative evaluation of text generation quality on explanatory rationales between Supervised Fine-Tuning (LoRA) and Counterfactual mDPO. (a) Group-wise comparison of ROUGE precision, recall, F1, and METEOR scores. (b) Precision decay profiles across cumulative n-gram orders from BLEU-1 through BLEU-4.
Table 3
Quantitative comparison of lexical diversity and textual redundancy on explanatory rationales between LoRA and counterfactual mDPO across lexical, structural, and class-wise metrics.
| Optimization Strategy | Distinct-1 (%) | Distinct-2 (%) | Distinct-3 (%) | Self-BLEU-2 (%) | Self-BLEU-4 (%) | Distinct-1 (%) | ||
|---|---|---|---|---|---|---|---|---|
| Weak | Medium | Strong | ||||||
| Supervised Fine-Tuning (LoRA) | 2.96 | 5.57 | 6.68 | 58.79 | 52.92 | 5.84 | 8.27 | 5.43 |
| Counterfactual mDPO + LoRA | 3.47 | 6.57 | 7.81 | 52.88 | 49.07 | 6.90 | 8.99 | 5.46 |
A qualitative comparative evaluation substantiated decision fidelity between Supervised Fine-Tuning (LoRA) and counterfactual mDPO under identical behavioral and contextual inputs. As illustrated in the inference transcripts in Fig. C.1, when presented with a strong feeding scenario characterized by an AC of 0.76, swimming speed of 19.68 cm/s, and acceleration of 543.97 cm/s , the baseline Supervised Fine-Tuning policy exhibits an operational discrepancy. Specifically, the baseline model generates text centered on post-suspension water quality monitoring and conservatively predicts an extended 7-second feeding interval rather than the required 5-second interval. This interval pacing mismatch reflects an operational error under vigorous feeding conditions. In contrast, the counterfactual mDPO policy associates high-magnitude visual kinematics with active feeding guidance, prescribing the 5-second feeding interval alongside continuous feeder operation and full ration delivery. This outcome confirms that counterfactual preference alignment reduces conservative pacing errors and improves alignment between continuous visual kinematics and discrete actuator execution (Fig. C.1, Appendix C).
4. Discussion
4.1. Physical representation of collective feeding activity via AC
The AC integrates disparate kinematic variables into a traceable and comparable metric of collective motion. In this study, the mean-based AC demonstrated reliable capability in distinguishing feeding intensity regimes. Constructed from explicit kinematic variables, the metric attributes overall activity shifts to specific motion components. This provides a physically grounded basis for partitioning feeding regimes and guiding downstream behavioral modeling. Furthermore, using the AC as a macroscopic baseline reveals kinematic heterogeneity across the school. Under comparable AC values, fish schools can exhibit either a heterogeneous pattern where a few individuals are highly active while others remain quiescent, or a homogeneous pattern characterized by uniform swimming speeds across the population. Because mean-based macroscopic metrics are insensitive to internal velocity distributions, aggregate quantification and fine-grained behavioral encoding exhibit an essential complementary relationship. Prior research demonstrated the utility of parsing behavioral structure from continuous kinematic data by linking keypoint tracking to pose dynamics (Weinreb et al., 2024). In alignment with this methodology, the subsequent modules in THPL retain the AC as a macroscopic activity baseline while incorporating temporal trajectory dynamics and spatial distributions into the HBE. This architecture supplies richer behavioral evidence for final decision-making than a single scalar index.
4.2. Joint modeling of kinematic feeding heterogeneity and collective relationships via HBE
In dense fish schools, severe occlusions alter the count of trackable targets. Furthermore, premature spatial averaging can obscure kinematic variance among individuals. Multi-animal tracking studies have identified occlusions, proximal interactions, and individual associations as central challenges in behavioral quantification (Lauer et al., 2022). The HBE addresses these issues through a decoupled structure that processes individual temporal dynamics before collective set aggregation. This design allows transient motion patterns to be captured prior to population-level pooling. The framework preserves individual temporal continuity alongside collective dynamic changes. It also retains transient feeding cues such as burst swimming and rapid turning. In addition, this design reduces dependence on persistent individual identities, thereby improving model applicability under intermittent tracking and identity switches.
The dual-evidence representation counteracts the over-compression of collective dynamics inherent in average metrics. It enables the model to differentiate behavioral states that exhibit similar macro-level intensity, such as localized feeding competition versus generalized schooling activity. The superior performance of combining explicit and implicit tokens confirms that both representations provide complementary perspectives on school dynamics. The former grounds motion features in traceable physical properties. The latter supplements spatiotemporal variations that summary statistics cannot capture. Feeding both representations into the decision layer preserves macroscopic physical meaning while avoiding the erasure of individual variation. These results demonstrate that the HBE provides a representational foundation for analyzing scenarios with comparable aggregate activity but distinct internal velocity distributions. Future work can further separate states such as localized scramble feeding and uniform swimming using targeted ground-truth annotations.
4.3. Contextual decision integration via LLM and mDPO preference alignment
In THPL, the LLM functions as a semantic decision interface. It synthesizes behavioral evidence, environmental telemetry, husbandry background, and expert rules into structured feeding directives. Practical feeding management requires more than classifying feeding intensity. It demands coordinated determination of feeder states, feeding intervals, feed rations, and operational rationales. The fine-tuned LLM performs high-level synthesis and conversion rather than direct processing of raw visual pixels. For standard classification of feeding intensity alone, conventional classifiers or rule-based models remain more direct and computationally efficient. However, when decisions require unifying multi-source inputs and generating actionable, interpretable guidance for farm operators, the context integration and instruction-following abilities of the LLM provide distinct utility. Prior studies have highlighted the capacity of LLMs to bridge heterogeneous inputs with operational execution. Boiko et al. (2023) linked LLMs with literature retrieval, code execution, and hardware automation for experimental planning. Mon-Williams et al. (2025) integrated knowledge retrieval, vision, and haptic feedback for robotic manipulation. In contrast to these chemical and robotic domains, this study focuses on integrating biological state representations with aquaculture operational guidelines during feeding progression.
Counterfactual mDPO supports the alignment of behavioral evidence with operational constraints. This method translates expert domain knowledge into pairwise response preferences, embedding rules into model parameters rather than relying on prompts alone. This mechanism should be understood as learning contextual policy selection rather than uncovering causal biological laws. The improved decision accuracy after mDPO demonstrates that preference optimization reshapes decision boundaries and error distributions. Its practical utility depends on the real-world operational costs of different error types. Regarding text metrics, aligned outputs show higher lexical overlap with expert references and reduced repetition, facilitating structured, verifiable explanations. THPL incorporates text quality, evidence grounding, and action compliance into a joint evaluation. Combining preference alignment with an independent output validator maintains conversational flexibility while enforcing deterministic operational boundaries (Steyvers et al., 2025).
4.4. Limitations and future research directions
Several limitations in this study warrant consideration. First, all video recordings were acquired from a single cohort of O. mykiss. The temporal test split evaluates only within-cohort temporal generalization and cannot substitute for independent biological replicates. Second, AC boundaries and kinematic features can vary with fish body size, stocking density, and individual traits. Their stability and calibration requirements across independent cohorts require systematic verification. Third, the pre-configured perturbation tests do not capture continuous online performance under concurrent tracking errors and dynamic environmental fluctuations. Finally, the sample size of the test set remains modest. Current decision metrics evaluate policy compliance rather than demonstrating empirical improvements in feed conversion ratio, growth rate, water quality, production cost, or animal welfare. Future investigations should incorporate multi-cohort trials and independent biological replicates, validating real-world production benefits through extended closed-loop feeding trials. Additionally, integrating uncertainty estimation, out-of-distribution detection, human-in-the-loop overrides, and fail-safe controls will be critical to evaluating operational stability and safety boundaries in continuous deployment. Further studies could leverage unseen environmental conditions and fine-grained behavioral annotations to validate the utility of contextual decision-making and motion heterogeneity.
5. Conclusion
This study investigated a behavior-grounded generative framework designed to translate fish motion into interpretable feeding decisions within recirculating aquaculture systems. The framework integrates a dimensionless AC, a HBE, and an LLM policy optimized via counterfactual preference alignment. The results indicate that THPL consolidates multidimensional kinematics into physically grounded behavioral priors while extracting structured behavioral evidence from fragmented trajectories. On this foundation, preference alignment enables the model to generate context-adaptive feeding directives that comply with expert operational rules. This provides a methodology for mapping continuous visual kinematics to verifiable control decisions. Despite these findings, this study is subject to limitations, including reliance on a single fish cohort, limited biological replication, and the absence of closed-loop operational validation across diverse farming conditions. Future work should focus on cross-cohort calibration, uncertainty-aware safety mechanisms, and long-term production trials to advance behavior-grounded generative decision support toward practical implementation in commercial aquaculture.
Acknowledgments
This research was supported by National key R&D Program of China (2024YFD2400100), the scientific research project in Fengjiawan of Hainan Provincial Seed Industry Laboratory (B24H10035), the Fundamental Research Funds for the Central Universities (226-2025-00074) and China Agriculture Research System of MOF and MARA (CARS-49).
CRediT authorship contribution statement
Meng Liang: Conceptualization, Methodology, Formal analysis, Software, Visualization, Investigation, Writing - original draft, Writing - review & editing. Guanbo Feng: Methodology, Formal analysis, Visualization, Writing - review & editing. Haozhuang Chi: Methodology, Writing - review & editing. Shilong Zhao: Resources, Data curation. Zhixin Xiong: Investigation. Yuhang He: Writing - review & editing. Wenfeng Han: Visualization, Writing - review & editing. Tianhao Zhao: Writing - review & editing. Zhihong Ma: Supervision, Project administration, Conceptualization, Resources, Writing - review & editing. Ying Liu: Conceptualization, Project administration, Funding acquisition, Supervision, Writing - review & editing.
Declaration of competing interest
The authors declare that they have no known competing financial interests or personal relationships that could have appeared to influence the work reported in this paper.
Data and code availability
The data and code in this study are available from the author upon reasonable academic request.
References
Boiko, D.A., MacKnight, R., Kline, B., Gomes, G., 2023. Autonomous chemical research with large language models. Nature 624, 570–578.
Butt, N., Kwiatkowski, A., Labiad, I., Kempe, J., Ollivier, Y., 2026. Soft Tokens, Hard Truths. International Conference on Learning Representations 2026, 114650–114675.
Cho, J.-H., Hamidoghli, A., Hur, S.-W., Lee, B.-J., Lee, Seunghan, Kim, K.-W., Lee, Seunghyung, 2024. Growth, Nutrient Deposition, Plasma Metabolites, and Innate Immunity Are Associated with Feeding Rate in Juvenile Starry Flounder (Platichthys stellatus). Animals 14, 3127. https://doi.org/10.3390/ani14213127
Fuchs, N.T., Caudill, C.C., 2019. Classifying and inferring behaviors using real-time acceleration biotelemetry in reproductive steelhead trout (Oncorhynchus mykiss). Ecol Evol 9, 11329–11343. https://doi.org/10.1002/ece3.5634
Geirhos, R., Jacobsen, J.-H., Michaelis, C., Zemel, R., Brendel, W., Bethge, M., Wichmann, F.A., 2020. Shortcut learning in deep neural networks. Nat Mach Intell 2, 665–673. https://doi.org/10.1038/s42256-020-00257-z
Gyllingberg, L., Szorkovszky, A., Sumpter, D.J.T., 2023. Using neuronal models to capture burst-and-glide motion and leadership in fish. Journal of The Royal Society Interface 20, 20230212. https://doi.org/10.1098/rsif.2023.0212
Hu, E.J., Shen, Y., Wallis, P., Allen-Zhu, Z., Li, Y., Wang, S., Wang, L., Chen, W., 2021. LoRA: Low-Rank Adaptation of Large Language Models. https://doi.org/10.48550/arXiv.2106.09685
Hvas, M., Kolarevic, J., Noble, C., Oppedal, F., Stien, L.H., 2024. Fasting and its implications for fish welfare in Atlantic salmon aquaculture. Reviews in Aquaculture 16, 1308–1332. https://doi.org/10.1111/raq.12898
Jiang, J., Yan, L., Liu, J., 2025. Agricultural large language model based on precise knowledge retrieval and knowledge collaborative generation.
Jin, M., Wang, S., Ma, L., Chu, Z., Zhang, J., Shi, X., Chen, P.-Y., Liang, Y., Li, Y.-F., Pan, S., 2024. Time-llm: Time series forecasting by reprogramming large language models, in: International Conference on Learning Representations. pp. 23857–23880.
Lauer, J., Zhou, M., Ye, S., Menegas, W., Schneider, S., Nath, T., Rahman, M.M., Di Santo, V., Soberanes, D., Feng, G., Murthy, V.N., Lauder, G., Dulac, C., Mathis, M.W., Mathis, A., 2022. Multi-animal pose estimation, identification and tracking with DeepLabCut. Nat Methods 19, 496–504. https://doi.org/10.1038/s41592-022-01443-0
Lee, J., Lee, Y., Kim, J., Kosiorek, A., Choi, S., Teh, Y.W., 2019. Set transformer: A framework for attention-based permutation-invariant neural networks, in: International Conference on Machine Learning. PMLR, pp. 3744–3753.
Li, D., Wang, Z., Wu, S., Miao, Z., Du, L., Duan, Y., 2020. Automatic recognition methods of fish feeding behavior in aquaculture: A review. Aquaculture 528, 735508. https://doi.org/10.1016/j.aquaculture.2020.735508
Li, J., Li, D., Savarese, S., Hoi, S., 2023. Blip-2: Bootstrapping language-image pre-training with frozen image encoders and large language models, in: International Conference on Machine Learning. PmLR, pp. 19730–19742.
Mon-Williams, R., Li, G., Long, R., Du, W., Lucas, C.G., 2025. Embodied large language models enable robots to complete complex tasks in unpredictable environments. Nature Machine Intelligence 7, 592–601.
Narisetty, P., Kattamanchi, U.K.R., Nimma, L.A., Karnati, S.R.K., Kore, S.N.B., Golamari, M., Nageshreddy, T., 2025. AQUA: A Large Language Model for Aquaculture & Fisheries. https://doi.org/10.48550/arXiv.2507.20520
Nielsen, B.L., de Jong, I.C., De Vries, T.J., 2016. The Use of Feeding Behaviour in the Assessment of Animal Welfare, in: Phillips, C.J.C. (Ed.), Nutrition and the Welfare of Farm Animals. Springer International Publishing, Cham, pp. 59–84. https://doi.org/10.1007/978-3-319-27356-3_4
Okutu, K., Yumetoshi, H., 2024. Explainability of Large Language Models (LLMs) in Providing Cybersecurity Advice. https://doi.org/10.31219/osf.io/q84rk
Steyvers, M., Tejeda, H., Kumar, A., Belem, C., Karny, S., Hu, X., Mayer, L.W., Smyth, P., 2025. What large language models know and what people think they know. Nature Machine Intelligence 7, 221–231.
Van Riel, A., Nederlof, M.A.J., Chary, K., Wiegertjes, G.F., De Boer, I.J.M., 2023. Feed-food competition in global aquaculture: Current trends and prospects. Reviews in Aquaculture 15, 1142–1158. https://doi.org/10.1111/raq.12804
Vaswani, A., Shazeer, N., Parmar, N., Uszkoreit, J., Jones, L., Gomez, A.N., Kaiser, L. ukasz, Polosukhin, I., 2017. Attention is All you Need, in: Advances in Neural Information Processing Systems. Curran Associates, Inc.
Wang, C., Li, Z., Wang, T., Xu, X., Zhang, X., Li, D., 2021. Intelligent fish farm—the future of aquaculture. Aquacult Int 29, 2681–2711. https://doi.org/10.1007/s10499-021-00773-8
Wang, F., Zhou, W., Huang, J.Y., Xu, N., Zhang, S., Poon, H., Chen, M., 2024. mDPO: Conditional Preference Optimization for Multimodal Large Language Models, in: Proceedings of the 2024 Conference on Empirical Methods in Natural Language Processing. Presented at the Proceedings of the 2024 Conference on Empirical Methods in Natural Language Processing, Association for Computational Linguistics, Miami, Florida, USA, pp. 8078–8088. https://doi.org/10.18653/v1/2024.emnlp-main.460
Wei, D., Bao, E., Wen, Y., Zhu, S., Ye, Z., Zhao, J., 2021. Behavioral spatial-temporal characteristics-based appetite assessment for fish school in recirculating aquaculture systems. Aquaculture 545, 737215. https://doi.org/10.1016/j.aquaculture.2021.737215
Weinreb, C., Pearl, J.E., Lin, S., Osman, M.A.M., Zhang, L., Annapragada, S., Conlin, E., Hoffmann, R., Makowska, S., Gillis, W.F., 2024. Keypoint-MoSeq: parsing behavior by linking point tracking to pose dynamics. Nature methods 21, 1329–1339.
Wu, Y., Wang, X., Shi, Y., Wang, Y., Qian, D., Jiang, Y., 2024. Fish feeding intensity assessment method using deep learning-based analysis of feeding splashes. Computers and Electronics in Agriculture 221, 108995. https://doi.org/10.1016/j.compag.2024.108995
Yang, X., Zhang, S., Liu, J., Gao, Q., Dong, S., Zhou, C., 2021. Deep learning for smart fish farming: applications, opportunities and challenges. Reviews in Aquaculture 13, 66–90. https://doi.org/10.1111/raq.12464
Zhao, S., Feng, G., Cai, K., Ma, Z., Liang, M., Liu, Y., 2026. A novel approach for quantifying and discriminating fish feeding behavior via Fishsort in RAS. Comput. Electron. Agric. 241. https://doi.org/10.1016/j.compag.2025.111271
Zhou, C., Lin, K., Xu, D., Chen, L., Guo, Q., Sun, C., Yang, X., 2018. Near infrared computer vision and neuro-fuzzy model-based feeding decision system for fish in aquaculture. Computers and Electronics in Agriculture 146, 114–124. https://doi.org/10.1016/j.compag.2018.02.006
Appendix A. Validation of kinematic data pipeline and behavioral indices
A.1. Physical-consistent kinematic augmentation and statistical distributional fidelity verification
A physical-consistent kinematic augmentation (PCKA) pipeline was applied to the 239 raw training segments, generating 2,868 transformed kinematic views to construct a composite training corpus of 3,107 instances (Section 2.1.2 and Table A.1). This pipeline incorporated spatial rigid flipping, global spatial rotation, viewpoint affine shearing, and temporal resampling to eliminate spatial biases. Spatial coordinates underwent geometric transformations, while planar velocities and accelerations were strictly re-calculated from transformed coordinates using finite differences to maintain internal kinematic consistency. To evaluate whether transformed views retain empirical kinematic distributions, multi-variable correlation distributions and two-sample Kolmogorov-Smirnov tests were conducted for displacement, velocity, acceleration, and the Activity Coefficient (AC) across all feeding intensity classes.
Table A.1
Summary of spatio-temporal data augmentation strategies, implementation details, and sample distributions.
| Augmentation Method | Transformation Details | Target Objective | Sample Count (N) |
|---|---|---|---|
| Raw Baseline | Original captured spatio-temporal sequences | Unaugmented experimental baseline | 239 |
| Spatial Rigid Flipping | Horizontal, vertical, and diagonal mirror transformations | Eliminate spatial positional bias | 717 (239×3) |
| Global Spatial Rotation | Isotropic coordinate rotations (90°, 180°, 270°) | Remove directional preferences | 717 (239×3) |
| Viewpoint Affine Shearing | Global shearing transformations along spatial axes | Simulate camera tilt and water refraction | 717 (239×3) |
| Temporal Resampling | Cubic spline interpolation along the time axis | Simulate rhythm variations ( continuity) | 717 (239×3) |
| Total Dataset | Comprehensive multi-view spatio-temporal expansion | Balanced dataset for robust model training | 3,107 |
Note: Each augmentation pipeline produces 717 synthesized samples, resulting in 2,868 augmented instances and a final dataset size of 3,107 sequences.
The bivariate scatter matrices and diagonal kernel density estimation curves for weak feeding in Fig. A.1(a), medium feeding in Fig. A.1(b), and strong feeding in Fig. A.1(c) illustrate high statistical concordance between the raw trajectories and synthesized views. Across all three feeding intensity categories, the diagonal kernel density distributions of displacement, velocity, acceleration, and the AC exhibit substantial overlap between raw and augmented data. Furthermore, the off-diagonal bivariate scatter distributions confirm that empirical linear and non-linear correlations among swimming displacement, velocity, and burst acceleration are largely preserved across the kinematic space. This demonstrates that the augmentation operations enriched training diversity without introducing severe numerical distortions or extreme outliers into the dataset.
The quantitative statistical similarity was substantiated by the two-sample Kolmogorov-Smirnov tests presented in Fig. A.2. All calculated p-values across displacement, velocity, acceleration, and the composite AC exceed the threshold of 0.05 across all three feeding intensity classes, ranging from 0.23 to 1.00. These non-parametric test results indicate that transformed sequences introduced no severe statistical distribution drift in low-order kinematics. This confirms empirical distributional consistency across training views, providing a stable data foundation for training the HBE.
Variance-AC Validation (PCKA): Weak [All Points]

b
Variance-AC Validation (PCKA): Medium [All Points]
C
Variance-AC Validation (PCKA): Strong [All Points]
Fig. A.1. Kinematic correlation scatter matrices and density distributions of original versus PCKA augmented data across feeding intensity classes: (a) weak feeding, (b) medium feeding, and (c) strong feeding.
Kolmogorov-Smirnov Test p-values: Original vs PCKA Augmented

Fig. A.2. Two-sample Kolmogorov-Smirnov test p-values between original and PCKA augmented distributions across kinematic features and feeding intensity classes.
A.2. Formulation ablation and discriminatory evaluation of candidate Activity Coefficients
An ablation study comparing the standardized mean formulated in Eq. (A.1), variance expressed in Eq. (A.2), and magnitude energy defined in Eq. (A.3) was conducted to determine the optimal mathematical representation for physical behavior aggregation.
Where , , and represent the school-averaged standardized displacement, velocity, and acceleration, and denotes the intra-group variance across tracked individuals within the segment.
A comparative ablation among , , and evaluated candidate formulations for the macroscopic behavior index on the independent validation split (N=30, comprising 10 balanced sequences per intensity class) prior to model freezing (Figs. A.3 to A.6). As shown in the box plots (Fig. A.3) and summary metrics (Fig. A.4), achieved the highest between-group discriminatory capability. A one-way ANOVA yielded an F-statistic of (p < 0.001), an effect size of 0.9291, and an empirical classification accuracy of 1.0000 across weak (mean = -0.4098), medium (mean = -0.0797), and strong (mean = 0.4895) feeding classes. In contrast, exhibited moderate discrimination (accuracy 0.9000, , ). suffered severe performance degradation
(accuracy 0.6333, , ). As visualized in the density distributions and pairwise scatter matrices in Fig. A.5, degraded separation because squaring zero-centered standardized variables folded negative velocity deviations into positive quadratic magnitudes. This sign folding forced weak and strong feeding states to overlap in the energy space, reflecting a structural limitation of standardized quadratic amplitudes rather than an intrinsic failure of energy metrics. Finally, the pairwise effect size heatmap in Fig. A.6 confirms that produced substantial absolute Cohen's d values (3.548 for weak vs. medium, 8.221 for weak vs. strong, and 4.731 for medium vs. strong). Consequently, was selected as the optimal kinematic aggregation metric.
AC Calculation Methods: Between-Group Separation Box Plot Comparison of Mean / Variance / Energy Methods

Fig. A.3. Box plot distributions and between-group separation metrics for candidate Activity Coefficient formulations across feeding intensity classes.
AC Method Comparison: Key Metrics
Key Metrics Comparison of Mean / Variance / Energy Methods

Fig. A.4. Key metrics comparison including ANOVA F-value, effect size eta-squared, and optimal classification accuracy.
AC (Mean)

AC (Variance)
AC (Energy)
AC (Variance)
AC (Energy)
Fig. A.5. Pairwise scatter matrices and kernel density distributions comparing the three AC formulations.
Absolute Cohen's d for Pairwise Group Separation

Fig. A.6. Pairwise Cohen's d effect size heatmap and bivariate correlation scatter matrices comparing AC(Mean), AC(Variance), and AC(Energy) formulations.
A.3. Data-driven empirical threshold optimization and decision boundary determination
An optimal empirical thresholding method was established to map continuous AC values into discrete feeding intensity categories. Let denote the scalar AC value, and let and represent the decision boundaries for weak and medium feeding regimes, respectively. The optimal threshold pair is determined by maximizing the empirical classification accuracy over the dataset of samples, subject to the monotonic physical constraint . A grid search optimization with a step size of was executed across candidate boundaries to identify coordinates yielding the highest classification accuracy. Formally, the piecewise classification function, accuracy objective, and optimal threshold formulation are expressed in Eqs. (A.4)-(A.6).
A.4. Ecological and biomechanical validation of the negative correlation between local fish density and feeding activity
Spatial schooling distribution was quantified via mean Local Density, defined as the inverse of the mean nearest-neighbor distance across tracked individuals (contrasting with the absolute neighborhood counts in Fig. 7). Across the 299 raw benchmark sequences, Local density showed a significant negative monotonic correlation with the composite AC (Spearman , , Pearson , ). Because both metrics derive from the trajectory tensor X, this correlation reflects behavioral consistency between spatial dispersion and locomotion activity during feeding, rather than an independent disproof of tracking artifacts. As visualized in the bivariate heatmap in Fig. A.7(a), sample concentrations shift continuously from high-density, low-AC resting zones toward low-density, high-AC foraging regimes across the decision boundaries (0.181 and 0.462). Furthermore, a Chi-square test of independence across five density intervals confirmed a significant structural shift in schooling organization ( , , Fig. A.7(b)), capturing the biological transition from cohesive shoaling at rest to spatial dispersal during competitive food scrambles.
2D Density: Avg Local Density vs AC

Feeding Intensity Proportion by Fish Density
b

Fig. A.7. Quantitative correlation between mean local fish school density and feeding intensity across the 299 raw benchmark sequences. Subplot (a) shows the bivariate density heatmap of normalized local density versus AC with supervisory boundaries of 0.181 and 0.462; subplot (b) shows feeding intensity class proportions across five progressive local density intervals.
A.5. Representation probing of kinematic velocity heterogeneity
While the scalar AC effectively quantifies collective swimming vigor, mean based spatial aggregation inherently compresses the underlying velocity distribution. Consequently, identical AC values may correspond to either a non-uniform distribution where a subset of individuals exhibits high velocities alongside slower moving peers, or a uniform distribution where the majority of individuals swim at homogeneous intermediate velocities. To verify whether downstream behavioral tokens preserve this kinematic heterogeneity rather than degenerating into macroscopic activity proxies, linear probing evaluations were conducted across the thirty held out benchmark sequences.
Kinematic dispersion was parameterized by the coefficient of variation (CV) of per fish mean swimming speed ( ), derived from individual tracking trajectories across the ten temporal segments. To probe behavioral representations without introducing unconstrained parameters, frozen token vectors were evaluated using ridge regression probes. For each sequence, the 14 behavioral tokens (M=4 explicit and K=10 implicit soft tokens) were mean pooled across the token dimension into a 4096 dimensional feature vector, avoiding excessive dimensionality expansion. Evaluations followed a strict five-fold cross validation protocol (random seed 42). Within each cross validation split, feature standardization via z score scaling and Ridge regressor fitting ( ) were fitted exclusively on the training folds and subsequently evaluated on the out of fold test split to ensure zero data leakage. The HBE backbone remained entirely frozen and had received no supervision regarding velocity dispersion during prior training stages.
Across five-fold evaluation, linear probing on full behavioral tokens achieved a cross-validated determination coefficient of (Pearson , ) for predicting speed CV, while simultaneously capturing overall activity ( for AC, Pearson , ). These empirical results demonstrate that the learned token space linearly preserves statistical dispersion in individual swimming speeds beyond population averages. However, this evaluation strictly confirms representation level retention of kinematic variance under the specified probing protocol. These findings do not imply verified behavioral hierarchy, feed intake dominance, or competitive social structures, which require fine scale nutritional validation and individual feeding ground truth in future research.
Regression Probing on Full Tokens (5-fold CV)

Fig. A.8. Linear regression probing on full behavioral tokens across thirty experimental sequences. The left panel plots predicted against empirical coefficient of variation values for per-fish swimming speed, demonstrating distribution shape preservation. Correspondingly, the right panel depicts model fidelity against the macroscopic AC to substantiate global activity level retention.
Same AC, Different Behavior Heterogeneity Gray lines: AC-matched A/B pairs
a

AC-Matched Pairs: Per-Fish Speed Distributions A (heterogeneous) vs B (homogeneous)
b

A (hetero): m115 AC=0.230
B (homo): m118 AC=0.250
A (hetero): m120 AC=0.270
B (homo): m119 AC=0.280
A (hetero): m97 AC=0.360
B (homo): m91 AC=0.340
Per-Fish Mean Speed
Per-Fish Mean Speed
Fig. A.9. Analysis of fish schooling behavioral heterogeneity across identical AC regimes. Subplot (a) shows the scatter distribution of AC versus the Coefficient of Variation of per-fish mean speed, with connected pairs denoting matched macroscopic activity levels across heterogeneous and homogeneous patterns. Subplot (b) displays per-fish speed distribution comparisons across three representative matched pairs, contrasting skewed minority-active distributions with uniform moderate-swimming distributions under equivalent AC baselines.
Appendix B. Mathematical formulations of architectural blocks, losses, and evaluation metrics
B.1. Architectural operator formulations of HBE
The fundamental mathematical operator driving both individual temporal modeling and collective set-level aggregation in the Hierarchical Behavior Encoder (HBE) is the scaled dot-product attention mechanism (Vaswani et al., 2017), which dynamically scales values V based on queries Q and keys K of dimension as defined in Eq. (B.1). To model multi-fish interactions across entity subspaces without imposing an artificial spatial order, the Set Transformer architecture defines the Multihead Attention Block (MAB) for two representation sets X and Y (Lee et al., 2019). This structure computes an intermediate normalized attention feature H via Eq. (B.2) and passes it through a row-wise feedforward network (rFF) with residual connection to yield the final block output formulated in Eq. (B.3). Building upon this formulation, the Set Attention Block (SAB) is defined as self-attention over the same set via Eq. (B.4). Within the HBE pipeline, the temporal modeling layer applies multi-head self-attention driven by Eq. (B.1) across the temporal dimension T for each individual fish sequence to produce entity representations , while the subsequent collective layer applies SAB across the entity dimension N to yield the permutation-invariant school representation .
B.2. Parameter-efficient fine-tuning formulation via LoRA
Low-Rank Adaptation (LoRA) is integrated into the multi-head attention projection layers to adapt the Large Language Model (LLM) to aquaculture feeding management without incurring prohibitive computational overhead (Hu et al., 2021). The pre-trained parameter matrix is frozen during training, and the intrinsic rank constraint is modeled by injecting trainable low-rank decomposition matrices and . The modified forward pass computation is mathematically formulated in Eq. (B.5), where and represent the layer input and output vectors respectively, and denote the low-rank adapter matrices with rank serves as a constant scaling factor:
B.3. Standard evaluation metric formulations
Accuracy is defined as the proportion of model-generated structured feeding decisions that are entirely consistent with the expert baseline strategies, computed via Eq. (B.6), where represents the number of samples with all three decision fields (feeder state, feeding interval, and feed amount) predicted correctly, and is the total number of samples. To evaluate class-wise performance, the decision recall measures the coverage of correct predictions within specific intensity classes. As formulated in Eq. (B.7), is calculated where represents the correctly predicted samples for class and is the actual total number of samples in class . The Invalid Rate quantifies the proportion of model outputs that suffer from formatting collapse or lack analysable decision fields, expressed in Eq. (B.8), where represents the number of samples missing at least one decision field.
Semantic fidelity is quantified through BLEU, which evaluates the exact n-gram overlap between generated rationales and expert reference texts via Eq. (B.9). Extending this to measure lexical diversity, Self-BLEU evaluates pairwise n-gram overlap across the generated responses according to Eq. (B.10). In both formulations, BP denotes the brevity penalty, with n-gram precision denoted as for external reference evaluations and for internal corpus evaluations. A lower Self-BLEU score indicates reduced phrasing redundancy across distinct test cases. ROUGE-L evaluates structural lexical overlap based on the Longest Common Subsequence (LCS), measuring surface sentence similarity between generated explanations and reference texts. The precision ( ) and recall ( ) of ROUGE-L are formulated in Eq. (B.11), with the F1 score calculated via Eq. (B.12). METEOR incorporates stemming and synonym matching to evaluate semantic alignment beyond strict surface matching, computing the harmonic mean ( ) in Eq. (B.13) before applying a fragmentation penalty in Eq. (B.14). Furthermore, BERTScore computes cosine similarity over contextual token embeddings to evaluate semantic similarity in latent space. Precision and recall for BERTScore are defined in Eq. (B.15), and the composite F1 score is formulated in Eq. (B.16).
Appendix C. Experimental configurations, counterfactual policy design, and qualitative case studies
C.1. Counterfactual perturbation scenarios and prescriptive action modulation protocol
Counterfactual preference pairs were curated in collaboration with aquaculture domain experts to prevent the policy model from relying on language shortcuts or unconstrained visual motion. The counterfactual protocol holds underlying visual kinematics v invariant while shifting environmental telemetry into biologically stressful or restrictive intervals (Table C.1). Under critical hypoxia or extreme thermal stress, restrictive actuation commands are mandated regardless of schooling vigor. This protocol enforces conditional reliance on environmental safety bounds when visual feeding activity conflicts with water quality constraints.
Table C.1
Counterfactual environmental perturbation scenarios and prescriptive action modulation effects in RAS.
| Environmental Dimension | Perturbation Scenarios | Physical Grounding & Biological Context | Prescribed Action Modulation Effect (Counterfactual Policy) |
|---|---|---|---|
| Water Temperature | Extreme Low (1°C) | Below critical physiological tolerance for O. mykiss | Force Stop: Feeder state, Stop; Feed amount, 0%; increase water temperature to 10-20°C |
| Low (5°C) | Suboptimal cold stress, depressed digestive enzyme activity | Restrict Feeding: Reduce feed amount by 50%; Extend interval to 10s; increase water temperature to 10-20°C | |
| Ideal (15°C) | Optimal metabolic range and feed conversion window | Nominal Baseline: Execute action strictly according to visual kinematics; maintain current water temperature | |
| High (25°C) | Suboptimal heat stress, elevated postprandial oxygen demand | Restrict Feeding: Reduce feed amount by 20%; Extend interval to 7s; reduce water temperature to 10-20°C | |
| Extreme High (30°C) | Approaching upper lethal thermal limit | Force Stop: Feeder state, stop; Feed amount, 0%; reduce the water temperature to 10-20°C | |
| Dissolved Oxygen (DO) | Critical Hypoxia (2.0 mg/L) | Below critical respiratory limit; acute asphyxia risk | Force Stop: Immediate feeding suspension to prevent DO collapse; increase DO to 8.0 mg/L |
| Mild Hypoxia (4.0 mg/L) | Suboptimal respiratory stress | Restrict Feeding: Reduce feed amount by 50%; Extend interval to 10s; increase DO to 8.0 mg/L | |
| Hyperoxia (14.0 mg/L) | In a supersaturated state, fish may suffer from Gas Bubble Disease | Nominal Baseline: Execute action strictly according to visual kinematics; decrease DO above 8.0 mg/L | |
| Stocking Density | Low Density (10 kg/m) | Minimal competition; abundant spatial resources | Nominal Baseline: Execute action strictly according to visual kinematics; moderately increase the number of fish |
| High Density (100 kg/m) | Increased metabolic waste; elevated biofilter load | Conservative Action: Reduce feed amount by 20%; Extend interval to 7s; moderately decrease the number of fish | |
| Extreme Density (130 kg/m) | Severe spatial crowding; risk of biological filter collapse | Force Stop: Feeder state, stop to safeguard water quality; moderately decrease the number of fish | |
| Feed Intake | Deficient (1% body weight) | Undersatiated baseline; high nutrient assimilation capacity | Nominal Baseline: Permit full ration according to visual appetite |
| Ideal (4% body weight) | Standard daily nutritional ration for 65g body weight | Nominal Baseline: Execute standard threshold response |
| Excessive (8% body weight) | Satiety limit exceeded; high residual feed pollution risk | Force Stop: Withhold feed regardless of schooling kinematics; remove residual food. | |
| Fish Species | Oreochromis niloticus (At 12°C) | Tropical species; 12°C induces acute hypothermic coma | Force Stop: Inhibit feeding due to critical physiological cold stress |
| Oreochromis niloticus (At 25°C, 8.0 mg/L DO) | Optimal tropical metabolic environment | Nominal Baseline: Permit feeding governed by visual kinematics | |
| Channa argus (At 12°C) | Low winter metabolic dormancy; depressed nutrient uptake | Force Stop: Inhibit feeding due to seasonal thermal dormancy | |
| Channa argus (At 20°C, 4.0 mg/L DO) | Compatible physiological baseline for the species | Nominal Baseline: Permit feeding governed by visual kinematics |
C.2. Hardware specifications and multi-stage hyperparameter configurations
The physical experimentation and algorithmic pipeline were developed across a heterogeneous edge-cloud architecture, with hardware specifications and operating environments detailed in Table C.2. Table C.3 documents the multi-stage hyperparameter configurations across Stage 1 (HBE pretraining), Stage 2 (LoRA supervised fine-tuning), and Stage 3 (mDPO alignment).
Table C.2 Hardware and software experimental environment configurations.
| Platform | Component | Specification |
|---|---|---|
| Edge Computing Device | CPU | 13th Gen Intel® Core™ i9-13900K @ 3.00 GHz |
| RAM | 64 GB DRAM | |
| GPU | NVIDIA GeForce RTX 4080 (16 GB VRAM) | |
| Cloud Server | CPU | Intel® Xeon® Platinum 8352V |
| RAM | 128 GB DRAM | |
| GPU | NVIDIA Tesla A800 (80 GB VRAM) | |
| Software Stack | Operating System | Ubuntu 22.04 LTS |
| Programming Language | Python 3.9.18 | |
| Deep Learning Framework | PyTorch 1.12.1 with CUDA 11.3 | |
| Development and Tooling | PyCharm IDE, DarkLabel |
Table C.3
Comprehensive hyperparameter settings and configuration details across the three training stages.
| Parameter | HBE Pretraining (Stage 1) | LLM SFT Training (Stage 2) | mDPO Training (Stage 3) |
|---|---|---|---|
| Learning Rate | (LoRA) / (HBE) | ||
| Batch Size (per device) | |||
| Grad Accumulation Steps | — | ||
| Epochs | |||
| Optimizer | Adam | AdamW (Dual LR) | AdamW |
| LR Scheduler | Cosine Annealing LR | Constant LR (no warmup) | Cosine (warmup_ratio=0.1) |
| Max Grad Norm | — | ||
| Max Sequence Length | — | ||
| Mixed Precision | AMP (default) | bf16=True, fp16=False | bf16=False, fp16=False (float32) |
| Weight Decay | — | — | |
| Loss Weights | [1.0, 1.0, 1.0, 0.5, 0.1, 0.1] | Weak class weighting (weight=2.0) | |
| LoRA Config | — | r=8, , dropout=0.05 | r=8, , dropout=0.05 |
| HBE Config | K=10, M=4, D=4096, Ds=64 | K=10, M=4, D=4096 (end-to-end joint training) | K=10, M=4, D=4096 (precomputed soft tokens) |
| Data Loading Workers | |||
| Gradient Checkpointing | — | Optional | Optional |
| Save Strategy | Best validation accuracy | Save every epoch (max 3) | Save every epoch (max 2) |
C.3. Qualitative behavior-grounded reasoning cases
Comparative inference transcripts evaluating Supervised Fine-Tuning (LoRA) against counterfactual mDPO in a representative strong feeding scenario are illustrated in Fig. C.1. This comparison shows how preference optimization resolves operational mismatches under identical environmental telemetry and visual prefix tokens. While the baseline Supervised Fine-Tuning model displays an action mismatch by recommending an extended 7-second feeding interval alongside contradictory text concerning feeding cessation, the preference-aligned policy links high-magnitude collective dynamics with active feeding protocols and prompt 5-second actuation verified by the deterministic validator.

"User query": "You are an aquaculture intelligent feeding decision system. Based on behavioral indicators of rainbow trout (Oncorhynchus mykiss) in RAS, please provide the corresponding feeding decision.", "input": "Count of trout: 78; Pond temperature: 12.0 °C; Dissolved O₂: 8.0 mg/L; pH: 8.0; Fish species: Oncorhynchus mykiss; System type: RAS; Average fish weight: 65 g; Feed size: 1.0 mm; Equipment status: Normal; Experiment location: Yuhang Smart Aquaculture Research Center (Hangzhou, Zhejiang Province, China); Experiment period: 10 days; Feeding times: 8:30 and 16:30 per day; Average displacement: 60.41 cm; Swimming speed: 19.68 cm/s; Acceleration: 543.97 cm/s²; Local_Density: 14.11, "soft_token_ref": {"video_name": "83", "shape": [10, 4096], "dtype": "torch.float32"}

AC=0.76, intensity=strong, count=78
FAIL expected:strong | output: After suspending feeding, it is essential to continuously monitor key water quality parameters, such as water temperature, dissolved oxygen, and ammonia nitrogen levels, as these factors directly influence the metabolism and feeding behavior of the rainbow trout. To ensure a stable growth environment for the trout, it is advised that the system's water circulation and filtration efficiency be thoroughly inspected. Poor water circulation or low filtration efficiency may lead to water quality deterioration, thereby affecting the health and feeding behavior of the fish. Maintaining a balanced environment during the period of halted feeding is especially important, as it will have a significant impact on the fish's subsequent feeding activity. Guided by the expert's recommendations, the suggested decision is: Feeder_state: [OK] exp='Continue' pred='Continue'; feeding_interval: [MISMATCH] exp='Keep 5s feeding interval' pred='Keep 7s feeding interval'; feed_amount: [MISMATCH] exp='Keep current feed amount' pred='Reduce feed amount by 20%'.

AC=0.76, intensity=strong, count=78
PASS expected:strong | output: Please maintain the current feeding rate and ensure even distribution so that all fish have access to the feed without excessive competition. However, please note that active feeding is often accompanied by an increase in metabolism, and the rise in fish excretions can lead to higher concentrations of harmful substances such as ammonia and nitrite. Therefore, it is essential to closely monitor water quality parameters such as dissolved oxygen, pH, ammonia, and nitrite levels to ensure that the water quality remains in good condition. Additionally, during active feeding periods, the fish's oxygen consumption will significantly increase. To ensure feeding effectiveness, please ensure adequate dissolved oxygen levels in the aquaculture water. This is particularly important in hot weather or when fish density is high, as oxygen demand will be greater. It is recommended to activate aeration devices in a timely manner to maintain oxygen concentration within an appropriate range (generally recommended to stay above 8 mg/L). Moreover, the optimal water temperature for raising rainbow trout should be between 10-18°C, and the daily feed amount for rainbow trout should be 1% to 3% of their body weight. Rainbow trout in rapid growth periods have higher nutritional needs, requiring higher feeding frequency and quantity. However, overfeeding should be avoided, as excessive feeding can impair the fish's digestive function and may lead to intestinal diseases, especially conditions such as fatty liver or enteritis. Finally, during periods of active feeding, avoid external disturbances (such as noise or sudden changes in water flow) that may cause stress reactions in the fish. Also, avoid large-scale feeding during sudden environment changes or when there are significant changes in water quality. In light of the above, the feeding decision is: Feeder state: [OK] exp='Continue' pred='Continue'; Feeding interval: [OK] exp='Keep 5s feeding interval' pred='Keep 5s feeding interval'; Feed amount: [OK] exp='Keep current feed amount' pred='Keep current feed amount'.
Fig. C.1. Qualitative comparative case study of behavior-grounded feeding decision reasoning between Supervised Fine-Tuning (LoRA) and Counterfactual mDPO.
C.4. Quantitative operational safety and rule constraint diagnostics
The deterministic validator monitors decision outputs against expert physiological boundaries, ensuring that autonomous actuators do not induce ecological degradation or biofilter collapse in recirculating systems. As illustrated in Fig. C.2(a), the baseline Supervised Fine-Tuning (LoRA) policy yielded 28 correct decisions and 2 errors across the thirty test samples (93.33% accuracy), with one error violating restrictive feeding boundaries to trigger an unsafe continuation (USCR of 3.33%). In contrast, counterfactual mDPO achieved 29 correct decisions and 1 non-matching error (96.67% accuracy), while eliminating hazardous commands (USCR of 0.00%). This single discrepancy under mDPO represented a conservative shift from medium to weak feeding, which constitutes a fail-safe adjustment toward resource preservation. Furthermore, Fig. C.2(b) confirms that both models produced no invalid hallucinated rule formats, maintaining a 100.00% Hallucination Penalty Score (HPS) across all feeding intensity regimes. This diagnostic confirms that preference alignment enforces strict operational boundaries, intercepting abnormal events and safeguarding water quality.

b
Fig. C2. Quantitative operational safety and constraint compliance diagnostics comparing Supervised Fine-Tuning (LoRA) and Counterfactual mDPO. (a) Frequency distributions of classification outcomes and Unsafe Continue Rate (USCR) metrics. (b) Hallucination Penalty Score (HPS) validation across feeding intensity classes.
Appendix D. Offline full-process feeding long-video inference of THPL on juvenile O. mykiss
To provide an intuitive demonstration of the continuous behavioral perception and decision-making pipeline, a complete recording of the offline long-video inference of THPL is provided. Supplementary video 1 (duration: 6 min 5 s). Demonstrates the offline long-video inference and contextual decision reasoning of THPL across a complete juvenile rainbow trout (O. mykiss) feeding session in RAS. Operating at 5-second intervals, the system extracts continuous multi-target trajectories, computes the dynamic Activity Coefficient (AC), and synthesizes water quality constraints to generate structured feeding directives (feeder state, interval, and feed amount) along with interpretable diagnostic explanations. The demonstration video is publicly accessible at https://youtu.be/Tg2Qk7m46-A.