torsh-functional
Functional operations for ToRSh tensors, providing PyTorch-compatible functional API.
Overview
This crate provides a comprehensive set of functional operations that work on tensors:
- Mathematical Operations: Element-wise, reduction, and special functions
- Neural Network Functions: Activations, normalization, loss functions
- Linear Algebra: Matrix operations, decompositions, solvers
- Signal Processing: FFT, convolution, filtering
- Image Operations: Transforms, filters, augmentations
Note: This crate integrates with various scirs2 modules (scirs2-linalg, scirs2-special, scirs2-signal, scirs2-fft) for optimized implementations.
Usage
Mathematical Operations
use torsh_functional as F;
use *;
// Element-wise arithmetic is provided by Tensor methods, not torsh_functional
let a = tensor!;
let b = tensor!;
let sum = a.add_op?;
let product = a.mul_op?;
let power = pow?;
// Trigonometric functions
let angles = tensor!;
let sines = sin?;
let cosines = cos?;
// Reductions
let sum_all = sum?;
let mean = mean?;
let std = std?; // unbiased
let = max_dim?; // dim, keepdim -> (values, indices)
Neural Network Functions
// Activation functions
let x = randn;
let relu = relu?;
let sigmoid = sigmoid?;
let tanh = tanh?;
let gelu = gelu?;
let swish = silu?;
// Softmax with temperature
let logits = randn;
let probs = softmax?;
let log_probs = log_softmax?;
// Normalization
let normalized = layer_norm?;
let batch_normed = batch_norm?;
// Dropout
let dropped = dropout?; // training mode
Loss Functions
use ReductionType;
// Classification losses (cross_entropy/nll_loss still take a &str reduction;
// note the current nll_loss implementation only supports weight=None, ignore_index=None)
let logits = model.forward?;
let targets = tensor!;
let ce_loss = cross_entropy?; // label_smoothing = 0.0
let nll = nll_loss?;
// Regression losses take a `ReductionType` enum, not a string
let predictions = model.forward?;
let targets = randn;
let mse = mse_loss?;
let mae = l1_loss?;
let huber = smooth_l1_loss?; // beta = 1.0
// Binary classification
let binary_logits = model.forward?;
let binary_targets = rand?;
let bce = binary_cross_entropy_with_logits?;
Convolution and Pooling
// 2D Convolution (stride/padding/dilation are (usize, usize) tuples, not slices)
let input = randn; // NCHW
let weight = randn;
let bias = randn;
let output = conv2d?;
// Pooling operations (max_pool2d returns (values, Option<indices>))
let = max_pool2d?; // kernel, stride, padding, dilation, ceil_mode, return_indices
let avg_pooled = avg_pool2d?; // kernel, stride, padding, ceil_mode, count_include_pad, divisor_override
let adaptive = adaptive_avg_pool2d?; // global pooling
Linear Algebra
// Matrix operations (leveraging scirs2-linalg)
let a = randn;
let b = randn;
let c = matmul?;
let det = det?;
let inv = inv?;
// Eigenvalues and eigenvectors
let = eig?;
// SVD
let = svd?;
// Solve linear systems
let x = solve?; // Solve Ax = b
Signal Processing
// FFT operations (leveraging scirs2-signal)
let signal = randn;
let spectrum = fft?;
let reconstructed = ifft?;
// 2D FFT for images
let image = randn;
let freq_domain = fft2?;
Advanced Operations
// Note: there are two distinct `InterpolationMode` enums in this crate.
// `torsh_functional::InterpolationMode` (re-exported from `image`) has
// Nearest/Bilinear/Bicubic/Area. interp2d/grid_sample instead take
// `torsh_functional::interpolation::InterpolationMode` (Linear/Nearest/Cubic/Spline) -
// import it explicitly to get the right type.
use InterpolationMode;
// Coordinate-based 2D interpolation (there is no PyTorch-style size-based
// F::interpolate/affine_grid; interp2d resamples at explicit coordinates)
let sampled_at_coords = interp2d?;
// Grid sampling (align_corners is a plain bool, not Option<bool>)
let grid = randn; // [N, H_out, W_out, 2]
let sampled = grid_sample?;
Utilities
use PaddingMode;
// Tensor manipulation (reshape is in torsh_functional; permute is a Tensor method)
let reshaped = reshape?;
let permuted = tensor.permute?;
// Padding (mode is a PaddingMode enum, value is a plain f32)
let padded = pad?;
// Concatenation and stacking (stack is a Tensor::stack associated function, not F::)
let tensors = vec!;
let concatenated = cat?;
let stacked = stack?;
// Splitting
let chunks = chunk?;
let splits = split?;
Integration with SciRS2
This crate leverages multiple scirs2 modules for optimized implementations:
- scirs2-linalg: For linear algebra operations (matrix multiplication, decompositions)
- scirs2-special: For special mathematical functions (bessel, gamma, etc.)
- scirs2-signal: For signal processing operations
- scirs2-fft: For Fast Fourier Transform operations
- scirs2-core: For SIMD operations and memory management
- scirs2-neural: For neural network specific operations
License
Licensed under the Apache License, Version 2.0. See LICENSE for details.