need to implement gradient-based optimization of k