fast-umap 1.5.1

Configurable UMAP (Uniform Manifold Approximation and Projection) 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
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
#![allow(unused_variables)]
#![allow(unused_imports)]

//! # fast-umap
//!
//! GPU-accelerated parametric UMAP (Uniform Manifold Approximation and Projection)
//! in Rust, built on [burn](https://github.com/tracel-ai/burn) +
//! [CubeCL](https://github.com/tracel-ai/cubecl).
//!
//! **Up to 4.7× faster** than [umap-rs](https://crates.io/crates/umap-rs) on
//! datasets ≥ 10 000 samples, with the ability to [`transform()`](FittedUmap::transform)
//! new unseen data (something classical UMAP cannot do).
//!
//! ## Quick start
//!
//! ```rust,no_run
//! use fast_umap::prelude::*;
//!
//! // 100 samples × 10 features
//! let data: Vec<Vec<f64>> = generate_test_data(100, 10)
//!     .chunks(10)
//!     .map(|c| c.iter().map(|&x: &f32| x as f64).collect())
//!     .collect();
//!
//! // Configure and fit UMAP
//! let config = UmapConfig::default();
//! // let umap = Umap::<MyAutodiffBackend>::new(config);
//! // let fitted = umap.fit(data.clone(), None);
//! // let embedding = fitted.embedding();
//! // let new_embedding = fitted.transform(new_data);
//! // fitted.save("model.umap")?; // Save trained model
//! // let loaded = FittedUmap::<MyAutodiffBackend>::load("model.umap", config, input_size, device)?;
//! ```
//!
//! ## Interface
//!
//! The public API mirrors the [`umap-rs`](https://crates.io/crates/umap-rs) crate:
//!
//! * [`Umap`] — Main algorithm struct, created via `Umap::new(config)`
//! * [`FittedUmap`] — Fitted model returned from `umap.fit(data)`, with
//!   [`embedding()`](FittedUmap::embedding),
//!   [`into_embedding()`](FittedUmap::into_embedding),
//!   [`transform()`](FittedUmap::transform), and
//!   [`config()`](FittedUmap::config)
//! * [`UmapConfig`] — Configuration with nested [`GraphParams`] and [`OptimizationParams`]
//! * [`Metric`] — Distance metric enum (`Euclidean`, `Manhattan`, `Cosine`, …)
//!
//! ## Performance
//!
//! | Dataset | fast-umap | umap-rs | Speedup |
//! |---------|-----------|---------|---------|
//! | 5 000 × 100 | 6.75s | 2.31s | 0.34× *(umap-rs faster)* |
//! | 10 000 × 100 | 5.93s | 8.68s | **1.5× faster** |
//! | 20 000 × 100 | 7.32s | 34.10s | **4.7× faster** |
//!
//! Benchmarked on Apple M3 Max. Reproduce with
//! `cargo run --release --example crate_comparison`.
//!
//! ## Architecture
//!
//! The dimensionality reduction is performed by a small feed-forward neural
//! network (`UMAPModel`) trained with the UMAP cross-entropy loss using
//! sparse edge subsampling and negative sampling:
//!
//! ```text
//! attraction  =  mean_{sampled k-NN edges}   [ −log q_ij ]
//! repulsion   =  mean_{negative samples}     [ −log (1 − q_ij) ]
//! loss        =  attraction  +  repulsion_strength × repulsion
//! ```
//!
//! where `q_ij = 1 / (1 + a · d_ij^(2b))` is the UMAP kernel applied to
//! embedding distances (`a` and `b` are fitted from `min_dist` / `spread`).
//! Per-epoch cost is O(min(n·k, 50K)) regardless of dataset size.
//!
//! ## Modules
//!
//! | Module | Description |
//! |--------|-------------|
//! | [`model`] | `UMAPModel` neural network and config builder |
//! | [`train`] | Training loop, `UmapConfig`, sparse training, loss computation |
//! | [`chart`] | 2-D scatter plots and loss curves (plotters, optional) |
//! | [`utils`] | Data generation, tensor conversion, normalisation |
//! | [`kernels`] | Custom CubeCL GPU kernels (Euclidean distance, k-NN) |
//! | [`backend`] | Backend trait extension for custom kernel dispatch |
//! | [`distances`] | CPU-side distance functions (Euclidean, cosine, Minkowski…) |
//! | [`serialize`] | Model weight serialization/deserialization |
//! | [`prelude`] | Re-exports of the most commonly used items |

use backend::AutodiffBackend;
use burn::module::AutodiffModule;

use crossbeam_channel::Receiver;
use model::{UMAPModel, UMAPModelConfigBuilder};
use num::Float;
use train::*;
use utils::*;

use burn::tensor::{Device, Tensor};

pub mod backend;
#[cfg(feature = "plotters")]
pub mod chart;
#[cfg(feature = "cpu")]
pub mod cpu_backend;
pub mod distances;
#[cfg(feature = "gpu")]
pub mod kernels;
pub mod macros;
pub mod model;
pub mod normalizer;
pub mod prelude;
pub mod serialize;
pub mod train;
pub mod utils;

// Re-export config types at crate root for umap-rs style access
pub use train::{
    EpochProgress, GraphParams, LossReduction, ManifoldParams, Metric, OptimizationParams,
    TrainingConfig, TrainingConfigBuilder, UmapConfig,
};

/// UMAP dimensionality reduction algorithm (GPU-accelerated, parametric).
///
/// This struct holds the configuration for UMAP. Use [`Umap::new`] to create
/// an instance, then call [`fit`](Umap::fit) to train and obtain a
/// [`FittedUmap`].
///
/// The interface mirrors [`umap-rs`](https://crates.io/crates/umap-rs), but
/// this implementation uses a parametric neural network trained on a GPU,
/// which means:
/// - It can [`transform`](FittedUmap::transform) new (unseen) data
/// - It leverages GPU acceleration via burn/CubeCL
/// - It does **not** require precomputed KNN (computed internally per batch)
///
/// # Example
///
/// ```ignore
/// use fast_umap::prelude::*;
///
/// let config = UmapConfig {
///     n_components: 2,
///     graph: GraphParams {
///         n_neighbors: 15,
///         ..Default::default()
///     },
///     optimization: OptimizationParams {
///         n_epochs: 200,
///         ..Default::default()
///     },
///     ..Default::default()
/// };
///
/// let umap = Umap::<MyAutodiffBackend>::new(config);
/// let fitted = umap.fit(data, None);
/// let embedding = fitted.embedding();
/// ```
pub struct Umap<B: AutodiffBackend> {
    config: UmapConfig,
    device: Device<B>,
}

impl<B: AutodiffBackend> Umap<B> {
    /// Create a new UMAP instance with the given configuration.
    ///
    /// Uses the default device for the backend.
    ///
    /// # Arguments
    ///
    /// * `config` - UMAP configuration parameters
    pub fn new(config: UmapConfig) -> Self {
        Self {
            config,
            device: Default::default(),
        }
    }

    /// Create a new UMAP instance with a specific device.
    ///
    /// # Arguments
    ///
    /// * `config` - UMAP configuration parameters
    /// * `device` - The device (CPU or GPU) on which to perform computation
    pub fn with_device(config: UmapConfig, device: Device<B>) -> Self {
        Self { config, device }
    }

    /// Get a reference to the configuration.
    pub fn config(&self) -> &UmapConfig {
        &self.config
    }

    /// Fit the UMAP model to the given data.
    ///
    /// Trains a parametric neural network to learn a low-dimensional embedding
    /// of the input data. The model can then be used to transform new data.
    ///
    /// # Arguments
    ///
    /// * `data` - Input data as a vector of vectors (n_samples × n_features)
    /// * `labels` - Optional per-sample labels for coloured epoch snapshots
    ///
    /// # Returns
    ///
    /// A [`FittedUmap`] containing the trained model and embedding.
    ///
    /// # Example
    ///
    /// ```ignore
    /// let config = UmapConfig::default();
    /// let umap = Umap::<MyAutodiffBackend>::new(config);
    /// let fitted = umap.fit(data, None);
    /// let embedding = fitted.embedding();
    /// ```
    pub fn fit<F: Float>(self, data: Vec<Vec<F>>, labels: Option<Vec<String>>) -> FittedUmap<B>
    where
        F: num::FromPrimitive + burn::tensor::Element,
    {
        let (exit_tx, exit_rx) = crossbeam_channel::unbounded();

        ctrlc::set_handler(move || {
            let _ = exit_tx.send(());
        })
        .ok(); // Ignore error if handler already set

        self.fit_with_signal(data, labels, exit_rx)
    }

    /// Fit the UMAP model with an external cancellation signal.
    ///
    /// Same as [`fit`](Umap::fit) but accepts an external `Receiver<()>` for
    /// graceful cancellation (e.g., from Ctrl-C).
    ///
    /// # Arguments
    ///
    /// * `data` - Input data as a vector of vectors (n_samples × n_features)
    /// * `labels` - Optional per-sample labels for coloured epoch snapshots
    /// * `exit_rx` - Channel receiver for cancellation signal
    ///
    /// # Returns
    ///
    /// A [`FittedUmap`] containing the trained model and embedding.
    pub fn fit_with_signal<F: Float>(
        self,
        data: Vec<Vec<F>>,
        labels: Option<Vec<String>>,
        exit_rx: Receiver<()>,
    ) -> FittedUmap<B>
    where
        F: num::FromPrimitive + burn::tensor::Element,
    {
        let default_name = "model";
        let num_samples = data.len();
        let num_features = data[0].len();
        let batch_size = num_samples;

        let seed = 9999;
        B::seed(&self.device, seed);

        // Flatten input data
        let train_data: Vec<F> = data.into_iter().flatten().collect();

        // Build model config
        let model_config = UMAPModelConfigBuilder::default()
            .input_size(num_features)
            .hidden_sizes(self.config.hidden_sizes.clone())
            .output_size(self.config.n_components)
            .build()
            .unwrap();

        let model: UMAPModel<B> = UMAPModel::new(&model_config, &self.device);

        // Build training config from UmapConfig
        let (kernel_a, kernel_b) = train::fit_ab(
            self.config.manifold.min_dist,
            self.config.manifold.spread,
        );
        let training_config = TrainingConfig {
            metric: self.config.graph.metric.clone(),
            epochs: self.config.optimization.n_epochs,
            batch_size,
            learning_rate: self.config.optimization.learning_rate,
            beta1: self.config.optimization.beta1,
            beta2: self.config.optimization.beta2,
            penalty: self.config.optimization.penalty,
            verbose: self.config.optimization.verbose,
            patience: self.config.optimization.patience,
            loss_reduction: self.config.optimization.loss_reduction.clone(),
            k_neighbors: self.config.graph.n_neighbors,
            min_desired_loss: self.config.optimization.min_desired_loss,
            timeout: self.config.optimization.timeout,
            normalized: self.config.graph.normalized,
            minkowski_p: self.config.graph.minkowski_p,
            repulsion_strength: self.config.optimization.repulsion_strength,
            kernel_a,
            kernel_b,
            neg_sample_rate: self.config.optimization.neg_sample_rate,
            cooldown_ms: self.config.optimization.cooldown_ms,
            figures_dir: self.config.optimization.figures_dir.clone(),
        };

        // Use the sparse training path (O(n·k) per epoch) by default.
        // Falls back to dense path only if explicitly requested in the future.
        let (model, _losses, _best_loss): (UMAPModel<B>, Vec<F>, F) = train::train_sparse(
            default_name,
            model,
            num_samples,
            num_features,
            train_data.clone(),
            &training_config,
            self.device.clone(),
            exit_rx,
            labels,
            None,
        );

        Self::finalize(model, train_data, num_samples, num_features, self.device, self.config)
    }

    /// Like [`fit_with_signal`], but also accepts a progress callback that is
    /// invoked every few epochs with timing and loss information.
    pub fn fit_with_progress<F: Float>(
        self,
        data: Vec<Vec<F>>,
        labels: Option<Vec<String>>,
        exit_rx: Receiver<()>,
        on_progress: Box<dyn Fn(EpochProgress) + Send>,
    ) -> FittedUmap<B>
    where
        F: num::FromPrimitive + burn::tensor::Element,
    {
        let default_name = "model";
        let num_samples = data.len();
        let num_features = data[0].len();
        let batch_size = num_samples;

        let seed = 9999;
        B::seed(&self.device, seed);

        let train_data: Vec<F> = data.into_iter().flatten().collect();

        let model_config = UMAPModelConfigBuilder::default()
            .input_size(num_features)
            .hidden_sizes(self.config.hidden_sizes.clone())
            .output_size(self.config.n_components)
            .build()
            .unwrap();

        let model: UMAPModel<B> = UMAPModel::new(&model_config, &self.device);

        let (kernel_a, kernel_b) = train::fit_ab(
            self.config.manifold.min_dist,
            self.config.manifold.spread,
        );
        let training_config = TrainingConfig {
            metric: self.config.graph.metric.clone(),
            epochs: self.config.optimization.n_epochs,
            batch_size,
            learning_rate: self.config.optimization.learning_rate,
            beta1: self.config.optimization.beta1,
            beta2: self.config.optimization.beta2,
            penalty: self.config.optimization.penalty,
            verbose: self.config.optimization.verbose,
            patience: self.config.optimization.patience,
            loss_reduction: self.config.optimization.loss_reduction.clone(),
            k_neighbors: self.config.graph.n_neighbors,
            min_desired_loss: self.config.optimization.min_desired_loss,
            timeout: self.config.optimization.timeout,
            normalized: self.config.graph.normalized,
            minkowski_p: self.config.graph.minkowski_p,
            repulsion_strength: self.config.optimization.repulsion_strength,
            kernel_a,
            kernel_b,
            neg_sample_rate: self.config.optimization.neg_sample_rate,
            cooldown_ms: self.config.optimization.cooldown_ms,
            figures_dir: self.config.optimization.figures_dir.clone(),
        };

        let (model, _losses, _best_loss): (UMAPModel<B>, Vec<F>, F) = train::train_sparse(
            default_name,
            model,
            num_samples,
            num_features,
            train_data.clone(),
            &training_config,
            self.device.clone(),
            exit_rx,
            labels,
            Some(on_progress),
        );

        Self::finalize(model, train_data, num_samples, num_features, self.device, self.config)
    }

    /// Shared finalization: extract embedding from trained model.
    fn finalize<F: Float>(
        model: UMAPModel<B>,
        train_data: Vec<F>,
        num_samples: usize,
        num_features: usize,
        device: Device<B>,
        config: UmapConfig,
    ) -> FittedUmap<B>
    where
        F: num::FromPrimitive + burn::tensor::Element,
    {
        let model: UMAPModel<B::InnerBackend> = model.valid();

        let mut normalized_data = train_data;
        normalize_data(&mut normalized_data, num_samples, num_features);
        let global = convert_vector_to_tensor(
            normalized_data,
            num_samples,
            num_features,
            &device,
        );
        let embedding_tensor = model.forward(global);
        let embedding: Vec<Vec<f64>> = convert_tensor_to_vector(embedding_tensor);

        FittedUmap {
            model,
            device,
            config,
            embedding,
            num_features,
        }
    }
}

/// A fitted UMAP model containing the trained neural network and embedding.
///
/// This struct is returned by [`Umap::fit`] and provides methods to:
/// - Access the computed embedding via [`embedding`](FittedUmap::embedding)
///   and [`into_embedding`](FittedUmap::into_embedding)
/// - Transform new data via [`transform`](FittedUmap::transform) and
///   [`transform_to_tensor`](FittedUmap::transform_to_tensor)
/// - Access the configuration via [`config`](FittedUmap::config)
///
/// Because this is a parametric UMAP (neural network), it can project unseen
/// data through [`transform`](FittedUmap::transform) — unlike classical UMAP
/// implementations.
pub struct FittedUmap<B: AutodiffBackend> {
    model: UMAPModel<B::InnerBackend>,
    device: Device<B>,
    config: UmapConfig,
    embedding: Vec<Vec<f64>>,
    #[allow(dead_code)]
    num_features: usize,
}

impl<B: AutodiffBackend> FittedUmap<B> {
    /// Get the computed embedding for the training data.
    ///
    /// Returns a reference to the embedding coordinates. Each inner vector
    /// represents one input sample in the low-dimensional space.
    ///
    /// # Returns
    ///
    /// A reference to a `Vec<Vec<f64>>` of shape (n_samples, n_components).
    pub fn embedding(&self) -> &Vec<Vec<f64>> {
        &self.embedding
    }

    /// Consume the fitted model and return the embedding, avoiding a copy.
    ///
    /// # Returns
    ///
    /// The embedding as `Vec<Vec<f64>>` of shape (n_samples, n_components).
    pub fn into_embedding(self) -> Vec<Vec<f64>> {
        self.embedding
    }

    /// Get a reference to the configuration used for this fit.
    pub fn config(&self) -> &UmapConfig {
        &self.config
    }

    /// Transform new data points into the embedding space.
    ///
    /// Projects new, unseen data through the trained neural network to obtain
    /// low-dimensional coordinates. This is possible because fast-umap uses a
    /// parametric (neural network) approach.
    ///
    /// # Arguments
    ///
    /// * `data` - New data points as `Vec<Vec<f64>>` (n_new_samples × n_features)
    ///
    /// # Returns
    ///
    /// Embeddings for the new data points as `Vec<Vec<f64>>` (n_new_samples × n_components).
    pub fn transform(&self, data: Vec<Vec<f64>>) -> Vec<Vec<f64>> {
        let local = self.transform_to_tensor(data);
        convert_tensor_to_vector(local)
    }

    /// Transform new data into the embedding space, returning a tensor.
    ///
    /// # Arguments
    ///
    /// * `data` - New data points as `Vec<Vec<f64>>` (n_new_samples × n_features)
    ///
    /// # Returns
    ///
    /// A 2D tensor of shape `[n_new_samples, n_components]`.
    pub fn transform_to_tensor(&self, data: Vec<Vec<f64>>) -> Tensor<B::InnerBackend, 2> {
        let num_samples = data.len();
        let num_features = data[0].len();

        let train_data: Vec<f64> = data.into_iter().flatten().collect();

        let global = convert_vector_to_tensor(train_data, num_samples, num_features, &self.device);

        self.model.forward(global)
    }

    /// Save the model's weights to a file.
    ///
    /// Serializes the trained model weights to disk for later use.
    /// The configuration and embedding are not saved, only the neural network weights.
    ///
    /// # Arguments
    ///
    /// * `path` - Path to the output file
    ///
    /// # Returns
    ///
    /// `Ok(())` on success, or an error if saving fails.
    ///
    /// # Example
    ///
    /// ```ignore
    /// use fast_umap::prelude::*;
    /// use burn::backend::Wgpu;
    ///
    /// let config = UmapConfig::default();
    /// let umap = Umap::<Wgpu>::new(config);
    /// let fitted = umap.fit(data, None);
    /// fitted.save("model.umap").expect("Failed to save model");
    /// ```
    pub fn save(&self, path: impl AsRef<std::path::Path>) -> Result<(), Box<dyn std::error::Error>> {
        serialize::save_model::<B>(&self.model, path)
    }

    /// Load a model's weights from a file into a new FittedUmap instance.
    ///
    /// Creates a new FittedUmap with the loaded weights. Note that the configuration
    /// must match the configuration used when the model was saved (same input size,
    /// hidden layer sizes, and output size).
    ///
    /// # Arguments
    ///
    /// * `path` - Path to the input file
    /// * `config` - The UMAP configuration that matches the saved model
    /// * `input_size` - The number of features in the input data (must match the saved model)
    /// * `device` - The device where the model should be loaded
    ///
    /// # Returns
    ///
    /// A new `FittedUmap` instance with the loaded weights, or an error if loading fails.
    ///
    /// # Example
    ///
    /// ```ignore
    /// use fast_umap::prelude::*;
    /// use burn::backend::Wgpu;
    ///
    /// // Load a previously saved model
    /// let config = UmapConfig::default();
    /// let device = Default::default();
    /// let input_size = 100; // Must match the data used during training
    /// let fitted = FittedUmap::<Wgpu>::load("model.umap", config, input_size, device)?;
    /// let embedding = fitted.transform(new_data);
    /// ```
    pub fn load(
        path: impl AsRef<std::path::Path>,
        config: UmapConfig,
        input_size: usize,
        device: Device<B>,
    ) -> Result<Self, Box<dyn std::error::Error>> {
        // Create a new model with the same architecture
        let model_config = UMAPModelConfigBuilder::default()
            .input_size(input_size)
            .hidden_sizes(config.hidden_sizes.clone())
            .output_size(config.n_components)
            .build()?;

        let mut model: UMAPModel<B::InnerBackend> = UMAPModel::new(&model_config, &device);

        // Load the weights
        serialize::load_model::<B>(&mut model, path, &device)?;

        // Create a FittedUmap instance (embedding will be empty since we don't have training data)
        Ok(Self {
            model,
            device,
            config,
            embedding: Vec::new(),
            num_features: input_size,
        })
    }

    /// Load a model's weights from a file, inferring input size from sample data.
    ///
    /// This convenience method creates a new FittedUmap with the loaded weights,
    /// using a sample data point to determine the input size.
    ///
    /// # Arguments
    ///
    /// * `path` - Path to the input file
    /// * `config` - The UMAP configuration that matches the saved model
    /// * `sample_data` - A single sample data point to infer the input size
    /// * `device` - The device where the model should be loaded
    ///
    /// # Returns
    ///
    /// A new `FittedUmap` instance with the loaded weights, or an error if loading fails.
    ///
    /// # Example
    ///
    /// ```ignore
    /// use fast_umap::prelude::*;
    /// use burn::backend::Wgpu;
    ///
    /// // Load a previously saved model
    /// let config = UmapConfig::default();
    /// let device = Default::default();
    /// let sample = vec![1.0, 2.0, 3.0]; // Same dimensionality as training data
    /// let fitted = FittedUmap::<Wgpu>::load_with_sample("model.umap", config, sample, device)?;
    /// ```
    pub fn load_with_sample(
        path: impl AsRef<std::path::Path>,
        config: UmapConfig,
        sample_data: Vec<f64>,
        device: Device<B>,
    ) -> Result<Self, Box<dyn std::error::Error>> {
        let input_size = sample_data.len();
        Self::load(path, config, input_size, device)
    }
}

// ─── Backward-compatible UMAP type alias ─────────────────────────────────────

/// Legacy UMAP struct — **Deprecated**: Use [`Umap`] and [`FittedUmap`] instead.
///
/// This struct is provided for backward compatibility. New code should use
/// the [`Umap`] / [`FittedUmap`] API which mirrors `umap-rs`.
pub struct UMAP<B: AutodiffBackend> {
    model: UMAPModel<B::InnerBackend>,
    device: Device<B>,
}

impl<B: AutodiffBackend> UMAP<B> {
    /// Trains the UMAP model on the given data and returns a fitted UMAP model.
    ///
    /// **Deprecated**: Use `Umap::new(config).fit(data, None)` instead.
    pub fn fit<F: Float>(
        data: Vec<Vec<F>>,
        device: Device<B>,
        output_size: usize,
        exit_rx: Receiver<()>,
    ) -> Self
    where
        F: num::FromPrimitive + burn::tensor::Element,
    {
        let default_name = "model";
        let num_samples = data.len();
        let num_features = data[0].len();
        let batch_size = num_samples;
        let hidden_sizes = vec![100];
        let learning_rate = 0.001;
        let beta1 = 0.9;
        let beta2 = 0.999;
        let epochs = 100;
        let seed = 9999;

        B::seed(&device, seed);

        let train_data: Vec<F> = data.into_iter().flatten().collect();

        let model_config = UMAPModelConfigBuilder::default()
            .input_size(num_features)
            .hidden_sizes(hidden_sizes)
            .output_size(output_size)
            .build()
            .unwrap();

        let model: UMAPModel<B> = UMAPModel::new(&model_config, &device);

        let config = TrainingConfig::builder()
            .with_epochs(epochs)
            .with_batch_size(batch_size)
            .with_learning_rate(learning_rate)
            .with_beta1(beta1)
            .with_beta2(beta2)
            .build()
            .expect("Failed to build TrainingConfig");

        let (model, _losses, _best_loss): (UMAPModel<B>, Vec<F>, F) = train(
            default_name,
            model,
            num_samples,
            num_features,
            train_data.clone(),
            &config,
            device.clone(),
            exit_rx,
            None,
        );

        let model: UMAPModel<B::InnerBackend> = model.valid();

        UMAP { model, device }
    }

    /// Transforms the input data to a tensor using the trained UMAP model.
    pub fn transform_to_tensor(&self, data: Vec<Vec<f64>>) -> Tensor<B::InnerBackend, 2> {
        let num_samples = data.len();
        let num_features = data[0].len();

        let train_data: Vec<f64> = data.into_iter().flatten().map(|f| f64::from(f)).collect();

        let global = convert_vector_to_tensor(train_data, num_samples, num_features, &self.device);

        let local = self.model.forward(global);

        local
    }

    /// Transforms the input data into a lower-dimensional space.
    pub fn transform(&self, data: Vec<Vec<f64>>) -> Vec<Vec<f64>> {
        let local = self.transform_to_tensor(data);
        convert_tensor_to_vector(local)
    }
}