Cut-paste a segment into a region that satisfy a condition

Hi,
I have two same-size tensors that are binary masks: A, B
I want to relocate the mask that I have in B, in the region(randomly select any location and use it as an anchor) where A’s mask is located, but I don’t know how to implement it in pytorch.

e.g.
A:
[0 0 0 0 0 0 ]
[0 0 1 1 0 0 ]
[0 0 1 1 0 0 ]
[0 0 0 0 0 0 ]

B:
[0 0 0 0 0 0 ]
[0 0 0 0 0 0 ]
[0 0 0 0 1 0 ]
[0 0 0 0 0 1 ]

C=f(A,B):
[0 0 0 0 0 0 ]
[0 0 1 0 0 0 ]
[0 0 0 1 0 0 ]
[0 0 0 0 0 0 ]

or
[0 0 0 0 0 0 ]
[0 0 0 1 0 0 ]
[0 0 0 0 1 0 ]
[0 0 0 0 0 0 ]

This is the numpy version of it.

A_boundary=np.where(A==1)
x_pos=np.random.choice(A_boundary[0])
y_pos=A_boundary[1][np.random.choice(np.where(A_boundary[0]==x_pos)[0])]
candid_mask = np.where(candid_segment_i == 1)
x_seg=np.subtract(candid_mask[0],np.min(candid_mask[0]))
y_seg=np.subtract(candid_mask[1], np.min(candid_mask[1]))
for replace_mask in range(len(candid_mask[0])):
    mask[x_pos+x_seg[replace_mask],y_pos+y_seg[replace_mask]]=1