dataset.cpp 37 KB
Newer Older
Guolin Ke's avatar
Guolin Ke committed
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <LightGBM/dataset.h>

#include <LightGBM/feature.h>
#include <LightGBM/network.h>

#include <omp.h>

#include <cstdio>
#include <unordered_map>
#include <limits>
#include <vector>
#include <utility>
#include <string>
Guolin Ke's avatar
Guolin Ke committed
14
#include <sstream>
Guolin Ke's avatar
Guolin Ke committed
15
16
17
18

namespace LightGBM {

Dataset::Dataset(const char* data_filename, const char* init_score_filename,
Guolin Ke's avatar
Guolin Ke committed
19
20
  const IOConfig& io_config, const PredictFunction& predict_fun)
  :data_filename_(data_filename), random_(io_config.data_random_seed),
Guolin Ke's avatar
Guolin Ke committed
21
22
  max_bin_(io_config.max_bin), is_enable_sparse_(io_config.is_enable_sparse), 
  predict_fun_(predict_fun), bin_construct_sample_cnt_(io_config.bin_construct_sample_cnt) {
23
  num_class_ = io_config.num_class;
Guolin Ke's avatar
Guolin Ke committed
24
25
26
  if (io_config.enable_load_from_binary_file) {
    CheckCanLoadFromBin();
  }
Guolin Ke's avatar
Guolin Ke committed
27
  if (is_loading_from_binfile_ && predict_fun != nullptr) {
28
    Log::Info("Cannot initialize prediction by using a binary file, using text file instead");
Guolin Ke's avatar
Guolin Ke committed
29
30
31
32
    is_loading_from_binfile_ = false;
  }

  if (!is_loading_from_binfile_) {
33
    // load weight, query information and initialize score
34
    metadata_.Init(data_filename, init_score_filename, num_class_);
Guolin Ke's avatar
Guolin Ke committed
35
36
37
38
39
40
41
42
    // create text reader
    text_reader_ = new TextReader<data_size_t>(data_filename, io_config.has_header);

    std::unordered_map<std::string, int> name2idx;
    // get column names
    if (io_config.has_header) {
      std::string first_line = text_reader_->first_line();
      feature_names_ = Common::Split(first_line.c_str(), "\t ,");
Guolin Ke's avatar
Guolin Ke committed
43
44
      for (size_t i = 0; i < feature_names_.size(); ++i) {
        name2idx[feature_names_[i]] = static_cast<int>(i);
Guolin Ke's avatar
Guolin Ke committed
45
46
47
48
49
50
51
52
53
54
      }
    }
    std::string name_prefix("name:");

    // load label idx
    if (io_config.label_column.size() > 0) {
      if (Common::StartsWith(io_config.label_column, name_prefix)) {
        std::string name = io_config.label_column.substr(name_prefix.size());
        if (name2idx.count(name) > 0) {
          label_idx_ = name2idx[name];
55
          Log::Info("Using column %s as label", name.c_str());
Guolin Ke's avatar
Guolin Ke committed
56
        } else {
57
          Log::Fatal("Could not find label column %s in data file", name.c_str());
Guolin Ke's avatar
Guolin Ke committed
58
59
        }
      } else {
60
        if (!Common::AtoiAndCheck(io_config.label_column.c_str(), &label_idx_)) {
Guolin Ke's avatar
Guolin Ke committed
61
          Log::Fatal("label_column is not a number, \
62
63
                      if you want to use a column name, \
                      please add the prefix \"name:\" to the column name");
Guolin Ke's avatar
Guolin Ke committed
64
        }
65
        Log::Info("Using column number %d as label", label_idx_);
Guolin Ke's avatar
Guolin Ke committed
66
67
      }
    }
Guolin Ke's avatar
Guolin Ke committed
68
69
70
71
    if (feature_names_.size() > 0) {
      // erase label column name
      feature_names_.erase(feature_names_.begin() + label_idx_);
    }
Guolin Ke's avatar
Guolin Ke committed
72
73
74
75
76
77
78
79
80
81
82
    // load ignore columns
    if (io_config.ignore_column.size() > 0) {
      if (Common::StartsWith(io_config.ignore_column, name_prefix)) {
        std::string names = io_config.ignore_column.substr(name_prefix.size());
        for (auto name : Common::Split(names.c_str(), ',')) {
          if (name2idx.count(name) > 0) {
            int tmp = name2idx[name];
            // skip for label column
            if (tmp > label_idx_) { tmp -= 1; }
            ignore_features_.emplace(tmp);
          } else {
83
            Log::Fatal("Could not find ignore column %s in data file", name.c_str());
Guolin Ke's avatar
Guolin Ke committed
84
85
86
87
          }
        }
      } else {
        for (auto token : Common::Split(io_config.ignore_column.c_str(), ',')) {
88
89
          int tmp = 0;
          if (!Common::AtoiAndCheck(token.c_str(), &tmp)) {
Guolin Ke's avatar
Guolin Ke committed
90
            Log::Fatal("ignore_column is not a number, \
91
92
                        if you want to use a column name, \
                        please add the prefix \"name:\" to the column name");
Guolin Ke's avatar
Guolin Ke committed
93
          }
Guolin Ke's avatar
Guolin Ke committed
94
95
96
97
98
99
100
101
102
103
104
105
106
107
          // skip for label column
          if (tmp > label_idx_) { tmp -= 1; }
          ignore_features_.emplace(tmp);
        }
      }

    }

    // load weight idx
    if (io_config.weight_column.size() > 0) {
      if (Common::StartsWith(io_config.weight_column, name_prefix)) {
        std::string name = io_config.weight_column.substr(name_prefix.size());
        if (name2idx.count(name) > 0) {
          weight_idx_ = name2idx[name];
108
          Log::Info("Using column %s as weight", name.c_str());
Guolin Ke's avatar
Guolin Ke committed
109
        } else {
110
          Log::Fatal("Could not find weight column %s in data file", name.c_str());
Guolin Ke's avatar
Guolin Ke committed
111
112
        }
      } else {
113
        if (!Common::AtoiAndCheck(io_config.weight_column.c_str(), &weight_idx_)) {
Guolin Ke's avatar
Guolin Ke committed
114
          Log::Fatal("weight_column is not a number, \
115
116
                      if you want to use a column name, \
                      please add the prefix \"name:\" to the column name");
Guolin Ke's avatar
Guolin Ke committed
117
        }
118
        Log::Info("Using column number %d as weight", weight_idx_);
Guolin Ke's avatar
Guolin Ke committed
119
120
121
122
123
124
125
126
127
128
129
130
131
      }
      // skip for label column
      if (weight_idx_ > label_idx_) {
        weight_idx_ -= 1;
      }
      ignore_features_.emplace(weight_idx_);
    }

    if (io_config.group_column.size() > 0) {
      if (Common::StartsWith(io_config.group_column, name_prefix)) {
        std::string name = io_config.group_column.substr(name_prefix.size());
        if (name2idx.count(name) > 0) {
          group_idx_ = name2idx[name];
132
          Log::Info("Using column %s as group/query id", name.c_str());
Guolin Ke's avatar
Guolin Ke committed
133
        } else {
134
          Log::Fatal("Could not find group/query column %s in data file", name.c_str());
Guolin Ke's avatar
Guolin Ke committed
135
136
        }
      } else {
137
        if (!Common::AtoiAndCheck(io_config.group_column.c_str(), &group_idx_)) {
Guolin Ke's avatar
Guolin Ke committed
138
          Log::Fatal("group_column is not a number, \
139
140
                      if you want to use a column name, \
                      please add the prefix \"name:\" to the column name");
Guolin Ke's avatar
Guolin Ke committed
141
        }
142
        Log::Info("Using column number %d as group/query id", group_idx_);
Guolin Ke's avatar
Guolin Ke committed
143
144
145
146
147
148
149
150
      }
      // skip for label column
      if (group_idx_ > label_idx_) {
        group_idx_ -= 1;
      }
      ignore_features_.emplace(group_idx_);
    }

Guolin Ke's avatar
Guolin Ke committed
151
    // create text parser
Guolin Ke's avatar
Guolin Ke committed
152
    parser_ = Parser::CreateParser(data_filename_, io_config.has_header, 0, label_idx_);
Guolin Ke's avatar
Guolin Ke committed
153
    if (parser_ == nullptr) {
154
      Log::Fatal("Could not recognize data format of %s", data_filename_);
Guolin Ke's avatar
Guolin Ke committed
155
156
    }
  } else {
157
    // only need to load initialize score, other meta data will be loaded from binary file
158
    metadata_.Init(init_score_filename, num_class_);
159
    Log::Info("Loading data set from binary file");
Guolin Ke's avatar
Guolin Ke committed
160
161
162
163
164
165
    parser_ = nullptr;
    text_reader_ = nullptr;
  }

}

Guolin Ke's avatar
Guolin Ke committed
166
167
168
169
Dataset::Dataset(const IOConfig& io_config, const PredictFunction& predict_fun)
  :data_filename_(""), random_(io_config.data_random_seed),
  max_bin_(io_config.max_bin), is_enable_sparse_(io_config.is_enable_sparse),
  predict_fun_(predict_fun), bin_construct_sample_cnt_(io_config.bin_construct_sample_cnt) {
Guolin Ke's avatar
Guolin Ke committed
170
  num_class_ = io_config.num_class;
Guolin Ke's avatar
Guolin Ke committed
171
172
173
174
175
176
  parser_ = nullptr;
  text_reader_ = nullptr;
}



Guolin Ke's avatar
Guolin Ke committed
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
Dataset::~Dataset() {
  if (parser_ != nullptr) { delete parser_; }
  if (text_reader_ != nullptr) { delete text_reader_; }
  for (auto& feature : features_) {
    delete feature;
  }
  features_.clear();
}

void Dataset::LoadDataToMemory(int rank, int num_machines, bool is_pre_partition) {
  used_data_indices_.clear();
  if (num_machines == 1 || is_pre_partition) {
    // read all lines
    num_data_ = text_reader_->ReadAllLines();
    global_num_data_ = num_data_;
  } else {  // need partition data
    // get query data
    const data_size_t* query_boundaries = metadata_.query_boundaries();

    if (query_boundaries == nullptr) {
      // if not contain query data, minimal sample unit is one record
      global_num_data_ = text_reader_->ReadAndFilterLines([this, rank, num_machines](data_size_t) {
        if (random_.NextInt(0, num_machines) == rank) {
          return true;
        } else {
          return false;
        }
      }, &used_data_indices_);
    } else {
      // if contain query data, minimal sample unit is one query
      data_size_t num_queries = metadata_.num_queries();
      data_size_t qid = -1;
      bool is_query_used = false;
      global_num_data_ = text_reader_->ReadAndFilterLines(
        [this, rank, num_machines, &qid, &query_boundaries, &is_query_used, num_queries]
      (data_size_t line_idx) {
        if (qid >= num_queries) {
214
          Log::Fatal("Current query exceeds the range of the query file, please ensure the query file is correct");
Guolin Ke's avatar
Guolin Ke committed
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
        }
        if (line_idx >= query_boundaries[qid + 1]) {
          // if is new query
          is_query_used = false;
          if (random_.NextInt(0, num_machines) == rank) {
            is_query_used = true;
          }
          ++qid;
        }
        return is_query_used;
      }, &used_data_indices_);
    }
    // set number of data
    num_data_ = static_cast<data_size_t>(used_data_indices_.size());
  }
}

void Dataset::SampleDataFromMemory(std::vector<std::string>* out_data) {
Guolin Ke's avatar
Guolin Ke committed
233
  const size_t sample_cnt = static_cast<size_t>(num_data_ < bin_construct_sample_cnt_ ? num_data_ : bin_construct_sample_cnt_);
Guolin Ke's avatar
Guolin Ke committed
234
235
236
237
238
239
240
241
242
243
244
  std::vector<size_t> sample_indices = random_.Sample(num_data_, sample_cnt);
  out_data->clear();
  for (size_t i = 0; i < sample_indices.size(); ++i) {
    const size_t idx = sample_indices[i];
    out_data->push_back(text_reader_->Lines()[idx]);
  }
}

void Dataset::SampleDataFromFile(int rank, int num_machines, bool is_pre_partition,
                                             std::vector<std::string>* out_data) {
  used_data_indices_.clear();
Guolin Ke's avatar
Guolin Ke committed
245
  const data_size_t sample_cnt = static_cast<data_size_t>(bin_construct_sample_cnt_);
Guolin Ke's avatar
Guolin Ke committed
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
  if (num_machines == 1 || is_pre_partition) {
    num_data_ = static_cast<data_size_t>(text_reader_->SampleFromFile(random_, sample_cnt, out_data));
    global_num_data_ = num_data_;
  } else {  // need partition data
    // get query data
    const data_size_t* query_boundaries = metadata_.query_boundaries();
    if (query_boundaries == nullptr) {
      // if not contain query file, minimal sample unit is one record
      global_num_data_ = text_reader_->SampleAndFilterFromFile([this, rank, num_machines]
      (data_size_t) {
        if (random_.NextInt(0, num_machines) == rank) {
          return true;
        } else {
          return false;
        }
      }, &used_data_indices_, random_, sample_cnt, out_data);
    } else {
      // if contain query file, minimal sample unit is one query
      data_size_t num_queries = metadata_.num_queries();
      data_size_t qid = -1;
      bool is_query_used = false;
      global_num_data_ = text_reader_->SampleAndFilterFromFile(
        [this, rank, num_machines, &qid, &query_boundaries, &is_query_used, num_queries]
      (data_size_t line_idx) {
        if (qid >= num_queries) {
271
272
          Log::Fatal("Query id exceeds the range of the query file, \
                      please ensure the query file is correct");
Guolin Ke's avatar
Guolin Ke committed
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
        }
        if (line_idx >= query_boundaries[qid + 1]) {
          // if is new query
          is_query_used = false;
          if (random_.NextInt(0, num_machines) == rank) {
            is_query_used = true;
          }
          ++qid;
        }
        return is_query_used;
      }, &used_data_indices_, random_, sample_cnt, out_data);
    }
    num_data_ = static_cast<data_size_t>(used_data_indices_.size());
  }
}

Guolin Ke's avatar
Guolin Ke committed
289
290
291
292
void Dataset::InitByBinMapper(std::vector<const BinMapper*> bin_mappers, data_size_t num_data) {
  num_data_ = num_data;
  global_num_data_ = num_data_;
  // initialize label
Guolin Ke's avatar
Guolin Ke committed
293
  metadata_.Init(num_data_, num_class_, -1, -1);
Guolin Ke's avatar
Guolin Ke committed
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
  // free old memory
  for (auto& feature : features_) {
    delete feature;
  }
  features_.clear();
  used_feature_map_ = std::vector<int>(bin_mappers.size(), -1);
  for (size_t i = 0; i < bin_mappers.size(); ++i) {
    if (bin_mappers[i] != nullptr) {
      features_.push_back(new Feature(static_cast<int>(i), new BinMapper(bin_mappers[i]), num_data_, is_enable_sparse_));
      used_feature_map_[i] = static_cast<int>(features_.size());
    }
  }
  num_features_ = static_cast<int>(features_.size());
}

std::vector<const BinMapper*> Dataset::GetBinMappers() const {
  std::vector<const BinMapper*> ret(num_total_features_, nullptr);
  for (const auto feature : features_) {
    ret[feature->feature_index()] = feature->bin_mapper();
  }
  return ret;
}

void Dataset::PushData(const std::vector<std::vector<std::pair<int, float>>>& datas, data_size_t start_idx, bool is_finished) {
  // if doesn't need to prediction with initial model
#pragma omp parallel for schedule(guided) 
  for (data_size_t i = 0; i < static_cast<int>(datas.size()); ++i) {
    const int tid = omp_get_thread_num();
    for (auto& inner_data : datas[i]) {
      int feature_idx = used_feature_map_[inner_data.first];
      if (feature_idx >= 0) {
        // if is used feature
        features_[feature_idx]->PushData(tid, start_idx + i, inner_data.second);
      } 
    }
  }
  if (is_finished) {
#pragma omp parallel for schedule(guided)
    for (int i = 0; i < num_features_; ++i) {
      features_[i]->FinishLoad();
    }
  }
}

void Dataset::SetField(const char* field_name, const void* field_data, data_size_t num_element, int type) {
  std::string name(field_name);
  name = Common::Trim(name);
  if (name == std::string("label") || name == std::string("target")) {
    if (type != 0) {
      Log::Fatal("type of label should be float");
    }
    metadata_.SetLabel(static_cast<const float*>(field_data), num_element);
  }else if (name == std::string("weight") || name == std::string("weights")) {
    if (type != 0) {
      Log::Fatal("type of weights should be float");
    }
    metadata_.SetWeights(static_cast<const float*>(field_data), num_element);
  } else if (name == std::string("init_score")) {
    if (type != 0) {
      Log::Fatal("type of init_score should be float");
    }
    metadata_.SetInitScore(static_cast<const float*>(field_data), num_element);
  } else if (name == std::string("query") || name == std::string("group")) {
    if (type != 1) {
      Log::Fatal("type of init_score should be int");
    }
    metadata_.SetQueryBoundaries(static_cast<const data_size_t*>(field_data), num_element);
  } else {
    Log::Fatal("unknow field name: %s", field_name);
  }
}

Guolin Ke's avatar
Guolin Ke committed
366
367
void Dataset::ConstructBinMappers(int rank, int num_machines, const std::vector<std::string>& sample_data) {
  // sample_values[i][j], means the value of j-th sample on i-th feature
368
  std::vector<std::vector<double>> sample_values;
Guolin Ke's avatar
Guolin Ke committed
369
  // temp buffer for one line features and label
370
371
  std::vector<std::pair<int, double>> oneline_features;
  double label;
Guolin Ke's avatar
Guolin Ke committed
372
373
374
375
376
377
378
379
  for (size_t i = 0; i < sample_data.size(); ++i) {
    oneline_features.clear();
    // parse features
    parser_->ParseOneLine(sample_data[i].c_str(), &oneline_features, &label);
    // push 0 first, then edit the value according existing feature values
    for (auto& feature_values : sample_values) {
      feature_values.push_back(0.0);
    }
380
    for (std::pair<int, double>& inner_data : oneline_features) {
Guolin Ke's avatar
Guolin Ke committed
381
382
383
384
385
      if (static_cast<size_t>(inner_data.first) >= sample_values.size()) {
        // if need expand feature set
        size_t need_size = inner_data.first - sample_values.size() + 1;
        for (size_t j = 0; j < need_size; ++j) {
          // push i+1 0
386
          sample_values.emplace_back(i + 1, 0.0f);
Guolin Ke's avatar
Guolin Ke committed
387
388
389
390
391
392
393
394
395
396
397
        }
      }
      // edit the feature value
      sample_values[inner_data.first][i] = inner_data.second;
    }
  }

  features_.clear();

  // -1 means doesn't use this feature
  used_feature_map_ = std::vector<int>(sample_values.size(), -1);
Guolin Ke's avatar
Guolin Ke committed
398
  num_total_features_ = static_cast<int>(sample_values.size());
Guolin Ke's avatar
Guolin Ke committed
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413

  // check the range of label_idx, weight_idx and group_idx
  CHECK(label_idx_ >= 0 && label_idx_ <= num_total_features_);
  CHECK(weight_idx_ < 0 || weight_idx_ < num_total_features_);
  CHECK(group_idx_ < 0 || group_idx_ < num_total_features_);

  // fill feature_names_ if not header
  if (feature_names_.size() <= 0) {
    for (int i = 0; i < num_total_features_; ++i) {
      std::stringstream str_buf;
      str_buf << "Column_" << i;
      feature_names_.push_back(str_buf.str());
    }
  }

Guolin Ke's avatar
Guolin Ke committed
414
415
416
  // start find bins
  if (num_machines == 1) {
    std::vector<BinMapper*> bin_mappers(sample_values.size());
417
    // if only one machine, find bin locally
Guolin Ke's avatar
Guolin Ke committed
418
419
    #pragma omp parallel for schedule(guided)
    for (int i = 0; i < static_cast<int>(sample_values.size()); ++i) {
Guolin Ke's avatar
Guolin Ke committed
420
421
422
423
      if (ignore_features_.count(i) > 0) {
        bin_mappers[i] = nullptr;
        continue;
      }
Guolin Ke's avatar
Guolin Ke committed
424
425
426
427
428
      bin_mappers[i] = new BinMapper();
      bin_mappers[i]->FindBin(&sample_values[i], max_bin_);
    }

    for (size_t i = 0; i < sample_values.size(); ++i) {
Guolin Ke's avatar
Guolin Ke committed
429
      if (bin_mappers[i] == nullptr) {
430
        Log::Warning("Ignoring feature %s", feature_names_[i].c_str());
Guolin Ke's avatar
Guolin Ke committed
431
432
      }
      else if (!bin_mappers[i]->is_trival()) {
Guolin Ke's avatar
Guolin Ke committed
433
434
435
436
437
438
439
        // map real feature index to used feature index
        used_feature_map_[i] = static_cast<int>(features_.size());
        // push new feature
        features_.push_back(new Feature(static_cast<int>(i), bin_mappers[i],
                                             num_data_, is_enable_sparse_));
      } else {
        // if feature is trival(only 1 bin), free spaces
440
        Log::Warning("Ignoring feature %s, only has one value", feature_names_[i].c_str());
Guolin Ke's avatar
Guolin Ke committed
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
        delete bin_mappers[i];
      }
    }
  } else {
    // if have multi-machines, need find bin distributed
    // different machines will find bin for different features

    // start and len will store the process feature indices for different machines
    // machine i will find bins for features in [ strat[i], start[i] + len[i] )
    int* start = new int[num_machines];
    int* len = new int[num_machines];
    int total_num_feature = static_cast<int>(sample_values.size());
    int step = (total_num_feature + num_machines - 1) / num_machines;
    if (step < 1) { step = 1; }

    start[0] = 0;
    for (int i = 0; i < num_machines - 1; ++i) {
      len[i] = Common::Min<int>(step, total_num_feature - start[i]);
      start[i + 1] = start[i] + len[i];
    }
    len[num_machines - 1] = total_num_feature - start[num_machines - 1];
    // get size of bin mapper with max_bin_ size
    int type_size = BinMapper::SizeForSpecificBin(max_bin_);
464
    // since sizes of different feature may not be same, we expand all bin mapper to type_size
Guolin Ke's avatar
Guolin Ke committed
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
    int buffer_size = type_size * total_num_feature;
    char* input_buffer = new char[buffer_size];
    char* output_buffer = new char[buffer_size];

    // find local feature bins and copy to buffer
    #pragma omp parallel for schedule(guided)
    for (int i = 0; i < len[rank]; ++i) {
      BinMapper* bin_mapper = new BinMapper();
      bin_mapper->FindBin(&sample_values[start[rank] + i], max_bin_);
      bin_mapper->CopyTo(input_buffer + i * type_size);
      // don't need this any more
      delete bin_mapper;
    }
    // convert to binary size
    for (int i = 0; i < num_machines; ++i) {
      start[i] *= type_size;
      len[i] *= type_size;
    }
    // gather global feature bin mappers
    Network::Allgather(input_buffer, buffer_size, start, len, output_buffer);
    // restore features bins from buffer
    for (int i = 0; i < total_num_feature; ++i) {
Guolin Ke's avatar
Guolin Ke committed
487
      if (ignore_features_.count(i) > 0) {
488
        Log::Warning("Ignoring feature %s", feature_names_[i].c_str());
Guolin Ke's avatar
Guolin Ke committed
489
490
        continue;
      }
Guolin Ke's avatar
Guolin Ke committed
491
492
493
494
495
496
      BinMapper* bin_mapper = new BinMapper();
      bin_mapper->CopyFrom(output_buffer + i * type_size);
      if (!bin_mapper->is_trival()) {
        used_feature_map_[i] = static_cast<int>(features_.size());
        features_.push_back(new Feature(static_cast<int>(i), bin_mapper, num_data_, is_enable_sparse_));
      } else {
497
        Log::Warning("Ignoring feature %s, only has one value", feature_names_[i].c_str());
Guolin Ke's avatar
Guolin Ke committed
498
499
500
501
502
503
504
505
506
507
508
509
510
511
        delete bin_mapper;
      }
    }
    // free buffer
    delete[] start;
    delete[] len;
    delete[] input_buffer;
    delete[] output_buffer;
  }
  num_features_ = static_cast<int>(features_.size());
}


void Dataset::LoadTrainData(int rank, int num_machines, bool is_pre_partition, bool use_two_round_loading) {
Guolin Ke's avatar
Guolin Ke committed
512
  // don't support query id in data file when training in parallel
Guolin Ke's avatar
Guolin Ke committed
513
514
  if (num_machines > 1 && !is_pre_partition) {
    if (group_idx_ > 0) {
515
516
      Log::Fatal("Using a query id without pre-partitioning the data file is not supported for parallel training. \
                  Please use an additional query file or pre-partition the data");
Guolin Ke's avatar
Guolin Ke committed
517
518
    }
  }
Guolin Ke's avatar
Guolin Ke committed
519
520
521
522
523
524
525
526
527
528
529
  used_data_indices_.clear();
  if (!is_loading_from_binfile_ ) {
    if (!use_two_round_loading) {
      // read data to memory
      LoadDataToMemory(rank, num_machines, is_pre_partition);
      std::vector<std::string> sample_data;
      // sample data
      SampleDataFromMemory(&sample_data);
      // construct feature bin mappers
      ConstructBinMappers(rank, num_machines, sample_data);
      // initialize label
530
      metadata_.Init(num_data_, num_class_, weight_idx_, group_idx_);
Guolin Ke's avatar
Guolin Ke committed
531
532
533
534
535
536
537
538
539
      // extract features
      ExtractFeaturesFromMemory();
    } else {
      std::vector<std::string> sample_data;
      // sample data from file
      SampleDataFromFile(rank, num_machines, is_pre_partition, &sample_data);
      // construct feature bin mappers
      ConstructBinMappers(rank, num_machines, sample_data);
      // initialize label
540
      metadata_.Init(num_data_, num_class_, weight_idx_, group_idx_);
Guolin Ke's avatar
Guolin Ke committed
541
542
543
544
545

      // extract features
      ExtractFeaturesFromFile();
    }
  } else {
Guolin Ke's avatar
Guolin Ke committed
546
547
    std::string bin_filename(data_filename_);
    bin_filename.append(".bin");
Guolin Ke's avatar
Guolin Ke committed
548
    // load data from binary file
Guolin Ke's avatar
Guolin Ke committed
549
    LoadDataFromBinFile(bin_filename.c_str(), rank, num_machines, is_pre_partition);
Guolin Ke's avatar
Guolin Ke committed
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
  }
  // check meta data
  metadata_.CheckOrPartition(static_cast<data_size_t>(global_num_data_), used_data_indices_);
  // free memory
  used_data_indices_.clear();
  used_data_indices_.shrink_to_fit();
  // need to check training data
  CheckDataset();
}

void Dataset::LoadValidationData(const Dataset* train_set, bool use_two_round_loading) {
  used_data_indices_.clear();
  if (!is_loading_from_binfile_ ) {
    if (!use_two_round_loading) {
      // read data in memory
      LoadDataToMemory(0, 1, false);
      // initialize label
567
      metadata_.Init(num_data_, num_class_, weight_idx_, group_idx_);
Guolin Ke's avatar
Guolin Ke committed
568
569
570
571
572
573
574
      features_.clear();
      // copy feature bin mapper data
      for (Feature* feature : train_set->features_) {
        features_.push_back(new Feature(feature->feature_index(), new BinMapper(*feature->bin_mapper()), num_data_, is_enable_sparse_));
      }
      used_feature_map_ = train_set->used_feature_map_;
      num_features_ = static_cast<int>(features_.size());
575
576
      num_total_features_ = train_set->num_total_features_;
      feature_names_ = train_set->feature_names_;
Guolin Ke's avatar
Guolin Ke committed
577
578
579
580
581
582
      // extract features
      ExtractFeaturesFromMemory();
    } else {
      // Get number of lines of data file
      num_data_ = static_cast<data_size_t>(text_reader_->CountLine());
      // initialize label
583
      metadata_.Init(num_data_, num_class_, weight_idx_, group_idx_);
Guolin Ke's avatar
Guolin Ke committed
584
585
586
587
588
589
590
      features_.clear();
      // copy feature bin mapper data
      for (Feature* feature : train_set->features_) {
        features_.push_back(new Feature(feature->feature_index(), new BinMapper(*feature->bin_mapper()), num_data_, is_enable_sparse_));
      }
      used_feature_map_ = train_set->used_feature_map_;
      num_features_ = static_cast<int>(features_.size());
591
592
      num_total_features_ = train_set->num_total_features_;
      feature_names_ = train_set->feature_names_;
Guolin Ke's avatar
Guolin Ke committed
593
594
595
596
      // extract features
      ExtractFeaturesFromFile();
    }
  } else {
Guolin Ke's avatar
Guolin Ke committed
597
598
    std::string bin_filename(data_filename_);
    bin_filename.append(".bin");
Guolin Ke's avatar
Guolin Ke committed
599
    // load from binary file
Guolin Ke's avatar
Guolin Ke committed
600
    LoadDataFromBinFile(bin_filename.c_str(), 0, 1, false);
Guolin Ke's avatar
Guolin Ke committed
601
602
603
604
605
606
607
608
  }
  // not need to check validation data
  // check meta data
  metadata_.CheckOrPartition(static_cast<data_size_t>(global_num_data_), used_data_indices_);
  // CheckDataset();
}

void Dataset::ExtractFeaturesFromMemory() {
609
610
  std::vector<std::pair<int, double>> oneline_features;
  double tmp_label = 0.0f;
Guolin Ke's avatar
Guolin Ke committed
611
612
613
614
615
616
617
618
619
  if (predict_fun_ == nullptr) {
    // if doesn't need to prediction with initial model
    #pragma omp parallel for schedule(guided) private(oneline_features) firstprivate(tmp_label)
    for (data_size_t i = 0; i < num_data_; ++i) {
      const int tid = omp_get_thread_num();
      oneline_features.clear();
      // parser
      parser_->ParseOneLine(text_reader_->Lines()[i].c_str(), &oneline_features, &tmp_label);
      // set label
620
      metadata_.SetLabelAt(i, static_cast<float>(tmp_label));
Guolin Ke's avatar
Guolin Ke committed
621
622
623
624
625
626
627
628
629
630
631
      // free processed line:
      text_reader_->Lines()[i].clear();
      // shrink_to_fit will be very slow in linux, and seems not free memory, disable for now
      // text_reader_->Lines()[i].shrink_to_fit();
      // push data
      for (auto& inner_data : oneline_features) {
        int feature_idx = used_feature_map_[inner_data.first];
        if (feature_idx >= 0) {
          // if is used feature
          features_[feature_idx]->PushData(tid, i, inner_data.second);
        }
Guolin Ke's avatar
Guolin Ke committed
632
633
        else {
          if (inner_data.first == weight_idx_) {
634
            metadata_.SetWeightAt(i, static_cast<float>(inner_data.second));
Guolin Ke's avatar
Guolin Ke committed
635
          } else if (inner_data.first == group_idx_) {
Guolin Ke's avatar
Guolin Ke committed
636
            metadata_.SetQueryAt(i, static_cast<data_size_t>(inner_data.second));
Guolin Ke's avatar
Guolin Ke committed
637
638
          }
        }
Guolin Ke's avatar
Guolin Ke committed
639
640
641
642
      }
    }
  } else {
    // if need to prediction with initial model
643
    float* init_score = new float[num_data_ * num_class_];
Guolin Ke's avatar
Guolin Ke committed
644
645
646
647
648
649
650
    #pragma omp parallel for schedule(guided) private(oneline_features) firstprivate(tmp_label)
    for (data_size_t i = 0; i < num_data_; ++i) {
      const int tid = omp_get_thread_num();
      oneline_features.clear();
      // parser
      parser_->ParseOneLine(text_reader_->Lines()[i].c_str(), &oneline_features, &tmp_label);
      // set initial score
651
      std::vector<double> oneline_init_score = predict_fun_(oneline_features);
652
      for (int k = 0; k < num_class_; ++k){
653
        init_score[k * num_data_ + i] = static_cast<float>(oneline_init_score[k]);
654
      }
Guolin Ke's avatar
Guolin Ke committed
655
      // set label
656
      metadata_.SetLabelAt(i, static_cast<float>(tmp_label));
Guolin Ke's avatar
Guolin Ke committed
657
658
659
660
661
662
663
664
665
666
667
      // free processed line:
      text_reader_->Lines()[i].clear();
      // shrink_to_fit will be very slow in linux, and seems not free memory, disable for now
      // text_reader_->Lines()[i].shrink_to_fit();
      // push data
      for (auto& inner_data : oneline_features) {
        int feature_idx = used_feature_map_[inner_data.first];
        if (feature_idx >= 0) {
          // if is used feature
          features_[feature_idx]->PushData(tid, i, inner_data.second);
        }
Guolin Ke's avatar
Guolin Ke committed
668
669
        else {
          if (inner_data.first == weight_idx_) {
670
            metadata_.SetWeightAt(i, static_cast<float>(inner_data.second));
Guolin Ke's avatar
Guolin Ke committed
671
          } else if (inner_data.first == group_idx_) {
Guolin Ke's avatar
Guolin Ke committed
672
            metadata_.SetQueryAt(i, static_cast<data_size_t>(inner_data.second));
Guolin Ke's avatar
Guolin Ke committed
673
674
          }
        }
Guolin Ke's avatar
Guolin Ke committed
675
676
677
      }
    }
    // metadata_ will manage space of init_score
678
    metadata_.SetInitScore(init_score, num_data_ * num_class_);
Guolin Ke's avatar
Guolin Ke committed
679
    delete[] init_score;
Guolin Ke's avatar
Guolin Ke committed
680
681
682
  }

  #pragma omp parallel for schedule(guided)
683
  for (int i = 0; i < num_features_; ++i) {
Guolin Ke's avatar
Guolin Ke committed
684
685
686
687
688
689
690
691
    features_[i]->FinishLoad();
  }
  // text data can be free after loaded feature values
  text_reader_->Clear();
}


void Dataset::ExtractFeaturesFromFile() {
Guolin Ke's avatar
Guolin Ke committed
692
  float* init_score = nullptr;
Guolin Ke's avatar
Guolin Ke committed
693
  if (predict_fun_ != nullptr) {
694
    init_score = new float[num_data_ * num_class_];
Guolin Ke's avatar
Guolin Ke committed
695
696
697
698
  }
  std::function<void(data_size_t, const std::vector<std::string>&)> process_fun =
    [this, &init_score]
  (data_size_t start_idx, const std::vector<std::string>& lines) {
699
700
    std::vector<std::pair<int, double>> oneline_features;
    double tmp_label = 0.0f;
Guolin Ke's avatar
Guolin Ke committed
701
    #pragma omp parallel for schedule(static) private(oneline_features) firstprivate(tmp_label)
702
    for (data_size_t i = 0; i < static_cast<data_size_t>(lines.size()); ++i) {
Guolin Ke's avatar
Guolin Ke committed
703
704
705
706
707
708
      const int tid = omp_get_thread_num();
      oneline_features.clear();
      // parser
      parser_->ParseOneLine(lines[i].c_str(), &oneline_features, &tmp_label);
      // set initial score
      if (init_score != nullptr) {
709
        std::vector<double> oneline_init_score = predict_fun_(oneline_features);
710
711
712
        for (int k = 0; k < num_class_; ++k){
            init_score[k * num_data_ + start_idx + i] = static_cast<float>(oneline_init_score[k]);
        }
Guolin Ke's avatar
Guolin Ke committed
713
714
      }
      // set label
715
      metadata_.SetLabelAt(start_idx + i, static_cast<float>(tmp_label));
Guolin Ke's avatar
Guolin Ke committed
716
717
718
719
720
721
722
      // push data
      for (auto& inner_data : oneline_features) {
        int feature_idx = used_feature_map_[inner_data.first];
        if (feature_idx >= 0) {
          // if is used feature
          features_[feature_idx]->PushData(tid, start_idx + i, inner_data.second);
        }
Guolin Ke's avatar
Guolin Ke committed
723
724
        else {
          if (inner_data.first == weight_idx_) {
725
            metadata_.SetWeightAt(start_idx + i, static_cast<float>(inner_data.second));
Guolin Ke's avatar
Guolin Ke committed
726
          } else if (inner_data.first == group_idx_) {
Guolin Ke's avatar
Guolin Ke committed
727
            metadata_.SetQueryAt(start_idx + i, static_cast<data_size_t>(inner_data.second));
Guolin Ke's avatar
Guolin Ke committed
728
729
          }
        }
Guolin Ke's avatar
Guolin Ke committed
730
731
732
733
734
735
736
737
738
739
740
741
742
743
      }
    }
  };

  if (used_data_indices_.size() > 0) {
    // only need part of data
    text_reader_->ReadPartAndProcessParallel(used_data_indices_, process_fun);
  } else {
    // need full data
    text_reader_->ReadAllAndProcessParallel(process_fun);
  }

  // metadata_ will manage space of init_score
  if (init_score != nullptr) {
744
    metadata_.SetInitScore(init_score, num_data_ * num_class_);
Guolin Ke's avatar
Guolin Ke committed
745
    delete[] init_score;
Guolin Ke's avatar
Guolin Ke committed
746
747
748
  }

  #pragma omp parallel for schedule(guided)
749
  for (int i = 0; i < num_features_; ++i) {
Guolin Ke's avatar
Guolin Ke committed
750
751
752
753
    features_[i]->FinishLoad();
  }
}

Guolin Ke's avatar
Guolin Ke committed
754
755
void Dataset::SaveBinaryFile(const char* bin_filename) {
  
Guolin Ke's avatar
Guolin Ke committed
756
  if (!is_loading_from_binfile_) {
Guolin Ke's avatar
Guolin Ke committed
757
758
759
760
761
762
    // if not pass a filename, just append ".bin" of original file
    if (bin_filename == nullptr || bin_filename[0] == '\0') {
      std::string bin_filename_str(data_filename_);
      bin_filename_str.append(".bin");
      bin_filename = bin_filename_str.c_str();
    }
Guolin Ke's avatar
Guolin Ke committed
763
764
    FILE* file;
    #ifdef _MSC_VER
Guolin Ke's avatar
Guolin Ke committed
765
    fopen_s(&file, bin_filename, "wb");
Guolin Ke's avatar
Guolin Ke committed
766
    #else
Guolin Ke's avatar
Guolin Ke committed
767
    file = fopen(bin_filename, "wb");
Guolin Ke's avatar
Guolin Ke committed
768
769
    #endif
    if (file == NULL) {
Guolin Ke's avatar
Guolin Ke committed
770
      Log::Fatal("Cannot write binary data to %s ", bin_filename);
Guolin Ke's avatar
Guolin Ke committed
771
772
    }

773
    Log::Info("Saving data to binary file %s", data_filename_);
Guolin Ke's avatar
Guolin Ke committed
774
775
776

    // get size of header
    size_t size_of_header = sizeof(global_num_data_) + sizeof(is_enable_sparse_)
777
778
779
780
781
      + sizeof(max_bin_) + sizeof(num_data_) + sizeof(num_features_) + sizeof(num_total_features_) +sizeof(size_t) + sizeof(int) * used_feature_map_.size();
    // size of feature names
    for (int i = 0; i < num_total_features_; ++i) {
      size_of_header += feature_names_[i].size() + sizeof(int);
    }
Guolin Ke's avatar
Guolin Ke committed
782
783
784
785
786
787
788
    fwrite(&size_of_header, sizeof(size_of_header), 1, file);
    // write header
    fwrite(&global_num_data_, sizeof(global_num_data_), 1, file);
    fwrite(&is_enable_sparse_, sizeof(is_enable_sparse_), 1, file);
    fwrite(&max_bin_, sizeof(max_bin_), 1, file);
    fwrite(&num_data_, sizeof(num_data_), 1, file);
    fwrite(&num_features_, sizeof(num_features_), 1, file);
789
    fwrite(&num_total_features_, sizeof(num_features_), 1, file);
Guolin Ke's avatar
Guolin Ke committed
790
791
792
793
    size_t num_used_feature_map = used_feature_map_.size();
    fwrite(&num_used_feature_map, sizeof(num_used_feature_map), 1, file);
    fwrite(used_feature_map_.data(), sizeof(int), num_used_feature_map, file);

794
795
796
797
798
799
800
801
    // write feature names
    for (int i = 0; i < num_total_features_; ++i) {
      int str_len = static_cast<int>(feature_names_[i].size());
      fwrite(&str_len, sizeof(int), 1, file);
      const char* c_str = feature_names_[i].c_str();
      fwrite(c_str, sizeof(char), str_len, file);
    }

Guolin Ke's avatar
Guolin Ke committed
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
    // get size of meta data
    size_t size_of_metadata = metadata_.SizesInByte();
    fwrite(&size_of_metadata, sizeof(size_of_metadata), 1, file);
    // write meta data
    metadata_.SaveBinaryToFile(file);

    // write feature data
    for (int i = 0; i < num_features_; ++i) {
      // get size of feature
      size_t size_of_feature = features_[i]->SizesInByte();
      fwrite(&size_of_feature, sizeof(size_of_feature), 1, file);
      // write feature
      features_[i]->SaveBinaryToFile(file);
    }
    fclose(file);
  }
}

void Dataset::CheckCanLoadFromBin() {
  std::string bin_filename(data_filename_);
  bin_filename.append(".bin");

  FILE* file;

  #ifdef _MSC_VER
  fopen_s(&file, bin_filename.c_str(), "rb");
  #else
  file = fopen(bin_filename.c_str(), "rb");
  #endif

  if (file == NULL) {
    is_loading_from_binfile_ = false;
  } else {
    is_loading_from_binfile_ = true;
    fclose(file);
  }
}

Guolin Ke's avatar
Guolin Ke committed
840
void Dataset::LoadDataFromBinFile(const char* bin_filename, int rank, int num_machines, bool is_pre_partition) {
Guolin Ke's avatar
Guolin Ke committed
841
842
843
844

  FILE* file;

  #ifdef _MSC_VER
Guolin Ke's avatar
Guolin Ke committed
845
  fopen_s(&file, bin_filename, "rb");
Guolin Ke's avatar
Guolin Ke committed
846
  #else
Guolin Ke's avatar
Guolin Ke committed
847
  file = fopen(bin_filename, "rb");
Guolin Ke's avatar
Guolin Ke committed
848
849
850
  #endif

  if (file == NULL) {
Guolin Ke's avatar
Guolin Ke committed
851
    Log::Fatal("Cannot read binary data from %s", bin_filename);
Guolin Ke's avatar
Guolin Ke committed
852
853
854
855
856
857
858
859
860
861
  }

  // buffer to read binary file
  size_t buffer_size = 16 * 1024 * 1024;
  char* buffer = new char[buffer_size];

  // read size of header
  size_t read_cnt = fread(buffer, sizeof(size_t), 1, file);

  if (read_cnt != 1) {
862
    Log::Fatal("Binary file error: header has the wrong size");
Guolin Ke's avatar
Guolin Ke committed
863
864
865
866
867
868
869
870
871
872
873
874
875
876
  }

  size_t size_of_head = *(reinterpret_cast<size_t*>(buffer));

  // re-allocmate space if not enough
  if (size_of_head > buffer_size) {
    delete[] buffer;
    buffer_size = size_of_head;
    buffer = new char[buffer_size];
  }
  // read header
  read_cnt = fread(buffer, 1, size_of_head, file);

  if (read_cnt != size_of_head) {
877
    Log::Fatal("Binary file error: header is incorrect");
Guolin Ke's avatar
Guolin Ke committed
878
  }
879
  // get header
Guolin Ke's avatar
Guolin Ke committed
880
881
882
883
884
885
886
887
888
889
890
  const char* mem_ptr = buffer;
  global_num_data_ = *(reinterpret_cast<const size_t*>(mem_ptr));
  mem_ptr += sizeof(global_num_data_);
  is_enable_sparse_ = *(reinterpret_cast<const bool*>(mem_ptr));
  mem_ptr += sizeof(is_enable_sparse_);
  max_bin_ = *(reinterpret_cast<const int*>(mem_ptr));
  mem_ptr += sizeof(max_bin_);
  num_data_ = *(reinterpret_cast<const data_size_t*>(mem_ptr));
  mem_ptr += sizeof(num_data_);
  num_features_ = *(reinterpret_cast<const int*>(mem_ptr));
  mem_ptr += sizeof(num_features_);
891
892
  num_total_features_ = *(reinterpret_cast<const int*>(mem_ptr));
  mem_ptr += sizeof(num_total_features_);
Guolin Ke's avatar
Guolin Ke committed
893
894
895
896
897
898
899
  size_t num_used_feature_map = *(reinterpret_cast<const size_t*>(mem_ptr));
  mem_ptr += sizeof(num_used_feature_map);
  const int* tmp_feature_map = reinterpret_cast<const int*>(mem_ptr);
  used_feature_map_.clear();
  for (size_t i = 0; i < num_used_feature_map; ++i) {
    used_feature_map_.push_back(tmp_feature_map[i]);
  }
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
  mem_ptr += sizeof(int) * num_used_feature_map;
  // get feature names
  feature_names_.clear();
  // write feature names
  for (int i = 0; i < num_total_features_; ++i) {
    int str_len = *(reinterpret_cast<const int*>(mem_ptr));
    mem_ptr += sizeof(int);
    std::stringstream str_buf;
    for (int j = 0; j < str_len; ++j) {
      char tmp_char = *(reinterpret_cast<const char*>(mem_ptr));
      mem_ptr += sizeof(char);
      str_buf << tmp_char;
    }
    feature_names_.emplace_back(str_buf.str());
  }
Guolin Ke's avatar
Guolin Ke committed
915
916
917
918
919

  // read size of meta data
  read_cnt = fread(buffer, sizeof(size_t), 1, file);

  if (read_cnt != 1) {
920
    Log::Fatal("Binary file error: meta data has the wrong size");
Guolin Ke's avatar
Guolin Ke committed
921
922
923
924
  }

  size_t size_of_metadata = *(reinterpret_cast<size_t*>(buffer));

Hui Xue's avatar
Hui Xue committed
925
  // re-allocate space if not enough
Guolin Ke's avatar
Guolin Ke committed
926
927
928
929
930
931
932
933
934
  if (size_of_metadata > buffer_size) {
    delete[] buffer;
    buffer_size = size_of_metadata;
    buffer = new char[buffer_size];
  }
  //  read meta data
  read_cnt = fread(buffer, 1, size_of_metadata, file);

  if (read_cnt != size_of_metadata) {
935
    Log::Fatal("Binary file error: meta data is incorrect");
Guolin Ke's avatar
Guolin Ke committed
936
937
938
939
940
941
942
943
944
945
946
  }
  // load meta data
  metadata_.LoadFromMemory(buffer);

  used_data_indices_.clear();
  global_num_data_ = num_data_;
  // sample local used data if need to partition
  if (num_machines > 1 && !is_pre_partition) {
    const data_size_t* query_boundaries = metadata_.query_boundaries();
    if (query_boundaries == nullptr) {
      // if not contain query file, minimal sample unit is one record
947
      for (data_size_t i = 0; i < num_data_; ++i) {
Guolin Ke's avatar
Guolin Ke committed
948
949
        if (random_.NextInt(0, num_machines) == rank) {
          used_data_indices_.push_back(i);
950
        }
Guolin Ke's avatar
Guolin Ke committed
951
952
953
954
955
956
      }
    } else {
      // if contain query file, minimal sample unit is one query
      data_size_t num_queries = metadata_.num_queries();
      data_size_t qid = -1;
      bool is_query_used = false;
957
      for (data_size_t i = 0; i < num_data_; ++i) {
Guolin Ke's avatar
Guolin Ke committed
958
        if (qid >= num_queries) {
959
          Log::Fatal("Current query exceeds the range of the query file, please ensure the query file is correct");
Guolin Ke's avatar
Guolin Ke committed
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
        }
        if (i >= query_boundaries[qid + 1]) {
          // if is new query
          is_query_used = false;
          if (random_.NextInt(0, num_machines) == rank) {
            is_query_used = true;
          }
          ++qid;
        }
        if (is_query_used) {
          used_data_indices_.push_back(i);
        }
      }
    }
    num_data_ = static_cast<data_size_t>(used_data_indices_.size());
  }
  metadata_.PartitionLabel(used_data_indices_);
  // read feature data
  for (int i = 0; i < num_features_; ++i) {
    // read feature size
    read_cnt = fread(buffer, sizeof(size_t), 1, file);
    if (read_cnt != 1) {
982
      Log::Fatal("Binary file error: feature %d has the wrong size", i);
Guolin Ke's avatar
Guolin Ke committed
983
984
    }
    size_t size_of_feature = *(reinterpret_cast<size_t*>(buffer));
Hui Xue's avatar
Hui Xue committed
985
    // re-allocate space if not enough
Guolin Ke's avatar
Guolin Ke committed
986
987
988
989
990
991
992
993
994
    if (size_of_feature > buffer_size) {
      delete[] buffer;
      buffer_size = size_of_feature;
      buffer = new char[buffer_size];
    }

    read_cnt = fread(buffer, 1, size_of_feature, file);

    if (read_cnt != size_of_feature) {
995
      Log::Fatal("Binary file error: feature %d is incorrect, read count: %d", i, read_cnt);
Guolin Ke's avatar
Guolin Ke committed
996
997
998
999
1000
1001
1002
1003
1004
    }
    features_.push_back(new Feature(buffer, static_cast<data_size_t>(global_num_data_), used_data_indices_));
  }
  delete[] buffer;
  fclose(file);
}

void Dataset::CheckDataset() {
  if (num_data_ <= 0) {
Qiwei Ye's avatar
Qiwei Ye committed
1005
    Log::Fatal("Data file %s is empty", data_filename_);
Guolin Ke's avatar
Guolin Ke committed
1006
1007
  }
  if (features_.size() <= 0) {
1008
    Log::Fatal("No usable features in data file %s", data_filename_);
Guolin Ke's avatar
Guolin Ke committed
1009
1010
1011
1012
  }
}

}  // namespace LightGBM