Skip to main content

tenflowers_neural/
multi_task.rs

1//! Multi-Task Learning (MTL) utilities.
2//!
3//! This module provides building blocks for training a single model on
4//! multiple related tasks simultaneously.  Multi-task learning regularises
5//! representations through shared inductive biases and often outperforms
6//! per-task single-task models in both accuracy and data efficiency.
7//!
8//! # Algorithms
9//!
10//! * [`MultiTaskLoss`] — Unified loss combination with four weighting strategies:
11//!   [`TaskWeighting::Equal`], [`TaskWeighting::Uncertainty`] (Kendall et al.
12//!   2018), [`TaskWeighting::GradNorm`] (Chen et al. 2018), and
13//!   [`TaskWeighting::Dynamic`] (user-supplied weights).
14//!
15//! * [`pcgrad_project`] — PCGrad (Yu et al. 2020): projects each task's
16//!   gradient onto the normal plane of conflicting gradients, reducing
17//!   destructive interference between tasks.
18//!
19//! * [`MultiTaskModel`] — Combines a shared backbone (represented by its
20//!   output dimension) with per-task [`TaskHead`] projections and a
21//!   [`MultiTaskLoss`] combiner.
22//!
23//! * [`AuxiliaryTaskScheduler`] — Decays auxiliary task weights over epochs
24//!   so that the main task gradually dominates training.
25//!
26//! # Quick start
27//!
28//! ```rust,ignore
29//! use tenflowers_neural::multi_task::{MultiTaskModel, TaskHead, MultiTaskLoss, TaskWeighting};
30//!
31//! let mut model = MultiTaskModel::new(128);
32//! model.add_task(TaskHead::new("classification", 128, 10));
33//! model.add_task(TaskHead::new("regression", 128, 1));
34//!
35//! let repr = vec![0.0_f32; 128];
36//! let outputs = model.forward_all(&repr);
37//! ```
38
39use std::fmt;
40
41// ─────────────────────────────────────────────────────────────────────────────
42// Error type
43// ─────────────────────────────────────────────────────────────────────────────
44
45/// Errors that can arise in multi-task learning operations.
46#[derive(Debug)]
47pub enum MultiTaskError {
48    /// No task with the given name exists.
49    TaskNotFound { name: String },
50    /// A task's prediction/target dimension doesn't match expectations.
51    DimensionMismatch {
52        task: String,
53        expected: usize,
54        found: usize,
55    },
56    /// The model has no task heads registered.
57    NoTasks,
58    /// The number of supplied weights doesn't match the number of tasks.
59    WeightMismatch {
60        num_tasks: usize,
61        num_weights: usize,
62    },
63}
64
65impl fmt::Display for MultiTaskError {
66    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
67        match self {
68            MultiTaskError::TaskNotFound { name } => {
69                write!(f, "task '{}' not found", name)
70            }
71            MultiTaskError::DimensionMismatch {
72                task,
73                expected,
74                found,
75            } => {
76                write!(
77                    f,
78                    "task '{}': expected dimension {} but found {}",
79                    task, expected, found
80                )
81            }
82            MultiTaskError::NoTasks => write!(f, "no task heads have been added to the model"),
83            MultiTaskError::WeightMismatch {
84                num_tasks,
85                num_weights,
86            } => {
87                write!(
88                    f,
89                    "weight count mismatch: {} tasks but {} weights provided",
90                    num_tasks, num_weights
91                )
92            }
93        }
94    }
95}
96
97impl std::error::Error for MultiTaskError {}
98
99// ─────────────────────────────────────────────────────────────────────────────
100// Task weighting strategies
101// ─────────────────────────────────────────────────────────────────────────────
102
103/// Strategy for combining per-task losses into a single scalar.
104#[derive(Debug, Clone)]
105pub enum TaskWeighting {
106    /// All tasks receive weight `1 / num_tasks` (uniform).
107    Equal,
108    /// Uncertainty weighting (Kendall et al. 2018): each task has a learned
109    /// log-variance `σ_t²`.  The loss for task `t` is
110    /// `L_t / (2σ_t²) + log σ_t`.
111    /// The inner `Vec<f32>` stores initial log-variance values.
112    Uncertainty(Vec<f32>),
113    /// GradNorm (Chen et al. 2018): dynamically re-weights tasks so that each
114    /// task's gradient norm grows at the same rate relative to the shared
115    /// backbone.  `alpha` controls the asymmetry strength (commonly 1.5).
116    GradNorm { alpha: f32 },
117    /// User-supplied static weights (one per task).
118    Dynamic(Vec<f32>),
119}
120
121// ─────────────────────────────────────────────────────────────────────────────
122// MultiTaskLoss
123// ─────────────────────────────────────────────────────────────────────────────
124
125/// Combined multi-task loss with pluggable weighting.
126///
127/// Maintains internal state for learnable weighting strategies (e.g.
128/// [`TaskWeighting::Uncertainty`]) and exposes a simple [`combine`] interface
129/// that maps a per-task loss vector to a scalar.
130///
131/// [`combine`]: MultiTaskLoss::combine
132#[derive(Debug, Clone)]
133pub struct MultiTaskLoss {
134    /// Active weighting strategy.
135    pub weighting: TaskWeighting,
136    /// Number of tasks.
137    pub num_tasks: usize,
138    /// Learned log-variance parameters used by the `Uncertainty` strategy.
139    /// For other strategies this vector is empty.
140    pub log_vars: Vec<f32>,
141}
142
143impl MultiTaskLoss {
144    /// Create a new multi-task loss combiner.
145    ///
146    /// For `TaskWeighting::Uncertainty(init_log_vars)`, the initial log-variance
147    /// values must have exactly `num_tasks` elements; they are copied into
148    /// `log_vars`.  For other strategies `log_vars` is initialised to zeros.
149    pub fn new(num_tasks: usize, weighting: TaskWeighting) -> Self {
150        let log_vars = match &weighting {
151            TaskWeighting::Uncertainty(init) => init.clone(),
152            _ => vec![0.0_f32; num_tasks],
153        };
154        MultiTaskLoss {
155            weighting,
156            num_tasks,
157            log_vars,
158        }
159    }
160
161    /// Combine per-task losses `task_losses` into a single scalar using the
162    /// configured weighting strategy.
163    ///
164    /// The returned value is the weighted total loss ready for
165    /// backpropagation.
166    pub fn combine(&mut self, task_losses: &[f32]) -> f32 {
167        let n = self.num_tasks;
168        match &self.weighting.clone() {
169            TaskWeighting::Equal => {
170                let w = if n > 0 { 1.0 / n as f32 } else { 0.0 };
171                task_losses.iter().map(|&l| w * l).sum()
172            }
173            TaskWeighting::Uncertainty(_) => {
174                // L = Σ_t  L_t / (2 * exp(log_var_t))  +  (1/2) * log_var_t
175                // Numerically stable: use exp(log_var) = precision.
176                task_losses
177                    .iter()
178                    .zip(self.log_vars.iter())
179                    .map(|(&lt, &lv)| {
180                        let precision = (-lv).exp(); // 1 / σ_t²
181                        lt * precision * 0.5 + lv * 0.5
182                    })
183                    .sum()
184            }
185            TaskWeighting::GradNorm { .. } => {
186                // GradNorm weights are updated externally; here we fall back to
187                // equal weighting since gradient norms require access to the
188                // actual gradient tensors which are not available in this
189                // scalar-only interface.
190                let w = if n > 0 { 1.0 / n as f32 } else { 0.0 };
191                task_losses.iter().map(|&l| w * l).sum()
192            }
193            TaskWeighting::Dynamic(weights) => {
194                let weights = weights.clone();
195                task_losses
196                    .iter()
197                    .zip(weights.iter().chain(std::iter::repeat(&1.0)))
198                    .map(|(&l, &w)| l * w)
199                    .sum()
200            }
201        }
202    }
203
204    /// Return the effective per-task weight vector given the current state.
205    ///
206    /// For `Uncertainty` weighting, weights are `1/(2σ_t²)` (precision halves).
207    /// For `GradNorm` weighting, equal weights are returned (runtime update
208    /// requires gradient access).
209    pub fn weights(&self) -> Vec<f32> {
210        let n = self.num_tasks;
211        match &self.weighting {
212            TaskWeighting::Equal | TaskWeighting::GradNorm { .. } => {
213                let w = if n > 0 { 1.0 / n as f32 } else { 0.0 };
214                vec![w; n]
215            }
216            TaskWeighting::Uncertainty(_) => {
217                self.log_vars.iter().map(|&lv| 0.5 * (-lv).exp()).collect()
218            }
219            TaskWeighting::Dynamic(weights) => weights.clone(),
220        }
221    }
222
223    /// Perform one gradient-based update step for the uncertainty `log_vars`.
224    ///
225    /// The gradient of the uncertainty loss w.r.t. `log_var_t` is:
226    ///
227    /// ```text
228    /// ∂L / ∂log_var_t = 0.5 - 0.5 * L_t * exp(-log_var_t)
229    ///                  = 0.5 * (1 - L_t / σ_t²)
230    /// ```
231    ///
232    /// Only modifies `log_vars` when `TaskWeighting::Uncertainty` is active.
233    pub fn update_uncertainty_weights(&mut self, task_losses: &[f32], lr: f32) {
234        if !matches!(self.weighting, TaskWeighting::Uncertainty(_)) {
235            return;
236        }
237        for (lv, &lt) in self.log_vars.iter_mut().zip(task_losses.iter()) {
238            // Gradient ascent on log_var to minimise L (gradient descent on -L).
239            let grad = 0.5 * (1.0 - lt * (-*lv).exp());
240            *lv -= lr * grad;
241        }
242    }
243}
244
245// ─────────────────────────────────────────────────────────────────────────────
246// PCGrad — Gradient Surgery
247// ─────────────────────────────────────────────────────────────────────────────
248
249/// Compute the cosine similarity between two flat gradient vectors.
250///
251/// Returns a value in `[-1, 1]` for unit-norm inputs; returns `0.0` when
252/// either vector has zero norm.
253pub fn gradient_cosine_similarity(g1: &[f32], g2: &[f32]) -> f32 {
254    let dot: f32 = g1.iter().zip(g2.iter()).map(|(&a, &b)| a * b).sum();
255    let n1: f32 = g1.iter().map(|&a| a * a).sum::<f32>().sqrt();
256    let n2: f32 = g2.iter().map(|&b| b * b).sum::<f32>().sqrt();
257    if n1 < f32::EPSILON || n2 < f32::EPSILON {
258        return 0.0;
259    }
260    (dot / (n1 * n2)).clamp(-1.0, 1.0)
261}
262
263/// PCGrad: Project Conflicting Gradients (Yu et al. 2020).
264///
265/// For each task `i`, the gradient `g_i` is projected onto the normal plane of
266/// `g_j` for every other task `j` that conflicts with it (i.e.
267/// `cos(g_i, g_j) < 0`):
268///
269/// ```text
270/// g_i  ←  g_i  −  (g_i · ĝ_j) · ĝ_j     if  g_i · g_j < 0
271/// ```
272///
273/// This removes the component of `g_i` that points in the opposite direction
274/// to `g_j`, thus reducing destructive interference without affecting tasks
275/// that are compatible.
276///
277/// All input gradients must have the same length.  Returns projected gradients
278/// in the same order as the input.
279pub fn pcgrad_project(task_grads: &[Vec<f32>]) -> Vec<Vec<f32>> {
280    let n = task_grads.len();
281    if n == 0 {
282        return Vec::new();
283    }
284
285    let dim = task_grads[0].len();
286    let mut projected: Vec<Vec<f32>> = task_grads.to_vec();
287
288    for i in 0..n {
289        for j in 0..n {
290            if i == j {
291                continue;
292            }
293            // Check for conflict.
294            let dot: f32 = projected[i]
295                .iter()
296                .zip(task_grads[j].iter())
297                .map(|(&a, &b)| a * b)
298                .sum();
299
300            if dot >= 0.0 {
301                // Gradients compatible — no projection needed.
302                continue;
303            }
304
305            // Compute the unit vector of g_j.
306            let norm_j_sq: f32 = task_grads[j].iter().map(|&b| b * b).sum();
307            if norm_j_sq < f32::EPSILON {
308                continue;
309            }
310
311            // Project g_i: g_i ← g_i − (g_i · g_j / |g_j|²) * g_j
312            let scale = dot / norm_j_sq;
313            for k in 0..dim {
314                if k < task_grads[j].len() {
315                    projected[i][k] -= scale * task_grads[j][k];
316                }
317            }
318        }
319    }
320
321    projected
322}
323
324// ─────────────────────────────────────────────────────────────────────────────
325// TaskHead
326// ─────────────────────────────────────────────────────────────────────────────
327
328/// Task-specific linear output head.
329///
330/// Projects the shared backbone representation into the task's output space:
331///
332/// ```text
333/// y = W · h + b
334/// ```
335///
336/// where `h ∈ ℝ^{shared_dim}` and `y ∈ ℝ^{out_features}`.
337///
338/// Weights are stored in row-major order: `weights[out * shared_dim + in]`.
339#[derive(Debug, Clone)]
340pub struct TaskHead {
341    /// Unique task name used for lookup.
342    pub task_name: String,
343    /// Flattened weight matrix, shape `[out_features * shared_dim]`.
344    pub weights: Vec<f32>,
345    /// Bias vector, shape `[out_features]`.
346    pub bias: Vec<f32>,
347    /// Output dimension.
348    pub out_features: usize,
349    /// Input dimension (shared backbone output size).
350    pub shared_dim: usize,
351    /// Scalar loss weight for this task (default 1.0).
352    pub loss_weight: f32,
353}
354
355impl TaskHead {
356    /// Create a new task head with zero-initialised weights and biases.
357    pub fn new(task_name: impl Into<String>, shared_dim: usize, out_features: usize) -> Self {
358        TaskHead {
359            task_name: task_name.into(),
360            weights: vec![0.0_f32; out_features * shared_dim],
361            bias: vec![0.0_f32; out_features],
362            out_features,
363            shared_dim,
364            loss_weight: 1.0,
365        }
366    }
367
368    /// Run a linear forward pass: `y = W · h + b`.
369    ///
370    /// `shared_repr` must have length `shared_dim`.  Missing elements are
371    /// treated as zero.
372    pub fn forward(&self, shared_repr: &[f32]) -> Vec<f32> {
373        let mut out = self.bias.clone();
374        for o in 0..self.out_features {
375            let row_start = o * self.shared_dim;
376            let dot: f32 = (0..self.shared_dim)
377                .map(|i| {
378                    let w = self.weights.get(row_start + i).copied().unwrap_or(0.0);
379                    let x = shared_repr.get(i).copied().unwrap_or(0.0);
380                    w * x
381                })
382                .sum();
383            out[o] += dot;
384        }
385        out
386    }
387}
388
389// ─────────────────────────────────────────────────────────────────────────────
390// MultiTaskModel
391// ─────────────────────────────────────────────────────────────────────────────
392
393/// A multi-task model composed of a shared backbone and per-task heads.
394///
395/// The backbone produces a shared representation vector of dimension
396/// `shared_backbone_dim`.  Each [`TaskHead`] then projects this into its own
397/// output space.  The [`MultiTaskLoss`] combiner aggregates per-task scalar
398/// losses into a single training objective.
399#[derive(Debug, Clone)]
400pub struct MultiTaskModel {
401    /// Dimension of the shared backbone output.
402    pub shared_backbone_dim: usize,
403    /// Ordered task-specific output heads.
404    pub task_heads: Vec<TaskHead>,
405    /// Loss combiner.
406    pub loss: MultiTaskLoss,
407}
408
409impl MultiTaskModel {
410    /// Create a new model with no task heads.  Uses equal task weighting.
411    pub fn new(shared_backbone_dim: usize) -> Self {
412        MultiTaskModel {
413            shared_backbone_dim,
414            task_heads: Vec::new(),
415            loss: MultiTaskLoss::new(0, TaskWeighting::Equal),
416        }
417    }
418
419    /// Add a task head to the model.
420    ///
421    /// The loss combiner is rebuilt after each addition to keep `num_tasks`
422    /// in sync, preserving the `Equal` weighting strategy.
423    pub fn add_task(&mut self, head: TaskHead) {
424        self.task_heads.push(head);
425        // Rebuild the loss combiner to reflect the new task count.
426        let n = self.task_heads.len();
427        self.loss = MultiTaskLoss::new(n, TaskWeighting::Equal);
428    }
429
430    /// Number of registered tasks.
431    pub fn num_tasks(&self) -> usize {
432        self.task_heads.len()
433    }
434
435    /// Names of all registered tasks in registration order.
436    pub fn task_names(&self) -> Vec<&str> {
437        self.task_heads
438            .iter()
439            .map(|h| h.task_name.as_str())
440            .collect()
441    }
442
443    /// Run a forward pass through every task head.
444    ///
445    /// Returns a vector of `(task_name, output)` pairs in registration order.
446    pub fn forward_all<'a>(&'a self, shared_repr: &[f32]) -> Vec<(&'a str, Vec<f32>)> {
447        self.task_heads
448            .iter()
449            .map(|head| (head.task_name.as_str(), head.forward(shared_repr)))
450            .collect()
451    }
452
453    /// Compute the total weighted multi-task loss.
454    ///
455    /// For each task, the per-task scalar loss is computed by applying
456    /// `loss_fn(predictions, targets)`.  The results are then combined via
457    /// the configured [`MultiTaskLoss`].
458    ///
459    /// `targets` is a slice of `(task_name, target_values)` pairs.  Tasks
460    /// not present in `targets` are skipped (their loss is zero).
461    ///
462    /// # Errors
463    ///
464    /// Returns [`MultiTaskError::NoTasks`] when no heads are registered, or
465    /// [`MultiTaskError::TaskNotFound`] when a target task name is not in the
466    /// model.
467    pub fn total_loss(
468        &mut self,
469        shared_repr: &[f32],
470        targets: &[(&str, &[f32])],
471        loss_fn: impl Fn(&[f32], &[f32]) -> f32,
472    ) -> Result<f32, MultiTaskError> {
473        if self.task_heads.is_empty() {
474            return Err(MultiTaskError::NoTasks);
475        }
476
477        let mut per_task_losses: Vec<f32> = vec![0.0_f32; self.task_heads.len()];
478
479        for &(name, tgt) in targets {
480            // Find the task head index.
481            let idx = self
482                .task_heads
483                .iter()
484                .position(|h| h.task_name == name)
485                .ok_or_else(|| MultiTaskError::TaskNotFound {
486                    name: name.to_string(),
487                })?;
488
489            let pred = self.task_heads[idx].forward(shared_repr);
490            let task_loss = loss_fn(&pred, tgt);
491            per_task_losses[idx] = task_loss * self.task_heads[idx].loss_weight;
492        }
493
494        Ok(self.loss.combine(&per_task_losses))
495    }
496}
497
498// ─────────────────────────────────────────────────────────────────────────────
499// AuxiliaryTaskScheduler
500// ─────────────────────────────────────────────────────────────────────────────
501
502/// Schedules loss weights for a main task and a set of auxiliary tasks.
503///
504/// Auxiliary tasks often help during the early phases of training (acting as a
505/// regulariser), but should be de-emphasised as training progresses so that
506/// the main task objective dominates.  Each call to [`step`] multiplies the
507/// auxiliary weights by `(1 - decay_rate)`.
508///
509/// [`step`]: AuxiliaryTaskScheduler::step
510#[derive(Debug, Clone)]
511pub struct AuxiliaryTaskScheduler {
512    /// Weight for the primary task (fixed).
513    pub main_task_weight: f32,
514    /// Current weights for each auxiliary task (decayed over time).
515    pub aux_weights: Vec<f32>,
516    /// Per-step multiplicative decay factor applied to auxiliary weights.
517    pub decay_rate: f32,
518}
519
520impl AuxiliaryTaskScheduler {
521    /// Create a new scheduler.
522    ///
523    /// `decay_rate` in `[0, 1)`: fraction of the auxiliary weight removed each
524    /// epoch.  A value of `0.0` means no decay.
525    pub fn new(main_weight: f32, aux_weights: Vec<f32>, decay_rate: f32) -> Self {
526        AuxiliaryTaskScheduler {
527            main_task_weight: main_weight,
528            aux_weights,
529            decay_rate: decay_rate.clamp(0.0, 1.0 - f32::EPSILON),
530        }
531    }
532
533    /// Advance one step: decay all auxiliary weights by `(1 − decay_rate)`.
534    pub fn step(&mut self) {
535        for w in &mut self.aux_weights {
536            *w *= 1.0 - self.decay_rate;
537        }
538    }
539
540    /// Return the current weight vector: `[main_weight, aux_weight_0, aux_weight_1, …]`.
541    pub fn weights(&self) -> Vec<f32> {
542        let mut out = Vec::with_capacity(1 + self.aux_weights.len());
543        out.push(self.main_task_weight);
544        out.extend_from_slice(&self.aux_weights);
545        out
546    }
547}
548
549// ─────────────────────────────────────────────────────────────────────────────
550// Tests
551// ─────────────────────────────────────────────────────────────────────────────
552
553#[cfg(test)]
554mod tests {
555    use super::*;
556
557    // ── Equal weighting ───────────────────────────────────────────────────────
558
559    #[test]
560    fn equal_weighting_uniform() {
561        let mut loss = MultiTaskLoss::new(4, TaskWeighting::Equal);
562        let task_losses = [1.0_f32, 2.0, 3.0, 4.0];
563        let combined = loss.combine(&task_losses);
564        let expected = (1.0 + 2.0 + 3.0 + 4.0) / 4.0;
565        assert!(
566            (combined - expected).abs() < 1e-5,
567            "equal weighting should average losses, expected {}, got {}",
568            expected,
569            combined
570        );
571    }
572
573    #[test]
574    fn equal_weighting_weights_vector() {
575        let loss = MultiTaskLoss::new(3, TaskWeighting::Equal);
576        let w = loss.weights();
577        assert_eq!(w.len(), 3);
578        for &wi in &w {
579            assert!(
580                (wi - 1.0 / 3.0).abs() < 1e-6,
581                "each weight should be 1/3, got {}",
582                wi
583            );
584        }
585    }
586
587    // ── Uncertainty weighting ─────────────────────────────────────────────────
588
589    #[test]
590    fn uncertainty_weighting_differs_from_equal() {
591        let init_log_vars = vec![0.0_f32, 2.0]; // different initial uncertainties
592        let mut uncertainty_loss = MultiTaskLoss::new(2, TaskWeighting::Uncertainty(init_log_vars));
593        let mut equal_loss = MultiTaskLoss::new(2, TaskWeighting::Equal);
594
595        let task_losses = [1.0_f32, 1.0];
596        let u = uncertainty_loss.combine(&task_losses);
597        let e = equal_loss.combine(&task_losses);
598        assert!(
599            (u - e).abs() > 1e-4,
600            "uncertainty weighting should differ from equal when log_vars differ: u={}, e={}",
601            u,
602            e
603        );
604    }
605
606    #[test]
607    fn uncertainty_update_modifies_log_vars() {
608        let init_log_vars = vec![0.0_f32, 0.0];
609        let mut loss = MultiTaskLoss::new(2, TaskWeighting::Uncertainty(init_log_vars));
610        let before = loss.log_vars.clone();
611        loss.update_uncertainty_weights(&[2.0, 0.5], 0.01);
612        let changed = loss
613            .log_vars
614            .iter()
615            .zip(before.iter())
616            .any(|(a, b)| (a - b).abs() > 1e-8);
617        assert!(changed, "update_uncertainty_weights should modify log_vars");
618    }
619
620    #[test]
621    fn uncertainty_weights_vector_uses_precision() {
622        let log_vars = vec![0.0_f32, 1.0]; // precision = exp(0)=1, exp(-1)≈0.368
623        let loss = MultiTaskLoss::new(2, TaskWeighting::Uncertainty(log_vars));
624        let w = loss.weights();
625        assert_eq!(w.len(), 2);
626        // w[0] = 0.5 * exp(0) = 0.5
627        assert!(
628            (w[0] - 0.5).abs() < 1e-5,
629            "w[0] should be 0.5, got {}",
630            w[0]
631        );
632    }
633
634    // ── Dynamic weighting ─────────────────────────────────────────────────────
635
636    #[test]
637    fn dynamic_weighting_uses_supplied_weights() {
638        let weights = vec![2.0_f32, 0.5];
639        let mut loss = MultiTaskLoss::new(2, TaskWeighting::Dynamic(weights));
640        let combined = loss.combine(&[1.0, 1.0]);
641        // 2.0*1.0 + 0.5*1.0 = 2.5
642        assert!(
643            (combined - 2.5).abs() < 1e-5,
644            "dynamic weighting should use supplied weights, got {}",
645            combined
646        );
647    }
648
649    // ── PCGrad ───────────────────────────────────────────────────────────────
650
651    #[test]
652    fn pcgrad_no_conflict_unchanged() {
653        // Parallel gradients: no projection needed.
654        let g1 = vec![1.0_f32, 0.0];
655        let g2 = vec![1.0_f32, 0.0];
656        let projected = pcgrad_project(&[g1.clone(), g2.clone()]);
657        assert_eq!(projected.len(), 2);
658        // g1 projected should be unchanged (dot > 0).
659        let diff: f32 = projected[0]
660            .iter()
661            .zip(g1.iter())
662            .map(|(a, b)| (a - b).abs())
663            .sum();
664        assert!(diff < 1e-5, "parallel gradients should not be projected");
665    }
666
667    #[test]
668    fn pcgrad_removes_conflicting_component() {
669        // g1 = [1, 0] and g2 = [-1, 0] are fully opposed.
670        let g1 = vec![1.0_f32, 0.0];
671        let g2 = vec![-1.0_f32, 0.0];
672        let projected = pcgrad_project(&[g1, g2]);
673
674        // g1 projected onto plane normal to g2 should be zero (fully in conflict).
675        let norm0: f32 = projected[0].iter().map(|&v| v * v).sum::<f32>().sqrt();
676        assert!(
677            norm0 < 1e-5,
678            "conflicting gradients should be projected to zero along conflict direction, norm={}",
679            norm0
680        );
681    }
682
683    #[test]
684    fn pcgrad_empty_input() {
685        let result = pcgrad_project(&[]);
686        assert!(result.is_empty());
687    }
688
689    #[test]
690    fn pcgrad_output_shape() {
691        let grads: Vec<Vec<f32>> = (0..3).map(|i| vec![i as f32, (i + 1) as f32]).collect();
692        let projected = pcgrad_project(&grads);
693        assert_eq!(projected.len(), 3);
694        for p in &projected {
695            assert_eq!(p.len(), 2);
696        }
697    }
698
699    // ── Cosine similarity ─────────────────────────────────────────────────────
700
701    #[test]
702    fn cosine_similarity_parallel() {
703        let g = vec![1.0_f32, 2.0, 3.0];
704        let sim = gradient_cosine_similarity(&g, &g);
705        assert!(
706            (sim - 1.0).abs() < 1e-5,
707            "parallel vectors should have cosine similarity 1, got {}",
708            sim
709        );
710    }
711
712    #[test]
713    fn cosine_similarity_antiparallel() {
714        let g1 = vec![1.0_f32, 0.0];
715        let g2 = vec![-1.0_f32, 0.0];
716        let sim = gradient_cosine_similarity(&g1, &g2);
717        assert!(
718            (sim + 1.0).abs() < 1e-5,
719            "antiparallel vectors should have cosine similarity -1, got {}",
720            sim
721        );
722    }
723
724    #[test]
725    fn cosine_similarity_orthogonal() {
726        let g1 = vec![1.0_f32, 0.0];
727        let g2 = vec![0.0_f32, 1.0];
728        let sim = gradient_cosine_similarity(&g1, &g2);
729        assert!(
730            sim.abs() < 1e-5,
731            "orthogonal vectors should have cosine similarity 0, got {}",
732            sim
733        );
734    }
735
736    #[test]
737    fn cosine_similarity_zero_vector() {
738        let g1 = vec![0.0_f32, 0.0];
739        let g2 = vec![1.0_f32, 2.0];
740        let sim = gradient_cosine_similarity(&g1, &g2);
741        assert_eq!(sim, 0.0, "zero vector should yield similarity 0");
742    }
743
744    // ── TaskHead ──────────────────────────────────────────────────────────────
745
746    #[test]
747    fn task_head_forward_zero_weights_returns_bias() {
748        let head = TaskHead::new("test", 4, 3);
749        // All zero weights → output equals bias.
750        let out = head.forward(&[1.0, 2.0, 3.0, 4.0]);
751        assert_eq!(out.len(), 3);
752        for &v in &out {
753            assert_eq!(v, 0.0, "zero-weight head should return all zeros");
754        }
755    }
756
757    #[test]
758    fn task_head_forward_identity_weight() {
759        // 1x1 head with weight=2, bias=1 → output = 2*x + 1.
760        let mut head = TaskHead::new("id", 1, 1);
761        head.weights = vec![2.0];
762        head.bias = vec![1.0];
763        let out = head.forward(&[3.0]);
764        assert!(
765            (out[0] - 7.0).abs() < 1e-5,
766            "expected 2*3+1=7, got {}",
767            out[0]
768        );
769    }
770
771    #[test]
772    fn task_head_output_dimension_correct() {
773        let head = TaskHead::new("task", 8, 5);
774        let out = head.forward(&[1.0_f32; 8]);
775        assert_eq!(out.len(), 5);
776    }
777
778    // ── MultiTaskModel ────────────────────────────────────────────────────────
779
780    #[test]
781    fn multi_task_model_forward_all_returns_all_tasks() {
782        let mut model = MultiTaskModel::new(4);
783        model.add_task(TaskHead::new("cls", 4, 2));
784        model.add_task(TaskHead::new("reg", 4, 1));
785        let repr = vec![1.0_f32, 0.0, 0.0, 0.0];
786        let outputs = model.forward_all(&repr);
787        assert_eq!(outputs.len(), 2);
788        assert_eq!(outputs[0].0, "cls");
789        assert_eq!(outputs[1].0, "reg");
790        assert_eq!(outputs[0].1.len(), 2);
791        assert_eq!(outputs[1].1.len(), 1);
792    }
793
794    #[test]
795    fn multi_task_model_task_names() {
796        let mut model = MultiTaskModel::new(4);
797        model.add_task(TaskHead::new("a", 4, 1));
798        model.add_task(TaskHead::new("b", 4, 1));
799        let names = model.task_names();
800        assert_eq!(names, vec!["a", "b"]);
801    }
802
803    #[test]
804    fn multi_task_model_total_loss_no_tasks_error() {
805        let mut model = MultiTaskModel::new(4);
806        let result = model.total_loss(&[0.0; 4], &[], |_, _| 0.0);
807        assert!(matches!(result, Err(MultiTaskError::NoTasks)));
808    }
809
810    #[test]
811    fn multi_task_model_total_loss_unknown_task_error() {
812        let mut model = MultiTaskModel::new(4);
813        model.add_task(TaskHead::new("cls", 4, 2));
814        let result = model.total_loss(&[0.0; 4], &[("missing", &[1.0, 0.0])], |_, _| 0.0);
815        assert!(matches!(result, Err(MultiTaskError::TaskNotFound { .. })));
816    }
817
818    #[test]
819    fn multi_task_model_total_loss_computes() {
820        let mut model = MultiTaskModel::new(2);
821        model.add_task(TaskHead::new("t1", 2, 2));
822        let repr = vec![0.0_f32; 2];
823        let targets: &[(&str, &[f32])] = &[("t1", &[0.0, 0.0])];
824        let loss_result = model.total_loss(&repr, targets, |pred, tgt| {
825            pred.iter()
826                .zip(tgt.iter())
827                .map(|(p, t)| (p - t).powi(2))
828                .sum::<f32>()
829        });
830        assert!(
831            loss_result.is_ok(),
832            "total_loss should succeed for known task"
833        );
834    }
835
836    // ── AuxiliaryTaskScheduler ────────────────────────────────────────────────
837
838    #[test]
839    fn aux_scheduler_initial_weights() {
840        let sched = AuxiliaryTaskScheduler::new(1.0, vec![0.5, 0.3], 0.1);
841        let w = sched.weights();
842        assert_eq!(w.len(), 3);
843        assert_eq!(w[0], 1.0);
844        assert!((w[1] - 0.5).abs() < 1e-6);
845        assert!((w[2] - 0.3).abs() < 1e-6);
846    }
847
848    #[test]
849    fn aux_scheduler_step_decays_aux() {
850        let mut sched = AuxiliaryTaskScheduler::new(1.0, vec![1.0], 0.1);
851        sched.step();
852        let w = sched.weights();
853        // After one step: 1.0 * (1 - 0.1) = 0.9
854        assert!(
855            (w[1] - 0.9).abs() < 1e-6,
856            "aux weight should decay to 0.9, got {}",
857            w[1]
858        );
859    }
860
861    #[test]
862    fn aux_scheduler_main_weight_unchanged() {
863        let mut sched = AuxiliaryTaskScheduler::new(2.0, vec![1.0], 0.5);
864        for _ in 0..10 {
865            sched.step();
866        }
867        assert_eq!(
868            sched.main_task_weight, 2.0,
869            "main task weight should not decay"
870        );
871    }
872
873    #[test]
874    fn aux_scheduler_multiple_steps_geometric_decay() {
875        let mut sched = AuxiliaryTaskScheduler::new(1.0, vec![1.0], 0.2);
876        sched.step();
877        sched.step();
878        let w = sched.weights();
879        // (1 - 0.2)^2 = 0.64
880        assert!(
881            (w[1] - 0.64).abs() < 1e-5,
882            "two steps should give 0.64, got {}",
883            w[1]
884        );
885    }
886
887    #[test]
888    fn aux_scheduler_no_aux_tasks() {
889        let sched = AuxiliaryTaskScheduler::new(1.0, vec![], 0.1);
890        let w = sched.weights();
891        assert_eq!(w.len(), 1);
892        assert_eq!(w[0], 1.0);
893    }
894
895    #[test]
896    fn multi_task_error_display() {
897        let err = MultiTaskError::TaskNotFound {
898            name: "seg".to_string(),
899        };
900        assert!(err.to_string().contains("seg"));
901
902        let err2 = MultiTaskError::WeightMismatch {
903            num_tasks: 3,
904            num_weights: 2,
905        };
906        assert!(err2.to_string().contains("3") && err2.to_string().contains("2"));
907    }
908}