/
tensorflow.go
244 lines (220 loc) · 7.64 KB
/
tensorflow.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
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
165
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
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
// Copyright 2020 The SQLFlow Authors. All rights reserved.
// 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.
package pai
import (
"bytes"
"encoding/json"
"fmt"
"os"
"strconv"
"strings"
"text/template"
"sqlflow.org/sqlflow/go/codegen/tensorflow"
"sqlflow.org/sqlflow/go/ir"
pb "sqlflow.org/sqlflow/go/proto"
)
func generateLoadOSSModelCode(estimator, ossModelPathToLoad string) (string, error) {
if ossModelPathToLoad == "" {
return "", nil
}
loadCodeTemplate := template.Must(template.New("LoadModel").Parse(tfLoadModelTmplText))
filler := loadModelFiller{
OSSModelDir: ossModelPathToLoad,
Estimator: estimator,
}
var loadCode bytes.Buffer
if err := loadCodeTemplate.Execute(&loadCode, filler); err != nil {
return "", err
}
return loadCode.String(), nil
}
// TFTrainWithLoadAndSave generates PAI-TF train program.
// Load pre-trained model if modelPathToLoad != "".
// Save the trained model to modelPathToSave.
func TFTrainWithLoadAndSave(ir *ir.TrainStmt, session *pb.Session, modelPathToSave, modelPathToLoad string, cc *ClusterConfig) (string, error) {
// Distributed training must call train_and_evaluate, which need the user to specify validation.select
valSelect, valOK := ir.Attributes["validation.select"]
hasVal := true
if !valOK || valSelect.(string) == "" {
hasVal = false
}
if cc.Worker.Count > 1 && !hasVal {
return "", fmt.Errorf("Distributed training must specify WITH validation.select")
}
loadCode, err := generateLoadOSSModelCode(ir.Estimator, modelPathToLoad)
if err != nil {
return "", err
}
trainCode, err := tensorflow.Train(ir, session)
if err != nil {
return "", err
}
fullCode := fmt.Sprintf("%s\n%s", loadCode, trainCode)
return fullCode, nil
}
// TFLoadAndPredict generates PAI-TF prediction program.
func TFLoadAndPredict(ir *ir.PredictStmt, session *pb.Session, modelPath string) (string, error) {
var tpl = template.Must(template.New("Predict").Parse(tfPredictTmplText))
ossModelDir := OSSModelURL(modelPath)
paiPredictTable := ""
if tensorflow.IsPAI() && ir.TmpPredictTable != "" {
paiPredictTable = ir.TmpPredictTable
}
filler := predictFiller{
OSSModelDir: ossModelDir,
DataSource: session.DbConnStr,
Select: ir.Select,
ResultTable: ir.ResultTable,
ResultColumn: ir.ResultColumn,
PAITable: paiPredictTable,
Using: ir.Using,
}
var code bytes.Buffer
if err := tpl.Execute(&code, filler); err != nil {
return "", err
}
return code.String(), nil
}
// TFLoadAndExplain generates PAI-TF explain program.
func TFLoadAndExplain(ir *ir.ExplainStmt, session *pb.Session, modelPath string, expn *ExplainRender) (string, error) {
var tpl = template.Must(template.New("Explain").Parse(tfExplainTmplText))
ossModelDir := OSSModelURL(modelPath)
paiExplainTable := ""
if tensorflow.IsPAI() && ir.TmpExplainTable != "" {
paiExplainTable = ir.TmpExplainTable
}
filler := explainFiller{
OSSModelDir: ossModelDir,
DataSource: session.DbConnStr,
Select: ir.Select,
ResultTable: ir.Into,
IsPAI: tensorflow.IsPAI(),
PAITable: paiExplainTable,
// TODO(weiguo): use GFile to write oss without ak/sk
// ref: https://yuque.antfin-inc.com/pai-user/manual/tf_oss_by_gfile
ResultOSSDest: expn.key,
ResultOSSAK: expn.ak,
ResultOSSSK: expn.sk,
ResultOSSEndpoint: expn.endpoint,
ResultOSSBucket: expn.bucket,
}
var code bytes.Buffer
if err := tpl.Execute(&code, filler); err != nil {
return "", err
}
return code.String(), nil
}
// TFLoadAndEvaluate generates PAI-TF evaluate program.
func TFLoadAndEvaluate(ir *ir.EvaluateStmt, session *pb.Session, modelPath string) (string, error) {
var tpl = template.Must(template.New("Evaluate").Parse(tfEvaluateTmplText))
ossModelDir := OSSModelURL(modelPath)
paiExplainTable := ""
if tensorflow.IsPAI() && ir.TmpEvaluateTable != "" {
paiExplainTable = ir.TmpEvaluateTable
}
// set default metrics to "Accuracy"
validationMetrics := "Accuracy"
if v, ok := ir.Attributes["validationMetrics"]; ok {
// validationMetrics should be a string like: "Accuracy,AUC,Recall"
validationMetrics = v.(string)
}
filler := evaluateFiller{
OSSModelDir: ossModelDir,
DataSource: session.DbConnStr,
Select: ir.Select,
ResultTable: ir.Into,
IsPAI: tensorflow.IsPAI(),
PAITable: paiExplainTable,
ValidationMetrics: validationMetrics,
}
var code bytes.Buffer
if err := tpl.Execute(&code, filler); err != nil {
return "", err
}
return code.String(), nil
}
func getTFPAICmd(cc *ClusterConfig, tarball, paramsFile, modelName, ossModelPath, trainTable, valTable, resTable, project, cwd string) (string, error) {
jobName := strings.Replace(strings.Join([]string{"sqlflow", modelName}, "_"), ".", "_", 0)
cfString, err := json.Marshal(cc)
if err != nil {
return "", err
}
cfQuote := strconv.Quote(string(cfString))
// submit table should format as: odps://<project>/tables/<table>,odps://<project>/tables/<table>...
submitTables, err := maxComputeTableURL(trainTable)
if err != nil {
return "", err
}
if trainTable != valTable && valTable != "" {
valTable, err := maxComputeTableURL(valTable)
if err != nil {
return "", err
}
submitTables = fmt.Sprintf("%s,%s", submitTables, valTable)
}
outputTables := ""
if resTable != "" {
table, err := maxComputeTableURL(resTable)
if err != nil {
return "", err
}
outputTables = fmt.Sprintf("-Doutputs=%s", table)
}
// NOTE(typhoonzero): use -DhyperParameters to define flags passing OSS credentials.
// TODO(typhoonzero): need to find a more secure way to pass credentials.
cmd := fmt.Sprintf("pai -name tensorflow1150 -project algo_public_dev -DmaxHungTimeBeforeGCInSeconds=0 -DjobName=%s -Dtags=dnn -Dscript=%s -DentryFile=entry.py -Dtables=%s %s -DhyperParameters=\"%s\"",
jobName, tarball, submitTables, outputTables, paramsFile)
chkpoint, err := getCheckpointDir(ossModelPath, project)
if err != nil {
return "", err
}
cmd = fmt.Sprintf("%s -DcheckpointDir='%s'", cmd, chkpoint)
if cc.Worker.Count > 1 {
cmd = fmt.Sprintf("%s -Dcluster=%s", cmd, cfQuote)
} else {
cmd = fmt.Sprintf("%s -DgpuRequired='%d'", cmd, cc.Worker.GPU)
}
return cmd, nil
}
type roleArn struct {
Host string `json:"host"`
Arn string `json:"arn"`
}
func getCheckpointDir(ossModelPath, project string) (string, error) {
ckpJSONStr := os.Getenv("SQLFLOW_OSS_CHECKPOINT_CONFIG")
if ckpJSONStr == "" {
return "", fmt.Errorf("need to configure SQLFLOW_OSS_CHECKPOINT_CONFIG when submitting to PAI")
}
ra := roleArn{}
if err := json.Unmarshal([]byte(ckpJSONStr), &ra); err != nil {
return "", err
}
ossURL := OSSModelURL(ossModelPath)
roleName := genRoleName(project)
// format the oss checkpoint path with ARN authorization.
return fmt.Sprintf("%s/?role_arn=%s/%s&host=%s", ossURL, ra.Arn, roleName, ra.Host), nil
}
// A valid role name contains letters and numbers only.
// The prefix 'pai2oss' of the role name denotes PAI access OSS
func genRoleName(project string) string {
var rn bytes.Buffer
rn.WriteString("pai2oss")
for _, ch := range project {
if (ch >= 'a' && ch <= 'z') || (ch >= '0' && ch <= '9') {
rn.WriteRune(ch)
} else if ch >= 'A' && ch <= 'Z' {
rn.WriteRune(ch - 'A' + 'a')
}
}
return rn.String()
}