tensor4all_core/randomized.rs
1//! Fixed-rank Gaussian range finding and dense randomized SVD.
2//!
3//! Composes the backend's contractions, QR and SVD following Halko, Martinsson
4//! and Tropp, SIAM Review 53 (2011), Algorithms 4.4 and 5.1. No upstream source
5//! code was translated. The input is a materialized local tensor; these routines
6//! do not materialize a tensor network.
7//!
8//! Only dense `f64` and `Complex64` inputs are supported. `f32` and `Complex32`
9//! (c32) return [`FactorizeError::UnsupportedStorage`] before consuming RNG state.
10
11use num_complex::Complex64;
12use rand::Rng;
13use std::time::{Duration, Instant};
14
15use crate::defaults::idx_tensor::{checked_product, unfold_index_sets, RandomScalar};
16use crate::defaults::svd::{
17 svd_for_factorize, svd_for_factorize_in, svd_for_factorize_on_session, SvdFactorizeResult,
18};
19use crate::{
20 DynIndex, ExecutionContext, FactorizeError, FactorizeOptions, FactorizeResult, IdxTensor,
21 IndexLike, PairwiseContractionOptions, SvdOptions,
22};
23use tensor4all_tensorbackend::explicit::Session;
24
25/// Sketch size and numerical stabilization for a Gaussian range finder.
26///
27/// Unlike SVD truncation policies, these options do not promise an error
28/// tolerance. [`RsvdOptions`] adds the requested output rank for RSVD.
29///
30/// # Examples
31/// ```
32/// use tensor4all_core::RangeOptions;
33/// let options = RangeOptions::default();
34/// assert_eq!(options.oversampling, 8);
35/// assert_eq!(options.power_iterations, 1);
36/// ```
37#[derive(Debug, Clone, Copy, PartialEq, Eq)]
38pub struct RangeOptions {
39 /// Extra Gaussian columns beyond the requested rank, capped at the matrix
40 /// dimensions. Eight is a useful default; use zero for a rank-`k` projector.
41 pub oversampling: usize,
42 /// Stabilized power iterations, with QR on both sides of each iteration.
43 /// One is the default; zero costs less, two can help slowly decaying spectra.
44 pub power_iterations: usize,
45}
46
47impl Default for RangeOptions {
48 fn default() -> Self {
49 Self {
50 oversampling: 8,
51 power_iterations: 1,
52 }
53 }
54}
55
56/// Fixed output rank and sketch options for [`randomized_svd`].
57///
58/// Global truncation defaults are ignored. Threshold-based accuracy needs an
59/// a posteriori estimator and is deliberately unsupported in this first version.
60/// Only dense `f64`/`Complex64` inputs are supported; `f32`/`Complex32` are not.
61///
62/// # Examples
63/// ```
64/// use tensor4all_core::RsvdOptions;
65/// let options = RsvdOptions::new(3);
66/// assert_eq!(options.max_bond_dim, 3);
67/// assert_eq!(options.range.oversampling, 8);
68/// ```
69#[derive(Debug, Clone, Copy)]
70pub struct RsvdOptions {
71 /// Positive output rank cap. The actual rank is `min(max_bond_dim, m, n)`.
72 pub max_bond_dim: usize,
73 /// Oversampling and power iterations; when in doubt use the defaults.
74 pub range: RangeOptions,
75}
76
77impl RsvdOptions {
78 /// Request a positive rank cap with default sketch options.
79 ///
80 /// Zero is rejected by the decomposition before consuming randomness.
81 ///
82 /// # Examples
83 /// ```
84 /// use tensor4all_core::RsvdOptions;
85 /// assert_eq!(RsvdOptions::new(2).max_bond_dim, 2);
86 /// ```
87 pub fn new(max_bond_dim: usize) -> Self {
88 Self {
89 max_bond_dim,
90 range: RangeOptions::default(),
91 }
92 }
93}
94
95/// Time spent in one RSVD composite, including sketch construction and index work.
96///
97/// The GEMM and QR counters allow comparison with the total before considering
98/// moving the composite upstream. They include operation dispatch overhead and
99/// are observational diagnostics, not a performance guarantee.
100///
101/// # Examples
102/// ```
103/// use tensor4all_core::RsvdTimings;
104/// let timings = RsvdTimings::default();
105/// assert_eq!(timings.gemm + timings.qr + timings.small_svd, timings.total);
106/// ```
107#[derive(Debug, Clone, Copy, Default)]
108pub struct RsvdTimings {
109 /// Whole RSVD driver, including validation, sampling and factor assembly.
110 pub total: Duration,
111 /// Sketch products, power-iteration products, projection and lifting.
112 pub gemm: Duration,
113 /// Thin QR operations, including reorthogonalization in power iterations.
114 pub qr: Duration,
115 /// SVD of the projected matrix, including rank slicing and index assembly.
116 pub small_svd: Duration,
117}
118
119/// Approximate SVD factors with directly contractible index identities.
120///
121/// Contract `u`, `s`, then `vh` to reconstruct the approximation. Unlike a
122/// deterministic SVD, `singular_values` describes the projected matrix only.
123///
124/// # Examples
125/// ```
126/// use rand::SeedableRng;
127/// use rand_chacha::ChaCha8Rng;
128/// use tensor4all_core::{randomized_svd, DynIndex, IdxTensor, RsvdOptions, TensorContractionLike};
129/// let i = DynIndex::new_dyn(2);
130/// let j = DynIndex::new_dyn(2);
131/// let a = IdxTensor::from_dense(vec![i.clone(), j], vec![3., 0., 0., 0.])?;
132/// let mut rng = ChaCha8Rng::seed_from_u64(11);
133/// let result = randomized_svd(&a, &[i], &RsvdOptions::new(1), &mut rng)?;
134/// let reconstructed = result.u.contract_pair(&result.s)?.contract_pair(&result.vh)?;
135/// assert!(a.sub(&reconstructed)?.maxabs()? < 1e-12);
136/// # Ok::<(), Box<dyn std::error::Error>>(())
137/// ```
138#[derive(Debug, Clone)]
139pub struct RsvdResult {
140 /// Orthonormal left singular vectors with the original left indices.
141 pub u: IdxTensor,
142 /// Singular values as a diagonal tensor connecting the two factor bonds.
143 pub s: IdxTensor,
144 /// Conjugate-transposed right singular vectors and original right indices.
145 pub vh: IdxTensor,
146 /// Retained singular values of `Q† A`, in nonincreasing order.
147 pub singular_values: Vec<f64>,
148 /// Measured cost attribution for this call; instrumentation is included.
149 pub timings: RsvdTimings,
150}
151
152fn computation(error: impl Into<anyhow::Error>) -> FactorizeError {
153 FactorizeError::ComputationError(error.into())
154}
155
156/// Selected execution boundary, shared by both randomized algorithms.
157pub(crate) enum Route<'a, 'session> {
158 Eager(Option<&'a ExecutionContext>),
159 Session(&'a mut Session<'session>),
160}
161
162impl Route<'_, '_> {
163 fn validate(&self, t: &IdxTensor) -> Result<(), FactorizeError> {
164 if t.is_diag()
165 || !(t.is_f64() || t.is_c64())
166 || t.axis_classes()
167 .iter()
168 .enumerate()
169 .any(|(axis, &class)| axis != class)
170 {
171 return Err(FactorizeError::UnsupportedStorage(
172 "RSVD requires dense f64 or Complex64 tensors",
173 ));
174 }
175 match self {
176 Self::Eager(Some(context)) => t.validate_context(context).map_err(computation)?,
177 Self::Session(_) if t.tracks_grad() || t.is_cuda_resident() => {
178 return Err(FactorizeError::UnsupportedStorage(
179 "explicit-session RSVD requires untracked host tensors",
180 ));
181 }
182 Self::Eager(None) if t.is_cuda_resident() => {
183 return Err(FactorizeError::UnsupportedStorage(
184 "resident RSVD requires a caller-owned execution context",
185 ));
186 }
187 _ => {}
188 }
189 Ok(())
190 }
191
192 fn gaussian<T: RandomScalar + tensor4all_tensorbackend::StorageScalar, R: Rng + ?Sized>(
193 &self,
194 template: &IdxTensor,
195 indices: Vec<DynIndex>,
196 rng: &mut R,
197 ) -> Result<IdxTensor, FactorizeError> {
198 let dims: Vec<_> = indices.iter().map(IndexLike::dim).collect();
199 let len = checked_product(&dims).map_err(computation)?;
200 len.checked_mul(std::mem::size_of::<T>())
201 .filter(|&bytes| bytes <= isize::MAX as usize)
202 .ok_or(FactorizeError::InvalidOptions(
203 "Gaussian sketch byte length overflows",
204 ))?;
205 let data = (0..len).map(|_| T::random_value(rng)).collect();
206 match self {
207 Self::Eager(Some(context)) => IdxTensor::from_dense_in(context, indices, data),
208 Self::Eager(None) => template.constant_dense_like(indices, data),
209 Self::Session(_) => IdxTensor::from_host_dense(indices, data),
210 }
211 .map_err(computation)
212 }
213
214 pub(crate) fn contract(
215 &mut self,
216 a: &IdxTensor,
217 b: &IdxTensor,
218 ) -> Result<IdxTensor, FactorizeError> {
219 self.contract_options(a, b, PairwiseContractionOptions::new())
220 }
221
222 fn contract_options(
223 &mut self,
224 a: &IdxTensor,
225 b: &IdxTensor,
226 options: PairwiseContractionOptions,
227 ) -> Result<IdxTensor, FactorizeError> {
228 match self {
229 // Both operands carry the same owning eager runtime. The implicit
230 // contraction resolves that runtime's engine, including on `_in`.
231 Self::Eager(_) => crate::contract_pair_with_operand_options(a, b, options),
232 Self::Session(session) => crate::contract_pair_on_session(session, a, b, options),
233 }
234 .map_err(computation)
235 }
236
237 fn qr(&mut self, t: &IdxTensor, left: &[DynIndex]) -> Result<IdxTensor, FactorizeError> {
238 let options = crate::qr::QrOptions::full_rank();
239 macro_rules! qr {
240 ($scalar:ty) => {
241 match self {
242 Self::Eager(None) => crate::qr::qr_with::<$scalar>(t, left, &options),
243 Self::Eager(Some(context)) => {
244 crate::qr::qr_with_in::<$scalar>(t, left, &options, context)
245 }
246 Self::Session(session) => {
247 crate::qr::qr_with_on_session::<$scalar>(session, t, left, &options)
248 }
249 }
250 };
251 }
252 let (q, _) = if t.is_f64() { qr!(f64) } else { qr!(Complex64) }?;
253 Ok(q)
254 }
255
256 fn svd(
257 &mut self,
258 t: &IdxTensor,
259 left: &[DynIndex],
260 rank: usize,
261 ) -> Result<SvdFactorizeResult, FactorizeError> {
262 let options = SvdOptions::full_rank().with_max_bond_dim(rank);
263 Ok(match self {
264 Self::Eager(None) => svd_for_factorize(t, left, &options),
265 Self::Eager(Some(context)) => svd_for_factorize_in(t, left, &options, context),
266 Self::Session(session) if t.is_f64() => {
267 svd_for_factorize_on_session::<f64>(session, t, left, &options)
268 }
269 Self::Session(session) => {
270 svd_for_factorize_on_session::<Complex64>(session, t, left, &options)
271 }
272 }?)
273 }
274}
275
276struct PreparedRange {
277 tensor: IdxTensor,
278 right: Vec<DynIndex>,
279 ell: usize,
280}
281
282fn prepare(
283 t: &IdxTensor,
284 left: &[DynIndex],
285 rank: usize,
286 options: &RangeOptions,
287 route: &Route<'_, '_>,
288) -> Result<PreparedRange, FactorizeError> {
289 route.validate(t)?;
290 if rank == 0 {
291 return Err(FactorizeError::InvalidOptions(
292 "RSVD rank must be at least 1",
293 ));
294 }
295 let (left, right, _) = unfold_index_sets(t, left).map_err(|_| {
296 FactorizeError::InvalidOptions(
297 "left indices must be a nonempty proper subset with no duplicates and full index identity")
298 })?;
299 let rows = checked_product(&left.iter().map(IndexLike::dim).collect::<Vec<_>>())
300 .map_err(computation)?;
301 let cols = checked_product(&right.iter().map(IndexLike::dim).collect::<Vec<_>>())
302 .map_err(computation)?;
303 let ell = rank
304 .checked_add(options.oversampling)
305 .ok_or(FactorizeError::InvalidOptions(
306 "rank + oversampling overflows usize",
307 ))?
308 .min(rows)
309 .min(cols);
310 if ell == 0 {
311 return Err(FactorizeError::InvalidOptions(
312 "RSVD requires nonempty matrix dimensions",
313 ));
314 }
315 cols.checked_mul(ell)
316 .and_then(|len| len.checked_mul(if t.is_f64() { 8 } else { 16 }))
317 .filter(|&bytes| bytes <= isize::MAX as usize)
318 .ok_or(FactorizeError::InvalidOptions(
319 "Gaussian sketch byte length overflows",
320 ))?;
321 let tensor = match route {
322 Route::Eager(Some(context)) => t.adopt_into(context).map_err(computation)?,
323 _ => t.clone(),
324 };
325 Ok(PreparedRange { tensor, right, ell })
326}
327
328fn range<R: Rng + ?Sized>(
329 prepared: &PreparedRange,
330 left: &[DynIndex],
331 options: &RangeOptions,
332 rng: &mut R,
333 route: &mut Route<'_, '_>,
334 timings: &mut RsvdTimings,
335) -> Result<IdxTensor, FactorizeError> {
336 let t = &prepared.tensor;
337 let right = &prepared.right;
338 let mut sketch_indices = right.to_vec();
339 sketch_indices.push(DynIndex::new_bond(prepared.ell).map_err(computation)?);
340 let omega = if t.is_f64() {
341 route.gaussian::<f64, _>(t, sketch_indices, rng)
342 } else {
343 route.gaussian::<Complex64, _>(t, sketch_indices, rng)
344 }?;
345 let started = Instant::now();
346 let y = route.contract(t, &omega)?;
347 timings.gemm += started.elapsed();
348 let started = Instant::now();
349 let mut q = route.qr(&y, left)?;
350 timings.qr += started.elapsed();
351 for _ in 0..options.power_iterations {
352 let started = Instant::now();
353 let z =
354 route.contract_options(t, &q, PairwiseContractionOptions::new().with_lhs_conj(true))?;
355 timings.gemm += started.elapsed();
356 let started = Instant::now();
357 let z = route.qr(&z, right)?;
358 timings.qr += started.elapsed();
359 let started = Instant::now();
360 let y = route.contract(t, &z)?;
361 timings.gemm += started.elapsed();
362 let started = Instant::now();
363 q = route.qr(&y, left)?;
364 timings.qr += started.elapsed();
365 }
366 Ok(q)
367}
368
369/// Find an orthonormal basis for a dense tensor's left-index range.
370///
371/// `left_inds` must be a nonempty proper subset of the full index values.
372/// Returns Q with these indices and a fresh bond of dimension
373/// `min(rank + options.oversampling, m, n)`. `Q Q†` is a bond projector.
374/// Consumes Gaussian samples directly from `rng`; global QR defaults are ignored.
375/// Only dense `f64` and `Complex64` are supported; `f32` and `Complex32` (c32)
376/// return [`FactorizeError::UnsupportedStorage`] before advancing the RNG.
377///
378/// # Errors
379/// Returns [`FactorizeError`] for zero rank, invalid/duplicate indices, size
380/// overflow, unsupported storage/dtype, or a backend failure.
381///
382/// # Examples
383/// ```
384/// use rand::SeedableRng;
385/// use rand_chacha::ChaCha8Rng;
386/// use tensor4all_core::{randomized_range, DynIndex, IdxTensor, RangeOptions, TensorContractionLike};
387/// let i = DynIndex::new_dyn(2);
388/// let j = DynIndex::new_dyn(2);
389/// let a = IdxTensor::from_dense(vec![i.clone(), j], vec![3., 0., 0., 0.])?;
390/// let mut rng = ChaCha8Rng::seed_from_u64(11);
391/// let q = randomized_range(&a, &[i], 1, &RangeOptions { oversampling: 0, power_iterations: 0 }, &mut rng)?;
392/// let projected = q.contract_pair(&q.conj().contract_pair(&a)?)?;
393/// assert!(a.sub(&projected)?.maxabs()? < 1e-12);
394/// # Ok::<(), Box<dyn std::error::Error>>(())
395/// ```
396pub fn randomized_range<R: Rng + ?Sized>(
397 t: &IdxTensor,
398 left_inds: &[DynIndex],
399 rank: usize,
400 options: &RangeOptions,
401 rng: &mut R,
402) -> Result<IdxTensor, FactorizeError> {
403 let mut route = Route::Eager(None);
404 let prepared = prepare(t, left_inds, rank, options, &route)?;
405 range(
406 &prepared,
407 left_inds,
408 options,
409 rng,
410 &mut route,
411 &mut RsvdTimings::default(),
412 )
413}
414
415/// Find a Gaussian range basis in a caller-owned execution context.
416///
417/// The rank, index split, oversampling and return contract match
418/// [`randomized_range`]. Inputs and sketches remain in `context`; validation
419/// precedes RNG advancement. Use zero oversampling for a rank-`rank` projector.
420///
421/// # Errors
422/// Returns [`FactorizeError`] for invalid rank/indices, unsupported storage,
423/// foreign contexts, size overflow, or a backend failure.
424///
425/// # Examples
426/// ```
427/// use std::sync::Arc;
428/// use rand::SeedableRng;
429/// use rand_chacha::ChaCha8Rng;
430/// use tensor4all_core::{randomized_range_in, DynIndex, ExecutionContext, IdxTensor, RangeOptions};
431/// use tensor4all_tensorbackend::{CpuBackend, CpuExecutionContext};
432/// let context = ExecutionContext::Cpu(Arc::new(CpuExecutionContext::from_backend(CpuBackend::with_threads(1)?)));
433/// let i = DynIndex::new_dyn(2);
434/// let j = DynIndex::new_dyn(2);
435/// let a = IdxTensor::from_dense_in(&context, vec![i.clone(), j], vec![3., 0., 0., 0.])?;
436/// let mut rng = ChaCha8Rng::seed_from_u64(11);
437/// let options = RangeOptions { oversampling: 0, power_iterations: 0 };
438/// let q = randomized_range_in(&a, &[i], 1, &options, &mut rng, &context)?;
439/// let values = q.to_vec::<f64>()?;
440/// assert!((values[0].abs() - 1.).abs() < 1e-12 && values[1].abs() < 1e-12);
441/// # Ok::<(), Box<dyn std::error::Error>>(())
442/// ```
443pub fn randomized_range_in<R: Rng + ?Sized>(
444 t: &IdxTensor,
445 left_inds: &[DynIndex],
446 rank: usize,
447 options: &RangeOptions,
448 rng: &mut R,
449 context: &ExecutionContext,
450) -> Result<IdxTensor, FactorizeError> {
451 let mut route = Route::Eager(Some(context));
452 let prepared = prepare(t, left_inds, rank, options, &route)?;
453 range(
454 &prepared,
455 left_inds,
456 options,
457 rng,
458 &mut route,
459 &mut RsvdTimings::default(),
460 )
461}
462
463/// Find a Gaussian range basis on a caller-held plain session.
464///
465/// Same rank, sketch and index contract as [`randomized_range`]. Numeric work
466/// stays on `session`; the returned Q is untracked host storage. Global QR
467/// defaults are ignored, and no eager runtime or nested session is entered.
468///
469/// # Errors
470/// Returns [`FactorizeError`] for tracked/resident or unsupported operands,
471/// invalid rank/indices, size overflow, or a backend failure.
472///
473/// # Examples
474/// ```
475/// use rand::SeedableRng;
476/// use rand_chacha::ChaCha8Rng;
477/// use tensor4all_core::{randomized_range_on_session, DynIndex, IdxTensor, RangeOptions};
478/// use tensor4all_tensorbackend::{explicit::Session, CpuBackend};
479/// let i = DynIndex::new_dyn(2);
480/// let j = DynIndex::new_dyn(2);
481/// let a = IdxTensor::from_dense(vec![i.clone(), j], vec![3., 0., 0., 0.])?;
482/// let mut rng = ChaCha8Rng::seed_from_u64(11);
483/// let mut backend = CpuBackend::with_threads(1)?;
484/// let q = {
485/// let mut session = Session::new(backend.engine_mut());
486/// randomized_range_on_session(&mut session, &a, &[i], 1,
487/// &RangeOptions { oversampling: 0, power_iterations: 0 }, &mut rng)?
488/// };
489/// let values = q.to_vec::<f64>()?;
490/// assert!((values[0].abs() - 1.).abs() < 1e-12 && values[1].abs() < 1e-12);
491/// # Ok::<(), Box<dyn std::error::Error>>(())
492/// ```
493pub fn randomized_range_on_session<R: Rng + ?Sized>(
494 session: &mut Session<'_>,
495 t: &IdxTensor,
496 left_inds: &[DynIndex],
497 rank: usize,
498 options: &RangeOptions,
499 rng: &mut R,
500) -> Result<IdxTensor, FactorizeError> {
501 let mut route = Route::Session(session);
502 let prepared = prepare(t, left_inds, rank, options, &route)?;
503 range(
504 &prepared,
505 left_inds,
506 options,
507 rng,
508 &mut route,
509 &mut RsvdTimings::default(),
510 )
511}
512
513pub(crate) fn svd_result<R: Rng + ?Sized>(
514 t: &IdxTensor,
515 left_inds: &[DynIndex],
516 options: &RsvdOptions,
517 rng: &mut R,
518 route: &mut Route<'_, '_>,
519) -> Result<(SvdFactorizeResult, RsvdTimings), FactorizeError> {
520 let total = Instant::now();
521 let mut timings = RsvdTimings::default();
522 let prepared = prepare(t, left_inds, options.max_bond_dim, &options.range, route)?;
523 let t = &prepared.tensor;
524 let q = range(
525 &prepared,
526 left_inds,
527 &options.range,
528 rng,
529 route,
530 &mut timings,
531 )?;
532 let bond = q
533 .indices()
534 .last()
535 .cloned()
536 .ok_or(FactorizeError::InvalidOptions("QR returned no bond"))?;
537 let started = Instant::now();
538 let projected =
539 route.contract_options(&q, t, PairwiseContractionOptions::new().with_lhs_conj(true))?;
540 timings.gemm += started.elapsed();
541 let started = Instant::now();
542 let mut result = route.svd(&projected, &[bond], options.max_bond_dim)?;
543 timings.small_svd += started.elapsed();
544 let started = Instant::now();
545 result.u = route.contract(&q, &result.u)?;
546 timings.gemm += started.elapsed();
547 timings.total = total.elapsed();
548 Ok((result, timings))
549}
550
551/// Compute a fixed-rank randomized SVD of a materialized local tensor.
552///
553/// The index split and sketch have the same contract as [`randomized_range`].
554/// Returns directly contractible U, S, V† with `min(max_bond_dim, m, n)`
555/// triplets. The projected singular values do not certify the full-input error.
556/// Uses the supplied RNG directly and ignores global truncation defaults.
557/// Supports dense `f64`/`Complex64`; `f32`/`Complex32` (c32) are unsupported.
558///
559/// # Errors
560/// Returns [`FactorizeError`] for invalid rank/indices, size overflow,
561/// unsupported storage/dtype, or contraction/decomposition failure.
562///
563/// # Examples
564/// ```
565/// use rand::SeedableRng;
566/// use rand_chacha::ChaCha8Rng;
567/// use tensor4all_core::{randomized_svd, DynIndex, IdxTensor, RsvdOptions, TensorContractionLike};
568/// let i = DynIndex::new_dyn(2);
569/// let j = DynIndex::new_dyn(2);
570/// let a = IdxTensor::from_dense(vec![i.clone(), j], vec![3., 0., 0., 0.])?;
571/// let mut rng = ChaCha8Rng::seed_from_u64(11);
572/// let result = randomized_svd(&a, &[i], &RsvdOptions::new(1), &mut rng)?;
573/// let reconstructed = result.u.contract_pair(&result.s)?.contract_pair(&result.vh)?;
574/// assert!(a.sub(&reconstructed)?.maxabs()? < 1e-12);
575/// # Ok::<(), Box<dyn std::error::Error>>(())
576/// ```
577pub fn randomized_svd<R: Rng + ?Sized>(
578 t: &IdxTensor,
579 left_inds: &[DynIndex],
580 options: &RsvdOptions,
581 rng: &mut R,
582) -> Result<RsvdResult, FactorizeError> {
583 let (result, timings) = svd_result(t, left_inds, options, rng, &mut Route::Eager(None))?;
584 let vh = result
585 .vh
586 .replaceind(&result.bond_index, &result.s.indices()[1])
587 .map_err(computation)?;
588 Ok(RsvdResult {
589 u: result.u,
590 s: result.s,
591 vh,
592 singular_values: result.singular_values,
593 timings,
594 })
595}
596
597pub(crate) fn factorize<R: Rng + ?Sized>(
598 t: &IdxTensor,
599 left_inds: &[DynIndex],
600 options: &FactorizeOptions,
601 rng: &mut R,
602 route: &mut Route<'_, '_>,
603) -> Result<FactorizeResult<IdxTensor>, FactorizeError> {
604 options.validate()?;
605 let rank = options
606 .max_bond_dim
607 .ok_or(FactorizeError::InvalidOptions("RSVD requires max_bond_dim"))?;
608 let (result, _) = svd_result(
609 t,
610 left_inds,
611 &RsvdOptions {
612 max_bond_dim: rank,
613 range: options.randomized,
614 },
615 rng,
616 route,
617 )?;
618 crate::defaults::factorize::assemble_svd_factors(result, options.canonical, &mut |a, b| {
619 route.contract(a, b)
620 })
621}