torsh-vision 0.1.2

Computer vision utilities for ToRSh deep learning framework
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
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
// Framework infrastructure - components designed for future use
#![allow(dead_code)]
use crate::unified_transforms::{TransformContext, TransformParameter, UnifiedTransform};
use crate::{Result, VisionError};
use scirs2_core::random::{Random, Rng};
use scirs2_core::RngExt;
use std::collections::HashMap;
use std::sync::Arc;
use torsh_core::device::Device;
use torsh_core::dtype::DType;
use torsh_tensor::Tensor;

/// Unified resize transform that implements both CPU and GPU acceleration
#[derive(Debug)]
pub struct UnifiedResize {
    size: (usize, usize),
    device: Option<Arc<dyn Device>>,
}

impl UnifiedResize {
    pub fn new(size: (usize, usize)) -> Self {
        Self { size, device: None }
    }

    pub fn with_device(size: (usize, usize), device: Arc<dyn Device>) -> Self {
        Self {
            size,
            device: Some(device),
        }
    }
}

impl UnifiedTransform for UnifiedResize {
    fn apply(&self, input: &Tensor<f32>) -> Result<Tensor<f32>> {
        crate::ops::resize(input, self.size)
    }

    fn apply_gpu(&self, input: &Tensor<f32>) -> Result<Tensor<f32>> {
        if let Some(device) = &self.device {
            if matches!(
                device.device_type(),
                torsh_core::device::DeviceType::Cuda(_)
            ) {
                // Use GPU-accelerated resize if available
                // For now, fallback to CPU implementation
                self.apply(input)
            } else {
                self.apply(input)
            }
        } else {
            self.apply(input)
        }
    }

    fn name(&self) -> &'static str {
        "UnifiedResize"
    }

    fn parameters(&self) -> HashMap<String, TransformParameter> {
        let mut params = HashMap::new();
        params.insert(
            "size".to_string(),
            TransformParameter::Tuple2Usize(self.size),
        );
        if let Some(device) = &self.device {
            params.insert(
                "device".to_string(),
                TransformParameter::String(format!("{:?}", device)),
            );
        }
        params
    }

    fn supports_gpu(&self) -> bool {
        self.device.as_ref().map_or(false, |d| {
            matches!(d.device_type(), torsh_core::device::DeviceType::Cuda(_))
        })
    }

    fn output_shape(&self, input_shape: &[usize]) -> Result<Vec<usize>> {
        if input_shape.len() != 3 {
            return Err(VisionError::InvalidShape(format!(
                "Expected 3D tensor (C, H, W), got {}D",
                input_shape.len()
            )));
        }
        Ok(vec![input_shape[0], self.size.1, self.size.0])
    }

    fn clone_transform(&self) -> Box<dyn UnifiedTransform> {
        Box::new(UnifiedResize {
            size: self.size,
            device: self.device.clone(),
        })
    }

    fn preferred_device(&self) -> Option<&dyn Device> {
        self.device.as_ref().map(|d| d.as_ref())
    }
}

/// Unified center crop transform
#[derive(Debug, Clone)]
pub struct UnifiedCenterCrop {
    size: (usize, usize),
}

impl UnifiedCenterCrop {
    pub fn new(size: (usize, usize)) -> Self {
        Self { size }
    }
}

impl UnifiedTransform for UnifiedCenterCrop {
    fn apply(&self, input: &Tensor<f32>) -> Result<Tensor<f32>> {
        crate::ops::center_crop(input, self.size)
    }

    fn name(&self) -> &'static str {
        "UnifiedCenterCrop"
    }

    fn parameters(&self) -> HashMap<String, TransformParameter> {
        let mut params = HashMap::new();
        params.insert(
            "size".to_string(),
            TransformParameter::Tuple2Usize(self.size),
        );
        params
    }

    fn output_shape(&self, input_shape: &[usize]) -> Result<Vec<usize>> {
        if input_shape.len() != 3 {
            return Err(VisionError::InvalidShape(format!(
                "Expected 3D tensor (C, H, W), got {}D",
                input_shape.len()
            )));
        }
        Ok(vec![input_shape[0], self.size.1, self.size.0])
    }

    fn clone_transform(&self) -> Box<dyn UnifiedTransform> {
        Box::new(self.clone())
    }
}

/// Unified random horizontal flip transform
#[derive(Debug, Clone)]
pub struct UnifiedRandomHorizontalFlip {
    p: f32,
}

impl UnifiedRandomHorizontalFlip {
    pub fn new(p: f32) -> Self {
        Self { p }
    }
}

impl UnifiedTransform for UnifiedRandomHorizontalFlip {
    fn apply(&self, input: &Tensor<f32>) -> Result<Tensor<f32>> {
        let mut rng = Random::seed(42);
        if rng.random::<f32>() < self.p {
            crate::ops::horizontal_flip(input)
        } else {
            Ok(input.clone())
        }
    }

    fn name(&self) -> &'static str {
        "UnifiedRandomHorizontalFlip"
    }

    fn parameters(&self) -> HashMap<String, TransformParameter> {
        let mut params = HashMap::new();
        params.insert("probability".to_string(), TransformParameter::Float(self.p));
        params
    }

    fn clone_transform(&self) -> Box<dyn UnifiedTransform> {
        Box::new(self.clone())
    }
}

/// Unified normalization transform
#[derive(Debug)]
pub struct UnifiedNormalize {
    mean: Vec<f32>,
    std: Vec<f32>,
    device: Option<Arc<dyn Device>>,
}

impl UnifiedNormalize {
    pub fn new(mean: Vec<f32>, std: Vec<f32>) -> Self {
        Self {
            mean,
            std,
            device: None,
        }
    }

    pub fn with_device(mean: Vec<f32>, std: Vec<f32>, device: Arc<dyn Device>) -> Self {
        Self {
            mean,
            std,
            device: Some(device),
        }
    }
}

impl UnifiedTransform for UnifiedNormalize {
    fn apply(&self, input: &Tensor<f32>) -> Result<Tensor<f32>> {
        crate::ops::normalize(
            input,
            crate::ops::color::NormalizationConfig {
                method: crate::ops::color::NormalizationMethod::Custom,
                mean: Some(self.mean.clone()),
                std: Some(self.std.clone()),
                per_channel: true,
                eps: 1e-8,
            },
        )
    }

    fn apply_gpu(&self, input: &Tensor<f32>) -> Result<Tensor<f32>> {
        if let Some(device) = &self.device {
            if matches!(
                device.device_type(),
                torsh_core::device::DeviceType::Cuda(_)
            ) {
                // Use GPU-accelerated normalization if available
                // For now, fallback to CPU implementation
                self.apply(input)
            } else {
                self.apply(input)
            }
        } else {
            self.apply(input)
        }
    }

    fn name(&self) -> &'static str {
        "UnifiedNormalize"
    }

    fn parameters(&self) -> HashMap<String, TransformParameter> {
        let mut params = HashMap::new();
        params.insert(
            "mean".to_string(),
            TransformParameter::FloatVec(self.mean.clone()),
        );
        params.insert(
            "std".to_string(),
            TransformParameter::FloatVec(self.std.clone()),
        );
        if let Some(device) = &self.device {
            params.insert(
                "device".to_string(),
                TransformParameter::String(format!("{:?}", device)),
            );
        }
        params
    }

    fn supports_gpu(&self) -> bool {
        self.device.as_ref().map_or(false, |d| {
            matches!(d.device_type(), torsh_core::device::DeviceType::Cuda(_))
        })
    }

    fn supports_mixed_precision(&self) -> bool {
        self.supports_gpu()
    }

    fn clone_transform(&self) -> Box<dyn UnifiedTransform> {
        Box::new(UnifiedNormalize {
            mean: self.mean.clone(),
            std: self.std.clone(),
            device: self.device.clone(),
        })
    }

    fn preferred_device(&self) -> Option<&dyn Device> {
        self.device.as_ref().map(|d| d.as_ref())
    }
}

/// Unified random crop transform
#[derive(Debug, Clone)]
pub struct UnifiedRandomCrop {
    size: (usize, usize),
    padding: Option<usize>,
}

impl UnifiedRandomCrop {
    pub fn new(size: (usize, usize)) -> Self {
        Self {
            size,
            padding: None,
        }
    }

    pub fn with_padding(size: (usize, usize), padding: usize) -> Self {
        Self {
            size,
            padding: Some(padding),
        }
    }
}

impl UnifiedTransform for UnifiedRandomCrop {
    fn apply(&self, input: &Tensor<f32>) -> Result<Tensor<f32>> {
        let input_to_crop = if let Some(padding) = self.padding {
            crate::ops::pad(
                input,
                (padding, padding, padding, padding),
                crate::ops::PaddingMode::Zero,
                0.0,
            )?
        } else {
            input.clone()
        };

        crate::ops::random_crop(&input_to_crop, self.size)
    }

    fn name(&self) -> &'static str {
        "UnifiedRandomCrop"
    }

    fn parameters(&self) -> HashMap<String, TransformParameter> {
        let mut params = HashMap::new();
        params.insert(
            "size".to_string(),
            TransformParameter::Tuple2Usize(self.size),
        );
        if let Some(padding) = self.padding {
            params.insert("padding".to_string(), TransformParameter::Usize(padding));
        }
        params
    }

    fn output_shape(&self, input_shape: &[usize]) -> Result<Vec<usize>> {
        if input_shape.len() != 3 {
            return Err(VisionError::InvalidShape(format!(
                "Expected 3D tensor (C, H, W), got {}D",
                input_shape.len()
            )));
        }
        Ok(vec![input_shape[0], self.size.1, self.size.0])
    }

    fn clone_transform(&self) -> Box<dyn UnifiedTransform> {
        Box::new(self.clone())
    }
}

/// Unified color jitter transform with GPU support
#[derive(Debug)]
pub struct UnifiedColorJitter {
    brightness: Option<f32>,
    contrast: Option<f32>,
    saturation: Option<f32>,
    hue: Option<f32>,
    device: Option<Arc<dyn Device>>,
}

impl UnifiedColorJitter {
    pub fn new() -> Self {
        Self {
            brightness: None,
            contrast: None,
            saturation: None,
            hue: None,
            device: None,
        }
    }

    pub fn brightness(mut self, brightness: f32) -> Self {
        self.brightness = Some(brightness);
        self
    }

    pub fn contrast(mut self, contrast: f32) -> Self {
        self.contrast = Some(contrast);
        self
    }

    pub fn saturation(mut self, saturation: f32) -> Self {
        self.saturation = Some(saturation);
        self
    }

    pub fn hue(mut self, hue: f32) -> Self {
        self.hue = Some(hue);
        self
    }

    pub fn with_device(mut self, device: Arc<dyn Device>) -> Self {
        self.device = Some(device);
        self
    }
}

impl Default for UnifiedColorJitter {
    fn default() -> Self {
        Self::new()
    }
}

impl UnifiedTransform for UnifiedColorJitter {
    fn apply(&self, input: &Tensor<f32>) -> Result<Tensor<f32>> {
        let mut output = input.clone();
        let mut rng = Random::seed(42);

        // Apply brightness adjustment
        if let Some(brightness) = self.brightness {
            let factor = rng.gen_range(1.0 - brightness..=1.0 + brightness);
            output = output.mul_scalar(factor)?;
        }

        // Apply contrast adjustment
        if let Some(contrast) = self.contrast {
            let factor = rng.gen_range(1.0 - contrast..=1.0 + contrast);
            let mean = output.mean(None, false)?;
            let mean_val = mean.to_vec()?[0];
            output.sub_scalar_(mean_val)?;
            output = output.mul_scalar(factor)?;
            output = output.add_scalar(mean_val)?;
        }

        // For saturation and hue, we'd need to convert to HSV space
        // This is a simplified implementation
        Ok(output)
    }

    fn apply_gpu(&self, input: &Tensor<f32>) -> Result<Tensor<f32>> {
        if let Some(device) = &self.device {
            if matches!(
                device.device_type(),
                torsh_core::device::DeviceType::Cuda(_)
            ) {
                // Use GPU-accelerated color jitter if available
                // For now, fallback to CPU implementation
                self.apply(input)
            } else {
                self.apply(input)
            }
        } else {
            self.apply(input)
        }
    }

    fn name(&self) -> &'static str {
        "UnifiedColorJitter"
    }

    fn parameters(&self) -> HashMap<String, TransformParameter> {
        let mut params = HashMap::new();
        if let Some(brightness) = self.brightness {
            params.insert(
                "brightness".to_string(),
                TransformParameter::Float(brightness),
            );
        }
        if let Some(contrast) = self.contrast {
            params.insert("contrast".to_string(), TransformParameter::Float(contrast));
        }
        if let Some(saturation) = self.saturation {
            params.insert(
                "saturation".to_string(),
                TransformParameter::Float(saturation),
            );
        }
        if let Some(hue) = self.hue {
            params.insert("hue".to_string(), TransformParameter::Float(hue));
        }
        if let Some(device) = &self.device {
            params.insert(
                "device".to_string(),
                TransformParameter::String(format!("{:?}", device)),
            );
        }
        params
    }

    fn supports_gpu(&self) -> bool {
        self.device.as_ref().map_or(false, |d| {
            matches!(d.device_type(), torsh_core::device::DeviceType::Cuda(_))
        })
    }

    fn supports_mixed_precision(&self) -> bool {
        self.supports_gpu()
    }

    fn clone_transform(&self) -> Box<dyn UnifiedTransform> {
        Box::new(UnifiedColorJitter {
            brightness: self.brightness,
            contrast: self.contrast,
            saturation: self.saturation,
            hue: self.hue,
            device: self.device.clone(),
        })
    }

    fn preferred_device(&self) -> Option<&dyn Device> {
        self.device.as_ref().map(|d| d.as_ref())
    }
}

/// Unified random rotation transform
#[derive(Debug, Clone)]
pub struct UnifiedRandomRotation {
    degrees: (f32, f32),
}

impl UnifiedRandomRotation {
    pub fn new(degrees: (f32, f32)) -> Self {
        Self { degrees }
    }
}

impl UnifiedTransform for UnifiedRandomRotation {
    fn apply(&self, input: &Tensor<f32>) -> Result<Tensor<f32>> {
        let mut rng = Random::seed(42);
        let angle = rng.gen_range(self.degrees.0..=self.degrees.1);
        crate::ops::rotate(input, angle)
    }

    fn name(&self) -> &'static str {
        "UnifiedRandomRotation"
    }

    fn parameters(&self) -> HashMap<String, TransformParameter> {
        let mut params = HashMap::new();
        params.insert(
            "degrees".to_string(),
            TransformParameter::Tuple2Float(self.degrees),
        );
        params
    }

    fn clone_transform(&self) -> Box<dyn UnifiedTransform> {
        Box::new(self.clone())
    }
}

/// Bridge implementations for backward compatibility with existing Transform trait

/// Bridge from old Transform trait to UnifiedTransform
#[derive(Debug)]
pub struct TransformBridge<T: crate::transforms::Transform> {
    inner: T,
}

impl<T: crate::transforms::Transform + Clone + std::fmt::Debug> TransformBridge<T> {
    pub fn new(transform: T) -> Self {
        Self { inner: transform }
    }
}

impl<T: crate::transforms::Transform + Clone + std::fmt::Debug + 'static> UnifiedTransform
    for TransformBridge<T>
{
    fn apply(&self, input: &Tensor<f32>) -> Result<Tensor<f32>> {
        self.inner.forward(input)
    }

    fn name(&self) -> &'static str {
        self.inner.name()
    }

    fn parameters(&self) -> HashMap<String, TransformParameter> {
        let old_params = self.inner.parameters();
        let mut params = HashMap::new();
        for (key, value) in old_params {
            params.insert(key.to_string(), TransformParameter::String(value));
        }
        params
    }

    fn is_inplace(&self) -> bool {
        self.inner.is_inplace()
    }

    fn clone_transform(&self) -> Box<dyn UnifiedTransform> {
        Box::new(TransformBridge::new(self.inner.clone()))
    }
}

/// Bridge from UnifiedTransform to old Transform trait
pub struct UnifiedTransformBridge {
    inner: Box<dyn UnifiedTransform>,
}

impl UnifiedTransformBridge {
    pub fn new(transform: Box<dyn UnifiedTransform>) -> Self {
        Self { inner: transform }
    }
}

impl crate::transforms::Transform for UnifiedTransformBridge {
    fn forward(&self, input: &Tensor<f32>) -> Result<Tensor<f32>> {
        self.inner.apply(input)
    }

    fn name(&self) -> &'static str {
        self.inner.name()
    }

    fn is_inplace(&self) -> bool {
        self.inner.is_inplace()
    }

    fn parameters(&self) -> Vec<(&'static str, String)> {
        // Simplified conversion - using static fallback to avoid memory leaks
        vec![("bridge", "legacy_transform".to_string())]
    }

    fn clone_transform(&self) -> Box<dyn crate::transforms::Transform> {
        Box::new(UnifiedTransformBridge::new(self.inner.clone_transform()))
    }
}

/// Factory functions for creating unified transforms with different backends
pub mod factory {
    use super::*;

    /// Create a resize transform optimized for the given context
    pub fn create_resize(
        size: (usize, usize),
        context: &TransformContext,
    ) -> Box<dyn UnifiedTransform> {
        if matches!(
            context.device.device_type(),
            torsh_core::device::DeviceType::Cuda(_)
        ) {
            Box::new(UnifiedResize::with_device(size, context.device.clone()))
        } else {
            Box::new(UnifiedResize::new(size))
        }
    }

    /// Create a normalization transform optimized for the given context
    pub fn create_normalize(
        mean: Vec<f32>,
        std: Vec<f32>,
        context: &TransformContext,
    ) -> Box<dyn UnifiedTransform> {
        if matches!(
            context.device.device_type(),
            torsh_core::device::DeviceType::Cuda(_)
        ) {
            Box::new(UnifiedNormalize::with_device(
                mean,
                std,
                context.device.clone(),
            ))
        } else {
            Box::new(UnifiedNormalize::new(mean, std))
        }
    }

    /// Create a color jitter transform optimized for the given context
    pub fn create_color_jitter(context: &TransformContext) -> UnifiedColorJitter {
        if matches!(
            context.device.device_type(),
            torsh_core::device::DeviceType::Cuda(_)
        ) {
            UnifiedColorJitter::new().with_device(context.device.clone())
        } else {
            UnifiedColorJitter::new()
        }
    }

    /// Create an ImageNet preprocessing pipeline
    pub fn imagenet_preprocessing(
        size: (usize, usize),
        context: &TransformContext,
    ) -> crate::unified_transforms::UnifiedCompose {
        use crate::unified_transforms::TransformBuilder;

        TransformBuilder::new()
            .with_context(context.clone())
            .add(UnifiedResize::with_device(size, context.device.clone()))
            .add(UnifiedCenterCrop::new(size))
            .add(UnifiedNormalize::with_device(
                vec![0.485, 0.456, 0.406],
                vec![0.229, 0.224, 0.225],
                context.device.clone(),
            ))
            .build()
    }

    /// Create a training augmentation pipeline
    pub fn training_augmentation(
        size: (usize, usize),
        context: &TransformContext,
    ) -> crate::unified_transforms::UnifiedCompose {
        use crate::unified_transforms::TransformBuilder;

        TransformBuilder::new()
            .with_context(context.clone())
            .add(UnifiedResize::with_device(
                (size.0 + 32, size.1 + 32),
                context.device.clone(),
            ))
            .add(UnifiedRandomCrop::with_padding(size, 4))
            .add(UnifiedRandomHorizontalFlip::new(0.5))
            .add(
                UnifiedColorJitter::new()
                    .brightness(0.2)
                    .contrast(0.2)
                    .with_device(context.device.clone()),
            )
            .add(UnifiedNormalize::with_device(
                vec![0.485, 0.456, 0.406],
                vec![0.229, 0.224, 0.225],
                context.device.clone(),
            ))
            .build()
    }
}

/// Migration utilities for transitioning between transform APIs
pub mod migration {
    use super::*;

    /// Convert a vector of old transforms to unified transforms
    ///
    /// # Status
    /// NOT IMPLEMENTED in v0.1.0
    ///
    /// # Reason
    /// The bridge pattern requires concrete types, not trait objects.
    /// Automatic conversion requires runtime type inspection or manual mapping.
    ///
    /// # Workaround
    /// Manually reconstruct transform pipeline using UnifiedTransform API:
    /// ```ignore
    /// // Old API
    /// let old = Compose::new(vec![Box::new(Resize::new(256)), ...]);
    ///
    /// // New API (manual conversion)
    /// let new = PipelineBuilder::new()
    ///     .add_transform(ResizeTransform::new(256, InterpolationMode::Bilinear))
    ///     .build();
    /// ```
    ///
    /// # Future
    /// May implement with macro-based conversion in v0.3.0
    /// Deferred - See ROADMAP.md
    pub fn convert_transforms(
        _transforms: Vec<Box<dyn crate::transforms::Transform>>,
    ) -> Vec<Box<dyn UnifiedTransform>> {
        // Returns empty vector - user must manually convert
        // Consider using analyze_pipeline() for migration guidance
        Vec::new()
    }

    /// Analyze old transform pipeline and suggest unified equivalents
    pub fn analyze_pipeline(_compose: &crate::transforms::Compose) -> String {
        let mut suggestions = Vec::new();

        suggestions.push("Consider migrating to UnifiedTransform API for:".to_string());
        suggestions.push("- Better GPU acceleration support".to_string());
        suggestions.push("- Mixed precision training capabilities".to_string());
        suggestions.push("- Improved parameter introspection".to_string());
        suggestions.push("- Hardware-aware optimization".to_string());

        suggestions.join("\n")
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use torsh_tensor::creation::zeros;

    #[test]
    fn test_unified_resize() {
        let transform = UnifiedResize::new((224, 224));
        let input = zeros(&[3, 256, 256]).expect("zeros should succeed");
        let output = transform
            .apply(&input)
            .expect("apply operation should succeed");
        assert_eq!(output.shape().dims(), &[3, 224, 224]);
    }

    #[test]
    fn test_unified_parameters() {
        let transform = UnifiedResize::new((224, 224));
        let params = transform.parameters();
        assert!(params.contains_key("size"));
    }

    #[test]
    fn test_transform_bridge() {
        let old_transform = crate::transforms::Resize::new((224, 224));
        let bridge = TransformBridge::new(old_transform);

        let input = zeros(&[3, 256, 256]).expect("zeros should succeed");
        let output = bridge
            .apply(&input)
            .expect("apply operation should succeed");
        assert_eq!(output.shape().dims(), &[3, 224, 224]);
    }

    #[test]
    fn test_factory_functions() {
        let context = TransformContext::default();
        let transform = factory::create_resize((224, 224), &context);

        let input = zeros(&[3, 256, 256]).expect("zeros should succeed");
        let output = transform
            .apply(&input)
            .expect("apply operation should succeed");
        assert_eq!(output.shape().dims(), &[3, 224, 224]);
    }

    #[test]
    fn test_gpu_context() {
        let context = TransformContext::auto_detect().unwrap_or_default();
        let transform = factory::create_normalize(
            vec![0.485, 0.456, 0.406],
            vec![0.229, 0.224, 0.225],
            &context,
        );

        assert_eq!(transform.name(), "UnifiedNormalize");
        assert!(
            transform.supports_gpu()
                || !matches!(
                    context.device.device_type(),
                    torsh_core::device::DeviceType::Cuda(_)
                )
        );
    }
}