-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathLightGBMSWIG.java
263 lines (228 loc) · 9.24 KB
/
LightGBMSWIG.java
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
/*
* Copyright 2020 Feedzai
*
* 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 com.feedzai.openml.provider.lightgbm;
import com.feedzai.openml.data.Instance;
import com.feedzai.openml.data.schema.DatasetSchema;
import com.feedzai.openml.provider.exception.ModelLoadingException;
import com.microsoft.ml.lightgbm.lightgbmlibConstants;
import com.microsoft.ml.lightgbm.lightgbmlibJNI;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.nio.file.Path;
import static com.feedzai.openml.provider.lightgbm.LightGBMUtils.BINARY_LGBM_NUM_CLASSES;
/**
* This class is used to wrap any lighgbmlib* calls and expose
* a simpler interface to LightGBM.
*
* <p>This class is <b>ThreadSafe</b>, not allowing for serializing any attempts for parallel scoring.
*
* @author Alberto Ferreira ([email protected])
* @since 1.0.10
*/
class LightGBMSWIG {
/**
* Logger for this class.
*/
private static final Logger logger = LoggerFactory.getLogger(LightGBMSWIG.class);
/**
* Stores the index to the target field in the schema.
*/
private final int schemaTargetIndex;
/**
* Constant: number of predictive fields in the schema.
*/
private final int schemaNumFeatures;
/**
* Number of features in the schema.
*/
private final int schemaNumFields;
/**
* Holds the number of features used by the model.
* It is fetched from the model binary and initialized at the constructor.
*/
private int boosterNumFeatures;
/**
* Number of loaded model classes.
* LightGBM represents binary classification as 1.
*/
private int boosterNumClasses;
/**
* This handles all low-level swig resource handlers
* creation/destruction to avoid memory issues
* and guarantee that those operations are correct
* even when low-level exceptions are thrown.
*/
private final SWIGResources swigResources;
/**
* Will read the model at path and initialize it.
* If any LightGBM error arises a ModelLoadingException is thrown.
* @param modelPath Path to the model
* @param schema Input schema
* @throws ModelLoadingException in case any LightGBM error occurs.
*/
LightGBMSWIG(final String modelPath, final DatasetSchema schema) throws ModelLoadingException {
this.schemaNumFields = schema.getFieldSchemas().size();
// TODO: should not be received! Model should know better.
this.schemaNumFeatures = schema.getPredictiveFields().size();
this.schemaTargetIndex = schema.getTargetIndex().orElse(-1);
this.swigResources = new SWIGResources(modelPath, this.schemaNumFeatures);
initBoosterNumClasses();
initGetBoosterNumFeatures();
}
/**
* From the input instance, copies the values into the
* SWIG Instance Array so it can be scored by LightGBM.
*
* <p>Skips the label (if it exists in the instance) and copies only the features.
*
* <p><b>Note</b> that this method is not thread safe (by itself) and thus needs to be called in a synchronized
* manner.
*
* @param instance The instance from pulse.
*/
private void initSWIGInstanceArray(final Instance instance) {
int skipTargetOffset = 0; // set to 1 after passing the target (if it exists)
for (int i = 0; i < this.schemaNumFields; ++i) {
// If the label is not present, targetIndex=-1, thus "if" wont't trigger:
if (i == this.schemaTargetIndex) {
skipTargetOffset = -1;
} else {
lightgbmlibJNI.doubleArray_setitem(
this.swigResources.swigInstancePtr,
i + skipTargetOffset,
instance.getValue(i)
);
}
}
}
/**
* Returns the class distribution scores for the current instance.
*
* @param instance The instance from pulse.
* @return double[2] array with scores.
*/
double[] getBinaryClassDistribution(final Instance instance) {
// we need to lock the resources to avoid having multiple threads sharing the same swig resources.
synchronized (this.swigResources) {
initSWIGInstanceArray(instance);
// LightGBM call configuration:
final int isRowMajor = 1;
final int numIterations = -1;
final String LightGBMParameters = "num_threads=1";
final int returnCodeLGBM = lightgbmlibJNI.LGBM_BoosterPredictForMatSingleRow(
this.swigResources.swigBoosterHandle,
this.swigResources.swigInstancePtr,
lightgbmlibConstants.C_API_DTYPE_FLOAT64,
this.schemaNumFeatures,
isRowMajor,
lightgbmlibConstants.C_API_PREDICT_NORMAL,
numIterations,
LightGBMParameters,
// useless API output: size known already (had to preallocate memory)
this.swigResources.swigOutLengthInt64Ptr,
this.swigResources.swigOutScoresPtr // preallocated memory
);
if (returnCodeLGBM == -1)
throw new LightGBMException();
final double predictionScore = lightgbmlibJNI.doubleArray_getitem(this.swigResources.swigOutScoresPtr, 0);
logger.trace("Prediction: {}", predictionScore);
final double[] binaryPredictionScores = new double[2];
binaryPredictionScores[0] = 1 - predictionScore;
binaryPredictionScores[1] = predictionScore;
return binaryPredictionScores;
}
}
/**
* Calls the SWIG API to fetch the number of features from the model binary.
*
* <p><b>Note</b> that this method is not thread safe (by itself) and thus needs to be called in a synchronized
* manner.
* @throws LightGBMException in case there's any lightGBM error.
*/
private void initGetBoosterNumFeatures() throws LightGBMException {
final int returnCodeLGBM = lightgbmlibJNI.LGBM_BoosterGetNumFeature(this.swigResources.swigBoosterHandle,
this.swigResources.swigOutIntPtr);
if (returnCodeLGBM == -1)
throw new LightGBMException();
this.boosterNumFeatures = lightgbmlibJNI.intp_value(this.swigResources.swigOutIntPtr);
logger.debug("Loaded LightGBM Model has {} features.", this.boosterNumFeatures);
}
/**
* Gets number of features in the model.
*
* @return Number of features in the model (retrieved from model binary).
*/
int getBoosterNumFeatures() {
return this.boosterNumFeatures;
}
/**
* Initializes the number of model classes from the model binary.
*
* <p><b>Note</b> that this method is not thread safe (by itself) and thus needs to be called in a synchronized
* manner.
*
* @throws LightGBMException in case there's an error in the C++ core library.
*/
private void initBoosterNumClasses() throws LightGBMException {
final int returnCodeLGBM = lightgbmlibJNI.LGBM_BoosterGetNumClasses(this.swigResources.swigBoosterHandle,
this.swigResources.swigOutIntPtr);
if (returnCodeLGBM == -1)
throw new LightGBMException();
this.boosterNumClasses = lightgbmlibJNI.intp_value(this.swigResources.swigOutIntPtr);
}
/**
* Gets the number of model classes.
*
* @return Number of model classes (retrieved from model binary).
* NOTE: It's 1 for binary case in LightGBM!
*/
int getBoosterNumClasses() {
return this.boosterNumClasses;
}
/**
* Checks if the model is binary.
*
* @return Returns true if the model is binary.
*/
boolean isModelBinary() {
return this.boosterNumClasses == BINARY_LGBM_NUM_CLASSES;
}
/**
* Gets the number of booster iterations in the model.
*
* @return The number of booster iterations in the model (retrieved from model binary).
*/
int getBoosterNumIterations() { return this.swigResources.getBoosterNumIterations(); }
/**
* Saves the model to disk.
*
* @param outputModelFilePath the path of the output LightGBM model file.
*/
void saveModelToDisk(final Path outputModelFilePath) {
logger.info("Saving model to disk.");
logger.debug("Saving model to disk @ {}.", outputModelFilePath);
final int returnCodeLGBM = lightgbmlibJNI.LGBM_BoosterSaveModel(
this.swigResources.swigBoosterHandle,
0, -1,
outputModelFilePath.toAbsolutePath().toString()
);
if (returnCodeLGBM == -1) {
logger.error("Could not save model to disk.");
throw new LightGBMException();
}
}
}