oarust 0.20.1

GPU-first semantic computing runtime written in Rust
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
461
462
463
464
//! Composable loss options: per-item vs. reduced objectives, sample/class
//! weights, ignored targets, logit-domain BCE, and multi-term normalization.
//!
//! Every routine composes over differentiable [`crate::matrix`] primitives so
//! reverse-mode gradients flow automatically through the exact same weighted,
//! masked, or unreduced formula without dedicated adjoint shaders.

use crate::{DType, Error, Matrix, Result, matrix};

use super::common::validate_pointwise_loss_inputs;

/// Reduction mode applied to per-item or per-element loss tensors.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum LossReduction {
	/// Return the unreduced per-item (or per-element) loss matrix unchanged.
	None,
	/// Sum all (optionally weighted) loss entries into an FP32 scalar `[]`.
	Sum,
	/// Mean over all entries, or `sum(loss * weight) / sum(weight)` when
	/// sample/class weights or masks are supplied.
	#[default]
	Mean,
}

fn validate_same_shape_weight(
	reference: &Matrix,
	weight: &Matrix,
	label: &str,
	operation: &str,
) -> Result<()> {
	if weight.dtype() != DType::F32 {
		return Err(Error::invalid_argument(format!(
			"{operation} {label} must be F32; found {}",
			weight.dtype().token()
		)));
	}
	if !weight.runtime().same_as(reference.runtime()) {
		return Err(Error::invalid_argument(format!(
			"{operation} {label} must belong to the same runtime"
		)));
	}
	if weight.shape() != reference.shape() {
		return Err(Error::invalid_argument(format!(
			"{operation} {label} shape {:?} must match loss shape {:?}",
			weight.shape(),
			reference.shape()
		)));
	}
	Ok(())
}

/// Apply optional elementwise `sample_weight` and [`LossReduction`] to a
/// per-item or per-element FP32 loss matrix.
///
/// When `sample_weight` is `Some`, its shape must match `per_item`. Under
/// [`LossReduction::Mean`], the weighted mean is `sum(per_item * weight) /
/// sum(weight)` (producing `NaN` if total weight is zero, matching the metric
/// contract).
///
/// # Errors
///
/// Returns an error when `per_item` is empty or non-FP32, `sample_weight` has
/// a mismatched shape, dtype, or runtime, or recording fails.
pub fn reduce_loss(
	per_item: &Matrix,
	sample_weight: Option<&Matrix>,
	reduction: LossReduction,
) -> Result<Matrix> {
	const OPERATION: &str = "reduce_loss";
	if per_item.dtype() != DType::F32 || per_item.num_elements() == 0 {
		return Err(Error::invalid_argument(format!(
			"{OPERATION} requires a nonempty F32 loss matrix; found {} {:?}",
			per_item.dtype().token(),
			per_item.shape()
		)));
	}
	match sample_weight {
		None => match reduction {
			LossReduction::None => Ok(per_item.clone()),
			LossReduction::Sum => matrix::sum(per_item, -1)?.reshape([]),
			LossReduction::Mean => matrix::mean(per_item, -1)?.reshape([]),
		},
		Some(weight) => {
			validate_same_shape_weight(per_item, weight, "sample_weight", OPERATION)?;
			let weighted = matrix::mul(per_item, weight)?;
			match reduction {
				LossReduction::None => Ok(weighted),
				LossReduction::Sum => matrix::sum(&weighted, -1)?.reshape([]),
				LossReduction::Mean => {
					let numerator = matrix::sum(&weighted, -1)?;
					let denominator = matrix::sum(weight, -1)?;
					matrix::div(&numerator, &denominator)?.reshape([])
				}
			}
		}
	}
}

/// Compute squared-error loss `(prediction - target)^2` with optional
/// elementwise `sample_weight` and [`LossReduction`].
///
/// # Errors
///
/// Returns an error for mismatched, empty, non-FP32, or cross-runtime inputs,
/// invalid `sample_weight`, or runtime recording failure.
pub fn mse_with_options(
	prediction: &Matrix,
	target: &Matrix,
	sample_weight: Option<&Matrix>,
	reduction: LossReduction,
) -> Result<Matrix> {
	validate_pointwise_loss_inputs(prediction, target, "mse_with_options")?;
	let diff = matrix::sub(prediction, target)?;
	let per_item = matrix::mul(&diff, &diff)?;
	reduce_loss(&per_item, sample_weight, reduction)
}

/// Compute absolute-error loss `|prediction - target|` with optional
/// elementwise `sample_weight` and [`LossReduction`].
///
/// # Errors
///
/// Returns an error for mismatched, empty, non-FP32, or cross-runtime inputs,
/// invalid `sample_weight`, or runtime recording failure.
pub fn l1_with_options(
	prediction: &Matrix,
	target: &Matrix,
	sample_weight: Option<&Matrix>,
	reduction: LossReduction,
) -> Result<Matrix> {
	validate_pointwise_loss_inputs(prediction, target, "l1_with_options")?;
	let per_item = matrix::abs(&matrix::sub(prediction, target)?)?;
	reduce_loss(&per_item, sample_weight, reduction)
}

/// Compute Huber / smooth-L1 loss with configurable transition threshold `beta`,
/// optional elementwise `sample_weight`, and [`LossReduction`].
///
/// For `d = |prediction - target|`, uses `0.5 * d^2 / beta` when `d < beta` and
/// `d - 0.5 * beta` otherwise (`beta == 1.0` matches [`super::smooth_l1`]).
///
/// # Errors
///
/// Returns an error when `beta` is not finite and positive, inputs are invalid,
/// `sample_weight` does not match, or runtime recording fails.
pub fn smooth_l1_with_options(
	prediction: &Matrix,
	target: &Matrix,
	beta: f32,
	sample_weight: Option<&Matrix>,
	reduction: LossReduction,
) -> Result<Matrix> {
	const OPERATION: &str = "smooth_l1_with_options";
	validate_pointwise_loss_inputs(prediction, target, OPERATION)?;
	if !beta.is_finite() || beta <= 0.0 {
		return Err(Error::invalid_argument(format!(
			"{OPERATION} beta must be positive and finite; found {beta}"
		)));
	}
	let abs_diff = matrix::abs(&matrix::sub(prediction, target)?)?;
	let quad_part = matrix::clamp_max(&abs_diff, beta)?;
	let quadratic = matrix::scale(&matrix::mul(&quad_part, &quad_part)?, 0.5 / beta)?;
	let linear = matrix::sub(&abs_diff, &quad_part)?;
	let per_item = matrix::add(&quadratic, &linear)?;
	reduce_loss(&per_item, sample_weight, reduction)
}

/// Compute probability-domain binary cross-entropy loss with optional
/// elementwise `sample_weight` and [`LossReduction`].
///
/// Predictions are probabilities clamped to `[1e-7, 1 - 1e-7]` matching
/// [`super::bce`]. For unnormalized logits, prefer [`bce_with_logits`] or
/// [`bce_with_logits_with_options`].
///
/// # Errors
///
/// Returns an error for invalid inputs, mismatched `sample_weight`, or runtime
/// recording failure.
pub fn bce_with_options(
	prediction: &Matrix,
	target: &Matrix,
	sample_weight: Option<&Matrix>,
	reduction: LossReduction,
) -> Result<Matrix> {
	const CLAMP_MIN: f32 = 1.0e-7;
	const CLAMP_MAX: f32 = 1.0 - 1.0e-7;
	validate_pointwise_loss_inputs(prediction, target, "bce_with_options")?;
	let clamped = matrix::clamp_max(&matrix::clamp_min(prediction, CLAMP_MIN)?, CLAMP_MAX)?;
	let one_minus_p = matrix::add_scalar(&matrix::neg(&clamped)?, 1.0)?;
	let one_minus_t = matrix::add_scalar(&matrix::neg(target)?, 1.0)?;
	let pos = matrix::mul(target, &matrix::log(&clamped)?)?;
	let neg = matrix::mul(&one_minus_t, &matrix::log(&one_minus_p)?)?;
	let per_item = matrix::neg(&matrix::add(&pos, &neg)?)?;
	reduce_loss(&per_item, sample_weight, reduction)
}

/// Compute numerically stable mean binary cross-entropy directly from
/// unnormalized `logits` and `[0, 1]` targets.
///
/// Uses the softplus form `max(x, 0) - x * y + log(1 + exp(-|x|))`, avoiding
/// probability clamping and overflow on large-magnitude logits.
///
/// # Errors
///
/// Returns an error for mismatched, empty, non-FP32, or cross-runtime inputs,
/// or when runtime recording fails.
pub fn bce_with_logits(logits: &Matrix, target: &Matrix) -> Result<Matrix> {
	bce_with_logits_with_options(logits, target, None, None, LossReduction::Mean)
}

/// Compute numerically stable binary cross-entropy directly from unnormalized
/// `logits`, with optional `sample_weight`, broadcastable positive-class
/// `pos_weight`, and [`LossReduction`].
///
/// When `pos_weight` is supplied (an FP32 tensor broadcastable to `logits`, such
/// as `[1]` or `[C]`), positive terms scale by `pos_weight` matching PyTorch's
/// `(1 - y) * x + (1 + (pos_weight - 1) * y) * (log(1 + exp(-|x|)) + max(-x, 0))`.
///
/// # Errors
///
/// Returns an error for mismatched, empty, non-FP32, or cross-runtime inputs,
/// invalid weights, or runtime recording failure.
pub fn bce_with_logits_with_options(
	logits: &Matrix,
	target: &Matrix,
	sample_weight: Option<&Matrix>,
	pos_weight: Option<&Matrix>,
	reduction: LossReduction,
) -> Result<Matrix> {
	const OPERATION: &str = "bce_with_logits_with_options";
	validate_pointwise_loss_inputs(logits, target, OPERATION)?;
	let log1p_exp_neg_abs = matrix::log(&matrix::add_scalar(
		&matrix::exp(&matrix::neg(&matrix::abs(logits)?)?)?,
		1.0,
	)?)?;
	let per_item = match pos_weight {
		None => matrix::add(
			&matrix::sub(
				&matrix::clamp_min(logits, 0.0)?,
				&matrix::mul(logits, target)?,
			)?,
			&log1p_exp_neg_abs,
		)?,
		Some(pw) => {
			if pw.dtype() != DType::F32 || pw.num_elements() == 0 {
				return Err(Error::invalid_argument(format!(
					"{OPERATION} pos_weight must be nonempty F32; found {} {:?}",
					pw.dtype().token(),
					pw.shape()
				)));
			}
			if !pw.runtime().same_as(logits.runtime()) {
				return Err(Error::invalid_argument(format!(
					"{OPERATION} pos_weight must belong to the same runtime"
				)));
			}
			let one_minus_y = matrix::add_scalar(&matrix::neg(target)?, 1.0)?;
			let log_weight =
				matrix::add_scalar(&matrix::mul(&matrix::sub_scalar(pw, 1.0)?, target)?, 1.0)?;
			let max_neg_x = matrix::clamp_min(&matrix::neg(logits)?, 0.0)?;
			let stable_log = matrix::add(&log1p_exp_neg_abs, &max_neg_x)?;
			matrix::add(
				&matrix::mul(&one_minus_y, logits)?,
				&matrix::mul(&log_weight, &stable_log)?,
			)?
		}
	};
	reduce_loss(&per_item, sample_weight, reduction)
}

/// Compute cross-entropy over `[N, C]` FP32 `logits` and `[N]` integer
/// (`U8`, `U32`, or `I32`) `targets`, with optional per-class weights `[C]`,
/// per-sample weights `[N]`, `ignore_index`, and [`LossReduction`].
///
/// Rows whose target equals `ignore_index` contribute exact zero to both loss
/// and logits gradients and are excluded from the mean denominator. When
/// `class_weight` and/or `sample_weight` are provided, effective per-row weight
/// is `valid_mask * class_weight[target_i] * sample_weight[i]`, and
/// [`LossReduction::Mean`] divides by `sum(effective_weight)`, matching PyTorch
/// `F.cross_entropy`.
///
/// # Errors
///
/// Returns an error for invalid ranks, shapes, dtypes, cross-runtime tensors,
/// out-of-range non-ignored targets, or runtime recording failures.
pub fn cross_entropy_with_options(
	logits: &Matrix,
	targets: &Matrix,
	class_weight: Option<&Matrix>,
	sample_weight: Option<&Matrix>,
	ignore_index: Option<i32>,
	reduction: LossReduction,
) -> Result<Matrix> {
	const OPERATION: &str = "cross_entropy_with_options";
	let &[rows, classes] = logits.shape() else {
		return Err(Error::invalid_argument(format!(
			"{OPERATION} requires rank-two [N, C] logits; found {:?}",
			logits.shape()
		)));
	};
	if rows == 0 || classes == 0 || logits.dtype() != DType::F32 {
		return Err(Error::invalid_argument(format!(
			"{OPERATION} requires nonempty F32 [N, C] logits; found {} {:?}",
			logits.dtype().token(),
			logits.shape()
		)));
	}
	if targets.shape() != [rows]
		|| !matches!(targets.dtype(), DType::U8 | DType::U32 | DType::I32)
		|| !logits.runtime().same_as(targets.runtime())
	{
		return Err(Error::invalid_argument(format!(
			"{OPERATION} requires same-runtime [N] U8/U32/I32 targets; found {} {:?}",
			targets.dtype().token(),
			targets.shape()
		)));
	}
	if let Some(cw) = class_weight
		&& (cw.dtype() != DType::F32
			|| cw.shape() != [classes]
			|| !cw.runtime().same_as(logits.runtime()))
	{
		return Err(Error::invalid_argument(format!(
			"{OPERATION} class_weight must be same-runtime F32 [{classes}]; found {} {:?}",
			cw.dtype().token(),
			cw.shape()
		)));
	}
	if let Some(sw) = sample_weight
		&& (sw.dtype() != DType::F32 || sw.shape() != [rows] || !sw.runtime().same_as(logits.runtime()))
	{
		return Err(Error::invalid_argument(format!(
			"{OPERATION} sample_weight must be same-runtime F32 [{rows}]; found {} {:?}",
			sw.dtype().token(),
			sw.shape()
		)));
	}

	let runtime = logits.runtime();
	// Prepare safe I32 gather indices [N, 1] and optional validity mask [N].
	// When targets are already I32 with no ignore_index, avoid host readback.
	let (safe_indices_2d, safe_indices_1d, valid_mask): (Matrix, Matrix, Option<Matrix>) =
		if targets.dtype() == DType::I32 && ignore_index.is_none() {
			(targets.reshape([rows, 1])?, targets.clone(), None)
		} else {
			let raw: Vec<i64> = match targets.dtype() {
				DType::U8 => targets.read::<u8>()?.into_iter().map(i64::from).collect(),
				DType::U32 => targets.read::<u32>()?.into_iter().map(i64::from).collect(),
				DType::I32 => targets.read::<i32>()?.into_iter().map(i64::from).collect(),
				_ => unreachable!("target dtype validated above"),
			};
			let classes_i64 = classes as i64;
			let ignore_i64 = ignore_index.map(i64::from);
			let mut safe = Vec::with_capacity(rows);
			let mut mask = Vec::with_capacity(rows);
			let mut any_ignored = false;
			for (row, label) in raw.into_iter().enumerate() {
				if ignore_i64 == Some(label) {
					safe.push(0_i32);
					mask.push(0.0_f32);
					any_ignored = true;
				} else if (0..classes_i64).contains(&label) {
					safe.push(label as i32);
					mask.push(1.0_f32);
				} else {
					return Err(Error::invalid_argument(format!(
						"{OPERATION} target {label} at row {row} is outside 0..{classes}"
					)));
				}
			}
			let idx_1d = Matrix::new_from_slice_handle(runtime, vec![rows], &safe)?;
			let idx_2d = idx_1d.reshape([rows, 1])?;
			let mask_mat = if any_ignored {
				Some(Matrix::new_from_slice_handle(runtime, vec![rows], &mask)?)
			} else {
				None
			};
			(idx_2d, idx_1d, mask_mat)
		};

	let log_probs = matrix::log_softmax(logits, 1)?;
	let nll =
		matrix::neg(&matrix::gather_last_dim(&log_probs, &safe_indices_2d)?)?.reshape([rows])?;

	// Compose effective per-row weight: class_weight[y_i] * valid_mask[i] * sample_weight[i].
	let mut effective_weight: Option<Matrix> = None;
	if let Some(cw) = class_weight {
		let gathered = matrix::gather(&cw.reshape([classes, 1])?, &safe_indices_1d)?.reshape([rows])?;
		effective_weight = Some(gathered);
	}
	if let Some(mask) = valid_mask {
		effective_weight = Some(match effective_weight {
			Some(prev) => matrix::mul(&prev, &mask)?,
			None => mask,
		});
	}
	if let Some(sw) = sample_weight {
		effective_weight = Some(match effective_weight {
			Some(prev) => matrix::mul(&prev, sw)?,
			None => sw.clone(),
		});
	}

	reduce_loss(&nll, effective_weight.as_ref(), reduction)
}

/// Combine multiple FP32 scalar loss terms with explicit non-negative weights.
///
/// When `normalize` is `true`, weights are normalized by their sum so
/// `sum((w_i / sum_j w_j) * L_i)` stays invariant to uniform weight rescaling
/// (and requires `sum(w_i) > 0`). When `normalize` is `false`, returns
/// `sum(w_i * L_i)`.
///
/// # Errors
///
/// Returns an error when `terms` is empty, any term is not a same-runtime FP32
/// scalar, any weight is negative or non-finite, `normalize` is `true` with
/// zero total weight, or recording fails.
pub fn combine_losses(terms: &[(&Matrix, f32)], normalize: bool) -> Result<Matrix> {
	const OPERATION: &str = "combine_losses";
	if terms.is_empty() {
		return Err(Error::invalid_argument(format!(
			"{OPERATION} requires at least one (loss, weight) term"
		)));
	}
	let runtime = terms[0].0.runtime();
	let mut total_weight = 0.0_f64;
	for (index, (loss, weight)) in terms.iter().enumerate() {
		if !loss.shape().is_empty() || loss.dtype() != DType::F32 {
			return Err(Error::invalid_argument(format!(
				"{OPERATION} term {index} must be an F32 scalar; found {} {:?}",
				loss.dtype().token(),
				loss.shape()
			)));
		}
		if !loss.runtime().same_as(runtime) {
			return Err(Error::invalid_argument(format!(
				"{OPERATION} term {index} must belong to the same runtime"
			)));
		}
		if !weight.is_finite() || *weight < 0.0 {
			return Err(Error::invalid_argument(format!(
				"{OPERATION} term {index} weight must be finite and non-negative; found {weight}"
			)));
		}
		total_weight += f64::from(*weight);
	}
	if normalize && total_weight <= 0.0 {
		return Err(Error::invalid_argument(format!(
			"{OPERATION} with normalize=true requires a positive weight sum"
		)));
	}
	let denom = if normalize { total_weight } else { 1.0 };
	let mut acc: Option<Matrix> = None;
	for (loss, weight) in terms {
		let factor = (f64::from(*weight) / denom) as f32;
		let scaled = matrix::scale(loss, factor)?;
		acc = Some(match acc {
			Some(prev) => matrix::add(&prev, &scaled)?,
			None => scaled,
		});
	}
	acc.ok_or_else(|| Error::internal("combine_losses nonempty guard failed"))
}