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
//! Common types and utilities for loss functions
//!
//! This module provides shared types and helper functions used across
//! different loss function categories.
use Result as TorshResult;
use Tensor;
/// Reduction type for loss functions
/// Floor applied to a sum of squares (or of `|d|^p`) before the root that turns
/// it into a distance.
///
/// `sqrt` and `x^(1/p)` have an infinite derivative at zero, so a pair of
/// identical embeddings — an ordinary, indeed *desirable*, input for a
/// metric-learning loss — would back-propagate `inf`. With the constant-mask
/// branch composition of [`blend`] that is worse than it sounds: the branch the
/// mask discards is still *evaluated*, so `0 * inf = NaN` then poisons every
/// sample in the batch, not just the degenerate one.
///
/// Flooring the radicand at `1e-12` moves the distance by at most `1e-6` (four
/// orders below the `1e-5` tolerance the forward-value pins use) and hands the
/// kink a finite subgradient instead. It is applied through
/// [`torsh_tensor::Tensor::clamp_min`], which records `Operation::ClampBounds`
/// and whose backward is zero wherever the clamp bit.
pub const DISTANCE_FLOOR: f32 = 1e-12;
/// Build the detached 0/1 indicator of `predicate` over `source`'s elements,
/// together with its complement.
///
/// This is the branch-selection primitive that replaces
/// [`torsh_tensor::Tensor::where_tensor`]. `where_tensor` rebuilds its result
/// from raw data and records nothing, so every loss that selected a branch with
/// it returned an honestly detached leaf and `backward()` never reached the
/// inputs. Both returned tensors are plain constants — they are built with
/// [`torsh_tensor::Tensor::from_data`] and never carry `requires_grad` — which
/// is exactly right: the branch indicator is piecewise constant, so it has zero
/// derivative wherever it is defined.
///
/// See [`blend`] for how the two masks are recombined.
pub
/// `mask_true * on_true + mask_false * on_false` — the recording replacement for
/// `on_true.where_tensor(&mask, &on_false)`.
///
/// Both branches stay on the autograd graph, and because the masks are
/// complementary constants produced by [`branch_masks`], backward routes each
/// element's gradient to exactly the branch that produced its value and gives
/// the other branch zero. The forward result is element-for-element identical to
/// `where_tensor`'s, provided neither branch holds a non-finite value at a
/// masked-out position — see [`DISTANCE_FLOOR`] for the one place in this crate
/// where that had to be arranged deliberately.
pub