Add missing .to_sparse(ndim) gradient (#58413)
Summary:
Fixes https://github.com/pytorch/pytorch/issues/46720, extends PR https://github.com/pytorch/pytorch/issues/46825 by adding test requested in [this comment](https://github.com/pytorch/pytorch/pull/46825#issuecomment-842304079).
Pull Request resolved: https://github.com/pytorch/pytorch/pull/58413
Reviewed By: ailzhang
Differential Revision: D28540550
Pulled By: albanD
fbshipit-source-id: d7e292e09b5402336c43844ee233b83b0a095035