cover.c 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257
  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. * Constructs a dictionary using a heuristic based on the following paper:
  12. *
  13. * Liao, Petri, Moffat, Wirth
  14. * Effective Construction of Relative Lempel-Ziv Dictionaries
  15. * Published in WWW 2016.
  16. *
  17. * Adapted from code originally written by @ot (Giuseppe Ottaviano).
  18. ******************************************************************************/
  19. /*-*************************************
  20. * Dependencies
  21. ***************************************/
  22. #include <stdio.h> /* fprintf */
  23. #include <stdlib.h> /* malloc, free, qsort */
  24. #include <string.h> /* memset */
  25. #include <time.h> /* clock */
  26. #ifndef ZDICT_STATIC_LINKING_ONLY
  27. # define ZDICT_STATIC_LINKING_ONLY
  28. #endif
  29. #include "../common/mem.h" /* read */
  30. #include "../common/pool.h"
  31. #include "../common/threading.h"
  32. #include "../common/zstd_internal.h" /* includes zstd.h */
  33. #include "../common/bits.h" /* ZSTD_highbit32 */
  34. #include "../zdict.h"
  35. #include "cover.h"
  36. /*-*************************************
  37. * Constants
  38. ***************************************/
  39. /**
  40. * There are 32bit indexes used to ref samples, so limit samples size to 4GB
  41. * on 64bit builds.
  42. * For 32bit builds we choose 1 GB.
  43. * Most 32bit platforms have 2GB user-mode addressable space and we allocate a large
  44. * contiguous buffer, so 1GB is already a high limit.
  45. */
  46. #define COVER_MAX_SAMPLES_SIZE (sizeof(size_t) == 8 ? ((unsigned)-1) : ((unsigned)1 GB))
  47. #define COVER_DEFAULT_SPLITPOINT 1.0
  48. /*-*************************************
  49. * Console display
  50. ***************************************/
  51. #ifndef LOCALDISPLAYLEVEL
  52. static int g_displayLevel = 0;
  53. #endif
  54. #undef DISPLAY
  55. #define DISPLAY(...) \
  56. { \
  57. fprintf(stderr, __VA_ARGS__); \
  58. fflush(stderr); \
  59. }
  60. #undef LOCALDISPLAYLEVEL
  61. #define LOCALDISPLAYLEVEL(displayLevel, l, ...) \
  62. if (displayLevel >= l) { \
  63. DISPLAY(__VA_ARGS__); \
  64. } /* 0 : no display; 1: errors; 2: default; 3: details; 4: debug */
  65. #undef DISPLAYLEVEL
  66. #define DISPLAYLEVEL(l, ...) LOCALDISPLAYLEVEL(g_displayLevel, l, __VA_ARGS__)
  67. #ifndef LOCALDISPLAYUPDATE
  68. static const clock_t g_refreshRate = CLOCKS_PER_SEC * 15 / 100;
  69. static clock_t g_time = 0;
  70. #endif
  71. #undef LOCALDISPLAYUPDATE
  72. #define LOCALDISPLAYUPDATE(displayLevel, l, ...) \
  73. if (displayLevel >= l) { \
  74. if ((clock() - g_time > g_refreshRate) || (displayLevel >= 4)) { \
  75. g_time = clock(); \
  76. DISPLAY(__VA_ARGS__); \
  77. } \
  78. }
  79. #undef DISPLAYUPDATE
  80. #define DISPLAYUPDATE(l, ...) LOCALDISPLAYUPDATE(g_displayLevel, l, __VA_ARGS__)
  81. /*-*************************************
  82. * Hash table
  83. ***************************************
  84. * A small specialized hash map for storing activeDmers.
  85. * The map does not resize, so if it becomes full it will loop forever.
  86. * Thus, the map must be large enough to store every value.
  87. * The map implements linear probing and keeps its load less than 0.5.
  88. */
  89. #define MAP_EMPTY_VALUE ((U32)-1)
  90. typedef struct COVER_map_pair_t_s {
  91. U32 key;
  92. U32 value;
  93. } COVER_map_pair_t;
  94. typedef struct COVER_map_s {
  95. COVER_map_pair_t *data;
  96. U32 sizeLog;
  97. U32 size;
  98. U32 sizeMask;
  99. } COVER_map_t;
  100. /**
  101. * Clear the map.
  102. */
  103. static void COVER_map_clear(COVER_map_t *map) {
  104. memset(map->data, MAP_EMPTY_VALUE, map->size * sizeof(COVER_map_pair_t));
  105. }
  106. /**
  107. * Initializes a map of the given size.
  108. * Returns 1 on success and 0 on failure.
  109. * The map must be destroyed with COVER_map_destroy().
  110. * The map is only guaranteed to be large enough to hold size elements.
  111. */
  112. static int COVER_map_init(COVER_map_t *map, U32 size) {
  113. map->sizeLog = ZSTD_highbit32(size) + 2;
  114. map->size = (U32)1 << map->sizeLog;
  115. map->sizeMask = map->size - 1;
  116. map->data = (COVER_map_pair_t *)malloc(map->size * sizeof(COVER_map_pair_t));
  117. if (!map->data) {
  118. map->sizeLog = 0;
  119. map->size = 0;
  120. return 0;
  121. }
  122. COVER_map_clear(map);
  123. return 1;
  124. }
  125. /**
  126. * Internal hash function
  127. */
  128. static const U32 COVER_prime4bytes = 2654435761U;
  129. static U32 COVER_map_hash(COVER_map_t *map, U32 key) {
  130. return (key * COVER_prime4bytes) >> (32 - map->sizeLog);
  131. }
  132. /**
  133. * Helper function that returns the index that a key should be placed into.
  134. */
  135. static U32 COVER_map_index(COVER_map_t *map, U32 key) {
  136. const U32 hash = COVER_map_hash(map, key);
  137. U32 i;
  138. for (i = hash;; i = (i + 1) & map->sizeMask) {
  139. COVER_map_pair_t *pos = &map->data[i];
  140. if (pos->value == MAP_EMPTY_VALUE) {
  141. return i;
  142. }
  143. if (pos->key == key) {
  144. return i;
  145. }
  146. }
  147. }
  148. /**
  149. * Returns the pointer to the value for key.
  150. * If key is not in the map, it is inserted and the value is set to 0.
  151. * The map must not be full.
  152. */
  153. static U32 *COVER_map_at(COVER_map_t *map, U32 key) {
  154. COVER_map_pair_t *pos = &map->data[COVER_map_index(map, key)];
  155. if (pos->value == MAP_EMPTY_VALUE) {
  156. pos->key = key;
  157. pos->value = 0;
  158. }
  159. return &pos->value;
  160. }
  161. /**
  162. * Deletes key from the map if present.
  163. */
  164. static void COVER_map_remove(COVER_map_t *map, U32 key) {
  165. U32 i = COVER_map_index(map, key);
  166. COVER_map_pair_t *del = &map->data[i];
  167. U32 shift = 1;
  168. if (del->value == MAP_EMPTY_VALUE) {
  169. return;
  170. }
  171. for (i = (i + 1) & map->sizeMask;; i = (i + 1) & map->sizeMask) {
  172. COVER_map_pair_t *const pos = &map->data[i];
  173. /* If the position is empty we are done */
  174. if (pos->value == MAP_EMPTY_VALUE) {
  175. del->value = MAP_EMPTY_VALUE;
  176. return;
  177. }
  178. /* If pos can be moved to del do so */
  179. if (((i - COVER_map_hash(map, pos->key)) & map->sizeMask) >= shift) {
  180. del->key = pos->key;
  181. del->value = pos->value;
  182. del = pos;
  183. shift = 1;
  184. } else {
  185. ++shift;
  186. }
  187. }
  188. }
  189. /**
  190. * Destroys a map that is inited with COVER_map_init().
  191. */
  192. static void COVER_map_destroy(COVER_map_t *map) {
  193. if (map->data) {
  194. free(map->data);
  195. }
  196. map->data = NULL;
  197. map->size = 0;
  198. }
  199. /*-*************************************
  200. * Context
  201. ***************************************/
  202. typedef struct {
  203. const BYTE *samples;
  204. size_t *offsets;
  205. const size_t *samplesSizes;
  206. size_t nbSamples;
  207. size_t nbTrainSamples;
  208. size_t nbTestSamples;
  209. U32 *suffix;
  210. size_t suffixSize;
  211. U32 *freqs;
  212. U32 *dmerAt;
  213. unsigned d;
  214. } COVER_ctx_t;
  215. /* We need a global context for qsort... */
  216. static COVER_ctx_t *g_coverCtx = NULL;
  217. /*-*************************************
  218. * Helper functions
  219. ***************************************/
  220. /**
  221. * Returns the sum of the sample sizes.
  222. */
  223. size_t COVER_sum(const size_t *samplesSizes, unsigned nbSamples) {
  224. size_t sum = 0;
  225. unsigned i;
  226. for (i = 0; i < nbSamples; ++i) {
  227. sum += samplesSizes[i];
  228. }
  229. return sum;
  230. }
  231. /**
  232. * Returns -1 if the dmer at lp is less than the dmer at rp.
  233. * Return 0 if the dmers at lp and rp are equal.
  234. * Returns 1 if the dmer at lp is greater than the dmer at rp.
  235. */
  236. static int COVER_cmp(COVER_ctx_t *ctx, const void *lp, const void *rp) {
  237. U32 const lhs = *(U32 const *)lp;
  238. U32 const rhs = *(U32 const *)rp;
  239. return memcmp(ctx->samples + lhs, ctx->samples + rhs, ctx->d);
  240. }
  241. /**
  242. * Faster version for d <= 8.
  243. */
  244. static int COVER_cmp8(COVER_ctx_t *ctx, const void *lp, const void *rp) {
  245. U64 const mask = (ctx->d == 8) ? (U64)-1 : (((U64)1 << (8 * ctx->d)) - 1);
  246. U64 const lhs = MEM_readLE64(ctx->samples + *(U32 const *)lp) & mask;
  247. U64 const rhs = MEM_readLE64(ctx->samples + *(U32 const *)rp) & mask;
  248. if (lhs < rhs) {
  249. return -1;
  250. }
  251. return (lhs > rhs);
  252. }
  253. /**
  254. * Same as COVER_cmp() except ties are broken by pointer value
  255. * NOTE: g_coverCtx must be set to call this function. A global is required because
  256. * qsort doesn't take an opaque pointer.
  257. */
  258. static int WIN_CDECL COVER_strict_cmp(const void *lp, const void *rp) {
  259. int result = COVER_cmp(g_coverCtx, lp, rp);
  260. if (result == 0) {
  261. result = lp < rp ? -1 : 1;
  262. }
  263. return result;
  264. }
  265. /**
  266. * Faster version for d <= 8.
  267. */
  268. static int WIN_CDECL COVER_strict_cmp8(const void *lp, const void *rp) {
  269. int result = COVER_cmp8(g_coverCtx, lp, rp);
  270. if (result == 0) {
  271. result = lp < rp ? -1 : 1;
  272. }
  273. return result;
  274. }
  275. /**
  276. * Returns the first pointer in [first, last) whose element does not compare
  277. * less than value. If no such element exists it returns last.
  278. */
  279. static const size_t *COVER_lower_bound(const size_t *first, const size_t *last,
  280. size_t value) {
  281. size_t count = last - first;
  282. while (count != 0) {
  283. size_t step = count / 2;
  284. const size_t *ptr = first;
  285. ptr += step;
  286. if (*ptr < value) {
  287. first = ++ptr;
  288. count -= step + 1;
  289. } else {
  290. count = step;
  291. }
  292. }
  293. return first;
  294. }
  295. /**
  296. * Generic groupBy function.
  297. * Groups an array sorted by cmp into groups with equivalent values.
  298. * Calls grp for each group.
  299. */
  300. static void
  301. COVER_groupBy(const void *data, size_t count, size_t size, COVER_ctx_t *ctx,
  302. int (*cmp)(COVER_ctx_t *, const void *, const void *),
  303. void (*grp)(COVER_ctx_t *, const void *, const void *)) {
  304. const BYTE *ptr = (const BYTE *)data;
  305. size_t num = 0;
  306. while (num < count) {
  307. const BYTE *grpEnd = ptr + size;
  308. ++num;
  309. while (num < count && cmp(ctx, ptr, grpEnd) == 0) {
  310. grpEnd += size;
  311. ++num;
  312. }
  313. grp(ctx, ptr, grpEnd);
  314. ptr = grpEnd;
  315. }
  316. }
  317. /*-*************************************
  318. * Cover functions
  319. ***************************************/
  320. /**
  321. * Called on each group of positions with the same dmer.
  322. * Counts the frequency of each dmer and saves it in the suffix array.
  323. * Fills `ctx->dmerAt`.
  324. */
  325. static void COVER_group(COVER_ctx_t *ctx, const void *group,
  326. const void *groupEnd) {
  327. /* The group consists of all the positions with the same first d bytes. */
  328. const U32 *grpPtr = (const U32 *)group;
  329. const U32 *grpEnd = (const U32 *)groupEnd;
  330. /* The dmerId is how we will reference this dmer.
  331. * This allows us to map the whole dmer space to a much smaller space, the
  332. * size of the suffix array.
  333. */
  334. const U32 dmerId = (U32)(grpPtr - ctx->suffix);
  335. /* Count the number of samples this dmer shows up in */
  336. U32 freq = 0;
  337. /* Details */
  338. const size_t *curOffsetPtr = ctx->offsets;
  339. const size_t *offsetsEnd = ctx->offsets + ctx->nbSamples;
  340. /* Once *grpPtr >= curSampleEnd this occurrence of the dmer is in a
  341. * different sample than the last.
  342. */
  343. size_t curSampleEnd = ctx->offsets[0];
  344. for (; grpPtr != grpEnd; ++grpPtr) {
  345. /* Save the dmerId for this position so we can get back to it. */
  346. ctx->dmerAt[*grpPtr] = dmerId;
  347. /* Dictionaries only help for the first reference to the dmer.
  348. * After that zstd can reference the match from the previous reference.
  349. * So only count each dmer once for each sample it is in.
  350. */
  351. if (*grpPtr < curSampleEnd) {
  352. continue;
  353. }
  354. freq += 1;
  355. /* Binary search to find the end of the sample *grpPtr is in.
  356. * In the common case that grpPtr + 1 == grpEnd we can skip the binary
  357. * search because the loop is over.
  358. */
  359. if (grpPtr + 1 != grpEnd) {
  360. const size_t *sampleEndPtr =
  361. COVER_lower_bound(curOffsetPtr, offsetsEnd, *grpPtr);
  362. curSampleEnd = *sampleEndPtr;
  363. curOffsetPtr = sampleEndPtr + 1;
  364. }
  365. }
  366. /* At this point we are never going to look at this segment of the suffix
  367. * array again. We take advantage of this fact to save memory.
  368. * We store the frequency of the dmer in the first position of the group,
  369. * which is dmerId.
  370. */
  371. ctx->suffix[dmerId] = freq;
  372. }
  373. /**
  374. * Selects the best segment in an epoch.
  375. * Segments of are scored according to the function:
  376. *
  377. * Let F(d) be the frequency of dmer d.
  378. * Let S_i be the dmer at position i of segment S which has length k.
  379. *
  380. * Score(S) = F(S_1) + F(S_2) + ... + F(S_{k-d+1})
  381. *
  382. * Once the dmer d is in the dictionary we set F(d) = 0.
  383. */
  384. static COVER_segment_t COVER_selectSegment(const COVER_ctx_t *ctx, U32 *freqs,
  385. COVER_map_t *activeDmers, U32 begin,
  386. U32 end,
  387. ZDICT_cover_params_t parameters) {
  388. /* Constants */
  389. const U32 k = parameters.k;
  390. const U32 d = parameters.d;
  391. const U32 dmersInK = k - d + 1;
  392. /* Try each segment (activeSegment) and save the best (bestSegment) */
  393. COVER_segment_t bestSegment = {0, 0, 0};
  394. COVER_segment_t activeSegment;
  395. /* Reset the activeDmers in the segment */
  396. COVER_map_clear(activeDmers);
  397. /* The activeSegment starts at the beginning of the epoch. */
  398. activeSegment.begin = begin;
  399. activeSegment.end = begin;
  400. activeSegment.score = 0;
  401. /* Slide the activeSegment through the whole epoch.
  402. * Save the best segment in bestSegment.
  403. */
  404. while (activeSegment.end < end) {
  405. /* The dmerId for the dmer at the next position */
  406. U32 newDmer = ctx->dmerAt[activeSegment.end];
  407. /* The entry in activeDmers for this dmerId */
  408. U32 *newDmerOcc = COVER_map_at(activeDmers, newDmer);
  409. /* If the dmer isn't already present in the segment add its score. */
  410. if (*newDmerOcc == 0) {
  411. /* The paper suggest using the L-0.5 norm, but experiments show that it
  412. * doesn't help.
  413. */
  414. activeSegment.score += freqs[newDmer];
  415. }
  416. /* Add the dmer to the segment */
  417. activeSegment.end += 1;
  418. *newDmerOcc += 1;
  419. /* If the window is now too large, drop the first position */
  420. if (activeSegment.end - activeSegment.begin == dmersInK + 1) {
  421. U32 delDmer = ctx->dmerAt[activeSegment.begin];
  422. U32 *delDmerOcc = COVER_map_at(activeDmers, delDmer);
  423. activeSegment.begin += 1;
  424. *delDmerOcc -= 1;
  425. /* If this is the last occurrence of the dmer, subtract its score */
  426. if (*delDmerOcc == 0) {
  427. COVER_map_remove(activeDmers, delDmer);
  428. activeSegment.score -= freqs[delDmer];
  429. }
  430. }
  431. /* If this segment is the best so far save it */
  432. if (activeSegment.score > bestSegment.score) {
  433. bestSegment = activeSegment;
  434. }
  435. }
  436. {
  437. /* Trim off the zero frequency head and tail from the segment. */
  438. U32 newBegin = bestSegment.end;
  439. U32 newEnd = bestSegment.begin;
  440. U32 pos;
  441. for (pos = bestSegment.begin; pos != bestSegment.end; ++pos) {
  442. U32 freq = freqs[ctx->dmerAt[pos]];
  443. if (freq != 0) {
  444. newBegin = MIN(newBegin, pos);
  445. newEnd = pos + 1;
  446. }
  447. }
  448. bestSegment.begin = newBegin;
  449. bestSegment.end = newEnd;
  450. }
  451. {
  452. /* Zero out the frequency of each dmer covered by the chosen segment. */
  453. U32 pos;
  454. for (pos = bestSegment.begin; pos != bestSegment.end; ++pos) {
  455. freqs[ctx->dmerAt[pos]] = 0;
  456. }
  457. }
  458. return bestSegment;
  459. }
  460. /**
  461. * Check the validity of the parameters.
  462. * Returns non-zero if the parameters are valid and 0 otherwise.
  463. */
  464. static int COVER_checkParameters(ZDICT_cover_params_t parameters,
  465. size_t maxDictSize) {
  466. /* k and d are required parameters */
  467. if (parameters.d == 0 || parameters.k == 0) {
  468. return 0;
  469. }
  470. /* k <= maxDictSize */
  471. if (parameters.k > maxDictSize) {
  472. return 0;
  473. }
  474. /* d <= k */
  475. if (parameters.d > parameters.k) {
  476. return 0;
  477. }
  478. /* 0 < splitPoint <= 1 */
  479. if (parameters.splitPoint <= 0 || parameters.splitPoint > 1){
  480. return 0;
  481. }
  482. return 1;
  483. }
  484. /**
  485. * Clean up a context initialized with `COVER_ctx_init()`.
  486. */
  487. static void COVER_ctx_destroy(COVER_ctx_t *ctx) {
  488. if (!ctx) {
  489. return;
  490. }
  491. if (ctx->suffix) {
  492. free(ctx->suffix);
  493. ctx->suffix = NULL;
  494. }
  495. if (ctx->freqs) {
  496. free(ctx->freqs);
  497. ctx->freqs = NULL;
  498. }
  499. if (ctx->dmerAt) {
  500. free(ctx->dmerAt);
  501. ctx->dmerAt = NULL;
  502. }
  503. if (ctx->offsets) {
  504. free(ctx->offsets);
  505. ctx->offsets = NULL;
  506. }
  507. }
  508. /**
  509. * Prepare a context for dictionary building.
  510. * The context is only dependent on the parameter `d` and can be used multiple
  511. * times.
  512. * Returns 0 on success or error code on error.
  513. * The context must be destroyed with `COVER_ctx_destroy()`.
  514. */
  515. static size_t COVER_ctx_init(COVER_ctx_t *ctx, const void *samplesBuffer,
  516. const size_t *samplesSizes, unsigned nbSamples,
  517. unsigned d, double splitPoint) {
  518. const BYTE *const samples = (const BYTE *)samplesBuffer;
  519. const size_t totalSamplesSize = COVER_sum(samplesSizes, nbSamples);
  520. /* Split samples into testing and training sets */
  521. const unsigned nbTrainSamples = splitPoint < 1.0 ? (unsigned)((double)nbSamples * splitPoint) : nbSamples;
  522. const unsigned nbTestSamples = splitPoint < 1.0 ? nbSamples - nbTrainSamples : nbSamples;
  523. const size_t trainingSamplesSize = splitPoint < 1.0 ? COVER_sum(samplesSizes, nbTrainSamples) : totalSamplesSize;
  524. const size_t testSamplesSize = splitPoint < 1.0 ? COVER_sum(samplesSizes + nbTrainSamples, nbTestSamples) : totalSamplesSize;
  525. /* Checks */
  526. if (totalSamplesSize < MAX(d, sizeof(U64)) ||
  527. totalSamplesSize >= (size_t)COVER_MAX_SAMPLES_SIZE) {
  528. DISPLAYLEVEL(1, "Total samples size is too large (%u MB), maximum size is %u MB\n",
  529. (unsigned)(totalSamplesSize>>20), (COVER_MAX_SAMPLES_SIZE >> 20));
  530. return ERROR(srcSize_wrong);
  531. }
  532. /* Check if there are at least 5 training samples */
  533. if (nbTrainSamples < 5) {
  534. DISPLAYLEVEL(1, "Total number of training samples is %u and is invalid.", nbTrainSamples);
  535. return ERROR(srcSize_wrong);
  536. }
  537. /* Check if there's testing sample */
  538. if (nbTestSamples < 1) {
  539. DISPLAYLEVEL(1, "Total number of testing samples is %u and is invalid.", nbTestSamples);
  540. return ERROR(srcSize_wrong);
  541. }
  542. /* Zero the context */
  543. memset(ctx, 0, sizeof(*ctx));
  544. DISPLAYLEVEL(2, "Training on %u samples of total size %u\n", nbTrainSamples,
  545. (unsigned)trainingSamplesSize);
  546. DISPLAYLEVEL(2, "Testing on %u samples of total size %u\n", nbTestSamples,
  547. (unsigned)testSamplesSize);
  548. ctx->samples = samples;
  549. ctx->samplesSizes = samplesSizes;
  550. ctx->nbSamples = nbSamples;
  551. ctx->nbTrainSamples = nbTrainSamples;
  552. ctx->nbTestSamples = nbTestSamples;
  553. /* Partial suffix array */
  554. ctx->suffixSize = trainingSamplesSize - MAX(d, sizeof(U64)) + 1;
  555. ctx->suffix = (U32 *)malloc(ctx->suffixSize * sizeof(U32));
  556. /* Maps index to the dmerID */
  557. ctx->dmerAt = (U32 *)malloc(ctx->suffixSize * sizeof(U32));
  558. /* The offsets of each file */
  559. ctx->offsets = (size_t *)malloc((nbSamples + 1) * sizeof(size_t));
  560. if (!ctx->suffix || !ctx->dmerAt || !ctx->offsets) {
  561. DISPLAYLEVEL(1, "Failed to allocate scratch buffers\n");
  562. COVER_ctx_destroy(ctx);
  563. return ERROR(memory_allocation);
  564. }
  565. ctx->freqs = NULL;
  566. ctx->d = d;
  567. /* Fill offsets from the samplesSizes */
  568. {
  569. U32 i;
  570. ctx->offsets[0] = 0;
  571. for (i = 1; i <= nbSamples; ++i) {
  572. ctx->offsets[i] = ctx->offsets[i - 1] + samplesSizes[i - 1];
  573. }
  574. }
  575. DISPLAYLEVEL(2, "Constructing partial suffix array\n");
  576. {
  577. /* suffix is a partial suffix array.
  578. * It only sorts suffixes by their first parameters.d bytes.
  579. * The sort is stable, so each dmer group is sorted by position in input.
  580. */
  581. U32 i;
  582. for (i = 0; i < ctx->suffixSize; ++i) {
  583. ctx->suffix[i] = i;
  584. }
  585. /* qsort doesn't take an opaque pointer, so pass as a global.
  586. * On OpenBSD qsort() is not guaranteed to be stable, their mergesort() is.
  587. */
  588. g_coverCtx = ctx;
  589. #if defined(__OpenBSD__)
  590. mergesort(ctx->suffix, ctx->suffixSize, sizeof(U32),
  591. (ctx->d <= 8 ? &COVER_strict_cmp8 : &COVER_strict_cmp));
  592. #else
  593. qsort(ctx->suffix, ctx->suffixSize, sizeof(U32),
  594. (ctx->d <= 8 ? &COVER_strict_cmp8 : &COVER_strict_cmp));
  595. #endif
  596. }
  597. DISPLAYLEVEL(2, "Computing frequencies\n");
  598. /* For each dmer group (group of positions with the same first d bytes):
  599. * 1. For each position we set dmerAt[position] = dmerID. The dmerID is
  600. * (groupBeginPtr - suffix). This allows us to go from position to
  601. * dmerID so we can look up values in freq.
  602. * 2. We calculate how many samples the dmer occurs in and save it in
  603. * freqs[dmerId].
  604. */
  605. COVER_groupBy(ctx->suffix, ctx->suffixSize, sizeof(U32), ctx,
  606. (ctx->d <= 8 ? &COVER_cmp8 : &COVER_cmp), &COVER_group);
  607. ctx->freqs = ctx->suffix;
  608. ctx->suffix = NULL;
  609. return 0;
  610. }
  611. void COVER_warnOnSmallCorpus(size_t maxDictSize, size_t nbDmers, int displayLevel)
  612. {
  613. const double ratio = (double)nbDmers / (double)maxDictSize;
  614. if (ratio >= 10) {
  615. return;
  616. }
  617. LOCALDISPLAYLEVEL(displayLevel, 1,
  618. "WARNING: The maximum dictionary size %u is too large "
  619. "compared to the source size %u! "
  620. "size(source)/size(dictionary) = %f, but it should be >= "
  621. "10! This may lead to a subpar dictionary! We recommend "
  622. "training on sources at least 10x, and preferably 100x "
  623. "the size of the dictionary! \n", (U32)maxDictSize,
  624. (U32)nbDmers, ratio);
  625. }
  626. COVER_epoch_info_t COVER_computeEpochs(U32 maxDictSize,
  627. U32 nbDmers, U32 k, U32 passes)
  628. {
  629. const U32 minEpochSize = k * 10;
  630. COVER_epoch_info_t epochs;
  631. epochs.num = MAX(1, maxDictSize / k / passes);
  632. epochs.size = nbDmers / epochs.num;
  633. if (epochs.size >= minEpochSize) {
  634. assert(epochs.size * epochs.num <= nbDmers);
  635. return epochs;
  636. }
  637. epochs.size = MIN(minEpochSize, nbDmers);
  638. epochs.num = nbDmers / epochs.size;
  639. assert(epochs.size * epochs.num <= nbDmers);
  640. return epochs;
  641. }
  642. /**
  643. * Given the prepared context build the dictionary.
  644. */
  645. static size_t COVER_buildDictionary(const COVER_ctx_t *ctx, U32 *freqs,
  646. COVER_map_t *activeDmers, void *dictBuffer,
  647. size_t dictBufferCapacity,
  648. ZDICT_cover_params_t parameters) {
  649. BYTE *const dict = (BYTE *)dictBuffer;
  650. size_t tail = dictBufferCapacity;
  651. /* Divide the data into epochs. We will select one segment from each epoch. */
  652. const COVER_epoch_info_t epochs = COVER_computeEpochs(
  653. (U32)dictBufferCapacity, (U32)ctx->suffixSize, parameters.k, 4);
  654. const size_t maxZeroScoreRun = MAX(10, MIN(100, epochs.num >> 3));
  655. size_t zeroScoreRun = 0;
  656. size_t epoch;
  657. DISPLAYLEVEL(2, "Breaking content into %u epochs of size %u\n",
  658. (U32)epochs.num, (U32)epochs.size);
  659. /* Loop through the epochs until there are no more segments or the dictionary
  660. * is full.
  661. */
  662. for (epoch = 0; tail > 0; epoch = (epoch + 1) % epochs.num) {
  663. const U32 epochBegin = (U32)(epoch * epochs.size);
  664. const U32 epochEnd = epochBegin + epochs.size;
  665. size_t segmentSize;
  666. /* Select a segment */
  667. COVER_segment_t segment = COVER_selectSegment(
  668. ctx, freqs, activeDmers, epochBegin, epochEnd, parameters);
  669. /* If the segment covers no dmers, then we are out of content.
  670. * There may be new content in other epochs, for continue for some time.
  671. */
  672. if (segment.score == 0) {
  673. if (++zeroScoreRun >= maxZeroScoreRun) {
  674. break;
  675. }
  676. continue;
  677. }
  678. zeroScoreRun = 0;
  679. /* Trim the segment if necessary and if it is too small then we are done */
  680. segmentSize = MIN(segment.end - segment.begin + parameters.d - 1, tail);
  681. if (segmentSize < parameters.d) {
  682. break;
  683. }
  684. /* We fill the dictionary from the back to allow the best segments to be
  685. * referenced with the smallest offsets.
  686. */
  687. tail -= segmentSize;
  688. memcpy(dict + tail, ctx->samples + segment.begin, segmentSize);
  689. DISPLAYUPDATE(
  690. 2, "\r%u%% ",
  691. (unsigned)(((dictBufferCapacity - tail) * 100) / dictBufferCapacity));
  692. }
  693. DISPLAYLEVEL(2, "\r%79s\r", "");
  694. return tail;
  695. }
  696. ZDICTLIB_API size_t ZDICT_trainFromBuffer_cover(
  697. void *dictBuffer, size_t dictBufferCapacity,
  698. const void *samplesBuffer, const size_t *samplesSizes, unsigned nbSamples,
  699. ZDICT_cover_params_t parameters)
  700. {
  701. BYTE* const dict = (BYTE*)dictBuffer;
  702. COVER_ctx_t ctx;
  703. COVER_map_t activeDmers;
  704. parameters.splitPoint = 1.0;
  705. /* Initialize global data */
  706. g_displayLevel = (int)parameters.zParams.notificationLevel;
  707. /* Checks */
  708. if (!COVER_checkParameters(parameters, dictBufferCapacity)) {
  709. DISPLAYLEVEL(1, "Cover parameters incorrect\n");
  710. return ERROR(parameter_outOfBound);
  711. }
  712. if (nbSamples == 0) {
  713. DISPLAYLEVEL(1, "Cover must have at least one input file\n");
  714. return ERROR(srcSize_wrong);
  715. }
  716. if (dictBufferCapacity < ZDICT_DICTSIZE_MIN) {
  717. DISPLAYLEVEL(1, "dictBufferCapacity must be at least %u\n",
  718. ZDICT_DICTSIZE_MIN);
  719. return ERROR(dstSize_tooSmall);
  720. }
  721. /* Initialize context and activeDmers */
  722. {
  723. size_t const initVal = COVER_ctx_init(&ctx, samplesBuffer, samplesSizes, nbSamples,
  724. parameters.d, parameters.splitPoint);
  725. if (ZSTD_isError(initVal)) {
  726. return initVal;
  727. }
  728. }
  729. COVER_warnOnSmallCorpus(dictBufferCapacity, ctx.suffixSize, g_displayLevel);
  730. if (!COVER_map_init(&activeDmers, parameters.k - parameters.d + 1)) {
  731. DISPLAYLEVEL(1, "Failed to allocate dmer map: out of memory\n");
  732. COVER_ctx_destroy(&ctx);
  733. return ERROR(memory_allocation);
  734. }
  735. DISPLAYLEVEL(2, "Building dictionary\n");
  736. {
  737. const size_t tail =
  738. COVER_buildDictionary(&ctx, ctx.freqs, &activeDmers, dictBuffer,
  739. dictBufferCapacity, parameters);
  740. const size_t dictionarySize = ZDICT_finalizeDictionary(
  741. dict, dictBufferCapacity, dict + tail, dictBufferCapacity - tail,
  742. samplesBuffer, samplesSizes, nbSamples, parameters.zParams);
  743. if (!ZSTD_isError(dictionarySize)) {
  744. DISPLAYLEVEL(2, "Constructed dictionary of size %u\n",
  745. (unsigned)dictionarySize);
  746. }
  747. COVER_ctx_destroy(&ctx);
  748. COVER_map_destroy(&activeDmers);
  749. return dictionarySize;
  750. }
  751. }
  752. size_t COVER_checkTotalCompressedSize(const ZDICT_cover_params_t parameters,
  753. const size_t *samplesSizes, const BYTE *samples,
  754. size_t *offsets,
  755. size_t nbTrainSamples, size_t nbSamples,
  756. BYTE *const dict, size_t dictBufferCapacity) {
  757. size_t totalCompressedSize = ERROR(GENERIC);
  758. /* Pointers */
  759. ZSTD_CCtx *cctx;
  760. ZSTD_CDict *cdict;
  761. void *dst;
  762. /* Local variables */
  763. size_t dstCapacity;
  764. size_t i;
  765. /* Allocate dst with enough space to compress the maximum sized sample */
  766. {
  767. size_t maxSampleSize = 0;
  768. i = parameters.splitPoint < 1.0 ? nbTrainSamples : 0;
  769. for (; i < nbSamples; ++i) {
  770. maxSampleSize = MAX(samplesSizes[i], maxSampleSize);
  771. }
  772. dstCapacity = ZSTD_compressBound(maxSampleSize);
  773. dst = malloc(dstCapacity);
  774. }
  775. /* Create the cctx and cdict */
  776. cctx = ZSTD_createCCtx();
  777. cdict = ZSTD_createCDict(dict, dictBufferCapacity,
  778. parameters.zParams.compressionLevel);
  779. if (!dst || !cctx || !cdict) {
  780. goto _compressCleanup;
  781. }
  782. /* Compress each sample and sum their sizes (or error) */
  783. totalCompressedSize = dictBufferCapacity;
  784. i = parameters.splitPoint < 1.0 ? nbTrainSamples : 0;
  785. for (; i < nbSamples; ++i) {
  786. const size_t size = ZSTD_compress_usingCDict(
  787. cctx, dst, dstCapacity, samples + offsets[i],
  788. samplesSizes[i], cdict);
  789. if (ZSTD_isError(size)) {
  790. totalCompressedSize = size;
  791. goto _compressCleanup;
  792. }
  793. totalCompressedSize += size;
  794. }
  795. _compressCleanup:
  796. ZSTD_freeCCtx(cctx);
  797. ZSTD_freeCDict(cdict);
  798. if (dst) {
  799. free(dst);
  800. }
  801. return totalCompressedSize;
  802. }
  803. /**
  804. * Initialize the `COVER_best_t`.
  805. */
  806. void COVER_best_init(COVER_best_t *best) {
  807. if (best==NULL) return; /* compatible with init on NULL */
  808. (void)ZSTD_pthread_mutex_init(&best->mutex, NULL);
  809. (void)ZSTD_pthread_cond_init(&best->cond, NULL);
  810. best->liveJobs = 0;
  811. best->dict = NULL;
  812. best->dictSize = 0;
  813. best->compressedSize = (size_t)-1;
  814. memset(&best->parameters, 0, sizeof(best->parameters));
  815. }
  816. /**
  817. * Wait until liveJobs == 0.
  818. */
  819. void COVER_best_wait(COVER_best_t *best) {
  820. if (!best) {
  821. return;
  822. }
  823. ZSTD_pthread_mutex_lock(&best->mutex);
  824. while (best->liveJobs != 0) {
  825. ZSTD_pthread_cond_wait(&best->cond, &best->mutex);
  826. }
  827. ZSTD_pthread_mutex_unlock(&best->mutex);
  828. }
  829. /**
  830. * Call COVER_best_wait() and then destroy the COVER_best_t.
  831. */
  832. void COVER_best_destroy(COVER_best_t *best) {
  833. if (!best) {
  834. return;
  835. }
  836. COVER_best_wait(best);
  837. if (best->dict) {
  838. free(best->dict);
  839. }
  840. ZSTD_pthread_mutex_destroy(&best->mutex);
  841. ZSTD_pthread_cond_destroy(&best->cond);
  842. }
  843. /**
  844. * Called when a thread is about to be launched.
  845. * Increments liveJobs.
  846. */
  847. void COVER_best_start(COVER_best_t *best) {
  848. if (!best) {
  849. return;
  850. }
  851. ZSTD_pthread_mutex_lock(&best->mutex);
  852. ++best->liveJobs;
  853. ZSTD_pthread_mutex_unlock(&best->mutex);
  854. }
  855. /**
  856. * Called when a thread finishes executing, both on error or success.
  857. * Decrements liveJobs and signals any waiting threads if liveJobs == 0.
  858. * If this dictionary is the best so far save it and its parameters.
  859. */
  860. void COVER_best_finish(COVER_best_t *best, ZDICT_cover_params_t parameters,
  861. COVER_dictSelection_t selection) {
  862. void* dict = selection.dictContent;
  863. size_t compressedSize = selection.totalCompressedSize;
  864. size_t dictSize = selection.dictSize;
  865. if (!best) {
  866. return;
  867. }
  868. {
  869. size_t liveJobs;
  870. ZSTD_pthread_mutex_lock(&best->mutex);
  871. --best->liveJobs;
  872. liveJobs = best->liveJobs;
  873. /* If the new dictionary is better */
  874. if (compressedSize < best->compressedSize) {
  875. /* Allocate space if necessary */
  876. if (!best->dict || best->dictSize < dictSize) {
  877. if (best->dict) {
  878. free(best->dict);
  879. }
  880. best->dict = malloc(dictSize);
  881. if (!best->dict) {
  882. best->compressedSize = ERROR(GENERIC);
  883. best->dictSize = 0;
  884. ZSTD_pthread_cond_signal(&best->cond);
  885. ZSTD_pthread_mutex_unlock(&best->mutex);
  886. return;
  887. }
  888. }
  889. /* Save the dictionary, parameters, and size */
  890. if (dict) {
  891. memcpy(best->dict, dict, dictSize);
  892. best->dictSize = dictSize;
  893. best->parameters = parameters;
  894. best->compressedSize = compressedSize;
  895. }
  896. }
  897. if (liveJobs == 0) {
  898. ZSTD_pthread_cond_broadcast(&best->cond);
  899. }
  900. ZSTD_pthread_mutex_unlock(&best->mutex);
  901. }
  902. }
  903. static COVER_dictSelection_t setDictSelection(BYTE* buf, size_t s, size_t csz)
  904. {
  905. COVER_dictSelection_t ds;
  906. ds.dictContent = buf;
  907. ds.dictSize = s;
  908. ds.totalCompressedSize = csz;
  909. return ds;
  910. }
  911. COVER_dictSelection_t COVER_dictSelectionError(size_t error) {
  912. return setDictSelection(NULL, 0, error);
  913. }
  914. unsigned COVER_dictSelectionIsError(COVER_dictSelection_t selection) {
  915. return (ZSTD_isError(selection.totalCompressedSize) || !selection.dictContent);
  916. }
  917. void COVER_dictSelectionFree(COVER_dictSelection_t selection){
  918. free(selection.dictContent);
  919. }
  920. COVER_dictSelection_t COVER_selectDict(BYTE* customDictContent, size_t dictBufferCapacity,
  921. size_t dictContentSize, const BYTE* samplesBuffer, const size_t* samplesSizes, unsigned nbFinalizeSamples,
  922. size_t nbCheckSamples, size_t nbSamples, ZDICT_cover_params_t params, size_t* offsets, size_t totalCompressedSize) {
  923. size_t largestDict = 0;
  924. size_t largestCompressed = 0;
  925. BYTE* customDictContentEnd = customDictContent + dictContentSize;
  926. BYTE * largestDictbuffer = (BYTE *)malloc(dictBufferCapacity);
  927. BYTE * candidateDictBuffer = (BYTE *)malloc(dictBufferCapacity);
  928. double regressionTolerance = ((double)params.shrinkDictMaxRegression / 100.0) + 1.00;
  929. if (!largestDictbuffer || !candidateDictBuffer) {
  930. free(largestDictbuffer);
  931. free(candidateDictBuffer);
  932. return COVER_dictSelectionError(dictContentSize);
  933. }
  934. /* Initial dictionary size and compressed size */
  935. memcpy(largestDictbuffer, customDictContent, dictContentSize);
  936. dictContentSize = ZDICT_finalizeDictionary(
  937. largestDictbuffer, dictBufferCapacity, customDictContent, dictContentSize,
  938. samplesBuffer, samplesSizes, nbFinalizeSamples, params.zParams);
  939. if (ZDICT_isError(dictContentSize)) {
  940. free(largestDictbuffer);
  941. free(candidateDictBuffer);
  942. return COVER_dictSelectionError(dictContentSize);
  943. }
  944. totalCompressedSize = COVER_checkTotalCompressedSize(params, samplesSizes,
  945. samplesBuffer, offsets,
  946. nbCheckSamples, nbSamples,
  947. largestDictbuffer, dictContentSize);
  948. if (ZSTD_isError(totalCompressedSize)) {
  949. free(largestDictbuffer);
  950. free(candidateDictBuffer);
  951. return COVER_dictSelectionError(totalCompressedSize);
  952. }
  953. if (params.shrinkDict == 0) {
  954. free(candidateDictBuffer);
  955. return setDictSelection(largestDictbuffer, dictContentSize, totalCompressedSize);
  956. }
  957. largestDict = dictContentSize;
  958. largestCompressed = totalCompressedSize;
  959. dictContentSize = ZDICT_DICTSIZE_MIN;
  960. /* Largest dict is initially at least ZDICT_DICTSIZE_MIN */
  961. while (dictContentSize < largestDict) {
  962. memcpy(candidateDictBuffer, largestDictbuffer, largestDict);
  963. dictContentSize = ZDICT_finalizeDictionary(
  964. candidateDictBuffer, dictBufferCapacity, customDictContentEnd - dictContentSize, dictContentSize,
  965. samplesBuffer, samplesSizes, nbFinalizeSamples, params.zParams);
  966. if (ZDICT_isError(dictContentSize)) {
  967. free(largestDictbuffer);
  968. free(candidateDictBuffer);
  969. return COVER_dictSelectionError(dictContentSize);
  970. }
  971. totalCompressedSize = COVER_checkTotalCompressedSize(params, samplesSizes,
  972. samplesBuffer, offsets,
  973. nbCheckSamples, nbSamples,
  974. candidateDictBuffer, dictContentSize);
  975. if (ZSTD_isError(totalCompressedSize)) {
  976. free(largestDictbuffer);
  977. free(candidateDictBuffer);
  978. return COVER_dictSelectionError(totalCompressedSize);
  979. }
  980. if ((double)totalCompressedSize <= (double)largestCompressed * regressionTolerance) {
  981. free(largestDictbuffer);
  982. return setDictSelection( candidateDictBuffer, dictContentSize, totalCompressedSize );
  983. }
  984. dictContentSize *= 2;
  985. }
  986. dictContentSize = largestDict;
  987. totalCompressedSize = largestCompressed;
  988. free(candidateDictBuffer);
  989. return setDictSelection( largestDictbuffer, dictContentSize, totalCompressedSize );
  990. }
  991. /**
  992. * Parameters for COVER_tryParameters().
  993. */
  994. typedef struct COVER_tryParameters_data_s {
  995. const COVER_ctx_t *ctx;
  996. COVER_best_t *best;
  997. size_t dictBufferCapacity;
  998. ZDICT_cover_params_t parameters;
  999. } COVER_tryParameters_data_t;
  1000. /**
  1001. * Tries a set of parameters and updates the COVER_best_t with the results.
  1002. * This function is thread safe if zstd is compiled with multithreaded support.
  1003. * It takes its parameters as an *OWNING* opaque pointer to support threading.
  1004. */
  1005. static void COVER_tryParameters(void *opaque)
  1006. {
  1007. /* Save parameters as local variables */
  1008. COVER_tryParameters_data_t *const data = (COVER_tryParameters_data_t*)opaque;
  1009. const COVER_ctx_t *const ctx = data->ctx;
  1010. const ZDICT_cover_params_t parameters = data->parameters;
  1011. size_t dictBufferCapacity = data->dictBufferCapacity;
  1012. size_t totalCompressedSize = ERROR(GENERIC);
  1013. /* Allocate space for hash table, dict, and freqs */
  1014. COVER_map_t activeDmers;
  1015. BYTE* const dict = (BYTE*)malloc(dictBufferCapacity);
  1016. COVER_dictSelection_t selection = COVER_dictSelectionError(ERROR(GENERIC));
  1017. U32* const freqs = (U32*)malloc(ctx->suffixSize * sizeof(U32));
  1018. if (!COVER_map_init(&activeDmers, parameters.k - parameters.d + 1)) {
  1019. DISPLAYLEVEL(1, "Failed to allocate dmer map: out of memory\n");
  1020. goto _cleanup;
  1021. }
  1022. if (!dict || !freqs) {
  1023. DISPLAYLEVEL(1, "Failed to allocate buffers: out of memory\n");
  1024. goto _cleanup;
  1025. }
  1026. /* Copy the frequencies because we need to modify them */
  1027. memcpy(freqs, ctx->freqs, ctx->suffixSize * sizeof(U32));
  1028. /* Build the dictionary */
  1029. {
  1030. const size_t tail = COVER_buildDictionary(ctx, freqs, &activeDmers, dict,
  1031. dictBufferCapacity, parameters);
  1032. selection = COVER_selectDict(dict + tail, dictBufferCapacity, dictBufferCapacity - tail,
  1033. ctx->samples, ctx->samplesSizes, (unsigned)ctx->nbTrainSamples, ctx->nbTrainSamples, ctx->nbSamples, parameters, ctx->offsets,
  1034. totalCompressedSize);
  1035. if (COVER_dictSelectionIsError(selection)) {
  1036. DISPLAYLEVEL(1, "Failed to select dictionary\n");
  1037. goto _cleanup;
  1038. }
  1039. }
  1040. _cleanup:
  1041. free(dict);
  1042. COVER_best_finish(data->best, parameters, selection);
  1043. free(data);
  1044. COVER_map_destroy(&activeDmers);
  1045. COVER_dictSelectionFree(selection);
  1046. free(freqs);
  1047. }
  1048. ZDICTLIB_API size_t ZDICT_optimizeTrainFromBuffer_cover(
  1049. void* dictBuffer, size_t dictBufferCapacity, const void* samplesBuffer,
  1050. const size_t* samplesSizes, unsigned nbSamples,
  1051. ZDICT_cover_params_t* parameters)
  1052. {
  1053. /* constants */
  1054. const unsigned nbThreads = parameters->nbThreads;
  1055. const double splitPoint =
  1056. parameters->splitPoint <= 0.0 ? COVER_DEFAULT_SPLITPOINT : parameters->splitPoint;
  1057. const unsigned kMinD = parameters->d == 0 ? 6 : parameters->d;
  1058. const unsigned kMaxD = parameters->d == 0 ? 8 : parameters->d;
  1059. const unsigned kMinK = parameters->k == 0 ? 50 : parameters->k;
  1060. const unsigned kMaxK = parameters->k == 0 ? 2000 : parameters->k;
  1061. const unsigned kSteps = parameters->steps == 0 ? 40 : parameters->steps;
  1062. const unsigned kStepSize = MAX((kMaxK - kMinK) / kSteps, 1);
  1063. const unsigned kIterations =
  1064. (1 + (kMaxD - kMinD) / 2) * (1 + (kMaxK - kMinK) / kStepSize);
  1065. const unsigned shrinkDict = 0;
  1066. /* Local variables */
  1067. const int displayLevel = parameters->zParams.notificationLevel;
  1068. unsigned iteration = 1;
  1069. unsigned d;
  1070. unsigned k;
  1071. COVER_best_t best;
  1072. POOL_ctx *pool = NULL;
  1073. int warned = 0;
  1074. /* Checks */
  1075. if (splitPoint <= 0 || splitPoint > 1) {
  1076. LOCALDISPLAYLEVEL(displayLevel, 1, "Incorrect parameters\n");
  1077. return ERROR(parameter_outOfBound);
  1078. }
  1079. if (kMinK < kMaxD || kMaxK < kMinK) {
  1080. LOCALDISPLAYLEVEL(displayLevel, 1, "Incorrect parameters\n");
  1081. return ERROR(parameter_outOfBound);
  1082. }
  1083. if (nbSamples == 0) {
  1084. DISPLAYLEVEL(1, "Cover must have at least one input file\n");
  1085. return ERROR(srcSize_wrong);
  1086. }
  1087. if (dictBufferCapacity < ZDICT_DICTSIZE_MIN) {
  1088. DISPLAYLEVEL(1, "dictBufferCapacity must be at least %u\n",
  1089. ZDICT_DICTSIZE_MIN);
  1090. return ERROR(dstSize_tooSmall);
  1091. }
  1092. if (nbThreads > 1) {
  1093. pool = POOL_create(nbThreads, 1);
  1094. if (!pool) {
  1095. return ERROR(memory_allocation);
  1096. }
  1097. }
  1098. /* Initialization */
  1099. COVER_best_init(&best);
  1100. /* Turn down global display level to clean up display at level 2 and below */
  1101. g_displayLevel = displayLevel == 0 ? 0 : displayLevel - 1;
  1102. /* Loop through d first because each new value needs a new context */
  1103. LOCALDISPLAYLEVEL(displayLevel, 2, "Trying %u different sets of parameters\n",
  1104. kIterations);
  1105. for (d = kMinD; d <= kMaxD; d += 2) {
  1106. /* Initialize the context for this value of d */
  1107. COVER_ctx_t ctx;
  1108. LOCALDISPLAYLEVEL(displayLevel, 3, "d=%u\n", d);
  1109. {
  1110. const size_t initVal = COVER_ctx_init(&ctx, samplesBuffer, samplesSizes, nbSamples, d, splitPoint);
  1111. if (ZSTD_isError(initVal)) {
  1112. LOCALDISPLAYLEVEL(displayLevel, 1, "Failed to initialize context\n");
  1113. COVER_best_destroy(&best);
  1114. POOL_free(pool);
  1115. return initVal;
  1116. }
  1117. }
  1118. if (!warned) {
  1119. COVER_warnOnSmallCorpus(dictBufferCapacity, ctx.suffixSize, displayLevel);
  1120. warned = 1;
  1121. }
  1122. /* Loop through k reusing the same context */
  1123. for (k = kMinK; k <= kMaxK; k += kStepSize) {
  1124. /* Prepare the arguments */
  1125. COVER_tryParameters_data_t *data = (COVER_tryParameters_data_t *)malloc(
  1126. sizeof(COVER_tryParameters_data_t));
  1127. LOCALDISPLAYLEVEL(displayLevel, 3, "k=%u\n", k);
  1128. if (!data) {
  1129. LOCALDISPLAYLEVEL(displayLevel, 1, "Failed to allocate parameters\n");
  1130. COVER_best_destroy(&best);
  1131. COVER_ctx_destroy(&ctx);
  1132. POOL_free(pool);
  1133. return ERROR(memory_allocation);
  1134. }
  1135. data->ctx = &ctx;
  1136. data->best = &best;
  1137. data->dictBufferCapacity = dictBufferCapacity;
  1138. data->parameters = *parameters;
  1139. data->parameters.k = k;
  1140. data->parameters.d = d;
  1141. data->parameters.splitPoint = splitPoint;
  1142. data->parameters.steps = kSteps;
  1143. data->parameters.shrinkDict = shrinkDict;
  1144. data->parameters.zParams.notificationLevel = g_displayLevel;
  1145. /* Check the parameters */
  1146. if (!COVER_checkParameters(data->parameters, dictBufferCapacity)) {
  1147. DISPLAYLEVEL(1, "Cover parameters incorrect\n");
  1148. free(data);
  1149. continue;
  1150. }
  1151. /* Call the function and pass ownership of data to it */
  1152. COVER_best_start(&best);
  1153. if (pool) {
  1154. POOL_add(pool, &COVER_tryParameters, data);
  1155. } else {
  1156. COVER_tryParameters(data);
  1157. }
  1158. /* Print status */
  1159. LOCALDISPLAYUPDATE(displayLevel, 2, "\r%u%% ",
  1160. (unsigned)((iteration * 100) / kIterations));
  1161. ++iteration;
  1162. }
  1163. COVER_best_wait(&best);
  1164. COVER_ctx_destroy(&ctx);
  1165. }
  1166. LOCALDISPLAYLEVEL(displayLevel, 2, "\r%79s\r", "");
  1167. /* Fill the output buffer and parameters with output of the best parameters */
  1168. {
  1169. const size_t dictSize = best.dictSize;
  1170. if (ZSTD_isError(best.compressedSize)) {
  1171. const size_t compressedSize = best.compressedSize;
  1172. COVER_best_destroy(&best);
  1173. POOL_free(pool);
  1174. return compressedSize;
  1175. }
  1176. *parameters = best.parameters;
  1177. memcpy(dictBuffer, best.dict, dictSize);
  1178. COVER_best_destroy(&best);
  1179. POOL_free(pool);
  1180. return dictSize;
  1181. }
  1182. }