Gradient-Based Dimension Reduction for Bayesian Inverse Problems and Simulation-Based Inference