sparse_accessor.cc 11.1 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
// Copyright (c) 2021 PaddlePaddle 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.

#include "paddle/fluid/distributed/ps/table/sparse_accessor.h"
16

17
#include <gflags/gflags.h>
18

19 20 21 22 23 24
#include "glog/logging.h"
#include "paddle/fluid/string/string_helper.h"

namespace paddle {
namespace distributed {

25
int SparseAccessor::Initialize() {
26 27
  auto name = _config.embed_sgd_param().name();
  _embed_sgd_rule = CREATE_PSCORE_CLASS(SparseValueSGDRule, name);
28
  _embed_sgd_rule->LoadConfig(_config.embed_sgd_param(), 1);
29 30 31

  name = _config.embedx_sgd_param().name();
  _embedx_sgd_rule = CREATE_PSCORE_CLASS(SparseValueSGDRule, name);
32 33
  _embedx_sgd_rule->LoadConfig(_config.embedx_sgd_param(),
                               _config.embedx_dim());
34

35
  sparse_feature_value.embed_sgd_dim = _embed_sgd_rule->Dim();
36
  sparse_feature_value.embedx_dim = _config.embedx_dim();
37
  sparse_feature_value.embedx_sgd_dim = _embedx_sgd_rule->Dim();
38 39
  _show_click_decay_rate = _config.ctr_accessor_param().show_click_decay_rate();

40
  InitAccessorInfo();
41 42 43
  return 0;
}

44 45 46
void SparseAccessor::InitAccessorInfo() {
  _accessor_info.dim = sparse_feature_value.Dim();
  _accessor_info.size = sparse_feature_value.Size();
47
  auto embedx_dim = _config.embedx_dim();
48 49 50 51 52 53 54
  _accessor_info.select_dim = 1 + embedx_dim;
  _accessor_info.select_size = _accessor_info.select_dim * sizeof(float);
  ;
  _accessor_info.update_dim = 4 + embedx_dim;
  _accessor_info.update_size = _accessor_info.update_dim * sizeof(float);
  _accessor_info.mf_size =
      (embedx_dim + sparse_feature_value.embedx_sgd_dim) * sizeof(float);
55 56
}

57
bool SparseAccessor::Shrink(float* value) {
58 59 60 61 62 63 64
  auto base_threshold = _config.ctr_accessor_param().base_threshold();
  auto delta_threshold = _config.ctr_accessor_param().delta_threshold();
  auto delete_after_unseen_days =
      _config.ctr_accessor_param().delete_after_unseen_days();
  auto delete_threshold = _config.ctr_accessor_param().delete_threshold();

  // time_decay first
65 66
  sparse_feature_value.Show(value) *= _show_click_decay_rate;
  sparse_feature_value.Click(value) *= _show_click_decay_rate;
67 68

  // shrink after
69 70 71
  auto score = ShowClickScore(sparse_feature_value.Show(value),
                              sparse_feature_value.Click(value));
  auto unseen_days = sparse_feature_value.UnseenDays(value);
72 73 74 75 76 77
  if (score < delete_threshold || unseen_days > delete_after_unseen_days) {
    return true;
  }
  return false;
}

78
bool SparseAccessor::Save(float* value, int param) {
79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
  auto base_threshold = _config.ctr_accessor_param().base_threshold();
  auto delta_threshold = _config.ctr_accessor_param().delta_threshold();
  auto delta_keep_days = _config.ctr_accessor_param().delta_keep_days();
  if (param == 2) {
    delta_threshold = 0;
  }
  switch (param) {
    // save all
    case 0: {
      return true;
    }
    // save xbox delta
    case 1:
    // save xbox base
    case 2: {
94 95 96 97
      if (ShowClickScore(sparse_feature_value.Show(value),
                         sparse_feature_value.Click(value)) >= base_threshold &&
          sparse_feature_value.DeltaScore(value) >= delta_threshold &&
          sparse_feature_value.UnseenDays(value) <= delta_keep_days) {
98 99
        // do this after save, because it must not be modified when retry
        if (param == 2) {
100
          sparse_feature_value.DeltaScore(value) = 0;
101 102 103 104 105 106 107 108 109
        }
        return true;
      } else {
        return false;
      }
    }
    // already decayed in shrink
    case 3: {
      // do this after save, because it must not be modified when retry
110
      // sparse_feature_value.UnseenDays(value)++;
111 112 113 114 115 116 117 118 119 120 121
      return true;
    }
    // save revert batch_model
    case 5: {
      return true;
    }
    default:
      return true;
  }
}

122
void SparseAccessor::UpdateStatAfterSave(float* value, int param) {
123 124 125 126 127 128 129 130
  auto base_threshold = _config.ctr_accessor_param().base_threshold();
  auto delta_threshold = _config.ctr_accessor_param().delta_threshold();
  auto delta_keep_days = _config.ctr_accessor_param().delta_keep_days();
  if (param == 2) {
    delta_threshold = 0;
  }
  switch (param) {
    case 1: {
131 132 133 134 135
      if (ShowClickScore(sparse_feature_value.Show(value),
                         sparse_feature_value.Click(value)) >= base_threshold &&
          sparse_feature_value.DeltaScore(value) >= delta_threshold &&
          sparse_feature_value.UnseenDays(value) <= delta_keep_days) {
        sparse_feature_value.DeltaScore(value) = 0;
136 137 138 139
      }
    }
      return;
    case 3: {
140
      sparse_feature_value.UnseenDays(value)++;
141 142 143 144 145 146 147
    }
      return;
    default:
      return;
  }
}

148
int32_t SparseAccessor::Create(float** values, size_t num) {
149 150 151
  auto embedx_dim = _config.embedx_dim();
  for (size_t value_item = 0; value_item < num; ++value_item) {
    float* value = values[value_item];
152 153
    value[sparse_feature_value.UnseenDaysIndex()] = 0;
    value[sparse_feature_value.DeltaScoreIndex()] = 0;
154 155 156
    value[sparse_feature_value.ShowIndex()] = 0;
    value[sparse_feature_value.ClickIndex()] = 0;
    value[sparse_feature_value.SlotIndex()] = -1;
157 158 159 160 161
    _embed_sgd_rule->InitValue(value + sparse_feature_value.EmbedWIndex(),
                               value + sparse_feature_value.EmbedG2SumIndex());
    _embedx_sgd_rule->InitValue(value + sparse_feature_value.EmbedxWIndex(),
                                value + sparse_feature_value.EmbedxG2SumIndex(),
                                false);
162 163 164 165
  }
  return 0;
}

166 167 168
bool SparseAccessor::NeedExtendMF(float* value) {
  float show = value[sparse_feature_value.ShowIndex()];
  float click = value[sparse_feature_value.ClickIndex()];
169 170 171 172 173
  float score = (show - click) * _config.ctr_accessor_param().nonclk_coeff() +
                click * _config.ctr_accessor_param().click_coeff();
  return score >= _config.embedx_threshold();
}

174
bool SparseAccessor::HasMF(int size) {
175
  return size > sparse_feature_value.EmbedxG2SumIndex();
176 177 178
}

// from SparseFeatureValue to SparsePullValue
179
int32_t SparseAccessor::Select(float** select_values, const float** values,
180 181 182 183 184
                               size_t num) {
  auto embedx_dim = _config.embedx_dim();
  for (size_t value_item = 0; value_item < num; ++value_item) {
    float* select_value = select_values[value_item];
    const float* value = values[value_item];
185 186 187 188
    select_value[SparsePullValue::EmbedWIndex()] =
        value[sparse_feature_value.EmbedWIndex()];
    memcpy(select_value + SparsePullValue::EmbedxWIndex(),
           value + sparse_feature_value.EmbedxWIndex(),
189 190 191 192 193 194 195 196
           embedx_dim * sizeof(float));
  }
  return 0;
}

// from SparsePushValue to SparsePushValue
// first dim: item
// second dim: field num
197
int32_t SparseAccessor::Merge(float** update_values,
198 199
                              const float** other_update_values, size_t num) {
  auto embedx_dim = _config.embedx_dim();
200
  size_t total_dim = SparsePushValue::Dim(embedx_dim);
201 202 203
  for (size_t value_item = 0; value_item < num; ++value_item) {
    float* update_value = update_values[value_item];
    const float* other_update_value = other_update_values[value_item];
204
    for (size_t i = 0; i < total_dim; ++i) {
205
      if (i != SparsePushValue::SlotIndex()) {
206 207 208 209 210 211 212 213 214 215
        update_value[i] += other_update_value[i];
      }
    }
  }
  return 0;
}

// from SparsePushValue to SparseFeatureValue
// first dim: item
// second dim: field num
216
int32_t SparseAccessor::Update(float** update_values, const float** push_values,
217 218 219 220 221
                               size_t num) {
  auto embedx_dim = _config.embedx_dim();
  for (size_t value_item = 0; value_item < num; ++value_item) {
    float* update_value = update_values[value_item];
    const float* push_value = push_values[value_item];
222 223 224 225 226 227
    float push_show = push_value[SparsePushValue::ShowIndex()];
    float push_click = push_value[SparsePushValue::ClickIndex()];
    float slot = push_value[SparsePushValue::SlotIndex()];
    update_value[sparse_feature_value.ShowIndex()] += push_show;
    update_value[sparse_feature_value.ClickIndex()] += push_click;
    update_value[sparse_feature_value.SlotIndex()] = slot;
228
    update_value[sparse_feature_value.DeltaScoreIndex()] +=
229 230
        (push_show - push_click) * _config.ctr_accessor_param().nonclk_coeff() +
        push_click * _config.ctr_accessor_param().click_coeff();
231 232 233 234 235 236 237 238 239
    update_value[sparse_feature_value.UnseenDaysIndex()] = 0;
    _embed_sgd_rule->UpdateValue(
        update_value + sparse_feature_value.EmbedWIndex(),
        update_value + sparse_feature_value.EmbedG2SumIndex(),
        push_value + SparsePushValue::EmbedGIndex());
    _embedx_sgd_rule->UpdateValue(
        update_value + sparse_feature_value.EmbedxWIndex(),
        update_value + sparse_feature_value.EmbedxG2SumIndex(),
        push_value + SparsePushValue::EmbedxGIndex());
240 241 242 243
  }
  return 0;
}

244
bool SparseAccessor::CreateValue(int stage, const float* value) {
245 246 247 248 249 250
  // stage == 0, pull
  // stage == 1, push
  if (stage == 0) {
    return true;
  } else if (stage == 1) {
    // operation
251 252
    auto show = SparsePushValue::Show(const_cast<float*>(value));
    auto click = SparsePushValue::Click(const_cast<float*>(value));
253
    auto score = ShowClickScore(show, click);
254 255 256 257 258 259 260 261 262 263 264 265 266
    if (score <= 0) {
      return false;
    }
    if (score >= 1) {
      return true;
    }
    return local_uniform_real_distribution<float>()(local_random_engine()) <
           score;
  } else {
    return true;
  }
}

267
float SparseAccessor::ShowClickScore(float show, float click) {
268 269 270 271 272
  auto nonclk_coeff = _config.ctr_accessor_param().nonclk_coeff();
  auto click_coeff = _config.ctr_accessor_param().click_coeff();
  return (show - click) * nonclk_coeff + click * click_coeff;
}

273
std::string SparseAccessor::ParseToString(const float* v, int param) {
274 275 276 277 278
  thread_local std::ostringstream os;
  os.clear();
  os.str("");
  os << v[0] << " " << v[1] << " " << v[2] << " " << v[3] << " " << v[4] << " "
     << v[5];
279 280
  for (int i = sparse_feature_value.EmbedG2SumIndex();
       i < sparse_feature_value.EmbedxWIndex(); i++) {
281 282
    os << " " << v[i];
  }
283 284
  auto show = sparse_feature_value.Show(const_cast<float*>(v));
  auto click = sparse_feature_value.Click(const_cast<float*>(v));
285
  auto score = ShowClickScore(show, click);
286
  if (score >= _config.embedx_threshold() &&
287 288
      param > sparse_feature_value.EmbedxWIndex()) {
    for (auto i = sparse_feature_value.EmbedxWIndex();
289
         i < sparse_feature_value.Dim(); ++i) {
290 291 292 293 294 295
      os << " " << v[i];
    }
  }
  return os.str();
}

296
int SparseAccessor::ParseFromString(const std::string& str, float* value) {
297 298
  int embedx_dim = _config.embedx_dim();

299 300
  _embedx_sgd_rule->InitValue(value + sparse_feature_value.EmbedxWIndex(),
                              value + sparse_feature_value.EmbedxG2SumIndex());
301 302 303 304 305 306 307
  auto ret = paddle::string::str_to_float(str.data(), value);
  CHECK(ret >= 6) << "expect more than 6 real:" << ret;
  return ret;
}

}  // namespace distributed
}  // namespace paddle