torsh-functional 0.2.0

Functional programming utilities for ToRSh tensors
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
//! Specialized loss functions
//!
//! This module provides specialized loss functions for specific domains
//! such as sequence-to-sequence learning, time series, and other advanced applications.

use crate::loss::common::{ReductionType, DISTANCE_FLOOR};
use crate::utils::{function_context, validate_positive};
use torsh_core::{Result as TorshResult, TorshError};
use torsh_tensor::Tensor;

/// Connectionist Temporal Classification (CTC) Loss
///
/// Computes the CTC loss between a sequence of predictions and a target sequence.
/// This is commonly used in speech recognition and handwriting recognition where
/// the alignment between input and target sequences is unknown.
///
/// # Arguments
/// * `log_probs` - Tensor of log probabilities with shape (T, N, C) where:
///   - T is the input sequence length
///   - N is the batch size
///   - C is the number of classes (including blank)
/// * `targets` - Target sequences with shape (N, S) where S is target sequence length
/// * `input_lengths` - Lengths of input sequences for each batch element
/// * `target_lengths` - Lengths of target sequences for each batch element
/// * `blank` - Index of the blank label (typically 0)
/// * `reduction` - Reduction type
/// * `zero_infinity` - Whether to zero out infinite losses
///
/// # Returns
/// CTC loss tensor
///
/// # Limitations
///
/// This is a **placeholder**: it sums the negative log-probabilities of the
/// target labels read straight off the time axis, with no blank handling and no
/// forward–backward marginalisation over alignments, so it does not compute the
/// CTC objective. It also builds its result from scalar reads
/// ([`torsh_tensor::Tensor::get`]) and therefore returns a tensor that is
/// **detached from the autograd graph** — `backward()` will not reach
/// `log_probs`.
///
/// Both facts are deliberate and recorded rather than papered over: reconnecting
/// autograd to a quantity that is not the CTC loss would make a wrong gradient
/// flow while looking fixed. A real implementation needs the alpha/beta dynamic
/// program over the blank-expanded label sequence.
pub fn ctc_loss(
    log_probs: &Tensor,
    targets: &Tensor,
    input_lengths: &Tensor,
    target_lengths: &Tensor,
    _blank: i64,
    reduction: ReductionType,
    zero_infinity: bool,
) -> TorshResult<Tensor> {
    let context = function_context("ctc_loss");

    // Validate input shapes
    if log_probs.ndim() != 3 {
        return Err(TorshError::config_error_with_context(
            "log_probs must be 3D tensor with shape (T, N, C)",
            &context,
        ));
    }

    if targets.ndim() != 2 {
        return Err(TorshError::config_error_with_context(
            "targets must be 2D tensor with shape (N, S)",
            &context,
        ));
    }

    let shape = log_probs.shape();
    let dims = shape.dims();
    let seq_len = dims[0];
    let batch_size = dims[1];
    let num_classes = dims[2];

    // For now, implement a simplified version that assumes:
    // - All sequences use full length
    // - No blank symbol handling (placeholder implementation)
    // A full CTC implementation would require dynamic programming with forward-backward algorithm

    // This is a placeholder implementation - real CTC loss requires:
    // 1. Forward-backward algorithm for probability computation
    // 2. Handling of blank symbols and repetitions
    // 3. Dynamic programming to find all valid alignments
    let mut total_loss = 0.0;

    for batch_idx in 0..batch_size {
        // Get input and target lengths for this batch
        let input_len = input_lengths.get(&[batch_idx])? as usize;
        let target_len = target_lengths.get(&[batch_idx])? as usize;

        if input_len == 0 || target_len == 0 {
            continue;
        }

        // Simple approximation: sum negative log probabilities of target sequence
        // This is NOT the actual CTC loss, just a placeholder
        let mut batch_loss = 0.0;
        for t in 0..input_len.min(seq_len).min(target_len) {
            let target_class = targets.get(&[batch_idx, t])? as usize;
            if target_class < num_classes {
                let log_prob = log_probs.get(&[t, batch_idx, target_class])?;
                batch_loss -= log_prob;
            }
        }

        if zero_infinity && batch_loss.is_infinite() {
            batch_loss = 0.0;
        }

        total_loss += batch_loss;
    }

    let loss_tensor = Tensor::from_vec(vec![total_loss], &[1])?;

    match reduction {
        ReductionType::None => Ok(loss_tensor),
        ReductionType::Mean => Ok(Tensor::from_vec(
            vec![total_loss / batch_size as f32],
            &[1],
        )?),
        ReductionType::Sum => Ok(loss_tensor),
    }
}

/// Sequence-to-Sequence Loss with attention
///
/// Computes loss for sequence-to-sequence models with attention mechanisms.
/// This combines cross-entropy loss with attention regularization.
///
/// # Arguments
/// * `predictions` - Predicted logits with shape (N, T_out, V) where V is vocab size
/// * `targets` - Target sequence with shape (N, T_out)
/// * `attention_weights` - Attention weights with shape (N, T_out, T_in)
/// * `attention_reg` - Regularization weight for attention
/// * `reduction` - Reduction type
pub fn seq2seq_loss_with_attention(
    predictions: &Tensor,
    targets: &Tensor,
    attention_weights: Option<&Tensor>,
    attention_reg: f32,
    reduction: ReductionType,
) -> TorshResult<Tensor> {
    // Cross-entropy loss on predictions
    let ce_loss = compute_sequence_cross_entropy(predictions, targets)?;

    let total_loss = if let Some(attn_weights) = attention_weights {
        // Add attention regularization
        let attn_reg_loss = attention_regularization_loss(attn_weights)?;
        ce_loss.add(&attn_reg_loss.mul_scalar(attention_reg)?)?
    } else {
        ce_loss
    };

    reduction.apply(total_loss)
}

/// Temporal Consistency Loss
///
/// Encourages temporal smoothness in sequence predictions.
/// Useful for video analysis, time series prediction, etc.
///
/// # Arguments
/// * `predictions` - Sequence predictions with shape (N, T, *)
/// * `smoothness_weight` - Weight for smoothness regularization
/// * `reduction` - Reduction type
pub fn temporal_consistency_loss(
    predictions: &Tensor,
    smoothness_weight: f32,
    reduction: ReductionType,
) -> TorshResult<Tensor> {
    if predictions.ndim() < 3 {
        return Err(TorshError::InvalidArgument(
            "predictions must be at least 3D (N, T, ...)".to_string(),
        ));
    }

    let shape = predictions.shape();
    let dims = shape.dims();
    let seq_len = dims[1];

    if seq_len < 2 {
        return Err(TorshError::InvalidArgument(
            "Sequence length must be at least 2".to_string(),
        ));
    }

    // Compute differences between consecutive time steps.
    //
    // `slice(..)?.to_tensor()?` used to be how the two windows were taken; that
    // pair rebuilds a fresh tensor from raw data and records nothing, which left
    // this loss detached from `predictions`. `Tensor::narrow` selects exactly the
    // same elements (verified element-for-element) and records, so the graph
    // survives. `narrow` is (dim, start, length) where `slice` was (dim, start,
    // end), hence the second argument of the second call.
    let pred_t = predictions.narrow(1, 0, seq_len - 1)?; // t=0 to T-2
    let pred_t_plus_1 = predictions.narrow(1, 1, seq_len - 1)?; // t=1 to T-1

    // L2 difference between consecutive predictions
    let diff = pred_t.sub(&pred_t_plus_1)?;
    let smoothness_loss = diff.pow_scalar(2.0)?.mean(None, false)?;

    let total_loss = smoothness_loss.mul_scalar(smoothness_weight)?;
    reduction.apply(total_loss)
}

/// Wasserstein Loss
///
/// Approximates the Wasserstein distance between distributions.
/// Used in Wasserstein GANs and optimal transport problems.
///
/// # Arguments
/// * `real_scores` - Discriminator scores for real samples
/// * `fake_scores` - Discriminator scores for fake samples
/// * `reduction` - Reduction type
pub fn wasserstein_loss(
    real_scores: &Tensor,
    fake_scores: &Tensor,
    reduction: ReductionType,
) -> TorshResult<Tensor> {
    // Wasserstein loss: E[D(real)] - E[D(fake)]
    // We want to maximize this for the discriminator, minimize for generator
    let real_mean = real_scores.mean(None, false)?;
    let fake_mean = fake_scores.mean(None, false)?;
    let wasserstein_distance = real_mean.sub(&fake_mean)?;

    // Return negative for minimization
    let loss = wasserstein_distance.neg()?;
    reduction.apply(loss)
}

/// Gradient Penalty Loss
///
/// Implements gradient penalty for improved training of GANs (WGAN-GP).
///
/// # Arguments
/// * `gradients` - Gradients of discriminator w.r.t. interpolated samples
/// * `penalty_weight` - Weight for gradient penalty
/// * `reduction` - Reduction type
pub fn gradient_penalty_loss(
    gradients: &Tensor,
    penalty_weight: f32,
    reduction: ReductionType,
) -> TorshResult<Tensor> {
    validate_positive(penalty_weight, "penalty_weight", "gradient_penalty_loss")?;

    // Compute L2 norm of gradients.
    //
    // `Tensor::norm` folds the sum of squares in plain Rust and returns a fresh
    // scalar (advanced_ops.rs), so it records nothing and this penalty used to be
    // a detached leaf — a WGAN-GP term that never actually penalised anything.
    // Spelling the same Frobenius norm out of recording ops reproduces the value
    // exactly (measured: 2.0808651 either way) and keeps the graph. The radicand
    // is floored so that an all-zero gradient tensor yields a finite derivative
    // instead of `sqrt'(0) = inf`.
    let grad_norm = gradients
        .pow_scalar(2.0)?
        .sum()?
        .clamp_min(DISTANCE_FLOOR)?
        .sqrt()?;

    // Gradient penalty: (||grad|| - 1)^2
    let penalty = grad_norm.sub_scalar(1.0)?.pow_scalar(2.0)?;
    let weighted_penalty = penalty.mul_scalar(penalty_weight)?;

    reduction.apply(weighted_penalty)
}

// Helper functions

/// Token-averaged negative log-likelihood of `targets` under `predictions`.
///
/// The predecessor accumulated `total_loss` in an `f32` by reading individual
/// entries with [`torsh_tensor::Tensor::get`] and then wrapped the number in a
/// brand-new tensor — an honestly detached leaf, so `seq2seq_loss_with_attention`
/// never propagated a gradient into its logits.
///
/// The gather is now a single differentiable expression: a constant selector
/// holding `-1 / (N * T)` at each `(n, t, target[n, t])` entry turns the whole
/// average into `sum(selector * log_probs)`. This is the same technique
/// `loss/classification.rs`'s [`crate::loss::nll_loss`] uses, and it produces
/// the same number (measured: 2.3025854 and 0.74311393 on the two pinned
/// fixtures) while keeping `predictions` on the graph.
///
/// The `[1]` output shape is the predecessor's and is preserved: under
/// `ReductionType::None` this loss reports `[1]`, not `[]`.
fn compute_sequence_cross_entropy(predictions: &Tensor, targets: &Tensor) -> TorshResult<Tensor> {
    let context = function_context("seq2seq_loss_with_attention");

    if predictions.ndim() != 3 {
        return Err(TorshError::config_error_with_context(
            "predictions must be 3D tensor with shape (N, T_out, V)",
            &context,
        ));
    }
    if targets.ndim() != 2 {
        return Err(TorshError::config_error_with_context(
            "targets must be 2D tensor with shape (N, T_out)",
            &context,
        ));
    }

    let prediction_shape = predictions.shape();
    let prediction_dims = prediction_shape.dims();
    let (batch_size, seq_len, vocab_size) =
        (prediction_dims[0], prediction_dims[1], prediction_dims[2]);

    let target_shape = targets.shape();
    let target_dims = target_shape.dims();
    if target_dims[0] != batch_size || target_dims[1] != seq_len {
        return Err(TorshError::ShapeMismatch {
            expected: vec![batch_size, seq_len],
            got: target_dims.to_vec(),
        });
    }
    if batch_size == 0 || seq_len == 0 {
        return Err(TorshError::config_error_with_context(
            "seq2seq loss needs at least one batch element and one time step",
            &context,
        ));
    }

    // Apply log_softmax to predictions
    let dim = (prediction_dims.len() - 1) as i32;
    let log_probs = predictions.log_softmax(dim)?;

    // Constant selector: -1/(N*T) at the target vocabulary entry of every token,
    // zero everywhere else. Folding the 1/(N*T) average into the selector keeps
    // the whole loss a single tensor expression.
    let scale = -1.0 / (batch_size * seq_len) as f32;
    let mut selector = vec![0.0f32; batch_size * seq_len * vocab_size];
    for i in 0..batch_size {
        for j in 0..seq_len {
            let raw = targets.get(&[i, j])?;
            if !raw.is_finite() || raw.fract() != 0.0 {
                return Err(TorshError::config_error_with_context(
                    &format!("targets[{i}, {j}] = {raw} is not an integral token index"),
                    &context,
                ));
            }
            let token = raw as i64;
            if token < 0 || token as usize >= vocab_size {
                return Err(TorshError::config_error_with_context(
                    &format!(
                        "targets[{i}, {j}] = {token} is out of range for a vocabulary of \
                         {vocab_size} tokens"
                    ),
                    &context,
                ));
            }
            selector[(i * seq_len + j) * vocab_size + token as usize] = scale;
        }
    }
    let selector_tensor = Tensor::from_data(
        selector,
        vec![batch_size, seq_len, vocab_size],
        predictions.device(),
    )?;

    log_probs.mul(&selector_tensor)?.sum()?.view(&[1])
}

fn attention_regularization_loss(attention_weights: &Tensor) -> TorshResult<Tensor> {
    // Encourage attention to be sparse and focused
    // L2 regularization on attention weights
    attention_weights.pow_scalar(2.0)?.mean(None, false)
}

#[cfg(test)]
mod tests {
    use super::*;
    use torsh_core::device::DeviceType;
    use torsh_tensor::creation::{from_vec, zeros};

    #[test]
    fn test_ctc_loss_basic() -> TorshResult<()> {
        // Simple CTC loss test with placeholder implementation
        let log_probs = zeros(&[10, 2, 5])?; // T=10, N=2, C=5
        let targets = from_vec(vec![1.0, 2.0, 3.0, 4.0], &[2, 2], DeviceType::Cpu)?;
        let input_lengths = from_vec(vec![10.0, 10.0], &[2], DeviceType::Cpu)?;
        let target_lengths = from_vec(vec![2.0, 2.0], &[2], DeviceType::Cpu)?;

        let loss = ctc_loss(
            &log_probs,
            &targets,
            &input_lengths,
            &target_lengths,
            0,
            ReductionType::Mean,
            false,
        )?;
        let loss_value = loss.item()?;

        // Loss should be non-negative
        assert!(loss_value >= 0.0);
        Ok(())
    }

    #[test]
    fn test_temporal_consistency_loss_basic() -> TorshResult<()> {
        // Create predictions with some temporal variation
        let predictions = from_vec(
            vec![1.0, 2.0, 3.0, 1.1, 2.1, 3.1, 1.2, 2.2, 3.2], // 3 time steps, 3 features
            &[1, 3, 3],
            DeviceType::Cpu,
        )?;

        let loss = temporal_consistency_loss(&predictions, 1.0, ReductionType::Mean)?;
        let loss_value = loss.item()?;

        // Should be small for smooth predictions
        assert!(loss_value >= 0.0 && loss_value < 1.0);
        Ok(())
    }

    #[test]
    fn test_wasserstein_loss_basic() -> TorshResult<()> {
        let real_scores = from_vec(vec![1.0, 2.0, 1.5], &[3], DeviceType::Cpu)?;
        let fake_scores = from_vec(vec![0.5, 0.8, 0.6], &[3], DeviceType::Cpu)?;

        let loss = wasserstein_loss(&real_scores, &fake_scores, ReductionType::Mean)?;
        let loss_value = loss.item()?;

        // Wasserstein loss can be positive or negative
        assert!(loss_value.is_finite());
        Ok(())
    }

    #[test]
    fn test_gradient_penalty_loss_basic() -> TorshResult<()> {
        let gradients = from_vec(vec![1.5, 0.8, 1.2], &[3], DeviceType::Cpu)?;

        let loss = gradient_penalty_loss(&gradients, 10.0, ReductionType::Mean)?;
        let loss_value = loss.item()?;

        // Gradient penalty should be non-negative
        assert!(loss_value >= 0.0);
        Ok(())
    }

    #[test]
    fn test_seq2seq_loss_basic() -> TorshResult<()> {
        let predictions = zeros(&[2, 5, 10])?; // N=2, T=5, V=10
        let targets = from_vec(
            vec![1.0, 2.0, 3.0, 4.0, 5.0, 0.0, 1.0, 2.0, 3.0, 4.0],
            &[2, 5],
            DeviceType::Cpu,
        )?;

        let loss =
            seq2seq_loss_with_attention(&predictions, &targets, None, 0.0, ReductionType::Mean)?;
        let loss_value = loss.item()?;

        // Loss should be positive for non-perfect predictions
        assert!(loss_value > 0.0);
        Ok(())
    }
}