fastcover.c 28 KB

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