lschoe / mpyc

MPyC: Multiparty Computation in Python
MIT License
367 stars 76 forks source link

Strange behavior with array created from np.zeros #61

Closed winnnnnny closed 1 year ago

winnnnnny commented 1 year ago

Hello, sorry for disturbing you.

I observed that when an array is created from np.zeros with mpc.SecInt and one is subtracted from it, it is still printed out as zeros instead of negative ones. In addition, when two is added to it, it is printed out as ones instead of twos.

Here is an example.

from mpyc.runtime import mpc
from mpyc.numpy import np
from mpyc import finfields
async def main():
    f = mpc.SecInt(32)
    a = np.array([[-1, -2, -3, -4], [0, 0, 0, 0], [1, 1, 1, 1], [1, 2, 3, 4]])
    F_a = f.array(a)
    print('F_a', await mpc.output(F_a))
    F_b = f.array(np.zeros((4,4)))
    F_b = F_b - 1
    print('-1', await mpc.output(F_b))
    F_b = F_b + 1
    print('0', await mpc.output(F_b))
    F_b = F_b + 1
    print('1', await mpc.output(F_b))

mpc.run(main())

Here is the result.

F_a [[-1 -2 -3 -4]
 [0 0 0 0]
 [1 1 1 1]
 [1 2 3 4]]
-1 [[0.0 0.0 0.0 0.0]
 [0.0 0.0 0.0 0.0]
 [0.0 0.0 0.0 0.0]
 [0.0 0.0 0.0 0.0]]
0 [[0.0 0.0 0.0 0.0]
 [0.0 0.0 0.0 0.0]
 [0.0 0.0 0.0 0.0]
 [0.0 0.0 0.0 0.0]]
1 [[1.0 1.0 1.0 1.0]
 [1.0 1.0 1.0 1.0]
 [1.0 1.0 1.0 1.0]
 [1.0 1.0 1.0 1.0]]

When the zero array is created with finfields.GF, the array with negative ones can printed out successfully.

from mpyc.runtime import mpc
from mpyc.numpy import np
from mpyc import finfields
async def main():
    f = finfields.GF(101)
    a = np.array([[-1, -2, -3, -4], [0, 0, 0, 0], [1, 1, 1, 1], [1, 2, 3, 4]])
    F_a = f.array(a)
    print('F_a', await mpc.output(F_a))
    F_b = f.array(np.zeros((4,4)))
    F_b = F_b - 1
    print('-1', await mpc.output(F_b))
    F_b = F_b + 1
    print('0', await mpc.output(F_b))
    F_b = F_b + 1
    print('1', await mpc.output(F_b))

mpc.run(main())

The result is shown below.

F_a [[-1 -2 -3 -4]
 [0 0 0 0]
 [1 1 1 1]
 [1 2 3 4]]
-1 [[-1.0 -1.0 -1.0 -1.0]
 [-1.0 -1.0 -1.0 -1.0]
 [-1.0 -1.0 -1.0 -1.0]
 [-1.0 -1.0 -1.0 -1.0]]
0 [[0.0 0.0 0.0 0.0]
 [0.0 0.0 0.0 0.0]
 [0.0 0.0 0.0 0.0]
 [0.0 0.0 0.0 0.0]]
1 [[1.0 1.0 1.0 1.0]
 [1.0 1.0 1.0 1.0]
 [1.0 1.0 1.0 1.0]
 [1.0 1.0 1.0 1.0]]

I cannot find the reason behind this behavior. Could you help me to explain this?

lschoe commented 1 year ago

The default dtype for functions like np.zeros is float, and that causes the unexpected behavior. To fix this use a call like np.zeros((4, 4), dtype=int) or np.zeros((4, 4), dtype=object).

If you search for np.zeros in the mpycrepo you'll find a couple of examples.

There is no warning yet for this use of float arrays, still TODO: https://github.com/lschoe/mpyc/blob/867cc0a957fe606aaba09001bb85be17b8b53395/mpyc/finfields.py#L712-L717

winnnnnny commented 1 year ago

Got it! Thank you for your replying.