import torch


def clamp_preserve_gradients(x: torch.Tensor, min: float, max: float) -> torch.Tensor:
    """clamp the tensor while preserving gradients in the clamped region."""
    return x + (x.clamp(min, max) - x).detach()