fastcover.c 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759
  1. /*
  2. * Copyright (c) Facebook, Inc.
  3. * All rights reserved.
  4. *
  5. * This source code is licensed under both the BSD-style license (found in the
  6. * LICENSE file in the root directory of this source tree) and the GPLv2 (found
  7. * in the COPYING file in the root directory of this source tree).
  8. * You may select, at your option, one of the above-listed licenses.
  9. */
  10. /*-*************************************
  11. * Dependencies
  12. ***************************************/
  13. #include <stdio.h> /* fprintf */
  14. #include <stdlib.h> /* malloc, free, qsort */
  15. #include <string.h> /* memset */
  16. #include <time.h> /* clock */
  17. #ifndef ZDICT_STATIC_LINKING_ONLY
  18. # define ZDICT_STATIC_LINKING_ONLY
  19. #endif
  20. #include "../common/mem.h" /* read */
  21. #include "../common/pool.h"
  22. #include "../common/threading.h"
  23. #include "../common/zstd_internal.h" /* includes zstd.h */
  24. #include "../compress/zstd_compress_internal.h" /* ZSTD_hash*() */
  25. #include "../zdict.h"
  26. #include "cover.h"
  27. /*-*************************************
  28. * Constants
  29. ***************************************/
  30. #define FASTCOVER_MAX_SAMPLES_SIZE (sizeof(size_t) == 8 ? ((unsigned)-1) : ((unsigned)1 GB))
  31. #define FASTCOVER_MAX_F 31
  32. #define FASTCOVER_MAX_ACCEL 10
  33. #define FASTCOVER_DEFAULT_SPLITPOINT 0.75
  34. #define DEFAULT_F 20
  35. #define DEFAULT_ACCEL 1
  36. /*-*************************************
  37. * Console display
  38. ***************************************/
  39. #ifndef LOCALDISPLAYLEVEL
  40. static int g_displayLevel = 2;
  41. #endif
  42. #undef DISPLAY
  43. #define DISPLAY(...) \
  44. { \
  45. fprintf(stderr, __VA_ARGS__); \
  46. fflush(stderr); \
  47. }
  48. #undef LOCALDISPLAYLEVEL
  49. #define LOCALDISPLAYLEVEL(displayLevel, l, ...) \
  50. if (displayLevel >= l) { \
  51. DISPLAY(__VA_ARGS__); \
  52. } /* 0 : no display; 1: errors; 2: default; 3: details; 4: debug */
  53. #undef DISPLAYLEVEL
  54. #define DISPLAYLEVEL(l, ...) LOCALDISPLAYLEVEL(g_displayLevel, l, __VA_ARGS__)
  55. #ifndef LOCALDISPLAYUPDATE
  56. static const clock_t g_refreshRate = CLOCKS_PER_SEC * 15 / 100;
  57. static clock_t g_time = 0;
  58. #endif
  59. #undef LOCALDISPLAYUPDATE
  60. #define LOCALDISPLAYUPDATE(displayLevel, l, ...) \
  61. if (displayLevel >= l) { \
  62. if ((clock() - g_time > g_refreshRate) || (displayLevel >= 4)) { \
  63. g_time = clock(); \
  64. DISPLAY(__VA_ARGS__); \
  65. } \
  66. }
  67. #undef DISPLAYUPDATE
  68. #define DISPLAYUPDATE(l, ...) LOCALDISPLAYUPDATE(g_displayLevel, l, __VA_ARGS__)
  69. /*-*************************************
  70. * Hash Functions
  71. ***************************************/
  72. /**
  73. * Hash the d-byte value pointed to by p and mod 2^f into the frequency vector
  74. */
  75. static size_t FASTCOVER_hashPtrToIndex(const void* p, U32 f, unsigned d) {
  76. if (d == 6) {
  77. return ZSTD_hash6Ptr(p, f);
  78. }
  79. return ZSTD_hash8Ptr(p, f);
  80. }
  81. /*-*************************************
  82. * Acceleration
  83. ***************************************/
  84. typedef struct {
  85. unsigned finalize; /* Percentage of training samples used for ZDICT_finalizeDictionary */
  86. unsigned skip; /* Number of dmer skipped between each dmer counted in computeFrequency */
  87. } FASTCOVER_accel_t;
  88. static const FASTCOVER_accel_t FASTCOVER_defaultAccelParameters[FASTCOVER_MAX_ACCEL+1] = {
  89. { 100, 0 }, /* accel = 0, should not happen because accel = 0 defaults to accel = 1 */
  90. { 100, 0 }, /* accel = 1 */
  91. { 50, 1 }, /* accel = 2 */
  92. { 34, 2 }, /* accel = 3 */
  93. { 25, 3 }, /* accel = 4 */
  94. { 20, 4 }, /* accel = 5 */
  95. { 17, 5 }, /* accel = 6 */
  96. { 14, 6 }, /* accel = 7 */
  97. { 13, 7 }, /* accel = 8 */
  98. { 11, 8 }, /* accel = 9 */
  99. { 10, 9 }, /* accel = 10 */
  100. };
  101. /*-*************************************
  102. * Context
  103. ***************************************/
  104. typedef struct {
  105. const BYTE *samples;
  106. size_t *offsets;
  107. const size_t *samplesSizes;
  108. size_t nbSamples;
  109. size_t nbTrainSamples;
  110. size_t nbTestSamples;
  111. size_t nbDmers;
  112. U32 *freqs;
  113. unsigned d;
  114. unsigned f;
  115. FASTCOVER_accel_t accelParams;
  116. } FASTCOVER_ctx_t;
  117. /*-*************************************
  118. * Helper functions
  119. ***************************************/
  120. /**
  121. * Selects the best segment in an epoch.
  122. * Segments of are scored according to the function:
  123. *
  124. * Let F(d) be the frequency of all dmers with hash value d.
  125. * Let S_i be hash value of the dmer at position i of segment S which has length k.
  126. *
  127. * Score(S) = F(S_1) + F(S_2) + ... + F(S_{k-d+1})
  128. *
  129. * Once the dmer with hash value d is in the dictionary we set F(d) = 0.
  130. */
  131. static COVER_segment_t FASTCOVER_selectSegment(const FASTCOVER_ctx_t *ctx,
  132. U32 *freqs, U32 begin, U32 end,
  133. ZDICT_cover_params_t parameters,
  134. U16* segmentFreqs) {
  135. /* Constants */
  136. const U32 k = parameters.k;
  137. const U32 d = parameters.d;
  138. const U32 f = ctx->f;
  139. const U32 dmersInK = k - d + 1;
  140. /* Try each segment (activeSegment) and save the best (bestSegment) */
  141. COVER_segment_t bestSegment = {0, 0, 0};
  142. COVER_segment_t activeSegment;
  143. /* Reset the activeDmers in the segment */
  144. /* The activeSegment starts at the beginning of the epoch. */
  145. activeSegment.begin = begin;
  146. activeSegment.end = begin;
  147. activeSegment.score = 0;
  148. /* Slide the activeSegment through the whole epoch.
  149. * Save the best segment in bestSegment.
  150. */
  151. while (activeSegment.end < end) {
  152. /* Get hash value of current dmer */
  153. const size_t idx = FASTCOVER_hashPtrToIndex(ctx->samples + activeSegment.end, f, d);
  154. /* Add frequency of this index to score if this is the first occurrence of index in active segment */
  155. if (segmentFreqs[idx] == 0) {
  156. activeSegment.score += freqs[idx];
  157. }
  158. /* Increment end of segment and segmentFreqs*/
  159. activeSegment.end += 1;
  160. segmentFreqs[idx] += 1;
  161. /* If the window is now too large, drop the first position */
  162. if (activeSegment.end - activeSegment.begin == dmersInK + 1) {
  163. /* Get hash value of the dmer to be eliminated from active segment */
  164. const size_t delIndex = FASTCOVER_hashPtrToIndex(ctx->samples + activeSegment.begin, f, d);
  165. segmentFreqs[delIndex] -= 1;
  166. /* Subtract frequency of this index from score if this is the last occurrence of this index in active segment */
  167. if (segmentFreqs[delIndex] == 0) {
  168. activeSegment.score -= freqs[delIndex];
  169. }
  170. /* Increment start of segment */
  171. activeSegment.begin += 1;
  172. }
  173. /* If this segment is the best so far save it */
  174. if (activeSegment.score > bestSegment.score) {
  175. bestSegment = activeSegment;
  176. }
  177. }
  178. /* Zero out rest of segmentFreqs array */
  179. while (activeSegment.begin < end) {
  180. const size_t delIndex = FASTCOVER_hashPtrToIndex(ctx->samples + activeSegment.begin, f, d);
  181. segmentFreqs[delIndex] -= 1;
  182. activeSegment.begin += 1;
  183. }
  184. {
  185. /* Zero the frequency of hash value of each dmer covered by the chosen segment. */
  186. U32 pos;
  187. for (pos = bestSegment.begin; pos != bestSegment.end; ++pos) {
  188. const size_t i = FASTCOVER_hashPtrToIndex(ctx->samples + pos, f, d);
  189. freqs[i] = 0;
  190. }
  191. }
  192. return bestSegment;
  193. }
  194. static int FASTCOVER_checkParameters(ZDICT_cover_params_t parameters,
  195. size_t maxDictSize, unsigned f,
  196. unsigned accel) {
  197. /* k, d, and f are required parameters */
  198. if (parameters.d == 0 || parameters.k == 0) {
  199. return 0;
  200. }
  201. /* d has to be 6 or 8 */
  202. if (parameters.d != 6 && parameters.d != 8) {
  203. return 0;
  204. }
  205. /* k <= maxDictSize */
  206. if (parameters.k > maxDictSize) {
  207. return 0;
  208. }
  209. /* d <= k */
  210. if (parameters.d > parameters.k) {
  211. return 0;
  212. }
  213. /* 0 < f <= FASTCOVER_MAX_F*/
  214. if (f > FASTCOVER_MAX_F || f == 0) {
  215. return 0;
  216. }
  217. /* 0 < splitPoint <= 1 */
  218. if (parameters.splitPoint <= 0 || parameters.splitPoint > 1) {
  219. return 0;
  220. }
  221. /* 0 < accel <= 10 */
  222. if (accel > 10 || accel == 0) {
  223. return 0;
  224. }
  225. return 1;
  226. }
  227. /**
  228. * Clean up a context initialized with `FASTCOVER_ctx_init()`.
  229. */
  230. static void
  231. FASTCOVER_ctx_destroy(FASTCOVER_ctx_t* ctx)
  232. {
  233. if (!ctx) return;
  234. free(ctx->freqs);
  235. ctx->freqs = NULL;
  236. free(ctx->offsets);
  237. ctx->offsets = NULL;
  238. }
  239. /**
  240. * Calculate for frequency of hash value of each dmer in ctx->samples
  241. */
  242. static void
  243. FASTCOVER_computeFrequency(U32* freqs, const FASTCOVER_ctx_t* ctx)
  244. {
  245. const unsigned f = ctx->f;
  246. const unsigned d = ctx->d;
  247. const unsigned skip = ctx->accelParams.skip;
  248. const unsigned readLength = MAX(d, 8);
  249. size_t i;
  250. assert(ctx->nbTrainSamples >= 5);
  251. assert(ctx->nbTrainSamples <= ctx->nbSamples);
  252. for (i = 0; i < ctx->nbTrainSamples; i++) {
  253. size_t start = ctx->offsets[i]; /* start of current dmer */
  254. size_t const currSampleEnd = ctx->offsets[i+1];
  255. while (start + readLength <= currSampleEnd) {
  256. const size_t dmerIndex = FASTCOVER_hashPtrToIndex(ctx->samples + start, f, d);
  257. freqs[dmerIndex]++;
  258. start = start + skip + 1;
  259. }
  260. }
  261. }
  262. /**
  263. * Prepare a context for dictionary building.
  264. * The context is only dependent on the parameter `d` and can used multiple
  265. * times.
  266. * Returns 0 on success or error code on error.
  267. * The context must be destroyed with `FASTCOVER_ctx_destroy()`.
  268. */
  269. static size_t
  270. FASTCOVER_ctx_init(FASTCOVER_ctx_t* ctx,
  271. const void* samplesBuffer,
  272. const size_t* samplesSizes, unsigned nbSamples,
  273. unsigned d, double splitPoint, unsigned f,
  274. FASTCOVER_accel_t accelParams)
  275. {
  276. const BYTE* const samples = (const BYTE*)samplesBuffer;
  277. const size_t totalSamplesSize = COVER_sum(samplesSizes, nbSamples);
  278. /* Split samples into testing and training sets */
  279. const unsigned nbTrainSamples = splitPoint < 1.0 ? (unsigned)((double)nbSamples * splitPoint) : nbSamples;
  280. const unsigned nbTestSamples = splitPoint < 1.0 ? nbSamples - nbTrainSamples : nbSamples;
  281. const size_t trainingSamplesSize = splitPoint < 1.0 ? COVER_sum(samplesSizes, nbTrainSamples) : totalSamplesSize;
  282. const size_t testSamplesSize = splitPoint < 1.0 ? COVER_sum(samplesSizes + nbTrainSamples, nbTestSamples) : totalSamplesSize;
  283. /* Checks */
  284. if (totalSamplesSize < MAX(d, sizeof(U64)) ||
  285. totalSamplesSize >= (size_t)FASTCOVER_MAX_SAMPLES_SIZE) {
  286. DISPLAYLEVEL(1, "Total samples size is too large (%u MB), maximum size is %u MB\n",
  287. (unsigned)(totalSamplesSize >> 20), (FASTCOVER_MAX_SAMPLES_SIZE >> 20));
  288. return ERROR(srcSize_wrong);
  289. }
  290. /* Check if there are at least 5 training samples */
  291. if (nbTrainSamples < 5) {
  292. DISPLAYLEVEL(1, "Total number of training samples is %u and is invalid\n", nbTrainSamples);
  293. return ERROR(srcSize_wrong);
  294. }
  295. /* Check if there's testing sample */
  296. if (nbTestSamples < 1) {
  297. DISPLAYLEVEL(1, "Total number of testing samples is %u and is invalid.\n", nbTestSamples);
  298. return ERROR(srcSize_wrong);
  299. }
  300. /* Zero the context */
  301. memset(ctx, 0, sizeof(*ctx));
  302. DISPLAYLEVEL(2, "Training on %u samples of total size %u\n", nbTrainSamples,
  303. (unsigned)trainingSamplesSize);
  304. DISPLAYLEVEL(2, "Testing on %u samples of total size %u\n", nbTestSamples,
  305. (unsigned)testSamplesSize);
  306. ctx->samples = samples;
  307. ctx->samplesSizes = samplesSizes;
  308. ctx->nbSamples = nbSamples;
  309. ctx->nbTrainSamples = nbTrainSamples;
  310. ctx->nbTestSamples = nbTestSamples;
  311. ctx->nbDmers = trainingSamplesSize - MAX(d, sizeof(U64)) + 1;
  312. ctx->d = d;
  313. ctx->f = f;
  314. ctx->accelParams = accelParams;
  315. /* The offsets of each file */
  316. ctx->offsets = (size_t*)calloc((nbSamples + 1), sizeof(size_t));
  317. if (ctx->offsets == NULL) {
  318. DISPLAYLEVEL(1, "Failed to allocate scratch buffers \n");
  319. FASTCOVER_ctx_destroy(ctx);
  320. return ERROR(memory_allocation);
  321. }
  322. /* Fill offsets from the samplesSizes */
  323. { U32 i;
  324. ctx->offsets[0] = 0;
  325. assert(nbSamples >= 5);
  326. for (i = 1; i <= nbSamples; ++i) {
  327. ctx->offsets[i] = ctx->offsets[i - 1] + samplesSizes[i - 1];
  328. }
  329. }
  330. /* Initialize frequency array of size 2^f */
  331. ctx->freqs = (U32*)calloc(((U64)1 << f), sizeof(U32));
  332. if (ctx->freqs == NULL) {
  333. DISPLAYLEVEL(1, "Failed to allocate frequency table \n");
  334. FASTCOVER_ctx_destroy(ctx);
  335. return ERROR(memory_allocation);
  336. }
  337. DISPLAYLEVEL(2, "Computing frequencies\n");
  338. FASTCOVER_computeFrequency(ctx->freqs, ctx);
  339. return 0;
  340. }
  341. /**
  342. * Given the prepared context build the dictionary.
  343. */
  344. static size_t
  345. FASTCOVER_buildDictionary(const FASTCOVER_ctx_t* ctx,
  346. U32* freqs,
  347. void* dictBuffer, size_t dictBufferCapacity,
  348. ZDICT_cover_params_t parameters,
  349. U16* segmentFreqs)
  350. {
  351. BYTE *const dict = (BYTE *)dictBuffer;
  352. size_t tail = dictBufferCapacity;
  353. /* Divide the data into epochs. We will select one segment from each epoch. */
  354. const COVER_epoch_info_t epochs = COVER_computeEpochs(
  355. (U32)dictBufferCapacity, (U32)ctx->nbDmers, parameters.k, 1);
  356. const size_t maxZeroScoreRun = 10;
  357. size_t zeroScoreRun = 0;
  358. size_t epoch;
  359. DISPLAYLEVEL(2, "Breaking content into %u epochs of size %u\n",
  360. (U32)epochs.num, (U32)epochs.size);
  361. /* Loop through the epochs until there are no more segments or the dictionary
  362. * is full.
  363. */
  364. for (epoch = 0; tail > 0; epoch = (epoch + 1) % epochs.num) {
  365. const U32 epochBegin = (U32)(epoch * epochs.size);
  366. const U32 epochEnd = epochBegin + epochs.size;
  367. size_t segmentSize;
  368. /* Select a segment */
  369. COVER_segment_t segment = FASTCOVER_selectSegment(
  370. ctx, freqs, epochBegin, epochEnd, parameters, segmentFreqs);
  371. /* If the segment covers no dmers, then we are out of content.
  372. * There may be new content in other epochs, for continue for some time.
  373. */
  374. if (segment.score == 0) {
  375. if (++zeroScoreRun >= maxZeroScoreRun) {
  376. break;
  377. }
  378. continue;
  379. }
  380. zeroScoreRun = 0;
  381. /* Trim the segment if necessary and if it is too small then we are done */
  382. segmentSize = MIN(segment.end - segment.begin + parameters.d - 1, tail);
  383. if (segmentSize < parameters.d) {
  384. break;
  385. }
  386. /* We fill the dictionary from the back to allow the best segments to be
  387. * referenced with the smallest offsets.
  388. */
  389. tail -= segmentSize;
  390. memcpy(dict + tail, ctx->samples + segment.begin, segmentSize);
  391. DISPLAYUPDATE(
  392. 2, "\r%u%% ",
  393. (unsigned)(((dictBufferCapacity - tail) * 100) / dictBufferCapacity));
  394. }
  395. DISPLAYLEVEL(2, "\r%79s\r", "");
  396. return tail;
  397. }
  398. /**
  399. * Parameters for FASTCOVER_tryParameters().
  400. */
  401. typedef struct FASTCOVER_tryParameters_data_s {
  402. const FASTCOVER_ctx_t* ctx;
  403. COVER_best_t* best;
  404. size_t dictBufferCapacity;
  405. ZDICT_cover_params_t parameters;
  406. } FASTCOVER_tryParameters_data_t;
  407. /**
  408. * Tries a set of parameters and updates the COVER_best_t with the results.
  409. * This function is thread safe if zstd is compiled with multithreaded support.
  410. * It takes its parameters as an *OWNING* opaque pointer to support threading.
  411. */
  412. static void FASTCOVER_tryParameters(void* opaque)
  413. {
  414. /* Save parameters as local variables */
  415. FASTCOVER_tryParameters_data_t *const data = (FASTCOVER_tryParameters_data_t*)opaque;
  416. const FASTCOVER_ctx_t *const ctx = data->ctx;
  417. const ZDICT_cover_params_t parameters = data->parameters;
  418. size_t dictBufferCapacity = data->dictBufferCapacity;
  419. size_t totalCompressedSize = ERROR(GENERIC);
  420. /* Initialize array to keep track of frequency of dmer within activeSegment */
  421. U16* segmentFreqs = (U16*)calloc(((U64)1 << ctx->f), sizeof(U16));
  422. /* Allocate space for hash table, dict, and freqs */
  423. BYTE *const dict = (BYTE*)malloc(dictBufferCapacity);
  424. COVER_dictSelection_t selection = COVER_dictSelectionError(ERROR(GENERIC));
  425. U32* freqs = (U32*) malloc(((U64)1 << ctx->f) * sizeof(U32));
  426. if (!segmentFreqs || !dict || !freqs) {
  427. DISPLAYLEVEL(1, "Failed to allocate buffers: out of memory\n");
  428. goto _cleanup;
  429. }
  430. /* Copy the frequencies because we need to modify them */
  431. memcpy(freqs, ctx->freqs, ((U64)1 << ctx->f) * sizeof(U32));
  432. /* Build the dictionary */
  433. { const size_t tail = FASTCOVER_buildDictionary(ctx, freqs, dict, dictBufferCapacity,
  434. parameters, segmentFreqs);
  435. const unsigned nbFinalizeSamples = (unsigned)(ctx->nbTrainSamples * ctx->accelParams.finalize / 100);
  436. selection = COVER_selectDict(dict + tail, dictBufferCapacity, dictBufferCapacity - tail,
  437. ctx->samples, ctx->samplesSizes, nbFinalizeSamples, ctx->nbTrainSamples, ctx->nbSamples, parameters, ctx->offsets,
  438. totalCompressedSize);
  439. if (COVER_dictSelectionIsError(selection)) {
  440. DISPLAYLEVEL(1, "Failed to select dictionary\n");
  441. goto _cleanup;
  442. }
  443. }
  444. _cleanup:
  445. free(dict);
  446. COVER_best_finish(data->best, parameters, selection);
  447. free(data);
  448. free(segmentFreqs);
  449. COVER_dictSelectionFree(selection);
  450. free(freqs);
  451. }
  452. static void
  453. FASTCOVER_convertToCoverParams(ZDICT_fastCover_params_t fastCoverParams,
  454. ZDICT_cover_params_t* coverParams)
  455. {
  456. coverParams->k = fastCoverParams.k;
  457. coverParams->d = fastCoverParams.d;
  458. coverParams->steps = fastCoverParams.steps;
  459. coverParams->nbThreads = fastCoverParams.nbThreads;
  460. coverParams->splitPoint = fastCoverParams.splitPoint;
  461. coverParams->zParams = fastCoverParams.zParams;
  462. coverParams->shrinkDict = fastCoverParams.shrinkDict;
  463. }
  464. static void
  465. FASTCOVER_convertToFastCoverParams(ZDICT_cover_params_t coverParams,
  466. ZDICT_fastCover_params_t* fastCoverParams,
  467. unsigned f, unsigned accel)
  468. {
  469. fastCoverParams->k = coverParams.k;
  470. fastCoverParams->d = coverParams.d;
  471. fastCoverParams->steps = coverParams.steps;
  472. fastCoverParams->nbThreads = coverParams.nbThreads;
  473. fastCoverParams->splitPoint = coverParams.splitPoint;
  474. fastCoverParams->f = f;
  475. fastCoverParams->accel = accel;
  476. fastCoverParams->zParams = coverParams.zParams;
  477. fastCoverParams->shrinkDict = coverParams.shrinkDict;
  478. }
  479. ZDICTLIB_API size_t
  480. ZDICT_trainFromBuffer_fastCover(void* dictBuffer, size_t dictBufferCapacity,
  481. const void* samplesBuffer,
  482. const size_t* samplesSizes, unsigned nbSamples,
  483. ZDICT_fastCover_params_t parameters)
  484. {
  485. BYTE* const dict = (BYTE*)dictBuffer;
  486. FASTCOVER_ctx_t ctx;
  487. ZDICT_cover_params_t coverParams;
  488. FASTCOVER_accel_t accelParams;
  489. /* Initialize global data */
  490. g_displayLevel = parameters.zParams.notificationLevel;
  491. /* Assign splitPoint and f if not provided */
  492. parameters.splitPoint = 1.0;
  493. parameters.f = parameters.f == 0 ? DEFAULT_F : parameters.f;
  494. parameters.accel = parameters.accel == 0 ? DEFAULT_ACCEL : parameters.accel;
  495. /* Convert to cover parameter */
  496. memset(&coverParams, 0 , sizeof(coverParams));
  497. FASTCOVER_convertToCoverParams(parameters, &coverParams);
  498. /* Checks */
  499. if (!FASTCOVER_checkParameters(coverParams, dictBufferCapacity, parameters.f,
  500. parameters.accel)) {
  501. DISPLAYLEVEL(1, "FASTCOVER parameters incorrect\n");
  502. return ERROR(parameter_outOfBound);
  503. }
  504. if (nbSamples == 0) {
  505. DISPLAYLEVEL(1, "FASTCOVER must have at least one input file\n");
  506. return ERROR(srcSize_wrong);
  507. }
  508. if (dictBufferCapacity < ZDICT_DICTSIZE_MIN) {
  509. DISPLAYLEVEL(1, "dictBufferCapacity must be at least %u\n",
  510. ZDICT_DICTSIZE_MIN);
  511. return ERROR(dstSize_tooSmall);
  512. }
  513. /* Assign corresponding FASTCOVER_accel_t to accelParams*/
  514. accelParams = FASTCOVER_defaultAccelParameters[parameters.accel];
  515. /* Initialize context */
  516. {
  517. size_t const initVal = FASTCOVER_ctx_init(&ctx, samplesBuffer, samplesSizes, nbSamples,
  518. coverParams.d, parameters.splitPoint, parameters.f,
  519. accelParams);
  520. if (ZSTD_isError(initVal)) {
  521. DISPLAYLEVEL(1, "Failed to initialize context\n");
  522. return initVal;
  523. }
  524. }
  525. COVER_warnOnSmallCorpus(dictBufferCapacity, ctx.nbDmers, g_displayLevel);
  526. /* Build the dictionary */
  527. DISPLAYLEVEL(2, "Building dictionary\n");
  528. {
  529. /* Initialize array to keep track of frequency of dmer within activeSegment */
  530. U16* segmentFreqs = (U16 *)calloc(((U64)1 << parameters.f), sizeof(U16));
  531. const size_t tail = FASTCOVER_buildDictionary(&ctx, ctx.freqs, dictBuffer,
  532. dictBufferCapacity, coverParams, segmentFreqs);
  533. const unsigned nbFinalizeSamples = (unsigned)(ctx.nbTrainSamples * ctx.accelParams.finalize / 100);
  534. const size_t dictionarySize = ZDICT_finalizeDictionary(
  535. dict, dictBufferCapacity, dict + tail, dictBufferCapacity - tail,
  536. samplesBuffer, samplesSizes, nbFinalizeSamples, coverParams.zParams);
  537. if (!ZSTD_isError(dictionarySize)) {
  538. DISPLAYLEVEL(2, "Constructed dictionary of size %u\n",
  539. (unsigned)dictionarySize);
  540. }
  541. FASTCOVER_ctx_destroy(&ctx);
  542. free(segmentFreqs);
  543. return dictionarySize;
  544. }
  545. }
  546. ZDICTLIB_API size_t
  547. ZDICT_optimizeTrainFromBuffer_fastCover(
  548. void* dictBuffer, size_t dictBufferCapacity,
  549. const void* samplesBuffer,
  550. const size_t* samplesSizes, unsigned nbSamples,
  551. ZDICT_fastCover_params_t* parameters)
  552. {
  553. ZDICT_cover_params_t coverParams;
  554. FASTCOVER_accel_t accelParams;
  555. /* constants */
  556. const unsigned nbThreads = parameters->nbThreads;
  557. const double splitPoint =
  558. parameters->splitPoint <= 0.0 ? FASTCOVER_DEFAULT_SPLITPOINT : parameters->splitPoint;
  559. const unsigned kMinD = parameters->d == 0 ? 6 : parameters->d;
  560. const unsigned kMaxD = parameters->d == 0 ? 8 : parameters->d;
  561. const unsigned kMinK = parameters->k == 0 ? 50 : parameters->k;
  562. const unsigned kMaxK = parameters->k == 0 ? 2000 : parameters->k;
  563. const unsigned kSteps = parameters->steps == 0 ? 40 : parameters->steps;
  564. const unsigned kStepSize = MAX((kMaxK - kMinK) / kSteps, 1);
  565. const unsigned kIterations =
  566. (1 + (kMaxD - kMinD) / 2) * (1 + (kMaxK - kMinK) / kStepSize);
  567. const unsigned f = parameters->f == 0 ? DEFAULT_F : parameters->f;
  568. const unsigned accel = parameters->accel == 0 ? DEFAULT_ACCEL : parameters->accel;
  569. const unsigned shrinkDict = 0;
  570. /* Local variables */
  571. const int displayLevel = parameters->zParams.notificationLevel;
  572. unsigned iteration = 1;
  573. unsigned d;
  574. unsigned k;
  575. COVER_best_t best;
  576. POOL_ctx *pool = NULL;
  577. int warned = 0;
  578. /* Checks */
  579. if (splitPoint <= 0 || splitPoint > 1) {
  580. LOCALDISPLAYLEVEL(displayLevel, 1, "Incorrect splitPoint\n");
  581. return ERROR(parameter_outOfBound);
  582. }
  583. if (accel == 0 || accel > FASTCOVER_MAX_ACCEL) {
  584. LOCALDISPLAYLEVEL(displayLevel, 1, "Incorrect accel\n");
  585. return ERROR(parameter_outOfBound);
  586. }
  587. if (kMinK < kMaxD || kMaxK < kMinK) {
  588. LOCALDISPLAYLEVEL(displayLevel, 1, "Incorrect k\n");
  589. return ERROR(parameter_outOfBound);
  590. }
  591. if (nbSamples == 0) {
  592. LOCALDISPLAYLEVEL(displayLevel, 1, "FASTCOVER must have at least one input file\n");
  593. return ERROR(srcSize_wrong);
  594. }
  595. if (dictBufferCapacity < ZDICT_DICTSIZE_MIN) {
  596. LOCALDISPLAYLEVEL(displayLevel, 1, "dictBufferCapacity must be at least %u\n",
  597. ZDICT_DICTSIZE_MIN);
  598. return ERROR(dstSize_tooSmall);
  599. }
  600. if (nbThreads > 1) {
  601. pool = POOL_create(nbThreads, 1);
  602. if (!pool) {
  603. return ERROR(memory_allocation);
  604. }
  605. }
  606. /* Initialization */
  607. COVER_best_init(&best);
  608. memset(&coverParams, 0 , sizeof(coverParams));
  609. FASTCOVER_convertToCoverParams(*parameters, &coverParams);
  610. accelParams = FASTCOVER_defaultAccelParameters[accel];
  611. /* Turn down global display level to clean up display at level 2 and below */
  612. g_displayLevel = displayLevel == 0 ? 0 : displayLevel - 1;
  613. /* Loop through d first because each new value needs a new context */
  614. LOCALDISPLAYLEVEL(displayLevel, 2, "Trying %u different sets of parameters\n",
  615. kIterations);
  616. for (d = kMinD; d <= kMaxD; d += 2) {
  617. /* Initialize the context for this value of d */
  618. FASTCOVER_ctx_t ctx;
  619. LOCALDISPLAYLEVEL(displayLevel, 3, "d=%u\n", d);
  620. {
  621. size_t const initVal = FASTCOVER_ctx_init(&ctx, samplesBuffer, samplesSizes, nbSamples, d, splitPoint, f, accelParams);
  622. if (ZSTD_isError(initVal)) {
  623. LOCALDISPLAYLEVEL(displayLevel, 1, "Failed to initialize context\n");
  624. COVER_best_destroy(&best);
  625. POOL_free(pool);
  626. return initVal;
  627. }
  628. }
  629. if (!warned) {
  630. COVER_warnOnSmallCorpus(dictBufferCapacity, ctx.nbDmers, displayLevel);
  631. warned = 1;
  632. }
  633. /* Loop through k reusing the same context */
  634. for (k = kMinK; k <= kMaxK; k += kStepSize) {
  635. /* Prepare the arguments */
  636. FASTCOVER_tryParameters_data_t *data = (FASTCOVER_tryParameters_data_t *)malloc(
  637. sizeof(FASTCOVER_tryParameters_data_t));
  638. LOCALDISPLAYLEVEL(displayLevel, 3, "k=%u\n", k);
  639. if (!data) {
  640. LOCALDISPLAYLEVEL(displayLevel, 1, "Failed to allocate parameters\n");
  641. COVER_best_destroy(&best);
  642. FASTCOVER_ctx_destroy(&ctx);
  643. POOL_free(pool);
  644. return ERROR(memory_allocation);
  645. }
  646. data->ctx = &ctx;
  647. data->best = &best;
  648. data->dictBufferCapacity = dictBufferCapacity;
  649. data->parameters = coverParams;
  650. data->parameters.k = k;
  651. data->parameters.d = d;
  652. data->parameters.splitPoint = splitPoint;
  653. data->parameters.steps = kSteps;
  654. data->parameters.shrinkDict = shrinkDict;
  655. data->parameters.zParams.notificationLevel = g_displayLevel;
  656. /* Check the parameters */
  657. if (!FASTCOVER_checkParameters(data->parameters, dictBufferCapacity,
  658. data->ctx->f, accel)) {
  659. DISPLAYLEVEL(1, "FASTCOVER parameters incorrect\n");
  660. free(data);
  661. continue;
  662. }
  663. /* Call the function and pass ownership of data to it */
  664. COVER_best_start(&best);
  665. if (pool) {
  666. POOL_add(pool, &FASTCOVER_tryParameters, data);
  667. } else {
  668. FASTCOVER_tryParameters(data);
  669. }
  670. /* Print status */
  671. LOCALDISPLAYUPDATE(displayLevel, 2, "\r%u%% ",
  672. (unsigned)((iteration * 100) / kIterations));
  673. ++iteration;
  674. }
  675. COVER_best_wait(&best);
  676. FASTCOVER_ctx_destroy(&ctx);
  677. }
  678. LOCALDISPLAYLEVEL(displayLevel, 2, "\r%79s\r", "");
  679. /* Fill the output buffer and parameters with output of the best parameters */
  680. {
  681. const size_t dictSize = best.dictSize;
  682. if (ZSTD_isError(best.compressedSize)) {
  683. const size_t compressedSize = best.compressedSize;
  684. COVER_best_destroy(&best);
  685. POOL_free(pool);
  686. return compressedSize;
  687. }
  688. FASTCOVER_convertToFastCoverParams(best.parameters, parameters, f, accel);
  689. memcpy(dictBuffer, best.dict, dictSize);
  690. COVER_best_destroy(&best);
  691. POOL_free(pool);
  692. return dictSize;
  693. }
  694. }