def calc_gradx_pad(pad, in_siz, out_siz, stride, ksize):
    """Calculate padding width for conv2d_gradx.

    Args:
        pad: Padding method, "SAME", "VALID", or manually speicified.
        in_siz: Size of the input to `conv2d_gradx` (i.e. size of `dy`).
        out_siz: Size of the output of `conv2d_gradx` (i.e. size of `dx`).
        stride: Length of the convolution stride.
        ksize: Kernel size.

    Returns:
        pad_: Actual padding width.
    """
    if pad == 'SAME':
        out_siz_min = (in_siz - 1) * stride + 1
        p = out_siz + ksize - 1 - out_siz_min
        p = max(p, 0)
        p = min(p, (ksize - 1) * 2)
        return p
    elif pad == 'VALID':
        return (ksize - 1) * 2
    else:
        return pad