lattigo icon indicating copy to clipboard operation
lattigo copied to clipboard

Bug[ring]: ´ring.UniformSampler´ bad sampling

Open Pro7ech opened this issue 1 year ago • 2 comments

The following code should produce polynomials with independent and identically distributed coefficients but ends up producing polynomials with overlapping coefficients:

package main


import(
	"fmt"
	"github.com/tuneinsight/lattigo/v5/core/rlwe"
	"github.com/tuneinsight/lattigo/v5/utils/sampling"
	"github.com/tuneinsight/lattigo/v5/ring"
)

func main(){
	params, err := rlwe.NewParametersFromLiteral(rlwe.ParametersLiteral{
		LogN: 10,
		LogQ: []int{50},
	})

	if err != nil{
		panic(err)
	}

	prng, _ := sampling.NewKeyedPRNG([]byte{0x02})
	uniform := ring.NewUniformSampler(prng, params.RingQ())
	_ = uniform.ReadNew()

	a0 := uniform.AtLevel(0).ReadNew()
	a1 := uniform.AtLevel(0).ReadNew()

	m := map[uint64]int{}
	for i, v := range a0.Coeffs[0]{
		m[v] = i
	}

	for i, v := range a1.Coeffs[0]{
		if j, ok := m[v]; ok{
			fmt.Println(a0.Coeffs[0][j:j+8])
			fmt.Println(a1.Coeffs[0][i:i+8])
			break
		}
	}
}

Pro7ech avatar May 12 '24 19:05 Pro7ech

Hey, the problem in the provided snippet is the reuse of an old sampler:

uniform.AtLevel(0) returns a new sampler copy from uniform which also copies the PRNG buffer which provides unused bytes to the next invocation for efficiency reasons.

uniform := ring.NewUniformSampler(prng, params.RingQ())
_ = uniform.ReadNew() // initalize PRNG buffer (1)

a0 := uniform.AtLevel(0).ReadNew() // reuses partially the same buffer from (1)
a1 := uniform.AtLevel(0).ReadNew() // reuses partially the same buffer from (1)

This is the reason coefficients in a0 and a1 overlap. One solution could be to reset the buffer in AtLevel but this would make repeated calls a bit slower. Otherwise, this problem can be avoided with:

uniform := ring.NewUniformSampler(prng, params.RingQ())
_ = uniform.ReadNew()

uniform = uniform.AtLevel(0).(*ring.UniformSampler)
a0 := uniform.ReadNew()

uniform = uniform.AtLevel(0).(*ring.UniformSampler)
a1 := uniform.ReadNew()
```

qantik avatar Jun 04 '24 14:06 qantik

The method AtLevel is a convenience method that is supposed to return an instance of the same sampler, but that will sample at a given level. It is expected that the two instances will share the same internal memory and cannot be used concurrently. So this issue shouldn't happen with the code snippet I provided.

Pro7ech avatar Jun 07 '24 06:06 Pro7ech