|
| 1 | +# /bin/python |
| 2 | +import time |
| 3 | + |
| 4 | +import fire |
| 5 | +import numpy as np |
| 6 | + |
| 7 | +from fedn.utils.helpers.helpers import get_helper, save_metadata, save_metrics |
| 8 | + |
| 9 | +HELPER_MODULE = 'numpyhelper' |
| 10 | +ARRAY_SIZE = 1000000 |
| 11 | + |
| 12 | + |
| 13 | +def save_model(weights, out_path): |
| 14 | + """ Save model to disk. |
| 15 | + |
| 16 | + :param model: The model to save. |
| 17 | + :type model: torch.nn.Module |
| 18 | + :param out_path: The path to save to. |
| 19 | + :type out_path: str |
| 20 | + """ |
| 21 | + helper = get_helper(HELPER_MODULE) |
| 22 | + helper.save(weights, out_path) |
| 23 | + |
| 24 | + |
| 25 | +def load_model(model_path): |
| 26 | + """ Load model from disk. |
| 27 | + |
| 28 | + param model_path: The path to load from. |
| 29 | + :type model_path: str |
| 30 | + :return: The loaded model. |
| 31 | + :rtype: torch.nn.Module |
| 32 | + """ |
| 33 | + helper = get_helper(HELPER_MODULE) |
| 34 | + weights = helper.load(model_path) |
| 35 | + return weights |
| 36 | + |
| 37 | + |
| 38 | +def init_seed(out_path='seed.npz'): |
| 39 | + """ Initialize seed model. |
| 40 | + |
| 41 | + :param out_path: The path to save the seed model to. |
| 42 | + :type out_path: str |
| 43 | + """ |
| 44 | + # Init and save |
| 45 | + weights = [np.random.rand(1, ARRAY_SIZE)] |
| 46 | + save_model(weights, out_path) |
| 47 | + |
| 48 | + |
| 49 | +def train(in_model_path, out_model_path): |
| 50 | + """ Train model. |
| 51 | + |
| 52 | + """ |
| 53 | + |
| 54 | + # Load model |
| 55 | + weights = load_model(in_model_path) |
| 56 | + |
| 57 | + # Train |
| 58 | + time.sleep(np.random.randint(4, 15)) |
| 59 | + |
| 60 | + # Metadata needed for aggregation server side |
| 61 | + metadata = { |
| 62 | + 'num_examples': ARRAY_SIZE, |
| 63 | + } |
| 64 | + |
| 65 | + # Save JSON metadata file |
| 66 | + save_metadata(metadata, out_model_path) |
| 67 | + |
| 68 | + # Save model update |
| 69 | + save_model(weights, out_model_path) |
| 70 | + |
| 71 | + |
| 72 | +def validate(in_model_path, out_json_path): |
| 73 | + """ Validate model. |
| 74 | + |
| 75 | + :param in_model_path: The path to the input model. |
| 76 | + :type in_model_path: str |
| 77 | + :param out_json_path: The path to save the output JSON to. |
| 78 | + :type out_json_path: str |
| 79 | + :param data_path: The path to the data file. |
| 80 | + :type data_path: str |
| 81 | + """ |
| 82 | + weights = load_model(in_model_path) |
| 83 | + |
| 84 | + # JSON schema |
| 85 | + report = { |
| 86 | + "mean": np.mean(weights), |
| 87 | + } |
| 88 | + |
| 89 | + # Save JSON |
| 90 | + save_metrics(report, out_json_path) |
| 91 | + |
| 92 | + |
| 93 | +if __name__ == '__main__': |
| 94 | + fire.Fire({ |
| 95 | + 'init_seed': init_seed, |
| 96 | + 'train': train, |
| 97 | + 'validate': validate |
| 98 | + }) |
0 commit comments