The following code is inspired by @googlebot:
def rand_perm(n, K):
    o = torch.arange(0, n)
    d = torch.randint_like(o, low=-K, high=K + 1)
    return torch.argsort(o + d)

but it does not actually meet my demands.