im.cc 2.2 KB
Newer Older
S
superjom 已提交
1
#include <glog/logging.h>
S
superjom 已提交
2
#include <ctime>
S
superjom 已提交
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

#include "visualdl/backend/logic/im.h"

namespace visualdl {

/*
 * @num_samples: number of instances to sample
 * @size: counter of the records.
 * @returns: id of the instance to replace, if drop this instance, return -1.
 */
int ReserviorSample(int num_samples, int num_records) {
  if (num_records <= num_samples) {
    return num_records;
  }

  std::srand(std::time(0));
  float prob = static_cast<float>(std::rand()) / RAND_MAX;
  float receive_prob = static_cast<float>(num_samples) / num_records;
  if (prob < receive_prob) {
    int offset2replace = std::rand() % num_samples;
    return offset2replace;
  }
  return -1;
}

void InformationMaintainer::SetPersistDest(const std::string &path) {
  CHECK(storage_.mutable_data()->dir().empty())
      << "duplicate set storage's path";
  storage_.mutable_data()->set_dir(path);
}

storage::Tablet *InformationMaintainer::AddTablet(const std::string &tag,
                                                  int num_samples) {
  auto *tablet = storage_.Find(tag);
  if (!tablet) {
    tablet = storage_.Add(tag, num_samples);
  }
  return tablet;
}

void InformationMaintainer::AddRecord(const std::string &tag,
S
superjom 已提交
44
                                      const storage::Record &data) {
S
superjom 已提交
45 46 47
  auto *tablet = storage_.Find(tag);
  CHECK(tablet);

S
superjom 已提交
48
  auto num_records = tablet->total_records();
S
superjom 已提交
49
  const auto num_samples = tablet->num_samples();
S
superjom 已提交
50 51 52 53 54

  int offset;
  // use reservoir sampling or not
  if (num_samples > 0) {
    offset = ReserviorSample(num_samples, num_records + 1);
S
superjom 已提交
55
    if (offset < 0) return;
S
superjom 已提交
56 57 58
  } else {
    offset = num_records;
  }
S
superjom 已提交
59 60 61 62 63 64 65 66

  storage::Record *record;
  if (offset >= num_records) {
    record = storage_.NewRecord(tag);
  } else {
    record = storage_.GetRecord(tag, offset);
  }

S
superjom 已提交
67
  *record = data;
S
superjom 已提交
68
  tablet->set_total_records(num_records + 1);
S
superjom 已提交
69 70
}

S
superjom 已提交
71
void InformationMaintainer::Clear() {
S
superjom 已提交
72
  auto *data = storage().mutable_data();
S
superjom 已提交
73 74 75 76 77
  data->clear_tablets();
  data->clear_dir();
  data->clear_timestamp();
}

S
superjom 已提交
78 79
void InformationMaintainer::PersistToDisk() {
  CHECK(!storage_.data().dir().empty()) << "path of storage should be set";
S
superjom 已提交
80
  // TODO make dir first
S
superjom 已提交
81
  // MakeDir(storage_.data().dir());
S
superjom 已提交
82
  storage_.Save(storage_.data().dir() + "/storage.pb");
S
superjom 已提交
83 84
}

S
superjom 已提交
85
}  // namespace visualdl