-
Notifications
You must be signed in to change notification settings - Fork 3
/
search.go
309 lines (268 loc) · 10.5 KB
/
search.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
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
//
// Copyright © 2021 Uncharted Software Inc.
//
// 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 compute
import (
"context"
"path"
"strings"
"github.com/pkg/errors"
log "github.com/unchartedsoftware/plog"
"github.com/uncharted-distil/distil-compute/model"
"github.com/uncharted-distil/distil-compute/pipeline"
"github.com/uncharted-distil/distil-compute/primitive/compute"
api "github.com/uncharted-distil/distil/api/model"
"github.com/uncharted-distil/distil/api/util"
)
type searchResult struct {
fittedSolutionID string
resultID string
resultURI string
}
type pipelineSearchContext struct {
searchID string
dataset string
storageName string
sourceDatasetURI string
trainDatasetURI string
testDatasetURI string
produceDatasetURI string
variables []*model.Variable
targetCol int
groupingCol int
sample bool
}
func (s *SolutionRequest) dispatchSolutionExplainPipeline(client *compute.Client, solutionStorage api.SolutionStorage,
dataStorage api.DataStorage, searchSolutionID string, searchContext pipelineSearchContext, searchResult *searchResult) error {
// get solution description
desc, err := describeSolution(client, searchSolutionID)
if err != nil {
return err
}
_, explainOutputs := s.createExplainPipeline(desc)
// if nothing to explain, then exit
if len(explainOutputs) == 0 {
return nil
}
// create a subset of the test dataset for the explain call if sampling
explainDatasetURI := searchContext.produceDatasetURI
if searchContext.sample {
outputFolder := path.Dir(path.Dir(strings.TrimPrefix(searchContext.produceDatasetURI, "file://")))
maxRows := getExplainDatasetMaxRows(searchContext.variables)
explainDatasetURI, err = SampleDataset(searchContext.produceDatasetURI, outputFolder, maxRows, true, searchContext.targetCol, searchContext.groupingCol)
if err != nil {
return err
}
}
exposedOutputs := []string{}
for _, eo := range explainOutputs {
exposedOutputs = append(exposedOutputs, eo.output)
}
// create the produce request that will generate the explanations - we force the use of CSV for output since the
// go parquet library doesn't handle nested lists well
produceSolutionRequest := createProduceSolutionRequest(explainDatasetURI, searchResult.fittedSolutionID, exposedOutputs, []string{compute.CSVURIValueType})
// generate predictions
_, predictionResponses, err := client.GeneratePredictions(context.Background(), produceSolutionRequest)
if err != nil {
return err
}
for _, response := range predictionResponses {
if response.Progress.State != pipeline.ProgressState_COMPLETED {
// only persist completed responses
continue
}
// Generate a path for each output key that has been exposed
outputKeyURIs := map[string]string{}
for _, exposedOutput := range explainOutputs {
outputURI, err := getFileFromOutput(response, exposedOutput.output)
if err != nil {
return err
}
outputKeyURIs[exposedOutput.key] = outputURI
}
// explain features per-record if the explanation is available
produceOutputs := map[string]*api.SolutionExplainResult{}
explainedResults := make(map[string]*api.SolutionExplainResult)
for _, explain := range explainOutputs {
if explain.typ == ExplainableTypeStep || explain.typ == ExplainableTypeConfidence {
explainURI := outputKeyURIs[explain.key]
log.Infof("explaining feature output from URI '%s'", explainURI)
explainDatasetURI = compute.BuildSchemaFileURI(explainDatasetURI)
parsedExplainResult, err := ExplainFeatureOutput(explainDatasetURI, explainURI)
if err != nil {
log.Warnf("failed to fetch output explanation - %v", err)
continue
}
if parsedExplainResult == nil {
log.Warnf("empty output explanation")
continue
}
parsedExplainResult.ResultURI = searchResult.resultURI
parsedExplainResult.ParsingFunction = explain.parsingFunction
explainedResults[explain.typ] = parsedExplainResult
}
produceOutputs[explain.typ] = &api.SolutionExplainResult{
ResultURI: outputKeyURIs[explain.key],
}
}
featureWeights := explainedResults[ExplainableTypeStep]
if featureWeights != nil {
log.Infof("persisting feature weights")
err = dataStorage.PersistSolutionFeatureWeight(searchContext.dataset, searchContext.storageName, featureWeights.ResultURI, featureWeights.Values)
if err != nil {
return err
}
}
// explain the features at the model level if the explanation is available
explainSolutionOutput := explainOutputs[ExplainableTypeSolution]
if explainSolutionOutput != nil {
explainSolutionURI := outputKeyURIs[explainSolutionOutput.key]
log.Infof("explaining solution output from URI '%s'", explainSolutionURI)
solutionWeights, err := s.explainSolutionOutput(explainSolutionURI, searchSolutionID, searchContext.variables)
if err != nil {
log.Warnf("failed to fetch output explanantion - %v", err)
}
for _, fw := range solutionWeights {
err = solutionStorage.PersistSolutionWeight(fw.SolutionID, fw.FeatureName, fw.FeatureIndex, fw.Weight)
if err != nil {
return err
}
}
}
// store the explain URIs
err = solutionStorage.PersistSolutionExplainedOutput(searchResult.resultID, produceOutputs)
if err != nil {
return err
}
// update results to store additional confidence / explain information
if produceOutputs[ExplainableTypeConfidence] != nil {
err = dataStorage.PersistExplainedResult(searchContext.dataset, searchContext.storageName, searchResult.resultURI, explainedResults[ExplainableTypeConfidence])
if err != nil {
return err
}
}
}
return nil
}
func (s *SolutionRequest) dispatchSolutionSearchPipeline(statusChan chan SolutionStatus, client *compute.Client,
solutionStorage api.SolutionStorage, dataStorage api.DataStorage, searchSolutionID string, searchContext pipelineSearchContext) (*searchResult, error) {
var fittedSolutionID string
var resultURI string
var resultID string
// persist the solution info
s.persistSolutionStatus(statusChan, solutionStorage, searchContext.searchID, searchSolutionID, compute.SolutionFittingStatus)
// fit solution
fitRequest := createFitSolutionRequest(searchContext.trainDatasetURI, searchSolutionID)
// create a context that will let us cancel the streaming request from the client side. We have to do this at the transport
// level rather than the ta3ta2 API level since the API only allows for stopping the search portion of the process
cancelContext, cancelFunc := context.WithCancel(context.Background())
s.CancelFuncs[searchSolutionID] = cancelFunc
fitResults, err := client.GenerateSolutionFit(cancelContext, fitRequest)
if err != nil {
return nil, err
}
// find the completed result and get the fitted solution ID out
for _, result := range fitResults {
if result.GetFittedSolutionId() != "" {
fittedSolutionID = result.GetFittedSolutionId()
break
}
}
if fittedSolutionID == "" {
return nil, errors.Errorf("no fitted solution ID for solution `%s`", searchSolutionID)
}
s.persistSolutionStatus(statusChan, solutionStorage, searchContext.searchID, searchSolutionID, compute.SolutionScoringStatus)
// score solution
solutionScoreResponses, err := client.GenerateSolutionScores(cancelContext, searchSolutionID, searchContext.testDatasetURI, s.Metrics, s.PosLabel)
if err != nil {
return nil, err
}
// persist the scores
for _, response := range solutionScoreResponses {
// only persist scores from COMPLETED responses
if response.Progress.State == pipeline.ProgressState_COMPLETED {
for _, score := range response.Scores {
metric := ""
if score.GetMetric() == nil {
metric = compute.ConvertMetricsFromTA3ToTA2(s.Metrics, s.PosLabel)[0].GetMetric()
} else {
metric = score.Metric.Metric
}
err := solutionStorage.PersistSolutionScore(searchSolutionID, metric, score.Value.GetRaw().GetDouble())
if err != nil {
return nil, err
}
}
}
}
// persist solution running status
s.persistSolutionStatus(statusChan, solutionStorage, searchContext.searchID, searchSolutionID, compute.SolutionProducingStatus)
// generate output keys, adding one extra for explanation output if we expect it to exist
outputKeys := []string{compute.DefaultExposedOutputKey}
exposeType := []string{}
if s.useParquet {
exposeType = append(exposeType, compute.ParquetURIValueType)
}
produceSolutionRequest := createProduceSolutionRequest(searchContext.produceDatasetURI, fittedSolutionID, outputKeys, exposeType)
// generate predictions
produceRequestID, predictionResponses, err := client.GeneratePredictions(cancelContext, produceSolutionRequest)
if err != nil {
return nil, err
}
for _, response := range predictionResponses {
if response.Progress.State != pipeline.ProgressState_COMPLETED {
// only persist completed responses
continue
}
// Generate a path for each output key that has been exposed
outputKeyURIs := map[string]string{}
for _, exposedOutputKey := range outputKeys {
outputURI, err := getFileFromOutput(response, exposedOutputKey)
if err != nil {
return nil, err
}
outputKeyURIs[exposedOutputKey] = outputURI
}
// get the result UUID. NOTE: Doing sha1 for now.
var ok bool
resultURI, ok = outputKeyURIs[compute.DefaultExposedOutputKey]
if ok {
// reformat result to have one row per d3m index since confidences
// can produce one row / class
resultURI, err = reformatResult(resultURI)
if err != nil {
return nil, err
}
resultID, err = util.Hash(resultURI)
if err != nil {
return nil, err
}
}
// persist results
log.Infof("persisting results in URI '%s'", resultURI)
err = s.persistSolutionResults(statusChan, client, solutionStorage, dataStorage, searchContext.searchID,
searchContext.dataset, searchContext.storageName, searchSolutionID, fittedSolutionID, produceRequestID, resultID, resultURI)
if err != nil {
return nil, err
}
}
if err != nil {
return nil, err
}
return &searchResult{
resultID: resultID,
resultURI: resultURI,
fittedSolutionID: fittedSolutionID,
}, nil
}