@@ -562,6 +562,89 @@ impl SparseCsr {
562562 }
563563}
564564
565+ /// A CSR sparsity pattern whose values are a learnable [`Tensor`]: `Y = S X` is differentiable with respect to both the
566+ /// non-zero values (the gradient of a value is the dot product of the matching row of `dY` and row of `X`, i.e. an SDDMM) and
567+ /// the dense operand (`S^T dY`). Use it for sparse layers, pruned weights and graph attention coefficients.
568+ #[ derive( Clone ) ]
569+ pub struct SparseCsrParam {
570+ pub row_ptr : Vec < usize > ,
571+ pub col_idx : Vec < usize > ,
572+ pub shape : [ usize ; 2 ] ,
573+ /// The `nnz` values, in CSR order; mark it `requires_grad` to learn them.
574+ pub values : Tensor ,
575+ }
576+
577+ impl SparseCsrParam {
578+ /// Takes the pattern of `csr` and its values as a tensor of dtype `dtype` (F32 or F64).
579+ pub fn from_csr ( csr : & SparseCsr , dtype : DType , requires_grad : bool ) -> Result < Self > {
580+ csr. check_valid ( ) ?;
581+ let v = Tensor :: from_slice ( & csr. values , & [ csr. values . len ( ) ] ) ?. to_dtype ( dtype) ?;
582+ Ok ( Self { row_ptr : csr. row_ptr . clone ( ) , col_idx : csr. col_idx . clone ( ) , shape : csr. shape , values : if requires_grad { v. requires_grad_ ( true ) } else { v } } )
583+ }
584+
585+ pub fn nnz ( & self ) -> usize {
586+ self . col_idx . len ( )
587+ }
588+
589+ /// The matrix with the current values (detached).
590+ pub fn to_csr ( & self ) -> Result < SparseCsr > {
591+ SparseCsr :: new ( self . row_ptr . clone ( ) , self . col_idx . clone ( ) , self . values . detach ( ) . to_dtype ( DType :: F64 ) ?. to_vec :: < f64 > ( ) ?, self . shape )
592+ }
593+
594+ pub fn to_dense ( & self , dtype : DType , device : & Device ) -> Result < Tensor > {
595+ self . to_csr ( ) ?. to_dense ( dtype, device)
596+ }
597+
598+ /// `Y = S X` for a dense `[K, N]` operand.
599+ pub fn spmm ( & self , dense : & Tensor ) -> Result < Tensor > {
600+ let [ m, k] = self . shape ;
601+ if dense. ndim ( ) != 2 || dense. shape ( ) [ 0 ] != k || self . values . numel ( ) != self . nnz ( ) {
602+ return Err ( Error :: ShapeMismatch { op : "SparseCsrParam::spmm" , expected : vec ! [ k, dense. shape( ) . get( 1 ) . copied( ) . unwrap_or( 0 ) ] , got : dense. shape ( ) . to_vec ( ) } ) ;
603+ }
604+ if dense. dtype ( ) != self . values . dtype ( ) {
605+ return Err ( Error :: DTypeMismatch { op : "SparseCsrParam::spmm" , expected : self . values . dtype ( ) , got : dense. dtype ( ) } ) ;
606+ }
607+ let n = dense. shape ( ) [ 1 ] ;
608+ let vals = self . values . detach ( ) . to_dtype ( DType :: F64 ) ?. to_vec :: < f64 > ( ) ?;
609+ let x = dense. detach ( ) . contiguous ( ) ?. to_dtype ( DType :: F64 ) ?. to_vec :: < f64 > ( ) ?;
610+ let mut y = vec ! [ 0.0f64 ; crate :: limits:: check_elements( "SparseCsrParam::spmm" , & [ m, n] ) ?] ;
611+ for r in 0 ..m {
612+ for e in self . row_ptr [ r] ..self . row_ptr [ r + 1 ] {
613+ let ( c, v) = ( self . col_idx [ e] , vals[ e] ) ;
614+ for j in 0 ..n {
615+ y[ r * n + j] += v * x[ c * n + j] ;
616+ }
617+ }
618+ }
619+ let layout = Layout :: contiguous ( vec ! [ m, n] ) ;
620+ let storage = Storage :: new_cpu ( CpuStorage :: F64 ( y) . to_dtype ( & layout, dense. dtype ( ) ) ?) . to_device ( & layout, & dense. device ( ) ) ?;
621+ let ( row_ptr, col_idx) = ( self . row_ptr . clone ( ) , self . col_idx . clone ( ) ) ;
622+ let ( dense_c, vals_dtype, dense_dtype) = ( dense. detach ( ) , self . values . dtype ( ) , dense. dtype ( ) ) ;
623+ Ok ( Tensor :: from_op ( storage, layout, "spmm_param" , vec ! [ self . values. clone( ) , dense. clone( ) ] , move |g| {
624+ let gy = g. contiguous ( ) ?. to_dtype ( DType :: F64 ) ?. to_vec :: < f64 > ( ) ?;
625+ let xv = dense_c. contiguous ( ) ?. to_dtype ( DType :: F64 ) ?. to_vec :: < f64 > ( ) ?;
626+ // d values[e] = sum_j dY[r, j] * X[c, j]
627+ let mut gv = vec ! [ 0.0f64 ; col_idx. len( ) ] ;
628+ // d X[c, :] += values[e] * dY[r, :]
629+ let mut gx = vec ! [ 0.0f64 ; k * n] ;
630+ for r in 0 ..m {
631+ for e in row_ptr[ r] ..row_ptr[ r + 1 ] {
632+ let c = col_idx[ e] ;
633+ let mut acc = 0.0 ;
634+ for j in 0 ..n {
635+ acc += gy[ r * n + j] * xv[ c * n + j] ;
636+ gx[ c * n + j] += vals[ e] * gy[ r * n + j] ;
637+ }
638+ gv[ e] = acc;
639+ }
640+ }
641+ let dv = Tensor :: from_slice ( & gv, & [ gv. len ( ) ] ) ?. to_dtype ( vals_dtype) ?;
642+ let dx = Tensor :: from_slice ( & gx, & [ k, n] ) ?. to_dtype ( dense_dtype) ?;
643+ Ok ( vec ! [ Some ( dv) , Some ( dx) ] )
644+ } ) )
645+ }
646+ }
647+
565648#[ cfg( test) ]
566649mod tests {
567650 use super :: * ;
@@ -799,3 +882,49 @@ mod tests {
799882 assert_close ( & coo_d, & [ 14.0 , 12.0 , 15.0 , 18.0 ] , 1e-12 , "coo spspmm" ) ;
800883 }
801884}
885+
886+ #[ cfg( test) ]
887+ mod param_tests {
888+ use super :: * ;
889+
890+ #[ test]
891+ fn sparse_values_and_dense_operand_get_the_dense_gradients ( ) {
892+ crate :: rng:: manual_seed ( 2 ) ;
893+ // a random 5 x 6 pattern with ~40% non-zeros
894+ let dense = Tensor :: randn ( & [ 5 , 6 ] ) . unwrap ( ) ;
895+ let mask = Tensor :: rand_uniform ( & [ 5 , 6 ] , 0.0 , 1.0 ) . unwrap ( ) . to_vec :: < f32 > ( ) . unwrap ( ) ;
896+ let masked: Vec < f32 > = dense. to_vec :: < f32 > ( ) . unwrap ( ) . iter ( ) . zip ( & mask) . map ( |( v, m) | if * m < 0.4 { * v } else { 0.0 } ) . collect ( ) ;
897+ let d = Tensor :: from_slice ( & masked, & [ 5 , 6 ] ) . unwrap ( ) ;
898+ let csr = SparseCsr :: from_dense ( & d, 0.0 ) . unwrap ( ) ;
899+ assert ! ( csr. nnz( ) > 3 && csr. nnz( ) < 30 ) ;
900+ for dt in [ DType :: F32 , DType :: F64 ] {
901+ let s = SparseCsrParam :: from_csr ( & csr, dt, true ) . unwrap ( ) ;
902+ let x = Tensor :: randn ( & [ 6 , 4 ] ) . unwrap ( ) . to_dtype ( dt) . unwrap ( ) . detach ( ) . requires_grad_ ( true ) ;
903+ let w = Tensor :: randn ( & [ 5 , 4 ] ) . unwrap ( ) . to_dtype ( dt) . unwrap ( ) ;
904+ let y = s. spmm ( & x) . unwrap ( ) ;
905+ y. mul ( & w) . unwrap ( ) . sum ( ) . unwrap ( ) . backward ( ) . unwrap ( ) ;
906+ // reference: the same product with the dense matrix
907+ let dd = d. to_dtype ( dt) . unwrap ( ) . detach ( ) . requires_grad_ ( true ) ;
908+ let xr = x. detach ( ) . requires_grad_ ( true ) ;
909+ let yr = dd. matmul ( & xr) . unwrap ( ) ;
910+ yr. mul ( & w) . unwrap ( ) . sum ( ) . unwrap ( ) . backward ( ) . unwrap ( ) ;
911+ let tol = if dt == DType :: F32 { 1e-4 } else { 1e-10 } ;
912+ assert ! ( y. allclose( & yr, tol, tol) . unwrap( ) ) ;
913+ assert ! ( x. grad( ) . unwrap( ) . allclose( & xr. grad( ) . unwrap( ) , tol, tol) . unwrap( ) ) ;
914+ // gradient of each stored value = the dense gradient at its (row, col)
915+ let gd = dd. grad ( ) . unwrap ( ) . to_dtype ( DType :: F64 ) . unwrap ( ) . to_vec :: < f64 > ( ) . unwrap ( ) ;
916+ let gv = s. values . grad ( ) . unwrap ( ) . to_dtype ( DType :: F64 ) . unwrap ( ) . to_vec :: < f64 > ( ) . unwrap ( ) ;
917+ let mut e = 0 ;
918+ for r in 0 ..5 {
919+ for k in csr. row_ptr [ r] ..csr. row_ptr [ r + 1 ] {
920+ assert ! ( ( gv[ e] - gd[ r * 6 + csr. col_idx[ k] ] ) . abs( ) < tol. max( 1e-9 ) * 10.0 , "value {e}: {} vs {}" , gv[ e] , gd[ r * 6 + csr. col_idx[ k] ] ) ;
921+ e += 1 ;
922+ }
923+ }
924+ assert_eq ! ( e, s. nnz( ) ) ;
925+ }
926+ // dtype mismatch is rejected
927+ let s = SparseCsrParam :: from_csr ( & csr, DType :: F32 , false ) . unwrap ( ) ;
928+ assert ! ( s. spmm( & Tensor :: randn( & [ 6 , 2 ] ) . unwrap( ) . to_dtype( DType :: F64 ) . unwrap( ) ) . is_err( ) ) ;
929+ }
930+ }
0 commit comments