Skip to main content

oa/ml/nn/
pairwise.rs

1//! Pairwise distance and cosine similarity over one axis.
2
3use crate::{Error, Matrix, Result, matrix};
4
5use super::super::{Module, ModuleRegistry};
6
7/// Pairwise p-norm distance (`nn.PairwiseDistance`) over one axis.
8///
9/// Emits `||x1 - x2||_p` keeping the reduced axis at extent one, matching the
10/// donor's `keepdim` shape.
11pub struct PairwiseDistance {
12	p: f32,
13	dim: i32,
14	eps: f32,
15	registry: ModuleRegistry,
16}
17
18impl PairwiseDistance {
19	/// Construct with the donor defaults (`p = 2`, `dim = 1`, `eps = 1e-6`).
20	pub const fn new() -> Self {
21		Self::new_with_options(2.0, 1, 1e-6)
22	}
23
24	/// Construct with explicit `p`, `dim`, and `eps`.
25	pub const fn new_with_options(p: f32, dim: i32, eps: f32) -> Self {
26		Self {
27			p,
28			dim,
29			eps,
30			registry: ModuleRegistry::new(),
31		}
32	}
33
34	/// Compute `(||x1 - x2||_p + eps)` along `dim`.
35	///
36	/// `eps` is added inside the norm for gradient stability at zero, matching
37	/// the donor contract.
38	///
39	/// # Errors
40	///
41	/// Returns an error for mismatched shapes, an out-of-range axis, or a
42	/// composed dispatch failure.
43	pub fn forward2(&self, input1: &Matrix, input2: &Matrix) -> Result<Matrix> {
44		let operation = "PairwiseDistance";
45		if input1.shape() != input2.shape() {
46			return Err(Error::invalid_argument(format!(
47				"{operation} requires matching input shapes; found {:?} and {:?}",
48				input1.shape(),
49				input2.shape()
50			)));
51		}
52		let rank = input1.shape().len();
53		let dim = if self.dim < 0 {
54			self.dim + rank as i32
55		} else {
56			self.dim
57		};
58		if dim < 0 || dim as usize >= rank || !self.p.is_finite() || self.p <= 0.0 {
59			return Err(Error::invalid_argument(format!(
60				"{operation} dim {} is outside rank {rank} or p is invalid",
61				self.dim
62			)));
63		}
64		let difference = matrix::sub(input1, input2)?;
65		let powered = matrix::pow(&matrix::abs(&difference)?, self.p)?;
66		matrix::pow(
67			&matrix::add_scalar(&matrix::sum(&powered, dim)?, self.eps)?,
68			1.0 / self.p,
69		)
70	}
71}
72
73impl Default for PairwiseDistance {
74	fn default() -> Self {
75		Self::new()
76	}
77}
78
79impl Module for PairwiseDistance {
80	fn forward(&self, input: &Matrix) -> Result<Matrix> {
81		let _ = input;
82		Err(Error::invalid_argument(
83			"PairwiseDistance requires two inputs; call forward2(input1, input2)",
84		))
85	}
86
87	fn registry(&self) -> &ModuleRegistry {
88		&self.registry
89	}
90}
91
92/// Cosine similarity (`nn.CosineSimilarity`) over one axis.
93///
94/// Emits `x1 . x2 / (max(||x1||, eps) * max(||x2||, eps))` keeping the reduced
95/// axis at extent one.
96pub struct CosineSimilarity {
97	dim: i32,
98	eps: f32,
99	registry: ModuleRegistry,
100}
101
102impl CosineSimilarity {
103	/// Construct with the donor defaults (`dim = 1`, `eps = 1e-8`).
104	pub const fn new() -> Self {
105		Self::new_with_options(1, 1e-8)
106	}
107
108	/// Construct with explicit `dim` and `eps`.
109	pub const fn new_with_options(dim: i32, eps: f32) -> Self {
110		Self {
111			dim,
112			eps,
113			registry: ModuleRegistry::new(),
114		}
115	}
116
117	/// Compute the cosine similarity of `input1` and `input2` along `dim`.
118	///
119	/// # Errors
120	///
121	/// Returns an error for mismatched shapes, an out-of-range axis, or a
122	/// composed dispatch failure.
123	pub fn forward2(&self, input1: &Matrix, input2: &Matrix) -> Result<Matrix> {
124		let operation = "CosineSimilarity";
125		if input1.shape() != input2.shape() {
126			return Err(Error::invalid_argument(format!(
127				"{operation} requires matching input shapes; found {:?} and {:?}",
128				input1.shape(),
129				input2.shape()
130			)));
131		}
132		let rank = input1.shape().len();
133		let dim = if self.dim < 0 {
134			self.dim + rank as i32
135		} else {
136			self.dim
137		};
138		if dim < 0 || dim as usize >= rank {
139			return Err(Error::invalid_argument(format!(
140				"{operation} dim {} is outside rank {rank}",
141				self.dim
142			)));
143		}
144		let norm = |input: &Matrix| -> Result<Matrix> {
145			matrix::clamp_min(
146				&matrix::sqrt(&matrix::sum(&matrix::mul(input, input)?, dim)?)?,
147				self.eps,
148			)
149		};
150		let numerator = matrix::sum(&matrix::mul(input1, input2)?, dim)?;
151		matrix::div(&numerator, &matrix::mul(&norm(input1)?, &norm(input2)?)?)
152	}
153}
154
155impl Default for CosineSimilarity {
156	fn default() -> Self {
157		Self::new()
158	}
159}
160
161impl Module for CosineSimilarity {
162	fn forward(&self, input: &Matrix) -> Result<Matrix> {
163		let _ = input;
164		Err(Error::invalid_argument(
165			"CosineSimilarity requires two inputs; call forward2(input1, input2)",
166		))
167	}
168
169	fn registry(&self) -> &ModuleRegistry {
170		&self.registry
171	}
172}