xybrid-core 0.1.0

Core runtime for hybrid cloud-edge AI inference: model execution, pipeline orchestration, and routing primitives.
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
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
//! Tensor operation postprocessing.
//!
//! This module provides:
//! - `argmax_step`: Get class ID with highest probability
//! - `softmax_step`: Apply softmax normalization
//! - `topk_step`: Get top-K predictions
//! - `threshold_step`: Apply threshold to probabilities
//! - `meanpool_step`: Mean pooling over sequence dimension
//! - `denormalize_step`: Denormalize tensor values (inverse of Normalize preprocessing)

use super::super::types::{ExecutorResult, RawOutputs};
use crate::runtime_adapter::AdapterError;
use ndarray::{ArrayD, IxDyn};
use std::collections::HashMap;

/// Apply argmax to get class ID with highest probability.
///
/// # Arguments
/// - `data`: Input data (TensorMap)
/// - `dim`: Dimension to apply argmax (ignored, uses last dimension)
pub fn argmax_step(data: RawOutputs, _dim: Option<usize>) -> ExecutorResult<RawOutputs> {
    let tensor_map = match data {
        RawOutputs::TensorMap(map) => map,
        _ => {
            return Err(AdapterError::InvalidInput(
                "Argmax requires tensor map".to_string(),
            ))
        }
    };

    // Get the first output tensor
    let tensor = tensor_map
        .values()
        .next()
        .ok_or_else(|| AdapterError::InvalidInput("No outputs to apply argmax".to_string()))?;

    let class_id = argmax_token(tensor)?;

    Ok(RawOutputs::ClassId(class_id))
}

/// Apply softmax normalization to tensor outputs.
///
/// # Arguments
/// - `data`: Input data (TensorMap)
/// - `dim`: Dimension to apply softmax (default: last dimension)
pub fn softmax_step(data: RawOutputs, dim: Option<usize>) -> ExecutorResult<RawOutputs> {
    let mut tensor_map = match data {
        RawOutputs::TensorMap(map) => map,
        _ => {
            return Err(AdapterError::InvalidInput(
                "Softmax requires tensor map".to_string(),
            ))
        }
    };

    // Apply softmax to each tensor in the map
    for (_name, tensor) in tensor_map.iter_mut() {
        apply_softmax(tensor, dim)?;
    }

    Ok(RawOutputs::TensorMap(tensor_map))
}

/// Get top-K predictions with scores.
///
/// # Arguments
/// - `data`: Input data (TensorMap)
/// - `k`: Number of top predictions to return
/// - `dim`: Dimension to apply topk (default: last dimension)
pub fn topk_step(data: RawOutputs, k: usize, dim: Option<usize>) -> ExecutorResult<RawOutputs> {
    let tensor_map = match data {
        RawOutputs::TensorMap(map) => map,
        _ => {
            return Err(AdapterError::InvalidInput(
                "TopK requires tensor map".to_string(),
            ))
        }
    };

    // Get the first output tensor
    let tensor = tensor_map
        .values()
        .next()
        .ok_or_else(|| AdapterError::InvalidInput("No outputs for TopK".to_string()))?;

    // Apply top-k
    let top_k_results = top_k_predictions(tensor, k, dim)?;

    // Return as tensor map with flattened [index1, score1, index2, score2, ...]
    let mut flattened = Vec::with_capacity(k * 2);
    for (idx, score) in top_k_results {
        flattened.push(idx as f32);
        flattened.push(score);
    }

    // Create a 1D tensor from the flattened results
    let topk_tensor = ArrayD::from_shape_vec(IxDyn(&[k * 2]), flattened).map_err(|e| {
        AdapterError::InvalidInput(format!("Failed to create TopK tensor: {:?}", e))
    })?;

    let mut result_map = HashMap::new();
    result_map.insert("topk".to_string(), topk_tensor);

    Ok(RawOutputs::TensorMap(result_map))
}

/// Apply threshold to convert probabilities to binary predictions.
///
/// # Arguments
/// - `data`: Input data (TensorMap)
/// - `threshold`: Probability threshold
/// - `return_indices`: If true, return indices where value > threshold; otherwise return binary mask
pub fn threshold_step(
    data: RawOutputs,
    threshold: f32,
    return_indices: bool,
) -> ExecutorResult<RawOutputs> {
    let tensor_map = match data {
        RawOutputs::TensorMap(map) => map,
        _ => {
            return Err(AdapterError::InvalidInput(
                "Threshold requires tensor map".to_string(),
            ))
        }
    };

    // Get the first output tensor
    let tensor = tensor_map
        .values()
        .next()
        .ok_or_else(|| AdapterError::InvalidInput("No outputs for Threshold".to_string()))?;

    let values = tensor.as_slice().ok_or_else(|| {
        AdapterError::InvalidInput("Tensor is not contiguous for Threshold".to_string())
    })?;

    if return_indices {
        // Return indices where value > threshold
        let indices: Vec<f32> = values
            .iter()
            .enumerate()
            .filter_map(|(idx, &val)| {
                if val > threshold {
                    Some(idx as f32)
                } else {
                    None
                }
            })
            .collect();

        let result_tensor =
            ArrayD::from_shape_vec(IxDyn(&[indices.len()]), indices).map_err(|e| {
                AdapterError::InvalidInput(format!("Failed to create threshold tensor: {:?}", e))
            })?;

        let mut result_map = HashMap::new();
        result_map.insert("threshold_indices".to_string(), result_tensor);
        Ok(RawOutputs::TensorMap(result_map))
    } else {
        // Return binary mask (0 or 1)
        let binary: Vec<f32> = values
            .iter()
            .map(|&val| if val > threshold { 1.0 } else { 0.0 })
            .collect();

        let result_tensor = ArrayD::from_shape_vec(IxDyn(tensor.shape()), binary).map_err(|e| {
            AdapterError::InvalidInput(format!("Failed to create threshold mask: {:?}", e))
        })?;

        let mut result_map = HashMap::new();
        result_map.insert("threshold_mask".to_string(), result_tensor);
        Ok(RawOutputs::TensorMap(result_map))
    }
}

/// Apply mean pooling over token embeddings.
///
/// # Arguments
/// - `data`: Input data (TensorMap with 3D tensor [batch, seq_len, hidden_size])
/// - `dim`: Dimension to pool over (must be 1 for sequence dimension)
pub fn meanpool_step(data: RawOutputs, dim: usize) -> ExecutorResult<RawOutputs> {
    let tensor_map = match data {
        RawOutputs::TensorMap(map) => map,
        _ => {
            return Err(AdapterError::InvalidInput(
                "MeanPool requires tensor map".to_string(),
            ))
        }
    };

    // Get the first output tensor (usually "last_hidden_state" or similar)
    let tensor = tensor_map
        .values()
        .next()
        .ok_or_else(|| AdapterError::InvalidInput("No outputs for MeanPool".to_string()))?;

    let shape = tensor.shape();

    // Expected shape: [batch, sequence_length, hidden_size]
    if shape.len() != 3 {
        return Err(AdapterError::InvalidInput(format!(
            "MeanPool expects 3D tensor [batch, seq_len, hidden_size], got {:?}",
            shape
        )));
    }

    let batch_size = shape[0];
    let seq_len = shape[1];
    let hidden_size = shape[2];

    // Pool over the sequence dimension (dim=1 by default)
    if dim != 1 {
        return Err(AdapterError::InvalidInput(format!(
            "MeanPool only supports pooling over dim=1 (sequence), got dim={}",
            dim
        )));
    }

    // Create output tensor [batch, hidden_size]
    let mut pooled = ArrayD::<f32>::zeros(IxDyn(&[batch_size, hidden_size]));

    // Compute mean over sequence length for each batch and hidden dimension
    for b in 0..batch_size {
        for h in 0..hidden_size {
            let mut sum = 0.0;
            for s in 0..seq_len {
                sum += tensor[IxDyn(&[b, s, h])];
            }
            pooled[IxDyn(&[b, h])] = sum / (seq_len as f32);
        }
    }

    // Return pooled embedding
    let mut result_map = HashMap::new();
    result_map.insert("sentence_embedding".to_string(), pooled);

    Ok(RawOutputs::TensorMap(result_map))
}

/// Denormalize tensor values (inverse of Normalize preprocessing).
///
/// Applies `output = (input * std) + mean` element-wise, cycling through
/// `mean`/`std` by flat index modulo their length. A length-1 slice broadcasts
/// the single value across all elements; a longer slice applies per-channel.
///
/// # Arguments
/// - `data`: Input data (TensorMap)
/// - `mean`: Per-channel mean values used during normalization
/// - `std`: Per-channel standard deviation values used during normalization
///
/// # Errors
/// Returns an error if `mean` and `std` have different lengths, if either is
/// empty, or if the input is not a TensorMap.
pub fn denormalize_step(data: RawOutputs, mean: &[f32], std: &[f32]) -> ExecutorResult<RawOutputs> {
    if mean.len() != std.len() {
        return Err(AdapterError::InvalidInput(format!(
            "Denormalize mean length ({}) must match std length ({})",
            mean.len(),
            std.len()
        )));
    }
    if mean.is_empty() {
        return Err(AdapterError::InvalidInput(
            "Denormalize requires at least one mean/std value".to_string(),
        ));
    }

    let mut tensor_map = match data {
        RawOutputs::TensorMap(map) => map,
        _ => {
            return Err(AdapterError::InvalidInput(
                "Denormalize requires tensor map input".to_string(),
            ))
        }
    };

    for (name, tensor) in tensor_map.iter_mut() {
        let tensor_slice = tensor.as_slice_mut().ok_or_else(|| {
            AdapterError::InvalidInput(format!(
                "Denormalize requires a contiguous tensor (output \"{}\" is non-contiguous)",
                name
            ))
        })?;

        for (i, val) in tensor_slice.iter_mut().enumerate() {
            let channel = i % mean.len();
            *val = (*val * std[channel]) + mean[channel];
        }
    }

    Ok(RawOutputs::TensorMap(tensor_map))
}

// ============================================================================
// Helper functions
// ============================================================================

/// Apply argmax to logits to get token ID.
pub fn argmax_token(logits: &ArrayD<f32>) -> ExecutorResult<usize> {
    let shape = logits.shape();
    let data = logits
        .as_slice()
        .ok_or_else(|| AdapterError::InvalidInput("Logits tensor is not contiguous".to_string()))?;

    // Handle 3D logits [batch, seq_len, vocab_size]
    if shape.len() == 3 {
        let vocab_size = shape[2];
        let start_idx = 0; // First batch, first position
        let end_idx = start_idx + vocab_size;

        let slice = &data[start_idx..end_idx];
        let max_idx = slice
            .iter()
            .enumerate()
            .max_by(|(_, a), (_, b)| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal))
            .map(|(idx, _)| idx)
            .unwrap_or(0);

        Ok(max_idx)
    } else if shape.len() == 2 {
        // 2D logits [batch, vocab_size]
        let vocab_size = shape[1];
        let slice = &data[0..vocab_size];
        let max_idx = slice
            .iter()
            .enumerate()
            .max_by(|(_, a), (_, b)| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal))
            .map(|(idx, _)| idx)
            .unwrap_or(0);

        Ok(max_idx)
    } else if shape.len() == 1 {
        // 1D logits [vocab_size]
        let max_idx = data
            .iter()
            .enumerate()
            .max_by(|(_, a), (_, b)| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal))
            .map(|(idx, _)| idx)
            .unwrap_or(0);

        Ok(max_idx)
    } else {
        Err(AdapterError::InvalidInput(format!(
            "Unexpected logits shape: {:?}",
            shape
        )))
    }
}

/// Apply softmax to a tensor along a dimension.
fn apply_softmax(tensor: &mut ArrayD<f32>, dim: Option<usize>) -> ExecutorResult<()> {
    let shape = tensor.shape().to_vec(); // Clone shape to avoid borrow conflicts

    // Default to last dimension if not specified
    let dim = dim.unwrap_or(shape.len() - 1);

    if dim >= shape.len() {
        return Err(AdapterError::InvalidInput(format!(
            "Softmax dimension {} out of bounds for tensor with {} dimensions",
            dim,
            shape.len()
        )));
    }

    // For simplicity, only handle the common case of 2D tensors (batch, classes)
    // or 1D tensors (classes)
    if let Some(slice) = tensor.as_slice_mut() {
        if shape.len() == 1 {
            // 1D tensor: apply softmax directly
            softmax_1d(slice);
        } else if shape.len() == 2 && dim == 1 {
            // 2D tensor: apply softmax along last dimension
            let batch_size = shape[0];
            let class_size = shape[1];

            for batch in 0..batch_size {
                let start = batch * class_size;
                let end = start + class_size;
                softmax_1d(&mut slice[start..end]);
            }
        } else {
            return Err(AdapterError::InvalidInput(format!(
                "Softmax only supports 1D or 2D tensors, got shape {:?}",
                shape
            )));
        }
    } else {
        return Err(AdapterError::InvalidInput(
            "Tensor is not contiguous, cannot apply softmax".to_string(),
        ));
    }

    Ok(())
}

/// Apply softmax to a 1D slice.
fn softmax_1d(slice: &mut [f32]) {
    // Find max for numerical stability
    let max = slice.iter().cloned().fold(f32::NEG_INFINITY, f32::max);

    // Compute exp(x - max) and sum
    let mut sum = 0.0;
    for val in slice.iter_mut() {
        *val = (*val - max).exp();
        sum += *val;
    }

    // Normalize
    for val in slice.iter_mut() {
        *val /= sum;
    }
}

/// Get top-K predictions from a tensor.
/// Returns Vec of (class_index, score) tuples.
fn top_k_predictions(
    tensor: &ArrayD<f32>,
    k: usize,
    dim: Option<usize>,
) -> ExecutorResult<Vec<(usize, f32)>> {
    let shape = tensor.shape();

    // Default to last dimension
    let _dim = dim.unwrap_or(shape.len() - 1);

    // Get values as slice
    let values = tensor.as_slice().ok_or_else(|| {
        AdapterError::InvalidInput("Tensor is not contiguous for TopK".to_string())
    })?;

    // For simplicity, handle the common case: 1D (classes) or 2D (batch=1, classes)
    let class_scores: &[f32] = if shape.len() == 1 {
        values
    } else if shape.len() == 2 && shape[0] == 1 {
        // Batch size 1, get the first batch
        &values[0..shape[1]]
    } else {
        return Err(AdapterError::InvalidInput(format!(
            "TopK only supports 1D or 2D (batch=1) tensors, got shape {:?}",
            shape
        )));
    };

    // Create (index, score) pairs and sort by score descending
    let mut indexed_scores: Vec<(usize, f32)> = class_scores
        .iter()
        .enumerate()
        .map(|(idx, &score)| (idx, score))
        .collect();

    indexed_scores.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap_or(std::cmp::Ordering::Equal));

    // Take top K
    let top_k: Vec<(usize, f32)> = indexed_scores.into_iter().take(k).collect();

    Ok(top_k)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::execution::preprocessing::tensor::normalize_step;
    use crate::execution::types::PreprocessedData;

    #[test]
    fn test_denormalize_step_round_trip() {
        let original = vec![1.0f32, 2.0, 3.0, 4.0];
        let mean = vec![2.5f32];
        let std_vals = vec![1.0f32];

        let orig_tensor =
            ArrayD::from_shape_vec(IxDyn(&[4]), original.clone()).expect("valid shape");
        let norm_data =
            normalize_step(PreprocessedData::Tensor(orig_tensor), &mean, &std_vals).unwrap();

        let norm_tensor = match norm_data {
            PreprocessedData::Tensor(t) => t,
            _ => panic!("Expected Tensor"),
        };

        let mut map = HashMap::new();
        map.insert("output".to_string(), norm_tensor);

        let result = denormalize_step(RawOutputs::TensorMap(map), &mean, &std_vals).unwrap();

        match result {
            RawOutputs::TensorMap(out_map) => {
                let out = out_map.values().next().unwrap();
                for (actual, expected) in out.iter().zip(original.iter()) {
                    assert!(
                        (actual - expected).abs() < 1e-5,
                        "round-trip failed: expected {}, got {}",
                        expected,
                        actual
                    );
                }
            }
            _ => panic!("Expected TensorMap output"),
        }
    }

    #[test]
    fn test_denormalize_step_per_channel() {
        // Flat slice with 3-element cycling: indices 0,1,2 use channels 0,1,2; then repeat.
        // Pre-normalized values: (-1 * std[c]) + mean[c] should recover the original.
        let mean = vec![1.0f32, 2.0, 3.0];
        let std_vals = vec![1.0f32, 1.0, 1.0];

        // Normalized values corresponding to original [0,1,2,3,4,5]:
        // (0-1)/1=-1, (1-2)/1=-1, (2-3)/1=-1, (3-1)/1=2, (4-2)/1=2, (5-3)/1=2
        let normalized = vec![-1.0f32, -1.0, -1.0, 2.0, 2.0, 2.0];
        let expected = [0.0f32, 1.0, 2.0, 3.0, 4.0, 5.0];

        let tensor = ArrayD::from_shape_vec(IxDyn(&[6]), normalized).expect("valid shape");
        let mut map = HashMap::new();
        map.insert("output".to_string(), tensor);

        let result = denormalize_step(RawOutputs::TensorMap(map), &mean, &std_vals).unwrap();

        match result {
            RawOutputs::TensorMap(out_map) => {
                let out = out_map.values().next().unwrap();
                for (actual, exp) in out.iter().zip(expected.iter()) {
                    assert!(
                        (actual - exp).abs() < 1e-5,
                        "per-channel failed: expected {}, got {}",
                        exp,
                        actual
                    );
                }
            }
            _ => panic!("Expected TensorMap output"),
        }
    }

    #[test]
    fn test_denormalize_step_scalar_broadcast() {
        // Single mean/std broadcasts to all elements.
        let mean = vec![0.5f32];
        let std_vals = vec![2.0f32];

        // Normalized zeros: (0.0 * 2.0) + 0.5 = 0.5 for every element.
        let tensor = ArrayD::from_shape_vec(IxDyn(&[4]), vec![0.0f32; 4]).expect("valid shape");
        let mut map = HashMap::new();
        map.insert("output".to_string(), tensor);

        let result = denormalize_step(RawOutputs::TensorMap(map), &mean, &std_vals).unwrap();

        match result {
            RawOutputs::TensorMap(out_map) => {
                let out = out_map.values().next().unwrap();
                for &val in out.iter() {
                    assert!(
                        (val - 0.5f32).abs() < 1e-5,
                        "scalar broadcast failed: expected 0.5, got {}",
                        val
                    );
                }
            }
            _ => panic!("Expected TensorMap output"),
        }
    }

    #[test]
    fn test_denormalize_step_shape_mismatch() {
        // mean and std have different lengths — must error, not panic.
        let mean = vec![0.5f32, 0.5];
        let std_vals = vec![1.0f32]; // length mismatch

        let tensor = ArrayD::from_shape_vec(IxDyn(&[4]), vec![0.0f32; 4]).expect("valid shape");
        let mut map = HashMap::new();
        map.insert("output".to_string(), tensor);

        let result = denormalize_step(RawOutputs::TensorMap(map), &mean, &std_vals);
        assert!(result.is_err(), "expected error on shape mismatch");
    }
}