pipeline-hetero-nn-train-binary-coae.py 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131
  1. #
  2. # Copyright 2019 The FATE Authors. All Rights Reserved.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. #
  16. import argparse
  17. from collections import OrderedDict
  18. import torch as t
  19. from torch import nn
  20. from torch import optim
  21. from pipeline import fate_torch as ft
  22. from pipeline import fate_torch_hook
  23. from pipeline.backend.pipeline import PipeLine
  24. from pipeline.component import DataTransform
  25. from pipeline.component import Evaluation
  26. from pipeline.component import HeteroNN
  27. from pipeline.component import Intersection
  28. from pipeline.component import Reader
  29. from pipeline.interface import Data
  30. from pipeline.interface import Model
  31. from pipeline.utils.tools import load_job_config
  32. # this is important, modify torch modules so that Sequential model be parsed by pipeline
  33. fate_torch_hook(t)
  34. def main(config="../../config.yaml", namespace=""):
  35. # obtain config
  36. if isinstance(config, str):
  37. config = load_job_config(config)
  38. parties = config.parties
  39. guest = parties.guest[0]
  40. host = parties.host[0]
  41. guest_train_data = {"name": "breast_hetero_guest", "namespace": f"experiment{namespace}"}
  42. host_train_data = {"name": "breast_hetero_host", "namespace": f"experiment{namespace}"}
  43. pipeline = PipeLine().set_initiator(role='guest', party_id=guest).set_roles(guest=guest, host=host)
  44. reader_0 = Reader(name="reader_0")
  45. reader_0.get_party_instance(role='guest', party_id=guest).component_param(table=guest_train_data)
  46. reader_0.get_party_instance(role='host', party_id=host).component_param(table=host_train_data)
  47. data_transform_0 = DataTransform(name="data_transform_0")
  48. data_transform_0.get_party_instance(role='guest', party_id=guest).component_param(with_label=True)
  49. data_transform_0.get_party_instance(role='host', party_id=host).component_param(with_label=False)
  50. intersection_0 = Intersection(name="intersection_0")
  51. # define network structure in torch style #
  52. # define guest model
  53. Linear = nn.Linear
  54. ReLU = nn.ReLU
  55. guest_bottom_a = Linear(10, 8, True)
  56. seq = nn.Sequential(
  57. OrderedDict([
  58. ('layer_0', guest_bottom_a),
  59. ('relu_0', ReLU())
  60. ])
  61. )
  62. seq2 = nn.Sequential(
  63. ReLU(),
  64. Linear(8, 2, True),
  65. nn.Softmax(dim=1) # to use coae in binary task, output unit is 2, and need use softmax to compute probability
  66. ) # so that we can compute loss using fake labels and 2-dim outputs
  67. # define host model
  68. seq3 = nn.Sequential(
  69. Linear(20, 8, True),
  70. ReLU()
  71. )
  72. # use interactive layer after fate_torch_hook
  73. interactive_layer = t.nn.InteractiveLayer(out_dim=8, guest_dim=8, host_dim=8, host_num=1)
  74. # loss fun
  75. ce_loss_fn = nn.CrossEntropyLoss()
  76. # optimizer, after fate torch hook optimizer can be created without parameters
  77. opt: ft.optim.Adam = optim.Adam(lr=0.01)
  78. hetero_nn_0 = HeteroNN(name="hetero_nn_0", epochs=30, floating_point_precision=None,
  79. interactive_layer_lr=0.1, batch_size=-1, early_stop="diff",
  80. coae_param={'enable': True, 'epoch': 100})
  81. guest_nn_0 = hetero_nn_0.get_party_instance(role='guest', party_id=guest)
  82. guest_nn_0.add_bottom_model(seq)
  83. guest_nn_0.add_top_model(seq2)
  84. host_nn_0 = hetero_nn_0.get_party_instance(role='host', party_id=host)
  85. host_nn_0.add_bottom_model(seq3)
  86. hetero_nn_0.set_interactive_layer(interactive_layer)
  87. hetero_nn_0.compile(opt, loss=ce_loss_fn)
  88. hetero_nn_1 = HeteroNN(name="hetero_nn_1")
  89. evaluation_0 = Evaluation(name="evaluation_0")
  90. pipeline.add_component(reader_0)
  91. pipeline.add_component(data_transform_0, data=Data(data=reader_0.output.data))
  92. pipeline.add_component(intersection_0, data=Data(data=data_transform_0.output.data))
  93. pipeline.add_component(hetero_nn_0, data=Data(train_data=intersection_0.output.data))
  94. pipeline.add_component(hetero_nn_1, data=Data(test_data=intersection_0.output.data),
  95. model=Model(model=hetero_nn_0.output.model))
  96. pipeline.add_component(evaluation_0, data=Data(data=hetero_nn_0.output.data))
  97. pipeline.compile()
  98. pipeline.fit()
  99. if __name__ == "__main__":
  100. parser = argparse.ArgumentParser("PIPELINE DEMO")
  101. parser.add_argument("-config", type=str,
  102. help="config file")
  103. args = parser.parse_args()
  104. if args.config is not None:
  105. main(args.config)
  106. else:
  107. main()