|
| 1 | +# Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"). |
| 4 | +# You may not use this file except in compliance with the License. |
| 5 | +# A copy of the License is located at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# or in the "license" file accompanying this file. This file is distributed |
| 10 | +# on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either |
| 11 | +# express or implied. See the License for the specific language governing |
| 12 | +# permissions and limitations under the License. |
| 13 | +from __future__ import print_function |
| 14 | + |
| 15 | +import argparse |
| 16 | +import json |
| 17 | +import logging |
| 18 | +import os |
| 19 | +import pickle as pkl |
| 20 | + |
| 21 | +import pandas as pd |
| 22 | +import xgboost as xgb |
| 23 | +from sagemaker_containers import entry_point |
| 24 | +from sagemaker_xgboost_container import distributed |
| 25 | +from sagemaker_xgboost_container.data_utils import get_dmatrix |
| 26 | + |
| 27 | + |
| 28 | +def _xgb_train(params, dtrain, evals, num_boost_round, model_dir, is_master): |
| 29 | + """Run xgb train on arguments given with rabit initialized. |
| 30 | +
|
| 31 | + This is our rabit execution function. |
| 32 | +
|
| 33 | + :param args_dict: Argument dictionary used to run xgb.train(). |
| 34 | + :param is_master: True if current node is master host in distributed training, |
| 35 | + or is running single node training job. |
| 36 | + Note that rabit_run will include this argument. |
| 37 | + """ |
| 38 | + booster = xgb.train(params=params, dtrain=dtrain, evals=evals, num_boost_round=num_boost_round) |
| 39 | + |
| 40 | + if is_master: |
| 41 | + model_location = model_dir + "/xgboost-model" |
| 42 | + pkl.dump(booster, open(model_location, "wb")) |
| 43 | + logging.info("Stored trained model at {}".format(model_location)) |
| 44 | + |
| 45 | + |
| 46 | +if __name__ == "__main__": |
| 47 | + parser = argparse.ArgumentParser() |
| 48 | + |
| 49 | + # Hyperparameters are described here. |
| 50 | + parser.add_argument( |
| 51 | + "--max_depth", |
| 52 | + type=int, |
| 53 | + ) |
| 54 | + parser.add_argument("--eta", type=float) |
| 55 | + parser.add_argument("--gamma", type=int) |
| 56 | + parser.add_argument("--min_child_weight", type=int) |
| 57 | + parser.add_argument("--subsample", type=float) |
| 58 | + parser.add_argument("--verbosity", type=int) |
| 59 | + parser.add_argument("--objective", type=str) |
| 60 | + parser.add_argument("--num_round", type=int) |
| 61 | + parser.add_argument("--tree_method", type=str, default="auto") |
| 62 | + parser.add_argument("--predictor", type=str, default="auto") |
| 63 | + |
| 64 | + # Sagemaker specific arguments. Defaults are set in the environment variables. |
| 65 | + parser.add_argument("--output_data_dir", type=str, default=os.environ.get("SM_OUTPUT_DATA_DIR")) |
| 66 | + parser.add_argument("--model_dir", type=str, default=os.environ.get("SM_MODEL_DIR")) |
| 67 | + parser.add_argument("--train", type=str, default=os.environ.get("SM_CHANNEL_TRAIN")) |
| 68 | + parser.add_argument("--validation", type=str, default=os.environ.get("SM_CHANNEL_VALIDATION")) |
| 69 | + parser.add_argument("--sm_hosts", type=str, default=os.environ.get("SM_HOSTS")) |
| 70 | + parser.add_argument("--sm_current_host", type=str, default=os.environ.get("SM_CURRENT_HOST")) |
| 71 | + |
| 72 | + args, _ = parser.parse_known_args() |
| 73 | + |
| 74 | + # Get SageMaker host information from runtime environment variables |
| 75 | + sm_hosts = json.loads(args.sm_hosts) |
| 76 | + sm_current_host = args.sm_current_host |
| 77 | + |
| 78 | + dtrain = get_dmatrix(args.train, "libsvm") |
| 79 | + dval = get_dmatrix(args.validation, "libsvm") |
| 80 | + watchlist = ( |
| 81 | + [(dtrain, "train"), (dval, "validation")] if dval is not None else [(dtrain, "train")] |
| 82 | + ) |
| 83 | + |
| 84 | + train_hp = { |
| 85 | + "max_depth": args.max_depth, |
| 86 | + "eta": args.eta, |
| 87 | + "gamma": args.gamma, |
| 88 | + "min_child_weight": args.min_child_weight, |
| 89 | + "subsample": args.subsample, |
| 90 | + "verbosity": args.verbosity, |
| 91 | + "objective": args.objective, |
| 92 | + "tree_method": args.tree_method, |
| 93 | + "predictor": args.predictor, |
| 94 | + } |
| 95 | + |
| 96 | + xgb_train_args = dict( |
| 97 | + params=train_hp, |
| 98 | + dtrain=dtrain, |
| 99 | + evals=watchlist, |
| 100 | + num_boost_round=args.num_round, |
| 101 | + model_dir=args.model_dir, |
| 102 | + ) |
| 103 | + |
| 104 | + if len(sm_hosts) > 1: |
| 105 | + # Wait until all hosts are able to find each other |
| 106 | + entry_point._wait_hostname_resolution() |
| 107 | + |
| 108 | + # Execute training function after initializing rabit. |
| 109 | + distributed.rabit_run( |
| 110 | + exec_fun=_xgb_train, |
| 111 | + args=xgb_train_args, |
| 112 | + include_in_training=(dtrain is not None), |
| 113 | + hosts=sm_hosts, |
| 114 | + current_host=sm_current_host, |
| 115 | + update_rabit_args=True, |
| 116 | + ) |
| 117 | + else: |
| 118 | + # If single node training, call training method directly. |
| 119 | + if dtrain: |
| 120 | + xgb_train_args["is_master"] = True |
| 121 | + _xgb_train(**xgb_train_args) |
| 122 | + else: |
| 123 | + raise ValueError("Training channel must have data to train model.") |
| 124 | + |
| 125 | + |
| 126 | +def model_fn(model_dir): |
| 127 | + """Deserialize and return fitted model. |
| 128 | +
|
| 129 | + Note that this should have the same name as the serialized model in the _xgb_train method |
| 130 | + """ |
| 131 | + model_file = "xgboost-model" |
| 132 | + booster = pkl.load(open(os.path.join(model_dir, model_file), "rb")) |
| 133 | + return booster |
0 commit comments