line 2 is trivially convertable to vectorized form, just with torch RNG
I don’t remember if line 3 if easily vectorizable - there is scatter_add_, but you may need to convert to 1d view/indexes (i1*size1+i2). Or do that scattering loop on cpu, that will be faster.