aby3.py 24.5 KB
Newer Older
J
jhjiangcs 已提交
1
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
J
jingqinghe 已提交
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
This module provide data utilities for ABY3 protocol, including
data encryption, decryption, share save and loading.
"""
import os
import numpy as np
import six
import paddle
import paddle.fluid as fluid
import mpc_data_utils as mdu
J
jhjiangcs 已提交
24
from ..layers import __all__ as all_ops
J
jingqinghe 已提交
25 26 27 28 29 30 31 32 33 34 35 36 37 38

__all__ = [
    'encrypt',
    'decrypt',
    'make_shares',
    'get_aby3_shares',
    'save_aby3_shares',
    'load_aby3_shares',
    'reconstruct',
    'batch',
    'encrypt_model',
    'decrypt_model',
]

J
jhjiangcs 已提交
39 40 41 42 43 44 45
# operators that should be skipped when encrypt and decrypt
op_to_skip = ['feed', 'fetch', 'scale', 'mpc_init']
# operators that are supported currently for model encryption and decryption
supported_mpc_ops = all_ops + ['fill_constant', 'sgd'] + op_to_skip
# variables that used as plain variables and need no encryption
plain_vars = ['learning_rate_0']

J
jingqinghe 已提交
46 47 48 49 50 51
SHARE_NUM = 3
ABY3_SHARE_DIM = 2
ABY3_MODEL_NAME = "__model__.aby3"
MODEL_NAME = "__model__"
MODEL_SHARE_DIR = "model_share"
MPC_OP_PREFIX = "mpc_"
J
jhjiangcs 已提交
52 53 54
# the MPC value of plain value 1, which is used for
# default value of fill_constant OP
MPC_ONE_SHARE = mdu.mpc_one_share
J
jingqinghe 已提交
55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87


def encrypt(number):
    """
    Encrypts the plaintext number into three secret shares
    Args:
        number: float, the number to share
    Returns:
        three shares of input number
    """
    try:
        return mdu.share(number)
    except Exception as e:
        raise RuntimeError(e.message)


def decrypt(shares):
    """
    Reveal plaintext value from raw secret shares
    Args:
        shares: shares to reveal from (list)
    Return:
       the plaintext number (float)
    """
    try:
        return mdu.reveal(shares)
    except Exception as e:
        raise RuntimeError(e.message)


def make_shares(num_array):
    """
    Create raw shares for an array.
J
jhjiangcs 已提交
88

J
jingqinghe 已提交
89 90 91 92 93 94 95 96 97 98 99 100 101 102 103
    Args:
        num_array: the input data array
    Returns:
        3 shares of the num_array in type of ndarray
    Example:
        input array with shape [2, 2]: [[a, b], [c, d]]
        output shares with shape [3, 2, 2]:
        [[[a0, b0],
          [c0, d0]],
         [[a1, b1],
          [c1, d1]],
         [[a2, b2],
          [c2, d2]]]
    """
    old_size = num_array.size
J
update  
jingqinghe 已提交
104
    flat_num_array = num_array.reshape(old_size,)
J
jingqinghe 已提交
105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164
    new_shape = (SHARE_NUM, ) + num_array.shape
    result = np.empty((old_size, SHARE_NUM), dtype=np.int64)
    for idx in six.moves.range(0, old_size):
        result[idx] = encrypt(flat_num_array[idx])

    result = result.transpose(1, 0)
    result = result.reshape(new_shape)
    return result


def get_aby3_shares(shares, index):
    """
    Build ABY3 shares from raw shares according to index

    Args:
        shares: the input raw share array, expected to have shape of [3, ...]
        index: index of the ABY3 share, should be 0, 1, or 2
    Returns:
        ABY3 shares array corresponding to index, e.g.:
            [shares[index % 3], shares[(index + 1) %3]]
    Examples:
        input_shares: [3, 2, 4], where 3 is the dim of raw shares
        index: 0
        output: [input_shares[0], input_shares[1]], shape = (2, 3, 4)
    """
    if index < 0 or index >= SHARE_NUM:
        raise ValueError("Index should fall in (0..2) but now: {}".format(
            index))

    if shares.size % SHARE_NUM != 0 or shares.shape[0] != SHARE_NUM:
        raise ValueError("Shares to split has incorrect shape: {}".format(
            shares.shape))

    first = index % SHARE_NUM
    second = (index + 1) % SHARE_NUM
    return np.array([shares[first], shares[second]], dtype=np.int64)


def save_aby3_shares(share_reader, part_name):
    """
    Combine raw shares to ABY3 shares, and persists to files. Each ABY3 share will be
    put into the corresponding file, e.g., ${part_name}.part[0..2]. For example,
        [share0, share1] -> ${part_name}.part0
        [share1, share2] -> ${part_name}.part1
        [share2, share0] -> ${part_name}.part2

    Args:
        share_reader: iteratable function object returning a single array of raw shares
            in shape of [3, ...] each time
        part_name: file name
    Returns:
        files with names of ${part_name}.part[0..2]
    """
    exts = [".part0", ".part1", ".part2"]
    with open(part_name + exts[0], 'wb') as file0, \
        open(part_name + exts[1], 'wb') as file1, \
        open(part_name + exts[2], 'wb') as file2:

        files = [file0, file1, file2]
        for shares in share_reader():
J
update  
jingqinghe 已提交
165
            for idx in six.moves.range(0, 3): # 3 parts
J
jingqinghe 已提交
166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224
                share = get_aby3_shares(shares, idx)
                files[idx].write(share.tostring())


def load_aby3_shares(part_name, id, shape, append_share_dim=True):
    """
    Load ABY3 shares from file with name ${part_name}.part{id} in shape of ${shape}.

    Args:
        part_name and id: use to build the file name of ${part_name}.part{id}
        shape: the shape of output array
        append_share_dim: if true, a dim of 2 will be add to first of shape, which
            means two share slices are in row store
    Returns:
        iteratable function object returing a share array with give shape each time
    """
    if id not in (0, 1, 2):
        raise ValueError("Illegal id: {}, should 0, 1 or 2".format(id))

    if append_share_dim == True:
        shape = (ABY3_SHARE_DIM, ) + shape
    elif shape[0] != ABY3_SHARE_DIM or len(
            shape) < 2:  # an aby3 share has at least 2 dimensions
        raise ValueError("Illegal ABY3 share shape: {}".format(shape))

    ext = ".part{}".format(id)
    share_size = np.prod(shape) * 8  # size of int64 in bytes

    def reader():
        """
        internal reader
        """
        with open(part_name + ext, 'rb') as part_file:
            share = part_file.read(share_size)
            while share:
                yield np.frombuffer(share, dtype=np.int64).reshape(shape)
                share = part_file.read(share_size)

    return reader


def reconstruct(aby3_shares, type=np.float):
    """
    Reconstruct plaintext from ABY3 shares

    Args:
        aby3_shares: all the three ABY3 share arrays, each is of shape (2, dims), where the share slices
            are stored rowwise
        type: expected type of final result
    Returns:
        plaintext array reconstructed from the three ABY3 shares, with shape of (dims)
    Example:
        aby3_shares: three ABY3 shares of shape [2, 2]
            shares[0]: [[a0, b0], [a1, b1]]
            shares[1]: [[a1, b1], [a2, b2]]
            shares[2]: [[a2, b2], [a0, b0]]
        output:
            [a, b], where a = decrypt(a0, a1, a2), b = decrypt(b0, b1, b2)
    """
J
update  
jingqinghe 已提交
225
    if len(aby3_shares) != 3: # should collect shares from 3 parts
J
jingqinghe 已提交
226 227 228 229
        raise ValueError("Number of aby3 shares should be 3 but was: {}".
                         format(len(aby3_shares)))

    raw_shares = aby3_shares[:, 0]
J
update  
jingqinghe 已提交
230
    data_shape = raw_shares.shape[1:] # get rid of the first dim of [3, xxx]
J
jingqinghe 已提交
231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265
    data_size = np.prod(data_shape)
    row_first_raw_shares = raw_shares.reshape(3, data_size).transpose(1, 0)

    result = np.empty((data_size, ), dtype=type)
    for idx in six.moves.range(0, data_size):
        result[idx] = decrypt(row_first_raw_shares[idx].tolist())

    return result.reshape(data_shape)


def batch(reader, batch_size, drop_last=False):
    """
    A batch reader return a batch data meeting the shared data's shape.
    E.g., a batch arrays with shape (2, 3, 4) of batch_size will be transform to (2, batch_size, 3, 4),
    where the first dim 2 is the number of secret shares in ABY3.

    Args: see paddle.batch method
    Returns: the batched reader
    """
    paddle_batch_reader = paddle.batch(reader, batch_size, drop_last)

    def reshaped_batch_reader():
        """
        internal reader
        """
        r = paddle_batch_reader()
        for instance in r:
            perm = np.arange(0, len(np.array(instance).shape), 1)
            # permute the first two axes
            perm[0], perm[1] = perm[1], perm[0]
            yield np.transpose(instance, perm)

    return reshaped_batch_reader


J
jhjiangcs 已提交
266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355
def transpile(program=None):
    """
    Transpile Paddle program into MPC program.

    Args:
        program: The plain Paddle model program, default to
        default_main_program.

    Returns: The MPC program.
    """
    if program is None:
        program = fluid.default_main_program()

    place = fluid.CPUPlace()
    if program.num_blocks > 1:
        raise NotImplementedError(
            "The number of blocks in current main program"
            "is {}, which is not supported in this version."
            .format(program.num_blocks()))

    global_block = program.global_block()
    g_scope = fluid.global_scope()

    mpc_vars_names = _transpile_type_and_shape(block=global_block)

    # encrypt tensor values for each variable in mpc_var_names
    for mpc_var_name in mpc_vars_names:
        if g_scope.find_var(mpc_var_name) is not None:
            param = g_scope.find_var(mpc_var_name)
            param_tensor = np.array(param.get_tensor())
            mpc_var = global_block.var(mpc_var_name)
            if mpc_var_name not in plain_vars:
                param.get_tensor()._set_dims(mpc_var.shape)
                # process initialized params that should be 0
                set_tensor_value = np.array([param_tensor, param_tensor]).astype(np.int64)
                param.get_tensor().set(set_tensor_value, place)
            else:
                param.get_tensor().set(np.array(param.get_tensor()).astype('float64'), place)

    # trigger sync to replace old ops.
    op_num = global_block.desc.op_size()
    _ = global_block.desc.append_op()
    global_block.desc._remove_op(op_num, op_num + 1)
    return program


def _transpile_type_and_shape(block):
    """
    Transpile dtype and shape of plain variables into MPC dtype and shape.
    And transpile op type into MPC type.

    Args:
        block: The block in Paddle program.

    Returns: A set of variable names to encrypt.
    """
    mpc_vars_names = set()

    # store variable name in mpc_vars_names, and encrypt dtype and shape
    for var_name in block.vars:
        var = block.var(var_name)
        if var.name != "feed" and var.name != "fetch":
            mpc_vars_names.add(var.name)
            if var_name in plain_vars:
                var.desc.set_dtype(fluid.framework.convert_np_dtype_to_dtype_(np.float64))
                continue
            # set mpc param shape = [2, old_shape]
            encrypted_var_shape = (ABY3_SHARE_DIM,) + var.shape
            var.desc.set_dtype(fluid.framework.convert_np_dtype_to_dtype_(np.int64))
            var.desc.set_shape(encrypted_var_shape)

    # encrypt op type, or other attrs if needed
    for op in block.ops:
        if _is_supported_op(op.type):
            if op.type == 'fill_constant':
                op._set_attr(name='shape', val=(2L, 1L))
                # set default MPC value for fill_constant OP
                op._set_attr(name='value', val=MPC_ONE_SHARE)
                op._set_attr(name='dtype', val=3)
            elif op.type in op_to_skip:
                pass
            else:
                op.desc.set_type(MPC_OP_PREFIX + op.type)
        else:
            raise NotImplementedError('Operator {} is unsupported.'
                                      .format(op.type))
    return mpc_vars_names


def encrypt_model(program, mpc_model_dir=None, model_filename=None):
J
jingqinghe 已提交
356
    """
J
jhjiangcs 已提交
357 358
    Encrypt model, and save encrypted model (i.e., MPC model shares) into
    files for MPC training, updating, or inference.
J
jingqinghe 已提交
359 360

    Args:
J
jhjiangcs 已提交
361 362 363
        program: The loaded program of paddle model.
        mpc_model_dir: The directory that save MPC model shares.
        model_filename: The name of MPC model file, default is __model__.aby3.
J
jingqinghe 已提交
364 365 366
    """
    place = fluid.CPUPlace()
    exe = fluid.Executor(place)
J
jhjiangcs 已提交
367 368 369

    # TODO(xukun): support more blocks. Tips: may just adding "for loop" for all blocks.
    if program.num_blocks > 1:
J
jingqinghe 已提交
370 371 372
        raise NotImplementedError(
            "The number of blocks in current main program"
            "is {}, which is not supported in this version."
J
jhjiangcs 已提交
373 374 375
            .format(program.num_blocks()))

    global_block = program.global_block()
J
jingqinghe 已提交
376
    g_scope = fluid.global_scope()
J
jhjiangcs 已提交
377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403

    mpc_vars_names = _transpile_type_and_shape(global_block)

    # encrypt tensor values for each variable in mpc_var_names
    for mpc_var_name in mpc_vars_names:
        if g_scope.find_var(mpc_var_name) is not None:
            param = g_scope.find_var(mpc_var_name)
            param_tensor = np.array(param.get_tensor())
            param_tensor_shares = make_shares(param_tensor)
            mpc_var = global_block.var(mpc_var_name)
            for idx in six.moves.range(SHARE_NUM):
                if mpc_var_name not in plain_vars:
                    param.get_tensor()._set_dims(mpc_var.shape)
                    set_tensor_value = get_aby3_shares(param_tensor_shares, idx)
                    param.get_tensor().set(set_tensor_value, place)
                else:
                    param.get_tensor().set(np.array(param.get_tensor()).astype('float64'), place)

                param_share_dir = os.path.join(
                    mpc_model_dir, MODEL_SHARE_DIR + "_" + str(idx))
                fluid.io.save_vars(
                    executor=exe,
                    dirname=param_share_dir,
                    vars=[mpc_var],
                    filename=mpc_var_name)

    # trigger sync to replace old ops.
J
jingqinghe 已提交
404 405 406 407 408 409 410 411 412 413 414 415 416 417
    op_num = global_block.desc.op_size()
    _ = global_block.desc.append_op()
    global_block.desc._remove_op(op_num, op_num + 1)

    # save mpc model file
    model_basename = os.path.basename(
        model_filename) if model_filename is not None else ABY3_MODEL_NAME
    for idx in six.moves.range(SHARE_NUM):
        model_share_dir = os.path.join(mpc_model_dir,
                                       MODEL_SHARE_DIR + "_" + str(idx))
        if not os.path.exists(model_share_dir):
            os.makedirs(model_share_dir)
        model_name = os.path.join(model_share_dir, model_basename)
        with open(model_name, "wb") as f:
J
jhjiangcs 已提交
418
            f.write(program.desc.serialize_to_string())
J
jingqinghe 已提交
419 420


J
jhjiangcs 已提交
421
def decrypt_model(mpc_model_dir, plain_model_path, mpc_model_filename=None, plain_model_filename=None):
J
jingqinghe 已提交
422
    """
J
jhjiangcs 已提交
423 424
    Reveal a paddle model. Load encrypted model (i.e., MPC model shares) from files and decrypt it
    into paddle model.
J
jingqinghe 已提交
425

J
jhjiangcs 已提交
426
    Args:
J
jingqinghe 已提交
427 428
        mpc_model_dir: The directory of all model shares.
        plain_model_path: The directory to save revealed paddle model.
J
jhjiangcs 已提交
429 430
        mpc_model_filename: The name of encrypted model file.
        plain_model_filename: The name of decrypted model file.
J
jingqinghe 已提交
431 432 433 434 435 436 437 438 439
    """
    share_dirs = []
    for sub_dir in os.listdir(mpc_model_dir):
        if not sub_dir.startswith("."):
            share_dirs.append(os.path.join(mpc_model_dir, sub_dir))

    place = fluid.CPUPlace()
    exe = fluid.Executor(place=place)
    mpc_model_basename = os.path.basename(
J
jhjiangcs 已提交
440
        mpc_model_filename) if mpc_model_filename is not None else ABY3_MODEL_NAME
J
jingqinghe 已提交
441 442 443 444 445 446 447 448 449 450 451

    [main_prog, _, _] = fluid.io.load_inference_model(
        dirname=share_dirs[0], executor=exe, model_filename=mpc_model_basename)
    if main_prog.num_blocks > 1:
        raise NotImplementedError(
            "The number of blocks in current main program"
            "is {}, which is not supported in this version"
            .format(main_prog.num_blocks()))

    global_block = main_prog.global_block()
    g_scope = fluid.global_scope()
J
jhjiangcs 已提交
452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479

    # a set storing unique variables to decrypt
    vars_set = set()

    # store variable name in vars_set, and decrypt dtype and shape
    for mpc_var_name in global_block.vars:
        mpc_var = global_block.var(mpc_var_name)
        if mpc_var.name != "feed" and mpc_var.name != "fetch":
            vars_set.add(mpc_var.name)
            if mpc_var_name in plain_vars:
                # var.desc.set_dtype(fluid.framework.convert_np_dtype_to_dtype_(np.float64))
                continue
            elif mpc_var.shape[0] != ABY3_SHARE_DIM:
                raise ValueError(
                    "Variable:{} shape: {} in saved model should start with 2."
                        .format(mpc_var.name, mpc_var.shape))
            else:
                plain_var_shape = mpc_var.shape[1:]
                mpc_var.desc.set_shape(plain_var_shape)
                mpc_var.desc.set_dtype(fluid.framework.convert_np_dtype_to_dtype_(np.float32))

    # remove init op
    first_mpc_op = global_block.ops[0]
    if first_mpc_op.type == 'mpc_init':
        global_block._remove_op(0)

    # decrypt op type, or other attrs if needed
    for mpc_op in global_block.ops:
J
jingqinghe 已提交
480
        # rename ops
J
jhjiangcs 已提交
481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510
        if str(mpc_op.type).startswith(MPC_OP_PREFIX):
            new_type = str(mpc_op.type)[len(MPC_OP_PREFIX):]
            mpc_op.desc.set_type(new_type)
        elif mpc_op.type == 'fill_constant':
            mpc_op._set_attr(name='shape', val=(1L))
            mpc_op._set_attr(name='value', val=1.0)
            mpc_op._set_attr(name='dtype', val=5)

    # decrypt tensor values for each variable in vars_set
    for var_name in vars_set:
        var = global_block.var(var_name)
        if g_scope.find_var(var_name) is not None:
            param = g_scope.find_var(var_name)
            if var_name in plain_vars:
                pass
            else:
                # reconstruct plaintext
                param_tensor_shares = _get_param_all_shares(
                    var_name, share_dirs, mpc_model_basename)
                param_tensor = reconstruct(
                    param_tensor_shares, type=np.float32)
                param.get_tensor()._set_dims(var.shape)
                param.get_tensor().set(param_tensor, place)

            fluid.io.save_vars(
                executor=exe,
                dirname=plain_model_path,
                vars=[var],
                filename=var_name)

J
jingqinghe 已提交
511 512 513 514 515 516 517
    # trigger sync to replace old ops
    op_num = global_block.desc.op_size()
    _ = global_block.desc.append_op()
    global_block.desc._remove_op(op_num, op_num + 1)

    # save plaintext model file.
    model_basename = os.path.basename(
J
jhjiangcs 已提交
518
        plain_model_filename) if plain_model_filename is not None else MODEL_NAME
J
jingqinghe 已提交
519 520 521 522 523 524 525 526 527 528 529 530 531 532 533
    if not os.path.exists(plain_model_path):
        os.makedirs(plain_model_path)
    model_name = os.path.join(plain_model_path, model_basename)
    with open(model_name, "wb") as f:
        f.write(main_prog.desc.serialize_to_string())


def _get_param_all_shares(param_name, share_dirs, model_file):
    """
    Get all shares of one parameter from directories.

    Args:
        param_name: The name of parameter.
        share_dirs: The directories which storing model shares.
        model_file: The name of model file.
J
jhjiangcs 已提交
534 535 536

    Returns:
        ndarray. The loaded shares.
J
jingqinghe 已提交
537 538 539 540 541 542 543 544 545 546 547
    """
    exe = fluid.Executor(place=fluid.CPUPlace())
    param_shares = []
    for share_dir in share_dirs:
        _ = fluid.io.load_inference_model(
            dirname=share_dir, executor=exe, model_filename=model_file)
        g_scope = fluid.global_scope()
        param = g_scope.find_var(param_name)
        param_tensor = np.array(param.get_tensor())
        param_shares.append(param_tensor)
    return np.array(param_shares, dtype=np.int64)
J
jhjiangcs 已提交
548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696


def _is_supported_op(op_name):
    """
    Check if op is supported for encryption and decryption.

    Args:
        op_name: The name of op.

    Returns:
        True if supported.
    """
    if op_name not in supported_mpc_ops:
        if str(op_name).endswith('_grad'):
            _is_supported_op(str(op_name)[:-5])
        else:
            return False
    return True


def load_mpc_model(exe, mpc_model_dir, mpc_model_filename, inference=False):
    """
    Load MPC model from files. The loaded program of the model would be inserted
    init OP and then switched to default_main_program for further MPC procedure.

    Args:
        exe: The executor used for loading.
        mpc_model_dir: The directory of MPC model.
        mpc_model_filename: The filename of MPC model.
        inference: Whether the model to load is used for inference. If true, the
        model to load should be an inference model, and feed_name, fetch_targets
        would be returned with the loaded program after inserting init OP. Otherwise,
        after inserting init OP, the loaded program would be switched to
        default_main_program and returned. Default value is False.

    Returns:
        default_main_program if inference is False. Otherwise, default_main_program,
        feed_name, and fetch_targets would be returned.
    """
    mpc_program, feed_names, fetch_targets = fluid.io.load_inference_model(executor=exe,
                                  dirname=mpc_model_dir,
                                  model_filename=mpc_model_filename)
    # find init OP
    global_block = fluid.default_main_program().global_block()
    init_op_idx = _find_init_op_idx(global_block)
    if init_op_idx < 0:
        raise RuntimeError('No mpc_init op in global block, '
                           'maybe you should use paddle_fl.mpc.init() first.')
    init_op = global_block.ops[init_op_idx]
    # find the last feed OP for inserting init OP
    last_feed_op_idx = _find_last_feed_op_idx(mpc_program.global_block())
    # insert init OP as the first OP of MPC program if no feed OP,
    # otherwise, insert it after the last feed OP.
    insert_idx = 0 if last_feed_op_idx < 0 else last_feed_op_idx + 1
    loaded_mpc_program = _insert_init_op(main_prog=mpc_program,
                                         init_op=init_op,
                                         index=insert_idx)
    if inference:
        return loaded_mpc_program, feed_names, fetch_targets
    else:
        # switch loaded_mpc_program to default_main_program
        fluid.framework.switch_main_program(loaded_mpc_program)
        return fluid.default_main_program()


def _find_init_op_idx(block):
    """
    Find the index of mpc_init op.

    Args:
        block: The block of program.

    Returns:
        The index of mpc_init op.
    """
    for idx, op in enumerate(block.ops):
        if op.type == 'mpc_init':
            return idx
    return -1


def _find_last_feed_op_idx(block):
    """
    Find the index of the last feed OP.

    Args:
        block: The block of program.

    Returns:
        The index of the last feed OP.
    """
    feed_idx = -1
    for idx, op in enumerate(block.ops):
        if op.type == 'feed':
            feed_idx = idx
    return feed_idx


def save_trainable_model(exe, model_dir, model_filename=None, program=None):
    """
    Save trainable model, which includes saving program and
    persistable parameters into files. The saved model can be
    loaded by fluid.io.load_inference_model for further training
    or updating.

    Args:
        exe: The executor used for saving.
        model_dir: The directory of model to save.
        model_filename: The filename of model to save.
        program: The program to save, default to default_main_program.

    TODO: can move this to paddle_mpc/python/paddle_fl/mpc/io.py
    """
    if not os.path.exists(model_dir):
        os.makedirs(model_dir)
    model_basename = os.path.basename(
        model_filename) if model_filename is not None else ABY3_MODEL_NAME
    # save program
    model_name = os.path.join(model_dir, model_basename)
    if program is None:
        program = fluid.default_main_program()
    with open(model_name, "wb") as f:
        f.write(program.desc.serialize_to_string())
    # save parameters
    fluid.io.save_persistables(executor=exe,
                               dirname=model_dir,
                               main_program=program)


def _insert_init_op(main_prog, init_op, index):
    """
    Insert init OP into main_prog according to the index.

    Args:
        main_prog: The program to insert init OP.
        init_op: The init OP for MPC running.
        index: The place that the init_op to insert.

    Returns:
        The program after inserting init OP.
    """
    main_prog.global_block()._sync_with_cpp()
    op_desc = main_prog.global_block().desc._insert_op(index)
    mpc_init_op = fluid.framework.Operator(block=main_prog.global_block(),
                                           desc=op_desc,
                                           type=init_op.type,
                                           attrs=init_op.all_attrs())
    main_prog.global_block().ops.insert(index, mpc_init_op)
    return main_prog