Oh I get it, I convert x to nn.Parameter and x.grad has the grad:
x = torch.rand((B, C, W, H), requires_grad=True)
x = nn.Parameter(x) # x should be the parameter
...
c = globalContrast(x)
y = torch.sum(c)
print(x.grad) # then get sth instead of None!

and I found your suggestion of  x.retain_grad() is better, thanks!