Hi
I would like to create a (n,c,h,w) self index tensor as below: (use (2,3,4,5) as example)

x = torch.tensor(range(5))
x = torch.stack((x,x,x,x), 0)
x = torch.stack((x,x,x),0)
x = torch.stack((x,x),0)

But how to generalize to (n,c,h,w)?
no problem with first step:
x = torch.tensor(range(w))
but how to do stack of x with h time?
or is there other way to create such tensor without looping?

If you want the tensor to have one column repeated all over, you can use expand:

x = torch.arange(5)[None, None, None, :].expand(2, 3, 4, 5)

or, if you prefer,

x = torch.arange(5).view(1, 1, 1, -1).expand(2, 3, 4, 5)

Both create singleton dimensions where you want the expansion to go to (with indexing or view) and then expand (with stride 0) to the desired size (similar to what is done in broadcasting).
If you want the exact same result (without strides) as the stacking, you can add .contiguous() at the end.