autotune.cc 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464
  1. /**
  2. * Copyright (c) 2016-present, Facebook, Inc.
  3. * All rights reserved.
  4. *
  5. * This source code is licensed under the MIT license found in the
  6. * LICENSE file in the root directory of this source tree.
  7. */
  8. #include "autotune.h"
  9. #include <algorithm>
  10. #include <csignal>
  11. #include <functional>
  12. #include <iomanip>
  13. #include <iostream>
  14. #include <random>
  15. #include <thread>
  16. #define LOG_VAL(name, val) \
  17. if (autotuneArgs.verbose > 2) { \
  18. std::cout << #name " = " << val << std::endl; \
  19. }
  20. #define LOG_VAL_NAN(name, val) \
  21. if (autotuneArgs.verbose > 2) { \
  22. if (std::isnan(val)) { \
  23. std::cout << #name " = NaN" << std::endl; \
  24. } else { \
  25. std::cout << #name " = " << val << std::endl; \
  26. } \
  27. }
  28. namespace {
  29. std::function<void()> interruptSignalHandler;
  30. void signalHandler(int signal) {
  31. if (signal == SIGINT) {
  32. interruptSignalHandler();
  33. }
  34. }
  35. class ElapsedTimeMarker {
  36. std::chrono::steady_clock::time_point start_;
  37. public:
  38. ElapsedTimeMarker() {
  39. start_ = std::chrono::steady_clock::now();
  40. }
  41. double getElapsed() {
  42. return fasttext::utils::getDuration(
  43. start_, std::chrono::steady_clock::now());
  44. }
  45. };
  46. } // namespace
  47. namespace fasttext {
  48. constexpr double kUnknownBestScore = -1.0;
  49. constexpr int kCutoffLimit = 256;
  50. template <typename T>
  51. T getArgGauss(
  52. T val,
  53. std::minstd_rand& rng,
  54. double startSigma,
  55. double endSigma,
  56. double t,
  57. bool linear) {
  58. T returnValue;
  59. const double stddev = startSigma -
  60. ((startSigma - endSigma) / 0.5) *
  61. std::min(0.5, std::max((t - 0.25), 0.0));
  62. std::normal_distribution<double> normal(0.0, stddev);
  63. const double coeff = normal(rng);
  64. double updateCoeff = 0.0;
  65. if (linear) {
  66. updateCoeff = coeff;
  67. returnValue = static_cast<T>(updateCoeff + val);
  68. } else {
  69. updateCoeff = std::pow(2.0, coeff);
  70. returnValue = static_cast<T>(updateCoeff * val);
  71. }
  72. return returnValue;
  73. }
  74. template <typename T>
  75. T updateArgGauss(
  76. T val,
  77. T min,
  78. T max,
  79. double startSigma,
  80. double endSigma,
  81. double t,
  82. bool linear,
  83. std::minstd_rand& rng) {
  84. T retVal = getArgGauss(val, rng, startSigma, endSigma, t, linear);
  85. if (retVal > max) {
  86. retVal = max;
  87. }
  88. if (retVal < min) {
  89. retVal = min;
  90. }
  91. return retVal;
  92. }
  93. AutotuneStrategy::AutotuneStrategy(
  94. const Args& originalArgs,
  95. std::minstd_rand::result_type seed)
  96. : bestArgs_(),
  97. maxDuration_(originalArgs.autotuneDuration),
  98. rng_(seed),
  99. trials_(0),
  100. bestMinnIndex_(0),
  101. bestDsubExponent_(1),
  102. bestNonzeroBucket_(2000000),
  103. originalBucket_(originalArgs.bucket) {
  104. minnChoices_ = {0, 2, 3};
  105. updateBest(originalArgs);
  106. }
  107. Args AutotuneStrategy::ask(double elapsed) {
  108. const double t = std::min(1.0, elapsed / maxDuration_);
  109. trials_++;
  110. if (trials_ == 1) {
  111. return bestArgs_;
  112. }
  113. Args args = bestArgs_;
  114. if (!args.isManual("epoch")) {
  115. args.epoch = updateArgGauss(args.epoch, 1, 100, 2.8, 2.5, t, false, rng_);
  116. }
  117. if (!args.isManual("lr")) {
  118. args.lr = updateArgGauss(args.lr, 0.01, 5.0, 1.9, 1.0, t, false, rng_);
  119. };
  120. if (!args.isManual("dim")) {
  121. args.dim = updateArgGauss(args.dim, 1, 1000, 1.4, 0.3, t, false, rng_);
  122. }
  123. if (!args.isManual("wordNgrams")) {
  124. args.wordNgrams =
  125. updateArgGauss(args.wordNgrams, 1, 5, 4.3, 2.4, t, true, rng_);
  126. }
  127. if (!args.isManual("dsub")) {
  128. int dsubExponent =
  129. updateArgGauss(bestDsubExponent_, 1, 4, 2.0, 1.0, t, true, rng_);
  130. args.dsub = (1 << dsubExponent);
  131. }
  132. if (!args.isManual("minn")) {
  133. int minnIndex = updateArgGauss(
  134. bestMinnIndex_,
  135. 0,
  136. static_cast<int>(minnChoices_.size() - 1),
  137. 4.0,
  138. 1.4,
  139. t,
  140. true,
  141. rng_);
  142. args.minn = minnChoices_[minnIndex];
  143. }
  144. if (!args.isManual("maxn")) {
  145. if (args.minn == 0) {
  146. args.maxn = 0;
  147. } else {
  148. args.maxn = args.minn + 3;
  149. }
  150. }
  151. if (!args.isManual("bucket")) {
  152. int nonZeroBucket = updateArgGauss(
  153. bestNonzeroBucket_, 10000, 10000000, 2.0, 1.5, t, false, rng_);
  154. args.bucket = nonZeroBucket;
  155. } else {
  156. args.bucket = originalBucket_;
  157. }
  158. if (args.wordNgrams <= 1 && args.maxn == 0) {
  159. args.bucket = 0;
  160. }
  161. if (!args.isManual("loss")) {
  162. args.loss = loss_name::softmax;
  163. }
  164. return args;
  165. }
  166. int AutotuneStrategy::getIndex(int val, const std::vector<int>& choices) {
  167. auto found = std::find(choices.begin(), choices.end(), val);
  168. int ind = 0;
  169. if (found != choices.end()) {
  170. ind = std::distance(choices.begin(), found);
  171. }
  172. return ind;
  173. }
  174. void AutotuneStrategy::updateBest(const Args& args) {
  175. bestArgs_ = args;
  176. bestMinnIndex_ = getIndex(args.minn, minnChoices_);
  177. bestDsubExponent_ = log2(args.dsub);
  178. if (args.bucket != 0) {
  179. bestNonzeroBucket_ = args.bucket;
  180. }
  181. }
  182. Autotune::Autotune(const std::shared_ptr<FastText>& fastText)
  183. : fastText_(fastText),
  184. elapsed_(0.),
  185. bestScore_(0.),
  186. trials_(0),
  187. sizeConstraintFailed_(0),
  188. continueTraining_(false),
  189. strategy_(),
  190. timer_() {}
  191. void Autotune::printInfo(double maxDuration) {
  192. double progress = elapsed_ * 100 / maxDuration;
  193. progress = std::min(progress, 100.0);
  194. std::cerr << "\r";
  195. std::cerr << std::fixed;
  196. std::cerr << "Progress: ";
  197. std::cerr << std::setprecision(1) << std::setw(5) << progress << "%";
  198. std::cerr << " Trials: " << std::setw(4) << trials_;
  199. std::cerr << " Best score: " << std::setw(9) << std::setprecision(6);
  200. if (bestScore_ == kUnknownBestScore) {
  201. std::cerr << "unknown";
  202. } else {
  203. std::cerr << bestScore_;
  204. }
  205. std::cerr << " ETA: "
  206. << utils::ClockPrint(std::max(maxDuration - elapsed_, 0.0));
  207. std::cerr << std::flush;
  208. }
  209. void Autotune::timer(
  210. const std::chrono::steady_clock::time_point& start,
  211. double maxDuration) {
  212. elapsed_ = 0.0;
  213. while (keepTraining(maxDuration)) {
  214. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  215. elapsed_ = utils::getDuration(start, std::chrono::steady_clock::now());
  216. printInfo(maxDuration);
  217. }
  218. abort();
  219. }
  220. bool Autotune::keepTraining(double maxDuration) const {
  221. return continueTraining_ && elapsed_ < maxDuration;
  222. }
  223. void Autotune::abort() {
  224. if (continueTraining_) {
  225. continueTraining_ = false;
  226. fastText_->abort();
  227. }
  228. }
  229. void Autotune::startTimer(const Args& args) {
  230. std::chrono::steady_clock::time_point start =
  231. std::chrono::steady_clock::now();
  232. timer_ = std::thread([=]() { timer(start, args.autotuneDuration); });
  233. bestScore_ = kUnknownBestScore;
  234. trials_ = 0;
  235. continueTraining_ = true;
  236. auto previousSignalHandler = std::signal(SIGINT, signalHandler);
  237. interruptSignalHandler = [&]() {
  238. std::signal(SIGINT, previousSignalHandler);
  239. std::cerr << std::endl << "Aborting autotune..." << std::endl;
  240. abort();
  241. };
  242. }
  243. double Autotune::getMetricScore(
  244. Meter& meter,
  245. const metric_name& metricName,
  246. const std::string& metricLabel) const {
  247. double score = 0.0;
  248. if (metricName == metric_name::f1score) {
  249. score = meter.f1Score();
  250. } else if (metricName == metric_name::labelf1score) {
  251. int32_t labelId = fastText_->getDictionary()->getId(metricLabel);
  252. if (labelId == -1) {
  253. throw std::runtime_error("Unknown autotune metric label");
  254. }
  255. labelId = labelId - fastText_->getDictionary()->nwords();
  256. score = meter.f1Score(labelId);
  257. } else {
  258. throw std::runtime_error("Unknown metric");
  259. }
  260. return score;
  261. }
  262. void Autotune::printArgs(const Args& args, const Args& autotuneArgs) {
  263. LOG_VAL(epoch, args.epoch)
  264. LOG_VAL(lr, args.lr)
  265. LOG_VAL(dim, args.dim)
  266. LOG_VAL(minCount, args.minCount)
  267. LOG_VAL(wordNgrams, args.wordNgrams)
  268. LOG_VAL(minn, args.minn)
  269. LOG_VAL(maxn, args.maxn)
  270. LOG_VAL(bucket, args.bucket)
  271. LOG_VAL(dsub, args.dsub)
  272. LOG_VAL(loss, args.lossToString(args.loss))
  273. }
  274. int Autotune::getCutoffForFileSize(
  275. bool qout,
  276. bool qnorm,
  277. int dsub,
  278. int64_t fileSize) const {
  279. int64_t outModelSize = 0;
  280. const int64_t outM = fastText_->getOutputMatrix()->size(0);
  281. const int64_t outN = fastText_->getOutputMatrix()->size(1);
  282. if (qout) {
  283. const int64_t outputPqSize = 16 + 4 * (outN * (1 << 8));
  284. outModelSize =
  285. 21 + (outM * ((outN + 2 - 1) / 2)) + outputPqSize + (qnorm ? outM : 0);
  286. } else {
  287. outModelSize = 16 + 4 * (outM * outN);
  288. }
  289. const int64_t dim = fastText_->getInputMatrix()->size(1);
  290. int target = (fileSize - (107) - 4 * (1 << 8) * dim - outModelSize);
  291. int cutoff = target / ((dim + dsub - 1) / dsub + (qnorm ? 1 : 0) + 10);
  292. return std::max(cutoff, kCutoffLimit);
  293. }
  294. bool Autotune::quantize(Args& args, const Args& autotuneArgs) {
  295. if (autotuneArgs.getAutotuneModelSize() == Args::kUnlimitedModelSize) {
  296. return true;
  297. }
  298. auto outputSize = fastText_->getOutputMatrix()->size(0);
  299. args.qnorm = true;
  300. args.qout = (outputSize >= kCutoffLimit);
  301. args.retrain = true;
  302. args.cutoff = getCutoffForFileSize(
  303. args.qout, args.qnorm, args.dsub, autotuneArgs.getAutotuneModelSize());
  304. LOG_VAL(cutoff, args.cutoff);
  305. if (args.cutoff == kCutoffLimit) {
  306. return false;
  307. }
  308. fastText_->quantize(args);
  309. return true;
  310. }
  311. void Autotune::printSkippedArgs(const Args& autotuneArgs) {
  312. std::unordered_set<std::string> argsToCheck = {"epoch",
  313. "lr",
  314. "dim",
  315. "wordNgrams",
  316. "loss",
  317. "bucket",
  318. "minn",
  319. "maxn",
  320. "dsub"};
  321. for (const auto& arg : argsToCheck) {
  322. if (autotuneArgs.isManual(arg)) {
  323. std::cerr << "Warning : " << arg
  324. << " is manually set to a specific value. "
  325. << "It will not be automatically optimized." << std::endl;
  326. }
  327. }
  328. }
  329. void Autotune::train(const Args& autotuneArgs) {
  330. std::ifstream validationFileStream(autotuneArgs.autotuneValidationFile);
  331. if (!validationFileStream.is_open()) {
  332. throw std::invalid_argument("Validation file cannot be opened!");
  333. }
  334. printSkippedArgs(autotuneArgs);
  335. bool sizeConstraintWarning = false;
  336. int verbose = autotuneArgs.verbose;
  337. Args bestTrainArgs(autotuneArgs);
  338. Args trainArgs(autotuneArgs);
  339. trainArgs.verbose = 0;
  340. strategy_ = std::unique_ptr<AutotuneStrategy>(
  341. new AutotuneStrategy(trainArgs, autotuneArgs.seed));
  342. startTimer(autotuneArgs);
  343. while (keepTraining(autotuneArgs.autotuneDuration)) {
  344. trials_++;
  345. trainArgs = strategy_->ask(elapsed_);
  346. LOG_VAL(Trial, trials_)
  347. printArgs(trainArgs, autotuneArgs);
  348. ElapsedTimeMarker elapsedTimeMarker;
  349. double currentScore = std::numeric_limits<double>::quiet_NaN();
  350. try {
  351. fastText_->train(trainArgs);
  352. bool sizeConstraintOK = quantize(trainArgs, autotuneArgs);
  353. if (sizeConstraintOK) {
  354. Meter meter;
  355. fastText_->test(
  356. validationFileStream, autotuneArgs.autotunePredictions, 0.0, meter);
  357. currentScore = getMetricScore(
  358. meter,
  359. autotuneArgs.getAutotuneMetric(),
  360. autotuneArgs.getAutotuneMetricLabel());
  361. if (bestScore_ == kUnknownBestScore || (currentScore > bestScore_)) {
  362. bestTrainArgs = trainArgs;
  363. bestScore_ = currentScore;
  364. strategy_->updateBest(bestTrainArgs);
  365. }
  366. } else {
  367. sizeConstraintFailed_++;
  368. if (!sizeConstraintWarning && trials_ > 10 &&
  369. sizeConstraintFailed_ > (trials_ / 2)) {
  370. sizeConstraintWarning = true;
  371. std::cerr << std::endl
  372. << "Warning : requested model size is probably too small. "
  373. "You may want to increase `autotune-modelsize`."
  374. << std::endl;
  375. }
  376. }
  377. } catch (DenseMatrix::EncounteredNaNError&) {
  378. // ignore diverging loss and go on
  379. } catch (std::bad_alloc&) {
  380. // ignore parameter samples asking too much memory
  381. } catch (TimeoutError&) {
  382. break;
  383. } catch (FastText::AbortError&) {
  384. break;
  385. }
  386. LOG_VAL_NAN(currentScore, currentScore)
  387. LOG_VAL(train took, elapsedTimeMarker.getElapsed())
  388. }
  389. if (timer_.joinable()) {
  390. timer_.join();
  391. }
  392. if (bestScore_ == kUnknownBestScore) {
  393. std::string errorMessage;
  394. if (sizeConstraintWarning) {
  395. errorMessage =
  396. "Couldn't fulfil model size constraint: please increase "
  397. "`autotune-modelsize`.";
  398. } else {
  399. errorMessage =
  400. "Didn't have enough time to train once: please increase "
  401. "`autotune-duration`.";
  402. }
  403. throw std::runtime_error(errorMessage);
  404. } else {
  405. std::cerr << std::endl;
  406. std::cerr << "Training again with best arguments" << std::endl;
  407. bestTrainArgs.verbose = verbose;
  408. LOG_VAL(Best selected args, 0)
  409. printArgs(bestTrainArgs, autotuneArgs);
  410. fastText_->train(bestTrainArgs);
  411. quantize(bestTrainArgs, autotuneArgs);
  412. }
  413. }
  414. } // namespace fasttext