|
| 1 | +// Copyright 2020 The SQLFlow Authors. All rights reserved. |
| 2 | +// Licensed under the Apache License, Version 2.0 (the "License"); |
| 3 | +// you may not use this file except in compliance with the License. |
| 4 | +// You may obtain a copy of the License at |
| 5 | +// |
| 6 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 7 | +// |
| 8 | +// Unless required by applicable law or agreed to in writing, software |
| 9 | +// distributed under the License is distributed on an "AS IS" BASIS, |
| 10 | +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 11 | +// See the License for the specific language governing permissions and |
| 12 | +// limitations under the License. |
| 13 | + |
| 14 | +package alps |
| 15 | + |
| 16 | +import "sqlflow.org/sqlflow/go/ir" |
| 17 | + |
| 18 | +type trainFiller struct { |
| 19 | +DataSource string |
| 20 | +TrainSelect string |
| 21 | +ValidationSelect string |
| 22 | +Estimator string |
| 23 | +FieldDescs map[string][]*ir.FieldDesc |
| 24 | +FeatureColumnCode string |
| 25 | +Y *ir.FieldDesc |
| 26 | +ModelParams map[string]interface{} |
| 27 | +TrainParams map[string]interface{} |
| 28 | +ValidationParams map[string]interface{} |
| 29 | +Save string |
| 30 | +TmpTrainTable string |
| 31 | +TmpValidateTable string |
| 32 | +} |
| 33 | + |
| 34 | +var templateTrain = `import copy |
| 35 | +import os |
| 36 | +import shutil |
| 37 | +
|
| 38 | +import tensorflow as tf |
| 39 | +from alps.framework.column.column import (DenseColumn, GroupedSparseColumn, |
| 40 | + SparseColumn) |
| 41 | +from alps.framework.engine import LocalEngine |
| 42 | +from alps.framework.experiment import EstimatorBuilder |
| 43 | +from alps.io.base import OdpsConf |
| 44 | +from runtime import db |
| 45 | +from runtime.alps.train import train |
| 46 | +from runtime.tensorflow.get_tf_version import tf_is_version2 |
| 47 | +
|
| 48 | +feature_column_names = [{{range $target, $desclist := .FieldDescs}}{{range $desclist}} |
| 49 | +"{{.Name}}", |
| 50 | +{{end}}{{end}}] |
| 51 | +
|
| 52 | +feature_metas = dict() |
| 53 | +{{ range $target, $desclist := .FieldDescs }} |
| 54 | +{{ range $value := $desclist }} |
| 55 | +feature_metas["{{$value.Name}}"] = { |
| 56 | + "feature_name": "{{$value.Name}}", |
| 57 | + "dtype": "{{$value.DType | DTypeToString}}", |
| 58 | + "delimiter": "{{$value.Delimiter}}", |
| 59 | + "format": "{{$value.Format}}", |
| 60 | + "shape": {{$value.Shape | intArrayToJSONString}}, |
| 61 | + "is_sparse": "{{$value.IsSparse}}" == "true" |
| 62 | +} |
| 63 | +{{end}} |
| 64 | +{{end}} |
| 65 | +
|
| 66 | +label_meta = { |
| 67 | + "feature_name": "{{.Y.Name}}", |
| 68 | + "dtype": "{{.Y.DType | DTypeToString}}", |
| 69 | + "delimiter": "{{.Y.Delimiter}}", |
| 70 | + "shape": {{.Y.Shape | intArrayToJSONString}}, |
| 71 | + "is_sparse": "{{.Y.IsSparse}}" == "true" |
| 72 | +} |
| 73 | +
|
| 74 | +model_params=dict() |
| 75 | +{{range $k, $v := .ModelParams}} |
| 76 | +model_params["{{$k}}"]={{$v | attrToPythonValue}} |
| 77 | +{{end}} |
| 78 | +
|
| 79 | +# Construct optimizer objects to pass to model initializer. |
| 80 | +# The original model_params is serializable (do not have tf.xxx objects). |
| 81 | +model_params_constructed = copy.deepcopy(model_params) |
| 82 | +for optimizer_arg in ["optimizer", "dnn_optimizer", "linear_optimizer"]: |
| 83 | + if optimizer_arg in model_params_constructed: |
| 84 | + model_params_constructed[optimizer_arg] = eval(model_params_constructed[optimizer_arg]) |
| 85 | +
|
| 86 | +if "loss" in model_params_constructed: |
| 87 | + model_params_constructed["loss"] = eval(model_params_constructed["loss"]) |
| 88 | +
|
| 89 | +
|
| 90 | +class SQLFlowEstimatorBuilder(EstimatorBuilder): |
| 91 | + def _build(self, experiment, run_config): |
| 92 | + feature_columns_map = {{.FeatureColumnCode}} |
| 93 | + if feature_columns_map.get("feature_columns"): |
| 94 | + feature_columns = feature_columns_map["feature_columns"] |
| 95 | + else: |
| 96 | + raise ValueError("Not supported feature column map") |
| 97 | + model_params_constructed["feature_columns"] = feature_columns |
| 98 | + return tf.estimator.{{.Estimator}}(config=run_config, |
| 99 | + **model_params_constructed) |
| 100 | +
|
| 101 | +
|
| 102 | +if __name__ == "__main__": |
| 103 | + if tf_is_version2(): |
| 104 | + raise ValueError("ALPS must run with Tensorflow == 1.15.x") |
| 105 | +
|
| 106 | + driver, dsn = "{{.DataSource}}".split("://") |
| 107 | + user, passwd, endpoint, odps_project = db.parseMaxComputeDSN(dsn) |
| 108 | + odps_conf = OdpsConf( |
| 109 | + accessid=user, |
| 110 | + accesskey=passwd, |
| 111 | + # endpoint should looks like: "https://service.cn.maxcompute.aliyun.com/api" |
| 112 | + endpoint=endpoint, |
| 113 | + project=odps_project) |
| 114 | +
|
| 115 | + features = [] |
| 116 | + for col_name in feature_column_names: |
| 117 | + # NOTE: add sparse columns like: SparseColumn(name="deep_id", shape=[15033], dtype="int") |
| 118 | + if feature_metas[col_name]["is_sparse"]: |
| 119 | + features.append(SparseColumn(name=feature_metas[col_name]["feature_name"], |
| 120 | + shape=feature_metas[col_name]["shape"], |
| 121 | + dtype=feature_metas[col_name]["dtype"], |
| 122 | + separator=feature_metas[col_name]["separator"])) |
| 123 | + else: |
| 124 | + features.append(DenseColumn(name=feature_metas[col_name]["feature_name"], |
| 125 | + shape=feature_metas[col_name]["shape"], |
| 126 | + dtype=feature_metas[col_name]["dtype"])) |
| 127 | + labels = DenseColumn(name=label_meta["feature_name"], |
| 128 | + shape=label_meta["shape"], |
| 129 | + dtype=label_meta["dtype"]) |
| 130 | +
|
| 131 | + try: |
| 132 | + os.mkdir("scratch") |
| 133 | + except FileExistsError: |
| 134 | + pass |
| 135 | +
|
| 136 | + train_max_steps = {{index .TrainParams "max_steps" | attrToPythonValue}} |
| 137 | + train_max_steps = None if train_max_steps == 0 else train_max_steps |
| 138 | +
|
| 139 | + # TODO(typhoonzero): support pass feature_map_table from WITH attributes. |
| 140 | + # TODO(typhoonzero): pass actual use_id. |
| 141 | + # TODO(typhoonzero): pass engine config to submit jobs to the cluster. |
| 142 | + train(SQLFlowEstimatorBuilder(), |
| 143 | + odps_conf=odps_conf, |
| 144 | + project=odps_project, |
| 145 | + train_table="{{.TmpTrainTable}}", |
| 146 | + eval_table="{{.TmpValidateTable}}", |
| 147 | + features=features, |
| 148 | + labels=labels, |
| 149 | + feature_map_table="", |
| 150 | + feature_map_partition="", |
| 151 | + epochs=1, |
| 152 | + batch_size=2, |
| 153 | + shuffle=False, |
| 154 | + shuffle_bufsize=128, |
| 155 | + cache_file="", |
| 156 | + max_steps=train_max_steps, |
| 157 | + eval_steps={{index .ValidationParams "steps" | attrToPythonValue}}, |
| 158 | + eval_batch_size=1, |
| 159 | + eval_start_delay={{index .ValidationParams "start_delay_secs" | attrToPythonValue}}, |
| 160 | + eval_throttle={{index .ValidationParams "throttle_secs" | attrToPythonValue}}, |
| 161 | + drop_remainder=True, |
| 162 | + export_path="./scratch/model", |
| 163 | + scratch_dir="./scratch", |
| 164 | + user_id="", |
| 165 | + engine_config={"name": "LocalEngine"}, |
| 166 | + exit_on_submit=False) |
| 167 | + shutil.rmtree("scratch") |
| 168 | +` |
0 commit comments