torsh_functional/api_patterns.rs
1//! Standardized API patterns and conventions for torsh-functional
2//!
3//! This module documents and demonstrates the standardized API patterns
4//! used throughout the torsh-functional crate to ensure consistency
5//! and usability.
6
7use crate::utils::*;
8use torsh_core::{Result as TorshResult, TorshError};
9use torsh_tensor::Tensor;
10
11/// Standard parameter ordering for functional operations
12///
13/// All functions in torsh-functional follow this parameter ordering convention:
14/// 1. Primary input tensor(s)
15/// 2. Required parameters (sizes, dimensions, etc.)
16/// 3. Optional parameters with defaults
17/// 4. Configuration flags (inplace, etc.)
18///
19/// Example: `conv2d(input, weight, bias, stride, padding, dilation, groups)`
20
21/// Standard documentation template for functions
22///
23/// All functions should include:
24/// - Brief description of what the function does
25/// - Mathematical formula (if applicable)
26/// - Parameter descriptions with types and constraints
27/// - Return value description
28/// - Error conditions
29/// - Usage example
30/// - References to related functions
31
32/// Standard error handling patterns
33///
34/// All functions should:
35/// 1. Create a function context using `function_context()`
36/// 2. Validate inputs using appropriate `validate_*` functions
37/// 3. Use descriptive error messages with context
38/// 4. Chain errors properly with `.map_err()`
39
40/// Example function demonstrating all API conventions
41///
42/// Linear transformation with bias: y = xW^T + b
43///
44/// Formula: linear(x, W, b) = xW^T + b
45///
46/// # Parameters
47/// * `input` - Input tensor of shape (N, *, in_features)
48/// * `weight` - Weight matrix of shape (out_features, in_features)
49/// * `bias` - Optional bias vector of shape (out_features,)
50///
51/// # Returns
52/// Output tensor of shape (N, *, out_features)
53///
54/// # Errors
55/// Returns error if:
56/// - Input tensor is empty
57/// - Weight/bias shapes are incompatible with input
58/// - Matrix multiplication fails
59///
60/// # Example
61/// ```rust,no_run
62/// use torsh_functional::api_patterns::example_linear;
63/// use torsh_functional::random_ops::randn;
64/// let input = randn(&[2, 3], None, None, None).unwrap();
65/// let weight = randn(&[4, 3], None, None, None).unwrap();
66/// let bias = Some(randn(&[4], None, None, None).unwrap());
67/// let output = example_linear(&input, &weight, bias.as_ref()).unwrap();
68/// assert_eq!(output.shape().dims(), &[2, 4]);
69/// ```
70pub fn example_linear(
71 input: &Tensor,
72 weight: &Tensor,
73 bias: Option<&Tensor>,
74) -> TorshResult<Tensor> {
75 let context = function_context("example_linear");
76
77 // 1. Input validation
78 validate_non_empty(input, &context)?;
79 validate_non_empty(weight, &context)?;
80 validate_tensor_dims(weight, 2, &context)?;
81
82 let input_shape_binding = input.shape();
83 let input_shape = input_shape_binding.dims();
84 let weight_shape_binding = weight.shape();
85 let weight_shape = weight_shape_binding.dims();
86 let input_features = input_shape[input_shape.len() - 1];
87 let weight_features = weight_shape[1];
88
89 if input_features != weight_features {
90 return Err(invalid_argument_error(
91 &format!(
92 "Input features ({}) don't match weight features ({})",
93 input_features, weight_features
94 ),
95 &context,
96 ));
97 }
98
99 if let Some(bias_tensor) = bias {
100 validate_non_empty(bias_tensor, &context)?;
101 validate_tensor_dims(bias_tensor, 1, &context)?;
102
103 let bias_shape_binding = bias_tensor.shape();
104 let bias_shape = bias_shape_binding.dims();
105 if bias_shape[0] != weight_shape[0] {
106 return Err(invalid_argument_error(
107 &format!(
108 "Bias size ({}) doesn't match output features ({})",
109 bias_shape[0], weight_shape[0]
110 ),
111 &context,
112 ));
113 }
114 }
115
116 // 2. Core computation with error handling
117 // Linear transformation: y = xW^T + b (weight needs to be transposed)
118 let weight_t = weight.transpose(0, 1).map_err(|e| {
119 TorshError::InvalidOperation(format!("Weight transpose failed: {}", e))
120 .with_context(&context)
121 })?;
122
123 let output = input.matmul(&weight_t).map_err(|e| {
124 TorshError::InvalidOperation(format!("Matrix multiplication failed: {}", e))
125 .with_context(&context)
126 })?;
127
128 // 3. Optional bias addition
129 if let Some(bias_tensor) = bias {
130 output.add(bias_tensor).map_err(|e| {
131 TorshError::InvalidOperation(format!("Bias addition failed: {}", e))
132 .with_context(&context)
133 })
134 } else {
135 Ok(output)
136 }
137}
138
139/// Standard activation function pattern
140///
141/// All activation functions should follow this pattern:
142/// - Generic over tensor element type
143/// - Optional inplace parameter (last position)
144/// - Comprehensive input validation
145/// - Proper error context
146pub fn example_activation<T>(input: &Tensor, alpha: f32, inplace: bool) -> TorshResult<Tensor>
147where
148 T: Copy + PartialOrd + From<f32>,
149{
150 let context = function_context("example_activation");
151
152 // Validate inputs
153 validate_non_empty(input, &context)?;
154 validate_positive(alpha, "alpha", &context)?;
155
156 // Handle inplace operation
157 handle_inplace_operation(
158 input,
159 inplace,
160 |tensor| {
161 // Perform the actual activation computation
162 tensor.relu() // Placeholder implementation
163 },
164 &context,
165 )
166}
167
168/// Standard pooling function pattern
169///
170/// All pooling functions should follow this pattern:
171/// - Kernel size as first required parameter
172/// - Optional stride (defaults to kernel_size)
173/// - Padding as optional parameter
174/// - Dilation for advanced pooling
175pub fn example_pool2d(
176 input: &Tensor,
177 kernel_size: (usize, usize),
178 stride: Option<(usize, usize)>,
179 padding: (usize, usize),
180 _dilation: (usize, usize),
181) -> TorshResult<Tensor> {
182 let context = function_context("example_pool2d");
183
184 // Validate 4D input tensor (N, C, H, W)
185 validate_tensor_dims(input, 4, &context)?;
186
187 // Validate pooling parameters
188 let kernel_slice = [kernel_size.0, kernel_size.1];
189 let stride_slice = stride.unwrap_or(kernel_size);
190 let stride_slice = [stride_slice.0, stride_slice.1];
191 let padding_slice = [padding.0, padding.1];
192
193 validate_pooling_params(
194 input,
195 &kernel_slice,
196 &stride_slice,
197 &padding_slice,
198 &context,
199 )?;
200
201 // Placeholder implementation
202 Ok(input.clone())
203}
204
205/// Standard loss function pattern
206///
207/// All loss functions should follow this pattern:
208/// - Input and target as first parameters
209/// - Reduction type as explicit enum
210/// - Comprehensive shape validation
211pub fn example_loss(
212 input: &Tensor,
213 target: &Tensor,
214 reduction: crate::loss::ReductionType,
215 weight: Option<&Tensor>,
216) -> TorshResult<Tensor> {
217 let context = function_context("example_loss");
218
219 // Validate inputs
220 validate_non_empty(input, &context)?;
221 validate_non_empty(target, &context)?;
222 validate_broadcastable_shapes(input, target, &context)?;
223
224 if let Some(weight_tensor) = weight {
225 validate_non_empty(weight_tensor, &context)?;
226 // Additional weight validation...
227 }
228
229 // Compute loss (placeholder)
230 let loss = input.sub(target)?;
231 reduction.apply(loss)
232}
233
234#[cfg(test)]
235mod tests {
236 use super::*;
237 use torsh_core::device::DeviceType;
238
239 #[test]
240 fn test_example_linear() -> TorshResult<()> {
241 let input = Tensor::from_data(
242 vec![1.0f32, 2.0, 3.0, 4.0, 5.0, 6.0],
243 vec![2, 3],
244 DeviceType::Cpu,
245 )?;
246
247 // Create weight tensor with correct dimensions [out_features, in_features] = [2, 3]
248 let weight = Tensor::from_data(
249 vec![0.1f32, 0.2, 0.3, 0.4, 0.5, 0.6],
250 vec![2, 3], // [out_features, in_features] = [2, 3]
251 DeviceType::Cpu,
252 )?;
253
254 let bias = Tensor::from_data(vec![0.1f32, 0.2], vec![2], DeviceType::Cpu)?;
255
256 let output = example_linear(&input, &weight, Some(&bias))?;
257 assert_eq!(output.shape().dims(), &[2, 2]);
258
259 Ok(())
260 }
261
262 #[test]
263 fn test_validation_patterns() -> TorshResult<()> {
264 // Test empty tensor validation
265 let empty = Tensor::from_data(vec![0.0f32; 0], vec![0], DeviceType::Cpu)?;
266 let valid = Tensor::from_data(vec![1.0f32], vec![1], DeviceType::Cpu)?;
267
268 let result = example_linear(&empty, &valid, None);
269 assert!(result.is_err());
270
271 Ok(())
272 }
273}